diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..d92eacf --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,9 @@ +# Windows: the C runtime is linked into the executable, so it starts on a Windows +# without the Visual C++ Redistributable (VCRUNTIME140.dll). +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] + +# WebAssembly in a browser: random numbers from crypto.getRandomValues (getrandom 0.3 +# needs this as well as its `wasm_js` feature, enabled by apps/web). +[target.wasm32-unknown-unknown] +rustflags = ["--cfg", "getrandom_backend=\"wasm_js\""] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e8497e4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,76 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - name: System libraries + run: sudo apt-get update && sudo apt-get install -y pkg-config libasound2-dev libxkbcommon-dev libwayland-dev + - run: cargo fmt --all --check + - run: cargo clippy --workspace --all-targets --locked -- -D warnings + - run: cargo test --workspace --locked + + windows-build: + runs-on: windows-latest + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - run: cargo build --release --locked -p chesspenguin + # Self-update: replacing the running executable (the Windows rename scheme). + - run: "cargo test --release --locked -p chesspenguin update::" + # The C runtime is inside the executable (.cargo/config.toml): no VCRUNTIME140.dll. + - name: No Visual C++ runtime needed + shell: pwsh + run: | + $bytes = [IO.File]::ReadAllBytes("target/release/chesspenguin.exe") + $text = [Text.Encoding]::ASCII.GetString($bytes) + if ($text -match "(?i)vcruntime140\.dll") { throw "chesspenguin.exe imports VCRUNTIME140.dll" } + # The window starts on a machine without a graphics card (the runner): the log says + # which graphics mode it took. Informational for now. + - name: Start the window + shell: pwsh + continue-on-error: true + run: | + $env:CP_SCREENSHOT = "$PWD/start.png" + $env:CP_SCREENSHOT_DELAY = "5" + $p = Start-Process target/release/chesspenguin.exe -PassThru + $p | Wait-Process -Timeout 90 -ErrorAction SilentlyContinue + Get-Process chesspenguin -ErrorAction SilentlyContinue | Stop-Process -Force + $dir = "$env:APPDATA/vrubelroman/ChessPenguin/config" + # Annotations: readable on the run page without signing in. + $lines = @("exit code: $($p.ExitCode)") + if (Test-Path "$dir/graphics") { $lines += "graphics: " + (Get-Content "$dir/graphics") } + if (Test-Path "$dir/chesspenguin.log") { $lines += Get-Content "$dir/chesspenguin.log" | Select-Object -First 40 } + foreach ($l in $lines) { Write-Output "::warning title=Windows start::$($l -replace '%','%25')" } + if (-not (Test-Path start.png)) { throw "no screenshot: the window did not start" } + - uses: actions/upload-artifact@v7 + if: always() + with: + name: windows-start + path: start.png + if-no-files-found: ignore + + # Apple Silicon: the build and the app bundle (decision 15). + macos-build: + runs-on: macos-15 + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - run: cargo build --release --locked -p chesspenguin + - run: VERSION=0.0.0 packaging/macos/build-app.sh dist + - run: "cargo test --locked -p chesspenguin update::" diff --git a/.github/workflows/release-notes.yml b/.github/workflows/release-notes.yml new file mode 100644 index 0000000..748e19a --- /dev/null +++ b/.github/workflows/release-notes.yml @@ -0,0 +1,52 @@ +name: Release notes + +# Corrections to the changelog must also reach an already published release, +# without moving its tag or rebuilding the signed packages. +on: + push: + branches: [main] + paths: [CHANGELOG.md] + workflow_dispatch: + +permissions: + contents: write + +jobs: + update: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - name: Update the current release notes if it has been published + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + python3 - <<'PY' + import json, os, pathlib, tomllib, urllib.error, urllib.request + + version = tomllib.loads(pathlib.Path('Cargo.toml').read_text())['workspace']['package']['version'] + heading = f'## [{version}]' + lines = pathlib.Path('CHANGELOG.md').read_text().splitlines() + start = next(i for i, line in enumerate(lines) if line.startswith(heading)) + 1 + end = next((i for i in range(start, len(lines)) if lines[i].startswith('## [')), len(lines)) + body = '\n'.join(lines[start:end]).strip() + assert body, 'Release notes must not be empty' + api = f'https://api.github.com/repos/{os.environ["GH_REPO"]}/releases' + headers = {'Authorization': f'Bearer {os.environ["GH_TOKEN"]}', + 'Accept': 'application/vnd.github+json', 'User-Agent': 'ChessPenguin-release-notes'} + try: + with urllib.request.urlopen(urllib.request.Request(f'{api}/tags/v{version}', headers=headers), timeout=30) as response: + release = json.load(response) + except urllib.error.HTTPError as error: + if error.code != 404: + raise + print(f'v{version} is not published yet; the release workflow will supply its notes.') + else: + data = json.dumps({'body': body}).encode() + request = urllib.request.Request(f'{api}/{release["id"]}', data=data, + headers={**headers, 'Content-Type': 'application/json'}, method='PATCH') + with urllib.request.urlopen(request, timeout=30) as response: + updated = json.load(response) + assert updated['body'].strip() == body + print(f'Updated notes for v{version}: {updated["html_url"]}') + PY diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..9864cfa --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,207 @@ +# Builds release packages on a version tag (v0.1.0, v0.2.0-beta.1, ...) and publishes a GitHub Release. +# Manual runs (workflow_dispatch) build everything and keep it as workflow artifacts only. +name: Release + +on: + push: + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: write + +env: + CARGO_TERM_COLOR: always + +jobs: + version: + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.v.outputs.version }} + steps: + - uses: actions/checkout@v7 + - id: v + name: Read and check the version + run: | + version=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2) + if [[ "${GITHUB_REF_TYPE}" == "tag" && "${GITHUB_REF_NAME}" != "v${version}" ]]; then + echo "::error::Tag ${GITHUB_REF_NAME} does not match Cargo.toml version ${version}" + exit 1 + fi + echo "version=${version}" >> "${GITHUB_OUTPUT}" + + linux: + needs: version + # Oldest supported runner: binaries and the AppImage then run on older glibc too. + runs-on: ubuntu-22.04 + env: + VERSION: ${{ needs.version.outputs.version }} + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: System libraries + run: sudo apt-get update && sudo apt-get install -y pkg-config libasound2-dev libxkbcommon-dev libwayland-dev libfuse2 + - run: cargo build --release --locked -p chesspenguin + # Stockfish is not bundled here: the program downloads it on request (decision 14). + - name: Tarball + run: | + name="ChessPenguin-${VERSION}-linux-x86_64" + mkdir -p "dist/${name}" + cp target/release/chesspenguin LICENSE README.md THIRD_PARTY_NOTICES.md "dist/${name}/" + cp -r packaging/icons packaging/*.desktop examples "dist/${name}/" + tar -C dist -czf "dist/${name}.tar.gz" "${name}" + rm -rf "dist/${name}" + - name: deb, rpm and Arch Linux packages + run: | + curl -fsSL -o /tmp/nfpm.deb https://github.com/goreleaser/nfpm/releases/download/v2.48.0/nfpm_2.48.0_amd64.deb + sudo dpkg -i /tmp/nfpm.deb + nfpm package -f packaging/nfpm.yaml -p deb -t dist/ + nfpm package -f packaging/nfpm.yaml -p rpm -t dist/ + nfpm package -f packaging/nfpm.yaml -p archlinux -t dist/ + - name: AppImage + run: packaging/build-appimage.sh dist + - uses: actions/upload-artifact@v7 + with: + name: linux + path: dist/* + + flatpak: + needs: version + runs-on: ubuntu-24.04 + container: + image: ghcr.io/flathub-infra/flatpak-github-actions:freedesktop-25.08 + options: --privileged + steps: + - uses: actions/checkout@v7 + - uses: flatpak/flatpak-github-actions/flatpak-builder@v6 + with: + bundle: ChessPenguin-${{ needs.version.outputs.version }}-x86_64.flatpak + manifest-path: packaging/flatpak/io.github.vrubelroman.chessPenguin.yml + cache-key: flatpak-builder-${{ github.sha }} + upload-artifact: false + - uses: actions/upload-artifact@v7 + with: + name: flatpak + path: ChessPenguin-*.flatpak + + windows: + needs: version + runs-on: windows-latest + env: + VERSION: ${{ needs.version.outputs.version }} + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - run: cargo build --release --locked -p chesspenguin + - name: Zip + shell: pwsh + run: | + $name = "ChessPenguin-$env:VERSION-windows-x86_64" + New-Item -ItemType Directory -Force -Path "dist/$name" | Out-Null + Copy-Item target/release/chesspenguin.exe "dist/$name/ChessPenguin.exe" + Copy-Item LICENSE, README.md, THIRD_PARTY_NOTICES.md "dist/$name/" + Copy-Item -Recurse examples "dist/$name/" + Compress-Archive -Path "dist/$name" -DestinationPath "dist/$name.zip" + Remove-Item -Recurse "dist/$name" + - uses: actions/upload-artifact@v7 + with: + name: windows + path: dist/* + + macos: + needs: version + # Apple Silicon (arm64). Not signed by Apple yet: the first start goes through + # "Open" in the context menu (decision 15). + runs-on: macos-15 + env: + VERSION: ${{ needs.version.outputs.version }} + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - run: cargo build --release --locked -p chesspenguin + - name: App bundle and disk image + run: packaging/macos/build-app.sh dist + - uses: actions/upload-artifact@v7 + with: + name: macos + path: dist/* + + android: + needs: version + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-linux-android,x86_64-linux-android + - uses: Swatinem/rust-cache@v2 + - name: Android NDK and platform, cargo-ndk + run: | + yes | "${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager" --install "ndk;30.0.16248370" "platforms;android-37.0" > /dev/null + cargo install cargo-ndk --version 4.1.2 --locked + # Two APKs: Stockfish built in, and Stockfish downloaded in the app + # (androidApp/scripts/release.sh, which also builds Stockfish from its source). + # The signing key comes from the repository secrets. + - name: Signed APKs + env: + KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + CP_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + CP_KEY_ALIAS: chesspenguin + CP_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: | + if [[ -z "${KEYSTORE_BASE64}" ]]; then + echo "::error::The Android signing key is not in the repository secrets" + exit 1 + fi + export CP_KEYSTORE="${RUNNER_TEMP}/release.jks" + echo "${KEYSTORE_BASE64}" | base64 -d > "${CP_KEYSTORE}" + export ANDROID_NDK_HOME="${ANDROID_HOME}/ndk/30.0.16248370" + androidApp/scripts/release.sh + rm -f "${CP_KEYSTORE}" + - uses: actions/upload-artifact@v7 + with: + name: android + 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: + needs: [version, linux, flatpak, windows, macos, android] + if: github.ref_type == 'tag' + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v8 + with: + path: dist + 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) + run: packaging/stockfish.sh source dist + - name: Checksums + run: cd dist && sha256sum * > SHA256SUMS.txt + # The release page says what is new: the site and the apps' "What's new" lead there. + - name: Release notes (this version's section of CHANGELOG.md) + run: | + v="${GITHUB_REF_NAME#v}" + awk -v h="## [$v]" 'index($0, h) == 1 { f = 1; next } f && /^## \[/ { exit } f' CHANGELOG.md > "${RUNNER_TEMP}/notes.md" + test -s "${RUNNER_TEMP}/notes.md" || echo "See CHANGELOG.md." > "${RUNNER_TEMP}/notes.md" + - uses: softprops/action-gh-release@v3 + with: + files: dist/* + body_path: ${{ runner.temp }}/notes.md + generate_release_notes: true + # v1.0.0-beta.1 and similar tags become pre-releases. + prerelease: ${{ contains(github.ref_name, '-') }} diff --git a/.github/workflows/rodent-iv.yml b/.github/workflows/rodent-iv.yml new file mode 100644 index 0000000..34c814a --- /dev/null +++ b/.github/workflows/rodent-iv.yml @@ -0,0 +1,123 @@ +# Builds Rodent IV (github.com/nescitus/rodent-iv, GPL-3.0) from the authors' sources at a +# pinned commit for Linux, Windows and macOS: its authors publish no builds for them +# (docs/decisions.md «Rodent IV»). ChessPenguin downloads the engine from this release on +# request, checked against the SHA-256 pinned in apps/desktop/src/rodent4_download.rs; the +# personalities and books come from the authors' repository at the same commit. +# +# Tag rodent-iv- to publish. The release is a pre-release that is never "latest": +# the app's update check and the website look for the latest release of ChessPenguin. +name: Rodent IV + +on: + push: + tags: ["rodent-iv-*"] + workflow_dispatch: + +permissions: + contents: write + +env: + # The authors' last commit (2021-04-29, Rodent IV 0.33). + COMMIT: e8d84c8c8c189a1cf4eb27c578fc573af3b916d2 + +jobs: + build: + strategy: + matrix: + include: + # An older glibc, so that the engine runs on the distributions ChessPenguin runs on. + - os: ubuntu-22.04 + name: rodent-iv-linux-x86_64 + - os: windows-latest + name: rodent-iv-windows-x86_64.exe + - os: macos-15 + name: rodent-iv-macos-arm64 + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + with: + path: cp + - name: Sources at the pinned commit, with our two fixes + shell: bash + # packaging/rodent-iv/home-dir.patch: on Linux the engine now and then took a + # wrong home folder and played without its personality and books; on macOS it + # had none, found no personality and did not offer the Personality option. + # packaging/rodent-iv/think-thread.patch: the search thread read its parameter + # after it was gone; clang builds (macOS) searched garbage out of the book. + run: | + git clone https://github.com/nescitus/rodent-iv.git src + git -C src checkout "$COMMIT" + git -C src apply ../cp/packaging/rodent-iv/home-dir.patch + git -C src apply ../cp/packaging/rodent-iv/think-thread.patch + - name: Windows compiler (MinGW-w64, linked statically) + if: runner.os == 'Windows' + uses: msys2/setup-msys2@v2 + with: + msystem: UCRT64 + install: mingw-w64-ucrt-x86_64-gcc + - name: Build (Linux, macOS) + if: runner.os != 'Windows' + shell: bash + run: | + cd src/sources + extra="" + if [ "$RUNNER_OS" = "Linux" ]; then extra="-static-libstdc++ -static-libgcc"; fi + c++ -O3 -w -pipe -DNDEBUG -fno-rtti -finline-functions -std=c++14 $extra src/*.cpp -o "../../${{ matrix.name }}" -lm + strip "../../${{ matrix.name }}" || true + - name: Build (Windows) + if: runner.os == 'Windows' + shell: msys2 {0} + run: | + cd src/sources + g++ -O3 -w -pipe -DNDEBUG -fno-rtti -finline-functions -std=c++14 -static src/*.cpp -o "../../${{ matrix.name }}" -lm + strip "../../${{ matrix.name }}" + - name: It answers UCI + shell: bash + run: printf 'uci\nquit\n' | "./${{ matrix.name }}" | grep -q "Rodent IV" + - name: It searches (a legal first move out of a book) + shell: bash + run: | + out=$( (printf 'uci\nsetoption name UseBook value false\nisready\nposition startpos\ngo depth 8\n'; sleep 10; printf 'quit\n') | "./${{ matrix.name }}" ) + best=$(printf '%s\n' "$out" | grep -o 'bestmove [a-h1-8]*' | tail -n1 | cut -d' ' -f2) + echo "bestmove: $best" + legal=" a2a3 a2a4 b2b3 b2b4 c2c3 c2c4 d2d3 d2d4 e2e3 e2e4 f2f3 f2f4 g2g3 g2g4 h2h3 h2h4 b1a3 b1c3 g1f3 g1h3 " + [[ -n "$best" && "$legal" == *" $best "* ]] + - name: It offers its personalities (its own folder, a space in it; started elsewhere) + shell: bash + # As ChessPenguin runs it: on macOS from ~/Library/Application Support/…. + run: | + home="$PWD/engine home" + mkdir -p "$home" && cp "./${{ matrix.name }}" "$home/" && cp -r src/personalities "$home/" + out=$(cd "$RUNNER_TEMP" && printf 'uci\nquit\n' | "$home/${{ matrix.name }}") + printf '%s\n' "$out" | grep '^option name Personality ' | grep -Eq ' var Tal( |$)' + - uses: actions/upload-artifact@v7 + with: + name: ${{ matrix.name }} + path: ${{ matrix.name }} + + publish: + needs: build + if: github.ref_type == 'tag' + runs-on: ubuntu-24.04 + steps: + - uses: actions/download-artifact@v8 + with: + path: dist + merge-multiple: true + - name: Checksums and the source offer + run: | + cd dist && sha256sum * > SHA256SUMS.txt + cat > "${RUNNER_TEMP}/notes.md" <` зелёные. Сломать �уще�твующий те�т нельз�; падающий до теб� те�т фик�ируешь и �ообщаешь, чужое молча не «чинишь». +- Поведенче�кие изменени� — � те�тами: ошибки данных, отмена, конкурентно�ть, roundtrip. UI проверенным объ�вл�ешь только по�ле реального запу�ка (dev-хуки `CP_*`, �нимок), не «на глаз» по коду. +- Замеры производительно�ти � методикой и оборудованием; цели не выдаёшь за результаты. + +Отчёт: изменённые файлы · команды проверки и их итог (�копированный вывод) · прин�тые решени� и почему · непроверенное · вопро�ы. diff --git a/.opencode/agents/orchestrator.md b/.opencode/agents/orchestrator.md new file mode 100644 index 0000000..c6635d2 --- /dev/null +++ b/.opencode/agents/orchestrator.md @@ -0,0 +1,17 @@ +--- +description: Ведёт разработку шахматного приложени�, координирует аналитика, дизайнера, разработчика и те�тировщика +mode: primary +color: "#5B8DEF" +--- + +Ты орке�тратор ChessPenguin — �ерьёзного локального шахматного приложени� (Rust + egui; релизы на Linux, Windows, macOS, Android). Общай�� по-ру��ки. До первого вывода прочитай: AGENTS.md (инварианты продукта), `docs/dev/tasks.md` (что в работе), `docs/decisions.md` (что решено; решени� пользовател� не переоткрываем), `docs/architecture.md` (у�трой�тво �и�темы). ТЗ и `docs/research/` — за и�ходной по�тановкой и и�торией. + +Тво� работа — доводить до проверенного результата, а не до активно�ти: + +1. Определи ближайший провер�емый результат и назови его пользователю до начала работы. +2. Делегируй незави�имые ча�ти агентам analyst, designer, developer, tester: каждой — отдельные файлы без пере�ечений, в задании — цель, изве�тные пути и факты, ожидаемый артефакт. �е дублируй их и��ледовани� �воими и не делай их работу за них. По�ле UI-реализации отдельно назначай дизайн-ревьюера, который не пи�ал �ту реализацию: об�зательны реальные �криншоты, �равнение � о�новными �кранами и проверка от�ут�тви� �качков между �о�то�ни�ми. +3. Интегрируй только проверенное: утверждение агента принимай как гипотезу, пока не увидел доказатель�тва (команда, её вывод, файл:�трока). Ключевое и �порное перепровер�й �ам. +4. Закрыва� задачу, обновл�й `docs/dev/tasks.md`, при �уще�твенных решени�х — `docs/decisions.md`; в отчёте различай: �делано / проверено / рекомендовано / ждёт ответа пользовател�. +5. Продуктовые решени� предлагай вариантами � рекомендацией и ценой каждого; �вою рекомендацию не выдавай за решение пользовател�. Объём без �огла�овани� не ра�шир�й. + +Е�ли ин�трументы текущей �е��ии не показывают профили команды, и�пользуй �убагентов общего назначени� � полным тек�том роли из `.opencode/agents/<роль>.md` и �кажи об �том пользователю. �ктивный �ерви� (OpenCode, Kimi Code) �амо�то�тельно не перезапу�кай. diff --git a/.opencode/agents/tester.md b/.opencode/agents/tester.md new file mode 100644 index 0000000..e9a909a --- /dev/null +++ b/.opencode/agents/tester.md @@ -0,0 +1,19 @@ +--- +description: �езави�имо провер�ет PGN, шахматную модель, UCI, Linux UI и регре��ии �охранно�ти данных +mode: subagent +color: "#E87575" +--- + +Ты инженер каче�тва ChessPenguin. Пиши по-ру��ки. Читай AGENTS.md, назначенное изменение и профильные dev-доки. Приоритет — реальные, во�производимые дефекты, а не чи�ло те�тов. �езави�имо�ть главна�: отчёты разработчика и орке�тратора — гипотезы, не доказатель�тва; в�ё ключевое во�производишь �ам, � нул�, по шагам. + +Предметные чек-ли�ты: + +- PGN и дерево: RAV не�кольких уровней, FEN и ход чёрных, комментарии у корн�/ходов/ветвей, NAG, не�тандартные теги, legacy-кодировки, у�ечённые данные, рокировки, en passant, превращени�, мат, пат, повтор позиции. Roundtrip �равнивай �емантиче�ки; отдельно провер�й, что неизменённый и�ходник уцелел побайтово. +- UCI: детерминированный fake engine, во�производ�щий задержки, у�таревший `info` по�ле `bestmove`, от�ут�твие `readyok`, му�орные �троки, MultiPV, мат и завершение проце��а. Реальный Stockfish — дополнительна� интеграци�, а не замена управл�емым �ценари�м гонок. +- UI и �ценарии: переход библиотека—парти�—библиотека, клавиатура и фоку�, предпро�мотр PV без изменени� документа, отмена операций, �к�порт, во��тановление по�ле аварии; Wayland/X11 и HiDPI в до�тупном окружении. + +Оформление дефекта — �трого: �ерьёзно�ть · окружение и вер�и� · шаги · ожидаемое и фактиче�кое поведение · файл/�трока · минимальный пример во�произведени�. �е во�произвёл — не репортишь: пишешь «не подтвердило�ь» � перечнем проверок. Производительно�ть: фик�ируешь оборудование, размер входа, методику и измерени�; цели не называешь результатами. + +Границы: production-код без задани� не и�правл�ешь; неподтверждённые бинарники не запу�каешь; пользователь�кие PGN и базы не измен�ешь — работаешь на копи�х; внешние те�товые библиотеки не публикуешь без вы��нени� у�ловий ра�про�транени�. + +Отчёт: проверено (чем и каким �ценарием) · дефекты (по формату) · не подтвердило�ь · непроверенное — �вным �пи�ком · оценка ри�ков о�татка. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..914434b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,47 @@ +# Chess database for Linux + +## Контек�т + +- И�ходное ТЗ: `техниче�кое задание.txt`. +- Пользователь�кие материалы: `designExample/`, `pgnFilesforExample/`, `engines/`. +- Рабочий �зык об�уждений и проектных заметок — ру��кий; идентификаторы кода — англий�кий. +- Текущий �тап: развитие выпу�каемого продукта (релиз 2.5.2). Задачи и б�клог — `docs/dev/tasks.md`. +- �рхитектура реализованной �и�темы: `docs/architecture.md`; архитектурное предложение �тапа и��ледовани� — `docs/research/architecture-proposal-2026-10-17.md`; и��ледовани�: `docs/research/`. +- Журнал решений: `docs/decisions.md`; подтверждённые пользователем решени� имеют приоритет над предложени�ми и��ледований. + +## Команда + +Орке�тратор ра�предел�ет незави�имые задачи между `analyst`, `designer`, `developer`, `tester`, �огла�ует результаты и об�уждает продуктовые решени� � пользователем. Делегирование разрешено. Дочерние агенты не �оздают дополнительные уровни команды без необходимо�ти. + +- �налитик поддерживает требовани�, реальные о�обенно�ти PGN и критерии приёмки. +- Дизайнер отвечает за �ценарии, компоновку, �о�то�ни�, клавиатуру и визуальную �и�тему. По�ле UI-реализации отдельный дизайн-ревьюер, не автор реализации, провер�ет её на реальных �нимках приложени�: �равнение � главным �краном и �краном партии, выравнивание, размеры и �о�то�ни�, от�ут�твие �качков при переходах и по�влении данных. Одного чтени� кода и те�тов дл� визуальной приёмки недо�таточно. +- Разработчик отвечает за Rust, архитектуру, хранение, PGN и UCI. +- Те�тировщик незави�имо провер�ет поведение и �ообщает конкретные во�производимые дефекты. + +Каждой параллельной задаче назначать �об�твенные файлы. �е перезапи�ывать работу другого агента. В отчёте указывать изменени�, проверки и нерешённые вопро�ы. + +### Механика в Kimi Code + +Канониче�кие профили ролей — файлы `.opencode/agents/*.md` (orchestrator, analyst, designer, developer, tester); �одержимое нейтрально к �реде и�полнени�. Kimi Code не реги�трирует �об�твенные типы �убагентов, и �убагент �тартует «холодным», по�тому роль передаёт�� в задании: ��ылка на файл профил� («прочитай и �ледуй ему») плю� цель, уже изве�тные пути и факты, назначенные файлы и ожидаемый результат. + +Тип �убагента выбирает�� по требуемым ин�трументам: `coder` — рол�м, которым нужно править файлы или запу�кать команды (developer, tester; analyst и designer при запи�и результатов в docs/); `plan` — read-only планирование и проектирование; `explore` — бы�трое read-only и��ледование без запи�и файлов. Орке�тратор — о�новна� �е��и�; его рабочие правила — в `.opencode/agents/orchestrator.md`. + +## Инварианты продукта + +- Локальное приложение дл� про�мотра, ввода и анализа шахматных партий, � PGN как форматом обмена. +- Варианты — дерево ходов, а не пло�ка� по�ледовательно�ть. Поддерживать и�ходную позицию FEN, комментарии и NAG. +- Реальные учебные PGN �одержат legacy-кодировки, FEN � fullmove=0 и `--`. Сохран�ть оригинал и диагно�тировать �овме�тимо�ть; учебный null move не �читать обычным легальным ходом. +- И�ходные пользователь�кие PGN �охран�ть; запи�ь и замена файла должны быть �вным дей�твием. +- Про�мотр линии движка не измен�ет партию. В�тавка варианта — отдельное дей�твие � возможно�тью отмены. +- �е показывать анализ �тарой позиции как анализ новой. UCI — управл�емый дочерний проце�� � таймаутами, о�тановкой и завершением. +- Т�жёлый разбор, индек�ирование и взаимодей�твие � движком не блокируют UI. +- Сохран�ть и�торию позиции дл� корректного анализа повторений; одного FEN недо�таточно дл� в�ех �ценариев. +- Сторонний код и ре�ур�ы брать из проверенных и�точников, фик�иру� конкретные лицензии и автор�тво. + +## Работа + +Окна приложени� дл� те�тов и �нимков запу�кать только через `scripts/dev/headless-run.sh -- ENV=… команда` (невидимый монитор Hyprland 1920×1080, без фоку�а и кур�ора владельца); пр�мой запу�к окна на мониторах владельца запрещён. �е запу�кать и не подмен�ть �лужбы �е��ии владельца (AT-SPI, D-Bus, порталы, ydotool и т. п.) дл� �мул�ции ввода; нужное дей�твие — через отладочный хук приложени�. + +Экономи� (владелец, 2026-11-27): визуальна� проверка — одно разрешение 1920×1080 и о�новна� (тёмна�) тема; �ветла� — только е�ли мен�ют�� цвета. Минимум �нимков: только те, что доказывают критерий; не �нимать �ерии и другие разрешени� без нужды, не держать не�колько агентов на проверке одного и того же. + +�е измен�ть и�ходное ТЗ и референ�ы. �е запу�кать неподтверждённые бинарники и незавершённые загрузки движков. Проверенные факты отдел�ть от предложений; дл� внешних техниче�ких утверждений �охран�ть ��ылки. Те�тировать значимое поведение, о�обенно �охранно�ть PGN и гонки UCI; не объ�вл�ть запланированные проверки выполненными. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9436f70 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,819 @@ +# Changelog + +All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). + +## [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 + +- Desktop, a game against the computer: the header shows its time control («5+3», «∞») + where the result comes after it; the players' cards show the king of the chosen piece + set; the player's clock turning red is heard once a game (a double tick, every sound + set); «The game is on» says which game is left («Maia 1550 · you play white · 5+3 · + move 5»). +- Android: «+ Add» sits in the Files heading, as «+ New database» in My databases, + instead of a button floating over the list. + +## [1.9.1] — 2026-10-27 + +- macOS: Rodent IV plays. Its build had no home folder on macOS (its authors left it + unwritten), found none of its personalities and offered no «Personality», so every game + ended at once with «Rodent did not start: it does not start on this computer». The + engine now takes its own folder, as on Linux and Windows; the program offers to + download it again, and only the engine itself (250 KB) is fetched. Its build is now + checked to offer its personalities from a folder like the one the program uses. + +## [1.9.0] — 2026-10-27 + +- Android: a new version is offered at each start of the app, as on the desktop (it used to + ask once a day, so a release out a day after the last check was not seen at once). +- macOS: an engine downloaded over an older one (Rodent IV from 1.7 to 1.8) no longer + fails «it does not start on this computer»: a download is written beside and put in + place, never rewritten in place (Apple silicon kills an executable changed that way). +- Desktop: a move can be taken back only in a blitz game against the computer; in rapid, + classical and games without a clock «↶ Take back» (and Ctrl+Z) is gone. + +## [1.8.0] — 2026-10-27 + +- macOS: Rodent IV out of its opening book searched garbage (a bug of its sources that + only builds by clang show) and is now built with the fix; an installed Rodent IV is + offered for download again, and only the engine itself (250 KB) is fetched. +- Android: Rodent IV joins Maia as an opponent. «Play» opens the sheet with the choice of + Maia or Rodent IV and, for Rodent, one of its 13 characters or 22 famous players (Tal, + Kasparov, Karpov…), each with its own strength scale (Rodent: 800–2800). The engine is + inside both APKs; its opening books are one download of 59 MB, removable in Settings, + and «No book» plays without them. Rematches and put-aside games keep the opponent. +- A game against the computer can be put aside and continued later: «� Put aside» in + the game, the main answer of «The game is on», and closing the window put it aside; + a card on the library's shelf continues it with the clocks as they were. A game a + crash interrupted is put aside too, no longer written into the database unfinished. + Starting a new game over it asks first. +- The window no longer freezes when a database on a network drive (NFS) becomes + unreachable, for example when the network drops during a game: whether the shelf's + files are there, their sizes and permissions are looked at by a thread of their own, + not in the frame. + +## [1.7.0] — 2026-10-26 + +- Rodent's list of styles gets Rodent IV's: 13 characters (Amanda, Defender, Strangler…) + and 22 famous players (Alekhine, Botvinnik, Fischer, Karpov, Kasparov, Petrosian, Tal…), + each with its opening books. The opponent is just «Rodent»; which engine plays follows + the style chosen (Rodent IV's strength: 800–2800). Rodent IV is downloaded once on + request: built by us from its authors' sources, with its characters and books from their + repository — on macOS too, where Rodent was not available before. + +- Android: the lists look richer. Games are divided by thin lines, each side has its + colour disc, the winner's «1» stands on a tile, the opening code (ECO) on a tag of its + own, and the game you came back from is marked. Search also finds by the ECO. On + «Databases» each kind has its colour (Catppuccin: PGN, ChessBase, archives, downloaded, + your own), groups are cards, and a game put aside shows its position. Settings are + grouped the same way, with icons. + +## [1.6.0] — 2026-10-26 + +- Games against the computer are written by themselves into the player's database, + «Roman — games against the computer» (without a name, «Games against the computer»), + made at the first game in the folder of new databases. The play dialog says where the + games go; the result strip says «Written to the database, No. n · Open». A game the program + stopped in (a crash, a power cut) is written at the next start, unfinished. Several + players of one computer each get their own database (the ▾ list by the name). It can + be turned off: Settings → Interface → Your databases. Android: the same in «My + databases» (♞), the result card says where the game went; a game put aside and let + go is written unfinished; Settings → «Write games against Maia…». +- Play against Rodent V (desktop, Linux and Windows): a strong engine with a style — + balanced, attacking, chaotic, restricting, classical, or Tal. It is downloaded once on + request (48 MB, the authors' release). +- The opponent's strength is on the engine's own scale, as its authors give it: Maia + 600–2600, Rodent V 800–3000 (its UCI_Elo). The dialog says that these are the engines' + ratings, not a person's Elo. (1.5's slider showed Maia's strength measured on the + Lichess blitz scale; a remembered strength keeps its number.) Android too: Maia + 600–2600. The engine's strength is in its name in the game («Maia 1550»), + with no Elo tag for it. +- Offer Maia a draw (desktop and Android): she accepts when she is clearly worse, or + when the position is about level (at most +0.2 for her) and has kept its character for + her last three moves; after a refusal, again two of her moves later. She judges with + Stockfish, as for her resignation. + +## [1.5.0] — 2026-10-26 + +- Play against Maia: the large model (79M parameters, 316 MB, downloaded once from the + authors' page) plays every strength; it is stronger and closer to how people play. + The slider shows her measured strength on the Lichess blitz scale (1100–2100; at the + top she chooses her moves more surely). The small model, when it is there, still + plays up to 1800. Maia thinks on half the cores; her clock counts the computing when + it takes longer than her pause. +- Game analysis: «Analyse» starts at once with the options chosen the last time; the + options dialog comes the first time and with «Analyse again…». +- Android: moves on the board (tap a piece and a square, or drag; a pawn becomes a + queen), variations, «Make it the main line» and «Delete» on a long press, «Undo». + A new game from the start; your own databases on the phone (create, rename, export + the file, delete) and saving games into them, with the game's data. +- Android: play against Maia (the small model, 21 MB, downloaded once; no clocks), + from the start or «Play on from here» after a move; take back, resign, Maia offers + to resign when lost; the game is put aside with «back» and goes on later. Learn an + opening up to a move, as on the desktop. Sounds, with a setting. +- The opening trainer and the rules of a game against Maia are shared by both apps. + +## [1.4.0] — 2026-10-25 + +- The library's title row in three groups: databases | a game to enter | Play. +- Paste a line from the clipboard (Ctrl+V on a game, or the move menu): moves («Nf3 d5», + «12...Rd8», UCI) go after the selected move or instead of it; a PGN game goes where its + moves part from this game — along any branch, or by another move order — with its + comments, symbols and variations and the players' names at the end. A game that shares + no position with this one is not pasted, with a message; a line starting before the + selected move is asked about. One Ctrl+Z takes it all back. +- Play on from here (the move menu, Ctrl+G on a game): a game against Maia from the + position, its moves up to it kept (Maia sees the history, repetitions count); the + game you came from waits under it, «⬅ Back to the game» returns to it. The side to + move plays by default; a rematch keeps the colour. +- Learn the opening (the move menu): replay from memory the moves of both sides up to + the chosen move. A wrong move is counted, shown for a moment with a short sound and + taken back; from the third mistake on a move you may ask to see it. At the end: the + mistakes by move, the runs of the line (last, best, clean in a row, recent), «Again». + The runs are kept by the line itself, across games. + +## [1.3.0] — 2026-10-25 + +- Play against the computer (desktop): «♞ Play» in the library (Ctrl+G) starts a game + against Maia — a neural network (Maia-3, CSSLab, University of Toronto) that plays like + a human of the chosen rating, 600–2600, mistakes included. Your name and rating + (optional; «Weaker · As me · Stronger» choose the strength relative to it), colour, + Lichess time controls from 3+0 to 30+20 (10+5 by default), custom, or no time limit. During the game: the + board, the notation, both clocks (time runs after each side's first move, increment + after the move, low time in red), take back, resign; no engine or analysis. Maia + thinks like a human — a pause that depends on her clock — and never loses on time. The + game ends by mate, stalemate, no material, threefold repetition, fifty moves, time or + resignation; then it is an ordinary game with the result strip: Analyse, Rematch, New + game, Save to a database (tags: players, ratings, TimeControl, Termination, [%clk]). + Maia is computed in plain Rust, about 0.1 s a move on one core; its weights (21 MB, + the authors' own file from huggingface.co) are downloaded once on request. +- Premoves against Maia, as on Lichess: while she thinks, set your next move; it is + played at once after hers when legal. +- Maia resigns: when her position is lost by twelve pawns or more for two of her turns + (judged by Stockfish, unseen), she offers to resign — accept the win, or play to the + end. +- Settings › Board: «Always promote to a queen» (off: the piece is chosen). + +## [1.2.0] — 2026-10-25 + +- Your own comments in a game (desktop): Enter on a move (or the right-click menu, a + double click on a comment, the ☰ menu) opens an editor right where the comment stands + in the notation — after any move of the main line or of a variation, or at the start of + the game; Enter — done, Esc — cancel, Shift+Enter — a paragraph; going to another move + writes the draft. Symbols of the move (! ? !! ?? !? ?!, also Ctrl+1…6) and of the + position (= ∞ ⩲ ⩱ ± ∓ +− −+) in the editor and in the move's menu, one click on, one + click off. Arrows and circles drawn with the right mouse button on the board (green; + Shift red, Alt blue, Shift+Alt yellow; the same shape again takes it off) go into the + comment as `[%cal]`/`[%csl]`. Existing comments, book ones too, can be edited and + deleted (Ctrl+Z puts them back); their `[%clk]`, `[%eval]` and board commands are kept, + an untouched comment keeps its bytes. One edit is one undo step; the game is marked + modified and Ctrl+S saves it. Paragraphs of comments survive writing now. +- The strip «Engine line preview … Add as variation · Exit» above the notation is gone: + stepping through a line of the report or of the engine panel just shows it on the + board, Esc leaves it, and a small «+ Add as variation» stands at the end of the line + being shown. Moves of variations and of the report's better lines keep their size under + the mouse. + +## [1.1.0] — 2026-10-25 + +- Your own databases (desktop): «✚ New database» on the shelf makes an empty PGN file + (Documents/ChessPenguin by default, the folder is shown and can be changed); any game — + new, pasted, from a ChessBase, an online or any other database — is added to a PGN of + your choice with «Add to database…» (Ctrl+Shift+S, the 💾 button, the ☰ menu); Ctrl+S + saves the changes back into the game's own PGN (replacing its record) or, for a game + from a read-only source, adds it to a database. The data of a game (players, Elo, event, + site, date, round, result, annotator from «Your name» in Settings) are asked when a new + game is first added and can be edited any time (F2, the title, the ☰ menu). A game that + is already in the target (same players, date and moves) can replace its record or go in + as a new one. Games are deleted from the table (Delete, the row menu) after a question, + with Undo for six seconds (Ctrl+Z). Online databases and ChessBase files stay read-only; + a PGN in a legacy encoding is offered a UTF-8 copy next to it. Writes are explicit: + appending to the file, or rewriting it through a temporary file and a rename, with a + check that the file did not change on the disk meanwhile. The game's header names its + database and number (🔒 read-only, � online); the card menu has «Show in folder»; + «Remove from list» says where the file stays. A new game gets today's date. +- Library: «+ Add database», «✚ New database» and «� Online games» moved from the row of + database cards to the title row, beside «Databases» (folded into «+ ▾» and «�» in a + narrow window); the cards row holds only databases. An empty shelf shows the three + actions as large cards in the middle. The table header of a database that takes games + has «+ Game»: a new game meant for that database — its header says so and Ctrl+S adds + it there straight away. «Add to database» lists only databases that take games; a PGN + in a legacy encoding gets its UTF-8 copy from its card's menu. The built-in sample + databases are read-only. An empty database shows no filter panel. + +## [1.0.3] — 2026-10-24 + +- A new icon — a penguin in a crown — on the desktop, Android and the website. + +## [1.0.2] — 2026-10-24 + +- Android: the update card on the main screen has a × that stops the offers (with "Undo"; + they come back with "Offer new versions" in Settings → About, where a new version can + always be installed); the update check and the counting go on. No "What's new" link to + GitHub anywhere in the app's update screens. + +## [1.0.1] — 2026-10-24 + +- The update check goes through the ChessPenguin site (GitHub when the site does not + answer), which counts installations that run: once a day, only a random number of the + installation, the version and the platform. With the check at start turned off, + nothing is sent unless one checks by hand. The site's statistics show installations by day, platform and version. + +## [1.0.0] — 2026-10-24 + +- Three more interface languages on the desktop, on Android and on the website: Brazilian + Portuguese, Uzbek (Latin script) and Kazakh (Cyrillic script) — nine in all. The + system's language is picked up; Portuguese notation uses its own piece letters. +- Android: the players stand above and below the board, as on Lichess (Black above, + swapped with the board), with their ratings and their share of the result; the top bar + names the event, the year and the round. In the list of games White and Black have a + line each, so neither name is cut. + +## [0.16.2] — 2026-10-24 + +- Desktop: narrow windows (half a screen, a tiling window manager) no longer overlap: + - the reference tab, the engine settings and the game's title fit their place (the + reference tab slid under the board from a 1200-point window down); + - in a narrow window the filters open over the list of games, and the search board + takes the place of the list (Esc goes back); + - a narrow tall window shows the notation under the board; + - the header of the list and the shelf shorten what does not fit, or take a second + line; the window can be made as small as 640×480. +- Desktop: Escape in the "Game modified" question quits nothing: when closing the program + it is Cancel (leaving a game, it still goes on without saving). + +## [0.16.1] — 2026-10-24 + +- Desktop: the filter panel no longer widens while a name is typed; the rows of «Game» + (years, rating, moves, ECO) are aligned on one grid. +- Desktop: Escape in a game with unsaved edits asks about saving (the question used to + close at once, so Escape seemed to do nothing); Escape in the question goes on without + saving, Cancel stays in the game. + +## [0.16.0] — 2026-10-24 + +- Desktop: **every database gets the filters and the position search of a ChessBase + database** — PGN files of any size, downloads from Lichess and Chess.com, archives and + small ChessBase databases. Player and opponent (with the colour), tournament or place, + annotator, years, rating, result, ECO, length, «with comments» (clock and evaluation + marks such as `[%clk]` do not count) and «with variations»; names suggested as you + type; the table sorts by any column. Fields a file does not have stay in the panel, + and an empty result says when no game of the database has that field. Dates are read + with dots, dashes or slashes (`2026-10-18`), the length of a game is counted when the + file has no `PlyCount`. +- Desktop: the quick search is in the header of every database (Mega too); each word may + be found in a different field ("carlsen 2024"). Ctrl+F goes there, again to the filters. +- Desktop: games downloaded from Lichess and Chess.com are shown newest first (by the + date and time they were played); on Android the count over a downloaded database's + games grows during its download. +- Names are found with «е» for «ё» («�ртем» finds «�ртём»). +- The memory a PGN's position search needs is reckoned from its moves, not from the size + of the file (a file with clock comments was thought to need 14 times too much). + +## [0.15.0] — 2026-10-23 + +- Android: **the app updates itself.** Once a day (a switch in About turns it off; «Check + now» is there too) it asks GitHub for the latest release. A newer one shows as a card + over the list of databases: «Update» downloads the small build (about 9 MB; the engine + already on the phone stays — the build with Stockfish inside keeps it first), checks it + against the release's SHA-256 and hands it to Android to install. The first time Android + asks to allow installs from ChessPenguin; the app leads there and back. The download + goes on with the app in the background, and the next start says what was updated. +- The release page on GitHub now lists what is new in that version (from this file); the + apps' and the site's «What's new» lead there. +- The desktop and Android apps share one check for new releases. + +## [0.14.0] — 2026-10-23 + +- Android: **games from Lichess and Chess.com** — «Add a database» → «Games from Lichess + and Chess.com»: any player's games by nickname (yours, a pupil's, an opponent's; no login, + another nickname for Chess.com if it differs) become a database on the phone, both sites + merged into one by default. «Download new games» — in the database's menu and over its + games list — fetches only the games played since; a download that was stopped, failed or + cut off by a closed app continues where it stopped, without duplicates. The games of such + a database are listed from the most recent one. The download goes on when the screen is + left; the list shows its progress and says how it ended. Only standard chess is kept. The + app asks the sites only when told to (both builds may now use the internet for this). +- The downloads of games from Lichess and Chess.com are one shared part of the desktop and + Android apps. +- Android: the status bar and the navigation bar follow the theme chosen in the app: with + the dark theme on a light phone their icons are light again (they stayed dark on dark). + +## [0.13.0] — 2026-10-23 + +- Android: **game report** — ⋮ → «Game analysis» lets Stockfish evaluate every move of the + main line, as on the desktop: inaccuracies, mistakes and blunders marked in the notation, + an evaluation graph under the board (tap or drag to go to a move), each player's accuracy + and average centipawn loss in the report, the better move of every error shown on the + board. Games with `[%eval]` comments (Lichess exports) and games analysed before show + their report at once. The live engine waits while the game is analysed. +- The game report's evaluations, judgements, accuracy and cache are now one shared part of + the desktop and Android apps, so both give the same numbers. + +## [0.12.0] — 2026-10-23 + +- Android: **paste PGN** — when the clipboard holds text, «Add a database» offers to paste + it: the games are kept in the app as a database and opened (one game on the board at + once). Text with no game in it is said so. +- Android: **open with ChessPenguin** — PGN, ZIP, 7z and ChessBase archives (`.cbv`) open + from other apps (Telegram, a file manager, «Share»): the file is copied into the app, + put on the list and opened. The same file again opens the same database. +- Android: the engine button turns the engine off again (in 0.11.1 it only turned it on). +- Android: a smoother screen while the engine thinks — its words are shown up to five + times a second and redraw only the engine strip and the arrows; Stockfish runs below the + app's priority and takes 2 threads by default (a value chosen in Settings stays). +- PGN: a game whose tags follow the previous game's result on the same line (`… 1-0 + [Event "B"]`, as pasted text often has it) now shows its players in the games list too. + +## [0.11.1] — 2026-10-23 + +- Android: **boards and pieces** — Settings → «Board and pieces» offers the 37 boards and + 17 piece sets of the desktop app, seen at once on a board above them. +- Android: the games list shows each game's number in the database (it stays the same + when a search narrows the list). +- Android: the engine turns on only with its button in each game, and turns off when you + leave the game or the app goes to the background. +- Android: the engine download no longer says there is not enough space on a phone with + plenty of it (the free space was asked of a folder not made yet). + +## [0.11.0] — 2026-10-22 + +- Android: **add a folder** — every database in it and in the folders inside it (two + levels) is offered with a tick box: PGN files, archives, ChessBase archives (`.cbv`) and + ChessBase databases (`.cbh` with the files beside it), which a single picked file could + not open. A ChessBase database without its `.cbg` is shown but not added; databases + already on the list are marked. Picking the folder again offers what is new. Errors say + in plain words when a file was moved or a part of a ChessBase database is missing. +- Desktop, keys in a game: ↑ goes to the end, ↓ to the start (as End and Home); variations are + switched with Shift+↑/↓. Escape first closes what is open (a preview of an engine line, + a picked-up piece); then it goes back to the game this one was opened from, or to the + library. A window, menu or dialog over the game keeps Escape for itself, and a game with + unsaved changes still asks first. + +## [0.10.0] — 2026-10-22 + +- **ChessPenguin for Android, alpha** (12 and newer): add databases of the same formats (PGN, ChessBase + `.cbv`, `.zip`/`.7z` archives), the desktop's sample games from the first start, a list of + games with a search, the game with the notation under the board (variations, comments, NAG, + comment arrows), paging games, and Stockfish 19 with its evaluation, lines and a preview of + a line on the board. Two APKs: Stockfish built in, or Stockfish downloaded in the app. + Files are only read, never changed. The engine's download goes on in the background, with + the app closed too. In English, Russian, German, French, Spanish and Italian. + +## [0.9.0] — 2026-10-22 + +The 0.8 series together — the reference tab, games from Lichess and Chess.com, self-update, +translated comments, move notation and piece animation — with these fixes: + +- Symbols that had no glyph and showed as empty boxes now render: the "✕" beside the + Chess.com nickname, the start-position mark in board search, the check marks of the + translation texts. A test checks every character the interface shows against the bundled + fonts. + +## [0.8.6] — 2026-10-21 + +- The side panel no longer widens by itself while a game's comments are translated (the mark + of a translated comment made its row a pixel wider than the panel, frame after frame), so + moves in comments no longer jump when the mouse moves over them. +- Comments inside variations have the same size as the other comments. +- No scroll bar pops up over the engine lines: a long line is cut at the edge (it still scrolls + with Shift+wheel or by dragging). +- A game whose comments go in one request shows just "Translating…": the count + ("12 of 40") is kept for long games sent in several parts. + +## [0.8.5] — 2026-10-21 + +- Translation with a ChatGPT subscription works: the list of models the subscription answers + with is now understood (it differs from the API's), so requests no longer go out without a + model and fail with "error 400". OpenAI's preferred model is used. A failed check now shows + in Settings › Translation, and translation errors are written to chesspenguin.log. +- Comments of a sentence or two in another language are offered for translation too, and text + in brackets ("[source: …]") is translated as well. + +## [0.8.4] — 2026-10-21 + +- Move notation (Settings › Board & pieces): Latin letters (Nf3), figurines as on Lichess + (♘f3), or the piece letters of the interface language — Russian Кр Ф Л С К, German + K D T L S, French R D T F C, Spanish and Italian R D T A C. It applies to the move list, + engine lines, the reference tab, board search and the analysis report; PGN files and + copied games always stay in K Q R B N. Latin remains the default. +- Translation of game comments: when a game's comments are in another language, ChessPenguin + offers to translate them into yours. Sign in with your ChatGPT Plus or Pro subscription (no + key), or use an API key — DeepSeek, OpenAI, Google Gemini — or a model on this computer + (Ollama, LM Studio). After the first consent, games in other languages are translated as you + open them; [Original | Translation] (Ctrl+Shift+T) switches back. Moves are never translated: + a translation that changes a move is not shown. The translation is never written to the PGN; + a local cache keeps it, so a game opens translated again without the network. Settings › + Translation: the target language, when to translate, the connection, permissions, the cache. +- Arrows (→, ⇄) and the evaluation signs ⩲ ⩱ ⌓, shown as empty boxes before, now render. +- Piece animation, as on Lichess: a move slides on the board (castling moves both king and + rook; jumping several moves slides every piece once), a captured piece fades out. Speed in + Settings → Board: Off, Fast (120 ms), Normal (250 ms, the default), Slow (500 ms). A piece + dropped by dragging is already in place and does not slide. + +## [0.8.2] — 2026-10-21 + +- Windows: ChessPenguin no longer quits silently on a machine whose graphics do not + cooperate (an old driver, a broken Vulkan, a virtual machine). A start that fails or dies + before its first frame tries again without Vulkan, then with OpenGL, then with software + drawing, and keeps the mode that worked. What still prevents the start is shown in a + message and written to chesspenguin.log beside the settings. The C runtime is now inside + the executable, so the Visual C++ Redistributable is not needed. +- The window "Games from Lichess and Chess.com" opens with an empty nickname, the cursor in + it: the next search is usually for another player (a database already downloaded fetches + its new games with "⟳ New games"). + +## [0.8.1] — 2026-10-20 + +- The side panel fits small screens (a laptop with 200 % scaling): the reference tab no longer + slides under the board and is no longer cut off on the left. Its tables narrow their columns + and drop the less important ones to fit, their headings wrap, and in a tall narrow window the + board gives way so the reference keeps enough width. + +## [0.8.0] — 2026-10-20 + +- Games from Lichess and Chess.com: anyone's games by nickname — yours, a pupil's, an + opponent's, a champion's (no login; another nickname for Chess.com if it differs). See what + was found, download the games into a database — both sites merged into one by default, or + one per site — and later fetch the new ones with "⟳ New games" in the database header. The + progress shows per site with the time left; the window may be closed meanwhile (the result + then shows as a message). An interrupted download — stopped, failed, or the program closed — + keeps what it got and continues where it stopped, without duplicates (also after a crash); + games still being played (correspondence) are fetched once they end. Only standard chess is + kept. The feature is offered only when the sites answer: ChessPenguin asks each for a public + profile at start (nothing of yours is sent), so offline it stays hidden. + +## [0.7.1] — 2026-10-20 + +- Updates: at start ChessPenguin asks GitHub for the latest version (can be turned off in + Settings → About) and offers a newer one with a button next to Settings. The Windows zip, + the AppImage and the Linux archive update themselves (download, checksum check, replace, + restart); macOS downloads and opens the disk image with step-by-step instructions; deb, rpm, + Arch and Flatpak packages are downloaded into Downloads and the one command that installs + them is shown with a Copy button; the AUR package shows the helper command. "Skip this + version" hides the button until the next one. +- The Flatpak may use the network (the update check). + +## [0.7.0] — 2026-10-20 + +- «Справочник» (Reference) tab of a game: what was played in the current position in a + database of the shelf (Mega for theory, an opening collection, a pupil's games), as two + tables — the moves with games, share, results, White's score, average rating, year and + the best players who played them, and the strongest (or newest) games that reached the + position with how they went on. Click a move to see its games, double-click to play it; + double-click a game to open it at this position (the current game stays a click away: + "⬅ Back to …", unsaved edits included). It also tells how far the game follows the + database (the novelty: the first move no other game of the database played) and finds the + game itself there (to open, for example, an annotated copy). +- The board of a game always keeps the full height of the window (the side panel is never + wider than the room beside it). +- Settings → Engines no longer offers to download Stockfish when one is already set up. +- Russian numbers use a decimal comma ("11,7 млн"). + +## [0.6.3] — 2026-10-19 + +- Import notes (for example, Chess960 games shown without moves) are a quiet grey "ℹ" now + instead of an orange warning sign. +- Position search in a large ChessBase database without a usable `.cbb` search index: the + program builds its own once (in the background, kept in the cache) and deep positions are + then found in milliseconds instead of a pass over every game. +- Opening positions (the start, 1.e4, …) in a large ChessBase database: an index of the + first ten moves of every game, built with the booster and kept in the cache, answers them + four to eight times faster. It is held in memory only when the machine has room for it + (about 600 MB for Mega Database); otherwise the search works as before. +- A big PGN file whose position table would not fit in memory now says so on the search + board instead of running out of memory. +- `chesspenguin --bench ` prints timings of opening, filtering and position + search for comparing machines. +- Settings → About: clicking the email address copies it instead of opening a mail app, + which does nothing useful when none is installed. + +## [0.6.2] — 2026-10-19 + +- Settings → About: the version, links to the website (in the interface language), the release + notes and the source code, and the support contacts. Links open in the browser. + +## [0.6.1] — 2026-10-19 + +- The library is no longer empty at the first start: two sample databases are on the shelf — + classic games (38 famous games from Anderssen and Morphy to Kasparov and Carlsen, each with a + short introduction; four with full comments, variations and arrows) and Alekhine's games (267 + games, moves only). Remove them from the shelf like any database; they do not come back. +- The first start uses the system language when it is one of the six (English, Russian, French, + German, Spanish, Italian), otherwise English. A language chosen in the settings is kept. + +## [0.6.0] — 2026-10-19 + +- Stockfish is no longer inside the packages (they shrink from about 95 MB to about 14 MB): the + first time you analyse, ChessPenguin offers to download the official Stockfish 19 (checked + before use, installed for your account only) and starts the analysis when it is there. The same + button is in Settings → Engines, with progress, cancel and "remove" to free the space. A system + `stockfish` is still found and offered; the Flatpak keeps Stockfish inside. +- macOS on Apple Silicon: a `.dmg` with ChessPenguin.app (not signed by Apple yet). +- Position search fixes (QA report 3): "in this move order" no longer reused from another move + order of the same position; while a search runs, the arrow and the position a game opens at + belong to the rows shown; in books the next move of a game ending in the position is no longer + taken from a variation; average rating of a continuation only from games with both ratings. +- Narrow windows: the [Filters | Board] switch stays visible, conditions that do not fit become + "+N more", columns hide by priority and the date becomes the year. +- Continuations are numbered through the whole list (keys 1-9 still play the first nine). +- Ctrl+Shift+Backspace clears all conditions with the position; a × removes the position in small + databases; the cache of search results is bounded. + +## [0.5.0] — 2026-10-19 + +- Find games by position: the "Board" pane next to the game list (Ctrl+B). Play moves and the list + shows the games that reach the position by any move order, with the moves played next (games, + results bar, average rating, last year); click a move to play it. Works together with the + filters, sorts strongest games first, marks games reached by another move order (↪) and offers + "only this order". Books and PGN collections are searched in variations too. A game opens at the + found position. On the game screen "� Find in database" (Ctrl+Shift+F) searches its position. + Mega Database: 0.4 s for the starting position, under 0.1 s deeper in the opening. +- The game list's "Moves" column is now "Length". +- Filter fields and the search field have a × to clear them. +- "Open as a new game" from the search board opens at the last move played on it. + +## [0.4.0] — 2026-10-19 + +- Large ChessBase databases (Mega Database: 11.7 million games) open in seconds: read in place from + the `.cbh` records, a game is converted when opened. A filter panel on the right (player with + suggestions, colour, opponent, tournament, annotator, years, Elo, result, ECO, moves, comments and + variations) updates the list as you type; sorting and filtering run in the background. +- Fixed: a ChessBase game that cannot be read from its first move (e.g. Chess960) crashed the import. +- Fixed: ChessBase databases mixing UTF-8 and single-byte texts could be decoded as Cyrillic. +- Removed the in-app ✕ (close) button: the window manager or desktop provides window controls. + +## [0.3.0] — 2026-10-18 + +- Open ChessBase databases (`.cbh` with companion files) and ChessBase archives (`.cbv`), and + `.zip` / `.7z` archives holding PGN, `.cbh` or `.cbv` files. Games, variations, comments (with the + right code page, including Cyrillic), symbols, coloured squares and arrows, set-up positions and + book chapters are converted to PGN in memory; sources are read-only. Problems are listed under + "Import notes" in the library. +- Comments keep paragraph breaks (a blank line starts a new paragraph). +- Game screen: the result next to the players; Lichess-style badges on the moved piece (engine + judgement or the author's symbol); on a marked move, arrows show the refutation and the best + answer; all engine arrows blue, only the live engine's while it runs. +- Library: games opened before are marked with a check (context menu to change). +- More looks: piece sets governor, kosal, metaltops; boards IC, NCF, Ice, Navy, Mint, Emerald, + Orange, Rose, Dusk, Night and Sketch; sound sets Futuristic, NES, Wood, Glass, Clicks. +- Fixed: the checkmate sound was silent (a copied link instead of a sound file). +- Library: "+ Add database"; long database names are shortened on the cards. + +## [0.2.0] — 2026-10-18 + +- Stockfish 19 is bundled with every package (unmodified official "universal" build, which picks + the right code path for the CPU) and set up on the first start; a system `stockfish` is detected + too. Settings → Engines offers engines found on the computer. Packages grow to about 95 MB. + +- Game analysis (Shift+A): background evaluation of the whole main line with its own engine process, + evaluation graph under the board, report tab with accuracy, inaccuracies, mistakes, blunders, + average centipawn loss and accuracy per game phase; engine marks and better lines in the notation; + "Write analysis to the game" (NAGs, comments, `[%eval]`, one undo step). Results are cached; + `[%eval]` comments of a PGN are used without an engine. +- Screenshots in English and Russian. + +## [0.1.0] — 2026-10-18 + +First public release. + +- PGN library with background loading, search and sorting; legacy encodings and real-world PGN quirks. +- Game view: board, notation with variations and comments, keyboard navigation. +- Move entry, variations, promote/delete lines, undo/redo, copy PGN/FEN, save as. +- UCI engine analysis: multiple lines, arrows, evaluation bar, inline engine settings, line preview. +- 14 piece sets, 26 boards, sounds, dark/light theme, six UI languages. +- Packages: deb, rpm, AppImage, Flatpak, Windows zip. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..094a952 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,6313 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accesskit" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954" +dependencies = [ + "accesskit", + "accesskit_consumer 0.36.0", + "atspi-common", + "phf 0.13.1", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer 0.38.0", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21" +dependencies = [ + "accesskit", + "accesskit_consumer 0.35.0", + "hashbrown 0.16.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313" +dependencies = [ + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "alsa" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d" +dependencies = [ + "alsa-sys", + "bitflags 2.13.2", + "cfg-if", + "libc", +] + +[[package]] +name = "alsa-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni 0.22.4", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "askama" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4" +dependencies = [ + "askama_macros", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39" +dependencies = [ + "askama_parser", + "basic-toml", + "glob", + "memchr", + "proc-macro2", + "quote", + "rustc-hash 2.1.3", + "serde", + "serde_derive", + "syn 3.0.9", +] + +[[package]] +name = "askama_macros" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b" +dependencies = [ + "askama_derive", +] + +[[package]] +name = "askama_parser" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583" +dependencies = [ + "rustc-hash 2.1.3", + "serde", + "serde_derive", + "unicode-ident", + "winnow", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.5", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.5", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.5", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "btoi" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b5ab9db53bcda568284df0fd39f6eac24ad6f7ba7ff1168b9e76eba6576b976" +dependencies = [ + "num-traits", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.5", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.5", + "rustix 1.1.5", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "cargo_metadata" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "chess-core" +version = "2.5.2" +dependencies = [ + "encoding_rs", + "pgn-reader", + "serde", + "shakmaty", + "thiserror 2.0.21", +] + +[[package]] +name = "chess-import" +version = "2.5.2" +dependencies = [ + "chess-core", + "encoding_rs", + "sevenz-rust2", + "shakmaty", + "sysinfo", + "thiserror 2.0.21", + "zip", +] + +[[package]] +name = "chess-openings" +version = "2.5.2" +dependencies = [ + "chess-import", + "serde", + "shakmaty", +] + +[[package]] +name = "chesspenguin" +version = "2.5.2" +dependencies = [ + "arboard", + "base64 0.22.1", + "chess-core", + "chess-import", + "chess-openings", + "chrono", + "directories", + "eframe", + "egui", + "egui_extras", + "flate2", + "form_urlencoded", + "game-review", + "getrandom 0.3.4", + "image", + "js-sys", + "log", + "maia", + "online-games", + "play", + "prep", + "releases", + "rfd", + "rodio", + "serde", + "serde_json", + "sha2", + "shakmaty", + "skrifa", + "sys-locale", + "tar", + "thiserror 2.0.21", + "trainer", + "uci", + "ureq", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "whatlang", + "winresource", + "zip", +] + +[[package]] +name = "chesspenguin-web" +version = "2.5.2" +dependencies = [ + "chesspenguin", + "eframe", + "log", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "coreaudio-rs" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58" +dependencies = [ + "bitflags 2.13.2", + "libc", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "cpal" +version = "0.17.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8942da362c0f0d895d7cac616263f2f9424edc5687364dfd1d25ef7eba506d7" +dependencies = [ + "alsa", + "coreaudio-rs", + "dasp_sample", + "jni 0.21.1", + "js-sys", + "libc", + "mach2", + "ndk", + "ndk-context", + "num-derive", + "num-traits", + "objc2 0.6.5", + "objc2-audio-toolbox", + "objc2-avf-audio", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dasp_sample" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "deflate64" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "ecolor" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34" +dependencies = [ + "bytemuck", + "emath", +] + +[[package]] +name = "eframe" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ad41fac6e3149abb4866e93df37dbd33baa95db525c3368c944584e95a5dc2" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "egui-wgpu", + "egui-winit", + "egui_glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "pollster 1.0.1", + "profiling", + "raw-window-handle", + "static_assertions", + "wasm-bindgen", + "web-sys", + "web-time", + "wgpu", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba" +dependencies = [ + "accesskit", + "ahash", + "bitflags 2.13.2", + "emath", + "epaint", + "itertools", + "log", + "nohash-hasher", + "profiling", + "smallvec", + "unicode-segmentation", + "web-sys", +] + +[[package]] +name = "egui-wgpu" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cef1f6d1bba40b09a4d0d62cb822b81030922cfbf65c5373398c3a3caafc5bd" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "epaint", + "log", + "profiling", + "thiserror 2.0.21", + "type-map", + "web-time", + "wgpu", + "winit", +] + +[[package]] +name = "egui-winit" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc" +dependencies = [ + "accesskit_winit", + "arboard", + "bytemuck", + "egui", + "log", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "objc2-ui-kit 0.3.2", + "profiling", + "raw-window-handle", + "smithay-clipboard", + "web-time", + "webbrowser", + "winit", +] + +[[package]] +name = "egui_extras" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05cbdc785020861553f230f23d330ba1fb72613b9d8e0e457f3bdc8ba6db6dcf" +dependencies = [ + "ahash", + "egui", + "enum-map", + "image", + "itertools", + "log", + "mime_guess2", + "profiling", + "resvg", +] + +[[package]] +name = "egui_glow" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "profiling", + "winit", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "emath" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enum-map" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "epaint" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3" +dependencies = [ + "ahash", + "bytemuck", + "ecolor", + "emath", + "epaint_default_fonts", + "font-types", + "harfrust", + "log", + "nohash-hasher", + "parking_lot", + "profiling", + "self_cell", + "skrifa", + "smallvec", + "unicode-general-category", + "unicode-segmentation", + "vello_cpu", +] + +[[package]] +name = "epaint_default_fonts" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "fearless_simd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "game-review" +version = "2.5.2" +dependencies = [ + "chess-core", + "chess-openings", + "serde", + "serde_json", + "shakmaty", + "uci", + "web-time", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glifo" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "skrifa", + "smallvec", + "vello_common", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "goblin" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47" +dependencies = [ + "log", + "plain", + "scroll", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libbz2-rs-sys" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lzma-rust2" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1c46f3fcd2e888afdb01a07efc071cb21300e07c68d32c3e8b01b5c8cb1fcaa" + +[[package]] +name = "mach2" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1b95cd5421ec55b445b5ae102f5ea0e768de1f82bd3001e11f426c269c3aea" +dependencies = [ + "libc", +] + +[[package]] +name = "maia" +version = "2.5.2" +dependencies = [ + "serde_json", + "shakmaty", + "thiserror 2.0.21", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess2" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1706dc14a2e140dec0a7a07109d9a3d5890b81e85bd6c60b906b249a77adf0ca" +dependencies = [ + "mime", + "phf 0.11.3", + "phf_shared 0.11.3", + "unicase", +] + +[[package]] +name = "minicov" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d" +dependencies = [ + "cc", + "walkdir", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mobile-api" +version = "2.5.2" +dependencies = [ + "chess-core", + "chess-import", + "game-review", + "maia", + "online-games", + "play", + "releases", + "shakmaty", + "thiserror 2.0.21", + "trainer", + "uci", + "uniffi", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-audio-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08" +dependencies = [ + "bitflags 2.13.2", + "libc", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "online-games" +version = "2.5.2" +dependencies = [ + "chess-core", + "serde", + "serde_json", + "ureq", +] + +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo 0.13.1", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "pgn-reader" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e9c8c7d9654b31768477ec2712b9e40682ad1dd323db2867dfeefa94651c6a" +dependencies = [ + "btoi", + "memchr", + "shakmaty", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.8", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.119", + "unicase", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", + "unicase", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "play" +version = "2.5.2" +dependencies = [ + "chess-core", + "getrandom 0.3.4", + "shakmaty", + "uci", +] + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppmd-rust" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1" + +[[package]] +name = "prep" +version = "2.5.2" +dependencies = [ + "chess-core", + "chess-import", + "chess-openings", + "game-review", + "serde", + "serde_json", + "uci", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_distr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8" +dependencies = [ + "num-traits", + "rand 0.10.3", +] + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "releases" +version = "2.5.2" +dependencies = [ + "serde_json", + "ureq", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "resvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" +dependencies = [ + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "pollster 0.4.0", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rodio" +version = "0.22.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a536bb79db59098ef71a4dd4246c02eb87b316deceb1b68e0cde7167ec01eb" +dependencies = [ + "cpal", + "dasp_sample", + "num-rational", + "rand 0.10.3", + "rand_distr", + "rtrb", + "symphonia", + "thiserror 2.0.21", +] + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "rtrb" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fae8ee26b0371a29a77d2b2d6b3ae13aa81def6f9bf1b1b92a32d279a5e709b7" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scroll" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6" +dependencies = [ + "scroll_derive", +] + +[[package]] +name = "scroll_derive" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sevenz-rust2" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0c68c0e8289bfd09e49ef433e8de02c7c464afc1d7f5a275c99749a880e301" +dependencies = [ + "bzip2", + "crc32fast", + "flate2", + "js-sys", + "lzma-rust2", + "ppmd-rust", + "wasm-bindgen", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shakmaty" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d465a6a07031a8c60d92dc9b656cc8f59f8c1640493576d5d88f898883b4bd67" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "btoi", + "nohash-hasher", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "smawk" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.14.5", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo 0.11.3", + "siphasher", +] + +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-aac", + "symphonia-codec-pcm", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-isomp4", + "symphonia-format-ogg", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-aac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" +dependencies = [ + "log", + "symphonia-core", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-format-isomp4" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5" +dependencies = [ + "encoding_rs", + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "sysinfo" +version = "0.39.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "textwrap" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" +dependencies = [ + "smawk", + "unicode-width", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "trainer" +version = "2.5.2" +dependencies = [ + "chess-core", + "chrono", + "serde", + "serde_json", + "web-time", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom 8.0.0", + "petgraph", +] + +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uci" +version = "2.5.2" +dependencies = [ + "js-sys", + "libc", + "thiserror 2.0.21", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test", + "web-sys", + "web-time", +] + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "uniffi" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76407f5f396a2c949a069eff4a9fca9ce462410eb872bffef4c2b7b89804a77a" +dependencies = [ + "anyhow", + "camino", + "cargo_metadata", + "clap", + "uniffi_bindgen", + "uniffi_core", + "uniffi_macros", + "uniffi_pipeline", +] + +[[package]] +name = "uniffi_bindgen" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3df3ced8f0eda3de99f6d50820e8628f443da8e4f447f477d1403ceba29dacbd" +dependencies = [ + "anyhow", + "askama", + "camino", + "cargo_metadata", + "fs-err", + "glob", + "goblin", + "heck", + "indexmap", + "once_cell", + "serde", + "tempfile", + "textwrap", + "toml", + "uniffi_internal_macros", + "uniffi_meta", + "uniffi_pipeline", + "uniffi_udl", +] + +[[package]] +name = "uniffi_core" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7530ae8efeaaa488622865966763fe0294832779fff80508c36d69c6a874a6a" +dependencies = [ + "anyhow", + "bytes", + "once_cell", + "static_assertions", +] + +[[package]] +name = "uniffi_internal_macros" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f4bad017164375d99450d70495014810d15a84ba9da6ed14b9628b1424223ba" +dependencies = [ + "anyhow", + "indexmap", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "uniffi_macros" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b855a58da153739ce6e863f6e296edc3716a093768c4d3d957f17f5e4317c60" +dependencies = [ + "camino", + "fs-err", + "once_cell", + "proc-macro2", + "quote", + "serde", + "syn 2.0.119", + "toml", + "uniffi_meta", +] + +[[package]] +name = "uniffi_meta" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af0c88664a9cb9559856f5a250283c9708923b303170e2e5c7db8f4ad65e9459" +dependencies = [ + "anyhow", + "siphasher", + "uniffi_internal_macros", + "uniffi_pipeline", +] + +[[package]] +name = "uniffi_pipeline" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d00f5c044b4a3dca0b1226c92ddaeea626f337470e22180dd182160c87a06b0b" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "tempfile", + "uniffi_internal_macros", +] + +[[package]] +name = "uniffi_udl" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55dfd9c778d6b39cb5acd541d9ff63431974035d2bad83c897b766a6ee3152ac" +dependencies = [ + "anyhow", + "textwrap", + "uniffi_meta", + "weedle2", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "usvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "imagesize", + "kurbo 0.11.3", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "xmlwriter", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vello_common" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "log", + "peniko", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "vello_common", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-bindgen-test" +version = "0.3.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42" +dependencies = [ + "async-trait", + "cast", + "js-sys", + "libm", + "minicov", + "nu-ansi-term", + "num-traits", + "oorandom", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test-macro", + "wasm-bindgen-test-shared", +] + +[[package]] +name = "wasm-bindgen-test-macro" +version = "0.3.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "wasm-bindgen-test-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe" + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.5", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.5", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webbrowser" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" +dependencies = [ + "jni 0.22.4", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weedle2" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "whatlang" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e8f38b596e2a359b755342473520a99421e43658548c79489ee221b728c107" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "smithay-client-toolkit 0.19.2", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" +dependencies = [ + "toml", + "version_check", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.5", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.5", +] + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zip" +version = "9.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" +dependencies = [ + "bzip2", + "crc32fast", + "deflate64", + "flate2", + "indexmap", + "memchr", + "nix", + "typed-path", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1884f98 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,67 @@ +[workspace] +resolver = "3" +members = [ + "crates/chess-core", + "crates/chess-import", + "crates/uci", + "crates/openings", + "crates/game-review", + "crates/online-games", + "crates/releases", + "crates/mobile-api", + "crates/maia", + "crates/trainer", + "crates/play", + "crates/prep", + "apps/desktop", + "apps/web", +] + +[workspace.package] +version = "2.5.2" +edition = "2024" +rust-version = "1.97" +license = "GPL-3.0-or-later" +authors = ["vrubelroman "] +repository = "https://github.com/vrubelroman/chessPenguin" +homepage = "https://github.com/vrubelroman/chessPenguin" + +[workspace.dependencies] +shakmaty = "0.30.2" +pgn-reader = "0.29.1" +encoding_rs = "0.8" +thiserror = "2" +# `Instant`/`SystemTime` that also work in a browser (std's panic there). +web-time = "1.1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +egui = "=0.36.2" +eframe = { version = "=0.36.2", default-features = false, features = ["wgpu", "wayland", "x11", "accesskit", "default_fonts", "links"] } +egui_extras = { version = "=0.36.2", features = ["svg", "image"] } +image = { version = "0.25", default-features = false, features = ["jpeg", "png"] } +rfd = "0.17" +arboard = { version = "3.6", features = ["wayland-data-control"] } +rodio = "0.22" +directories = "6" +chess-core = { path = "crates/chess-core" } +chess-import = { path = "crates/chess-import" } +uci = { path = "crates/uci" } +maia = { path = "crates/maia" } +game-review = { path = "crates/game-review" } +chess-openings = { path = "crates/openings" } +online-games = { path = "crates/online-games" } +releases = { path = "crates/releases" } +trainer = { path = "crates/trainer" } +play = { path = "crates/play" } +prep = { path = "crates/prep" } + +[profile.dev.package."*"] +opt-level = 2 + +# The web version (apps/web/build.sh): small to download, the release otherwise. +[profile.web] +inherits = "release" +opt-level = "s" +lto = "fat" +codegen-units = 1 +panic = "abort" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + 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), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 66c9369..bbcb8ad 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,160 @@ -# ChessPenguin — private files +

+ ChessPenguin icon +

-Branch `private` of the home Forgejo only. It has no common history with `main`, and -`scripts/publish-github.sh` publishes only `main` and the tags: nothing here reaches -GitHub. **Never merge this branch into `main` and never tag a commit of it.** +

ChessPenguin

-| Path | What | Where it goes | -| --- | --- | --- | -| `secrets/android/` | Android release key `release.jks` (+ base64 for the GitHub secret) and `.env` with its passwords | `~/.config/chesspenguin/android/` | -| `secrets/chesspenguin/` | Desktop app settings and `credentials.json` (ChatGPT tokens) | `~/.config/chesspenguin/` | -| `secrets/website.env` | The website's `.env` for a local run (the production one lives on docker-prodVM) | `website/.env` | -| `test-data/` | Small databases of every kind for testing: PGN, ChessBase `.cbv`, 7z | `pgnFilesforExample/` (ignored by git) | -| `claude/memory/` | The assistant's memory of this project: the owner's rules and decisions | `~/.claude/projects//memory/` | -| `claude/transcripts/` | The past Claude Code sessions, images removed, zstd | `~/.claude/projects//` | -| `claude/settings.local.json` | Command permissions granted to the assistant in this project | `.claude/settings.local.json` | -| `emulator/` | `tap.py` (tap a UI element by text) and `shot.sh` (screenshot) for the headless emulator | used from here or copied to a scratch folder | +

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

-## On a new machine +

+ Download · + Ру��кий +

+ +![A game with its review](docs/screenshots/game.png) + +## Features + +- **PGN library** — keep several databases at hand, search and sort games, reopen where you left off. +- **ChessBase and archives** — open ChessBase databases (`.cbh`) and archives (`.cbv`), and `.zip` / + `.7z` files with PGN or ChessBase inside: games, variations, comments, symbols, arrows and the book + chapters, read-only (export to PGN by saving a game). +- **Real-world PGN** — nested variations, comments, NAGs, games from a FEN position, legacy + encodings (windows-1251, windows-1252, KOI8-R, CP866) and teaching null moves (`--`). + Source files are never modified. +- **Notation** — main line as a two-column table, comments and variations as blocks, + mouse and keyboard navigation. +- **Stockfish included** — analysis works right after installation; other UCI engines can be added. +- **Reference** — the moves played from the current position in a database of your shelf + (a big one for theory) with their statistics, how long the game stays in it, the + strongest games that reached it. +- **Search by position** — set up moves on a board and filter a database of millions of + games by the position, next to filters by player, years, rating, opening and result. +- **Engine analysis** — any UCI engine, up to 5 lines, best-move arrows, evaluation bar; + search time, threads and memory are set right in the analysis panel. +- **Game review** — evaluate the whole game in the background: evaluation graph under the board, + accuracy, inaccuracies, mistakes and blunders per player and per game phase (Lichess method), + **brilliant (!!) and great (!) moves** calibrated on chess.com's marks of famous games, better + moves in the notation and marks on the board; write it into the game as NAGs, comments and + `[%eval]` (undoable). The review always runs the same engine search, so a game gets the same + marks on every computer and phone. +- **Preparing against an opponent** — pick a player of a database and see their opening + repertoire for each colour: a tree of their moves with opening names, games, score and the + last game, a table of openings and variations with their first moves, where they leave + theory; on request the engine finds their opening mistakes, by opening, with the ones they + repeat. Every table sorts by its columns. +- **Engine lines on the board** — step through a line without touching the game, add it as a + variation with one click (undoable). +- **Editing** — enter moves and variations, promote or delete lines, undo/redo, + copy PGN/FEN, save a game to a new file. +- **Your comments** — write a comment after any move or at the start of the game, in the + main line or inside a variation, right in the notation; put symbols on moves and + positions; draw arrows and circles on the board with the right mouse button. Existing + book comments can be edited; their embedded commands and bytes are kept when untouched. +- **Your own databases** — create an empty PGN database, add any game to it (a new one, a + pasted one, a game from a ChessBase or online database), save your changes back + (Ctrl+S), edit the game data (players, event, date, result, annotator), delete games with + Undo. Any PGN file on the shelf takes games; writes happen only when you ask, by appending + to the file or rewriting it atomically. Online and ChessBase databases stay read-only; a + file in a legacy encoding gets a UTF-8 copy. +- **Paste a line** — moves or a whole PGN game from the clipboard go into the open game as a + variation, from where they part from it, with their comments and variations (Ctrl+V). +- **Learn an opening** — replay from memory the moves of both sides of a game up to a chosen + move; mistakes are counted, the runs of each line remembered. Or play on from any move + against Maia. +- **Play against the computer** — Maia, a neural network trained on human games, plays like a + human of the level you choose, mistakes included (600–2600 on her own scale); Rodent, a + strong engine with a character: styles, characters and 22 famous players from Morphy to + Kasparov (Rodent V and Rodent IV, 800–3000). Lichess + time controls (3+0 to 30+20, your own, unlimited), clocks, premoves, take-backs, draw + offers; the opponent offers to resign when lost. Played games go by themselves into the + player's database. Maia (316 MB) and Rodent (48 and 70 MB) are downloaded on request. +- **Looks** — 17 piece sets, 37 boards (flat colours and textures), 7 sound sets, + dark and light themes. +- **Online games** — download anyone's games from Lichess and Chess.com by nickname (yours, a pupil's, an opponent's; no login) into a database, both sites merged or one per site; new games arrive by themselves. +- **100 classic games** built in — from Anderssen and Morphy to Carlsen, the famous ones + with short introductions; the sample databases update with the program. +- **Android app** — databases and games in the same formats, moves on the board, your own + databases, game review with !! and !, play against Maia, learning an opening. +- **Languages** — English, Ру��кий, Français, Deutsch, Español, Italiano, Português, Oʻzbekcha, Қазақша. + +| Preparing against an opponent | Game review: report, !! and ! | +| --- | --- | +| ![Preparing against an opponent](docs/screenshots/prep-openings.jpg) | ![Game review](docs/screenshots/review.png) | +| **Engine analysis** | **Reference: what was played here** | +| ![Engine analysis](docs/screenshots/engine.jpg) | ![Reference](docs/screenshots/reference.jpg) | +| **Library with filters** | **Search by position** | +| ![Library](docs/screenshots/library.png) | ![Search by position](docs/screenshots/position-search.jpg) | +| **Play against the computer** | **Android** | +| ![Play](docs/screenshots/play.jpg) | ![Android](docs/screenshots/android.jpg) | +| **Boards, pieces and a light theme** | | +| ![Looks](docs/screenshots/looks.jpg) | | + +## Install + +Packages for every release are on the [Releases](https://github.com/vrubelroman/chessPenguin/releases) page. + +| Format | Command | +| --- | --- | +| Debian / Ubuntu | `sudo apt install ./chesspenguin__amd64.deb` | +| Fedora / openSUSE | `sudo dnf install ./chesspenguin--1.x86_64.rpm` | +| Arch Linux | `sudo pacman -U ./chesspenguin--1-x86_64.pkg.tar.zst` | +| Any distribution | `chmod +x ChessPenguin--x86_64.AppImage && ./ChessPenguin--x86_64.AppImage` | +| Flatpak | `flatpak install --user ChessPenguin--x86_64.flatpak` | +| Windows | unzip `ChessPenguin--windows-x86_64.zip`, run `ChessPenguin.exe` | +| macOS (Apple Silicon) | open `ChessPenguin--macos-arm64.dmg`, drag ChessPenguin to Applications | +| Android 12+ | open `ChessPenguin--android.apk` (Stockfish built in) or `…-android-noengine.apk` (Stockfish downloaded in the app) on the phone | + +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). + +**Stockfish** is one click away: the first time you analyse, ChessPenguin offers to download the +official Stockfish 19 (about 80 MB, checked before use, installed for your account only); the +button is also in **Settings → Engines**. A `stockfish` installed on the system is found +automatically, any other UCI engine can be added from a file. The Flatpak includes Stockfish. + +The **Android app** opens databases and games (the same formats), with the notation under the +board and Stockfish. Moves are made on the board (variations, undo); your own databases live on +the phone; game review with !! and !; play against Maia and Rodent IV; learn an opening up to a +move. The two APKs install over each other; databases and settings are kept. + +### Build from source + +Rust 1.97 or newer. On Debian/Ubuntu: `sudo apt install pkg-config libasound2-dev libxkbcommon-dev libwayland-dev`. ```sh -git clone ssh://git@192.168.8.174:2222/vrubelroman/chessbaseLinux.git ~/services/chessBaseLinux -git -C ~/services/chessBaseLinux worktree add ../chessBaseLinux-private private -~/services/chessBaseLinux-private/restore.sh ~/services/chessBaseLinux +cargo run --release -p chesspenguin -- examples/classics.pgn +./scripts/install.sh # install for the current user (~/.local) with Stockfish; --no-stockfish, --uninstall ``` -Then follow `docs/dev/handoff.md` (branch `main`): tools, Android SDK, emulator, and -the state of the work. Keeping the same path (`~/services/chessBaseLinux`) lets -`claude --resume` find the past sessions. +## Keyboard -Not here, copy it yourself: `~/.ssh` (the key that opens this Forgejo, GitHub over -port 443 and docker-prodVM) and the large reference databases (Mega 2026, 4.8 GB). +| Where | Keys | +| --- | --- | +| Library | ↑/↓ select · Enter open · Ctrl+O add database · Ctrl+Shift+N new database · Ctrl+N new game · Ctrl+F search · F2 game data · Ctrl+Shift+S add the game to another database · Delete delete the game (Ctrl+Z puts it back) | +| Game | �/→ move · ↑ end · ↓ start (also End/Home) · Shift+↑/↓ switch variation · F flip · L engine · Shift+A game analysis · Esc leave a preview, then back to the previous game or the library (unsaved edits: Esc again leaves without saving) | +| Editing | Ctrl+Z / Ctrl+Y undo/redo · Ctrl+Shift+C copy PGN · Ctrl+S save to the game's database (or add to one) · Ctrl+Shift+S add to a database · F2 game data · Ctrl+W back to library | +| Comments | Enter comment on the move (Enter done · Esc cancel · Shift+Enter paragraph) · Ctrl+1…6 the move's symbol ! ? !! ?? !? ?! · right mouse button on the board: an arrow (drag) or a circle (click); Shift red, Alt blue, Shift+Alt yellow | -To update after a change of a key or a setting: copy the file in, commit, `git push -origin private`. +## Project layout + +- `crates/chess-core` — game tree, tolerant PGN import/export. +- `crates/uci` — UCI engine process supervisor. +- `apps/desktop` — the egui application. +- `crates/mobile-api`, `androidApp` — the core for the Android app and the app itself. +- `packaging/` — desktop entry, AppStream metadata, icons, deb/rpm, AppImage and Flatpak recipes. + +The Android app is `androidApp/` (Kotlin, Jetpack Compose) over the same Rust core +(`crates/mobile-api`, UniFFI); `androidApp/scripts/release.sh` builds the two signed APKs. + +Releases are built by GitHub Actions when a `v*` tag is pushed (see `.github/workflows/release.yml`). + +## License + +GPL-3.0-or-later. Third-party piece sets, boards and sounds come from +[Lichess](https://github.com/lichess-org/lila) under their own free licenses — +see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..b4a00ef --- /dev/null +++ b/README.ru.md @@ -0,0 +1,96 @@ +# ChessPenguin + +Шахматна� база дл� Linux, Windows, macOS и Android: открывайте �борники PGN и ChessBase, читайте +аннотированные партии, вводите �вои, анализируйте их �о Stockfish, готовьте�ь к �опернику и +играйте � компьютером. + +[English](README.md) · [Скачать](https://github.com/vrubelroman/chessPenguin/releases/latest) + +![Парти� � разбором](docs/screenshots/game.png) + +Скриншоты — англий�кого интерфей�а; в программе дев�ть �зыков, ру��кий �реди них. + +## Возможно�ти + +- **Библиотека PGN** — не�колько баз под рукой, пои�к и �ортировка партий, возврат к той же �троке. +- **ChessBase и архивы** — базы ChessBase (`.cbh`) и архивы (`.cbv`), а также `.zip` / `.7z` � PGN + или ChessBase внутри: партии, варианты, комментарии, знаки, �трелки и тек�товые главы книг; только + чтение (в PGN — �охранением партии). +- **Реальные PGN** — вложенные варианты, комментарии, NAG, партии из позиции FEN, �тарые кодировки + (windows-1251, windows-1252, KOI8-R, CP866) и учебные нулевые ходы `--`. И�ходные файлы не измен�ют��. +- **�отаци�** — о�новна� лини� таблицей в две колонки, комментарии и варианты блоками, + навигаци� мышью и клавиатурой. +- **Справочник** — какие ходы делали из текущей позиции в базе � полки (дл� теории — в большой), + их �тати�тика, �колько парти� держит�� в базе, �ильнейшие партии � �той позицией. +- **Пои�к по позиции** — ра��тавьте ходы на до�ке и отфильтруйте базу на миллионы партий по + позиции, р�дом — фильтры по игроку, годам, рейтингу, дебюту и результату. +- **�нализ движком** — любой UCI-движок, до 5 линий, �трелки лучших ходов, шкала оценки; + врем�, потоки и пам�ть на�траивают�� пр�мо в панели анализа. +- **Разбор партии** — оценка в�ей партии в фоне: график под до�кой, точно�ть, неточно�ти, ошибки + и зевки каждого игрока и по �тади�м партии (методика Lichess), **бле�т�щие (!!) и + замечательные (!) ходы**, �веренные � отметками chess.com на изве�тных парти�х, лучшие ходы в + нотации и значки на до�ке; запи�ь разбора в партию знаками, комментари�ми и `[%eval]` (� + отменой). Разбор в�егда идёт на одних и тех же параметрах движка, по�тому у партии одинаковые + отметки на любом компьютере и телефоне. +- **Подготовка к �опернику** — выберите игрока базы и по�мотрите его дебютный репертуар за белых и + за чёрных: дерево его ходов � названи�ми дебютов, парти�ми, �чётом и датой по�ледней партии, + таблица дебютов и вариантов � первыми ходами, где он уходит из теории; по кнопке движок находит + его ошибки в дебютах — по дебютам и те, что он повтор�ет. В�е таблицы �ортируют�� по колонкам. +- **Линии движка на до�ке** — про�мотр линии без изменени� партии и в�тавка её вариантом (� отменой). +- **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор, + копирование PGN/FEN, �охранение партии в новый файл. +- **В�тавка варианта** — ходы или цела� парти� PGN из буфера в�тают в открытую партию вариантом + � того ме�та, где ра�ход�т��, � комментари�ми и вариантами (Ctrl+V). +- **Изучение дебюта** — повторите по пам�ти ходы обеих �торон партии до выбранного хода; ошибки + �читают��, прохождени� каждой линии запоминают��. Или продолжите партию � любого хода против Maia. +- **Игра � компьютером** — Maia, нейро�еть, обученна� на парти�х людей, играет как человек + выбранного уровн�, вме�те � ошибками (600–2600 по её �об�твенной шкале); Rodent — �ильный + движок � характером: �тили, характеры и 22 великих шахмати�та от Морфи до Ка�парова + (Rodent V и Rodent IV, 800–3000). Контроль времени как на + Lichess (от 3+0 до 30+20, �вой, бе��рочно), ча�ы, предходы, ход назад, предложение ничьей; + в проигранной позиции �оперник предлагает �дать��. Сыгранные партии �ами запи�ывают�� в базу + игрока. Maia (316 МБ) и Rodent (48 и 70 МБ) �качивают�� по кнопке. +- **Оформление** — 17 наборов фигур, 37 до�ок (цвета и тек�туры), 7 наборов звуков, тёмна� и �ветла� тема. +- **Онлайн-партии** — партии любого игрока � Lichess и Chess.com по нику (без входа) в базу; новые партии приход�т �ами. +- **100 кла��иче�ких партий** в�троены — от �ндер�ена и Морфи до Карл�ена, знаменитые — � + короткими введени�ми; в�троенные базы обновл�ют�� вме�те � программой. +- **Приложение дл� Android** — базы и партии тех же форматов, ходы на до�ке, �вои базы, разбор + партии � !! и !, игра � Maia, изучение дебюта. +- **Языки** — English, Ру��кий, Français, Deutsch, Español, Italiano, Português, Oʻzbekcha, Қазақша. + +| Подготовка к �опернику | Разбор партии: отчёт, !! и ! | +| --- | --- | +| ![Подготовка к �опернику](docs/screenshots/prep-openings.jpg) | ![Разбор партии](docs/screenshots/review.png) | +| **�нализ движком** | **Справочник: что зде�ь играли** | +| ![�нализ движком](docs/screenshots/engine.jpg) | ![Справочник](docs/screenshots/reference.jpg) | +| **Библиотека � фильтрами** | **Пои�к по позиции** | +| ![Библиотека](docs/screenshots/library.png) | ![Пои�к по позиции](docs/screenshots/position-search.jpg) | +| **Игра � компьютером** | **Android** | +| ![Игра](docs/screenshots/play.jpg) | ![Android](docs/screenshots/android.jpg) | +| **До�ки, фигуры и �ветла� тема** | | +| ![Оформление](docs/screenshots/looks.jpg) | | + +## У�тановка + +Пакеты каждого релиза — на �транице [Releases](https://github.com/vrubelroman/chessPenguin/releases): +`.deb`, `.rpm`, AppImage, Flatpak, архив дл� Windows и `.dmg` дл� macOS на Apple Silicon (приложение пока +не подпи�ано Apple: в первый раз — правый клик → «Открыть»). Команды у�тановки — в [README.md](README.md#install). + +**Stockfish — в один клик:** при первом анализе ChessPenguin предложит �качать официальный +Stockfish 19 (около 80 МБ, провер�ет�� перед запу�ком, �тавит�� только дл� ва�); та же кнопка е�ть +в **�а�тройки → Движки**. У�тановленный в �и�теме `stockfish` находит�� �ам, другие UCI-движки +добавл�ют�� из файла. Во Flatpak Stockfish уже е�ть. + +**Android 12+:** базы и партии (те же форматы), нотаци� под до�кой, Stockfish; ходы на до�ке +(варианты, отмена), �вои базы на телефоне, разбор партии � !! и !, игра � Maia и Rodent IV, +изучение дебюта. +Две �борки: `ChessPenguin-<вер�и�>-android.apk` — Stockfish уже внутри, `…-android-noengine.apk` — +Stockfish �качивает�� в приложении. Став�т�� одна поверх другой, базы и на�тройки �охран�ют��. + +Сборка из и�ходников: Rust 1.97+, затем `cargo run --release -p chesspenguin` +или `./scripts/install.sh` дл� у�тановки в `~/.local` вме�те �о Stockfish (`--no-stockfish` — без него). + +## Лицензи� + +GPL-3.0-or-later. �аборы фигур, до�ки и звуки — из [Lichess](https://github.com/lichess-org/lila) +под �об�твенными �вободными лицензи�ми, �м. [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..c0403f8 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,218 @@ +# Third-party notices + +The application is licensed under GPL-3.0-or-later (see `LICENSE`). + +## Bundled assets + +All assets below were downloaded unmodified from +https://github.com/lichess-org/lila at revision `cd2656d2787a766ba743da8da1dd3b24975e6329` +(2026-10-17). Authorship and license as stated in that revision's `COPYING.md`. + +| Path in this repo | Source path | Author | License | +| --- | --- | --- | --- | +| `apps/desktop/assets/pieces/cburnett` | `public/piece/cburnett` | Colin M.L. Burnett | GPLv2+ | +| `apps/desktop/assets/pieces/merida` | `public/piece/merida` | Armando Hernandez Marroquin | GPLv2+ | +| `apps/desktop/assets/pieces/mpchess` | `public/piece/mpchess` | Maxime Chupin | GPLv3+ | +| `apps/desktop/assets/pieces/chessnut` | `public/piece/chessnut` | Alexis Luengas | Apache-2.0 | +| `apps/desktop/assets/pieces/fantasy` | `public/piece/fantasy` | Maurizio Monge | MIT | +| `apps/desktop/assets/pieces/celtic` | `public/piece/celtic` | Maurizio Monge | MIT | +| `apps/desktop/assets/pieces/spatial` | `public/piece/spatial` | Maurizio Monge | MIT | +| `apps/desktop/assets/pieces/rhosgfx` | `public/piece/rhosgfx` | RhosGFX | CC0-1.0 | +| `apps/desktop/assets/pieces/shapes` | `public/piece/shapes` | flugsio | CC BY-SA 4.0 | +| `apps/desktop/assets/pieces/kiwen-suwi` | `public/piece/kiwen-suwi` | neverRare | CC BY 4.0 | +| `apps/desktop/assets/pieces/firi` | `public/piece/firi` | James Faure | CC BY 4.0 | +| `apps/desktop/assets/pieces/pixel` | `public/piece/pixel` | therealqtpi | AGPLv3+ | +| `apps/desktop/assets/pieces/letter` | `public/piece/letter` | usolando | AGPLv3+ | +| `apps/desktop/assets/pieces/pirouetti` | `public/piece/pirouetti` | pirouetti | AGPLv3+ | +| `apps/desktop/assets/boards/*` | `public/images/board/*` (wood, wood2–4, maple, maple2, leather, marble, blue-marble, blue2, blue3, canvas2, metal, olive, grey, green-plastic, purple-diag, pink-pyramid) | the lila authors and pirouetti | AGPLv3+ | +| `apps/desktop/assets/sounds/sfx` | `public/sound/sfx` | Enigmahack | AGPLv3+ | +| `apps/desktop/assets/sounds/piano` | `public/sound/piano` | Enigmahack | AGPLv3+ | +| `apps/desktop/assets/sounds/futuristic` | `public/sound/futuristic` | Enigmahack | AGPLv3+ | +| `apps/desktop/assets/sounds/nes` | `public/sound/nes` | Enigmahack | AGPLv3+ | +| `apps/desktop/assets/boards/horsey.jpg` | `public/images/board/horsey.jpg` | the lila authors | AGPLv3+ | + +The flat "IC" and "NCF" boards reproduce the two colours of `public/images/board/ic.png` and +`ncf-board.png`; the other flat boards are ChessPenguin's own colour pairs. + +### From PyChess + +Downloaded unmodified (files renamed `wk.svg` → `wK.svg`) from https://github.com/pychess/pychess +(`pieces/`, 2026-10-18), with the license file of each set: + +| Path in this repo | Author / origin | License | +| --- | --- | --- | +| `apps/desktop/assets/pieces/governor` | the lila authors (Lichess "governor") | AGPLv3+ | +| `apps/desktop/assets/pieces/kosal` | Kosal Sen (philatype.com) | CC BY 4.0 | +| `apps/desktop/assets/pieces/metaltops` | PyChess (`license.txt`: "published under the GPL") | GPL | + +### Kenney sounds + +`apps/desktop/assets/sounds/wood`, `glass` and `clicks` are made from Kenney's "Impact Sounds" and +"Interface Sounds" (https://kenney.nl, CC0 1.0): leading silence trimmed, loudness matched to the +other sets, re-encoded as Ogg Vorbis. + +| Set | Move | Capture | Check | Checkmate | Defeat | Success | +| --- | --- | --- | --- | --- | --- | --- | +| wood | impactWood_light_002 | impactWood_heavy_002 | impactPlank_medium_002 | impactBell_heavy_001 | minimize_008 | confirmation_004 | +| glass | impactGlass_light_001 | impactGlass_heavy_001 | glass_002 | impactBell_heavy_000 | minimize_004 | confirmation_002 | +| clicks | click_002 | drop_002 | confirmation_001 | maximize_006 | minimize_006 | confirmation_003 | + +`apps/desktop/assets/sounds/common/Wrong.ogg` (a wrong move while learning an opening, every +set) is Kenney's `error_003` of "Interface Sounds" (CC0), made the same way. +`apps/desktop/assets/sounds/common/LowTime.ogg` (the player's clock getting low, every set) is +two of Kenney's `tick_004` of "Interface Sounds" (CC0) 180 ms apart, 4 dB quieter, re-encoded +as Ogg Vorbis. + +The Defeat and Success sounds of the Lichess sets (`Defeat.ogg` and `Victory.ogg` of +`public/sound/sfx`, `piano`, `futuristic`, `nes`, by Enigmahack, AGPLv3+) were downloaded +unmodified on 2026-10-25. + +Notes: +- Lichess keeps a set's checkmate sound as a link to its check sound; ChessPenguin plays the check + sound for checkmate in the Lichess sets. +- Lichess "standard" sounds are listed as non-free in `COPYING.md` and are intentionally not used. +- Piece sets and boards under CC BY-NC-SA (e.g. california, staunty, maestro, horsey) are not bundled: non-commercial terms are incompatible with the GPL. +- AGPLv3+ sound, piece and board files are combined with this GPLv3+ program under GPLv3 §13. + +## Maia-3 (play against the computer) + +`crates/maia` computes the Maia-3 network (CSSLab, University of Toronto: Reid McIlroy-Young, +Ashton Anderson and co-authors) in Rust. Its architecture and input encoding follow the +reference implementation https://github.com/CSSLab/maia3 (AGPL-3.0), translated to Rust and +checked against it (`scripts/maia-reference.py`, `crates/maia/tests/reference.json`); as with the +AGPL sounds above, it is combined with this GPLv3+ program under GPLv3 §13. + +The network weights are **not** part of ChessPenguin. On the user's request the program +downloads the authors' own file `maia3-5m.pt` from https://huggingface.co/UofTCSSLab/Maia3-5M +(revision and SHA-256 pinned in `apps/desktop/src/maia_download.rs`) into the user's data +directory. The weights' licence is not stated by the authors. + +## Rodent V (an opponent with a style) + +**Rodent V 1.2** (Naman Thanki and Paweł Koziol, based on Sungorus by Pablo Vázquez) is not +part of ChessPenguin. On the user's request the program downloads the authors' unmodified +release archive `release-1-2.zip` from https://github.com/nescitus/Rodent-V/releases/tag/Rodent_v_1.2 +(SHA-256 pinned in `apps/desktop/src/rodent_download.rs`) into the user's data directory and +takes from it the engine for the platform and its `personalities/`, `nets/` and `books/`. It +runs as a separate program through UCI. + +- License: GNU General Public License version 3 (https://github.com/nescitus/Rodent-V/blob/main/LICENSE); + source: https://github.com/nescitus/Rodent-V. +- The opening books of the release come with it as the authors publish them. + +## Rodent IV (characters and famous players) + +**Rodent IV 0.33** (Paweł Koziol and Bernhard C. Maerz, based on Sungorus by Pablo Vázquez) is +not part of ChessPenguin. Its authors publish no builds for Linux and Windows, so the engine +is built from their sources at commit `e8d84c8c8c189a1cf4eb27c578fc573af3b916d2` of +https://github.com/nescitus/rodent-iv with one fix of ours, `packaging/rodent-iv/home-dir.patch` +(on Linux the engine now and then took a wrong home folder and played without its +personality), by `.github/workflows/rodent-iv.yml`, and published as the release +`rodent-iv-0.33` of this repository. On the user's request the program downloads +that build (SHA-256 pinned in `apps/desktop/src/rodent4_download.rs`) and the engine's +personalities and opening books from the authors' repository at the same commit (each file's +SHA-256 pinned in `crates/play/src/rodent4_files.rs`) into the user's data directory. It runs +as a separate program through UCI. + +On Android the engine is built from the same commit with the same fix and two more, +`packaging/rodent-iv/think-thread.patch` (the search thread read its position from a dead +stack frame; clang builds searched garbage) and `packaging/rodent-iv/android.patch` (bionic has +no `wordexp`), by `androidApp/scripts/rodent4.sh`; the executable and the personalities are in +the APK (both builds), with the license, the authors' README and the credits of the books +(`licenses/rodent-iv` among the APK's assets). The opening books the characters use are +downloaded on the user's request from the authors' repository at the same commit, each file +checked against its SHA-256. + +- License: GNU General Public License version 3 (https://github.com/nescitus/rodent-iv/blob/master/LICENSE); + source: the commit above. +- The opening books come as the authors publish them, with their own credits (`#readme.txt` + in each folder of `books/`). +- Three personalities (Strangler, Spassky, Deborah) name their book by a path not in the + authors' files; the program puts a copy of the book under that name (on Android the book is + saved under that name). + +## Stockfish (engine) + +**Stockfish 19** (tag `sf_19`) is the unmodified official "universal" build from +https://github.com/official-stockfish/Stockfish/releases/tag/sf_19. The Flatpak bundles it; +the other packages do not: on request the program downloads the same official archive for the +platform into the user's data directory and checks its SHA-256 (pinned in +`apps/desktop/src/engine_download.rs` and `packaging/stockfish.sh`) before using it. + +- License: GNU General Public License version 3 (`Copying.txt`, installed as + `stockfish-Copying.txt` next to this application's license); authors: the Stockfish + developers (`AUTHORS`, installed alongside). +- Source code: https://github.com/official-stockfish/Stockfish/tree/sf_19 ; every GitHub release of + ChessPenguin also carries `stockfish-sf_19-source.tar.gz`. The neural networks embedded in the + binary are published by the Stockfish project (see its `README.md` and `src/evaluate.h`). +- Stockfish's networks are trained on data provided by the Leela Chess Zero project under the + Open Database License (ODbL). +- ChessPenguin runs Stockfish as a separate process over the UCI protocol. + +### Stockfish.js (the web version) + +The web version (`/app/` on the site) uses **Stockfish.js 19.0.1** by Nathan Rugg and Chess.com +(https://github.com/nmrugg/stockfish.js), its single-threaded build `stockfish-19-single.js` + +`stockfish-19-single.wasm`, unmodified, from the npm package `stockfish@19.0.1` +(https://registry.npmjs.org/stockfish/-/stockfish-19.0.1.tgz, integrity +`sha512-bTwsO4e9HAwPBKls1+szcfibmaWRNzTF20rQE/XPdB3LOSoT6XTZDr1zYwriwSRRFT5MkvqrglPmJrKEVXGnyQ==`, +checked by `apps/web/build.sh`). It is Stockfish 19 compiled to WebAssembly with the network +`nn-1a298aa575a0` built in. Our site serves the files beside the program (`/app/engine/`, with the +package's `Copying.txt`); the browser downloads the `.wasm` only when the user agrees and keeps it +in its Cache Storage; it runs in Web Workers over UCI. + +- License: GNU General Public License version 3 (the engine; `Copying.txt`); the JavaScript + wrapper as published in the package. +- Source code: https://github.com/nmrugg/stockfish.js/tree/v19.0.1 (the build scripts and the + emscripten glue) and the Stockfish source above. + +## Opening names (preparing against an opponent) + +`crates/openings/data/a.tsv` … `e.tsv` are the five files of the Lichess opening table +https://github.com/lichess-org/chess-openings (the lichess.org contributors), downloaded +unmodified at revision `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27) on 2026-10-28 and +embedded in the program. Its README: "As a collection of facts, this data set is in the public +domain … released under the CC0 Public Domain Dedication" (CC0 1.0). SHA-256 of the files: + +| File | SHA-256 | +| --- | --- | +| `a.tsv` | `3282e4c9155289a29224f9a85fba0decb46efa35c2fa5e39662d2ac48fb0f793` | +| `b.tsv` | `4bf2269a8e7571a00a7b346bae4fa86a241a6e7e86beab01783c81acb1622b63` | +| `c.tsv` | `45e843c7b7e79a0d04d5bda879c9bd23f5a10974488bd8615e4f4c5d0749986f` | +| `d.tsv` | `1cf4057a8aece94f27bb3f278ad410ee2844831a642364eeceaafa091dbcceda` | +| `e.tsv` | `48c6f6645b031a5937c8386839debab0e2e48837251687ba1afb6369677f8546` | + +## ChessBase formats + +- `crates/chess-import/src/cbv.rs` reads ChessBase archives following uncbv + (https://github.com/antoyo/uncbv, Antoni Boucher, GPL-3.0-or-later); the code is a rewrite. +- The ChessBase database layout (`crates/chess-import/src/chessbase/`) follows the public format + description in https://github.com/Yarin78/morphy (`format/v1`), used as a source of facts; no code + is taken from that project. +- ChessBase is a trademark of ChessBase GmbH; ChessPenguin is not affiliated with it. + +## Rust crates + +Dependency licenses are recorded by `Cargo.lock`; key ones: shakmaty / pgn-reader (GPL-3.0-or-later), +egui / eframe (MIT OR Apache-2.0), zip (MIT), sevenz-rust2 (Apache-2.0), sysinfo (MIT), +sys-locale (MIT OR Apache-2.0), whatlang (MIT, detecting the language of comments). + +egui's bundled fonts are part of the program: Ubuntu Light (Ubuntu Font Licence 1.0), Hack +(MIT and Bitstream Vera licence), Noto Emoji (SIL OFL 1.1), emoji-icon-font (MIT). +Three evaluation signs (⩲ ⩱ ⌓) come from Noto Sans Math (Copyright 2022 Google LLC, SIL OFL 1.1), +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 +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`. diff --git a/androidApp/.gitignore b/androidApp/.gitignore new file mode 100644 index 0000000..5772074 --- /dev/null +++ b/androidApp/.gitignore @@ -0,0 +1,18 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +/dist +/dist-rustore +.env diff --git a/androidApp/app/.gitignore b/androidApp/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/androidApp/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/androidApp/app/build.gradle.kts b/androidApp/app/build.gradle.kts new file mode 100644 index 0000000..81b9fde --- /dev/null +++ b/androidApp/app/build.gradle.kts @@ -0,0 +1,275 @@ +// ChessPenguin for Android (docs/design/android-ui.md, docs/research/android-stack.md): +// the interface in Kotlin + Jetpack Compose, the reading of databases in the Rust core +// of the desktop app (crates/mobile-api), bound with UniFFI. +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.compose.compiler) + alias(libs.plugins.kotlin.serialization) +} + +/// The repository root: the Rust workspace, the sample games, the piece sets. +val repo: File = rootDir.parentFile +val cargoOut = layout.buildDirectory.dir("rust/ndk") +val rustLibs = layout.buildDirectory.dir("rust/jniLibs") +val bindings = layout.buildDirectory.dir("generated/uniffi") +val bundled = layout.buildDirectory.dir("generated/assets") +val ndkHome = System.getenv("ANDROID_NDK_HOME") + ?: "${System.getenv("ANDROID_HOME") ?: "${System.getProperty("user.home")}/Android/Sdk"}/ndk/30.0.16248370" + +/// The version of the workspace (Cargo.toml): the phone and the desktop are one release. +val version: String = Regex("""(?m)^version = "([^"]+)"""") + .find(File(repo, "Cargo.toml").readText())!!.groupValues[1] +val versionNumber: Int = version.split('.').map { it.takeWhile(Char::isDigit).toInt() } + .let { (major, minor, patch) -> major * 10000 + minor * 100 + patch } + +/// The core for the phones (arm64) and the emulator (x86_64). +val cargoBuild = tasks.register("cargoBuild") { + workingDir = repo + environment("ANDROID_NDK_HOME", ndkHome) + commandLine( + "cargo", "ndk", "-t", "arm64-v8a", "-t", "x86_64", "--platform", "31", + "-o", cargoOut.get().asFile.path, "build", "--release", "-p", "mobile-api", + ) + inputs.dir(File(repo, "crates")) + inputs.file(File(repo, "Cargo.lock")) + outputs.dir(cargoOut) +} + +/// Only our library: cargo-ndk also copies the cdylibs of dependencies (sevenz-rust2), +/// which are linked into ours already. +val rustJniLibs = tasks.register("rustJniLibs") { + dependsOn(cargoBuild) + from(cargoOut) { include("*/libmobile_api.so") } + into(rustLibs) +} + +/// The Kotlin side of the bridge, generated from the built library. +val uniffiBindings = tasks.register("uniffiBindings") { + dependsOn(rustJniLibs) + workingDir = repo + commandLine( + "cargo", "run", "-q", "-p", "mobile-api", "--features", "bindgen", "--bin", "uniffi-bindgen", + "--", "generate", "--no-format", "--language", "kotlin", + "--library", rustLibs.get().file("x86_64/libmobile_api.so").asFile.path, + "--out-dir", bindings.get().asFile.path, + ) + inputs.dir(rustLibs) + inputs.file(repo.resolve("crates/mobile-api/uniffi.toml")) + outputs.dir(bindings) +} + +/// Stockfish for Android (scripts/stockfish.sh): the executable for both builds, its +/// network only inside the "full" one. +val stockfishOut = layout.buildDirectory.dir("stockfish") +val stockfish = tasks.register("stockfish") { + environment("ANDROID_NDK_HOME", ndkHome) + commandLine(File(rootDir, "scripts/stockfish.sh").path, stockfishOut.get().asFile.path) + inputs.file(File(rootDir, "scripts/stockfish.sh")) + outputs.dir(stockfishOut) +} + +/// Rodent IV for Android (scripts/rodent4.sh, docs/design/android-rodent.md): the executable +/// and its personalities in both builds; its opening books are downloaded on request. +val rodent4Out = layout.buildDirectory.dir("rodent4") +val rodent4 = tasks.register("rodent4") { + environment("ANDROID_NDK_HOME", ndkHome) + commandLine(File(rootDir, "scripts/rodent4.sh").path, rodent4Out.get().asFile.path) + inputs.file(File(rootDir, "scripts/rodent4.sh")) + inputs.dir(File(repo, "packaging/rodent-iv")) + outputs.dir(rodent4Out) +} + +/// The sample games, the piece sets, the board images and sounds of the desktop app, as +/// app assets. +val bundleAssets = tasks.register("bundleAssets") { + from(File(repo, "examples")) { + include("*.pgn") + into("examples") + } + from(File(repo, "apps/desktop/assets/pieces")) { + include("*/*.svg") + into("pieces") + } + from(File(repo, "apps/desktop/assets/boards")) { + include("*.jpg", "*.png") + into("boards") + } + // One set of sounds (the desktop's «SFX») and the trainer's wrong move (§33). + from(File(repo, "apps/desktop/assets/sounds/sfx")) { + include("*.ogg") + into("sounds") + } + from(File(repo, "apps/desktop/assets/sounds/common")) { + include("Wrong.ogg") + into("sounds") + } + from(stockfishOut.map { it.dir("source") }) { + into("licenses/stockfish") + } + // Rodent IV's personalities, copied into its home folder on the phone (RodentFiles). + from(rodent4Out.map { it.dir("home/personalities") }) { + into("rodent4/personalities") + } + from(rodent4Out.map { it.dir("source") }) { + into("licenses/rodent-iv") + } + dependsOn(stockfish, rodent4) + into(bundled) +} + +android { + namespace = "io.github.vrubelroman.chesspenguin" + compileSdk = 37 + flavorDimensions += "engine" + productFlavors { + // «Stockfish уже внутри»: the network is in the APK, nothing to download. + create("full") { + dimension = "engine" + buildConfigField("boolean", "NET_BUILT_IN", "true") + } + // «Stockfish �качивает�� в приложении»: the network is downloaded on request. + create("light") { + dimension = "engine" + buildConfigField("boolean", "NET_BUILT_IN", "false") + } + } + + defaultConfig { + applicationId = "io.github.vrubelroman.chesspenguin" + minSdk = 31 + targetSdk = 36 + versionCode = versionNumber + versionName = version + ndk { + abiFilters += listOf("arm64-v8a", "x86_64") + } + // The network of Stockfish 19 (scripts/stockfish.sh), checked after download. + buildConfigField("String", "NET_NAME", "\"nn-1a298aa575a0.nnue\"") + buildConfigField("String", "NET_SHA256", "\"1a298aa575a085434d29027978dc36867fe9c5bcea9376654b7a8eba1e52dfc2\"") + 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( + "String", + "NET_URL", + "\"https://github.com/official-stockfish/networks/raw/master/nn-1a298aa575a0.nnue\"", + ) + } + + // The release key is never in the repository: CP_KEYSTORE, CP_KEYSTORE_PASSWORD, + // CP_KEY_ALIAS, CP_KEY_PASSWORD come from the environment (scripts/release.sh, CI). + val keystore = System.getenv("CP_KEYSTORE") + signingConfigs { + if (keystore != null) { + create("release") { + storeFile = File(keystore) + storePassword = System.getenv("CP_KEYSTORE_PASSWORD") + keyAlias = System.getenv("CP_KEY_ALIAS") + keyPassword = System.getenv("CP_KEY_PASSWORD") + } + } + } + + buildTypes { + // Where the app asks for a newer release: GitHub ("" = the core's address). A debug + // build may ask a test server instead (CP_UPDATE_API at build time, e.g. + // http://10.0.2.2:8765/latest.json for a server on the emulator's host). + debug { + buildConfigField("String", "UPDATE_API", "\"${System.getenv("CP_UPDATE_API") ?: ""}\"") + } + release { + buildConfigField("String", "UPDATE_API", "\"\"") + isMinifyEnabled = true + isShrinkResources = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + 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. + androidResources { + localeFilters += listOf("en", "ru", "de", "fr", "es", "it", "pt", "uz", "kk") + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + buildFeatures { + compose = true + aidl = false + buildConfig = true + shaders = false + } + sourceSets { + getByName("main") { + jniLibs.directories.add(rustLibs.get().asFile.path) + jniLibs.directories.add(stockfishOut.get().dir("jniLibs").asFile.path) + jniLibs.directories.add(rodent4Out.get().dir("jniLibs").asFile.path) + kotlin.directories.add(bindings.get().asFile.path) + assets.directories.add(bundled.get().asFile.path) + } + getByName("full") { + assets.directories.add(stockfishOut.get().dir("net").asFile.path) + } + } + packaging { + // Unpacked at install: Stockfish and Rodent IV run from nativeLibraryDir as their + // own processes. + jniLibs { + useLegacyPackaging = true + } + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } +} + +kotlin { + jvmToolchain(21) +} + +tasks.named("preBuild") { + 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 { + val composeBom = platform(libs.androidx.compose.bom) + implementation(composeBom) + + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.lifecycle.viewmodel.compose) + + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons) + debugImplementation(libs.androidx.compose.ui.tooling) + + implementation(libs.androidx.navigation3.ui) + implementation(libs.androidx.navigation3.runtime) + implementation(libs.androidx.lifecycle.viewmodel.navigation3) + implementation(libs.androidx.datastore.preferences) + implementation(libs.kotlinx.serialization.json) + + // The bridge to the Rust core (UniFFI uses JNA), and the SVG pieces. + implementation("${libs.jna.get()}@aar") + implementation(libs.androidsvg) + + testImplementation(libs.junit) +} diff --git a/androidApp/app/proguard-rules.pro b/androidApp/app/proguard-rules.pro new file mode 100644 index 0000000..e533f6f --- /dev/null +++ b/androidApp/app/proguard-rules.pro @@ -0,0 +1,6 @@ +# The Rust core is reached through JNA (UniFFI): JNA finds the native functions and +# the structures by reflection, so neither may be renamed or removed. +-keep class com.sun.jna.** { *; } +-keep class * implements com.sun.jna.** { *; } +-keep class uniffi.mobile_api.** { *; } +-dontwarn java.awt.** diff --git a/androidApp/app/src/debug/AndroidManifest.xml b/androidApp/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..68f484a --- /dev/null +++ b/androidApp/app/src/debug/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/androidApp/app/src/debug/res/xml/network_security_config.xml b/androidApp/app/src/debug/res/xml/network_security_config.xml new file mode 100644 index 0000000..ed3e1a4 --- /dev/null +++ b/androidApp/app/src/debug/res/xml/network_security_config.xml @@ -0,0 +1,8 @@ + + + + + 10.0.2.2 + + diff --git a/androidApp/app/src/main/AndroidManifest.xml b/androidApp/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9f5c421 --- /dev/null +++ b/androidApp/app/src/main/AndroidManifest.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt new file mode 100644 index 0000000..df5aa92 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt @@ -0,0 +1,218 @@ +package io.github.vrubelroman.chesspenguin + +import android.app.Application +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import android.net.Uri +import android.provider.OpenableColumns +import io.github.vrubelroman.chesspenguin.data.AppUpdates +import io.github.vrubelroman.chesspenguin.data.CLIPBOARD_PREFERENCES +import io.github.vrubelroman.chesspenguin.data.ClipboardOffer +import io.github.vrubelroman.chesspenguin.data.ClipboardPgn +import io.github.vrubelroman.chesspenguin.data.DbEntry +import io.github.vrubelroman.chesspenguin.data.EngineFiles +import io.github.vrubelroman.chesspenguin.data.MaiaFiles +import io.github.vrubelroman.chesspenguin.data.MaiaGames +import io.github.vrubelroman.chesspenguin.data.PlayerGames +import io.github.vrubelroman.chesspenguin.data.RodentFiles +import io.github.vrubelroman.chesspenguin.data.Sounds +import io.github.vrubelroman.chesspenguin.data.Library +import io.github.vrubelroman.chesspenguin.data.OnlineDownloads +import io.github.vrubelroman.chesspenguin.data.Settings +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.io.FileNotFoundException +import java.util.UUID + +/// The app's databases, settings and engine files live as long as the process. +class ChessPenguinApp : Application() { + /// Work that outlives a screen (the download of the engine). + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + val library by lazy { Library(this) } + val settings by lazy { Settings(this) } + val engineFiles by lazy { EngineFiles(this, scope) } + /// Maia's weights, downloaded on request (android-play.md §31). + val maiaFiles by lazy { MaiaFiles(this, scope) } + /// Rodent IV's home and its book pack (android-rodent.md). + val rodentFiles by lazy { RodentFiles(this, scope) } + /// The game against the computer in hand (android-play.md §31.7). + val maiaGames by lazy { MaiaGames(this) } + /// The players' databases: games against Maia written by themselves (player-games.md). + val playerGames by lazy { PlayerGames(this, library) } + /// The sounds of moves and of the end of a game (android-play.md §33). + val sounds by lazy { Sounds(this, settings) } + /// Games from Lichess and Chess.com being downloaded (android-ui.md §23). + val downloads by lazy { OnlineDownloads(library, scope) } + /// The app's own updates (android-ui.md §25). + val updates by lazy { AppUpdates(this, scope, engineFiles) } + val clipboardPgn by lazy { + ClipboardPgn( + library, + scope, + getSharedPreferences(CLIPBOARD_PREFERENCES, MODE_PRIVATE), + latestIncoming.lock, + ) { + if (latestIncoming.invalidateClipboard() && incoming.value == Incoming.Opening) { + incoming.value = null + } + } + } + + override fun onCreate() { + super.onCreate() + // The opening trainer's runs (android-play.md §32.3). + uniffi.mobile_api.trainerSetFile(java.io.File(filesDir, "training.json").path) + // Loaded now: the first move's sound is ready when it is played. + sounds + } + + /// The games shown on the list of each database (after a search), for paging + /// games from the game screen: database id → game numbers. + val shown = HashMap>() + /// The game last opened from a database's list: the search it was found with and its + /// place there (android-lists.md §3.6; the list marks it and shows it again). + val lastOpened = HashMap>() + + /// Changes each time the app goes to the background, and in every new process: the + /// engine button of a game holds only for the visit it was pressed in (§8.3). + var visit by mutableStateOf(UUID.randomUUID().toString()) + private set + + fun leftApp() { + visit = UUID.randomUUID().toString() + } + + /// A file opened from another app: being copied in, on the list, or why not. + val incoming = MutableStateFlow(null) + + /// One copy at a time, in the order the files came; only the last one opened is shown. + private val copying = Mutex() + private val latestIncoming = LatestIncoming() + + /// Copies a file another app gave (it gives access only for a while) and puts it on + /// the list; `incoming` tells the screens how it went. + fun receive(uri: Uri) { + val request = latestIncoming.withLock { + latestIncoming.next(IncomingOrigin.Uri).also { incoming.value = Incoming.Opening } + } + scope.launch { + val result = copying.withLock { + try { + val name = displayName(uri) ?: "games.pgn" + val ext = name.substringAfterLast('.', "").lowercase() + // One file of a ChessBase database: the others are not given with it. + if (ext in CHESSBASE_PARTS) throw ChessBasePart() + // A name with no known ending (some apps give "file_123") is read as PGN. + val fileName = if (ext in setOf("pgn", "zip", "7z", "cbv")) name else "$name.pgn" + val input = contentResolver.openInputStream(uri) ?: throw FileNotFoundException(uri.toString()) + Incoming.Opened(input.use { library.addCopy(fileName, it) { name.substringBeforeLast('.') } }) + } catch (e: Exception) { + Incoming.Failed(e) + } + } + latestIncoming.publish(request) { incoming.value = result } + } + } + + fun openClipboard(offer: ClipboardOffer, name: String) { + val (accepted, request) = latestIncoming.withLock { + val accepted = clipboardPgn.accept(offer) ?: return + val request = latestIncoming.next(IncomingOrigin.Clipboard) + incoming.value = Incoming.Opening + accepted to request + } + scope.launch { + val result = copying.withLock { + try { + Incoming.Pasted(library.addCopy("clipboard.pgn", accepted.bytes.inputStream()) { name }) + } catch (e: Exception) { + Incoming.Failed(e) + } + } + latestIncoming.withLock { + if (!latestIncoming.isLatest(request)) { + clipboardPgn.finish(accepted, false) + return@withLock + } + if (!clipboardPgn.canPublish(accepted)) { + if (incoming.value == Incoming.Opening) incoming.value = null + return@withLock + } + when (result) { + is Incoming.Pasted -> { + clipboardPgn.finish(accepted, true) + incoming.value = result + } + is Incoming.Failed -> { + clipboardPgn.finish(accepted, false) + incoming.value = result + } + else -> incoming.value = null + } + latestIncoming.clear(request) + } + } + } + + private fun displayName(uri: Uri): String? = runCatching { + contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } + }.getOrNull() +} + +/// A `.cbh` (or another part) of a ChessBase database, opened alone. +class ChessBasePart : Exception() + +private val CHESSBASE_PARTS = setOf("cbh", "cbg", "cba", "cbp", "cbs", "cbj", "cbt", "cbc", "cbe", "cbm") + +internal enum class IncomingOrigin { + Uri, + Clipboard, +} + +internal class LatestIncoming { + internal val lock = Any() + private var generation = 0L + private var origin: IncomingOrigin? = null + + fun next(origin: IncomingOrigin = IncomingOrigin.Uri): Long = synchronized(lock) { + this.origin = origin + ++generation + } + + fun isLatest(request: Long): Boolean = synchronized(lock) { request == generation } + + fun invalidateClipboard(): Boolean = synchronized(lock) { + if (origin != IncomingOrigin.Clipboard) return false + origin = null + generation += 1 + true + } + + fun clear(request: Long) = synchronized(lock) { + if (isLatest(request)) origin = null + } + + fun publish(request: Long, action: () -> Unit): Boolean = synchronized(lock) { + if (!isLatest(request)) return false + action() + clear(request) + true + } + + inline fun withLock(action: () -> T): T = synchronized(lock, action) +} + +sealed interface Incoming { + data object Opening : Incoming + data class Opened(val entry: DbEntry) : Incoming + data class Pasted(val entry: DbEntry) : Incoming + data class Failed(val error: Throwable) : Incoming +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt new file mode 100644 index 0000000..b130968 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt @@ -0,0 +1,139 @@ +package io.github.vrubelroman.chesspenguin + +import android.content.ClipboardManager +import android.content.Context +import android.app.UiModeManager +import android.content.Intent +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import kotlinx.coroutines.launch +import android.net.Uri +import android.os.Bundle +import android.graphics.Color +import androidx.activity.ComponentActivity +import androidx.activity.SystemBarStyle +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.ui.Modifier +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import io.github.vrubelroman.chesspenguin.data.Language +import io.github.vrubelroman.chesspenguin.data.Theme +import io.github.vrubelroman.chesspenguin.theme.ChessPenguinTheme + +/// The scrims behind three-button navigation, as `enableEdgeToEdge` has them by default. +private val LIGHT_SCRIM = Color.argb(0xe6, 0xFF, 0xFF, 0xFF) +private val DARK_SCRIM = Color.argb(0x80, 0x1b, 0x1b, 0x1b) + +class MainActivity : ComponentActivity() { + override fun attachBaseContext(base: Context) { + super.attachBaseContext(Language.wrap(base)) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + // Not again when the activity is made anew (turned): it was taken the first time. + if (savedInstanceState == null) receive(intent) + val app = application as ChessPenguinApp + val settings = app.settings + // Android's question «Update this app?» is put on the screen only while the app is + // on it (the installer may answer while the user is elsewhere). + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.RESUMED) { + app.updates.confirm.collect { confirm -> + if (confirm != null) { + app.updates.confirmShown() + startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + } + } + } + setContent { + val prefs by settings.prefs.collectAsState() + val dark = when (prefs.theme) { + Theme.System -> isSystemInDarkTheme() + Theme.Light -> false + 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 + // icons over a dark app even when the phone itself is light, and back. + DisposableEffect(dark) { + enableEdgeToEdge( + statusBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT) { dark }, + navigationBarStyle = SystemBarStyle.auto(LIGHT_SCRIM, DARK_SCRIM) { dark }, + ) + onDispose {} + } + ChessPenguinTheme(darkTheme = dark) { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { MainNavigation() } + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + receive(intent) + } + + /// A file given by another app: "Open with" (VIEW) or "Share" (SEND). + private fun receive(intent: Intent?) { + // Opened again from Recents: the task keeps the intent of the file it was made for. + if (intent == null || intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0) return + val uri = when (intent.action) { + Intent.ACTION_VIEW -> intent.data + Intent.ACTION_SEND -> androidx.core.content.IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java) + else -> null + } ?: return + (application as ChessPenguinApp).receive(uri) + } + + override fun onStart() { + super.onStart() + val updates = (application as ChessPenguinApp).updates + updates.foreground = true + updates.checkIfDue() + // The downloaded databases get their new games (at most every ten minutes). + (application as ChessPenguinApp).downloads.updateAllQuietly() + } + + override fun onResume() { + super.onResume() + val app = application as ChessPenguinApp + app.updates.onResume() + app.clipboardPgn.check(clipboardText(this)) + } + + override fun onStop() { + super.onStop() + (application as ChessPenguinApp).updates.foreground = false + // Gone to the background or closed, not turned. + if (!isChangingConfigurations) (application as ChessPenguinApp).leftApp() + } +} + +fun clipboardText(context: Context): String? = context.getSystemService(ClipboardManager::class.java) + ?.primaryClip + ?.takeIf { it.itemCount > 0 } + ?.getItemAt(0) + ?.text + ?.toString() diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt new file mode 100644 index 0000000..9ca888e --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt @@ -0,0 +1,273 @@ +package io.github.vrubelroman.chesspenguin + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.compose.ui.semantics.semantics +import io.github.vrubelroman.chesspenguin.data.DbEntry +import io.github.vrubelroman.chesspenguin.data.NoGames +import uniffi.mobile_api.ApiException +import java.io.FileNotFoundException +import io.github.vrubelroman.chesspenguin.ui.app +import io.github.vrubelroman.chesspenguin.ui.openProblem +import io.github.vrubelroman.chesspenguin.ui.UpdateSheet +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator +import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.ui.NavDisplay +import io.github.vrubelroman.chesspenguin.ui.AboutScreen +import io.github.vrubelroman.chesspenguin.ui.BoardStyleScreen +import io.github.vrubelroman.chesspenguin.ui.DatabasesScreen +import io.github.vrubelroman.chesspenguin.ui.SettingsScreen +import io.github.vrubelroman.chesspenguin.ui.GameScreen +import io.github.vrubelroman.chesspenguin.ui.NEW_GAME +import io.github.vrubelroman.chesspenguin.ui.PLAY_GAME +import io.github.vrubelroman.chesspenguin.ui.GamesScreen +import io.github.vrubelroman.chesspenguin.ui.OnlineScreen +import io.github.vrubelroman.chesspenguin.ui.PlayersScreen +import io.github.vrubelroman.chesspenguin.ui.PrepScreen +import io.github.vrubelroman.chesspenguin.ui.PrepStart +import kotlinx.serialization.Serializable + +@Serializable data object Databases : NavKey + +@Serializable data class Games(val db: String) : NavKey + +@Serializable data class Players(val db: String) : NavKey + +@Serializable data class Preparation(val request: PrepStart) : NavKey + +/// The game at `place` on the list of games found by `query` in the database (kept, so +/// the same game comes back after Android restarts the app). +@Serializable data class GameAt(val db: String, val place: Int, val query: String = "") : NavKey + +/// A new game from the start position (android-play.md §30.4). +@Serializable data object NewGameKey : NavKey + +/// The game against Maia in hand (android-play.md §31). +@Serializable data object PlayKey : NavKey + +@Serializable data object SettingsKey : NavKey + +@Serializable data object AboutKey : NavKey + +@Serializable data object BoardStyleKey : NavKey + +@Serializable data object OnlineKey : NavKey + +@Composable +fun MainNavigation() { + val backStack = rememberNavBackStack(Databases) + // A database just added from outside (the clipboard, another app): its list, or its + // only game at once, over the list of databases. + fun show(entry: DbEntry) { + while (backStack.size > 1) backStack.removeAt(backStack.lastIndex) + backStack.add(Games(entry.id)) + if (entry.games == 1) backStack.add(GameAt(entry.id, 0)) + } + fun showPasted(entry: DbEntry) { + while (backStack.size > 1) backStack.removeAt(backStack.lastIndex) + backStack.add(Games(entry.id)) + backStack.add(GameAt(entry.id, 0)) + } + val app = app() + val incoming by app.incoming.collectAsState() + LaunchedEffect(incoming) { + when (val i = incoming) { + is Incoming.Opened -> { + if (app.incoming.compareAndSet(i, null)) show(i.entry) + } + is Incoming.Pasted -> { + if (app.incoming.compareAndSet(i, null)) { + resetPastedView(app.shown, app.lastOpened, i.entry.id) + showPasted(i.entry) + } + } + else -> {} + } + } + // The app's update, over any screen (android-ui.md §25.3). + val updateSheet by app.updates.sheet.collectAsState() + if (updateSheet) UpdateSheet() + val clipboardUnblocked = incoming == null && !updateSheet + val context = LocalContext.current + LaunchedEffect(clipboardUnblocked) { + if (clipboardUnblocked) app.clipboardPgn.check(clipboardText(context)) + } + val clipboardOffer by app.clipboardPgn.offer.collectAsState() + if (clipboardUnblocked) { + clipboardOffer?.let { offer -> + val clipboardName = stringResource(R.string.clipboard_database_name) + AlertDialog( + onDismissRequest = { app.clipboardPgn.dismiss(offer) }, + title = { Text(pluralStringResource(R.plurals.clipboard_open_title, offer.games, offer.games)) }, + text = { + Text( + if (offer.games == 1) { + stringResource(R.string.clipboard_open_one) + } else { + stringResource( + R.string.clipboard_open_many, + pluralStringResource(R.plurals.games_count, offer.games, offer.games), + ) + }, + ) + }, + confirmButton = { + TextButton(onClick = { app.openClipboard(offer, clipboardName) }) { + Text(stringResource(R.string.clipboard_open)) + } + }, + dismissButton = { + TextButton(onClick = { app.clipboardPgn.dismiss(offer) }) { + Text(stringResource(R.string.cancel)) + } + }, + ) + } + } + when (val i = incoming) { + Incoming.Opening -> Dialog(onDismissRequest = {}, properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)) { + Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceContainerHigh) { + Row(Modifier.padding(24.dp).semantics(mergeDescendants = true) {}, verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 3.dp) + Spacer(Modifier.size(16.dp)) + Text(stringResource(R.string.opening_file), style = MaterialTheme.typography.bodyLarge) + } + } + } + is Incoming.Failed -> AlertDialog( + onDismissRequest = { app.incoming.compareAndSet(i, null) }, + title = { Text(stringResource(R.string.file_failed)) }, + text = { Text(incomingProblem(i.error)) }, + confirmButton = { TextButton(onClick = { app.incoming.compareAndSet(i, null) }) { Text(stringResource(R.string.ok)) } }, + ) + else -> {} + } + NavDisplay( + backStack = backStack, + onBack = { backStack.removeLastOrNull() }, + // Each screen keeps its own saved state and view models: they go with the screen + // when it leaves the stack (the search of the online screen must not outlive it). + entryDecorators = listOf( + rememberSaveableStateHolderNavEntryDecorator(), + rememberViewModelStoreNavEntryDecorator(), + ), + entryProvider = entryProvider { + entry { + DatabasesScreen( + onOpen = { backStack.add(Games(it)) }, + onAdded = ::show, + onSettings = { backStack.add(SettingsKey) }, + onOnline = { backStack.add(OnlineKey) }, + onNewGame = { backStack.add(NewGameKey) }, + onPlay = { backStack.add(PlayKey) }, + ) + } + entry { + GameScreen(NEW_GAME, 0, "", onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.add(PlayKey) }) + } + entry { + GameScreen(PLAY_GAME, 0, "", onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { + backStack.removeLastOrNull() + backStack.add(PlayKey) + }, onOpenDatabase = { id -> backStack.add(Games(id)) }) + } + entry { key -> + GamesScreen( + key.db, + onBack = { backStack.removeLastOrNull() }, + onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) }, + onPlayers = { backStack.add(Players(key.db)) }, + ) + } + entry { key -> + PlayersScreen( + key.db, + onBack = { backStack.removeLastOrNull() }, + onPrepare = { player, white -> + backStack.add(Preparation(PrepStart(db = key.db, player = player.name, white = white))) + }, + ) + } + entry { key -> + PrepScreen(key.request, onBack = { backStack.removeLastOrNull() }) + } + entry { key -> + GameScreen( + key.db, + key.place, + key.query, + onBack = { backStack.removeLastOrNull() }, + onSettings = { backStack.add(SettingsKey) }, + onPlayGame = { backStack.add(PlayKey) }, + onPrepare = { backStack.add(Preparation(it)) }, + ) + } + entry { + SettingsScreen( + onBack = { backStack.removeLastOrNull() }, + onAbout = { backStack.add(AboutKey) }, + onBoardStyle = { backStack.add(BoardStyleKey) }, + ) + } + entry { + BoardStyleScreen(onBack = { backStack.removeLastOrNull() }) + } + entry { + OnlineScreen( + onBack = { backStack.removeLastOrNull() }, + // The downloaded database instead of this screen: "back" goes to the list. + onOpen = { id -> + backStack.removeLastOrNull() + backStack.add(Games(id)) + }, + ) + } + entry { + AboutScreen(onBack = { backStack.removeLastOrNull() }) + } + }, + ) +} + +internal fun resetPastedView( + shown: HashMap>, + lastOpened: HashMap>, + id: String, +) { + shown.remove(id) + lastOpened.remove(id) +} + +/// Why a file from another app did not open; it never got on the list, so the advice is +/// not that of a database on it (openProblem). +@Composable +private fun incomingProblem(e: Throwable): String = when (e) { + is ChessBasePart -> stringResource(R.string.file_chessbase_part) + is NoGames -> stringResource(R.string.file_no_games) + is SecurityException, is FileNotFoundException, is ApiException.Io -> stringResource(R.string.file_unreadable) + is ApiException -> openProblem(e).ifEmpty { stringResource(R.string.open_corrupt) } + else -> stringResource(R.string.file_copy_failed) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/AppUpdates.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/AppUpdates.kt new file mode 100644 index 0000000..c3e0ef7 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/AppUpdates.kt @@ -0,0 +1,662 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.app.DownloadManager +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.pm.PackageInstaller +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.Uri +import android.os.Build +import android.os.storage.StorageManager +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.ChessPenguinApp +import io.github.vrubelroman.chesspenguin.R +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import uniffi.mobile_api.ReleaseCheck +import uniffi.mobile_api.checkRelease +import uniffi.mobile_api.checkReleaseCounted +import java.io.File +import java.io.IOException +import java.security.MessageDigest + +/// A newer release, as it is kept between starts: its light APK is what is installed. +@Serializable +data class Update( + val version: String, + val page: String, + val apkName: String, + val apkUrl: String, + val apkSize: Long, + val sha256: String, +) + +/// A step that takes seconds and cannot be stopped. +enum class UpdateStep { CheckingFile, KeepingEngine, Installing } + +/// Why an update did not go on (android-ui.md §25.3 F). +enum class UpdateProblem { NoInternet, DownloadFailed, NoSpace, Corrupt, BadRelease, InstallStorage, Conflict, Blocked, InstallFailed } + +/// Where the update of a known newer release is. +sealed interface UpdateState { + val update: Update + + data class Available(override val update: Update) : UpdateState + + /// Android needs the user's permission to install apps; `denied`: back without it. + data class NeedsPermission(override val update: Update, val denied: Boolean) : UpdateState + + data class Downloading(override val update: Update, val done: Long, val waitingNetwork: Boolean) : UpdateState + + data class Busy(override val update: Update, val step: UpdateStep) : UpdateState + + /// Downloaded and checked; `aborted`: the user said no to Android's question. + data class Ready(override val update: Update, val aborted: Boolean) : UpdateState + + data class Failed(override val update: Update, val problem: UpdateProblem, val detail: String?) : UpdateState +} + +/// The manual check in About. +sealed interface CheckState { + data object Idle : CheckState + data object Checking : CheckState + data object Latest : CheckState + data object Offline : CheckState + data object Failed : CheckState +} + +/// Messages for a snackbar over the app. +sealed interface UpdateMessage { + data object Ready : UpdateMessage + data object Cancelled : UpdateMessage + data object Latest : UpdateMessage + data class Updated(val from: String, val to: String) : UpdateMessage +} + +/// The app updating itself (android-ui.md §25): asks GitHub for a newer release (the +/// core's check, the same as the desktop's), downloads its light APK with the system's +/// download service, checks it against the release's SHA-256 and gives it to Android's +/// package installer. What is known is kept, so a restart picks it up where it was. +class AppUpdates(private val context: Context, private val scope: CoroutineScope, private val engine: EngineFiles) { + private val prefs = context.getSharedPreferences("update", Context.MODE_PRIVATE) + private val downloads get() = context.getSystemService(DownloadManager::class.java) + private val dir get() = context.getExternalFilesDir("updates") + private val json = Json { ignoreUnknownKeys = true } + /// A test server (debug builds); otherwise the site, which counts this installation. + private val testApi = BuildConfig.UPDATE_API + + /// A random id of this installation, made once; the site counts installations that + /// run by it (nothing else about the user is sent). + private fun installId(): String = prefs.getString(INSTALL_ID, null) ?: java.util.UUID.randomUUID().toString().replace("-", "").also { + prefs.edit().putString(INSTALL_ID, it).apply() + } + + private val _state = MutableStateFlow(null) + /// The known newer release and where its update is; null when there is none. + val state: StateFlow = _state.asStateFlow() + + private val _check = MutableStateFlow(CheckState.Idle) + val check: StateFlow = _check.asStateFlow() + + private val _auto = MutableStateFlow(prefs.getBoolean(AUTO, !BuildConfig.DEBUG)) + /// «Check for updates at start». + val auto: StateFlow = _auto.asStateFlow() + + private val _offer = MutableStateFlow(prefs.getBoolean(OFFER, true)) + /// «Offer new versions»: the card on «Databases» (its × turns this off). The check + /// goes on without it. + val offer: StateFlow = _offer.asStateFlow() + + /// The release was found by «Check now»: its card shows even with the check off. + private val _asked = MutableStateFlow(false) + val asked: StateFlow = _asked.asStateFlow() + + private val _lastCheck = MutableStateFlow(prefs.getLong(LAST_OK, 0L)) + /// When the last check that got an answer was made (0: never). + val lastCheck: StateFlow = _lastCheck.asStateFlow() + + private val _message = MutableStateFlow(null) + /// One message for a snackbar; the screen that shows it calls [shown]. + val message: StateFlow = _message.asStateFlow() + + fun shown(m: UpdateMessage) { + _message.compareAndSet(m, null) + if (m is UpdateMessage.Updated) prefs.edit().remove(UPDATED_FROM).apply() + } + + private val _confirm = MutableStateFlow(null) + /// Android's question «Update this app?», to be shown when the app is on the screen. + val confirm: StateFlow = _confirm.asStateFlow() + + private val _sheet = MutableStateFlow(prefs.getString(AWAITING_PERMISSION, null) != null) + /// The update sheet is open: a finished download goes on to install by itself. It + /// opens again after a restart while the user was in the permission's settings. + val sheet: StateFlow = _sheet.asStateFlow() + /// The app is on the screen (MainActivity's onStart … onStop). + @Volatile var foreground = false + + /// The user watches the sheet: a finished download goes on to install. Not when the + /// app is in the background — Android would close it unseen (§25.1 p. 6). + private val watched get() = _sheet.value && foreground + + fun openSheet() { + _sheet.value = true + } + + fun closeSheet() { + _sheet.value = false + } + + private var watching: Job? = null + private var session: Int? = null + private var confirmShown = false + + init { + // The first start of a new version: say so, and forget the update. + // Kept until a screen shows it: Android may start the new version in the background + // first, only to hand it the installer's answer. + // Keys of 1.0.0 and earlier: a version hidden with «Not now», a page of what's new. + prefs.edit().remove(HIDDEN).remove(UPDATED_PAGE).apply() + prefs.getString(INSTALLING_FROM, null)?.let { from -> + if (from != BuildConfig.VERSION_NAME) { + prefs.edit() + .putString(UPDATED_FROM, from) + .remove(LATEST) + .remove(READY) + .apply() + forgetFile() + } + prefs.edit().remove(INSTALLING_FROM).apply() + } + prefs.getString(UPDATED_FROM, null)?.let { from -> + _message.value = UpdateMessage.Updated(from, BuildConfig.VERSION_NAME) + } + val update = known() + when { + // Installed by hand from the site, or never newer than this app; or a store's + // build put over the site's (the store updates it, a release kept is dropped). + !BuildConfig.SELF_UPDATE || update == null || !newer(update.version) -> forgetAll() + prefs.getLong(DOWNLOAD, -1L) != -1L -> watch(update, prefs.getLong(DOWNLOAD, -1L)) + 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) + else -> { + forgetFile() + _state.value = UpdateState.Available(update) + } + } + } + + /// Whether this run of the app asked already: the first start always asks. + private var askedThisRun = false + + /// On start and on return to the app: a check when one is due (§25.6): at each start + /// 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). + fun checkIfDue() { + if (!BuildConfig.SELF_UPDATE || !_auto.value || busy()) return + val now = System.currentTimeMillis() + if (askedThisRun && (now - _lastCheck.value < RECHECK || now - prefs.getLong(LAST_ATTEMPT, 0L) < HOUR)) return + askedThisRun = true + scope.launch { runCheck(manual = false) } + } + + /// «Check now» (works with the automatic check off). + fun checkNow() { + if (!BuildConfig.SELF_UPDATE || _check.value == CheckState.Checking) return + scope.launch { runCheck(manual = true) } + } + + 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 (manual) _check.value = CheckState.Idle + return + } + _check.value = CheckState.Checking + prefs.edit().putLong(LAST_ATTEMPT, System.currentTimeMillis()).apply() + if (!online()) { + _check.value = if (manual) CheckState.Offline else CheckState.Idle + return + } + val platform = if (BuildConfig.FLAVOR == "full") "android" else "android-noengine" + val result = withContext(Dispatchers.IO) { + if (testApi.isNotEmpty()) checkRelease(testApi) else checkReleaseCounted(installId(), platform) + } + when (result) { + is ReleaseCheck.Newer -> { + val light = result.release.light ?: return + val update = Update(result.release.version, result.release.page, light.name, light.url, light.size.toLong(), light.sha256) + checked() + _check.value = CheckState.Idle + if (manual) _asked.value = true + found(update) + } + is ReleaseCheck.Unverifiable -> { + checked() + _check.value = CheckState.Idle + val light = result.release.light ?: return + val update = Update(result.release.version, result.release.page, light.name, light.url, light.size.toLong(), "") + if (manual) _asked.value = true + found(update) + if (!busy()) _state.value = UpdateState.Failed(update, UpdateProblem.BadRelease, null) + } + is ReleaseCheck.UpToDate -> { + checked() + _check.value = CheckState.Latest + if (manual) _message.value = UpdateMessage.Latest + if (!busy()) forgetAll() + } + is ReleaseCheck.Failed -> _check.value = if (manual) CheckState.Failed else CheckState.Idle + } + } + + private fun checked() { + val now = System.currentTimeMillis() + _lastCheck.value = now + prefs.edit().putLong(LAST_OK, now).apply() + } + + /// A newer release found: a downloaded older one is of no use any more. + private fun found(update: Update) { + val current = _state.value + if (current != null && current.update == update) return + if (busy()) return + forgetFile() + prefs.edit().putString(LATEST, json.encodeToString(update)).remove(READY).apply() + _state.value = UpdateState.Available(update) + } + + fun setAuto(on: Boolean) { + _auto.value = on + if (!on) _asked.value = false + prefs.edit().putBoolean(AUTO, on).apply() + if (on) checkIfDue() + } + + fun setOffer(on: Boolean) { + _offer.value = on + prefs.edit().putBoolean(OFFER, on).apply() + if (on) checkIfDue() + } + + /// «Update» / «Try again» / «Download again»: from the permission on to the install. + fun start() { + val update = _state.value?.update ?: return + if (update.sha256.isEmpty()) { + _state.value = UpdateState.Failed(update, UpdateProblem.BadRelease, null) + return + } + if (!context.packageManager.canRequestPackageInstalls()) { + _state.value = UpdateState.NeedsPermission(update, denied = false) + return + } + if (prefs.getString(READY, null) == update.version && apk(update).exists()) { + install(update) + return + } + download(update) + } + + /// The permission's settings page is being opened: back from it, the update goes on + /// (also when Android restarted the app meanwhile). + fun permissionAsked() { + _state.value?.let { prefs.edit().putString(AWAITING_PERMISSION, it.update.version).apply() } + } + + /// Back in the app after the permission's settings page. + fun onResume() { + prefs.getString(AWAITING_PERMISSION, null)?.let { version -> + val update = _state.value?.update + prefs.edit().remove(AWAITING_PERMISSION).apply() + if (update != null && update.version == version) { + if (context.packageManager.canRequestPackageInstalls()) { + _sheet.value = true + start() + } else { + _state.value = UpdateState.NeedsPermission(update, denied = true) + } + } + } + // Android's question was closed with no answer: the file waits for «Install». + if (confirmShown) { + confirmShown = false + scope.launch { + delay(1500) + val s = _state.value + if (s is UpdateState.Busy && s.step == UpdateStep.Installing && _confirm.value == null) { + abandon() + _state.value = UpdateState.Ready(s.update, aborted = true) + } + } + } + } + + /// The question was put on the screen. + fun confirmShown() { + _confirm.value = null + confirmShown = true + } + + private fun download(update: Update) { + if (!online()) { + _state.value = UpdateState.Failed(update, UpdateProblem.NoInternet, null) + return + } + if (freeSpace() < needed(update)) { + _state.value = UpdateState.Failed(update, UpdateProblem.NoSpace, null) + return + } + forgetFile() + // Under another name while it comes: removing the download from the system's list + // deletes its file, and the checked file must stay. + val target = File(apk(update).path + ".download") + val request = DownloadManager.Request(Uri.parse(update.apkUrl)) + .setTitle(context.getString(R.string.upd_notification)) + .setDestinationUri(Uri.fromFile(target)) + // No "complete" notification: tapping it would open the file past the check. + .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) + .setAllowedOverMetered(true) + .setAllowedOverRoaming(true) + val id = try { + downloads.enqueue(request) + } catch (e: IllegalArgumentException) { + _state.value = UpdateState.Failed(update, UpdateProblem.DownloadFailed, e.message) + return + } + prefs.edit().putLong(DOWNLOAD, id).putString(DOWNLOAD_VERSION, update.version).apply() + _state.value = UpdateState.Downloading(update, 0, waitingNetwork = false) + watch(update, id) + } + + /// «Cancel» while downloading. + fun cancel() { + val update = _state.value?.update ?: return + watching?.cancel() + val id = prefs.getLong(DOWNLOAD, -1L) + if (id != -1L) downloads.remove(id) + prefs.edit().remove(DOWNLOAD).remove(DOWNLOAD_VERSION).apply() + forgetFile() + _state.value = UpdateState.Available(update) + _message.value = UpdateMessage.Cancelled + } + + /// «Not now» in the sheet after an error: the card shows the release again. + fun dismissProblem() { + val s = _state.value + // The same file would fail the same way: the card keeps saying so. + if (s is UpdateState.Failed && s.problem in setOf(UpdateProblem.Conflict, UpdateProblem.Blocked, UpdateProblem.BadRelease)) return + if (s is UpdateState.Failed || s is UpdateState.NeedsPermission) { + prefs.edit().remove(AWAITING_PERMISSION).apply() + val ready = prefs.getString(READY, null) == s.update.version && apk(s.update).exists() + _state.value = if (ready) UpdateState.Ready(s.update, aborted = false) else UpdateState.Available(s.update) + } + } + + private fun watch(update: Update, id: Long) { + watching?.cancel() + _state.value = UpdateState.Downloading(update, 0, waitingNetwork = false) + watching = scope.launch(Dispatchers.Main.immediate) { + while (isActive) { + val row = withContext(Dispatchers.IO) { progress(id) } + if (row == null) { + // Removed from the system's list of downloads. + prefs.edit().remove(DOWNLOAD).remove(DOWNLOAD_VERSION).apply() + _state.value = UpdateState.Available(update) + return@launch + } + when (row.status) { + DownloadManager.STATUS_SUCCESSFUL -> { + val moved = File(apk(update).path + ".download").renameTo(apk(update)) + downloads.remove(id) + prefs.edit().remove(DOWNLOAD).remove(DOWNLOAD_VERSION).apply() + if (moved) { + verify(update) + } else { + forgetFile() + _state.value = UpdateState.Failed(update, UpdateProblem.DownloadFailed, null) + } + return@launch + } + DownloadManager.STATUS_FAILED -> { + downloads.remove(id) + prefs.edit().remove(DOWNLOAD).remove(DOWNLOAD_VERSION).apply() + forgetFile() + val space = row.reason == DownloadManager.ERROR_INSUFFICIENT_SPACE + _state.value = UpdateState.Failed(update, if (space) UpdateProblem.NoSpace else UpdateProblem.DownloadFailed, null) + return@launch + } + else -> { + // A server that does not answer is retried quietly; only a missing network is said. + val waiting = row.status == DownloadManager.STATUS_PAUSED && row.reason == DownloadManager.PAUSED_WAITING_FOR_NETWORK + _state.value = UpdateState.Downloading(update, row.done.coerceAtLeast(0), waiting) + } + } + delay(500) + } + } + } + + private class Row(val status: Int, val reason: Int, val done: Long) + + private fun progress(id: Long): Row? = + downloads.query(DownloadManager.Query().setFilterById(id))?.use { c -> + if (!c.moveToFirst()) return null + Row( + c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)), + c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON)), + c.getLong(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)), + ) + } + + /// The SHA-256 of the file against the release's; then on to the install when the user + /// waits for it in the sheet, or «downloaded» when they are elsewhere. + private suspend fun verify(update: Update) { + _state.value = UpdateState.Busy(update, UpdateStep.CheckingFile) + val file = apk(update) + val sum = withContext(Dispatchers.IO) { runCatching { sha256(file) }.getOrNull() } + if (sum != update.sha256) { + forgetFile() + _state.value = UpdateState.Failed(update, UpdateProblem.Corrupt, null) + return + } + prefs.edit().putString(READY, update.version).apply() + if (watched) { + install(update) + } else { + _state.value = UpdateState.Ready(update, aborted = false) + // With the sheet open the user sees it there. + if (!_sheet.value) _message.value = UpdateMessage.Ready + } + } + + /// «Install»: the engine's network kept (full build), then Android's installer. + fun install() { + val s = _state.value ?: return + if (!context.packageManager.canRequestPackageInstalls()) { + start() + return + } + install(s.update) + } + + private fun install(update: Update) { + scope.launch(Dispatchers.Main.immediate) { + if (engine.builtIn) { + _state.value = UpdateState.Busy(update, UpdateStep.KeepingEngine) + engine.keepBuiltIn() + } + _state.value = UpdateState.Busy(update, UpdateStep.Installing) + val committed = withContext(Dispatchers.IO) { runCatching { commit(apk(update)) } } + committed.onFailure { e -> + abandon() + val problem = if (e is IOException && freeSpace() < update.apkSize * 2) UpdateProblem.InstallStorage else UpdateProblem.InstallFailed + _state.value = UpdateState.Failed(update, problem, e.message) + } + } + } + + /// Writes the APK into an installer session and commits it; the answer comes to + /// [InstallResult]. + private fun commit(file: File) { + val installer = context.packageManager.packageInstaller + val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { + setAppPackageName(context.packageName) + setSize(file.length()) + // Without Android's question when it allows that (the app installed the last + // version itself): the conditions are Android's. + setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + if (Build.VERSION.SDK_INT >= 33) setPackageSource(PackageInstaller.PACKAGE_SOURCE_DOWNLOADED_FILE) + } + val id = installer.createSession(params) + session = id + installer.openSession(id).use { s -> + file.inputStream().use { input -> + s.openWrite("base.apk", 0, file.length()).use { out -> + input.copyTo(out, 256 * 1024) + s.fsync(out) + } + } + prefs.edit().putString(INSTALLING_FROM, BuildConfig.VERSION_NAME).apply() + val intent = Intent(context, InstallResult::class.java).setPackage(context.packageName) + // Mutable: the installer fills in the result. + val pending = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE) + s.commit(pending.intentSender) + } + } + + private fun abandon() { + session?.let { runCatching { context.packageManager.packageInstaller.abandonSession(it) } } + session = null + prefs.edit().remove(INSTALLING_FROM).apply() + } + + /// The installer's answer (from [InstallResult]). + internal fun onInstallResult(status: Int, message: String?, confirm: Intent?) { + val update = _state.value?.update ?: return + when (status) { + PackageInstaller.STATUS_PENDING_USER_ACTION -> _confirm.value = confirm + // The process ends with the install: nothing more to show. + PackageInstaller.STATUS_SUCCESS -> {} + else -> { + session = null + prefs.edit().remove(INSTALLING_FROM).apply() + _confirm.value = null + _state.value = when (status) { + PackageInstaller.STATUS_FAILURE_ABORTED -> UpdateState.Ready(update, aborted = true) + PackageInstaller.STATUS_FAILURE_STORAGE -> UpdateState.Failed(update, UpdateProblem.InstallStorage, message) + PackageInstaller.STATUS_FAILURE_CONFLICT -> UpdateState.Failed(update, UpdateProblem.Conflict, message) + PackageInstaller.STATUS_FAILURE_BLOCKED -> UpdateState.Failed(update, UpdateProblem.Blocked, message) + else -> UpdateState.Failed(update, UpdateProblem.InstallFailed, message) + } + } + } + } + + /// Space the update needs: the file twice (download, install), and the engine's + /// network when the full build keeps it first. + fun needed(update: Update): Long = + 2 * update.apkSize + if (engine.builtIn && engine.state.value != NetState.Ready) BuildConfig.NET_SIZE else 0 + + /// Downloading, checking or installing: a check waits for it to end. + private fun busy(): Boolean = _state.value.let { it is UpdateState.Downloading || it is UpdateState.Busy || it is UpdateState.NeedsPermission } + + private fun known(): Update? = prefs.getString(LATEST, null)?.let { runCatching { json.decodeFromString(it) }.getOrNull() } + + private fun newer(version: String): Boolean = compare(version, BuildConfig.VERSION_NAME) > 0 + + private fun apk(update: Update): File = File(dir ?: context.cacheDir, update.apkName) + + private fun forgetFile() { + dir?.listFiles()?.forEach { it.delete() } + prefs.edit().remove(READY).apply() + } + + private fun forgetAll() { + forgetFile() + prefs.edit().remove(LATEST).remove(DOWNLOAD).remove(DOWNLOAD_VERSION).remove(AWAITING_PERMISSION).apply() + _state.value = null + _asked.value = false + } + + private fun freeSpace(): Long = try { + val storage = context.getSystemService(StorageManager::class.java) + storage.getAllocatableBytes(storage.getUuidForPath(context.filesDir)) + } catch (e: IOException) { + context.filesDir.usableSpace + } + + private fun online(): Boolean { + val cm = context.getSystemService(ConnectivityManager::class.java) ?: return true + val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false + return caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + } + + private companion object { + const val AUTO = "autoCheck" + const val LAST_OK = "lastCheckOk" + const val LAST_ATTEMPT = "lastAttempt" + const val INSTALL_ID = "installId" + const val LATEST = "latest" + const val OFFER = "offerUpdates" + /// No longer used: «Not now» hid one version (until 1.0.1). + const val HIDDEN = "hiddenVersion" + const val DOWNLOAD = "downloadId" + const val DOWNLOAD_VERSION = "downloadVersion" + const val READY = "readyVersion" + const val AWAITING_PERMISSION = "awaitingPermission" + const val INSTALLING_FROM = "installingFrom" + const val UPDATED_FROM = "updatedFrom" + /// No longer used (until 1.0.1). + const val UPDATED_PAGE = "updatedPage" + const val RECHECK = 6 * 60 * 60 * 1000L + const val HOUR = 60 * 60 * 1000L + } +} + +/// "0.15.0" against "0.14.2": the numbers major.minor.patch. +fun compare(a: String, b: String): Int { + fun parts(v: String) = v.trim().removePrefix("v").split('.').map { p -> p.takeWhile(Char::isDigit).toIntOrNull() ?: 0 } + val (x, y) = parts(a) to parts(b) + for (i in 0 until maxOf(x.size, y.size)) { + val c = (x.getOrElse(i) { 0 }).compareTo(y.getOrElse(i) { 0 }) + if (c != 0) return c + } + return 0 +} + +private fun sha256(file: File): String { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buf = ByteArray(256 * 1024) + while (true) { + val n = input.read(buf) + if (n < 0) break + digest.update(buf, 0, n) + } + } + return digest.digest().joinToString("") { "%02x".format(it) } +} + +/// The package installer's answer to an update. +class InstallResult : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE) + val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) + val confirm = androidx.core.content.IntentCompat.getParcelableExtra(intent, Intent.EXTRA_INTENT, Intent::class.java) + (context.applicationContext as ChessPenguinApp).updates.onInstallResult(status, message, confirm) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/BoardStyle.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/BoardStyle.kt new file mode 100644 index 0000000..7eb8c11 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/BoardStyle.kt @@ -0,0 +1,78 @@ +package io.github.vrubelroman.chesspenguin.data + +import androidx.annotation.StringRes +import androidx.compose.ui.graphics.Color +import io.github.vrubelroman.chesspenguin.R + +/// The piece sets of the desktop app (apps/desktop/src/assets.rs), drawn from +/// `assets/pieces/`; the name is the set's own, as on Lichess. +enum class PieceSet(val dir: String) { + Cburnett("cburnett"), + Merida("merida"), + Mpchess("mpchess"), + Chessnut("chessnut"), + Fantasy("fantasy"), + Celtic("celtic"), + Spatial("spatial"), + Rhosgfx("rhosgfx"), + Shapes("shapes"), + KiwenSuwi("kiwen-suwi"), + Firi("firi"), + Pixel("pixel"), + Letter("letter"), + Pirouetti("pirouetti"), + Governor("governor"), + Kosal("kosal"), + Metaltops("metaltops"), +} + +/// The boards of the desktop app (assets.rs `BoardThemeId`): two colors, and for some a +/// full-board image (`assets/boards/`, 8×8 squares, a1 dark) drawn instead of them. +/// The colors stay for the coordinates and the previews. +enum class BoardTheme( + @StringRes val label: Int, + val number: Int?, + val light: Color, + val dark: Color, + val texture: String? = null, +) { + Brown(R.string.board_brown, null, rgb(240, 217, 181), rgb(181, 136, 99)), + Blue(R.string.board_blue, null, rgb(222, 227, 230), rgb(140, 162, 173)), + Green(R.string.board_green, null, rgb(255, 255, 221), rgb(134, 166, 102)), + Tournament(R.string.board_tournament, null, rgb(238, 238, 210), rgb(118, 150, 86)), + Sand(R.string.board_sand, null, rgb(240, 228, 196), rgb(200, 168, 110)), + Coral(R.string.board_coral, null, rgb(177, 228, 185), rgb(112, 162, 163)), + Grey(R.string.board_grey, null, rgb(217, 217, 217), rgb(154, 154, 154)), + Purple(R.string.board_purple, null, rgb(232, 224, 240), rgb(159, 144, 176)), + Ic(R.string.board_ic, null, rgb(236, 236, 236), rgb(193, 193, 142)), + Ncf(R.string.board_ncf, null, rgb(187, 207, 255), rgb(84, 119, 202)), + Ice(R.string.board_ice, null, rgb(222, 234, 240), rgb(122, 157, 178)), + Navy(R.string.board_navy, null, rgb(220, 226, 236), rgb(70, 96, 140)), + Mint(R.string.board_mint, null, rgb(222, 241, 230), rgb(118, 178, 148)), + Emerald(R.string.board_emerald, null, rgb(226, 236, 218), rgb(74, 132, 100)), + Orange(R.string.board_orange, null, rgb(250, 228, 196), rgb(208, 139, 72)), + Rose(R.string.board_rose, null, rgb(242, 220, 220), rgb(190, 126, 138)), + Dusk(R.string.board_dusk, null, rgb(204, 186, 176), rgb(112, 102, 122)), + Night(R.string.board_night, null, rgb(128, 136, 146), rgb(68, 74, 84)), + Wood(R.string.board_wood, null, rgb(215, 161, 91), rgb(154, 88, 35), "wood.jpg"), + Wood2(R.string.board_wood, 2, rgb(151, 124, 79), rgb(121, 95, 48), "wood2.jpg"), + Wood3(R.string.board_wood, 3, rgb(186, 173, 157), rgb(129, 94, 56), "wood3.jpg"), + Wood4(R.string.board_wood, 4, rgb(191, 158, 104), rgb(134, 91, 54), "wood4.jpg"), + Maple(R.string.board_maple, null, rgb(224, 190, 146), rgb(180, 111, 60), "maple.jpg"), + Maple2(R.string.board_maple, 2, rgb(222, 193, 151), rgb(167, 114, 85), "maple2.jpg"), + Leather(R.string.board_leather, null, rgb(206, 206, 198), rgb(192, 140, 18), "leather.jpg"), + Marble(R.string.board_marble, null, rgb(126, 150, 128), rgb(97, 120, 97), "marble.jpg"), + BlueMarble(R.string.board_blue_marble, null, rgb(229, 224, 212), rgb(148, 158, 174), "blue-marble.jpg"), + Blue2(R.string.board_blue, 2, rgb(129, 151, 173), rgb(96, 118, 138), "blue2.jpg"), + Blue3(R.string.board_blue, 3, rgb(189, 200, 211), rgb(68, 114, 163), "blue3.jpg"), + Canvas(R.string.board_canvas, null, rgb(203, 206, 223), rgb(114, 130, 156), "canvas2.jpg"), + Metal(R.string.board_metal, null, rgb(177, 177, 177), rgb(119, 119, 119), "metal.jpg"), + Olive(R.string.board_olive, null, rgb(173, 166, 148), rgb(132, 124, 106), "olive.jpg"), + Stone(R.string.board_stone, null, rgb(169, 169, 169), rgb(136, 136, 136), "grey.jpg"), + GreenPlastic(R.string.board_green_plastic, null, rgb(241, 246, 178), rgb(89, 147, 93), "green-plastic.png"), + PurpleDiag(R.string.board_purple_diag, null, rgb(227, 216, 238), rgb(151, 123, 178), "purple-diag.png"), + PinkPyramid(R.string.board_pink_pyramid, null, rgb(237, 238, 191), rgb(242, 117, 117), "pink-pyramid.png"), + Horsey(R.string.board_sketch, null, rgb(239, 222, 198), rgb(151, 112, 81), "horsey.jpg"), +} + +private fun rgb(r: Int, g: Int, b: Int) = Color(r, g, b) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/CheckedDownload.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/CheckedDownload.kt new file mode 100644 index 0000000..295b566 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/CheckedDownload.kt @@ -0,0 +1,286 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.app.DownloadManager +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.Uri +import android.os.storage.StorageManager +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.security.MessageDigest + +/// Why a downloaded file is not there. +enum class NetProblem { NoInternet, Interrupted, NoSpace, Corrupt } + +sealed interface NetState { + data object Missing : NetState + data class Loading(val done: Long, val total: Long) : NetState + data class Failed(val problem: NetProblem) : NetState + data object Ready : NetState +} + +/// A file of known size and SHA-256 fetched on request into the app's storage: the +/// engine's network, Maia's weights, a book of Rodent IV. +data class FileSpec( + /// Folder in the app's files, and the file's name. + val dir: String, + val name: String, + val url: String, + val size: Long, + val sha256: String, + /// The download's title in the system's notification. + val title: String, + /// The preferences that keep the system's download id (one file each). + val prefs: String, + /// The folder is the file's own: other files there (of other versions) are removed. + /// Not for a folder of several files (Rodent's books: their pack sees to them). + val ownFolder: Boolean = true, +) + +/// The download is the system's (DownloadManager): it goes on with the app closed, +/// waits for the network and resumes, and shows its progress in a notification. Its id +/// is kept, so the app picks the download up again when it starts. The file is checked +/// by its SHA-256 as it is moved into place. +class CheckedDownload(private val context: Context, private val scope: CoroutineScope, private val spec: FileSpec) { + private val dir = File(context.filesDir, spec.dir) + val file = File(dir, spec.name) + val size: Long get() = spec.size + private val part = File(dir, spec.name + ".part") + private val prefs = context.getSharedPreferences(spec.prefs, Context.MODE_PRIVATE) + private val downloads get() = context.getSystemService(DownloadManager::class.java) + + private val _state = MutableStateFlow(NetState.Missing) + val state: StateFlow = _state.asStateFlow() + private var job: Job? = null + + init { + // Files of other versions (kept before an update) are of no use to this one. + if (spec.ownFolder) dir.listFiles()?.filter { it.name != file.name && it.name != part.name }?.forEach { it.delete() } + when { + installed() -> _state.value = NetState.Ready + downloadId() != NO_DOWNLOAD -> { + _state.value = NetState.Loading(0, spec.size) + watch(downloadId()) + } + } + } + + /// A file checked when it was written: the right size is enough later. + fun installed() = file.length() == spec.size + + /// True when the phone is on a metered (mobile) connection right now. + fun metered(): Boolean { + val cm = context.getSystemService(ConnectivityManager::class.java) ?: return false + val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false + return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) + } + + /// Fetches the file from the internet. + fun download() { + if (_state.value == NetState.Ready || _state.value is NetState.Loading) return + if (!online()) { + _state.value = NetState.Failed(NetProblem.NoInternet) + return + } + // The file is downloaded next to the app's files, then checked and moved in. + if (freeSpace() < 2 * spec.size) { + _state.value = NetState.Failed(NetProblem.NoSpace) + return + } + target()?.delete() + val request = DownloadManager.Request(Uri.parse(spec.url)) + .setTitle(spec.title) + .setDestinationInExternalFilesDir(context, null, spec.name) + .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) + .setAllowedOverMetered(true) + val id = try { + downloads.enqueue(request) + } catch (e: IllegalArgumentException) { + // No shared storage for the download (or the download service is off). + _state.value = NetState.Failed(NetProblem.Interrupted) + return + } + prefs.edit().putLong(KEY, id).apply() + _state.value = NetState.Loading(0, spec.size) + watch(id) + } + + /// Writes the file from `open()` (inside the APK) into place, checked, in the + /// background, the progress shown as a download's. + fun installFrom(open: () -> InputStream) { + if (_state.value == NetState.Ready || _state.value is NetState.Loading) return + _state.value = NetState.Loading(0, spec.size) + job = scope.launch(Dispatchers.IO) { + val result = try { + open().use { install(it, progress = true) } + NetState.Ready + } catch (e: Failure) { + NetState.Failed(e.problem) + } catch (e: IOException) { + NetState.Failed(if (freeSpace() < spec.size) NetProblem.NoSpace else NetProblem.Interrupted) + } + if (isActive) _state.value = result + } + } + + /// The same, at once (the caller waits): false when it could not (no space). + suspend fun installNow(open: () -> InputStream): Boolean = withContext(Dispatchers.IO) { + if (installed()) return@withContext true + if (freeSpace() < 2 * spec.size) return@withContext false + try { + open().use { install(it, progress = false) } + _state.value = NetState.Ready + true + } catch (e: Exception) { + part.delete() + if (!installed()) _state.value = NetState.Missing + false + } + } + + /// Stops a download and throws away what came. + fun cancel() { + job?.cancel() + val id = downloadId() + if (id != NO_DOWNLOAD) downloads.remove(id) + forget() + part.delete() + if (!installed()) _state.value = NetState.Missing + } + + /// Removes the file. + fun delete() { + cancel() + file.delete() + _state.value = NetState.Missing + } + + private class Failure(val problem: NetProblem) : Exception() + + private fun downloadId(): Long = prefs.getLong(KEY, NO_DOWNLOAD) + + private fun forget() = prefs.edit().remove(KEY).apply() + + /// Where the system puts the downloaded file (the app's own external folder). + private fun target(): File? = context.getExternalFilesDir(null)?.let { File(it, spec.name) } + + /// Follows a download of the system until it ends. The state is set on the main + /// thread, as "Cancel" sets it: after a cancel the watcher sets nothing more. + private fun watch(id: Long) { + job = scope.launch(Dispatchers.Main.immediate) { + while (isActive) { + val row = withContext(Dispatchers.IO) { progress(id) } + if (row == null) { + // Removed in the system's list of downloads. + forget() + _state.value = NetState.Missing + return@launch + } + when (row.status) { + DownloadManager.STATUS_SUCCESSFUL -> { + val result = withContext(Dispatchers.IO) { + try { + val f = target() ?: throw IOException("no external folder") + f.inputStream().use { install(it, progress = false) } + NetState.Ready + } catch (e: Failure) { + NetState.Failed(e.problem) + } catch (e: IOException) { + NetState.Failed(if (freeSpace() < spec.size) NetProblem.NoSpace else NetProblem.Interrupted) + } + } + downloads.remove(id) + forget() + _state.value = result + return@launch + } + DownloadManager.STATUS_FAILED -> { + downloads.remove(id) + forget() + _state.value = NetState.Failed( + if (row.reason == DownloadManager.ERROR_INSUFFICIENT_SPACE) NetProblem.NoSpace else NetProblem.Interrupted, + ) + return@launch + } + else -> _state.value = NetState.Loading(row.done.coerceAtLeast(0), spec.size) + } + delay(500) + } + } + } + + private class Row(val status: Int, val reason: Int, val done: Long) + + private fun progress(id: Long): Row? = + downloads.query(DownloadManager.Query().setFilterById(id))?.use { c -> + if (!c.moveToFirst()) return null + Row( + c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)), + c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON)), + c.getLong(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)), + ) + } + + /// Writes the file into place, checking its SHA-256 on the way; a wrong file is + /// thrown away. + private suspend fun install(input: InputStream, progress: Boolean) { + dir.mkdirs() + val digest = MessageDigest.getInstance("SHA-256") + var done = 0L + part.outputStream().use { out -> + val buf = ByteArray(256 * 1024) + var last = 0L + while (true) { + kotlin.coroutines.coroutineContext.ensureActive() + val n = input.read(buf) + if (n < 0) break + out.write(buf, 0, n) + digest.update(buf, 0, n) + done += n + if (progress && done - last > 512 * 1024) { + last = done + _state.value = NetState.Loading(done, spec.size) + } + } + } + val sum = digest.digest().joinToString("") { "%02x".format(it) } + if (sum != spec.sha256 || done != spec.size) { + part.delete() + throw Failure(NetProblem.Corrupt) + } + if (!part.renameTo(file)) throw IOException("cannot move the file into place") + } + + /// The space the app can take, with the caches the system would clear for it. Asked + /// of filesDir, which always exists: a folder not made yet answers 0. + private fun freeSpace(): Long = try { + val storage = context.getSystemService(StorageManager::class.java) + storage.getAllocatableBytes(storage.getUuidForPath(context.filesDir)) + } catch (e: IOException) { + context.filesDir.usableSpace + } + + private fun online(): Boolean { + val cm = context.getSystemService(ConnectivityManager::class.java) ?: return true + val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false + return caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + } + + private companion object { + const val KEY = "download" + const val NO_DOWNLOAD = -1L + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ClipboardPgn.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ClipboardPgn.kt new file mode 100644 index 0000000..6677f47 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ClipboardPgn.kt @@ -0,0 +1,173 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.SharedPreferences +import java.security.MessageDigest +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +internal const val CLIPBOARD_PGN_MAX_BYTES = 8 * 1024 * 1024 +internal const val CLIPBOARD_PREFERENCES = "clipboard-pgn" +private const val PREFS_DIGESTS = "decided-sha256" + +data class ClipboardOffer( + val bytes: ByteArray, + val games: Int, + internal val digest: String, + internal val generation: Long, +) + +data class ClipboardAccept( + val bytes: ByteArray, + internal val digest: String, + internal val generation: Long, +) + +class ClipboardPgn( + private val library: Library, + private val scope: CoroutineScope, + preferences: SharedPreferences, + private val requestLock: Any, + private val invalidateIncoming: () -> Unit, +) { + private val gate = ClipboardPromptGate( + decided = preferences.getStringSet(PREFS_DIGESTS, null).orEmpty(), + onDecide = { digests -> preferences.edit().putStringSet(PREFS_DIGESTS, digests).apply() }, + ) + private val _offer = MutableStateFlow(null) + val offer: StateFlow = _offer.asStateFlow() + private var hasSnapshot = false + private var lastSnapshot: String? = null + + fun check(text: String?) { + val generation = synchronized(requestLock) { + val changed = if (hasSnapshot && text == lastSnapshot) { + false + } else { + hasSnapshot = true + lastSnapshot = text + true + } + if (!changed) return + invalidateIncoming() + gate.invalidate().also { _offer.value = null } + } + if (text.isNullOrBlank() || !clipboardPgnLengthMayFit(text)) return + scope.launch { + val bytes = clipboardUtf8(text) + if (!clipboardPgnWithinLimit(bytes.size)) return@launch + val digest = clipboardSha256(bytes) + val games = try { + library.countPgnGames(bytes) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + null + } + if (games == null) return@launch + val offer = ClipboardOffer(bytes, games, digest, generation) + synchronized(requestLock) { + if (gate.publish(offer)) { + _offer.value = offer + } + } + } + } + + fun accept(offer: ClipboardOffer): ClipboardAccept? = synchronized(requestLock) { + gate.accept(offer)?.also { _offer.value = null } + } + + fun dismiss(offer: ClipboardOffer) { + synchronized(requestLock) { + if (gate.dismiss(offer)) { + _offer.value = null + } + } + } + + fun canPublish(accept: ClipboardAccept): Boolean = synchronized(requestLock) { gate.canPublish(accept) } + + fun finish(accept: ClipboardAccept, success: Boolean): Boolean = synchronized(requestLock) { + val finished = gate.finish(accept, success) + if (finished && !success) { + hasSnapshot = false + lastSnapshot = null + } + finished + } +} + +internal class ClipboardPromptGate( + decided: Set = emptySet(), + private val onDecide: (Set) -> Unit = {}, +) { + private val decided = HashSet(decided) + private var generation = 0L + private var offer: ClipboardOffer? = null + private var accepted: ClipboardAccept? = null + + @Synchronized + fun invalidate(): Long { + generation += 1 + offer = null + accepted = null + return generation + } + + @Synchronized + fun publish(offer: ClipboardOffer): Boolean { + if (offer.generation != generation || offer.digest in decided || accepted != null) return false + this.offer = offer + return true + } + + @Synchronized + fun accept(offer: ClipboardOffer): ClipboardAccept? { + if (this.offer != offer || accepted != null) return null + val accept = ClipboardAccept(offer.bytes, offer.digest, offer.generation) + accepted = accept + this.offer = null + return accept + } + + @Synchronized + fun dismiss(offer: ClipboardOffer): Boolean { + if (this.offer != offer) return false + this.offer = null + decide(offer.digest) + return true + } + + @Synchronized + fun canPublish(accept: ClipboardAccept): Boolean = + accepted == accept && accept.generation == generation + + @Synchronized + fun finish(accept: ClipboardAccept, success: Boolean): Boolean { + if (accepted != accept || accept.generation != generation) return false + accepted = null + if (success) { + decide(accept.digest) + } else { + invalidate() + } + return true + } + + private fun decide(digest: String) { + if (decided.add(digest)) onDecide(decided.toSet()) + } +} + +internal fun clipboardPgnLengthMayFit(text: String): Boolean = text.length <= CLIPBOARD_PGN_MAX_BYTES + +internal fun clipboardUtf8(text: String): ByteArray = text.toByteArray(Charsets.UTF_8) + +internal fun clipboardSha256(bytes: ByteArray): String = + MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + +internal fun clipboardPgnWithinLimit(size: Int): Boolean = size <= CLIPBOARD_PGN_MAX_BYTES diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineFiles.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineFiles.kt new file mode 100644 index 0000000..b078696 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineFiles.kt @@ -0,0 +1,55 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.StateFlow +import java.io.File + +/// Stockfish and its network (android-ui.md §8). The executable is a "library" of the +/// APK; the network is a file in the app's storage: copied from the APK in the "full" +/// build, downloaded on request in the "light" one, checked by its SHA-256 either way +/// ([CheckedDownload]). +class EngineFiles(private val context: Context, scope: CoroutineScope) { + private val download = CheckedDownload( + context, + scope, + FileSpec( + dir = "engine", + name = BuildConfig.NET_NAME, + url = BuildConfig.NET_URL, + size = BuildConfig.NET_SIZE, + sha256 = BuildConfig.NET_SHA256, + title = context.getString(R.string.download_title), + prefs = "engine", + ), + ) + val net: File get() = download.file + + /// The executable, unpacked by the installer (useLegacyPackaging). + val executable: String get() = context.applicationInfo.nativeLibraryDir + "/libstockfish.so" + + val state: StateFlow get() = download.state + + val builtIn: Boolean get() = BuildConfig.NET_BUILT_IN + + /// True when the phone is on a metered (mobile) connection right now. + fun metered(): Boolean = download.metered() + + /// Gets the network ready: from the APK, or from the internet. + fun prepare() { + if (builtIn) download.installFrom { context.assets.open(BuildConfig.NET_NAME) } else download.download() + } + + /// Keeps the network of the full build in the app's storage, so that it stays after + /// the app is updated to the light build (android-ui.md §25.6). False when it could + /// not (no space): the light build then offers the download, as always. + suspend fun keepBuiltIn(): Boolean = !builtIn || download.installNow { context.assets.open(BuildConfig.NET_NAME) } + + /// Stops a download and throws away what came. + fun cancel() = download.cancel() + + /// Removes a downloaded network (Settings → "Delete the engine"). + fun delete() = download.delete() +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt new file mode 100644 index 0000000..ebc0025 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt @@ -0,0 +1,230 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.os.SystemClock +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import uniffi.mobile_api.Analysis +import uniffi.mobile_api.Analyzer +import uniffi.mobile_api.GameData + +/// The position for the engine: where the history starts and the moves since then. +data class EnginePosition(val startFen: String, val moves: List) + +/// The history of a node, so the engine sees repetitions; after a training null move +/// ("--") it starts again from the position as a FEN (android-ui.md §8, AGENTS.md). +fun enginePosition(game: GameData, node: Int): EnginePosition { + val path = ArrayList() + var n: Int? = node + while (n != null) { + path.add(n) + n = game.nodes[n].parent?.toInt() + } + path.reverse() + var start = game.nodes[0].fen + val moves = ArrayList() + for (id in path.drop(1)) { + val m = game.nodes[id] + if (m.uci.isEmpty()) { + start = m.fen + moves.clear() + } else { + moves.add(m.uci) + } + } + return EnginePosition(start, moves) +} + +sealed interface EngineStatus { + data object Off : EngineStatus + data object Starting : EngineStatus + /// Thinking about the current position. + data object Thinking : EngineStatus + /// The time per position is over; "Deeper" thinks on. + data object Paused : EngineStatus + /// The engine stopped answering or does not run on this phone. + data class Failed(val notStarting: Boolean) : EngineStatus +} + +/// What the engine said, and about which position: the screen shows it only while that +/// position is on the board, so an old evaluation never appears for a new one, not +/// even for a frame. +data class EngineView(val position: EnginePosition, val analysis: Analysis) + +/// The engine while a game is on the screen: one Stockfish process, the analysis of the +/// shown position only. +class EngineSession(private val files: EngineFiles, private val scope: CoroutineScope) { + private val _status = MutableStateFlow(EngineStatus.Off) + val status: StateFlow = _status.asStateFlow() + private val _analysis = MutableStateFlow(null) + val analysis: StateFlow = _analysis.asStateFlow() + + private val lock = Mutex() + @Volatile private var analyzer: Analyzer? = null + private var loop: Job? = null + private var timer: Job? = null + + /// The search whose snapshots are taken, and its position (set together). + private data class Search(val id: ULong, val position: EnginePosition) + @Volatile private var search: Search? = null + private var position: EnginePosition? = null + private var prefs = Prefs() + + /// Bumped by [shutdown]: work queued before it is dropped instead of starting the + /// engine again. + @Volatile private var generation = 0 + + /// Starts the engine (if it is not running) and analyses `pos`. + fun show(pos: EnginePosition, p: Prefs) { + prefs = p + val changed = pos != position + position = pos + val gen = generation + scope.launch { + lock.withLock { + if (gen != generation) return@withLock + val a = analyzer ?: startLocked(gen) ?: return@withLock + // The same position again (the screen redrawn, the time over) stays as it is. + if (changed || _status.value == EngineStatus.Starting) analyzeLocked(a, pos) + } + } + } + + /// Stops thinking (a mate or stalemate on the board); the process stays for the next + /// position. + fun pause() { + position = null + search = null + _analysis.value = null + timer?.cancel() + val gen = generation + scope.launch { + lock.withLock { + if (gen != generation) return@withLock + val a = analyzer ?: return@withLock + withContext(Dispatchers.IO) { a.stop() } + _status.value = EngineStatus.Paused + } + } + } + + /// Thinks on about the same position after the time ran out. + fun deeper() { + val pos = position ?: return + val gen = generation + scope.launch { + lock.withLock { + if (gen == generation) analyzer?.let { analyzeLocked(it, pos) } + } + } + } + + /// Quits the process (the screen went away, the button was turned off). + fun shutdown() { + generation++ + position = null + search = null + _analysis.value = null + _status.value = EngineStatus.Off + loop?.cancel() + timer?.cancel() + // Taken now, so that a show() right after it starts a new engine. + val a = analyzer ?: return + analyzer = null + scope.launch(Dispatchers.IO) { + lock.withLock { + a.quit() + a.close() + } + } + } + + private suspend fun startLocked(gen: Int): Analyzer? { + _status.value = EngineStatus.Starting + val a = withContext(Dispatchers.IO) { + runCatching { + Analyzer.start(files.executable, files.net.path, prefs.engineThreads.toUInt(), prefs.engineHashMb.toUInt()) + } + }.getOrElse { + if (gen == generation) _status.value = EngineStatus.Failed(notStarting = true) + return null + } + if (gen != generation) { + // Turned off while it was starting. + withContext(Dispatchers.IO) { + a.quit() + a.close() + } + return null + } + analyzer = a + loop = scope.launch(Dispatchers.IO) { poll(a) } + return a + } + + private suspend fun analyzeLocked(a: Analyzer, pos: EnginePosition) { + search = null + val id = withContext(Dispatchers.IO) { + runCatching { a.analyze(pos.startFen, pos.moves, prefs.engineLines.toUInt()) } + }.getOrElse { + _status.value = EngineStatus.Failed(notStarting = false) + return + } + val s = Search(id, pos) + search = s + _status.value = EngineStatus.Thinking + timer?.cancel() + if (prefs.engineSeconds > 0) { + timer = scope.launch { + delay(prefs.engineSeconds * 1000L) + lock.withLock { + if (search == s && analyzer === a) { + withContext(Dispatchers.IO) { a.stop() } + _status.value = EngineStatus.Paused + } + } + } + } + } + + private suspend fun poll(a: Analyzer) { + // What the engine said last and was not shown yet. + var held: EngineView? = null + var shown = 0L + while (scope.isActive && analyzer === a) { + // A short wait: analyze() waits for the engine handle while this holds it. + val snapshot = try { + a.poll(40u) + } catch (e: Exception) { + if (analyzer === a) _status.value = EngineStatus.Failed(notStarting = false) + return + } + val s = search + if (snapshot != null && s != null && snapshot.search == s.id && analyzer === a) { + held = EngineView(s.position, snapshot) + } + // The screen follows the engine a few times a second, not at every word of + // it; the first words about a new position are shown at once. + val next = held ?: continue + val now = SystemClock.uptimeMillis() + if (now - shown >= SHOW_EVERY_MS || next.position != _analysis.value?.position) { + _analysis.value = next + held = null + shown = now + } + } + } + + private companion object { + const val SHOW_EVERY_MS = 200L + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Language.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Language.kt new file mode 100644 index 0000000..f494e66 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Language.kt @@ -0,0 +1,44 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.app.LocaleManager +import android.content.Context +import android.content.res.Configuration +import android.os.Build +import android.os.LocaleList + +/// The interface languages; "" follows the system (android-ui.md §9). +val LANGUAGES = listOf("", "en", "ru", "de", "fr", "es", "it", "pt", "uz", "kk") + +/// The language chosen in the app. Android 13+ keeps it itself (and shows it in the +/// system settings of the app); on Android 12 the app keeps it and applies it to its +/// activity. +object Language { + private const val KEY = "language" + + fun get(context: Context): String = if (Build.VERSION.SDK_INT >= 33) { + context.getSystemService(LocaleManager::class.java).applicationLocales.get(0)?.language ?: "" + } else { + context.getSharedPreferences("settings", Context.MODE_PRIVATE).getString(KEY, "") ?: "" + } + + /// Returns true when the activity has to be recreated to show it (Android 12). + fun set(context: Context, tag: String): Boolean { + if (Build.VERSION.SDK_INT >= 33) { + context.getSystemService(LocaleManager::class.java).applicationLocales = + if (tag.isEmpty()) LocaleList.getEmptyLocaleList() else LocaleList.forLanguageTags(tag) + return false + } + context.getSharedPreferences("settings", Context.MODE_PRIVATE).edit().putString(KEY, tag).apply() + return true + } + + /// The activity's context in the chosen language (Android 12 only). + fun wrap(base: Context): Context { + if (Build.VERSION.SDK_INT >= 33) return base + val tag = base.getSharedPreferences("settings", Context.MODE_PRIVATE).getString(KEY, "") ?: "" + if (tag.isEmpty()) return base + val config = Configuration(base.resources.configuration) + config.setLocales(LocaleList.forLanguageTags(tag)) + return base.createConfigurationContext(config) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt new file mode 100644 index 0000000..e247bc9 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt @@ -0,0 +1,663 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.OpenableColumns +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import uniffi.mobile_api.ApiException +import uniffi.mobile_api.Database +import uniffi.mobile_api.FolderFile +import uniffi.mobile_api.openBytes +import uniffi.mobile_api.openChessbase +import uniffi.mobile_api.openFile +import uniffi.mobile_api.openPath +import uniffi.mobile_api.ownCreate +import uniffi.mobile_api.ownRemove +import uniffi.mobile_api.ownSave +import java.io.File +import java.util.UUID + +/// Where a database comes from. +@Serializable +enum class Source { + /// One of the sample games of the desktop app, inside the app (assets/examples). + Sample, + + /// A file the user picked, or found in a picked folder; read in place through its + /// persisted permission (of the file, or of the folder: [DbEntry.tree]). + File, + + /// A ChessBase database (`.cbh` with `.cbg`, `.cba`, … beside it) in a picked folder. + ChessBase, + + /// A copy kept inside the app (`files/copies/`): games pasted from the clipboard, a + /// file opened from another app, which gives access to it only for a while. + Copy, + + /// A player's games downloaded from Lichess and Chess.com (`files/online/`, with the + /// state of the download beside it, android-ui.md §23). + Online, + + /// The user's own database (`files/own/`, android-play.md §30): the only file the app + /// writes, and only on "Save". + Own, +} + +/// A database on the list. Its file is never changed, except an own database's. +@Serializable +data class DbEntry( + val id: String, + val name: String, + val source: Source, + /// The asset path of a sample, the content URI of a file; for a ChessBase database, + /// the URI of the folder it is in; for a copy, its file's name in `files/copies/`. + val location: String, + /// The file's name, for its extension (PGN, .zip, .7z, .cbv, .cbh). + val fileName: String, + /// The picked folder whose permission covers this database (none for a picked file). + val tree: String? = null, + /// The file's size when it was added: with the name, how the same file is known when + /// it is picked again through another way (a folder, or on its own). + val size: Long? = null, + val games: Int? = null, + val format: String? = null, + /// A sample shows the name of the current language until it is renamed (displayName). + val renamed: Boolean = false, + /// A copy's SHA-256: the same file opened again is not copied twice. A sample's: of + /// the text its number of games was taken from (a new app may bring a new text). + val sha256: String? = null, + /// A downloaded database: when its last download finished (Unix seconds). + val updated: Long? = null, +) + +/// Text or a file with no games in it. +class NoGames : Exception() + +/// A database found in a picked folder, offered to be added. +data class Found( + val name: String, + val fileName: String, + /// What [DbEntry.location] becomes. + val location: String, + val source: Source, + /// Where it lies inside the picked folder ("" at its top), shown with the name. + val path: String, + val size: Long? = null, + /// A ChessBase database without its games file (`.cbg`): it cannot be opened. + val incomplete: Boolean = false, + /// Already on the list. + val added: Boolean = false, +) + +/// A file of a ChessBase database is not beside its `.cbh` any more. +class MissingPart(val file: String) : Exception(file) + +/// Names as people sort them: "g2" before "g10", letters without case. +fun naturalOrder(a: String, b: String): Int { + val chunk = Regex("\\d+|\\D+") + val x = chunk.findAll(a.lowercase()).map { it.value }.toList() + val y = chunk.findAll(b.lowercase()).map { it.value }.toList() + for (i in 0 until minOf(x.size, y.size)) { + val (p, q) = x[i] to y[i] + val c = if (p[0].isDigit() && q[0].isDigit()) { + compareValuesBy(p, q, { it.trimStart('0').length }, { it.trimStart('0') }) + } else { + p.compareTo(q) + } + if (c != 0) return c + } + return x.size - y.size +} + +/// What a picked folder holds. +data class FolderScan(val tree: Uri, val name: String, val found: List) + +/// The databases on the list and the open ones (docs/design/android-ui.md §3). +class Library(private val context: Context) { + private val file = File(context.filesDir, "library.json") + private val copies = File(context.filesDir, "copies") + /// Downloaded databases (android-ui.md §23). + val onlineDir = File(context.filesDir, "online") + /// The user's own databases (android-play.md §30). + val ownDir = File(context.filesDir, "own") + private val json = Json { ignoreUnknownKeys = true } + private val _entries = MutableStateFlow(load()) + val entries: StateFlow> = _entries.asStateFlow() + + /// Open databases by entry id (they are small: phone-sized). + private val open = HashMap() + private val lock = Mutex() + + /// Taken off the list, "Undo" still offered: their access is kept. + private val pending = ArrayList() + + init { + releaseUnused() + // A download cut short by a closed app wrote games the list does not know of yet. + update { list -> list.map(::withOnlineState) } + } + + /// A downloaded database with the number of games and the time of its last download + /// as its state file has them (they change while the list does not look). + private fun withOnlineState(e: DbEntry): DbEntry { + if (e.source != Source.Online) return e + val info = uniffi.mobile_api.onlineDatabase(onlineFile(e).path) ?: return e + return e.copy(games = info.games.toInt(), updated = info.updated ?: e.updated) + } + + /// Gives back the access to files and folders no database on the list uses (a + /// folder picked, then the app closed before anything was added from it; the app + /// closed while "Undo" was offered). + private fun releaseUnused() { + val kept = _entries.value.filter { it.source == Source.Copy }.map { it.location }.toSet() + copies.listFiles()?.filter { it.name !in kept }?.forEach { it.delete() } + // A downloaded database left behind (the app closed while "Undo" was offered). + // Names may hold dots ("Name (Lichess + Chess.com).pgn"): whole names are compared. + val online = _entries.value.filter { it.source == Source.Online }.flatMap { + val stem = it.location.removeSuffix(".pgn") + listOf("$stem.pgn", "$stem.online.json", "$stem.online.lock") + }.toSet() + onlineDir.listFiles()?.filter { it.name !in online }?.forEach { it.delete() } + // An own database deleted while its "Undo" was offered, the app closed meanwhile. + val own = _entries.value.filter { it.source == Source.Own }.map { it.location }.toSet() + ownDir.listFiles()?.filter { it.name !in own }?.forEach { it.delete() } + val used = _entries.value.mapNotNull { it.tree ?: it.location.takeIf { _ -> it.source == Source.File || it.source == Source.ChessBase } }.toSet() + for (p in context.contentResolver.persistedUriPermissions) { + if (p.uri.toString() !in used) { + runCatching { context.contentResolver.releasePersistableUriPermission(p.uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } + } + } + } + + private fun load(): List { + if (!file.exists()) return samples().also { save(it) } + return runCatching { json.decodeFromString>(file.readText()) }.getOrDefault(emptyList()) + } + + private fun save(list: List) { + val tmp = File(file.path + ".tmp") + tmp.writeText(json.encodeToString(list)) + tmp.renameTo(file) + } + + private fun update(change: (List) -> List) { + val next = change(_entries.value) + _entries.value = next + save(next) + } + + /// The sample games of the desktop app: on the list from the first start. + private fun samples(): List { + val names = listOf( + "classics.pgn" to context.getString(io.github.vrubelroman.chesspenguin.R.string.sample_classics), + "alekhine.pgn" to context.getString(io.github.vrubelroman.chesspenguin.R.string.sample_alekhine), + ) + return names.map { (f, name) -> DbEntry(id = "sample-$f", name = name, source = Source.Sample, location = "examples/$f", fileName = f) } + } + + /// Counts the samples on the list not counted yet, or counted in a text other than + /// the one in this app: an update of the app brings a sample's new version (more + /// games), read from the app itself as ever, and its row shows it at once. + suspend fun countSamples() { + for (e in _entries.value.filter { it.source == Source.Sample }) { + if (e.games != null && e.sha256 == withContext(Dispatchers.IO) { sha256(sampleBytes(e)) }) continue + database(e.id) + } + } + + private fun sampleBytes(e: DbEntry): ByteArray = context.assets.open(e.location).use { it.readBytes() } + + /// Puts the sample games back on the list (those not on it), at its end. + fun addSamples() = update { list -> list + samples().filter { s -> list.none { it.id == s.id } } } + + fun entry(id: String): DbEntry? = _entries.value.firstOrNull { it.id == id } + + /// Adds a file picked with the system picker; its read permission is kept across + /// restarts. Returns the new entry, or the one already on the list. + fun addFile(uri: Uri): DbEntry { + // Taken again for a file already on the list: picking it grants a new permission. + runCatching { + context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + val fileName = displayName(uri) ?: "database.pgn" + val size = fileSize(uri) + _entries.value.firstOrNull { it.location == uri.toString() || sameFile(it, fileName, size) }?.let { + // The entry keeps its own way to the file; the new permission is not needed. + if (it.location != uri.toString()) { + runCatching { context.contentResolver.releasePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } + } + open.remove(it.id)?.close() + return it + } + val entry = DbEntry( + id = UUID.randomUUID().toString(), + name = fileName.substringBeforeLast('.'), + source = Source.File, + location = uri.toString(), + fileName = fileName, + size = size, + ) + update { it + 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 + /// 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 + /// stays behind then. + suspend fun addCopy(fileName: String, input: java.io.InputStream, name: (Database) -> String): DbEntry = withContext(Dispatchers.IO) { + copies.mkdirs() + val ext = fileName.substringAfterLast('.', "pgn").lowercase() + val tmp = File(copies, "incoming-${UUID.randomUUID()}.$ext") + try { + val digest = java.security.MessageDigest.getInstance("SHA-256") + tmp.outputStream().use { out -> + val buf = ByteArray(256 * 1024) + while (true) { + val n = input.read(buf) + if (n < 0) break + out.write(buf, 0, n) + digest.update(buf, 0, n) + } + } + val sum = digest.digest().joinToString("") { "%02x".format(it) } + lock.withLock { + copyWithDigest(_entries.value, sum)?.let { return@withContext it } + } + val id = UUID.randomUUID().toString() + val kept = File(copies, "$id.$ext") + if (!tmp.renameTo(kept)) throw java.io.IOException("cannot keep the copy") + val db = try { + openFile(fileName, android.os.ParcelFileDescriptor.open(kept, android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd()) + } catch (e: ApiException.Empty) { + kept.delete() + throw NoGames() + } catch (t: Throwable) { + kept.delete() + throw t + } + // PGN reading is lenient: any text is one "game" of a comment. A game counts + // when it has a tag or a move. + if (db.len() == 0u || (db.len() == 1u && db.game(0u).let { it.tags.isEmpty() && it.nodes.size <= 1 })) { + db.close() + kept.delete() + throw NoGames() + } + val entry = DbEntry( + id = id, + name = name(db), + source = Source.Copy, + location = kept.name, + fileName = fileName, + size = kept.length(), + games = db.len().toInt(), + format = db.format(), + sha256 = sum, + ) + lock.withLock { + copyWithDigest(_entries.value, sum)?.let { existing -> + db.close() + kept.delete() + return@withContext existing + } + open[id] = db + update { it + entry } + } + entry + } finally { + tmp.delete() + } + } + + /// The file of a downloaded database. + fun onlineFile(e: DbEntry): File = File(onlineDir, e.location) + + /// The file of an own database. + fun ownFile(e: DbEntry): File = File(ownDir, e.location) + + /// A new empty own database named `name`, first among the own ones. + suspend fun createOwn(name: String): DbEntry = withContext(Dispatchers.IO) { + val id = UUID.randomUUID().toString() + val entry = DbEntry(id = id, name = name, source = Source.Own, location = "$id.pgn", fileName = "$id.pgn", games = 0, format = "PGN") + ownCreate(ownFile(entry).path) + update { list -> listOf(entry) + list } + entry + } + + /// Saves the game `pgn` into the own database `id`: as game `index`, or at the end. + /// Returns its number; the database is read again when next opened. + suspend fun saveOwn(id: String, index: UInt?, pgn: String): UInt = lock.withLock { + val e = entry(id)?.takeIf { it.source == Source.Own } ?: throw IllegalArgumentException("not an own database") + val n = withContext(Dispatchers.IO) { ownSave(ownFile(e).path, index, pgn) } + open.remove(id) + update { list -> list.map { if (it.id == id) it.copy(games = if (index == null) (it.games ?: 0) + 1 else it.games) else it } } + n + } + + /// Takes game `index` out of the own database `id`. + suspend fun removeOwnGame(id: String, index: UInt) = lock.withLock { + val e = entry(id)?.takeIf { it.source == Source.Own } ?: return@withLock + withContext(Dispatchers.IO) { ownRemove(ownFile(e).path, index) } + open.remove(id) + update { list -> list.map { if (it.id == id) it.copy(games = ((it.games ?: 1) - 1).coerceAtLeast(0)) else it } } + } + + /// Puts a downloaded database (a file of [onlineDir]) on the list, or gives its entry. + fun addOnline(file: File): DbEntry = synchronized(this) { + _entries.value.firstOrNull { it.source == Source.Online && it.location == file.name }?.let { return it } + val entry = DbEntry( + id = UUID.randomUUID().toString(), + name = file.name.substringBeforeLast('.'), + source = Source.Online, + location = file.name, + fileName = file.name, + games = 0, + format = "PGN", + ) + update { it + entry } + entry + } + + /// A downloaded database got new games: it is read again when next opened. The old + /// one is not closed: a screen may still show it; it is freed once nothing holds it. + suspend fun downloaded(id: String, games: Int, updated: Long?) { + lock.withLock { + open.remove(id) + update { list -> list.map { if (it.id == id) it.copy(games = games, updated = updated ?: it.updated) else it } } + } + } + + /// Takes a downloaded database that got no games off the list, with its files. + fun dropEmpty(id: String) { + val e = entry(id) ?: return + update { it.filterNot { x -> x.id == id } } + open.remove(id)?.close() + uniffi.mobile_api.deleteOnlineDatabase(onlineFile(e).path) + } + + fun rename(id: String, name: String) = update { list -> list.map { if (it.id == id) it.copy(name = name, renamed = true) else it } } + + /// Takes the database off the list (the file stays where it is). Returns its place, + /// for "Undo"; the access to the file is kept until [forget]. + fun remove(id: String): Pair? { + val list = _entries.value + val i = list.indexOfFirst { it.id == id } + if (i < 0) return null + val e = list[i] + pending += e + update { it.filterNot { x -> x.id == id } } + open.remove(id)?.close() + return i to e + } + + /// Gives the access to a removed file back to the system, once "Undo" is gone. + fun forget(entry: DbEntry) { + pending.remove(entry) + if (entry.source == Source.Sample) return + if (entry.source == Source.Copy) { + File(copies, entry.location).delete() + return + } + if (entry.source == Source.Online) { + uniffi.mobile_api.deleteOnlineDatabase(onlineFile(entry).path) + return + } + // The only copy of the user's games: gone once "Undo" is (asked before when not + // empty, android-play.md §30.3). + if (entry.source == Source.Own) { + ownFile(entry).delete() + return + } + // The permission of a folder is given back with the last of its databases, also + // counting those whose "Undo" is still offered. + val granted = entry.tree ?: entry.location + if ((_entries.value + pending).any { (it.tree ?: it.location) == granted }) return + runCatching { + context.contentResolver.releasePersistableUriPermission(Uri.parse(granted), Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } + + /// Keeps the read permission of a picked folder, for the databases added from it + /// (given back by [forgetFolder] when none is). + fun keepFolder(tree: Uri) { + runCatching { + context.contentResolver.takePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } + + /// Looks for databases in a picked folder and in the folders inside it (two levels + /// down): PGN files, archives, ChessBase archives (.cbv) and ChessBase databases. + suspend fun scanFolder(tree: Uri): FolderScan = withContext(Dispatchers.IO) { + val rootId = DocumentsContract.getTreeDocumentId(tree) + val rootName = childName(DocumentsContract.buildDocumentUriUsingTree(tree, rootId)) ?: "" + val list = _entries.value + val found = ArrayList() + fun visit(dirId: String, path: String, depth: Int) { + val children = children(tree, dirId) + val names = children.filter { !it.dir }.map { it.name }.toSet() + fun has(name: String) = names.any { it.equals(name, ignoreCase = true) } + for (c in children.sortedWith { a, b -> naturalOrder(a.name, b.name) }) { + if (c.dir) continue + val ext = c.name.substringAfterLast('.', "").lowercase() + val stem = c.name.substringBeforeLast('.') + when (ext) { + "pgn", "zip", "7z", "cbv" -> { + // A ChessBase archive beside its unpacked database is the same + // database: the unpacked one is offered. + if (ext == "cbv" && has("$stem.cbh") && has("$stem.cbg")) continue + val uri = DocumentsContract.buildDocumentUriUsingTree(tree, c.id).toString() + val added = list.any { it.location == uri || sameFile(it, c.name, c.size) } + found += Found(stem, c.name, uri, Source.File, path, size = c.size, added = added) + } + "cbh" -> { + val dir = DocumentsContract.buildDocumentUriUsingTree(tree, dirId).toString() + found += Found( + stem, c.name, dir, Source.ChessBase, path, + incomplete = !has("$stem.cbg"), + added = list.any { it.source == Source.ChessBase && it.location == dir && it.fileName == c.name }, + ) + } + } + } + if (depth < 2) { + for (c in children.filter { it.dir }.sortedWith { a, b -> naturalOrder(a.name, b.name) }) { + visit(c.id, if (path.isEmpty()) c.name else "$path/${c.name}", depth + 1) + } + } + } + visit(rootId, "", 0) + FolderScan(tree, rootName, found) + } + + /// Gives a scanned folder's permission back when none of its databases is on the list. + fun forgetFolder(tree: Uri) { + if ((_entries.value + pending).any { it.tree == tree.toString() }) return + runCatching { + context.contentResolver.releasePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } + + /// Puts the chosen databases of a folder on the list, at its end. + fun addFound(tree: Uri, chosen: List) = update { list -> + list + chosen.filter { !it.added && !it.incomplete }.map { + DbEntry( + id = UUID.randomUUID().toString(), + name = it.name, + source = it.source, + location = it.location, + fileName = it.fileName, + tree = tree.toString(), + size = it.size, + ) + } + } + + private class Child(val id: String, val name: String, val dir: Boolean, val size: Long?) + + private fun children(tree: Uri, dirId: String): List { + val uri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, dirId) + val columns = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_SIZE, + ) + return runCatching { + context.contentResolver.query(uri, columns, null, null, null)?.use { c -> + buildList { + while (c.moveToNext()) { + val name = c.getString(1) ?: continue + val size = if (c.isNull(3)) null else c.getLong(3) + add(Child(c.getString(0), name, c.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR, size)) + } + } + } + }.getOrNull() ?: emptyList() + } + + private fun childName(uri: Uri): String? = runCatching { + context.contentResolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } + }.getOrNull() + + /// A file for reading. A file deleted from a picked folder makes the provider throw + /// IllegalArgumentException ("is not a child of the tree"): it is a missing file. + private fun openDocument(uri: Uri): android.os.ParcelFileDescriptor = try { + context.contentResolver.openFileDescriptor(uri, "r") ?: throw java.io.FileNotFoundException(uri.toString()) + } catch (e: IllegalArgumentException) { + throw java.io.FileNotFoundException(e.message) + } + + /// The files of a ChessBase database: those beside its `.cbh` with the same name. + private fun openChessBase(e: DbEntry): Database { + val tree = Uri.parse(e.tree ?: throw ApiException.Io(detail = "no access to the folder")) + val dirId = DocumentsContract.getDocumentId(Uri.parse(e.location)) + val stem = e.fileName.substringBeforeLast('.') + // Names may differ in case (sets copied from Windows: "Base.CBH", "base.cbg"). + val parts = children(tree, dirId).filter { !it.dir && it.name.substringBeforeLast('.').equals(stem, ignoreCase = true) } + if (parts.none { it.name.equals(e.fileName, ignoreCase = true) }) throw java.io.FileNotFoundException(e.fileName) + if (parts.none { it.name.substringAfterLast('.').equals("cbg", ignoreCase = true) }) throw MissingPart("$stem.cbg") + // All opened first: a file that cannot be opened leaves none of them open. + val opened = ArrayList>() + try { + for (c in parts) { + val pfd = openDocument(DocumentsContract.buildDocumentUriUsingTree(tree, c.id)) + opened += c.name to pfd + } + } catch (t: Throwable) { + opened.forEach { it.second.close() } + throw t + } + // The descriptors go over to the core, which closes them. + return openChessbase(e.fileName, opened.map { (name, pfd) -> FolderFile(name, pfd.detachFd()) }) + } + + fun restore(place: Int, entry: DbEntry) { + pending.remove(entry) + // A download may have gone on while it was off the list. + update { it.toMutableList().apply { add(place.coerceIn(0, size), withOnlineState(entry)) } } + } + + /// The same file on the list, picked through another way (its URI differs). + private fun sameFile(e: DbEntry, fileName: String, size: Long?) = + e.source == Source.File && size != null && e.size == size && e.fileName == fileName + + private fun fileSize(uri: Uri): Long? = runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { c -> + if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null + } + }.getOrNull() + + private fun displayName(uri: Uri): String? = runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } + }.getOrNull() + + /// The games of a database that `query` finds, in the order the list shows them: a + /// downloaded database from the most recent game down (android-ui.md §23), the others + /// as in the file. Slow for a big database: call it off the main thread. + fun listed(id: String, db: Database, query: String): List { + val found = db.find(query) + return if (entry(id)?.source == Source.Online) db.newestFirst(found) else found + } + + /// The open database of an entry (opened in the background the first time). + suspend fun database(id: String): Result = lock.withLock { + open[id]?.let { return@withLock Result.success(it) } + val e = entry(id) ?: return@withLock Result.failure(IllegalArgumentException("no database $id")) + var text: String? = e.sha256 + val result = withContext(Dispatchers.IO) { + runCatching { + when (e.source) { + Source.Sample -> sampleBytes(e).let { bytes -> + text = sha256(bytes) + openBytes(e.fileName, bytes) + } + Source.File -> openFile(e.fileName, openDocument(Uri.parse(e.location)).detachFd()) + Source.ChessBase -> openChessBase(e) + Source.Copy -> openFile( + e.fileName, + android.os.ParcelFileDescriptor.open(File(copies, e.location), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(), + ) + Source.Online -> openFile( + e.fileName, + android.os.ParcelFileDescriptor.open(onlineFile(e), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(), + ) + Source.Own -> openPath(ownFile(e).path) + } + } + } + result.onSuccess { db -> + open[id] = db + val games = db.len().toInt() + val format = db.format() + val sum = text + if (e.games != games || e.format != format || e.sha256 != sum) { + update { list -> list.map { if (it.id == id) it.copy(games = games, format = format, sha256 = sum) else it } } + } + } + result + } +} + +internal fun firstPgnGameIsMeaningful(count: Int, tags: Int, nodes: Int): Boolean = + count > 0 && (tags > 0 || nodes > 1) + +internal fun copyWithDigest(entries: List, digest: String): DbEntry? = + entries.firstOrNull { it.source == Source.Copy && it.sha256 == digest } + +private fun sha256(bytes: ByteArray): String = + java.security.MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaFiles.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaFiles.kt new file mode 100644 index 0000000..18580d6 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaFiles.kt @@ -0,0 +1,24 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import io.github.vrubelroman.chesspenguin.R +import kotlinx.coroutines.CoroutineScope + +/// Maia's weights (android-play.md §31.2): the small model (`maia3-5m.pt`, 21 MB) of a +/// pinned revision, downloaded on request from the authors' Hugging Face page — the +/// file is theirs, not shipped in the APK. The same file as the desktop app's. +class MaiaFiles(context: Context, scope: CoroutineScope) { + val download = CheckedDownload( + context, + scope, + FileSpec( + dir = "maia", + name = "maia3-5m.pt", + url = "https://huggingface.co/UofTCSSLab/Maia3-5M/resolve/b6559de2398d7140b985f28fd2c19fb5e47ddabe/maia3-5m.pt", + size = 20_968_049, + sha256 = "ba14208b2992d85502f5fb501934abf6aaaeb355e9f3fdf90e326911f562524f", + title = context.getString(R.string.maia_download_title), + prefs = "maia", + ), + ) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt new file mode 100644 index 0000000..ac49c80 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt @@ -0,0 +1,114 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.io.File + +/// A game against the computer: the opponent (Maia, or Rodent IV in the character +/// `style`), its strength, the user's colour and name; `floor`: the half-moves that came +/// from another game ("Play on from here", not taken back); `over`: it ended. +data class PlayMeta( + val strength: Int, + val userWhite: Boolean, + val name: String, + val floor: Int, + val over: Boolean = false, + val rival: Opponent = Opponent.Maia, + val style: String = "", +) + +/// The game against the computer being played (android-play.md §31.7, android-rodent.md +/// §6.5): its PGN is written after every move, so that "back" puts it aside and it +/// outlives the app being closed. One at a time. (Named when Maia was the only opponent.) +class MaiaGames(context: Context) { + private val file = File(context.filesDir, "play/current.pgn") + private val prefs = context.getSharedPreferences("play", Context.MODE_PRIVATE) + private val _current = MutableStateFlow(read()) + /// The game in hand, if any. + val current: StateFlow = _current.asStateFlow() + + private fun read(): PlayMeta? { + if (!file.isFile || !prefs.contains("strength")) return null + return PlayMeta( + strength = prefs.getInt("strength", 1500), + userWhite = prefs.getBoolean("white", true), + name = prefs.getString("name", "") ?: "", + floor = prefs.getInt("floor", 0), + over = prefs.getBoolean("over", false), + // A game put aside before Rodent came is a game against Maia. + rival = Opponent.entries.firstOrNull { it.key == prefs.getString("rival", null) } ?: Opponent.Maia, + style = prefs.getString("style", "") ?: "", + ) + } + + /// The PGN of the game in hand. + fun pgn(): String? = runCatching { file.readText() }.getOrNull() + + /// Which game is in hand: bumped by each new one (a write that ends after a rematch + /// began is not taken for the new game's). + var serial = 0 + private set + + /// A new game: it replaces the one in hand. + fun begin(pgn: String, meta: PlayMeta) { + serial++ + write(pgn) + prefs.edit() + .remove("writtenDb") + .remove("writtenIndex") + .putInt("strength", meta.strength) + .putBoolean("white", meta.userWhite) + .putString("name", meta.name) + .putInt("floor", meta.floor) + .putBoolean("over", meta.over) + .putString("rival", meta.rival.key) + .putString("style", meta.style) + .apply() + _current.value = meta + } + + /// The game after a move. + fun save(pgn: String) { + if (_current.value != null) write(pgn) + } + + /// The game ended: it is not offered to go on with any more. + fun finish(pgn: String) { + save(pgn) + // At once (commit): a game over must not come back as one to go on with. + prefs.edit().putBoolean("over", true).commit() + _current.value = _current.value?.copy(over = true) + } + + /// The game was written into its player's database: database and number there. + fun setWritten(id: String, index: UInt, game: Int) { + if (game != serial) return + prefs.edit().putString("writtenDb", id).putLong("writtenIndex", index.toLong()).commit() + } + + /// Where the game in hand was written, if it was. + fun written(): Pair? { + val id = prefs.getString("writtenDb", null) ?: return null + return id to prefs.getLong("writtenIndex", 0).toUInt() + } + + /// The game is gone (left after its end, removed by the user). + fun clear() { + file.delete() + prefs.edit().clear().apply() + _current.value = null + } + + /// Written beside and moved in: a cut-off write leaves the last move's game whole. + private fun write(pgn: String) { + file.parentFile?.mkdirs() + val tmp = File(file.path + ".tmp") + tmp.writeText(pgn) + if (!tmp.renameTo(file)) { + file.writeText(pgn) + tmp.delete() + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/OnlineDownloads.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/OnlineDownloads.kt new file mode 100644 index 0000000..a0e5b4a --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/OnlineDownloads.kt @@ -0,0 +1,114 @@ +package io.github.vrubelroman.chesspenguin.data + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import uniffi.mobile_api.DownloadState +import uniffi.mobile_api.OnlineAccount +import uniffi.mobile_api.OnlineDownload +import uniffi.mobile_api.onlineDatabase +import java.io.File +import java.util.concurrent.ConcurrentHashMap + +/// A download of a database and how it stands (or how it ended); `fresh` when the +/// database did not exist before it (its first download). +data class DownloadView(val accounts: List, val state: DownloadState, val fresh: Boolean = false) + +/// 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, val quiet: Boolean = false) + +/// 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 +/// databases shows how they go. +class OnlineDownloads(private val library: Library, private val scope: CoroutineScope) { + private val _views = MutableStateFlow>(emptyMap()) + /// By database id: the running downloads, and the last one of each database. + val views: StateFlow> = _views.asStateFlow() + + private val running = ConcurrentHashMap() + + private val _finished = MutableSharedFlow(extraBufferCapacity = 8) + /// Each download as it ends (android-ui.md §23.3: a snackbar says how it went). + val finished: SharedFlow = _finished.asSharedFlow() + + /// Where the downloaded databases are kept. + val dir: File get() = library.onlineDir + + /// 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. + fun start(accounts: List, path: String): DbEntry = run(accounts, path, false).first + + private fun run(accounts: List, path: String, quiet: Boolean): Pair { + val fresh = !File(path).exists() + val entry = library.addOnline(File(path)) + if (running.containsKey(entry.id)) return entry to null + val d = OnlineDownload.start(accounts, path) + running[entry.id] = d + val job = scope.launch(Dispatchers.IO) { + while (true) { + val s = d.state() + _views.update { it + (entry.id to DownloadView(accounts, s, fresh)) } + if (!s.running) break + delay(POLL_MS) + } + running.remove(entry.id) + d.close() + val info = onlineDatabase(path) + val games = info?.games?.toInt() ?: 0 + // 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 + 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)) } + } + return entry to job + } + + /// Fetches the games played since the last download of a database. + fun update(entry: DbEntry) { + val path = library.onlineFile(entry).path + val info = onlineDatabase(path) ?: return + 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. + fun cancel(id: String) { + running[id]?.cancel() + } + + fun isRunning(id: String): Boolean = running.containsKey(id) + + private companion object { + const val POLL_MS = 400L + const val AUTO_EVERY_MS = 10 * 60 * 1000L + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PlayerGames.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PlayerGames.kt new file mode 100644 index 0000000..66375cf --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PlayerGames.kt @@ -0,0 +1,111 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import io.github.vrubelroman.chesspenguin.R +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/// A game written into its player's database: the database, its number there (from 0), +/// and whether the database was made for it. +data class Written(val id: String, val name: String, val index: UInt, val created: Boolean) + +/// The players' databases (docs/design/player-games.md §6, decisions «Партии игрока +/// запи�ывают�� �ами»): every game against Maia goes by itself into an own database of +/// its player — «Roman — games against the computer», made at their first game; without +/// a name, «Games against the computer». Only new games are added; replacing and +/// deleting stay the user's. +class PlayerGames(private val context: Context, private val library: Library) { + private val store = context.getSharedPreferences("players", Context.MODE_PRIVATE) + private val lock = Mutex() + + /// The name as it is kept: trimmed, inner spaces single. + fun tidy(name: String): String = name.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.joinToString(" ") + + /// Names that are the same player: «Иван» and «иван ». + private fun key(name: String) = tidy(name).lowercase() + + /// The name of a new database for the player. + fun dbName(name: String): String = tidy(name).let { + if (it.isEmpty()) context.getString(R.string.player_db_shared) else context.getString(R.string.player_db_name, it) + } + + /// The player's database, while it is on the list. + fun database(name: String): DbEntry? = + store.getString("db:" + key(name), null)?.let { library.entry(it) }?.takeIf { it.source == Source.Own } + + /// Whether `id` is a player's database (a knight on its row). + fun isPlayers(id: String): Boolean = store.all.any { (k, v) -> k.startsWith("db:") && v == id } + + /// The players who played here, the last first (named ones). + fun players(): List = + (store.getString("order", "") ?: "").split('\n').filter { it.isNotEmpty() } + .mapNotNull { store.getString("name:$it", null) } + + /// The player who starts a game goes first in the list. + fun remember(name: String) { + val k = key(name) + if (k.isEmpty()) return + val order = listOf(k) + (store.getString("order", "") ?: "").split('\n').filter { it.isNotEmpty() && it != k } + store.edit().putString("name:$k", tidy(name)).putString("order", order.joinToString("\n")).apply() + } + + /// The game in hand let go unfinished (× on its card, a new game in its place, Maia + /// failing): kept in the player's database with `*` once both have moved, unless it + /// was written already or the user turned writing off. What is in hand is taken at + /// once (the caller may put a new game there right after); `then` on `scope`. + /// Whether it is written (a game without moves of both sides is not). + fun keepUnfinished(games: MaiaGames, record: Boolean, scope: CoroutineScope, then: (Written) -> Unit = {}): Boolean { + if (!wouldKeep(games, record)) return false + val m = games.current.value ?: return false + val pgn = games.pgn() ?: return false + scope.launch { runCatching { writeUnfinished(m, pgn) }.getOrNull()?.let(then) } + return true + } + + /// Whether the game in hand, let go now, would be kept. + fun wouldKeep(games: MaiaGames, record: Boolean): Boolean { + val m = games.current.value ?: return false + if (m.over || !record || games.written() != null) return false + val pgn = games.pgn() ?: return false + return plies(pgn) - m.floor >= 2 + } + + /// Half-moves of the main line. + private fun plies(pgn: String): Int { + val s = uniffi.mobile_api.GameSession.fromPgn(pgn) + try { + val d = s.data() + var n = 0 + var plies = 0 + while (true) { + n = d.nodes[n].children.firstOrNull()?.toInt() ?: return plies + plies++ + } + } finally { + s.close() + } + } + + private suspend fun writeUnfinished(m: PlayMeta, pgn: String): Written { + val s = uniffi.mobile_api.GameSession.fromPgn(pgn) + val text = try { + s.setData(listOf(uniffi.mobile_api.Tag("Termination", "Unterminated")), "*") + s.pgn() + } finally { + s.close() + } + return write(m.name, text) + } + + /// Adds `pgn` to the player's database, making it first when they have none. + suspend fun write(name: String, pgn: String): Written = lock.withLock { + val existing = database(name) + val entry = existing ?: library.createOwn(dbName(name)).also { + store.edit().putString("db:" + key(name), it.id).apply() + } + val n = library.saveOwn(entry.id, null, pgn) + Written(entry.id, entry.name, n, existing == null) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PrepSearch.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PrepSearch.kt new file mode 100644 index 0000000..ce1ed25 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PrepSearch.kt @@ -0,0 +1,129 @@ +package io.github.vrubelroman.chesspenguin.data + +import io.github.vrubelroman.chesspenguin.ui.PlayerPage +import io.github.vrubelroman.chesspenguin.ui.PlayerSummary +import io.github.vrubelroman.chesspenguin.ui.PrepContinuation +import io.github.vrubelroman.chesspenguin.ui.PrepGameMatch +import io.github.vrubelroman.chesspenguin.ui.PrepOutOfMemory +import io.github.vrubelroman.chesspenguin.ui.PrepPlayerNotFound +import io.github.vrubelroman.chesspenguin.ui.PrepPosition +import io.github.vrubelroman.chesspenguin.ui.PrepSearchFailed +import io.github.vrubelroman.chesspenguin.ui.PrepStart +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlin.coroutines.coroutineContext +import uniffi.mobile_api.Database +import uniffi.mobile_api.PrepPhase +import uniffi.mobile_api.PrepResult +import uniffi.mobile_api.PrepSearch as RustPrepSearch + +internal data class PrepQuery( + val player: String, + val white: Boolean, + val fen: String, +) + +internal fun PrepStart.query(fen: String): PrepQuery = PrepQuery(player, white, fen) + +/// The Android side of mobile-api's preparation contract. Database aggregation stays in +/// Rust; the object being closed is the search, never the library's shared Database. +internal interface PrepBackend { + suspend fun players(query: String, offset: Int, limit: Int): PlayerPage + suspend fun position(query: PrepQuery): PrepPosition + fun cancel() + fun close() +} + +internal object PrepBackends { + fun open(database: Database): PrepBackend = RustPrepBackend(database) +} + +private class RustPrepBackend(private val database: Database) : PrepBackend { + private val lock = Any() + private val playerIds = java.util.concurrent.ConcurrentHashMap() + private var active: RustPrepSearch? = null + @Volatile private var closed = false + + override suspend fun players(query: String, offset: Int, limit: Int): PlayerPage { + coroutineContext.ensureActive() + if (closed) throw CancellationException("The player list is closed") + val start = offset.coerceAtLeast(0) + val answer = database.suggestPlayers(query, start.toUInt(), limit.coerceIn(0, 200).toUInt()) + val players = answer.players.map { + PlayerSummary(it.id.toInt(), it.name, it.games.toInt(), it.whiteGames.toInt(), it.blackGames.toInt()) + } + val end = start + players.size + return PlayerPage(players, answer.total.toInt(), end.takeIf { players.isNotEmpty() && it < answer.total.toInt() }) + } + + override suspend fun position(query: PrepQuery): PrepPosition { + coroutineContext.ensureActive() + val id = findPlayer(query.player) + coroutineContext.ensureActive() + val search = synchronized(lock) { + if (closed) throw CancellationException("The position search is closed") + active?.cancel() + database.preparePosition(id, query.white, query.fen).also { active = it } + } + try { + while (true) { + val state = search.state() + when (state.phase) { + PrepPhase.GAMES, PrepPhase.INDEX, PrepPhase.SEARCH -> delay(25) + PrepPhase.READY -> return state.result?.toUi() + ?: throw PrepSearchFailed(state.failure.ifEmpty { "The position search returned no result" }) + PrepPhase.CANCELLED -> throw CancellationException("The position search was cancelled") + PrepPhase.NO_MEMORY -> throw PrepOutOfMemory() + PrepPhase.FAILED -> throw PrepSearchFailed(state.failure.ifEmpty { "The position search failed" }) + } + } + } finally { + synchronized(lock) { + if (active === search) active = null + } + search.close() + } + } + + private fun findPlayer(name: String): UInt { + playerIds[name]?.let { return it } + var offset = 0 + while (true) { + val page = database.suggestPlayers(name, offset.toUInt(), 200u) + page.players.firstOrNull { it.name == name }?.let { + playerIds[name] = it.id + return it.id + } + if (page.players.isEmpty()) break + offset += page.players.size + if (offset >= page.total.toInt()) break + } + throw PrepPlayerNotFound(name) + } + + override fun cancel() { + synchronized(lock) { active?.cancel() } + } + + override fun close() { + synchronized(lock) { + closed = true + active?.cancel() + active = null + } + } +} + +private fun PrepResult.toUi() = PrepPosition( + games = games.toInt(), + continuations = continuations.map { + PrepContinuation(it.uci, it.san, it.count.toInt(), it.wins.toInt(), it.draws.toInt(), it.losses.toInt(), it.unknown.toInt()) + }, + endedHere = ended.toInt(), + noNormalContinuation = noNormalContinuation.toInt(), + unknownResults = unknown.toInt(), + playerToMove = playerToMove, + matches = matches.map { PrepGameMatch(it.index, it.ply) }, + matchesTotal = matchesTotal.toInt(), +) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt new file mode 100644 index 0000000..d0fb7a7 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt @@ -0,0 +1,133 @@ +package io.github.vrubelroman.chesspenguin.data + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import uniffi.mobile_api.Database +import uniffi.mobile_api.GameReview +import uniffi.mobile_api.ReviewState + +/// A first guess at the speed of one engine process (one thread) before it was measured +/// on this phone. +const val GUESS_NPS = 250_000L + +/// 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 +/// job has its own engine process (the Rust side runs it on a thread of its own). +class ReviewSession(private val cacheDir: String, private val scope: CoroutineScope) { + private val _state = MutableStateFlow(null) + /// The analysis of the game shown, `null` while it loads. + val state: StateFlow = _state.asStateFlow() + + private val lock = Mutex() + private var review: GameReview? = null + private var game: Pair? = null + private var poller: Job? = null + + /// Bumped whenever another game comes: work for the old one is dropped. + @Volatile private var generation = 0 + + /// Shows the analysis of game `index` of database `db` (from the cache or its + /// `[%eval]` comments); the analysis of the game before is stopped and kept. + suspend fun open(db: String, database: Database, index: UInt) = openWith(db to index) { database.review(index, cacheDir) } + + /// The analysis of a game being changed or played (no file of its own), as it is + /// now; `stamp` names this state of it (a new stamp: the game changed). + suspend fun openSession(stamp: String, session: uniffi.mobile_api.GameSession) = openWith("session" to stamp.hashCode().toUInt()) { session.review(cacheDir) } + + private suspend fun openWith(key: Pair, make: () -> GameReview) { + if (game == key) return + val gen = ++generation + _state.value = null + lock.withLock { + closeLocked() + val r = withContext(Dispatchers.IO) { runCatching { make() }.getOrNull() } ?: return + if (gen != generation) { + withContext(Dispatchers.IO) { r.close() } + return + } + review = r + game = key + _state.value = withContext(Dispatchers.IO) { r.state() } + } + } + + /// Starts the engine on the positions without an evaluation, or on all when `full` + /// (or when the analysis is stale). The search is fixed, the same as on the desktop + /// (decisions.md, 2026-10-28). `done` gets the final state when the job ends by itself. + fun start(path: String, evalFile: String, full: Boolean, done: (ReviewState) -> Unit) { + val gen = generation + scope.launch { + lock.withLock { + val r = review ?: return@withLock + if (gen != generation) return@withLock + val started = withContext(Dispatchers.IO) { + r.start(path, evalFile, full) + } + _state.value = withContext(Dispatchers.IO) { r.state() } + if (started) poll(r, gen, done) + } + } + } + + /// Stops the engine; what it evaluated stays (and is cached). + fun cancel() { + poller?.cancel() + val gen = generation + scope.launch { + lock.withLock { + val r = review ?: return@withLock + withContext(Dispatchers.IO) { r.cancel() } + if (gen == generation) _state.value = withContext(Dispatchers.IO) { r.state() } + } + } + } + + /// The screen went away: the job stops and the object is freed. + fun close() { + generation++ + poller?.cancel() + scope.launch { lock.withLock { closeLocked() } } + } + + private suspend fun closeLocked() { + poller?.cancel() + val r = review ?: return + review = null + game = null + withContext(Dispatchers.IO) { + r.cancel() + r.close() + } + } + + /// While the job runs: its state a few times a second (the graph grows with it). + private fun poll(r: GameReview, gen: Int, done: (ReviewState) -> Unit) { + poller?.cancel() + poller = scope.launch(Dispatchers.IO) { + while (true) { + delay(POLL_MS) + val s = lock.withLock { + if (review !== r || gen != generation) null else r.state() + } ?: return@launch + _state.value = s + if (!s.running) { + done(s) + return@launch + } + } + } + } + + private companion object { + const val POLL_MS = 300L + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/RodentFiles.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/RodentFiles.kt new file mode 100644 index 0000000..8d38fe1 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/RodentFiles.kt @@ -0,0 +1,168 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import io.github.vrubelroman.chesspenguin.R +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException + +/// Rodent IV on the phone (android-rodent.md): the engine is a "library" of the APK +/// (scripts/rodent4.sh), its personalities come with the APK and are copied into its +/// home folder, its opening books are one pack downloaded on request from the authors' +/// repository ([BookPack]). The engine finds both in its home (RODENT4HOME). +class RodentFiles(private val context: Context, scope: CoroutineScope) { + /// The engine's home: `personalities/` and `books/`. + val home = File(context.filesDir, "rodent4") + + /// The executable, unpacked by the installer (useLegacyPackaging). + val executable: String get() = context.applicationInfo.nativeLibraryDir + "/librodent4.so" + + val books = BookPack(context, scope, home) + + /// Copies the personalities out of the APK when they are not there or are of another + /// version (written beside, then moved in: a cut-off copy is not taken for whole). + /// False when they could not be (no space): Rodent then does not start. + suspend fun prepare(): Boolean = withContext(Dispatchers.IO) { + val version = uniffi.mobile_api.rodentVersion() + val dir = File(home, "personalities") + val mark = File(home, "personalities.version") + if (dir.isDirectory && runCatching { mark.readText() }.getOrNull() == version) return@withContext true + val fresh = File(home, "personalities.new") + try { + fresh.deleteRecursively() + fresh.mkdirs() + val assets = context.assets + for (name in assets.list(ASSETS).orEmpty()) { + assets.open("$ASSETS/$name").use { input -> File(fresh, name).outputStream().use { input.copyTo(it) } } + } + dir.deleteRecursively() + if (!fresh.renameTo(dir)) throw IOException("cannot move the personalities into place") + mark.writeText(version) + true + } catch (e: IOException) { + fresh.deleteRecursively() + false + } + } + + private companion object { + const val ASSETS = "rodent4/personalities" + } +} + +/// Rodent IV's opening books as one pack (android-rodent.md §5): the books its characters +/// open, each a [CheckedDownload] of the system's, fetched one after another and each +/// checked by its SHA-256. A file checked stays: after a cancel or a break only the rest +/// is fetched. The pack is ready only when every file is there. +class BookPack(context: Context, private val scope: CoroutineScope, home: File) { + private val files: List = uniffi.mobile_api.rodentBookPack().map { b -> + val local = File(home, b.local) + CheckedDownload( + context, + scope, + FileSpec( + dir = local.parentFile!!.relativeTo(context.filesDir).path, + name = local.name, + url = b.url, + size = b.size.toLong(), + sha256 = b.sha256, + title = context.getString(R.string.books_notification), + prefs = "rodent4-book-" + local.name, + ownFolder = false, + ), + ) + } + + /// The pack in all (bytes). + val size: Long = files.sumOf { it.size } + + private val _state = MutableStateFlow(if (installed()) NetState.Ready else NetState.Missing) + /// Missing (some or all of it), Loading (of what was left when it began), Failed, Ready. + val state: StateFlow = _state.asStateFlow() + private var job: Job? = null + + private val books = File(home, "books") + + init { + sweep() + // A download of the system's still going on from before: the pack goes on. + if (files.any { it.state.value is NetState.Loading }) download() + } + + fun installed() = files.all { it.installed() } + + /// Files of another version of the pack (or left half-written) go, and folders left + /// empty. + private fun sweep() { + val known = files.flatMap { listOf(it.file.path, it.file.path + ".part") }.toSet() + books.walkBottomUp().forEach { f -> + if (f.isFile && f.path !in known) f.delete() + if (f.isDirectory && f != books && f.list().isNullOrEmpty()) f.delete() + } + } + + /// What is left to download (bytes). + fun remaining(): Long = files.filterNot { it.installed() }.sumOf { it.size } + + /// Fetches the files not there yet, one after another; stops at the first failure. + fun download() { + if (_state.value == NetState.Ready || _state.value is NetState.Loading) return + val left = files.filterNot { it.installed() } + val total = left.sumOf { it.size } + _state.value = NetState.Loading(0, total) + job = scope.launch(Dispatchers.Main.immediate) { + var done = 0L + for (f in left) { + f.download() + // Its progress as part of the whole, until it is in place or fails. + val end = f.state.first { s -> + if (s is NetState.Loading) _state.value = NetState.Loading(done + s.done, total) + s !is NetState.Loading + } + when (end) { + NetState.Ready -> done += f.size + is NetState.Failed -> { + _state.value = end + return@launch + } + // Removed in the system's list of downloads. + else -> { + _state.value = NetState.Missing + return@launch + } + } + } + _state.value = if (installed()) NetState.Ready else NetState.Missing + } + } + + /// The failure of an earlier attempt is forgotten (the network may be back): the pack + /// is offered again as it is. + fun forgetFailure() { + if (_state.value is NetState.Failed) _state.value = if (installed()) NetState.Ready else NetState.Missing + } + + /// Stops the download; the files checked so far stay. + fun cancel() { + job?.cancel() + job = null + files.forEach { if (it.state.value is NetState.Loading) it.cancel() } + _state.value = if (installed()) NetState.Ready else NetState.Missing + } + + /// Removes the books (Settings → Engine). + fun delete() { + cancel() + files.forEach { it.delete() } + sweep() + _state.value = NetState.Missing + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt new file mode 100644 index 0000000..e69b91f --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt @@ -0,0 +1,124 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +enum class Theme { System, Light, Dark } + +/// Who plays against the user (android-rodent.md): kept by these names. +enum class Opponent(val key: String) { Maia("maia"), Rodent("rodent4") } + +/// How moves are written on the screen (PGN keeps K Q R B N). +enum class Notation { Latin, Figurines, Local } + +/// The user's choices (android-ui.md §9), applied at once and kept across starts. +data class Prefs( + val theme: Theme = Theme.Dark, + val notation: Notation = Notation.Latin, + val board: BoardTheme = BoardTheme.Green, + val pieces: PieceSet = PieceSet.Merida, + val vibration: Boolean = true, + val animation: Boolean = true, + val bestArrow: Boolean = true, + val engineLines: Int = 2, + /// Seconds of thinking per position; 0 = no limit. + val engineSeconds: Int = 20, + val engineThreads: Int = defaultThreads(), + val engineHashMb: Int = 64, + /// The speed of one engine process (one thread) measured by the last game analysis + /// (0 = not yet), for the time estimate. + val reviewNps: Long = 0, + /// The last choices of a game against the computer (android-play.md §31.1, + /// android-rodent.md §7.1): the opponent, each one's strength on its own scale, + /// Rodent's character ("" = never chosen), the user's colour (-1 Black, 0 at + /// random, 1 White), the user's name. + val opponent: Opponent = Opponent.Maia, + val maiaStrength: Int = 1500, + val rodentStrength: Int = 1500, + val rodentPersonality: String = "", + val playColor: Int = 0, + val yourName: String = "", + /// Sounds of moves and of the end of a game (§33). + val sound: Boolean = true, + /// Games against the computer go by themselves into the player's database (player-games.md). + val recordGames: Boolean = true, +) + +/// Half the cores, at most 2: the engine leaves the phone's interface room (§9). +fun defaultThreads(): Int = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 2) + +class Settings(context: Context) { + private val store = context.getSharedPreferences("settings", Context.MODE_PRIVATE) + private val _prefs = MutableStateFlow(read()) + + init { + // Up to 0.11 the engine button was kept here (it is not remembered any more), and + // the threads were half the cores up to 4: that default becomes the new one. + if (store.getInt("version", 1) < 2) { + val oldDefault = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4) + if (store.getInt("engineThreads", oldDefault) == oldDefault) update { it.copy(engineThreads = defaultThreads()) } + store.edit().remove("engineOn").putInt("version", 2).apply() + } + } + val prefs: StateFlow = _prefs.asStateFlow() + + private fun read(): Prefs { + val d = Prefs() + return Prefs( + theme = enumValueOrNull(store.getString("theme", null)) ?: d.theme, + notation = enumValueOrNull(store.getString("notation", null)) ?: d.notation, + board = enumValueOrNull(store.getString("board", null)) ?: d.board, + pieces = enumValueOrNull(store.getString("pieces", null)) ?: d.pieces, + vibration = store.getBoolean("vibration", d.vibration), + animation = store.getBoolean("animation", d.animation), + bestArrow = store.getBoolean("bestArrow", d.bestArrow), + engineLines = store.getInt("engineLines", d.engineLines), + engineSeconds = store.getInt("engineSeconds", d.engineSeconds), + engineThreads = store.getInt("engineThreads", d.engineThreads), + engineHashMb = store.getInt("engineHashMb", d.engineHashMb), + reviewNps = store.getLong("reviewNps", d.reviewNps), + opponent = Opponent.entries.firstOrNull { it.key == store.getString("opponent", null) } ?: d.opponent, + maiaStrength = store.getInt("maiaStrength", d.maiaStrength), + rodentStrength = store.getInt("rodentStrength", d.rodentStrength), + rodentPersonality = store.getString("rodentPersonality", d.rodentPersonality) ?: d.rodentPersonality, + // Kept as `maiaColor` up to 1.7, when Maia was the only opponent. + playColor = store.getInt("playColor", store.getInt("maiaColor", d.playColor)).coerceIn(-1, 1), + yourName = store.getString("yourName", d.yourName) ?: d.yourName, + sound = store.getBoolean("sound", d.sound), + recordGames = store.getBoolean("recordGames", d.recordGames), + ) + } + + fun update(change: (Prefs) -> Prefs) { + val p = change(_prefs.value) + _prefs.value = p + store.edit() + .putString("theme", p.theme.name) + .putString("notation", p.notation.name) + .putString("board", p.board.name) + .putString("pieces", p.pieces.name) + .putBoolean("vibration", p.vibration) + .putBoolean("animation", p.animation) + .putBoolean("bestArrow", p.bestArrow) + .putInt("engineLines", p.engineLines) + .putInt("engineSeconds", p.engineSeconds) + .putInt("engineThreads", p.engineThreads) + .putInt("engineHashMb", p.engineHashMb) + .putLong("reviewNps", p.reviewNps) + .putString("opponent", p.opponent.key) + .putInt("maiaStrength", p.maiaStrength) + .putInt("rodentStrength", p.rodentStrength) + .putString("rodentPersonality", p.rodentPersonality) + .putInt("playColor", p.playColor) + .remove("maiaColor") + .putString("yourName", p.yourName) + .putBoolean("sound", p.sound) + .putBoolean("recordGames", p.recordGames) + .apply() + } +} + +private inline fun > enumValueOrNull(name: String?): T? = + enumValues().firstOrNull { it.name == name } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Sounds.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Sounds.kt new file mode 100644 index 0000000..5c0ed74 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Sounds.kt @@ -0,0 +1,41 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import android.media.AudioAttributes +import android.media.SoundPool + +/// What a sound says (android-play.md §33). +enum class Sound(val file: String) { + Move("Move"), + Capture("Capture"), + Check("Check"), + Defeat("Defeat"), + Success("Success"), + Wrong("Wrong"), +} + +/// The desktop's «SFX» set, loaded once; played when the setting «Sound» is on. +class Sounds(context: Context, private val settings: Settings) { + private val pool = SoundPool.Builder() + .setMaxStreams(2) + .setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build()) + .build() + private val ids: Map = Sound.entries.associateWith { s -> + runCatching { context.assets.openFd("sounds/${s.file}.ogg").use { pool.load(it, 1) } }.getOrDefault(0) + } + + fun play(sound: Sound) { + if (!settings.prefs.value.sound) return + val id = ids[sound] ?: return + if (id != 0) pool.play(id, 1f, 1f, 1, 0, 1f) + } + + /// The sound of a move by its SAN: a check, a capture, or a move. + fun move(san: String) = play( + when { + san.endsWith("+") || san.endsWith("#") -> Sound.Check + 'x' in san -> Sound.Capture + else -> Sound.Move + }, + ) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Color.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Color.kt new file mode 100644 index 0000000..096014b --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Color.kt @@ -0,0 +1,105 @@ +package io.github.vrubelroman.chesspenguin.theme + +import androidx.compose.ui.graphics.Color + +// The colors of the desktop app and the website (docs/design/android-ui.md §10.3). + +val LightBackground = Color(0xFFFFFFFF) +val LightContainerLow = Color(0xFFF5F6F7) +val LightContainer = Color(0xFFEEF0F2) +val LightContainerHigh = Color(0xFFE8EAED) +val LightOnSurface = Color(0xFF1C1D1F) +val LightOnSurfaceVariant = Color(0xFF5D636B) +val LightOutline = Color(0xFFC4C8CD) +val LightOutlineVariant = Color(0xFFE1E3E6) +val LightPrimary = Color(0xFF1F6FA8) +val LightPrimaryContainer = Color(0xFFD6E8F6) +val LightOnPrimaryContainer = Color(0xFF1A5F91) +val LightError = Color(0xFFC42B1C) +val LightErrorContainer = Color(0xFFFCE4E1) + +val DarkBackground = Color(0xFF161718) +val DarkContainerLow = Color(0xFF1F2022) +val DarkContainer = Color(0xFF232427) +val DarkContainerHigh = Color(0xFF2A2C2F) +val DarkOnSurface = Color(0xFFE8E8E8) +val DarkOnSurfaceVariant = Color(0xFFA3A7AD) +val DarkOutline = Color(0xFF4A4D52) +val DarkOutlineVariant = Color(0xFF2E3033) +val DarkPrimary = Color(0xFF62AEE6) +val DarkOnPrimary = Color(0xFF0B2A40) +val DarkPrimaryContainer = Color(0xFF1A4566) +val DarkError = Color(0xFFF28B82) +val DarkErrorContainer = Color(0xFF5C1A14) + +/// Colors of the notation and the board that stay ours whatever the theme (the +/// squares are the chosen board's, data/BoardStyle.kt). +data class ChessColors( + val dark: Boolean, + val currentMove: Color, + val comment: Color, + val lastMove: Color, +) + +val LightChess = ChessColors( + dark = false, + currentMove = Color(0xFF90D1FF), + comment = Color(0xFF2A5B8A), + lastMove = Color(0x699BC700), +) + +val DarkChess = LightChess.copy( + dark = true, + currentMove = Color(0xFF005C80), + comment = Color(0xFF9EC4E0), +) + +/// Move assessments in the owner's palette (chess.com's), as on the desktop. On a light +/// background they are darkened to stay readable (contrast at least 4.5:1). +fun nagColor(nag: Int, dark: Boolean): Color? = if (dark) { + when (nag) { + 1 -> Color(0xFF81B64C) // ! + 2 -> Color(0xFFFFA459) // ? + 3 -> Color(0xFF26C2A3) // !! + 4 -> Color(0xFFFA412D) // ?? + 5 -> Color(0xFFEA45D8) // !? + 6 -> Color(0xFF56B4E9) // ?! (Lichess blue) + else -> null + } +} else { + when (nag) { + 1 -> Color(0xFF5B8135) + 2 -> Color(0xFFC25700) + 3 -> Color(0xFF1A846F) + 4 -> Color(0xFFD2301C) + 5 -> Color(0xFFB0259F) + 6 -> Color(0xFF1F72A8) + else -> null + } +} + +/// The kinds of databases, each in its own colour on its badge (android-lists.md §5.1). +enum class DbKind { Pgn, ChessBase, Archive, Online, Own } + +/// A badge's background and what is written on it. +data class KindColor(val container: Color, val content: Color) + +/// The colour of a kind of database, from Catppuccin (the owner's choice): Mocha in the +/// dark theme, Latte in the light one, on a tint of the same hue (contrast at least 5:1). +fun kindColor(kind: DbKind, dark: Boolean): KindColor = if (dark) { + when (kind) { + DbKind.Pgn -> KindColor(Color(0xFF384660), Color(0xFF89B4FA)) // blue + DbKind.ChessBase -> KindColor(Color(0xFF55443B), Color(0xFFFAB387)) // peach + DbKind.Archive -> KindColor(Color(0xFF4A3F5E), Color(0xFFCBA6F7)) // mauve + DbKind.Online -> KindColor(Color(0xFF3A5250), Color(0xFF94E2D5)) // teal + DbKind.Own -> KindColor(Color(0xFF3F523F), Color(0xFFA6E3A1)) // green + } +} else { + when (kind) { + DbKind.Pgn -> KindColor(Color(0xFFDFEAFE), Color(0xFF1957D0)) + DbKind.ChessBase -> KindColor(Color(0xFFFFE9DD), Color(0xFFA54107)) + DbKind.Archive -> KindColor(Color(0xFFEEE3FD), Color(0xFF7A33D7)) + DbKind.Online -> KindColor(Color(0xFFDFF0F1), Color(0xFF116D73)) + DbKind.Own -> KindColor(Color(0xFFE4F2E1), Color(0xFF2D701E)) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Theme.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Theme.kt new file mode 100644 index 0000000..b0ab13d --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Theme.kt @@ -0,0 +1,72 @@ +package io.github.vrubelroman.chesspenguin.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Color + +private val Light = lightColorScheme( + primary = LightPrimary, + onPrimary = Color.White, + primaryContainer = LightPrimaryContainer, + onPrimaryContainer = LightOnPrimaryContainer, + secondary = LightPrimary, + onSecondary = Color.White, + secondaryContainer = LightPrimaryContainer, + onSecondaryContainer = LightOnPrimaryContainer, + tertiary = LightPrimary, + background = LightBackground, + onBackground = LightOnSurface, + surface = LightBackground, + onSurface = LightOnSurface, + onSurfaceVariant = LightOnSurfaceVariant, + surfaceContainerLowest = LightBackground, + surfaceContainerLow = LightContainerLow, + surfaceContainer = LightContainer, + surfaceContainerHigh = LightContainerHigh, + surfaceContainerHighest = LightContainerHigh, + outline = LightOutline, + outlineVariant = LightOutlineVariant, + error = LightError, + errorContainer = LightErrorContainer, +) + +private val Dark = darkColorScheme( + primary = DarkPrimary, + onPrimary = DarkOnPrimary, + primaryContainer = DarkPrimaryContainer, + onPrimaryContainer = LightPrimaryContainer, + secondary = DarkPrimary, + onSecondary = DarkOnPrimary, + secondaryContainer = DarkPrimaryContainer, + onSecondaryContainer = LightPrimaryContainer, + tertiary = DarkPrimary, + background = DarkBackground, + onBackground = DarkOnSurface, + surface = DarkBackground, + onSurface = DarkOnSurface, + onSurfaceVariant = DarkOnSurfaceVariant, + surfaceContainerLowest = DarkBackground, + surfaceContainerLow = DarkContainerLow, + surfaceContainer = DarkContainer, + surfaceContainerHigh = DarkContainerHigh, + surfaceContainerHighest = DarkContainerHigh, + outline = DarkOutline, + outlineVariant = DarkOutlineVariant, + error = DarkError, + errorContainer = DarkErrorContainer, +) + +val LocalChessColors = staticCompositionLocalOf { LightChess } + +/// Our own colors in the light or dark theme of the system (docs/design/android-ui.md §10.3). +@Composable +fun ChessPenguinTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { + CompositionLocalProvider(LocalChessColors provides if (darkTheme) DarkChess else LightChess) { + MaterialTheme(colorScheme = if (darkTheme) Dark else Light, typography = Typography, content = content) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Type.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Type.kt new file mode 100644 index 0000000..1358853 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Type.kt @@ -0,0 +1,20 @@ +package io.github.vrubelroman.chesspenguin.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// The system font (Roboto on most phones), the sizes of §10.2. +val Typography = Typography().run { + copy( + titleLarge = titleLarge.copy(fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.Normal), + bodyLarge = bodyLarge.copy(fontSize = 16.sp, lineHeight = 24.sp), + bodyMedium = bodyMedium.copy(fontSize = 14.sp, lineHeight = 20.sp), + labelLarge = labelLarge.copy(fontSize = 14.sp, lineHeight = 20.sp, fontWeight = FontWeight.Medium), + labelSmall = labelSmall.copy(fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.Medium), + ) +} + +/// Digits that keep their width (results, counters). +val Tabular = TextStyle(fontFeatureSettings = "tnum") diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt new file mode 100644 index 0000000..0cb80f5 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt @@ -0,0 +1,108 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R + +private const val SITE = "https://chess.vrubel.xyz" + +/// The authors and licenses of what the app is made of (android-ui.md §8.3, §9). +private val NOTICES = listOf( + "ChessPenguin" to "GPL-3.0-or-later · vrubelroman", + "Stockfish 19" to "GPL-3.0 · The Stockfish developers (see AUTHORS) · github.com/official-stockfish/Stockfish", + "Pieces cburnett, merida" to "GPLv2+ · Colin M.L. Burnett; Armando Hernandez Marroquin (via Lichess)", + "Pieces mpchess" to "GPLv3+ · Maxime Chupin (via Lichess)", + "Pieces chessnut" to "Apache-2.0 · Alexis Luengas (via Lichess)", + "Pieces fantasy, celtic, spatial" to "MIT · Maurizio Monge (via Lichess)", + "Pieces rhosgfx" to "CC0-1.0 · RhosGFX (via Lichess)", + "Pieces shapes" to "CC BY-SA 4.0 · flugsio (via Lichess)", + "Pieces kiwen-suwi, firi" to "CC BY 4.0 · neverRare; James Faure (via Lichess)", + "Pieces pixel, letter, pirouetti" to "AGPLv3+ · therealqtpi; usolando; pirouetti (via Lichess)", + "Pieces governor" to "AGPLv3+ · the lila authors (via PyChess)", + "Pieces kosal" to "CC BY 4.0 · Kosal Sen, philatype.com (via PyChess)", + "Pieces metaltops" to "GPL · PyChess", + "Board images" to "AGPLv3+ · the lila authors and pirouetti (Lichess)", + "Sounds (SFX)" to "AGPLv3+ · Enigmahack (via Lichess)", + "Sound of a wrong move" to "CC0-1.0 · Kenney, kenney.nl", + "Rodent IV 0.33" to "GPL-3.0 · Paweł Koziol, Bernhard C. Maerz (based on Sungorus by Pablo Vázquez) · github.com/nescitus/rodent-iv", + "Rodent IV opening books (downloaded from its authors on request)" to "Their authors' credits in the books' folders · github.com/nescitus/rodent-iv", + "Maia-3 (downloaded from its authors on request)" to "CSSLab, University of Toronto · huggingface.co/UofTCSSLab", + "Figurines, Noto Sans Math" to "SIL Open Font License 1.1", + "Jetpack Compose, AndroidX, Kotlin" to "Apache-2.0 · Google, JetBrains", + "UniFFI" to "MPL-2.0 · Mozilla", + "JNA" to "Apache-2.0 / LGPL-2.1", + "AndroidSVG" to "Apache-2.0 · Paul LeBeau", + "shakmaty" to "GPL-3.0-or-later · Niklas Fiekas", +) + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AboutScreen(onBack: () -> Unit) { + val uri = LocalUriHandler.current + val snackbar = remember { SnackbarHostState() } + UpdateMessages(snackbar) + Scaffold( + snackbarHost = { SnackbarHost(snackbar) }, + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.about)) }, + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp)) { + Image(painterResource(R.drawable.penguin), null, Modifier.size(72.dp)) + Spacer(Modifier.height(16.dp)) + 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) + Text("${BuildConfig.VERSION_NAME} · $build", color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.height(24.dp)) + // Right under the version (android-ui.md §25.5); a store's build is updated by + // the store. + if (BuildConfig.SELF_UPDATE) { + AboutUpdates() + Spacer(Modifier.height(24.dp)) + } + Text(stringResource(R.string.about_text), style = MaterialTheme.typography.bodyLarge) + TextButton(onClick = { uri.openUri(SITE) }, contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)) { + Text(stringResource(R.string.website)) + } + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.licenses), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) + NOTICES.forEach { (what, license) -> + Spacer(Modifier.height(12.dp)) + Text(what, style = MaterialTheme.typography.bodyLarge) + Text(license, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt new file mode 100644 index 0000000..298b194 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt @@ -0,0 +1,227 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.ui.draw.clip +import androidx.compose.foundation.background +import io.github.vrubelroman.chesspenguin.theme.DbKind +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.PaddingValues +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.CloudDownload +import androidx.compose.material.icons.outlined.ContentPaste +import androidx.compose.material.icons.outlined.Description +import androidx.compose.material.icons.outlined.Folder +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +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.FolderScan +import io.github.vrubelroman.chesspenguin.data.Found +import io.github.vrubelroman.chesspenguin.data.Source + +/// The icon of a way to add, in a round tile coloured as the database it brings +/// (android-lists.md §6). +@Composable +private fun KindIcon(kind: DbKind, icon: androidx.compose.ui.graphics.vector.ImageVector) { + val c = io.github.vrubelroman.chesspenguin.theme.kindColor(kind, io.github.vrubelroman.chesspenguin.theme.LocalChessColors.current.dark) + Box(Modifier.size(40.dp).clip(androidx.compose.foundation.shape.CircleShape).background(c.container), contentAlignment = Alignment.Center) { + Icon(icon, null, tint = c.content, modifier = Modifier.size(22.dp)) + } +} + +/// "Add a database": games in the clipboard, a file, every database in a folder, or a +/// player's games from Lichess and Chess.com. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, onOnline: () -> Unit, onDismiss: () -> Unit) { + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.navigationBarsPadding().padding(bottom = 24.dp)) { + Text( + stringResource(R.string.add_database), + style = MaterialTheme.typography.titleLarge, + modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp).semantics { heading() }, + ) + // Only when there is text to paste (asked without reading it: reading the + // clipboard makes Android say so on the screen). + if (onPaste != null) { + ListItem( + headlineContent = { Text(stringResource(R.string.add_paste)) }, + supportingContent = { Text(stringResource(R.string.add_paste_hint)) }, + leadingContent = { KindIcon(DbKind.Pgn, Icons.Outlined.ContentPaste) }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + modifier = Modifier.clickable(role = Role.Button, onClick = onPaste).padding(horizontal = 8.dp), + ) + } + ListItem( + headlineContent = { Text(stringResource(R.string.online_title)) }, + supportingContent = { Text(stringResource(R.string.add_online_hint)) }, + leadingContent = { KindIcon(DbKind.Online, Icons.Outlined.CloudDownload) }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + modifier = Modifier.clickable(role = Role.Button, onClick = onOnline).padding(horizontal = 8.dp), + ) + ListItem( + headlineContent = { Text(stringResource(R.string.add_file)) }, + supportingContent = { Text(stringResource(R.string.add_file_hint)) }, + leadingContent = { KindIcon(DbKind.Pgn, Icons.Outlined.Description) }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + modifier = Modifier.clickable(role = Role.Button, onClick = onFile).padding(horizontal = 8.dp), + ) + ListItem( + headlineContent = { Text(stringResource(R.string.add_folder)) }, + supportingContent = { Text(stringResource(R.string.add_folder_hint)) }, + leadingContent = { KindIcon(DbKind.Pgn, Icons.Outlined.Folder) }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + modifier = Modifier.clickable(role = Role.Button, onClick = onFolder).padding(horizontal = 8.dp), + ) + // The system picker only says "Can't use this folder" in English, and gives + // nothing back: so it is said before. + Text( + stringResource(R.string.add_tree_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp), + ) + } + } +} + +/// The databases found in a picked folder, to tick and add; `scan` is null while the +/// folder is being looked through. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun FolderSheet(scan: FolderScan?, onAdd: (List) -> Unit, onPickAnother: () -> Unit, onDismiss: () -> Unit) { + // Open in full at once: the buttons under the list are always on the screen. + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + Column(Modifier.navigationBarsPadding().padding(horizontal = 24.dp).padding(bottom = 24.dp)) { + if (scan == null) { + Row(Modifier.fillMaxWidth().height(96.dp), verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 3.dp) + Spacer(Modifier.size(16.dp)) + Text(stringResource(R.string.folder_scanning), style = MaterialTheme.typography.bodyLarge) + } + return@Column + } + val addable = scan.found.filter { !it.added && !it.incomplete } + if (scan.found.isEmpty()) { + Text(stringResource(R.string.folder_empty_title), style = MaterialTheme.typography.titleLarge, modifier = Modifier.semantics { heading() }) + Spacer(Modifier.height(8.dp)) + Text( + stringResource(R.string.folder_empty_text), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } + Button(onClick = onPickAnother) { Text(stringResource(R.string.pick_another)) } + } + return@Column + } + // Everything that can be added is ticked at first. + var chosen by remember(scan) { mutableStateOf(addable.toSet()) } + Text( + pluralStringResource(R.plurals.folder_found, scan.found.size, scan.found.size, scan.name), + style = MaterialTheme.typography.titleLarge, + modifier = Modifier.semantics { heading() }, + ) + if (addable.size > 1) { + val all = chosen.size == addable.size + TextButton(onClick = { chosen = if (all) emptySet() else addable.toSet() }, contentPadding = PaddingValues(0.dp)) { + Text(stringResource(if (all) R.string.choose_none else R.string.choose_all)) + } + } + Spacer(Modifier.height(8.dp)) + LazyColumn(Modifier.weight(1f, fill = false)) { + itemsIndexed(scan.found) { _, f -> + FoundRow(f, f in chosen) { on -> chosen = if (on) chosen + f else chosen - f } + } + } + Spacer(Modifier.height(16.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + if (addable.isEmpty()) { + // Everything there is already on the list (or cannot be opened). + Button(onClick = onDismiss) { Text(stringResource(R.string.done)) } + } else { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } + Button(onClick = { onAdd(scan.found.filter { it in chosen }) }, enabled = chosen.isNotEmpty()) { + Text(if (chosen.isEmpty()) stringResource(R.string.add) else pluralStringResource(R.plurals.add_chosen, chosen.size, chosen.size)) + } + } + } + } + } +} + +@Composable +private fun FoundRow(f: Found, checked: Boolean, onChange: (Boolean) -> Unit) { + val enabled = !f.added && !f.incomplete + val label = when { + f.source == Source.ChessBase -> "CB" + else -> f.fileName.substringAfterLast('.', "").uppercase().let { if (it == "CBV") "CB" else it } + } + val note = when { + f.added -> stringResource(R.string.folder_added) + f.incomplete -> stringResource(R.string.folder_incomplete) + else -> f.fileName + } + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 64.dp) + .toggleable(value = checked || f.added, enabled = enabled, role = Role.Checkbox, onValueChange = onChange), + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox(checked = checked || f.added, onCheckedChange = null, enabled = enabled) + Spacer(Modifier.size(12.dp)) + FormatBadge(label, error = f.incomplete, kind = when (label) { "CB" -> DbKind.ChessBase; "7Z", "ZIP" -> DbKind.Archive; else -> DbKind.Pgn }) + Column(Modifier.weight(1f).padding(start = 16.dp)) { + Text(f.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + val where = if (f.path.isEmpty()) note else "${f.path} · $note" + Text( + where, + style = MaterialTheme.typography.bodyMedium, + color = if (f.incomplete) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + Box(Modifier.size(8.dp)) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt new file mode 100644 index 0000000..9fae784 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt @@ -0,0 +1,540 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.BitmapRegionDecoder +import android.graphics.Canvas +import android.graphics.Rect +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalViewConfiguration +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.drawText +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.caverock.androidsvg.SVG +import io.github.vrubelroman.chesspenguin.data.BoardTheme +import io.github.vrubelroman.chesspenguin.data.PieceSet +import io.github.vrubelroman.chesspenguin.theme.LocalChessColors +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/// The 64 squares of a FEN's placement, a8 first: the piece letter or ' '. +fun placement(fen: String): CharArray { + val out = CharArray(64) { ' ' } + var i = 0 + for (c in fen.substringBefore(' ')) { + when { + c == '/' -> {} + c.isDigit() -> i += c - '0' + i < 64 -> out[i++] = c + } + } + return out +} + +/// "e4" → its index in [placement] (a8 = 0). +fun squareIndex(square: String?): Int? { + if (square == null || square.length < 2) return null + val file = square[0] - 'a' + val rank = square[1] - '1' + if (file !in 0..7 || rank !in 0..7) return null + return (7 - rank) * 8 + file +} + +/// The pieces of the desktop app's sets, drawn from their SVG at a size once. +class Pieces(private val context: Context) { + private val svgs = HashMap, SVG>() + private val bitmaps = HashMap, ImageBitmap>() + + fun bitmap(set: PieceSet, piece: Char, size: Int): ImageBitmap? { + if (size <= 0) return null + return bitmaps.getOrPut(Triple(set, piece, size)) { + val name = (if (piece.isUpperCase()) "w" else "b") + piece.uppercaseChar() + val svg = svgs.getOrPut(set to piece) { context.assets.open("pieces/${set.dir}/$name.svg").use { SVG.getFromInputStream(it) } } + val bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) + // Without a viewBox (kiwen-suwi, metaltops) AndroidSVG draws a set at its own + // size, whatever size is asked for. + if (svg.documentViewBox == null) svg.setDocumentViewBox(0f, 0f, svg.documentWidth, svg.documentHeight) + svg.setDocumentWidth(size.toFloat()) + svg.setDocumentHeight(size.toFloat()) + svg.renderToCanvas(Canvas(bmp)) + bmp.asImageBitmap() + } + } +} + +/// A board's image (1024 px) read at about `size` px: a phone's board needs no more, and +/// the whole image would take 4 MB. +fun boardImage(context: Context, file: String, size: Int): ImageBitmap? = runCatching { + val bytes = context.assets.open("boards/$file").use { it.readBytes() } + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + var sample = 1 + while (bounds.outWidth / (sample * 2) >= size) sample *= 2 + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap() +}.getOrNull() + +/// The corner of a board's image with a1: 2×2 squares, for the choice of boards. +fun boardCorner(context: Context, file: String, size: Int): ImageBitmap? = runCatching { + context.assets.open("boards/$file").use { input -> + val decoder = BitmapRegionDecoder.newInstance(input) ?: return null + try { + val q = decoder.width / 4 + var sample = 1 + while (q / (sample * 2) >= size) sample *= 2 + decoder.decodeRegion(Rect(0, decoder.height - q, q, decoder.height), BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap() + } finally { + decoder.recycle() + } + } +}.getOrNull() + +/// "e4" of the square with index `i` of [placement] (a8 = 0). +fun squareName(i: Int): String = "${'a' + i % 8}${'8' - i / 8}" + +/// Moves on the board (android-play.md §29): the legal moves of the position in UCI and +/// what to do with the one made. A pawn on the last rank becomes a queen (owner's +/// decision §29.4); `promotion` may name another piece for a from–to pair (the trainer +/// takes the line's own piece). +class BoardInput( + val legal: List, + val onMove: (String) -> Unit, + val promotion: (String) -> Char? = { null }, +) { + /// The squares a piece on `from` can go to. + fun targets(from: String): Set = legal.filter { it.startsWith(from) }.map { it.substring(2, 4) }.toSet() + + /// The move from `from` to `to`, or null when there is none. + fun move(from: String, to: String): String? { + val pair = from + to + val all = legal.filter { it.startsWith(pair) } + if (all.isEmpty()) return null + if (all.size == 1) return all[0] + val piece = promotion(pair) ?: 'q' + return all.firstOrNull { it == pair + piece } ?: all.firstOrNull { it == pair + 'q' } ?: all[0] + } +} + +/// An arrow on the board: a comment's `[%cal]` or the engine's best move. +data class BoardArrow(val from: String, val to: String, val color: Color, val weight: Float = 1f) + +/// A continuation attached to an arrow. Several UCI moves may share one direction +/// (promotions); in that case the callback receives all of them for an explicit choice. +data class BoardArrowMove( + val uci: String, + val from: String, + val to: String, + val actionLabel: String, +) + +/// A marked square of a comment (`[%csl]`), drawn as a ring. +data class BoardMark(val square: String, val color: Color) + +/// 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`). +fun markColor(letter: String): Color = when (letter) { + "R" -> Color(136, 32, 32, 170) + "G" -> Color(21, 120, 27, 170) + "B" -> Color(0, 48, 136, 170) + "Y" -> Color(230, 143, 0, 170) + else -> Color(120, 120, 120, 170) +} + +/// The engine's arrows are blue, as on the desktop. +val EngineArrow = Color(0, 48, 136, 160) + +internal fun boardCell(index: Int, square: Float, flipped: Boolean): Offset { + val row = index / 8 + val col = index % 8 + val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col + return Offset(c * square, r * square) +} + +private data class ArrowGeometry(val start: Offset, val base: Offset, val tip: Offset) + +private fun arrowGeometry(from: Offset, to: Offset, square: Float, weight: Float): ArrowGeometry? { + val delta = to - from + val length = delta.getDistance() + if (length < 1f) return null + val direction = delta / length + val headLength = square * 0.42f * kotlin.math.sqrt(weight) + val tip = to - direction * (square * 0.12f) + return ArrowGeometry(from + direction * (square * 0.2f), tip - direction * headLength, tip) +} + +private fun distanceToSegment(point: Offset, start: Offset, end: Offset): Float { + val segment = end - start + val length2 = segment.x * segment.x + segment.y * segment.y + if (length2 < 1f) return (point - start).getDistance() + val t = (((point - start).x * segment.x + (point - start).y * segment.y) / length2).coerceIn(0f, 1f) + return (point - (start + segment * t)).getDistance() +} + +/// Hit testing uses the same square transform and arrow endpoints as drawing. The head +/// has at least a 48 dp target; shaft corridors stay narrower so neighbours do not all +/// become one arbitrary shortcut. +internal fun arrowHits( + point: Offset, + square: Float, + flipped: Boolean, + moves: List, + headRadius: Float, +): List { + if (square <= 0f || point.x < 0 || point.y < 0 || point.x > square * 8 || point.y > square * 8) return emptyList() + val corridor = maxOf(square * 0.16f, headRadius * 0.5f) + return moves.filter { move -> + val from = squareIndex(move.from) ?: return@filter false + val to = squareIndex(move.to) ?: return@filter false + val center = Offset(square / 2, square / 2) + val geometry = arrowGeometry(boardCell(from, square, flipped) + center, boardCell(to, square, flipped) + center, square, 1f) ?: return@filter false + (point - geometry.tip).getDistance() <= headRadius || + distanceToSegment(point, geometry.start, geometry.base) <= corridor || + distanceToSegment(point, geometry.base, geometry.tip) <= corridor + } +} + +/// The board: full width, the chosen board and pieces, the last move lit, the +/// coordinates inside the edge squares (as on Lichess). With `input` a move is made by +/// tapping a piece and then a square, or by dragging it (android-play.md §29.2–29.3); +/// without it the board takes no touches. A move slides into place (250 ms). +@Composable +fun Board( + fen: String, + flipped: Boolean, + lastFrom: String?, + lastTo: String?, + pieces: Pieces, + theme: BoardTheme, + set: PieceSet, + description: String, + modifier: Modifier = Modifier, + arrows: List = emptyList(), + arrowMoves: List = emptyList(), + onArrowMoves: (List) -> Unit = {}, + marks: List = emptyList(), + check: Boolean = false, + animated: Boolean = true, + input: BoardInput? = null, + /// Two squares lit red: a wrong move of the trainer, shown for a moment (§32.2). + alert: Pair? = null, + /// The files and ranks along the edges (none on a small board that only shows). + coordinates: Boolean = true, + badge: BoardBadge? = null, +) { + val colors = LocalChessColors.current + val context = LocalContext.current + // The image of a textured board, read off the main thread; the flat colors until then. + var side by remember { mutableIntStateOf(0) } + val texture by produceState(null, theme, side) { + value = null + val file = theme.texture ?: return@produceState + if (side > 0) value = withContext(Dispatchers.IO) { boardImage(context, file, side) } + } + val measurer = rememberTextMeasurer() + val squares = remember(fen) { placement(fen) } + val from = squareIndex(lastFrom) + val to = squareIndex(lastTo) + // The piece of the last move slides from its square when the position steps on. + val slide = remember { Animatable(1f) } + var previous by remember { mutableStateOf(null) } + var animate by remember { mutableStateOf(false) } + LaunchedEffect(fen) { + animate = animated && previous != null && from != null && to != null && placement(previous!!).let { p -> p[from] != ' ' && p[to] != squares[to] } + previous = fen + if (animate) { + slide.snapTo(0f) + slide.animateTo(1f, tween(250, easing = FastOutSlowInEasing)) + } else { + slide.snapTo(1f) + } + } + val coordStyle = TextStyle(fontSize = 10.sp, fontWeight = FontWeight.Medium) + val density = LocalDensity.current + // A move being made: the piece chosen, and while dragged, where the finger is. + var selected by remember(fen) { mutableStateOf(null) } + var dragAt by remember(fen) { mutableStateOf(null) } + val slop = LocalViewConfiguration.current.touchSlop + val currentInput = androidx.compose.runtime.rememberUpdatedState(input) + val currentArrowMoves = androidx.compose.runtime.rememberUpdatedState(arrowMoves) + val currentArrowAction = androidx.compose.runtime.rememberUpdatedState(onArrowMoves) + val lift = with(density) { 22.dp.toPx() } + fun indexAt(p: Offset, sq: Float): Int? { + val col = (p.x / sq).toInt() + val row = (p.y / sq).toInt() + if (p.x < 0 || p.y < 0 || col !in 0..7 || row !in 0..7) return null + return if (flipped) (7 - row) * 8 + (7 - col) else row * 8 + col + } + val touch = if (input == null) Modifier else Modifier.pointerInput(fen, flipped) { + awaitEachGesture { + val down = awaitFirstDown() + val inp = currentInput.value ?: return@awaitEachGesture + val sq = size.width / 8f + val start = indexAt(down.position, sq) ?: return@awaitEachGesture + val startName = squareName(start) + val movable = inp.targets(startName).isNotEmpty() + val was = selected + // A tap on a target of the piece chosen makes the move. An already chosen + // piece always has priority over continuation arrows. + if (was != null && start != was) { + inp.move(squareName(was), startName)?.let { m -> + selected = null + inp.onMove(m) + return@awaitEachGesture + } + } + if (movable) selected = start + val shortcutCandidate = was == null && !movable + var dragging = false + while (true) { + val e = awaitPointerEvent() + val c = e.changes.firstOrNull { it.id == down.id } ?: break + if (!c.pressed) { + if (dragging) { + val end = indexAt(c.position, sq) + dragAt = null + val m = end?.let { inp.move(startName, squareName(it)) } + if (m != null) { + selected = null + inp.onMove(m) + } + // A drop elsewhere: the piece goes back, still chosen. + } else { + if (!movable || start == was) { + // A tap on the same piece, an empty square or the other side's + // piece: nothing chosen any more. + selected = null + } + if (shortcutCandidate) { + val hits = arrowHits( + c.position, + sq, + flipped, + currentArrowMoves.value, + with(density) { 24.dp.toPx() }, + ) + if (hits.isNotEmpty()) currentArrowAction.value(hits.map { it.uci }.distinct()) + } + } + c.consume() + break + } + if (!dragging && (c.position - down.position).getDistance() > slop) dragging = true + if (dragging) { + if (movable) dragAt = c.position + c.consume() + } + } + } + } + Canvas( + modifier + .aspectRatio(1f) + .onSizeChanged { side = it.width } + .then(touch) + .semantics { + contentDescription = description + if (arrowMoves.isNotEmpty()) { + customActions = arrowMoves.map { move -> + CustomAccessibilityAction(move.actionLabel) { + onArrowMoves(listOf(move.uci)) + true + } + } + } + }, + ) { + val sq = size.width / 8f + val px = sq.toInt() + fun cell(i: Int): Offset = boardCell(i, sq, flipped) + val image = texture + if (image != null) { + // The squares of the image are the same seen from either side: it is not turned. + drawImage(image, dstSize = IntSize(size.width.toInt(), size.height.toInt())) + } + for (i in 0 until 64) { + val light = (i / 8 + i % 8) % 2 == 0 + if (image == null) drawRect(if (light) theme.light else theme.dark, cell(i), Size(sq, sq)) + if (i == from || i == to) drawRect(colors.lastMove, cell(i), Size(sq, sq)) + } + alert?.let { (a, b) -> + // A fill and a ring: seen on dark squares of every board too. + for (sqName in listOf(a, b)) squareIndex(sqName)?.let { + val c = cell(it) + drawRect(Color(220, 40, 40, 153), c, Size(sq, sq)) + val w = with(density) { 3.dp.toPx() } + drawRect(Color(186, 26, 26), c + Offset(w / 2, w / 2), Size(sq - w, sq - w), style = Stroke(width = w)) + } + } + val chosen = selected + if (chosen != null) drawRect(colors.lastMove.copy(alpha = 0.5f), cell(chosen), Size(sq, sq)) + for (m in marks) { + val i = squareIndex(m.square) ?: continue + val c = cell(i) + drawCircle(m.color, radius = sq * 0.45f, center = Offset(c.x + sq / 2, c.y + sq / 2), style = Stroke(width = sq * 0.08f)) + } + if (check) { + // A red glow under the king of the side to move. + val king = if (fen.substringAfter(' ').startsWith("b")) 'k' else 'K' + val i = squares.indexOf(king) + if (i >= 0) { + val c = cell(i) + val center = Offset(c.x + sq / 2, c.y + sq / 2) + drawCircle( + Brush.radialGradient( + 0f to Color(255, 0, 0, 230), + 0.25f to Color(231, 0, 0, 230), + 0.89f to Color(169, 0, 0, 0), + center = center, + radius = sq * 0.6f, + ), + radius = sq * 0.6f, + center = center, + ) + } + } + for (i in 0 until 64) { + val p = squares[i] + if (p == ' ') continue + val bmp = pieces.bitmap(set, p, px) ?: continue + var at = cell(i) + // The piece being dragged: faint on its square, drawn under the finger below. + if (i == chosen && dragAt != null) { + drawImage(bmp, dstOffset = IntOffset(at.x.toInt(), at.y.toInt()), dstSize = IntSize(px, px), alpha = 0.3f) + continue + } + if (animate && i == to && from != null && slide.value < 1f) { + val start = cell(from) + at = Offset(start.x + (at.x - start.x) * slide.value, start.y + (at.y - start.y) * slide.value) + } + drawImage(bmp, dstOffset = IntOffset(at.x.toInt(), at.y.toInt()), dstSize = IntSize(px, px)) + } + // Where the piece chosen can go: a dot, a ring round a capture (as on Lichess). + if (chosen != null && input != null) { + val shade = Color(0, 0, 0, 64) + for (t in input.targets(squareName(chosen))) { + val i = squareIndex(t) ?: continue + val c = cell(i) + Offset(sq / 2, sq / 2) + if (squares[i] != ' ') { + drawCircle(shade, radius = sq / 2 - sq * 0.045f, center = c, style = Stroke(width = sq * 0.09f)) + } else { + drawCircle(shade, radius = sq * 0.155f, center = c) + } + } + } + // Over the pieces, so that b, c, f, g stay readable (as on Lichess). + // Coordinates: files along the bottom edge, ranks along the left edge. + for (k in 0 until (if (coordinates) 8 else 0)) { + val fileIndex = if (flipped) 7 - k else k + val rankIndex = if (flipped) k else 7 - k + val bottomLight = (7 + k) % 2 == 0 + val leftLight = k % 2 == 0 + drawCoord(measurer, ('a' + fileIndex).toString(), coordStyle.copy(color = if (bottomLight) theme.dark else theme.light), + Offset((k + 1) * sq - with(density) { 8.sp.toPx() }, 8 * sq - with(density) { 13.sp.toPx() })) + drawCoord(measurer, ('1' + rankIndex).toString(), coordStyle.copy(color = if (leftLight) theme.dark else theme.light), + Offset(with(density) { 2.sp.toPx() }, k * sq + with(density) { 1.sp.toPx() })) + } + for (a in arrows) { + val f = squareIndex(a.from) ?: continue + val t = squareIndex(a.to) ?: continue + 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 + // under it so that one sees where it goes. + val held = dragAt + if (held != null && chosen != null) { + val under = indexAt(held, sq) + if (under != null) drawCircle(Color(0, 0, 0, 31), radius = sq, center = cell(under) + Offset(sq / 2, sq / 2)) + val big = (px * 1.5f).toInt() + pieces.bitmap(set, squares[chosen], big)?.let { + drawImage(it, dstOffset = IntOffset((held.x - big / 2f).toInt(), (held.y - lift - big / 2f).toInt()), dstSize = IntSize(big, big)) + } + } + } +} + +/// An arrow as on the desktop (board.rs `draw_arrow`): a shaft and a head that stops +/// short of the square's center. +private fun DrawScope.drawArrow(from: Offset, to: Offset, sq: Float, a: BoardArrow) { + val geometry = arrowGeometry(from, to, sq, a.weight) ?: return + val d = to - from + val dir = d / d.getDistance() + val width = sq * 0.16f * a.weight + val headW = sq * 0.38f * kotlin.math.sqrt(a.weight) + val normal = Offset(-dir.y, dir.x) + drawLine(a.color, geometry.start, geometry.base, strokeWidth = width) + val head = Path().apply { + moveTo(geometry.tip.x, geometry.tip.y) + lineTo(geometry.base.x + normal.x * headW, geometry.base.y + normal.y * headW) + lineTo(geometry.base.x - normal.x * headW, geometry.base.y - normal.y * headW) + close() + } + drawPath(head, a.color) +} + +private fun DrawScope.drawCoord( + measurer: androidx.compose.ui.text.TextMeasurer, + text: String, + style: TextStyle, + at: Offset, +) { + drawText(measurer, text, at, style) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/BoardStyleScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/BoardStyleScreen.kt new file mode 100644 index 0000000..9b911c2 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/BoardStyleScreen.kt @@ -0,0 +1,256 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.border +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.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SecondaryTabRow +import androidx.compose.material3.Tab +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.produceState +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.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.BoardTheme +import io.github.vrubelroman.chesspenguin.data.PieceSet +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/// A position to see a board and its pieces by: the Ruy Lopez after 3.Bb5. +private const val SAMPLE = "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3" + +/// "Board and pieces": the boards and the piece sets of the desktop app, chosen at once +/// and seen on a board above them (android-ui.md §9). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun BoardStyleScreen(onBack: () -> Unit) { + val app = app() + val context = LocalContext.current + val prefs by app.settings.prefs.collectAsState() + val pieces = remember { Pieces(context) } + val landscape = LocalConfiguration.current.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.board_and_pieces)) }, + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + ) + }, + ) { padding -> + val preview: @Composable (Modifier) -> Unit = { modifier -> + Board( + fen = SAMPLE, + flipped = false, + lastFrom = "f1", + lastTo = "b5", + pieces = pieces, + theme = prefs.board, + set = prefs.pieces, + description = boardLabel(prefs.board) + " · " + prefs.pieces.dir, + animated = false, + modifier = modifier, + ) + } + val choices: @Composable (Modifier) -> Unit = { modifier -> + Choices( + board = prefs.board, + set = prefs.pieces, + pieces = pieces, + onBoard = { b -> app.settings.update { it.copy(board = b) } }, + onSet = { p -> app.settings.update { it.copy(pieces = p) } }, + modifier = modifier, + ) + } + // The board stays in sight while the choices scroll under it (or beside it). + if (landscape) { + Row(Modifier.fillMaxSize().padding(padding)) { + Box(Modifier.fillMaxSize().weight(1f), contentAlignment = Alignment.Center) { + preview(Modifier.padding(16.dp).fillMaxSize()) + } + choices(Modifier.weight(1.4f)) + } + } else { + Column(Modifier.fillMaxSize().padding(padding)) { + Box(Modifier.fillMaxWidth().padding(vertical = 12.dp), contentAlignment = Alignment.Center) { + preview(Modifier.fillMaxWidth(0.6f).widthIn(max = 240.dp)) + } + choices(Modifier.weight(1f)) + } + } + } +} + +/// "Wood 2": the board's name in the interface language. +@Composable +fun boardLabel(b: BoardTheme): String = stringResource(b.label) + (b.number?.let { " $it" } ?: "") + +/// Two tabs, so that the piece sets are not hidden under 37 boards. +@Composable +private fun Choices( + board: BoardTheme, + set: PieceSet, + pieces: Pieces, + onBoard: (BoardTheme) -> Unit, + onSet: (PieceSet) -> Unit, + modifier: Modifier, +) { + var tab by rememberSaveable { mutableIntStateOf(0) } + Column(modifier) { + SecondaryTabRow(selectedTabIndex = tab) { + Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.board)) }) + Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.pieces_tab)) }) + } + LazyVerticalGrid( + GridCells.Adaptive(88.dp), + Modifier.fillMaxSize(), + contentPadding = androidx.compose.foundation.layout.PaddingValues(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (tab == 0) { + items(BoardTheme.entries, key = { "b" + it.name }) { b -> + Swatch(b, b == board) { onBoard(b) } + } + } else { + items(PieceSet.entries, key = { "p" + it.name }) { p -> + PieceChoice(p, p == set, board, pieces) { onSet(p) } + } + } + } + } +} + +/// The ring around the chosen board or set. +@Composable +private fun Modifier.chosen(selected: Boolean, shape: RoundedCornerShape): Modifier = + if (selected) border(3.dp, MaterialTheme.colorScheme.primary, shape) else this + +/// A board as 2×2 squares (the corner of its image), its name under it. +@Composable +private fun Swatch(b: BoardTheme, selected: Boolean, onClick: () -> Unit) { + val context = LocalContext.current + var side by remember { mutableIntStateOf(0) } + val corner by produceState(null, b, side) { + val file = b.texture ?: return@produceState + if (side > 0) value = withContext(Dispatchers.IO) { boardCorner(context, file, side) } + } + val shape = RoundedCornerShape(6.dp) + Column( + Modifier + .clip(RoundedCornerShape(8.dp)) + .selectable(selected = selected, role = Role.RadioButton, onClick = onClick) + .padding(4.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Canvas( + Modifier + .fillMaxWidth() + .aspectRatio(1f) + .chosen(selected, shape) + .padding(if (selected) 5.dp else 0.dp) + .clip(RoundedCornerShape(if (selected) 2.dp else 6.dp)) + .onSizeChanged { side = it.width }, + ) { + val image = corner + if (image != null) { + drawImage(image, dstOffset = IntOffset.Zero, dstSize = IntSize(size.width.toInt(), size.height.toInt())) + } else { + val sq = size.width / 2 + // a1 dark at the bottom left, as on the board. + drawRect(b.light, Offset(0f, 0f), Size(sq, sq)) + drawRect(b.dark, Offset(sq, 0f), Size(sq, sq)) + drawRect(b.dark, Offset(0f, sq), Size(sq, sq)) + drawRect(b.light, Offset(sq, sq), Size(sq, sq)) + } + } + Label(boardLabel(b), selected) + } +} + +/// A set as its white knight on a light square and black queen on a dark one of the +/// chosen board (a dark set stays readable), its name under them. +@Composable +private fun PieceChoice(p: PieceSet, selected: Boolean, board: BoardTheme, pieces: Pieces, onClick: () -> Unit) { + val shape = RoundedCornerShape(6.dp) + Column( + Modifier + .clip(RoundedCornerShape(8.dp)) + .selectable(selected = selected, role = Role.RadioButton, onClick = onClick) + .padding(4.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Canvas( + Modifier + .fillMaxWidth() + .aspectRatio(2f) + .chosen(selected, shape) + .padding(if (selected) 5.dp else 0.dp) + .clip(RoundedCornerShape(if (selected) 2.dp else 6.dp)), + ) { + val sq = size.height + val px = sq.toInt() + val gap = (size.width - 2 * sq) / 2 + drawRect(board.light, Offset(gap, 0f), Size(sq, sq)) + drawRect(board.dark, Offset(gap + sq, 0f), Size(sq, sq)) + pieces.bitmap(p, 'N', px)?.let { drawImage(it, dstOffset = IntOffset(gap.toInt(), 0), dstSize = IntSize(px, px)) } + pieces.bitmap(p, 'q', px)?.let { drawImage(it, dstOffset = IntOffset((gap + sq).toInt(), 0), dstSize = IntSize(px, px)) } + } + Label(p.dir, selected) + } +} + +@Composable +private fun Label(text: String, selected: Boolean) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 4.dp), + ) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt new file mode 100644 index 0000000..f7476d1 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt @@ -0,0 +1,338 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.border +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.withStyle +import io.github.vrubelroman.chesspenguin.ChessPenguinApp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.theme.Tabular +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.fillMaxSize +import io.github.vrubelroman.chesspenguin.theme.kindColor +import io.github.vrubelroman.chesspenguin.theme.LocalChessColors +import io.github.vrubelroman.chesspenguin.theme.DbKind +import io.github.vrubelroman.chesspenguin.data.Notation +import io.github.vrubelroman.chesspenguin.data.DbEntry +import io.github.vrubelroman.chesspenguin.data.Source +import androidx.compose.ui.res.stringResource + +@Composable +fun app(): ChessPenguinApp = LocalContext.current.applicationContext as ChessPenguinApp + +/// 1248 → "1 248": digit groups apart, as on the desktop. +fun groupDigits(n: Int): String = "%,d".format(n).replace(',', ' ').replace(' ', ' ') + +/// The name on the list: a sample keeps the name of the current language until renamed. +@Composable +fun displayName(e: DbEntry): String = when { + e.source != Source.Sample || e.renamed -> e.name + e.id == "sample-classics.pgn" -> stringResource(R.string.sample_classics) + e.id == "sample-alekhine.pgn" -> stringResource(R.string.sample_alekhine) + else -> e.name +} + +/// The label of a database's format, for its badge (§10.6). +fun badge(e: DbEntry): String { + val ext = e.fileName.substringAfterLast('.', "").lowercase() + return when (ext) { + "zip" -> "ZIP" + "7z" -> "7Z" + "cbv", "cbh", "cbz" -> "CB" + else -> "PGN" + } +} + +/// The format of a database in words, as the core names it once it is opened. +fun formatName(e: DbEntry): String = when (e.fileName.substringAfterLast('.', "").lowercase()) { + "cbh" -> "ChessBase" + "cbv" -> "ChessBase CBV" + "zip" -> "ZIP" + "7z" -> "7z" + else -> "PGN" +} + +/// What kind of database an entry is (its badge's colour, android-lists.md §5.1). +fun kindOf(e: DbEntry): DbKind { + return when { + e.source == Source.Own -> DbKind.Own + e.source == Source.Online -> DbKind.Online + else -> when (badge(e)) { + "CB" -> DbKind.ChessBase + "7Z", "ZIP" -> DbKind.Archive + else -> DbKind.Pgn + } + } +} + +/// A database's badge: 40 dp, the colour of its kind, a word or an icon on it. +@Composable +fun KindBadge( + kind: DbKind, + error: Boolean = false, + content: @Composable (Color) -> Unit, +) { + val c = kindColor(kind, LocalChessColors.current.dark) + Box( + Modifier + .size(40.dp) + .clip(RoundedCornerShape(10.dp)) + .background(if (error) MaterialTheme.colorScheme.errorContainer else c.container), + contentAlignment = Alignment.Center, + ) { content(if (error) MaterialTheme.colorScheme.error else c.content) } +} + +@Composable +fun FormatBadge(text: String, error: Boolean = false, kind: DbKind = DbKind.Pgn) { + KindBadge(kind, error) { color -> Text(text, style = MaterialTheme.typography.labelSmall, color = color) } +} + +/// The shape of a card in a group of `count` (android-lists.md §5.3): 16 dp outside, +/// 4 dp where it meets its neighbours. +fun groupShape(index: Int, count: Int): RoundedCornerShape { + val top = if (index == 0) 16.dp else 4.dp + val bottom = if (index == count - 1) 16.dp else 4.dp + return RoundedCornerShape(topStart = top, topEnd = top, bottomStart = bottom, bottomEnd = bottom) +} + +/// A row of a group drawn as its card: 12 dp from the screen's edges, 2 dp between cards. +@Composable +fun Modifier.groupCard(index: Int, count: Int): Modifier { + val shape = groupShape(index, count) + return this + .padding(start = 12.dp, end = 12.dp, bottom = 2.dp) + .clip(shape) + .background(MaterialTheme.colorScheme.surfaceContainerLow, shape) +} + +/// "Carlsen, Magnus" → "Carlsen M."; other names stay as in the file (§6.2). +fun shortName(name: String): String { + val n = name.trim() + if (n.isEmpty() || n == "?") return "?" + val comma = n.indexOf(',') + if (comma <= 0) return n + val surname = n.substring(0, comma).trim() + val initials = n.substring(comma + 1).trim().split(' ', '-').filter { it.isNotEmpty() }.joinToString(" ") { "${it.first()}." } + return if (initials.isEmpty()) surname else "$surname $initials" +} + +/// A player's name (android-ui.md §7.11): in full while it fits, else "Surname F.", else +/// cut with "…". `abbreviate = false` keeps the text as it is (a study's title for White). +@Composable +fun PlayerName( + name: String, + style: TextStyle, + modifier: Modifier = Modifier, + color: Color = Color.Unspecified, + maxLines: Int = 1, + abbreviate: Boolean = true, + /// Words searched for: shown marked where they are in the name as shown. + highlight: String? = null, +) { + val measurer = rememberTextMeasurer() + BoxWithConstraints(modifier) { + val text = if (abbreviate && measurer.measure(name, style, softWrap = false).size.width > constraints.maxWidth) shortName(name) else name + Text(highlighted(text, highlight), style = style, color = color, maxLines = maxLines, overflow = TextOverflow.Ellipsis) + } +} + +/// `text` with the first place of each searched word marked (android-lists.md §3.7); +/// case does not matter. +@Composable +fun highlighted(text: String, query: String?): AnnotatedString { + val words = query?.split(' ')?.filter { it.isNotBlank() }.orEmpty() + if (words.isEmpty()) return AnnotatedString(text) + val mark = SpanStyle( + background = MaterialTheme.colorScheme.primaryContainer, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + return buildAnnotatedString { + append(text) + for (w in words) { + val at = text.indexOf(w, ignoreCase = true) + if (at >= 0) addStyle(mark, at, at + w.length) + } + } +} + +/// A player's share of the result in the list of games (android-lists.md §3.3): the +/// winner's «1» on a tile, «½» on a quieter one, a loss as a plain «0». +@Composable +fun ResultTile(result: String?) { + // At least 24×20 dp; it grows with the font. + Box(Modifier.widthIn(min = 24.dp).heightIn(min = 20.dp), contentAlignment = Alignment.Center) { + when (result) { + "1" -> Box( + Modifier.widthIn(min = 24.dp).heightIn(min = 20.dp).clip(RoundedCornerShape(6.dp)).background(MaterialTheme.colorScheme.primaryContainer), + contentAlignment = Alignment.Center, + ) { + Text("1", style = MaterialTheme.typography.labelLarge.merge(Tabular), fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onPrimaryContainer) + } + "½" -> Box( + Modifier.widthIn(min = 24.dp).heightIn(min = 20.dp).clip(RoundedCornerShape(6.dp)).background(MaterialTheme.colorScheme.surfaceContainerHigh), + contentAlignment = Alignment.Center, + ) { + Text("½", style = MaterialTheme.typography.labelLarge.merge(Tabular), color = MaterialTheme.colorScheme.onSurface) + } + null -> {} + else -> Text(result, style = MaterialTheme.typography.labelLarge.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +/// A player's share of the result: "1", "0", "½", or null (unknown, unfinished). +fun sideResult(result: String, white: Boolean): String? = when (result) { + "1-0" -> if (white) "1" else "0" + "0-1" -> if (white) "0" else "1" + "1/2-1/2" -> "½" + else -> null +} + +/// The rating of a player, or nothing ("0", "?", ""). +fun elo(value: String): String = value.trim().takeIf { v -> v.toIntOrNull()?.let { it > 0 } == true } ?: "" + +/// The colour of a side: a small disc (white with a rim, or black). +@Composable +fun SideDisc(white: Boolean, size: androidx.compose.ui.unit.Dp = 12.dp) { + // Black darker than any background, white whiter; the ring in the text's muted colour + // keeps either from reading as an empty circle (android-lists.md §3.2). + val dark = LocalChessColors.current.dark + Box( + Modifier.size(size).clip(CircleShape) + .background(if (white) Color.White else if (dark) Color(0xFF0E0F10) else Color(0xFF1C1D1F)) + .border(1.dp, MaterialTheme.colorScheme.onSurfaceVariant, CircleShape), + ) +} + +/// One player's line: name (giving way), Elo, the share of the result on the right. +@Composable +fun PlayerLine( + name: String, + elo: String, + result: String?, + style: TextStyle, + modifier: Modifier = Modifier, + disc: Boolean? = null, + nameColor: Color = Color.Unspecified, + maxLines: Int = 1, + abbreviate: Boolean = true, + /// What the player is doing now («thinking…» of Maia, android-play.md §31.3). + status: String? = null, +) { + Row(modifier, verticalAlignment = Alignment.CenterVertically) { + if (disc != null) { + SideDisc(disc) + Spacer(Modifier.width(8.dp)) + } + Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + PlayerName(name, style, Modifier.weight(1f, fill = false), nameColor, maxLines, abbreviate) + if (elo.isNotEmpty()) { + Spacer(Modifier.width(8.dp)) + Text(elo, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) + } + } + if (status != null) { + androidx.compose.material3.CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp) + Text(status, Modifier.padding(start = 6.dp), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, softWrap = false) + } + Text( + result ?: "", + style = style.merge(Tabular), + color = if (result == "1") MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + fontWeight = if (result == "1") androidx.compose.ui.text.font.FontWeight.Medium else null, + textAlign = androidx.compose.ui.text.style.TextAlign.End, + maxLines = 1, + modifier = Modifier.width(24.dp), + ) + } +} + +/// "1/2-1/2" → "½-½". +fun shortResult(result: String): String = when (result) { + "1/2-1/2" -> "½-½" + "" -> "*" + else -> result +} + +/// The year of a PGN date ("1927.??.??" → "1927"), or nothing. +fun year(date: String): String = date.take(4).takeIf { y -> y.length == 4 && y.all { it.isDigit() } } ?: "" + +/// The parts that are known, joined with " · " (empty values and "?" left out). +fun joinKnown(vararg parts: String): String = parts.map { it.trim() }.filter { it.isNotEmpty() && it != "?" }.joinToString(" · ") + +/// The figurines of the desktop app (OFL, apps/desktop/assets/fonts/OFL.txt). +val Figurines = FontFamily(Font(R.font.figurines)) + +/// King, queen, rook, bishop, knight in a language, as on the desktop (san.rs). +fun localLetters(lang: String): List? = when (lang) { + "ru" -> listOf("Кр", "Ф", "Л", "С", "К") + "de" -> listOf("K", "D", "T", "L", "S") + "fr" -> listOf("R", "D", "T", "F", "C") + "es", "it" -> listOf("R", "D", "T", "A", "C") + "pt" -> listOf("R", "D", "T", "B", "C") + else -> null +} + +/// A SAN move as shown: the piece letter at the start and after "=" replaced; the +/// game itself stays in Latin SAN. +fun displaySan(san: String, mode: Notation, lang: String): AnnotatedString { + val local = localLetters(lang) + if (mode == Notation.Latin || (mode == Notation.Local && local == null)) return AnnotatedString(san) + return buildAnnotatedString { + san.forEachIndexed { i, c -> + val k = "KQRBN".indexOf(c) + val piece = k >= 0 && (i == 0 || san[i - 1] == '=') + when { + !piece -> append(c) + mode == Notation.Figurines -> withStyle(SpanStyle(fontFamily = Figurines)) { append("♔♕♖♗♘"[k]) } + else -> append(local!![k]) + } + } + } +} + +/// A line like "14.Nd5 Bxd5 15.exd5": each move shown with [displaySan]. +fun displayLine(text: String, mode: Notation, lang: String): AnnotatedString { + if (mode == Notation.Latin) return AnnotatedString(text) + return buildAnnotatedString { + text.split(' ').forEachIndexed { i, word -> + if (i > 0) append(' ') + val cut = word.indexOfLast { it == '.' || it == '…' } + 1 + append(word.substring(0, cut)) + append(displaySan(word.substring(cut), mode, lang)) + } + } +} + +/// The language of the interface ("ru", "en", …). +@Composable +fun uiLanguage(): String = LocalConfiguration.current.locales[0].language diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt new file mode 100644 index 0000000..5b32995 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt @@ -0,0 +1,824 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.layout.heightIn +import androidx.compose.material3.ButtonDefaults +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.width +import androidx.compose.ui.text.font.FontWeight +import io.github.vrubelroman.chesspenguin.theme.DbKind +import androidx.compose.material.icons.rounded.CloudDownload +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.text.SpanStyle +import android.content.ClipboardManager +import android.text.format.DateUtils +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.background +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.draw.clip +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.EditNote +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.SmartToy +import androidx.compose.material.icons.rounded.MoreVert +import androidx.compose.material.icons.rounded.Settings +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalResources +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +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 androidx.compose.material3.LinearProgressIndicator +import io.github.vrubelroman.chesspenguin.data.DownloadView +import io.github.vrubelroman.chesspenguin.data.Finished +import io.github.vrubelroman.chesspenguin.data.DbEntry +import io.github.vrubelroman.chesspenguin.data.FolderScan +import io.github.vrubelroman.chesspenguin.data.Source +import uniffi.mobile_api.Database +import kotlinx.coroutines.launch + +/// The first screen: the databases on the list (android-ui.md §3). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit, onOnline: () -> Unit, onNewGame: () -> Unit, onPlay: () -> Unit) { + val library = app().library + val downloads = app().downloads + val views by downloads.views.collectAsState() + val entries by library.entries.collectAsState() + val snackbar = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val removedText = stringResource(R.string.removed) + val removedCopyText = stringResource(R.string.removed_copy) + val removedOwnText = stringResource(R.string.own_removed) + val update = shownUpdate() + val offersOffText = stringResource(R.string.upd_offers_off_snack) + val offersUndoText = stringResource(R.string.undo) + val updatesForUndo = app().updates + // The card's ×: offers are off; «Undo» for a slip of the finger (android-ui.md §25.2). + val onUpdateDismissed: () -> Unit = { + scope.launch { + snackbar.currentSnackbarData?.dismiss() + if (snackbar.showSnackbar(offersOffText, offersUndoText, duration = androidx.compose.material3.SnackbarDuration.Long) == androidx.compose.material3.SnackbarResult.ActionPerformed) { + updatesForUndo.setOffer(true) + } + } + } + UpdateMessages(snackbar) + val removedOnlineText = stringResource(R.string.online_removed) + val resourcesForSnack = LocalResources.current + val openText = stringResource(R.string.online_open_short) + // How a download ended, said while this screen is shown (android-ui.md §23.3). + LaunchedEffect(Unit) { + downloads.finished.collect { f -> + val text = finishedText(resourcesForSnack, f) ?: return@collect + snackbar.currentSnackbarData?.dismiss() + val canOpen = f.games > 0 && library.entry(f.id) != null + if (snackbar.showSnackbar(text, if (canOpen) openText else null, withDismissAction = false) == SnackbarResult.ActionPerformed) onOpen(f.id) + } + } + val undoText = stringResource(R.string.undo) + val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) onOpen(library.addFile(uri).id) + } + var choosing by remember { mutableStateOf(false) } + // The folder sheet: shown while `folderOpen`, `scan` null while looking through it. + // The picked folder outlives a rotation; it is then looked through again. + var folderOpen by rememberSaveable { mutableStateOf(false) } + var folder by rememberSaveable { mutableStateOf(null) } + var scan by remember { mutableStateOf(null) } + LaunchedEffect(folderOpen, folder) { + val tree = folder + if (folderOpen && tree != null && scan?.tree != tree) scan = library.scanFolder(tree) + } + val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { tree -> + if (tree != null) { + scan = null + library.keepFolder(tree) + folder = tree + folderOpen = true + } + } + val add = { choosing = true } + var renaming by remember { mutableStateOf(null) } + // Own databases (android-play.md §30): a new one asked for, one to delete asked about. + var creating by remember { mutableStateOf(false) } + var deleting by remember { mutableStateOf(null) } + var exporting by remember { mutableStateOf(null) } + val context = androidx.compose.ui.platform.LocalContext.current + val exportedText = stringResource(R.string.own_exported) + val exportFailedText = stringResource(R.string.own_export_failed) + val export = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/x-chess-pgn")) { uri -> + val e = exporting + exporting = null + if (uri == null || e == null) return@rememberLauncherForActivityResult + scope.launch { + val ok = withContext(Dispatchers.IO) { + runCatching { + context.contentResolver.openOutputStream(uri, "wt")!!.use { out -> library.ownFile(e).inputStream().use { it.copyTo(out) } } + }.isSuccess + } + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(if (ok) exportedText else exportFailedText) + } + } + val own = entries.filter { it.source == Source.Own } + val theApp = app() + val adjourned by theApp.maiaGames.current.collectAsState() + // Back on the list of databases, a list of games was left: its mark goes (android-lists.md §3.6). + LaunchedEffect(Unit) { theApp.lastOpened.clear() } + val playRemovedText = stringResource(R.string.play_removed) + val keptText = stringResource(R.string.player_kept_unfinished) + var playing by remember { mutableStateOf(false) } + // A game put aside: asked about before a new one replaces it. + var askingAdjourned by remember { mutableStateOf(false) } + adjourned?.takeIf { askingAdjourned && !it.over }?.let { m -> + AdjournedQuestion(m, onContinue = { + askingAdjourned = false + onPlay() + }, onNew = { + askingAdjourned = false + playing = true + }, onDismiss = { askingAdjourned = false }) + } + val eventText = stringResource(R.string.play_event) + if (playing) { + PlaySheet(null, onPlay = { choice -> + playing = false + val s = uniffi.mobile_api.GameSession.newGame("") + beginComputerGame(theApp, s, choice.meta(0), eventText, null) + s.close() + onPlay() + }, onDismiss = { playing = false }) + } + val files = entries.filter { it.source != Source.Own } + val list = rememberLazyListState() + // The card of a game just put aside is brought into sight. + LaunchedEffect(adjourned) { + if (adjourned?.over == false) list.animateScrollToItem(0) + } + // The card comes when GitHub answers, after the list is drawn: a list at its top then + // keeps its first database in place and the card lands above the screen. It is + // brought into sight; a list scrolled down by the user stays where it is. + val cardShown = update != null + LaunchedEffect(cardShown) { + if (cardShown && list.firstVisibleItemIndex == 1 && list.firstVisibleItemScrollOffset == 0) list.animateScrollToItem(0) + } + val scroll = TopAppBarDefaults.pinnedScrollBehavior() + // The samples are small: read them at once, so their rows show the number of games. + LaunchedEffect(Unit) { library.countSamples() } + + Scaffold( + modifier = Modifier.nestedScroll(scroll.nestedScrollConnection), + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.app_name)) }, + actions = { + IconButton(onClick = onSettings) { Icon(Icons.Rounded.Settings, stringResource(R.string.settings)) } + }, + scrollBehavior = scroll, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + if (entries.isEmpty()) { + Column(Modifier.padding(padding)) { + update?.let { UpdateCard(it, onDismissed = onUpdateDismissed) } + Empty(Modifier.weight(1f), onAdd = add, onSamples = { + library.addSamples() + library.entries.value.firstOrNull()?.let { onOpen(it.id) } + }) + } + } else { + LazyColumn( + Modifier.fillMaxSize(), + state = list, + contentPadding = PaddingValues(top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding() + 16.dp), + ) { + // A newer version of the app (android-ui.md §25.2): the first item of the list. + update?.let { u -> item(key = "update") { UpdateCard(u, onDismissed = onUpdateDismissed, modifier = Modifier.animateItem()) } } + // A game against the computer put aside (§31.7): go on with it, or let it go. + adjourned?.takeIf { !it.over }?.let { m -> + item(key = "adjourned") { + // The game's position on a small board, the side and the move, and + // «Continue» as the screen's main action while it waits (android-lists.md §5.4). + val shownAt = remember(m) { adjournedPosition(theApp.maiaGames.pgn()) } + val sideText = stringResource(if (m.userWhite) R.string.play_as_white else R.string.play_as_black) + // «you play Black · move 2», Rodent's character first, as the game's header + // says it (android-rodent.md §6.5): «Tal · you play Black · move 2». + val played = shownAt?.second?.let { stringResource(R.string.play_adjourned_sub, sideText, stringResource(R.string.play_move_n, it)) } ?: sideText + val sub = listOfNotNull(m.styleShown(), played).joinToString(" · ") + val title = stringResource(R.string.play_adjourned_title, m.label()) + Row( + Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp) + .clip(RoundedCornerShape(16.dp)) + .background(MaterialTheme.colorScheme.primaryContainer) + .clickable(onClick = onPlay) + .semantics(mergeDescendants = true) {} + .padding(start = 12.dp, top = 12.dp, bottom = 12.dp, end = 4.dp), + verticalAlignment = Alignment.Top, + ) { + shownAt?.let { (fen, _) -> + Box(Modifier.clip(RoundedCornerShape(6.dp))) { MiniBoard(fen, flipped = !m.userWhite, size = 72.dp) } + Spacer(Modifier.width(12.dp)) + } + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onPrimaryContainer) + Text(sub, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onPrimaryContainer) + Spacer(Modifier.height(8.dp)) + Button(onClick = onPlay, modifier = Modifier.heightIn(min = 32.dp), contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp)) { + Text(stringResource(R.string.play_continue)) + } + } + IconButton(onClick = { + // Played on both sides: kept in the player's database, + // unfinished (no «Undo»: it is there to be deleted). + val kept = theApp.playerGames.keepUnfinished(theApp.maiaGames, theApp.settings.prefs.value.recordGames, scope) { w -> + scope.launch { + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(String.format(keptText, w.name)) + } + } + if (kept) { + theApp.maiaGames.clear() + return@IconButton + } + val pgn = theApp.maiaGames.pgn() + theApp.maiaGames.clear() + scope.launch { + snackbar.currentSnackbarData?.dismiss() + if (snackbar.showSnackbar(playRemovedText, undoText, duration = SnackbarDuration.Long) == SnackbarResult.ActionPerformed && pgn != null) { + theApp.maiaGames.begin(pgn, m) + } + } + }) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } + } + } + } + item(key = "actions") { + // Two equal buttons over the whole width (android-lists.md §5.5). + // Neutral, as the cards' edges: the blue stays for the game put aside. + val quiet = ButtonDefaults.filledTonalButtonColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, + contentColor = MaterialTheme.colorScheme.onSurface, + ) + Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + // «Play»: the opponent is chosen on the sheet (android-rodent.md, question 6). + val playLabel = stringResource(R.string.play_button_cd) + FilledTonalButton( + onClick = { if (adjourned?.over == false) askingAdjourned = true else playing = true }, + modifier = Modifier.weight(1f).heightIn(min = 56.dp).semantics { contentDescription = playLabel }, + shape = RoundedCornerShape(16.dp), + colors = quiet, + ) { + Icon(Icons.Rounded.SmartToy, null, tint = MaterialTheme.colorScheme.primary) + Spacer(Modifier.size(8.dp)) + Text(stringResource(R.string.play_button)) + } + FilledTonalButton(onClick = onNewGame, modifier = Modifier.weight(1f).heightIn(min = 56.dp), shape = RoundedCornerShape(16.dp), colors = quiet) { + Icon(Icons.Rounded.Add, null, tint = MaterialTheme.colorScheme.primary) + Spacer(Modifier.size(8.dp)) + Text(stringResource(R.string.new_game)) + } + } + } + item(key = "own-head") { + Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.own_databases), Modifier.weight(1f), style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) + TextButton(onClick = { creating = true }) { Text(stringResource(R.string.own_new)) } + } + } + if (own.isEmpty()) { + item(key = "own-empty") { + Text( + stringResource(R.string.own_empty), + Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + items(own.size, key = { own[it].id }) { k -> + val e = own[k] + OwnRow( + e, + player = theApp.playerGames.isPlayers(e.id), + onOpen = { onOpen(e.id) }, + onRename = { renaming = e }, + onExport = { + exporting = e + export.launch(e.name + ".pgn") + }, + onDelete = { + if ((e.games ?: 0) == 0) { + val removed = library.remove(e.id) ?: return@OwnRow + scope.launch { + snackbar.currentSnackbarData?.dismiss() + var restored = false + try { + if (snackbar.showSnackbar(removedOwnText, undoText, withDismissAction = false, duration = SnackbarDuration.Long) == SnackbarResult.ActionPerformed) { + library.restore(removed.first, removed.second) + restored = true + } + } finally { + if (!restored) library.forget(removed.second) + } + } + } else { + deleting = e + } + }, + modifier = Modifier.animateItem().groupCard(k, own.size), + ) + } + // «+ Add» in the section's heading, as «+ New database» in its own: nothing + // floats over the list. + item(key = "files-head") { + val addLabel = stringResource(R.string.add_database) + Row(Modifier.fillMaxWidth().padding(top = 8.dp).height(48.dp).padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.files), Modifier.weight(1f), style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) + TextButton(onClick = add, modifier = Modifier.semantics { contentDescription = addLabel }) { Text(stringResource(R.string.files_add)) } + } + } + if (files.isEmpty()) { + item(key = "files-empty") { + Text( + stringResource(R.string.files_empty), + Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + items(files.size, key = { files[it].id }) { k -> + val e = files[k] + DatabaseRow( + e, + download = views[e.id], + onOpen = { onOpen(e.id) }, + onRename = { renaming = e }, + onUpdate = { downloads.update(e) }, + onStop = { downloads.cancel(e.id) }, + onRemove = { + // A download into it stops first: its file goes with it. + downloads.cancel(e.id) + val removed = library.remove(e.id) ?: return@DatabaseRow + scope.launch { + snackbar.currentSnackbarData?.dismiss() + var restored = false + try { + // A copy is deleted, not only taken off the list. + val text = when (e.source) { + Source.Copy -> removedCopyText + Source.Online -> removedOnlineText + else -> removedText + } + // Not for ever: the deleted file goes once "Undo" is gone. + if (snackbar.showSnackbar(text, undoText, withDismissAction = false, duration = SnackbarDuration.Long) == SnackbarResult.ActionPerformed) { + library.restore(removed.first, removed.second) + restored = true + } + } finally { + // Also when the screen goes away while "Undo" is offered. + if (!restored) library.forget(removed.second) + } + } + }, + modifier = Modifier.animateItem().groupCard(k, files.size), + ) + } + } + } + } + val pasteNone = stringResource(R.string.paste_none) + val resources = LocalResources.current + if (choosing) { + val clipboard = remember { context.getSystemService(ClipboardManager::class.java) } + val hasText = remember { clipboard.primaryClipDescription?.hasMimeType("text/*") == true } + AddSheet( + onFile = { + choosing = false + pick.launch(arrayOf("*/*")) + }, + onFolder = { + choosing = false + pickFolder.launch(null) + }, + onPaste = if (!hasText) null else { + { + choosing = false + val text = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(context)?.toString().orEmpty() + val dated = resources.getString( + R.string.paste_db, + DateUtils.formatDateTime(context, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH), + ) + scope.launch { + runCatching { + library.addCopy("clipboard.pgn", text.byteInputStream()) { db -> pastedName(db, dated) } + }.onSuccess(onAdded).onFailure { + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(pasteNone) + } + } + } + }, + onOnline = { + choosing = false + onOnline() + }, + onDismiss = { choosing = false }, + ) + } + if (folderOpen) { + FolderSheet( + scan, + onAdd = { chosen -> + val s = scan ?: return@FolderSheet + library.addFound(s.tree, chosen) + folderOpen = false + val n = chosen.count { !it.added && !it.incomplete } + scope.launch { + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(resources.getQuantityString(R.plurals.added_count, n, n)) + } + // Nothing added: the folder's permission goes back. + if (n == 0) library.forgetFolder(s.tree) + }, + onPickAnother = { + folderOpen = false + folder?.let { library.forgetFolder(it) } + pickFolder.launch(null) + }, + onDismiss = { + folderOpen = false + folder?.let { library.forgetFolder(it) } + }, + ) + } + renaming?.let { e -> + RenameDialog(displayName(e), own = e.source == Source.Own, onDismiss = { renaming = null }, onSave = { + library.rename(e.id, it) + renaming = null + }) + } + if (creating) { + NewOwnDialog( + suggested = freeName(stringResource(R.string.own_default_name), own.map { it.name }), + onDismiss = { creating = false }, + onCreate = { name -> + creating = false + scope.launch { runCatching { library.createOwn(name) } } + }, + ) + } + deleting?.let { e -> + val n = e.games ?: 0 + AlertDialog( + onDismissRequest = { deleting = null }, + title = { Text(stringResource(R.string.own_delete_title, displayName(e))) }, + text = { Text(pluralStringResource(R.plurals.own_delete_text, n, groupDigits(n))) }, + confirmButton = { + TextButton(onClick = { + deleting = null + library.remove(e.id)?.let { library.forget(it.second) } + }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { TextButton(onClick = { deleting = null }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +/// "My games", or "My games 2" when that one is taken. +fun freeName(base: String, taken: List): String { + if (base !in taken) return base + var i = 2 + while ("$base $i" in taken) i++ + return "$base $i" +} + +@Composable +private fun NewOwnDialog(suggested: String, onDismiss: () -> Unit, onCreate: (String) -> Unit) { + var value by remember { mutableStateOf(TextFieldValue(suggested, TextRange(0, suggested.length))) } + val trimmed = value.text.trim() + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.own_new_title)) }, + text = { + OutlinedTextField( + value = value, + onValueChange = { value = it }, + singleLine = true, + label = { Text(stringResource(R.string.own_name)) }, + supportingText = { Text(stringResource(R.string.own_new_hint)) }, + ) + }, + confirmButton = { TextButton(onClick = { onCreate(trimmed) }, enabled = trimmed.isNotEmpty()) { Text(stringResource(R.string.create)) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } }, + ) +} + +/// An own database: its games are the user's, kept on the phone (android-play.md §30.2). +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun OwnRow(e: DbEntry, player: Boolean, onOpen: () -> Unit, onRename: () -> Unit, onExport: () -> Unit, onDelete: () -> Unit, modifier: Modifier) { + var menu by remember { mutableStateOf(false) } + val n = e.games ?: 0 + Box(modifier) { + Row( + Modifier + .fillMaxWidth() + .height(72.dp) + .combinedClickable(onClick = onOpen, onLongClick = { menu = true }) + .padding(start = 12.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + KindBadge(DbKind.Own) { color -> + // A player's database (games against Maia written by themselves): a knight. + if (player) { + Text("♞", style = MaterialTheme.typography.titleLarge, color = color) + } else { + Icon(Icons.Rounded.EditNote, null, tint = color) + } + } + Column(Modifier.weight(1f).padding(start = 12.dp)) { + Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + countFirst(pluralStringResource(R.plurals.games_count, n, groupDigits(n)), stringResource(if (player) R.string.player_db_row else R.string.own_on_phone)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem(text = { Text(stringResource(R.string.rename)) }, onClick = { + menu = false + onRename() + }) + DropdownMenuItem(text = { Text(stringResource(R.string.own_export)) }, onClick = { + menu = false + onExport() + }) + DropdownMenuItem(text = { Text(stringResource(R.string.own_delete)) }, onClick = { + menu = false + onDelete() + }) + } + } + } + } +} + +@Composable +private fun Empty(modifier: Modifier, onAdd: () -> Unit, onSamples: () -> Unit) { + Column( + modifier.fillMaxSize().padding(horizontal = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Image(painterResource(R.drawable.penguin), null, Modifier.size(96.dp)) + Spacer(Modifier.height(24.dp)) + Text(stringResource(R.string.empty_title), style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center) + Spacer(Modifier.height(12.dp)) + Text( + stringResource(R.string.empty_text), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.widthIn(max = 296.dp), + ) + Spacer(Modifier.height(32.dp)) + Button(onClick = onAdd, modifier = Modifier.height(48.dp)) { + Icon(Icons.Rounded.Add, null) + Spacer(Modifier.size(8.dp)) + Text(stringResource(R.string.add_database)) + } + TextButton(onClick = onSamples, modifier = Modifier.height(48.dp)) { Text(stringResource(R.string.open_samples)) } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun DatabaseRow( + e: DbEntry, + download: DownloadView?, + onOpen: () -> Unit, + onRename: () -> Unit, + onUpdate: () -> Unit, + onStop: () -> Unit, + onRemove: () -> Unit, + modifier: Modifier, +) { + var menu by remember { mutableStateOf(false) } + val format = badge(e) + val running = download?.state?.running == true + val failure = download?.state?.failure?.takeIf { !running } + val subtitle = e.games?.let { + stringResource(R.string.games_with_format, pluralStringResource(R.plurals.games_count, it, groupDigits(it)), e.format ?: format) + } ?: stringResource(R.string.not_opened, formatName(e)) + val gamesText = e.games?.let { pluralStringResource(R.plurals.games_count, it, groupDigits(it)) } + val shownSubtitle = when { + // A copy kept in the app says so: removing it deletes it. + e.source == Source.Copy -> subtitle + " · " + stringResource(R.string.db_copy) + e.source != Source.Online -> subtitle + // A downloaded database: how its download goes, or when it was last brought up to date. + running -> stringResource(R.string.online_downloading, groupDigits(((e.games ?: 0) + download.state.added.toInt()))) + else -> pluralStringResource(R.plurals.games_count, e.games ?: 0, groupDigits(e.games ?: 0)) + " · " + when { + // The games stay in the line: the database is not empty because a site failed. + failure != null -> onlineProblemShort(failure) + e.updated == null -> stringResource(R.string.online_unfinished) + System.currentTimeMillis() - e.updated * 1000 < 60_000 -> stringResource(R.string.online_updated_now) + else -> stringResource( + R.string.online_updated, + DateUtils.getRelativeTimeSpanString(e.updated * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString(), + ) + } + } + Box(modifier) { + Row( + Modifier + .fillMaxWidth() + .height(72.dp) + .combinedClickable(onClick = onOpen, onLongClick = { menu = true }) + .padding(start = 12.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + // A downloaded database is told by where it comes from, not by its format. + val kind = kindOf(e) + KindBadge(kind) { color -> + if (kind == DbKind.Online) Icon(Icons.Rounded.CloudDownload, null, tint = color, modifier = Modifier.size(22.dp)) + else Text(format, style = MaterialTheme.typography.labelSmall, color = color) + } + Column(Modifier.weight(1f).padding(start = 12.dp)) { + Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + // The number of games stands out (a big database from a small one). + if (failure == null && gamesText != null && shownSubtitle.startsWith(gamesText)) countFirst(gamesText, shownSubtitle.removePrefix(gamesText).removePrefix(" · ")) else androidx.compose.ui.text.AnnotatedString(shownSubtitle), + style = MaterialTheme.typography.bodyMedium, + color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + if (e.source == Source.Online) { + DropdownMenuItem(text = { Text(stringResource(if (running) R.string.online_stop_download else R.string.online_update)) }, onClick = { + menu = false + if (running) onStop() else onUpdate() + }) + } + DropdownMenuItem(text = { Text(stringResource(R.string.rename)) }, onClick = { + menu = false + onRename() + }) + DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, onClick = { + menu = false + onRemove() + }) + } + } + } + // A download going on: a thin bar along the bottom of the row (§23.3). + if (running) { + val share = downloadShare(download) + val bar = Modifier.fillMaxWidth().height(2.dp).align(Alignment.BottomStart) + if (share != null) LinearProgressIndicator(progress = { share }, modifier = bar) else LinearProgressIndicator(bar) + } + } +} + +@Composable +private fun RenameDialog(name: String, own: Boolean = false, onDismiss: () -> Unit, onSave: (String) -> Unit) { + var value by remember { mutableStateOf(TextFieldValue(name, TextRange(0, name.length))) } + val trimmed = value.text.trim() + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.rename)) }, + text = { + OutlinedTextField( + value = value, + onValueChange = { value = it }, + singleLine = true, + // An own database's file is ours: no "the file does not change". + supportingText = if (own) null else { { Text(stringResource(R.string.rename_hint)) } }, + ) + }, + confirmButton = { TextButton(onClick = { onSave(trimmed) }, enabled = trimmed.isNotEmpty()) { Text(stringResource(R.string.save)) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } }, + ) +} + +/// «**267 games** · PGN»: the number of games heavier and in the text's colour. +@Composable +private fun countFirst(count: String, rest: String): androidx.compose.ui.text.AnnotatedString { + val strong = SpanStyle(fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface) + return buildAnnotatedString { + withStyle(strong) { append(count) } + if (rest.isNotEmpty()) append(" · $rest") + } +} + +/// The position on the board of a game put aside, and the number of its last move. +private fun adjournedPosition(pgn: String?): Pair? { + pgn ?: return null + val s = runCatching { uniffi.mobile_api.GameSession.fromPgn(pgn) }.getOrNull() ?: return null + return try { + val d = s.data() + val end = lineEnd(d) + val node = d.nodes[end] + // The move to be made: after White's, the same number; after Black's, the next. + node.fen to (if (end == 0) 1 else node.moveNumber.toInt() + if (node.white) 0 else 1) + } finally { + s.close() + } +} + +/// The name of pasted games: one game by its players, games of one event by it, others by +/// when they were pasted (`dated`), so that two pastes differ. +private fun pastedName(db: Database, dated: String): String { + val rows = db.rowsOf((0u until db.len()).toList()) + if (rows.size == 1) { + val (white, black) = shortName(rows[0].white) to shortName(rows[0].black) + if (white != "?" || black != "?") return "$white – $black" + } else { + rows.map { it.event.trim() }.distinct().singleOrNull()?.takeIf { it.isNotEmpty() && it != "?" }?.let { return it } + } + return dated +} + +/// The snackbar of a finished download: "“Name�: +12, 1 246 games in all", "“Name�: no +/// new games", "“Name�: Lichess does not answer"; none when it was stopped or got nothing. +fun finishedText(res: android.content.res.Resources, f: Finished): String? { + val s = f.view.state + 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)) } + return when { + s.cancelled || f.games == 0 -> null + s.added == 0UL -> res.getString(R.string.online_snack_none, f.name) + else -> res.getString(R.string.online_snack_added, f.name, groupDigits(s.added.toInt()), games) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt new file mode 100644 index 0000000..503eab4 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt @@ -0,0 +1,315 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +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.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.ExpandLess +import androidx.compose.material.icons.rounded.ExpandMore +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +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.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.EngineStatus +import io.github.vrubelroman.chesspenguin.data.NetProblem +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.theme.Tabular +import uniffi.mobile_api.Analysis +import uniffi.mobile_api.EngineLine +import kotlin.math.exp + +/// White's share of the bar, as on Lichess: 0.5 is equal, 1 is White winning. +fun whiteShare(line: EngineLine?): Float { + if (line == null) return 0.5f + line.mate?.let { return if (it > 0) 1f else 0f } + val cp = (line.cp ?: 0).coerceIn(-1000, 1000) + return (0.5 + 0.5 * (2 / (1 + exp(-0.00368208 * cp)) - 1)).toFloat() +} + +/// The engine's row between the board and the notation (android-ui.md §8.2): the +/// evaluation, the depth, the best line; ▾ shows more lines. While the game is being +/// analysed (`waiting`, §21.6) the engine rests and the row says so. +@Composable +fun EngineStrip( + ending: String?, + status: EngineStatus, + analysis: Analysis?, + flipped: Boolean, + lines: Int, + expanded: Boolean, + onExpand: () -> Unit, + onLine: (EngineLine) -> Unit, + onDeeper: () -> Unit, + onRestart: () -> Unit, + notation: (String) -> AnnotatedString, + waiting: Boolean = false, +) { + val best = analysis?.lines?.firstOrNull() + val share by animateFloatAsState(whiteShare(best), tween(300), label = "eval") + Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainerLow)) { + // White's share on the left; on the right when the board is turned. + Row(Modifier.fillMaxWidth().height(3.dp)) { + // The light part must stand out from a light strip too. + val white = if (MaterialTheme.colorScheme.surface.luminance() > 0.5f) Color(0xFFD5D8DC) else Color(0xFFF5F5F0) + val black = Color(0xFF26282B) + val left = if (flipped) 1f - share else share + if (left > 0f) Box(Modifier.weight(left.coerceAtLeast(0.001f)).fillMaxHeight().background(if (flipped) black else white)) + if (left < 1f) Box(Modifier.weight((1f - left).coerceAtLeast(0.001f)).fillMaxHeight().background(if (flipped) white else black)) + } + if (ending != null) { + Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Text(ending, style = MaterialTheme.typography.labelLarge) + } + return@Column + } + if (waiting) { + Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.review_engine_paused), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + return@Column + } + if (status is EngineStatus.Failed) { + Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(if (status.notStarting) R.string.engine_not_starting else R.string.engine_not_answering), + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.weight(1f), + ) + if (!status.notStarting) TextButton(onClick = onRestart) { Text(stringResource(R.string.restart)) } + } + return@Column + } + LineRow(best, analysis, status, true, lines > 1, expanded, onExpand, onLine, onDeeper, notation) + if (expanded) { + analysis?.lines?.drop(1)?.take(lines - 1)?.forEach { l -> + LineRow(l, analysis, status, false, false, false, {}, onLine, {}, notation) + } + } + } +} + +@Composable +private fun LineRow( + line: EngineLine?, + analysis: Analysis?, + status: EngineStatus, + first: Boolean, + canExpand: Boolean, + expanded: Boolean, + onExpand: () -> Unit, + onLine: (EngineLine) -> Unit, + onDeeper: () -> Unit, + notation: (String) -> AnnotatedString, +) { + Row( + Modifier + .fillMaxWidth() + .height(if (first) 48.dp else 40.dp) + .then(if (line != null) Modifier.clickable { onLine(line) } else Modifier) + .padding(start = 16.dp, end = if (first) 0.dp else 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + EvalPlaque(line) + Spacer(Modifier.width(8.dp)) + if (first) { + val depth = analysis?.depth?.toInt() ?: 0 + val label = when { + line == null || status == EngineStatus.Starting -> stringResource(R.string.thinking) + status == EngineStatus.Paused -> stringResource(R.string.depth, depth) + " · " + stringResource(R.string.paused) + else -> stringResource(R.string.depth, depth) + } + Text( + label, + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + ) + Spacer(Modifier.width(8.dp)) + } + Text( + line?.let { notation(it.text) } ?: AnnotatedString(""), + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (first && status == EngineStatus.Paused) { + TextButton(onClick = onDeeper) { Text(stringResource(R.string.deeper)) } + } + if (first && canExpand) { + IconButton(onClick = onExpand) { + Icon( + if (expanded) Icons.Rounded.ExpandLess else Icons.Rounded.ExpandMore, + stringResource(if (expanded) R.string.fewer_lines else R.string.more_lines), + ) + } + } + } +} + +/// The evaluation: light when White is better, dark when Black is (§8.2). +@Composable +private fun EvalPlaque(line: EngineLine?) { + // Dark only when Black is better by what is shown ("0.0" stays light). + val blackBetter = line != null && ((line.mate ?: 0) < 0 || (line.mate == null && Math.round((line.cp ?: 0) / 10.0) < 0)) + val bg = if (blackBetter) Color(0xFF26282B) else Color(0xFFF5F5F0) + val fg = if (blackBetter) Color(0xFFE8E8E8) else Color(0xFF1C1D1F) + Box( + Modifier + .width(56.dp) + .height(28.dp) + .clip(RoundedCornerShape(8.dp)) + .background(bg) + .border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(8.dp)), + contentAlignment = Alignment.Center, + ) { + Text( + line?.let(::shownEval) ?: "", + color = fg, + fontSize = 15.sp, + fontWeight = FontWeight.Bold, + style = Tabular, + ) + } +} + +/// The evaluation as shown (§8.2): pawns with one decimal, rounded ("+0.45" → "+0.5"), +/// no sign for an equal position; mates as the engine line has them ("#3", "#−2"). +fun shownEval(line: EngineLine): String { + if (line.mate != null) return line.eval + val tenths = Math.round((line.cp ?: 0) / 10.0).toInt() + if (tenths == 0) return "0.0" + val sign = if (tenths > 0) "+" else "\u2212" + val a = kotlin.math.abs(tenths) + return "$sign${a / 10}.${a % 10}" +} + +/// The bar above the notation while an engine line is shown on the board (§8.3); `best` +/// for the better line of a game report's error (§21.1). +@Composable +fun PreviewBar(step: Int, total: Int, onClose: () -> Unit, best: Boolean = false) { + Row( + Modifier + .fillMaxWidth() + .height(48.dp) + .background(MaterialTheme.colorScheme.primaryContainer) + .padding(start = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(if (best) R.string.review_best_preview else R.string.engine_line_preview, step, total), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.weight(1f), + ) + IconButton(onClick = onClose) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } + } +} + +private fun mb(bytes: Long) = (bytes / 1_000_000).toInt() + +/// The sheet that offers the download of the engine (light build, §8.4). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun EngineSheet(state: NetState, metered: Boolean, onDownload: () -> Unit, onCancel: () -> Unit, onDismiss: () -> Unit) { + val size = mb(BuildConfig.NET_SIZE) + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().padding(start = 24.dp, end = 24.dp, bottom = 24.dp)) { + Text(stringResource(R.string.engine_sheet_title), style = MaterialTheme.typography.titleLarge) + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.engine_sheet_text), style = MaterialTheme.typography.bodyLarge) + Spacer(Modifier.height(16.dp)) + when (state) { + is NetState.Loading -> { + LinearProgressIndicator( + progress = { state.done.toFloat() / state.total.coerceAtLeast(1) }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + Text( + stringResource(R.string.downloaded_of, mb(state.done), mb(state.total)), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel_download)) } + } + } + is NetState.Failed -> { + val text = when (state.problem) { + NetProblem.NoInternet -> stringResource(R.string.no_internet) + NetProblem.Interrupted -> stringResource(R.string.interrupted) + NetProblem.NoSpace -> stringResource(R.string.no_space, size) + NetProblem.Corrupt -> stringResource(R.string.corrupt) + } + Text(text, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + if (state.problem != NetProblem.NoSpace) TextButton(onClick = onDismiss) { Text(stringResource(R.string.not_now)) } + when (state.problem) { + NetProblem.NoSpace -> Button(onClick = onDismiss) { Text(stringResource(R.string.ok)) } + NetProblem.NoInternet, NetProblem.Interrupted -> Button(onClick = onDownload) { Text(stringResource(R.string.retry)) } + NetProblem.Corrupt -> Button(onClick = onDownload) { Text(stringResource(R.string.download_again)) } + } + } + } + else -> { + Text(stringResource(R.string.engine_size, size), style = MaterialTheme.typography.bodyMedium.merge(Tabular)) + if (metered) { + Spacer(Modifier.height(8.dp)) + Text( + stringResource(R.string.engine_metered), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.not_now)) } + Button(onClick = onDownload) { Text(stringResource(R.string.download)) } + } + } + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameBarState.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameBarState.kt new file mode 100644 index 0000000..d57e185 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameBarState.kt @@ -0,0 +1,19 @@ +package io.github.vrubelroman.chesspenguin.ui + +internal enum class ReviewAction { Start, Report, Wait } + +/// The same availability the menu entry had, now used by the visible bottom-bar button. +internal fun reviewEnabled( + hasMoves: Boolean, + gameOn: Boolean, + sessionGame: Boolean, + loaded: Boolean, + hasData: Boolean, + running: Boolean, +): Boolean = hasMoves && !gameOn && (sessionGame || loaded) && (hasData || !running) + +internal fun reviewAction(hasData: Boolean, running: Boolean): ReviewAction = when { + hasData -> ReviewAction.Report + running -> ReviewAction.Wait + else -> ReviewAction.Start +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameDataForm.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameDataForm.kt new file mode 100644 index 0000000..011fa81 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameDataForm.kt @@ -0,0 +1,171 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import io.github.vrubelroman.chesspenguin.R +import uniffi.mobile_api.GameData +import uniffi.mobile_api.Tag + +/// "2026.10.26", "2026.10", "2026", "26.10.2026" (as people write it) → the PGN date +/// ("2026.10.26", "2026.10.??", "2026.??.??"); "" stays ""; null when it is not a date. +fun pgnDateOf(text: String): String? { + val t = text.trim() + if (t.isEmpty()) return "" + Regex("""(\d{4})(?:[.\-/](\d{1,2}|\?\?))?(?:[.\-/](\d{1,2}|\?\?))?""").matchEntire(t)?.let { m -> + val (y, mo, d) = m.destructured + return listOf(y, part(mo, 12) ?: return null, part(d, 31) ?: return null).joinToString(".").takeIf(::realDay) + } + Regex("""(\d{1,2})[.\-/](\d{1,2})[.\-/](\d{4})""").matchEntire(t)?.let { m -> + val (d, mo, y) = m.destructured + return listOf(y, part(mo, 12) ?: return null, part(d, 31) ?: return null).joinToString(".").takeIf(::realDay) + } + return null +} + +private fun part(p: String, max: Int): String? = when { + p.isEmpty() || p == "??" -> "??" + p.toInt() in 1..max -> p.padStart(2, '0') + else -> null +} + +/// A day that the month has (31.02 is not one). +private fun realDay(date: String): Boolean { + val (y, m, d) = date.split('.').map { it.toIntOrNull() } + listOf(null, null, null) + if (y == null || m == null || d == null) return true + return runCatching { java.time.LocalDate.of(y, m, d) }.isSuccess +} + +private val RESULTS = listOf("1-0", "1/2-1/2", "0-1", "*") + +/// The game's data (android-play.md §30.5): players and ratings, event, place, date, +/// round, result. Nothing is required; `done` gets the tags (empty: removed) and result. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GameDataForm(game: GameData, doneLabel: String, onDone: (List, String) -> Unit, onDismiss: () -> Unit) { + fun tag(name: String) = game.tags.firstOrNull { it.name == name }?.value?.takeIf { it != "?" && !it.startsWith("????") }.orEmpty() + var white by rememberSaveable { mutableStateOf(tag("White")) } + var whiteElo by rememberSaveable { mutableStateOf(tag("WhiteElo")) } + var black by rememberSaveable { mutableStateOf(tag("Black")) } + var blackElo by rememberSaveable { mutableStateOf(tag("BlackElo")) } + var event by rememberSaveable { mutableStateOf(tag("Event")) } + var site by rememberSaveable { mutableStateOf(tag("Site")) } + var date by rememberSaveable { mutableStateOf(tag("Date")) } + var round by rememberSaveable { mutableStateOf(tag("Round")) } + var result by rememberSaveable { mutableStateOf(game.result.takeIf { it in RESULTS } ?: "*") } + val start = listOf(white, whiteElo, black, blackElo, event, site, date, round, result) + val initial = rememberSaveable { start.joinToString("\u0000") } + val changed = start.joinToString("\u0000") != initial + var asking by rememberSaveable { mutableStateOf(false) } + val pgnDate = pgnDateOf(date) + fun close() = if (changed) asking = true else onDismiss() + Dialog(onDismissRequest = ::close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { IconButton(onClick = ::close) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } }, + title = { Text(stringResource(R.string.game_data)) }, + actions = { + TextButton(enabled = pgnDate != null, onClick = { + onDone( + listOf( + Tag("White", white.trim()), Tag("WhiteElo", whiteElo.trim()), + Tag("Black", black.trim()), Tag("BlackElo", blackElo.trim()), + Tag("Event", event.trim()), Tag("Site", site.trim()), + Tag("Date", pgnDate ?: ""), Tag("Round", round.trim()), + ), + result, + ) + }) { Text(doneLabel) } + }, + ) + }, + ) { padding -> + Column( + Modifier.fillMaxSize().padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + val digits = KeyboardOptions(keyboardType = KeyboardType.Number) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(white, { white = it }, Modifier.weight(1f), label = { Text(stringResource(R.string.tag_white)) }, singleLine = true) + OutlinedTextField(whiteElo, { v -> whiteElo = v.filter(Char::isDigit).take(4) }, Modifier.width(88.dp), label = { Text(stringResource(R.string.elo)) }, singleLine = true, keyboardOptions = digits) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(black, { black = it }, Modifier.weight(1f), label = { Text(stringResource(R.string.tag_black)) }, singleLine = true) + OutlinedTextField(blackElo, { v -> blackElo = v.filter(Char::isDigit).take(4) }, Modifier.width(88.dp), label = { Text(stringResource(R.string.elo)) }, singleLine = true, keyboardOptions = digits) + } + OutlinedTextField(event, { event = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.tag_event)) }, singleLine = true) + OutlinedTextField(site, { site = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.tag_site)) }, singleLine = true) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + date, { date = it }, Modifier.weight(1f), + label = { Text(stringResource(R.string.tag_date)) }, + placeholder = { Text(stringResource(R.string.date_hint)) }, + singleLine = true, + isError = pgnDate == null, + supportingText = if (pgnDate == null) { { Text(stringResource(R.string.date_wrong)) } } else null, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), + ) + OutlinedTextField(round, { round = it }, Modifier.width(88.dp), label = { Text(stringResource(R.string.tag_round)) }, singleLine = true) + } + Text(stringResource(R.string.tag_result), style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 8.dp)) + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { + RESULTS.forEachIndexed { i, r -> + SegmentedButton( + selected = result == r, + onClick = { result = r }, + shape = SegmentedButtonDefaults.itemShape(i, RESULTS.size), + ) { Text(if (r == "1/2-1/2") "½-½" else r) } + } + } + } + } + if (asking) { + AlertDialog( + onDismissRequest = { asking = false }, + title = { Text(stringResource(R.string.discard_changes)) }, + confirmButton = { + TextButton(onClick = { + asking = false + onDismiss() + }) { Text(stringResource(R.string.discard)) } + }, + dismissButton = { TextButton(onClick = { asking = false }) { Text(stringResource(R.string.keep_editing)) } }, + ) + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt new file mode 100644 index 0000000..4208c9f --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt @@ -0,0 +1,1991 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.content.Context +import android.content.res.Configuration +import android.content.Intent +import android.view.HapticFeedbackConstants +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.windowInsetsPadding +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.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.outlined.Memory +import androidx.compose.material.icons.rounded.ChevronLeft +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Save +import androidx.compose.material.icons.rounded.School +import androidx.compose.material.icons.rounded.SmartToy +import androidx.compose.material.icons.rounded.VerticalAlignTop +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.Download +import androidx.compose.material.icons.rounded.Memory +import androidx.compose.material.icons.rounded.MoreVert +import androidx.compose.material.icons.rounded.PlayArrow +import androidx.compose.material.icons.rounded.QueryStats +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +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.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.disabled +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.onLongClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.viewmodel.compose.viewModel +import io.github.vrubelroman.chesspenguin.data.Source +import io.github.vrubelroman.chesspenguin.data.Written +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.EngineSession +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.data.Opponent +import io.github.vrubelroman.chesspenguin.data.ReviewSession +import io.github.vrubelroman.chesspenguin.data.enginePosition +import io.github.vrubelroman.chesspenguin.theme.LocalChessColors +import io.github.vrubelroman.chesspenguin.theme.Tabular +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import uniffi.mobile_api.EngineLine +import uniffi.mobile_api.Edited +import uniffi.mobile_api.GameData +import uniffi.mobile_api.GameSession +import io.github.vrubelroman.chesspenguin.theme.nagColor +import uniffi.mobile_api.MoveJudgement +import uniffi.mobile_api.MoveNode + +/// An engine line shown on the board (§8.3): the game itself does not change. `best`: +/// the better line of an error of the game report (§21.1). +private data class Preview(val line: EngineLine, val step: Int, val best: Boolean = false) + +/// One game: the board on top, the notation under it, the move buttons at the bottom +/// under the thumb; ‹ › page the games of the list (android-ui.md §7). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GameScreen( + db: String, + startPlace: Int, + query: String, + onBack: () -> Unit, + onSettings: () -> Unit, + onPlayGame: () -> Unit = {}, + onOpenDatabase: (String) -> Unit = {}, + onPrepare: (PrepStart) -> Unit = {}, +) { + val app = app() + val context = LocalContext.current + // Configuration-aware (the language can change while the screen is up). + val resources = androidx.compose.ui.platform.LocalResources.current + val prefs by app.settings.prefs.collectAsState() + val libraryEntries by app.library.entries.collectAsState() + val dbEntry = libraryEntries.firstOrNull { it.id == db } + var games by remember { mutableStateOf(app.shown[db]) } + var place by rememberSaveable { mutableIntStateOf(startPlace) } + // The list marks the game it comes back to (the one paged to with ‹ ›, too). + LaunchedEffect(place) { if (db != NEW_GAME && db != PLAY_GAME) app.lastOpened[db] = query to place } + // The game as changed on the board (android-play.md §29), kept while the phone turns: + // a game of someone else's file is changed for analysis and never written there. + val held: GameEdit = viewModel() + var game by held.data + var edit by held.session + val newGame = db == NEW_GAME + // The game against Maia in hand (android-play.md §31). + val playGame = db == PLAY_GAME + val run = held.play.value + // Learning the opening of this game: its own screen over the game (§32). + held.trainer.value?.let { t -> + TrainScreen(t, held.trainPly, held.trainFlipped, onPly = { held.trainPly = it }, onExit = { + held.trainer.value = null + t.close() + }) + return + } + var failed by remember { mutableStateOf(false) } + var current by rememberSaveable(place) { mutableIntStateOf(0) } + // Back from the trainer: the move it was opened from, the board as it was. + LaunchedEffect(Unit) { + held.trainReturn?.let { current = it } + held.trainReturn = null + } + var flipped by rememberSaveable { mutableStateOf(false) } + var preview by remember { mutableStateOf(null) } + // The game report (§21): its own engine job; the live engine rests while it runs. + val review = remember { ReviewSession(java.io.File(context.cacheDir, "analysis").path, app.scope) } + LaunchedEffect(db, place, held.reloads.intValue) { + preview = null + if (playGame) { + if (held.key != PLAY_GAME) { + val meta = app.maiaGames.current.value + val pgn = app.maiaGames.pgn() + if (meta == null || pgn == null) { + failed = true + return@LaunchedEffect + } + held.key = PLAY_GAME + // A game written into its player's database is that database's game. + val written = app.maiaGames.written() + held.savedTo = written + held.recordError.value = null + held.recorded.value = written?.let { (id, n) -> Written(id, app.library.entry(id)?.name ?: "", n, false) } + val s = GameSession.fromPgn(pgn) + edit = s + val d = s.data() + game = d + held.play.value?.close() + held.play.value = PlayRun(meta).also { r -> + // A game that ended before the app was closed: its end as it was. + if (meta.over) r.over.value = PlayOver(d.result, if (d.result == "1/2-1/2") R.string.play_draw else if ((d.result == "1-0") == meta.userWhite) R.string.play_won else R.string.play_lost, null) + } + flipped = !meta.userWhite + current = lineEnd(d) + } + return@LaunchedEffect + } + if (newGame) { + if (held.key != NEW_GAME) { + held.key = NEW_GAME + edit = GameSession.newGame(java.text.SimpleDateFormat("yyyy.MM.dd", java.util.Locale.ROOT).format(java.util.Date())) + game = edit?.data() + } + return@LaunchedEffect + } + val database = app.library.database(db).getOrNull() + if (database == null) { + failed = true + return@LaunchedEffect + } + // After the process was restarted the list is gone: the same search finds it again. + val list = games ?: withContext(Dispatchers.Default) { app.library.listed(db, database, query) }.also { + games = it + app.shown[db] = it + } + val index = list.getOrNull(place) ?: return@LaunchedEffect + val key = "$db/$index" + // The phone turned: the game as it was changed is still there. + if (held.key != key || edit == null) { + game = null + edit = null + held.savedTo = null + val loaded = withContext(Dispatchers.Default) { runCatching { database.game(index) to database.session(index) } } + failed = loaded.isFailure + game = loaded.getOrNull()?.first + edit = loaded.getOrNull()?.second + held.notes = game?.notes ?: emptyList() + held.key = key + } + if (game != null) review.open(db, database, index) + } + val pieces = remember { Pieces(context) } + val snackbar = remember { SnackbarHostState() } + UpdateMessages(snackbar) + val scope = rememberCoroutineScope() + val view = LocalView.current + val readyText = stringResource(R.string.engine_ready) + val cancelledText = stringResource(R.string.download_cancelled) + val total = games?.size ?: 0 + val lang = uiLanguage() + val san = remember(prefs.notation, lang) { { s: String -> displaySan(s, prefs.notation, lang) } } + val line = remember(prefs.notation, lang) { { s: String -> displayLine(s, prefs.notation, lang) } } + + // The engine: one process while this screen is visible and the button is on. + val files = app.engineFiles + val netState by files.state.collectAsState() + val session = remember { EngineSession(files, app.scope) } + val status by session.status.collectAsState() + // Read only where it is shown (the strip, the arrows): the engine speaks several + // times a second, the rest of the screen is not drawn again for it. + val engineView = session.analysis.collectAsState() + var visible by remember { mutableStateOf(true) } + var sheet by rememberSaveable { mutableStateOf(false) } + var wantEngine by rememberSaveable { mutableStateOf(false) } + // The engine button: off in every game screen opened, on only when pressed, and + // only until the app goes to the background (§8.3). Kept while Settings is open over + // the game and when the phone is turned. + var engineVisit by rememberSaveable { mutableStateOf(null) } + val engineWanted = engineVisit == app.visit + var expanded by rememberSaveable { mutableStateOf(false) } + val reviewState by review.state.collectAsState() + // "Hide" in the report: until the next game. + var reviewHidden by remember(place) { mutableStateOf(false) } + var reviewStart by remember { mutableStateOf(false) } + var reviewReport by remember { mutableStateOf(false) } + // A start that waits for the engine (downloaded or unpacked): full or not. + var wantReview by remember { mutableStateOf(null) } + // The download sheet was opened to analyse the game (not for the engine button). + var sheetForReview by remember { mutableStateOf(null) } + // Stopped because the app went to the background: goes on when it comes back. + // Kept when the phone is turned (the screen is made again): the analysis goes on. + var reviewResume by rememberSaveable(place) { mutableStateOf(false) } + val reviewCycle = remember(place) { HashMap, Int>() } + var menu by remember { mutableStateOf(false) } + var info by remember { mutableStateOf(false) } + var prepSheet by remember(place) { mutableStateOf(false) } + @Suppress("DEPRECATION") + val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current + val pgnCopied = stringResource(R.string.pgn_copied) + val fenCopied = stringResource(R.string.fen_copied) + suspend fun pgnText(): String? { + // Moves added on the board go along (the file is as it was). + edit?.takeIf { it.isModified() }?.let { e -> return withContext(Dispatchers.Default) { e.pgn() } } + val index = games?.getOrNull(place) ?: return null + val database = app.library.database(db).getOrNull() ?: return null + return withContext(Dispatchers.Default) { database.pgn(index) } + } + val lifecycle = LocalLifecycleOwner.current.lifecycle + DisposableEffect(lifecycle) { + val observer = LifecycleEventObserver { _, e -> + when (e) { + Lifecycle.Event.ON_START -> visible = true + // The screen went dark or the app went away: the engine quits (§8.3). + Lifecycle.Event.ON_STOP -> { + visible = false + session.shutdown() + } + else -> {} + } + } + lifecycle.addObserver(observer) + onDispose { + lifecycle.removeObserver(observer) + session.shutdown() + } + } + + val g = game + val tag = { name: String -> g?.tags?.firstOrNull { it.name == name }?.value ?: "" } + // The player bars above and below the board (§7.11); the top bar names the event. + val whiteName = tag("White").trim().takeIf { it.isNotEmpty() && it != "?" } + val blackName = tag("Black").trim().takeIf { it.isNotEmpty() && it != "?" } + val prepPathAvailable = g?.let { data -> + prepStartFromGame(data, current, db, whiteName ?: blackName.orEmpty(), whiteName != null) != null + } == true + val whiteLabel = stringResource(R.string.tag_white) + val blackLabel = stringResource(R.string.tag_black) + val resultText = g?.let { resultLine(context, it.result) } ?: "" + val (items, where) = remember(g, resultText) { g?.let { layout(it, resultText) } ?: (emptyList() to emptyMap()) } + val nodes = g?.nodes + val node = nodes?.getOrNull(current) + val notation = rememberLazyListState() + val engineReady = netState == NetState.Ready + val engineOn = engineWanted && engineReady + val position = remember(g, current) { g?.let { enginePosition(it, current) } } + // Only what the engine said about the position on the board. + fun analysis() = engineView.value?.takeIf { it.position == position }?.analysis + // Mate and stalemate need no engine: the strip says what it is (§7.3). + val ending = when (node?.end) { + "checkmate" -> stringResource(R.string.checkmate) + (g?.let { " · " + shortResult(it.result) }?.takeIf { !it.endsWith("*") } ?: "") + "stalemate" -> stringResource(R.string.stalemate) + " · ½-½" + else -> null + } + + val reviewRunning = reviewState?.running == true + LaunchedEffect(position, engineOn, visible, prefs.engineLines, prefs.engineSeconds, reviewRunning) { + if (position == null || !visible) return@LaunchedEffect + when { + // One engine at a time on a phone: the analysis of the game comes first (§21.6). + !engineOn || reviewRunning -> session.shutdown() + ending != null -> session.pause() + else -> session.show(position, prefs) + } + } + // A download started from the button turns the engine on when it is done. + LaunchedEffect(netState) { + if (netState == NetState.Ready && wantEngine) { + wantEngine = false + sheet = false + engineVisit = app.visit + if (!files.builtIn) snackbar.showSnackbar(readyText) + } + } + + fun startReview(full: Boolean) { + if (files.state.value != NetState.Ready) { + if (files.builtIn) { + wantReview = full + files.prepare() + } else { + sheetForReview = full + sheet = true + } + return + } + wantReview = null + reviewHidden = false + review.start(files.executable, files.net.path, full) { s -> + if (s.npsPerProcess > 0UL) app.settings.update { it.copy(reviewNps = s.npsPerProcess.toLong()) } + } + } + // The engine became ready for an analysis that was asked for. + LaunchedEffect(netState) { + if (netState == NetState.Ready) wantReview?.let { full -> + sheet = false + startReview(full) + } + } + // An analysis stopped by the background or a turn of the phone goes on once this + // game's analysis is loaded again and the screen is visible. + val reviewLoaded = reviewState != null + LaunchedEffect(reviewLoaded, visible) { + if (reviewLoaded && visible && reviewResume) { + reviewResume = false + startReview(false) + } + } + DisposableEffect(lifecycle) { + val observer = LifecycleEventObserver { _, e -> + when (e) { + // Battery first (§21.6): the analysis stops with the screen and goes on after. + Lifecycle.Event.ON_STOP -> if (review.state.value?.running == true) { + reviewResume = true + review.cancel() + } + else -> {} + } + } + lifecycle.addObserver(observer) + onDispose { + lifecycle.removeObserver(observer) + review.close() + } + } + + val rs = reviewState + val preparingReview = wantReview != null && files.builtIn && netState is NetState.Loading + // A game without moves has nothing to analyse. + val hasMoves = g?.nodes?.firstOrNull()?.children?.isNotEmpty() == true + val reviewShown = rs != null && hasMoves && !reviewHidden && (rs.hasData || rs.running || preparingReview) + val reviewPoints = remember(rs) { rs?.points?.withIndex()?.associate { it.value.node.toInt() to it.index } ?: 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 + + // The one visible entry to the report: start it, or bring its panel back and open it. + fun openReview() { + reviewHidden = false + val e = edit + if ((newGame || playGame) && e != null && rs == null) { + scope.launch { + review.openSession("${held.key}/${System.nanoTime()}", e) + reviewStart = true + } + return + } + when (reviewAction(rs?.hasData == true, rs?.running == true)) { + ReviewAction.Report -> reviewReport = true + ReviewAction.Wait -> {} + ReviewAction.Start -> reviewStart = true + } + } + + fun buzz(edge: Boolean) { + if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK) + } + // A change of the game: shown at once, the cursor where the change says. + fun apply(e: Edited) { + preview = null + game = e.data.copy(notes = held.notes) + current = e.cursor.toInt() + } + // The move sheet of a long press on a move (§29.6): which move. + var moveSheet by remember { mutableStateOf(null) } + // «Play on from here» asked for at this move. + var playFrom by remember { mutableStateOf(null) } + var askFrom by remember { mutableStateOf(null) } + val deletedText = stringResource(R.string.moves_deleted) + val mainText = stringResource(R.string.made_main) + val undoText = stringResource(R.string.undo_action) + fun undo() { + edit?.undo()?.let { apply(it) } + } + + // ----- a game against the computer (§31, android-rodent.md) ----- + val runOver = run?.over?.value + val runOffer = run?.offer?.value == true + val runThinking = run?.thinking?.value == true + val runFailure = run?.failure?.value + val gameOn = run != null && runOver == null + fun persist() { + if (run != null) edit?.let { app.maiaGames.save(it.pgn()) } + } + val recordFailedText = stringResource(R.string.player_write_failed) + fun finishGame(over: PlayOver) { + val r = run ?: return + val e = edit ?: return + r.generation++ + r.rodent?.forget() + r.thinking.value = false + r.offer.value = false + e.setData(listOf(uniffi.mobile_api.Tag("Termination", "Normal")), over.result) + game = e.data().copy(notes = held.notes) + r.over.value = over + val pgn = e.pgn() + app.maiaGames.finish(pgn) + // Into the player's database by itself (player-games.md); a new one is said once. + val serial = app.maiaGames.serial + if (prefs.recordGames && app.maiaGames.written() == null) scope.launch { + runCatching { app.playerGames.write(r.meta.name, pgn) } + .onSuccess { w -> + app.maiaGames.setWritten(w.id, w.index, serial) + // The screen still shows that game (no rematch since). + if (app.maiaGames.serial == serial) { + if (edit === e && e.pgn() == pgn) e.markSaved() + held.savedTo = w.id to w.index + held.recorded.value = w + } + } + .onFailure { err -> + if (app.maiaGames.serial != serial) return@onFailure + val name = app.playerGames.database(r.meta.name)?.name ?: app.playerGames.dbName(r.meta.name) + held.recordError.value = String.format(recordFailedText, name, err.message ?: err.javaClass.simpleName) + } + } + app.sounds.play( + when (over.heading) { + R.string.play_won -> io.github.vrubelroman.chesspenguin.data.Sound.Success + R.string.play_draw -> io.github.vrubelroman.chesspenguin.data.Sound.Move + else -> io.github.vrubelroman.chesspenguin.data.Sound.Defeat + }, + ) + } + // After a move of either side: kept, and the end of the game if it came. + fun afterMove(e: Edited) { + val r = run ?: return + persist() + edit?.ending(e.cursor)?.let { finishGame(overBy(it, r.meta.userWhite)) } + } + // The opponent's move when it is its turn: computed in the background, shown after its + // pause. Maia computes at once and waits; Rodent thinks for the pause (android-rodent.md §6.1). + LaunchedEffect(run, g, runOver, runOffer, runFailure) { + val r = run ?: return@LaunchedEffect + val gg = g ?: return@LaunchedEffect + val e = edit ?: return@LaunchedEffect + if (runOver != null || runOffer || runFailure != null) return@LaunchedEffect + val end = lineEnd(gg) + if (whiteToMove(gg.nodes[end].fen) == r.meta.userWhite) return@LaunchedEffect + val gen = ++r.generation + r.thinking.value = true + try { + val started = System.currentTimeMillis() + val only = e.legalMoves(end.toUInt()).size == 1 + val pause = uniffi.mobile_api.movePauseMs(depth(gg, end).toUInt(), only) + val rodentFiles = app.rodentFiles + val think: suspend () -> String? = if (r.meta.rival == Opponent.Rodent) { + // Rodent is in the APK: its personalities copied out, its books if the pack is + // whole (a game goes on without them, §1.7). + val rodent = r.rodent ?: ( + if (rodentFiles.prepare()) { + uniffi.mobile_api.RodentPlayer.start(rodentFiles.executable, rodentFiles.home.path, r.meta.style, r.meta.strength.toUInt(), rodentFiles.books.installed()) + } else { + r.failure.value = PlayFailure("no space for the personalities") + return@LaunchedEffect + } + ).also { r.rodent = it } + suspend { + // None: passed over by a newer request (a take-back), or Rodent failed. + withContext(Dispatchers.IO) { rodent.choose(e, end.toUInt(), pause) }.also { m -> + if (m == null) { + rodent.failure()?.let { f -> + r.failure.value = when (f) { + is uniffi.mobile_api.RodentFailure.DidNotStart -> PlayFailure(f.detail) + uniffi.mobile_api.RodentFailure.Stopped -> PlayFailure("", stopped = true) + } + } + } + } + } + } else { + val player = r.player ?: withContext(Dispatchers.IO) { runCatching { uniffi.mobile_api.MaiaPlayer.load(app.maiaFiles.download.file.path) } } + .getOrElse { ex -> + r.failure.value = PlayFailure(ex.message ?: "") + return@LaunchedEffect + }.also { r.player = it } + suspend { + withContext(Dispatchers.Default) { + player.choose(e, end.toUInt(), r.meta.strength.toUInt(), null, kotlin.random.Random.nextFloat()) + } + } + } + // Its resignation is judged by Stockfish, when it is there. + if (r.judge == null && files.state.value == NetState.Ready) { + r.judge = runCatching { uniffi.mobile_api.ResignJudge.start(files.executable, files.net.path) }.getOrNull() + } + r.judge?.ask(e, end.toUInt()) + val uci = think() ?: return@LaunchedEffect + val wait = pause.toLong() - (System.currentTimeMillis() - started) + if (wait > 0) delay(wait) + if (gen != r.generation) return@LaunchedEffect + // The judge's answer, given up to two seconds more (a slow phone, an engine + // just started): an offer comes when it is due, not turns later. + r.judge?.let { j -> + var verdict = j.hopeless() + var waited = 0 + while (verdict == null && waited < 2000) { + delay(100) + waited += 100 + verdict = j.hopeless() + } + if (gen != r.generation) return@LaunchedEffect + verdict?.let { if (it) r.hopeless++ else r.hopeless = 0u } + } + if (!r.playOn && r.hopeless >= uniffi.mobile_api.hopelessTurns()) { + r.offer.value = true + app.sounds.play(io.github.vrubelroman.chesspenguin.data.Sound.Defeat) + return@LaunchedEffect + } + runCatching { e.play(end.toUInt(), uci) }.getOrNull()?.let { ed -> + apply(ed) + app.sounds.move(ed.data.nodes[ed.cursor.toInt()].san) + afterMove(ed) + } + } finally { + if (gen == r.generation) r.thinking.value = false + } + } + var resigning by remember { mutableStateOf(false) } + val drawDeclined = stringResource(run?.meta?.said(R.string.play_draw_declined, R.string.rodent_draw_declined) ?: R.string.play_draw_declined) + val drawLater = stringResource(run?.meta?.said(R.string.play_draw_later, R.string.rodent_draw_later) ?: R.string.play_draw_later) + val drawNoEngine = stringResource(run?.meta?.said(R.string.play_draw_no_engine, R.string.rodent_draw_no_engine) ?: R.string.play_draw_no_engine) + // A draw offered (§31.3): the opponent answers by its judge's scores of its last turns. + fun offerDraw() { + val r = run ?: return + val j = r.judge + val say = { text: String -> scope.launch { snackbar.currentSnackbarData?.dismiss(); snackbar.showSnackbar(text) } } + when { + j == null -> say(drawNoEngine) + !j.mayOfferDraw() -> say(drawLater) + j.offerDraw() -> finishGame(PlayOver("1/2-1/2", R.string.play_draw, R.string.end_agreement)) + else -> say(drawDeclined) + } + } + // The result card closed with ×: until the next game. + var resultClosed by remember(run) { mutableStateOf(false) } + // A change after the end (a variation, an undo): the card's result may not hold. + val atEnd = remember(runOver) { g?.let { lineEnd(it) } } + LaunchedEffect(g) { + if (runOver != null && atEnd != null && g != null && lineEnd(g) != atEnd) resultClosed = true + } + // Maia's file fetched again after she failed: she starts anew once it is there. + var maiaRetry by remember { mutableStateOf(false) } + val maiaState by app.maiaFiles.download.state.collectAsState() + LaunchedEffect(maiaState, maiaRetry) { + if (maiaRetry && maiaState == NetState.Ready) { + maiaRetry = false + run?.player?.close() + run?.player = null + run?.failure?.value = null + } + } + val eventText = stringResource(R.string.play_event) + val runStyle = run?.meta?.styleShown() + // A new game asked for when a rematch cannot start at once (Rodent's books removed + // meanwhile, android-rodent.md §1.6): the sheet, as for a new game. + var newGameSheet by remember { mutableStateOf(false) } + // The same opponent and strength again, colours swapped; from a position: the same one + // and colour. + fun rematch() { + val r = run ?: return + val e = edit ?: return + val gg = g ?: return + val m = r.meta + if (m.rival == Opponent.Rodent && m.floor == 0 && !app.rodentFiles.books.installed()) { + newGameSheet = true + return + } + val base = if (m.floor > 0) { + var n = 0 + repeat(m.floor) { n = gg.nodes[n].children.firstOrNull()?.toInt() ?: n } + runCatching { e.playFrom(n.toUInt()) }.getOrNull() ?: return + } else { + GameSession.newGame("") + } + val next = m.copy(userWhite = if (m.floor > 0) m.userWhite else !m.userWhite, over = false) + beginComputerGame(app, base, next, eventText, playNote(resources, next, runStyle)) + base.close() + // The report of the game before is not this one's. + review.close() + reviewHidden = true + held.key = null + held.reloads.intValue++ + } + fun takeBack() { + val r = run ?: return + val gg = g ?: return + val e = edit ?: return + val end = lineEnd(gg) + // While the opponent thinks or offers to resign, the last move is the user's; else + // its, and the user's before. + val userLast = r.thinking.value || r.offer.value + val from = if (userLast) end else gg.nodes[end].parent?.toInt() ?: return + if (depth(gg, from) <= r.meta.floor) return + r.generation++ + r.rodent?.forget() + r.thinking.value = false + r.offer.value = false + r.judge?.forget() + r.judge?.forgetScores() + r.hopeless = 0u + runCatching { e.deleteFrom(from.toUInt()) }.getOrNull()?.let { + apply(it) + persist() + } + } + + // Saving (android-play.md §30.4): an own database's game in its place; a new game or + // a copy of someone else's into an own database chosen once, then in its place there. + val ownGame = dbEntry?.source == Source.Own && !newGame + var saves by remember { mutableIntStateOf(0) } + @Suppress("UNUSED_EXPRESSION") saves + val modified = g != null && edit?.isModified() == true + // Kept when the phone turns (the activity is made again). + var saving by rememberSaveable { mutableStateOf(false) } + // The game's data form; `firstSave`: a new game's first save asks for it first. + var editingData by rememberSaveable { mutableStateOf(false) } + var firstSave by rememberSaveable { mutableStateOf(false) } + // Each opening of the form starts from the game (its fields are kept only while open). + var formOpening by rememberSaveable { mutableIntStateOf(0) } + var leaving by rememberSaveable { mutableStateOf(false) } + var afterSave by remember { mutableStateOf<(() -> Unit)?>(null) } + val ownEntries = libraryEntries.filter { it.source == Source.Own } + val savedText = stringResource(R.string.saved_to) + val saveFailedText = stringResource(R.string.save_failed) + val lastOwn = remember { context.getSharedPreferences("own", Context.MODE_PRIVATE) } + fun saveInto(id: String, index: UInt?) { + val e = edit ?: return + val then = afterSave + afterSave = null + scope.launch { + val pgn = withContext(Dispatchers.Default) { e.pgn() } + val done = runCatching { app.library.saveOwn(id, index, pgn) } + snackbar.currentSnackbarData?.dismiss() + done.onSuccess { n -> + e.markSaved() + saves++ + if (!ownGame) held.savedTo = id to n + lastOwn.edit().putString("last", id).apply() + val name = app.library.entry(id)?.name ?: "" // own databases: their own names + then?.invoke() ?: snackbar.showSnackbar(String.format(savedText, name, (n + 1u).toString())) + }.onFailure { snackbar.showSnackbar(saveFailedText) } + } + } + fun save(then: (() -> Unit)? = null) { + afterSave = then + val to = held.savedTo + when { + ownGame -> games?.getOrNull(place)?.let { saveInto(db, it) } + to != null -> saveInto(to.first, to.second) + // A new game's names and result first, as the desktop asks when adding. + newGame && !playGame -> { + firstSave = true + editingData = true + formOpening++ + } + else -> saving = true + } + } + // Leaving with changes asks only where they are the user's to keep (an own game, a + // new one); moves in someone else's game are for trying out (owner's decision). + // A game against Maia: put aside while it goes on (no question); after its end like + // a new game, and gone from hand once left. + // A copy saved into an own database is that database's game from then on. + val asksOnLeave = modified && (ownGame || newGame || held.savedTo != null || (playGame && runOver != null)) + val exit: () -> Unit = { + val r = held.play.value + val gg = game + // Over, or no move made yet: nothing to put aside. + val empty = r != null && gg != null && depth(gg, lineEnd(gg)) <= r.meta.floor + if (playGame && (r?.over?.value != null || empty)) app.maiaGames.clear() + onBack() + } + // What leaving's question leads to (back, or a rematch). + var leaveTo by remember { mutableStateOf<(() -> Unit)?>(null) } + fun leave() { + if (asksOnLeave) { + leaveTo = exit + leaving = true + } else { + exit() + } + } + fun go(to: Int) { + preview = null + if (nodes == null || to == current || to !in nodes.indices) return + current = to + buzz(to == 0 || nodes[to].children.isEmpty()) + } + fun stepPreview(by: Int) { + val p = preview ?: return + val next = p.step + by + if (next < 0) { + preview = null + } else if (next < p.line.steps.size) { + preview = p.copy(step = next) + buzz(next == p.line.steps.size - 1) + } + } + val canBack = preview != null || node?.parent != null + val canForward = preview?.let { it.step + 1 < it.line.steps.size } ?: (node?.children?.isNotEmpty() == true) + fun back() { + if (preview != null) stepPreview(-1) else node?.parent?.let { go(it.toInt()) } + } + fun forward() { + if (preview != null) stepPreview(1) else node?.children?.firstOrNull()?.let { go(it.toInt()) } + } + fun start() { + preview?.let { + preview = it.copy(step = 0) + return + } + go(0) + } + fun end() { + preview?.let { + preview = it.copy(step = it.line.steps.size - 1) + return + } + var n = node ?: return + while (n.children.isNotEmpty()) n = nodes[n.children[0].toInt()] + go(n.id.toInt()) + } + fun toggleEngine() { + // Read from the states now: the button may hold this function as it was when the + // screen was first drawn. + val ready = files.state.value == NetState.Ready + when { + ready && engineVisit == app.visit -> engineVisit = null + ready -> engineVisit = app.visit + files.builtIn -> { + wantEngine = true + files.prepare() + } + else -> { + sheetForReview = null + sheet = true + } + } + } + BackHandler(preview != null) { preview = null } + BackHandler(preview == null && asksOnLeave) { leaving = true } + + val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE + val controls: @Composable (Modifier) -> Unit = { modifier -> + if (gameOn && run != null && g != null) { + val end = lineEnd(g) + val endDepth = depth(g, end) + val floor = run.meta.floor + Column(modifier) { + // Looking back during the game: a strip leads back to it (§31.3). + if (current != end) { + val n = g.nodes[current] + val label = if (current == 0) stringResource(R.string.start_position) else (if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san).text + Row( + Modifier.fillMaxWidth().height(48.dp).background(MaterialTheme.colorScheme.primaryContainer).clickable { go(end) }.padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(stringResource(R.string.play_viewing, label), color = MaterialTheme.colorScheme.onPrimaryContainer, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + PlayControls( + // While Maia thinks the last move is the user's; else hers and the user's before. + canTakeBack = if (runThinking || runOffer) endDepth > floor else endDepth - 1 > floor, + started = endDepth - floor >= 2, + canBack = canBack, + canForward = canForward, + onTakeBack = ::takeBack, + onResign = { resigning = true }, + onDraw = ::offerDraw, + onAbort = { + app.playerGames.keepUnfinished(app.maiaGames, prefs.recordGames, app.scope) + app.maiaGames.clear() + onBack() + }, + onFlip = { flipped = !flipped }, + onBack = ::back, + onForward = ::forward, + ) + } + } else Column(modifier) { + val p = preview + if (p == null && node != null && nodes != null && node.children.size > 1) { + Forks(node.children.map { nodes[it.toInt()] }, san, onMove = ::go) + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + BoxWithConstraints(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) { + val compact = maxWidth < 320.dp + val narrow = maxWidth < 360.dp + val engineSlot = if (compact) 52f else if (narrow) 56f else 60f + val reviewSlot = if (compact) 52f else if (narrow) 88f else 96f + val moveSlot = if (compact || narrow) 64f else 78f + Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { + EngineButton( + on = engineOn, + needsDownload = !engineReady && !files.builtIn, + loading = netState as? NetState.Loading, + modifier = Modifier.weight(engineSlot), + onClick = ::toggleEngine, + ) + BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(48f)) { flipped = !flipped } + + BarButton( + icon = Icons.Rounded.PlayArrow, + label = stringResource(R.string.move_back), + description = stringResource(R.string.move_back), + enabled = canBack, + modifier = Modifier.weight(moveSlot), + iconSize = 32, + mirrored = true, + onLongClickLabel = stringResource(R.string.to_start), + onLongClick = ::start, + onClick = ::back, + ) + BarButton( + icon = Icons.Rounded.PlayArrow, + label = stringResource(R.string.move_forward), + description = stringResource(R.string.move_forward), + enabled = canForward, + modifier = Modifier.weight(moveSlot), + iconSize = 32, + onLongClickLabel = stringResource(R.string.to_end), + onLongClick = ::end, + onClick = ::forward, + ) + ReviewButton( + report = rs?.hasData == true, + enabled = reviewEnabled( + hasMoves = hasMoves, + gameOn = gameOn, + sessionGame = newGame || playGame, + loaded = rs != null, + hasData = rs?.hasData == true, + running = rs?.running == true, + ) && !preparingReview, + preparing = preparingReview, + progress = if (rs?.running == true) rs.done.toInt() to rs.total.toInt() else null, + showLabel = !compact, + modifier = Modifier.weight(reviewSlot), + onClick = ::openReview, + ) + } + } + } + } + } + val board: @Composable (Modifier) -> Unit = { boardModifier -> + val dark = LocalChessColors.current.dark + val p = preview + val step = p?.let { it.line.steps[it.step] } + val fen = step?.fen ?: node?.fen ?: START + val description = when { + step != null -> stringResource(R.string.board_description, step.label) + 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) + + (currentMark?.let { ", " + judgementName(it.judgement) } ?: "") + } + val arrows = buildList { + if (p != null) { + p.line.steps.getOrNull(p.step + 1)?.let { add(BoardArrow(it.fromSquare, it.toSquare, EngineArrow)) } + } else { + node?.marks?.forEach { m -> m.to?.let { add(BoardArrow(m.from, it, markColor(m.color), 0.9f)) } } + // After an error of the report: how the opponent punishes it (§21.1). + if (!engineOn) currentMark?.let { m -> + val f = m.replyFrom + val t = m.replyTo + if (f != null && t != null) add(BoardArrow(f, t, judgementColor(m.judgement, dark).copy(alpha = 0.8f), 0.9f)) + } + if (engineOn && prefs.bestArrow) { + analysis()?.lines?.take(2)?.forEachIndexed { i, l -> + val f = l.fromSquare + val t = l.toSquare + 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)) + } + + } + } + } + } + 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("#") } + // 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( + fen = fen, + flipped = flipped, + lastFrom = step?.fromSquare ?: node?.fromSquare, + lastTo = step?.toSquare ?: node?.toSquare, + pieces = pieces, + theme = prefs.board, + set = prefs.pieces, + description = description, + arrows = arrows, + marks = marks, + badge = badge, + check = check, + animated = prefs.animation, + // A touch during a preview of an engine line closes it; no move is made (§29.5). + modifier = if (p != null) boardModifier.pointerInput(Unit) { detectTapGestures { preview = null } } else boardModifier, + input = edit?.takeIf { + // In a game: only the user's side, in their turn, at the game's last move. + p == null && g != null && (!gameOn || (current == lineEnd(g) && !runThinking && !runOffer && whiteToMove(g.nodes[current].fen) == run!!.meta.userWhite)) + }?.let { e -> + val legal = remember(g, current) { e.legalMoves(current.toUInt()) } + BoardInput(legal, onMove = { uci -> + runCatching { e.play(current.toUInt(), uci) }.getOrNull()?.let { + apply(it) + app.sounds.move(it.data.nodes[it.cursor.toInt()].san) + if (gameOn) afterMove(it) + } + }) + }, + ) + } + val side: @Composable (Modifier) -> Unit = { sideModifier -> + Column(sideModifier.fillMaxWidth()) { + val p = preview + if (engineOn) { + Live { + EngineStrip( + ending = ending, + status = status, + analysis = analysis(), + flipped = flipped, + lines = prefs.engineLines, + expanded = expanded, + onExpand = { expanded = !expanded }, + onLine = { l -> if (l.steps.isNotEmpty()) preview = Preview(l, 0) }, + onDeeper = { session.deeper() }, + onRestart = { + session.shutdown() + position?.let { session.show(it, prefs) } + }, + notation = line, + waiting = reviewRunning, + ) + } + } else if (wantEngine && files.builtIn && netState is NetState.Loading) { + Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + Text(stringResource(R.string.preparing_engine), Modifier.padding(start = 12.dp), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + if (reviewShown) { + val cursor = g?.let { pointIndex(reviewPoints, it, current) } + ReviewPanel( + state = rs, + cursor = cursor, + // TalkBack: "6…Nf6, evaluation +1.2" (the start position has no move). + cursorLabel = cursor?.takeIf { it > 0 }?.let { rs.points[it].node.toInt() }?.let { id -> + nodes?.getOrNull(id)?.let { n -> (if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + n.san } + }, + // A phone on its side has little height: with the engine strip on, only the row (§21.3). + showGraph = !(landscape && engineOn), + mark = currentMark, + preparing = preparingReview, + notation = line, + onIndex = { i -> rs.points.getOrNull(i)?.let { go(it.node.toInt()) } }, + onBest = { m -> m.best?.takeIf { it.steps.isNotEmpty() }?.let { preview = Preview(it, 0, best = true) } }, + onReport = { reviewReport = true }, + onStop = { review.cancel() }, + onResume = { startReview(false) }, + ) + } + if (p != null) PreviewBar(p.step + 1, p.line.steps.size, onClose = { preview = null }, best = p.best) + if (run != null) { + when { + runOffer -> OfferCard( + run.meta, + onAccept = { finishGame(PlayOver(if (run.meta.userWhite) "1-0" else "0-1", R.string.play_won, run.meta.said(R.string.end_maia_resigned, R.string.end_rodent_resigned))) }, + onPlayOn = { + run.playOn = true + run.offer.value = false + }, + ) + runFailure != null -> FailureCard( + run.meta, + runFailure, + onRetry = { + if (run.meta.rival == Opponent.Rodent) { + // Rodent is in the APK: it is started again. + run.rodent?.close() + run.rodent = null + run.failure.value = null + } else { + // A missing or damaged file is fetched again, then she starts. + app.maiaFiles.download.delete() + app.maiaFiles.download.download() + maiaRetry = true + } + }, + onAbort = { + app.playerGames.keepUnfinished(app.maiaGames, prefs.recordGames, app.scope) + app.maiaGames.clear() + onBack() + }, + ) + runOver != null && !resultClosed -> ResultCard( + runOver, + saved = held.savedTo != null && !modified, + recorded = held.recorded.value, + recordError = held.recordError.value, + onOpenRecorded = { id -> onOpenDatabase(id) }, + onAnalyse = { + val e = edit + // The report takes the place: the card would be squeezed. + resultClosed = true + if (e != null) scope.launch { + review.openSession("${held.key}/${System.nanoTime()}", e) + reviewHidden = false + reviewStart = true + } + }, + onRematch = { + val go = { rematch() } + if (modified) { + leaveTo = go + leaving = true + } else { + go() + } + }, + onSave = { save() }, + onClose = { resultClosed = true }, + ) + } + } + Box(Modifier.weight(1f).fillMaxWidth()) { + when { + g != null -> Notation( + g, items, where, current, notation, san, onMove = ::go, modifier = Modifier.fillMaxSize(), + marks = if (reviewShown) reviewMarks else emptyMap(), + onLongMove = edit?.let { + { id -> + go(id) + buzz(true) + moveSheet = id + } + }, + ) + failed -> Text( + stringResource(R.string.game_failed), + color = MaterialTheme.colorScheme.error, + modifier = Modifier.align(Alignment.Center), + ) + else -> CircularProgressIndicator(Modifier.align(Alignment.Center)) + } + } + } + } + + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = ::leave) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + title = { + // The event and year (else the site); the game's place and round. A tap + // shows the game's details. + // No event and no site: the database's name. + // «Game against Rodent IV 1800» (android-rodent.md §6.1): a name, not a command. + val event = if (playGame && run != null) { + stringResource(R.string.play_adjourned_title, run.meta.label()) + } else if (newGame && held.savedTo == null) { + stringResource(R.string.new_game) + } else { + // No event: the site, else the database; a year alone is no title. + joinKnown(tag("Event")).let { e -> if (e.isEmpty()) e else joinKnown(e, year(tag("Date"))) } + .ifEmpty { joinKnown(tag("Site")) } + .ifEmpty { (held.savedTo?.first?.let { app.library.entry(it) } ?: dbEntry)?.let { displayName(it) } ?: "" } + } + val yearInLine = if (joinKnown(tag("Event")).isEmpty()) year(tag("Date")) else "" + val round = tag("Round").trim().takeIf { it.isNotEmpty() && it != "?" && it != "-" } + val placeLine = if (playGame && run != null) { + listOfNotNull( + runStyle, + stringResource(R.string.play_adjourned_sub, stringResource(if (run.meta.userWhite) R.string.play_as_white else R.string.play_as_black), stringResource(R.string.play_untimed)), + ).joinToString(" · ") + } else joinKnown( + if (total > 0 && held.savedTo == null) stringResource(R.string.game_of, place + 1, total) else "", + yearInLine, + round?.let { stringResource(R.string.tag_round).lowercase() + " " + it } ?: "", + ) + Column( + Modifier.fillMaxWidth().clickable( + enabled = g != null, + onClickLabel = stringResource(R.string.game_info), + role = Role.Button, + ) { info = true }, + ) { + Text( + event.ifEmpty { placeLine }, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (event.isNotEmpty() && placeLine.isNotEmpty()) { + Text( + placeLine, + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, + actions = { + // Changes not saved: "Save" in place of ‹ › (they would need a decision). + if (modified && !gameOn) { + val where = when { + ownGame -> dbEntry?.let { stringResource(R.string.save_in, displayName(it)) } + else -> held.savedTo?.first?.let { app.library.entry(it) }?.let { stringResource(R.string.save_in, displayName(it)) } + } ?: stringResource(R.string.save_to_mine) + IconButton(onClick = { save() }) { Icon(Icons.Rounded.Save, where) } + } else if (!newGame && !playGame && held.savedTo == null) { + IconButton(onClick = { place -= 1 }, enabled = place > 0) { + Icon(Icons.Rounded.ChevronLeft, stringResource(R.string.previous_game)) + } + IconButton(onClick = { place += 1 }, enabled = place + 1 < total) { + Icon(Icons.Rounded.ChevronRight, stringResource(R.string.next_game)) + } + } + // No menu during a game against Maia (§31.3): its moves go by its own buttons. + if (!gameOn) Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + // First, and only when there is something to take back (§29.6). + if (g != null && edit?.canUndo() == true) { + DropdownMenuItem(text = { Text(stringResource(R.string.undo_menu)) }, onClick = { + menu = false + undo() + }) + } + DropdownMenuItem(text = { Text(stringResource(R.string.game_info)) }, enabled = g != null, onClick = { + menu = false + info = true + }) + if (!newGame && !playGame && (whiteName != null || blackName != null)) { + val reason = when { + preview != null -> stringResource(R.string.prep_close_engine_line) + !prepPathAvailable -> stringResource(R.string.prep_null_move_unavailable) + else -> null + } + DropdownMenuItem( + text = { + Column { + Text(stringResource(R.string.prep_opponent)) + if (reason != null) { + Text(reason, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + }, + enabled = reason == null, + onClick = { + menu = false + prepSheet = true + }, + ) + } + DropdownMenuItem(text = { Text(stringResource(R.string.copy_pgn)) }, enabled = g != null, onClick = { + menu = false + scope.launch { + pgnText()?.let { + clipboard.setText(AnnotatedString(it)) + snackbar.showSnackbar(pgnCopied) + } + } + }) + DropdownMenuItem(text = { Text(stringResource(R.string.copy_fen)) }, enabled = node != null, onClick = { + menu = false + (preview?.let { it.line.steps[it.step].fen } ?: node?.fen)?.let { + clipboard.setText(AnnotatedString(it)) + scope.launch { snackbar.showSnackbar(fenCopied) } + } + }) + DropdownMenuItem(text = { Text(stringResource(R.string.share_game)) }, enabled = g != null, onClick = { + menu = false + scope.launch { + pgnText()?.let { text -> + val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, text) + context.startActivity(Intent.createChooser(send, null)) + } + } + }) + DropdownMenuItem(text = { Text(stringResource(R.string.settings)) }, onClick = { + menu = false + onSettings() + }) + } + } + }, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + // In the bottom bar, so that snackbars stand above the move buttons; beside the + // board when the phone lies on its side. + bottomBar = { if (!landscape) controls(Modifier) }, + ) { padding -> + val inner = Modifier.fillMaxSize().padding(top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding()) + // Black above the board, White below (swapped with the board, §7.11). A study with + // a title for White and no Black keeps both bars, so the board does not jump. + val study = whiteName != null && blackName == null + val result = g?.result ?: "" + // In a game: «thinking…» on the opponent's bar while it computes (§31.3). + val thinkingText = stringResource(R.string.play_thinking) + val maiaThinks = { white: Boolean -> if (gameOn && runThinking && run?.meta?.userWhite != white) thinkingText else null } + // In a game against the computer: the user without a name is «You»; the opponent is + // named with its strength and Rodent's character («Rodent IV 1800 · Tal»: the end + // goes first when it does not fit, never the strength, android-rodent.md §6.1). + val youText = stringResource(R.string.play_you) + val rivalText = run?.meta?.let { m -> listOfNotNull(m.label(), runStyle).joinToString(" · ") } + val playName = { white: Boolean -> + when { + !playGame || run == null -> null + run.meta.userWhite == white -> if ((if (white) whiteName else blackName) == null) youText else null + else -> rivalText + } + } + val whiteBar: @Composable () -> Unit = { + PlayerBar(playName(true) ?: whiteName ?: whiteLabel, if (playGame) "" else elo(tag("WhiteElo")), true, sideResult(result, true), known = whiteName != null || playGame, abbreviate = !study && !playGame, status = maiaThinks(true)) + } + val blackBar: @Composable () -> Unit = { + PlayerBar(playName(false) ?: blackName ?: blackLabel, if (playGame) "" else elo(tag("BlackElo")), false, sideResult(result, false), known = blackName != null || playGame, abbreviate = !playGame, status = maiaThinks(false)) + } + val topBar = if (flipped) whiteBar else blackBar + val bottomBar = if (flipped) blackBar else whiteBar + if (landscape) { + // The navigation buttons stand on a side of the screen: nothing goes under them. + // The bars go beside the board, so it keeps the full height. + Row(inner.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal))) { + board(Modifier.fillMaxHeight()) + Column(Modifier.weight(1f).fillMaxHeight()) { + topBar() + side(Modifier.weight(1f)) + bottomBar() + controls(Modifier) + } + } + } else { + Column(inner) { + topBar() + board(Modifier.fillMaxWidth()) + bottomBar() + side(Modifier.weight(1f)) + } + } + } + if (prepSheet && g != null) { + androidx.compose.material3.ModalBottomSheet(onDismissRequest = { prepSheet = false }) { + Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { + Text( + stringResource(R.string.prep_title), + style = MaterialTheme.typography.titleLarge, + modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp), + ) + listOfNotNull( + whiteName?.let { true to it }, + blackName?.let { false to it }, + ).forEach { (white, name) -> + Row( + Modifier.fillMaxWidth().heightIn(min = 64.dp).clickable { + prepStartFromGame(g, current, db, name, white)?.let { + prepSheet = false + onPrepare(it) + } + }.padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + SideDisc(white) + Spacer(Modifier.width(12.dp)) + Column { + PlayerName(name, MaterialTheme.typography.bodyLarge) + Text( + stringResource(if (white) R.string.prep_as_white else R.string.prep_as_black), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + } + } + if (info && g != null) { + AlertDialog( + onDismissRequest = { info = false }, + title = { Text(stringResource(R.string.game_info)) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + g.tags.filter { it.value.isNotBlank() && it.value != "?" && !it.value.startsWith("????") }.forEach { t -> + Row(Modifier.padding(vertical = 4.dp)) { + Text(tagLabel(t.name), Modifier.width(112.dp), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium) + Text(if (t.name == "Date" || t.name == "EventDate") pgnDate(t.value) else t.value, style = MaterialTheme.typography.bodyMedium) + } + } + if (g.notes.isNotEmpty()) { + Text(stringResource(R.string.notes), Modifier.padding(top = 12.dp), style = MaterialTheme.typography.labelLarge) + g.notes.forEach { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } + } + }, + confirmButton = { TextButton(onClick = { info = false }) { Text(stringResource(R.string.close)) } }, + // The user's own game, or a new one: its data can be changed (§30.5). + dismissButton = if (ownGame || newGame || held.savedTo != null) { + { + TextButton(onClick = { + info = false + editingData = true + formOpening++ + }) { Text(stringResource(R.string.edit)) } + } + } else { + null + }, + ) + } + if (editingData && g != null) androidx.compose.runtime.key(formOpening) { + GameDataForm( + g, + doneLabel = stringResource(if (firstSave) R.string.next else R.string.done), + onDone = { tags, result -> + editingData = false + edit?.let { e -> + e.setData(tags, result) + game = e.data().copy(notes = held.notes) + saves++ + } + if (firstSave) { + firstSave = false + saving = true + } + }, + onDismiss = { + editingData = false + firstSave = false + afterSave = null + }, + ) + } + if (saving) { + SaveSheet( + own = ownEntries, + last = lastOwn.getString("last", null), + onSave = { e -> + saving = false + saveInto(e.id, null) + }, + onCreate = { name -> + saving = false + scope.launch { runCatching { app.library.createOwn(name) }.onSuccess { saveInto(it.id, null) } } + }, + onDismiss = { + saving = false + afterSave = null + }, + ) + } + if (leaving) { + AlertDialog( + onDismissRequest = { leaving = false }, + title = { + Text( + if (ownGame) stringResource(R.string.save_changes_in, dbEntry?.let { displayName(it) } ?: "") + else stringResource(R.string.save_game_question), + ) + }, + confirmButton = { + TextButton(onClick = { + leaving = false + save(then = leaveTo ?: exit) + }) { Text(stringResource(if (ownGame || held.savedTo != null) R.string.save else R.string.save_to_db_ellipsis)) } + }, + dismissButton = { + Row { + TextButton(onClick = { + leaving = false + (leaveTo ?: exit)() + }) { Text(stringResource(R.string.dont_save)) } + TextButton(onClick = { leaving = false }) { Text(stringResource(R.string.cancel)) } + } + }, + ) + } + // «Play on from here» (§31.6): the moves up to the move, then a game against Maia. + val fromMove = playFrom + if (fromMove != null && g != null && edit != null) { + val n = g.nodes.getOrNull(fromMove) + if (n == null) { + playFrom = null + } else { + val moveLabel = (if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san).text + val origin = listOfNotNull(whiteName, blackName).joinToString(" — ").takeIf { it.isNotEmpty() } + val styles = RODENT_TEXTS.mapValues { stringResource(it.value.first) } + PlaySheet( + PlayFrom(n.fen, listOfNotNull(stringResource(R.string.play_from_label, moveLabel), origin).joinToString("\n"), whiteToMove(n.fen)), + onPlay = { choice -> + playFrom = null + val s = runCatching { edit?.playFrom(fromMove.toUInt()) }.getOrNull() ?: return@PlaySheet + val meta = choice.meta(depth(g, fromMove)) + beginComputerGame(app, s, meta, eventText, playNote(resources, meta, styles[meta.style])) + s.close() + // On the play screen itself the game in hand is read anew. + held.key = null + onPlayGame() + }, + onDismiss = { playFrom = null }, + ) + } + } + if (newGameSheet) { + PlaySheet(null, onPlay = { choice -> + newGameSheet = false + val s = GameSession.newGame("") + beginComputerGame(app, s, choice.meta(0), eventText, null) + s.close() + // The report of the game before is not this one's. + review.close() + reviewHidden = true + held.key = null + held.reloads.intValue++ + }, onDismiss = { newGameSheet = false }) + } + val askAt = askFrom + val adjournedMeta = app.maiaGames.current.collectAsState().value + if (askAt != null && adjournedMeta != null) { + AdjournedQuestion(adjournedMeta, onContinue = { + askFrom = null + held.key = null + onPlayGame() + }, onNew = { + askFrom = null + playFrom = askAt + }, onDismiss = { askFrom = null }) + } + if (resigning) { + AlertDialog( + onDismissRequest = { resigning = false }, + title = { Text(stringResource(R.string.play_resign_q)) }, + confirmButton = { + TextButton(onClick = { + resigning = false + run?.let { finishGame(PlayOver(if (it.meta.userWhite) "0-1" else "1-0", R.string.play_you_resigned, null)) } + }) { Text(stringResource(R.string.play_resign).removePrefix("⚑ "), color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { TextButton(onClick = { resigning = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } + val sheetMove = moveSheet + if (sheetMove != null && g != null && edit != null) { + val n = g.nodes.getOrNull(sheetMove) + if (n == null || n.parent == null) { + moveSheet = null + } else { + MoveSheet( + label = AnnotatedString(if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san), + inVariation = g.nodes[n.parent!!.toInt()].children.firstOrNull()?.toInt() != sheetMove, + runs = remember(sheetMove) { edit?.trainingRuns(sheetMove.toUInt())?.toInt() }, + canTrain = !n.nullMove, + // Not at mate or stalemate, nor after a null move; not inside a game being played. + canPlay = !n.nullMove && n.end.isEmpty() && !gameOn, + onPlay = { + moveSheet = null + if (app.maiaGames.current.value?.over == false) askFrom = sheetMove else playFrom = sheetMove + }, + onTrain = { + moveSheet = null + edit?.trainer(sheetMove.toUInt())?.let { t -> + preview = null + held.trainPly = 0 + held.trainFlipped = flipped + held.trainReturn = sheetMove + held.trainer.value = t + } + }, + onMakeMain = { + moveSheet = null + runCatching { edit?.makeMain(sheetMove.toUInt()) }.getOrNull()?.let { e -> + apply(e) + scope.launch { + if (snackbar.showSnackbar(mainText, undoText, duration = SnackbarDuration.Short) == SnackbarResult.ActionPerformed) undo() + } + } + }, + onDelete = { + moveSheet = null + runCatching { edit?.deleteFrom(sheetMove.toUInt()) }.getOrNull()?.let { e -> + apply(e) + scope.launch { + if (snackbar.showSnackbar(deletedText, undoText, duration = SnackbarDuration.Short) == SnackbarResult.ActionPerformed) undo() + } + } + }, + onDismiss = { moveSheet = null }, + ) + } + } + if (sheet) { + EngineSheet( + state = netState, + metered = remember(sheet) { !files.builtIn && files.metered() }, + onDownload = { + // Asked for by the analysis of the game: it starts when the engine is ready, + // the engine button stays as it is. + val forReview = sheetForReview + if (forReview != null) wantReview = forReview else wantEngine = true + files.prepare() + }, + onCancel = { + files.cancel() + wantEngine = false + wantReview = null + sheetForReview = null + sheet = false + scope.launch { snackbar.showSnackbar(cancelledText) } + }, + onDismiss = { + sheet = false + sheetForReview = null + }, + ) + } + if (reviewStart) { + ReviewStartSheet( + state = rs, + npsPerProcess = prefs.reviewNps, + onStart = { full -> + reviewStart = false + startReview(full) + }, + onDismiss = { reviewStart = false }, + ) + } + if (reviewReport && rs != null) { + ReviewSheet( + state = rs, + white = whiteName ?: whiteLabel, + black = blackName ?: blackLabel, + onError = { w, j -> + reviewReport = false + val hits = rs.moves.filter { it.white == w && it.judgement == j } + if (hits.isNotEmpty()) { + val k = ((reviewCycle[w to j] ?: -1) + 1) % hits.size + reviewCycle[w to j] = k + go(hits[k].node.toInt()) + } + }, + onAgain = { + reviewReport = false + reviewStart = true + }, + onHide = { + reviewReport = false + reviewHidden = true + }, + onDismiss = { reviewReport = false }, + ) + } +} + +private const val START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" + +/// The engine switch of the bottom bar, with its label (§7.4): filled and underlined +/// when on; with a download mark while the light build has no engine yet. +@Composable +private fun EngineButton(on: Boolean, needsDownload: Boolean, loading: NetState.Loading?, modifier: Modifier, onClick: () -> Unit) { + val label = stringResource(R.string.engine) + val state = stringResource( + when { + needsDownload -> R.string.engine_state_missing + on -> R.string.engine_state_on + else -> R.string.engine_state_off + }, + ) + val action by rememberUpdatedState(onClick) + val color = if (on) MaterialTheme.colorScheme.primary else LocalContentColor.current + Column( + modifier + .fillMaxHeight() + .semantics { + contentDescription = label + role = Role.Switch + stateDescription = state + onClick { action(); true } + } + .clickable(onClick = action), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { + Icon(if (on) Icons.Rounded.Memory else Icons.Outlined.Memory, null, tint = color) + if (loading != null) { + CircularProgressIndicator( + progress = { loading.done.toFloat() / loading.total.coerceAtLeast(1) }, + modifier = Modifier.size(34.dp), + strokeWidth = 2.dp, + ) + } else if (needsDownload) { + Icon( + Icons.Rounded.Download, + null, + tint = color, + modifier = Modifier.size(14.dp).align(Alignment.BottomEnd).background(MaterialTheme.colorScheme.surfaceContainer), + ) + } + } + Text(label, style = MaterialTheme.typography.labelSmall, color = color) + Box(Modifier.padding(top = 2.dp).width(24.dp).height(2.dp).background(if (on) MaterialTheme.colorScheme.primary else Color.Transparent)) + } +} + +/// The visible entry to whole-game analysis. The invitation uses the report's «!!» +/// teal; a finished report drops the fill. Progress and stopping stay in `ReviewPanel`. +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun ReviewButton( + report: Boolean, + enabled: Boolean, + modifier: Modifier, + preparing: Boolean = false, + progress: Pair? = null, + showLabel: Boolean = true, + onClick: () -> Unit, +) { + val label = when { + progress != null && !report -> "${progress.first}/${progress.second}" + report -> stringResource(R.string.review_report) + else -> stringResource(R.string.play_analyse_short) + } + val description = stringResource(if (report) R.string.review_report_menu else R.string.review_menu) + val spokenState = when { + preparing -> stringResource(R.string.preparing_engine) + progress != null -> stringResource(R.string.review_progress, progress.first, progress.second) + else -> null + } + val action by rememberUpdatedState(onClick) + val dark = LocalChessColors.current.dark + val accent = nagColor(3, dark) ?: LocalContentColor.current + val disabled = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + val filled = enabled && !report && !preparing && progress == null + val iconColor = when { + !enabled -> disabled + filled && dark -> Color(0xFF1B1B1B) + filled -> Color.White + else -> accent + } + Column( + modifier + .fillMaxHeight() + .clearAndSetSemantics { + contentDescription = description + role = Role.Button + if (enabled) onClick(description) { action(); true } else disabled() + spokenState?.let { stateDescription = it } + } + .combinedClickable( + enabled = enabled, + onClickLabel = description, + role = Role.Button, + hapticFeedbackEnabled = false, + onClick = action, + ), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box( + Modifier.size(36.dp).clip(RoundedCornerShape(10.dp)).background(if (filled) accent else Color.Transparent), + contentAlignment = Alignment.Center, + ) { + Icon(Icons.Rounded.QueryStats, null, tint = iconColor) + when { + progress != null -> CircularProgressIndicator( + progress = { progress.first.toFloat() / progress.second.coerceAtLeast(1) }, + modifier = Modifier.size(34.dp), + color = if (enabled) accent else disabled, + strokeWidth = 2.dp, + ) + preparing -> CircularProgressIndicator( + modifier = Modifier.size(34.dp), + color = if (enabled) accent else disabled, + strokeWidth = 2.dp, + ) + } + } + if (showLabel) { + Text( + label, + style = MaterialTheme.typography.labelSmall.merge(Tabular), + color = if (enabled) MaterialTheme.colorScheme.onSurface else disabled, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Box(Modifier.padding(top = 2.dp).width(24.dp).height(2.dp)) + } +} + +/// The row of continuations at a fork (§7.5): the line's own move first and filled. +@Composable +private fun Forks(moves: List, san: (String) -> AnnotatedString, onMove: (Int) -> Unit) { + Row( + Modifier.fillMaxWidth().height(48.dp).horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(stringResource(R.string.next_moves), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + moves.forEachIndexed { i, m -> + FilterChip( + selected = i == 0, + onClick = { onMove(m.id.toInt()) }, + label = { Text(AnnotatedString(if (m.white) "${m.moveNumber}." else "${m.moveNumber}…") + san(m.san)) }, + ) + } + } +} + +/// A button of the bottom bar. A tap is one action; an optional long press is a separate +/// action, never an auto-repeat. Long-press is also an accessibility custom action. +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun BarButton( + icon: ImageVector, + label: String, + enabled: Boolean, + modifier: Modifier, + iconSize: Int = 24, + mirrored: Boolean = false, + description: String = label, + onLongClickLabel: String? = null, + onLongClick: (() -> Unit)? = null, + onClick: () -> Unit, +) { + val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + val action by rememberUpdatedState(onClick) + val longAction by rememberUpdatedState(onLongClick) + Box( + modifier + .fillMaxHeight() + .clearAndSetSemantics { + contentDescription = description + role = Role.Button + if (enabled) { + onClick(label) { action(); true } + if (onLongClickLabel != null && longAction != null) { + onLongClick(onLongClickLabel) { longAction?.invoke(); true } + customActions = listOf(CustomAccessibilityAction(onLongClickLabel) { longAction?.invoke(); true }) + } + } else { + disabled() + } + } + .combinedClickable( + enabled = enabled, + onClickLabel = label, + role = Role.Button, + onLongClickLabel = onLongClickLabel, + onLongClick = onLongClick, + hapticFeedbackEnabled = false, + onClick = onClick, + ), + contentAlignment = Alignment.Center, + ) { + Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp).then(if (mirrored) Modifier.scale(-1f, 1f) else Modifier)) + } +} + +/// The names of the usual PGN tags in the language of the interface; others as they are. +@Composable +private fun tagLabel(name: String): String = when (name) { + "Event" -> stringResource(R.string.tag_event) + "Site" -> stringResource(R.string.tag_site) + "Date" -> stringResource(R.string.tag_date) + "Round" -> stringResource(R.string.tag_round) + "White" -> stringResource(R.string.tag_white) + "Black" -> stringResource(R.string.tag_black) + "Result" -> stringResource(R.string.tag_result) + "WhiteElo" -> stringResource(R.string.tag_white_elo) + "BlackElo" -> stringResource(R.string.tag_black_elo) + "ECO" -> "ECO" + "Annotator" -> stringResource(R.string.tag_annotator) + "PlyCount" -> stringResource(R.string.tag_plies) + else -> name +} + +/// "1858.??.??" → "1858", "1927.09.16" → "16.09.1927". +private fun pgnDate(date: String): String { + val parts = date.split('.') + if (parts.size != 3) return date + val (y, m, d) = parts + return when { + m.all { it.isDigit() } && d.all { it.isDigit() } -> "$d.$m.$y" + m.all { it.isDigit() } -> "$m.$y" + else -> y + } +} + +/// "Carlsen, Magnus" → "Carlsen"; "Magnus Carlsen" stays as it is. +/// A player above or below the board (§7.11): the side's disc, the name (full while it +/// fits), the rating, the share of the result. A missing name shows the side, greyed. +@Composable +private fun PlayerBar(name: String, elo: String, white: Boolean, result: String?, known: Boolean, abbreviate: Boolean = true, status: String? = null) { + PlayerLine( + name = name, + elo = elo, + result = result, + // A missing name shows the side greyed and in the regular weight (§7.11). + style = MaterialTheme.typography.titleSmall.let { if (known) it else it.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.Normal) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 36.dp).padding(horizontal = 16.dp), + disc = white, + nameColor = if (known) androidx.compose.ui.graphics.Color.Unspecified else MaterialTheme.colorScheme.onSurfaceVariant, + abbreviate = abbreviate, + status = status, + ) +} + +/// "1-0 · White won" for the end of the notation. +private fun resultLine(context: Context, result: String): String = when (result) { + "1-0" -> "1-0 · " + context.getString(R.string.white_won) + "0-1" -> "0-1 · " + context.getString(R.string.black_won) + "1/2-1/2" -> "½-½ · " + context.getString(R.string.draw) + else -> "" +} + +/// True only the very first time the board is touched (then the hint is shown). +/// A scope of its own: what is read in it is drawn again without its surroundings. +@Composable +private fun Live(content: @Composable () -> Unit) = content() + +/// What a long press on a move offers (android-play.md §29.6): make its line the main +/// one (in a variation), remove it with what follows. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun MoveSheet( + label: AnnotatedString, + inVariation: Boolean, + runs: Int?, + canTrain: Boolean, + onMakeMain: () -> Unit, + onDelete: () -> Unit, + onTrain: () -> Unit, + canPlay: Boolean, + onPlay: () -> Unit, + onDismiss: () -> Unit, +) { + androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { + Text(label, style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) + if (inVariation) SheetAction(Icons.Rounded.VerticalAlignTop, stringResource(R.string.make_main), onClick = onMakeMain) + SheetAction(Icons.Rounded.Close, stringResource(R.string.delete_move), onClick = onDelete) + HorizontalDivider(Modifier.padding(vertical = 4.dp), color = MaterialTheme.colorScheme.outlineVariant) + SheetAction(Icons.Rounded.SmartToy, stringResource(R.string.play_from_here), enabled = canPlay, onClick = onPlay) + SheetAction( + Icons.Rounded.School, + stringResource(R.string.train_learn), + trailing = runs?.takeIf { it > 0 }?.let { pluralStringResource(R.plurals.train_runs, it, it) }, + enabled = canTrain, + onClick = onTrain, + ) + } + } +} + +@Composable +private fun SheetAction(icon: ImageVector, text: String, trailing: String? = null, enabled: Boolean = true, onClick: () -> Unit) { + val alpha = if (enabled) 1f else 0.38f + Row( + Modifier.fillMaxWidth().height(56.dp).clickable(enabled = enabled, onClick = onClick).padding(horizontal = 24.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(icon, null, tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)) + Text(text, Modifier.weight(1f).padding(start = 16.dp), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface.copy(alpha = alpha)) + trailing?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt new file mode 100644 index 0000000..403064e --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt @@ -0,0 +1,501 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.layout.heightIn +import kotlinx.coroutines.flow.first +import androidx.compose.runtime.snapshotFlow +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +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.rounded.Close +import androidx.compose.material.icons.rounded.Search +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextButton +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +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.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +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.Source +import androidx.compose.ui.zIndex +import androidx.compose.ui.platform.LocalResources +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material.icons.rounded.Download +import androidx.compose.material.icons.rounded.Groups +import io.github.vrubelroman.chesspenguin.theme.Tabular +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import uniffi.mobile_api.ApiException +import uniffi.mobile_api.Database +import uniffi.mobile_api.GameRow + +private const val CHUNK = 100 + +/// The games of a database, with a search (android-ui.md §6). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GamesScreen( + db: String, + onBack: () -> Unit, + onGame: (place: Int, query: String) -> Unit, + onPlayers: () -> Unit = {}, +) { + val app = app() + val entries by app.library.entries.collectAsState() + val entry = entries.firstOrNull { it.id == db } + var database by remember { mutableStateOf(null) } + var failed by remember { mutableStateOf(null) } + // Read again when a download brought new games into it (android-ui.md §23). + LaunchedEffect(db, entry?.games, entry?.updated) { + app.library.database(db).onSuccess { database = it }.onFailure { failed = it } + } + var searching by rememberSaveable { mutableStateOf(false) } + var query by rememberSaveable { mutableStateOf("") } + var shown by remember { mutableStateOf?>(null) } + val list = rememberLazyListState() + val rows = remember { mutableStateMapOf>() } + LaunchedEffect(database, query) { + val d = database ?: return@LaunchedEffect + if (query.isNotEmpty()) delay(250) + val found = withContext(Dispatchers.Default) { app.library.listed(db, d, query) } + rows.clear() + shown = found + // Once the new list is laid out (else the list keeps its place by a row's key). + snapshotFlow { list.layoutInfo.totalItemsCount }.first { it == found.size } + // Back from a game: it in sight; new results start at the top. + val last = app.lastOpened[db]?.takeIf { it.first == query }?.second?.takeIf { it < found.size } + val first = list.firstVisibleItemIndex + val seen = list.layoutInfo.visibleItemsInfo.size.takeIf { it > 0 } ?: 6 + when { + last == null -> list.scrollToItem(0) + // Already on the screen (the list kept its place): it stays where it is. + last in first until first + seen - 1 -> {} + else -> list.scrollToItem((last - 3).coerceAtLeast(0)) + } + app.shown[db] = found + } + val scroll = TopAppBarDefaults.pinnedScrollBehavior() + val download = app.downloads.views.collectAsState().value[db] + val snackbar = remember { SnackbarHostState() } + UpdateMessages(snackbar) + val resources = LocalResources.current + // How a download of this database ended (§23.3); the list reads it again by itself. + LaunchedEffect(db) { + app.downloads.finished.collect { f -> + if (f.id != db) return@collect + val text = finishedText(resources, f) ?: return@collect + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(text) + } + } + val focus = remember { FocusRequester() } + val keyboard = LocalSoftwareKeyboardController.current + BackHandler(searching) { + searching = false + query = "" + } + + Scaffold( + modifier = Modifier.nestedScroll(scroll.nestedScrollConnection), + 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.search_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(entry?.let { displayName(it) } ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis) + database?.let { d -> + val n = d.len().toInt() + val found = shown?.size + Text( + if (query.isNotEmpty() && found != null) { + stringResource(R.string.found_of, groupDigits(found), groupDigits(n)) + } else if (download?.state?.running == true) { + // The games come as the download goes, as on the list of + // databases; the list itself is read again when it ends. + stringResource(R.string.online_downloading, groupDigits((entry?.games ?: n) + download.state.added.toInt())) + } else { + pluralStringResource(R.plurals.games_count, n, groupDigits(n)) + }, + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + }, + 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 = onPlayers) { Icon(Icons.Rounded.Groups, stringResource(R.string.players)) } + IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) } + // A downloaded database: its new games from here, where they are + // looked for (android-ui.md §23.3); ✕ while they come. + if (entry?.source == Source.Online) { + if (download?.state?.running == true) { + IconButton(onClick = { app.downloads.cancel(db) }) { Icon(Icons.Rounded.Close, stringResource(R.string.online_stop_download)) } + } else { + IconButton(onClick = { entry.let { app.downloads.update(it) } }) { Icon(Icons.Rounded.Download, stringResource(R.string.online_update)) } + } + } + } + }, + scrollBehavior = scroll, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + Box(Modifier.fillMaxSize().padding(padding)) { + download?.takeIf { it.state.running }?.let { v -> + val share = downloadShare(v) + val bar = Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopStart).zIndex(1f) + if (share != null) LinearProgressIndicator(progress = { share }, modifier = bar) else LinearProgressIndicator(bar) + } + val games = shown + when { + failed != null -> Message(stringResource(R.string.open_failed), openProblem(failed!!)) { + // The way out: take the database off the list, add the file again. + TextButton(onClick = { + app.library.remove(db)?.let { app.library.forget(it.second) } + onBack() + }) { Text(stringResource(R.string.remove)) } + } + games == null -> Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) { + CircularProgressIndicator() + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.reading), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + games.isEmpty() -> Message(stringResource(R.string.nothing_found), "") + else -> { + // Wide enough for the database's largest number. + val numberWidth = numberWidth(database?.len()?.toInt() ?: games.size) + val last = app.lastOpened[db]?.takeIf { it.first == query }?.second + LazyColumn(Modifier.fillMaxSize(), state = list) { + items(games.size, key = { games[it].toLong() }) { place -> + val chunk = place / CHUNK + val loaded = rows[chunk] + LaunchedEffect(chunk, games) { + if (rows[chunk] == null) { + val d = database ?: return@LaunchedEffect + val part = games.subList(chunk * CHUNK, minOf(games.size, (chunk + 1) * CHUNK)) + val read = withContext(Dispatchers.Default) { d.rowsOf(part) } + // Rows of a list replaced meanwhile (a new search) are not this one's. + if (shown === games) rows[chunk] = read + } + } + GameRowView( + games[place].toInt() + 1, + numberWidth, + loaded?.getOrNull(place % CHUNK), + lastOpened = place == last, + divider = place < games.size - 1, + query = query, + ) { onGame(place, query) } + } + } + } + } + } + } +} + +@Composable +private fun Message(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() + } + } +} + +/// Why a database did not open, in plain words with the next step (§11). +@Composable +fun openProblem(e: Throwable): String = when (e) { + is io.github.vrubelroman.chesspenguin.data.NoGames -> stringResource(R.string.file_no_games) + is io.github.vrubelroman.chesspenguin.data.MissingPart -> stringResource(R.string.open_missing_part, e.file) + is SecurityException, is java.io.FileNotFoundException, is ApiException.Io -> stringResource(R.string.open_no_access) + is ApiException.Corrupt -> stringResource(R.string.open_corrupt) + is ApiException.Empty -> stringResource(R.string.open_empty) + is ApiException.Unsupported -> stringResource(R.string.open_unsupported, e.detail) + else -> "" +} + +/// The width of the numbers column: the digits of `count`, grouped as shown. +@Composable +private fun numberWidth(count: Int): androidx.compose.ui.unit.Dp { + val style = MaterialTheme.typography.bodySmall.merge(Tabular) + val measurer = androidx.compose.ui.text.rememberTextMeasurer() + val density = androidx.compose.ui.platform.LocalDensity.current + return remember(count, style, density) { + with(density) { measurer.measure(groupDigits(count.coerceAtLeast(1)), style).size.width.toDp() } + } +} + +/// One game (§6.2, android-lists.md §3): its number, White and Black each on a line of +/// their own (a disc of the side, the rating, the share of the result), then event · year +/// and the ECO on a tag. A thin line under it; the game last opened is marked. The row +/// is read as one sentence by TalkBack. +@Composable +private fun GameRowView( + number: Int, + numberWidth: androidx.compose.ui.unit.Dp, + row: GameRow?, + lastOpened: Boolean, + divider: Boolean, + query: String, + onClick: () -> Unit, +) { + // 6 + 24 + 24 + 20 + 6 = 80 dp at the normal font size; the lines grow with a larger font. + val nameLine = lineHeight(MaterialTheme.typography.bodyLarge, 24.dp) + val detailsLine = lineHeight(MaterialTheme.typography.bodyMedium, 20.dp) + val lastText = stringResource(R.string.last_opened) + val said = row?.let { rowDescription(number, it) + if (lastOpened) ". $lastText" else "" } ?: "" + val colors = MaterialTheme.colorScheme + Box( + Modifier + .fillMaxWidth() + .height(12.dp + nameLine * 2 + detailsLine) + .background(if (lastOpened) colors.surfaceContainer else Color.Transparent) + .clickable(enabled = row != null, onClick = onClick) + .clearAndSetSemantics { if (row != null) contentDescription = said }, + ) { + Row(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 6.dp), verticalAlignment = Alignment.Top) { + // Level with White's line. + Box(Modifier.width(numberWidth).height(nameLine), contentAlignment = Alignment.CenterEnd) { + Text( + groupDigits(number), + style = MaterialTheme.typography.bodySmall.merge(Tabular), + color = colors.onSurfaceVariant, + maxLines = 1, + ) + } + Spacer(Modifier.width(12.dp)) + GameRowText(row, nameLine, detailsLine, query, Modifier.weight(1f)) + } + if (lastOpened) { + Box( + Modifier.align(Alignment.CenterStart).width(3.dp).fillMaxHeight() + .background(colors.primary, RoundedCornerShape(topEnd = 2.dp, bottomEnd = 2.dp)), + ) + } + // From the discs to 16 dp before the edge; the number stays in the margin. + if (divider) { + Box( + Modifier.align(Alignment.BottomStart).padding(start = 16.dp + numberWidth + 12.dp, end = 16.dp) + .fillMaxWidth().height(1.dp).background(colors.outlineVariant), + ) + } + } +} + +@Composable +private fun GameRowText(row: GameRow?, nameLine: androidx.compose.ui.unit.Dp, detailsLine: androidx.compose.ui.unit.Dp, query: String, modifier: Modifier) { + Column(modifier) { + if (row == null) return@Column + val style = MaterialTheme.typography.bodyLarge + val muted = MaterialTheme.colorScheme.onSurfaceVariant + val white = row.white.trim().takeIf { it.isNotEmpty() && it != "?" } + val black = row.black.trim().takeIf { it.isNotEmpty() && it != "?" } + val study = white != null && black == null + if (study) { + // A study or a book position: a title for White and no Black — two lines of it. + // From the top, level with the number, not centred in the two lines; no discs: + // these are not players. + Box(Modifier.height(nameLine * 2)) { + PlayerName(white, style, maxLines = 2, abbreviate = false, highlight = query) + } + } else { + ListPlayer(white, elo(row.whiteElo), sideResult(row.result, true), true, style, nameLine, query) + ListPlayer(black, elo(row.blackElo), sideResult(row.result, false), false, style, nameLine, query) + } + val details = joinKnown(row.event, year(row.date)) + val eco = row.eco.trim().takeIf { it.isNotEmpty() && it != "?" } + if (details.isNotEmpty() || eco != null) { + // Under the names (past the discs); the ECO tag never gives way, the event does. + Row(Modifier.height(detailsLine).padding(start = if (study) 0.dp else 16.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + highlighted(details, query), + style = MaterialTheme.typography.bodyMedium, + color = muted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (eco != null) { + Spacer(Modifier.width(8.dp)) + EcoTag(eco, marked = query.split(' ').any { it.isNotBlank() && eco.startsWith(it.trim(), ignoreCase = true) }) + } + } + } + } +} + +/// One player in the list: the disc of the side, the name (the winner's a little +/// heavier), the rating, the share of the result on its tile. +@Composable +private fun ListPlayer( + name: String?, + rating: String, + result: String?, + white: Boolean, + style: androidx.compose.ui.text.TextStyle, + height: androidx.compose.ui.unit.Dp, + query: String, +) { + val won = result == "1" + Row(Modifier.height(height), verticalAlignment = Alignment.CenterVertically) { + SideDisc(white, 8.dp) + Spacer(Modifier.width(8.dp)) + Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + PlayerName( + name ?: "?", + if (won) style.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.Medium) else style, + Modifier.weight(1f, fill = false), + if (name == null) MaterialTheme.colorScheme.onSurfaceVariant else Color.Unspecified, + highlight = query, + ) + if (rating.isNotEmpty()) { + Spacer(Modifier.width(8.dp)) + Text(rating, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) + } + } + Spacer(Modifier.width(8.dp)) + ResultTile(result) + } +} + +/// The opening's code on a small outlined tag at the right of the details line; filled +/// like the other matches when it is what was searched for. +@Composable +private fun EcoTag(eco: String, marked: Boolean) { + val shape = RoundedCornerShape(4.dp) + val colors = MaterialTheme.colorScheme + Box( + Modifier.heightIn(min = 16.dp).widthIn(min = 32.dp) + .background(if (marked) colors.primaryContainer else Color.Transparent, shape) + .border(1.dp, if (marked) colors.primaryContainer else colors.outline, shape) + .padding(horizontal = 4.dp), + contentAlignment = Alignment.Center, + ) { + Text( + eco, + style = MaterialTheme.typography.labelSmall.merge(Tabular), + color = if (marked) colors.onPrimaryContainer else colors.onSurfaceVariant, + maxLines = 1, + ) + } +} + +/// "No. 12. White: Carlsen, Magnus, 2830. Black: … . 1-0, White won. Event · 2025 · C42." +@Composable +private fun rowDescription(number: Int, row: GameRow): String { + val player = { label: String, name: String, rating: String -> + "$label: " + joinKnownComma(name.trim().takeIf { it.isNotEmpty() } ?: "?", elo(rating).let { if (it.isEmpty()) "" else "Elo $it" }) + } + val result = when (row.result) { + "1-0" -> "1-0, " + stringResource(R.string.white_won).lowercase() + "0-1" -> "0-1, " + stringResource(R.string.black_won).lowercase() + "1/2-1/2" -> stringResource(R.string.draw) + else -> "" + } + // A study or a book chapter: a title for White and no Black is read as the title. + val title = row.white.trim().takeIf { it.isNotEmpty() && it != "?" && row.black.trim().let { b -> b.isEmpty() || b == "?" } } + return listOf( + stringResource(R.string.game_number, groupDigits(number)), + title ?: player(stringResource(R.string.tag_white), row.white, row.whiteElo), + if (title != null) "" else player(stringResource(R.string.tag_black), row.black, row.blackElo), + result, + listOf(row.event, year(row.date), row.eco).map { it.trim() }.filter { it.isNotEmpty() && it != "?" }.joinToString(", "), + ).filter { it.isNotEmpty() }.joinToString(". ") +} + +private fun joinKnownComma(vararg parts: String): String = parts.filter { it.isNotEmpty() }.joinToString(", ") + +/// A text style's line height in dp (it grows with the font scale), at least `min`. +@Composable +private fun lineHeight(style: androidx.compose.ui.text.TextStyle, min: androidx.compose.ui.unit.Dp): androidx.compose.ui.unit.Dp { + val h = style.lineHeight + if (!h.isSp) return min + return with(androidx.compose.ui.platform.LocalDensity.current) { h.toDp() }.coerceAtLeast(min) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt new file mode 100644 index 0000000..711b0f2 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt @@ -0,0 +1,435 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.ui.input.pointer.PointerEventPass +import kotlinx.coroutines.withTimeoutOrNull +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.withLink +import androidx.compose.ui.text.withStyle +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.onClick +import androidx.compose.ui.semantics.onLongClick +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.theme.ChessColors +import io.github.vrubelroman.chesspenguin.theme.LocalChessColors +import io.github.vrubelroman.chesspenguin.theme.nagColor +import uniffi.mobile_api.GameData +import uniffi.mobile_api.MoveJudgement +import uniffi.mobile_api.MoveNode + +/// A piece of the notation: the main line as a table of moves, comments and variations +/// as full-width blocks between its rows (as on the desktop, android-ui.md §7.3). +sealed interface Item { + data class Comment(val text: String) : Item + data class Moves(val number: Int, val white: Int?, val black: Int?) : Item + data class Variation(val start: Int, val depth: Int) : Item + data class Result(val text: String) : Item +} + +/// The items of a game, and for each node the item that shows it (to keep it in view). +fun layout(game: GameData, resultText: String): Pair, Map> { + val nodes = game.nodes + val items = ArrayList() + val where = HashMap() + fun node(i: Int) = nodes[i] + val root = node(0) + if (root.commentAfter.isNotEmpty()) items += Item.Comment(root.commentAfter) + var row: Item.Moves? = null + fun flush() { + row?.let { r -> + items += r + r.white?.let { where[it] = items.size - 1 } + r.black?.let { where[it] = items.size - 1 } + } + row = null + } + fun markVariation(start: Int, at: Int) { + // Every node of the variation (its whole subtree) is shown by this item. + val stack = ArrayDeque(listOf(start)) + while (stack.isNotEmpty()) { + val n = stack.removeLast() + where[n] = at + node(n).children.forEach { stack.add(it.toInt()) } + } + } + var parent = 0 + while (true) { + val kids = node(parent).children + if (kids.isEmpty()) break + val id = kids[0].toInt() + val n = node(id) + if (n.commentBefore.isNotEmpty()) { + flush() + items += Item.Comment(n.commentBefore) + } + if (n.white) { + flush() + row = Item.Moves(n.moveNumber.toInt(), id, null) + } else { + row = (row ?: Item.Moves(n.moveNumber.toInt(), null, null)).copy(black = id) + } + val variations = kids.drop(1).map { it.toInt() } + val interrupted = n.commentAfter.isNotEmpty() || variations.isNotEmpty() + if (interrupted || !n.white) { + flush() + if (n.commentAfter.isNotEmpty()) items += Item.Comment(n.commentAfter) + for (v in variations) { + items += Item.Variation(v, 1) + markVariation(v, items.size - 1) + } + } + parent = id + } + flush() + if (resultText.isNotEmpty()) items += Item.Result(resultText) + return items to where +} + +private fun label(n: MoveNode, number: Boolean, san: (String) -> AnnotatedString): AnnotatedString = when { + n.white -> AnnotatedString("${n.moveNumber}.") + san(n.san) + number -> AnnotatedString("${n.moveNumber}…") + san(n.san) + else -> san(n.san) +} + +/// A variation as flowing text: its moves (each a link), comments in italics, nested +/// variations in parentheses. +@Composable +private fun variationText( + game: GameData, + start: Int, + current: Int, + chess: ChessColors, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, +): AnnotatedString { + val nodes = game.nodes + val comment = chess.comment + val onSurface = MaterialTheme.colorScheme.onSurface + return remember(game, start, current, san) { + buildAnnotatedString { + // A space goes before each word, except right after "(". + var space = false + fun word(write: () -> Unit) { + if (space) append(' ') + write() + space = true + } + fun line(first: Int) { + var id = first + var number = true + while (true) { + val n = nodes[id] + if (n.commentBefore.isNotEmpty()) { + word { withStyle(SpanStyle(color = comment, fontStyle = FontStyle.Italic)) { append(n.commentBefore) } } + number = true + } + val style = if (id == current) { + SpanStyle(background = chess.currentMove, color = onSurface, fontWeight = FontWeight.Medium) + } else { + SpanStyle(color = onSurface) + } + val target = id + word { + withLink(LinkAnnotation.Clickable("m$id", TextLinkStyles(style)) { onMove(target) }) { + append(label(n, number, san)) + } + if (n.nagSymbols.isNotEmpty()) { + // On the highlighted move the sign takes the text color. + val c = if (id == current) onSurface else n.nags.firstOrNull()?.let { nagColor(it.toInt(), chess.dark) } ?: onSurface + withStyle(SpanStyle(color = c)) { append(n.nagSymbols) } + } + } + number = false + if (n.commentAfter.isNotEmpty()) { + word { withStyle(SpanStyle(color = comment, fontStyle = FontStyle.Italic)) { append(n.commentAfter) } } + number = true + } + // The alternatives to this move (but not to the line's first move: those + // belong to the level above). + if (id != first) { + val parent = n.parent?.toInt() + if (parent != null) { + for (v in nodes[parent].children.drop(1)) { + word { append('(') } + space = false + line(v.toInt()) + append(')') + number = true + } + } + } + val next = n.children.firstOrNull() ?: break + id = next.toInt() + } + } + line(start) + } + } +} + +/// The notation under the board (android-ui.md §7.3): the current move highlighted +/// and kept in view; a tap on a move goes there. `marks` are the engine's judgements of +/// main-line moves (the game report, §21.4). +@Composable +fun Notation( + game: GameData, + items: List, + where: Map, + current: Int, + state: LazyListState, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, + modifier: Modifier = Modifier, + marks: Map = emptyMap(), + onLongMove: ((Int) -> Unit)? = null, +) { + val chess = LocalChessColors.current + LaunchedEffect(current) { + val at = where[current] ?: if (current == 0) 0 else return@LaunchedEffect + val visible = state.layoutInfo.visibleItemsInfo + if (visible.none { it.index == at } || visible.firstOrNull()?.index == at || visible.lastOrNull()?.index == at) { + // The current move a third down what is visible: whole however few rows fit + // (beside the board with the engine on, only two or three). + state.animateScrollToItem(at, -(state.layoutInfo.viewportSize.height / 3)) + } + } + LazyColumn(modifier, state = state, contentPadding = PaddingValues(bottom = 8.dp)) { + itemsIndexed(items) { _, item -> + when (item) { + is Item.Comment -> Text( + item.text, + color = chess.comment, + fontSize = 15.sp, + lineHeight = 22.sp, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 4.dp) + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerLow) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) + is Item.Moves -> MovesRow(game, item, current, chess, san, onMove, marks, onLongMove) + is Item.Variation -> Box( + Modifier + .fillMaxWidth() + .padding(start = (16 + 16 * (item.depth - 1)).dp, end = 16.dp, top = 2.dp, bottom = 2.dp), + ) { + Row(Modifier.height(androidx.compose.foundation.layout.IntrinsicSize.Min)) { + Box(Modifier.width(2.dp).fillMaxHeight().background(MaterialTheme.colorScheme.outlineVariant)) + val text = variationText(game, item.start, current, chess, san, onMove) + var layout by remember { mutableStateOf(null) } + Text( + text, + fontSize = 15.sp, + lineHeight = 28.sp, + onTextLayout = { layout = it }, + modifier = Modifier + .padding(start = 12.dp, end = 4.dp) + .then( + if (onLongMove == null) Modifier else Modifier.pointerInput(text) { + // A long press on a move of the variation: the move it is + // on. Seen before the links (the first pass), and the rest + // of the press is taken, so that the link does not also + // take it as a tap; a short tap stays the link's. + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + val released = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) { + while (true) { + val e = awaitPointerEvent(PointerEventPass.Initial) + val c = e.changes.firstOrNull { it.id == down.id } ?: return@withTimeoutOrNull true + if (!c.pressed || (c.position - down.position).getDistance() > viewConfiguration.touchSlop) return@withTimeoutOrNull true + } + @Suppress("UNREACHABLE_CODE") true + } + if (released != null) return@awaitEachGesture + val offset = layout?.getOffsetForPosition(down.position) ?: return@awaitEachGesture + val id = text.getLinkAnnotations(offset, offset + 1).firstOrNull() + ?.let { (it.item as? LinkAnnotation.Clickable)?.tag?.removePrefix("m")?.toIntOrNull() } + ?: return@awaitEachGesture + onLongMove(id) + while (true) { + val e = awaitPointerEvent(PointerEventPass.Initial) + e.changes.forEach { it.consume() } + if (e.changes.none { it.pressed }) break + } + } + }, + ), + ) + } + } + is Item.Result -> Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) { + Text( + item.text, + style = MaterialTheme.typography.labelLarge, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + .padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + } + } + } +} + +@Composable +private fun MovesRow( + game: GameData, + row: Item.Moves, + current: Int, + chess: ChessColors, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, + marks: Map, + onLongMove: ((Int) -> Unit)?, +) { + Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + "${row.number}", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 15.sp, + modifier = Modifier.width(40.dp).padding(end = 8.dp), + textAlign = androidx.compose.ui.text.style.TextAlign.End, + ) + MoveCell(game, row.white, true, current, chess, san, onMove, Modifier.weight(1f), row.white?.let { marks[it] }, onLongMove) + MoveCell(game, row.black, false, current, chess, san, onMove, Modifier.weight(1f), row.black?.let { marks[it] }, onLongMove) + } +} + +@Composable +private fun MoveCell( + game: GameData, + id: Int?, + white: Boolean, + current: Int, + chess: ChessColors, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, + modifier: Modifier, + mark: MoveJudgement?, + onLongMove: ((Int) -> Unit)?, +) { + val selected = id != null && id == current + // The engine's mark stands right after the move, the move in its color (as on Lichess); + // where the author already gave the move a sign, the author's sign stands instead. + val mark = mark?.takeIf { id == null || game.nodes[id].nags.none { (it.toInt() and 0xFF) in 1..6 } } + // TalkBack reads "4, White, dxe5", the engine's judgement, and whether it is the + // current move. + val markName = mark?.let { judgementName(it) } + val spoken = id?.let { + val n = game.nodes[it] + stringResource(if (white) R.string.move_white else R.string.move_black, n.moveNumber.toInt(), n.san + n.nagSymbols) + + (markName?.let { m -> ", $m" } ?: "") + } + val currentLabel = stringResource(R.string.current_move) + val actionsLabel = stringResource(R.string.move_actions) + // The whole cell takes the tap; the fill only hugs the move. + Box( + modifier + .fillMaxHeight() + .then( + when { + id == null -> Modifier + onLongMove != null -> Modifier.combinedClickable(onLongClick = { onLongMove(id) }) { onMove(id) } + else -> Modifier.clickable { onMove(id) } + }, + ) + .then( + if (spoken != null) { + Modifier.clearAndSetSemantics { + contentDescription = spoken + role = Role.Button + this.selected = selected + if (selected) stateDescription = currentLabel + onClick { onMove(id); true } + if (onLongMove != null) onLongClick(actionsLabel) { onLongMove(id); true } + } + } else { + Modifier + }, + ) + .padding(start = 4.dp), + contentAlignment = Alignment.CenterStart, + ) { + if (id == null) { + // "4. … Nf6": only White's empty cell says that a move is there. + if (white) Text("…", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 17.sp, modifier = Modifier.padding(horizontal = 8.dp)) + } else { + val n = game.nodes[id] + Row(verticalAlignment = Alignment.CenterVertically) { + Row( + Modifier + .clip(RoundedCornerShape(6.dp)) + .background(if (selected) chess.currentMove else Color.Transparent) + .padding(horizontal = 8.dp, vertical = 6.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.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()) { + Text( + n.nagSymbols, + fontSize = 17.sp, + fontWeight = FontWeight.Bold, + color = if (selected) { + MaterialTheme.colorScheme.onSurface + } else { + n.nags.firstOrNull()?.let { nagColor(it.toInt(), chess.dark) } ?: MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + } + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/OnlineScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/OnlineScreen.kt new file mode 100644 index 0000000..cf7fa77 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/OnlineScreen.kt @@ -0,0 +1,500 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +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.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +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.platform.LocalSoftwareKeyboardController +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.heading +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.compose.viewModel +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.DownloadView +import io.github.vrubelroman.chesspenguin.data.Source +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import uniffi.mobile_api.AccountLookup +import uniffi.mobile_api.OnlineAccount +import uniffi.mobile_api.OnlineFailure +import uniffi.mobile_api.OnlineProblem +import uniffi.mobile_api.Site +import uniffi.mobile_api.findAccount +import uniffi.mobile_api.onlineDatabase +import uniffi.mobile_api.onlineTargets +import uniffi.mobile_api.validNickname +import java.io.File +import kotlin.math.ceil + +/// Lichess gives about this many games a second to an anonymous export. +private const val LICHESS_GAMES_PER_SECOND = 20.0 + +fun siteName(s: Site): String = when (s) { + Site.LICHESS -> "Lichess" + Site.CHESS_COM -> "Chess.com" +} + +/// "1 234 games" in the language of the interface. +@Composable +fun gamesText(n: Long): String { + val k = n.coerceAtMost(Int.MAX_VALUE.toLong()).toInt() + return pluralStringResource(R.plurals.games_count, k, groupDigits(k)) +} + +/// Seconds Lichess needs for `games` games. +private fun lichessSeconds(games: Long): Double = games / LICHESS_GAMES_PER_SECOND + +/// What went wrong, in words for a chess player (android-ui.md §23.4). +@Composable +fun onlineProblemText(f: OnlineFailure): String { + val site = f.site?.let(::siteName) ?: "—" + return when (f.problem) { + OnlineProblem.NETWORK -> stringResource(R.string.online_err_network, site) + OnlineProblem.RATE_LIMITED -> stringResource(R.string.online_err_rate, site) + OnlineProblem.UNEXPECTED -> stringResource(R.string.online_err_unexpected, site) + OnlineProblem.DISK -> stringResource(R.string.online_err_disk) + OnlineProblem.BUSY -> stringResource(R.string.online_err_busy) + } +} + +/// The short form, for the subtitle of a database and the snackbar (§23.3). +fun problemShort(res: android.content.res.Resources, f: OnlineFailure): String { + val site = f.site?.let(::siteName) + return when { + site != null && f.problem == OnlineProblem.NETWORK -> res.getString(R.string.online_short_network, site) + site != null && f.problem == OnlineProblem.RATE_LIMITED -> res.getString(R.string.online_short_rate, site) + else -> res.getString(R.string.online_short_failed) + } +} + +@Composable +fun onlineProblemShort(f: OnlineFailure): String = problemShort(androidx.compose.ui.platform.LocalResources.current, f) + +/// What a running download is doing: "Lichess: 1 200 of about 6 541 · about 5 min left", +/// "Chess.com: month 12 of 84 · 340 games". +@Composable +fun downloadProgressText(v: DownloadView): String { + val s = v.state + val account = v.accounts.getOrNull(s.account.toInt()) + val games = s.accountGames.toLong() + return when (account?.site) { + Site.LICHESS -> { + val total = account.games?.toLong() ?: 0 + if (total > games) { + val minutes = ceil(lichessSeconds(total - games) / 60.0).toInt().coerceAtLeast(1) + stringResource(R.string.online_progress_lichess, groupDigits(games.toInt()), groupDigits(total.toInt()), minutes) + } else { + stringResource(R.string.online_progress_count, "Lichess", gamesText(games)) + } + } + Site.CHESS_COM -> if (s.monthsTotal > 0u) { + stringResource(R.string.online_progress_chesscom, s.monthsDone.toInt(), s.monthsTotal.toInt(), gamesText(games)) + } else { + stringResource(R.string.online_progress_count, "Chess.com", gamesText(games)) + } + null -> stringResource(R.string.online_downloading, groupDigits(s.added.toInt())) + } +} + +/// How a finished download went: "Done: 473 games" the first time, "+12, 1 246 games in +/// all" later. +@Composable +fun downloadResultText(v: DownloadView): String { + val s = v.state + s.failure?.let { return onlineProblemText(it) } + val total = s.total?.toLong() ?: 0 + return when { + s.cancelled -> stringResource(R.string.online_stopped, gamesText(total)) + total == 0L -> stringResource(R.string.online_no_games) + s.added == 0UL -> stringResource(R.string.online_no_new, gamesText(total)) + v.fresh -> stringResource(R.string.online_done, gamesText(total)) + else -> stringResource(R.string.online_added, groupDigits(s.added.toInt()), gamesText(total)) + } +} + +/// The share of the whole download done, when it is known: each account is an equal part +/// (Lichess counted by its games, Chess.com by months). +fun downloadShare(v: DownloadView): Float? { + val s = v.state + val i = s.account.toInt() + val account = v.accounts.getOrNull(i) ?: return null + val part = when (account.site) { + Site.LICHESS -> account.games?.takeIf { it > 0UL }?.let { (s.accountGames.toDouble() / it.toDouble()).toFloat() } + Site.CHESS_COM -> s.monthsTotal.takeIf { it > 0u }?.let { s.monthsDone.toFloat() / it.toFloat() } + } ?: return null + return ((i + part.coerceIn(0f, 1f)) / v.accounts.size).coerceIn(0f, 1f) +} + +/// The search of the screen: kept when the phone is turned (android-ui.md §23.2). +class OnlineSearch : ViewModel() { + var found by mutableStateOf?>(null) + var chosen by mutableStateOf(setOf()) + var searching by mutableStateOf(false) + + fun find(forLichess: String, forChessCom: String) { + if (searching) return + searching = true + viewModelScope.launch { + val result = withContext(Dispatchers.IO) { + val li = async { findAccount(Site.LICHESS, forLichess) } + val cc = async { findAccount(Site.CHESS_COM, forChessCom) } + mapOf(Site.LICHESS to li.await(), Site.CHESS_COM to cc.await()) + } + found = result + chosen = result.filterValues { it is AccountLookup.Found }.keys + searching = false + } + } + + fun forget() { + found = null + } +} + +/// A nickname is shown as wrong only for a character it may not have or when it is too +/// long; a short one is still being typed. +private fun badNick(nick: String): Boolean { + val t = nick.trim() + return t.length > 30 || t.any { !(it.isLetterOrDigit() && it.code < 128) && it != '_' && it != '-' } +} + +/// "Games from Lichess and Chess.com" (android-ui.md §23.2): a nickname, what was found on +/// each site, the download and how it goes. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun OnlineScreen(onBack: () -> Unit, onOpen: (String) -> Unit) { + val app = app() + val downloads = app.downloads + val views by downloads.views.collectAsState() + val entries by app.library.entries.collectAsState() + val search: OnlineSearch = viewModel() + val keyboard = LocalSoftwareKeyboardController.current + var nick by rememberSaveable { mutableStateOf("") } + // A different nickname on Chess.com, once asked for. + var other by rememberSaveable { mutableStateOf(null) } + var together by rememberSaveable { mutableStateOf(true) } + // The databases this screen started downloading; the found accounts are hidden then, + // until the next search. + var started by rememberSaveable { mutableStateOf(listOf()) } + var launched by rememberSaveable { mutableStateOf(false) } + + val nickOk = validNickname(nick) + val otherOk = other?.let { it.isBlank() || validNickname(it) } ?: true + fun find() { + if (!nickOk || !otherOk) return + keyboard?.hide() + launched = false + val forLichess = nick.trim() + search.find(forLichess, other?.trim()?.takeIf { it.isNotEmpty() } ?: forLichess) + } + + val found = search.found + val accounts: List = found.orEmpty() + .filterKeys { it in search.chosen } + .values.mapNotNull { (it as? AccountLookup.Found)?.account } + val merge = together && accounts.size > 1 + // Where the games go, and how many are there already; read again when a download ends. + val ended = started.count { views[it]?.state?.running == false } + val targets by produceState(emptyList>(), accounts, merge, ended) { + value = withContext(Dispatchers.IO) { + if (accounts.isEmpty()) { + emptyList() + } else { + onlineTargets(downloads.dir.path, accounts, merge).map { t -> + t.path to (if (t.exists) onlineDatabase(t.path)?.games?.toLong() else null) + } + } + } + } + // A database's name as on the list (it may have been renamed), else its file's. + fun nameOf(path: String): String { + val file = File(path).name + return entries.firstOrNull { it.source == Source.Online && it.location == file }?.name ?: file.removeSuffix(".pgn") + } + + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } }, + title = { Text(stringResource(R.string.online_title)) }, + ) + }, + ) { padding -> + Column( + Modifier + .fillMaxSize() + .padding(padding) + .imePadding() + .verticalScroll(rememberScrollState()) + .navigationBarsPadding() + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + Text(stringResource(R.string.online_intro), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.height(16.dp)) + NickField( + value = nick, + label = stringResource(if (other == null) R.string.online_nick else R.string.online_nick_lichess), + bad = badNick(nick), + onChange = { + nick = it + search.forget() + }, + onDone = ::find, + ) + if (other == null) { + TextButton(onClick = { other = "" }, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_other)) } + } else { + Spacer(Modifier.height(8.dp)) + NickField( + value = other.orEmpty(), + label = stringResource(R.string.online_other_nick), + bad = badNick(other.orEmpty()), + onChange = { + other = it + search.forget() + }, + onDone = ::find, + ) + TextButton(onClick = { + other = null + search.forget() + }, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_same_nick)) } + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) { + if (search.searching) { + CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + Spacer(Modifier.size(12.dp)) + Text(stringResource(R.string.online_searching), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) + } + val enabled = nickOk && otherOk && !search.searching + // After a search the main button of the screen is "Download". + if (found != null && !launched) { + OutlinedButton(onClick = ::find, enabled = enabled) { Text(stringResource(R.string.online_find)) } + } else { + Button(onClick = ::find, enabled = enabled) { Text(stringResource(R.string.online_find)) } + } + } + + if (found != null && !launched) { + Spacer(Modifier.height(16.dp)) + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Spacer(Modifier.height(8.dp)) + for (site in listOf(Site.LICHESS, Site.CHESS_COM)) { + val r = found[site] ?: continue + FoundRow(site, r, site in search.chosen, onToggle = { on -> search.chosen = if (on) search.chosen + site else search.chosen - site }, onRetry = ::find) + } + if (found.values.count { it is AccountLookup.Found } > 1 && search.chosen.size > 1) { + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 64.dp) + .toggleable(value = together, role = Role.Switch, onValueChange = { together = it }), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.online_merge), style = MaterialTheme.typography.bodyLarge) + Text(stringResource(R.string.online_merge_hint), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Switch(checked = together, onCheckedChange = null) + } + } + for ((path, games) in targets) { + val name = nameOf(path) + Text( + if (games != null) { + stringResource(R.string.online_into_existing, name, gamesText(games)) + } else { + stringResource(R.string.online_into_new, name) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(vertical = 4.dp), + ) + } + if (accounts.isNotEmpty()) { + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.End) { + Button(onClick = { + val groups = onlineTargets(downloads.dir.path, accounts, merge) + started = groups.map { downloads.start(it.accounts, it.path).id } + launched = true + }) { Text(stringResource(R.string.online_download)) } + } + } + } + + // The downloads started here: how they go, then how they went. + for (id in started) { + val v = views[id] ?: continue + Spacer(Modifier.height(16.dp)) + DownloadCard( + name = entries.firstOrNull { it.id == id }?.name ?: v.accounts.joinToString(" + ") { it.username }, + view = v, + onStop = { downloads.cancel(id) }, + onOpen = if (!v.state.running && (v.state.total ?: 0UL) > 0UL && entries.any { it.id == id }) ({ onOpen(id) }) else null, + ) + } + } + } +} + +@Composable +private fun NickField(value: String, label: String, bad: Boolean, onChange: (String) -> Unit, onDone: () -> Unit) { + OutlinedTextField( + value = value, + onValueChange = onChange, + label = { Text(label) }, + placeholder = { Text(stringResource(R.string.online_nick_hint)) }, + singleLine = true, + isError = bad, + supportingText = if (bad) ({ Text(stringResource(R.string.online_nick_rule)) }) else null, + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Ascii, + imeAction = ImeAction.Search, + ), + keyboardActions = KeyboardActions(onSearch = { onDone() }), + modifier = Modifier.fillMaxWidth(), + ) +} + +/// What one site gave for the nickname: the account to tick, "no such player", or why it +/// did not answer. +@Composable +private fun FoundRow(site: Site, r: AccountLookup, checked: Boolean, onToggle: (Boolean) -> Unit, onRetry: () -> Unit) { + when (r) { + is AccountLookup.Found -> { + val a = r.account + val lichess = a.games?.toLong() + val detail = when { + lichess != null -> { + val upTo = pluralStringResource(R.plurals.games_up_to, lichess.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(), groupDigits(lichess.toInt())) + val secs = lichessSeconds(lichess) + if (secs < 60) { + stringResource(R.string.online_lichess_quick, upTo) + } else { + stringResource(R.string.online_lichess_found, upTo, ceil(secs / 60.0).toInt()) + } + } + a.months != null -> stringResource(R.string.online_chesscom_found, a.months!!.toInt()) + else -> "" + } + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 64.dp) + .toggleable(value = checked, role = Role.Checkbox, onValueChange = onToggle), + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox(checked = checked, onCheckedChange = null) + Column(Modifier.weight(1f).padding(start = 12.dp)) { + Text("${siteName(site)} · ${a.username}", style = MaterialTheme.typography.bodyLarge) + if (detail.isNotEmpty()) { + Text(detail, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } + } + AccountLookup.NotFound -> Text( + stringResource(R.string.online_not_found, siteName(site)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.heightIn(min = 48.dp).padding(start = 36.dp, top = 12.dp), + ) + is AccountLookup.Failed -> Column(Modifier.padding(start = 36.dp, top = 8.dp)) { + Text(onlineProblemText(r.failure), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error) + TextButton(onClick = onRetry, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_try_again)) } + } + } +} + +/// A download started on this screen: its progress and Stop, then its result and Open. +@Composable +private fun DownloadCard(name: String, view: DownloadView, onStop: () -> Unit, onOpen: (() -> Unit)?) { + val s = view.state + Column(Modifier.fillMaxWidth()) { + Text(name, style = MaterialTheme.typography.titleMedium, modifier = Modifier.semantics { heading() }) + Spacer(Modifier.height(4.dp)) + if (s.running) { + // Not a live region: it changes a few times a second (TalkBack would not stop). + Text(downloadProgressText(view), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.height(8.dp)) + val share = downloadShare(view) + if (share != null) { + LinearProgressIndicator(progress = { share }, modifier = Modifier.fillMaxWidth()) + } else { + LinearProgressIndicator(Modifier.fillMaxWidth()) + } + Spacer(Modifier.height(8.dp)) + Text(stringResource(R.string.online_leave), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + OutlinedButton(onClick = onStop, modifier = Modifier.padding(top = 8.dp)) { Text(stringResource(R.string.online_stop)) } + } + } else { + Text( + downloadResultText(view), + style = MaterialTheme.typography.bodyMedium, + color = if (s.failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + ) + if (onOpen != null) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button(onClick = onOpen, modifier = Modifier.padding(top = 8.dp)) { Text(stringResource(R.string.online_open)) } + } + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt new file mode 100644 index 0000000..21a8267 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt @@ -0,0 +1,340 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.layout.wrapContentHeight + +import androidx.compose.foundation.layout.heightIn + +import androidx.compose.foundation.clickable + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.Undo +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Flag +import androidx.compose.material.icons.rounded.Handshake +import androidx.compose.material.icons.rounded.PlayArrow +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.Button +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Alignment +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.scale +import androidx.compose.ui.res.stringResource +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.Opponent +import io.github.vrubelroman.chesspenguin.data.PlayMeta +import uniffi.mobile_api.GameData +import uniffi.mobile_api.GameEnding +import uniffi.mobile_api.MaiaPlayer +import uniffi.mobile_api.ResignJudge +import uniffi.mobile_api.Rival +import uniffi.mobile_api.RodentPlayer + +/// The key of the game against the computer in hand (a game screen without a database). +const val PLAY_GAME = "play" + +/// How a game against the computer ended: the result and what the strip says. +data class PlayOver(val result: String, val heading: Int, val detail: Int?) + +/// The opponent of a game for the core. +fun PlayMeta.rivalOf(): Rival = when (rival) { + Opponent.Maia -> Rival.Maia + Opponent.Rodent -> Rival.Rodent(style) +} + +/// «Maia 1500», «Rodent IV 1800» (android-rodent.md §6.1): the title, the card, the question. +fun PlayMeta.label(): String = uniffi.mobile_api.rivalLabel(rivalOf(), strength.toUInt()) + +/// A character's name in the app's language (the English one, should the app not know it). +@Composable +fun styleTitle(id: String): String = + RODENT_TEXTS[id]?.let { stringResource(it.first) } + ?: uniffi.mobile_api.rodentStyles().firstOrNull { it.id == id }?.title ?: id + +/// Rodent's character after its name (none for Maia): «Таль». +@Composable +fun PlayMeta.styleShown(): String? = if (rival == Opponent.Rodent) styleTitle(style) else null + +/// A text of either opponent: Maia's, or Rodent's (their own sentences: in Russian and +/// other languages the words agree with her or him, rodent-opponent.md §7). +fun PlayMeta.said(maia: Int, rodent: Int): Int = if (rival == Opponent.Rodent) rodent else maia + +/// Why the opponent does not play: it did not start (`detail`: the words of the error), +/// or it stopped during the game (Rodent's process gone, android-rodent.md §6.6). +data class PlayFailure(val detail: String, val stopped: Boolean = false) + +/// A game against the computer being played (android-play.md §31), kept while the phone +/// turns: Maia (her network) or Rodent IV (its process). +class PlayRun(val meta: PlayMeta) { + var player: MaiaPlayer? = null + var rodent: RodentPlayer? = null + var judge: ResignJudge? = null + val thinking = mutableStateOf(false) + /// The opponent offers to resign (its position hopeless two turns in a row). + val offer = mutableStateOf(false) + val over = mutableStateOf(null) + /// The opponent does not play: why. + val failure = mutableStateOf(null) + /// «Play to the end»: no more offers in this game. + var playOn = false + var hopeless = 0u + /// Bumped by a take-back: the answer for the old position is dropped. + var generation = 0 + + fun close() { + player?.close() + rodent?.close() + judge?.close() + player = null + rodent = null + judge = null + } +} + +/// The last node of the main line. +fun lineEnd(g: GameData): Int { + var n = 0 + while (true) n = g.nodes[n].children.firstOrNull()?.toInt() ?: return n +} + +/// Half-moves from the start to node `id`. +fun depth(g: GameData, id: Int): Int { + var d = 0 + var n = g.nodes.getOrNull(id) ?: return 0 + while (true) { + n = g.nodes.getOrNull(n.parent?.toInt() ?: return d) ?: return d + d++ + } +} + +fun whiteToMove(fen: String) = fen.substringAfter(' ').startsWith("w") + +/// The end of a game by the rules, from the user's side. +fun overBy(ending: GameEnding, userWhite: Boolean): PlayOver = when (ending) { + is GameEnding.Checkmate -> PlayOver( + if (ending.whiteWon) "1-0" else "0-1", + if (ending.whiteWon == userWhite) R.string.play_won else R.string.play_lost, + R.string.end_mate, + ) + GameEnding.Stalemate -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_stalemate) + GameEnding.InsufficientMaterial -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_material) + GameEnding.Threefold -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_threefold) + GameEnding.FiftyMoves -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_fifty) +} + +/// The bottom bar during a game (§31.3): take back, resign (abort before the first +/// moves), flip, a move back and forward. +@Composable +fun PlayControls( + canTakeBack: Boolean, + started: Boolean, + canBack: Boolean, + canForward: Boolean, + onTakeBack: () -> Unit, + onResign: () -> Unit, + onDraw: () -> Unit, + onAbort: () -> Unit, + onFlip: () -> Unit, + onBack: () -> Unit, + onForward: () -> Unit, +) { + Column { + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp), verticalAlignment = Alignment.CenterVertically) { + LabeledButton(Icons.AutoMirrored.Rounded.Undo, stringResource(R.string.play_take_back).removePrefix("↶ "), canTakeBack, Modifier.weight(1f), onTakeBack) + if (started) { + LabeledButton(Icons.Rounded.Flag, stringResource(R.string.play_resign).removePrefix("⚑ "), true, Modifier.weight(1f), onResign) + LabeledButton(Icons.Rounded.Handshake, stringResource(R.string.play_offer_draw), true, Modifier.weight(1f), onDraw) + } else { + LabeledButton(Icons.Rounded.Close, stringResource(R.string.play_abort), true, Modifier.weight(1f), onAbort) + } + IconButton(onClick = onFlip, modifier = Modifier.weight(0.8f)) { Icon(Icons.Rounded.SwapVert, stringResource(R.string.flip)) } + IconButton(onClick = onBack, enabled = canBack, modifier = Modifier.weight(1f)) { + // The forward arrow turned round, as the game screen's. + Icon(Icons.Rounded.PlayArrow, stringResource(R.string.move_back), Modifier.scale(-1f, 1f)) + } + IconButton(onClick = onForward, enabled = canForward, modifier = Modifier.weight(1f)) { Icon(Icons.Rounded.PlayArrow, stringResource(R.string.move_forward)) } + } + } + } +} + +@Composable +private fun LabeledButton(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, enabled: Boolean, modifier: Modifier, onClick: () -> Unit) { + androidx.compose.material3.TextButton(onClick = onClick, enabled = enabled, modifier = modifier.height(64.dp), contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 2.dp)) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon(icon, null) + // Six buttons in a row: a long word goes to a second line, not cut. + Text(label, style = MaterialTheme.typography.labelSmall, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = androidx.compose.ui.text.style.TextAlign.Center) + } + } +} + +/// The opponent offers to resign (§31.3): accept the win, or play on. +@Composable +fun OfferCard(meta: PlayMeta, onAccept: () -> Unit, onPlayOn: () -> Unit) { + Card { + Text(stringResource(meta.said(R.string.play_maia_resigns, R.string.rodent_resigns)), style = MaterialTheme.typography.titleMedium) + Text(stringResource(meta.said(R.string.play_her_position_lost, R.string.rodent_position_lost)), style = MaterialTheme.typography.bodyMedium) + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = onAccept, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_accept_win)) } + OutlinedButton(onClick = onPlayOn, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_on_short)) } + } + } +} + +/// The end of the game (§31.4): the result, then analyse, rematch, save. +@Composable +fun ResultCard( + over: PlayOver, + saved: Boolean, + recorded: io.github.vrubelroman.chesspenguin.data.Written?, + recordError: String?, + onOpenRecorded: (String) -> Unit, + onAnalyse: () -> Unit, + onRematch: () -> Unit, + onSave: () -> Unit, + onClose: () -> Unit, +) { + Card { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + (if (over.result == "1/2-1/2") "½-½" else over.result) + " · " + stringResource(over.heading) + (over.detail?.let { " · " + stringResource(it) } ?: ""), + Modifier.weight(1f), + style = MaterialTheme.typography.titleMedium, + ) + IconButton(onClick = onClose) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } + } + // Where the game went by itself: its player's database, opened by a tap. + // A new database says so here, once (no snackbar over the buttons). + recorded?.let { w -> + Text( + stringResource(if (w.created) R.string.player_written_new else R.string.player_written, w.name, (w.index + 1u).toString()), + Modifier.fillMaxWidth().heightIn(min = 40.dp).clickable { onOpenRecorded(w.id) }.wrapContentHeight(Alignment.CenterVertically), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.primary, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + recordError?.let { + Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, maxLines = 3) + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + val pad = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp) + Button(onClick = onAnalyse, modifier = Modifier.weight(1f), contentPadding = pad) { Text(stringResource(R.string.play_analyse_short), maxLines = 1, overflow = TextOverflow.Ellipsis) } + OutlinedButton(onClick = onRematch, modifier = Modifier.weight(1f), contentPadding = pad) { + Text(stringResource(R.string.play_rematch).removePrefix("↻ "), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + // Written by itself: the line above says where; no third button. + if (recorded == null) { + OutlinedButton(onClick = onSave, enabled = !saved, modifier = Modifier.weight(1f), contentPadding = pad) { + Text(stringResource(if (saved) R.string.play_saved else R.string.play_save), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + } +} + +@Composable +private fun Card(content: @Composable () -> Unit) { + Column( + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp) + .background(MaterialTheme.colorScheme.surfaceContainerHigh, RoundedCornerShape(12.dp)) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { content() } +} + +/// Puts a new game against the computer in hand (android-play.md §31): `session` holds +/// its moves so far (none, or those of the game it goes on from: `meta.floor` +/// half-moves); its tags are set, and after the moves of another game a note says where +/// it comes from. +fun beginComputerGame( + app: io.github.vrubelroman.chesspenguin.ChessPenguinApp, + session: uniffi.mobile_api.GameSession, + meta: PlayMeta, + event: String, + note: String?, +) { + val date = java.text.SimpleDateFormat("yyyy.MM.dd", java.util.Locale.ROOT).format(java.util.Date()) + val tags = uniffi.mobile_api.computerGameTags(event, meta.userWhite, meta.name, meta.rivalOf(), meta.strength.toUInt()) + + uniffi.mobile_api.Tag("Date", date) + session.setData(tags, "*") + if (meta.floor > 0 && note != null) { + val data = session.data() + runCatching { session.addComment(lineEnd(data).toUInt(), note) } + } + session.markSaved() + // The game it replaces, if left unfinished, is kept in its player's database. + app.playerGames.keepUnfinished(app.maiaGames, app.settings.prefs.value.recordGames, app.scope) + app.playerGames.remember(meta.name) + app.maiaGames.begin(session.pgn(), meta) +} + +/// The note in a game played on from another one: «From here on, a game against Maia +/// 1500.», «… Rodent IV 1800 · Tal.» (in the app's language). +fun playNote(resources: android.content.res.Resources, meta: PlayMeta, style: String?): String = + if (meta.rival == Opponent.Rodent && style != null) { + resources.getString(R.string.play_note_from_rodent, meta.strength.toString(), style) + } else { + resources.getString(R.string.play_note_from, meta.strength.toString()) + } + +/// The opponent did not start (§31.3, android-rodent.md §6.6): Maia's file again, or +/// Rodent started again (it is in the APK: nothing to download); or leave the game. +@Composable +fun FailureCard(meta: PlayMeta, failure: PlayFailure, onRetry: () -> Unit, onAbort: () -> Unit) { + val text = when { + meta.rival != Opponent.Rodent -> R.string.play_maia_stopped + failure.stopped -> R.string.rodent_stopped_playing + else -> R.string.rodent_stopped + } + Card { + Text(stringResource(text), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.error) + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = onRetry, modifier = Modifier.weight(1f)) { + Text(stringResource(meta.said(R.string.play_maia_reload, R.string.rodent_restart)), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + OutlinedButton(onClick = onAbort, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_abort), maxLines = 1) } + } + } +} + +/// A new game while one is put aside (§31.7): go on with that one, or begin anew (it is +/// replaced). +@Composable +fun AdjournedQuestion(meta: PlayMeta, onContinue: () -> Unit, onNew: () -> Unit, onDismiss: () -> Unit) { + val app = app() + // Said only when the game will be kept (moves of both sides, writing on). + val kept = remember { app.playerGames.wouldKeep(app.maiaGames, app.settings.prefs.value.recordGames) } + androidx.compose.material3.AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.play_adjourned_q, meta.label())) }, + text = { Text(stringResource(if (kept) R.string.play_adjourned_new_text else R.string.play_adjourned_replaced)) }, + confirmButton = { androidx.compose.material3.TextButton(onClick = onContinue) { Text(stringResource(R.string.play_continue_it)) } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = onNew) { Text(stringResource(R.string.play_start_new)) } }, + ) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt new file mode 100644 index 0000000..6ae4900 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt @@ -0,0 +1,620 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.ExperimentalFoundationApi +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.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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +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.Check +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Person +import androidx.compose.material3.Button +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +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.OutlinedCard +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.material3.ScaffoldDefaults +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.ui.draw.clip +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +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.heading +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.NetProblem +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.data.Opponent +import io.github.vrubelroman.chesspenguin.data.PlayMeta +import io.github.vrubelroman.chesspenguin.theme.Tabular +import uniffi.mobile_api.RodentStyle +import uniffi.mobile_api.maiaRange +import uniffi.mobile_api.rodentRange +import uniffi.mobile_api.rodentStyles + +/// The position a game against the computer starts from (android-play.md §31.6): drawn +/// small, with where it comes from; the side to move plays by default. +data class PlayFrom(val fen: String, val label: String, val whiteToMove: Boolean) + +/// What the sheet starts: the opponent (Rodent in `style`), its strength, the user's +/// colour and name. +data class PlayChoice(val rival: Opponent, val strength: Int, val style: String, val userWhite: Boolean, val name: String) { + /// The game's description; `floor`: the half-moves it goes on from. + fun meta(floor: Int) = PlayMeta(strength, userWhite, name, floor, rival = rival, style = if (rival == Opponent.Rodent) style else "") +} + +/// «Play against the computer» (android-play.md §31.1, android-rodent.md §2): the +/// opponent — Maia or Rodent IV with its character — its strength on its own scale, the +/// colour, the name. What the opponent needs is downloaded here the first time (Maia's +/// file; Rodent's opening books, or «Without book»). The state line and the button stay +/// at the bottom; the rest scrolls. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun PlaySheet(from: PlayFrom?, onPlay: (PlayChoice) -> Unit, onDismiss: () -> Unit) { + val app = app() + val prefs by app.settings.prefs.collectAsState() + val maiaFiles = app.maiaFiles.download + val maiaState by maiaFiles.state.collectAsState() + val books = app.rodentFiles.books + val booksState by books.state.collectAsState() + val styles = remember { rodentStyles() } + var rival by remember { mutableStateOf(prefs.opponent) } + val rodent = rival == Opponent.Rodent + // Each opponent's strength on its own scale, remembered apart (§4). + val maiaRange = remember { maiaRange().map { it.toInt() } } + val rodentRange = remember { rodentRange().map { it.toInt() } } + var maiaLevel by remember { mutableFloatStateOf(prefs.maiaStrength.coerceIn(maiaRange[0], maiaRange[1]).toFloat()) } + var rodentLevel by remember { mutableFloatStateOf(prefs.rodentStrength.coerceIn(rodentRange[0], rodentRange[1]).toFloat()) } + // The character: kept at once when chosen (§7.1); an unknown one is Tal. + val style = prefs.rodentPersonality.takeIf { id -> styles.any { it.id == id } } ?: DEFAULT_RODENT_STYLE + var picking by remember { mutableStateOf(false) } + // From a position: the side to move by default, not remembered (play-from-position.md §2). + var color by remember { mutableIntStateOf(if (from != null) (if (from.whiteToMove) 1 else -1) else prefs.playColor) } + var name by remember { mutableStateOf(prefs.yourName) } + // «Download and play»: the game starts once the files are checked, if this opponent + // is still the one chosen. + var playAfter by remember { mutableStateOf(false) } + val range = if (rodent) rodentRange else maiaRange + val strength = if (rodent) rodentLevel else maiaLevel + val level = (strength / 50f).toInt() * 50 + // From a position Rodent needs no book (§1.5); Maia always needs her file. + val state = if (rodent) booksState else maiaState + // From a position Rodent plays at once, whatever its books (§1.5, question 4). + val noBookNeeded = rodent && from != null + val ready = state == NetState.Ready || noBookNeeded + fun play() { + val white = when (color) { + 1 -> true + -1 -> false + else -> kotlin.random.Random.nextBoolean() + } + app.settings.update { p -> + val q = p.copy(opponent = rival, yourName = name.trim(), playColor = if (from != null) p.playColor else color) + if (rodent) q.copy(rodentStrength = level) else q.copy(maiaStrength = level) + } + onPlay(PlayChoice(rival, level, style, white, name.trim())) + } + // A failure of an earlier attempt is not this sheet's: the download is offered anew. + LaunchedEffect(Unit) { books.forgetFailure() } + LaunchedEffect(state, rival) { + if (playAfter && state == NetState.Ready) { + playAfter = false + play() + } + } + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + val scroll = rememberScrollState() + Column(Modifier.fillMaxWidth()) { + Column(Modifier.weight(1f, fill = false).verticalScroll(scroll).padding(horizontal = 24.dp)) { + Text(stringResource(R.string.play_title), style = MaterialTheme.typography.titleLarge) + if (from != null) { + Row(Modifier.padding(top = 12.dp), verticalAlignment = Alignment.CenterVertically) { + MiniBoard(from.fen, flipped = color == -1, size = 96.dp) + Text(from.label, Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 4, overflow = TextOverflow.Ellipsis) + } + } + Spacer(Modifier.height(16.dp)) + // Who first, then how strong: the scale is the opponent's (§2.1). + Row(Modifier.fillMaxWidth().selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OpponentCard("Maia", stringResource(R.string.opp_maia_sub), !rodent, Modifier.weight(1f)) { + if (rodent) playAfter = false + rival = Opponent.Maia + } + OpponentCard("Rodent IV", stringResource(R.string.opp_rodent_sub), rodent, Modifier.weight(1f)) { + if (!rodent) playAfter = false + rival = Opponent.Rodent + // The first time, the list opens by itself with Tal suggested (§3.4). + if (prefs.rodentPersonality.isEmpty()) picking = true + } + } + Spacer(Modifier.height(8.dp)) + CharacterRow(if (rodent) styles.firstOrNull { it.id == style } else null) { picking = true } + Spacer(Modifier.height(8.dp)) + Text( + stringResource(R.string.strength_n, level.toString()), + style = MaterialTheme.typography.titleMedium.merge(Tabular), + fontWeight = FontWeight.Medium, + ) + val strengthLabel = stringResource(R.string.strength) + val strengthState = stringResource(R.string.strength_range, level.toString(), range[0].toString(), range[1].toString()) + Row(verticalAlignment = Alignment.CenterVertically) { + Text("${range[0]}", style = MaterialTheme.typography.bodySmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) + Slider( + value = strength, + onValueChange = { if (rodent) rodentLevel = it else maiaLevel = it }, + valueRange = range[0].toFloat()..range[1].toFloat(), + modifier = Modifier.weight(1f).padding(horizontal = 8.dp).semantics { + contentDescription = strengthLabel + stateDescription = strengthState + }, + ) + Text("${range[1]}", style = MaterialTheme.typography.bodySmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + // Always two lines: the sheet does not jump when the opponent changes. It + // changes only with the opponent: TalkBack says it then, not at each step of + // the slider. + Text( + stringResource(if (rodent) R.string.rodent_measured else R.string.play_measured), + Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + minLines = 2, + ) + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.play_colour), style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(8.dp)) + val options = listOf(1 to R.string.color_white, 0 to R.string.color_random, -1 to R.string.color_black) + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { + options.forEachIndexed { i, (v, label) -> + SegmentedButton(selected = color == v, onClick = { color = v }, shape = SegmentedButtonDefaults.itemShape(i, options.size)) { + Text(stringResource(label)) + } + } + } + Spacer(Modifier.height(12.dp)) + NameField(name, prefs.recordGames) { name = it } + Spacer(Modifier.height(12.dp)) + } + // The footer: what the chosen opponent needs, and the button (§2.4). A line + // over it while the content goes on under it. + HorizontalDivider(color = if (scroll.canScrollForward) MaterialTheme.colorScheme.outlineVariant else Color.Transparent) + Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 8.dp, bottom = 24.dp)) { + // At least 40 dp (it grows with a large font). Only the lines that change with + // the kind of state are read out, not every step of the progress. + Row(Modifier.fillMaxWidth().heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) { + val noBookText = stringResource(R.string.books_without_cd) + val noBook = @Composable { + TextButton(onClick = { + playAfter = false + play() + }, modifier = Modifier.heightIn(min = 48.dp).semantics { contentDescription = noBookText }) { + Text(stringResource(R.string.books_without), maxLines = 1) + } + } + // What is left to download (the books checked so far stay). + val booksLeft = remember(booksState) { books.remaining() } + val left = if (rodent) booksLeft else maiaFiles.size + when (val s = state) { + NetState.Ready -> StateText(stringResource(if (rodent) R.string.books_ready else R.string.play_maia_ready)) + NetState.Missing -> if (noBookNeeded) { + StateText(stringResource(R.string.books_not_needed)) + } else if (rodent) { + StateText(stringResource(R.string.books_offer, megabytes(left)), Modifier.weight(1f)) + noBook() + } else { + StateText(stringResource(R.string.play_download_note, megabytes(left))) + } + is NetState.Loading -> { + val what = stringResource(R.string.online_downloading, if (rodent) stringResource(R.string.books_notification) else "Maia") + Column( + Modifier.weight(1f).clearAndSetSemantics { + contentDescription = what + progressBarRangeInfo = ProgressBarRangeInfo(s.done.toFloat() / s.total.coerceAtLeast(1), 0f..1f) + }, + ) { + LinearProgressIndicator(progress = { s.done.toFloat() / s.total.coerceAtLeast(1) }, modifier = Modifier.fillMaxWidth()) + Text(stringResource(R.string.downloaded_of, megabytes(s.done), megabytes(s.total)), style = MaterialTheme.typography.bodySmall.merge(Tabular)) + } + IconButton(onClick = { + playAfter = false + if (rodent) books.cancel() else maiaFiles.cancel() + }) { Icon(Icons.Rounded.Close, stringResource(R.string.cancel_download)) } + } + // From a position a failed download does not matter to Rodent. + is NetState.Failed -> if (noBookNeeded) { + StateText(stringResource(R.string.books_not_needed)) + } else { + Text( + when (s.problem) { + NetProblem.NoInternet -> stringResource(R.string.no_internet) + NetProblem.Interrupted -> stringResource(R.string.interrupted) + NetProblem.NoSpace -> stringResource(R.string.no_space, megabytes(left)) + NetProblem.Corrupt -> stringResource(R.string.corrupt) + }, + Modifier.weight(1f).semantics { liveRegion = LiveRegionMode.Polite }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + // Rodent plays without its books (§5.5); from a position it needs none. + if (rodent) noBook() + } + } + } + Spacer(Modifier.height(8.dp)) + val loading = state is NetState.Loading + Button( + onClick = { + if (ready) { + play() + } else { + playAfter = true + if (rodent) books.download() else maiaFiles.download() + } + }, + enabled = !loading || noBookNeeded, + modifier = Modifier.fillMaxWidth().height(56.dp), + ) { + Text( + stringResource( + when { + ready || loading -> R.string.play_play + state is NetState.Failed -> R.string.play_retry + else -> R.string.play_download_and_play + }, + ), + ) + } + } + } + } + if (picking) { + // Closed without a choice the first time: Tal stays, and the list does not open + // by itself again (§3.4). + StylePicker(styles, style, onPick = { id -> + picking = false + app.settings.update { it.copy(rodentPersonality = id) } + }, onDismiss = { + picking = false + if (prefs.rodentPersonality.isEmpty()) app.settings.update { it.copy(rodentPersonality = style) } + }) + } +} + +@Composable +private fun StateText(text: String, modifier: Modifier = Modifier) { + // Not cut: with a large font the footer grows (§8.2). + Text(text, modifier.semantics { liveRegion = LiveRegionMode.Polite }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) +} + +/// One of the two opponents (§2.2): chosen, it is filled and ticked (not by colour alone). +@Composable +private fun OpponentCard(title: String, sub: String, selected: Boolean, modifier: Modifier, onClick: () -> Unit) { + OutlinedCard( + modifier = modifier.heightIn(min = 64.dp).selectable(selected = selected, role = Role.RadioButton, onClick = onClick), + shape = RoundedCornerShape(12.dp), + colors = CardDefaults.outlinedCardColors( + containerColor = if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surface, + ), + border = BorderStroke(if (selected) 2.dp else 1.dp, if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant), + ) { + Column(Modifier.padding(12.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (selected) { + Icon(Icons.Rounded.Check, null, Modifier.size(18.dp), tint = MaterialTheme.colorScheme.primary) + Spacer(Modifier.width(4.dp)) + } + Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Medium, maxLines = 1) + } + Text(sub, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } +} + +/// The character's line (§2.3): Rodent's character, a tap opens the list; for Maia the +/// same line, inactive («Like a human»), so that the sheet keeps its height. +@Composable +private fun CharacterRow(style: RodentStyle?, onClick: () -> Unit) { + val title = style?.let { styleTitle(it.id) } ?: stringResource(R.string.like_human) + val about = style?.let { s -> RODENT_TEXTS[s.id]?.let { stringResource(it.second) } ?: s.about } ?: stringResource(R.string.maia_no_style) + val active = style != null + val described = if (active) stringResource(R.string.character_cd, title) + ". " + about else "$title. $about" + val change = stringResource(R.string.pick_change) + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 80.dp) + .background(MaterialTheme.colorScheme.surfaceContainerHigh, RoundedCornerShape(12.dp)) + .then(if (active) Modifier.clickable(onClickLabel = change, role = Role.Button, onClick = onClick) else Modifier) + .clearAndSetSemantics { contentDescription = described } + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + val dim = if (active) 1f else 0.38f + if (style != null) { + Initial(title, style.player) + } else { + Box(Modifier.size(40.dp).background(MaterialTheme.colorScheme.surfaceContainerHighest, CircleShape), contentAlignment = Alignment.Center) { + Icon(Icons.Rounded.Person, null, Modifier.size(24.dp), tint = MaterialTheme.colorScheme.onSurface.copy(alpha = dim)) + } + } + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface.copy(alpha = dim), maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(about, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = dim), minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + if (active) Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +/// A character's initial in a circle (§3.2): the players in one colour, the characters +/// in another. Decoration: not read out. +@Composable +private fun Initial(title: String, player: Boolean) { + val (back, fore) = if (player) { + MaterialTheme.colorScheme.tertiaryContainer to MaterialTheme.colorScheme.onTertiaryContainer + } else { + MaterialTheme.colorScheme.secondaryContainer to MaterialTheme.colorScheme.onSecondaryContainer + } + Box(Modifier.size(40.dp).background(back, CircleShape), contentAlignment = Alignment.Center) { + Text(title.take(1), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium, color = fore) + } +} + +/// «Who to play» (§3): Rodent IV's characters in two groups, each in the alphabet of the +/// app's language; a tap chooses and closes. Full screen on a phone, a dialog on a tablet. +@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) +@Composable +private fun StylePicker(styles: List, selected: String, onPick: (String) -> Unit, onDismiss: () -> Unit) { + val wide = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.width.toDp() } >= 600.dp + val locale = LocalConfiguration.current.locales[0] + val titled = styles.map { it to styleTitle(it.id) } + val collator = remember(locale) { java.text.Collator.getInstance(locale) } + val groups = listOf(R.string.pick_players to true, R.string.pick_characters to false).map { (heading, player) -> + heading to titled.filter { it.first.player == player }.sortedWith { a, b -> collator.compare(a.second, b.second) } + } + // Opened with the chosen one in sight: the row above it just under the group's heading + // (which stays on top of the list), so that neither is cut. + val index = run { + var i = 0 + for ((_, rows) in groups) { + i++ // the group's heading + val at = rows.indexOfFirst { it.first.id == selected } + if (at >= 0) return@run i + at + i += rows.size + } + 0 + } + val list = rememberLazyListState() + val headerPx = with(LocalDensity.current) { 48.dp.roundToPx() } + LaunchedEffect(Unit) { + // A negative offset: the row above starts below the sticky heading. + if (index >= 2) list.scrollToItem(index - 1, -headerPx) + } + // Full screen: edge to edge, the bars' insets inside. A dialog: in the window between + // the system bars, clipped to its corners, no insets of its own. + Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = wide)) { + val frame = if (wide) { + Modifier.widthIn(max = 560.dp).fillMaxWidth().fillMaxHeight(0.9f).clip(RoundedCornerShape(28.dp)) + } else { + Modifier.fillMaxSize() + } + val insets = if (wide) WindowInsets(0) else ScaffoldDefaults.contentWindowInsets + Scaffold( + modifier = frame, + containerColor = MaterialTheme.colorScheme.surface, + contentWindowInsets = insets, + topBar = { + Column { + TopAppBar( + windowInsets = if (wide) WindowInsets(0) else TopAppBarDefaults.windowInsets, + navigationIcon = { IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } }, + title = { Text(stringResource(R.string.pick_title)) }, + ) + // Fixed under the bar: what the list is for, wherever it is scrolled. + Text( + stringResource(R.string.pick_intro), + Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + }, + ) { padding -> + LazyColumn(Modifier.fillMaxSize().padding(padding), state = list) { + groups.forEach { (heading, rows) -> + stickyHeader(key = heading) { + Surface(color = MaterialTheme.colorScheme.surface) { + Text( + stringResource(heading), + Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 14.dp).semantics { heading() }, + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.primary, + ) + } + } + items(rows, key = { it.first.id }) { (st, title) -> + val on = st.id == selected + val about = RODENT_TEXTS[st.id]?.let { stringResource(it.second) } ?: st.about + val described = stringResource(if (st.player) R.string.pick_player_cd else R.string.pick_character_cd, title) + ". " + about + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 72.dp) + .background(if (on) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent) + .selectable(selected = on, role = Role.RadioButton) { onPick(st.id) } + // One reading: the name, the group, what it does; not the texts again. + .clearAndSetSemantics { + contentDescription = described + this.selected = on + role = Role.RadioButton + onClick { onPick(st.id); true } + } + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Initial(title, st.player) + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge) + Text(about, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (on) Icon(Icons.Rounded.Check, null, Modifier.padding(start = 8.dp), tint = MaterialTheme.colorScheme.primary) + } + } + } + } + } + } +} + +/// The name, with the players of this phone to pick from; under it, where the games go +/// (player-games.md §6). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun NameField(name: String, record: Boolean, onName: (String) -> Unit) { + val app = app() + val players = remember { app.playerGames.players() } + var picking by remember { mutableStateOf(false) } + val line = if (!record) { + stringResource(R.string.player_line_off) + } else { + val db = app.playerGames.database(name) + when { + app.playerGames.tidy(name).isEmpty() -> stringResource(R.string.player_line_noname, db?.name ?: app.playerGames.dbName("")) + db != null -> stringResource(R.string.player_line_existing, db.name) + " · " + + androidx.compose.ui.res.pluralStringResource(R.plurals.games_count, db.games ?: 0, groupDigits(db.games ?: 0)) + else -> stringResource(R.string.player_line_new, app.playerGames.dbName(name)) + } + } + // The players whose names begin with what is typed (none once it is one of them). + val typed = app.playerGames.tidy(name).lowercase() + val matching = players.filter { it.lowercase().startsWith(typed) && it.lowercase() != typed } + // Opened by typing or by its arrow, not by a tap in the field (it would cover «Play»). + ExposedDropdownMenuBox(expanded = picking && matching.isNotEmpty(), onExpandedChange = { if (!it) picking = false }) { + OutlinedTextField( + name, + { + onName(it) + picking = it.isNotBlank() + }, + Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable), + label = { Text(stringResource(R.string.play_your_name)) }, + supportingText = { Text(line) }, + trailingIcon = { + if (matching.isNotEmpty()) { + IconButton(onClick = { picking = !picking }) { ExposedDropdownMenuDefaults.TrailingIcon(expanded = picking) } + } + }, + singleLine = true, + ) + ExposedDropdownMenu(expanded = picking && matching.isNotEmpty(), onDismissRequest = { picking = false }) { + matching.forEach { p -> + DropdownMenuItem(text = { Text(p) }, onClick = { + onName(p) + picking = false + }) + } + } + } +} + +/// A small board of a position (no touches, no coordinates). +@Composable +fun MiniBoard(fen: String, flipped: Boolean, size: androidx.compose.ui.unit.Dp) { + val app = app() + val prefs by app.settings.prefs.collectAsState() + val context = androidx.compose.ui.platform.LocalContext.current + val pieces = remember { Pieces(context) } + Board( + fen = fen, + flipped = flipped, + lastFrom = null, + lastTo = null, + pieces = pieces, + theme = prefs.board, + set = prefs.pieces, + description = "", + animated = false, + modifier = Modifier.width(size), + coordinates = false, + ) +} + +private fun megabytes(bytes: Long) = ((bytes + 999_999) / 1_000_000).toInt() diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayersScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayersScreen.kt new file mode 100644 index 0000000..a5b1749 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayersScreen.kt @@ -0,0 +1,444 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Search +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.disabled +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.PrepBackends +import io.github.vrubelroman.chesspenguin.theme.Tabular +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import uniffi.mobile_api.Database +import java.text.Collator +import java.util.Locale + +private const val PLAYER_PAGE = 100 + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun PlayersScreen( + db: String, + onBack: () -> Unit, + onPrepare: (player: PlayerSummary, white: Boolean) -> Unit, +) { + val app = app() + val entries by app.library.entries.collectAsState() + val entry = entries.firstOrNull { it.id == db } + var database by remember { mutableStateOf(null) } + var openFailure by remember { mutableStateOf(null) } + val backend = remember(database) { database?.let(PrepBackends::open) } + DisposableEffect(backend) { onDispose { backend?.close() } } + + var searching by rememberSaveable { mutableStateOf(false) } + var query by rememberSaveable { mutableStateOf("") } + var colorChoice by remember { mutableStateOf(null) } + var players by remember { mutableStateOf?>(null) } + var nextOffset by remember { mutableStateOf(null) } + var failure by remember { mutableStateOf(null) } + var loadingMore by remember { mutableStateOf(false) } + var generation by remember { mutableIntStateOf(0) } + var retry by rememberSaveable { mutableIntStateOf(0) } + LaunchedEffect(db, entry?.games, entry?.updated, retry) { + database = null + openFailure = null + app.library.database(db).onSuccess { database = it }.onFailure { openFailure = it } + } + val list = rememberLazyListState() + val focus = remember { FocusRequester() } + val keyboard = LocalSoftwareKeyboardController.current + BackHandler(searching) { + searching = false + query = "" + } + + LaunchedEffect(backend, query, retry) { + val source = backend ?: return@LaunchedEffect + val expected = ++generation + players = null + nextOffset = null + failure = null + loadingMore = false + if (query.isNotEmpty()) delay(250) + try { + val page = withContext(Dispatchers.IO) { source.players(query, 0, PLAYER_PAGE) } + if (expected != generation) return@LaunchedEffect + players = sortPlayers(page.players) + nextOffset = page.nextOffset + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Throwable) { + if (expected == generation) failure = e + } + } + + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + title = { + if (searching) { + TextField( + value = query, + onValueChange = { query = it }, + placeholder = { Text(stringResource(R.string.player_name_hint)) }, + singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { keyboard?.hide() }), + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + ), + modifier = Modifier.fillMaxWidth().focusRequester(focus), + ) + LaunchedEffect(Unit) { focus.requestFocus() } + } else { + Column { + Text(stringResource(R.string.players), maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + entry?.let { displayName(it) } ?: "", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, + actions = { + if (searching) { + IconButton(onClick = { if (query.isEmpty()) searching = false else query = "" }) { + Icon(Icons.Rounded.Close, stringResource(R.string.clear)) + } + } else if (database != null) { + IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) } + } + }, + ) + }, + ) { padding -> + Box(Modifier.fillMaxSize().padding(padding)) { + val shownPlayers = players + when { + openFailure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(openFailure!!)) { + TextButton(onClick = { database = null; openFailure = null; retry += 1 }) { Text(stringResource(R.string.retry)) } + } + failure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(failure!!).ifEmpty { failure!!.message ?: "" }) { + TextButton(onClick = { retry += 1 }) { Text(stringResource(R.string.retry)) } + } + shownPlayers == null -> LoadingPlayers() + shownPlayers.isEmpty() && query.isEmpty() -> PrepMessage(stringResource(R.string.no_named_players), "") { + TextButton(onClick = onBack) { Text(stringResource(R.string.to_games)) } + } + shownPlayers.isEmpty() -> PrepMessage(stringResource(R.string.player_not_found), "") { + TextButton(onClick = { query = "" }) { Text(stringResource(R.string.reset_search)) } + } + else -> LazyColumn(Modifier.fillMaxSize(), state = list) { + val shown = shownPlayers + val expectedGeneration = generation + items(shown.size, key = { shown[it].id }) { index -> + val player = shown[index] + PlayerPrepRow( + player = player, + divider = index < shown.lastIndex || nextOffset != null, + onPlayerClick = { chosen -> + keyboard?.hide() + val onlyColor = solePlayerColor(chosen) + when { + playerNeedsColorChoice(chosen) -> colorChoice = chosen + onlyColor != null -> onPrepare(chosen, onlyColor) + } + }, + ) + if (index == shown.lastIndex && nextOffset != null) { + LaunchedEffect(nextOffset, generation) { + val source = backend ?: return@LaunchedEffect + val offset = nextOffset ?: return@LaunchedEffect + loadingMore = true + try { + val page = withContext(Dispatchers.IO) { source.players(query, offset, PLAYER_PAGE) } + if (expectedGeneration == generation) { + players = sortPlayers((shown + page.players).distinctBy { it.id }) + nextOffset = page.nextOffset + } + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Throwable) { + if (expectedGeneration == generation) failure = e + } finally { + if (expectedGeneration == generation) loadingMore = false + } + } + } + } + if (loadingMore) { + items(3, key = { "loading-$it" }) { PlayerPrepPlaceholder() } + } + } + } + } + } + colorChoice?.let { player -> + PlayerColorSheet( + player = player, + onDismiss = { colorChoice = null }, + onPrepare = { chosen, white -> + colorChoice = null + onPrepare(chosen, white) + }, + ) + } +} + +private fun sortPlayers(players: List): List { + val collator = Collator.getInstance(Locale.getDefault()).apply { strength = Collator.PRIMARY } + return players.sortedWith(compareBy(collator) { it.name }) +} + +internal fun playerNeedsColorChoice(player: PlayerSummary): Boolean = player.whiteGames > 0 && player.blackGames > 0 + +internal fun solePlayerColor(player: PlayerSummary): Boolean? = when { + player.whiteGames > 0 && player.blackGames == 0 -> true + player.blackGames > 0 && player.whiteGames == 0 -> false + else -> null +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun PlayerPrepRow( + player: PlayerSummary, + divider: Boolean = false, + onPlayerClick: (PlayerSummary) -> Unit, +) { + val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total)) + val whiteSide = stringResource(R.string.prep_as_white) + val blackSide = stringResource(R.string.prep_as_black) + val chooseColor = stringResource(R.string.prep_choose_color) + val prepare = stringResource(R.string.prepare_action) + val onlyColor = solePlayerColor(player) + val hasAction = playerNeedsColorChoice(player) || onlyColor != null + val action = when { + playerNeedsColorChoice(player) -> chooseColor + onlyColor == true -> "$prepare $whiteSide" + onlyColor == false -> "$prepare $blackSide" + else -> prepare + } + val description = "${player.name}, $games. $whiteSide ${groupDigits(player.whiteGames)}, $blackSide ${groupDigits(player.blackGames)}. $action" + BoxWithConstraints(Modifier.fillMaxWidth()) { + val grows = maxWidth < 320.dp || LocalDensity.current.fontScale > 1f + val height = if (grows) Modifier.heightIn(min = 72.dp) else Modifier.height(72.dp) + Box( + Modifier.fillMaxWidth().then(height) + .clearAndSetSemantics { + contentDescription = description + role = Role.Button + if (hasAction) onClick(action) { onPlayerClick(player); true } else disabled() + } + .clickable(enabled = hasAction, role = Role.Button, onClickLabel = action) { onPlayerClick(player) }, + ) { + Row( + Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Row(Modifier.fillMaxWidth().heightIn(min = 24.dp), verticalAlignment = Alignment.CenterVertically) { + PlayerName(player.name, MaterialTheme.typography.bodyLarge, Modifier.weight(1f)) + Spacer(Modifier.width(8.dp)) + Text(games, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) + } + Spacer(Modifier.height(4.dp)) + FlowRow( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + PlayerColorText(true, whiteSide, player.whiteGames) + PlayerColorText(false, blackSide, player.blackGames) + } + } + Spacer(Modifier.width(8.dp)) + Icon( + Icons.AutoMirrored.Rounded.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(24.dp), + ) + } + if (divider) HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant) + } + } +} + +@Composable +private fun PlayerColorText(white: Boolean, side: String, count: Int) { + Row(Modifier.heightIn(min = 20.dp), verticalAlignment = Alignment.CenterVertically) { + SideDisc(white) + Spacer(Modifier.width(8.dp)) + Text("$side · ${groupDigits(count)}", style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun PlayerColorSheet(player: PlayerSummary, onDismiss: () -> Unit, onPrepare: (PlayerSummary, Boolean) -> Unit) { + val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total)) + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp)) { + Text( + stringResource(R.string.prep_against_player, player.name), + Modifier.fillMaxWidth(), + style = MaterialTheme.typography.titleLarge, + ) + Spacer(Modifier.height(4.dp)) + Text( + games, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + PlayerColorAction(player, true, onPrepare) + PlayerColorAction(player, false, onPrepare) + } + } +} + +@Composable +private fun PlayerColorAction(player: PlayerSummary, white: Boolean, onPrepare: (PlayerSummary, Boolean) -> Unit) { + val count = if (white) player.whiteGames else player.blackGames + val side = stringResource(if (white) R.string.prep_against_white else R.string.prep_against_black) + val games = pluralStringResource(R.plurals.games_count, count, groupDigits(count)) + val prepare = stringResource(R.string.prepare_action) + Row( + Modifier.fillMaxWidth().heightIn(min = 64.dp) + .clearAndSetSemantics { + contentDescription = "${player.name}, $side, $games. $prepare" + role = Role.Button + onClick(prepare) { onPrepare(player, white); true } + } + .clickable(role = Role.Button, onClickLabel = prepare) { onPrepare(player, white) } + .padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + SideDisc(white) + Spacer(Modifier.width(12.dp)) + Text(side, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) + Spacer(Modifier.width(8.dp)) + Text(groupDigits(count), style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.width(8.dp)) + Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(24.dp)) + } +} + +@Composable +private fun PlayerPrepPlaceholder() { + Box(Modifier.fillMaxWidth().height(72.dp)) { + Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) { + Row(Modifier.fillMaxWidth().height(24.dp)) { + Box(Modifier.weight(1f).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp))) + Spacer(Modifier.width(8.dp)) + Box(Modifier.width(64.dp).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp))) + } + Spacer(Modifier.height(4.dp)) + Box(Modifier.fillMaxWidth(0.65f).height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp))) + } + HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant) + } +} + +@Composable +private fun LoadingPlayers() { + Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + CircularProgressIndicator() + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.reading_players), color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +internal fun PrepMessage(title: String, detail: String, action: (@Composable () -> Unit)? = null) { + Column(Modifier.fillMaxSize().padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + Text(title, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center) + if (detail.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + Text(detail, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center) + } + if (action != null) { + Spacer(Modifier.height(16.dp)) + action() + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepController.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepController.kt new file mode 100644 index 0000000..caf4dde --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepController.kt @@ -0,0 +1,161 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import io.github.vrubelroman.chesspenguin.data.PrepBackend +import io.github.vrubelroman.chesspenguin.data.PrepQuery +import io.github.vrubelroman.chesspenguin.data.query +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import uniffi.mobile_api.GameData +import uniffi.mobile_api.GameSession + +internal class PrepController(val request: PrepStart) : ViewModel() { + var line by mutableStateOf(PrepLineState(request.startFen, request.startFen)) + private set + var data by mutableStateOf(null) + private set + var position by mutableStateOf(null) + private set + var failure by mutableStateOf(null) + private set + var loading by mutableStateOf(false) + private set + var initialised by mutableStateOf(false) + private set + var moveFailed by mutableStateOf(false) + var retry by mutableIntStateOf(0) + private set + + private var session: GameSession? = null + private var search: Job? = null + private var generation = 0L + + suspend fun initialise() { + if (session != null) return + failure = null + val loaded = withContext(Dispatchers.Default) { + runCatching { + val fen = request.startFen + val s = GameSession.fromPgn("[SetUp \"1\"]\n[FEN \"$fen\"]\n\n*") + try { + var edited = s.data() to 0 + for (uci in request.moves) { + val next = s.play(edited.second.toUInt(), uci) + edited = next.data to next.cursor.toInt() + } + Triple(s, edited.first, edited.second) + } catch (e: Throwable) { + s.close() + throw e + } + } + } + if (session != null) { + loaded.getOrNull()?.first?.close() + return + } + val (s, game, cursor) = loaded.getOrElse { + failure = it + initialised = false + return + } + session = s + data = game + line = prepLine(game, cursor, request.startFen) + initialised = true + } + + private fun invalidate() { + generation += 1 + search?.cancel() + position = null + failure = null + loading = false + } + + fun back() { + if (!line.canBack) return + line = line.back() + invalidate() + } + + fun forward() { + if (!line.canForward) return + line = line.forward() + invalidate() + } + + fun start() { + if (!line.canBack) return + line = line.start() + invalidate() + } + + fun end() { + if (!line.canForward) return + line = line.end() + invalidate() + } + + fun legalMoves(): List = session?.legalMoves(line.currentNode.toUInt()).orEmpty() + + fun play(uci: String): String? { + val s = session ?: return null + if (s.legalMoves(line.currentNode.toUInt()).none { it == uci }) return null + val edited = runCatching { s.play(line.currentNode.toUInt(), uci) }.getOrElse { + moveFailed = true + return null + } + val visible = prepLine(edited.data, edited.cursor.toInt(), request.startFen) + line = visible + data = edited.data + invalidate() + return visible.last?.san + } + + fun repeat() { + retry += 1 + invalidate() + } + + fun search(backend: PrepBackend) { + if (!initialised || failure != null) return + invalidate() + backend.cancel() + val query: PrepQuery = request.query(line.fen) + val expected = generation + search = viewModelScope.launch { + val delayed = launch { + delay(300) + if (generation == expected) loading = true + } + try { + val answer = withContext(Dispatchers.IO) { backend.position(query) } + if (generation == expected && query == request.query(line.fen)) position = answer + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (generation == expected && query == request.query(line.fen)) failure = e + } finally { + delayed.cancel() + if (generation == expected) loading = false + } + } + } + + override fun onCleared() { + generation += 1 + search?.cancel() + session?.close() + session = null + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepModels.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepModels.kt new file mode 100644 index 0000000..a218043 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepModels.kt @@ -0,0 +1,187 @@ +package io.github.vrubelroman.chesspenguin.ui + +import kotlinx.serialization.Serializable +import uniffi.mobile_api.GameData +import kotlin.math.roundToInt + +internal const val STANDARD_START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" + +/// The position and history of a preparation request. The game document is not part of it. +@Serializable +data class PrepStart( + val db: String, + val player: String, + val white: Boolean, + val startFen: String = STANDARD_START, + val moves: List = emptyList(), + val fromGame: Boolean = false, +) + +/// One move of the temporary line. `node` belongs only to this preparation session. +@Serializable +data class PrepLineStep( + val node: Int, + val uci: String, + val san: String, + val moveNumber: Int, + val white: Boolean, + val fen: String, + val from: String?, + val to: String?, +) { + val label: String get() = "$moveNumber${if (white) "." else "…"}$san" +} + +/// A linear, read-only exploration. Going back never chooses a different continuation; +/// making a move after going back drops only this temporary future. +@Serializable +data class PrepLineState( + val startFen: String, + val rootFen: String, + val rootNode: Int = 0, + val steps: List = emptyList(), + val cursor: Int = 0, +) { + init { + require(cursor in 0..steps.size) { "line cursor is outside the line" } + } + + val fen: String get() = steps.getOrNull(cursor - 1)?.fen ?: rootFen + val currentNode: Int get() = steps.getOrNull(cursor - 1)?.node ?: rootNode + val last: PrepLineStep? get() = steps.getOrNull(cursor - 1) + val moves: List get() = steps.map { it.uci } + val canBack: Boolean get() = cursor > 0 + val canForward: Boolean get() = cursor < steps.size + + fun back(): PrepLineState = if (canBack) copy(cursor = cursor - 1) else this + fun forward(): PrepLineState = if (canForward) copy(cursor = cursor + 1) else this + fun start(): PrepLineState = if (canBack) copy(cursor = 0) else this + fun end(): PrepLineState = if (canForward) copy(cursor = steps.size) else this + + fun replaceVisibleLine(visible: List, currentNode: Int): PrepLineState { + val at = visible.indexOfLast { it.node == currentNode } + require(at >= 0 && at + 1 == visible.size) { "the played move must end the visible line" } + return copy(steps = visible, cursor = visible.size) + } +} + +internal fun prepLine(data: GameData, cursor: Int, startFen: String): PrepLineState { + val path = ArrayList() + var at: Int? = cursor + while (at != null) { + if (at !in data.nodes.indices || at in path) break + path += at + at = data.nodes[at].parent?.toInt() + } + path.reverse() + val root = path.firstOrNull() ?: 0 + val steps = path.drop(1).mapNotNull { id -> + val n = data.nodes[id] + if (n.uci.isEmpty()) return@mapNotNull null + PrepLineStep(id, n.uci, n.san, n.moveNumber.toInt(), n.white, n.fen, n.fromSquare, n.toSquare) + } + return PrepLineState(startFen, data.nodes.getOrNull(root)?.fen ?: startFen, root, steps, steps.size) +} + +/// A null move cannot be represented by the normal-move position search. +internal fun prepStartFromGame(data: GameData, at: Int, db: String, player: String, white: Boolean): PrepStart? { + if (at !in data.nodes.indices) return null + val path = ArrayList() + var node: Int? = at + while (node != null) { + if (node !in data.nodes.indices || node in path) return null + path += node + node = data.nodes[node].parent?.toInt() + } + path.reverse() + if (path.any { data.nodes[it].nullMove }) return null + val moves = path.drop(1).map { data.nodes[it].uci } + if (moves.any { it.isEmpty() }) return null + return PrepStart( + db = db, + player = player, + white = white, + startFen = data.nodes[path.first()].fen, + moves = moves, + fromGame = true, + ) +} + +/// Preparation shows the user's side at the bottom, opposite to the selected opponent. +internal fun prepBoardStartsFlipped(opponentWhite: Boolean): Boolean = opponentWhite + +internal fun prepWhiteToMove(fen: String): Boolean? = fen.split(' ').getOrNull(1)?.let { + when (it) { + "w" -> true + "b" -> false + else -> null + } +} + +internal fun moveLabel(fen: String, san: String): String { + val fields = fen.split(' ') + val number = fields.getOrNull(5)?.toIntOrNull()?.coerceAtLeast(0) ?: 1 + val white = prepWhiteToMove(fen) ?: true + return "$number${if (white) "." else "…"}$san" +} + +data class PlayerSummary( + val id: Int, + val name: String, + val total: Int, + val whiteGames: Int, + val blackGames: Int, +) + +data class PlayerPage( + val players: List, + val total: Int, + val nextOffset: Int?, +) + +data class PrepContinuation( + val uci: String, + val san: String, + val games: Int, + val wins: Int, + val draws: Int, + val losses: Int, + val unknown: Int = 0, +) { + val from: String? get() = uci.takeIf { it.length >= 4 }?.substring(0, 2) + val to: String? get() = uci.takeIf { it.length >= 4 }?.substring(2, 4) +} + +/// A matching game is part of the result contract even though its list is outside this MVP. +data class PrepGameMatch(val index: UInt, val ply: UInt) + +data class PrepPosition( + val games: Int, + val continuations: List, + val endedHere: Int = 0, + val noNormalContinuation: Int = 0, + val unknownResults: Int = 0, + val playerToMove: Boolean? = null, + val matches: List = emptyList(), + val matchesTotal: Int = 0, +) + +internal fun sortedContinuations(position: PrepPosition): List = + position.continuations.sortedWith(compareByDescending { it.games }.thenBy { it.san }) + +internal fun frequencyPercent(games: Int, total: Int): String = when { + games <= 0 || total <= 0 -> "0" + games * 100L < total -> "<1" + else -> (games * 100.0 / total).roundToInt().toString() +} + +internal fun outcomePercents(move: PrepContinuation): Triple { + val known = move.wins + move.draws + move.losses + if (known <= 0) return Triple("—", "—", "—") + fun percent(n: Int) = (n * 100.0 / known).roundToInt().toString() + return Triple(percent(move.wins), percent(move.draws), percent(move.losses)) +} + +internal class PrepOutOfMemory : IllegalStateException("Not enough memory for the position index") +internal class PrepSearchFailed(message: String) : IllegalStateException(message) +internal class PrepPlayerNotFound(name: String) : IllegalStateException("Player is not in this database: $name") diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepScreen.kt new file mode 100644 index 0000000..e7317f8 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepScreen.kt @@ -0,0 +1,469 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.content.res.Configuration +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.rounded.PlayArrow +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.foundation.focusable +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.viewmodel.compose.viewModel +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.PrepBackends +import io.github.vrubelroman.chesspenguin.theme.Tabular +import uniffi.mobile_api.Database + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun PrepScreen(request: PrepStart, onBack: () -> Unit) { + val app = app() + val context = LocalContext.current + val controller: PrepController = viewModel(key = "prep") { PrepController(request) } + val entries by app.library.entries.collectAsState() + val entry = entries.firstOrNull { it.id == request.db } + var database by remember { mutableStateOf(null) } + var openFailure by remember { mutableStateOf(null) } + var openRetry by rememberSaveable { mutableIntStateOf(0) } + LaunchedEffect(request.db, entry?.games, entry?.updated, openRetry) { + database = null + openFailure = null + controller.repeat() + app.library.database(request.db).onSuccess { database = it }.onFailure { openFailure = it } + } + val backend = remember(database) { database?.let(PrepBackends::open) } + DisposableEffect(backend) { onDispose { backend?.cancel(); backend?.close() } } + LaunchedEffect(controller.retry) { controller.initialise() } + LaunchedEffect(backend, controller.initialised, controller.line, controller.retry) { + if (backend != null && controller.initialised) controller.search(backend) + } + + val prefs by app.settings.prefs.collectAsState() + val lang = uiLanguage() + val san = remember(prefs.notation, lang) { { value: String -> displaySan(value, prefs.notation, lang) } } + val pieces = remember { Pieces(context) } + var flipped by rememberSaveable { mutableStateOf(prepBoardStartsFlipped(request.white)) } + var conflicts by remember { mutableStateOf>(emptyList()) } + val list = rememberLazyListState() + val contextFocus = remember { FocusRequester() } + val snackbar = remember { SnackbarHostState() } + val moveFailed = stringResource(R.string.prep_move_failed) + LaunchedEffect(controller.moveFailed) { + if (controller.moveFailed) { + snackbar.showSnackbar(moveFailed) + controller.moveFailed = false + } + } + + fun play(uci: String) { + val played = controller.play(uci) ?: return + conflicts = emptyList() + app.sounds.move(played) + contextFocus.requestFocus() + } + + fun arrowsChosen(moves: List) { + when (moves.size) { + 0 -> {} + 1 -> play(moves[0]) + else -> conflicts = moves + } + } + + val position = controller.position + val continuations = position?.let(::sortedContinuations).orEmpty() + val arrowContinuations = continuations.distinctBy { it.from to it.to }.take(3) + val arrows = arrowContinuations.mapIndexedNotNull { index, move -> + val from = move.from ?: return@mapIndexedNotNull null + val to = move.to ?: return@mapIndexedNotNull null + val weight = if (index == 0) 1f else if (index == 1) 0.85f else 0.70f + val alpha = if (index == 0) 0.63f else if (index == 1) 0.45f else 0.35f + BoardArrow(from, to, EngineArrow.copy(alpha = alpha), weight) + } + val arrowMoves = continuations.filter { move -> arrowContinuations.any { it.from == move.from && it.to == move.to } } + .mapNotNull { move -> + val from = move.from ?: return@mapNotNull null + val to = move.to ?: return@mapNotNull null + val label = moveLabel(controller.line.fen, move.san) + val games = pluralStringResource(R.plurals.games_count, move.games, groupDigits(move.games)) + val action = stringResource(R.string.prep_play_continuation, label, games, frequencyPercent(move.games, position?.games ?: 0)) + BoardArrowMove(move.uci, from, to, action) + } + val last = controller.line.last + val boardDescription = if (last == null) { + stringResource(R.string.prep_board_start, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white)) + } else { + stringResource(R.string.prep_board_after, last.label, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white)) + } + val board: @Composable (Modifier) -> Unit = { modifier -> + Board( + fen = controller.line.fen, + flipped = flipped, + lastFrom = last?.from, + lastTo = last?.to, + pieces = pieces, + theme = prefs.board, + set = prefs.pieces, + description = boardDescription, + modifier = modifier, + arrows = arrows, + arrowMoves = arrowMoves, + onArrowMoves = ::arrowsChosen, + check = last?.san?.let { it.endsWith("+") || it.endsWith("#") } == true, + animated = prefs.animation, + input = if (controller.initialised && controller.data != null) { + BoardInput(controller.legalMoves(), onMove = ::play) + } else { + null + }, + ) + } + + val turnWhite = prepWhiteToMove(controller.line.fen) + val opponentPlays = position?.playerToMove ?: (turnWhite == request.white) + val sideToMove = when (turnWhite) { + true -> stringResource(R.string.turn_white) + false -> stringResource(R.string.turn_black) + null -> "" + } + val who = stringResource(if (opponentPlays) R.string.prep_opponent_plays else R.string.prep_opponents_play) + val where = last?.let { stringResource(R.string.prep_after, it.label) } ?: stringResource(R.string.prep_beginning) + val gamesCount = position?.games + val gamesText = if (gamesCount == null) "…" else pluralStringResource(R.plurals.games_count, gamesCount, groupDigits(gamesCount)) + val contextDescription = stringResource(R.string.prep_context_description, who, sideToMove, where, gamesText) + val contextRow: @Composable () -> Unit = { + Row( + Modifier.fillMaxWidth().heightIn(min = 32.dp).focusRequester(contextFocus).focusable() + .semantics(mergeDescendants = true) { + contentDescription = contextDescription + liveRegion = LiveRegionMode.Polite + } + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + "$who · $where", + Modifier.weight(1f), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.width(8.dp)) + Text(gamesText, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) + } + } + val results: @Composable (Modifier) -> Unit = { modifier -> + Box(modifier) { + when { + openFailure != null -> PrepMessage(stringResource(R.string.prep_failed), openProblem(openFailure!!)) { + TextButton(onClick = { openRetry += 1 }) { Text(stringResource(R.string.retry)) } + } + controller.failure != null -> { + val memory = controller.failure is PrepOutOfMemory + val problem = openProblem(controller.failure!!).ifEmpty { controller.failure!!.message ?: "" } + PrepMessage(stringResource(if (memory) R.string.prep_no_memory else R.string.prep_failed), problem) { + TextButton(onClick = { controller.repeat() }) { Text(stringResource(R.string.retry)) } + } + } + position == null && controller.loading -> { + LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopStart)) + Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + CircularProgressIndicator() + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.prep_calculating), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + position == null -> PrepPlaceholders() + position.games == 0 -> PrepMessage( + stringResource(R.string.prep_position_absent, request.player), + stringResource(R.string.prep_position_absent_hint), + ) + continuations.isEmpty() && position.endedHere == position.games -> PrepMessage(stringResource(R.string.prep_all_ended), "") + else -> LazyColumn(Modifier.fillMaxSize(), state = list) { + items(continuations.size, key = { continuations[it].uci }) { index -> + ContinuationRow( + continuation = continuations[index], + total = position.games, + fen = controller.line.fen, + player = request.player, + san = san, + divider = index < continuations.lastIndex, + onClick = { play(continuations[index].uci) }, + ) + } + if (position.endedHere > 0 && continuations.isNotEmpty()) { + item(key = "ended") { PrepDisabledRow(stringResource(R.string.prep_ended_here, groupDigits(position.endedHere))) } + } + if (position.noNormalContinuation > 0) { + item(key = "no-normal") { PrepDisabledRow(stringResource(R.string.prep_no_normal, groupDigits(position.noNormalContinuation))) } + } + } + } + } + } + val controls: @Composable () -> Unit = { + PrepControls( + canBack = controller.line.canBack, + canForward = controller.line.canForward, + onFlip = { flipped = !flipped }, + onBack = controller::back, + onForward = controller::forward, + onStart = controller::start, + onEnd = controller::end, + ) + } + val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = onBack) { + Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(if (request.fromGame) R.string.to_game else R.string.to_players)) + } + }, + title = { + Column { + PlayerName(request.player, MaterialTheme.typography.titleMedium) + Text( + stringResource(if (request.white) R.string.prep_as_white else R.string.prep_as_black) + " · " + (entry?.let { displayName(it) } ?: ""), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + bottomBar = { if (!landscape) controls() }, + ) { padding -> + val inner = Modifier.fillMaxSize().padding(padding) + if (landscape) { + Row(inner.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal))) { + board(Modifier.fillMaxHeight()) + Column(Modifier.weight(1f).fillMaxHeight()) { + contextRow() + results(Modifier.weight(1f).fillMaxWidth()) + controls() + } + } + } else { + Column(inner, horizontalAlignment = Alignment.CenterHorizontally) { + board(Modifier.widthIn(max = 480.dp).fillMaxWidth()) + Column(Modifier.widthIn(max = 480.dp).fillMaxWidth().weight(1f)) { + contextRow() + results(Modifier.weight(1f).fillMaxWidth()) + } + } + } + } + + if (conflicts.isNotEmpty()) { + ModalBottomSheet(onDismissRequest = { conflicts = emptyList() }) { + Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { + Text(stringResource(R.string.prep_choose_move), style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) + conflicts.mapNotNull { uci -> continuations.firstOrNull { it.uci == uci } }.forEach { move -> + Row( + Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable { play(move.uci) }.padding(horizontal = 24.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(san(moveLabel(controller.line.fen, move.san)), style = MaterialTheme.typography.bodyLarge) + } + } + } + } + } +} + +@Composable +internal fun ContinuationRow( + continuation: PrepContinuation, + total: Int, + fen: String, + player: String, + san: (String) -> AnnotatedString, + divider: Boolean, + onClick: () -> Unit, +) { + val label = moveLabel(fen, continuation.san) + val frequency = frequencyPercent(continuation.games, total) + val (wins, draws, losses) = outcomePercents(continuation) + val games = pluralStringResource(R.plurals.games_count, total, groupDigits(total)) + val winsText = pluralStringResource(R.plurals.prep_wins, continuation.wins, groupDigits(continuation.wins)) + val drawsText = pluralStringResource(R.plurals.prep_draws, continuation.draws, groupDigits(continuation.draws)) + val lossesText = pluralStringResource(R.plurals.prep_losses, continuation.losses, groupDigits(continuation.losses)) + val unknown = if (continuation.unknown > 0) stringResource(R.string.prep_unknown_accessibility, continuation.unknown) else "" + val description = stringResource( + R.string.prep_continuation_description, + continuation.san, + continuation.games, + games, + frequency, + player, + winsText, + drawsText, + lossesText, + wins, + draws, + losses, + unknown, + ) + Column( + Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable(onClickLabel = stringResource(R.string.prep_play), role = Role.Button, onClick = onClick) + .clearAndSetSemantics { + contentDescription = description + role = Role.Button + onClick { onClick(); true } + } + .padding(start = 16.dp, top = 5.dp, end = 16.dp, bottom = 5.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(san(label), Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge.copy(fontSize = androidx.compose.ui.unit.TextUnit(17f, androidx.compose.ui.unit.TextUnitType.Sp)), maxLines = 1, overflow = TextOverflow.Ellipsis) + Spacer(Modifier.width(8.dp)) + Text( + "${groupDigits(continuation.games)}/${groupDigits(total)} · $frequency %", + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + maxLines = 1, + softWrap = false, + ) + } + val raw = buildString { + if (continuation.unknown > 0) append(stringResource(R.string.prep_unknown_short, groupDigits(continuation.unknown))).append(' ') + append(stringResource(R.string.prep_wdl_counts, groupDigits(continuation.wins), groupDigits(continuation.draws), groupDigits(continuation.losses), wins, draws, losses)) + } + Text(raw, style = MaterialTheme.typography.labelSmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) + if (divider) HorizontalDivider(Modifier.padding(top = 5.dp), color = MaterialTheme.colorScheme.outlineVariant) + } +} + +@Composable +private fun PrepDisabledRow(text: String) { + Text( + text, + Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 12.dp), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +@Composable +private fun PrepPlaceholders() { + Column(Modifier.fillMaxWidth()) { + repeat(4) { + Column(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 16.dp, vertical = 8.dp)) { + Box(Modifier.fillMaxWidth().height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow)) + Spacer(Modifier.height(4.dp)) + Box(Modifier.fillMaxWidth().height(16.dp).background(MaterialTheme.colorScheme.surfaceContainerLow)) + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } + } +} + +@Composable +internal fun PrepControls( + canBack: Boolean, + canForward: Boolean, + onFlip: () -> Unit, + onBack: () -> Unit, + onForward: () -> Unit, + onStart: () -> Unit, + onEnd: () -> Unit, +) { + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) { + BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.width(72.dp), onClick = onFlip) + BarButton( + icon = Icons.Rounded.PlayArrow, + label = stringResource(R.string.move_back), + description = stringResource(R.string.move_back_hint), + enabled = canBack, + modifier = Modifier.weight(1f), + iconSize = 32, + mirrored = true, + onLongClickLabel = stringResource(R.string.to_start), + onLongClick = onStart, + onClick = onBack, + ) + BarButton( + icon = Icons.Rounded.PlayArrow, + label = stringResource(R.string.move_forward), + description = stringResource(R.string.move_forward_hint), + enabled = canForward, + modifier = Modifier.weight(1f), + iconSize = 32, + onLongClickLabel = stringResource(R.string.to_end), + onLongClick = onEnd, + onClick = onForward, + ) + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt new file mode 100644 index 0000000..655bd2f --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt @@ -0,0 +1,668 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material3.Button +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.rememberModalBottomSheetState +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.input.pointer.pointerInput +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.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.GUESS_NPS +import io.github.vrubelroman.chesspenguin.theme.LocalChessColors +import io.github.vrubelroman.chesspenguin.theme.Tabular +import io.github.vrubelroman.chesspenguin.theme.nagColor +import uniffi.mobile_api.GameData +import uniffi.mobile_api.MoveJudgement +import uniffi.mobile_api.ReviewMove +import uniffi.mobile_api.ReviewState +import uniffi.mobile_api.SideReview +import kotlin.math.roundToInt + +/// The NAG of the same sign: $3 !!, $1 !, $6 ?!, $2 ?, $4 ??. +fun judgementNag(j: MoveJudgement): Int = when (j) { + MoveJudgement.INACCURACY -> 6 + MoveJudgement.MISTAKE -> 2 + MoveJudgement.BLUNDER -> 4 + MoveJudgement.GREAT -> 1 + MoveJudgement.BRILLIANT -> 3 +} + +/// The colors of the NAGs !!, !, ?!, ? and ?? (§21.4). +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) { + MoveJudgement.INACCURACY -> "?!" + MoveJudgement.MISTAKE -> "?" + MoveJudgement.BLUNDER -> "??" + MoveJudgement.GREAT -> "!" + MoveJudgement.BRILLIANT -> "!!" +} + +@Composable +fun judgementName(j: MoveJudgement): String = stringResource( + when (j) { + MoveJudgement.INACCURACY -> R.string.review_inaccuracy + MoveJudgement.MISTAKE -> R.string.review_mistake + MoveJudgement.BLUNDER -> R.string.review_blunder + MoveJudgement.GREAT -> R.string.review_great + MoveJudgement.BRILLIANT -> R.string.review_brilliant + }, +) + +@Composable +private fun judgementPlural(j: MoveJudgement): String = stringResource( + when (j) { + MoveJudgement.INACCURACY -> R.string.review_inaccuracies + MoveJudgement.MISTAKE -> R.string.review_mistakes + MoveJudgement.BLUNDER -> R.string.review_blunders + MoveJudgement.GREAT -> R.string.review_greats + MoveJudgement.BRILLIANT -> R.string.review_brilliants + }, +) + +/// The place in `state.points` of a node: itself on the main line, or the main-line move +/// its variation leaves from. +fun pointIndex(points: Map, game: GameData, node: Int): Int? { + var n = node + while (true) { + points[n]?.let { return it } + n = game.nodes.getOrNull(n)?.parent?.toInt() ?: return null + } +} + +/// "91%", or "—" when the accuracy is not known yet. +private fun percent(a: Double?): String = a?.let { "${it.roundToInt()}%" } ?: "—" + +/// The analysis between the board and the notation (§21.3): what is going on or what the +/// current move was, and the evaluation graph. +@Composable +fun ReviewPanel( + state: ReviewState, + cursor: Int?, + mark: ReviewMove?, + preparing: Boolean, + notation: (String) -> AnnotatedString, + onIndex: (Int) -> Unit, + onBest: (ReviewMove) -> Unit, + onReport: () -> Unit, + onStop: () -> Unit, + onResume: () -> Unit, + cursorLabel: String? = null, + showGraph: Boolean = true, +) { + val dark = LocalChessColors.current.dark + Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainerLow)) { + // 48 dp: every button here and the error row itself are touch targets (§21.3). + Row( + Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + val textStyle = MaterialTheme.typography.bodyMedium + val report: @Composable () -> Unit = { + TextButton(onClick = onReport) { Text(stringResource(R.string.review_report)) } + } + when { + state.running -> { + Text( + stringResource(R.string.review_progress, state.done.toInt(), state.total.toInt()), + style = textStyle.merge(Tabular), + modifier = Modifier.weight(1f), + ) + IconButton(onClick = onStop) { Icon(Icons.Rounded.Close, stringResource(R.string.review_stop)) } + } + preparing -> Text( + stringResource(R.string.preparing_engine), + style = textStyle, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + mark != null -> { + val c = judgementColor(mark.judgement, dark) + val name = judgementName(mark.judgement) + val canShow = mark.best?.steps?.isNotEmpty() == true + // Without a line (evaluations from the PGN) the better move is not named. + val better = mark.bestLabel.takeIf { it.isNotEmpty() && canShow }?.let { notation(it) } + // The template around the move ("{move} was better", "лучше было {move}"). + val betterText = better?.let { stringResource(R.string.review_better, "\u0000").split('\u0000') } + val link = MaterialTheme.colorScheme.primary + val text = buildAnnotatedString { + withStyle(SpanStyle(color = c, fontWeight = FontWeight.Bold)) { append(judgementSymbol(mark.judgement) + " " + name) } + if (better != null && betterText != null) { + append(" · ") + append(betterText.first()) + // The move in the link color: the row can be tapped (§21.3). + withStyle(SpanStyle(color = link, fontWeight = FontWeight.Medium)) { append(better) } + append(betterText.getOrElse(1) { "" }) + } + } + Box( + Modifier + .weight(1f) + .height(48.dp) + .then(if (canShow) Modifier.clickable(onClickLabel = stringResource(R.string.review_show_best)) { onBest(mark) } else Modifier), + contentAlignment = Alignment.CenterStart, + ) { + Text(text, style = textStyle, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + report() + } + state.failure != null -> { + Text(stringResource(R.string.review_failed), style = textStyle, color = MaterialTheme.colorScheme.error, modifier = Modifier.weight(1f)) + TextButton(onClick = onResume) { Text(stringResource(R.string.review_resume)) } + report() + } + // Made with other engine settings (before the fixed search): made again. + state.stale -> { + Text( + stringResource(R.string.review_stale), + style = textStyle, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = onResume) { Text(stringResource(R.string.review_update)) } + report() + } + state.missing > 0u || state.secondsMissing > 0u -> { + Text( + // An analysis from before !! and !: filling in looks for them only. + if (state.missing > 0u) stringResource(R.string.review_missing, state.missing.toInt()) else stringResource(R.string.review_no_seconds), + style = textStyle.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = onResume) { Text(stringResource(R.string.review_fill)) } + report() + } + else -> { + val spoken = stringResource(R.string.review_accuracy_of, percent(state.white.accuracy), percent(state.black.accuracy)) + Row( + Modifier.weight(1f).clearAndSetSemantics { contentDescription = spoken }, + verticalAlignment = Alignment.CenterVertically, + ) { + Text(stringResource(R.string.review_accuracy), style = textStyle, color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.width(10.dp)) + SideDot(white = true) + Text(percent(state.white.accuracy), style = textStyle.merge(Tabular), fontWeight = FontWeight.Medium, modifier = Modifier.padding(start = 6.dp)) + Spacer(Modifier.width(14.dp)) + SideDot(white = false) + Text(percent(state.black.accuracy), style = textStyle.merge(Tabular), fontWeight = FontWeight.Medium, modifier = Modifier.padding(start = 6.dp)) + } + report() + } + } + } + if (showGraph) { + EvalGraph(state, cursor, cursorLabel, onIndex, Modifier.fillMaxWidth().height(40.dp).padding(start = 16.dp, end = 16.dp, bottom = 8.dp)) + } + } +} + +/// A circle in a side's color, outlined so the white one shows on a light background. +@Composable +private fun SideDot(white: Boolean, size: Int = 12) { + Box( + Modifier + .size(size.dp) + .clip(CircleShape) + .background(if (white) Color(0xFFF5F5F0) else Color(0xFF26282B)) + .border(1.dp, MaterialTheme.colorScheme.outline, CircleShape), + ) +} + +/// White's chance of winning along the main line (§21.3), as on the desktop: light area +/// for White, dark for Black, the curve, the errors as dots, the phases and the current +/// move. A tap or a drag goes to a move. +@Composable +fun EvalGraph(state: ReviewState, cursor: Int?, cursorLabel: String?, onIndex: (Int) -> Unit, modifier: Modifier) { + val chess = LocalChessColors.current + val dark = chess.dark + // In the light theme a shade darker than the panel, so that White's area shows. + val bg = if (dark) MaterialTheme.colorScheme.surfaceContainerHighest else Color(0xFFDCDFE3) + val whiteFill = if (dark) Color(0xFF969696) else Color(0xFFFFFFFF) + val blackFill = if (dark) Color(0xFF0A0A0A) else Color(0xFF464646) + val curve = Color(0xFFE07B1F) + val midColor = MaterialTheme.colorScheme.outline + val phaseColor = MaterialTheme.colorScheme.onSurfaceVariant + val description = stringResource(R.string.review_graph) + val now = cursor?.let { state.points.getOrNull(it) } + val spokenState = now?.eval?.takeIf { it.isNotEmpty() }?.let { e -> + stringResource(R.string.review_graph_state, cursorLabel ?: stringResource(R.string.review_start_position), e) + } + val points = state.points + val n = points.size + val pick by rememberUpdatedState(onIndex) + Canvas( + modifier + .clip(RoundedCornerShape(6.dp)) + .background(bg) + .semantics { + contentDescription = description + spokenState?.let { stateDescription = it } + } + .pointerInput(n) { + if (n < 2) return@pointerInput + val pad = 6.dp.toPx() + fun index(x: Float): Int { + val t = ((x - pad) / (size.width - 2 * pad)).coerceIn(0f, 1f) + return (t * (n - 1)).roundToInt() + } + awaitEachGesture { + val down = awaitFirstDown() + var last = index(down.position.x) + pick(last) + down.consume() + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull { it.id == down.id } ?: break + if (!change.pressed) break + val i = index(change.position.x) + if (i != last) { + last = i + pick(i) + } + change.consume() + } + } + }, + ) { + if (n < 2) return@Canvas + val padX = 6.dp.toPx() + val padY = 4.dp.toPx() + val w = size.width - 2 * padX + val h = size.height - 2 * padY + fun x(i: Int) = padX + w * i / (n - 1) + fun y(wp: Float) = padY + h * (1f - wp / 100f) + val mid = y(50f) + // Advantage areas between the curve and the middle line: one outline per run of + // evaluated positions, drawn light above the middle and dark below it (one shape, + // so no seams between the moves). + val area = Path() + var open = false + var lastX = 0f + points.forEachIndexed { i, p -> + val wp = p.whiteWin + if (wp == null) { + if (open) { + area.lineTo(lastX, mid) + area.close() + open = false + } + } else { + if (!open) { + area.moveTo(x(i), mid) + open = true + } + area.lineTo(x(i), y(wp)) + lastX = x(i) + } + } + if (open) { + area.lineTo(lastX, mid) + area.close() + } + clipRect(bottom = mid) { drawPath(area, whiteFill) } + clipRect(top = mid) { drawPath(area, blackFill) } + drawLine(midColor.copy(alpha = 0.6f), Offset(padX, mid), Offset(size.width - padX, mid), 1.dp.toPx()) + // Phase boundaries, without labels: at this height they would cover the curve + // (§21.3); the report has the accuracy per phase. + listOfNotNull(state.middlegame?.toInt(), state.endgame?.toInt()).filter { it in 1 until n }.forEach { i -> + drawLine(phaseColor.copy(alpha = 0.5f), Offset(x(i), 0f), Offset(x(i), size.height), 1.dp.toPx()) + } + // The curve, broken where positions are not evaluated yet. + val stroke = Stroke(width = 1.6.dp.toPx()) + var path: Path? = null + var count = 0 + fun flush() { + if (count > 1) path?.let { drawPath(it, curve, style = stroke) } + path = null + count = 0 + } + points.forEachIndexed { i, p -> + val wp = p.whiteWin + if (wp == null) { + flush() + } else { + val px = x(i) + val py = y(wp) + val current = path + if (current == null) { + path = Path().apply { moveTo(px, py) } + } else { + current.lineTo(px, py) + } + count++ + } + } + flush() + // The errors on top of everything but the current move. + points.forEachIndexed { i, p -> + val j = p.judgement ?: return@forEachIndexed + val wp = p.whiteWin ?: return@forEachIndexed + drawCircle(judgementColor(j, dark), 3.5.dp.toPx(), Offset(x(i), y(wp))) + } + if (cursor != null && cursor in 0 until n) { + drawLine(curve, Offset(x(cursor), 0f), Offset(x(cursor), size.height), 1.5.dp.toPx()) + } + } +} + +/// The sheet that starts the analysis (§21.2): what it does and how long it takes. The +/// engine search is fixed, the same on every phone and computer: nothing to choose. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ReviewStartSheet( + state: ReviewState?, + npsPerProcess: Long, + onStart: (full: Boolean) -> Unit, + onDismiss: () -> Unit, +) { + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(start = 24.dp, end = 24.dp, bottom = 24.dp)) { + Text(stringResource(R.string.review_menu), style = MaterialTheme.typography.titleLarge) + Spacer(Modifier.height(12.dp)) + Text(stringResource(R.string.review_text), style = MaterialTheme.typography.bodyLarge) + Spacer(Modifier.height(12.dp)) + val total = state?.positions?.toInt() ?: 0 + val missing = state?.missing?.toInt() ?: total + // Evaluations from the PGN: the engine makes its own, all of them. + val pgn = state != null && state.hasData && state.nodes == 0UL + // Some positions already have an engine evaluation of today's search: filled in. + val partial = state != null && state.hasData && !pgn && !state.stale && missing in 1 until total + val positions = if (partial) missing else total + // A full run also searches again for moves that could be !! or ! (about a third more). + val searches = if (partial) positions else (state?.searches?.toInt() ?: positions) + val secs = uniffi.mobile_api.reviewEstimateSecs(searches.toUInt(), (if (npsPerProcess > 0) npsPerProcess else GUESS_NPS).toULong()).toInt().coerceAtLeast(1) + val time = if (secs < 60) stringResource(R.string.review_seconds, secs) else stringResource(R.string.review_minutes, (secs + 59) / 60) + Text( + pluralStringResource(R.plurals.review_estimate, positions, positions, time), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (partial) { + Spacer(Modifier.height(4.dp)) + Text( + stringResource(R.string.review_partial, total - missing, total), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } + // The same search again would give the same evaluations: only the missing + // ones are made, or all of them over the PGN's (or a stale analysis). + Button(onClick = { onStart(pgn) }) { Text(stringResource(if (partial) R.string.review_fill else R.string.review_start)) } + } + } + } +} + +/// The report (§21.5): White and Black side by side, as on Lichess; a count above zero +/// goes to the next such move of that player. +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +fun ReviewSheet( + state: ReviewState, + white: String, + black: String, + onError: (white: Boolean, MoveJudgement) -> Unit, + onAgain: () -> Unit, + onHide: () -> Unit, + onDismiss: () -> Unit, +) { + // Opened whole: nothing in it should hide below the edge (§21.5). + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).navigationBarsPadding().padding(start = 24.dp, end = 16.dp, bottom = 24.dp)) { + Text(stringResource(R.string.review_report_menu), style = MaterialTheme.typography.titleLarge) + Spacer(Modifier.height(16.dp)) + val dark = LocalChessColors.current.dark + val variant = MaterialTheme.colorScheme.onSurfaceVariant + // Player names over the two columns. + ReportRow( + label = {}, + white = { PlayerHead(white, true) }, + black = { PlayerHead(black, false) }, + height = null, + ) + ReportRow( + label = { Text(stringResource(R.string.review_accuracy), style = MaterialTheme.typography.bodyLarge) }, + white = { ReportNumber(percent(state.white.accuracy), MaterialTheme.typography.headlineSmall) }, + black = { ReportNumber(percent(state.black.accuracy), MaterialTheme.typography.headlineSmall) }, + ) + val next = stringResource(R.string.review_next) + listOf( + MoveJudgement.BRILLIANT, + MoveJudgement.GREAT, + MoveJudgement.INACCURACY, + MoveJudgement.MISTAKE, + MoveJudgement.BLUNDER, + ).forEach { j -> + val c = judgementColor(j, dark) + 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 active = count > 0u && !unknown + val shown = if (unknown) "\u2014" else count.toString() + Row( + Modifier + .fillMaxWidth() + .height(48.dp) + .then( + if (active) { + Modifier + .clickable(onClickLabel = next) { onError(isWhite, j) } + .semantics { + role = Role.Button + contentDescription = "$label, $side, $count" + } + } else { + Modifier.clearAndSetSemantics { contentDescription = "$label, $side, $shown" } + }, + ), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.End, + ) { + Text( + shown, + style = MaterialTheme.typography.titleMedium.merge(Tabular), + color = if (active) c else variant, + ) + Box(Modifier.width(24.dp), contentAlignment = Alignment.CenterEnd) { + if (active) Icon(Icons.Rounded.ChevronRight, null, tint = variant, modifier = Modifier.size(20.dp)) + } + } + } + val whiteSide = stringResource(R.string.tag_white) + val blackSide = stringResource(R.string.tag_black) + ReportRow( + label = { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(judgementSymbol(j), color = c, fontWeight = FontWeight.Bold, modifier = Modifier.width(28.dp)) + Text(label, style = MaterialTheme.typography.bodyLarge) + } + }, + white = { cell(true, state.white.inaccuraciesOf(j), whiteSide) }, + black = { cell(false, state.black.inaccuraciesOf(j), blackSide) }, + ) + } + ReportRow( + label = { Text(stringResource(R.string.review_acpl), style = MaterialTheme.typography.bodyMedium, color = variant) }, + white = { ReportNumber(state.white.acpl?.toString() ?: "\u2014") }, + black = { ReportNumber(state.black.acpl?.toString() ?: "\u2014") }, + height = null, + ) + listOf( + Triple(R.string.review_opening, state.white.opening, state.black.opening), + Triple(R.string.review_middlegame, state.white.middlegame, state.black.middlegame), + Triple(R.string.review_endgame, state.white.endgame, state.black.endgame), + ).filter { it.second != null || it.third != null }.forEach { (res, w, b) -> + ReportRow( + label = { Text(stringResource(res), style = MaterialTheme.typography.bodyMedium, color = variant) }, + white = { ReportNumber(percent(w)) }, + black = { ReportNumber(percent(b)) }, + height = 40, + ) + } + Spacer(Modifier.height(12.dp)) + Text( + if (state.nodes == 0UL) { + stringResource(R.string.review_source_pgn) + } else { + stringResource(R.string.review_source, state.engine, compactCount(state.nodes)) + }, + style = MaterialTheme.typography.bodySmall, + 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)) + // With a large font the two buttons go on two lines instead of breaking words. + FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(onClick = onHide) { Text(stringResource(R.string.review_hide)) } + // Over evaluations of the PGN the engine can make its own; an engine + // analysis made again would only repeat itself. + if (state.nodes == 0UL) { + OutlinedButton(onClick = onAgain, enabled = !state.running) { Text(stringResource(R.string.review_engine)) } + } + } + } + } +} + +private fun SideReview.inaccuraciesOf(j: MoveJudgement): UInt = when (j) { + MoveJudgement.INACCURACY -> inaccuracies + MoveJudgement.MISTAKE -> mistakes + 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. +@Composable +private fun ReportRow( + label: @Composable () -> Unit, + white: @Composable () -> Unit, + black: @Composable () -> Unit, + height: Int? = 48, +) { + Row( + Modifier.fillMaxWidth().then(if (height != null) Modifier.height(height.dp) else Modifier.padding(vertical = 4.dp)), + verticalAlignment = Alignment.CenterVertically, + ) { + Box(Modifier.weight(1f)) { label() } + Box(Modifier.width(96.dp), contentAlignment = Alignment.CenterEnd) { white() } + Box(Modifier.width(96.dp), contentAlignment = Alignment.CenterEnd) { black() } + } +} + +/// A player over a column: the side's circle and the surname, up to two lines; the full +/// name for TalkBack. +@Composable +private fun PlayerHead(name: String, white: Boolean) { + Row( + Modifier.padding(start = 4.dp).semantics(mergeDescendants = true) { contentDescription = name }, + verticalAlignment = Alignment.CenterVertically, + ) { + SideDot(white, 12) + Text( + name.substringBefore(',').trim(), + style = MaterialTheme.typography.labelLarge, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(start = 8.dp), + ) + } +} + +@Composable +private fun ReportNumber(text: String, style: TextStyle = MaterialTheme.typography.bodyLarge) { + Text(text, style = style.merge(Tabular), fontWeight = FontWeight.Medium, modifier = Modifier.padding(end = 24.dp)) +} + +/// 250 000 → "250k", 1 000 000 → "1M", 1 500 000 → "1.5M" (as on the desktop). +private fun compactCount(n: ULong): String { + val v = n.toLong() + return when { + v >= 1_000_000 && v % 100_000 == 0L -> if (v % 1_000_000 == 0L) "${v / 1_000_000}M" else "%.1fM".format(java.util.Locale.ROOT, v / 1e6) + v >= 1000 -> "${v / 1000}k" + else -> v.toString() + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/RodentStyles.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/RodentStyles.kt new file mode 100644 index 0000000..52e9def --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/RodentStyles.kt @@ -0,0 +1,48 @@ +package io.github.vrubelroman.chesspenguin.ui + +import io.github.vrubelroman.chesspenguin.R + +/// Rodent IV's characters in the app's language (android-rodent.md §3.3): their names and +/// what they do, as the desktop app says them (apps/desktop/src/i18n.rs), by the ids of +/// the shared list (`play::rodent::STYLES`, given by `rodentStyles()`). +val RODENT_TEXTS: Map> = mapOf( + "iv_amanda" to (R.string.rodent_iv_amanda to R.string.rodent_iv_amanda_about), + "iv_cloe" to (R.string.rodent_iv_cloe to R.string.rodent_iv_cloe_about), + "iv_deborah" to (R.string.rodent_iv_deborah to R.string.rodent_iv_deborah_about), + "iv_defender" to (R.string.rodent_iv_defender to R.string.rodent_iv_defender_about), + "iv_dynamic" to (R.string.rodent_iv_dynamic to R.string.rodent_iv_dynamic_about), + "iv_grumpy" to (R.string.rodent_iv_grumpy to R.string.rodent_iv_grumpy_about), + "iv_partisan" to (R.string.rodent_iv_partisan to R.string.rodent_iv_partisan_about), + "iv_pawnsacker" to (R.string.rodent_iv_pawnsacker to R.string.rodent_iv_pawnsacker_about), + "iv_pedrita" to (R.string.rodent_iv_pedrita to R.string.rodent_iv_pedrita_about), + "iv_preston" to (R.string.rodent_iv_preston to R.string.rodent_iv_preston_about), + "iv_simple" to (R.string.rodent_iv_simple to R.string.rodent_iv_simple_about), + "iv_spitfire" to (R.string.rodent_iv_spitfire to R.string.rodent_iv_spitfire_about), + "iv_strangler" to (R.string.rodent_iv_strangler to R.string.rodent_iv_strangler_about), + "iv_alekhine" to (R.string.rodent_iv_alekhine to R.string.rodent_iv_alekhine_about), + "iv_anand" to (R.string.rodent_iv_anand to R.string.rodent_iv_anand_about), + "iv_anderssen" to (R.string.rodent_iv_anderssen to R.string.rodent_iv_anderssen_about), + "iv_bosboom" to (R.string.rodent_iv_bosboom to R.string.rodent_iv_bosboom_about), + "iv_botvinnik" to (R.string.rodent_iv_botvinnik to R.string.rodent_iv_botvinnik_about), + "iv_fischer" to (R.string.rodent_iv_fischer to R.string.rodent_iv_fischer_about), + "iv_karpov" to (R.string.rodent_iv_karpov to R.string.rodent_iv_karpov_about), + "iv_kasparov" to (R.string.rodent_iv_kasparov to R.string.rodent_iv_kasparov_about), + "iv_kortchnoi" to (R.string.rodent_iv_kortchnoi to R.string.rodent_iv_kortchnoi_about), + "iv_larsen" to (R.string.rodent_iv_larsen to R.string.rodent_iv_larsen_about), + "iv_lasker" to (R.string.rodent_iv_lasker to R.string.rodent_iv_lasker_about), + "iv_marshall" to (R.string.rodent_iv_marshall to R.string.rodent_iv_marshall_about), + "iv_morphy" to (R.string.rodent_iv_morphy to R.string.rodent_iv_morphy_about), + "iv_nimzowitsch" to (R.string.rodent_iv_nimzowitsch to R.string.rodent_iv_nimzowitsch_about), + "iv_petrosian" to (R.string.rodent_iv_petrosian to R.string.rodent_iv_petrosian_about), + "iv_reti" to (R.string.rodent_iv_reti to R.string.rodent_iv_reti_about), + "iv_rubinstein" to (R.string.rodent_iv_rubinstein to R.string.rodent_iv_rubinstein_about), + "iv_spassky" to (R.string.rodent_iv_spassky to R.string.rodent_iv_spassky_about), + "iv_steinitz" to (R.string.rodent_iv_steinitz to R.string.rodent_iv_steinitz_about), + "iv_tal" to (R.string.rodent_iv_tal to R.string.rodent_iv_tal_about), + "iv_tarrasch" to (R.string.rodent_iv_tarrasch to R.string.rodent_iv_tarrasch_about), + "iv_topalov" to (R.string.rodent_iv_topalov to R.string.rodent_iv_topalov_about), +) + +/// The character suggested first (android-rodent.md §3.4), and the one an unknown id +/// (of a later version) falls back to. +const val DEFAULT_RODENT_STYLE = "iv_tal" diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SaveGame.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SaveGame.kt new file mode 100644 index 0000000..7cc5995 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SaveGame.kt @@ -0,0 +1,138 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.DbEntry +import uniffi.mobile_api.GameData +import uniffi.mobile_api.GameSession + +/// The game of a game screen as it is being changed (android-play.md §29–30), kept while +/// the phone turns: the screen is made again, the moves stay. +class GameEdit : ViewModel() { + /// Which game: "database/index", or [NEW_GAME]. + var key: String? = null + val session = mutableStateOf(null) + val data = mutableStateOf(null) + /// What reading the game noticed: kept when the game is changed. + var notes: List = emptyList() + /// Where a new game or a copy was saved: saving again replaces it there. + var savedTo: Pair? = null + /// Where the game against Maia went by itself (its player's database), if it did. + val recorded = mutableStateOf(null) + /// Why it did not (the card says so; «Save…» stays). + val recordError = mutableStateOf(null) + /// An opening being learned over the game (android-play.md §32), how far, the board's side. + val trainer = mutableStateOf(null) + /// The game against Maia, when this screen plays one (§31). + val play = mutableStateOf(null) + /// Bumped to read the game in hand again (a rematch). + val reloads = androidx.compose.runtime.mutableIntStateOf(0) + var trainPly = 0 + var trainFlipped = false + /// The move the trainer was opened from: the game shows it again after. + var trainReturn: Int? = null + + override fun onCleared() { + trainer.value?.close() + play.value?.close() + session.value?.close() + } +} + +/// The key of a new game (a game screen without a database). +const val NEW_GAME = "new" + +/// «Save to a database» (android-play.md §30.6): the own databases to choose from (the +/// last one used first), or a new one named here. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SaveSheet(own: List, last: String?, onSave: (DbEntry) -> Unit, onCreate: (String) -> Unit, onDismiss: () -> Unit) { + var chosen by remember { mutableStateOf(own.firstOrNull { it.id == last }?.id ?: own.firstOrNull()?.id) } + var creating by remember { mutableStateOf(own.isEmpty()) } + val defaultName = stringResource(R.string.own_default_name) + var name by remember { mutableStateOf(freeName(defaultName, own.map { it.name })) } + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { + Text(stringResource(R.string.save_to_db), style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) + Column(Modifier.selectableGroup()) { + for (e in own) { + val n = e.games ?: 0 + Row( + Modifier + .fillMaxWidth() + .height(56.dp) + .selectable(selected = !creating && chosen == e.id, role = Role.RadioButton) { + creating = false + chosen = e.id + } + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = !creating && chosen == e.id, onClick = null) + Text(displayName(e), Modifier.weight(1f).padding(start = 16.dp), maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(pluralStringResource(R.plurals.games_count, n, groupDigits(n)), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium) + } + } + } + if (own.isNotEmpty() && !creating) { + Row( + Modifier.fillMaxWidth().height(56.dp).clickable { creating = true }.padding(horizontal = 24.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(Icons.Rounded.Add, null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + Text(stringResource(R.string.own_new_ellipsis), Modifier.padding(start = 16.dp)) + } + } + if (creating) { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + singleLine = true, + label = { Text(stringResource(R.string.own_name)) }, + modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp), + ) + } + Spacer(Modifier.size(8.dp)) + Row(Modifier.fillMaxWidth().padding(horizontal = 24.dp), horizontalArrangement = Arrangement.End) { + if (creating) { + Button(onClick = { onCreate(name.trim()) }, enabled = name.isNotBlank()) { Text(stringResource(R.string.create_and_save)) } + } else { + Button(onClick = { own.firstOrNull { it.id == chosen }?.let(onSave) }, enabled = chosen != null) { Text(stringResource(R.string.save)) } + } + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt new file mode 100644 index 0000000..7e2fdfa --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt @@ -0,0 +1,440 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.material.icons.rounded.Info +import androidx.compose.material.icons.rounded.SdCard +import androidx.compose.material.icons.rounded.DeveloperBoard +import androidx.compose.material.icons.rounded.Timer +import androidx.compose.material.icons.rounded.Delete +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.automirrored.rounded.MenuBook +import kotlinx.coroutines.launch +import androidx.compose.material.icons.rounded.Memory +import androidx.compose.material.icons.rounded.Translate +import androidx.compose.material.icons.rounded.Palette +import androidx.compose.material.icons.rounded.GridOn +import androidx.compose.material.icons.rounded.Save +import androidx.compose.material.icons.rounded.Vibration +import androidx.compose.material.icons.automirrored.rounded.FormatListBulleted +import androidx.compose.material.icons.automirrored.rounded.Notes +import androidx.compose.material.icons.automirrored.rounded.VolumeUp +import androidx.compose.material.icons.automirrored.rounded.ArrowRightAlt +import androidx.compose.material.icons.rounded.Animation +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.size +import androidx.compose.ui.draw.clip +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.background +import android.app.Activity +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +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.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.takeOrElse +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import java.util.Locale +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.LANGUAGES +import io.github.vrubelroman.chesspenguin.data.Language +import io.github.vrubelroman.chesspenguin.data.NetProblem +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.data.Notation +import io.github.vrubelroman.chesspenguin.data.Theme + +/// One screen of groups, changes apply at once (android-ui.md §9). The board and the +/// pieces are chosen on a screen of their own, with a board to see them on. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () -> Unit) { + val app = app() + val prefs by app.settings.prefs.collectAsState() + val files = app.engineFiles + val net by files.state.collectAsState() + val set = app.settings::update + var choice by remember { mutableStateOf(null) } + var deleting by remember { mutableStateOf(false) } + var sheet by remember { mutableStateOf(false) } + val lang = uiLanguage() + val scroll = TopAppBarDefaults.pinnedScrollBehavior() + val snackbar = remember { androidx.compose.material3.SnackbarHostState() } + UpdateMessages(snackbar) + val size = (BuildConfig.NET_SIZE / 1_000_000).toInt() + + val themeNames = listOf( + Theme.System to stringResource(R.string.theme_system), + Theme.Light to stringResource(R.string.theme_light), + Theme.Dark to stringResource(R.string.theme_dark), + ) + val notationNames = buildList { + add(Notation.Latin to stringResource(R.string.notation_latin)) + add(Notation.Figurines to stringResource(R.string.notation_figurines)) + // Only a language with letters of its own (not English, Uzbek, Kazakh; move-notation.md §2.1). + if (localLetters(lang) != null) add(Notation.Local to stringResource(R.string.notation_local)) + } + val secondsNames = listOf( + 10 to stringResource(R.string.seconds, 10), + 20 to stringResource(R.string.seconds, 20), + 60 to stringResource(R.string.one_minute), + 0 to stringResource(R.string.no_limit), + ) + val cores = Runtime.getRuntime().availableProcessors() + + Scaffold( + modifier = Modifier.nestedScroll(scroll.nestedScrollConnection), + snackbarHost = { androidx.compose.material3.SnackbarHost(snackbar) }, + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.settings)) }, + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + scrollBehavior = scroll, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + Group(stringResource(R.string.group_game)) + Cards { + val notationNow = notationNames.firstOrNull { it.first == prefs.notation } ?: notationNames.first() + Item(stringResource(R.string.notation), notationNow.second, icon = Icons.AutoMirrored.Rounded.Notes) { + choice = Choice( + R.string.notation, + notationNames.map { it.second }, + notationNames.indexOf(notationNow), + hint = R.string.notation_hint, + ) { i -> set { it.copy(notation = notationNames[i].first) } } + } + + Toggle(stringResource(R.string.animation), prefs.animation, Icons.Rounded.Animation) { v -> set { it.copy(animation = v) } } + Toggle(stringResource(R.string.best_arrow), prefs.bestArrow, Icons.AutoMirrored.Rounded.ArrowRightAlt) { v -> set { it.copy(bestArrow = v) } } + Toggle(stringResource(R.string.sound), prefs.sound, Icons.AutoMirrored.Rounded.VolumeUp) { v -> set { it.copy(sound = v) } } + Toggle(stringResource(R.string.vibration), prefs.vibration, Icons.Rounded.Vibration) { v -> set { it.copy(vibration = v) } } + Toggle(stringResource(R.string.record_games), prefs.recordGames, Icons.Rounded.Save) { v -> set { it.copy(recordGames = v) } } + } + + Group(stringResource(R.string.group_look)) + Cards { + Item(stringResource(R.string.board_and_pieces), boardLabel(prefs.board) + " · " + prefs.pieces.dir, icon = Icons.Rounded.GridOn, onClick = onBoardStyle) + Item(stringResource(R.string.theme), themeNames.first { it.first == prefs.theme }.second, icon = Icons.Rounded.Palette) { + choice = Choice(R.string.theme, themeNames.map { it.second }, themeNames.indexOfFirst { it.first == prefs.theme }) { i -> + set { it.copy(theme = themeNames[i].first) } + } + } + val context = LocalContext.current + val languageNames = LANGUAGES.map { + if (it.isEmpty()) stringResource(R.string.theme_system) else Locale.forLanguageTag(it).let { l -> l.getDisplayLanguage(l).replaceFirstChar(Char::uppercase) } + } + val language = remember { Language.get(context) } + Item(stringResource(R.string.language), languageNames[LANGUAGES.indexOf(language).coerceAtLeast(0)], icon = Icons.Rounded.Translate) { + choice = Choice(R.string.language, languageNames, LANGUAGES.indexOf(language).coerceAtLeast(0)) { i -> + if (Language.set(context, LANGUAGES[i])) (context as? Activity)?.recreate() + } + } + } + + Group(stringResource(R.string.group_engine)) + Cards { + when { + files.builtIn -> Status(stringResource(R.string.engine_built_in), Icons.Rounded.Memory) + net == NetState.Ready -> { + Status(stringResource(R.string.engine_downloaded), Icons.Rounded.Memory) + Item(stringResource(R.string.engine_delete, size), null, icon = Icons.Rounded.Delete) { deleting = true } + } + net is NetState.Loading -> { + val l = net as NetState.Loading + Item(stringResource(R.string.engine_downloading, (l.done / 1_000_000).toInt(), (l.total / 1_000_000).toInt()), null, icon = Icons.Rounded.Memory) { sheet = true } + } + // The same sheet as in a game: the size, mobile data, cancel (§9). + else -> Item(stringResource(R.string.engine_missing, size), null, icon = Icons.Rounded.Memory) { sheet = true } + } + // Rodent IV's opening books (android-rodent.md §7.2): the engine itself is in the app. + RodentBooks(snackbar) + Item(stringResource(R.string.lines), "${prefs.engineLines}", icon = Icons.AutoMirrored.Rounded.FormatListBulleted) { + choice = Choice(R.string.lines, listOf("1", "2", "3"), prefs.engineLines - 1) { i -> set { it.copy(engineLines = i + 1) } } + } + Item(stringResource(R.string.time_per_position), secondsNames.firstOrNull { it.first == prefs.engineSeconds }?.second ?: "", icon = Icons.Rounded.Timer) { + choice = Choice(R.string.time_per_position, secondsNames.map { it.second }, secondsNames.indexOfFirst { it.first == prefs.engineSeconds }) { i -> + set { it.copy(engineSeconds = secondsNames[i].first) } + } + } + Item(stringResource(R.string.threads), "${prefs.engineThreads}", icon = Icons.Rounded.DeveloperBoard) { + choice = Choice(R.string.threads, (1..cores).map { "$it" }, prefs.engineThreads - 1) { i -> set { it.copy(engineThreads = i + 1) } } + } + val hashes = listOf(16, 32, 64, 128, 256) + val hashNames = hashes.map { stringResource(R.string.megabytes, it) } + Item(stringResource(R.string.memory), stringResource(R.string.megabytes, prefs.engineHashMb), icon = Icons.Rounded.SdCard) { + choice = Choice(R.string.memory, hashNames, hashes.indexOf(prefs.engineHashMb)) { i -> set { it.copy(engineHashMb = hashes[i]) } } + } + } + Text( + stringResource(R.string.engine_battery), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + Spacer(Modifier.height(16.dp)) + // A newer version of the app, even with its card hidden (android-ui.md §25.5). + Cards { + Item(stringResource(R.string.about), aboutUpdateLine(), valueColor = MaterialTheme.colorScheme.primary, icon = Icons.Rounded.Info, onClick = onAbout) + } + } + } + + choice?.let { c -> + AlertDialog( + onDismissRequest = { choice = null }, + title = { Text(stringResource(c.title)) }, + text = { + Column { + c.options.forEachIndexed { i, label -> + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .selectable(selected = i == c.selected, role = Role.RadioButton) { + c.pick(i) + choice = null + }, + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = i == c.selected, onClick = null) + Text(label, Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyLarge) + } + } + c.hint?.let { + Spacer(Modifier.height(8.dp)) + Text(stringResource(it), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + }, + confirmButton = { TextButton(onClick = { choice = null }) { Text(stringResource(R.string.cancel)) } }, + ) + } + if (sheet) { + EngineSheet( + state = net, + metered = remember(sheet) { files.metered() }, + onDownload = { files.prepare() }, + onCancel = { + files.cancel() + sheet = false + }, + onDismiss = { sheet = false }, + ) + } + LaunchedEffect(net) { if (net == NetState.Ready) sheet = false } + if (deleting) { + AlertDialog( + onDismissRequest = { deleting = false }, + text = { Text(stringResource(R.string.engine_delete_question)) }, + confirmButton = { + TextButton(onClick = { + files.delete() + deleting = false + }) { Text(stringResource(R.string.delete)) } + }, + dismissButton = { TextButton(onClick = { deleting = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +/// «Rodent IV — opening books»: downloaded or not, with what is left to download; +/// download, or delete (not while a game against Rodent goes on); the progress and ✕ +/// while downloading; why it failed, and «Try again». +@Composable +private fun RodentBooks(snackbar: androidx.compose.material3.SnackbarHostState) { + val app = app() + val books = app.rodentFiles.books + val state by books.state.collectAsState() + val game by app.maiaGames.current.collectAsState() + val playing = game?.let { !it.over && it.rival == io.github.vrubelroman.chesspenguin.data.Opponent.Rodent } == true + val scope = androidx.compose.runtime.rememberCoroutineScope() + val deletedText = stringResource(R.string.books_deleted) + val deleteText = stringResource(R.string.books_delete_cd) + fun mb(bytes: Long) = ((bytes + 999_999) / 1_000_000).toInt() + // The books checked so far stay: what is left is offered. + val left = remember(state) { books.remaining() } + Row( + Modifier.card().heightIn(min = 56.dp).padding(start = 16.dp, end = 4.dp, top = 8.dp, bottom = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ItemIcon(Icons.AutoMirrored.Rounded.MenuBook) + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.books_settings), style = MaterialTheme.typography.bodyLarge) + when (val s = state) { + is NetState.Loading -> { + androidx.compose.material3.LinearProgressIndicator( + progress = { s.done.toFloat() / s.total.coerceAtLeast(1) }, + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + ) + Text( + stringResource(R.string.downloaded_of, mb(s.done), mb(s.total)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + is NetState.Failed -> Text( + when (s.problem) { + NetProblem.NoInternet -> stringResource(R.string.no_internet) + NetProblem.Interrupted -> stringResource(R.string.interrupted) + NetProblem.NoSpace -> stringResource(R.string.no_space, mb(left)) + NetProblem.Corrupt -> stringResource(R.string.corrupt) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + NetState.Ready -> Text( + stringResource(R.string.books_downloaded_mb, mb(books.size)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + NetState.Missing -> Text( + stringResource(R.string.books_missing_mb, mb(left)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + when (state) { + is NetState.Loading -> IconButton(onClick = { books.cancel() }) { + Icon(Icons.Rounded.Close, stringResource(R.string.cancel_download)) + } + NetState.Ready -> TextButton( + enabled = !playing, + modifier = Modifier.semantics { contentDescription = deleteText }, + onClick = { + books.delete() + scope.launch { + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(deletedText) + } + }, + ) { Text(stringResource(R.string.delete)) } + is NetState.Failed -> TextButton(onClick = { books.download() }) { Text(stringResource(R.string.play_retry)) } + NetState.Missing -> TextButton(onClick = { books.download() }) { Text(stringResource(R.string.download)) } + } + } +} + +private class Choice(val title: Int, val options: List, val selected: Int, val hint: Int? = null, val pick: (Int) -> Unit) + +@Composable +private fun Group(title: String) { + Text( + title, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 24.dp, bottom = 8.dp), + ) +} + +/// A group's items as cards (android-lists.md §6): 16 dp corners outside, 4 dp between +/// them, 2 dp of the background between cards. +@Composable +private fun Cards(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) { + Column( + Modifier.padding(horizontal = 12.dp).clip(RoundedCornerShape(16.dp)), + verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(2.dp), + content = content, + ) +} + +/// One card of a group. +@Composable +private fun Modifier.card(): Modifier = fillMaxWidth().clip(RoundedCornerShape(4.dp)).background(MaterialTheme.colorScheme.surfaceContainerLow) + +/// An item's icon: 24 dp, then 16 dp to its text. +@Composable +private fun ItemIcon(icon: androidx.compose.ui.graphics.vector.ImageVector?) { + if (icon == null) return + Icon(icon, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(24.dp)) + Spacer(Modifier.width(16.dp)) +} + +@Composable +private fun Item( + title: String, + value: String?, + valueColor: androidx.compose.ui.graphics.Color = androidx.compose.ui.graphics.Color.Unspecified, + icon: androidx.compose.ui.graphics.vector.ImageVector? = null, + onClick: (() -> Unit)?, +) { + Row( + Modifier + .card() + .heightIn(min = 56.dp) + .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier) + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ItemIcon(icon) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge) + if (value != null) { + Text(value, style = MaterialTheme.typography.bodyMedium, color = valueColor.takeOrElse { MaterialTheme.colorScheme.onSurfaceVariant }) + } + } + } +} + +/// A line that tells, not a button. +@Composable +private fun Status(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector? = null) { + Row(Modifier.card().heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { + ItemIcon(icon) + Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +private fun Toggle(title: String, value: Boolean, icon: androidx.compose.ui.graphics.vector.ImageVector? = null, onChange: (Boolean) -> Unit) { + Row( + Modifier + .card() + .heightIn(min = 56.dp) + .selectable(selected = value, role = Role.Switch) { onChange(!value) } + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ItemIcon(icon) + Text(title, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + Switch(checked = value, onCheckedChange = null) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/TrainScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/TrainScreen.kt new file mode 100644 index 0000000..24cecb0 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/TrainScreen.kt @@ -0,0 +1,306 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.view.HapticFeedbackConstants +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +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.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.rounded.Replay +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.Button +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.OutlinedButton +import androidx.compose.material3.Scaffold +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.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.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.R +import kotlinx.coroutines.delay +import uniffi.mobile_api.TrainVerdict +import uniffi.mobile_api.Trainer + +/// A wrong move of the trainer, on the board for a moment (§32.2). +private data class Wrong(val fen: String, val from: String, val to: String) + +/// Learning an opening (android-play.md §32): the user plays the moves of both sides +/// of the line from memory; a wrong move shows for 400 ms and is taken back. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TrainScreen(trainer: Trainer, ply0: Int, startFlipped: Boolean, onPly: (Int) -> Unit, onExit: () -> Unit) { + val app = app() + val prefs by app.settings.prefs.collectAsState() + val context = androidx.compose.ui.platform.LocalContext.current + val pieces = remember { Pieces(context) } + val view = LocalView.current + val lang = uiLanguage() + val san = remember(prefs.notation, lang) { { s: String -> displaySan(s, prefs.notation, lang) } } + var ply by remember { mutableIntStateOf(ply0) } + var flipped by remember { mutableStateOf(startFlipped) } + var wrong by remember { mutableStateOf(null) } + // Said after a wrong move until the right one. + var missed by remember { mutableStateOf(false) } + var changes by remember { mutableIntStateOf(0) } + val st = remember(ply, changes) { trainer.state(ply.toUInt()) } + BackHandler(onBack = onExit) + LaunchedEffect(wrong) { + if (wrong != null) { + delay(400) + wrong = null + } + } + fun buzz(reject: Boolean) { + if (prefs.vibration) view.performHapticFeedback(if (reject) HapticFeedbackConstants.REJECT else HapticFeedbackConstants.CLOCK_TICK) + } + fun move(uci: String) { + when (trainer.judge(ply.toUInt(), uci)) { + TrainVerdict.RIGHT -> { + missed = false + ply += 1 + onPly(ply) + buzz(false) + trainer.state(ply.toUInt()).played.lastOrNull()?.let { app.sounds.move(it) } + } + TrainVerdict.FINISHED -> { + missed = false + ply += 1 + onPly(ply) + buzz(false) + app.sounds.play(io.github.vrubelroman.chesspenguin.data.Sound.Success) + } + TrainVerdict.WRONG -> { + trainer.fenAfter(ply.toUInt(), uci)?.let { wrong = Wrong(it, uci.substring(0, 2), uci.substring(2, 4)) } + missed = true + changes++ + buzz(true) + app.sounds.play(io.github.vrubelroman.chesspenguin.data.Sound.Wrong) + } + TrainVerdict.DONE -> {} + } + } + val sub = listOfNotNull(trainer.game(), stringResource(R.string.train_up_to, san(trainer.upTo()).text)).joinToString(" · ") + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { IconButton(onClick = onExit) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } }, + title = { + Column { + Text(stringResource(R.string.train_title), style = MaterialTheme.typography.titleMedium) + Text(sub, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + }, + ) + }, + bottomBar = { + Column { + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly) { + IconButton(onClick = { flipped = !flipped }) { Icon(Icons.Rounded.SwapVert, stringResource(R.string.flip)) } + TextButton(enabled = ply > 0 || st.done, onClick = { + trainer.again() + ply = 0 + onPly(0) + missed = false + wrong = null + changes++ + }) { + Icon(Icons.Rounded.Replay, null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.train_restart)) + } + } + } + } + }, + ) { padding -> + val landscape = androidx.compose.ui.platform.LocalConfiguration.current.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE + val task: @Composable () -> Unit = { + if (!st.done) { + // The task: which move, whose turn, how far. + val whiteToMove = st.fen.substringAfter(' ').startsWith("w") + Column(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalArrangement = Arrangement.Center) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.train_move_of, (ply + 1).toString(), st.length.toString()), Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) + Text(stringResource(if (whiteToMove) R.string.train_white else R.string.train_black), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Medium) + } + LinearProgressIndicator(progress = { ply.toFloat() / st.length.toInt().coerceAtLeast(1) }, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) + } + } + } + val boardBox: @Composable (Modifier) -> Unit = { m -> + val w = wrong + Board( + fen = w?.fen ?: st.fen, + flipped = flipped, + lastFrom = w?.from ?: st.fromSquare, + lastTo = w?.to ?: st.toSquare, + pieces = pieces, + theme = prefs.board, + set = prefs.pieces, + description = stringResource(R.string.train_title), + arrows = st.hint?.let { listOf(BoardArrow(it[0], it[1], EngineArrow)) } ?: emptyList(), + animated = prefs.animation, + modifier = m, + input = if (st.done || w != null) null else BoardInput( + remember(ply, changes) { trainer.legalMoves(ply.toUInt()) }, + onMove = ::move, + // The line's own piece where it promotes; a queen otherwise (§29.4). + promotion = { pair -> trainer.promotionAt(ply.toUInt())?.takeIf { it.startsWith(pair) }?.last() }, + ), + alert = w?.let { it.from to it.to }, + ) + } + val you: @Composable () -> Unit = { + if (!st.done) { + // You: the mistakes of this run, or before the first move what was before. + Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) { + val text = when { + st.hint != null -> stringResource(R.string.train_arrow) + missed -> stringResource(R.string.train_wrong) + ply == 0 && st.mistakes == 0u -> history(st.before) + else -> stringResource(R.string.train_mistakes, st.mistakes.toString()) + } + Text( + text, + Modifier.weight(1f), + color = if (missed && st.hint == null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (st.mayShow && st.hint == null) { + TextButton(onClick = { + trainer.show(ply.toUInt()) + changes++ + }) { Text(stringResource(R.string.train_show)) } + } else if (ply > 0 || st.mistakes > 0u) { + // With the message of a wrong move, the count stays in sight. + Text( + if (missed && st.hint == null) stringResource(R.string.train_mistakes, st.mistakes.toString()) + else stringResource(R.string.train_run, (st.before.runs + 1u).toString()), + Modifier.padding(end = 12.dp), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.bodyMedium, + ) + } + } + } + } + val notes: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit = { + Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) { + if (st.done) Result(st, onAgain = { + trainer.again() + ply = 0 + onPly(0) + missed = false + changes++ + }, onExit = onExit) + // The moves played so far, two to a row. + st.played.chunked(2).forEachIndexed { i, pair -> + Row(Modifier.fillMaxWidth().height(40.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Text("${i + 1}", Modifier.width(32.dp), color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(san(pair[0]), Modifier.weight(1f), fontWeight = FontWeight.Medium) + Text(pair.getOrNull(1)?.let { san(it) } ?: androidx.compose.ui.text.AnnotatedString(""), Modifier.weight(1f), fontWeight = FontWeight.Medium) + } + } + } + } + // A phone on its side: the board at full height, the rest beside it. + if (landscape) { + Row(Modifier.fillMaxSize().padding(padding)) { + boardBox(Modifier.fillMaxHeight()) + Column(Modifier.weight(1f).fillMaxHeight()) { + task() + you() + notes() + } + } + } else { + Column(Modifier.fillMaxSize().padding(padding)) { + task() + boardBox(Modifier.fillMaxWidth()) + you() + notes() + } + } + } +} + +/// «Last time: 2 · best: 0», «Not done before». +@Composable +private fun history(s: uniffi.mobile_api.TrainStats): String = when { + s.runs == 0u -> stringResource(R.string.train_not_done) + s.cleanStreak >= 2u -> stringResource(R.string.train_last_streak, (s.last ?: 0u).toString(), s.cleanStreak.toString()) + else -> stringResource(R.string.train_last_best, (s.last ?: 0u).toString(), s.best?.toString() ?: "–") +} + +/// The end of a run (§32.3): how it went, the line's runs, again or back to the game. +@Composable +private fun Result(st: uniffi.mobile_api.TrainState, onAgain: () -> Unit, onExit: () -> Unit) { + val after = st.after ?: st.before + Column( + Modifier + .fillMaxWidth() + .padding(16.dp) + .background(MaterialTheme.colorScheme.surfaceContainerHigh, RoundedCornerShape(16.dp)) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text( + when { + st.hinted -> stringResource(R.string.train_done_hint, st.mistakes.toString()) + st.mistakes == 0u -> stringResource(R.string.train_done_clean) + else -> stringResource(R.string.train_done, st.mistakes.toString()) + }, + style = MaterialTheme.typography.titleMedium, + ) + val line = buildList { + add(stringResource(R.string.train_run_best, after.runs.toString(), after.best?.toString() ?: "–")) + if (after.cleanStreak >= 2u) add(stringResource(R.string.train_streak, after.cleanStreak.toString())) + }.joinToString(" · ") + Text(line, style = MaterialTheme.typography.bodyMedium) + if (after.recentMistakes.size > 1) { + val runs = after.recentMistakes.zip(after.recentHinted).joinToString(" · ") { (m, h) -> if (h) "$m*" else "$m" } + Text(stringResource(R.string.train_recent, runs), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // The desktop's texts carry their signs; here the buttons are the signs. + Button(onClick = onAgain, modifier = Modifier.weight(1f).height(48.dp)) { Text(stringResource(R.string.train_again).removePrefix("↻ "), maxLines = 1) } + OutlinedButton(onClick = onExit, modifier = Modifier.weight(1f).height(48.dp)) { Text(stringResource(R.string.train_back).removePrefix("⬅ "), maxLines = 1) } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/UpdateViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/UpdateViews.kt new file mode 100644 index 0000000..bf24dd3 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/UpdateViews.kt @@ -0,0 +1,583 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.content.Intent +import android.net.Uri +import android.provider.Settings +import android.text.format.DateUtils +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +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.rememberScrollState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight +import androidx.compose.material.icons.rounded.Close +import androidx.compose.foundation.layout.offset +import androidx.compose.material3.IconButton +import androidx.compose.material.icons.rounded.SystemUpdateAlt +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +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.platform.LocalContext +import androidx.compose.ui.platform.LocalUriHandler +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.heading +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.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.CheckState +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.data.UpdateMessage +import io.github.vrubelroman.chesspenguin.data.UpdateProblem +import io.github.vrubelroman.chesspenguin.data.UpdateState +import io.github.vrubelroman.chesspenguin.data.UpdateStep +import io.github.vrubelroman.chesspenguin.theme.Tabular + +private const val SITE_URL = "https://chess.vrubel.xyz" + +private fun mb(bytes: Long) = ((bytes + 999_999) / 1_000_000).toInt() + +/// The update the card on «Databases» shows, or null: none known, offers turned off (its +/// ×, or Settings), or the check turned off (unless the user asked for it). +@Composable +fun shownUpdate(): UpdateState? { + val updates = app().updates + val state by updates.state.collectAsState() + val auto by updates.auto.collectAsState() + val offer by updates.offer.collectAsState() + val asked by updates.asked.collectAsState() + val s = state ?: return null + if (!offer) return null + if (!auto && !asked && s is UpdateState.Available) return null + return s +} + +/// The card over the list of databases (android-ui.md §25.2): the new version, one +/// button, and × that stops the offers (they come back in Settings → About). +@Composable +fun UpdateCard(state: UpdateState, onDismissed: () -> Unit, modifier: Modifier = Modifier) { + val updates = app().updates + val update = state.update + val title = stringResource(R.string.upd_title, update.version) + val progressOnly = state is UpdateState.Downloading || state is UpdateState.Busy + val downloadingText = when (state) { + is UpdateState.Downloading -> if (state.waitingNetwork) { + title + ", " + stringResource(R.string.upd_waiting_net_short) + } else { + stringResource(R.string.upd_card_downloading, update.version, mb(state.done), mb(update.apkSize)) + } + is UpdateState.Busy -> title + ", " + stepText(state.step) + else -> null + } + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(12.dp), + modifier = modifier + .fillMaxWidth() + .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 8.dp) + .then( + if (progressOnly) { + Modifier + .clickable(role = Role.Button) { updates.openSheet() } + .clearAndSetSemantics { + contentDescription = downloadingText ?: title + role = Role.Button + onClick { updates.openSheet(); true } + } + } else { + Modifier + }, + ), + ) { + Column(Modifier.padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = if (progressOnly) 16.dp else 8.dp)) { + Row(verticalAlignment = Alignment.Top) { + Icon(Icons.Rounded.SystemUpdateAlt, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(24.dp)) + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text( + title, + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + modifier = Modifier.semantics { heading() }, + ) + Spacer(Modifier.height(2.dp)) + when (state) { + is UpdateState.Available, is UpdateState.NeedsPermission -> Text( + stringResource(R.string.upd_you_have, BuildConfig.VERSION_NAME), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + is UpdateState.Downloading -> { + Spacer(Modifier.height(6.dp)) + LinearProgressIndicator( + progress = { state.done.toFloat() / update.apkSize.coerceAtLeast(1) }, + modifier = Modifier.fillMaxWidth().height(4.dp), + ) + Spacer(Modifier.height(6.dp)) + Text( + if (state.waitingNetwork) stringResource(R.string.upd_waiting_net_short) else stringResource(R.string.downloaded_of, mb(state.done), mb(update.apkSize)), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + is UpdateState.Busy -> { + Spacer(Modifier.height(6.dp)) + LinearProgressIndicator(Modifier.fillMaxWidth().height(4.dp)) + Spacer(Modifier.height(6.dp)) + Text(stepText(state.step), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + is UpdateState.Ready -> Text( + stringResource(R.string.upd_ready_short), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + is UpdateState.Failed -> Text( + shortProblem(state.problem), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + } + if (progressOnly) { + // The whole card opens the sheet. + Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(24.dp)) + } else { + IconButton( + onClick = { + updates.setOffer(false) + onDismissed() + }, + modifier = Modifier.offset(x = 12.dp, y = (-12).dp), + ) { + Icon(Icons.Rounded.Close, stringResource(R.string.upd_dismiss_cd), tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(20.dp)) + } + } + } + if (!progressOnly) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + when (state) { + is UpdateState.Ready -> FilledTonalButton(onClick = { + updates.openSheet() + updates.install() + }) { Text(stringResource(R.string.upd_install)) } + is UpdateState.Failed -> FilledTonalButton(onClick = { updates.openSheet() }) { Text(stringResource(R.string.upd_more)) } + else -> FilledTonalButton(onClick = { + updates.openSheet() + updates.start() + }) { Text(stringResource(R.string.upd_update)) } + } + } + } + } + } +} + +@Composable +private fun stepText(step: UpdateStep): String = stringResource( + when (step) { + UpdateStep.CheckingFile -> R.string.upd_checking_file + UpdateStep.KeepingEngine -> R.string.upd_keeping_engine + UpdateStep.Installing -> R.string.upd_installing + }, +) + +@Composable +private fun shortProblem(p: UpdateProblem): String = stringResource( + when (p) { + UpdateProblem.NoInternet -> R.string.upd_short_offline + UpdateProblem.NoSpace, UpdateProblem.InstallStorage -> R.string.upd_short_space + UpdateProblem.Corrupt -> R.string.upd_short_corrupt + UpdateProblem.DownloadFailed -> R.string.upd_short_failed + UpdateProblem.BadRelease -> R.string.upd_short_release + UpdateProblem.Conflict, UpdateProblem.Blocked, UpdateProblem.InstallFailed -> R.string.upd_short_install + }, +) + +/// The «Update» sheet (android-ui.md §25.3), over whatever screen is shown. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun UpdateSheet() { + val app = app() + val updates = app.updates + val state by updates.state.collectAsState() + val net by app.engineFiles.state.collectAsState() + val games by app.downloads.views.collectAsState() + val context = LocalContext.current + val uri = LocalUriHandler.current + val s = state + if (s == null) { + LaunchedEffect(Unit) { updates.closeSheet() } + return + } + val update = s.update + // Back from the settings with the permission: TalkBack says the download has begun. + val view = androidx.compose.ui.platform.LocalView.current + val granted = stringResource(R.string.upd_perm_granted) + var waited by remember { mutableStateOf(false) } + LaunchedEffect(s is UpdateState.NeedsPermission, s is UpdateState.Downloading) { + if (s is UpdateState.NeedsPermission) waited = true + if (s is UpdateState.Downloading && waited) { + waited = false + @Suppress("DEPRECATION") + view.announceForAccessibility(granted) + } + } + val close = { + updates.closeSheet() + updates.dismissProblem() + } + ModalBottomSheet(onDismissRequest = close, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + Column( + Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(start = 24.dp, end = 24.dp, bottom = 24.dp), + ) { + Text(stringResource(R.string.upd_title, update.version), style = MaterialTheme.typography.titleLarge, modifier = Modifier.semantics { heading() }) + Spacer(Modifier.height(4.dp)) + Text( + stringResource(R.string.upd_you_have, BuildConfig.VERSION_NAME), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(16.dp)) + // The engine stays when there is one to keep: in the app's storage, or in a full + // build that keeps it before the install. + val engine = net == NetState.Ready || BuildConfig.NET_BUILT_IN + Text(stringResource(if (engine) R.string.upd_keeps else R.string.upd_keeps_no_engine), style = MaterialTheme.typography.bodyLarge) + Text(stringResource(R.string.upd_closes), style = MaterialTheme.typography.bodyLarge) + if (games.values.any { it.state.running }) { + Spacer(Modifier.height(8.dp)) + Text(stringResource(R.string.upd_online_note), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Spacer(Modifier.height(16.dp)) + val live = Modifier.semantics { liveRegion = LiveRegionMode.Polite } + when (s) { + is UpdateState.Available -> Buttons( + secondary = stringResource(R.string.not_now) to close, + primary = stringResource(R.string.upd_update) to { updates.start() }, + ) + is UpdateState.NeedsPermission -> { + val openSettings = { + updates.permissionAsked() + context.startActivity( + Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}")), + ) + } + if (!s.denied) { + Text(stringResource(R.string.upd_perm_title), style = MaterialTheme.typography.titleMedium, modifier = live) + Spacer(Modifier.height(4.dp)) + Text(stringResource(R.string.upd_perm_body), style = MaterialTheme.typography.bodyMedium) + } else { + Text(stringResource(R.string.upd_perm_denied), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, modifier = live) + Link(stringResource(R.string.upd_on_site)) { uri.openUri(SITE_URL) } + } + Spacer(Modifier.height(24.dp)) + Buttons( + secondary = stringResource(R.string.cancel) to close, + primary = stringResource(R.string.upd_perm_open) to openSettings, + ) + } + is UpdateState.Downloading -> { + LinearProgressIndicator( + progress = { s.done.toFloat() / update.apkSize.coerceAtLeast(1) }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + Text( + if (s.waitingNetwork) stringResource(R.string.upd_waiting_net) else stringResource(R.string.downloaded_of, mb(s.done), mb(update.apkSize)), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + ) + Text(stringResource(R.string.upd_leave), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = live) + Spacer(Modifier.height(16.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { + updates.cancel() + updates.closeSheet() + }) { Text(stringResource(R.string.cancel_download)) } + } + } + is UpdateState.Busy -> { + LinearProgressIndicator(Modifier.fillMaxWidth()) + Spacer(Modifier.height(8.dp)) + Text(stepText(s.step), style = MaterialTheme.typography.bodyMedium, modifier = live) + } + is UpdateState.Ready -> { + Text( + stringResource(if (s.aborted) R.string.upd_aborted else R.string.upd_ready), + style = MaterialTheme.typography.bodyMedium, + modifier = live, + ) + Spacer(Modifier.height(24.dp)) + Buttons( + secondary = stringResource(R.string.not_now) to { updates.closeSheet() }, + primary = stringResource(R.string.upd_install) to { updates.install() }, + ) + } + is UpdateState.Failed -> Problem(s, onRetry = { updates.start() }, onSite = { uri.openUri(SITE_URL) }, onClose = close) + } + } + } +} + +@Composable +private fun Problem(s: UpdateState.Failed, onRetry: () -> Unit, onSite: () -> Unit, onClose: () -> Unit) { + val updates = app().updates + val text = when (s.problem) { + UpdateProblem.NoInternet -> stringResource(R.string.no_internet) + UpdateProblem.DownloadFailed -> stringResource(R.string.upd_err_failed) + UpdateProblem.NoSpace -> stringResource(R.string.no_space, mb(updates.needed(s.update))) + UpdateProblem.Corrupt -> stringResource(R.string.upd_err_corrupt) + UpdateProblem.BadRelease -> stringResource(R.string.upd_err_release) + UpdateProblem.InstallStorage -> stringResource(R.string.upd_err_storage, mb(updates.needed(s.update))) + UpdateProblem.Conflict -> stringResource(R.string.upd_err_conflict) + UpdateProblem.Blocked -> stringResource(R.string.upd_err_blocked) + UpdateProblem.InstallFailed -> stringResource(R.string.upd_err_install) + } + Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }) + val install = s.problem in setOf(UpdateProblem.InstallStorage, UpdateProblem.Conflict, UpdateProblem.Blocked, UpdateProblem.InstallFailed) + val detail = s.detail + if (install && !detail.isNullOrBlank()) { + var open by rememberSaveable { mutableStateOf(false) } + Link(stringResource(R.string.upd_details)) { open = !open } + if (open) { + @Suppress("DEPRECATION") + val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current + Text(detail, fontFamily = FontFamily.Monospace, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + TextButton(onClick = { clipboard.setText(androidx.compose.ui.text.AnnotatedString(detail)) }) { Text(stringResource(R.string.upd_copy)) } + } + } + Spacer(Modifier.height(24.dp)) + val notNow = stringResource(R.string.not_now) + val ok = stringResource(R.string.ok) + val retry = stringResource(R.string.retry) + val site = stringResource(R.string.upd_open_site) + when (s.problem) { + UpdateProblem.NoInternet, UpdateProblem.DownloadFailed, UpdateProblem.InstallStorage -> Buttons(notNow to onClose, retry to onRetry) + UpdateProblem.Corrupt -> Buttons(notNow to onClose, stringResource(R.string.download_again) to onRetry) + UpdateProblem.NoSpace -> Buttons(null, ok to onClose) + UpdateProblem.BadRelease, UpdateProblem.Conflict, UpdateProblem.Blocked -> Buttons(ok to onClose, site to onSite) + UpdateProblem.InstallFailed -> Buttons(site to onSite, retry to onRetry) + } +} + +@Composable +private fun Buttons(secondary: Pair Unit>?, primary: Pair Unit>) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + secondary?.let { (label, action) -> TextButton(onClick = action) { Text(label) } } + Button(onClick = primary.second) { Text(primary.first) } + } +} + +@Composable +private fun Link(text: String, onClick: () -> Unit) { + Row( + Modifier.heightIn(min = 48.dp).clickable(role = Role.Button, onClick = onClick), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.primary) + } +} + +/// The «Updates» block of About (android-ui.md §25.5). +@Composable +fun AboutUpdates() { + val updates = app().updates + val state by updates.state.collectAsState() + val check by updates.check.collectAsState() + val auto by updates.auto.collectAsState() + val offer by updates.offer.collectAsState() + val last by updates.lastCheck.collectAsState() + val context = LocalContext.current + Column(Modifier.fillMaxWidth()) { + Text( + stringResource(R.string.upd_group), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.semantics { heading() }, + ) + Spacer(Modifier.height(8.dp)) + val s = state + if (s == null) { + // Said only after a check that got an answer. + if (last > 0 || check == CheckState.Latest) Text(stringResource(R.string.upd_latest), style = MaterialTheme.typography.bodyLarge) + } else { + Text(stringResource(R.string.upd_title, s.update.version), style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium) + Text( + stringResource(R.string.upd_you_have, BuildConfig.VERSION_NAME), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + when (s) { + is UpdateState.Downloading -> { + LinearProgressIndicator(progress = { s.done.toFloat() / s.update.apkSize.coerceAtLeast(1) }, modifier = Modifier.fillMaxWidth()) + Text( + if (s.waitingNetwork) stringResource(R.string.upd_waiting_net_short) else stringResource(R.string.downloaded_of, mb(s.done), mb(s.update.apkSize)), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + ) + } + is UpdateState.Busy -> { + LinearProgressIndicator(Modifier.fillMaxWidth()) + Text(stepText(s.step), style = MaterialTheme.typography.bodyMedium) + } + is UpdateState.Failed -> Text(shortProblem(s.problem), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error) + else -> {} + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + when (s) { + is UpdateState.Ready -> Button(onClick = { + updates.openSheet() + updates.install() + }) { Text(stringResource(R.string.upd_install)) } + is UpdateState.Downloading, is UpdateState.Busy -> TextButton(onClick = { updates.openSheet() }) { Text(stringResource(R.string.upd_more)) } + is UpdateState.Failed -> TextButton(onClick = { updates.openSheet() }) { Text(stringResource(R.string.upd_more)) } + else -> Button(onClick = { + updates.openSheet() + updates.start() + }) { Text(stringResource(R.string.upd_update)) } + } + } + } + // The card on «Databases» (its × turns this off); the check below goes on either way. + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 72.dp) + .toggleable(value = offer, enabled = auto, role = Role.Switch, onValueChange = { updates.setOffer(it) }), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(stringResource(R.string.upd_offer), style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + Switch(checked = offer, enabled = auto, onCheckedChange = null) + } + Text( + stringResource(if (auto) R.string.upd_offer_sub else R.string.upd_offer_needs_check), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 72.dp) + .toggleable(value = auto, role = Role.Switch, onValueChange = { updates.setAuto(it) }), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(stringResource(R.string.upd_auto), style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + Switch(checked = auto, onCheckedChange = null) + } + Text(stringResource(R.string.upd_auto_sub), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (check == CheckState.Checking) { + Row(Modifier.heightIn(min = 48.dp), verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) + Spacer(Modifier.width(12.dp)) + Text(stringResource(R.string.upd_checking), style = MaterialTheme.typography.bodyMedium) + } + } else { + // Not while an update is downloaded or installed: the check waits for it. + val busy = s is UpdateState.Downloading || s is UpdateState.Busy || s is UpdateState.NeedsPermission + TextButton(onClick = { updates.checkNow() }, enabled = !busy, contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)) { + Text(stringResource(R.string.upd_check_now)) + } + } + when (check) { + CheckState.Offline -> Text(stringResource(R.string.upd_check_offline), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error) + CheckState.Failed -> Text(stringResource(R.string.upd_check_failed), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error) + else -> {} + } + if (last > 0) { + // «today, 14:05» inside the sentence: Android writes it from a capital. + val whenText = DateUtils.getRelativeDateTimeString(context, last, DateUtils.DAY_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0) + .toString().replaceFirstChar { it.lowercaseChar() } + Text(stringResource(R.string.upd_checked, whenText), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +/// The second line of «About» in Settings while a newer version is known (§25.5). +@Composable +fun aboutUpdateLine(): String? { + val updates = app().updates + val state by updates.state.collectAsState() + val auto by updates.auto.collectAsState() + val asked by updates.asked.collectAsState() + val s = state ?: return null + if (!auto && !asked && s is UpdateState.Available) return null + return when (s) { + is UpdateState.Downloading, is UpdateState.Busy -> stringResource(R.string.s_about_downloading, s.update.version) + is UpdateState.Ready -> stringResource(R.string.s_about_ready, s.update.version) + else -> stringResource(R.string.s_about_available, s.update.version) + } +} + +/// Shows the update's messages in a screen's snackbar (only one screen is on at a time). +@Composable +fun UpdateMessages(snackbar: SnackbarHostState) { + val updates = app().updates + val message by updates.message.collectAsState() + val ready = stringResource(R.string.upd_ready_snack) + val install = stringResource(R.string.upd_install) + val cancelled = stringResource(R.string.download_cancelled) + val latest = stringResource(R.string.upd_latest) + val doneText = (message as? UpdateMessage.Updated)?.let { stringResource(R.string.upd_done_snack, it.from, it.to) } + // Marked shown when its snackbar is gone: a screen left meanwhile hands it to the next. + LaunchedEffect(message) { + val m = message ?: return@LaunchedEffect + snackbar.currentSnackbarData?.dismiss() + when (m) { + UpdateMessage.Ready -> { + if (snackbar.showSnackbar(ready, install, duration = SnackbarDuration.Long) == SnackbarResult.ActionPerformed) { + updates.openSheet() + updates.install() + } + } + UpdateMessage.Cancelled -> snackbar.showSnackbar(cancelled) + UpdateMessage.Latest -> snackbar.showSnackbar(latest) + is UpdateMessage.Updated -> snackbar.showSnackbar(doneText ?: "", duration = SnackbarDuration.Long) + } + updates.shown(m) + } +} diff --git a/androidApp/app/src/main/res/drawable-nodpi/penguin.png b/androidApp/app/src/main/res/drawable-nodpi/penguin.png new file mode 100644 index 0000000..9caf333 Binary files /dev/null and b/androidApp/app/src/main/res/drawable-nodpi/penguin.png differ diff --git a/androidApp/app/src/main/res/font/figurines.ttf b/androidApp/app/src/main/res/font/figurines.ttf new file mode 100644 index 0000000..dbc3e1b Binary files /dev/null and b/androidApp/app/src/main/res/font/figurines.ttf differ diff --git a/androidApp/app/src/main/res/font/nag_symbols.ttf b/androidApp/app/src/main/res/font/nag_symbols.ttf new file mode 100644 index 0000000..3134da8 Binary files /dev/null and b/androidApp/app/src/main/res/font/nag_symbols.ttf differ diff --git a/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..1451b6a --- /dev/null +++ b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..1451b6a --- /dev/null +++ b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..9548278 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp differ diff --git a/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp new file mode 100644 index 0000000..53fad10 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp differ diff --git a/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..b7a79cb Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp differ diff --git a/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp new file mode 100644 index 0000000..2591fdf Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..a3ce542 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp new file mode 100644 index 0000000..fba761a Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..52a6030 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp new file mode 100644 index 0000000..86383ab Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..72d64e0 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp new file mode 100644 index 0000000..6a139b9 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp differ diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml new file mode 100644 index 0000000..d5bc812 --- /dev/null +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -0,0 +1,724 @@ + + Klassische Partien + Aljechin + + Hier erscheinen Ihre Datenbanken + Fügen Sie eine PGN-Datei, eine ChessBase-Datenbank oder ein .zip/.7z-Archiv hinzu – vom Telefon oder aus der Cloud – oder laden Sie Partien von Lichess und Chess.com. + Datenbank hinzufügen + Beispielpartien öffnen + noch nicht geöffnet · %1$s + + %1$s Partie + %1$s Partien + + %1$s · %2$s + Menü + Umbenennen + Aus der Liste entfernen + Der Name in der Liste. Die Datei wird nicht geändert. + Abbrechen + Speichern + Datenbank aus der Liste entfernt + Rückgängig + Zurück + + Wird gelesen… + Datenbank konnte nicht geöffnet werden + Suchen + Spieler, Turnier, Jahr + Nichts gefunden + Leeren + + %1$d von %2$d + Vorherige Partie + Nächste Partie + Brett drehen + Zum Anfang + Zug zurück + Zug vor + Vorheriger Zug. Gedrückt halten: zum Anfang + Nächster Zug. Gedrückt halten: zum Ende der Variante + Zum Ende der Variante + Weiter: + Brett, Stellung nach %1$s + Brett, Ausgangsstellung + Weiß hat gewonnen + Schwarz hat gewonnen + Remis + Partie konnte nicht gelesen werden + + Engine + Rechnet… + Tiefe %1$d + pausiert + Tiefer + Mehr Varianten + Weniger Varianten + Die Engine antwortet nicht + Die Engine startet auf diesem Telefon nicht + Neu starten + Engine-Variante · Zug %1$d von %2$d + Schließen + Stockfish-Engine + Bewertet die Stellung und zeigt die besten Züge. Funktioniert offline — sie muss nur einmal heruntergeladen werden. + Größe: %1$d MB + Gerade kein WLAN: Der Download nutzt mobile Daten. + Nicht jetzt + Herunterladen + %1$d von %2$d MB heruntergeladen + Abbrechen + Download abgebrochen + Die Engine ist bereit + Kein Internet. Verbinden Sie sich mit einem Netzwerk und versuchen Sie es erneut. + ChessPenguin: Stockfish-Engine + Der Download wurde unterbrochen. Bitte versuchen Sie es erneut. + Nicht genug Speicherplatz: %1$d MB nötig. + Die Engine-Datei wurde beim Download beschädigt. Laden Sie sie erneut herunter. + Erneut versuchen + Erneut herunterladen + OK + Engine wird vorbereitet… + + Einstellungen + Darstellung + Engine + Design + Systemstandard + Hell + Dunkel + Zugnotation + Englische Buchstaben (K Q R B N) + Figurinen + Deutsche Buchstaben (K D T L S) + Nur zur Anzeige. PGN verwendet immer K Q R B N. + Figurenanimation + Pfeil für den besten Zug + Vibration + Stockfish 19 · eingebaut + Stockfish 19 · heruntergeladen + Nicht geladen · Herunterladen (%1$d MB) + Wird heruntergeladen… %1$d von %2$d MB + Engine löschen (gibt %1$d MB frei) + Engine löschen? Sie können sie erneut herunterladen. + Löschen + Varianten + Zeit pro Stellung + %1$d s + 1 min + Unbegrenzt + Threads + Speicher + %1$d MB + Die Engine verbraucht Akku. Sie schaltet sich von selbst aus, wenn Sie die Partie verlassen oder die App in den Hintergrund geht. + Über + Stockfish eingebaut + Stockfish wird in der App geladen + Schachdatenbanken, Partieanalyse und Spiel gegen den Computer. Ihre Dateien werden nur gelesen, nie geändert. + Lizenzen und Autoren + Website und Quellcode + + Partiedaten + PGN kopieren + FEN kopieren + Partie teilen + Hinweise + an + aus + nicht geladen + %1$s von %2$s gefunden + Partie + %1$d, Weiß, %2$s + %1$d, Schwarz, %2$s + aktueller Zug + Sprache + Matt + Patt + PGN kopiert + FEN kopiert + Turnier + Ort + Datum + Runde + Weiß + Schwarz + Ergebnis + Elo Weiß + Elo Schwarz + Kommentator + Halbzüge + Kein Zugriff auf die Datei: Sie wurde verschoben, gelöscht oder die Berechtigung wurde entzogen. Entfernen Sie sie aus der Liste und fügen Sie sie erneut hinzu. + Die Datei ist beschädigt oder keine Schachdatenbank. + Im Archiv ist keine PGN- oder ChessBase-Datenbank. + Diese Art von Datenbank kann nicht gelesen werden: %1$s + Datei + PGN, .cbv, .zip oder .7z + Ordner + Alle Datenbanken in einem Ordner, auch ChessBase (.cbh) + Datenbanken werden gesucht… + Keine Datenbanken in diesem Ordner + Gefunden werden PGN-Dateien, ChessBase-Datenbanken (.cbh, .cbv) und .zip- oder .7z-Archive – im Ordner und in zwei Ebenen von Unterordnern. + schon in der Liste + die .cbg-Datei fehlt: die Partien lassen sich nicht öffnen + + %1$d Datenbank in „%2$s“ + %1$d Datenbanken in „%2$s“ + + + %1$d hinzufügen + %1$d hinzufügen + + + %1$d Datenbank hinzugefügt + %1$d Datenbanken hinzugefügt + + Android lässt weder den Speicherstamm noch „Downloads“ selbst auswählen — nur einen Ordner darin. + Anderen wählen + Fertig + Hinzufügen + Alle auswählen + Keine auswählen + Die Datei %1$s liegt nicht mehr neben der Datenbank: Sie wurde verschoben oder gelöscht. + Brett und Figuren + Braun + Blau + Grün + Turnier + Sand + Koralle + Grau + Lila + Eis + Marineblau + Minze + Smaragd + Orange + Rosa + Dämmerung + Nacht + Holz + Ahorn + Leder + Marmor + Blauer Marmor + Leinwand + Metall + Olive + Stein + Grünes Plastik + Lila Diagonalen + Rosa Pyramiden + Skizze + Brett + Figuren + Nr. %1$s + PGN aus der Zwischenablage einfügen + In einer anderen App kopierte Partien + Keine PGN-Partien in der Zwischenablage + Eingefügt am %1$s + + Partie in der Zwischenablage + Partien in der Zwischenablage + + Diese PGN-Partie speichern und auf dem Brett öffnen? + %1$s speichern und die erste Partie auf dem Brett öffnen? Alle Partien bleiben in der lokalen Kopie. + Öffnen + Zwischenablage + Datei wird geöffnet… + Die Datei ließ sich nicht öffnen + Diese Datei enthält keine Schachpartien. + Die Datei ließ sich nicht lesen: Sie existiert nicht mehr, oder die App, aus der sie stammt, hat keinen Zugriff gewährt. Öffnen Sie sie erneut. + Eine ChessBase-Datenbank (.cbh) besteht aus mehreren Dateien, gekommen ist nur eine. Fügen Sie ihren Ordner hinzu: „Datenbank hinzufügen“ → „Ordner“. + Die App konnte keine Kopie der Datei speichern. Prüfen Sie, ob auf dem Telefon Platz frei ist. + Kopie + Datenbank aus ChessPenguin gelöscht + + Partieanalyse + Partiebericht + Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert. + %d s + %d Min. + Analysieren + Ergänzen + %1$d von %2$d Stellungen sind schon bewertet. + Partieanalyse · %1$d von %2$d + Analyse anhalten + Genauigkeit + Genauigkeit: Weiß %1$s, Schwarz %2$s + Bericht + besser war %1$s + Ungenauigkeit + Fehler + Grober Fehler + Ungenauigkeiten + Fehler + Grobe Fehler + Starker Zug + Brillanter Zug + Starke Züge + Brillante Züge + Ohne Bewertung: %d + Die Analyse wurde unterbrochen + Fortsetzen + Durchschnittlicher Centibauernverlust + Eröffnung + Mittelspiel + Endspiel + %1$s · %2$s Knoten pro Zug + Bewertungen aus der PGN ([%eval]) + !! und ! braucht die Engine: die PGN enthält nur Bewertungen + In dieser Analyse wurde noch nicht nach !! und ! gesucht + Analyse mit anderen Engine-Einstellungen gemacht + Aktualisieren + Mit der Engine analysieren + Analyse ausblenden + Bewertungsgrafik + Pausiert: Partie wird analysiert + Bessere Variante · Zug %1$d von %2$d + Zum nächsten solchen Zug + Die bessere Variante auf dem Brett zeigen + %1$s, Bewertung %2$s + Ausgangsstellung + + %1$d Stellung, etwa %2$s + %1$d Stellungen, etwa %2$s + + + Partien von Lichess und Chess.com + Partien beliebiger Spieler per Nickname: eigene, eines Schülers, eines Gegners + Die Partien des Spielers werden zu einer Datenbank auf dem Telefon – zum Suchen, Ansehen und Analysieren. Nur der Nickname ist nötig, keine Anmeldung. + Nickname des Spielers + wie auf der Seite + Anderer Nickname auf Chess.com + Nickname auf Chess.com + Derselbe Nickname + Lateinische Buchstaben, Ziffern, _ und -, 2 bis 30 Zeichen + Suchen + Suche auf den Seiten… + %1$s · beim ersten Mal etwa %2$d Min. + Monate mit Partien: %1$d + %1$s: kein Spieler mit diesem Nickname – Schreibweise prüfen + Beide Seiten in einer Datenbank zusammenführen + Sonst bekommt jede Seite eine eigene Datenbank + In die neue Datenbank „%1$s“ + In „%1$s“ (schon %2$s dort; nur neue Partien kommen dazu) + Herunterladen + Lichess: %1$s von etwa %2$s · noch etwa %3$d Min. + %1$s: %2$s + Chess.com: Monat %1$d von %2$d · %3$s + Anhalten + +%1$s, insgesamt %2$s + Keine neuen Partien, %1$s in der Datenbank + Angehalten, %1$s in der Datenbank + Dort gibt es keine Partien im Standardschach. + Datenbank öffnen + Erneut versuchen + %1$s antwortet nicht. Prüfen Sie die Internetverbindung und versuchen Sie es erneut. + %1$s bittet um eine Pause: zu viele Anfragen hintereinander. Warten Sie eine Minute und versuchen Sie es erneut; Geladenes bleibt erhalten. + %1$s hat unverständlich geantwortet: die Seite hat sich vielleicht geändert. Versuchen Sie es später oder aktualisieren Sie ChessPenguin. + Die Datenbank konnte nicht geschrieben werden: auf dem Telefon ist kein Platz mehr. + Diese Datenbank wird bereits geladen. + %1$s antwortet nicht + %1$s bittet um eine Pause + Der Download wurde unterbrochen + Neue Partien laden + Download anhalten + Wird geladen · %1$s + aktualisiert %1$s + unvollständig + Geladene Datenbank gelöscht + Nickname auf Lichess + %1$s · beim ersten Mal unter einer Minute + Sie können diesen Bildschirm verlassen: die Datenbank ist in der Liste, der Download läuft weiter. + Fertig: %1$s + gerade aktualisiert + „%1$s“: +%2$s, insgesamt %3$s + „%1$s“: keine neuen Partien + „%1$s“: %2$s + Öffnen + + bis zu %1$s Partie + bis zu %1$s Partien + + Version %1$s ist erschienen + Sie haben %1$s + Aktualisieren + Installieren + Datenbanken, Einstellungen und die Engine bleiben erhalten. + Datenbanken und Einstellungen bleiben erhalten. + ChessPenguin schließt sich während der Installation — öffnen Sie es danach wieder. + Partien werden gerade heruntergeladen: Die Installation unterbricht den Download, danach können Sie ihn fortsetzen. + Eine Berechtigung ist nötig + Android installiert Apps außerhalb eines Stores nur mit Ihrer Erlaubnis. Die Einstellungen öffnen sich: Aktivieren Sie den Schalter für ChessPenguin und kehren Sie zurück. + Einstellungen öffnen + Die Berechtigung ist deaktiviert — ohne sie installiert Android die neue Version nicht. + Berechtigung erteilt, Download läuft + Von der Website herunterladen + Website öffnen + Sie können dieses Fenster schließen: Der Download läuft weiter. + Kein Netz. Der Download läuft von selbst weiter, sobald das Netz zurück ist. + Wartet auf Netz + Datei wird geprüft… + Engine wird gesichert… + Wird installiert… + Die neue Version ist heruntergeladen und geprüft. + Heruntergeladen und geprüft + Die neue Version ist heruntergeladen + Installation abgebrochen. Die neue Version ist heruntergeladen — installieren Sie sie, wann es Ihnen passt. + ChessPenguin-Update + ChessPenguin wurde aktualisiert: %1$s → %2$s + Der Download ist fehlgeschlagen. Versuchen Sie es erneut. + Die Datei wurde beim Herunterladen beschädigt und deshalb nicht installiert. Versuchen Sie es erneut. + Mit dieser Version stimmt etwas nicht: Die Android-Datei lässt sich nicht prüfen. Laden Sie die neue Version von der Website herunter. + Android hat die neue Version nicht installiert: zu wenig Speicher. Geben Sie %1$d MB frei und versuchen Sie es erneut. + Android hat die neue Version nicht installiert: Dieses ChessPenguin ist mit einem anderen Schlüssel signiert. Die neue Version lässt sich erst nach dem Entfernen dieser installieren, und dabei gehen die Datenbankliste und die heruntergeladenen Datenbanken verloren. + Android oder der Schutz des Telefons hat die Installation gestoppt. Laden Sie die neue Version von der Website herunter. + Android hat die neue Version nicht installiert. Versuchen Sie es erneut oder laden Sie sie von der Website herunter. + Kein Internet + Zu wenig Speicher + Die Datei ist beschädigt + Von Android nicht installiert + Download fehlgeschlagen + Mehr erfahren + Details + Kopieren + Updates + Beim Start nach Updates suchen + Einmal am Tag fragt ChessPenguin seine Website nach der neuesten Version; die Website zählt laufende Installationen. Gesendet werden nur eine Zufallsnummer dieser Installation, die Version und das System. Die Prüfung läuft auch ohne Angebote. + Neue Versionen anbieten + Eine Karte auf dem Bildschirm Datenbanken, wenn eine neue Version erscheint. + Funktioniert, wenn die Update-Prüfung eingeschaltet ist. + Wird nicht mehr angeboten. Einschalten unter Einstellungen, Über + Keine Updates anbieten + Jetzt prüfen + Wird geprüft… + Sie haben die neueste Version + Zuletzt geprüft: %1$s + Kein Internet — Updates lassen sich nicht prüfen + Updates konnten nicht geprüft werden: Die Website hat nicht geantwortet. Später erneut versuchen. + Version %1$s ist erschienen + Version %1$s wird heruntergeladen… + Version %1$s ist heruntergeladen + Update auf %1$s, %2$d von %3$d Megabyte heruntergeladen + Datei lässt sich nicht prüfen + Rückgängig + Züge gelöscht + Zur Hauptvariante machen + Zug und Fortsetzung löschen + Aktionen zum Zug + Neue Partie + Meine Datenbanken + + Neue Datenbank + Hier stehen die Partien, die Sie eingeben oder gegen den Computer spielen + + Hinzufügen + Hier stehen PGN- und ChessBase-Dateien, Ordner und Partien aus dem Internet, die Sie hinzufügen + Dateien + Meine Partien + Neue Datenbank + Name + Wird auf dem Telefon in ChessPenguin gespeichert. Die Datei lässt sich im Menü der Datenbank exportieren. + Erstellen + auf dem Telefon + Datei exportieren… + Datenbank löschen + Datei gespeichert + Die Datei konnte nicht gespeichert werden + Datenbank gelöscht + „%1$s“ löschen? + + %1$s Partie wird vom Telefon gelöscht. Wenn Sie sie brauchen, exportieren Sie zuerst die Datei. + %1$s Partien werden vom Telefon gelöscht. Wenn Sie sie brauchen, exportieren Sie zuerst die Datei. + + In „%1$s“ gespeichert, Nr. %2$s + Die Partie konnte nicht gespeichert werden + In „%1$s“ speichern + In meiner Datenbank speichern… + In einer Datenbank speichern + In einer Datenbank speichern… + Neue Datenbank… + Erstellen und speichern + Änderungen in „%1$s“ speichern? + Partie speichern? + Nicht speichern + Partiedaten + JJJJ.MM.TT + Kein Datum: 2026.10.26, 2026 oder 26.10.2026 + Änderungen verwerfen? + Verwerfen + Weiter bearbeiten + Bearbeiten + Weiter + Eröffnung lernen + bis %1$s + Eröffnung bis zu diesem Zug lernen + Zug %1$s von %2$s + ♔ Weiß am Zug + ♚ Schwarz am Zug + Fehler: %1$s + Durchgang %1$s + × In der Partie folgt hier ein anderer Zug + Zug zeigen + Diese Linie noch nicht geübt + Zuletzt: %1$s · fehlerfrei in Folge: %2$s + Zuletzt: %1$s · Bestwert: %2$s + Fehlerfrei geschafft + Mit Hinweis geschafft · Fehler: %1$s + Geschafft · Fehler: %1$s + Durchgang %1$s · Bestwert: %2$s + fehlerfrei in Folge: %1$s + Letzte: %1$s + Spielen Sie den Zug des Pfeils + ↻ Noch einmal + ⬅ Zurück zur Partie + Von vorn + + %1$d Durchgang + %1$d Durchgänge + + Maia für ChessPenguin + Sie haben gewonnen + Sie haben verloren + Sie haben aufgegeben + Remis + Schachmatt + Patt + die Stellung ist dreimal aufgetreten + 50 Züge ohne Schlagen oder Bauernzug + keine Seite kann mattsetzen + Maia hat aufgegeben + Aufgeben? + ⚑ Aufgeben + ↶ Zurücknehmen + Gegen den Computer spielen + Ihre Farbe + Weiß + Schwarz + Zufällig + Die eigene Wertung von Maia: sie entspricht nicht der Elo eines Menschen. + Maia wird einmalig heruntergeladen (%1$s MB, von huggingface.co, die Datei der Autoren selbst). + Herunterladen und spielen + Spielen + denkt nach… + Partie gegen den Computer + Analysieren + ↻ Revanche + Von hier aus spielen… + Wird geprüft… + Maia ist nicht gestartet: %1$s + Sieg annehmen + Zu Ende spielen + Maia gibt auf + Ab hier eine Partie gegen Maia %1$s. + Abbrechen + Ihr Name + Maia ist heruntergeladen + Erneut versuchen + Ihre Stellung ist verloren. Sieg annehmen oder weiterspielen? + Fortsetzen + Partie gegen Maia %1$s · Sie spielen %2$s + Weiß + Schwarz + Partie entfernt + ohne Uhr + Sie + ✓ Gespeichert + Speichern… + Sie spielen %1$s · %2$s + Nach %1$s + Ton + Rückgängig + Jetzt die Hauptvariante + Elo + Analyse + Weiterspielen + Ansicht %1$s · zurück zur Partie › + die Ausgangsstellung + Maia ist nicht gestartet. + Maia neu herunterladen + Eine Partie gegen %1$s ist zurückgestellt + Fortsetzen + Neue beginnen + Eine neue Partie ersetzt sie; das Gespielte kommt unvollendet in die Datenbank des Spielers. + Remis + durch Einigung + Maia lehnt das Remis ab + Maia hat abgelehnt; nach zwei ihrer Züge wieder anbieten + Maia beantwortet Remis mit Stockfish: über „Engine“ herunterladen + %1$s — Partien gegen den Computer + Partien gegen den Computer + ✓ In „%1$s“, Nr. %2$s › + Partie unvollendet in „%1$s“ gespeichert + werden selbst gespeichert + Partien gegen den Computer in die Datenbank des Spielers schreiben + Partien werden in „%1$s“ gespeichert + Die Partien werden in eine neue Datenbank „%1$s“ gespeichert. + Ohne Namen gehen die Partien in „%1$s“. Geben Sie einen Namen ein, um eine eigene Datenbank zu bekommen. + Partien werden nicht von selbst gespeichert (Einstellungen). + ✓ Neue Datenbank „%1$s“, Nr. %2$s › + Konnte nicht in „%1$s“ schreiben: %2$s + Eine neue Partie ersetzt sie. + Zuletzt geöffnet + Partie gegen %1$s + Zug %1$d + + Amanda + Greift zuerst an, spielt dann auf aktive Figuren. + Cloe + Mag geschlossene Stellungen. + Deborah + Verteidigt gut und mag ihre Läufer. + Verteidiger + Solide und vorsichtig; mit Remis zufrieden. + Dynamiker + Greift an, mag Läufer, opfert ab und zu. + Brummbär + Angriff und Einengung; mag blockierte Stellungen, meidet Remis. + Partisan + Greift nach ruhigen, unauffälligen Eröffnungen an. + Bauernopferer + Ausgewogen, gibt aber eher Bauern her. + Pedrita + Bauern, Verteidigung und Einengung. + Preston + Ein materialistischer, maßvoller Angreifer. + Schlicht + Am computerhaftesten: schlichtes, solides Schach. + Hitzkopf + Scharf und aggressiv. + Würger + Eine Würgeschlange: würgt langsam, sehr menschlich. + Aljechin + Dynamische Angriffe und tiefe Kombinationen. + Anand + Schnelles, universelles Spiel mit scharfen Eröffnungen. + Anderssen + Ein romantischer Angreifer des 19. Jahrhunderts: Opfer. + Bosboom + Ausgefallene Eröffnungen und kreatives Blitzspiel. + Botvinnik + Wissenschaftliches, strategisches Spiel aus tiefer Vorbereitung. + Fischer + Klar, klassisch und präzise. + Karpov + Positioneller Druck, Prophylaxe und Technik. + Kasparov + Initiative und kraftvoller Angriff. + Kortchnoi + Ein zäher Verteidiger und Konterspieler. + Larsen + Originell und riskant, mit ausgefallenen Eröffnungen. + Lasker + Ein praktischer, psychologischer Kämpfer. + Marshall + Ein verwegener Angreifer mit Gambits. + Morphy + Schnelle Entwicklung und offene Linien. + Nimzowitsch + Einengung, Blockade und Überdeckung. + Petrosian + Prophylaxe und Sicherheit zuerst. + Reti + Hypermodern: kontrolliert das Zentrum aus der Ferne. + Rubinstein + Klassisches Positionsspiel, stark im Endspiel. + Spassky + Ein Universalspieler, in jeder Stellung zu Hause. + Steinitz + Der Begründer des Positionsspiels, ein hartnäckiger Verteidiger. + Tal + Der Zauberer aus Riga: Opfer und Angriff. + Tarrasch + Klassische Regeln: Raum, Entwicklung, aktive Figuren. + Topalov + Aggressiv und dynamisch, opfert die Qualität. + spielt wie ein Mensch + stark, mit Stil + Wie ein Mensch + Maia wählt keinen Stil: Sie spielt wie Menschen ihrer Wertung. + Die eigene Wertung von Rodent (UCI_Elo): sie entspricht nicht der Elo eines Menschen. + Rodent gibt auf + Rodent hat aufgegeben + Rodent lehnt das Remis ab + Rodent hat abgelehnt; nach zwei seiner Züge wieder anbieten + Seine Stellung ist verloren. Sieg annehmen oder zu Ende spielen? + Spielen + Gegen den Computer spielen + Spielstärke: %1$s + Gegen wen spielen + Ein Charakter ist ein Stil mit seinen Eröffnungen; die Spielstärke stellt der Schieberegler ein. + Große Spieler + Charaktere + Ändern + %1$s, großer Spieler + %1$s, Charakter + Charakter: %1$s + Rodent IV und seine Eröffnungsbücher sind auf dem Telefon + Eröffnungsbücher von Rodent IV: %1$s MB, einmalig von github.com + Aus einer Stellung heraus ist kein Eröffnungsbuch nötig: Rodent IV spielt sofort + Ohne Buch + Ohne Buch: ohne Eröffnungsbuch spielen + Eröffnungsbücher von Rodent IV + Rodent IV — Eröffnungsbücher + heruntergeladen · %1$s MB + nicht heruntergeladen · %1$s MB + Eröffnungsbücher gelöscht + Rodent beantwortet Remis mit Stockfish: über „Engine“ herunterladen + Rodent ist nicht gestartet. + Neu starten + Ab hier eine Partie gegen Rodent IV %1$s · %2$s. + Rodent hat während der Partie aufgehört. + %1$s, von %2$s bis %3$s + Spielstärke + Eröffnungsbücher löschen + + + Spieler + Spielername + Spieler konnten nicht gelesen werden + Spieler werden gelesen… + Diese Datenbank enthält keine benannten Spieler + Spieler nicht gefunden + Zu den Partien + Suche zurücksetzen + Vorbereiten + Farbe wählen + Vorbereiten gegen %1$s + Gegen Weiß + Gegen Schwarz + Auf Gegner vorbereiten… + Vorbereitung auf den Gegner + Schließen Sie zuerst die Engine-Variante + + Suche nach einem Lehrzug -- ist nicht verfügbar + Weiß + Schwarz + Dieser Zug konnte nicht ausgeführt werden + %1$s spielen, %2$s, %3$s Prozent + Brett, Ausgangsstellung. %1$s unten. + Brett, Stellung nach %1$s. %2$s unten. + Weiß am Zug + Schwarz am Zug + Gegner spielt + Seine Gegner spielen + nach %1$s + Anfang + %1$s, %2$s, %3$s, %4$s + Fortsetzungen konnten nicht berechnet werden + Nicht genügend Speicher für die Suche in dieser Datenbank + Fortsetzungen werden berechnet… + Diese Stellung kommt in Partien von %1$s nicht vor + Sie können auf dem Brett fortsetzen oder zurückgehen + Alle Partien endeten hier + Hier beendet: %1$s + Keine normale Fortsetzung: %1$s + Zur Partie + Zu den Spielern + Zug auswählen + %1$s Sieg%1$s Siege + %1$s Remis%1$s Remis + %1$s Niederlage%1$s Niederlagen + Unbekannte Ergebnisse: %1$d; nicht in den Prozentwerten enthalten. + %1$s. %2$d von %3$s, %4$s Prozent. Ergebnisse für %5$s: %6$s, %7$s, %8$s; %9$s, %10$s und %11$s Prozent. %12$s Spielen. + Spielen + weitere %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml new file mode 100644 index 0000000..80bd056 --- /dev/null +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -0,0 +1,733 @@ + + Partidas clásicas + Alekhine + + Aquí aparecerán tus bases + Añade un archivo PGN, una base ChessBase o un archivo .zip/.7z — desde el teléfono o la nube — o descarga partidas de Lichess y Chess.com. + Añadir base + Abrir partidas de ejemplo + aún sin abrir · %1$s + + %1$s partida + %1$s de partidas + %1$s partidas + + %1$s · %2$s + Menú + Cambiar nombre + Quitar de la lista + El nombre en la lista. El archivo no se modifica. + Cancelar + Guardar + Base quitada de la lista + Deshacer + Atrás + + Leyendo… + No se pudo abrir la base + Buscar + Jugador, torneo, año + No se encontró nada + Borrar + + %1$d de %2$d + Partida anterior + Partida siguiente + Girar el tablero + Al inicio + Jugada atrás + Jugada adelante + Jugada anterior. Mantén pulsado para ir al inicio + Jugada siguiente. Mantén pulsado para ir al final de la línea + Al final de la línea + Siguiente: + Tablero, posición tras %1$s + Tablero, posición inicial + Ganaron las blancas + Ganaron las negras + Tablas + No se pudo leer la partida + + Motor + Pensando… + profundidad %1$d + en pausa + Más profundo + Más líneas + Menos líneas + El motor no responde + El motor no arranca en este teléfono + Reiniciar + Línea del motor · jugada %1$d de %2$d + Cerrar + Motor Stockfish + Evalúa la posición y muestra las mejores jugadas. Funciona sin conexión — solo hay que descargarlo una vez. + Tamaño: %1$d MB + Ahora no hay Wi-Fi: la descarga usará datos móviles. + Ahora no + Descargar + Descargados %1$d de %2$d MB + Cancelar + Descarga cancelada + El motor está listo + Sin Internet. Conéctate a una red e inténtalo de nuevo. + ChessPenguin: motor Stockfish + La descarga se detuvo. Inténtalo de nuevo. + No hay espacio suficiente: se necesitan %1$d MB. + El archivo del motor se dañó durante la descarga. Descárgalo de nuevo. + Reintentar + Descargar de nuevo + Aceptar + Preparando el motor… + + Ajustes + Apariencia + Motor + Tema + Predeterminado del sistema + Claro + Oscuro + Notación de jugadas + Letras inglesas (K Q R B N) + Figurines + Letras españolas (R D T A C) + Solo para mostrar. PGN siempre usa K Q R B N. + Animación de piezas + Flecha de la mejor jugada + Vibración + Stockfish 19 · incluido + Stockfish 19 · descargado + No descargado · Descargar (%1$d MB) + Descargando… %1$d de %2$d MB + Eliminar el motor (libera %1$d MB) + ¿Eliminar el motor? Puedes volver a descargarlo. + Eliminar + Líneas + Tiempo por posición + %1$d s + 1 min + Sin límite + Hilos + Memoria + %1$d MB + El motor consume batería. Se apaga solo cuando sales de la partida o la aplicación pasa a segundo plano. + Acerca de + Stockfish incluido + Stockfish se descarga en la aplicación + Bases de ajedrez, análisis de partidas y juego contra el ordenador. Tus archivos solo se leen, nunca se modifican. + Licencias y autores + Sitio web y código fuente + + Datos de la partida + Copiar PGN + Copiar FEN + Compartir partida + Notas + activado + desactivado + no descargado + Encontradas %1$s de %2$s + Partida + %1$d, blancas, %2$s + %1$d, negras, %2$s + jugada actual + Idioma + Jaque mate + Ahogado + PGN copiado + FEN copiado + Torneo + Lugar + Fecha + Ronda + Blancas + Negras + Resultado + Elo blancas + Elo negras + Comentarista + Medias jugadas + Sin acceso al archivo: se movió, se eliminó o se retiró el permiso. Quítalo de la lista y vuelve a añadirlo. + El archivo está dañado o no es una base de ajedrez. + El archivo comprimido no contiene ninguna base PGN ni ChessBase. + Este tipo de base no se puede leer: %1$s + Archivo + PGN, .cbv, .zip o .7z + Carpeta + Todas las bases de una carpeta, también ChessBase (.cbh) + Buscando bases… + No hay bases en esta carpeta + Se encuentran archivos PGN, bases de ChessBase (.cbh, .cbv) y archivos .zip o .7z, en la carpeta y en dos niveles de subcarpetas. + ya está en la lista + falta el archivo .cbg: las partidas no se pueden abrir + + %1$d base en «%2$s» + %1$d de bases en «%2$s» + %1$d bases en «%2$s» + + + Añadir %1$d + Añadir %1$d + Añadir %1$d + + + %1$d base añadida + %1$d de bases añadidas + %1$d bases añadidas + + Android no deja elegir la raíz del almacenamiento ni «Descargas» en sí: solo una carpeta dentro de ellas. + Elegir otra + Hecho + Añadir + Marcar todas + Desmarcar todas + El archivo %1$s ya no está junto a la base: se movió o se borró. + Tablero y piezas + Marrón + Azul + Verde + Torneo + Arena + Coral + Gris + Morado + Hielo + Azul marino + Menta + Esmeralda + Naranja + Rosa + Anochecer + Noche + Madera + Arce + Cuero + Mármol + Mármol azul + Lienzo + Metal + Oliva + Piedra + Plástico verde + Diagonales moradas + Pirámides rosas + Boceto + Tablero + Piezas + N.º %1$s + Pegar PGN del portapapeles + Partidas copiadas en otra aplicación + No hay partidas PGN en el portapapeles + Pegado el %1$s + + Partida en el portapapeles + Partidas en el portapapeles + Partidas en el portapapeles + + Guardar esta partida PGN y abrirla en el tablero? + Guardar %1$s y abrir la primera partida en el tablero? Todas las partidas se conservarán en la copia local. + Abrir + Portapapeles + Abriendo el archivo… + No se pudo abrir el archivo + Este archivo no contiene partidas de ajedrez. + No se pudo leer el archivo: ya no existe o la aplicación de la que viene no dio acceso. �bralo otra vez. + Una base de ChessBase (.cbh) consta de varios archivos y solo llegó uno. Añada su carpeta: «Añadir base» → «Carpeta». + La aplicación no pudo guardar una copia del archivo. Compruebe que el teléfono tiene espacio libre. + copia + Base eliminada de ChessPenguin + + Análisis de la partida + Informe de la partida + El motor evalúa cada posición de la línea principal. La partida en sí no cambia. + %d s + %d min + Analizar + Completar + Ya hay %1$d de %2$d posiciones evaluadas. + Análisis · %1$d de %2$d + Detener el análisis + Precisión + Precisión: blancas %1$s, negras %2$s + Informe + era mejor %1$s + Imprecisión + Error + Error grave + Imprecisiones + Errores + Errores graves + Gran jugada + Jugada brillante + Grandes jugadas + Jugadas brillantes + Sin evaluar: %d + El análisis se interrumpió + Continuar + Pérdida media de centipeones + Apertura + Medio juego + Final + %1$s · %2$s nodos por jugada + Evaluaciones del PGN ([%eval]) + !! y ! requieren el motor: el PGN solo trae evaluaciones + Este análisis aún no buscó !! ni ! + Análisis hecho con otros ajustes del motor + Actualizar + Analizar con el motor + Ocultar el análisis + Gráfico de evaluación + En pausa: se está analizando la partida + Mejor línea · jugada %1$d de %2$d + Ir a la siguiente jugada así + Mostrar la mejor línea en el tablero + %1$s, evaluación %2$s + Posición inicial + + %1$d posición, unos %2$s + %1$d posiciones, unos %2$s + %1$d posiciones, unos %2$s + + + Partidas de Lichess y Chess.com + Partidas de cualquier jugador por apodo: las tuyas, de un alumno, de un rival + Las partidas del jugador se convierten en una base en el teléfono, para buscar, ver y analizar. Solo hace falta el apodo, sin iniciar sesión. + Apodo del jugador + como en el sitio + Otro apodo en Chess.com + Apodo en Chess.com + El mismo apodo + Letras latinas, dígitos, _ y -, de 2 a 30 caracteres + Buscar + Buscando en los sitios… + %1$s · la primera vez unos %2$d min + meses con partidas: %1$d + %1$s: no hay ningún jugador con este apodo; revisa cómo se escribe + Unir ambos sitios en una sola base + Si no, cada sitio tendrá su propia base + En la nueva base «%1$s» + En «%1$s» (ya hay %2$s; solo se añaden las nuevas) + Descargar + Lichess: %1$s de unas %2$s · quedan unos %3$d min + %1$s: %2$s + Chess.com: mes %1$d de %2$d · %3$s + Detener + +%1$s, %2$s en total + No hay partidas nuevas, %1$s en la base + Detenido, %1$s en la base + Allí no hay partidas de ajedrez estándar. + Abrir la base + Reintentar + %1$s no responde. Comprueba la conexión a internet e inténtalo de nuevo. + %1$s pide una pausa: demasiadas solicitudes seguidas. Espera un minuto e inténtalo de nuevo; lo descargado se conserva. + %1$s respondió de una forma que ChessPenguin no entiende: quizá el sitio cambió. Inténtalo más tarde o actualiza ChessPenguin. + No se pudo escribir la base: el teléfono no tiene espacio. + Esta base ya se está descargando. + %1$s no responde + %1$s pide una pausa + La descarga se interrumpió + Descargar partidas nuevas + Detener la descarga + Descargando · %1$s + actualizada %1$s + incompleta + Base descargada eliminada + Apodo en Lichess + %1$s · la primera vez menos de un minuto + Puedes salir de esta pantalla: la base ya está en la lista y la descarga continúa. + Listo: %1$s + actualizada ahora mismo + «%1$s»: +%2$s, %3$s en total + «%1$s»: no hay partidas nuevas + «%1$s»: %2$s + Abrir + + hasta %1$s partida + hasta %1$s partidas + hasta %1$s partidas + + Ha salido la versión %1$s + Tienes la %1$s + Actualizar + Instalar + Las bases, los ajustes y el motor se conservan. + Las bases y los ajustes se conservan. + ChessPenguin se cierra durante la instalación; luego vuelve a abrirlo. + Se están descargando partidas: la instalación detendrá la descarga; luego puedes continuarla. + Hace falta un permiso + Android solo instala aplicaciones de fuera de una tienda con tu permiso. Se abrirán los ajustes: activa el interruptor para ChessPenguin y vuelve. + Abrir ajustes + El permiso está desactivado; sin él, Android no instalará la nueva versión. + Permiso concedido, descargando + Descargar desde la web + Abrir la web + Puedes cerrar esto: la descarga continúa. + Sin red. La descarga seguirá sola cuando vuelva la red. + Esperando red + Comprobando el archivo… + Guardando el motor… + Instalando… + La nueva versión está descargada y comprobada. + Descargada y comprobada + La nueva versión está descargada + Instalación cancelada. La nueva versión está descargada: instálala cuando quieras. + Actualización de ChessPenguin + ChessPenguin se ha actualizado: %1$s → %2$s + La descarga ha fallado. Inténtalo de nuevo. + El archivo se dañó al descargarse, así que no se instaló. Inténtalo de nuevo. + Algo falla en esta versión: no se puede comprobar el archivo de Android. Descarga la nueva versión en la web. + Android no ha instalado la nueva versión: no hay espacio. Libera %1$d MB e inténtalo de nuevo. + Android no ha instalado la nueva versión: este ChessPenguin está firmado con otra clave. La nueva versión solo se puede instalar tras desinstalar esta, y al desinstalarla se pierden la lista de bases y las bases descargadas. + Android o la protección del teléfono detuvo la instalación. Descarga la nueva versión en la web. + Android no ha instalado la nueva versión. Inténtalo de nuevo o descárgala en la web. + Sin internet + No hay espacio suficiente + El archivo se dañó + Android no la instaló + La descarga ha fallado + Ver más + Detalles + Copiar + Actualizaciones + Buscar actualizaciones al iniciar + Una vez al día ChessPenguin pregunta a su sitio cuál es la última versión; el sitio cuenta las instalaciones en uso. Solo se envían un número aleatorio de esta instalación, la versión y el sistema. La comprobación sigue aunque las ofertas estén desactivadas. + Ofrecer nuevas versiones + Una tarjeta en la pantalla Bases cuando sale una versión nueva. + Funciona con la comprobación de actualizaciones activada. + No lo ofreceremos más. Actívalo en Ajustes, Acerca de + No ofrecer actualizaciones + Comprobar ahora + Comprobando… + Tienes la última versión + Última comprobación: %1$s + Sin internet: no se pueden buscar actualizaciones + No se pudieron comprobar las actualizaciones: el sitio no respondió. Inténtalo más tarde. + Ha salido la versión %1$s + Descargando la versión %1$s… + La versión %1$s está descargada + Actualización a %1$s, %2$d de %3$d megabytes descargados + No se puede comprobar el archivo + Deshacer + Jugadas eliminadas + Convertir en línea principal + Eliminar la jugada y lo que sigue + Acciones de la jugada + Nueva partida + Mis bases + + Nueva base + Aquí estarán las partidas que introduzcas o juegues contra el ordenador + + Añadir + Aquí estarán los archivos PGN y ChessBase, las carpetas y las partidas de internet que añadas + Archivos + Mis partidas + Nueva base + Nombre + Se guarda en el teléfono, en ChessPenguin. El archivo se exporta desde el menú de la base. + Crear + en el teléfono + Exportar el archivo… + Eliminar la base + Archivo guardado + No se pudo guardar el archivo + Base eliminada + ¿Eliminar «%1$s»? + + Se eliminará %1$s partida del teléfono. Si la necesitas, exporta antes el archivo. + Se eliminarán %1$s partidas del teléfono. Si las necesitas, exporta antes el archivo. + Se eliminarán %1$s partidas del teléfono. Si las necesitas, exporta antes el archivo. + + Guardada en «%1$s», n.º %2$s + No se pudo guardar la partida + Guardar en «%1$s» + Guardar en mi base… + Guardar en una base + Guardar en una base… + Nueva base… + Crear y guardar + ¿Guardar los cambios en «%1$s»? + ¿Guardar la partida? + No guardar + Datos de la partida + AAAA.MM.DD + No es una fecha: 2026.10.26, 2026 o 26.10.2026 + ¿Descartar los cambios? + Descartar + Seguir editando + Editar + Siguiente + Aprendiendo la apertura + hasta %1$s + Aprender la apertura hasta esta jugada + Jugada %1$s de %2$s + ♔ Juegan blancas + ♚ Juegan negras + Errores: %1$s + Repaso %1$s + × En la partida hay otra jugada aquí + Mostrar la jugada + Línea aún no repasada + La última vez: %1$s · sin errores seguidos: %2$s + La última vez: %1$s · mejor: %2$s + Completado sin errores + Completado con pista · errores: %1$s + Completado · errores: %1$s + Repaso %1$s · mejor: %2$s + sin errores seguidos: %1$s + Recientes: %1$s + Juega la jugada de la flecha + ↻ Otra vez + ⬅ Volver a la partida + Desde el principio + + %1$d repaso + %1$d repasos + %1$d repasos + + Maia para ChessPenguin + Has ganado + Has perdido + Has abandonado + Tablas + jaque mate + rey ahogado + la posición se repitió tres veces + 50 jugadas sin capturas ni movimientos de peón + ningún bando puede dar mate + Maia se rindió + ¿Abandonar? + ⚑ Abandonar + ↶ Deshacer jugada + Jugar contra el ordenador + Tu color + Blancas + Negras + Al azar + El rating propio de Maia: no equivale al Elo de una persona. + Maia se descarga una sola vez (%1$s MB, desde huggingface.co, el archivo de los propios autores). + Descargar y jugar + Jugar + pensando… + Partida contra el ordenador + Analizar + ↻ Revancha + Jugar desde aquí… + Comprobando… + Maia no se inició: %1$s + Aceptar la victoria + Jugar hasta el final + Maia se rinde + A partir de aquí, una partida contra Maia %1$s. + Abortar + Tu nombre + Maia está descargada + Reintentar + Su posición está perdida. ¿Aceptar la victoria o seguir? + Continuar + Partida contra Maia %1$s · juegas con %2$s + blancas + negras + Partida eliminada + sin reloj + Tú + ✓ Guardada + Guardar… + juegas con %1$s · %2$s + Tras %1$s + Sonido + Deshacer + Ahora es la línea principal + Elo + Analizar + Seguir + Viendo %1$s · volver a la partida › + la posición inicial + Maia no se inició. + Volver a descargar Maia + Hay una partida aplazada contra %1$s + Continuarla + Empezar una nueva + Una partida nueva la sustituye; lo jugado va sin terminar a la base del jugador. + Tablas + por acuerdo + Maia rechaza las tablas + Maia lo rechazó; ofrece de nuevo tras dos de sus jugadas + Maia responde a las tablas con Stockfish: descárgalo con «Motor» + %1$s — partidas contra el ordenador + Partidas contra el ordenador + ✓ En «%1$s», n.º %2$s › + Partida guardada sin terminar en «%1$s» + se guardan solas + Guardar las partidas contra el ordenador en la base del jugador + Las partidas se guardan en «%1$s» + Las partidas se guardarán en una base nueva «%1$s». + Sin nombre, las partidas van a «%1$s». Escribe un nombre para tener tu propia base. + Las partidas no se guardan solas (Ajustes). + ✓ Base nueva «%1$s», n.º %2$s › + No se pudo escribir en «%1$s»: %2$s + Una partida nueva la sustituye. + Abierta por última vez + Partida contra %1$s + jugada %1$d + + Amanda + Primero ataca, luego busca piezas activas. + Cloe + Le gustan las posiciones cerradas. + Débora + Defiende bien y le gustan sus alfiles. + Defensor + Sólido y prudente; se conforma con tablas. + Dinámico + Ataca, le gustan los alfiles, sacrifica de vez en cuando. + Gruñón + Ataque y restricción; le gustan las posiciones bloqueadas, evita las tablas. + Partisano + Ataca tras aperturas tranquilas y discretas. + Gambitero + Equilibrado, pero entrega peones con más facilidad. + Pedrita + Peones, defensa y restricción. + Preston + Un atacante materialista y moderado. + Sencillo + El más «computadora»: ajedrez sencillo y sólido. + Fogoso + Agudo y agresivo. + Estrangulador + Una boa: asfixia despacio, muy humano. + Alekhine + Ataques dinámicos y combinaciones profundas. + Anand + Juego rápido y universal con aperturas agudas. + Anderssen + Un atacante romántico del siglo XIX: sacrificios. + Bosboom + Aperturas poco habituales y blitz creativo. + Botvinnik + Juego estratégico y científico, preparación profunda. + Fischer + Claro, clásico y preciso. + Karpov + Presión posicional, profilaxis y técnica. + Kasparov + Iniciativa y ataque poderoso. + Kortchnoi + Un defensor tenaz y contraatacante. + Larsen + Original y arriesgado, con aperturas inusuales. + Lasker + Un luchador práctico y psicológico. + Marshall + Un atacante audaz, amigo de los gambitos. + Morphy + Desarrollo rápido y líneas abiertas. + Nimzowitsch + Restricción, bloqueo y sobreprotección. + Petrosian + Profilaxis y seguridad ante todo. + Reti + Hipermoderno: controla el centro a distancia. + Rubinstein + Juego posicional clásico, gran finalista. + Spassky + Un jugador universal, cómodo en cualquier posición. + Steinitz + El fundador del juego posicional, un defensor obstinado. + Tal + El mago de Riga: sacrificios y ataque. + Tarrasch + Reglas clásicas: espacio, desarrollo, piezas activas. + Topalov + Agresivo y dinámico, sacrifica la calidad. + juega como una persona + fuerte, con estilo + Como una persona + Maia no elige estilo: juega como la gente de su nivel. + El rating propio de Rodent (UCI_Elo): no equivale al Elo de una persona. + Rodent se rinde + Rodent se rindió + Rodent rechaza las tablas + Rodent lo rechazó; ofrece de nuevo tras dos de sus jugadas + Su posición está perdida. ¿Aceptar la victoria o jugar hasta el final? + Jugar + Jugar contra el ordenador + Fuerza: %1$s + Contra quién jugar + Un carácter es un estilo y unas aperturas; la fuerza la marca el control deslizante. + Grandes jugadores + Caracteres + Cambiar + %1$s, gran jugador + %1$s, carácter + Carácter: %1$s + Rodent IV y sus libros de aperturas están en el teléfono + Libros de aperturas de Rodent IV: %1$s MB, una sola vez de github.com + Desde una posición no hace falta libro de aperturas: Rodent IV juega enseguida + Sin libro + Sin libro: jugar sin libro de aperturas + Libros de aperturas de Rodent IV + Rodent IV — libros de aperturas + descargados · %1$s MB + no descargados · %1$s MB + Libros de aperturas eliminados + Rodent responde a las tablas con Stockfish: descárgalo con «Motor» + Rodent no se inició. + Reiniciar + A partir de aquí, una partida contra Rodent IV %1$s · %2$s. + Rodent se detuvo durante la partida. + %1$s, de %2$s a %3$s + Fuerza + Eliminar los libros de aperturas + + + Jugadores + Nombre del jugador + No se pudieron leer los jugadores + Leyendo jugadores… + No hay jugadores con nombre en esta base + Jugador no encontrado + Volver a las partidas + Borrar búsqueda + Preparar + Elige un color + Prepararse contra %1$s + Contra las blancas + Contra las negras + Prepararse contra el rival… + Preparación contra el rival + Cierra primero la línea del motor + + La búsqueda después de un -- didáctico no está disponible + Blancas + Negras + No se pudo jugar este movimiento + Jugar %1$s, %2$s, %3$s por ciento + Tablero, posición inicial. %1$s abajo. + Tablero, posición después de %1$s. %2$s abajo. + Juegan las blancas + Juegan las negras + Juega el rival + Juegan sus rivales + después de %1$s + inicio + %1$s, %2$s, %3$s, %4$s + No se pudieron calcular las continuaciones + No hay memoria suficiente para buscar en esta base + Calculando continuaciones… + Esta posición no aparece en las partidas de %1$s + Puedes continuar en el tablero o retroceder + Todas las partidas terminaron aquí + Terminaron aquí: %1$s + Sin continuación normal: %1$s + Volver a la partida + Volver a los jugadores + Elige un movimiento + %1$s victoria%1$s victorias%1$s victorias + %1$s tabla%1$s tablas%1$s tablas + %1$s derrota%1$s derrotas%1$s derrotas + Resultados desconocidos: %1$d; excluidos de los porcentajes. + %1$s. %2$d de %3$s, %4$s por ciento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s y %11$s por ciento. %12$s Jugar. + Jugar + %1$s más + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml new file mode 100644 index 0000000..70c23c8 --- /dev/null +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -0,0 +1,733 @@ + + Parties classiques + Alekhine + + Vos bases apparaîtront ici + Ajoutez un fichier PGN, une base ChessBase ou une archive .zip/.7z — depuis le téléphone ou le cloud — ou téléchargez des parties de Lichess et Chess.com. + Ajouter une base + Ouvrir les parties d’exemple + pas encore ouverte · %1$s + + %1$s partie + %1$s de parties + %1$s parties + + %1$s · %2$s + Menu + Renommer + Retirer de la liste + Le nom dans la liste. Le fichier n’est pas modifié. + Annuler + Enregistrer + Base retirée de la liste + Annuler + Retour + + Lecture… + Impossible d’ouvrir la base + Rechercher + Joueur, tournoi, année + Rien trouvé + Effacer + + %1$d sur %2$d + Partie précédente + Partie suivante + Retourner l’échiquier + Au début + Coup précédent + Coup suivant + Coup précédent. Maintenez pour aller au début + Coup suivant. Maintenez pour aller à la fin de la ligne + À la fin de la ligne + Suite : + Échiquier, position après %1$s + Échiquier, position initiale + Les Blancs ont gagné + Les Noirs ont gagné + Nulle + Impossible de lire la partie + + Moteur + Réflexion… + profondeur %1$d + en pause + Plus loin + Plus de lignes + Moins de lignes + Le moteur ne répond pas + Le moteur ne démarre pas sur ce téléphone + Redémarrer + Ligne du moteur · coup %1$d sur %2$d + Fermer + Moteur Stockfish + Évalue la position et montre les meilleurs coups. Fonctionne hors ligne — il suffit de le télécharger une fois. + Taille : %1$d Mo + Pas de Wi-Fi pour l’instant : le téléchargement utilisera les données mobiles. + Plus tard + Télécharger + %1$d sur %2$d Mo téléchargés + Annuler + Téléchargement annulé + Le moteur est prêt + Pas d’Internet. Connectez-vous à un réseau et réessayez. + ChessPenguin : moteur Stockfish + Le téléchargement s’est arrêté. Veuillez réessayer. + Espace insuffisant : %1$d Mo nécessaires. + Le fichier du moteur a été endommagé pendant le téléchargement. Téléchargez-le à nouveau. + Réessayer + Télécharger à nouveau + OK + Préparation du moteur… + + Paramètres + Apparence + Moteur + Thème + Par défaut du système + Clair + Sombre + Notation des coups + Lettres anglaises (K Q R B N) + Figurines + Lettres françaises (R D T F C) + Affichage seulement. Le PGN utilise toujours K Q R B N. + Animation des pièces + Flèche du meilleur coup + Vibration + Stockfish 19 · intégré + Stockfish 19 · téléchargé + Non téléchargé · Télécharger (%1$d Mo) + Téléchargement… %1$d sur %2$d Mo + Supprimer le moteur (libère %1$d Mo) + Supprimer le moteur ? Vous pourrez le télécharger à nouveau. + Supprimer + Lignes + Temps par position + %1$d s + 1 min + Sans limite + Threads + Mémoire + %1$d Mo + Le moteur consomme de la batterie. Il s’éteint de lui-même quand vous quittez la partie ou que l’application passe en arrière-plan. + À propos + Stockfish intégré + Stockfish téléchargé dans l’application + Bases d’échecs, analyse des parties et jeu contre l’ordinateur. Vos fichiers sont seulement lus, jamais modifiés. + Licences et auteurs + Site web et code source + + Détails de la partie + Copier le PGN + Copier la FEN + Partager la partie + Remarques + activé + désactivé + non téléchargé + %1$s trouvées sur %2$s + Partie + %1$d, Blancs, %2$s + %1$d, Noirs, %2$s + coup actuel + Langue + Échec et mat + Pat + PGN copié + FEN copiée + Tournoi + Lieu + Date + Ronde + Blancs + Noirs + Résultat + Elo Blancs + Elo Noirs + Commentateur + Demi-coups + Pas d’accès au fichier : il a été déplacé, supprimé ou son autorisation a été retirée. Retirez-le de la liste et ajoutez-le à nouveau. + Le fichier est endommagé ou n’est pas une base d’échecs. + L’archive ne contient aucune base PGN ou ChessBase. + Ce type de base ne peut pas être lu : %1$s + Fichier + PGN, .cbv, .zip ou .7z + Dossier + Toutes les bases d’un dossier, y compris ChessBase (.cbh) + Recherche des bases… + Aucune base dans ce dossier + Sont recherchés : fichiers PGN, bases ChessBase (.cbh, .cbv) et archives .zip ou .7z, dans le dossier et deux niveaux de sous-dossiers. + déjà dans la liste + le fichier .cbg manque : les parties ne s’ouvrent pas + + %1$d base dans « %2$s » + %1$d de bases dans « %2$s » + %1$d bases dans « %2$s » + + + Ajouter %1$d + Ajouter %1$d + Ajouter %1$d + + + %1$d base ajoutée + %1$d de bases ajoutées + %1$d bases ajoutées + + Android ne laisse choisir ni la racine du stockage ni « Téléchargements » lui-même — seulement un dossier à l’intérieur. + Choisir un autre + Terminé + Ajouter + Tout cocher + Tout décocher + Le fichier %1$s n’est plus à côté de la base : il a été déplacé ou supprimé. + Échiquier et pièces + Marron + Bleu + Vert + Tournoi + Sable + Corail + Gris + Violet + Glace + Marine + Menthe + Émeraude + Orange + Rose + Crépuscule + Nuit + Bois + Érable + Cuir + Marbre + Marbre bleu + Toile + Métal + Olive + Pierre + Plastique vert + Diagonales violettes + Pyramides roses + Croquis + Échiquier + Pièces + N° %1$s + Coller le PGN du presse-papiers + Parties copiées dans une autre application + Aucune partie PGN dans le presse-papiers + Collé le %1$s + + %1$s partie dans le presse-papiers + %1$s parties dans le presse-papiers + %1$s parties dans le presse-papiers + + Enregistrer cette partie PGN et l’ouvrir sur l’échiquier ? + Enregistrer %1$s et ouvrir la première partie sur l’échiquier ? Toutes les parties seront conservées dans la copie locale. + Ouvrir + Presse-papiers + Ouverture du fichier… + Impossible d’ouvrir le fichier + Ce fichier ne contient aucune partie d’échecs. + Impossible de lire le fichier : il n’existe plus, ou l’application d’origine n’y a pas donné accès. Réessayez de l’ouvrir. + Une base ChessBase (.cbh) se compose de plusieurs fichiers, et un seul est arrivé. Ajoutez son dossier : « Ajouter une base » → « Dossier ». + L’application n’a pas pu garder une copie du fichier. Vérifiez qu’il reste de la place sur le téléphone. + copie + Base supprimée de ChessPenguin + + Analyse de la partie + Rapport de la partie + Le moteur évalue chaque position de la ligne principale. La partie elle-même n\'est pas modifiée. + %d s + %d min + Analyser + Compléter + %1$d positions sur %2$d sont déjà évaluées. + Analyse · %1$d sur %2$d + Arrêter l\'analyse + Précision + Précision : Blancs %1$s, Noirs %2$s + Rapport + %1$s était meilleur + Imprécision + Erreur + Gaffe + Imprécisions + Erreurs + Gaffes + Excellent coup + Coup brillant + Excellents coups + Coups brillants + Non évaluées : %d + L\'analyse s\'est interrompue + Continuer + Perte moyenne en centipions + Ouverture + Milieu de partie + Finale + %1$s · %2$s nœuds par coup + Évaluations issues du PGN ([%eval]) + !! et ! demandent le moteur : le PGN ne contient que des évaluations + Cette analyse n’a pas encore cherché les !! et ! + Analyse faite avec d’autres réglages du moteur + Mettre à jour + Analyser avec le moteur + Masquer l\'analyse + Graphique d\'évaluation + En pause : analyse de la partie en cours + Meilleure ligne · coup %1$d sur %2$d + Aller au coup suivant de ce type + Afficher la meilleure ligne sur l\'échiquier + %1$s, évaluation %2$s + Position de départ + + %1$d position, environ %2$s + %1$d positions, environ %2$s + %1$d positions, environ %2$s + + + Parties de Lichess et Chess.com + Les parties de n\'importe quel joueur par pseudo : les vôtres, d\'un élève, d\'un adversaire + Les parties du joueur deviennent une base sur le téléphone, à chercher, voir et analyser. Seul le pseudo est nécessaire, sans connexion. + Pseudo du joueur + comme sur le site + Un autre pseudo sur Chess.com + Pseudo sur Chess.com + Le même pseudo + Lettres latines, chiffres, _ et -, de 2 à 30 caractères + Rechercher + Recherche sur les sites… + %1$s · environ %2$d min la première fois + mois avec des parties : %1$d + %1$s : aucun joueur avec ce pseudo — vérifiez l\'orthographe + Réunir les deux sites dans une seule base + Sinon chaque site a sa propre base + Dans la nouvelle base « %1$s » + Dans « %1$s » (déjà %2$s ; seules les nouvelles parties sont ajoutées) + Télécharger + Lichess : %1$s sur environ %2$s · encore environ %3$d min + %1$s : %2$s + Chess.com : mois %1$d sur %2$d · %3$s + Arrêter + +%1$s, %2$s en tout + Pas de nouvelles parties, %1$s dans la base + Arrêté, %1$s dans la base + Aucune partie d\'échecs standard là-bas. + Ouvrir la base + Réessayer + %1$s ne répond pas. Vérifiez la connexion Internet et réessayez. + %1$s demande une pause : trop de requêtes d\'affilée. Attendez une minute et réessayez ; ce qui est téléchargé est conservé. + %1$s a répondu d\'une façon que ChessPenguin ne comprend pas : le site a peut-être changé. Réessayez plus tard ou mettez ChessPenguin à jour. + Impossible d\'écrire la base : le téléphone n\'a plus de place. + Cette base est déjà en cours de téléchargement. + %1$s ne répond pas + %1$s demande une pause + Le téléchargement s\'est interrompu + Télécharger les nouvelles parties + Arrêter le téléchargement + Téléchargement · %1$s + mise à jour %1$s + incomplète + Base téléchargée supprimée + Pseudo sur Lichess + %1$s · moins d\'une minute la première fois + Vous pouvez quitter cet écran : la base est dans la liste et le téléchargement continue. + Terminé : %1$s + mise à jour à l\'instant + « %1$s » : +%2$s, %3$s en tout + « %1$s » : pas de nouvelles parties + « %1$s » : %2$s + Ouvrir + + jusqu\'à %1$s partie + jusqu\'à %1$s parties + jusqu\'à %1$s parties + + La version %1$s est sortie + Vous avez %1$s + Mettre à jour + Installer + Les bases, les paramètres et le moteur sont conservés. + Les bases et les paramètres sont conservés. + ChessPenguin se ferme pendant l’installation — rouvrez-le ensuite. + Des parties sont en cours de téléchargement : l’installation va l’interrompre, vous pourrez le reprendre ensuite. + Une autorisation est nécessaire + Android n’installe des applications hors d’une boutique qu’avec votre autorisation. Les paramètres vont s’ouvrir : activez l’interrupteur pour ChessPenguin et revenez. + Ouvrir les paramètres + L’autorisation est désactivée — sans elle, Android n’installera pas la nouvelle version. + Autorisation accordée, téléchargement en cours + Télécharger sur le site + Ouvrir le site + Vous pouvez fermer : le téléchargement continue. + Pas de réseau. Le téléchargement reprendra tout seul quand le réseau reviendra. + En attente du réseau + Vérification du fichier… + Conservation du moteur… + Installation… + La nouvelle version est téléchargée et vérifiée. + Téléchargée et vérifiée + La nouvelle version est téléchargée + Installation annulée. La nouvelle version est téléchargée — installez-la quand vous voulez. + Mise à jour de ChessPenguin + ChessPenguin est mis à jour : %1$s → %2$s + Le téléchargement a échoué. Réessayez. + Le fichier a été endommagé pendant le téléchargement ; il n’a pas été installé. Réessayez. + Cette version pose problème : le fichier Android ne peut pas être vérifié. Téléchargez la nouvelle version sur le site. + Android n’a pas installé la nouvelle version : pas assez d’espace. Libérez %1$d Mo et réessayez. + Android n’a pas installé la nouvelle version : ce ChessPenguin est signé avec une autre clé. La nouvelle version ne peut s’installer qu’après la suppression de celle-ci, et la suppression efface la liste des bases et les bases téléchargées. + Android ou la protection du téléphone a arrêté l’installation. Téléchargez la nouvelle version sur le site. + Android n’a pas installé la nouvelle version. Réessayez ou téléchargez-la sur le site. + Pas d’Internet + Pas assez d’espace + Le fichier est endommagé + Android ne l’a pas installée + Le téléchargement a échoué + En savoir plus + Détails + Copier + Mises à jour + Rechercher les mises à jour au démarrage + Une fois par jour, ChessPenguin demande à son site quelle est la dernière version ; le site compte les installations actives. Seuls un numéro aléatoire de cette installation, la version et le système sont envoyés. La vérification se fait même sans les propositions. + Proposer les nouvelles versions + Une carte sur l’écran Bases quand une nouvelle version sort. + Fonctionne quand la vérification des mises à jour est activée. + Nous ne le proposerons plus. Réactivez-le dans Réglages, À propos + Ne pas proposer les mises à jour + Vérifier maintenant + Vérification… + Vous avez la dernière version + Dernière vérification : %1$s + Pas d’Internet — impossible de vérifier les mises à jour + Impossible de vérifier les mises à jour : le site n’a pas répondu. Réessayez plus tard. + La version %1$s est sortie + Téléchargement de la version %1$s… + La version %1$s est téléchargée + Mise à jour vers %1$s, %2$d sur %3$d mégaoctets téléchargés + Fichier impossible à vérifier + Annuler + Coups supprimés + En faire la ligne principale + Supprimer le coup et la suite + Actions sur le coup + Nouvelle partie + Mes bases + + Nouvelle base + Ici seront les parties que vous saisirez ou jouerez contre l’ordinateur + + Ajouter + Ici seront les fichiers PGN et ChessBase, les dossiers et les parties d’Internet que vous ajouterez + Fichiers + Mes parties + Nouvelle base + Nom + Conservée sur le téléphone, dans ChessPenguin. Le fichier s’exporte depuis le menu de la base. + Créer + sur le téléphone + Exporter le fichier… + Supprimer la base + Fichier enregistré + Impossible d’enregistrer le fichier + Base supprimée + Supprimer « %1$s » ? + + %1$s partie sera supprimée du téléphone. Si vous en avez besoin, exportez d’abord le fichier. + %1$s parties seront supprimées du téléphone. Si vous en avez besoin, exportez d’abord le fichier. + %1$s parties seront supprimées du téléphone. Si vous en avez besoin, exportez d’abord le fichier. + + Enregistrée dans « %1$s », n° %2$s + Impossible d’enregistrer la partie + Enregistrer dans « %1$s » + Enregistrer dans ma base… + Enregistrer dans une base + Enregistrer dans une base… + Nouvelle base… + Créer et enregistrer + Enregistrer les modifications dans « %1$s » ? + Enregistrer la partie ? + Ne pas enregistrer + Données de la partie + AAAA.MM.JJ + Pas une date : 2026.10.26, 2026 ou 26.10.2026 + Annuler les modifications ? + Annuler + Continuer + Modifier + Suivant + Apprentissage de l\'ouverture + jusqu\'à %1$s + Apprendre l\'ouverture jusqu\'à ce coup + Coup %1$s sur %2$s + ♔ Trait aux Blancs + ♚ Trait aux Noirs + Erreurs : %1$s + Passage %1$s + × La partie a un autre coup ici + Montrer le coup + Ligne jamais parcourue + La dernière fois : %1$s · sans erreur d\'affilée : %2$s + La dernière fois : %1$s · meilleur : %2$s + Terminé sans erreur + Terminé avec un indice · erreurs : %1$s + Terminé · erreurs : %1$s + Passage %1$s · meilleur : %2$s + sans erreur d\'affilée : %1$s + Récents : %1$s + Jouez le coup indiqué par la flèche + ↻ Encore + ⬅ Retour à la partie + Recommencer + + %1$d passage + %1$d passages + %1$d passages + + Maia pour ChessPenguin + Vous avez gagné + Vous avez perdu + Vous avez abandonné + Nulle + échec et mat + pat + la position s’est répétée trois fois + 50 coups sans prise ni coup de pion + aucun camp ne peut mater + Maia a abandonné + Abandonner ? + ⚑ Abandonner + ↶ Reprendre + Jouer contre l’ordinateur + Votre couleur + Blancs + Noirs + Au hasard + Le classement propre de Maia : il ne correspond pas à l’Elo d’une personne. + Maia est téléchargée une seule fois (%1$s Mo, depuis huggingface.co, le fichier des auteurs eux-mêmes). + Télécharger et jouer + Jouer + réfléchit… + Partie contre l’ordinateur + Analyser + ↻ Revanche + Jouer à partir d’ici… + Vérification… + Maia n’a pas démarré : %1$s + Accepter la victoire + Jouer jusqu’au bout + Maia abandonne + À partir d’ici, une partie contre Maia %1$s. + Abandonner + Votre nom + Maia est téléchargée + Réessayer + Sa position est perdue. Accepter la victoire ou continuer ? + Continuer + Partie contre Maia %1$s · vous jouez %2$s + les Blancs + les Noirs + Partie supprimée + sans pendule + Vous + ✓ Enregistrée + Enregistrer… + vous jouez %1$s · %2$s + Après %1$s + Son + Annuler + Ligne principale désormais + Elo + Analyser + Continuer + Consultation %1$s · retour à la partie › + la position initiale + Maia n’a pas démarré. + Retélécharger Maia + Une partie contre %1$s est en attente + La continuer + En commencer une nouvelle + Une nouvelle partie la remplace ; ce qui a été joué va, inachevé, dans la base du joueur. + Nulle + par accord mutuel + Maia refuse la nulle + Maia a refusé ; reproposez après deux de ses coups + Maia répond à la nulle avec Stockfish : téléchargez-le avec « Moteur » + %1$s — parties contre l’ordinateur + Parties contre l’ordinateur + ✓ Dans « %1$s », n° %2$s › + Partie enregistrée inachevée dans « %1$s » + enregistrées d’elles-mêmes + Enregistrer les parties contre l’ordinateur dans la base du joueur + Les parties sont enregistrées dans « %1$s » + Les parties seront enregistrées dans une nouvelle base « %1$s ». + Sans nom, les parties vont dans « %1$s ». Saisissez un nom pour avoir votre propre base. + Les parties ne sont pas enregistrées d’elles-mêmes (Réglages). + ✓ Nouvelle base « %1$s », n° %2$s › + Impossible d’écrire dans « %1$s » : %2$s + Une nouvelle partie la remplace. + Ouverte en dernier + Partie contre %1$s + coup %1$d + + Amanda + Attaque d’abord, puis joue pour l’activité des pièces. + Cloé + Aime les positions fermées. + Déborah + Défend bien et aime ses fous. + Défenseur + Solide et prudent ; se contente de la nulle. + Dynamique + Attaque, aime les fous, sacrifie de temps en temps. + Grincheux + Attaque et restriction ; aime les positions bloquées, évite la nulle. + Partisan + Attaque après des ouvertures calmes et discrètes. + Gambiteur + Équilibré, mais cède plus volontiers des pions. + Pedrita + Pions, défense et restriction. + Preston + Un attaquant matérialiste et modéré. + Simplet + Le plus « ordinateur » : un jeu simple et sain. + Boutefeu + Tranchant et agressif. + Étrangleur + Un boa : étouffe lentement, très humain. + Alekhine + Attaques dynamiques et combinaisons profondes. + Anand + Jeu rapide et universel, ouvertures tranchantes. + Anderssen + Un attaquant romantique du XIXe siècle : sacrifices. + Bosboom + Ouvertures originales et blitz créatif. + Botvinnik + Jeu stratégique et scientifique, préparation profonde. + Fischer + Clair, classique et précis. + Karpov + Étau positionnel, prophylaxie et technique. + Kasparov + Initiative et attaque puissante. + Kortchnoi + Un défenseur tenace et contre-attaquant. + Larsen + Original et risqué, aux ouvertures insolites. + Lasker + Un combattant pratique et psychologue. + Marshall + Un attaquant fougueux, amateur de gambits. + Morphy + Développement rapide et lignes ouvertes. + Nimzowitsch + Restriction, blocus et surprotection. + Petrosian + Prophylaxie et sécurité avant tout. + Reti + Hypermoderne : contrôle le centre à distance. + Rubinstein + Jeu positionnel classique, excellent en finale. + Spassky + Un joueur universel, à l’aise partout. + Steinitz + Le fondateur du jeu positionnel, défenseur obstiné. + Tal + Le magicien de Riga : sacrifices et attaque. + Tarrasch + Règles classiques : espace, développement, pièces actives. + Topalov + Agressif et dynamique, sacrifie la qualité. + joue comme un humain + fort, avec un style + Comme un humain + Maia ne choisit pas de style : elle joue comme les gens de son niveau. + Le classement propre de Rodent (UCI_Elo) : il ne correspond pas à l’Elo d’une personne. + Rodent abandonne + Rodent a abandonné + Rodent refuse la nulle + Rodent a refusé ; reproposez après deux de ses coups + Sa position est perdue. Accepter la victoire ou jouer jusqu’au bout ? + Jouer + Jouer contre l’ordinateur + Force : %1$s + Contre qui jouer + Un caractère, c’est un style et des ouvertures ; le curseur règle la force. + Grands joueurs + Caractères + Changer + %1$s, grand joueur + %1$s, caractère + Caractère : %1$s + Rodent IV et ses livres d’ouvertures sont sur le téléphone + Livres d’ouvertures de Rodent IV : %1$s Mo, une seule fois depuis github.com + Depuis une position, pas besoin de livre d’ouvertures : Rodent IV joue tout de suite + Sans livre + Sans livre : jouer sans livre d’ouvertures + Livres d’ouvertures de Rodent IV + Rodent IV — livres d’ouvertures + téléchargés · %1$s Mo + non téléchargés · %1$s Mo + Livres d’ouvertures supprimés + Rodent répond à la nulle avec Stockfish : téléchargez-le avec « Moteur » + Rodent n’a pas démarré. + Redémarrer + À partir d’ici, une partie contre Rodent IV %1$s · %2$s. + Rodent s’est arrêté pendant la partie. + %1$s, de %2$s à %3$s + Force + Supprimer les livres d’ouvertures + + + Joueurs + Nom du joueur + Impossible de lire les joueurs + Lecture des joueurs… + Cette base ne contient aucun joueur nommé + Joueur introuvable + Retour aux parties + Effacer la recherche + Préparer + Choisissez la couleur + Préparer contre %1$s + Contre les Blancs + Contre les Noirs + Préparer contre l’adversaire… + Préparation contre l’adversaire + Fermez d’abord la ligne du moteur + + La recherche après un -- pédagogique est indisponible + Blancs + Noirs + Impossible de jouer ce coup + Jouer %1$s, %2$s, %3$s pour cent + Échiquier, position initiale. %1$s en bas. + Échiquier, position après %1$s. %2$s en bas. + Trait aux blancs + Trait aux noirs + L’adversaire joue + Ses adversaires jouent + après %1$s + début + %1$s, %2$s, %3$s, %4$s + Impossible de calculer les continuations + Mémoire insuffisante pour rechercher dans cette base + Calcul des continuations… + Cette position n’apparaît pas dans les parties de %1$s + Vous pouvez continuer sur l’échiquier ou revenir en arrière + Toutes les parties se terminent ici + Terminées ici : %1$s + Aucune continuation normale : %1$s + Retour à la partie + Retour aux joueurs + Choisir un coup + %1$s victoire%1$s victoires%1$s victoires + %1$s nulle%1$s nulles%1$s nulles + %1$s défaite%1$s défaites%1$s défaites + Résultats inconnus : %1$d ; exclus des pourcentages. + %1$s. %2$d sur %3$s, %4$s pour cent. Résultats de %5$s : %6$s, %7$s, %8$s ; %9$s, %10$s et %11$s pour cent. %12$s Jouer. + Jouer + plus %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml new file mode 100644 index 0000000..1db014a --- /dev/null +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -0,0 +1,733 @@ + + Partite classiche + Alekhine + + Qui compariranno i tuoi database + Aggiungi un file PGN, un database ChessBase o un archivio .zip/.7z — dal telefono o dal cloud — oppure scarica partite da Lichess e Chess.com. + Aggiungi database + Apri le partite di esempio + non ancora aperto · %1$s + + %1$s partita + %1$s di partite + %1$s partite + + %1$s · %2$s + Menu + Rinomina + Rimuovi dall\'elenco + Il nome nell\'elenco. Il file non viene modificato. + Annulla + Salva + Database rimosso dall\'elenco + Annulla + Indietro + + Lettura… + Impossibile aprire il database + Cerca + Giocatore, torneo, anno + Nessun risultato + Cancella + + %1$d di %2$d + Partita precedente + Partita successiva + Ruota la scacchiera + All\'inizio + Mossa indietro + Mossa avanti + Mossa precedente. Tieni premuto per andare all\'inizio + Mossa successiva. Tieni premuto per andare alla fine della linea + Alla fine della linea + Seguito: + Scacchiera, posizione dopo %1$s + Scacchiera, posizione iniziale + Hanno vinto i bianchi + Hanno vinto i neri + Patta + Impossibile leggere la partita + + Motore + Sto pensando… + profondità %1$d + in pausa + Più a fondo + Più linee + Meno linee + Il motore non risponde + Il motore non si avvia su questo telefono + Riavvia + Linea del motore · mossa %1$d di %2$d + Chiudi + Motore Stockfish + Valuta la posizione e mostra le mosse migliori. Funziona offline — basta scaricarlo una volta. + Dimensione: %1$d MB + Ora non c\'è Wi-Fi: il download userà i dati mobili. + Non ora + Scarica + Scaricati %1$d di %2$d MB + Annulla + Download annullato + Il motore è pronto + Nessuna connessione Internet. Connettiti a una rete e riprova. + ChessPenguin: motore Stockfish + Il download si è interrotto. Riprova. + Spazio insufficiente: servono %1$d MB. + Il file del motore si è danneggiato durante il download. Scaricalo di nuovo. + Riprova + Scarica di nuovo + OK + Preparazione del motore… + + Impostazioni + Aspetto + Motore + Tema + Predefinito di sistema + Chiaro + Scuro + Notazione delle mosse + Lettere inglesi (K Q R B N) + Figurine + Lettere italiane (R D T A C) + Solo per la visualizzazione. Il PGN usa sempre K Q R B N. + Animazione dei pezzi + Freccia della mossa migliore + Vibrazione + Stockfish 19 · incluso + Stockfish 19 · scaricato + Non scaricato · Scarica (%1$d MB) + Scaricamento… %1$d di %2$d MB + Elimina il motore (libera %1$d MB) + Eliminare il motore? Potrai scaricarlo di nuovo. + Elimina + Linee + Tempo per posizione + %1$d s + 1 min + Nessun limite + Thread + Memoria + %1$d MB + Il motore consuma batteria. Si spegne da solo quando esci dalla partita o l’app va in background. + Informazioni + Stockfish incluso + Stockfish si scarica nell\'app + Database scacchistici, analisi delle partite e gioco contro il computer. I tuoi file vengono solo letti, mai modificati. + Licenze e autori + Sito web e codice sorgente + + Dati della partita + Copia PGN + Copia FEN + Condividi la partita + Note + attivo + disattivato + non scaricato + Trovate %1$s di %2$s + Partita + %1$d, Bianco, %2$s + %1$d, Nero, %2$s + mossa attuale + Lingua + Scacco matto + Stallo + PGN copiato + FEN copiata + Torneo + Luogo + Data + Turno + Bianco + Nero + Risultato + Elo Bianco + Elo Nero + Commentatore + Semimosse + Nessun accesso al file: è stato spostato, eliminato o il permesso è stato revocato. Rimuovilo dall\'elenco e aggiungilo di nuovo. + Il file è danneggiato o non è un database scacchistico. + Nell\'archivio non c\'è alcun database PGN o ChessBase. + Questo tipo di database non può essere letto: %1$s + File + PGN, .cbv, .zip o .7z + Cartella + Tutti i database di una cartella, anche ChessBase (.cbh) + Cerco i database… + Nessun database in questa cartella + Vengono trovati file PGN, database ChessBase (.cbh, .cbv) e archivi .zip o .7z, nella cartella e in due livelli di sottocartelle. + già nell’elenco + manca il file .cbg: le partite non si possono aprire + + %1$d database in «%2$s» + %1$d di database in «%2$s» + %1$d database in «%2$s» + + + Aggiungi %1$d + Aggiungi %1$d + Aggiungi %1$d + + + %1$d database aggiunto + %1$d di database aggiunti + %1$d database aggiunti + + Android non permette di scegliere la radice della memoria né «Download» stessa: solo una cartella al loro interno. + Scegli un’altra + Fatto + Aggiungi + Seleziona tutti + Deseleziona tutti + Il file %1$s non è più accanto al database: è stato spostato o eliminato. + Scacchiera e pezzi + Marrone + Blu + Verde + Torneo + Sabbia + Corallo + Grigio + Viola + Ghiaccio + Blu navy + Menta + Smeraldo + Arancione + Rosa + Crepuscolo + Notte + Legno + Acero + Pelle + Marmo + Marmo blu + Tela + Metallo + Oliva + Pietra + Plastica verde + Diagonali viola + Piramidi rosa + Schizzo + Scacchiera + Pezzi + N. %1$s + Incolla PGN dagli appunti + Partite copiate in un’altra app + Nessuna partita PGN negli appunti + Incollato il %1$s + + Partita negli appunti + Partite negli appunti + Partite negli appunti + + Salvare questa partita PGN e aprirla sulla scacchiera? + Salvare %1$s e aprire la prima partita sulla scacchiera? Tutte le partite saranno conservate nella copia locale. + Apri + Appunti + Apertura del file… + Impossibile aprire il file + Questo file non contiene partite a scacchi. + Impossibile leggere il file: non esiste più o l’app da cui proviene non ha concesso l’accesso. Riaprilo. + Un database ChessBase (.cbh) è fatto di più file, ma ne è arrivato solo uno. Aggiungi la sua cartella: «Aggiungi database» → «Cartella». + L’app non è riuscita a salvare una copia del file. Controlla che sul telefono ci sia spazio libero. + copia + Database eliminato da ChessPenguin + + Analisi della partita + Resoconto della partita + Il motore valuta ogni posizione della linea principale. La partita non viene modificata. + %d s + %d min + Analizza + Completa + %1$d posizioni su %2$d sono già valutate. + Analisi · %1$d di %2$d + Interrompi l\'analisi + Precisione + Precisione: Bianco %1$s, Nero %2$s + Resoconto + era meglio %1$s + Imprecisione + Errore + Svarione + Imprecisioni + Errori + Svarioni + Ottima mossa + Mossa brillante + Ottime mosse + Mosse brillanti + Non valutate: %d + L\'analisi si è interrotta + Continua + Perdita media in centipedoni + Apertura + Mediogioco + Finale + %1$s · %2$s nodi per mossa + Valutazioni dal PGN ([%eval]) + !! e ! richiedono il motore: il PGN contiene solo valutazioni + Questa analisi non ha ancora cercato !! e ! + Analisi fatta con altre impostazioni del motore + Aggiorna + Analizza con il motore + Nascondi l\'analisi + Grafico di valutazione + In pausa: analisi della partita in corso + Linea migliore · mossa %1$d di %2$d + Vai alla prossima mossa di questo tipo + Mostra la linea migliore sulla scacchiera + %1$s, valutazione %2$s + Posizione iniziale + + %1$d posizione, circa %2$s + %1$d posizioni, circa %2$s + %1$d posizioni, circa %2$s + + + Partite da Lichess e Chess.com + Partite di qualsiasi giocatore per nickname: le tue, di un allievo, di un avversario + Le partite del giocatore diventano una base sul telefono, da cercare, vedere e analizzare. Serve solo il nickname, senza accesso. + Nickname del giocatore + come sul sito + Un altro nickname su Chess.com + Nickname su Chess.com + Lo stesso nickname + Lettere latine, cifre, _ e -, da 2 a 30 caratteri + Cerca + Cerco sui siti… + %1$s · la prima volta circa %2$d min + mesi con partite: %1$d + %1$s: nessun giocatore con questo nickname — controlla come è scritto + Unire entrambi i siti in una sola base + Altrimenti ogni sito avrà la sua base + Nella nuova base «%1$s» + In «%1$s» (già %2$s; si aggiungono solo le nuove) + Scarica + Lichess: %1$s di circa %2$s · mancano circa %3$d min + %1$s: %2$s + Chess.com: mese %1$d di %2$d · %3$s + Ferma + +%1$s, %2$s in tutto + Nessuna partita nuova, %1$s nella base + Fermato, %1$s nella base + Lì non ci sono partite di scacchi standard. + Apri la base + Riprova + %1$s non risponde. Controlla la connessione a internet e riprova. + %1$s chiede una pausa: troppe richieste di fila. Aspetta un minuto e riprova; il già scaricato resta. + %1$s ha risposto in un modo che ChessPenguin non capisce: forse il sito è cambiato. Riprova più tardi o aggiorna ChessPenguin. + Impossibile scrivere la base: il telefono non ha spazio. + Questa base è già in download. + %1$s non risponde + %1$s chiede una pausa + Il download si è interrotto + Scarica le partite nuove + Ferma il download + Download in corso · %1$s + aggiornata %1$s + incompleta + Base scaricata eliminata + Nickname su Lichess + %1$s · la prima volta meno di un minuto + Puoi uscire da questa schermata: la base è già nell\'elenco e il download continua. + Fatto: %1$s + aggiornata adesso + «%1$s»: +%2$s, %3$s in tutto + «%1$s»: nessuna partita nuova + «%1$s»: %2$s + Apri + + fino a %1$s partita + fino a %1$s partite + fino a %1$s partite + + È uscita la versione %1$s + Hai la %1$s + Aggiorna + Installa + Database, impostazioni e motore vengono mantenuti. + Database e impostazioni restano. + ChessPenguin si chiude durante l’installazione: poi riaprilo. + Si stanno scaricando partite: l’installazione interrompe il download, poi puoi riprenderlo. + Serve un’autorizzazione + Android installa app non provenienti da uno store solo con il tuo permesso. Si apriranno le impostazioni: attiva l’interruttore per ChessPenguin e torna indietro. + Apri impostazioni + L’autorizzazione è disattivata: senza di essa, Android non installerà la nuova versione. + Autorizzazione concessa, download in corso + Scarica dal sito + Apri il sito + Puoi chiudere: il download continua. + Nessuna rete. Il download riprenderà da solo quando torna la rete. + In attesa di rete + Controllo del file… + Salvataggio del motore… + Installazione… + La nuova versione è scaricata e controllata. + Scaricata e controllata + La nuova versione è scaricata + Installazione annullata. La nuova versione è scaricata: installala quando vuoi. + Aggiornamento di ChessPenguin + ChessPenguin è aggiornato: %1$s → %2$s + Il download non è riuscito. Riprova. + Il file si è danneggiato durante lo scaricamento, quindi non è stato installato. Riprova. + Qualcosa non va in questa versione: il file per Android non si può controllare. Scarica la nuova versione dal sito. + Android non ha installato la nuova versione: spazio insufficiente. Libera %1$d MB e riprova. + Android non ha installato la nuova versione: questo ChessPenguin è firmato con un’altra chiave. La nuova versione si può installare solo dopo aver rimosso questa, e rimuovendola si perdono l’elenco dei database e i database scaricati. + Android o la protezione del telefono ha fermato l’installazione. Scarica la nuova versione dal sito. + Android non ha installato la nuova versione. Riprova o scaricala dal sito. + Nessuna connessione + Spazio insufficiente + Il file si è danneggiato + Android non l’ha installata + Download non riuscito + Scopri di più + Dettagli + Copia + Aggiornamenti + Cerca aggiornamenti all’avvio + Una volta al giorno ChessPenguin chiede al suo sito qual è l’ultima versione; il sito conta le installazioni in uso. Vengono inviati solo un numero casuale di questa installazione, la versione e il sistema. Il controllo avviene anche senza le proposte. + Proponi nuove versioni + Una scheda nella schermata Database quando esce una nuova versione. + Funziona con il controllo degli aggiornamenti attivo. + Non lo proporremo più. Riattivalo in Impostazioni, Informazioni + Non proporre aggiornamenti + Controlla ora + Controllo in corso… + Hai l’ultima versione + Ultimo controllo: %1$s + Nessuna connessione: impossibile cercare aggiornamenti + Impossibile controllare gli aggiornamenti: il sito non ha risposto. Riprova più tardi. + È uscita la versione %1$s + Scaricamento della versione %1$s… + La versione %1$s è scaricata + Aggiornamento a %1$s, %2$d di %3$d megabyte scaricati + File non verificabile + Annulla + Mosse eliminate + Rendi linea principale + Elimina la mossa e il seguito + Azioni sulla mossa + Nuova partita + I miei database + + Nuovo database + Qui ci saranno le partite che inserisci o giochi contro il computer + + Aggiungi + Qui ci saranno i file PGN e ChessBase, le cartelle e le partite da internet che aggiungi + File + Le mie partite + Nuovo database + Nome + Conservato sul telefono, in ChessPenguin. Il file si esporta dal menu del database. + Crea + sul telefono + Esporta il file… + Elimina il database + File salvato + Impossibile salvare il file + Database eliminato + Eliminare «%1$s»? + + %1$s partita sarà eliminata dal telefono. Se ti serve, esporta prima il file. + %1$s partite saranno eliminate dal telefono. Se ti servono, esporta prima il file. + %1$s partite saranno eliminate dal telefono. Se ti servono, esporta prima il file. + + Salvata in «%1$s», n. %2$s + Impossibile salvare la partita + Salva in «%1$s» + Salva nel mio database… + Salva in un database + Salva in un database… + Nuovo database… + Crea e salva + Salvare le modifiche in «%1$s»? + Salvare la partita? + Non salvare + Dati della partita + AAAA.MM.GG + Non è una data: 2026.10.26, 2026 o 26.10.2026 + Annullare le modifiche? + Annulla + Continua a modificare + Modifica + Avanti + Studio dell\'apertura + fino a %1$s + Studia l\'apertura fino a questa mossa + Mossa %1$s di %2$s + ♔ Muove il Bianco + ♚ Muove il Nero + Errori: %1$s + Giro %1$s + × Nella partita qui c\'è un\'altra mossa + Mostra la mossa + Linea mai ripassata + L\'ultima volta: %1$s · senza errori di fila: %2$s + L\'ultima volta: %1$s · migliore: %2$s + Completato senza errori + Completato con un aiuto · errori: %1$s + Completato · errori: %1$s + Giro %1$s · migliore: %2$s + senza errori di fila: %1$s + Recenti: %1$s + Gioca la mossa indicata dalla freccia + ↻ Ancora + ⬅ Torna alla partita + Da capo + + %1$d ripasso + %1$d ripassi + %1$d ripassi + + Maia per ChessPenguin + Hai vinto + Hai perso + Hai abbandonato + Patta + scacco matto + stallo + la posizione si è ripetuta tre volte + 50 mosse senza catture né mosse di pedone + nessuno dei due può dare matto + Maia ha abbandonato + Abbandonare? + ⚑ Abbandona + ↶ Ritira mossa + Gioca contro il computer + Il tuo colore + Bianco + Nero + Casuale + Il rating proprio di Maia: non corrisponde all’Elo di una persona. + Maia si scarica una sola volta (%1$s MB, da huggingface.co, il file degli autori stessi). + Scarica e gioca + Gioca + sta pensando… + Partita contro il computer + Analizza + ↻ Rivincita + Gioca da qui… + Controllo… + Maia non si è avviata: %1$s + Accetta la vittoria + Gioca fino alla fine + Maia abbandona + Da qui, una partita contro Maia %1$s. + Annulla + Il tuo nome + Maia è scaricata + Riprova + La sua posizione è persa. Accettare la vittoria o continuare? + Continua + Partita contro Maia %1$s · giochi con %2$s + il Bianco + il Nero + Partita rimossa + senza orologio + Tu + ✓ Salvata + Salva… + giochi con %1$s · %2$s + Dopo %1$s + Suono + Annulla + Ora è la linea principale + Elo + Analizza + Continua + Visione %1$s · torna alla partita › + la posizione iniziale + Maia non si è avviata. + Riscarica Maia + C’è una partita sospesa contro %1$s + Continuala + Iniziarne una nuova + Una nuova partita la sostituisce; quanto giocato va, non finito, nel database del giocatore. + Patta + per accordo + Maia rifiuta la patta + Maia ha rifiutato; riproponi dopo due sue mosse + Maia risponde alla patta con Stockfish: scaricalo con «Motore» + %1$s — partite contro il computer + Partite contro il computer + ✓ In «%1$s», n. %2$s › + Partita salvata non finita in «%1$s» + salvate da sole + Salvare le partite contro il computer nel database del giocatore + Le partite vengono salvate in «%1$s» + Le partite saranno salvate in un nuovo database «%1$s». + Senza nome le partite vanno in «%1$s». Inserisci un nome per avere un database tuo. + Le partite non vengono salvate da sole (Impostazioni). + ✓ Nuovo database «%1$s», n. %2$s › + Impossibile scrivere in «%1$s»: %2$s + Una nuova partita la sostituisce. + Aperta per ultima + Partita contro %1$s + mossa %1$d + + Amanda + Prima attacca, poi gioca per l’attività dei pezzi. + Cloe + Ama le posizioni chiuse. + Debora + Difende bene e ama i suoi alfieri. + Difensore + Solido e prudente; si accontenta della patta. + Dinamico + Attacca, ama gli alfieri, sacrifica di tanto in tanto. + Brontolo + Attacco e restrizione; ama le posizioni bloccate, evita la patta. + Partigiano + Attacca dopo aperture tranquille e discrete. + Gambettista + Equilibrato, ma cede pedoni più volentieri. + Pedrita + Pedoni, difesa e restrizione. + Preston + Un attaccante materialista e moderato. + Semplice + Il più «computer»: scacchi semplici e solidi. + Testa calda + Tagliente e aggressivo. + Strangolatore + Un boa: stringe lentamente, molto umano. + Aljechin + Attacchi dinamici e combinazioni profonde. + Anand + Gioco rapido e universale con aperture taglienti. + Anderssen + Un attaccante romantico dell’Ottocento: sacrifici. + Bosboom + Aperture insolite e blitz creativo. + Botvinnik + Gioco strategico e scientifico, preparazione profonda. + Fischer + Chiaro, classico e preciso. + Karpov + Morsa posizionale, profilassi e tecnica. + Kasparov + Iniziativa e attacco potente. + Kortchnoi + Un difensore tenace e contrattaccante. + Larsen + Originale e rischioso, con aperture insolite. + Lasker + Un combattente pratico e psicologico. + Marshall + Un attaccante spavaldo con i gambetti. + Morphy + Sviluppo rapido e linee aperte. + Nimzowitsch + Restrizione, blocco e sovraprotezione. + Petrosian + Profilassi e sicurezza prima di tutto. + Reti + Ipermoderno: controlla il centro da lontano. + Rubinstein + Gioco posizionale classico, ottimo nei finali. + Spassky + Un giocatore universale, a suo agio ovunque. + Steinitz + Il fondatore del gioco posizionale, difensore ostinato. + Tal + Il mago di Riga: sacrifici e attacco. + Tarrasch + Regole classiche: spazio, sviluppo, pezzi attivi. + Topalov + Aggressivo e dinamico, sacrifica la qualità. + gioca come un umano + forte, con uno stile + Come un umano + Maia non sceglie uno stile: gioca come le persone del suo livello. + Il rating proprio di Rodent (UCI_Elo): non corrisponde all’Elo di una persona. + Rodent abbandona + Rodent ha abbandonato + Rodent rifiuta la patta + Rodent ha rifiutato; riproponi dopo due sue mosse + La sua posizione è persa. Accettare la vittoria o giocare fino in fondo? + Gioca + Gioca contro il computer + Forza: %1$s + Contro chi giocare + Un carattere è uno stile con le sue aperture; la forza la regola il cursore. + Grandi giocatori + Caratteri + Cambia + %1$s, grande giocatore + %1$s, carattere + Carattere: %1$s + Rodent IV e i suoi libri di aperture sono sul telefono + Libri di aperture di Rodent IV: %1$s MB, una sola volta da github.com + Da una posizione non serve il libro di aperture: Rodent IV gioca subito + Senza libro + Senza libro: gioca senza libro di aperture + Libri di aperture di Rodent IV + Rodent IV — libri di aperture + scaricati · %1$s MB + non scaricati · %1$s MB + Libri di aperture eliminati + Rodent risponde alla patta con Stockfish: scaricalo con «Motore» + Rodent non si è avviato. + Riavvia + Da qui, una partita contro Rodent IV %1$s · %2$s. + Rodent si è fermato durante la partita. + %1$s, da %2$s a %3$s + Forza + Elimina i libri di aperture + + + Giocatori + Nome del giocatore + Impossibile leggere i giocatori + Lettura dei giocatori… + Questo database non contiene giocatori con nome + Giocatore non trovato + Torna alle partite + Cancella ricerca + Prepara + Scegli un colore + Preparati contro %1$s + Contro il Bianco + Contro il Nero + Preparati contro l\'avversario… + Preparazione contro l\'avversario + Chiudi prima la linea del motore + + La ricerca dopo un -- didattico non è disponibile + Bianco + Nero + Impossibile giocare questa mossa + Gioca %1$s, %2$s, %3$s per cento + Scacchiera, posizione iniziale. %1$s in basso. + Scacchiera, posizione dopo %1$s. %2$s in basso. + Tocca al bianco + Tocca al nero + Gioca l\'avversario + Giocano i suoi avversari + dopo %1$s + inizio + %1$s, %2$s, %3$s, %4$s + Impossibile calcolare le continuazioni + Memoria insufficiente per cercare in questo database + Calcolo delle continuazioni… + Questa posizione non compare nelle partite di %1$s + Puoi continuare sulla scacchiera o tornare indietro + Tutte le partite sono terminate qui + Terminate qui: %1$s + Nessuna continuazione normale: %1$s + Torna alla partita + Torna ai giocatori + Scegli una mossa + %1$s vittoria%1$s vittorie%1$s vittorie + %1$s patta%1$s patte%1$s patte + %1$s sconfitta%1$s sconfitte%1$s sconfitte + Risultati sconosciuti: %1$d; esclusi dalle percentuali. + %1$s. %2$d di %3$s, %4$s per cento. Risultati di %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s per cento. %12$s Gioca. + Gioca + altri %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml new file mode 100644 index 0000000..17bb8eb --- /dev/null +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -0,0 +1,725 @@ + + Кла��икалық парти�лар + �лехин + + Базаларыңыз о�ында пайда болады + PGN файлын, ChessBase база�ын неме�е .zip/.7z мұрағатын телефоннан не бұлттан қо�ыңыз, неме�е Lichess пен Chess.com-нан парти�лар жүктеп алыңыз. + База қо�у + Үлгі парти�ларды ашу + әлі ашылмаған · %1$s + + %1$s парти� + %1$s парти� + + %1$s · %2$s + Мәзір + �тын өзгерту + Тізімнен алып та�тау + Тізімдегі атауы. Файл өзгермейді. + Ба� тарту + Сақтау + База тізімнен алынды + Болдырмау + �ртқа + + Оқылуда… + Базаны ашу мүмкін болмады + Іздеу + Ойыншы, турнир, жыл + Ештеңе табылмады + Тазалау + + %1$d / %2$d + �лдыңғы парти� + Келе�і парти� + Тақтаны аудару + Ба�ына + Бір жүрі� артқа + Бір жүрі� алға + �лдыңғы жүрі�. Ба�ына өту үшін ба�ып тұрыңыз + Келе�і жүрі�. Варианттың �оңына өту үшін ба�ып тұрыңыз + Варианттың �оңына + Келе�і: + Тақта, %1$s кейінгі позици� + Тақта, ба�тапқы позици� + �қтар жеңді + Қаралар жеңді + Тең ойын + Парти�ны оқу мүмкін болмады + + Қозғалтқыш + Ойлануда… + тереңдік %1$d + кідіртілді + Тереңірек + Көбірек вариант + �зырақ вариант + Қозғалтқыш жауап бермейді + Қозғалтқыш бұл телефонда і�ке қо�ылмайды + Қайта і�ке қо�у + Қозғалтқыш варианты · жүрі� %1$d / %2$d + Жабу + Stockfish қозғалтқышы + Позици�ны бағалап, үздік жүрі�терді көр�етеді. Интернет�із жұмы� і�тейді — оны бір рет жүктеп алу жеткілікті. + Көлемі: %1$d МБ + Қазір Wi-Fi жоқ: жүктеу мобильді трафикті пайдаланады. + Қазір еме� + Жүктеп алу + Жүктелді %1$d / %2$d МБ + Ба� тарту + Жүктеу тоқтатылды + Қозғалтқыш дайын + Интернет жоқ. Желіге қо�ылып, қайталап көріңіз. + ChessPenguin: Stockfish қозғалтқышы + Жүктеу тоқтап қалды. Қайталап көріңіз. + Орын жетпейді: %1$d МБ керек. + Қозғалтқыш файлы жүктеу кезінде бүлінді. Қайта жүктеп алыңыз. + Қайталап көру + Қайта жүктеу + OK + Қозғалтқыш дайындалуда… + + Баптаулар + Сыртқы түрі + Қозғалтқыш + Тақырып + Жүйедегідей + �шық + Қараңғы + Жүрі�тер жазба�ы + Латын әріптері (K Q R B N) + Фигуралар белгі�і + Тілдің әріптері + Тек көріні�і. PGN-да әрқашан K Q R B N. + Фигуралар анимаци��ы + Үздік жүрі� көр�еткі�і + Діріл + Stockfish 19 · кіріктірілген + Stockfish 19 · жүктелген + Жүктелмеген · Жүктеп алу (%1$d МБ) + Жүктелуде… %1$d / %2$d МБ + Қозғалтқышты жою (%1$d МБ бо�айды) + Қозғалтқыш жойыл�ын ба? Оны қайта жүктеп алуға болады. + Жою + Варианттар + Позици�ға уақыт + %1$d � + 1 мин + Шектеу�із + �ғындар + Жад + %1$d МБ + Қозғалтқыш батаре�ны пайдаланады. Парти�дан шыққанда неме�е бағдарлама фонға кеткенде ол өзі өшеді. + Бағдарлама туралы + Stockfish кіріктірілген + Stockfish бағдарлама ішінде жүктеледі + Шахмат базалары, парти�ларды талдау және компьютермен ойын. Файлдарыңыз тек оқылады, ешқашан өзгертілмейді. + Лицензи�лар мен авторлар + Сайт және ба�тапқы код + + Парти� мәліметтері + PGN көшіру + FEN көшіру + Парти�мен бөлі�у + Е�кертпелер + қо�улы + өшірулі + жүктелмеген + Табылды %1$s / %2$s + Парти� + %1$d, �қтар, %2$s + %1$d, Қаралар, %2$s + ағымдағы жүрі� + Тіл + Мат + Пат + PGN көшірілді + FEN көшірілді + Турнир + Орны + Күні + Тур + �қтар + Қаралар + �әтиже + �қтардың Elo + Қаралардың Elo + Тү�ініктеме авторы + Жартылай жүрі�тер + Файлға қолжетім жоқ: ол жылжытылған, жойылған неме�е рұқ�аты қайтарылған. Оны тізімнен алып та�тап, қайта қо�ыңыз. + Файл бүлінген неме�е шахмат база�ы еме�. + Мұрағатта PGN неме�е ChessBase база�ы жоқ. + Мұндай базаны оқу мүмкін еме�: %1$s + Файл + PGN, .cbv, .zip неме�е .7z + Қалта + Қалтадағы барлық база, ChessBase (.cbh) те + Базалар ізделуде… + Бұл қалтада база жоқ + Қалтадан және оның ішіндегі екі деңгейлі қалталардан PGN файлдарын, ChessBase базаларын (.cbh, .cbv) және .zip неме�е .7z мұрағаттарын іздейді. + тізімде бар + .cbg файлы жоқ — парти�ларды ашу мүмкін еме� + + «%2$s» ішінде %1$d база + «%2$s» ішінде %1$d база + + + %1$d қо�у + %1$d қо�у + + + %1$d база қо�ылды + %1$d база қо�ылды + + Android бағдарламаларға жад түбірін неме�е Downloads қалта�ының өзін таңдатпайды — тек олардың ішіндегі қалтаны. + Ба�қа�ын таңдау + Дайын + Қо�у + Бәрін белгілеу + Белгілерді алу + %1$s файлы енді база жанында жоқ: ол жылжытылған неме�е жойылған. + Тақта және фигуралар + Қоңыр + Көк + Жа�ыл + Турнирлік + Құм + Маржан + Сұр + Күлгін + Мұз + Қою көк + Жалбыз + Зүбәржат + Қызғылт �ары + Раушан + Ымырт + Түн + �ғаш + Үйеңкі + Былғары + Мәрмәр + Көк мәрмәр + Кенеп + Металл + Зәйтүн + Та� + Жа�ыл пла�тик + Күлгін диагональдар + Қызғылт пирамидалар + �обай + Тақта + Фигуралар + № %1$s + �лма�у буферінен PGN қою + Ба�қа бағдарламада көшірілген парти�лар + �лма�у буферінде PGN парти��ы жоқ + Қойылды: %1$s + + �лма�у буферіндегі парти� + �лма�у буферіндегі парти�лар + + О�ы PGN парти��ын �ақтап, тақтада ашу керек пе? + %1$s �ақтап, бірінші парти�ны тақтада ашу керек пе? Барлық парти�лар жергілікті көшірмеде �ақталады. + �шу + �лма�у буфері + Файл ашылуда… + Файлды ашу мүмкін болмады + Бұл файлда шахмат парти�лары жоқ. + Файлды оқу мүмкін болмады: ол жоқ болуы мүмкін неме�е оны жіберген бағдарлама қолжетім бермеген. Қайта ашып көріңіз. + ChessBase база�ы (.cbh) бірнеше файлдан тұрады, ал тек біреуі келді. Ол жатқан қалтаны қо�ыңыз: «База қо�у» → «Қалта». + Бағдарлама файлдың көшірме�ін �ақтай алмады. Телефонда бо� орын бар екенін тек�еріңіз. + көшірме + База ChessPenguin-нен жойылды + + Парти�ны талдау + Парти� е�ебі + Қозғалтқыш негізгі варианттың әр позици��ын бағалайды. Парти�ның өзі өзгермейді. + %d � + %d мин + Талдау + Толықтыру + %2$d позици�ның %1$d бағаланып қойған. + Парти�ны талдау · %1$d / %2$d + Талдауды тоқтату + Дәлдік + Дәлдік: �қтар %1$s, Қаралар %2$s + Е�еп + %1$s жақ�ырақ еді + Дәл�іздік + Қате + Өре�кел қате + Дәл�іздіктер + Қателер + Өре�кел қателер + Мықты жүрі� + Тамаша жүрі� + Мықты жүрі�тер + Тамаша жүрі�тер + Бағаланбаған: %d + Талдау тоқтап қалды + Жалға�тыру + Орташа �антипешка шығыны + Дебют + Миттельшпиль + Эндшпиль + %1$s · жүрі�ке %2$s түйін + PGN-дағы бағалар ([%eval]) + !! және ! тек қозғалтқышпен: PGN-да тек бағалар бар + Бұл талдауда !! мен ! әлі ізделмеген + Талдау қозғалтқыштың ба�қа баптауларымен жа�алған + Жаңарту + Қозғалтқышпен талдау + Талдауды жа�ыру + Бағалау графигі + Кідіртілді: парти� талдануда + Жақ�ырақ вариант · жүрі� %1$d / %2$d + Келе�і о�ындай жүрі�ке өту + Жақ�ырақ вариантты тақтада көр�ету + %1$s, баға %2$s + Ба�тапқы позици� + + %1$d позици�, шамамен %2$s + %1$d позици�, шамамен %2$s + + + Lichess және Chess.com парти�лары + Кез келген ойыншының парти�лары лақап аты бойынша: өзіңіздің, оқушының, қар�ыла�тың + Ойыншының парти�лары телефоныңызда іздеу, қарау және талдау үшін базаға айналады. Тек лақап ат керек, тіркелгіге кірудің қажеті жоқ. + Ойыншының лақап аты + �айттағыдай + Chess.com-да ба�қа лақап ат + Chess.com-дағы лақап ат + Сол лақап ат + Латын әріптері, �андар, _ және -, 2-ден 30-ға дейін таңба + Табу + Сайттардан ізделуде… + %1$s · алғашқы рет шамамен %2$d мин + парти�лары бар айлар: %1$d + %1$s: мұндай лақап аты бар ойыншы жоқ — жазылуын тек�еріңіз + Екі �айтты бір базаға біріктіру + Әйтпе�е әр �айттың өз база�ы болады + Жаңа «%1$s» база�ына + «%1$s» база�ына (онда %2$s бар; тек жаңа парти�лар қо�ылады) + Жүктеп алу + Lichess: %1$s / шамамен %2$s · шамамен %3$d мин қалды + %1$s: %2$s + Chess.com: ай %1$d / %2$d · %3$s + Тоқтату + +%1$s, барлығы %2$s + Жаңа парти� жоқ, базада %1$s + Тоқтатылды, базада %1$s + Онда �тандартты шахмат парти�лары жоқ. + Базаны ашу + Қайталап көру + %1$s жауап бермейді. Интернет байланы�ын тек�еріп, қайталап көріңіз. + %1$s үзілі� �ұрайды: қатарынан тым көп �ұраны�. Бір минут күтіп, қайталап көріңіз; жүктелгені �ақталады. + %1$s ChessPenguin тү�інбейтін жауап берді: �айт өзгерген болуы мүмкін. Кейінірек көріңіз неме�е ChessPenguin-ді жаңартыңыз. + Базаны жазу мүмкін болмады: телефонда орын тау�ылды. + Бұл база қазір жүктелуде. + %1$s жауап бермейді + %1$s үзілі� �ұрайды + Жүктеу тоқтап қалды + Жаңа парти�ларды жүктеу + Жүктеуді тоқтату + Жүктелуде · %1$s + жаңартылды %1$s + а�қталмаған + Жүктелген база жойылды + Lichess-тегі лақап ат + %1$s · алғашқы рет бір минуттан аз + Бұл �краннан шыға беруге болады: база тізімде, жүктеу жалға�ады. + Дайын: %1$s + жаңа ғана жаңартылды + «%1$s»: +%2$s, барлығы %3$s + «%1$s»: жаңа парти� жоқ + «%1$s»: %2$s + �шу + + %1$s парти�ға дейін + %1$s парти�ға дейін + + %1$s нұ�қа�ы шықты + Сізде %1$s + Жаңарту + Орнату + Базалар, баптаулар мен қозғалтқыш �ақталады. + Базалар мен баптаулар �ақталады. + Орнату кезінде ChessPenguin жабылады — �одан кейін оны қайта ашыңыз. + Парти�лар жүктелуде: орнату оны тоқтатады; кейін жалға�тыруға болады. + Бір рұқ�ат керек + Android дүкеннен ты� бағдарламаларды тек �іздің рұқ�атыңызбен орнатады. Баптаулар ашылады: ChessPenguin үшін ауы�тырғышты қо�ып, қайта оралыңыз. + Баптауларды ашу + Рұқ�ат өшірулі — он�ыз Android жаңа нұ�қаны орнатпайды. + Рұқ�ат берілді, жүктелуде + Сайттан жүктеп алу + Сайтты ашу + Мұны жаба беруге болады: жүктеу жалға�ады. + Желі жоқ. Желі қалпына келгенде жүктеу өзі жалға�ады. + Желі күтілуде + Файл тек�ерілуде… + Қозғалтқыш �ақталуда… + Орнатылуда… + Жаңа нұ�қа жүктелді және тек�ерілді. + Жүктелді және тек�ерілді + Жаңа нұ�қа жүктелді + Орнату тоқтатылды. Жаңа нұ�қа жүктелген — оны қалаған кезде орнатыңыз. + ChessPenguin жаңартуы + ChessPenguin жаңартылды: %1$s → %2$s + Жүктеу �әт�із болды. Қайталап көріңіз. + Файл жүктеу кезінде бүлінді, �ондықтан орнатылмады. Қайталап көріңіз. + Бұл шығарылымда ақау бар: Android файлын тек�еру мүмкін еме�. Жаңа нұ�қаны �айттан жүктеп алыңыз. + Android жаңа нұ�қаны орнатпады: орын жетпейді. %1$d МБ бо�атып, қайталап көріңіз. + Android жаңа нұ�қаны орнатпады: бұл ChessPenguin ба�қа кілтпен қол қойылған. Жаңа нұ�қаны тек о�ыны жойғаннан кейін орнатуға болады, ал жойғанда базалар тізімі мен жүктелген базалар жоғалады. + Android неме�е телефон қорғаны�ы орнатуды тоқтатты. Жаңа нұ�қаны �айттан жүктеп алыңыз. + Android жаңа нұ�қаны орнатпады. Қайталап көріңіз неме�е оны �айттан жүктеп алыңыз. + Интернет жоқ + Орын жетпейді + Файл бүлінді + Android орнатпады + Жүктеу �әт�із болды + Тағы + Толығырақ + Көшіру + Жаңартулар + І�ке қо�қанда жаңартуларды тек�еру + Күніне бір рет ChessPenguin өз �айтынан �оңғы нұ�қаны �ұрайды; �айт жұмы� і�теп тұрған орнатуларды �анайды. Тек о�ы орнатудың кездей�оқ нөмірі, нұ�қа және жүйе жіберіледі. Ұ�ыны�тар өшірулі бол�а да тек�еру жүреді. + Жаңа нұ�қаларды ұ�ыну + Жаңа нұ�қа шыққанда «Базалар» �кранындағы карта. + Жаңартуларды тек�еру қо�улы болғанда жұмы� і�тейді. + Енді ұ�ынбаймыз. Қо�у — Баптаулар, «Бағдарлама туралы» + Жаңартуларды ұ�ынбау + Қазір тек�еру + Тек�ерілуде… + Сізде �оңғы нұ�қа + Тек�ерілді %1$s + Интернет жоқ — жаңартуларды тек�еру мүмкін еме� + Жаңартуларды тек�еру мүмкін болмады: �айт жауап бермеді. Кейінірек көріңіз. + %1$s нұ�қа�ы шықты + %1$s нұ�қа�ы жүктелуде… + %1$s нұ�қа�ы жүктелді + %1$s нұ�қа�ына жаңарту, %3$d мегабайттың %2$d жүктелді + + Файлды тек�еру мүмкін еме� + Қайтару + Жүрі�тер жойылды + �егізгі ету + Жүрі�ті және жалға�ын жою + Жүрі�пен әрекеттер + Жаңа ойын + Менің базаларым + + Жаңа база + Мұнда �із енгізген неме�е компьютермен ойнаған ойындар болады + + Қо�у + Мұнда �із қо�қан PGN және ChessBase файлдары, қалталар және интернеттегі ойындар болады + Файлдар + Менің ойындарым + Жаңа база + �тауы + Телефонда, ChessPenguin ішінде �ақталады. Файлды база мәзірінен �к�порттауға болады. + Құру + телефонда + Файлды �к�порттау… + Базаны жою + Файл �ақталды + Файлды �ақтау мүмкін болмады + База жойылды + «%1$s» жойыл�ын ба? + + Телефоннан %1$s ойын жойылады. Керек бол�а, алдымен файлды �к�порттаңыз. + Телефоннан %1$s ойын жойылады. Керек бол�а, алдымен файлды �к�порттаңыз. + + «%1$s» ішіне �ақталды, № %2$s + Ойынды �ақтау мүмкін болмады + «%1$s» ішіне �ақтау + Менің базама �ақтау… + Базаға �ақтау + Базаға �ақтау… + Жаңа база… + Құру және �ақтау + Өзгері�тер «%1$s» ішіне �ақтал�ын ба? + Ойын �ақтал�ын ба? + Сақтамау + Ойын деректері + ЖЖЖЖ.��.КК + Күн еме�: 2026.10.26, 2026 неме�е 26.10.2026 + Өзгері�тер болдырылма�ын ба? + Болдырмау + Өңдеуді жалға�тыру + Өзгерту + Келе�і + Дебютті үйрену + %1$s дейін + Дебютті о�ы жүрі�ке дейін үйрену + Жүрі� %1$s / %2$s + ♔ �қтар жүреді + ♚ Қаралар жүреді + Қателер: %1$s + Әрекет %1$s + × Парти�да мұнда ба�қа жүрі� + Жүрі�ті көр�ету + Бұл лини� әлі өтілмеген + Соңғы рет: %1$s · қатарынан қате�із: %2$s + Соңғы рет: %1$s · ең үздігі: %2$s + Қате�із өтілді + Көмекпен өтілді · қателер: %1$s + Өтілді · қателер: %1$s + Әрекет %1$s · ең үздігі: %2$s + қатарынан қате�із: %1$s + Соңғылары: %1$s + Көр�еткідегі жүрі�ті жа�аңыз + ↻ Қайталау + ⬅ Парти�ға оралу + Ба�ынан + + %1$d рет + %1$d рет + + ChessPenguin үшін Maia + Сіз жеңдіңіз + Сіз жеңілдіңіз + Сіз берілдіңіз + Тең ойын + мат + пат + позици� үш рет қайталанды + 50 жүрі� бойы алу да, пешка жүрі�і де жоқ + ешбір жақ мат қо� алмайды + Maia берілді + Беріле�із бе? + ⚑ Берілу + ↶ Жүрі�ті қайтару + Компьютермен ойнау + Тү�іңіз + �қтар + Қаралар + Кездей�оқ + Maia-ның өз рейтингі: ол адамның Эло рейтингіне �әйке� келмейді. + Maia бір рет жүктеледі (%1$s МБ, huggingface.co �айтынан — авторлардың өз файлы). + Жүктеп алып ойнау + Ойнау + ойлануда… + Компьютермен парти� + Талдау + ↻ Реванш + О�ы жерден ойнау… + Тек�ерілуде… + Maia і�ке қо�ылмады: %1$s + Жеңі�ті қабылдау + Соңына дейін ойнау + Maia беріледі + Бұдан әрі — Maia %1$s-мен ойын. + Тоқтату + �тыңыз + Maia жүктелді + Қайталау + Оның позици��ы ұтылды. Жеңі�ті қабылдай�ыз ба, әлде жалға�тыра�ыз ба? + Жалға�тыру + Maia %1$s-мен ойын · �із %2$s + ақпен + қарамен + Ойын жойылды + �ағат�ыз + Сіз + ✓ Сақталды + Сақтау… + �із %1$s · %2$s + %1$s кейін + Дыбы� + Болдырмау + Енді негізгі нұ�қа + Эло + Талдау + Жалға�тыру + Қарау %1$s · ойынға оралу › + ба�тапқы позици� + Maia і�ке қо�ылмады. + Maia-ны қайта жүктеу + %1$s-мен кейінге қалдырылған ойын бар + Жалға�тыру + Жаңа�ын ба�тау + Жаңа ойын оның орнын ба�ады; ойналғаны а�қталмаған күйде ойыншы база�ына жазылады. + Тең + келі�ім бойынша + Maia тең ойыннан ба� тартады + Maia ба� тартты; оның екі жүрі�інен кейін қайта ұ�ыныңыз + Maia тең ойынға Stockfish арқылы жауап береді: оны «Қозғалтқыш» батырма�ымен жүктеңіз + %1$s — компьютермен ойындар + Компьютермен ойындар + ✓ «%1$s» база�ында, № %2$s › + Ойын а�қталмаған күйде «%1$s» база�ына жазылды + өзі жазылады + Компьютермен ойындарды ойыншы база�ына жазу + Ойындар «%1$s» база�ына жазылады + Ойындар жаңа «%1$s» база�ына жазылады. + �т�ыз ойындар «%1$s» база�ына тү�еді. Өз базаңыз болуы үшін атыңызды жазыңыз. + Ойындар өзі жазылмайды (Баптаулар). + ✓ Жаңа база «%1$s», № %2$s › + «%1$s» база�ына жазу мүмкін болмады: %2$s + Жаңа ойын оның орнын ба�ады. + Соңғы ашылған + %1$s-мен ойын + %1$d-жүрі� + + �манда + �лдымен шабуылдайды, кейін фигуралар бел�енділігіне ойнайды. + Клои + Жабық позици�ларды ұнатады. + Дебора + Жақ�ы қорғанады және пілдерін ұнатады. + Қорғаушы + Сенімді әрі �ақ; тең ойынға келі�еді. + Динамик + Шабуылдайды, пілдерді ұнатады, анда-�анда құрбан етеді. + Күңкілдек + Шабуыл мен қы�у; бітелген позици�ларды ұнатады, тең ойыннан қашады. + Партизан + Тыныш, байқалмайтын дебюттерден кейін шабуылдайды. + Гамбитші + Теңгерімді, бірақ пешкаларды оңай береді. + Педрита + Пешкалар, қорғаны� және қы�у. + Пре�тон + Материали�т, қалыпты шабуылшы. + Қарапайым + Ең «компьютерлік»: қарапайым, дұры� шахмат. + Қызба + Өткір және агре��ивті. + Тұншықтырушы + �йдаһар-жылан: ба�у қы�ады, өте адамға ұқ�а�. + �лехин + Серпінді шабуылдар мен терең комбинаци�лар. + �нанд + Жылдам, әмбебап ойын, өткір дебюттермен. + �ндер�ен + XIX ға�ырдың романтик шабуылшы�ы: құрбандар. + Бо�бум + Әдеттен ты� дебюттер және шығармашыл блиц. + Ботвинник + Терең дайындыққа негізделген ғылыми, �тратеги�лық ойын. + Фишер + �нық, кла��икалық және дәл. + Карпов + Позици�лық қы�ым, профилактика және техника. + Ка�паров + Ба�тама және қуатты шабуыл. + Корчной + Табанды қорғаушы және қар�ы шабуылшы. + Лар�ен + Өзгеше және тәуекелшіл, әдеттен ты� дебюттермен. + Ла�кер + Практикалық, п�ихолог күре�кер. + Маршалл + Гамбиттері бар батыл шабуылшы. + Морфи + Жылдам дамыту және ашық �ызықтар. + �имцович + Қы�у, блокада және артық қорғау. + Петро��н + Профилактика және қауіп�іздік бірінші. + Рети + Гиперзаманауи: орталықты алы�тан бақылайды. + Рубинштейн + Кла��икалық позици�лық ойын, �ндшпильде мықты. + Спа��кий + Әмбебап ойыншы, кез келген позици�да өзін үйдегідей �езінеді. + Стейниц + Позици�лық ойынның негізін �алушы, қыңыр қорғаушы. + Таль + Ригалық �иқыршы: құрбандар мен шабуыл. + Тарраш + Кла��икалық ережелер: кеңі�тік, дамыту, бел�енді фигуралар. + Топалов + �гре��ивті және �ерпінді, �апаны құрбан етеді. + адам �и�қты ойнайды + күшті, �тилімен + �дам �и�қты + Maia �тиль таңдамайды: ол өз рейтингіндегі адамдар �и�қты ойнайды. + Rodent-тің өз рейтингі (UCI_Elo): ол адамның Эло рейтингіне �әйке� келмейді. + Rodent беріледі + Rodent берілді + Rodent тең ойыннан ба� тартады + Rodent ба� тартты; оның екі жүрі�інен кейін қайта ұ�ыныңыз + Оның позици��ы ұтылды. Жеңі�ті қабылдай�ыз ба, әлде �оңына дейін ойнай�ыз ба? + Ойнау + Компьютермен ойнау + Күші: %1$s + Кіммен ойнау + Мінез — бұл �тиль мен дебюттер, күшті жүгірткі белгілейді. + Ұлы шахматшылар + Мінездер + Өзгерту + %1$s, ұлы шахматшы + %1$s, мінез + Мінез: %1$s + Rodent IV және оның дебют кітаптары телефонда + Rodent IV дебют кітаптары: %1$s МБ, github.com �айтынан бір рет + Позици�дан ойнағанда дебют кітабы керек еме� — Rodent IV бірден ойнайды + Кітап�ыз + Кітап�ыз: дебют кітабы�ыз ойнау + Rodent IV дебют кітаптары + Rodent IV — дебют кітаптары + жүктелген · %1$s МБ + жүктелмеген · %1$s МБ + Дебют кітаптары жойылды + Rodent тең ойынға Stockfish арқылы жауап береді: оны «Қозғалтқыш» батырма�ымен жүктеңіз + Rodent і�ке қо�ылмады. + Қайта і�ке қо�у + Бұдан әрі — Rodent IV %1$s-мен ойын (%2$s). + Rodent ойын кезінде тоқтады. + %1$s, %2$s-ден %3$s-ге дейін + Күші + Дебют кітаптарын жою + + + Ойыншылар + Ойыншының аты + Ойыншыларды оқу мүмкін болмады + Ойыншылар оқылуда… + Бұл базада аты көр�етілген ойыншылар жоқ + Ойыншы табылмады + Парти�ларға оралу + Іздеуді тазалау + Дайындалу + Тү�ті таңдаңыз + Қар�ыла�қа дайындалу %1$s + �қтарға қар�ы + Қараларға қар�ы + Қар�ыла�қа дайындалу… + Қар�ыла�қа дайындық + �лдымен қозғалтқыш желі�ін жабыңыз + + Оқу -- кейін іздеу қолжетім�із + �қтар + Қаралар + Бұл жүрі�ті жа�ау мүмкін болмады + %1$s жүру, %2$s, %3$s пайыз + Тақта, ба�тапқы позици�. Төменде %1$s. + Тақта, %1$s кейінгі позици�. Төменде %2$s. + �қтардың жүрі�і + Қаралардың жүрі�і + Қар�ыла� жүреді + Оның қар�ыла�тары жүреді + %1$s кейін + ба�ы + %1$s, %2$s, %3$s, %4$s + Жалға�тарды е�ептеу мүмкін болмады + Бұл базадан іздеуге жад жеткілік�із + Жалға�тар е�ептелуде… + %1$s парти�ларында бұл позици� жоқ + Тақтада жалға�тыруға неме�е артқа оралуға болады + Барлық парти� о�ы жерде а�қталды + О�ы жерде а�қталды: %1$s + Қалыпты жалға� жоқ: %1$s + Парти�ға оралу + Ойыншыларға оралу + Жүрі�ті таңдаңыз + %1$s жеңі�%1$s жеңі� + %1$s тең ойын%1$s тең ойын + %1$s жеңілі�%1$s жеңілі� + Белгі�із нәтижелер: %1$d; олар пайызға кірмейді. + %1$s. %3$s ішінен %2$d, %4$s пайыз. %5$s нәтижелері: %6$s, %7$s, %8$s; %9$s, %10$s және %11$s пайыз. %12$s Жүру. + Жүру + тағы %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values-night/themes.xml b/androidApp/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..ccd27c6 --- /dev/null +++ b/androidApp/app/src/main/res/values-night/themes.xml @@ -0,0 +1,8 @@ + + + + diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml new file mode 100644 index 0000000..578c2d3 --- /dev/null +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -0,0 +1,734 @@ + + Partidas clássicas + Alekhine + + Suas bases vão aparecer aqui + Adicione um arquivo PGN, uma base ChessBase ou um arquivo .zip/.7z — do celular ou da nuvem — ou baixe partidas do Lichess e do Chess.com. + Adicionar base + Abrir partidas de exemplo + ainda não aberta · %1$s + + %1$s partida + %1$s partidas + %1$s partidas + + %1$s · %2$s + Menu + Renomear + Remover da lista + O nome na lista. O arquivo não é alterado. + Cancelar + Salvar + Base removida da lista + Desfazer + Voltar + + Lendo… + Não foi possível abrir a base + Buscar + Jogador, evento, ano + Nada encontrado + Limpar + + %1$d de %2$d + Partida anterior + Próxima partida + Girar tabuleiro + Ao início + Voltar um lance + Avançar um lance + Lance anterior. Mantenha premido para ir ao início + Lance seguinte. Mantenha premido para ir ao fim da linha + Ao fim da linha + Próximo: + Tabuleiro, posição após %1$s + Tabuleiro, posição inicial + Brancas venceram + Pretas venceram + Empate + Não foi possível ler a partida + + Motor + Pensando… + profundidade %1$d + em pausa + Mais fundo + Mais linhas + Menos linhas + O motor não está respondendo + O motor não inicia neste celular + Reiniciar + Linha do motor · lance %1$d de %2$d + Fechar + Motor Stockfish + Avalia a posição e mostra os melhores lances. Funciona offline — basta baixar uma vez. + Tamanho: %1$d MB + Sem Wi-Fi agora: o download usará dados móveis. + Agora não + Baixar + Baixados %1$d de %2$d MB + Cancelar + Download cancelado + O motor está pronto + Sem internet. Conecte-se a uma rede e tente de novo. + ChessPenguin: motor Stockfish + O download parou. Tente de novo. + Espaço insuficiente: são necessários %1$d MB. + O arquivo do motor foi danificado durante o download. Baixe de novo. + Tentar de novo + Baixar de novo + OK + Preparando o motor… + + Configurações + Aparência + Motor + Tema + Padrão do sistema + Claro + Escuro + Notação dos lances + Letras latinas (K Q R B N) + Figurinhas + Letras do idioma + Só na tela. O PGN sempre usa K Q R B N. + Animação das peças + Seta do melhor lance + Vibração + Stockfish 19 · embutido + Stockfish 19 · baixado + Não baixado · Baixar (%1$d MB) + Baixando… %1$d de %2$d MB + Excluir o motor (libera %1$d MB) + Excluir o motor? Você pode baixá-lo de novo. + Excluir + Linhas + Tempo por posição + %1$d s + 1 min + Sem limite + Threads + Memória + %1$d MB + O motor gasta bateria. Ele desliga sozinho quando você sai da partida ou o app vai para segundo plano. + Sobre + Stockfish embutido + Stockfish baixado no app + Bases de xadrez, análise de partidas e jogo contra o computador. Os seus arquivos são só lidos, nunca alterados. + Licenças e autores + Site e código-fonte + + Detalhes da partida + Copiar PGN + Copiar FEN + Compartilhar partida + Notas + ligado + desligado + não baixado + Encontradas %1$s de %2$s + Partida + %1$d, brancas, %2$s + %1$d, pretas, %2$s + lance atual + Idioma + Xeque-mate + Afogamento + PGN copiado + FEN copiado + Evento + Local + Data + Rodada + Brancas + Pretas + Resultado + Elo das brancas + Elo das pretas + Comentarista + Meios-lances + Sem acesso ao arquivo: ele foi movido, excluído ou a permissão foi retirada. Remova-o da lista e adicione de novo. + O arquivo está danificado ou não é uma base de xadrez. + Não há base PGN ou ChessBase no arquivo compactado. + Este tipo de base não pode ser lido: %1$s + Arquivo + PGN, .cbv, .zip ou .7z + Pasta + Todas as bases de uma pasta, inclusive ChessBase (.cbh) + Procurando bases… + Nenhuma base nesta pasta + Procura arquivos PGN, bases ChessBase (.cbh, .cbv) e arquivos .zip ou .7z na pasta e em até dois níveis de pastas dentro dela. + já está na lista + sem arquivo .cbg — as partidas não podem ser abertas + + %1$d base em “%2$s� + %1$d bases em “%2$s� + %1$d bases em “%2$s� + + + Adicionar %1$d + Adicionar %1$d + Adicionar %1$d + + + %1$d base adicionada + %1$d bases adicionadas + %1$d bases adicionadas + + O Android não deixa os apps escolherem a raiz do armazenamento nem a própria pasta Downloads — só uma pasta dentro delas. + Escolher outra + Concluído + Adicionar + Marcar todas + Desmarcar todas + O arquivo %1$s não está mais junto da base: foi movido ou excluído. + Tabuleiro e peças + Marrom + Azul + Verde + Torneio + Areia + Coral + Cinza + Roxo + Gelo + Marinho + Menta + Esmeralda + Laranja + Rosa + Crepúsculo + Noite + Madeira + Bordo + Couro + Mármore + Mármore azul + Tela + Metal + Oliva + Pedra + Plástico verde + Diagonal roxa + Pirâmide rosa + Esboço + Tabuleiro + Peças + Nº %1$s + Colar PGN da área de transferência + Partidas copiadas em outro app + Nenhuma partida PGN na área de transferência + Colado %1$s + + %1$s partida na área de transferência + %1$s partidas na área de transferência + %1$s partidas na área de transferência + + Salvar esta partida PGN e abri-la no tabuleiro? + Salvar %1$s e abrir a primeira partida no tabuleiro? Todas as partidas serão mantidas na cópia local. + Abrir + �rea de transferência + Abrindo o arquivo… + Não foi possível abrir o arquivo + Não há partidas de xadrez neste arquivo. + Não foi possível ler o arquivo: talvez ele não exista mais, ou o app de onde veio não deu acesso a ele. Tente abri-lo de novo. + Uma base ChessBase (.cbh) é feita de vários arquivos, e só um chegou. Adicione a pasta onde ela está: \"Adicionar base\" → \"Pasta\". + O app não conseguiu guardar uma cópia do arquivo. Verifique se o celular tem espaço livre. + cópia + Base excluída do ChessPenguin + + Análise da partida + Relatório da partida + O motor avalia cada posição da linha principal. A partida em si não é alterada. + %d s + %d min + Analisar + Completar + %1$d de %2$d posições já estão avaliadas. + Análise da partida · %1$d de %2$d + Parar a análise + Precisão + Precisão: brancas %1$s, pretas %2$s + Relatório + %1$s era melhor + Imprecisão + Erro + Erro grave + Imprecisões + Erros + Erros graves + Ótimo lance + Lance brilhante + Ótimos lances + Lances brilhantes + Não avaliadas: %d + A análise parou + Continuar + Perda média de centipeões + Abertura + Meio-jogo + Final + %1$s · %2$s nós por lance + Avaliações do PGN ([%eval]) + !! e ! exigem o motor: o PGN traz só avaliações + Esta análise ainda não procurou !! e ! + Análise feita com outras definições do motor + Atualizar + Analisar com o motor + Ocultar análise + Gráfico de avaliação + Em pausa: a partida está sendo analisada + Linha melhor · lance %1$d de %2$d + Ir para o próximo lance assim + Mostrar a linha melhor no tabuleiro + %1$s, avaliação %2$s + Posição inicial + + %1$d posição, cerca de %2$s + %1$d posições, cerca de %2$s + %1$d posições, cerca de %2$s + + + Partidas do Lichess e do Chess.com + Partidas de qualquer jogador pelo nick: suas, de um aluno, de um adversário + As partidas do jogador viram uma base no seu celular, para buscar, ver e analisar. Basta o nick, sem login. + Nick do jogador + como no site + Outro nick no Chess.com + Nick no Chess.com + O mesmo nick + Letras latinas, números, _ e -, de 2 a 30 caracteres + Buscar + Procurando nos sites… + %1$s · cerca de %2$d min na primeira vez + meses com partidas: %1$d + %1$s: nenhum jogador com este nick — confira a grafia + Juntar os dois sites em uma base + Senão cada site recebe uma base própria + Para a nova base “%1$s� + Para “%1$s� (já tem %2$s; só partidas novas são adicionadas) + Baixar + Lichess: %1$s de cerca de %2$s · faltam cerca de %3$d min + %1$s: %2$s + Chess.com: mês %1$d de %2$d · %3$s + Parar + +%1$s, %2$s no total + Sem partidas novas, %1$s na base + Parado, %1$s na base + Não há partidas de xadrez padrão ali. + Abrir a base + Tentar de novo + %1$s não responde. Verifique a conexão com a internet e tente de novo. + %1$s pede uma pausa: muitas solicitações seguidas. Espere um minuto e tente de novo; o que foi baixado fica guardado. + %1$s respondeu de um jeito que o ChessPenguin não entende: o site pode ter mudado. Tente mais tarde ou atualize o ChessPenguin. + Não foi possível gravar a base: o celular está sem espaço. + Esta base já está sendo baixada. + %1$s não responde + %1$s pede uma pausa + O download parou + Baixar partidas novas + Parar o download + Baixando · %1$s + atualizada %1$s + não concluída + Base baixada excluída + Nick no Lichess + %1$s · menos de um minuto na primeira vez + Você pode sair desta tela: a base está na lista e o download continua. + Concluído: %1$s + atualizada agora + “%1$s�: +%2$s, %3$s no total + “%1$s�: sem partidas novas + “%1$s�: %2$s + Abrir + + até %1$s partida + até %1$s partidas + até %1$s partidas + + Saiu a versão %1$s + Você tem a %1$s + Atualizar + Instalar + Bases, configurações e o motor ficam. + Bases e configurações ficam. + O ChessPenguin fecha durante a instalação — depois abra-o de novo. + Partidas estão sendo baixadas: instalar interrompe isso; você pode continuar depois. + É preciso uma permissão + O Android só instala apps de fora de uma loja com a sua permissão. As configurações vão abrir: ative a chave para o ChessPenguin e volte. + Abrir configurações + A permissão está desativada — sem ela o Android não instala a nova versão. + Permissão concedida, baixando + Baixar no site + Abrir o site + Você pode fechar isto: o download continua. + Sem rede. O download continua sozinho quando a rede voltar. + Aguardando rede + Verificando o arquivo… + Guardando o motor… + Instalando… + A nova versão foi baixada e verificada. + Baixada e verificada + A nova versão foi baixada + Instalação cancelada. A nova versão está baixada — instale quando quiser. + Atualização do ChessPenguin + O ChessPenguin foi atualizado: %1$s → %2$s + O download falhou. Tente de novo. + O arquivo foi danificado durante o download, por isso não foi instalado. Tente de novo. + Há algo errado com esta versão: o arquivo para Android não pode ser verificado. Baixe a nova versão no site. + O Android não instalou a nova versão: espaço insuficiente. Libere %1$d MB e tente de novo. + O Android não instalou a nova versão: este ChessPenguin foi assinado com outra chave. A nova versão só pode ser instalada depois de remover esta, e ao removê-la perdem-se a lista de bases e as bases baixadas. + O Android ou a proteção do celular bloqueou a instalação. Baixe a nova versão no site. + O Android não instalou a nova versão. Tente de novo ou baixe-a no site. + Sem internet + Espaço insuficiente + O arquivo foi danificado + O Android não instalou + O download falhou + Mais + Detalhes + Copiar + Atualizações + Verificar atualizações ao iniciar + Uma vez por dia o ChessPenguin pergunta ao seu site qual é a versão mais recente; o site conta as instalações em uso. São enviados apenas um número aleatório desta instalação, a versão e o sistema. A verificação continua mesmo sem as ofertas. + Oferecer novas versões + Um cartão na tela Bases quando sai uma nova versão. + Funciona com a verificação de atualizações ligada. + Não vamos mais oferecer. Ative em Configurações, Sobre + Não oferecer atualizações + Verificar agora + Verificando… + Você tem a versão mais recente + Verificado %1$s + Sem internet — não é possível verificar atualizações + Não foi possível verificar atualizações: o site não respondeu. Tente mais tarde. + Saiu a versão %1$s + Baixando a versão %1$s… + A versão %1$s foi baixada + Atualização para %1$s, %2$d de %3$d megabytes baixados + + O arquivo não pode ser verificado + Desfazer + Lances excluídos + Tornar linha principal + Excluir o lance e a continuação + Ações do lance + Nova partida + Minhas bases + + Nova base + Aqui ficarão as partidas que você inserir ou jogar contra o computador + + Adicionar + Aqui ficarão os arquivos PGN e ChessBase, as pastas e as partidas da internet que você adicionar + Arquivos + Minhas partidas + Nova base + Nome + Fica no telefone, no ChessPenguin. O arquivo pode ser exportado no menu da base. + Criar + no telefone + Exportar o arquivo… + Excluir a base + Arquivo salvo + Não foi possível salvar o arquivo + Base excluída + Excluir “%1$s�? + + %1$s partida será excluída do telefone. Se precisar dela, exporte o arquivo antes. + %1$s partidas serão excluídas do telefone. Se precisar delas, exporte o arquivo antes. + %1$s partidas serão excluídas do telefone. Se precisar delas, exporte o arquivo antes. + + Salva em “%1$s�, nº %2$s + Não foi possível salvar a partida + Salvar em “%1$s� + Salvar na minha base… + Salvar numa base + Salvar numa base… + Nova base… + Criar e salvar + Salvar as alterações em “%1$s�? + Salvar a partida? + Não salvar + Dados da partida + AAAA.MM.DD + Não é uma data: 2026.10.26, 2026 ou 26.10.2026 + Descartar as alterações? + Descartar + Continuar editando + Editar + Avançar + Aprendendo a abertura + até %1$s + Aprender a abertura até este lance + Lance %1$s de %2$s + ♔ Brancas jogam + ♚ Pretas jogam + Erros: %1$s + Rodada %1$s + × Na partida há outro lance aqui + Mostrar o lance + Linha ainda não treinada + Última vez: %1$s · sem erros seguidos: %2$s + Última vez: %1$s · melhor: %2$s + Concluído sem erros + Concluído com dica · erros: %1$s + Concluído · erros: %1$s + Rodada %1$s · melhor: %2$s + sem erros seguidos: %1$s + Recentes: %1$s + Jogue o lance da seta + ↻ De novo + ⬅ Voltar à partida + Do início + + %1$d passagem + %1$d passagens + %1$d passagens + + Maia para o ChessPenguin + Você venceu + Você perdeu + Você abandonou + Empate + xeque-mate + afogamento + a posição se repetiu três vezes + 50 lances sem captura nem lance de peão + nenhum lado consegue dar mate + Maia desistiu + Abandonar? + ⚑ Abandonar + ↶ Voltar lance + Jogar contra o computador + Sua cor + Brancas + Pretas + Aleatório + O rating próprio da Maia: não corresponde ao Elo de uma pessoa. + A Maia é baixada uma única vez (%1$s MB, de huggingface.co, o arquivo dos próprios autores). + Baixar e jogar + Jogar + pensando… + Partida contra o computador + Analisar + ↻ Revanche + Jogar a partir daqui… + Verificando… + A Maia não iniciou: %1$s + Aceitar a vitória + Jogar até o fim + Maia desiste + A partir daqui, uma partida contra Maia %1$s. + Abortar + O seu nome + A Maia foi baixada + Tentar de novo + A posição dela está perdida. Aceitar a vitória ou continuar? + Continuar + Partida contra a Maia %1$s · você joga de %2$s + brancas + pretas + Partida removida + sem relógio + Você + ✓ Salva + Salvar… + você joga de %1$s · %2$s + Depois de %1$s + Som + Desfazer + Agora é a linha principal + Elo + Analisar + Continuar + Vendo %1$s · voltar à partida › + a posição inicial + A Maia não iniciou. + Baixar a Maia de novo + Há uma partida adiada contra %1$s + Continuá-la + Começar uma nova + Uma nova partida a substitui; o que foi jogado vai, inacabado, para a base do jogador. + Empate + por acordo + A Maia recusa o empate + A Maia recusou; ofereça de novo após dois lances dela + A Maia responde ao empate com o Stockfish: baixe-o com «Motor» + %1$s — partidas contra o computador + Partidas contra o computador + ✓ Em «%1$s», n.º %2$s › + Partida gravada inacabada em «%1$s» + gravadas sozinhas + Gravar as partidas contra o computador na base do jogador + As partidas são gravadas em «%1$s» + As partidas serão gravadas numa nova base «%1$s». + Sem nome, as partidas vão para «%1$s». Escreva um nome para ter a sua própria base. + As partidas não são gravadas sozinhas (Definições). + ✓ Nova base «%1$s», n.º %2$s › + Não foi possível gravar em «%1$s»: %2$s + Uma nova partida a substitui. + Aberta por último + Partida contra %1$s + lance %1$d + + Amanda + Primeiro ataca, depois joga pela atividade das peças. + Cloe + Gosta de posições fechadas. + Débora + Defende bem e gosta dos seus bispos. + Defensor + Sólido e cuidadoso; contenta-se com o empate. + Dinâmico + Ataca, gosta de bispos, sacrifica de vez em quando. + Rabugento + Ataque e restrição; gosta de posições bloqueadas, evita empates. + Partisano + Ataca depois de aberturas calmas e discretas. + Gambiteiro + Equilibrado, mas entrega peões com mais facilidade. + Pedrita + Peões, defesa e restrição. + Preston + Um atacante materialista e moderado. + Simples + O mais «computador»: xadrez simples e sólido. + Esquentado + Agudo e agressivo. + Estrangulador + Uma jiboia: aperta devagar, muito humano. + Alekhine + Ataques dinâmicos e combinações profundas. + Anand + Jogo rápido e universal com aberturas agudas. + Anderssen + Um atacante romântico do século XIX: sacrifícios. + Bosboom + Aberturas incomuns e blitz criativo. + Botvinnik + Jogo estratégico e científico, preparação profunda. + Fischer + Claro, clássico e preciso. + Karpov + Pressão posicional, profilaxia e técnica. + Kasparov + Iniciativa e ataque poderoso. + Kortchnoi + Um defensor tenaz e contra-atacante. + Larsen + Original e arriscado, com aberturas incomuns. + Lasker + Um lutador prático e psicológico. + Marshall + Um atacante ousado com gambitos. + Morphy + Desenvolvimento rápido e linhas abertas. + Nimzowitsch + Restrição, bloqueio e superproteção. + Petrosian + Profilaxia e segurança acima de tudo. + Reti + Hipermoderno: controla o centro à distância. + Rubinstein + Jogo posicional clássico, ótimo em finais. + Spassky + Um jogador universal, à vontade em qualquer posição. + Steinitz + O fundador do jogo posicional, um defensor obstinado. + Tal + O mágico de Riga: sacrifícios e ataque. + Tarrasch + Regras clássicas: espaço, desenvolvimento, peças ativas. + Topalov + Agressivo e dinâmico, sacrifica a qualidade. + joga como um humano + forte, com estilo + Como um humano + A Maia não escolhe estilo: joga como as pessoas do nível dela. + O rating próprio do Rodent (UCI_Elo): não corresponde ao Elo de uma pessoa. + O Rodent desiste + O Rodent desistiu + O Rodent recusa o empate + O Rodent recusou; ofereça de novo após dois lances dele + A posição dele está perdida. Aceitar a vitória ou jogar até o fim? + Jogar + Jogar contra o computador + Força: %1$s + Contra quem jogar + Um caráter é um estilo e suas aberturas; a força é definida pelo controle deslizante. + Grandes jogadores + Caracteres + Alterar + %1$s, grande jogador + %1$s, caráter + Caráter: %1$s + O Rodent IV e seus livros de aberturas estão no telefone + Livros de aberturas do Rodent IV: %1$s MB, baixados uma vez de github.com + A partir de uma posição não é preciso livro de aberturas: o Rodent IV joga na hora + Sem livro + Sem livro: jogar sem livro de aberturas + Livros de aberturas do Rodent IV + Rodent IV — livros de aberturas + baixados · %1$s MB + não baixados · %1$s MB + Livros de aberturas excluídos + O Rodent responde ao empate com o Stockfish: baixe-o com «Motor» + O Rodent não iniciou. + Reiniciar + A partir daqui, uma partida contra Rodent IV %1$s · %2$s. + O Rodent parou durante a partida. + %1$s, de %2$s a %3$s + Força + Excluir os livros de aberturas + + + Jogadores + Nome do jogador + Não foi possível ler os jogadores + A ler jogadores… + Não há jogadores identificados nesta base + Jogador não encontrado + Voltar às partidas + Limpar pesquisa + Preparar + Escolha uma cor + Preparar contra %1$s + Contra as brancas + Contra as pretas + Preparar contra o adversário… + Preparação contra o adversário + Feche primeiro a linha do motor + + A pesquisa depois de um -- didático não está disponível + Brancas + Pretas + Não foi possível jogar este lance + Jogar %1$s, %2$s, %3$s por cento + Tabuleiro, posição inicial. %1$s em baixo. + Tabuleiro, posição depois de %1$s. %2$s em baixo. + Jogam as brancas + Jogam as pretas + O adversário joga + Os seus adversários jogam + depois de %1$s + início + %1$s, %2$s, %3$s, %4$s + Não foi possível calcular as continuações + Memória insuficiente para pesquisar nesta base + A calcular continuações… + Esta posição não ocorre nas partidas de %1$s + Pode continuar no tabuleiro ou retroceder + Todas as partidas terminaram aqui + Terminaram aqui: %1$s + Sem continuação normal: %1$s + Voltar à partida + Voltar aos jogadores + Escolha um lance + %1$s vitória%1$s vitórias%1$s vitórias + %1$s empate%1$s empates%1$s empates + %1$s derrota%1$s derrotas%1$s derrotas + Resultados desconhecidos: %1$d; excluídos das percentagens. + %1$s. %2$d de %3$s, %4$s por cento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s por cento. %12$s Jogar. + Jogar + mais %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml new file mode 100644 index 0000000..83254ab --- /dev/null +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -0,0 +1,757 @@ + + Кла��иче�кие партии + �лехин + + Зде�ь будут ваши базы + Добавьте файл PGN, базу ChessBase или архив .zip/.7z — � телефона или из облака — или �качайте партии � Lichess и Chess.com. + Добавить базу + Открыть примеры партий + ещё не открывала�ь · %1$s + + %1$s парти� + %1$s партии + %1$s партий + %1$s партии + + %1$s · %2$s + Меню + Переименовать + Убрать из �пи�ка + �азвание в �пи�ке. Файл не мен�ет��. + Отмена + Сохранить + База убрана из �пи�ка + Вернуть + �азад + + Читаю… + �е удало�ь открыть базу + Пои�к + Игрок, турнир, год + �ичего не найдено + Очи�тить + + %1$d из %2$d + Предыдуща� парти� + Следующа� парти� + Перевернуть до�ку + В начало + Ход назад + Ход вперёд + Предыдущий ход. Удерживайте дл� перехода в начало + Следующий ход. Удерживайте дл� перехода в конец линии + В конец линии + Дальше: + До�ка, позици� по�ле %1$s + До�ка, начальна� позици� + Победили белые + Победили чёрные + �ичь� + �е удало�ь прочитать партию + + Движок + Считаю… + гл. %1$d + пауза + Глубже + Больше линий + Меньше линий + Движок не отвечает + Движок не запу�кает�� на �том телефоне + Перезапу�тить + Лини� движка · ход %1$d из %2$d + Закрыть + Движок Stockfish + Оценивает позицию и показывает лучшие ходы. Работает без интернета — нужно один раз �качать. + Размер: %1$d МБ + Сейча� нет Wi-Fi: загрузка пойдёт через мобильный интернет. + �е �ейча� + Скачать + Скачано %1$d из %2$d МБ + Отменить + Загрузка отменена + Движок готов + �ет интернета. Подключите�ь к �ети и попробуйте ещё раз. + ChessPenguin: движок Stockfish + Загрузка о�тановила�ь. Попробуйте ещё раз. + �е хватает ме�та: нужно %1$d МБ. + Файл движка повреждён при загрузке. Скачайте его ещё раз. + Повторить + Скачать �нова + Пон�тно + Готовлю движок… + + �а�тройки + Внешний вид + Движок + Тема + Как в �и�теме + Светла� + Тёмна� + Запи�ь ходов + Латин�кие буквы (K Q R B N) + Фигурки + Ру��кие буквы (Кр Ф Л С К) + Только вид на �кране. В PGN в�егда K Q R B N. + �нимаци� фигур + Стрелка лучшего хода + Вибраци� + Stockfish 19 · в�троен + Stockfish 19 · �качан + �е �качан · Скачать (%1$d МБ) + Скачивает��… %1$d из %2$d МБ + Удалить движок (о�вободит %1$d МБ) + Удалить движок? Его можно �качать �нова. + Удалить + Линий + Врем� на позицию + %1$d � + 1 мин + Без ограничени� + Потоки + Пам�ть + %1$d МБ + Движок ра�ходует зар�д. Он �ам выключает��, когда вы выходите из партии или �ворачиваете приложение. + О программе + Stockfish уже внутри + Stockfish �качивает�� в приложении + Шахматные базы, анализ партий и игра � компьютером. Ваши файлы только читают�� и никогда не мен�ют��. + Лицензии и авторы + Сайт и и�ходный код + + Сведени� о партии + Копировать PGN + Копировать FEN + Поделить�� партией + Замечани� + включён + выключен + не �качан + �айдено %1$s из %2$s + Парти� + %1$d, белые, %2$s + %1$d, чёрные, %2$s + текущий ход + Язык + Мат + Пат + PGN �копирован + FEN �копирован + Турнир + Ме�то + Дата + Тур + Белые + Чёрные + Результат + Эло белых + Эло чёрных + Комментатор + Полуходов + �ет до�тупа к файлу: его переме�тили, удалили или отозвали разрешение. Уберите базу из �пи�ка и добавьте �нова. + Файл повреждён или �то не шахматна� база. + В архиве нет базы PGN или ChessBase. + Такую базу прочитать нельз�: %1$s + Файл + PGN, .cbv, .zip или .7z + Папка + В�е базы в папке, в том чи�ле ChessBase (.cbh) + Ищу базы… + В папке нет баз + Подход�т файлы PGN, базы ChessBase (.cbh, .cbv) и архивы .zip и .7z — в �амой папке и во вложенных папках на два уровн�. + уже в �пи�ке + нет файла .cbg — партии не открыть + + В папке «%2$s» найдена %1$d база + В папке «%2$s» найдены %1$d базы + В папке «%2$s» найдено %1$d баз + В папке «%2$s» найдено %1$d базы + + + Добавить %1$d + Добавить %1$d + Добавить %1$d + Добавить %1$d + + + Добавлена %1$d база + Добавлены %1$d базы + Добавлено %1$d баз + Добавлено %1$d базы + + Корень пам�ти и �аму «Загрузки» выбрать нельз� — только папку внутри них. + Выбрать другую + Готово + Добавить + Отметить в�е + Сн�ть в�е + Р�дом � базой больше нет файла %1$s: его переме�тили или удалили. + До�ка и фигуры + Коричнева� + Син�� + Зелёна� + Турнирна� + Пе�очна� + Мор�ка� + Сера� + Фиолетова� + Лёд + Тёмно-�ин�� + М�та + Изумруд + Оранжева� + Розова� + Сумерки + �очь + Дерево + Клён + Кожа + Мрамор + Синий мрамор + Хол�т + Металл + Олива + Камень + Зелёный пла�тик + Фиолетовые диагонали + Розовые пирамиды + �абро�ок + До�ка + Фигуры + № %1$s + В�тавить PGN из буфера + Партии, �копированные в другом приложении + В буфере нет партий в формате PGN + Из буфера, %1$s + + %1$s парти� в буфере обмена + %1$s партии в буфере обмена + %1$s партий в буфере обмена + %1$s партии в буфере обмена + + Сохранить PGN-партию и открыть её на до�ке? + Сохранить %1$s и открыть первую партию на до�ке? В�е партии о�танут�� в локальной копии. + Открыть + Буфер обмена + Открываю файл… + Файл не открыл�� + В �том файле нет шахматных партий. + Файл не прочитал��: его уже нет или приложение, из которого он открыт, не дало к нему до�тупа. Попробуйте открыть его ещё раз. + База ChessBase (.cbh) �о�тоит из не�кольких файлов, а пришёл один. Добавьте папку, где она лежит: «Добавить базу» → «Папка». + Приложению не удало�ь �охранить копию файла. Проверьте, е�ть ли на телефоне �вободное ме�то. + копи� + База удалена из ChessPenguin + + �нализ партии + Отчёт по партии + Движок оценит каждую позицию о�новной линии. Сама парти� не изменит��. + %d � + %d мин + �нализировать + Дополнить + Уже оценено позиций: %1$d из %2$d. + �нализ партии · %1$d из %2$d + О�тановить анализ + Точно�ть + Точно�ть: белые %1$s, чёрные %2$s + Отчёт + лучше было %1$s + �еточно�ть + Ошибка + Зевок + �еточно�ти + Ошибки + Зевки + Замечательный ход + Бле�т�щий ход + Замечательный + Бле�т�щий + Без оценки: %d + �нализ прервал�� + Продолжить + Средн�� потер� �антипешек + Дебют + Миттельшпиль + Эндшпиль + %1$s · %2$s узлов на ход + Оценки из PGN ([%eval]) + !! и ! �тавит только движок: в PGN е�ть лишь оценки + В �том анализе !! и ! ещё не и�кали + �нализ �делан � прежними на�тройками движка + Обновить + Проанализировать движком + Скрыть анализ + График оценки + Пауза: идёт анализ партии + Лучша� лини� · ход %1$d из %2$d + Перейти к �ледующему такому ходу + Показать лучшую линию на до�ке + %1$s, оценка %2$s + �ачальна� позици� + + Позиций: %1$d, примерно %2$s + Позиций: %1$d, примерно %2$s + Позиций: %1$d, примерно %2$s + Позиций: %1$d, примерно %2$s + + + Партии � Lichess и Chess.com + Партии любого игрока по нику: �вои, ученика, �оперника + Партии игрока �танут базой на телефоне — и�кать, �мотреть, анализировать. �ужен только ник, входить на �айт не нужно. + �ик игрока + как на �айте + �а Chess.com другой ник + �ик на Chess.com + Тот же ник + Латиница, цифры, _ и -, от 2 до 30 �имволов + �айти + Ищу на �айтах… + %1$s · первый раз около %2$d мин + ме��цев � парти�ми: %1$d + %1$s: игрока � таким ником нет — проверьте напи�ание + Объединить оба �айта в одну базу + Иначе у каждого �айта будет �во� база + В новую базу «%1$s» + В базу «%1$s» (там уже %2$s; добав�т�� только новые) + Скачать + Lichess: %1$s из примерно %2$s · о�тало�ь около %3$d мин + %1$s: %2$s + Chess.com: ме��ц %1$d из %2$d · %3$s + О�тановить + +%1$s, в�его %2$s + �овых партий нет, в базе %1$s + О�тановлено, в базе %1$s + Партий в обычные шахматы там нет. + Открыть базу + Попробовать ещё раз + %1$s не отвечает. Проверьте подключение к интернету и попробуйте ещё раз. + %1$s про�ит �делать паузу: �лишком много запро�ов подр�д. Подождите минуту и попробуйте �нова — �качанное �охранит��. + %1$s ответил непон�тно — возможно, �айт что-то помен�л. Попробуйте позже или обновите ChessPenguin. + �е удало�ь запи�ать базу: на телефоне не хватает ме�та. + Эта база уже �качивает��. + %1$s не отвечает + %1$s про�ит паузу + Скачивание прервало�ь + Скачать новые партии + О�тановить �качивание + Скачивает�� · %1$s + обновлено %1$s + не докачана + Скачанна� база удалена + �ик на Lichess + %1$s · первый раз меньше минуты + Можно уйти � �того �крана: база уже в �пи�ке, �качивание продолжит��. + Готово: %1$s + обновлено только что + «%1$s»: +%2$s, в�его %3$s + «%1$s»: новых партий нет + «%1$s»: %2$s + Открыть + + до %1$s партии + до %1$s партий + до %1$s партий + до %1$s партии + + Вышла вер�и� %1$s + У ва� %1$s + Обновить + У�тановить + Базы, на�тройки и движок о�танут��. + Базы и на�тройки о�танут��. + �а врем� у�тановки ChessPenguin закроет�� — потом откройте его �нова. + Идёт �качивание партий: у�тановка его о�тановит, потом его можно продолжить. + �ужно одно разрешение + Android �тавит приложени� не из магазина только � вашего разрешени�. Откроют�� на�тройки: включите переключатель дл� ChessPenguin и верните�ь назад. + Открыть на�тройки + Разрешение не включено — без него Android не у�тановит новую вер�ию. + Разрешение е�ть, �качиваю + Скачать на �айте + Открыть �айт + Ли�т можно закрыть: загрузка продолжит��. + �ет �ети. Загрузка продолжит�� �ама, когда �еть по�вит��. + Ждёт �еть + Провер�ю файл… + Сохран�ю движок… + У�танавливаю… + �ова� вер�и� �качана и проверена. + Скачана и проверена + �ова� вер�и� �качана + У�тановка отменена. �ова� вер�и� �качана — у�тановите её, когда будет удобно. + Обновление ChessPenguin + ChessPenguin обновлён: %1$s → %2$s + Загрузка не удала�ь. Попробуйте ещё раз. + Файл повредил�� при �качивании, по�тому не у�тановлен. Попробуйте ещё раз. + С �тим выпу�ком что-то не так: файл дл� Android нельз� проверить. Скачайте новую вер�ию на �айте. + Android не у�тановил новую вер�ию: не хватает ме�та. О�вободите %1$d МБ и попробуйте ещё раз. + Android не у�тановил новую вер�ию: �тот ChessPenguin подпи�ан другим ключом. По�тавить новую вер�ию можно только по�ле удалени� �той, а при удалении пропадут �пи�ок баз и �качанные базы. + У�тановку о�тановил Android или защита телефона. Скачайте новую вер�ию на �айте. + Android не у�тановил новую вер�ию. Попробуйте ещё раз или �качайте её на �айте. + �ет интернета + �е хватает ме�та + Файл повредил�� + Android не у�тановил + Загрузка не удала�ь + Подробнее + Подробно�ти + Копировать + Обновлени� + Провер�ть обновлени� при запу�ке + Раз в день ChessPenguin �прашивает у �воего �айта, кака� вер�и� по�ледн��; �айт �читает работающие у�тановки. Передают�� только �лучайный номер �той у�тановки, вер�и� и �и�тема. Проверка идёт и при выключенных предложени�х. + Предлагать новые вер�ии + Карточка на �кране «Базы», когда выходит нова� вер�и�. + Работает, когда включена проверка обновлений. + Больше не предлагаем. Включить — в �а�тройках, «О программе» + �е предлагать обновлени� + Проверить �ейча� + Провер�ю… + У ва� по�ледн�� вер�и� + Проверено %1$s + �ет интернета — проверить обновлени� нельз� + �е удало�ь проверить обновлени�: �айт не ответил. Попробуйте позже. + Вышла вер�и� %1$s + Скачивает�� вер�и� %1$s… + Вер�и� %1$s �качана + Обновление до %1$s, �качано %2$d из %3$d мегабайт + Файл нельз� проверить + Вернуть + Ходы удалены + Сделать о�новным + Удалить ход и продолжение + Дей�тви� � ходом + �ова� парти� + Мои базы + + �ова� база + Зде�ь будут партии, которые вы введёте или �ыграете � компьютером + + Добавить + Зде�ь будут файлы PGN и ChessBase, папки и партии из интернета, которые вы добавите + Файлы + Мои партии + �ова� база + �азвание + Хранит�� на телефоне, в ChessPenguin. Выгрузить файл можно в меню базы. + Создать + на телефоне + Выгрузить файл… + Удалить базу + Файл �охранён + �е удало�ь �охранить файл + База удалена + Удалить «%1$s»? + + %1$s парти� будет удалена � телефона. Е�ли она нужна, �начала выгрузите файл. + %1$s партии будут удалены � телефона. Е�ли они нужны, �начала выгрузите файл. + %1$s партий будут удалены � телефона. Е�ли они нужны, �начала выгрузите файл. + %1$s партии будут удалены � телефона. Е�ли они нужны, �начала выгрузите файл. + + Сохранено в «%1$s», № %2$s + �е удало�ь �охранить партию + Сохранить в «%1$s» + Сохранить в мою базу… + Сохранить в базу + Сохранить в базу… + �ова� база… + Создать и �охранить + Сохранить изменени� в «%1$s»? + Сохранить партию? + �е �охран�ть + Данные партии + ГГГГ.ММ.ДД + �е дата: 2026.10.26, 2026 или 26.10.2026 + Отменить изменени�? + Отменить + Продолжить правку + Изменить + Далее + Учим дебют + до %1$s + Учить дебют до �того хода + Ход %1$s из %2$s + ♔ ход белых + ♚ ход чёрных + Ошибок: %1$s + Прохождение %1$s + × В партии — другой ход + Показать ход + Эту линию ещё не проходили + Прошлое: %1$s · без ошибок подр�д: %2$s + Прошлое: %1$s · лучшее: %2$s + Пройдено без ошибок + Пройдено � под�казкой · ошибок: %1$s + Пройдено · ошибок: %1$s + Прохождение %1$s · лучшее: %2$s + без ошибок подр�д: %1$s + По�ледние: %1$s + Сделайте ход �о �трелки + ↻ Ещё раз + ⬅ К партии + Сначала + + прохождений: %1$d + прохождений: %1$d + прохождений: %1$d + прохождений: %1$d + + Maia дл� ChessPenguin + Вы выиграли + Вы проиграли + Вы �дали�ь + �ичь� + мат + пат + позици� повторила�ь трижды + 50 ходов без вз�тий и ходов пешек + ни у кого нет материала дл� мата + Maia �дала�ь + Сдать��? + ⚑ Сдать�� + ↶ Ход назад + Игра � компьютером + Цвет + Белые + Чёрные + Случайно + Соб�твенный рейтинг Maia: он не равен Эло человека. + Maia �качивает�� один раз (%1$s МБ, � huggingface.co — файл �амих авторов). + Скачать и играть + Играть + думает… + Парти� � компьютером + �нализировать + ↻ Реванш + Играть от�юда… + Провер�ю… + Maia не запу�тила�ь: %1$s + Прин�ть победу + Играть до конца + Maia �даёт�� + Дальше — игра � Maia %1$s. + Прервать + Ваше им� + Maia �качана + Повторить + Её позици� проиграна. Прин�ть победу или доиграть? + Продолжить + Парти� � Maia %1$s · вы %2$s + белыми + чёрными + Парти� удалена + без ча�ов + Вы + ✓ Сохранено + Сохранить… + вы %1$s · %2$s + По�ле %1$s + Звук + Отменить + Теперь о�новной вариант + Эло + �нализ + Доиграть + Про�мотр: %1$s · к игре › + начальна� позици� + Maia не запу�тила�ь. + Скачать Maia заново + Е�ть отложенна� парти� � %1$s + Продолжить её + �ачать новую + �ова� парти� заменит её; �ыгранное запишет�� в базу игрока неоконченным. + �ичь� + по �оглашению + Maia отказывает�� от ничьей + Maia отказала�ь; �нова можно предложить через два её хода + Maia отвечает на ничью � помощью Stockfish: �качайте его кнопкой «Движок» + %1$s — партии � компьютером + Партии � компьютером + ✓ В «%1$s», № %2$s › + Парти� запи�ана в «%1$s» неоконченной + пишут�� �ами + Запи�ывать партии � компьютером в базу игрока + Партии запи�ывают�� в «%1$s» + Партии будут запи�ывать�� в новую базу «%1$s». + Без имени партии идут в «%1$s». Впишите им� — заведём вашу базу. + Партии �ами не запи�ывают�� (�а�тройки). + ✓ Создана база «%1$s», № %2$s › + �е удало�ь запи�ать в «%1$s»: %2$s + �ова� парти� заменит её. + Открыта по�ледней + Парти� � %1$s + %1$d-й ход + + �манда + Сначала атакует, потом играет на активно�ть фигур. + Клои + Любит закрытые позиции. + Дебора + Хорошо защищает�� и любит �лонов. + Защитник + �адёжный и о�торожный, �огла�ен на ничью. + Динамик + �такует, любит �лонов, врем� от времени жертвует. + Ворчун + �така и �ковывание; любит запертые позиции, избегает ничьих. + Партизан + �такует по�ле тихих, неприметных дебютов. + Гамбити�т + Сбалан�ированный, но охотнее отдаёт пешки. + Педрита + Пешки, защита и �ковывание. + Пре�тон + Материали�т, атакует умеренно. + Про�так + Самый «компьютерный»: про�тые, правильные шахматы. + Задира + О�трый и агре��ивный. + Удав + Удав: медленно душит, очень по-человече�ки. + �лехин + Динамичные атаки и глубокие комбинации. + �нанд + Бы�тра�, универ�альна� игра � о�трыми дебютами. + �ндер�ен + Романтик-атакёр XIX века: жертвы. + Бо�бум + �еобычные дебюты и творче�ка� блиц-игра. + Ботвинник + �аучна� �тратегиче�ка� игра на глубокой подготовке. + Фишер + Я�на�, кла��иче�ка� и точна� игра. + Карпов + Позиционное давление, профилактика и техника. + Ка�паров + Инициатива и мощна� атака. + Корчной + Упорный защитник и ма�тер контратаки. + Лар�ен + Оригинальный и ри�кованный, � необычными дебютами. + Ла�кер + Практичный боец-п�ихолог. + Маршалл + Лихой атакёр � гамбитами. + Морфи + Бы�трое развитие и открытые линии. + �имцович + Сковывание, блокада и �верхзащита. + Петро��н + Профилактика и безопа�но�ть прежде в�его. + Рети + Гипер�овременный: контролирует центр издалека. + Рубинштейн + Кла��иче�ка� позиционна� игра, �илён в �ндшпиле. + Спа��кий + Универ�ал, в любой позиции как дома. + Стейниц + О�нователь позиционной игры, упр�мый защитник. + Таль + Риж�кий волшебник: жертвы и атака. + Тарраш + Кла��иче�кие правила: про�тран�тво, развитие, активные фигуры. + Топалов + �гре��ивный и динамичный, жертвует каче�тво. + играет как человек + �ильный, �о �тилем + Как человек + Maia не выбирает �тиль: она играет, как люди её рейтинга. + Соб�твенный рейтинг Rodent (UCI_Elo): он не равен Эло человека. + Rodent �даёт�� + Rodent �дал�� + Rodent отказывает�� от ничьей + Rodent отказал��; �нова можно предложить через два его хода + Его позици� проиграна. Прин�ть победу или доиграть? + Играть + Играть � компьютером + Сила: %1$s + С кем играть + Характер — �то �тиль и дебюты, �илу задаёт ползунок. + Великие шахмати�ты + Характеры + Изменить + %1$s, великий шахмати�т + %1$s, характер + Характер: %1$s + Rodent IV и его дебютные книги на телефоне + Дебютные книги Rodent IV: %1$s МБ, �качивают�� один раз � github.com + С позиции дебютна� книга не нужна — Rodent IV играет �разу + Без книги + Без книги: играть без дебютной книги + Дебютные книги Rodent IV + Rodent IV — дебютные книги + �качаны · %1$s МБ + не �качаны · %1$s МБ + Дебютные книги удалены + Rodent отвечает на ничью � помощью Stockfish: �качайте его кнопкой «Движок» + Rodent не запу�тил��. + Перезапу�тить + Дальше — игра � Rodent IV %1$s · %2$s. + Rodent о�тановил�� во врем� игры. + %1$s, от %2$s до %3$s + Сила + Удалить дебютные книги + + + Игроки + Им� игрока + �е удало�ь прочитать игроков + Читаю игроков… + В �той базе нет именованных игроков + Игрок не найден + К парти�м + Сбро�ить пои�к + Подготовить�� + Выберите цвет + Подготовить�� к %1$s + Против белых + Против чёрных + Подготовить�� к �опернику… + Подготовка к �опернику + Сначала закройте линию движка + + Пои�к по�ле учебного -- недо�тупен + Белыми + Чёрными + �е удало�ь �делать ход + Сыграть %1$s, %2$s, %3$s процентов + До�ка, начальна� позици�. Внизу %1$s. + До�ка, позици� по�ле %1$s. Внизу %2$s. + ход белых + ход чёрных + Соперник играет + Его оппоненты играют + по�ле %1$s + начало + %1$s, %2$s, %3$s, %4$s + �е удало�ь по�читать продолжени� + �едо�таточно пам�ти дл� пои�ка по �той базе + Считаю продолжени�… + В парти�х %1$s �той позиции нет + Можно продолжить на до�ке или вернуть�� назад + В�е партии зде�ь закончили�ь + Зде�ь закончили�ь: %1$s + �ет обычного продолжени�: %1$s + К партии + К игрокам + Выберите ход + + %1$s победа + %1$s победы + %1$s побед + %1$s победы + + + %1$s ничь� + %1$s ничьи + %1$s ничьих + %1$s ничьи + + + %1$s поражение + %1$s поражени� + %1$s поражений + %1$s поражени� + + �еизве�тных и�ходов: %1$d; они не вход�т в знаменатель процентов. + %1$s. %2$d из %3$s, %4$s процентов. Результаты %5$s: %6$s, %7$s, %8$s; %9$s, %10$s и %11$s процентов. %12$s Сыграть. + Сыграть + ещё %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml new file mode 100644 index 0000000..f3dcc0b --- /dev/null +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -0,0 +1,723 @@ + + + Klassik partiyalar + Alyoxin + + Bazalaringiz shu yerda koʻrinadi + PGN fayl, ChessBase bazasi yoki .zip/.7z arxivini — telefoningizdan yoki bulutdan — qoʻshing yoki Lichess va Chess.comdan partiyalarni yuklab oling. + Baza qoʻshish + Namuna partiyalarni ochish + hali ochilmagan · %1$s + + %1$s ta partiya + %1$s ta partiya + + %1$s · %2$s + Menyu + Nomini oʻzgartirish + Roʻyxatdan olib tashlash + Roʻyxatdagi nom. Fayl oʻzgarmaydi. + Bekor qilish + Saqlash + Baza roʻyxatdan olib tashlandi + Qaytarish + Orqaga + + Oʻqilmoqda… + Bazani ochib boʻlmadi + Qidirish + Oʻyinchi, turnir, yil + Hech narsa topilmadi + Tozalash + + %1$d / %2$d + Oldingi partiya + Keyingi partiya + Taxtani aylantirish + Boshiga + Bir yurish orqaga + Bir yurish oldinga + Oldingi yurish. Boshiga oʻtish uchun bosib turing + Keyingi yurish. Liniya oxiriga oʻtish uchun bosib turing + Liniya oxiriga + Keyin: + Taxta, %1$sdan keyingi pozitsiya + Taxta, boshlangʻich pozitsiya + Oqlar yutdi + Qoralar yutdi + Durang + Partiyani oʻqib boʻlmadi + + Dvigatel + Oʻylanmoqda… + chuqurlik %1$d + pauza + Chuqurroq + Koʻproq liniya + Kamroq liniya + Dvigatel javob bermayapti + Dvigatel bu telefonda ishga tushmaydi + Qayta ishga tushirish + Dvigatel liniyasi · yurish %1$d / %2$d + Yopish + Stockfish dvigateli + Pozitsiyani baholaydi va eng yaxshi yurishlarni koʻrsatadi. Internetsiz ishlaydi — faqat bir marta yuklab olish kerak. + Hajmi: %1$d MB + Hozir Wi-Fi yoʻq: yuklab olish mobil internetdan foydalanadi. + Hozir emas + Yuklab olish + Yuklab olindi: %1$d / %2$d MB + Bekor qilish + Yuklab olish bekor qilindi + Dvigatel tayyor + Internet yoʻq. Tarmoqqa ulanib, qayta urinib koʻring. + ChessPenguin: Stockfish dvigateli + Yuklab olish toʻxtadi. Qayta urinib koʻring. + Joy yetmaydi: %1$d MB kerak. + Dvigatel fayli yuklab olishda shikastlandi. Qayta yuklab oling. + Qayta urinish + Qayta yuklab olish + OK + Dvigatel tayyorlanmoqda… + + Sozlamalar + Koʻrinish + Dvigatel + Mavzu + Tizimdagidek + Yorugʻ + Qorongʻi + Yurishlar yozuvi + Lotin harflari (K Q R B N) + Figura belgilari + Til harflari + Faqat koʻrinish. PGNda doim K Q R B N. + Figura animatsiyasi + Eng yaxshi yurish strelkasi + Tebranish + Stockfish 19 · ichki + Stockfish 19 · yuklab olingan + Yuklab olinmagan · Yuklab olish (%1$d MB) + Yuklab olinmoqda… %1$d / %2$d MB + Dvigatelni oʻchirish (%1$d MB boʻshaydi) + Dvigatel oʻchirilsinmi? Uni qayta yuklab olish mumkin. + Oʻchirish + Liniyalar + Har pozitsiyaga vaqt + %1$d s + 1 daq. + Cheklovsiz + Oqimlar + Xotira + %1$d MB + Dvigatel batareyani sarflaydi. Partiyadan chiqqaningizda yoki ilova fonga oʻtganda u oʻzi oʻchadi. + Dastur haqida + Stockfish ichki + Stockfish ilovada yuklab olinadi + Shaxmat bazalari, partiyalar tahlili va kompyuter bilan oʻyin. Fayllaringiz faqat oʻqiladi, hech qachon oʻzgartirilmaydi. + Litsenziyalar va mualliflar + Sayt va manba kodi + + Partiya maʼlumotlari + PGN nusxalash + FEN nusxalash + Partiyani ulashish + Eslatmalar + yoqiq + oʻchiq + yuklab olinmagan + Topildi: %1$s / %2$s + Partiya + %1$d, oqlar, %2$s + %1$d, qoralar, %2$s + joriy yurish + Til + Mat + Pat + PGN nusxalandi + FEN nusxalandi + Turnir + Joy + Sana + Tur + Oqlar + Qoralar + Natija + Oqlar Elo + Qoralar Elo + Izohlovchi + Yarim yurishlar + Faylga kirish yoʻq: u koʻchirilgan, oʻchirilgan yoki ruxsat qaytarib olingan. Uni roʻyxatdan olib tashlab, qayta qoʻshing. + Fayl shikastlangan yoki shaxmat bazasi emas. + Arxivda PGN yoki ChessBase bazasi yoʻq. + Bu turdagi bazani oʻqib boʻlmaydi: %1$s + Fayl + PGN, .cbv, .zip yoki .7z + Jild + Jilddagi barcha bazalar, ChessBase (.cbh) ham + Bazalar qidirilmoqda… + Bu jildda bazalar yoʻq + Jildda va uning ichidagi ikki daraja jildlarda PGN fayllar, ChessBase bazalari (.cbh, .cbv) va .zip yoki .7z arxivlarni qidiradi. + roʻyxatda bor + .cbg fayli yoʻq — partiyalarni ochib boʻlmaydi + + “%2$s�da %1$d ta baza + “%2$s�da %1$d ta baza + + + %1$d tasini qoʻshish + %1$d tasini qoʻshish + + + %1$d ta baza qoʻshildi + %1$d ta baza qoʻshildi + + Android ilovalarga xotiraning ildizini yoki Downloads jildining oʻzini tanlashga ruxsat bermaydi — faqat ularning ichidagi jildni. + Boshqasini tanlash + Tayyor + Qoʻshish + Hammasini belgilash + Belgilarni olib tashlash + %1$s fayli endi baza yonida emas: u koʻchirilgan yoki oʻchirilgan. + Taxta va figuralar + Jigarrang + Koʻk + Yashil + Turnir + Qum + Marjon + Kulrang + Binafsha + Muz + Toʻq koʻk + Yalpiz + Zumrad + Toʻq sariq + Atirgul + Shom + Tun + Yogʻoch + Zarang + Charm + Marmar + Koʻk marmar + Mato + Metall + Zaytun + Tosh + Yashil plastik + Binafsha diagonal + Pushti piramida + Eskiz + Taxta + Figuralar + № %1$s + Almashish buferidan PGN qoʻyish + Boshqa ilovada nusxalangan partiyalar + Almashish buferida PGN partiyalar yoʻq + Qoʻyildi: %1$s + + Almashish buferida partiya + Almashish buferida partiyalar + + Bu PGN partiyani saqlab, doskada ochish? + %1$s saqlab, birinchi partiyani doskada ochish? Barcha partiyalar mahalliy nusxada saqlanadi. + Ochish + Almashish buferi + Fayl ochilmoqda… + Faylni ochib boʻlmadi + Bu faylda shaxmat partiyalari yoʻq. + Faylni oʻqib boʻlmadi: u yoʻqolgan boʻlishi yoki u kelgan ilova unga kirishga ruxsat bermagan boʻlishi mumkin. Uni qayta ochib koʻring. + ChessBase bazasi (.cbh) bir nechta fayldan iborat, lekin faqat bittasi keldi. U turgan jildni qoʻshing: \"Baza qoʻshish\" → \"Jild\". + Ilova fayl nusxasini saqlay olmadi. Telefonda boʻsh joy borligini tekshiring. + nusxa + Baza ChessPenguindan oʻchirildi + Partiya tahlili + Partiya hisoboti + Dvigatel asosiy liniyaning har bir pozitsiyasini baholaydi. Partiyaning oʻzi oʻzgarmaydi. + %d s + %d daq. + Tahlil qilish + Toʻldirish + %2$d ta pozitsiyadan %1$d tasi allaqachon baholangan. + Partiya tahlili · %1$d / %2$d + Tahlilni toʻxtatish + Aniqlik + Aniqlik: oqlar %1$s, qoralar %2$s + Hisobot + %1$s yaxshiroq edi + Noaniqlik + Xato + Qoʻpol xato + Noaniqliklar + Xatolar + Qoʻpol xatolar + Kuchli yurish + Ajoyib yurish + Kuchli yurishlar + Ajoyib yurishlar + Baholanmagan: %d + Tahlil toʻxtadi + Davom etish + Oʻrtacha santipeshka yoʻqotish + Debyut + Mittelshpil + Endshpil + %1$s · har yurishga %2$s tugun + PGNdagi baholar ([%eval]) + !! va ! faqat dvigatel bilan: PGNda faqat baholar bor + Bu tahlilda !! va ! hali qidirilmagan + Tahlil dvigatelning boshqa sozlamalari bilan qilingan + Yangilash + Dvigatel bilan tahlil qilish + Tahlilni yashirish + Baho grafigi + Pauza: partiya tahlil qilinmoqda + Yaxshiroq liniya · yurish %1$d / %2$d + Keyingi shunday yurishga oʻtish + Yaxshiroq liniyani taxtada koʻrsatish + %1$s, baho %2$s + Boshlangʻich pozitsiya + + %1$d ta pozitsiya, taxminan %2$s + %1$d ta pozitsiya, taxminan %2$s + + Lichess va Chess.com partiyalari + Istalgan oʻyinchining partiyalari taxallus boʻyicha: oʻzingizniki, shogirdingizniki, raqibingizniki + Oʻyinchining partiyalari telefoningizda qidirish, koʻrish va tahlil uchun bazaga aylanadi. Faqat taxallus kerak, hisobga kirish shart emas. + Oʻyinchi taxallusi + saytdagidek + Chess.comda boshqa taxallus + Chess.comdagi taxallus + Oʻsha taxallus + Lotin harflari, raqamlar, _ va -, 2 dan 30 gacha belgi + Topish + Saytlarda qidirilmoqda… + %1$s · birinchi marta taxminan %2$d daq. + partiyali oylar: %1$d + %1$s: bunday taxallusli oʻyinchi yoʻq — yozilishini tekshiring + Ikkala saytni bitta bazaga birlashtirish + Aks holda har bir sayt uchun alohida baza boʻladi + Yangi “%1$s� bazasiga + “%1$s� bazasiga (unda allaqachon %2$s; faqat yangi partiyalar qoʻshiladi) + Yuklab olish + Lichess: %1$s / taxminan %2$s · taxminan %3$d daq. qoldi + %1$s: %2$s + Chess.com: oy %1$d / %2$d · %3$s + Toʻxtatish + +%1$s, jami %2$s + Yangi partiyalar yoʻq, bazada %1$s + Toʻxtatildi, bazada %1$s + U yerda klassik shaxmat partiyalari yoʻq. + Bazani ochish + Qayta urinish + %1$s javob bermayapti. Internet aloqasini tekshirib, qayta urinib koʻring. + %1$s tanaffus soʻrayapti: ketma-ket juda koʻp soʻrov. Bir daqiqa kutib, qayta urinib koʻring; yuklab olingani saqlanadi. + %1$s ChessPenguin tushunmaydigan tarzda javob berdi: sayt oʻzgargan boʻlishi mumkin. Keyinroq urinib koʻring yoki ChessPenguinni yangilang. + Bazani yozib boʻlmadi: telefonda joy qolmadi. + Bu baza allaqachon yuklab olinmoqda. + %1$s javob bermayapti + %1$s tanaffus soʻrayapti + Yuklab olish toʻxtadi + Yangi partiyalarni yuklab olish + Yuklab olishni toʻxtatish + Yuklab olinmoqda · %1$s + yangilangan: %1$s + tugallanmagan + Yuklab olingan baza oʻchirildi + Lichessdagi taxallus + %1$s · birinchi marta bir daqiqadan kam + Bu ekrandan chiqishingiz mumkin: baza roʻyxatda, yuklab olish davom etadi. + Tayyor: %1$s + hozirgina yangilandi + “%1$s�: +%2$s, jami %3$s + “%1$s�: yangi partiyalar yoʻq + “%1$s�: %2$s + Ochish + + %1$s tagacha partiya + %1$s tagacha partiya + + %1$s versiyasi chiqdi + Sizda %1$s + Yangilash + Oʻrnatish + Bazalar, sozlamalar va dvigatel saqlanadi. + Bazalar va sozlamalar saqlanadi. + Oʻrnatish vaqtida ChessPenguin yopiladi — soʻng uni qayta oching. + Partiyalar yuklab olinmoqda: oʻrnatish uni toʻxtatadi; keyinroq davom ettirish mumkin. + Bitta ruxsat kerak + Android doʻkondan tashqaridagi ilovalarni faqat sizning ruxsatingiz bilan oʻrnatadi. Sozlamalar ochiladi: ChessPenguin uchun kalitni yoqing va qayting. + Sozlamalarni ochish + Ruxsat oʻchiq — usiz Android yangi versiyani oʻrnatmaydi. + Ruxsat berildi, yuklab olinmoqda + Saytdan yuklab olish + Saytni ochish + Buni yopishingiz mumkin: yuklab olish davom etadi. + Tarmoq yoʻq. Tarmoq tiklanganda yuklab olish oʻzi davom etadi. + Tarmoq kutilmoqda + Fayl tekshirilmoqda… + Dvigatel saqlanmoqda… + Oʻrnatilmoqda… + Yangi versiya yuklab olindi va tekshirildi. + Yuklab olindi va tekshirildi + Yangi versiya yuklab olindi + Oʻrnatish bekor qilindi. Yangi versiya yuklab olingan — istalgan vaqtda oʻrnating. + ChessPenguin yangilanishi + ChessPenguin yangilandi: %1$s → %2$s + Yuklab olib boʻlmadi. Qayta urinib koʻring. + Fayl yuklab olishda shikastlandi, shuning uchun oʻrnatilmadi. Qayta urinib koʻring. + Bu nashrda muammo bor: Android faylini tekshirib boʻlmaydi. Yangi versiyani saytdan yuklab oling. + Android yangi versiyani oʻrnatmadi: joy yetmaydi. %1$d MB boʻshatib, qayta urinib koʻring. + Android yangi versiyani oʻrnatmadi: bu ChessPenguin boshqa kalit bilan imzolangan. Yangi versiyani faqat bunisini oʻchirgandan keyin oʻrnatish mumkin, oʻchirilganda esa bazalar roʻyxati va yuklab olingan bazalar yoʻqoladi. + Android yoki telefon himoyasi oʻrnatishni toʻxtatdi. Yangi versiyani saytdan yuklab oling. + Android yangi versiyani oʻrnatmadi. Qayta urinib koʻring yoki saytdan yuklab oling. + Internet yoʻq + Joy yetmaydi + Fayl shikastlandi + Android oʻrnatmadi + Yuklab olib boʻlmadi + Yana + Batafsil + Nusxalash + Yangilanishlar + Ishga tushganda yangilanishlarni tekshirish + ChessPenguin kuniga bir marta oʻz saytidan eng soʻnggi versiyani soʻraydi; sayt ishlayotgan oʻrnatmalarni sanaydi. Faqat shu oʻrnatmaning tasodifiy raqami, versiya va tizim yuboriladi. Takliflar oʻchiq boʻlsa ham tekshiruv davom etadi. + Yangi versiyalarni taklif qilish + Yangi versiya chiqqanda «Bazalar» ekranida karta. + Yangilanishlarni tekshirish yoqilganda ishlaydi. + Endi taklif qilmaymiz. Yoqish — Sozlamalar, «Dastur haqida» + Yangilanishlarni taklif qilmaslik + Hozir tekshirish + Tekshirilmoqda… + Sizda eng soʻnggi versiya + Tekshirildi: %1$s + Internet yoʻq — yangilanishlarni tekshirib boʻlmaydi + Yangilanishlarni tekshirib boʻlmadi: sayt javob bermadi. Keyinroq urinib koʻring. + %1$s versiyasi chiqdi + %1$s versiyasi yuklab olinmoqda… + %1$s versiyasi yuklab olindi + %1$sga yangilash, %3$d megabaytdan %2$d tasi yuklab olindi + Faylni tekshirib boʻlmaydi + Qaytarish + Yurishlar o‘chirildi + Asosiy qilish + Yurish va davomini o‘chirish + Yurish amallari + Yangi o‘yin + Mening bazalarim + + Yangi baza + Bu yerda siz kiritgan yoki kompyuter bilan o‘ynagan o‘yinlar bo‘ladi + + Qo‘shish + Bu yerda siz qo‘shgan PGN va ChessBase fayllari, papkalar va internetdagi o‘yinlar bo‘ladi + Fayllar + Mening o‘yinlarim + Yangi baza + Nomi + Telefonda, ChessPenguin ichida saqlanadi. Faylni baza menyusidan eksport qilish mumkin. + Yaratish + telefonda + Faylni eksport qilish… + Bazani o‘chirish + Fayl saqlandi + Faylni saqlab bo‘lmadi + Baza o‘chirildi + “%1$s� o‘chirilsinmi? + + Telefondan %1$s ta o‘yin o‘chiriladi. Agar kerak bo‘lsa, avval faylni eksport qiling. + Telefondan %1$s ta o‘yin o‘chiriladi. Agar kerak bo‘lsa, avval faylni eksport qiling. + + “%1$s� ga saqlandi, № %2$s + O‘yinni saqlab bo‘lmadi + “%1$s� ga saqlash + Mening bazamga saqlash… + Bazaga saqlash + Bazaga saqlash… + Yangi baza… + Yaratish va saqlash + O‘zgarishlar “%1$s� ga saqlansinmi? + O‘yin saqlansinmi? + Saqlamaslik + O‘yin ma’lumotlari + YYYY.OO.KK + Sana emas: 2026.10.26, 2026 yoki 26.10.2026 + O‘zgarishlar bekor qilinsinmi? + Bekor qilish + Tahrirlashni davom ettirish + Tahrirlash + Keyingi + Debyutni o‘rganish + %1$s gacha + Debyutni shu yurishgacha o‘rganish + Yurish %1$s / %2$s + ♔ Oqlar yuradi + ♚ Qoralar yuradi + Xatolar: %1$s + Urinish %1$s + × Partiyada bu yerda boshqa yurish + Yurishni ko‘rsatish + Bu liniya hali o‘tilmagan + Oxirgi marta: %1$s · ketma-ket xatosiz: %2$s + Oxirgi marta: %1$s · eng yaxshi: %2$s + Xatosiz o‘tildi + Yordam bilan o‘tildi · xatolar: %1$s + O‘tildi · xatolar: %1$s + Urinish %1$s · eng yaxshi: %2$s + ketma-ket xatosiz: %1$s + So‘nggilari: %1$s + Strelkadagi yurishni qiling + ↻ Yana + ⬅ Partiyaga qaytish + Boshidan + + %1$d marta + %1$d marta + + ChessPenguin uchun Maia + Siz yutdingiz + Siz yutqazdingiz + Siz taslim bo‘ldingiz + Durang + mat + pat + pozitsiya uch marta takrorlandi + 50 yurish davomida olish ham, piyoda yurishi ham yo‘q + hech bir tomon mat qila olmaydi + Maia taslim bo‘ldi + Taslim bo‘lasizmi? + ⚑ Taslim bo‘lish + ↶ Yurishni qaytarish + Kompyuter bilan o‘ynash + Rangingiz + Oqlar + Qoralar + Tasodifiy + Maia ning o‘z reytingi: u odamning Elo reytingiga teng emas. + Maia bir marta yuklab olinadi (%1$s MB, huggingface.co dan — mualliflarning o‘z fayli). + Yuklab olish va o‘ynash + O‘ynash + o‘ylamoqda… + Kompyuter bilan partiya + Tahlil qilish + ↻ Revansh + Shu yerdan o‘ynash… + Tekshirilmoqda… + Maia ishga tushmadi: %1$s + G‘alabani qabul qilish + Oxirigacha o‘ynash + Maia taslim bo‘lmoqda + Bundan keyin — Maia %1$s bilan o‘yin. + To‘xtatish + Ismingiz + Maia yuklab olindi + Qayta urinish + Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki davom etasizmi? + Davom ettirish + Maia %1$s bilan o‘yin · siz %2$s + oqlar bilan + qoralar bilan + O‘yin o‘chirildi + soatsiz + Siz + ✓ Saqlandi + Saqlash… + siz %1$s · %2$s + %1$s dan keyin + Ovoz + Bekor qilish + Endi asosiy variant + Elo + Tahlil + Davom etish + Ko‘rish %1$s · o‘yinga qaytish › + boshlang‘ich pozitsiya + Maia ishga tushmadi. + Maia’ni qayta yuklab olish + %1$s bilan to‘xtatilgan o‘yin bor + Davom ettirish + Yangisini boshlash + Yangi o‘yin uning o‘rnini oladi; o‘ynalgani tugallanmagan holda o‘yinchi bazasiga yoziladi. + Durang + kelishuv bo‘yicha + Maia durangdan bosh tortadi + Maia rad etdi; uning ikki yurishidan keyin yana taklif qiling + Maia durangga Stockfish bilan javob beradi: uni «Dvigatel» tugmasi bilan yuklab oling + %1$s — kompyuter bilan o‘yinlar + Kompyuter bilan o‘yinlar + ✓ «%1$s» da, № %2$s › + O‘yin tugallanmagan holda «%1$s» ga yozildi + o‘zi yoziladi + Kompyuter bilan o‘yinlarni o‘yinchi bazasiga yozish + O‘yinlar «%1$s» ga yoziladi + O‘yinlar yangi «%1$s» bazasiga yoziladi. + Ismsiz o‘yinlar «%1$s» ga tushadi. O‘z bazangiz bo‘lishi uchun ismingizni yozing. + O‘yinlar o‘zi yozilmaydi (Sozlamalar). + ✓ Yangi baza «%1$s», № %2$s › + «%1$s» ga yozib bo‘lmadi: %2$s + Yangi o‘yin uning o‘rnini oladi. + Oxirgi ochilgan + %1$s bilan o‘yin + %1$d-yurish + + Amanda + Avval hujum qiladi, keyin donalar faolligi uchun o‘ynaydi. + Kloe + Yopiq pozitsiyalarni yaxshi ko‘radi. + Debora + Yaxshi himoyalanadi va filllarini yaxshi ko‘radi. + Himoyachi + Mustahkam va ehtiyotkor; duranga rozi. + Dinamik + Hujum qiladi, fillarni yaxshi ko‘radi, ba’zan qurbon qiladi. + G‘udranuvchi + Hujum va siqish; yopiq pozitsiyalarni yoqtiradi, durangdan qochadi. + Partizan + Sokin, sezilmas debyutlardan keyin hujum qiladi. + Gambitchi + Muvozanatli, lekin piyodalarni osonroq beradi. + Pedrita + Piyodalar, himoya va siqish. + Preston + Materialist, o‘rtacha hujumchi. + Oddiy + Eng «kompyuterona»: oddiy, to‘g‘ri shaxmat. + Jo‘shqin + O‘tkir va tajovuzkor. + Bo‘g‘uvchi + Bo‘g‘ma ilon: sekin siqadi, juda insoniy. + Alyoxin + Dinamik hujumlar va chuqur kombinatsiyalar. + Anand + Tez, universal o‘yin, o‘tkir debyutlar bilan. + Anderssen + XIX asrning romantik hujumchisi: qurbonlar. + Bosboom + Noodatiy debyutlar va ijodiy blits. + Botvinnik + Chuqur tayyorgarlikka asoslangan ilmiy, strategik o‘yin. + Fischer + Aniq, klassik va puxta. + Karpov + Pozitsion bosim, profilaktika va texnika. + Kasparov + Tashabbus va kuchli hujum. + Kortchnoi + Qat’iyatli himoyachi va qarshi hujumchi. + Larsen + O‘ziga xos va tavakkalchi, noodatiy debyutlar bilan. + Lasker + Amaliy, psixolog kurashchi. + Marshall + Gambitlar bilan dadil hujumchi. + Morphy + Tez rivojlanish va ochiq chiziqlar. + Nimzowitsch + Siqish, blokada va ortiqcha himoya. + Petrosian + Profilaktika va xavfsizlik birinchi. + Reti + Gipermodern: markazni uzoqdan nazorat qiladi. + Rubinstein + Klassik pozitsion o‘yin, endshpilda kuchli. + Spassky + Universal o‘yinchi, har qanday pozitsiyada o‘zini uydagidek his qiladi. + Steinitz + Pozitsion o‘yin asoschisi, qaysar himoyachi. + Tal + Rigalik sehrgar: qurbonlar va hujum. + Tarrasch + Klassik qoidalar: makon, rivojlanish, faol donalar. + Topalov + Tajovuzkor va dinamik, sifatni qurbon qiladi. + odamdek o‘ynaydi + kuchli, uslubli + Odamdek + Maia uslub tanlamaydi: u o‘z reytingidagi odamlardek o‘ynaydi. + Rodent ning o‘z reytingi (UCI_Elo): u odamning Elo reytingiga teng emas. + Rodent taslim bo‘lmoqda + Rodent taslim bo‘ldi + Rodent durangdan bosh tortadi + Rodent rad etdi; uning ikki yurishidan keyin yana taklif qiling + Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki oxirigacha o‘ynaysizmi? + O‘ynash + Kompyuter bilan o‘ynash + Kuch: %1$s + Kim bilan o‘ynash + Xarakter — bu uslub va debyutlar, kuchni esa slayder belgilaydi. + Buyuk shaxmatchilar + Xarakterlar + O‘zgartirish + %1$s, buyuk shaxmatchi + %1$s, xarakter + Xarakter: %1$s + Rodent IV va uning debyut kitoblari telefonda + Rodent IV debyut kitoblari: %1$s MB, github.com dan bir marta + Pozitsiyadan o‘ynashda debyut kitobi kerak emas — Rodent IV darhol o‘ynaydi + Kitobsiz + Kitobsiz: debyut kitobisiz o‘ynash + Rodent IV debyut kitoblari + Rodent IV — debyut kitoblari + yuklab olingan · %1$s MB + yuklab olinmagan · %1$s MB + Debyut kitoblari o‘chirildi + Rodent durangga Stockfish bilan javob beradi: uni «Dvigatel» tugmasi bilan yuklab oling + Rodent ishga tushmadi. + Qayta ishga tushirish + Bundan keyin — Rodent IV %1$s · %2$s bilan o‘yin. + Rodent o‘yin paytida to‘xtadi. + %1$s, %2$s dan %3$s gacha + Kuch + Debyut kitoblarini o‘chirish + + + Oʻyinchilar + Oʻyinchi ismi + Oʻyinchilarni oʻqib boʻlmadi + Oʻyinchilar oʻqilmoqda… + Bu bazada nomi koʻrsatilgan oʻyinchilar yoʻq + Oʻyinchi topilmadi + Partiyalarga qaytish + Qidiruvni tozalash + Tayyorlanish + Rangni tanlang + Raqibga tayyorlanish %1$s + Oqlarga qarshi + Qoralarga qarshi + Raqibga tayyorlanish… + Raqibga tayyorgarlik + Avval dvigatel chizigʻini yoping + + Oʻquv -- dan keyin qidirish mavjud emas + Oqlar + Qoralar + Bu yurishni bajarib boʻlmadi + %1$s yurish, %2$s, %3$s foiz + Doska, boshlangʻich pozitsiya. Pastda %1$s. + Doska, %1$s dan keyingi pozitsiya. Pastda %2$s. + Oqlar yurishi + Qoralar yurishi + Raqib yuradi + Uning raqiblari yuradi + %1$s dan keyin + boshlanishi + %1$s, %2$s, %3$s, %4$s + Davomlarni hisoblab boʻlmadi + Bu bazadan qidirish uchun xotira yetarli emas + Davomlar hisoblanmoqda… + %1$s partiyalarida bu pozitsiya yoʻq + Doskada davom etishingiz yoki orqaga qaytishingiz mumkin + Barcha partiyalar shu yerda tugagan + Shu yerda tugagan: %1$s + Oddiy davom yoʻq: %1$s + Partiyaga qaytish + Oʻyinchilarga qaytish + Yurishni tanlang + %1$s gʻalaba%1$s gʻalaba + %1$s durang%1$s durang + %1$s magʻlubiyat%1$s magʻlubiyat + Nomaʼlum natijalar: %1$d; ular foizlarga kiritilmaydi. + %1$s. %3$s dan %2$d tasi, %4$s foiz. %5$s natijalari: %6$s, %7$s, %8$s; %9$s, %10$s va %11$s foiz. %12$s Yurish. + Yurish + yana %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values/ic_launcher_colors.xml b/androidApp/app/src/main/res/values/ic_launcher_colors.xml new file mode 100644 index 0000000..ce2ad72 --- /dev/null +++ b/androidApp/app/src/main/res/values/ic_launcher_colors.xml @@ -0,0 +1,5 @@ + + + + #EAF2F9 + diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..71a4a84 --- /dev/null +++ b/androidApp/app/src/main/res/values/strings.xml @@ -0,0 +1,737 @@ + + ChessPenguin + Classic games + Alekhine + + Your databases will appear here + Add a PGN file, a ChessBase database or a .zip/.7z archive — from your phone or the cloud — or download games from Lichess and Chess.com. + Add database + Open sample games + not opened yet · %1$s + + %1$s game + %1$s games + + %1$s · %2$s + Menu + Rename + Remove from list + The name in the list. The file is not changed. + Cancel + Save + Database removed from the list + Undo + Back + + Reading… + Could not open the database + Search + Player, event, year + Nothing found + Clear + + %1$d of %2$d + Previous game + Next game + Flip board + To the start + Move back + Move forward + Previous move. Hold for the first position + Next move. Hold for the end of the line + To the end of the line + Next: + Board, position after %1$s + Board, starting position + White won + Black won + Draw + Could not read the game + + Engine + Thinking… + depth %1$d + paused + Deeper + More lines + Fewer lines + The engine is not responding + The engine does not start on this phone + Restart + Engine line · move %1$d of %2$d + Close + Stockfish engine + Evaluates the position and shows the best moves. Works offline — it only has to be downloaded once. + Size: %1$d MB + No Wi-Fi now: the download will use mobile data. + Not now + Download + Downloaded %1$d of %2$d MB + Cancel + Download cancelled + The engine is ready + No internet. Connect to a network and try again. + ChessPenguin: Stockfish engine + The download stopped. Please try again. + Not enough space: %1$d MB needed. + The engine file was damaged during the download. Download it again. + Try again + Download again + OK + Preparing the engine… + + Settings + Appearance + Engine + Theme + System default + Light + Dark + Move notation + Latin letters (K Q R B N) + Figurines + Letters of the language + Display only. PGN always uses K Q R B N. + Piece animation + Best-move arrow + Vibration + Stockfish 19 · built in + Stockfish 19 · downloaded + Not downloaded · Download (%1$d MB) + Downloading… %1$d of %2$d MB + Delete the engine (frees %1$d MB) + Delete the engine? You can download it again. + Delete + Lines + Time per position + %1$d s + 1 min + No limit + Threads + Memory + %1$d MB + The engine uses the battery. It turns off by itself when you leave the game or the app goes to the background. + About + Stockfish built in + Stockfish downloaded in the app + Chess databases, game analysis and play against the computer. Your files are only read, never changed. + Licenses and authors + Website and source code + + Game details + Copy PGN + Copy FEN + Share game + Notes + on + off + not downloaded + Found %1$s of %2$s + Game + %1$d, White, %2$s + %1$d, Black, %2$s + current move + Language + Checkmate + Stalemate + PGN copied + FEN copied + Event + Site + Date + Round + White + Black + Result + White Elo + Black Elo + Annotator + Plies + No access to the file: it was moved, deleted or its permission was taken back. Remove it from the list and add it again. + The file is damaged or is not a chess database. + There is no PGN or ChessBase database in the archive. + This kind of database cannot be read: %1$s + File + PGN, .cbv, .zip or .7z + Folder + Every database in a folder, ChessBase (.cbh) too + Looking for databases… + No databases in this folder + Looks for PGN files, ChessBase databases (.cbh, .cbv) and .zip or .7z archives in the folder and two levels of folders inside it. + already on the list + no .cbg file — the games can’t be opened + + %1$d database in “%2$s� + %1$d databases in “%2$s� + + + Add %1$d + Add %1$d + + + %1$d database added + %1$d databases added + + Android won’t let apps pick the storage root or Downloads itself — only a folder inside them. + Pick another + Done + Add + Tick all + Untick all + The file %1$s is not beside the database any more: it was moved or deleted. + Board and pieces + Brown + Blue + Green + Tournament + Sand + Coral + Grey + Purple + Ice + Navy + Mint + Emerald + Orange + Rose + Dusk + Night + Wood + Maple + Leather + Marble + Blue marble + Canvas + Metal + Olive + Stone + Green plastic + Purple diagonal + Pink pyramid + Sketch + Board + IC + NCF + Pieces + No. %1$s + Paste PGN from the clipboard + Games copied in another app + No PGN games in the clipboard + Pasted %1$s + + Game in clipboard + Games in clipboard + + Save this PGN game and open it on the board? + Save %1$s and open the first game on the board? All games will be kept in the local copy. + Open + Clipboard + Opening the file… + Couldn’t open the file + There are no chess games in this file. + The file could not be read: it may be gone, or the app it came from did not give access to it. Try opening it again. + A ChessBase database (.cbh) is made of several files, and only one came. Add the folder it is in: \"Add database\" → \"Folder\". + The app could not keep a copy of the file. Check that the phone has free space. + copy + Database deleted from ChessPenguin + + Game analysis + Game report + The engine evaluates every position of the main line. The game itself is not changed. + %d s + %d min + Analyse + Fill in + %1$d of %2$d positions are evaluated already. + Game analysis · %1$d of %2$d + Stop the analysis + Accuracy + Accuracy: White %1$s, Black %2$s + Report + %1$s was better + Inaccuracy + Mistake + Blunder + Inaccuracies + Mistakes + Blunders + Great move + Brilliant move + Great moves + Brilliant moves + Not evaluated: %d + The analysis stopped + Continue + Average centipawn loss + Opening + Middlegame + Endgame + %1$s · %2$s nodes per move + Evaluations from the PGN ([%eval]) + !! and ! need the engine: the PGN has evaluations only + !! and ! were not looked for in this analysis + This analysis was made with other engine settings + Update + Analyse with the engine + Hide analysis + Evaluation graph + Paused: the game is being analysed + Better line · move %1$d of %2$d + Go to the next such move + Show the better line on the board + %1$s, evaluation %2$s + Start position + + %1$d position, about %2$s + %1$d positions, about %2$s + + + Games from Lichess and Chess.com + Any player\'s games by nickname: yours, a pupil\'s, an opponent\'s + The player\'s games become a database on your phone, to search, view and analyse. Only the nickname is needed, no login. + Player\'s nickname + as on the site + A different nickname on Chess.com + Nickname on Chess.com + The same nickname + Latin letters, digits, _ and -, 2 to 30 characters + Find + Looking on the sites… + %1$s · about %2$d min the first time + months with games: %1$d + %1$s: no player with this nickname — check the spelling + Merge both sites into one database + Otherwise each site gets a database of its own + Into the new database “%1$s� + Into “%1$s� (%2$s there already; only new games are added) + Download + Lichess: %1$s of about %2$s · about %3$d min left + %1$s: %2$s + Chess.com: month %1$d of %2$d · %3$s + Stop + +%1$s, %2$s in all + No new games, %1$s in the database + Stopped, %1$s in the database + No games of standard chess there. + Open the database + Try again + %1$s does not answer. Check the internet connection and try again. + %1$s asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept. + %1$s answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin. + Could not write the database: the phone is out of space. + This database is being downloaded already. + %1$s does not answer + %1$s asks for a pause + The download stopped + Download new games + Stop the download + Downloading · %1$s + updated %1$s + not finished + Downloaded database deleted + Nickname on Lichess + %1$s · under a minute the first time + You can leave this screen: the database is on the list and the download goes on. + Done: %1$s + updated just now + “%1$s�: +%2$s, %3$s in all + “%1$s�: no new games + “%1$s�: %2$s + Open + + up to %1$s game + up to %1$s games + + Version %1$s is out + You have %1$s + Update + Install + Databases, settings and the engine stay. + Databases and settings stay. + ChessPenguin closes while it installs — then open it again. + Games are downloading: installing stops it; you can continue it later. + One permission is needed + Android installs apps from outside a store only with your permission. Settings will open: turn the switch on for ChessPenguin and come back. + Open settings + The permission is off — without it Android won’t install the new version. + Permission granted, downloading + Download from the website + Open the website + You can close this: the download goes on. + No network. The download goes on by itself when the network is back. + Waiting for network + Checking the file… + Keeping the engine… + Installing… + The new version is downloaded and checked. + Downloaded and checked + The new version is downloaded + Installation cancelled. The new version is downloaded — install it whenever you like. + ChessPenguin update + ChessPenguin is updated: %1$s → %2$s + The download failed. Try again. + The file got damaged while downloading, so it was not installed. Try again. + Something is wrong with this release: the Android file cannot be checked. Download the new version from the website. + Android did not install the new version: not enough space. Free %1$d MB and try again. + Android did not install the new version: this ChessPenguin is signed with a different key. The new version can only be installed after removing this one, and removing it loses the list of databases and the downloaded databases. + Android or the phone’s protection stopped the installation. Download the new version from the website. + Android did not install the new version. Try again or download it from the website. + No internet + Not enough space + The file got damaged + Android did not install it + The download failed + More + Details + Copy + Updates + Check for updates at start + Once a day ChessPenguin asks its site which version is the latest; the site counts installations that run. Only a random number of this installation, the version and the system are sent. The check runs even with offers off. + Offer new versions + A card on the Databases screen when a new version is out. + Works when the update check is on. + We won’t offer it again. Turn it on in Settings, About + Don’t offer updates + Check now + Checking… + You have the latest version + Checked %1$s + No internet — cannot check for updates + Could not check for updates: the site did not answer. Try later. + Version %1$s is out + Downloading version %1$s… + Version %1$s is downloaded + Update to %1$s, %2$d of %3$d megabytes downloaded + + The file cannot be checked + Undo + Moves deleted + Make it the main line + Delete the move and what follows + Move actions + New game + My databases + + New database + Games you enter or play against the computer will be here + + Add + PGN and ChessBase files, folders and games from the internet that you add will be here + Files + My games + New database + Name + Kept on the phone, in ChessPenguin. You can export the file from the database\'s menu. + Create + on the phone + Export the file… + Delete the database + File saved + Could not save the file + Database deleted + Delete “%1$s�? + + %1$s game will be deleted from the phone. If you need it, export the file first. + %1$s games will be deleted from the phone. If you need them, export the file first. + + Saved to “%1$s�, No. %2$s + Could not save the game + Save to “%1$s� + Save to my database… + Save to a database + Save to a database… + New database… + Create and save + Save the changes to “%1$s�? + Save the game? + Don’t save + Game data + YYYY.MM.DD + Not a date: 2026.10.26, 2026 or 26.10.2026 + Discard the changes? + Discard + Keep editing + Edit + Next + Learning the opening + up to %1$s + Learn the opening up to this move + Move %1$s of %2$s + ♔ White to move + ♚ Black to move + Mistakes: %1$s + Run %1$s + × The game has another move here + Show the move + Not done before + Last time: %1$s · clean in a row: %2$s + Last time: %1$s · best: %2$s + Done without mistakes + Done with a hint · mistakes: %1$s + Done · mistakes: %1$s + Run %1$s · best: %2$s + clean in a row: %1$s + Recent: %1$s + Play the move on the arrow + ↻ Again + ⬅ Back to the game + From the start + + %1$d run + %1$d runs + + Maia for ChessPenguin + You won + You lost + You resigned + Draw + checkmate + stalemate + the position occurred three times + 50 moves without a capture or a pawn move + neither side can checkmate + Maia resigned + Resign? + ⚑ Resign + ↶ Take back + Play against the computer + Your colour + White + Black + Random + Maia’s own rating: it does not match a person’s Elo. + Maia is downloaded once (%1$s MB, from huggingface.co, the authors\' own file). + Download and play + Play + thinking… + Game vs computer + Analyse + ↻ Rematch + Play on from here… + Checking… + Maia did not start: %1$s + Accept the win + Play to the end + Maia resigns + From here on, a game against Maia %1$s. + Abort + Your name + Maia is downloaded + Try again + Her position is lost. Accept the win or play on? + Continue + Game against Maia %1$s · you play %2$s + White + Black + Game removed + no clock + You + ✓ Saved + Save… + you play %1$s · %2$s + After %1$s + Sound + Undo + Now the main line + Elo + Analyse + Play on + Viewing: %1$s · back to the game › + the starting position + Maia did not start. + Download Maia again + There is a game put aside against %1$s + Continue it + Start a new one + A new game replaces it; what was played goes into the player’s database, unfinished. + Draw + by agreement + Maia declines the draw + Maia declined; offer again after two of her moves + Maia answers a draw offer with Stockfish: download it in the game screen (“Engine�) + %1$s — games against the computer + Games against the computer + ✓ In “%1$s�, No. %2$s › + Game written to “%1$s� unfinished + recorded automatically + Write games against the computer to the player’s database + Games are written to “%1$s� + Games will be written to a new database “%1$s�. + Without a name games go to “%1$s�. Enter a name to have a database of your own. + Games are not written by themselves (Settings). + ✓ New database “%1$s�, No. %2$s › + Could not write to “%1$s�: %2$s + A new game replaces it. + Last opened + Game against %1$s + move %1$d + + Amanda + Attacks first, then plays for active pieces. + Cloe + Likes closed positions. + Deborah + Defends well and likes her bishops. + Defender + Solid and careful; content with a draw. + Dynamic + Attacks, likes bishops, sacrifices now and then. + Grumpy + Attack and restraint; likes blocked positions, avoids draws. + Partisan + Attacks after quiet, stealthy openings. + Pawnsacker + Balanced, but gives up pawns more readily. + Pedrita + Pawns, defence and restraint. + Preston + A materialistic, moderate attacker. + Simple + The most computer-like: plain, sound chess. + Spitfire + Sharp and aggressive. + Strangler + A boa constrictor: squeezes slowly, very human-like. + Alekhine + Dynamic attacks and deep combinations. + Anand + Quick, universal play with sharp openings. + Anderssen + A romantic attacker of the 19th century: sacrifices. + Bosboom + Offbeat openings and creative blitz play. + Botvinnik + Scientific, strategic play from deep preparation. + Fischer + Clear, classical and precise. + Karpov + Positional squeeze, prophylaxis and technique. + Kasparov + Initiative and powerful attack. + Kortchnoi + A tenacious defender and counter-attacker. + Larsen + Original and risky, with offbeat openings. + Lasker + A practical, psychological fighter. + Marshall + A swashbuckling attacker with gambits. + Morphy + Quick development and open lines. + Nimzowitsch + Restraint, blockade and overprotection. + Petrosian + Prophylaxis and safety first. + Reti + Hypermodern: controls the centre from afar. + Rubinstein + Classical positional play, great in endgames. + Spassky + A universal player, at home in any position. + Steinitz + The founder of positional play, a stubborn defender. + Tal + The magician from Riga: sacrifices and attack. + Tarrasch + Classical rules: space, development, active pieces. + Topalov + Aggressive and dynamic, sacrifices the exchange. + plays like a human + strong, with a style + Like a human + Maia does not pick a style: she plays like people of her rating. + Rodent’s own rating (UCI_Elo): it does not match a person’s Elo. + Rodent resigns + Rodent resigned + Rodent declines the draw + Rodent declined; offer again after two of its moves + Its position is lost. Accept the win, or play to the end? + Play + Play the computer + Strength: %1$s + Who to play + A character is a style and openings; the slider sets the strength. + Great players + Characters + Change + %1$s, great player + %1$s, character + Character: %1$s + Rodent IV and its opening books are on the phone + Rodent IV opening books: %1$s MB, downloaded once from github.com + From a position no opening book is needed: Rodent IV plays at once + No book + No book: play without the opening book + Rodent IV opening books + Rodent IV — opening books + downloaded · %1$s MB + not downloaded · %1$s MB + Opening books deleted + Rodent answers a draw offer with Stockfish: download it in the game screen (“Engine�) + Rodent did not start. + Restart + From here on, a game against Rodent IV %1$s · %2$s. + Rodent stopped during the game. + %1$s, from %2$s to %3$s + Strength + Delete the opening books + + + Players + Player name + Could not read players + Reading players… + There are no named players in this database + Player not found + Back to games + Clear search + Prepare + Choose a color + Prepare against %1$s + Against White + Against Black + Prepare for opponent… + Opponent preparation + Close the engine line first + + Search after a teaching -- is unavailable + White + Black + Could not play this move + Play %1$s, %2$s, %3$s percent + Board, starting position. %1$s at the bottom. + Board, position after %1$s. %2$s at the bottom. + White to move + Black to move + Opponent plays + Their opponents play + after %1$s + start + %1$s, %2$s, %3$s, %4$s + Could not calculate continuations + Not enough memory to search this database + Calculating continuations… + This position does not occur in games by %1$s + You can continue on the board or go back + All games ended here + Ended here: %1$s + No normal continuation: %1$s + Back to game + Back to players + Choose a move + + %1$s win + %1$s wins + + + %1$s draw + %1$s draws + + + %1$s loss + %1$s losses + + Unknown results: %1$d; excluded from the percentages. + %1$s. %2$d of %3$s, %4$s percent. Results for %5$s: %6$s, %7$s, %8$s; %9$s, %10$s and %11$s percent. %12$s Play. + Play + more %1$s + +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% + diff --git a/androidApp/app/src/main/res/values/themes.xml b/androidApp/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..5bbd611 --- /dev/null +++ b/androidApp/app/src/main/res/values/themes.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/androidApp/app/src/main/res/xml/locales_config.xml b/androidApp/app/src/main/res/xml/locales_config.xml new file mode 100644 index 0000000..971c210 --- /dev/null +++ b/androidApp/app/src/main/res/xml/locales_config.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/androidApp/app/src/rustore/AndroidManifest.xml b/androidApp/app/src/rustore/AndroidManifest.xml new file mode 100644 index 0000000..ecf6e33 --- /dev/null +++ b/androidApp/app/src/rustore/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ClipboardIncomingTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ClipboardIncomingTest.kt new file mode 100644 index 0000000..215f6d1 --- /dev/null +++ b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ClipboardIncomingTest.kt @@ -0,0 +1,95 @@ +package io.github.vrubelroman.chesspenguin + +import io.github.vrubelroman.chesspenguin.data.DbEntry +import io.github.vrubelroman.chesspenguin.data.Source +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ClipboardIncomingTest { + @Test + fun `pasted existing copy ignores a previous empty filtered view`() { + val shown = hashMapOf("copy" to emptyList()) + val lastOpened = hashMapOf("copy" to ("not-found" to 0)) + + resetPastedView(shown, lastOpened, "copy") + + assertFalse(shown.containsKey("copy")) + assertFalse(lastOpened.containsKey("copy")) + } + + @Test + fun `uri and clipboard publish only their latest common request`() { + val requests = LatestIncoming() + val uri = requests.next() + val clipboard = requests.next() + + assertFalse(requests.isLatest(uri)) + assertTrue(requests.isLatest(clipboard)) + + val newerUri = requests.next() + assertFalse(requests.isLatest(clipboard)) + assertTrue(requests.isLatest(newerUri)) + } + + @Test + fun `stale request cannot publish after a newer request starts`() { + val requests = LatestIncoming() + val old = requests.next() + val current = requests.next() + var published: Long? = null + + assertFalse(requests.publish(old) { published = old }) + assertNull(published) + assertTrue(requests.publish(current) { published = current }) + assertEquals(current, published) + } + + @Test + fun `blank clipboard snapshot does not invalidate uri import`() { + val requests = LatestIncoming() + val uri = requests.next(IncomingOrigin.Uri) + + assertFalse(requests.invalidateClipboard()) + assertTrue(requests.isLatest(uri)) + } + + @Test + fun `clipboard snapshot invalidates active clipboard import`() { + val requests = LatestIncoming() + val clipboard = requests.next(IncomingOrigin.Clipboard) + + assertTrue(requests.invalidateClipboard()) + assertFalse(requests.isLatest(clipboard)) + } + + @Test + fun `failed dismiss compareAndSet cannot clear a newer opening`() { + val incoming = MutableStateFlow(Incoming.Failed(IllegalStateException("old"))) + val expected = incoming.value + incoming.value = Incoming.Opening + + assertFalse(incoming.compareAndSet(expected, null)) + assertEquals(Incoming.Opening, incoming.value) + } + + @Test + fun `stale collector cannot clear a newer incoming event`() { + val entry = DbEntry( + id = "copy", + name = "Clipboard", + source = Source.Copy, + location = "copy.pgn", + fileName = "clipboard.pgn", + ) + val incoming = MutableStateFlow(Incoming.Opened(entry)) + val expected = incoming.value + incoming.value = Incoming.Opening + + assertFalse(incoming.compareAndSet(expected, null)) + assertEquals(Incoming.Opening, incoming.value) + } +} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/ClipboardPromptGateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/ClipboardPromptGateTest.kt new file mode 100644 index 0000000..3a173a2 --- /dev/null +++ b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/ClipboardPromptGateTest.kt @@ -0,0 +1,135 @@ +package io.github.vrubelroman.chesspenguin.data + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class ClipboardPromptGateTest { + @Test + fun `new offer is accepted once and same offer cannot be accepted twice`() { + val gate = ClipboardPromptGate() + val generation = gate.invalidate() + val offer = offer("same", generation) + assertTrue(gate.publish(offer)) + + val accepted = gate.accept(offer) + + assertNotNull(accepted) + assertNull(gate.accept(offer)) + assertTrue(gate.canPublish(accepted!!)) + } + + @Test + fun `blank snapshot invalidates offer and pending publication`() { + val gate = ClipboardPromptGate() + val generation = gate.invalidate() + val offer = offer("old", generation) + assertTrue(gate.publish(offer)) + val accepted = gate.accept(offer)!! + + gate.invalidate() + + assertFalse(gate.canPublish(accepted)) + assertFalse(gate.publish(offer)) + } + + @Test + fun `stale accept is ignored after snapshot changes`() { + val gate = ClipboardPromptGate() + val old = offer("old", gate.invalidate()) + assertTrue(gate.publish(old)) + gate.invalidate() + val current = offer("current", gate.invalidate()) + + assertNull(gate.accept(old)) + assertTrue(gate.publish(current)) + assertNotNull(gate.accept(current)) + } + + @Test + fun `changed snapshot forbids old import publication`() { + val gate = ClipboardPromptGate() + val accepted = gate.accept(offer("old", gate.invalidate()).also { gate.publish(it) })!! + + gate.invalidate() + + assertFalse(gate.canPublish(accepted)) + } + + @Test + fun `dismissed digest stays decided while changed text is allowed`() { + val gate = ClipboardPromptGate() + val dismissed = offer("dismissed", gate.invalidate()) + assertTrue(gate.publish(dismissed)) + assertTrue(gate.dismiss(dismissed)) + + assertFalse(gate.publish(dismissed.copy(generation = gate.invalidate()))) + assertTrue(gate.publish(offer("changed", gate.invalidate()))) + } + + @Test + fun `successful open persists digest only after entry and survives cold restoration`() { + var persisted = emptySet() + val first = ClipboardPromptGate(onDecide = { persisted = it }) + val offer = offer("sha256-of-opened-text", first.invalidate()) + assertTrue(first.publish(offer)) + val accepted = first.accept(offer)!! + assertTrue(persisted.isEmpty()) + + assertTrue(first.finish(accepted, true)) + + val restored = ClipboardPromptGate(decided = persisted) + assertFalse(restored.publish(offer.copy(generation = restored.invalidate()))) + assertTrue(restored.publish(offer.copy(digest = "new-text", generation = restored.invalidate()))) + } + + @Test + fun `failed import does not persist digest and retries after cold start`() { + var persisted = emptySet() + val first = ClipboardPromptGate(onDecide = { persisted = it }) + val offer = offer("retry-digest", first.invalidate()) + assertTrue(first.publish(offer)) + val accepted = first.accept(offer)!! + assertTrue(persisted.isEmpty()) + + assertTrue(first.finish(accepted, false)) + + val restored = ClipboardPromptGate(decided = persisted) + assertTrue(restored.publish(offer.copy(generation = restored.invalidate()))) + } + + @Test + fun `one UTF8 snapshot preserves BOM CRLF unicode and import bytes`() { + val text = "\uFEFF[Event \"Парти� 😀\"]\r\n1. e4 e5\r\n*" + val bytes = clipboardUtf8(text) + val gate = ClipboardPromptGate() + val offer = ClipboardOffer(bytes, 1, clipboardSha256(bytes), gate.invalidate()) + assertTrue(gate.publish(offer)) + + val accepted = gate.accept(offer)!! + + assertArrayEquals(text.toByteArray(Charsets.UTF_8), accepted.bytes) + assertSame(bytes, accepted.bytes) + assertNotEquals( + clipboardSha256(bytes), + clipboardSha256(clipboardUtf8(text.replace("\r\n", "\n"))), + ) + } + + @Test + fun `clipboard size limit includes eight MiB and rejects one byte more`() { + assertTrue(clipboardPgnLengthMayFit("a".repeat(CLIPBOARD_PGN_MAX_BYTES))) + assertFalse(clipboardPgnLengthMayFit("a".repeat(CLIPBOARD_PGN_MAX_BYTES + 1))) + assertTrue(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES - 1)) + assertTrue(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES)) + assertFalse(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES + 1)) + } + + private fun offer(digest: String, generation: Long, games: Int = 1): ClipboardOffer = + ClipboardOffer(byteArrayOf(1), games, digest, generation) +} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/LibraryClipboardTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/LibraryClipboardTest.kt new file mode 100644 index 0000000..1495074 --- /dev/null +++ b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/LibraryClipboardTest.kt @@ -0,0 +1,47 @@ +package io.github.vrubelroman.chesspenguin.data + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class LibraryClipboardTest { + @Test + fun `first valid record is accepted even when a later record is malformed`() { + assertTrue(firstPgnGameIsMeaningful(count = 2, tags = 1, nodes = 1)) + assertTrue(firstPgnGameIsMeaningful(count = 2, tags = 0, nodes = 2)) + } + + @Test + fun `first malformed record is rejected even when a later record is valid`() { + assertFalse(firstPgnGameIsMeaningful(count = 2, tags = 0, nodes = 1)) + } + + @Test + fun `multiple empty records and zero records are rejected`() { + assertFalse(firstPgnGameIsMeaningful(count = 3, tags = 0, nodes = 1)) + assertFalse(firstPgnGameIsMeaningful(count = 0, tags = 0, nodes = 0)) + } + + @Test + fun `tag only first record is accepted by the shared addCopy rule`() { + assertTrue(firstPgnGameIsMeaningful(count = 1, tags = 1, nodes = 1)) + } + + @Test + fun `final digest lookup reuses an existing copy after concurrent parsing`() { + val existing = DbEntry( + id = "existing", + name = "Clipboard", + source = Source.Copy, + location = "existing.pgn", + fileName = "clipboard.pgn", + sha256 = "same-digest", + ) + val other = existing.copy(id = "other", sha256 = "other-digest") + + assertSame(existing, copyWithDigest(listOf(other, existing), "same-digest")) + assertNull(copyWithDigest(listOf(other, existing), "new-digest")) + } +} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/BoardArrowHitTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/BoardArrowHitTest.kt new file mode 100644 index 0000000..daa6fd9 --- /dev/null +++ b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/BoardArrowHitTest.kt @@ -0,0 +1,41 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.ui.geometry.Offset +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class BoardArrowHitTest { + @Test + fun `flip changes the hit point but not UCI`() { + val move = BoardArrowMove("e2e4", "e2", "e4", "e4") + val square = 40f + val center = Offset(square / 2, square / 2) + val target = squareIndex("e4")!! + val normal = boardCell(target, square, false) + center + val flipped = boardCell(target, square, true) + center + + assertEquals(listOf("e2e4"), arrowHits(normal, square, false, listOf(move), 24f).map { it.uci }) + assertTrue(arrowHits(normal, square, true, listOf(move), 24f).isEmpty()) + assertEquals(listOf("e2e4"), arrowHits(flipped, square, true, listOf(move), 24f).map { it.uci }) + } + + @Test + fun `overlapping targets return every conflicting UCI`() { + val square = 35f + val center = Offset(square / 2, square / 2) + val target = boardCell(squareIndex("e8")!!, square, false) + center + val moves = listOf( + BoardArrowMove("e7e8q", "e7", "e8", "queen"), + BoardArrowMove("e7e8n", "e7", "e8", "knight"), + ) + + assertEquals(listOf("e7e8q", "e7e8n"), arrowHits(target, square, false, moves, 24f).map { it.uci }) + } + + @Test + fun `points outside the board never activate an arrow`() { + val move = BoardArrowMove("e2e4", "e2", "e4", "e4") + assertTrue(arrowHits(Offset(-1f, 10f), 40f, false, listOf(move), 24f).isEmpty()) + } +} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/GameBarStateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/GameBarStateTest.kt new file mode 100644 index 0000000..c424c18 --- /dev/null +++ b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/GameBarStateTest.kt @@ -0,0 +1,54 @@ +package io.github.vrubelroman.chesspenguin.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class GameBarStateTest { + @Test + fun `loaded game can start or open its report`() { + assertTrue(enabled()) + assertTrue(enabled(hasData = true, running = true)) + } + + @Test + fun `review is unavailable during computer play and without moves`() { + assertFalse(enabled(gameOn = true, sessionGame = true)) + assertFalse(enabled(hasMoves = false)) + } + + @Test + fun `database game waits for its review state`() { + assertFalse(enabled(loaded = false)) + assertTrue(enabled(sessionGame = true, loaded = false)) + } + + @Test + fun `first running database analysis disables duplicate start`() { + assertFalse(enabled(running = true)) + } + + @Test + fun `session game cannot duplicate its first run`() { + assertFalse(enabled(sessionGame = true, loaded = true, running = true)) + assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true)) + } + + @Test + fun `report wins over running while an empty run waits`() { + assertEquals(ReviewAction.Start, reviewAction(hasData = false, running = false)) + assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true)) + assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = false)) + assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = true)) + } + + private fun enabled( + hasMoves: Boolean = true, + gameOn: Boolean = false, + sessionGame: Boolean = false, + loaded: Boolean = true, + hasData: Boolean = false, + running: Boolean = false, + ) = reviewEnabled(hasMoves, gameOn, sessionGame, loaded, hasData, running) +} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PlayersStateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PlayersStateTest.kt new file mode 100644 index 0000000..a3a8321 --- /dev/null +++ b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PlayersStateTest.kt @@ -0,0 +1,46 @@ +package io.github.vrubelroman.chesspenguin.ui + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class PlayersStateTest { + @Test + fun `two available colors always require an explicit choice`() { + val blackMoreOften = player(white = 2, black = 3) + val whiteMoreOften = player(white = 9, black = 1) + + assertTrue(playerNeedsColorChoice(blackMoreOften)) + assertTrue(playerNeedsColorChoice(whiteMoreOften)) + assertNull(solePlayerColor(blackMoreOften)) + assertNull(solePlayerColor(whiteMoreOften)) + } + + @Test + fun `exactly one available color is the direct action`() { + val whiteOnly = player(white = 2, black = 0) + val blackOnly = player(white = 0, black = 1) + + assertTrue(solePlayerColor(whiteOnly) == true) + assertTrue(solePlayerColor(blackOnly) == false) + assertFalse(playerNeedsColorChoice(whiteOnly)) + assertFalse(playerNeedsColorChoice(blackOnly)) + } + + @Test + fun `zero colors do not become an action`() { + val empty = player(white = 0, black = 0) + + assertNull(solePlayerColor(empty)) + assertFalse(playerNeedsColorChoice(empty)) + } + + private fun player(white: Int, black: Int) = PlayerSummary( + id = 1, + name = "Player", + total = 100, + whiteGames = white, + blackGames = black, + ) +} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PrepLineStateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PrepLineStateTest.kt new file mode 100644 index 0000000..bb9491b --- /dev/null +++ b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PrepLineStateTest.kt @@ -0,0 +1,101 @@ +package io.github.vrubelroman.chesspenguin.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class PrepLineStateTest { + @Test + fun `back and forward follow the same continuation`() { + val line = line("e2e4", "e7e5", "g1f3") + + val back = line.back().back() + assertEquals(1, back.cursor) + assertEquals("e2e4", back.last?.uci) + assertTrue(back.canForward) + + val forward = back.forward() + assertEquals("e7e5", forward.last?.uci) + assertEquals("g1f3", forward.forward().last?.uci) + } + + @Test + fun `long actions jump without an extra step`() { + val line = line("e2e4", "e7e5", "g1f3") + assertEquals(0, line.start().cursor) + assertEquals(line.steps.size, line.start().end().cursor) + assertEquals(line, line.end()) + assertEquals(line.start(), line.start().start()) + } + + @Test + fun `a played line replaces only the temporary future`() { + val original = line("e2e4", "e7e5", "g1f3").back().back() + val prefix = original.steps.take(original.cursor) + val replacement = step("c7c5", 2, "c5") + val changed = original.replaceVisibleLine(prefix + replacement, replacement.node) + + assertEquals(listOf("e2e4", "c7c5"), changed.moves) + assertEquals(2, changed.cursor) + assertFalse(changed.canForward) + assertEquals(listOf("e2e4", "e7e5", "g1f3"), original.moves) + } + + @Test + fun `opponent color puts the user at the bottom`() { + assertTrue(prepBoardStartsFlipped(opponentWhite = true)) + assertFalse(prepBoardStartsFlipped(opponentWhite = false)) + } + + @Test + fun `side and number come from FEN rather than parity`() { + val black = "8/8/8/8/8/8/4k3/4K3 b - - 0 0" + assertEquals(false, prepWhiteToMove(black)) + assertEquals("0…Kd2", moveLabel(black, "Kd2")) + assertEquals("12.Nf3", moveLabel(STANDARD_START.substringBeforeLast(" 1") + " 12", "Nf3")) + assertNull(prepWhiteToMove("not a fen")) + } + + @Test + fun `frequency and WDL have separate denominators`() { + val move = PrepContinuation("e7e5", "e5", games = 4, wins = 2, draws = 0, losses = 1, unknown = 1) + assertEquals("40", frequencyPercent(move.games, 10)) + assertEquals(Triple("67", "0", "33"), outcomePercents(move)) + assertEquals("<1", frequencyPercent(1, 113)) + assertEquals("0", frequencyPercent(0, 113)) + assertEquals(Triple("—", "—", "—"), outcomePercents(move.copy(wins = 0, losses = 0))) + } + + @Test + fun `continuations are sorted by games then SAN without hiding rare moves`() { + val position = PrepPosition( + games = 5, + continuations = listOf( + PrepContinuation("g1f3", "Nf3", 1, 1, 0, 0), + PrepContinuation("e2e4", "e4", 3, 1, 1, 1), + PrepContinuation("d2d4", "d4", 1, 0, 1, 0), + ), + ) + assertEquals(listOf("e4", "Nf3", "d4"), sortedContinuations(position).map { it.san }) + } + + private fun line(vararg moves: String): PrepLineState = PrepLineState( + startFen = STANDARD_START, + rootFen = STANDARD_START, + steps = moves.mapIndexed { i, uci -> step(uci, i + 1, uci.take(4)) }, + cursor = moves.size, + ) + + private fun step(uci: String, node: Int, san: String) = PrepLineStep( + node = node, + uci = uci, + san = san, + moveNumber = (node + 1) / 2, + white = node % 2 == 1, + fen = STANDARD_START, + from = uci.take(2), + to = uci.substring(2, 4), + ) +} diff --git a/androidApp/build.gradle.kts b/androidApp/build.gradle.kts new file mode 100644 index 0000000..bb92a46 --- /dev/null +++ b/androidApp/build.gradle.kts @@ -0,0 +1,6 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + alias(libs.plugins.android.application) apply false + alias(libs.plugins.compose.compiler) apply false + alias(libs.plugins.kotlin.serialization) apply false +} \ No newline at end of file diff --git a/androidApp/gradle.properties b/androidApp/gradle.properties new file mode 100644 index 0000000..32d72a9 --- /dev/null +++ b/androidApp/gradle.properties @@ -0,0 +1,29 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# Enables Gradle Build Cache. +# See https://docs.gradle.org/current/userguide/build_cache.html +org.gradle.caching=true +# Enables Gradle Configuration Cache, the preferred Gradle execution mode. +# See https://docs.gradle.org/current/userguide/configuration_cache.html +org.gradle.configuration-cache=true +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true diff --git a/androidApp/gradle/libs.versions.toml b/androidApp/gradle/libs.versions.toml new file mode 100644 index 0000000..01b05b6 --- /dev/null +++ b/androidApp/gradle/libs.versions.toml @@ -0,0 +1,53 @@ +[versions] +androidGradlePlugin = "9.4.1" +androidxCore = "1.19.1" +androidxLifecycle = "2.11.0" +androidxActivity = "1.13.0" +androidxComposeBom = "2026.09.00" +androidxTest = "1.7.0" +androidxTestExt = "1.3.0" +androidxTestRunner = "1.7.0" +androidxTestEspresso = "3.7.0" +coroutines = "1.11.0" +junit = "4.13.2" +kotlin = "2.4.21" +nav3Core = "1.0.1" +lifecycleViewmodelNav3 = "2.10.0" + +jna = "5.19.1" +serializationJson = "1.12.0" +androidsvg = "1.4" +datastore = "1.3.0" + +[libraries] +androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidxCore" } +jna = { module = "net.java.dev.jna:jna", version.ref = "jna" } +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serializationJson" } +androidsvg = { module = "com.caverock:androidsvg-aar", version.ref = "androidsvg" } +androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastore" } +androidx-compose-material-icons = { group = "androidx.compose.material", name = "material-icons-extended" } +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidxActivity" } +androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "androidxComposeBom" } +androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3"} +androidx-compose-ui = { group = "androidx.compose.ui", name = "ui"} +androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview"} +androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4"} +androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling"} +androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest"} +androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidxLifecycle" } +androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "androidxLifecycle" } +androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "androidxLifecycle" } +androidx-test-core = { module = "androidx.test:core", version.ref = "androidxTest" } +androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestExt" } +androidx-test-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "androidxTestEspresso" } +androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" } +junit = { module = "junit:junit", version.ref = "junit" } +kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } +androidx-navigation3-runtime = { module = "androidx.navigation3:navigation3-runtime", version.ref = "nav3Core" } +androidx-navigation3-ui = { module = "androidx.navigation3:navigation3-ui", version.ref = "nav3Core" } +androidx-lifecycle-viewmodel-navigation3 = { module = "androidx.lifecycle:lifecycle-viewmodel-navigation3", version.ref = "lifecycleViewmodelNav3" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" } +compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } \ No newline at end of file diff --git a/androidApp/gradle/wrapper/gradle-wrapper.jar b/androidApp/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9fa7f28 Binary files /dev/null and b/androidApp/gradle/wrapper/gradle-wrapper.jar differ diff --git a/androidApp/gradle/wrapper/gradle-wrapper.properties b/androidApp/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5907d39 --- /dev/null +++ b/androidApp/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/androidApp/gradlew b/androidApp/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/androidApp/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/androidApp/gradlew.bat b/androidApp/gradlew.bat new file mode 100644 index 0000000..03754c4 --- /dev/null +++ b/androidApp/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/androidApp/scripts/release.sh b/androidApp/scripts/release.sh new file mode 100755 index 0000000..30badc5 --- /dev/null +++ b/androidApp/scripts/release.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Builds the two signed release APKs into androidApp/dist: +# ChessPenguin--android.apk Stockfish built in ("full") +# ChessPenguin--android-noengine.apk Stockfish downloaded in the app ("light") +# and, apart (not a file of the release), into androidApp/dist-rustore: +# ChessPenguin--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. +set -euo pipefail +cd "$(dirname "$0")/.." +env_file="${CP_SIGNING_ENV:-$HOME/.config/chesspenguin/android/.env}" +if [[ -z "${CP_KEYSTORE:-}" && -f "${env_file}" ]]; then + set -a + # shellcheck disable=SC1090 + source "${env_file}" + set +a +fi +: "${CP_KEYSTORE:?no release key: set CP_KEYSTORE and the passwords, or CP_SIGNING_ENV}" +./gradlew --console=plain assembleFullRelease assembleLightRelease assembleFullRustore +version="$(sed -n 's/^version = "\(.*\)"/\1/p' ../Cargo.toml | head -n1)" +mkdir -p dist +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" +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)" +for apk in dist/ChessPenguin-"${version}"-android*.apk dist-rustore/ChessPenguin-"${version}"-rustore.apk; do + "${build_tools}/apksigner" verify "${apk}" + "${build_tools}/zipalign" -c -P 16 4 "${apk}" +done +(cd dist && sha256sum ChessPenguin-"${version}"-android*.apk > ChessPenguin-"${version}"-android.sha256) +# The store's build asks for nothing it would not need. +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 diff --git a/androidApp/scripts/rodent4.sh b/androidApp/scripts/rodent4.sh new file mode 100755 index 0000000..f8e8db6 --- /dev/null +++ b/androidApp/scripts/rodent4.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Builds Rodent IV (github.com/nescitus/rodent-iv, GPL-3.0) for Android from the authors' +# sources at the commit the desktop build uses (.github/workflows/rodent-iv.yml), with the +# same fix (packaging/rodent-iv/home-dir.patch), and two more: think-thread.patch (a +# dangling reference that clang builds trip over) and android.patch (bionic has no +# wordexp); takes its personalities. +# +# scripts/rodent4.sh OUT_DIR +# OUT_DIR/jniLibs/arm64-v8a/librodent4.so, OUT_DIR/jniLibs/x86_64/librodent4.so +# OUT_DIR/home/personalities/* (basic.ini and the personality files) +# OUT_DIR/source/LICENSE, README.md, COPYRIGHT, books//readme.txt (the books' +# credits, the authors' #readme.txt) +# +# The executable goes into the APK as a "library", the only place Android 10+ lets an +# app execute a file from (docs/research/android-stack.md §5). The engine finds its +# personalities and books in the folder named by RODENT4HOME: NDK clang defines +# __ANDROID__ but not ANDROID, so the authors' /sdcard/Rodent4 branch is not compiled +# (android.patch keys only the missing wordexp on __ANDROID__). +# The books are not here: the app downloads them. libc++ is linked statically. +# The source is cached in ~/.cache/chesspenguin-android and checked against its SHA-256. +# Needs ANDROID_NDK_HOME (NDK r27c or later). +set -euo pipefail + +commit="e8d84c8c8c189a1cf4eb27c578fc573af3b916d2" +source_sha256="db372b48a8ccf22d9bfbe3e5454cbbccb81dadca0120cbc0abaee2a81a0cb3fe" +api=31 + +here="$(cd "$(dirname "$0")" && pwd)" +patches="${here}/../../packaging/rodent-iv" +out="$(realpath -m "${1:?usage: $0 OUT_DIR}")" +ndk="${ANDROID_NDK_HOME:?set ANDROID_NDK_HOME}" +cache="${XDG_CACHE_HOME:-$HOME/.cache}/chesspenguin-android" +mkdir -p "${cache}" "${out}" + +file="rodent-iv-${commit}.tar.gz" +if ! { [[ -f "${cache}/${file}" ]] \ + && echo "${source_sha256} ${cache}/${file}" | sha256sum -c --quiet - 2>/dev/null; }; then + curl -fsSL --retry 3 --max-time 900 -o "${cache}/${file}.part" \ + "https://github.com/nescitus/rodent-iv/archive/${commit}.tar.gz" + if ! echo "${source_sha256} ${cache}/${file}.part" | sha256sum -c --quiet -; then + rm -f "${cache}/${file}.part" + echo "rodent4.sh: the source does not match its SHA-256" >&2 + exit 1 + fi + mv "${cache}/${file}.part" "${cache}/${file}" +fi + +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT +tar -xzf "${cache}/${file}" -C "${work}" +root="${work}/rodent-iv-${commit}" +patch -s -d "${root}" -p1 < "${patches}/home-dir.patch" +patch -s -d "${root}" -p1 < "${patches}/think-thread.patch" +patch -s -d "${root}" -p1 < "${patches}/android.patch" + +bin="${ndk}/toolchains/llvm/prebuilt/linux-x86_64/bin" +build() { # abi target + "${bin}/$2${api}-clang++" -O3 -w -pipe -DNDEBUG -fno-rtti -finline-functions -std=c++14 \ + -static-libstdc++ "${root}"/sources/src/*.cpp -o "${work}/rodent4-$1" -lm + mkdir -p "${out}/jniLibs/$1" + "${bin}/llvm-strip" -o "${out}/jniLibs/$1/librodent4.so" "${work}/rodent4-$1" +} +build arm64-v8a aarch64-linux-android +build x86_64 x86_64-linux-android + +rm -rf "${out}/home" "${out}/source" +mkdir -p "${out}/home" "${out}/source" +cp -r "${root}/personalities" "${out}/home/personalities" +cp "${root}/LICENSE" "${root}/README.md" "${out}/source/" +# The authors are named in the sources' headers; the repository has no AUTHORS file. +sed -n '/^\/\*/,/^\*\//p' "${root}/sources/src/main.cpp" > "${out}/source/COPYRIGHT" +# The books are downloaded by the app; their credits come with the licence. +for credits in $(cd "${root}" && find books -name '#readme.txt'); do + mkdir -p "${out}/source/$(dirname "${credits}")" + cp "${root}/${credits}" "${out}/source/$(dirname "${credits}")/readme.txt" +done +echo "Rodent IV (${commit:0:8}) for Android -> ${out}" diff --git a/androidApp/scripts/stockfish.sh b/androidApp/scripts/stockfish.sh new file mode 100755 index 0000000..fc383da --- /dev/null +++ b/androidApp/scripts/stockfish.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# Builds Stockfish for Android from the pinned official source, without the network +# inside (the app passes it with EvalFile), and fetches that network. +# +# scripts/stockfish.sh OUT_DIR +# OUT_DIR/jniLibs/arm64-v8a/libstockfish.so, OUT_DIR/jniLibs/x86_64/libstockfish.so +# OUT_DIR/net/.nnue, OUT_DIR/source/Copying.txt, AUTHORS +# +# The executable goes into the APK as a "library", the only place Android 10+ lets an +# app execute a file from (docs/research/android-stack.md §5). Downloads are cached in +# ~/.cache/chesspenguin-android and checked against their SHA-256. +# Needs ANDROID_NDK_HOME (NDK r27c or later). +set -euo pipefail + +tag="sf_19" +source_sha256="519b653d0d1ffb96531d982ccbe5c6a19425e8388e0e3c2f70f34b424ab32d76" +net="nn-1a298aa575a0.nnue" +net_sha256="1a298aa575a085434d29027978dc36867fe9c5bcea9376654b7a8eba1e52dfc2" + +out="$(realpath -m "${1:?usage: $0 OUT_DIR}")" +ndk="${ANDROID_NDK_HOME:?set ANDROID_NDK_HOME}" +cache="${XDG_CACHE_HOME:-$HOME/.cache}/chesspenguin-android" +mkdir -p "${cache}" "${out}" + +fetch() { # file sha256 url... + local file="$1" sha="$2" + shift 2 + if [[ -f "${cache}/${file}" ]] && echo "${sha} ${cache}/${file}" | sha256sum -c --quiet - 2>/dev/null; then + return + fi + for url in "$@"; do + if curl -fsSL --retry 3 --max-time 900 -o "${cache}/${file}.part" "${url}" \ + && echo "${sha} ${cache}/${file}.part" | sha256sum -c --quiet -; then + mv "${cache}/${file}.part" "${cache}/${file}" + return + fi + echo "stockfish.sh: ${url} failed or did not match" >&2 + done + rm -f "${cache}/${file}.part" + exit 1 +} + +fetch "${tag}.tar.gz" "${source_sha256}" \ + "https://github.com/official-stockfish/Stockfish/archive/refs/tags/${tag}.tar.gz" +fetch "${net}" "${net_sha256}" \ + "https://github.com/official-stockfish/networks/raw/master/${net}" \ + "https://tests.stockfishchess.org/api/nn/${net}" + +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT +tar -xzf "${cache}/${tag}.tar.gz" -C "${work}" +src="$(find "${work}" -maxdepth 2 -type d -name src | head -n1)" +# The Makefile checks the network before building; it finds it in place. +cp "${cache}/${net}" "${src}/${net}" + +export PATH="${ndk}/toolchains/llvm/prebuilt/linux-x86_64/bin:${PATH}" +build() { # abi arch + make -C "${src}" -s clean >/dev/null + make -C "${src}" -j"$(nproc)" build ARCH="$2" COMP=ndk EXTRACXXFLAGS=-DNNUE_EMBEDDING_OFF >/dev/null + mkdir -p "${out}/jniLibs/$1" + llvm-strip -o "${out}/jniLibs/$1/libstockfish.so" "${src}/stockfish" +} +build arm64-v8a armv8 +build x86_64 x86-64-sse41-popcnt + +mkdir -p "${out}/net" "${out}/source" +cp "${cache}/${net}" "${out}/net/${net}" +cp "${src}/../Copying.txt" "${src}/../AUTHORS" "${out}/source/" +echo "Stockfish ${tag} for Android -> ${out}" diff --git a/androidApp/settings.gradle.kts b/androidApp/settings.gradle.kts new file mode 100644 index 0000000..8023ef1 --- /dev/null +++ b/androidApp/settings.gradle.kts @@ -0,0 +1,33 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("androidx.*") + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google { + content { + includeGroupByRegex("androidx.*") + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + } + } + mavenCentral() + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + +rootProject.name = "ChessPenguin" +include(":app") diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml new file mode 100644 index 0000000..4e5ae2c --- /dev/null +++ b/apps/desktop/Cargo.toml @@ -0,0 +1,96 @@ +[package] +name = "chesspenguin" +description = "Chess database for Linux: view, enter and analyse PGN games with UCI engines" +version.workspace = true +authors.workspace = true +repository.workspace = true +homepage.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true + +# The interface, shared with the web version (apps/web); src/main.rs starts it in a +# window. +[lib] +name = "chesspenguin_app" +path = "src/lib.rs" + +[[bin]] +name = "chesspenguin" +path = "src/main.rs" + +[dependencies] +chess-core.workspace = true +chess-openings.workspace = true +maia.workspace = true +game-review.workspace = true +prep.workspace = true +chess-import.workspace = true +shakmaty.workspace = true +uci.workspace = true +egui.workspace = true +eframe.workspace = true +egui_extras.workspace = true +image.workspace = true +directories.workspace = true +trainer.workspace = true +play.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +online-games.workspace = true +web-time.workspace = true +sha2 = "0.11" +zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs"] } +# The system language for the first start. +sys-locale = "0.3" +whatlang = "0.18.0" +getrandom = "0.3" +# Today's date for a new game. +chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +# Warnings of the window and graphics libraries into chesspenguin.log. +log = "0.4" +base64 = "0.22" +form_urlencoded = "1" + +# The desktop program: native dialogs, the clipboard, sound, the network (updates, +# engines and Maia on request, online games, translation). +[target.'cfg(not(target_family = "wasm"))'.dependencies] +rfd.workspace = true +arboard.workspace = true +rodio.workspace = true +releases.workspace = true +# Downloading the official Stockfish on request (decision 14). +ureq = "3.4" +flate2 = "1.1" +tar = "0.4" + +# The web version: the page, its files and storage (apps/web starts it). +[target.'cfg(target_family = "wasm")'.dependencies] +# The reader worker gives the page a database's index (platform::web::import). +chess-core = { workspace = true, features = ["serde"] } +getrandom = { version = "0.3", features = ["wasm_js"] } +# The browser's languages for the first start. +sys-locale = { version = "0.3", features = ["js"] } +# Today's date from the browser's clock. +chrono = { version = "0.4", default-features = false, features = ["clock", "std", "wasmbind"] } +wasm-bindgen = "0.2.129" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" +web-sys = { version = "0.3", features = [ + "Window", "Document", "Element", "HtmlElement", "HtmlInputElement", "HtmlAnchorElement", + "File", "FileList", "Blob", "BlobPropertyBag", "Url", "Event", "Location", "Navigator", + "Storage", "UrlSearchParams", "EventTarget", "CssStyleDeclaration", "Clipboard", + "IdbFactory", "IdbDatabase", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", + "IdbTransactionMode", "IdbObjectStore", "DomStringList", "HtmlAudioElement", + "HtmlMediaElement", "HtmlCanvasElement", "console", "CacheStorage", "Cache", + "Request", "Response", "ResponseInit", "Headers", "ReadableStream", + "ReadableStreamDefaultReader", "StorageManager", "StorageEstimate", "History", + "BeforeUnloadEvent", "WorkerOptions", "WorkerType", +] } + +[build-dependencies] +winresource = "0.1" + +[dev-dependencies] +skrifa = "0.44" diff --git a/apps/desktop/assets/boards/blue-marble.jpg b/apps/desktop/assets/boards/blue-marble.jpg new file mode 100644 index 0000000..0a2a5d6 Binary files /dev/null and b/apps/desktop/assets/boards/blue-marble.jpg differ diff --git a/apps/desktop/assets/boards/blue2.jpg b/apps/desktop/assets/boards/blue2.jpg new file mode 100644 index 0000000..e222f3b Binary files /dev/null and b/apps/desktop/assets/boards/blue2.jpg differ diff --git a/apps/desktop/assets/boards/blue3.jpg b/apps/desktop/assets/boards/blue3.jpg new file mode 100644 index 0000000..1f1f84e Binary files /dev/null and b/apps/desktop/assets/boards/blue3.jpg differ diff --git a/apps/desktop/assets/boards/canvas2.jpg b/apps/desktop/assets/boards/canvas2.jpg new file mode 100644 index 0000000..79c54ca Binary files /dev/null and b/apps/desktop/assets/boards/canvas2.jpg differ diff --git a/apps/desktop/assets/boards/green-plastic.png b/apps/desktop/assets/boards/green-plastic.png new file mode 100644 index 0000000..4b9b128 Binary files /dev/null and b/apps/desktop/assets/boards/green-plastic.png differ diff --git a/apps/desktop/assets/boards/grey.jpg b/apps/desktop/assets/boards/grey.jpg new file mode 100644 index 0000000..8a71cf6 Binary files /dev/null and b/apps/desktop/assets/boards/grey.jpg differ diff --git a/apps/desktop/assets/boards/horsey.jpg b/apps/desktop/assets/boards/horsey.jpg new file mode 100644 index 0000000..1cf2628 Binary files /dev/null and b/apps/desktop/assets/boards/horsey.jpg differ diff --git a/apps/desktop/assets/boards/leather.jpg b/apps/desktop/assets/boards/leather.jpg new file mode 100644 index 0000000..0d7a93f Binary files /dev/null and b/apps/desktop/assets/boards/leather.jpg differ diff --git a/apps/desktop/assets/boards/maple.jpg b/apps/desktop/assets/boards/maple.jpg new file mode 100644 index 0000000..3f4bdc2 Binary files /dev/null and b/apps/desktop/assets/boards/maple.jpg differ diff --git a/apps/desktop/assets/boards/maple2.jpg b/apps/desktop/assets/boards/maple2.jpg new file mode 100644 index 0000000..237def2 Binary files /dev/null and b/apps/desktop/assets/boards/maple2.jpg differ diff --git a/apps/desktop/assets/boards/marble.jpg b/apps/desktop/assets/boards/marble.jpg new file mode 100644 index 0000000..3f0b94e Binary files /dev/null and b/apps/desktop/assets/boards/marble.jpg differ diff --git a/apps/desktop/assets/boards/metal.jpg b/apps/desktop/assets/boards/metal.jpg new file mode 100644 index 0000000..91de155 Binary files /dev/null and b/apps/desktop/assets/boards/metal.jpg differ diff --git a/apps/desktop/assets/boards/olive.jpg b/apps/desktop/assets/boards/olive.jpg new file mode 100644 index 0000000..5c17c41 Binary files /dev/null and b/apps/desktop/assets/boards/olive.jpg differ diff --git a/apps/desktop/assets/boards/pink-pyramid.png b/apps/desktop/assets/boards/pink-pyramid.png new file mode 100644 index 0000000..a8ae1b2 Binary files /dev/null and b/apps/desktop/assets/boards/pink-pyramid.png differ diff --git a/apps/desktop/assets/boards/purple-diag.png b/apps/desktop/assets/boards/purple-diag.png new file mode 100644 index 0000000..aa64b86 Binary files /dev/null and b/apps/desktop/assets/boards/purple-diag.png differ diff --git a/apps/desktop/assets/boards/wood.jpg b/apps/desktop/assets/boards/wood.jpg new file mode 100644 index 0000000..cc4d3cb Binary files /dev/null and b/apps/desktop/assets/boards/wood.jpg differ diff --git a/apps/desktop/assets/boards/wood2.jpg b/apps/desktop/assets/boards/wood2.jpg new file mode 100644 index 0000000..90d47d9 Binary files /dev/null and b/apps/desktop/assets/boards/wood2.jpg differ diff --git a/apps/desktop/assets/boards/wood3.jpg b/apps/desktop/assets/boards/wood3.jpg new file mode 100644 index 0000000..ac620cb Binary files /dev/null and b/apps/desktop/assets/boards/wood3.jpg differ diff --git a/apps/desktop/assets/boards/wood4.jpg b/apps/desktop/assets/boards/wood4.jpg new file mode 100644 index 0000000..25ae7c9 Binary files /dev/null and b/apps/desktop/assets/boards/wood4.jpg differ diff --git a/apps/desktop/assets/fonts/NotoSansMath-nag.ttf b/apps/desktop/assets/fonts/NotoSansMath-nag.ttf new file mode 100644 index 0000000..3134da8 Binary files /dev/null and b/apps/desktop/assets/fonts/NotoSansMath-nag.ttf differ diff --git a/apps/desktop/assets/fonts/OFL.txt b/apps/desktop/assets/fonts/OFL.txt new file mode 100644 index 0000000..45f71ff --- /dev/null +++ b/apps/desktop/assets/fonts/OFL.txt @@ -0,0 +1,95 @@ +NotoSansMath-nag.ttf: Noto Sans Math (https://github.com/notofonts/math), Copyright 2022 Google LLC, +cut down by ChessPenguin to three glyphs (U+2313, U+2A71, U+2A72) used for move evaluations. + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"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. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. 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. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license 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. diff --git a/apps/desktop/assets/fonts/UFL.txt b/apps/desktop/assets/fonts/UFL.txt new file mode 100644 index 0000000..ae78a8f --- /dev/null +++ b/apps/desktop/assets/fonts/UFL.txt @@ -0,0 +1,96 @@ +------------------------------- +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. diff --git a/apps/desktop/assets/fonts/Ubuntu-B.ttf b/apps/desktop/assets/fonts/Ubuntu-B.ttf new file mode 100644 index 0000000..b173da2 Binary files /dev/null and b/apps/desktop/assets/fonts/Ubuntu-B.ttf differ diff --git a/apps/desktop/assets/fonts/figurines.ttf b/apps/desktop/assets/fonts/figurines.ttf new file mode 100644 index 0000000..dbc3e1b Binary files /dev/null and b/apps/desktop/assets/fonts/figurines.ttf differ diff --git a/apps/desktop/assets/icon-256.png b/apps/desktop/assets/icon-256.png new file mode 100644 index 0000000..ee11d19 Binary files /dev/null and b/apps/desktop/assets/icon-256.png differ diff --git a/apps/desktop/assets/pieces/cburnett/bB.svg b/apps/desktop/assets/pieces/cburnett/bB.svg new file mode 100644 index 0000000..51a8751 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/bK.svg b/apps/desktop/assets/pieces/cburnett/bK.svg new file mode 100644 index 0000000..543b910 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/bN.svg b/apps/desktop/assets/pieces/cburnett/bN.svg new file mode 100644 index 0000000..fc29188 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/bP.svg b/apps/desktop/assets/pieces/cburnett/bP.svg new file mode 100644 index 0000000..c97ccf5 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/bQ.svg b/apps/desktop/assets/pieces/cburnett/bQ.svg new file mode 100644 index 0000000..0bd3233 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/bR.svg b/apps/desktop/assets/pieces/cburnett/bR.svg new file mode 100644 index 0000000..1f87576 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/wB.svg b/apps/desktop/assets/pieces/cburnett/wB.svg new file mode 100644 index 0000000..8eee13f --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/wK.svg b/apps/desktop/assets/pieces/cburnett/wK.svg new file mode 100644 index 0000000..3370721 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/wN.svg b/apps/desktop/assets/pieces/cburnett/wN.svg new file mode 100644 index 0000000..afd1fc8 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/wP.svg b/apps/desktop/assets/pieces/cburnett/wP.svg new file mode 100644 index 0000000..c252c58 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/wQ.svg b/apps/desktop/assets/pieces/cburnett/wQ.svg new file mode 100644 index 0000000..c40c4e0 --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/cburnett/wR.svg b/apps/desktop/assets/pieces/cburnett/wR.svg new file mode 100644 index 0000000..8564f6b --- /dev/null +++ b/apps/desktop/assets/pieces/cburnett/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/bB.svg b/apps/desktop/assets/pieces/celtic/bB.svg new file mode 100644 index 0000000..88ed220 --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/bK.svg b/apps/desktop/assets/pieces/celtic/bK.svg new file mode 100644 index 0000000..3f4e72b --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/bN.svg b/apps/desktop/assets/pieces/celtic/bN.svg new file mode 100644 index 0000000..a85ad9d --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/bP.svg b/apps/desktop/assets/pieces/celtic/bP.svg new file mode 100644 index 0000000..d61bc99 --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/bQ.svg b/apps/desktop/assets/pieces/celtic/bQ.svg new file mode 100644 index 0000000..b0e2cf2 --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/bR.svg b/apps/desktop/assets/pieces/celtic/bR.svg new file mode 100644 index 0000000..8ac7363 --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/wB.svg b/apps/desktop/assets/pieces/celtic/wB.svg new file mode 100644 index 0000000..180d98f --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/wK.svg b/apps/desktop/assets/pieces/celtic/wK.svg new file mode 100644 index 0000000..caeb6b3 --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/wN.svg b/apps/desktop/assets/pieces/celtic/wN.svg new file mode 100644 index 0000000..52ab49f --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/wP.svg b/apps/desktop/assets/pieces/celtic/wP.svg new file mode 100644 index 0000000..0e6ac4d --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/wQ.svg b/apps/desktop/assets/pieces/celtic/wQ.svg new file mode 100644 index 0000000..40be4db --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/celtic/wR.svg b/apps/desktop/assets/pieces/celtic/wR.svg new file mode 100644 index 0000000..56f2664 --- /dev/null +++ b/apps/desktop/assets/pieces/celtic/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/bB.svg b/apps/desktop/assets/pieces/chessnut/bB.svg new file mode 100644 index 0000000..8944055 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/bK.svg b/apps/desktop/assets/pieces/chessnut/bK.svg new file mode 100644 index 0000000..a231ff2 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/bN.svg b/apps/desktop/assets/pieces/chessnut/bN.svg new file mode 100644 index 0000000..39126a2 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/bP.svg b/apps/desktop/assets/pieces/chessnut/bP.svg new file mode 100644 index 0000000..337915d --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/bQ.svg b/apps/desktop/assets/pieces/chessnut/bQ.svg new file mode 100644 index 0000000..89b1902 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/bR.svg b/apps/desktop/assets/pieces/chessnut/bR.svg new file mode 100644 index 0000000..3b3d47d --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/wB.svg b/apps/desktop/assets/pieces/chessnut/wB.svg new file mode 100644 index 0000000..7a2fb6c --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/wK.svg b/apps/desktop/assets/pieces/chessnut/wK.svg new file mode 100644 index 0000000..de4bc29 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/wN.svg b/apps/desktop/assets/pieces/chessnut/wN.svg new file mode 100644 index 0000000..7ccaeda --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/wP.svg b/apps/desktop/assets/pieces/chessnut/wP.svg new file mode 100644 index 0000000..e27c1b9 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/wQ.svg b/apps/desktop/assets/pieces/chessnut/wQ.svg new file mode 100644 index 0000000..f748b85 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/chessnut/wR.svg b/apps/desktop/assets/pieces/chessnut/wR.svg new file mode 100644 index 0000000..6648406 --- /dev/null +++ b/apps/desktop/assets/pieces/chessnut/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/bB.svg b/apps/desktop/assets/pieces/fantasy/bB.svg new file mode 100644 index 0000000..bc68ec8 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/bK.svg b/apps/desktop/assets/pieces/fantasy/bK.svg new file mode 100644 index 0000000..52e411f --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/bN.svg b/apps/desktop/assets/pieces/fantasy/bN.svg new file mode 100644 index 0000000..caaba40 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/bP.svg b/apps/desktop/assets/pieces/fantasy/bP.svg new file mode 100644 index 0000000..67d5c9e --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/bQ.svg b/apps/desktop/assets/pieces/fantasy/bQ.svg new file mode 100644 index 0000000..246be11 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/bR.svg b/apps/desktop/assets/pieces/fantasy/bR.svg new file mode 100644 index 0000000..ca02a6a --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/wB.svg b/apps/desktop/assets/pieces/fantasy/wB.svg new file mode 100644 index 0000000..4ca47c9 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/wK.svg b/apps/desktop/assets/pieces/fantasy/wK.svg new file mode 100644 index 0000000..7ad06f2 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/wN.svg b/apps/desktop/assets/pieces/fantasy/wN.svg new file mode 100644 index 0000000..beaff33 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/wP.svg b/apps/desktop/assets/pieces/fantasy/wP.svg new file mode 100644 index 0000000..7aba494 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/wQ.svg b/apps/desktop/assets/pieces/fantasy/wQ.svg new file mode 100644 index 0000000..e46811e --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/fantasy/wR.svg b/apps/desktop/assets/pieces/fantasy/wR.svg new file mode 100644 index 0000000..2bc9da8 --- /dev/null +++ b/apps/desktop/assets/pieces/fantasy/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/bB.svg b/apps/desktop/assets/pieces/firi/bB.svg new file mode 100644 index 0000000..a31832e --- /dev/null +++ b/apps/desktop/assets/pieces/firi/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/bK.svg b/apps/desktop/assets/pieces/firi/bK.svg new file mode 100644 index 0000000..7c8282c --- /dev/null +++ b/apps/desktop/assets/pieces/firi/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/bN.svg b/apps/desktop/assets/pieces/firi/bN.svg new file mode 100644 index 0000000..176bbfb --- /dev/null +++ b/apps/desktop/assets/pieces/firi/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/bP.svg b/apps/desktop/assets/pieces/firi/bP.svg new file mode 100644 index 0000000..32e26c4 --- /dev/null +++ b/apps/desktop/assets/pieces/firi/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/bQ.svg b/apps/desktop/assets/pieces/firi/bQ.svg new file mode 100644 index 0000000..69d4796 --- /dev/null +++ b/apps/desktop/assets/pieces/firi/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/bR.svg b/apps/desktop/assets/pieces/firi/bR.svg new file mode 100644 index 0000000..5e90d6a --- /dev/null +++ b/apps/desktop/assets/pieces/firi/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/wB.svg b/apps/desktop/assets/pieces/firi/wB.svg new file mode 100644 index 0000000..06c49ca --- /dev/null +++ b/apps/desktop/assets/pieces/firi/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/wK.svg b/apps/desktop/assets/pieces/firi/wK.svg new file mode 100644 index 0000000..c76ac00 --- /dev/null +++ b/apps/desktop/assets/pieces/firi/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/wN.svg b/apps/desktop/assets/pieces/firi/wN.svg new file mode 100644 index 0000000..a5aa974 --- /dev/null +++ b/apps/desktop/assets/pieces/firi/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/wP.svg b/apps/desktop/assets/pieces/firi/wP.svg new file mode 100644 index 0000000..1dfe5b3 --- /dev/null +++ b/apps/desktop/assets/pieces/firi/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/wQ.svg b/apps/desktop/assets/pieces/firi/wQ.svg new file mode 100644 index 0000000..a3f9bee --- /dev/null +++ b/apps/desktop/assets/pieces/firi/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/firi/wR.svg b/apps/desktop/assets/pieces/firi/wR.svg new file mode 100644 index 0000000..cf59d4b --- /dev/null +++ b/apps/desktop/assets/pieces/firi/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/governor/bB.svg b/apps/desktop/assets/pieces/governor/bB.svg new file mode 100644 index 0000000..7bd379e --- /dev/null +++ b/apps/desktop/assets/pieces/governor/bB.svg @@ -0,0 +1,37 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/bK.svg b/apps/desktop/assets/pieces/governor/bK.svg new file mode 100644 index 0000000..c28fb3e --- /dev/null +++ b/apps/desktop/assets/pieces/governor/bK.svg @@ -0,0 +1,48 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/bN.svg b/apps/desktop/assets/pieces/governor/bN.svg new file mode 100644 index 0000000..ad50387 --- /dev/null +++ b/apps/desktop/assets/pieces/governor/bN.svg @@ -0,0 +1,45 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/bP.svg b/apps/desktop/assets/pieces/governor/bP.svg new file mode 100644 index 0000000..e92b619 --- /dev/null +++ b/apps/desktop/assets/pieces/governor/bP.svg @@ -0,0 +1,37 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/bQ.svg b/apps/desktop/assets/pieces/governor/bQ.svg new file mode 100644 index 0000000..775e2d9 --- /dev/null +++ b/apps/desktop/assets/pieces/governor/bQ.svg @@ -0,0 +1,76 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/bR.svg b/apps/desktop/assets/pieces/governor/bR.svg new file mode 100644 index 0000000..420b7aa --- /dev/null +++ b/apps/desktop/assets/pieces/governor/bR.svg @@ -0,0 +1,45 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/wB.svg b/apps/desktop/assets/pieces/governor/wB.svg new file mode 100644 index 0000000..251731f --- /dev/null +++ b/apps/desktop/assets/pieces/governor/wB.svg @@ -0,0 +1,37 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/wK.svg b/apps/desktop/assets/pieces/governor/wK.svg new file mode 100644 index 0000000..0d690d7 --- /dev/null +++ b/apps/desktop/assets/pieces/governor/wK.svg @@ -0,0 +1,48 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/wN.svg b/apps/desktop/assets/pieces/governor/wN.svg new file mode 100644 index 0000000..5bf6b14 --- /dev/null +++ b/apps/desktop/assets/pieces/governor/wN.svg @@ -0,0 +1,45 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/wP.svg b/apps/desktop/assets/pieces/governor/wP.svg new file mode 100644 index 0000000..9d8e403 --- /dev/null +++ b/apps/desktop/assets/pieces/governor/wP.svg @@ -0,0 +1,37 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/wQ.svg b/apps/desktop/assets/pieces/governor/wQ.svg new file mode 100644 index 0000000..0f0d2be --- /dev/null +++ b/apps/desktop/assets/pieces/governor/wQ.svg @@ -0,0 +1,76 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/governor/wR.svg b/apps/desktop/assets/pieces/governor/wR.svg new file mode 100644 index 0000000..bb0aec1 --- /dev/null +++ b/apps/desktop/assets/pieces/governor/wR.svg @@ -0,0 +1,43 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kiwen-suwi/bB.svg b/apps/desktop/assets/pieces/kiwen-suwi/bB.svg new file mode 100644 index 0000000..5be8e7b --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/bK.svg b/apps/desktop/assets/pieces/kiwen-suwi/bK.svg new file mode 100644 index 0000000..02e141b --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/bN.svg b/apps/desktop/assets/pieces/kiwen-suwi/bN.svg new file mode 100644 index 0000000..dbdc5e4 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/bP.svg b/apps/desktop/assets/pieces/kiwen-suwi/bP.svg new file mode 100644 index 0000000..2fefd97 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/bQ.svg b/apps/desktop/assets/pieces/kiwen-suwi/bQ.svg new file mode 100644 index 0000000..460f485 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/bR.svg b/apps/desktop/assets/pieces/kiwen-suwi/bR.svg new file mode 100644 index 0000000..c113173 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/wB.svg b/apps/desktop/assets/pieces/kiwen-suwi/wB.svg new file mode 100644 index 0000000..c9d2b98 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/wK.svg b/apps/desktop/assets/pieces/kiwen-suwi/wK.svg new file mode 100644 index 0000000..b16fad9 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/wN.svg b/apps/desktop/assets/pieces/kiwen-suwi/wN.svg new file mode 100644 index 0000000..4e6e620 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/wP.svg b/apps/desktop/assets/pieces/kiwen-suwi/wP.svg new file mode 100644 index 0000000..a30c4dc --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/wQ.svg b/apps/desktop/assets/pieces/kiwen-suwi/wQ.svg new file mode 100644 index 0000000..9182d4c --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kiwen-suwi/wR.svg b/apps/desktop/assets/pieces/kiwen-suwi/wR.svg new file mode 100644 index 0000000..8e031c9 --- /dev/null +++ b/apps/desktop/assets/pieces/kiwen-suwi/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/kosal/bB.svg b/apps/desktop/assets/pieces/kosal/bB.svg new file mode 100644 index 0000000..b5d981c --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/bB.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/bK.svg b/apps/desktop/assets/pieces/kosal/bK.svg new file mode 100644 index 0000000..0b00e31 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/bK.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/bN.svg b/apps/desktop/assets/pieces/kosal/bN.svg new file mode 100644 index 0000000..8cfa600 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/bN.svg @@ -0,0 +1,18 @@ + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/bP.svg b/apps/desktop/assets/pieces/kosal/bP.svg new file mode 100644 index 0000000..2c14967 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/bP.svg @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/bQ.svg b/apps/desktop/assets/pieces/kosal/bQ.svg new file mode 100644 index 0000000..a47be38 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/bQ.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/bR.svg b/apps/desktop/assets/pieces/kosal/bR.svg new file mode 100644 index 0000000..345757b --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/bR.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/wB.svg b/apps/desktop/assets/pieces/kosal/wB.svg new file mode 100644 index 0000000..2a2ae31 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/wB.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/wK.svg b/apps/desktop/assets/pieces/kosal/wK.svg new file mode 100644 index 0000000..bb1ab6a --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/wK.svg @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/wN.svg b/apps/desktop/assets/pieces/kosal/wN.svg new file mode 100644 index 0000000..3130db7 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/wN.svg @@ -0,0 +1,22 @@ + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/wP.svg b/apps/desktop/assets/pieces/kosal/wP.svg new file mode 100644 index 0000000..bb2d341 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/wP.svg @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/wQ.svg b/apps/desktop/assets/pieces/kosal/wQ.svg new file mode 100644 index 0000000..edb9048 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/wQ.svg @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/kosal/wR.svg b/apps/desktop/assets/pieces/kosal/wR.svg new file mode 100644 index 0000000..8a4e8a1 --- /dev/null +++ b/apps/desktop/assets/pieces/kosal/wR.svg @@ -0,0 +1,17 @@ + + + + + + + + diff --git a/apps/desktop/assets/pieces/letter/bB.svg b/apps/desktop/assets/pieces/letter/bB.svg new file mode 100644 index 0000000..7652c83 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/bK.svg b/apps/desktop/assets/pieces/letter/bK.svg new file mode 100644 index 0000000..8e32e27 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/bN.svg b/apps/desktop/assets/pieces/letter/bN.svg new file mode 100644 index 0000000..4b3b74d --- /dev/null +++ b/apps/desktop/assets/pieces/letter/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/bP.svg b/apps/desktop/assets/pieces/letter/bP.svg new file mode 100644 index 0000000..7eb5075 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/bQ.svg b/apps/desktop/assets/pieces/letter/bQ.svg new file mode 100644 index 0000000..7b81ab3 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/bR.svg b/apps/desktop/assets/pieces/letter/bR.svg new file mode 100644 index 0000000..a82ccad --- /dev/null +++ b/apps/desktop/assets/pieces/letter/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/wB.svg b/apps/desktop/assets/pieces/letter/wB.svg new file mode 100644 index 0000000..a8fdc33 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/wK.svg b/apps/desktop/assets/pieces/letter/wK.svg new file mode 100644 index 0000000..10667a7 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/wN.svg b/apps/desktop/assets/pieces/letter/wN.svg new file mode 100644 index 0000000..d0f4c2b --- /dev/null +++ b/apps/desktop/assets/pieces/letter/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/wP.svg b/apps/desktop/assets/pieces/letter/wP.svg new file mode 100644 index 0000000..3635996 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/wQ.svg b/apps/desktop/assets/pieces/letter/wQ.svg new file mode 100644 index 0000000..e3a68d7 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/letter/wR.svg b/apps/desktop/assets/pieces/letter/wR.svg new file mode 100644 index 0000000..9bba535 --- /dev/null +++ b/apps/desktop/assets/pieces/letter/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/bB.svg b/apps/desktop/assets/pieces/merida/bB.svg new file mode 100644 index 0000000..1709847 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/bK.svg b/apps/desktop/assets/pieces/merida/bK.svg new file mode 100644 index 0000000..beaa21b --- /dev/null +++ b/apps/desktop/assets/pieces/merida/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/bN.svg b/apps/desktop/assets/pieces/merida/bN.svg new file mode 100644 index 0000000..c5ff441 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/bP.svg b/apps/desktop/assets/pieces/merida/bP.svg new file mode 100644 index 0000000..2bcb5c1 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/bQ.svg b/apps/desktop/assets/pieces/merida/bQ.svg new file mode 100644 index 0000000..9754451 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/bR.svg b/apps/desktop/assets/pieces/merida/bR.svg new file mode 100644 index 0000000..a9be8b0 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/wB.svg b/apps/desktop/assets/pieces/merida/wB.svg new file mode 100644 index 0000000..951b795 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/wK.svg b/apps/desktop/assets/pieces/merida/wK.svg new file mode 100644 index 0000000..5ea308f --- /dev/null +++ b/apps/desktop/assets/pieces/merida/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/wN.svg b/apps/desktop/assets/pieces/merida/wN.svg new file mode 100644 index 0000000..a3fd414 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/wP.svg b/apps/desktop/assets/pieces/merida/wP.svg new file mode 100644 index 0000000..b255c0e --- /dev/null +++ b/apps/desktop/assets/pieces/merida/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/wQ.svg b/apps/desktop/assets/pieces/merida/wQ.svg new file mode 100644 index 0000000..cba7551 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/merida/wR.svg b/apps/desktop/assets/pieces/merida/wR.svg new file mode 100644 index 0000000..de003a7 --- /dev/null +++ b/apps/desktop/assets/pieces/merida/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/metaltops/bB.svg b/apps/desktop/assets/pieces/metaltops/bB.svg new file mode 100644 index 0000000..cae9b0b --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/bB.svg @@ -0,0 +1,1888 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/bK.svg b/apps/desktop/assets/pieces/metaltops/bK.svg new file mode 100644 index 0000000..fc8d29f --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/bK.svg @@ -0,0 +1,2680 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/bN.svg b/apps/desktop/assets/pieces/metaltops/bN.svg new file mode 100644 index 0000000..01a630b --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/bN.svg @@ -0,0 +1,1953 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/bP.svg b/apps/desktop/assets/pieces/metaltops/bP.svg new file mode 100644 index 0000000..9cbfc2d --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/bP.svg @@ -0,0 +1,1889 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/bQ.svg b/apps/desktop/assets/pieces/metaltops/bQ.svg new file mode 100644 index 0000000..b76d945 --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/bQ.svg @@ -0,0 +1,2792 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/bR.svg b/apps/desktop/assets/pieces/metaltops/bR.svg new file mode 100644 index 0000000..7c8917f --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/bR.svg @@ -0,0 +1,1948 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/wB.svg b/apps/desktop/assets/pieces/metaltops/wB.svg new file mode 100644 index 0000000..e66ff1c --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/wB.svg @@ -0,0 +1,1915 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/wK.svg b/apps/desktop/assets/pieces/metaltops/wK.svg new file mode 100644 index 0000000..4c2228c --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/wK.svg @@ -0,0 +1,2768 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/wN.svg b/apps/desktop/assets/pieces/metaltops/wN.svg new file mode 100644 index 0000000..80c18fe --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/wN.svg @@ -0,0 +1,2001 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/wP.svg b/apps/desktop/assets/pieces/metaltops/wP.svg new file mode 100644 index 0000000..f1499ea --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/wP.svg @@ -0,0 +1,1937 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/wQ.svg b/apps/desktop/assets/pieces/metaltops/wQ.svg new file mode 100644 index 0000000..2d7ea86 --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/wQ.svg @@ -0,0 +1,2840 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/metaltops/wR.svg b/apps/desktop/assets/pieces/metaltops/wR.svg new file mode 100644 index 0000000..0a5c98f --- /dev/null +++ b/apps/desktop/assets/pieces/metaltops/wR.svg @@ -0,0 +1,1984 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/desktop/assets/pieces/mpchess/bB.svg b/apps/desktop/assets/pieces/mpchess/bB.svg new file mode 100644 index 0000000..0d8646f --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/bK.svg b/apps/desktop/assets/pieces/mpchess/bK.svg new file mode 100644 index 0000000..999895e --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/bN.svg b/apps/desktop/assets/pieces/mpchess/bN.svg new file mode 100644 index 0000000..9a2cbb9 --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/bP.svg b/apps/desktop/assets/pieces/mpchess/bP.svg new file mode 100644 index 0000000..6e4cd7e --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/bQ.svg b/apps/desktop/assets/pieces/mpchess/bQ.svg new file mode 100644 index 0000000..7fa7a32 --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/bR.svg b/apps/desktop/assets/pieces/mpchess/bR.svg new file mode 100644 index 0000000..05d27f2 --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/wB.svg b/apps/desktop/assets/pieces/mpchess/wB.svg new file mode 100644 index 0000000..d7ce3bc --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/wK.svg b/apps/desktop/assets/pieces/mpchess/wK.svg new file mode 100644 index 0000000..319681a --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/wN.svg b/apps/desktop/assets/pieces/mpchess/wN.svg new file mode 100644 index 0000000..e298c39 --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/wP.svg b/apps/desktop/assets/pieces/mpchess/wP.svg new file mode 100644 index 0000000..5680b34 --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/wQ.svg b/apps/desktop/assets/pieces/mpchess/wQ.svg new file mode 100644 index 0000000..6915012 --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/mpchess/wR.svg b/apps/desktop/assets/pieces/mpchess/wR.svg new file mode 100644 index 0000000..c97e286 --- /dev/null +++ b/apps/desktop/assets/pieces/mpchess/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/bB.svg b/apps/desktop/assets/pieces/pirouetti/bB.svg new file mode 100644 index 0000000..5677a27 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/bK.svg b/apps/desktop/assets/pieces/pirouetti/bK.svg new file mode 100644 index 0000000..c2cd2d8 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/bN.svg b/apps/desktop/assets/pieces/pirouetti/bN.svg new file mode 100644 index 0000000..4edc792 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/bP.svg b/apps/desktop/assets/pieces/pirouetti/bP.svg new file mode 100644 index 0000000..0a79dcc --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/bQ.svg b/apps/desktop/assets/pieces/pirouetti/bQ.svg new file mode 100644 index 0000000..2ee75b3 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/bR.svg b/apps/desktop/assets/pieces/pirouetti/bR.svg new file mode 100644 index 0000000..4425bd8 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/wB.svg b/apps/desktop/assets/pieces/pirouetti/wB.svg new file mode 100644 index 0000000..eb37820 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/wK.svg b/apps/desktop/assets/pieces/pirouetti/wK.svg new file mode 100644 index 0000000..8ed4c8d --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/wN.svg b/apps/desktop/assets/pieces/pirouetti/wN.svg new file mode 100644 index 0000000..036addd --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/wP.svg b/apps/desktop/assets/pieces/pirouetti/wP.svg new file mode 100644 index 0000000..fd5a557 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/wQ.svg b/apps/desktop/assets/pieces/pirouetti/wQ.svg new file mode 100644 index 0000000..819c548 --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pirouetti/wR.svg b/apps/desktop/assets/pieces/pirouetti/wR.svg new file mode 100644 index 0000000..c1d4eab --- /dev/null +++ b/apps/desktop/assets/pieces/pirouetti/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/bB.svg b/apps/desktop/assets/pieces/pixel/bB.svg new file mode 100644 index 0000000..b339ce2 --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/bK.svg b/apps/desktop/assets/pieces/pixel/bK.svg new file mode 100644 index 0000000..9b36598 --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/bN.svg b/apps/desktop/assets/pieces/pixel/bN.svg new file mode 100644 index 0000000..898aa2e --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/bP.svg b/apps/desktop/assets/pieces/pixel/bP.svg new file mode 100644 index 0000000..88cc70d --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/bQ.svg b/apps/desktop/assets/pieces/pixel/bQ.svg new file mode 100644 index 0000000..f998eda --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/bR.svg b/apps/desktop/assets/pieces/pixel/bR.svg new file mode 100644 index 0000000..84977dd --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/wB.svg b/apps/desktop/assets/pieces/pixel/wB.svg new file mode 100644 index 0000000..2f7ef78 --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/wK.svg b/apps/desktop/assets/pieces/pixel/wK.svg new file mode 100644 index 0000000..274a8ed --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/wN.svg b/apps/desktop/assets/pieces/pixel/wN.svg new file mode 100644 index 0000000..7923ce5 --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/wP.svg b/apps/desktop/assets/pieces/pixel/wP.svg new file mode 100644 index 0000000..51ec38e --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/wQ.svg b/apps/desktop/assets/pieces/pixel/wQ.svg new file mode 100644 index 0000000..d4c7ff3 --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/pixel/wR.svg b/apps/desktop/assets/pieces/pixel/wR.svg new file mode 100644 index 0000000..cdcee6f --- /dev/null +++ b/apps/desktop/assets/pieces/pixel/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/bB.svg b/apps/desktop/assets/pieces/rhosgfx/bB.svg new file mode 100644 index 0000000..b2aeb13 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/bK.svg b/apps/desktop/assets/pieces/rhosgfx/bK.svg new file mode 100644 index 0000000..a726621 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/bN.svg b/apps/desktop/assets/pieces/rhosgfx/bN.svg new file mode 100644 index 0000000..0bf9be8 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/bP.svg b/apps/desktop/assets/pieces/rhosgfx/bP.svg new file mode 100644 index 0000000..e97fce6 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/bQ.svg b/apps/desktop/assets/pieces/rhosgfx/bQ.svg new file mode 100644 index 0000000..cb352ff --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/bR.svg b/apps/desktop/assets/pieces/rhosgfx/bR.svg new file mode 100644 index 0000000..5ce91a9 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/wB.svg b/apps/desktop/assets/pieces/rhosgfx/wB.svg new file mode 100644 index 0000000..16fc2ea --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/wK.svg b/apps/desktop/assets/pieces/rhosgfx/wK.svg new file mode 100644 index 0000000..a21a5eb --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/wN.svg b/apps/desktop/assets/pieces/rhosgfx/wN.svg new file mode 100644 index 0000000..9650e74 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/wP.svg b/apps/desktop/assets/pieces/rhosgfx/wP.svg new file mode 100644 index 0000000..ceb32e2 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/wQ.svg b/apps/desktop/assets/pieces/rhosgfx/wQ.svg new file mode 100644 index 0000000..c0af0ab --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/rhosgfx/wR.svg b/apps/desktop/assets/pieces/rhosgfx/wR.svg new file mode 100644 index 0000000..ba3d4e3 --- /dev/null +++ b/apps/desktop/assets/pieces/rhosgfx/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/bB.svg b/apps/desktop/assets/pieces/shapes/bB.svg new file mode 100644 index 0000000..1ef308a --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/bK.svg b/apps/desktop/assets/pieces/shapes/bK.svg new file mode 100644 index 0000000..cb4906c --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/bN.svg b/apps/desktop/assets/pieces/shapes/bN.svg new file mode 100644 index 0000000..7128572 --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/bP.svg b/apps/desktop/assets/pieces/shapes/bP.svg new file mode 100644 index 0000000..456c846 --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/bQ.svg b/apps/desktop/assets/pieces/shapes/bQ.svg new file mode 100644 index 0000000..741a4be --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/bR.svg b/apps/desktop/assets/pieces/shapes/bR.svg new file mode 100644 index 0000000..afd3269 --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/wB.svg b/apps/desktop/assets/pieces/shapes/wB.svg new file mode 100644 index 0000000..c69ff1a --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/wK.svg b/apps/desktop/assets/pieces/shapes/wK.svg new file mode 100644 index 0000000..f3239bd --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/wN.svg b/apps/desktop/assets/pieces/shapes/wN.svg new file mode 100644 index 0000000..41220c4 --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/wP.svg b/apps/desktop/assets/pieces/shapes/wP.svg new file mode 100644 index 0000000..4efa812 --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/wQ.svg b/apps/desktop/assets/pieces/shapes/wQ.svg new file mode 100644 index 0000000..9f7ea7f --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/shapes/wR.svg b/apps/desktop/assets/pieces/shapes/wR.svg new file mode 100644 index 0000000..c5d60af --- /dev/null +++ b/apps/desktop/assets/pieces/shapes/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/bB.svg b/apps/desktop/assets/pieces/spatial/bB.svg new file mode 100644 index 0000000..b5734c8 --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/bK.svg b/apps/desktop/assets/pieces/spatial/bK.svg new file mode 100644 index 0000000..ddf037c --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/bN.svg b/apps/desktop/assets/pieces/spatial/bN.svg new file mode 100644 index 0000000..94928ee --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/bP.svg b/apps/desktop/assets/pieces/spatial/bP.svg new file mode 100644 index 0000000..87be083 --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/bQ.svg b/apps/desktop/assets/pieces/spatial/bQ.svg new file mode 100644 index 0000000..a15d269 --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/bR.svg b/apps/desktop/assets/pieces/spatial/bR.svg new file mode 100644 index 0000000..271dbcd --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/wB.svg b/apps/desktop/assets/pieces/spatial/wB.svg new file mode 100644 index 0000000..20345f5 --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/wK.svg b/apps/desktop/assets/pieces/spatial/wK.svg new file mode 100644 index 0000000..ca198d7 --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/wN.svg b/apps/desktop/assets/pieces/spatial/wN.svg new file mode 100644 index 0000000..d641bcf --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/wP.svg b/apps/desktop/assets/pieces/spatial/wP.svg new file mode 100644 index 0000000..ea3cd6a --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/wQ.svg b/apps/desktop/assets/pieces/spatial/wQ.svg new file mode 100644 index 0000000..1a94749 --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/pieces/spatial/wR.svg b/apps/desktop/assets/pieces/spatial/wR.svg new file mode 100644 index 0000000..c5f86a4 --- /dev/null +++ b/apps/desktop/assets/pieces/spatial/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/assets/repertoires/queens-gambit-white.pgn b/apps/desktop/assets/repertoires/queens-gambit-white.pgn new file mode 100644 index 0000000..fa324df --- /dev/null +++ b/apps/desktop/assets/repertoires/queens-gambit-white.pgn @@ -0,0 +1,12 @@ +[Event "ChessPenguin: Queen's Gambit for White"] +[White "Repertoire"] +[Black "?"] +[Result "*"] +[ECO "D37"] + +{Queen's Gambit for White: the Queen's Gambit Declined with 5.Bf4, plus answers to the Queen's Gambit Accepted and the Slav Defence.} +1. d4 d5 2. c4 {White offers a pawn to deflect Black's d-pawn from the centre.} +2... e6 (2... dxc4 {Queen's Gambit Accepted.} 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 8. Qxd8+ Kxd8 {White keeps a small, risk-free edge in the endgame.}) +(2... c6 {Slav Defence.} 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O {White has a central space advantage and easy development.}) +3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 {The modern main line: the bishop is active and safe from ...h6 and ...Ne4.} +5... O-O 6. e3 c5 7. dxc5 Bxc5 8. a3 Nc6 9. Qc2 Qa5 10. Rd1 Re8 11. Nd2 {White plays against the isolated pawn that may appear after ...dxc4 or cxd5.} * diff --git a/apps/desktop/assets/repertoires/queens-gambit-white.ru.pgn b/apps/desktop/assets/repertoires/queens-gambit-white.ru.pgn new file mode 100644 index 0000000..61c219b --- /dev/null +++ b/apps/desktop/assets/repertoires/queens-gambit-white.ru.pgn @@ -0,0 +1,12 @@ +[Event "ChessPenguin: Ферзевый гамбит за белых"] +[White "Repertoire"] +[Black "?"] +[Result "*"] +[ECO "D37"] + +{Ферзевый гамбит за белых: отказанный ферзевый гамбит � 5.Bf4, а также ответы на прин�тый ферзевый гамбит и Слав�н�кую защиту.} +1. d4 d5 2. c4 {Белые предлагают пешку, чтобы отвлечь пешку d5 из центра.} +2... e6 (2... dxc4 {Прин�тый ферзевый гамбит.} 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 8. Qxd8+ Kxd8 {Белые �охран�ют небольшой безри�ковый переве� в �ндшпиле.}) +(2... c6 {Слав�н�ка� защита.} 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O {У белых переве� в про�тран�тве в центре и удобное развитие.}) +3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 {Современна� о�новна� �и�тема: �лон активен и не попадает под ...h6 и ...Ne4.} +5... O-O 6. e3 c5 7. dxc5 Bxc5 8. a3 Nc6 9. Qc2 Qa5 10. Rd1 Re8 11. Nd2 {Белые играют против изолированной пешки, котора� может возникнуть по�ле ...dxc4 или cxd5.} * diff --git a/apps/desktop/assets/repertoires/sicilian-black.pgn b/apps/desktop/assets/repertoires/sicilian-black.pgn new file mode 100644 index 0000000..a050f88 --- /dev/null +++ b/apps/desktop/assets/repertoires/sicilian-black.pgn @@ -0,0 +1,11 @@ +[Event "ChessPenguin: Sicilian Najdorf for Black"] +[White "?"] +[Black "Repertoire"] +[Result "*"] +[ECO "B90"] + +{Sicilian Defence, Najdorf Variation for Black, with answers to 6.Be3, 6.Bg5 and the Alapin 2.c3.} +1. e4 c5 2. Nf3 (2. c3 {Alapin Variation.} 2... Nf6 3. e5 Nd5 4. d4 cxd4 5. Nf3 Nc6 6. cxd4 d6 {Black attacks the e5 pawn at once.}) +2... d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 {The Najdorf: ...a6 controls b5 and prepares ...e5 or ...b5.} +6. Be3 (6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 {Black keeps the position solid and prepares ...b5.}) +6... e5 7. Nb3 Be6 8. f3 Be7 9. Qd2 O-O 10. O-O-O Nbd7 11. g4 b5 {English Attack: both sides race on opposite wings.} * diff --git a/apps/desktop/assets/repertoires/sicilian-black.ru.pgn b/apps/desktop/assets/repertoires/sicilian-black.ru.pgn new file mode 100644 index 0000000..42f4a82 --- /dev/null +++ b/apps/desktop/assets/repertoires/sicilian-black.ru.pgn @@ -0,0 +1,11 @@ +[Event "ChessPenguin: Сицилиан�ка� защита, вариант �айдорфа за чёрных"] +[White "?"] +[Black "Repertoire"] +[Result "*"] +[ECO "B90"] + +{Сицилиан�ка� защита, вариант �айдорфа за чёрных: ответы на 6.Be3, 6.Bg5 и вариант �лапина 2.c3.} +1. e4 c5 2. Nf3 (2. c3 {Вариант �лапина.} 2... Nf6 3. e5 Nd5 4. d4 cxd4 5. Nf3 Nc6 6. cxd4 d6 {Чёрные �разу атакуют пешку e5.}) +2... d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 {Вариант �айдорфа: ...a6 контролирует b5 и готовит ...e5 или ...b5.} +6. Be3 (6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 {Чёрные �охран�ют прочную позицию и готов�т ...b5.}) +6... e5 7. Nb3 Be6 8. f3 Be7 9. Qd2 O-O 10. O-O-O Nbd7 11. g4 b5 {�нглий�ка� атака: обе �тороны на�тупают на противоположных флангах.} * diff --git a/apps/desktop/assets/repertoires/spanish-white.pgn b/apps/desktop/assets/repertoires/spanish-white.pgn new file mode 100644 index 0000000..c1d8739 --- /dev/null +++ b/apps/desktop/assets/repertoires/spanish-white.pgn @@ -0,0 +1,13 @@ +[Event "ChessPenguin: Spanish Opening for White"] +[White "Repertoire"] +[Black "?"] +[Result "*"] +[ECO "C84"] + +{Spanish Opening (Ruy Lopez) for White: the Closed main line, the Marshall Attack and the Berlin Defence.} +1. e4 e5 2. Nf3 Nc6 3. Bb5 {The Spanish bishop pressures the knight that defends e5.} +3... a6 (3... Nf6 {Berlin Defence.} 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 +8. Qxd8+ Kxd8 {The Berlin endgame: White has the healthier pawn majority.}) +4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 (7... O-O 8. c3 d5 {Marshall Attack.} +9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 {White returns material later if needed, but keeps the extra pawn for now.}) +8. c3 O-O 9. h3 {Stops ...Bg4 and prepares d4.} 9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 {Chigorin Variation: the knight heads for f1 and g3.} * diff --git a/apps/desktop/assets/repertoires/spanish-white.ru.pgn b/apps/desktop/assets/repertoires/spanish-white.ru.pgn new file mode 100644 index 0000000..48ff6ac --- /dev/null +++ b/apps/desktop/assets/repertoires/spanish-white.ru.pgn @@ -0,0 +1,13 @@ +[Event "ChessPenguin: И�пан�ка� парти� за белых"] +[White "Repertoire"] +[Black "?"] +[Result "*"] +[ECO "C84"] + +{И�пан�ка� парти� за белых: закрыта� о�новна� �и�тема, атака Маршалла и Берлин�ка� защита.} +1. e4 e5 2. Nf3 Nc6 3. Bb5 {И�пан�кий �лон давит на кон�, защищающего e5.} +3... a6 (3... Nf6 {Берлин�ка� защита.} 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 +8. Qxd8+ Kxd8 {Берлин�кий �ндшпиль: у белых более здоровое пешечное большин�тво.}) +4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 (7... O-O 8. c3 d5 {�така Маршалла.} +9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 {Белые пока �охран�ют лишнюю пешку, а при необходимо�ти вернут материал позже.}) +8. c3 O-O 9. h3 {�е допу�кает ...Bg4 и готовит d4.} 9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 {Вариант Чигорина: конь идёт на f1 и g3.} * diff --git a/apps/desktop/assets/repertoires/triangle-black.pgn b/apps/desktop/assets/repertoires/triangle-black.pgn new file mode 100644 index 0000000..36a8851 --- /dev/null +++ b/apps/desktop/assets/repertoires/triangle-black.pgn @@ -0,0 +1,13 @@ +[Event "ChessPenguin: Semi-Slav Triangle for Black"] +[White "?"] +[Black "Repertoire"] +[Result "*"] +[ECO "D47"] + +{Semi-Slav (Triangle) for Black: the Meran main line, with answers to 5.Bg5, the Exchange Variation and the quiet 4.e3.} +1. d4 d5 2. c4 c6 3. Nf3 e6 {The triangle c6-d5-e6 makes the centre very solid.} +4. Nc3 (4. e3 Nf6 5. Bd3 Nbd7 6. O-O Bd6 7. Nbd2 O-O 8. e4 dxe4 9. Nxe4 Nxe4 10. Bxe4 e5 {Black frees the position with the central break.}) +(4. cxd5 exd5 5. Nc3 Nf6 6. Bg5 Be7 7. e3 Bf5 {Exchange Variation: the c8-bishop gets outside the pawn chain.}) +4... Nf6 5. e3 (5. Bg5 h6 6. Bh4 dxc4 7. e4 g5 8. Bg3 b5 {Moscow Variation: Black grabs the pawn and keeps it with ...b5.}) +5... Nbd7 6. Bd3 dxc4 7. Bxc4 b5 {The Meran: Black gains space on the queenside with tempo.} +8. Bd3 Bb7 9. O-O a6 10. e4 c5 11. d5 Qc7 {Black attacks the centre and is ready to castle.} * diff --git a/apps/desktop/assets/repertoires/triangle-black.ru.pgn b/apps/desktop/assets/repertoires/triangle-black.ru.pgn new file mode 100644 index 0000000..13287b2 --- /dev/null +++ b/apps/desktop/assets/repertoires/triangle-black.ru.pgn @@ -0,0 +1,13 @@ +[Event "ChessPenguin: Полу�лав�н�ка� защита (треугольник) за чёрных"] +[White "?"] +[Black "Repertoire"] +[Result "*"] +[ECO "D47"] + +{Полу�лав�н�ка� защита (треугольник) за чёрных: о�новна� �и�тема Меран и ответы на 5.Bg5, разменный вариант и �покойное 4.e3.} +1. d4 d5 2. c4 c6 3. Nf3 e6 {Треугольник c6-d5-e6 делает центр очень прочным.} +4. Nc3 (4. e3 Nf6 5. Bd3 Nbd7 6. O-O Bd6 7. Nbd2 O-O 8. e4 dxe4 9. Nxe4 Nxe4 10. Bxe4 e5 {Чёрные о�вобождают игру центральным подрывом.}) +(4. cxd5 exd5 5. Nc3 Nf6 6. Bg5 Be7 7. e3 Bf5 {Разменный вариант: �лон c8 выходит за пешечную цепь.}) +4... Nf6 5. e3 (5. Bg5 h6 6. Bh4 dxc4 7. e4 g5 8. Bg3 b5 {Мо�ков�кий вариант: чёрные берут пешку и удерживают её ходом ...b5.}) +5... Nbd7 6. Bd3 dxc4 7. Bxc4 b5 {Меран: чёрные � темпом захватывают про�тран�тво на ферзевом фланге.} +8. Bd3 Bb7 9. O-O a6 10. e4 c5 11. d5 Qc7 {Чёрные атакуют центр и готовы рокировать��.} * diff --git a/apps/desktop/assets/sounds/clicks/Capture.ogg b/apps/desktop/assets/sounds/clicks/Capture.ogg new file mode 100644 index 0000000..017d801 Binary files /dev/null and b/apps/desktop/assets/sounds/clicks/Capture.ogg differ diff --git a/apps/desktop/assets/sounds/clicks/Check.ogg b/apps/desktop/assets/sounds/clicks/Check.ogg new file mode 100644 index 0000000..809d4c0 Binary files /dev/null and b/apps/desktop/assets/sounds/clicks/Check.ogg differ diff --git a/apps/desktop/assets/sounds/clicks/Checkmate.ogg b/apps/desktop/assets/sounds/clicks/Checkmate.ogg new file mode 100644 index 0000000..bacd3de Binary files /dev/null and b/apps/desktop/assets/sounds/clicks/Checkmate.ogg differ diff --git a/apps/desktop/assets/sounds/clicks/Defeat.ogg b/apps/desktop/assets/sounds/clicks/Defeat.ogg new file mode 100644 index 0000000..7aa651e Binary files /dev/null and b/apps/desktop/assets/sounds/clicks/Defeat.ogg differ diff --git a/apps/desktop/assets/sounds/clicks/Move.ogg b/apps/desktop/assets/sounds/clicks/Move.ogg new file mode 100644 index 0000000..8fe38ce Binary files /dev/null and b/apps/desktop/assets/sounds/clicks/Move.ogg differ diff --git a/apps/desktop/assets/sounds/clicks/Success.ogg b/apps/desktop/assets/sounds/clicks/Success.ogg new file mode 100644 index 0000000..e04af48 Binary files /dev/null and b/apps/desktop/assets/sounds/clicks/Success.ogg differ diff --git a/apps/desktop/assets/sounds/common/LowTime.ogg b/apps/desktop/assets/sounds/common/LowTime.ogg new file mode 100644 index 0000000..6a97b2e Binary files /dev/null and b/apps/desktop/assets/sounds/common/LowTime.ogg differ diff --git a/apps/desktop/assets/sounds/common/Wrong.ogg b/apps/desktop/assets/sounds/common/Wrong.ogg new file mode 100644 index 0000000..4db14dc Binary files /dev/null and b/apps/desktop/assets/sounds/common/Wrong.ogg differ diff --git a/apps/desktop/assets/sounds/futuristic/Capture.ogg b/apps/desktop/assets/sounds/futuristic/Capture.ogg new file mode 100644 index 0000000..d2678a3 Binary files /dev/null and b/apps/desktop/assets/sounds/futuristic/Capture.ogg differ diff --git a/apps/desktop/assets/sounds/futuristic/Check.ogg b/apps/desktop/assets/sounds/futuristic/Check.ogg new file mode 100644 index 0000000..844fbe5 Binary files /dev/null and b/apps/desktop/assets/sounds/futuristic/Check.ogg differ diff --git a/apps/desktop/assets/sounds/futuristic/Defeat.ogg b/apps/desktop/assets/sounds/futuristic/Defeat.ogg new file mode 100644 index 0000000..1a5a0c6 Binary files /dev/null and b/apps/desktop/assets/sounds/futuristic/Defeat.ogg differ diff --git a/apps/desktop/assets/sounds/futuristic/Move.ogg b/apps/desktop/assets/sounds/futuristic/Move.ogg new file mode 100644 index 0000000..0d6c2c4 Binary files /dev/null and b/apps/desktop/assets/sounds/futuristic/Move.ogg differ diff --git a/apps/desktop/assets/sounds/futuristic/Success.ogg b/apps/desktop/assets/sounds/futuristic/Success.ogg new file mode 100644 index 0000000..0522e55 Binary files /dev/null and b/apps/desktop/assets/sounds/futuristic/Success.ogg differ diff --git a/apps/desktop/assets/sounds/glass/Capture.ogg b/apps/desktop/assets/sounds/glass/Capture.ogg new file mode 100644 index 0000000..2f5df47 Binary files /dev/null and b/apps/desktop/assets/sounds/glass/Capture.ogg differ diff --git a/apps/desktop/assets/sounds/glass/Check.ogg b/apps/desktop/assets/sounds/glass/Check.ogg new file mode 100644 index 0000000..4420676 Binary files /dev/null and b/apps/desktop/assets/sounds/glass/Check.ogg differ diff --git a/apps/desktop/assets/sounds/glass/Checkmate.ogg b/apps/desktop/assets/sounds/glass/Checkmate.ogg new file mode 100644 index 0000000..f44de75 Binary files /dev/null and b/apps/desktop/assets/sounds/glass/Checkmate.ogg differ diff --git a/apps/desktop/assets/sounds/glass/Defeat.ogg b/apps/desktop/assets/sounds/glass/Defeat.ogg new file mode 100644 index 0000000..6235f5b Binary files /dev/null and b/apps/desktop/assets/sounds/glass/Defeat.ogg differ diff --git a/apps/desktop/assets/sounds/glass/Move.ogg b/apps/desktop/assets/sounds/glass/Move.ogg new file mode 100644 index 0000000..ea6a717 Binary files /dev/null and b/apps/desktop/assets/sounds/glass/Move.ogg differ diff --git a/apps/desktop/assets/sounds/glass/Success.ogg b/apps/desktop/assets/sounds/glass/Success.ogg new file mode 100644 index 0000000..4331f4a Binary files /dev/null and b/apps/desktop/assets/sounds/glass/Success.ogg differ diff --git a/apps/desktop/assets/sounds/nes/Capture.ogg b/apps/desktop/assets/sounds/nes/Capture.ogg new file mode 100644 index 0000000..4f88402 Binary files /dev/null and b/apps/desktop/assets/sounds/nes/Capture.ogg differ diff --git a/apps/desktop/assets/sounds/nes/Check.ogg b/apps/desktop/assets/sounds/nes/Check.ogg new file mode 100644 index 0000000..a58720f Binary files /dev/null and b/apps/desktop/assets/sounds/nes/Check.ogg differ diff --git a/apps/desktop/assets/sounds/nes/Defeat.ogg b/apps/desktop/assets/sounds/nes/Defeat.ogg new file mode 100644 index 0000000..5db6d6b Binary files /dev/null and b/apps/desktop/assets/sounds/nes/Defeat.ogg differ diff --git a/apps/desktop/assets/sounds/nes/Move.ogg b/apps/desktop/assets/sounds/nes/Move.ogg new file mode 100644 index 0000000..de81b9e Binary files /dev/null and b/apps/desktop/assets/sounds/nes/Move.ogg differ diff --git a/apps/desktop/assets/sounds/nes/Success.ogg b/apps/desktop/assets/sounds/nes/Success.ogg new file mode 100644 index 0000000..537115f Binary files /dev/null and b/apps/desktop/assets/sounds/nes/Success.ogg differ diff --git a/apps/desktop/assets/sounds/piano/Capture.ogg b/apps/desktop/assets/sounds/piano/Capture.ogg new file mode 100644 index 0000000..7c028a5 Binary files /dev/null and b/apps/desktop/assets/sounds/piano/Capture.ogg differ diff --git a/apps/desktop/assets/sounds/piano/Check.ogg b/apps/desktop/assets/sounds/piano/Check.ogg new file mode 100644 index 0000000..278db83 Binary files /dev/null and b/apps/desktop/assets/sounds/piano/Check.ogg differ diff --git a/apps/desktop/assets/sounds/piano/Defeat.ogg b/apps/desktop/assets/sounds/piano/Defeat.ogg new file mode 100644 index 0000000..93df79b Binary files /dev/null and b/apps/desktop/assets/sounds/piano/Defeat.ogg differ diff --git a/apps/desktop/assets/sounds/piano/Move.ogg b/apps/desktop/assets/sounds/piano/Move.ogg new file mode 100644 index 0000000..10dc131 Binary files /dev/null and b/apps/desktop/assets/sounds/piano/Move.ogg differ diff --git a/apps/desktop/assets/sounds/piano/Success.ogg b/apps/desktop/assets/sounds/piano/Success.ogg new file mode 100644 index 0000000..fa2cc74 Binary files /dev/null and b/apps/desktop/assets/sounds/piano/Success.ogg differ diff --git a/apps/desktop/assets/sounds/sfx/Capture.ogg b/apps/desktop/assets/sounds/sfx/Capture.ogg new file mode 100644 index 0000000..92b3f9e Binary files /dev/null and b/apps/desktop/assets/sounds/sfx/Capture.ogg differ diff --git a/apps/desktop/assets/sounds/sfx/Check.ogg b/apps/desktop/assets/sounds/sfx/Check.ogg new file mode 100644 index 0000000..e5ffec8 Binary files /dev/null and b/apps/desktop/assets/sounds/sfx/Check.ogg differ diff --git a/apps/desktop/assets/sounds/sfx/Defeat.ogg b/apps/desktop/assets/sounds/sfx/Defeat.ogg new file mode 100644 index 0000000..934cc54 Binary files /dev/null and b/apps/desktop/assets/sounds/sfx/Defeat.ogg differ diff --git a/apps/desktop/assets/sounds/sfx/Move.ogg b/apps/desktop/assets/sounds/sfx/Move.ogg new file mode 100644 index 0000000..03745d4 Binary files /dev/null and b/apps/desktop/assets/sounds/sfx/Move.ogg differ diff --git a/apps/desktop/assets/sounds/sfx/Success.ogg b/apps/desktop/assets/sounds/sfx/Success.ogg new file mode 100644 index 0000000..e8646a3 Binary files /dev/null and b/apps/desktop/assets/sounds/sfx/Success.ogg differ diff --git a/apps/desktop/assets/sounds/wood/Capture.ogg b/apps/desktop/assets/sounds/wood/Capture.ogg new file mode 100644 index 0000000..7443a51 Binary files /dev/null and b/apps/desktop/assets/sounds/wood/Capture.ogg differ diff --git a/apps/desktop/assets/sounds/wood/Check.ogg b/apps/desktop/assets/sounds/wood/Check.ogg new file mode 100644 index 0000000..513965a Binary files /dev/null and b/apps/desktop/assets/sounds/wood/Check.ogg differ diff --git a/apps/desktop/assets/sounds/wood/Checkmate.ogg b/apps/desktop/assets/sounds/wood/Checkmate.ogg new file mode 100644 index 0000000..d7cbbea Binary files /dev/null and b/apps/desktop/assets/sounds/wood/Checkmate.ogg differ diff --git a/apps/desktop/assets/sounds/wood/Defeat.ogg b/apps/desktop/assets/sounds/wood/Defeat.ogg new file mode 100644 index 0000000..3543ff0 Binary files /dev/null and b/apps/desktop/assets/sounds/wood/Defeat.ogg differ diff --git a/apps/desktop/assets/sounds/wood/Move.ogg b/apps/desktop/assets/sounds/wood/Move.ogg new file mode 100644 index 0000000..3c34b28 Binary files /dev/null and b/apps/desktop/assets/sounds/wood/Move.ogg differ diff --git a/apps/desktop/assets/sounds/wood/Success.ogg b/apps/desktop/assets/sounds/wood/Success.ogg new file mode 100644 index 0000000..32d3b4f Binary files /dev/null and b/apps/desktop/assets/sounds/wood/Success.ogg differ diff --git a/apps/desktop/build.rs b/apps/desktop/build.rs new file mode 100644 index 0000000..3c834bf --- /dev/null +++ b/apps/desktop/build.rs @@ -0,0 +1,17 @@ +fn main() { + // `cfg(web)`: WebAssembly in a browser (the web version, apps/web). + println!("cargo::rustc-check-cfg=cfg(web)"); + if std::env::var("CARGO_CFG_TARGET_FAMILY").as_deref() == Ok("wasm") + && std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("unknown") + { + println!("cargo::rustc-cfg=web"); + } + // Embeds the application icon into the Windows executable. + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + let mut res = winresource::WindowsResource::new(); + res.set_icon("../../packaging/windows/chesspenguin.ico"); + if let Err(e) = res.compile() { + println!("cargo:warning=could not embed the Windows icon: {e}"); + } + } +} diff --git a/apps/desktop/src/adjourned.rs b/apps/desktop/src/adjourned.rs new file mode 100644 index 0000000..dfa318d --- /dev/null +++ b/apps/desktop/src/adjourned.rs @@ -0,0 +1,348 @@ +//! The card of a game put aside (docs/design/desktop-adjourned.md): on the library's +//! shelf, as a strip under a folded shelf, and in the question about a new game. + +use chess_core::shakmaty::{Chess, Color, Position, Square}; +use egui::{RichText, Sense, Ui, vec2}; + +use crate::i18n::{tr, trf}; +use crate::player_games::PutAside; +use crate::settings::Settings; + +/// What the card shows, read once from the game put aside. +pub struct Card { + pos: Chess, + last: Option<(Square, Square)>, + user: Color, + /// «Game against Maia 1550». + pub title: String, + /// «Alekhine · you play black · move 18». + pub line2: String, + /// «5+3 · you 4:12 · Maia 3:58», «no clock». + pub line3: String, + /// The lines of its tooltip under the board. + tip: Vec, + /// Where × writes it (`None`: × deletes it). + pub db: Option, +} + +/// What was pressed on a card. +#[derive(PartialEq)] +pub enum Pressed { + Continue, + Discard, +} + +impl Card { + pub fn new(aside: &PutAside) -> Self { + let game = crate::play::parse_game(aside.pgn()).unwrap_or_default(); + let saved = aside.game(); + let user = if saved.white { + Color::White + } else { + Color::Black + }; + let end = game.line_end(chess_core::NodeId::ROOT); + let pos = game.position(end).cloned().unwrap_or_default(); + let last = game.game_move(end).and_then(|m| match &m.kind { + chess_core::MoveKind::Normal(m) => Some((m.from()?, m.to())), + chess_core::MoveKind::Null => None, + }); + let style = crate::play::style(&saved.style); + let (rival, short) = match saved.rival { + crate::play::Rival::Maia => (format!("Maia {}", saved.strength), "Maia".to_owned()), + crate::play::Rival::Rodent => { + let name = style.rodent.name(); + (format!("{name} {}", saved.strength), name.to_owned()) + } + }; + let side = if saved.white { + tr("you play white") + } else { + tr("you play black") + }; + let n = pos.fullmoves().get(); + let mv = trf("move {n}", &[("n", &n)]); + let mut line2 = Vec::new(); + if saved.rival == crate::play::Rival::Rodent && saved.style != crate::play::STYLES[0].id { + line2.push(tr(style.title()).to_owned()); + } + line2.push(side.to_owned()); + line2.push(mv); + let line3 = match saved.clock { + Some(tc) => { + let left = crate::play::times_left(&game, saved.floor, aside.to_move_left()); + let base = std::time::Duration::from_secs(tc.base.into()); + let text = |c: Color| { + crate::play::clock_text( + left[if c == Color::White { 0 } else { 1 }].unwrap_or(base), + ) + }; + format!( + "{} · {} · {short} {}", + tc.label(), + trf("you {t}", &[("t", &text(user))]), + text(!user) + ) + } + None => tr("no clock").to_owned(), + }; + let whose = if pos.turn() == user { + trf("move {n}, yours", &[("n", &n)]) + } else { + trf("move {n}, {rival} to move", &[("n", &n), ("rival", &short)]) + }; + let when = chrono::DateTime::::from(aside.when()) + .format("%d.%m, %H:%M") + .to_string(); + let mut tip = vec![trf("Game against {rival}", &[("rival", &rival)])]; + if line2.len() > 2 { + tip.push(format!("{} · {}", line2[0], side)); + } else { + tip.push(side.to_owned()); + } + tip.push(whose); + tip.push(trf("Put aside {when}", &[("when", &when)])); + Card { + pos, + last, + user, + title: trf("Game against {rival}", &[("rival", &rival)]), + line2: line2.join(" · "), + line3, + tip, + db: aside.target().map(crate::own_db::base_name), + } + } + + /// The board of the position, `size` square, at `at`. + pub fn board(&self, ui: &mut Ui, rect: egui::Rect, settings: &Settings) { + let view = crate::board::BoardView { + pos: &self.pos, + orientation: self.user, + last_move: self.last, + arrows: &[], + circles: &[], + badge: None, + interactive: false, + temporary_shapes: false, + show_coords: false, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: 0.0, + premove: None, + auto_queen: false, + alert: None, + }; + let mut state = crate::board::BoardState::default(); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + view.show(ui, &mut state); + }); + } + + /// The board and the lines under the pointer. + fn tooltip(&self, ui: &mut Ui, settings: &Settings) { + let (rect, _) = ui.allocate_exact_size(vec2(192.0, 192.0), Sense::hover()); + self.board(ui, rect, settings); + ui.add_space(4.0); + ui.label(RichText::new(&self.tip[0]).strong()); + for line in &self.tip[1..] { + ui.label(line); + } + ui.label(RichText::new(tr("Click, or Ctrl+G, Enter")).weak()); + } + + fn discard_hint(&self) -> String { + match &self.db { + Some(db) => trf( + "Don't finish it: the game is written to «{db}» unfinished", + &[("db", db)], + ), + None => tr("Don't finish it: the game is deleted").to_owned(), + } + } + + /// The width of the full card: its lines, its button, within 360…460. + pub fn width(&self, ui: &Ui) -> f32 { + let w = |s: &str, size: f32| { + ui.fonts_mut(|f| { + f.layout_no_wrap( + s.to_owned(), + egui::FontId::proportional(size), + egui::Color32::WHITE, + ) + .size() + .x + }) + }; + let lines = w(&self.title, 14.0) + .max(w(&self.line2, 12.0)) + .max(w(&self.line3, 12.0)); + let button = w(tr("Continue"), 14.0) + 2.0 * ui.spacing().button_padding.x; + (64.0 + 12.0 + lines + 12.0 + button + 8.0 + 20.0 + 4.0).clamp(360.0, 460.0) + } + + /// The card on the shelf: 64 high, `width` wide. + pub fn show(&self, ui: &mut Ui, width: f32, settings: &Settings) -> Option { + self.frame(ui, vec2(width, 64.0), settings, |ui, rect, card| { + let v = ui.visuals().clone(); + let button = tr("Continue"); + let bw = ui.fonts_mut(|f| { + f.layout_no_wrap( + button.to_owned(), + egui::FontId::proportional(14.0), + v.text_color(), + ) + .size() + .x + }) + 2.0 * ui.spacing().button_padding.x; + let text_left = rect.left() + 64.0 + 12.0; + let text_w = rect.right() - 4.0 - 20.0 - 8.0 - bw - 12.0 - text_left; + let mut y = rect.top() + 7.0; + for (line, size, color) in [ + (&card.title, 14.0, v.text_color()), + (&card.line2, 12.0, v.weak_text_color()), + (&card.line3, 12.0, v.weak_text_color()), + ] { + let galley = cut(ui, line, size, color, text_w); + let h = galley.size().y; + ui.painter().galley(egui::pos2(text_left, y), galley, color); + y += h + 2.0; + } + let at = egui::Rect::from_min_size( + egui::pos2(rect.right() - 4.0 - 20.0 - 8.0 - bw, rect.center().y - 14.0), + vec2(bw, 28.0), + ); + ui.put(at, primary_button(ui, button)).clicked() + }) + } + + /// The strip under a folded shelf: 40 high, one line. + pub fn strip(&self, ui: &mut Ui, settings: &Settings) -> Option { + let width = ui.available_width(); + self.frame(ui, vec2(width, 40.0), settings, |ui, rect, card| { + let v = ui.visuals().clone(); + let button = tr("Continue"); + let bw = ui.fonts_mut(|f| { + f.layout_no_wrap( + button.to_owned(), + egui::FontId::proportional(14.0), + v.text_color(), + ) + .size() + .x + }) + 2.0 * ui.spacing().button_padding.x; + let text_left = rect.left() + 40.0 + 10.0; + let text_w = rect.right() - 4.0 - 20.0 - 8.0 - bw - 10.0 - text_left; + let line = format!("{} · {} · {}", card.title, card.line2, card.line3); + let galley = cut(ui, &line, 13.0, v.text_color(), text_w); + let y = rect.center().y - galley.size().y / 2.0; + ui.painter() + .galley(egui::pos2(text_left, y), galley, v.text_color()); + let at = egui::Rect::from_min_size( + egui::pos2(rect.right() - 4.0 - 20.0 - 8.0 - bw, rect.center().y - 14.0), + vec2(bw, 28.0), + ); + ui.put(at, primary_button(ui, button)).clicked() + }) + } + + /// The card's frame, board, × and click; `inside` draws the rest and says whether its + /// button was pressed. + fn frame( + &self, + ui: &mut Ui, + size: egui::Vec2, + settings: &Settings, + inside: impl FnOnce(&mut Ui, egui::Rect, &Card) -> bool, + ) -> Option { + let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); + let v = ui.visuals(); + let fill = if ui.rect_contains_pointer(rect) { + v.widgets.hovered.weak_bg_fill + } else { + v.faint_bg_color + }; + let stroke = egui::Stroke::new(1.5, v.selection.bg_fill); + ui.painter().rect_filled(rect, 6.0, fill); + // Inside the rounded frame, clear of its outline. + let side = rect.height() - 8.0; + let board = egui::Rect::from_min_size(rect.min + vec2(4.0, 4.0), vec2(side, side)); + self.board(ui, board, settings); + ui.painter() + .rect_stroke(rect, 6.0, stroke, egui::StrokeKind::Inside); + // The whole card goes on with the game, its board too (over it: later); the + // button and × are their own. + let resp = ui + .interact(rect, ui.id().with("aside_card"), Sense::click()) + .on_hover_ui(|ui| self.tooltip(ui, settings)); + let mut pressed = None; + if inside(ui, rect, self) { + pressed = Some(Pressed::Continue); + } + let x = egui::Rect::from_min_size(rect.right_top() + vec2(-26.0, 4.0), vec2(22.0, 20.0)); + if ui + .put(x, |ui: &mut Ui| crate::widgets::small_close_button(ui)) + .on_hover_text(self.discard_hint()) + .clicked() + { + pressed = Some(Pressed::Discard); + } + if pressed.is_none() && resp.clicked() { + pressed = Some(Pressed::Continue); + } + resp.widget_info(|| { + egui::WidgetInfo::labeled( + egui::WidgetType::Button, + true, + format!( + "{}: {} · {} · {}. {}", + tr("Game put aside"), + self.title, + self.line2, + self.line3, + tr("Continue") + ), + ) + }); + pressed + } + + /// The board and the three lines, for the question about a new game. + pub fn summary(&self, ui: &mut Ui, settings: &Settings) { + ui.horizontal_top(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(96.0, 96.0), Sense::hover()); + self.board(ui, rect, settings); + ui.add_space(12.0 - ui.spacing().item_spacing.x); + ui.vertical(|ui| { + ui.label(RichText::new(&self.title).size(14.0).strong()); + ui.label(RichText::new(&self.line2).weak()); + ui.label(RichText::new(&self.line3).weak()); + }); + }); + } +} + +/// A line cut with «…» to `width`. +fn cut( + ui: &Ui, + text: &str, + size: f32, + color: egui::Color32, + width: f32, +) -> std::sync::Arc { + let mut job = egui::text::LayoutJob::simple( + text.to_owned(), + egui::FontId::proportional(size), + color, + width.max(10.0), + ); + job.wrap.max_rows = 1; + job.wrap.break_anywhere = true; + job.wrap.overflow_character = Some('…'); + ui.fonts_mut(|f| f.layout_job(job)) +} + +/// As `widgets::primary`, to be put at a place. +fn primary_button(ui: &Ui, label: &str) -> egui::Button<'static> { + egui::Button::new(RichText::new(label.to_owned()).strong()).fill(ui.visuals().selection.bg_fill) +} diff --git a/apps/desktop/src/analysis.rs b/apps/desktop/src/analysis.rs new file mode 100644 index 0000000..339ed8f --- /dev/null +++ b/apps/desktop/src/analysis.rs @@ -0,0 +1,432 @@ +//! Engine analysis controller: owns the engine (a UCI process; in a browser a Web +//! Worker), binds results to the analysed position. + +use crate::i18n::{tr, trf}; + +use shakmaty::san::SanPlus; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, Move, Position}; +use uci::{ + EngineEvent, EngineHandle, EnginePosition, SearchId, SearchInfo, SearchLimits, Side, + TerminationReason, WhiteEval, WhiteScore, +}; + +use crate::settings::EngineConfig; + +#[derive(Clone, Debug)] +pub struct PvLine { + pub multipv: u32, + pub depth: u32, + pub score: WhiteScore, + /// Legal moves of the PV from the analysed position (stops at the first illegal move). + pub moves: Vec, + pub san: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Status { + Off, + Starting, + Running, + Failed(String), +} + +/// A position the engine is (or should be) analysing. +struct Target { + key: String, + root: Chess, + engine_pos: EnginePosition, +} + +/// An engine on its way: its process started on a thread of its own (the handshake +/// blocks for up to ~20 s); in a browser its worker, the handshake by its messages. +enum Launch { + #[cfg(not(web))] + Thread(std::sync::mpsc::Receiver>), + /// The worker and the options to set once it answered. + #[cfg(web)] + Worker(uci::Starting, EngineConfig), +} + +impl Launch { + /// The engine once it answered, its options set (or why it did not answer). + fn poll(&mut self) -> Option> { + match self { + #[cfg(not(web))] + Launch::Thread(rx) => rx.try_recv().ok(), + #[cfg(web)] + Launch::Worker(s, cfg) => s.poll().map(|r| r.inspect(|h| set_options(h, cfg))), + } + } +} + +/// Threads, hash and lines of `cfg` (unknown options are not fatal: some engines lack +/// Threads/Hash/MultiPV). +fn set_options(h: &EngineHandle, cfg: &EngineConfig) { + let _ = h.set_threads(cfg.threads); + let _ = h.set_hash_mb(cfg.hash_mb); + let _ = h.set_multipv(cfg.multipv.max(1)); +} + +pub struct Analysis { + engine: Option, + spawning: Option, + pub status: Status, + pub engine_name: String, + next_id: u64, + current: Option<(SearchId, Target)>, + /// Requested while the engine is still starting. + queued: Option, + pub lines: Vec, + pub nodes: u64, + pub nps: u64, + multipv: u32, + /// Search time per position; `None` = infinite analysis. + limit: Option, + /// The current search ended (time limit reached); lines stay as the final result. + pub finished: bool, + /// Executable of the running engine (to detect a switch of the active engine). + pub engine_path: Option, +} + +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 { + pub fn new() -> Self { + Self { + engine: None, + spawning: None, + status: Status::Off, + engine_name: String::new(), + next_id: 1, + current: None, + queued: None, + lines: Vec::new(), + nodes: 0, + nps: 0, + multipv: 1, + limit: None, + finished: false, + engine_path: None, + } + } + + pub fn is_on(&self) -> bool { + matches!(self.status, Status::Starting | Status::Running) + } + + /// Starts the engine in the background: its options are set once it answered. + pub fn start(&mut self, cfg: &EngineConfig, ctx: &egui::Context) { + self.stop(); + let Some(path) = cfg.executable() else { + self.status = + Status::Failed(tr("The built-in engine is not part of this build").into()); + return; + }; + self.engine_name = cfg.name.clone(); + self.multipv = cfg.multipv.max(1); + self.limit = cfg.search_secs; + self.engine_path = Some(path.clone()); + match launch(path, cfg.clone(), ctx) { + Ok(l) => { + self.spawning = Some(l); + self.status = Status::Starting; + } + Err(e) => self.status = Status::Failed(e), + } + } + + /// Stops analysis and terminates the engine. + pub fn stop(&mut self) { + if let Some(e) = self.engine.take() { + // quit() may wait up to the quit timeout; do it off the UI thread. A worker + // stops at once. + #[cfg(not(web))] + let _ = std::thread::Builder::new() + .name("engine-quit".into()) + .spawn(move || { + e.quit(); + }); + #[cfg(web)] + e.quit(); + } + self.spawning = None; + self.current = None; + self.queued = None; + self.lines.clear(); + self.engine_path = None; + self.status = Status::Off; + } + + /// Applies Threads/Hash/MultiPV/time of the running engine and restarts the current search. + pub fn reconfigure(&mut self, cfg: &EngineConfig, ctx: &egui::Context) { + if self.engine_path != cfg.executable() || self.spawning.is_some() { + self.start(cfg, ctx); + return; + } + let Some(engine) = &self.engine else { return }; + let _ = engine.set_threads(cfg.threads); + let _ = engine.set_hash_mb(cfg.hash_mb); + let _ = engine.set_multipv(cfg.multipv.max(1)); + self.multipv = cfg.multipv.max(1); + self.limit = cfg.search_secs; + if let Some((_, t)) = self.current.take() { + self.set_position(&t.root, t.engine_pos); + } + } + + /// Requests analysis of `root`; no-op if that exact history is already being analysed. + pub fn set_position(&mut self, root: &Chess, engine_pos: EnginePosition) { + if !self.is_on() { + return; + } + let key = format!("{:?}|{}", engine_pos.base, engine_pos.moves.join(" ")); + if self.current.as_ref().is_some_and(|(_, t)| t.key == key) { + return; + } + if self.queued.as_ref().is_some_and(|t| t.key == key) { + return; + } + let target = Target { + key, + root: root.clone(), + engine_pos, + }; + self.lines.clear(); + self.nodes = 0; + self.nps = 0; + self.finished = false; + let Some(engine) = &self.engine else { + self.queued = Some(target); + return; + }; + let id = SearchId(self.next_id); + self.next_id += 1; + let res = match self.limit { + None => engine.analyze(target.engine_pos.clone(), id), + Some(secs) => engine.search( + target.engine_pos.clone(), + id, + SearchLimits::MoveTime(std::time::Duration::from_secs(u64::from(secs))), + ), + }; + match res { + Ok(()) => self.current = Some((id, target)), + Err(e) => { + self.current = None; + self.status = Status::Failed(e.to_string()); + } + } + } + + /// Drains engine events; call once per frame. + pub fn poll(&mut self) { + if let Some(res) = self.spawning.as_mut().and_then(Launch::poll) { + self.spawning = None; + match res { + Ok(h) => { + if let Some(name) = &h.info().name { + self.engine_name = name.clone(); + } + self.engine = Some(h); + self.status = Status::Running; + if let Some(t) = self.queued.take() { + let (root, pos) = (t.root, t.engine_pos); + self.set_position(&root, pos); + } + } + Err(e) => { + self.lines.clear(); + self.status = Status::Failed(e.to_string()); + } + } + } + let Some(engine) = &self.engine else { return }; + let events: Vec = engine.drain_events().collect(); + for ev in events { + match ev { + EngineEvent::Info { search_id, info } => { + if let Some((id, target)) = &self.current + && *id == search_id + { + let side = side(target.root.turn()); + if let Some(line) = make_line(&target.root, side, &info) { + self.nodes = info.nodes.unwrap_or(self.nodes); + self.nps = info.nps.unwrap_or(self.nps); + upsert(&mut self.lines, line, self.multipv); + } + } + } + EngineEvent::BestMove { search_id, .. } => { + if self + .current + .as_ref() + .is_some_and(|(id, _)| *id == search_id) + { + self.finished = true; + } + } + EngineEvent::Terminated(reason) => { + self.engine = None; + self.current = None; + self.lines.clear(); + self.status = Status::Failed(termination_message(&reason)); + return; + } + _ => {} + } + } + } + + /// Best line of the current search, already bound to the position it was computed for. + pub fn best(&self) -> Option<&PvLine> { + if self.status == Status::Running { + self.lines.first() + } else { + None + } + } +} + +/// Starts the engine of `cfg` at `path` with its options. +#[cfg(not(web))] +fn launch( + location: crate::engines::EngineLocation, + cfg: EngineConfig, + ctx: &egui::Context, +) -> Result { + let crate::engines::EngineLocation::Program(path) = location; + let (tx, rx) = std::sync::mpsc::channel(); + let ctx_w = ctx.clone(); + let ctx_done = ctx.clone(); + std::thread::Builder::new() + .name("engine-spawn".into()) + .spawn(move || { + let res = uci::Engine::spawn_with( + uci::EngineConfig::new(&path), + Box::new(move || ctx_w.request_repaint()), + ) + .inspect(|h| set_options(h, &cfg)); + let _ = tx.send(res); + ctx_done.request_repaint(); + }) + .map(|_| Launch::Thread(rx)) + .map_err(|e| e.to_string()) +} + +/// Starts the engine of `cfg` in its Web Worker. +#[cfg(web)] +fn launch( + location: crate::engines::EngineLocation, + cfg: EngineConfig, + ctx: &egui::Context, +) -> Result { + let crate::engines::EngineLocation::Worker(script) = location; + let ctx = ctx.clone(); + uci::Engine::start_worker( + uci::WorkerConfig::new(script), + Box::new(move || ctx.request_repaint()), + ) + .map(|s| Launch::Worker(s, cfg)) + .map_err(|e| e.to_string()) +} + +impl Drop for Analysis { + fn drop(&mut self) { + self.stop(); + } +} + +/// Human-readable reason of an engine process ending. +pub fn termination_message(reason: &TerminationReason) -> String { + match reason { + TerminationReason::Hung { .. } => tr("The engine hung and was stopped").into(), + TerminationReason::Exited { status } | TerminationReason::Quit { status } => match status { + Some(s) => trf("The engine exited ({s})", &[("s", s)]), + None => tr("The engine exited").into(), + }, + } +} + +fn side(c: Color) -> Side { + match c { + Color::White => Side::White, + Color::Black => Side::Black, + } +} + +fn make_line(root: &Chess, side: Side, info: &SearchInfo) -> Option { + let score = info.score?.to_white(side); + if info.pv.is_empty() { + return None; + } + let mut pos = root.clone(); + let mut moves = Vec::new(); + let mut san = Vec::new(); + for u in &info.pv { + let Ok(m) = u + .parse::() + .map_err(|_| ()) + .and_then(|um| um.to_move(&pos).map_err(|_| ())) + else { + break; + }; + san.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); + moves.push(m); + } + if moves.is_empty() { + return None; + } + Some(PvLine { + multipv: info.multipv_index(), + depth: info.depth.unwrap_or(0), + score, + moves, + san, + }) +} + +fn upsert(lines: &mut Vec, line: PvLine, multipv: u32) { + if line.multipv > multipv { + return; + } + match lines.iter_mut().find(|l| l.multipv == line.multipv) { + Some(l) => *l = line, + None => lines.push(line), + } + lines.sort_by_key(|l| l.multipv); +} + +/// "+0.35", "-1.20", "#3", "#-2" from White's point of view. +pub fn format_eval(s: &WhiteScore) -> String { + match s.eval { + WhiteEval::Cp(cp) => format!("{:+.2}", cp as f32 / 100.0), + WhiteEval::Mate { winner, moves } => match winner { + Side::White => format!("#{moves}"), + Side::Black => format!("#-{moves}"), + }, + } +} + +/// Evaluation squashed into 0..1 for the eval bar (1 = White winning). +pub fn bar_fraction(s: &WhiteScore) -> f32 { + match s.eval { + WhiteEval::Cp(cp) => { + let x = cp as f32 / 100.0; + 0.5 + 0.5 * (2.0 / (1.0 + (-0.37 * x).exp()) - 1.0) + } + WhiteEval::Mate { + winner: Side::White, + .. + } => 1.0, + WhiteEval::Mate { + winner: Side::Black, + .. + } => 0.0, + } +} diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs new file mode 100644 index 0000000..7c7f185 --- /dev/null +++ b/apps/desktop/src/app.rs @@ -0,0 +1,5243 @@ +//! Top-level application state: library ⇄ game, settings, engine, background dialogs. + +use crate::i18n::{tr, trf}; +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use std::sync::atomic::AtomicBool; + +use chess_core::{Game, PgnDatabase, TextEncoding}; +use egui::{Key, KeyboardShortcut, Modifiers, RichText}; + +use crate::analysis::Analysis; +use crate::assets::Sound; +use crate::game_view::{GameAction, GameSource, GameView}; +use crate::library::{Library, LibraryAction}; +use crate::own_db::{ + self, Answer, ChooserFor, ChooserOutcome, EditorMode, EditorOutcome, NewBaseOutcome, + QuestionKind, +}; +use crate::prep_ui::{DialogOutcome, PrepAction, PrepDialog, PrepScreen}; +use crate::settings::{EngineConfig, Settings}; +use crate::settings_ui::{SettingsAction, SettingsWindow, Tab}; +use crate::sound::SoundPlayer; + +/// Results of work done off the UI thread (file dialogs, engine checks). +enum Async { + /// Databases chosen in a dialog (none: it was cancelled). + DatabasesPicked(Vec), + /// Databases dropped on the window. + DatabasesDropped(Vec), + /// Files dropped on the window that are no longer there (their names). + Missing(Vec), + /// Files not opened: too big for a browser (name, bytes). + #[cfg(web)] + TooBig(Vec<(String, u64)>), + SavePicked(PathBuf), + SaveCancelled, + EngineChecked(Result<(PathBuf, String), String>), + /// The folder for new databases (`None`: the dialog was cancelled). + FolderPicked(Option), + /// A remembered file the browser let the page read again. + #[cfg(web)] + ReadAllowed(PathBuf), + /// ChessBase databases not all files of which were chosen (their `.cbh` names). + #[cfg(web)] + Incomplete(Vec), + /// A folder was chosen (or dropped) with no database in it. + EmptyFolder, + /// Files dropped on the window that are no databases (their names). + NotDatabases(Vec), + /// A copy of the visit's database `.0` kept in the browser, or why not. + #[cfg(web)] + CopyKept(PathBuf, Result), +} + +/// What the web version tells in a window of its own about the files chosen. +#[cfg(web)] +enum WebNotice { + /// Databases too big for a browser (name, bytes). + TooBig(Vec<(String, u64)>), + /// A ChessBase database's `.cbh` chosen without its other files (its name). + Incomplete(String), +} + +/// A passing message at the bottom; `undo`: with the button that puts a deleted game back. +struct Toast { + text: String, + until: f64, + undo: bool, +} + +/// The dialogs and the pending steps of the user's own databases (own_db.rs). +#[derive(Default)] +struct Own { + new_base: Option, + chooser: Option, + editor: Option<(own_db::DataEditor, EditorThen)>, + question: Option<(own_db::Question, QuestionThen)>, + /// The advice about a big database was given this session. + big_advised: std::collections::HashSet, + /// Waits for its database to be read. + pending: Option, + /// A deleted record that can be put back (the toast's Undo, Ctrl+Z). + undo: Option, + /// Leaving the game once it is saved or added (the question about unsaved edits led + /// to the save or the chooser). + then_close: Option, +} + +enum EditorThen { + Done, + Add(PathBuf), +} + +enum QuestionThen { + Duplicate { + target: PathBuf, + index: usize, + }, + /// A record of a table is already in the target (record `at`). + DuplicateRecord { + from: PathBuf, + index: usize, + target: PathBuf, + at: usize, + }, + Delete { + path: PathBuf, + index: usize, + }, + /// Make the copy (asked from the card's menu); its card is then selected. + Utf8Copy { + path: PathBuf, + dest: PathBuf, + }, + /// The write failed: the same write again. + Retry(Retry), + /// The file changed on the disk: the game can only go in as a new record. + Changed(Retry), + BigBase, +} + +/// A step that waits for a database to be read (it was just created, reloaded after a +/// write, or not opened yet). +enum Pending { + AddCurrent(PathBuf), + AppendRecord { + from: PathBuf, + index: usize, + target: PathBuf, + }, + Replace, + Undo, +} + +impl Pending { + fn path(&self, game: Option<&GameView>, undo: Option<&UndoDelete>) -> Option { + match self { + Pending::AddCurrent(p) => Some(p.clone()), + Pending::AppendRecord { target, .. } => Some(target.clone()), + Pending::Replace => game.and_then(|g| g.source.as_ref()).map(|s| s.path.clone()), + Pending::Undo => undo.map(|u| u.path.clone()), + } + } +} + +/// What to do again after a failed write. +#[derive(Clone)] +enum Retry { + Replace, + /// The duplicate's record in `target` is replaced. + ReplaceIn { + target: PathBuf, + index: usize, + }, + Append(PathBuf), + AppendRecord { + from: PathBuf, + index: usize, + target: PathBuf, + }, + Delete { + path: PathBuf, + index: usize, + }, +} + +struct UndoDelete { + path: PathBuf, + removed: chess_core::pgn::store::Removed, + /// The open game was this record: it gets its source back with the record. + open: Option, +} + +/// The id of the toast: a passing message, never in the way of the keyboard. +pub const TOAST: &str = "toast"; + +/// Something is open over the screen — a window, a menu, a dialog — in this frame or the +/// last one: Escape is meant for it (it closes itself), not for leaving the screen. +pub fn overlay_open(ctx: &egui::Context) -> bool { + overlay_open_besides(ctx, &[]) +} + +/// `overlay_open`, not counting these layers of the screen itself (the filters over +/// the list). +pub fn overlay_open_besides(ctx: &egui::Context, own: &[egui::Id]) -> bool { + let passive = [ + egui::Id::new(TOAST), + egui::Id::new(crate::engine_offer::DOWNLOAD_INDICATOR), + ]; + ctx.memory(|m| m.areas().visible_layer_ids()) + .iter() + .any(|l| { + matches!(l.order, egui::Order::Middle | egui::Order::Foreground) + && !passive.contains(&l.id) + && !own.contains(&l.id) + }) +} + +/// What starts once the played game is closed. +enum PlayNext { + Rematch(crate::play::Start), + /// The play dialog again (from the same position, for a game from a position). + Dialog(Option>), +} + +#[derive(Clone, Copy, PartialEq)] +pub enum CloseIntent { + BackToLibrary, + QuitApp, + /// Back to the game this one was opened from (reference tab). + ReturnToPrevious, +} + +/// The online databases are updated on their own at most this often (s). +const ONLINE_EVERY: f64 = 600.0; + +pub struct App { + settings: Settings, + settings_dirty: bool, + sound: SoundPlayer, + library: Library, + game: Option, + analysis: Analysis, + /// The live engine was stopped for a whole-game analysis and resumes after it. + live_paused: bool, + settings_ui: SettingsWindow, + toast: Option, + own: Own, + /// The play dialog («Play against the computer»). + play_dialog: Option, + /// A game against the computer put aside (or left by a crash): it can go on + /// (docs/design/desktop-adjourned.md). + put_aside: Option, + /// A new game was asked for while a game is put aside: «There is a game put aside» + /// asks first; what was asked for comes after «Start a new one». + aside_question: Option, + /// × on the card of a game that goes into no database: «Delete it?». + aside_delete: bool, + /// The opponent of the game put aside is not on the disk: offered for download + /// (`Some(None)`: asked, not started), then the game goes on. + aside_fetch: Option>, + /// After the current game is closed: a new game against Maia (a rematch, or the + /// dialog for a new one). + play_next: Option, + tx: Sender, + rx: Receiver, + /// «Paste PGN»: the clipboard being read. + pasting: Option, + /// A file of the last visit being chosen again (a browser's). + choosing_again: Option, + /// The web version's draft of an unsaved game: the one left at the last visit + /// (offered), and when this visit's was last written (egui time; `None`: none). + #[cfg(web)] + draft_offer: Option, + #[cfg(web)] + draft_at: Option, + #[cfg(web)] + web_notice: Option, + confirm_close: Option, + /// Close the game once the pending "save as" succeeds. + close_after_save: Option, + /// The offer to download Stockfish when an action needs an engine. + engine_offer: crate::engine_offer::EngineOffer, + /// What waits for an engine of the user's to be probed (`review_engine`): at most + /// one game analysis and one search for opening errors. + review_wait: Vec, + offer_hook_done: bool, + /// What only the desktop program has: online games, updates. + #[cfg(not(web))] + desktop: Desktop, + /// Translating comments: the setup and consent windows, the ChatGPT sign-in. + translation: crate::translate_ui::Hub, + /// A position to find in a database once the game is closed. + find_after_close: Option<(PathBuf, shakmaty::Chess, Vec, bool)>, + /// Games left for one opened from the reference tab ("⬅ Back to …"), kept as they + /// were (unsaved edits included). + previous_games: Vec, + /// The last game showed the reference tab: the next one opens with it too. + reference_tab: bool, + /// The executable to start after quitting (a restart into the new version). + restart_to: Option, + /// The reference tab of games (kept across games: its results stay cached). + reference: crate::reference::Reference, + /// Preparing against an opponent: the dialog, and the report screen in the stack + /// between the library and the game (opponent-prep.md §3.1). + prep_dialog: Option, + prep: Option, + /// The library's «Preparations» window, and a saved preparation waiting for its + /// database to be read. + prep_list: Option, + /// The names of its player, found again in the database once it is read. + prep_waiting: Option<(crate::prep_ui::PrepStart, Vec)>, + /// Quitting while the opening errors are searched: asked first; «Quit» answered. + prep_quit_ask: bool, + prep_quit_ok: bool, + allow_quit: bool, + #[cfg(not(web))] + repertoire: Option, + #[cfg(not(web))] + toast_repertoire: Option<(trainer::repertoire::RepertoireId, String)>, + /// The database a copy of chosen games made: the toast's «Open». + toast_open_db: Option, + /// The search for great moves (task 27): its question, the list and conditions of + /// the pass under way, and its summary. + brilliant_start: Option, + brilliant_pass: Option, + brilliant_summary: Option, + /// A pass asked for while Stockfish 19 is fetched or checked: it starts after. + brilliant_waiting: Option, + /// The plies of the games the pass under way analyses, for its time left. + brilliant_plies: std::collections::HashMap, + applied_dark: Option, + debug: DebugStartup, +} + +/// What only the desktop program has. +#[cfg(not(web))] +struct Desktop { + /// Lichess / Chess.com: which answered at start, and the download window. + online_probe: crate::online::Probe, + /// When the online databases were last updated on their own (egui time, s), and + /// whether the window had the focus in the last frame. + online_updated_at: f64, + was_focused: bool, + online: crate::online_ui::OnlineDialog, + /// Updates: the release check, how this copy is installed, the window. + update_check: crate::update::Check, + update_kind: crate::update::Install, + update_ui: crate::update_ui::UpdateDialog, +} + +#[cfg(not(web))] +impl Desktop { + fn new(ctx: &egui::Context, settings: &Settings) -> Desktop { + let online_dbs: Vec = settings + .databases + .iter() + .filter(|p| crate::online::is_online(p)) + .cloned() + .collect(); + Desktop { + online_probe: crate::online::Probe::start(ctx), + online_updated_at: 0.0, + was_focused: true, + online: { + // Every downloaded database gets the games played since, at each start. + let mut d = crate::online_ui::OnlineDialog::from_env(); + d.update_quietly(online_dbs); + d + }, + update_check: if settings.check_updates { + crate::update::Check::start(ctx) + } else { + crate::update::Check::idle() + }, + update_kind: crate::update::detect(), + update_ui: crate::update_ui::UpdateDialog::from_env(), + } + } +} + +/// Dev-only startup automation for screenshots/manual QA (see docs/dev/desktop.md): +/// `CP_OPEN=` opens a game from the first database, `CP_PLY=` steps +/// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings (`=board`, `=about`: that tab), +/// `CP_REVIEW=1` starts the whole-game analysis (`=dialog` only opens its dialog, `=ask` +/// presses «Analyse»: the dialog or, the options chosen before, the analysis), +/// `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` presses these keys, one every half second +/// from the second second. +#[derive(Default)] +struct DebugStartup { + open: Option, + /// `CP_PLAY_FROM=white|black`: the game against Maia from the move reached. + play_from: Option, + ply: usize, + analyze: bool, + /// `CP_SCREENSHOT=`: go fullscreen, wait `CP_SCREENSHOT_DELAY` seconds, + /// save the window contents and quit (README screenshots without desktop overlays). + screenshot: Option, + screenshot_delay: f64, + screenshot_requested: bool, + open_settings: bool, + /// `CP_SETTINGS_CLICK=x,y`: one primary click in viewport points, after opening. + #[cfg(all(debug_assertions, not(web)))] + settings_click: Option, + /// `CP_OWN=new|chooser|data|save|delete`: that dialog of the own databases + /// (own_db.rs) after a short delay; `delete` and `chooser` without a game: the + /// record `CP_OPEN` (default 0) of the first database. + own: Option, + /// `CP_PLAY`: a game against Maia at start (see `debug_screenshot`). + play: Option, + keys: std::collections::VecDeque<(Modifiers, Key)>, + next_key: f64, + /// `CP_TYPE=`: typed into the field that has the keyboard, 2.5 s after start. + typed: Option, + /// `CP_PREP=`: «Prepare against…» for this name in the first database + /// (`CP_PREP_OPEN=1` presses «Open report», `CP_PREP_TAB`). + prep: Option, +} + +impl DebugStartup { + fn from_env() -> Self { + let num = |k| std::env::var(k).ok().and_then(|v| v.parse::().ok()); + Self { + open: num("CP_OPEN"), + play_from: None, + ply: num("CP_PLY").unwrap_or(0), + analyze: std::env::var("CP_ANALYZE").is_ok(), + screenshot: std::env::var_os("CP_SCREENSHOT").map(PathBuf::from), + screenshot_delay: std::env::var("CP_SCREENSHOT_DELAY") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(4.0), + screenshot_requested: false, + open_settings: false, + #[cfg(all(debug_assertions, not(web)))] + settings_click: std::env::var("CP_SETTINGS_CLICK").ok().and_then(|coords| { + let (x, y) = coords.split_once(',')?; + Some(egui::pos2(x.parse().ok()?, y.parse().ok()?)) + }), + own: std::env::var("CP_OWN").ok(), + play: std::env::var("CP_PLAY").ok(), + keys: std::env::var("CP_KEYS") + .unwrap_or_default() + .split_whitespace() + .filter_map(|k| { + // "Shift+ArrowUp", "Ctrl+Z", "Ctrl+Shift+S". + let mut mods = Modifiers::NONE; + let mut name = k; + loop { + if let Some(rest) = name.strip_prefix("Shift+") { + mods |= Modifiers::SHIFT; + name = rest; + } else if let Some(rest) = name.strip_prefix("Ctrl+") { + mods |= Modifiers::COMMAND; + name = rest; + } else { + break; + } + } + Key::from_name(name).map(|key| (mods, key)) + }) + .collect(), + next_key: 2.0, + typed: std::env::var("CP_TYPE").ok(), + prep: std::env::var("CP_PREP").ok(), + } + } +} + +impl App { + pub fn new(ctx: &egui::Context) -> Self { + let mut settings = Settings::load(); + let repertoire_migrated = settings.migrate_repertoire_flow(); + #[cfg(not(web))] + { + if let Ok(language) = std::env::var("CP_LANG") + && let Some(language) = crate::i18n::Lang::from_locale(&language) + { + settings.language = language; + } + if let Ok(dark) = std::env::var("CP_DARK") { + settings.dark_mode = dark != "0"; + } + // Dev hook (screenshots, tests): `CP_HINT_RESET=1` shows the one-time hints anew. + if std::env::var("CP_HINT_RESET").as_deref() == Ok("1") { + settings.hints = Default::default(); + } + } + // Before the samples, which are named in this language. + crate::i18n::set_lang(settings.language); + crate::engine_download::clean_leftovers(); + // Temporary files of copies of chosen games left by a crash: in the folders of the + // databases, away from the window's thread (a network drive may be slow). + #[cfg(not(web))] + { + let mut dirs: Vec = settings + .databases + .iter() + .filter_map(|p| p.parent().map(|d| d.to_path_buf())) + .collect(); + dirs.push(own_db::default_base_dir( + settings.new_database_dir.as_deref(), + )); + dirs.sort(); + dirs.dedup(); + let _ = std::thread::Builder::new() + .name("copy-leftovers".into()) + .spawn(move || crate::batch_copy::clean_orphans(&dirs)); + } + let current = env!("CARGO_PKG_VERSION"); + #[cfg(not(web))] + let updated_from = { + crate::update::clean_leftovers(); + // "Updated to …" once, when this version runs for the first time after another. + let from = settings.last_version.clone().filter(|v| { + crate::update::parse_version(v) < crate::update::parse_version(current) + }); + if settings.install_id.is_empty() { + settings.install_id = crate::update::new_install_id(); + } + crate::update::set_install_id(&settings.install_id); + from + }; + if settings.last_version.as_deref() != Some(current) { + settings.last_version = Some(current.to_owned()); + let _ = settings.save(); + } + let engines_found = crate::engines::first_run_setup(&mut settings); + if crate::examples::setup(&mut settings) || engines_found { + let _ = settings.save(); + } + // After the samples: a new library opens on the classics. + #[cfg(web)] + if crate::my_games::setup(&mut settings) { + let _ = settings.save(); + } + // PGN files passed on the command line (e.g. "Open with…") join the library, first one selected. + let args: Vec = std::env::args_os() + .skip(1) + .map(PathBuf::from) + .filter(|p| p.is_file()) + .collect(); + for p in args.iter().rev() { + let p = p.canonicalize().unwrap_or_else(|_| p.clone()); + settings.touch_database(&p); + } + if !args.is_empty() { + let _ = settings.save(); + } + #[cfg(not(web))] + let desktop = Desktop::new(ctx, &settings); + let (tx, rx) = channel(); + let mut library = Library::new(ctx); + // Read in the background: a missing file says so there (a lost network drive + // does not hold the start). + if let Some(first) = settings.databases.first() { + library.select_db(first, ctx); + } + let mut app = Self { + settings, + settings_dirty: repertoire_migrated, + sound: SoundPlayer::new(), + library, + game: None, + analysis: Analysis::new(), + live_paused: false, + settings_ui: SettingsWindow::new(), + toast: None, + own: Own::default(), + play_dialog: None, + put_aside: None, + aside_question: None, + aside_delete: false, + aside_fetch: None, + play_next: None, + tx, + rx, + pasting: None, + choosing_again: None, + #[cfg(web)] + draft_offer: crate::my_games::read_draft(), + #[cfg(web)] + draft_at: None, + #[cfg(web)] + web_notice: None, + confirm_close: None, + close_after_save: None, + find_after_close: None, + previous_games: Vec::new(), + reference_tab: false, + restart_to: None, + reference: Default::default(), + prep_dialog: None, + prep: None, + prep_list: None, + prep_waiting: None, + prep_quit_ask: false, + prep_quit_ok: false, + engine_offer: crate::engine_offer::EngineOffer::new(), + review_wait: Vec::new(), + offer_hook_done: false, + #[cfg(not(web))] + desktop, + translation: Default::default(), + allow_quit: false, + #[cfg(not(web))] + repertoire: None, + #[cfg(not(web))] + toast_repertoire: None, + toast_open_db: None, + brilliant_start: None, + brilliant_pass: None, + brilliant_summary: None, + brilliant_waiting: None, + brilliant_plies: std::collections::HashMap::new(), + applied_dark: None, + debug: DebugStartup::from_env(), + } + .with_debug_settings(); + crate::review_engine::set_candidates(&app.settings); + #[cfg(not(web))] + if let Some(from) = updated_from { + let msg = trf( + "ChessPenguin is updated: {from} → {to}", + &[("from", &from), ("to", ¤t)], + ); + app.toast(ctx, msg); + } + // Journals no program plays now: a game that can go on is put aside; finished + // games kept from their database and older ones go into it now. + let (written, aside) = crate::player_games::recover(); + let mut aside = aside; + let crashed = aside.as_ref().is_some_and(|a| a.crashed()); + if let Some(a) = aside.as_mut().filter(|_| crashed) { + // Said once: from now on it is a game put aside. + a.crash_said(); + } + app.set_aside(aside); + for r in written { + if r.put_aside { + app.written_unfinished(ctx, r); + continue; + } + let res = r.written.map_err(|e| { + let db = own_db::base_name(&r.target); + trf( + "Could not write to «{db}»: {reason}", + &[("db", &db), ("reason", &e)], + ) + }); + app.recorded(ctx, &r.player, res, true); + } + if crashed { + app.toast_for( + ctx, + tr("The program closed during a game: the game is put aside, you can go on with it"), + 6.0, + ); + } + app + } + + fn with_debug_settings(mut self) -> Self { + if let Ok(tab) = std::env::var("CP_SETTINGS") { + // Opened after a short delay (see debug_screenshot) so a fullscreen switch is done first. + self.debug.open_settings = true; + match tab.as_str() { + "board" => self.settings_ui.tab = Tab::Board, + "interface" => self.settings_ui.tab = Tab::Interface, + "about" => self.settings_ui.tab = Tab::About, + "translation" => self.settings_ui.tab = Tab::Translation, + _ => {} + } + } + // `CP_TRANSLATE_SETUP=1`: the "How to translate?" window (`=key`: with an API key chosen). + if let Ok(v) = std::env::var("CP_TRANSLATE_SETUP") { + self.translation + .debug_open_setup(&self.settings.translation, v == "key"); + } + self + } + + fn debug_keys(&mut self, ctx: &egui::Context) { + let now = ctx.input(|i| i.time); + if now >= 2.5 + && let Some(text) = self.debug.typed.take() + { + ctx.input_mut(|i| i.events.push(egui::Event::Text(text))); + } + if self.debug.keys.is_empty() { + return; + } + if now >= self.debug.next_key + && let Some((modifiers, key)) = self.debug.keys.pop_front() + { + self.debug.next_key = now + 0.5; + ctx.input_mut(|i| { + i.modifiers = modifiers; + i.events.push(egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers, + }); + }); + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + + fn debug_screenshot(&mut self, ctx: &egui::Context) { + // `CP_RESUME=1`: the game put aside goes on at once; `=ask`: a new game is asked + // for over it. + static RESUMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if let Ok(v) = std::env::var("CP_RESUME") + && self.put_aside.is_some() + && self.game.is_none() + && self.aside_question.is_none() + && ctx.input(|i| i.time) > 1.0 + && !RESUMED.swap(true, std::sync::atomic::Ordering::Relaxed) + { + if v == "ask" { + self.play_new(ctx, PlayNext::Dialog(None)); + } else { + self.resume_aside(ctx); + } + } + if self.debug.open_settings && ctx.input(|i| i.time) > 1.5 { + self.debug.open_settings = false; + self.settings_ui.open = true; + } + // `CP_PLAY=white|black[,5+3|none][,1500]`: a game against Maia starts at once; + // `CP_PLAY=dialog`: the play dialog. + if let Some(spec) = self.debug.play.take() { + if spec == "dialog" { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)); + } else { + let mut parts = spec.split(','); + let user = if parts.next() == Some("black") { + chess_core::shakmaty::Color::Black + } else { + chess_core::shakmaty::Color::White + }; + let clock = match parts.next() { + Some("none") => None, + Some(tc) => tc.split_once('+').and_then(|(m, i)| { + Some(crate::play::TimeControl { + base: m.parse::().ok()? * 60, + increment: i.parse().ok()?, + }) + }), + None => Some(crate::play::TimeControl { + base: 300, + increment: 3, + }), + }; + let strength = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1500); + self.start_play( + ctx, + crate::play::Start { + user, + strength, + rival: crate::play::debug_rival().0, + style: crate::play::debug_rival().1, + user_elo: self.settings.rating, + user_name: self.settings.your_name.clone(), + clock, + from: None, + }, + ); + } + } + if self.debug.own.is_some() && ctx.input(|i| i.time) > 1.5 { + let what = self.debug.own.take().unwrap_or_default(); + // `CP_PASTE=`: this game is open first (a game from no database). + if let Ok(text) = std::env::var("CP_PASTE") { + self.open_pgn_text(ctx, text, false); + } + let first = self.settings.databases.first().cloned(); + let index = self.debug.open.unwrap_or(0); + match (what.as_str(), first) { + ("new", _) => self.new_base_dialog(own_db::AfterCreate::Shelf), + ("chooser", _) if self.game.is_some() => { + self.open_chooser(ctx, ChooserFor::CurrentGame) + } + ("chooser", Some(path)) => { + self.open_chooser(ctx, ChooserFor::Record { path, index }) + } + ("data", _) => self.edit_game_data(), + // The table's «+ Game» for the first database. + ("newin", Some(path)) => { + self.new_game(); + if let Some(g) = self.game.as_mut() { + g.target = Some(path); + } + } + ("save", _) => self.save_current(ctx, None), + ("delete", Some(path)) => self.delete_game(ctx, path, index), + _ => {} + } + } + let Some(path) = self.debug.screenshot.clone() else { + return; + }; + let now = ctx.input(|i| i.time); + if !self.debug.screenshot_requested { + let size = std::env::var("CP_SCREENSHOT_SIZE").ok().and_then(|size| { + let (width, height) = size.split_once('x')?; + Some(egui::vec2(width.parse().ok()?, height.parse().ok()?)) + }); + if let Some(size) = size { + ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size)); + } else if ctx.cumulative_frame_nr() == 1 { + ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(true)); + } + if now >= self.debug.screenshot_delay { + self.debug.screenshot_requested = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(Default::default())); + } + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + let shot = ctx.input(|i| { + i.raw.events.iter().find_map(|e| match e { + egui::Event::Screenshot { image, .. } => Some(image.clone()), + _ => None, + }) + }); + if let Some(img) = shot { + let [w, h] = img.size; + let bytes: Vec = img.pixels.iter().flat_map(|c| c.to_array()).collect(); + if let Err(e) = + image::save_buffer(&path, &bytes, w as u32, h as u32, image::ColorType::Rgba8) + { + eprintln!("screenshot: {e}"); + } + self.allow_quit = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + + fn debug_step(&mut self, ctx: &egui::Context) { + #[cfg(not(web))] + if let Ok(what) = std::env::var("CP_REPERTOIRE") { + static OPEN: std::sync::Once = std::sync::Once::new(); + OPEN.call_once(|| { + self.repertoire = Some(crate::repertoire_ui::RepertoireUi::new()); + if let Some(screen) = self.repertoire.as_mut() { + screen.debug_open(&what, &mut self.settings); + } + }); + } + #[cfg(not(web))] + if let Ok(path) = std::env::var("CP_REPERTOIRE_IMPORT_FILE") { + static IMPORT: std::sync::Once = std::sync::Once::new(); + IMPORT.call_once(|| { + if let Some(screen) = self.repertoire.as_mut() { + screen.debug_import(PathBuf::from(path)); + } + }); + } + #[cfg(not(web))] + if std::env::var_os("CP_REPERTOIRE_EXPORT").is_some() { + static EXPORT: std::sync::Once = std::sync::Once::new(); + EXPORT.call_once(|| { + if let Some(screen) = self.repertoire.as_mut() { + screen.debug_export(); + } + }); + } + #[cfg(not(web))] + if std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some() + && let Some(screen) = self.repertoire.as_mut() + { + screen.debug_confirm_import(&self.settings); + } + #[cfg(not(web))] + if let Ok(name) = std::env::var("CP_REPERTOIRE_RENAME") { + static RENAME: std::sync::Once = std::sync::Once::new(); + if !RENAME.is_completed() { + let mut done = false; + if let Some(screen) = self.repertoire.as_mut() { + done = screen.debug_rename(name, &self.settings); + } + if done { + RENAME.call_once(|| {}); + } + } + } + #[cfg(not(web))] + if std::env::var_os("CP_REPERTOIRE_DELETE").is_some() { + static DELETE: std::sync::Once = std::sync::Once::new(); + if !DELETE.is_completed() { + let mut done = false; + if let Some(screen) = self.repertoire.as_mut() { + done = screen.debug_delete(&self.settings); + } + if done { + DELETE.call_once(|| {}); + } + } + } + #[cfg(not(web))] + if let Ok(moves) = std::env::var("CP_REPERTOIRE_MOVES") { + static MOVES: std::sync::Once = std::sync::Once::new(); + MOVES.call_once(|| { + if let Some(screen) = self.repertoire.as_mut() { + screen.debug_moves(&moves); + } + }); + } + #[cfg(not(web))] + if std::env::var_os("CP_REPERTOIRE_HINT").is_some() { + static HINT: std::sync::Once = std::sync::Once::new(); + HINT.call_once(|| { + if let Some(screen) = self.repertoire.as_mut() { + screen.debug_hint(); + } + }); + } + if self.debug.prep.is_some() + && let Some(path) = self.settings.databases.first().cloned() + && self.library.database(&path).is_some() + { + let query = self.debug.prep.take().unwrap_or_default(); + let side = match std::env::var("CP_PREP_COLOR").as_deref() { + Ok("white") => chess_import::chessbase::base::Side::White, + Ok("black") => chess_import::chessbase::base::Side::Black, + _ => chess_import::chessbase::base::Side::Any, + }; + let entry = crate::prep_ui::PrepEntry { + query, + exact: None, + side, + }; + self.prep_dialog = Some(PrepDialog::new(path, entry)); + } + // `CP_PREP_LIST=1`: the «Preparations» window at the start (screenshots). + if self.prep_list.is_none() && std::env::var_os("CP_PREP_LIST").is_some() { + static SHOWN: std::sync::Once = std::sync::Once::new(); + SHOWN.call_once(|| self.prep_list = Some(crate::prep_ui::PrepList::new())); + } + let Some(index) = self.debug.open else { return }; + let Some(path) = self.settings.databases.first().cloned() else { + return; + }; + if self.library.database(&path).is_none() { + return; + } + self.debug.open = None; + self.open_game(ctx, path, index, None); + if let Some(g) = &mut self.game { + g.debug_advance(self.debug.ply); + // `CP_COMMENT=text`: a comment on the move reached, so the game counts as + // modified (to try saving it). + if let Ok(text) = std::env::var("CP_COMMENT") { + g.debug_comment(&text); + } + if let Ok(spec) = std::env::var("CP_SHAPE") { + g.debug_shapes(&spec); + } + if std::env::var_os("CP_COMMENT_EDIT").is_some() { + g.debug_comment_edit(); + } + if let Ok(text) = std::env::var("CP_PASTE_LINE") { + g.debug_paste(&text); + } + // `CP_PLAY_FROM=dialog`: the play dialog from the move reached; + // `white|black[,strength]`: the game at once. + if let Ok(spec) = std::env::var("CP_PLAY_FROM") + && let Some(from) = g.debug_play_from() + { + let mut parts = spec.split(','); + let side = parts.next().unwrap_or("dialog"); + let strength = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1500); + let user = match side { + "white" => Some(chess_core::shakmaty::Color::White), + "black" => Some(chess_core::shakmaty::Color::Black), + _ => None, + }; + match user { + Some(user) => { + self.debug.play_from = Some(crate::play::Start { + rival: crate::play::debug_rival().0, + style: crate::play::debug_rival().1, + user, + strength, + user_elo: self.settings.rating, + user_name: self.settings.your_name.clone(), + clock: self.settings.play.clock, + from: Some(Box::new(from)), + }) + } + None => { + self.play_dialog = + Some(crate::play::Dialog::new_from(&self.settings, from)); + } + } + } + if std::env::var("CP_ENGINE_PANEL").is_ok() { + g.debug_open_engine_settings(); + } + if std::env::var("CP_REPORT").is_ok() { + g.debug_show_report(); + } + if let Some(k) = std::env::var("CP_BEST").ok().and_then(|v| v.parse().ok()) { + // `CP_BEST_DELAY=`: the line opens that long after the notation is first + // drawn (`CP_BEST_EXIT_AFTER=`: and closes that long after it opened). + let ms = |name| { + std::env::var(name) + .ok() + .and_then(|v| v.parse::().ok()) + .map(|ms| ms as f64 / 1000.0) + }; + match ms("CP_BEST_DELAY") { + Some(delay) => g.debug_best_line_later(k, delay, ms("CP_BEST_EXIT_AFTER")), + None => g.debug_best_line(k), + } + } + // CP_REVIEW=ask presses «Analyse», any other value starts the analysis. + if let Ok(v) = std::env::var("CP_REVIEW") { + g.debug_review(ctx, &v); + } + } + #[cfg(not(web))] + { + static ADD_REPERTOIRE: std::sync::Once = std::sync::Once::new(); + if let Ok(name) = std::env::var("CP_ADD_REPERTOIRE") + && !ADD_REPERTOIRE.is_completed() + && let Some((game, at)) = + self.game.as_ref().and_then(|g| g.debug_repertoire_source()) + { + ADD_REPERTOIRE.call_once(|| {}); + let title = self.game.as_ref().map(GameView::title).unwrap_or_default(); + if let Some(game_view) = self.game.as_mut() { + game_view.suspend(); + } + self.analysis.stop(); + self.repertoire = Some(crate::repertoire_ui::RepertoireUi::new()); + if let Some(screen) = self.repertoire.as_mut() { + screen.debug_add_from_game(game, at, title, name); + } + } + } + if let Some(start) = self.debug.play_from.take() { + self.start_play(ctx, start); + } + // `CP_TRAIN=1`: learning the opening up to the move reached; `CP_TRAIN_MOVES`: + // moves made in it (UCI). + if std::env::var_os("CP_TRAIN").is_some() + && let Some(start) = self.game.as_ref().and_then(|g| g.debug_train()) + { + self.open_training(start); + if let (Ok(moves), Some(g)) = (std::env::var("CP_TRAIN_MOVES"), self.game.as_mut()) { + g.debug_train_moves(&moves); + } + } + if self.debug.analyze { + self.toggle_engine(ctx); + } + } + + fn toast(&mut self, ctx: &egui::Context, msg: impl Into) { + self.toast_for(ctx, msg, 3.5); + } + + /// The shelf as the reference tab and the preparation see it. + fn shelf_dbs(&self) -> Vec { + self.settings + .databases + .iter() + .filter(|p| self.library.files.exists(p)) + .map(|p| crate::reference::RefDb { + path: p.clone(), + name: p + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(), + db: self.library.database(p), + failed: self.library.failure(p).map(str::to_owned), + bytes: self.library.file_size(p), + }) + .collect() + } + + // ----- preparing against an opponent (docs/design/opponent-prep.md) ------------ + + /// «Open report»: the report of the same player as it was, else a new one. + fn open_prep(&mut self, ctx: &egui::Context, start: crate::prep_ui::PrepStart) { + let Some(db) = self.library.database(&start.path) else { + return; + }; + if let Some(p) = self.prep.as_mut() + && p.matches(&start.path, &start.player) + { + // The report as it was, with the colour of the dialog. + p.reopen(start.side); + return; + } + if let Some(mut old) = self.prep.take() { + old.save(); + } + self.prep = Some(PrepScreen::new(start, db, &self.settings, ctx)); + } + + /// «Opening errors are being searched. Quit and stop?» + fn prep_quit_question(&mut self, ctx: &egui::Context) { + if !self.prep_quit_ask { + return; + } + let mut choice = None; + egui::Modal::new(egui::Id::new("prep_quit")).show(ctx, |ui| { + ui.set_width(400.0); + ui.label(tr("Opening errors are being searched. Quit and stop?")); + ui.label(RichText::new(tr("What was found is kept.")).weak()); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Cancel")).clicked() { + choice = Some(false); + } + if crate::widgets::primary(ui, tr("Quit")).clicked() { + choice = Some(true); + } + }); + }); + if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { + choice = Some(false); + } + match choice { + Some(true) => { + self.prep_quit_ask = false; + self.prep_quit_ok = true; + if let Some(p) = self.prep.as_mut() { + p.stop(); + } + // The usual way out from here (unsaved games are asked about). + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + Some(false) => self.prep_quit_ask = false, + None => {} + } + } + + /// «ðŸ—� Preparations», and a saved preparation opened once its database is read. + fn prep_list(&mut self, ctx: &egui::Context) { + if let Some((mut start, names)) = self.prep_waiting.take() { + if let Some(db) = self.library.database(&start.path) { + // The player by his names: the database's ids of them may have changed. + let mut ids = Vec::new(); + let mut missing = None; + for name in &names { + // Every id of the name (a ChessBase database can have two). + let (found, _) = prep::candidates(&db, name, 50); + let before = ids.len(); + ids.extend(found.iter().filter(|c| c.name == *name).map(|c| c.id)); + if ids.len() == before { + missing = Some(name.clone()); + } + } + match missing { + Some(name) => self.toast( + ctx, + trf( + "The player is not in the database: {name}", + &[("name", &name)], + ), + ), + None => { + start.player = prep::Player::new(ids); + self.open_prep(ctx, start); + } + } + } else if let Some(e) = self.library.failure(&start.path) { + let e = e.to_owned(); + self.toast( + ctx, + trf("This database cannot be opened: {e}", &[("e", &e)]), + ); + } else { + self.prep_waiting = Some((start, names)); + } + } + let Some(list) = self.prep_list.as_mut() else { + return; + }; + let can_new = !self.settings.databases.is_empty(); + match list.show(ctx, can_new) { + Some(crate::prep_ui::ListOutcome::Close) => self.prep_list = None, + Some(crate::prep_ui::ListOutcome::New) => { + self.prep_list = None; + let (path, entry) = match self.library.prep_entry() { + Some((path, entry)) => (path, entry.unwrap_or_default()), + None => match self.settings.databases.first() { + Some(p) => (p.clone(), Default::default()), + None => return, + }, + }; + self.prep_dialog = Some(PrepDialog::new(path, entry)); + } + Some(crate::prep_ui::ListOutcome::Open(id)) => { + let Some(meta) = crate::prep_saved::dir() + .as_deref() + .and_then(|d| crate::prep_saved::get(d, &id)) + else { + return; + }; + self.prep_list = None; + if !self.settings.databases.contains(&meta.path) { + self.settings.touch_database(&meta.path); + self.settings_dirty = true; + } + let start = crate::prep_ui::PrepStart { + path: meta.path, + player: meta.player, + side: meta.color, + }; + if self.library.database(&start.path).is_none() { + self.library.load(&start.path, ctx); + self.toast(ctx, tr("Opening the database…")); + } + self.prep_waiting = Some((start, meta.names)); + ctx.request_repaint(); + } + None => {} + } + } + + /// The preparation's dialog, when it is open. + fn prep_dialog(&mut self, ctx: &egui::Context) { + if self.prep_dialog.is_none() { + return; + } + let dbs = self.shelf_dbs(); + let Some(d) = self.prep_dialog.as_mut() else { + return; + }; + d.dbs = dbs; + let outcome = d.show(ctx, &mut self.settings); + match outcome { + Some(DialogOutcome::Open(start)) => { + self.prep_dialog = None; + self.settings_dirty = true; + self.open_prep(ctx, start); + } + Some(DialogOutcome::Cancel) => self.prep_dialog = None, + Some(DialogOutcome::LoadDb(p)) + if !self.library.loading(&p) && self.library.database(&p).is_none() => + { + self.library.load(&p, ctx); + } + Some(DialogOutcome::LoadDb(_)) | None => {} + } + } + + fn prep_actions(&mut self, ctx: &egui::Context, actions: Vec) { + for a in actions { + match a { + PrepAction::Back => { + if let Some(p) = self.prep.as_mut() { + p.shown = false; + p.save(); + } + } + PrepAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open, + PrepAction::OpenGame { path, index, ply } => { + let title = self.prep.as_ref().map(|p| p.title()); + self.open_game(ctx, path, index, None); + if let Some(g) = self.game.as_mut() { + g.previous = title; + g.previous_prep = true; + g.goto_ply(ply); + } + } + // One engine job for the whole program: the live engine is off while + // the report is on the screen anyway (no game is open then). + PrepAction::EngineStarted => { + self.analysis.stop(); + self.live_paused = false; + } + PrepAction::EngineEnded => {} + PrepAction::NeedEngine => { + if let Some(prep) = self.prep.as_ref().map(|p| p.serial) { + let pending = crate::engine_offer::Pending::OpeningErrors { prep }; + self.need_review_engine(ctx, pending); + } + } + PrepAction::SettingsChanged => self.settings_dirty = true, + PrepAction::Toast(m) => self.toast(ctx, m), + PrepAction::CopyText(text, msg) => { + ctx.copy_text(text); + self.toast(ctx, msg); + } + PrepAction::OpenPgn(text) => { + let title = self.prep.as_ref().map(|p| p.title()); + self.open_pgn_text(ctx, text, true); + if let Some(g) = self.game.as_mut() { + g.previous = title; + g.previous_prep = true; + } + } + PrepAction::FindPosition(path, start, line, flipped) => { + if let Some(p) = self.prep.as_mut() { + p.shown = false; + } + self.library.show_position(&path, start, line, flipped, ctx); + } + PrepAction::PlayFrom(from) => self.play_new(ctx, PlayNext::Dialog(Some(from))), + } + } + } + + /// A message said once and seldom (a database made for the player): longer in view. + fn toast_for(&mut self, ctx: &egui::Context, msg: impl Into, secs: f64) { + #[cfg(not(web))] + { + self.toast_repertoire = None; + } + self.toast_open_db = None; + self.toast = Some(Toast { + text: msg.into(), + until: ctx.input(|i| i.time) + secs, + undo: false, + }); + } + + // ----- own databases (docs/design/own-databases.md) -------------------------------- + + /// The game on the screen, when there is one. + fn game_view(&mut self) -> Option<&mut GameView> { + self.game.as_mut() + } + + /// Ctrl+S: a game from a PGN that takes games is saved back into it; any other game + /// is added to a database of the user's choice. + fn save_current(&mut self, ctx: &egui::Context, then_close: Option) { + // A comment being written goes into the game first. + if let Some(g) = self.game.as_mut() { + g.commit_editor(); + } + let target = self.current_target(); + let Some(g) = &self.game else { return }; + self.own.then_close = then_close; + // The web version keeps the user's games in «My games»: a game from anywhere + // else (a file, which is only read, a sample, a new one) goes there, no question. + #[cfg(web)] + if !matches!(&g.source, Some(src) if src.block.is_none()) { + if crate::platform::web::storage::persisted() != Some(true) { + crate::platform::web::storage::persist(|_| {}); + } + self.add_current_to(ctx, crate::my_games::path()); + return; + } + match &g.source { + Some(src) if src.block.is_none() => { + if !g.game.is_modified() { + self.toast(ctx, tr("No changes to save")); + self.finish_then_close(ctx); + return; + } + let path = src.path.clone(); + let bytes = self.library.file_size(&path); + if bytes > own_db::BIG_REWRITE_BYTES && !self.own.big_advised.contains(&path) { + self.own.big_advised.insert(path.clone()); + self.ask(QuestionKind::BigBase { path, bytes }, QuestionThen::BigBase); + return; + } + self.replace_current(ctx); + } + // A new game meant for a database (the table's «+ Game»): straight there. + None if let Some(t) = target => self.add_current_to(ctx, t), + _ => self.open_chooser(ctx, ChooserFor::CurrentGame), + } + } + + /// The database the new game on the screen is meant for, while it still takes games + /// and is on the shelf; else the target is dropped. + fn current_target(&mut self) -> Option { + let g = self.game.as_mut()?; + let t = g.target.clone()?; + if g.source.is_some() + || !self.settings.databases.contains(&t) + || self.library.write_block(&t).is_some() + { + g.target = None; + return None; + } + Some(t) + } + + /// Writes the game over its record in its own PGN. + fn replace_current(&mut self, ctx: &egui::Context) { + let Some(g) = &self.game else { return }; + let Some(src) = g.source.clone() else { return }; + let Some(db) = self.library.database(&src.path) else { + self.wait_for(ctx, &src.path, Pending::Replace); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + let text = g.game.to_pgn(); + match crate::platform::pgn_store::replace(pgn, &src.path, src.index, &text) { + Ok(()) => { + let name = own_db::base_name(&src.path); + if let Some(g) = self.game.as_mut() { + g.game.mark_saved(); + } + self.after_written( + ctx, + &src.path, + src.index, + trf("Saved to «{name}»", &[("name", &name)]), + ); + } + Err(e) => self.write_failed(ctx, &src.path, e, Retry::Replace, false), + } + } + + /// The shelf for the chooser: each database with its count and what blocks it. + fn chooser_rows(&self) -> Vec { + self.settings + .databases + .iter() + .map(|p| own_db::ChooserRow { + path: p.clone(), + name: own_db::base_name(p), + games: self.library.database(p).map(|d| d.len()), + block: self.library.write_block(p), + }) + .collect() + } + + /// The list of databases to add a game to. + fn open_chooser(&mut self, ctx: &egui::Context, purpose: ChooserFor) { + let rows = self.chooser_rows(); + let title = match &purpose { + ChooserFor::CurrentGame => self.game.as_ref().map(|g| g.title()).unwrap_or_default(), + ChooserFor::Record { path, index } => self + .library + .database(path) + .and_then(|db| db.load_game(*index)) + .map(|p| GameView::new(p.game, None, Vec::new()).title()) + .unwrap_or_default(), + }; + let source = self + .game + .as_ref() + .and_then(|g| g.source.as_ref()) + .map(|s| s.path.clone()); + let target = self.current_target(); + let preselect = target.or(self.settings.last_target.clone()).or(source); + // Databases not read yet are read now, for their counts and encodings. + for p in self.settings.databases.clone() { + if self.library.database(&p).is_none() && self.library.files.exists(&p) { + self.library.load(&p, ctx); + } + } + self.own.chooser = Some(own_db::Chooser::new( + rows, + preselect.as_deref(), + purpose, + title, + )); + } + + fn ask(&mut self, kind: QuestionKind, then: QuestionThen) { + self.own.question = Some((own_db::Question { kind }, then)); + } + + /// The game on the screen goes to `target`: its data are asked once for a game that + /// is in no database yet, then the duplicate check, then the write. + fn add_current_to(&mut self, ctx: &egui::Context, target: PathBuf) { + let Some(g) = &self.game else { return }; + if g.source.is_none() && !g.data_asked { + let editor = own_db::DataEditor::from_game( + &g.game, + &self.settings.your_name, + EditorMode::Add(target.clone()), + ); + self.own.editor = Some((editor, EditorThen::Add(target))); + return; + } + self.add_current_now(ctx, target); + } + + fn add_current_now(&mut self, ctx: &egui::Context, target: PathBuf) { + let Some(g) = &self.game else { return }; + let Some(db) = self.library.database(&target) else { + self.wait_for(ctx, &target, Pending::AddCurrent(target.clone())); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + if let Some(index) = chess_core::pgn::store::find_same_game(pgn, &g.game) { + let title = g.title(); + self.ask( + QuestionKind::Duplicate { + target: target.clone(), + index, + title, + }, + QuestionThen::Duplicate { target, index }, + ); + return; + } + self.append_current(ctx, target); + } + + /// The PGN text of the game on the screen: the original record when it is an + /// unchanged game of a PGN file, else written anew. A source whose letters are + /// restored on reading (ч/ÑŽ written as `~~`/`o^`) is written anew too: the copy + /// gets the restored text. + fn current_pgn(&self) -> Option { + let g = self.game.as_ref()?; + if !g.game.is_modified() + && let Some(src) = &g.source + && let Some(db) = self.library.database(&src.path) + && let Some(pgn) = db.as_pgn() + && !pgn.repair_letters_enabled() + && let Some(text) = db.raw_text(src.index) + { + return Some(text); + } + Some(g.game.to_pgn()) + } + + /// The PGN text of record `index` of a database, as `current_pgn` would give it. + fn record_pgn(&self, from: &std::path::Path, index: usize) -> Option { + let db = self.library.database(from)?; + crate::batch_copy::record_text(&db, index) + } + + fn append_current(&mut self, ctx: &egui::Context, target: PathBuf) { + let Some(text) = self.current_pgn() else { + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match crate::platform::pgn_store::append(pgn, &target, &text) { + Ok(_) => { + let index = pgn.len(); + let name = own_db::base_name(&target); + if let Some(g) = self.game.as_mut() { + g.source = Some(GameSource { + path: target.clone(), + index, + block: None, + }); + g.target = None; + g.game.mark_saved(); + g.unwritten = None; + } + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.after_written( + ctx, + &target, + index, + trf( + "Added to «{name}» (No. {n})", + &[("name", &name), ("n", &(index + 1))], + ), + ); + } + Err(e) => self.write_failed(ctx, &target, e, Retry::Append(target.clone()), false), + } + } + + /// The game on the screen replaces record `index` of `target` (a duplicate). + fn replace_in(&mut self, ctx: &egui::Context, target: PathBuf, index: usize) { + let Some(text) = self.current_pgn() else { + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match crate::platform::pgn_store::replace(pgn, &target, index, &text) { + Ok(()) => { + let name = own_db::base_name(&target); + if let Some(g) = self.game.as_mut() { + g.source = Some(GameSource { + path: target.clone(), + index, + block: None, + }); + g.game.mark_saved(); + g.unwritten = None; + } + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.after_written( + ctx, + &target, + index, + trf( + "Saved to «{name}» (No. {n})", + &[("name", &name), ("n", &(index + 1))], + ), + ); + } + Err(e) => self.write_failed( + ctx, + &target, + e, + Retry::ReplaceIn { + target: target.clone(), + index, + }, + false, + ), + } + } + + /// A record of a table goes into `target`: the duplicate check first. + fn append_record(&mut self, ctx: &egui::Context, from: PathBuf, index: usize, target: PathBuf) { + let Some(db) = self.library.database(&target) else { + self.wait_for( + ctx, + &target, + Pending::AppendRecord { + from, + index, + target: target.clone(), + }, + ); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + let Some(parsed) = self + .library + .database(&from) + .and_then(|d| d.load_game(index)) + else { + self.toast(ctx, tr("Could not read the game")); + return; + }; + if let Some(at) = chess_core::pgn::store::find_same_game(pgn, &parsed.game) { + let title = GameView::new(parsed.game, None, Vec::new()).title(); + self.ask( + QuestionKind::Duplicate { + target: target.clone(), + index: at, + title, + }, + QuestionThen::DuplicateRecord { + from, + index, + target, + at, + }, + ); + return; + } + self.append_record_now(ctx, from, index, target); + } + + fn append_record_now( + &mut self, + ctx: &egui::Context, + from: PathBuf, + index: usize, + target: PathBuf, + ) { + let Some(text) = self.record_pgn(&from, index) else { + self.toast(ctx, tr("Could not read the game")); + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match crate::platform::pgn_store::append(pgn, &target, &text) { + Ok(_) => { + let n = pgn.len(); + let name = own_db::base_name(&target); + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.library.reload(&target, ctx); + self.toast( + ctx, + trf( + "Added to «{name}» (No. {n})", + &[("name", &name), ("n", &(n + 1))], + ), + ); + } + Err(e) => self.write_failed( + ctx, + &target, + e, + Retry::AppendRecord { + from, + index, + target: target.clone(), + }, + false, + ), + } + } + + /// A record of a table replaces record `at` of `target` (its duplicate). + fn replace_record( + &mut self, + ctx: &egui::Context, + from: PathBuf, + index: usize, + target: PathBuf, + at: usize, + ) { + let Some(text) = self.record_pgn(&from, index) else { + self.toast(ctx, tr("Could not read the game")); + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match crate::platform::pgn_store::replace(pgn, &target, at, &text) { + Ok(()) => { + let name = own_db::base_name(&target); + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.library.reload(&target, ctx); + self.toast( + ctx, + trf( + "Saved to «{name}» (No. {n})", + &[("name", &name), ("n", &(at + 1))], + ), + ); + } + Err(e) => self.write_failed( + ctx, + &target, + e, + Retry::ReplaceIn { + target: target.clone(), + index: at, + }, + false, + ), + } + } + + /// A step that needs the database read: it runs once the file is in (`run_pending`). + fn wait_for(&mut self, ctx: &egui::Context, path: &std::path::Path, step: Pending) { + if !self.library.loading(path) && self.library.database(path).is_none() { + self.library.load(path, ctx); + } + self.own.pending = Some(step); + } + + /// The database a step waits for is read: the step runs. Could not be read: said. + fn run_pending(&mut self, ctx: &egui::Context) { + let Some(step) = self.own.pending.as_ref() else { + return; + }; + let Some(path) = step.path(self.game.as_ref(), self.own.undo.as_ref()) else { + self.own.pending = None; + return; + }; + if self.library.database(&path).is_some() { + match self.own.pending.take().expect("pending") { + Pending::AddCurrent(target) => self.add_current_to(ctx, target), + Pending::AppendRecord { + from, + index, + target, + } => self.append_record(ctx, from, index, target), + Pending::Replace => self.replace_current(ctx), + Pending::Undo => self.undo_delete(ctx), + } + } else if !self.library.loading(&path) { + self.own.pending = None; + let why = self.library.failure(&path).unwrap_or("?").to_owned(); + self.toast(ctx, trf("Could not read the database: {e}", &[("e", &why)])); + } else { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + + /// The file is written: the library reads it again and shows the record. + fn after_written( + &mut self, + ctx: &egui::Context, + path: &std::path::Path, + index: usize, + msg: String, + ) { + self.library.reload(path, ctx); + self.library.reveal(path, index); + self.toast(ctx, msg); + self.finish_then_close(ctx); + } + + fn finish_then_close(&mut self, ctx: &egui::Context) { + if let Some(intent) = self.own.then_close.take() { + self.finish_close(ctx, intent); + } + } + + fn write_failed( + &mut self, + ctx: &egui::Context, + path: &std::path::Path, + e: chess_core::pgn::store::WriteError, + retry: Retry, + deleting: bool, + ) { + use chess_core::pgn::store::WriteError; + match e { + WriteError::Changed => { + self.library.reload(path, ctx); + self.ask( + QuestionKind::ChangedOnDisk { + path: path.to_path_buf(), + deleting, + }, + QuestionThen::Changed(retry), + ); + } + e => self.ask( + QuestionKind::WriteFailed { + path: path.to_path_buf(), + error: e.to_string(), + deleting, + }, + QuestionThen::Retry(retry), + ), + } + } + + fn retry(&mut self, ctx: &egui::Context, retry: Retry) { + match retry { + Retry::Replace => self.replace_current(ctx), + Retry::ReplaceIn { target, index } => self.replace_in(ctx, target, index), + Retry::Append(target) => self.append_current(ctx, target), + Retry::AppendRecord { + from, + index, + target, + } => self.append_record(ctx, from, index, target), + Retry::Delete { path, index } => self.delete_now(ctx, path, index), + } + } + + fn delete_game(&mut self, ctx: &egui::Context, path: PathBuf, index: usize) { + if let Some(block) = self.library.write_block(&path) { + self.toast(ctx, block.long()); + return; + } + let title = self + .library + .database(&path) + .and_then(|db| db.load_game(index)) + .map(|p| GameView::new(p.game, None, Vec::new()).title()) + .unwrap_or_default(); + self.ask( + QuestionKind::Delete { + path: path.clone(), + index, + title, + }, + QuestionThen::Delete { path, index }, + ); + } + + fn delete_now(&mut self, ctx: &egui::Context, path: PathBuf, index: usize) { + let Some(db) = self.library.database(&path) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match crate::platform::pgn_store::remove(pgn, &path, index) { + Ok(removed) => { + // Games open from this file: their records moved up by one. + let mut open = None; + for g in self.game.iter_mut().chain(self.previous_games.iter_mut()) { + if let Some(s) = &mut g.source + && s.path == path + { + if s.index == index { + open = g.source.take(); + } else if s.index > index { + s.index -= 1; + } + } + } + self.own.undo = Some(UndoDelete { + path: path.clone(), + removed, + open, + }); + self.library.reload(&path, ctx); + self.library.reveal(&path, index); + self.toast = Some(Toast { + text: trf( + "Deleted from «{name}»", + &[("name", &own_db::base_name(&path))], + ), + until: ctx.input(|i| i.time) + 6.0, + undo: true, + }); + } + Err(e) => self.write_failed( + ctx, + &path, + e, + Retry::Delete { + path: path.clone(), + index, + }, + true, + ), + } + } + + /// Puts the last deleted record back (the toast's Undo, Ctrl+Z on the library). + fn undo_delete(&mut self, ctx: &egui::Context) { + let Some(undo) = self.own.undo.take() else { + return; + }; + let Some(db) = self.library.database(&undo.path) else { + // The file is still being read after the delete: as soon as it is in. + let path = undo.path.clone(); + self.own.undo = Some(undo); + self.wait_for(ctx, &path, Pending::Undo); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match crate::platform::pgn_store::restore(pgn, &undo.path, &undo.removed) { + Ok(()) => { + let index = undo.removed.index; + for g in self.game.iter_mut().chain(self.previous_games.iter_mut()) { + if let Some(s) = &mut g.source + && s.path == undo.path + && s.index >= index + { + s.index += 1; + } + } + // The open game was the deleted record: it is that record again. + if let Some(src) = undo.open + && let Some(g) = self.game.as_mut() + && g.source.is_none() + { + g.source = Some(src); + } + self.library.reload(&undo.path, ctx); + self.library.reveal(&undo.path, index); + self.toast(ctx, tr("The game is back")); + } + Err(e) => self.toast(ctx, trf("Could not put the game back: {e}", &[("e", &e)])), + } + } + + /// A UTF-8 copy of a PGN in a legacy encoding (the card's menu): asked first. + fn utf8_copy(&mut self, path: PathBuf) { + let encoding = match self.library.write_block(&path) { + Some(own_db::Block::Encoding(e)) => e, + _ => return, + }; + // "X (UTF-8).pgn", or "X (UTF-8 2).pgn" when that is taken. + let stem = own_db::base_name(&path); + let dest = (1..) + .map(|k| { + let n = if k == 1 { + String::new() + } else { + format!(" {k}") + }; + path.with_file_name(format!("{stem} (UTF-8{n}).pgn")) + }) + .find(|p| !p.exists()) + .expect("a free name"); + self.ask( + QuestionKind::Utf8Copy { + path: path.clone(), + dest: dest.clone(), + encoding, + }, + QuestionThen::Utf8Copy { path, dest }, + ); + } + + fn new_base_dialog(&mut self, after: own_db::AfterCreate) { + let dir = own_db::default_base_dir(self.settings.new_database_dir.as_deref()); + self.own.new_base = Some(own_db::NewBaseDialog::new(dir, after)); + } + + /// Why the engine cannot take the search for great moves now, if it cannot (one engine + /// job in the program, task 27 §4.5). + fn engine_job_busy(&self) -> Option { + if self.prep.as_ref().is_some_and(|p| p.running()) { + return Some( + tr("The engine is busy searching opening errors in a preparation: wait or stop it") + .to_owned(), + ); + } + if let Some(g) = self.game.as_ref().filter(|g| g.review_running()) { + return Some(trf( + "The engine is busy reviewing {game}", + &[("game", &g.title())], + )); + } + None + } + + /// While the search for great moves runs, what cannot start says why. + fn pass_busy(&self) -> Option { + let job = self.library.pass.as_ref()?; + Some(trf( + "Searching for great moves in «{db}»: {i} of {n}. Stop it in the library", + &[ + ("db", &own_db::base_name(&job.source)), + ("i", &job.done()), + ("n", &job.records.len()), + ], + )) + } + + /// «!! Find great moves»: the question first (or the summary, when every game is + /// analysed already). + fn ask_great_moves( + &mut self, + ctx: &egui::Context, + path: PathBuf, + records: Vec, + filter: chess_import::chessbase::base::Filter, + about: String, + selected: Option, + ) { + if self.library.pass.is_some() { + return; + } + if let Some(why) = self.engine_job_busy() { + self.toast(ctx, why); + return; + } + let (Some(db), Some(cache)) = (self.library.database(&path), crate::review::cache_dir()) + else { + return; + }; + let index = self.library.marks(&path); + let mut dialog = crate::brilliant_ui::StartDialog::new( + ctx, path, db, records, filter, about, selected, cache, index, + ); + // `CP_BRILLIANT_RUN=1`: no question. + if std::env::var_os("CP_BRILLIANT_RUN").is_some() { + let cancel = std::sync::atomic::AtomicBool::new(false); + if let (Some(db), Some(cache)) = ( + self.library.database(&dialog.source), + crate::review::cache_dir(), + ) { + let index = self.library.marks(&dialog.source); + dialog.counted = Some(crate::brilliant_ui::count( + &db, + &dialog.records, + &dialog.filter, + &cache, + &index, + &cancel, + )); + } + self.start_great_moves(ctx, dialog); + return; + } + self.brilliant_start = Some(dialog); + } + + /// Starts the pass of `dialog` over its games not analysed yet (a browser has none: + /// `CAPS.great_moves`). + #[cfg(web)] + fn start_great_moves( + &mut self, + _ctx: &egui::Context, + _dialog: crate::brilliant_ui::StartDialog, + ) { + } + + /// Starts the pass of `dialog` over its games not analysed yet. + #[cfg(not(web))] + fn start_great_moves(&mut self, ctx: &egui::Context, dialog: crate::brilliant_ui::StartDialog) { + let mut dialog = dialog; + let Some(counted) = dialog.counted.take() else { + return; + }; + let Some(crate::engines::EngineLocation::Program(engine)) = crate::review_engine::engine() + else { + // The offer of «Analyse game»: download Stockfish 19 (or check the user's); + // the pass starts after it. + dialog.counted = Some(counted); + self.brilliant_waiting = Some(dialog); + self.need_review_engine(ctx, crate::engine_offer::Pending::GreatMoves); + return; + }; + let (Some(db), Some(cache)) = ( + self.library.database(&dialog.source), + crate::review::cache_dir(), + ) else { + return; + }; + // One engine job: the live analysis stops. + if self.analysis.is_on() { + self.analysis.stop(); + self.live_paused = false; + } + let path = engine.clone(); + let engine = crate::brilliant::Engine { + config: crate::review::engine_config(&engine), + settings: game_review::JobSettings::new(crate::review::processes(), None), + fits: Box::new(move |name| crate::review_engine::name_fits(&path, name)), + pause: if std::env::var_os("CP_BRILLIANT_SLOW").is_some() { + std::time::Duration::from_millis(1500) + } else { + std::time::Duration::ZERO + }, + }; + let index = self.library.marks(&dialog.source); + // The list in the table's order: the analysed ones are taken first (at once). + let mut list = counted.reviewed.clone(); + list.extend(&counted.left); + self.brilliant_plies = counted + .left + .iter() + .copied() + .zip(counted.plies_left.iter().copied()) + .collect(); + let order: std::collections::HashMap = dialog + .records + .iter() + .enumerate() + .map(|(i, r)| (*r, i)) + .collect(); + list.sort_by_key(|r| order.get(r).copied().unwrap_or(usize::MAX)); + match crate::brilliant::PassJob::start( + ctx, + dialog.source.clone(), + db, + list, + dialog.filter.clone(), + dialog.selected, + index, + cache, + engine, + ) { + Ok(job) => { + self.library.set_pass_error(&dialog.source, None); + self.library.pass = Some(job); + self.brilliant_pass = Some(( + dialog.filter.clone(), + dialog.about.clone(), + dialog.selected, + counted.skipped, + )); + } + Err(e) => self.toast(ctx, e.to_string()), + } + } + + /// The summary of `records` of `source`. + #[allow(clippy::too_many_arguments)] + fn great_moves_summary( + &mut self, + source: &std::path::Path, + records: &[u32], + sides: &crate::brilliant::Sides, + filter: &chess_import::chessbase::base::Filter, + about: String, + selected: Option, + stopped: Option<(usize, usize)>, + skipped: Vec<(u32, crate::brilliant::Skip)>, + ) { + let Some(db) = self.library.database(source) else { + return; + }; + let index = self.library.marks(source); + let Ok(index) = index.lock() else { + return; + }; + self.brilliant_summary = Some(crate::brilliant_ui::Summary::new( + source, &db, &index, records, sides, filter, about, selected, stopped, skipped, + )); + } + + /// Every frame: the pass's state in the conditions lines, its end, the question and + /// the summary; and the engine taken by the pass for everything else. + fn great_moves_frame(&mut self, ctx: &egui::Context) { + let busy = self.engine_job_busy(); + self.library.set_engine_busy(busy); + let pass_busy = self.pass_busy(); + if let Some(p) = self.prep.as_mut() { + p.engine_blocked = pass_busy; + } + let plies = &self.brilliant_plies; + let estimate = |rest: &[u32]| { + crate::brilliant::estimate_secs( + rest.iter().filter_map(|r| plies.get(r).copied()), + crate::review::processes(), + ) + }; + self.library.show_pass(estimate); + // `CP_BRILLIANT_STOP_AFTER=`: «Stop» pressed that long after the start. + if let Some(ms) = std::env::var("CP_BRILLIANT_STOP_AFTER") + .ok() + .and_then(|ms| ms.parse::().ok()) + && let Some(job) = self.library.pass.as_mut() + && !job.stopping + && job.started.elapsed() >= std::time::Duration::from_millis(ms) + { + job.stop(); + } + if let Some(job) = self.library.pass.as_ref() + && let Some((end, sides)) = job.poll() + { + let job = self.library.pass.take().expect("pass"); + let (filter, about, selected, mut skipped) = + self.brilliant_pass.take().unwrap_or_default(); + skipped.extend(end.skipped.iter().copied()); + skipped.sort_unstable_by_key(|(r, _)| *r); + skipped.dedup(); + let reviewed = end.reviewed.len(); + let total = job.records.len(); + match &end.outcome { + crate::brilliant::Outcome::Finished => self.great_moves_summary( + &job.source, + &job.records, + &sides, + &filter, + about, + selected, + None, + skipped, + ), + crate::brilliant::Outcome::Stopped if reviewed == 0 => { + self.toast(ctx, tr("Search stopped: no game was reviewed")); + } + crate::brilliant::Outcome::Stopped => self.great_moves_summary( + &job.source, + &job.records, + &sides, + &filter, + about, + selected, + Some((reviewed, total)), + skipped, + ), + crate::brilliant::Outcome::EngineFailed(why) => { + let text = trf( + "The engine failed: {reason}. {i} of {n} reviewed", + &[("reason", why), ("i", &reviewed), ("n", &total)], + ); + self.library.set_pass_error(&job.source, Some(text)); + } + crate::brilliant::Outcome::SourceChanged => { + let text = trf( + "«{db}» changed; the search stopped. {i} of {n} reviewed", + &[ + ("db", &own_db::base_name(&job.source)), + ("i", &reviewed), + ("n", &total), + ], + ); + self.library.set_pass_error(&job.source, Some(text)); + } + } + } + if let Some(dialog) = self.brilliant_start.as_mut() + && let Some(outcome) = dialog.show(ctx) + { + let dialog = self.brilliant_start.take().expect("dialog"); + match outcome { + crate::brilliant_ui::StartOutcome::Cancel => {} + crate::brilliant_ui::StartOutcome::Start => self.start_great_moves(ctx, dialog), + crate::brilliant_ui::StartOutcome::Summary => { + if let Some(c) = &dialog.counted { + let reviewed = c.reviewed.clone(); + self.great_moves_summary( + &dialog.source, + &reviewed, + &c.sides, + &dialog.filter, + dialog.about.clone(), + dialog.selected, + None, + c.skipped.clone(), + ); + } + } + } + } + if self.game.is_none() + && let Some(summary) = self.brilliant_summary.as_mut() + && let Some(action) = summary.show(ctx) + { + let source = summary.source.clone(); + let summary_about = summary.about.clone(); + let summary_selected = summary.selected_games; + use crate::brilliant_ui::SummaryAction; + match action { + SummaryAction::Close => self.brilliant_summary = None, + SummaryAction::Select(record) => { + self.library.choose_only(&source, record as usize); + } + SummaryAction::Sort => self.library.sort_by_marks(&source), + SummaryAction::Continue { records, filter } => { + self.brilliant_summary = None; + let about = summary_about.clone(); + self.ask_great_moves(ctx, source, records, *filter, about, summary_selected); + } + SummaryAction::Open { record, ply } => { + self.brilliant_summary = None; + let at = self.library.database(&source).and_then(|db| { + let game = db.load_game(record as usize)?.game; + let node = *game.mainline().get(ply as usize)?; + Some(game.node(node)?.position().clone()) + }); + self.library.choose_only(&source, record as usize); + self.open_game(ctx, source, record as usize, at); + if let Some(g) = self.game.as_mut() { + g.show_report(); + } + } + } + } + } + + /// Starts the copy of the chosen records of the new-database dialog into `path` + /// (task 42): the file appears only when the copy is whole; the user stays in the + /// source database. + fn start_copy(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> { + let Some(own_db::AfterCreate::CopySelection { + path: from, + records, + sort, + ascending, + .. + }) = self.own.new_base.as_ref().map(|d| d.after.clone()) + else { + return Ok(()); + }; + if path.exists() { + return Err(tr("A file with this name is already there.").to_owned()); + } + if self + .library + .start_batch(ctx, &from, records, sort, ascending, path) + { + Ok(()) + } else { + Err(tr("Another copy is being written: wait until it finishes").to_owned()) + } + } + + /// The end of a copy of chosen records: a toast, and the new database on the shelf. + fn batch_ended(&mut self, ctx: &egui::Context, end: crate::library::BatchEnd) { + use crate::library::BatchEnd; + match end { + BatchEnd::Done { target, report } => { + let name = own_db::base_name(&target); + // At the end of the shelf: the cards stay where they are; «Open» brings it + // to the front. + self.settings.add_database_last(&target); + self.settings_dirty = true; + self.toast_for(ctx, crate::batch_copy::summary(&name, &report), 8.0); + self.toast_open_db = Some(target); + } + BatchEnd::Cancelled { target } => { + let name = own_db::base_name(&target); + self.toast( + ctx, + trf( + "Copying cancelled: «{name}» was not created", + &[("name", &name)], + ), + ); + } + BatchEnd::Failed { + source, + target, + error, + } => { + let text = match error { + crate::batch_copy::CopyError::SourceChanged => { + self.library.clear_selection(&source); + trf( + "«{src}» changed while copying. Nothing was written", + &[("src", &own_db::base_name(&source))], + ) + } + e => trf( + "Could not write «{name}»: {reason}. Nothing was written", + &[ + ("name", &own_db::base_name(&target)), + ("reason", &e.reason()), + ], + ), + }; + self.library.set_batch_error(&source, text.clone()); + self.toast_for(ctx, text, 8.0); + } + } + } + + /// Makes the empty file and puts it on the shelf, selected and as the database the + /// next game goes to. + fn create_base(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> { + path.parent() + .map(std::fs::create_dir_all) + .unwrap_or(Ok(())) + .and_then(|()| { + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + }) + .and_then(|f| f.sync_all()) + .map_err(|e| trf("Could not create the file: {e}", &[("e", &e)]))?; + self.settings.touch_database(&path); + self.settings.last_target = Some(path.clone()); + self.settings_dirty = true; + self.library.select_db(&path, ctx); + Ok(()) + } + + /// A new game to enter, with today's date (it is probably being played or entered + /// now). + fn new_game(&mut self) { + let mut g = Game::new(); + g.set_tag("Date", &chrono::Local::now().format("%Y.%m.%d").to_string()); + g.mark_saved(); + self.game = Some(GameView::new(g, None, Vec::new())); + } + + /// What comes after a game against Maia was closed: a rematch, the dialog. + fn play_next_now(&mut self, ctx: &egui::Context) { + // A game put aside: asked about first. + if self.put_aside.is_some() && self.play_next.is_some() { + self.aside_question = self.play_next.take(); + return; + } + match self.play_next.take() { + Some(PlayNext::Rematch(s)) => self.start_play(ctx, s), + Some(PlayNext::Dialog(None)) => { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)) + } + Some(PlayNext::Dialog(Some(from))) => { + self.play_dialog = Some(crate::play::Dialog::new_from(&self.settings, *from)) + } + None => {} + } + } + + /// A new game against the computer, or its dialog (asking first about a game put + /// aside). + fn play_new(&mut self, ctx: &egui::Context, next: PlayNext) { + self.play_next = Some(next); + self.play_next_now(ctx); + } + + /// The game put aside, and its card on the shelf. + fn set_aside(&mut self, aside: Option) { + self.library.aside = aside.as_ref().map(crate::adjourned::Card::new); + self.put_aside = aside; + } + + /// The game being played is put aside (its card on the shelf). False: it could not + /// be (no folder for its journal): it goes on. + fn put_game_aside(&mut self, ctx: &egui::Context) -> bool { + let Some(aside) = self.game.as_mut().and_then(|g| g.put_aside()) else { + self.toast( + ctx, + tr("The game could not be put aside: its file could not be written"), + ); + return false; + }; + // One at a time: a game started over another asked about it first. + self.let_go_aside(ctx); + self.set_aside(Some(aside)); + true + } + + /// The game put aside is let go: written into its player's database unfinished, or + /// deleted when games are not written. + fn let_go_aside(&mut self, ctx: &egui::Context) { + let Some(aside) = self.put_aside.take() else { + return; + }; + self.library.aside = None; + match aside.discard() { + Ok(Some(r)) => self.written_unfinished(ctx, r), + Ok(None) => {} + // Not written: it stays put aside (its card back), the reason said. + Err(b) => { + let (r, aside) = *b; + self.set_aside(Some(aside)); + self.written_unfinished(ctx, r); + } + } + } + + /// A game put aside went into its database unfinished (or could not): said. + fn written_unfinished(&mut self, ctx: &egui::Context, r: crate::player_games::Recovered) { + let db = own_db::base_name(&r.target); + match r.written { + Ok(w) => { + let n = w.index + 1; + self.recorded(ctx, &r.player, Ok(w), false); + self.toast_for( + ctx, + trf( + "Game written to «{db}» unfinished, No. {n}", + &[("db", &db), ("n", &n)], + ), + 6.0, + ); + } + Err(e) => self.toast( + ctx, + trf( + "Could not write to «{db}»: {reason}", + &[("db", &db), ("reason", &e)], + ), + ), + } + } + + /// Goes on with the game put aside: its record on the screen, the opponent started + /// again with its moves, the clocks where they stopped. + fn resume_aside(&mut self, ctx: &egui::Context) { + if let Some(why) = engine_game_refused(self.pass_busy()) { + self.toast(ctx, why); + return; + } + let Some(aside) = self.put_aside.as_ref() else { + return; + }; + let saved = aside.game().clone(); + let Some(game) = crate::play::parse_game(aside.pgn()) else { + self.toast(ctx, tr("The game put aside could not be read")); + return; + }; + let Some(engine) = crate::play::engine_for(&saved.start(None)) else { + // Its opponent is no longer on the disk: downloaded first. + self.aside_fetch = Some(None); + return; + }; + let judge = crate::engines::own_stockfish().or_else(|| { + self.settings + .active_engine() + .and_then(|e| e.executable()) + .filter(|l| l.present()) + }); + let Some(aside) = self.put_aside.take() else { + return; + }; + self.library.aside = None; + let to_move_left = aside.to_move_left(); + self.open_over(game); + if let Some(g) = self.game.as_mut() { + g.resume_play(&saved, to_move_left, engine, judge, aside.resume(), ctx); + } + } + + /// «There is a game put aside»: go on with it, or let it go for the new game. + fn aside_question(&mut self, ctx: &egui::Context) { + if self.aside_question.is_none() { + return; + } + let Some(card) = self.library.aside.as_ref() else { + // Let go meanwhile: what was asked for goes on. + self.play_next = self.aside_question.take(); + self.play_next_now(ctx); + return; + }; + let mut choice = None; + egui::Modal::new(egui::Id::new("aside_question")).show(ctx, |ui| { + ui.set_width(460.0); + ui.heading(tr("There is a game put aside")); + ui.add_space(4.0); + card.summary(ui, &self.settings); + ui.add_space(8.0); + ui.label(match &card.db { + Some(db) => trf( + "A new game replaces it; the one put aside is written to «{db}» unfinished.", + &[("db", db)], + ), + None => tr("A new game replaces it: the one put aside is deleted.").to_owned(), + }); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let go_on = crate::widgets::primary(ui, tr("Continue it")); + // The main answer has the keyboard (its focus seen). + if ui.memory(|m| m.focused().is_none()) { + go_on.request_focus(); + } + if go_on.clicked() { + choice = Some(true); + } + if ui.button(tr("Start a new one")).clicked() { + choice = Some(false); + } + }); + }); + if choice.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) { + choice = Some(true); + } + if choice.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) + { + self.aside_question = None; + return; + } + match choice { + Some(true) => { + self.aside_question = None; + self.resume_aside(ctx); + } + Some(false) => { + self.let_go_aside(ctx); + self.play_next = self.aside_question.take(); + self.play_next_now(ctx); + } + None => {} + } + } + + /// The opponent of the game put aside is downloaded, then the game goes on; the card + /// stays meanwhile and after a failure. + fn aside_fetch_question(&mut self, ctx: &egui::Context) { + let Some(fetch) = self.aside_fetch.as_ref() else { + return; + }; + let Some(saved) = self.put_aside.as_ref().map(|a| a.game().clone()) else { + self.aside_fetch = None; + return; + }; + let mut start = false; + let mut close = false; + let mut done = false; + egui::Modal::new(egui::Id::new("aside_fetch")).show(ctx, |ui| { + ui.set_width(460.0); + ui.heading(tr("The opponent of this game is not installed")); + if let Some(card) = self.library.aside.as_ref() { + ui.add_space(4.0); + card.summary(ui, &self.settings); + } + ui.add_space(8.0); + let state = match fetch { + None => { + ui.label(RichText::new(crate::play::Fetch::note(&saved)).weak()); + None + } + Some(f) => Some(f.show(ui)), + }; + done = state == Some(crate::play::Fetched::Done); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + match state { + None => start |= crate::widgets::primary(ui, tr("Download")).clicked(), + Some(crate::play::Fetched::Failed) => { + start |= crate::widgets::primary(ui, tr("Try again")).clicked() + } + _ => {} + } + close |= ui.button(tr("Cancel")).clicked(); + }); + }); + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { + close = true; + } + if done { + self.aside_fetch = None; + self.resume_aside(ctx); + } else if close { + // Dropping the download stops it. + self.aside_fetch = None; + } else if start { + self.aside_fetch = Some(Some(crate::play::Fetch::start(&saved, ctx))); + } + } + + /// × on the card of a game that goes into no database: deleting it is asked. + fn aside_delete_question(&mut self, ctx: &egui::Context) { + if !self.aside_delete { + return; + } + let mut choice = None; + egui::Modal::new(egui::Id::new("aside_delete")).show(ctx, |ui| { + ui.set_width(400.0); + ui.heading(tr("Delete the game put aside?")); + if let Some(card) = self.library.aside.as_ref() { + ui.add_space(4.0); + card.summary(ui, &self.settings); + ui.add_space(8.0); + } + ui.label(tr( + "Games are not written into a database: it is not kept anywhere.", + )); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Cancel")).clicked() { + choice = Some(false); + } + let delete = + egui::Button::new(RichText::new(tr("Delete")).color(egui::Color32::WHITE)) + .fill(ui.visuals().error_fg_color); + if ui.add(delete).clicked() { + choice = Some(true); + } + }); + }); + if choice.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) + { + choice = Some(false); + } + match choice { + Some(true) => { + self.aside_delete = false; + self.let_go_aside(ctx); + } + Some(false) => self.aside_delete = false, + None => {} + } + } + + /// A game from a position of another game: its moves to that position, the game + /// it comes from waiting under it (as a game opened from the reference does). + fn game_from(&mut self, from: &crate::play::StartFrom) { + let mut g = match from + .start_fen + .as_deref() + .and_then(|f| chess_core::StartPosition::from_fen(f).ok()) + { + Some(start) => Game::from_start(start), + None => Game::new(), + }; + g.set_tag("Date", &chrono::Local::now().format("%Y.%m.%d").to_string()); + if !from.moves.is_empty() { + let _ = g.add_line(chess_core::NodeId::ROOT, &from.moves); + } + g.forget_history(); + g.mark_saved(); + self.open_over(g); + } + + /// `g` opens over the current game, which waits under it as it is (as a game + /// opened from the reference does); the engine stops. + fn open_over(&mut self, g: Game) { + self.analysis.stop(); + let title = self.game.as_ref().map(|g| g.title()); + if let Some(mut prev) = self.game.take() { + prev.suspend(); + self.previous_games.push(prev); + } + let mut view = GameView::new(g, None, Vec::new()); + view.previous = title; + self.game = Some(view); + } + + #[cfg(not(web))] + fn open_repertoire(&mut self, ctx: &egui::Context) { + if self.analysis.is_on() { + self.analysis.stop(); + self.live_paused = true; + } + if let Some(game) = self.game.as_mut() { + game.suspend(); + } + self.repertoire + .get_or_insert_with(crate::repertoire_ui::RepertoireUi::new) + .open_library(); + ctx.request_repaint(); + } + + #[cfg(not(web))] + fn open_repertoire_add(&mut self, ctx: &egui::Context, source: Game, at: chess_core::NodeId) { + self.open_repertoire(ctx); + if let Some(screen) = self.repertoire.as_mut() { + let title = self.game.as_ref().map(GameView::title).unwrap_or_default(); + screen.open_add_from_game(source, at, title); + } + } + + #[cfg(not(web))] + fn close_repertoire(&mut self, ctx: &egui::Context) { + self.repertoire = None; + if self.game.is_some() + && std::mem::take(&mut self.live_paused) + && let Some(config) = self.settings.active_engine().cloned() + { + self.analysis.start(&config, ctx); + } + } + + #[cfg(not(web))] + fn show_repertoire(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + self.library.poll(); + let Some(mut screen) = self.repertoire.take() else { + return; + }; + let actions = screen.show(ui, &mut self.settings); + self.repertoire = Some(screen); + for action in actions { + match action { + crate::repertoire_ui::RepertoireAction::Close => self.close_repertoire(ctx), + crate::repertoire_ui::RepertoireAction::OpenSettings => { + self.settings_ui.open = true + } + crate::repertoire_ui::RepertoireAction::Sound(sound) => self.play(sound), + crate::repertoire_ui::RepertoireAction::Toast(message) => self.toast(ctx, message), + crate::repertoire_ui::RepertoireAction::SettingsChanged => { + self.settings_dirty = true + } + crate::repertoire_ui::RepertoireAction::Added { id, name, report } => { + let title = self.game.as_ref().map(GameView::title).unwrap_or_default(); + let text = if report.added_nodes == 0 && report.annotation_changes == 0 { + tr("Already in the repertoire — no changes").to_owned() + } else if report.added_nodes == 0 { + trf( + "The path was already in the repertoire; annotations added: {n}", + &[("n", &report.annotation_changes)], + ) + } else { + trf( + "Added to “{name}â€�: new moves: {added} · matched: {matched}", + &[ + ("name", &name), + ("added", &report.added_nodes), + ("matched", &report.merged_nodes.saturating_sub(1)), + ], + ) + }; + self.toast_for(ctx, text, 8.0); + self.toast_repertoire = Some((id, title)); + self.close_repertoire(ctx); + } + } + } + } + + /// Learning the opening of the current game: the training opens over it. + fn open_training(&mut self, start: crate::train::TrainStart) { + let g = match start + .start_fen + .as_deref() + .and_then(|f| chess_core::StartPosition::from_fen(f).ok()) + { + Some(s) => Game::from_start(s), + None => Game::new(), + }; + self.open_over(g); + if let Some(view) = self.game.as_mut() { + view.start_training(start); + } + } + + /// A new game against Maia. Her model missing (a rematch, a game from a position): + /// the dialog with the same choices, to download it. + fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) { + // No game against the engine while the search for great moves runs (the owner's + // decision, task 27). + if let Some(why) = engine_game_refused(self.pass_busy()) { + self.toast(ctx, why); + return; + } + let Some(maia) = crate::play::engine_for(&start) else { + self.play_dialog = Some(crate::play::Dialog::for_start(&self.settings, &start)); + return; + }; + // The engine judging Maia's resignation: ChessPenguin's Stockfish (its node count + // and the twelve pawns are Stockfish's measures), else the active engine when its + // file is there; none — she plays every game to its end. + let judge = crate::engines::own_stockfish().or_else(|| { + self.settings + .active_engine() + .and_then(|e| e.executable()) + .filter(|l| l.present()) + }); + match &start.from { + Some(from) => self.game_from(from), + None => self.new_game(), + } + // Where the game goes by itself (player-games.md): the player's database. + let record = self + .settings + .record_games + .then(|| self.player_target(&start.user_name)); + if let Some(g) = self.game.as_mut() { + g.start_play(start, maia, judge, record, ctx); + } + } + + /// The database of the player of this name: theirs, else a new one in the folder of + /// new databases. + fn player_target(&self, name: &str) -> PathBuf { + let dir = own_db::default_base_dir(self.settings.new_database_dir.as_deref()); + crate::player_games::target(&self.settings.players, name, &dir) + } + + /// A game went into the player's database (or a game a crash left, at the start): + /// the player is linked to it, it is first on the shelf and read anew; a new one is + /// said once. + fn recorded( + &mut self, + ctx: &egui::Context, + name: &str, + res: Result, + crashed: bool, + ) { + match res { + Ok(w) => { + crate::player_games::link(&mut self.settings.players, name, &w.path); + self.settings.touch_database(&w.path); + self.settings_dirty = true; + self.library.reload(&w.path, ctx); + let db = own_db::base_name(&w.path); + if crashed { + self.toast_for( + ctx, + trf( + "An unfinished game (the program closed) is written to «{db}», No. {n}", + &[("db", &db), ("n", &(w.index + 1))], + ), + 6.0, + ); + } else if w.created { + self.toast_for( + ctx, + trf( + "Database «{db}» created: your games will be written there", + &[("db", &db)], + ), + 6.0, + ); + } + } + // The result strip says so (with «Add to database…»); after a crash, a toast. + Err(e) if crashed => self.toast(ctx, e), + Err(_) => {} + } + } + + /// The game's data for editing (F2, the title, the menu). + fn edit_game_data(&mut self) { + let Some(g) = &self.game else { return }; + let editor = + own_db::DataEditor::from_game(&g.game, &self.settings.your_name, EditorMode::Done); + self.own.editor = Some((editor, EditorThen::Done)); + } + + #[cfg(not(web))] + fn pick_folder(&self, ctx: &egui::Context, start: PathBuf) { + self.spawn_dialog(ctx, move || { + let picked = rfd::FileDialog::new() + .set_title(tr("Folder for new databases")) + .set_directory(start) + .pick_folder(); + Some(Async::FolderPicked(picked)) + }); + } + + /// Draws the dialog that is open and acts on what was chosen. + fn own_dialogs(&mut self, ctx: &egui::Context) { + self.run_pending(ctx); + if let Some((q, _)) = self.own.question.as_mut() + && let Some(answer) = q.show(ctx) + { + let (_, then) = self.own.question.take().expect("question"); + match (then, answer) { + (QuestionThen::Duplicate { target, index }, Answer::Primary) => { + self.replace_in(ctx, target, index) + } + (QuestionThen::Duplicate { target, .. }, Answer::Secondary) => { + self.append_current(ctx, target) + } + ( + QuestionThen::DuplicateRecord { + from, + index, + target, + at, + }, + Answer::Primary, + ) => self.replace_record(ctx, from, index, target, at), + ( + QuestionThen::DuplicateRecord { + from, + index, + target, + .. + }, + Answer::Secondary, + ) => self.append_record_now(ctx, from, index, target), + (QuestionThen::Delete { path, index }, Answer::Primary) => { + self.delete_now(ctx, path, index) + } + (QuestionThen::Utf8Copy { path, dest }, Answer::Primary) => { + let Some(db) = self.library.database(&path) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::write_utf8_copy(pgn, &dest) { + Ok(()) => { + // The copy goes on the shelf right after the original. + let at = self + .settings + .databases + .iter() + .position(|p| *p == path) + .map_or(0, |i| i + 1); + self.settings.databases.retain(|p| *p != dest); + self.settings + .databases + .insert(at.min(self.settings.databases.len()), dest.clone()); + // The copy is the one to add to from now on. + self.settings.last_target = Some(dest.clone()); + self.settings_dirty = true; + self.library.select_db(&dest, ctx); + self.toast( + ctx, + trf( + "Copy made: {path}", + &[("path", &crate::platform::files::shown(&dest))], + ), + ); + } + Err(e) => { + self.toast(ctx, trf("Could not make the copy: {e}", &[("e", &e)])) + } + } + } + (QuestionThen::Retry(retry), Answer::Primary) => self.retry(ctx, retry), + (QuestionThen::Retry(_), Answer::Secondary) => { + self.open_chooser(ctx, ChooserFor::CurrentGame) + } + // After a change on the disk a record cannot be replaced: the game goes + // in as a new one ("Add as new"); a delete is only reread ("Reread"). + (QuestionThen::Changed(retry), Answer::Primary) => match retry { + Retry::Replace => { + if let Some(src) = self.game.as_ref().and_then(|g| g.source.clone()) { + self.append_current(ctx, src.path); + } + } + Retry::ReplaceIn { target, .. } | Retry::Append(target) => { + self.append_current(ctx, target) + } + Retry::AppendRecord { + from, + index, + target, + } => self.append_record(ctx, from, index, target), + Retry::Delete { .. } => {} + }, + (QuestionThen::Changed(_), Answer::Secondary) => {} + (QuestionThen::BigBase, Answer::Primary) => self.replace_current(ctx), + (QuestionThen::BigBase, Answer::Secondary) => { + self.open_chooser(ctx, ChooserFor::CurrentGame) + } + (_, Answer::Cancel) + | (QuestionThen::Delete { .. }, _) + | (QuestionThen::Utf8Copy { .. }, _) => { + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + } + return; + } + if let Some((editor, _)) = self.own.editor.as_mut() + && let Some(outcome) = editor.show(ctx) + { + let (editor, then) = self.own.editor.take().expect("editor"); + match (outcome, then) { + (EditorOutcome::Done, EditorThen::Done) => { + if let Some(g) = self.game_view() { + editor.apply(&mut g.game); + } + } + (EditorOutcome::Done, EditorThen::Add(target)) => { + if let Some(g) = self.game_view() { + editor.apply(&mut g.game); + g.data_asked = true; + } + self.add_current_now(ctx, target); + } + (EditorOutcome::Cancel, EditorThen::Add(_)) => { + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + (EditorOutcome::Cancel, EditorThen::Done) => {} + } + return; + } + if self.own.chooser.is_some() { + let rows = self.chooser_rows(); + if let Some(c) = self.own.chooser.as_mut() { + c.refresh(rows); + } + } + if let Some(chooser) = self.own.chooser.as_mut() + && let Some(outcome) = chooser.show(ctx) + { + let chooser = self.own.chooser.take().expect("chooser"); + match outcome { + ChooserOutcome::Pick(target) => match chooser.purpose { + ChooserFor::CurrentGame => self.add_current_to(ctx, target), + ChooserFor::Record { path, index } => { + self.append_record(ctx, path, index, target) + } + }, + ChooserOutcome::NewBase => { + let after = match chooser.purpose { + ChooserFor::CurrentGame => own_db::AfterCreate::AddGame, + ChooserFor::Record { path, index } => { + own_db::AfterCreate::AddRecord { path, index } + } + }; + self.new_base_dialog(after); + } + ChooserOutcome::SaveAsFile => { + self.close_after_save = self.own.then_close.take(); + #[cfg(not(web))] + self.pick_save(ctx); + // A file of its own in a browser: a download. + #[cfg(web)] + self.download_pgn(ctx); + } + ChooserOutcome::Cancel => { + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + } + return; + } + if let Some(dialog) = self.own.new_base.as_mut() + && let Some(outcome) = dialog.show(ctx) + { + match outcome { + // A browser has no folders: there are no new databases there. + NewBaseOutcome::PickFolder => { + #[cfg(not(web))] + { + let start = dialog.dir.clone(); + self.pick_folder(ctx, start); + } + } + NewBaseOutcome::Cancel => { + self.own.new_base = None; + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + NewBaseOutcome::Create(_) | NewBaseOutcome::AddExisting(_) => { + let (create, path) = match outcome { + NewBaseOutcome::Create(p) => (true, p), + NewBaseOutcome::AddExisting(p) => (false, p), + _ => unreachable!(), + }; + let copy = matches!( + self.own.new_base.as_ref().map(|d| &d.after), + Some(own_db::AfterCreate::CopySelection { .. }) + ); + let made = if copy { + self.start_copy(ctx, path.clone()) + } else if create { + self.create_base(ctx, path.clone()) + } else { + self.settings.touch_database(&path); + self.settings_dirty = true; + self.library.select_db(&path, ctx); + Ok(()) + }; + match made { + // The dialog stays, with the reason, and the name typed. + Err(e) => { + if let Some(d) = self.own.new_base.as_mut() { + d.error = Some(e); + } + } + Ok(()) => { + let dialog = self.own.new_base.take().expect("dialog"); + self.settings.new_database_dir = Some(dialog.dir.clone()); + self.settings_dirty = true; + match dialog.after { + own_db::AfterCreate::Shelf => {} + own_db::AfterCreate::AddGame => { + self.wait_for(ctx, &path, Pending::AddCurrent(path.clone())) + } + own_db::AfterCreate::AddRecord { path: from, index } => { + let step = Pending::AppendRecord { + from, + index, + target: path.clone(), + }; + self.wait_for(ctx, &path, step) + } + // Started by `start_copy`; its end is a toast. + own_db::AfterCreate::CopySelection { .. } => {} + } + } + } + } + } + } + } + + fn play(&self, s: Sound) { + if self.settings.sound_enabled { + self.sound + .play(self.settings.sound_set, s, self.settings.volume); + } + } + + #[cfg(not(web))] + fn spawn_dialog( + &self, + ctx: &egui::Context, + f: impl FnOnce() -> Option + Send + 'static, + ) { + let tx = self.tx.clone(); + let ctx = ctx.clone(); + let _ = std::thread::Builder::new() + .name("dialog".into()) + .spawn(move || { + if let Some(r) = f() { + let _ = tx.send(r); + } + ctx.request_repaint(); + }); + } + + fn pick_databases(&self, ctx: &egui::Context) { + let (tx, ctx) = (self.tx.clone(), ctx.clone()); + crate::platform::files::pick_databases(move |picked| { + send_picked(&tx, picked, false); + ctx.request_repaint(); + }); + } + + #[cfg(not(web))] + fn pick_save(&self, ctx: &egui::Context) { + let Some(g) = &self.game else { return }; + let name = sanitize(&g.title()) + ".pgn"; + self.spawn_dialog(ctx, move || { + rfd::FileDialog::new() + .set_title(tr("Save game")) + .set_file_name(name) + .add_filter("PGN", &["pgn"]) + .save_file() + .map_or(Some(Async::SaveCancelled), |p| Some(Async::SavePicked(p))) + }); + } + + #[cfg(not(web))] + fn pick_engine(&mut self, ctx: &egui::Context) { + self.settings_ui.checking_engine = true; + let tx = self.tx.clone(); + let ctx2 = ctx.clone(); + let _ = std::thread::Builder::new() + .name("engine-check".into()) + .spawn(move || { + let Some(path) = rfd::FileDialog::new() + .set_title(tr("Choose the UCI engine executable")) + .pick_file() + else { + let _ = tx.send(Async::EngineChecked(Err(String::new()))); + ctx2.request_repaint(); + return; + }; + let res = uci::Engine::spawn(&path, std::iter::empty::<&str>(), Box::new(|| {})) + .map(|h| { + let name = h.info().name.clone().unwrap_or_else(|| { + path.file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + }); + h.quit(); + (path.clone(), name) + }) + .map_err(|e| format!("{}: {e}", path.display())); + let _ = tx.send(Async::EngineChecked(res)); + ctx2.request_repaint(); + }); + } + + fn handle_async(&mut self, ctx: &egui::Context) { + self.pasted(ctx); + while let Ok(msg) = self.rx.try_recv() { + match msg { + #[cfg(web)] + Async::TooBig(files) => self.web_notice = Some(WebNotice::TooBig(files)), + #[cfg(web)] + Async::Incomplete(names) => { + if let Some(name) = names.into_iter().next() { + self.web_notice = Some(WebNotice::Incomplete(name)); + } + } + Async::EmptyFolder => { + self.toast( + ctx, + tr("There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z)."), + ); + } + Async::NotDatabases(names) => { + let files = names_text(&names); + self.toast( + ctx, + trf( + "Not a database: {files}. ChessPenguin opens .pgn, .cbh, .cbv, .zip and .7z files.", + &[("files", &files)], + ), + ); + } + #[cfg(web)] + Async::CopyKept(path, kept) => self.copy_kept(ctx, path, kept), + Async::Missing(names) => { + let files = names_text(&names); + self.toast(ctx, trf("Not found: {files}", &[("files", &files)])); + } + Async::DatabasesDropped(paths) => { + // As «Add database»; the game on the screen stays, so it is told. + // The first one ends up first on the shelf (as the shelf has it: a + // link to a database there is that database). + let mut first = None; + for p in paths.iter().rev() { + first = Some(self.settings.touch_database(p)); + } + if let Some(first) = first { + self.library.select_db(&first, ctx); + } + self.settings_dirty = true; + if self.game.is_some() { + let names: Vec = + paths.iter().map(|p| own_db::base_name(p)).collect(); + let files = names_text(&names); + self.toast( + ctx, + trf("Added to the shelf: {files}", &[("files", &files)]), + ); + } + } + Async::DatabasesPicked(paths) => { + // The file chosen again takes the place of the one gone (a cancelled + // dialog ends «Choose again» too). + let old = self.choosing_again.take(); + if paths.is_empty() { + continue; + } + if let Some(old) = old { + self.settings.databases.retain(|d| *d != old); + self.library.forget(&old); + crate::platform::files::forget(&old); + } + // The first one ends up first on the shelf (as the shelf has it: a + // link to a database there is that database). + let mut first = None; + for p in paths.iter().rev() { + first = Some(self.settings.touch_database(p)); + } + if let Some(first) = first { + self.library.select_db(&first, ctx); + } + self.settings_dirty = true; + } + Async::SavePicked(path) => self.save_game(ctx, path), + #[cfg(web)] + Async::ReadAllowed(path) => self.library.reload(&path, ctx), + Async::SaveCancelled => { + self.close_after_save = None; + self.restart_to = None; + } + Async::FolderPicked(Some(dir)) => { + self.settings.new_database_dir = Some(dir.clone()); + self.settings_dirty = true; + if let Some(d) = self.own.new_base.as_mut() { + d.dir = dir; + } + } + Async::FolderPicked(None) => {} + Async::EngineChecked(res) => { + self.settings_ui.checking_engine = false; + match res { + Ok((path, name)) => { + self.settings + .engines + .push(EngineConfig::new(name.clone(), path)); + if self.settings.active_engine.is_none() { + self.settings.active_engine = Some(self.settings.engines.len() - 1); + } + self.settings_dirty = true; + self.toast(ctx, trf("Engine “{name}â€� added", &[("name", &name)])); + } + Err(e) if e.is_empty() => {} + Err(e) => self.toast( + ctx, + trf("Not a UCI engine or it failed to start: {e}", &[("e", &e)]), + ), + } + } + } + } + } + + fn save_game(&mut self, ctx: &egui::Context, path: PathBuf) { + // Never replace a source database with a single game (explicit invariant). + let same = |a: &std::path::Path| match (a.canonicalize(), path.canonicalize()) { + (Ok(x), Ok(y)) => x == y, + _ => a == path, + }; + let is_source = self + .game + .as_ref() + .and_then(|g| g.source.as_ref()) + .is_some_and(|s| same(&s.path)); + if is_source || self.settings.databases.iter().any(|d| same(d)) { + self.close_after_save = None; + self.toast( + ctx, + tr("An open database cannot be overwritten with a single game — choose another file"), + ); + return; + } + let Some(g) = &mut self.game else { return }; + let pgn = g.game.to_pgn(); + // The user's game file: synced to the disk before the rename, like a database. + match chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) { + Ok(()) => { + g.game.mark_saved(); + self.toast( + ctx, + trf( + "Saved: {path}", + &[("path", &crate::platform::files::shown(&path))], + ), + ); + if let Some(intent) = self.close_after_save.take() { + self.finish_close(ctx, intent); + } + } + Err(e) => { + self.close_after_save = None; + self.toast(ctx, trf("Save failed: {e}", &[("e", &e)])); + } + } + } + + fn open_game( + &mut self, + ctx: &egui::Context, + path: PathBuf, + index: usize, + at: Option, + ) { + let Some(db) = self.library.database(&path) else { + return; + }; + match db.load_game(index) { + Some(parsed) => { + self.game = Some(GameView::new( + parsed.game, + Some(GameSource { + path: path.clone(), + index, + block: self.library.write_block(&path), + }), + parsed.diagnostics, + )); + if self.reference_tab + && let Some(g) = self.game.as_mut() + { + g.show_reference_tab(); + } + if let (Some(target), Some(g)) = (at, self.game.as_mut()) { + g.goto_position(&target); + } + self.library.mark_viewed(&path, index); + self.settings.touch_database(&path); + self.settings_dirty = true; + } + None => self.toast(ctx, tr("Could not read the game")), + } + } + + fn request_close(&mut self, ctx: &egui::Context, intent: CloseIntent) { + // A comment being written goes into the game first. A game against Maia in + // progress asks «The game is on» (its answer leaves, or not); before its first + // moves it is just dropped. + if let Some(g) = self.game.as_mut() { + g.commit_editor(); + if g.playing_started() { + // Quitting puts the game aside: nothing is lost, no question. + if intent != CloseIntent::QuitApp || !self.put_game_aside(ctx) { + if let Some(g) = self.game.as_mut() { + g.ask_leave(intent); + } + return; + } + } else { + g.resign_if_playing(); + } + } + if self.game.as_ref().is_some_and(|g| g.game.is_modified()) { + self.confirm_close = Some(intent); + } else { + self.finish_close(ctx, intent); + } + } + + fn finish_close(&mut self, ctx: &egui::Context, intent: CloseIntent) { + self.analysis.stop(); + self.live_paused = false; + let closed = self.game.take(); + if intent == CloseIntent::ReturnToPrevious { + self.game = self.previous_games.pop(); + // A rematch from a position goes on over the same game. + self.play_next_now(ctx); + return; + } + // Games left for others (reference tab) with unsaved edits are asked about one + // by one (each shown with the question) before the library, the search board or + // quitting. + if let Some(k) = self + .previous_games + .iter() + .rposition(|g| g.game.is_modified()) + { + self.previous_games.truncate(k + 1); + self.game = self.previous_games.pop(); + // Ask about it right away; its answer continues to where the user was going + // (the library, the search board, quitting). + self.confirm_close = Some(intent); + return; + } + self.previous_games.clear(); + if let Some(p) = self.prep.as_mut() { + p.shown = false; + } + if let Some(g) = closed + && let Some(src) = g.source + { + self.library.reveal(&src.path, src.index); + } + self.play_next_now(ctx); + if let Some((path, start, line, flipped)) = self.find_after_close.take() { + self.library.show_position(&path, start, line, flipped, ctx); + } + + if intent == CloseIntent::QuitApp { + // A restart into the new version: start it as this one goes. + if let Some(exe) = self.restart_to.take() { + // The settings first (the new process reads them), and none of the dev + // hooks of this one (they would start the update again). + let _ = self.settings.save(); + // The game put aside is let go of (its files stay): the new process + // offers it. + self.set_aside(None); + let mut cmd = std::process::Command::new(exe); + for (k, _) in std::env::vars_os() { + if k.to_string_lossy().starts_with("CP_") { + cmd.env_remove(k); + } + } + let _ = cmd.spawn(); + } + self.allow_quit = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + + /// Leaves the game for the library's search board with the game's current position. + fn find_position(&mut self, ctx: &egui::Context, db: Option) { + let Some((start, line, flipped)) = self.game.as_ref().and_then(|g| g.search_line()) else { + return; + }; + let path = db + .or_else(|| self.library.selected_db.clone()) + .or_else(|| self.settings.databases.first().cloned()); + let Some(path) = path else { + self.toast(ctx, tr("Add a database first")); + return; + }; + self.find_after_close = Some((path, start, line, flipped)); + self.request_close(ctx, CloseIntent::BackToLibrary); + } + + fn toggle_engine(&mut self, ctx: &egui::Context) { + self.live_paused = false; + // The search for great moves has the engine (task 27 §4.5). + if !self.analysis.is_on() + && let Some(why) = self.pass_busy() + { + self.toast(ctx, why); + return; + } + if self.prep.as_ref().is_some_and(|p| p.running()) && !self.analysis.is_on() { + self.toast( + ctx, + tr("Opening errors are being searched — wait or stop it in the report"), + ); + return; + } + if self.analysis.is_on() { + self.analysis.stop(); + return; + } + match self.settings.active_engine().cloned() { + Some(cfg) if crate::engine_offer::EngineOffer::engine_ready(&self.settings) => { + self.analysis.start(&cfg, ctx) + } + _ => self + .engine_offer + .ask(crate::engine_offer::Pending::LiveAnalysis, &self.settings), + } + } + + /// Makes ChessPenguin's Stockfish (just downloaded) or a found engine the active + /// one, then runs what the user was doing. The game analysis and the opening errors + /// use ChessPenguin's Stockfish whatever the active engine: downloaded for them, it + /// becomes the active one only when there was none. + fn engine_arrived( + &mut self, + ctx: &egui::Context, + cfg: crate::settings::EngineConfig, + pending: Option, + ) { + let known = self.settings.engines.iter().position(|e| { + (cfg.builtin && e.builtin) || (!cfg.builtin && !e.builtin && e.path == cfg.path) + }); + let index = known.unwrap_or_else(|| { + self.settings.engines.push(cfg); + self.settings.engines.len() - 1 + }); + let own_search = matches!( + pending, + Some( + crate::engine_offer::Pending::GameAnalysis { .. } + | crate::engine_offer::Pending::OpeningErrors { .. } + | crate::engine_offer::Pending::GreatMoves + ) + ); + if !own_search || self.settings.active_engine().is_none() { + self.settings.active_engine = Some(index); + } + self.settings_dirty = true; + self.run_engine_pending(ctx, pending); + } + + /// The game analysis or the opening errors found no engine to search with: a + /// Stockfish 19 of the user's that searches as ours is taken (probed first, in the + /// background: the action waits for it, on its own game or preparation), else ours + /// is offered for download, saying why the user's engine does not do. + fn need_review_engine(&mut self, ctx: &egui::Context, pending: crate::engine_offer::Pending) { + crate::review_engine::set_candidates(&self.settings); + let waited = !self.review_wait.is_empty(); + // One wait per kind: the newer request of a kind takes its place, the other + // kind keeps its own. + let same_kind = |p: &crate::engine_offer::Pending| { + std::mem::discriminant(p) == std::mem::discriminant(&pending) + }; + self.review_wait.retain(|p| !same_kind(p)); + self.review_wait.push(pending); + // Said only when an engine is really being checked (not when the answer is + // known already: then it starts, or the offer says why not). + if self.poll_review_wait(ctx) && !waited { + self.toast( + ctx, + tr("Checking whether your engine can run the analysis…"), + ); + } + } + + /// The actions waiting for an engine of the user's to be probed: dropped when their + /// game or preparation is no longer there; when the probe is done, started, or the + /// download of ours is offered for the latest of them. + /// Returns whether they still wait. + fn poll_review_wait(&mut self, ctx: &egui::Context) -> bool { + use crate::review_engine::Lookup; + let (game, prep) = ( + self.game.as_ref().map(|g| g.serial), + self.prep.as_ref().map(|p| p.serial), + ); + self.review_wait.retain(|p| still_waiting(p, game, prep)); + if self.review_wait.is_empty() { + return false; + } + match crate::review_engine::lookup(ctx) { + Lookup::Checking => return true, + Lookup::Ready(_) => { + for p in std::mem::take(&mut self.review_wait) { + self.run_engine_pending(ctx, Some(p)); + } + } + Lookup::Unfit(unfit) => { + let waiting = std::mem::take(&mut self.review_wait); + if let Some(p) = waiting.last() { + self.engine_offer.ask_instead_of(*p, unfit); + } + } + Lookup::None => { + let waiting = std::mem::take(&mut self.review_wait); + if let Some(p) = waiting.last() { + self.engine_offer.ask(*p, &self.settings); + } + } + } + false + } + + /// Runs what the user was doing when an engine had to be found first: on the game + /// or the preparation it was asked on, if it is still there. + fn run_engine_pending( + &mut self, + ctx: &egui::Context, + pending: Option, + ) { + match pending { + Some(crate::engine_offer::Pending::LiveAnalysis) => { + if !self.analysis.is_on() { + self.toggle_engine(ctx); + } + } + Some(crate::engine_offer::Pending::GameAnalysis { game, full }) => { + let actions = match self.game.as_mut().filter(|g| g.serial == game) { + Some(g) => g.start_review_now(ctx, full), + None => Vec::new(), + }; + for a in actions { + match a { + GameAction::PauseLive if self.analysis.is_on() => { + self.analysis.stop(); + self.live_paused = true; + } + GameAction::Toast(m) => self.toast(ctx, m), + _ => {} + } + } + } + Some(crate::engine_offer::Pending::GreatMoves) => { + if let Some(dialog) = self.brilliant_waiting.take() { + self.start_great_moves(ctx, dialog); + } + } + Some(crate::engine_offer::Pending::OpeningErrors { prep }) => { + let actions = match self.prep.as_mut().filter(|p| p.serial == prep) { + Some(p) => p.start_after_engine(ctx), + None => Vec::new(), + }; + self.prep_actions(ctx, actions); + } + None => {} + } + } + + fn offer_events(&mut self, ctx: &egui::Context) { + for e in self.engine_offer.show(ctx) { + match e { + crate::engine_offer::OfferEvent::Installed(pending) => { + self.engine_arrived(ctx, crate::engines::builtin_config(), pending) + } + crate::engine_offer::OfferEvent::UseSystem(path, pending) => { + let cfg = crate::settings::EngineConfig::new("Stockfish".into(), path); + self.engine_arrived(ctx, cfg, pending) + } + #[cfg(not(web))] + crate::engine_offer::OfferEvent::ChooseFile => self.pick_engine(ctx), + crate::engine_offer::OfferEvent::Toast(m) => self.toast(ctx, m), + } + } + } + + /// The page's side of the frame: the game on the screen as an entry of the browser's + /// history, the browser's question on leaving with unsaved work, the draft of an + /// unsaved game. Nothing of it on a computer. + fn page_frame(&mut self, ctx: &egui::Context) { + crate::platform::page::game_shown(ctx, self.game.is_some()); + let modified = self.game.as_ref().is_some_and(|g| g.game.is_modified()); + let reviewing = self.game.as_ref().is_some_and(|g| g.review_running()); + crate::platform::page::warn_on_leave(modified || reviewing); + #[cfg(web)] + { + const EVERY: f64 = 5.0; + let now = ctx.input(|i| i.time); + match self.game.as_ref().filter(|g| g.game.is_modified()) { + Some(g) if self.draft_at.is_none_or(|t| now - t >= EVERY) => { + crate::my_games::write_draft(&crate::my_games::Draft { + title: g.title(), + moves: g.game.mainline().len().div_ceil(2), + pgn: g.game.to_pgn(), + }); + self.draft_at = Some(now); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(EVERY)); + } + Some(_) => {} + // Saved, or left without saving: no draft of this visit is kept. + None if self.draft_at.take().is_some() => crate::my_games::delete_draft(), + None => {} + } + } + } + + /// «There is an unsaved game» over the library, with Open and Delete. + #[cfg(web)] + fn draft_strip(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + let Some(d) = self.draft_offer.clone() else { + return; + }; + let mut open = false; + let mut delete = false; + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(8, 6)) + .fill(ui.visuals().faint_bg_color) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(trf( + "There is an unsaved game: {title}, moves: {n}.", + &[("title", &d.title), ("n", &d.moves)], + )) + .color(ui.visuals().warn_fg_color), + ); + open = ui.button(tr("Open")).clicked(); + delete = ui.button(tr("Delete")).clicked(); + }); + }); + if open { + self.draft_offer = None; + self.open_pgn_text(ctx, d.pgn, false); + crate::my_games::delete_draft(); + } else if delete { + self.draft_offer = None; + crate::my_games::delete_draft(); + } + } + + /// Files dropped on the window open as databases, like chosen ones; while files are + /// dragged over it, the window says so. + fn dropped_files(&mut self, ctx: &egui::Context) { + let (tx, waker) = (self.tx.clone(), ctx.clone()); + crate::platform::files::take_dropped(ctx, move |picked| { + send_picked(&tx, picked, true); + waker.request_repaint(); + }); + if crate::platform::files::dragging(ctx) { + let rect = ctx.content_rect(); + let painter = ctx.layer_painter(egui::LayerId::new( + egui::Order::Foreground, + egui::Id::new("dropping files"), + )); + // The window tinted and framed in the accent colour; the words on a card of + // the window's own background, readable in both themes. + let visuals = ctx.global_style().visuals.clone(); + let accent = visuals.selection.bg_fill; + painter.rect_filled(rect, 0.0, accent.gamma_multiply(0.28)); + painter.rect_stroke( + rect.shrink(2.0), + 6.0, + egui::Stroke::new(4.0, accent), + egui::StrokeKind::Inside, + ); + let galley = painter.layout_no_wrap( + tr("Release to open").to_owned(), + egui::FontId::proportional(22.0), + visuals.strong_text_color(), + ); + let card = + egui::Rect::from_center_size(rect.center(), galley.size() + egui::vec2(48.0, 32.0)); + painter.rect( + card, + 10.0, + visuals.window_fill, + egui::Stroke::new(2.0, accent), + egui::StrokeKind::Inside, + ); + painter.galley( + card.center() - galley.size() / 2.0, + galley, + visuals.strong_text_color(), + ); + } + } + + /// A copy of a file of this visit kept in the browser: it takes the file's place on + /// the shelf. Only a browser has such files. + fn keep_copy(&mut self, ctx: &egui::Context, path: PathBuf) { + #[cfg(web)] + { + let (tx, wake) = (self.tx.clone(), ctx.clone()); + crate::platform::files::keep_copy(&path.clone(), move |kept| { + let _ = tx.send(Async::CopyKept(path, kept)); + wake.request_repaint(); + }); + } + #[cfg(not(web))] + let _ = (ctx, path); + } + + /// The copy of `path` is kept (or not): it takes the file's place on the shelf. + #[cfg(web)] + fn copy_kept( + &mut self, + ctx: &egui::Context, + path: PathBuf, + kept: Result, + ) { + { + use crate::platform::files::KeepCopy; + use crate::platform::size_text; + match kept { + Ok(copy) => { + for d in self.settings.databases.iter_mut().filter(|d| **d == path) { + *d = copy.clone(); + } + self.library.forget(&path); + crate::platform::files::forget(&path); + self.library.select_db(©, ctx); + self.settings_dirty = true; + let ctx2 = ctx.clone(); + crate::platform::web::storage::refresh(move || ctx2.request_repaint()); + if crate::platform::web::storage::persisted() != Some(true) { + crate::platform::web::storage::persist(|_| {}); + } + self.toast(ctx, tr("A copy is kept in the browser")); + } + Err(KeepCopy::NoRoom { need, free }) => self.toast_for( + ctx, + trf( + "Doesn't fit: the copy needs {need}, and the browser gives the site only {free} more. Free up space in “Browser dataâ€� or open the file from disk.", + &[("need", &size_text(need)), ("free", &size_text(free))], + ), + 8.0, + ), + Err(KeepCopy::Failed(e)) => self.toast(ctx, e), + } + } + } + + /// The window of [`WebNotice`]: a database too big for a browser (with the way to + /// the program for the computer), or a ChessBase database's other files to choose. + #[cfg(web)] + fn web_notice(&mut self, ctx: &egui::Context) { + let Some(notice) = &self.web_notice else { + return; + }; + let mut close = false; + let mut folder = false; + let mut files = false; + let modal = egui::Modal::new(egui::Id::new("web_notice")).show(ctx, |ui| { + ui.set_width(460.0); + match notice { + WebNotice::TooBig(dbs) => { + for (name, size) in dbs { + ui.label(RichText::new(name.as_str()).strong()); + ui.label(trf( + "This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.", + &[ + ("size", &crate::platform::size_text(*size)), + ("limit", &crate::platform::size_text(crate::platform::files::TOO_BIG)), + ], + )); + } + ui.add_space(6.0); + let lang = match crate::i18n::current() { + crate::i18n::Lang::En => "", + crate::i18n::Lang::Ru => "ru/", + crate::i18n::Lang::Fr => "fr/", + crate::i18n::Lang::De => "de/", + crate::i18n::Lang::Es => "es/", + crate::i18n::Lang::It => "it/", + crate::i18n::Lang::Pt => "pt/", + crate::i18n::Lang::Uz => "uz/", + crate::i18n::Lang::Kk => "kk/", + }; + ui.hyperlink_to( + tr("Download ChessPenguin for the computer"), + format!("/{lang}#download"), + ); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + close = ui.button(tr("Close")).clicked(); + }); + } + WebNotice::Incomplete(name) => { + ui.label(RichText::new(name.as_str()).strong()); + ui.label(tr( + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + )); + ui.add_space(4.0); + ui.label( + RichText::new(if crate::platform::files::remembers_chosen() { + tr("Allow access to the database's folder — its other files will be found by themselves.") + } else { + tr("Choose the database's folder — its other files will be found by themselves.") + }) + .weak(), + ); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + folder = ui.button(tr("ðŸ“� Choose the database's folder")).clicked(); + files = ui.button(tr("Choose the database's files")).clicked(); + close = ui.button(tr("Cancel")).clicked(); + }); + } + } + }); + if close || modal.should_close() { + self.web_notice = None; + } + if folder { + self.web_notice = None; + self.pick_database_folder(ctx); + } + if files { + self.web_notice = None; + self.pick_databases(ctx); + } + } + + #[cfg(web)] + fn pick_database_folder(&self, ctx: &egui::Context) { + let (tx, ctx) = (self.tx.clone(), ctx.clone()); + crate::platform::files::pick_database_folder(move |picked| { + send_picked(&tx, picked, false); + ctx.request_repaint(); + }); + } + + /// The open game's PGN, downloaded as a file named after the game. + #[cfg(web)] + fn download_pgn(&mut self, ctx: &egui::Context) { + let Some(g) = &self.game else { return }; + let name = sanitize(&g.title()) + ".pgn"; + if let Err(e) = crate::platform::files::download_pgn(&name, &g.game.to_pgn()) { + self.toast( + ctx, + trf("The PGN could not be downloaded: {e}", &[("e", &e)]), + ); + } + } + + fn paste_pgn(&mut self, ctx: &egui::Context) { + self.pasting = Some(crate::platform::clipboard::read_text(ctx)); + } + + /// The clipboard read for «Paste PGN», once it is there. + fn pasted(&mut self, ctx: &egui::Context) { + let Some(text) = self.pasting.as_ref().and_then(|r| r.poll()) else { + return; + }; + self.pasting = None; + match text { + Some(t) if !t.trim().is_empty() => self.open_pgn_text(ctx, t, false), + _ => self.toast(ctx, tr("The clipboard is empty or unavailable")), + } + } + + /// Opens PGN text (the first game of it) as a new game. + /// `at_end`: show the position after the last main-line move (a line from the + /// search board continues where the user stopped). + fn open_pgn_text(&mut self, ctx: &egui::Context, t: String, at_end: bool) { + // Split into records first: several games must not be glued into one. + let never = AtomicBool::new(false); + let db = PgnDatabase::from_bytes( + t.into_bytes(), + Some(TextEncoding::Utf8), + &mut |_| {}, + &never, + ); + let (parsed, count) = match db.as_ref().ok().filter(|db| !db.is_empty()) { + Some(db) => (db.load_game(0), db.len()), + None => (None, 0), + }; + let Some(parsed) = parsed else { + self.toast(ctx, tr("The clipboard contains no recognizable PGN game")); + return; + }; + if parsed.game.main_child(parsed.game.root()).is_none() + && parsed.game.tags().len() <= 7 + && !parsed.diagnostics.is_empty() + { + self.toast(ctx, tr("The clipboard contains no recognizable PGN game")); + return; + } + if count > 1 { + self.toast(ctx, trf("The clipboard has {count} games — the first one is open. To work with all of them, save them to a .pgn file and add it as a database", &[("count", &count)])); + } + let mut view = GameView::new(parsed.game, None, parsed.diagnostics); + if at_end { + view.goto_main_line_end(); + } + self.game = Some(view); + } + + fn confirm_dialog(&mut self, ctx: &egui::Context) { + let Some(intent) = self.confirm_close else { + return; + }; + let mut choice = None; + // Where the game can go (own-databases.md §3.4): back into its own PGN, or into a + // database of the user's choice. + let source = self.game.as_ref().and_then(|g| g.source.clone()); + let own = source + .as_ref() + .filter(|s| s.block.is_none()) + .map(|s| own_db::base_name(&s.path)); + // A new game meant for a database goes there. + let target = self.current_target().map(|t| own_db::base_name(&t)); + egui::Modal::new(egui::Id::new("confirm_close")).show(ctx, |ui| { + ui.set_width(380.0); + ui.heading(tr("Game modified")); + if let Some(g) = &self.game { + ui.label(RichText::new(g.title()).strong()); + } + match (&own, &source) { + (Some(name), _) => { + ui.label(trf("Save the changes to «{name}»?", &[("name", name)])); + } + (None, None) if let Some(name) = &target => { + ui.label(trf("Add the game to «{name}»?", &[("name", name)])); + } + (None, Some(s)) => { + if let Some(b) = &s.block { + ui.label(b.long()); + } + ui.label(tr( + "Add the game with the changes to a database of your own?", + )); + } + (None, None) => { + ui.label(tr("The game is in no database yet. Add it to one?")); + } + } + ui.add_space(8.0); + ui.horizontal(|ui| { + let primary = match (&own, &target) { + (Some(name), _) => trf("Save to «{name}»", &[("name", name)]), + (None, Some(name)) => trf("Add to «{name}»", &[("name", name)]), + (None, None) => tr("Add to database…").to_owned(), + }; + if crate::widgets::primary(ui, &primary).clicked() { + choice = Some(0); + } + // Escape goes on where the user was going back to (the owner's choice): + // the second Escape of "Escape, Escape" leaves the game without saving. + // Quitting the program is not undone that lightly: there it is Cancel. + let leaving = intent != CloseIntent::QuitApp; + let esc = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)); + let dont = ui.button(tr("Don't save")); + let dont = if leaving { + dont.on_hover_text("Esc") + } else { + dont + }; + if dont.clicked() || (esc && leaving) { + choice = Some(1); + } + let cancel = ui.button(tr("Cancel")); + let cancel = if leaving { + cancel + } else { + cancel.on_hover_text("Esc") + }; + if cancel.clicked() || (esc && !leaving) { + choice = Some(2); + } + }); + }); + match choice { + Some(0) => { + self.confirm_close = None; + if own.is_some() || target.is_some() { + self.save_current(ctx, Some(intent)); + } else { + self.own.then_close = Some(intent); + self.open_chooser(ctx, ChooserFor::CurrentGame); + } + } + Some(1) => { + self.confirm_close = None; + self.finish_close(ctx, intent); + } + Some(2) => { + self.confirm_close = None; + self.find_after_close = None; + self.play_next = None; + // A restart asked for waits for no later quit. + self.restart_to = None; + } + _ => {} + } + } + + /// Online games and updates, each frame (the desktop program's). + #[cfg(not(web))] + fn desktop_frame(&mut self, ctx: &egui::Context) { + // Back to the window after a while: the downloaded databases get the games + // played since (at the start they did already). + let now = ctx.input(|i| i.time); + let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); + if focused + && !self.desktop.was_focused + && now - self.desktop.online_updated_at > ONLINE_EVERY + { + self.desktop.online_updated_at = now; + self.desktop.online.update_quietly( + self.settings + .databases + .iter() + .filter(|p| crate::online::is_online(p)) + .cloned(), + ); + } + self.desktop.was_focused = focused; + let events = self + .desktop + .online + .show(ctx, &mut self.desktop.online_probe); + for e in events { + match e { + crate::online_ui::OnlineEvent::Added(p) => { + let known = self.settings.databases.contains(&p); + self.settings.touch_database(&p); + if known { + self.library.reload(&p, ctx); + } + self.library.select_db(&p, ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Updated(p) => self.library.reload(&p, ctx), + crate::online_ui::OnlineEvent::Open(p) => { + self.settings.touch_database(&p); + self.library.select_db(&p, ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Message(t) => self.toast(ctx, t), + } + } + // Updates: the badge next to Settings, the window, the status in Settings → About. + self.desktop.update_check.poll(); + let skipped = self.settings.skipped_version.clone(); + let badge = self + .desktop + .update_check + .newer() + .filter(|r| { + self.desktop.update_ui.active() || skipped.as_deref() != Some(r.version.as_str()) + }) + .map(|r| self.desktop.update_ui.badge(r)); + self.library.update = badge.clone(); + if let Some(g) = &mut self.game { + g.update = badge; + } + for e in self.desktop.update_ui.show( + ctx, + self.desktop.update_check.newer(), + &self.desktop.update_kind, + ) { + match e { + crate::update_ui::UpdateEvent::Restart(exe) => { + self.restart_to = Some(exe); + self.request_close(ctx, CloseIntent::QuitApp); + } + crate::update_ui::UpdateEvent::CopyText(t) => { + ctx.copy_text(t); + self.toast(ctx, tr("Copied")); + } + crate::update_ui::UpdateEvent::Quit => { + self.request_close(ctx, CloseIntent::QuitApp); + } + crate::update_ui::UpdateEvent::Skip(v) => { + self.settings.skipped_version = Some(v); + self.settings_dirty = true; + } + } + } + self.settings_ui.update_available = + self.desktop.update_check.newer().map(|r| r.version.clone()); + self.settings_ui.update_status = if self.desktop.update_check.running() { + Some(tr("Checking…").to_owned()) + } else if let Some(r) = self.desktop.update_check.newer() { + Some(trf("Version {v} is out", &[("v", &r.version)])) + } else if self.desktop.update_check.release.is_some() { + Some(tr("This is the latest version").to_owned()) + } else if self.desktop.update_check.error.is_some() { + Some(tr("Could not check for updates").to_owned()) + } else { + None + }; + } +} + +impl eframe::App for App { + #[cfg(all(debug_assertions, not(web)))] + fn raw_input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) { + if self.settings_ui.open + && ctx.input(|i| i.time) >= 3.0 + && let Some(pos) = self.debug.settings_click.take() + { + input.events.push(egui::Event::PointerMoved(pos)); + for pressed in [true, false] { + input.events.push(egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }); + } + } + } + + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + crate::san::set(self.settings.move_notation); + // The window has shown its first frame: this graphics mode works. + #[cfg(not(web))] + if ui.ctx().cumulative_frame_nr() >= 1 { + crate::graphics::started(); + } + let ctx = ui.ctx().clone(); + if self.applied_dark != Some(self.settings.dark_mode) { + ctx.set_visuals(if self.settings.dark_mode { + egui::Visuals::dark() + } else { + egui::Visuals::light() + }); + self.applied_dark = Some(self.settings.dark_mode); + } + // The opening panel's dragged width: given to the panel, saved when dragged anew. + #[cfg(not(web))] + let side_width = egui::Id::new(crate::opening_layout::SIDE_WIDTH_ID); + #[cfg(not(web))] + match ctx.data(|d| d.get_temp::(side_width)) { + None => { + if let Some(width) = self.settings.opening_side_width { + ctx.data_mut(|d| d.insert_temp(side_width, width)); + } + } + Some(width) if self.settings.opening_side_width != Some(width) => { + self.settings.opening_side_width = Some(width); + let _ = self.settings.save(); + } + Some(_) => {} + } + // Quitting while the opening errors are searched: asked first (what was found + // is kept either way). + if ctx.input(|i| i.viewport().close_requested()) + && !self.allow_quit + && !self.prep_quit_ok + && self.prep.as_ref().is_some_and(|p| p.running()) + { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.prep_quit_ask = true; + } + #[cfg(not(web))] + if ctx.input(|i| i.viewport().close_requested()) + && !self.allow_quit + && self + .repertoire + .as_ref() + .is_some_and(|screen| screen.has_unsaved()) + { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + if let Some(screen) = self.repertoire.as_mut() { + screen.resolve_unsaved(); + } + } + let quitting = !self.prep_quit_ask; + // Quitting: a comment being written goes into the game first, so the question + // about unsaved changes counts it. + if quitting + && ctx.input(|i| i.viewport().close_requested()) + && !self.allow_quit + && let Some(g) = self.game.as_mut() + { + g.commit_editor(); + if g.playing_started() { + // Put aside: the next start offers to go on with it. + if !self.put_game_aside(&ctx) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + if let Some(g) = self.game.as_mut() { + g.ask_leave(CloseIntent::QuitApp); + } + } + } else { + g.resign_if_playing(); + } + } + // Quitting with a modified game left for another (reference tab): show that one, + // so the question "save?" is about the game that has the changes. + if quitting + && ctx.input(|i| i.viewport().close_requested()) + && !self.allow_quit + && !self.game.as_ref().is_some_and(|g| g.game.is_modified()) + && let Some(k) = self + .previous_games + .iter() + .rposition(|g| g.game.is_modified()) + { + self.previous_games.truncate(k + 1); + self.game = self.previous_games.pop(); + } + // (A game against Maia in progress has asked «The game is on» instead.) + if quitting + && ctx.input(|i| i.viewport().close_requested()) + && !self.allow_quit + && self + .game + .as_ref() + .is_some_and(|g| g.game.is_modified() && !g.playing_started()) + { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.confirm_close = Some(CloseIntent::QuitApp); + } + self.dropped_files(&ctx); + self.handle_async(&ctx); + // The browser's «Back» in a game: «â†� Library». + if crate::platform::page::take_back() && self.game.is_some() { + self.request_close(&ctx, CloseIntent::BackToLibrary); + } + // Dev hook (screenshots): the engine offer as on pressing L without an engine. + if std::env::var("CP_ENGINE_OFFER").is_ok() && !self.offer_hook_done { + self.offer_hook_done = true; + self.engine_offer + .ask(crate::engine_offer::Pending::LiveAnalysis, &self.settings); + if std::env::var("CP_ENGINE_OFFER").as_deref() == Ok("download") { + self.engine_offer.start(&ctx); + } + } + if !self.review_wait.is_empty() { + let _ = self.poll_review_wait(&ctx); + } + self.offer_events(&ctx); + self.page_frame(&ctx); + #[cfg(web)] + self.web_notice(&ctx); + self.debug_step(&ctx); + self.debug_keys(&ctx); + self.debug_screenshot(&ctx); + self.analysis.poll(); + + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + #[cfg(not(web))] + let repertoire_visible = self.repertoire.is_some(); + #[cfg(web)] + let repertoire_visible = false; + if !repertoire_visible && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) { + self.pick_databases(&ctx); + } + if ctx.input_mut(|i| { + i.consume_shortcut(&KeyboardShortcut::new( + Modifiers::COMMAND | Modifiers::SHIFT, + Key::N, + )) + }) && self.game.is_none() + && !repertoire_visible + && crate::platform::CAPS.own_databases + { + self.own.then_close = None; + self.new_base_dialog(own_db::AfterCreate::Shelf); + } + // In the library a game from the start; on a game's screen the game plays on + // from its position (the game view takes Ctrl+G there). + if self.game.is_none() + && !repertoire_visible + && crate::platform::CAPS.play + && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) + { + self.play_new(&ctx, PlayNext::Dialog(None)); + } + // A browser keeps Ctrl+N for its window: N in the library there (design §4). + let new_game_key = cfg!(web) + && self.game.is_none() + && !repertoire_visible + && !ctx.egui_wants_keyboard_input() + && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::N)); + if (new_game_key || ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N)))) + && self.game.is_none() + && !repertoire_visible + { + self.new_game(); + } + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Comma))) { + self.settings_ui.open = !self.settings_ui.open; + } + + // A new game's target base that left the shelf or stopped taking games is + // dropped before the game is drawn (its header names the target). + let _ = self.current_target(); + let shelf = self.shelf_dbs(); + let pass_busy = self.pass_busy(); + if repertoire_visible { + #[cfg(not(web))] + self.show_repertoire(ui, &ctx); + } else if let Some(game) = &mut self.game { + let input_enabled = self.confirm_close.is_none(); + // A database opened for the reference tab arrives here (the library is + // not drawn while a game is shown). + self.library.poll(); + self.reference.dbs = shelf; + // The preparation's engine goes on under the game; no game analysis meanwhile. + game.engine_busy = + self.prep.as_ref().is_some_and(|p| p.running()) || self.library.pass.is_some(); + game.engine_busy_why = pass_busy.clone(); + if let Some(p) = self.prep.as_mut() { + p.poll_quietly(&ctx, &self.settings); + } + let actions = game.show( + ui, + &mut self.settings, + &mut self.analysis, + &mut self.reference, + &mut self.translation, + input_enabled, + ); + self.reference_tab = game.reference_tab(); + let game_back_previous = game.previous_prep && game.previous.is_some(); + // Before the actions: leaving may take the game away. + if let Some(res) = game.record_news.take() { + let name = game.player_name(); + self.recorded(&ctx, &name, res, false); + } + for a in actions { + match a { + GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary), + GameAction::BackKey => { + // Ctrl+W: back where the game was opened from (the report, a + // game), else to the library. + let intent = if game_back_previous { + CloseIntent::ReturnToPrevious + } else { + CloseIntent::BackToLibrary + }; + self.request_close(&ctx, intent); + } + // The game's database in the library, the game's row shown (its row is + // revealed as the game closes). + GameAction::OpenDatabase(path) => { + self.library.select_db(&path, &ctx); + self.request_close(&ctx, CloseIntent::BackToLibrary); + } + GameAction::FindPosition(db) => self.find_position(&ctx, db), + GameAction::ReferenceChoose(p) => { + self.settings.reference_db = Some(p); + self.settings_dirty = true; + } + GameAction::ReferenceLoad(p) => self.library.load(&p, &ctx), + GameAction::OpenGame(path, index, at) => { + if let Some(mut prev) = self.game.take() { + let title = prev.title(); + prev.suspend(); + self.previous_games.push(prev); + self.open_game(&ctx, path, index, Some(at)); + match &mut self.game { + Some(g) => { + g.previous = Some(title); + g.show_reference_tab(); + } + // Not opened: back to where we were. + None => self.game = self.previous_games.pop(), + } + } + } + #[cfg(not(web))] + GameAction::OpenUpdate => self.desktop.update_ui.open = true, + #[cfg(web)] + GameAction::DownloadPgn => self.download_pgn(&ctx), + GameAction::ReturnToPrevious => { + if !self.previous_games.is_empty() + || self.prep.as_ref().is_some_and(|p| p.shown) + { + self.request_close(&ctx, CloseIntent::ReturnToPrevious); + } + } + GameAction::NeedEngine { full } => { + if let Some(game) = self.game.as_ref().map(|g| g.serial) { + let pending = crate::engine_offer::Pending::GameAnalysis { game, full }; + self.need_review_engine(&ctx, pending); + } + } + GameAction::Sound(s) => self.play(s), + GameAction::CopyText(text, msg) => { + ctx.copy_text(text); + self.toast(&ctx, msg); + } + GameAction::Save => self.save_current(&ctx, None), + GameAction::Leave(intent) => self.request_close(&ctx, intent), + GameAction::SaveAndLeave(intent) => self.save_current(&ctx, Some(intent)), + GameAction::Rematch => { + let next = self + .game + .as_ref() + .and_then(|g| g.play_end.clone()) + .map(|e| { + let mut s = e.start; + // From a position the colour is part of the task: the same. + s.user = match self.settings.play.color { + _ if s.from.is_some() => s.user, + crate::play::ColorChoice::Random => { + if crate::play::random_unit() < 0.5 { + chess_core::shakmaty::Color::White + } else { + chess_core::shakmaty::Color::Black + } + } + _ => !s.user, + }; + s + }); + if let Some(s) = next { + // From a position: back over the game it came from. + let intent = if s.from.is_some() && !self.previous_games.is_empty() { + CloseIntent::ReturnToPrevious + } else { + CloseIntent::BackToLibrary + }; + self.play_next = Some(PlayNext::Rematch(s)); + self.request_close(&ctx, intent); + } + } + GameAction::PlayAgain => { + let from = self + .game + .as_ref() + .and_then(|g| g.play_end.as_ref()) + .and_then(|e| e.start.from.clone()); + let intent = if from.is_some() && !self.previous_games.is_empty() { + CloseIntent::ReturnToPrevious + } else { + CloseIntent::BackToLibrary + }; + self.play_next = Some(PlayNext::Dialog(from)); + self.request_close(&ctx, intent); + } + #[cfg(not(web))] + GameAction::AddToRepertoire(game, at) => { + self.open_repertoire_add(&ctx, *game, at) + } + GameAction::PlayFrom(from) => self.play_new(&ctx, PlayNext::Dialog(Some(from))), + GameAction::PutAside(intent) => { + let intent = intent.unwrap_or( + if self.game.as_ref().is_some_and(|g| g.previous.is_some()) { + CloseIntent::ReturnToPrevious + } else { + CloseIntent::BackToLibrary + }, + ); + if self.put_game_aside(&ctx) { + // Over another game the shelf is not in view: said. + if intent == CloseIntent::ReturnToPrevious { + self.toast(&ctx, tr("Game put aside: go on from the library")); + } + self.request_close(&ctx, intent); + } + } + GameAction::AddToDatabase => { + if let Some(g) = self.game.as_mut() { + g.commit_editor(); + } + self.own.then_close = None; + self.open_chooser(&ctx, ChooserFor::CurrentGame); + } + GameAction::EditGameData => self.edit_game_data(), + GameAction::ToggleEngine => self.toggle_engine(&ctx), + GameAction::EngineReconfigure => { + self.settings_dirty = true; + if self.analysis.is_on() + && let Some(cfg) = self.settings.active_engine().cloned() + { + self.analysis.reconfigure(&cfg, &ctx); + } + } + GameAction::EngineSwitch => { + self.settings_dirty = true; + if self.analysis.is_on() + && let Some(cfg) = self.settings.active_engine().cloned() + { + self.analysis.start(&cfg, &ctx); + } + } + GameAction::OpenEngineSettings => { + self.settings_ui.open = true; + self.settings_ui.tab = Tab::Engines; + } + GameAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open, + GameAction::OpenTranslationSettings => { + self.settings_ui.open = true; + self.settings_ui.tab = Tab::Translation; + } + GameAction::Toast(m) => self.toast(&ctx, m), + GameAction::Reviewed { path, index, entry } => { + let marks = self.library.marks(&path); + if let Ok(mut marks) = marks.lock() { + marks.set(index as u32, entry); + if let Err(e) = marks.save() { + eprintln!("marks: {e}"); + } + } + } + GameAction::HintsChanged => self.settings_dirty = true, + GameAction::PauseLive => { + if self.analysis.is_on() { + self.analysis.stop(); + self.live_paused = true; + } + } + GameAction::ResumeLive => { + if std::mem::take(&mut self.live_paused) + && let Some(cfg) = self.settings.active_engine().cloned() + { + self.analysis.start(&cfg, &ctx); + } + } + } + } + } else if self.prep.as_ref().is_some_and(|p| p.shown) { + self.library.poll(); + let actions = match self.prep.as_mut() { + Some(p) => p.show(ui, &mut self.settings), + None => Vec::new(), + }; + self.prep_actions(&ctx, actions); + } else { + let dbs = self.settings.databases.clone(); + if let Some(p) = self.prep.as_mut() { + p.poll_quietly(&ctx, &self.settings); + } + // Ctrl+Shift+P: «Prepare against…» with the player of the filter. + if ctx.input_mut(|i| { + i.consume_shortcut(&KeyboardShortcut::new( + Modifiers::COMMAND | Modifiers::SHIFT, + Key::P, + )) + }) && self.prep_dialog.is_none() + && let Some((path, entry)) = self.library.prep_entry() + { + self.prep_dialog = Some(PrepDialog::new(path, entry.unwrap_or_default())); + } + #[cfg(not(web))] + { + let d = &mut self.desktop; + d.online_probe.poll(); + self.library.online = d.online_probe.any(); + self.library.online_busy = d.online.busy(); + self.library.online_running = d.online.running(); + } + #[cfg(web)] + self.draft_strip(ui, &ctx); + for a in self.library.show(ui, &dbs, &self.settings) { + match a { + LibraryAction::OpenGame { path, index, at } => { + self.open_game(&ctx, path, index, at) + } + LibraryAction::OpenGameReport { path, index, at } => { + self.open_game(&ctx, path, index, at); + if let Some(g) = self.game.as_mut() { + g.show_report(); + } + } + LibraryAction::Sound(s) => self.play(s), + LibraryAction::CopyText(text, msg) => { + ctx.copy_text(text); + self.toast(&ctx, msg); + } + LibraryAction::OpenPgn(text) => self.open_pgn_text(&ctx, text, true), + LibraryAction::NewGame => self.new_game(), + LibraryAction::ResumeAside => self.resume_aside(&ctx), + LibraryAction::DiscardAside => { + if self.library.aside.as_ref().is_some_and(|c| c.db.is_some()) { + self.let_go_aside(&ctx); + } else { + self.aside_delete = true; + } + } + LibraryAction::Play => self.play_new(&ctx, PlayNext::Dialog(None)), + LibraryAction::NewGameIn(path) => { + self.new_game(); + if let Some(g) = self.game.as_mut() { + g.target = Some(path); + } + } + LibraryAction::PastePgn => self.paste_pgn(&ctx), + LibraryAction::AddDatabases => self.pick_databases(&ctx), + #[cfg(not(web))] + LibraryAction::OnlineGames => self.desktop.online.open(), + #[cfg(not(web))] + LibraryAction::UpdateOnline(p) => self.desktop.online.update(&p, &ctx), + #[cfg(not(web))] + LibraryAction::OpenUpdate => self.desktop.update_ui.open = true, + LibraryAction::RemoveDatabase(p) => { + self.settings.databases.retain(|d| *d != p); + self.library.forget(&p); + crate::platform::files::forget(&p); + self.settings_dirty = true; + // The file stays where it is; said so, with the place. + self.toast = Some(Toast { + text: trf( + "Removed from the shelf; the file stays: {path}", + &[("path", &crate::platform::files::shown(&p))], + ), + until: ctx.input(|i| i.time) + 6.0, + undo: false, + }); + } + #[cfg(web)] + LibraryAction::AllowReading(p) => { + let (tx, wake) = (self.tx.clone(), ctx.clone()); + crate::platform::files::allow_reading(&p.clone(), move |back| { + if back { + let _ = tx.send(Async::ReadAllowed(p)); + } + wake.request_repaint(); + }); + } + LibraryAction::ChooseAgain(p) => { + self.choosing_again = Some(p); + self.pick_databases(&ctx); + } + #[cfg(web)] + LibraryAction::ChooseFolderAgain(p) => { + self.choosing_again = Some(p); + self.pick_database_folder(&ctx); + } + LibraryAction::KeepCopy(p) => self.keep_copy(&ctx, p), + LibraryAction::OpenSettings => self.settings_ui.open = true, + LibraryAction::NewDatabase => { + self.own.then_close = None; + self.new_base_dialog(own_db::AfterCreate::Shelf); + } + LibraryAction::Utf8Copy(path) => self.utf8_copy(path), + LibraryAction::DeleteGame { path, index } => { + self.delete_game(&ctx, path, index) + } + LibraryAction::AddGameToDatabase { path, index } => { + self.own.then_close = None; + self.open_chooser(&ctx, ChooserFor::Record { path, index }); + } + LibraryAction::CopySelection { + path, + records, + sort, + ascending, + hidden, + } => { + self.own.then_close = None; + self.new_base_dialog(own_db::AfterCreate::CopySelection { + path, + records, + sort, + ascending, + hidden, + }); + // `CP_BATCH=new:`: the dialog answered at once. + if let Some(name) = std::env::var("CP_BATCH") + .ok() + .and_then(|b| b.strip_prefix("new:").map(str::to_owned)) + && let Some(d) = self.own.new_base.as_mut() + { + d.name = name; + let target = d.path(); + match self.start_copy(&ctx, target) { + Ok(()) => self.own.new_base = None, + Err(e) => { + if let Some(d) = self.own.new_base.as_mut() { + d.error = Some(e); + } + } + } + } + } + LibraryAction::Notice(text) => self.toast(&ctx, text), + LibraryAction::FindGreatMoves { + path, + records, + filter, + about, + selected, + } => self.ask_great_moves(&ctx, path, records, filter, about, selected), + LibraryAction::EditGameData { path, index } => { + self.open_game(&ctx, path, index, None); + self.edit_game_data(); + } + LibraryAction::PrepareAgainst { path, entry } => { + self.prep_dialog = Some(PrepDialog::new(path, entry)); + } + LibraryAction::Preparations => { + self.prep_list = Some(crate::prep_ui::PrepList::new()); + } + #[cfg(not(web))] + LibraryAction::OpeningTraining => self.open_repertoire(&ctx), + } + } + } + + #[cfg(not(web))] + self.desktop_frame(&ctx); + + self.settings_ui.download = self.engine_offer.stage(); + self.settings_dirty |= self.translation.poll(&ctx, &mut self.settings); + self.settings_dirty |= self.translation.windows(&ctx, &mut self.settings); + if std::mem::take(&mut self.translation.open_settings) { + self.settings_ui.open = true; + self.settings_ui.tab = Tab::Translation; + } + let (actions, changed) = + self.settings_ui + .show(&ctx, &mut self.settings, &mut self.translation); + self.settings_dirty |= changed; + for a in actions { + match a { + #[cfg(not(web))] + SettingsAction::AddEngine => self.pick_engine(&ctx), + #[cfg(not(web))] + SettingsAction::CheckUpdates => { + self.desktop.update_check = self.desktop.update_check.again(&ctx); + } + #[cfg(not(web))] + SettingsAction::PickBaseFolder => { + let start = own_db::default_base_dir(self.settings.new_database_dir.as_deref()); + self.pick_folder(&ctx, start); + } + #[cfg(not(web))] + SettingsAction::OpenUpdate => self.desktop.update_ui.open = true, + #[cfg(web)] + SettingsAction::DownloadMyGames => { + if let Err(e) = crate::my_games::download_all() { + self.toast( + &ctx, + trf("The PGN could not be downloaded: {e}", &[("e", &e)]), + ); + } + } + #[cfg(web)] + SettingsAction::KeepData => { + let ctx = ctx.clone(); + crate::platform::web::storage::persist(move |_| ctx.request_repaint()); + } + SettingsAction::DownloadEngine => self.engine_offer.start(&ctx), + SettingsAction::CancelDownload => self.engine_offer.cancel(), + SettingsAction::RemoveDownloaded => { + if let Err(e) = crate::engine_download::remove() { + self.toast(&ctx, e.to_string()); + } + if self.settings.active_engine().is_some_and(|e| e.builtin) + && !crate::engine_offer::EngineOffer::engine_ready(&self.settings) + { + self.analysis.stop(); + } + } + SettingsAction::TestSound => { + if self.settings.sound_enabled { + self.sound + .play(self.settings.sound_set, Sound::Move, self.settings.volume); + } + } + SettingsAction::EngineChanged => { + if self.analysis.is_on() { + self.analysis.stop(); + if let Some(cfg) = self.settings.active_engine().cloned() { + self.analysis.start(&cfg, &ctx); + } + } + } + } + } + + self.confirm_dialog(&ctx); + self.own_dialogs(&ctx); + self.prep_list(&ctx); + self.prep_dialog(&ctx); + self.prep_quit_question(&ctx); + // Whether the database the dialog names is there, as last found. + if let Some(d) = self.play_dialog.as_mut() { + d.target_there = d + .record_target() + .is_some_and(|p| self.library.files.get(p).is_some_and(|s| s.exists)); + } + // The number of games of the database the dialog names (read once, if needed). + if let Some(d) = self.play_dialog.as_mut() + && let Some(path) = d.record_target().map(std::path::Path::to_path_buf) + && self.library.files.exists(&path) + && !d.counts.contains_key(&path) + { + match self.library.database(&path) { + Some(db) => { + d.counts.insert(path, db.len()); + } + None if !self.library.loading(&path) && self.library.failure(&path).is_none() => { + self.library.load(&path, &ctx) + } + None => {} + } + } + self.aside_question(&ctx); + self.aside_delete_question(&ctx); + self.aside_fetch_question(&ctx); + if let Some(d) = self.play_dialog.as_mut() + && let Some(out) = d.show(&ctx, &mut self.settings) + { + self.play_dialog = None; + if let crate::play::DialogOutcome::Play(start) = out { + self.settings_dirty = true; + self.start_play(&ctx, start); + } + } + // A copy of chosen games ends whatever is on the screen. + self.great_moves_frame(&ctx); + if let Some(end) = self.library.poll_batch(&ctx) { + self.batch_ended(&ctx, end); + } + // Ctrl+Z on the library while the deleted game can still come back. + if self.game.is_none() + && self.own.undo.is_some() + && self.toast.as_ref().is_some_and(|t| t.undo) + && ctx.input_mut(|i| { + i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::Z)) + }) + { + self.undo_delete(&ctx); + } + + let mut undo_clicked = false; + let mut open_copy: Option = None; + #[cfg(not(web))] + let mut open_repertoire = None; + if let Some(t) = &self.toast { + let now = ctx.input(|i| i.time); + if now > t.until { + self.toast = None; + self.own.undo = None; + #[cfg(not(web))] + { + self.toast_repertoire = None; + } + } else { + let (msg, undo) = (t.text.clone(), t.undo && self.own.undo.is_some()); + #[cfg(not(web))] + let repertoire_link = self.toast_repertoire.clone(); + let open_db = self.toast_open_db.clone(); + #[cfg(not(web))] + let has_action = undo || repertoire_link.is_some() || open_db.is_some(); + #[cfg(web)] + let has_action = undo || open_db.is_some(); + let area = egui::Area::new(egui::Id::new(TOAST)) + .anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0)) + .order(egui::Order::Foreground) + .show(&ctx, |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + // Long messages wrap: at most 560 wide, inside a narrow window. + ui.set_max_width((ctx.content_rect().width() - 32.0).min(560.0)); + ui.horizontal_wrapped(|ui| { + ui.add( + egui::Label::new(RichText::new(msg.as_str()).size(14.0)).wrap(), + ); + if undo && ui.button(tr("Undo")).on_hover_text("Ctrl+Z").clicked() { + undo_clicked = true; + } + #[cfg(not(web))] + if repertoire_link.is_some() && ui.button(tr("Open")).clicked() { + open_repertoire = repertoire_link.clone(); + } + if open_db.is_some() && ui.button(tr("Open")).clicked() { + open_copy = open_db.clone(); + } + }); + }); + }); + // Under the mouse the toast waits (the button is being reached for). + if has_action + && area.response.contains_pointer() + && let Some(t) = self.toast.as_mut() + { + t.until = t.until.max(now + 1.5); + } + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } + } + if undo_clicked { + self.toast = None; + self.undo_delete(&ctx); + } + if let Some(path) = open_copy { + self.toast = None; + self.toast_open_db = None; + self.settings.touch_database(&path); + self.settings_dirty = true; + self.library.select_db(&path, &ctx); + } + #[cfg(not(web))] + if let Some((id, title)) = open_repertoire { + self.toast = None; + self.toast_repertoire = None; + self.open_repertoire(&ctx); + if let Some(screen) = self.repertoire.as_mut() { + screen.open_from_toast(id, title, &self.settings); + } + } + + if self.settings_dirty && !ctx.input(|i| i.pointer.any_down()) { + self.settings_dirty = false; + if let Err(e) = self.settings.save() { + eprintln!("settings: save failed: {e}"); + } + crate::review_engine::set_candidates(&self.settings); + } + } + + fn on_exit(&mut self) { + self.library.stop_batch(); + if let Some(job) = self.library.pass.as_mut() { + job.shutdown(std::time::Duration::from_secs(3)); + } + self.analysis.stop(); + crate::review_engine::shutdown(); + if let Some(p) = self.prep.as_mut() { + p.save(); + } + // Downloads of online games stop and save what they got; a new database goes on + // the shelf with it (the next download continues it). + #[cfg(not(web))] + for p in self.desktop.online.stop_all() { + if crate::online::State::load(&p).is_some_and(|s| s.games > 0) { + self.settings.touch_database(&p); + } + } + let _ = self.settings.save(); + } +} + +/// What the user chose or dropped, to the screen. +/// Sends what was chosen in a dialog (`dropped`: dropped on the window) to the screen. +/// A dialog's choice is sent even when empty (cancelled): «Choose again» ends with it. +fn send_picked(tx: &Sender, picked: crate::platform::files::Picked, dropped: bool) { + if dropped { + if !picked.paths.is_empty() { + let _ = tx.send(Async::DatabasesDropped(picked.paths)); + } + } else { + let _ = tx.send(Async::DatabasesPicked(picked.paths)); + } + if !picked.missing.is_empty() { + let _ = tx.send(Async::Missing(picked.missing)); + } + if picked.empty_folder { + let _ = tx.send(Async::EmptyFolder); + } + if !picked.unsupported.is_empty() { + let _ = tx.send(Async::NotDatabases(picked.unsupported)); + } + #[cfg(web)] + { + if !picked.too_big.is_empty() { + let _ = tx.send(Async::TooBig(picked.too_big)); + } + if !picked.incomplete.is_empty() { + let _ = tx.send(Async::Incomplete(picked.incomplete)); + } + } +} + +/// Whether an action waiting for an engine still has its screen: the game (by its +/// serial) or the preparation on which it was asked. +fn still_waiting( + pending: &crate::engine_offer::Pending, + game: Option, + prep: Option, +) -> bool { + use crate::engine_offer::Pending; + match pending { + Pending::GameAnalysis { game: g, .. } => Some(*g) == game, + Pending::OpeningErrors { prep: p } => Some(*p) == prep, + Pending::LiveAnalysis => false, + // The app keeps its question (`brilliant_waiting`) until it starts. + Pending::GreatMoves => true, + } +} + +/// Files' names for a message: at most three, each at most 40 characters. +fn names_text(names: &[String]) -> String { + let mut text = names + .iter() + .take(3) + .map(|n| crate::widgets::shorten(n, 40)) + .collect::>() + .join(", "); + if names.len() > 3 { + text.push_str(", …"); + } + text +} + +fn sanitize(s: &str) -> String { + s.chars() + .map(|c| match c { + '—' | '–' => '-', + c if c.is_alphanumeric() || " -.,".contains(c) => c, + _ => '_', + }) + .collect::() +} + +/// Why a game against the engine (Maia, a rematch, the game put aside) may not start: +/// the search for great moves has the engine (`pass`: its message while it runs). +fn engine_game_refused(pass: Option) -> Option { + pass.map(|why| { + format!( + "{} {}", + tr("A game against the engine waits until the search for great moves ends."), + why + ) + }) +} + +#[cfg(test)] +mod waiting_tests { + use super::{names_text, still_waiting}; + use crate::engine_offer::Pending; + + /// An analysis waiting for an engine starts on its own game only: another game on + /// the screen, or none, drops it; the two kinds wait apart. + #[test] + fn a_waiting_analysis_belongs_to_its_game() { + let review = Pending::GameAnalysis { + game: 7, + full: true, + }; + let errors = Pending::OpeningErrors { prep: 3 }; + assert!(still_waiting(&review, Some(7), None)); + assert!(!still_waiting(&review, Some(8), Some(3))); + assert!(!still_waiting(&review, None, Some(3))); + assert!(still_waiting(&errors, Some(8), Some(3))); + assert!(!still_waiting(&errors, Some(7), Some(4))); + assert!(!still_waiting(&Pending::LiveAnalysis, Some(7), Some(3))); + } + + /// Every way to a game against the engine asks the same guard: refused while the + /// search for great moves runs, allowed otherwise. + #[test] + fn a_game_against_the_engine_waits_for_the_search() { + assert!(super::engine_game_refused(None).is_none()); + let why = super::engine_game_refused(Some("x".into())).unwrap(); + assert!(why.ends_with('x')); + let src = include_str!("app.rs"); + for f in ["fn resume_aside(", "fn start_play("] { + let body = &src[src.find(f).unwrap()..]; + let guard = body.find("engine_game_refused(self.pass_busy())").unwrap(); + let first_return = body.find("return").unwrap(); + assert!(guard < first_return + 40, "{f} checks the search first"); + } + } + + #[test] + fn names_in_messages_are_short() { + let names: Vec = ["a.pgn", "b.pgn", "c.pgn", "d.pgn"] + .map(String::from) + .into(); + assert_eq!(names_text(&names), "a.pgn, b.pgn, c.pgn, …"); + let long = vec!["x".repeat(100) + ".pgn"]; + assert_eq!(names_text(&long).chars().count(), 40); + } +} diff --git a/apps/desktop/src/assets.rs b/apps/desktop/src/assets.rs new file mode 100644 index 0000000..388fdaf --- /dev/null +++ b/apps/desktop/src/assets.rs @@ -0,0 +1,693 @@ +//! Bundled piece sets, board themes and sounds (see THIRD_PARTY_NOTICES.md). + +use crate::i18n::tr; +use egui::{Color32, Rect}; +use serde::{Deserialize, Serialize}; +use shakmaty::{Color, Piece, Role}; + +macro_rules! piece_set { + ($name:literal) => { + [ + include_bytes!(concat!("../assets/pieces/", $name, "/wK.svg")).as_slice(), + include_bytes!(concat!("../assets/pieces/", $name, "/wQ.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/wR.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/wB.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/wN.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/wP.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/bK.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/bQ.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/bR.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/bB.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/bN.svg")), + include_bytes!(concat!("../assets/pieces/", $name, "/bP.svg")), + ] + }; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum PieceSet { + #[default] + Cburnett, + Merida, + Mpchess, + Chessnut, + Fantasy, + Celtic, + Spatial, + Rhosgfx, + Shapes, + KiwenSuwi, + Firi, + Pixel, + Letter, + Pirouetti, + Governor, + Kosal, + Metaltops, +} + +impl PieceSet { + pub const ALL: [PieceSet; 17] = [ + PieceSet::Cburnett, + PieceSet::Merida, + PieceSet::Mpchess, + PieceSet::Chessnut, + PieceSet::Fantasy, + PieceSet::Celtic, + PieceSet::Spatial, + PieceSet::Rhosgfx, + PieceSet::Shapes, + PieceSet::KiwenSuwi, + PieceSet::Firi, + PieceSet::Pixel, + PieceSet::Letter, + PieceSet::Pirouetti, + PieceSet::Governor, + PieceSet::Kosal, + PieceSet::Metaltops, + ]; + + pub fn name(self) -> &'static str { + match self { + PieceSet::Cburnett => "cburnett", + PieceSet::Merida => "merida", + PieceSet::Mpchess => "mpchess", + PieceSet::Chessnut => "chessnut", + PieceSet::Fantasy => "fantasy", + PieceSet::Celtic => "celtic", + PieceSet::Spatial => "spatial", + PieceSet::Rhosgfx => "rhosgfx", + PieceSet::Shapes => "shapes", + PieceSet::KiwenSuwi => "kiwen-suwi", + PieceSet::Firi => "firi", + PieceSet::Pixel => "pixel", + PieceSet::Letter => "letter", + PieceSet::Pirouetti => "pirouetti", + PieceSet::Governor => "governor", + PieceSet::Kosal => "kosal", + PieceSet::Metaltops => "metaltops", + } + } + + fn files(self) -> [&'static [u8]; 12] { + match self { + PieceSet::Cburnett => piece_set!("cburnett"), + PieceSet::Merida => piece_set!("merida"), + PieceSet::Mpchess => piece_set!("mpchess"), + PieceSet::Chessnut => piece_set!("chessnut"), + PieceSet::Fantasy => piece_set!("fantasy"), + PieceSet::Celtic => piece_set!("celtic"), + PieceSet::Spatial => piece_set!("spatial"), + PieceSet::Rhosgfx => piece_set!("rhosgfx"), + PieceSet::Shapes => piece_set!("shapes"), + PieceSet::KiwenSuwi => piece_set!("kiwen-suwi"), + PieceSet::Firi => piece_set!("firi"), + PieceSet::Pixel => piece_set!("pixel"), + PieceSet::Letter => piece_set!("letter"), + PieceSet::Pirouetti => piece_set!("pirouetti"), + PieceSet::Governor => piece_set!("governor"), + PieceSet::Kosal => piece_set!("kosal"), + PieceSet::Metaltops => piece_set!("metaltops"), + } + } + + fn index(piece: Piece) -> usize { + let r = match piece.role { + Role::King => 0, + Role::Queen => 1, + Role::Rook => 2, + Role::Bishop => 3, + Role::Knight => 4, + Role::Pawn => 5, + }; + if piece.color == Color::White { + r + } else { + r + 6 + } + } + + fn uri(self, piece: Piece) -> String { + format!("bytes://pieces/{}/{}.svg", self.name(), Self::index(piece)) + } + + /// The piece's picture, to put in a widget. + pub fn image(self, piece: Piece) -> egui::Image<'static> { + egui::Image::new(self.uri(piece)) + } + + pub fn paint(self, ui: &egui::Ui, piece: Piece, rect: Rect) { + egui::Image::new(self.uri(piece)).paint_at(ui, rect); + } + + pub fn paint_tinted(self, ui: &egui::Ui, piece: Piece, rect: Rect, tint: egui::Color32) { + egui::Image::new(self.uri(piece)) + .tint(tint) + .paint_at(ui, rect); + } +} + +/// Registers all bundled SVGs with egui's byte loader. +pub fn install(ctx: &egui::Context) { + egui_extras::install_image_loaders(ctx); + for set in PieceSet::ALL { + for (i, bytes) in set.files().into_iter().enumerate() { + ctx.include_bytes(format!("bytes://pieces/{}/{i}.svg", set.name()), bytes); + } + } + for (name, bytes) in TEXTURES { + ctx.include_bytes(format!("bytes://boards/{name}"), *bytes); + } + 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. +pub fn font_definitions() -> egui::FontDefinitions { + // Arrows (→ ⇄ ↔) are only in egui's monospace font, and three evaluation signs + // (⩲ ⩱ ⌓) in none: the last fallbacks of the text. + let mut fonts = egui::FontDefinitions::default(); + fonts.font_data.insert( + "nag-symbols".into(), + std::sync::Arc::new(egui::FontData::from_static(include_bytes!( + "../assets/fonts/NotoSansMath-nag.ttf" + ))), + ); + // Figurines in move notation (♔♕♖♗♘): a copy of egui's icon glyphs, a little + // smaller and on the baseline (the icons themselves stay as they are). + fonts.font_data.insert( + "figurine".into(), + std::sync::Arc::new( + egui::FontData::from_static(include_bytes!("../assets/fonts/figurines.ttf")).tweak( + egui::FontTweak { + scale: 0.85, + y_offset: -1.0, + ..Default::default() + }, + ), + ), + ); + // The bold face of the same family (egui's text is Ubuntu Light): the moves of the + // 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) { + list.insert(1, "figurine".into()); + } + } + let mono = fonts + .families + .get(&egui::FontFamily::Monospace) + .and_then(|f| f.first()) + .cloned(); + 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(m) = &mono + && !list.contains(m) + { + list.push(m.clone()); + } + list.push("nag-symbols".into()); + } + } + fonts +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum BoardThemeId { + #[default] + Brown, + Blue, + Green, + Tournament, + Sand, + Coral, + Grey, + Purple, + Ic, + Ncf, + Ice, + Navy, + Mint, + Emerald, + Orange, + Rose, + Dusk, + Night, + Wood, + Wood2, + Wood3, + Wood4, + Maple, + Maple2, + Leather, + Marble, + BlueMarble, + Blue2, + Blue3, + Canvas, + Metal, + Olive, + Stone, + GreenPlastic, + PurpleDiag, + PinkPyramid, + Horsey, +} + +#[derive(Clone, Copy, Debug)] +pub struct BoardTheme { + pub light: Color32, + pub dark: Color32, + /// Full-board image (8×8 squares, a1 dark) drawn instead of flat squares. + pub texture: Option<&'static str>, + pub last_move: Color32, + pub selected: Color32, + pub dot: Color32, +} + +/// Board image textures from Lichess (see THIRD_PARTY_NOTICES.md). +const TEXTURES: &[(&str, &[u8])] = &[ + ("wood.jpg", include_bytes!("../assets/boards/wood.jpg")), + ("wood2.jpg", include_bytes!("../assets/boards/wood2.jpg")), + ("wood3.jpg", include_bytes!("../assets/boards/wood3.jpg")), + ("wood4.jpg", include_bytes!("../assets/boards/wood4.jpg")), + ("maple.jpg", include_bytes!("../assets/boards/maple.jpg")), + ("maple2.jpg", include_bytes!("../assets/boards/maple2.jpg")), + ( + "leather.jpg", + include_bytes!("../assets/boards/leather.jpg"), + ), + ("marble.jpg", include_bytes!("../assets/boards/marble.jpg")), + ( + "blue-marble.jpg", + include_bytes!("../assets/boards/blue-marble.jpg"), + ), + ("blue2.jpg", include_bytes!("../assets/boards/blue2.jpg")), + ("blue3.jpg", include_bytes!("../assets/boards/blue3.jpg")), + ( + "canvas2.jpg", + include_bytes!("../assets/boards/canvas2.jpg"), + ), + ("metal.jpg", include_bytes!("../assets/boards/metal.jpg")), + ("olive.jpg", include_bytes!("../assets/boards/olive.jpg")), + ("grey.jpg", include_bytes!("../assets/boards/grey.jpg")), + ( + "green-plastic.png", + include_bytes!("../assets/boards/green-plastic.png"), + ), + ( + "purple-diag.png", + include_bytes!("../assets/boards/purple-diag.png"), + ), + ( + "pink-pyramid.png", + include_bytes!("../assets/boards/pink-pyramid.png"), + ), + ("horsey.jpg", include_bytes!("../assets/boards/horsey.jpg")), +]; + +impl BoardThemeId { + pub const ALL: [BoardThemeId; 37] = [ + BoardThemeId::Brown, + BoardThemeId::Blue, + BoardThemeId::Green, + BoardThemeId::Tournament, + BoardThemeId::Sand, + BoardThemeId::Coral, + BoardThemeId::Grey, + BoardThemeId::Purple, + BoardThemeId::Ic, + BoardThemeId::Ncf, + BoardThemeId::Ice, + BoardThemeId::Navy, + BoardThemeId::Mint, + BoardThemeId::Emerald, + BoardThemeId::Orange, + BoardThemeId::Rose, + BoardThemeId::Dusk, + BoardThemeId::Night, + BoardThemeId::Wood, + BoardThemeId::Wood2, + BoardThemeId::Wood3, + BoardThemeId::Wood4, + BoardThemeId::Maple, + BoardThemeId::Maple2, + BoardThemeId::Leather, + BoardThemeId::Marble, + BoardThemeId::BlueMarble, + BoardThemeId::Blue2, + BoardThemeId::Blue3, + BoardThemeId::Canvas, + BoardThemeId::Metal, + BoardThemeId::Olive, + BoardThemeId::Stone, + BoardThemeId::GreenPlastic, + BoardThemeId::PurpleDiag, + BoardThemeId::PinkPyramid, + BoardThemeId::Horsey, + ]; + + pub fn label(self) -> String { + let (key, n): (&'static str, Option<&str>) = match self { + BoardThemeId::Brown => ("Brown", None), + BoardThemeId::Blue => ("Blue", None), + BoardThemeId::Green => ("Green", None), + BoardThemeId::Tournament => ("Tournament", None), + BoardThemeId::Sand => ("Sand", None), + BoardThemeId::Coral => ("Coral", None), + BoardThemeId::Grey => ("Grey", None), + BoardThemeId::Purple => ("Purple", None), + BoardThemeId::Ic => ("IC", None), + BoardThemeId::Ncf => ("NCF", None), + BoardThemeId::Ice => ("Ice", None), + BoardThemeId::Navy => ("Navy", None), + BoardThemeId::Mint => ("Mint", None), + BoardThemeId::Emerald => ("Emerald", None), + BoardThemeId::Orange => ("Orange", None), + BoardThemeId::Rose => ("Rose", None), + BoardThemeId::Dusk => ("Dusk", None), + BoardThemeId::Night => ("Night", None), + BoardThemeId::Wood => ("Wood", None), + BoardThemeId::Wood2 => ("Wood", Some("2")), + BoardThemeId::Wood3 => ("Wood", Some("3")), + BoardThemeId::Wood4 => ("Wood", Some("4")), + BoardThemeId::Maple => ("Maple", None), + BoardThemeId::Maple2 => ("Maple", Some("2")), + BoardThemeId::Leather => ("Leather", None), + BoardThemeId::Marble => ("Marble", None), + BoardThemeId::BlueMarble => ("Blue marble", None), + BoardThemeId::Blue2 => ("Blue", Some("2")), + BoardThemeId::Blue3 => ("Blue", Some("3")), + BoardThemeId::Canvas => ("Canvas", None), + BoardThemeId::Metal => ("Metal", None), + BoardThemeId::Olive => ("Olive", None), + BoardThemeId::Stone => ("Stone", None), + BoardThemeId::GreenPlastic => ("Green plastic", None), + BoardThemeId::PurpleDiag => ("Purple diagonal", None), + BoardThemeId::PinkPyramid => ("Pink pyramid", None), + BoardThemeId::Horsey => ("Sketch", None), + }; + match n { + Some(n) => format!("{} {n}", tr(key)), + None => tr(key).to_string(), + } + } + + pub fn theme(self) -> BoardTheme { + let rgb = |(r, g, b): (u8, u8, u8)| Color32::from_rgb(r, g, b); + let (light, dark, texture) = match self { + BoardThemeId::Brown => (rgb((240, 217, 181)), rgb((181, 136, 99)), None), + BoardThemeId::Blue => (rgb((222, 227, 230)), rgb((140, 162, 173)), None), + BoardThemeId::Green => (rgb((255, 255, 221)), rgb((134, 166, 102)), None), + BoardThemeId::Tournament => (rgb((238, 238, 210)), rgb((118, 150, 86)), None), + BoardThemeId::Sand => (rgb((240, 228, 196)), rgb((200, 168, 110)), None), + BoardThemeId::Coral => (rgb((177, 228, 185)), rgb((112, 162, 163)), None), + BoardThemeId::Grey => (rgb((217, 217, 217)), rgb((154, 154, 154)), None), + BoardThemeId::Purple => (rgb((232, 224, 240)), rgb((159, 144, 176)), None), + // The colours of the Lichess "ic" and "ncf-board" boards. + BoardThemeId::Ic => (rgb((236, 236, 236)), rgb((193, 193, 142)), None), + BoardThemeId::Ncf => (rgb((187, 207, 255)), rgb((84, 119, 202)), None), + BoardThemeId::Ice => (rgb((222, 234, 240)), rgb((122, 157, 178)), None), + BoardThemeId::Navy => (rgb((220, 226, 236)), rgb((70, 96, 140)), None), + BoardThemeId::Mint => (rgb((222, 241, 230)), rgb((118, 178, 148)), None), + BoardThemeId::Emerald => (rgb((226, 236, 218)), rgb((74, 132, 100)), None), + BoardThemeId::Orange => (rgb((250, 228, 196)), rgb((208, 139, 72)), None), + BoardThemeId::Rose => (rgb((242, 220, 220)), rgb((190, 126, 138)), None), + BoardThemeId::Dusk => (rgb((204, 186, 176)), rgb((112, 102, 122)), None), + BoardThemeId::Night => (rgb((128, 136, 146)), rgb((68, 74, 84)), None), + BoardThemeId::Wood => ( + rgb((215, 161, 91)), + rgb((154, 88, 35)), + Some("bytes://boards/wood.jpg"), + ), + BoardThemeId::Wood2 => ( + rgb((151, 124, 79)), + rgb((121, 95, 48)), + Some("bytes://boards/wood2.jpg"), + ), + BoardThemeId::Wood3 => ( + rgb((186, 173, 157)), + rgb((129, 94, 56)), + Some("bytes://boards/wood3.jpg"), + ), + BoardThemeId::Wood4 => ( + rgb((191, 158, 104)), + rgb((134, 91, 54)), + Some("bytes://boards/wood4.jpg"), + ), + BoardThemeId::Maple => ( + rgb((224, 190, 146)), + rgb((180, 111, 60)), + Some("bytes://boards/maple.jpg"), + ), + BoardThemeId::Maple2 => ( + rgb((222, 193, 151)), + rgb((167, 114, 85)), + Some("bytes://boards/maple2.jpg"), + ), + BoardThemeId::Leather => ( + rgb((206, 206, 198)), + rgb((192, 140, 18)), + Some("bytes://boards/leather.jpg"), + ), + BoardThemeId::Marble => ( + rgb((126, 150, 128)), + rgb((97, 120, 97)), + Some("bytes://boards/marble.jpg"), + ), + BoardThemeId::BlueMarble => ( + rgb((229, 224, 212)), + rgb((148, 158, 174)), + Some("bytes://boards/blue-marble.jpg"), + ), + BoardThemeId::Blue2 => ( + rgb((129, 151, 173)), + rgb((96, 118, 138)), + Some("bytes://boards/blue2.jpg"), + ), + BoardThemeId::Blue3 => ( + rgb((189, 200, 211)), + rgb((68, 114, 163)), + Some("bytes://boards/blue3.jpg"), + ), + BoardThemeId::Canvas => ( + rgb((203, 206, 223)), + rgb((114, 130, 156)), + Some("bytes://boards/canvas2.jpg"), + ), + BoardThemeId::Metal => ( + rgb((177, 177, 177)), + rgb((119, 119, 119)), + Some("bytes://boards/metal.jpg"), + ), + BoardThemeId::Olive => ( + rgb((173, 166, 148)), + rgb((132, 124, 106)), + Some("bytes://boards/olive.jpg"), + ), + BoardThemeId::Stone => ( + rgb((169, 169, 169)), + rgb((136, 136, 136)), + Some("bytes://boards/grey.jpg"), + ), + BoardThemeId::GreenPlastic => ( + rgb((241, 246, 178)), + rgb((89, 147, 93)), + Some("bytes://boards/green-plastic.png"), + ), + BoardThemeId::PurpleDiag => ( + rgb((227, 216, 238)), + rgb((151, 123, 178)), + Some("bytes://boards/purple-diag.png"), + ), + BoardThemeId::PinkPyramid => ( + rgb((237, 238, 191)), + rgb((242, 117, 117)), + Some("bytes://boards/pink-pyramid.png"), + ), + BoardThemeId::Horsey => ( + rgb((239, 222, 198)), + rgb((151, 112, 81)), + Some("bytes://boards/horsey.jpg"), + ), + }; + BoardTheme { + light, + dark, + texture, + last_move: Color32::from_rgba_unmultiplied(155, 199, 0, 105), + selected: Color32::from_rgba_unmultiplied(20, 85, 30, 125), + dot: Color32::from_rgba_unmultiplied(20, 85, 30, 110), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum SoundSet { + #[default] + Sfx, + Piano, + Futuristic, + Nes, + Wood, + Glass, + Clicks, +} + +impl SoundSet { + pub const ALL: [SoundSet; 7] = [ + SoundSet::Sfx, + SoundSet::Piano, + SoundSet::Futuristic, + SoundSet::Nes, + SoundSet::Wood, + SoundSet::Glass, + SoundSet::Clicks, + ]; + + pub fn label(self) -> &'static str { + match self { + SoundSet::Sfx => "SFX", + SoundSet::Piano => tr("Piano"), + SoundSet::Futuristic => tr("Futuristic"), + SoundSet::Nes => "NES", + SoundSet::Wood => tr("Wood"), + SoundSet::Glass => tr("Glass"), + SoundSet::Clicks => tr("Clicks"), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Sound { + Move, + Capture, + Check, + Checkmate, + /// A game lost — here: Maia offers to resign. + Defeat, + /// Not the move of the line (learning an opening). + Wrong, + /// The line done (learning an opening). + Success, + /// The player's clock got low (once a game). + LowTime, +} + +pub fn sound_bytes(set: SoundSet, sound: Sound) -> &'static [u8] { + macro_rules! s { + ($set:literal, $f:literal) => { + include_bytes!(concat!("../assets/sounds/", $set, "/", $f, ".ogg")).as_slice() + }; + } + // The Lichess sets have no checkmate sound of their own (it is the check sound there). + match (set, sound) { + (SoundSet::Sfx, Sound::Move) => s!("sfx", "Move"), + (SoundSet::Sfx, Sound::Capture) => s!("sfx", "Capture"), + (SoundSet::Sfx, Sound::Check | Sound::Checkmate) => s!("sfx", "Check"), + (SoundSet::Piano, Sound::Move) => s!("piano", "Move"), + (SoundSet::Piano, Sound::Capture) => s!("piano", "Capture"), + (SoundSet::Piano, Sound::Check | Sound::Checkmate) => s!("piano", "Check"), + (SoundSet::Futuristic, Sound::Move) => s!("futuristic", "Move"), + (SoundSet::Futuristic, Sound::Capture) => s!("futuristic", "Capture"), + (SoundSet::Futuristic, Sound::Check | Sound::Checkmate) => s!("futuristic", "Check"), + (SoundSet::Nes, Sound::Move) => s!("nes", "Move"), + (SoundSet::Nes, Sound::Capture) => s!("nes", "Capture"), + (SoundSet::Nes, Sound::Check | Sound::Checkmate) => s!("nes", "Check"), + (SoundSet::Wood, Sound::Move) => s!("wood", "Move"), + (SoundSet::Wood, Sound::Capture) => s!("wood", "Capture"), + (SoundSet::Wood, Sound::Check) => s!("wood", "Check"), + (SoundSet::Wood, Sound::Checkmate) => s!("wood", "Checkmate"), + (SoundSet::Glass, Sound::Move) => s!("glass", "Move"), + (SoundSet::Glass, Sound::Capture) => s!("glass", "Capture"), + (SoundSet::Glass, Sound::Check) => s!("glass", "Check"), + (SoundSet::Glass, Sound::Checkmate) => s!("glass", "Checkmate"), + (SoundSet::Clicks, Sound::Move) => s!("clicks", "Move"), + (SoundSet::Clicks, Sound::Capture) => s!("clicks", "Capture"), + (SoundSet::Clicks, Sound::Check) => s!("clicks", "Check"), + (SoundSet::Clicks, Sound::Checkmate) => s!("clicks", "Checkmate"), + (SoundSet::Sfx, Sound::Defeat) => s!("sfx", "Defeat"), + (SoundSet::Piano, Sound::Defeat) => s!("piano", "Defeat"), + (SoundSet::Futuristic, Sound::Defeat) => s!("futuristic", "Defeat"), + (SoundSet::Nes, Sound::Defeat) => s!("nes", "Defeat"), + (SoundSet::Wood, Sound::Defeat) => s!("wood", "Defeat"), + (SoundSet::Glass, Sound::Defeat) => s!("glass", "Defeat"), + (SoundSet::Clicks, Sound::Defeat) => s!("clicks", "Defeat"), + // One short falling tone for every set (Kenney, CC0). + (_, Sound::Wrong) => s!("common", "Wrong"), + // A double tick for every set (Kenney, CC0). + (_, Sound::LowTime) => s!("common", "LowTime"), + (SoundSet::Sfx, Sound::Success) => s!("sfx", "Success"), + (SoundSet::Piano, Sound::Success) => s!("piano", "Success"), + (SoundSet::Futuristic, Sound::Success) => s!("futuristic", "Success"), + (SoundSet::Nes, Sound::Success) => s!("nes", "Success"), + (SoundSet::Wood, Sound::Success) => s!("wood", "Success"), + (SoundSet::Glass, Sound::Success) => s!("glass", "Success"), + (SoundSet::Clicks, Sound::Success) => s!("clicks", "Success"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_sound_is_a_real_ogg_file() { + // Lichess keeps some sounds as git symlinks; a copied link is a few bytes of text. + for set in SoundSet::ALL { + for s in [ + Sound::Move, + Sound::Capture, + Sound::Check, + Sound::Checkmate, + Sound::Defeat, + Sound::LowTime, + ] { + let b = sound_bytes(set, s); + assert!(b.starts_with(b"OggS") && b.len() > 1000, "{set:?} {s:?}"); + } + } + } + + #[test] + fn every_piece_file_is_an_svg() { + for set in PieceSet::ALL { + for f in set.files() { + let head = String::from_utf8_lossy(&f[..f.len().min(400)]); + assert!(head.contains(", + count: usize, +} + +impl Selection { + pub fn contains(&self, index: usize) -> bool { + self.words + .get(index / 64) + .is_some_and(|w| w & (1 << (index % 64)) != 0) + } + + pub fn len(&self) -> usize { + self.count + } + + pub fn is_empty(&self) -> bool { + self.count == 0 + } + + pub fn insert(&mut self, index: usize) { + let word = index / 64; + if word >= self.words.len() { + self.words.resize(word + 1, 0); + } + let bit = 1 << (index % 64); + if self.words[word] & bit == 0 { + self.words[word] |= bit; + self.count += 1; + } + } + + pub fn remove(&mut self, index: usize) { + if let Some(w) = self.words.get_mut(index / 64) { + let bit = 1 << (index % 64); + if *w & bit != 0 { + *w &= !bit; + self.count -= 1; + } + } + } + + pub fn toggle(&mut self, index: usize) { + if self.contains(index) { + self.remove(index); + } else { + self.insert(index); + } + } + + pub fn clear(&mut self) { + self.words.clear(); + self.count = 0; + } + + /// Only `index` chosen. + pub fn only(&mut self, index: usize) { + self.clear(); + self.insert(index); + } + + /// Adds every record of `records` (a list of the table). + pub fn extend(&mut self, records: &[u32]) { + if let Some(&most) = records.iter().max() { + let words = most as usize / 64 + 1; + if words > self.words.len() { + self.words.resize(words, 0); + } + } + for &r in records { + let (word, bit) = (r as usize / 64, 1u64 << (r % 64)); + if self.words[word] & bit == 0 { + self.words[word] |= bit; + self.count += 1; + } + } + } + + /// The chosen records, in the order of their numbers. + pub fn records(&self) -> Vec { + let mut out = Vec::with_capacity(self.count); + for (n, &w) in self.words.iter().enumerate() { + let mut w = w; + while w != 0 { + let bit = w.trailing_zeros(); + out.push((n * 64) as u32 + bit); + w &= w - 1; + } + } + out + } + + /// The highest chosen record. + pub fn last(&self) -> Option { + let (n, w) = self + .words + .iter() + .enumerate() + .rev() + .find(|(_, w)| **w != 0)?; + Some(n * 64 + 63 - w.leading_zeros() as usize) + } + + /// Records from `len` on let go (a database with fewer records now). + pub fn retain_below(&mut self, len: usize) { + while let Some(last) = self.last().filter(|&l| l >= len) { + self.remove(last); + } + } + + /// How many of `records` are chosen. + pub fn count_in(&self, records: &[u32]) -> usize { + if self.is_empty() { + return 0; + } + records + .iter() + .filter(|&&r| self.contains(r as usize)) + .count() + } +} + +/// The PGN text of record `index` as «Add to database» copies it: the record's own +/// text when the file is PGN read without restoring letters, otherwise the game written +/// anew (a ChessBase database has no PGN; restored letters are in the copy). +pub fn record_text(db: &Database, index: usize) -> Option { + match db.as_pgn() { + Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index), + _ => db.load_game(index).map(|p| p.game.to_pgn()), + } +} + +/// What to copy: the chosen records (by number), the table's order and the new file. +#[derive(Clone, Debug)] +pub struct CopyRequest { + pub records: Vec, + pub sort: SortKey, + pub ascending: bool, + pub target: PathBuf, + /// A pause per record (`CP_BATCH_SLOW`): the progress can be seen and photographed. + pub slow: bool, +} + +/// How a copy went. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CopyReport { + pub copied: usize, + /// Record numbers (from 0) skipped as a copy of a record already copied: the same + /// PGN text, white space aside. + pub duplicates: Vec, + /// Record numbers (from 0) that could not be read. + pub unreadable: Vec, +} + +impl CopyReport { + pub fn skipped(&self) -> usize { + self.duplicates.len() + self.unreadable.len() + } +} + +/// Why nothing was written. +#[derive(Debug, thiserror::Error)] +pub enum CopyError { + /// A file of that name appeared meanwhile: it is not touched. + #[error("a file with this name is already there")] + Exists, + /// The source file changed on disk: the record numbers no longer mean the same games. + #[error("the source changed")] + SourceChanged, + #[error("{0}")] + Io(#[from] std::io::Error), +} + +impl CopyError { + /// The reason in the user's words. + pub fn reason(&self) -> String { + match self { + CopyError::Exists => tr("a file with this name is already there").to_owned(), + CopyError::SourceChanged => tr("the source changed").to_owned(), + CopyError::Io(e) => match e.kind() { + std::io::ErrorKind::StorageFull => tr("no space left on the disk").to_owned(), + std::io::ErrorKind::PermissionDenied => tr("no permission to write").to_owned(), + _ => e.to_string(), + }, + } + } +} + +/// The temporary file of a copy; removed unless published. +struct Partial { + path: PathBuf, + published: bool, +} + +impl Drop for Partial { + fn drop(&mut self) { + if !self.published { + let _ = std::fs::remove_file(&self.path); + } + } +} + +/// The temporary file of a copy into `target`: `..part--`, the +/// process that writes it in its name (`clean_orphans` knows from it whether its writer +/// is gone). +fn partial_path(target: &Path) -> PathBuf { + let name = target + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let mut h = std::collections::hash_map::DefaultHasher::new(); + std::time::SystemTime::now().hash(&mut h); + std::thread::current().id().hash(&mut h); + target.hash(&mut h); + target.with_file_name(format!( + ".{name}{PART}{}-{:016x}", + std::process::id(), + h.finish() + )) +} + +const PART: &str = ".part-"; + +/// Temporary files of copies whose process is gone (a crash, a power cut), in `dirs`: +/// removed. Only names this program gives (`..pgn.part--`) and only when +/// no process `` runs; anything else is left alone. +pub fn clean_orphans(dirs: &[PathBuf]) { + for dir in dirs { + let Ok(entries) = std::fs::read_dir(dir) else { + continue; + }; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if let Some(pid) = orphan_pid(&name) + && pid != std::process::id() + && !Path::new(&format!("/proc/{pid}")).exists() + && entry.file_type().is_ok_and(|t| t.is_file()) + { + let _ = std::fs::remove_file(entry.path()); + } + } + } +} + +/// The writer's process of a temporary copy file named so, if the name is one. +fn orphan_pid(name: &str) -> Option { + let rest = name.strip_prefix('.')?; + let (stem, tail) = rest.rsplit_once(PART)?; + if !stem.to_lowercase().ends_with(".pgn") { + return None; + } + let (pid, hex) = tail.split_once('-')?; + (hex.len() == 16 && hex.chars().all(|c| c.is_ascii_hexdigit())) + .then(|| pid.parse().ok()) + .flatten() +} + +/// A record's PGN text with every run of white space as one space: what makes two +/// records the same for a copy (the owner's rule: tags, moves, variations, comments and +/// NAG all equal; line breaks and spaces aside). +fn normalized(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// 128 bits of a normalized record text: millions of copied records are told apart +/// without keeping their texts; equal keys are compared again in full. +fn key_of(normalized: &str) -> u128 { + let half = |salt: u64| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + salt.hash(&mut h); + normalized.hash(&mut h); + h.finish() + }; + (u128::from(half(0x9e37_79b9_7f4a_7c15)) << 64) | u128::from(half(0x6a09_e667_f3bc_c909)) +} + +/// Copies the records of `req` from `db` into the new file `req.target`, in the table's +/// order (records of equal value by number). Each record has the bytes «Add to +/// database» would append to it; a record whose text was already copied is skipped, a +/// record that cannot be read too. Written into a temporary file beside the target and published by a hard +/// link, which fails rather than replace a file of that name. `None`: cancelled, nothing +/// is left on disk. +pub fn copy_into_new( + db: &Database, + req: &CopyRequest, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Option> { + let mut order = req.records.clone(); + order.sort_unstable(); + db.sort_records(&mut order, req.sort, req.ascending); + if cancel.load(Ordering::Relaxed) { + return None; + } + let partial = Partial { + path: partial_path(&req.target), + published: false, + }; + let run = || -> Result, CopyError> { + if let Some(dir) = req.target.parent() { + std::fs::create_dir_all(dir)?; + } + if req.target.exists() { + return Err(CopyError::Exists); + } + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&partial.path)?; + let mut out = std::io::BufWriter::new(file); + let mut report = CopyReport::default(); + // Copied records by the key of their text; equal keys of different texts (all + // but impossible) in `more`. + let mut seen: HashMap = HashMap::new(); + let mut more: Vec = Vec::new(); + for (n, &record) in order.iter().enumerate() { + if cancel.load(Ordering::Relaxed) { + return Ok(None); + } + if req.slow { + std::thread::sleep(std::time::Duration::from_millis(100)); + } + let index = record as usize; + let text = db + .load_game(index) + .and_then(|parsed| Some((parsed, record_text(db, index)?))); + match text { + None => report.unreadable.push(index), + Some((_, text)) => { + let flat = normalized(&text); + let key = key_of(&flat); + let same = |other: u32| { + record_text(db, other as usize).is_some_and(|t| normalized(&t) == flat) + }; + let duplicate = match seen.get(&key) { + None => { + seen.insert(key, record); + false + } + Some(&first) => { + let dup = same(first) || more.iter().any(|&o| same(o)); + if !dup { + more.push(record); + } + dup + } + }; + if duplicate { + report.duplicates.push(index); + } else { + out.write_all(&store::record_for_new_file(&text))?; + report.copied += 1; + } + } + } + progress.store(n + 1, Ordering::Relaxed); + } + let file = out.into_inner().map_err(|e| e.into_error())?; + file.sync_all()?; + if let Some(pgn) = db.as_pgn() + && pgn.source_changed().unwrap_or(true) + { + return Err(CopyError::SourceChanged); + } + if cancel.load(Ordering::Relaxed) { + return Ok(None); + } + match std::fs::hard_link(&partial.path, &req.target) { + Ok(()) => Ok(Some(report)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(CopyError::Exists), + Err(e) => Err(e.into()), + } + }; + match run() { + Ok(None) => None, + Ok(Some(report)) => Some(Ok(report)), + Err(e) => Some(Err(e)), + } +} + +/// « (No. 3, 4 and 2 more)» for up to `most` record numbers, nothing for none. +fn numbers(records: &[usize], most: usize) -> String { + if records.is_empty() { + return String::new(); + } + let mut list: Vec = records + .iter() + .take(most) + .map(|i| (i + 1).to_string()) + .collect(); + if records.len() > most { + list.push(trf("and {n} more", &[("n", &(records.len() - most))])); + } + format!(" ({})", trf("No. {list}", &[("list", &list.join(", "))])) +} + +/// «Name: copied 3, skipped 1 — duplicates 1 (No. 9), unreadable 0». +pub fn summary(name: &str, report: &CopyReport) -> String { + if report.skipped() == 0 { + return trf( + "{name}: copied {n}, skipped {m}", + &[("name", &name), ("n", &report.copied), ("m", &0)], + ); + } + trf( + "{name}: copied {n}, skipped {m} — duplicates {d}{dl}, unreadable {u}{ul}", + &[ + ("name", &name), + ("n", &report.copied), + ("m", &report.skipped()), + ("d", &report.duplicates.len()), + ("dl", &numbers(&report.duplicates, 10)), + ("u", &report.unreadable.len()), + ("ul", &numbers(&report.unreadable, 5)), + ], + ) +} + +#[cfg(test)] +#[path = "batch_copy_tests.rs"] +mod tests; diff --git a/apps/desktop/src/batch_copy_tests.rs b/apps/desktop/src/batch_copy_tests.rs new file mode 100644 index 0000000..b956075 --- /dev/null +++ b/apps/desktop/src/batch_copy_tests.rs @@ -0,0 +1,554 @@ +use std::sync::atomic::{AtomicBool, AtomicUsize}; + +use chess_core::PgnDatabase; +use chess_core::pgn::store; + +use super::*; + +struct Dir(PathBuf); + +impl Dir { + fn new(name: &str) -> Dir { + let path = std::env::temp_dir().join(format!("cp-batch-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Dir(path) + } + + fn file(&self, name: &str, bytes: &[u8]) -> PathBuf { + let path = self.0.join(name); + std::fs::write(&path, bytes).unwrap(); + path + } + + /// Files of the folder besides `keep` (a temporary file left behind shows here). + fn others(&self, keep: &[&Path]) -> Vec { + std::fs::read_dir(&self.0) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| !keep.contains(&p.as_path())) + .collect() + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn open(path: &Path) -> Database { + chess_import::open(path, &mut |_| {}, &AtomicBool::new(false)) + .unwrap() + .db +} + +/// Games with what a copy must keep: a start position with fullmove 0, variations three +/// deep, comments at the root and after moves, NAG, arrows, a tag of its own, and the +/// first game once more (a duplicate). +const SOURCE: &str = r#"[Event "Club"] +[Site "?"] +[Date "2020.01.02"] +[Round "1"] +[White "Alpha"] +[Black "Beta"] +[Result "1-0"] +[MyTag "kept"] + +{A comment at the root} 1. e4 $1 {[%cal Ge2e4]} e5 (1... c5 2. Nf3 (2. c3 d5 (2... Nf6 3. e5)) d6) 2. Nf3 $14 Nc6 1-0 + +[Event "Study"] +[Site "?"] +[Date "2021.??.??"] +[Round "?"] +[White "Gamma"] +[Black "Delta"] +[Result "*"] +[SetUp "1"] +[FEN "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0"] + +1. e4 Kd7 {the king} 2. Kf2 * + +[Event "Club"] +[Site "?"] +[Date "2019.05.05"] +[Round "2"] +[White "Beta"] +[Black "Alpha"] +[Result "0-1"] + +1. d4 d5 2. c4 $2 dxc4 0-1 + +[Event "Club again"] +[Site "?"] +[Date "2020.01.02"] +[Round "1"] +[White "alpha"] +[Black "BETA"] +[Result "1-0"] + +1. e4 e5 2. Nf3 Nc6 1-0 + +[Event "Club"] +[Site "?"] +[Date "2020.01.02"] +[Round "1"] +[White "Alpha"] +[Black "Beta"] +[Result "1-0"] +[MyTag "kept"] + +{A comment at the root} 1. e4 $1 {[%cal Ge2e4]} +e5 (1... c5 2. Nf3 (2. c3 d5 (2... Nf6 3. e5)) d6) 2. Nf3 $14 Nc6 1-0 +"#; + +fn request(records: &[u32], target: &Path) -> CopyRequest { + CopyRequest { + records: records.to_vec(), + sort: SortKey::Number, + ascending: true, + target: target.to_path_buf(), + slow: false, + } +} + +fn copy(db: &Database, req: &CopyRequest) -> Option> { + copy_into_new(db, req, &AtomicUsize::new(0), &AtomicBool::new(false)) +} + +/// The new database as «Add to database» would make it: an empty file, then each record +/// appended in turn, a game already there skipped. +fn one_by_one(db: &Database, order: &[usize], target: &Path) { + std::fs::write(target, b"").unwrap(); + let mut written: Vec = Vec::new(); + for &i in order { + let into = PgnDatabase::open(target, &mut |_| {}, &AtomicBool::new(false)).unwrap(); + let text = record_text(db, i).unwrap(); + if !written.contains(&normalized(&text)) { + store::append(&into, &text).unwrap(); + written.push(normalized(&text)); + } + } +} + +#[test] +fn a_selection_keeps_a_bit_per_record() { + let mut s = Selection::default(); + assert!(s.is_empty() && !s.contains(5)); + s.insert(5); + s.insert(5); + s.insert(200); + assert_eq!((s.len(), s.records()), (2, vec![5, 200])); + s.toggle(5); + s.toggle(7); + assert_eq!(s.records(), vec![7, 200]); + s.extend(&[1, 7, 300]); + assert_eq!((s.len(), s.records()), (4, vec![1, 7, 200, 300])); + assert_eq!(s.count_in(&[0, 1, 2, 300]), 2); + s.remove(1000); + s.remove(7); + assert_eq!(s.len(), 3); + assert_eq!(s.last(), Some(300)); + s.retain_below(201); + assert_eq!(s.records(), vec![1, 200]); + s.only(42); + assert_eq!(s.records(), vec![42]); + s.clear(); + assert!(s.is_empty()); +} + +#[test] +fn a_copy_has_the_bytes_of_adding_the_games_one_by_one() { + let dir = Dir::new("same"); + let source = dir.file("source.pgn", SOURCE.as_bytes()); + let before = std::fs::read(&source).unwrap(); + let db = open(&source); + assert_eq!(db.len(), 5); + let target = dir.0.join("copy.pgn"); + let report = copy(&db, &request(&[3, 0, 4, 2, 1], &target)) + .unwrap() + .unwrap(); + // Record 5 is record 1 again with other line breaks: skipped; record 4 is the same + // game with other tags: copied. + assert_eq!( + report, + CopyReport { + copied: 4, + duplicates: vec![4], + unreadable: Vec::new() + } + ); + let expected = dir.0.join("expected.pgn"); + one_by_one(&db, &[0, 1, 2, 3, 4], &expected); + assert_eq!( + std::fs::read(&target).unwrap(), + std::fs::read(&expected).unwrap() + ); + // The source is only read; no temporary file is left. + assert_eq!(std::fs::read(&source).unwrap(), before); + assert!(dir.others(&[&source, &target, &expected]).is_empty()); + // Every game whole: tags, start position, variations, comments, NAG, arrows. + let copied = open(&target); + for (i, j) in [(0, 0), (1, 1), (2, 2)] { + assert_eq!( + copied.load_game(j).unwrap().game.to_pgn(), + db.load_game(i).unwrap().game.to_pgn() + ); + } + let text = std::fs::read_to_string(&target).unwrap(); + for kept in [ + "[MyTag \"kept\"]", + "{A comment at the root}", + "$1", + "[%cal Ge2e4]", + "(2... Nf6 3. e5)", + "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0", + ] { + assert!(text.contains(kept), "{kept}"); + } +} + +/// The owner's example: in Dvoretsky's endgame manual records 719 and 728 are one game +/// with other comments; both are copied (the user's file, read only, when it is there). +#[test] +fn records_with_other_comments_are_both_copied() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Дворецкий. Учебник жндшпилÑ�.pgn"); + if !path.exists() { + return; + } + let db = open(&path); + let dir = Dir::new("dvoretsky"); + let target = dir.0.join("copy.pgn"); + let report = copy(&db, &request(&[718, 727], &target)).unwrap().unwrap(); + assert_eq!((report.copied, report.duplicates.len()), (2, 0)); + // The same record twice in a source: the second is skipped. + let one = record_text(&db, 718).unwrap(); + let source = dir.file("twice.pgn", format!("{one}\n\n{one}\n").as_bytes()); + let twice = open(&source); + let target = dir.0.join("twice-copy.pgn"); + let report = copy(&twice, &request(&[0, 1], &target)).unwrap().unwrap(); + assert_eq!((report.copied, report.duplicates), (1, vec![1])); +} + +#[test] +fn the_summary_names_the_skipped_records() { + let report = CopyReport { + copied: 5, + duplicates: (0..12).collect(), + unreadable: vec![39], + }; + assert_eq!( + summary("Pick", &report), + "Pick: copied 5, skipped 13 — duplicates 12 (No. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 2 more), unreadable 1 (No. 40)" + ); + let clean = CopyReport { + copied: 3, + ..CopyReport::default() + }; + assert_eq!(summary("Pick", &clean), "Pick: copied 3, skipped 0"); +} + +#[test] +fn only_orphans_of_this_program_are_removed() { + let dir = Dir::new("orphans"); + let mine_live = format!(".a.pgn.part-{}-0123456789abcdef", std::process::id()); + // No process has a number that high on Linux (pid_max is at most 4194304). + let dead = ".a.pgn.part-999999999-0123456789abcdef"; + let others = [ + ".a.pgn.part-999999999", + ".a.txt.part-999999999-0123456789abcdef", + "a.pgn.part-999999999-0123456789abcdef", + ".a.pgn.part-999999999-xyz", + ]; + for name in [mine_live.as_str(), dead].iter().chain(others.iter()) { + dir.file(name, b"x"); + } + clean_orphans(std::slice::from_ref(&dir.0)); + assert!(!dir.0.join(dead).exists()); + assert!(dir.0.join(&mine_live).exists()); + for name in others { + assert!(dir.0.join(name).exists(), "{name}"); + } + // Each copy has a name of its own. + let target = dir.0.join("t.pgn"); + assert_ne!(partial_path(&target), partial_path(&target)); + let name = partial_path(&target); + assert!(orphan_pid(&name.file_name().unwrap().to_string_lossy()).is_some()); +} + +#[test] +fn a_copy_follows_the_tables_order() { + let dir = Dir::new("order"); + let source = dir.file("source.pgn", SOURCE.as_bytes()); + let db = open(&source); + let target = dir.0.join("copy.pgn"); + let req = CopyRequest { + sort: SortKey::White, + ascending: false, + ..request(&[0, 1, 2], &target) + }; + copy(&db, &req).unwrap().unwrap(); + let mut table = vec![0, 1, 2]; + db.sort_records(&mut table, SortKey::White, false); + let whites: Vec = (0..3) + .map(|i| { + open(&target) + .load_game(i) + .unwrap() + .game + .tag("White") + .unwrap() + .to_owned() + }) + .collect(); + let wanted: Vec = table + .iter() + .map(|&i| { + db.load_game(i as usize) + .unwrap() + .game + .tag("White") + .unwrap() + .to_owned() + }) + .collect(); + assert_eq!(whites, wanted); + assert_eq!(whites, ["Gamma", "Beta", "Alpha"]); +} + +#[test] +fn a_cancelled_copy_leaves_nothing() { + let dir = Dir::new("cancel"); + let source = dir.file("source.pgn", SOURCE.as_bytes()); + let db = open(&source); + let target = dir.0.join("copy.pgn"); + let cancel = AtomicBool::new(true); + let got = copy_into_new( + &db, + &request(&[0, 1], &target), + &AtomicUsize::new(0), + &cancel, + ); + assert!(got.is_none()); + assert!(!target.exists()); + assert!(dir.others(&[&source]).is_empty()); + + // Cancelled while writing (another thread, a slow copy). + let cancel = std::sync::Arc::new(AtomicBool::new(false)); + let progress = std::sync::Arc::new(AtomicUsize::new(0)); + let (c, p) = (cancel.clone(), progress.clone()); + let req = CopyRequest { + slow: true, + ..request(&[0, 1, 2, 3], &target) + }; + let worker = std::thread::spawn(move || copy_into_new(&db, &req, &p, &c)); + while progress.load(std::sync::atomic::Ordering::Relaxed) == 0 { + std::thread::yield_now(); + } + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + assert!(worker.join().unwrap().is_none()); + assert!(!target.exists()); + assert!(dir.others(&[&source]).is_empty()); +} + +#[test] +fn a_copy_never_replaces_a_file() { + let dir = Dir::new("exists"); + let source = dir.file("source.pgn", SOURCE.as_bytes()); + let db = open(&source); + let target = dir.file("copy.pgn", b"mine"); + let got = copy(&db, &request(&[0], &target)).unwrap(); + assert!(matches!(got, Err(CopyError::Exists))); + assert_eq!(std::fs::read(&target).unwrap(), b"mine"); + assert!(dir.others(&[&source, &target]).is_empty()); +} + +#[test] +fn a_source_changed_while_copying_writes_nothing() { + let dir = Dir::new("changed"); + let source = dir.file("source.pgn", SOURCE.as_bytes()); + let db = open(&source); + std::fs::write(&source, format!("{SOURCE}\n[White \"x\"]\n\n1. e4 *\n")).unwrap(); + let target = dir.0.join("copy.pgn"); + let got = copy(&db, &request(&[0], &target)).unwrap(); + assert!(matches!(got, Err(CopyError::SourceChanged))); + assert!(!target.exists()); + assert!(dir.others(&[&source]).is_empty()); +} + +#[test] +fn a_legacy_source_is_copied_as_its_text_reads() { + let dir = Dir::new("legacy"); + // windows-1252: «é», «ü» and «—» are one byte each. + let mut bytes = b"[Event \"Caf\xe9\"]\n[White \"M\xfcller\"]\n[Black \"Ren\xe9\"]\n[Result \"1-0\"]\n\n{Le d\xe9but \x97 bien} 1. e4 e5 1-0\n".to_vec(); + bytes.extend_from_slice(b"\n[White \"B\"]\n[Black \"C\"]\n[Result \"*\"]\n\n1. d4 *\n"); + let source = dir.file("legacy.pgn", &bytes); + let db = open(&source); + let target = dir.0.join("copy.pgn"); + copy(&db, &request(&[0, 1], &target)).unwrap().unwrap(); + let expected = dir.0.join("expected.pgn"); + one_by_one(&db, &[0, 1], &expected); + assert_eq!( + std::fs::read(&target).unwrap(), + std::fs::read(&expected).unwrap() + ); + let copied = open(&target); + let (a, b) = ( + db.load_game(0).unwrap().game, + copied.load_game(0).unwrap().game, + ); + assert_eq!(a.tag("White"), b.tag("White")); + assert_eq!(a.to_pgn(), b.to_pgn()); + assert!(String::from_utf8(std::fs::read(&target).unwrap()).is_ok()); + assert_eq!(std::fs::read(&source).unwrap(), bytes); +} + +/// windows-1251 bytes of `text` (ASCII and the Russian letters without «ё»). +fn cp1251(text: &str) -> Vec { + text.chars() + .map(|c| match c { + 'Ð�'..='Ñ�' => (c as u32 - 'Ð�' as u32 + 0xC0) as u8, + c => c as u8, + }) + .collect() +} + +#[test] +fn a_source_with_restored_letters_is_copied_as_adding_one_game() { + let dir = Dir::new("repair"); + // `~~`, `o^` and `><` stand for ч, ÑŽ and Ч in old Russian files; restored on reading + // (a copy has the restored text, as a game added alone; tasks.md, task 42, Д1). + let comment = "{Клo^~~евые полÑ�, ><ерные играo^Ñ‚, ~~ерные} ".repeat(12); + let text = format!( + "[White \"Петров\"]\n[Black \"Иванов\"]\n[Result \"*\"]\n\n{comment}1. e4 *\n\n[White \"Б\"]\n[Black \"Ð’\"]\n[Result \"*\"]\n\n{{~~ерные}} 1. d4 *\n" + ); + let bytes = cp1251(&text); + let source = dir.file("repair.pgn", &bytes); + let db = open(&source); + assert!(db.as_pgn().is_some_and(|p| p.repair_letters_enabled())); + let target = dir.0.join("copy.pgn"); + copy(&db, &request(&[0, 1], &target)).unwrap().unwrap(); + let expected = dir.0.join("expected.pgn"); + one_by_one(&db, &[0, 1], &expected); + assert_eq!( + std::fs::read(&target).unwrap(), + std::fs::read(&expected).unwrap() + ); + assert!(std::fs::read_to_string(&target).unwrap().contains("ерные")); + assert_eq!(std::fs::read(&source).unwrap(), bytes); +} + +/// Copying 1000 games and choosing 4 million rows: timed (`cargo test -- --ignored +/// --nocapture`, release for figures). +#[test] +#[ignore] +fn timing() { + let dir = Dir::new("timing"); + let mut text = String::new(); + for i in 0..1000 { + text.push_str(&format!( + "[Event \"E\"]\n[White \"W{i}\"]\n[Black \"B{i}\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 (2. f4 exf4 {{gambit}}) Nc6 3. Bb5 $1 a6 4. Ba4 Nf6 5. O-O Be7 *\n\n" + )); + } + let source = dir.file("source.pgn", text.as_bytes()); + let db = open(&source); + let target = dir.0.join("copy.pgn"); + let records: Vec = (0..1000).collect(); + let t = std::time::Instant::now(); + let report = copy(&db, &request(&records, &target)).unwrap().unwrap(); + println!( + "copy 1000 games: {:?} ({} copied)", + t.elapsed(), + report.copied + ); + let view: Vec = (0..4_000_000).collect(); + let t = std::time::Instant::now(); + let mut s = Selection::default(); + s.extend(&view); + println!("select all of 4 000 000: {:?}", t.elapsed()); + let t = std::time::Instant::now(); + let n = s.count_in(&view); + println!("count chosen in 4 000 000: {:?} ({n})", t.elapsed()); +} + +fn rss_anon_kb() -> u64 { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|s| { + s.lines() + .find(|l| l.starts_with("RssAnon:")) + .and_then(|l| l.split_whitespace().nth(1)?.parse().ok()) + }) + .unwrap_or(0) +} + +/// The memory a copy takes beyond the open database: the peak of `RssAnon` while it runs +/// less the value before. `CP_PROBE_DB=` and `CP_PROBE_N=` (release: +/// `cargo test --release -- --ignored --nocapture copy_memory`); without them, synthetic +/// PGN of 1 000 000 games in a temporary folder. +#[test] +#[ignore] +fn copy_memory() { + let dir = Dir::new("memory"); + let (db, n) = match std::env::var("CP_PROBE_DB") { + Ok(path) => { + let n = std::env::var("CP_PROBE_N") + .ok() + .and_then(|n| n.parse().ok()) + .unwrap_or(200_000); + (open(Path::new(&path)), n) + } + Err(_) => { + let n: usize = std::env::var("CP_PROBE_N") + .ok() + .and_then(|n| n.parse().ok()) + .unwrap_or(1_000_000); + let path = dir.0.join("big.pgn"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&path).unwrap()); + for i in 0..n { + write!( + out, + "[White \"W{i}\"]\n[Black \"B{}\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O *\n\n", + i % 977 + ) + .unwrap(); + } + drop(out); + (open(&path), n) + } + }; + let records: Vec = (0..n.min(db.len()) as u32).collect(); + // The database's own index for sorting is built once, by the table: not the copy's. + db.sort_records(&mut records.clone(), SortKey::Number, true); + let before = rss_anon_kb(); + let done = std::sync::Arc::new(AtomicBool::new(false)); + let peak = { + let done = done.clone(); + std::thread::spawn(move || { + let mut peak = 0; + while !done.load(std::sync::atomic::Ordering::Relaxed) { + peak = peak.max(rss_anon_kb()); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + peak + }) + }; + let target = dir.0.join("copy.pgn"); + let t = std::time::Instant::now(); + let report = copy(&db, &request(&records, &target)).unwrap().unwrap(); + let took = t.elapsed(); + done.store(true, std::sync::atomic::Ordering::Relaxed); + let peak = peak.join().unwrap(); + println!( + "records {}: copied {}, duplicates {}, {:?}; RssAnon before {} KB, peak {} KB, +{} KB ({:.0} B per record)", + records.len(), + report.copied, + report.duplicates.len(), + took, + before, + peak, + peak.saturating_sub(before), + peak.saturating_sub(before) as f64 * 1024.0 / records.len().max(1) as f64 + ); +} diff --git a/apps/desktop/src/board.rs b/apps/desktop/src/board.rs new file mode 100644 index 0000000..3081f3a --- /dev/null +++ b/apps/desktop/src/board.rs @@ -0,0 +1,1265 @@ +//! Chessboard widget: drawing, click/drag move input, promotion picker, arrows. + +use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Shape, Stroke, Vec2, vec2}; +use shakmaty::{Board, Chess, Color, File, Move, Piece, Position, Rank, Role, Square}; + +use crate::assets::{BoardTheme, PieceSet}; + +#[derive(Clone, Copy, Debug)] +pub struct Arrow { + pub from: Square, + pub to: Square, + pub color: Color32, + /// Relative thickness, 1.0 = default. + pub weight: f32, +} + +/// A round label in the top right corner of a square, as on Lichess. +#[derive(Clone, Copy, Debug)] +pub struct Badge { + pub square: Square, + pub text: &'static str, + pub color: Color32, +} + +/// Interaction state that lives across frames (per board instance). +/// A shape the user drew with the right mouse button (docs/design/user-comments.md +/// §10): an arrow, or a circle on one square. The colour is the modifier held when the +/// button was released: none green, Shift red, Alt blue, Shift+Alt yellow (Lichess). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Drawn { + Arrow(chess_core::ShapeColor, Square, Square), + Circle(chess_core::ShapeColor, Square), +} + +#[cfg(test)] +pub(crate) type TestAnimation<'a> = (f64, &'a [(Piece, Square, Square)], f32); + +#[derive(Default)] +pub struct BoardState { + selected: Option, + drag: Option, + promotion: Option<(Square, Square)>, + /// The square the right button went down on: a shape is being drawn. + shape_from: Option, + /// A shape drawn this frame, for the game to take (`take_shape`). + shape: Option, + /// Temporary shapes in play and training; never written to the PGN. + temporary_shapes: Vec, + temporary_position: Option, + /// The position drawn last: a different one next frame is animated from it. + shown: Option, + anim: Option, + /// A move was dropped by dragging the piece from this square: that piece is + /// already in place (a castling rook or a captured pawn still move). + dropped: Option, + /// A premove set while the opponent thinks (from, to): played at once after their + /// move if it is legal then (Lichess). + premove: Option<(Square, Square)>, +} + +impl BoardState { + /// Forgets the selection, the drag and the promotion choice. + pub fn clear(&mut self) { + self.selected = None; + self.drag = None; + self.promotion = None; + } + + /// The opponent has moved: a piece of `own` in the hand (selected or dragged) stays + /// there, as on Lichess; one that was captured, and a promotion choice, are dropped. + pub fn opponent_moved(&mut self, board: &Board, own: Color) { + let mine = |sq: Square| board.piece_at(sq).is_some_and(|p| p.color == own); + self.selected = self.selected.filter(|&s| mine(s)); + self.drag = self.drag.filter(|&s| mine(s)); + self.promotion = None; + } + + /// The premove set, taken (it is played or dropped after the opponent's move). + pub fn take_premove(&mut self) -> Option<(Square, Square)> { + self.premove.take() + } + + /// Sets a premove (dev hook `CP_PREMOVE`). + pub fn set_premove(&mut self, from: Square, to: Square) { + self.premove = Some((from, to)); + } + + /// Drops the premove (a take-back, the end of the game). + pub fn clear_premove(&mut self) { + self.premove = None; + } + + /// The shape the user has just drawn, once. + pub fn take_shape(&mut self) -> Option { + self.shape.take() + } + + pub fn draw_temporary(&mut self, drawn: Drawn, pos: &Chess) { + self.shape = None; + self.sync_temporary_position(pos); + let same = |shape: &Drawn| match (*shape, drawn) { + (Drawn::Arrow(_, af, at), Drawn::Arrow(_, bf, bt)) => af == bf && at == bt, + (Drawn::Circle(_, a), Drawn::Circle(_, b)) => a == b, + _ => false, + }; + if let Some(index) = self.temporary_shapes.iter().position(same) { + if self.temporary_shapes[index] == drawn { + self.temporary_shapes.remove(index); + } else { + self.temporary_shapes[index] = drawn; + } + } else { + self.temporary_shapes.push(drawn); + } + } + + fn sync_temporary_position(&mut self, pos: &Chess) { + if self.temporary_position.as_ref() != Some(pos) { + self.temporary_shapes.clear(); + self.temporary_position = Some(pos.clone()); + } + } + + /// A piece is selected or dragged, or a promotion is being chosen. + pub fn is_busy(&self) -> bool { + self.selected.is_some() || self.drag.is_some() || self.promotion.is_some() + } + + #[cfg(test)] + pub(crate) fn animation_at(&self, now: f64) -> Option> { + let anim = self.anim.as_ref()?; + Some((anim.duration, &anim.slides, anim.rest(now)?)) + } +} + +/// Pieces moving from one position to the next, as on Lichess (chessground): each piece +/// of the new position that was not there slides from the nearest square that held the +/// same piece; a piece left without a new square fades out. +struct Anim { + start: f64, + duration: f64, + slides: Vec<(Piece, Square, Square)>, + fadings: Vec<(Piece, Square)>, +} + +impl Anim { + fn new(prev: &Board, cur: &Board, start: f64, duration: f64) -> Anim { + let mut missing: Vec<(Piece, Square)> = Vec::new(); + let mut new: Vec<(Piece, Square)> = Vec::new(); + for sq in Square::ALL { + match (prev.piece_at(sq), cur.piece_at(sq)) { + (Some(a), Some(b)) if a == b => {} + (a, b) => { + missing.extend(a.map(|p| (p, sq))); + new.extend(b.map(|p| (p, sq))); + } + } + } + let mut slides = Vec::new(); + for (piece, to) in new { + let nearest = missing + .iter() + .enumerate() + .filter(|(_, (p, _))| *p == piece) + .min_by_key(|(_, (_, from))| { + let df = i32::from(from.file()) - i32::from(to.file()); + let dr = i32::from(from.rank()) - i32::from(to.rank()); + df * df + dr * dr + }) + .map(|(i, _)| i); + if let Some(i) = nearest { + let (_, from) = missing.swap_remove(i); + slides.push((piece, from, to)); + } + } + Anim { + start, + duration, + slides, + fadings: missing, + } + } + + /// How much of the way is left: 1 at the start, 0 at the end (eased like chessground). + fn rest(&self, now: f64) -> Option { + let t = 1.0 - (now - self.start) / self.duration; + (t > 0.0).then(|| { + let t = t as f32; + if t < 0.5 { + 4.0 * t * t * t + } else { + (t - 1.0) * (2.0 * t - 2.0) * (2.0 * t - 2.0) + 1.0 + } + }) + } +} + +pub struct BoardView<'a> { + pub pos: &'a Chess, + pub orientation: Color, + pub last_move: Option<(Square, Square)>, + pub arrows: &'a [Arrow], + /// Circled squares (from `[%csl]` comment annotations). + pub circles: &'a [(Square, Color32)], + /// Move assessment shown on the destination square of the last move ("??" in red, …). + pub badge: Option, + pub interactive: bool, + /// Right-button shapes stay until the position changes instead of becoming PGN comments. + pub temporary_shapes: bool, + pub show_coords: bool, + pub theme: BoardTheme, + pub pieces: PieceSet, + /// Seconds a move takes to slide (0: no animation). + pub animation: f32, + /// Not this side's turn, but it may set a premove (a game against the computer). + pub premove: Option, + /// A pawn reaching the last rank becomes a queen without asking. + pub auto_queen: bool, + /// The squares of a wrong move, in red (learning an opening). + pub alert: Option<(Square, Square)>, +} + +impl BoardView<'_> { + /// Draws the board into the available square area. Returns a move the user made, if any. + pub fn show(self, ui: &mut egui::Ui, state: &mut BoardState) -> Option { + let avail = ui.available_size(); + // A board to play on stays usable; one only shown may be a thumbnail. + let least = if self.interactive || self.premove.is_some() { + 64.0 + } else { + 16.0 + }; + let side = avail.x.min(avail.y).max(least).floor(); + let (rect, response) = ui.allocate_exact_size(Vec2::splat(side), Sense::click_and_drag()); + let sq_size = side / 8.0; + let geo = Geometry { + rect, + sq: sq_size, + flipped: self.orientation == Color::Black, + }; + let painter = ui.painter_at(rect); + let legal = self.pos.legal_moves(); + let mut result = None; + // A premove is set instead of a move: the board takes input for that side. + let premoving = !self.interactive && self.premove.is_some(); + if !self.interactive && !premoving { + state.selected = None; + state.drag = None; + } + if self.temporary_shapes { + state.sync_temporary_position(self.pos); + } else { + state.temporary_shapes.clear(); + } + + // --- input ----------------------------------------------------------------------- + if (self.interactive || premoving) && state.promotion.is_none() { + let pointer = response.interact_pointer_pos(); + if response.drag_started() { + let origin = ui.input(|i| i.pointer.press_origin()).or(pointer); + if let Some(sq) = origin.and_then(|p| geo.square_at(p)) + && self.own_piece(sq) + { + // The piece is taken from where it stands now, not from mid-flight. + state.anim = None; + state.drag = Some(sq); + state.selected = Some(sq); + } + } + if response.drag_stopped() { + if let Some(from) = state.drag.take() { + let target = ui + .input(|i| i.pointer.latest_pos()) + .and_then(|p| geo.square_at(p)); + if let Some(to) = target.filter(|&t| t != from) { + result = self.try_move(state, &legal, from, to); + state.dropped = result.is_some().then_some(from); + } + } + } else if response.clicked() + && let Some(sq) = pointer.and_then(|p| geo.square_at(p)) + { + match state.selected { + // try_move also covers castling by clicking the own rook, + // and reselects when the target is just another own piece. + Some(from) if from != sq => { + result = self.try_move(state, &legal, from, sq); + } + Some(from) if from == sq => state.selected = None, + _ => { + state.selected = self.own_piece(sq).then_some(sq); + // A click beside the own pieces cancels a premove. + if premoving && state.selected.is_none() { + state.premove = None; + } + } + } + } + // The right button draws: a drag — an arrow, a click — a circle on the square. + // Pressing it also drops a picked-up piece, as before. + if response.drag_started_by(egui::PointerButton::Secondary) { + let origin = ui.input(|i| i.pointer.press_origin()).or(pointer); + state.shape_from = origin.and_then(|p| geo.square_at(p)); + state.selected = None; + state.drag = None; + } + if response.drag_stopped_by(egui::PointerButton::Secondary) { + let to = ui + .input(|i| i.pointer.latest_pos()) + .and_then(|p| geo.square_at(p)); + let color = shape_color_for(ui.input(|i| i.modifiers)); + if let Some(from) = state.shape_from.take() { + let drawn = match to { + Some(to) if to != from => Drawn::Arrow(color, from, to), + _ => Drawn::Circle(color, from), + }; + self.record_shape(state, drawn); + } + } + if response.secondary_clicked() { + state.clear(); + state.premove = None; + if let Some(sq) = pointer.and_then(|p| geo.square_at(p)) { + let color = shape_color_for(ui.input(|i| i.modifiers)); + self.record_shape(state, Drawn::Circle(color, sq)); + } + } + } + + // A released legal drag is already at its destination. Draw that result + // in this frame too, before the caller installs the move in its model. + // Click moves keep the ordinary animation on the following frame. + let dropped_position = result + .as_ref() + .filter(|_| state.dropped.is_some()) + .map(|mv| { + let mut position = self.pos.clone(); + position.play_unchecked(*mv); + position + }); + let painted_position = dropped_position.as_ref().unwrap_or(self.pos); + + // --- animation --------------------------------------------------------------------- + let now = ui.input(|i| i.time); + let board = painted_position.board(); + if state.shown.as_ref() != Some(board) { + state.anim = None; + if let Some(prev) = &state.shown + && self.animation > 0.0 + { + let mut anim = Anim::new(prev, board, now, f64::from(self.animation)); + if let Some(from) = state.dropped { + anim.slides.retain(|s| s.1 != from); + } + state.anim = Some(anim); + } + state.dropped = None; + state.shown = Some(board.clone()); + } + let rest = state.anim.as_ref().and_then(|a| a.rest(now)); + if rest.is_none() { + state.anim = None; + } else { + ui.ctx().request_repaint(); + } + + // --- squares ----------------------------------------------------------------------- + if let Some(uri) = self.theme.texture { + egui::Image::new(uri).paint_at(ui, rect); + } + for sq in Square::ALL + .into_iter() + .filter(|_| self.theme.texture.is_none()) + { + let light = (u32::from(sq.file()) + u32::from(sq.rank())) % 2 == 1; + let fill = if light { + self.theme.light + } else { + self.theme.dark + }; + painter.rect_filled(geo.square_rect(sq), 0.0, fill); + } + let hl = |painter: &egui::Painter, sq: Square, c: Color32| { + painter.rect_filled(geo.square_rect(sq), 0.0, c); + }; + if let Some((from, to)) = self.last_move { + hl(&painter, from, self.theme.last_move); + hl(&painter, to, self.theme.last_move); + } + if let Some((from, to)) = state.premove.filter(|_| premoving) { + hl(&painter, from, PREMOVE); + hl(&painter, to, PREMOVE); + } + if let Some(sel) = state.selected { + hl(&painter, sel, self.theme.selected); + } + if let Some((from, to)) = self.alert { + let red = ui.visuals().error_fg_color.gamma_multiply(0.45); + hl(&painter, from, red); + hl(&painter, to, red); + } + if painted_position.is_check() + && let Some(k) = painted_position.board().king_of(painted_position.turn()) + { + let r = geo.square_rect(k); + painter.circle_filled( + r.center(), + sq_size * 0.48, + Color32::from_rgba_unmultiplied(230, 40, 40, 150), + ); + } + + if self.show_coords { + self.draw_coords(&painter, &geo); + } + + // --- pieces -------------------------------------------------------------------------- + let anim = state.anim.as_ref().zip(rest); + if let Some((a, rest)) = anim { + for &(piece, sq) in &a.fadings { + let r = geo.square_rect(sq).shrink(sq_size * 0.02); + self.pieces + .paint_tinted(ui, piece, r, Color32::WHITE.gamma_multiply(rest)); + } + } + for (sq, piece) in painted_position.board().clone() { + if state.drag == Some(sq) && response.dragged() { + continue; + } + if anim.is_some_and(|(a, _)| a.slides.iter().any(|s| s.2 == sq)) { + continue; + } + self.pieces + .paint(ui, piece, geo.square_rect(sq).shrink(sq_size * 0.02)); + } + // Moving pieces over the others. + if let Some((a, rest)) = anim { + for &(piece, from, to) in &a.slides { + let r = geo.square_rect(to); + let offset = (geo.square_rect(from).center() - r.center()) * rest; + self.pieces + .paint(ui, piece, r.translate(offset).shrink(sq_size * 0.02)); + } + } + + // where the selected piece may premove to + if let Some(sel) = state.selected.filter(|_| premoving) + && let Some(piece) = self.pos.board().piece_at(sel) + { + for to in premove_targets(self.pos.board(), sel, piece) { + let r = geo.square_rect(to); + painter.circle_filled(r.center(), sq_size * 0.15, PREMOVE_DOT); + } + } + // legal targets of the selected piece + if let Some(sel) = state.selected.filter(|_| !premoving) { + for m in legal.iter().filter(|m| m.from() == Some(sel)) { + let to = ui_target(m); + let r = geo.square_rect(to); + if self.pos.board().piece_at(to).is_some() && !m.is_castle() { + painter.circle_stroke( + r.center(), + sq_size * 0.44, + Stroke::new(sq_size * 0.07, self.theme.dot), + ); + } else { + painter.circle_filled(r.center(), sq_size * 0.15, self.theme.dot); + } + } + } + + for (sq, c) in self.circles { + let r = geo.square_rect(*sq); + painter.circle_stroke(r.center(), sq_size * 0.46, Stroke::new(sq_size * 0.07, *c)); + } + for a in self.arrows { + draw_arrow(&painter, &geo, a); + } + for drawn in &state.temporary_shapes { + let color = shape_preview_color(match *drawn { + Drawn::Arrow(color, _, _) | Drawn::Circle(color, _) => color, + }); + match *drawn { + Drawn::Arrow(_, from, to) => draw_arrow( + &painter, + &geo, + &Arrow { + from, + to, + color, + weight: 0.9, + }, + ), + Drawn::Circle(_, square) => { + let r = geo.square_rect(square); + painter.circle_stroke( + r.center(), + sq_size * 0.46, + Stroke::new(sq_size * 0.07, color), + ); + } + } + } + if let Some(from) = state.shape_from + && response.dragged_by(egui::PointerButton::Secondary) + { + let color = shape_color_for(ui.input(|i| i.modifiers)); + let c = shape_preview_color(color); + match ui + .input(|i| i.pointer.latest_pos()) + .and_then(|p| geo.square_at(p)) + { + Some(to) if to != from => draw_arrow( + &painter, + &geo, + &Arrow { + from, + to, + color: c, + weight: 0.9, + }, + ), + _ => { + let r = geo.square_rect(from); + painter.circle_stroke( + r.center(), + sq_size * 0.46, + Stroke::new(sq_size * 0.07, c), + ); + } + } + } + if let Some(b) = self.badge { + let r = geo.square_rect(b.square); + let radius = sq_size * 0.19; + // Over the corner of the square, kept inside the board. + let c = egui::pos2( + (r.right() - radius * 0.35).min(rect.right() - radius - 1.0), + (r.top() + radius * 0.35).max(rect.top() + radius + 1.0), + ); + painter.circle_filled( + c + vec2(0.0, sq_size * 0.015), + radius, + Color32::from_black_alpha(90), + ); + painter.circle( + c, + radius, + b.color, + Stroke::new(sq_size * 0.02, Color32::WHITE), + ); + painter.text( + c, + egui::Align2::CENTER_CENTER, + b.text, + crate::assets::bold(radius * 1.05), + Color32::WHITE, + ); + } + + // dragged piece follows the cursor + if let (Some(from), true) = (state.drag, response.dragged()) + && let (Some(piece), Some(p)) = ( + self.pos.board().piece_at(from), + ui.input(|i| i.pointer.latest_pos()), + ) + { + let r = Rect::from_center_size(p, Vec2::splat(sq_size * 1.1)); + self.pieces.paint(ui, piece, r); + } + + // --- promotion picker --------------------------------------------------------------- + if let Some((from, to)) = state.promotion { + painter.rect_filled(rect, 0.0, Color32::from_black_alpha(140)); + let color = self.pos.turn(); + let roles = [Role::Queen, Role::Knight, Role::Rook, Role::Bishop]; + let top_down = geo.square_rect(to).center().y < rect.center().y; + for (i, role) in roles.iter().enumerate() { + let off = if top_down { i as f32 } else { -(i as f32) }; + let r = geo.square_rect(to).translate(vec2(0.0, off * sq_size)); + let hover = ui.rect_contains_pointer(r); + painter.circle_filled( + r.center(), + sq_size * 0.5, + if hover { + Color32::from_gray(240) + } else { + Color32::from_gray(190) + }, + ); + self.pieces + .paint(ui, Piece { color, role: *role }, r.shrink(sq_size * 0.08)); + if hover && ui.input(|i| i.pointer.primary_clicked()) { + result = legal + .iter() + .find(|m| { + m.from() == Some(from) && m.to() == to && m.promotion() == Some(*role) + }) + .cloned(); + state.clear(); + } + } + if result.is_none() + && ui.input(|i| i.key_pressed(egui::Key::Escape) || i.pointer.secondary_clicked()) + { + state.clear(); + } + } + + if result.is_some() { + state.clear(); + } + result + } + + fn record_shape(&self, state: &mut BoardState, drawn: Drawn) { + if self.temporary_shapes { + state.draw_temporary(drawn, self.pos); + } else { + state.shape = Some(drawn); + } + } + + /// The side that moves on this board now: the side to move, or the premoving one. + fn mover(&self) -> Color { + match self.premove { + Some(c) if !self.interactive => c, + _ => self.pos.turn(), + } + } + + fn own_piece(&self, sq: Square) -> bool { + self.pos + .board() + .piece_at(sq) + .is_some_and(|p| p.color == self.mover()) + } + + fn try_move( + &self, + state: &mut BoardState, + legal: &shakmaty::MoveList, + from: Square, + to: Square, + ) -> Option { + if !self.interactive && self.premove.is_some() { + let piece = self.pos.board().piece_at(from)?; + if premove_targets(self.pos.board(), from, piece).contains(to) { + state.premove = Some((from, to)); + state.selected = None; + } else { + state.selected = self.own_piece(to).then_some(to); + if state.selected.is_none() { + state.premove = None; + } + } + return None; + } + let candidates: Vec<&Move> = legal + .iter() + .filter(|m| m.from() == Some(from) && (ui_target(m) == to || m.to() == to)) + .collect(); + match candidates.as_slice() { + [] => { + state.selected = self.own_piece(to).then_some(to); + None + } + [m] => Some(*(*m)), + _ if self.auto_queen && candidates.iter().all(|m| m.is_promotion()) => candidates + .iter() + .find(|m| m.promotion() == Some(Role::Queen)) + .map(|m| *(*m)), + _ if candidates.iter().all(|m| m.is_promotion()) => { + state.promotion = Some((from, to)); + state.selected = None; + None + } + _ => candidates.first().map(|m| *(*m)), + } + } + + fn draw_coords(&self, painter: &egui::Painter, geo: &Geometry) { + let font = FontId::proportional((geo.sq * 0.17).max(9.0)); + for i in 0..8u32 { + let file = File::new(i); + let rank = Rank::new(i); + let bottom_rank = if geo.flipped { + Rank::Eighth + } else { + Rank::First + }; + let left_file = if geo.flipped { File::H } else { File::A }; + let fsq = Square::from_coords(file, bottom_rank); + let rsq = Square::from_coords(left_file, rank); + let color_for = |sq: Square| { + let light = (u32::from(sq.file()) + u32::from(sq.rank())) % 2 == 1; + if light { + self.theme.dark + } else { + self.theme.light + } + }; + let fr = geo.square_rect(fsq); + painter.text( + fr.right_bottom() + vec2(-geo.sq * 0.06, -geo.sq * 0.02), + Align2::RIGHT_BOTTOM, + file.char(), + font.clone(), + color_for(fsq), + ); + let rr = geo.square_rect(rsq); + painter.text( + rr.left_top() + vec2(geo.sq * 0.05, geo.sq * 0.03), + Align2::LEFT_TOP, + rank.char(), + font.clone(), + color_for(rsq), + ); + } + } +} + +/// The premove highlight (Lichess's dark blue) and its target dots. +const PREMOVE: Color32 = Color32::from_rgba_premultiplied(10, 15, 43, 128); +const PREMOVE_DOT: Color32 = Color32::from_rgba_premultiplied(10, 15, 43, 140); + +/// Where a piece may premove: how it moves on an empty board (the position will have +/// changed), a pawn forward and diagonally, the king at home also to castle with an own +/// rook of `board` on the a- or h-file — on the king's square or the rook's (chessground +/// `premove.ts`). +pub fn premove_targets(board: &Board, from: Square, piece: Piece) -> shakmaty::Bitboard { + use shakmaty::{Bitboard, attacks}; + match piece.role { + Role::Pawn => { + let mut b = attacks::pawn_attacks(piece.color, from); + let step: i32 = if piece.color == Color::White { 8 } else { -8 }; + let home = if piece.color == Color::White { + Rank::Second + } else { + Rank::Seventh + }; + if let Some(one) = from.offset(step) { + b.add(one); + if from.rank() == home + && let Some(two) = from.offset(2 * step) + { + b.add(two); + } + } + b + } + Role::King => { + let mut b = attacks::king_attacks(from); + let back = piece.color.backrank(); + let rook = Piece { + color: piece.color, + role: Role::Rook, + }; + if from == Square::from_coords(File::E, back) { + for (rook_file, king_file) in [(File::H, File::G), (File::A, File::C)] { + let r = Square::from_coords(rook_file, back); + if board.piece_at(r) == Some(rook) { + b.add(Square::from_coords(king_file, back)); + b.add(r); + } + } + } + b + } + _ => attacks::attacks(from, piece, Bitboard::EMPTY), + } +} + +/// The move a premove means in `pos`, if it is legal there (a pawn promotes to a queen). +pub fn premove_move(pos: &Chess, from: Square, to: Square) -> Option { + let legal = pos.legal_moves(); + let mut found = legal + .iter() + .filter(|m| m.from() == Some(from) && (ui_target(m) == to || m.to() == to)); + let first = *found.next()?; + if first.is_promotion() { + return legal + .iter() + .find(|m| m.from() == Some(from) && m.to() == to && m.promotion() == Some(Role::Queen)) + .copied(); + } + Some(first) +} + +/// Square the user clicks to make a move: for castling, the king's destination. +pub fn ui_target(m: &Move) -> Square { + match (m, m.castling_side()) { + (Move::Castle { king, .. }, Some(side)) => side.king_to(if king.rank() == Rank::First { + Color::White + } else { + Color::Black + }), + _ => m.to(), + } +} + +struct Geometry { + rect: Rect, + sq: f32, + flipped: bool, +} + +impl Geometry { + fn square_rect(&self, sq: Square) -> Rect { + let (f, r) = (u32::from(sq.file()) as f32, u32::from(sq.rank()) as f32); + let (x, y) = if self.flipped { + (7.0 - f, r) + } else { + (f, 7.0 - r) + }; + Rect::from_min_size( + self.rect.min + vec2(x * self.sq, y * self.sq), + Vec2::splat(self.sq), + ) + } + + fn center(&self, sq: Square) -> Pos2 { + self.square_rect(sq).center() + } + + fn square_at(&self, p: Pos2) -> Option { + if !self.rect.contains(p) { + return None; + } + let x = ((p.x - self.rect.min.x) / self.sq).floor().clamp(0.0, 7.0) as u32; + let y = ((p.y - self.rect.min.y) / self.sq).floor().clamp(0.0, 7.0) as u32; + let (f, r) = if self.flipped { (7 - x, y) } else { (x, 7 - y) }; + Some(Square::from_coords(File::new(f), Rank::new(r))) + } +} + +/// The colour of a shape from the modifiers held (as on Lichess). +fn shape_color_for(m: egui::Modifiers) -> chess_core::ShapeColor { + match (m.shift, m.alt) { + (false, false) => chess_core::ShapeColor::Green, + (true, false) => chess_core::ShapeColor::Red, + (false, true) => chess_core::ShapeColor::Blue, + (true, true) => chess_core::ShapeColor::Yellow, + } +} + +/// How a shape being drawn looks (the game draws the finished ones). +pub fn shape_preview_color(c: chess_core::ShapeColor) -> Color32 { + match c { + chess_core::ShapeColor::Red => Color32::from_rgba_unmultiplied(136, 32, 32, 170), + chess_core::ShapeColor::Green => Color32::from_rgba_unmultiplied(21, 120, 27, 170), + chess_core::ShapeColor::Blue => Color32::from_rgba_unmultiplied(0, 48, 136, 170), + chess_core::ShapeColor::Yellow => Color32::from_rgba_unmultiplied(230, 143, 0, 170), + chess_core::ShapeColor::Other(_) => Color32::from_rgba_unmultiplied(120, 120, 120, 170), + } +} + +fn draw_arrow(painter: &egui::Painter, geo: &Geometry, a: &Arrow) { + let from = geo.center(a.from); + let to = geo.center(a.to); + let dir = (to - from).normalized(); + if !dir.x.is_finite() { + return; + } + let width = geo.sq * 0.16 * a.weight; + let head_len = geo.sq * 0.42 * a.weight.sqrt(); + let head_w = geo.sq * 0.38 * a.weight.sqrt(); + let tip = to - dir * geo.sq * 0.12; + let base = tip - dir * head_len; + let start = from + dir * geo.sq * 0.2; + let normal = vec2(-dir.y, dir.x); + painter.line_segment([start, base], Stroke::new(width, a.color)); + painter.add(Shape::convex_polygon( + vec![tip, base + normal * head_w, base - normal * head_w], + a.color, + Stroke::NONE, + )); +} + +#[cfg(test)] +mod tests { + #[test] + fn premoves_as_on_lichess() { + use shakmaty::fen::Fen; + let sq = |s: &str| s.parse::().unwrap(); + let wp = Piece { + color: Color::White, + role: Role::Pawn, + }; + // A pawn: forward one or two from home, both diagonals. + let start = Board::default(); + let t = premove_targets(&start, sq("e2"), wp); + for s in ["e3", "e4", "d3", "f3"] { + assert!(t.contains(sq(s)), "{s}"); + } + assert_eq!(t.count(), 4); + // A rook through pieces: the position will change. + let wr = Piece { + color: Color::White, + role: Role::Rook, + }; + assert_eq!(premove_targets(&start, sq("a1"), wr).count(), 14); + // The king at home: also its castling squares. + let wk = Piece { + color: Color::White, + role: Role::King, + }; + // The king at home: castling by its square or the rook's, only with the rook. + let k = premove_targets(&start, sq("e1"), wk); + assert!(k.contains(sq("g1")) && k.contains(sq("h1")) && k.contains(sq("c1"))); + let no_h_rook: Board = "4k3/8/8/8/8/8/8/R3K3".parse().unwrap(); + let k = premove_targets(&no_h_rook, sq("e1"), wk); + assert!(!k.contains(sq("g1")) && k.contains(sq("c1")) && k.contains(sq("a1"))); + // Played when legal; a promotion becomes a queen; castling by the king's square. + let pos: Chess = "4k3/1P6/8/8/8/8/8/4K2R w K - 0 1" + .parse::() + .unwrap() + .into_position(shakmaty::CastlingMode::Standard) + .unwrap(); + let m = premove_move(&pos, sq("b7"), sq("b8")).unwrap(); + assert_eq!(m.promotion(), Some(Role::Queen)); + assert!(premove_move(&pos, sq("e1"), sq("g1")).unwrap().is_castle()); + assert!(premove_move(&pos, sq("e1"), sq("h1")).unwrap().is_castle()); + assert!(premove_move(&pos, sq("h1"), sq("h8")).is_some()); + assert!(premove_move(&pos, sq("b7"), sq("c8")).is_none()); + } + + use super::*; + use shakmaty::fen::Fen; + use shakmaty::san::San; + use shakmaty::{CastlingMode, Chess}; + + fn after(fen: &str, moves: &str) -> (Board, Board) { + let pos: Chess = fen + .parse::() + .unwrap() + .into_position(CastlingMode::Standard) + .unwrap(); + let mut next = pos.clone(); + for san in moves.split_whitespace() { + let m = san.parse::().unwrap().to_move(&next).unwrap(); + next.play_unchecked(m); + } + (pos.board().clone(), next.board().clone()) + } + + fn plan(fen: &str, moves: &str) -> (Vec, Vec) { + let (a, b) = after(fen, moves); + let anim = Anim::new(&a, &b, 0.0, 0.25); + let mut slides: Vec = anim + .slides + .iter() + .map(|(p, f, t)| format!("{}{f}{t}", p.char())) + .collect(); + let mut fadings: Vec = anim + .fadings + .iter() + .map(|(p, s)| format!("{}{s}", p.char())) + .collect(); + slides.sort(); + fadings.sort(); + (slides, fadings) + } + + const START: &str = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; + + #[test] + fn a_move_slides_one_piece() { + assert_eq!(plan(START, "e4"), (vec!["Pe2e4".into()], vec![])); + } + + #[test] + fn a_captured_piece_fades() { + let fen = "rnbqkbnr/ppp1pppp/8/3p4/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2"; + assert_eq!( + plan(fen, "exd5"), + (vec!["Pe4d5".into()], vec!["pd5".into()]) + ); + } + + #[test] + fn castling_slides_king_and_rook() { + let fen = "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1"; + assert_eq!( + plan(fen, "O-O"), + (vec!["Ke1g1".into(), "Rh1f1".into()], vec![]) + ); + } + + #[test] + fn a_promoted_pawn_fades_and_the_queen_appears() { + let fen = "8/4P3/8/8/8/8/k7/4K3 w - - 0 1"; + assert_eq!(plan(fen, "e8=Q"), (vec![], vec!["Pe7".into()])); + } + + #[test] + fn en_passant_fades_the_pawn_beside() { + let fen = "4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 2"; + assert_eq!( + plan(fen, "exd6"), + (vec!["Pe5d6".into()], vec!["pd5".into()]) + ); + } + + #[test] + fn a_jump_over_several_moves_slides_each_piece_once() { + let (slides, fadings) = plan(START, "e4 e5 Nf3 Nc6"); + assert_eq!( + slides, + vec!["Ng1f3", "Pe2e4", "nb8c6", "pe7e5"] + .into_iter() + .map(String::from) + .collect::>() + ); + assert!(fadings.is_empty()); + } + + fn board_frame( + ctx: &egui::Context, + state: &mut BoardState, + pos: &Chess, + time: f64, + events: Vec, + temporary_shapes: bool, + ) { + let mut view = Some(BoardView { + pos, + orientation: Color::White, + last_move: None, + arrows: &[], + circles: &[], + badge: None, + interactive: true, + temporary_shapes, + show_coords: false, + theme: crate::assets::BoardThemeId::Brown.theme(), + pieces: PieceSet::Cburnett, + animation: 0.0, + premove: None, + auto_queen: false, + alert: None, + }); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(400.0, 400.0), + )), + time: Some(time), + events, + ..Default::default() + }, + |ui| { + view.take().unwrap().show(ui, state); + }, + ) + .drop_without_applying_deltas(); + } + + fn right_click(at: egui::Pos2, modifiers: egui::Modifiers) -> Vec { + vec![ + egui::Event::ModifiersChanged(modifiers), + egui::Event::PointerMoved(at), + egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Secondary, + pressed: true, + modifiers, + }, + egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Secondary, + pressed: false, + modifiers, + }, + ] + } + + #[test] + fn temporary_shapes_accept_mouse_input_toggle_and_clear() { + let ctx = egui::Context::default(); + let pos = Chess::default(); + let mut state = BoardState::default(); + let sq = |s: &str| s.parse::().unwrap(); + let from = egui::pos2(225.0, 325.0); + let to = egui::pos2(225.0, 225.0); + board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), true); + board_frame( + &ctx, + &mut state, + &pos, + 0.1, + vec![ + egui::Event::PointerMoved(from), + egui::Event::PointerButton { + pos: from, + button: egui::PointerButton::Secondary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ], + true, + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.2, + vec![egui::Event::PointerMoved(to)], + true, + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.3, + vec![egui::Event::PointerButton { + pos: to, + button: egui::PointerButton::Secondary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }], + true, + ); + assert_eq!( + state.temporary_shapes, + vec![Drawn::Arrow( + chess_core::ShapeColor::Green, + sq("e2"), + sq("e4") + )] + ); + assert!(state.shape.is_none()); + + let d5 = egui::pos2(175.0, 175.0); + board_frame( + &ctx, + &mut state, + &pos, + 0.4, + right_click(d5, egui::Modifiers::NONE), + true, + ); + assert_eq!(state.temporary_shapes.len(), 2); + board_frame( + &ctx, + &mut state, + &pos, + 0.5, + right_click(d5, egui::Modifiers::SHIFT), + true, + ); + assert_eq!( + state.temporary_shapes[1], + Drawn::Circle(chess_core::ShapeColor::Red, sq("d5")) + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.6, + right_click(d5, egui::Modifiers::SHIFT), + true, + ); + assert_eq!(state.temporary_shapes.len(), 1); + + let mut next = pos.clone(); + next.play_unchecked("e4".parse::().unwrap().to_move(&pos).unwrap()); + board_frame(&ctx, &mut state, &next, 0.7, Vec::new(), true); + assert!(state.temporary_shapes.is_empty()); + } + + /// A right-button drag in the analysis of a game: one arrow, handed over once, in + /// the colour of the modifiers held as the button is let go. + #[test] + fn analysis_arrow_is_drawn_by_a_right_drag() { + let ctx = egui::Context::default(); + let pos = Chess::default(); + let mut state = BoardState::default(); + let from = egui::pos2(225.0, 325.0); + let to = egui::pos2(225.0, 225.0); + let shift_alt = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), false); + board_frame( + &ctx, + &mut state, + &pos, + 0.1, + vec![ + egui::Event::PointerMoved(from), + egui::Event::PointerButton { + pos: from, + button: egui::PointerButton::Secondary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ], + false, + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.2, + vec![egui::Event::PointerMoved(to)], + false, + ); + assert!( + state.take_shape().is_none(), + "nothing before the button is let go" + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.3, + vec![ + egui::Event::ModifiersChanged(shift_alt), + egui::Event::PointerButton { + pos: to, + button: egui::PointerButton::Secondary, + pressed: false, + modifiers: shift_alt, + }, + ], + false, + ); + assert!(state.temporary_shapes.is_empty()); + assert_eq!( + state.take_shape(), + Some(Drawn::Arrow( + chess_core::ShapeColor::Yellow, + "e2".parse().unwrap(), + "e4".parse().unwrap() + )) + ); + assert!(state.take_shape().is_none()); + } + + #[test] + fn analysis_shapes_remain_one_shot_events() { + let ctx = egui::Context::default(); + let pos = Chess::default(); + let mut state = BoardState::default(); + let at = egui::pos2(175.0, 175.0); + board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), false); + board_frame( + &ctx, + &mut state, + &pos, + 0.1, + right_click(at, egui::Modifiers::NONE), + false, + ); + assert!(state.temporary_shapes.is_empty()); + assert_eq!( + state.take_shape(), + Some(Drawn::Circle( + chess_core::ShapeColor::Green, + "d5".parse().unwrap() + )) + ); + assert!(state.take_shape().is_none()); + } +} diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs new file mode 100644 index 0000000..73d050e --- /dev/null +++ b/apps/desktop/src/board_search.rs @@ -0,0 +1,972 @@ +//! The search board of the library: the user plays moves and the game list shows the +//! games that reach the position, with the moves played next and their results. +//! Layout and behaviour: `docs/design/board-search.md` (decision 13). + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, channel}; + +use chess_import::position::{MoveStat, PositionOutcome, PositionQuery, Tally}; +use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; +use shakmaty::fen::Fen; +use shakmaty::san::SanPlus; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, EnPassantMode, Move, Position}; + +use crate::assets::Sound; +use crate::board::{self, Arrow, BoardState, BoardView}; +use crate::i18n::{tr, trf}; +use crate::settings::Settings; + +/// Seconds the "Undo" of a reset stays offered. +const UNDO_SECONDS: f64 = 8.0; +/// Continuations next to the board from this panel width; below it, under the board. +const WIDE: f32 = 820.0; +const CONTINUATIONS_WIDTH: f32 = 360.0; +/// Arrow of a previewed move (continuation or a game's next move): blue, unlike the +/// engine's green arrows. +pub const PREVIEW_ARROW: Color32 = Color32::from_rgba_premultiplied(40, 110, 200, 190); + +/// What the board asks of its owner. +pub enum BoardEvent { + /// The position changed: search again. + Changed, + Sound(Sound), + CopyText(String, &'static str), + /// Open the moves as a new game (PGN text). + OpenAsGame(String), +} + +/// The board a reset replaced, and when. +struct Replaced { + start: Chess, + start_fen: Option, + line: Vec, + cursor: usize, + at: f64, +} + +/// The search board: a start position, the moves played from it and the move shown. +pub struct SearchBoard { + start: Chess, + /// FEN of a start that is not the usual one (a position taken from a game). + start_fen: Option, + line: Vec, + /// Moves of `line` played on the board (the rest is kept until a new move). + cursor: usize, + pub flipped: bool, + board: BoardState, + /// What a reset replaced (for "Undo"). + undo: Option, + /// Continuation under the pointer (its arrow is drawn). + hover: Option, + /// The first search of the database also prepares its position table (a PGN's, + /// once per session): the waiting line says so. + pub preparing: bool, + /// The position cannot be searched now (no memory for the table): no continuations. + pub unavailable: bool, +} + +impl SearchBoard { + pub fn new() -> SearchBoard { + SearchBoard { + start: Chess::default(), + start_fen: None, + line: Vec::new(), + cursor: 0, + flipped: false, + board: BoardState::default(), + undo: None, + hover: None, + preparing: false, + unavailable: false, + } + } + + /// Dev hook (screenshots, manual checks): `CP_BOARD="e4 c5 Nf3"` opens the search + /// board with these moves. + pub fn from_env() -> Option { + let line = std::env::var("CP_BOARD").ok()?; + let mut pos = Chess::default(); + let mut moves = Vec::new(); + for san in line.split_whitespace() { + let Some(m) = san + .parse::() + .ok() + .and_then(|s| s.to_move(&pos).ok()) + else { + break; + }; + pos.play_unchecked(m); + moves.push(m); + } + let mut board = SearchBoard::new(); + board.set(Chess::default(), moves, false); + Some(board) + } + + /// Sets the board to `line` played from `start` (a position taken from a game). + pub fn set(&mut self, start: Chess, line: Vec, flipped: bool) { + self.start_fen = (start != Chess::default()) + .then(|| Fen::from_position(&start, EnPassantMode::Legal).to_string()); + self.start = start; + self.cursor = line.len(); + self.line = line; + self.flipped = flipped; + self.board.clear(); + self.undo = None; + } + + pub fn position(&self) -> Chess { + let mut pos = self.start.clone(); + for m in &self.line[..self.cursor] { + pos.play_unchecked(*m); + } + pos + } + + /// A position is a search condition once it differs from the usual start. + /// A piece is picked up or dragged, or a promotion is being chosen. + pub fn is_busy(&self) -> bool { + self.board.is_busy() + } + + /// Puts the piece back (Escape). + pub fn drop_pick(&mut self) { + self.board.clear(); + } + + pub fn is_set(&self) -> bool { + self.cursor > 0 || self.start_fen.is_some() + } + + /// The query for the shown position (also for the start, whose continuations are + /// shown without filtering the list). + pub fn query(&self) -> PositionQuery { + let line = self + .start_fen + .is_none() + .then(|| self.line[..self.cursor].to_vec()); + PositionQuery::new(self.position(), line) + } + + /// Identity of the shown position (for caching and comparing requests). + pub fn key(&self) -> u64 { + chess_import::position::key(&self.position()) + } + + /// "1.e4 c5 2.Nf3 d6" (with "ðŸ� " before a start taken from a game). + fn san_line(&self, upto: usize) -> Vec<(String, usize)> { + let mut pos = self.start.clone(); + let mut out = Vec::new(); + for (i, m) in self.line.iter().enumerate() { + let label = move_label(&pos, *m, i == 0); + out.push((label, i + 1)); + pos.play_unchecked(*m); + if i + 1 >= upto { + break; + } + } + out + } + + /// The last move shown, with its number ("14…Nf6"). + fn last_label(&self) -> Option { + let i = self.cursor.checked_sub(1)?; + let mut pos = self.start.clone(); + for m in &self.line[..i] { + pos.play_unchecked(*m); + } + Some(crate::san::show(&move_label(&pos, *self.line.get(i)?, true)).into_owned()) + } + + /// Text of the position chip: the moves up to 8 half-moves, then "after 14…Nf6". + pub fn chip_text(&self) -> String { + let moves = self.san_line(self.cursor); + let prefix = if self.start_fen.is_some() { + "ðŸ�  " + } else { + "" + }; + if moves.len() <= 8 { + let text: Vec = moves + .into_iter() + .map(|(s, _)| crate::san::show(&s).into_owned()) + .collect(); + format!("{prefix}{}", text.join(" ")) + } else { + let last = self.last_label().unwrap_or_default(); + format!("{prefix}{}", trf("after {move}", &[("move", &last)])) + } + } + + /// PGN of the moves, for copying or opening as a new game. + fn pgn(&self) -> String { + let mut out = String::new(); + if let Some(fen) = &self.start_fen { + out.push_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n")); + } + let moves: Vec = self + .san_line(self.cursor) + .into_iter() + .map(|(s, _)| s) + .collect(); + out.push_str(&moves.join(" ")); + out.push_str(" *\n"); + out + } + + fn go(&mut self, cursor: usize) -> bool { + let cursor = cursor.min(self.line.len()); + if cursor == self.cursor { + return false; + } + self.cursor = cursor; + self.board.clear(); + true + } + + /// Plays a move at the cursor: the rest of the line is replaced unless it starts + /// with the same move. + fn play(&mut self, m: Move) { + if self.line.get(self.cursor) != Some(&m) { + self.line.truncate(self.cursor); + self.line.push(m); + } + self.cursor += 1; + self.board.clear(); + } + + fn reset(&mut self, now: f64) { + if !self.is_set() { + return; + } + let old = std::mem::replace(self, SearchBoard::new()); + self.flipped = old.flipped; + self.undo = Some(Replaced { + start: old.start, + start_fen: old.start_fen, + line: old.line, + cursor: old.cursor, + at: now, + }); + } + + fn undo_reset(&mut self) { + if let Some(r) = self.undo.take() { + self.start = r.start; + self.start_fen = r.start_fen; + self.line = r.line; + self.cursor = r.cursor; + self.board.clear(); + } + } + + fn sound_after(&self) -> Sound { + let pos = self.position(); + let capture = self + .cursor + .checked_sub(1) + .and_then(|i| self.line.get(i)) + .is_some_and(|m| m.is_capture()); + if pos.is_checkmate() { + Sound::Checkmate + } else if pos.is_check() { + Sound::Check + } else if capture { + Sound::Capture + } else { + Sound::Move + } + } + + /// Keys of the board (only while no text field has the focus): arrows, Home/End, + /// Backspace, 1-9, F, Ctrl+Backspace. + pub fn keys( + &mut self, + ctx: &egui::Context, + outcome: Option<&PositionOutcome>, + events: &mut Vec, + ) { + if ctx.egui_wants_keyboard_input() { + return; + } + use egui::{Key, Modifiers}; + let now = ctx.input(|i| i.time); + let mut changed = false; + ctx.input_mut(|i| { + // Ctrl+Backspace (not with Shift: that clears all conditions). + if !i.modifiers.shift && i.consume_key(Modifiers::COMMAND, Key::Backspace) { + self.reset(now); + changed = true; + } + if i.consume_key(Modifiers::COMMAND, Key::Z) + && self + .undo + .as_ref() + .is_some_and(|u| now - u.at < UNDO_SECONDS) + { + self.undo_reset(); + changed = true; + } + if i.consume_key(Modifiers::NONE, Key::ArrowLeft) { + changed |= self.go(self.cursor.saturating_sub(1)); + } + if i.consume_key(Modifiers::NONE, Key::ArrowRight) { + changed |= self.go(self.cursor + 1); + } + if i.consume_key(Modifiers::NONE, Key::Home) { + changed |= self.go(0); + } + if i.consume_key(Modifiers::NONE, Key::End) { + changed |= self.go(self.line.len()); + } + if i.consume_key(Modifiers::NONE, Key::Backspace) && self.cursor > 0 { + self.line.truncate(self.cursor - 1); + changed |= self.go(self.cursor - 1); + } + if i.consume_key(Modifiers::NONE, Key::F) { + self.flipped = !self.flipped; + } + }); + let digits = [ + Key::Num1, + Key::Num2, + Key::Num3, + Key::Num4, + Key::Num5, + Key::Num6, + Key::Num7, + Key::Num8, + Key::Num9, + ]; + if let Some(out) = outcome { + let pos = self.position(); + for (n, key) in digits.into_iter().enumerate() { + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key)) + && let Some(m) = out.moves.get(n).and_then(|s| s.uci.to_move(&pos).ok()) + { + self.play(m); + events.push(BoardEvent::Sound(self.sound_after())); + changed = true; + } + } + } + if changed { + events.push(BoardEvent::Changed); + } + } + + /// The board panel: header, board, line of moves and continuations. + /// `outcome` belongs to the shown position (`None` while it is being counted); + /// `table_hover` is the next move of the game under the pointer in the table; + /// `books` shows continuations as chapters without results. + pub fn panel( + &mut self, + ui: &mut Ui, + settings: &Settings, + outcome: Option<&PositionOutcome>, + counting: Option, + table_hover: Option, + books: bool, + ) -> Vec { + let mut events = Vec::new(); + let now = ui.input(|i| i.time); + self.header(ui, now, &mut events); + ui.add_space(4.0); + let pos = self.position(); + let hover = self.hover.or(table_hover); + self.hover = None; + let wide = ui.available_width() >= WIDE; + if wide { + let height = ui.available_height(); + ui.horizontal_top(|ui| { + let side = (height - 64.0 - 16.0) + .min(ui.available_width() - CONTINUATIONS_WIDTH - 24.0) + .clamp(240.0, 640.0); + ui.vertical(|ui| { + ui.set_width(side); + self.board(ui, settings, &pos, side, hover, &mut events); + self.line_ui(ui, &mut events); + }); + ui.add_space(12.0); + ui.vertical(|ui| { + self.continuations(ui, &pos, outcome, counting, books, &mut events); + }); + }); + } else { + let side = (ui.available_width() - 16.0) + .min(ui.available_height() - 64.0 - 156.0 - 16.0) + .clamp(240.0, 640.0); + ui.vertical_centered(|ui| { + self.board(ui, settings, &pos, side, hover, &mut events); + }); + self.line_ui(ui, &mut events); + ui.add_space(4.0); + self.continuations(ui, &pos, outcome, counting, books, &mut events); + } + events + } + + fn header(&mut self, ui: &mut Ui, now: f64, events: &mut Vec) { + ui.horizontal(|ui| { + let pos = self.position(); + let (rect, _) = ui.allocate_exact_size(vec2(12.0, 12.0), Sense::hover()); + let (fill, stroke) = if pos.turn() == Color::White { + (Color32::WHITE, Color32::from_gray(60)) + } else { + (Color32::from_gray(20), Color32::from_gray(200)) + }; + ui.painter() + .circle(rect.center(), 5.0, fill, Stroke::new(1.0, stroke)); + let text = if !self.is_set() { + tr("Starting position").to_string() + } else { + let side = if pos.turn() == Color::White { + tr("White to move") + } else { + tr("Black to move") + }; + match self.last_label() { + Some(last) => { + format!("{side} · {}", trf("after {move}", &[("move", &last)])) + } + None => side.to_string(), + } + }; + ui.label(text); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.menu_button("☰", |ui| { + if ui.button(tr("Open as a new game")).clicked() { + events.push(BoardEvent::OpenAsGame(self.pgn())); + ui.close(); + } + if ui.button(tr("Copy FEN")).clicked() { + let fen = Fen::from_position(&self.position(), EnPassantMode::Legal); + events.push(BoardEvent::CopyText(fen.to_string(), tr("FEN copied"))); + ui.close(); + } + if ui.button(tr("Copy moves (PGN)")).clicked() { + events.push(BoardEvent::CopyText(self.pgn(), tr("PGN copied"))); + ui.close(); + } + }); + let undo_open = self + .undo + .as_ref() + .is_some_and(|u| now - u.at < UNDO_SECONDS); + if undo_open && !self.is_set() { + if ui.button(tr("Undo")).on_hover_text("Ctrl+Z").clicked() { + self.undo_reset(); + events.push(BoardEvent::Changed); + } + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + } else if ui + .add_enabled(self.is_set(), egui::Button::new(tr("Reset"))) + .on_hover_text(tr("Starting position (Ctrl+Backspace)")) + .clicked() + { + self.reset(now); + events.push(BoardEvent::Changed); + } + if ui + .button("🔃") + .on_hover_text(tr("Flip the board (F)")) + .clicked() + { + self.flipped = !self.flipped; + } + }); + }); + } + + fn board( + &mut self, + ui: &mut Ui, + settings: &Settings, + pos: &Chess, + side: f32, + hover: Option, + events: &mut Vec, + ) { + let last_move = self + .cursor + .checked_sub(1) + .and_then(|i| self.line.get(i)) + .and_then(|m| Some((m.from()?, board::ui_target(m)))); + let arrows: Vec = hover + .and_then(|u| u.to_move(pos).ok()) + .and_then(|m| { + Some(Arrow { + from: m.from()?, + to: board::ui_target(&m), + color: PREVIEW_ARROW, + weight: 1.0, + }) + }) + .into_iter() + .collect(); + let view = BoardView { + pos, + orientation: if self.flipped { + Color::Black + } else { + Color::White + }, + last_move, + arrows: &arrows, + circles: &[], + badge: None, + interactive: true, + temporary_shapes: false, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: settings.animation.seconds(), + premove: None, + auto_queen: settings.auto_queen, + alert: None, + }; + let played = ui + .allocate_ui(vec2(side, side), |ui| view.show(ui, &mut self.board)) + .inner; + if let Some(m) = played { + // A click on the board takes the keys away from text fields. + ui.ctx().memory_mut(|m| m.surrender_focus(egui::Id::NULL)); + self.play(m); + events.push(BoardEvent::Sound(self.sound_after())); + events.push(BoardEvent::Changed); + } + } + + fn line_ui(&mut self, ui: &mut Ui, events: &mut Vec) { + ui.add_space(4.0); + ui.horizontal_top(|ui| { + if ui + .add_enabled(self.cursor > 0, egui::Button::new("â—€")) + .on_hover_text(tr("Move back (Left arrow)")) + .clicked() + && self.go(self.cursor - 1) + { + events.push(BoardEvent::Changed); + } + if ui + .add_enabled(self.cursor < self.line.len(), egui::Button::new("â–¶")) + .on_hover_text(tr("Move forward (Right arrow)")) + .clicked() + && self.go(self.cursor + 1) + { + events.push(BoardEvent::Changed); + } + egui::ScrollArea::vertical() + .max_height(60.0) + .auto_shrink([false, true]) + .show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if self.start_fen.is_some() { + ui.label("ðŸ� ").on_hover_text(format!( + "{}\n{}", + tr("Start position of the game"), + self.start_fen.clone().unwrap_or_default() + )); + } + if self.line.is_empty() { + ui.label(RichText::new(tr("Play moves on the board")).weak()); + } + let all = self.san_line(self.line.len()); + let mut clicked = None; + for (label, n) in all { + let current = n == self.cursor; + let mut text = + RichText::new(crate::san::show(&label).into_owned()).size(14.0); + if n > self.cursor { + text = text.weak(); + } + let r = ui.add(egui::Button::selectable(current, text).frame(false)); + if current { + r.scroll_to_me(None); + } + if r.clicked() { + clicked = Some(n); + } + } + if let Some(n) = clicked + && self.go(n) + { + events.push(BoardEvent::Changed); + } + }); + }); + }); + } + + fn continuations( + &mut self, + ui: &mut Ui, + pos: &Chess, + outcome: Option<&PositionOutcome>, + counting: Option, + books: bool, + events: &mut Vec, + ) { + let title = if books { + tr("Continuations in the book") + } else { + tr("Continuations") + }; + let Some(out) = outcome else { + ui.label(RichText::new(title).strong()); + ui.add_space(8.0); + if self.unavailable { + ui.label(RichText::new("—").weak()); + return; + } + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + let p = format!("{:.0}", counting.unwrap_or(0.0) * 100.0); + let text = match counting { + _ if self.preparing => { + trf("Preparing the position search (once)… {p} %", &[("p", &p)]) + } + Some(c) if c > 0.0 => trf("Counting… {p} %", &[("p", &p)]), + _ => tr("Counting…").to_string(), + }; + ui.label(RichText::new(text).weak()); + }); + return; + }; + let total: u32 = out.moves.iter().map(|m| m.tally.games).sum::() + out.ended.games; + ui.horizontal(|ui| { + ui.label(RichText::new(title).strong()); + let n = crate::large_db::grouped(out.matches.len()); + let label = if books { + trf("· {n} chapters", &[("n", &n)]) + } else { + trf("· {n} games", &[("n", &n)]) + }; + ui.label(RichText::new(label).weak()); + }); + if out.moves.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new(tr("No continuations in this selection")).weak()); + } + let mut play = None; + egui::ScrollArea::vertical() + .id_salt("continuations") + .auto_shrink([false, true]) + .max_height((ui.available_height() - 24.0).max(60.0)) + .show(ui, |ui| { + for (i, stat) in out.moves.iter().enumerate() { + let r = continuation_row(ui, i, pos, stat, total, books); + if r.hovered() { + self.hover = Some(stat.uci); + } + if r.clicked() { + play = stat.uci.to_move(pos).ok(); + } + } + }); + if out.ended.games > 0 { + ui.label( + RichText::new(trf( + "Ended here: {n}", + &[("n", &crate::large_db::grouped(out.ended.games as usize))], + )) + .weak(), + ); + } + if let Some(m) = play { + self.play(m); + events.push(BoardEvent::Sound(self.sound_after())); + events.push(BoardEvent::Changed); + } + } +} + +/// "3.d4" / "3…Nc6"; the first move of a line starting with Black gets its number too. +fn move_label(pos: &Chess, m: Move, first: bool) -> String { + let san = SanPlus::from_move(pos.clone(), m).to_string(); + let n = pos.fullmoves().get(); + match pos.turn() { + Color::White => format!("{n}.{san}"), + Color::Black if first => format!("{n}…{san}"), + Color::Black => san, + } +} + +/// One continuation: number, move, games, share, results bar, average rating, year. +pub fn continuation_row( + ui: &mut Ui, + i: usize, + pos: &Chess, + stat: &MoveStat, + total: u32, + books: bool, +) -> egui::Response { + let height = 22.0; + let width = ui.available_width(); + let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click()); + let visuals = ui.visuals(); + if resp.hovered() { + ui.painter() + .rect_filled(rect, 3.0, visuals.widgets.hovered.weak_bg_fill); + } + let few = stat.tally.games < 10 && !books; + let text_color = if few { + visuals.weak_text_color() + } else { + visuals.text_color() + }; + let font = egui::FontId::proportional(13.0); + let y = rect.center().y; + let mut x = rect.left() + 4.0; + let text = |x: f32, s: &str, color: Color32, align: egui::Align2| { + ui.painter() + .text(egui::pos2(x, y), align, s, font.clone(), color); + }; + // Every row is numbered; 1-9 also play the move. + text( + x + 18.0, + &(i + 1).to_string(), + visuals.weak_text_color(), + egui::Align2::RIGHT_CENTER, + ); + x += 26.0; + let label = stat + .uci + .to_move(pos) + .map(|m| move_label(pos, m, true)) + .unwrap_or_else(|_| stat.san.clone()); + let label = crate::san::show(&label); + text(x, &label, text_color, egui::Align2::LEFT_CENTER); + x += 78.0; + let games = crate::large_db::grouped(stat.tally.games as usize); + if books { + text( + x, + &trf("{n} chapters", &[("n", &games)]), + text_color, + egui::Align2::LEFT_CENTER, + ); + return resp; + } + text(x + 56.0, &games, text_color, egui::Align2::RIGHT_CENTER); + x += 62.0; + let share = if total > 0 { + stat.tally.games as f32 / total as f32 + } else { + 0.0 + }; + let show_share = width >= 330.0; + if show_share { + text( + x + 34.0, + &format!("{:.0}%", share * 100.0), + visuals.weak_text_color(), + egui::Align2::RIGHT_CENTER, + ); + x += 40.0; + } + let tail = if width >= 300.0 { 92.0 } else { 48.0 }; + let bar_width = (rect.right() - tail - x).max(60.0); + let bar = egui::Rect::from_min_size(egui::pos2(x, y - 7.0), vec2(bar_width, 14.0)); + results_bar(ui, bar, &stat.tally, text_color); + let resp = resp.on_hover_text(results_text(&stat.tally)); + x = bar.right() + 6.0; + let elo = stat + .tally + .average_elo() + .map_or_else(|| "—".to_string(), |e| e.to_string()); + text( + x, + &elo, + visuals.weak_text_color(), + egui::Align2::LEFT_CENTER, + ); + if width >= 300.0 && stat.tally.last_year > 0 { + text( + x + 44.0, + &stat.tally.last_year.to_string(), + visuals.weak_text_color(), + egui::Align2::LEFT_CENTER, + ); + } + resp +} + +/// White wins (light), draws (grey), Black wins (dark), with the percentages inside +/// wide enough segments: readable without telling colours apart. +pub fn results_bar(ui: &Ui, rect: egui::Rect, t: &Tally, _text: Color32) { + let decided = t.white_wins + t.draws + t.black_wins; + let painter = ui.painter(); + if decided == 0 { + painter.rect_stroke( + rect, + 2.0, + Stroke::new(1.0, ui.visuals().weak_text_color()), + egui::StrokeKind::Inside, + ); + return; + } + let parts = [ + ( + t.white_wins, + Color32::from_gray(0xe8), + Color32::from_gray(0x20), + ), + (t.draws, Color32::from_gray(0x8c), Color32::from_gray(0x10)), + ( + t.black_wins, + Color32::from_gray(0x2b), + Color32::from_gray(0xe0), + ), + ]; + let mut x = rect.left(); + for (n, fill, ink) in parts { + let w = rect.width() * n as f32 / decided as f32; + if w <= 0.0 { + continue; + } + let seg = + egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(x + w, rect.bottom())); + painter.rect_filled(seg, 0.0, fill); + if w >= 26.0 { + painter.text( + seg.center(), + egui::Align2::CENTER_CENTER, + format!("{:.0}", 100.0 * n as f32 / decided as f32), + egui::FontId::proportional(10.5), + ink, + ); + } + x += w; + } + painter.rect_stroke( + rect, + 2.0, + Stroke::new(1.0, Color32::from_gray(0x70)), + egui::StrokeKind::Inside, + ); +} + +fn results_text(t: &Tally) -> String { + let decided = (t.white_wins + t.draws + t.black_wins).max(1) as f32; + let pct = |n: u32| format!("{:.0}", 100.0 * n as f32 / decided); + let mut s = trf( + "White won {w} ({wp} %) · draws {d} ({dp} %) · Black won {b} ({bp} %)", + &[ + ("w", &t.white_wins), + ("wp", &pct(t.white_wins)), + ("d", &t.draws), + ("dp", &pct(t.draws)), + ("b", &t.black_wins), + ("bp", &pct(t.black_wins)), + ], + ); + if t.games < 10 { + s.push('\n'); + s.push_str(tr("Few games: the statistics are not reliable")); + } + s +} + +/// "9." after White's move, "9…" after Black's: the move after which a game reached +/// the position, from the number of half-moves. +pub fn ply_label(ply: u32) -> String { + if ply == 0 { + "0".into() + } else if ply % 2 == 1 { + format!("{}.", ply.div_ceil(2)) + } else { + format!("{}…", ply / 2) + } +} + +/// A position search (or other work with progress and cancelling) in the background. +pub struct Background { + cancel: Arc, + progress: Arc, + rx: Receiver>, + pub started: f64, +} + +impl Background { + /// Runs `work(progress, cancel)` in a thread; `None` from it means cancelled. + pub fn spawn( + ctx: &egui::Context, + now: f64, + work: impl FnOnce(&AtomicUsize, &AtomicBool) -> Option + Send + 'static, + ) -> Option> { + let cancel = Arc::new(AtomicBool::new(false)); + let progress = Arc::new(AtomicUsize::new(0)); + let (tx, rx) = channel(); + let (c, p, ctx) = (cancel.clone(), progress.clone(), ctx.clone()); + crate::platform::spawn("position-search", move || { + let r = work(&p, &c); + let _ = tx.send(r); + ctx.request_repaint(); + }) + .ok()?; + Some(Background { + cancel, + progress, + rx, + started: now, + }) + } + + /// The result once ready (`Some(None)`: cancelled or failed). + pub fn poll(&self) -> Option> { + self.rx.try_recv().ok() + } + + pub fn progress(&self) -> usize { + self.progress.load(Ordering::Relaxed) + } + + /// Asks the work to stop; its result still arrives. + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + + /// Waits up to `timeout` for the result (the work cleans up after itself). + pub fn wait(&self, timeout: std::time::Duration) -> Option> { + self.rx.recv_timeout(timeout).ok() + } +} + +impl Drop for Background { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +/// The move a game played next, drawn as an arrow when its row is under the pointer. +pub fn next_move_of(outcome: &PositionOutcome, index: usize) -> Option { + let i = outcome + .matches + .binary_search_by_key(&(index as u32), |m| m.index) + .ok()?; + outcome.matches.get(i)?.next +} + +/// Moves from the game's start to `node` (a position taken from a game), or `None` +/// when the path holds a null move (a teaching scheme, not a position of a game). +pub fn line_to(game: &chess_core::Game, node: chess_core::NodeId) -> Option<(Chess, Vec)> { + let start = game.position(game.root())?.clone(); + let mut pos = start.clone(); + let mut line = Vec::new(); + for id in game.path(node) { + if id == game.root() { + continue; + } + let gm = game.game_move(id)?; + let uci: UciMove = gm.uci()?.parse().ok()?; + let m = uci.to_move(&pos).ok()?; + pos.play_unchecked(m); + line.push(m); + } + Some((start, line)) +} diff --git a/apps/desktop/src/brilliant.rs b/apps/desktop/src/brilliant.rs new file mode 100644 index 0000000..f41e4ec --- /dev/null +++ b/apps/desktop/src/brilliant.rs @@ -0,0 +1,862 @@ +//! The search for brilliant and great moves (!!, !) in the games of a filtered list +//! or a manual selection (tasks 27 and 42): a background pass of +//! the game analysis's engine over at most [`LIMIT`] games, the index of what each +//! analysed record holds (kept beside the analysis cache, one file per database), and +//! the totals of a pass by category. Games already analysed come from the analysis +//! cache, the engine is not asked again; the source database is only read. + +use std::collections::BTreeMap; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use chess_core::Game; +use chess_import::Database; +use game_review::{CacheStore, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement}; +use serde::{Deserialize, Serialize}; + +/// A pass takes at most this many games (the owner's limit, inclusive). +pub const LIMIT: usize = 100; + +/// Why a pass over `n` listed games cannot start (the button is disabled with this). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Blocked { + NoGames, + TooMany, +} + +/// Whether a pass over a list of `n` games may start: 1 to [`LIMIT`] inclusive. +pub fn can_start(n: usize) -> Result<(), Blocked> { + match n { + 0 => Err(Blocked::NoGames), + n if n > LIMIT => Err(Blocked::TooMany), + _ => Ok(()), + } +} + +/// The manual source of a pass: its size before cached or unsupported games are taken +/// out, and how many of those records the current filter hid when the request was made. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SelectedGames { + pub games: usize, + pub hidden: usize, +} + +/// Engine judgements of one side of a game. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Counts { + pub brilliant: u32, + pub great: u32, + pub inaccuracies: u32, + pub mistakes: u32, + pub blunders: u32, +} + +/// One side of an analysed game: its judgements, average centipawn loss and accuracy. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct SideMarks { + #[serde(flatten)] + pub counts: Counts, + #[serde(default)] + pub acpl: Option, + #[serde(default)] + pub accuracy: Option, +} + +impl SideMarks { + fn of(s: &game_review::SideStats) -> SideMarks { + SideMarks { + counts: Counts { + brilliant: s.brilliant, + great: s.great, + inaccuracies: s.inaccuracies, + mistakes: s.mistakes, + blunders: s.blunders, + }, + acpl: s.acpl, + accuracy: s.accuracy, + } + } +} + +impl Counts { + pub fn add(&mut self, o: &Counts) { + self.brilliant += o.brilliant; + self.great += o.great; + self.inaccuracies += o.inaccuracies; + self.mistakes += o.mistakes; + self.blunders += o.blunders; + } +} + +/// A move of note: its ply in the main line (0: the first move), who made it, its +/// number and SAN (Latin letters, as in PGN), and whether it is brilliant (else great). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Found { + pub ply: u16, + pub white: bool, + pub number: u32, + pub san: String, + pub brilliant: bool, +} + +impl Found { + /// «21.Rxf7!!», «34…Nf3+!!» in the notation of the settings. + pub fn label(&self) -> String { + let dots = if self.white { "." } else { "…" }; + let mark = if self.brilliant { "!!" } else { "!" }; + format!("{}{dots}{}{mark}", self.number, crate::san::show(&self.san)) + } +} + +/// Why a game is not analysed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Skip { + NoMoves, + Chess960, + /// A training null move (`--`) in the main line. + NullMove, + Unreadable, +} + +impl Skip { + pub fn reason(self) -> &'static str { + crate::i18n::tr(match self { + Skip::NoMoves => "no moves", + Skip::Chess960 => "Chess960", + Skip::NullMove => "a null move in the main line", + Skip::Unreadable => "the game cannot be read", + }) + } +} + +/// What the index knows of a record. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Entry { + /// The main line's name in the analysis cache: the entry holds only while the record + /// still has this main line. + pub line: String, + #[serde(default)] + pub white: SideMarks, + #[serde(default)] + pub black: SideMarks, + /// Every !! and the first three !. + #[serde(default)] + pub found: Vec, + /// Analysed with the engine settings of before (counted as analysed). + #[serde(default)] + pub stale: bool, + #[serde(default)] + pub skip: Option, +} + +impl Entry { + /// The entry with only the marks of the sides that count (the filter's player): the + /// row's sign and hint show only them. + pub fn for_sides(&self, white: bool, black: bool) -> Entry { + let keep = |on: bool, s: &SideMarks| if on { *s } else { SideMarks::default() }; + Entry { + white: keep(white, &self.white), + black: keep(black, &self.black), + found: self + .found + .iter() + .filter(|f| if f.white { white } else { black }) + .cloned() + .collect(), + ..self.clone() + } + } + + /// The !! and ! of the sides that count. + pub fn of_sides(&self, white: bool, black: bool) -> Counts { + let mut c = Counts::default(); + if white { + c.add(&self.white.counts); + } + if black { + c.add(&self.black.counts); + } + c + } +} + +/// The entry of `record` if it still belongs to the game the database has there now (its +/// main line is the one analysed): a deleted or changed game never lends its marks to +/// the record that took its number. +pub fn current_entry(index: &Index, db: &Database, record: u32) -> Option { + let entry = index.get(record)?; + let game = db.load_game(record as usize)?.game; + (GameAnalysis::new(&game, None).cache_key() == entry.line).then(|| entry.clone()) +} + +/// The record of an analysis of `game`: its marks per side and its moves of note. +pub fn entry_of(analysis: &GameAnalysis, game: &Game) -> Entry { + let report = &analysis.report; + let line = analysis.line(); + let mut found = Vec::new(); + let mut great = 0; + for (ply, j) in report.judgements.iter().enumerate() { + let brilliant = match j { + Some(Judgement::Brilliant) => true, + Some(Judgement::Great) if great < 3 => { + great += 1; + false + } + _ => continue, + }; + let Some(&node) = line.get(ply + 1) else { + continue; + }; + let (Some(m), Some((number, color))) = (game.game_move(node), game.move_number(node)) + else { + continue; + }; + found.push(Found { + ply: ply as u16, + white: color == chess_core::shakmaty::Color::White, + number, + san: m.san.clone(), + brilliant, + }); + } + Entry { + line: analysis.cache_key(), + white: SideMarks::of(&report.white), + black: SideMarks::of(&report.black), + found, + stale: analysis.stale(), + skip: None, + } +} + +/// The entry of a game that is not analysed, and why («—» in the column). +pub fn skipped_entry(line: String, skip: Skip) -> Entry { + Entry { + line, + white: SideMarks::default(), + black: SideMarks::default(), + found: Vec::new(), + stale: false, + skip: Some(skip), + } +} + +/// Why `game` is not analysed, if it is not. +pub fn skip_of(game: &Game, chess960: bool) -> Option { + if chess960 { + return Some(Skip::Chess960); + } + let line = game.mainline(); + if line.is_empty() { + return Some(Skip::NoMoves); + } + if line + .iter() + .any(|id| game.game_move(*id).is_none_or(|m| m.is_null())) + { + return Some(Skip::NullMove); + } + None +} + +#[derive(Serialize, Deserialize)] +struct IndexFile { + version: u32, + records: Vec<(u32, Entry)>, +} + +const INDEX_VERSION: u32 = 1; + +/// The marks of a database's records, by record number, in a file of their own. No +/// file (or one of another version) is an empty index: nothing found yet. +#[derive(Debug, Default)] +pub struct Index { + file: Option, + records: BTreeMap, + /// Changes since it was read (the table re-checks what it shows). + pub generation: u64, +} + +/// The folder of the indexes: beside the analysis cache. +fn index_dir() -> Option { + crate::settings::Settings::cache_dir().map(|d| d.join("marks")) +} + +/// The index file of the database at `db`: named by a hash of its real path. +pub fn index_file(dir: &Path, db: &Path) -> PathBuf { + let real = std::fs::canonicalize(db).unwrap_or_else(|_| db.to_path_buf()); + let mut h = std::collections::hash_map::DefaultHasher::new(); + real.hash(&mut h); + dir.join(format!("{:016x}.json", h.finish())) +} + +impl Index { + /// The index of the database at `db`, from the program's cache. + pub fn of(db: &Path) -> Index { + match index_dir() { + Some(dir) => Index::load(index_file(&dir, db)), + None => Index::default(), + } + } + + /// The index kept in `file`. + pub fn load(file: PathBuf) -> Index { + let records = match crate::platform::fs::read(&file) { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(f) if f.version == INDEX_VERSION => f.records.into_iter().collect(), + Ok(f) => { + eprintln!("marks: {}: version {}", file.display(), f.version); + BTreeMap::new() + } + Err(e) => { + eprintln!("marks: {}: {e}", file.display()); + BTreeMap::new() + } + }, + Err(_) => BTreeMap::new(), + }; + Index { + file: Some(file), + records, + generation: 0, + } + } + + /// The records with an entry. + pub fn records(&self) -> impl Iterator + '_ { + self.records.keys().copied() + } + + pub fn get(&self, record: u32) -> Option<&Entry> { + self.records.get(&record) + } + + pub fn set(&mut self, record: u32, entry: Entry) { + self.records.insert(record, entry); + self.generation += 1; + } + + /// Where a record goes when the table is sorted by its marks: !! first, then !, + /// analysed without them, not analysable, not analysed. + pub fn rank(&self, record: u32, sides: &Sides, current: &dyn Fn(u32) -> bool) -> u8 { + match self.records.get(&record).filter(|_| current(record)) { + None => 4, + Some(e) if e.skip.is_some() => 3, + Some(e) => { + let (w, b) = sides.of(record); + let c = e.of_sides(w, b); + if c.brilliant > 0 { + 0 + } else if c.great > 0 { + 1 + } else { + 2 + } + } + } + } + + #[cfg(test)] + pub fn len(&self) -> usize { + self.records.len() + } + + /// Written whole into a temporary file and renamed over the old one. + pub fn save(&self) -> std::io::Result<()> { + let Some(file) = &self.file else { + return Ok(()); + }; + let out = IndexFile { + version: INDEX_VERSION, + records: self.records.iter().map(|(r, e)| (*r, e.clone())).collect(), + }; + let bytes = serde_json::to_vec(&out).map_err(std::io::Error::other)?; + if let Some(dir) = file.parent() { + std::fs::create_dir_all(dir)?; + } + crate::platform::fs::write_atomic(file, &bytes) + } +} + +/// How far a pass is: games done, and the record being analysed (its number + 1; 0: +/// none). +#[derive(Debug, Default)] +pub struct Progress { + pub done: AtomicUsize, + pub current: AtomicUsize, +} + +/// How a pass ended. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + Finished, + Stopped, + EngineFailed(String), + SourceChanged, +} + +/// What a pass did. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PassEnd { + pub outcome: Outcome, + /// Records analysed (by the engine now, or from the cache), in the pass's order. + pub reviewed: Vec, + /// Of them, taken from the cache without the engine. + pub from_cache: usize, + pub skipped: Vec<(u32, Skip)>, +} + +/// The engine of a pass: started for each game that needs it. +pub struct Engine { + #[cfg(not(web))] + pub config: uci::EngineConfig, + pub settings: JobSettings, + /// Whether the engine, by the name it gives, is still the one checked. + pub fits: Box bool + Send + Sync>, + /// A pause before each game (`CP_BRILLIANT_SLOW`: the progress can be photographed). + pub pause: std::time::Duration, +} + +/// The engine job over `targets` (on a computer; a browser has no pass, `CAPS`). +#[cfg(not(web))] +fn engine_run( + engine: &Engine, + targets: Vec, + cancel: &AtomicBool, + on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + game_review::run( + engine.config.clone(), + &engine.settings, + targets, + cancel, + on_event, + ) +} + +#[cfg(web)] +fn engine_run( + _engine: &Engine, + _targets: Vec, + _cancel: &AtomicBool, + _on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + Err(JobFailure::Start( + crate::i18n::tr("the engine did not start").to_owned(), + )) +} + +/// Analyses `records` of `db` in this order: each from the analysis cache in `cache` +/// when it is there (also one made with the engine settings of before), else with +/// `engine`; after each game the cache and `index` are saved, so a stop or a crash +/// keeps what was done. `cancel` stops it within the current search. +pub fn run_pass( + db: &Database, + records: &[u32], + index: &Mutex, + cache: &dyn CacheStore, + engine: &Engine, + progress: &Progress, + cancel: &AtomicBool, +) -> PassEnd { + let mut end = PassEnd { + outcome: Outcome::Finished, + reviewed: Vec::new(), + from_cache: 0, + skipped: Vec::new(), + }; + for &record in records { + if cancel.load(Ordering::Relaxed) { + end.outcome = Outcome::Stopped; + break; + } + if let Some(pgn) = db.as_pgn() + && pgn.source_changed().unwrap_or(true) + { + end.outcome = Outcome::SourceChanged; + break; + } + progress + .current + .store(record as usize + 1, Ordering::Relaxed); + if !engine.pause.is_zero() { + std::thread::sleep(engine.pause); + if cancel.load(Ordering::Relaxed) { + end.outcome = Outcome::Stopped; + break; + } + } + let index_skip = |skip: Skip, line: String| { + if let Ok(mut i) = index.lock() { + i.set( + record, + Entry { + line, + white: SideMarks::default(), + black: SideMarks::default(), + found: Vec::new(), + stale: false, + skip: Some(skip), + }, + ); + let _ = i.save(); + } + }; + let Some(parsed) = db.load_game(record as usize) else { + end.skipped.push((record, Skip::Unreadable)); + index_skip(Skip::Unreadable, String::new()); + progress.done.fetch_add(1, Ordering::Relaxed); + continue; + }; + let game = parsed.game; + let chess960 = db.row(record as usize).chess960; + let mut analysis = GameAnalysis::with_store(&game, Some(cache)); + if let Some(skip) = skip_of(&game, chess960) { + end.skipped.push((record, skip)); + index_skip(skip, analysis.cache_key()); + progress.done.fetch_add(1, Ordering::Relaxed); + continue; + } + let by_engine = analysis.has_data() && analysis.meta.as_ref().is_some_and(|m| m.nodes > 0); + // An analysis with every position evaluated is one, also of the engine settings + // of before (the owner's decision; `begin` would drop that one): it is taken as + // it is, the engine is not asked. + let targets = if by_engine && (analysis.stale() || analysis.missing() == 0) { + Vec::new() + } else { + analysis.begin(&game, !by_engine) + }; + if targets.is_empty() && by_engine { + end.from_cache += 1; + } else { + let mut changed = false; + let result = engine_run(engine, targets, cancel, &mut |e| { + if changed { + return; + } + if let JobEvent::Engine(name) = &e + && !(engine.fits)(name) + { + changed = true; + return; + } + analysis.apply(e); + }); + if changed { + end.outcome = Outcome::EngineFailed( + crate::i18n::tr("the engine is no longer the Stockfish 19 that was checked") + .to_owned(), + ); + break; + } + if let Err(e) = result { + end.outcome = Outcome::EngineFailed(match e { + JobFailure::Start(e) => { + eprintln!("great moves: {e}"); + crate::i18n::tr("the engine did not start").to_owned() + } + JobFailure::Engine(e) => { + eprintln!("great moves: {e}"); + crate::i18n::tr("the engine stopped answering").to_owned() + } + JobFailure::Terminated(r) => crate::analysis::termination_message(&r), + }); + break; + } + if cancel.load(Ordering::Relaxed) { + // The evaluations made are kept for later; the game is not counted. + let _ = analysis.save_to(cache); + end.outcome = Outcome::Stopped; + break; + } + if let Err(e) = analysis.save_to(cache) { + eprintln!("review cache: {e}"); + } + } + analysis.refresh(&game); + if let Ok(mut i) = index.lock() { + i.set(record, entry_of(&analysis, &game)); + if let Err(e) = i.save() { + eprintln!("marks: {e}"); + } + } + end.reviewed.push(record); + progress.done.fetch_add(1, Ordering::Relaxed); + } + progress.current.store(0, Ordering::Relaxed); + end +} + +/// Whose moves count in the totals of each record: the player of the filter's sides +/// (`white`, `black`), or both when the filter names no player. +#[derive(Clone, Debug, Default)] +pub struct Sides { + /// Records where the filter's player has White, and Black; `None`: no player. + pub player: Option<(Vec, Vec)>, +} + +impl Sides { + /// Whether White's and Black's moves of `record` count. + pub fn of(&self, record: u32) -> (bool, bool) { + match &self.player { + None => (true, true), + Some((w, b)) => ( + w.binary_search(&record).is_ok(), + b.binary_search(&record).is_ok(), + ), + } + } +} + +/// The totals of a pass: games analysed, those with !! and with !, every category +/// summed over the sides that count, the averages over those sides, and the !! moves. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Totals { + pub games: usize, + pub with_brilliant: usize, + pub with_great: usize, + pub counts: Counts, + /// Sides counted (a game counts twice when both of its sides do). + pub sides: usize, + /// Average over the sides of their average centipawn loss, and of their accuracy, + /// with the least and the greatest accuracy. + pub acpl: Option, + pub accuracy: Option, + pub accuracy_range: Option<(f64, f64)>, + /// Of them, analysed with the engine settings of before. + pub stale: usize, + /// Records where the filter's player was found on neither side. + pub player_missing: Vec, + /// Every !! of the sides that count: record and move, in the records' order. + pub brilliant: Vec<(u32, Found)>, +} + +/// Sums the index's entries of `records` over the sides that count (`sides`). +pub fn totals(index: &Index, db: &Database, records: &[u32], sides: &Sides) -> Totals { + let mut t = Totals::default(); + let (mut acpl, mut acc) = (Vec::new(), Vec::new()); + for &r in records { + let Some(e) = current_entry(index, db, r).filter(|e| e.skip.is_none()) else { + continue; + }; + let e = &e; + let (white, black) = sides.of(r); + if !white && !black { + t.player_missing.push(r); + } + let c = e.of_sides(white, black); + t.games += 1; + t.stale += usize::from(e.stale); + t.with_brilliant += usize::from(c.brilliant > 0); + t.with_great += usize::from(c.great > 0); + t.counts.add(&c); + for (counted, side) in [(white, &e.white), (black, &e.black)] { + if counted { + t.sides += 1; + acpl.extend(side.acpl.map(f64::from)); + acc.extend(side.accuracy); + } + } + t.brilliant.extend( + e.found + .iter() + .filter(|f| f.brilliant && if f.white { white } else { black }) + .map(|f| (r, f.clone())), + ); + } + let mean = |v: &[f64]| (!v.is_empty()).then(|| v.iter().sum::() / v.len() as f64); + t.acpl = mean(&acpl); + t.accuracy = mean(&acc); + t.accuracy_range = acc.iter().copied().fold(None, |r: Option<(f64, f64)>, a| { + Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a)))) + }); + t +} + +/// The records where the filter's player has White and Black: the player condition +/// with the side fixed, without the other conditions. A selected game hidden by those +/// other conditions still keeps its player's side; a game of another player has neither. +pub fn player_sides( + db: &Database, + filter: &chess_import::chessbase::base::Filter, + cancel: &AtomicBool, +) -> Sides { + use chess_import::chessbase::base::{Side, SortKey}; + if !filter.player.is_set() { + return Sides::default(); + } + let player = chess_import::chessbase::base::Filter { + player: filter.player.clone(), + side: filter.side, + ..Default::default() + }; + let side = |s: Side| { + let f = chess_import::chessbase::base::Filter { + side: s, + ..player.clone() + }; + let mut v = db + .query(&f, SortKey::Number, true, &AtomicUsize::new(0), cancel) + .unwrap_or_default(); + v.sort_unstable(); + v + }; + let (w, b) = match filter.side { + Side::White => (side(Side::White), Vec::new()), + Side::Black => (Vec::new(), side(Side::Black)), + _ => (side(Side::White), side(Side::Black)), + }; + Sides { + player: Some((w, b)), + } +} + +/// What the app keeps of a pass for its summary: the filter, the words for its +/// conditions (or the manual source), and the games that could not be analysed. +pub type PassMeta = ( + chess_import::chessbase::base::Filter, + String, + Option, + Vec<(u32, Skip)>, +); + +/// A pass under way, on a thread of its own: its source, its list, how far it is, and +/// how it ended once it did. +pub struct PassJob { + pub source: PathBuf, + pub records: Vec, + pub selected: Option, + progress: std::sync::Arc, + cancel: std::sync::Arc, + rx: std::sync::mpsc::Receiver<(PassEnd, Sides)>, + pub stopping: bool, + pub started: std::time::Instant, +} + +impl PassJob { + /// Starts the pass over `records` of `db` (the database at `source`); the sides of + /// the filter's player are found first, in the same thread. + #[allow(clippy::too_many_arguments)] + pub fn start( + ctx: &egui::Context, + source: PathBuf, + db: std::sync::Arc, + records: Vec, + filter: chess_import::chessbase::base::Filter, + selected: Option, + index: std::sync::Arc>, + cache: PathBuf, + engine: Engine, + ) -> std::io::Result { + let progress = std::sync::Arc::new(Progress::default()); + let cancel = std::sync::Arc::new(AtomicBool::new(false)); + let (tx, rx) = std::sync::mpsc::channel(); + let (p, c, list, ctx) = ( + progress.clone(), + cancel.clone(), + records.clone(), + ctx.clone(), + ); + std::thread::Builder::new() + .name("brilliant-search".into()) + .spawn(move || { + let sides = player_sides(&db, &filter, &c); + let store = crate::review::Cache(cache); + let end = run_pass(&db, &list, &index, &store, &engine, &p, &c); + let _ = tx.send((end, sides)); + ctx.request_repaint(); + })?; + Ok(PassJob { + source, + records, + selected, + progress, + cancel, + rx, + stopping: false, + started: std::time::Instant::now(), + }) + } + + pub fn done(&self) -> usize { + self.progress.done.load(Ordering::Relaxed) + } + + /// The record being analysed. + pub fn current(&self) -> Option { + match self.progress.current.load(Ordering::Relaxed) { + 0 => None, + n => Some(n as u32 - 1), + } + } + + /// «Stop»: the engines stop within their search; what was analysed stays. + pub fn stop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + self.stopping = true; + } + + /// How it ended, once it did. + pub fn poll(&self) -> Option<(PassEnd, Sides)> { + self.rx.try_recv().ok() + } + + /// Stops and waits up to `timeout` (closing the program). + pub fn shutdown(&mut self, timeout: std::time::Duration) { + self.stop(); + let _ = self.rx.recv_timeout(timeout); + } + + /// The time left, from the pace so far after three games, else from the moves. + pub fn left_secs(&self, estimate: impl Fn(&[u32]) -> f64) -> f64 { + let done = self.done(); + let rest = &self.records[done.min(self.records.len())..]; + if done >= 3 { + self.started.elapsed().as_secs_f64() / done as f64 * rest.len() as f64 + } else { + estimate(rest) + } + } +} + +impl Drop for PassJob { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +/// Seconds per position of one engine process, with the second search of !! and !: +/// measured, 3 games of 170 plies in 44 s in 8 processes (i7-13700KF, +/// docs/qa/task-27-functional-2026-11-27.md). +const SECS_PER_POSITION: f64 = 2.0; + +/// Seconds an engine takes for games of these many plies over `processes`: the same in +/// the question and in the progress until three games are done. +pub fn estimate_secs(plies: impl Iterator, processes: usize) -> f64 { + plies + .map(|p| (p + 1) as f64 * SECS_PER_POSITION) + .sum::() + / processes.max(1) as f64 +} + +/// «less than a minute», «about 14 min», «about 1 h 20 min». +pub fn format_estimate(secs: f64) -> String { + if secs < 60.0 { + return crate::i18n::tr("less than a minute").to_owned(); + } + let min = (secs / 60.0).round() as u64; + if min < 60 { + crate::i18n::trf("about {n} min", &[("n", &min)]) + } else { + crate::i18n::trf( + "about {h} h {m} min", + &[("h", &(min / 60)), ("m", &(min % 60))], + ) + } +} + +#[cfg(test)] +#[path = "brilliant_tests.rs"] +mod tests; diff --git a/apps/desktop/src/brilliant_tests.rs b/apps/desktop/src/brilliant_tests.rs new file mode 100644 index 0000000..3cca246 --- /dev/null +++ b/apps/desktop/src/brilliant_tests.rs @@ -0,0 +1,617 @@ +use std::sync::Arc; + +use game_review::CacheDir; + +use super::*; + +struct Dir(PathBuf); + +impl Dir { + fn new(name: &str) -> Dir { + let path = std::env::temp_dir().join(format!("cp-brilliant-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(path.join("cache")).unwrap(); + Dir(path) + } + + fn cache(&self) -> PathBuf { + self.0.join("cache") + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). +fn fake() -> PathBuf { + let fake = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/debug/fake_uci"); + assert!( + fake.exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + fake +} + +fn engine_at(path: &Path) -> Engine { + Engine { + config: uci::EngineConfig { + // The second search of !! and ! (`searchmoves`), as Stockfish makes it. + args: vec!["--searchmoves".into()], + ..uci::EngineConfig::new(path) + }, + settings: JobSettings::new(2, None), + fits: Box::new(|_| true), + pause: std::time::Duration::ZERO, + } +} + +/// An engine that cannot start: a pass that asks for it fails. +fn no_engine(dir: &Dir) -> Engine { + engine_at(&dir.0.join("no-such-engine")) +} + +const GAMES: &str = "[White \"Carlsen\"]\n[Black \"Kasparov\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 Nc6 *\n\n\ +[White \"Kasparov\"]\n[Black \"Carlsen\"]\n[Result \"*\"]\n\n1. d4 d5 2. c4 *\n\n\ +[White \"Anand\"]\n[Black \"Topalov\"]\n[Result \"*\"]\n\n1. e4 -- 2. d4 *\n\n\ +[White \"Anand\"]\n[Black \"Kramnik\"]\n[Result \"*\"]\n\n*\n"; + +fn source(dir: &Dir) -> (PathBuf, Database) { + let path = dir.0.join("games.pgn"); + std::fs::write(&path, GAMES).unwrap(); + let db = chess_import::open(&path, &mut |_| {}, &AtomicBool::new(false)) + .unwrap() + .db; + (path, db) +} + +fn pass( + db: &Database, + records: &[u32], + index: &Mutex, + dir: &Dir, + engine: &Engine, +) -> PassEnd { + let cache = dir.cache(); + run_pass( + db, + records, + index, + &CacheDir(&cache), + engine, + &Progress::default(), + &AtomicBool::new(false), + ) +} + +#[test] +fn the_limit_is_one_hundred_games_inclusive() { + assert_eq!(can_start(0), Err(Blocked::NoGames)); + assert_eq!(can_start(1), Ok(())); + assert_eq!(can_start(LIMIT), Ok(())); + assert_eq!(LIMIT, 100); + assert_eq!(can_start(101), Err(Blocked::TooMany)); +} + +#[test] +fn a_pass_analyses_keeps_the_index_and_takes_the_cache_next_time() { + let dir = Dir::new("pass"); + let (path, db) = source(&dir); + let before = std::fs::read(&path).unwrap(); + let file = dir.0.join("marks.json"); + let index = Mutex::new(Index::load(file.clone())); + let end = pass(&db, &[0, 1, 2, 3], &index, &dir, &engine_at(&fake())); + assert_eq!(end.outcome, Outcome::Finished); + assert_eq!(end.reviewed, vec![0, 1]); + assert_eq!(end.from_cache, 0); + assert_eq!(end.skipped, vec![(2, Skip::NullMove), (3, Skip::NoMoves)]); + // The index lives on: read anew (as after a restart) it has every record. + let again = Index::load(file.clone()); + assert_eq!(again.len(), 4); + let entry = again.get(0).unwrap(); + let game = db.load_game(0).unwrap().game; + assert_eq!(entry.line, GameAnalysis::new(&game, None).cache_key()); + assert_eq!(again.get(2).unwrap().skip, Some(Skip::NullMove)); + // Again: from the cache, the engine is not asked (there is none now). + let index = Mutex::new(again); + let end = pass(&db, &[1, 0], &index, &dir, &no_engine(&dir)); + assert_eq!(end.outcome, Outcome::Finished); + assert_eq!((end.reviewed, end.from_cache), (vec![1, 0], 2)); + // The source is only read. + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn an_analysis_of_the_settings_of_before_counts_as_made() { + let dir = Dir::new("stale"); + let (_, db) = source(&dir); + let index = Mutex::new(Index::load(dir.0.join("marks.json"))); + pass(&db, &[0], &index, &dir, &engine_at(&fake())); + // The cached analysis made «before the fixed search». + for f in std::fs::read_dir(dir.cache()).unwrap() { + let f = f.unwrap().path(); + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&f).unwrap()).unwrap(); + v["meta"]["search"] = serde_json::json!(0); + std::fs::write(&f, serde_json::to_vec(&v).unwrap()).unwrap(); + } + let end = pass(&db, &[0], &index, &dir, &no_engine(&dir)); + assert_eq!((end.outcome, end.from_cache), (Outcome::Finished, 1)); + assert!(index.lock().unwrap().get(0).unwrap().stale); +} + +#[test] +fn a_stopped_pass_keeps_what_it_analysed() { + let dir = Dir::new("stop"); + let (_, db) = source(&dir); + let file = dir.0.join("marks.json"); + let index = Mutex::new(Index::load(file.clone())); + // Stopped when the second game's engine starts: the first one is kept. + let cancel = Arc::new(AtomicBool::new(false)); + let starts = Arc::new(AtomicUsize::new(0)); + let (c, s) = (cancel.clone(), starts.clone()); + let engine = Engine { + fits: Box::new(move |_| { + if s.fetch_add(1, Ordering::Relaxed) >= 1 { + c.store(true, Ordering::Relaxed); + } + true + }), + ..engine_at(&fake()) + }; + let cache = dir.cache(); + let end = run_pass( + &db, + &[0, 1], + &index, + &CacheDir(&cache), + &engine, + &Progress::default(), + &cancel, + ); + assert_eq!(end.outcome, Outcome::Stopped); + assert_eq!(end.reviewed, vec![0]); + let kept = Index::load(file); + assert!(kept.get(0).is_some() && kept.get(1).is_none()); +} + +#[test] +fn starting_and_stopping_at_once_never_breaks_the_index() { + let dir = Dir::new("race"); + let (_, db) = source(&dir); + let db = Arc::new(db); + let file = dir.0.join("marks.json"); + for round in 0..10 { + let index = Arc::new(Mutex::new(Index::load(file.clone()))); + let cancel = Arc::new(AtomicBool::new(false)); + let (d, i, c, cache) = (db.clone(), index.clone(), cancel.clone(), dir.cache()); + let worker = std::thread::spawn(move || { + run_pass( + &d, + &[0, 1, 2, 3], + &i, + &CacheDir(&cache), + &engine_at(&fake()), + &Progress::default(), + &c, + ) + }); + if round % 2 == 0 { + std::thread::yield_now(); + } + cancel.store(true, Ordering::Relaxed); + let end = worker.join().unwrap(); + assert!(matches!(end.outcome, Outcome::Stopped | Outcome::Finished)); + // The file is whole: it reads. + if file.exists() { + let bytes = std::fs::read(&file).unwrap(); + assert!(serde_json::from_slice::(&bytes).is_ok()); + } + } +} + +#[test] +fn a_broken_index_is_an_empty_one() { + let dir = Dir::new("broken"); + let file = dir.0.join("marks.json"); + std::fs::write(&file, b"{not json").unwrap(); + assert_eq!(Index::load(file.clone()).len(), 0); + std::fs::write(&file, br#"{"version":99,"records":[]}"#).unwrap(); + assert_eq!(Index::load(file).len(), 0); + assert_eq!(Index::load(dir.0.join("none.json")).len(), 0); +} + +/// The entries of `index` made the database's own: their main lines are those of its +/// games (as a pass writes them). +fn fit(index: &mut Index, db: &Database) { + let records: Vec = index.records().collect(); + for r in records { + let mut e = index.get(r).unwrap().clone(); + e.line = GameAnalysis::new(&db.load_game(r as usize).unwrap().game, None).cache_key(); + index.set(r, e); + } +} + +fn side(brilliant: u32, great: u32, blunders: u32, acpl: u32, accuracy: f64) -> SideMarks { + SideMarks { + counts: Counts { + brilliant, + great, + blunders, + ..Counts::default() + }, + acpl: Some(acpl), + accuracy: Some(accuracy), + } +} + +fn found(ply: u16, white: bool, number: u32, san: &str, brilliant: bool) -> Found { + Found { + ply, + white, + number, + san: san.into(), + brilliant, + } +} + +#[test] +fn totals_count_only_the_filters_players_moves() { + let mut index = Index::default(); + let entry = |white, black, found| Entry { + line: String::new(), + white, + black, + found, + stale: false, + skip: None, + }; + index.set( + 0, + entry( + side(1, 0, 0, 20, 90.0), + side(0, 2, 1, 40, 70.0), + vec![ + found(40, true, 21, "Rxf7", true), + found(13, false, 7, "Nd5", false), + ], + ), + ); + index.set( + 1, + entry( + side(0, 0, 3, 60, 60.0), + side(1, 1, 0, 10, 96.0), + vec![found(67, false, 34, "Nf3+", true)], + ), + ); + index.set( + 2, + Entry { + skip: Some(Skip::Chess960), + ..entry(SideMarks::default(), SideMarks::default(), Vec::new()) + }, + ); + let dir = Dir::new("totals"); + let (_, db) = source(&dir); + fit(&mut index, &db); + let all = totals(&index, &db, &[0, 1, 2], &Sides::default()); + assert_eq!( + (all.games, all.sides, all.with_brilliant, all.with_great), + (2, 4, 2, 2) + ); + assert_eq!( + all.counts, + Counts { + brilliant: 2, + great: 3, + blunders: 4, + ..Counts::default() + } + ); + assert_eq!(all.acpl, Some(32.5)); + assert_eq!(all.accuracy_range, Some((60.0, 96.0))); + assert_eq!(all.brilliant.len(), 2); + // The player had White in game 0 and Black in game 1: only those sides count. + let player = Sides { + player: Some((vec![0], vec![1])), + }; + let t = totals(&index, &db, &[0, 1, 2], &player); + assert_eq!( + (t.games, t.sides, t.with_brilliant, t.with_great), + (2, 2, 2, 1) + ); + assert_eq!(t.counts.blunders, 0); + assert_eq!(t.acpl, Some(15.0)); + assert_eq!(t.accuracy, Some(93.0)); + assert_eq!( + t.brilliant + .iter() + .map(|(r, f)| (*r, f.label())) + .collect::>(), + [(0, "21.Rxf7!!".to_owned()), (1, "34…Nf3+!!".to_owned())] + ); + // A player found on neither side is said. + let nobody = Sides { + player: Some((Vec::new(), Vec::new())), + }; + assert_eq!( + totals(&index, &db, &[0, 1], &nobody).player_missing, + vec![0, 1] + ); +} + +#[test] +fn the_players_sides_come_from_the_filter() { + let dir = Dir::new("sides"); + let (_, db) = source(&dir); + let filter = chess_import::chessbase::base::Filter { + player: chess_import::chessbase::base::NameFilter { + text: "carlsen".into(), + exact: None, + }, + ..Default::default() + }; + let sides = player_sides(&db, &filter, &AtomicBool::new(false)); + assert_eq!(sides.player, Some((vec![0], vec![1]))); + assert!( + player_sides(&db, &Default::default(), &AtomicBool::new(false)) + .player + .is_none() + ); + let quick_search = chess_import::chessbase::base::Filter { + text: "carlsen".into(), + ..Default::default() + }; + assert!( + player_sides(&db, &quick_search, &AtomicBool::new(false)) + .player + .is_none() + ); +} + +#[test] +fn a_selected_game_hidden_by_another_condition_keeps_its_players_side() { + let dir = Dir::new("hidden-sides"); + let (_, db) = source(&dir); + let filter = chess_import::chessbase::base::Filter { + player: chess_import::chessbase::base::NameFilter { + text: "carlsen".into(), + exact: None, + }, + // None of the sample games has a year, so the filtered table is empty. The + // manually selected Carlsen games nevertheless retain White and Black. + year_from: Some(2020), + ..Default::default() + }; + let sides = player_sides(&db, &filter, &AtomicBool::new(false)); + assert_eq!(sides.player, Some((vec![0], vec![1]))); + assert_eq!(sides.of(0), (true, false)); + assert_eq!(sides.of(1), (false, true)); + assert_eq!(sides.of(2), (false, false)); + + let mut white = filter.clone(); + white.side = chess_import::chessbase::base::Side::White; + assert_eq!( + player_sides(&db, &white, &AtomicBool::new(false)).player, + Some((vec![0], Vec::new())) + ); + let mut black = filter; + black.side = chess_import::chessbase::base::Side::Black; + assert_eq!( + player_sides(&db, &black, &AtomicBool::new(false)).player, + Some((Vec::new(), vec![1])) + ); +} + +/// White found a !! and Black a !: the row of a filter on the Black player shows !. +fn two_sided() -> Index { + let mut index = Index::default(); + index.set( + 0, + Entry { + line: String::new(), + white: side(1, 0, 0, 10, 95.0), + black: side(0, 1, 2, 40, 70.0), + found: vec![ + found(20, true, 11, "Rxf7", true), + found(23, false, 12, "Nd5", false), + ], + stale: false, + skip: None, + }, + ); + index.set( + 1, + Entry { + found: Vec::new(), + ..index.get(0).unwrap().clone() + }, + ); + index +} + +#[test] +fn the_column_counts_only_the_filters_players_moves() { + let index = two_sided(); + let any = |_| true; + let both = Sides::default(); + let black = Sides { + player: Some((Vec::new(), vec![0])), + }; + assert_eq!(index.rank(0, &both, &any), 0); + assert_eq!(index.rank(0, &black, &any), 1); + // A game where the player is on neither side has nothing of his. + assert_eq!(index.rank(1, &black, &any), 2); + let e = index.get(0).unwrap().for_sides(false, true); + assert_eq!(e.of_sides(true, true).brilliant, 0); + assert_eq!(e.of_sides(true, true).great, 1); + assert_eq!( + e.found.iter().map(Found::label).collect::>(), + ["12…Nd5!"] + ); +} + +#[test] +fn the_summary_keeps_the_original_snapshot_and_player_for_continue() { + let dir = Dir::new("summary"); + let (path, db) = source(&dir); + let filter = chess_import::chessbase::base::Filter { + player: chess_import::chessbase::base::NameFilter { + text: "carlsen".into(), + exact: None, + }, + ..Default::default() + }; + let sides = player_sides(&db, &filter, &AtomicBool::new(false)); + let mut index = two_sided(); + fit(&mut index, &db); + let mut original = vec![0, 1, 2]; + let selected = Some(SelectedGames { + games: 3, + hidden: 1, + }); + // Record 0: Carlsen has White (its !!); record 1: Carlsen has Black (a !). + let summary = crate::brilliant_ui::Summary::new( + &path, + &db, + &index, + &original, + &sides, + &filter, + String::new(), + selected, + Some((2, 3)), + Vec::new(), + ); + // A later live selection has new records: neither the new record nor the changed + // order can enter the continuation held by this summary. + original.clear(); + original.push(3); + assert_eq!(summary.filter, filter); + assert_eq!(summary.rest, vec![2]); + assert_eq!(summary.selected_games, selected); + assert_eq!( + (summary.totals.counts.brilliant, summary.totals.counts.great), + (1, 1) + ); + assert_eq!(summary.totals.counts.blunders, 2); + assert_eq!(summary.player, Some(("carlsen".to_owned(), 1, 1))); + assert_eq!(summary.rows.len(), 1); +} + +const FIVE: &str = "[White \"A\"]\n[Black \"B\"]\n[Result \"*\"]\n\n1. e4 e5 *\n\n\ +[White \"C\"]\n[Black \"D\"]\n[Result \"*\"]\n\n1. d4 d5 *\n\n\ +[White \"E\"]\n[Black \"F\"]\n[Result \"*\"]\n\n1. c4 e5 *\n\n\ +[White \"G\"]\n[Black \"H\"]\n[Result \"*\"]\n\n1. Nf3 d5 *\n\n\ +[White \"I\"]\n[Black \"J\"]\n[Result \"*\"]\n\n1. g3 g6 *\n"; + +/// A game deleted (the 2nd of 5): the records after it take other numbers, and none of +/// them lends another game's marks — not in the summary, not in the sort; asked again, +/// the entries are made anew from the cache. +#[test] +fn a_deleted_game_never_lends_its_marks() { + let dir = Dir::new("deleted"); + let path = dir.0.join("five.pgn"); + std::fs::write(&path, FIVE).unwrap(); + let open = |p: &Path| { + chess_import::open(p, &mut |_| {}, &AtomicBool::new(false)) + .unwrap() + .db + }; + let db = open(&path); + let file = dir.0.join("marks.json"); + let index = Mutex::new(Index::load(file.clone())); + pass(&db, &[0, 1, 2, 3, 4], &index, &dir, &engine_at(&fake())); + // Each game marked: a !! of its own, told apart by its number. + { + let mut i = index.lock().unwrap(); + for r in 0..5u32 { + let mut e = i.get(r).unwrap().clone(); + e.white.counts.brilliant = 1; + e.found = vec![found(0, true, r + 1, "x", true)]; + i.set(r, e); + } + i.save().unwrap(); + } + let without_second: String = FIVE + .split("\n\n[") + .enumerate() + .filter(|(i, _)| *i != 1) + .map(|(i, g)| { + if i == 0 { + g.to_owned() + } else { + format!("[{g}") + } + }) + .collect::>() + .join("\n\n"); + std::fs::write(&path, without_second).unwrap(); + let db = open(&path); + assert_eq!(db.len(), 4); + let i = index.lock().unwrap(); + let t = totals(&i, &db, &[0, 1, 2, 3], &Sides::default()); + assert_eq!(t.games, 1); + assert_eq!( + t.brilliant + .iter() + .map(|(_, f)| f.number) + .collect::>(), + [1] + ); + assert!(current_entry(&i, &db, 1).is_none()); + assert_eq!( + i.rank(1, &Sides::default(), &|r| current_entry(&i, &db, r) + .is_some()), + 4 + ); + drop(i); + // «Find» again: counted from the cache, the entries are the games' own again. + let cache = dir.cache(); + let c = crate::brilliant_ui::count( + &db, + &[0, 1, 2, 3], + &Default::default(), + &cache, + &index, + &AtomicBool::new(false), + ); + assert_eq!(c.reviewed, vec![0, 1, 2, 3]); + let i = index.lock().unwrap(); + assert_eq!(totals(&i, &db, &[0, 1, 2, 3], &Sides::default()).games, 4); +} + +/// Games that cannot be analysed get «—» with the reason in the index. +#[test] +fn games_not_analysable_get_their_reason() { + let dir = Dir::new("skips"); + let (_, db) = source(&dir); + let index = Mutex::new(Index::load(dir.0.join("marks.json"))); + let c = crate::brilliant_ui::count( + &db, + &[2, 3], + &Default::default(), + &dir.cache(), + &index, + &AtomicBool::new(false), + ); + assert_eq!(c.skipped, vec![(2, Skip::NullMove), (3, Skip::NoMoves)]); + let i = index.lock().unwrap(); + assert_eq!( + current_entry(&i, &db, 2).unwrap().skip, + Some(Skip::NullMove) + ); + assert_eq!(i.get(3).unwrap().skip, Some(Skip::NoMoves)); +} + +#[test] +fn estimates_are_said_plainly() { + assert_eq!(format_estimate(30.0), "less than a minute"); + assert_eq!(format_estimate(14.0 * 60.0), "about 14 min"); + assert_eq!(format_estimate(80.0 * 60.0), "about 1 h 20 min"); + // The tester's measure: 3 games of 170 plies in 8 processes, 44 s. + let secs = estimate_secs([56, 57, 57].into_iter(), 8); + assert!((40.0..48.0).contains(&secs), "{secs}"); +} diff --git a/apps/desktop/src/brilliant_ui.rs b/apps/desktop/src/brilliant_ui.rs new file mode 100644 index 0000000..b37c07e --- /dev/null +++ b/apps/desktop/src/brilliant_ui.rs @@ -0,0 +1,776 @@ +//! The windows of the search for great moves (task 27, +//! docs/design/task-27-brilliant-search-2026-11-27.md): the question before a pass +//! (§4.4) and the summary after it (§4.9). + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; + +use chess_import::Database; +use chess_import::chessbase::base::Filter; +use egui::{Key, RichText}; +use game_review::{GameAnalysis, Judgement}; + +use crate::brilliant::{Found, Index, SelectedGames, Sides, Skip, Totals}; +use crate::i18n::{tr, trf}; + +/// What a list holds before a pass: the records already analysed, those to analyse with +/// their plies, those that cannot be, and the sides of the filter's player. +pub struct Counted { + pub reviewed: Vec, + pub left: Vec, + pub plies_left: Vec, + pub skipped: Vec<(u32, Skip)>, + pub sides: Sides, +} + +/// Counts what of `records` is analysed (the analysis cache in `cache`), on this thread. +/// The index follows: a game analysed whose entry is missing or belongs to another game +/// (one deleted or changed) gets its entry anew from the cache, a game that cannot be +/// analysed gets «—» with the reason. +pub fn count( + db: &Database, + records: &[u32], + filter: &Filter, + cache: &Path, + index: &std::sync::Mutex, + cancel: &AtomicBool, +) -> Counted { + let store = crate::review::Cache(cache.to_path_buf()); + let mut c = Counted { + reviewed: Vec::new(), + left: Vec::new(), + plies_left: Vec::new(), + skipped: Vec::new(), + sides: crate::brilliant::player_sides(db, filter, cancel), + }; + for &r in records { + if cancel.load(Ordering::Relaxed) { + break; + } + let set = |entry: crate::brilliant::Entry| { + if let Ok(mut i) = index.lock() + && i.get(r) != Some(&entry) + { + i.set(r, entry); + let _ = i.save(); + } + }; + let Some(parsed) = db.load_game(r as usize) else { + c.skipped.push((r, Skip::Unreadable)); + set(crate::brilliant::skipped_entry( + String::new(), + Skip::Unreadable, + )); + continue; + }; + let mut a = GameAnalysis::with_store(&parsed.game, Some(&store)); + if let Some(skip) = crate::brilliant::skip_of(&parsed.game, db.row(r as usize).chess960) { + c.skipped.push((r, skip)); + set(crate::brilliant::skipped_entry(a.cache_key(), skip)); + continue; + } + let by_engine = a.has_data() && a.meta.as_ref().is_some_and(|m| m.nodes > 0); + if by_engine && (a.stale() || a.missing() == 0) { + c.reviewed.push(r); + a.refresh(&parsed.game); + set(crate::brilliant::entry_of(&a, &parsed.game)); + } else { + c.left.push(r); + c.plies_left.push(parsed.game.mainline().len()); + } + } + c +} + +/// The question before a pass. +pub struct StartDialog { + pub source: PathBuf, + pub records: Vec, + pub filter: Filter, + pub about: String, + pub selected: Option, + rx: Receiver, + cancel: Arc, + pub counted: Option, +} + +pub enum StartOutcome { + Start, + /// Every game is analysed already, or «Summary of the reviewed». + Summary, + Cancel, +} + +/// One of the three fixed-height source rows: empty rows keep their place. +fn source_line(ui: &mut egui::Ui, text: &str, weak: bool, hover: Option<&str>) { + if text.is_empty() { + return; + } + let text = RichText::new(text).size(12.0); + let text = if weak { text.weak() } else { text }; + let response = ui.add(egui::Label::new(text).truncate()); + if let Some(hover) = hover { + response.on_hover_text(hover); + } +} + +impl StartDialog { + #[allow(clippy::too_many_arguments)] + pub fn new( + ctx: &egui::Context, + source: PathBuf, + db: Arc, + records: Vec, + filter: Filter, + about: String, + selected: Option, + cache: PathBuf, + index: Arc>, + ) -> StartDialog { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let (list, f, c, ctx) = (records.clone(), filter.clone(), cancel.clone(), ctx.clone()); + let _ = std::thread::Builder::new() + .name("brilliant-count".into()) + .spawn(move || { + let _ = tx.send(count(&db, &list, &f, &cache, &index, &c)); + ctx.request_repaint(); + }); + StartDialog { + source, + records, + filter, + about, + selected, + rx, + cancel, + counted: None, + } + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + if self.counted.is_none() + && let Ok(c) = self.rx.try_recv() + { + // All analysed: no question, the summary at once. + if c.left.is_empty() { + self.counted = Some(c); + return Some(StartOutcome::Summary); + } + self.counted = Some(c); + } + let mut out = None; + let name = crate::own_db::base_name(&self.source); + egui::Window::new(tr("Find great moves")) + .id(egui::Id::new("brilliant_start")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .default_width(520.0) + .show(ctx, |ui| { + ui.set_width(520.0); + let (source, hidden) = match self.selected { + Some(selected) => ( + trf( + "Selected: {games}", + &[("games", &crate::i18n::games(selected.games))], + ), + (selected.hidden > 0).then(|| { + trf( + "{k} hidden by the current filter", + &[("k", &crate::large_db::grouped(selected.hidden))], + ) + }), + ), + None => ( + format!( + "{} · {}", + crate::i18n::games(self.records.len()), + self.about + ), + None, + ), + }; + let player = (self.selected.is_some() && self.filter.player.is_set()).then(|| { + let name = self.filter.player.text.trim(); + match self.filter.side { + chess_import::chessbase::base::Side::White => trf( + "Only the moves of «{name}» as White count.", + &[("name", &name)], + ), + chess_import::chessbase::base::Side::Black => trf( + "Only the moves of «{name}» as Black count.", + &[("name", &name)], + ), + _ => trf("Only the moves of «{name}» count.", &[("name", &name)]), + } + }); + for (text, weak, hover) in [ + (format!("{name} · {source}"), true, None), + (hidden.unwrap_or_default(), true, None), + ( + player.unwrap_or_default(), + false, + self.filter.player.is_set().then(|| { + tr( + "The player condition limits the moves counted, but does not exclude selected games from review.", + ) + }), + ), + ] { + ui.allocate_ui(egui::vec2(520.0, 18.0), |ui| { + source_line(ui, &text, weak, hover); + }); + } + ui.add_space(8.0); + // Two lines kept for the counts: the window does not jump when they come. + ui.allocate_ui(egui::vec2(520.0, 60.0), |ui| match &self.counted { + None => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(tr("Counting the games already reviewed…")); + }); + } + Some(c) => { + let secs = crate::brilliant::estimate_secs( + c.plies_left.iter().copied(), + crate::review::processes(), + ); + ui.label(trf( + "The engine will review {games} — {time}.", + &[ + ("games", &crate::i18n::games_object(c.left.len())), + ("time", &crate::brilliant::format_estimate(secs)), + ], + )); + if !c.reviewed.is_empty() { + let key = if crate::i18n::is_one(c.reviewed.len()) { + "{games} is already reviewed: its marks come from the saved review." + } else { + "{games} are already reviewed: their marks come from the saved review." + }; + ui.label(trf(key, &[("games", &crate::i18n::games(c.reviewed.len()))])); + } + // Why the list here is shorter than the table's. + if !c.skipped.is_empty() { + let mut reasons: Vec<&str> = + c.skipped.iter().map(|(_, s)| s.reason()).collect(); + reasons.sort_unstable(); + reasons.dedup(); + ui.label( + RichText::new(trf( + "{k} cannot be reviewed ({reason})", + &[("k", &c.skipped.len()), ("reason", &reasons.join(", "))], + )) + .weak(), + ); + } + } + }); + ui.add_space(6.0); + ui.label(trf( + "The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept.", + &[("p", &crate::review::processes())], + )); + ui.add_space(8.0); + // Its own height, not the window's: the buttons sit under the text. + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let ready = self.counted.is_some(); + let start = ui.add_enabled(ready, egui::Button::new(tr("Start"))); + if start.clicked() || (ready && ui.input(|i| i.key_pressed(Key::Enter))) { + out = Some(StartOutcome::Start); + } + if ui.button(tr("Cancel")).clicked() { + out = Some(StartOutcome::Cancel); + } + if let Some(c) = &self.counted + && !c.reviewed.is_empty() + && ui + .button(trf( + "Summary of the reviewed ({k})", + &[("k", &c.reviewed.len())], + )) + .clicked() + { + out = Some(StartOutcome::Summary); + } + }); + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(StartOutcome::Cancel); + } + out + } +} + +impl Drop for StartDialog { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +/// A row of the summary's list: a !! move of a game. +pub struct BrilliantRow { + pub record: u32, + pub found: Found, + /// «White — Black · result · event · date». + pub game: String, +} + +/// The summary of a pass (§4.9), counted anew from the index for the pass's list. +pub struct Summary { + pub source: PathBuf, + pub about: String, + pub selected_games: Option, + pub totals: Totals, + /// The filter's player and the games counted for each colour. + pub player: Option<(String, usize, usize)>, + /// Stopped: analysed of all. + pub stopped: Option<(usize, usize)>, + /// Not analysed (for «Continue»). + pub rest: Vec, + pub skipped: Vec<(u32, Skip)>, + pub rows: Vec, + pub selected: Option, + /// The pass's filter: «Continue» goes on with it (its player's moves only). + pub filter: Filter, +} + +pub enum SummaryAction { + /// The game of a row chosen in the table behind. + Select(u32), + /// Open the game at the position after the move. + Open { + record: u32, + ply: u16, + }, + Continue { + records: Vec, + filter: Box, + }, + /// Sort the table by the «!!» column. + Sort, + Close, +} + +impl Summary { + /// The summary of `records` (a pass's list, in its order) from `index`. + #[allow(clippy::too_many_arguments)] + pub fn new( + source: &Path, + db: &Database, + index: &Index, + records: &[u32], + sides: &Sides, + filter: &Filter, + about: String, + selected: Option, + stopped: Option<(usize, usize)>, + skipped: Vec<(u32, Skip)>, + ) -> Summary { + let totals = crate::brilliant::totals(index, db, records, sides); + let rest = records + .iter() + .copied() + .filter(|r| crate::brilliant::current_entry(index, db, *r).is_none()) + .collect(); + let player = sides.player.as_ref().map(|(w, b)| { + let count = |v: &Vec| { + records + .iter() + .filter(|r| v.binary_search(r).is_ok()) + .count() + }; + (filter.player.text.trim().to_owned(), count(w), count(b)) + }); + let rows = totals + .brilliant + .iter() + .map(|(r, f)| { + let row = db.row(*r as usize); + let mut parts = vec![format!("{} — {}", row.white, row.black)]; + parts.push(row.result.to_string()); + if !row.event.trim().is_empty() && row.event != "?" { + parts.push(row.event.to_string()); + } + let date = crate::library::display_date(&row.date); + if !date.is_empty() { + parts.push(date); + } + BrilliantRow { + record: *r, + found: f.clone(), + game: parts.join(" · "), + } + }) + .collect(); + Summary { + source: source.to_path_buf(), + about, + selected_games: selected, + totals, + player, + stopped, + rest, + skipped, + rows, + selected: None, + filter: filter.clone(), + } + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + // `CP_SUMMARY_CONTINUE=1`, `CP_SUMMARY_OPEN=`: «Continue», or the i-th move of + // «Games with !!» opened, once (checks without a mouse). + static HOOK: std::sync::Once = std::sync::Once::new(); + let mut hook = None; + HOOK.call_once(|| { + if std::env::var_os("CP_SUMMARY_CONTINUE").is_some() && !self.rest.is_empty() { + hook = Some(SummaryAction::Continue { + records: self.rest.clone(), + filter: Box::new(self.filter.clone()), + }); + } else if let Some(row) = std::env::var("CP_SUMMARY_OPEN") + .ok() + .and_then(|i| i.parse::().ok()) + .and_then(|i| self.rows.get(i)) + { + hook = Some(SummaryAction::Open { + record: row.record, + ply: row.found.ply, + }); + } + }); + if hook.is_some() { + return hook; + } + let mut open = true; + let t = &self.totals; + let title = match self.stopped { + Some((i, n)) if crate::i18n::is_one(i) => trf( + "Search stopped · reviewed: {i} of {n} game", + &[("i", &i), ("n", &n)], + ), + Some((i, n)) => trf( + "Search stopped · reviewed: {i} of {n}", + &[("i", &i), ("n", &n)], + ), + None => trf( + "Summary · reviewed: {games}", + &[("games", &crate::i18n::games(t.games))], + ), + }; + let width = (ctx.content_rect().width() - 40.0).min(600.0); + egui::Window::new(title) + .id(egui::Id::new("brilliant_summary")) + // In the middle: the «!!» column it sums up stays in sight. + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .open(&mut open) + .collapsible(false) + .resizable(false) + .default_width(width) + .max_height(ctx.content_rect().height() - 80.0) + .show(ctx, |ui| { + ui.set_width(width); + let weak = |ui: &mut egui::Ui, text: String| { + ui.add(egui::Label::new(RichText::new(text).weak().size(12.0)).truncate()) + }; + let about = match self.selected_games { + Some(selected) => trf( + "Selected: {games}", + &[("games", &crate::i18n::games(selected.games))], + ), + None => self.about.clone(), + }; + let subtitle = weak( + ui, + format!("{} · {about}", crate::own_db::base_name(&self.source)), + ); + if let Some(selected) = self.selected_games + && selected.hidden > 0 + { + subtitle.on_hover_text(trf( + "Hidden by the filter at start: {k}", + &[("k", &crate::large_db::grouped(selected.hidden))], + )); + } + if let Some((name, w, b)) = &self.player { + weak( + ui, + trf( + "Only the moves of «{name}» count: as White {w}, as Black {b}", + &[("name", name), ("w", w), ("b", b)], + ), + ); + } + if !self.skipped.is_empty() { + let reasons: Vec<&str> = { + let mut r: Vec<&str> = self.skipped.iter().map(|(_, s)| s.reason()).collect(); + r.sort_unstable(); + r.dedup(); + r + }; + weak( + ui, + trf( + "Not reviewed: {k} ({reason})", + &[("k", &self.skipped.len()), ("reason", &reasons.join(", "))], + ), + ); + } + if t.stale > 0 { + weak( + ui, + trf( + "{k} of them were reviewed with the previous engine settings", + &[("k", &t.stale)], + ), + ); + } + if !t.player_missing.is_empty() { + let numbers: Vec = + t.player_missing.iter().map(|r| (r + 1).to_string()).collect(); + ui.add( + egui::Label::new( + RichText::new(trf( + "In {k} games the player was not found by name: their moves did not count", + &[("k", &t.player_missing.len())], + )) + .weak() + .size(12.0), + ) + .truncate(), + ) + .on_hover_text(numbers.join(", ")); + } + if self.stopped.is_some() && !self.rest.is_empty() { + weak( + ui, + trf( + "{k} games are not reviewed: «Continue» reviews only them", + &[("k", &self.rest.len())], + ), + ); + } + ui.add_space(8.0); + let dark = ui.visuals().dark_mode; + egui::Grid::new("brilliant_totals") + .num_columns(2) + .spacing([12.0, 4.0]) + .show(ui, |ui| { + let c = &t.counts; + for (j, n) in [ + (Judgement::Brilliant, c.brilliant), + (Judgement::Great, c.great), + (Judgement::Inaccuracy, c.inaccuracies), + (Judgement::Mistake, c.mistakes), + (Judgement::Blunder, c.blunders), + ] { + let color = if n == 0 { + ui.visuals().weak_text_color() + } else { + crate::review::judgement_text_color(j, dark) + }; + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(n.to_string()).strong().size(15.0).color(color)); + }); + ui.label( + RichText::new(crate::review::judgement_plural(j)) + .size(15.0) + .color(color), + ); + ui.end_row(); + } + let shown = |v: Option| v.unwrap_or_else(|| "—".to_owned()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label( + RichText::new(shown(t.acpl.map(|a| format!("{}", a.round() as i64)))) + .strong() + .size(15.0), + ); + }); + ui.label(RichText::new(tr("Average centipawn loss")).size(15.0)); + ui.end_row(); + let color = t + .accuracy + .map(|a| crate::review::accuracy_color(a, dark)) + .unwrap_or(ui.visuals().weak_text_color()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label( + RichText::new(shown(t.accuracy.map(|a| format!("{}%", a.round() as i64)))) + .strong() + .size(15.0) + .color(color), + ); + }); + let label = ui.label(RichText::new(tr("Average accuracy")).size(15.0)); + if let Some((lo, hi)) = t.accuracy_range { + label.on_hover_text(trf( + "Average over {k}: from {min}% to {max}%", + &[ + ("k", &crate::i18n::games(t.sides)), + ("min", &(lo.round() as i64)), + ("max", &(hi.round() as i64)), + ], + )); + } + ui.end_row(); + }); + ui.separator(); + if self.rows.is_empty() { + if t.counts.great > 0 { + ui.horizontal(|ui| { + ui.label( + RichText::new(tr( + "No brilliant moves. Games with ! — sort by the «!!» column", + )) + .weak(), + ); + if ui.link(tr("Sort")).clicked() { + out = Some(SummaryAction::Sort); + } + }); + } else { + ui.label(RichText::new(tr("No brilliant or great moves")).weak()); + } + } else { + ui.label( + RichText::new(trf("Games with !! ({n})", &[("n", &self.rows.len())])) + .strong() + .size(13.0), + ); + let teal = crate::review::judgement_text_color(Judgement::Brilliant, dark); + let labels: Vec = self.rows.iter().map(|r| r.found.label()).collect(); + let move_w = labels + .iter() + .map(|l| { + ui.fonts_mut(|f| { + f.layout_no_wrap( + l.clone(), + egui::TextStyle::Body.resolve(ui.style()), + egui::Color32::WHITE, + ) + .size() + .x + }) + }) + .fold(0.0, f32::max) + + 12.0; + let rows = if ctx.content_rect().height() < 700.0 { 3 } else { 6 }; + egui::ScrollArea::vertical() + .max_height(24.0 * rows as f32) + .auto_shrink([false, true]) + .show_rows(ui, 24.0, self.rows.len(), |ui, range| { + for i in range { + let row = &self.rows[i]; + let selected = self.selected == Some(i); + let (rect, resp) = ui.allocate_exact_size( + egui::vec2(ui.available_width(), 24.0), + egui::Sense::click(), + ); + if selected { + ui.painter().rect_filled(rect, 0.0, ui.visuals().selection.bg_fill); + } else if resp.hovered() { + ui.painter() + .rect_filled(rect, 0.0, ui.visuals().widgets.hovered.weak_bg_fill); + } + let mut child = ui.new_child( + egui::UiBuilder::new() + .max_rect(rect.shrink2(egui::vec2(4.0, 0.0))) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + ); + let color = if selected { ui.visuals().selection.stroke.color } else { teal }; + child.add_sized( + egui::vec2(move_w, 24.0), + egui::Label::new(RichText::new(&labels[i]).strong().color(color)) + .selectable(false), + ); + child.add(egui::Label::new(&row.game).truncate().selectable(false)); + if resp.clicked() { + self.selected = Some(i); + out = Some(SummaryAction::Select(row.record)); + } + if resp.double_clicked() { + out = Some(SummaryAction::Open { + record: row.record, + ply: row.found.ply, + }); + } + } + }); + ui.label( + RichText::new(tr( + "Click: choose the row in the table; double click: open at this move", + )) + .weak() + .size(12.0), + ); + // ↑ ↓ through the list, Enter opens. + let (up, down, enter) = ui.input(|i| { + ( + i.key_pressed(Key::ArrowUp), + i.key_pressed(Key::ArrowDown), + i.key_pressed(Key::Enter), + ) + }); + if up || down { + let last = self.rows.len() - 1; + let next = match (self.selected, down) { + (None, _) => 0, + (Some(s), true) => (s + 1).min(last), + (Some(s), false) => s.saturating_sub(1), + }; + self.selected = Some(next); + out = Some(SummaryAction::Select(self.rows[next].record)); + } + if enter && let Some(s) = self.selected { + out = Some(SummaryAction::Open { + record: self.rows[s].record, + ply: self.rows[s].found.ply, + }); + } + } + ui.add_space(6.0); + // Its own height, not the window's: the buttons sit under the text. + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Close")).clicked() { + out = Some(SummaryAction::Close); + } + if !self.rows.is_empty() { + let pick = self.selected.map(|s| &self.rows[s]); + if ui + .add_enabled(pick.is_some(), egui::Button::new(tr("Open game"))) + .clicked() + && let Some(r) = pick + { + out = Some(SummaryAction::Open { + record: r.record, + ply: r.found.ply, + }); + } + } + if self.stopped.is_some() + && !self.rest.is_empty() + && ui.button(tr("Continue")).clicked() + { + out = Some(SummaryAction::Continue { + records: self.rest.clone(), + filter: Box::new(self.filter.clone()), + }); + } + }); + }); + }); + if !open || (out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape))) { + out = Some(SummaryAction::Close); + } + out + } +} diff --git a/apps/desktop/src/chatgpt.rs b/apps/desktop/src/chatgpt.rs new file mode 100644 index 0000000..57d79e3 --- /dev/null +++ b/apps/desktop/src/chatgpt.rs @@ -0,0 +1,876 @@ +//! Sign in with ChatGPT: requests paid from the user's ChatGPT plan +//! (https://developers.openai.com/siwc/token-sharing-open-source). +//! +//! OAuth with PKCE in the system browser and a loopback listener on 127.0.0.1; the +//! client is registered on the first sign-in (`dynamic_agent_client`), the issued client +//! id and this installation's host id are kept in the settings, the tokens beside them +//! in `credentials.json`. Inference: the Responses API, streamed, not stored. + +use std::io::{BufRead, BufReader, Write as _}; +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; +use std::time::Duration; +use web_time::{Instant, SystemTime, UNIX_EPOCH}; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use crate::translate::{Failure, update_credentials}; +#[cfg(not(web))] +use crate::translate::{agent, with_waits}; + +const AUTHORIZE: &str = "https://auth.openai.com/api/accounts/authorize"; +const TOKEN: &str = "https://auth.openai.com/api/accounts/oauth/token"; +const DISCOVERY: &str = "https://auth.openai.com/.well-known/openid-configuration"; +const API: &str = "https://api.openai.com/v1"; +const RESOURCE: &str = "https://api.openai.com/v1"; +const SCOPES: &str = + "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct"; +/// The scope that lets requests use the plan. +const PLAN_SCOPE: &str = "chatgpt.tokens.use.direct"; +const CALLBACK_PATH: &str = "/auth/callback"; +/// Ports tried for the callback (any port works; the path must stay the same). +const PORTS: [u16; 4] = [1455, 1456, 1457, 0]; +/// How long the browser has for the sign-in. +const SIGN_IN_TIME: Duration = Duration::from_secs(10 * 60); + +#[derive(Clone, Debug, Serialize, Deserialize, Default)] +pub struct Tokens { + pub access: String, + pub refresh: String, + /// Unix seconds. + pub expires: u64, + pub scope: String, + pub client_id: String, +} + +impl Tokens { + /// The plan may be used (the user granted it at consent). + pub fn plan(&self) -> bool { + self.scope.split_whitespace().any(|s| s == PLAN_SCOPE) + } +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +fn random_bytes() -> [u8; N] { + let mut b = [0u8; N]; + // No randomness is a broken system; a weaker fallback still differs per attempt. + if getrandom::fill(&mut b).is_err() { + let t = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let h = Sha256::digest(t.to_le_bytes()); + for (i, x) in b.iter_mut().enumerate() { + *x = h[i % h.len()]; + } + } + b +} + +fn random_text() -> String { + URL_SAFE_NO_PAD.encode(random_bytes::<32>()) +} + +/// A new installation id (`urn:uuid:` with a random UUID v4). +pub fn new_host_id() -> String { + let mut b = random_bytes::<16>(); + b[6] = (b[6] & 0x0f) | 0x40; + b[8] = (b[8] & 0x3f) | 0x80; + let h: String = b.iter().map(|x| format!("{x:02x}")).collect(); + format!( + "urn:uuid:{}-{}-{}-{}-{}", + &h[0..8], + &h[8..12], + &h[12..16], + &h[16..20], + &h[20..32] + ) +} + +fn form(pairs: &[(&str, &str)]) -> String { + let mut s = form_urlencoded::Serializer::new(String::new()); + for (k, v) in pairs { + s.append_pair(k, v); + } + s.finish() +} + +/// The `email` claim of an ID token (not verified: shown only, never trusted). +fn email_of(id_token: &str) -> Option { + let payload = id_token.split('.').nth(1)?; + let bytes = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?; + let v: Value = serde_json::from_slice(&bytes).ok()?; + v.get("email").and_then(Value::as_str).map(str::to_owned) +} + +fn nonce_of(id_token: &str) -> Option { + let payload = id_token.split('.').nth(1)?; + let bytes = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?; + let v: Value = serde_json::from_slice(&bytes).ok()?; + v.get("nonce").and_then(Value::as_str).map(str::to_owned) +} + +// --- Sign-in ------------------------------------------------------------------------------- + +/// How a sign-in ended. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SignedIn { + /// Signed in with the plan usable: the account, the issued client id. + Ok { + account: String, + client_id: String, + }, + /// Signed in, but the plan usage was not granted at consent. + NoPlan { + account: String, + client_id: String, + }, + /// The user declined in the browser. + Declined, + /// The browser did not come back in time. + TimedOut, + Failed(String), +} + +pub struct SignIn { + /// The address to open (also offered for copying when no browser opens). + pub url: String, + rx: Receiver, + cancel: Arc, +} + +impl SignIn { + /// The web version does not sign in to ChatGPT (it would listen on a port). + #[cfg(web)] + pub fn start(_ctx: &egui::Context, _host_id: &str, _client_id: &str) -> Result { + Err("the web version does not sign in to ChatGPT".into()) + } + + #[cfg(not(web))] + /// Starts listening for the callback and returns the address to open in the browser. + pub fn start(ctx: &egui::Context, host_id: &str, client_id: &str) -> Result { + let listener = PORTS + .iter() + .find_map(|p| TcpListener::bind(("127.0.0.1", *p)).ok()) + .ok_or_else(|| "no free port on 127.0.0.1".to_owned())?; + let port = listener.local_addr().map_err(|e| e.to_string())?.port(); + listener.set_nonblocking(true).map_err(|e| e.to_string())?; + let redirect = format!("http://127.0.0.1:{port}{CALLBACK_PATH}"); + let verifier = random_text(); + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + let state = random_text(); + let nonce = random_text(); + let first = client_id.is_empty(); + let client = if first { + "dynamic_agent_client" + } else { + client_id + }; + let mut params = vec![ + ("client_id", client), + ("ext_agent_host_id", host_id), + ("response_type", "code"), + ("redirect_uri", redirect.as_str()), + ("scope", SCOPES), + ("resource", RESOURCE), + ("state", state.as_str()), + ("nonce", nonce.as_str()), + ("code_challenge_method", "S256"), + ("code_challenge", challenge.as_str()), + ]; + if first { + params.push(("agent_name_hint", "ChessPenguin")); + } + let url = format!("{AUTHORIZE}?{}", form(¶ms)); + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let c = cancel.clone(); + let ctx = ctx.clone(); + let client = client.to_owned(); + std::thread::Builder::new() + .name("chatgpt-sign-in".into()) + .spawn(move || { + let r = wait_for_callback(&listener, &c, &state).and_then(|(code, issued)| { + let client = issued.unwrap_or(client); + exchange(&code, &verifier, &redirect, &client, &nonce) + }); + let _ = tx.send(r.unwrap_or_else(|e| e)); + ctx.request_repaint(); + }) + .map_err(|e| e.to_string())?; + Ok(SignIn { url, rx, cancel }) + } + + pub fn poll(&self) -> Option { + self.rx.try_recv().ok() + } + + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +impl Drop for SignIn { + fn drop(&mut self) { + self.cancel(); + } +} + +#[cfg(not(web))] +/// The page the browser tab shows after the sign-in. +fn page(ok: bool) -> String { + let (title, text) = if ok { + ( + crate::i18n::tr("✔ You are signed in to ChatGPT"), + crate::i18n::tr( + "Go back to ChessPenguin — the translation goes on there. You can close this tab.", + ), + ) + } else { + ( + crate::i18n::tr("Sign-in could not be finished"), + crate::i18n::tr("Go back to ChessPenguin and try again."), + ) + }; + format!( + "ChessPenguin\ + \ +

{title}

{text}

" + ) +} + +#[cfg(not(web))] +fn reply(stream: &mut TcpStream, status: &str, body: &str) { + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); +} + +#[cfg(not(web))] +/// Waits for the browser to come back to the callback: (code, issued client id). +fn wait_for_callback( + listener: &TcpListener, + cancel: &AtomicBool, + state: &str, +) -> Result<(String, Option), SignedIn> { + let start = Instant::now(); + loop { + if cancel.load(Ordering::Relaxed) { + return Err(SignedIn::Failed("cancelled".into())); + } + if start.elapsed() > SIGN_IN_TIME { + return Err(SignedIn::TimedOut); + } + let mut stream = match listener.accept() { + Ok((s, _)) => s, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(100)); + continue; + } + Err(e) => return Err(SignedIn::Failed(e.to_string())), + }; + let _ = stream.set_nonblocking(false); + let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); + let mut line = String::new(); + if BufReader::new(&stream).read_line(&mut line).is_err() { + continue; + } + // "GET /auth/callback?code=…&state=… HTTP/1.1" + let target = line.split_whitespace().nth(1).unwrap_or(""); + let (path, query) = target.split_once('?').unwrap_or((target, "")); + if path != CALLBACK_PATH { + reply(&mut stream, "404 Not Found", ""); + continue; + } + let q: std::collections::HashMap = form_urlencoded::parse(query.as_bytes()) + .into_owned() + .collect(); + if q.get("state").map(String::as_str) != Some(state) { + reply(&mut stream, "400 Bad Request", &page(false)); + continue; + } + if let Some(err) = q.get("error") { + reply(&mut stream, "200 OK", &page(false)); + return Err(if err == "access_denied" { + SignedIn::Declined + } else { + SignedIn::Failed(format!( + "{err}: {}", + q.get("error_description").map_or("", |s| s.as_str()) + )) + }); + } + let Some(code) = q.get("code").cloned() else { + reply(&mut stream, "200 OK", &page(false)); + return Err(SignedIn::Failed("no code in the callback".into())); + }; + reply(&mut stream, "200 OK", &page(true)); + return Ok((code, q.get("client_id").cloned())); + } +} + +#[cfg(not(web))] +fn token_request(body: &str) -> Result { + let mut resp = agent(Duration::from_secs(30)) + .post(TOKEN) + .header("Content-Type", "application/x-www-form-urlencoded") + .send(body) + .map_err(|e| (0, e.to_string()))?; + let status = resp.status().as_u16(); + let text = resp.body_mut().read_to_string().unwrap_or_default(); + if status != 200 { + return Err((status, text)); + } + serde_json::from_str(&text).map_err(|e| (status, e.to_string())) +} + +fn tokens_from(v: &Value, client_id: &str, old_refresh: &str) -> Tokens { + let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_owned(); + let refresh = s("refresh_token"); + Tokens { + access: s("access_token"), + refresh: if refresh.is_empty() { + old_refresh.to_owned() + } else { + refresh + }, + expires: now() + v.get("expires_in").and_then(Value::as_u64).unwrap_or(3600), + scope: s("scope"), + client_id: client_id.to_owned(), + } +} + +#[cfg(not(web))] +fn exchange( + code: &str, + verifier: &str, + redirect: &str, + client_id: &str, + nonce: &str, +) -> Result { + let body = form(&[ + ("grant_type", "authorization_code"), + ("client_id", client_id), + ("code", code), + ("code_verifier", verifier), + ("redirect_uri", redirect), + ("resource", RESOURCE), + ]); + let v = token_request(&body) + .map_err(|(status, e)| SignedIn::Failed(format!("token exchange: {status} {e}")))?; + let id_token = v.get("id_token").and_then(Value::as_str).unwrap_or(""); + if let Some(n) = nonce_of(id_token) + && n != nonce + { + return Err(SignedIn::Failed( + "the sign-in answer is not for this request".into(), + )); + } + let tokens = tokens_from(&v, client_id, ""); + if tokens.access.is_empty() { + return Err(SignedIn::Failed("no access token".into())); + } + let account = email_of(id_token).unwrap_or_default(); + let plan = tokens.plan(); + update_credentials(|c| c.chatgpt = Some(tokens)); + let client_id = client_id.to_owned(); + Ok(if plan { + SignedIn::Ok { account, client_id } + } else { + SignedIn::NoPlan { account, client_id } + }) +} + +#[cfg(not(web))] +/// Refreshes are one at a time: the refresh token rotates. +static REFRESH: Mutex<()> = Mutex::new(()); + +#[cfg(not(web))] +/// A valid access token, refreshed when it is about to expire. +fn access_token() -> Result { + let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner()); + let Some(t) = crate::translate::credentials().chatgpt else { + return Err(Failure::SignedOut); + }; + if !t.plan() { + return Err(Failure::NotEligible("plan usage not granted".into())); + } + if t.expires > now() + 120 { + return Ok(t.access); + } + refresh(&t) +} + +#[cfg(not(web))] +fn refresh(t: &Tokens) -> Result { + let body = form(&[ + ("grant_type", "refresh_token"), + ("client_id", &t.client_id), + ("refresh_token", &t.refresh), + ("resource", RESOURCE), + ]); + match token_request(&body) { + Ok(v) => { + let new = tokens_from(&v, &t.client_id, &t.refresh); + let access = new.access.clone(); + // The scope may be omitted on refresh: the grant stays. + let new = Tokens { + scope: if new.scope.is_empty() { + t.scope.clone() + } else { + new.scope + }, + ..new + }; + // Signed out meanwhile: the new tokens are not kept. + update_credentials(|c| { + if c.chatgpt.as_ref().is_some_and(|x| x.refresh == t.refresh) { + c.chatgpt = Some(new); + } + }); + Ok(access) + } + Err((0, e)) => Err(Failure::Offline(e)), + Err((status, body)) => { + let terminal = [ + "invalid_grant", + "invalid_refresh_token", + "token_expired", + "refresh_token_expired", + "refresh_token_invalidated", + "refresh_token_reused", + ]; + if (400..500).contains(&status) && terminal.iter().any(|c| body.contains(c)) { + // Only this sign-in is over (not a newer one made meanwhile). + update_credentials(|c| { + if c.chatgpt.as_ref().is_some_and(|x| x.refresh == t.refresh) { + c.chatgpt = None; + } + }); + Err(Failure::SignedOut) + } else { + Err(Failure::Service(status, body.chars().take(300).collect())) + } + } + } +} + +/// Signs out: the tokens are forgotten at once, the refresh token is revoked at OpenAI +/// in the background (if that fails, the user can disconnect the app in ChatGPT's +/// settings — the link is beside the button). +pub fn sign_out() { + let Some(t) = crate::translate::credentials().chatgpt else { + return; + }; + update_credentials(|c| c.chatgpt = None); + #[cfg(not(web))] + let _ = std::thread::Builder::new() + .name("chatgpt-sign-out".into()) + .spawn(move || revoke(&t)); + #[cfg(web)] + let _ = t; +} + +#[cfg(not(web))] +fn revoke(t: &Tokens) -> bool { + let body = form(&[ + ("token", &t.refresh), + ("token_type_hint", "refresh_token"), + ("client_id", &t.client_id), + ]); + // The revocation address is published in the OpenID configuration. + let revoke = agent(Duration::from_secs(20)) + .get(DISCOVERY) + .call() + .ok() + .and_then(|mut r| r.body_mut().read_to_string().ok()) + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| v.get("revocation_endpoint")?.as_str().map(str::to_owned)); + revoke.is_some_and(|url| { + agent(Duration::from_secs(20)) + .post(&url) + .header("Content-Type", "application/x-www-form-urlencoded") + .send(&body) + .is_ok_and(|r| r.status().as_u16() == 200) + }) +} + +// --- Requests ------------------------------------------------------------------------------ + +#[cfg(web)] +pub fn models() -> Result, Failure> { + Err(crate::translate::no_requests()) +} + +#[cfg(web)] +pub fn respond( + _model: &str, + _system: &str, + _user: &str, + _cancel: &AtomicBool, +) -> Result { + Err(crate::translate::no_requests()) +} + +#[cfg(not(web))] +/// The models this account may use (`visibility: list`). +pub fn models() -> Result, Failure> { + let token = access_token()?; + let mut resp = agent(Duration::from_secs(30)) + .get(format!("{API}/models")) + .header("Authorization", format!("Bearer {token}")) + .call() + .map_err(|e| Failure::Offline(e.to_string()))?; + let status = resp.status().as_u16(); + let body = resp.body_mut().read_to_string().unwrap_or_default(); + if status != 200 { + return Err(failure(status, &body)); + } + let v: Value = + serde_json::from_str(&body).map_err(|e| Failure::Service(status, e.to_string()))?; + Ok(model_list(&v)) +} + +/// The listed models, OpenAI's preferred first. The plan's answer is +/// `{"models": [{"slug", "visibility", "priority", "supported_in_api"}]}`; the API's +/// usual `{"data": [{"id"}]}` is read too. +fn model_list(v: &Value) -> Vec { + let mut found: Vec<(i64, String)> = Vec::new(); + for (key, name) in [("models", "slug"), ("data", "id")] { + for m in v.get(key).and_then(Value::as_array).into_iter().flatten() { + let listed = m + .get("visibility") + .and_then(Value::as_str) + .is_none_or(|s| s == "list"); + let api = m + .get("supported_in_api") + .and_then(Value::as_bool) + .unwrap_or(true); + if let (true, true, Some(id)) = (listed, api, m.get(name).and_then(Value::as_str)) { + let priority = m + .get("priority") + .and_then(Value::as_i64) + .unwrap_or(i64::MAX); + found.push((priority, id.to_owned())); + } + } + } + found.sort_by_key(|(p, _)| *p); + found.into_iter().map(|(_, id)| id).collect() +} + +/// The model to start with: a small fast one if listed (translation needs no more). +pub fn default_model(models: &[String]) -> Option { + // OpenAI's preferred chat model (the list comes in its order); models for other + // work (code review, search, sound, pictures) do not take a plain text request. + const OTHER: [&str; 12] = [ + "codex", + "search", + "research", + "audio", + "realtime", + "image", + "tts", + "transcribe", + "embedding", + "moderation", + "computer", + "review", + ]; + models + .iter() + .find(|m| { + let m = m.to_lowercase(); + !OTHER.iter().any(|w| m.contains(w)) + }) + .or_else(|| models.first()) + .cloned() +} + +fn failure(status: u16, body: &str) -> Failure { + let v: Option = serde_json::from_str(body).ok(); + let code = v + .as_ref() + .and_then(|v| v.pointer("/error/code")) + .and_then(Value::as_str) + .unwrap_or(""); + let message = v + .as_ref() + .and_then(|v| v.pointer("/error/message").or_else(|| v.get("detail"))) + .and_then(Value::as_str) + .unwrap_or(body) + .chars() + .take(300) + .collect::(); + match code { + "subscription_sharing_usage_limit_exceeded" => Failure::PlanLimit, + "subscription_sharing_user_not_eligible" => Failure::NotEligible(message), + "subscription_sharing_invalid_user" => Failure::SignedOut, + "subscription_sharing_usage_unavailable" | "subscription_sharing_user_unavailable" => { + Failure::Service(503, message) + } + _ => match status { + 401 => Failure::SignedOut, + 403 => Failure::NotEligible(message), + 429 => Failure::RateLimited, + _ => Failure::Service(status, message), + }, + } +} + +#[cfg(not(web))] +/// One answer of the model, read from the event stream. +pub fn respond( + model: &str, + system: &str, + user: &str, + cancel: &AtomicBool, +) -> Result { + let mut body = json!({ + "model": model, + "instructions": system, + "input": [{"role": "user", "content": [{"type": "input_text", "text": user}]}], + "store": false, + "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. + "reasoning": {"effort": "low"}, + }); + let mut refreshed = false; + with_waits(cancel, || { + loop { + let token = access_token()?; + let resp = agent(Duration::from_secs(300)) + .post(format!("{API}/responses")) + .header("Authorization", format!("Bearer {token}")) + .header("Content-Type", "application/json") + .header("Accept", "text/event-stream") + .send(&body.to_string()) + .map_err(|e| Failure::Offline(e.to_string()))?; + let status = resp.status().as_u16(); + if status == 401 && !refreshed { + // The token may have been revoked or expired early: refresh once. + refreshed = true; + let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner()); + // Read under the lock: another request may have refreshed already. + if let Some(t) = crate::translate::credentials().chatgpt + && t.access == token + { + refresh(&t)?; + } + continue; + } + if status != 200 { + let mut resp = resp; + 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 read_stream(BufReader::new(resp.into_body().into_reader()), cancel); + } + }) +} + +#[cfg(not(web))] +/// The text of a Responses event stream: the deltas until `response.completed`. +fn read_stream(reader: impl BufRead, cancel: &AtomicBool) -> Result { + let mut text = String::new(); + for line in reader.lines() { + if cancel.load(Ordering::Relaxed) { + return Err(Failure::Offline("cancelled".into())); + } + let line = line.map_err(|e| Failure::Offline(e.to_string()))?; + let Some(data) = line.strip_prefix("data:") else { + continue; + }; + let data = data.trim(); + if data == "[DONE]" { + break; + } + let Ok(v) = serde_json::from_str::(data) else { + continue; + }; + match v.get("type").and_then(Value::as_str).unwrap_or("") { + "response.output_text.delta" => { + if let Some(d) = v.get("delta").and_then(Value::as_str) { + text.push_str(d); + } + } + "response.completed" => return Ok(text), + "response.failed" | "error" => { + let err = v + .pointer("/response/error") + .or_else(|| v.get("error")) + .cloned() + .unwrap_or(Value::Null); + return Err(failure(0, &json!({ "error": err }).to_string())); + } + "response.incomplete" => { + return Err(Failure::Service(0, "the answer was cut short".into())); + } + _ => {} + } + } + Err(Failure::Offline("the answer stream ended early".into())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Read as _; + + #[test] + fn host_ids_are_uuid_urns() { + let id = new_host_id(); + assert!(id.starts_with("urn:uuid:"), "{id}"); + let u = &id[9..]; + assert_eq!(u.len(), 36); + assert_eq!(&u[14..15], "4"); + assert_ne!(new_host_id(), id); + } + + #[test] + fn a_stream_gives_its_text() { + let s = "event: response.created\ndata: {\"type\":\"response.created\"}\n\n\ + data: {\"type\":\"response.output_text.delta\",\"delta\":\"{\\\"translations\\\"\"}\n\n\ + data: {\"type\":\"response.output_text.delta\",\"delta\":\": []}\"}\n\n\ + data: {\"type\":\"response.completed\",\"response\":{}}\n\n"; + let never = AtomicBool::new(false); + assert_eq!( + read_stream(s.as_bytes(), &never).unwrap(), + "{\"translations\": []}" + ); + } + + #[test] + fn a_used_up_limit_is_told_apart() { + let s = "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"subscription_sharing_usage_limit_exceeded\",\"message\":\"limit\"}}}\n\n"; + let never = AtomicBool::new(false); + assert_eq!(read_stream(s.as_bytes(), &never), Err(Failure::PlanLimit)); + assert_eq!( + failure( + 403, + r#"{"error":{"code":"subscription_sharing_user_not_eligible","message":"free plan"}}"# + ), + Failure::NotEligible("free plan".into()) + ); + assert_eq!(failure(401, r#"{"detail":"bad"}"#), Failure::SignedOut); + } + + #[test] + fn a_cut_stream_is_not_an_answer() { + let s = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"half\"}\n\n"; + let never = AtomicBool::new(false); + assert!(read_stream(s.as_bytes(), &never).is_err()); + } + + #[test] + fn the_email_is_read_from_the_id_token() { + let payload = URL_SAFE_NO_PAD.encode(br#"{"email":"a@b.c","nonce":"n1"}"#); + let t = format!("x.{payload}.y"); + assert_eq!(email_of(&t).as_deref(), Some("a@b.c")); + assert_eq!(nonce_of(&t).as_deref(), Some("n1")); + } + + #[test] + fn the_plan_model_list_is_read() { + // The shape the plan's /v1/models answers with (seen 2026-10-21). + let v: Value = serde_json::from_str( + r#"{"models": [ + {"slug": "gpt-6-luna", "visibility": "list", "priority": 5, "supported_in_api": true}, + {"slug": "codex-auto-review", "visibility": "hide", "priority": 0, "supported_in_api": true}, + {"slug": "gpt-6.1-sol", "visibility": "list", "priority": 1, "supported_in_api": true}, + {"slug": "gpt-reserve", "visibility": "hide", "priority": 3} + ]}"#, + ) + .unwrap(); + let list = model_list(&v); + assert_eq!(list, vec!["gpt-6.1-sol", "gpt-6-luna"]); + assert_eq!(default_model(&list).as_deref(), Some("gpt-6.1-sol")); + let api: Value = serde_json::from_str(r#"{"data": [{"id": "gpt-x"}]}"#).unwrap(); + assert_eq!(model_list(&api), vec!["gpt-x"]); + let m = |v: &[&str]| default_model(&v.iter().map(|s| s.to_string()).collect::>()); + assert_eq!( + m(&["gpt-6.1-codex", "gpt-6.1-sol"]), + Some("gpt-6.1-sol".into()) + ); + assert_eq!(m(&[]), None); + } + + #[test] + fn the_plan_scope_is_checked() { + let t = Tokens { + scope: "openid email chatgpt.tokens.use.direct".into(), + ..Default::default() + }; + assert!(t.plan()); + assert!(!Tokens::default().plan()); + } + + #[test] + fn the_callback_brings_the_code() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + listener.set_nonblocking(true).unwrap(); + let port = listener.local_addr().unwrap().port(); + let browser = std::thread::spawn(move || { + let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap(); + write!( + s, + "GET /auth/callback?code=abc&state=st&client_id=oaiapp_1 HTTP/1.1\r\nHost: x\r\n\r\n" + ) + .unwrap(); + let mut answer = String::new(); + let _ = s.read_to_string(&mut answer); + answer + }); + let never = AtomicBool::new(false); + let got = wait_for_callback(&listener, &never, "st").unwrap(); + assert_eq!(got, ("abc".to_string(), Some("oaiapp_1".to_string()))); + assert!(browser.join().unwrap().starts_with("HTTP/1.1 200")); + } + + #[test] + fn a_declined_consent_is_told_apart() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + listener.set_nonblocking(true).unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap(); + write!( + s, + "GET /auth/callback?error=access_denied&state=st HTTP/1.1\r\n\r\n" + ) + .unwrap(); + let mut a = String::new(); + let _ = s.read_to_string(&mut a); + }); + let never = AtomicBool::new(false); + assert_eq!( + wait_for_callback(&listener, &never, "st"), + Err(SignedIn::Declined) + ); + } +} diff --git a/apps/desktop/src/db_counts.rs b/apps/desktop/src/db_counts.rs new file mode 100644 index 0000000..fe9ee57 --- /dev/null +++ b/apps/desktop/src/db_counts.rs @@ -0,0 +1,294 @@ +//! 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>>, + /// `None`: for this run only. + file: Option, + ctx: egui::Context, +} + +impl Counter { + /// What the job leaves to do: a file to read, or nothing (its count is known now). + fn take(&self, job: Job) -> Option { + let (path, known) = match job { + Job::Count(p) => (p, None), + Job::Known(p, c) => (p, Some(c)), + }; + let stamp = stamp(&path)?; + let fresh = self.known.lock().ok().and_then(|k| { + k.get(&path) + .filter(|e| (e.size, e.modified) == stamp) + .map(|e| e.count) + }); + match known { + Some(c) if fresh == Some(c) => None, + Some(c) => { + self.record(path, stamp, c); + None + } + None if fresh.is_some() => None, + None => Some(ToCount(path, stamp)), + } + } + + fn record(&self, path: PathBuf, (size, modified): (u64, u64), count: Count) { + let json = match self.known.lock() { + Ok(mut k) => { + k.insert( + path, + Entry { + size, + modified, + count, + }, + ); + serde_json::to_vec(&*k).ok() + } + Err(_) => return, + }; + if let (Some(f), Some(json)) = (&self.file, json) { + let _ = crate::platform::fs::write_atomic(f, &json); + } + self.ctx.request_repaint(); + } + + /// Counts the files of the jobs, one after another, on a thread of its own. + #[cfg(not(web))] + fn start(self, jobs: Receiver) -> bool { + let spawned = std::thread::Builder::new() + .name("db-counts".into()) + .spawn(move || { + let never = std::sync::atomic::AtomicBool::new(false); + for job in jobs { + let Some(ToCount(path, stamp)) = self.take(job) else { + continue; + }; + // The card says why it cannot be read when the database is opened. + if let Ok(o) = chess_import::open(&path, &mut |_| {}, &never) { + self.record(path, stamp, Count::of(&o.db)); + } + } + }); + spawned.is_ok() + } + + /// Counts the files of the jobs, one after another, in the page's reader: the next + /// once the last is answered ([`Counts`] calls [`Counter::next`] after each job). + #[cfg(web)] + fn start(self, jobs: Receiver) -> bool { + WEB.with_borrow_mut(|w| { + *w = Some(Web { + counter: self, + jobs, + busy: false, + }) + }); + true + } + + #[cfg(web)] + fn next() { + let read = WEB.with_borrow_mut(|w| { + let w = w.as_mut()?; + if w.busy { + return None; + } + while let Ok(job) = w.jobs.try_recv() { + if let Some(to_count) = w.counter.take(job) { + w.busy = true; + return Some((w.counter.clone(), to_count)); + } + } + None + }); + let Some((counter, ToCount(path, stamp))) = read else { + return; + }; + crate::platform::web::import::count(&path.clone(), move |games| { + if let Some(games) = games { + let locked = false; + counter.record(path, stamp, Count { games, locked }); + } + WEB.with_borrow_mut(|w| { + if let Some(w) = w.as_mut() { + w.busy = false; + } + }); + Counter::next(); + }); + } +} + +/// The counting of the page: the jobs not taken yet, and whether a file is being read. +#[cfg(web)] +struct Web { + counter: Counter, + jobs: Receiver, + busy: bool, +} + +#[cfg(web)] +thread_local! { + static WEB: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +pub struct Counts { + known: Arc>>, + asked: HashSet, + jobs: Option>, +} + +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, ctx: &egui::Context) -> Self { + let known: HashMap = 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::(); + 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 { + 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); + } +} diff --git a/apps/desktop/src/engine_download.rs b/apps/desktop/src/engine_download.rs new file mode 100644 index 0000000..45dc123 --- /dev/null +++ b/apps/desktop/src/engine_download.rs @@ -0,0 +1,572 @@ +//! Downloading the official Stockfish on request (decision 14): the "universal" build of +//! a pinned release from github.com/official-stockfish/Stockfish, checked against its +//! SHA-256 before use and unpacked into the user's data directory. Nothing is downloaded +//! without the user asking. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +use sha2::{Digest, Sha256}; + +/// The release offered; keep in step with `packaging/stockfish.sh` (Flatpak bundles it). +const TAG: &str = "sf_19"; + +/// An archive of the release for this platform. +pub struct Asset { + pub file: &'static str, + pub sha256: &'static str, + /// Bytes, for the size shown before the download. + pub size: u64, + pub zip: bool, +} + +fn asset() -> Option { + let (file, sha256, size, zip) = match (std::env::consts::OS, std::env::consts::ARCH) { + ("linux", "x86_64") => ( + "stockfish-linux-x86-64-universal.tar.gz", + "9defc0d4e55d49c65a6d042f3e571a39fcea499ade6dbe741b53b8c65e03611f", + 81_388_977, + false, + ), + ("linux", "aarch64") => ( + "stockfish-linux-arm64-universal.tar.gz", + "fe26cfd1d9db4c8af3d21e24d9ff34cacb31c1f940085a7583da11796f2bac01", + 80_181_250, + false, + ), + ("macos", _) => ( + "stockfish-macos-universal.tar.gz", + "a1f0e3bcc5a6927a11fe6fc8e54a779754645f3c2bae2cf13420fd1957adaa77", + 82_323_876, + false, + ), + ("windows", "x86_64") => ( + "stockfish-windows-x86-64-universal.zip", + "3c8bf1f9ea66a09350a40df4f632288285ac206d99f33ab5842c408fc30b48a7", + 81_431_614, + true, + ), + ("windows", "aarch64") => ( + "stockfish-windows-arm64-universal.zip", + "8372ad3f0d7276deb2c70f801f541ec7db463219fc6d9c7592864e542aa4f401", + 80_190_536, + true, + ), + _ => return None, + }; + Some(Asset { + file, + sha256, + size, + zip, + }) +} + +/// Whether a download is offered on this platform at all. +pub fn available() -> bool { + cfg!(web) || asset().is_some() +} + +/// Size of the download in megabytes (rounded), for the offer. +pub fn size_mb() -> u64 { + #[cfg(web)] + return crate::platform::web::engine::DOWNLOAD_MB; + #[cfg(not(web))] + asset().map_or(0, |a| a.size.div_ceil(1_000_000)) +} + +#[cfg(windows)] +const EXE: &str = "stockfish.exe"; +#[cfg(not(windows))] +const EXE: &str = "stockfish"; + +/// Where the downloaded engine lives: `/engines/sf_19/` (on Windows +/// the local, not the roaming, profile). +fn dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("engines").join(TAG)) +} + +/// Removes what an interrupted download left (the program was closed meanwhile). +pub fn clean_leftovers() { + let Some(entries) = dir().and_then(|d| std::fs::read_dir(d).ok()) else { + return; + }; + for e in entries.flatten() { + if e.path().extension().is_some_and(|x| x == "part") { + let _ = std::fs::remove_file(e.path()); + } + } +} + +/// The downloaded engine, if it is there. +pub fn installed() -> Option { + #[cfg(web)] + return crate::platform::web::engine::worker_script() + .map(crate::engines::EngineLocation::Worker); + #[cfg(not(web))] + { + let p = dir()?.join(EXE); + p.is_file() + .then_some(crate::engines::EngineLocation::Program(p)) + } +} + +/// The size of the downloaded engine, in MB (0 when it is not there). +pub fn installed_mb() -> u64 { + #[cfg(web)] + return if crate::platform::web::engine::ready() { + crate::platform::web::engine::WASM_BYTES / 1_000_000 + } else { + 0 + }; + #[cfg(not(web))] + dir() + .and_then(|d| std::fs::metadata(d.join(EXE)).ok()) + .map_or(0, |m| m.len() / 1_000_000) +} + +/// Removes the downloaded engine (frees its space). +pub fn remove() -> std::io::Result<()> { + #[cfg(web)] + { + crate::platform::web::engine::remove(); + Ok(()) + } + #[cfg(not(web))] + match dir() { + Some(d) if d.exists() => std::fs::remove_dir_all(d), + _ => Ok(()), + } +} + +/// What went wrong, in terms of what the user can do about it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Failure { + /// No connection, or the connection broke. + Network(String), + /// The server answered with an error status. + Server(u16), + /// The engine was installed but does not start on this computer. + Broken, + /// The file is not the published one (damaged on the way or replaced). + Checksum, + /// Writing to the disk failed (space, permissions). + Disk(String), + /// No download for this platform. + Unsupported, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Stage { + Downloading { done: u64, total: u64 }, + Unpacking, + Done(PathBuf), + Failed(Failure), + Cancelled, +} + +/// What a download thread does: reports its stages, stops when told; the file in the end. +pub type Job = fn(&dyn Fn(Stage), &AtomicBool) -> Result; + +/// A download running in a background thread. +pub struct Download { + stage: Arc>, + cancel: Arc, +} + +impl Download { + #[cfg(not(web))] + pub fn start(ctx: &egui::Context) -> Download { + let total = asset().map_or(0, |a| a.size); + Download::spawn(ctx, total, run) + } + + /// The browser's engine: Stockfish 19 in WebAssembly from our site, into the + /// browser's cache (`platform::web::engine`). + #[cfg(web)] + pub fn start(ctx: &egui::Context) -> Download { + use crate::platform::web::engine::{self, Fetch}; + let total = engine::WASM_BYTES; + let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0, total })); + let cancel = Arc::new(AtomicBool::new(false)); + let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone()); + wasm_bindgen_futures::spawn_local(async move { + let report = |st: Stage| { + if let Ok(mut g) = s.lock() { + *g = st; + } + ctx.request_repaint(); + }; + let end = + match engine::download(|done, total| report(Stage::Downloading { done, total }), c) + .await + { + // The engine's file: its worker's script. + Ok(()) => Stage::Done(PathBuf::from(engine::SCRIPT)), + Err(Fetch::Cancelled) => Stage::Cancelled, + Err(Fetch::Network(e)) => Stage::Failed(Failure::Network(e)), + Err(Fetch::Server(code)) => Stage::Failed(Failure::Server(code)), + Err(Fetch::Checksum) => Stage::Failed(Failure::Checksum), + Err(Fetch::Storage(e)) => Stage::Failed(Failure::Disk(e)), + }; + report(end); + }); + Download { stage, cancel } + } + + /// The download of a platform that has none (Rodent and the like in a browser). + #[cfg(web)] + pub fn unsupported() -> Download { + Download { + stage: Arc::new(Mutex::new(Stage::Failed(Failure::Unsupported))), + cancel: Arc::new(AtomicBool::new(false)), + } + } + + /// Runs `job` (a download and what follows it) in a thread of its own; `total`: the + /// bytes expected, shown until the server says. + pub fn spawn(ctx: &egui::Context, total: u64, job: Job) -> Download { + 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()); + let spawned = std::thread::Builder::new() + .name("engine-download".into()) + .spawn(move || { + let report = |st: Stage| { + if let Ok(mut g) = s.lock() { + *g = st; + } + ctx.request_repaint(); + }; + let end = match job(&report, &c) { + Ok(path) => Stage::Done(path), + Err(_) if c.load(Ordering::Relaxed) => Stage::Cancelled, + Err(f) => Stage::Failed(f), + }; + report(end); + }); + if spawned.is_err() + && let Ok(mut g) = stage.lock() + { + *g = Stage::Failed(Failure::Disk("cannot start a thread".into())); + } + Download { stage, cancel } + } + + pub fn stage(&self) -> Stage { + self.stage + .lock() + .map(|g| g.clone()) + .unwrap_or(Stage::Cancelled) + } + + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + + pub fn running(&self) -> bool { + matches!(self.stage(), Stage::Downloading { .. } | Stage::Unpacking) + } +} + +impl Drop for Download { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +#[cfg(not(web))] +fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { + let asset = asset().ok_or(Failure::Unsupported)?; + let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; + std::fs::create_dir_all(&dir).map_err(disk)?; + let archive = dir.join(format!("{}.part", asset.file)); + let url = format!( + "https://github.com/official-stockfish/Stockfish/releases/download/{TAG}/{}", + asset.file + ); + let result = fetch(&url, &archive, &asset, report, cancel) + .and_then(|()| { + report(Stage::Unpacking); + unpack(&archive, &dir, asset.zip) + }) + .and_then(|exe| check_runs(&exe).map(|()| exe)); + let _ = std::fs::remove_file(&archive); + if result.is_err() { + // Nothing half-installed is left behind. + let _ = std::fs::remove_file(dir.join(EXE)); + } + result +} + +#[cfg(not(web))] +/// Downloads `url` into `to`, checking the size and the SHA-256 on the way. The file is +/// written beside and put in place once checked: a new file, never the old one rewritten +/// (macOS on Apple silicon kills an executable rewritten in place after it once ran: it +/// keeps the old signature for that file). +pub fn fetch( + url: &str, + to: &Path, + asset: &Asset, + report: &dyn Fn(Stage), + cancel: &AtomicBool, +) -> Result<(), Failure> { + let mut part = to.as_os_str().to_owned(); + part.push(".part"); + let part = PathBuf::from(part); + let result = fetch_into(url, &part, asset, report, cancel) + .and_then(|()| std::fs::rename(&part, to).map_err(disk)); + if result.is_err() { + let _ = std::fs::remove_file(&part); + } + result +} + +#[cfg(not(web))] +fn fetch_into( + url: &str, + to: &Path, + asset: &Asset, + report: &dyn Fn(Stage), + cancel: &AtomicBool, +) -> Result<(), Failure> { + let mut response = ureq::get(url).call().map_err(|e| match e { + ureq::Error::StatusCode(code) => Failure::Server(code), + e => Failure::Network(e.to_string()), + })?; + let total = response + .headers() + .get("content-length") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(asset.size); + let mut body = response + .body_mut() + .with_config() + .limit(asset.size + 1) + .reader(); + let mut file = std::fs::File::create(to).map_err(disk)?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + let mut done = 0u64; + let mut reported = 0u64; + loop { + if cancel.load(Ordering::Relaxed) { + return Err(Failure::Network("cancelled".into())); + } + let n = body + .read(&mut buf) + .map_err(|e| Failure::Network(e.to_string()))?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]).map_err(disk)?; + done += n as u64; + if done - reported >= 512 * 1024 { + reported = done; + report(Stage::Downloading { done, total }); + } + } + file.sync_all().map_err(disk)?; + if done != asset.size || hex(hasher) != asset.sha256 { + return Err(Failure::Checksum); + } + Ok(()) +} + +fn hex(hasher: Sha256) -> String { + hasher + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Whether the file is there already as the asset is (a folder of an older build: only +/// what changed is downloaded again). +pub fn already(file: &Path, asset: &Asset) -> bool { + let Ok(mut f) = std::fs::File::open(file) else { + return false; + }; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + loop { + match f.read(&mut buf) { + Ok(0) => return hex(hasher) == asset.sha256, + Ok(n) => hasher.update(&buf[..n]), + Err(_) => return false, + } + } +} + +/// Takes the engine executable and its license files out of the archive. +#[cfg(not(web))] +fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result { + let exe = dir.join(EXE); + let wanted = |name: &str| -> Option { + let base = name.rsplit(['/', '\\']).next().unwrap_or(name); + if base.starts_with("stockfish") && (base.ends_with(".exe") || !base.contains('.')) { + Some(exe.clone()) + } else if base == "Copying.txt" || base == "AUTHORS" { + Some(dir.join(base)) + } else { + None + } + }; + let file = std::fs::File::open(archive).map_err(disk)?; + if zip { + let mut z = zip::ZipArchive::new(file).map_err(|e| Failure::Disk(e.to_string()))?; + for i in 0..z.len() { + let mut entry = z.by_index(i).map_err(|e| Failure::Disk(e.to_string()))?; + if !entry.is_file() { + continue; + } + let name = entry + .name() + .map_err(|e| Failure::Disk(e.to_string()))? + .into_owned(); + if let Some(dest) = wanted(&name) { + let mut out = std::fs::File::create(&dest).map_err(disk)?; + std::io::copy(&mut entry, &mut out).map_err(disk)?; + } + } + } else { + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file)); + for entry in tar.entries().map_err(disk)? { + let mut entry = entry.map_err(disk)?; + if !entry.header().entry_type().is_file() { + continue; + } + let name = entry.path().map_err(disk)?.to_string_lossy().into_owned(); + if let Some(dest) = wanted(&name) { + let mut out = std::fs::File::create(&dest).map_err(disk)?; + std::io::copy(&mut entry, &mut out).map_err(disk)?; + } + } + } + if !exe.is_file() { + return Err(Failure::Disk("no engine in the archive".into())); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).map_err(disk)?; + } + Ok(exe) +} + +#[cfg(not(web))] +/// Starts the engine once and waits for its name: the binary runs on this computer. +fn check_runs(exe: &Path) -> Result<(), Failure> { + let mut cmd = std::process::Command::new(exe); + cmd.arg("quit"); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // No console window. + cmd.creation_flags(0x0800_0000); + } + let out = cmd.output().map_err(|_| Failure::Broken)?; + if String::from_utf8_lossy(&out.stdout).contains("Stockfish") { + Ok(()) + } else { + Err(Failure::Broken) + } +} + +pub fn disk(e: std::io::Error) -> Failure { + Failure::Disk(e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_file_already_there_is_known_by_its_checksum() { + let dir = std::env::temp_dir().join(format!("cp-already-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("book.bin"); + std::fs::write(&file, b"abc").unwrap(); + let mut asset = Asset { + file: "book.bin", + // SHA-256 of «abc». + sha256: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + size: 3, + zip: false, + }; + assert!(already(&file, &asset)); + asset.sha256 = "0000000000000000000000000000000000000000000000000000000000000000"; + assert!(!already(&file, &asset)); + assert!(!already(&dir.join("missing.bin"), &asset)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn this_platform_has_a_pinned_download() { + if cfg!(all(target_os = "linux", target_arch = "x86_64")) { + let a = asset().expect("asset"); + assert_eq!(a.sha256.len(), 64); + assert!(!a.zip); + assert_eq!(size_mb(), 82); + } + } + + /// Downloads the real release (≈ 80 MB): `XDG_DATA_HOME=… cargo test -- --ignored`. + #[test] + #[ignore] + fn downloads_the_real_engine() { + let ctx = egui::Context::default(); + let d = Download::start(&ctx); + while d.running() { + std::thread::sleep(std::time::Duration::from_millis(200)); + } + let Stage::Done(exe) = d.stage() else { + panic!("{:?}", d.stage()); + }; + let out = std::process::Command::new(&exe) + .arg("quit") + .output() + .expect("runs"); + assert!(String::from_utf8_lossy(&out.stdout).contains("Stockfish")); + assert_eq!( + installed(), + Some(crate::engines::EngineLocation::Program(exe)) + ); + } + + #[test] + fn unpacks_the_engine_and_licenses_from_a_tarball() { + let dir = std::env::temp_dir().join(format!("cp-sf-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let archive = dir.join("a.tar.gz"); + { + let gz = flate2::write::GzEncoder::new( + std::fs::File::create(&archive).unwrap(), + flate2::Compression::fast(), + ); + let mut b = tar::Builder::new(gz); + for (name, data) in [ + ("stockfish/stockfish-linux-x86-64-universal", &b"engine"[..]), + ("stockfish/Copying.txt", b"GPL"), + ("stockfish/README.md", b"x"), + ] { + let mut h = tar::Header::new_gnu(); + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_cksum(); + b.append_data(&mut h, name, data).unwrap(); + } + b.into_inner().unwrap().finish().unwrap(); + } + let exe = unpack(&archive, &dir, false).expect("unpacked"); + assert_eq!(std::fs::read(&exe).unwrap(), b"engine"); + assert!(dir.join("Copying.txt").is_file()); + assert!(!dir.join("README.md").exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs new file mode 100644 index 0000000..c218ced --- /dev/null +++ b/apps/desktop/src/engine_offer.rs @@ -0,0 +1,661 @@ +//! Getting an engine when there is none (decision 14, `docs/design/engine-download.md`): +//! an offer to download the official Stockfish, its progress (hidden into a small +//! indicator if the user wants), the errors with what to do next, and the action the +//! user came for (live analysis or game analysis) started once the engine is there. + +use std::path::PathBuf; + +use egui::{RichText, Ui, vec2}; + +use crate::engine_download::{self, Download, Failure, Stage}; +use crate::i18n::{tr, trf}; +use crate::settings::Settings; + +/// The id of the download indicator in the corner (it is never in the way of Escape). +pub const DOWNLOAD_INDICATOR: &str = "download_indicator"; + +/// What the user wanted to do when the engine turned out to be missing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Pending { + LiveAnalysis, + /// The search for great moves in a database's list (task 27), waiting in the app. + GreatMoves, + /// The analysis of the game on the screen whose `serial` is `game` (no other game's); + /// `full`: anew, over evaluations read from the PGN. + GameAnalysis { + game: u64, + full: bool, + }, + /// The search for opening errors of the preparation whose `serial` is `prep`. + OpeningErrors { + prep: u64, + }, +} + +/// A number of its own for a screen an action waits on (a game, a preparation), so +/// that an engine arriving later starts it there and nowhere else. +pub fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +/// What the owner should do. +pub enum OfferEvent { + /// The downloaded Stockfish is ready: make it the active engine, then run `Pending`. + Installed(Option), + /// Use the Stockfish found on this computer, then run `Pending`. + UseSystem(PathBuf, Option), + /// Open the file dialog to choose an engine. + #[cfg(not(web))] + ChooseFile, + Toast(String), +} + +#[derive(Clone, PartialEq)] +enum Mode { + Offer, + /// A `stockfish` is installed on the computer. + System(PathBuf), + /// The downloaded engine was deleted from the disk. + Missing, + /// The game analysis or the opening errors, which need ChessPenguin's Stockfish 19 + /// itself (their search is the same on every computer): only its download helps. + Own, + /// The same, when the user's engine does not do (`review_engine`): it is named. + OwnInstead(crate::review_engine::Unfit), +} + +pub struct EngineOffer { + open: bool, + mode: Mode, + pending: Option, + download: Option, + failure: Option, + /// Bytes per second, smoothed, for "about 20 s left". + speed: f64, + last: Option<(f64, u64)>, +} + +impl EngineOffer { + pub fn new() -> EngineOffer { + EngineOffer { + open: false, + mode: Mode::Offer, + pending: None, + download: None, + failure: None, + speed: 0.0, + last: None, + } + } + + /// Whether the active engine can be started. + pub fn engine_ready(settings: &Settings) -> bool { + settings.active_engine().is_some_and(|e| e.present()) + } + + /// Opens the offer for an action that needs an engine. + pub fn ask(&mut self, pending: Pending, settings: &Settings) { + self.pending = Some(pending); + self.failure = None; + self.mode = if pending != Pending::LiveAnalysis { + Mode::Own + } else if settings.active_engine().is_some_and(|e| e.builtin) { + Mode::Missing + } else if settings.engines.is_empty() + && let Some(p) = crate::engines::system_stockfish() + { + Mode::System(p) + } else { + Mode::Offer + }; + self.open = true; + } + + /// Opens the offer of ChessPenguin's Stockfish 19 for the game analysis or the + /// opening errors, saying why the user's engine does not do. + pub fn ask_instead_of(&mut self, pending: Pending, unfit: crate::review_engine::Unfit) { + self.pending = Some(pending); + self.failure = None; + self.mode = Mode::OwnInstead(unfit); + self.open = true; + } + + /// Starts the download (from the offer or from the settings). + pub fn start(&mut self, ctx: &egui::Context) { + if self.download.as_ref().is_some_and(Download::running) { + return; + } + self.failure = None; + self.speed = 0.0; + self.last = None; + self.download = Some(Download::start(ctx)); + } + + /// The download's stage, for the settings window. + pub fn stage(&self) -> Option { + self.download.as_ref().map(Download::stage) + } + + pub fn cancel(&mut self) { + if let Some(d) = &self.download { + d.cancel(); + } + } + + /// The offer window, the indicator of a hidden download, and what follows a + /// finished one. + pub fn show(&mut self, ctx: &egui::Context) -> Vec { + let mut events = Vec::new(); + let now = ctx.input(|i| i.time); + if let Some(d) = &self.download { + match d.stage() { + Stage::Done(_) => { + let pending = self.pending.take(); + events.push(OfferEvent::Installed(pending)); + events.push(OfferEvent::Toast( + match pending { + Some(Pending::GameAnalysis { .. }) => { + tr("Stockfish installed — game analysis started") + } + Some(Pending::LiveAnalysis) => { + tr("Stockfish installed — analysis is on") + } + Some(Pending::OpeningErrors { .. }) => { + tr("Stockfish installed — the search for opening errors started") + } + Some(Pending::GreatMoves) => { + tr("Stockfish installed — the search for great moves started") + } + None => tr("Stockfish installed"), + } + .to_string(), + )); + self.download = None; + self.open = false; + } + Stage::Failed(f) => { + if !self.open { + events.push(OfferEvent::Toast( + tr("âš  Stockfish wasn't downloaded").into(), + )); + } + self.failure = Some(f); + self.download = None; + } + Stage::Cancelled => { + self.download = None; + self.pending = None; + self.open = false; + } + Stage::Downloading { done, .. } => { + if let Some((t, b)) = self.last + && now - t >= 0.5 + { + let rate = (done.saturating_sub(b)) as f64 / (now - t); + self.speed = if self.speed == 0.0 { + rate + } else { + 0.7 * self.speed + 0.3 * rate + }; + self.last = Some((now, done)); + } else if self.last.is_none() { + self.last = Some((now, done)); + } + ctx.request_repaint_after(std::time::Duration::from_millis(200)); + } + Stage::Unpacking => { + ctx.request_repaint_after(std::time::Duration::from_millis(200)); + } + } + } + if self.open { + self.window(ctx, &mut events); + } else if self.download.is_some() || self.failure.is_some() { + self.indicator(ctx); + } + events + } + + fn window(&mut self, ctx: &egui::Context, events: &mut Vec) { + let modal = egui::Modal::new(egui::Id::new("engine_offer")).show(ctx, |ui| { + ui.set_width(440.0); + if let Some(d) = &self.download { + self.progress_body(ui, &d.stage()); + } else if let Some(f) = self.failure.clone() { + self.failure_body(ui, &f, events); + } else { + self.offer_body(ui, events); + } + }); + if modal.should_close() { + // Escape or a click outside: "Later", or "Hide" while downloading. + self.open = false; + if self.download.is_none() { + self.pending = None; + self.failure = None; + } + } + } + + fn offer_body(&mut self, ui: &mut Ui, events: &mut Vec) { + let size = engine_download::size_mb(); + let (title, text): (&str, String) = match &self.mode { + Mode::Offer => ( + tr("Analysis needs a chess engine"), + tr( + "Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.", + ) + .into(), + ), + Mode::System(_) => ( + tr("Analysis needs a chess engine"), + tr("Stockfish is already installed on this computer.").into(), + ), + Mode::Missing => ( + tr("Stockfish not found"), + tr("The Stockfish file is missing from the disk. Download it again?").into(), + ), + Mode::Own => ( + tr("Analysis needs Stockfish 19"), + tr( + "Game analysis and the search for opening errors always use ChessPenguin's Stockfish 19, so that their marks are the same on every computer. Download it? The analysis will start as soon as the download finishes.", + ) + .into(), + ), + Mode::OwnInstead(unfit) => ( + tr("Analysis needs Stockfish 19"), + instead_text(unfit, self.pending), + ), + }; + ui.heading(title); + ui.add_space(6.0); + ui.label(text); + ui.add_space(4.0); + if matches!(self.mode, Mode::System(_)) { + ui.label( + RichText::new(trf( + "Or download the official Stockfish 19 build ({mb} MB).", + &[("mb", &size)], + )) + .weak(), + ); + } else if cfg!(web) { + // The browser's engine: from our site, into this browser (design §1.4). + ui.label(tr( + "It evaluates the position, shows the best moves and reviews the game. It is downloaded once and kept in this browser.", + )); + let free = crate::platform::storage_free().map(|f| { + trf( + "free for the site: {free}", + &[("free", &crate::platform::size_text(f))], + ) + }); + let size = trf("Size: {size}", &[("size", &format!("{size} MB"))]); + ui.label(RichText::new(free.map_or(size.clone(), |f| format!("{size} · {f}"))).weak()); + } else { + ui.label( + RichText::new(trf( + "{mb} MB · from the official Stockfish page", + &[("mb", &size)], + )) + .weak(), + ) + .on_hover_text("https://github.com/official-stockfish/Stockfish/releases/tag/sf_19"); + ui.label(RichText::new(tr("Installed for your account only")).weak()); + } + ui.add_space(10.0); + let enter = ui.input(|i| i.key_pressed(egui::Key::Enter)); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + match self.mode.clone() { + Mode::System(p) => { + let main = ui.add(egui::Button::new(RichText::new(tr("Use it")).strong())); + main.request_focus(); + if main.clicked() || enter { + events.push(OfferEvent::UseSystem(p, self.pending.take())); + self.open = false; + } + if ui.button(tr("Later")).clicked() { + self.open = false; + self.pending = None; + } + if ui.button(tr("Download")).clicked() { + self.start(ui.ctx()); + } + } + mode => { + let label = if mode == Mode::Missing { + tr("Download again") + } else { + tr("Download Stockfish") + }; + let main = ui.add(egui::Button::new(RichText::new(label).strong())); + main.request_focus(); + if main.clicked() || enter { + self.start(ui.ctx()); + } + if ui.button(tr("Later")).clicked() { + self.open = false; + self.pending = None; + } + } + } + // Another engine does not do for the game analysis (and a browser has + // no engine programs). + #[cfg(not(web))] + if !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) { + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.button(tr("Choose engine file…")).clicked() { + events.push(OfferEvent::ChooseFile); + self.open = false; + self.pending = None; + } + }); + } + }); + }); + } + + fn progress_body(&mut self, ui: &mut Ui, stage: &Stage) { + ui.heading(tr("Downloading Stockfish")); + ui.add_space(8.0); + match *stage { + Stage::Downloading { done, total } => { + let frac = if total > 0 { + done as f32 / total as f32 + } else { + 0.0 + }; + ui.add( + egui::ProgressBar::new(frac) + .show_percentage() + .desired_width(ui.available_width()), + ); + let mb = |b: u64| b / 1_000_000; + let mut line = trf( + "{done} of {total} MB", + &[("done", &mb(done)), ("total", &mb(total))], + ); + if self.speed > 0.0 { + let left = (total.saturating_sub(done)) as f64 / self.speed; + line.push_str(" · "); + line.push_str(&trf("about {s} s left", &[("s", &(left.ceil() as u64))])); + } + ui.label(line); + } + _ => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(tr("Checking and installing…")); + }); + } + } + ui.add_space(4.0); + let after = match self.pending { + Some(Pending::GameAnalysis { .. }) => { + tr("Game analysis will start by itself when the download finishes.") + } + Some(Pending::OpeningErrors { .. }) => { + tr("The search for opening errors will start by itself when the download finishes.") + } + Some(Pending::GreatMoves) => { + tr("The search for great moves will start by itself when the download finishes.") + } + _ => tr("Analysis will start by itself when the download finishes."), + }; + ui.label(RichText::new(after).weak()); + ui.add_space(10.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let hide = ui.add(egui::Button::new(RichText::new(tr("Hide")).strong())); + hide.request_focus(); + if hide.clicked() { + self.open = false; + } + if ui.button(tr("Cancel download")).clicked() { + self.cancel(); + } + }); + }); + } + + // In a browser nothing is pushed: there are no engine files to choose. + #[cfg_attr(web, allow(clippy::ptr_arg))] + fn failure_body(&mut self, ui: &mut Ui, f: &Failure, events: &mut Vec) { + ui.heading(tr("âš  Stockfish wasn't downloaded")); + ui.add_space(6.0); + let (text, details) = failure_text(f); + ui.label(text); + if let Some(d) = details { + egui::CollapsingHeader::new(tr("Details")) + .id_salt("download_details") + .show(ui, |ui| { + ui.label(RichText::new(d).small().weak()); + }); + } + if matches!(f, Failure::Network(_)) + && cfg!(target_os = "linux") + && !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) + { + ui.label( + RichText::new(tr( + "A stockfish package of your distribution is found by ChessPenguin too.", + )) + .weak(), + ); + } + ui.add_space(10.0); + let enter = ui.input(|i| i.key_pressed(egui::Key::Enter)); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let retry = ui.add(egui::Button::new(RichText::new(tr("Retry")).strong())); + retry.request_focus(); + if retry.clicked() || enter { + self.start(ui.ctx()); + } + if ui.button(tr("Close")).clicked() { + self.open = false; + self.failure = None; + self.pending = None; + } + #[cfg(not(web))] + if !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) { + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.button(tr("Choose engine file…")).clicked() { + events.push(OfferEvent::ChooseFile); + self.open = false; + self.failure = None; + self.pending = None; + } + }); + } + }); + }); + } + + /// "⬇ Stockfish 42 %" in the top right corner while a download runs hidden (or + /// "âš  Stockfish wasn't downloaded" after it failed); a click opens the window. + fn indicator(&mut self, ctx: &egui::Context) { + let text = match self.download.as_ref().map(Download::stage) { + Some(Stage::Downloading { done, total }) if total > 0 => { + format!("⬇ Stockfish {} %", done * 100 / total) + } + Some(_) => "⬇ Stockfish…".to_string(), + None => tr("âš  Stockfish wasn't downloaded").to_string(), + }; + egui::Area::new(egui::Id::new(DOWNLOAD_INDICATOR)) + .anchor(egui::Align2::RIGHT_BOTTOM, vec2(-12.0, -12.0)) + .order(egui::Order::Foreground) + .show(ctx, |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.horizontal(|ui| { + if ui + .add(egui::Label::new(text).sense(egui::Sense::click())) + .on_hover_text(tr("Show the download")) + .clicked() + { + self.open = true; + } + let close = crate::widgets::small_close_button(ui); + let close = if self.download.is_some() { + close.on_hover_text(tr("Cancel download")) + } else { + close.on_hover_text(tr("Close")) + }; + if close.clicked() { + if self.download.is_some() { + self.cancel(); + } else { + self.failure = None; + self.pending = None; + } + } + }); + }); + }); + } +} + +/// Why the user's engine does not do for the game analysis (or the opening errors), +/// what is offered instead, and that the analysis follows the download by itself. +fn instead_text(unfit: &crate::review_engine::Unfit, pending: Option) -> String { + use crate::review_engine::Why; + let errors = matches!(pending, Some(Pending::OpeningErrors { .. })); + let engine = crate::widgets::shorten(&unfit.name, 48); + let mut parts = vec![match unfit.why { + Why::Differs => tr( + "Your Stockfish 19 calculates differently from ChessPenguin's build (another build or network).", + ) + .to_owned(), + Why::NotStarted => trf("{engine} could not be started.", &[("engine", &engine)]), + Why::TimedOut => trf( + "{engine} did not finish the check in time; it will be checked again next time.", + &[("engine", &engine)], + ), + Why::Other if unfit.from_settings => { + trf("The settings name {engine}.", &[("engine", &engine)]) + } + Why::Other => trf("The system has {engine}.", &[("engine", &engine)]), + }]; + let official = matches!(unfit.why, Why::Differs | Why::TimedOut); + parts.push( + match (official, errors) { + (true, false) => tr( + "So that the marks are the same on every computer, game analysis runs on the official build.", + ), + (true, true) => tr( + "So that the marks are the same on every computer, the search for opening errors runs on the official build.", + ), + (false, false) => tr( + "Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer.", + ), + (false, true) => tr( + "The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer.", + ), + } + .to_owned(), + ); + parts.push( + if official { + tr("Download it?") + } else { + tr("Download Stockfish 19?") + } + .to_owned(), + ); + if unfit.why != Why::NotStarted { + parts.push(tr("Your engine stays for position analysis.").to_owned()); + } + parts.push( + if errors { + tr("The search for opening errors will start by itself when the download finishes.") + } else { + tr("Game analysis will start by itself when the download finishes.") + } + .to_owned(), + ); + parts.join(" ") +} + +/// What to tell the user about a failure, and the technical details (collapsed). +fn failure_text(f: &Failure) -> (String, Option) { + match f { + Failure::Network(e) => ( + tr("Couldn't connect. Check your internet connection and try again.").into(), + Some(e.clone()), + ), + Failure::Server(code) => ( + trf( + "The server didn't provide the file (error {code}). Please try again later.", + &[("code", code)], + ), + None, + ), + Failure::Checksum => ( + tr("The downloaded file failed the integrity check and was deleted. It was most likely damaged during the download.").into(), + Some("SHA-256 mismatch".into()), + ), + Failure::Disk(e) => ( + tr("Couldn't save the engine on the disk (not enough space or no permission).").into(), + Some(e.clone()), + ), + Failure::Broken => ( + tr("Stockfish was downloaded but doesn't run on this computer.").into(), + None, + ), + Failure::Unsupported => ( + tr("There is no Stockfish download for this computer. Choose an engine file instead.") + .into(), + None, + ), + } +} + +#[cfg(test)] +mod tests { + use super::{Pending, instead_text}; + use crate::review_engine::{Unfit, Why}; + + fn text(why: Why, from_settings: bool, pending: Pending) -> String { + let unfit = Unfit { + name: "Rodent V 1.2".into(), + from_settings, + why, + }; + instead_text(&unfit, Some(pending)) + } + + /// The offer says why the user's engine does not do and where it is from; the + /// user's engine stays for the live analysis, the analysis follows the download. + #[test] + fn the_offer_says_why_the_users_engine_does_not_do() { + let game = Pending::GameAnalysis { + game: 1, + full: false, + }; + let errors = Pending::OpeningErrors { prep: 1 }; + let t = text(Why::Other, true, game); + assert!(t.starts_with("The settings name Rodent V 1.2."), "{t}"); + assert!(t.contains("Your engine stays for position analysis.")); + assert!(t.ends_with("Game analysis will start by itself when the download finishes.")); + let t = text(Why::Other, false, errors); + assert!(t.starts_with("The system has Rodent V 1.2."), "{t}"); + assert!(t.contains("The search for opening errors needs Stockfish 19 itself")); + let t = text(Why::Differs, true, game); + assert!( + t.starts_with("Your Stockfish 19 calculates differently"), + "{t}" + ); + assert!(t.contains("Download it?")); + let t = text(Why::TimedOut, true, game); + assert!( + t.starts_with("Rodent V 1.2 did not finish the check in time"), + "{t}" + ); + assert!(t.contains("runs on the official build") && t.contains("Download it?")); + let t = text(Why::NotStarted, true, game); + assert!(t.starts_with("Rodent V 1.2 could not be started."), "{t}"); + assert!(!t.contains("stays for position analysis")); + } +} diff --git a/apps/desktop/src/engines.rs b/apps/desktop/src/engines.rs new file mode 100644 index 0000000..3e86544 --- /dev/null +++ b/apps/desktop/src/engines.rs @@ -0,0 +1,153 @@ +//! Finding engines without a file dialog: ChessPenguin's Stockfish (bundled in the +//! Flatpak, otherwise downloaded on request, see `engine_download`) and a `stockfish` +//! installed by the system package manager. + +use std::path::{Path, PathBuf}; + +use crate::i18n::tr; +use crate::settings::{EngineConfig, Settings}; + +#[cfg(windows)] +const STOCKFISH: &str = "stockfish.exe"; +#[cfg(not(windows))] +const STOCKFISH: &str = "stockfish"; + +/// The Stockfish shipped next to the application: +/// `/lib/chesspenguin/stockfish` for `/bin/chesspenguin` (deb, rpm, Arch, +/// AppImage, Flatpak) or `stockfish/stockfish[.exe]` beside the executable (Windows zip, +/// Linux tarball). Resolved at every start: the AppImage mount point changes between runs. +pub fn bundled_stockfish() -> Option { + let exe = std::env::current_exe().ok()?.canonicalize().ok()?; + let dir = exe.parent()?; + let candidates = [ + dir.parent() + .map(|prefix| prefix.join("lib").join("chesspenguin").join(STOCKFISH)), + Some(dir.join("stockfish").join(STOCKFISH)), + ]; + candidates.into_iter().flatten().find(|p| is_executable(p)) +} + +/// Where an engine starts from: its program on a computer; in a browser, which runs no +/// programs, the address of its Web Worker's script. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EngineLocation { + #[cfg(not(web))] + Program(PathBuf), + #[cfg(web)] + Worker(String), +} + +impl EngineLocation { + /// Whether the engine is there to start (its program's file; a worker always). + pub fn present(&self) -> bool { + match self { + #[cfg(not(web))] + EngineLocation::Program(p) => p.is_file(), + #[cfg(web)] + EngineLocation::Worker(_) => true, + } + } +} + +impl std::fmt::Display for EngineLocation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + #[cfg(not(web))] + EngineLocation::Program(p) => write!(f, "{}", p.display()), + #[cfg(web)] + EngineLocation::Worker(script) => write!(f, "{script}"), + } + } +} + +/// ChessPenguin's Stockfish: the bundled one, or else the downloaded one. +pub fn own_stockfish() -> Option { + #[cfg(not(web))] + return bundled_stockfish() + .map(EngineLocation::Program) + .or_else(crate::engine_download::installed); + #[cfg(web)] + crate::engine_download::installed() +} + +/// `stockfish` from `PATH` (for example, the distribution package). On macOS an app +/// started from the Finder does not get the shell's `PATH`: Homebrew's directories are +/// looked at too. +#[cfg(not(web))] +pub fn system_stockfish() -> Option { + let path = std::env::var_os("PATH").unwrap_or_default(); + let extra: &[&str] = if cfg!(target_os = "macos") { + &["/opt/homebrew/bin", "/usr/local/bin"] + } else { + &[] + }; + std::env::split_paths(&path) + .chain(extra.iter().map(PathBuf::from)) + .map(|dir| dir.join(STOCKFISH)) + .find(|p| is_executable(p)) +} + +/// A browser has no programs of the system to find. +#[cfg(web)] +pub fn system_stockfish() -> Option { + None +} + +fn is_executable(p: &Path) -> bool { + let Ok(meta) = std::fs::metadata(p) else { + return false; + }; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + meta.is_file() && meta.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + { + meta.is_file() + } +} + +pub fn builtin_config() -> EngineConfig { + let mut cfg = EngineConfig::new("Stockfish 19".into(), PathBuf::new()); + cfg.builtin = true; + cfg +} + +/// First start: if no engine is configured, adds the bundled Stockfish (or else the system +/// one) and makes it active, so analysis works right after installation. Runs once. +pub fn first_run_setup(settings: &mut Settings) -> bool { + if settings.engines_discovered { + return false; + } + settings.engines_discovered = true; + if settings.engines.is_empty() { + let found = if own_stockfish().is_some() { + Some(builtin_config()) + } else { + system_stockfish().map(|p| EngineConfig::new("Stockfish".into(), p)) + }; + if let Some(cfg) = found { + settings.engines.push(cfg); + settings.active_engine = Some(0); + } + } + true +} + +/// Engines found on this system that are not in the list yet (offered in the settings). +pub fn suggestions(settings: &Settings) -> Vec { + let mut out = Vec::new(); + if own_stockfish().is_some() && !settings.engines.iter().any(|e| e.builtin) { + out.push(builtin_config()); + } + if let Some(p) = system_stockfish() { + let known = |e: &EngineConfig| { + !e.builtin && (e.path == p || e.path.canonicalize().ok() == p.canonicalize().ok()) + }; + if !settings.engines.iter().any(known) { + out.push(EngineConfig::new(tr("Stockfish (system)").into(), p)); + } + } + out +} diff --git a/apps/desktop/src/examples.rs b/apps/desktop/src/examples.rs new file mode 100644 index 0000000..4843acd --- /dev/null +++ b/apps/desktop/src/examples.rs @@ -0,0 +1,255 @@ +//! Sample databases of the program, so the library is not empty: classic games with +//! short introductions, and Alekhine's games (moves only). At the first start they are +//! written, named in the interface language, to `/examples/` and put on +//! the library shelf; a sample removed from the shelf does not come back. +//! +//! The samples are read only, so their files are the program's: at every start a file +//! that is not the text built into this version (an older version of the sample, a file +//! damaged or edited outside) is replaced by it, whether on the shelf or not. Nothing +//! keeps a sample by its place in the file: the counts of the cards are of the file's +//! size and time, the marks of viewed games of the games' text. + +use std::path::{Path, PathBuf}; + +use crate::i18n::{all_languages, tr}; +use crate::settings::Settings; + +/// The samples: the English name (a key of the translations) and the text. +const SAMPLES: [(&str, &str); 2] = [ + ( + "Classic games", + include_str!("../../../examples/classics.pgn"), + ), + ("Alekhine", include_str!("../../../examples/alekhine.pgn")), +]; + +#[cfg(test)] +const OPENING_SAMPLES: [(&str, &str); 2] = [ + ("najdorf", include_str!("../../../examples/najdorf.pgn")), + ("spanish", include_str!("../../../examples/spanish.pgn")), +]; + +fn dir() -> Option { + crate::platform::examples_dir() +} + +/// A sample database of the program: only read (games added there would end up in a +/// hidden data folder). +pub fn is_example(path: &std::path::Path) -> bool { + dir().is_some_and(|d| path.starts_with(d)) +} + +/// Adds the samples at the first start and brings their files up to this version; +/// `true` when the settings changed. A new library starts with them (the classics +/// open); an existing one gets them after its own databases. +pub fn setup(settings: &mut Settings) -> bool { + match dir() { + Some(dir) => setup_in(&dir, settings), + None => !std::mem::replace(&mut settings.examples_added, true), + } +} + +fn setup_in(dir: &Path, settings: &mut Settings) -> bool { + let first = !std::mem::replace(&mut settings.examples_added, true); + for (key, text) in SAMPLES { + let named = dir.join(format!("{}.pgn", tr(key))); + // The file is named in the language of the first start: the sample's file under + // any language's name is it. + for name in all_languages(key) { + let path = dir.join(format!("{name}.pgn")); + let kept = crate::platform::fs::exists(&path) || settings.databases.contains(&path); + if (kept || (first && path == named)) + && let Err(e) = bring_up_to_date(&path, text) + { + eprintln!("examples: cannot write {}: {e}", path.display()); + } + } + if first && crate::platform::fs::exists(&named) && !settings.databases.contains(&named) { + 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)] +mod tests { + use super::*; + + /// A folder of its own for each test, empty. + fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("cp-examples-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + fn classics(dir: &Path) -> PathBuf { + dir.join(format!("{}.pgn", tr("Classic games"))) + } + + #[test] + fn samples_are_valid_pgn() { + let dir = folder("valid"); + std::fs::create_dir_all(&dir).unwrap(); + for (name, text) in SAMPLES { + let path = dir.join(format!("{name}.pgn")); + std::fs::write(&path, text).unwrap(); + let db = chess_core::PgnDatabase::open( + &path, + &mut |_| {}, + &std::sync::atomic::AtomicBool::new(false), + ) + .unwrap(); + assert!(db.len() >= 30, "{name}: {} games", db.len()); + for i in 0..db.len() { + let parsed = db.load_game(i).unwrap(); + assert!( + parsed.diagnostics.is_empty(), + "{name} #{}: {:?}", + i + 1, + 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 = game + .mainline() + .iter() + .filter_map(|id| game.game_move(*id).map(|mv| mv.san.clone())) + .collect(); + let common: &[&str] = if name == "najdorf" { + &[ + "e4", "c5", "Nf3", "d6", "d4", "cxd4", "Nxd4", "Nf6", "Nc3", "a6", + ] + } else { + &["e4", "e5", "Nf3", "Nc6", "Bb5"] + }; + assert!(san.len() >= common.len(), "{name} #{index}: {san:?}"); + assert!( + common + .iter() + .zip(&san) + .all(|(expected, actual)| *expected == actual), + "{name} #{index}: {san:?}" + ); + branches.push(san); + } + if name == "najdorf" { + assert_eq!(branches[0][10], "Be3"); + assert_eq!(branches[1][10], "Bg5"); + assert_eq!(branches[2][10], "Be2"); + } else { + assert_eq!(branches[0][5], "Nf6"); + assert_eq!(branches[1][5], "a6"); + assert_eq!(branches[2][5], "a6"); + assert_eq!(branches[2][9], "Nxe4"); + } + } + } + + #[test] + fn the_first_start_writes_the_samples_and_shelves_them() { + let dir = folder("first"); + let mut settings = Settings::default(); + assert!(setup_in(&dir, &mut settings)); + assert!(settings.examples_added); + assert_eq!(settings.databases.len(), SAMPLES.len()); + assert_eq!(settings.databases[0], classics(&dir)); + for (path, (_, text)) in settings.databases.iter().zip(SAMPLES) { + assert_eq!(std::fs::read_to_string(path).unwrap(), text); + } + // The next start changes nothing. + let before = settings.databases.clone(); + assert!(!setup_in(&dir, &mut settings)); + assert_eq!(settings.databases, before); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn an_older_or_damaged_sample_is_replaced() { + let dir = folder("older"); + let mut settings = Settings::default(); + setup_in(&dir, &mut settings); + let path = classics(&dir); + let old: String = SAMPLES[0].1.chars().take(SAMPLES[0].1.len() / 3).collect(); + std::fs::write(&path, old).unwrap(); + assert!(!setup_in(&dir, &mut settings)); + assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1); + // Edited outside: the same. + let mut edited = SAMPLES[0].1.to_owned(); + edited.push_str("\n[Event \"mine\"]\n\n1. e4 *\n"); + std::fs::write(&path, edited).unwrap(); + setup_in(&dir, &mut settings); + assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A program that started in another language named the file in it. + #[test] + fn a_sample_named_in_another_language_is_replaced() { + let dir = folder("language"); + std::fs::create_dir_all(&dir).unwrap(); + let russian = dir.join("КлаÑ�Ñ�ичеÑ�кие партии.pgn"); + std::fs::write(&russian, "[Event \"old\"]\n\n1. e4 *\n").unwrap(); + let mut settings = Settings { + examples_added: true, + databases: vec![russian.clone()], + ..Settings::default() + }; + assert!(!setup_in(&dir, &mut settings)); + assert_eq!(std::fs::read_to_string(&russian).unwrap(), SAMPLES[0].1); + // The samples of the other names are not made. + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + assert_eq!(settings.databases, vec![russian]); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_sample_taken_off_the_shelf_stays_off() { + let dir = folder("off"); + let mut settings = Settings::default(); + setup_in(&dir, &mut settings); + let path = classics(&dir); + settings.databases.retain(|p| *p != path); + std::fs::write(&path, "[Event \"old\"]\n\n1. e4 *\n").unwrap(); + assert!(!setup_in(&dir, &mut settings)); + assert!(!settings.databases.contains(&path)); + // Its file is the new one, should the user open it again. + assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1); + // Deleted as well: not made again. + std::fs::remove_file(&path).unwrap(); + setup_in(&dir, &mut settings); + assert!(!path.exists()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/file_state.rs b/apps/desktop/src/file_state.rs new file mode 100644 index 0000000..f214d98 --- /dev/null +++ b/apps/desktop/src/file_state.rs @@ -0,0 +1,127 @@ +//! What the screen needs to know about the databases' files (there or not, their size, +//! read only) without touching the disk in the frame: a network drive that has lost its +//! network (an NFS mount waits for it) would hold the whole window. A thread of its own +//! looks at the files the screen asks about, again every few seconds; the screen reads +//! what it last found. A file not looked at yet counts as there. In a browser the +//! files are the page's, in memory: they are looked at when asked. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// A file as last found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct State { + pub exists: bool, + pub size: u64, + pub readonly: bool, +} + +#[derive(Default)] +struct Shared { + found: HashMap, + asked: HashSet, +} + +pub struct FileStates { + shared: Arc>, +} + +/// How often the files are looked at again. +const EVERY: Duration = Duration::from_secs(3); + +impl FileStates { + #[cfg(not(web))] + pub fn new() -> Self { + let shared = Arc::new(Mutex::new(Shared::default())); + let looked = shared.clone(); + let _ = std::thread::Builder::new() + .name("file-states".into()) + .spawn(move || { + loop { + let asked: Vec = match looked.lock() { + Ok(s) => s.asked.iter().cloned().collect(), + Err(_) => return, + }; + for path in asked { + // May wait long (a lost network drive): only this thread waits. + let state = look(&path); + if let Ok(mut s) = looked.lock() { + s.found.insert(path, state); + } + } + std::thread::sleep(EVERY); + } + }); + Self { shared } + } + + #[cfg(web)] + pub fn new() -> Self { + Self { + shared: Arc::default(), + } + } + + /// The file as it is (the page's files are in memory: no waiting). + #[cfg(web)] + pub fn get(&self, path: &Path) -> Option { + Some(look(path)) + } + + /// The file as last found (`None`: not looked at yet); it is looked at from now on. + #[cfg(not(web))] + pub fn get(&self, path: &Path) -> Option { + let mut s = self.shared.lock().ok()?; + if !s.asked.contains(path) { + s.asked.insert(path.to_owned()); + } + s.found.get(path).copied() + } + + /// Whether the file is there (as last found; yes until looked at). + pub fn exists(&self, path: &Path) -> bool { + self.get(path).is_none_or(|s| s.exists) + } +} + +fn look(path: &Path) -> State { + match crate::platform::fs::meta(path) { + Ok(m) => State { + exists: true, + size: m.len, + readonly: m.readonly, + }, + Err(_) => State { + exists: false, + size: 0, + readonly: false, + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn files_are_looked_at_away_from_the_caller() { + let dir = std::env::temp_dir().join(format!("cp-file-states-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let there = dir.join("a.pgn"); + std::fs::write(&there, "1. e4 *\n").unwrap(); + let gone = dir.join("b.pgn"); + let states = FileStates::new(); + // Not looked at yet: counted as there, nothing waited for. + assert!(states.get(&there).is_none()); + assert!(states.exists(&gone)); + let deadline = web_time::Instant::now() + Duration::from_secs(5); + while states.get(&gone).is_none() && web_time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + assert!(!states.exists(&gone)); + assert_eq!(states.get(&there).map(|s| s.size), Some(8)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/game_link.rs b/apps/desktop/src/game_link.rs new file mode 100644 index 0000000..a29f587 --- /dev/null +++ b/apps/desktop/src/game_link.rs @@ -0,0 +1,133 @@ +//! The game's page on the site it was played on: Lichess writes it in the Site tag +//! («https://lichess.org/AbCdEfGh»), Chess.com in the Link tag (its Site is +//! «Chess.com»). A Lichess game opens at the move shown and from the side at the +//! bottom of the board; Chess.com's page has no such address, it opens at the start. + +use crate::i18n::tr; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Site { + Lichess, + ChessCom, + /// Another web address. + Other, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GameLink { + pub url: String, + pub site: Site, + /// The Lichess game id (8 characters), when the address is a game's. + lichess_id: Option, +} + +/// The game's web address from its tags (Link first, then Site), if it has one. +pub fn of(tag: impl Fn(&str) -> Option) -> Option { + let url = ["Link", "Site"] + .into_iter() + .filter_map(&tag) + .map(|v| v.trim().to_owned()) + .find(|v| v.starts_with("https://") || v.starts_with("http://"))?; + let host_and_path = url.split_once("://").map_or("", |(_, rest)| rest); + let (host, path) = host_and_path.split_once('/').unwrap_or((host_and_path, "")); + let host = host.to_ascii_lowercase(); + let host = host.strip_prefix("www.").unwrap_or(&host); + let site = match host { + "lichess.org" => Site::Lichess, + "chess.com" => Site::ChessCom, + _ => Site::Other, + }; + // «AbCdEfGh», or the 12-character id of one player's view of it. + let first = path.split(['/', '#', '?']).next().unwrap_or(""); + let lichess_id = (site == Site::Lichess + && (first.len() == 8 || first.len() == 12) + && first.chars().all(|c| c.is_ascii_alphanumeric())) + .then(|| first[..8].to_owned()); + Some(GameLink { + url, + site, + lichess_id, + }) +} + +impl GameLink { + /// The address to open: a Lichess game at half-move `ply` (0: the start) from + /// Black's side when `black`; any other as written. + pub fn at(&self, ply: u32, black: bool) -> String { + match &self.lichess_id { + Some(id) => { + let mut url = format!("https://lichess.org/{id}"); + if black { + url.push_str("/black"); + } + if ply > 0 { + url.push_str(&format!("#{ply}")); + } + url + } + None => self.url.clone(), + } + } + + /// The globe's tooltip: «Open on Lichess (in the browser, at this move)». + pub fn hint(&self) -> &'static str { + match (self.site, self.lichess_id.is_some()) { + (Site::Lichess, true) => tr("Open on Lichess (in the browser, at this move)"), + (Site::Lichess, false) => tr("Open on Lichess (in the browser)"), + (Site::ChessCom, _) => tr("Open on Chess.com (in the browser)"), + (Site::Other, _) => tr("Open the game's link (in the browser)"), + } + } + + /// «ðŸŒ� Open on Lichess». + pub fn label(&self) -> &'static str { + match self.site { + Site::Lichess => tr("ðŸŒ� Open on Lichess"), + Site::ChessCom => tr("ðŸŒ� Open on Chess.com"), + Site::Other => tr("ðŸŒ� Open the game's link"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn link(tags: &[(&str, &str)]) -> Option { + of(|name| { + tags.iter() + .find(|(n, _)| *n == name) + .map(|(_, v)| (*v).to_owned()) + }) + } + + #[test] + fn lichess_chess_com_and_others() { + let l = link(&[("Site", "https://lichess.org/AbCdEfGh")]).expect("lichess"); + assert_eq!(l.site, Site::Lichess); + assert_eq!(l.at(0, false), "https://lichess.org/AbCdEfGh"); + assert_eq!(l.at(23, true), "https://lichess.org/AbCdEfGh/black#23"); + // One player's view (12 characters): the game. + let l = link(&[("Site", "https://lichess.org/AbCdEfGh1234")]).unwrap(); + assert_eq!(l.at(4, false), "https://lichess.org/AbCdEfGh#4"); + // A study is opened as it is. + let s = link(&[("Site", "https://lichess.org/study/abcdefgh/ijklmnop")]).unwrap(); + assert_eq!( + s.at(10, true), + "https://lichess.org/study/abcdefgh/ijklmnop" + ); + let c = link(&[ + ("Site", "Chess.com"), + ("Link", "https://www.chess.com/game/live/123456789"), + ]) + .expect("chess.com"); + assert_eq!(c.site, Site::ChessCom); + assert_eq!(c.at(12, true), "https://www.chess.com/game/live/123456789"); + assert_eq!( + link(&[("Site", "http://example.org/g/1")]).unwrap().site, + Site::Other + ); + assert!(link(&[("Site", "Moscow RUS")]).is_none()); + assert!(link(&[("Site", "Chess.com")]).is_none()); + } +} diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs new file mode 100644 index 0000000..5d6950c --- /dev/null +++ b/apps/desktop/src/game_view.rs @@ -0,0 +1,5882 @@ +//! Game screen: board with eval bar, engine lines with PV preview, notation, toolbar. + +use crate::i18n::{tr, trf}; +use crate::reference::RefAction; +use std::path::PathBuf; + +use chess_core::shakmaty::{Chess, Color, Move, Position, Square}; +use chess_core::{ + Annotation, CommentPart, Diagnostic, Game, GameResult, MoveKind, Nag, NodeId, Severity, + ShapeColor, parse_comment, +}; +use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Sense, Ui, vec2}; + +use crate::analysis::{self, Analysis, PvLine, Status}; +use crate::assets::Sound; +use crate::board::{self, Arrow, BoardState, BoardView}; +use crate::notation::{ + CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, ShapeCount, Slot, + toggle_nag, +}; +use crate::review::{ReportAction, Review}; +use crate::settings::Settings; +use std::collections::HashMap; + +/// Where an opened game came from (to return to the same library row, to save into). +#[derive(Clone, Debug)] +pub struct GameSource { + pub path: PathBuf, + pub index: usize, + /// Why the game cannot be saved back there (`None`: a PGN that takes games). + pub block: Option, +} + +/// A frozen engine line being stepped through on the board. Never changes the game. +pub struct Preview { + base: NodeId, + root: Chess, + moves: Vec, + san: Vec, + shown: usize, +} + +impl Preview { + fn position(&self) -> Chess { + let mut pos = self.root.clone(); + for m in &self.moves[..self.shown] { + pos.play_unchecked(*m); + } + pos + } +} + +pub struct GameView { + /// This view's own number (`engine_offer::next_serial`). + pub serial: u64, + pub game: Game, + pub source: Option, + /// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there. + /// Cleared once the game is in a database. + pub target: Option, + pub diagnostics: Vec, + cursor: NodeId, + board: BoardState, + flipped: bool, + preview: Option, + scroll_to_cursor: bool, + /// Height of one engine line in the panel (its room is kept while lines come). + pv_row_height: f32, + /// The comment being written (user-comments.md). + editor: Option, + /// A game against Maia in progress (play-mode.md). + pub play: Option, + /// The game just played: the result strip. + pub play_end: Option, + /// Where the game just played went by itself (player-games.md), or why it did not: + /// said on the result strip. + pub recorded: Option>, + /// The same, once, for the program: the shelf, the player's link, a toast. + pub record_news: Option>, + /// The journal of a game its database did not take: kept (a crash still leaves the + /// game to the next start) until the game is saved elsewhere or left. + pub unwritten: Option, + /// What the play started with (for the end, a rematch). + play_start: Option, + /// «The game is on» asked (leaving during a game); the clocks wait meanwhile. + /// Where leaving goes, and since when the question is open. + play_leave: Option<(crate::app::CloseIntent, web_time::Instant)>, + /// Learning an opening (this screen is the training). + pub train: Option, + /// A line from the clipboard that would go elsewhere than the user stands: asked. + paste_pending: Option, + /// Text to paste on the next frame (dev hook `CP_PASTE_LINE`). + paste_request: Option, + /// The menu's «Paste a line»: the clipboard being read. + clipboard: Option, + show_diagnostics: bool, + engine_settings_open: bool, + review: Review, + /// «Analyse» was pressed: started (or its dialog shown) where the settings are. + review_asked: bool, + side_tab: SideTab, + /// The game this one was opened from (reference tab): the title for "â†� back to". + pub previous: Option, + /// The game was opened from the opponent preparation: «⬅ Back to preparation». + pub previous_prep: bool, + /// The engine is busy with the opponent preparation: no game analysis meanwhile + /// (one engine job for the whole program, opponent-prep.md §4.3). + pub engine_busy: bool, + /// Why, when another job than the search for opening errors has it (the search for + /// great moves, task 27). + pub engine_busy_why: Option, + /// The game's data were asked once (on its first add); not again. + pub data_asked: bool, + /// A newer version to offer (its number), next to Settings. + pub update: Option, + /// Comments in another language, translated for reading (never into the PGN). + translation: crate::translate_ui::GameTranslation, + /// "Translate comments" was chosen (menu, Ctrl+Shift+T): done once the settings are at hand. + translate_now: bool, + /// The moves whose comments draw on the board, for the notation's sign; by the + /// revision of the game they were counted at. + shape_counts: Option<(u64, HashMap)>, + /// The hint about drawing arrows above the notation: decided as the notation is + /// first drawn (`None`: not yet). + shapes_hint: Option, + /// An arrow or a circle went into the game on this frame (the hint has done its job). + shape_drawn: bool, + /// Dev hook `CP_BEST_DELAY`: the better line to open after the notation is drawn. + debug_best: Option, +} + +/// The better line opened on a timer (screenshots of the notation before, during and +/// after the line); times in seconds. +struct DebugBest { + shown: usize, + delay: f64, + exit: Option, + /// When the notation was first drawn. + start: Option, + opened: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SideTab { + Notation, + /// What was played here in a database (`reference.rs`). + Reference, + Report, +} + +pub enum GameAction { + Back, + /// Ctrl+W: back to what the game was opened from, else to the library. + BackKey, + /// Back to the library with this database chosen (the game's own). + OpenDatabase(PathBuf), + /// «Play on from here»: the play dialog for this position. + PlayFrom(Box), + #[cfg(not(web))] + AddToRepertoire(Box, NodeId), + Sound(Sound), + CopyText(String, &'static str), + /// Ctrl+S: into the game's own database, else "Add to database…". + Save, + /// After a game against Maia: the same again with colours swapped. + Rematch, + /// Leaving after «The game is on» was answered. + Leave(crate::app::CloseIntent), + /// The game in progress is put aside (GameView::put_aside), then leaving: where the + /// user was going (`None`: where «⬅» leads). + PutAside(Option), + /// Saving into a database, then leaving. + SaveAndLeave(crate::app::CloseIntent), + /// After a game against Maia: the play dialog. + PlayAgain, + /// Ctrl+Shift+S: choose the database to add the game to. + AddToDatabase, + /// F2: players, event, date, result… + EditGameData, + ToggleEngine, + /// Threads/Hash/MultiPV/search time of the active engine changed (settings already updated). + EngineReconfigure, + /// Another engine was made active. + EngineSwitch, + OpenEngineSettings, + OpenSettings, + Toast(String), + /// The analysis of a game of a database ended: its marks go into that database's + /// index (task 27), so its row shows them. + Reviewed { + path: PathBuf, + index: usize, + entry: crate::brilliant::Entry, + }, + /// A whole-game analysis started: pause the live engine (they would share the CPU). + PauseLive, + /// The whole-game analysis ended: resume the live engine if it was paused. + ResumeLive, + /// Find the current position in a database (`None`: the last chosen one). + FindPosition(Option), + /// Game analysis (`full`: anew) needs an engine that is not there yet (offer to + /// download one). + NeedEngine { + full: bool, + }, + /// The reference tab: use / load a database, open one of its games. + ReferenceChoose(std::path::PathBuf), + ReferenceLoad(std::path::PathBuf), + OpenGame(std::path::PathBuf, usize, Chess), + /// Back to the game this one was opened from. + ReturnToPrevious, + /// The window offering a newer version. + #[cfg(not(web))] + OpenUpdate, + /// The game's PGN as a downloaded file (the web version saves so). + #[cfg(web)] + DownloadPgn, + /// Settings → Translation. + OpenTranslationSettings, + /// A hint was shown or put away: the settings are to be written. + HintsChanged, +} + +impl GameView { + pub fn new(game: Game, source: Option, diagnostics: Vec) -> Self { + let flipped = false; + let review = Review::new(&game); + Self { + serial: crate::engine_offer::next_serial(), + game, + source, + diagnostics, + cursor: NodeId::ROOT, + board: BoardState::default(), + flipped, + preview: None, + scroll_to_cursor: true, + pv_row_height: 0.0, + editor: None, + play: None, + play_end: None, + recorded: None, + record_news: None, + unwritten: None, + play_start: None, + play_leave: None, + paste_pending: None, + train: None, + paste_request: None, + clipboard: None, + show_diagnostics: false, + engine_settings_open: false, + review, + review_asked: false, + // Dev hook (screenshots): `CP_TAB=reference` opens that tab. + side_tab: if std::env::var("CP_TAB").as_deref() == Ok("reference") { + SideTab::Reference + } else { + SideTab::Notation + }, + previous: None, + previous_prep: false, + engine_busy: false, + engine_busy_why: None, + data_asked: false, + target: None, + update: None, + translation: Default::default(), + translate_now: false, + shape_counts: None, + shapes_hint: None, + shape_drawn: false, + debug_best: None, + } + } + + /// The game is put aside (another one opened): its translation stops. + pub fn suspend(&mut self) { + self.translation.suspend(); + } + + /// The whole-game analysis is running. + pub fn review_running(&self) -> bool { + self.review.running() + } + + /// Copying the PGN always copies the original comments; say so when the translation is shown. + fn copy_pgn(&self) -> GameAction { + let note = if self.translation.shown().is_some() { + tr("PGN copied (comments in the original)") + } else { + tr("PGN copied") + }; + GameAction::CopyText(self.game.to_pgn(), note) + } + + pub fn title(&self) -> String { + if let Some(t) = &self.train { + return match &t.start.game { + Some(game) => trf("Learning the opening: {game}", &[("game", game)]), + None => tr("Learning the opening").to_owned(), + }; + } + let g = &self.game; + // In a game against Maia an unnamed user is «You». + let user = self.play.as_ref().map(|s| s.user); + let unnamed = |c: Color| { + if user == Some(c) { + tr("You") + } else { + c.fold_wb(tr("White"), tr("Black")) + } + }; + let white = g + .tag("White") + .filter(|s| *s != "?") + .unwrap_or(unnamed(Color::White)); + // A book chapter imported from ChessBase: its title is in White, Black is empty. + if g.tag("Black") == Some("") { + return white.to_string(); + } + let black = g + .tag("Black") + .filter(|s| *s != "?") + .unwrap_or(unnamed(Color::Black)); + format!("{white} — {black}") + } + + /// Where the game lives: «🗄 Petrov · No. 13» (ðŸŒ� an online database, 🔒 a read-only + /// one); nothing for a game that is in no database yet. + pub fn source_line(&self) -> Option { + if self.source.is_none() + && let Some(t) = &self.target + { + return Some(format!( + "🗄 {}", + trf( + "{name} · new game", + &[("name", &crate::own_db::base_name(t))] + ) + )); + } + let s = self.source.as_ref()?; + let icon = match &s.block { + None => "🗄", + Some(crate::own_db::Block::Online) => "ðŸŒ�", + Some(_) => "🔒", + }; + Some(format!( + "{icon} {} · â„– {}", + crate::own_db::base_name(&s.path), + s.index + 1 + )) + } + + /// What Ctrl+S does to this game, for the button's tooltip. + pub fn save_hint(&self) -> String { + match (&self.source, &self.target) { + (Some(s), _) if s.block.is_none() => trf( + "Save to «{name}» (Ctrl+S)", + &[("name", &crate::own_db::base_name(&s.path))], + ), + (None, Some(t)) => trf( + "Add to «{name}» (Ctrl+S)", + &[("name", &crate::own_db::base_name(t))], + ), + _ => tr("Add to database… (Ctrl+S)").to_owned(), + } + } + + /// The game's web page, if its tags have one. + fn link(&self) -> Option { + crate::game_link::of(|t| self.game.tag(t).map(str::to_owned)) + } + + /// Opens the game's page at the move shown, from the side at the bottom. + fn open_link(&self, ctx: &egui::Context, link: &crate::game_link::GameLink) { + let ply = self.game.node(self.cursor).map_or(0, |n| n.ply()); + ctx.open_url(egui::OpenUrl::new_tab(link.at(ply, self.flipped))); + } + + fn subtitle(&self) -> String { + if let Some(t) = &self.train { + let up_to = trf( + "up to {move}", + &[("move", &crate::san::show(&t.start.up_to))], + ); + return match &t.start.event { + Some(e) => format!("{e} · {up_to}"), + None => up_to, + }; + } + let g = &self.game; + let mut parts = Vec::new(); + for t in ["Event", "Site", "Date", "ECO", "Annotator"] { + if let Some(v) = g + .tag(t) + // A web address is the globe's, not text. + .filter(|v| { + !v.is_empty() && !v.chars().all(|c| c == '?' || c == '.') && !v.contains("://") + }) + { + parts.push(v.to_string()); + } + } + parts.join(" · ") + } + + /// A move made on the board or picked in the reference tab: goes to it if the + /// game has it, else adds it (undoable). + fn play_move(&mut self, m: Move, actions: &mut Vec) { + if self.train.is_some() { + self.train_move(m, actions); + return; + } + if self.play.is_some() { + self.user_move(m, actions); + return; + } + match self.game.add_move(self.cursor, m) { + Ok(id) => { + self.goto(id); + if let Some(s) = self.sound_for(id) { + actions.push(GameAction::Sound(s)); + } + } + Err(e) => actions.push(GameAction::Toast(trf("Move not added: {e}", &[("e", &e)]))), + } + } + + fn goto(&mut self, id: NodeId) { + if id != self.cursor { + // Leaving the move writes the comment being written (user-comments.md §4). + self.commit_editor(); + self.cursor = id; + self.board.clear(); + self.scroll_to_cursor = true; + } + self.preview = None; + } + + // ----- comments (docs/design/user-comments.md) ------------------------------------ + + /// «4.Ba4» / «4…Nf6» as the editor's title names the move. + fn move_name(&self, id: NodeId) -> String { + let Some((num, color)) = self.game.move_number(id) else { + return String::new(); + }; + let san = self + .game + .game_move(id) + .map(|m| m.san.as_str()) + .unwrap_or("?"); + let san = crate::san::show(san); + match color { + Color::White => format!("{num}.{san}"), + Color::Black => format!("{num}…{san}"), + } + } + + /// Opens the editor on this comment (the one open before is written first). The + /// move becomes the current one. + fn open_editor(&mut self, slot: Slot) { + if self.preview.is_some() { + return; + } + if self.editor.as_ref().is_some_and(|e| e.slot == slot) { + if let Some(e) = self.editor.as_mut() { + e.focus = true; + } + return; + } + self.commit_editor(); + let id = slot.node(); + let Some(node) = self.game.node(id) else { + return; + }; + let (original, nags, title, short) = match slot { + Slot::After(NodeId::ROOT) => ( + node.comments_after().to_vec(), + Vec::new(), + tr("Comment at the start of the game").to_owned(), + tr("At the start").to_owned(), + ), + Slot::After(_) => ( + node.comments_after().to_vec(), + node.nags().to_vec(), + trf("Comment after {move}", &[("move", &self.move_name(id))]), + trf("After {move}", &[("move", &self.move_name(id))]), + ), + Slot::Before(_) => ( + node.comments_before().to_vec(), + Vec::new(), + trf("Comment before {move}", &[("move", &self.move_name(id))]), + trf("Before {move}", &[("move", &self.move_name(id))]), + ), + }; + let text = chess_core::comment_display_text(&original); + let translated = self + .translation + .shown() + .and_then(|m| m.get(&text)) + .is_some_and(|m| matches!(m, crate::translate_ui::Mark::Translated(_))); + if matches!(slot, Slot::After(_)) && id != NodeId::ROOT { + self.goto(id); + } + self.editor = Some(CommentEditor { + slot, + initial: text.clone(), + text, + initial_nags: nags.clone(), + nags, + title, + short_title: short, + translated, + focus: true, + scroll: true, + field_id: None, + }); + } + + /// Writes the comment being written into the game (one undo step) and closes the + /// editor; nothing written when nothing changed. Also for the program: before the + /// game is left or saved. + pub fn commit_editor(&mut self) { + let Some(ed) = self.editor.take() else { return }; + if !ed.changed() { + return; + } + let id = ed.slot.node(); + let Some(node) = self.game.node(id) else { + return; + }; + match ed.slot { + Slot::After(_) => { + let original = node.comments_after().to_vec(); + let comments = if ed.text_changed() { + chess_core::with_text(&original, &ed.text) + } else { + original + }; + let _ = self.game.annotate(id, ed.nags, comments); + } + Slot::Before(_) => { + let original = node.comments_before().to_vec(); + let _ = self + .game + .set_comments_before(id, chess_core::with_text(&original, &ed.text)); + } + } + self.scroll_to_cursor = true; + } + + fn cancel_editor(&mut self) { + self.editor = None; + self.scroll_to_cursor = true; + } + + /// The editor's text field has the keyboard. + fn editor_focused(&self, ui: &Ui) -> bool { + self.editor + .as_ref() + .and_then(|e| e.field_id) + .is_some_and(|id| ui.ctx().memory(|m| m.focused() == Some(id))) + } + + /// The keys of the editor, taken before the text field sees them: Enter — done, + /// Shift+Enter — a paragraph, Esc — cancel, Ctrl+S / Ctrl+W — done and then the + /// action, Ctrl+1…6 — the move's symbol in the draft. + fn editor_keys(&mut self, ui: &Ui, actions: &mut Vec) { + if !self.editor_focused(ui) { + return; + } + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let (done, paragraph, cancel, save, back, nag) = ui.input_mut(|i| { + // Shift+Enter first: a plain Enter would match it too (an extra Shift is + // ignored by egui's key match). + let paragraph = i.consume_key(Modifiers::SHIFT, Key::Enter); + let done = !paragraph + && (i.consume_key(Modifiers::NONE, Key::Enter) + || i.consume_shortcut(&ctrl(Key::Enter))); + let cancel = i.consume_key(Modifiers::NONE, Key::Escape); + let save = i.consume_shortcut(&ctrl(Key::S)); + let back = i.consume_shortcut(&ctrl(Key::W)); + let nag = [ + Key::Num1, + Key::Num2, + Key::Num3, + Key::Num4, + Key::Num5, + Key::Num6, + ] + .into_iter() + .zip(MOVE_NAGS) + .find(|(k, _)| i.consume_shortcut(&ctrl(*k))) + .map(|(_, (nag, _, _))| nag); + (done, paragraph, cancel, save, back, nag) + }); + if let Some(nag) = nag + && let Some(ed) = self.editor.as_mut() + { + ed.nags = toggle_nag(&ed.nags, nag); + } + if paragraph && let Some(ed) = self.editor.as_mut() { + // A blank line at the cursor. + let Some(field) = ed.field_id else { return }; + let mut state = egui::TextEdit::load_state(ui.ctx(), field).unwrap_or_default(); + let at = state + .cursor + .char_range() + .map_or(ed.text.chars().count(), |r| r.primary.index.into()); + let byte = ed + .text + .char_indices() + .nth(at) + .map_or(ed.text.len(), |(b, _)| b); + ed.text.insert_str(byte, "\n\n"); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::one( + egui::text::CCursor::new(at + 2), + ))); + state.store(ui.ctx(), field); + } + if cancel { + self.cancel_editor(); + } else if done || save || back { + self.commit_editor(); + if save { + actions.push(GameAction::Save); + } + if back { + actions.push(GameAction::Back); + } + } + } + + /// A symbol put on or taken off a move at once (the menu, Ctrl+1…6): one undo step. + fn toggle_nag_on(&mut self, id: NodeId, nag: Nag) { + if id == NodeId::ROOT { + return; + } + let Some(node) = self.game.node(id) else { + return; + }; + let nags = toggle_nag(node.nags(), nag); + let comments = node.comments_after().to_vec(); + let _ = self.game.annotate(id, nags, comments); + } + + /// Deletes a comment (its board commands and clocks stay); undoable. + fn delete_comment(&mut self, slot: Slot, actions: &mut Vec) { + if self.editor.as_ref().is_some_and(|e| e.slot == slot) { + self.editor = None; + } + let id = slot.node(); + let Some(node) = self.game.node(id) else { + return; + }; + let done = match slot { + Slot::After(_) => { + let comments = chess_core::with_text(node.comments_after(), ""); + self.game.annotate(id, node.nags().to_vec(), comments) + } + Slot::Before(_) => { + let comments = chess_core::with_text(node.comments_before(), ""); + self.game.set_comments_before(id, comments) + } + }; + if done.is_ok() { + actions.push(GameAction::Toast( + tr("Comment deleted (Ctrl+Z to undo)").to_owned(), + )); + } + } + + /// An arrow or a circle drawn on the board goes into the comment of the current move + /// (`[%cal]`, `[%csl]`); the same shape again takes it off, another colour replaces it. + fn apply_shape(&mut self, drawn: board::Drawn) { + let id = self.cursor; + let Some(node) = self.game.node(id) else { + return; + }; + let (mut arrows, mut squares) = chess_core::shapes(node.comments_after()); + match drawn { + board::Drawn::Arrow(color, from, to) => { + let same = arrows.iter().position(|(_, a, b)| *a == from && *b == to); + match same { + Some(i) if arrows[i].0 == color => { + arrows.remove(i); + } + Some(i) => arrows[i].0 = color, + None => arrows.push((color, from, to)), + } + } + board::Drawn::Circle(color, sq) => { + let same = squares.iter().position(|(_, s)| *s == sq); + match same { + Some(i) if squares[i].0 == color => { + squares.remove(i); + } + Some(i) => squares[i].0 = color, + None => squares.push((color, sq)), + } + } + } + let comments = chess_core::with_shapes(node.comments_after(), &arrows, &squares); + if self + .game + .annotate(id, node.nags().to_vec(), comments) + .is_ok() + { + self.shape_drawn = true; + } + } + + /// The moves with arrows or circles in their comments, counted again after an edit. + fn shape_counts(&mut self) -> &HashMap { + let revision = self.game.revision(); + if self + .shape_counts + .as_ref() + .is_none_or(|(r, _)| *r != revision) + { + self.shape_counts = Some((revision, crate::notation::shape_counts(&self.game))); + } + &self.shape_counts.get_or_insert_default().1 + } + + /// Who this game is among those opened in the session (a hint counts a game once). + fn session_key(&self) -> String { + match &self.source { + Some(s) => format!("{}#{}", s.path.display(), s.index), + None => format!("view#{}", self.serial), + } + } + + /// Whether the hint about drawing on the board stands above the notation + /// (docs/design/tasks-42-43-2026-11-27.md §43.3). Decided once, as the notation is + /// first drawn: only where shapes go into the game, never with the translation strip + /// (then not counted either). Returns whether the hint's settings changed. + fn decide_shapes_hint( + &mut self, + hint: &mut crate::settings::Hint, + seen: &mut std::collections::HashSet, + translating: bool, + ) -> bool { + if self.shapes_hint.is_some() { + return false; + } + let possible = + !translating && self.preview.is_none() && self.play.is_none() && self.train.is_none(); + let key = self.session_key(); + let fresh = !seen.contains(&key); + let show = possible && hint.offer(fresh); + if show { + seen.insert(key); + } + self.shapes_hint = Some(show); + show && fresh + } + + /// The hint's strip: the translation strip's look, closed for good by its ×; dimmed + /// (its height kept) while the board shows an engine line and takes no drawing. + /// Returns whether the hint's settings changed. + fn shapes_hint_strip( + &mut self, + ui: &mut Ui, + hint: &mut crate::settings::Hint, + dim: bool, + ) -> bool { + let mut closed = false; + egui::Frame::new() + .fill(ui.visuals().faint_bg_color) + .inner_margin(egui::Margin::symmetric(8, 4)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + let row_h = ui.spacing().interact_size.y; + ui.horizontal_top(|ui| { + let close_w = 22.0 + ui.spacing().item_spacing.x; + ui.allocate_ui_with_layout( + vec2((ui.available_width() - close_w).max(120.0), 0.0), + egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), + |ui| { + ui.set_min_height(row_h); + ui.add_enabled_ui(!dim, |ui| { + ui.add( + egui::Label::new(tr( + "Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game.", + )) + .wrap(), + ) + .on_hover_text(tr( + "No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes.", + )); + }); + }, + ); + ui.allocate_ui_with_layout( + vec2(22.0, row_h), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Don't show again")) + .clicked() + { + closed = true; + } + }, + ); + }); + }); + if closed { + hint.done = true; + self.shapes_hint = Some(false); + } + closed + } + + /// Assessment of the move that led to the current position, for the board: the + /// engine's judgement when the game analysis is shown, otherwise the author's + /// `!`/`?` symbol. + fn badge(&self) -> Option { + let square = match self.game.game_move(self.cursor)?.kind { + MoveKind::Normal(m) => move_squares(&m)?.1, + MoveKind::Null => return None, + }; + if self.review.visible + && let Some(mark) = self.review.analysis.marks.get(&self.cursor) + { + return Some(board::Badge { + square, + text: crate::review::judgement_symbol(mark.judgement), + color: crate::review::judgement_color(mark.judgement), + }); + } + let nag = self + .game + .node(self.cursor)? + .nags() + .iter() + .copied() + .find(|n| n.is_move_assessment())?; + Some(board::Badge { + square, + text: nag.symbol()?, + color: crate::notation::assessment_color(nag)?, + }) + } + + fn sound_for(&self, id: NodeId) -> Option { + let mv = self.game.game_move(id)?; + let pos = self.game.position(id)?; + Some(if pos.is_checkmate() { + Sound::Checkmate + } else if pos.is_check() { + Sound::Check + } else if matches!(mv.kind, MoveKind::Normal(m) if m.is_capture()) { + Sound::Capture + } else { + Sound::Move + }) + } + + /// `input_enabled` is false while a modal dialog is open over the game. + pub fn show( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + analysis: &mut Analysis, + reference: &mut crate::reference::Reference, + hub: &mut crate::translate_ui::Hub, + input_enabled: bool, + ) -> Vec { + let mut actions = Vec::new(); + self.translation.update(ui.ctx(), &self.game, settings, hub); + let reviewed = self.review.poll(); + if reviewed { + actions.push(GameAction::ResumeLive); + if let Some(e) = &self.review.error { + actions.push(GameAction::Toast(e.clone())); + } + } + self.review.refresh(&self.game); + if reviewed + && self.review.error.is_none() + && !self.game.is_modified() + && self.review.missing() == 0 + && let Some(src) = &self.source + { + actions.push(GameAction::Reviewed { + path: src.path.clone(), + index: src.index, + entry: crate::brilliant::entry_of(&self.review.analysis, &self.game), + }); + } + if analysis.status == Status::Running + && let Some(e) = settings.active_engine() + { + self.review.note_live_speed(analysis.nps, e.threads); + } + self.play_tick(ui.ctx(), &mut actions); + if input_enabled && self.play_leave.is_none() { + self.editor_keys(ui, &mut actions); + self.keyboard(ui, &mut actions); + } + + // The cursor can change inside any panel; re-bind the engine before each use of its lines. + self.sync_analysis(analysis); + let databases = settings.databases.clone(); + egui::Panel::top("game_header").show(ui, |ui| self.header(ui, &databases, &mut actions)); + // Side by side or stacked (docs/design/narrow-windows.md §3): decided by the size + // of the window alone, for the notation tab with the evaluation bar and no graph, + // so that switching a tab, the engine or the report never rearranges the screen. + let width = ui.available_width(); + let height = ui.available_height(); + let graph = self.review.visible && (self.review.has_data() || self.review.running()); + let graph_h = if graph { + (height * 0.14).clamp(80.0, 130.0) + 8.0 + } else { + 0.0 + }; + let board_side = (height - 16.0).min(width - SIDE_MIN - EVAL_BAR - 24.0); + let board_stack = (width - 16.0 - EVAL_BAR).min(height - STACK_BOTTOM_MIN - 16.0); + let stacked = board_stack >= 1.25 * board_side; + let least = if self.side_tab == SideTab::Reference { + REF_MIN + } else { + SIDE_MIN + }; + let side = if stacked { + // The notation under the board, as high as the board leaves; dragging its + // edge up gives the notation more and the board less. + // The engine's lines and settings come on top of the notation's least + // part (their height as last drawn); the board gives way for them. + let engine = + egui::containers::panel::PanelState::load(ui.ctx(), egui::Id::new("engine_panel")) + .map_or(0.0, |p| (p.size().y - ENGINE_ROW).max(0.0)); + let most = (height - BOARD_MIN - graph_h - 16.0).max(STACK_BOTTOM_MIN); + let bottom_least = (STACK_BOTTOM_MIN + engine).min(most); + let rest = (height - board_stack - graph_h - 16.0).clamp(bottom_least, most); + egui::Panel::bottom("game_side_stacked") + .resizable(true) + .default_size(rest) + .size_range(bottom_least..=most) + .show(ui, |ui| { + self.side_panel(ui, settings, analysis, reference, hub, &mut actions) + }) + } else { + // The board takes the full height of the window: the side panel is never + // wider than what is left beside it (the user can make it narrower, not + // wider), nor than leaves the board its least size. The reference tab has + // two wide tables and its own width (egui remembers each). + let board = height - graph_h - 16.0; + let most = (width - BOARD_MIN - EVAL_BAR - 24.0).max(least); + let room = (width - board - 24.0).clamp(least, most); + let (side_id, side_width) = if self.side_tab == SideTab::Reference { + ("game_side_ref", room.min(1100.0)) + } else { + ("game_side", (width * 0.4).clamp(260.0, 460.0).min(room)) + }; + egui::Panel::right(side_id) + .resizable(true) + .default_size(side_width) + .size_range(least..=most) + .show(ui, |ui| { + self.side_panel(ui, settings, analysis, reference, hub, &mut actions) + }) + }; + crate::widgets::check_panel("game_side", &side.response); + self.sync_analysis(analysis); + let hover = (self.side_tab == SideTab::Reference) + .then(|| reference.hover()) + .flatten(); + egui::CentralPanel::default().show(ui, |ui| { + self.board_area(ui, &*settings, analysis, hover, &mut actions) + }); + // Drawn on the board: the hint has done its job (gone after the button is let go). + if std::mem::take(&mut self.shape_drawn) { + let hint = &mut settings.hints.board_shapes; + if !hint.done { + hint.done = true; + actions.push(GameAction::HintsChanged); + } + if self.shapes_hint == Some(true) { + self.shapes_hint = Some(false); + ui.ctx().request_repaint(); + } + } + self.sync_analysis(analysis); + + // «Analyse»: at once — the search is the same for everyone, nothing to choose. + if std::mem::take(&mut self.review_asked) { + if self.engine_busy { + actions.push(GameAction::Toast( + self.engine_busy_why.clone().unwrap_or_else(|| { + tr("Opening errors are being searched — wait or stop it in the report") + .to_owned() + }), + )); + } else { + self.start_review(false, ui.ctx(), &mut actions); + } + } + + // A line from the clipboard: pasted, or asked about. + if let Some(text) = self.clipboard.as_ref().and_then(|r| r.poll()) { + self.clipboard = None; + self.paste_request = Some(text.unwrap_or_default()); + } + if let Some(text) = self.paste_request.take() { + self.paste_text(&text, &mut actions); + } + self.paste_question(ui.ctx(), &mut actions); + + // Leaving during a game asks first; the question itself. + self.guard_leaving(&mut actions); + self.leave_question(ui.ctx(), &mut actions); + + if self.show_diagnostics { + let mut open = true; + egui::Window::new(tr("PGN compatibility")) + .open(&mut open) + .default_width(520.0) + .show(ui.ctx(), |ui| { + egui::ScrollArea::vertical() + .max_height(400.0) + .show(ui, |ui| { + for d in &self.diagnostics { + let (icon, color) = match d.severity { + Severity::Info => ("ℹ", ui.visuals().weak_text_color()), + Severity::Warning => ("âš ", ui.visuals().warn_fg_color), + Severity::Error => ("✖", ui.visuals().error_fg_color), + }; + let line = d + .location + .as_ref() + .map(|l| trf("line {n}: ", &[("n", &l.line)])) + .unwrap_or_default(); + ui.label( + RichText::new(format!("{icon} {line}{}", d.message)) + .color(color), + ); + } + }); + }); + self.show_diagnostics = open; + } + self.scroll_to_cursor = false; + actions + } + + /// Starts the game analysis with Stockfish 19 (ChessPenguin's, or the user's that + /// searches the same, `review_engine`); without it, the app finds one or offers to + /// download ours. + fn start_review(&mut self, full: bool, ctx: &egui::Context, actions: &mut Vec) { + let Some(path) = crate::review_engine::engine() else { + actions.push(GameAction::NeedEngine { full }); + return; + }; + if self.review.start(&self.game, &path, full, ctx) { + actions.push(GameAction::PauseLive); + self.side_tab = SideTab::Report; + } else if let Some(e) = &self.review.error { + actions.push(GameAction::Toast(e.clone())); + } else { + actions.push(GameAction::Toast( + tr("Every position is already evaluated").into(), + )); + } + } + + /// Toolbar button: start, progress with cancel, or show/hide the report. + fn review_button(&mut self, ui: &mut Ui, actions: &mut Vec) { + let big = |s: &str| RichText::new(s).size(18.0); + if let Some((done, total)) = self.review.progress() { + ui.add( + egui::ProgressBar::new(done as f32 / total.max(1) as f32) + .desired_width(70.0) + .text(format!("{done}/{total}")), + ) + .on_hover_text(tr("Game analysis")); + if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Stop the game analysis")) + .clicked() + { + self.review.cancel(); + actions.push(GameAction::ResumeLive); + } + } else if self.review.has_data() { + ui.toggle_value(&mut self.review.visible, big("📈")) + .on_hover_text(tr( + "Report: show or hide the evaluation graph and the report (Shift+A)", + )); + } else if review_colored(ui, !self.engine_busy, |ui| { + ui.add_enabled(!self.engine_busy, egui::Button::new(big("📈"))) + }) + .on_hover_text(format!( + "{}\n{}", + tr("Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)"), + self.review.estimate() + )) + .on_disabled_hover_text(self.engine_busy_why.clone().unwrap_or_else(|| { + tr("Opening errors are being searched — wait or stop it in the report").to_owned() + })) + .clicked() + { + self.review_asked = true; + } + } + + /// Keeps the engine bound to the game cursor (never to the preview). Cheap when unchanged. + fn sync_analysis(&self, analysis: &mut Analysis) { + if !analysis.is_on() { + return; + } + if let (Some(h), Some(pos)) = ( + self.game.engine_history(self.cursor), + self.game.position(self.cursor), + ) { + let ep = match h.start_fen { + None => uci::EnginePosition::startpos(h.moves), + Some(fen) => uci::EnginePosition::fen(fen, h.moves), + }; + analysis.set_position(pos, ep); + } + } + + fn header( + &mut self, + ui: &mut Ui, + databases: &[std::path::PathBuf], + actions: &mut Vec, + ) { + ui.add_space(4.0); + let warnings = self + .diagnostics + .iter() + .filter(|d| d.severity >= Severity::Warning) + .count(); + let notes = (!self.diagnostics.is_empty()).then(|| { + if warnings > 0 { + RichText::new(format!("âš  {warnings}")).color(ui.visuals().warn_fg_color) + } else { + RichText::new(format!("ℹ {}", self.diagnostics.len())).weak() + } + }); + let back_to = self.previous.as_ref().map(|t| { + if self.previous_prep { + tr("⬅ Back to preparation").to_owned() + } else { + trf("⬅ Back to {game}", &[("game", t)]) + } + }); + // The buttons are measured first: the title gets what they leave (shortened with + // "…"; the result always shows). When it would get under 160 pt, the buttons + // around it give up their words for their icons (the words go to the tooltips). + let gap = ui.spacing().item_spacing.x; + let button = |ui: &Ui, text: &str| { + text_width(ui, text, egui::TextStyle::Button) + + 2.0 * ui.spacing().button_padding.x + + gap + }; + let left = |compact: bool| { + button(ui, tr("⬅ Library")) + + back_to + .as_deref() + .map_or(0.0, |b| button(ui, if compact { "⬅" } else { b })) + + gap + + 2.0 * gap + }; + let right = |compact: bool| { + button(ui, if compact { "âš™" } else { tr("âš™ Settings") }) + + self.update.as_deref().map_or(0.0, |v| button(ui, v)) + + if cfg!(web) { + button( + ui, + if compact { + "⇩" + } else { + tr("⇩ Download PGN") + }, + ) + } else { + 0.0 + } + + if crate::platform::CAPS.reference { + button(ui, "â�·") + + button( + ui, + if compact { + "ðŸ”�" + } else { + tr("ðŸ”� Find in database") + }, + ) + } else { + 0.0 + } + + notes.as_ref().map_or(0.0, |n| button(ui, n.text())) + }; + // The result, or during a game against the computer its time control («5+3», «∞») + // in the same place. + let (result, result_hint) = match result_label(self.game.result()) { + Some(r) => (Some(r.to_owned()), result_hint(self.game.result())), + None => match &self.play { + Some(s) => match &s.clock { + Some(c) => (Some(c.control.label()), tr("Time control")), + None => (Some("∞".to_owned()), tr("Unlimited")), + }, + None => (None, ""), + }, + }; + // The game's page on Lichess or Chess.com: a globe after the result. + let link = self.link(); + let link_w = if link.is_some() { + ui.painter() + .layout_no_wrap( + "ðŸŒ�".to_owned(), + egui::TextStyle::Button.resolve(ui.style()), + Color32::WHITE, + ) + .size() + .x + + 2.0 * ui.spacing().button_padding.x + + gap + } else { + 0.0 + }; + let result_w = link_w + + result.as_ref().map_or(0.0, |r| { + ui.painter() + .layout_no_wrap( + format!(" {r} "), + egui::FontId::proportional(15.0), + Color32::WHITE, + ) + .size() + .x + + gap + }); + let row = ui.available_width(); + let compact = row - left(false) - right(false) - result_w < 160.0; + let title_room = (row - left(compact) - right(compact)).max(0.0); + ui.horizontal(|ui| { + if ui + .button(if compact { "⬅" } else { tr("⬅ Library") }) + .on_hover_text(if self.previous_prep { + tr("Back to the game list") + } else if self.previous.is_some() { + tr("Back to the game list (Ctrl+W)") + } else { + tr("Back to the game list (Esc, Ctrl+W)") + }) + .clicked() + { + actions.push(GameAction::Back); + } + if let Some(b) = &back_to + && ui + .button(if compact { "⬅" } else { b.as_str() }) + .on_hover_text({ + let hint = if self.previous_prep { + tr("The preparation this game was opened from, as you left it (Esc, Ctrl+W)") + } else { + tr("The game this one was opened from, as you left it (Esc)") + }; + if compact { format!("{b}\n{hint}") } else { hint.to_owned() } + }) + .clicked() + { + actions.push(GameAction::ReturnToPrevious); + } + ui.separator(); + let height = ui.available_height(); + ui.allocate_ui_with_layout( + vec2(title_room, height), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.set_width(title_room); + ui.horizontal(|ui| { + ui.set_max_width(title_room); + // The unsaved mark first: it must not be truncated away. + let mut mark_w = 0.0; + if self.game.is_modified() && self.play.is_none() { + let mark = ui + .label(RichText::new("•").strong().size(16.0)) + .on_hover_text(tr("Unsaved changes")); + mark_w = mark.rect.width() + ui.spacing().item_spacing.x; + } + let title = self.title(); + ui.allocate_ui(vec2((title_room - result_w - mark_w).max(0.0), height), |ui| { + // The title opens the game's data (players, event, date…). + let label = egui::Label::new(RichText::new(&title).strong().size(16.0)) + .truncate(); + if self.play.is_some() || self.train.is_some() { + ui.add(label); + } else if ui + .add(label.sense(Sense::click())) + .on_hover_text(tr("Game data (F2)")) + .on_hover_cursor(egui::CursorIcon::PointingHand) + .clicked() + { + actions.push(GameAction::EditGameData); + } + }); + if let Some(result) = &result { + ui.label( + RichText::new(format!(" {result} ")) + .strong() + .size(15.0) + .background_color(ui.visuals().widgets.inactive.weak_bg_fill), + ) + .on_hover_text(result_hint); + } + if let Some(l) = &link + && ui.button("ðŸŒ�").on_hover_text(l.hint()).clicked() + { + self.open_link(ui.ctx(), l); + } + }); + let sub: Vec = self + .source_line() + .into_iter() + .chain(Some(self.subtitle()).filter(|s| !s.is_empty())) + .collect(); + if !sub.is_empty() { + ui.add(egui::Label::new(RichText::new(sub.join(" · ")).weak()).truncate()); + } + }, + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::settings_button(ui, compact).clicked() { + actions.push(GameAction::OpenSettings); + } + #[cfg(not(web))] + if let Some(v) = &self.update + && crate::widgets::update_button(ui, v).clicked() + { + actions.push(GameAction::OpenUpdate); + } + #[cfg(web)] + if ui + .button(if compact { "⇩" } else { tr("⇩ Download PGN") }) + .on_hover_text(tr( + "Download the game as a PGN file: the browser puts it where it puts downloads", + )) + .clicked() + { + actions.push(GameAction::DownloadPgn); + } + // Find the position in a database: the last chosen one, or another. + let searchable = self.search_line().is_some(); + let why = tr("After a null move (--) this is a teaching scheme, not a position of a game: it is not searched"); + // Not during a game against Maia: it would leave the game. + let playing = self.play.is_some() || self.train.is_some(); + if !playing && crate::platform::CAPS.reference { ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| { + ui.menu_button("â�·", |ui| { + for db in databases { + let name = db + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + if ui.button(name).clicked() { + actions.push(GameAction::FindPosition(Some(db.clone()))); + ui.close(); + } + } + }) + .response + .on_hover_text(tr("Find in another database")); + if ui + .button(if compact { "ðŸ”�" } else { tr("ðŸ”� Find in database") }) + .on_hover_text(tr("Find this position in a database (Ctrl+Shift+F)")) + .on_disabled_hover_text(if searchable { tr("Add a database first") } else { why }) + .clicked() + { + actions.push(GameAction::FindPosition(None)); + } + }); } + if let Some(text) = notes + && ui + .button(text) + .on_hover_text(tr("PGN compatibility notes")) + .clicked() + { + self.show_diagnostics = true; + } + }); + }); + ui.add_space(4.0); + } + + fn board_area( + &mut self, + ui: &mut Ui, + settings: &Settings, + analysis: &Analysis, + reference_hover: Option, + actions: &mut Vec, + ) { + self.train_tick(ui.ctx()); + let preview_pos = self.preview.as_ref().map(|p| p.position()); + let Some(game_pos) = self.game.position(self.cursor) else { + return; + }; + let pos: Chess = preview_pos.unwrap_or_else(|| game_pos.clone()); + let over = game_over(game_pos); + + let mut arrows = Vec::new(); + let mut circles = Vec::new(); + let last_move; + if let Some(p) = &self.preview { + last_move = p + .shown + .checked_sub(1) + .and_then(|i| p.moves.get(i)) + .and_then(move_squares); + if let Some(next) = p.moves.get(p.shown).and_then(move_squares) { + arrows.push(Arrow { + from: next.0, + to: next.1, + color: Color32::from_rgba_unmultiplied(0, 48, 136, 160), + weight: 1.0, + }); + } + } else { + last_move = match self.game.game_move(self.cursor).map(|m| m.kind) { + Some(MoveKind::Normal(m)) => move_squares(&m), + _ => None, + }; + if let Some(node) = self.game.node(self.cursor) { + for c in node.comments_after() { + for part in parse_comment(c) { + match part { + CommentPart::Annotation(Annotation::Arrows(list)) => { + for (color, from, to) in list { + arrows.push(Arrow { + from, + to, + color: shape_color(color), + weight: 0.9, + }); + } + } + CommentPart::Annotation(Annotation::Squares(list)) => { + circles + .extend(list.into_iter().map(|(c, sq)| (sq, shape_color(c)))); + } + _ => {} + } + } + } + } + // With the live engine on, only its arrows are drawn: two sources of engine + // arrows on one board would overlap and compete. + if self.review.visible && !analysis.is_on() { + // The opponent's best reply to a marked move (strong) and the best answer to it. + let line = self.review.refutation(self.cursor, &self.game); + for (k, m) in line.iter().enumerate() { + if let Some(sq) = move_squares(m) { + engine_arrow( + &mut arrows, + sq, + if k == 0 { 200 } else { 100 }, + if k == 0 { 1.0 } else { 0.75 }, + ); + } + } + } + if settings.show_best_arrow && analysis.best().is_some() { + for (i, line) in analysis.lines.iter().take(3).enumerate() { + if let Some(sq) = line.moves.first().and_then(move_squares) { + let alpha = if i == 0 { 200 } else { 100 }; + engine_arrow(&mut arrows, sq, alpha, if i == 0 { 1.0 } else { 0.7 }); + } + } + } + } + + // A continuation under the pointer in the reference tab (blue, like the library's). + if self.preview.is_none() + && let Some(m) = reference_hover.and_then(|u| u.to_move(&pos).ok()) + && let Some((from, to)) = move_squares(&m) + { + arrows.push(Arrow { + from, + to, + color: crate::board_search::PREVIEW_ARROW, + weight: 1.0, + }); + } + + // Learning an opening: a wrong move stands on the board for a moment, in red; a + // hint is the arrow of the right move. + let flash = self + .train + .as_ref() + .and_then(|t| t.flash.as_ref()) + .map(|f| (f.after.clone(), (f.from, f.to))); + let alert = flash.as_ref().map(|(_, sq)| *sq); + let last_move = flash.as_ref().map_or(last_move, |(_, sq)| Some(*sq)); + let pos = flash.map_or(pos, |(p, _)| p); + if let Some(t) = &self.train + && t.hint + && self.cursor == self.game.line_end(NodeId::ROOT) + && let Some(sq) = t + .start + .line + .get(self.game.mainline().len()) + .and_then(move_squares) + { + arrows.push(Arrow { + from: sq.0, + to: sq.1, + color: shape_color(ShapeColor::Green), + weight: 1.0, + }); + } + + // Center the eval bar + board horizontally between the left edge and the side panel. + let area = ui.available_rect_before_wrap(); + let show_bar = analysis.is_on(); + let bar_w = if show_bar { 18.0 } else { 0.0 }; + let gap = if show_bar { 8.0 } else { 0.0 }; + let show_graph = self.review.visible && (self.review.has_data() || self.review.running()); + let graph_h = if show_graph { + (area.height() * 0.14).clamp(80.0, 130.0) + } else { + 0.0 + }; + let graph_gap = if show_graph { 8.0 } else { 0.0 }; + let side = (area.width() - bar_w - gap) + .min(area.height() - graph_h - graph_gap) + .max(BOARD_MIN); + let total = bar_w + gap + side; + let left = area.left() + ((area.width() - total) / 2.0).max(0.0).floor(); + let group = egui::Rect::from_min_size(egui::pos2(left, area.top()), vec2(total, side)); + let builder = egui::UiBuilder::new() + .max_rect(group) + .layout(egui::Layout::left_to_right(egui::Align::Min)); + ui.scope_builder(builder, |ui| { + ui.spacing_mut().item_spacing.x = gap; + if show_bar { + let (rect, _) = ui.allocate_exact_size(vec2(bar_w, side), Sense::hover()); + let frac = match over { + Some(GameOver::Mated(loser)) => { + if loser == Color::White { + 0.0 + } else { + 1.0 + } + } + Some(GameOver::Draw(_)) => 0.5, + None => analysis + .best() + .map(|l| analysis::bar_fraction(&l.score)) + .unwrap_or(0.5), + }; + let frac = if self.flipped { 1.0 - frac } else { frac }; + let painter = ui.painter(); + let (top_c, bottom_c) = if self.flipped { + (Color32::from_gray(235), Color32::from_gray(40)) + } else { + (Color32::from_gray(40), Color32::from_gray(235)) + }; + painter.rect_filled(rect, 2.0, top_c); + let split = rect.bottom() - rect.height() * frac; + painter.rect_filled( + egui::Rect::from_min_max(egui::pos2(rect.left(), split), rect.max), + 2.0, + bottom_c, + ); + painter.line_segment( + [ + egui::pos2(rect.left(), rect.center().y), + egui::pos2(rect.right(), rect.center().y), + ], + egui::Stroke::new(1.0, Color32::from_rgb(200, 60, 60)), + ); + } + ui.allocate_ui(vec2(side, side), |ui| { + let view = BoardView { + pos: &pos, + orientation: if self.flipped { + Color::Black + } else { + Color::White + }, + last_move, + arrows: &arrows, + circles: &circles, + badge: if self.preview.is_none() { + self.badge() + } else { + None + }, + interactive: self.preview.is_none() + && self.user_may_move() + && self.train.as_ref().is_none_or(|t| { + !t.done + && t.flash.is_none() + && self.cursor == self.game.line_end(NodeId::ROOT) + }), + temporary_shapes: self.play.is_some() || self.train.is_some(), + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: settings.animation.seconds(), + premove: self.premove_side(), + // Training: the piece is always chosen (a queen for a knight is a mistake). + auto_queen: settings.auto_queen && self.train.is_none(), + alert, + }; + if let Some(m) = view.show(ui, &mut self.board) { + self.play_move(m, actions); + } + if let Some(drawn) = self.board.take_shape() + && self.preview.is_none() + && self.play.is_none() + && self.train.is_none() + { + self.apply_shape(drawn); + } + }); + }); + if show_graph { + let graph_rect = egui::Rect::from_min_size( + egui::pos2(left, area.top() + side + graph_gap), + vec2(total, graph_h), + ); + let target = ui + .scope_builder(egui::UiBuilder::new().max_rect(graph_rect), |ui| { + self.review + .graph(ui, graph_rect.size(), self.cursor, &self.game) + }) + .inner; + if let Some(id) = target { + self.goto(id); + } + } + } + + fn side_panel( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + analysis: &mut Analysis, + reference: &mut crate::reference::Reference, + hub: &mut crate::translate_ui::Hub, + actions: &mut Vec, + ) { + if self.play.is_some() { + self.play_side(ui, settings, analysis, reference, hub, actions); + return; + } + if self.train.is_some() { + self.train_side(ui, actions); + return; + } + if self.play_end.is_some() { + egui::Panel::top("play_result").show(ui, |ui| self.result_strip(ui, actions)); + } + egui::Panel::bottom("game_toolbar").show(ui, |ui| self.toolbar(ui, actions)); + egui::Panel::top("engine_panel") + .show(ui, |ui| self.engine_panel(ui, settings, analysis, actions)); + let report = self.review.visible && (self.review.has_data() || self.review.running()); + if !report && self.side_tab == SideTab::Report { + self.side_tab = SideTab::Notation; + } + egui::CentralPanel::default().show(ui, |ui| { + ui.horizontal(|ui| { + ui.selectable_value(&mut self.side_tab, SideTab::Notation, tr("Notation")); + if crate::platform::CAPS.reference { + ui.selectable_value(&mut self.side_tab, SideTab::Reference, tr("Reference")) + .on_hover_text(tr("What was played in this position in a database")); + } + if report { + ui.selectable_value(&mut self.side_tab, SideTab::Report, tr("Report")); + } + }); + ui.separator(); + if self.side_tab == SideTab::Reference { + let source = self.source.as_ref().map(|s| (s.path.as_path(), s.index)); + let action = egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| { + reference.ui( + ui, + &self.game, + self.cursor, + settings.reference_db.as_deref(), + source, + ) + }) + .inner; + match action { + Some(RefAction::Play(m)) => self.play_move(m, actions), + Some(RefAction::Goto(id)) => self.goto(id), + Some(RefAction::Choose(p)) => actions.push(GameAction::ReferenceChoose(p)), + Some(RefAction::Load(p)) => actions.push(GameAction::ReferenceLoad(p)), + Some(RefAction::OpenGame(p, i, at)) => { + actions.push(GameAction::OpenGame(p, i, at)) + } + Some(RefAction::FindInLibrary(p)) => { + actions.push(GameAction::FindPosition(Some(p))) + } + None => {} + } + return; + } + if self.side_tab == SideTab::Report { + let action = egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| self.review.report_ui(ui, &self.game)) + .inner; + match action { + Some(ReportAction::Goto(id)) => self.goto(id), + Some(ReportAction::Write) => { + let n = self.review.write_to_game(&mut self.game); + actions.push(GameAction::Toast(trf( + "Analysis written to the game: {n} marked moves (Ctrl+Z to undo)", + &[("n", &n)], + ))); + } + Some(ReportAction::Update) => self.start_review(false, ui.ctx(), actions), + Some(ReportAction::Analyse) => self.start_review(true, ui.ctx(), actions), + None => {} + } + return; + } + let strip_top = ui.cursor().top(); + let strip = if crate::platform::CAPS.translation { + self.translation.strip(ui, settings, hub) + } else { + None + }; + let translating = ui.cursor().top() > strip_top; + let seen_id = egui::Id::new("shapes_hint_games"); + let mut seen: std::collections::HashSet = + ui.data_mut(|d| d.get_temp(seen_id)).unwrap_or_default(); + let mut hints_changed = + self.decide_shapes_hint(&mut settings.hints.board_shapes, &mut seen, translating); + ui.data_mut(|d| d.insert_temp(seen_id, seen)); + if self.shapes_hint == Some(true) && !translating { + let dim = self.preview.is_some(); + hints_changed |= self.shapes_hint_strip(ui, &mut settings.hints.board_shapes, dim); + } + if hints_changed { + actions.push(GameAction::HintsChanged); + } + match strip { + Some(crate::translate_ui::StripAction::OpenSettings) => { + actions.push(GameAction::OpenTranslationSettings) + } + Some(crate::translate_ui::StripAction::Toast(t)) => { + actions.push(GameAction::Toast(t)) + } + None => {} + } + if std::mem::take(&mut self.translate_now) { + self.translation.translate(ui.ctx(), settings, hub); + } + self.shape_counts(); + self.debug_best_tick(ui.ctx()); + egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| { + let resp = Notation { + game: &self.game, + cursor: self.cursor, + scroll_to_cursor: self.scroll_to_cursor, + marks: self.review.visible.then_some(&self.review.analysis.marks), + preview: self + .preview + .as_ref() + .map(|p| (p.base, p.san.as_slice(), p.shown)), + translations: self.translation.shown(), + editor: self.editor.as_mut(), + read_only: self.play.is_some(), + dim_until: None, + mistakes: None, + shapes: self.shape_counts.as_ref().map(|(_, c)| c), + } + .show(ui); + if let Some(id) = resp.clicked { + self.goto(id); + } + match resp.editor { + Some(EditorOutcome::Done) => self.commit_editor(), + Some(EditorOutcome::Cancel) => self.cancel_editor(), + None => {} + } + if resp.insert_preview { + self.insert_preview(actions); + } + if let Some(slot) = resp.edit { + self.open_editor(slot); + } + if let Some(slot) = resp.delete { + self.delete_comment(slot, actions); + } + if let Some((id, nag)) = resp.nag { + self.toggle_nag_on(id, nag); + } + if resp.best.is_some() { + self.commit_editor(); + } + if let Some((id, shown)) = resp.best + && let Some(mark) = self.review.analysis.marks.get(&id) + && let Some(root) = self.game.position(mark.base) + && !mark.best.is_empty() + { + self.cursor = mark.base; + self.scroll_to_cursor = false; + self.board.clear(); + self.preview = Some(Preview { + base: mark.base, + root: root.clone(), + moves: mark.best.clone(), + san: mark.best_san.clone(), + shown: shown.min(mark.best.len()), + }); + } + if let Some((_, NotationCommand::Paste)) = resp.context { + self.paste_clipboard(ui.ctx()); + } else if let Some((id, NotationCommand::PlayFrom)) = resp.context { + self.play_from(id, actions); + } else if let Some((id, NotationCommand::Train)) = resp.context { + #[cfg(not(web))] + self.add_repertoire_from(id, actions); + #[cfg(web)] + let _ = id; + } else if let Some((id, cmd)) = resp.context { + let result = match cmd { + NotationCommand::Paste + | NotationCommand::PlayFrom + | NotationCommand::Train => Ok(self.cursor), + NotationCommand::Promote => { + self.game.promote_variation(id).map(|_| self.cursor) + } + NotationCommand::Delete => self.game.delete_variation(id), + }; + match result { + Ok(cursor) => { + // Deleting may detach the cursor; fall back to the returned parent. + let c = if self.game.is_attached(self.cursor) { + self.cursor + } else { + cursor + }; + self.goto(c); + } + Err(e) => actions.push(GameAction::Toast(e.to_string())), + } + } + }); + }); + } + + fn engine_panel( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + analysis: &mut Analysis, + actions: &mut Vec, + ) { + ui.add_space(4.0); + let mut below = None; + ui.horizontal(|ui| { + let mut on = analysis.is_on(); + let label = if on { + tr("Analysis: on") + } else { + tr("Analysis: off") + }; + if ui + .toggle_value(&mut on, label) + .on_hover_text(tr("Turn the engine on/off (L)")) + .changed() + { + actions.push(GameAction::ToggleEngine); + } + match self.game.position(self.cursor).and_then(game_over) { + Some(over) if analysis.is_on() => { + ui.label(RichText::new(over.label()).strong().size(18.0)); + } + _ => { + if let Some(best) = analysis.best() { + ui.label( + RichText::new(analysis::format_eval(&best.score)) + .strong() + .size(20.0), + ); + } else if analysis.is_on() { + // As tall as the evaluation that is coming: the row keeps its + // height between two positions. + ui.label(RichText::new("…").strong().size(20.0).weak()); + } + } + } + // The engine's name and how it goes: beside the evaluation (two small lines, + // or one centred line when there is no status); in a narrow panel, on a line + // of their own under the row, shortened. + let name = if analysis.is_on() { + analysis.engine_name.clone() + } else { + settings + .active_engine() + .map(|e| e.name.clone()) + .unwrap_or_else(|| tr("No engine selected").into()) + }; + let status = match &analysis.status { + Status::Starting => Some(RichText::new(tr("starting…")).small().weak()), + Status::Running => { + let depth = analysis.best().map(|l| l.depth).unwrap_or(0); + let tail = if analysis.finished { + tr(" · done").to_string() + } else { + trf( + " · {n} Mn/s", + &[("n", &format!("{:.1}", analysis.nps as f64 / 1e6))], + ) + }; + Some( + RichText::new(format!("{}{tail}", trf("Depth {n}", &[("n", &depth)]))) + .small() + .weak(), + ) + } + Status::Failed(e) => { + Some(RichText::new(e).small().color(ui.visuals().error_fg_color)) + } + Status::Off => self.review.running().then(|| { + RichText::new(tr("paused: the game is being analysed")) + .small() + .weak() + }), + }; + let small = |t: &str| text_width(ui, t, egui::TextStyle::Small); + let block = small(&name).max(status.as_ref().map_or(0.0, |s| small(s.text()))); + let gear = ui + .painter() + .layout_no_wrap("âš™".into(), egui::FontId::proportional(18.0), Color32::WHITE) + .size() + .x + + 2.0 * ui.spacing().button_padding.x + + ui.spacing().item_spacing.x; + let beside = block + ui.spacing().item_spacing.x <= ui.available_width() - gear; + if beside { + match &status { + Some(st) => { + ui.vertical(|ui| { + ui.label(RichText::new(&name).small()); + ui.label(st.clone()); + }); + } + None => { + ui.label(RichText::new(&name).small()); + } + } + } else { + below = Some((name, status)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.toggle_value( + &mut self.engine_settings_open, + RichText::new("âš™").size(18.0), + ) + .on_hover_text(tr("Engine settings")); + }); + }); + if let Some((name, status)) = below { + ui.horizontal(|ui| { + let name = RichText::new(name).small(); + match status { + Some(st) => { + ui.label(name); + ui.add(egui::Label::new(st).truncate()); + } + None => { + ui.add(egui::Label::new(name).truncate()); + } + } + }); + } + if self.engine_settings_open { + engine_settings(ui, settings, actions); + } + if analysis.is_on() { + let base = self.cursor; + let root = self.game.position(base).cloned(); + let lines: Vec = analysis.lines.clone(); + let mut insert = false; + for line in &lines { + let previewed = self + .preview + .as_ref() + .is_some_and(|p| p.base == base && p.san == line.san); + let row = ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 3.0; + // The line being stepped through on the board: added from here. + if previewed + && ui + .small_button(tr("+ Add as variation")) + .on_hover_text(tr( + "Puts the line into the game as a variation (Ctrl+Z to undo)", + )) + .clicked() + { + insert = true; + } + ui.label( + RichText::new(analysis::format_eval(&line.score)) + .strong() + .monospace(), + ); + let start_num = root.as_ref().map(|p| (p.fullmoves().get(), p.turn())); + // No bar popping up over the next line: a long line is cut at the + // edge (it still scrolls with Shift+wheel or by dragging). + egui::ScrollArea::horizontal() + .id_salt(("pv", line.multipv)) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) + .show(ui, |ui| { + ui.horizontal(|ui| { + for (i, san) in line.san.iter().enumerate().take(14) { + let label = match start_num { + Some((n, turn)) => { + let ply = i as u32 + u32::from(turn == Color::Black); + let num = n + ply / 2; + if ply.is_multiple_of(2) { + format!("{num}.{san}") + } else if i == 0 { + format!("{num}…{san}") + } else { + san.clone() + } + } + None => san.clone(), + }; + let label = crate::san::show(&label).into_owned(); + let selected = self.preview.as_ref().is_some_and(|p| { + p.base == base && p.shown == i + 1 && p.san == line.san + }); + let resp = ui.add( + egui::Button::selectable(selected, label) + .frame_when_inactive(false), + ); + if resp.clicked() + && let Some(root) = &root + { + self.commit_editor(); + self.preview = Some(Preview { + base, + root: root.clone(), + moves: line.moves.clone(), + san: line.san.clone(), + shown: i + 1, + }); + self.board.clear(); + } + } + }); + }); + }); + self.pv_row_height = row.response.rect.height(); + } + // Room for the lines still to come: between two positions the old lines are + // gone at once (never shown for the new one) and the new ones come a moment + // later; without it the notation below jumped up and back on every move. + let missing = analysis.line_count().saturating_sub(lines.len()); + if missing > 0 { + let row = if self.pv_row_height > 0.0 { + self.pv_row_height + } else { + ui.spacing().interact_size.y + }; + ui.add_space(missing as f32 * (row + ui.spacing().item_spacing.y)); + } + if insert { + self.insert_preview(actions); + } + } + ui.add_space(4.0); + } + + fn insert_preview(&mut self, actions: &mut Vec) { + let Some(p) = self.preview.take() else { return }; + match self.game.add_line(p.base, &p.moves) { + Ok(_) => { + let mut cur = p.base; + for m in &p.moves[..p.shown] { + match self.game.find_child(cur, *m) { + Some(c) => cur = c, + None => break, + } + } + self.goto(cur); + actions.push(GameAction::Toast( + tr("Line added as a variation (Ctrl+Z to undo)").into(), + )); + } + Err(e) => actions.push(GameAction::Toast(trf( + "Could not add the line: {e}", + &[("e", &e)], + ))), + } + } + + fn toolbar(&mut self, ui: &mut Ui, actions: &mut Vec) { + ui.add_space(4.0); + // Wraps onto a second row when the side panel is narrow, a group at a time + // (moves, board and edits, copying, the game analysis): a group that does not + // fit the rest of the row starts the next one, without a separator. + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 5.0; + let big = |s: &str| RichText::new(s).size(18.0); + let next_group = |ui: &mut Ui, icons: &[&str], extra: f32| { + let font = egui::FontId::proportional(18.0); + let gap = ui.spacing().item_spacing.x; + let width: f32 = icons + .iter() + .map(|i| { + ui.painter() + .layout_no_wrap((*i).to_owned(), font.clone(), Color32::WHITE) + .size() + .x + + 2.0 * ui.spacing().button_padding.x + + gap + }) + .sum::() + + extra; + if ui.available_size_before_wrap().x < width + 2.0 * gap + 1.0 { + ui.end_row(); + } else { + ui.separator(); + } + }; + if ui + .button(big("â�®")) + .on_hover_text(tr("To start (Home)")) + .clicked() + { + self.goto(NodeId::ROOT); + } + if ui.button(big("â—€")).on_hover_text(tr("Back (â†�)")).clicked() { + self.step_back(); + } + if ui + .button(big("â–¶")) + .on_hover_text(tr("Forward (→)")) + .clicked() + { + self.step_forward(actions); + } + if ui + .button(big("â�­")) + .on_hover_text(tr("To the end of the line (End)")) + .clicked() + { + let end = self.game.line_end(self.cursor); + self.goto(end); + } + next_group(ui, &["🔃", "↩", "↪"], 0.0); + if ui + .button(big("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.flipped = !self.flipped; + } + // Not while a comment is being written: it would undo what stands under it. + let no_editor = self.editor.is_none(); + if ui + .add_enabled( + self.game.can_undo() && no_editor, + egui::Button::new(big("↩")), + ) + .on_hover_text(tr("Undo move/edit (Ctrl+Z)")) + .clicked() + { + self.undo(); + } + if ui + .add_enabled( + self.game.can_redo() && no_editor, + egui::Button::new(big("↪")), + ) + .on_hover_text(tr("Redo move/edit (Ctrl+Y)")) + .clicked() + { + self.redo(); + } + next_group(ui, &["☰", "💾", "📋"], 0.0); + ui.menu_button(big("☰"), |ui| { + if ui.button(tr("Game data… (F2)")).clicked() { + actions.push(GameAction::EditGameData); + ui.close(); + } + let comment = if self.cursor == NodeId::ROOT { + tr("Comment at the start of the game… (Enter)") + } else { + tr("Comment on the move… (Enter)") + }; + if ui.button(comment).clicked() { + self.open_editor(Slot::After(self.cursor)); + ui.close(); + } + let writable_source = self.source.as_ref().is_some_and(|s| s.block.is_none()); + if (writable_source || (self.source.is_none() && self.target.is_some())) + && ui.button(self.save_hint()).clicked() + { + actions.push(GameAction::Save); + ui.close(); + } + if crate::platform::CAPS.own_databases + && ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() + { + actions.push(GameAction::AddToDatabase); + ui.close(); + } + if let Some(l) = self.link() + && ui.button(l.label()).clicked() + { + self.open_link(ui.ctx(), &l); + ui.close(); + } + ui.separator(); + if ui.button(tr("Copy PGN")).clicked() { + actions.push(self.copy_pgn()); + ui.close(); + } + #[cfg(web)] + if ui.button(tr("⇩ Download PGN")).clicked() { + actions.push(GameAction::DownloadPgn); + ui.close(); + } + if ui.button(tr("Copy FEN")).clicked() { + if let Some(fen) = self.game.fen(self.cursor) { + actions.push(GameAction::CopyText(fen, tr("FEN copied"))); + } + ui.close(); + } + if self.play.is_none() + && ui + .button(tr("Paste a line from the clipboard (Ctrl+V)")) + .clicked() + { + self.paste_clipboard(ui.ctx()); + ui.close(); + } + if self.play.is_none() && crate::platform::CAPS.play { + ui.separator(); + if ui.button(tr("Play on from here… (Ctrl+G)")).clicked() { + let at = self.cursor; + self.play_from(at, actions); + ui.close(); + } + } + #[cfg(not(web))] + if self.play.is_none() && crate::platform::CAPS.training { + if !crate::platform::CAPS.play { + ui.separator(); + } + let line = crate::train::TrainStart::from_game(&self.game, self.cursor); + if ui + .add_enabled(line.is_some(), egui::Button::new(tr("Add to repertoire…"))) + .on_disabled_hover_text(if self.cursor == NodeId::ROOT { + tr("Select the move up to which to add") + } else { + tr("The line has a null move (--): it cannot be played on the board") + }) + .clicked() + { + let at = self.cursor; + self.add_repertoire_from(at, actions); + ui.close(); + } + } + if !self.diagnostics.is_empty() && ui.button(tr("Compatibility notes")).clicked() { + self.show_diagnostics = true; + ui.close(); + } + ui.separator(); + if crate::platform::CAPS.translation + && self.translation.can_translate() + && ui.button(tr("Translate comments")).clicked() + { + self.translate_now = true; + self.side_tab = SideTab::Notation; + ui.close(); + } + if self.translation.has_translation() { + let label = if self.translation.original { + tr("Show the translation (Ctrl+Shift+T)") + } else { + tr("Show the original (Ctrl+Shift+T)") + }; + if ui.button(label).clicked() { + self.translation.toggle(); + ui.close(); + } + } + if ui.button(tr("Translation settings…")).clicked() { + actions.push(GameAction::OpenTranslationSettings); + ui.close(); + } + }); + if ui + .button(big("💾")) + .on_hover_text(self.save_hint()) + .clicked() + { + actions.push(GameAction::Save); + } + if ui + .button(big("📋")) + .on_hover_text(tr("Copy PGN (Ctrl+Shift+C)")) + .clicked() + { + actions.push(self.copy_pgn()); + } + // A running analysis shows its progress (70) and its × (22) instead. + if self.review.progress().is_some() { + next_group(ui, &[], 70.0 + 22.0 + 2.0 * 5.0); + } else { + next_group(ui, &["📈"], 0.0); + } + self.review_button(ui, actions); + }); + ui.add_space(4.0); + } + + /// Moves the cursor `plies` steps along the main line (dev startup automation). + pub fn debug_open_engine_settings(&mut self) { + self.engine_settings_open = true; + } + + /// Shows the Report tab (with the graph) when an analysis is available. + pub fn debug_show_report(&mut self) { + if self.review.has_data() { + self.review.visible = true; + self.side_tab = SideTab::Report; + } + } + + /// `debug_best_line` `delay` s after the notation is first drawn; closed (as by a + /// click on the game's move) `exit` s after it opened. + pub fn debug_best_line_later(&mut self, shown: usize, delay: f64, exit: Option) { + self.debug_best = Some(DebugBest { + shown, + delay, + exit, + start: None, + opened: false, + }); + } + + fn debug_best_tick(&mut self, ctx: &egui::Context) { + let Some(mut d) = self.debug_best.take() else { + return; + }; + let now = ctx.input(|i| i.time); + let start = *d.start.get_or_insert(now); + if !d.opened { + if now - start >= d.delay { + self.debug_best_line(d.shown); + d.opened = true; + d.start = Some(now); + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64( + d.delay - (now - start), + )); + } + self.debug_best = Some(d); + return; + } + match d.exit { + Some(exit) if now - start >= exit => { + let base = self.cursor; + self.goto(base); + } + Some(exit) => { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(exit - (now - start))); + self.debug_best = Some(d); + } + None => {} + } + } + + /// Opens the better line of the first engine-marked move up to its `shown`-th move. + pub fn debug_best_line(&mut self, shown: usize) { + let mark = self + .game + .mainline() + .into_iter() + .find_map(|id| self.review.analysis.marks.get(&id).cloned()); + self.commit_editor(); + if let Some(mark) = mark + && let Some(root) = self.game.position(mark.base) + && !mark.best.is_empty() + { + self.cursor = mark.base; + self.preview = Some(Preview { + base: mark.base, + root: root.clone(), + shown: shown.clamp(1, mark.best.len()), + moves: mark.best, + san: mark.best_san, + }); + } + } + + /// `how`: "ask" presses «Analyse», else the analysis starts. + pub fn debug_review(&mut self, ctx: &egui::Context, how: &str) { + match how { + "ask" => self.review_asked = true, + _ => self.start_review(false, ctx, &mut Vec::new()), + } + } + + /// Starts the game analysis right away (after an engine was found or installed for + /// it); `full` as it was asked. + pub fn start_review_now(&mut self, ctx: &egui::Context, full: bool) -> Vec { + let mut actions = Vec::new(); + self.start_review(full, ctx, &mut actions); + actions + } + + /// Moves the cursor to the end of the main line. + pub fn goto_main_line_end(&mut self) { + let end = self.game.line_end(self.game.root()); + self.goto(end); + } + + /// Moves the cursor to the first node showing `target`: the main line first, then + /// the variations. Returns false if the game never reaches the position. + pub fn goto_position(&mut self, target: &Chess) -> bool { + let root = self.game.root(); + let found = std::iter::once(root) + .chain(self.game.mainline()) + .chain(self.game.attached_nodes()) + .find(|&id| { + self.game + .position(id) + .is_some_and(|p| chess_import::position::same_position(p, target)) + }); + match found { + Some(id) => { + self.goto(id); + true + } + None => false, + } + } + + /// The cursor's position as a line of moves from the game's start, for searching + /// it in a database; `None` after a null move or in a game that cannot be searched. + /// The reference tab is shown (kept for the next game opened from it). + pub fn reference_tab(&self) -> bool { + self.side_tab == SideTab::Reference + } + + pub fn show_reference_tab(&mut self) { + if crate::platform::CAPS.reference { + self.side_tab = SideTab::Reference; + } + } + + pub fn search_line(&self) -> Option<(Chess, Vec, bool)> { + let (start, line) = crate::board_search::line_to(&self.game, self.cursor)?; + Some((start, line, self.flipped)) + } + + /// The cursor on move `ply` of the main line (0: the start; past the end: the + /// last move). + pub fn goto_ply(&mut self, ply: usize) { + let mut at = self.game.root(); + for _ in 0..ply { + match self.game.main_child(at) { + Some(n) => at = n, + None => break, + } + } + self.goto(at); + } + + pub fn debug_advance(&mut self, plies: usize) { + for _ in 0..plies { + match self.game.main_child(self.cursor) { + Some(n) => self.cursor = n, + None => break, + } + } + if std::env::var("CP_VAR").is_ok() + && let Some(v) = self.game.next_sibling(self.cursor) + { + self.cursor = self.game.main_child(v).unwrap_or(v); + } + } + + // ----- playing against Maia (docs/design/play-mode.md) ----------------------------- + + /// Starts a game against Maia in this (new, empty) game. + pub fn start_play( + &mut self, + start: crate::play::Start, + (engine, file): (crate::play::Engine, std::path::PathBuf), + judge: Option, + record: Option, + ctx: &egui::Context, + ) { + use crate::play::Clock; + // Dev hook `CP_PREMOVE=e7e5`: a premove set at the start (to see it without a mouse). + if let Some(pm) = std::env::var("CP_PREMOVE").ok().filter(|p| p.len() == 4) + && let (Ok(from), Ok(to)) = (pm[..2].parse(), pm[2..].parse()) + { + self.board.set_premove(from, to); + } + let event = match start.clock { + Some(tc) => trf( + "Game vs computer, {speed}", + &[("speed", &tc.speed().name().to_lowercase())], + ), + None => tr("Game vs computer").to_owned(), + }; + let g = &mut self.game; + for (name, value) in ::play::game_tags( + &event, + start.user, + &start.user_name, + start.user_elo, + &start.rival_name(), + &start.clock.map_or_else(|| "-".to_owned(), |tc| tc.pgn()), + ) { + g.set_tag(&name, &value); + } + // From a position of another game: its moves are already here; after the last + // of them, where the game comes from (a comment of the game, written in PGN). + let floor = match &start.from { + Some(from) => { + let floor = g.line_end(NodeId::ROOT); + let elo = start.strength.to_string(); + // Rodent's notes name him whole («Rodent V 2400 (Tal)»). + let rodent = start.rival == crate::play::Rival::Rodent; + let name = start.rival_name(); + let note = if rodent { + match (&from.game, &from.after) { + (Some(game), Some(m)) => trf( + "Continued from {game}, after {move}. From here on, a game against {name}.", + &[("game", game), ("move", m), ("name", &name)], + ), + (None, Some(m)) => trf( + "Continued after {move}. From here on, a game against {name}.", + &[("move", m), ("name", &name)], + ), + (Some(game), None) => trf( + "Continued from {game}. From here on, a game against {name}.", + &[("game", game), ("name", &name)], + ), + (None, None) => { + trf("From here on, a game against {name}.", &[("name", &name)]) + } + } + } else { + match (&from.game, &from.after) { + (Some(game), Some(m)) => trf( + "Continued from {game}, after {move}. From here on, a game against Maia {elo}.", + &[("game", game), ("move", m), ("elo", &elo)], + ), + (None, Some(m)) => trf( + "Continued after {move}. From here on, a game against Maia {elo}.", + &[("move", m), ("elo", &elo)], + ), + (Some(game), None) => trf( + "Continued from {game}. From here on, a game against Maia {elo}.", + &[("game", game), ("elo", &elo)], + ), + (None, None) => { + trf("From here on, a game against Maia {elo}.", &[("elo", &elo)]) + } + } + }; + let (nags, mut comments) = g + .node(floor) + .map(|n| (n.nags().to_vec(), n.comments_after().to_vec())) + .unwrap_or_default(); + comments.push(note); + let _ = g.annotate(floor, nags, comments); + g.forget_history(); + floor + } + None => NodeId::ROOT, + }; + g.mark_saved(); + if floor != NodeId::ROOT { + self.goto(floor); + } + // Its journal keeps what it is played with: it can be put aside and go on. + let floor_plies = self.plies_to(floor); + let journal = Some(crate::player_games::Journal::new( + record, + &start.user_name, + start.saved(floor_plies), + )); + let clock = start.clock.map(Clock::new); + self.begin_play(start, (engine, file), judge, journal, clock, floor, ctx); + } + + /// Goes on with a game put aside (docs/design/desktop-adjourned.md): the game on the + /// screen is its record so far; the clocks have the time each side had left (the side + /// to move's when it was put aside, the other's at its last move, `[%clk]`); its own + /// journal goes on. + pub fn resume_play( + &mut self, + saved: &crate::play::Saved, + to_move_left: Option, + engine: (crate::play::Engine, std::path::PathBuf), + judge: Option, + journal: crate::player_games::Journal, + ctx: &egui::Context, + ) { + use crate::play::Clock; + // Unfinished while it was aside: the game goes on. + self.game.remove_tag("Termination"); + self.game.mark_saved(); + let line = self.game.mainline(); + let floor = if saved.floor == 0 { + NodeId::ROOT + } else { + line.get(saved.floor - 1).copied().unwrap_or(NodeId::ROOT) + }; + let from = (floor != NodeId::ROOT) + .then(|| self.start_from(floor).ok()) + .flatten(); + let start = saved.start(from); + let end = self.play_end_node(); + let to_move = self.game.position(end).map_or(Color::White, |p| p.turn()); + let left = crate::play::times_left(&self.game, saved.floor, to_move_left); + let clock = start + .clock + .map(|tc| Clock::resumed(tc, left, to_move, web_time::Instant::now())); + self.goto(end); + self.begin_play(start, engine, judge, Some(journal), clock, floor, ctx); + } + + /// Half-moves of the main line up to `node` (0 for the start). + fn plies_to(&self, node: NodeId) -> usize { + self.game + .mainline() + .iter() + .position(|&n| n == node) + .map_or(0, |k| k + 1) + } + + /// The game against the computer runs: its opponent and judge start, its clocks. + #[allow(clippy::too_many_arguments)] + fn begin_play( + &mut self, + start: crate::play::Start, + (engine, file): (crate::play::Engine, std::path::PathBuf), + judge: Option, + journal: Option, + clock: Option, + floor: NodeId, + ctx: &egui::Context, + ) { + use crate::play::{Opponent, Session}; + self.flipped = start.user == Color::Black; + self.play_end = None; + self.recorded = None; + // A game put aside with the player's time already low goes on without the tick: + // it was heard before. + let low_time_heard = clock + .as_ref() + .is_some_and(|c| c.left(start.user, web_time::Instant::now()) <= c.low()); + self.play = Some(Session { + journal, + user: start.user, + strength: start.strength, + engine, + style: start.style.clone(), + user_elo: start.user_elo, + clock, + opponent: match engine { + crate::play::Engine::Maia(_) => Opponent::start(file, ctx), + #[cfg(not(web))] + crate::play::Engine::Rodent(_) => { + Opponent::start_rodent(file, start.style.clone(), Some(start.strength), ctx) + } + #[cfg(web)] + crate::play::Engine::Rodent(_) => { + Opponent::not_started(tr("a browser cannot start it").to_owned()) + } + }, + resign_asked: false, + low_time_heard, + judge: judge.and_then(|p| crate::play::start_judge(p, ctx)), + hopeless: 0, + resign_offer: None, + play_on: false, + floor, + }); + self.play_start = Some(start); + self.ask_maia(); + } + + /// The positions of the main line, from the start to its end. + fn mainline_positions(&self) -> Vec { + let mut out = Vec::new(); + if let Some(p) = self.game.position(NodeId::ROOT) { + out.push(p.clone()); + } + for id in self.game.mainline() { + if let Some(p) = self.game.position(id) { + out.push(p.clone()); + } + } + out + } + + fn play_end_node(&self) -> NodeId { + self.game.line_end(NodeId::ROOT) + } + + /// The side to move at the end of the main line. + fn play_turn(&self) -> Color { + self.game + .position(self.play_end_node()) + .map_or(Color::White, |p| p.turn()) + } + + /// Closes Maia's offer to resign: the clocks waited while it was open. + fn close_resign_offer(&mut self) { + let Some(s) = self.play.as_mut() else { return }; + if let Some(since) = s.resign_offer.take() + && let Some(c) = s.clock.as_mut() + { + c.pause(since.elapsed()); + } + } + + /// Maia offers to resign: accept the win, or play to the end (no more offers). + fn resign_offer(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(s) = &self.play else { return }; + let user = s.user; + ui.add_space(4.0); + let mut choice = None; + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 8)) + .corner_radius(4) + .fill(ui.visuals().extreme_bg_color) + .stroke(egui::Stroke::new(1.0, ui.visuals().selection.bg_fill)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + let rival = self + .play + .as_ref() + .map_or(crate::play::Rival::Maia, |s| s.rival()); + ui.label( + RichText::new(crate::play::said(rival, "Maia resigns", "Rodent resigns")) + .strong() + .size(16.0), + ); + ui.label( + RichText::new(crate::play::said( + rival, + "Her position is lost. Accept the win, or play to the end?", + "Its position is lost. Accept the win, or play to the end?", + )) + .weak(), + ); + ui.add_space(4.0); + // One under the other, as wide as the card: they fit a narrow panel. + let w = ui.available_width(); + if ui + .add_sized( + [w, 30.0], + egui::Button::new(RichText::new(tr("Accept the win")).strong().size(14.0)) + .fill(ui.visuals().selection.bg_fill), + ) + .clicked() + { + choice = Some(true); + } + if ui + .add_sized( + [w, 30.0], + egui::Button::new(RichText::new(tr("Play to the end")).size(14.0)), + ) + .on_hover_text(crate::play::said( + rival, + "Maia plays on and will not offer again in this game", + "Rodent plays on and will not offer again in this game", + )) + .clicked() + { + choice = Some(false); + } + }); + match choice { + Some(true) => { + self.close_resign_offer(); + self.finish_play(crate::play::Ending::Resigned { loser: !user }, actions); + } + Some(false) => { + self.close_resign_offer(); + if let Some(s) = self.play.as_mut() { + s.play_on = true; + } + self.ask_maia(); + } + None => {} + } + } + + /// The side that may set a premove now: the user, while Maia is to move, at the + /// current position of the game. + fn premove_side(&self) -> Option { + let s = self.play.as_ref()?; + (self.preview.is_none() + && self.play_leave.is_none() + && self.play_turn() != s.user + && self.cursor == self.play_end_node()) + .then_some(s.user) + } + + /// The user may move: their turn, at the current position, Maia not thinking. + fn user_may_move(&self) -> bool { + match &self.play { + None => true, + Some(s) => { + self.play_leave.is_none() + && self.play_turn() == s.user + && self.cursor == self.play_end_node() + && !s.opponent.thinking + } + } + } + + /// Asks Maia for a move when it is her turn (dev hook `CP_PLAY_AUTO`: for the user + /// too, quickly — a whole game without a mouse). + fn ask_maia(&mut self) { + let turn = self.play_turn(); + let end = self.play_end_node(); + let engine_pos = self.game.engine_history(end).map(|h| match h.start_fen { + None => uci::EnginePosition::startpos(h.moves), + Some(fen) => uci::EnginePosition::fen(fen, h.moves), + }); + let positions = self.mainline_positions(); + let ply = positions.len() - 1; + let only = positions.last().is_some_and(|p| p.legal_moves().len() == 1); + let auto = std::env::var_os("CP_PLAY_AUTO").is_some(); + let Some(s) = self.play.as_mut() else { return }; + if turn == s.user { + if auto { + let elo = s.user_elo.unwrap_or(s.strength); + s.opponent.ask( + positions, + engine_pos.clone(), + s.engine.input(elo), + s.strength, + std::time::Duration::from_millis(30), + ); + } + return; + } + let now = web_time::Instant::now(); + let clock = s + .clock + .as_ref() + .map(|c| (c.left(turn, now), c.control.increment)); + // (Self-play: Maia slower than the user, so that the judge is heard.) + let pause = if auto { + std::time::Duration::from_millis(300) + } else { + crate::play::pause(clock, ply, only) + }; + // Her rating input is what makes her play at her strength; the user's is as is. + let oppo = s.user_elo.unwrap_or(s.strength); + let own = s.engine.input(s.strength); + s.opponent + .ask(positions, engine_pos.clone(), own, oppo, pause); + // Is her position lost? (Unless the user wants to play to the end.) + if !s.play_on + && let (Some(j), Some(ep)) = (s.judge.as_mut(), engine_pos) + { + j.ask(ep); + } + } + + /// A move at the end of the main line by the side to move: the clock, `[%clk]`, the + /// sound, the end of the game, Maia's turn. + fn play_add( + &mut self, + m: Move, + spent: Option, + actions: &mut Vec, + ) { + let end = self.play_end_node(); + let mover = self.play_turn(); + let Ok(id) = self.game.add_move(end, m) else { + return; + }; + let now = web_time::Instant::now(); + if let Some(s) = self.play.as_mut() { + s.resign_asked = false; + if let Some(c) = s.clock.as_mut() { + c.moved(mover, now, spent); + let left = c.left(mover, now); + let _ = self + .game + .annotate(id, Vec::new(), vec![crate::play::clk_command(left)]); + } + } + // Her move made, a verdict still on its way is about a position gone. + if let Some(s) = self.play.as_mut() + && mover != s.user + && let Some(j) = s.judge.as_mut() + { + j.forget(); + } + // Maia's move: what the user holds in hand stays there (Lichess); any other + // move goes to its position as usual. + let user = self.play.as_ref().map(|s| s.user); + if user.is_some_and(|u| u != mover) && self.cursor == end { + self.commit_editor(); + self.cursor = id; + self.scroll_to_cursor = true; + self.preview = None; + if let (Some(u), Some(pos)) = (user, self.game.position(id)) { + self.board.opponent_moved(pos.board(), u); + } + } else { + self.goto(id); + } + if let Some(snd) = self.sound_for(id) { + actions.push(GameAction::Sound(snd)); + } + if let Some(e) = crate::play::ending(&self.mainline_positions()) { + self.finish_play(e, actions); + } else { + self.keep_journal(); + self.ask_maia(); + } + } + + fn user_move(&mut self, m: Move, actions: &mut Vec) { + if !self.user_may_move() { + // A move in a past position: back to the game. + let end = self.play_end_node(); + self.goto(end); + return; + } + self.play_add(m, None, actions); + } + + /// The clock and Maia's answers, each frame. + fn play_tick(&mut self, ctx: &egui::Context, actions: &mut Vec) { + if self.play_leave.is_some() { + return; + } + let maia_to_move = self + .play + .as_ref() + .is_some_and(|s| self.play_turn() != s.user); + let Some(s) = self.play.as_mut() else { return }; + if s.resign_offer.is_some() { + return; + } + // The judge's verdict on the position Maia is to move in: lost for two of her + // turns in a row, she offers to resign instead of moving (the clocks wait). + if let Some(score) = s.judge.as_mut().and_then(|j| j.answer()) { + s.hopeless = if crate::play::hopeless(score) { + s.hopeless + 1 + } else { + 0 + }; + if maia_to_move + && !s.play_on + && s.hopeless >= crate::play::HOPELESS_TURNS + && s.opponent.thinking + { + s.opponent.forget(); + s.resign_offer = Some(web_time::Instant::now()); + self.scroll_to_cursor = true; + actions.push(GameAction::Sound(Sound::Defeat)); + return; + } + } + if let Some(err) = s.opponent.failed() { + // A file that does not start is removed: the dialog offers it again. + let text = match s.engine { + crate::play::Engine::Maia(m) => { + crate::maia_download::forget_broken(m); + "Maia did not start: {e}" + } + crate::play::Engine::Rodent(g) => { + crate::play::RodentFiles::remove(g); + "Rodent did not start: {e}" + } + }; + actions.push(GameAction::Toast(trf(text, &[("e", &err)]))); + // What was played is kept, unfinished. + let journal = self.play.take().and_then(|mut s| s.journal.take()); + self.game.set_tag("Termination", "Unterminated"); + self.record(journal); + self.game.mark_saved(); + actions.push(GameAction::Back); + return; + } + if let Some((m, pause)) = s.opponent.answer() { + // Maia's clock takes her pause, not the program's computing. + self.play_add(m, Some(pause), actions); + // The user's premove, at once when it is legal now (else it is dropped). + if let Some((from, to)) = self.board.take_premove() + && self.play.is_some() + && self.user_may_move() + && let Some(pos) = self.game.position(self.play_end_node()) + && let Some(m) = crate::board::premove_move(pos, from, to) + { + self.play_add(m, None, actions); + } + } + let now = web_time::Instant::now(); + let end_pos = self.game.position(self.play_end_node()).cloned(); + let Some(s) = self.play.as_mut() else { return }; + if let Some(c) = &s.clock + && let Some(side) = c.running() + { + let left = c.left(side, now); + if left.is_zero() { + // Time is up; a draw when the other side cannot mate (FIDE 6.9). + let draw = end_pos.is_some_and(|p| p.has_insufficient_material(!side)); + self.finish_play(crate::play::Ending::Time { loser: side, draw }, actions); + return; + } + // The player's time getting low is heard once, as on Lichess (the clock turns + // red at the same moment). + if side == s.user && left <= c.low() && !s.low_time_heard { + s.low_time_heard = true; + actions.push(GameAction::Sound(Sound::LowTime)); + } + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + + /// The game is over: the result, the tags, the strip; the screen becomes an ordinary + /// new game. + fn finish_play(&mut self, ending: crate::play::Ending, actions: &mut Vec) { + self.close_resign_offer(); + let Some(mut s) = self.play.take() else { + return; + }; + s.opponent.forget(); + self.board.clear_premove(); + let now = web_time::Instant::now(); + let left = s.clock.as_mut().map(|c| { + c.stop(now); + (c.left(s.user, now), c.left(!s.user, now)) + }); + self.game.set_result(ending.result()); + self.game.set_tag("Termination", ending.termination()); + self.game.forget_history(); + self.record(s.journal.take()); + let end = self.play_end_node(); + self.goto(end); + if matches!(ending, crate::play::Ending::Checkmate { .. }) { + actions.push(GameAction::Sound(Sound::Checkmate)); + } + if let Some(start) = self.play_start.clone() { + self.play_end = Some(crate::play::End { + ending, + user: s.user, + start, + left, + }); + } + } + + /// The game as a crash would leave it, kept after each move (once both have moved). + fn keep_journal(&self) { + if !self.play_started() { + return; + } + if let Some(j) = self.play.as_ref().and_then(|s| s.journal.as_ref()) { + let mut g = self.game.clone(); + g.set_tag("Termination", "Unterminated"); + j.save(&g.to_pgn()); + } + } + + /// The game ended (or stopped): it goes into the player's database, once a move of + /// it was made; it becomes that database's record. + fn record(&mut self, journal: Option) { + let Some(journal) = journal else { return }; + if self.played().is_empty() { + return; + } + let Some(target) = journal.target() else { + return; + }; + let name = crate::own_db::base_name(target); + let Some(res) = journal.finish(&self.game.to_pgn()) else { + return; + }; + let res = res.map_err(|e| { + trf( + "Could not write to «{db}»: {reason}", + &[("db", &name), ("reason", &e)], + ) + }); + if let Ok(w) = &res { + self.source = Some(GameSource { + path: w.path.clone(), + index: w.index, + block: None, + }); + self.target = None; + self.game.mark_saved(); + } + if res.is_err() { + self.unwritten = Some(journal); + } + self.recorded = Some(res.clone()); + self.record_news = Some(res); + } + + /// Puts the game in progress aside (docs/design/desktop-adjourned.md): it stops here, + /// its journal stays and it can go on later. `None`: its journal could not be made + /// (no folder for it): the game is left as it is, still played. + pub fn put_aside(&mut self) -> Option { + let journal = self.play.as_ref()?.journal.as_ref()?; + if !journal.can_put_aside() { + return None; + } + // «The game is on» was open (the window closed over it): the clocks waited. + if let Some((_, since)) = self.play_leave.take() + && let Some(s) = self.play.as_mut() + && s.resign_offer.is_none() + && let Some(c) = s.clock.as_mut() + { + c.pause(since.elapsed()); + } + self.close_resign_offer(); + let mut s = self.play.take()?; + s.opponent.forget(); + self.board.clear_premove(); + let mut g = self.game.clone(); + g.set_tag("Termination", "Unterminated"); + // The side to move keeps the time it had now (not its last move's). + let to_move = self + .game + .position(self.play_end_node()) + .map_or(Color::White, |p| p.turn()); + let left = s + .clock + .as_ref() + .map(|c| c.left(to_move, web_time::Instant::now())); + let aside = s + .journal + .take() + .and_then(|j| j.put_aside(&g.to_pgn(), left)); + self.game.mark_saved(); + aside + } + + /// The player's name of the game against the computer on the screen. + pub fn player_name(&self) -> String { + self.play_start + .as_ref() + .map(|s| s.user_name.clone()) + .unwrap_or_default() + } + + /// Before both sides have moved there is nothing to lose: the game is dropped. + fn play_started(&self) -> bool { + self.played().len() >= 2 + } + + /// The moves of the game against Maia: the main line after the position it + /// started from. + fn played(&self) -> Vec { + let floor = self.play.as_ref().map_or(NodeId::ROOT, |s| s.floor); + let line = self.game.mainline(); + match line.iter().position(|&n| n == floor) { + Some(k) => line[k + 1..].to_vec(), + None => line, + } + } + + /// The user has made a move of the game against Maia. + fn user_moved(&self, user: Color) -> bool { + self.played().iter().any(|&n| { + self.game + .parent(n) + .and_then(|p| self.game.position(p)) + .is_some_and(|p| p.turn() == user) + }) + } + + /// Leaving a game before its first moves: back to the game it went on from, if + /// there is one, else to the library. + fn leave_action(&self) -> GameAction { + if self.previous.is_some() { + GameAction::ReturnToPrevious + } else { + GameAction::Back + } + } + + /// «Play on from here»: the dialog for a game against Maia from the position of + /// `at` (a finished position says why not). + fn play_from(&mut self, at: NodeId, actions: &mut Vec) { + if self.play.is_some() { + return; + } + self.commit_editor(); + self.preview = None; + match self.start_from(at) { + Ok(from) => actions.push(GameAction::PlayFrom(Box::new(from))), + Err(why) => actions.push(GameAction::Toast(why)), + } + } + + /// Where a game from the position of `at` starts: the moves to it (after the last + /// null move), the position, how to name it. + fn start_from(&self, at: NodeId) -> Result { + let g = &self.game; + let pos = g.position(at).ok_or_else(String::new)?.clone(); + let over = if pos.is_checkmate() { + Some(tr("checkmate")) + } else if pos.is_stalemate() { + Some(tr("stalemate")) + } else if pos.is_insufficient_material() { + Some(tr("neither side can checkmate")) + } else { + None + }; + if let Some(why) = over { + return Err(trf("The game is over here: {why}", &[("why", &why)])); + } + let path = g.path(at); + // A teaching null move: the game starts after the last one. + let null = path + .iter() + .rposition(|&n| g.game_move(n).is_some_and(|m| m.is_null())); + let (start_fen, from_k) = match null { + Some(k) => (g.fen(path[k]), k + 1), + None => ((!g.start().is_standard()).then(|| g.start().fen()), 1), + }; + let moves = path[from_k.min(path.len())..] + .iter() + .filter_map(|&n| match g.game_move(n)?.kind { + chess_core::MoveKind::Normal(m) => Some(m), + chess_core::MoveKind::Null => None, + }) + .collect(); + let last = g.game_move(at).and_then(|m| match m.kind { + chess_core::MoveKind::Normal(m) => Some((m.from()?, crate::board::ui_target(&m))), + chess_core::MoveKind::Null => None, + }); + let (after, after_shown) = match (g.move_number(at), g.game_move(at)) { + (Some((n, side)), Some(m)) => ( + Some(match side { + Color::White => format!("{n}.{}", m.san), + Color::Black => format!("{n}...{}", m.san), + }), + Some(move_label(n, side, &m.san, true)), + ), + _ => (None, None), + }; + let name = |t: &str| { + g.tag(t) + .map(str::trim) + .filter(|v| !v.is_empty() && *v != "?") + }; + let players = match (name("White"), name("Black")) { + (None, None) => None, + (w, b) => Some(format!("{} — {}", w.unwrap_or("?"), b.unwrap_or("?"))), + }; + let year = name("Date") + .map(|d| d.chars().take(4).collect::()) + .filter(|y| y.chars().all(|c| c.is_ascii_digit())); + let event = [name("Event").map(str::to_owned), year] + .into_iter() + .flatten() + .collect::>() + .join(" "); + let game = match (players, event.is_empty()) { + (Some(p), false) => Some(format!("{p}, {event}")), + (Some(p), true) => Some(p), + (None, false) => Some(event), + (None, true) => None, + }; + Ok(crate::play::StartFrom { + start_fen, + moves, + position: pos, + last, + after, + after_shown, + game, + null_dropped: null.is_some(), + }) + } + + /// Resigns the game in progress (leaving it, closing the program); before the first + /// moves it is dropped instead. The game stays as played. + pub fn resign_if_playing(&mut self) { + let Some(s) = &self.play else { return }; + if self.play_started() { + let user = s.user; + let mut sink = Vec::new(); + self.finish_play(crate::play::Ending::Resigned { loser: user }, &mut sink); + } else { + self.play = None; + self.game.mark_saved(); + } + } + + /// Whether a move can be taken back in this game: in a blitz only (the owner's + /// choice, docs/decisions.md «Ход назад — только в блице»). + fn take_back_offered(&self) -> bool { + self.play + .as_ref() + .and_then(|s| s.clock.as_ref()) + .is_some_and(|c| c.control.speed() == crate::play::Speed::Blitz) + } + + /// Takes back the user's last move and Maia's answer to it (no variation is left). + fn take_back(&mut self) { + if !self.take_back_offered() { + return; + } + self.board.clear_premove(); + self.close_resign_offer(); + let Some(s) = self.play.as_mut() else { return }; + s.hopeless = 0; + if let Some(j) = s.judge.as_mut() { + j.forget(); + j.forget_scores(); + } + s.opponent.forget(); + let user = s.user; + // The last move of the user in this game (never one of the game it went on from). + let line = self.played(); + let last = line.iter().rev().find(|&&id| { + self.game + .parent(id) + .and_then(|p| self.game.position(p)) + .is_some_and(|p| p.turn() == user) + }); + if let Some(&id) = last + && let Ok(parent) = self.game.delete_variation(id) + { + self.goto(parent); + let moved = self.user_moved(user); + if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) { + c.take_back(user, moved, web_time::Instant::now()); + } + } + self.keep_journal(); + self.ask_maia(); + } + + /// Keys during a game: looking through it, flipping, the take-back; Esc asks. + fn play_keys(&mut self, ui: &Ui, actions: &mut Vec) { + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let mut cmds = Vec::new(); + ui.input_mut(|i| { + if i.consume_shortcut(&ctrl(Key::Z)) { + cmds.push("takeback"); + } + if i.consume_shortcut(&ctrl(Key::W)) { + cmds.push("leave"); + } + if i.modifiers.is_none() { + for (key, cmd) in [ + (Key::ArrowLeft, "back1"), + (Key::ArrowRight, "fwd1"), + (Key::ArrowUp, "end"), + (Key::ArrowDown, "home"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::L, "engine"), + (Key::Escape, "leave"), + ] { + if i.key_pressed(key) { + cmds.push(cmd); + } + } + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) { + cmds.push("engine"); + } + }); + for cmd in cmds { + match cmd { + "takeback" => self.take_back(), + "back1" => self.step_back(), + "fwd1" => self.step_forward(actions), + "home" => self.goto(NodeId::ROOT), + "end" => { + let end = self.play_end_node(); + self.goto(end); + } + "flip" => self.flipped = !self.flipped, + "engine" => actions.push(GameAction::Toast( + tr("The engine is off during the game — analyse after it ends").to_owned(), + )), + "leave" => { + if let Some(s) = self.play.as_mut() + && s.resign_asked + { + s.resign_asked = false; + } else { + ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)); + actions.push(self.leave_action()); + } + } + _ => {} + } + } + } + + /// Leaving during a game asks first (play-mode.md §6); before the first moves of + /// both sides the game is just dropped. + fn guard_leaving(&mut self, actions: &mut Vec) { + if self.play.is_none() { + return; + } + let leaving = actions + .iter() + .position(|a| matches!(a, GameAction::Back | GameAction::ReturnToPrevious)); + if let Some(k) = leaving { + let a = actions.remove(k); + if self.play_started() { + let intent = if matches!(a, GameAction::ReturnToPrevious) { + crate::app::CloseIntent::ReturnToPrevious + } else { + crate::app::CloseIntent::BackToLibrary + }; + self.ask_leave(intent); + } else { + if let Some(s) = self.play.as_mut() { + s.opponent.forget(); + } + self.play = None; + self.game.mark_saved(); + actions.push(a); + } + } + } + + /// Leaving a game in progress (any way: back, the window closed, …) asks first; + /// the clocks wait while the question is open. + pub fn ask_leave(&mut self, intent: crate::app::CloseIntent) { + self.board.clear_premove(); + if self.play_leave.is_none() { + self.play_leave = Some((intent, web_time::Instant::now())); + } + } + + /// A game is in progress and its first moves are made (leaving it costs a result). + pub fn playing_started(&self) -> bool { + self.play.is_some() && self.play_started() + } + + /// «The game is on»: resign (and add), keep playing, put aside (the main answer: it + /// costs nothing). + fn leave_question(&mut self, ctx: &egui::Context, actions: &mut Vec) { + let Some((intent, since)) = self.play_leave else { + return; + }; + // Which game: «Rodent IV 2800 · Tal · you play white · 5+3 · move 10», as on the + // card of a game put aside. + let context = self.play.as_ref().map(|s| { + let mut parts = vec![s.rival_label()]; + parts.extend(s.rival_style().map(str::to_owned)); + parts.push( + if s.user == Color::White { + tr("you play white") + } else { + tr("you play black") + } + .to_owned(), + ); + parts.push( + s.clock + .as_ref() + .map_or_else(|| tr("no clock").to_owned(), |c| c.control.label()), + ); + if let Some(pos) = self.game.position(self.play_end_node()) { + parts.push(trf("move {n}", &[("n", &pos.fullmoves().get())])); + } + parts.join(" · ") + }); + let mut choice = None; + egui::Modal::new(egui::Id::new("play_leave")).show(ctx, |ui| { + ui.set_width(460.0); + ui.heading(tr("The game is on")); + if let Some(context) = &context { + ui.label(RichText::new(context).weak()); + ui.add_space(4.0); + } + // A game written by itself needs no «add»: where it goes is said instead. + let target = self + .play + .as_ref() + .and_then(|s| s.journal.as_ref()) + .and_then(|j| j.target()) + .map(crate::own_db::base_name); + match &target { + Some(db) => ui.label(trf( + "Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends and is written to «{db}».", + &[("db", db)], + )), + None => ui.label(tr("Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends.")), + }; + ui.add_space(8.0); + // Resigning on the left, apart from the main answer; all of one height. With + // «add to a database» too they take a row of their own above. + let button = |text: &str| egui::Button::new(text).min_size(vec2(0.0, 30.0)); + let resign = |ui: &mut Ui, choice: &mut Option| { + if target.is_none() && ui.add(button(tr("Resign and add to a database…"))).clicked() { + *choice = Some(0); + } + if ui.add(button(tr("Resign and leave"))).clicked() { + *choice = Some(1); + } + }; + let main = |ui: &mut Ui, choice: &mut Option| { + if crate::widgets::primary(ui, tr("Put aside")).clicked() { + *choice = Some(3); + } + if ui.add(button(tr("Keep playing"))).clicked() { + *choice = Some(2); + } + }; + if target.is_none() { + ui.horizontal(|ui| resign(ui, &mut choice)); + ui.add_space(4.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + main(ui, &mut choice) + }); + } else { + let mut right = None; + egui::Sides::new().show(ui, |ui| resign(ui, &mut choice), |ui| main(ui, &mut right)); + choice = choice.or(right); + } + }); + if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { + choice = Some(2); + } + if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) { + choice = Some(3); + } + let Some(choice) = choice else { return }; + self.play_leave = None; + // The clocks waited while the question was open. + // (Over Maia's offer to resign the clocks wait since the offer: its closing + // gives that time back, all of it.) + let waited = since.elapsed(); + if let Some(s) = self.play.as_mut() + && s.resign_offer.is_none() + && let Some(c) = s.clock.as_mut() + { + c.pause(waited); + } + match choice { + // Then the game goes on where the user was going once it is saved. + 0 => { + self.resign_if_playing(); + actions.push(GameAction::SaveAndLeave(intent)); + } + // Leaving was the answer: no second question about saving (a game written + // by itself is in its database already). + 1 => { + self.resign_if_playing(); + self.game.mark_saved(); + actions.push(GameAction::Leave(intent)); + } + 3 => actions.push(GameAction::PutAside(Some(intent))), + _ => {} + } + } + + /// The side panel during a game: the opponent's clock, the notation, the user's + /// clock, the game's buttons. + fn play_side( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + analysis: &mut Analysis, + reference: &mut crate::reference::Reference, + hub: &mut crate::translate_ui::Hub, + actions: &mut Vec, + ) { + let _ = (analysis, reference, hub); + let Some(s) = &self.play else { return }; + let user = s.user; + // The side whose pieces are at the top of the board is at the top. + let top = if self.flipped { + Color::White + } else { + Color::Black + }; + egui::Panel::bottom("play_toolbar").show(ui, |ui| self.play_toolbar(ui, actions)); + egui::Panel::bottom("play_card_bottom") + .show_separator_line(false) + .show(ui, |ui| self.clock_card(ui, !top, user, settings.piece_set)); + egui::Panel::top("play_card_top") + .show_separator_line(false) + .show(ui, |ui| self.clock_card(ui, top, user, settings.piece_set)); + if self.play.as_ref().is_some_and(|s| s.resign_offer.is_some()) { + egui::Panel::bottom("play_resign_offer") + .show_separator_line(false) + .show(ui, |ui| self.resign_offer(ui, actions)); + } + if self.cursor != self.play_end_node() { + egui::Panel::bottom("play_viewing") + .show_separator_line(false) + .show(ui, |ui| { + if ui + .link( + RichText::new(tr( + "Viewing an earlier position · back to the game — End", + )) + .weak(), + ) + .clicked() + { + let end = self.play_end_node(); + self.goto(end); + } + }); + } + egui::CentralPanel::default().show(ui, |ui| { + egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| { + let resp = Notation { + game: &self.game, + cursor: self.cursor, + scroll_to_cursor: self.scroll_to_cursor, + marks: None, + preview: None, + translations: None, + editor: None, + read_only: true, + dim_until: self + .play + .as_ref() + .filter(|s| s.floor != NodeId::ROOT) + .and_then(|s| self.game.node(s.floor)) + .map(|n| n.ply()), + mistakes: None, + shapes: None, + } + .show(ui); + if let Some(id) = resp.clicked { + self.goto(id); + } + self.scroll_to_cursor = false; + }); + }); + } + + /// A player's card: name, rating, the clock and what is going on. + fn clock_card(&self, ui: &mut Ui, side: Color, user: Color, pieces: crate::assets::PieceSet) { + let Some(s) = &self.play else { return }; + // While «The game is on» is open, the clocks stand at the moment it opened. + let now = self + .play_leave + .map(|(_, since)| since) + .into_iter() + .chain(s.resign_offer) + .min() + .unwrap_or_else(web_time::Instant::now); + let turn = self.play_turn(); + let active = turn == side; + let left = s.clock.as_ref().map(|c| c.left(side, now)); + let low = s + .clock + .as_ref() + .zip(left) + .is_some_and(|(c, l)| c.running() == Some(side) && l <= c.low()); + let sel = ui.visuals().selection; + let mut frame = egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 6)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )); + if active { + frame = frame.fill(sel.bg_fill.gamma_multiply(0.35)); + } + if low { + frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color)); + } + ui.add_space(4.0); + frame.show(ui, |ui| { + ui.set_width(ui.available_width()); + // The clock gives way to the opponent's name in a narrow panel: smaller digits + // (the same on both bars), then the name cut. + let width = |text: String, font: egui::FontId| { + ui.painter() + .layout_no_wrap(text, font, egui::Color32::WHITE) + .size() + .x + }; + // The king of the board's piece set before the name. + let king_size = 22.0; + let rival_w = king_size + + ui.spacing().item_spacing.x + + width(s.rival_label(), egui::FontId::proportional(15.0)); + let clock_size = left.map_or(28.0, |l| { + let at_28 = width(crate::play::clock_text(l), egui::FontId::monospace(28.0)); + let room = ui.available_width() - rival_w - 16.0; + (28.0 * room / at_28).clamp(18.0, 28.0) + }); + let clock_w = left.map_or(0.0, |l| { + width( + crate::play::clock_text(l), + egui::FontId::monospace(clock_size), + ) + 12.0 + }); + ui.horizontal(|ui| { + ui.vertical(|ui| { + ui.set_max_width(ui.available_width() - clock_w); + let name = if side == user { + match s.user_elo { + Some(r) => format!("{} · {r}", tr("You")), + None => tr("You").to_owned(), + } + } else { + s.rival_label() + }; + ui.horizontal(|ui| { + let (rect, _) = + ui.allocate_exact_size(vec2(king_size, king_size), Sense::hover()); + let king = chess_core::shakmaty::Piece { + color: side, + role: chess_core::shakmaty::Role::King, + }; + pieces.paint(ui, king, rect); + // One line however narrow the panel: a long style is cut, not + // wrapped under the clock (the whole name on hover). + ui.add(egui::Label::new(RichText::new(&name).size(15.0)).truncate()) + .on_hover_text(&name); + }); + let state = if side != user && s.resign_offer.is_some() { + tr("resigns") + } else if side != user && s.opponent.thinking { + tr("thinking…") + } else if side == user && active { + tr("your move") + } else if side != user { + tr("waiting") + } else { + "" + }; + // Rodent's style before what he does: «Tal · thinking…». + let state = match s.rival_style().filter(|_| side != user) { + Some(st) if state.is_empty() => st.to_owned(), + Some(st) => format!("{st} · {state}"), + None => state.to_owned(), + }; + // Under the name, not under the king. + ui.horizontal(|ui| { + ui.add_space(king_size + ui.spacing().item_spacing.x); + ui.add(egui::Label::new(RichText::new(state).weak().size(13.0)).truncate()); + }); + }); + if let Some(left) = left { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut t = RichText::new(crate::play::clock_text(left)) + .monospace() + .size(clock_size); + if low { + t = t.color(ui.visuals().error_fg_color); + } else if active { + t = t.strong(); + } else { + t = t.weak(); + } + ui.label(t); + }); + } + }); + }); + ui.add_space(4.0); + } + + /// â�® â—€ â–¶ â�­ · 🔃 · ↶ Take back (a blitz only) · ðŸ�³ Resign (✕ Abort before the first + /// moves). + fn play_toolbar(&mut self, ui: &mut Ui, actions: &mut Vec) { + ui.add_space(4.0); + // Every button of one height; the moves and the board on one row, the game's own + // actions on the next (a row wrapping in the middle of a group looks broken). + const H: f32 = 28.0; + let icon = |s: &str| egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, H)); + let word = |s: &str| egui::Button::new(RichText::new(s).size(14.0)).min_size(vec2(0.0, H)); + ui.horizontal_wrapped(|ui| { + if ui.add(icon("â�®")).clicked() { + self.goto(NodeId::ROOT); + } + if ui.add(icon("â—€")).clicked() { + self.step_back(); + } + if ui.add(icon("â–¶")).clicked() { + self.step_forward(actions); + } + if ui.add(icon("â�­")).clicked() { + let end = self.play_end_node(); + self.goto(end); + } + ui.separator(); + if ui + .add(icon("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.flipped = !self.flipped; + } + }); + ui.horizontal_wrapped(|ui| { + let user = self.play.as_ref().map_or(Color::White, |s| s.user); + let user_moved = self.user_moved(user); + if self.take_back_offered() + && ui + .add_enabled(user_moved, word(tr("↶ Take back"))) + .on_hover_text(tr("Take back a move (Ctrl+Z)")) + .clicked() + { + self.take_back(); + } + if !self.play_started() { + if ui + .add(word(tr("× Abort"))) + .on_hover_text(tr("Leave without a result: no moves made yet")) + .clicked() + { + actions.push(self.leave_action()); + } + } else if self.play.as_ref().is_some_and(|s| s.resign_asked) { + ui.label(RichText::new(tr("Resign?")).size(14.0)); + // «Yes» and «No» of one size, side by side. + if ui + .add_sized( + [56.0, 28.0], + egui::Button::new( + RichText::new(tr("Yes")).size(14.0).color(Color32::WHITE), + ) + .fill(ui.visuals().error_fg_color), + ) + .clicked() + { + let user = self.play.as_ref().map_or(Color::White, |s| s.user); + self.finish_play(crate::play::Ending::Resigned { loser: user }, actions); + } else if ui.add_sized([56.0, 28.0], word(tr("No"))).clicked() + && let Some(s) = self.play.as_mut() + { + s.resign_asked = false; + } + } else if ui.add(word(tr("âš‘ Resign"))).clicked() + && let Some(s) = self.play.as_mut() + { + s.resign_asked = true; + } + // A draw offered: Maia answers by the judge's scores of her last turns (no + // judge, no answer: the button says why). + if self.play_started() { + let judge = self.play.as_ref().and_then(|s| s.judge.as_ref()); + let rival = self + .play + .as_ref() + .map_or(crate::play::Rival::Maia, |s| s.rival()); + let may = judge.is_some_and(|j| j.may_offer_draw()); + let said = |m, r| crate::play::said(rival, m, r); + let hint = match judge { + None => said( + "Maia answers a draw offer with Stockfish's help: none is installed", + "Rodent answers a draw offer with Stockfish's help: none is installed", + ), + Some(_) if !may => said( + "Maia declined; offer again after two of her moves", + "Rodent declined; offer again after two of its moves", + ), + Some(_) => said( + "Maia accepts when her position is no better and has settled", + "Rodent accepts when its position is no better and has settled", + ), + }; + // Short on the button (the row stays one line); the words in the tooltip. + let hint = format!("{}\n{hint}", tr("Offer a draw")); + if ui + .add_enabled(may, word("½–½")) + .on_hover_text(&hint) + .on_disabled_hover_text(&hint) + .clicked() + { + let yes = self + .play + .as_mut() + .and_then(|s| s.judge.as_mut()) + .is_some_and(|j| j.offer_draw()); + if yes { + self.finish_play(crate::play::Ending::DrawAgreed, actions); + } else { + actions.push(GameAction::Toast( + said("Maia declines the draw", "Rodent declines the draw").into(), + )); + } + } + // Leaving without an end, apart from the game's endings. Short of room + // it is its icon (the words in its tooltip). + let hint = format!( + "{}\n{}", + tr("â�¸ Put aside"), + tr("Put the game aside: the clocks stop; go on from its card in the library") + ); + let w = |t: &str| { + ui.fonts_mut(|f| { + f.layout_no_wrap(t.to_owned(), egui::FontId::proportional(14.0), Color32::WHITE) + .size() + .x + }) + 2.0 * ui.spacing().button_padding.x + }; + // What is left of this row (a wrapping row offers its whole width). + let room = ui.max_rect().right() - ui.cursor().min.x; + let full = room >= w(tr("â�¸ Put aside")); + let label = if full { tr("â�¸ Put aside") } else { "â�¸" }; + if ui + .add(word(label)) + .on_hover_text(if full { + tr("Put the game aside: the clocks stop; go on from its card in the library") + } else { + &hint + }) + .clicked() + { + actions.push(GameAction::PutAside(None)); + } + } + }); + ui.add_space(4.0); + } + + /// The strip above the notation after a game: the result and what to do next. + fn result_strip(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(end) = self.play_end.clone() else { + return; + }; + let mut close = false; + ui.add_space(4.0); + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 8)) + .corner_radius(4) + .fill(ui.visuals().extreme_bg_color) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(format!(" {} ", end.ending.result().as_str())) + .strong() + .size(15.0) + .background_color(ui.visuals().widgets.inactive.weak_bg_fill), + ); + ui.label(RichText::new(end.heading()).strong().size(17.0)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Close")) + .clicked() + { + close = true; + } + }); + }); + if !end.detail().is_empty() { + ui.label(end.detail()); + } + if let Some((you, maia)) = end.left { + ui.label( + RichText::new(trf( + crate::play::said( + end.start.rival, + "Left: you {you} · Maia {maia}", + "Left: you {you} · Rodent {maia}", + ), + &[ + ("you", &crate::play::clock_text(you)), + ("maia", &crate::play::clock_text(maia)), + ], + )) + .weak(), + ); + } + // Where the game went by itself (player-games.md §4); a write that failed + // is said, and «Save to a database…» stays for it. + match &self.recorded { + Some(Ok(w)) => { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + // The database's name is under the title already: here only + // the number, the name on hover. + let db = crate::own_db::base_name(&w.path); + ui.label( + RichText::new(trf( + "✔ Written to the database, No. {n}", + &[("n", &(w.index + 1))], + )) + .weak(), + ) + .on_hover_text(&db); + if ui + .link(tr("Open")) + .on_hover_text(tr( + "The database in the library, this game selected", + )) + .clicked() + { + actions.push(GameAction::OpenDatabase(w.path.clone())); + } + }); + } + Some(Err(e)) => { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + None => {} + } + ui.add_space(4.0); + // All in a row when they fit; else Analyse, then Rematch and New game side + // by side, then Save (when the game is not in a database) — each as wide + // as the strip. + let saved = matches!(self.recorded, Some(Ok(_))); + let labels = [ + tr("📈 Analyse"), + tr("↻ Rematch"), + tr("♞ New game"), + tr("💾 Save to a database…"), + ]; + let labels = &labels[..if saved { 3 } else { 4 }]; + let font = egui::FontId::proportional(14.0); + let pad = 2.0 * ui.spacing().button_padding.x + ui.spacing().item_spacing.x; + let one_row: f32 = labels + .iter() + .map(|l| { + ui.painter() + .layout_no_wrap((*l).to_owned(), font.clone(), Color32::WHITE) + .size() + .x + + pad + }) + .sum(); + let fits = one_row <= ui.available_width(); + // A rematch from a position keeps the colour (the position is the task). + let from_side = end.start.from.as_ref().map(|_| end.user); + let mut clicked = [false; 4]; + let mut button = |ui: &mut Ui, k: usize, w: f32| { + let mut text = RichText::new(labels[k]).size(14.0); + let mut b = egui::Button::new(text.clone()); + if k == 0 { + text = text.strong(); + b = egui::Button::new(text).fill(ui.visuals().selection.bg_fill); + } + let mut r = ui.add(b.min_size(vec2(w, 30.0))); + if k == 1 { + r = r.on_hover_text(match &from_side { + Some(Color::White) => tr("The same position, you play White again"), + Some(Color::Black) => tr("The same position, you play Black again"), + None => tr("Same settings, colours swapped"), + }); + } + if k == 3 { + r = r.on_hover_text("Ctrl+S"); + } + clicked[k] = r.clicked(); + }; + if fits { + ui.horizontal(|ui| { + for k in 0..labels.len() { + button(ui, k, 0.0); + } + }); + } else { + let full = ui.available_width(); + button(ui, 0, full); + ui.horizontal(|ui| { + let half = (full - ui.spacing().item_spacing.x) / 2.0; + button(ui, 1, half); + button(ui, 2, half); + }); + if !saved { + button(ui, 3, full); + } + } + if clicked[0] { + self.review_asked = true; + } + if clicked[1] { + actions.push(GameAction::Rematch); + } + if clicked[2] { + actions.push(GameAction::PlayAgain); + } + if clicked[3] { + actions.push(GameAction::Save); + } + }); + if close { + self.play_end = None; + } + } + + /// Dev hook (`CP_SHAPE=Ge2e4,Rd5`): shapes drawn on the board at the current move. + pub fn debug_shapes(&mut self, spec: &str) { + let temporary = self.play.is_some() || self.train.is_some(); + let position = if temporary { + self.game.position(self.cursor).cloned() + } else { + None + }; + let mut record = |drawn| { + if temporary { + if let Some(pos) = &position { + self.board.draw_temporary(drawn, pos); + } + } else { + self.apply_shape(drawn); + } + }; + for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) { + let parsed = chess_core::parse_comment(&if item.len() > 3 { + format!("[%cal {item}]") + } else { + format!("[%csl {item}]") + }); + for p in parsed { + match p { + CommentPart::Annotation(Annotation::Arrows(list)) => { + for (c, a, b) in list { + record(board::Drawn::Arrow(c, a, b)); + } + } + CommentPart::Annotation(Annotation::Squares(list)) => { + for (c, sq) in list { + record(board::Drawn::Circle(c, sq)); + } + } + _ => {} + } + } + } + } + + // ----- learning an opening (docs/design/opening-trainer.md) ---------------------- + + #[cfg(not(web))] + fn add_repertoire_from(&self, at: NodeId, actions: &mut Vec) { + if self.play.is_none() && crate::train::TrainStart::from_game(&self.game, at).is_some() { + actions.push(GameAction::AddToRepertoire(Box::new(self.game.clone()), at)); + } + } + + /// This screen becomes the training of `start` (its game: the line's start). + pub fn start_training(&mut self, start: crate::train::TrainStart) { + self.flipped = start.flipped; + self.train = Some(crate::train::Training::new(start)); + self.goto(NodeId::ROOT); + } + + /// The wrong move shown long enough: taken back. + fn train_tick(&mut self, ctx: &egui::Context) { + if let Some(t) = self.train.as_mut() + && let Some(f) = &t.flash + { + let now = web_time::Instant::now(); + if now >= f.until { + t.flash = None; + } else { + ctx.request_repaint_after(f.until - now); + } + } + } + + /// A move on the board while training: the line's move goes on, another one is a + /// mistake (shown for a moment, then taken back). + fn train_move(&mut self, m: Move, actions: &mut Vec) { + let end = self.game.line_end(NodeId::ROOT); + if self.cursor != end { + // A move in a past position: back to the training. + self.goto(end); + return; + } + let k = self.game.mainline().len(); + let Some(pos) = self.game.position(end).cloned() else { + return; + }; + let Some(t) = self.train.as_mut() else { return }; + if t.done || t.flash.is_some() { + return; + } + let verdict = t.judge(k, m); + if matches!( + verdict, + crate::train::Verdict::Right | crate::train::Verdict::Finished + ) { + if let Ok(id) = self.game.add_move(end, m) { + // The game of the training is never «modified»: nothing to save. + self.game.forget_history(); + self.game.mark_saved(); + self.goto(id); + if verdict == crate::train::Verdict::Finished { + actions.push(GameAction::Sound(Sound::Success)); + } else if let Some(s) = self.sound_for(id) { + actions.push(GameAction::Sound(s)); + } + } + } else if verdict == crate::train::Verdict::Wrong { + let mut after = pos; + after.play_unchecked(m); + t.flash = Some(crate::train::Flash { + after, + from: m.from().unwrap_or(m.to()), + to: crate::board::ui_target(&m), + until: web_time::Instant::now() + crate::train::WRONG_SHOWN, + }); + actions.push(GameAction::Sound(Sound::Wrong)); + } + } + + /// The run again from the start (after the end, or «Restart»). + fn train_again(&mut self) { + if let Some(first) = self.game.main_child(NodeId::ROOT) { + let _ = self.game.delete_variation(first); + } + self.game.forget_history(); + self.game.mark_saved(); + self.goto(NodeId::ROOT); + if let Some(t) = self.train.as_mut() { + t.again(); + } + } + + /// Leaving the training: back to the game it came from. + fn train_leave(&self) -> GameAction { + if self.previous.is_some() { + GameAction::ReturnToPrevious + } else { + GameAction::Back + } + } + + /// The side panel while training: the task above, the moves made, the user's card + /// below; at the end the result instead of both cards. + fn train_side(&mut self, ui: &mut Ui, actions: &mut Vec) { + let done = self.train.as_ref().is_some_and(|t| t.done); + egui::Panel::bottom("train_toolbar").show(ui, |ui| self.train_toolbar(ui, actions)); + if !done { + egui::Panel::bottom("train_you") + .show_separator_line(false) + .show(ui, |ui| self.train_you(ui)); + } + egui::Panel::top("train_task") + .show_separator_line(false) + .show(ui, |ui| { + if done { + self.train_result(ui, actions); + } else { + self.train_task(ui); + } + }); + let end = self.game.line_end(NodeId::ROOT); + if !done && self.cursor != end { + egui::Panel::bottom("train_viewing") + .show_separator_line(false) + .show(ui, |ui| { + if ui + .link( + RichText::new(tr( + "Viewing an earlier position · back to training — End", + )) + .weak(), + ) + .clicked() + { + self.goto(end); + } + }); + } + // At the end the moves with mistakes are marked. + let marks: Option> = + self.train.as_ref().filter(|t| t.done).map(|t| { + self.game + .mainline() + .into_iter() + .zip(t.mistakes.iter().zip(&t.shown)) + .filter(|(_, (n, _))| **n > 0) + .map(|(id, (&n, &s))| (id, (n, s))) + .collect() + }); + egui::CentralPanel::default().show(ui, |ui| { + egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| { + let resp = Notation { + game: &self.game, + cursor: self.cursor, + scroll_to_cursor: self.scroll_to_cursor, + marks: None, + preview: None, + translations: None, + editor: None, + read_only: true, + dim_until: None, + shapes: None, + mistakes: marks.as_ref(), + } + .show(ui); + if let Some(id) = resp.clicked { + self.goto(id); + } + self.scroll_to_cursor = false; + }); + }); + } + + /// The frame of a training card (as a clock card); red while a mistake is shown. + fn train_card(ui: &Ui, alert: bool) -> egui::Frame { + let color = if alert { + ui.visuals().error_fg_color + } else { + ui.visuals().widgets.noninteractive.bg_stroke.color + }; + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 6)) + .corner_radius(4) + .stroke(egui::Stroke::new(if alert { 1.5 } else { 1.0 }, color)) + } + + /// «Move 7 of 12 · â™” White to move», «up to 12…Rd8», the progress bar. + fn train_task(&self, ui: &mut Ui) { + let Some(t) = &self.train else { return }; + let end = self.game.line_end(NodeId::ROOT); + let Some(pos) = self.game.position(end) else { + return; + }; + let played = self.game.mainline().len() as f32; + let total = t.start.line.len().max(1) as f32; + ui.add_space(4.0); + let frame = Self::train_card(ui, false).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(trf( + "Move {n} of {last}", + &[("n", &pos.fullmoves()), ("last", &t.start.last_number)], + )) + .size(15.0), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let white = pos.turn() == Color::White; + let long = if white { + tr("White to move") + } else { + tr("Black to move") + }; + // In a narrow panel the king alone says who moves. + let narrow = ui.available_width() < 110.0; + if !narrow { + ui.label(RichText::new(long).strong().size(15.0)); + } + ui.add(crate::widgets::side_king(white, 17.0).sense(egui::Sense::hover())) + .on_hover_text(long); + }); + }); + ui.label( + RichText::new(trf( + "up to {move}", + &[("move", &crate::san::show(&t.start.up_to))], + )) + .weak() + .size(13.0), + ); + ui.add_space(3.0); + }); + // The progress: a bar of 3 along the bottom, inside the frame. + let r = frame.response.rect.shrink2(vec2(10.0, 0.0)); + let bar = egui::Rect::from_min_max( + egui::pos2(r.left(), r.bottom() - 6.0), + egui::pos2(r.right(), r.bottom() - 3.0), + ); + let p = ui.painter(); + p.rect_filled( + bar, + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + ); + let done = egui::Rect::from_min_max( + bar.min, + egui::pos2(bar.left() + bar.width() * played / total, bar.bottom()), + ); + p.rect_filled(done, 1.0, ui.visuals().selection.bg_fill); + } + + /// «Mistakes: 2 · Run 3», then the history of the line — or, after a wrong move, + /// «× The game has another move here» (and from the third: «Show the move»). + fn train_you(&mut self, ui: &mut Ui) { + let k = self.game.mainline().len(); + let Some(t) = self.train.as_mut() else { return }; + let total = t.total(); + let here = t.mistakes.get(k).copied().unwrap_or(0); + let alert = t.flash.is_some(); + let mut show = false; + ui.add_space(4.0); + Self::train_card(ui, alert).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + let text = RichText::new(trf("Mistakes: {n}", &[("n", &total)])).size(15.0); + ui.label(if total == 0 { text.weak() } else { text }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label( + RichText::new(trf("Run {n}", &[("n", &(t.before.runs + 1))])) + .weak() + .size(13.0), + ); + }); + }); + let error = ui.visuals().error_fg_color; + if t.hint { + ui.label( + RichText::new(tr("Play the move on the arrow")) + .weak() + .size(13.0), + ); + } else if here > 0 { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(tr("× The game has another move here")) + .color(error) + .size(13.0), + ); + if here >= crate::train::HINT_AFTER { + ui.label(RichText::new("·").color(error).size(13.0)); + if ui + .link( + RichText::new(tr("Show the move")) + .color(error) + .size(13.0) + .underline(), + ) + .clicked() + { + show = true; + } + } + }); + } else { + let b = &t.before; + let history = match b.last { + None => tr("Not done before").to_owned(), + Some(last) if b.clean_streak >= 2 => trf( + "Last time: {n} · clean in a row: {k}", + &[("n", &last), ("k", &b.clean_streak)], + ), + Some(last) => trf( + "Last time: {n} · best: {m}", + &[ + ("n", &last), + ("m", &b.best.map_or("—".to_owned(), |x| x.to_string())), + ], + ), + }; + ui.add(egui::Label::new(RichText::new(history).weak().size(13.0)).truncate()); + } + }); + if show { + t.hint = true; + if let Some(s) = t.shown.get_mut(k) { + *s = true; + } + } + } + + /// The end of a run: how it went, the runs so far, «Again» and «Back to the game». + fn train_result(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(t) = &self.train else { return }; + let Some(after) = t.after.clone() else { return }; + let total = t.total(); + let hinted = t.hinted(); + let heading = if hinted { + trf("Done with a hint · mistakes: {n}", &[("n", &total)]) + } else if total == 0 { + tr("Done without mistakes").to_owned() + } else { + trf("Done · mistakes: {n}", &[("n", &total)]) + }; + let line = trf( + "Run {n} · best: {m}", + &[ + ("n", &after.runs), + ("m", &after.best.map_or("—".to_owned(), |x| x.to_string())), + ], + ); + let streak = (after.clean_streak >= 2) + .then(|| trf("clean in a row: {k}", &[("k", &after.clean_streak)])); + // «Recent: 3 · 2 · 1 · 0», this run (the last) bold. + let recent = (after.recent.len() > 1).then(|| { + let runs: Vec = after + .recent + .iter() + .map(|(n, h)| if *h { format!("{n}*") } else { n.to_string() }) + .collect(); + let (last, rest) = runs.split_last().unwrap_or((&runs[0], &[])); + let mut head = rest.join(" · "); + head.push_str(" · "); + let text = trf("Recent: {runs}", &[("runs", &format!("{head}{last}"))]); + let weak = ui.visuals().weak_text_color(); + let strong = ui.visuals().strong_text_color(); + let font = egui::FontId::proportional(13.0); + let mut job = egui::text::LayoutJob::default(); + let cut = text.len() - last.len(); + job.append( + &text[..cut], + 0.0, + egui::TextFormat::simple(font.clone(), weak), + ); + job.append(&text[cut..], 0.0, egui::TextFormat::simple(font, strong)); + job + }); + let mut again = false; + let mut back = false; + ui.add_space(4.0); + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 8)) + .corner_radius(4) + .fill(ui.visuals().extreme_bg_color) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + let color = if total == 0 && !hinted { + // Lichess's «good move» green. + Color32::from_rgb(98, 153, 36) + } else { + ui.visuals().strong_text_color() + }; + ui.label(RichText::new(heading).strong().size(17.0).color(color)); + ui.label(RichText::new(line).size(13.0)); + if let Some(s) = streak { + ui.label(RichText::new(s).size(13.0)); + } + if let Some(r) = recent { + ui.add(egui::Label::new(r).wrap()); + } + ui.add_space(6.0); + let w = ui.available_width(); + let row = w >= 300.0; + let half = if row { + (w - ui.spacing().item_spacing.x) / 2.0 + } else { + w + }; + let mut buttons = |ui: &mut Ui| { + if ui + .add_sized( + [half, 30.0], + egui::Button::new(RichText::new(tr("↻ Again")).strong().size(14.0)) + .fill(ui.visuals().selection.bg_fill), + ) + .on_hover_text("Enter") + .clicked() + { + again = true; + } + if ui + .add_sized( + [half, 30.0], + egui::Button::new(RichText::new(tr("⬅ Back to the game")).size(14.0)), + ) + .on_hover_text("Esc") + .clicked() + { + back = true; + } + }; + if row { + ui.horizontal(|ui| buttons(ui)); + } else { + buttons(ui); + } + }); + if again { + self.train_again(); + } + if back { + actions.push(self.train_leave()); + } + } + + /// â�® â—€ â–¶ â�­ │ 🔃 │ ↻ Restart │ × Leave + fn train_toolbar(&mut self, ui: &mut Ui, actions: &mut Vec) { + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + let big = |s: &str| RichText::new(s).size(18.0); + let word = + |s: &str| egui::Button::new(RichText::new(s).size(14.0)).min_size(vec2(0.0, 28.0)); + if ui.button(big("â�®")).clicked() { + self.goto(NodeId::ROOT); + } + if ui.button(big("â—€")).clicked() { + self.step_back(); + } + if ui.button(big("â–¶")).clicked() { + self.step_forward(actions); + } + if ui.button(big("â�­")).clicked() { + let end = self.game.line_end(NodeId::ROOT); + self.goto(end); + } + ui.separator(); + if ui + .button(big("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.flipped = !self.flipped; + } + let done = self.train.as_ref().is_some_and(|t| t.done); + if !done { + ui.separator(); + let started = self.game.main_child(NodeId::ROOT).is_some(); + if ui + .add_enabled(started, word(tr("↻ Restart"))) + .on_hover_text(tr("Start the run again; this one is not counted")) + .clicked() + { + self.train_again(); + } + if ui + .add(word(tr("× Leave"))) + .on_hover_text(tr("Back to the game; the run is not counted (Esc)")) + .clicked() + { + actions.push(self.train_leave()); + } + } + }); + ui.add_space(4.0); + } + + /// Keys while training: looking through the moves, flipping, Esc back to the game, + /// Enter again after the end; the engine stays off. + fn train_keys(&mut self, ui: &Ui, actions: &mut Vec) { + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let done = self.train.as_ref().is_some_and(|t| t.done); + let mut cmds = Vec::new(); + ui.input_mut(|i| { + if i.consume_shortcut(&ctrl(Key::W)) { + cmds.push("library"); + } + if !i.modifiers.any() { + for (key, cmd) in [ + (Key::ArrowLeft, "back1"), + (Key::ArrowRight, "fwd1"), + (Key::ArrowUp, "end"), + (Key::ArrowDown, "home"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::L, "engine"), + ] { + if i.key_pressed(key) { + cmds.push(cmd); + } + } + // Esc first lets go of a piece or the choice of a promotion. + if !self.board.is_busy() && i.consume_key(Modifiers::NONE, Key::Escape) { + cmds.push("leave"); + } + if done && i.consume_key(Modifiers::NONE, Key::Enter) { + cmds.push("again"); + } + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) { + cmds.push("engine"); + } + }); + for cmd in cmds { + match cmd { + "back1" => self.step_back(), + "fwd1" => self.step_forward(actions), + "home" => self.goto(NodeId::ROOT), + "end" => { + let end = self.game.line_end(NodeId::ROOT); + self.goto(end); + } + "flip" => self.flipped = !self.flipped, + "engine" => actions.push(GameAction::Toast( + tr("The engine is off while training").to_owned(), + )), + "leave" => actions.push(self.train_leave()), + "library" => actions.push(GameAction::Back), + "again" => self.train_again(), + _ => {} + } + } + } + + /// Dev hook (`CP_TRAIN`): the training up to the current move. + pub fn debug_train(&self) -> Option { + let mut t = crate::train::TrainStart::from_game(&self.game, self.cursor)?; + t.flipped = self.flipped; + Some(t) + } + + #[cfg(not(web))] + pub fn debug_repertoire_source(&self) -> Option<(Game, NodeId)> { + crate::train::TrainStart::from_game(&self.game, self.cursor) + .map(|_| (self.game.clone(), self.cursor)) + } + + /// Dev hook (`CP_TRAIN_MOVES`): moves of the training made as on the board (UCI; + /// a wrong one is a mistake). + pub fn debug_train_moves(&mut self, uci: &str) { + let mut sink = Vec::new(); + for w in uci.split_whitespace() { + self.train_tick_now(); + let end = self.game.line_end(NodeId::ROOT); + let Some(pos) = self.game.position(end).cloned() else { + return; + }; + if let Some(m) = w + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + { + self.train_move(m, &mut sink); + } + } + } + + /// The wrong move taken back at once (the hook makes moves without waiting). + fn train_tick_now(&mut self) { + if let Some(t) = self.train.as_mut() + && t.flash + .as_ref() + .is_some_and(|_| std::env::var_os("CP_TRAIN_KEEP").is_none()) + { + t.flash = None; + } + } + + /// Dev hook (`CP_PLAY_FROM`): «Play on from here» at the current move. + pub fn debug_play_from(&mut self) -> Option { + self.start_from(self.cursor).ok() + } + + /// Dev hook (`CP_PASTE_LINE`): the text pasted as a line, as by Ctrl+V. + pub fn debug_paste(&mut self, text: &str) { + self.paste_request = Some(text.to_owned()); + } + + // ----- a line from the clipboard (docs/design/paste-variation.md) ---------------- + + /// The menu's «Paste a line from the clipboard»: the clipboard is read, the line + /// pasted once it is there (at once on a computer). + fn paste_clipboard(&mut self, ctx: &egui::Context) { + self.clipboard = Some(crate::platform::clipboard::read_text(ctx)); + } + + /// Pastes `text` as a line: at once where the user stands, a question when it + /// goes elsewhere, a message when it does not fit (the game then unchanged). + fn paste_text(&mut self, text: &str, actions: &mut Vec) { + use chess_core::paste::PasteError; + if self.play.is_some() { + return; + } + self.commit_editor(); + self.preview = None; + match chess_core::paste::plan(&self.game, self.cursor, text) { + Ok(plan) if self.paste_elsewhere(&plan) => self.paste_pending = Some(plan), + Ok(plan) => self.paste_apply(plan, actions), + Err(e) => { + let msg = match &e { + PasteError::NoMoves => tr("The clipboard holds no moves").to_owned(), + PasteError::DoesNotFit => trf( + "These moves fit neither after {move} nor instead of it", + &[("move", &self.node_label(self.cursor))], + ), + PasteError::Illegal { number, side, san } => trf( + "The move {move} is impossible — nothing inserted", + &[("move", &move_label(*number, *side, san, true))], + ), + PasteError::Unrelated => tr( + "The game in the clipboard does not fit: none of its positions occur in this game", + ) + .to_owned(), + PasteError::AlreadyThere { comments: false, .. } => { + tr("These moves are already in the game").to_owned() + } + PasteError::AlreadyThere { comments: true, .. } => tr( + "These moves are already in the game — the comments from the clipboard were not carried over", + ) + .to_owned(), + }; + // «Already there»: here they are. + if let PasteError::AlreadyThere { at, .. } = e { + self.goto(at); + self.scroll_to_cursor = true; + } + actions.push(GameAction::Toast(msg)); + } + } + } + + /// The line would not go where the user looks: not the selected move, not after + /// it, not instead of it (and the start of the game looks at everything). + fn paste_elsewhere(&self, plan: &chess_core::paste::PastePlan) -> bool { + let c = self.cursor; + !(c == NodeId::ROOT + || plan.at == c + || self.game.parent(c) == Some(plan.at) + || self.game.path(plan.at).contains(&c)) + } + + /// Inserts the line: the cursor on its first move, a message naming it. + fn paste_apply( + &mut self, + mut plan: chess_core::paste::PastePlan, + actions: &mut Vec, + ) { + // The note on the move order is written in the interface's language. + plan.transposition = plan + .transposition + .take() + .map(|m| trf("By another move order: {moves}", &[("moves", &m)])); + let line = paste_line(&plan.line); + let after = (plan.at != NodeId::ROOT).then(|| self.node_label(plan.at)); + match self.game.apply_paste(&plan) { + Ok(first) => { + self.goto(first); + self.scroll_to_cursor = true; + let mut msg = if plan.continuation && plan.at != NodeId::ROOT { + trf( + "The game is continued: {moves} (Ctrl+Z to undo)", + &[("moves", &line)], + ) + } else { + match after { + Some(m) => trf( + "Line {moves} inserted after {move} (Ctrl+Z to undo)", + &[("moves", &line), ("move", &m)], + ), + None => trf( + "Line {moves} inserted at the start of the game (Ctrl+Z to undo)", + &[("moves", &line)], + ), + } + }; + if plan.games > 1 { + msg.push(' '); + msg.push_str(&trf( + "The clipboard has {count} games — the first one is inserted.", + &[("count", &plan.games)], + )); + } + actions.push(GameAction::Toast(msg)); + } + Err(e) => actions.push(GameAction::Toast(e.to_string())), + } + } + + /// «12.Nf3» / «12…Nf6» of a node, as shown (the start: «the start of the game»). + fn node_label(&self, id: NodeId) -> String { + match (self.game.move_number(id), self.game.game_move(id)) { + (Some((n, side)), Some(m)) => move_label(n, side, &m.san, true), + _ => tr("the start of the game").to_owned(), + } + } + + /// «Insert the line earlier?»: Enter inserts, Esc does not. + fn paste_question(&mut self, ctx: &egui::Context, actions: &mut Vec) { + let Some(plan) = &self.paste_pending else { + return; + }; + let from = (plan.at != NodeId::ROOT).then(|| self.node_label(plan.at)); + let cursor = self.node_label(self.cursor); + let earlier = self.game.path(self.cursor).contains(&plan.at); + let text = match (&from, earlier) { + (None, _) => { + tr("The game in the clipboard parts from this one at the start of the game.") + .to_owned() + } + (Some(f), true) => trf( + "The game in the clipboard parts from this one before the selected move: after {from}, not after {cursor}.", + &[("from", f), ("cursor", &cursor)], + ), + (Some(f), false) => trf( + "The game in the clipboard parts from this one in another line: after {from}.", + &[("from", f)], + ), + }; + let button = match &from { + Some(f) => trf("Insert after {move}", &[("move", f)]), + None => tr("Insert at the start").to_owned(), + }; + let line = paste_line_full(&plan.line); + let source = plan.source_ref.clone(); + let mut choice = None; + let width = (ctx.content_rect().width() - 32.0).min(460.0); + egui::Modal::new(egui::Id::new("paste_question")).show(ctx, |ui| { + ui.set_width(width); + ui.heading(tr("Insert the line earlier?")); + ui.add_space(4.0); + ui.label(text); + ui.add_space(8.0); + egui::Frame::new() + .inner_margin(egui::Margin::same(8)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.add(egui::Label::new(RichText::new(&line).size(14.0)).truncate()); + if let Some(s) = &source { + ui.label(RichText::new(s).weak().size(13.0)); + } + }); + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::primary(ui, &button).clicked() { + choice = Some(true); + } + if ui + .add(egui::Button::new(tr("Cancel")).min_size(vec2(0.0, 30.0))) + .clicked() + { + choice = Some(false); + } + }); + }); + if choice.is_none() { + ctx.input_mut(|i| { + if i.consume_key(Modifiers::NONE, Key::Enter) { + choice = Some(true); + } else if i.consume_key(Modifiers::NONE, Key::Escape) { + choice = Some(false); + } + }); + } + match choice { + Some(true) => { + if let Some(plan) = self.paste_pending.take() { + self.paste_apply(plan, actions); + } + } + Some(false) => self.paste_pending = None, + None => {} + } + } + + /// Dev hook (`CP_COMMENT_EDIT`): the editor on the current move. + pub fn debug_comment_edit(&mut self) { + self.open_editor(Slot::After(self.cursor)); + } + + /// Dev hook (`CP_COMMENT`): a comment after the current move. + pub fn debug_comment(&mut self, text: &str) { + let nags = self + .game + .node(self.cursor) + .map(|n| n.nags().to_vec()) + .unwrap_or_default(); + let _ = self.game.annotate(self.cursor, nags, vec![text.to_owned()]); + } + + fn step_back(&mut self) { + if let Some(p) = &mut self.preview { + self.scroll_to_cursor = true; + p.shown = p.shown.saturating_sub(1); + if p.shown == 0 { + self.preview = None; + } + return; + } + if let Some(parent) = self.game.parent(self.cursor) { + self.goto(parent); + } + } + + fn step_forward(&mut self, actions: &mut Vec) { + if let Some(p) = &mut self.preview { + if p.shown < p.moves.len() { + self.scroll_to_cursor = true; + p.shown += 1; + actions.push(GameAction::Sound(Sound::Move)); + } + return; + } + if let Some(next) = self.game.main_child(self.cursor) { + self.goto(next); + if let Some(s) = self.sound_for(next) { + actions.push(GameAction::Sound(s)); + } + } + } + + fn undo(&mut self) { + if let Some(o) = self.game.undo() { + self.goto(o.cursor); + } + } + + fn redo(&mut self) { + if let Some(o) = self.game.redo() { + self.goto(o.cursor); + } + } + + fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() { + return; + } + // A modal question or dialog over the game has the keys (its Enter and Esc); + // the game under it does not change. + if self.paste_pending.is_some() || ui.ctx().memory(|m| m.top_modal_layer()).is_some() { + return; + } + if self.play.is_some() { + self.play_keys(ui, actions); + return; + } + if self.train.is_some() { + self.train_keys(ui, actions); + return; + } + // Ctrl+V: egui gives it as the text pasted, not as a key. + let pasted = ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::Paste(t) => Some(t.clone()), + _ => None, + }) + }); + if let Some(text) = pasted + && self.paste_pending.is_none() + { + self.paste_text(&text, actions); + } + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let ctrl_shift = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k); + let overlay = crate::app::overlay_open(ui.ctx()); + let mut cmds = Vec::new(); + ui.input_mut(|i| { + if i.consume_shortcut(&ctrl_shift(Key::Z)) || i.consume_shortcut(&ctrl(Key::Y)) { + cmds.push("redo"); + } + if i.consume_shortcut(&ctrl(Key::Z)) { + cmds.push("undo"); + } + if i.consume_shortcut(&ctrl_shift(Key::C)) { + cmds.push("copy"); + } + if i.consume_shortcut(&ctrl_shift(Key::S)) { + cmds.push("add_to_db"); + } + if i.consume_shortcut(&ctrl(Key::S)) { + cmds.push("save"); + } + // F2 as in ChessBase; on a Mac F2 is the brightness key, ⌘I too. + if i.consume_key(Modifiers::NONE, Key::F2) + || (cfg!(target_os = "macos") && i.consume_shortcut(&ctrl(Key::I))) + { + cmds.push("game_data"); + } + if i.consume_shortcut(&ctrl(Key::W)) { + cmds.push("back"); + } + // A browser keeps Ctrl+W, Ctrl+1…6 and Ctrl+Shift+C for itself + // (docs/design/web-version.md §4): Alt+â†�, plain 1…6 and Ctrl+C there. + if cfg!(web) { + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::ALT, Key::ArrowLeft)) { + cmds.push("back"); + } + if i.consume_shortcut(&ctrl(Key::C)) { + cmds.push("copy"); + } + } + if i.consume_shortcut(&ctrl(Key::G)) { + cmds.push("play_from"); + } + if i.consume_shortcut(&ctrl_shift(Key::F)) { + cmds.push("find"); + } + if i.consume_shortcut(&ctrl_shift(Key::T)) { + cmds.push("translate"); + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) { + cmds.push("review"); + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::ArrowUp)) { + cmds.push("prev_var"); + } + for (key, cmd) in [ + (Key::Num1, "nag1"), + (Key::Num2, "nag2"), + (Key::Num3, "nag3"), + (Key::Num4, "nag4"), + (Key::Num5, "nag5"), + (Key::Num6, "nag6"), + ] { + if i.consume_shortcut(&ctrl(key)) + || (cfg!(web) && i.consume_key(Modifiers::NONE, key)) + { + cmds.push(cmd); + } + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::ArrowDown)) { + cmds.push("next_var"); + } + if i.modifiers.is_none() { + for (key, cmd) in [ + (Key::ArrowLeft, "back1"), + (Key::ArrowRight, "fwd1"), + (Key::ArrowUp, "end"), + (Key::ArrowDown, "home"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::L, "engine"), + (Key::Escape, "esc"), + ] { + if i.key_pressed(key) { + cmds.push(cmd); + } + } + // Taken: the Enter that closed a dialog this frame must not open the editor. + if i.key_pressed(Key::Enter) && !overlay && i.modifiers.is_none() { + i.consume_key(Modifiers::NONE, Key::Enter); + cmds.push("comment"); + } + } + }); + for cmd in cmds { + match cmd { + "undo" if self.editor.is_none() => self.undo(), + "redo" if self.editor.is_none() => self.redo(), + "comment" => { + if self.preview.is_none() { + self.open_editor(Slot::After(self.cursor)); + } + } + "nag1" | "nag2" | "nag3" | "nag4" | "nag5" | "nag6" => { + if self.preview.is_none() { + let k: u8 = cmd[3..].parse().unwrap_or(1); + // With the editor open the symbol is part of its draft. + match self.editor.as_mut() { + Some(ed) if ed.slot == Slot::After(self.cursor) => { + ed.nags = toggle_nag(&ed.nags, Nag(k)); + } + _ => self.toggle_nag_on(self.cursor, Nag(k)), + } + } + } + "copy" => actions.push(self.copy_pgn()), + "save" => actions.push(GameAction::Save), + "play_from" if crate::platform::CAPS.play => { + let at = self.cursor; + self.play_from(at, actions); + } + "add_to_db" if crate::platform::CAPS.own_databases => { + actions.push(GameAction::AddToDatabase) + } + "game_data" => actions.push(GameAction::EditGameData), + "back" => actions.push(GameAction::BackKey), + "find" if crate::platform::CAPS.reference && self.search_line().is_some() => { + actions.push(GameAction::FindPosition(None)) + } + "back1" => self.step_back(), + "fwd1" => self.step_forward(actions), + "prev_var" => { + if self.preview.is_none() + && let Some(s) = self.game.prev_sibling(self.cursor) + { + self.goto(s); + } + } + "next_var" => { + if self.preview.is_none() + && let Some(s) = self.game.next_sibling(self.cursor) + { + self.goto(s); + } + } + "home" => self.goto(NodeId::ROOT), + "end" => { + let end = self.game.line_end(self.cursor); + self.goto(end); + } + "flip" => self.flipped = !self.flipped, + "translate" if crate::platform::CAPS.translation => { + if self.translation.has_translation() { + self.translation.toggle(); + } else if self.translation.can_translate() { + self.translate_now = true; + self.side_tab = SideTab::Notation; + } + } + "engine" => actions.push(GameAction::ToggleEngine), + "review" => { + if self.review.has_data() || self.review.running() { + self.review.visible = !self.review.visible; + } else { + self.review_asked = true; + } + } + // Escape cancels what is going on first (a preview of an engine line, a + // piece picked up); then it leaves the game: to the game this one was + // opened from, or to the library. A window, menu or dialog open over the + // game takes the key itself. + "esc" => { + if self.preview.is_some() { + self.preview = None; + } else if self.board.is_busy() { + self.board.clear(); + } else if !crate::app::overlay_open(ui.ctx()) { + // Taken: the question about unsaved edits that leaving may open in + // this frame must not read the same key as its own Escape. + ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)); + actions.push(if self.previous.is_some() { + GameAction::ReturnToPrevious + } else { + GameAction::Back + }); + } + } + _ => {} + } + } + } +} + +/// The least widths and heights of the game screen (docs/design/narrow-windows.md §1): +/// the side panel (notation, report), its reference tab, the board, the notation part +/// under a stacked board, the evaluation bar with its gap. +const SIDE_MIN: f32 = 240.0; +const REF_MIN: f32 = 320.0; +const BOARD_MIN: f32 = 220.0; +const STACK_BOTTOM_MIN: f32 = 300.0; +const EVAL_BAR: f32 = 26.0; +/// The engine row alone (the "Analysis" toggle), as counted in `STACK_BOTTOM_MIN`. +const ENGINE_ROW: f32 = 44.0; + +const SEARCH_TIMES: [Option; 11] = [ + Some(2), + Some(4), + Some(6), + Some(8), + Some(10), + Some(15), + Some(20), + Some(30), + Some(60), + Some(90), + None, +]; + +/// Lichess-style inline engine settings: engine choice, search time, lines, threads, memory. +fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec) { + egui::Frame::new() + .fill(ui.visuals().extreme_bg_color) + .inner_margin(egui::Margin::symmetric(12, 8)) + .corner_radius(4) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label(tr("Engine")); + let current = settings + .active_engine() + .map(|e| e.name.clone()) + .unwrap_or_else(|| tr("not selected").into()); + egui::ComboBox::from_id_salt("engine_pick") + .selected_text(current) + .width(ui.available_width() - 40.0) + .show_ui(ui, |ui| { + for i in 0..settings.engines.len() { + let selected = settings.active_engine == Some(i); + if ui + .selectable_label(selected, &settings.engines[i].name) + .clicked() + && !selected + { + settings.active_engine = Some(i); + actions.push(GameAction::EngineSwitch); + } + } + ui.separator(); + if ui.button(tr("Add or edit engines…")).clicked() { + actions.push(GameAction::OpenEngineSettings); + } + }); + }); + let Some(i) = settings + .active_engine + .filter(|i| *i < settings.engines.len()) + else { + if ui.button(tr("Add engine…")).clicked() { + actions.push(GameAction::OpenEngineSettings); + } + return; + }; + let e = &mut settings.engines[i]; + let cores = std::thread::available_parallelism() + .map(|n| n.get() as u32) + .unwrap_or(1); + let hash_steps = hash_steps(); + let mut settled = false; + // Each setting: its name, the slider, the value. The slider gets what the + // measured names and values leave; in a narrow panel (under 100 pt for it) + // the name and the value share a line above a slider across the panel. + let mut t = SEARCH_TIMES + .iter() + .position(|s| *s == e.search_secs) + .unwrap_or(SEARCH_TIMES.len() - 1); + let mut k = e.multipv.clamp(1, 5) as usize - 1; + let mut th = e.threads.clamp(1, cores) as usize - 1; + let mut h = hash_steps + .iter() + .position(|m| *m >= e.hash_mb) + .unwrap_or(hash_steps.len() - 1); + let search_value = |t: usize| { + SEARCH_TIMES[t] + .map(|s| trf("{n} s", &[("n", &s)])) + .unwrap_or_else(|| "∞".into()) + }; + let names = [tr("Search time"), tr("Lines"), tr("Threads"), tr("Memory")]; + // The widest value each setting can show, so the slider does not jump. + let widest = [ + (0..SEARCH_TIMES.len()) + .map(search_value) + .collect::>(), + vec!["5 / 5".to_owned()], + vec![format!("{cores} / {cores}")], + hash_steps.iter().map(|m| format_mb(*m)).collect(), + ]; + let font = egui::TextStyle::Body.resolve(ui.style()); + let text_w = |t: &str| { + ui.painter() + .layout_no_wrap(t.to_owned(), font.clone(), Color32::WHITE) + .size() + .x + }; + let name_w = names.iter().map(|n| text_w(n)).fold(0.0, f32::max); + let value_w = widest + .iter() + .flatten() + .map(|v| text_w(v)) + .fold(0.0, f32::max); + let gap = 12.0; + let slider = (ui.available_width() - name_w - value_w - 2.0 * gap).floor(); + let mut rows: [(&str, &mut usize, usize); 4] = [ + (names[0], &mut t, SEARCH_TIMES.len()), + (names[1], &mut k, 5), + (names[2], &mut th, cores as usize), + (names[3], &mut h, hash_steps.len()), + ]; + let value = |i: usize, idx: usize| match i { + 0 => search_value(idx), + 1 => format!("{} / 5", idx + 1), + 2 => format!("{} / {cores}", idx + 1), + _ => format_mb(hash_steps[idx]), + }; + // In a browser threads and memory are the platform's: one thread (the + // single-threaded engine), its memory (design §1.5). + let shown = if crate::platform::CAPS.engine_programs { + 4 + } else { + 2 + }; + if slider >= 100.0 { + ui.spacing_mut().slider_width = slider; + egui::Grid::new("engine_settings_grid") + .num_columns(3) + .spacing(vec2(gap, 8.0)) + .show(ui, |ui| { + for (i, (name, idx, len)) in rows.iter_mut().enumerate().take(shown) { + ui.label(*name); + settled |= index_slider(ui, idx, *len); + ui.label(value(i, **idx)); + ui.end_row(); + } + }); + } else { + ui.spacing_mut().slider_width = ui.available_width().floor(); + for (i, (name, idx, len)) in rows.iter_mut().enumerate().take(shown) { + ui.horizontal(|ui| { + ui.label(*name); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(value(i, **idx)); + }); + }); + settled |= index_slider(ui, idx, *len); + ui.add_space(4.0); + } + } + e.search_secs = SEARCH_TIMES[t]; + e.multipv = k as u32 + 1; + e.threads = th as u32 + 1; + e.hash_mb = hash_steps[h]; + if settled { + actions.push(GameAction::EngineReconfigure); + } + }); +} + +/// Slider over `0..len`; returns true when the user finished changing it. +pub(crate) fn index_slider(ui: &mut Ui, idx: &mut usize, len: usize) -> bool { + let before = *idx; + let r = ui.add(egui::Slider::new(idx, 0..=len.saturating_sub(1)).show_value(false)); + r.drag_stopped() || (*idx != before && !r.dragged()) +} + +pub(crate) fn format_mb(mb: u32) -> String { + if mb >= 1024 { + trf("{n} GB", &[("n", &(mb / 1024))]) + } else { + trf("{n} MB", &[("n", &mb)]) + } +} + +/// Hash sizes from 16 MB up to half of physical memory (powers of two). +pub(crate) fn hash_steps() -> Vec { + let total_mb = std::fs::read_to_string("/proc/meminfo") + .ok() + .and_then(|s| { + s.lines() + .find(|l| l.starts_with("MemTotal:")) + .and_then(|l| l.split_whitespace().nth(1)) + .and_then(|kb| kb.parse::().ok()) + }) + .map(|kb| kb / 1024) + .unwrap_or(4096); + let max = (total_mb / 2).clamp(16, 65536) as u32; + let mut v = vec![16]; + while v.last().is_some_and(|m| m * 2 <= max) { + let next = v.last().copied().unwrap_or(16) * 2; + v.push(next); + } + v +} + +#[derive(Clone, Copy)] +enum GameOver { + Mated(Color), + Draw(&'static str), +} + +impl GameOver { + fn label(self) -> &'static str { + match self { + GameOver::Mated(Color::White) => tr("Checkmate · 0-1"), + GameOver::Mated(Color::Black) => tr("Checkmate · 1-0"), + GameOver::Draw(s) => s, + } + } +} + +/// Terminal positions: engines send no PV there, so the UI states the outcome itself. +fn game_over(pos: &Chess) -> Option { + if pos.is_checkmate() { + Some(GameOver::Mated(pos.turn())) + } else if pos.is_stalemate() { + Some(GameOver::Draw(tr("Stalemate · ½-½"))) + } else if pos.is_insufficient_material() { + Some(GameOver::Draw(tr("Insufficient material"))) + } else { + None + } +} + +/// Engine arrows (live analysis and game analysis) are all blue; a move both suggest +/// is drawn once, with the stronger of the two looks. +fn engine_arrow(arrows: &mut Vec, (from, to): (Square, Square), alpha: u8, weight: f32) { + let color = Color32::from_rgba_unmultiplied(0, 48, 136, alpha); + if let Some(a) = arrows.iter_mut().find(|a| a.from == from && a.to == to) { + if a.color.a() < color.a() { + a.color = color; + } + a.weight = a.weight.max(weight); + return; + } + arrows.push(Arrow { + from, + to, + color, + weight, + }); +} + +/// "1-0", "0-1", "½-½"; `None` for an unfinished game. +fn result_label(r: GameResult) -> Option<&'static str> { + match r { + GameResult::WhiteWins => Some("1-0"), + GameResult::BlackWins => Some("0-1"), + GameResult::Draw => Some("½-½"), + GameResult::Unknown => None, + } +} + +fn result_hint(r: GameResult) -> &'static str { + match r { + GameResult::WhiteWins => tr("White won"), + GameResult::BlackWins => tr("Black won"), + _ => tr("Draw"), + } +} + +fn move_squares(m: &Move) -> Option<(Square, Square)> { + Some((m.from()?, board::ui_target(m))) +} + +pub(crate) fn shape_color(c: ShapeColor) -> Color32 { + match c { + ShapeColor::Red => Color32::from_rgba_unmultiplied(136, 32, 32, 170), + ShapeColor::Green => Color32::from_rgba_unmultiplied(21, 120, 27, 170), + ShapeColor::Blue => Color32::from_rgba_unmultiplied(0, 48, 136, 170), + ShapeColor::Yellow => Color32::from_rgba_unmultiplied(230, 143, 0, 170), + ShapeColor::Other(_) => Color32::from_rgba_unmultiplied(120, 120, 120, 170), + } +} + +/// The width of `text` in `style` (as a label or a button would lay it out on one line). +pub(crate) fn text_width(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { + ui.painter() + .layout_no_wrap(text.to_owned(), style.resolve(ui.style()), Color32::WHITE) + .size() + .x +} + +/// A move as shown: «12.Nf3», «12…Nf6» (`numbered`: black's number too). +fn move_label(n: u32, side: Color, san: &str, numbered: bool) -> String { + let label = match side { + Color::White => format!("{n}.{san}"), + Color::Black if numbered => format!("{n}…{san}"), + Color::Black => san.to_owned(), + }; + crate::san::show(&label).into_owned() +} + +/// The moves of a pasted line as shown: all of a short one, else «first … last». +fn paste_line(line: &[(u32, Color, String)]) -> String { + if line.len() <= 3 { + return paste_line_full(line); + } + let one = |(n, side, san): &(u32, Color, String)| move_label(*n, *side, san, true); + format!("{} … {}", one(&line[0]), one(&line[line.len() - 1])) +} + +/// Every move of a line, numbered as in the notation. +fn paste_line_full(line: &[(u32, Color, String)]) -> String { + line.iter() + .enumerate() + .map(|(i, (n, side, san))| move_label(*n, *side, san, i == 0)) + .collect::>() + .join(" ") +} + +impl GameView { + /// The report tab and the graph shown (a game opened at a move the search for great + /// moves found). + pub fn show_report(&mut self) { + self.review.visible = true; + self.side_tab = SideTab::Report; + } +} + +/// «📈 Analyse game» in the colour of «!!» (task 26): the report it makes marks its finds +/// with it. Hover and press stay visible (egui's own states, shaded); a disabled button +/// keeps the usual look. +fn review_colored( + ui: &mut egui::Ui, + enabled: bool, + add: impl FnOnce(&mut egui::Ui) -> egui::Response, +) -> egui::Response { + if !enabled { + return add(ui); + } + let dark = ui.visuals().dark_mode; + let Some(fill) = crate::notation::assessment_text_color(Nag(3), dark) else { + return add(ui); + }; + // The icon dark on the dark theme's teal, white on the light one's (contrast ≥ 4.5:1). + let icon = if dark { + egui::Color32::from_rgb(0x1b, 0x1b, 0x1b) + } else { + egui::Color32::WHITE + }; + let (hover, press) = if dark { + ( + fill.lerp_to_gamma(egui::Color32::WHITE, 0.18), + fill.lerp_to_gamma(egui::Color32::BLACK, 0.15), + ) + } else { + ( + fill.lerp_to_gamma(egui::Color32::BLACK, 0.15), + fill.lerp_to_gamma(egui::Color32::BLACK, 0.3), + ) + }; + ui.scope(|ui| { + let w = &mut ui.visuals_mut().widgets; + for (state, color) in [ + (&mut w.inactive, fill), + (&mut w.hovered, hover), + (&mut w.active, press), + ] { + state.weak_bg_fill = color; + state.bg_fill = color; + state.fg_stroke.color = icon; + } + add(ui) + }) + .inner +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::settings::Hint; + use std::collections::HashSet; + + type Shapes = (Vec<(ShapeColor, Square, Square)>, Vec<(ShapeColor, Square)>); + + fn view(pgn: &str) -> GameView { + let parsed = chess_core::parse_str(pgn); + GameView::new(parsed.game, None, parsed.diagnostics) + } + + /// The node reached by these moves from the start, through any variation. + fn at(game: &Game, moves: &[&str]) -> NodeId { + moves.iter().fold(NodeId::ROOT, |node, san| { + *game + .children(node) + .iter() + .find(|c| game.game_move(**c).is_some_and(|m| m.san == *san)) + .unwrap_or_else(|| panic!("no {san} after {node:?}")) + }) + } + + fn sq(s: &str) -> Square { + s.parse().unwrap() + } + + fn arrow(color: ShapeColor, from: &str, to: &str) -> board::Drawn { + board::Drawn::Arrow(color, sq(from), sq(to)) + } + + fn shapes_at(game: &Game, id: NodeId) -> Shapes { + chess_core::shapes(game.node(id).unwrap().comments_after()) + } + + /// Written to PGN and read again: the shapes of the same node. + fn reread(game: &Game, moves: &[&str]) -> Shapes { + let text = chess_core::write_game(game, &Default::default()); + let back = chess_core::parse_str(&text).game; + shapes_at(&back, at(&back, moves)) + } + + #[test] + fn a_shape_goes_into_the_current_move_and_back_out() { + let mut v = view("1. e4 e5 {Open game [%clk 0:05:00]} $1 2. Nf3 *"); + let e5 = at(&v.game, &["e4", "e5"]); + v.goto(e5); + v.apply_shape(arrow(ShapeColor::Green, "g1", "f3")); + assert_eq!( + shapes_at(&v.game, e5), + (vec![(ShapeColor::Green, sq("g1"), sq("f3"))], vec![]) + ); + let node = v.game.node(e5).unwrap(); + assert_eq!(node.nags(), &[Nag(1)]); + let text = node.comments_after().join(" "); + assert!( + text.contains("Open game") && text.contains("[%clk 0:05:00]"), + "{text}" + ); + assert_eq!( + reread(&v.game, &["e4", "e5"]).0, + vec![(ShapeColor::Green, sq("g1"), sq("f3"))] + ); + + // Another colour repaints it, the same colour again takes it off. + v.apply_shape(arrow(ShapeColor::Red, "g1", "f3")); + assert_eq!( + shapes_at(&v.game, e5).0, + vec![(ShapeColor::Red, sq("g1"), sq("f3"))] + ); + v.apply_shape(arrow(ShapeColor::Red, "g1", "f3")); + assert!(shapes_at(&v.game, e5).0.is_empty()); + + // One step of undo per shape. + v.game.undo(); + assert_eq!( + shapes_at(&v.game, e5).0, + vec![(ShapeColor::Red, sq("g1"), sq("f3"))] + ); + v.game.undo(); + v.game.undo(); + assert_eq!(shapes_at(&v.game, e5), (vec![], vec![])); + assert!(!v.game.is_modified()); + } + + #[test] + fn circles_toggle_and_recolour() { + let mut v = view("1. d4 *"); + let d4 = at(&v.game, &["d4"]); + v.goto(d4); + v.apply_shape(board::Drawn::Circle(ShapeColor::Green, sq("d5"))); + v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5"))); + v.apply_shape(board::Drawn::Circle(ShapeColor::Yellow, sq("d5"))); + assert_eq!( + shapes_at(&v.game, d4).1, + vec![(ShapeColor::Yellow, sq("d5")), (ShapeColor::Blue, sq("e5"))] + ); + v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5"))); + assert_eq!( + shapes_at(&v.game, d4).1, + vec![(ShapeColor::Yellow, sq("d5"))] + ); + } + + #[test] + fn a_shape_at_the_start_stays_with_the_start() { + let mut v = view("{Intro} 1. e4 e5 *"); + v.apply_shape(arrow(ShapeColor::Blue, "e2", "e4")); + assert_eq!( + reread(&v.game, &[]).0, + vec![(ShapeColor::Blue, sq("e2"), sq("e4"))] + ); + let text = chess_core::write_game(&v.game, &Default::default()); + assert!(text.contains("Intro"), "{text}"); + assert!(shapes_at(&v.game, at(&v.game, &["e4"])).0.is_empty()); + } + + #[test] + fn a_shape_in_a_nested_variation_stays_there() { + let mut v = view("1. e4 e5 (1... c5 2. Nf3 (2. c3 d5) 2... d6) 2. Nf3 *"); + let path = ["e4", "c5", "c3", "d5"]; + let d5 = at(&v.game, &path); + v.goto(d5); + v.apply_shape(arrow(ShapeColor::Green, "e4", "d5")); + assert_eq!( + reread(&v.game, &path).0, + vec![(ShapeColor::Green, sq("e4"), sq("d5"))] + ); + assert!(reread(&v.game, &["e4", "e5"]).0.is_empty()); + } + + #[test] + fn a_shape_after_a_null_move_and_from_a_fen_with_move_zero() { + let mut v = view("1. e4 -- 2. d4 *"); + let null = at(&v.game, &["e4", "--"]); + v.goto(null); + v.apply_shape(board::Drawn::Circle(ShapeColor::Red, sq("d4"))); + assert_eq!( + reread(&v.game, &["e4", "--"]).1, + vec![(ShapeColor::Red, sq("d4"))] + ); + + let mut v = + view("[FEN \"4k3/8/8/8/8/8/8/4K3 b - - 0 0\"]\n[SetUp \"1\"]\n\n0... Kd7 1. Ke2 *"); + let kd7 = at(&v.game, &["Kd7"]); + v.goto(kd7); + v.apply_shape(arrow(ShapeColor::Yellow, "e1", "e2")); + assert_eq!( + reread(&v.game, &["Kd7"]).0, + vec![(ShapeColor::Yellow, sq("e1"), sq("e2"))] + ); + } + + #[test] + fn a_shape_drawn_marks_the_hint_done_and_counts_for_the_notation() { + let mut v = view("1. e4 e5 {[%csl Gd5]} *"); + assert_eq!(v.shape_counts().len(), 1); + let e4 = at(&v.game, &["e4"]); + v.goto(e4); + v.apply_shape(arrow(ShapeColor::Green, "g1", "f3")); + assert!(v.shape_drawn); + assert_eq!( + v.shape_counts().get(&e4), + Some(&ShapeCount { + arrows: 1, + circles: 0 + }) + ); + assert_eq!(v.shape_counts().len(), 2); + v.game.undo(); + assert_eq!(v.shape_counts().len(), 1); + } + + #[test] + fn the_hint_is_decided_once_per_game_and_not_beside_the_translation() { + let mut hint = Hint::default(); + let mut seen = HashSet::new(); + + // With the translation strip: not shown, not counted. + let mut v = view("1. e4 *"); + assert!(!v.decide_shapes_hint(&mut hint, &mut seen, true)); + assert_eq!(v.shapes_hint, Some(false)); + assert_eq!(hint.shown, 0); + assert!(seen.is_empty()); + + // Decided on the first frame only. + let mut v = view("1. e4 *"); + assert!(v.decide_shapes_hint(&mut hint, &mut seen, false)); + assert!(!v.decide_shapes_hint(&mut hint, &mut seen, false)); + assert_eq!((v.shapes_hint, hint.shown), (Some(true), 1)); + + // The same game opened again in the session: shown, not counted. + let source = |index| GameSource { + path: PathBuf::from("/tmp/a.pgn"), + index, + block: None, + }; + let open = |index| { + let mut v = view("1. e4 *"); + v.source = Some(source(index)); + v + }; + let mut a = open(0); + assert!(a.decide_shapes_hint(&mut hint, &mut seen, false)); + let mut again = open(0); + assert!(!again.decide_shapes_hint(&mut hint, &mut seen, false)); + assert_eq!((again.shapes_hint, hint.shown), (Some(true), 2)); + + let mut b = open(1); + b.decide_shapes_hint(&mut hint, &mut seen, false); + assert_eq!(hint.shown, 3); + // The third counted game opened again keeps the hint, uncounted. + let mut b_again = open(1); + assert!(!b_again.decide_shapes_hint(&mut hint, &mut seen, false)); + assert_eq!((b_again.shapes_hint, hint.shown), (Some(true), 3)); + // The fourth game: gone by itself. + let mut c = open(2); + assert!(!c.decide_shapes_hint(&mut hint, &mut seen, false)); + assert_eq!(c.shapes_hint, Some(false)); + } + + #[test] + fn the_hint_is_not_shown_while_playing_or_after_it_is_done() { + let mut seen = HashSet::new(); + let mut hint = Hint { + done: true, + shown: 0, + }; + let mut v = view("1. e4 *"); + v.decide_shapes_hint(&mut hint, &mut seen, false); + assert_eq!(v.shapes_hint, Some(false)); + + let mut hint = Hint::default(); + let mut v = view("1. e4 *"); + v.preview = Some(Preview { + base: NodeId::ROOT, + root: Chess::default(), + moves: Vec::new(), + san: Vec::new(), + shown: 0, + }); + v.decide_shapes_hint(&mut hint, &mut seen, false); + assert_eq!((v.shapes_hint, hint.shown), (Some(false), 0)); + } +} diff --git a/apps/desktop/src/graphics.rs b/apps/desktop/src/graphics.rs new file mode 100644 index 0000000..8a7091c --- /dev/null +++ b/apps/desktop/src/graphics.rs @@ -0,0 +1,276 @@ +//! Starting the window on machines whose graphics do not cooperate (an old driver, a +//! broken Vulkan, a virtual machine, remote desktop). A start that fails or dies before +//! the first frames tries the next, more modest mode; the mode that worked is kept. +//! A failure no mode overcomes, and any panic, is shown in a message box and written to +//! `chesspenguin.log` beside the settings: a Windows program has no console to print to. + +use std::io::Write as _; +use std::path::PathBuf; +use std::sync::OnceLock; + +use eframe::egui_wgpu::{WgpuConfiguration, WgpuSetup, WgpuSetupCreateNew}; +use eframe::wgpu; + +/// The ways to draw, from the usual one to software rendering. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// wgpu's own choice: Vulkan, DirectX 12 or Metal, then OpenGL. + Default, + /// Without Vulkan (a broken Vulkan driver can kill the process on Windows). + NoVulkan, + /// OpenGL only. + OpenGl, + /// The processor draws (WARP on Windows, llvmpipe on Linux): slow but works. + Software, +} + +const MODES: [Mode; 4] = [Mode::Default, Mode::NoVulkan, Mode::OpenGl, Mode::Software]; + +static CURRENT: OnceLock = OnceLock::new(); +static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn state_file() -> Option { + crate::settings::Settings::config_dir().map(|d| d.join("graphics")) +} + +pub fn log_file() -> Option { + crate::settings::Settings::config_dir().map(|d| d.join("chesspenguin.log")) +} + +/// The state file: "trying N" while a start in mode N is not yet known to work, +/// "ok N" once it drew its first frames. +fn read_state() -> Option<(bool, usize)> { + let text = std::fs::read_to_string(state_file()?).ok()?; + let (word, n) = text.trim().split_once(' ')?; + let n: usize = n.parse().ok()?; + (n < MODES.len()).then_some((word == "ok", n)) +} + +fn write_state(ok: bool, n: usize) { + if let Some(f) = state_file() { + if let Some(d) = f.parent() { + let _ = std::fs::create_dir_all(d); + } + let _ = std::fs::write(f, format!("{} {n}", if ok { "ok" } else { "trying" })); + } +} + +/// Set for a process started again after a failed start: the modes tried so far. +const TRIED: &str = "CP_GRAPHICS_TRIED"; + +/// The mode for this start: the one that worked last time, the next one after a start +/// that died before its first frame, or the one a failed start chose for this process. +/// `WGPU_BACKEND` set by hand wins. +pub fn choose() -> Mode { + if std::env::var_os("WGPU_BACKEND").is_some() { + return *CURRENT.get_or_init(|| Mode::Default); + } + let retrying = std::env::var_os(TRIED).is_some(); + let n = match read_state() { + Some((ok, n)) if ok || retrying => n, + Some((_, n)) => { + let next = (n + 1) % MODES.len(); + log(&format!( + "the last start in mode {:?} did not finish, trying {:?}", + MODES[n], MODES[next] + )); + next + } + None => 0, + }; + write_state(false, n); + *CURRENT.get_or_init(|| MODES[n]) +} + +/// The first frame is shown: keep this mode for the next starts. +pub fn started() { + if STARTED.swap(true, std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Some(&mode) = CURRENT.get() + && std::env::var_os("WGPU_BACKEND").is_none() + && let Some(n) = MODES.iter().position(|m| *m == mode) + && read_state() != Some((true, n)) + { + write_state(true, n); + if mode != Mode::Default { + log(&format!("started in mode {mode:?}")); + } + } +} + +/// The start in this mode failed with an error: start again in a mode not tried yet +/// (a new process: the window system allows one event loop per process). False when +/// every mode has failed. +pub fn retry(error: &str) -> bool { + let mode = CURRENT.get().copied().unwrap_or(Mode::Default); + log(&format!("the start in mode {mode:?} failed: {error}")); + let n = MODES.iter().position(|m| *m == mode).unwrap_or(0); + let mut tried: Vec = std::env::var(TRIED) + .unwrap_or_default() + .split(',') + .filter_map(|t| t.parse().ok()) + .collect(); + tried.push(n); + let next = (1..MODES.len()) + .map(|k| (n + k) % MODES.len()) + .find(|m| !tried.contains(m)); + let exe = std::env::current_exe(); + let (Some(next), Ok(exe), None) = (next, exe, std::env::var_os("WGPU_BACKEND")) else { + if let Some(f) = state_file() { + let _ = std::fs::remove_file(f); + } + return false; + }; + write_state(false, next); + let tried: Vec = tried.iter().map(|t| t.to_string()).collect(); + std::process::Command::new(exe) + .args(std::env::args_os().skip(1)) + .env(TRIED, tried.join(",")) + .spawn() + .is_ok() +} + +pub fn options(mode: Mode) -> WgpuConfiguration { + let mut setup = WgpuSetupCreateNew::without_display_handle(); + let backends = &mut setup.instance_descriptor.backends; + match mode { + Mode::Default => return WgpuConfiguration::default(), + Mode::NoVulkan => { + *backends = (wgpu::Backends::PRIMARY | wgpu::Backends::GL) - wgpu::Backends::VULKAN + } + Mode::OpenGl => *backends = wgpu::Backends::GL, + Mode::Software => { + *backends = wgpu::Backends::all(); + setup.native_adapter_selector = Some(std::sync::Arc::new(|adapters, surface| { + adapters + .iter() + .filter(|a| a.get_info().device_type == wgpu::DeviceType::Cpu) + .find(|a| surface.is_none_or(|s| a.is_surface_supported(s))) + .cloned() + .ok_or_else(|| "no software renderer".to_owned()) + })); + } + } + WgpuConfiguration { + wgpu_setup: WgpuSetup::CreateNew(setup), + ..Default::default() + } +} + +/// The warnings of the window and graphics libraries (wgpu, eframe, winit…) go to the log +/// and to stderr: a window that stops drawing says why there. One message repeated (a +/// dropped frame each frame) is written once a minute with how many times it came. +struct LibraryLog { + last: std::sync::Mutex>, + /// `CP_LOG_FRAMES=1`: also how each frame reaches the screen (egui_wgpu's debug and + /// trace messages: a frame skipped as "occluded" is said only there). + frames: bool, +} + +impl log::Log for LibraryLog { + fn enabled(&self, metadata: &log::Metadata) -> bool { + metadata.level() <= log::Level::Warn + || (self.frames && metadata.target().starts_with("egui_wgpu")) + } + + fn log(&self, record: &log::Record) { + if !self.enabled(record.metadata()) { + return; + } + let text = format!("{} {}: {}", record.level(), record.target(), record.args()); + let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((prev, since, count)) = last.as_mut() + && *prev == text + && since.elapsed() < std::time::Duration::from_secs(60) + { + *count += 1; + return; + } + if let Some((prev, _, count)) = last.take() + && count > 0 + { + log(&format!("{prev} (and {count} times more)")); + } + eprintln!("{text}"); + log(&text); + *last = Some((text, web_time::Instant::now(), 0)); + } + + fn flush(&self) {} +} + +/// Starts writing the libraries' warnings (see [`LibraryLog`]). +pub fn init_library_log() { + static LOGGER: OnceLock = OnceLock::new(); + let logger = LOGGER.get_or_init(|| LibraryLog { + last: std::sync::Mutex::new(None), + frames: std::env::var_os("CP_LOG_FRAMES").is_some(), + }); + if log::set_logger(logger).is_ok() { + log::set_max_level(if logger.frames { + log::LevelFilter::Trace + } else { + log::LevelFilter::Warn + }); + } +} + +/// Appends a line to the log (kept under a megabyte). +pub fn log(line: &str) { + let Some(f) = log_file() else { + return; + }; + if let Some(d) = f.parent() { + let _ = std::fs::create_dir_all(d); + } + if std::fs::metadata(&f).is_ok_and(|m| m.len() > 1 << 20) { + let _ = std::fs::remove_file(&f); + } + let now = web_time::SystemTime::now() + .duration_since(web_time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&f) + { + let _ = writeln!( + file, + "[{now}] ChessPenguin {}: {line}", + env!("CARGO_PKG_VERSION") + ); + } +} + +/// A message box for what ended the program (there may be no window to show it in). +pub fn fatal(text: &str) { + let path = log_file() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Error) + .set_title("ChessPenguin") + .set_description(format!( + "{}\n\n{text}\n\n{}", + crate::i18n::tr("ChessPenguin could not start."), + crate::i18n::trf("Details are in {path}", &[("path", &path)]), + )) + .set_buttons(rfd::MessageButtons::Ok) + .show(); +} + +/// Panics go to the log; one on the main thread also to a message box. +pub fn install_panic_hook() { + let default = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let thread = std::thread::current(); + let name = thread.name().unwrap_or("?").to_owned(); + let backtrace = std::backtrace::Backtrace::force_capture(); + log(&format!("panic in thread {name}: {info}\n{backtrace}")); + default(info); + if name == "main" { + fatal(&info.to_string()); + } + })); +} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs new file mode 100644 index 0000000..d69cdc4 --- /dev/null +++ b/apps/desktop/src/i18n.rs @@ -0,0 +1,21144 @@ +//! UI translations. The English text is the key; missing entries fall back to English. + +use std::collections::HashMap; +use std::fmt::Display; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU8, Ordering}; + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +pub enum Lang { + #[default] + En, + Ru, + Fr, + De, + Es, + It, + /// Brazilian Portuguese. + Pt, + /// Uzbek in the Latin script. + Uz, + /// Kazakh in the Cyrillic script. + Kk, +} + +impl Lang { + pub const ALL: [Lang; 9] = [ + Lang::En, + Lang::Ru, + Lang::Fr, + Lang::De, + Lang::Es, + Lang::It, + Lang::Pt, + Lang::Uz, + Lang::Kk, + ]; + + /// Native language name. + pub fn label(self) -> &'static str { + match self { + Lang::En => "English", + Lang::Ru => "РуÑ�Ñ�кий", + Lang::Fr => "Français", + Lang::De => "Deutsch", + Lang::Es => "Español", + Lang::It => "Italiano", + Lang::Pt => "Português", + Lang::Uz => "O‘zbekcha", + Lang::Kk => "Қазақша", + } + } + + fn column(self) -> usize { + self as usize + } + + /// The first supported language among the system's preferred ones ("uk-UA, ru-RU" + /// gives Russian), or English. + pub fn from_locales>(locales: impl IntoIterator) -> Lang { + locales + .into_iter() + .find_map(|l| Lang::from_locale(l.as_ref())) + .unwrap_or_default() + } + + /// The language of a locale ("ru-RU", "ru_RU.UTF-8", "de-CH", "es-419", "fr"), if + /// it is one of ours. + pub fn from_locale(locale: &str) -> Option { + let code = locale + .split(['-', '_', '.', '@']) + .next()? + .to_ascii_lowercase(); + match code.as_str() { + "en" => Some(Lang::En), + "ru" => Some(Lang::Ru), + "fr" => Some(Lang::Fr), + "de" => Some(Lang::De), + "es" => Some(Lang::Es), + "it" => Some(Lang::It), + "pt" => Some(Lang::Pt), + "uz" => Some(Lang::Uz), + "kk" => Some(Lang::Kk), + _ => None, + } + } + + /// The language of this system (see [`Lang::from_locales`]). + pub fn system() -> Lang { + Lang::from_locales(sys_locale::get_locales()) + } +} + +#[cfg(not(test))] +static CURRENT: AtomicU8 = AtomicU8::new(0); +// Tests run in parallel threads: a test that switches the language switches only its own. +#[cfg(test)] +thread_local! { + static CURRENT: AtomicU8 = const { AtomicU8::new(0) }; +} + +pub fn set_lang(lang: Lang) { + #[cfg(not(test))] + CURRENT.store(lang as u8, Ordering::Relaxed); + #[cfg(test)] + CURRENT.with(|c| c.store(lang as u8, Ordering::Relaxed)); +} + +pub fn current() -> Lang { + #[cfg(not(test))] + let index = CURRENT.load(Ordering::Relaxed); + #[cfg(test)] + let index = CURRENT.with(|c| c.load(Ordering::Relaxed)); + Lang::ALL.get(index as usize).copied().unwrap_or_default() +} + +fn table() -> &'static HashMap<&'static str, &'static [&'static str; 9]> { + static MAP: OnceLock> = OnceLock::new(); + MAP.get_or_init(|| ROWS.iter().map(|row| (row[0], row)).collect()) +} + +/// Translates an English UI string into the current language. +pub fn tr(key: &'static str) -> &'static str { + let lang = current(); + if lang == Lang::En { + return key; + } + table() + .get(key) + .map(|row| row[lang.column()]) + .unwrap_or(key) +} + +/// `key` in every language (English first; the same text once). +pub fn all_languages(key: &'static str) -> Vec<&'static str> { + let mut out = vec![key]; + for t in table().get(key).into_iter().flat_map(|row| row.iter()) { + if !out.contains(t) { + out.push(t); + } + } + out +} + +/// "1 game", "5 games" in the interface language, with Russian plural forms +/// ("1 партиÑ�", "3 партии", "5 партий"). +pub fn games(n: usize) -> String { + let num = crate::large_db::grouped(n); + match current() { + Lang::Ru => { + let word = match (n % 10, n % 100) { + (1, x) if x != 11 => "партиÑ�", + (2..=4, x) if !(12..=14).contains(&x) => "партии", + _ => "партий", + }; + format!("{num} {word}") + } + Lang::En => format!("{num} {}", if n == 1 { "game" } else { "games" }), + Lang::Fr => format!("{num} {}", if n <= 1 { "partie" } else { "parties" }), + Lang::De => format!("{num} {}", if n == 1 { "Partie" } else { "Partien" }), + Lang::Es => format!("{num} {}", if n == 1 { "partida" } else { "partidas" }), + Lang::It => format!("{num} {}", if n == 1 { "partita" } else { "partite" }), + Lang::Pt => format!("{num} {}", if n == 1 { "partida" } else { "partidas" }), + // A noun after a number stays singular in Uzbek and Kazakh. + // "ta" counts things: "38 ta partiya", as in the other Uzbek texts. + Lang::Uz => format!("{num} ta partiya"), + Lang::Kk => format!("{num} партиÑ�"), + } +} + +/// [`games`] as the object of a verb: «разберёт 1 партию» in Russian; the same as +/// [`games`] in the other languages. +pub fn games_object(n: usize) -> String { + match current() { + Lang::Ru if n % 10 == 1 && n % 100 != 11 => { + format!("{} партию", crate::large_db::grouped(n)) + } + _ => games(n), + } +} + +/// Whether `n` takes the singular in the current language (a verb or an adjective +/// after the number: «1 партиÑ� разобрана», «21 партиÑ� разобрана», «2 партии разобраны»). +pub fn is_one(n: usize) -> bool { + match current() { + Lang::Ru => n % 10 == 1 && n % 100 != 11, + Lang::Fr => n <= 1, + // The noun after a number stays singular, and so does what goes with it. + Lang::Uz | Lang::Kk => true, + _ => n == 1, + } +} + +/// "1 text", "21 texts" (guiding texts of a database), with Russian plural forms +/// ("1 текÑ�Ñ‚", "3 текÑ�та", "5 текÑ�тов"). +pub fn texts(n: usize) -> String { + let num = crate::large_db::grouped(n); + match current() { + Lang::Ru => { + let word = match (n % 10, n % 100) { + (1, x) if x != 11 => "текÑ�Ñ‚", + (2..=4, x) if !(12..=14).contains(&x) => "текÑ�та", + _ => "текÑ�тов", + }; + format!("{num} {word}") + } + Lang::En => format!("{num} {}", if n == 1 { "text" } else { "texts" }), + Lang::Fr => format!("{num} {}", if n <= 1 { "texte" } else { "textes" }), + Lang::De => format!("{num} {}", if n == 1 { "Text" } else { "Texte" }), + Lang::Es => format!("{num} {}", if n == 1 { "texto" } else { "textos" }), + Lang::It => format!("{num} {}", if n == 1 { "testo" } else { "testi" }), + Lang::Pt => format!("{num} {}", if n == 1 { "texto" } else { "textos" }), + Lang::Uz => format!("{num} ta matn"), + Lang::Kk => format!("{num} мәтін"), + } +} + +/// "11,7 млн партий" / "267 партий": a database size in a short form. +pub fn games_short(n: usize) -> String { + if n >= 1_000_000 { + let short = crate::large_db::short_count(n); + let word = match current() { + Lang::Ru => "партий", + Lang::En => "games", + Lang::Fr => "parties", + Lang::De => "Partien", + Lang::Es => "partidas", + Lang::It => "partite", + Lang::Pt => "partidas", + Lang::Uz => "ta partiya", + Lang::Kk => "партиÑ�", + }; + format!("{short} {word}") + } else { + games(n) + } +} + +/// Translates and substitutes `{name}` placeholders. +pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String { + let mut s = tr(key).to_string(); + for (name, value) in args { + s = s.replace(&format!("{{{name}}}"), &value.to_string()); + } + s +} + +// [English, РуÑ�Ñ�кий, Français, Deutsch, Español, Italiano, Português (BR), O‘zbekcha, Қазақша] +// Uzbek o‘ and g‘ are written with ‘ (U+2018): the interface font has no U+02BB. +const ROWS: &[[&str; 9]] = &[ + [ + "You play White", + "Ð’Ñ‹ играете белыми", + "Vous jouez les Blancs", + "Sie spielen Weiß", + "Juegas con blancas", + "Giochi con il Bianco", + "Você joga de brancas", + "Siz oq bilan o‘ynaysiz", + "Сіз ақпен ойнайÑ�ыз", + ], + [ + "You play Black", + "Ð’Ñ‹ играете чёрными", + "Vous jouez les Noirs", + "Sie spielen Schwarz", + "Juegas con negras", + "Giochi con il Nero", + "Você joga de pretas", + "Siz qora bilan o‘ynaysiz", + "Сіз қарамен ойнайÑ�ыз", + ], + [ + "Correct!", + "Верно", + "Exact !", + "Richtig!", + "¡Correcto!", + "Esatto!", + "Correto!", + "To‘g‘ri!", + "ДұрыÑ�!", + ], + [ + "tomorrow", + "завтра", + "demain", + "morgen", + "mañana", + "domani", + "amanhã", + "ertaga", + "ертең", + ], + [ + "today at {time}", + "Ñ�егоднÑ� в {time}", + "aujourd’hui à {time}", + "heute um {time}", + "hoy a las {time}", + "oggi alle {time}", + "hoje às {time}", + "bugun soat {time} da", + "бүгін {time}", + ], + [ + "in {days} days", + "через {days} дн.", + "dans {days} jours", + "in {days} Tagen", + "en {days} días", + "tra {days} giorni", + "em {days} dias", + "{days} kundan keyin", + "{days} күннен кейін", + ], + [ + "Not trained", + "Ð�е тренируетÑ�Ñ�", + "Pas entraînée", + "Wird nicht trainiert", + "No se entrena", + "Non allenata", + "Não treinada", + "Mashq qilinmaydi", + "Жаттықтырылмайды", + ], + [ + "Counting moves…", + "Считаем ходы…", + "Comptage des coups…", + "Züge werden gezählt…", + "Contando jugadas…", + "Conteggio delle mosse…", + "Contando lances…", + "Yurishlar sanalmoqda…", + "ЖүріÑ�тер Ñ�аналуда…", + ], + [ + "Review all", + "Повторить вÑ�Ñ‘", + "Tout réviser", + "Alles wiederholen", + "Repasar todo", + "Ripassa tutto", + "Revisar tudo", + "Hammasini takrorlash", + "Барлығын қайталау", + ], + [ + "Review all lines", + "Повторить вÑ�Ñ‘ подрÑ�д", + "Réviser toutes les lignes", + "Alle Varianten wiederholen", + "Repasar todas las líneas", + "Ripassa tutte le linee", + "Revisar todas as linhas", + "Barcha variantlarni takrorlash", + "Барлық нұÑ�қаны қайталау", + ], + [ + "Train this branch", + "Тренировать Ñ�ту ветку", + "Entraîner cette branche", + "Diesen Zweig trainieren", + "Entrenar esta rama", + "Allena questo ramo", + "Treinar este ramo", + "Shu shoxni mashq qilish", + "ОÑ�Ñ‹ тармақты жаттықтыру", + ], + [ + "Train again", + "Снова тренировать", + "Entraîner à nouveau", + "Wieder trainieren", + "Volver a entrenar", + "Allena di nuovo", + "Treinar de novo", + "Yana mashq qilish", + "Қайта жаттықтыру", + ], + [ + "Don't train", + "Ð�е тренировать", + "Ne pas entraîner", + "Nicht trainieren", + "No entrenar", + "Non allenare", + "Não treinar", + "Mashq qilmaslik", + "Жаттықтырмау", + ], + [ + "⬅ Repertoires", + "⬅ Репертуары", + "⬅ Répertoires", + "⬅ Repertoires", + "⬅ Repertorios", + "⬅ Repertori", + "⬅ Repertórios", + "⬅ Repertuarlar", + "⬅ Репертуарлар", + ], + [ + "⬅ Lines", + "⬅ Варианты", + "⬅ Lignes", + "⬅ Varianten", + "⬅ Líneas", + "⬅ Linee", + "⬅ Linhas", + "⬅ Variantlar", + "⬅ Ð�Ò±Ñ�қалар", + ], + [ + "⬅ To game", + "⬅ К партии", + "⬅ À la partie", + "⬅ Zur Partie", + "⬅ A la partida", + "⬅ Alla partita", + "⬅ Para a partida", + "⬅ Partiyaga", + "⬅ ПартиÑ�ға", + ], + [ + "Lines · {n} lines · {y} your moves", + "Варианты · вариантов: {n} · ваших ходов: {y}", + "Lignes · {n} lignes · {y} de vos coups", + "Varianten · {n} Varianten · {y} eigene Züge", + "Líneas · {n} líneas · {y} jugadas tuyas", + "Linee · {n} linee · {y} tue mosse", + "Linhas · {n} linhas · {y} lances seus", + "Variantlar · {n} ta variant · sizning {y} ta yurishingiz", + "Ð�Ò±Ñ�қалар · {n} нұÑ�қа · Ñ�іздің {y} жүріÑ�іңіз", + ], + [ + "Training · you play White", + "Тренировка · вы играете белыми", + "Entraînement · vous jouez les Blancs", + "Training · Sie spielen Weiß", + "Entrenamiento · juegas con blancas", + "Allenamento · giochi con il Bianco", + "Treino · você joga de brancas", + "Mashq · siz oq bilan o‘ynaysiz", + "Жаттығу · Ñ�із ақпен ойнайÑ�ыз", + ], + [ + "Training · you play Black", + "Тренировка · вы играете чёрными", + "Entraînement · vous jouez les Noirs", + "Training · Sie spielen Schwarz", + "Entrenamiento · juegas con negras", + "Allenamento · giochi con il Nero", + "Treino · você joga de pretas", + "Mashq · siz qora bilan o‘ynaysiz", + "Жаттығу · Ñ�із қарамен ойнайÑ�ыз", + ], + [ + "Review all lines · you play White", + "Повторение подрÑ�д · вы играете белыми", + "Révision de toutes les lignes · vous jouez les Blancs", + "Alle Varianten · Sie spielen Weiß", + "Repaso de todas las líneas · juegas con blancas", + "Ripasso di tutte le linee · giochi con il Bianco", + "Revisão de todas as linhas · você joga de brancas", + "Barchasini takrorlash · siz oq bilan o‘ynaysiz", + "Бәрін қайталау · Ñ�із ақпен ойнайÑ�ыз", + ], + [ + "Review all lines · you play Black", + "Повторение подрÑ�д · вы играете чёрными", + "Révision de toutes les lignes · vous jouez les Noirs", + "Alle Varianten · Sie spielen Schwarz", + "Repaso de todas las líneas · juegas con negras", + "Ripasso di tutte le linee · giochi con il Nero", + "Revisão de todas as linhas · você joga de pretas", + "Barchasini takrorlash · siz qora bilan o‘ynaysiz", + "Бәрін қайталау · Ñ�із қарамен ойнайÑ�ыз", + ], + [ + "Watch", + "Смотрите", + "Regardez", + "Zuschauen", + "Observa", + "Guarda", + "Observe", + "Kuzating", + "Қараңыз", + ], + [ + "Moves up to your next question", + "Ходы до вашего Ñ�ледующего вопроÑ�а", + "Les coups jusqu’à votre prochaine question", + "Die Züge bis zu Ihrer nächsten Frage", + "Las jugadas hasta tu próxima pregunta", + "Le mosse fino alla prossima domanda", + "Os lances até a sua próxima pergunta", + "Keyingi savolingizgacha bo‘lgan yurishlar", + "КелеÑ�Ñ– Ñ�ұрағыңызға дейінгі жүріÑ�тер", + ], + [ + "Next line", + "Следующий вариант", + "Ligne suivante", + "Nächste Variante", + "Siguiente línea", + "Linea successiva", + "Próxima linha", + "Keyingi variant", + "КелеÑ�Ñ– нұÑ�қа", + ], + [ + "New move", + "Ð�овый ход", + "Nouveau coup", + "Neuer Zug", + "Jugada nueva", + "Mossa nuova", + "Lance novo", + "Yangi yurish", + "Жаңа жүріÑ�", + ], + [ + "Your move", + "Ваш ход", + "À vous", + "Ihr Zug", + "Tu jugada", + "Tocca a te", + "Sua vez", + "Sizning yurishingiz", + "Сіздің жүріÑ�іңіз", + ], + [ + "Play the move from your repertoire", + "Сыграйте ход из репертуара", + "Jouez le coup de votre répertoire", + "Spielen Sie den Zug Ihres Repertoires", + "Juega la jugada de tu repertorio", + "Gioca la mossa del tuo repertorio", + "Jogue o lance do seu repertório", + "Repertuaringizdagi yurishni qiling", + "Репертуарыңыздағы жүріÑ�ті жаÑ�аңыз", + ], + [ + "Not this move", + "Ð�е тот ход", + "Pas ce coup", + "Nicht dieser Zug", + "No es esta jugada", + "Non è questa mossa", + "Não é este lance", + "Bu yurish emas", + "Бұл жүріÑ� емеÑ�", + ], + [ + "This one is in your repertoire too", + "Этот ход тоже еÑ�ть в репертуаре", + "Ce coup est aussi dans votre répertoire", + "Auch dieser Zug ist in Ihrem Repertoire", + "Esta jugada también está en tu repertorio", + "Anche questa mossa è nel tuo repertorio", + "Este lance também está no seu repertório", + "Bu yurish ham repertuaringizda bor", + "Бұл жүріÑ� те репертуарыңызда бар", + ], + [ + "Got it", + "Запомним", + "Noté", + "Gemerkt", + "Anotado", + "Ricevuto", + "Anotado", + "Eslab qolamiz", + "ЕÑ�те Ñ�ақтаймыз", + ], + [ + "Could not save your answer", + "Ð�е удалоÑ�ÑŒ Ñ�охранить ответ", + "Impossible d’enregistrer votre réponse", + "Ihre Antwort konnte nicht gespeichert werden", + "No se pudo guardar tu respuesta", + "Impossibile salvare la risposta", + "Não foi possível salvar sua resposta", + "Javobingizni saqlab bo‘lmadi", + "Жауабыңызды Ñ�ақтау мүмкін болмады", + ], + [ + "Could not continue the session", + "Ð�е удалоÑ�ÑŒ продолжить занÑ�тие", + "Impossible de poursuivre la séance", + "Die Übung konnte nicht fortgesetzt werden", + "No se pudo continuar la sesión", + "Impossibile continuare la sessione", + "Não foi possível continuar a sessão", + "Mashg‘ulotni davom ettirib bo‘lmadi", + "Сабақты жалғаÑ�тыру мүмкін болмады", + ], + [ + "Session stopped", + "ЗанÑ�тие прервано", + "Séance interrompue", + "Übung abgebrochen", + "Sesión interrumpida", + "Sessione interrotta", + "Sessão interrompida", + "Mashg‘ulot to‘xtatildi", + "Сабақ үзілді", + ], + [ + "Session complete", + "ЗанÑ�тие окончено", + "Séance terminée", + "Übung beendet", + "Sesión terminada", + "Sessione completata", + "Sessão concluída", + "Mashg‘ulot tugadi", + "Сабақ аÑ�қталды", + ], + [ + "Everything is saved", + "Ð’Ñ�Ñ‘ Ñ�охранено", + "Tout est enregistré", + "Alles ist gespeichert", + "Todo está guardado", + "Tutto è salvato", + "Tudo está salvo", + "Hammasi saqlandi", + "Бәрі Ñ�ақталды", + ], + [ + "left", + "оÑ�талоÑ�ÑŒ", + "restants", + "übrig", + "quedan", + "rimaste", + "restantes", + "qoldi", + "қалды", + ], + [ + "line", + "вариант", + "ligne", + "Variante", + "línea", + "linea", + "linha", + "variant", + "нұÑ�қа", + ], + [ + "Lines reviewed", + "Пройдено вариантов", + "Lignes révisées", + "Wiederholte Varianten", + "Líneas repasadas", + "Linee ripassate", + "Linhas revisadas", + "Takrorlangan variantlar", + "Қайталанған нұÑ�қалар", + ], + [ + "Correct first time", + "Верно Ñ� первого раза", + "Justes du premier coup", + "Beim ersten Mal richtig", + "Correctas a la primera", + "Giuste al primo colpo", + "Certos de primeira", + "Birinchi urinishda to‘g‘ri", + "Бірінші реттен дұрыÑ�", + ], + [ + "New moves learned", + "Ð�овых ходов", + "Nouveaux coups appris", + "Neue Züge gelernt", + "Jugadas nuevas aprendidas", + "Mosse nuove imparate", + "Lances novos aprendidos", + "Yangi yurishlar", + "Жаңа жүріÑ�тер", + ], + [ + "Moves to remember", + "Что запомнить", + "Coups à retenir", + "Züge zum Merken", + "Jugadas que recordar", + "Mosse da ricordare", + "Lances para lembrar", + "Eslab qolinadigan yurishlar", + "ЕÑ�те Ñ�ақтайтын жүріÑ�тер", + ], + [ + "10 more new (N)", + "Ещё 10 новых (N)", + "10 nouveaux de plus (N)", + "10 weitere neue (N)", + "10 nuevas más (N)", + "Altre 10 nuove (N)", + "Mais 10 novos (N)", + "Yana 10 ta yangi (N)", + "Тағы 10 жаңа (N)", + ], + [ + "{n} more new (N)", + "Ещё {n} новых (N)", + "{n} nouveaux de plus (N)", + "{n} weitere neue (N)", + "{n} nuevas más (N)", + "Altre {n} nuove (N)", + "Mais {n} novos (N)", + "Yana {n} ta yangi (N)", + "Тағы {n} жаңа (N)", + ], + [ + "To lines (Enter)", + "К вариантам (Enter)", + "Aux lignes (Entrée)", + "Zu den Varianten (Enter)", + "A las líneas (Intro)", + "Alle linee (Invio)", + "Para as linhas (Enter)", + "Variantlarga (Enter)", + "Ð�Ò±Ñ�қаларға (Enter)", + ], + [ + "To repertoires (Enter)", + "К репертуарам (Enter)", + "Aux répertoires (Entrée)", + "Zu den Repertoires (Enter)", + "A los repertorios (Intro)", + "Ai repertori (Invio)", + "Para os repertórios (Enter)", + "Repertuarlarga (Enter)", + "Репертуарларға (Enter)", + ], + [ + "Finish", + "Закончить", + "Terminer", + "Beenden", + "Terminar", + "Termina", + "Encerrar", + "Tugatish", + "Ð�Ñ�қтау", + ], + [ + "× Finish", + "× Закончить", + "× Terminer", + "× Beenden", + "× Terminar", + "× Termina", + "× Encerrar", + "× Tugatish", + "× Ð�Ñ�қтау", + ], + [ + "Finish the session (Esc)", + "Закончить занÑ�тие (Esc)", + "Terminer la séance (Échap)", + "Übung beenden (Esc)", + "Terminar la sesión (Esc)", + "Termina la sessione (Esc)", + "Encerrar a sessão (Esc)", + "Mashg‘ulotni tugatish (Esc)", + "Сабақты аÑ�қтау (Esc)", + ], + [ + "Hint (H)", + "ПодÑ�казка (H)", + "Indice (H)", + "Hinweis (H)", + "Pista (H)", + "Suggerimento (H)", + "Dica (H)", + "Maslahat (H)", + "КеңеÑ� (H)", + ], + [ + "Skip (Enter)", + "ПропуÑ�тить (Enter)", + "Passer (Entrée)", + "Überspringen (Enter)", + "Saltar (Intro)", + "Salta (Invio)", + "Pular (Enter)", + "O‘tkazib yuborish (Enter)", + "Өткізу (Enter)", + ], + [ + "Preparing…", + "Готовим занÑ�тие…", + "Préparation…", + "Wird vorbereitet…", + "Preparando…", + "Preparazione…", + "Preparando…", + "Tayyorlanmoqda…", + "Дайындалуда…", + ], + [ + "Branch: {path}", + "Ветка: {path}", + "Branche : {path}", + "Zweig: {path}", + "Rama: {path}", + "Ramo: {path}", + "Ramo: {path}", + "Shox: {path}", + "Тармақ: {path}", + ], + [ + "no moves", + "нет ходов", + "aucun coup", + "keine Züge", + "sin jugadas", + "nessuna mossa", + "sem lances", + "yurish yo‘q", + "жүріÑ� жоқ", + ], + [ + "The repertoire has no moves yet: import a PGN or add a line from a game", + "Ð’ репертуаре пока нет ходов: импортируйте PGN или добавьте линию из партии", + "Le répertoire n’a pas encore de coups : importez un PGN ou ajoutez une ligne depuis une partie", + "Das Repertoire hat noch keine Züge: PGN importieren oder eine Linie aus einer Partie hinzufügen", + "El repertorio aún no tiene jugadas: importe un PGN o añada una línea desde una partida", + "Il repertorio non ha ancora mosse: importa un PGN o aggiungi una linea da una partita", + "O repertório ainda não tem lances: importe um PGN ou adicione uma linha de uma partida", + "Repertuarda hali yurishlar yo‘q: PGN import qiling yoki partiyadan liniya qo‘shing", + "Репертуарда әзірге жүріÑ� жоқ: PGN импорттаңыз немеÑ�е партиÑ�дан желі қоÑ�ыңыз", + ], + [ + "review {n}", + "повторить {n}", + "réviser {n}", + "{n} wiederholen", + "repasar {n}", + "ripassare {n}", + "revisar {n}", + "takrorlash {n}", + "қайталау {n}", + ], + [ + "new: {n}", + "новые: {n}", + "nouveaux : {n}", + "neu: {n}", + "nuevas: {n}", + "nuove: {n}", + "novos: {n}", + "yangi: {n}", + "жаңа: {n}", + ], + [ + "To review {n}, new in the session {m}", + "К повторению {n}, новых в занÑ�тие {m}", + "À réviser {n}, nouveaux dans la séance {m}", + "Zu wiederholen {n}, neu in der Einheit {m}", + "Por repasar {n}, nuevas en la sesión {m}", + "Da ripassare {n}, nuove nella sessione {m}", + "Para revisar {n}, novos na sessão {m}", + "Takrorlash uchun {n}, mashg‘ulotda yangi {m}", + "Қайталауға {n}, Ñ�абақта жаңа {m}", + ], + [ + "Passed", + "Пройдено", + "Vus", + "Durchgenommen", + "Vistas", + "Viste", + "Vistos", + "O‘tilgan", + "Өтілген", + ], + [ + "Consolidated", + "Закреплено", + "Consolidés", + "Gefestigt", + "Consolidadas", + "Consolidate", + "Consolidados", + "Mustahkamlangan", + "Бекітілген", + ], + [ + "Passed {a} of {y} moves · consolidated {l}", + "Пройдено {a} из {y} ходов · закреплено {l}", + "{a} coups vus sur {y} · {l} consolidés", + "{a} von {y} Zügen durchgenommen · {l} gefestigt", + "{a} de {y} jugadas vistas · {l} consolidadas", + "{a} mosse viste su {y} · {l} consolidate", + "{a} de {y} lances vistos · {l} consolidados", + "{y} ta yurishdan {a} tasi o‘tilgan · {l} tasi mustahkamlangan", + "{y} жүріÑ�тің {a} өтілген · {l} бекітілген", + ], + [ + "Passed {a} of {y} moves, {l} of them consolidated. A move is consolidated after three correct answers in a row without a hint — usually over several days of reviews.", + "Пройдено {a} из {y} ходов, из них закреплено {l}. Ход закреплён поÑ�ле трёх верных ответов подрÑ�д без подÑ�казки — обычно за неÑ�колько дней повторений.", + "{a} coups vus sur {y}, dont {l} consolidés. Un coup est consolidé après trois bonnes réponses d’affilée sans indice — en général sur plusieurs jours de révisions.", + "{a} von {y} Zügen durchgenommen, davon {l} gefestigt. Ein Zug ist gefestigt nach drei richtigen Antworten in Folge ohne Hinweis — meist über mehrere Tage Wiederholung.", + "{a} de {y} jugadas vistas, {l} de ellas consolidadas. Una jugada queda consolidada tras tres respuestas correctas seguidas sin pista; normalmente en varios días de repaso.", + "{a} mosse viste su {y}, di cui {l} consolidate. Una mossa è consolidata dopo tre risposte giuste di fila senza suggerimento — di solito in alcuni giorni di ripasso.", + "{a} de {y} lances vistos, {l} deles consolidados. Um lance fica consolidado após três respostas certas seguidas sem dica — normalmente em vários dias de revisão.", + "{y} ta yurishdan {a} tasi o‘tilgan, ulardan {l} tasi mustahkamlangan. Yurish ketma-ket uchta to‘g‘ri javobdan keyin (yordamsiz) mustahkamlanadi — odatda bir necha kunlik takrorlashda.", + "{y} жүріÑ�тің {a} өтілген, оның {l} бекітілген. ЖүріÑ� кеңеÑ�Ñ�із қатарынан үш дұрыÑ� жауаптан кейін бекітіледі — әдетте бірнеше күндік қайталауда.", + ], + [ + "Below: {n} lines · {y} your moves · consolidated {x}", + "Дальше: вариантов {n} · ваших ходов {y} · закреплено {x}", + "En dessous : {n} lignes · {y} de vos coups · {x} consolidés", + "Darunter: {n} Varianten · {y} eigene Züge · {x} gefestigt", + "Debajo: {n} líneas · {y} jugadas tuyas · {x} consolidadas", + "Sotto: {n} linee · {y} tue mosse · {x} consolidate", + "Abaixo: {n} linhas · {y} lances seus · {x} consolidados", + "Keyin: {n} ta variant · sizning {y} ta yurishingiz · {x} tasi mustahkamlangan", + "Әрі қарай: {n} нұÑ�қа · Ñ�іздің {y} жүріÑ�іңіз · {x} бекітілген", + ], + [ + "New moves left", + "Ð�овых ходов оÑ�талоÑ�ÑŒ", + "Nouveaux coups restants", + "Neue Züge übrig", + "Jugadas nuevas restantes", + "Mosse nuove rimaste", + "Lances novos restantes", + "Qolgan yangi yurishlar", + "Қалған жаңа жүріÑ�тер", + ], + [ + "nothing scheduled", + "нет запланированных", + "rien de prévu", + "nichts geplant", + "nada programado", + "niente in programma", + "nada agendado", + "rejalashtirilmagan", + "жоÑ�парланған жоқ", + ], + [ + "{k} of {n}", + "{k} из {n}", + "{k} sur {n}", + "{k} von {n}", + "{k} de {n}", + "{k} di {n}", + "{k} de {n}", + "{n} tadan {k}", + "{n} ішінен {k}", + ], + [ + "Play {san} — it is shown by the arrow", + "Сыграйте {san} — он показан Ñ�трелкой", + "Jouez {san} — la flèche le montre", + "Spielen Sie {san} — der Pfeil zeigt ihn", + "Juega {san}: la flecha lo muestra", + "Gioca {san}: lo mostra la freccia", + "Jogue {san} — a seta o mostra", + "{san} yurishini qiling — u strelka bilan ko‘rsatilgan", + "{san} жүріÑ�ін жаÑ�аңыз — ол көрÑ�еткімен көрÑ�етілген", + ], + [ + "One more move of yours here, not {san}", + "ЗдеÑ�ÑŒ еÑ�ть ещё один ваш ход, не {san}", + "Vous avez un autre coup ici, pas {san}", + "Hier gibt es noch einen eigenen Zug, nicht {san}", + "Aquí tienes otra jugada, no {san}", + "Qui hai un’altra mossa, non {san}", + "Há mais um lance seu aqui, não {san}", + "Bu yerda yana bir yurishingiz bor, {san} emas", + "Мұнда тағы бір жүріÑ�іңіз бар, {san} емеÑ�", + ], + [ + "Correct: {san}. Play it", + "Правильно: {san}. Сыграйте его", + "Le bon coup : {san}. Jouez-le", + "Richtig ist {san}. Spielen Sie ihn", + "La correcta: {san}. Juégala", + "Quella giusta: {san}. Giocala", + "O correto: {san}. Jogue-o", + "To‘g‘risi: {san}. Uni qiling", + "ДұрыÑ�Ñ‹: {san}. Соны жаÑ�аңыз", + ], + [ + "Now the other one: play {san}", + "СейчаÑ� нужен другой: Ñ�ыграйте {san}", + "Maintenant l’autre : jouez {san}", + "Jetzt der andere: Spielen Sie {san}", + "Ahora la otra: juega {san}", + "Ora l’altra: gioca {san}", + "Agora o outro: jogue {san}", + "Endi boshqasi: {san} yurishini qiling", + "Енді баÑ�қаÑ�Ñ‹: {san} жүріÑ�ін жаÑ�аңыз", + ], + [ + "{move} will come back in this session", + "{move} вернётÑ�Ñ� в Ñ�том занÑ�тии", + "{move} reviendra dans cette séance", + "{move} kommt in dieser Übung wieder", + "{move} volverá en esta sesión", + "{move} tornerà in questa sessione", + "{move} voltará nesta sessão", + "{move} shu mashg‘ulotda yana so‘raladi", + "{move} оÑ�Ñ‹ Ñ�абақта қайта Ñ�ұралады", + ], + [ + "Play {san}", + "Сыграйте {san}", + "Jouez {san}", + "Spielen Sie {san}", + "Juega {san}", + "Gioca {san}", + "Jogue {san}", + "{san} yurishini qiling", + "{san} жүріÑ�ін жаÑ�аңыз", + ], + [ + "Play {san}. It will come back in this session", + "Сыграйте {san}. Ход вернётÑ�Ñ� в Ñ�том занÑ�тии", + "Jouez {san}. Il reviendra dans cette séance", + "Spielen Sie {san}. Er kommt in dieser Übung wieder", + "Juega {san}. Volverá en esta sesión", + "Gioca {san}. Tornerà in questa sessione", + "Jogue {san}. Ele voltará nesta sessão", + "{san} yurishini qiling. U shu mashg‘ulotda yana so‘raladi", + "{san} жүріÑ�ін жаÑ�аңыз. Ол оÑ�Ñ‹ Ñ�абақта қайта Ñ�ұралады", + ], + [ + "after {path}", + "поÑ�ле {path}", + "après {path}", + "nach {path}", + "después de {path}", + "dopo {path}", + "depois de {path}", + "{path} dan keyin", + "{path} кейін", + ], + [ + "and {k} more", + "и ещё {k}", + "et {k} de plus", + "und {k} weitere", + "y {k} más", + "e altre {k}", + "e mais {k}", + "va yana {k} ta", + "және тағы {k}", + ], + [ + "Nothing to train here right now", + "СейчаÑ� здеÑ�ÑŒ нечего тренировать", + "Rien à entraîner ici pour l’instant", + "Hier gibt es gerade nichts zu trainieren", + "Ahora no hay nada que entrenar aquí", + "Al momento qui non c’è niente da allenare", + "Nada para treinar aqui agora", + "Hozir bu yerda mashq qiladigan narsa yo‘q", + "Қазір мұнда жаттығатын ештеңе жоқ", + ], + [ + "A repertoire is your opening moves as a PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…â€�.", + "Репертуар — Ñ�то ваши дебютные ходы в PGN Ñ� вариантами. Импортируйте файл или откройте любую партию, выберите ход и нажмите «Добавить в репертуар…».", + "Un répertoire, ce sont vos coups d’ouverture dans un PGN avec variantes. Importez un fichier, ou ouvrez une partie, choisissez un coup et « Ajouter au répertoire… ».", + "Ein Repertoire sind Ihre Eröffnungszüge als PGN mit Varianten. Importieren Sie eine Datei oder öffnen Sie eine Partie, wählen Sie einen Zug und „Zum Repertoire hinzufügen…“.", + "Un repertorio son tus jugadas de apertura en un PGN con variantes. Importa un archivo, o abre una partida, elige una jugada y pulsa «Añadir al repertorio…».", + "Un repertorio sono le tue mosse d’apertura in un PGN con varianti. Importa un file, oppure apri una partita, scegli una mossa e «Aggiungi al repertorio…».", + "Um repertório são seus lances de abertura em um PGN com variantes. Importe um arquivo, ou abra uma partida, escolha um lance e clique em “Adicionar ao repertório…â€�.", + "Repertuar — bu variantlari bor PGN dagi debyut yurishlaringiz. Faylni import qiling yoki istalgan partiyani ochib, yurishni tanlang va «Repertuarga qo‘shish…» ni bosing.", + "Репертуар — нұÑ�қалары бар PGN-дегі дебют жүріÑ�теріңіз. Файлды импорттаңыз немеÑ�е кез келген партиÑ�ны ашып, жүріÑ�ті таңдап, «Репертуарға қоÑ�у…» баÑ�ыңыз.", + ], + [ + "Moves are added from a PGN file or with “Add to repertoire…â€� in any game.", + "Ходы добавлÑ�ÑŽÑ‚Ñ�Ñ� из PGN-файла или кнопкой «Добавить в репертуар…» в любой партии.", + "Les coups s’ajoutent depuis un fichier PGN ou avec « Ajouter au répertoire… » dans une partie.", + "Züge kommen aus einer PGN-Datei oder über „Zum Repertoire hinzufügen…“ in einer Partie.", + "Las jugadas se añaden desde un archivo PGN o con «Añadir al repertorio…» en cualquier partida.", + "Le mosse si aggiungono da un file PGN o con «Aggiungi al repertorio…» in una partita.", + "Os lances são adicionados de um arquivo PGN ou com “Adicionar ao repertório…â€� em qualquer partida.", + "Yurishlar PGN fayldan yoki istalgan partiyadagi «Repertuarga qo‘shish…» tugmasi bilan qo‘shiladi.", + "ЖүріÑ�тер PGN файлынан немеÑ�е кез келген партиÑ�дағы «Репертуарға қоÑ�у…» батырмаÑ�ымен қоÑ�ылады.", + ], + [ + "Rename repertoire", + "Переименовать репертуар", + "Renommer le répertoire", + "Repertoire umbenennen", + "Renombrar el repertorio", + "Rinomina il repertorio", + "Renomear o repertório", + "Repertuar nomini o‘zgartirish", + "Репертуар атын өзгерту", + ], + [ + "Switch", + "Переключить", + "Changer", + "Wechseln", + "Cambiar", + "Cambia", + "Trocar", + "Almashtirish", + "Ð�уыÑ�тыру", + ], + [ + "The moves themselves and PGN files do not change.", + "Сами ходы и PGN-файлы не менÑ�ÑŽÑ‚Ñ�Ñ�.", + "Les coups eux-mêmes et les fichiers PGN ne changent pas.", + "Die Züge selbst und die PGN-Dateien ändern sich nicht.", + "Las jugadas y los archivos PGN no cambian.", + "Le mosse e i file PGN non cambiano.", + "Os lances e os arquivos PGN não mudam.", + "Yurishlarning o‘zi va PGN fayllar o‘zgarmaydi.", + "ЖүріÑ�тердің өзі мен PGN файлдары өзгермейді.", + ], + [ + "The repertoire leaves this list. PGN files on disk do not change.", + "Репертуар иÑ�чезнет из Ñ�пиÑ�ка. PGN-файлы на диÑ�ке не менÑ�ÑŽÑ‚Ñ�Ñ�.", + "Le répertoire quitte cette liste. Les fichiers PGN sur le disque ne changent pas.", + "Das Repertoire verschwindet aus der Liste. PGN-Dateien auf dem Datenträger ändern sich nicht.", + "El repertorio desaparece de la lista. Los archivos PGN del disco no cambian.", + "Il repertorio esce dall’elenco. I file PGN sul disco non cambiano.", + "O repertório sai da lista. Os arquivos PGN no disco não mudam.", + "Repertuar ro‘yxatdan yo‘qoladi. Diskdagi PGN fayllar o‘zgarmaydi.", + "Репертуар тізімнен жоғалады. ДиÑ�кідегі PGN файлдары өзгермейді.", + ], + [ + "Your answers are kept: import the same PGN again and the progress returns.", + "Ответы Ñ�охранÑ�Ñ‚Ñ�Ñ�: еÑ�ли импортировать тот же PGN Ñ�нова, прогреÑ�Ñ� вернётÑ�Ñ�.", + "Vos réponses sont conservées : réimportez le même PGN et la progression revient.", + "Ihre Antworten bleiben: Importieren Sie dieselbe PGN erneut, ist der Fortschritt wieder da.", + "Tus respuestas se conservan: importa el mismo PGN de nuevo y el progreso vuelve.", + "Le risposte restano: reimporta lo stesso PGN e i progressi tornano.", + "Suas respostas ficam guardadas: importe o mesmo PGN de novo e o progresso volta.", + "Javoblaringiz saqlanadi: o‘sha PGN ni qayta import qilsangiz, natija qaytadi.", + "Жауаптарыңыз Ñ�ақталады: Ñ�ол PGN-ді қайта импорттаÑ�аңыз, нәтиже қайтады.", + ], + [ + "Nothing to review today", + "ПовторÑ�ть Ñ�егоднÑ� нечего", + "Rien à réviser aujourd’hui", + "Heute nichts zu wiederholen", + "Hoy no hay nada que repasar", + "Oggi niente da ripassare", + "Nada para revisar hoje", + "Bugun takrorlash kerak emas", + "Бүгін қайталайтын ештеңе жоқ", + ], + [ + "Done for today", + "Ð�а Ñ�егоднÑ� вÑ�Ñ‘", + "C’est fini pour aujourd’hui", + "Für heute fertig", + "Por hoy, terminado", + "Per oggi è tutto", + "Por hoje é só", + "Bugunga yetarli", + "Бүгінге оÑ�Ñ‹", + ], + [ + "No moves yet", + "Ходов пока нет", + "Pas encore de coups", + "Noch keine Züge", + "Aún no hay jugadas", + "Ancora nessuna mossa", + "Ainda sem lances", + "Hali yurishlar yo‘q", + "Әзірге жүріÑ� жоқ", + ], + [ + "Add a PGN, or use “Add to repertoire…â€� in any game", + "Добавьте PGN или нажмите «Добавить в репертуар…» в любой партии", + "Ajoutez un PGN, ou « Ajouter au répertoire… » dans une partie", + "Fügen Sie eine PGN hinzu oder „Zum Repertoire hinzufügen…“ in einer Partie", + "Añade un PGN o usa «Añadir al repertorio…» en una partida", + "Aggiungi un PGN o usa «Aggiungi al repertorio…» in una partita", + "Adicione um PGN ou use “Adicionar ao repertório…â€� em uma partida", + "PGN qo‘shing yoki istalgan partiyada «Repertuarga qo‘shish…» ni bosing", + "PGN қоÑ�ыңыз немеÑ�е кез келген партиÑ�да «Репертуарға қоÑ�у…» баÑ�ыңыз", + ], + [ + "No moves for White here", + "ЗдеÑ�ÑŒ нет ходов за белых", + "Pas de coups des Blancs ici", + "Hier gibt es keine Züge für Weiß", + "Aquí no hay jugadas de las blancas", + "Qui non ci sono mosse del Bianco", + "Não há lances das brancas aqui", + "Bu yerda oq uchun yurishlar yo‘q", + "Мұнда ақтың жүріÑ�тері жоқ", + ], + [ + "No moves for Black here", + "ЗдеÑ�ÑŒ нет ходов за чёрных", + "Pas de coups des Noirs ici", + "Hier gibt es keine Züge für Schwarz", + "Aquí no hay jugadas de las negras", + "Qui non ci sono mosse del Nero", + "Não há lances das pretas aqui", + "Bu yerda qora uchun yurishlar yo‘q", + "Мұнда қараның жүріÑ�тері жоқ", + ], + [ + "This PGN may be a repertoire for the other colour", + "Возможно, Ñ�то репертуар за другой цвет", + "Ce PGN est peut-être un répertoire pour l’autre couleur", + "Diese PGN ist vielleicht ein Repertoire für die andere Farbe", + "Quizá este PGN sea un repertorio del otro color", + "Forse questo PGN è un repertorio per l’altro colore", + "Talvez este PGN seja um repertório da outra cor", + "Ehtimol, bu boshqa rang uchun repertuar", + "Мүмкін, бұл баÑ�қа түÑ�тің репертуары", + ], + [ + "Cannot read this repertoire", + "Ð�е удалоÑ�ÑŒ прочитать репертуар", + "Impossible de lire ce répertoire", + "Dieses Repertoire kann nicht gelesen werden", + "No se puede leer este repertorio", + "Impossibile leggere questo repertorio", + "Não foi possível ler este repertório", + "Bu repertuarni o‘qib bo‘lmadi", + "Бұл репертуарды оқу мүмкін болмады", + ], + [ + "Switch colour to Black", + "Сменить цвет на чёрные", + "Passer aux Noirs", + "Farbe auf Schwarz wechseln", + "Cambiar a negras", + "Passa al Nero", + "Mudar para pretas", + "Rangni qoraga almashtirish", + "ТүÑ�ті қараға ауыÑ�тыру", + ], + [ + "Switch colour to White", + "Сменить цвет на белые", + "Passer aux Blancs", + "Farbe auf Weiß wechseln", + "Cambiar a blancas", + "Passa al Bianco", + "Mudar para brancas", + "Rangni oqqa almashtirish", + "ТүÑ�ті аққа ауыÑ�тыру", + ], + [ + "Lines…", + "Варианты…", + "Lignes…", + "Varianten…", + "Líneas…", + "Linee…", + "Linhas…", + "Variantlar…", + "Ð�Ò±Ñ�қалар…", + ], + [ + "Rename…", + "Переименовать…", + "Renommer…", + "Umbenennen…", + "Renombrar…", + "Rinomina…", + "Renomear…", + "Nomini o‘zgartirish…", + "Ð�тын өзгерту…", + ], + [ + "Add PGN to this repertoire…", + "Добавить PGN в Ñ�тот репертуар…", + "Ajouter un PGN à ce répertoire…", + "PGN zu diesem Repertoire hinzufügen…", + "Añadir un PGN a este repertorio…", + "Aggiungi un PGN a questo repertorio…", + "Adicionar PGN a este repertório…", + "Bu repertuarga PGN qo‘shish…", + "Бұл репертуарға PGN қоÑ�у…", + ], + [ + "Reset progress…", + "СброÑ�ить прогреÑ�Ñ�…", + "Réinitialiser la progression…", + "Fortschritt zurücksetzen…", + "Restablecer el progreso…", + "Azzera i progressi…", + "Redefinir o progresso…", + "Natijani tiklash…", + "Ð�әтижені таÑ�тау…", + ], + [ + "You play", + "Ð’Ñ‹ играете", + "Vous jouez", + "Sie spielen", + "Juegas con", + "Giochi con", + "Você joga de", + "Siz o‘ynaysiz", + "Сіз ойнайÑ�ыз", + ], + [ + "Import PGN", + "Импорт PGN", + "Importer un PGN", + "PGN importieren", + "Importar PGN", + "Importa PGN", + "Importar PGN", + "PGN import qilish", + "PGN импорттау", + ], + [ + "Chosen from the PGN — check it", + "Выбрано по PGN — проверьте", + "Choisi d’après le PGN — vérifiez", + "Aus der PGN gewählt — bitte prüfen", + "Elegido según el PGN: compruébalo", + "Scelto in base al PGN: controlla", + "Escolhido pelo PGN — confira", + "PGN bo‘yicha tanlandi — tekshiring", + "PGN бойынша таңдалды — текÑ�еріңіз", + ], + [ + "Reading the file…", + "Читаем файл…", + "Lecture du fichier…", + "Datei wird gelesen…", + "Leyendo el archivo…", + "Lettura del file…", + "Lendo o arquivo…", + "Fayl o‘qilmoqda…", + "Файл оқылуда…", + ], + [ + "Nothing new in this file", + "Ð’ файле нет новых ходов", + "Rien de nouveau dans ce fichier", + "Nichts Neues in dieser Datei", + "No hay nada nuevo en este archivo", + "Niente di nuovo in questo file", + "Nada de novo neste arquivo", + "Bu faylda yangi yurishlar yo‘q", + "Бұл файлда жаңа жүріÑ� жоқ", + ], + [ + "No moves for this colour", + "Ð�ет ходов за Ñ�тот цвет", + "Aucun coup pour cette couleur", + "Keine Züge für diese Farbe", + "No hay jugadas de este color", + "Nessuna mossa per questo colore", + "Sem lances para esta cor", + "Bu rang uchun yurishlar yo‘q", + "Бұл түÑ� үшін жүріÑ� жоқ", + ], + [ + "Import", + "Импортировать", + "Importer", + "Importieren", + "Importar", + "Importa", + "Importar", + "Import qilish", + "Импорттау", + ], + [ + "No games with moves in this file", + "Ð’ файле нет партий Ñ� ходами", + "Aucune partie avec des coups dans ce fichier", + "Keine Partie mit Zügen in dieser Datei", + "No hay partidas con jugadas en este archivo", + "Nessuna partita con mosse in questo file", + "Nenhuma partida com lances neste arquivo", + "Bu faylda yurishli partiyalar yo‘q", + "Бұл файлда жүріÑ�Ñ– бар партиÑ� жоқ", + ], + [ + "Saved to {path}", + "Сохранено: {path}", + "Enregistré : {path}", + "Gespeichert: {path}", + "Guardado en {path}", + "Salvato in {path}", + "Salvo em {path}", + "Saqlandi: {path}", + "Сақталды: {path}", + ], + [ + "{n} repertoires", + "Репертуаров: {n}", + "{n} répertoires", + "{n} Repertoires", + "{n} repertorios", + "{n} repertori", + "{n} repertórios", + "Repertuarlar: {n}", + "Репертуарлар: {n}", + ], + [ + "Could not read the repertoires: {e}", + "Ð�е удалоÑ�ÑŒ прочитать репертуары: {e}", + "Impossible de lire les répertoires : {e}", + "Die Repertoires konnten nicht gelesen werden: {e}", + "No se pudieron leer los repertorios: {e}", + "Impossibile leggere i repertori: {e}", + "Não foi possível ler os repertórios: {e}", + "Repertuarlarni o‘qib bo‘lmadi: {e}", + "Репертуарларды оқу мүмкін болмады: {e}", + ], + [ + "Play “{name}â€� as Black?", + "Играть «{name}» чёрными?", + "Jouer « {name} » avec les Noirs ?", + "„{name}“ mit Schwarz spielen?", + "¿Jugar «{name}» con negras?", + "Giocare «{name}» con il Nero?", + "Jogar “{name}â€� de pretas?", + "«{name}» ni qora bilan o‘ynaysizmi?", + "«{name}» қарамен ойнайÑ�ыз ба?", + ], + [ + "Play “{name}â€� as White?", + "Играть «{name}» белыми?", + "Jouer « {name} » avec les Blancs ?", + "„{name}“ mit Weiß spielen?", + "¿Jugar «{name}» con blancas?", + "Giocare «{name}» con il Bianco?", + "Jogar “{name}â€� de brancas?", + "«{name}» ni oq bilan o‘ynaysizmi?", + "«{name}» ақпен ойнайÑ�ыз ба?", + ], + [ + "You will be asked Black's moves: {y}. Progress for White is kept and comes back if you switch again.", + "СпрашиватьÑ�Ñ� будут ходы чёрных: {y}. ПрогреÑ�Ñ� за белых Ñ�охранитÑ�Ñ� и вернётÑ�Ñ�, еÑ�ли переключить обратно.", + "On vous demandera les coups des Noirs : {y}. La progression des Blancs est conservée et revient si vous changez à nouveau.", + "Gefragt werden die Züge von Schwarz: {y}. Der Fortschritt für Weiß bleibt erhalten und kehrt beim Zurückwechseln zurück.", + "Se te preguntarán las jugadas de las negras: {y}. El progreso de las blancas se guarda y vuelve si cambias de nuevo.", + "Ti verranno chieste le mosse del Nero: {y}. I progressi del Bianco restano e tornano se cambi di nuovo.", + "Serão perguntados os lances das pretas: {y}. O progresso das brancas fica guardado e volta se você trocar de novo.", + "Qoraning yurishlari so‘raladi: {y}. Oq bo‘yicha natija saqlanadi va qayta almashtirsangiz qaytadi.", + "Қараның жүріÑ�тері Ñ�ұралады: {y}. Ð�қтағы нәтиже Ñ�ақталады және қайта ауыÑ�тырÑ�аңыз қайтады.", + ], + [ + "You will be asked White's moves: {y}. Progress for Black is kept and comes back if you switch again.", + "СпрашиватьÑ�Ñ� будут ходы белых: {y}. ПрогреÑ�Ñ� за чёрных Ñ�охранитÑ�Ñ� и вернётÑ�Ñ�, еÑ�ли переключить обратно.", + "On vous demandera les coups des Blancs : {y}. La progression des Noirs est conservée et revient si vous changez à nouveau.", + "Gefragt werden die Züge von Weiß: {y}. Der Fortschritt für Schwarz bleibt erhalten und kehrt beim Zurückwechseln zurück.", + "Se te preguntarán las jugadas de las blancas: {y}. El progreso de las negras se guarda y vuelve si cambias de nuevo.", + "Ti verranno chieste le mosse del Bianco: {y}. I progressi del Nero restano e tornano se cambi di nuovo.", + "Serão perguntados os lances das brancas: {y}. O progresso das pretas fica guardado e volta se você trocar de novo.", + "Oqning yurishlari so‘raladi: {y}. Qora bo‘yicha natija saqlanadi va qayta almashtirsangiz qaytadi.", + "Ð�қтың жүріÑ�тері Ñ�ұралады: {y}. Қарадағы нәтиже Ñ�ақталады және қайта ауыÑ�тырÑ�аңыз қайтады.", + ], + [ + "Reset progress of “{name}â€�?", + "СброÑ�ить прогреÑ�Ñ� «{name}»?", + "Réinitialiser la progression de « {name} » ?", + "Fortschritt von „{name}“ zurücksetzen?", + "¿Restablecer el progreso de «{name}»?", + "Azzerare i progressi di «{name}»?", + "Redefinir o progresso de “{name}â€�?", + "«{name}» natijasini tiklaysizmi?", + "«{name}» нәтижеÑ�ін таÑ�тау керек пе?", + ], + [ + "All {y} moves of this repertoire become new again: answers and review dates are erased.", + "Ð’Ñ�е ходы Ñ�того репертуара ({y}) Ñ�нова Ñ�танут новыми: ответы и Ñ�роки повторений будут Ñ�тёрты.", + "Les {y} coups de ce répertoire redeviennent nouveaux : réponses et dates de révision sont effacées.", + "Alle {y} Züge dieses Repertoires werden wieder neu: Antworten und Wiederholungstermine werden gelöscht.", + "Las {y} jugadas de este repertorio vuelven a ser nuevas: se borran las respuestas y las fechas de repaso.", + "Tutte le {y} mosse di questo repertorio tornano nuove: risposte e date di ripasso vengono cancellate.", + "Todos os {y} lances deste repertório voltam a ser novos: respostas e datas de revisão são apagadas.", + "Bu repertuarning barcha yurishlari ({y}) yana yangi bo‘ladi: javoblar va takrorlash muddatlari o‘chiriladi.", + "Бұл репертуардың барлық жүріÑ�Ñ– ({y}) қайта жаңа болады: жауаптар мен қайталау мерзімдері өшіріледі.", + ], + [ + "{s} of these moves are also in: {names}. They become new there too.", + "Из них {s} вÑ�тречаютÑ�Ñ� также в: {names}. Там они тоже Ñ�танут новыми.", + "{s} de ces coups sont aussi dans : {names}. Ils y redeviennent nouveaux aussi.", + "{s} dieser Züge stehen auch in: {names}. Dort werden sie ebenfalls neu.", + "{s} de estas jugadas también están en: {names}. Allí también vuelven a ser nuevas.", + "{s} di queste mosse sono anche in: {names}. Anche lì tornano nuove.", + "{s} desses lances também estão em: {names}. Lá eles também voltam a ser novos.", + "Ulardan {s} tasi bularda ham bor: {names}. U yerda ham yangi bo‘ladi.", + "Олардың {s} жүріÑ�Ñ– мұнда да бар: {names}. Онда да жаңа болады.", + ], + [ + "Delete “{name}â€�?", + "Удалить «{name}»?", + "Supprimer « {name} » ?", + "„{name}“ löschen?", + "¿Eliminar «{name}»?", + "Eliminare «{name}»?", + "Excluir “{name}â€�?", + "«{name}» ni o‘chirasizmi?", + "«{name}» жою керек пе?", + ], + [ + "Today: {n} to review · {m} new", + "СегоднÑ�: {n} повторить · {m} новых", + "Aujourd’hui : {n} à réviser · {m} nouveaux", + "Heute: {n} wiederholen · {m} neu", + "Hoy: {n} para repasar · {m} nuevas", + "Oggi: {n} da ripassare · {m} nuove", + "Hoje: {n} para revisar · {m} novos", + "Bugun: {n} ta takrorlash · {m} ta yangi", + "Бүгін: {n} қайталау · {m} жаңа", + ], + [ + "Today: {n} to review", + "СегоднÑ�: {n} повторить", + "Aujourd’hui : {n} à réviser", + "Heute: {n} wiederholen", + "Hoy: {n} para repasar", + "Oggi: {n} da ripassare", + "Hoje: {n} para revisar", + "Bugun: {n} ta takrorlash", + "Бүгін: {n} қайталау", + ], + [ + "About {t} min", + "Примерно {t} мин", + "Environ {t} min", + "Etwa {t} Min.", + "Unos {t} min", + "Circa {t} min", + "Cerca de {t} min", + "Taxminan {t} daqiqa", + "Шамамен {t} мин", + ], + [ + "Today: {m} new moves", + "СегоднÑ�: {m} новых ходов", + "Aujourd’hui : {m} nouveaux coups", + "Heute: {m} neue Züge", + "Hoy: {m} jugadas nuevas", + "Oggi: {m} mosse nuove", + "Hoje: {m} lances novos", + "Bugun: {m} ta yangi yurish", + "Бүгін: {m} жаңа жүріÑ�", + ], + [ + "Next review: {when} · {n} moves", + "Следующее повторение: {when} · ходов: {n}", + "Prochaine révision : {when} · {n} coups", + "Nächste Wiederholung: {when} · {n} Züge", + "Próximo repaso: {when} · {n} jugadas", + "Prossimo ripasso: {when} · {n} mosse", + "Próxima revisão: {when} · {n} lances", + "Keyingi takrorlash: {when} · {n} ta yurish", + "КелеÑ�Ñ– қайталау: {when} · {n} жүріÑ�", + ], + [ + "Learn {m} new", + "Учить {m} новых", + "Apprendre {m} nouveaux", + "{m} neue lernen", + "Aprender {m} nuevas", + "Impara {m} nuove", + "Aprender {m} novos", + "{m} ta yangisini o‘rganish", + "{m} жаңаÑ�ын үйрену", + ], + [ + "Add PGN to “{name}â€�", + "Добавить PGN в «{name}»", + "Ajouter un PGN à « {name} »", + "PGN zu „{name}“ hinzufügen", + "Añadir un PGN a «{name}»", + "Aggiungi un PGN a «{name}»", + "Adicionar PGN a “{name}â€�", + "«{name}» ga PGN qo‘shish", + "«{name}» ішіне PGN қоÑ�у", + ], + [ + "{m} new moves · {v} new lines", + "Ð�овых ходов: {m} · новых вариантов: {v}", + "{m} nouveaux coups · {v} nouvelles lignes", + "{m} neue Züge · {v} neue Varianten", + "{m} jugadas nuevas · {v} líneas nuevas", + "{m} mosse nuove · {v} linee nuove", + "{m} lances novos · {v} linhas novas", + "Yangi yurishlar: {m} · yangi variantlar: {v}", + "Жаңа жүріÑ�тер: {m} · жаңа нұÑ�қалар: {v}", + ], + [ + "{g} games · {v} lines · {y} your moves", + "Партий: {g} · вариантов: {v} · ваших ходов: {y}", + "{g} parties · {v} lignes · {y} de vos coups", + "{g} Partien · {v} Varianten · {y} eigene Züge", + "{g} partidas · {v} líneas · {y} jugadas tuyas", + "{g} partite · {v} linee · {y} tue mosse", + "{g} partidas · {v} linhas · {y} lances seus", + "Partiyalar: {g} · variantlar: {v} · yurishlaringiz: {y}", + "ПартиÑ�лар: {g} · нұÑ�қалар: {v} · Ñ�іздің жүріÑ�теріңіз: {y}", + ], + [ + "Game {n}: could not be read", + "ПартиÑ� {n}: не удалоÑ�ÑŒ прочитать", + "Partie {n} : illisible", + "Partie {n}: nicht lesbar", + "Partida {n}: no se pudo leer", + "Partita {n}: illeggibile", + "Partida {n}: não foi possível ler", + "{n}-partiya: o‘qib bo‘lmadi", + "{n}-партиÑ�: оқу мүмкін болмады", + ], + [ + "Game {n}: {message}", + "ПартиÑ� {n}: {message}", + "Partie {n} : {message}", + "Partie {n}: {message}", + "Partida {n}: {message}", + "Partita {n}: {message}", + "Partida {n}: {message}", + "{n}-partiya: {message}", + "{n}-партиÑ�: {message}", + ], + [ + "Game {n} has no moves", + "Ð’ партии {n} нет ходов", + "La partie {n} n’a pas de coups", + "Partie {n} hat keine Züge", + "La partida {n} no tiene jugadas", + "La partita {n} non ha mosse", + "A partida {n} não tem lances", + "{n}-partiyada yurishlar yo‘q", + "{n}-партиÑ�да жүріÑ� жоқ", + ], + [ + "Checking access to Lichess and Chess.com…", + "ПроверÑ�ем доÑ�тупноÑ�ть Lichess и Chess.com…", + "Vérification de l’accès à Lichess et Chess.com…", + "Zugriff auf Lichess und Chess.com wird geprüft…", + "Comprobando el acceso a Lichess y Chess.com…", + "Verifica dell’accesso a Lichess e Chess.com…", + "Verificando o acesso ao Lichess e ao Chess.com…", + "Lichess va Chess.com mavjudligi tekshirilmoqda…", + "Lichess пен Chess.com қолжетімділігі текÑ�ерілуде…", + ], + [ + "Saving progress…", + "Сохранение прогреÑ�Ñ�а…", + "Enregistrement du progrès…", + "Fortschritt wird gespeichert…", + "Guardando progreso…", + "Salvataggio progressi…", + "Salvando progresso…", + "Natija saqlanmoqda…", + "Ð�әтиже Ñ�ақталуда…", + ], + [ + "Train", + "ТренироватьÑ�Ñ�", + "S’entraîner", + "Trainieren", + "Entrenar", + "Allenati", + "Treinar", + "Mashq qilish", + "Жаттығу", + ], + [ + "Learn new moves", + "Учить новые", + "Apprendre des coups", + "Neue Züge lernen", + "Aprender jugadas", + "Impara mosse", + "Aprender lances", + "Yangi yurishlar", + "Жаңа жүріÑ�тер", + ], + // --- the web version --- + [ + "This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.", + "База Ñ�лишком большаÑ� длÑ� браузера ({size}, предел {limit}). Извините — откройте её в программе длÑ� компьютера.", + "Cette base est trop grande pour le navigateur ({size}, la limite est de {limit}). Désolé — ouvrez-la dans le programme pour ordinateur.", + "Diese Datenbank ist zu groß für den Browser ({size}, die Grenze liegt bei {limit}). Entschuldigung – öffnen Sie sie im Programm für den Computer.", + "Esta base es demasiado grande para el navegador ({size}, el límite es {limit}). Lo sentimos: ábrela en el programa para ordenador.", + "Questo database è troppo grande per il browser ({size}, il limite è {limit}). Ci dispiace: aprilo nel programma per computer.", + "Esta base é grande demais para o navegador ({size}, o limite é {limit}). Desculpe — abra no programa para computador.", + "Bu baza brauzer uchun juda katta ({size}, chegara {limit}). Kechirasiz — uni kompyuter dasturida oching.", + "Бұл база браузер үшін тым үлкен ({size}, шегі {limit}). Кешіріңіз — оны компьютерге арналған бағдарламада ашыңыз.", + ], + [ + "Download ChessPenguin for the computer", + "Скачать ChessPenguin длÑ� компьютера", + "Télécharger ChessPenguin pour ordinateur", + "ChessPenguin für den Computer herunterladen", + "Descargar ChessPenguin para ordenador", + "Scarica ChessPenguin per computer", + "Baixar o ChessPenguin para computador", + "ChessPenguin’ni kompyuter uchun yuklab olish", + "ChessPenguin-ді компьютерге жүктеп алу", + ], + [ + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + "База ChessBase Ñ�оÑ�тоит из неÑ�кольких файлов (.cbh, .cbg, .cba…). Выберите её папку или Ñ�разу вÑ�е её файлы.", + "Une base ChessBase se compose de plusieurs fichiers (.cbh, .cbg, .cba…). Choisissez son dossier ou tous ses fichiers à la fois.", + "Eine ChessBase-Datenbank besteht aus mehreren Dateien (.cbh, .cbg, .cba…). Wählen Sie ihren Ordner oder alle ihre Dateien auf einmal.", + "Una base de ChessBase consta de varios archivos (.cbh, .cbg, .cba…). Elige su carpeta o todos sus archivos a la vez.", + "Un database ChessBase è composto da più file (.cbh, .cbg, .cba…). Scegli la sua cartella o tutti i suoi file insieme.", + "Uma base do ChessBase é formada por vários arquivos (.cbh, .cbg, .cba…). Escolha a pasta dela ou todos os arquivos de uma vez.", + "ChessBase bazasi bir nechta fayldan iborat (.cbh, .cbg, .cba…). Uning papkasini yoki barcha fayllarini birdaniga tanlang.", + "ChessBase базаÑ�Ñ‹ бірнеше файлдан тұрады (.cbh, .cbg, .cba…). Оның қалтаÑ�ын немеÑ�е барлық файлдарын бірден таңдаңыз.", + ], + [ + "Allow access to the database's folder — its other files will be found by themselves.", + "Разрешите доÑ�туп к папке базы — оÑ�тальные файлы базы найдутÑ�Ñ� Ñ�ами.", + "Autorisez l'accès au dossier de la base — ses autres fichiers seront trouvés automatiquement.", + "Erlauben Sie den Zugriff auf den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.", + "Permite el acceso a la carpeta de la base: sus demás archivos se encontrarán solos.", + "Consenti l'accesso alla cartella del database: gli altri suoi file verranno trovati da soli.", + "Permita o acesso à pasta da base — os outros arquivos dela serão encontrados sozinhos.", + "Baza papkasiga ruxsat bering — uning qolgan fayllari o‘zi topiladi.", + "База қалтаÑ�ына Ñ€Ò±Ò›Ñ�ат беріңіз — оның қалған файлдары өздігінен табылады.", + ], + [ + "Choose the database's folder — its other files will be found by themselves.", + "Выберите папку базы — оÑ�тальные файлы базы найдутÑ�Ñ� Ñ�ами.", + "Choisissez le dossier de la base — ses autres fichiers seront trouvés automatiquement.", + "Wählen Sie den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.", + "Elige la carpeta de la base: sus demás archivos se encontrarán solos.", + "Scegli la cartella del database: gli altri suoi file verranno trovati da soli.", + "Escolha a pasta da base — os outros arquivos dela serão encontrados sozinhos.", + "Baza papkasini tanlang — uning qolgan fayllari o‘zi topiladi.", + "База қалтаÑ�ын таңдаңыз — оның қалған файлдары өздігінен табылады.", + ], + [ + "ðŸ“� Choose the database's folder", + "ðŸ“� Выбрать папку базы", + "ðŸ“� Choisir le dossier de la base", + "ðŸ“� Ordner der Datenbank wählen", + "ðŸ“� Elegir la carpeta de la base", + "ðŸ“� Scegli la cartella del database", + "ðŸ“� Escolher a pasta da base", + "ðŸ“� Baza papkasini tanlash", + "ðŸ“� База қалтаÑ�ын таңдау", + ], + [ + "Choose the database's files", + "Выбрать файлы базы", + "Choisir les fichiers de la base", + "Dateien der Datenbank wählen", + "Elegir los archivos de la base", + "Scegli i file del database", + "Escolher os arquivos da base", + "Baza fayllarini tanlash", + "База файлдарын таңдау", + ], + [ + "There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z).", + "Ð’ Ñ�той папке нет базы (.pgn, .cbh, .cbv, .zip, .7z).", + "Ce dossier ne contient aucune base (.pgn, .cbh, .cbv, .zip, .7z).", + "In diesem Ordner gibt es keine Datenbank (.pgn, .cbh, .cbv, .zip, .7z).", + "En esta carpeta no hay ninguna base (.pgn, .cbh, .cbv, .zip, .7z).", + "In questa cartella non c'è nessun database (.pgn, .cbh, .cbv, .zip, .7z).", + "Não há nenhuma base nesta pasta (.pgn, .cbh, .cbv, .zip, .7z).", + "Bu papkada baza yo‘q (.pgn, .cbh, .cbv, .zip, .7z).", + "Бұл қалтада база жоқ (.pgn, .cbh, .cbv, .zip, .7z).", + ], + [ + "The browser doesn't have enough memory for this database. Open it in the desktop program.", + "Браузеру не хватает памÑ�ти длÑ� Ñ�той базы. Откройте её в программе длÑ� компьютера.", + "Le navigateur n'a pas assez de mémoire pour cette base. Ouvrez-la dans le programme pour ordinateur.", + "Dem Browser fehlt der Speicher für diese Datenbank. Öffnen Sie sie im Programm für den Computer.", + "Al navegador le falta memoria para esta base. Ã�brela en el programa para ordenador.", + "Al browser manca la memoria per questo database. Aprilo nel programma per computer.", + "O navegador não tem memória suficiente para esta base. Abra no programa para computador.", + "Brauzerda bu baza uchun xotira yetmaydi. Uni kompyuter dasturida oching.", + "Браузерге бұл база үшін жад жетпейді. Оны компьютерге арналған бағдарламада ашыңыз.", + ], + [ + "A dropped file is not remembered: after a reload, choose the file again or keep a copy in the browser.", + "Перетащенный файл не запоминаетÑ�Ñ�: поÑ�ле перезагрузки выберите его Ñ�нова или Ñ�охраните копию в браузере.", + "Un fichier déposé n'est pas mémorisé : après un rechargement, choisissez-le à nouveau ou gardez-en une copie dans le navigateur.", + "Eine hineingezogene Datei wird nicht gemerkt: Wählen Sie sie nach dem Neuladen erneut oder behalten Sie eine Kopie im Browser.", + "Un archivo arrastrado no se recuerda: tras recargar, elíjalo de nuevo o guarde una copia en el navegador.", + "Un file trascinato non viene ricordato: dopo il ricaricamento sceglilo di nuovo o conserva una copia nel browser.", + "Um arquivo arrastado não é lembrado: após recarregar, escolha-o novamente ou guarde uma cópia no navegador.", + "Sudrab tashlangan fayl eslab qolinmaydi: qayta yuklangandan keyin uni yana tanlang yoki brauzerda nusxasini saqlang.", + "Сүйреп әкелінген файл еÑ�те Ñ�ақталмайды: қайта жүктегеннен кейін оны қайта таңдаңыз немеÑ�е браузерде көшірмеÑ�ін Ñ�ақтаңыз.", + ], + [ + "🔒 Allow reading", + "🔒 Разрешить чтение", + "🔒 Autoriser la lecture", + "🔒 Lesen erlauben", + "🔒 Permitir lectura", + "🔒 Consenti la lettura", + "🔒 Permitir leitura", + "🔒 O‘qishga ruxsat berish", + "🔒 Оқуға Ñ€Ò±Ò›Ñ�ат беру", + ], + [ + "The browser remembers this file and asks before the page reads it again.", + "Браузер помнит Ñ�тот файл и Ñ�прашивает, прежде чем Ñ�траница прочитает его Ñ�нова.", + "Le navigateur se souvient de ce fichier et demande avant que la page le relise.", + "Der Browser merkt sich diese Datei und fragt, bevor die Seite sie erneut liest.", + "El navegador recuerda este archivo y pregunta antes de que la página vuelva a leerlo.", + "Il browser ricorda questo file e chiede prima che la pagina lo rilegga.", + "O navegador lembra este arquivo e pergunta antes que a página o leia novamente.", + "Brauzer bu faylni eslab qoladi va sahifa uni qayta o‘qishidan oldin so‘raydi.", + "Браузер бұл файлды еÑ�те Ñ�ақтайды және бет оны қайта оқымаÑ� бұрын Ñ�ұрайды.", + ], + [ + "There is an unsaved game: {title}, moves: {n}.", + "ЕÑ�ть неÑ�охранённаÑ� партиÑ�: {title}, ходов: {n}.", + "Il y a une partie non enregistrée : {title}, coups : {n}.", + "Es gibt eine nicht gespeicherte Partie: {title}, Züge: {n}.", + "Hay una partida sin guardar: {title}, jugadas: {n}.", + "C'è una partita non salvata: {title}, mosse: {n}.", + "Há uma partida não salva: {title}, lances: {n}.", + "Saqlanmagan partiya bor: {title}, yurishlar: {n}.", + "Сақталмаған партиÑ� бар: {title}, жүріÑ�тер: {n}.", + ], + [ + "📋 Keep a copy in the browser", + "📋 ОÑ�тавить копию в браузере", + "📋 Garder une copie dans le navigateur", + "📋 Kopie im Browser behalten", + "📋 Guardar una copia en el navegador", + "📋 Tieni una copia nel browser", + "📋 Manter uma cópia no navegador", + "📋 Brauzerda nusxa qoldirish", + "📋 Браузерде көшірме қалдыру", + ], + [ + "The copy opens right away, without choosing the file. It is stored in this browser on this device and is lost if you clear the site's data. The file on disk is not changed.", + "КопиÑ� откроетÑ�Ñ� Ñ�разу, без выбора файла. Она хранитÑ�Ñ� в Ñ�том браузере на Ñ�том уÑ�тройÑ�тве и пропадёт, еÑ�ли очиÑ�тить данные Ñ�айта. Файл на диÑ�ке не менÑ�етÑ�Ñ�.", + "La copie s'ouvre aussitôt, sans choisir le fichier. Elle est stockée dans ce navigateur sur cet appareil et disparaît si vous effacez les données du site. Le fichier sur le disque n'est pas modifié.", + "Die Kopie öffnet sich sofort, ohne die Datei zu wählen. Sie ist in diesem Browser auf diesem Gerät gespeichert und geht verloren, wenn Sie die Daten der Website löschen. Die Datei auf der Festplatte bleibt unverändert.", + "La copia se abre al instante, sin elegir el archivo. Se guarda en este navegador en este dispositivo y se pierde si borras los datos del sitio. El archivo del disco no cambia.", + "La copia si apre subito, senza scegliere il file. È salvata in questo browser su questo dispositivo e si perde se cancelli i dati del sito. Il file sul disco non cambia.", + "A cópia abre na hora, sem escolher o arquivo. Ela fica guardada neste navegador neste aparelho e se perde se você limpar os dados do site. O arquivo no disco não muda.", + "Nusxa faylni tanlamasdan darhol ochiladi. U shu qurilmadagi shu brauzerda saqlanadi va sayt ma’lumotlari tozalansa, yo‘qoladi. Diskdagi fayl o‘zgarmaydi.", + "Көшірме файлды таңдамай-ақ бірден ашылады. Ол оÑ�Ñ‹ құрылғыдағы оÑ�Ñ‹ браузерде Ñ�ақталады және Ñ�айт деректерін тазалаÑ�аңыз, жоғалады. ДиÑ�ктегі файл өзгермейді.", + ], + [ + "↻ Choose the file again", + "↻ Выбрать файл Ñ�нова", + "↻ Choisir le fichier à nouveau", + "↻ Datei erneut wählen", + "↻ Elegir el archivo de nuevo", + "↻ Scegli di nuovo il file", + "↻ Escolher o arquivo de novo", + "↻ Faylni qayta tanlash", + "↻ Файлды қайта таңдау", + ], + [ + "This browser doesn't remember files: after a reload, choose the file again or keep a copy in the browser.", + "Этот браузер не запоминает файлы: поÑ�ле перезагрузки выберите файл Ñ�нова или оÑ�тавьте копию в браузере.", + "Ce navigateur ne retient pas les fichiers : après un rechargement, choisissez à nouveau le fichier ou gardez-en une copie dans le navigateur.", + "Dieser Browser merkt sich keine Dateien: Wählen Sie die Datei nach einem Neuladen erneut oder behalten Sie eine Kopie im Browser.", + "Este navegador no recuerda los archivos: tras recargar, elige el archivo de nuevo o guarda una copia en el navegador.", + "Questo browser non ricorda i file: dopo un ricaricamento scegli di nuovo il file o tienine una copia nel browser.", + "Este navegador não lembra os arquivos: depois de recarregar, escolha o arquivo de novo ou mantenha uma cópia no navegador.", + "Bu brauzer fayllarni eslab qolmaydi: qayta yuklangandan keyin faylni yana tanlang yoki brauzerda nusxa qoldiring.", + "Бұл браузер файлдарды еÑ�те Ñ�ақтамайды: қайта жүктегеннен кейін файлды қайта таңдаңыз немеÑ�е браузерде көшірме қалдырыңыз.", + ], + [ + "A copy is kept in the browser", + "КопиÑ� оÑ�тавлена в браузере", + "Une copie est gardée dans le navigateur", + "Eine Kopie ist im Browser gespeichert", + "Se guardó una copia en el navegador", + "Una copia è conservata nel browser", + "Uma cópia ficou no navegador", + "Nusxa brauzerda qoldirildi", + "Көшірме браузерде қалдырылды", + ], + [ + "Doesn't fit: the copy needs {need}, and the browser gives the site only {free} more. Free up space in “Browser dataâ€� or open the file from disk.", + "Ð�е помещаетÑ�Ñ�: копии нужно {need}, а браузер даёт Ñ�айту ещё {free}. ОÑ�вободите меÑ�то в «Данных в браузере» или открывайте файл Ñ� диÑ�ка.", + "Ne tient pas : la copie a besoin de {need}, et le navigateur ne donne plus que {free} au site. Libérez de la place dans « Données du navigateur » ou ouvrez le fichier depuis le disque.", + "Passt nicht: Die Kopie braucht {need}, der Browser gibt der Website nur noch {free}. Schaffen Sie Platz unter „Daten im Browser“ oder öffnen Sie die Datei von der Festplatte.", + "No cabe: la copia necesita {need} y el navegador solo da al sitio {free} más. Libera espacio en «Datos del navegador» o abre el archivo desde el disco.", + "Non ci sta: la copia richiede {need} e il browser concede al sito solo altri {free}. Libera spazio in «Dati del browser» o apri il file dal disco.", + "Não cabe: a cópia precisa de {need}, e o navegador dá ao site só mais {free}. Libere espaço em “Dados do navegadorâ€� ou abra o arquivo do disco.", + "Sig‘maydi: nusxaga {need} kerak, brauzer esa saytga yana {free} beradi. «Brauzerdagi ma’lumotlar»da joy bo‘shating yoki faylni diskdan oching.", + "Сыймайды: көшірмеге {need} керек, ал браузер Ñ�айтқа тағы {free} береді. «Браузердегі деректер» бөлімінде орын боÑ�атыңыз немеÑ�е файлды диÑ�ктен ашыңыз.", + ], + [ + "My games", + "Мои партии", + "Mes parties", + "Meine Partien", + "Mis partidas", + "Le mie partite", + "Minhas partidas", + "Mening partiyalarim", + "Менің партиÑ�ларым", + ], + [ + "Browser data", + "Данные в браузере", + "Données du navigateur", + "Daten im Browser", + "Datos del navegador", + "Dati del browser", + "Dados do navegador", + "Brauzerdagi ma’lumotlar", + "Браузердегі деректер", + ], + [ + "Everything below is stored only here, on this device. Files on disk are not changed.", + "Ð’Ñ�Ñ‘ ниже хранитÑ�Ñ� только здеÑ�ÑŒ, на Ñ�том уÑ�тройÑ�тве. Файлы на диÑ�ке не менÑ�ÑŽÑ‚Ñ�Ñ�.", + "Tout ce qui suit est stocké uniquement ici, sur cet appareil. Les fichiers sur le disque ne sont pas modifiés.", + "Alles Folgende ist nur hier auf diesem Gerät gespeichert. Dateien auf der Festplatte werden nicht geändert.", + "Todo lo de abajo se guarda solo aquí, en este dispositivo. Los archivos del disco no cambian.", + "Tutto ciò che segue è salvato solo qui, su questo dispositivo. I file sul disco non cambiano.", + "Tudo abaixo fica guardado só aqui, neste aparelho. Os arquivos no disco não mudam.", + "Quyidagilarning barchasi faqat shu yerda, shu qurilmada saqlanadi. Diskdagi fayllar o‘zgarmaydi.", + "Төмендегінің бәрі тек оÑ�ында, оÑ�Ñ‹ құрылғыда Ñ�ақталады. ДиÑ�ктегі файлдар өзгермейді.", + ], + [ + "Used {used} · free for the site {free}", + "ЗанÑ�то {used} · Ñ�вободно длÑ� Ñ�айта {free}", + "Utilisé {used} · libre pour le site {free}", + "Belegt {used} · frei für die Website {free}", + "Ocupado {used} · libre para el sitio {free}", + "Occupato {used} · libero per il sito {free}", + "Ocupado {used} · livre para o site {free}", + "Band {used} · sayt uchun bo‘sh {free}", + "БоÑ� емеÑ� {used} · Ñ�айт үшін боÑ� {free}", + ], + [ + "Persistent storage: on", + "ПоÑ�тоÑ�нное хранение: включено", + "Stockage persistant : activé", + "Dauerhafte Speicherung: an", + "Almacenamiento persistente: activado", + "Archiviazione persistente: attiva", + "Armazenamento persistente: ativado", + "Doimiy saqlash: yoqilgan", + "Тұрақты Ñ�ақтау: қоÑ�улы", + ], + [ + "Persistent storage: not allowed by the browser", + "ПоÑ�тоÑ�нное хранение: не разрешено браузером", + "Stockage persistant : refusé par le navigateur", + "Dauerhafte Speicherung: vom Browser nicht erlaubt", + "Almacenamiento persistente: no permitido por el navegador", + "Archiviazione persistente: non consentita dal browser", + "Armazenamento persistente: não permitido pelo navegador", + "Doimiy saqlash: brauzer ruxsat bermagan", + "Тұрақты Ñ�ақтау: браузер Ñ€Ò±Ò›Ñ�ат етпеген", + ], + [ + "Ask the browser", + "СпроÑ�ить браузер", + "Demander au navigateur", + "Browser fragen", + "Pedírselo al navegador", + "Chiedi al browser", + "Pedir ao navegador", + "Brauzerdan so‘rash", + "Браузерден Ñ�ұрау", + ], + [ + "My games · {n}", + "Мои партии · {n}", + "Mes parties · {n}", + "Meine Partien · {n}", + "Mis partidas · {n}", + "Le mie partite · {n}", + "Minhas partidas · {n}", + "Mening partiyalarim · {n}", + "Менің партиÑ�ларым · {n}", + ], + [ + "Download all as PGN", + "Скачать вÑ�Ñ‘ в PGN", + "Tout télécharger en PGN", + "Alles als PGN herunterladen", + "Descargar todo en PGN", + "Scarica tutto in PGN", + "Baixar tudo em PGN", + "Hammasini PGN qilib yuklab olish", + "Барлығын PGN етіп жүктеп алу", + ], + [ + "Stockfish 19 engine", + "Движок Stockfish 19", + "Moteur Stockfish 19", + "Engine Stockfish 19", + "Motor Stockfish 19", + "Motore Stockfish 19", + "Motor Stockfish 19", + "Stockfish 19 dvijogi", + "Stockfish 19 қозғалтқышы", + ], + [ + "If you clear the site's data in the browser, all of this is lost. Download your games as PGN to keep them.", + "ЕÑ�ли очиÑ�тить данные Ñ�айта в браузере, вÑ�Ñ‘ Ñ�то пропадёт. Скачайте Ñ�вои партии в PGN, чтобы не потерÑ�ть их.", + "Si vous effacez les données du site dans le navigateur, tout cela est perdu. Téléchargez vos parties en PGN pour les garder.", + "Wenn Sie die Daten der Website im Browser löschen, geht all das verloren. Laden Sie Ihre Partien als PGN herunter, um sie zu behalten.", + "Si borras los datos del sitio en el navegador, todo esto se pierde. Descarga tus partidas en PGN para conservarlas.", + "Se cancelli i dati del sito nel browser, tutto questo va perso. Scarica le tue partite in PGN per conservarle.", + "Se você limpar os dados do site no navegador, tudo isso se perde. Baixe suas partidas em PGN para não perdê-las.", + "Agar brauzerda sayt ma’lumotlarini tozalasangiz, bularning barchasi yo‘qoladi. Partiyalaringizni saqlab qolish uchun ularni PGN qilib yuklab oling.", + "Браузерде Ñ�айт деректерін тазалаÑ�аңыз, мұның бәрі жоғалады. ПартиÑ�ларыңызды Ñ�ақтау үшін оларды PGN етіп жүктеп алыңыз.", + ], + [ + "It evaluates the position, shows the best moves and reviews the game. It is downloaded once and kept in this browser.", + "Оценивает позицию, показывает лучшие ходы и разбирает партию. СкачиваетÑ�Ñ� один раз и хранитÑ�Ñ� в Ñ�том браузере.", + "Il évalue la position, montre les meilleurs coups et analyse la partie. Il est téléchargé une fois et gardé dans ce navigateur.", + "Sie bewertet die Stellung, zeigt die besten Züge und analysiert die Partie. Sie wird einmal heruntergeladen und in diesem Browser gespeichert.", + "Evalúa la posición, muestra las mejores jugadas y analiza la partida. Se descarga una vez y se guarda en este navegador.", + "Valuta la posizione, mostra le mosse migliori e analizza la partita. Si scarica una volta e resta in questo browser.", + "Avalia a posição, mostra os melhores lances e analisa a partida. É baixado uma vez e fica guardado neste navegador.", + "U pozitsiyani baholaydi, eng yaxshi yurishlarni ko‘rsatadi va partiyani tahlil qiladi. Bir marta yuklab olinadi va shu brauzerda saqlanadi.", + "Ол позициÑ�ны бағалайды, ең жақÑ�Ñ‹ жүріÑ�терді көрÑ�етеді және партиÑ�ны талдайды. Бір рет жүктеліп, оÑ�Ñ‹ браузерде Ñ�ақталады.", + ], + [ + "Size: {size}", + "Размер: {size}", + "Taille : {size}", + "Größe: {size}", + "Tamaño: {size}", + "Dimensione: {size}", + "Tamanho: {size}", + "Hajmi: {size}", + "Көлемі: {size}", + ], + [ + "free for the site: {free}", + "Ñ�вободно длÑ� Ñ�айта: {free}", + "libre pour le site : {free}", + "frei für die Website: {free}", + "libre para el sitio: {free}", + "libero per il sito: {free}", + "livre para o site: {free}", + "sayt uchun bo‘sh: {free}", + "Ñ�айт үшін боÑ�: {free}", + ], + [ + "Not a database: {files}. ChessPenguin opens .pgn, .cbh, .cbv, .zip and .7z files.", + "Это не база: {files}. ChessPenguin открывает файлы .pgn, .cbh, .cbv, .zip и .7z.", + "Ce n’est pas une base : {files}. ChessPenguin ouvre les fichiers .pgn, .cbh, .cbv, .zip et .7z.", + "Keine Datenbank: {files}. ChessPenguin öffnet .pgn-, .cbh-, .cbv-, .zip- und .7z-Dateien.", + "No es una base: {files}. ChessPenguin abre archivos .pgn, .cbh, .cbv, .zip y .7z.", + "Non è un database: {files}. ChessPenguin apre i file .pgn, .cbh, .cbv, .zip e .7z.", + "Não é uma base: {files}. O ChessPenguin abre arquivos .pgn, .cbh, .cbv, .zip e .7z.", + "Bu baza emas: {files}. ChessPenguin .pgn, .cbh, .cbv, .zip va .7z fayllarini ochadi.", + "Бұл база емеÑ�: {files}. ChessPenguin .pgn, .cbh, .cbv, .zip және .7z файлдарын ашады.", + ], + [ + "Release to open", + "ОтпуÑ�тите, чтобы открыть", + "Relâchez pour ouvrir", + "Zum Öffnen loslassen", + "Suelta para abrir", + "Rilascia per aprire", + "Solte para abrir", + "Ochish uchun qo‘yib yuboring", + "Ð�шу үшін жіберіңіз", + ], + [ + "⇩ Download PGN", + "⇩ Скачать PGN", + "⇩ Télécharger le PGN", + "⇩ PGN herunterladen", + "⇩ Descargar PGN", + "⇩ Scarica PGN", + "⇩ Baixar PGN", + "⇩ PGN yuklab olish", + "⇩ PGN жүктеп алу", + ], + [ + "Download the game as a PGN file: the browser puts it where it puts downloads", + "Скачать партию файлом PGN: браузер положит его туда же, куда вÑ�е загрузки", + "Télécharger la partie en fichier PGN : le navigateur le met avec les autres téléchargements", + "Die Partie als PGN-Datei herunterladen: Der Browser legt sie zu den anderen Downloads", + "Descargar la partida como archivo PGN: el navegador lo guarda con las demás descargas", + "Scarica la partita come file PGN: il browser lo mette insieme agli altri download", + "Baixar a partida como arquivo PGN: o navegador o coloca junto dos outros downloads", + "Partiyani PGN fayl sifatida yuklab olish: brauzer uni boshqa yuklamalar qatoriga qo‘yadi", + "ПартиÑ�ны PGN файлы ретінде жүктеп алу: браузер оны баÑ�қа жүктемелермен бірге Ñ�ақтайды", + ], + [ + "The PGN could not be downloaded: {e}", + "Ð�е удалоÑ�ÑŒ Ñ�качать PGN: {e}", + "Impossible de télécharger le PGN : {e}", + "PGN konnte nicht heruntergeladen werden: {e}", + "No se pudo descargar el PGN: {e}", + "Impossibile scaricare il PGN: {e}", + "Não foi possível baixar o PGN: {e}", + "PGN yuklab olinmadi: {e}", + "PGN жүктеп алынбады: {e}", + ], + [ + "a browser cannot start it", + "браузер не может его запуÑ�тить", + "un navigateur ne peut pas le lancer", + "ein Browser kann ihn nicht starten", + "un navegador no puede iniciarlo", + "un browser non può avviarlo", + "um navegador não consegue iniciá-lo", + "brauzer uni ishga tushira olmaydi", + "браузер оны Ñ–Ñ�ке қоÑ�а алмайды", + ], + // --- engine download --- + [ + "Stockfish installed — game analysis started", + "Stockfish уÑ�тановлен — анализ партии запущен", + "Stockfish installé — analyse de la partie lancée", + "Stockfish installiert — Partieanalyse gestartet", + "Stockfish instalado — análisis de la partida iniciado", + "Stockfish installato — analisi della partita avviata", + "Stockfish instalado — análise da partida iniciada", + "Stockfish o‘rnatildi — partiya tahlili boshlandi", + "Stockfish орнатылды — партиÑ�ны талдау баÑ�талды", + ], + [ + "Stockfish installed — analysis is on", + "Stockfish уÑ�тановлен — анализ включён", + "Stockfish installé — l'analyse est active", + "Stockfish installiert — Analyse läuft", + "Stockfish instalado — análisis activado", + "Stockfish installato — analisi attiva", + "Stockfish instalado — análise ativada", + "Stockfish o‘rnatildi — tahlil yoqildi", + "Stockfish орнатылды — талдау қоÑ�улы", + ], + [ + "Stockfish installed", + "Stockfish уÑ�тановлен", + "Stockfish installé", + "Stockfish installiert", + "Stockfish instalado", + "Stockfish installato", + "Stockfish instalado", + "Stockfish o‘rnatildi", + "Stockfish орнатылды", + ], + [ + "âš  Stockfish wasn't downloaded", + "âš  Stockfish не Ñ�качан", + "âš  Stockfish n'a pas été téléchargé", + "âš  Stockfish wurde nicht heruntergeladen", + "âš  Stockfish no se descargó", + "âš  Stockfish non è stato scaricato", + "âš  O Stockfish não foi baixado", + "âš  Stockfish yuklab olinmadi", + "âš  Stockfish жүктелмеді", + ], + [ + "Analysis needs a chess engine", + "ДлÑ� анализа нужен движок", + "L'analyse nécessite un moteur", + "Für die Analyse wird eine Engine benötigt", + "El análisis necesita un motor", + "L'analisi richiede un motore", + "A análise precisa de um motor de xadrez", + "Tahlil uchun dvigatel kerak", + "Талдау үшін қозғалтқыш керек", + ], + [ + "Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.", + "Скачать Stockfish — Ñ�амый Ñ�ильный беÑ�платный шахматный движок? Ð�нализ включитÑ�Ñ� Ñ�ам, как только загрузка закончитÑ�Ñ�.", + "Télécharger Stockfish, le meilleur moteur d'échecs gratuit ? L'analyse démarrera dès la fin du téléchargement.", + "Stockfish herunterladen, die stärkste kostenlose Schach-Engine? Die Analyse startet, sobald der Download fertig ist.", + "¿Descargar Stockfish, el motor de ajedrez gratuito más fuerte? El análisis empezará en cuanto termine la descarga.", + "Scaricare Stockfish, il motore scacchistico gratuito più forte? L'analisi partirà appena finisce il download.", + "Baixar o Stockfish, o motor de xadrez gratuito mais forte? A análise começa assim que o download terminar.", + "Eng kuchli bepul shaxmat dvigateli Stockfish yuklab olinsinmi? Yuklab olish tugashi bilan tahlil o‘zi boshlanadi.", + "Stockfish — ең күшті тегін шахмат қозғалтқышын жүктеп алу керек пе? Жүктеу аÑ�қталған Ñ�оң талдау өзі баÑ�талады.", + ], + [ + "Stockfish is already installed on this computer.", + "Ð�а компьютере уже уÑ�тановлен Stockfish.", + "Stockfish est déjà installé sur cet ordinateur.", + "Stockfish ist auf diesem Computer bereits installiert.", + "Stockfish ya está instalado en este ordenador.", + "Stockfish è già installato su questo computer.", + "O Stockfish já está instalado neste computador.", + "Bu kompyuterda Stockfish allaqachon o‘rnatilgan.", + "Бұл компьютерде Stockfish орнатылған.", + ], + [ + "Stockfish not found", + "Stockfish не найден", + "Stockfish introuvable", + "Stockfish nicht gefunden", + "Stockfish no encontrado", + "Stockfish non trovato", + "Stockfish não encontrado", + "Stockfish topilmadi", + "Stockfish табылмады", + ], + [ + "The Stockfish file is missing from the disk. Download it again?", + "Файл Stockfish пропал Ñ� диÑ�ка. Скачать его заново?", + "Le fichier Stockfish a disparu du disque. Le télécharger à nouveau ?", + "Die Stockfish-Datei fehlt auf der Festplatte. Erneut herunterladen?", + "El archivo de Stockfish ya no está en el disco. ¿Descargarlo de nuevo?", + "Il file di Stockfish non è più sul disco. Scaricarlo di nuovo?", + "O arquivo do Stockfish não está no disco. Baixar de novo?", + "Stockfish fayli diskda yo‘q. Qayta yuklab olinsinmi?", + "Stockfish файлы диÑ�кіде жоқ. Қайта жүктеп алу керек пе?", + ], + [ + "Installed for your account only", + "УÑ�танавливаетÑ�Ñ� только длÑ� ваÑ�", + "Installé pour votre compte uniquement", + "Nur für Ihr Konto installiert", + "Se instala solo para su cuenta", + "Installato solo per il tuo account", + "Instalado apenas para sua conta", + "Faqat sizning hisobingiz uchun o‘rnatiladi", + "Тек Ñ�іздің тіркелгіңізге орнатылады", + ], + [ + "Use it", + "ИÑ�пользовать его", + "L'utiliser", + "Diese verwenden", + "Usarlo", + "Usalo", + "Usar", + "Undan foydalanish", + "Соны қолдану", + ], + [ + "Later", + "Позже", + "Plus tard", + "Später", + "Más tarde", + "Più tardi", + "Depois", + "Keyinroq", + "Кейінірек", + ], + [ + "Download", + "Скачать", + "Télécharger", + "Herunterladen", + "Descargar", + "Scarica", + "Baixar", + "Yuklab olish", + "Жүктеп алу", + ], + [ + "Download again", + "Скачать заново", + "Télécharger à nouveau", + "Erneut herunterladen", + "Descargar de nuevo", + "Scarica di nuovo", + "Baixar de novo", + "Qayta yuklab olish", + "Қайта жүктеу", + ], + [ + "Download Stockfish", + "Скачать Stockfish", + "Télécharger Stockfish", + "Stockfish herunterladen", + "Descargar Stockfish", + "Scarica Stockfish", + "Baixar Stockfish", + "Stockfish yuklab olish", + "Stockfish жүктеу", + ], + [ + "Choose engine file…", + "Указать файл движка…", + "Choisir le fichier du moteur…", + "Engine-Datei wählen…", + "Elegir archivo del motor…", + "Scegli il file del motore…", + "Escolher arquivo do motor…", + "Dvigatel faylini tanlash…", + "Қозғалтқыш файлын таңдау…", + ], + [ + "+ Choose engine file…", + "+ Указать файл движка…", + "+ Choisir le fichier du moteur…", + "+ Engine-Datei wählen…", + "+ Elegir archivo del motor…", + "+ Scegli il file del motore…", + "+ Escolher arquivo do motor…", + "+ Dvigatel faylini tanlash…", + "+ Қозғалтқыш файлын таңдау…", + ], + [ + "Downloading Stockfish", + "Скачивание Stockfish", + "Téléchargement de Stockfish", + "Stockfish wird heruntergeladen", + "Descargando Stockfish", + "Download di Stockfish", + "Baixando o Stockfish", + "Stockfish yuklab olinmoqda", + "Stockfish жүктелуде", + ], + [ + "Checking and installing…", + "Проверка и уÑ�тановка…", + "Vérification et installation…", + "Prüfen und installieren…", + "Comprobando e instalando…", + "Verifica e installazione…", + "Verificando e instalando…", + "Tekshirilmoqda va o‘rnatilmoqda…", + "ТекÑ�еру және орнату…", + ], + [ + "Game analysis will start by itself when the download finishes.", + "Ð�нализ партии начнётÑ�Ñ� Ñ�ам поÑ�ле загрузки.", + "L'analyse de la partie démarrera seule à la fin du téléchargement.", + "Die Partieanalyse startet nach dem Download von selbst.", + "El análisis de la partida empezará solo al terminar la descarga.", + "L'analisi della partita partirà da sola a fine download.", + "A análise da partida começa sozinha quando o download terminar.", + "Yuklab olish tugagach, partiya tahlili o‘zi boshlanadi.", + "Жүктеу аÑ�қталғанда партиÑ�ны талдау өзі баÑ�талады.", + ], + [ + "Analysis will start by itself when the download finishes.", + "Ð�нализ включитÑ�Ñ� Ñ�ам поÑ�ле загрузки.", + "L'analyse démarrera seule à la fin du téléchargement.", + "Die Analyse startet nach dem Download von selbst.", + "El análisis empezará solo al terminar la descarga.", + "L'analisi partirà da sola a fine download.", + "A análise começa sozinha quando o download terminar.", + "Yuklab olish tugagach, tahlil o‘zi boshlanadi.", + "Жүктеу аÑ�қталғанда талдау өзі баÑ�талады.", + ], + [ + "Hide", + "Скрыть", + "Masquer", + "Ausblenden", + "Ocultar", + "Nascondi", + "Ocultar", + "Yashirish", + "ЖаÑ�ыру", + ], + [ + "Cancel download", + "Отменить загрузку", + "Annuler le téléchargement", + "Download abbrechen", + "Cancelar la descarga", + "Annulla il download", + "Cancelar download", + "Yuklab olishni bekor qilish", + "Жүктеуді тоқтату", + ], + [ + "Details", + "ПодробноÑ�ти", + "Détails", + "Details", + "Detalles", + "Dettagli", + "Detalhes", + "Batafsil", + "Толығырақ", + ], + [ + "PGN copied (comments in the original)", + "PGN Ñ�копирован (комментарии — в оригинале)", + "PGN copié (commentaires dans l’original)", + "PGN kopiert (Kommentare im Original)", + "PGN copiado (comentarios en el original)", + "PGN copiato (commenti in originale)", + "PGN copiado (comentários no original)", + "PGN nusxalandi (izohlar asl holida)", + "PGN көшірілді (түÑ�ініктемелер — түпнұÑ�қада)", + ], + [ + "Translate comments", + "ПеревеÑ�ти комментарии", + "Traduire les commentaires", + "Kommentare übersetzen", + "Traducir los comentarios", + "Traduci i commenti", + "Traduzir comentários", + "Izohlarni tarjima qilish", + "ТүÑ�ініктемелерді аудару", + ], + [ + "Show the translation (Ctrl+Shift+T)", + "Показать перевод (Ctrl+Shift+T)", + "Afficher la traduction (Ctrl+Maj+T)", + "Übersetzung zeigen (Strg+Umschalt+T)", + "Mostrar la traducción (Ctrl+Mayús+T)", + "Mostra la traduzione (Ctrl+Maiusc+T)", + "Mostrar a tradução (Ctrl+Shift+T)", + "Tarjimani ko‘rsatish (Ctrl+Shift+T)", + "Ð�удармаÑ�ын көрÑ�ету (Ctrl+Shift+T)", + ], + [ + "Show the original (Ctrl+Shift+T)", + "Показать оригинал (Ctrl+Shift+T)", + "Afficher l’original (Ctrl+Maj+T)", + "Original zeigen (Strg+Umschalt+T)", + "Mostrar el original (Ctrl+Mayús+T)", + "Mostra l’originale (Ctrl+Maiusc+T)", + "Mostrar o original (Ctrl+Shift+T)", + "Aslini ko‘rsatish (Ctrl+Shift+T)", + "ТүпнұÑ�қаÑ�ын көрÑ�ету (Ctrl+Shift+T)", + ], + [ + "Translation settings…", + "Ð�аÑ�тройки перевода…", + "Paramètres de traduction…", + "Übersetzungseinstellungen…", + "Ajustes de traducción…", + "Impostazioni di traduzione…", + "Configurações de tradução…", + "Tarjima sozlamalari…", + "Ð�ударма баптаулары…", + ], + [ + "Machine translation. Original:", + "Машинный перевод. Оригинал:", + "Traduction automatique. Original :", + "Maschinelle Übersetzung. Original:", + "Traducción automática. Original:", + "Traduzione automatica. Originale:", + "Tradução automática. Original:", + "Mashina tarjimasi. Asli:", + "Машиналық аударма. ТүпнұÑ�қа:", + ], + [ + "Machine translation", + "Машинный перевод", + "Traduction automatique", + "Maschinelle Übersetzung", + "Traducción automática", + "Traduzione automatica", + "Tradução automática", + "Mashina tarjimasi", + "Машиналық аударма", + ], + [ + "Translating…", + "ПереводитÑ�Ñ�…", + "Traduction…", + "Wird übersetzt…", + "Traduciendo…", + "Traduzione in corso…", + "Traduzindo…", + "Tarjima qilinmoqda…", + "Ð�ударылуда…", + ], + [ + "This comment could not be translated — the original is shown. Press “Retryâ€� in the line above the notation.", + "Этот комментарий не удалоÑ�ÑŒ перевеÑ�ти — показан оригинал. Ð�ажмите «Повторить» в Ñ�троке над нотацией.", + "Ce commentaire n’a pas pu être traduit — l’original est affiché. Appuyez sur « Réessayer » dans la ligne au-dessus de la notation.", + "Dieser Kommentar konnte nicht übersetzt werden — das Original wird gezeigt. Klicken Sie in der Zeile über der Notation auf „Erneut versuchen“.", + "No se pudo traducir este comentario: se muestra el original. Pulse «Reintentar» en la línea sobre la notación.", + "Questo commento non è stato tradotto: è mostrato l’originale. Premi «Riprova» nella riga sopra la notazione.", + "Não foi possível traduzir este comentário — o original é exibido. Clique em “Tentar de novoâ€� na linha acima da notação.", + "Bu izohni tarjima qilib bo‘lmadi — asli ko‘rsatilgan. Notatsiya ustidagi qatorda “Qayta urinishâ€�ni bosing.", + "Бұл түÑ�ініктеме аударылмады — түпнұÑ�қаÑ�Ñ‹ көрÑ�етілген. Ð�отациÑ�ның Ò¯Ñ�тіндегі жолда «Қайталау» түймеÑ�ін баÑ�ыңыз.", + ], + [ + "Not translated", + "Ð�е переведено", + "Non traduit", + "Nicht übersetzt", + "No traducido", + "Non tradotto", + "Não traduzido", + "Tarjima qilinmagan", + "Ð�ударылмаған", + ], + [ + "Translation", + "Перевод", + "Traduction", + "Übersetzung", + "Traducción", + "Traduzione", + "Tradução", + "Tarjima", + "Ð�ударма", + ], + [ + "Another address", + "Свой адреÑ�", + "Autre adresse", + "Eigene Adresse", + "Otra dirección", + "Altro indirizzo", + "Outro endereço", + "Boshqa manzil", + "БаÑ�қа мекенжай", + ], + [ + "How to translate?", + "Как переводить?", + "Comment traduire ?", + "Wie übersetzen?", + "¿Cómo traducir?", + "Come tradurre?", + "Como traduzir?", + "Qanday tarjima qilinsin?", + "Қалай аудару керек?", + ], + [ + "• player names, the event and the opening — for accurate terms.", + "• имена игроков, турнир и дебют — длÑ� точных терминов.", + "• les noms des joueurs, le tournoi et l’ouverture — pour des termes justes.", + "• Spielernamen, Turnier und Eröffnung — für genaue Begriffe.", + "• los nombres de los jugadores, el torneo y la apertura, para términos precisos.", + "• i nomi dei giocatori, il torneo e l’apertura, per termini precisi.", + "• nomes dos jogadores, o evento e a abertura — para termos precisos.", + "• o‘yinchilar ismi, turnir va debyut — atamalar aniq bo‘lishi uchun.", + "• ойыншылардың аты, турнир және дебют — терминдер дәл болуы үшін.", + ], + [ + "The game's moves are not sent; moves written inside comments are.", + "Ходы партии не отправлÑ�ÑŽÑ‚Ñ�Ñ�; ходы, запиÑ�анные в комментариÑ�Ñ…, — отправлÑ�ÑŽÑ‚Ñ�Ñ�.", + "Les coups de la partie ne sont pas envoyés ; ceux écrits dans les commentaires le sont.", + "Die Züge der Partie werden nicht gesendet; Züge in Kommentaren schon.", + "Las jugadas de la partida no se envían; las escritas en los comentarios sí.", + "Le mosse della partita non vengono inviate; quelle scritte nei commenti sì.", + "Os lances da partida não são enviados; os lances escritos nos comentários, sim.", + "Partiya yurishlari yuborilmaydi; izohlar ichida yozilgan yurishlar yuboriladi.", + "ПартиÑ� жүріÑ�тері жіберілмейді; түÑ�ініктемелердегі жүріÑ�тер жіберіледі.", + ], + [ + "Translation uses part of your subscription's limit.", + "Перевод раÑ�ходует чаÑ�ть лимита вашей подпиÑ�ки.", + "La traduction utilise une partie de la limite de votre abonnement.", + "Die Übersetzung verbraucht einen Teil des Kontingents Ihres Abos.", + "La traducción consume parte del límite de su suscripción.", + "La traduzione usa parte del limite del tuo abbonamento.", + "A tradução usa parte do limite da sua assinatura.", + "Tarjima obunangiz limitining bir qismini sarflaydi.", + "Ð�ударма жазылым лимитінің бір бөлігін жұмÑ�айды.", + ], + [ + "From now on, comments in other languages will be translated by themselves when you open a game. To turn it off or withdraw the permission: Settings › Translation.", + "Дальше комментарии на других Ñ�зыках будут переводитьÑ�Ñ� Ñ�ами, когда вы открываете партию. Отключить или отозвать разрешение: Ð�аÑ�тройки › Перевод.", + "Désormais, les commentaires dans d’autres langues seront traduits d’eux-mêmes à l’ouverture d’une partie. Pour désactiver ou retirer l’autorisation : Paramètres › Traduction.", + "Ab jetzt werden Kommentare in anderen Sprachen beim Öffnen einer Partie von selbst übersetzt. Ausschalten oder die Erlaubnis zurücknehmen: Einstellungen › Übersetzung.", + "A partir de ahora, los comentarios en otros idiomas se traducirán solos al abrir una partida. Para desactivarlo o retirar el permiso: Ajustes › Traducción.", + "D’ora in poi i commenti in altre lingue verranno tradotti da soli quando apri una partita. Per disattivare o revocare il permesso: Impostazioni › Traduzione.", + "A partir de agora, comentários em outros idiomas serão traduzidos sozinhos ao abrir uma partida. Para desativar ou retirar a permissão: Configurações › Tradução.", + "Endi partiya ochilganda boshqa tillardagi izohlar o‘zi tarjima qilinadi. O‘chirish yoki ruxsatni bekor qilish: Sozlamalar › Tarjima.", + "Енді баÑ�қа тілдегі түÑ�ініктемелер партиÑ�ны ашқанда өзі аударылады. Өшіру немеÑ�е Ñ€Ò±Ò›Ñ�атты қайтарып алу: Баптаулар › Ð�ударма.", + ], + [ + "Start translating", + "Переводить", + "Traduire", + "Übersetzen", + "Traducir", + "Traduci", + "Começar a traduzir", + "Tarjimani boshlash", + "Ð�ударуды баÑ�тау", + ], + [ + "Back", + "Ð�азад", + "Retour", + "Zurück", + "Atrás", + "Indietro", + "Voltar", + "Orqaga", + "Ð�ртқа", + ], + [ + "Checking the subscription…", + "ПроверÑ�ÑŽ подпиÑ�ку…", + "Vérification de l’abonnement…", + "Abo wird geprüft…", + "Comprobando la suscripción…", + "Verifica dell’abbonamento…", + "Verificando a assinatura…", + "Obuna tekshirilmoqda…", + "Жазылым текÑ�ерілуде…", + ], + [ + "Comments are translated by a language model. Choose which:", + "Комментарии переводит Ñ�зыковаÑ� модель. Выберите, какую:", + "Les commentaires sont traduits par un modèle de langage. Choisissez lequel :", + "Kommentare übersetzt ein Sprachmodell. Wählen Sie, welches:", + "Los comentarios los traduce un modelo de lenguaje. Elija cuál:", + "I commenti li traduce un modello linguistico. Scegli quale:", + "Os comentários são traduzidos por um modelo de linguagem. Escolha qual:", + "Izohlarni til modeli tarjima qiladi. Qaysi birini tanlang:", + "ТүÑ�ініктемелерді тілдік модель аударады. ҚайÑ�Ñ‹Ñ�ын таңдаңыз:", + ], + [ + "I have ChatGPT Plus or Pro", + "У менÑ� еÑ�ть ChatGPT Plus или Pro", + "J’ai ChatGPT Plus ou Pro", + "Ich habe ChatGPT Plus oder Pro", + "Tengo ChatGPT Plus o Pro", + "Ho ChatGPT Plus o Pro", + "Tenho ChatGPT Plus ou Pro", + "Menda ChatGPT Plus yoki Pro bor", + "Менде ChatGPT Plus немеÑ�е Pro бар", + ], + [ + "The easiest way: sign in, no key needed.", + "Проще вÑ�его: войдите, ключ не нужен.", + "Le plus simple : connectez-vous, aucune clé nécessaire.", + "Am einfachsten: anmelden, kein Schlüssel nötig.", + "Lo más fácil: inicie sesión, no hace falta clave.", + "Il modo più semplice: accedi, nessuna chiave.", + "O jeito mais fácil: entre na conta, sem chave.", + "Eng oson yo‘l: kiring, kalit kerak emas.", + "Ең оңай жолы: кіріңіз, кілт керек емеÑ�.", + ], + [ + "Uses part of your subscription's limit.", + "РаÑ�ходует чаÑ�ть лимита подпиÑ�ки.", + "Utilise une partie de la limite de l’abonnement.", + "Verbraucht einen Teil des Abo-Kontingents.", + "Consume parte del límite de la suscripción.", + "Usa parte del limite dell’abbonamento.", + "Usa parte do limite da sua assinatura.", + "Obuna limitining bir qismini sarflaydi.", + "Жазылым лимитінің бір бөлігін жұмÑ�айды.", + ], + [ + "No subscription — an API key", + "ПодпиÑ�ки нет — ключ API", + "Pas d’abonnement — une clé API", + "Kein Abo — ein API-Schlüssel", + "Sin suscripción: una clave API", + "Nessun abbonamento: una chiave API", + "Sem assinatura — uma chave de API", + "Obuna yo‘q — API kaliti", + "Жазылым жоқ — API кілті", + ], + [ + "A service with a key, or a model on this computer.", + "СервиÑ� Ñ� ключом или модель на Ñ�том компьютере.", + "Un service avec une clé, ou un modèle sur cet ordinateur.", + "Ein Dienst mit Schlüssel oder ein Modell auf diesem Computer.", + "Un servicio con clave o un modelo en este ordenador.", + "Un servizio con chiave o un modello su questo computer.", + "Um serviço com chave ou um modelo neste computador.", + "Kalitli xizmat yoki shu kompyuterdagi model.", + "Кілті бар Ñ�ервиÑ� немеÑ�е оÑ�Ñ‹ компьютердегі модель.", + ], + [ + "From now on, comments in other languages will be translated by themselves when you open a game. To change: Settings › Translation.", + "Дальше комментарии на других Ñ�зыках будут переводитьÑ�Ñ� Ñ�ами, когда вы открываете партию. Изменить: Ð�аÑ�тройки › Перевод.", + "Désormais, les commentaires dans d’autres langues seront traduits d’eux-mêmes à l’ouverture d’une partie. Pour changer : Paramètres › Traduction.", + "Ab jetzt werden Kommentare in anderen Sprachen beim Öffnen einer Partie von selbst übersetzt. Ändern: Einstellungen › Übersetzung.", + "A partir de ahora, los comentarios en otros idiomas se traducirán solos al abrir una partida. Para cambiarlo: Ajustes › Traducción.", + "D’ora in poi i commenti in altre lingue verranno tradotti da soli quando apri una partita. Per cambiare: Impostazioni › Traduzione.", + "A partir de agora, comentários em outros idiomas serão traduzidos sozinhos ao abrir uma partida. Para mudar: Configurações › Tradução.", + "Endi partiya ochilganda boshqa tillardagi izohlar o‘zi tarjima qilinadi. O‘zgartirish: Sozlamalar › Tarjima.", + "Енді баÑ�қа тілдегі түÑ�ініктемелер партиÑ�ны ашқанда өзі аударылады. Өзгерту: Баптаулар › Ð�ударма.", + ], + [ + "Sign in with ChatGPT", + "Войти через ChatGPT", + "Se connecter avec ChatGPT", + "Mit ChatGPT anmelden", + "Iniciar sesión con ChatGPT", + "Accedi con ChatGPT", + "Entrar com o ChatGPT", + "ChatGPT orqali kirish", + "ChatGPT арқылы кіру", + ], + [ + "ChatGPT sign-in", + "Вход через ChatGPT", + "Connexion avec ChatGPT", + "Anmeldung mit ChatGPT", + "Inicio de sesión con ChatGPT", + "Accesso con ChatGPT", + "Login com o ChatGPT", + "ChatGPT orqali kirish", + "ChatGPT арқылы кіру", + ], + [ + "Check and continue", + "Проверить и продолжить", + "Vérifier et continuer", + "Prüfen und weiter", + "Comprobar y continuar", + "Verifica e continua", + "Verificar e continuar", + "Tekshirish va davom etish", + "ТекÑ�еру және жалғаÑ�тыру", + ], + [ + "Paste the key first", + "Сначала вÑ�тавьте ключ", + "Collez d’abord la clé", + "Fügen Sie zuerst den Schlüssel ein", + "Pegue primero la clave", + "Incolla prima la chiave", + "Cole a chave primeiro", + "Avval kalitni qo‘ying", + "Ð�лдымен кілтті қойыңыз", + ], + [ + "Sign-in was not finished in 10 minutes.", + "Вход не завершён за 10 минут.", + "La connexion n’a pas abouti en 10 minutes.", + "Die Anmeldung wurde nicht in 10 Minuten abgeschlossen.", + "El inicio de sesión no terminó en 10 minutos.", + "L’accesso non è stato completato in 10 minuti.", + "O login não foi concluído em 10 minutos.", + "Kirish 10 daqiqada yakunlanmadi.", + "Кіру 10 минутта аÑ�қталмады.", + ], + [ + "Sign-in was cancelled in the browser.", + "Вход отменён в браузере.", + "La connexion a été annulée dans le navigateur.", + "Die Anmeldung wurde im Browser abgebrochen.", + "El inicio de sesión se canceló en el navegador.", + "L’accesso è stato annullato nel browser.", + "O login foi cancelado no navegador.", + "Kirish brauzerda bekor qilindi.", + "Кіру браузерде тоқтатылды.", + ], + [ + "âš  Sign-in could not be finished.", + "âš  Ð�е удалоÑ�ÑŒ завершить вход.", + "âš  La connexion n’a pas pu aboutir.", + "âš  Die Anmeldung konnte nicht abgeschlossen werden.", + "âš  No se pudo completar el inicio de sesión.", + "âš  Non è stato possibile completare l’accesso.", + "âš  Não foi possível concluir o login.", + "âš  Kirishni yakunlab bo‘lmadi.", + "âš  Кіруді аÑ�қтау мүмкін болмады.", + ], + [ + "âš  Sign-in could not be prepared: ChessPenguin cannot receive the browser's answer.", + "âš  Ð�е удалоÑ�ÑŒ подготовить вход: ChessPenguin не может принÑ�ть ответ браузера.", + "âš  Impossible de préparer la connexion : ChessPenguin ne peut pas recevoir la réponse du navigateur.", + "âš  Die Anmeldung konnte nicht vorbereitet werden: ChessPenguin kann die Antwort des Browsers nicht empfangen.", + "âš  No se pudo preparar el inicio de sesión: ChessPenguin no puede recibir la respuesta del navegador.", + "âš  Impossibile preparare l’accesso: ChessPenguin non può ricevere la risposta del browser.", + "âš  Não foi possível preparar o login: o ChessPenguin não consegue receber a resposta do navegador.", + "âš  Kirishni tayyorlab bo‘lmadi: ChessPenguin brauzer javobini qabul qila olmaydi.", + "âš  Кіруді дайындау мүмкін болмады: ChessPenguin браузердің жауабын қабылдай алмайды.", + ], + [ + "âš  You signed in, but did not allow ChessPenguin to use the subscription's limit. Without it, translation with ChatGPT does not work.", + "âš  Ð’Ñ‹ вошли, но не разрешили ChessPenguin раÑ�ходовать лимит подпиÑ�ки. Без Ñ�того перевод через ChatGPT не работает.", + "âš  Vous êtes connecté, mais n’avez pas autorisé ChessPenguin à utiliser la limite de l’abonnement. Sans cela, la traduction avec ChatGPT ne fonctionne pas.", + "âš  Sie sind angemeldet, haben ChessPenguin aber nicht erlaubt, das Abo-Kontingent zu nutzen. Ohne das funktioniert die Übersetzung mit ChatGPT nicht.", + "âš  Ha iniciado sesión, pero no ha permitido a ChessPenguin usar el límite de la suscripción. Sin eso, la traducción con ChatGPT no funciona.", + "âš  Hai effettuato l’accesso, ma non hai permesso a ChessPenguin di usare il limite dell’abbonamento. Senza, la traduzione con ChatGPT non funziona.", + "âš  Você entrou, mas não permitiu que o ChessPenguin use o limite da assinatura. Sem isso, a tradução com o ChatGPT não funciona.", + "âš  Siz kirdingiz, lekin ChessPenguinga obuna limitidan foydalanishga ruxsat bermadingiz. Busiz ChatGPT orqali tarjima ishlamaydi.", + "âš  Сіз кірдіңіз, бірақ ChessPenguin-ге жазылым лимитін пайдалануға Ñ€Ò±Ò›Ñ�ат бермедіңіз. ОнÑ�ыз ChatGPT арқылы аударма жұмыÑ� Ñ–Ñ�темейді.", + ], + [ + "âš  This ChatGPT account cannot translate in ChessPenguin: a Plus or Pro subscription is needed.", + "âš  Этот аккаунт ChatGPT не может переводить в ChessPenguin: нужна подпиÑ�ка Plus или Pro.", + "âš  Ce compte ChatGPT ne peut pas traduire dans ChessPenguin : un abonnement Plus ou Pro est nécessaire.", + "âš  Dieses ChatGPT-Konto kann in ChessPenguin nicht übersetzen: Ein Plus- oder Pro-Abo ist nötig.", + "âš  Esta cuenta de ChatGPT no puede traducir en ChessPenguin: hace falta una suscripción Plus o Pro.", + "âš  Questo account ChatGPT non può tradurre in ChessPenguin: serve un abbonamento Plus o Pro.", + "âš  Esta conta do ChatGPT não pode traduzir no ChessPenguin: é preciso uma assinatura Plus ou Pro.", + "âš  Bu ChatGPT hisobi ChessPenguinda tarjima qila olmaydi: Plus yoki Pro obunasi kerak.", + "âš  Бұл ChatGPT тіркелгіÑ�Ñ– ChessPenguin-де аудара алмайды: Plus немеÑ�е Pro жазылымы керек.", + ], + [ + "On the OpenAI site, leave the permission to use the subscription turned on", + "Ð�а Ñ�айте OpenAI оÑ�тавьте разрешение на иÑ�пользование подпиÑ�ки включённым", + "Sur le site d’OpenAI, laissez activée l’autorisation d’utiliser l’abonnement", + "Lassen Sie auf der OpenAI-Seite die Erlaubnis zur Nutzung des Abos eingeschaltet", + "En el sitio de OpenAI, deje activado el permiso para usar la suscripción", + "Sul sito di OpenAI lascia attivo il permesso di usare l’abbonamento", + "No site da OpenAI, deixe ativada a permissão para usar a assinatura", + "OpenAI saytida obunadan foydalanish ruxsatini yoqilgan holda qoldiring", + "OpenAI Ñ�айтында жазылымды пайдалану Ñ€Ò±Ò›Ñ�атын қоÑ�улы қалдырыңыз", + ], + [ + "Service:", + "СервиÑ�:", + "Service :", + "Dienst:", + "Servicio:", + "Servizio:", + "Serviço:", + "Xizmat:", + "СервиÑ�:", + ], + [ + "1. Open the {service} website ↗ and sign in.", + "1. Откройте Ñ�айт {service} ↗ и войдите.", + "1. Ouvrez le site {service} ↗ et connectez-vous.", + "1. Öffnen Sie die Website von {service} ↗ und melden Sie sich an.", + "1. Abra el sitio de {service} ↗ e inicie sesión.", + "1. Apri il sito di {service} ↗ e accedi.", + "1. Abra o site do {service} ↗ e entre na conta.", + "1. {service} saytini oching ↗ va kiring.", + "1. {service} Ñ�айтын ашып ↗, кіріңіз.", + ], + [ + "2. Top up the balance: DeepSeek works with prepayment.", + "2. Пополните баланÑ�: DeepSeek работает по предоплате.", + "2. Rechargez le solde : DeepSeek fonctionne en prépaiement.", + "2. Laden Sie das Guthaben auf: DeepSeek arbeitet mit Vorauszahlung.", + "2. Recargue el saldo: DeepSeek funciona con prepago.", + "2. Ricarica il saldo: DeepSeek funziona con il prepagato.", + "2. Adicione saldo: o DeepSeek funciona com pré-pagamento.", + "2. Balansni to‘ldiring: DeepSeek oldindan to‘lov bilan ishlaydi.", + "2. БаланÑ�ты толтырыңыз: DeepSeek алдын ала төлеммен жұмыÑ� Ñ–Ñ�тейді.", + ], + [ + "3. Press “Create new API keyâ€� and copy the key — it is shown only once.", + "3. Ð�ажмите «Create new API key» и Ñ�копируйте ключ — его показывают один раз.", + "3. Cliquez sur « Create new API key » et copiez la clé — elle n’est affichée qu’une fois.", + "3. Klicken Sie auf „Create new API key“ und kopieren Sie den Schlüssel — er wird nur einmal gezeigt.", + "3. Pulse «Create new API key» y copie la clave: solo se muestra una vez.", + "3. Premi «Create new API key» e copia la chiave: viene mostrata una sola volta.", + "3. Clique em “Create new API keyâ€� e copie a chave — ela é exibida só uma vez.", + "3. “Create new API keyâ€�ni bosing va kalitni nusxalang — u faqat bir marta ko‘rsatiladi.", + "3. «Create new API key» түймеÑ�ін баÑ�ып, кілтті көшіріңіз — ол бір рет қана көрÑ�етіледі.", + ], + [ + "4. Paste the key here:", + "4. Ð’Ñ�тавьте ключ Ñ�юда:", + "4. Collez la clé ici :", + "4. Fügen Sie den Schlüssel hier ein:", + "4. Pegue la clave aquí:", + "4. Incolla la chiave qui:", + "4. Cole a chave aqui:", + "4. Kalitni shu yerga qo‘ying:", + "4. Кілтті оÑ�ында қойыңыз:", + ], + [ + "2. Top up the balance in the Billing section.", + "2. Пополните баланÑ� в разделе Billing.", + "2. Rechargez le solde dans la section Billing.", + "2. Laden Sie das Guthaben im Bereich Billing auf.", + "2. Recargue el saldo en la sección Billing.", + "2. Ricarica il saldo nella sezione Billing.", + "2. Adicione saldo na seção Billing.", + "2. Billing bo‘limida balansni to‘ldiring.", + "2. Billing бөлімінде баланÑ�ты толтырыңыз.", + ], + [ + "3. Press “Create new secret keyâ€� and copy the key.", + "3. Ð�ажмите «Create new secret key» и Ñ�копируйте ключ.", + "3. Cliquez sur « Create new secret key » et copiez la clé.", + "3. Klicken Sie auf „Create new secret key“ und kopieren Sie den Schlüssel.", + "3. Pulse «Create new secret key» y copie la clave.", + "3. Premi «Create new secret key» e copia la chiave.", + "3. Clique em “Create new secret keyâ€� e copie a chave.", + "3. “Create new secret keyâ€�ni bosing va kalitni nusxalang.", + "3. «Create new secret key» түймеÑ�ін баÑ�ып, кілтті көшіріңіз.", + ], + [ + "The API key is paid separately from the ChatGPT subscription.", + "Ключ API оплачиваетÑ�Ñ� отдельно от подпиÑ�ки ChatGPT.", + "La clé API se paie à part de l’abonnement ChatGPT.", + "Der API-Schlüssel wird getrennt vom ChatGPT-Abo bezahlt.", + "La clave API se paga aparte de la suscripción a ChatGPT.", + "La chiave API si paga a parte rispetto all’abbonamento ChatGPT.", + "A chave de API é paga à parte da assinatura do ChatGPT.", + "API kaliti ChatGPT obunasidan alohida to‘lanadi.", + "API кілті ChatGPT жазылымынан бөлек төленеді.", + ], + [ + "1. Open Google AI Studio ↗ and sign in with your Google account.", + "1. Откройте Google AI Studio ↗ и войдите Ñ� аккаунтом Google.", + "1. Ouvrez Google AI Studio ↗ et connectez-vous avec votre compte Google.", + "1. Öffnen Sie Google AI Studio ↗ und melden Sie sich mit Ihrem Google-Konto an.", + "1. Abra Google AI Studio ↗ e inicie sesión con su cuenta de Google.", + "1. Apri Google AI Studio ↗ e accedi con il tuo account Google.", + "1. Abra o Google AI Studio ↗ e entre com sua conta Google.", + "1. Google AI Studioni oching ↗ va Google hisobingiz bilan kiring.", + "1. Google AI Studio ашып ↗, Google тіркелгіÑ�імен кіріңіз.", + ], + [ + "2. Press “Create API keyâ€� and copy the key.", + "2. Ð�ажмите «Create API key» и Ñ�копируйте ключ.", + "2. Cliquez sur « Create API key » et copiez la clé.", + "2. Klicken Sie auf „Create API key“ und kopieren Sie den Schlüssel.", + "2. Pulse «Create API key» y copie la clave.", + "2. Premi «Create API key» e copia la chiave.", + "2. Clique em “Create API keyâ€� e copie a chave.", + "2. “Create API keyâ€�ni bosing va kalitni nusxalang.", + "2. «Create API key» түймеÑ�ін баÑ�ып, кілтті көшіріңіз.", + ], + [ + "3. Paste the key here:", + "3. Ð’Ñ�тавьте ключ Ñ�юда:", + "3. Collez la clé ici :", + "3. Fügen Sie den Schlüssel hier ein:", + "3. Pegue la clave aquí:", + "3. Incolla la chiave qui:", + "3. Cole a chave aqui:", + "3. Kalitni shu yerga qo‘ying:", + "3. Кілтті оÑ�ында қойыңыз:", + ], + [ + "Free with a Google account, but Google may use the texts to train its models.", + "БеÑ�платно Ñ� аккаунтом Google, но Google может иÑ�пользовать текÑ�ты длÑ� обучениÑ� Ñ�воих моделей.", + "Gratuit avec un compte Google, mais Google peut utiliser les textes pour entraîner ses modèles.", + "Kostenlos mit einem Google-Konto, aber Google darf die Texte zum Training seiner Modelle nutzen.", + "Gratis con una cuenta de Google, pero Google puede usar los textos para entrenar sus modelos.", + "Gratis con un account Google, ma Google può usare i testi per addestrare i suoi modelli.", + "Grátis com uma conta Google, mas o Google pode usar os textos para treinar seus modelos.", + "Google hisobi bilan bepul, lekin Google matnlardan o‘z modellarini o‘qitishda foydalanishi mumkin.", + "Google тіркелгіÑ�імен тегін, бірақ Google мәтіндерді өз модельдерін оқытуға пайдалануы мүмкін.", + ], + [ + "1. Install Ollama from ollama.com ↗ and start it.", + "1. УÑ�тановите Ollama Ñ� Ñ�айта ollama.com ↗ и запуÑ�тите её.", + "1. Installez Ollama depuis ollama.com ↗ et lancez-le.", + "1. Installieren Sie Ollama von ollama.com ↗ und starten Sie es.", + "1. Instale Ollama desde ollama.com ↗ y ábralo.", + "1. Installa Ollama da ollama.com ↗ e avvialo.", + "1. Instale o Ollama em ollama.com ↗ e inicie-o.", + "1. Ollamani ollama.com saytidan o‘rnating ↗ va ishga tushiring.", + "1. Ollama-ны ollama.com ↗ Ñ�айтынан орнатып, Ñ–Ñ�ке қоÑ�ыңыз.", + ], + [ + "2. Download a model:", + "2. Скачайте модель:", + "2. Téléchargez un modèle :", + "2. Laden Sie ein Modell herunter:", + "2. Descargue un modelo:", + "2. Scarica un modello:", + "2. Baixe um modelo:", + "2. Modelni yuklab oling:", + "2. Модельді жүктеп алыңыз:", + ], + [ + "3. Press “Check and continueâ€�.", + "3. Ð�ажмите «Проверить и продолжить».", + "3. Cliquez sur « Vérifier et continuer ».", + "3. Klicken Sie auf „Prüfen und weiter“.", + "3. Pulse «Comprobar y continuar».", + "3. Premi «Verifica e continua».", + "3. Clique em “Verificar e continuarâ€�.", + "3. “Tekshirish va davom etishâ€�ni bosing.", + "3. «ТекÑ�еру және жалғаÑ�тыру» түймеÑ�ін баÑ�ыңыз.", + ], + [ + "1. Install LM Studio from lmstudio.ai ↗.", + "1. УÑ�тановите LM Studio Ñ� Ñ�айта lmstudio.ai ↗.", + "1. Installez LM Studio depuis lmstudio.ai ↗.", + "1. Installieren Sie LM Studio von lmstudio.ai ↗.", + "1. Instale LM Studio desde lmstudio.ai ↗.", + "1. Installa LM Studio da lmstudio.ai ↗.", + "1. Instale o LM Studio em lmstudio.ai ↗.", + "1. LM Studioni lmstudio.ai saytidan o‘rnating ↗.", + "1. LM Studio-ны lmstudio.ai ↗ Ñ�айтынан орнатыңыз.", + ], + [ + "2. Download a model in LM Studio.", + "2. Загрузите в LM Studio модель.", + "2. Téléchargez un modèle dans LM Studio.", + "2. Laden Sie in LM Studio ein Modell herunter.", + "2. Descargue un modelo en LM Studio.", + "2. Scarica un modello in LM Studio.", + "2. Baixe um modelo no LM Studio.", + "2. LM Studioda modelni yuklab oling.", + "2. LM Studio-да модель жүктеп алыңыз.", + ], + [ + "3. Turn on the server: the Developer tab › Start Server.", + "3. Включите Ñ�ервер: вкладка Developer › Start Server.", + "3. Démarrez le serveur : onglet Developer › Start Server.", + "3. Schalten Sie den Server ein: Reiter Developer › Start Server.", + "3. Active el servidor: pestaña Developer › Start Server.", + "3. Avvia il server: scheda Developer › Start Server.", + "3. Ative o servidor: aba Developer › Start Server.", + "3. Serverni yoqing: Developer yorlig‘i › Start Server.", + "3. Серверді қоÑ�ыңыз: Developer қойындыÑ�Ñ‹ › Start Server.", + ], + [ + "4. Press “Check and continueâ€�.", + "4. Ð�ажмите «Проверить и продолжить».", + "4. Cliquez sur « Vérifier et continuer ».", + "4. Klicken Sie auf „Prüfen und weiter“.", + "4. Pulse «Comprobar y continuar».", + "4. Premi «Verifica e continua».", + "4. Clique em “Verificar e continuarâ€�.", + "4. “Tekshirish va davom etishâ€�ni bosing.", + "4. «ТекÑ�еру және жалғаÑ�тыру» түймеÑ�ін баÑ�ыңыз.", + ], + [ + "Address:", + "Ð�дреÑ�:", + "Adresse :", + "Adresse:", + "Dirección:", + "Indirizzo:", + "Endereço:", + "Manzil:", + "Мекенжай:", + ], + [ + "The address of an OpenAI-compatible service, with /v1", + "Ð�дреÑ� Ñ�ервиÑ�а, Ñ�овмеÑ�тимого Ñ� OpenAI, вмеÑ�те Ñ� /v1", + "L’adresse d’un service compatible OpenAI, avec /v1", + "Die Adresse eines OpenAI-kompatiblen Dienstes, mit /v1", + "La dirección de un servicio compatible con OpenAI, con /v1", + "L’indirizzo di un servizio compatibile con OpenAI, con /v1", + "O endereço de um serviço compatível com OpenAI, com /v1", + "OpenAI bilan mos xizmat manzili, /v1 bilan", + "OpenAI-үйлеÑ�імді Ñ�ервиÑ�тің мекенжайы, /v1 қоÑ�а", + ], + [ + "Model:", + "Модель:", + "Modèle :", + "Modell:", + "Modelo:", + "Modello:", + "Modelo:", + "Model:", + "Модель:", + ], + [ + "Key (if needed):", + "Ключ (еÑ�ли нужен):", + "Clé (si nécessaire) :", + "Schlüssel (falls nötig):", + "Clave (si hace falta):", + "Chiave (se serve):", + "Chave (se necessária):", + "Kalit (kerak bo‘lsa):", + "Кілт (керек болÑ�а):", + ], + [ + "Key:", + "Ключ:", + "Clé :", + "Schlüssel:", + "Clave:", + "Chiave:", + "Chave:", + "Kalit:", + "Кілт:", + ], + [ + "Waiting for sign-in in the browser…", + "Ждём вход в браузере…", + "En attente de la connexion dans le navigateur…", + "Warten auf die Anmeldung im Browser…", + "Esperando el inicio de sesión en el navegador…", + "In attesa dell’accesso nel browser…", + "Aguardando o login no navegador…", + "Brauzerda kirish kutilmoqda…", + "Браузерде кіру күтілуде…", + ], + [ + "A page from OpenAI has opened in the browser. Sign in to your ChatGPT account and allow access for ChessPenguin. Then come back here — everything goes on by itself.", + "Ð’ браузере открылаÑ�ÑŒ Ñ�траница OpenAI. Войдите в аккаунт ChatGPT и разрешите доÑ�туп длÑ� ChessPenguin. Потом вернитеÑ�ÑŒ Ñ�юда — вÑ�Ñ‘ продолжитÑ�Ñ� Ñ�амо.", + "Une page d’OpenAI s’est ouverte dans le navigateur. Connectez-vous à votre compte ChatGPT et autorisez l’accès à ChessPenguin. Revenez ensuite ici — tout continue de soi-même.", + "Im Browser hat sich eine Seite von OpenAI geöffnet. Melden Sie sich bei Ihrem ChatGPT-Konto an und erlauben Sie ChessPenguin den Zugriff. Kommen Sie dann hierher zurück — alles geht von selbst weiter.", + "Se ha abierto una página de OpenAI en el navegador. Inicie sesión en su cuenta de ChatGPT y permita el acceso a ChessPenguin. Después vuelva aquí: todo sigue solo.", + "Nel browser si è aperta una pagina di OpenAI. Accedi al tuo account ChatGPT e consenti l’accesso a ChessPenguin. Poi torna qui: tutto prosegue da solo.", + "Uma página da OpenAI foi aberta no navegador. Entre na sua conta do ChatGPT e permita o acesso ao ChessPenguin. Depois volte aqui — tudo continua sozinho.", + "Brauzerda OpenAI sahifasi ochildi. ChatGPT hisobingizga kiring va ChessPenguinga ruxsat bering. So‘ng shu yerga qayting — hammasi o‘zi davom etadi.", + "Браузерде OpenAI беті ашылды. ChatGPT тіркелгіңізге кіріп, ChessPenguin-ге Ñ€Ò±Ò›Ñ�ат беріңіз. Содан кейін оÑ�ында оралыңыз — бәрі өзі жалғаÑ�ады.", + ], + [ + "The browser did not open? Copy the link", + "Браузер не открылÑ�Ñ�? Скопировать Ñ�Ñ�ылку", + "Le navigateur ne s’est pas ouvert ? Copier le lien", + "Der Browser hat sich nicht geöffnet? Link kopieren", + "¿No se abrió el navegador? Copiar el enlace", + "Il browser non si è aperto? Copia il link", + "O navegador não abriu? Copie o link", + "Brauzer ochilmadimi? Havolani nusxalash", + "Браузер ашылмады ма? Сілтемені көшіру", + ], + [ + "Copied. Paste the link into the browser's address bar.", + "Скопировано. Ð’Ñ�тавьте Ñ�Ñ�ылку в адреÑ�ную Ñ�троку браузера.", + "Copié. Collez le lien dans la barre d’adresse du navigateur.", + "Kopiert. Fügen Sie den Link in die Adresszeile des Browsers ein.", + "Copiado. Pegue el enlace en la barra de direcciones del navegador.", + "Copiato. Incolla il link nella barra degli indirizzi del browser.", + "Copiado. Cole o link na barra de endereços do navegador.", + "Nusxalandi. Havolani brauzerning manzil qatoriga qo‘ying.", + "Көшірілді. Сілтемені браузердің мекенжай жолына қойыңыз.", + ], + [ + "You can close this window: the sign-in goes on.", + "Это окно можно закрыть: вход продолжитÑ�Ñ�.", + "Vous pouvez fermer cette fenêtre : la connexion continue.", + "Sie können dieses Fenster schließen: Die Anmeldung läuft weiter.", + "Puede cerrar esta ventana: el inicio de sesión continúa.", + "Puoi chiudere questa finestra: l’accesso continua.", + "Você pode fechar esta janela: o login continua.", + "Bu oynani yopishingiz mumkin: kirish davom etadi.", + "Бұл терезені жаба беруге болады: кіру жалғаÑ�ады.", + ], + [ + "Comments in other languages are translated by a language model. Moves are not translated. The translation is not written to PGN files.", + "Комментарии партий на других Ñ�зыках переводит Ñ�зыковаÑ� модель. Ходы не переводÑ�Ñ‚Ñ�Ñ�. Ð’ файлы PGN перевод не запиÑ�ываетÑ�Ñ�.", + "Les commentaires dans d’autres langues sont traduits par un modèle de langage. Les coups ne sont pas traduits. La traduction n’est pas écrite dans les fichiers PGN.", + "Kommentare in anderen Sprachen übersetzt ein Sprachmodell. Züge werden nicht übersetzt. Die Übersetzung wird nicht in PGN-Dateien geschrieben.", + "Los comentarios en otros idiomas los traduce un modelo de lenguaje. Las jugadas no se traducen. La traducción no se escribe en los archivos PGN.", + "I commenti in altre lingue li traduce un modello linguistico. Le mosse non vengono tradotte. La traduzione non viene scritta nei file PGN.", + "Comentários em outros idiomas são traduzidos por um modelo de linguagem. Os lances não são traduzidos. A tradução não é gravada nos arquivos PGN.", + "Boshqa tillardagi izohlarni til modeli tarjima qiladi. Yurishlar tarjima qilinmaydi. Tarjima PGN fayllariga yozilmaydi.", + "БаÑ�қа тілдегі түÑ�ініктемелерді тілдік модель аударады. ЖүріÑ�тер аударылмайды. Ð�ударма PGN файлдарына жазылмайды.", + ], + [ + "Translate into:", + "Переводить на:", + "Traduire en :", + "Übersetzen in:", + "Traducir al:", + "Traduci in:", + "Traduzir para:", + "Qaysi tilga:", + "Ð�удару тілі:", + ], + [ + "When comments are in another language:", + "Когда комментарии на другом Ñ�зыке:", + "Quand les commentaires sont dans une autre langue :", + "Wenn Kommentare in einer anderen Sprache sind:", + "Cuando los comentarios están en otro idioma:", + "Quando i commenti sono in un’altra lingua:", + "Quando os comentários estão em outro idioma:", + "Izohlar boshqa tilda bo‘lsa:", + "ТүÑ�ініктемелер баÑ�қа тілде болÑ�а:", + ], + [ + "Translate at once", + "Переводить Ñ�разу", + "Traduire tout de suite", + "Sofort übersetzen", + "Traducir enseguida", + "Traduci subito", + "Traduzir na hora", + "Darhol tarjima qilish", + "Бірден аудару", + ], + [ + "Ask", + "Спрашивать", + "Demander", + "Fragen", + "Preguntar", + "Chiedi", + "Perguntar", + "So‘rash", + "Сұрау", + ], + [ + "Do nothing", + "Ð�ичего не делать", + "Ne rien faire", + "Nichts tun", + "No hacer nada", + "Non fare nulla", + "Não fazer nada", + "Hech narsa qilmaslik", + "Ештеңе Ñ–Ñ�темеу", + ], + [ + "How to translate", + "Как переводить", + "Comment traduire", + "Wie übersetzen", + "Cómo traducir", + "Come tradurre", + "Como traduzir", + "Qanday tarjima qilish", + "Қалай аудару", + ], + [ + "For a Plus or Pro subscription. Uses part of its limit.", + "ДлÑ� подпиÑ�ки Plus или Pro. РаÑ�ходует чаÑ�ть её лимита.", + "Pour un abonnement Plus ou Pro. Utilise une partie de sa limite.", + "Für ein Plus- oder Pro-Abo. Verbraucht einen Teil seines Kontingents.", + "Para una suscripción Plus o Pro. Consume parte de su límite.", + "Per un abbonamento Plus o Pro. Usa parte del suo limite.", + "Para assinatura Plus ou Pro. Usa parte do seu limite.", + "Plus yoki Pro obunasi uchun. Uning limitidan bir qismini sarflaydi.", + "Plus немеÑ�е Pro жазылымы үшін. Оның лимитінің бір бөлігін жұмÑ�айды.", + ], + [ + "API key", + "Ключ API", + "Clé API", + "API-Schlüssel", + "Clave API", + "Chiave API", + "Chave de API", + "API kaliti", + "API кілті", + ], + [ + "Comments may be sent to:", + "Разрешено отправлÑ�ть комментарии:", + "Les commentaires peuvent être envoyés à :", + "Kommentare dürfen gesendet werden an:", + "Se pueden enviar comentarios a:", + "I commenti possono essere inviati a:", + "Os comentários podem ser enviados para:", + "Izohlarni yuborish mumkin:", + "ТүÑ�ініктемелерді жіберуге Ñ€Ò±Ò›Ñ�ат:", + ], + [ + "Nowhere yet.", + "Пока никуда.", + "Nulle part pour l’instant.", + "Noch nirgendwohin.", + "A ningún sitio aún.", + "Ancora da nessuna parte.", + "Nenhum lugar ainda.", + "Hozircha hech qayerga.", + "Әзірге ешқайда.", + ], + [ + "Delete all saved translations?", + "Удалить вÑ�е Ñ�охранённые переводы?", + "Supprimer toutes les traductions enregistrées ?", + "Alle gespeicherten Übersetzungen löschen?", + "¿Eliminar todas las traducciones guardadas?", + "Eliminare tutte le traduzioni salvate?", + "Excluir todas as traduções salvas?", + "Barcha saqlangan tarjimalar o‘chirilsinmi?", + "Сақталған барлық аударманы жою керек пе?", + ], + [ + "Delete", + "Удалить", + "Supprimer", + "Löschen", + "Eliminar", + "Elimina", + "Excluir", + "O‘chirish", + "Жою", + ], + [ + "So that translated games open without the internet and without cost.", + "Чтобы переведённые партии открывалиÑ�ÑŒ без Ñ�ети и без раÑ�хода.", + "Pour que les parties traduites s’ouvrent sans internet et sans frais.", + "Damit übersetzte Partien ohne Internet und ohne Kosten öffnen.", + "Para que las partidas traducidas se abran sin internet y sin coste.", + "Così le partite tradotte si aprono senza internet e senza costi.", + "Para que partidas traduzidas abram sem internet e sem custo.", + "Tarjima qilingan partiyalar internetsiz va xarajatsiz ochilishi uchun.", + "Ð�ударылған партиÑ�лар интернетÑ�із және шығынÑ�ыз ашылуы үшін.", + ], + [ + "âš  The sign-in is no longer valid.", + "âš  Вход больше не дейÑ�твует.", + "âš  La connexion n’est plus valable.", + "âš  Die Anmeldung ist nicht mehr gültig.", + "âš  El inicio de sesión ya no es válido.", + "âš  L’accesso non è più valido.", + "âš  O login não é mais válido.", + "âš  Kirish endi amal qilmaydi.", + "âš  Кіру енді жарамÑ�ыз.", + ], + [ + "Sign out", + "Выйти", + "Se déconnecter", + "Abmelden", + "Cerrar sesión", + "Esci", + "Sair", + "Chiqish", + "Шығу", + ], + [ + "Manage access on the OpenAI site ↗", + "УправлÑ�ть доÑ�тупом на Ñ�айте OpenAI ↗", + "Gérer l’accès sur le site d’OpenAI ↗", + "Zugriff auf der OpenAI-Seite verwalten ↗", + "Gestionar el acceso en el sitio de OpenAI ↗", + "Gestisci l’accesso sul sito di OpenAI ↗", + "Gerenciar acesso no site da OpenAI ↗", + "OpenAI saytida ruxsatlarni boshqarish ↗", + "OpenAI Ñ�айтында Ñ€Ò±Ò›Ñ�атты баÑ�қару ↗", + ], + [ + "âš  You did not allow ChessPenguin to use the subscription's limit.", + "âš  Ð’Ñ‹ не разрешили ChessPenguin раÑ�ходовать лимит подпиÑ�ки.", + "âš  Vous n’avez pas autorisé ChessPenguin à utiliser la limite de l’abonnement.", + "âš  Sie haben ChessPenguin nicht erlaubt, das Abo-Kontingent zu nutzen.", + "âš  No ha permitido a ChessPenguin usar el límite de la suscripción.", + "âš  Non hai permesso a ChessPenguin di usare il limite dell’abbonamento.", + "âš  Você não permitiu que o ChessPenguin use o limite da assinatura.", + "âš  Siz ChessPenguinga obuna limitidan foydalanishga ruxsat bermadingiz.", + "âš  Сіз ChessPenguin-ге жазылым лимитін пайдалануға Ñ€Ò±Ò›Ñ�ат бермедіңіз.", + ], + [ + "Sign in again", + "Войти Ñ�нова", + "Se reconnecter", + "Erneut anmelden", + "Volver a iniciar sesión", + "Accedi di nuovo", + "Entrar de novo", + "Qayta kirish", + "Қайта кіру", + ], + [ + "âš  This account needs a Plus or Pro subscription.", + "âš  Этому аккаунту нужна подпиÑ�ка Plus или Pro.", + "âš  Ce compte a besoin d’un abonnement Plus ou Pro.", + "âš  Dieses Konto braucht ein Plus- oder Pro-Abo.", + "âš  Esta cuenta necesita una suscripción Plus o Pro.", + "âš  Questo account ha bisogno di un abbonamento Plus o Pro.", + "âš  Esta conta precisa de uma assinatura Plus ou Pro.", + "âš  Bu hisobga Plus yoki Pro obunasi kerak.", + "âš  Бұл тіркелгіге Plus немеÑ�е Pro жазылымы керек.", + ], + [ + "âš  The subscription's limit for ChessPenguin is used up.", + "âš  Лимит подпиÑ�ки длÑ� ChessPenguin иÑ�черпан.", + "âš  La limite de l’abonnement pour ChessPenguin est épuisée.", + "âš  Das Abo-Kontingent für ChessPenguin ist aufgebraucht.", + "âš  Se agotó el límite de la suscripción para ChessPenguin.", + "âš  Il limite dell’abbonamento per ChessPenguin è esaurito.", + "âš  O limite da assinatura para o ChessPenguin acabou.", + "âš  ChessPenguin uchun obuna limiti tugadi.", + "âš  ChessPenguin үшін жазылым лимиті тауÑ�ылды.", + ], + [ + "ChatGPT settings ↗", + "Ð�аÑ�тройки ChatGPT ↗", + "Paramètres de ChatGPT ↗", + "ChatGPT-Einstellungen ↗", + "Ajustes de ChatGPT ↗", + "Impostazioni di ChatGPT ↗", + "Configurações do ChatGPT ↗", + "ChatGPT sozlamalari ↗", + "ChatGPT баптаулары ↗", + ], + [ + "Check", + "Проверить", + "Vérifier", + "Prüfen", + "Comprobar", + "Verifica", + "Verificar", + "Tekshirish", + "ТекÑ�еру", + ], + [ + "Advanced", + "Дополнительно", + "Avancé", + "Erweitert", + "Avanzado", + "Avanzate", + "Avançado", + "Qo‘shimcha", + "ҚоÑ�ымша", + ], + [ + "Ollama — on this computer", + "Ollama — на Ñ�том компьютере", + "Ollama — sur cet ordinateur", + "Ollama — auf diesem Computer", + "Ollama: en este ordenador", + "Ollama — su questo computer", + "Ollama — neste computador", + "Ollama — shu kompyuterda", + "Ollama — оÑ�Ñ‹ компьютерде", + ], + [ + "LM Studio — on this computer", + "LM Studio — на Ñ�том компьютере", + "LM Studio — sur cet ordinateur", + "LM Studio — auf diesem Computer", + "LM Studio: en este ordenador", + "LM Studio — su questo computer", + "LM Studio — neste computador", + "LM Studio — shu kompyuterda", + "LM Studio — оÑ�Ñ‹ компьютерде", + ], + [ + "âš  The key was not accepted. Perhaps it was copied incompletely or deleted on the site.", + "âš  Ключ не подошёл. Возможно, он Ñ�копирован не полноÑ�тью или удалён на Ñ�айте.", + "âš  La clé n’a pas été acceptée. Elle a peut-être été copiée en partie ou supprimée sur le site.", + "âš  Der Schlüssel wurde nicht akzeptiert. Vielleicht wurde er unvollständig kopiert oder auf der Seite gelöscht.", + "âš  La clave no fue aceptada. Quizá se copió incompleta o se eliminó en el sitio.", + "âš  La chiave non è stata accettata. Forse è stata copiata incompleta o eliminata sul sito.", + "âš  A chave não foi aceita. Talvez tenha sido copiada incompleta ou excluída no site.", + "âš  Kalit qabul qilinmadi. Ehtimol, u to‘liq nusxalanmagan yoki saytda o‘chirilgan.", + "âš  Кілт жарамады. Мүмкін, ол толық көшірілмеген немеÑ�е Ñ�айтта жойылған.", + ], + [ + "âš  The service is overloaded. What is translated is saved.", + "âš  СервиÑ� перегружен. Уже переведённое Ñ�охранено.", + "âš  Le service est surchargé. Ce qui est traduit est enregistré.", + "âš  Der Dienst ist überlastet. Bereits Übersetztes ist gespeichert.", + "âš  El servicio está saturado. Lo ya traducido está guardado.", + "âš  Il servizio è sovraccarico. Ciò che è tradotto è salvato.", + "âš  O serviço está sobrecarregado. O que já foi traduzido está salvo.", + "âš  Xizmat haddan tashqari band. Tarjima qilinganlari saqlandi.", + "âš  СервиÑ� шамадан тыÑ� жүктелген. Ð�ударылғаны Ñ�ақталды.", + ], + [ + "âš  The ChatGPT subscription's limit for ChessPenguin is used up. When it comes back is shown in the ChatGPT settings.", + "âš  Лимит подпиÑ�ки ChatGPT длÑ� ChessPenguin иÑ�черпан. Когда он воÑ�Ñ�тановитÑ�Ñ�, видно в наÑ�тройках ChatGPT.", + "âš  La limite de l’abonnement ChatGPT pour ChessPenguin est épuisée. Le moment où elle revient est indiqué dans les paramètres de ChatGPT.", + "âš  Das ChatGPT-Abo-Kontingent für ChessPenguin ist aufgebraucht. Wann es zurückkommt, zeigen die ChatGPT-Einstellungen.", + "âš  Se agotó el límite de la suscripción a ChatGPT para ChessPenguin. Cuándo vuelve se ve en los ajustes de ChatGPT.", + "âš  Il limite dell’abbonamento ChatGPT per ChessPenguin è esaurito. Quando torna si vede nelle impostazioni di ChatGPT.", + "âš  O limite da assinatura do ChatGPT para o ChessPenguin acabou. Quando ele volta é mostrado nas configurações do ChatGPT.", + "âš  ChessPenguin uchun ChatGPT obuna limiti tugadi. Qachon tiklanishi ChatGPT sozlamalarida ko‘rsatilgan.", + "âš  ChessPenguin үшін ChatGPT жазылым лимиті тауÑ�ылды. Қашан қалпына келетіні ChatGPT баптауларында көрÑ�етілген.", + ], + [ + "âš  The ChatGPT sign-in is no longer valid. Sign in again.", + "âš  Вход в ChatGPT больше не дейÑ�твует. Войдите Ñ�нова.", + "âš  La connexion à ChatGPT n’est plus valable. Reconnectez-vous.", + "âš  Die ChatGPT-Anmeldung ist nicht mehr gültig. Melden Sie sich erneut an.", + "âš  El inicio de sesión en ChatGPT ya no es válido. Vuelva a iniciar sesión.", + "âš  L’accesso a ChatGPT non è più valido. Accedi di nuovo.", + "âš  O login no ChatGPT não é mais válido. Entre de novo.", + "âš  ChatGPTga kirish endi amal qilmaydi. Qayta kiring.", + "âš  ChatGPT-ге кіру енді жарамÑ�ыз. Қайта кіріңіз.", + ], + [ + "There are no models in Ollama. Download one with the command below.", + "Ð’ Ollama нет моделей. Скачайте модель командой ниже.", + "Ollama n’a aucun modèle. Téléchargez-en un avec la commande ci-dessous.", + "In Ollama gibt es keine Modelle. Laden Sie eines mit dem Befehl unten herunter.", + "Ollama no tiene modelos. Descargue uno con el comando de abajo.", + "In Ollama non ci sono modelli. Scaricane uno con il comando qui sotto.", + "Não há modelos no Ollama. Baixe um com o comando abaixo.", + "Ollamada modellar yo‘q. Quyidagi buyruq bilan model yuklab oling.", + "Ollama-да модель жоқ. Төмендегі командамен модель жүктеп алыңыз.", + ], + [ + "Choose how to translate", + "Выбрать, как переводить", + "Choisir comment traduire", + "Wählen, wie übersetzt wird", + "Elegir cómo traducir", + "Scegli come tradurre", + "Escolha como traduzir", + "Tarjima usulini tanlash", + "Ð�удару тәÑ�ілін таңдау", + ], + [ + "Translate", + "ПеревеÑ�ти", + "Traduire", + "Übersetzen", + "Traducir", + "Traduci", + "Traduzir", + "Tarjima qilish", + "Ð�удару", + ], + [ + "Don't offer", + "Ð�е предлагать", + "Ne plus proposer", + "Nicht mehr anbieten", + "No ofrecer", + "Non proporre", + "Não oferecer", + "Taklif qilmaslik", + "Ò°Ñ�ынбау", + ], + [ + "Never offer to translate comments. You can turn it back on in Settings › Translation.", + "Больше не предлагать перевод. Вернуть можно в Ð�аÑ�тройки › Перевод.", + "Ne plus proposer de traduire. Vous pouvez le réactiver dans Paramètres › Traduction.", + "Übersetzung nicht mehr anbieten. Wieder einschalten: Einstellungen › Übersetzung.", + "No volver a ofrecer la traducción. Se puede reactivar en Ajustes › Traducción.", + "Non proporre più la traduzione. Si può riattivare in Impostazioni › Traduzione.", + "Nunca oferecer tradução de comentários. Você pode reativar em Configurações › Tradução.", + "Izohlarni tarjima qilish hech qachon taklif qilinmasin. Qayta yoqish: Sozlamalar › Tarjima.", + "ТүÑ�ініктемелерді аударуды енді Ò±Ñ�ынбау. Қайта қоÑ�у: Баптаулар › Ð�ударма.", + ], + [ + "Hide for this game", + "Скрыть длÑ� Ñ�той партии", + "Masquer pour cette partie", + "Für diese Partie ausblenden", + "Ocultar para esta partida", + "Nascondi per questa partita", + "Ocultar nesta partida", + "Bu partiya uchun yashirish", + "Бұл партиÑ� үшін жаÑ�ыру", + ], + [ + "Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game.", + "Стрелки и круги: праваÑ� кнопка мыши на доÑ�ке — протÑ�ните или щёлкните. СохранÑ�ÑŽÑ‚Ñ�Ñ� в партии.", + "Flèches et cercles : faites glisser ou cliquez avec le bouton droit de la souris sur l’échiquier. Ils sont enregistrés dans la partie.", + "Pfeile und Kreise: mit der rechten Maustaste auf dem Brett ziehen oder klicken. Sie werden in der Partie gespeichert.", + "Flechas y círculos: arrastra o haz clic con el botón derecho del ratón en el tablero. Se guardan en la partida.", + "Frecce e cerchi: trascina o fai clic con il tasto destro del mouse sulla scacchiera. Vengono salvati nella partita.", + "Setas e círculos: arraste ou clique com o botão direito do mouse no tabuleiro. Eles são salvos na partida.", + "Strelkalar va doiralar: taxtada sichqonchaning o‘ng tugmasi bilan torting yoki bosing. Ular partiyada saqlanadi.", + "КөрÑ�еткілер мен шеңберлер: тақтада тышқанның оң жақ батырмаÑ�ымен Ñ�үйреңіз немеÑ�е баÑ�ыңыз. Олар партиÑ�да Ñ�ақталады.", + ], + [ + "No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes.", + "Без клавиши — зелёный, Shift — краÑ�ный, Alt — Ñ�иний, Shift+Alt — жёлтый. Та же фигура ещё раз — убрать. Ctrl+Z — отменить.", + "Sans touche — vert, Maj — rouge, Alt — bleu, Maj+Alt — jaune. Tracez la même forme à nouveau pour la retirer. Ctrl+Z annule.", + "Ohne Taste — grün, Umschalt — rot, Alt — blau, Umschalt+Alt — gelb. Dieselbe Form noch einmal zeichnen entfernt sie. Strg+Z macht rückgängig.", + "Sin tecla — verde, Mayús — rojo, Alt — azul, Mayús+Alt — amarillo. Dibuja la misma otra vez para quitarla. Ctrl+Z deshace.", + "Senza tasto — verde, Maiusc — rosso, Alt — blu, Maiusc+Alt — giallo. Disegna di nuovo la stessa per toglierla. Ctrl+Z annulla.", + "Sem tecla — verde, Shift — vermelho, Alt — azul, Shift+Alt — amarelo. Desenhe a mesma de novo para removê-la. Ctrl+Z desfaz.", + "Tugmasiz — yashil, Shift — qizil, Alt — ko‘k, Shift+Alt — sariq. Xuddi shuni yana chizsangiz, olib tashlanadi. Ctrl+Z — bekor qilish.", + "ПернеÑ�із — жаÑ�ыл, Shift — қызыл, Alt — көк, Shift+Alt — Ñ�ары. Сол пішінді қайта Ñ�алÑ�аңыз — алынып таÑ�талады. Ctrl+Z — болдырмау.", + ], + [ + "Don't show again", + "Больше не показывать", + "Ne plus afficher", + "Nicht mehr anzeigen", + "No volver a mostrar", + "Non mostrare più", + "Não mostrar novamente", + "Boshqa ko‘rsatilmasin", + "Енді көрÑ�етпеу", + ], + [ + "Arrows: {a} · circles: {c} — shown on the board at this move", + "Стрелки: {a} · круги: {c} — видны на доÑ�ке на Ñ�том ходу", + "Flèches : {a} · cercles : {c} — affichés sur l’échiquier à ce coup", + "Pfeile: {a} · Kreise: {c} — bei diesem Zug auf dem Brett zu sehen", + "Flechas: {a} · círculos: {c} — se ven en el tablero en esta jugada", + "Frecce: {a} · cerchi: {c} — visibili sulla scacchiera a questa mossa", + "Setas: {a} · círculos: {c} — aparecem no tabuleiro neste lance", + "Strelkalar: {a} · doiralar: {c} — shu yurishda taxtada ko‘rinadi", + "КөрÑ�еткілер: {a} · шеңберлер: {c} — оÑ�Ñ‹ жүріÑ�те тақтада көрінеді", + ], + [ + "Arrows: {a} — shown on the board at this move", + "Стрелки: {a} — видны на доÑ�ке на Ñ�том ходу", + "Flèches : {a} — affichées sur l’échiquier à ce coup", + "Pfeile: {a} — bei diesem Zug auf dem Brett zu sehen", + "Flechas: {a} — se ven en el tablero en esta jugada", + "Frecce: {a} — visibili sulla scacchiera a questa mossa", + "Setas: {a} — aparecem no tabuleiro neste lance", + "Strelkalar: {a} — shu yurishda taxtada ko‘rinadi", + "КөрÑ�еткілер: {a} — оÑ�Ñ‹ жүріÑ�те тақтада көрінеді", + ], + [ + "Circles: {c} — shown on the board at this move", + "Круги: {c} — видны на доÑ�ке на Ñ�том ходу", + "Cercles : {c} — affichés sur l’échiquier à ce coup", + "Kreise: {c} — bei diesem Zug auf dem Brett zu sehen", + "Círculos: {c} — se ven en el tablero en esta jugada", + "Cerchi: {c} — visibili sulla scacchiera a questa mossa", + "Círculos: {c} — aparecem no tabuleiro neste lance", + "Doiralar: {c} — shu yurishda taxtada ko‘rinadi", + "Шеңберлер: {c} — оÑ�Ñ‹ жүріÑ�те тақтада көрінеді", + ], + [ + "Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]).", + "Стрелки и круги — праваÑ� кнопка мыши на доÑ�ке; Shift — краÑ�ный, Alt — Ñ�иний, Shift+Alt — жёлтый. СохранÑ�ÑŽÑ‚Ñ�Ñ� в комментарии хода ([%cal], [%csl]).", + "Flèches et cercles : bouton droit de la souris sur l’échiquier ; Maj — rouge, Alt — bleu, Maj+Alt — jaune. Enregistrés dans le commentaire du coup ([%cal], [%csl]).", + "Pfeile und Kreise: rechte Maustaste auf dem Brett; Umschalt — rot, Alt — blau, Umschalt+Alt — gelb. Gespeichert im Kommentar des Zuges ([%cal], [%csl]).", + "Flechas y círculos: botón derecho del ratón en el tablero; Mayús — rojo, Alt — azul, Mayús+Alt — amarillo. Se guardan en el comentario de la jugada ([%cal], [%csl]).", + "Frecce e cerchi: tasto destro del mouse sulla scacchiera; Maiusc — rosso, Alt — blu, Maiusc+Alt — giallo. Salvati nel commento della mossa ([%cal], [%csl]).", + "Setas e círculos: botão direito do mouse no tabuleiro; Shift — vermelho, Alt — azul, Shift+Alt — amarelo. Salvos no comentário do lance ([%cal], [%csl]).", + "Strelkalar va doiralar — taxtada sichqonchaning o‘ng tugmasi; Shift — qizil, Alt — ko‘k, Shift+Alt — sariq. Yurish izohida saqlanadi ([%cal], [%csl]).", + "КөрÑ�еткілер мен шеңберлер — тақтада тышқанның оң жақ батырмаÑ�Ñ‹; Shift — қызыл, Alt — көк, Shift+Alt — Ñ�ары. ЖүріÑ� түÑ�ініктемеÑ�інде Ñ�ақталады ([%cal], [%csl]).", + ], + [ + "The model is loading into memory — this can take up to a minute…", + "Модель загружаетÑ�Ñ� в памÑ�ть — Ñ�то бывает до минуты…", + "Le modèle se charge en mémoire — cela peut prendre jusqu’à une minute…", + "Das Modell wird in den Speicher geladen — das kann bis zu einer Minute dauern…", + "El modelo se está cargando en memoria: puede tardar hasta un minuto…", + "Il modello si sta caricando in memoria: può volerci fino a un minuto…", + "O modelo está sendo carregado na memória — isso pode levar até um minuto…", + "Model xotiraga yuklanmoqda — bu bir daqiqagacha cho‘zilishi mumkin…", + "Модель жадқа жүктелуде — бұл бір минутқа дейін Ñ�озылуы мүмкін…", + ], + [ + "Saved translation shown — nothing was sent. The translation is not written to the PGN file.", + "Показан Ñ�охранённый перевод — ничего не отправлÑ�лоÑ�ÑŒ. Ð’ файл PGN перевод не запиÑ�ываетÑ�Ñ�.", + "Traduction enregistrée affichée — rien n’a été envoyé. La traduction n’est pas écrite dans le fichier PGN.", + "Gespeicherte Übersetzung — nichts wurde gesendet. Die Übersetzung wird nicht in die PGN-Datei geschrieben.", + "Se muestra la traducción guardada: no se envió nada. La traducción no se escribe en el archivo PGN.", + "Mostrata la traduzione salvata: non è stato inviato nulla. La traduzione non viene scritta nel file PGN.", + "Tradução salva exibida — nada foi enviado. A tradução não é gravada no arquivo PGN.", + "Saqlangan tarjima ko‘rsatildi — hech narsa yuborilmadi. Tarjima PGN fayliga yozilmaydi.", + "Сақталған аударма көрÑ�етілді — ештеңе жіберілмеді. Ð�ударма PGN файлына жазылмайды.", + ], + [ + "Continue", + "Продолжить", + "Continuer", + "Weiter", + "Continuar", + "Continua", + "Continuar", + "Davom etish", + "ЖалғаÑ�тыру", + ], + [ + "Translation settings", + "Ð�аÑ�тройки перевода", + "Paramètres de traduction", + "Übersetzungseinstellungen", + "Ajustes de traducción", + "Impostazioni di traduzione", + "Configurações de tradução", + "Tarjima sozlamalari", + "Ð�ударма баптаулары", + ], + [ + "Copy the command", + "Копировать команду", + "Copier la commande", + "Befehl kopieren", + "Copiar el comando", + "Copia il comando", + "Copiar o comando", + "Buyruqni nusxalash", + "Команданы көшіру", + ], + [ + "Open the site ↗", + "Открыть Ñ�айт ↗", + "Ouvrir le site ↗", + "Website öffnen ↗", + "Abrir el sitio ↗", + "Apri il sito ↗", + "Abrir o site ↗", + "Saytni ochish ↗", + "Сайтты ашу ↗", + ], + [ + "Another way", + "Другой Ñ�поÑ�об", + "Autre moyen", + "Anderer Weg", + "Otra forma", + "Un altro modo", + "Outro jeito", + "Boshqa usul", + "БаÑ�қа тәÑ�іл", + ], + [ + "Use an API key", + "ИÑ�пользовать ключ API", + "Utiliser une clé API", + "Einen API-Schlüssel nutzen", + "Usar una clave API", + "Usa una chiave API", + "Usar uma chave de API", + "API kalitidan foydalanish", + "API кілтін қолдану", + ], + [ + "Original", + "Оригинал", + "Original", + "Original", + "Original", + "Originale", + "Original", + "Asli", + "ТүпнұÑ�қа", + ], + [ + "Send comments to {service}?", + "ОтправлÑ�ть комментарии в {service}?", + "Envoyer les commentaires à {service} ?", + "Kommentare an {service} senden?", + "¿Enviar comentarios a {service}?", + "Inviare i commenti a {service}?", + "Enviar comentários para {service}?", + "Izohlar {service} xizmatiga yuborilsinmi?", + "ТүÑ�ініктемелер {service} Ñ�ервиÑ�іне жіберілÑ�ін бе?", + ], + [ + "To translate, these will be sent to {service} ({host}):", + "ДлÑ� перевода в {service} ({host}) будут отправлены:", + "Pour traduire, ceci sera envoyé à {service} ({host}) :", + "Zum Übersetzen wird an {service} ({host}) gesendet:", + "Para traducir, se enviará a {service} ({host}):", + "Per tradurre verranno inviati a {service} ({host}):", + "Para traduzir, isto será enviado para {service} ({host}):", + "Tarjima uchun {service} ({host}) xizmatiga yuboriladi:", + "Ð�удару үшін {service} ({host}) Ñ�ервиÑ�іне мыналар жіберіледі:", + ], + [ + "• comment texts — {n} in this game, about {k} thousand characters;", + "• текÑ�ты комментариев — в Ñ�той партии {n}, ≈ {k} тыÑ�. Ñ�имволов;", + "• les textes des commentaires — {n} dans cette partie, environ {k} milliers de caractères ;", + "• die Kommentartexte — {n} in dieser Partie, etwa {k} Tausend Zeichen;", + "• los textos de los comentarios: {n} en esta partida, unos {k} mil caracteres;", + "• i testi dei commenti: {n} in questa partita, circa {k} mila caratteri;", + "• textos dos comentários — {n} nesta partida, cerca de {k} mil caracteres;", + "• izoh matnlari — bu partiyada {n} ta, taxminan {k} ming belgi;", + "• түÑ�ініктеме мәтіндері — оÑ�Ñ‹ партиÑ�да {n}, шамамен {k} мың таңба;", + ], + [ + "How {service} stores data: privacy policy ↗", + "Как {service} хранит данные: политика конфиденциальноÑ�ти ↗", + "Comment {service} conserve les données : politique de confidentialité ↗", + "Wie {service} Daten speichert: Datenschutzerklärung ↗", + "Cómo guarda {service} los datos: política de privacidad ↗", + "Come {service} conserva i dati: informativa sulla privacy ↗", + "Como {service} guarda os dados: política de privacidade ↗", + "{service} maʼlumotlarni qanday saqlaydi: maxfiylik siyosati ↗", + "{service} деректерді қалай Ñ�ақтайды: құпиÑ�лық Ñ�аÑ�Ñ�аты ↗", + ], + [ + "✔ Works: “{sample}â€� → “{result}â€�", + "✔ Работает: «{sample}» → «{result}»", + "✔ Fonctionne : « {sample} » → « {result} »", + "✔ Funktioniert: „{sample}“ → „{result}“", + "✔ Funciona: «{sample}» → «{result}»", + "✔ Funziona: «{sample}» → «{result}»", + "✔ Funciona: “{sample}â€� → “{result}â€�", + "✔ Ishlaydi: “{sample}â€� → “{result}â€�", + "✔ ЖұмыÑ� Ñ–Ñ�тейді: «{sample}» → «{result}»", + ], + [ + "As the interface ({lang})", + "Как в интерфейÑ�е ({lang})", + "Comme l’interface ({lang})", + "Wie die Oberfläche ({lang})", + "Como la interfaz ({lang})", + "Come l’interfaccia ({lang})", + "Como a interface ({lang})", + "Interfeysdagidek ({lang})", + "ИнтерфейÑ�тегідей ({lang})", + ], + [ + "Stop sending comments to {service}", + "Больше не отправлÑ�ть комментарии в {service}", + "Ne plus envoyer de commentaires à {service}", + "Keine Kommentare mehr an {service} senden", + "Dejar de enviar comentarios a {service}", + "Non inviare più commenti a {service}", + "Parar de enviar comentários para {service}", + "Izohlarni {service} xizmatiga boshqa yubormaslik", + "ТүÑ�ініктемелерді {service} Ñ�ервиÑ�іне енді жібермеу", + ], + [ + "Saved translations: {size}", + "Сохранённые переводы: {size}", + "Traductions enregistrées : {size}", + "Gespeicherte Übersetzungen: {size}", + "Traducciones guardadas: {size}", + "Traduzioni salvate: {size}", + "Traduções salvas: {size}", + "Saqlangan tarjimalar: {size}", + "Сақталған аудармалар: {size}", + ], + [ + "You are signed in: {account}", + "Ð’Ñ‹ вошли: {account}", + "Vous êtes connecté : {account}", + "Sie sind angemeldet: {account}", + "Ha iniciado sesión: {account}", + "Hai effettuato l’accesso: {account}", + "Você está conectado: {account}", + "Siz kirdingiz: {account}", + "Сіз кірдіңіз: {account}", + ], + [ + "✔ Works, model {model}", + "✔ Работает, модель {model}", + "✔ Fonctionne, modèle {model}", + "✔ Funktioniert, Modell {model}", + "✔ Funciona, modelo {model}", + "✔ Funziona, modello {model}", + "✔ Funciona, modelo {model}", + "✔ Ishlaydi, model {model}", + "✔ ЖұмыÑ� Ñ–Ñ�тейді, модель {model}", + ], + [ + "Get a key on the {service} website ↗", + "Получить ключ на Ñ�айте {service} ↗", + "Obtenir une clé sur le site {service} ↗", + "Schlüssel auf der Website von {service} holen ↗", + "Obtener una clave en el sitio de {service} ↗", + "Ottieni una chiave sul sito di {service} ↗", + "Obter uma chave no site do {service} ↗", + "{service} saytida kalit olish ↗", + "Кілтті {service} Ñ�айтынан алу ↗", + ], + [ + "âš  The {service} account has run out of money. Top up the balance on the site.", + "âš  Ð�а Ñ�чёте {service} закончилиÑ�ÑŒ деньги. Пополните баланÑ� на Ñ�айте.", + "âš  Le compte {service} n’a plus de crédit. Rechargez le solde sur le site.", + "âš  Das {service}-Konto hat kein Guthaben mehr. Laden Sie es auf der Website auf.", + "âš  La cuenta de {service} se quedó sin saldo. Recárguela en el sitio.", + "âš  L’account {service} ha finito il credito. Ricarica il saldo sul sito.", + "âš  A conta do {service} ficou sem saldo. Adicione saldo no site.", + "âš  {service} hisobida mablag‘ tugadi. Saytda balansni to‘ldiring.", + "âš  {service} шотында ақша тауÑ�ылды. Сайтта баланÑ�ты толтырыңыз.", + ], + [ + "No connection to {service}. We will translate when the connection is back.", + "Ð�ет Ñ�вÑ�зи Ñ� {service}. Переведём, когда Ñ�вÑ�зь поÑ�витÑ�Ñ�.", + "Pas de connexion à {service}. Nous traduirons quand elle reviendra.", + "Keine Verbindung zu {service}. Wir übersetzen, sobald sie wieder da ist.", + "Sin conexión con {service}. Traduciremos cuando vuelva.", + "Nessuna connessione a {service}. Tradurremo quando tornerà.", + "Sem conexão com {service}. Vamos traduzir quando a conexão voltar.", + "{service} bilan aloqa yo‘q. Aloqa tiklanganda tarjima qilamiz.", + "{service} Ñ�ервиÑ�імен байланыÑ� жоқ. БайланыÑ� қалпына келгенде аударамыз.", + ], + [ + "âš  {service} does not answer. Start {service} and press “Retryâ€�.", + "âš  {service} не отвечает. ЗапуÑ�тите {service} и нажмите «Повторить».", + "âš  {service} ne répond pas. Lancez {service} et cliquez sur « Réessayer ».", + "âš  {service} antwortet nicht. Starten Sie {service} und klicken Sie auf „Erneut versuchen“.", + "âš  {service} no responde. Abra {service} y pulse «Reintentar».", + "âš  {service} non risponde. Avvia {service} e premi «Riprova».", + "âš  {service} não responde. Inicie o {service} e clique em “Tentar de novoâ€�.", + "âš  {service} javob bermayapti. {service}ni ishga tushiring va “Qayta urinishâ€�ni bosing.", + "âš  {service} жауап бермейді. {service} Ñ–Ñ�ке қоÑ�ып, «Қайталау» түймеÑ�ін баÑ�ыңыз.", + ], + [ + "âš  Ollama has no model {model}. Download it with the command: ollama pull {model}", + "âš  Ð’ Ollama нет модели {model}. Скачайте её командой: ollama pull {model}", + "âš  Ollama n’a pas le modèle {model}. Téléchargez-le avec la commande : ollama pull {model}", + "âš  Ollama hat kein Modell {model}. Laden Sie es mit dem Befehl herunter: ollama pull {model}", + "âš  Ollama no tiene el modelo {model}. Descárguelo con el comando: ollama pull {model}", + "âš  Ollama non ha il modello {model}. Scaricalo con il comando: ollama pull {model}", + "âš  O Ollama não tem o modelo {model}. Baixe-o com o comando: ollama pull {model}", + "âš  Ollamada {model} modeli yo‘q. Uni buyruq bilan yuklab oling: ollama pull {model}", + "âš  Ollama-да {model} моделі жоқ. Оны мына командамен жүктеп алыңыз: ollama pull {model}", + ], + [ + "âš  {service} has no model {model}. Choose another one in the translation settings.", + "âš  У {service} нет модели {model}. Выберите другую в наÑ�тройках перевода.", + "âš  {service} n’a pas le modèle {model}. Choisissez-en un autre dans les paramètres de traduction.", + "âš  {service} hat kein Modell {model}. Wählen Sie in den Übersetzungseinstellungen ein anderes.", + "âš  {service} no tiene el modelo {model}. Elija otro en los ajustes de traducción.", + "âš  {service} non ha il modello {model}. Scegline un altro nelle impostazioni di traduzione.", + "âš  {service} não tem o modelo {model}. Escolha outro nas configurações de tradução.", + "âš  {service}da {model} modeli yo‘q. Tarjima sozlamalarida boshqasini tanlang.", + "âš  {service} Ñ�ервиÑ�інде {model} моделі жоқ. Ð�ударма баптауларында баÑ�қаÑ�ын таңдаңыз.", + ], + [ + "âš  The service answered with an error ({code}).", + "âš  СервиÑ� ответил ошибкой ({code}).", + "âš  Le service a répondu par une erreur ({code}).", + "âš  Der Dienst antwortete mit einem Fehler ({code}).", + "âš  El servicio respondió con un error ({code}).", + "âš  Il servizio ha risposto con un errore ({code}).", + "âš  O serviço respondeu com um erro ({code}).", + "âš  Xizmat xato bilan javob berdi ({code}).", + "âš  СервиÑ� қатемен жауап берді ({code}).", + ], + [ + "Many comments in another language ({lang}), about {k} thousand characters", + "Много комментариев на другом Ñ�зыке ({lang}), ≈ {k} тыÑ�. Ñ�имволов", + "Beaucoup de commentaires dans une autre langue ({lang}), environ {k} milliers de caractères", + "Viele Kommentare in einer anderen Sprache ({lang}), etwa {k} Tausend Zeichen", + "Muchos comentarios en otro idioma ({lang}), unos {k} mil caracteres", + "Molti commenti in un’altra lingua ({lang}), circa {k} mila caratteri", + "Muitos comentários em outro idioma ({lang}), cerca de {k} mil caracteres", + "Boshqa tildagi ({lang}) izohlar ko‘p, taxminan {k} ming belgi", + "БаÑ�қа тілде ({lang}) түÑ�ініктеме көп, шамамен {k} мың таңба", + ], + [ + "Comments in another language ({lang})", + "Комментарии на другом Ñ�зыке ({lang})", + "Commentaires dans une autre langue ({lang})", + "Kommentare in einer anderen Sprache ({lang})", + "Comentarios en otro idioma ({lang})", + "Commenti in un’altra lingua ({lang})", + "Comentários em outro idioma ({lang})", + "Boshqa tildagi izohlar ({lang})", + "БаÑ�қа тілдегі түÑ�ініктемелер ({lang})", + ], + [ + "Translate with {service}", + "ПеревеÑ�ти через {service}", + "Traduire avec {service}", + "Mit {service} übersetzen", + "Traducir con {service}", + "Traduci con {service}", + "Traduzir com {service}", + "{service} orqali tarjima qilish", + "{service} арқылы аудару", + ], + [ + "The service asks to wait… {s} s", + "СервиÑ� проÑ�ит подождать… {s} Ñ�", + "Le service demande d’attendre… {s} s", + "Der Dienst bittet zu warten… {s} s", + "El servicio pide esperar… {s} s", + "Il servizio chiede di attendere… {s} s", + "O serviço pede para aguardar… {s} s", + "Xizmat kutishni so‘rayapti… {s} s", + "СервиÑ� күтуді Ñ�ұрайды… {s} Ñ�", + ], + [ + "Translating… {n} of {total}", + "Перевод… {n} из {total}", + "Traduction… {n} sur {total}", + "Übersetzung… {n} von {total}", + "Traduciendo… {n} de {total}", + "Traduzione… {n} di {total}", + "Traduzindo… {n} de {total}", + "Tarjima qilinmoqda… {n} / {total}", + "Ð�ударылуда… {n} / {total}", + ], + [ + "Translated: {n} of {total}. Sent now: about {k} thousand characters. The translation is not written to the PGN file.", + "Переведено: {n} из {total}. Отправлено Ñ�ейчаÑ�: ≈ {k} тыÑ�. Ñ�имволов. Ð’ файл PGN перевод не запиÑ�ываетÑ�Ñ�.", + "Traduits : {n} sur {total}. Envoyé : environ {k} milliers de caractères. La traduction n’est pas écrite dans le fichier PGN.", + "Übersetzt: {n} von {total}. Gesendet: etwa {k} Tausend Zeichen. Die Übersetzung wird nicht in die PGN-Datei geschrieben.", + "Traducidos: {n} de {total}. Enviado: unos {k} mil caracteres. La traducción no se escribe en el archivo PGN.", + "Tradotti: {n} di {total}. Inviati: circa {k} mila caratteri. La traduzione non viene scritta nel file PGN.", + "Traduzidos: {n} de {total}. Enviados agora: cerca de {k} mil caracteres. A tradução não é gravada no arquivo PGN.", + "Tarjima qilindi: {n} / {total}. Hozir yuborildi: taxminan {k} ming belgi. Tarjima PGN fayliga yozilmaydi.", + "Ð�ударылды: {n} / {total}. Қазір жіберілді: шамамен {k} мың таңба. Ð�ударма PGN файлына жазылмайды.", + ], + [ + "Machine translation ({service})", + "Машинный перевод ({service})", + "Traduction automatique ({service})", + "Maschinelle Übersetzung ({service})", + "Traducción automática ({service})", + "Traduzione automatica ({service})", + "Tradução automática ({service})", + "Mashina tarjimasi ({service})", + "Машиналық аударма ({service})", + ], + [ + "Translated: {n} of {total}, failed: {bad}", + "Переведено: {n} из {total}, не удалоÑ�ÑŒ: {bad}", + "Traduits : {n} sur {total}, échecs : {bad}", + "Übersetzt: {n} von {total}, fehlgeschlagen: {bad}", + "Traducidos: {n} de {total}, fallidos: {bad}", + "Tradotti: {n} di {total}, non riusciti: {bad}", + "Traduzidos: {n} de {total}, falharam: {bad}", + "Tarjima qilindi: {n} / {total}, bo‘lmadi: {bad}", + "Ð�ударылды: {n} / {total}, Ñ�әтÑ�із: {bad}", + ], + [ + "Translated: {n} of {total}", + "Переведено: {n} из {total}", + "Traduits : {n} sur {total}", + "Übersetzt: {n} von {total}", + "Traducidos: {n} de {total}", + "Tradotti: {n} di {total}", + "Traduzidos: {n} de {total}", + "Tarjima qilindi: {n} / {total}", + "Ð�ударылды: {n} / {total}", + ], + [ + "✔ You are signed in to ChatGPT", + "✔ Ð’Ñ‹ вошли в ChatGPT", + "✔ Vous êtes connecté à ChatGPT", + "✔ Sie sind bei ChatGPT angemeldet", + "✔ Ha iniciado sesión en ChatGPT", + "✔ Hai effettuato l’accesso a ChatGPT", + "✔ Você entrou no ChatGPT", + "✔ Siz ChatGPTga kirdingiz", + "✔ Сіз ChatGPT-ге кірдіңіз", + ], + [ + "Go back to ChessPenguin — the translation goes on there. You can close this tab.", + "ВернитеÑ�ÑŒ в ChessPenguin — перевод продолжитÑ�Ñ� там. Эту вкладку можно закрыть.", + "Revenez à ChessPenguin — la traduction continue là-bas. Vous pouvez fermer cet onglet.", + "Gehen Sie zurück zu ChessPenguin — dort geht die Übersetzung weiter. Sie können diesen Tab schließen.", + "Vuelva a ChessPenguin: la traducción continúa allí. Puede cerrar esta pestaña.", + "Torna a ChessPenguin: la traduzione prosegue lì. Puoi chiudere questa scheda.", + "Volte ao ChessPenguin — a tradução continua lá. Você pode fechar esta aba.", + "ChessPenguinga qayting — tarjima o‘sha yerda davom etadi. Bu varaqni yopishingiz mumkin.", + "ChessPenguin-ге оралыңыз — аударма Ñ�онда жалғаÑ�ады. Бұл қойындыны жаба беруге болады.", + ], + [ + "Sign-in could not be finished", + "Ð�е удалоÑ�ÑŒ завершить вход", + "La connexion n’a pas pu aboutir", + "Die Anmeldung konnte nicht abgeschlossen werden", + "No se pudo completar el inicio de sesión", + "Non è stato possibile completare l’accesso", + "Não foi possível concluir o login", + "Kirishni yakunlab bo‘lmadi", + "Кіруді аÑ�қтау мүмкін болмады", + ], + [ + "Go back to ChessPenguin and try again.", + "ВернитеÑ�ÑŒ в ChessPenguin и попробуйте ещё раз.", + "Revenez à ChessPenguin et réessayez.", + "Gehen Sie zurück zu ChessPenguin und versuchen Sie es erneut.", + "Vuelva a ChessPenguin e inténtelo de nuevo.", + "Torna a ChessPenguin e riprova.", + "Volte ao ChessPenguin e tente de novo.", + "ChessPenguinga qayting va yana urinib ko‘ring.", + "ChessPenguin-ге оралып, қайталап көріңіз.", + ], + [ + "English", + "английÑ�кий", + "anglais", + "Englisch", + "inglés", + "inglese", + "Inglês", + "Inglizcha", + "ағылшын", + ], + [ + "Russian", + "руÑ�Ñ�кий", + "russe", + "Russisch", + "ruso", + "russo", + "Russo", + "Ruscha", + "орыÑ�", + ], + [ + "German", + "немецкий", + "allemand", + "Deutsch", + "alemán", + "tedesco", + "Alemão", + "Nemischa", + "неміÑ�", + ], + [ + "French", + "французÑ�кий", + "français", + "Französisch", + "francés", + "francese", + "Francês", + "Fransuzcha", + "француз", + ], + [ + "Spanish", + "иÑ�панÑ�кий", + "espagnol", + "Spanisch", + "español", + "spagnolo", + "Espanhol", + "Ispancha", + "иÑ�пан", + ], + [ + "Italian", + "итальÑ�нÑ�кий", + "italien", + "Italienisch", + "italiano", + "italiano", + "Italiano", + "Italyancha", + "итальÑ�н", + ], + [ + "Portuguese", + "португальÑ�кий", + "portugais", + "Portugiesisch", + "portugués", + "portoghese", + "Português", + "Portugalcha", + "португал", + ], + [ + "Dutch", + "нидерландÑ�кий", + "néerlandais", + "Niederländisch", + "neerlandés", + "olandese", + "Holandês", + "Niderlandcha", + "нидерланд", + ], + [ + "Ukrainian", + "украинÑ�кий", + "ukrainien", + "Ukrainisch", + "ucraniano", + "ucraino", + "Ucraniano", + "Ukraincha", + "украин", + ], + [ + "Belarusian", + "белоруÑ�Ñ�кий", + "biélorusse", + "Belarussisch", + "bielorruso", + "bielorusso", + "Bielorrusso", + "Belaruscha", + "беларуÑ�ÑŒ", + ], + [ + "Polish", + "польÑ�кий", + "polonais", + "Polnisch", + "polaco", + "polacco", + "Polonês", + "Polyakcha", + "полÑ�к", + ], + [ + "Czech", + "чешÑ�кий", + "tchèque", + "Tschechisch", + "checo", + "ceco", + "Tcheco", + "Chexcha", + "чех", + ], + [ + "Slovak", + "Ñ�ловацкий", + "slovaque", + "Slowakisch", + "eslovaco", + "slovacco", + "Eslovaco", + "Slovakcha", + "Ñ�ловак", + ], + [ + "Slovene", + "Ñ�ловенÑ�кий", + "slovène", + "Slowenisch", + "esloveno", + "sloveno", + "Esloveno", + "Slovencha", + "Ñ�ловен", + ], + [ + "Croatian", + "хорватÑ�кий", + "croate", + "Kroatisch", + "croata", + "croato", + "Croata", + "Xorvatcha", + "хорват", + ], + [ + "Serbian", + "Ñ�ербÑ�кий", + "serbe", + "Serbisch", + "serbio", + "serbo", + "Sérvio", + "Serbcha", + "Ñ�ерб", + ], + [ + "Bulgarian", + "болгарÑ�кий", + "bulgare", + "Bulgarisch", + "búlgaro", + "bulgaro", + "Búlgaro", + "Bolgarcha", + "болгар", + ], + [ + "Macedonian", + "македонÑ�кий", + "macédonien", + "Mazedonisch", + "macedonio", + "macedone", + "Macedônio", + "Makedoncha", + "македон", + ], + [ + "Romanian", + "румынÑ�кий", + "roumain", + "Rumänisch", + "rumano", + "rumeno", + "Romeno", + "Rumincha", + "румын", + ], + [ + "Hungarian", + "венгерÑ�кий", + "hongrois", + "Ungarisch", + "húngaro", + "ungherese", + "Húngaro", + "Vengercha", + "венгр", + ], + [ + "Greek", + "гречеÑ�кий", + "grec", + "Griechisch", + "griego", + "greco", + "Grego", + "Grekcha", + "грек", + ], + [ + "Turkish", + "турецкий", + "turc", + "Türkisch", + "turco", + "turco", + "Turco", + "Turkcha", + "түрік", + ], + [ + "Swedish", + "шведÑ�кий", + "suédois", + "Schwedisch", + "sueco", + "svedese", + "Sueco", + "Shvedcha", + "швед", + ], + [ + "Danish", + "датÑ�кий", + "danois", + "Dänisch", + "danés", + "danese", + "Dinamarquês", + "Daniyacha", + "дат", + ], + [ + "Bokmal", + "норвежÑ�кий", + "norvégien", + "Norwegisch", + "noruego", + "norvegese", + "Norueguês", + "Norvegcha (bokmÃ¥l)", + "норвег", + ], + [ + "Finnish", + "финÑ�кий", + "finnois", + "Finnisch", + "finés", + "finlandese", + "Finlandês", + "Fincha", + "фин", + ], + [ + "Estonian", + "Ñ�Ñ�тонÑ�кий", + "estonien", + "Estnisch", + "estonio", + "estone", + "Estoniano", + "Estoncha", + "Ñ�Ñ�тон", + ], + [ + "Latvian", + "латышÑ�кий", + "letton", + "Lettisch", + "letón", + "lettone", + "Letão", + "Latishcha", + "латыш", + ], + [ + "Lithuanian", + "литовÑ�кий", + "lituanien", + "Litauisch", + "lituano", + "lituano", + "Lituano", + "Litvacha", + "литва", + ], + [ + "Catalan", + "каталанÑ�кий", + "catalan", + "Katalanisch", + "catalán", + "catalano", + "Catalão", + "Katalancha", + "каталан", + ], + [ + "Esperanto", + "Ñ�Ñ�перанто", + "espéranto", + "Esperanto", + "esperanto", + "esperanto", + "Esperanto", + "Esperanto", + "Ñ�Ñ�перанто", + ], + [ + "Latin", + "латинÑ�кий", + "latin", + "Latein", + "latín", + "latino", + "Latim", + "Lotincha", + "латын", + ], + [ + "Georgian", + "грузинÑ�кий", + "géorgien", + "Georgisch", + "georgiano", + "georgiano", + "Georgiano", + "Gruzincha", + "грузин", + ], + [ + "Armenian", + "армÑ�нÑ�кий", + "arménien", + "Armenisch", + "armenio", + "armeno", + "Armênio", + "Armancha", + "армÑ�н", + ], + [ + "Azerbaijani", + "азербайджанÑ�кий", + "azerbaïdjanais", + "Aserbaidschanisch", + "azerbaiyano", + "azero", + "Azerbaijano", + "Ozarbayjoncha", + "әзербайжан", + ], + [ + "Hebrew", + "иврит", + "hébreu", + "Hebräisch", + "hebreo", + "ebraico", + "Hebraico", + "Ivrit", + "иврит", + ], + [ + "Arabic", + "арабÑ�кий", + "arabe", + "Arabisch", + "árabe", + "arabo", + "Ã�rabe", + "Arabcha", + "араб", + ], + [ + "Persian", + "перÑ�идÑ�кий", + "persan", + "Persisch", + "persa", + "persiano", + "Persa", + "Forscha", + "парÑ�Ñ‹", + ], + [ + "Mandarin", + "китайÑ�кий", + "chinois", + "Chinesisch", + "chino", + "cinese", + "Mandarim", + "Xitoycha", + "қытай", + ], + [ + "Japanese", + "Ñ�понÑ�кий", + "japonais", + "Japanisch", + "japonés", + "giapponese", + "Japonês", + "Yaponcha", + "жапон", + ], + [ + "Korean", + "корейÑ�кий", + "coréen", + "Koreanisch", + "coreano", + "coreano", + "Coreano", + "Koreyscha", + "корей", + ], + [ + "Vietnamese", + "вьетнамÑ�кий", + "vietnamien", + "Vietnamesisch", + "vietnamita", + "vietnamita", + "Vietnamita", + "Vyetnamcha", + "вьетнам", + ], + [ + "Hindi", + "хинди", + "hindi", + "Hindi", + "hindi", + "hindi", + "Hindi", + "Hindcha", + "хинди", + ], + [ + "Indonesian", + "индонезийÑ�кий", + "indonésien", + "Indonesisch", + "indonesio", + "indonesiano", + "Indonésio", + "Indonezcha", + "индонезиÑ�", + ], + [ + "Move notation", + "ЗапиÑ�ÑŒ ходов", + "Notation des coups", + "Zugnotation", + "Notación de jugadas", + "Notazione delle mosse", + "Notação dos lances", + "Yurishlar yozuvi", + "ЖүріÑ�тер жазбаÑ�Ñ‹", + ], + [ + "Letters (K Q R B N)", + "ЛатинÑ�кие буквы (K Q R B N)", + "Lettres anglaises (K Q R B N)", + "Englische Buchstaben (K Q R B N)", + "Letras inglesas (K Q R B N)", + "Lettere inglesi (K Q R B N)", + "Letras (K Q R B N)", + "Harflar (K Q R B N)", + "Латын әріптері (K Q R B N)", + ], + [ + "Figurines", + "Фигурки", + "Figurines", + "Figurinen", + "Figurines", + "Figurine", + "Figurinhas", + "Figura belgilari", + "Фигуралар белгіÑ�Ñ–", + ], + [ + "Interface language letters", + "РуÑ�Ñ�кие буквы", + "Lettres françaises", + "Deutsche Buchstaben", + "Letras españolas", + "Lettere italiane", + "Letras em português", + "Interfeys tili harflari", + "ИнтерфейÑ� тілінің әріптері", + ], + [ + "International notation, as in PGN files and engine output", + "МеждународнаÑ� запиÑ�ÑŒ, как в PGN-файлах и у движков", + "Notation internationale, comme dans les fichiers PGN et chez les moteurs", + "Internationale Notation, wie in PGN-Dateien und bei Engines", + "Notación internacional, como en los archivos PGN y en los motores", + "Notazione internazionale, come nei file PGN e nei motori", + "Notação internacional, como nos arquivos PGN e na saída dos motores", + "Xalqaro yozuv, PGN fayllari va dvigatellardagidek", + "Халықаралық жазба, PGN файлдары мен қозғалтқыштардағыдай", + ], + [ + "Piece symbols, as on Lichess. They look the same in every language.", + "Значки фигур, как на Lichess. Одинаковы на любом Ñ�зыке.", + "Symboles de pièces, comme sur Lichess. Identiques dans toutes les langues.", + "Figurensymbole wie auf Lichess. In jeder Sprache gleich.", + "Símbolos de piezas, como en Lichess. Iguales en cualquier idioma.", + "Simboli dei pezzi, come su Lichess. Uguali in ogni lingua.", + "Símbolos das peças, como no Lichess. São iguais em qualquer idioma.", + "Lichessdagidek figura belgilari. Har qanday tilda bir xil ko‘rinadi.", + "Фигура белгілері, Lichess-тегідей. Кез келген тілде бірдей көрінеді.", + ], + [ + "Follows the interface language", + "МенÑ�етÑ�Ñ� вмеÑ�те Ñ� Ñ�зыком интерфейÑ�а", + "Suit la langue de l’interface", + "Folgt der Sprache der Oberfläche", + "Sigue el idioma de la interfaz", + "Segue la lingua dell’interfaccia", + "Segue o idioma da interface", + "Interfeys tiliga qarab o‘zgaradi", + "ИнтерфейÑ� тіліне Ñ�әйкеÑ�", + ], + [ + "Only how moves look on screen. PGN files and copied games always use K Q R B N.", + "Только вид на Ñ�кране. Ð’ PGN и при копировании вÑ�егда K Q R B N.", + "Seulement l’affichage. Les fichiers PGN et les parties copiées utilisent toujours K Q R B N.", + "Nur die Anzeige. PGN-Dateien und kopierte Partien verwenden immer K Q R B N.", + "Solo cambia la vista. Los archivos PGN y las partidas copiadas siempre usan K Q R B N.", + "Cambia solo la visualizzazione. I file PGN e le partite copiate usano sempre K Q R B N.", + "Só a aparência dos lances na tela. Arquivos PGN e partidas copiadas sempre usam K Q R B N.", + "Faqat ekrandagi ko‘rinish. PGN fayllari va nusxalangan partiyalarda doim K Q R B N.", + "Тек Ñ�крандағы көрініÑ�Ñ–. PGN файлдары мен көшірілген партиÑ�ларда әрқашан K Q R B N.", + ], + [ + "Piece animation", + "Ð�нимациÑ� фигур", + "Animation des pièces", + "Figurenanimation", + "Animación de piezas", + "Animazione dei pezzi", + "Animação das peças", + "Figura animatsiyasi", + "Фигуралар анимациÑ�Ñ�Ñ‹", + ], + [ + "Off", "Ð�ет", "Aucune", "Aus", "No", "No", "Não", "Yo‘q", "Жоқ", + ], + [ + "Slow", + "Медленно", + "Lent", + "Langsam", + "Lento", + "Lento", + "Lenta", + "Sekin", + "БаÑ�у", + ], + [ + "ChessPenguin could not start.", + "ChessPenguin не удалоÑ�ÑŒ запуÑ�тить.", + "ChessPenguin n’a pas pu démarrer.", + "ChessPenguin konnte nicht starten.", + "ChessPenguin no pudo iniciarse.", + "ChessPenguin non è riuscito ad avviarsi.", + "O ChessPenguin não conseguiu iniciar.", + "ChessPenguin ishga tushmadi.", + "ChessPenguin Ñ–Ñ�ке қоÑ�ылмады.", + ], + [ + "Details are in {path}", + "ПодробноÑ�ти в файле {path}", + "Les détails sont dans {path}", + "Details stehen in {path}", + "Los detalles están en {path}", + "I dettagli sono in {path}", + "Detalhes em {path}", + "Batafsil: {path}", + "Толығырақ: {path}", + ], + [ + "A stockfish package of your distribution is found by ChessPenguin too.", + "Пакет stockfish вашего диÑ�трибутива ChessPenguin тоже находит Ñ�ам.", + "ChessPenguin trouve aussi le paquet stockfish de votre distribution.", + "ChessPenguin findet auch das stockfish-Paket Ihrer Distribution.", + "ChessPenguin también encuentra el paquete stockfish de su distribución.", + "ChessPenguin trova anche il pacchetto stockfish della tua distribuzione.", + "O ChessPenguin também encontra o pacote stockfish da sua distribuição.", + "Distributivingizdagi stockfish paketini ham ChessPenguin o‘zi topadi.", + "ChessPenguin диÑ�трибутивіңіздің stockfish пакетін де өзі табады.", + ], + [ + "Close", + "Закрыть", + "Fermer", + "Schließen", + "Cerrar", + "Chiudi", + "Fechar", + "Yopish", + "Жабу", + ], + [ + "Show the download", + "Показать загрузку", + "Afficher le téléchargement", + "Download anzeigen", + "Mostrar la descarga", + "Mostra il download", + "Mostrar o download", + "Yuklab olishni ko‘rsatish", + "Жүктеуді көрÑ�ету", + ], + [ + "Couldn't connect. Check your internet connection and try again.", + "Ð�е удалоÑ�ÑŒ подключитьÑ�Ñ�. Проверьте интернет и попробуйте ещё раз.", + "Connexion impossible. Vérifiez votre connexion Internet et réessayez.", + "Keine Verbindung. Prüfen Sie die Internetverbindung und versuchen Sie es erneut.", + "No se pudo conectar. Compruebe su conexión a Internet e inténtelo de nuevo.", + "Impossibile connettersi. Controlla la connessione Internet e riprova.", + "Não foi possível conectar. Verifique sua conexão com a internet e tente de novo.", + "Ulanib bo‘lmadi. Internet aloqasini tekshirib, qayta urinib ko‘ring.", + "ҚоÑ�ылу мүмкін болмады. Интернетті текÑ�еріп, қайталап көріңіз.", + ], + [ + "The downloaded file failed the integrity check and was deleted. It was most likely damaged during the download.", + "Скачанный файл не прошёл проверку и удалён. Скорее вÑ�его, он повредилÑ�Ñ� при загрузке.", + "Le fichier téléchargé n'a pas passé la vérification et a été supprimé. Il a probablement été endommagé pendant le téléchargement.", + "Die heruntergeladene Datei hat die Prüfung nicht bestanden und wurde gelöscht. Sie wurde wahrscheinlich beim Download beschädigt.", + "El archivo descargado no pasó la verificación y se eliminó. Probablemente se dañó durante la descarga.", + "Il file scaricato non ha superato la verifica ed è stato eliminato. Probabilmente si è danneggiato durante il download.", + "O arquivo baixado falhou na verificação de integridade e foi excluído. Provavelmente foi danificado durante o download.", + "Yuklab olingan fayl yaxlitlik tekshiruvidan o‘tmadi va o‘chirildi. Ehtimol, u yuklab olishda shikastlangan.", + "Жүктелген файл текÑ�еруден өтпей, жойылды. Ол жүктеу кезінде бүлінген болуы мүмкін.", + ], + [ + "Couldn't save the engine on the disk (not enough space or no permission).", + "Ð�е удалоÑ�ÑŒ Ñ�охранить движок на диÑ�к (не хватает меÑ�та или нет прав).", + "Impossible d'enregistrer le moteur sur le disque (espace insuffisant ou pas de droits).", + "Die Engine konnte nicht gespeichert werden (kein Platz oder keine Berechtigung).", + "No se pudo guardar el motor en el disco (falta espacio o permisos).", + "Impossibile salvare il motore sul disco (spazio insufficiente o permessi mancanti).", + "Não foi possível salvar o motor no disco (sem espaço ou sem permissão).", + "Dvigatelni diskka saqlab bo‘lmadi (joy yetmaydi yoki ruxsat yo‘q).", + "Қозғалтқышты диÑ�кіге Ñ�ақтау мүмкін болмады (орын жетпейді немеÑ�е Ñ€Ò±Ò›Ñ�ат жоқ).", + ], + [ + "Stockfish was downloaded but doesn't run on this computer.", + "Stockfish Ñ�качан, но не запуÑ�каетÑ�Ñ� на Ñ�том компьютере.", + "Stockfish a été téléchargé mais ne fonctionne pas sur cet ordinateur.", + "Stockfish wurde heruntergeladen, läuft aber auf diesem Computer nicht.", + "Stockfish se descargó pero no funciona en este ordenador.", + "Stockfish è stato scaricato ma non funziona su questo computer.", + "O Stockfish foi baixado, mas não roda neste computador.", + "Stockfish yuklab olindi, lekin bu kompyuterda ishlamaydi.", + "Stockfish жүктелді, бірақ бұл компьютерде Ñ–Ñ�ке қоÑ�ылмайды.", + ], + [ + "There is no Stockfish download for this computer. Choose an engine file instead.", + "ДлÑ� Ñ�того компьютера нет Ñ�борки Stockfish. Укажите файл движка.", + "Aucune version de Stockfish pour cet ordinateur. Choisissez un fichier de moteur.", + "Für diesen Computer gibt es keinen Stockfish-Download. Wählen Sie eine Engine-Datei.", + "No hay descarga de Stockfish para este ordenador. Elija un archivo de motor.", + "Non c'è un download di Stockfish per questo computer. Scegli un file del motore.", + "Não há download do Stockfish para este computador. Escolha um arquivo de motor.", + "Bu kompyuter uchun Stockfish yig‘masi yo‘q. O‘rniga dvigatel faylini tanlang.", + "Бұл компьютерге арналған Stockfish жинағы жоқ. Оның орнына қозғалтқыш файлын таңдаңыз.", + ], + [ + "Or download the official Stockfish 19 build ({mb} MB).", + "Или Ñ�качайте официальную Ñ�борку Stockfish 19 ({mb} МБ).", + "Ou téléchargez la version officielle de Stockfish 19 ({mb} Mo).", + "Oder laden Sie die offizielle Stockfish-19-Version herunter ({mb} MB).", + "O descargue la versión oficial de Stockfish 19 ({mb} MB).", + "Oppure scarica la versione ufficiale di Stockfish 19 ({mb} MB).", + "Ou baixe a versão oficial do Stockfish 19 ({mb} MB).", + "Yoki rasmiy Stockfish 19 yig‘masini yuklab oling ({mb} MB).", + "Ð�емеÑ�е Stockfish 19 реÑ�ми жинағын жүктеп алыңыз ({mb} МБ).", + ], + [ + "{mb} MB · from the official Stockfish page", + "{mb} МБ · Ñ� официальной Ñ�траницы Stockfish", + "{mb} Mo · depuis la page officielle de Stockfish", + "{mb} MB · von der offiziellen Stockfish-Seite", + "{mb} MB · desde la página oficial de Stockfish", + "{mb} MB · dalla pagina ufficiale di Stockfish", + "{mb} MB · da página oficial do Stockfish", + "{mb} MB · rasmiy Stockfish sahifasidan", + "{mb} МБ · Stockfish реÑ�ми бетінен", + ], + [ + "{done} of {total} MB", + "{done} из {total} МБ", + "{done} sur {total} Mo", + "{done} von {total} MB", + "{done} de {total} MB", + "{done} di {total} MB", + "{done} de {total} MB", + "{done} / {total} MB", + "{done} / {total} МБ", + ], + [ + "about {s} s left", + "оÑ�талоÑ�ÑŒ около {s} Ñ�", + "encore environ {s} s", + "noch etwa {s} s", + "quedan unos {s} s", + "ancora circa {s} s", + "faltam cerca de {s} s", + "taxminan {s} s qoldi", + "шамамен {s} Ñ� қалды", + ], + [ + "The server didn't provide the file (error {code}). Please try again later.", + "Сервер не отдал файл (ошибка {code}). Попробуйте позже.", + "Le serveur n'a pas fourni le fichier (erreur {code}). Réessayez plus tard.", + "Der Server hat die Datei nicht geliefert (Fehler {code}). Bitte später erneut versuchen.", + "El servidor no entregó el archivo (error {code}). Inténtelo más tarde.", + "Il server non ha fornito il file (errore {code}). Riprova più tardi.", + "O servidor não forneceu o arquivo (erro {code}). Tente de novo mais tarde.", + "Server faylni bermadi (xato {code}). Keyinroq qayta urinib ko‘ring.", + "Сервер файлды бермеді (қате {code}). Кейінірек қайталап көріңіз.", + ], + [ + "No engine yet", + "Движок ещё не выбран", + "Pas encore de moteur", + "Noch keine Engine", + "Aún no hay motor", + "Nessun motore per ora", + "Nenhum motor ainda", + "Hali dvigatel yo‘q", + "Қозғалтқыш әлі жоқ", + ], + [ + "An engine evaluates positions and suggests moves. Stockfish is the strongest free one.", + "Движок оценивает позиции и подÑ�казывает ходы. Stockfish — Ñ�амый Ñ�ильный из беÑ�платных.", + "Un moteur évalue les positions et propose des coups. Stockfish est le meilleur gratuit.", + "Eine Engine bewertet Stellungen und schlägt Züge vor. Stockfish ist die stärkste kostenlose.", + "Un motor evalúa posiciones y sugiere jugadas. Stockfish es el más fuerte de los gratuitos.", + "Un motore valuta le posizioni e suggerisce mosse. Stockfish è il più forte tra quelli gratuiti.", + "Um motor avalia posições e sugere lances. O Stockfish é o gratuito mais forte.", + "Dvigatel pozitsiyalarni baholaydi va yurishlar taklif qiladi. Stockfish — bepullarining eng kuchlisi.", + "Қозғалтқыш позициÑ�ларды бағалап, жүріÑ� Ò±Ñ�ынады. Stockfish — тегіндердің ең күштіÑ�Ñ–.", + ], + [ + "⬇ Download Stockfish 19", + "⬇ Скачать Stockfish 19", + "⬇ Télécharger Stockfish 19", + "⬇ Stockfish 19 herunterladen", + "⬇ Descargar Stockfish 19", + "⬇ Scarica Stockfish 19", + "⬇ Baixar Stockfish 19", + "⬇ Stockfish 19 yuklab olish", + "⬇ Stockfish 19 жүктеп алу", + ], + [ + "⬇ Download Stockfish 19 · {mb} MB", + "⬇ Скачать Stockfish 19 · {mb} МБ", + "⬇ Télécharger Stockfish 19 · {mb} Mo", + "⬇ Stockfish 19 herunterladen · {mb} MB", + "⬇ Descargar Stockfish 19 · {mb} MB", + "⬇ Scarica Stockfish 19 · {mb} MB", + "⬇ Baixar Stockfish 19 · {mb} MB", + "⬇ Stockfish 19 yuklab olish · {mb} MB", + "⬇ Stockfish 19 жүктеп алу · {mb} МБ", + ], + [ + "Remove (and delete the downloaded files)", + "Удалить (вмеÑ�те Ñ�о Ñ�качанными файлами)", + "Retirer (et supprimer les fichiers téléchargés)", + "Entfernen (mit den heruntergeladenen Dateien)", + "Quitar (y borrar los archivos descargados)", + "Rimuovi (ed elimina i file scaricati)", + "Remover (e excluir os arquivos baixados)", + "Olib tashlash (yuklab olingan fayllar bilan)", + "Өшіру (жүктелген файлдарымен бірге)", + ], + [ + "Included with ChessPenguin", + "Входит в ChessPenguin", + "Inclus avec ChessPenguin", + "In ChessPenguin enthalten", + "Incluido con ChessPenguin", + "Incluso in ChessPenguin", + "Incluído no ChessPenguin", + "ChessPenguin tarkibida", + "ChessPenguin құрамында", + ], + [ + "âš  File not found", + "âš  Файл не найден", + "âš  Fichier introuvable", + "âš  Datei nicht gefunden", + "âš  Archivo no encontrado", + "âš  File non trovato", + "âš  Arquivo não encontrado", + "âš  Fayl topilmadi", + "âš  Файл табылмады", + ], + [ + "Remove", + "Удалить", + "Supprimer", + "Entfernen", + "Quitar", + "Rimuovi", + "Remover", + "Olib tashlash", + "Өшіру", + ], + [ + "From the official Stockfish page; installed for your account only", + "С официальной Ñ�траницы Stockfish; уÑ�танавливаетÑ�Ñ� только длÑ� ваÑ�", + "Depuis la page officielle de Stockfish ; installé pour votre compte uniquement", + "Von der offiziellen Stockfish-Seite; nur für Ihr Konto installiert", + "Desde la página oficial de Stockfish; solo para su cuenta", + "Dalla pagina ufficiale di Stockfish; installato solo per il tuo account", + "Da página oficial do Stockfish; instalado apenas para sua conta", + "Rasmiy Stockfish sahifasidan; faqat sizning hisobingiz uchun o‘rnatiladi", + "Stockfish реÑ�ми бетінен; тек Ñ�іздің тіркелгіңізге орнатылады", + ], + [ + "{mb} MB from the official Stockfish page; installed for your account only", + "{mb} МБ Ñ� официальной Ñ�траницы Stockfish; уÑ�танавливаетÑ�Ñ� только длÑ� ваÑ�", + "{mb} Mo depuis la page officielle de Stockfish ; installé pour votre compte uniquement", + "{mb} MB von der offiziellen Stockfish-Seite; nur für Ihr Konto installiert", + "{mb} MB desde la página oficial de Stockfish; solo para su cuenta", + "{mb} MB dalla pagina ufficiale di Stockfish; installato solo per il tuo account", + "{mb} MB da página oficial do Stockfish; instalado apenas para sua conta", + "Rasmiy Stockfish sahifasidan {mb} MB; faqat sizning hisobingiz uchun o‘rnatiladi", + "Stockfish реÑ�ми бетінен {mb} МБ; тек Ñ�іздің тіркелгіңізге орнатылады", + ], + [ + "Downloaded by ChessPenguin · {mb} MB", + "Скачан ChessPenguin · {mb} МБ", + "Téléchargé par ChessPenguin · {mb} Mo", + "Von ChessPenguin heruntergeladen · {mb} MB", + "Descargado por ChessPenguin · {mb} MB", + "Scaricato da ChessPenguin · {mb} MB", + "Baixado pelo ChessPenguin · {mb} MB", + "ChessPenguin yuklab olgan · {mb} MB", + "ChessPenguin жүктеген · {mb} МБ", + ], + [ + "Remove Stockfish 19? This frees {mb} MB. You can download it again at any time.", + "Удалить Stockfish 19? ОÑ�вободитÑ�Ñ� {mb} МБ. Скачать Ñ�нова можно в любой момент.", + "Supprimer Stockfish 19 ? Cela libère {mb} Mo. Vous pourrez le retélécharger à tout moment.", + "Stockfish 19 entfernen? Das gibt {mb} MB frei. Sie können es jederzeit erneut herunterladen.", + "¿Quitar Stockfish 19? Se liberan {mb} MB. Puede volver a descargarlo cuando quiera.", + "Rimuovere Stockfish 19? Si liberano {mb} MB. Puoi scaricarlo di nuovo in qualsiasi momento.", + "Remover o Stockfish 19? Isso libera {mb} MB. Você pode baixá-lo de novo a qualquer momento.", + "Stockfish 19 olib tashlansinmi? {mb} MB bo‘shaydi. Istalgan vaqtda qayta yuklab olish mumkin.", + "Stockfish 19 өшірілÑ�ін бе? {mb} МБ боÑ�айды. Кез келген уақытта қайта жүктеп алуға болады.", + ], + // --- position search --- + [ + "Year", "Год", "Année", "Jahr", "Año", "Anno", "Ano", "Yil", "Жыл", + ], + [ + "+{n} more", + "ещё {n}", + "+{n} autres", + "+{n} weitere", + "+{n} más", + "+{n} altri", + "+{n} mais", + "+{n} ta yana", + "тағы {n}", + ], + [ + "Clear", + "ОчиÑ�тить", + "Effacer", + "Leeren", + "Borrar", + "Cancella", + "Limpar", + "Tozalash", + "Тазалау", + ], + [ + "Add a database first", + "Сначала добавьте базу", + "Ajoutez d'abord une base", + "Zuerst eine Datenbank hinzufügen", + "Añada primero una base", + "Aggiungi prima un database", + "Adicione uma base primeiro", + "Avval baza qo‘shing", + "Ð�лдымен база қоÑ�ыңыз", + ], + [ + "After a null move (--) this is a teaching scheme, not a position of a game: it is not searched", + "ПоÑ�ле пуÑ�того хода (--) Ñ�то учебнаÑ� Ñ�хема, а не позициÑ� партии — в базе не ищетÑ�Ñ�", + "Après un coup nul (--), c'est un schéma d'étude, pas une position de partie : elle n'est pas recherchée", + "Nach einem Nullzug (--) ist das ein Lehrschema, keine Partiestellung: sie wird nicht gesucht", + "Tras una jugada nula (--) es un esquema didáctico, no una posición de partida: no se busca", + "Dopo una mossa nulla (--) è uno schema didattico, non una posizione di partita: non viene cercata", + "Após um lance nulo (--) isto é um esquema didático, não uma posição de partida: não é pesquisado", + "Bo‘sh yurishdan (--) keyin bu partiya pozitsiyasi emas, o‘quv sxemasi: u qidirilmaydi", + "БоÑ� жүріÑ�тен (--) кейін бұл партиÑ� позициÑ�Ñ�Ñ‹ емеÑ�, оқу Ñ�ызбаÑ�Ñ‹: ол ізделмейді", + ], + [ + "Find in another database", + "Ð�айти в другой базе", + "Chercher dans une autre base", + "In einer anderen Datenbank suchen", + "Buscar en otra base", + "Cerca in un altro database", + "Buscar em outra base", + "Boshqa bazadan topish", + "БаÑ�қа базадан табу", + ], + [ + "ðŸ”� Find in database", + "ðŸ”� Ð�айти в базе", + "ðŸ”� Chercher dans la base", + "ðŸ”� In Datenbank suchen", + "ðŸ”� Buscar en la base", + "ðŸ”� Cerca nel database", + "ðŸ”� Buscar na base", + "ðŸ”� Bazadan topish", + "ðŸ”� Базадан табу", + ], + [ + "Find this position in a database (Ctrl+Shift+F)", + "Ð�айти Ñ�ту позицию в базе (Ctrl+Shift+F)", + "Chercher cette position dans une base (Ctrl+Maj+F)", + "Diese Stellung in einer Datenbank suchen (Strg+Umschalt+F)", + "Buscar esta posición en una base (Ctrl+Mayús+F)", + "Cerca questa posizione in un database (Ctrl+Maiusc+F)", + "Buscar esta posição em uma base (Ctrl+Shift+F)", + "Bu pozitsiyani bazadan topish (Ctrl+Shift+F)", + "Бұл позициÑ�ны базадан табу (Ctrl+Shift+F)", + ], + [ + "Find games by position: play moves on the board (Ctrl+B)", + "Ð�айти партии по позиции: делайте ходы на доÑ�ке (Ctrl+B)", + "Trouver des parties par position : jouez des coups sur l'échiquier (Ctrl+B)", + "Partien nach Stellung finden: Züge auf dem Brett ausführen (Strg+B)", + "Buscar partidas por posición: haga jugadas en el tablero (Ctrl+B)", + "Trova partite per posizione: gioca mosse sulla scacchiera (Ctrl+B)", + "Buscar partidas por posição: jogue lances no tabuleiro (Ctrl+B)", + "Partiyalarni pozitsiya bo‘yicha topish: taxtada yurishlar qiling (Ctrl+B)", + "ПартиÑ�ларды позициÑ� бойынша табу: тақтада жүріÑ� жаÑ�аңыз (Ctrl+B)", + ], + [ + "Length", + "Длина", + "Longueur", + "Länge", + "Longitud", + "Lunghezza", + "Duração", + "Uzunlik", + "Ұзындық", + ], + [ + "Move", + "Ход", + "Coup", + "Zug", + "Jugada", + "Mossa", + "Lance", + "Yurish", + "ЖүріÑ�", + ], + [ + "The move after which the position arose in the game. ↪ — reached by another move order, 🔀 — in a variation", + "Ход, поÑ�ле которого в партии возникла позициÑ�. ↪ — пришли другим порÑ�дком ходов, 🔀 — в варианте", + "Coup après lequel la position est apparue dans la partie. ↪ — atteinte par un autre ordre de coups, 🔀 — dans une variante", + "Zug, nach dem die Stellung in der Partie entstand. ↪ — mit anderer Zugfolge erreicht, 🔀 — in einer Variante", + "Jugada tras la que surgió la posición en la partida. ↪ — alcanzada con otro orden de jugadas, 🔀 — en una variante", + "Mossa dopo la quale è nata la posizione nella partita. ↪ — raggiunta con un altro ordine di mosse, 🔀 — in una variante", + "O lance após o qual a posição surgiu na partida. ↪ — alcançada por outra ordem de lances, 🔀 — em uma variante", + "Partiyada pozitsiya qaysi yurishdan keyin paydo bo‘lgani. ↪ — boshqa yurishlar tartibida, 🔀 — variantda", + "ПартиÑ�да позициÑ� пайда болған жүріÑ�. ↪ — баÑ�қа жүріÑ� ретімен келген, 🔀 — вариантта", + ], + [ + "Position: {line}", + "ПозициÑ�: {line}", + "Position : {line}", + "Stellung: {line}", + "Posición: {line}", + "Posizione: {line}", + "Posição: {line}", + "Pozitsiya: {line}", + "ПозициÑ�: {line}", + ], + [ + "Moves: {line} (this order)", + "Ходы: {line} (точно Ñ�тот порÑ�док)", + "Coups : {line} (cet ordre)", + "Züge: {line} (genau diese Folge)", + "Jugadas: {line} (este orden)", + "Mosse: {line} (questo ordine)", + "Lances: {line} (nesta ordem)", + "Yurishlar: {line} (aynan shu tartib)", + "ЖүріÑ�тер: {line} (дәл оÑ�Ñ‹ рет)", + ], + [ + "Filters", + "Фильтры", + "Filtres", + "Filter", + "Filtros", + "Filtri", + "Filtros", + "Filtrlar", + "Сүзгілер", + ], + [ + "Filters ({n})", + "Фильтры ({n})", + "Filtres ({n})", + "Filter ({n})", + "Filtros ({n})", + "Filtri ({n})", + "Filtros ({n})", + "Filtrlar ({n})", + "Сүзгілер ({n})", + ], + [ + "Filters: players, tournament, years, rating… (Ctrl+F)", + "Фильтры: игроки, турнир, годы, рейтинг… (Ctrl+F)", + "Filtres : joueurs, tournoi, années, classement… (Ctrl+F)", + "Filter: Spieler, Turnier, Jahre, Wertung… (Strg+F)", + "Filtros: jugadores, torneo, años, Elo… (Ctrl+F)", + "Filtri: giocatori, torneo, anni, Elo… (Ctrl+F)", + "Filtros: jogadores, torneio, anos, rating… (Ctrl+F)", + "Filtrlar: o‘yinchilar, turnir, yillar, reyting… (Ctrl+F)", + "Сүзгілер: ойыншылар, турнир, жылдар, рейтинг… (Ctrl+F)", + ], + [ + "Show the list of games (Esc)", + "Показать Ñ�пиÑ�ок партий (Esc)", + "Afficher la liste des parties (Échap)", + "Partienliste anzeigen (Esc)", + "Mostrar la lista de partidas (Esc)", + "Mostra l'elenco delle partite (Esc)", + "Mostrar a lista de partidas (Esc)", + "Partiyalar ro‘yxatini ko‘rsatish (Esc)", + "ПартиÑ�лар тізімін көрÑ�ету (Esc)", + ], + [ + "Hide the panel", + "Скрыть панель", + "Masquer le panneau", + "Bereich ausblenden", + "Ocultar el panel", + "Nascondi il pannello", + "Ocultar o painel", + "Panelni yashirish", + "Панельді жаÑ�ыру", + ], + [ + "no texts", + "без текÑ�тов", + "sans textes", + "ohne Texte", + "sin textos", + "senza testi", + "sem textos", + "matnlarsiz", + "мәтінÑ�із", + ], + [ + "No conditions: all games are shown", + "УÑ�ловий нет — показаны вÑ�е партии", + "Aucune condition : toutes les parties sont affichées", + "Keine Bedingungen: alle Partien werden gezeigt", + "Sin condiciones: se muestran todas las partidas", + "Nessuna condizione: sono mostrate tutte le partite", + "Sem condições: todas as partidas são exibidas", + "Shartlar yo‘q: barcha partiyalar ko‘rsatilgan", + "Шарт жоқ: барлық партиÑ� көрÑ�етілген", + ], + [ + "all move orders", + "вÑ�е порÑ�дки", + "tous les ordres", + "alle Zugfolgen", + "todos los órdenes", + "tutti gli ordini", + "todas as ordens", + "har qanday tartib", + "кез келген рет", + ], + [ + "only this order", + "только Ñ�тот порÑ�док", + "seulement cet ordre", + "nur diese Folge", + "solo este orden", + "solo questo ordine", + "só esta ordem", + "faqat shu tartib", + "тек оÑ�Ñ‹ рет", + ], + [ + "Show only the games whose moves went exactly as on your board. Otherwise all games that reached this position by any path are shown.", + "Показать только партии, где ходы шли в точноÑ�ти как у ваÑ� на доÑ�ке. СейчаÑ� показаны вÑ�е партии, пришедшие к Ñ�той позиции любым путём.", + "N'afficher que les parties dont les coups ont suivi exactement ceux de votre échiquier. Sinon, toutes les parties ayant atteint cette position par n'importe quel chemin sont affichées.", + "Nur Partien zeigen, deren Züge genau wie auf Ihrem Brett verliefen. Sonst werden alle Partien gezeigt, die diese Stellung auf beliebigem Weg erreichten.", + "Mostrar solo las partidas cuyas jugadas fueron exactamente como en su tablero. Si no, se muestran todas las que llegaron a esta posición por cualquier camino.", + "Mostra solo le partite le cui mosse sono andate esattamente come sulla tua scacchiera. Altrimenti sono mostrate tutte le partite giunte a questa posizione per qualsiasi via.", + "Mostrar só as partidas cujos lances foram exatamente como no seu tabuleiro. Caso contrário, são exibidas todas as partidas que chegaram a esta posição por qualquer caminho.", + "Faqat yurishlari aynan taxtangizdagidek borgan partiyalarni ko‘rsatish. Aks holda bu pozitsiyaga istalgan yo‘l bilan kelgan barcha partiyalar ko‘rsatiladi.", + "ЖүріÑ�тері тақтаңыздағыдай дәл жүрілген партиÑ�ларды ғана көрÑ�ету. ӘйтпеÑ�е оÑ�Ñ‹ позициÑ�ға кез келген жолмен келген барлық партиÑ� көрÑ�етіледі.", + ], + [ + "The position does not occur in these games", + "ПозициÑ� не вÑ�третилаÑ�ÑŒ в Ñ�тих партиÑ�Ñ…", + "La position n'apparaît pas dans ces parties", + "Die Stellung kommt in diesen Partien nicht vor", + "La posición no aparece en estas partidas", + "La posizione non compare in queste partite", + "A posição não ocorre nestas partidas", + "Bu partiyalarda pozitsiya uchramadi", + "Бұл партиÑ�ларда позициÑ� кездеÑ�пейді", + ], + [ + "Search the whole database", + "ИÑ�кать во вÑ�ей базе", + "Chercher dans toute la base", + "In der ganzen Datenbank suchen", + "Buscar en toda la base", + "Cerca in tutto il database", + "Buscar na base inteira", + "Butun bazadan qidirish", + "Бүкіл базадан іздеу", + ], + [ + "Remove the condition", + "СнÑ�ть уÑ�ловие", + "Retirer la condition", + "Bedingung entfernen", + "Quitar la condición", + "Rimuovi la condizione", + "Remover a condição", + "Shartni olib tashlash", + "Шартты алып таÑ�тау", + ], + [ + "in this move order: {n} of {m} ·", + "Ñ�тим порÑ�дком ходов — {n} из {m} ·", + "dans cet ordre de coups : {n} sur {m} ·", + "in dieser Zugfolge: {n} von {m} ·", + "en este orden de jugadas: {n} de {m} ·", + "in questo ordine di mosse: {n} su {m} ·", + "nesta ordem de lances: {n} de {m} ·", + "shu yurishlar tartibida: {n} / {m} ·", + "оÑ�Ñ‹ жүріÑ� ретімен: {n} / {m} ·", + ], + [ + "Starting position", + "Ð�ачальнаÑ� позициÑ�", + "Position initiale", + "Grundstellung", + "Posición inicial", + "Posizione iniziale", + "Posição inicial", + "Boshlang‘ich pozitsiya", + "БаÑ�тапқы позициÑ�", + ], + [ + "White to move", + "Ход белых", + "Trait aux Blancs", + "Weiß am Zug", + "Juegan blancas", + "Muove il Bianco", + "Brancas jogam", + "Oqlar yuradi", + "Ð�қтар жүреді", + ], + [ + "Black to move", + "Ход чёрных", + "Trait aux Noirs", + "Schwarz am Zug", + "Juegan negras", + "Muove il Nero", + "Pretas jogam", + "Qoralar yuradi", + "Қаралар жүреді", + ], + [ + "after {move}", + "поÑ�ле {move}", + "après {move}", + "nach {move}", + "tras {move}", + "dopo {move}", + "após {move}", + "{move}dan keyin", + "{move} кейін", + ], + [ + "Open as a new game", + "Открыть как новую партию", + "Ouvrir comme nouvelle partie", + "Als neue Partie öffnen", + "Abrir como partida nueva", + "Apri come nuova partita", + "Abrir como nova partida", + "Yangi partiya sifatida ochish", + "Жаңа партиÑ� ретінде ашу", + ], + [ + "Copy moves (PGN)", + "Копировать ходы (PGN)", + "Copier les coups (PGN)", + "Züge kopieren (PGN)", + "Copiar jugadas (PGN)", + "Copia le mosse (PGN)", + "Copiar lances (PGN)", + "Yurishlarni nusxalash (PGN)", + "ЖүріÑ�терді көшіру (PGN)", + ], + [ + "Undo", + "Вернуть", + "Annuler", + "Rückgängig", + "Deshacer", + "Annulla", + "Desfazer", + "Bekor qilish", + "Болдырмау", + ], + [ + "Reset", + "СброÑ�ить", + "Réinitialiser", + "Zurücksetzen", + "Restablecer", + "Azzera", + "Redefinir", + "Tiklash", + "Қалпына келтіру", + ], + [ + "Reset statistics for this repertoire and color?", + "СброÑ�ить Ñ�татиÑ�тику Ñ�того репертуара и цвета?", + "Réinitialiser les statistiques de ce répertoire et de cette couleur ?", + "Statistik für dieses Repertoire und diese Farbe zurücksetzen?", + "¿Restablecer las estadísticas de este repertorio y color?", + "Azzerare le statistiche di questo repertorio e colore?", + "Redefinir as estatísticas deste repertório e cor?", + "Ushbu repertuar va rang statistikasi tiklansinmi?", + "ОÑ�Ñ‹ репертуар мен түÑ�тің Ñ�татиÑ�тикаÑ�Ñ‹ қалпына келтірилÑ�ін бе?", + ], + [ + "Starting position (Ctrl+Backspace)", + "Ð�ачальнаÑ� позициÑ� (Ctrl+Backspace)", + "Position initiale (Ctrl+Retour arrière)", + "Grundstellung (Strg+Rücktaste)", + "Posición inicial (Ctrl+Retroceso)", + "Posizione iniziale (Ctrl+Backspace)", + "Posição inicial (Ctrl+Backspace)", + "Boshlang‘ich pozitsiya (Ctrl+Backspace)", + "БаÑ�тапқы позициÑ� (Ctrl+Backspace)", + ], + [ + "Flip the board (F)", + "Перевернуть доÑ�ку (F)", + "Retourner l'échiquier (F)", + "Brett drehen (F)", + "Girar el tablero (F)", + "Gira la scacchiera (F)", + "Girar o tabuleiro (F)", + "Taxtani aylantirish (F)", + "Тақтаны аудару (F)", + ], + [ + "Move back (Left arrow)", + "Ход назад (Ñ�трелка влево)", + "Coup précédent (flèche gauche)", + "Zug zurück (Pfeil links)", + "Jugada atrás (flecha izquierda)", + "Mossa indietro (freccia sinistra)", + "Voltar um lance (seta esquerda)", + "Bir yurish orqaga (chap strelka)", + "Бір жүріÑ� артқа (Ñ�ол жақ бағыттауыш)", + ], + [ + "Move forward (Right arrow)", + "Ход вперёд (Ñ�трелка вправо)", + "Coup suivant (flèche droite)", + "Zug vor (Pfeil rechts)", + "Jugada adelante (flecha derecha)", + "Mossa avanti (freccia destra)", + "Avançar um lance (seta direita)", + "Bir yurish oldinga (o‘ng strelka)", + "Бір жүріÑ� алға (оң жақ бағыттауыш)", + ], + [ + "Start position of the game", + "СтартоваÑ� позициÑ� партии", + "Position de départ de la partie", + "Ausgangsstellung der Partie", + "Posición de inicio de la partida", + "Posizione di partenza della partita", + "Posição inicial da partida", + "Partiyaning boshlang‘ich pozitsiyasi", + "ПартиÑ�ның баÑ�тапқы позициÑ�Ñ�Ñ‹", + ], + [ + "Play moves on the board", + "Делайте ходы на доÑ�ке", + "Jouez des coups sur l'échiquier", + "Züge auf dem Brett ausführen", + "Haga jugadas en el tablero", + "Gioca mosse sulla scacchiera", + "Jogue lances no tabuleiro", + "Taxtada yurishlar qiling", + "Тақтада жүріÑ� жаÑ�аңыз", + ], + [ + "Continuations in the book", + "ПродолжениÑ� в книге", + "Suites dans le livre", + "Fortsetzungen im Buch", + "Continuaciones en el libro", + "Continuazioni nel libro", + "Continuações no livro", + "Kitobdagi davomlar", + "Кітаптағы жалғаÑ�улар", + ], + [ + "Continuations", + "ПродолжениÑ�", + "Suites", + "Fortsetzungen", + "Continuaciones", + "Continuazioni", + "Continuações", + "Davomlar", + "ЖалғаÑ�улар", + ], + [ + "Counting…", + "Считаю…", + "Calcul…", + "Zähle…", + "Contando…", + "Conteggio…", + "Contando…", + "Hisoblanmoqda…", + "ЕÑ�ептелуде…", + ], + [ + "Counting… {p} %", + "ПодÑ�чёт… {p} %", + "Calcul… {p} %", + "Zähle… {p} %", + "Contando… {p} %", + "Conteggio… {p} %", + "Contando… {p} %", + "Hisoblanmoqda… {p} %", + "ЕÑ�ептелуде… {p} %", + ], + [ + "No continuations in this selection", + "Ð�ет продолжений в Ñ�той выборке", + "Aucune suite dans cette sélection", + "Keine Fortsetzungen in dieser Auswahl", + "Sin continuaciones en esta selección", + "Nessuna continuazione in questa selezione", + "Sem continuações nesta seleção", + "Bu tanlovda davomlar yo‘q", + "Бұл іріктемеде жалғаÑ�у жоқ", + ], + [ + "Few games: the statistics are not reliable", + "Мало партий — Ñ�татиÑ�тика ненадёжна", + "Peu de parties : statistiques peu fiables", + "Wenige Partien: die Statistik ist unzuverlässig", + "Pocas partidas: estadística poco fiable", + "Poche partite: statistica poco affidabile", + "Poucas partidas: a estatística não é confiável", + "Partiyalar kam: statistika ishonchli emas", + "ПартиÑ� аз: Ñ�татиÑ�тика Ñ�енімÑ�із", + ], + [ + "· {n} chapters", + "· {n} глав", + "· {n} chapitres", + "· {n} Kapitel", + "· {n} capítulos", + "· {n} capitoli", + "· {n} capítulos", + "· {n} ta bob", + "· {n} тарау", + ], + [ + "{n} chapters", + "{n} глав", + "{n} chapitres", + "{n} Kapitel", + "{n} capítulos", + "{n} capitoli", + "{n} capítulos", + "{n} ta bob", + "{n} тарау", + ], + [ + "Ended here: {n}", + "ЗакончилиÑ�ÑŒ здеÑ�ÑŒ: {n}", + "Terminées ici : {n}", + "Hier beendet: {n}", + "Terminadas aquí: {n}", + "Terminate qui: {n}", + "Terminaram aqui: {n}", + "Shu yerda tugagan: {n}", + "ОÑ�ында аÑ�қталды: {n}", + ], + [ + "White won {w} ({wp} %) · draws {d} ({dp} %) · Black won {b} ({bp} %)", + "Белые выиграли {w} ({wp} %) · ничьих {d} ({dp} %) · чёрные выиграли {b} ({bp} %)", + "Gains des Blancs {w} ({wp} %) · nulles {d} ({dp} %) · gains des Noirs {b} ({bp} %)", + "Weiß gewann {w} ({wp} %) · Remis {d} ({dp} %) · Schwarz gewann {b} ({bp} %)", + "Ganan blancas {w} ({wp} %) · tablas {d} ({dp} %) · ganan negras {b} ({bp} %)", + "Vince il Bianco {w} ({wp} %) · patte {d} ({dp} %) · vince il Nero {b} ({bp} %)", + "Brancas venceram {w} ({wp} %) · empates {d} ({dp} %) · Pretas venceram {b} ({bp} %)", + "Oqlar yutgan {w} ({wp} %) · durang {d} ({dp} %) · qoralar yutgan {b} ({bp} %)", + "Ð�қтар жеңді {w} ({wp} %) · тең ойын {d} ({dp} %) · Қаралар жеңді {b} ({bp} %)", + ], + // --- large databases --- + [ + "Reset filters", + "СброÑ�ить фильтры", + "Réinitialiser les filtres", + "Filter zurücksetzen", + "Restablecer filtros", + "Azzera filtri", + "Redefinir filtros", + "Filtrlarni tiklash", + "Сүзгілерді таÑ�тау", + ], + [ + "Reset filters ({n})", + "СброÑ�ить фильтры ({n})", + "Réinitialiser les filtres ({n})", + "Filter zurücksetzen ({n})", + "Restablecer filtros ({n})", + "Azzera filtri ({n})", + "Redefinir filtros ({n})", + "Filtrlarni tiklash ({n})", + "Сүзгілерді таÑ�тау ({n})", + ], + [ + "Players", + "Игроки", + "Joueurs", + "Spieler", + "Jugadores", + "Giocatori", + "Jogadores", + "O‘yinchilar", + "Ойыншылар", + ], + [ + "Player", + "Игрок", + "Joueur", + "Spieler", + "Jugador", + "Giocatore", + "Jogador", + "O‘yinchi", + "Ойыншы", + ], + [ + "either colour", + "любым", + "toute couleur", + "beliebig", + "cualquier color", + "qualsiasi colore", + "qualquer cor", + "istalgan rangda", + "кез келген", + ], + [ + "as White", + "белыми", + "avec les Blancs", + "mit Weiß", + "con blancas", + "con il Bianco", + "de brancas", + "oqlarda", + "ақтармен", + ], + [ + "as Black", + "чёрными", + "avec les Noirs", + "mit Schwarz", + "con negras", + "con il Nero", + "de pretas", + "qoralarda", + "қаралармен", + ], + [ + "Enter a player first", + "Сначала укажите игрока", + "Indiquez d'abord un joueur", + "Zuerst einen Spieler angeben", + "Indique primero un jugador", + "Indica prima un giocatore", + "Informe um jogador primeiro", + "Avval o‘yinchini kiriting", + "Ð�лдымен ойыншыны көрÑ�етіңіз", + ], + [ + "Opponent", + "Соперник", + "Adversaire", + "Gegner", + "Rival", + "Avversario", + "Adversário", + "Raqib", + "ҚарÑ�ылаÑ�", + ], + [ + "Tournament or place", + "Турнир или меÑ�то", + "Tournoi ou lieu", + "Turnier oder Ort", + "Torneo o lugar", + "Torneo o luogo", + "Torneio ou local", + "Turnir yoki joy", + "Турнир немеÑ�е орын", + ], + [ + "Annotator", + "Комментатор", + "Commentateur", + "Kommentator", + "Comentarista", + "Commentatore", + "Comentarista", + "Izohlovchi", + "ТүÑ�ініктеме авторы", + ], + [ + "Game", + "ПартиÑ�", + "Partie", + "Partie", + "Partida", + "Partita", + "Partida", + "Partiya", + "ПартиÑ�", + ], + [ + "Years", + "Годы", + "Années", + "Jahre", + "Años", + "Anni", + "Anos", + "Yillar", + "Жылдар", + ], + [ + "Elo from", + "Эло от", + "Elo dès", + "Elo ab", + "Elo desde", + "Elo da", + "Elo a partir de", + "Elo kamida", + "Elo, кемінде", + ], + [ + "both", + "обоих", + "les deux", + "beide", + "ambos", + "entrambi", + "ambos", + "ikkalasi", + "екеуі", + ], + [ + "either", + "любого", + "l'un", + "einer", + "cualquiera", + "uno dei due", + "qualquer", + "biri", + "біреуінің", + ], + [ + "average", + "Ñ�реднее", + "moyenne", + "Schnitt", + "media", + "media", + "média", + "o‘rtacha", + "орташа", + ], + [ + "opponent", + "Ñ�оперника", + "adversaire", + "Gegner", + "rival", + "avversario", + "adversário", + "raqib", + "қарÑ�ылаÑ�тың", + ], + [ + "Win", + "Выигрыш", + "Gain", + "Sieg", + "Victoria", + "Vittoria", + "Vitória", + "G‘alaba", + "ЖеңіÑ�", + ], + [ + "Loss", + "Проигрыш", + "Perte", + "Niederlage", + "Derrota", + "Sconfitta", + "Derrota", + "Mag‘lubiyat", + "ЖеңіліÑ�", + ], + [ + "B90, B9 or C60-C99", + "B90, B9 или C60-C99", + "B90, B9 ou C60-C99", + "B90, B9 oder C60-C99", + "B90, B9 o C60-C99", + "B90, B9 o C60-C99", + "B90, B9 ou C60-C99", + "B90, B9 yoki C60-C99", + "B90, B9 немеÑ�е C60-C99", + ], + [ + "A code (B90), a prefix (B9) or a range (C60-C99), separated by commas", + "Код (B90), начало кода (B9) или диапазон (C60-C99), через запÑ�тую", + "Un code (B90), un préfixe (B9) ou une plage (C60-C99), séparés par des virgules", + "Ein Code (B90), ein Präfix (B9) oder ein Bereich (C60-C99), durch Kommas getrennt", + "Un código (B90), un prefijo (B9) o un rango (C60-C99), separados por comas", + "Un codice (B90), un prefisso (B9) o un intervallo (C60-C99), separati da virgole", + "Um código (B90), um prefixo (B9) ou um intervalo (C60-C99), separados por vírgulas", + "Kod (B90), kod boshi (B9) yoki oraliq (C60-C99), vergul bilan", + "Код (B90), кодтың баÑ�Ñ‹ (B9) немеÑ�е аралық (C60-C99), үтір арқылы", + ], + [ + "Annotations", + "Ð�ннотации", + "Annotations", + "Anmerkungen", + "Anotaciones", + "Annotazioni", + "Anotações", + "Annotatsiyalar", + "Ð�ннотациÑ�лар", + ], + [ + "with comments", + "Ñ� комментариÑ�ми", + "avec commentaires", + "mit Kommentaren", + "con comentarios", + "con commenti", + "com comentários", + "izohlar bilan", + "түÑ�ініктемеÑ�Ñ– бар", + ], + [ + "with variations", + "Ñ� вариантами", + "avec variantes", + "mit Varianten", + "con variantes", + "con varianti", + "com variantes", + "variantlar bilan", + "варианттары бар", + ], + [ + "show texts", + "показывать текÑ�ты", + "afficher les textes", + "Texte zeigen", + "mostrar textos", + "mostra i testi", + "mostrar textos", + "matnlarni ko‘rsatish", + "мәтіндерді көрÑ�ету", + ], + [ + "Guiding texts of the database; left out by any condition on players, dates, ratings, results or moves", + "ТекÑ�товые главы базы; Ñ�крываютÑ�Ñ� при любом уÑ�ловии на игроков, даты, рейтинг, результат или ходы", + "Textes de la base ; exclus par toute condition sur les joueurs, dates, classements, résultats ou coups", + "Texte der Datenbank; ausgeblendet bei jeder Bedingung zu Spielern, Daten, Wertungen, Ergebnissen oder Zügen", + "Textos de la base; se ocultan con cualquier condición sobre jugadores, fechas, Elo, resultados o jugadas", + "Testi del database; esclusi da qualsiasi condizione su giocatori, date, Elo, risultati o mosse", + "Textos de orientação da base; excluídos por qualquer condição sobre jogadores, datas, ratings, resultados ou lances", + "Bazaning yo‘l-yo‘riq matnlari; o‘yinchilar, sanalar, reyting, natija yoki yurishlar bo‘yicha har qanday shartda yashiriladi", + "Базаның мәтіндік тараулары; ойыншыларға, күнге, рейтингке, нәтижеге немеÑ�е жүріÑ�терге кез келген шарт қойылÑ�а, жаÑ�ырылады", + ], + [ + "Exactly this name; edit the text to search by words again", + "Точно Ñ�то имÑ�; измените текÑ�Ñ‚, чтобы Ñ�нова иÑ�кать по Ñ�ловам", + "Exactement ce nom ; modifiez le texte pour chercher à nouveau par mots", + "Genau dieser Name; Text ändern, um wieder nach Wörtern zu suchen", + "Exactamente este nombre; edite el texto para volver a buscar por palabras", + "Esattamente questo nome; modifica il testo per cercare di nuovo per parole", + "Exatamente este nome; edite o texto para buscar por palavras de novo", + "Aynan shu ism; so‘zlar bo‘yicha qayta qidirish uchun matnni o‘zgartiring", + "Дәл оÑ�Ñ‹ аты; Ñ�өздер бойынша қайта іздеу үшін мәтінді өзгертіңіз", + ], + [ + "ChessBase, read-only", + "ChessBase, только чтение", + "ChessBase, lecture seule", + "ChessBase, schreibgeschützt", + "ChessBase, solo lectura", + "ChessBase, sola lettura", + "ChessBase, somente leitura", + "ChessBase, faqat o‘qish", + "ChessBase, тек оқу", + ], + [ + "{format}, read-only", + "{format}, только чтение", + "{format}, lecture seule", + "{format}, schreibgeschützt", + "{format}, solo lectura", + "{format}, sola lettura", + "{format}, somente leitura", + "{format}, faqat o‘qish", + "{format}, тек оқу", + ], + [ + "PGN, encoding {enc}", + "PGN, кодировка {enc}", + "PGN, encodage {enc}", + "PGN, Kodierung {enc}", + "PGN, codificación {enc}", + "PGN, codifica {enc}", + "PGN, codificação {enc}", + "PGN, kodlash {enc}", + "PGN, кодтау {enc}", + ], + [ + "Ctrl+F; again — the filters", + "Ctrl+F; ещё раз — фильтры", + "Ctrl+F ; deux fois : filtres", + "Strg+F; noch einmal — die Filter", + "Ctrl+F; otra vez — los filtros", + "Ctrl+F; di nuovo — i filtri", + "Ctrl+F; de novo — os filtros", + "Ctrl+F; yana bir marta — filtrlar", + "Ctrl+F; тағы бір рет — Ñ�үзгілер", + ], + [ + "Filters: players, tournament, years, rating… (Ctrl+F twice)", + "Фильтры: игроки, турнир, годы, рейтинг… (Ctrl+F дважды)", + "Filtres : joueurs, tournoi, années, classement… (Ctrl+F deux fois)", + "Filter: Spieler, Turnier, Jahre, Wertung… (zweimal Strg+F)", + "Filtros: jugadores, torneo, años, Elo… (Ctrl+F dos veces)", + "Filtri: giocatori, torneo, anni, Elo… (Ctrl+F due volte)", + "Filtros: jogadores, torneio, anos, rating… (Ctrl+F duas vezes)", + "Filtrlar: o‘yinchilar, turnir, yillar, reyting… (Ctrl+F ikki marta)", + "Сүзгілер: ойыншылар, турнир, жылдар, рейтинг… (Ctrl+F екі рет)", + ], + [ + "Not applied: not enough memory for position search", + "Ð�е применена: не хватает памÑ�ти длÑ� поиÑ�ка по позициÑ�м", + "Non appliquée : pas assez de mémoire pour la recherche de position", + "Nicht angewendet: zu wenig Speicher für die Stellungssuche", + "No aplicada: no hay memoria suficiente para buscar por posición", + "Non applicata: memoria insufficiente per la ricerca per posizione", + "Não aplicado: memória insuficiente para a busca por posição", + "Qo‘llanmadi: pozitsiya bo‘yicha qidirishga xotira yetmaydi", + "Қолданылмады: позициÑ� бойынша іздеуге жад жетпейді", + ], + [ + "Search", + "ПоиÑ�к", + "Recherche", + "Suche", + "Búsqueda", + "Ricerca", + "Buscar", + "Qidirish", + "Іздеу", + ], + [ + "No game of this database has an ECO code", + "Ð�и у одной партии Ñ�той базы нет кода ECO", + "Aucune partie de cette base n'a de code ECO", + "Keine Partie dieser Datenbank hat einen ECO-Code", + "Ninguna partida de esta base tiene código ECO", + "Nessuna partita di questo database ha un codice ECO", + "Nenhuma partida desta base tem código ECO", + "Bu bazadagi birorta partiyada ECO kodi yo‘q", + "Бұл базадағы бірде-бір партиÑ�ның ECO коды жоқ", + ], + [ + "No game of this database has an annotator", + "Ð�и у одной партии Ñ�той базы нет комментатора", + "Aucune partie de cette base n'a d'annotateur", + "Keine Partie dieser Datenbank hat einen Kommentator", + "Ninguna partida de esta base tiene comentarista", + "Nessuna partita di questo database ha un commentatore", + "Nenhuma partida desta base tem comentarista", + "Bu bazadagi birorta partiyada izohlovchi yo‘q", + "Бұл базадағы бірде-бір партиÑ�ның түÑ�ініктеме авторы жоқ", + ], + [ + "No game of this database has a rating", + "Ð�и у одной партии Ñ�той базы нет Эло", + "Aucune partie de cette base n'a de classement", + "Keine Partie dieser Datenbank hat eine Wertung", + "Ninguna partida de esta base tiene Elo", + "Nessuna partita di questo database ha un Elo", + "Nenhuma partida desta base tem rating", + "Bu bazadagi birorta partiyada reyting yo‘q", + "Бұл базадағы бірде-бір партиÑ�ның рейтингі жоқ", + ], + [ + "No game of this database has a year", + "Ð�и у одной партии Ñ�той базы нет года", + "Aucune partie de cette base n'a d'année", + "Keine Partie dieser Datenbank hat ein Jahr", + "Ninguna partida de esta base tiene año", + "Nessuna partita di questo database ha un anno", + "Nenhuma partida desta base tem ano", + "Bu bazadagi birorta partiyada yil yo‘q", + "Бұл базадағы бірде-бір партиÑ�ның жылы жоқ", + ], + [ + "Reset search", + "СброÑ�ить поиÑ�к", + "Réinitialiser la recherche", + "Suche zurücksetzen", + "Restablecer búsqueda", + "Azzera ricerca", + "Limpar busca", + "Qidiruvni tiklash", + "Іздеуді таÑ�тау", + ], + [ + "Reset filters and search", + "СброÑ�ить фильтры и поиÑ�к", + "Réinitialiser les filtres et la recherche", + "Filter und Suche zurücksetzen", + "Restablecer filtros y búsqueda", + "Azzera filtri e ricerca", + "Redefinir filtros e busca", + "Filtrlar va qidiruvni tiklash", + "Сүзгілер мен іздеуді таÑ�тау", + ], + [ + "moves: {n}", + "ходов: {n}", + "coups : {n}", + "Züge: {n}", + "jugadas: {n}", + "mosse: {n}", + "lances: {n}", + "yurishlar: {n}", + "жүріÑ�: {n}", + ], + [ + "Preparing the position search (once)… {p} %", + "Готовлю поиÑ�к по позициÑ�м (один раз)… {p} %", + "Préparation de la recherche de position (une fois)… {p} %", + "Stellungssuche wird vorbereitet (einmalig)… {p} %", + "Preparando la búsqueda por posición (una vez)… {p} %", + "Preparo la ricerca per posizione (una volta)… {p} %", + "Preparando a busca por posição (uma vez)… {p} %", + "Pozitsiya bo‘yicha qidiruv tayyorlanmoqda (bir marta)… {p} %", + "ПозициÑ� бойынша іздеу дайындалуда (бір рет)… {p} %", + ], + [ + "· ChessBase, read-only", + "· ChessBase, только чтение", + "· ChessBase, lecture seule", + "· ChessBase, schreibgeschützt", + "· ChessBase, solo lectura", + "· ChessBase, sola lettura", + "· ChessBase, somente leitura", + "· ChessBase, faqat o‘qish", + "· ChessBase, тек оқу", + ], + [ + "Read in place; the original files are not changed. Save a game to keep your edits.", + "ЧитаетÑ�Ñ� на меÑ�те; иÑ�ходные файлы не изменÑ�ÑŽÑ‚Ñ�Ñ�. Чтобы Ñ�охранить правки, Ñ�охраните партию.", + "Lue sur place ; les fichiers d'origine ne sont pas modifiés. Enregistrez une partie pour garder vos modifications.", + "Wird direkt gelesen; die Originaldateien bleiben unverändert. Speichern Sie eine Partie, um Ihre Änderungen zu behalten.", + "Se lee en su sitio; los archivos originales no cambian. Guarde una partida para conservar sus cambios.", + "Letto sul posto; i file originali non vengono modificati. Salva una partita per conservare le modifiche.", + "Lido no local; os arquivos originais não são alterados. Salve uma partida para manter suas edições.", + "Joyida o‘qiladi; asl fayllar o‘zgarmaydi. Tahrirlaringizni saqlash uchun partiyani saqlang.", + "Орнында оқылады; баÑ�тапқы файлдар өзгермейді. Түзетулерді Ñ�ақтау үшін партиÑ�ны Ñ�ақтаңыз.", + ], + [ + "Filters »", + "Фильтры »", + "Filtres »", + "Filter »", + "Filtros »", + "Filtri »", + "Filtros »", + "Filtrlar »", + "Сүзгілер »", + ], + [ + "« Filters", + "« Фильтры", + "« Filtres", + "« Filter", + "« Filtros", + "« Filtri", + "« Filtros", + "« Filtrlar", + "« Сүзгілер", + ], + [ + "« Filters ({n})", + "« Фильтры ({n})", + "« Filtres ({n})", + "« Filter ({n})", + "« Filtros ({n})", + "« Filtri ({n})", + "« Filtros ({n})", + "« Filtrlar ({n})", + "« Сүзгілер ({n})", + ], + [ + "Nothing found", + "Ð�ичего не найдено", + "Rien trouvé", + "Nichts gefunden", + "No se encontró nada", + "Nessun risultato", + "Nada encontrado", + "Hech narsa topilmadi", + "Ештеңе табылмады", + ], + [ + "Round", "Тур", "Ronde", "Runde", "Ronda", "Turno", "Rodada", "Tur", "Тур", + ], + [ + "Chess960: the moves cannot be read; the header and result are shown", + "Chess960: ходы не читаютÑ�Ñ�, показаны заголовок и результат", + "Chess960 : les coups ne peuvent pas être lus ; l'en-tête et le résultat sont affichés", + "Chess960: Die Züge können nicht gelesen werden; Kopf und Ergebnis werden gezeigt", + "Chess960: las jugadas no se pueden leer; se muestran la cabecera y el resultado", + "Chess960: le mosse non possono essere lette; sono mostrati intestazione e risultato", + "Chess960: os lances não podem ser lidos; o cabeçalho e o resultado são exibidos", + "Chess960: yurishlarni o‘qib bo‘lmaydi; sarlavha va natija ko‘rsatilgan", + "Chess960: жүріÑ�терді оқу мүмкін емеÑ�; тақырып пен нәтиже көрÑ�етілген", + ], + ["decimal comma", ",", ",", ",", ",", ",", ",", ",", ","], + [ + "{n} more matches…", + "ещё Ñ�овпадений: {n}…", + "{n} autres résultats…", + "{n} weitere Treffer…", + "{n} coincidencias más…", + "altri {n} risultati…", + "Mais {n} resultados…", + "Yana {n} ta moslik…", + "тағы {n} Ñ�әйкеÑ�тік…", + ], + [ + "· found {n} of {total}", + "· найдено {n} из {total}", + "· {n} trouvées sur {total}", + "· {n} von {total} gefunden", + "· {n} de {total} encontradas", + "· {n} trovate su {total}", + "· encontradas {n} de {total}", + "· {n} / {total} topildi", + "· табылды {n} / {total}", + ], + [ + "· {n} games · {t} texts", + "· {n} партий · {t} текÑ�тов", + "· {n} parties · {t} textes", + "· {n} Partien · {t} Texte", + "· {n} partidas · {t} textos", + "· {n} partite · {t} testi", + "· {n} partidas · {t} textos", + "· {n} ta partiya · {t} ta matn", + "· {n} партиÑ� · {t} мәтін", + ], + [ + "· {n} games", + "· {n} партий", + "· {n} parties", + "· {n} Partien", + "· {n} partidas", + "· {n} partite", + "· {n} partidas", + "· {n} ta partiya", + "· {n} партиÑ�", + ], + [ + "{n} thousand", + "{n} тыÑ�.", + "{n} k", + "{n} Tsd.", + "{n} mil", + "{n} mila", + "{n} mil", + "{n} ming", + "{n} мың", + ], + [ + "{n} million", + "{n} млн", + "{n} M", + "{n} Mio.", + "{n} M", + "{n} mln", + "{n} mi", + "{n} mln", + "{n} млн", + ], + // --- board themes --- + [ + "Tournament", + "ТурнирнаÑ�", + "Tournoi", + "Turnier", + "Torneo", + "Torneo", + "Torneio", + "Turnir", + "Турнир", + ], + [ + "Sand", + "ПеÑ�очнаÑ�", + "Sable", + "Sand", + "Arena", + "Sabbia", + "Areia", + "Qum", + "Құм", + ], + [ + "Coral", + "МорÑ�каÑ�", + "Corail", + "Koralle", + "Coral", + "Corallo", + "Coral", + "Marjon", + "Маржан", + ], + [ + "Wood", + "Дерево", + "Bois", + "Holz", + "Madera", + "Legno", + "Madeira", + "Yog‘och", + "Ð�ғаш", + ], + [ + "Maple", + "Клён", + "Érable", + "Ahorn", + "Arce", + "Acero", + "Bordo", + "Zarang", + "Үйеңкі", + ], + [ + "Leather", + "Кожа", + "Cuir", + "Leder", + "Cuero", + "Pelle", + "Couro", + "Charm", + "Былғары", + ], + [ + "Marble", + "Мрамор", + "Marbre", + "Marmor", + "Mármol", + "Marmo", + "Mármore", + "Marmar", + "Мәрмәр", + ], + [ + "Blue marble", + "Синий мрамор", + "Marbre bleu", + "Blauer Marmor", + "Mármol azul", + "Marmo blu", + "Mármore azul", + "Ko‘k marmar", + "Көк мәрмәр", + ], + [ + "Canvas", + "ХолÑ�Ñ‚", + "Toile", + "Leinwand", + "Lienzo", + "Tela", + "Tela", + "Mato", + "Кенеп", + ], + [ + "Metal", + "Металл", + "Métal", + "Metall", + "Metal", + "Metallo", + "Metal", + "Metall", + "Металл", + ], + [ + "Olive", + "Олива", + "Olive", + "Olive", + "Oliva", + "Oliva", + "Oliva", + "Zaytun", + "Зәйтүн", + ], + [ + "Stone", + "Камень", + "Pierre", + "Stein", + "Piedra", + "Pietra", + "Pedra", + "Tosh", + "ТаÑ�", + ], + [ + "Green plastic", + "Зелёный плаÑ�тик", + "Plastique vert", + "Grünes Plastik", + "Plástico verde", + "Plastica verde", + "Plástico verde", + "Yashil plastik", + "ЖаÑ�ыл плаÑ�тик", + ], + [ + "Purple diagonal", + "Фиолетовые диагонали", + "Diagonales violettes", + "Lila Diagonalen", + "Diagonales moradas", + "Diagonali viola", + "Diagonal roxa", + "Binafsha diagonal", + "Күлгін диагональдар", + ], + [ + "Pink pyramid", + "Розовые пирамиды", + "Pyramides roses", + "Rosa Pyramiden", + "Pirámides rosas", + "Piramidi rosa", + "Pirâmide rosa", + "Pushti piramida", + "Қызғылт пирамидалар", + ], + // --- common / window --- + [ + "Cancel", + "Отмена", + "Annuler", + "Abbrechen", + "Cancelar", + "Annulla", + "Cancelar", + "Bekor qilish", + "БаÑ� тарту", + ], + [ + "Retry", + "Повторить", + "Réessayer", + "Erneut versuchen", + "Reintentar", + "Riprova", + "Tentar de novo", + "Qayta urinish", + "Қайталау", + ], + [ + "Remove from list", + "Убрать Ñ� полки", + "Retirer de la liste", + "Aus der Liste entfernen", + "Quitar de la lista", + "Rimuovi dall'elenco", + "Remover da lista", + "Ro‘yxatdan olib tashlash", + "Тізімнен алып таÑ�тау", + ], + [ + "White", + "Белые", + "Blancs", + "Weiß", + "Blancas", + "Bianco", + "Brancas", + "Oqlar", + "Ð�қтар", + ], + [ + "Black", + "Чёрные", + "Noirs", + "Schwarz", + "Negras", + "Nero", + "Pretas", + "Qoralar", + "Қаралар", + ], + // --- notation --- + [ + "Make main line", + "Сделать главным продолжением", + "Promouvoir en ligne principale", + "Zur Hauptvariante machen", + "Convertir en línea principal", + "Rendi linea principale", + "Tornar linha principal", + "Asosiy davom qilish", + "Ð�егізгі жалғаÑ�у ету", + ], + [ + "Delete move and continuation", + "Удалить ход и продолжение", + "Supprimer le coup et la suite", + "Zug und Fortsetzung löschen", + "Eliminar jugada y continuación", + "Elimina mossa e seguito", + "Excluir lance e continuação", + "Yurish va davomini o‘chirish", + "ЖүріÑ� пен жалғаÑ�уын жою", + ], + [ + "PGN fragment that could not be parsed; kept as is", + "Фрагмент PGN, который не удалоÑ�ÑŒ разобрать; Ñ�охранÑ�етÑ�Ñ� как еÑ�ть", + "Fragment PGN non analysable ; conservé tel quel", + "Nicht lesbares PGN-Fragment; bleibt unverändert erhalten", + "Fragmento PGN no reconocido; se conserva tal cual", + "Frammento PGN non interpretabile; conservato così com'è", + "Trecho de PGN que não pôde ser lido; mantido como está", + "Tahlil qilib bo‘lmagan PGN bo‘lagi; o‘z holicha saqlanadi", + "Талдау мүмкін болмаған PGN үзіндіÑ�Ñ–; Ñ�ол күйінде Ñ�ақталады", + ], + // --- assets --- + [ + "Brown", + "КоричневаÑ�", + "Marron", + "Braun", + "Marrón", + "Marrone", + "Marrom", + "Jigarrang", + "Қоңыр", + ], + [ + "Blue", + "СинÑ�Ñ�", + "Bleu", + "Blau", + "Azul", + "Blu", + "Azul", + "Ko‘k", + "Көк", + ], + [ + "Green", + "ЗелёнаÑ�", + "Vert", + "Grün", + "Verde", + "Verde", + "Verde", + "Yashil", + "ЖаÑ�ыл", + ], + [ + "Grey", + "СераÑ�", + "Gris", + "Grau", + "Gris", + "Grigio", + "Cinza", + "Kulrang", + "Сұр", + ], + [ + "Purple", + "ФиолетоваÑ�", + "Violet", + "Lila", + "Morado", + "Viola", + "Roxo", + "Binafsha", + "Күлгін", + ], + [ + "Piano", + "Фортепиано", + "Piano", + "Klavier", + "Piano", + "Pianoforte", + "Piano", + "Fortepiano", + "Фортепиано", + ], + // --- app --- + [ + "All files", + "Ð’Ñ�е файлы", + "Tous les fichiers", + "Alle Dateien", + "Todos los archivos", + "Tutti i file", + "Todos os arquivos", + "Barcha fayllar", + "Барлық файлдар", + ], + [ + "Save game", + "Сохранить партию", + "Enregistrer la partie", + "Partie speichern", + "Guardar partida", + "Salva partita", + "Salvar partida", + "Partiyani saqlash", + "ПартиÑ�ны Ñ�ақтау", + ], + [ + "Choose the UCI engine executable", + "Выберите иÑ�полнÑ�емый файл UCI-движка", + "Choisissez l'exécutable du moteur UCI", + "UCI-Engine-Programmdatei wählen", + "Elija el ejecutable del motor UCI", + "Scegli l'eseguibile del motore UCI", + "Escolha o executável do motor UCI", + "UCI dvigatelining bajariladigan faylini tanlang", + "UCI қозғалтқышының орындалатын файлын таңдаңыз", + ], + [ + "Engine “{name}â€� added", + "Движок «{name}» добавлен", + "Moteur « {name} » ajouté", + "Engine „{name}“ hinzugefügt", + "Motor «{name}» añadido", + "Motore «{name}» aggiunto", + "Motor “{name}â€� adicionado", + "“{name}â€� dvigateli qo‘shildi", + "«{name}» қозғалтқышы қоÑ�ылды", + ], + [ + "Not a UCI engine or it failed to start: {e}", + "Это не UCI-движок или он не запуÑ�тилÑ�Ñ�: {e}", + "Ce n'est pas un moteur UCI ou il n'a pas démarré : {e}", + "Keine UCI-Engine oder Start fehlgeschlagen: {e}", + "No es un motor UCI o no se pudo iniciar: {e}", + "Non è un motore UCI o non si è avviato: {e}", + "Não é um motor UCI ou falhou ao iniciar: {e}", + "Bu UCI dvigateli emas yoki ishga tushmadi: {e}", + "Бұл UCI қозғалтқышы емеÑ� немеÑ�е Ñ–Ñ�ке қоÑ�ылмады: {e}", + ], + [ + "An open database cannot be overwritten with a single game — choose another file", + "Ð�ельзÑ� перезапиÑ�ать открытую базу одной партией — выберите другой файл", + "Impossible d'écraser une base ouverte par une seule partie — choisissez un autre fichier", + "Eine geöffnete Datenbank kann nicht mit einer einzelnen Partie überschrieben werden — andere Datei wählen", + "No se puede sobrescribir una base abierta con una sola partida: elija otro archivo", + "Non si può sovrascrivere un database aperto con una sola partita: scegli un altro file", + "Uma base aberta não pode ser sobrescrita com uma única partida — escolha outro arquivo", + "Ochiq bazani bitta partiya bilan qayta yozib bo‘lmaydi — boshqa fayl tanlang", + "Ð�шық базаны бір партиÑ�мен қайта жазуға болмайды — баÑ�қа файл таңдаңыз", + ], + [ + "Saved: {path}", + "Сохранено: {path}", + "Enregistré : {path}", + "Gespeichert: {path}", + "Guardado: {path}", + "Salvato: {path}", + "Salvo: {path}", + "Saqlandi: {path}", + "Сақталды: {path}", + ], + [ + "Save failed: {e}", + "Ошибка Ñ�охранениÑ�: {e}", + "Échec de l'enregistrement : {e}", + "Speichern fehlgeschlagen: {e}", + "Error al guardar: {e}", + "Salvataggio non riuscito: {e}", + "Falha ao salvar: {e}", + "Saqlab bo‘lmadi: {e}", + "Сақтау қатеÑ�Ñ–: {e}", + ], + [ + "Could not read the game", + "Ð�е удалоÑ�ÑŒ прочитать партию", + "Impossible de lire la partie", + "Partie konnte nicht gelesen werden", + "No se pudo leer la partida", + "Impossibile leggere la partita", + "Não foi possível ler a partida", + "Partiyani o‘qib bo‘lmadi", + "ПартиÑ�ны оқу мүмкін болмады", + ], + [ + "Add a UCI engine (for example, Stockfish)", + "Добавьте UCI-движок (например, Stockfish)", + "Ajoutez un moteur UCI (par exemple Stockfish)", + "Fügen Sie eine UCI-Engine hinzu (z. B. Stockfish)", + "Añada un motor UCI (por ejemplo, Stockfish)", + "Aggiungi un motore UCI (ad esempio Stockfish)", + "Adicionar um motor UCI (por exemplo, Stockfish)", + "UCI dvigatelini qo‘shing (masalan, Stockfish)", + "UCI қозғалтқышын қоÑ�ыңыз (мыÑ�алы, Stockfish)", + ], + [ + "The clipboard contains no recognizable PGN game", + "Ð’ буфере обмена нет раÑ�познаваемой партии PGN", + "Le presse-papiers ne contient aucune partie PGN reconnaissable", + "Die Zwischenablage enthält keine erkennbare PGN-Partie", + "El portapapeles no contiene ninguna partida PGN reconocible", + "Gli appunti non contengono una partita PGN riconoscibile", + "A área de transferência não contém uma partida PGN reconhecível", + "Almashish buferida taniladigan PGN partiyasi yo‘q", + "Ð�лмаÑ�у буферінде танылатын PGN партиÑ�Ñ�Ñ‹ жоқ", + ], + [ + "The clipboard has {count} games — the first one is open. To work with all of them, save them to a .pgn file and add it as a database", + "Ð’ буфере {count} партий — открыта перваÑ�. Чтобы работать Ñ�о вÑ�еми, Ñ�охраните их в .pgn и добавьте как базу", + "Le presse-papiers contient {count} parties — la première est ouverte. Pour toutes les utiliser, enregistrez-les dans un fichier .pgn et ajoutez-le comme base", + "Die Zwischenablage enthält {count} Partien — die erste ist geöffnet. Um alle zu nutzen, speichern Sie sie als .pgn und fügen Sie sie als Datenbank hinzu", + "El portapapeles tiene {count} partidas; se abrió la primera. Para usarlas todas, guárdelas en un .pgn y añádalo como base", + "Negli appunti ci sono {count} partite: è aperta la prima. Per usarle tutte, salvale in un file .pgn e aggiungilo come database", + "A área de transferência tem {count} partidas — a primeira está aberta. Para trabalhar com todas, salve-as em um arquivo .pgn e adicione-o como base", + "Buferda {count} ta partiya — birinchisi ochildi. Hammasi bilan ishlash uchun ularni .pgn fayliga saqlang va baza sifatida qo‘shing", + "Ð�лмаÑ�у буферінде {count} партиÑ� бар — біріншіÑ�Ñ– ашылды. Барлығымен жұмыÑ� Ñ–Ñ�теу үшін оларды .pgn файлына Ñ�ақтап, база ретінде қоÑ�ыңыз", + ], + [ + "The clipboard is empty or unavailable", + "Буфер обмена пуÑ�Ñ‚ или недоÑ�тупен", + "Le presse-papiers est vide ou indisponible", + "Die Zwischenablage ist leer oder nicht verfügbar", + "El portapapeles está vacío o no disponible", + "Gli appunti sono vuoti o non disponibili", + "A área de transferência está vazia ou indisponível", + "Almashish buferi bo‘sh yoki mavjud emas", + "Ð�лмаÑ�у буфері боÑ� немеÑ�е қолжетімÑ�із", + ], + [ + "Game modified", + "ПартиÑ� изменена", + "Partie modifiée", + "Partie geändert", + "Partida modificada", + "Partita modificata", + "Partida alterada", + "Partiya o‘zgartirildi", + "ПартиÑ� өзгерді", + ], + [ + "The source PGN is not changed. Save the changes to a separate file?", + "ИÑ�ходный PGN не менÑ�етÑ�Ñ�. Сохранить изменениÑ� в отдельный файл?", + "Le PGN source n'est pas modifié. Enregistrer les modifications dans un fichier séparé ?", + "Die Quell-PGN wird nicht verändert. Änderungen in eine separate Datei speichern?", + "El PGN original no se modifica. ¿Guardar los cambios en un archivo aparte?", + "Il PGN originale non viene modificato. Salvare le modifiche in un file separato?", + "O PGN original não é alterado. Salvar as alterações em um arquivo separado?", + "Asl PGN o‘zgarmaydi. O‘zgarishlar alohida faylga saqlansinmi?", + "БаÑ�тапқы PGN өзгермейді. ӨзгеріÑ�терді бөлек файлға Ñ�ақтау керек пе?", + ], + [ + "Save as…", + "Сохранить как…", + "Enregistrer sous…", + "Speichern unter…", + "Guardar como…", + "Salva con nome…", + "Salvar como…", + "Boshqacha saqlash…", + "БаÑ�қаша Ñ�ақтау…", + ], + [ + "Don't save", + "Ð�е Ñ�охранÑ�ть", + "Ne pas enregistrer", + "Nicht speichern", + "No guardar", + "Non salvare", + "Não salvar", + "Saqlamaslik", + "Сақтамау", + ], + // --- analysis --- + [ + "The engine hung and was stopped", + "Движок завиÑ� и был оÑ�тановлен", + "Le moteur ne répondait plus et a été arrêté", + "Die Engine reagierte nicht und wurde beendet", + "El motor se bloqueó y se detuvo", + "Il motore si è bloccato ed è stato fermato", + "O motor travou e foi parado", + "Dvigatel qotib qoldi va to‘xtatildi", + "Қозғалтқыш қатып қалды және тоқтатылды", + ], + [ + "The engine exited ({s})", + "Движок завершилÑ�Ñ� ({s})", + "Le moteur s'est arrêté ({s})", + "Die Engine wurde beendet ({s})", + "El motor terminó ({s})", + "Il motore è terminato ({s})", + "O motor encerrou ({s})", + "Dvigatel yopildi ({s})", + "Қозғалтқыш жұмыÑ�ын аÑ�қтады ({s})", + ], + [ + "The engine exited", + "Движок завершилÑ�Ñ�", + "Le moteur s'est arrêté", + "Die Engine wurde beendet", + "El motor terminó", + "Il motore è terminato", + "O motor encerrou", + "Dvigatel yopildi", + "Қозғалтқыш жұмыÑ�ын аÑ�қтады", + ], + // --- settings --- + [ + "Settings", + "Ð�аÑ�тройки", + "Paramètres", + "Einstellungen", + "Ajustes", + "Impostazioni", + "Configurações", + "Sozlamalar", + "Баптаулар", + ], + [ + "Engines", + "Движки", + "Moteurs", + "Engines", + "Motores", + "Motori", + "Motores", + "Dvigatellar", + "Қозғалтқыштар", + ], + [ + "Board & pieces", + "ДоÑ�ка и фигуры", + "Échiquier et pièces", + "Brett und Figuren", + "Tablero y piezas", + "Scacchiera e pezzi", + "Tabuleiro e peças", + "Taxta va figuralar", + "Тақта және фигуралар", + ], + [ + "Sound", + "Звук", + "Son", + "Ton", + "Sonido", + "Audio", + "Som", + "Ovoz", + "ДыбыÑ�", + ], + [ + "Interface", + "ИнтерфейÑ�", + "Interface", + "Oberfläche", + "Interfaz", + "Interfaccia", + "Interface", + "Interfeys", + "ИнтерфейÑ�", + ], + [ + "Language:", + "Язык:", + "Langue :", + "Sprache:", + "Idioma:", + "Lingua:", + "Idioma:", + "Til:", + "Тіл:", + ], + [ + "Theme:", + "Тема:", + "Thème :", + "Design:", + "Tema:", + "Tema:", + "Tema:", + "Mavzu:", + "Тақырып:", + ], + [ + "Dark", + "ТёмнаÑ�", + "Sombre", + "Dunkel", + "Oscuro", + "Scuro", + "Escuro", + "Qorong‘i", + "Қараңғы", + ], + [ + "Light", + "СветлаÑ�", + "Clair", + "Hell", + "Claro", + "Chiaro", + "Claro", + "Yorug‘", + "Ð�шық", + ], + [ + "UCI engines. The active one is used for game analysis. Time, lines, threads and memory are set with âš™ in the analysis panel.", + "UCI-движки. Ð�ктивный иÑ�пользуетÑ�Ñ� длÑ� анализа партии. ВремÑ�, линии, потоки и памÑ�ть наÑ�траиваютÑ�Ñ� кнопкой âš™ в панели анализа.", + "Moteurs UCI. Le moteur actif sert à l'analyse. Temps, lignes, threads et mémoire se règlent avec âš™ dans le panneau d'analyse.", + "UCI-Engines. Die aktive Engine wird für die Analyse verwendet. Zeit, Varianten, Threads und Speicher stellen Sie mit âš™ im Analysebereich ein.", + "Motores UCI. El activo se usa para analizar la partida. El tiempo, las líneas, los hilos y la memoria se ajustan con âš™ en el panel de análisis.", + "Motori UCI. Quello attivo viene usato per l'analisi. Tempo, linee, thread e memoria si impostano con âš™ nel pannello di analisi.", + "Motores UCI. O ativo é usado na análise de partidas. Tempo, linhas, threads e memória são definidos com âš™ no painel de análise.", + "UCI dvigatellari. Faoli partiya tahlilida ishlatiladi. Vaqt, liniyalar, oqimlar va xotira tahlil panelidagi âš™ bilan sozlanadi.", + "UCI қозғалтқыштары. БелÑ�ендіÑ�Ñ– партиÑ�ны талдауға қолданылады. Уақыт, варианттар, ағындар және жад талдау панеліндегі âš™ арқылы бапталады.", + ], + [ + "Make active", + "Сделать активным", + "Rendre actif", + "Aktivieren", + "Activar", + "Rendi attivo", + "Tornar ativo", + "Faol qilish", + "БелÑ�енді ету", + ], + [ + "Threads", + "Потоки", + "Threads", + "Threads", + "Hilos", + "Thread", + "Threads", + "Oqimlar", + "Ð�ғындар", + ], + [ + "+ Add engine…", + "+ Добавить движок…", + "+ Ajouter un moteur…", + "+ Engine hinzufügen…", + "+ Añadir motor…", + "+ Aggiungi motore…", + "+ Adicionar motor…", + "+ Dvigatel qo‘shish…", + "+ Қозғалтқыш қоÑ�у…", + ], + [ + "Speeding up search in this database (once)… {p} %", + "УÑ�корÑ�ÑŽ поиÑ�к по Ñ�той базе (один раз)… {p} %", + "Accélération de la recherche dans cette base (une seule fois)… {p} %", + "Suche in dieser Datenbank wird beschleunigt (einmalig)… {p} %", + "Acelerando la búsqueda en esta base (una sola vez)… {p} %", + "Velocizzo la ricerca in questa base (una volta sola)… {p} %", + "Acelerando a busca nesta base (uma vez)… {p} %", + "Bu bazada qidiruv tezlashtirilmoqda (bir marta)… {p} %", + "Бұл базада іздеу жылдамдатылуда (бір рет)… {p} %", + ], + [ + "An index for fast position search is built once and kept in the cache. Searching works meanwhile, only slower.", + "СтроитÑ�Ñ� индекÑ� длÑ� быÑ�трого поиÑ�ка по позиции. Это делаетÑ�Ñ� один раз, результат хранитÑ�Ñ� в кÑ�ше. Пока идёт подготовка, поиÑ�к работает, но медленнее.", + "Un index pour la recherche rapide par position est construit une fois et conservé dans le cache. La recherche fonctionne en attendant, mais plus lentement.", + "Ein Index für die schnelle Stellungssuche wird einmal erstellt und im Cache behalten. Die Suche funktioniert währenddessen, nur langsamer.", + "Se construye una vez un índice para la búsqueda rápida por posición y se guarda en la caché. Mientras tanto la búsqueda funciona, aunque más despacio.", + "Un indice per la ricerca rapida per posizione viene costruito una volta e tenuto nella cache. Nel frattempo la ricerca funziona, solo più lentamente.", + "Um índice para busca rápida por posição é criado uma vez e guardado no cache. Enquanto isso a busca funciona, só que mais devagar.", + "Tez pozitsiya qidiruvi uchun indeks bir marta tuziladi va keshda saqlanadi. Bu orada qidiruv ishlaydi, faqat sekinroq.", + "ПозициÑ�ны жылдам іздеу индекÑ�Ñ– бір рет құрылып, кÑ�ште Ñ�ақталады. ОÑ�Ñ‹ уақытта іздеу жұмыÑ� Ñ–Ñ�тейді, тек баÑ�уырақ.", + ], + [ + "Add a database to the library to see what was played here.", + "Добавьте базу в библиотеку, чтобы видеть, что здеÑ�ÑŒ играли.", + "Ajoutez une base à la bibliothèque pour voir ce qui a été joué ici.", + "Fügen Sie der Bibliothek eine Datenbank hinzu, um zu sehen, was hier gespielt wurde.", + "Añade una base a la biblioteca para ver qué se jugó aquí.", + "Aggiungi una base alla libreria per vedere cosa è stato giocato qui.", + "Adicione uma base à biblioteca para ver o que foi jogado aqui.", + "Bu yerda nima o‘ynalganini ko‘rish uchun kutubxonaga baza qo‘shing.", + "Мұнда не ойналғанын көру үшін кітапханаға база қоÑ�ыңыз.", + ], + [ + "Known up to", + "Ð’ базе до хода", + "Connu jusqu'à", + "Bekannt bis", + "Conocida hasta", + "Nota fino a", + "Na base até", + "Bazada shu yurishgacha", + "Базада оÑ�Ñ‹ жүріÑ�ке дейін", + ], + [ + "Not even the start of the game is in this database", + "Даже начала Ñ�той партии нет в базе", + "Même le début de la partie n'est pas dans cette base", + "Nicht einmal der Anfang der Partie ist in dieser Datenbank", + "Ni siquiera el inicio de la partida está en esta base", + "Nemmeno l'inizio della partita è in questa base", + "Nem o início da partida está nesta base", + "Bu partiyaning hatto boshi ham bazada yo‘q", + "Бұл базада партиÑ�ның баÑ�Ñ‹ да жоқ", + ], + [ + "Nothing was played here in this database", + "Ð’ Ñ�той базе отÑ�юда не играли", + "Rien n'a été joué ici dans cette base", + "In dieser Datenbank wurde hier nichts gespielt", + "En esta base no se jugó nada aquí", + "In questa base qui non si è giocato nulla", + "Nada foi jogado aqui nesta base", + "Bu bazada bu yerdan o‘ynalmagan", + "Бұл базада оÑ�Ñ‹ жерден ойналмаған", + ], + [ + "Open this game at this position", + "Открыть Ñ�ту партию на Ñ�той позиции", + "Ouvrir cette partie à cette position", + "Diese Partie an dieser Stellung öffnen", + "Abrir esta partida en esta posición", + "Apri questa partita in questa posizione", + "Abrir esta partida nesta posição", + "Bu partiyani shu pozitsiyada ochish", + "Бұл партиÑ�ны оÑ�Ñ‹ позициÑ�да ашу", + ], + [ + "Opening the database…", + "Открываю базу…", + "Ouverture de la base…", + "Datenbank wird geöffnet…", + "Abriendo la base…", + "Apertura della base…", + "Abrindo a base…", + "Baza ochilmoqda…", + "База ашылуда…", + ], + [ + "Reference", + "Справочник", + "Référence", + "Referenz", + "Referencia", + "Riferimento", + "Referência", + "Maʼlumotnoma", + "Ð�нықтамалық", + ], + [ + "Strongest games", + "Сильнейшие партии", + "Parties les plus fortes", + "Stärkste Partien", + "Partidas más fuertes", + "Partite più forti", + "Partidas mais fortes", + "Eng kuchli partiyalar", + "Ең күшті партиÑ�лар", + ], + [ + "The last move of the game still played in other games of this database", + "ПоÑ�ледний ход партии, который ещё вÑ�тречаетÑ�Ñ� в других партиÑ�Ñ… Ñ�той базы", + "Le dernier coup de la partie encore joué dans d'autres parties de cette base", + "Der letzte Zug der Partie, der noch in anderen Partien dieser Datenbank vorkommt", + "La última jugada de la partida que aún aparece en otras partidas de esta base", + "L'ultima mossa della partita ancora giocata in altre partite di questa base", + "O último lance da partida que ainda aparece em outras partidas desta base", + "Bu bazaning boshqa partiyalarida hali uchraydigan oxirgi yurish", + "Бұл базаның баÑ�қа партиÑ�ларында әлі кездеÑ�етін партиÑ�ның Ñ�оңғы жүріÑ�Ñ–", + ], + [ + "The whole game is in this database", + "Ð’Ñ�Ñ� партиÑ� еÑ�ть в Ñ�той базе", + "Toute la partie est dans cette base", + "Die ganze Partie ist in dieser Datenbank", + "Toda la partida está en esta base", + "L'intera partita è in questa base", + "A partida inteira está nesta base", + "Butun partiya bu bazada bor", + "Бүкіл партиÑ� оÑ�Ñ‹ базада бар", + ], + [ + "This database cannot be opened: {e}", + "Эту базу не удалоÑ�ÑŒ открыть: {e}", + "Impossible d'ouvrir cette base : {e}", + "Diese Datenbank lässt sich nicht öffnen: {e}", + "No se puede abrir esta base: {e}", + "Impossibile aprire questa base: {e}", + "Não é possível abrir esta base: {e}", + "Bu bazani ochib bo‘lmadi: {e}", + "Бұл базаны ашу мүмкін болмады: {e}", + ], + [ + "What was played in this position in a database", + "Что играли в Ñ�той позиции в выбранной базе", + "Ce qui a été joué dans cette position dans une base", + "Was in dieser Stellung in einer Datenbank gespielt wurde", + "Qué se jugó en esta posición en una base", + "Cosa è stato giocato in questa posizione in una base", + "O que foi jogado nesta posição em uma base", + "Bazada bu pozitsiyada nima o‘ynalgan", + "Базада оÑ�Ñ‹ позициÑ�да не ойналды", + ], + [ + "Database", + "База", + "Base", + "Datenbank", + "Base", + "Base", + "Base", + "Baza", + "База", + ], + [ + "This position is not in this database", + "Ð’ Ñ�той базе такой позиции нет", + "Cette position n'est pas dans cette base", + "Diese Stellung ist nicht in dieser Datenbank", + "Esta posición no está en esta base", + "Questa posizione non è in questa base", + "Esta posição não está nesta base", + "Bu pozitsiya bu bazada yo‘q", + "Бұл позициÑ� оÑ�Ñ‹ базада жоқ", + ], + [ + "Click: show its games and an arrow; double click: play it", + "Клик — показать партии Ñ� ходом и Ñ�трелку; двойной клик — Ñ�ыграть ход", + "Clic : montrer ses parties et une flèche ; double clic : jouer le coup", + "Klick: Partien und Pfeil zeigen; Doppelklick: Zug spielen", + "Clic: ver sus partidas y una flecha; doble clic: jugarla", + "Clic: mostra partite e freccia; doppio clic: gioca la mossa", + "Clique: mostrar suas partidas e uma seta; clique duplo: jogar o lance", + "Bosish: partiyalari va strelkani ko‘rsatish; ikki marta bosish: yurishni qilish", + "БаÑ�у: партиÑ�лары мен көрÑ�еткіні көрÑ�ету; қоÑ� баÑ�у: жүріÑ�ті жаÑ�ау", + ], + [ + "Games", + "Партии", + "Parties", + "Partien", + "Partidas", + "Partite", + "Partidas", + "Partiyalar", + "ПартиÑ�", + ], + [ + "Games that played the move", + "Партий, где Ñ�ыграли Ñ�тот ход", + "Parties où ce coup a été joué", + "Partien mit diesem Zug", + "Partidas con esta jugada", + "Partite con questa mossa", + "Partidas que jogaram o lance", + "Bu yurish qilingan partiyalar", + "Бұл жүріÑ� жаÑ�алған партиÑ�лар", + ], + [ + "Share of the games in this position", + "ДолÑ� партий в Ñ�той позиции", + "Part des parties dans cette position", + "Anteil der Partien in dieser Stellung", + "Proporción de partidas en esta posición", + "Quota delle partite in questa posizione", + "Parcela das partidas nesta posição", + "Bu pozitsiyadagi partiyalar ulushi", + "ОÑ�Ñ‹ позициÑ�дағы партиÑ�лар үлеÑ�Ñ–", + ], + [ + "White wins · draws · Black wins", + "Победы белых · ничьи · победы чёрных", + "Gains des Blancs · nulles · gains des Noirs", + "Weißsiege · Remis · Schwarzsiege", + "Victorias blancas · tablas · victorias negras", + "Vittorie del Bianco · patte · vittorie del Nero", + "Vitórias das brancas · empates · vitórias das pretas", + "Oqlar yutgan · durang · qoralar yutgan", + "Ð�қтар жеңіÑ�Ñ– · тең ойын · Қаралар жеңіÑ�Ñ–", + ], + [ + "White's score", + "Очки белых", + "Score des Blancs", + "Punkte von Weiß", + "Puntuación de las blancas", + "Punteggio del Bianco", + "Pontuação das brancas", + "Oqlar ochkosi", + "Ð�қтардың ұпайы", + ], + [ + "Avg Elo", + "Ср. Эло", + "Elo moy.", + "Ø Elo", + "Elo med.", + "Elo medio", + "Elo méd.", + "O‘rt. Elo", + "Орт. Elo", + ], + [ + "Average rating, games where both are known", + "Средний рейтинг партий, где извеÑ�тны оба", + "Classement moyen, parties où les deux sont connus", + "Durchschnittliche Wertung, Partien mit beiden Wertungen", + "Elo medio, partidas con ambos conocidos", + "Elo medio, partite con entrambi noti", + "Rating médio, em partidas em que ambos são conhecidos", + "O‘rtacha reyting, ikkalasi maʼlum partiyalar", + "Орташа рейтинг, екеуінің де рейтингі белгілі партиÑ�лар", + ], + [ + "The latest game", + "ПоÑ�леднÑ�Ñ� партиÑ�", + "La partie la plus récente", + "Die neueste Partie", + "La partida más reciente", + "La partita più recente", + "A partida mais recente", + "Eng so‘nggi partiya", + "Ең Ñ�оңғы партиÑ�", + ], + [ + "Best players", + "Лучшие игроки", + "Meilleurs joueurs", + "Beste Spieler", + "Mejores jugadores", + "Migliori giocatori", + "Melhores jogadores", + "Eng yaxshi o‘yinchilar", + "Үздік ойыншылар", + ], + [ + "The strongest players who played the move", + "Сильнейшие игроки, Ñ�ыгравшие Ñ�тот ход", + "Les joueurs les plus forts ayant joué ce coup", + "Die stärksten Spieler mit diesem Zug", + "Los jugadores más fuertes que jugaron esta jugada", + "I giocatori più forti che hanno giocato la mossa", + "Os jogadores mais fortes que jogaram o lance", + "Bu yurishni qilgan eng kuchli o‘yinchilar", + "Бұл жүріÑ�ті жаÑ�аған ең күшті ойыншылар", + ], + [ + "Ended", + "ЗакончилиÑ�ÑŒ", + "Terminées", + "Beendet", + "Terminadas", + "Terminate", + "Terminaram", + "Tugagan", + "Ð�Ñ�қталды", + ], + [ + "All moves", + "Ð’Ñ�е ходы", + "Tous les coups", + "Alle Züge", + "Todas las jugadas", + "Tutte le mosse", + "Todos os lances", + "Barcha yurishlar", + "Барлық жүріÑ�", + ], + [ + "Strongest first", + "Сильнейшие Ñ�верху", + "Les plus fortes d'abord", + "Stärkste zuerst", + "Las más fuertes primero", + "Prima le più forti", + "Mais fortes primeiro", + "Avval eng kuchlilar", + "Ð�лдымен күштілері", + ], + [ + "Res.", "Рез.", "Rés.", "Erg.", "Res.", "Ris.", "Res.", "Nat.", "Ð�әт.", + ], + [ + "Newest first", + "Ð�овые Ñ�верху", + "Les plus récentes d'abord", + "Neueste zuerst", + "Las más recientes primero", + "Prima le più recenti", + "Mais recentes primeiro", + "Avval eng yangilar", + "Ð�лдымен жаңалары", + ], + [ + "Then", + "Дальше", + "Ensuite", + "Weiter", + "Después", + "Poi", + "Depois", + "Keyin", + "Әрі қарай", + ], + [ + "How the game went on from this position", + "Как партиÑ� продолжилаÑ�ÑŒ из Ñ�той позиции", + "Comment la partie a continué depuis cette position", + "Wie die Partie von hier weiterging", + "Cómo siguió la partida desde esta posición", + "Come è proseguita la partita da qui", + "Como a partida continuou a partir desta posição", + "Partiya bu pozitsiyadan qanday davom etgan", + "ПартиÑ� оÑ�Ñ‹ позициÑ�дан қалай жалғаÑ�ты", + ], + [ + "Double click: open this game at this position", + "Двойной клик — открыть партию на Ñ�той позиции", + "Double clic : ouvrir la partie à cette position", + "Doppelklick: Partie an dieser Stellung öffnen", + "Doble clic: abrir la partida en esta posición", + "Doppio clic: apri la partita in questa posizione", + "Clique duplo: abrir esta partida nesta posição", + "Ikki marta bosish: partiyani shu pozitsiyada ochish", + "ҚоÑ� баÑ�у: бұл партиÑ�ны оÑ�Ñ‹ позициÑ�да ашу", + ], + [ + "Games with {m}", + "Партии Ñ� ходом {m}", + "Parties avec {m}", + "Partien mit {m}", + "Partidas con {m}", + "Partite con {m}", + "Partidas com {m}", + "{m} yurishli partiyalar", + "{m} жүріÑ�Ñ– бар партиÑ�лар", + ], + [ + "· the {n} strongest shown", + "· показаны {n} Ñ�ильнейших", + "· les {n} plus fortes affichées", + "· die {n} stärksten gezeigt", + "· se muestran las {n} más fuertes", + "· mostrate le {n} più forti", + "· exibidas as {n} mais fortes", + "· eng kuchli {n} tasi ko‘rsatilgan", + "· ең күшті {n} партиÑ� көрÑ�етілген", + ], + [ + "Back to {game}: it has unsaved changes", + "Возврат к партии {game}: в ней неÑ�охранённые изменениÑ�", + "Retour à {game} : elle a des modifications non enregistrées", + "Zurück zu {game}: sie hat ungespeicherte Änderungen", + "Vuelta a {game}: tiene cambios sin guardar", + "Ritorno a {game}: ha modifiche non salvate", + "Voltar para {game}: há alterações não salvas", + "{game}ga qaytish: unda saqlanmagan o‘zgarishlar bor", + "{game} партиÑ�Ñ�ына оралу: онда Ñ�ақталмаған өзгеріÑ�тер бар", + ], + [ + "The game this one was opened from, as you left it", + "ПартиÑ�, из которой открыта Ñ�та, — в том виде, как вы её оÑ�тавили", + "La partie d'où celle-ci a été ouverte, telle que vous l'avez laissée", + "Die Partie, aus der diese geöffnet wurde, so wie Sie sie verlassen haben", + "La partida desde la que se abrió esta, tal como la dejaste", + "La partita da cui è stata aperta questa, come l'hai lasciata", + "A partida de onde esta foi aberta, como você a deixou", + "Bu partiya ochilgan partiya, siz qoldirgan holatda", + "Бұл партиÑ� ашылған партиÑ�, Ñ�із қалдырған күйінде", + ], + [ + "The game this one was opened from, as you left it (Esc)", + "ПартиÑ�, из которой открыта Ñ�та, — в том виде, как вы её оÑ�тавили (Esc)", + "La partie d'où celle-ci a été ouverte, telle que vous l'avez laissée (Esc)", + "Die Partie, aus der diese geöffnet wurde, so wie Sie sie verlassen haben (Esc)", + "La partida desde la que se abrió esta, tal como la dejaste (Esc)", + "La partita da cui è stata aperta questa, come l'hai lasciata (Esc)", + "A partida de onde esta foi aberta, como você a deixou (Esc)", + "Bu partiya ochilgan partiya, siz qoldirgan holatda (Esc)", + "Бұл партиÑ� ашылған партиÑ�, Ñ�із қалдырған күйінде (Esc)", + ], + [ + "⬅ Back to {game}", + "⬅ К партии {game}", + "⬅ Retour à {game}", + "⬅ Zurück zu {game}", + "⬅ Volver a {game}", + "⬅ Torna a {game}", + "⬅ Voltar para {game}", + "⬅ {game}ga qaytish", + "⬅ {game} партиÑ�Ñ�ына", + ], + [ + "not open", + "не открыта", + "non ouverte", + "nicht geöffnet", + "no abierta", + "non aperta", + "não aberta", + "ochilmagan", + "ашық емеÑ�", + ], + [ + "Comparing the game with the database…", + "СверÑ�ÑŽ партию Ñ� базой…", + "Comparaison de la partie avec la base…", + "Partie wird mit der Datenbank verglichen…", + "Comparando la partida con la base…", + "Confronto la partita con la base…", + "Comparando a partida com a base…", + "Partiya baza bilan solishtirilmoqda…", + "ПартиÑ� базамен Ñ�алыÑ�тырылуда…", + ], + [ + "This game is in the database", + "Эта партиÑ� еÑ�ть в базе", + "Cette partie est dans la base", + "Diese Partie ist in der Datenbank", + "Esta partida está en la base", + "Questa partita è nella base", + "Esta partida está na base", + "Bu partiya bazada bor", + "Бұл партиÑ� базада бар", + ], + [ + "open it", + "открыть", + "l'ouvrir", + "öffnen", + "abrirla", + "aprila", + "abrir", + "ochish", + "ашу", + ], + [ + "Open the copy of this game from the database at this position", + "Открыть копию Ñ�той партии из базы на Ñ�той позиции", + "Ouvrir la copie de cette partie de la base à cette position", + "Die Kopie dieser Partie aus der Datenbank an dieser Stellung öffnen", + "Abrir la copia de esta partida de la base en esta posición", + "Apri la copia di questa partita dalla base in questa posizione", + "Abrir a cópia desta partida da base nesta posição", + "Bu partiyaning bazadagi nusxasini shu pozitsiyada ochish", + "Бұл партиÑ�ның базадағы көшірмеÑ�ін оÑ�Ñ‹ позициÑ�да ашу", + ], + [ + "This position could not be counted", + "Ð�е удалоÑ�ÑŒ поÑ�читать Ñ�ту позицию", + "Impossible de compter cette position", + "Diese Stellung konnte nicht gezählt werden", + "No se pudo contar esta posición", + "Impossibile contare questa posizione", + "Não foi possível contar esta posição", + "Bu pozitsiyani hisoblab bo‘lmadi", + "Бұл позициÑ�ны еÑ�ептеу мүмкін болмады", + ], + [ + "Click: show its games and an arrow. Double click: play the move (it is added to the game as a variation if the game has another move; Ctrl+Z undoes it)", + "Клик — показать партии Ñ� Ñ�тим ходом и Ñ�трелку. Двойной клик — Ñ�ыграть ход (еÑ�ли в партии другой ход, добавитÑ�Ñ� вариант; Ctrl+Z отменÑ�ет)", + "Clic : montrer ses parties et une flèche. Double clic : jouer le coup (ajouté en variante si la partie a un autre coup ; Ctrl+Z annule)", + "Klick: Partien und Pfeil zeigen. Doppelklick: Zug spielen (als Variante, wenn die Partie anders weitergeht; Strg+Z macht es rückgängig)", + "Clic: ver sus partidas y una flecha. Doble clic: jugarla (se añade como variante si la partida tiene otra jugada; Ctrl+Z deshace)", + "Clic: mostra partite e freccia. Doppio clic: gioca la mossa (aggiunta come variante se la partita ha un'altra mossa; Ctrl+Z annulla)", + "Clique: mostrar suas partidas e uma seta. Clique duplo: jogar o lance (entra na partida como variante se a partida tiver outro lance; Ctrl+Z desfaz)", + "Bosish: partiyalari va strelkani ko‘rsatish. Ikki marta bosish: yurishni qilish (partiyada boshqa yurish bo‘lsa, variant sifatida qo‘shiladi; Ctrl+Z bekor qiladi)", + "БаÑ�у: партиÑ�лары мен көрÑ�еткіні көрÑ�ету. ҚоÑ� баÑ�у: жүріÑ�ті жаÑ�ау (партиÑ�да баÑ�қа жүріÑ� болÑ�а, вариант ретінде қоÑ�ылады; Ctrl+Z болдырмайды)", + ], + [ + "Chapters", + "Главы", + "Chapitres", + "Kapitel", + "Capítulos", + "Capitoli", + "Capítulos", + "Boblar", + "Тараулар", + ], + [ + "Chapters that play the move", + "Главы, где Ñ�ыгран Ñ�тот ход", + "Chapitres où ce coup est joué", + "Kapitel mit diesem Zug", + "Capítulos con esta jugada", + "Capitoli con questa mossa", + "Capítulos que jogam o lance", + "Bu yurish qilingan boblar", + "Бұл жүріÑ� жаÑ�алған тараулар", + ], + [ + "The move played in this game", + "Ход, Ñ�ыгранный в Ñ�той партии", + "Le coup joué dans cette partie", + "Der in dieser Partie gespielte Zug", + "La jugada de esta partida", + "La mossa giocata in questa partita", + "O lance jogado nesta partida", + "Bu partiyada qilingan yurish", + "Бұл партиÑ�да жаÑ�алған жүріÑ�", + ], + [ + "all in the library âž¡", + "вÑ�е в библиотеке âž¡", + "toutes dans la bibliothèque âž¡", + "alle in der Bibliothek âž¡", + "todas en la biblioteca âž¡", + "tutte nella libreria âž¡", + "todas na biblioteca âž¡", + "barchasi kutubxonada âž¡", + "кітапханада бәрі âž¡", + ], + [ + "Open this position on the search board of this database", + "Открыть Ñ�ту позицию на доÑ�ке поиÑ�ка Ñ�той базы", + "Ouvrir cette position sur l'échiquier de recherche de cette base", + "Diese Stellung auf dem Suchbrett dieser Datenbank öffnen", + "Abrir esta posición en el tablero de búsqueda de esta base", + "Apri questa posizione sulla scacchiera di ricerca di questa base", + "Abrir esta posição no tabuleiro de busca desta base", + "Bu pozitsiyani shu bazaning qidiruv taxtasida ochish", + "Бұл позициÑ�ны оÑ�Ñ‹ базаның іздеу тақтаÑ�ында ашу", + ], + [ + "in the game {m}", + "в партии {m}", + "dans la partie {m}", + "in der Partie {m}", + "en la partida {m}", + "nella partita {m}", + "na partida {m}", + "partiyada {m}", + "партиÑ�да {m}", + ], + [ + "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", + "Ð�е хватает памÑ�ти длÑ� поиÑ�ка по позиции в Ñ�той базе: нужно ещё около {n} МБ. Закройте другие программы и попробуйте ещё раз.", + "Mémoire insuffisante pour la recherche par position dans cette base : il manque environ {n} Mo. Fermez d'autres programmes et réessayez.", + "Nicht genug Speicher für die Stellungssuche in dieser Datenbank: es fehlen etwa {n} MB. Schließen Sie andere Programme und versuchen Sie es erneut.", + "No hay memoria suficiente para buscar por posición en esta base: faltan unos {n} MB. Cierra otros programas y vuelve a intentarlo.", + "Memoria insufficiente per la ricerca per posizione in questa base: mancano circa {n} MB. Chiudi altri programmi e riprova.", + "Memória insuficiente para a busca por posição nesta base: faltam cerca de {n} MB. Feche outros programas e tente de novo.", + "Bu bazada pozitsiya bo‘yicha qidirishga xotira yetmaydi: yana taxminan {n} MB kerak. Boshqa dasturlarni yopib, qayta urinib ko‘ring.", + "Бұл базада позициÑ� бойынша іздеуге жад жетпейді: тағы шамамен {n} МБ керек. БаÑ�қа бағдарламаларды жауып, қайталап көріңіз.", + ], + [ + "The games of this database leave this one at its first move", + "Партии Ñ�той базы раÑ�ходÑ�Ñ‚Ñ�Ñ� Ñ� Ñ�той уже на первом ходу", + "Les parties de cette base quittent celle-ci dès le premier coup", + "Die Partien dieser Datenbank weichen schon im ersten Zug ab", + "Las partidas de esta base se separan de esta ya en la primera jugada", + "Le partite di questa base si separano da questa già alla prima mossa", + "As partidas desta base se separam desta já no primeiro lance", + "Bu baza partiyalari birinchi yurishdayoq bundan ajraladi", + "Бұл базаның партиÑ�лары бұл партиÑ�дан бірінші жүріÑ�те-ақ ажырайды", + ], + [ + "Try again", + "Попробовать ещё раз", + "Réessayer", + "Erneut versuchen", + "Reintentar", + "Riprova", + "Tentar de novo", + "Qayta urinib ko‘rish", + "Қайталап көру", + ], + [ + "· the {n} newest shown", + "· показаны {n} новых", + "· les {n} plus récentes affichées", + "· die {n} neuesten gezeigt", + "· se muestran las {n} más recientes", + "· mostrate le {n} più recenti", + "· exibidas as {n} mais recentes", + "· eng yangi {n} tasi ko‘rsatilgan", + "· ең жаңа {n} партиÑ� көрÑ�етілген", + ], + [ + "No other games reached this position", + "Других партий Ñ� Ñ�той позицией нет", + "Aucune autre partie n'a atteint cette position", + "Keine andere Partie erreichte diese Stellung", + "Ninguna otra partida llegó a esta posición", + "Nessun'altra partita ha raggiunto questa posizione", + "Nenhuma outra partida chegou a esta posição", + "Bu pozitsiyaga boshqa partiyalar kelmagan", + "Бұл позициÑ�ға баÑ�қа партиÑ� жетпеген", + ], + [ + "Novelty:", + "Ð�овинка:", + "Nouveauté :", + "Neuerung:", + "Novedad:", + "Novità:", + "Novidade:", + "Yangilik:", + "Жаңалық:", + ], + [ + "The first move of this game that no other game of this database played; before it the game followed games of the database", + "Первый ход Ñ�той партии, которого нет ни в одной другой партии базы; до него партиÑ� шла по партиÑ�м базы", + "Le premier coup de cette partie qu'aucune autre partie de la base n'a joué ; avant, la partie suivait des parties de la base", + "Der erste Zug dieser Partie, den keine andere Partie der Datenbank spielte; davor folgte sie Partien der Datenbank", + "La primera jugada de esta partida que ninguna otra partida de la base jugó; antes seguía partidas de la base", + "La prima mossa di questa partita che nessun'altra partita della base ha giocato; prima seguiva partite della base", + "O primeiro lance desta partida que nenhuma outra partida desta base jogou; antes dele a partida seguiu partidas da base", + "Bu partiyaning bazadagi boshqa hech bir partiyada qilinmagan birinchi yurishi; undan oldin partiya baza partiyalari bo‘yicha borgan", + "Бұл базаның баÑ�қа бірде-бір партиÑ�Ñ�ында жаÑ�алмаған оÑ�Ñ‹ партиÑ�ның алғашқы жүріÑ�Ñ–; оған дейін партиÑ� база партиÑ�ларымен жүрді", + ], + [ + "Game over", + "Конец партии", + "Fin de partie", + "Partieende", + "Fin de la partida", + "Fine partita", + "Fim de jogo", + "Partiya tugadi", + "ПартиÑ� аÑ�қталды", + ], + [ + "Games that ended in this position (resignation, draw, mate, time)", + "Столько партий закончилоÑ�ÑŒ в Ñ�той позиции (Ñ�дача, ничьÑ�, мат, времÑ�)", + "Parties terminées dans cette position (abandon, nulle, mat, temps)", + "Partien, die in dieser Stellung endeten (Aufgabe, Remis, Matt, Zeit)", + "Partidas que terminaron en esta posición (abandono, tablas, mate, tiempo)", + "Partite finite in questa posizione (abbandono, patta, matto, tempo)", + "Partidas que terminaram nesta posição (abandono, empate, mate, tempo)", + "Shu pozitsiyada tugagan partiyalar (taslim, durang, mat, vaqt)", + "ОÑ�Ñ‹ позициÑ�да аÑ�қталған партиÑ�лар (берілу, тең ойын, мат, уақыт)", + ], + [ + "Without moves", + "Без ходов", + "Sans coups", + "Ohne Züge", + "Sin jugadas", + "Senza mosse", + "Sem lances", + "Yurishlarsiz", + "ЖүріÑ�Ñ�із", + ], + [ + "Games of the database with only the players and the result, no moves", + "Партии базы, у которых запиÑ�аны только игроки и результат, без ходов", + "Parties de la base avec seulement les joueurs et le résultat, sans coups", + "Partien der Datenbank nur mit Spielern und Ergebnis, ohne Züge", + "Partidas de la base solo con los jugadores y el resultado, sin jugadas", + "Partite della base con solo giocatori e risultato, senza mosse", + "Partidas da base só com os jogadores e o resultado, sem lances", + "Bazaning faqat o‘yinchilar va natija yozilgan, yurishlarsiz partiyalari", + "Тек ойыншылар мен нәтиже жазылған, жүріÑ�тері жоқ база партиÑ�лары", + ], + [ + "A different nickname on Chess.com", + "Ð�а Chess.com другой ник", + "Un autre pseudo sur Chess.com", + "Anderer Nickname auf Chess.com", + "Otro apodo en Chess.com", + "Un altro nickname su Chess.com", + "Outro nick no Chess.com", + "Chess.comda boshqa taxallus", + "Chess.com-да баÑ�қа лақап ат", + ], + [ + "Fetch the games played since the last download", + "Загрузить партии, Ñ�ыгранные поÑ�ле прошлой загрузки", + "Récupérer les parties jouées depuis le dernier téléchargement", + "Die seit dem letzten Download gespielten Partien holen", + "Descargar las partidas jugadas desde la última descarga", + "Scarica le partite giocate dall'ultimo download", + "Baixar as partidas jogadas desde o último download", + "Oxirgi yuklab olishdan keyin o‘ynalgan partiyalarni olish", + "Соңғы жүктеуден кейін ойналған партиÑ�ларды алу", + ], + [ + "Find", + "Ð�айти", + "Rechercher", + "Suchen", + "Buscar", + "Cerca", + "Buscar", + "Topish", + "Табу", + ], + [ + "Letters, digits, _ and -, 2 to 30 characters", + "Латиница, цифры, _ и -, от 2 до 30 Ñ�имволов", + "Lettres, chiffres, _ et -, de 2 à 30 caractères", + "Buchstaben, Ziffern, _ und -, 2 bis 30 Zeichen", + "Letras, dígitos, _ y -, de 2 a 30 caracteres", + "Lettere, cifre, _ e -, da 2 a 30 caratteri", + "Letras, números, _ e -, de 2 a 30 caracteres", + "Harflar, raqamlar, _ va -, 2 dan 30 gacha belgi", + "Әріптер, Ñ�андар, _ және -, 2-ден 30-ға дейін таңба", + ], + [ + "Nickname on Chess.com", + "Ð�ик на Chess.com", + "Pseudo sur Chess.com", + "Nickname auf Chess.com", + "Apodo en Chess.com", + "Nickname su Chess.com", + "Nick no Chess.com", + "Chess.comdagi taxallus", + "Chess.com-дағы лақап ат", + ], + [ + "Stop", + "ОÑ�тановить", + "Arrêter", + "Anhalten", + "Detener", + "Ferma", + "Parar", + "To‘xtatish", + "Тоқтату", + ], + [ + "The same nickname", + "Тот же ник", + "Le même pseudo", + "Derselbe Nickname", + "El mismo apodo", + "Lo stesso nickname", + "O mesmo nick", + "O‘sha taxallus", + "Сол лақап ат", + ], + [ + "as on the site", + "как на Ñ�айте", + "comme sur le site", + "wie auf der Seite", + "como en el sitio", + "come sul sito", + "como no site", + "saytdagidek", + "Ñ�айттағыдай", + ], + [ + "updating…", + "обновлÑ�етÑ�Ñ�…", + "mise à jour…", + "wird aktualisiert…", + "actualizando…", + "aggiornamento…", + "atualizando…", + "yangilanmoqda…", + "жаңартылуда…", + ], + [ + "Checking…", + "ПроверÑ�ю…", + "Vérification…", + "Wird geprüft…", + "Comprobando…", + "Controllo…", + "Verificando…", + "Tekshirilmoqda…", + "ТекÑ�ерілуде…", + ], + [ + "This is the latest version", + "Это поÑ�леднÑ�Ñ� верÑ�иÑ�", + "C'est la dernière version", + "Das ist die neueste Version", + "Es la última versión", + "È l'ultima versione", + "Esta é a versão mais recente", + "Bu eng so‘nggi versiya", + "Бұл Ñ�оңғы нұÑ�қа", + ], + [ + "Could not check (no connection?)", + "Ð�е удалоÑ�ÑŒ проверить (нет Ñ�вÑ�зи?)", + "Vérification impossible (pas de connexion ?)", + "Prüfung nicht möglich (keine Verbindung?)", + "No se pudo comprobar (¿sin conexión?)", + "Impossibile controllare (nessuna connessione?)", + "Não foi possível verificar (sem conexão?)", + "Tekshirib bo‘lmadi (aloqa yo‘qmi?)", + "ТекÑ�еру мүмкін болмады (байланыÑ� жоқ па?)", + ], + [ + "Version {v} is out", + "Вышла верÑ�иÑ� {v}", + "La version {v} est sortie", + "Version {v} ist erschienen", + "Ha salido la versión {v}", + "È uscita la versione {v}", + "Saiu a versão {v}", + "{v} versiyasi chiqdi", + "{v} нұÑ�қаÑ�Ñ‹ шықты", + ], + [ + "Check for a new version at start", + "ПроверÑ�ть новую верÑ�ию при запуÑ�ке", + "Rechercher une nouvelle version au démarrage", + "Beim Start nach einer neuen Version suchen", + "Buscar una versión nueva al iniciar", + "Cerca una nuova versione all'avvio", + "Verificar nova versão ao iniciar", + "Ishga tushganda yangi versiyani tekshirish", + "ІÑ�ке қоÑ�қанда жаңа нұÑ�қаны текÑ�еру", + ], + [ + "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", + "ChessPenguin Ñ�прашивает у Ñ�воего Ñ�айта, какаÑ� верÑ�иÑ� поÑ�леднÑ�Ñ�; Ñ�айт Ñ�читает работающие уÑ�тановки: передаютÑ�Ñ� только Ñ�лучайный номер Ñ�той уÑ�тановки, верÑ�иÑ� и Ñ�иÑ�тема", + "ChessPenguin demande à son site quelle est la dernière version ; le site compte les installations actives : seuls un numéro aléatoire de cette installation, la version et le système sont envoyés", + "ChessPenguin fragt seine Website nach der neuesten Version; die Website zählt laufende Installationen: Gesendet werden nur eine Zufallsnummer dieser Installation, die Version und das System", + "ChessPenguin pregunta a su sitio cuál es la última versión; el sitio cuenta las instalaciones en uso: solo se envían un número aleatorio de esta instalación, la versión y el sistema", + "ChessPenguin chiede al suo sito qual è l'ultima versione; il sito conta le installazioni in uso: vengono inviati solo un numero casuale di questa installazione, la versione e il sistema", + "O ChessPenguin pergunta ao seu site qual é a versão mais recente; o site conta as instalações em uso: são enviados apenas um número aleatório desta instalação, a versão e o sistema", + "ChessPenguin o‘z saytidan eng so‘nggi versiyani so‘raydi; sayt ishlayotgan o‘rnatmalarni sanaydi: faqat shu o‘rnatmaning tasodifiy raqami, versiya va tizim yuboriladi", + "ChessPenguin өз Ñ�айтынан Ñ�оңғы нұÑ�қаны Ñ�ұрайды; Ñ�айт жұмыÑ� Ñ–Ñ�теп тұрған орнатуларды Ñ�анайды: тек оÑ�Ñ‹ орнатудың кездейÑ�оқ нөмірі, нұÑ�қа және жүйе жіберіледі", + ], + [ + "Check now", + "Проверить Ñ�ейчаÑ�", + "Vérifier maintenant", + "Jetzt prüfen", + "Comprobar ahora", + "Controlla ora", + "Verificar agora", + "Hozir tekshirish", + "Қазір текÑ�еру", + ], + [ + "A new version of ChessPenguin is out", + "Вышла новаÑ� верÑ�иÑ� ChessPenguin", + "Une nouvelle version de ChessPenguin est sortie", + "Eine neue Version von ChessPenguin ist erschienen", + "Ha salido una nueva versión de ChessPenguin", + "È uscita una nuova versione di ChessPenguin", + "Saiu uma nova versão do ChessPenguin", + "ChessPenguinning yangi versiyasi chiqdi", + "ChessPenguin-нің жаңа нұÑ�қаÑ�Ñ‹ шықты", + ], + [ + "⬆ Update {v}", + "⬆ Обновить до {v}", + "⬆ Mettre à jour vers {v}", + "⬆ Auf {v} aktualisieren", + "⬆ Actualizar a {v}", + "⬆ Aggiorna a {v}", + "⬆ Atualizar {v}", + "⬆ Yangilash: {v}", + "⬆ Жаңарту: {v}", + ], + [ + "the deb package", + "пакет deb", + "le paquet deb", + "das deb-Paket", + "el paquete deb", + "il pacchetto deb", + "o pacote deb", + "deb paketi", + "deb пакеті", + ], + [ + "the rpm package", + "пакет rpm", + "le paquet rpm", + "das rpm-Paket", + "el paquete rpm", + "il pacchetto rpm", + "o pacote rpm", + "rpm paketi", + "rpm пакеті", + ], + [ + "the Arch Linux package", + "пакет Arch Linux", + "le paquet Arch Linux", + "das Arch-Linux-Paket", + "el paquete de Arch Linux", + "il pacchetto Arch Linux", + "o pacote do Arch Linux", + "Arch Linux paketi", + "Arch Linux пакеті", + ], + [ + "The new version is installed.", + "Ð�оваÑ� верÑ�иÑ� уÑ�тановлена.", + "La nouvelle version est installée.", + "Die neue Version ist installiert.", + "La nueva versión está instalada.", + "La nuova versione è installata.", + "A nova versão está instalada.", + "Yangi versiya o‘rnatildi.", + "Жаңа нұÑ�қа орнатылды.", + ], + [ + "It starts after a restart; unsaved games are asked about first.", + "Она запуÑ�титÑ�Ñ� поÑ�ле перезапуÑ�ка; про неÑ�охранённые партии программа Ñ�начала Ñ�проÑ�ит.", + "Elle démarre après un redémarrage ; les parties non enregistrées sont d'abord proposées à l'enregistrement.", + "Sie startet nach einem Neustart; nach ungespeicherten Partien wird vorher gefragt.", + "Se inicia tras reiniciar; antes se pregunta por las partidas sin guardar.", + "Parte dopo il riavvio; prima viene chiesto delle partite non salvate.", + "Ela começa após reiniciar; antes disso, perguntamos sobre partidas não salvas.", + "U qayta ishga tushirilgandan keyin ishlaydi; avval saqlanmagan partiyalar haqida so‘raladi.", + "Ол қайта Ñ–Ñ�ке қоÑ�қаннан кейін баÑ�талады; Ñ�ақталмаған партиÑ�лар туралы алдымен Ñ�ұралады.", + ], + [ + "Restart now", + "ПерезапуÑ�тить Ñ�ейчаÑ�", + "Redémarrer maintenant", + "Jetzt neu starten", + "Reiniciar ahora", + "Riavvia ora", + "Reiniciar agora", + "Hozir qayta ishga tushirish", + "Қазір қайта Ñ–Ñ�ке қоÑ�у", + ], + [ + "The disk image is open.", + "Образ диÑ�ка открыт.", + "L'image disque est ouverte.", + "Das Disk-Image ist geöffnet.", + "La imagen de disco está abierta.", + "L'immagine disco è aperta.", + "A imagem de disco está aberta.", + "Disk obrazi ochildi.", + "ДиÑ�к бейнеÑ�Ñ– ашық.", + ], + [ + "Drag ChessPenguin onto Applications in its window and choose Replace. Then quit this window of ChessPenguin and start it again.", + "Ð’ его окне перетащите ChessPenguin в «Программы» и выберите «Заменить». Затем закройте ChessPenguin и запуÑ�тите Ñ�нова.", + "Dans sa fenêtre, faites glisser ChessPenguin sur Applications et choisissez Remplacer. Puis quittez ChessPenguin et relancez-le.", + "Ziehen Sie ChessPenguin in seinem Fenster auf Programme und wählen Sie Ersetzen. Beenden Sie dann ChessPenguin und starten Sie es neu.", + "En su ventana, arrastra ChessPenguin a Aplicaciones y elige Reemplazar. Luego cierra ChessPenguin y ábrelo de nuevo.", + "Nella sua finestra trascina ChessPenguin su Applicazioni e scegli Sostituisci. Poi chiudi ChessPenguin e riavvialo.", + "Arraste o ChessPenguin para Aplicativos na janela dela e escolha Substituir. Depois feche esta janela do ChessPenguin e inicie-o de novo.", + "Uning oynasida ChessPenguinni Applications jildiga torting va Replace tugmasini bosing. So‘ng ChessPenguinning bu oynasini yoping va qayta ishga tushiring.", + "Оның терезеÑ�інде ChessPenguin-ді Applications қалтаÑ�ына Ñ�үйреп апарып, Replace таңдаңыз. Содан кейін ChessPenguin-нің оÑ�Ñ‹ терезеÑ�ін жауып, қайта Ñ–Ñ�ке қоÑ�ыңыз.", + ], + [ + "The package is downloaded and checked.", + "Пакет Ñ�качан и проверен.", + "Le paquet est téléchargé et vérifié.", + "Das Paket ist heruntergeladen und geprüft.", + "El paquete está descargado y comprobado.", + "Il pacchetto è scaricato e verificato.", + "O pacote foi baixado e verificado.", + "Paket yuklab olindi va tekshirildi.", + "Пакет жүктелді және текÑ�ерілді.", + ], + [ + "To install it, run this command in a terminal (it may ask for your password):", + "Чтобы уÑ�тановить его, выполните в терминале команду (может Ñ�проÑ�ить пароль):", + "Pour l'installer, lancez cette commande dans un terminal (le mot de passe peut être demandé) :", + "Zum Installieren diesen Befehl im Terminal ausführen (eventuell wird das Passwort abgefragt):", + "Para instalarlo, ejecuta este comando en una terminal (puede pedir tu contraseña):", + "Per installarlo, esegui questo comando in un terminale (potrebbe chiedere la password):", + "Para instalá-lo, execute este comando em um terminal (pode pedir sua senha):", + "Uni o‘rnatish uchun terminalda bu buyruqni bajaring (parol so‘rashi mumkin):", + "Орнату үшін терминалда мына команданы орындаңыз (құпиÑ�Ñ�өз Ñ�ұралуы мүмкін):", + ], + [ + "Run it in the terminal of your system, not inside the Flatpak.", + "Выполните её в обычном терминале Ñ�иÑ�темы, не внутри Flatpak.", + "Lancez-la dans le terminal du système, pas à l'intérieur du Flatpak.", + "Führen Sie ihn im Terminal des Systems aus, nicht im Flatpak.", + "Ejecútalo en la terminal del sistema, no dentro del Flatpak.", + "Eseguilo nel terminale del sistema, non dentro il Flatpak.", + "Execute-o no terminal do seu sistema, não dentro do Flatpak.", + "Uni Flatpak ichida emas, tizimingiz terminalida bajaring.", + "Оны Flatpak ішінде емеÑ�, жүйенің терминалында орындаңыз.", + ], + [ + "Then close ChessPenguin and start it again.", + "Затем закройте ChessPenguin и запуÑ�тите Ñ�нова.", + "Puis fermez ChessPenguin et relancez-le.", + "Schließen Sie dann ChessPenguin und starten Sie es neu.", + "Luego cierra ChessPenguin y ábrelo de nuevo.", + "Poi chiudi ChessPenguin e riavvialo.", + "Depois feche o ChessPenguin e inicie-o de novo.", + "So‘ng ChessPenguinni yoping va qayta ishga tushiring.", + "Содан кейін ChessPenguin-ді жауып, қайта Ñ–Ñ�ке қоÑ�ыңыз.", + ], + [ + "The downloaded file is damaged (its checksum does not match). Try again.", + "Скачанный файл повреждён (контрольнаÑ� Ñ�умма не Ñ�овпала). Попробуйте ещё раз.", + "Le fichier téléchargé est endommagé (la somme de contrôle ne correspond pas). Réessayez.", + "Die heruntergeladene Datei ist beschädigt (Prüfsumme passt nicht). Versuchen Sie es erneut.", + "El archivo descargado está dañado (la suma de comprobación no coincide). Inténtalo de nuevo.", + "Il file scaricato è danneggiato (il checksum non corrisponde). Riprova.", + "O arquivo baixado está danificado (o checksum não confere). Tente de novo.", + "Yuklab olingan fayl shikastlangan (nazorat yig‘indisi mos emas). Qayta urinib ko‘ring.", + "Жүктелген файл бүлінген (бақылау Ñ�омаÑ�Ñ‹ Ñ�әйкеÑ� емеÑ�). Қайталап көріңіз.", + ], + [ + "Cancelled.", + "Отменено.", + "Annulé.", + "Abgebrochen.", + "Cancelado.", + "Annullato.", + "Cancelado.", + "Bekor qilindi.", + "Тоқтатылды.", + ], + [ + "ChessPenguin is installed from the AUR. Update it with your AUR helper:", + "ChessPenguin уÑ�тановлен из AUR. Обновите его через AUR-помощник:", + "ChessPenguin est installé depuis l'AUR. Mettez-le à jour avec votre assistant AUR :", + "ChessPenguin ist aus dem AUR installiert. Aktualisieren Sie es mit Ihrem AUR-Helfer:", + "ChessPenguin está instalado desde AUR. Actualízalo con tu asistente de AUR:", + "ChessPenguin è installato da AUR. Aggiornalo con il tuo helper AUR:", + "O ChessPenguin foi instalado pelo AUR. Atualize-o com seu AUR helper:", + "ChessPenguin AURdan o‘rnatilgan. Uni AUR yordamchingiz bilan yangilang:", + "ChessPenguin AUR-дан орнатылған. Оны AUR көмекшіÑ�імен жаңартыңыз:", + ], + [ + "⬆ Update", + "⬆ Обновить", + "⬆ Mettre à jour", + "⬆ Aktualisieren", + "⬆ Actualizar", + "⬆ Aggiorna", + "⬆ Atualizar", + "⬆ Yangilash", + "⬆ Жаңарту", + ], + [ + "⬇ Download", + "⬇ Скачать", + "⬇ Télécharger", + "⬇ Herunterladen", + "⬇ Descargar", + "⬇ Scarica", + "⬇ Baixar", + "⬇ Yuklab olish", + "⬇ Жүктеп алу", + ], + [ + "⬇ Download the package", + "⬇ Скачать пакет", + "⬇ Télécharger le paquet", + "⬇ Paket herunterladen", + "⬇ Descargar el paquete", + "⬇ Scarica il pacchetto", + "⬇ Baixar o pacote", + "⬇ Paketni yuklab olish", + "⬇ Пакетті жүктеп алу", + ], + [ + "Download the new version from the website:", + "Скачайте новую верÑ�ию на Ñ�айте:", + "Téléchargez la nouvelle version sur le site :", + "Laden Sie die neue Version von der Website:", + "Descarga la nueva versión en el sitio web:", + "Scarica la nuova versione dal sito:", + "Baixe a nova versão no site:", + "Yangi versiyani saytdan yuklab oling:", + "Жаңа нұÑ�қаны Ñ�айттан жүктеп алыңыз:", + ], + [ + "Copy", + "Копировать", + "Copier", + "Kopieren", + "Copiar", + "Copia", + "Copiar", + "Nusxalash", + "Көшіру", + ], + [ + "ChessPenguin {v}", + "ChessPenguin {v}", + "ChessPenguin {v}", + "ChessPenguin {v}", + "ChessPenguin {v}", + "ChessPenguin {v}", + "ChessPenguin {v}", + "ChessPenguin {v}", + "ChessPenguin {v}", + ], + [ + "A new version is out: {new} (you have {old}).", + "Вышла новаÑ� верÑ�иÑ�: {new} (у ваÑ� {old}).", + "Une nouvelle version est sortie : {new} (vous avez {old}).", + "Eine neue Version ist erschienen: {new} (Sie haben {old}).", + "Ha salido una nueva versión: {new} (tienes la {old}).", + "È uscita una nuova versione: {new} (hai la {old}).", + "Saiu uma nova versão: {new} (você tem a {old}).", + "Yangi versiya chiqdi: {new} (sizda {old}).", + "Жаңа нұÑ�қа шықты: {new} (Ñ�ізде {old}).", + ], + [ + "Downloading… {done} of {total} MB", + "Скачиваю… {done} из {total} МБ", + "Téléchargement… {done} sur {total} Mo", + "Wird heruntergeladen… {done} von {total} MB", + "Descargando… {done} de {total} MB", + "Scaricamento… {done} di {total} MB", + "Baixando… {done} de {total} MB", + "Yuklab olinmoqda… {done} / {total} MB", + "Жүктелуде… {done} / {total} МБ", + ], + [ + "It is in {path}.", + "Он лежит здеÑ�ÑŒ: {path}.", + "Il se trouve ici : {path}.", + "Es liegt hier: {path}.", + "Está aquí: {path}.", + "Si trova qui: {path}.", + "Está em {path}.", + "U shu yerda: {path}.", + "Ол мына жерде: {path}.", + ], + [ + "The update failed: {e}", + "Обновить не удалоÑ�ÑŒ: {e}", + "La mise à jour a échoué : {e}", + "Die Aktualisierung ist fehlgeschlagen: {e}", + "La actualización falló: {e}", + "L'aggiornamento non è riuscito: {e}", + "A atualização falhou: {e}", + "Yangilab bo‘lmadi: {e}", + "Жаңарту Ñ�әтÑ�із болды: {e}", + ], + [ + "ChessPenguin ({kind}) updates itself: the new version is downloaded ({mb} MB), checked and put in place of this one.", + "ChessPenguin ({kind}) обновлÑ�етÑ�Ñ� Ñ�ам: новаÑ� верÑ�иÑ� Ñ�качиваетÑ�Ñ� ({mb} МБ), проверÑ�етÑ�Ñ� и вÑ�таёт на меÑ�то Ñ�той.", + "ChessPenguin ({kind}) se met à jour tout seul : la nouvelle version est téléchargée ({mb} Mo), vérifiée et mise à la place de celle-ci.", + "ChessPenguin ({kind}) aktualisiert sich selbst: die neue Version wird heruntergeladen ({mb} MB), geprüft und ersetzt diese.", + "ChessPenguin ({kind}) se actualiza solo: la nueva versión se descarga ({mb} MB), se comprueba y sustituye a esta.", + "ChessPenguin ({kind}) si aggiorna da solo: la nuova versione viene scaricata ({mb} MB), verificata e messa al posto di questa.", + "O ChessPenguin ({kind}) se atualiza sozinho: a nova versão é baixada ({mb} MB), verificada e colocada no lugar desta.", + "ChessPenguin ({kind}) o‘zini o‘zi yangilaydi: yangi versiya yuklab olinadi ({mb} MB), tekshiriladi va bunisining o‘rniga qo‘yiladi.", + "ChessPenguin ({kind}) өзін өзі жаңартады: жаңа нұÑ�қа жүктеліп ({mb} МБ), текÑ�еріледі және оÑ�ының орнына қойылады.", + ], + [ + "The disk image ({mb} MB) is downloaded, checked and opened; you drag the app over the old one, as when you installed it.", + "Образ диÑ�ка ({mb} МБ) Ñ�качиваетÑ�Ñ�, проверÑ�етÑ�Ñ� и открываетÑ�Ñ�; вы перетаÑ�киваете программу поверх Ñ�тарой, как при уÑ�тановке.", + "L'image disque ({mb} Mo) est téléchargée, vérifiée et ouverte ; vous glissez l'app sur l'ancienne, comme à l'installation.", + "Das Disk-Image ({mb} MB) wird heruntergeladen, geprüft und geöffnet; Sie ziehen die App über die alte, wie bei der Installation.", + "La imagen de disco ({mb} MB) se descarga, se comprueba y se abre; arrastras la app sobre la antigua, como al instalarla.", + "L'immagine disco ({mb} MB) viene scaricata, verificata e aperta; trascini l'app sopra la vecchia, come all'installazione.", + "A imagem de disco ({mb} MB) é baixada, verificada e aberta; você arrasta o app sobre o antigo, como na instalação.", + "Disk obrazi ({mb} MB) yuklab olinadi, tekshiriladi va ochiladi; dasturni o‘rnatgandagidek eskisining ustiga tortasiz.", + "ДиÑ�к бейнеÑ�Ñ– ({mb} МБ) жүктеліп, текÑ�еріліп, ашылады; орнатқандағыдай, бағдарламаны еÑ�кіÑ�інің Ò¯Ñ�тіне Ñ�үйреп апараÑ�ыз.", + ], + [ + "ChessPenguin is installed as {kind}: the system installs it. The new package ({mb} MB) is downloaded into Downloads and checked; then you run one command.", + "ChessPenguin уÑ�тановлен как {kind}: его Ñ�тавит Ñ�иÑ�тема. Ð�овый пакет ({mb} МБ) Ñ�качиваетÑ�Ñ� в «Загрузки» и проверÑ�етÑ�Ñ�, затем вы выполнÑ�ете одну команду.", + "ChessPenguin est installé comme {kind} : c'est le système qui l'installe. Le nouveau paquet ({mb} Mo) est téléchargé dans Téléchargements et vérifié ; puis vous lancez une commande.", + "ChessPenguin ist als {kind} installiert: das System installiert es. Das neue Paket ({mb} MB) wird nach Downloads geladen und geprüft; dann führen Sie einen Befehl aus.", + "ChessPenguin está instalado como {kind}: lo instala el sistema. El nuevo paquete ({mb} MB) se descarga en Descargas y se comprueba; luego ejecutas un comando.", + "ChessPenguin è installato come {kind}: lo installa il sistema. Il nuovo pacchetto ({mb} MB) viene scaricato in Download e verificato; poi esegui un comando.", + "O ChessPenguin está instalado como {kind}: o sistema o instala. O novo pacote ({mb} MB) é baixado em Downloads e verificado; depois você executa um comando.", + "ChessPenguin {kind} sifatida o‘rnatilgan: uni tizim o‘rnatadi. Yangi paket ({mb} MB) Downloads jildiga yuklab olinadi va tekshiriladi; so‘ng siz bitta buyruqni bajarasiz.", + "ChessPenguin {kind} ретінде орнатылған: оны жүйе орнатады. Жаңа пакет ({mb} МБ) Downloads қалтаÑ�ына жүктеліп, текÑ�еріледі; Ñ�одан кейін бір команда орындайÑ�ыз.", + ], + [ + "Could not check for updates", + "Ð�е удалоÑ�ÑŒ проверить обновлениÑ�", + "Impossible de rechercher les mises à jour", + "Suche nach Updates nicht möglich", + "No se pudieron buscar actualizaciones", + "Impossibile cercare aggiornamenti", + "Não foi possível verificar atualizações", + "Yangilanishlarni tekshirib bo‘lmadi", + "Жаңартуларды текÑ�еру мүмкін болмады", + ], + [ + "ChessPenguin is updated: {from} → {to}", + "ChessPenguin обновлён: {from} → {to}", + "ChessPenguin est mis à jour : {from} → {to}", + "ChessPenguin wurde aktualisiert: {from} → {to}", + "ChessPenguin se ha actualizado: {from} → {to}", + "ChessPenguin è aggiornato: {from} → {to}", + "O ChessPenguin foi atualizado: {from} → {to}", + "ChessPenguin yangilandi: {from} → {to}", + "ChessPenguin жаңартылды: {from} → {to}", + ], + [ + "Check for updates at start", + "ПроверÑ�ть обновлениÑ� при запуÑ�ке", + "Rechercher les mises à jour au démarrage", + "Beim Start nach Updates suchen", + "Buscar actualizaciones al iniciar", + "Cerca aggiornamenti all'avvio", + "Verificar atualizações ao iniciar", + "Ishga tushganda yangilanishlarni tekshirish", + "ІÑ�ке қоÑ�қанда жаңартуларды текÑ�еру", + ], + [ + "⬆ Update to {v}…", + "⬆ Обновить до {v}…", + "⬆ Mettre à jour vers {v}…", + "⬆ Auf {v} aktualisieren…", + "⬆ Actualizar a {v}…", + "⬆ Aggiorna a {v}…", + "⬆ Atualizar para {v}…", + "⬆ {v}ga yangilash…", + "⬆ {v} нұÑ�қаÑ�ына жаңарту…", + ], + [ + "less than 1", + "меньше 1", + "moins de 1", + "unter 1", + "menos de 1", + "meno di 1", + "menos de 1", + "1 dan kam", + "1-ден аз", + ], + [ + "deb package", + "пакет deb", + "paquet deb", + "deb-Paket", + "paquete deb", + "pacchetto deb", + "pacote deb", + "deb paketi", + "deb пакеті", + ], + [ + "rpm package", + "пакет rpm", + "paquet rpm", + "rpm-Paket", + "paquete rpm", + "pacchetto rpm", + "pacote rpm", + "rpm paketi", + "rpm пакеті", + ], + [ + "Arch Linux package", + "пакет Arch Linux", + "paquet Arch Linux", + "Arch-Linux-Paket", + "paquete de Arch Linux", + "pacchetto Arch Linux", + "pacote do Arch Linux", + "Arch Linux paketi", + "Arch Linux пакеті", + ], + [ + "archive (tar.gz)", + "архив (tar.gz)", + "archive (tar.gz)", + "Archiv (tar.gz)", + "archivo (tar.gz)", + "archivio (tar.gz)", + "arquivo compactado (tar.gz)", + "arxiv (tar.gz)", + "мұрағат (tar.gz)", + ], + [ + "The file got damaged while downloading, so it was not installed. Try again.", + "Файл повредилÑ�Ñ� при Ñ�качивании, поÑ�тому не уÑ�тановлен. Попробуйте ещё раз.", + "Le fichier a été endommagé pendant le téléchargement ; il n'a pas été installé. Réessayez.", + "Die Datei wurde beim Herunterladen beschädigt und deshalb nicht installiert. Versuchen Sie es erneut.", + "El archivo se dañó al descargarse, así que no se instaló. Inténtalo de nuevo.", + "Il file si è danneggiato durante lo scaricamento, quindi non è stato installato. Riprova.", + "O arquivo foi danificado durante o download, por isso não foi instalado. Tente de novo.", + "Fayl yuklab olishda shikastlandi, shuning uchun o‘rnatilmadi. Qayta urinib ko‘ring.", + "Файл жүктеу кезінде бүлінді, Ñ�ондықтан орнатылмады. Қайталап көріңіз.", + ], + [ + "The download was cancelled.", + "Скачивание отменено.", + "Le téléchargement a été annulé.", + "Der Download wurde abgebrochen.", + "La descarga se canceló.", + "Lo scaricamento è stato annullato.", + "O download foi cancelado.", + "Yuklab olish bekor qilindi.", + "Жүктеу тоқтатылды.", + ], + [ + "This release has no file for your system yet. Download the new version from the website.", + "Ð’ Ñ�том выпуÑ�ке пока нет файла длÑ� вашей Ñ�иÑ�темы. Скачайте новую верÑ�ию на Ñ�айте.", + "Cette version n'a pas encore de fichier pour votre système. Téléchargez-la sur le site.", + "Diese Version hat noch keine Datei für Ihr System. Laden Sie sie von der Website.", + "Esta versión aún no tiene archivo para tu sistema. Descárgala en el sitio web.", + "Questa versione non ha ancora un file per il tuo sistema. Scaricala dal sito.", + "Esta versão ainda não tem arquivo para o seu sistema. Baixe a nova versão no site.", + "Bu nashrda hali tizimingiz uchun fayl yo‘q. Yangi versiyani saytdan yuklab oling.", + "Бұл шығарылымда Ñ�іздің жүйеңізге арналған файл әлі жоқ. Жаңа нұÑ�қаны Ñ�айттан жүктеп алыңыз.", + ], + [ + "The file could not be saved: no permission to write there, or the disk is full.", + "Ð�е удалоÑ�ÑŒ Ñ�охранить файл: нет прав на запиÑ�ÑŒ в Ñ�ту папку или диÑ�к заполнен.", + "Impossible d'enregistrer le fichier : pas le droit d'écrire ici, ou le disque est plein.", + "Die Datei konnte nicht gespeichert werden: keine Schreibrechte oder die Festplatte ist voll.", + "No se pudo guardar el archivo: sin permiso de escritura o el disco está lleno.", + "Impossibile salvare il file: nessun permesso di scrittura o disco pieno.", + "Não foi possível salvar o arquivo: sem permissão de gravação ali ou disco cheio.", + "Faylni saqlab bo‘lmadi: u yerga yozishga ruxsat yo‘q yoki disk to‘la.", + "Файлды Ñ�ақтау мүмкін болмады: ол жерге жазуға Ñ€Ò±Ò›Ñ�ат жоқ немеÑ�е диÑ�к толы.", + ], + [ + "The new version could not be downloaded: no connection to the server. Check the internet and try again.", + "Ð�е удалоÑ�ÑŒ Ñ�качать новую верÑ�ию: нет Ñ�вÑ�зи Ñ� Ñ�ервером. Проверьте интернет и попробуйте ещё раз.", + "Impossible de télécharger la nouvelle version : pas de connexion au serveur. Vérifiez Internet et réessayez.", + "Die neue Version konnte nicht geladen werden: keine Verbindung zum Server. Prüfen Sie das Internet und versuchen Sie es erneut.", + "No se pudo descargar la nueva versión: sin conexión con el servidor. Comprueba internet e inténtalo de nuevo.", + "Impossibile scaricare la nuova versione: nessuna connessione al server. Controlla internet e riprova.", + "Não foi possível baixar a nova versão: sem conexão com o servidor. Verifique a internet e tente de novo.", + "Yangi versiyani yuklab bo‘lmadi: server bilan aloqa yo‘q. Internetni tekshirib, qayta urinib ko‘ring.", + "Жаңа нұÑ�қаны жүктеу мүмкін болмады: Ñ�ервермен байланыÑ� жоқ. Интернетті текÑ�еріп, қайталап көріңіз.", + ], + [ + "ChessPenguin update", + "Обновление ChessPenguin", + "Mise à jour de ChessPenguin", + "ChessPenguin-Update", + "Actualización de ChessPenguin", + "Aggiornamento di ChessPenguin", + "Atualização do ChessPenguin", + "ChessPenguin yangilanishi", + "ChessPenguin жаңартуы", + ], + [ + "You can close this window: the download goes on.", + "Окно можно закрыть: Ñ�качивание продолжитÑ�Ñ�.", + "Vous pouvez fermer cette fenêtre : le téléchargement continue.", + "Sie können dieses Fenster schließen: der Download läuft weiter.", + "Puedes cerrar esta ventana: la descarga continúa.", + "Puoi chiudere questa finestra: lo scaricamento continua.", + "Você pode fechar esta janela: o download continua.", + "Bu oynani yopishingiz mumkin: yuklab olish davom etadi.", + "Бұл терезені жаба беруге болады: жүктеу жалғаÑ�ады.", + ], + [ + "It starts after a restart. Unsaved games are asked about first; databases and settings stay as they are.", + "Она запуÑ�титÑ�Ñ� поÑ�ле перезапуÑ�ка. Про неÑ�охранённые партии программа Ñ�начала Ñ�проÑ�ит; базы и наÑ�тройки оÑ�танутÑ�Ñ� как еÑ�ть.", + "Elle démarre après un redémarrage. Les parties non enregistrées sont d'abord proposées à l'enregistrement ; bases et réglages restent tels quels.", + "Sie startet nach einem Neustart. Nach ungespeicherten Partien wird zuerst gefragt; Datenbanken und Einstellungen bleiben erhalten.", + "Se inicia tras reiniciar. Antes se pregunta por las partidas sin guardar; las bases y los ajustes se conservan.", + "Parte dopo il riavvio. Prima viene chiesto delle partite non salvate; basi e impostazioni restano come sono.", + "Ela começa após reiniciar. Antes, perguntamos sobre partidas não salvas; bases e configurações ficam como estão.", + "U qayta ishga tushirilgandan keyin ishlaydi. Avval saqlanmagan partiyalar haqida so‘raladi; bazalar va sozlamalar o‘z holicha qoladi.", + "Ол қайта Ñ–Ñ�ке қоÑ�қаннан кейін баÑ�талады. Сақталмаған партиÑ�лар туралы алдымен Ñ�ұралады; базалар мен баптаулар өзгермейді.", + ], + [ + "⟳ Restart now", + "⟳ ПерезапуÑ�тить Ñ�ейчаÑ�", + "⟳ Redémarrer maintenant", + "⟳ Jetzt neu starten", + "⟳ Reiniciar ahora", + "⟳ Riavvia ora", + "⟳ Reiniciar agora", + "⟳ Hozir qayta ishga tushirish", + "⟳ Қазір қайта Ñ–Ñ�ке қоÑ�у", + ], + [ + "The disk image is open", + "Образ диÑ�ка открыт", + "L'image disque est ouverte", + "Das Disk-Image ist geöffnet", + "La imagen de disco está abierta", + "L'immagine disco è aperta", + "A imagem de disco está aberta", + "Disk obrazi ochildi", + "ДиÑ�к бейнеÑ�Ñ– ашық", + ], + [ + "1. Quit ChessPenguin (the button below): a running app cannot be replaced.", + "1. Закройте ChessPenguin (кнопка ниже): запущенную программу заменить нельзÑ�.", + "1. Quittez ChessPenguin (bouton ci-dessous) : une app ouverte ne peut pas être remplacée.", + "1. Beenden Sie ChessPenguin (Knopf unten): eine laufende App lässt sich nicht ersetzen.", + "1. Cierra ChessPenguin (botón de abajo): una app abierta no se puede reemplazar.", + "1. Chiudi ChessPenguin (pulsante sotto): un'app aperta non si può sostituire.", + "1. Feche o ChessPenguin (o botão abaixo): um app em execução não pode ser substituído.", + "1. ChessPenguinni yoping (quyidagi tugma): ishlab turgan dasturni almashtirib bo‘lmaydi.", + "1. ChessPenguin-ді жабыңыз (төмендегі түйме): Ñ–Ñ�ке қоÑ�улы бағдарламаны ауыÑ�тыру мүмкін емеÑ�.", + ], + [ + "2. In the window of the disk image, drag the ChessPenguin icon onto the Applications folder and choose Replace.", + "2. Ð’ окне образа диÑ�ка перетащите значок ChessPenguin на папку «Программы» и нажмите «Заменить».", + "2. Dans la fenêtre de l'image disque, faites glisser l'icône de ChessPenguin sur le dossier Applications et choisissez Remplacer.", + "2. Ziehen Sie im Fenster des Disk-Images das ChessPenguin-Symbol auf den Ordner Programme und wählen Sie Ersetzen.", + "2. En la ventana de la imagen de disco, arrastra el icono de ChessPenguin a la carpeta Aplicaciones y elige Reemplazar.", + "2. Nella finestra dell'immagine disco trascina l'icona di ChessPenguin sulla cartella Applicazioni e scegli Sostituisci.", + "2. Na janela da imagem de disco, arraste o ícone do ChessPenguin para a pasta Aplicativos e escolha Substituir.", + "2. Disk obrazi oynasida ChessPenguin belgisini Applications jildiga torting va Replace tugmasini bosing.", + "2. ДиÑ�к бейнеÑ�інің терезеÑ�інде ChessPenguin белгішеÑ�ін Applications қалтаÑ�ына Ñ�үйреп апарып, Replace таңдаңыз.", + ], + [ + "3. Start ChessPenguin from Applications.", + "3. ЗапуÑ�тите ChessPenguin из «Программ».", + "3. Lancez ChessPenguin depuis Applications.", + "3. Starten Sie ChessPenguin aus Programme.", + "3. Abre ChessPenguin desde Aplicaciones.", + "3. Avvia ChessPenguin da Applicazioni.", + "3. Inicie o ChessPenguin a partir de Aplicativos.", + "3. ChessPenguinni Applications jildidan ishga tushiring.", + "3. ChessPenguin-ді Applications қалтаÑ�ынан Ñ–Ñ�ке қоÑ�ыңыз.", + ], + [ + "Quit ChessPenguin", + "Закрыть ChessPenguin", + "Quitter ChessPenguin", + "ChessPenguin beenden", + "Cerrar ChessPenguin", + "Chiudi ChessPenguin", + "Fechar o ChessPenguin", + "ChessPenguinni yopish", + "ChessPenguin-ді жабу", + ], + [ + "The new version is downloaded", + "Ð�оваÑ� верÑ�иÑ� Ñ�качана", + "La nouvelle version est téléchargée", + "Die neue Version ist heruntergeladen", + "La nueva versión está descargada", + "La nuova versione è scaricata", + "A nova versão foi baixada", + "Yangi versiya yuklab olindi", + "Жаңа нұÑ�қа жүктелді", + ], + [ + "Open the folder", + "Открыть папку", + "Ouvrir le dossier", + "Ordner öffnen", + "Abrir la carpeta", + "Apri la cartella", + "Abrir a pasta", + "Jildni ochish", + "Қалтаны ашу", + ], + [ + "1. Copy the command.", + "1. Скопируйте команду.", + "1. Copiez la commande.", + "1. Kopieren Sie den Befehl.", + "1. Copia el comando.", + "1. Copia il comando.", + "1. Copie o comando.", + "1. Buyruqni nusxalang.", + "1. Команданы көшіріңіз.", + ], + [ + "2. Open the Terminal of your system (not inside the Flatpak), paste the command (Ctrl+Shift+V) and press Enter.", + "2. Откройте «Терминал» Ñ�иÑ�темы (не внутри Flatpak), вÑ�тавьте команду (Ctrl+Shift+V) и нажмите Enter.", + "2. Ouvrez le Terminal du système (pas dans le Flatpak), collez la commande (Ctrl+Maj+V) et appuyez sur Entrée.", + "2. Öffnen Sie das Terminal des Systems (nicht im Flatpak), fügen Sie den Befehl ein (Strg+Umschalt+V) und drücken Sie Enter.", + "2. Abre la Terminal del sistema (no dentro del Flatpak), pega el comando (Ctrl+Mayús+V) y pulsa Intro.", + "2. Apri il Terminale del sistema (non dentro il Flatpak), incolla il comando (Ctrl+Maiusc+V) e premi Invio.", + "2. Abra o Terminal do seu sistema (não dentro do Flatpak), cole o comando (Ctrl+Shift+V) e pressione Enter.", + "2. Tizimingiz terminalini oching (Flatpak ichida emas), buyruqni qo‘ying (Ctrl+Shift+V) va Enter tugmasini bosing.", + "2. Жүйенің терминалын ашыңыз (Flatpak ішінде емеÑ�), команданы қойып (Ctrl+Shift+V), Enter баÑ�ыңыз.", + ], + [ + "2. Open the Terminal, paste the command (Ctrl+Shift+V) and press Enter. It asks for your password: while you type it nothing is shown, that is normal.", + "2. Откройте «Терминал», вÑ�тавьте команду (Ctrl+Shift+V) и нажмите Enter. СиÑ�тема Ñ�проÑ�ит пароль: при вводе он не отображаетÑ�Ñ�, Ñ�то нормально.", + "2. Ouvrez le Terminal, collez la commande (Ctrl+Maj+V) et appuyez sur Entrée. Votre mot de passe est demandé : rien ne s'affiche pendant la saisie, c'est normal.", + "2. Öffnen Sie das Terminal, fügen Sie den Befehl ein (Strg+Umschalt+V) und drücken Sie Enter. Es fragt nach Ihrem Passwort: bei der Eingabe wird nichts angezeigt, das ist normal.", + "2. Abre la Terminal, pega el comando (Ctrl+Mayús+V) y pulsa Intro. Pedirá tu contraseña: al escribirla no se ve nada, es normal.", + "2. Apri il Terminale, incolla il comando (Ctrl+Maiusc+V) e premi Invio. Chiede la password: mentre la scrivi non si vede nulla, è normale.", + "2. Abra o Terminal, cole o comando (Ctrl+Shift+V) e pressione Enter. Ele pede sua senha: enquanto você digita nada aparece, isso é normal.", + "2. Terminalni oching, buyruqni qo‘ying (Ctrl+Shift+V) va Enter tugmasini bosing. U parol so‘raydi: parol yozilayotganda hech narsa ko‘rinmaydi, bu odatiy hol.", + "2. Терминалды ашып, команданы қойыңыз (Ctrl+Shift+V) да, Enter баÑ�ыңыз. ҚұпиÑ�Ñ�өз Ñ�ұралады: оны терген кезде ештеңе көрінбейді, бұл қалыпты жағдай.", + ], + [ + "3. When the command has finished, start ChessPenguin again.", + "3. Когда команда закончитÑ�Ñ�, запуÑ�тите ChessPenguin Ñ�нова.", + "3. Quand la commande est terminée, relancez ChessPenguin.", + "3. Wenn der Befehl fertig ist, starten Sie ChessPenguin neu.", + "3. Cuando el comando termine, abre ChessPenguin de nuevo.", + "3. Quando il comando è finito, riavvia ChessPenguin.", + "3. Quando o comando terminar, inicie o ChessPenguin de novo.", + "3. Buyruq tugagach, ChessPenguinni qayta ishga tushiring.", + "3. Команда аÑ�қталғанда ChessPenguin-ді қайта Ñ–Ñ�ке қоÑ�ыңыз.", + ], + [ + "ChessPenguin is installed from the AUR. Update it as usual, for example:", + "ChessPenguin уÑ�тановлен из AUR. Обновите его как обычно, например:", + "ChessPenguin est installé depuis l'AUR. Mettez-le à jour comme d'habitude, par exemple :", + "ChessPenguin ist aus dem AUR installiert. Aktualisieren Sie es wie gewohnt, zum Beispiel:", + "ChessPenguin está instalado desde AUR. Actualízalo como siempre, por ejemplo:", + "ChessPenguin è installato da AUR. Aggiornalo come al solito, per esempio:", + "O ChessPenguin foi instalado pelo AUR. Atualize-o como de costume, por exemplo:", + "ChessPenguin AURdan o‘rnatilgan. Uni odatdagidek yangilang, masalan:", + "ChessPenguin AUR-дан орнатылған. Оны әдеттегідей жаңартыңыз, мыÑ�алы:", + ], + [ + "This release has no file for your system yet. Download the new version from the website:", + "Ð’ Ñ�том выпуÑ�ке пока нет файла длÑ� вашей Ñ�иÑ�темы. Скачайте новую верÑ�ию на Ñ�айте:", + "Cette version n'a pas encore de fichier pour votre système. Téléchargez-la sur le site :", + "Diese Version hat noch keine Datei für Ihr System. Laden Sie sie von der Website:", + "Esta versión aún no tiene archivo para tu sistema. Descárgala en el sitio web:", + "Questa versione non ha ancora un file per il tuo sistema. Scaricala dal sito:", + "Esta versão ainda não tem arquivo para o seu sistema. Baixe a nova versão no site:", + "Bu nashrda hali tizimingiz uchun fayl yo‘q. Yangi versiyani saytdan yuklab oling:", + "Бұл шығарылымда Ñ�іздің жүйеңізге арналған файл әлі жоқ. Жаңа нұÑ�қаны Ñ�айттан жүктеп алыңыз:", + ], + [ + "Not now", + "Ð�е Ñ�ейчаÑ�", + "Pas maintenant", + "Nicht jetzt", + "Ahora no", + "Non ora", + "Agora não", + "Hozir emas", + "Қазір емеÑ�", + ], + [ + "Skip this version", + "ПропуÑ�тить Ñ�ту верÑ�ию", + "Ignorer cette version", + "Diese Version überspringen", + "Omitir esta versión", + "Salta questa versione", + "Pular esta versão", + "Bu versiyani o‘tkazib yuborish", + "Бұл нұÑ�қаны өткізіп жіберу", + ], + [ + "The button next to Settings is hidden until the next version; Settings → About still offers this one", + "Кнопка Ñ€Ñ�дом Ñ� «Ð�аÑ�тройками» Ñ�прÑ�четÑ�Ñ� до Ñ�ледующей верÑ�ии; в «Ð�аÑ�тройки → О программе» Ñ�ту можно будет поÑ�тавить", + "Le bouton près de Réglages est masqué jusqu'à la prochaine version ; Réglages → À propos propose toujours celle-ci", + "Der Knopf neben Einstellungen wird bis zur nächsten Version ausgeblendet; Einstellungen → Über bietet diese weiterhin an", + "El botón junto a Ajustes se oculta hasta la próxima versión; Ajustes → Acerca de sigue ofreciendo esta", + "Il pulsante accanto a Impostazioni resta nascosto fino alla prossima versione; Impostazioni → Informazioni offre ancora questa", + "O botão ao lado de Configurações fica oculto até a próxima versão; Configurações → Sobre ainda oferece esta", + "Sozlamalar yonidagi tugma keyingi versiyagacha yashiriladi; Sozlamalar → Dastur haqida bo‘limida bu versiya baribir taklif qilinadi", + "Баптаулар жанындағы түйме келеÑ�Ñ– нұÑ�қаға дейін жаÑ�ырылады; Баптаулар → Бағдарлама туралы бөлімінде бұл нұÑ�қа әлі Ò±Ñ�ынылады", + ], + [ + "⬇ {v}: {p} %", + "⬇ {v}: {p} %", + "⬇ {v} : {p} %", + "⬇ {v}: {p} %", + "⬇ {v}: {p} %", + "⬇ {v}: {p} %", + "⬇ {v}: {p} %", + "⬇ {v}: {p} %", + "⬇ {v}: {p} %", + ], + [ + "⟳ Restart for {v}", + "⟳ ПерезапуÑ�тить ({v})", + "⟳ Redémarrer ({v})", + "⟳ Neu starten ({v})", + "⟳ Reiniciar ({v})", + "⟳ Riavvia ({v})", + "⟳ Reiniciar para {v}", + "⟳ {v} uchun qayta ishga tushirish", + "⟳ {v} үшін қайта Ñ–Ñ�ке қоÑ�у", + ], + [ + "⬆ {v}: install", + "⬆ {v}: уÑ�тановить", + "⬆ {v} : installer", + "⬆ {v}: installieren", + "⬆ {v}: instalar", + "⬆ {v}: installa", + "⬆ {v}: instalar", + "⬆ {v}: o‘rnatish", + "⬆ {v}: орнату", + ], + [ + "Version {v} is installed", + "ВерÑ�иÑ� {v} уÑ�тановлена", + "La version {v} est installée", + "Version {v} ist installiert", + "La versión {v} está instalada", + "La versione {v} è installata", + "Versão {v} instalada", + "{v} versiyasi o‘rnatildi", + "{v} нұÑ�қаÑ�Ñ‹ орнатылды", + ], + [ + "The file is in the folder {dir}.", + "Файл Ñ�охранён в папку {dir}.", + "Le fichier est dans le dossier {dir}.", + "Die Datei liegt im Ordner {dir}.", + "El archivo está en la carpeta {dir}.", + "Il file è nella cartella {dir}.", + "O arquivo está na pasta {dir}.", + "Fayl {dir} jildida.", + "Файл {dir} қалтаÑ�ында.", + ], + [ + "or: {c}", + "или: {c}", + "ou : {c}", + "oder: {c}", + "o: {c}", + "oppure: {c}", + "ou: {c}", + "yoki: {c}", + "немеÑ�е: {c}", + ], + [ + "ChessPenguin downloads the new version ({mb} MB), checks it and puts it in place of this one. Databases, games and settings are not touched.", + "Программа Ñ�качает новую верÑ�ию ({mb} МБ), проверит её и заменит текущую. Базы, партии и наÑ�тройки не затрагиваютÑ�Ñ�.", + "ChessPenguin télécharge la nouvelle version ({mb} Mo), la vérifie et la met à la place de celle-ci. Bases, parties et réglages ne sont pas touchés.", + "ChessPenguin lädt die neue Version ({mb} MB), prüft sie und ersetzt diese. Datenbanken, Partien und Einstellungen bleiben unberührt.", + "ChessPenguin descarga la nueva versión ({mb} MB), la comprueba y sustituye a esta. Las bases, partidas y ajustes no se tocan.", + "ChessPenguin scarica la nuova versione ({mb} MB), la verifica e la mette al posto di questa. Basi, partite e impostazioni non vengono toccate.", + "O ChessPenguin baixa a nova versão ({mb} MB), verifica e coloca no lugar desta. Bases, partidas e configurações não são tocadas.", + "ChessPenguin yangi versiyani yuklab oladi ({mb} MB), tekshiradi va bunisining o‘rniga qo‘yadi. Bazalar, partiyalar va sozlamalarga tegilmaydi.", + "ChessPenguin жаңа нұÑ�қаны ({mb} МБ) жүктеп, текÑ�еріп, оÑ�ының орнына қоÑ�ды. Базалар, партиÑ�лар мен баптаулар өзгермейді.", + ], + [ + "ChessPenguin downloads the disk image ({mb} MB), checks it and opens it; then you drag the app over the old one, as when you installed it.", + "Программа Ñ�качает образ диÑ�ка ({mb} МБ), проверит и откроет его; затем вы перетащите программу поверх Ñ�тарой, как при уÑ�тановке.", + "ChessPenguin télécharge l'image disque ({mb} Mo), la vérifie et l'ouvre ; vous glissez ensuite l'app sur l'ancienne, comme à l'installation.", + "ChessPenguin lädt das Disk-Image ({mb} MB), prüft und öffnet es; dann ziehen Sie die App über die alte, wie bei der Installation.", + "ChessPenguin descarga la imagen de disco ({mb} MB), la comprueba y la abre; luego arrastras la app sobre la antigua, como al instalarla.", + "ChessPenguin scarica l'immagine disco ({mb} MB), la verifica e la apre; poi trascini l'app sopra la vecchia, come all'installazione.", + "O ChessPenguin baixa a imagem de disco ({mb} MB), verifica e abre; depois você arrasta o app sobre o antigo, como na instalação.", + "ChessPenguin disk obrazini yuklab oladi ({mb} MB), tekshiradi va ochadi; so‘ng dasturni o‘rnatgandagidek eskisining ustiga tortasiz.", + "ChessPenguin диÑ�к бейнеÑ�ін ({mb} МБ) жүктеп, текÑ�еріп, ашады; Ñ�одан кейін орнатқандағыдай, бағдарламаны еÑ�кіÑ�інің Ò¯Ñ�тіне Ñ�үйреп апараÑ�ыз.", + ], + [ + "ChessPenguin was installed through the system (its package manager), so it cannot replace itself. It downloads the new version ({mb} MB) into Downloads; to install it you run one command in a terminal, which you can copy.", + "ChessPenguin уÑ�тановлен через Ñ�иÑ�тему (менеджер пакетов), поÑ�тому заменить Ñ�ебÑ� Ñ�ам не может. Программа Ñ�качает новую верÑ�ию ({mb} МБ) в «Загрузки», а уÑ�тановить её нужно одной командой в терминале — её можно будет Ñ�копировать.", + "ChessPenguin a été installé par le système (son gestionnaire de paquets) : il ne peut pas se remplacer lui-même. Il télécharge la nouvelle version ({mb} Mo) dans Téléchargements ; pour l'installer, lancez une commande dans un terminal, que vous pourrez copier.", + "ChessPenguin wurde über das System (Paketverwaltung) installiert und kann sich nicht selbst ersetzen. Es lädt die neue Version ({mb} MB) nach Downloads; zum Installieren führen Sie einen Befehl im Terminal aus, den Sie kopieren können.", + "ChessPenguin se instaló a través del sistema (su gestor de paquetes), así que no puede reemplazarse solo. Descarga la nueva versión ({mb} MB) en Descargas; para instalarla ejecutas un comando en una terminal, que podrás copiar.", + "ChessPenguin è stato installato tramite il sistema (il gestore dei pacchetti), quindi non può sostituirsi da solo. Scarica la nuova versione ({mb} MB) in Download; per installarla esegui un comando in un terminale, che potrai copiare.", + "O ChessPenguin foi instalado pelo sistema (seu gerenciador de pacotes), então não pode se substituir. Ele baixa a nova versão ({mb} MB) em Downloads; para instalá-la, você executa um comando no terminal, que pode ser copiado.", + "ChessPenguin tizim orqali (paket menejeri bilan) o‘rnatilgan, shuning uchun o‘zini o‘zi almashtira olmaydi. U yangi versiyani ({mb} MB) Downloads jildiga yuklab oladi; o‘rnatish uchun terminalda bitta buyruqni bajarasiz, uni nusxalash mumkin.", + "ChessPenguin жүйе арқылы (пакет менеджерімен) орнатылған, Ñ�ондықтан өзін өзі ауыÑ�тыра алмайды. Ол жаңа нұÑ�қаны ({mb} МБ) Downloads қалтаÑ�ына жүктейді; орнату үшін терминалда бір команда орындайÑ�ыз, оны көшіріп алуға болады.", + ], + [ + "Installation: {kind}", + "Тип уÑ�тановки: {kind}", + "Installation : {kind}", + "Installation: {kind}", + "Instalación: {kind}", + "Installazione: {kind}", + "Instalação: {kind}", + "O‘rnatish: {kind}", + "Орнату түрі: {kind}", + ], + [ + "You have {old}", + "У ваÑ� {old}", + "Vous avez {old}", + "Sie haben {old}", + "Tienes la {old}", + "Hai la {old}", + "Você tem a {old}", + "Sizda {old}", + "Сізде {old}", + ], + [ + "Otherwise each site gets a database of its own", + "Иначе у каждого Ñ�айта будет Ñ�воÑ� база", + "Sinon chaque site a sa propre base", + "Sonst bekommt jede Seite eine eigene Datenbank", + "Si no, cada sitio tendrá su propia base", + "Altrimenti ogni sito avrà la sua base", + "Senão cada site recebe uma base própria", + "Aks holda har bir sayt uchun alohida baza bo‘ladi", + "ӘйтпеÑ�е әр Ñ�айттың өз базаÑ�Ñ‹ болады", + ], + [ + "Download any player's games by nickname into a database: yours, a pupil's, an opponent's", + "Скачать партии любого игрока по нику в базу: Ñ�вои, ученика, Ñ�оперника", + "Télécharger les parties de n'importe quel joueur par pseudo dans une base : les vôtres, celles d'un élève, d'un adversaire", + "Partien beliebiger Spieler per Nickname in eine Datenbank laden: eigene, eines Schülers, eines Gegners", + "Descargar las partidas de cualquier jugador por apodo a una base: las tuyas, de un alumno, de un rival", + "Scarica le partite di qualsiasi giocatore per nickname in una base: le tue, di un allievo, di un avversario", + "Baixe as partidas de qualquer jogador pelo nick para uma base: suas, de um aluno, de um adversário", + "Istalgan o‘yinchining partiyalarini taxallus bo‘yicha bazaga yuklab olish: o‘zingizniki, shogirdingizniki, raqibingizniki", + "Кез келген ойыншының партиÑ�ларын лақап аты бойынша базаға жүктеу: өзіңіздің, оқушының, қарÑ�ылаÑ�тың", + ], + [ + "Online games", + "Онлайн-партии", + "Parties en ligne", + "Online-Partien", + "Partidas en línea", + "Partite online", + "Partidas online", + "Onlayn partiyalar", + "Онлайн ойындар", + ], + [ + "No connection to Lichess and Chess.com", + "Ð�ет Ñ�вÑ�зи Ñ� Lichess и Chess.com", + "Pas de connexion à Lichess et Chess.com", + "Keine Verbindung zu Lichess und Chess.com", + "Sin conexión con Lichess y Chess.com", + "Nessuna connessione a Lichess e Chess.com", + "Sem conexão com Lichess e Chess.com", + "Lichess va Chess.com bilan aloqa yo‘q", + "Lichess және Chess.com-мен байланыÑ� жоқ", + ], + [ + "⟳ New games", + "⟳ Ð�овые партии", + "⟳ Nouvelles parties", + "⟳ Neue Partien", + "⟳ Partidas nuevas", + "⟳ Nuove partite", + "⟳ Novas partidas", + "⟳ Yangi partiyalar", + "⟳ Жаңа партиÑ�лар", + ], + [ + "downloading… {n}", + "Ñ�качиваетÑ�Ñ�… {n}", + "téléchargement… {n}", + "wird geladen… {n}", + "descargando… {n}", + "download… {n}", + "baixando… {n}", + "yuklab olinmoqda… {n}", + "жүктелуде… {n}", + ], + [ + "Fetch the games played since the last download ({when})", + "Скачать партии, Ñ�ыгранные поÑ�ле прошлой загрузки ({when})", + "Récupérer les parties jouées depuis le dernier téléchargement ({when})", + "Die seit dem letzten Download gespielten Partien holen ({when})", + "Descargar las partidas jugadas desde la última descarga ({when})", + "Scarica le partite giocate dall'ultimo download ({when})", + "Baixar as partidas jogadas desde o último download ({when})", + "Oxirgi yuklab olishdan keyin o‘ynalgan partiyalarni olish ({when})", + "Соңғы жүктеуден ({when}) кейін ойналған партиÑ�ларды алу", + ], + [ + "{n} min ago", + "{n} мин назад", + "il y a {n} min", + "vor {n} Min.", + "hace {n} min", + "{n} min fa", + "há {n} min", + "{n} daq. oldin", + "{n} мин бұрын", + ], + [ + "{n} h ago", + "{n} ч назад", + "il y a {n} h", + "vor {n} Std.", + "hace {n} h", + "{n} h fa", + "há {n} h", + "{n} soat oldin", + "{n} Ñ�ағ бұрын", + ], + [ + "{n} d ago", + "{n} дн. назад", + "il y a {n} j", + "vor {n} T.", + "hace {n} d", + "{n} g fa", + "há {n} d", + "{n} kun oldin", + "{n} күн бұрын", + ], + [ + "Could not write the database: no permission to write or the disk is full.", + "Ð�е удалоÑ�ÑŒ запиÑ�ать базу: нет прав на запиÑ�ÑŒ или диÑ�к заполнен.", + "Impossible d'écrire la base : pas de droit d'écriture ou disque plein.", + "Die Datenbank konnte nicht geschrieben werden: keine Schreibrechte oder die Festplatte ist voll.", + "No se pudo escribir la base: sin permiso de escritura o el disco está lleno.", + "Impossibile scrivere la base: nessun permesso di scrittura o disco pieno.", + "Não foi possível gravar a base: sem permissão de gravação ou disco cheio.", + "Bazani yozib bo‘lmadi: yozishga ruxsat yo‘q yoki disk to‘la.", + "Базаны жазу мүмкін болмады: жазуға Ñ€Ò±Ò›Ñ�ат жоқ немеÑ�е диÑ�к толы.", + ], + [ + "This database is being downloaded already.", + "Эта база уже Ñ�качиваетÑ�Ñ�.", + "Cette base est déjà en cours de téléchargement.", + "Diese Datenbank wird bereits geladen.", + "Esta base ya se está descargando.", + "Questa base è già in download.", + "Esta base já está sendo baixada.", + "Bu baza allaqachon yuklab olinmoqda.", + "Бұл база қазір жүктелуде.", + ], + [ + "Games from Lichess and Chess.com", + "Партии Ñ� Lichess и Chess.com", + "Parties de Lichess et Chess.com", + "Partien von Lichess und Chess.com", + "Partidas de Lichess y Chess.com", + "Partite da Lichess e Chess.com", + "Partidas do Lichess e do Chess.com", + "Lichess va Chess.com partiyalari", + "Lichess және Chess.com партиÑ�лары", + ], + [ + "Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.", + "Партии любого игрока — Ñ�вои, ученика, Ñ�оперника — Ñ�танут здеÑ�ÑŒ базой длÑ� поиÑ�ка и анализа. Ð�ужен только ник, входить в аккаунт не нужно.", + "Les parties de n'importe quel joueur — les vôtres, celles d'un élève, d'un adversaire — deviennent ici une base pour chercher et analyser. Seul le pseudo est nécessaire, sans connexion.", + "Die Partien beliebiger Spieler — eigene, eines Schülers, eines Gegners — werden hier zu einer Datenbank zum Suchen und Analysieren. Nur der Nickname ist nötig, keine Anmeldung.", + "Las partidas de cualquier jugador — las tuyas, de un alumno, de un rival — se convierten aquí en una base para buscar y analizar. Solo hace falta el apodo, sin iniciar sesión.", + "Le partite di qualsiasi giocatore — le tue, di un allievo, di un avversario — diventano qui una base da cercare e analizzare. Serve solo il nickname, nessun accesso.", + "As partidas de qualquer jogador — suas, de um aluno, de um adversário — viram uma base aqui, para buscar e analisar. Basta o nick, sem login.", + "Istalgan o‘yinchining partiyalari — o‘zingizniki, shogirdingizniki, raqibingizniki — bu yerda qidirish va tahlil uchun bazaga aylanadi. Faqat taxallus kerak, hisobga kirish shart emas.", + "Кез келген ойыншының партиÑ�лары — өзіңіздің, оқушының, қарÑ�ылаÑ�тың — мұнда іздеу мен талдауға арналған базаға айналады. Тек лақап ат керек, тіркелгіге кірудің қажеті жоқ.", + ], + [ + "Player's nickname", + "Ð�ик игрока", + "Pseudo du joueur", + "Nickname des Spielers", + "Apodo del jugador", + "Nickname del giocatore", + "Nick do jogador", + "O‘yinchi taxallusi", + "Ойыншының лақап аты", + ], + [ + "Merge the games of both sites into one database", + "Объединить партии Ñ� обоих Ñ�айтов в одну базу", + "Réunir les parties des deux sites dans une seule base", + "Partien beider Seiten in einer Datenbank zusammenführen", + "Unir las partidas de ambos sitios en una sola base", + "Unire le partite di entrambi i siti in una sola base", + "Juntar as partidas dos dois sites em uma base", + "Ikkala sayt partiyalarini bitta bazaga birlashtirish", + "Екі Ñ�айттың партиÑ�ларын бір базаға біріктіру", + ], + [ + "What is downloaded is kept; downloading again continues from there", + "Скачанное Ñ�охранитÑ�Ñ�; Ñ�ледующаÑ� загрузка продолжит Ñ� Ñ�того меÑ�та", + "Ce qui est téléchargé est conservé ; le prochain téléchargement reprend à partir de là", + "Bereits Geladenes bleibt; der nächste Download setzt dort fort", + "Lo descargado se conserva; la próxima descarga continúa desde ahí", + "Il già scaricato resta; il prossimo download riprende da lì", + "O que foi baixado fica guardado; baixar de novo continua dali", + "Yuklab olingani saqlanadi; qayta yuklab olish shu yerdan davom etadi", + "Жүктелгені Ñ�ақталады; қайта жүктеу Ñ�ол жерден жалғаÑ�ады", + ], + [ + "You can close the window: the download goes on, and what is downloaded is kept.", + "Окно можно закрыть: загрузка продолжитÑ�Ñ�, Ñ�качанное не пропадёт.", + "Vous pouvez fermer la fenêtre : le téléchargement continue et ce qui est téléchargé est conservé.", + "Das Fenster kann geschlossen werden: der Download läuft weiter, Geladenes bleibt erhalten.", + "Puedes cerrar la ventana: la descarga continúa y lo descargado se conserva.", + "Puoi chiudere la finestra: il download continua e il già scaricato resta.", + "Você pode fechar a janela: o download continua, e o que foi baixado fica guardado.", + "Oynani yopishingiz mumkin: yuklab olish davom etadi, yuklab olingani saqlanadi.", + "Терезені жаба беруге болады: жүктеу жалғаÑ�ады, жүктелгені Ñ�ақталады.", + ], + [ + "Open the database", + "Открыть базу", + "Ouvrir la base", + "Datenbank öffnen", + "Abrir la base", + "Apri la base", + "Abrir a base", + "Bazani ochish", + "Базаны ашу", + ], + [ + "{p} does not answer. Check the internet connection and try again.", + "{p} не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.", + "{p} ne répond pas. Vérifiez la connexion Internet et réessayez.", + "{p} antwortet nicht. Prüfen Sie die Internetverbindung und versuchen Sie es erneut.", + "{p} no responde. Comprueba la conexión a internet e inténtalo de nuevo.", + "{p} non risponde. Controlla la connessione a internet e riprova.", + "{p} não responde. Verifique a conexão com a internet e tente de novo.", + "{p} javob bermayapti. Internet aloqasini tekshirib, qayta urinib ko‘ring.", + "{p} жауап бермейді. Интернет байланыÑ�ын текÑ�еріп, қайталап көріңіз.", + ], + [ + "{p} asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.", + "{p} проÑ�ит Ñ�делать паузу: Ñ�лишком много запроÑ�ов подрÑ�д. Подождите минуту и попробуйте Ñ�нова — Ñ�качанное Ñ�охранитÑ�Ñ�.", + "{p} demande une pause : trop de requêtes d'affilée. Attendez une minute et réessayez ; ce qui est téléchargé est conservé.", + "{p} bittet um eine Pause: zu viele Anfragen hintereinander. Warten Sie eine Minute und versuchen Sie es erneut; Geladenes bleibt erhalten.", + "{p} pide una pausa: demasiadas solicitudes seguidas. Espera un minuto e inténtalo de nuevo; lo descargado se conserva.", + "{p} chiede una pausa: troppe richieste di fila. Aspetta un minuto e riprova; il già scaricato resta.", + "{p} pede uma pausa: muitas solicitações seguidas. Espere um minuto e tente de novo; o que foi baixado fica guardado.", + "{p} tanaffus so‘rayapti: ketma-ket juda ko‘p so‘rov. Bir daqiqa kutib, qayta urinib ko‘ring; yuklab olingani saqlanadi.", + "{p} үзіліÑ� Ñ�ұрайды: қатарынан тым көп Ñ�ұраныÑ�. Бір минут күтіп, қайталап көріңіз; жүктелгені Ñ�ақталады.", + ], + [ + "{p} answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.", + "{p} ответил непонÑ�тно — возможно, Ñ�айт что-то поменÑ�л. Попробуйте позже или обновите ChessPenguin.", + "{p} a répondu d'une façon que ChessPenguin ne comprend pas : le site a peut-être changé. Réessayez plus tard ou mettez ChessPenguin à jour.", + "{p} hat unverständlich geantwortet: die Seite hat sich vielleicht geändert. Versuchen Sie es später oder aktualisieren Sie ChessPenguin.", + "{p} respondió de una forma que ChessPenguin no entiende: quizá el sitio cambió. Inténtalo más tarde o actualiza ChessPenguin.", + "{p} ha risposto in un modo che ChessPenguin non capisce: forse il sito è cambiato. Riprova più tardi o aggiorna ChessPenguin.", + "{p} respondeu de um jeito que o ChessPenguin não entende: o site pode ter mudado. Tente mais tarde ou atualize o ChessPenguin.", + "{p} ChessPenguin tushunmaydigan tarzda javob berdi: sayt o‘zgargan bo‘lishi mumkin. Keyinroq urinib ko‘ring yoki ChessPenguinni yangilang.", + "{p} ChessPenguin түÑ�інбейтін жауап берді: Ñ�айт өзгерген болуы мүмкін. Кейінірек көріңіз немеÑ�е ChessPenguin-ді жаңартыңыз.", + ], + [ + "“{name}â€�: stopped, {total} in the database", + "«{name}»: оÑ�тановлено, в базе {total}", + "« {name} » : arrêté, {total} dans la base", + "„{name}“: angehalten, {total} in der Datenbank", + "«{name}»: detenido, {total} en la base", + "«{name}»: fermato, {total} nella base", + "“{name}â€�: parado, {total} na base", + "“{name}â€�: to‘xtatildi, bazada {total}", + "«{name}»: тоқтатылды, базада {total}", + ], + [ + "“{name}â€�: no new games", + "«{name}»: новых партий нет", + "« {name} » : pas de nouvelles parties", + "„{name}“: keine neuen Partien", + "«{name}»: no hay partidas nuevas", + "«{name}»: nessuna partita nuova", + "“{name}â€�: sem partidas novas", + "“{name}â€�: yangi partiyalar yo‘q", + "«{name}»: жаңа партиÑ� жоқ", + ], + [ + "“{name}â€�: +{added}, {total} in all", + "«{name}»: +{added}, вÑ�его {total}", + "« {name} » : +{added}, {total} en tout", + "„{name}“: +{added}, insgesamt {total}", + "«{name}»: +{added}, {total} en total", + "«{name}»: +{added}, {total} in tutto", + "“{name}â€�: +{added}, {total} no total", + "“{name}â€�: +{added}, jami {total}", + "«{name}»: +{added}, барлығы {total}", + ], + [ + "“{name}â€�: {e}", + "«{name}»: {e}", + "« {name} » : {e}", + "„{name}“: {e}", + "«{name}»: {e}", + "«{name}»: {e}", + "“{name}â€�: {e}", + "“{name}â€�: {e}", + "«{name}»: {e}", + ], + [ + "{p}: {name} — {games}, about {m} min the first time", + "{p}: {name} — {games}, первый раз около {m} мин", + "{p} : {name} — {games}, environ {m} min la première fois", + "{p}: {name} — {games}, beim ersten Mal etwa {m} Min.", + "{p}: {name} — {games}, la primera vez unos {m} min", + "{p}: {name} — {games}, la prima volta circa {m} min", + "{p}: {name} — {games}, cerca de {m} min na primeira vez", + "{p}: {name} — {games}, birinchi marta taxminan {m} daq.", + "{p}: {name} — {games}, алғашқы рет шамамен {m} мин", + ], + [ + "{p}: {name} — {games}", + "{p}: {name} — {games}", + "{p} : {name} — {games}", + "{p}: {name} — {games}", + "{p}: {name} — {games}", + "{p}: {name} — {games}", + "{p}: {name} — {games}", + "{p}: {name} — {games}", + "{p}: {name} — {games}", + ], + [ + "{p}: {name} — months with games: {m}", + "{p}: {name} — меÑ�Ñ�цев Ñ� партиÑ�ми: {m}", + "{p} : {name} — mois avec des parties : {m}", + "{p}: {name} — Monate mit Partien: {m}", + "{p}: {name} — meses con partidas: {m}", + "{p}: {name} — mesi con partite: {m}", + "{p}: {name} — meses com partidas: {m}", + "{p}: {name} — partiyali oylar: {m}", + "{p}: {name} — партиÑ�лары бар айлар: {m}", + ], + [ + "✖ {p}: no player with this nickname — check the spelling", + "✖ {p}: игрока Ñ� таким ником нет — проверьте напиÑ�ание", + "✖ {p} : aucun joueur avec ce pseudo — vérifiez l'orthographe", + "✖ {p}: kein Spieler mit diesem Nickname — prüfen Sie die Schreibweise", + "✖ {p}: no hay ningún jugador con este apodo — revisa cómo se escribe", + "✖ {p}: nessun giocatore con questo nickname — controlla come si scrive", + "✖ {p}: nenhum jogador com este nick — confira a grafia", + "✖ {p}: bunday taxallusli o‘yinchi yo‘q — yozilishini tekshiring", + "✖ {p}: мұндай лақап аты бар ойыншы жоқ — жазылуын текÑ�еріңіз", + ], + [ + "Into “{name}â€� (already {n} there; only new games are added)", + "Ð’ базу «{name}» (там уже {n}; добавÑ�Ñ‚Ñ�Ñ� только новые)", + "Dans « {name} » (déjà {n} ; seules les nouvelles parties sont ajoutées)", + "In „{name}“ (schon {n} dort; nur neue Partien kommen dazu)", + "En «{name}» (ya hay {n}; solo se añaden las nuevas)", + "In «{name}» (già {n}; si aggiungono solo le nuove)", + "Para “{name}â€� (já tem {n}; só partidas novas são adicionadas)", + "“{name}â€� bazasiga (unda allaqachon {n}; faqat yangi partiyalar qo‘shiladi)", + "«{name}» базаÑ�ына (онда {n} бар; тек жаңа партиÑ�лар қоÑ�ылады)", + ], + [ + "Into the new database “{name}â€�", + "Ð’ новую базу «{name}»", + "Dans la nouvelle base « {name} »", + "In die neue Datenbank „{name}“", + "En la nueva base «{name}»", + "Nella nuova base «{name}»", + "Para a nova base “{name}â€�", + "Yangi “{name}â€� bazasiga", + "Жаңа «{name}» базаÑ�ына", + ], + [ + "Lichess: {n} of about {t} · about {m} min left", + "Lichess: {n} из примерно {t} · оÑ�талоÑ�ÑŒ около {m} мин", + "Lichess : {n} sur environ {t} · encore environ {m} min", + "Lichess: {n} von etwa {t} · noch etwa {m} Min.", + "Lichess: {n} de unas {t} · quedan unos {m} min", + "Lichess: {n} di circa {t} · mancano circa {m} min", + "Lichess: {n} de cerca de {t} · faltam cerca de {m} min", + "Lichess: {n} / taxminan {t} · taxminan {m} daq. qoldi", + "Lichess: {n} / шамамен {t} · шамамен {m} мин қалды", + ], + [ + "Chess.com: month {i} of {n} · {games}", + "Chess.com: меÑ�Ñ�ц {i} из {n} · {games}", + "Chess.com : mois {i} sur {n} · {games}", + "Chess.com: Monat {i} von {n} · {games}", + "Chess.com: mes {i} de {n} · {games}", + "Chess.com: mese {i} di {n} · {games}", + "Chess.com: mês {i} de {n} · {games}", + "Chess.com: oy {i} / {n} · {games}", + "Chess.com: ай {i} / {n} · {games}", + ], + [ + "Checking engine…", + "Проверка движка…", + "Vérification du moteur…", + "Engine wird geprüft…", + "Comprobando el motor…", + "Verifica del motore…", + "Verificando o motor…", + "Dvigatel tekshirilmoqda…", + "Қозғалтқыш текÑ�ерілуде…", + ], + [ + "Piece set", + "Ð�абор фигур", + "Jeu de pièces", + "Figurensatz", + "Juego de piezas", + "Set di pezzi", + "Conjunto de peças", + "Figuralar to‘plami", + "Фигуралар жиыны", + ], + [ + "Board", + "ДоÑ�ка", + "Échiquier", + "Brett", + "Tablero", + "Scacchiera", + "Tabuleiro", + "Taxta", + "Тақта", + ], + [ + "Show coordinates", + "Показывать координаты", + "Afficher les coordonnées", + "Koordinaten anzeigen", + "Mostrar coordenadas", + "Mostra coordinate", + "Mostrar coordenadas", + "Koordinatalarni ko‘rsatish", + "Координаттарды көрÑ�ету", + ], + [ + "Show engine best-move arrows", + "Показывать Ñ�трелки лучших ходов движка", + "Afficher les flèches des meilleurs coups", + "Pfeile für beste Engine-Züge anzeigen", + "Mostrar flechas de las mejores jugadas", + "Mostra frecce delle mosse migliori", + "Mostrar setas do melhor lance do motor", + "Dvigatelning eng yaxshi yurish strelkalarini ko‘rsatish", + "Қозғалтқыштың үздік жүріÑ� көрÑ�еткілерін көрÑ�ету", + ], + [ + "Move sounds", + "Звуки ходов", + "Sons des coups", + "Zuggeräusche", + "Sonidos de jugadas", + "Suoni delle mosse", + "Sons dos lances", + "Yurish ovozlari", + "ЖүріÑ� дыбыÑ�тары", + ], + [ + "Set:", + "Ð�абор:", + "Jeu :", + "Satz:", + "Conjunto:", + "Set:", + "Conjunto:", + "To‘plam:", + "Жиын:", + ], + [ + "Volume:", + "ГромкоÑ�ть:", + "Volume :", + "Lautstärke:", + "Volumen:", + "Volume:", + "Volume:", + "Ovoz balandligi:", + "ДыбыÑ� деңгейі:", + ], + [ + "â–¶ Test", + "â–¶ Проверить", + "â–¶ Tester", + "â–¶ Testen", + "â–¶ Probar", + "â–¶ Prova", + "â–¶ Testar", + "â–¶ Sinash", + "â–¶ ТекÑ�еру", + ], + // --- library --- + [ + "Loading cancelled", + "Загрузка отменена", + "Chargement annulé", + "Laden abgebrochen", + "Carga cancelada", + "Caricamento annullato", + "Carregamento cancelado", + "Yuklash bekor qilindi", + "Жүктеу тоқтатылды", + ], + [ + "Databases", + "Базы", + "Bases", + "Datenbanken", + "Bases", + "Database", + "Bases", + "Bazalar", + "Базалар", + ], + [ + "âš™ Settings", + "âš™ Ð�аÑ�тройки", + "âš™ Paramètres", + "âš™ Einstellungen", + "âš™ Ajustes", + "âš™ Impostazioni", + "âš™ Configurações", + "âš™ Sozlamalar", + "âš™ Баптаулар", + ], + [ + "📋 Paste PGN", + "📋 Ð’Ñ�тавить PGN", + "📋 Coller un PGN", + "📋 PGN einfügen", + "📋 Pegar PGN", + "📋 Incolla PGN", + "📋 Colar PGN", + "📋 PGN qo‘yish", + "📋 PGN қою", + ], + [ + "Open a game from the clipboard", + "Открыть партию из буфера обмена", + "Ouvrir une partie depuis le presse-papiers", + "Partie aus der Zwischenablage öffnen", + "Abrir una partida del portapapeles", + "Apri una partita dagli appunti", + "Abrir uma partida da área de transferência", + "Almashish buferidan partiyani ochish", + "Ð�лмаÑ�у буферінен партиÑ� ашу", + ], + [ + "♟ New game", + "♟ Ð�оваÑ� партиÑ�", + "♟ Nouvelle partie", + "♟ Neue Partie", + "♟ Nueva partida", + "♟ Nuova partita", + "♟ Nova partida", + "♟ Yangi partiya", + "♟ Жаңа партиÑ�", + ], + [ + "Empty board in the starting position (Ctrl+N)", + "ПуÑ�таÑ� доÑ�ка в начальной позиции (Ctrl+N)", + "Échiquier en position initiale (Ctrl+N)", + "Brett in der Grundstellung (Ctrl+N)", + "Tablero en la posición inicial (Ctrl+N)", + "Scacchiera nella posizione iniziale (Ctrl+N)", + "Tabuleiro vazio na posição inicial (Ctrl+N)", + "Boshlang‘ich pozitsiyadagi bo‘sh taxta (Ctrl+N)", + "БаÑ�тапқы позициÑ�дағы боÑ� тақта (Ctrl+N)", + ], + [ + "{n} games", + "{n} партий", + "{n} parties", + "{n} Partien", + "{n} partidas", + "{n} partite", + "{n} partidas", + "{n} ta partiya", + "{n} партиÑ�", + ], + [ + "loading… {n}", + "загрузка… {n}", + "chargement… {n}", + "lädt… {n}", + "cargando… {n}", + "caricamento… {n}", + "carregando… {n}", + "yuklanmoqda… {n}", + "жүктелуде… {n}", + ], + [ + "error", + "ошибка", + "erreur", + "Fehler", + "error", + "errore", + "erro", + "xato", + "қате", + ], + [ + "file not found", + "файл не найден", + "fichier introuvable", + "Datei nicht gefunden", + "archivo no encontrado", + "file non trovato", + "arquivo não encontrado", + "fayl topilmadi", + "файл табылмады", + ], + [ + "Reload file", + "Перечитать файл", + "Recharger le fichier", + "Datei neu laden", + "Volver a leer el archivo", + "Ricarica il file", + "Recarregar arquivo", + "Faylni qayta o‘qish", + "Файлды қайта оқу", + ], + [ + "Choose a database above, add a PGN file or start a new game", + "Выберите базу Ñ�верху, добавьте PGN-файл или начните новую партию", + "Choisissez une base ci-dessus, ajoutez un fichier PGN ou commencez une nouvelle partie", + "Wählen Sie oben eine Datenbank, fügen Sie eine PGN-Datei hinzu oder beginnen Sie eine neue Partie", + "Elija una base arriba, añada un archivo PGN o empiece una partida nueva", + "Scegli un database in alto, aggiungi un file PGN o inizia una nuova partita", + "Escolha uma base acima, adicione um arquivo PGN ou comece uma nova partida", + "Yuqoridan baza tanlang, PGN fayl qo‘shing yoki yangi partiya boshlang", + "Жоғарыдан база таңдаңыз, PGN файлын қоÑ�ыңыз немеÑ�е жаңа партиÑ� баÑ�таңыз", + ], + [ + "Reading {path} — games found: {n}", + "Чтение {path} — найдено партий: {n}", + "Lecture de {path} — parties trouvées : {n}", + "Lese {path} — gefundene Partien: {n}", + "Leyendo {path}: partidas encontradas: {n}", + "Lettura di {path}: partite trovate: {n}", + "Lendo {path} — partidas encontradas: {n}", + "{path} o‘qilmoqda — topilgan partiyalar: {n}", + "{path} оқылуда — табылған партиÑ�лар: {n}", + ], + [ + "Could not open {path}: {e}", + "Ð�е удалоÑ�ÑŒ открыть {path}: {e}", + "Impossible d'ouvrir {path} : {e}", + "{path} konnte nicht geöffnet werden: {e}", + "No se pudo abrir {path}: {e}", + "Impossibile aprire {path}: {e}", + "Não foi possível abrir {path}: {e}", + "{path}ni ochib bo‘lmadi: {e}", + "{path} ашу мүмкін болмады: {e}", + ], + [ + "· {n} games · encoding {enc}", + "· {n} партий · кодировка {enc}", + "· {n} parties · encodage {enc}", + "· {n} Partien · Kodierung {enc}", + "· {n} partidas · codificación {enc}", + "· {n} partite · codifica {enc}", + "· {n} partidas · codificação {enc}", + "· {n} ta partiya · kodlash {enc}", + "· {n} партиÑ� · кодтау {enc}", + ], + [ + "ðŸ”� Search: player, event, ECO, year", + "ðŸ”� ПоиÑ�к: игрок, турнир, ECO, год", + "ðŸ”� Recherche : joueur, tournoi, ECO, année", + "ðŸ”� Suche: Spieler, Turnier, ECO, Jahr", + "ðŸ”� Buscar: jugador, torneo, ECO, año", + "ðŸ”� Cerca: giocatore, torneo, ECO, anno", + "ðŸ”� Buscar: jogador, evento, ECO, ano", + "ðŸ”� Qidirish: o‘yinchi, turnir, ECO, yil", + "ðŸ”� Іздеу: ойыншы, турнир, ECO, жыл", + ], + [ + "Result", + "Результат", + "Résultat", + "Ergebnis", + "Resultado", + "Risultato", + "Resultado", + "Natija", + "Ð�әтиже", + ], + [ + "Moves", + "Ходы", + "Coups", + "Züge", + "Jugadas", + "Mosse", + "Lances", + "Yurishlar", + "ЖүріÑ�тер", + ], + [ + "Event", + "Турнир", + "Tournoi", + "Turnier", + "Torneo", + "Torneo", + "Evento", + "Turnir", + "Турнир", + ], + [ + "Date", "Дата", "Date", "Datum", "Fecha", "Data", "Data", "Sana", "Күні", + ], + // --- game view --- + [ + "PGN compatibility", + "СовмеÑ�тимоÑ�ть PGN", + "Compatibilité PGN", + "PGN-Kompatibilität", + "Compatibilidad PGN", + "Compatibilità PGN", + "Compatibilidade PGN", + "PGN mosligi", + "PGN үйлеÑ�імділігі", + ], + [ + "line {n}: ", + "Ñ�трока {n}: ", + "ligne {n} : ", + "Zeile {n}: ", + "línea {n}: ", + "riga {n}: ", + "linha {n}: ", + "{n}-qator: ", + "{n}-жол: ", + ], + [ + "⬅ Library", + "⬅ Библиотека", + "⬅ Bibliothèque", + "⬅ Bibliothek", + "⬅ Biblioteca", + "⬅ Libreria", + "⬅ Biblioteca", + "⬅ Kutubxona", + "⬅ Кітапхана", + ], + [ + "Back to the game list (Ctrl+W)", + "ВернутьÑ�Ñ� к Ñ�пиÑ�ку партий (Ctrl+W)", + "Retour à la liste des parties (Ctrl+W)", + "Zurück zur Partienliste (Ctrl+W)", + "Volver a la lista de partidas (Ctrl+W)", + "Torna all'elenco delle partite (Ctrl+W)", + "Voltar à lista de partidas (Ctrl+W)", + "Partiyalar ro‘yxatiga qaytish (Ctrl+W)", + "ПартиÑ�лар тізіміне оралу (Ctrl+W)", + ], + [ + "Back to the game list (Esc, Ctrl+W)", + "ВернутьÑ�Ñ� к Ñ�пиÑ�ку партий (Esc, Ctrl+W)", + "Retour à la liste des parties (Esc, Ctrl+W)", + "Zurück zur Partienliste (Esc, Ctrl+W)", + "Volver a la lista de partidas (Esc, Ctrl+W)", + "Torna all'elenco delle partite (Esc, Ctrl+W)", + "Voltar à lista de partidas (Esc, Ctrl+W)", + "Partiyalar ro‘yxatiga qaytish (Esc, Ctrl+W)", + "ПартиÑ�лар тізіміне оралу (Esc, Ctrl+W)", + ], + [ + "PGN compatibility notes", + "ЗамечаниÑ� по Ñ�овмеÑ�тимоÑ�ти PGN", + "Remarques de compatibilité PGN", + "Hinweise zur PGN-Kompatibilität", + "Avisos de compatibilidad PGN", + "Note di compatibilità PGN", + "Notas de compatibilidade PGN", + "PGN mosligi bo‘yicha eslatmalar", + "PGN үйлеÑ�імділігі бойынша еÑ�кертпелер", + ], + [ + "Move not added: {e}", + "Ход не добавлен: {e}", + "Coup non ajouté : {e}", + "Zug nicht hinzugefügt: {e}", + "Jugada no añadida: {e}", + "Mossa non aggiunta: {e}", + "Lance não adicionado: {e}", + "Yurish qo‘shilmadi: {e}", + "ЖүріÑ� қоÑ�ылмады: {e}", + ], + [ + "Analysis: on", + "Ð�нализ: вкл", + "Analyse : activée", + "Analyse: an", + "Análisis: activado", + "Analisi: attiva", + "Análise: ligada", + "Tahlil: yoqiq", + "Талдау: қоÑ�улы", + ], + [ + "Analysis: off", + "Ð�нализ: выкл", + "Analyse : désactivée", + "Analyse: aus", + "Análisis: desactivado", + "Analisi: disattiva", + "Análise: desligada", + "Tahlil: o‘chiq", + "Талдау: өшірулі", + ], + [ + "Turn the engine on/off (L)", + "Включить/выключить движок (L)", + "Activer/désactiver le moteur (L)", + "Engine ein/aus (L)", + "Activar/desactivar el motor (L)", + "Attiva/disattiva il motore (L)", + "Ligar/desligar o motor (L)", + "Dvigatelni yoqish/o‘chirish (L)", + "Қозғалтқышты қоÑ�у/өшіру (L)", + ], + [ + "No engine selected", + "Движок не выбран", + "Aucun moteur sélectionné", + "Keine Engine gewählt", + "Ningún motor seleccionado", + "Nessun motore selezionato", + "Nenhum motor selecionado", + "Dvigatel tanlanmagan", + "Қозғалтқыш таңдалмаған", + ], + [ + "starting…", + "запуÑ�к…", + "démarrage…", + "startet…", + "iniciando…", + "avvio…", + "iniciando…", + "ishga tushmoqda…", + "Ñ–Ñ�ке қоÑ�ылуда…", + ], + [ + " · done", + " · готово", + " · terminé", + " · fertig", + " · listo", + " · completato", + " · pronto", + " · tayyor", + " · дайын", + ], + [ + " · {n} Mn/s", + " · {n} Музл/Ñ�", + " · {n} Mn/s", + " · {n} MKn/s", + " · {n} Mn/s", + " · {n} Mn/s", + " · {n} Mn/s", + " · {n} mln tugun/s", + " · {n} Мтүйін/Ñ�", + ], + [ + "Depth {n}", + "Глубина {n}", + "Profondeur {n}", + "Tiefe {n}", + "Profundidad {n}", + "Profondità {n}", + "Profundidade {n}", + "Chuqurlik {n}", + "Тереңдік {n}", + ], + [ + "Engine settings", + "Ð�аÑ�тройки движка", + "Réglages du moteur", + "Engine-Einstellungen", + "Ajustes del motor", + "Impostazioni del motore", + "Configurações do motor", + "Dvigatel sozlamalari", + "Қозғалтқыш баптаулары", + ], + [ + "Add as variation", + "Добавить как вариант", + "Ajouter comme variante", + "Als Variante hinzufügen", + "Añadir como variante", + "Aggiungi come variante", + "Adicionar como variante", + "Variant sifatida qo‘shish", + "Вариант ретінде қоÑ�у", + ], + [ + "Line added as a variation (Ctrl+Z to undo)", + "ЛиниÑ� добавлена как вариант (Ctrl+Z — отменить)", + "Ligne ajoutée comme variante (Ctrl+Z pour annuler)", + "Variante hinzugefügt (Ctrl+Z zum Rückgängigmachen)", + "Línea añadida como variante (Ctrl+Z para deshacer)", + "Linea aggiunta come variante (Ctrl+Z per annullare)", + "Linha adicionada como variante (Ctrl+Z para desfazer)", + "Liniya variant sifatida qo‘shildi (bekor qilish: Ctrl+Z)", + "Вариант ретінде қоÑ�ылды (болдырмау — Ctrl+Z)", + ], + [ + "Could not add the line: {e}", + "Ð�е удалоÑ�ÑŒ добавить линию: {e}", + "Impossible d'ajouter la ligne : {e}", + "Variante konnte nicht hinzugefügt werden: {e}", + "No se pudo añadir la línea: {e}", + "Impossibile aggiungere la linea: {e}", + "Não foi possível adicionar a linha: {e}", + "Liniyani qo‘shib bo‘lmadi: {e}", + "Вариантты қоÑ�у мүмкін болмады: {e}", + ], + [ + "To start (Home)", + "Ð’ начало (Home)", + "Au début (Début)", + "Zum Anfang (Pos1)", + "Al inicio (Inicio)", + "All'inizio (Home)", + "Ao início (Home)", + "Boshiga (Home)", + "БаÑ�ына (Home)", + ], + [ + "Back (â†�)", + "Ð�азад (â†�)", + "Reculer (â†�)", + "Zurück (â†�)", + "Atrás (â†�)", + "Indietro (â†�)", + "Voltar (â†�)", + "Orqaga (â†�)", + "Ð�ртқа (â†�)", + ], + [ + "Forward (→)", + "Вперёд (→)", + "Avancer (→)", + "Vor (→)", + "Adelante (→)", + "Avanti (→)", + "Avançar (→)", + "Oldinga (→)", + "Ð�лға (→)", + ], + [ + "To the end of the line (End)", + "Ð’ конец линии (End)", + "À la fin de la ligne (Fin)", + "Zum Ende der Variante (Ende)", + "Al final de la línea (Fin)", + "Alla fine della linea (Fine)", + "Ao fim da linha (End)", + "Liniya oxiriga (End)", + "Варианттың Ñ�оңына (End)", + ], + [ + "Flip board (F)", + "Перевернуть доÑ�ку (F)", + "Retourner l'échiquier (F)", + "Brett drehen (F)", + "Girar el tablero (F)", + "Ruota la scacchiera (F)", + "Girar tabuleiro (F)", + "Taxtani aylantirish (F)", + "Тақтаны аудару (F)", + ], + [ + "Undo move/edit (Ctrl+Z)", + "Отменить изменение (Ctrl+Z)", + "Annuler la modification (Ctrl+Z)", + "Änderung rückgängig (Ctrl+Z)", + "Deshacer cambio (Ctrl+Z)", + "Annulla modifica (Ctrl+Z)", + "Desfazer lance/edição (Ctrl+Z)", + "Yurish/tahrirni bekor qilish (Ctrl+Z)", + "ЖүріÑ�ті/түзетуді болдырмау (Ctrl+Z)", + ], + [ + "Redo move/edit (Ctrl+Y)", + "Вернуть изменение (Ctrl+Y)", + "Rétablir la modification (Ctrl+Y)", + "Änderung wiederherstellen (Ctrl+Y)", + "Rehacer cambio (Ctrl+Y)", + "Ripristina modifica (Ctrl+Y)", + "Refazer lance/edição (Ctrl+Y)", + "Yurish/tahrirni qaytarish (Ctrl+Y)", + "ЖүріÑ�ті/түзетуді қайтару (Ctrl+Y)", + ], + [ + "Copy PGN", + "Копировать PGN", + "Copier le PGN", + "PGN kopieren", + "Copiar PGN", + "Copia PGN", + "Copiar PGN", + "PGN nusxalash", + "PGN көшіру", + ], + [ + "PGN copied", + "PGN Ñ�копирован", + "PGN copié", + "PGN kopiert", + "PGN copiado", + "PGN copiato", + "PGN copiado", + "PGN nusxalandi", + "PGN көшірілді", + ], + [ + "Copy FEN", + "Копировать FEN", + "Copier la FEN", + "FEN kopieren", + "Copiar FEN", + "Copia FEN", + "Copiar FEN", + "FEN nusxalash", + "FEN көшіру", + ], + [ + "FEN copied", + "FEN Ñ�копирован", + "FEN copiée", + "FEN kopiert", + "FEN copiado", + "FEN copiato", + "FEN copiado", + "FEN nusxalandi", + "FEN көшірілді", + ], + [ + "Save game as…", + "Сохранить партию как…", + "Enregistrer la partie sous…", + "Partie speichern unter…", + "Guardar partida como…", + "Salva partita con nome…", + "Salvar partida como…", + "Partiyani boshqacha saqlash…", + "ПартиÑ�ны баÑ�қаша Ñ�ақтау…", + ], + [ + "Compatibility notes", + "ЗамечаниÑ� по Ñ�овмеÑ�тимоÑ�ти", + "Remarques de compatibilité", + "Kompatibilitätshinweise", + "Avisos de compatibilidad", + "Note di compatibilità", + "Notas de compatibilidade", + "Moslik eslatmalari", + "ҮйлеÑ�імділік еÑ�кертпелері", + ], + [ + "Copy PGN (Ctrl+Shift+C)", + "Копировать PGN (Ctrl+Shift+C)", + "Copier le PGN (Ctrl+Maj+C)", + "PGN kopieren (Ctrl+Umschalt+C)", + "Copiar PGN (Ctrl+Mayús+C)", + "Copia PGN (Ctrl+Maiusc+C)", + "Copiar PGN (Ctrl+Shift+C)", + "PGN nusxalash (Ctrl+Shift+C)", + "PGN көшіру (Ctrl+Shift+C)", + ], + [ + "Engine", + "Движок", + "Moteur", + "Engine", + "Motor", + "Motore", + "Motor", + "Dvigatel", + "Қозғалтқыш", + ], + [ + "not selected", + "не выбран", + "non sélectionné", + "nicht gewählt", + "no seleccionado", + "non selezionato", + "não selecionado", + "tanlanmagan", + "таңдалмаған", + ], + [ + "Add or edit engines…", + "Добавить или изменить движки…", + "Ajouter ou modifier des moteurs…", + "Engines hinzufügen oder bearbeiten…", + "Añadir o editar motores…", + "Aggiungi o modifica motori…", + "Adicionar ou editar motores…", + "Dvigatellarni qo‘shish yoki tahrirlash…", + "Қозғалтқыштарды қоÑ�у немеÑ�е өзгерту…", + ], + [ + "Add engine…", + "Добавить движок…", + "Ajouter un moteur…", + "Engine hinzufügen…", + "Añadir motor…", + "Aggiungi motore…", + "Adicionar motor…", + "Dvigatel qo‘shish…", + "Қозғалтқыш қоÑ�у…", + ], + [ + "Search time", + "ВремÑ� поиÑ�ка", + "Temps de recherche", + "Suchzeit", + "Tiempo de búsqueda", + "Tempo di ricerca", + "Tempo de busca", + "Qidiruv vaqti", + "Іздеу уақыты", + ], + [ + "{n} s", "{n} Ñ�", "{n} s", "{n} s", "{n} s", "{n} s", "{n} s", "{n} s", "{n} Ñ�", + ], + [ + "Lines", + "Линий", + "Lignes", + "Varianten", + "Líneas", + "Linee", + "Linhas", + "Liniyalar", + "Варианттар", + ], + [ + "Memory", + "ПамÑ�ть", + "Mémoire", + "Speicher", + "Memoria", + "Memoria", + "Memória", + "Xotira", + "Жад", + ], + [ + "{n} GB", "{n} ГБ", "{n} Go", "{n} GB", "{n} GB", "{n} GB", "{n} GB", "{n} GB", "{n} ГБ", + ], + [ + "{n} MB", "{n} МБ", "{n} Mo", "{n} MB", "{n} MB", "{n} MB", "{n} MB", "{n} MB", "{n} МБ", + ], + [ + "{n} KB", "{n} КБ", "{n} Ko", "{n} KB", "{n} KB", "{n} KB", "{n} KB", "{n} KB", "{n} КБ", + ], + [ + "none", "нет", "aucune", "keine", "ninguna", "nessuna", "nenhum", "yo‘q", "жоқ", + ], + [ + "Translation will not be offered again. To turn it back on: Settings › Translation.", + "Перевод больше не предлагаетÑ�Ñ�. Вернуть: Ð�аÑ�тройки › Перевод.", + "La traduction ne sera plus proposée. Pour la réactiver : Paramètres › Traduction.", + "Die Übersetzung wird nicht mehr angeboten. Wieder einschalten: Einstellungen › Übersetzung.", + "La traducción ya no se ofrecerá. Para reactivarla: Ajustes › Traducción.", + "La traduzione non verrà più proposta. Per riattivarla: Impostazioni › Traduzione.", + "A tradução não será oferecida de novo. Para reativar: Configurações › Tradução.", + "Tarjima boshqa taklif qilinmaydi. Qayta yoqish: Sozlamalar › Tarjima.", + "Ð�ударма енді Ò±Ñ�ынылмайды. Қайта қоÑ�у: Баптаулар › Ð�ударма.", + ], + [ + "Checkmate · 0-1", + "Мат · 0-1", + "Mat · 0-1", + "Matt · 0-1", + "Jaque mate · 0-1", + "Scacco matto · 0-1", + "Xeque-mate · 0-1", + "Mat · 0-1", + "Мат · 0-1", + ], + [ + "Checkmate · 1-0", + "Мат · 1-0", + "Mat · 1-0", + "Matt · 1-0", + "Jaque mate · 1-0", + "Scacco matto · 1-0", + "Xeque-mate · 1-0", + "Mat · 1-0", + "Мат · 1-0", + ], + [ + "Stalemate · ½-½", + "Пат · ½-½", + "Pat · ½-½", + "Patt · ½-½", + "Ahogado · ½-½", + "Stallo · ½-½", + "Afogamento · ½-½", + "Pat · ½-½", + "Пат · ½-½", + ], + [ + "Insufficient material", + "Ð�едоÑ�таточно материала", + "Matériel insuffisant", + "Ungenügendes Material", + "Material insuficiente", + "Materiale insufficiente", + "Material insuficiente", + "Material yetarli emas", + "Материал жеткілікÑ�із", + ], + // Whole-game analysis + [ + "Report: show or hide the evaluation graph and the report (Shift+A)", + "Отчёт: показать или Ñ�крыть график оценки и отчёт (Shift+A)", + "Rapport : afficher ou masquer le graphique d'évaluation et le rapport (Maj+A)", + "Bericht: Bewertungsgrafik und Bericht ein- oder ausblenden (Umschalt+A)", + "Informe: mostrar u ocultar el gráfico de evaluación y el informe (Mayús+A)", + "Resoconto: mostra o nascondi il grafico di valutazione e il resoconto (Maiusc+A)", + "Relatório: mostrar ou ocultar o gráfico de avaliação e o relatório (Shift+A)", + "Hisobot: baho grafigi va hisobotni ko‘rsatish yoki yashirish (Shift+A)", + "ЕÑ�еп: бағалау графигі мен еÑ�епті көрÑ�ету не жаÑ�ыру (Shift+A)", + ], + [ + "Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)", + "Ð�нализ партии: точноÑ�ть, неточноÑ�ти, ошибки, зевки (Shift+A)", + "Analyser la partie : précision, imprécisions, erreurs, gaffes (Maj+A)", + "Partie analysieren: Genauigkeit, Ungenauigkeiten, Fehler, grobe Fehler (Umschalt+A)", + "Analizar la partida: precisión, imprecisiones, errores, errores graves (Mayús+A)", + "Analizza la partita: precisione, imprecisioni, errori, svarioni (Maiusc+A)", + "Analisar a partida: precisão, imprecisões, erros, erros graves (Shift+A)", + "Partiya tahlili: aniqlik, noaniqliklar, xatolar, qo‘pol xatolar (Shift+A)", + "ПартиÑ�ны талдау: дәлдік, дәлÑ�іздіктер, қателер, өреÑ�кел қателер (Shift+A)", + ], + [ + "Every position is already evaluated", + "Ð’Ñ�е позиции уже оценены", + "Toutes les positions sont déjà évaluées", + "Alle Stellungen sind bereits bewertet", + "Todas las posiciones ya están evaluadas", + "Tutte le posizioni sono già valutate", + "Todas as posições já estão avaliadas", + "Har bir pozitsiya allaqachon baholangan", + "Әр позициÑ� бағаланып қойған", + ], + [ + "Stop the game analysis", + "ОÑ�тановить анализ партии", + "Arrêter l'analyse de la partie", + "Partieanalyse abbrechen", + "Detener el análisis de la partida", + "Interrompi l'analisi della partita", + "Parar a análise da partida", + "Partiya tahlilini to‘xtatish", + "ПартиÑ�ны талдауды тоқтату", + ], + [ + "Game analysis", + "Ð�нализ партии", + "Analyse de la partie", + "Partieanalyse", + "Análisis de la partida", + "Analisi della partita", + "Análise da partida", + "Partiya tahlili", + "ПартиÑ�ны талдау", + ], + [ + "Notation", + "Ð�отациÑ�", + "Notation", + "Notation", + "Notación", + "Notazione", + "Notação", + "Notatsiya", + "Ð�отациÑ�", + ], + [ + "Report", + "Отчёт", + "Rapport", + "Bericht", + "Informe", + "Resoconto", + "Relatório", + "Hisobot", + "ЕÑ�еп", + ], + [ + "paused: the game is being analysed", + "пауза: идёт анализ партии", + "en pause : analyse de la partie en cours", + "pausiert: Partie wird analysiert", + "en pausa: se está analizando la partida", + "in pausa: analisi della partita in corso", + "em pausa: a partida está sendo analisada", + "pauza: partiya tahlil qilinmoqda", + "үзіліÑ�: партиÑ� талдануда", + ], + [ + "Analysis written to the game: {n} marked moves (Ctrl+Z to undo)", + "Ð�нализ запиÑ�ан в партию: отмечено ходов — {n} (Ctrl+Z — отменить)", + "Analyse écrite dans la partie : {n} coups marqués (Ctrl+Z pour annuler)", + "Analyse in die Partie geschrieben: {n} markierte Züge (Strg+Z zum Rückgängigmachen)", + "Análisis escrito en la partida: {n} jugadas marcadas (Ctrl+Z para deshacer)", + "Analisi scritta nella partita: {n} mosse segnate (Ctrl+Z per annullare)", + "Análise gravada na partida: {n} lances marcados (Ctrl+Z para desfazer)", + "Tahlil partiyaga yozildi: {n} ta belgilangan yurish (bekor qilish: Ctrl+Z)", + "Талдау партиÑ�ға жазылды: белгіленген жүріÑ�тер — {n} (болдырмау — Ctrl+Z)", + ], + [ + "Best:", + "Лучше:", + "Meilleur :", + "Besser:", + "Mejor:", + "Meglio:", + "Melhor:", + "Yaxshirog‘i:", + "Үздігі:", + ], + [ + "Show this line on the board", + "Показать Ñ�тот вариант на доÑ�ке", + "Afficher cette ligne sur l'échiquier", + "Diese Variante auf dem Brett zeigen", + "Mostrar esta línea en el tablero", + "Mostra questa linea sulla scacchiera", + "Mostrar esta linha no tabuleiro", + "Bu liniyani taxtada ko‘rsatish", + "Бұл вариантты тақтада көрÑ�ету", + ], + [ + "Opening", + "Дебют", + "Ouverture", + "Eröffnung", + "Apertura", + "Apertura", + "Abertura", + "Debyut", + "Дебют", + ], + [ + "Middlegame", + "Миттельшпиль", + "Milieu de partie", + "Mittelspiel", + "Medio juego", + "Mediogioco", + "Meio-jogo", + "Mittelshpil", + "Миттельшпиль", + ], + [ + "Endgame", + "Эндшпиль", + "Finale", + "Endspiel", + "Final", + "Finale", + "Final", + "Endshpil", + "Эндшпиль", + ], + [ + "Start position", + "Ð�ачальнаÑ� позициÑ�", + "Position de départ", + "Ausgangsstellung", + "Posición inicial", + "Posizione iniziale", + "Posição inicial", + "Boshlang‘ich pozitsiya", + "БаÑ�тапқы позициÑ�", + ], + [ + "Evaluations from the PGN ([%eval])", + "Оценки из PGN ([%eval])", + "Évaluations issues du PGN ([%eval])", + "Bewertungen aus der PGN ([%eval])", + "Evaluaciones del PGN ([%eval])", + "Valutazioni dal PGN ([%eval])", + "Avaliações do PGN ([%eval])", + "PGNdagi baholar ([%eval])", + "PGN-дағы бағалар ([%eval])", + ], + [ + "Analyse again", + "Обновить", + "Mettre à jour", + "Aktualisieren", + "Actualizar", + "Aggiorna", + "Atualizar", + "Yangilash", + "Жаңарту", + ], + [ + "Update", + "Дополнить", + "Compléter", + "Ergänzen", + "Completar", + "Completa", + "Completar", + "To‘ldirish", + "Толықтыру", + ], + [ + "Write analysis to the game", + "ЗапиÑ�ать анализ в партию", + "Écrire l'analyse dans la partie", + "Analyse in die Partie schreiben", + "Escribir el análisis en la partida", + "Scrivi l'analisi nella partita", + "Gravar a análise na partida", + "Tahlilni partiyaga yozish", + "Талдауды партиÑ�ға жазу", + ], + [ + "Adds evaluations, !!/!/?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", + "ДобавлÑ�ет в партию оценки, знаки !!/!/?!/?/??, комментарии и лучшие варианты (Ctrl+Z — отменить)", + "Ajoute à la partie les évaluations, les signes !!/!/?!/?/??, des commentaires et les meilleures lignes (Ctrl+Z pour annuler)", + "Fügt der Partie Bewertungen, !!/!/?!/?/??-Zeichen, Kommentare und bessere Varianten hinzu (Strg+Z zum Rückgängigmachen)", + "Añade a la partida evaluaciones, signos !!/!/?!/?/??, comentarios y mejores líneas (Ctrl+Z para deshacer)", + "Aggiunge alla partita valutazioni, segni !!/!/?!/?/??, commenti e linee migliori (Ctrl+Z per annullare)", + "Adiciona avaliações, marcas !!/!/?!/?/??, comentários e linhas melhores à partida (Ctrl+Z para desfazer)", + "Partiyaga baholar, !!/!/?!/?/?? belgilari, izohlar va yaxshiroq liniyalarni qo‘shadi (bekor qilish: Ctrl+Z)", + "ПартиÑ�ға бағаларды, !!/!/?!/?/?? белгілерін, түÑ�ініктемелер мен жақÑ�ырақ варианттарды қоÑ�ады (болдырмау — Ctrl+Z)", + ], + [ + "Go to the next one", + "Перейти к Ñ�ледующей", + "Aller au suivant", + "Zum nächsten", + "Ir al siguiente", + "Vai al successivo", + "Ir para a próxima", + "Keyingisiga o‘tish", + "КелеÑ�Ñ–Ñ�іне өту", + ], + [ + "Average centipawn loss", + "СреднÑ�Ñ� потерÑ� Ñ�антипешек", + "Perte moyenne en centipions", + "Durchschnittlicher Centibauernverlust", + "Pérdida media de centipeones", + "Perdita media in centipedoni", + "Perda média de centipeões", + "O‘rtacha santipeshka yo‘qotish", + "Орташа Ñ�антипешка шығыны", + ], + [ + "Accuracy", + "ТочноÑ�ть", + "Précision", + "Genauigkeit", + "Precisión", + "Precisione", + "Precisão", + "Aniqlik", + "Дәлдік", + ], + [ + "Inaccuracy", + "Ð�еточноÑ�ть", + "Imprécision", + "Ungenauigkeit", + "Imprecisión", + "Imprecisione", + "Imprecisão", + "Noaniqlik", + "ДәлÑ�іздік", + ], + [ + "Mistake", + "Ошибка", + "Erreur", + "Fehler", + "Error", + "Errore", + "Erro", + "Xato", + "Қате", + ], + [ + "Blunder", + "Зевок", + "Gaffe", + "Grober Fehler", + "Error grave", + "Svarione", + "Erro grave", + "Qo‘pol xato", + "ӨреÑ�кел қате", + ], + [ + "Inaccuracies", + "Ð�еточноÑ�ти", + "Imprécisions", + "Ungenauigkeiten", + "Imprecisiones", + "Imprecisioni", + "Imprecisões", + "Noaniqliklar", + "ДәлÑ�іздіктер", + ], + [ + "Mistakes", + "Ошибки", + "Erreurs", + "Fehler", + "Errores", + "Errori", + "Erros", + "Xatolar", + "Қателер", + ], + [ + "Blunders", + "Зевки", + "Gaffes", + "Grobe Fehler", + "Errores graves", + "Svarioni", + "Erros graves", + "Qo‘pol xatolar", + "ӨреÑ�кел қателер", + ], + [ + "{judgement}. {best} was best.", + "{judgement}. Лучше было {best}.", + "{judgement}. {best} était meilleur.", + "{judgement}. Besser war {best}.", + "{judgement}. Era mejor {best}.", + "{judgement}. Era meglio {best}.", + "{judgement}. {best} era melhor.", + "{judgement}. {best} yaxshiroq edi.", + "{judgement}. {best} жақÑ�ырақ еді.", + ], + [ + "{engine} · {nodes} nodes per move", + "{engine} · {nodes} узлов на ход", + "{engine} · {nodes} nÅ“uds par coup", + "{engine} · {nodes} Knoten pro Zug", + "{engine} · {nodes} nodos por jugada", + "{engine} · {nodes} nodi per mossa", + "{engine} · {nodes} nós por lance", + "{engine} · har yurishga {nodes} tugun", + "{engine} · жүріÑ�ке {nodes} түйін", + ], + [ + "Positions without evaluation: {n}", + "Позиций без оценки: {n}", + "Positions sans évaluation : {n}", + "Stellungen ohne Bewertung: {n}", + "Posiciones sin evaluación: {n}", + "Posizioni senza valutazione: {n}", + "Posições sem avaliação: {n}", + "Bahosiz pozitsiyalar: {n}", + "БағаÑ�ыз позициÑ�лар: {n}", + ], + [ + "{n} positions, about {time}", + "Позиций: {n}, примерно {time}", + "{n} positions, environ {time}", + "{n} Stellungen, etwa {time}", + "{n} posiciones, unos {time}", + "{n} posizioni, circa {time}", + "{n} posições, cerca de {time}", + "{n} ta pozitsiya, taxminan {time}", + "{n} позициÑ�, шамамен {time}", + ], + [ + "{n} min", + "{n} мин", + "{n} min", + "{n} Min.", + "{n} min", + "{n} min", + "{n} min", + "{n} daq.", + "{n} мин", + ], + [ + "Fast", + "БыÑ�тро", + "Rapide", + "Schnell", + "Rápido", + "Veloce", + "Rápida", + "Tez", + "Жылдам", + ], + [ + "Normal", + "Обычно", + "Normal", + "Normal", + "Normal", + "Normale", + "Normal", + "Oddiy", + "Қалыпты", + ], + // Engines + [ + "The built-in engine is not part of this build", + "Ð’Ñ�троенного движка нет в Ñ�той Ñ�борке", + "Le moteur intégré ne fait pas partie de cette version", + "Die eingebaute Engine ist in diesem Build nicht enthalten", + "El motor integrado no forma parte de esta compilación", + "Il motore integrato non fa parte di questa build", + "O motor embutido não faz parte desta versão", + "Ichki dvigatel bu yig‘mada yo‘q", + "Кіріктірілген қозғалтқыш бұл жинақта жоқ", + ], + [ + "Shipped with ChessPenguin: {path}", + "ПоÑ�тавлÑ�етÑ�Ñ� Ñ� ChessPenguin: {path}", + "Fourni avec ChessPenguin : {path}", + "Mit ChessPenguin geliefert: {path}", + "Incluido con ChessPenguin: {path}", + "Fornito con ChessPenguin: {path}", + "Incluído no ChessPenguin: {path}", + "ChessPenguin bilan birga keladi: {path}", + "ChessPenguin-мен бірге келеді: {path}", + ], + [ + "Shipped with ChessPenguin: not part of this build", + "ПоÑ�тавлÑ�етÑ�Ñ� Ñ� ChessPenguin: в Ñ�той Ñ�борке отÑ�утÑ�твует", + "Fourni avec ChessPenguin : absent de cette version", + "Mit ChessPenguin geliefert: in diesem Build nicht enthalten", + "Incluido con ChessPenguin: no está en esta compilación", + "Fornito con ChessPenguin: assente in questa build", + "Incluído no ChessPenguin: não faz parte desta versão", + "ChessPenguin bilan birga keladi: bu yig‘mada yo‘q", + "ChessPenguin-мен бірге келеді: бұл жинақта жоқ", + ], + [ + "Found on this computer:", + "Ð�айдено на Ñ�том компьютере:", + "Trouvé sur cet ordinateur :", + "Auf diesem Computer gefunden:", + "Encontrado en este equipo:", + "Trovato su questo computer:", + "Encontrados neste computador:", + "Bu kompyuterda topildi:", + "ОÑ�Ñ‹ компьютерде табылды:", + ], + [ + "Add", + "Добавить", + "Ajouter", + "Hinzufügen", + "Añadir", + "Aggiungi", + "Adicionar", + "Qo‘shish", + "ҚоÑ�у", + ], + [ + "Stockfish (built-in)", + "Stockfish (вÑ�троенный)", + "Stockfish (intégré)", + "Stockfish (eingebaut)", + "Stockfish (integrado)", + "Stockfish (integrato)", + "Stockfish (embutido)", + "Stockfish (ichki)", + "Stockfish (кіріктірілген)", + ], + [ + "Stockfish (system)", + "Stockfish (Ñ�иÑ�темный)", + "Stockfish (système)", + "Stockfish (System)", + "Stockfish (del sistema)", + "Stockfish (di sistema)", + "Stockfish (sistema)", + "Stockfish (tizimdagi)", + "Stockfish (жүйелік)", + ], + // Importing ChessBase databases and archives + [ + "Open database", + "Открыть базу", + "Ouvrir une base", + "Datenbank öffnen", + "Abrir base de datos", + "Apri database", + "Abrir base", + "Bazani ochish", + "Базаны ашу", + ], + [ + "Chess databases", + "Шахматные базы", + "Bases d'échecs", + "Schachdatenbanken", + "Bases de datos de ajedrez", + "Database di scacchi", + "Bases de xadrez", + "Shaxmat bazalari", + "Шахмат базалары", + ], + [ + "Import notes", + "ЗамечаниÑ� импорта", + "Remarques d'import", + "Importhinweise", + "Notas de importación", + "Note di importazione", + "Notas de importação", + "Import eslatmalari", + "Импорт еÑ�кертпелері", + ], + [ + "Everything else was read. Games listed here are shown as far as they could be decoded.", + "Ð’Ñ�Ñ‘ оÑ�тальное прочитано. ПеречиÑ�ленные здеÑ�ÑŒ партии показаны до того меÑ�та, где их удалоÑ�ÑŒ раÑ�кодировать.", + "Tout le reste a été lu. Les parties listées ici sont affichées jusqu'où elles ont pu être décodées.", + "Alles andere wurde gelesen. Die hier aufgeführten Partien werden so weit gezeigt, wie sie entschlüsselt werden konnten.", + "Todo lo demás se ha leído. Las partidas listadas aquí se muestran hasta donde se pudieron decodificar.", + "Tutto il resto è stato letto. Le partite elencate qui sono mostrate fin dove è stato possibile decodificarle.", + "Todo o resto foi lido. As partidas listadas aqui são exibidas até onde puderam ser decodificadas.", + "Qolgan hammasi o‘qildi. Bu yerda sanab o‘tilgan partiyalar dekodlash mumkin bo‘lgan joygacha ko‘rsatilgan.", + "Қалғанының бәрі оқылды. Мұнда аталған партиÑ�лар таратып оқылған жеріне дейін көрÑ�етілген.", + ], + [ + "+ Add database", + "+ Добавить базу", + "+ Ajouter une base", + "+ Datenbank hinzufügen", + "+ Añadir base", + "+ Aggiungi database", + "+ Adicionar base", + "+ Baza qo‘shish", + "+ База қоÑ�у", + ], + [ + "Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)", + "Открыть PGN, ChessBase (.cbh, .cbv) или архив (.zip, .7z) (Ctrl+O)", + "Ouvrir un PGN, une base ChessBase (.cbh, .cbv) ou une archive (.zip, .7z) (Ctrl+O)", + "PGN, ChessBase (.cbh, .cbv) oder ein Archiv (.zip, .7z) öffnen (Strg+O)", + "Abrir PGN, ChessBase (.cbh, .cbv) o un archivo comprimido (.zip, .7z) (Ctrl+O)", + "Apri PGN, ChessBase (.cbh, .cbv) o un archivio (.zip, .7z) (Ctrl+O)", + "Abrir PGN, ChessBase (.cbh, .cbv) ou um arquivo compactado (.zip, .7z) (Ctrl+O)", + "PGN, ChessBase (.cbh, .cbv) yoki arxiv (.zip, .7z) ochish (Ctrl+O)", + "PGN, ChessBase (.cbh, .cbv) немеÑ�е мұрағат (.zip, .7z) ашу (Ctrl+O)", + ], + [ + "Converted to PGN when opened; the original files are not changed. Save a game to keep your edits.", + "При открытии база переводитÑ�Ñ� в PGN, иÑ�ходные файлы не менÑ�ÑŽÑ‚Ñ�Ñ�. Чтобы Ñ�охранить правки, Ñ�охраните партию.", + "Convertie en PGN à l'ouverture ; les fichiers d'origine ne sont pas modifiés. Enregistrez une partie pour garder vos modifications.", + "Beim Öffnen in PGN umgewandelt; die Originaldateien bleiben unverändert. Speichern Sie eine Partie, um Ihre Änderungen zu behalten.", + "Se convierte a PGN al abrirla; los archivos originales no cambian. Guarda una partida para conservar tus cambios.", + "Convertito in PGN all'apertura; i file originali non vengono modificati. Salva una partita per mantenere le modifiche.", + "Convertido para PGN ao abrir; os arquivos originais não são alterados. Salve uma partida para manter suas edições.", + "Ochilganda PGNga o‘giriladi; asl fayllar o‘zgarmaydi. Tahrirlaringizni saqlash uchun partiyani saqlang.", + "Ð�шқанда PGN-ге түрлендіріледі; баÑ�тапқы файлдар өзгермейді. Түзетулерді Ñ�ақтау үшін партиÑ�ны Ñ�ақтаңыз.", + ], + [ + "No PGN or ChessBase database in the archive", + "Ð’ архиве нет баз PGN или ChessBase", + "Aucune base PGN ou ChessBase dans l'archive", + "Keine PGN- oder ChessBase-Datenbank im Archiv", + "No hay ninguna base PGN o ChessBase en el archivo", + "Nessun database PGN o ChessBase nell'archivio", + "Nenhuma base PGN ou ChessBase no arquivo compactado", + "Arxivda PGN yoki ChessBase bazasi yo‘q", + "Мұрағатта PGN немеÑ�е ChessBase базаÑ�Ñ‹ жоқ", + ], + [ + "Password-protected archives (.cbz, encrypted zip/7z) are not supported", + "Ð�рхивы Ñ� паролем (.cbz, зашифрованные zip/7z) не поддерживаютÑ�Ñ�", + "Les archives protégées par mot de passe (.cbz, zip/7z chiffrés) ne sont pas prises en charge", + "Passwortgeschützte Archive (.cbz, verschlüsselte zip/7z) werden nicht unterstützt", + "Los archivos con contraseña (.cbz, zip/7z cifrados) no son compatibles", + "Gli archivi protetti da password (.cbz, zip/7z cifrati) non sono supportati", + "Arquivos compactados com senha (.cbz, zip/7z criptografado) não são suportados", + "Parolli arxivlar (.cbz, shifrlangan zip/7z) qo‘llab-quvvatlanmaydi", + "ҚұпиÑ�Ñ�өзбен қорғалған мұрағаттарға (.cbz, шифрланған zip/7z) қолдау жоқ", + ], + [ + "The ChessBase 2CBH format is not supported: export the database from ChessBase as CBH or PGN", + "Формат ChessBase 2CBH не поддерживаетÑ�Ñ�: Ñ�кÑ�портируйте базу из ChessBase в CBH или PGN", + "Le format ChessBase 2CBH n'est pas pris en charge : exportez la base depuis ChessBase en CBH ou PGN", + "Das ChessBase-Format 2CBH wird nicht unterstützt: Exportieren Sie die Datenbank aus ChessBase als CBH oder PGN", + "El formato ChessBase 2CBH no es compatible: exporta la base desde ChessBase como CBH o PGN", + "Il formato ChessBase 2CBH non è supportato: esporta il database da ChessBase come CBH o PGN", + "O formato ChessBase 2CBH não é suportado: exporte a base do ChessBase como CBH ou PGN", + "ChessBase 2CBH formati qo‘llab-quvvatlanmaydi: bazani ChessBasedan CBH yoki PGN sifatida eksport qiling", + "ChessBase 2CBH пішіміне қолдау жоқ: базаны ChessBase-тен CBH немеÑ�е PGN ретінде Ñ�кÑ�порттаңыз", + ], + [ + "· {n} games · {format}, read-only", + "· {n} партий · {format}, только чтение", + "· {n} parties · {format}, lecture seule", + "· {n} Partien · {format}, schreibgeschützt", + "· {n} partidas · {format}, solo lectura", + "· {n} partite · {format}, sola lettura", + "· {n} partidas · {format}, somente leitura", + "· {n} ta partiya · {format}, faqat o‘qish", + "· {n} партиÑ� · {format}, тек оқу", + ], + // Game result + [ + "White won", + "Победили белые", + "Les Blancs ont gagné", + "Weiß hat gewonnen", + "Ganaron las blancas", + "Hanno vinto i bianchi", + "Brancas venceram", + "Oqlar yutdi", + "Ð�қтар жеңді", + ], + [ + "Black won", + "Победили чёрные", + "Les Noirs ont gagné", + "Schwarz hat gewonnen", + "Ganaron las negras", + "Hanno vinto i neri", + "Pretas venceram", + "Qoralar yutdi", + "Қаралар жеңді", + ], + [ + "Draw", + "Ð�ичьÑ�", + "Nulle", + "Remis", + "Tablas", + "Patta", + "Empate", + "Durang", + "Тең ойын", + ], + // Viewed games + [ + "Mark as viewed", + "Отметить как проÑ�мотренную", + "Marquer comme vue", + "Als angesehen markieren", + "Marcar como vista", + "Segna come vista", + "Marcar como vista", + "Ko‘rilgan deb belgilash", + "Қаралды деп белгілеу", + ], + [ + "Mark as not viewed", + "СнÑ�ть отметку «проÑ�мотрена»", + "Marquer comme non vue", + "Als nicht angesehen markieren", + "Marcar como no vista", + "Segna come non vista", + "Marcar como não vista", + "Ko‘rilmagan deb belgilash", + "Қаралмады деп белгілеу", + ], + // Boards and sound sets + [ + "Futuristic", + "ФутуриÑ�тичные", + "Futuriste", + "Futuristisch", + "Futurista", + "Futuristico", + "Futurista", + "Futuristik", + "ФутуриÑ�тік", + ], + [ + "Glass", + "Стекло", + "Verre", + "Glas", + "Cristal", + "Vetro", + "Vidro", + "Shisha", + "Шыны", + ], + [ + "Clicks", + "Щелчки", + "Clics", + "Klicks", + "Clics", + "Clic", + "Cliques", + "Chertishlar", + "Шертулер", + ], + ["IC", "IC", "IC", "IC", "IC", "IC", "IC", "IC", "IC"], + [ + "NCF", "NCF", "NCF", "NCF", "NCF", "NCF", "NCF", "NCF", "NCF", + ], + [ + "Ice", "Лёд", "Glace", "Eis", "Hielo", "Ghiaccio", "Gelo", "Muz", "Мұз", + ], + [ + "Navy", + "Тёмно-Ñ�инÑ�Ñ�", + "Marine", + "Marineblau", + "Azul marino", + "Blu navy", + "Marinho", + "To‘q ko‘k", + "Қою көк", + ], + [ + "Mint", + "МÑ�та", + "Menthe", + "Minze", + "Menta", + "Menta", + "Menta", + "Yalpiz", + "Жалбыз", + ], + [ + "Emerald", + "Изумруд", + "Émeraude", + "Smaragd", + "Esmeralda", + "Smeraldo", + "Esmeralda", + "Zumrad", + "Зүбәржат", + ], + [ + "Orange", + "ОранжеваÑ�", + "Orange", + "Orange", + "Naranja", + "Arancione", + "Laranja", + "To‘q sariq", + "Қызғылт Ñ�ары", + ], + [ + "Rose", + "РозоваÑ�", + "Rose", + "Rosa", + "Rosa", + "Rosa", + "Rosa", + "Atirgul", + "Раушан", + ], + [ + "Dusk", + "Сумерки", + "Crépuscule", + "Dämmerung", + "Anochecer", + "Crepuscolo", + "Crepúsculo", + "Shom", + "Ымырт", + ], + [ + "Night", "Ð�очь", "Nuit", "Nacht", "Noche", "Notte", "Noite", "Tun", "Түн", + ], + [ + "Sketch", + "Ð�аброÑ�ок", + "Croquis", + "Skizze", + "Boceto", + "Schizzo", + "Esboço", + "Eskiz", + "Ð�обай", + ], + // Names of the sample databases (examples.rs). + [ + "Classic games", + "КлаÑ�Ñ�ичеÑ�кие партии", + "Parties classiques", + "Klassische Partien", + "Partidas clásicas", + "Partite classiche", + "Partidas clássicas", + "Klassik partiyalar", + "КлаÑ�Ñ�икалық партиÑ�лар", + ], + [ + "Alekhine", + "Ð�лехин", + "Alekhine", + "Aljechin", + "Alekhine", + "Aljechin", + "Alekhine", + "Alyoxin", + "Ð�лехин", + ], // Settings → About. + [ + "About", + "О программе", + "À propos", + "Über", + "Acerca de", + "Informazioni", + "Sobre", + "Dastur haqida", + "Бағдарлама туралы", + ], + [ + "Version", + "ВерÑ�иÑ�", + "Version", + "Version", + "Versión", + "Versione", + "Versão", + "Versiya", + "Ð�Ò±Ñ�қа", + ], + [ + "Free chess database software for Windows, macOS and Linux.", + "БеÑ�платнаÑ� программа длÑ� работы Ñ� шахматными базами на Windows, macOS и Linux.", + "Logiciel gratuit pour bases de données d'échecs sur Windows, macOS et Linux.", + "Kostenloses Programm für Schachdatenbanken unter Windows, macOS und Linux.", + "Programa gratuito para bases de datos de ajedrez en Windows, macOS y Linux.", + "Programma gratuito per database di scacchi su Windows, macOS e Linux.", + "Programa gratuito de base de dados de xadrez para Windows, macOS e Linux.", + "Windows, macOS va Linux uchun bepul shaxmat bazasi dasturi.", + "Windows, macOS және Linux жүйелеріне арналған тегін шахмат базаÑ�Ñ‹ бағдарламаÑ�Ñ‹.", + ], + [ + "Website", + "Сайт", + "Site web", + "Website", + "Sitio web", + "Sito web", + "Site", + "Sayt", + "Сайт", + ], + [ + "What's new", + "Что нового", + "Nouveautés", + "Neuigkeiten", + "Novedades", + "Novità", + "Novidades", + "Nima yangi", + "Ð�е жаңа", + ], + [ + "Source code", + "ИÑ�ходный код", + "Code source", + "Quellcode", + "Código fuente", + "Codice sorgente", + "Código-fonte", + "Manba kodi", + "БаÑ�тапқы код", + ], + [ + "Copied", + "Скопировано", + "Copié", + "Kopiert", + "Copiado", + "Copiato", + "Copiado", + "Nusxalandi", + "Көшірілді", + ], + [ + "Click to copy the address", + "Ð�ажмите, чтобы Ñ�копировать адреÑ�", + "Cliquez pour copier l'adresse", + "Klicken, um die Adresse zu kopieren", + "Haz clic para copiar la dirección", + "Fai clic per copiare l'indirizzo", + "Clique para copiar o endereço", + "Manzilni nusxalash uchun bosing", + "Мекенжайды көшіру үшін баÑ�ыңыз", + ], + [ + "Found a problem or have an idea? Write to us:", + "Ð�ашли проблему или еÑ�ть идеÑ�? Ð�апишите нам:", + "Un problème ou une idée ? Écrivez-nous :", + "Ein Problem gefunden oder eine Idee? Schreiben Sie uns:", + "¿Has encontrado un problema o tienes una idea? Escríbenos:", + "Hai trovato un problema o hai un'idea? Scrivici:", + "Encontrou um problema ou tem uma ideia? Escreva para nós:", + "Muammo topdingizmi yoki g‘oyangiz bormi? Bizga yozing:", + "МәÑ�еле таптыңыз ба, әлде идеÑ�ңыз бар ма? Бізге жазыңыз:", + ], + [ + "Free software under GPL-3.0-or-later. Piece sets, boards and sounds come from Lichess under their own free licences.", + "СвободнаÑ� программа под лицензией GPL-3.0-or-later. Ð�аборы фигур, доÑ�ки и звуки взÑ�ты из Lichess под их Ñ�обÑ�твенными Ñ�вободными лицензиÑ�ми.", + "Logiciel libre sous GPL-3.0-or-later. Les jeux de pièces, échiquiers et sons viennent de Lichess, sous leurs propres licences libres.", + "Freie Software unter GPL-3.0-or-later. Figurensätze, Bretter und Sounds stammen von Lichess, unter ihren eigenen freien Lizenzen.", + "Software libre bajo GPL-3.0-or-later. Los juegos de piezas, tableros y sonidos provienen de Lichess, con sus propias licencias libres.", + "Software libero sotto GPL-3.0-or-later. Set di pezzi, scacchiere e suoni provengono da Lichess, con le loro licenze libere.", + "Software livre sob GPL-3.0-or-later. Conjuntos de peças, tabuleiros e sons vêm do Lichess, sob suas próprias licenças livres.", + "GPL-3.0-or-later litsenziyasidagi erkin dastur. Figuralar to‘plamlari, taxtalar va ovozlar Lichessdan, o‘z erkin litsenziyalari asosida olingan.", + "GPL-3.0-or-later лицензиÑ�Ñ�ымен таратылатын еркін бағдарлама. Фигуралар жиындары, тақталар мен дыбыÑ�тар Lichess-тен, өз еркін лицензиÑ�ларымен алынған.", + ], + // --- own databases --- + [ + "No changes to save", + "Изменений нет", + "Aucune modification à enregistrer", + "Keine Änderungen zu speichern", + "No hay cambios que guardar", + "Nessuna modifica da salvare", + "Nenhuma alteração para salvar", + "Saqlanadigan o‘zgarish yo‘q", + "Сақтайтын өзгеріÑ� жоқ", + ], + [ + "The database is being read — try again in a moment", + "База ещё читаетÑ�Ñ� — попробуйте через Ñ�екунду", + "La base est en cours de lecture — réessayez dans un instant", + "Die Datenbank wird noch gelesen — versuchen Sie es gleich noch einmal", + "La base todavía se está leyendo; inténtelo de nuevo en un momento", + "Il database è ancora in lettura: riprova tra un attimo", + "A base ainda está sendo lida — tente de novo em instantes", + "Baza hali o‘qilmoqda — birozdan so‘ng qayta urinib ko‘ring", + "База әлі оқылып жатыр — Ñ�әлден Ñ�оң қайталап көріңіз", + ], + [ + "Saved to «{name}»", + "Сохранено в «{name}»", + "Enregistré dans « {name} »", + "In „{name}“ gespeichert", + "Guardado en «{name}»", + "Salvato in «{name}»", + "Salvo em “{name}â€�", + "“{name}â€� bazasiga saqlandi", + "«{name}» базаÑ�ына Ñ�ақталды", + ], + [ + "Added to «{name}» (No. {n})", + "Добавлено в «{name}» (â„– {n})", + "Ajoutée à « {name} » (n° {n})", + "Zu „{name}“ hinzugefügt (Nr. {n})", + "Añadida a «{name}» (n.º {n})", + "Aggiunta a «{name}» (n. {n})", + "Adicionada a “{name}â€� (nº {n})", + "“{name}â€� bazasiga qo‘shildi (â„– {n})", + "«{name}» базаÑ�ына қоÑ�ылды (â„– {n})", + ], + [ + "Saved to «{name}» (No. {n})", + "Сохранено в «{name}» (â„– {n})", + "Enregistrée dans « {name} » (n° {n})", + "In „{name}“ gespeichert (Nr. {n})", + "Guardada en «{name}» (n.º {n})", + "Salvata in «{name}» (n. {n})", + "Salva em “{name}â€� (nº {n})", + "“{name}â€� bazasiga saqlandi (â„– {n})", + "«{name}» базаÑ�ына Ñ�ақталды (â„– {n})", + ], + [ + "Deleted from «{name}»", + "Удалено из «{name}»", + "Supprimée de « {name} »", + "Aus „{name}“ gelöscht", + "Eliminada de «{name}»", + "Eliminata da «{name}»", + "Excluída de “{name}â€�", + "“{name}â€� bazasidan o‘chirildi", + "«{name}» базаÑ�ынан жойылды", + ], + [ + "The game is back", + "ПартиÑ� возвращена", + "La partie est rétablie", + "Die Partie ist wieder da", + "La partida se ha restaurado", + "La partita è stata ripristinata", + "A partida foi restaurada", + "Partiya qaytarildi", + "ПартиÑ� қайтарылды", + ], + [ + "Could not put the game back: {e}", + "Ð�е удалоÑ�ÑŒ вернуть партию: {e}", + "Impossible de rétablir la partie : {e}", + "Die Partie konnte nicht wiederhergestellt werden: {e}", + "No se pudo restaurar la partida: {e}", + "Impossibile ripristinare la partita: {e}", + "Não foi possível restaurar a partida: {e}", + "Partiyani qaytarib bo‘lmadi: {e}", + "ПартиÑ�ны қайтару мүмкін болмады: {e}", + ], + [ + "Could not create the file: {e}", + "Ð�е удалоÑ�ÑŒ Ñ�оздать файл: {e}", + "Impossible de créer le fichier : {e}", + "Die Datei konnte nicht erstellt werden: {e}", + "No se pudo crear el archivo: {e}", + "Impossibile creare il file: {e}", + "Não foi possível criar o arquivo: {e}", + "Faylni yaratib bo‘lmadi: {e}", + "Файлды жаÑ�ау мүмкін болмады: {e}", + ], + [ + "Folder for new databases", + "Папка новых баз", + "Dossier des nouvelles bases", + "Ordner für neue Datenbanken", + "Carpeta para bases nuevas", + "Cartella dei nuovi database", + "Pasta para novas bases", + "Yangi bazalar jildi", + "Жаңа базалар қалтаÑ�Ñ‹", + ], + [ + "Copy made: {path}", + "КопиÑ� Ñ�оздана: {path}", + "Copie créée : {path}", + "Kopie erstellt: {path}", + "Copia creada: {path}", + "Copia creata: {path}", + "Cópia criada: {path}", + "Nusxa yaratildi: {path}", + "Көшірме жаÑ�алды: {path}", + ], + [ + "Could not make the copy: {e}", + "Ð�е удалоÑ�ÑŒ Ñ�оздать копию: {e}", + "Impossible de créer la copie : {e}", + "Die Kopie konnte nicht erstellt werden: {e}", + "No se pudo crear la copia: {e}", + "Impossibile creare la copia: {e}", + "Não foi possível criar a cópia: {e}", + "Nusxa yaratib bo‘lmadi: {e}", + "Көшірме жаÑ�ау мүмкін болмады: {e}", + ], + [ + "Save the changes to «{name}»?", + "Сохранить изменениÑ� в «{name}»?", + "Enregistrer les modifications dans « {name} » ?", + "Änderungen in „{name}“ speichern?", + "¿Guardar los cambios en «{name}»?", + "Salvare le modifiche in «{name}»?", + "Salvar as alterações em “{name}â€�?", + "O‘zgarishlar “{name}â€� bazasiga saqlansinmi?", + "ӨзгеріÑ�тер «{name}» базаÑ�ына Ñ�ақталÑ�ын ба?", + ], + [ + "The game is in no database yet. Add it to one?", + "ПартиÑ� пока не в базе. Добавить её в базу?", + "La partie n’est encore dans aucune base. L’ajouter à une base ?", + "Die Partie ist noch in keiner Datenbank. In eine aufnehmen?", + "La partida aún no está en ninguna base. ¿Añadirla a una?", + "La partita non è ancora in nessun database. Aggiungerla a uno?", + "A partida ainda não está em nenhuma base. Adicioná-la a uma?", + "Partiya hali hech qaysi bazada emas. Bazaga qo‘shilsinmi?", + "ПартиÑ� әлі ешбір базада жоқ. Базаға қоÑ�ылÑ�ын ба?", + ], + [ + "Save to «{name}»", + "Сохранить в «{name}»", + "Enregistrer dans « {name} »", + "In „{name}“ speichern", + "Guardar en «{name}»", + "Salva in «{name}»", + "Salvar em “{name}â€�", + "“{name}â€� bazasiga saqlash", + "«{name}» базаÑ�ына Ñ�ақтау", + ], + [ + "Add to database…", + "Добавить в базу…", + "Ajouter à une base…", + "Zur Datenbank hinzufügen…", + "Añadir a una base…", + "Aggiungi a un database…", + "Adicionar a uma base…", + "Bazaga qo‘shish…", + "Базаға қоÑ�у…", + ], + [ + "Removed from the shelf; the file stays: {path}", + "Убрано Ñ� полки; файл оÑ�талÑ�Ñ�: {path}", + "Retirée de l’étagère ; le fichier reste : {path}", + "Aus dem Regal entfernt; die Datei bleibt erhalten: {path}", + "Quitada del estante; el archivo se conserva: {path}", + "Rimosso dallo scaffale; il file resta: {path}", + "Removida da estante; o arquivo continua em: {path}", + "Javondan olindi; fayl joyida qoldi: {path}", + "Сөреден алынды; файл орнында қалды: {path}", + ], + [ + "Save to «{name}» (Ctrl+S)", + "Сохранить в «{name}» (Ctrl+S)", + "Enregistrer dans « {name} » (Ctrl+S)", + "In „{name}“ speichern (Ctrl+S)", + "Guardar en «{name}» (Ctrl+S)", + "Salva in «{name}» (Ctrl+S)", + "Salvar em “{name}â€� (Ctrl+S)", + "“{name}â€� bazasiga saqlash (Ctrl+S)", + "«{name}» базаÑ�ына Ñ�ақтау (Ctrl+S)", + ], + [ + "Add to database… (Ctrl+S)", + "Добавить в базу… (Ctrl+S)", + "Ajouter à une base… (Ctrl+S)", + "Zur Datenbank hinzufügen… (Ctrl+S)", + "Añadir a una base… (Ctrl+S)", + "Aggiungi a un database… (Ctrl+S)", + "Adicionar a uma base… (Ctrl+S)", + "Bazaga qo‘shish… (Ctrl+S)", + "Базаға қоÑ�у… (Ctrl+S)", + ], + [ + "Game data (F2)", + "Данные партии (F2)", + "Données de la partie (F2)", + "Partiedaten (F2)", + "Datos de la partida (F2)", + "Dati della partita (F2)", + "Dados da partida (F2)", + "Partiya maʼlumotlari (F2)", + "ПартиÑ� деректері (F2)", + ], + [ + "Game data… (F2)", + "Данные партии… (F2)", + "Données de la partie… (F2)", + "Partiedaten… (F2)", + "Datos de la partida… (F2)", + "Dati della partita… (F2)", + "Dados da partida… (F2)", + "Partiya maʼlumotlari… (F2)", + "ПартиÑ� деректері… (F2)", + ], + [ + "Add to database… (Ctrl+Shift+S)", + "Добавить в базу… (Ctrl+Shift+S)", + "Ajouter à une base… (Ctrl+Shift+S)", + "Zur Datenbank hinzufügen… (Ctrl+Shift+S)", + "Añadir a una base… (Ctrl+Shift+S)", + "Aggiungi a un database… (Ctrl+Shift+S)", + "Adicionar a uma base… (Ctrl+Shift+S)", + "Bazaga qo‘shish… (Ctrl+Shift+S)", + "Базаға қоÑ�у… (Ctrl+Shift+S)", + ], + [ + "No games in «{name}» yet", + "Ð’ базе «{name}» пока нет партий", + "Aucune partie dans « {name} » pour l’instant", + "Noch keine Partien in „{name}“", + "Aún no hay partidas en «{name}»", + "Ancora nessuna partita in «{name}»", + "Ainda não há partidas em “{name}â€�", + "“{name}â€� bazasida hali partiya yo‘q", + "«{name}» базаÑ�ында әзірге партиÑ� жоқ", + ], + [ + "Add one: ♟ New game, or «Add to database…» (Ctrl+Shift+S) from any game.", + "Добавьте: ♟ Ð�оваÑ� партиÑ� или «Добавить в базу…» (Ctrl+Shift+S) из любой партии.", + "Ajoutez-en une : ♟ Nouvelle partie, ou « Ajouter à une base… » (Ctrl+Shift+S) depuis n’importe quelle partie.", + "Fügen Sie eine hinzu: ♟ Neue Partie oder „Zur Datenbank hinzufügen…“ (Ctrl+Shift+S) aus einer beliebigen Partie.", + "Añada una: ♟ Nueva partida, o «Añadir a una base…» (Ctrl+Shift+S) desde cualquier partida.", + "Aggiungine una: ♟ Nuova partita, oppure «Aggiungi a un database…» (Ctrl+Shift+S) da qualsiasi partita.", + "Adicione uma: ♟ Nova partida, ou “Adicionar a uma base…â€� (Ctrl+Shift+S) a partir de qualquer partida.", + "Partiya qo‘shing: ♟ Yangi partiya yoki istalgan partiyadan “Bazaga qo‘shish…â€� (Ctrl+Shift+S).", + "ПартиÑ� қоÑ�ыңыз: ♟ Жаңа партиÑ� немеÑ�е кез келген партиÑ�дан «Базаға қоÑ�у…» (Ctrl+Shift+S).", + ], + [ + "Open", + "Открыть", + "Ouvrir", + "Öffnen", + "Abrir", + "Apri", + "Abrir", + "Ochish", + "Ð�шу", + ], + [ + "Delete from the database… (Delete)", + "Удалить из базы… (Delete)", + "Supprimer de la base… (Delete)", + "Aus der Datenbank löschen… (Delete)", + "Eliminar de la base… (Delete)", + "Elimina dal database… (Delete)", + "Excluir da base… (Delete)", + "Bazadan o‘chirish… (Delete)", + "Базадан жою… (Delete)", + ], + [ + "✚ New database", + "✚ Ð�оваÑ� база", + "✚ Nouvelle base", + "✚ Neue Datenbank", + "✚ Nueva base", + "✚ Nuovo database", + "✚ Nova base", + "✚ Yangi baza", + "✚ Жаңа база", + ], + [ + "Add database…", + "Добавить базу…", + "Ajouter une base…", + "Datenbank hinzufügen…", + "Añadir base…", + "Aggiungi database…", + "Adicionar base…", + "Baza qo‘shish…", + "База қоÑ�у…", + ], + [ + "New database…", + "Ð�оваÑ� база…", + "Nouvelle base…", + "Neue Datenbank…", + "Nueva base…", + "Nuovo database…", + "Nova base…", + "Yangi baza…", + "Жаңа база…", + ], + [ + "An empty PGN file for your own games (Ctrl+Shift+N)", + "ПуÑ�той PGN-файл длÑ� Ñ�воих партий (Ctrl+Shift+N)", + "Un fichier PGN vide pour vos propres parties (Ctrl+Shift+N)", + "Eine leere PGN-Datei für Ihre eigenen Partien (Ctrl+Shift+N)", + "Un archivo PGN vacío para sus propias partidas (Ctrl+Shift+N)", + "Un file PGN vuoto per le tue partite (Ctrl+Shift+N)", + "Um arquivo PGN vazio para suas próprias partidas (Ctrl+Shift+N)", + "O‘z partiyalaringiz uchun bo‘sh PGN fayl (Ctrl+Shift+N)", + "Өз партиÑ�ларыңызға арналған боÑ� PGN файлы (Ctrl+Shift+N)", + ], + [ + "Show in folder", + "Показать в папке", + "Afficher dans le dossier", + "Im Ordner zeigen", + "Mostrar en la carpeta", + "Mostra nella cartella", + "Mostrar na pasta", + "Jildda ko‘rsatish", + "Қалтада көрÑ�ету", + ], + [ + "This database is downloaded from Lichess and Chess.com and updates itself: a game added by hand would be lost at the next update. Add the game to a database of your own.", + "Эта база Ñ�качана Ñ� Lichess и Chess.com и обновлÑ�етÑ�Ñ� Ñ�ама: партиÑ�, добавленнаÑ� вручную, пропадёт при Ñ�ледующем обновлении. Добавьте партию в Ñ�вою базу.", + "Cette base est téléchargée depuis Lichess et Chess.com et se met à jour toute seule : une partie ajoutée à la main serait perdue à la prochaine mise à jour. Ajoutez la partie à l’une de vos propres bases.", + "Diese Datenbank wird von Lichess und Chess.com heruntergeladen und aktualisiert sich selbst: Eine von Hand hinzugefügte Partie ginge beim nächsten Update verloren. Fügen Sie die Partie einer eigenen Datenbank hinzu.", + "Esta base se descarga de Lichess y Chess.com y se actualiza sola: una partida añadida a mano se perdería en la próxima actualización. Añada la partida a una base propia.", + "Questo database viene scaricato da Lichess e Chess.com e si aggiorna da solo: una partita aggiunta a mano andrebbe persa al prossimo aggiornamento. Aggiungi la partita a un tuo database.", + "Esta base é baixada do Lichess e do Chess.com e se atualiza sozinha: uma partida adicionada à mão seria perdida na próxima atualização. Adicione a partida a uma base sua.", + "Bu baza Lichess va Chess.com saytlaridan yuklab olinadi va o‘zi yangilanadi: qo‘lda qo‘shilgan partiya keyingi yangilanishda yo‘qoladi. Partiyani o‘z bazangizga qo‘shing.", + "Бұл база Lichess пен Chess.com Ñ�айттарынан жүктеледі және өзі жаңарады: қолмен қоÑ�ылған партиÑ� келеÑ�Ñ– жаңартуда жоғалады. ПартиÑ�ны өз базаңызға қоÑ�ыңыз.", + ], + [ + "ChessBase databases and archives are only read. Add the game to a PGN database of your own.", + "Базы ChessBase и архивы только читаютÑ�Ñ�. Добавьте партию в Ñ�вою PGN-базу.", + "Les bases ChessBase et les archives sont en lecture seule. Ajoutez la partie à l’une de vos bases PGN.", + "ChessBase-Datenbanken und Archive werden nur gelesen. Fügen Sie die Partie einer eigenen PGN-Datenbank hinzu.", + "Las bases de ChessBase y los archivos comprimidos solo se leen. Añada la partida a una base PGN propia.", + "I database ChessBase e gli archivi vengono solo letti. Aggiungi la partita a un tuo database PGN.", + "Bases do ChessBase e arquivos compactados são apenas lidos. Adicione a partida a uma base PGN sua.", + "ChessBase bazalari va arxivlar faqat o‘qiladi. Partiyani o‘z PGN bazangizga qo‘shing.", + "ChessBase базалары мен архивтер тек оқылады. ПартиÑ�ны өз PGN базаңызға қоÑ�ыңыз.", + ], + [ + "This file is in the {enc} encoding; games are written in UTF-8. Make a copy of it in UTF-8 and add games to the copy — the original stays as it is.", + "Этот файл в кодировке {enc}, а партии запиÑ�ываютÑ�Ñ� в UTF-8. Создайте его копию в UTF-8 и добавлÑ�йте партии в копию — иÑ�ходный файл оÑ�танетÑ�Ñ� как еÑ�ть.", + "Ce fichier est en encodage {enc} ; les parties sont écrites en UTF-8. Créez-en une copie en UTF-8 et ajoutez les parties à la copie — l’original reste intact.", + "Diese Datei hat die Kodierung {enc}; Partien werden in UTF-8 geschrieben. Erstellen Sie eine UTF-8-Kopie und fügen Sie die Partien der Kopie hinzu — das Original bleibt unverändert.", + "Este archivo está en la codificación {enc}, y las partidas se escriben en UTF-8. Cree una copia en UTF-8 y añada las partidas a la copia; el original queda como está.", + "Questo file è nella codifica {enc}, mentre le partite vengono scritte in UTF-8. Creane una copia in UTF-8 e aggiungi le partite alla copia: l’originale resta com’è.", + "Este arquivo está na codificação {enc}, e as partidas são gravadas em UTF-8. Crie uma cópia dele em UTF-8 e adicione as partidas à cópia — o original fica como está.", + "Bu fayl {enc} kodlashida, partiyalar esa UTF-8 da yoziladi. Uning UTF-8 dagi nusxasini yarating va partiyalarni nusxaga qo‘shing — asl fayl o‘zgarmaydi.", + "Бұл файл {enc} кодтауында, ал партиÑ�лар UTF-8 форматында жазылады. Оның UTF-8 көшірмеÑ�ін жаÑ�ап, партиÑ�ларды көшірмеге қоÑ�ыңыз — түпнұÑ�қа файл өзгермейді.", + ], + [ + "The file cannot be written: no permission.", + "Файл нельзÑ� запиÑ�ать: нет прав.", + "Impossible d’écrire dans le fichier : pas de droits.", + "Die Datei kann nicht geschrieben werden: keine Berechtigung.", + "No se puede escribir el archivo: no hay permiso.", + "Impossibile scrivere il file: permesso negato.", + "Não é possível gravar o arquivo: sem permissão.", + "Faylga yozib bo‘lmaydi: ruxsat yo‘q.", + "Файлға жазу мүмкін емеÑ�: Ñ€Ò±Ò›Ñ�ат жоқ.", + ], + [ + "The file is not on the disk any more.", + "Файла больше нет на диÑ�ке.", + "Le fichier n’est plus sur le disque.", + "Die Datei ist nicht mehr auf dem Datenträger.", + "El archivo ya no está en el disco.", + "Il file non è più sul disco.", + "O arquivo não está mais no disco.", + "Fayl endi diskda yo‘q.", + "Файл енді диÑ�кіде жоқ.", + ], + [ + "A name cannot have / \\ : * ? \" < > |", + "Ð’ имени нельзÑ� иÑ�пользовать / \\ : * ? \" < > |", + "Un nom ne peut pas contenir / \\ : * ? \" < > |", + "Im Namen sind nicht erlaubt: / \\ : * ? \" < > |", + "Un nombre no puede contener / \\ : * ? \" < > |", + "Un nome non può contenere / \\ : * ? \" < > |", + "Um nome não pode conter / \\ : * ? \" < > |", + "Nomda bo‘lishi mumkin emas: / \\ : * ? \" < > |", + "Ð�тауда болмауы керек: / \\ : * ? \" < > |", + ], + [ + "New database", + "Ð�оваÑ� база", + "Nouvelle base", + "Neue Datenbank", + "Nueva base", + "Nuovo database", + "Nova base", + "Yangi baza", + "Жаңа база", + ], + [ + "e.g. Petrov, My games, Sicilian", + "например, Петров, Мои партии, СицилианÑ�каÑ�", + "par ex. Dupont, Mes parties, Sicilienne", + "z. B. Müller, Meine Partien, Sizilianisch", + "p. ej., García, Mis partidas, Siciliana", + "ad es. Rossi, Le mie partite, Siciliana", + "ex.: Silva, Minhas partidas, Siciliana", + "masalan, Karimov, Mening partiyalarim, Sitsiliya", + "мыÑ�алы, Ð�хметов, Менің партиÑ�ларым, СицилиÑ�", + ], + [ + "File:", + "Файл:", + "Fichier :", + "Datei:", + "Archivo:", + "File:", + "Arquivo:", + "Fayl:", + "Файл:", + ], + [ + "A file with this name is already there.", + "Файл Ñ� таким именем уже еÑ�ть.", + "Un fichier portant ce nom existe déjà.", + "Eine Datei mit diesem Namen gibt es bereits.", + "Ya existe un archivo con este nombre.", + "Esiste già un file con questo nome.", + "Já existe um arquivo com este nome.", + "Bunday nomli fayl allaqachon bor.", + "Бұл атаумен файл бұрыннан бар.", + ], + [ + "Create", + "Создать", + "Créer", + "Erstellen", + "Crear", + "Crea", + "Criar", + "Yaratish", + "ЖаÑ�ау", + ], + [ + "Put it on the shelf", + "ПоÑ�тавить на полку", + "Mettre sur l’étagère", + "Ins Regal stellen", + "Poner en el estante", + "Metti sullo scaffale", + "Colocar na estante", + "Javonga qo‘yish", + "Сөреге қою", + ], + [ + "Add to database", + "Добавить в базу", + "Ajouter à une base", + "Zur Datenbank hinzufügen", + "Añadir a una base", + "Aggiungi a un database", + "Adicionar a uma base", + "Bazaga qo‘shish", + "Базаға қоÑ�у", + ], + [ + "ðŸ”� Find a database", + "ðŸ”� Ð�айти базу", + "ðŸ”� Trouver une base", + "ðŸ”� Datenbank suchen", + "ðŸ”� Buscar una base", + "ðŸ”� Cerca un database", + "ðŸ”� Procurar uma base", + "ðŸ”� Baza qidirish", + "ðŸ”� База іздеу", + ], + [ + "✚ New database…", + "✚ Ð�оваÑ� база…", + "✚ Nouvelle base…", + "✚ Neue Datenbank…", + "✚ Nueva base…", + "✚ Nuovo database…", + "✚ Nova base…", + "✚ Yangi baza…", + "✚ Жаңа база…", + ], + [ + "Save as a file…", + "Сохранить как файл…", + "Enregistrer dans un fichier…", + "Als Datei speichern…", + "Guardar como archivo…", + "Salva come file…", + "Salvar como arquivo…", + "Fayl sifatida saqlash…", + "Файл ретінде Ñ�ақтау…", + ], + [ + "A separate PGN file with this game only; it is not put on the shelf", + "Отдельный PGN-файл только Ñ� Ñ�той партией; на полку не Ñ�тавитÑ�Ñ�", + "Un fichier PGN distinct avec cette seule partie ; il n’est pas mis sur l’étagère", + "Eine eigene PGN-Datei nur mit dieser Partie; sie kommt nicht ins Regal", + "Un archivo PGN aparte solo con esta partida; no se pone en el estante", + "Un file PGN a parte con solo questa partita; non viene messo sullo scaffale", + "Um arquivo PGN separado só com esta partida; ele não vai para a estante", + "Faqat shu partiya bo‘lgan alohida PGN fayl; javonga qo‘yilmaydi", + "Тек оÑ�Ñ‹ партиÑ�Ñ�Ñ‹ бар бөлек PGN файлы; Ñ�өреге қойылмайды", + ], + [ + "Game data", + "Данные партии", + "Données de la partie", + "Partiedaten", + "Datos de la partida", + "Dati della partita", + "Dados da partida", + "Partiya maʼlumotlari", + "ПартиÑ� деректері", + ], + [ + "Surname, Name", + "ФамилиÑ�, ИмÑ�", + "Nom, Prénom", + "Nachname, Vorname", + "Apellido, Nombre", + "Cognome, Nome", + "Sobrenome, Nome", + "Familiya, Ism", + "Тегі, Ð�ты", + ], + [ + "Site", + "МеÑ�то", + "Lieu", + "Ort", + "Lugar", + "Luogo", + "Local", + "Joy", + "Орны", + ], + [ + "2026.10.18, 18.10.2026, 2026.10, 2026 or empty", + "2026.10.18, 18.10.2026, 2026.10, 2026 или пуÑ�то", + "2026.10.18, 18.10.2026, 2026.10, 2026 ou vide", + "2026.10.18, 18.10.2026, 2026.10, 2026 oder leer", + "2026.10.18, 18.10.2026, 2026.10, 2026 o vacío", + "2026.10.18, 18.10.2026, 2026.10, 2026 o vuoto", + "2026.10.18, 18.10.2026, 2026.10, 2026 ou vazio", + "2026.10.18, 18.10.2026, 2026.10, 2026 yoki bo‘sh", + "2026.10.18, 18.10.2026, 2026.10, 2026 немеÑ�е боÑ�", + ], + [ + "Done", + "Готово", + "Terminé", + "Fertig", + "Listo", + "Fatto", + "Concluído", + "Tayyor", + "Дайын", + ], + [ + "Add to «{name}»", + "Добавить в «{name}»", + "Ajouter à « {name} »", + "Zu „{name}“ hinzufügen", + "Añadir a «{name}»", + "Aggiungi a «{name}»", + "Adicionar a “{name}â€�", + "“{name}â€� bazasiga qo‘shish", + "«{name}» базаÑ�ына қоÑ�у", + ], + [ + "This game is already there", + "ТакаÑ� партиÑ� уже еÑ�ть", + "Cette partie y est déjà", + "Diese Partie ist schon vorhanden", + "Esta partida ya está ahí", + "Questa partita c’è già", + "Esta partida já está lá", + "Bu partiya allaqachon bor", + "Бұл партиÑ� бұрыннан бар", + ], + [ + "Replace No. {n}", + "Заменить â„– {n}", + "Remplacer le n° {n}", + "Nr. {n} ersetzen", + "Reemplazar n.º {n}", + "Sostituisci n. {n}", + "Substituir nº {n}", + "Almashtirish: â„– {n}", + "Ð�уыÑ�тыру: â„– {n}", + ], + [ + "Add as new", + "Добавить как новую", + "Ajouter comme nouvelle", + "Als neue hinzufügen", + "Añadir como nueva", + "Aggiungi come nuova", + "Adicionar como nova", + "Yangi sifatida qo‘shish", + "Жаңа ретінде қоÑ�у", + ], + [ + "A copy in UTF-8", + "КопиÑ� в UTF-8", + "Une copie en UTF-8", + "Eine Kopie in UTF-8", + "Una copia en UTF-8", + "Una copia in UTF-8", + "Uma cópia em UTF-8", + "UTF-8 dagi nusxa", + "UTF-8 көшірмеÑ�Ñ–", + ], + [ + "«{name}» is in the {enc} encoding, and games are written in UTF-8. A copy «{copy}» will be made next to it with all its games; the game is added to the copy, the original stays as it is.", + "«{name}» в кодировке {enc}, а партии запиÑ�ываютÑ�Ñ� в UTF-8. РÑ�дом будет Ñ�оздана копиÑ� «{copy}» Ñ�о вÑ�еми партиÑ�ми; партиÑ� добавитÑ�Ñ� в копию, иÑ�ходный файл оÑ�танетÑ�Ñ� как еÑ�ть.", + "« {name} » est en encodage {enc}, alors que les parties sont écrites en UTF-8. Une copie « {copy} » contenant toutes ses parties sera créée à côté ; la partie est ajoutée à la copie, l’original reste intact.", + "„{name}“ hat die Kodierung {enc}, Partien werden aber in UTF-8 geschrieben. Daneben wird eine Kopie „{copy}“ mit allen Partien erstellt; die Partie kommt in die Kopie, das Original bleibt unverändert.", + "«{name}» está en la codificación {enc}, y las partidas se escriben en UTF-8. Al lado se creará una copia «{copy}» con todas sus partidas; la partida se añade a la copia y el original queda como está.", + "«{name}» è nella codifica {enc}, mentre le partite vengono scritte in UTF-8. Accanto verrà creata una copia «{copy}» con tutte le sue partite; la partita viene aggiunta alla copia, l’originale resta com’è.", + "“{name}â€� está na codificação {enc}, e as partidas são gravadas em UTF-8. Ao lado será criada uma cópia “{copy}â€� com todas as partidas; a partida é adicionada à cópia, o original fica como está.", + "“{name}â€� {enc} kodlashida, partiyalar esa UTF-8 da yoziladi. Yonida barcha partiyalari bilan “{copy}â€� nusxasi yaratiladi; partiya nusxaga qo‘shiladi, asl fayl o‘zgarmaydi.", + "«{name}» {enc} кодтауында, ал партиÑ�лар UTF-8 форматында жазылады. ҚаÑ�ында барлық партиÑ�лары бар «{copy}» көшірмеÑ�Ñ– жаÑ�алады; партиÑ� көшірмеге қоÑ�ылады, түпнұÑ�қа файл өзгермейді.", + ], + [ + "Make the copy", + "Создать копию", + "Créer la copie", + "Kopie erstellen", + "Crear la copia", + "Crea la copia", + "Criar a cópia", + "Nusxa yaratish", + "Көшірме жаÑ�ау", + ], + [ + "Could not delete", + "Ð�е удалоÑ�ÑŒ удалить", + "Impossible de supprimer", + "Löschen fehlgeschlagen", + "No se pudo eliminar", + "Impossibile eliminare", + "Não foi possível excluir", + "O‘chirib bo‘lmadi", + "Жою мүмкін болмады", + ], + [ + "Could not save", + "Ð�е удалоÑ�ÑŒ Ñ�охранить", + "Impossible d’enregistrer", + "Speichern fehlgeschlagen", + "No se pudo guardar", + "Impossibile salvare", + "Não foi possível salvar", + "Saqlab bo‘lmadi", + "Сақтау мүмкін болмады", + ], + [ + "Add to another database…", + "Добавить в другую базу…", + "Ajouter à une autre base…", + "Zu einer anderen Datenbank hinzufügen…", + "Añadir a otra base…", + "Aggiungi a un altro database…", + "Adicionar a outra base…", + "Boshqa bazaga qo‘shish…", + "БаÑ�қа базаға қоÑ�у…", + ], + [ + "The file changed on disk", + "Файл изменилÑ�Ñ� на диÑ�ке", + "Le fichier a changé sur le disque", + "Die Datei wurde auf dem Datenträger geändert", + "El archivo cambió en el disco", + "Il file è cambiato sul disco", + "O arquivo mudou no disco", + "Fayl diskda o‘zgardi", + "Файл диÑ�кіде өзгерді", + ], + [ + "«{name}» was changed by another program since it was read. Reread it and look again.", + "«{name}» изменила другаÑ� программа поÑ�ле чтениÑ�. Перечитайте и поÑ�мотрите Ñ�нова.", + "Un autre programme a modifié « {name} » depuis sa lecture. Relisez le fichier et vérifiez de nouveau.", + "„{name}“ wurde seit dem Lesen von einem anderen Programm geändert. Lesen Sie die Datei neu ein und sehen Sie noch einmal nach.", + "Otro programa modificó «{name}» después de la lectura. Vuelva a leer el archivo y revíselo de nuevo.", + "Un altro programma ha modificato «{name}» dopo la lettura. Rileggi il file e controlla di nuovo.", + "Outro programa alterou “{name}â€� depois da leitura. Releia o arquivo e confira de novo.", + "“{name}â€� o‘qilgandan keyin boshqa dastur tomonidan o‘zgartirildi. Faylni qayta o‘qing va yana bir bor qarang.", + "«{name}» оқылғаннан кейін оны баÑ�қа бағдарлама өзгертті. Файлды қайта оқып, тағы бір қараңыз.", + ], + [ + "«{name}» was changed by another program since it was read. The game can be added to it as a new one; replacing a record in it would need a fresh read first.", + "«{name}» изменила другаÑ� программа поÑ�ле чтениÑ�. Партию можно добавить как новую; чтобы заменить запиÑ�ÑŒ, файл надо Ñ�начала перечитать.", + "Un autre programme a modifié « {name} » depuis sa lecture. La partie peut y être ajoutée comme nouvelle ; pour remplacer une partie existante, il faut d’abord relire le fichier.", + "„{name}“ wurde seit dem Lesen von einem anderen Programm geändert. Die Partie kann als neue hinzugefügt werden; um einen Eintrag zu ersetzen, muss die Datei zuerst neu eingelesen werden.", + "Otro programa modificó «{name}» después de la lectura. La partida puede añadirse como nueva; para reemplazar un registro, primero hay que volver a leer el archivo.", + "Un altro programma ha modificato «{name}» dopo la lettura. La partita può essere aggiunta come nuova; per sostituire una voce bisogna prima rileggere il file.", + "Outro programa alterou “{name}â€� depois da leitura. A partida pode ser adicionada como nova; para substituir um registro, é preciso reler o arquivo primeiro.", + "“{name}â€� o‘qilgandan keyin boshqa dastur tomonidan o‘zgartirildi. Partiyani yangi sifatida qo‘shish mumkin; yozuvni almashtirish uchun avval faylni qayta o‘qish kerak.", + "«{name}» оқылғаннан кейін оны баÑ�қа бағдарлама өзгертті. ПартиÑ�ны жаңа ретінде қоÑ�уға болады; жазбаны ауыÑ�тыру үшін алдымен файлды қайта оқу керек.", + ], + [ + "Reread", + "Перечитать", + "Relire", + "Neu einlesen", + "Volver a leer", + "Rileggi", + "Reler", + "Qayta o‘qish", + "Қайта оқу", + ], + [ + "A big database", + "БольшаÑ� база", + "Une grande base", + "Eine große Datenbank", + "Una base grande", + "Un database grande", + "Uma base grande", + "Katta baza", + "Үлкен база", + ], + [ + "«{name}» is {mb} MB: saving a game into it rewrites the whole file, which takes a while. Your own games are handier in a smaller database of their own.", + "«{name}» веÑ�ит {mb} МБ: Ñ�охранение партии перепиÑ�ывает веÑ�ÑŒ файл, Ñ�то занимает времÑ�. Свои партии удобнее держать в отдельной небольшой базе.", + "« {name} » pèse {mb} Mo : y enregistrer une partie réécrit tout le fichier, ce qui prend du temps. Vos propres parties sont plus pratiques dans une petite base à part.", + "„{name}“ ist {mb} MB groß: Das Speichern einer Partie schreibt die ganze Datei neu, das dauert eine Weile. Eigene Partien sind in einer kleineren, eigenen Datenbank besser aufgehoben.", + "«{name}» ocupa {mb} MB: guardar una partida en ella reescribe todo el archivo, lo que lleva un tiempo. Sus propias partidas son más cómodas en una base aparte más pequeña.", + "«{name}» occupa {mb} MB: salvarvi una partita riscrive l’intero file, il che richiede tempo. Le tue partite sono più comode in un database a parte, più piccolo.", + "“{name}â€� tem {mb} MB: salvar uma partida nela regrava o arquivo inteiro, o que leva um tempo. Suas próprias partidas ficam mais práticas em uma base separada e menor.", + "“{name}â€� hajmi {mb} MB: unga partiya saqlash butun faylni qayta yozadi, bu vaqt oladi. O‘z partiyalaringizni alohida kichik bazada saqlash qulayroq.", + "«{name}» көлемі {mb} МБ: оған партиÑ� Ñ�ақтау бүкіл файлды қайта жазады, бұл уақыт алады. Өз партиÑ�ларыңызды бөлек шағын базада Ñ�ақтаған ыңғайлы.", + ], + [ + "Save anyway", + "Ð’Ñ�Ñ‘ равно Ñ�охранить", + "Enregistrer quand même", + "Trotzdem speichern", + "Guardar de todos modos", + "Salva comunque", + "Salvar mesmo assim", + "Baribir saqlash", + "Бәрібір Ñ�ақтау", + ], + [ + "Your databases", + "Свои базы", + "Vos bases", + "Ihre Datenbanken", + "Sus bases", + "I tuoi database", + "Suas bases", + "Sizning bazalaringiz", + "Өз базаларыңыз", + ], + [ + "Your name:", + "Ваше имÑ�:", + "Votre nom :", + "Ihr Name:", + "Su nombre:", + "Il tuo nome:", + "Seu nome:", + "Ismingiz:", + "Ð�тыңыз:", + ], + [ + "Written as the annotator of the games you add", + "ЗапиÑ�ываетÑ�Ñ� комментатором добавлÑ�емых партий", + "Inscrit comme commentateur des parties que vous ajoutez", + "Wird als Kommentator der hinzugefügten Partien eingetragen", + "Se anota como comentarista de las partidas que añada", + "Viene scritto come commentatore delle partite che aggiungi", + "É registrado como comentarista das partidas que você adicionar", + "Qo‘shiladigan partiyalarning izohlovchisi sifatida yoziladi", + "ҚоÑ�ылатын партиÑ�лардың түÑ�ініктеме авторы ретінде жазылады", + ], + [ + "Folder for new databases:", + "Папка новых баз:", + "Dossier des nouvelles bases :", + "Ordner für neue Datenbanken:", + "Carpeta para bases nuevas:", + "Cartella dei nuovi database:", + "Pasta para novas bases:", + "Yangi bazalar jildi:", + "Жаңа базалар қалтаÑ�Ñ‹:", + ], + [ + "Change…", + "Изменить…", + "Modifier…", + "Ändern…", + "Cambiar…", + "Cambia…", + "Alterar…", + "O‘zgartirish…", + "Өзгерту…", + ], + // --- own databases, second batch --- + [ + "Add the game with the changes to a database of your own?", + "Добавить партию Ñ� изменениÑ�ми в Ñ�вою базу?", + "Ajouter la partie avec les modifications à l’une de vos bases ?", + "Die Partie mit den Änderungen in eine eigene Datenbank aufnehmen?", + "¿Añadir la partida con los cambios a una base propia?", + "Aggiungere la partita con le modifiche a un tuo database?", + "Adicionar a partida com as alterações a uma base própria?", + "Partiyani o‘zgarishlar bilan o‘z bazangizga qo‘shasizmi?", + "ПартиÑ�ны өзгеріÑ�терімен өз базаңызға қоÑ�аÑ�ыз ба?", + ], + [ + "Unsaved changes", + "Ð�еÑ�охранённые изменениÑ�", + "Modifications non enregistrées", + "Nicht gespeicherte Änderungen", + "Cambios sin guardar", + "Modifiche non salvate", + "Alterações não salvas", + "Saqlanmagan o‘zgarishlar", + "Сақталмаған өзгеріÑ�тер", + ], + [ + "File: {path}", + "Файл: {path}", + "Fichier : {path}", + "Datei: {path}", + "Archivo: {path}", + "File: {path}", + "Arquivo: {path}", + "Fayl: {path}", + "Файл: {path}", + ], + [ + "Title", + "Ð�азвание", + "Nom", + "Name", + "Nombre", + "Nome", + "Nome", + "Nomi", + "Ð�тауы", + ], + [ + "Change folder…", + "Изменить папку…", + "Changer de dossier…", + "Ordner ändern…", + "Cambiar carpeta…", + "Cambia cartella…", + "Alterar pasta…", + "Papkani o‘zgartirish…", + "Қалтаны өзгерту…", + ], + [ + "reading…", + "читаетÑ�Ñ�…", + "lecture…", + "wird gelesen…", + "leyendo…", + "in lettura…", + "lendo…", + "o‘qilmoqda…", + "оқылуда…", + ], + [ + "Make a copy in UTF-8…", + "Сделать копию в UTF-8…", + "Créer une copie en UTF-8…", + "UTF-8-Kopie erstellen…", + "Crear una copia en UTF-8…", + "Crea una copia in UTF-8…", + "Criar uma cópia em UTF-8…", + "UTF-8 da nusxa yaratish…", + "UTF-8 көшірмеÑ�ін жаÑ�ау…", + ], + [ + "Game data → «{name}»", + "Данные партии → «{name}»", + "Données de la partie → « {name} »", + "Partiedaten → „{name}“", + "Datos de la partida → «{name}»", + "Dati della partita → «{name}»", + "Dados da partida → “{name}â€�", + "Partiya maʼlumotlari → “{name}â€�", + "ПартиÑ� деректері → «{name}»", + ], + [ + "YYYY.MM.DD", + "ГГГГ.ММ.ДД", + "AAAA.MM.JJ", + "JJJJ.MM.TT", + "AAAA.MM.DD", + "AAAA.MM.GG", + "AAAA.MM.DD", + "YYYY.OO.KK", + "ЖЖЖЖ.Ð�Ð�.КК", + ], + [ + "Other tags stay as they are: {tags}", + "Другие теги Ñ�охранÑ�Ñ‚Ñ�Ñ�: {tags}", + "Les autres balises restent inchangées : {tags}", + "Andere Tags bleiben unverändert: {tags}", + "Las demás etiquetas se mantienen: {tags}", + "Gli altri tag restano invariati: {tags}", + "As outras tags permanecem como estão: {tags}", + "Boshqa teglar o‘zgarmaydi: {tags}", + "БаÑ�қа тегтер өзгермейді: {tags}", + ], + [ + "«{name}» already has this game: No. {n}, {title} — the same players, date and moves.", + "Ð’ «{name}» уже еÑ�ть Ñ�та партиÑ�: â„– {n}, {title} — те же игроки, дата и ходы.", + "« {name} » contient déjà cette partie : n° {n}, {title} — mêmes joueurs, même date et mêmes coups.", + "„{name}“ enthält diese Partie bereits: Nr. {n}, {title} — dieselben Spieler, dasselbe Datum und dieselben Züge.", + "«{name}» ya tiene esta partida: n.º {n}, {title} — los mismos jugadores, la misma fecha y las mismas jugadas.", + "«{name}» contiene già questa partita: n. {n}, {title} — stessi giocatori, stessa data e stesse mosse.", + "“{name}â€� já tem esta partida: nº {n}, {title} — os mesmos jogadores, a mesma data e os mesmos lances.", + "“{name}â€� bazasida bu partiya allaqachon bor: â„– {n}, {title} — o‘yinchilar, sana va yurishlar bir xil.", + "«{name}» базаÑ�ында бұл партиÑ� бұрыннан бар: â„– {n}, {title} — ойыншылары, күні және жүріÑ�тері бірдей.", + ], + [ + "Delete the game from the database?", + "Удалить партию из базы?", + "Supprimer la partie de la base ?", + "Die Partie aus der Datenbank löschen?", + "¿Eliminar la partida de la base?", + "Eliminare la partita dal database?", + "Excluir a partida da base?", + "Partiyani bazadan o‘chirasizmi?", + "ПартиÑ�ны базадан жоÑ�Ñ�ыз ба?", + ], + [ + "«{title}» (No. {n}) is removed from the file «{file}»; other databases are not touched. Undo is offered for a few seconds.", + "«{title}» (â„– {n}) будет удалена из файла «{file}»; другие базы не затрагиваютÑ�Ñ�. Ð�еÑ�колько Ñ�екунд можно отменить.", + "« {title} » (n° {n}) sera supprimée du fichier « {file} » ; les autres bases ne sont pas touchées. Vous pourrez annuler pendant quelques secondes.", + "„{title}“ (Nr. {n}) wird aus der Datei „{file}“ gelöscht; andere Datenbanken bleiben unberührt. Einige Sekunden lang lässt sich das rückgängig machen.", + "«{title}» (n.º {n}) se eliminará del archivo «{file}»; las demás bases no se modifican. Durante unos segundos se podrá deshacer.", + "«{title}» (n. {n}) verrà eliminata dal file «{file}»; gli altri database non vengono toccati. Per qualche secondo si potrà annullare.", + "“{title}â€� (nº {n}) será excluída do arquivo “{file}â€�; as outras bases não são afetadas. Por alguns segundos, será possível desfazer.", + "“{title}â€� (â„– {n}) “{file}â€� faylidan o‘chiriladi; boshqa bazalarga tegilmaydi. Bir necha soniya davomida bekor qilish mumkin.", + "«{title}» (â„– {n}) «{file}» файлынан жойылады; баÑ�қа базаларға Ó™Ñ�ер етпейді. Бірнеше Ñ�екунд бойы болдырмауға болады.", + ], + [ + "Could not read the database: {e}", + "Ð�е удалоÑ�ÑŒ прочитать базу: {e}", + "Impossible de lire la base : {e}", + "Die Datenbank konnte nicht gelesen werden: {e}", + "No se pudo leer la base: {e}", + "Impossibile leggere il database: {e}", + "Não foi possível ler a base: {e}", + "Bazani o‘qib bo‘lmadi: {e}", + "Базаны оқу мүмкін болмады: {e}", + ], + [ + "A copy of the file in UTF-8, next to it: games can be added to the copy", + "КопиÑ� файла в UTF-8 Ñ€Ñ�дом Ñ� ним: в копию можно добавлÑ�ть партии", + "Une copie du fichier en UTF-8, à côté de lui : on peut ajouter des parties à la copie", + "Eine Kopie der Datei in UTF-8 daneben: In die Kopie lassen sich Partien aufnehmen", + "Una copia del archivo en UTF-8, junto a él: a la copia se pueden añadir partidas", + "Una copia del file in UTF-8, accanto a esso: alla copia si possono aggiungere partite", + "Uma cópia do arquivo em UTF-8, ao lado dele: à cópia é possível adicionar partidas", + "Faylning UTF-8 dagi nusxasi yonida: nusxaga o‘yinlar qo‘shish mumkin", + "Файлдың UTF-8 көшірмеÑ�Ñ– қаÑ�ында: көшірмеге партиÑ� қоÑ�уға болады", + ], + [ + "Add the game to «{name}»?", + "Добавить партию в «{name}»?", + "Ajouter la partie à « {name} » ?", + "Die Partie in „{name}“ aufnehmen?", + "¿Añadir la partida a «{name}»?", + "Aggiungere la partita a «{name}»?", + "Adicionar a partida a “{name}â€�?", + "O‘yinni “{name}â€� bazasiga qo‘shasizmi?", + "ПартиÑ�ны «{name}» базаÑ�ына қоÑ�у керек пе?", + ], + [ + "{name} · new game", + "{name} · новаÑ� партиÑ�", + "{name} · nouvelle partie", + "{name} · neue Partie", + "{name} · partida nueva", + "{name} · nuova partita", + "{name} · nova partida", + "{name} · yangi o‘yin", + "{name} · жаңа партиÑ�", + ], + [ + "Add to «{name}» (Ctrl+S)", + "Добавить в «{name}» (Ctrl+S)", + "Ajouter à « {name} » (Ctrl+S)", + "In „{name}“ aufnehmen (Ctrl+S)", + "Añadir a «{name}» (Ctrl+S)", + "Aggiungi a «{name}» (Ctrl+S)", + "Adicionar a “{name}â€� (Ctrl+S)", + "“{name}â€� bazasiga qo‘shish (Ctrl+S)", + "«{name}» базаÑ�ына қоÑ�у (Ctrl+S)", + ], + [ + "ðŸ”� Search", + "ðŸ”� ПоиÑ�к", + "ðŸ”� Rechercher", + "ðŸ”� Suche", + "ðŸ”� Buscar", + "ðŸ”� Cerca", + "ðŸ”� Buscar", + "ðŸ”� Qidirish", + "ðŸ”� Іздеу", + ], + [ + "+ Game", + "+ ПартиÑ�", + "+ Partie", + "+ Partie", + "+ Partida", + "+ Partita", + "+ Partida", + "+ O‘yin", + "+ ПартиÑ�", + ], + [ + "A new game for «{name}»: Ctrl+S adds it to this database", + "Ð�оваÑ� партиÑ� длÑ� «{name}»: Ctrl+S добавит её в Ñ�ту базу", + "Une nouvelle partie pour « {name} » : Ctrl+S l’ajoute à cette base", + "Eine neue Partie für „{name}“: Strg+S nimmt sie in diese Datenbank auf", + "Una partida nueva para «{name}»: Ctrl+S la añade a esta base", + "Una nuova partita per «{name}»: Ctrl+S la aggiunge a questo database", + "Uma nova partida para “{name}â€�: Ctrl+S a adiciona a esta base", + "“{name}â€� uchun yangi o‘yin: Ctrl+S uni shu bazaga qo‘shadi", + "«{name}» үшін жаңа партиÑ�: Ctrl+S оны оÑ�Ñ‹ базаға қоÑ�ады", + ], + [ + "This is a sample database of the program; it is only read. Make a database of your own for your games.", + "Это пример из комплекта программы, он только читаетÑ�Ñ�. ДлÑ� Ñ�воих партий Ñ�оздайте Ñ�вою базу.", + "C’est une base d’exemple du programme ; elle est en lecture seule. Créez votre propre base pour vos parties.", + "Dies ist eine Beispieldatenbank des Programms; sie wird nur gelesen. Legen Sie für Ihre Partien eine eigene Datenbank an.", + "Es una base de ejemplo del programa; solo se lee. Cree su propia base para sus partidas.", + "È un database di esempio del programma; è in sola lettura. Crea un tuo database per le tue partite.", + "É uma base de exemplo do programa; ela é somente leitura. Crie sua própria base para suas partidas.", + "Bu dasturning namuna bazasi, u faqat o‘qiladi. O‘yinlaringiz uchun o‘z bazangizni yarating.", + "Бұл бағдарламаның үлгі базаÑ�Ñ‹, ол тек оқылады. Өз партиÑ�ларыңыз үшін жеке база жаÑ�аңыз.", + ], + [ + "No databases yet", + "Баз пока нет", + "Aucune base pour l’instant", + "Noch keine Datenbanken", + "Aún no hay bases", + "Nessun database per ora", + "Ainda não há bases", + "Hozircha bazalar yo‘q", + "Әзірге база жоқ", + ], + [ + "or", + "или", + "ou", + "oder", + "o", + "oppure", + "ou", + "yoki", + "немеÑ�е", + ], + [ + "Choose a database above", + "Выберите базу выше", + "Choisissez une base ci-dessus", + "Wählen Sie oben eine Datenbank", + "Elija una base arriba", + "Scegli un database qui sopra", + "Escolha uma base acima", + "Yuqoridan bazani tanlang", + "Жоғарыдан базаны таңдаңыз", + ], + [ + "No databases of your own yet: create one below.", + "Своих баз пока нет: Ñ�оздайте её ниже.", + "Pas encore de base à vous : créez-en une ci-dessous.", + "Noch keine eigene Datenbank: Legen Sie unten eine an.", + "Aún no tiene bases propias: cree una abajo.", + "Non hai ancora database tuoi: creane uno qui sotto.", + "Você ainda não tem bases próprias: crie uma abaixo.", + "Hozircha o‘z bazangiz yo‘q: quyida yarating.", + "Әзірге өз базаңыз жоқ: төменде жаÑ�аңыз.", + ], + [ + "«+ Game» opens an empty board; Ctrl+S adds the game here. Or open any game and choose «Add to database…» (Ctrl+Shift+S)", + "«+ ПартиÑ�» откроет пуÑ�тую доÑ�ку; Ctrl+S добавит партию Ñ�юда. Или откройте любую партию и выберите «Добавить в базу…» (Ctrl+Shift+S)", + "« + Partie » ouvre un échiquier vide ; Ctrl+S ajoute la partie ici. Ou ouvrez n’importe quelle partie et choisissez « Ajouter à une base… » (Ctrl+Shift+S)", + "„+ Partie“ öffnet ein leeres Brett; Strg+S nimmt die Partie hier auf. Oder öffnen Sie eine beliebige Partie und wählen Sie „Zur Datenbank hinzufügen…“ (Strg+Umschalt+S)", + "«+ Partida» abre un tablero vacío; Ctrl+S añade la partida aquí. O abra cualquier partida y elija «Añadir a una base…» (Ctrl+Shift+S)", + "«+ Partita» apre una scacchiera vuota; Ctrl+S aggiunge qui la partita. Oppure apri una partita qualsiasi e scegli «Aggiungi a un database…» (Ctrl+Shift+S)", + "“+ Partidaâ€� abre um tabuleiro vazio; Ctrl+S adiciona a partida aqui. Ou abra qualquer partida e escolha “Adicionar a uma base…â€� (Ctrl+Shift+S)", + "“+ O‘yinâ€� bo‘sh taxtani ochadi; Ctrl+S o‘yinni shu yerga qo‘shadi. Yoki istalgan o‘yinni oching va “Bazaga qo‘shish…â€� ni tanlang (Ctrl+Shift+S)", + "«+ ПартиÑ�» боÑ� тақтаны ашады; Ctrl+S партиÑ�ны оÑ�ында қоÑ�ады. Ð�емеÑ�е кез келген партиÑ�ны ашып, «Базаға қоÑ�у…» таңдаңыз (Ctrl+Shift+S)", + ], + // --- user comments --- + [ + "Comment at the start of the game", + "Комментарий в начале партии", + "Commentaire au début de la partie", + "Kommentar zu Beginn der Partie", + "Comentario al inicio de la partida", + "Commento all’inizio della partita", + "Comentário no início da partida", + "Partiya boshidagi izoh", + "ПартиÑ� баÑ�ындағы түÑ�ініктеме", + ], + [ + "At the start", + "Ð’ начале партии", + "Au début de la partie", + "Zu Beginn der Partie", + "Al inicio de la partida", + "All’inizio della partita", + "No início da partida", + "Partiya boshida", + "ПартиÑ� баÑ�ында", + ], + [ + "Comment after {move}", + "Комментарий поÑ�ле {move}", + "Commentaire après {move}", + "Kommentar nach {move}", + "Comentario después de {move}", + "Commento dopo {move}", + "Comentário depois de {move}", + "{move} yurishidan keyingi izoh", + "{move} жүріÑ�інен кейінгі түÑ�ініктеме", + ], + [ + "After {move}", + "ПоÑ�ле {move}", + "Après {move}", + "Nach {move}", + "Después de {move}", + "Dopo {move}", + "Depois de {move}", + "{move} yurishidan keyin", + "{move} жүріÑ�інен кейін", + ], + [ + "Comment before {move}", + "Комментарий перед {move}", + "Commentaire avant {move}", + "Kommentar vor {move}", + "Comentario antes de {move}", + "Commento prima di {move}", + "Comentário antes de {move}", + "{move} yurishidan oldingi izoh", + "{move} жүріÑ�інің алдындағы түÑ�ініктеме", + ], + [ + "Before {move}", + "Перед {move}", + "Avant {move}", + "Vor {move}", + "Antes de {move}", + "Prima di {move}", + "Antes de {move}", + "{move} yurishidan oldin", + "{move} жүріÑ�інің алдында", + ], + [ + "Comment deleted (Ctrl+Z to undo)", + "Комментарий удалён (Ctrl+Z — вернуть)", + "Commentaire supprimé (Ctrl+Z pour annuler)", + "Kommentar gelöscht (Ctrl+Z zum Rückgängigmachen)", + "Comentario eliminado (Ctrl+Z para deshacer)", + "Commento eliminato (Ctrl+Z per annullare)", + "Comentário excluído (Ctrl+Z para desfazer)", + "Izoh o‘chirildi (bekor qilish: Ctrl+Z)", + "ТүÑ�ініктеме жойылды (болдырмау — Ctrl+Z)", + ], + [ + "Comment at the start of the game… (Enter)", + "Комментарий в начале партии… (Enter)", + "Commentaire au début de la partie… (Enter)", + "Kommentar zu Beginn der Partie… (Enter)", + "Comentario al inicio de la partida… (Enter)", + "Commento all’inizio della partita… (Enter)", + "Comentário no início da partida… (Enter)", + "Partiya boshidagi izoh… (Enter)", + "ПартиÑ� баÑ�ындағы түÑ�ініктеме… (Enter)", + ], + [ + "Comment on the move… (Enter)", + "Комментарий к ходу… (Enter)", + "Commentaire sur le coup… (Enter)", + "Kommentar zum Zug… (Enter)", + "Comentario a la jugada… (Enter)", + "Commento alla mossa… (Enter)", + "Comentário ao lance… (Enter)", + "Yurishga izoh… (Enter)", + "ЖүріÑ�ке түÑ�ініктеме… (Enter)", + ], + [ + "Edit comment…", + "Изменить комментарий…", + "Modifier le commentaire…", + "Kommentar bearbeiten…", + "Editar comentario…", + "Modifica commento…", + "Editar comentário…", + "Izohni tahrirlash…", + "ТүÑ�ініктемені өзгерту…", + ], + [ + "Comment…", + "Комментарий…", + "Commentaire…", + "Kommentar…", + "Comentario…", + "Commento…", + "Comentário…", + "Izoh…", + "ТүÑ�ініктеме…", + ], + [ + "Delete comment", + "Удалить комментарий", + "Supprimer le commentaire", + "Kommentar löschen", + "Eliminar comentario", + "Elimina commento", + "Excluir comentário", + "Izohni o‘chirish", + "ТүÑ�ініктемені жою", + ], + [ + "Comment at the start of the game…", + "Комментарий в начале партии…", + "Commentaire au début de la partie…", + "Kommentar zu Beginn der Partie…", + "Comentario al inicio de la partida…", + "Commento all’inizio della partita…", + "Comentário no início da partida…", + "Partiya boshidagi izoh…", + "ПартиÑ� баÑ�ындағы түÑ�ініктеме…", + ], + [ + "Cancel (Esc)", + "Отмена (Esc)", + "Annuler (Esc)", + "Abbrechen (Esc)", + "Cancelar (Esc)", + "Annulla (Esc)", + "Cancelar (Esc)", + "Bekor qilish (Esc)", + "БаÑ� тарту (Esc)", + ], + [ + "Done (Enter)", + "Готово (Enter)", + "Terminé (Enter)", + "Fertig (Enter)", + "Listo (Enter)", + "Fatto (Enter)", + "Concluído (Enter)", + "Tayyor (Enter)", + "Дайын (Enter)", + ], + [ + "Position assessment", + "Оценка позиции", + "Évaluation de la position", + "Stellungsbewertung", + "Valoración de la posición", + "Valutazione della posizione", + "Avaliação da posição", + "Pozitsiya bahosi", + "ПозициÑ�ны бағалау", + ], + [ + "Your comment…", + "Ваш комментарий…", + "Votre commentaire…", + "Ihr Kommentar…", + "Su comentario…", + "Il tuo commento…", + "Seu comentário…", + "Izohingiz…", + "Сіздің түÑ�ініктемеңіз…", + ], + [ + "Enter — done · Esc — cancel · Shift+Enter — new paragraph", + "Enter — готово · Esc — отмена · Shift+Enter — новый абзац", + "Enter — terminer · Esc — annuler · Shift+Enter — nouveau paragraphe", + "Enter — fertig · Esc — abbrechen · Shift+Enter — neuer Absatz", + "Enter — listo · Esc — cancelar · Shift+Enter — nuevo párrafo", + "Enter — fatto · Esc — annulla · Shift+Enter — nuovo paragrafo", + "Enter — concluir · Esc — cancelar · Shift+Enter — novo parágrafo", + "Enter — tayyor · Esc — bekor qilish · Shift+Enter — yangi xatboshi", + "Enter — дайын · Esc — баÑ� тарту · Shift+Enter — жаңа абзац", + ], + [ + "⇄ You are editing the original; its translation will be dropped", + "⇄ ПравитÑ�Ñ� оригинал; перевод Ñ�того комментариÑ� пропадёт", + "⇄ Vous modifiez l’original ; sa traduction sera supprimée", + "⇄ Sie bearbeiten das Original; seine Übersetzung wird verworfen", + "⇄ Está editando el original; su traducción se descartará", + "⇄ Stai modificando l’originale; la sua traduzione verrà scartata", + "⇄ Você está editando o original; sua tradução será descartada", + "⇄ Siz aslini tahrirlayapsiz; uning tarjimasi o‘chiriladi", + "⇄ Сіз түпнұÑ�қаны өңдеп жатырÑ�ыз; оның аудармаÑ�Ñ‹ жойылады", + ], + [ + "Great move", + "Замечательный ход", + "Excellent coup", + "Starker Zug", + "Gran jugada", + "Ottima mossa", + "Ótimo lance", + "Kuchli yurish", + "Мықты жүріÑ�", + ], + [ + "Brilliant moves", + "БлеÑ�Ñ‚Ñ�щий", + "Coups brillants", + "Brillante Züge", + "Jugadas brillantes", + "Mosse brillanti", + "Lances brilhantes", + "Ajoyib yurishlar", + "Тамаша жүріÑ�тер", + ], + [ + "Great moves", + "Замечательный", + "Excellents coups", + "Starke Züge", + "Grandes jugadas", + "Ottime mosse", + "Ótimos lances", + "Kuchli yurishlar", + "Мықты жүріÑ�тер", + ], + [ + "!! and ! need the engine: the PGN has evaluations only", + "!! и ! Ñ�тавит только движок: в PGN еÑ�ть лишь оценки", + "!! et ! demandent le moteur : le PGN ne contient que des évaluations", + "!! und ! braucht die Engine: die PGN enthält nur Bewertungen", + "!! y ! requieren el motor: el PGN solo trae evaluaciones", + "!! e ! richiedono il motore: il PGN contiene solo valutazioni", + "!! e ! exigem o motor: o PGN traz só avaliações", + "!! va ! faqat dvigatel bilan: PGNda faqat baholar bor", + "!! және ! тек қозғалтқышпен: PGN-да тек бағалар бар", + ], + [ + "!! and ! were not looked for in this analysis", + "Ð’ Ñ�том анализе !! и ! ещё не иÑ�кали", + "Cette analyse n’a pas encore cherché les !! et !", + "In dieser Analyse wurde noch nicht nach !! und ! gesucht", + "Este análisis aún no buscó !! ni !", + "Questa analisi non ha ancora cercato !! e !", + "Esta análise ainda não procurou !! e !", + "Bu tahlilda !! va ! hali qidirilmagan", + "Бұл талдауда !! мен ! әлі ізделмеген", + ], + [ + "Good move", + "Хороший ход", + "Bon coup", + "Guter Zug", + "Buena jugada", + "Buona mossa", + "Bom lance", + "Yaxshi yurish", + "ЖақÑ�Ñ‹ жүріÑ�", + ], + [ + "Brilliant move", + "БлеÑ�Ñ‚Ñ�щий ход", + "Coup brillant", + "Brillanter Zug", + "Jugada brillante", + "Mossa brillante", + "Lance brilhante", + "Ajoyib yurish", + "Тамаша жүріÑ�", + ], + [ + "Interesting move", + "ИнтереÑ�ный ход", + "Coup intéressant", + "Interessanter Zug", + "Jugada interesante", + "Mossa interessante", + "Lance interessante", + "Qiziqarli yurish", + "Қызықты жүріÑ�", + ], + [ + "Dubious move", + "Сомнительный ход", + "Coup douteux", + "Zweifelhafter Zug", + "Jugada dudosa", + "Mossa dubbia", + "Lance duvidoso", + "Shubhali yurish", + "Күмәнді жүріÑ�", + ], + [ + "Equal position", + "РавенÑ�тво", + "Position égale", + "Ausgeglichene Stellung", + "Posición igualada", + "Posizione pari", + "Posição igual", + "Teng pozitsiya", + "Тең позициÑ�", + ], + [ + "Unclear position", + "Ð�еÑ�Ñ�но", + "Position peu claire", + "Unklare Stellung", + "Posición poco clara", + "Posizione poco chiara", + "Posição pouco clara", + "Noaniq pozitsiya", + "Ð�нық емеÑ� позициÑ�", + ], + [ + "White is slightly better", + "У белых чуть лучше", + "Les Blancs sont légèrement mieux", + "Weiß steht etwas besser", + "Las blancas están ligeramente mejor", + "Il Bianco sta leggermente meglio", + "As brancas estão ligeiramente melhor", + "Oqlar biroz yaxshiroq", + "Ð�қтардың жағдайы Ñ�әл жақÑ�Ñ‹", + ], + [ + "Black is slightly better", + "У чёрных чуть лучше", + "Les Noirs sont légèrement mieux", + "Schwarz steht etwas besser", + "Las negras están ligeramente mejor", + "Il Nero sta leggermente meglio", + "As pretas estão ligeiramente melhor", + "Qoralar biroz yaxshiroq", + "Қаралардың жағдайы Ñ�әл жақÑ�Ñ‹", + ], + [ + "White is better", + "У белых перевеÑ�", + "Les Blancs sont mieux", + "Weiß steht besser", + "Las blancas están mejor", + "Il Bianco sta meglio", + "As brancas estão melhor", + "Oqlar yaxshiroq", + "Ð�қтардың жағдайы жақÑ�Ñ‹", + ], + [ + "Black is better", + "У чёрных перевеÑ�", + "Les Noirs sont mieux", + "Schwarz steht besser", + "Las negras están mejor", + "Il Nero sta meglio", + "As pretas estão melhor", + "Qoralar yaxshiroq", + "Қаралардың жағдайы жақÑ�Ñ‹", + ], + [ + "White is winning", + "Белые выигрывают", + "Les Blancs gagnent", + "Weiß steht auf Gewinn", + "Las blancas ganan", + "Il Bianco vince", + "As brancas estão ganhando", + "Oqlar yutmoqda", + "Ð�қтар ұтып жатыр", + ], + [ + "Black is winning", + "Чёрные выигрывают", + "Les Noirs gagnent", + "Schwarz steht auf Gewinn", + "Las negras ganan", + "Il Nero vince", + "As pretas estão ganhando", + "Qoralar yutmoqda", + "Қаралар ұтып жатыр", + ], + [ + "+ Add as variation", + "+ Добавить как вариант", + "+ Ajouter comme variante", + "+ Als Variante hinzufügen", + "+ Añadir como variante", + "+ Aggiungi come variante", + "+ Adicionar como variante", + "+ Variant sifatida qo‘shish", + "+ Ð�Ò±Ñ�қа ретінде қоÑ�у", + ], + [ + "Puts the line into the game as a variation (Ctrl+Z to undo)", + "Запишет линию в партию вариантом (Ctrl+Z — отменить)", + "Ajoute la ligne à la partie comme variante (Ctrl+Z pour annuler)", + "Nimmt die Linie als Variante in die Partie auf (Ctrl+Z zum Rückgängigmachen)", + "Añade la línea a la partida como variante (Ctrl+Z para deshacer)", + "Aggiunge la linea alla partita come variante (Ctrl+Z per annullare)", + "Adiciona a linha à partida como variante (Ctrl+Z para desfazer)", + "Liniyani o‘yinga variant sifatida yozadi (Ctrl+Z — bekor qilish)", + "Желіні партиÑ�ға нұÑ�қа ретінде жазады (Ctrl+Z — болдырмау)", + ], + // --- play against Maia --- + [ + "Game vs computer, {speed}", + "ПартиÑ� Ñ� компьютером, {speed}", + "Partie contre l’ordinateur, {speed}", + "Partie gegen den Computer, {speed}", + "Partida contra el ordenador, {speed}", + "Partita contro il computer, {speed}", + "Partida contra o computador, {speed}", + "Kompyuter bilan partiya, {speed}", + "Компьютермен партиÑ�, {speed}", + ], + [ + "Game vs computer", + "ПартиÑ� Ñ� компьютером", + "Partie contre l’ordinateur", + "Partie gegen den Computer", + "Partida contra el ordenador", + "Partita contro il computer", + "Partida contra o computador", + "Kompyuter bilan partiya", + "Компьютермен партиÑ�", + ], + [ + "Maia did not start: {e}", + "Maia не запуÑ�тилаÑ�ÑŒ: {e}", + "Maia n’a pas démarré : {e}", + "Maia ist nicht gestartet: {e}", + "Maia no se inició: {e}", + "Maia non si è avviata: {e}", + "A Maia não iniciou: {e}", + "Maia ishga tushmadi: {e}", + "Maia Ñ–Ñ�ке қоÑ�ылмады: {e}", + ], + [ + "The engine is off during the game — analyse after it ends", + "Во времÑ� партии движок выключен — анализ поÑ�ле конца", + "Le moteur est désactivé pendant la partie — analysez après la fin", + "Die Engine ist während der Partie aus — analysieren Sie nach dem Ende", + "El motor está apagado durante la partida — analiza al terminar", + "Il motore è spento durante la partita — analizza dopo la fine", + "O motor fica desligado durante a partida — analise depois do fim", + "Partiya davomida dvigatel o‘chiq — tahlil partiyadan keyin", + "ПартиÑ� кезінде қозғалтқыш Ñ�өндірулі — талдау партиÑ�дан кейін", + ], + [ + "The game is on", + "ПартиÑ� идёт", + "La partie est en cours", + "Die Partie läuft", + "La partida está en curso", + "La partita è in corso", + "A partida está em andamento", + "Partiya davom etmoqda", + "ПартиÑ� жүріп жатыр", + ], + [ + "Resign and add to a database…", + "СдатьÑ�Ñ� и добавить в базу…", + "Abandonner et ajouter à une base…", + "Aufgeben und zur Datenbank hinzufügen…", + "Abandonar y añadir a una base…", + "Abbandona e aggiungi a un database…", + "Abandonar e adicionar a uma base…", + "Taslim bo‘lish va bazaga qo‘shish…", + "Берілу және базаға қоÑ�у…", + ], + [ + "Resign and leave", + "СдатьÑ�Ñ� и выйти", + "Abandonner et quitter", + "Aufgeben und verlassen", + "Abandonar y salir", + "Abbandona ed esci", + "Abandonar e sair", + "Taslim bo‘lish va chiqish", + "Берілу және шығу", + ], + [ + "Keep playing", + "Продолжить игру", + "Continuer à jouer", + "Weiterspielen", + "Seguir jugando", + "Continua a giocare", + "Continuar jogando", + "O‘yinni davom ettirish", + "Ойынды жалғаÑ�тыру", + ], + [ + "Viewing an earlier position · back to the game — End", + "ПроÑ�мотр прошлой позиции · к игре — End", + "Position antérieure affichée · retour à la partie — End", + "Frühere Stellung wird angezeigt · zurück zur Partie — End", + "Viendo una posición anterior · volver a la partida — End", + "Posizione precedente · torna alla partita — End", + "Vendo uma posição anterior · voltar à partida — End", + "Oldingi pozitsiya ko‘rilmoqda · o‘yinga qaytish — End", + "Бұрынғы позициÑ� көрÑ�етілуде · ойынға оралу — End", + ], + ["You", "Ð’Ñ‹", "Vous", "Sie", "Tú", "Tu", "Você", "Siz", "Сіз"], + [ + "thinking…", + "думает…", + "réfléchit…", + "denkt nach…", + "pensando…", + "sta pensando…", + "pensando…", + "o‘ylamoqda…", + "ойлануда…", + ], + [ + "your move", + "ваш ход", + "à vous de jouer", + "Sie sind am Zug", + "tu turno", + "tocca a te", + "sua vez", + "sizning yurishingiz", + "Ñ�іздің жүріÑ�іңіз", + ], + [ + "waiting", + "ждёт", + "en attente", + "wartet", + "esperando", + "in attesa", + "aguardando", + "kutmoqda", + "күтуде", + ], + [ + "↶ Take back", + "↶ Ход назад", + "↶ Reprendre", + "↶ Zurücknehmen", + "↶ Deshacer jugada", + "↶ Ritira mossa", + "↶ Voltar lance", + "↶ Yurishni qaytarish", + "↶ ЖүріÑ�ті қайтару", + ], + [ + "Take back a move (Ctrl+Z)", + "ВзÑ�ть ход назад (Ctrl+Z)", + "Reprendre un coup (Ctrl+Z)", + "Einen Zug zurücknehmen (Ctrl+Z)", + "Deshacer una jugada (Ctrl+Z)", + "Ritira una mossa (Ctrl+Z)", + "Voltar um lance (Ctrl+Z)", + "Yurishni qaytarish (Ctrl+Z)", + "ЖүріÑ�ті қайтару (Ctrl+Z)", + ], + [ + "× Abort", + "× Прервать", + "× Annuler la partie", + "× Abbrechen", + "× Anular", + "× Annulla partita", + "× Anular", + "× To‘xtatish", + "× Тоқтату", + ], + [ + "Leave without a result: no moves made yet", + "Выйти без результата: ходы ещё не Ñ�деланы", + "Quitter sans résultat : aucun coup n’a encore été joué", + "Ohne Ergebnis verlassen: noch keine Züge gespielt", + "Salir sin resultado: aún no se ha hecho ninguna jugada", + "Esci senza risultato: nessuna mossa ancora giocata", + "Sair sem resultado: nenhum lance foi feito ainda", + "Natijasiz chiqish: hali yurish qilinmagan", + "Ð�әтижеÑ�із шығу: әзірге жүріÑ� жаÑ�алмаған", + ], + [ + "Resign?", + "СдатьÑ�Ñ�?", + "Abandonner ?", + "Aufgeben?", + "¿Abandonar?", + "Abbandonare?", + "Abandonar?", + "Taslim bo‘lasizmi?", + "БерілеÑ�із бе?", + ], + ["Yes", "Да", "Oui", "Ja", "Sí", "Sì", "Sim", "Ha", "Иә"], + ["No", "Ð�ет", "Non", "Nein", "No", "No", "Não", "Yo‘q", "Жоқ"], + [ + "âš‘ Resign", + "âš‘ СдатьÑ�Ñ�", + "âš‘ Abandonner", + "âš‘ Aufgeben", + "âš‘ Abandonar", + "âš‘ Abbandona", + "âš‘ Abandonar", + "âš‘ Taslim bo‘lish", + "âš‘ Берілу", + ], + [ + "Left: you {you} · Maia {maia}", + "ОÑ�талоÑ�ÑŒ: вы {you} · Maia {maia}", + "Restant : vous {you} · Maia {maia}", + "Verbleibend: Sie {you} · Maia {maia}", + "Queda: tú {you} · Maia {maia}", + "Rimasto: tu {you} · Maia {maia}", + "Restante: você {you} · Maia {maia}", + "Qoldi: siz {you} · Maia {maia}", + "Қалды: Ñ�із {you} · Maia {maia}", + ], + [ + "📈 Analyse", + "📈 Ð�нализировать", + "📈 Analyser", + "📈 Analysieren", + "📈 Analizar", + "📈 Analizza", + "📈 Analisar", + "📈 Tahlil qilish", + "📈 Талдау", + ], + [ + "↻ Rematch", + "↻ Реванш", + "↻ Revanche", + "↻ Revanche", + "↻ Revancha", + "↻ Rivincita", + "↻ Revanche", + "↻ Revansh", + "↻ Реванш", + ], + [ + "Same settings, colours swapped", + "Те же наÑ�тройки, цвета менÑ�ÑŽÑ‚Ñ�Ñ�", + "Mêmes réglages, couleurs inversées", + "Gleiche Einstellungen, Farben getauscht", + "Misma configuración, colores intercambiados", + "Stesse impostazioni, colori invertiti", + "Mesmas configurações, cores trocadas", + "Sozlamalar o‘sha, ranglar almashadi", + "Баптаулар Ñ�ол, түÑ�тер ауыÑ�ады", + ], + [ + "♞ New game", + "♞ Ð�оваÑ� игра", + "♞ Nouvelle partie", + "♞ Neue Partie", + "♞ Nueva partida", + "♞ Nuova partita", + "♞ Nova partida", + "♞ Yangi o‘yin", + "♞ Жаңа ойын", + ], + [ + "💾 Save to a database…", + "💾 Сохранить в базу…", + "💾 Enregistrer dans une base…", + "💾 In einer Datenbank speichern…", + "💾 Guardar en una base…", + "💾 Salva in un database…", + "💾 Salvar em uma base…", + "💾 Bazaga saqlash…", + "💾 Базаға Ñ�ақтау…", + ], + [ + "♞ Play", + "♞ Играть", + "♞ Jouer", + "♞ Spielen", + "♞ Jugar", + "♞ Gioca", + "♞ Jogar", + "♞ O‘ynash", + "♞ Ойнау", + ], + [ + "A game against Maia, which plays like a human of the chosen rating (Ctrl+G)", + "ПартиÑ� Ñ� Maia — она играет как человек выбранного рейтинга (Ctrl+G)", + "Une partie contre Maia, qui joue comme un humain du classement choisi (Ctrl+G)", + "Eine Partie gegen Maia, die wie ein Mensch der gewählten Wertungszahl spielt (Ctrl+G)", + "Una partida contra Maia, que juega como un humano del rating elegido (Ctrl+G)", + "Una partita contro Maia, che gioca come un umano del rating scelto (Ctrl+G)", + "Uma partida contra a Maia, que joga como um humano do rating escolhido (Ctrl+G)", + "Maia bilan partiya — u tanlangan reytingdagi odamdek o‘ynaydi (Ctrl+G)", + "Maia-мен партиÑ� — ол таңдалған рейтингтегі адамдай ойнайды (Ctrl+G)", + ], + [ + "The file is not the published one", + "Файл не Ñ�овпадает Ñ� опубликованным", + "Le fichier ne correspond pas à celui publié", + "Die Datei stimmt nicht mit der veröffentlichten überein", + "El archivo no coincide con el publicado", + "Il file non corrisponde a quello pubblicato", + "O arquivo não corresponde ao publicado", + "Fayl eʼlon qilingani bilan mos kelmaydi", + "Файл жариÑ�ланғанымен Ñ�әйкеÑ� келмейді", + ], + [ + "Blitz", "Блиц", "Blitz", "Blitz", "Blitz", "Blitz", "Blitz", "Blits", "Блиц", + ], + [ + "Rapid", + "Рапид", + "Rapide", + "Schnellschach", + "Rápidas", + "Rapid", + "Rápida", + "Tezkor", + "Рапид", + ], + [ + "Classical", + "КлаÑ�Ñ�ика", + "Classique", + "Klassisch", + "Clásicas", + "Classica", + "Clássica", + "Klassik", + "КлаÑ�Ñ�ика", + ], + [ + "Play against the computer", + "Игра Ñ� компьютером", + "Jouer contre l’ordinateur", + "Gegen den Computer spielen", + "Jugar contra el ordenador", + "Gioca contro il computer", + "Jogar contra o computador", + "Kompyuter bilan o‘ynash", + "Компьютермен ойнау", + ], + [ + "Maia plays like a human of the chosen rating: it makes the moves people of that level make, mistakes included.", + "Maia играет как человек выбранного рейтинга: делает ходы, какие делают люди Ñ�того уровнÑ�, вмеÑ�те Ñ� их ошибками.", + "Maia joue comme un humain du classement choisi : elle joue les coups que jouent les joueurs de ce niveau, erreurs comprises.", + "Maia spielt wie ein Mensch der gewählten Wertungszahl: Sie macht die Züge, die Spieler dieser Stärke machen, Fehler eingeschlossen.", + "Maia juega como un humano del rating elegido: hace las jugadas que hacen las personas de ese nivel, errores incluidos.", + "Maia gioca come un umano del rating scelto: fa le mosse che fanno i giocatori di quel livello, errori compresi.", + "A Maia joga como um humano do rating escolhido: faz os lances que pessoas desse nível fazem, erros incluídos.", + "Maia tanlangan reytingdagi odamdek o‘ynaydi: shu darajadagi odamlar qiladigan yurishlarni, xatolari bilan birga qiladi.", + "Maia таңдалған рейтингтегі адамдай ойнайды: оÑ�Ñ‹ деңгейдегі адамдар жаÑ�айтын жүріÑ�терді қателерімен қоÑ�а жаÑ�айды.", + ], + [ + "Name:", "ИмÑ�:", "Nom :", "Name:", "Nombre:", "Nome:", "Nome:", "Ism:", "Ð�ты:", + ], + [ + "Rating:", + "Рейтинг:", + "Classement :", + "Wertungszahl:", + "Rating:", + "Rating:", + "Rating:", + "Reyting:", + "Рейтинг:", + ], + [ + "Your colour", + "Цвет", + "Votre couleur", + "Ihre Farbe", + "Tu color", + "Il tuo colore", + "Sua cor", + "Rangingiz", + "ТүÑ�іңіз", + ], + [ + "Random", + "Случайно", + "Au hasard", + "Zufällig", + "Al azar", + "Casuale", + "Aleatório", + "Tasodifiy", + "КездейÑ�оқ", + ], + [ + "Time", + "ВремÑ�", + "Cadence", + "Bedenkzeit", + "Tiempo", + "Tempo", + "Tempo", + "Vaqt", + "Уақыт", + ], + [ + "Custom", + "Свой", + "Personnalisée", + "Eigene", + "Personalizado", + "Personalizzato", + "Personalizado", + "Boshqa", + "Өзіндік", + ], + [ + "Minutes:", + "Минуты:", + "Minutes :", + "Minuten:", + "Minutos:", + "Minuti:", + "Minutos:", + "Daqiqa:", + "Минут:", + ], + [ + "Increment, s:", + "Прибавка, Ñ�:", + "Incrément, s :", + "Inkrement, s:", + "Incremento, s:", + "Incremento, s:", + "Incremento, s:", + "Qo‘shimcha, s:", + "ҚоÑ�ымша, Ñ�:", + ], + [ + "Play", + "Играть", + "Jouer", + "Spielen", + "Jugar", + "Gioca", + "Jogar", + "O‘ynash", + "Ойнау", + ], + [ + "Maia is downloaded once ({mb} MB, from huggingface.co, the authors' own file).", + "Maia Ñ�качиваетÑ�Ñ� один раз ({mb} МБ, Ñ� huggingface.co — файл Ñ�амих авторов).", + "Maia est téléchargée une seule fois ({mb} Mo, depuis huggingface.co, le fichier des auteurs eux-mêmes).", + "Maia wird einmalig heruntergeladen ({mb} MB, von huggingface.co, die Datei der Autoren selbst).", + "Maia se descarga una sola vez ({mb} MB, desde huggingface.co, el archivo de los propios autores).", + "Maia si scarica una sola volta ({mb} MB, da huggingface.co, il file degli autori stessi).", + "A Maia é baixada uma única vez ({mb} MB, de huggingface.co, o arquivo dos próprios autores).", + "Maia bir marta yuklab olinadi ({mb} MB, huggingface.co dan — mualliflarning o‘z fayli).", + "Maia бір рет жүктеледі ({mb} МБ, huggingface.co Ñ�айтынан — авторлардың өз файлы).", + ], + [ + "You resigned", + "Ð’Ñ‹ Ñ�далиÑ�ÑŒ", + "Vous avez abandonné", + "Sie haben aufgegeben", + "Has abandonado", + "Hai abbandonato", + "Você abandonou", + "Siz taslim bo‘ldingiz", + "Сіз берілдіңіз", + ], + [ + "You won", + "Ð’Ñ‹ выиграли", + "Vous avez gagné", + "Sie haben gewonnen", + "Has ganado", + "Hai vinto", + "Você venceu", + "Siz yutdingiz", + "Сіз жеңдіңіз", + ], + [ + "You lost", + "Ð’Ñ‹ проиграли", + "Vous avez perdu", + "Sie haben verloren", + "Has perdido", + "Hai perso", + "Você perdeu", + "Siz yutqazdingiz", + "Сіз жеңілдіңіз", + ], + [ + "checkmate", + "мат", + "échec et mat", + "Schachmatt", + "jaque mate", + "scacco matto", + "xeque-mate", + "mat", + "мат", + ], + [ + "stalemate", + "пат", + "pat", + "Patt", + "rey ahogado", + "stallo", + "afogamento", + "pat", + "пат", + ], + [ + "neither side can checkmate", + "ни у кого нет материала длÑ� мата", + "aucun camp ne peut mater", + "keine Seite kann mattsetzen", + "ningún bando puede dar mate", + "nessuno dei due può dare matto", + "nenhum lado consegue dar mate", + "hech bir tomon mat qila olmaydi", + "ешбір жақ мат қоÑ� алмайды", + ], + [ + "the position occurred three times", + "позициÑ� повторилаÑ�ÑŒ трижды", + "la position s’est répétée trois fois", + "die Stellung ist dreimal aufgetreten", + "la posición se repitió tres veces", + "la posizione si è ripetuta tre volte", + "a posição se repetiu três vezes", + "pozitsiya uch marta takrorlandi", + "позициÑ� үш рет қайталанды", + ], + [ + "50 moves without a capture or a pawn move", + "50 ходов без взÑ�тий и ходов пешек", + "50 coups sans prise ni coup de pion", + "50 Züge ohne Schlagen oder Bauernzug", + "50 jugadas sin capturas ni movimientos de peón", + "50 mosse senza catture né mosse di pedone", + "50 lances sem captura nem lance de peão", + "50 yurish davomida olish ham, piyoda yurishi ham yo‘q", + "50 жүріÑ� бойы алу да, пешка жүріÑ�Ñ– де жоқ", + ], + [ + "time is up, but Maia cannot checkmate", + "времÑ� вышло, но у Maia нечем поÑ�тавить мат", + "le temps est écoulé, mais Maia ne peut pas mater", + "die Zeit ist abgelaufen, aber Maia kann nicht mattsetzen", + "se acabó el tiempo, pero Maia no puede dar mate", + "il tempo è scaduto, ma Maia non può dare matto", + "o tempo acabou, mas a Maia não consegue dar mate", + "vaqt tugadi, lekin Maia mat qila olmaydi", + "уақыт бітті, бірақ Maia мат қоÑ� алмайды", + ], + [ + "time is up", + "времÑ� вышло", + "le temps est écoulé", + "die Zeit ist abgelaufen", + "se acabó el tiempo", + "il tempo è scaduto", + "o tempo acabou", + "vaqt tugadi", + "уақыт бітті", + ], + [ + "Maia's time is up, but you cannot checkmate", + "у Maia вышло времÑ�, но вам нечем поÑ�тавить мат", + "le temps de Maia est écoulé, mais vous ne pouvez pas mater", + "Maias Zeit ist abgelaufen, aber Sie können nicht mattsetzen", + "a Maia se le acabó el tiempo, pero no puedes dar mate", + "il tempo di Maia è scaduto, ma non puoi dare scacco matto", + "o tempo de Maia acabou, mas você não consegue dar mate", + "Maiada vaqt tugadi, lekin sizda mot qilishga yetarli kuch yo‘q", + "Maia-ның уақыты бітті, бірақ Ñ�ізде мат қоюға күш жоқ", + ], + [ + "Download and play", + "Скачать и играть", + "Télécharger et jouer", + "Herunterladen und spielen", + "Descargar y jugar", + "Scarica e gioca", + "Baixar e jogar", + "Yuklab olish va o‘ynash", + "Жүктеп алып ойнау", + ], + [ + "No clocks: think as long as you like", + "Без чаÑ�ов: думайте Ñ�колько угодно", + "Sans pendule : réfléchissez aussi longtemps que vous voulez", + "Ohne Uhr: Denken Sie so lange, wie Sie möchten", + "Sin reloj: piensa todo lo que quieras", + "Senza orologio: pensa quanto vuoi", + "Sem relógio: pense o quanto quiser", + "Soatsiz: xohlagancha o‘ylang", + "СағатÑ�ыз: қалағаныңызша ойланыңыз", + ], + [ + "Always promote to a queen", + "Ð’Ñ�егда превращать пешку в ферзÑ�", + "Toujours promouvoir en dame", + "Immer in eine Dame umwandeln", + "Coronar siempre en dama", + "Promuovi sempre a donna", + "Sempre promover a dama", + "Piyodani doim farzinga aylantirish", + "Пешканы әрқашан уәзірге айналдыру", + ], + [ + "Off: a pawn on the last rank asks which piece it becomes", + "Выключено: пешка на поÑ�ледней горизонтали Ñ�прашивает, в какую фигуру превратитьÑ�Ñ�", + "Désactivé : un pion sur la dernière rangée demande en quelle pièce il se transforme", + "Aus: Ein Bauer auf der letzten Reihe fragt, in welche Figur er sich umwandelt", + "Desactivado: un peón en la última fila pregunta en qué pieza se convierte", + "Disattivato: un pedone sull’ultima traversa chiede in quale pezzo trasformarsi", + "Desligado: um peão na última fileira pergunta em qual peça se transforma", + "O‘chiq: oxirgi qatordagi piyoda qaysi donaga aylanishini so‘raydi", + "Өшірулі: Ñ�оңғы көлденеңдегі пешка қай таÑ�қа айналатынын Ñ�ұрайды", + ], + [ + "not required", + "не обÑ�зательно", + "facultatif", + "optional", + "opcional", + "facoltativo", + "opcional", + "majburiy emas", + "міндетті емеÑ�", + ], + [ + "Opponent — Maia {elo}", + "Соперник — Maia {elo}", + "Adversaire — Maia {elo}", + "Gegner — Maia {elo}", + "Rival — Maia {elo}", + "Avversario — Maia {elo}", + "Adversário — Maia {elo}", + "Raqib — Maia {elo}", + "ҚарÑ�ылаÑ� — Maia {elo}", + ], + [ + "Time control", + "Контроль времени", + "Cadence", + "Bedenkzeit", + "Ritmo de juego", + "Cadenza", + "Ritmo de jogo", + "Vaqt nazorati", + "Уақыт бақылауы", + ], + [ + "Unlimited", + "БеÑ�Ñ�рочно", + "Illimité", + "Unbegrenzt", + "Ilimitado", + "Illimitato", + "Ilimitado", + "Cheklovsiz", + "ШектеуÑ�із", + ], + [ + "Her measured strength, on the Lichess blitz scale.", + "Её измереннаÑ� Ñ�ила, по шкале блица Lichess.", + "Sa force mesurée, sur l’échelle du blitz Lichess.", + "Ihre gemessene Spielstärke, auf der Lichess-Blitz-Skala.", + "Su fuerza medida, en la escala de blitz de Lichess.", + "La sua forza misurata, sulla scala del blitz di Lichess.", + "A força medida dela, na escala de blitz do Lichess.", + "Uning o‘lchangan kuchi, Lichess blits shkalasi bo‘yicha.", + "Оның өлшенген күші, Lichess блиц шкалаÑ�Ñ‹ бойынша.", + ], + [ + "Stronger than {elo} plays the large Maia: {mb} MB, downloaded once.", + "Сильнее {elo} играет большаÑ� Maia: {mb} МБ, Ñ�качиваетÑ�Ñ� один раз.", + "Au-delà de {elo}, c’est la grande Maia qui joue : {mb} Mo, téléchargée une seule fois.", + "Stärker als {elo} spielt die große Maia: {mb} MB, einmalig heruntergeladen.", + "Por encima de {elo} juega la Maia grande: {mb} MB, se descarga una sola vez.", + "Oltre {elo} gioca la Maia grande: {mb} MB, si scarica una sola volta.", + "Acima de {elo} joga a Maia grande: {mb} MB, baixada uma única vez.", + "{elo} dan kuchliroq katta Maia o‘ynaydi: {mb} MB, bir marta yuklab olinadi.", + "{elo}-ден күштірек үлкен Maia ойнайды: {mb} МБ, бір рет жүктеледі.", + ], + [ + "by agreement", + "по Ñ�оглашению", + "par accord mutuel", + "durch Einigung", + "por acuerdo", + "per accordo", + "por acordo", + "kelishuv bo‘yicha", + "келіÑ�ім бойынша", + ], + [ + "Offer a draw", + "Предложить ничью", + "Proposer nulle", + "Remis anbieten", + "Ofrecer tablas", + "Proponi patta", + "Propor empate", + "Durang taklif qilish", + "Тең ойын Ò±Ñ�ыну", + ], + [ + "Maia answers a draw offer with Stockfish's help: none is installed", + "Maia отвечает на предложение ничьей Ñ� помощью Stockfish, а он не уÑ�тановлен", + "Maia répond à une proposition de nulle avec l’aide de Stockfish, qui n’est pas installé", + "Maia beantwortet Remisangebote mit Hilfe von Stockfish, der nicht installiert ist", + "Maia responde a las tablas con ayuda de Stockfish, que no está instalado", + "Maia risponde alla patta con l’aiuto di Stockfish, che non è installato", + "A Maia responde ao empate com a ajuda do Stockfish, que não está instalado", + "Maia durang taklifiga Stockfish yordamida javob beradi, u o‘rnatilmagan", + "Maia тең ойын Ò±Ñ�ыныÑ�ына Stockfish көмегімен жауап береді, ол орнатылмаған", + ], + [ + "Maia declined; offer again after two of her moves", + "Maia отказалаÑ�ÑŒ; Ñ�нова можно предложить через два её хода", + "Maia a refusé ; reproposez après deux de ses coups", + "Maia hat abgelehnt; nach zwei ihrer Züge wieder anbieten", + "Maia lo rechazó; ofrece de nuevo tras dos de sus jugadas", + "Maia ha rifiutato; riproponi dopo due sue mosse", + "A Maia recusou; ofereça de novo após dois lances dela", + "Maia rad etdi; uning ikki yurishidan keyin yana taklif qiling", + "Maia баÑ� тартты; оның екі жүріÑ�інен кейін қайта Ò±Ñ�ыныңыз", + ], + [ + "Maia accepts when her position is no better and has settled", + "Maia Ñ�оглашаетÑ�Ñ�, когда её позициÑ� не лучше и уже не менÑ�етÑ�Ñ�", + "Maia accepte quand sa position n’est pas meilleure et s’est stabilisée", + "Maia nimmt an, wenn ihre Stellung nicht besser ist und sich beruhigt hat", + "Maia acepta cuando su posición no es mejor y se ha estabilizado", + "Maia accetta quando la sua posizione non è migliore e si è stabilizzata", + "A Maia aceita quando a posição dela não é melhor e se estabilizou", + "Maia pozitsiyasi yaxshi bo‘lmasa va o‘zgarmay qolsa, rozi bo‘ladi", + "Maia позициÑ�Ñ�Ñ‹ жақÑ�Ñ‹ болмаÑ�а және өзгермей қалÑ�а, келіÑ�еді", + ], + [ + "Maia declines the draw", + "Maia отказываетÑ�Ñ� от ничьей", + "Maia refuse la nulle", + "Maia lehnt das Remis ab", + "Maia rechaza las tablas", + "Maia rifiuta la patta", + "A Maia recusa o empate", + "Maia durangdan bosh tortadi", + "Maia тең ойыннан баÑ� тартады", + ], + [ + "Opponent — Rodent {elo}", + "Соперник — Rodent {elo}", + "Adversaire — Rodent {elo}", + "Gegner — Rodent {elo}", + "Rival — Rodent {elo}", + "Avversario — Rodent {elo}", + "Adversário — Rodent {elo}", + "Raqib — Rodent {elo}", + "ҚарÑ�ылаÑ� — Rodent {elo}", + ], + [ + "not yet for macOS", + "пока нет длÑ� macOS", + "pas encore pour macOS", + "noch nicht für macOS", + "aún no para macOS", + "non ancora per macOS", + "ainda não para macOS", + "macOS uchun hali yo‘q", + "macOS үшін әзірге жоқ", + ], + [ + "not yet for this system", + "пока нет длÑ� Ñ�той Ñ�иÑ�темы", + "pas encore pour ce système", + "noch nicht für dieses System", + "aún no para este sistema", + "non ancora per questo sistema", + "ainda não para este sistema", + "bu tizim uchun hali yo‘q", + "бұл жүйе үшін әзірге жоқ", + ], + [ + "Rodent is not available for this system yet. When it is, it will be here.", + "ДлÑ� Ñ�той Ñ�иÑ�темы Rodent пока нет. Когда поÑ�витÑ�Ñ�, он будет здеÑ�ÑŒ.", + "Rodent n’est pas encore disponible pour ce système. Dès qu’il le sera, il sera ici.", + "Rodent gibt es für dieses System noch nicht. Sobald es ihn gibt, ist er hier.", + "Rodent aún no está disponible para este sistema. Cuando lo esté, estará aquí.", + "Rodent non è ancora disponibile per questo sistema. Quando lo sarà, sarà qui.", + "O Rodent ainda não está disponível para este sistema. Quando estiver, estará aqui.", + "Bu tizim uchun Rodent hali yo‘q. Paydo bo‘lsa, shu yerda bo‘ladi.", + "Бұл жүйе үшін Rodent әзірге жоқ. Пайда болғанда, оÑ�ында болады.", + ], + [ + "Maia plays up to {elo}: the strength is lowered to {elo}.", + "Maia играет до {elo} — Ñ�ила Ñ�нижена до {elo}.", + "Maia joue jusqu’à {elo} : la force est ramenée à {elo}.", + "Maia spielt bis {elo}: die Stärke ist auf {elo} gesenkt.", + "Maia juega hasta {elo}: la fuerza baja a {elo}.", + "Maia gioca fino a {elo}: la forza è ridotta a {elo}.", + "A Maia joga até {elo}: a força foi reduzida para {elo}.", + "Maia {elo} gacha o‘ynaydi: kuch {elo} ga tushirildi.", + "Maia {elo} дейін ойнайды: күш {elo} дейін төмендетілді.", + ], + [ + "Weaker than {elo} plays Maia.", + "Слабее {elo} играет Maia.", + "En dessous de {elo}, c’est Maia.", + "Schwächer als {elo} spielt Maia.", + "Por debajo de {elo} juega Maia.", + "Sotto {elo} gioca Maia.", + "Abaixo de {elo} joga a Maia.", + "{elo} dan kuchsizroq Maia o‘ynaydi.", + "{elo}-ден әлÑ�іздеу Maia ойнайды.", + ], + [ + "Maia can play here too: choose her if you want human mistakes.", + "ЗдеÑ�ÑŒ может играть и Maia — выберите её, еÑ�ли хотите человечных ошибок.", + "Maia peut aussi jouer ici : choisissez-la pour des erreurs humaines.", + "Hier kann auch Maia spielen: wählen Sie sie für menschliche Fehler.", + "Aquí también puede jugar Maia: elígela si quieres errores humanos.", + "Qui può giocare anche Maia: sceglila per errori umani.", + "Aqui também pode jogar a Maia: escolha-a para erros humanos.", + "Bu yerda Maia ham o‘ynay oladi: insoniy xatolar istasangiz, uni tanlang.", + "Мұнда Maia да ойнай алады: адами қателер керек болÑ�а, оны таңдаңыз.", + ], + [ + "Measured strength, on the Lichess blitz scale.", + "ИзмереннаÑ� Ñ�ила, по шкале блица Lichess.", + "Force mesurée, sur l’échelle du blitz Lichess.", + "Gemessene Spielstärke, auf der Lichess-Blitz-Skala.", + "Fuerza medida, en la escala de blitz de Lichess.", + "Forza misurata, sulla scala del blitz di Lichess.", + "Força medida, na escala de blitz do Lichess.", + "O‘lchangan kuch, Lichess blits shkalasi bo‘yicha.", + "Өлшенген күш, Lichess блиц шкалаÑ�Ñ‹ бойынша.", + ], + [ + "Like a human", + "Как человек", + "Comme un humain", + "Wie ein Mensch", + "Como una persona", + "Come un umano", + "Como um humano", + "Odamdek", + "Ð�дам Ñ�иÑ�қты", + ], + [ + "Style", + "Стиль", + "Style", + "Stil", + "Estilo", + "Stile", + "Estilo", + "Uslub", + "Стиль", + ], + [ + "As a player", + "Как игрок", + "Comme un joueur", + "Wie ein Spieler", + "Como un jugador", + "Come un giocatore", + "Como um jogador", + "O‘yinchidek", + "Ойыншы Ñ�иÑ�қты", + ], + [ + "The style is chosen for Rodent", + "Стиль выбираетÑ�Ñ� у Rodent", + "Le style se choisit pour Rodent", + "Der Stil wird für Rodent gewählt", + "El estilo se elige para Rodent", + "Lo stile si sceglie per Rodent", + "O estilo é escolhido para o Rodent", + "Uslub Rodent uchun tanlanadi", + "Стиль Rodent үшін таңдалады", + ], + [ + "Maia does not pick a style: she plays like people of her rating.", + "Maia не выбирает Ñ�тиль: она играет, как люди её рейтинга.", + "Maia ne choisit pas de style : elle joue comme les gens de son niveau.", + "Maia wählt keinen Stil: Sie spielt wie Menschen ihrer Wertung.", + "Maia no elige estilo: juega como la gente de su nivel.", + "Maia non sceglie uno stile: gioca come le persone del suo livello.", + "A Maia não escolhe estilo: joga como as pessoas do nível dela.", + "Maia uslub tanlamaydi: u o‘z reytingidagi odamlardek o‘ynaydi.", + "Maia Ñ�тиль таңдамайды: ол өз рейтингіндегі адамдар Ñ�иÑ�қты ойнайды.", + ], + [ + "Balanced", + "СбаланÑ�ированный", + "Équilibré", + "Ausgewogen", + "Equilibrado", + "Equilibrato", + "Equilibrado", + "Muvozanatli", + "Теңгерімді", + ], + [ + "Attacking", + "Ð�такующий", + "Offensif", + "Angriffslustig", + "Atacante", + "Offensivo", + "Atacante", + "Hujumkor", + "Шабуылшыл", + ], + [ + "Chaotic", + "Хаотичный", + "Chaotique", + "Chaotisch", + "Caótico", + "Caotico", + "Caótico", + "Tartibsiz", + "РетÑ�із", + ], + [ + "Restricting", + "Сковывающий", + "Étouffant", + "Einengend", + "Restrictivo", + "Soffocante", + "Restritivo", + "Siqib qo‘yuvchi", + "ҚыÑ�ып таÑ�тайтын", + ], + [ + "Tal", "Таль", "Tal", "Tal", "Tal", "Tal", "Tal", "Tal", "Таль", + ], + [ + "Tal (network)", + "Таль (Ñ�еть)", + "Tal (réseau)", + "Tal (Netz)", + "Tal (red)", + "Tal (rete)", + "Tal (rede)", + "Tal (tarmoq)", + "Таль (желі)", + ], + [ + "Even, all-round play with no bias.", + "РовнаÑ� универÑ�альнаÑ� игра, без перекоÑ�ов.", + "Jeu régulier et polyvalent, sans parti pris.", + "Gleichmäßiges, vielseitiges Spiel ohne Vorlieben.", + "Juego regular y versátil, sin sesgos.", + "Gioco regolare e completo, senza sbilanciamenti.", + "Jogo regular e versátil, sem desvios.", + "Bir tekis, har tomonlama o‘yin, og‘ishsiz.", + "Біркелкі, жан-жақты ойын, бұрмалануÑ�ыз.", + ], + [ + "Active pieces and attack, sound pawn structure.", + "Ð�ктивные фигуры и атака, крепкаÑ� пешечнаÑ� Ñ�труктура.", + "Pièces actives et attaque, structure de pions saine.", + "Aktive Figuren und Angriff, gesunde Bauernstruktur.", + "Piezas activas y ataque, estructura de peones sólida.", + "Pezzi attivi e attacco, struttura pedonale sana.", + "Peças ativas e ataque, estrutura de peões sólida.", + "Faol donalar va hujum, mustahkam piyoda tuzilmasi.", + "БелÑ�енді фигуралар мен шабуыл, мықты пешка құрылымы.", + ], + [ + "Aggressive, tricky openings, careless with pawns.", + "Ð�греÑ�Ñ�иÑ� и хитрые дебюты, пешки не бережёт.", + "Agressif, ouvertures pièges, peu soucieux des pions.", + "Aggressiv, trickreiche Eröffnungen, sorglos mit Bauern.", + "Agresivo, aperturas tramposas, descuidado con los peones.", + "Aggressivo, aperture insidiose, poco attento ai pedoni.", + "Agressivo, aberturas traiçoeiras, descuidado com os peões.", + "Tajovuzkor, ayyorona debyutlar, piyodalarni ayamaydi.", + "Ð�греÑ�Ñ�ивті, айлалы дебюттер, пешкаларды аÑ�майды.", + ], + [ + "Closed positions, cramping the opponent, old openings.", + "Закрытые позиции, Ñ�теÑ�нение Ñ�оперника, Ñ�тарые дебюты.", + "Positions fermées, étouffer l’adversaire, ouvertures anciennes.", + "Geschlossene Stellungen, den Gegner einengen, alte Eröffnungen.", + "Posiciones cerradas, ahogar al rival, aperturas antiguas.", + "Posizioni chiuse, soffocare l’avversario, aperture antiche.", + "Posições fechadas, sufocar o adversário, aberturas antigas.", + "Yopiq pozitsiyalar, raqibni siqish, eski debyutlar.", + "Жабық позициÑ�лар, қарÑ�ылаÑ�ты қыÑ�у, еÑ�кі дебюттер.", + ], + [ + "Hand-written evaluation, no neural network.", + "Оценка, напиÑ�аннаÑ� вручную, без нейроÑ�ети.", + "Évaluation écrite à la main, sans réseau de neurones.", + "Handgeschriebene Bewertung, kein neuronales Netz.", + "Evaluación escrita a mano, sin red neuronal.", + "Valutazione scritta a mano, senza rete neurale.", + "Avaliação escrita à mão, sem rede neural.", + "Qo‘lda yozilgan baholash, neyrotarmoqsiz.", + "Қолмен жазылған бағалау, нейрожеліÑ�із.", + ], + [ + "Attacking style tuned on Tal's games.", + "Ð�такующий Ñ�тиль, наÑ�троенный по партиÑ�м ТалÑ�.", + "Style offensif réglé sur les parties de Tal.", + "Angriffsstil, abgestimmt auf Tals Partien.", + "Estilo atacante ajustado con las partidas de Tal.", + "Stile offensivo tarato sulle partite di Tal.", + "Estilo atacante ajustado nas partidas de Tal.", + "Tal o‘yinlari asosida sozlangan hujumkor uslub.", + "Таль ойындары бойынша бапталған шабуыл Ñ�тилі.", + ], + [ + "A neural network trained on Tal's games.", + "Ð�ейроÑ�еть, обученнаÑ� на партиÑ�Ñ… ТалÑ�.", + "Un réseau de neurones entraîné sur les parties de Tal.", + "Ein neuronales Netz, trainiert mit Tals Partien.", + "Una red neuronal entrenada con las partidas de Tal.", + "Una rete neurale addestrata sulle partite di Tal.", + "Uma rede neural treinada nas partidas de Tal.", + "Tal o‘yinlarida o‘qitilgan neyrotarmoq.", + "Таль ойындарында оқытылған нейрожелі.", + ], + [ + "Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).", + "Rodent V Ñ�качиваетÑ�Ñ� один раз ({mb} МБ, Ñ� github.com — файл Ñ�амих авторов).", + "Rodent V est téléchargé une seule fois ({mb} Mo, depuis github.com, le fichier des auteurs).", + "Rodent V wird einmalig heruntergeladen ({mb} MB, von github.com, die Datei der Autoren).", + "Rodent V se descarga una sola vez ({mb} MB, desde github.com, el archivo de los autores).", + "Rodent V si scarica una sola volta ({mb} MB, da github.com, il file degli autori).", + "O Rodent V é baixado uma única vez ({mb} MB, de github.com, o arquivo dos autores).", + "Rodent V bir marta yuklab olinadi ({mb} MB, github.com dan — mualliflarning o‘z fayli).", + "Rodent V бір рет жүктеледі ({mb} МБ, github.com Ñ�айтынан — авторлардың өз файлы).", + ], + [ + "Unpacking…", + "РаÑ�паковка…", + "Décompression…", + "Entpacken…", + "Descomprimiendo…", + "Estrazione…", + "Descompactando…", + "Ochilmoqda…", + "Ð�шылуда…", + ], + [ + "Could not download Rodent: {error}", + "Ð�е удалоÑ�ÑŒ Ñ�качать Rodent: {error}", + "Impossible de télécharger Rodent : {error}", + "Rodent konnte nicht heruntergeladen werden: {error}", + "No se pudo descargar Rodent: {error}", + "Impossibile scaricare Rodent: {error}", + "Não foi possível baixar o Rodent: {error}", + "Rodent’ni yuklab bo‘lmadi: {error}", + "Rodent жүктелмеді: {error}", + ], + [ + "it does not start on this computer", + "он не запуÑ�каетÑ�Ñ� на Ñ�том компьютере", + "il ne démarre pas sur cet ordinateur", + "er startet auf diesem Computer nicht", + "no arranca en este ordenador", + "non si avvia su questo computer", + "ele não inicia neste computador", + "u bu kompyuterda ishga tushmaydi", + "ол бұл компьютерде Ñ–Ñ�ке қоÑ�ылмайды", + ], + [ + "Rodent did not start: {e}", + "Rodent не запуÑ�тилÑ�Ñ�: {e}", + "Rodent n’a pas démarré : {e}", + "Rodent ist nicht gestartet: {e}", + "Rodent no se inició: {e}", + "Rodent non si è avviato: {e}", + "O Rodent não iniciou: {e}", + "Rodent ishga tushmadi: {e}", + "Rodent Ñ–Ñ�ке қоÑ�ылмады: {e}", + ], + [ + "time is up, but Rodent cannot checkmate", + "времÑ� вышло, но Rodent нечем поÑ�тавить мат", + "le temps est écoulé, mais Rodent ne peut pas mater", + "die Zeit ist um, aber Rodent kann nicht mattsetzen", + "se acabó el tiempo, pero Rodent no puede dar mate", + "tempo scaduto, ma Rodent non può dare matto", + "o tempo acabou, mas o Rodent não pode dar mate", + "vaqt tugadi, lekin Rodent mot qila olmaydi", + "уақыт бітті, бірақ Rodent мат қоÑ� алмайды", + ], + [ + "Rodent's time is up, but you cannot checkmate", + "у Rodent вышло времÑ�, но вам нечем поÑ�тавить мат", + "le temps de Rodent est écoulé, mais vous ne pouvez pas mater", + "Die Zeit von Rodent ist um, aber Sie können nicht mattsetzen", + "a Rodent se le acabó el tiempo, pero no puedes dar mate", + "il tempo di Rodent è scaduto, ma non puoi dare matto", + "o tempo do Rodent acabou, mas você não pode dar mate", + "Rodent ning vaqti tugadi, lekin siz mot qila olmaysiz", + "Rodent-тің уақыты бітті, бірақ Ñ�із мат қоÑ� алмайÑ�ыз", + ], + [ + "Rodent resigned", + "Rodent Ñ�далÑ�Ñ�", + "Rodent a abandonné", + "Rodent hat aufgegeben", + "Rodent se rindió", + "Rodent ha abbandonato", + "O Rodent desistiu", + "Rodent taslim bo‘ldi", + "Rodent берілді", + ], + [ + "Rodent resigns", + "Rodent Ñ�даётÑ�Ñ�", + "Rodent abandonne", + "Rodent gibt auf", + "Rodent se rinde", + "Rodent abbandona", + "O Rodent desiste", + "Rodent taslim bo‘lmoqda", + "Rodent беріледі", + ], + [ + "Its position is lost. Accept the win, or play to the end?", + "Его позициÑ� проиграна. ПринÑ�ть победу или играть до конца?", + "Sa position est perdue. Accepter la victoire ou jouer jusqu’au bout ?", + "Seine Stellung ist verloren. Sieg annehmen oder zu Ende spielen?", + "Su posición está perdida. ¿Aceptar la victoria o jugar hasta el final?", + "La sua posizione è persa. Accettare la vittoria o giocare fino in fondo?", + "A posição dele está perdida. Aceitar a vitória ou jogar até o fim?", + "Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki oxirigacha o‘ynaysizmi?", + "Оның позициÑ�Ñ�Ñ‹ ұтылды. ЖеңіÑ�ті қабылдайÑ�ыз ба, әлде Ñ�оңына дейін ойнайÑ�ыз ба?", + ], + [ + "Rodent plays on and will not offer again in this game", + "Rodent играет дальше и в Ñ�той партии больше не предложит", + "Rodent continue et ne proposera plus dans cette partie", + "Rodent spielt weiter und bietet in dieser Partie nicht mehr an", + "Rodent sigue y no volverá a ofrecer en esta partida", + "Rodent continua e non lo proporrà più in questa partita", + "O Rodent continua e não oferecerá de novo nesta partida", + "Rodent davom etadi va bu o‘yinda boshqa taklif qilmaydi", + "Rodent жалғаÑ�тырады және бұл ойында енді Ò±Ñ�ынбайды", + ], + [ + "Continued from {game}, after {move}. From here on, a game against {name}.", + "Продолжение партии {game} поÑ�ле {move}. Дальше — партиÑ� против {name}.", + "Suite de {game}, après {move}. À partir d’ici, une partie contre {name}.", + "Fortsetzung von {game} nach {move}. Ab hier eine Partie gegen {name}.", + "Continuación de {game} tras {move}. Desde aquí, una partida contra {name}.", + "Seguito di {game} dopo {move}. Da qui, una partita contro {name}.", + "Continuação de {game} após {move}. Daqui em diante, uma partida contra {name}.", + "{game} davomi, {move} dan keyin. Bundan buyon — {name} ga qarshi o‘yin.", + "{game} жалғаÑ�Ñ‹, {move} кейін. ОÑ�Ñ‹ жерден — {name} қарÑ�Ñ‹ ойын.", + ], + [ + "Continued after {move}. From here on, a game against {name}.", + "Продолжение поÑ�ле {move}. Дальше — партиÑ� против {name}.", + "Suite après {move}. À partir d’ici, une partie contre {name}.", + "Fortsetzung nach {move}. Ab hier eine Partie gegen {name}.", + "Continuación tras {move}. Desde aquí, una partida contra {name}.", + "Seguito dopo {move}. Da qui, una partita contro {name}.", + "Continuação após {move}. Daqui em diante, uma partida contra {name}.", + "{move} dan keyin davomi. Bundan buyon — {name} ga qarshi o‘yin.", + "{move} кейінгі жалғаÑ�Ñ‹. ОÑ�Ñ‹ жерден — {name} қарÑ�Ñ‹ ойын.", + ], + [ + "Continued from {game}. From here on, a game against {name}.", + "Продолжение партии {game}. Дальше — партиÑ� против {name}.", + "Suite de {game}. À partir d’ici, une partie contre {name}.", + "Fortsetzung von {game}. Ab hier eine Partie gegen {name}.", + "Continuación de {game}. Desde aquí, una partida contra {name}.", + "Seguito di {game}. Da qui, una partita contro {name}.", + "Continuação de {game}. Daqui em diante, uma partida contra {name}.", + "{game} davomi. Bundan buyon — {name} ga qarshi o‘yin.", + "{game} жалғаÑ�Ñ‹. ОÑ�Ñ‹ жерден — {name} қарÑ�Ñ‹ ойын.", + ], + [ + "From here on, a game against {name}.", + "Дальше — партиÑ� против {name}.", + "À partir d’ici, une partie contre {name}.", + "Ab hier eine Partie gegen {name}.", + "Desde aquí, una partida contra {name}.", + "Da qui, una partita contro {name}.", + "Daqui em diante, uma partida contra {name}.", + "Bundan buyon — {name} ga qarshi o‘yin.", + "ОÑ�Ñ‹ жерден — {name} қарÑ�Ñ‹ ойын.", + ], + [ + "Rodent answers a draw offer with Stockfish's help: none is installed", + "Rodent отвечает на предложение ничьей Ñ� помощью Stockfish, а он не уÑ�тановлен", + "Rodent répond à une proposition de nulle avec l’aide de Stockfish, qui n’est pas installé", + "Rodent beantwortet Remisangebote mit Hilfe von Stockfish, der nicht installiert ist", + "Rodent responde a las tablas con ayuda de Stockfish, que no está instalado", + "Rodent risponde alla patta con l’aiuto di Stockfish, che non è installato", + "O Rodent responde ao empate com a ajuda do Stockfish, que não está instalado", + "Rodent durang taklifiga Stockfish yordamida javob beradi, u o‘rnatilmagan", + "Rodent тең ойын Ò±Ñ�ыныÑ�ына Stockfish көмегімен жауап береді, ол орнатылмаған", + ], + [ + "Rodent declined; offer again after two of its moves", + "Rodent отказалÑ�Ñ�; Ñ�нова можно предложить через два его хода", + "Rodent a refusé ; reproposez après deux de ses coups", + "Rodent hat abgelehnt; nach zwei seiner Züge wieder anbieten", + "Rodent lo rechazó; ofrece de nuevo tras dos de sus jugadas", + "Rodent ha rifiutato; riproponi dopo due sue mosse", + "O Rodent recusou; ofereça de novo após dois lances dele", + "Rodent rad etdi; uning ikki yurishidan keyin yana taklif qiling", + "Rodent баÑ� тартты; оның екі жүріÑ�інен кейін қайта Ò±Ñ�ыныңыз", + ], + [ + "Rodent accepts when its position is no better and has settled", + "Rodent Ñ�оглашаетÑ�Ñ�, когда его позициÑ� не лучше и уже не менÑ�етÑ�Ñ�", + "Rodent accepte quand sa position n’est pas meilleure et s’est stabilisée", + "Rodent nimmt an, wenn seine Stellung nicht besser ist und sich beruhigt hat", + "Rodent acepta cuando su posición no es mejor y se ha estabilizado", + "Rodent accetta quando la sua posizione non è migliore e si è stabilizzata", + "O Rodent aceita quando a posição dele não é melhor e se estabilizou", + "Rodent pozitsiyasi yaxshi bo‘lmasa va o‘zgarmay qolsa, rozi bo‘ladi", + "Rodent позициÑ�Ñ�Ñ‹ жақÑ�Ñ‹ болмаÑ�а және өзгермей қалÑ�а, келіÑ�еді", + ], + [ + "Rodent declines the draw", + "Rodent отказываетÑ�Ñ� от ничьей", + "Rodent refuse la nulle", + "Rodent lehnt das Remis ab", + "Rodent rechaza las tablas", + "Rodent rifiuta la patta", + "O Rodent recusa o empate", + "Rodent durangdan bosh tortadi", + "Rodent тең ойыннан баÑ� тартады", + ], + [ + "plays like a human", + "играет как человек", + "joue comme un humain", + "spielt wie ein Mensch", + "juega como una persona", + "gioca come un umano", + "joga como um humano", + "odamdek o‘ynaydi", + "адам Ñ�иÑ�қты ойнайды", + ], + [ + "strong, with a style", + "Ñ�ильный, Ñ�о Ñ�тилем", + "fort, avec un style", + "stark, mit Stil", + "fuerte, con estilo", + "forte, con uno stile", + "forte, com estilo", + "kuchli, uslubli", + "күшті, Ñ�тилімен", + ], + [ + "Stronger than {elo} plays Rodent V, from {min} on: Maia does not play that strong.", + "Сильнее {elo} играет Rodent V, от {min}: Maia так Ñ�ильно не играет.", + "Au-delà de {elo}, c’est Rodent V, à partir de {min} : Maia ne joue pas aussi fort.", + "Stärker als {elo} spielt Rodent V, ab {min}: so stark spielt Maia nicht.", + "Por encima de {elo} juega Rodent V, desde {min}: Maia no juega tan fuerte.", + "Oltre {elo} gioca Rodent V, da {min}: Maia non gioca così forte.", + "Acima de {elo} joga o Rodent V, a partir de {min}: a Maia não joga tão forte.", + "{elo} dan kuchliroq Rodent V o‘ynaydi, {min} dan: Maia bunchalik kuchli o‘ynamaydi.", + "{elo}-ден күштірек Rodent V ойнайды, {min} баÑ�тап: Maia мұндай күшті ойнамайды.", + ], + [ + "Left: you {you} · Rodent {maia}", + "ОÑ�талоÑ�ÑŒ: вы {you} · Rodent {maia}", + "Restant : vous {you} · Rodent {maia}", + "Verbleibend: Sie {you} · Rodent {maia}", + "Queda: tú {you} · Rodent {maia}", + "Rimasto: tu {you} · Rodent {maia}", + "Restante: você {you} · Rodent {maia}", + "Qoldi: siz {you} · Rodent {maia}", + "Қалды: Ñ�із {you} · Rodent {maia}", + ], + [ + "it stopped while playing", + "он оÑ�тановилÑ�Ñ� во времÑ� игры", + "il s’est arrêté pendant la partie", + "er hat während der Partie aufgehört", + "se detuvo durante la partida", + "si è fermato durante la partita", + "ele parou durante a partida", + "u o‘yin paytida to‘xtadi", + "ол ойын кезінде тоқтады", + ], + [ + "A game against the computer: Maia, who plays like a human, or Rodent, strong and with a style (Ctrl+G)", + "ПартиÑ� Ñ� компьютером: Maia играет как человек, Rodent — Ñ�ильно и Ñ�о Ñ�тилем (Ctrl+G)", + "Une partie contre l’ordinateur : Maia joue comme un humain, Rodent fort et avec un style (Ctrl+G)", + "Eine Partie gegen den Computer: Maia spielt wie ein Mensch, Rodent stark und mit Stil (Strg+G)", + "Una partida contra el ordenador: Maia juega como una persona, Rodent fuerte y con estilo (Ctrl+G)", + "Una partita contro il computer: Maia gioca come un umano, Rodent forte e con uno stile (Ctrl+G)", + "Uma partida contra o computador: a Maia joga como um humano, o Rodent forte e com estilo (Ctrl+G)", + "Kompyuter bilan o‘yin: Maia odamdek o‘ynaydi, Rodent — kuchli va uslubli (Ctrl+G)", + "Компьютермен ойын: Maia адам Ñ�иÑ�қты ойнайды, Rodent — күшті және Ñ�тилімен (Ctrl+G)", + ], + [ + "A game against the computer from this position", + "ПартиÑ� Ñ� компьютером Ñ� Ñ�той позиции", + "Une partie contre l’ordinateur depuis cette position", + "Eine Partie gegen den Computer ab dieser Stellung", + "Una partida contra el ordenador desde esta posición", + "Una partita contro il computer da questa posizione", + "Uma partida contra o computador a partir desta posição", + "Shu pozitsiyadan kompyuter bilan o‘yin", + "ОÑ�Ñ‹ позициÑ�дан компьютермен ойын", + ], + [ + "Stronger than {elo} plays Rodent V: Maia does not play that strong.", + "Сильнее {elo} играет Rodent V: Maia так Ñ�ильно не играет.", + "Au-delà de {elo}, c’est Rodent V : Maia ne joue pas aussi fort.", + "Stärker als {elo} spielt Rodent V: so stark spielt Maia nicht.", + "Por encima de {elo} juega Rodent V: Maia no juega tan fuerte.", + "Oltre {elo} gioca Rodent V: Maia non gioca così forte.", + "Acima de {elo} joga o Rodent V: a Maia não joga tão forte.", + "{elo} dan kuchliroq Rodent V o‘ynaydi: Maia bunchalik kuchli o‘ynamaydi.", + "{elo}-ден күштірек Rodent V ойнайды: Maia мұндай күшті ойнамайды.", + ], + [ + "In this style Rodent V plays from {min} to {max}: the strength is set to {elo}.", + "Ð’ Ñ�том Ñ�тиле Rodent V играет от {min} до {max} — Ñ�ила {elo}.", + "Dans ce style, Rodent V joue de {min} à {max} : la force est réglée à {elo}.", + "In diesem Stil spielt Rodent V von {min} bis {max}: die Stärke ist auf {elo} gesetzt.", + "En este estilo Rodent V juega de {min} a {max}: la fuerza queda en {elo}.", + "In questo stile Rodent V gioca da {min} a {max}: la forza è impostata a {elo}.", + "Neste estilo o Rodent V joga de {min} a {max}: a força fica em {elo}.", + "Bu uslubda Rodent V {min} dan {max} gacha o‘ynaydi: kuch {elo}.", + "Бұл Ñ�тильде Rodent V {min} баÑ�тап {max} дейін ойнайды: күш {elo}.", + ], + [ + "Games against the computer", + "Партии Ñ� компьютером", + "Parties contre l’ordinateur", + "Partien gegen den Computer", + "Partidas contra el ordenador", + "Partite contro il computer", + "Partidas contra o computador", + "Kompyuter bilan o‘yinlar", + "Компьютермен ойындар", + ], + [ + "{name} — games against the computer", + "{name} — партии Ñ� компьютером", + "{name} — parties contre l’ordinateur", + "{name} — Partien gegen den Computer", + "{name} — partidas contra el ordenador", + "{name} — partite contro il computer", + "{name} — partidas contra o computador", + "{name} — kompyuter bilan o‘yinlar", + "{name} — компьютермен ойындар", + ], + [ + "Could not write to «{db}»: {reason}", + "Ð�е удалоÑ�ÑŒ запиÑ�ать в «{db}»: {reason}", + "Impossible d’écrire dans « {db} » : {reason}", + "Konnte nicht in „{db}“ schreiben: {reason}", + "No se pudo escribir en «{db}»: {reason}", + "Impossibile scrivere in «{db}»: {reason}", + "Não foi possível gravar em «{db}»: {reason}", + "«{db}» ga yozib bo‘lmadi: {reason}", + "«{db}» базаÑ�ына жазу мүмкін болмады: {reason}", + ], + [ + "Database «{db}» created: your games will be written there", + "Создана база «{db}» — Ñ�юда будут запиÑ�ыватьÑ�Ñ� ваши партии", + "Base « {db} » créée : vos parties y seront enregistrées", + "Datenbank „{db}“ angelegt: Ihre Partien werden dort gespeichert", + "Se creó la base «{db}»: tus partidas se guardarán allí", + "Creato il database «{db}»: le tue partite saranno salvate lì", + "Base «{db}» criada: as suas partidas serão gravadas nela", + "«{db}» bazasi yaratildi: o‘yinlaringiz shu yerga yoziladi", + "«{db}» базаÑ�Ñ‹ құрылды: ойындарыңыз оÑ�ында жазылады", + ], + [ + "The database in the library, this game selected", + "База в библиотеке, Ñ�та партиÑ� выделена", + "La base dans la bibliothèque, cette partie sélectionnée", + "Die Datenbank in der Bibliothek, diese Partie ausgewählt", + "La base en la biblioteca, con esta partida seleccionada", + "Il database nella libreria, con questa partita selezionata", + "A base na biblioteca, com esta partida selecionada", + "Kutubxonadagi baza, bu o‘yin belgilangan", + "Кітапханадағы база, бұл ойын белгіленген", + ], + [ + "Games against the computer are written here", + "Сюда запиÑ�ываютÑ�Ñ� партии Ñ� компьютером", + "Les parties contre l’ordinateur sont enregistrées ici", + "Partien gegen den Computer werden hier gespeichert", + "Aquí se guardan las partidas contra el ordenador", + "Qui vengono salvate le partite contro il computer", + "Aqui são gravadas as partidas contra o computador", + "Kompyuter bilan o‘yinlar shu yerga yoziladi", + "Компьютермен ойындар оÑ�ында жазылады", + ], + [ + "{name}'s games against the computer are written here", + "Сюда запиÑ�ываютÑ�Ñ� партии игрока {name} Ñ� компьютером", + "Les parties de {name} contre l’ordinateur sont enregistrées ici", + "Die Partien von {name} gegen den Computer werden hier gespeichert", + "Aquí se guardan las partidas de {name} contra el ordenador", + "Qui vengono salvate le partite di {name} contro il computer", + "Aqui são gravadas as partidas de {name} contra o computador", + "{name} ning kompyuter bilan o‘yinlari shu yerga yoziladi", + "{name} ойыншыÑ�ының компьютермен ойындары оÑ�ында жазылады", + ], + [ + "Write games against the computer to the player's database", + "ЗапиÑ�ывать партии Ñ� компьютером в базу игрока", + "Enregistrer les parties contre l’ordinateur dans la base du joueur", + "Partien gegen den Computer in die Datenbank des Spielers schreiben", + "Guardar las partidas contra el ordenador en la base del jugador", + "Salvare le partite contro il computer nel database del giocatore", + "Gravar as partidas contra o computador na base do jogador", + "Kompyuter bilan o‘yinlarni o‘yinchi bazasiga yozish", + "Компьютермен ойындарды ойыншы базаÑ�ына жазу", + ], + [ + "Games are not written by themselves (Settings → Interface → Your databases).", + "Партии Ñ�ами не запиÑ�ываютÑ�Ñ� (Ð�аÑ�тройки → ИнтерфейÑ� → Свои базы).", + "Les parties ne sont pas enregistrées d’elles-mêmes (Réglages → Interface → Vos bases).", + "Partien werden nicht von selbst gespeichert (Einstellungen → Oberfläche → Eigene Datenbanken).", + "Las partidas no se guardan solas (Ajustes → Interfaz → Tus bases).", + "Le partite non vengono salvate da sole (Impostazioni → Interfaccia → I tuoi database).", + "As partidas não são gravadas sozinhas (Definições → Interface → As suas bases).", + "O‘yinlar o‘zi yozilmaydi (Sozlamalar → Interfeys → Sizning bazalaringiz).", + "Ойындар өзі жазылмайды (Баптаулар → ИнтерфейÑ� → Өз базаларыңыз).", + ], + [ + "Without a name games go to «{db}». Enter a name to have a database of your own.", + "Без имени партии идут в «{db}». Впишите имÑ� — заведём вашу базу.", + "Sans nom, les parties vont dans « {db} ». Saisissez un nom pour avoir votre propre base.", + "Ohne Namen gehen die Partien in „{db}“. Geben Sie einen Namen ein, um eine eigene Datenbank zu bekommen.", + "Sin nombre, las partidas van a «{db}». Escribe un nombre para tener tu propia base.", + "Senza nome le partite vanno in «{db}». Inserisci un nome per avere un database tuo.", + "Sem nome, as partidas vão para «{db}». Escreva um nome para ter a sua própria base.", + "Ismsiz o‘yinlar «{db}» ga tushadi. O‘z bazangiz bo‘lishi uchun ismingizni yozing.", + "Ð�Ñ‚Ñ�ыз ойындар «{db}» базаÑ�ына түÑ�еді. Өз базаңыз болуы үшін атыңызды жазыңыз.", + ], + [ + "Games will be written to a new database «{db}».", + "Партии будут запиÑ�ыватьÑ�Ñ� в новую базу «{db}».", + "Les parties seront enregistrées dans une nouvelle base « {db} ».", + "Die Partien werden in eine neue Datenbank „{db}“ gespeichert.", + "Las partidas se guardarán en una base nueva «{db}».", + "Le partite saranno salvate in un nuovo database «{db}».", + "As partidas serão gravadas numa nova base «{db}».", + "O‘yinlar yangi «{db}» bazasiga yoziladi.", + "Ойындар жаңа «{db}» базаÑ�ына жазылады.", + ], + [ + "Games are written to «{db}» · {n}", + "Партии запиÑ�ываютÑ�Ñ� в «{db}» · {n}", + "Les parties sont enregistrées dans « {db} » · {n}", + "Partien werden in „{db}“ gespeichert · {n}", + "Las partidas se guardan en «{db}» · {n}", + "Le partite vengono salvate in «{db}» · {n}", + "As partidas são gravadas em «{db}» · {n}", + "O‘yinlar «{db}» ga yoziladi · {n}", + "Ойындар «{db}» базаÑ�ына жазылады · {n}", + ], + [ + "Games are written to «{db}»", + "Партии запиÑ�ываютÑ�Ñ� в «{db}»", + "Les parties sont enregistrées dans « {db} »", + "Partien werden in „{db}“ gespeichert", + "Las partidas se guardan en «{db}»", + "Le partite vengono salvate in «{db}»", + "As partidas são gravadas em «{db}»", + "O‘yinlar «{db}» ga yoziladi", + "Ойындар «{db}» базаÑ�ына жазылады", + ], + [ + "✔ Written to the database, No. {n}", + "✔ ЗапиÑ�ано в базу, â„– {n}", + "✔ Enregistrée dans la base, n° {n}", + "✔ In der Datenbank gespeichert, Nr. {n}", + "✔ Guardada en la base, n.º {n}", + "✔ Salvata nel database, n. {n}", + "✔ Gravada na base, n.º {n}", + "✔ Bazaga yozildi, â„– {n}", + "✔ Базаға жазылды, â„– {n}", + ], + [ + "Players of this computer (↓ in the name field)", + "Игроки на Ñ�том компьютере (↓ в поле имени)", + "Joueurs de cet ordinateur (↓ dans le champ du nom)", + "Spieler an diesem Computer (↓ im Namensfeld)", + "Jugadores de este ordenador (↓ en el campo del nombre)", + "Giocatori di questo computer (↓ nel campo del nome)", + "Jogadores deste computador (↓ no campo do nome)", + "Bu kompyuterdagi o‘yinchilar (ism maydonida ↓)", + "ОÑ�Ñ‹ компьютердегі ойыншылар (аты өріÑ�інде ↓)", + ], + [ + "An unfinished game (the program closed) is written to «{db}», No. {n}", + "Ð�едоиграннаÑ� партиÑ� (программа закрылаÑ�ÑŒ) запиÑ�ана в «{db}», â„– {n}", + "Une partie inachevée (le programme s’est fermé) est enregistrée dans « {db} », n° {n}", + "Eine unvollendete Partie (das Programm wurde beendet) ist in „{db}“ gespeichert, Nr. {n}", + "Una partida sin terminar (el programa se cerró) se guardó en «{db}», n.º {n}", + "Una partita non finita (il programma si è chiuso) è salvata in «{db}», n. {n}", + "Uma partida inacabada (o programa fechou) foi gravada em «{db}», n.º {n}", + "Tugallanmagan o‘yin (dastur yopildi) «{db}» ga yozildi, â„– {n}", + "Ð�Ñ�қталмаған ойын (бағдарлама жабылды) «{db}» базаÑ�ына жазылды, â„– {n}", + ], + [ + "Rodent's own rating (UCI_Elo): it does not match a person's Elo.", + "СобÑ�твенный рейтинг Rodent (UCI_Elo): он не равен Эло человека.", + "Le classement propre de Rodent (UCI_Elo) : il ne correspond pas à l’Elo d’une personne.", + "Die eigene Wertung von Rodent (UCI_Elo): sie entspricht nicht der Elo eines Menschen.", + "El rating propio de Rodent (UCI_Elo): no equivale al Elo de una persona.", + "Il rating proprio di Rodent (UCI_Elo): non corrisponde all’Elo di una persona.", + "O rating próprio do Rodent (UCI_Elo): não corresponde ao Elo de uma pessoa.", + "Rodent ning o‘z reytingi (UCI_Elo): u odamning Elo reytingiga teng emas.", + "Rodent-тің өз рейтингі (UCI_Elo): ол адамның Эло рейтингіне Ñ�әйкеÑ� келмейді.", + ], + [ + "Maia's own rating: it does not match a person's Elo.", + "СобÑ�твенный рейтинг Maia: он не равен Эло человека.", + "Le classement propre de Maia : il ne correspond pas à l’Elo d’une personne.", + "Die eigene Wertung von Maia: sie entspricht nicht der Elo eines Menschen.", + "El rating propio de Maia: no equivale al Elo de una persona.", + "Il rating proprio di Maia: non corrisponde all’Elo di una persona.", + "O rating próprio da Maia: não corresponde ao Elo de uma pessoa.", + "Maia ning o‘z reytingi: u odamning Elo reytingiga teng emas.", + "Maia-ның өз рейтингі: ол адамның Эло рейтингіне Ñ�әйкеÑ� келмейді.", + ], + [ + "Character", + "Характер", + "Caractère", + "Charakter", + "Carácter", + "Carattere", + "Caráter", + "Xarakter", + "Мінез", + ], + [ + "Rodent IV is downloaded once ({mb} MB): the engine built from its authors' sources, its characters and books from their repository.", + "Rodent IV Ñ�качиваетÑ�Ñ� один раз ({mb} МБ): движок, Ñ�обранный из иÑ�ходников авторов, его характеры и книги — из их репозиториÑ�.", + "Rodent IV se télécharge une seule fois ({mb} Mo) : le moteur compilé depuis les sources de ses auteurs, ses caractères et livres depuis leur dépôt.", + "Rodent IV wird einmalig heruntergeladen ({mb} MB): die aus den Quellen der Autoren gebaute Engine, Charaktere und Bücher aus deren Repository.", + "Rodent IV se descarga una sola vez ({mb} MB): el motor compilado desde las fuentes de sus autores, sus caracteres y libros desde su repositorio.", + "Rodent IV si scarica una sola volta ({mb} MB): il motore compilato dai sorgenti degli autori, caratteri e libri dal loro repository.", + "O Rodent IV é baixado uma única vez ({mb} MB): o motor compilado a partir das fontes dos autores, os caráteres e livros do repositório deles.", + "Rodent IV bir marta yuklab olinadi ({mb} MB): mualliflar manbasidan yig‘ilgan dvigatel, xarakterlar va kitoblar ularning omboridan.", + "Rodent IV бір рет жүктеледі ({mb} МБ): авторлардың баÑ�тапқы кодынан жиналған қозғалтқыш, мінездер мен кітаптар олардың репозиторийінен.", + ], + [ + "Attacks first, then plays for active pieces.", + "Сначала атакует, потом играет на активноÑ�ть фигур.", + "Attaque d’abord, puis joue pour l’activité des pièces.", + "Greift zuerst an, spielt dann auf aktive Figuren.", + "Primero ataca, luego busca piezas activas.", + "Prima attacca, poi gioca per l’attività dei pezzi.", + "Primeiro ataca, depois joga pela atividade das peças.", + "Avval hujum qiladi, keyin donalar faolligi uchun o‘ynaydi.", + "Ð�лдымен шабуылдайды, кейін фигуралар белÑ�енділігіне ойнайды.", + ], + [ + "Likes closed positions.", + "Любит закрытые позиции.", + "Aime les positions fermées.", + "Mag geschlossene Stellungen.", + "Le gustan las posiciones cerradas.", + "Ama le posizioni chiuse.", + "Gosta de posições fechadas.", + "Yopiq pozitsiyalarni yaxshi ko‘radi.", + "Жабық позициÑ�ларды ұнатады.", + ], + [ + "Defends well and likes her bishops.", + "Хорошо защищаетÑ�Ñ� и любит Ñ�лонов.", + "Défend bien et aime ses fous.", + "Verteidigt gut und mag ihre Läufer.", + "Defiende bien y le gustan sus alfiles.", + "Difende bene e ama i suoi alfieri.", + "Defende bem e gosta dos seus bispos.", + "Yaxshi himoyalanadi va filllarini yaxshi ko‘radi.", + "ЖақÑ�Ñ‹ қорғанады және пілдерін ұнатады.", + ], + [ + "Solid and careful; content with a draw.", + "Ð�адёжный и оÑ�торожный, Ñ�оглаÑ�ен на ничью.", + "Solide et prudent ; se contente de la nulle.", + "Solide und vorsichtig; mit Remis zufrieden.", + "Sólido y prudente; se conforma con tablas.", + "Solido e prudente; si accontenta della patta.", + "Sólido e cuidadoso; contenta-se com o empate.", + "Mustahkam va ehtiyotkor; duranga rozi.", + "Сенімді әрі Ñ�ақ; тең ойынға келіÑ�еді.", + ], + [ + "Attacks, likes bishops, sacrifices now and then.", + "Ð�такует, любит Ñ�лонов, времÑ� от времени жертвует.", + "Attaque, aime les fous, sacrifie de temps en temps.", + "Greift an, mag Läufer, opfert ab und zu.", + "Ataca, le gustan los alfiles, sacrifica de vez en cuando.", + "Attacca, ama gli alfieri, sacrifica di tanto in tanto.", + "Ataca, gosta de bispos, sacrifica de vez em quando.", + "Hujum qiladi, fillarni yaxshi ko‘radi, ba’zan qurbon qiladi.", + "Шабуылдайды, пілдерді ұнатады, анда-Ñ�анда құрбан етеді.", + ], + [ + "Attack and restraint; likes blocked positions, avoids draws.", + "Ð�така и Ñ�ковывание; любит запертые позиции, избегает ничьих.", + "Attaque et restriction ; aime les positions bloquées, évite la nulle.", + "Angriff und Einengung; mag blockierte Stellungen, meidet Remis.", + "Ataque y restricción; le gustan las posiciones bloqueadas, evita las tablas.", + "Attacco e restrizione; ama le posizioni bloccate, evita la patta.", + "Ataque e restrição; gosta de posições bloqueadas, evita empates.", + "Hujum va siqish; yopiq pozitsiyalarni yoqtiradi, durangdan qochadi.", + "Шабуыл мен қыÑ�у; бітелген позициÑ�ларды ұнатады, тең ойыннан қашады.", + ], + [ + "Attacks after quiet, stealthy openings.", + "Ð�такует поÑ�ле тихих, неприметных дебютов.", + "Attaque après des ouvertures calmes et discrètes.", + "Greift nach ruhigen, unauffälligen Eröffnungen an.", + "Ataca tras aperturas tranquilas y discretas.", + "Attacca dopo aperture tranquille e discrete.", + "Ataca depois de aberturas calmas e discretas.", + "Sokin, sezilmas debyutlardan keyin hujum qiladi.", + "Тыныш, байқалмайтын дебюттерден кейін шабуылдайды.", + ], + [ + "Balanced, but gives up pawns more readily.", + "СбаланÑ�ированный, но охотнее отдаёт пешки.", + "Équilibré, mais cède plus volontiers des pions.", + "Ausgewogen, gibt aber eher Bauern her.", + "Equilibrado, pero entrega peones con más facilidad.", + "Equilibrato, ma cede pedoni più volentieri.", + "Equilibrado, mas entrega peões com mais facilidade.", + "Muvozanatli, lekin piyodalarni osonroq beradi.", + "Теңгерімді, бірақ пешкаларды оңай береді.", + ], + [ + "Pawns, defence and restraint.", + "Пешки, защита и Ñ�ковывание.", + "Pions, défense et restriction.", + "Bauern, Verteidigung und Einengung.", + "Peones, defensa y restricción.", + "Pedoni, difesa e restrizione.", + "Peões, defesa e restrição.", + "Piyodalar, himoya va siqish.", + "Пешкалар, қорғаныÑ� және қыÑ�у.", + ], + [ + "A materialistic, moderate attacker.", + "МатериалиÑ�Ñ‚, атакует умеренно.", + "Un attaquant matérialiste et modéré.", + "Ein materialistischer, maßvoller Angreifer.", + "Un atacante materialista y moderado.", + "Un attaccante materialista e moderato.", + "Um atacante materialista e moderado.", + "Materialist, o‘rtacha hujumchi.", + "МатериалиÑ�Ñ‚, қалыпты шабуылшы.", + ], + [ + "The most computer-like: plain, sound chess.", + "Самый «компьютерный»: проÑ�тые, правильные шахматы.", + "Le plus « ordinateur » : un jeu simple et sain.", + "Am computerhaftesten: schlichtes, solides Schach.", + "El más «computadora»: ajedrez sencillo y sólido.", + "Il più «computer»: scacchi semplici e solidi.", + "O mais «computador»: xadrez simples e sólido.", + "Eng «kompyuterona»: oddiy, to‘g‘ri shaxmat.", + "Ең «компьютерлік»: қарапайым, дұрыÑ� шахмат.", + ], + [ + "Sharp and aggressive.", + "ОÑ�трый и агреÑ�Ñ�ивный.", + "Tranchant et agressif.", + "Scharf und aggressiv.", + "Agudo y agresivo.", + "Tagliente e aggressivo.", + "Agudo e agressivo.", + "O‘tkir va tajovuzkor.", + "Өткір және агреÑ�Ñ�ивті.", + ], + [ + "A boa constrictor: squeezes slowly, very human-like.", + "Удав: медленно душит, очень по-человечеÑ�ки.", + "Un boa : étouffe lentement, très humain.", + "Eine Würgeschlange: würgt langsam, sehr menschlich.", + "Una boa: asfixia despacio, muy humano.", + "Un boa: stringe lentamente, molto umano.", + "Uma jiboia: aperta devagar, muito humano.", + "Bo‘g‘ma ilon: sekin siqadi, juda insoniy.", + "Ð�йдаһар-жылан: баÑ�у қыÑ�ады, өте адамға Ò±Ò›Ñ�аÑ�.", + ], + [ + "Dynamic attacks and deep combinations.", + "Динамичные атаки и глубокие комбинации.", + "Attaques dynamiques et combinaisons profondes.", + "Dynamische Angriffe und tiefe Kombinationen.", + "Ataques dinámicos y combinaciones profundas.", + "Attacchi dinamici e combinazioni profonde.", + "Ataques dinâmicos e combinações profundas.", + "Dinamik hujumlar va chuqur kombinatsiyalar.", + "Серпінді шабуылдар мен терең комбинациÑ�лар.", + ], + [ + "Quick, universal play with sharp openings.", + "БыÑ�траÑ�, универÑ�альнаÑ� игра Ñ� оÑ�трыми дебютами.", + "Jeu rapide et universel, ouvertures tranchantes.", + "Schnelles, universelles Spiel mit scharfen Eröffnungen.", + "Juego rápido y universal con aperturas agudas.", + "Gioco rapido e universale con aperture taglienti.", + "Jogo rápido e universal com aberturas agudas.", + "Tez, universal o‘yin, o‘tkir debyutlar bilan.", + "Жылдам, әмбебап ойын, өткір дебюттермен.", + ], + [ + "A romantic attacker of the 19th century: sacrifices.", + "Романтик-атакёр XIX века: жертвы.", + "Un attaquant romantique du XIXe siècle : sacrifices.", + "Ein romantischer Angreifer des 19. Jahrhunderts: Opfer.", + "Un atacante romántico del siglo XIX: sacrificios.", + "Un attaccante romantico dell’Ottocento: sacrifici.", + "Um atacante romântico do século XIX: sacrifícios.", + "XIX asrning romantik hujumchisi: qurbonlar.", + "XIX ғаÑ�ырдың романтик шабуылшыÑ�Ñ‹: құрбандар.", + ], + [ + "Offbeat openings and creative blitz play.", + "Ð�еобычные дебюты и творчеÑ�каÑ� блиц-игра.", + "Ouvertures originales et blitz créatif.", + "Ausgefallene Eröffnungen und kreatives Blitzspiel.", + "Aperturas poco habituales y blitz creativo.", + "Aperture insolite e blitz creativo.", + "Aberturas incomuns e blitz criativo.", + "Noodatiy debyutlar va ijodiy blits.", + "Әдеттен тыÑ� дебюттер және шығармашыл блиц.", + ], + [ + "Scientific, strategic play from deep preparation.", + "Ð�аучнаÑ� Ñ�тратегичеÑ�каÑ� игра на глубокой подготовке.", + "Jeu stratégique et scientifique, préparation profonde.", + "Wissenschaftliches, strategisches Spiel aus tiefer Vorbereitung.", + "Juego estratégico y científico, preparación profunda.", + "Gioco strategico e scientifico, preparazione profonda.", + "Jogo estratégico e científico, preparação profunda.", + "Chuqur tayyorgarlikka asoslangan ilmiy, strategik o‘yin.", + "Терең дайындыққа негізделген ғылыми, Ñ�тратегиÑ�лық ойын.", + ], + [ + "Clear, classical and precise.", + "ЯÑ�наÑ�, клаÑ�Ñ�ичеÑ�каÑ� и точнаÑ� игра.", + "Clair, classique et précis.", + "Klar, klassisch und präzise.", + "Claro, clásico y preciso.", + "Chiaro, classico e preciso.", + "Claro, clássico e preciso.", + "Aniq, klassik va puxta.", + "Ð�нық, клаÑ�Ñ�икалық және дәл.", + ], + [ + "Positional squeeze, prophylaxis and technique.", + "Позиционное давление, профилактика и техника.", + "Étau positionnel, prophylaxie et technique.", + "Positioneller Druck, Prophylaxe und Technik.", + "Presión posicional, profilaxis y técnica.", + "Morsa posizionale, profilassi e tecnica.", + "Pressão posicional, profilaxia e técnica.", + "Pozitsion bosim, profilaktika va texnika.", + "ПозициÑ�лық қыÑ�ым, профилактика және техника.", + ], + [ + "Initiative and powerful attack.", + "Инициатива и мощнаÑ� атака.", + "Initiative et attaque puissante.", + "Initiative und kraftvoller Angriff.", + "Iniciativa y ataque poderoso.", + "Iniziativa e attacco potente.", + "Iniciativa e ataque poderoso.", + "Tashabbus va kuchli hujum.", + "БаÑ�тама және қуатты шабуыл.", + ], + [ + "A tenacious defender and counter-attacker.", + "Упорный защитник и маÑ�тер контратаки.", + "Un défenseur tenace et contre-attaquant.", + "Ein zäher Verteidiger und Konterspieler.", + "Un defensor tenaz y contraatacante.", + "Un difensore tenace e contrattaccante.", + "Um defensor tenaz e contra-atacante.", + "Qat’iyatli himoyachi va qarshi hujumchi.", + "Табанды қорғаушы және қарÑ�Ñ‹ шабуылшы.", + ], + [ + "Original and risky, with offbeat openings.", + "Оригинальный и риÑ�кованный, Ñ� необычными дебютами.", + "Original et risqué, aux ouvertures insolites.", + "Originell und riskant, mit ausgefallenen Eröffnungen.", + "Original y arriesgado, con aperturas inusuales.", + "Originale e rischioso, con aperture insolite.", + "Original e arriscado, com aberturas incomuns.", + "O‘ziga xos va tavakkalchi, noodatiy debyutlar bilan.", + "Өзгеше және тәуекелшіл, әдеттен тыÑ� дебюттермен.", + ], + [ + "A practical, psychological fighter.", + "Практичный боец-пÑ�ихолог.", + "Un combattant pratique et psychologue.", + "Ein praktischer, psychologischer Kämpfer.", + "Un luchador práctico y psicológico.", + "Un combattente pratico e psicologico.", + "Um lutador prático e psicológico.", + "Amaliy, psixolog kurashchi.", + "Практикалық, пÑ�ихолог күреÑ�кер.", + ], + [ + "A swashbuckling attacker with gambits.", + "Лихой атакёр Ñ� гамбитами.", + "Un attaquant fougueux, amateur de gambits.", + "Ein verwegener Angreifer mit Gambits.", + "Un atacante audaz, amigo de los gambitos.", + "Un attaccante spavaldo con i gambetti.", + "Um atacante ousado com gambitos.", + "Gambitlar bilan dadil hujumchi.", + "Гамбиттері бар батыл шабуылшы.", + ], + [ + "Quick development and open lines.", + "БыÑ�трое развитие и открытые линии.", + "Développement rapide et lignes ouvertes.", + "Schnelle Entwicklung und offene Linien.", + "Desarrollo rápido y líneas abiertas.", + "Sviluppo rapido e linee aperte.", + "Desenvolvimento rápido e linhas abertas.", + "Tez rivojlanish va ochiq chiziqlar.", + "Жылдам дамыту және ашық Ñ�ызықтар.", + ], + [ + "Restraint, blockade and overprotection.", + "Сковывание, блокада и Ñ�верхзащита.", + "Restriction, blocus et surprotection.", + "Einengung, Blockade und Überdeckung.", + "Restricción, bloqueo y sobreprotección.", + "Restrizione, blocco e sovraprotezione.", + "Restrição, bloqueio e superproteção.", + "Siqish, blokada va ortiqcha himoya.", + "ҚыÑ�у, блокада және артық қорғау.", + ], + [ + "Prophylaxis and safety first.", + "Профилактика и безопаÑ�ноÑ�ть прежде вÑ�его.", + "Prophylaxie et sécurité avant tout.", + "Prophylaxe und Sicherheit zuerst.", + "Profilaxis y seguridad ante todo.", + "Profilassi e sicurezza prima di tutto.", + "Profilaxia e segurança acima de tudo.", + "Profilaktika va xavfsizlik birinchi.", + "Профилактика және қауіпÑ�іздік бірінші.", + ], + [ + "Hypermodern: controls the centre from afar.", + "ГиперÑ�овременный: контролирует центр издалека.", + "Hypermoderne : contrôle le centre à distance.", + "Hypermodern: kontrolliert das Zentrum aus der Ferne.", + "Hipermoderno: controla el centro a distancia.", + "Ipermoderno: controlla il centro da lontano.", + "Hipermoderno: controla o centro à distância.", + "Gipermodern: markazni uzoqdan nazorat qiladi.", + "Гиперзаманауи: орталықты алыÑ�тан бақылайды.", + ], + [ + "Classical positional play, great in endgames.", + "КлаÑ�Ñ�ичеÑ�каÑ� позиционнаÑ� игра, Ñ�илён в Ñ�ндшпиле.", + "Jeu positionnel classique, excellent en finale.", + "Klassisches Positionsspiel, stark im Endspiel.", + "Juego posicional clásico, gran finalista.", + "Gioco posizionale classico, ottimo nei finali.", + "Jogo posicional clássico, ótimo em finais.", + "Klassik pozitsion o‘yin, endshpilda kuchli.", + "КлаÑ�Ñ�икалық позициÑ�лық ойын, Ñ�ндшпильде мықты.", + ], + [ + "A universal player, at home in any position.", + "УниверÑ�ал, в любой позиции как дома.", + "Un joueur universel, à l’aise partout.", + "Ein Universalspieler, in jeder Stellung zu Hause.", + "Un jugador universal, cómodo en cualquier posición.", + "Un giocatore universale, a suo agio ovunque.", + "Um jogador universal, à vontade em qualquer posição.", + "Universal o‘yinchi, har qanday pozitsiyada o‘zini uydagidek his qiladi.", + "Әмбебап ойыншы, кез келген позициÑ�да өзін үйдегідей Ñ�езінеді.", + ], + [ + "The founder of positional play, a stubborn defender.", + "ОÑ�нователь позиционной игры, упрÑ�мый защитник.", + "Le fondateur du jeu positionnel, défenseur obstiné.", + "Der Begründer des Positionsspiels, ein hartnäckiger Verteidiger.", + "El fundador del juego posicional, un defensor obstinado.", + "Il fondatore del gioco posizionale, difensore ostinato.", + "O fundador do jogo posicional, um defensor obstinado.", + "Pozitsion o‘yin asoschisi, qaysar himoyachi.", + "ПозициÑ�лық ойынның негізін Ñ�алушы, қыңыр қорғаушы.", + ], + [ + "The magician from Riga: sacrifices and attack.", + "РижÑ�кий волшебник: жертвы и атака.", + "Le magicien de Riga : sacrifices et attaque.", + "Der Zauberer aus Riga: Opfer und Angriff.", + "El mago de Riga: sacrificios y ataque.", + "Il mago di Riga: sacrifici e attacco.", + "O mágico de Riga: sacrifícios e ataque.", + "Rigalik sehrgar: qurbonlar va hujum.", + "Ригалық Ñ�иқыршы: құрбандар мен шабуыл.", + ], + [ + "Classical rules: space, development, active pieces.", + "КлаÑ�Ñ�ичеÑ�кие правила: проÑ�транÑ�тво, развитие, активные фигуры.", + "Règles classiques : espace, développement, pièces actives.", + "Klassische Regeln: Raum, Entwicklung, aktive Figuren.", + "Reglas clásicas: espacio, desarrollo, piezas activas.", + "Regole classiche: spazio, sviluppo, pezzi attivi.", + "Regras clássicas: espaço, desenvolvimento, peças ativas.", + "Klassik qoidalar: makon, rivojlanish, faol donalar.", + "КлаÑ�Ñ�икалық ережелер: кеңіÑ�тік, дамыту, белÑ�енді фигуралар.", + ], + [ + "Aggressive and dynamic, sacrifices the exchange.", + "Ð�греÑ�Ñ�ивный и динамичный, жертвует качеÑ�тво.", + "Agressif et dynamique, sacrifie la qualité.", + "Aggressiv und dynamisch, opfert die Qualität.", + "Agresivo y dinámico, sacrifica la calidad.", + "Aggressivo e dinamico, sacrifica la qualità.", + "Agressivo e dinâmico, sacrifica a qualidade.", + "Tajovuzkor va dinamik, sifatni qurbon qiladi.", + "Ð�греÑ�Ñ�ивті және Ñ�ерпінді, Ñ�апаны құрбан етеді.", + ], + [ + "Tal (classic)", + "Таль (клаÑ�Ñ�ика)", + "Tal (classique)", + "Tal (klassisch)", + "Tal (clásico)", + "Tal (classico)", + "Tal (clássico)", + "Tal (klassik)", + "Таль (клаÑ�Ñ�ика)", + ], + [ + "Anand", + "Ð�нанд", + "Anand", + "Anand", + "Anand", + "Anand", + "Anand", + "Anand", + "Ð�нанд", + ], + [ + "Anderssen", + "Ð�ндерÑ�ен", + "Anderssen", + "Anderssen", + "Anderssen", + "Anderssen", + "Anderssen", + "Anderssen", + "Ð�ндерÑ�ен", + ], + [ + "Bosboom", + "БоÑ�бум", + "Bosboom", + "Bosboom", + "Bosboom", + "Bosboom", + "Bosboom", + "Bosboom", + "БоÑ�бум", + ], + [ + "Botvinnik", + "Ботвинник", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Ботвинник", + ], + [ + "Fischer", + "Фишер", + "Fischer", + "Fischer", + "Fischer", + "Fischer", + "Fischer", + "Fischer", + "Фишер", + ], + [ + "Karpov", + "Карпов", + "Karpov", + "Karpov", + "Karpov", + "Karpov", + "Karpov", + "Karpov", + "Карпов", + ], + [ + "Kasparov", + "КаÑ�паров", + "Kasparov", + "Kasparov", + "Kasparov", + "Kasparov", + "Kasparov", + "Kasparov", + "КаÑ�паров", + ], + [ + "Kortchnoi", + "Корчной", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Корчной", + ], + [ + "Larsen", + "ЛарÑ�ен", + "Larsen", + "Larsen", + "Larsen", + "Larsen", + "Larsen", + "Larsen", + "ЛарÑ�ен", + ], + [ + "Lasker", + "ЛаÑ�кер", + "Lasker", + "Lasker", + "Lasker", + "Lasker", + "Lasker", + "Lasker", + "ЛаÑ�кер", + ], + [ + "Marshall", + "Маршалл", + "Marshall", + "Marshall", + "Marshall", + "Marshall", + "Marshall", + "Marshall", + "Маршалл", + ], + [ + "Morphy", + "Морфи", + "Morphy", + "Morphy", + "Morphy", + "Morphy", + "Morphy", + "Morphy", + "Морфи", + ], + [ + "Nimzowitsch", + "Ð�имцович", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Ð�имцович", + ], + [ + "Petrosian", + "ПетроÑ�Ñ�н", + "Petrosian", + "Petrosian", + "Petrosian", + "Petrosian", + "Petrosian", + "Petrosian", + "ПетроÑ�Ñ�н", + ], + [ + "Reti", "Рети", "Reti", "Reti", "Reti", "Reti", "Reti", "Reti", "Рети", + ], + [ + "Rubinstein", + "Рубинштейн", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Рубинштейн", + ], + [ + "Spassky", + "СпаÑ�Ñ�кий", + "Spassky", + "Spassky", + "Spassky", + "Spassky", + "Spassky", + "Spassky", + "СпаÑ�Ñ�кий", + ], + [ + "Steinitz", + "Стейниц", + "Steinitz", + "Steinitz", + "Steinitz", + "Steinitz", + "Steinitz", + "Steinitz", + "Стейниц", + ], + [ + "Tarrasch", + "Тарраш", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Тарраш", + ], + [ + "Topalov", + "Топалов", + "Topalov", + "Topalov", + "Topalov", + "Topalov", + "Topalov", + "Topalov", + "Топалов", + ], + [ + "Amanda", + "Ð�манда", + "Amanda", + "Amanda", + "Amanda", + "Amanda", + "Amanda", + "Amanda", + "Ð�манда", + ], + [ + "Cloe", "Клои", "Cloé", "Cloe", "Cloe", "Cloe", "Cloe", "Kloe", "Клои", + ], + [ + "Deborah", + "Дебора", + "Déborah", + "Deborah", + "Débora", + "Debora", + "Débora", + "Debora", + "Дебора", + ], + [ + "Defender", + "Защитник", + "Défenseur", + "Verteidiger", + "Defensor", + "Difensore", + "Defensor", + "Himoyachi", + "Қорғаушы", + ], + [ + "Dynamic", + "Динамик", + "Dynamique", + "Dynamiker", + "Dinámico", + "Dinamico", + "Dinâmico", + "Dinamik", + "Динамик", + ], + [ + "Grumpy", + "Ворчун", + "Grincheux", + "Brummbär", + "Gruñón", + "Brontolo", + "Rabugento", + "G‘udranuvchi", + "Күңкілдек", + ], + [ + "Partisan", + "Партизан", + "Partisan", + "Partisan", + "Partisano", + "Partigiano", + "Partisano", + "Partizan", + "Партизан", + ], + [ + "Pawnsacker", + "ГамбитиÑ�Ñ‚", + "Gambiteur", + "Bauernopferer", + "Gambitero", + "Gambettista", + "Gambiteiro", + "Gambitchi", + "Гамбитші", + ], + [ + "Pedrita", + "Педрита", + "Pedrita", + "Pedrita", + "Pedrita", + "Pedrita", + "Pedrita", + "Pedrita", + "Педрита", + ], + [ + "Preston", + "ПреÑ�тон", + "Preston", + "Preston", + "Preston", + "Preston", + "Preston", + "Preston", + "ПреÑ�тон", + ], + [ + "Simple", + "ПроÑ�так", + "Simplet", + "Schlicht", + "Sencillo", + "Semplice", + "Simples", + "Oddiy", + "Қарапайым", + ], + [ + "Spitfire", + "Задира", + "Boutefeu", + "Hitzkopf", + "Fogoso", + "Testa calda", + "Esquentado", + "Jo‘shqin", + "Қызба", + ], + [ + "Strangler", + "Удав", + "Étrangleur", + "Würger", + "Estrangulador", + "Strangolatore", + "Estrangulador", + "Bo‘g‘uvchi", + "Тұншықтырушы", + ], + [ + "Maia resigned", + "Maia Ñ�далаÑ�ÑŒ", + "Maia a abandonné", + "Maia hat aufgegeben", + "Maia se rindió", + "Maia ha abbandonato", + "Maia desistiu", + "Maia taslim bo‘ldi", + "Maia берілді", + ], + [ + "Maia resigns", + "Maia Ñ�даётÑ�Ñ�", + "Maia abandonne", + "Maia gibt auf", + "Maia se rinde", + "Maia abbandona", + "Maia desiste", + "Maia taslim bo‘lmoqda", + "Maia беріледі", + ], + [ + "Her position is lost. Accept the win, or play to the end?", + "Её позициÑ� проиграна. ПринÑ�ть победу или играть до конца?", + "Sa position est perdue. Accepter la victoire ou jouer jusqu’au bout ?", + "Ihre Stellung ist verloren. Den Sieg annehmen oder zu Ende spielen?", + "Su posición está perdida. ¿Aceptar la victoria o jugar hasta el final?", + "La sua posizione è persa. Accettare la vittoria o giocare fino alla fine?", + "A posição dela está perdida. Aceitar a vitória ou jogar até o fim?", + "Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki oxirigacha o‘ynaysizmi?", + "Оның позициÑ�Ñ�Ñ‹ ұтылған. ЖеңіÑ�ті қабылдайÑ�ыз ба, әлде Ñ�оңына дейін ойнайÑ�ыз ба?", + ], + [ + "Accept the win", + "ПринÑ�ть победу", + "Accepter la victoire", + "Sieg annehmen", + "Aceptar la victoria", + "Accetta la vittoria", + "Aceitar a vitória", + "G‘alabani qabul qilish", + "ЖеңіÑ�ті қабылдау", + ], + [ + "Play to the end", + "Играть до конца", + "Jouer jusqu’au bout", + "Zu Ende spielen", + "Jugar hasta el final", + "Gioca fino alla fine", + "Jogar até o fim", + "Oxirigacha o‘ynash", + "Соңына дейін ойнау", + ], + [ + "Maia plays on and will not offer again in this game", + "Maia продолжит и в Ñ�той партии больше не предложит", + "Maia continue et ne le proposera plus dans cette partie", + "Maia spielt weiter und bietet es in dieser Partie nicht mehr an", + "Maia sigue jugando y no volverá a ofrecerlo en esta partida", + "Maia continua e non lo proporrà più in questa partita", + "Maia continua e não oferecerá de novo nesta partida", + "Maia davom etadi va bu o‘yinda boshqa taklif qilmaydi", + "Maia жалғаÑ�тырады және бұл партиÑ�да енді Ò±Ñ�ынбайды", + ], + [ + "resigns", + "Ñ�даётÑ�Ñ�", + "abandonne", + "gibt auf", + "se rinde", + "abbandona", + "desiste", + "taslim bo‘lmoqda", + "беріледі", + ], + // --- paste a line --- + [ + "Paste a line from the clipboard (Ctrl+V)", + "Ð’Ñ�тавить вариант из буфера (Ctrl+V)", + "Coller une variante depuis le presse-papiers (Ctrl+V)", + "Variante aus der Zwischenablage einfügen (Ctrl+V)", + "Pegar una variante del portapapeles (Ctrl+V)", + "Incolla una variante dagli appunti (Ctrl+V)", + "Colar uma variante da área de transferência (Ctrl+V)", + "Buferdan variant qo‘yish (Ctrl+V)", + "Буферден вариант қою (Ctrl+V)", + ], + [ + "The clipboard holds no moves", + "Ð’ буфере нет ходов", + "Le presse-papiers ne contient aucun coup", + "Die Zwischenablage enthält keine Züge", + "El portapapeles no contiene jugadas", + "Gli appunti non contengono mosse", + "A área de transferência não contém lances", + "Buferda yurishlar yo‘q", + "Буферде жүріÑ�тер жоқ", + ], + [ + "These moves fit neither after {move} nor instead of it", + "Эти ходы нельзÑ� Ñ�делать ни поÑ�ле {move}, ни вмеÑ�то него", + "Ces coups ne peuvent être joués ni après {move}, ni à sa place", + "Diese Züge passen weder nach {move} noch an seiner Stelle", + "Estas jugadas no caben ni después de {move} ni en su lugar", + "Queste mosse non si possono giocare né dopo {move} né al suo posto", + "Estes lances não cabem nem depois de {move} nem no lugar dele", + "Bu yurishlarni {move} yurishidan keyin ham, uning o‘rniga ham qilib bo‘lmaydi", + "Бұл жүріÑ�терді {move} жүріÑ�інен кейін де, оның орнына да жаÑ�ау мүмкін емеÑ�", + ], + [ + "The move {move} is impossible — nothing inserted", + "Ход {move} невозможен — ничего не вÑ�тавлено", + "Le coup {move} est impossible — rien n’a été inséré", + "Der Zug {move} ist unmöglich — nichts eingefügt", + "La jugada {move} es imposible — no se insertó nada", + "La mossa {move} è impossibile — non è stato inserito nulla", + "O lance {move} é impossível — nada foi inserido", + "{move} yurishi mumkin emas — hech narsa qo‘yilmadi", + "{move} жүріÑ�Ñ– мүмкін емеÑ� — ештеңе қойылмады", + ], + [ + "The game in the clipboard does not fit: none of its positions occur in this game", + "ПартиÑ� из буфера Ñ�юда не подходит: в Ñ�той партии нет её позиций", + "La partie du presse-papiers ne convient pas : aucune de ses positions n’apparaît dans cette partie", + "Die Partie aus der Zwischenablage passt nicht: keine ihrer Stellungen kommt in dieser Partie vor", + "La partida del portapapeles no encaja: ninguna de sus posiciones aparece en esta partida", + "La partita negli appunti non è compatibile: nessuna delle sue posizioni compare in questa partita", + "A partida da área de transferência não se encaixa: nenhuma de suas posições ocorre nesta partida", + "Buferdagi partiya bu yerga mos kelmaydi: uning pozitsiyalari bu partiyada yo‘q", + "Буфердегі партиÑ� бұл жерге Ñ�әйкеÑ� келмейді: оның позициÑ�лары бұл партиÑ�да жоқ", + ], + [ + "These moves are already in the game", + "Эти ходы уже еÑ�ть в партии", + "Ces coups figurent déjà dans la partie", + "Diese Züge sind bereits in der Partie", + "Estas jugadas ya están en la partida", + "Queste mosse sono già nella partita", + "Estes lances já estão na partida", + "Bu yurishlar partiyada allaqachon bor", + "Бұл жүріÑ�тер партиÑ�да бұрыннан бар", + ], + [ + "These moves are already in the game — the comments from the clipboard were not carried over", + "Эти ходы уже еÑ�ть в партии — комментарии из буфера не перенеÑ�ены", + "Ces coups figurent déjà dans la partie — les commentaires du presse-papiers n’ont pas été repris", + "Diese Züge sind bereits in der Partie — die Kommentare aus der Zwischenablage wurden nicht übernommen", + "Estas jugadas ya están en la partida — los comentarios del portapapeles no se trasladaron", + "Queste mosse sono già nella partita — i commenti degli appunti non sono stati riportati", + "Estes lances já estão na partida — os comentários da área de transferência não foram transferidos", + "Bu yurishlar partiyada allaqachon bor — buferdagi izohlar ko‘chirilmadi", + "Бұл жүріÑ�тер партиÑ�да бұрыннан бар — буфердегі түÑ�ініктемелер көшірілмеді", + ], + [ + "By another move order: {moves}", + "Другим порÑ�дком ходов: {moves}", + "Par un autre ordre de coups : {moves}", + "Mit anderer Zugfolge: {moves}", + "Con otro orden de jugadas: {moves}", + "Con un altro ordine di mosse: {moves}", + "Por outra ordem de lances: {moves}", + "Boshqa yurishlar tartibida: {moves}", + "БаÑ�қа жүріÑ� ретімен: {moves}", + ], + [ + "The game is continued: {moves} (Ctrl+Z to undo)", + "ПартиÑ� продолжена: {moves} (Ctrl+Z — отменить)", + "Partie prolongée : {moves} (Ctrl+Z pour annuler)", + "Partie fortgesetzt: {moves} (Ctrl+Z zum Rückgängigmachen)", + "Partida continuada: {moves} (Ctrl+Z para deshacer)", + "Partita proseguita: {moves} (Ctrl+Z per annullare)", + "Partida continuada: {moves} (Ctrl+Z para desfazer)", + "Partiya davom ettirildi: {moves} (bekor qilish: Ctrl+Z)", + "ПартиÑ� жалғаÑ�тырылды: {moves} (болдырмау — Ctrl+Z)", + ], + [ + "Line {moves} inserted after {move} (Ctrl+Z to undo)", + "Вариант {moves} вÑ�тавлен поÑ�ле {move} (Ctrl+Z — отменить)", + "Variante {moves} insérée après {move} (Ctrl+Z pour annuler)", + "Variante {moves} nach {move} eingefügt (Ctrl+Z zum Rückgängigmachen)", + "Variante {moves} insertada después de {move} (Ctrl+Z para deshacer)", + "Variante {moves} inserita dopo {move} (Ctrl+Z per annullare)", + "Variante {moves} inserida depois de {move} (Ctrl+Z para desfazer)", + "{moves} varianti {move} yurishidan keyin qo‘yildi (bekor qilish: Ctrl+Z)", + "{moves} варианты {move} жүріÑ�інен кейін қойылды (болдырмау — Ctrl+Z)", + ], + [ + "Line {moves} inserted at the start of the game (Ctrl+Z to undo)", + "Вариант {moves} вÑ�тавлен в начале партии (Ctrl+Z — отменить)", + "Variante {moves} insérée au début de la partie (Ctrl+Z pour annuler)", + "Variante {moves} am Anfang der Partie eingefügt (Ctrl+Z zum Rückgängigmachen)", + "Variante {moves} insertada al inicio de la partida (Ctrl+Z para deshacer)", + "Variante {moves} inserita all’inizio della partita (Ctrl+Z per annullare)", + "Variante {moves} inserida no início da partida (Ctrl+Z para desfazer)", + "{moves} varianti partiya boshiga qo‘yildi (bekor qilish: Ctrl+Z)", + "{moves} варианты партиÑ�ның баÑ�ына қойылды (болдырмау — Ctrl+Z)", + ], + [ + "The clipboard has {count} games — the first one is inserted.", + "Ð’ буфере партий: {count} — вÑ�тавлена перваÑ�.", + "Parties dans le presse-papiers : {count} — la première est insérée.", + "Partien in der Zwischenablage: {count} — die erste wurde eingefügt.", + "Partidas en el portapapeles: {count} — se insertó la primera.", + "Partite negli appunti: {count} — è stata inserita la prima.", + "Partidas na área de transferência: {count} — a primeira foi inserida.", + "Buferdagi partiyalar: {count} — birinchisi qo‘yildi.", + "Буфердегі партиÑ�лар: {count} — біріншіÑ�Ñ– қойылды.", + ], + [ + "the start of the game", + "начало партии", + "le début de la partie", + "der Partieanfang", + "el inicio de la partida", + "l’inizio della partita", + "o início da partida", + "partiya boshi", + "партиÑ� баÑ�Ñ‹", + ], + [ + "The game in the clipboard parts from this one at the start of the game.", + "ПартиÑ� из буфера раÑ�ходитÑ�Ñ� Ñ� Ñ�той в Ñ�амом начале.", + "La partie du presse-papiers diverge de celle-ci dès le début.", + "Die Partie aus der Zwischenablage weicht von dieser gleich am Anfang ab.", + "La partida del portapapeles se separa de esta desde el inicio.", + "La partita negli appunti si discosta da questa fin dall’inizio.", + "A partida da área de transferência diverge desta logo no início.", + "Buferdagi partiya bu partiyadan boshidanoq ajraladi.", + "Буфердегі партиÑ� бұл партиÑ�дан ең баÑ�ында ажырайды.", + ], + [ + "The game in the clipboard parts from this one before the selected move: after {from}, not after {cursor}.", + "ПартиÑ� из буфера раÑ�ходитÑ�Ñ� Ñ� Ñ�той раньше выбранного хода: поÑ�ле {from}, а не поÑ�ле {cursor}.", + "La partie du presse-papiers diverge de celle-ci avant le coup sélectionné : après {from}, et non après {cursor}.", + "Die Partie aus der Zwischenablage weicht von dieser schon vor dem gewählten Zug ab: nach {from}, nicht nach {cursor}.", + "La partida del portapapeles se separa de esta antes de la jugada seleccionada: después de {from}, no después de {cursor}.", + "La partita negli appunti si discosta da questa prima della mossa selezionata: dopo {from}, non dopo {cursor}.", + "A partida da área de transferência diverge desta antes do lance selecionado: depois de {from}, não depois de {cursor}.", + "Buferdagi partiya bu partiyadan tanlangan yurishdan oldin ajraladi: {from} yurishidan keyin, {cursor} yurishidan keyin emas.", + "Буфердегі партиÑ� бұл партиÑ�дан таңдалған жүріÑ�тен бұрын ажырайды: {from} жүріÑ�інен кейін, {cursor} жүріÑ�інен кейін емеÑ�.", + ], + [ + "The game in the clipboard parts from this one in another line: after {from}.", + "ПартиÑ� из буфера раÑ�ходитÑ�Ñ� Ñ� Ñ�той в другом варианте: поÑ�ле {from}.", + "La partie du presse-papiers diverge de celle-ci dans une autre variante : après {from}.", + "Die Partie aus der Zwischenablage weicht von dieser in einer anderen Variante ab: nach {from}.", + "La partida del portapapeles se separa de esta en otra variante: después de {from}.", + "La partita negli appunti si discosta da questa in un’altra variante: dopo {from}.", + "A partida da área de transferência diverge desta em outra variante: depois de {from}.", + "Buferdagi partiya bu partiyadan boshqa variantda ajraladi: {from} yurishidan keyin.", + "Буфердегі партиÑ� бұл партиÑ�дан баÑ�қа вариантта ажырайды: {from} жүріÑ�інен кейін.", + ], + [ + "Insert after {move}", + "Ð’Ñ�тавить поÑ�ле {move}", + "Insérer après {move}", + "Nach {move} einfügen", + "Insertar después de {move}", + "Inserisci dopo {move}", + "Inserir depois de {move}", + "{move} yurishidan keyin qo‘yish", + "{move} жүріÑ�інен кейін қою", + ], + [ + "Insert at the start", + "Ð’Ñ�тавить в начале", + "Insérer au début", + "Am Anfang einfügen", + "Insertar al inicio", + "Inserisci all’inizio", + "Inserir no início", + "Boshiga qo‘yish", + "БаÑ�ына қою", + ], + [ + "Insert the line earlier?", + "Ð’Ñ�тавить вариант раньше?", + "Insérer la variante plus tôt ?", + "Variante früher einfügen?", + "¿Insertar la variante antes?", + "Inserire la variante prima?", + "Inserir a variante antes?", + "Variant oldinroq qo‘yilsinmi?", + "Вариант ертерек қойылÑ�ын ба?", + ], + [ + "Paste a line from the clipboard", + "Ð’Ñ�тавить вариант из буфера", + "Coller une variante depuis le presse-papiers", + "Variante aus der Zwischenablage einfügen", + "Pegar una variante del portapapeles", + "Incolla una variante dagli appunti", + "Colar uma variante da área de transferência", + "Buferdan variant qo‘yish", + "Буферден вариант қою", + ], + [ + "Moves or a PGN game from the clipboard, as a variation from where they part from this game", + "Ходы или партиÑ� PGN из буфера — вариантом Ñ� того меÑ�та, где они раÑ�ходÑ�Ñ‚Ñ�Ñ� Ñ� Ñ�той партией", + "Des coups ou une partie PGN du presse-papiers, en variante à partir de l’endroit où ils divergent de cette partie", + "Züge oder eine PGN-Partie aus der Zwischenablage, als Variante ab der Stelle, an der sie von dieser Partie abweichen", + "Jugadas o una partida PGN del portapapeles, como variante desde donde se separan de esta partida", + "Mosse o una partita PGN dagli appunti, come variante dal punto in cui si discostano da questa partita", + "Lances ou uma partida PGN da área de transferência, como variante a partir de onde divergem desta partida", + "Buferdagi yurishlar yoki PGN partiya — bu partiyadan ajralgan joyidan variant sifatida", + "Буфердегі жүріÑ�тер немеÑ�е PGN партиÑ�Ñ�Ñ‹ — оÑ�Ñ‹ партиÑ�дан ажырайтын жерден вариант ретінде", + ], + // --- play on from here --- + [ + "Play on from here… (Ctrl+G)", + "Играть отÑ�юда… (Ctrl+G)", + "Jouer à partir d’ici… (Ctrl+G)", + "Von hier aus spielen… (Ctrl+G)", + "Jugar desde aquí… (Ctrl+G)", + "Gioca da qui… (Ctrl+G)", + "Jogar a partir daqui… (Ctrl+G)", + "Shu yerdan o‘ynash… (Ctrl+G)", + "ОÑ�Ñ‹ жерден ойнау… (Ctrl+G)", + ], + [ + "Play on from here…", + "Играть отÑ�юда…", + "Jouer à partir d’ici…", + "Von hier aus spielen…", + "Jugar desde aquí…", + "Gioca da qui…", + "Jogar a partir daqui…", + "Shu yerdan o‘ynash…", + "ОÑ�Ñ‹ жерден ойнау…", + ], + [ + "A game against Maia from this position", + "ПартиÑ� Ñ� Maia из Ñ�той позиции", + "Une partie contre Maia à partir de cette position", + "Eine Partie gegen Maia aus dieser Stellung", + "Una partida contra Maia desde esta posición", + "Una partita contro Maia da questa posizione", + "Uma partida contra Maia a partir desta posição", + "Shu pozitsiyadan Maia bilan o‘yin", + "ОÑ�Ñ‹ позициÑ�дан Maia-мен партиÑ�", + ], + [ + "The game is over here: {why}", + "ЗдеÑ�ÑŒ партиÑ� окончена: {why}", + "La partie est terminée ici : {why}", + "Hier ist die Partie zu Ende: {why}", + "Aquí la partida ha terminado: {why}", + "Qui la partita è finita: {why}", + "Aqui a partida terminou: {why}", + "Bu yerda o‘yin tugagan: {why}", + "Мұнда партиÑ� аÑ�қталған: {why}", + ], + [ + "From the position after {move}", + "С позиции поÑ�ле {move}", + "À partir de la position après {move}", + "Aus der Stellung nach {move}", + "Desde la posición tras {move}", + "Dalla posizione dopo {move}", + "A partir da posição após {move}", + "{move} yurishidan keyingi pozitsiyadan", + "{move} жүріÑ�інен кейінгі позициÑ�дан", + ], + [ + "From the game's starting position", + "С начальной позиции партии", + "À partir de la position de départ de la partie", + "Aus der Anfangsstellung der Partie", + "Desde la posición inicial de la partida", + "Dalla posizione iniziale della partita", + "A partir da posição inicial da partida", + "O‘yinning boshlang‘ich pozitsiyasidan", + "ПартиÑ�ның баÑ�тапқы позициÑ�Ñ�ынан", + ], + [ + "from the game {game}", + "из партии {game}", + "de la partie {game}", + "aus der Partie {game}", + "de la partida {game}", + "dalla partita {game}", + "da partida {game}", + "{game} o‘yinidan", + "{game} партиÑ�Ñ�ынан", + ], + [ + "The moves before the null move (--) are not carried over", + "Ходы до пропуÑ�ка хода (--) в игру не войдут", + "Les coups avant le coup nul (--) ne sont pas repris", + "Die Züge vor dem Nullzug (--) werden nicht übernommen", + "Las jugadas antes de la jugada nula (--) no se incluyen", + "Le mosse prima della mossa nulla (--) non vengono riprese", + "Os lances antes do lance nulo (--) não são incluídos", + "Bo‘sh yurishdan (--) oldingi yurishlar o‘yinga kirmaydi", + "БоÑ� жүріÑ�ке (--) дейінгі жүріÑ�тер ойынға кірмейді", + ], + [ + "Continued from {game}, after {move}. From here on, a game against Maia {elo}.", + "Продолжение партии {game}, поÑ�ле {move}. Дальше — игра Ñ� Maia {elo}.", + "Suite de la partie {game}, après {move}. À partir d’ici, une partie contre Maia {elo}.", + "Fortsetzung der Partie {game} nach {move}. Ab hier eine Partie gegen Maia {elo}.", + "Continuación de la partida {game}, tras {move}. A partir de aquí, una partida contra Maia {elo}.", + "Seguito della partita {game}, dopo {move}. Da qui, una partita contro Maia {elo}.", + "Continuação da partida {game}, após {move}. A partir daqui, uma partida contra Maia {elo}.", + "{game} o‘yinining davomi, {move} dan keyin. Bundan keyin — Maia {elo} bilan o‘yin.", + "{game} партиÑ�Ñ�ының жалғаÑ�Ñ‹, {move} кейін. Бұдан әрі — Maia {elo}-мен ойын.", + ], + [ + "Continued after {move}. From here on, a game against Maia {elo}.", + "Продолжение поÑ�ле {move}. Дальше — игра Ñ� Maia {elo}.", + "Suite après {move}. À partir d’ici, une partie contre Maia {elo}.", + "Fortsetzung nach {move}. Ab hier eine Partie gegen Maia {elo}.", + "Continuación tras {move}. A partir de aquí, una partida contra Maia {elo}.", + "Seguito dopo {move}. Da qui, una partita contro Maia {elo}.", + "Continuação após {move}. A partir daqui, uma partida contra Maia {elo}.", + "{move} dan keyingi davomi. Bundan keyin — Maia {elo} bilan o‘yin.", + "{move} кейінгі жалғаÑ�Ñ‹. Бұдан әрі — Maia {elo}-мен ойын.", + ], + [ + "Continued from {game}. From here on, a game against Maia {elo}.", + "Продолжение партии {game}. Дальше — игра Ñ� Maia {elo}.", + "Suite de la partie {game}. À partir d’ici, une partie contre Maia {elo}.", + "Fortsetzung der Partie {game}. Ab hier eine Partie gegen Maia {elo}.", + "Continuación de la partida {game}. A partir de aquí, una partida contra Maia {elo}.", + "Seguito della partita {game}. Da qui, una partita contro Maia {elo}.", + "Continuação da partida {game}. A partir daqui, uma partida contra Maia {elo}.", + "{game} o‘yinining davomi. Bundan keyin — Maia {elo} bilan o‘yin.", + "{game} партиÑ�Ñ�ының жалғаÑ�Ñ‹. Бұдан әрі — Maia {elo}-мен ойын.", + ], + [ + "From here on, a game against Maia {elo}.", + "Дальше — игра Ñ� Maia {elo}.", + "À partir d’ici, une partie contre Maia {elo}.", + "Ab hier eine Partie gegen Maia {elo}.", + "A partir de aquí, una partida contra Maia {elo}.", + "Da qui, una partita contro Maia {elo}.", + "A partir daqui, uma partida contra Maia {elo}.", + "Bundan keyin — Maia {elo} bilan o‘yin.", + "Бұдан әрі — Maia {elo}-мен ойын.", + ], + // --- learning an opening --- + [ + "Learning the opening: {game}", + "Учим дебют: {game}", + "Apprentissage de l'ouverture : {game}", + "Eröffnung lernen: {game}", + "Aprendiendo la apertura: {game}", + "Studio dell'apertura: {game}", + "Aprendendo a abertura: {game}", + "Debyutni o‘rganish: {game}", + "Дебютті үйрену: {game}", + ], + [ + "Learning the opening", + "Учим дебют", + "Apprentissage de l'ouverture", + "Eröffnung lernen", + "Aprendiendo la apertura", + "Studio dell'apertura", + "Aprendendo a abertura", + "Debyutni o‘rganish", + "Дебютті үйрену", + ], + [ + "up to {move}", + "до {move}", + "jusqu'à {move}", + "bis {move}", + "hasta {move}", + "fino a {move}", + "até {move}", + "{move} gacha", + "{move} дейін", + ], + [ + "Learn the opening up to this move", + "Учить дебют до Ñ�того хода", + "Apprendre l'ouverture jusqu'à ce coup", + "Eröffnung bis zu diesem Zug lernen", + "Aprender la apertura hasta esta jugada", + "Studia l'apertura fino a questa mossa", + "Aprender a abertura até este lance", + "Debyutni shu yurishgacha o‘rganish", + "Дебютті оÑ�Ñ‹ жүріÑ�ке дейін үйрену", + ], + [ + "Select the move to learn up to", + "Выберите ход, до которого учить", + "Choisissez le coup jusqu'auquel apprendre", + "Wählen Sie den Zug, bis zu dem gelernt wird", + "Elige la jugada hasta la que aprender", + "Scegli la mossa fino a cui studiare", + "Escolha o lance até onde aprender", + "O‘rganiladigan oxirgi yurishni tanlang", + "Үйренетін Ñ�оңғы жүріÑ�ті таңдаңыз", + ], + [ + "The line has a null move (--): it cannot be played on the board", + "Ð’ линии еÑ�ть пропуÑ�к хода (--) — его нельзÑ� Ñ�ыграть на доÑ�ке", + "La ligne contient un coup nul (--) : il ne peut pas être joué sur l'échiquier", + "Die Linie enthält einen Nullzug (--): er kann nicht auf dem Brett gespielt werden", + "La línea tiene una jugada nula (--): no se puede jugar en el tablero", + "La linea contiene una mossa nulla (--): non si può giocare sulla scacchiera", + "A linha tem um lance nulo (--): ele não pode ser jogado no tabuleiro", + "Liniyada bo‘sh yurish (--) bor: uni taxtada o‘ynab bo‘lmaydi", + "ЛиниÑ�да боÑ� жүріÑ� (--) бар: оны тақтада ойнауға болмайды", + ], + [ + "Viewing an earlier position · back to training — End", + "ПроÑ�мотр прошлой позиции · к тренировке — End", + "Position antérieure affichée · retour à l'entraînement — End", + "Frühere Stellung wird angezeigt · zurück zum Training — End", + "Viendo una posición anterior · volver al entrenamiento — End", + "Posizione precedente · torna all'allenamento — End", + "Vendo uma posição anterior · voltar ao treino — End", + "Oldingi pozitsiya ko‘rilmoqda · mashg‘ulotga qaytish — End", + "Бұрынғы позициÑ� көрÑ�етілуде · жаттығуға оралу — End", + ], + [ + "Move {n} of {last}", + "Ход {n} из {last}", + "Coup {n} sur {last}", + "Zug {n} von {last}", + "Jugada {n} de {last}", + "Mossa {n} di {last}", + "Lance {n} de {last}", + "Yurish {n} / {last}", + "ЖүріÑ� {n} / {last}", + ], + [ + "Mistakes: {n}", + "Ошибок: {n}", + "Erreurs : {n}", + "Fehler: {n}", + "Errores: {n}", + "Errori: {n}", + "Erros: {n}", + "Xatolar: {n}", + "Қателер: {n}", + ], + [ + "Run {n}", + "Прохождение {n}", + "Passage {n}", + "Durchgang {n}", + "Repaso {n}", + "Giro {n}", + "Rodada {n}", + "Urinish {n}", + "Әрекет {n}", + ], + [ + "Play the move on the arrow", + "Сделайте ход Ñ�о Ñ�трелки", + "Jouez le coup indiqué par la flèche", + "Spielen Sie den Zug des Pfeils", + "Juega la jugada de la flecha", + "Gioca la mossa indicata dalla freccia", + "Jogue o lance da seta", + "Strelkadagi yurishni qiling", + "КөрÑ�еткідегі жүріÑ�ті жаÑ�аңыз", + ], + [ + "× The game has another move here", + "× Ð’ партии — другой ход", + "× La partie a un autre coup ici", + "× In der Partie folgt hier ein anderer Zug", + "× En la partida hay otra jugada aquí", + "× Nella partita qui c'è un'altra mossa", + "× Na partida há outro lance aqui", + "× Partiyada bu yerda boshqa yurish", + "× ПартиÑ�да мұнда баÑ�қа жүріÑ�", + ], + [ + "Show the move", + "Показать ход", + "Montrer le coup", + "Zug zeigen", + "Mostrar la jugada", + "Mostra la mossa", + "Mostrar o lance", + "Yurishni ko‘rsatish", + "ЖүріÑ�ті көрÑ�ету", + ], + [ + "Not done before", + "Эту линию ещё не проходили", + "Ligne jamais parcourue", + "Diese Linie noch nicht geübt", + "Línea aún no repasada", + "Linea mai ripassata", + "Linha ainda não treinada", + "Bu liniya hali o‘tilmagan", + "Бұл линиÑ� әлі өтілмеген", + ], + [ + "Last time: {n} · clean in a row: {k}", + "Прошлое: {n} · без ошибок подрÑ�д: {k}", + "La dernière fois : {n} · sans erreur d'affilée : {k}", + "Zuletzt: {n} · fehlerfrei in Folge: {k}", + "La última vez: {n} · sin errores seguidos: {k}", + "L'ultima volta: {n} · senza errori di fila: {k}", + "Última vez: {n} · sem erros seguidos: {k}", + "Oxirgi marta: {n} · ketma-ket xatosiz: {k}", + "Соңғы рет: {n} · қатарынан қатеÑ�із: {k}", + ], + [ + "Last time: {n} · best: {m}", + "Прошлое: {n} · лучшее: {m}", + "La dernière fois : {n} · meilleur : {m}", + "Zuletzt: {n} · Bestwert: {m}", + "La última vez: {n} · mejor: {m}", + "L'ultima volta: {n} · migliore: {m}", + "Última vez: {n} · melhor: {m}", + "Oxirgi marta: {n} · eng yaxshi: {m}", + "Соңғы рет: {n} · ең үздігі: {m}", + ], + [ + "Done with a hint · mistakes: {n}", + "Пройдено Ñ� подÑ�казкой · ошибок: {n}", + "Terminé avec un indice · erreurs : {n}", + "Mit Hinweis geschafft · Fehler: {n}", + "Completado con pista · errores: {n}", + "Completato con un aiuto · errori: {n}", + "Concluído com dica · erros: {n}", + "Yordam bilan o‘tildi · xatolar: {n}", + "Көмекпен өтілді · қателер: {n}", + ], + [ + "Done without mistakes", + "Пройдено без ошибок", + "Terminé sans erreur", + "Fehlerfrei geschafft", + "Completado sin errores", + "Completato senza errori", + "Concluído sem erros", + "Xatosiz o‘tildi", + "ҚатеÑ�із өтілді", + ], + [ + "Done · mistakes: {n}", + "Пройдено · ошибок: {n}", + "Terminé · erreurs : {n}", + "Geschafft · Fehler: {n}", + "Completado · errores: {n}", + "Completato · errori: {n}", + "Concluído · erros: {n}", + "O‘tildi · xatolar: {n}", + "Өтілді · қателер: {n}", + ], + [ + "Run {n} · best: {m}", + "Прохождение {n} · лучшее: {m}", + "Passage {n} · meilleur : {m}", + "Durchgang {n} · Bestwert: {m}", + "Repaso {n} · mejor: {m}", + "Giro {n} · migliore: {m}", + "Rodada {n} · melhor: {m}", + "Urinish {n} · eng yaxshi: {m}", + "Әрекет {n} · ең үздігі: {m}", + ], + [ + "clean in a row: {k}", + "без ошибок подрÑ�д: {k}", + "sans erreur d'affilée : {k}", + "fehlerfrei in Folge: {k}", + "sin errores seguidos: {k}", + "senza errori di fila: {k}", + "sem erros seguidos: {k}", + "ketma-ket xatosiz: {k}", + "қатарынан қатеÑ�із: {k}", + ], + [ + "Recent: {runs}", + "ПоÑ�ледние: {runs}", + "Récents : {runs}", + "Letzte: {runs}", + "Recientes: {runs}", + "Recenti: {runs}", + "Recentes: {runs}", + "So‘nggilari: {runs}", + "Соңғылары: {runs}", + ], + [ + "↻ Again", + "↻ Повторить", + "↻ Encore", + "↻ Noch einmal", + "↻ Otra vez", + "↻ Ancora", + "↻ De novo", + "↻ Yana", + "↻ Қайталау", + ], + [ + "⬅ Back to the game", + "⬅ К партии", + "⬅ Retour à la partie", + "⬅ Zurück zur Partie", + "⬅ Volver a la partida", + "⬅ Torna alla partita", + "⬅ Voltar à partida", + "⬅ Partiyaga qaytish", + "⬅ ПартиÑ�ға оралу", + ], + [ + "↻ Restart", + "↻ Сначала", + "↻ Recommencer", + "↻ Neu starten", + "↻ Reiniciar", + "↻ Ricomincia", + "↻ Recomeçar", + "↻ Boshidan", + "↻ БаÑ�ынан", + ], + [ + "Start the run again; this one is not counted", + "Ð�ачать прохождение заново — Ñ�то не заÑ�читываетÑ�Ñ�", + "Recommencer le passage ; celui-ci n'est pas compté", + "Durchgang neu beginnen; dieser wird nicht gezählt", + "Empezar el repaso de nuevo; este no cuenta", + "Ricomincia il giro; questo non viene contato", + "Começar a rodada de novo; esta não conta", + "Urinishni qaytadan boshlash; bu hisobga olinmaydi", + "Әрекетті қайта баÑ�тау; бұл еÑ�ептелмейді", + ], + [ + "× Leave", + "× Выйти", + "× Quitter", + "× Beenden", + "× Salir", + "× Esci", + "× Sair", + "× Chiqish", + "× Шығу", + ], + [ + "Back to the game; the run is not counted (Esc)", + "К партии — прохождение не заÑ�читываетÑ�Ñ� (Esc)", + "Retour à la partie ; le passage n'est pas compté (Esc)", + "Zurück zur Partie; der Durchgang wird nicht gezählt (Esc)", + "Volver a la partida; el repaso no cuenta (Esc)", + "Torna alla partita; il giro non viene contato (Esc)", + "Voltar à partida; a rodada não conta (Esc)", + "Partiyaga qaytish; urinish hisobga olinmaydi (Esc)", + "ПартиÑ�ға оралу; әрекет еÑ�ептелмейді (Esc)", + ], + [ + "The engine is off while training", + "Во времÑ� тренировки движок выключен", + "Le moteur est désactivé pendant l'entraînement", + "Die Engine ist während des Trainings aus", + "El motor está apagado durante el entrenamiento", + "Il motore è spento durante l'allenamento", + "O motor fica desligado durante o treino", + "Mashg‘ulot paytida dvigatel o‘chiq", + "Жаттығу кезінде қозғалтқыш өшірулі", + ], + [ + "Mistakes: {n}; the move was shown", + "Ошибок: {n}, ход показан", + "Erreurs : {n} ; le coup a été montré", + "Fehler: {n}; der Zug wurde gezeigt", + "Errores: {n}; se mostró la jugada", + "Errori: {n}; la mossa è stata mostrata", + "Erros: {n}; o lance foi mostrado", + "Xatolar: {n}; yurish ko‘rsatildi", + "Қателер: {n}; жүріÑ� көрÑ�етілді", + ], + [ + "Mistakes on this move: {n}", + "Ошибок на Ñ�том ходу: {n}", + "Erreurs sur ce coup : {n}", + "Fehler bei diesem Zug: {n}", + "Errores en esta jugada: {n}", + "Errori su questa mossa: {n}", + "Erros neste lance: {n}", + "Shu yurishdagi xatolar: {n}", + "ОÑ�Ñ‹ жүріÑ�тегі қателер: {n}", + ], + [ + "runs: {n}", + "прохождений: {n}", + "passages : {n}", + "Durchgänge: {n}", + "repasos: {n}", + "giri: {n}", + "rodadas: {n}", + "urinishlar: {n}", + "әрекеттер: {n}", + ], + [ + "Replay from memory the moves of both sides from the start of the game up to this move", + "Повторите по памÑ�ти ходы обеих Ñ�торон от начала партии до Ñ�того хода", + "Rejouez de mémoire les coups des deux camps depuis le début de la partie jusqu'à ce coup", + "Spielen Sie die Züge beider Seiten vom Partiebeginn bis zu diesem Zug aus dem Gedächtnis nach", + "Repite de memoria las jugadas de ambos bandos desde el inicio de la partida hasta esta jugada", + "Ripeti a memoria le mosse di entrambi i lati dall'inizio della partita fino a questa mossa", + "Repita de memória os lances dos dois lados desde o início da partida até este lance", + "Partiya boshidan shu yurishgacha ikkala tomonning yurishlarini yoddan takrorlang", + "ПартиÑ� баÑ�ынан оÑ�Ñ‹ жүріÑ�ке дейін екі жақтың жүріÑ�терін жатқа қайталаңыз", + ], + [ + "The same position, you play White again", + "Та же позициÑ�, вы Ñ�нова за белых", + "La même position, vous jouez de nouveau les Blancs", + "Dieselbe Stellung, Sie spielen wieder Weiß", + "La misma posición, vuelves a jugar con blancas", + "La stessa posizione, giochi di nuovo con il Bianco", + "A mesma posição, você joga de novo de brancas", + "O‘sha pozitsiya, yana oqlar bilan o‘ynaysiz", + "Сол позициÑ�, Ñ�із қайтадан ақтармен ойнайÑ�ыз", + ], + [ + "The same position, you play Black again", + "Та же позициÑ�, вы Ñ�нова за чёрных", + "La même position, vous jouez de nouveau les Noirs", + "Dieselbe Stellung, Sie spielen wieder Schwarz", + "La misma posición, vuelves a jugar con negras", + "La stessa posizione, giochi di nuovo con il Nero", + "A mesma posição, você joga de novo de pretas", + "O‘sha pozitsiya, yana qoralar bilan o‘ynaysiz", + "Сол позициÑ�, Ñ�із қайтадан қаралармен ойнайÑ�ыз", + ], + [ + "â�¸ Put aside", + "â�¸ Отложить", + "â�¸ Ajourner", + "â�¸ Vertagen", + "â�¸ Aplazar", + "â�¸ Rinvia", + "â�¸ Adiar", + "â�¸ Keyinga qoldirish", + "â�¸ Кейінге қалдыру", + ], + [ + "Put aside", + "Отложить", + "Ajourner", + "Vertagen", + "Aplazar", + "Rinvia", + "Adiar", + "Keyinga qoldirish", + "Кейінге қалдыру", + ], + [ + "Put the game aside: the clocks stop; go on from its card in the library", + "Отложить партию: чаÑ�Ñ‹ оÑ�тановÑ�Ñ‚Ñ�Ñ�, продолжить можно Ñ� карточки в библиотеке", + "Ajourner la partie : les pendules s'arrêtent ; reprenez-la depuis sa carte dans la bibliothèque", + "Partie vertagen: Die Uhren halten an; weiter geht es über ihre Karte in der Bibliothek", + "Aplazar la partida: los relojes se detienen; continúa desde su tarjeta en la biblioteca", + "Rinvia la partita: gli orologi si fermano; riprendila dalla sua scheda nella biblioteca", + "Adiar a partida: os relógios param; continue pelo cartão dela na biblioteca", + "O‘yinni keyinga qoldirish: soatlar to‘xtaydi; kutubxonadagi kartasidan davom ettiring", + "Ойынды кейінге қалдыру: Ñ�ағаттар тоқтайды; кітапханадағы карточкаÑ�ынан жалғаÑ�тырыңыз", + ], + [ + "Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends and is written to «{db}».", + "Отложите партию — чаÑ�Ñ‹ оÑ�тановÑ�Ñ‚Ñ�Ñ�, а продолжить её можно Ñ� карточки в библиотеке. ЕÑ�ли Ñ�датьÑ�Ñ�, партиÑ� закончитÑ�Ñ� и запишетÑ�Ñ� в «{db}».", + "Ajournez la partie : les pendules s'arrêtent et vous pourrez la reprendre depuis sa carte dans la bibliothèque. Si vous abandonnez, la partie se termine et est enregistrée dans « {db} ».", + "Vertagen Sie die Partie: Die Uhren halten an, und Sie können über ihre Karte in der Bibliothek weiterspielen. Wenn Sie aufgeben, endet die Partie und wird in „{db}“ geschrieben.", + "Aplaza la partida: los relojes se detienen y podrás continuarla desde su tarjeta en la biblioteca. Si abandonas, la partida termina y se guarda en «{db}».", + "Rinvia la partita: gli orologi si fermano e potrai riprenderla dalla sua scheda nella biblioteca. Se abbandoni, la partita finisce e viene scritta in «{db}».", + "Adie a partida: os relógios param e você pode continuá-la pelo cartão dela na biblioteca. Se abandonar, a partida termina e é gravada em «{db}».", + "O‘yinni keyinga qoldiring: soatlar to‘xtaydi, uni kutubxonadagi kartasidan davom ettirish mumkin. Taslim bo‘lsangiz, o‘yin tugaydi va «{db}» ga yoziladi.", + "Ойынды кейінге қалдырыңыз: Ñ�ағаттар тоқтайды, оны кітапханадағы карточкаÑ�ынан жалғаÑ�тыруға болады. БерілÑ�еңіз, ойын аÑ�қталып, «{db}» ішіне жазылады.", + ], + [ + "Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends.", + "Отложите партию — чаÑ�Ñ‹ оÑ�тановÑ�Ñ‚Ñ�Ñ�, а продолжить её можно Ñ� карточки в библиотеке. ЕÑ�ли Ñ�датьÑ�Ñ�, партиÑ� закончитÑ�Ñ� вашей Ñ�дачей.", + "Ajournez la partie : les pendules s'arrêtent et vous pourrez la reprendre depuis sa carte dans la bibliothèque. Si vous abandonnez, la partie se termine.", + "Vertagen Sie die Partie: Die Uhren halten an, und Sie können über ihre Karte in der Bibliothek weiterspielen. Wenn Sie aufgeben, endet die Partie.", + "Aplaza la partida: los relojes se detienen y podrás continuarla desde su tarjeta en la biblioteca. Si abandonas, la partida termina.", + "Rinvia la partita: gli orologi si fermano e potrai riprenderla dalla sua scheda nella biblioteca. Se abbandoni, la partita finisce.", + "Adie a partida: os relógios param e você pode continuá-la pelo cartão dela na biblioteca. Se abandonar, a partida termina.", + "O‘yinni keyinga qoldiring: soatlar to‘xtaydi, uni kutubxonadagi kartasidan davom ettirish mumkin. Taslim bo‘lsangiz, o‘yin tugaydi.", + "Ойынды кейінге қалдырыңыз: Ñ�ағаттар тоқтайды, оны кітапханадағы карточкаÑ�ынан жалғаÑ�тыруға болады. БерілÑ�еңіз, ойын аÑ�қталады.", + ], + [ + "you play white", + "вы белыми", + "vous avez les Blancs", + "Sie spielen Weiß", + "juegas con blancas", + "giochi con il Bianco", + "você joga de brancas", + "siz oqlar bilan", + "Ñ�із ақтармен", + ], + [ + "you play black", + "вы чёрными", + "vous avez les Noirs", + "Sie spielen Schwarz", + "juegas con negras", + "giochi con il Nero", + "você joga de pretas", + "siz qoralar bilan", + "Ñ�із қаралармен", + ], + [ + "move {n}", + "{n}-й ход", + "coup {n}", + "Zug {n}", + "jugada {n}", + "mossa {n}", + "lance {n}", + "{n}-yurish", + "{n}-жүріÑ�", + ], + [ + "you {t}", + "вы {t}", + "vous {t}", + "Sie {t}", + "tú {t}", + "tu {t}", + "você {t}", + "siz {t}", + "Ñ�із {t}", + ], + [ + "no clock", + "без чаÑ�ов", + "sans pendule", + "ohne Uhr", + "sin reloj", + "senza orologio", + "sem relógio", + "soatsiz", + "Ñ�ағатÑ�ыз", + ], + [ + "move {n}, yours", + "{n}-й ход, ваш", + "coup {n}, à vous", + "Zug {n}, Sie sind am Zug", + "jugada {n}, te toca", + "mossa {n}, tocca a te", + "lance {n}, sua vez", + "{n}-yurish, sizniki", + "{n}-жүріÑ�, Ñ�іздікі", + ], + [ + "move {n}, {rival} to move", + "{n}-й ход, ход {rival}", + "coup {n}, au tour de {rival}", + "Zug {n}, {rival} ist am Zug", + "jugada {n}, le toca a {rival}", + "mossa {n}, tocca a {rival}", + "lance {n}, vez de {rival}", + "{n}-yurish, {rival} navbati", + "{n}-жүріÑ�, {rival} кезегі", + ], + [ + "Game against {rival}", + "ПартиÑ� Ñ� {rival}", + "Partie contre {rival}", + "Partie gegen {rival}", + "Partida contra {rival}", + "Partita contro {rival}", + "Partida contra {rival}", + "{rival} bilan o‘yin", + "{rival} қарÑ�Ñ‹ ойын", + ], + [ + "Put aside {when}", + "Отложена {when}", + "Ajournée le {when}", + "Vertagt am {when}", + "Aplazada el {when}", + "Rinviata il {when}", + "Adiada em {when}", + "Qoldirilgan: {when}", + "Қалдырылған: {when}", + ], + [ + "Click, or Ctrl+G, Enter", + "Щелчок или Ctrl+G, Enter", + "Clic, ou Ctrl+G, Entrée", + "Klick, oder Strg+G, Enter", + "Clic, o Ctrl+G, Intro", + "Clic, oppure Ctrl+G, Invio", + "Clique, ou Ctrl+G, Enter", + "Bosish yoki Ctrl+G, Enter", + "БаÑ�у немеÑ�е Ctrl+G, Enter", + ], + [ + "Don't finish it: the game is written to «{db}» unfinished", + "Ð�е доигрывать: партиÑ� запишетÑ�Ñ� в «{db}» неоконченной", + "Ne pas la finir : la partie est enregistrée dans « {db} » inachevée", + "Nicht zu Ende spielen: Die Partie wird unbeendet in „{db}“ geschrieben", + "No terminarla: la partida se guarda en «{db}» sin terminar", + "Non finirla: la partita viene scritta in «{db}» non finita", + "Não terminar: a partida é gravada em «{db}» inacabada", + "Tugatmaslik: o‘yin «{db}» ga tugallanmagan holda yoziladi", + "Ð�Ñ�қтамау: ойын «{db}» ішіне аÑ�қталмаған күйде жазылады", + ], + [ + "Don't finish it: the game is deleted", + "Ð�е доигрывать: партиÑ� будет удалена", + "Ne pas la finir : la partie est supprimée", + "Nicht zu Ende spielen: Die Partie wird gelöscht", + "No terminarla: la partida se elimina", + "Non finirla: la partita viene eliminata", + "Não terminar: a partida é excluída", + "Tugatmaslik: o‘yin o‘chiriladi", + "Ð�Ñ�қтамау: ойын жойылады", + ], + [ + "The program closed during a game: the game is put aside, you can go on with it", + "Программа закрылаÑ�ÑŒ поÑ�реди партии — партиÑ� отложена, её можно продолжить", + "Le programme s'est fermé pendant une partie : elle est ajournée, vous pouvez la reprendre", + "Das Programm wurde während einer Partie beendet: Die Partie ist vertagt, Sie können weiterspielen", + "El programa se cerró durante una partida: la partida está aplazada, puedes continuarla", + "Il programma si è chiuso durante una partita: la partita è rinviata, puoi riprenderla", + "O programa fechou durante uma partida: a partida foi adiada, você pode continuá-la", + "Dastur o‘yin vaqtida yopildi: o‘yin keyinga qoldirildi, uni davom ettirish mumkin", + "Бағдарлама ойын кезінде жабылды: ойын кейінге қалдырылды, оны жалғаÑ�тыруға болады", + ], + [ + "The game could not be put aside: its file could not be written", + "Партию не удалоÑ�ÑŒ отложить: не запиÑ�алÑ�Ñ� её файл", + "Impossible d'ajourner la partie : son fichier n'a pas pu être écrit", + "Die Partie konnte nicht vertagt werden: Ihre Datei ließ sich nicht schreiben", + "No se pudo aplazar la partida: no se pudo escribir su archivo", + "Impossibile rinviare la partita: non è stato possibile scrivere il suo file", + "Não foi possível adiar a partida: o arquivo dela não pôde ser gravado", + "O‘yinni keyinga qoldirib bo‘lmadi: uning fayli yozilmadi", + "Ойынды кейінге қалдыру мүмкін болмады: оның файлы жазылмады", + ], + [ + "Game written to «{db}» unfinished, No. {n}", + "ПартиÑ� запиÑ�ана в «{db}» неоконченной, â„– {n}", + "Partie enregistrée dans « {db} » inachevée, n° {n}", + "Partie unbeendet in „{db}“ geschrieben, Nr. {n}", + "Partida guardada en «{db}» sin terminar, n.º {n}", + "Partita scritta in «{db}» non finita, n. {n}", + "Partida gravada em «{db}» inacabada, nº {n}", + "O‘yin «{db}» ga tugallanmagan holda yozildi, â„– {n}", + "Ойын «{db}» ішіне аÑ�қталмаған күйде жазылды, â„– {n}", + ], + [ + "The game put aside could not be read", + "Отложенную партию не удалоÑ�ÑŒ прочитать", + "Impossible de lire la partie ajournée", + "Die vertagte Partie ließ sich nicht lesen", + "No se pudo leer la partida aplazada", + "Impossibile leggere la partita rinviata", + "Não foi possível ler a partida adiada", + "Qoldirilgan o‘yinni o‘qib bo‘lmadi", + "Қалдырылған ойынды оқу мүмкін болмады", + ], + [ + "There is a game put aside", + "ЕÑ�ть отложеннаÑ� партиÑ�", + "Une partie est ajournée", + "Es gibt eine vertagte Partie", + "Hay una partida aplazada", + "C'è una partita rinviata", + "Há uma partida adiada", + "Keyinga qoldirilgan o‘yin bor", + "Кейінге қалдырылған ойын бар", + ], + [ + "A new game replaces it; the one put aside is written to «{db}» unfinished.", + "Ð�оваÑ� партиÑ� заменит её; отложеннаÑ� запишетÑ�Ñ� в «{db}» неоконченной.", + "Une nouvelle partie la remplace ; la partie ajournée est enregistrée dans « {db} » inachevée.", + "Eine neue Partie ersetzt sie; die vertagte wird unbeendet in „{db}“ geschrieben.", + "Una partida nueva la sustituye; la aplazada se guarda en «{db}» sin terminar.", + "Una nuova partita la sostituisce; quella rinviata viene scritta in «{db}» non finita.", + "Uma nova partida a substitui; a adiada é gravada em «{db}» inacabada.", + "Yangi o‘yin uning o‘rnini oladi; qoldirilgani «{db}» ga tugallanmagan holda yoziladi.", + "Жаңа ойын оның орнын баÑ�ады; қалдырылғаны «{db}» ішіне аÑ�қталмаған күйде жазылады.", + ], + [ + "A new game replaces it: the one put aside is deleted.", + "Ð�оваÑ� партиÑ� заменит её: отложеннаÑ� будет удалена.", + "Une nouvelle partie la remplace : la partie ajournée est supprimée.", + "Eine neue Partie ersetzt sie: Die vertagte wird gelöscht.", + "Una partida nueva la sustituye: la aplazada se elimina.", + "Una nuova partita la sostituisce: quella rinviata viene eliminata.", + "Uma nova partida a substitui: a adiada é excluída.", + "Yangi o‘yin uning o‘rnini oladi: qoldirilgani o‘chiriladi.", + "Жаңа ойын оның орнын баÑ�ады: қалдырылғаны жойылады.", + ], + [ + "Continue it", + "Продолжить её", + "La reprendre", + "Weiterspielen", + "Continuarla", + "Riprenderla", + "Continuá-la", + "Davom ettirish", + "ЖалғаÑ�тыру", + ], + [ + "Start a new one", + "Ð�ачать новую", + "En commencer une nouvelle", + "Neue beginnen", + "Empezar una nueva", + "Iniziarne una nuova", + "Começar uma nova", + "Yangisini boshlash", + "ЖаңаÑ�ын баÑ�тау", + ], + [ + "Delete the game put aside?", + "Удалить отложенную партию?", + "Supprimer la partie ajournée ?", + "Die vertagte Partie löschen?", + "¿Eliminar la partida aplazada?", + "Eliminare la partita rinviata?", + "Excluir a partida adiada?", + "Qoldirilgan o‘yin o‘chirilsinmi?", + "Қалдырылған ойын жойылÑ�ын ба?", + ], + [ + "Games are not written into a database: it is not kept anywhere.", + "Партии не запиÑ�ываютÑ�Ñ� в базу: она нигде не Ñ�охранитÑ�Ñ�.", + "Les parties ne sont pas enregistrées dans une base : elle n'est conservée nulle part.", + "Partien werden in keine Datenbank geschrieben: Sie wird nirgends aufbewahrt.", + "Las partidas no se guardan en una base: no se conservará en ningún sitio.", + "Le partite non vengono scritte in un database: non sarà conservata da nessuna parte.", + "As partidas não são gravadas em uma base: ela não fica guardada em lugar nenhum.", + "O‘yinlar bazaga yozilmaydi: u hech qayerda saqlanmaydi.", + "Ойындар базаға жазылмайды: ол ешқайда Ñ�ақталмайды.", + ], + [ + "Game put aside: go on from the library", + "ПартиÑ� отложена — продолжить можно в библиотеке", + "Partie ajournée : reprenez-la depuis la bibliothèque", + "Partie vertagt: weiter geht es in der Bibliothek", + "Partida aplazada: continúa desde la biblioteca", + "Partita rinviata: riprendila dalla biblioteca", + "Partida adiada: continue pela biblioteca", + "O‘yin keyinga qoldirildi: kutubxonadan davom ettiring", + "Ойын кейінге қалдырылды: кітапханадан жалғаÑ�тырыңыз", + ], + [ + "The opponent of this game is not installed", + "Соперник Ñ�той партии не уÑ�тановлен", + "L'adversaire de cette partie n'est pas installé", + "Der Gegner dieser Partie ist nicht installiert", + "El rival de esta partida no está instalado", + "L'avversario di questa partita non è installato", + "O adversário desta partida não está instalado", + "Bu o‘yinning raqibi o‘rnatilmagan", + "Бұл ойынның қарÑ�ылаÑ�Ñ‹ орнатылмаған", + ], + [ + "Game put aside", + "ОтложеннаÑ� партиÑ�", + "Partie ajournée", + "Vertagte Partie", + "Partida aplazada", + "Partita rinviata", + "Partida adiada", + "Keyinga qoldirilgan o‘yin", + "Кейінге қалдырылған ойын", + ], + [ + "Opening errors are being searched — wait or stop it in the report", + "Идёт поиÑ�к ошибок в дебютах — дождитеÑ�ÑŒ или оÑ�тановите его в отчёте", + "La recherche d'erreurs d'ouverture est en cours — attendez ou arrêtez-la dans le rapport", + "Die Suche nach Eröffnungsfehlern läuft — warten Sie oder stoppen Sie sie im Bericht", + "Se están buscando errores de apertura — espere o deténgala en el informe", + "È in corso la ricerca degli errori di apertura — attendi o fermala nel rapporto", + "A busca de erros de abertura está em andamento — aguarde ou pare-a no relatório", + "Debyut xatolari qidirilmoqda — kuting yoki hisobotda to‘xtating", + "Дебют қателері ізделуде — күтіңіз немеÑ�е еÑ�епте тоқтатыңыз", + ], + [ + "⬅ Back to preparation", + "⬅ К подготовке", + "⬅ Retour à la préparation", + "⬅ Zurück zur Vorbereitung", + "⬅ Volver a la preparación", + "⬅ Torna alla preparazione", + "⬅ Voltar à preparação", + "⬅ Tayyorgarlikka qaytish", + "⬅ Дайындыққа оралу", + ], + [ + "♟ Prepare against an opponent…", + "♟ ПодготовитьÑ�Ñ� к Ñ�опернику…", + "♟ Se préparer contre un adversaire…", + "♟ Auf einen Gegner vorbereiten…", + "♟ Prepararse contra un rival…", + "♟ Prepararsi contro un avversario…", + "♟ Preparar-se contra um adversário…", + "♟ Raqibga tayyorlanish…", + "♟ ҚарÑ�ылаÑ�қа дайындалу…", + ], + [ + "The player's openings by colour, with names, and the opening errors the engine finds (Ctrl+Shift+P)", + "Дебюты игрока по цветам, Ñ� названиÑ�ми, и ошибки в дебюте, которые находит движок (Ctrl+Shift+P)", + "Les ouvertures du joueur par couleur, avec leurs noms, et les erreurs d'ouverture trouvées par le moteur (Ctrl+Maj+P)", + "Die Eröffnungen des Spielers nach Farbe, mit Namen, und die Eröffnungsfehler, die die Engine findet (Strg+Umschalt+P)", + "Las aperturas del jugador por color, con nombres, y los errores de apertura que encuentra el motor (Ctrl+Mayús+P)", + "Le aperture del giocatore per colore, con i nomi, e gli errori di apertura trovati dal motore (Ctrl+Maiusc+P)", + "As aberturas do jogador por cor, com nomes, e os erros de abertura que o motor encontra (Ctrl+Shift+P)", + "O‘yinchining ranglar bo‘yicha debyutlari, nomlari bilan, va dvijok topgan debyut xatolari (Ctrl+Shift+P)", + "Ойыншының түÑ�тер бойынша дебюттері, атауларымен, және қозғалтқыш тапқан дебют қателері (Ctrl+Shift+P)", + ], + [ + "♟ Prepare against {name}…", + "♟ ПодготовитьÑ�Ñ� к {name}…", + "♟ Se préparer contre {name}…", + "♟ Auf {name} vorbereiten…", + "♟ Prepararse contra {name}…", + "♟ Prepararsi contro {name}…", + "♟ Preparar-se contra {name}…", + "♟ {name} ga tayyorlanish…", + "♟ {name} қарÑ�ылаÑ�ына дайындалу…", + ], + [ + "Stockfish installed — the search for opening errors started", + "Stockfish уÑ�тановлен — поиÑ�к ошибок в дебютах начат", + "Stockfish installé — la recherche d'erreurs d'ouverture a commencé", + "Stockfish installiert — die Suche nach Eröffnungsfehlern hat begonnen", + "Stockfish instalado — la búsqueda de errores de apertura ha comenzado", + "Stockfish installato — la ricerca degli errori di apertura è iniziata", + "Stockfish instalado — a busca de erros de abertura começou", + "Stockfish o‘rnatildi — debyut xatolarini qidirish boshlandi", + "Stockfish орнатылды — дебют қателерін іздеу баÑ�талды", + ], + [ + "The search for opening errors will start by itself when the download finishes.", + "ПоиÑ�к ошибок в дебютах начнётÑ�Ñ� Ñ�ам, когда загрузка закончитÑ�Ñ�.", + "La recherche d'erreurs d'ouverture démarrera d'elle-même à la fin du téléchargement.", + "Die Suche nach Eröffnungsfehlern startet von selbst, wenn der Download fertig ist.", + "La búsqueda de errores de apertura empezará sola cuando termine la descarga.", + "La ricerca degli errori di apertura partirà da sola al termine del download.", + "A busca de erros de abertura começará sozinha quando o download terminar.", + "Yuklab olish tugagach debyut xatolarini qidirish o‘zi boshlanadi.", + "Жүктеу аÑ�қталғанда дебют қателерін іздеу өзі баÑ�талады.", + ], + [ + "Both", + "Оба", + "Les deux", + "Beide", + "Ambos", + "Entrambi", + "Ambas", + "Ikkalasi", + "Екеуі", + ], + [ + "None", "Ð�ет", "Aucun", "Keines", "Ninguno", "Nessuno", "Nenhum", "Yo‘q", "Жоқ", + ], + [ + "Preparing against an opponent", + "Подготовка к Ñ�опернику", + "Préparation contre un adversaire", + "Vorbereitung auf einen Gegner", + "Preparación contra un rival", + "Preparazione contro un avversario", + "Preparação contra um adversário", + "Raqibga tayyorgarlik", + "ҚарÑ�ылаÑ�қа дайындық", + ], + [ + "Name or part of it", + "ИмÑ� или его чаÑ�ть", + "Nom ou une partie", + "Name oder ein Teil davon", + "Nombre o parte de él", + "Nome o parte di esso", + "Nome ou parte dele", + "Ism yoki uning qismi", + "Ð�ты немеÑ�е оның бөлігі", + ], + [ + "Colour", "Цвет", "Couleur", "Farbe", "Color", "Colore", "Cor", "Rang", "ТүÑ�", + ], + [ + "Book", + "Книга", + "Livre", + "Buch", + "Libro", + "Libro", + "Livro", + "Kitob", + "Кітап", + ], + [ + "Open report", + "Открыть отчёт", + "Ouvrir le rapport", + "Bericht öffnen", + "Abrir informe", + "Apri rapporto", + "Abrir relatório", + "Hisobotni ochish", + "ЕÑ�епті ашу", + ], + [ + "Tick a player", + "Отметьте игрока", + "Cochez un joueur", + "Wählen Sie einen Spieler", + "Marque un jugador", + "Spunta un giocatore", + "Marque um jogador", + "O‘yinchini belgilang", + "Ойыншыны белгілеңіз", + ], + [ + "Searching…", + "Ищу…", + "Recherche…", + "Suche…", + "Buscando…", + "Ricerca…", + "Procurando…", + "Qidirilmoqda…", + "Ізделуде…", + ], + [ + "Type a name: the players of the database are offered", + "Введите имÑ�: будут предложены игроки базы", + "Tapez un nom : les joueurs de la base sont proposés", + "Geben Sie einen Namen ein: die Spieler der Datenbank werden angeboten", + "Escriba un nombre: se ofrecen los jugadores de la base", + "Digita un nome: vengono proposti i giocatori del database", + "Digite um nome: os jogadores da base são sugeridos", + "Ism kiriting: bazadagi o‘yinchilar taklif qilinadi", + "Ð�тын теріңіз: базадағы ойыншылар Ò±Ñ�ынылады", + ], + [ + "No such player in this database", + "Ð’ Ñ�той базе нет такого игрока", + "Aucun joueur de ce nom dans cette base", + "Kein solcher Spieler in dieser Datenbank", + "No hay tal jugador en esta base", + "Nessun giocatore così in questo database", + "Não há tal jogador nesta base", + "Bu bazada bunday o‘yinchi yo‘q", + "Бұл базада мұндай ойыншы жоқ", + ], + [ + "Similar names — most likely other people", + "Похожие имена — Ñ�корее вÑ�его, другие люди", + "Noms proches — probablement d'autres personnes", + "Ähnliche Namen — wahrscheinlich andere Personen", + "Nombres parecidos — probablemente otras personas", + "Nomi simili — probabilmente altre persone", + "Nomes parecidos — provavelmente outras pessoas", + "O‘xshash ismlar — ehtimol boshqa odamlar", + "Ò°Ò›Ñ�аÑ� еÑ�імдер — бәлкім, баÑ�қа адамдар", + ], + [ + "The games could not be read", + "Партии не удалоÑ�ÑŒ прочитать", + "Les parties n'ont pas pu être lues", + "Die Partien konnten nicht gelesen werden", + "No se pudieron leer las partidas", + "Impossibile leggere le partite", + "Não foi possível ler as partidas", + "Partiyalarni o‘qib bo‘lmadi", + "ПартиÑ�ларды оқу мүмкін болмады", + ], + [ + "Opening errors", + "Ошибки в дебютах", + "Erreurs d'ouverture", + "Eröffnungsfehler", + "Errores de apertura", + "Errori di apertura", + "Erros de abertura", + "Debyut xatolari", + "Дебют қателері", + ], + [ + "identical positions are counted once", + "одинаковые позиции Ñ�читаютÑ�Ñ� один раз", + "les positions identiques ne sont comptées qu'une fois", + "gleiche Stellungen werden einmal gezählt", + "las posiciones idénticas se cuentan una vez", + "le posizioni identiche si contano una volta", + "posições idênticas são contadas uma vez", + "bir xil pozitsiyalar bir marta hisoblanadi", + "бірдей позициÑ�лар бір рет Ñ�аналады", + ], + [ + "Find errors", + "Ð�айти ошибки", + "Chercher les erreurs", + "Fehler suchen", + "Buscar errores", + "Trova errori", + "Procurar erros", + "Xatolarni topish", + "Қателерді табу", + ], + [ + "Settings (Ctrl+,)", + "Ð�аÑ�тройки (Ctrl+,)", + "Paramètres (Ctrl+,)", + "Einstellungen (Strg+,)", + "Ajustes (Ctrl+,)", + "Impostazioni (Ctrl+,)", + "Configurações (Ctrl+,)", + "Sozlamalar (Ctrl+,)", + "Баптаулар (Ctrl+,)", + ], + [ + "How deep the tree and the engine look", + "Как глубоко Ñ�мотрÑ�Ñ‚ дерево и движок", + "Profondeur de l'arbre et du moteur", + "Wie tief Baum und Engine schauen", + "Hasta dónde miran el árbol y el motor", + "Quanto in profondità guardano l'albero e il motore", + "Até onde a árvore e o motor olham", + "Daraxt va dvijok qanchalik chuqur qaraydi", + "Ð�ғаш пен қозғалтқыш қаншалықты терең қарайды", + ], + [ + "The board of the chosen position", + "ДоÑ�ка выбранной позиции", + "L'échiquier de la position choisie", + "Das Brett der gewählten Stellung", + "El tablero de la posición elegida", + "La scacchiera della posizione scelta", + "O tabuleiro da posição escolhida", + "Tanlangan pozitsiya taxtasi", + "Таңдалған позициÑ� тақтаÑ�Ñ‹", + ], + [ + "Errors found", + "Ошибки найдены", + "Erreurs trouvées", + "Fehler gefunden", + "Errores encontrados", + "Errori trovati", + "Erros encontrados", + "Xatolar topildi", + "Қателер табылды", + ], + [ + "The engine finds the opening errors in his games (Shift+A)", + "Движок находит ошибки в дебютах его партий (Shift+A)", + "Le moteur trouve les erreurs d'ouverture dans ses parties (Maj+A)", + "Die Engine findet die Eröffnungsfehler in seinen Partien (Umschalt+A)", + "El motor encuentra los errores de apertura en sus partidas (Mayús+A)", + "Il motore trova gli errori di apertura nelle sue partite (Maiusc+A)", + "O motor encontra os erros de abertura nas partidas dele (Shift+A)", + "Dvijok uning partiyalaridagi debyut xatolarini topadi (Shift+A)", + "Қозғалтқыш оның партиÑ�ларындағы дебют қателерін табады (Shift+A)", + ], + [ + "Options…", + "Параметры…", + "Options…", + "Optionen…", + "Opciones…", + "Opzioni…", + "Opções…", + "Parametrlar…", + "Параметрлер…", + ], + [ + "As White", + "Белыми", + "Avec les Blancs", + "Mit Weiß", + "Con blancas", + "Con il Bianco", + "De brancas", + "Oq bilan", + "Ð�қпен", + ], + [ + "As Black", + "Чёрными", + "Avec les Noirs", + "Mit Schwarz", + "Con negras", + "Con il Nero", + "De pretas", + "Qora bilan", + "Қарамен", + ], + [ + "No engine yet. Stockfish finds the opening errors in his games; add it to start the search.", + "Движка пока нет. Stockfish ищет ошибки в его дебютах; добавьте его, чтобы начать поиÑ�к.", + "Pas encore de moteur. Stockfish trouve les erreurs d’ouverture de ses parties ; ajoutez-le pour lancer la recherche.", + "Noch keine Engine. Stockfish findet die Eröffnungsfehler in seinen Partien; fügen Sie sie hinzu, um die Suche zu starten.", + "Aún no hay motor. Stockfish encuentra los errores de apertura de sus partidas; añádelo para empezar la búsqueda.", + "Ancora nessun motore. Stockfish trova gli errori di apertura delle sue partite; aggiungilo per iniziare la ricerca.", + "Ainda não há motor. O Stockfish encontra os erros de abertura das suas partidas; adicione-o para começar a procura.", + "Hali dvijok yo‘q. Stockfish uning partiyalaridagi debyut xatolarini topadi; qidiruvni boshlash uchun uni qo‘shing.", + "Әзірге движок жоқ. Stockfish оның партиÑ�ларындағы дебют қателерін табады; іздеуді баÑ�тау үшін оны қоÑ�ыңыз.", + ], + [ + "Choose a move in the tree, an opening or an error: its position is shown here", + "Выберите ход в дереве, дебют или ошибку: здеÑ�ÑŒ будет его позициÑ�", + "Choisissez un coup dans l'arbre, une ouverture ou une erreur : sa position s'affiche ici", + "Wählen Sie einen Zug im Baum, eine Eröffnung oder einen Fehler: seine Stellung erscheint hier", + "Elija una jugada del árbol, una apertura o un error: su posición se muestra aquí", + "Scegli una mossa nell'albero, un'apertura o un errore: la sua posizione appare qui", + "Escolha um lance na árvore, uma abertura ou um erro: a posição aparece aqui", + "Daraxtdan yurish, debyut yoki xatoni tanlang: uning pozitsiyasi shu yerda ko‘rinadi", + "Ð�ғаштан жүріÑ�, дебют немеÑ�е қате таңдаңыз: оның позициÑ�Ñ�Ñ‹ оÑ�ында көрінеді", + ], + [ + "Open as a game", + "Открыть как партию", + "Ouvrir comme partie", + "Als Partie öffnen", + "Abrir como partida", + "Apri come partita", + "Abrir como partida", + "Partiya sifatida ochish", + "ПартиÑ� ретінде ашу", + ], + [ + "The line as a new game, to add moves and comments", + "ЛиниÑ� как новаÑ� партиÑ� — чтобы допиÑ�ать ходы и комментарии", + "La ligne comme nouvelle partie, pour ajouter des coups et des commentaires", + "Die Linie als neue Partie, um Züge und Kommentare hinzuzufügen", + "La línea como partida nueva, para añadir jugadas y comentarios", + "La linea come nuova partita, per aggiungere mosse e commenti", + "A linha como nova partida, para acrescentar lances e comentários", + "Chiziq yangi partiya sifatida — yurishlar va izohlar qo‘shish uchun", + "Желі жаңа партиÑ� ретінде — жүріÑ�тер мен түÑ�ініктемелер қоÑ�у үшін", + ], + [ + "Repertoire", + "Репертуар", + "Répertoire", + "Repertoire", + "Repertorio", + "Repertorio", + "Repertório", + "Repertuar", + "Репертуар", + ], + [ + "Openings", + "Дебюты", + "Ouvertures", + "Eröffnungen", + "Aperturas", + "Aperture", + "Aberturas", + "Debyutlar", + "Дебюттер", + ], + [ + "Errors", + "Ошибки", + "Erreurs", + "Fehler", + "Errores", + "Errori", + "Erros", + "Xatolar", + "Қателер", + ], + [ + "Collapse", + "Свернуть", + "Replier", + "Einklappen", + "Contraer", + "Comprimi", + "Recolher", + "Yig‘ish", + "Жию", + ], + [ + "Expand all", + "РаÑ�крыть вÑ�Ñ‘", + "Tout déplier", + "Alles ausklappen", + "Expandir todo", + "Espandi tutto", + "Expandir tudo", + "Hammasini yoyish", + "Барлығын жаю", + ], + [ + "Moves with fewer games fold into «other moves»", + "Ходы Ñ� меньшим чиÑ�лом партий Ñ�ворачиваютÑ�Ñ� в «другие ходы»", + "Les coups avec moins de parties sont regroupés dans « autres coups »", + "Züge mit weniger Partien werden zu „andere Züge“ zusammengefasst", + "Las jugadas con menos partidas se agrupan en «otras jugadas»", + "Le mosse con meno partite si raggruppano in «altre mosse»", + "Lances com menos partidas são agrupados em «outros lances»", + "Partiyasi kamroq yurishlar «boshqa yurishlar»ga yig‘iladi", + "ПартиÑ�Ñ�Ñ‹ азырақ жүріÑ�тер «баÑ�қа жүріÑ�терге» жиналады", + ], + [ + "His moves plain, the opponents' weak; ⇄ — the position is reached by another move order too", + "Его ходы — обычным, ходы Ñ�оперников — Ñ�лабым; ⇄ — к позиции приходÑ�Ñ‚ и другим порÑ�дком ходов", + "Ses coups en clair, ceux des adversaires en pâle ; ⇄ — la position est aussi atteinte par un autre ordre de coups", + "Seine Züge normal, die der Gegner blass; ⇄ — die Stellung wird auch über eine andere Zugfolge erreicht", + "Sus jugadas en normal, las de los rivales en tenue; ⇄ — la posición también se alcanza por otro orden de jugadas", + "Le sue mosse in chiaro, quelle degli avversari attenuate; ⇄ — la posizione si raggiunge anche con un altro ordine di mosse", + "Os lances dele em normal, os dos adversários esmaecidos; ⇄ — a posição também é alcançada por outra ordem de lances", + "Uning yurishlari oddiy, raqiblarniki xira; ⇄ — pozitsiyaga boshqa tartibda ham kelinadi", + "Оның жүріÑ�тері әдеттегі, қарÑ�ылаÑ�тарынікі күңгірт; ⇄ — позициÑ�ға баÑ�қа жүріÑ� ретімен де келеді", + ], + [ + "Share of the games of the move above", + "ДолÑ� от партий хода выше", + "Part des parties du coup au-dessus", + "Anteil an den Partien des Zuges darüber", + "Parte de las partidas de la jugada superior", + "Quota delle partite della mossa sopra", + "Parte das partidas do lance acima", + "Yuqoridagi yurish partiyalaridan ulush", + "Жоғарыдағы жүріÑ� партиÑ�ларынан үлеÑ�", + ], + [ + "Score", + "Счёт", + "Score", + "Ergebnis", + "Puntuación", + "Punteggio", + "Pontuação", + "Hisob", + "ЕÑ�еп", + ], + [ + "The opponent's points in these games", + "Очки Ñ�оперника в Ñ�тих партиÑ�Ñ…", + "Les points de l'adversaire dans ces parties", + "Die Punkte des Gegners in diesen Partien", + "Los puntos del rival en estas partidas", + "I punti dell'avversario in queste partite", + "Os pontos do adversário nestas partidas", + "Raqibning bu partiyalardagi ochkolari", + "ҚарÑ�ылаÑ�тың оÑ�Ñ‹ партиÑ�лардағы ұпайлары", + ], + [ + "Last", + "ПоÑ�леднÑ�Ñ�", + "Dernière", + "Letzte", + "Última", + "Ultima", + "Última", + "Oxirgi", + "Соңғы", + ], + [ + "Few games: percentages are unreliable", + "Мало партий — проценты ненадёжны", + "Peu de parties : les pourcentages ne sont pas fiables", + "Wenige Partien: die Prozente sind unzuverlässig", + "Pocas partidas: los porcentajes no son fiables", + "Poche partite: le percentuali non sono affidabili", + "Poucas partidas: as porcentagens não são confiáveis", + "Partiyalar kam: foizlar ishonchsiz", + "ПартиÑ�лар аз: пайыздар Ñ�енімÑ�із", + ], + [ + "First moves", + "Первые ходы", + "Premiers coups", + "Erste Züge", + "Primeras jugadas", + "Prime mosse", + "Primeiros lances", + "Birinchi yurishlar", + "Ð�лғашқы жүріÑ�тер", + ], + [ + "no name", + "без названиÑ�", + "sans nom", + "ohne Namen", + "sin nombre", + "senza nome", + "sem nome", + "nomsiz", + "атауÑ�ыз", + ], + [ + "no deeper name", + "без названиÑ� глубже", + "sans nom plus loin", + "kein tieferer Name", + "sin nombre más adelante", + "nessun nome più avanti", + "sem nome mais adiante", + "chuqurroq nom yo‘q", + "тереңірек атау жоқ", + ], + [ + "in both colours", + "обоими цветами", + "avec les deux couleurs", + "mit beiden Farben", + "con ambos colores", + "con entrambi i colori", + "com ambas as cores", + "ikkala rang bilan", + "екі түÑ�пен де", + ], + [ + "â–¶ Find opening errors", + "â–¶ Ð�айти ошибки в дебютах", + "â–¶ Chercher les erreurs d'ouverture", + "â–¶ Eröffnungsfehler suchen", + "â–¶ Buscar errores de apertura", + "â–¶ Trova gli errori di apertura", + "â–¶ Procurar erros de abertura", + "â–¶ Debyut xatolarini topish", + "â–¶ Дебют қателерін табу", + ], + [ + "Repeated errors — the same position, the same move", + "ПовторÑ�ющиеÑ�Ñ� ошибки — одна и та же позициÑ�, тот же ход", + "Erreurs répétées — même position, même coup", + "Wiederholte Fehler — dieselbe Stellung, derselbe Zug", + "Errores repetidos — la misma posición, la misma jugada", + "Errori ripetuti — la stessa posizione, la stessa mossa", + "Erros repetidos — a mesma posição, o mesmo lance", + "Takrorlanuvchi xatolar — o‘sha pozitsiya, o‘sha yurish", + "Қайталанатын қателер — Ñ�ол позициÑ�, Ñ�ол жүріÑ�", + ], + [ + "Played", + "Сыграл", + "Joué", + "Gespielt", + "Jugó", + "Giocata", + "Jogou", + "O‘ynadi", + "Жүрді", + ], + [ + "Better", + "Лучше", + "Mieux", + "Besser", + "Mejor", + "Meglio", + "Melhor", + "Yaxshiroq", + "ЖақÑ�ырақ", + ], + [ + "start", + "начало", + "début", + "Anfang", + "inicio", + "inizio", + "início", + "boshlanish", + "баÑ�Ñ‹", + ], + [ + "By opening", + "По дебютам", + "Par ouverture", + "Nach Eröffnung", + "Por apertura", + "Per apertura", + "Por abertura", + "Debyutlar bo‘yicha", + "Дебюттер бойынша", + ], + [ + "All games", + "Ð’Ñ�е партии", + "Toutes les parties", + "Alle Partien", + "Todas las partidas", + "Tutte le partite", + "Todas as partidas", + "Barcha partiyalar", + "Барлық партиÑ�лар", + ], + [ + "His marked moves in the opening of this game", + "Его отмеченные ходы в дебюте Ñ�той партии", + "Ses coups marqués dans l'ouverture de cette partie", + "Seine markierten Züge in der Eröffnung dieser Partie", + "Sus jugadas marcadas en la apertura de esta partida", + "Le sue mosse segnate nell'apertura di questa partita", + "Os lances marcados dele na abertura desta partida", + "Bu partiya debyutidagi uning belgilangan yurishlari", + "ОÑ�Ñ‹ партиÑ� дебютіндегі оның белгіленген жүріÑ�тері", + ], + [ + "Selected: {names} · {n}", + "Отмечено: {names} · {n}", + "Sélection : {names} · {n}", + "Gewählt: {names} · {n}", + "Marcados: {names} · {n}", + "Selezionati: {names} · {n}", + "Marcados: {names} · {n}", + "Belgilandi: {names} · {n}", + "Белгіленді: {names} · {n}", + ], + [ + "White — {n}", + "Белые — {n}", + "Blancs — {n}", + "Weiß — {n}", + "Blancas — {n}", + "Bianco — {n}", + "Brancas — {n}", + "Oq — {n}", + "Ð�Ò› — {n}", + ], + [ + "Black — {n}", + "Чёрные — {n}", + "Noirs — {n}", + "Schwarz — {n}", + "Negras — {n}", + "Nero — {n}", + "Pretas — {n}", + "Qora — {n}", + "Қара — {n}", + ], + [ + "Preparing against {name}", + "Подготовка к Ñ�опернику: {name}", + "Préparation contre {name}", + "Vorbereitung auf {name}", + "Preparación contra {name}", + "Preparazione contro {name}", + "Preparação contra {name}", + "Tayyorgarlik: {name}", + "Дайындық: {name}", + ], + [ + "The engine evaluates the first {n} moves of every game of the opponent. The games are not changed.", + "Движок оценит первые {n} ходов каждой партии Ñ�оперника. Партии не менÑ�ÑŽÑ‚Ñ�Ñ�.", + "Le moteur évalue les {n} premiers coups de chaque partie de l'adversaire. Les parties ne sont pas modifiées.", + "Die Engine bewertet die ersten {n} Züge jeder Partie des Gegners. Die Partien werden nicht verändert.", + "El motor evalúa las primeras {n} jugadas de cada partida del rival. Las partidas no se modifican.", + "Il motore valuta le prime {n} mosse di ogni partita dell'avversario. Le partite non vengono modificate.", + "O motor avalia os primeiros {n} lances de cada partida do adversário. As partidas não são alteradas.", + "Dvijok raqibning har bir partiyasidagi dastlabki {n} yurishni baholaydi. Partiyalar o‘zgarmaydi.", + "Қозғалтқыш қарÑ�ылаÑ�тың әр партиÑ�Ñ�ының алғашқы {n} жүріÑ�ін бағалайды. ПартиÑ�лар өзгермейді.", + ], + [ + "identical positions are counted once; {n} already evaluated earlier", + "одинаковые позиции Ñ�читаютÑ�Ñ� один раз; {n} уже оценены раньше", + "les positions identiques ne sont comptées qu'une fois ; {n} déjà évaluées", + "gleiche Stellungen werden einmal gezählt; {n} schon früher bewertet", + "las posiciones idénticas se cuentan una vez; {n} ya evaluadas antes", + "le posizioni identiche si contano una volta; {n} già valutate prima", + "posições idênticas são contadas uma vez; {n} já avaliadas antes", + "bir xil pozitsiyalar bir marta hisoblanadi; {n} tasi avval baholangan", + "бірдей позициÑ�лар бір рет Ñ�аналады; {n} бұрын бағаланған", + ], + [ + "+{n} spelling", + "+{n} напиÑ�ание", + "+{n} orthographe", + "+{n} Schreibweise", + "+{n} grafía", + "+{n} grafia", + "+{n} grafia", + "+{n} yozilish", + "+{n} жазылу", + ], + [ + "not counted: from a set position — {n}", + "не учтены: Ñ� заданной позиции — {n}", + "non comptées : depuis une position donnée — {n}", + "nicht gezählt: aus einer Ausgangsstellung — {n}", + "no contadas: desde una posición dada — {n}", + "non contate: da una posizione data — {n}", + "não contadas: de uma posição dada — {n}", + "hisobga olinmadi: berilgan pozitsiyadan — {n}", + "еÑ�ептелмеді: берілген позициÑ�дан — {n}", + ], + [ + "Opening: {n} moves", + "Дебют: {n} ходов", + "Ouverture : {n} coups", + "Eröffnung: {n} Züge", + "Apertura: {n} jugadas", + "Apertura: {n} mosse", + "Abertura: {n} lances", + "Debyut: {n} yurish", + "Дебют: {n} жүріÑ�", + ], + [ + "Finding errors: {done} of {total} positions · ≈ {time}", + "Ищу ошибки: {done} из {total} позиций · ≈ {time}", + "Recherche d'erreurs : {done} sur {total} positions · ≈ {time}", + "Fehlersuche: {done} von {total} Stellungen · ≈ {time}", + "Buscando errores: {done} de {total} posiciones · ≈ {time}", + "Ricerca errori: {done} di {total} posizioni · ≈ {time}", + "Procurando erros: {done} de {total} posições · ≈ {time}", + "Xatolar qidirilmoqda: {total} dan {done} pozitsiya · ≈ {time}", + "Қателер ізделуде: {total} ішінен {done} позициÑ� · ≈ {time}", + ], + [ + "â–¶ Errors ≈ {time}", + "â–¶ Ошибки ≈ {time}", + "â–¶ Erreurs ≈ {time}", + "â–¶ Fehler ≈ {time}", + "â–¶ Errores ≈ {time}", + "â–¶ Errori ≈ {time}", + "â–¶ Erros ≈ {time}", + "â–¶ Xatolar ≈ {time}", + "â–¶ Қателер ≈ {time}", + ], + [ + "â–¶ Find opening errors ≈ {time}", + "â–¶ Ð�айти ошибки в дебютах ≈ {time}", + "â–¶ Chercher les erreurs d'ouverture ≈ {time}", + "â–¶ Eröffnungsfehler suchen ≈ {time}", + "â–¶ Buscar errores de apertura ≈ {time}", + "â–¶ Trova gli errori di apertura ≈ {time}", + "â–¶ Procurar erros de abertura ≈ {time}", + "â–¶ Debyut xatolarini topish ≈ {time}", + "â–¶ Дебют қателерін табу ≈ {time}", + ], + [ + "Errors found · {engine} · {n} positions", + "Ошибки найдены · {engine} · {n} позиций", + "Erreurs trouvées · {engine} · {n} positions", + "Fehler gefunden · {engine} · {n} Stellungen", + "Errores encontrados · {engine} · {n} posiciones", + "Errori trovati · {engine} · {n} posizioni", + "Erros encontrados · {engine} · {n} posições", + "Xatolar topildi · {engine} · {n} pozitsiya", + "Қателер табылды · {engine} · {n} позициÑ�", + ], + [ + "opponents ≈ {elo}", + "Ñ�оперники ≈ {elo}", + "adversaires ≈ {elo}", + "Gegner ≈ {elo}", + "rivales ≈ {elo}", + "avversari ≈ {elo}", + "adversários ≈ {elo}", + "raqiblar ≈ {elo}", + "қарÑ�ылаÑ�тар ≈ {elo}", + ], + [ + "last {date}", + "поÑ�леднÑ�Ñ� {date}", + "dernière {date}", + "letzte {date}", + "última {date}", + "ultima {date}", + "última {date}", + "oxirgisi {date}", + "Ñ�оңғыÑ�Ñ‹ {date}", + ], + [ + "Few games ({n}): percentages and scores are unreliable", + "Партий мало ({n}) — проценты и Ñ�чёт ненадёжны", + "Peu de parties ({n}) : pourcentages et scores ne sont pas fiables", + "Wenige Partien ({n}): Prozente und Ergebnisse sind unzuverlässig", + "Pocas partidas ({n}): porcentajes y puntuaciones no son fiables", + "Poche partite ({n}): percentuali e punteggi non sono affidabili", + "Poucas partidas ({n}): porcentagens e pontuações não são confiáveis", + "Partiyalar kam ({n}): foizlar va hisob ishonchsiz", + "ПартиÑ�лар аз ({n}): пайыздар мен еÑ�еп Ñ�енімÑ�із", + ], + [ + "Collecting games… {p} %", + "Собираю партии… {p} %", + "Collecte des parties… {p} %", + "Partien werden gesammelt… {p} %", + "Reuniendo partidas… {p} %", + "Raccolta delle partite… {p} %", + "Reunindo partidas… {p} %", + "Partiyalar yig‘ilmoqda… {p} %", + "ПартиÑ�лар жиналуда… {p} %", + ], + [ + "Branches from {n} games", + "Ветви от {n} партий", + "Branches dès {n} parties", + "Zweige ab {n} Partien", + "Ramas desde {n} partidas", + "Rami da {n} partite", + "Ramos a partir de {n} partidas", + "{n} partiyadan shoxlar", + "{n} партиÑ�дан тармақтар", + ], + [ + "other moves ({n})", + "другие ходы ({n})", + "autres coups ({n})", + "andere Züge ({n})", + "otras jugadas ({n})", + "altre mosse ({n})", + "outros lances ({n})", + "boshqa yurishlar ({n})", + "баÑ�қа жүріÑ�тер ({n})", + ], + [ + "Reached by another move order too: {orders}", + "К позиции приходили и другим порÑ�дком: {orders}", + "Aussi atteinte par un autre ordre de coups : {orders}", + "Auch über eine andere Zugfolge erreicht: {orders}", + "También alcanzada por otro orden de jugadas: {orders}", + "Raggiunta anche con un altro ordine di mosse: {orders}", + "Também alcançada por outra ordem de lances: {orders}", + "Boshqa tartibda ham kelingan: {orders}", + "БаÑ�қа жүріÑ� ретімен де келген: {orders}", + ], + [ + "No games as {colour}. As {other} — {n}", + "{colour} партий нет. {other} — {n}", + "Aucune partie avec les {colour}. Avec les {other} — {n}", + "Keine Partien mit {colour}. Mit {other} — {n}", + "No hay partidas con {colour}. Con {other} — {n}", + "Nessuna partita con il {colour}. Con il {other} — {n}", + "Nenhuma partida de {colour}. De {other} — {n}", + "{colour} bilan partiyalar yo‘q. {other} bilan — {n}", + "{colour} партиÑ�лар жоқ. {other} — {n}", + ], + [ + "Show {other}", + "Показать {other}", + "Afficher {other}", + "{other} zeigen", + "Mostrar {other}", + "Mostra {other}", + "Mostrar {other}", + "{other} ko‘rsatish", + "{other} көрÑ�ету", + ], + [ + "The engine has not searched for errors yet. It will check the first {n} moves of {games} games {colour} — {positions} positions, about {time}.", + "Движок ещё не иÑ�кал ошибки. Он проверит первые {n} ходов {games} партий {colour} — {positions} позиций, около {time}.", + "Le moteur n'a pas encore cherché d'erreurs. Il vérifiera les {n} premiers coups de {games} parties {colour} — {positions} positions, environ {time}.", + "Die Engine hat noch nicht nach Fehlern gesucht. Sie prüft die ersten {n} Züge von {games} Partien {colour} — {positions} Stellungen, etwa {time}.", + "El motor aún no ha buscado errores. Comprobará las primeras {n} jugadas de {games} partidas {colour} — {positions} posiciones, unos {time}.", + "Il motore non ha ancora cercato errori. Controllerà le prime {n} mosse di {games} partite {colour} — {positions} posizioni, circa {time}.", + "O motor ainda não procurou erros. Ele verificará os primeiros {n} lances de {games} partidas {colour} — {positions} posições, cerca de {time}.", + "Dvijok hali xatolarni qidirmadi. U {colour} {games} partiyaning dastlabki {n} yurishini tekshiradi — {positions} pozitsiya, taxminan {time}.", + "Қозғалтқыш әлі қателерді іздеген жоқ. Ол {colour} {games} партиÑ�ның алғашқы {n} жүріÑ�ін текÑ�ереді — {positions} позициÑ�, шамамен {time}.", + ], + [ + "Checked {done} of {total} positions", + "Проверено {done} из {total} позиций", + "{done} positions vérifiées sur {total}", + "{done} von {total} Stellungen geprüft", + "Comprobadas {done} de {total} posiciones", + "Verificate {done} di {total} posizioni", + "Verificadas {done} de {total} posições", + "{total} dan {done} pozitsiya tekshirildi", + "{total} ішінен {done} позициÑ� текÑ�ерілді", + ], + [ + "No errors in the first {n} moves ({i} inaccuracies).", + "Ð’ первых {n} ходах ошибок не нашлоÑ�ÑŒ (неточноÑ�тей {i}).", + "Pas d'erreur dans les {n} premiers coups ({i} imprécisions).", + "Keine Fehler in den ersten {n} Zügen ({i} Ungenauigkeiten).", + "Sin errores en las primeras {n} jugadas ({i} imprecisiones).", + "Nessun errore nelle prime {n} mosse ({i} imprecisioni).", + "Sem erros nos primeiros {n} lances ({i} imprecisões).", + "Dastlabki {n} yurishda xato topilmadi ({i} noaniqlik).", + "Ð�лғашқы {n} жүріÑ�те қате табылмады ({i} дәлÑ�іздік).", + ], + [ + "Deeper: {n} moves", + "Глубже: {n} ходов", + "Plus loin : {n} coups", + "Tiefer: {n} Züge", + "Más profundo: {n} jugadas", + "Più a fondo: {n} mosse", + "Mais fundo: {n} lances", + "Chuqurroq: {n} yurish", + "Тереңірек: {n} жүріÑ�", + ], + [ + "better {best}", + "лучше {best}", + "mieux {best}", + "besser {best}", + "mejor {best}", + "meglio {best}", + "melhor {best}", + "yaxshisi {best}", + "жақÑ�Ñ‹Ñ�Ñ‹ {best}", + ], + [ + "Games · {n}", + "Партии · {n}", + "Parties · {n}", + "Partien · {n}", + "Partidas · {n}", + "Partite · {n}", + "Partidas · {n}", + "Partiyalar · {n}", + "ПартиÑ�лар · {n}", + ], + [ + "Games · after {move} · {n}", + "Партии · поÑ�ле {move} · {n}", + "Parties · après {move} · {n}", + "Partien · nach {move} · {n}", + "Partidas · tras {move} · {n}", + "Partite · dopo {move} · {n}", + "Partidas · após {move} · {n}", + "Partiyalar · {move} dan keyin · {n}", + "ПартиÑ�лар · {move} кейін · {n}", + ], + [ + "Games · {opening} · {n}", + "Партии · {opening} · {n}", + "Parties · {opening} · {n}", + "Partien · {opening} · {n}", + "Partidas · {opening} · {n}", + "Partite · {opening} · {n}", + "Partidas · {opening} · {n}", + "Partiyalar · {opening} · {n}", + "ПартиÑ�лар · {opening} · {n}", + ], + [ + "Games · {move} · {n}", + "Партии · {move} · {n}", + "Parties · {move} · {n}", + "Partien · {move} · {n}", + "Partidas · {move} · {n}", + "Partite · {move} · {n}", + "Partidas · {move} · {n}", + "Partiyalar · {move} · {n}", + "ПартиÑ�лар · {move} · {n}", + ], + [ + "{played} — better {best} · {before} → {after}", + "{played} — лучше {best} · {before} → {after}", + "{played} — mieux {best} · {before} → {after}", + "{played} — besser {best} · {before} → {after}", + "{played} — mejor {best} · {before} → {after}", + "{played} — meglio {best} · {before} → {after}", + "{played} — melhor {best} · {before} → {after}", + "{played} — yaxshisi {best} · {before} → {after}", + "{played} — жақÑ�Ñ‹Ñ�Ñ‹ {best} · {before} → {after}", + ], + [ + "Opening errors are being searched. Quit and stop?", + "Идёт поиÑ�к ошибок в дебютах. Выйти и оÑ�тановить?", + "La recherche d'erreurs d'ouverture est en cours. Quitter et l'arrêter ?", + "Die Suche nach Eröffnungsfehlern läuft. Beenden und stoppen?", + "Se están buscando errores de apertura. ¿Salir y detenerla?", + "È in corso la ricerca degli errori di apertura. Uscire e fermarla?", + "A busca de erros de abertura está em andamento. Sair e parar?", + "Debyut xatolari qidirilmoqda. Chiqib, to‘xtatilsinmi?", + "Дебют қателері ізделуде. Шығып, тоқтату керек пе?", + ], + [ + "What was found is kept.", + "Ð�айденное Ñ�охранитÑ�Ñ�.", + "Ce qui a été trouvé est conservé.", + "Was gefunden wurde, bleibt erhalten.", + "Lo encontrado se conserva.", + "Quanto trovato viene conservato.", + "O que foi encontrado é mantido.", + "Topilganlar saqlanadi.", + "Табылғаны Ñ�ақталады.", + ], + [ + "Quit", + "Выйти", + "Quitter", + "Beenden", + "Salir", + "Esci", + "Sair", + "Chiqish", + "Шығу", + ], + [ + "Back to the game list", + "Ð�азад к Ñ�пиÑ�ку партий", + "Retour à la liste des parties", + "Zurück zur Partienliste", + "Volver a la lista de partidas", + "Torna all'elenco delle partite", + "Voltar à lista de partidas", + "Partiyalar ro‘yxatiga qaytish", + "ПартиÑ�лар тізіміне оралу", + ], + [ + "The preparation this game was opened from, as you left it (Esc, Ctrl+W)", + "Подготовка, из которой открыта партиÑ�, — такой, как вы её оÑ�тавили (Esc, Ctrl+W)", + "La préparation d'où cette partie a été ouverte, telle que vous l'avez laissée (Échap, Ctrl+W)", + "Die Vorbereitung, aus der diese Partie geöffnet wurde, so wie Sie sie verlassen haben (Esc, Strg+W)", + "La preparación desde la que se abrió esta partida, tal como la dejó (Esc, Ctrl+W)", + "La preparazione da cui è stata aperta questa partita, come l'hai lasciata (Esc, Ctrl+W)", + "A preparação de onde esta partida foi aberta, como você a deixou (Esc, Ctrl+W)", + "Bu partiya ochilgan tayyorgarlik — siz qoldirgan holatda (Esc, Ctrl+W)", + "ОÑ�Ñ‹ партиÑ� ашылған дайындық — Ñ�із қалдырған күйінде (Esc, Ctrl+W)", + ], + [ + "no errors", + "ошибок нет", + "aucune erreur", + "keine Fehler", + "sin errores", + "nessun errore", + "sem erros", + "xatolar yo‘q", + "қателер жоқ", + ], + [ + "Share of the colour's games; a variation's — of its family's", + "ДолÑ� от партий цветом; у варианта — от Ñ�емейÑ�тва", + "Part des parties de cette couleur ; pour une variante — de sa famille", + "Anteil an den Partien dieser Farbe; bei einer Variante — an ihrer Familie", + "Parte de las partidas de ese color; de una variante — de su familia", + "Quota delle partite di quel colore; di una variante — della sua famiglia", + "Parte das partidas dessa cor; de uma variante — da sua família", + "Shu rangdagi partiyalardan ulush; variantda — oilasidan", + "ОÑ�Ñ‹ түÑ�тегі партиÑ�лардан үлеÑ�; нұÑ�қада — тобынан", + ], + [ + "The counts are of the checked positions", + "ЧиÑ�ла — по проверенным позициÑ�м", + "Les nombres portent sur les positions vérifiées", + "Die Zahlen gelten für die geprüften Stellungen", + "Las cifras son de las posiciones comprobadas", + "I numeri riguardano le posizioni verificate", + "Os números são das posições verificadas", + "Sonlar tekshirilgan pozitsiyalar bo‘yicha", + "Сандар текÑ�ерілген позициÑ�лар бойынша", + ], + [ + "Show the inaccuracies (?!) with the mistakes and blunders", + "Показывать неточноÑ�ти (?!) вмеÑ�те Ñ� ошибками и зевками", + "Afficher les imprécisions (?!) avec les erreurs et les gaffes", + "Ungenauigkeiten (?!) mit Fehlern und groben Fehlern zeigen", + "Mostrar las imprecisiones (?!) con los errores y errores graves", + "Mostra le imprecisioni (?!) con errori e svarioni", + "Mostrar as imprecisões (?!) com os erros e erros graves", + "Noaniqliklarni (?!) xato va qo‘pol xatolar bilan ko‘rsatish", + "ДәлÑ�іздіктерді (?!) қателер мен өреÑ�кел қателермен бірге көрÑ�ету", + ], + [ + "White wins {w} % · draws {d} % · Black wins {b} %", + "Победы белых {w} % · ничьи {d} % · победы чёрных {b} %", + "Victoires des Blancs {w} % · nulles {d} % · victoires des Noirs {b} %", + "Weißsiege {w} % · Remis {d} % · Schwarzsiege {b} %", + "Victorias blancas {w} % · tablas {d} % · victorias negras {b} %", + "Vittorie del Bianco {w} % · patte {d} % · vittorie del Nero {b} %", + "Vitórias das brancas {w} % · empates {d} % · vitórias das pretas {b} %", + "Oq g‘alabalari {w} % · durang {d} % · qora g‘alabalari {b} %", + "Ð�Ò› жеңіÑ�тері {w} % · тең {d} % · қара жеңіÑ�тері {b} %", + ], + [ + "{n} moves", + "{n} ходов", + "{n} coups", + "{n} Züge", + "{n} jugadas", + "{n} mosse", + "{n} lances", + "{n} yurish", + "{n} жүріÑ�", + ], + [ + "{n} m.", "{n} Ñ….", "{n} c.", "{n} Z.", "{n} j.", "{n} m.", "{n} l.", "{n} yur.", "{n} ж.", + ], + [ + "Continue ≈ {time}", + "Продолжить ≈ {time}", + "Continuer ≈ {time}", + "Fortsetzen ≈ {time}", + "Continuar ≈ {time}", + "Continua ≈ {time}", + "Continuar ≈ {time}", + "Davom ettirish ≈ {time}", + "ЖалғаÑ�тыру ≈ {time}", + ], + [ + "Errors found · {n} positions", + "Ошибки найдены · {n} позиций", + "Erreurs trouvées · {n} positions", + "Fehler gefunden · {n} Stellungen", + "Errores encontrados · {n} posiciones", + "Errori trovati · {n} posizioni", + "Erros encontrados · {n} posições", + "Xatolar topildi · {n} pozitsiya", + "Қателер табылды · {n} позициÑ�", + ], + [ + "in {p} % of games", + "в {p} % партий", + "dans {p} % des parties", + "in {p} % der Partien", + "en el {p} % de las partidas", + "nel {p} % delle partite", + "em {p} % das partidas", + "partiyalarning {p} % ida", + "партиÑ�лардың {p} % інде", + ], + [ + "others ({n})", + "другие ({n})", + "autres ({n})", + "andere ({n})", + "otras ({n})", + "altre ({n})", + "outros ({n})", + "boshqalar ({n})", + "баÑ�қалары ({n})", + ], + [ + "{judgement}: better {best} ({before} → {after}) · in {n} games", + "{judgement}: лучше {best} (оценка {before} → {after}) · в {n} партиÑ�Ñ…", + "{judgement} : mieux {best} ({before} → {after}) · dans {n} parties", + "{judgement}: besser {best} ({before} → {after}) · in {n} Partien", + "{judgement}: mejor {best} ({before} → {after}) · en {n} partidas", + "{judgement}: meglio {best} ({before} → {after}) · in {n} partite", + "{judgement}: melhor {best} ({before} → {after}) · em {n} partidas", + "{judgement}: yaxshisi {best} ({before} → {after}) · {n} partiyada", + "{judgement}: жақÑ�Ñ‹Ñ�Ñ‹ {best} ({before} → {after}) · {n} партиÑ�да", + ], + [ + "Checking whether your engine can run the analysis…", + "ПроверÑ�ÑŽ, подойдёт ли ваш движок длÑ� разбора…", + "Vérification : votre moteur peut-il faire l’analyse…", + "Es wird geprüft, ob Ihre Engine die Analyse machen kann…", + "Comprobando si su motor puede hacer el análisis…", + "Verifica se il tuo motore può fare l’analisi…", + "Verificando se o seu motor pode fazer a análise…", + "Dvigatelingiz tahlilga yaraydimi, tekshirilmoqda…", + "Қозғалтқышыңыз талдауға жарай ма, текÑ�ерілуде…", + ], + [ + "Your Stockfish 19 calculates differently from ChessPenguin's build (another build or network).", + "Ваш Stockfish 19 Ñ�читает иначе, чем Ñ�борка ChessPenguin (другаÑ� Ñ�борка или Ñ�еть).", + "Votre Stockfish 19 calcule autrement que la version de ChessPenguin (autre compilation ou autre réseau).", + "Ihr Stockfish 19 rechnet anders als der Build von ChessPenguin (anderer Build oder anderes Netz).", + "Su Stockfish 19 calcula de otra manera que la compilación de ChessPenguin (otra compilación u otra red).", + "Il tuo Stockfish 19 calcola diversamente dalla build di ChessPenguin (un’altra build o un’altra rete).", + "Seu Stockfish 19 calcula de outro jeito que a versão do ChessPenguin (outra compilação ou outra rede).", + "Sizning Stockfish 19 ChessPenguin yig‘masidan boshqacha hisoblaydi (boshqa yig‘ma yoki tarmoq).", + "Сіздің Stockfish 19 ChessPenguin жинағынан баÑ�қаша еÑ�ептейді (баÑ�қа жинақ немеÑ�е желі).", + ], + [ + "{engine} did not finish the check in time; it will be checked again next time.", + "{engine} не уÑ�пел ответить на проверку — проверю Ñ�нова в Ñ�ледующий раз.", + "{engine} n’a pas répondu à temps à la vérification ; il sera vérifié à nouveau la prochaine fois.", + "{engine} hat die Prüfung nicht rechtzeitig beantwortet; beim nächsten Mal wird erneut geprüft.", + "{engine} no respondió a tiempo a la comprobación; se comprobará de nuevo la próxima vez.", + "{engine} non ha risposto in tempo alla verifica; sarà verificato di nuovo la prossima volta.", + "{engine} não respondeu a tempo à verificação; será verificado de novo na próxima vez.", + "{engine} tekshiruvga o‘z vaqtida javob bermadi — keyingi safar yana tekshiriladi.", + "{engine} текÑ�еруге уақытында жауап бермеді — келеÑ�Ñ– жолы қайта текÑ�еріледі.", + ], + [ + "{engine} could not be started.", + "Ð�е удалоÑ�ÑŒ запуÑ�тить {engine}.", + "Impossible de lancer {engine}.", + "{engine} konnte nicht gestartet werden.", + "No se pudo iniciar {engine}.", + "Impossibile avviare {engine}.", + "Não foi possível iniciar {engine}.", + "{engine} ishga tushmadi.", + "{engine} Ñ–Ñ�ке қоÑ�ылмады.", + ], + [ + "The settings name {engine}.", + "Ð’ наÑ�тройках указан {engine}.", + "Les réglages indiquent {engine}.", + "In den Einstellungen steht {engine}.", + "En los ajustes figura {engine}.", + "Nelle impostazioni è indicato {engine}.", + "Nas configurações está {engine}.", + "Sozlamalarda {engine} ko‘rsatilgan.", + "Баптауларда {engine} көрÑ�етілген.", + ], + [ + "The system has {engine}.", + "Ð’ Ñ�иÑ�теме найден {engine}.", + "Le système contient {engine}.", + "Im System gefunden: {engine}.", + "En el sistema se encontró {engine}.", + "Nel sistema è stato trovato {engine}.", + "No sistema foi encontrado {engine}.", + "Tizimda {engine} topildi.", + "Жүйеде {engine} табылды.", + ], + [ + "So that the marks are the same on every computer, game analysis runs on the official build.", + "Чтобы отметки Ñ�овпадали на вÑ�ех компьютерах, разбор партии идёт на официальной Ñ�борке.", + "Pour que les signes soient les mêmes sur tous les ordinateurs, l’analyse de partie se fait avec la version officielle.", + "Damit die Zeichen auf jedem Computer gleich sind, läuft die Partieanalyse mit dem offiziellen Build.", + "Para que los signos sean iguales en cualquier ordenador, el análisis de partidas usa la compilación oficial.", + "Perché i segni siano uguali su ogni computer, l’analisi della partita usa la build ufficiale.", + "Para que as marcas sejam iguais em qualquer computador, a análise de partidas usa a versão oficial.", + "Belgilar har qanday kompyuterda bir xil bo‘lishi uchun partiya tahlili rasmiy yig‘mada bo‘ladi.", + "Белгілер кез келген компьютерде бірдей болуы үшін партиÑ�ны талдау реÑ�ми жинақта жүреді.", + ], + [ + "So that the marks are the same on every computer, the search for opening errors runs on the official build.", + "Чтобы отметки Ñ�овпадали на вÑ�ех компьютерах, поиÑ�к ошибок в дебютах идёт на официальной Ñ�борке.", + "Pour que les signes soient les mêmes sur tous les ordinateurs, la recherche d’erreurs d’ouverture se fait avec la version officielle.", + "Damit die Zeichen auf jedem Computer gleich sind, läuft die Suche nach Eröffnungsfehlern mit dem offiziellen Build.", + "Para que los signos sean iguales en cualquier ordenador, la búsqueda de errores de apertura usa la compilación oficial.", + "Perché i segni siano uguali su ogni computer, la ricerca degli errori d’apertura usa la build ufficiale.", + "Para que as marcas sejam iguais em qualquer computador, a procura de erros de abertura usa a versão oficial.", + "Belgilar har qanday kompyuterda bir xil bo‘lishi uchun debyut xatolarini qidirish rasmiy yig‘mada bo‘ladi.", + "Белгілер кез келген компьютерде бірдей болуы үшін дебют қателерін іздеу реÑ�ми жинақта жүреді.", + ], + [ + "Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer.", + "ДлÑ� разбора партии нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере.", + "L’analyse de partie a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs.", + "Die Partieanalyse braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind.", + "El análisis de partidas necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador.", + "L’analisi della partita richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer.", + "A análise de partidas precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador.", + "Partiya tahlili uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi.", + "ПартиÑ�ны талдау үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады.", + ], + [ + "The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer.", + "ДлÑ� поиÑ�ка ошибок в дебютах нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере.", + "La recherche d’erreurs d’ouverture a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs.", + "Die Suche nach Eröffnungsfehlern braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind.", + "La búsqueda de errores de apertura necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador.", + "La ricerca degli errori d’apertura richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer.", + "A procura de erros de abertura precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador.", + "Debyut xatolarini qidirish uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi.", + "Дебют қателерін іздеу үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады.", + ], + [ + "Download it?", + "Скачать её?", + "La télécharger ?", + "Herunterladen?", + "¿Descargarla?", + "Scaricarla?", + "Baixá-la?", + "Yuklab olinsinmi?", + "Жүктеп алу керек пе?", + ], + [ + "Download Stockfish 19?", + "Скачать Stockfish 19?", + "Télécharger Stockfish 19 ?", + "Stockfish 19 herunterladen?", + "¿Descargar Stockfish 19?", + "Scaricare Stockfish 19?", + "Baixar o Stockfish 19?", + "Stockfish 19 yuklab olinsinmi?", + "Stockfish 19 жүктеп алу керек пе?", + ], + [ + "Your engine stays for position analysis.", + "Ваш движок оÑ�таётÑ�Ñ� длÑ� анализа позиции.", + "Votre moteur reste pour l’analyse de position.", + "Ihre Engine bleibt für die Stellungsanalyse.", + "Su motor sigue para el análisis de posiciones.", + "Il tuo motore resta per l’analisi della posizione.", + "Seu motor continua para a análise de posição.", + "Dvigatelingiz pozitsiya tahlili uchun qoladi.", + "Қозғалтқышыңыз позициÑ�ны талдау үшін қалады.", + ], + [ + "Not found: {files}", + "Ð�е найдено: {files}", + "Introuvable : {files}", + "Nicht gefunden: {files}", + "No encontrado: {files}", + "Non trovato: {files}", + "Não encontrado: {files}", + "Topilmadi: {files}", + "Табылмады: {files}", + ], + [ + "Added to the shelf: {files}", + "Добавлено на полку: {files}", + "Ajouté à l’étagère : {files}", + "Zum Regal hinzugefügt: {files}", + "Añadido al estante: {files}", + "Aggiunto allo scaffale: {files}", + "Adicionado à estante: {files}", + "Javonga qo‘shildi: {files}", + "Сөреге қоÑ�ылды: {files}", + ], + [ + "The engine is no longer the Stockfish 19 that was checked. Start the analysis again.", + "Движок уже не тот Stockfish 19, что прошёл проверку. ЗапуÑ�тите разбор Ñ�нова.", + "Le moteur n’est plus le Stockfish 19 vérifié. Relancez l’analyse.", + "Die Engine ist nicht mehr der geprüfte Stockfish 19. Starten Sie die Analyse erneut.", + "El motor ya no es el Stockfish 19 comprobado. Inicie el análisis de nuevo.", + "Il motore non è più lo Stockfish 19 verificato. Avvia di nuovo l’analisi.", + "O motor não é mais o Stockfish 19 verificado. Inicie a análise de novo.", + "Dvigatel endi tekshirilgan Stockfish 19 emas. Tahlilni qaytadan boshlang.", + "Қозғалтқыш енді текÑ�ерілген Stockfish 19 емеÑ�. Талдауды қайта баÑ�таңыз.", + ], + [ + "Analysis needs Stockfish 19", + "ДлÑ� анализа нужен Stockfish 19", + "L’analyse nécessite Stockfish 19", + "Die Analyse braucht Stockfish 19", + "El análisis necesita Stockfish 19", + "L’analisi richiede Stockfish 19", + "A análise precisa do Stockfish 19", + "Tahlil uchun Stockfish 19 kerak", + "Талдау үшін Stockfish 19 керек", + ], + [ + "Game analysis and the search for opening errors always use ChessPenguin's Stockfish 19, so that their marks are the same on every computer. Download it? The analysis will start as soon as the download finishes.", + "Ð�нализ партии и поиÑ�к ошибок в дебютах вÑ�егда идут на Stockfish 19 из ChessPenguin — так отметки одинаковы на любом компьютере. Скачать его? Ð�нализ начнётÑ�Ñ�, как только загрузка закончитÑ�Ñ�.", + "L’analyse de partie et la recherche d’erreurs d’ouverture utilisent toujours le Stockfish 19 de ChessPenguin, pour que leurs signes soient les mêmes sur tous les ordinateurs. Le télécharger ? L’analyse commencera dès la fin du téléchargement.", + "Die Partieanalyse und die Suche nach Eröffnungsfehlern verwenden immer das Stockfish 19 von ChessPenguin, damit ihre Zeichen auf jedem Computer gleich sind. Herunterladen? Die Analyse beginnt, sobald der Download fertig ist.", + "El análisis de partidas y la búsqueda de errores de apertura usan siempre el Stockfish 19 de ChessPenguin, para que sus signos sean iguales en cualquier ordenador. ¿Descargarlo? El análisis empezará en cuanto termine la descarga.", + "L’analisi della partita e la ricerca degli errori d’apertura usano sempre lo Stockfish 19 di ChessPenguin, perché i segni siano uguali su ogni computer. Scaricarlo? L’analisi partirà appena finito il download.", + "A análise de partidas e a procura de erros de abertura usam sempre o Stockfish 19 do ChessPenguin, para que as marcas sejam iguais em qualquer computador. Descarregá-lo? A análise começa assim que o download terminar.", + "Partiya tahlili va debyut xatolarini qidirish doim ChessPenguin’ning Stockfish 19 dvigatelida bo‘ladi — belgilar har qanday kompyuterda bir xil chiqadi. Yuklab olinsinmi? Yuklash tugashi bilan tahlil boshlanadi.", + "ПартиÑ�ны талдау мен дебют қателерін іздеу әрқашан ChessPenguin-нің Stockfish 19 қозғалтқышында жүреді — белгілер кез келген компьютерде бірдей болады. Жүктеп алу керек пе? Жүктеу біткен Ñ�оң талдау баÑ�талады.", + ], + [ + "This analysis was made with other engine settings", + "Этот анализ Ñ�делан Ñ� прежними наÑ�тройками движка", + "Cette analyse a été faite avec d’autres réglages du moteur", + "Diese Analyse wurde mit anderen Engine-Einstellungen gemacht", + "Este análisis se hizo con otros ajustes del motor", + "Questa analisi è stata fatta con altre impostazioni del motore", + "Esta análise foi feita com outras definições do motor", + "Bu tahlil dvigatelning boshqa sozlamalari bilan qilingan", + "Бұл талдау қозғалтқыштың баÑ�қа баптауларымен жаÑ�алған", + ], + [ + "Every position is analysed again, the same way on every computer", + "Ð’Ñ�е позиции анализируютÑ�Ñ� заново — одинаково на любом компьютере", + "Toutes les positions sont analysées de nouveau, de la même façon sur tous les ordinateurs", + "Alle Stellungen werden neu analysiert, auf jedem Computer gleich", + "Todas las posiciones se analizan de nuevo, igual en cualquier ordenador", + "Tutte le posizioni vengono analizzate di nuovo, allo stesso modo su ogni computer", + "Todas as posições são analisadas de novo, da mesma forma em qualquer computador", + "Barcha pozitsiyalar qayta tahlil qilinadi — har qanday kompyuterda bir xil", + "Барлық позициÑ� қайта талданады — кез келген компьютерде бірдей", + ], + [ + "Analyse with the engine", + "Проанализировать движком", + "Analyser avec le moteur", + "Mit der Engine analysieren", + "Analizar con el motor", + "Analizza con il motore", + "Analisar com o motor", + "Dvigatel bilan tahlil qilish", + "Қозғалтқышпен талдау", + ], + [ + "Last year", + "За год", + "La dernière année", + "Letztes Jahr", + "Último año", + "Ultimo anno", + "Último ano", + "Oxirgi yil", + "Соңғы жыл", + ], + [ + "Last 2 years", + "За 2 года", + "Les 2 dernières années", + "Letzte 2 Jahre", + "Últimos 2 años", + "Ultimi 2 anni", + "Últimos 2 anos", + "Oxirgi 2 yil", + "Соңғы 2 жыл", + ], + [ + "Last 3 months", + "За 3 меÑ�Ñ�ца", + "Les 3 derniers mois", + "Letzte 3 Monate", + "Últimos 3 meses", + "Ultimi 3 mesi", + "Últimos 3 meses", + "Oxirgi 3 oy", + "Соңғы 3 ай", + ], + [ + "Last 6 months", + "За полгода", + "Les 6 derniers mois", + "Letzte 6 Monate", + "Últimos 6 meses", + "Ultimi 6 mesi", + "Últimos 6 meses", + "Oxirgi 6 oy", + "Соңғы 6 ай", + ], + [ + "Last {n} months", + "За {n} меÑ�.", + "Les {n} derniers mois", + "Letzte {n} Monate", + "Últimos {n} meses", + "Ultimi {n} mesi", + "Últimos {n} meses", + "Oxirgi {n} oy", + "Соңғы {n} ай", + ], + [ + "Last {n} games", + "ПоÑ�ледние {n} партий", + "Les {n} dernières parties", + "Letzte {n} Partien", + "Últimas {n} partidas", + "Ultime {n} partite", + "Últimas {n} partidas", + "Oxirgi {n} partiya", + "Соңғы {n} партиÑ�", + ], + [ + "The games have no dates: by number only", + "У партий нет дат: выбор только по чиÑ�лу", + "Les parties n’ont pas de date : par nombre seulement", + "Die Partien haben kein Datum: nur nach Anzahl", + "Las partidas no tienen fecha: solo por número", + "Le partite non hanno data: solo per numero", + "As partidas não têm data: só por número", + "Partiyalarda sana yo‘q: faqat soni bo‘yicha", + "ПартиÑ�лардың күні жоқ: тек Ñ�аны бойынша", + ], + [ + "Without a date: {n} — taken only with all games", + "Без даты: {n} — учитываютÑ�Ñ� только во «ВÑ�ех партиÑ�х»", + "Sans date : {n} — prises seulement avec toutes les parties", + "Ohne Datum: {n} — nur bei allen Partien berücksichtigt", + "Sin fecha: {n} — solo se cuentan con todas las partidas", + "Senza data: {n} — contate solo con tutte le partite", + "Sem data: {n} — contadas só com todas as partidas", + "Sanasiz: {n} — faqat «Barcha partiyalar»da hisoblanadi", + "КүнÑ�із: {n} — тек «Барлық партиÑ�лар» кезінде еÑ�ептеледі", + ], + [ + "Which of his games: by date — counted back from his newest game; by number — the newest of each colour", + "Какие его партии брать: по времени — Ñ�читаÑ� назад от его поÑ�ледней партии; по чиÑ�лу — Ñ�амые Ñ�вежие каждым цветом", + "Quelles parties prendre : par date — en remontant depuis sa dernière partie ; par nombre — les plus récentes de chaque couleur", + "Welche seiner Partien: nach Zeit — rückwärts ab seiner letzten Partie; nach Anzahl — die neuesten mit jeder Farbe", + "Qué partidas tomar: por fecha — contando hacia atrás desde su última partida; por número — las más recientes con cada color", + "Quali partite prendere: per data — a ritroso dalla sua ultima partita; per numero — le più recenti con ogni colore", + "Quais partidas usar: por data — contando para trás da sua última partida; por número — as mais recentes com cada cor", + "Qaysi partiyalarini olish: vaqt bo‘yicha — oxirgi partiyasidan orqaga sanab; soni bo‘yicha — har bir rangda eng yangilari", + "Қай партиÑ�ларын алу: уақыт бойынша — Ñ�оңғы партиÑ�Ñ�ынан кері Ñ�анап; Ñ�аны бойынша — әр түÑ�пен ең жаңалары", + ], + [ + "Preparations", + "Подготовки", + "Préparations", + "Vorbereitungen", + "Preparaciones", + "Preparazioni", + "Preparações", + "Tayyorgarliklar", + "Дайындықтар", + ], + [ + "ðŸ—� Preparations", + "ðŸ—� Подготовки", + "ðŸ—� Préparations", + "ðŸ—� Vorbereitungen", + "ðŸ—� Preparaciones", + "ðŸ—� Preparazioni", + "ðŸ—� Preparações", + "ðŸ—� Tayyorgarliklar", + "ðŸ—� Дайындықтар", + ], + [ + "Preparations against opponents: the saved ones and a new one", + "Подготовки к Ñ�оперникам: Ñ�охранённые и новаÑ�", + "Préparations contre des adversaires : les enregistrées et une nouvelle", + "Vorbereitungen auf Gegner: die gespeicherten und eine neue", + "Preparaciones contra rivales: las guardadas y una nueva", + "Preparazioni contro avversari: quelle salvate e una nuova", + "Preparações contra adversários: as salvas e uma nova", + "Raqiblarga tayyorgarliklar: saqlanganlari va yangisi", + "ҚарÑ�ылаÑ�тарға дайындықтар: Ñ�ақталғандары және жаңаÑ�Ñ‹", + ], + [ + "Nothing yet. A preparation is saved by itself as soon as you start it: prepare against a player.", + "Пока пуÑ�то. Подготовка Ñ�охранÑ�етÑ�Ñ� Ñ�ама Ñ�разу при запуÑ�ке: подготовьтеÑ�ÑŒ к Ñ�опернику.", + "Rien pour l’instant. Une préparation s’enregistre d’elle-même dès son lancement : préparez-vous contre un joueur.", + "Noch nichts. Eine Vorbereitung wird von selbst gespeichert, sobald sie begonnen wird: bereiten Sie sich auf einen Spieler vor.", + "Nada todavía. Una preparación se guarda sola en cuanto la inicias: prepárate contra un jugador.", + "Ancora niente. Una preparazione si salva da sola appena la avvii: preparati contro un giocatore.", + "Nada ainda. Uma preparação é guardada sozinha assim que a inicias: prepara-te contra um jogador.", + "Hozircha bo‘sh. Tayyorgarlik boshlanishi bilan o‘zi saqlanadi: raqibga tayyorlaning.", + "Әзірге боÑ�. Дайындық баÑ�талғанымен өзі Ñ�ақталады: қарÑ�ылаÑ�қа дайындалыңыз.", + ], + [ + "Could not save: {e}", + "Ð�е удалоÑ�ÑŒ Ñ�охранить: {e}", + "Impossible d’enregistrer : {e}", + "Speichern fehlgeschlagen: {e}", + "No se pudo guardar: {e}", + "Impossibile salvare: {e}", + "Não foi possível salvar: {e}", + "Saqlab bo‘lmadi: {e}", + "Сақтау мүмкін болмады: {e}", + ], + [ + "♟ New preparation…", + "♟ Ð�оваÑ� подготовка…", + "♟ Nouvelle préparation…", + "♟ Neue Vorbereitung…", + "♟ Nueva preparación…", + "♟ Nuova preparazione…", + "♟ Nova preparação…", + "♟ Yangi tayyorgarlik…", + "♟ Жаңа дайындық…", + ], + [ + "Add a database to the shelf first", + "Сначала добавьте базу на полку", + "Ajoutez d’abord une base à l’étagère", + "Fügen Sie zuerst eine Datenbank zum Regal hinzu", + "Primero añada una base a la estantería", + "Aggiungi prima un database allo scaffale", + "Primeiro adicione uma base à estante", + "Avval javonga baza qo‘shing", + "Ð�лдымен Ñ�өреге база қоÑ�ыңыз", + ], + [ + "Choose a player in the current database", + "Выбрать игрока в текущей базе", + "Choisir un joueur dans la base actuelle", + "Einen Spieler in der aktuellen Datenbank wählen", + "Elegir un jugador en la base actual", + "Scegli un giocatore nel database attuale", + "Escolher um jogador na base atual", + "Joriy bazadan o‘yinchini tanlash", + "Ð�ғымдағы базадан ойыншыны таңдау", + ], + ["OK", "ОК", "OK", "OK", "Aceptar", "OK", "OK", "OK", "ОК"], + [ + "Delete?", + "Удалить?", + "Supprimer ?", + "Löschen?", + "¿Eliminar?", + "Eliminare?", + "Excluir?", + "O‘chirilsinmi?", + "Жою керек пе?", + ], + [ + "Rename", + "Переименовать", + "Renommer", + "Umbenennen", + "Renombrar", + "Rinomina", + "Renomear", + "Qayta nomlash", + "Ð�тын өзгерту", + ], + [ + "errors: ?? {b} · ? {m} · ?! {i}", + "ошибки: ?? {b} · ? {m} · ?! {i}", + "erreurs : ?? {b} · ? {m} · ?! {i}", + "Fehler: ?? {b} · ? {m} · ?! {i}", + "errores: ?? {b} · ? {m} · ?! {i}", + "errori: ?? {b} · ? {m} · ?! {i}", + "erros: ?? {b} · ? {m} · ?! {i}", + "xatolar: ?? {b} · ? {m} · ?! {i}", + "қателер: ?? {b} · ? {m} · ?! {i}", + ], + [ + "errors not searched", + "ошибки ещё не иÑ�кали", + "erreurs non cherchées", + "Fehler nicht gesucht", + "errores no buscados", + "errori non cercati", + "erros não procurados", + "xatolar qidirilmagan", + "қателер ізделмеген", + ], + [ + "saved {date}", + "Ñ�охранено {date}", + "enregistrée le {date}", + "gespeichert am {date}", + "guardada el {date}", + "salvata il {date}", + "salva em {date}", + "saqlangan: {date}", + "Ñ�ақталған: {date}", + ], + [ + "database not found: {path}", + "база не найдена: {path}", + "base introuvable : {path}", + "Datenbank nicht gefunden: {path}", + "base no encontrada: {path}", + "database non trovato: {path}", + "base não encontrada: {path}", + "baza topilmadi: {path}", + "база табылмады: {path}", + ], + [ + "All", + "Ð’Ñ�е", + "Toutes", + "Alle", + "Todas", + "Tutte", + "Todas", + "Hammasi", + "Барлығы", + ], + [ + "1 yr", "1 год", "1 an", "1 J.", "1 año", "1 anno", "1 ano", "1 yil", "1 жыл", + ], + [ + "2 yrs", + "2 года", + "2 ans", + "2 J.", + "2 años", + "2 anni", + "2 anos", + "2 yil", + "2 жыл", + ], + [ + "{n} mo.", + "{n} меÑ�.", + "{n} mois", + "{n} Mon.", + "{n} m.", + "{n} mesi", + "{n} m.", + "{n} oy", + "{n} ай", + ], + [ + "Last {n}", + "ПоÑ�л. {n}", + "{n} dern.", + "Letzte {n}", + "Últ. {n}", + "Ult. {n}", + "Últ. {n}", + "Oxirgi {n}", + "Соңғы {n}", + ], + [ + "Counted back from his newest game — {date}", + "СчитаÑ� от его поÑ�ледней партии — {date}", + "En remontant depuis sa dernière partie — {date}", + "Ab seiner letzten Partie gezählt — {date}", + "Contando desde su última partida — {date}", + "Contando dalla sua ultima partita — {date}", + "Contando a partir da sua última partida — {date}", + "Oxirgi partiyasidan sanaladi — {date}", + "Соңғы партиÑ�Ñ�ынан баÑ�тап Ñ�аналады — {date}", + ], + [ + "Without a date, not counted: {n} (only with all games)", + "Без даты не учтено: {n} (только во «ВÑ�ех партиÑ�х»)", + "Sans date, non comptées : {n} (seulement avec toutes les parties)", + "Ohne Datum, nicht gezählt: {n} (nur bei allen Partien)", + "Sin fecha, no contadas: {n} (solo con todas las partidas)", + "Senza data, non contate: {n} (solo con tutte le partite)", + "Sem data, não contadas: {n} (só com todas as partidas)", + "Sanasiz, hisobga olinmagan: {n} (faqat «Barcha partiyalar»da)", + "КүнÑ�із, еÑ�епке алынбаған: {n} (тек «Барлық партиÑ�лар» кезінде)", + ], + [ + "No games in this period", + "За Ñ�тот период партий нет", + "Aucune partie sur cette période", + "Keine Partien in diesem Zeitraum", + "No hay partidas en este periodo", + "Nessuna partita in questo periodo", + "Nenhuma partida neste período", + "Bu davrda partiyalar yo‘q", + "Бұл кезеңде партиÑ�лар жоқ", + ], + [ + "both colours", + "обоими цветами", + "des deux couleurs", + "mit beiden Farben", + "con ambos colores", + "con entrambi i colori", + "com ambas as cores", + "ikkala rangda", + "екі түÑ�пен", + ], + [ + "Double-click to open", + "Двойной щелчок — открыть", + "Double-clic pour ouvrir", + "Doppelklick zum Öffnen", + "Doble clic para abrir", + "Doppio clic per aprire", + "Clique duplo para abrir", + "Ochish uchun ikki marta bosing", + "Ð�шу үшін екі рет баÑ�ыңыз", + ], + [ + "The database is not found: put the file back or delete the preparation", + "База не найдена: верните файл на меÑ�то или удалите подготовку", + "Base introuvable : remettez le fichier en place ou supprimez la préparation", + "Datenbank nicht gefunden: Datei zurücklegen oder Vorbereitung löschen", + "Base no encontrada: devuelva el archivo a su sitio o elimine la preparación", + "Database non trovato: rimetti il file al suo posto o elimina la preparazione", + "Base não encontrada: devolva o arquivo ao lugar ou exclua a preparação", + "Baza topilmadi: faylni joyiga qaytaring yoki tayyorgarlikni o‘chiring", + "База табылмады: файлды орнына қайтарыңыз немеÑ�е дайындықты жойыңыз", + ], + [ + "The player is not in the database: {name}", + "Игрока нет в базе: {name}", + "Le joueur n’est pas dans la base : {name}", + "Der Spieler ist nicht in der Datenbank: {name}", + "El jugador no está en la base: {name}", + "Il giocatore non è nel database: {name}", + "O jogador não está na base: {name}", + "O‘yinchi bazada yo‘q: {name}", + "Ойыншы базада жоқ: {name}", + ], + [ + "No games as White in this period", + "Белыми за Ñ�тот период партий нет", + "Aucune partie avec les Blancs sur cette période", + "Keine Partien mit Weiß in diesem Zeitraum", + "No hay partidas con blancas en este periodo", + "Nessuna partita con il Bianco in questo periodo", + "Nenhuma partida de brancas neste período", + "Bu davrda oqlar bilan partiyalar yo‘q", + "Бұл кезеңде ақтармен партиÑ�лар жоқ", + ], + [ + "No games as Black in this period", + "Чёрными за Ñ�тот период партий нет", + "Aucune partie avec les Noirs sur cette période", + "Keine Partien mit Schwarz in diesem Zeitraum", + "No hay partidas con negras en este periodo", + "Nessuna partita con il Nero in questo periodo", + "Nenhuma partida de pretas neste período", + "Bu davrda qoralar bilan partiyalar yo‘q", + "Бұл кезеңде қаралармен партиÑ�лар жоқ", + ], + [ + "last {n}", + "поÑ�ледние {n}", + "les {n} dernières", + "letzte {n}", + "últimas {n}", + "ultime {n}", + "últimas {n}", + "oxirgi {n}", + "Ñ�оңғы {n}", + ], + [ + "ðŸŒ� Open on Lichess", + "ðŸŒ� Открыть на Lichess", + "ðŸŒ� Ouvrir sur Lichess", + "ðŸŒ� Auf Lichess öffnen", + "ðŸŒ� Abrir en Lichess", + "ðŸŒ� Apri su Lichess", + "ðŸŒ� Abrir no Lichess", + "ðŸŒ� Lichess’da ochish", + "ðŸŒ� Lichess-те ашу", + ], + [ + "ðŸŒ� Open on Chess.com", + "ðŸŒ� Открыть на Chess.com", + "ðŸŒ� Ouvrir sur Chess.com", + "ðŸŒ� Auf Chess.com öffnen", + "ðŸŒ� Abrir en Chess.com", + "ðŸŒ� Apri su Chess.com", + "ðŸŒ� Abrir no Chess.com", + "ðŸŒ� Chess.com’da ochish", + "ðŸŒ� Chess.com-да ашу", + ], + [ + "ðŸŒ� Open the game's link", + "ðŸŒ� Открыть Ñ�Ñ�ылку партии", + "ðŸŒ� Ouvrir le lien de la partie", + "ðŸŒ� Link der Partie öffnen", + "ðŸŒ� Abrir el enlace de la partida", + "ðŸŒ� Apri il link della partita", + "ðŸŒ� Abrir o link da partida", + "ðŸŒ� Partiya havolasini ochish", + "ðŸŒ� ПартиÑ� Ñ�ілтемеÑ�ін ашу", + ], + [ + "Open on Lichess (in the browser, at this move)", + "Открыть на Lichess (в браузере, Ñ� Ñ�того хода)", + "Ouvrir sur Lichess (dans le navigateur, à ce coup)", + "Auf Lichess öffnen (im Browser, bei diesem Zug)", + "Abrir en Lichess (en el navegador, en esta jugada)", + "Apri su Lichess (nel browser, a questa mossa)", + "Abrir no Lichess (no navegador, neste lance)", + "Lichess’da ochish (brauzerda, shu yurishdan)", + "Lichess-те ашу (браузерде, оÑ�Ñ‹ жүріÑ�тен)", + ], + [ + "Open on Lichess (in the browser)", + "Открыть на Lichess (в браузере)", + "Ouvrir sur Lichess (dans le navigateur)", + "Auf Lichess öffnen (im Browser)", + "Abrir en Lichess (en el navegador)", + "Apri su Lichess (nel browser)", + "Abrir no Lichess (no navegador)", + "Lichess’da ochish (brauzerda)", + "Lichess-те ашу (браузерде)", + ], + [ + "Open on Chess.com (in the browser)", + "Открыть на Chess.com (в браузере)", + "Ouvrir sur Chess.com (dans le navigateur)", + "Auf Chess.com öffnen (im Browser)", + "Abrir en Chess.com (en el navegador)", + "Apri su Chess.com (nel browser)", + "Abrir no Chess.com (no navegador)", + "Chess.com’da ochish (brauzerda)", + "Chess.com-да ашу (браузерде)", + ], + [ + "Open the game's link (in the browser)", + "Открыть Ñ�Ñ�ылку партии (в браузере)", + "Ouvrir le lien de la partie (dans le navigateur)", + "Link der Partie öffnen (im Browser)", + "Abrir el enlace de la partida (en el navegador)", + "Apri il link della partita (nel browser)", + "Abrir o link da partida (no navegador)", + "Partiya havolasini ochish (brauzerda)", + "ПартиÑ� Ñ�ілтемеÑ�ін ашу (браузерде)", + ], + // --- opening repertoires --- + [ + "Already in the repertoire — no changes", + "Уже в репертуаре — изменений нет", + "Déjà dans le répertoire — aucun changement", + "Bereits im Repertoire — keine Änderungen", + "Ya está en el repertorio — sin cambios", + "Già nel repertorio — nessuna modifica", + "Já está no repertório — sem alterações", + "Repertuarda bor — o‘zgarish yo‘q", + "Репертуарда бар — өзгеріÑ� жоқ", + ], + [ + "The path was already in the repertoire; annotations added: {n}", + "Путь уже был в репертуаре; добавлены аннотации: {n}", + "Le chemin était déjà dans le répertoire ; annotations ajoutées : {n}", + "Der Pfad war bereits im Repertoire; hinzugefügte Anmerkungen: {n}", + "La ruta ya estaba en el repertorio; anotaciones añadidas: {n}", + "Il percorso era già nel repertorio; annotazioni aggiunte: {n}", + "O caminho já estava no repertório; anotações adicionadas: {n}", + "Yo‘l repertuarda bor edi; qo‘shilgan izohlar: {n}", + "Жол репертуарда болды; қоÑ�ылған түÑ�ініктемелер: {n}", + ], + [ + "Added to “{name}â€�: new moves: {added} · matched: {matched}", + "Добавлено в «{name}»: новых ходов: {added} · Ñ�овпало: {matched}", + "Ajouté à « {name} » : nouveaux coups : {added} · correspondants : {matched}", + "Zu „{name}“ hinzugefügt: neue Züge: {added} · übereinstimmend: {matched}", + "Añadido a «{name}»: jugadas nuevas: {added} · coincidentes: {matched}", + "Aggiunto a «{name}»: nuove mosse: {added} · corrispondenti: {matched}", + "Adicionado a “{name}â€�: novos lances: {added} · coincidentes: {matched}", + "“{name}â€� repertuariga qo‘shildi: yangi yurishlar: {added} · mos: {matched}", + "«{name}» репертуарына қоÑ�ылды: жаңа жүріÑ�тер: {added} · Ñ�әйкеÑ�: {matched}", + ], + [ + "Add to repertoire…", + "Добавить в репертуар…", + "Ajouter au répertoire…", + "Zum Repertoire hinzufügen…", + "Añadir al repertorio…", + "Aggiungi al repertorio…", + "Adicionar ao repertório…", + "Repertuariga qo‘shish…", + "Репертуарға қоÑ�у…", + ], + [ + "Select the move up to which to add", + "Выберите ход, до которого добавить", + "Sélectionnez le coup jusqu’auquel ajouter", + "Zug auswählen, bis zu dem hinzugefügt wird", + "Selecciona la jugada hasta la que añadir", + "Seleziona la mossa fino alla quale aggiungere", + "Selecione o lance até o qual adicionar", + "Qaysi yurishgacha qo‘shishni tanlang", + "Қай жүріÑ�ке дейін қоÑ�уды таңдаңыз", + ], + [ + "Opening training (α version)", + "Тренировка дебюта (α верÑ�иÑ�)", + "Entraînement aux ouvertures (version α)", + "Eröffnungstraining (α-Version)", + "Entrenamiento de aperturas (versión α)", + "Allenamento nelle aperture (versione α)", + "Treino de aberturas (versão α)", + "Debyut mashg‘uloti (α versiya)", + "Дебют жаттығуы (α нұÑ�қаÑ�Ñ‹)", + ], + [ + "Add only the path from the start through this move, with its comments and NAGs", + "Добавить только путь от начала до Ñ�того хода Ñ�о вÑ�еми комментариÑ�ми и NAG", + "Ajouter uniquement le chemin du début jusqu’à ce coup, avec ses commentaires et NAG", + "Nur den Pfad vom Beginn bis zu diesem Zug mit Kommentaren und NAGs hinzufügen", + "Añadir solo la ruta desde el inicio hasta esta jugada, con sus comentarios y NAG", + "Aggiungi solo il percorso dall’inizio fino a questa mossa, con commenti e NAG", + "Adicionar apenas o caminho do início até este lance, com seus comentários e NAGs", + "Faqat boshlang‘ichdan shu yurishgacha bo‘lgan yo‘lni izohlar va NAG bilan qo‘shish", + "Тек баÑ�ынан оÑ�Ñ‹ жүріÑ�ке дейінгі жолды түÑ�ініктемелері мен NAG арқылы қоÑ�у", + ], + [ + "No enabled moves in this repertoire", + "Ð’ репертуаре нет включённых ходов", + "Aucun coup actif dans ce répertoire", + "Keine aktiven Züge in diesem Repertoire", + "No hay jugadas activas en este repertorio", + "Nessuna mossa attiva in questo repertorio", + "Não há lances ativos neste repertório", + "Bu repertuarda faol yurishlar yo‘q", + "Бұл репертуарда белÑ�енді жүріÑ�тер жоқ", + ], + [ + "Choose a repertoire", + "Выберите репертуар", + "Choisissez un répertoire", + "Repertoire auswählen", + "Elige un repertorio", + "Scegli un repertorio", + "Escolha um repertório", + "Repertuarni tanlang", + "Репертуарды таңдаңыз", + ], + [ + "Import PGN…", + "Импорт PGN…", + "Importer un PGN…", + "PGN importieren…", + "Importar PGN…", + "Importa PGN…", + "Importar PGN…", + "PGN import…", + "PGN импорт…", + ], + [ + "Export PGN…", + "ЭкÑ�порт PGN…", + "Exporter le PGN…", + "PGN exportieren…", + "Exportar PGN…", + "Esporta PGN…", + "Exportar PGN…", + "PGN eksport…", + "PGN Ñ�кÑ�порт…", + ], + [ + "Repertoires", + "Репертуары", + "Répertoires", + "Repertoires", + "Repertorios", + "Repertori", + "Repertórios", + "Repertuarlar", + "Репертуарлар", + ], + [ + "Name", + "Ð�азвание", + "Nom", + "Name", + "Nombre", + "Nome", + "Nome", + "Nomi", + "Ð�ты", + ], + [ + "Import into one repertoire", + "Импортировать в один репертуар", + "Importer dans un seul répertoire", + "In ein Repertoire importieren", + "Importar en un solo repertorio", + "Importa in un solo repertorio", + "Importar para um único repertório", + "Bitta repertuarga import qilish", + "Бір репертуарға импорттау", + ], + [ + "No repertoires yet", + "Репертуаров пока нет", + "Aucun répertoire pour le moment", + "Noch keine Repertoires", + "Aún no hay repertorios", + "Ancora nessun repertorio", + "Ainda não há repertórios", + "Hozircha repertuarlar yo‘q", + "Әзірге репертуар жоқ", + ], + [ + "Spanish Opening", + "ИÑ�панÑ�каÑ� партиÑ�", + "Partie espagnole", + "Spanische Partie", + "Apertura española", + "Partita spagnola", + "Abertura Espanhola", + "Ispan o'yini", + "ИÑ�пан партиÑ�Ñ�Ñ‹", + ], + [ + "Sicilian Defence: Najdorf", + "СицилианÑ�каÑ� защита: Ð�айдорф", + "Défense sicilienne : Najdorf", + "Sizilianische Verteidigung: Najdorf", + "Defensa siciliana: Najdorf", + "Difesa siciliana: Najdorf", + "Defesa Siciliana: Najdorf", + "Sitsiliya himoyasi: Naydorf", + "СицилиÑ� қорғаныÑ�Ñ‹: Ð�айдорф", + ], + [ + "The record of example repertoires is damaged; examples were not added", + "ЗапиÑ�ÑŒ о примерах репертуаров повреждена; примеры не добавлены", + "L’enregistrement des répertoires d’exemple est endommagé ; les exemples n’ont pas été ajoutés", + "Die Liste der Beispielrepertoires ist beschädigt; Beispiele wurden nicht hinzugefügt", + "El registro de repertorios de ejemplo está dañado; no se añadieron ejemplos", + "Il registro dei repertori di esempio è danneggiato; gli esempi non sono stati aggiunti", + "O registro dos repertórios de exemplo está danificado; os exemplos não foram adicionados", + "Namuna repertuarlar yozuvi buzilgan; namunalar qo‘shilmadi", + "МыÑ�ал репертуарлар жазбаÑ�Ñ‹ бүлінген; мыÑ�алдар қоÑ�ылмады", + ], + [ + "Queen's Gambit", + "Ферзевый гамбит", + "Gambit dame", + "Damengambit", + "Gambito de dama", + "Gambetto di donna", + "Gambito da Dama", + "Farzin gambiti", + "Ферзь гамбиті", + ], + [ + "Semi-Slav: Triangle", + "ПолуÑ�лавÑ�нÑ�каÑ� защита: треугольник", + "Semi-slave : triangle", + "Halbslawisch: Dreieck", + "Semieslava: triángulo", + "Semi-Slava: triangolo", + "Semi-Eslava: triângulo", + "Yarim slavyan himoyasi: uchburchak", + "Жартылай Ñ�лавÑ�н қорғаныÑ�Ñ‹: үшбұрыш", + ], + [ + "New repertoire", + "Ð�овый репертуар", + "Nouveau répertoire", + "Neues Repertoire", + "Nuevo repertorio", + "Nuovo repertorio", + "Novo repertório", + "Yangi repertuar", + "Жаңа репертуар", + ], + [ + "Enabled moves", + "Включено ходов", + "Coups actifs", + "Aktive Züge", + "Jugadas activas", + "Mosse attive", + "Lances ativos", + "Faol yurishlar", + "БелÑ�енді жүріÑ�тер", + ], + [ + "White: due", + "Белые: к повт.", + "Blancs : à réviser", + "Weiß: fällig", + "Blancas: por repasar", + "Bianco: da ripassare", + "Brancas: por revisar", + "Oq: takrorlash", + "Ð�Ò›: қайталау", + ], + [ + "Black: due", + "Чёрные: к повт.", + "Noirs : à réviser", + "Schwarz: fällig", + "Negras: por repasar", + "Nero: da ripassare", + "Pretas: por revisar", + "Qora: takrorlash", + "Қара: қайталау", + ], + [ + "Both sides", + "Обе Ñ�тороны", + "Les deux camps", + "Beide Seiten", + "Ambos bandos", + "Entrambi i lati", + "Ambos os lados", + "Ikkala tomon", + "Екі тарап", + ], + [ + "This mode has not been used yet", + "Этот режим ещё не иÑ�пользовалÑ�Ñ�", + "Ce mode n’a pas encore été utilisé", + "Dieser Modus wurde noch nicht verwendet", + "Este modo aún no se ha utilizado", + "Questa modalità non è ancora stata usata", + "Este modo ainda não foi usado", + "Bu rejim hali ishlatilmagan", + "Бұл режим әлі қолданылмады", + ], + [ + "Due", + "К повторению", + "À réviser", + "Fällig", + "Por repasar", + "Da ripassare", + "Por revisar", + "Takrorlash", + "Қайталау", + ], + [ + "Delete…", + "Удалить…", + "Supprimer…", + "Löschen…", + "Eliminar…", + "Elimina…", + "Excluir…", + "O‘chirish…", + "Жою…", + ], + [ + "Line", + "ЛиниÑ�", + "Ligne", + "Linie", + "Línea", + "Linea", + "Linha", + "Chiziq", + "Жол", + ], + [ + "Runs", + "ПрохождениÑ�", + "Parcours", + "Durchgänge", + "Recorridos", + "Percorsi", + "Percursos", + "O‘tishlar", + "Өтулер", + ], + [ + "Last mistakes", + "Ошибки поÑ�леднего", + "Erreurs du dernier parcours", + "Fehler im letzten Durchgang", + "Errores del último recorrido", + "Errori dell’ultimo percorso", + "Erros do último percurso", + "Oxirgi o‘tishdagi xatolar", + "Соңғы өтудегі қателер", + ], + [ + "Clean streak", + "ЧиÑ�таÑ� Ñ�ериÑ�", + "Série sans erreur", + "Fehlerfreie Serie", + "Racha sin errores", + "Serie senza errori", + "Sequência sem erros", + "Xatosiz seriya", + "ҚатеÑ�із Ñ�ериÑ�", + ], + [ + "Recent", + "ПоÑ�ледние", + "Récents", + "Zuletzt", + "Recientes", + "Recenti", + "Recentes", + "So‘nggi", + "Соңғы", + ], + [ + "Add to repertoire", + "Добавить в репертуар", + "Ajouter au répertoire", + "Zum Repertoire hinzufügen", + "Añadir al repertorio", + "Aggiungi al repertorio", + "Adicionar ao repertório", + "Repertuariga qo‘shish", + "Репертуарға қоÑ�у", + ], + [ + "â†� Repertoires", + "â†� Репертуары", + "â†� Répertoires", + "â†� Repertoires", + "â†� Repertorios", + "â†� Repertori", + "â†� Repertórios", + "â†� Repertuarlar", + "â†� Репертуарлар", + ], + [ + "Start over", + "Ð�ачать заново", + "Recommencer", + "Neu beginnen", + "Empezar de nuevo", + "Ricomincia", + "Recomeçar", + "Qaytadan boshlash", + "Қайта баÑ�тау", + ], + [ + "Queue", + "Очередь", + "File d’attente", + "Warteschlange", + "Cola", + "Coda", + "Fila", + "Navbat", + "Кезек", + ], + [ + "Path queues are not available in the current core API", + "Очереди путей недоÑ�тупны в текущем API Ñ�дра", + "Les files de chemins ne sont pas disponibles dans l’API actuelle du moteur", + "Pfad-Warteschlangen sind in der aktuellen Core-API nicht verfügbar", + "Las colas de rutas no están disponibles en la API actual del núcleo", + "Le code dei percorsi non sono disponibili nell’API attuale del core", + "As filas de caminhos não estão disponíveis na API atual do núcleo", + "Yo‘l navbatlari joriy yadro API sida mavjud emas", + "Жол кезектері ағымдағы Ñ�дро API-інде жоқ", + ], + [ + "half-moves", + "полуходов", + "demi-coups", + "Halbzüge", + "medias jugadas", + "mezze mosse", + "meio-lances", + "yarim yurishlar", + "жарты жүріÑ�тер", + ], + [ + "No limit", + "Без ограничениÑ�", + "Sans limite", + "Unbegrenzt", + "Sin límite", + "Senza limite", + "Sem limite", + "Cheksiz", + "ШектеуÑ�із", + ], + [ + "Start branch run", + "Ð�ачать проход веток", + "Commencer un parcours de variante", + "Variantendurchgang starten", + "Iniciar recorrido de variantes", + "Avvia percorso della variante", + "Iniciar percurso de variantes", + "Variantlar o‘tishini boshlash", + "Ð�Ò±Ñ�қалар өтіÑ�ін баÑ�тау", + ], + [ + "No enabled moves for this mode and depth", + "Ð�ет включённых ходов длÑ� Ñ�того режима и глубины", + "Aucun coup actif pour ce mode et cette profondeur", + "Keine aktiven Züge für diesen Modus und diese Tiefe", + "No hay jugadas activas para este modo y profundidad", + "Nessuna mossa attiva per questa modalità e profondità", + "Não há lances ativos para este modo e profundidade", + "Bu rejim va chuqurlikda faol yurishlar yo‘q", + "Бұл режим мен тереңдікте белÑ�енді жүріÑ�тер жоқ", + ], + [ + "Tree", + "Дерево", + "Arbre", + "Baum", + "Ã�rbol", + "Albero", + "Ã�rvore", + "Daraxt", + "Ð�ғаш", + ], + [ + "Enable for training", + "Вернуть в тренировку", + "Réactiver pour l’entraînement", + "Wieder trainieren", + "Reactivar para entrenar", + "Riattiva per l’allenamento", + "Reativar para treino", + "Mashg‘ulotga qaytarish", + "Жаттығуға қайтару", + ], + [ + "Disable branch", + "Ð�е учить ветку", + "Ne pas apprendre la variante", + "Variante nicht lernen", + "No aprender la variante", + "Non imparare la variante", + "Não aprender a variante", + "Variantni o‘rganmaslik", + "Ð�Ò±Ñ�қаны үйренмеу", + ], + [ + "There are no moves in this repertoire yet", + "Ð’ репертуаре пока нет ходов", + "Ce répertoire ne contient encore aucun coup", + "Dieses Repertoire enthält noch keine Züge", + "Este repertorio aún no tiene jugadas", + "Questo repertorio non contiene ancora mosse", + "Este repertório ainda não tem lances", + "Bu repertuarda hali yurishlar yo‘q", + "Бұл репертуарда әлі жүріÑ�тер жоқ", + ], + [ + "Or open a game, select the last move of a line and choose “Add to repertoire…â€�.", + "Или откройте партию, выберите поÑ�ледний ход нужной линии и нажмите «Добавить в репертуар…».", + "Ou ouvrez une partie, sélectionnez le dernier coup d’une ligne et choisissez « Ajouter au répertoire… ».", + "Oder öffnen Sie eine Partie, wählen Sie den letzten Zug einer Linie und „Zum Repertoire hinzufügen…“.", + "O abre una partida, selecciona la última jugada de una línea y elige «Añadir al repertorio…».", + "Oppure apri una partita, seleziona l’ultima mossa di una linea e scegli «Aggiungi al repertorio…».", + "Ou abra uma partida, selecione o último lance de uma linha e escolha “Adicionar ao repertório…â€�.", + "Yoki partiyani oching, yo‘ldagi oxirgi yurishni tanlang va “Repertuariga qo‘shish…â€�ni bosing.", + "Ð�емеÑ�е партиÑ�ны ашыңыз, жолдың Ñ�оңғы жүріÑ�ін таңдап, «Репертуарға қоÑ�у…» баÑ�ыңыз.", + ], + [ + " ∅ not trained", + " ∅ не учить", + " ∅ non appris", + " ∅ nicht trainiert", + " ∅ no aprendido", + " ∅ non imparato", + " ∅ não aprendido", + " ∅ o‘rganilmaydi", + " ∅ үйренілмейді", + ], + [ + "Show position", + "Показать позицию", + "Afficher la position", + "Stellung anzeigen", + "Mostrar posición", + "Mostra posizione", + "Mostrar posição", + "Pozitsiyani ko‘rsatish", + "ПозициÑ�ны көрÑ�ету", + ], + [ + "Show move statistics", + "Показать Ñ�татиÑ�тику хода", + "Afficher les statistiques du coup", + "Zugstatistik anzeigen", + "Mostrar estadísticas de la jugada", + "Mostra statistiche della mossa", + "Mostrar estatísticas do lance", + "Yurish statistikasini ko‘rsatish", + "ЖүріÑ� Ñ�татиÑ�тикаÑ�ын көрÑ�ету", + ], + [ + "No attempts in the selected mode", + "Ð�ет попыток в выбранном режиме", + "Aucune tentative dans le mode sélectionné", + "Keine Versuche im gewählten Modus", + "No hay intentos en el modo seleccionado", + "Nessun tentativo nella modalità selezionata", + "Não há tentativas no modo selecionado", + "Tanlangan rejimda urinishlar yo‘q", + "Таңдалған режимде әрекеттер жоқ", + ], + [ + "Filter", + "Фильтр", + "Filtre", + "Filter", + "Filtro", + "Filtro", + "Filtro", + "Filtr", + "Сүзгі", + ], + [ + "With mistakes", + "С ошибками", + "Avec erreurs", + "Mit Fehlern", + "Con errores", + "Con errori", + "Com erros", + "Xatolar bilan", + "Қателермен", + ], + [ + "Wrong", + "Ð�еверных", + "Incorrects", + "Falsch", + "Incorrectas", + "Sbagliate", + "Incorretos", + "Noto‘g‘ri", + "Қате", + ], + [ + "Hints", + "ПодÑ�казки", + "Indices", + "Hinweise", + "Pistas", + "Suggerimenti", + "Dicas", + "Maslahatlar", + "КеңеÑ�тер", + ], + [ + "History", + "ИÑ�ториÑ�", + "Historique", + "Verlauf", + "Historial", + "Cronologia", + "Histórico", + "Tarix", + "Тарих", + ], + [ + "No completed runs", + "Ð�ет завершённых проходов", + "Aucun parcours terminé", + "Keine abgeschlossenen Durchgänge", + "No hay recorridos completados", + "Nessun percorso completato", + "Não há percursos concluídos", + "Yakunlangan o‘tishlar yo‘q", + "Ð�Ñ�қталған өтулер жоқ", + ], + [ + "The PGN file has no games", + "Ð’ PGN-файле нет партий", + "Le fichier PGN ne contient aucune partie", + "Die PGN-Datei enthält keine Partien", + "El archivo PGN no contiene partidas", + "Il file PGN non contiene partite", + "O arquivo PGN não contém partidas", + "PGN faylda partiyalar yo‘q", + "PGN файлда партиÑ�лар жоқ", + ], + [ + "The repertoire name must not be empty", + "Ð�азвание репертуара не должно быть пуÑ�тым", + "Le nom du répertoire ne doit pas être vide", + "Der Repertoirename darf nicht leer sein", + "El nombre del repertorio no debe estar vacío", + "Il nome del repertorio non può essere vuoto", + "O nome do repertório não pode estar vazio", + "Repertuar nomi bo‘sh bo‘lmasligi kerak", + "Репертуар аты боÑ� болмауы керек", + ], + [ + "The repertoire name is longer than 120 characters", + "Ð�азвание репертуара длиннее 120 Ñ�имволов", + "Le nom du répertoire dépasse 120 caractères", + "Der Repertoirename ist länger als 120 Zeichen", + "El nombre del repertorio supera los 120 caracteres", + "Il nome del repertorio supera i 120 caratteri", + "O nome do repertório excede 120 caracteres", + "Repertuar nomi 120 belgidan uzun", + "Репертуар аты 120 таңбадан ұзын", + ], + [ + "A repertoire with this name already exists", + "Репертуар Ñ� таким названием уже Ñ�ущеÑ�твует", + "Un répertoire portant ce nom existe déjà", + "Ein Repertoire mit diesem Namen existiert bereits", + "Ya existe un repertorio con este nombre", + "Esiste già un repertorio con questo nome", + "Já existe um repertório com este nome", + "Bu nomli repertuar allaqachon mavjud", + "Бұл аттағы репертуар бар", + ], + [ + "PGN exported: {path}", + "PGN Ñ�кÑ�портирован: {path}", + "PGN exporté : {path}", + "PGN exportiert: {path}", + "PGN exportado: {path}", + "PGN esportato: {path}", + "PGN exportado: {path}", + "PGN eksport qilindi: {path}", + "PGN Ñ�кÑ�портталды: {path}", + ], + [ + "Could not read statistics: {error}. The file was not replaced", + "Ð�е удалоÑ�ÑŒ прочитать Ñ�татиÑ�тику: {error}. Файл не заменён", + "Impossible de lire les statistiques : {error}. Le fichier n’a pas été remplacé", + "Statistik konnte nicht gelesen werden: {error}. Die Datei wurde nicht ersetzt", + "No se pudieron leer las estadísticas: {error}. El archivo no fue reemplazado", + "Impossibile leggere le statistiche: {error}. Il file non è stato sostituito", + "Não foi possível ler as estatísticas: {error}. O arquivo não foi substituído", + "Statistikani o‘qib bo‘lmadi: {error}. Fayl almashtirilmadi", + "СтатиÑ�тиканы оқу мүмкін емеÑ�: {error}. Файл ауыÑ�тырылмады", + ], + [ + "Reading PGN · records: {n}", + "Чтение PGN · запиÑ�ей: {n}", + "Lecture du PGN · enregistrements : {n}", + "PGN wird gelesen · Einträge: {n}", + "Leyendo PGN · registros: {n}", + "Lettura PGN · record: {n}", + "Lendo PGN · registros: {n}", + "PGN o‘qilmoqda · yozuvlar: {n}", + "PGN оқылуда · жазбалар: {n}", + ], + [ + "Import: {path}", + "Импорт: {path}", + "Import : {path}", + "Import: {path}", + "Importar: {path}", + "Importa: {path}", + "Importar: {path}", + "Import: {path}", + "Импорт: {path}", + ], + [ + "Into one repertoire: {name}", + "Ð’ один репертуар: {name}", + "Dans un seul répertoire : {name}", + "In ein Repertoire: {name}", + "En un solo repertorio: {name}", + "In un solo repertorio: {name}", + "Para um único repertório: {name}", + "Bitta repertuarga: {name}", + "Бір репертуарға: {name}", + ], + [ + "PGN records: {games} · new moves: {added} · matching moves: {matched} · branches: {branches}", + "ЗапиÑ�ей PGN: {games} · новых ходов: {added} · Ñ�овпадающих: {matched} · ветвей: {branches}", + "Enregistrements PGN : {games} · nouveaux coups : {added} · correspondants : {matched} · variantes : {branches}", + "PGN-Einträge: {games} · neue Züge: {added} · übereinstimmende Züge: {matched} · Varianten: {branches}", + "Registros PGN: {games} · jugadas nuevas: {added} · coincidentes: {matched} · variantes: {branches}", + "Record PGN: {games} · nuove mosse: {added} · corrispondenti: {matched} · varianti: {branches}", + "Registros PGN: {games} · novos lances: {added} · coincidentes: {matched} · variantes: {branches}", + "PGN yozuvlari: {games} · yangi yurishlar: {added} · mos: {matched} · variantlar: {branches}", + "PGN жазбалары: {games} · жаңа жүріÑ�тер: {added} · Ñ�әйкеÑ�: {matched} · нұÑ�қалар: {branches}", + ], + [ + "Maximum depth: {depth} half-moves · targets at the current depth: {n}", + "МакÑ�имальнаÑ� глубина: {depth} полуходов · целей при текущей глубине: {n}", + "Profondeur maximale : {depth} demi-coups · cibles à la profondeur actuelle : {n}", + "Maximale Tiefe: {depth} Halbzüge · Ziele bei aktueller Tiefe: {n}", + "Profundidad máxima: {depth} medias jugadas · objetivos a la profundidad actual: {n}", + "Profondità massima: {depth} mezze mosse · obiettivi alla profondità attuale: {n}", + "Profundidade máxima: {depth} meio-lances · objetivos na profundidade atual: {n}", + "Maksimal chuqurlik: {depth} yarim yurish · joriy chuqurlikdagi maqsadlar: {n}", + "Ең тереңдік: {depth} жарты жүріÑ� · ағымдағы тереңдіктегі мақÑ�аттар: {n}", + ], + [ + "Delete “{name}â€� and its new statistics?", + "Удалить «{name}» и вÑ�ÑŽ его новую Ñ�татиÑ�тику?", + "Supprimer « {name} » et ses nouvelles statistiques ?", + "„{name}“ und die neue Statistik löschen?", + "¿Eliminar «{name}» y sus nuevas estadísticas?", + "Eliminare «{name}» e le sue nuove statistiche?", + "Excluir “{name}â€� e suas novas estatísticas?", + "“{name}â€� va uning yangi statistikasini o‘chirish kerakmi?", + "«{name}» және оның жаңа Ñ�татиÑ�тикаÑ�ын жою керек пе?", + ], + [ + "Runs: {n}", + "Прохождений: {n}", + "Parcours : {n}", + "Durchgänge: {n}", + "Recorridos: {n}", + "Percorsi: {n}", + "Percursos: {n}", + "O‘tishlar: {n}", + "Өтулер: {n}", + ], + [ + "{line} — {n} half-moves", + "{line} — {n} полуходов", + "{line} — {n} demi-coups", + "{line} — {n} Halbzüge", + "{line} — {n} medias jugadas", + "{line} — {n} mezze mosse", + "{line} — {n} meio-lances", + "{line} — {n} yarim yurish", + "{line} — {n} жарты жүріÑ�", + ], + [ + "â†� To game {title}", + "â†� К партии {title}", + "â†� Vers la partie {title}", + "â†� Zur Partie {title}", + "â†� A la partida {title}", + "â†� Alla partita {title}", + "â†� Para a partida {title}", + "â†� {title} partiyasiga", + "â†� {title} партиÑ�Ñ�ына", + ], + [ + "Unfinished training: {progress}", + "Ð�езавершённаÑ� тренировка: {progress}", + "Entraînement inachevé : {progress}", + "Nicht abgeschlossenes Training: {progress}", + "Entrenamiento sin terminar: {progress}", + "Allenamento non completato: {progress}", + "Treino não concluído: {progress}", + "Yakunlanmagan mashg‘ulot: {progress}", + "Ð�Ñ�қталмаған жаттығу: {progress}", + ], + [ + "In scope: {targets} · due: {due} · unseen: {unseen}", + "Ð’ облаÑ�ти: {targets} · к повторению: {due} · новых: {unseen}", + "Dans la zone : {targets} · à réviser : {due} · nouveaux : {unseen}", + "Im Bereich: {targets} · fällig: {due} · neu: {unseen}", + "En el ámbito: {targets} · por repasar: {due} · nuevos: {unseen}", + "Nell’ambito: {targets} · da ripassare: {due} · nuovi: {unseen}", + "No âmbito: {targets} · por revisar: {due} · novos: {unseen}", + "Hududda: {targets} · takrorlash: {due} · yangi: {unseen}", + "Ð�ймақта: {targets} · қайталау: {due} · жаңа: {unseen}", + ], + [ + "Start: {n} due", + "Ð�ачать: {n} к повторению", + "Commencer : {n} à réviser", + "Start: {n} fällig", + "Empezar: {n} por repasar", + "Inizia: {n} da ripassare", + "Começar: {n} por revisar", + "Boshlash: {n} takrorlash", + "БаÑ�тау: {n} қайталау", + ], + [ + "Start: {n} new", + "Ð�ачать: {n} новых", + "Commencer : {n} nouveaux", + "Start: {n} neue", + "Empezar: {n} nuevas", + "Inizia: {n} nuove", + "Começar: {n} novos", + "Boshlash: {n} yangi", + "БаÑ�тау: {n} жаңа", + ], + [ + " ⇄ {n} paths", + " ⇄ {n} путей", + " ⇄ {n} chemins", + " ⇄ {n} Pfade", + " ⇄ {n} rutas", + " ⇄ {n} percorsi", + " ⇄ {n} caminhos", + " ⇄ {n} yo‘llar", + " ⇄ {n} жолдар", + ], + [ + "Attempts: {attempts} · correct: {correct} · wrong: {wrong} · hints: {hints}", + "Попыток: {attempts} · верных: {correct} · неверных: {wrong} · подÑ�казок: {hints}", + "Tentatives : {attempts} · correctes : {correct} · incorrectes : {wrong} · indices : {hints}", + "Versuche: {attempts} · richtig: {correct} · falsch: {wrong} · Hinweise: {hints}", + "Intentos: {attempts} · correctas: {correct} · incorrectas: {wrong} · pistas: {hints}", + "Tentativi: {attempts} · corrette: {correct} · sbagliate: {wrong} · suggerimenti: {hints}", + "Tentativas: {attempts} · corretos: {correct} · incorretos: {wrong} · dicas: {hints}", + "Urinishlar: {attempts} · to‘g‘ri: {correct} · noto‘g‘ri: {wrong} · maslahatlar: {hints}", + "Әрекеттер: {attempts} · дұрыÑ�: {correct} · қате: {wrong} · кеңеÑ�тер: {hints}", + ], + [ + "Clean streak: {streak} · last seen: {last} · next due: {due}", + "ЧиÑ�таÑ� Ñ�ериÑ�: {streak} · поÑ�ледний показ: {last} · Ñ�ледующий Ñ�рок: {due}", + "Série sans erreur : {streak} · vu pour la dernière fois : {last} · prochaine révision : {due}", + "Fehlerfreie Serie: {streak} · zuletzt gesehen: {last} · nächster Termin: {due}", + "Racha sin errores: {streak} · última vez: {last} · próximo repaso: {due}", + "Serie senza errori: {streak} · ultima visualizzazione: {last} · prossimo ripasso: {due}", + "Sequência sem erros: {streak} · última visualização: {last} · próxima revisão: {due}", + "Xatosiz seriya: {streak} · oxirgi ko‘rish: {last} · keyingi takrorlash: {due}", + "ҚатеÑ�із Ñ�ериÑ�: {streak} · Ñ�оңғы көрÑ�ету: {last} · келеÑ�Ñ– қайталау: {due}", + ], + [ + "Enabled: {targets} · seen: {seen} · due: {due} · unseen: {unseen} · unscheduled: {unscheduled}", + "Включено: {targets} · показано: {seen} · к повторению: {due} · новых: {unseen} · вне раÑ�пиÑ�аниÑ�: {unscheduled}", + "Actifs : {targets} · vus : {seen} · à réviser : {due} · nouveaux : {unseen} · non planifiés : {unscheduled}", + "Aktiv: {targets} · gesehen: {seen} · fällig: {due} · neu: {unseen} · nicht eingeplant: {unscheduled}", + "Activas: {targets} · vistas: {seen} · por repasar: {due} · nuevas: {unseen} · sin programar: {unscheduled}", + "Attive: {targets} · viste: {seen} · da ripassare: {due} · nuove: {unseen} · non pianificate: {unscheduled}", + "Ativos: {targets} · vistos: {seen} · por revisar: {due} · novos: {unseen} · não agendados: {unscheduled}", + "Faol: {targets} · ko‘rilgan: {seen} · takrorlash: {due} · yangi: {unseen} · rejasiz: {unscheduled}", + "БелÑ�енді: {targets} · көрÑ�етілген: {seen} · қайталау: {due} · жаңа: {unseen} · жоÑ�парÑ�ыз: {unscheduled}", + ], + [ + "{date} · half-moves: {plies} · mistakes: {mistakes} · hints: {hints}", + "{date} · полуходов: {plies} · ошибок: {mistakes} · подÑ�казок: {hints}", + "{date} · demi-coups : {plies} · erreurs : {mistakes} · indices : {hints}", + "{date} · Halbzüge: {plies} · Fehler: {mistakes} · Hinweise: {hints}", + "{date} · medias jugadas: {plies} · errores: {mistakes} · pistas: {hints}", + "{date} · mezze mosse: {plies} · errori: {mistakes} · suggerimenti: {hints}", + "{date} · meio-lances: {plies} · erros: {mistakes} · dicas: {hints}", + "{date} · yarim yurishlar: {plies} · xatolar: {mistakes} · maslahatlar: {hints}", + "{date} · жарты жүріÑ�тер: {plies} · қателер: {mistakes} · кеңеÑ�тер: {hints}", + ], + [ + "Could not read PGN record {n}", + "Ð�е удалоÑ�ÑŒ прочитать запиÑ�ÑŒ PGN {n}", + "Impossible de lire l’enregistrement PGN {n}", + "PGN-Eintrag {n} konnte nicht gelesen werden", + "No se pudo leer el registro PGN {n}", + "Impossibile leggere il record PGN {n}", + "Não foi possível ler o registro PGN {n}", + "PGN {n} yozuvini o‘qib bo‘lmadi", + "PGN {n} жазбаÑ�ын оқу мүмкін емеÑ�", + ], + [ + "PGN record {n} was rejected: {errors}", + "ЗапиÑ�ÑŒ PGN {n} отклонена: {errors}", + "L’enregistrement PGN {n} a été rejeté : {errors}", + "PGN-Eintrag {n} wurde abgelehnt: {errors}", + "El registro PGN {n} fue rechazado: {errors}", + "Il record PGN {n} è stato rifiutato: {errors}", + "O registro PGN {n} foi rejeitado: {errors}", + "PGN {n} yozuvi rad etildi: {errors}", + "PGN {n} жазбаÑ�Ñ‹ қабылданбады: {errors}", + ], + [ + "Record {n}: {message}", + "ЗапиÑ�ÑŒ {n}: {message}", + "Enregistrement {n} : {message}", + "Eintrag {n}: {message}", + "Registro {n}: {message}", + "Record {n}: {message}", + "Registro {n}: {message}", + "{n}-yozuv: {message}", + "{n}-жазба: {message}", + ], + [ + "PGN record {n}: {error}", + "ЗапиÑ�ÑŒ PGN {n}: {error}", + "Enregistrement PGN {n} : {error}", + "PGN-Eintrag {n}: {error}", + "Registro PGN {n}: {error}", + "Record PGN {n}: {error}", + "Registro PGN {n}: {error}", + "PGN {n}-yozuv: {error}", + "PGN {n}-жазба: {error}", + ], + [ + "× This move is outside the enabled variations", + "× Этот ход вне включённых вариантов", + "× Ce coup est en dehors des variantes actives", + "× Dieser Zug liegt außerhalb der aktiven Varianten", + "× Esta jugada está fuera de las variantes activas", + "× Questa mossa è fuori dalle varianti attive", + "× Este lance está fora das variantes ativas", + "× Bu yurish faol variantlardan tashqarida", + "× Бұл жүріÑ� белÑ�енді нұÑ�қалардан тыÑ�", + ], + [ + "× Another move is expected here", + "× СейчаÑ� в репертуаре ожидаетÑ�Ñ� другой ход", + "× Un autre coup est attendu ici", + "× Hier ist ein anderer Zug aus dem Repertoire erwartet", + "× Aquí se espera otra jugada", + "× Qui è prevista un’altra mossa", + "× Outro lance é esperado aqui", + "× Bu yerda boshqa yurish kutilmoqda", + "× Мұнда баÑ�қа жүріÑ� күтілуде", + ], + [ + "This move is in the repertoire, but another one is being reviewed now · Try again", + "Этот ход еÑ�ть в репертуаре, но Ñ�ейчаÑ� повторÑ�етÑ�Ñ� другой · Попробуйте ещё раз", + "Ce coup est dans le répertoire, mais un autre est en cours de révision · Réessayez", + "Dieser Zug ist im Repertoire, aber gerade wird ein anderer wiederholt · Noch einmal versuchen", + "Esta jugada está en el repertorio, pero ahora se repasa otra · Inténtalo de nuevo", + "Questa mossa è nel repertorio, ma ora se ne sta ripassando un’altra · Riprova", + "Este lance está no repertório, mas outro está sendo revisto agora · Tente novamente", + "Bu yurish repertuarda bor, lekin hozir boshqasi takrorlanmoqda · Qayta urining", + "Бұл жүріÑ� репертуарда бар, бірақ қазір баÑ�қаÑ�Ñ‹ қайталануда · Қайта байқап көріңіз", + ], + [ + "Until the depth limit or the end of the branch", + "До глубины или конца ветки", + "Jusqu’à la profondeur limite ou la fin de la variante", + "Bis zur Tiefengrenze oder zum Ende der Variante", + "Hasta el límite de profundidad o el final de la variante", + "Fino al limite di profondità o alla fine della variante", + "Até ao limite de profundidade ou ao fim da variante", + "Chuqurlik chegarasigacha yoki variant oxirigacha", + "Тереңдік шегіне дейін немеÑ�е нұÑ�қа аÑ�ғына дейін", + ], + [ + "New run", + "Ð�овый проход", + "Nouveau parcours", + "Neuer Durchgang", + "Nuevo recorrido", + "Nuovo percorso", + "Novo percurso", + "Yangi o‘tish", + "Жаңа өту", + ], + [ + "Half-moves played: {n}", + "Сыграно полуходов: {n}", + "Demi-coups joués : {n}", + "Gespielte Halbzüge: {n}", + "Medias jugadas: {n}", + "Mezze mosse giocate: {n}", + "Meio-lances jogados: {n}", + "O‘ynalgan yarim yurishlar: {n}", + "Ойналған жарты жүріÑ�тер: {n}", + ], + [ + "Half-move {n}", + "Полуход {n}", + "Demi-coup {n}", + "Halbzug {n}", + "Media jugada {n}", + "Mezza mossa {n}", + "Meio-lance {n}", + "{n}-yarim yurish", + "{n}-жарты жүріÑ�", + ], + [ + "Half-moves played: {n} · mistakes: {m}", + "Пройдено полуходов: {n} · ошибок: {m}", + "Demi-coups joués : {n} · erreurs : {m}", + "Gespielte Halbzüge: {n} · Fehler: {m}", + "Medias jugadas: {n} · errores: {m}", + "Mezze mosse giocate: {n} · errori: {m}", + "Meio-lances jogados: {n} · erros: {m}", + "O‘ynalgan yarim yurishlar: {n} · xatolar: {m}", + "Ойналған жарты жүріÑ�тер: {n} · қателер: {m}", + ], + [ + "Enabled half-moves: {targets} · completed runs: {runs}", + "Включено полуходов: {targets} · завершено проходов: {runs}", + "Demi-coups actifs : {targets} · parcours terminés : {runs}", + "Aktive Halbzüge: {targets} · abgeschlossene Durchgänge: {runs}", + "Medias jugadas activas: {targets} · recorridos completados: {runs}", + "Mezze mosse attive: {targets} · percorsi completati: {runs}", + "Meio-lances ativos: {targets} · percursos concluídos: {runs}", + "Faol yarim yurishlar: {targets} · yakunlangan o‘tishlar: {runs}", + "БелÑ�енді жарты жүріÑ�тер: {targets} · аÑ�қталған өтулер: {runs}", + ], + [ + "No due or unseen targets; choose a review queue", + "Ð�ет целей к повторению или новых; выберите обзорную очередь", + "Aucune cible à réviser ou nouvelle ; choisissez une file de révision", + "Keine fälligen oder neuen Ziele; wählen Sie eine Wiederholungswarteschlange", + "No hay objetivos por repasar ni nuevos; elige una cola de repaso", + "Nessun obiettivo da ripassare o nuovo; scegli una coda di ripasso", + "Não há objetivos por revisar ou novos; escolha uma fila de revisão", + "Takrorlanadigan yoki yangi maqsad yo‘q; takrorlash navbatini tanlang", + "Қайталанатын немеÑ�е жаңа мақÑ�ат жоқ; қайталау кезегін таңдаңыз", + ], + [ + "Last played", + "ПоÑ�ледний раз Ñ�ыгран", + "Dernière fois joué", + "Zuletzt gespielt", + "Última vez jugado", + "Ultima mossa giocata", + "Última vez jogado", + "Oxirgi o‘ynalgan", + "Соңғы ойналған", + ], + [ + "Last played: {last}", + "ПоÑ�ледний раз Ñ�ыгран: {last}", + "Dernière fois joué : {last}", + "Zuletzt gespielt: {last}", + "Última vez jugado: {last}", + "Ultima mossa giocata: {last}", + "Última vez jogado: {last}", + "Oxirgi o‘ynalgan: {last}", + "Соңғы ойналған: {last}", + ], + [ + "Enabled half-moves: {targets} · played: {seen} · completed runs: {runs}", + "Включено полуходов: {targets} · Ñ�ыграно: {seen} · завершено проходов: {runs}", + "Demi-coups actifs : {targets} · joués : {seen} · parcours terminés : {runs}", + "Aktive Halbzüge: {targets} · gespielt: {seen} · abgeschlossene Durchgänge: {runs}", + "Medias jugadas activas: {targets} · jugadas: {seen} · recorridos completados: {runs}", + "Mezze mosse attive: {targets} · giocate: {seen} · percorsi completati: {runs}", + "Meio-lances ativos: {targets} · jogados: {seen} · percursos concluídos: {runs}", + "Faol yarim yurishlar: {targets} · o‘ynalgan: {seen} · yakunlangan o‘tishlar: {runs}", + "БелÑ�енді жарты жүріÑ�тер: {targets} · ойналған: {seen} · аÑ�қталған өтулер: {runs}", + ], + [ + "Spaced schedule", + "По раÑ�пиÑ�анию", + "Répétition espacée", + "Nach Zeitplan", + "Repetición espaciada", + "Ripetizione spaziata", + "Repetição espaçada", + "Oraliq jadval", + "Ð�ралық кеÑ�те", + ], + [ + "Unscheduled", + "Вне раÑ�пиÑ�аниÑ�", + "Non planifié", + "Nicht eingeplant", + "Sin programar", + "Non pianificato", + "Não agendado", + "Rejasiz", + "ЖоÑ�парÑ�ыз", + ], + [ + "Scope", + "ОблаÑ�ть", + "Zone", + "Bereich", + "Ã�mbito", + "Ambito", + "Âmbito", + "Hudud", + "Ð�ймақ", + ], + [ + "Reset scope", + "СброÑ�ить облаÑ�ть", + "Réinitialiser la zone", + "Bereich zurücksetzen", + "Restablecer ámbito", + "Reimposta ambito", + "Redefinir âmbito", + "Hududni tiklash", + "Ð�ймақты қалпына келтіру", + ], + [ + "Use selected as scope", + "Сделать выбранное облаÑ�тью", + "Utiliser la sélection comme zone", + "Auswahl als Bereich verwenden", + "Usar selección como ámbito", + "Usa selezione come ambito", + "Usar seleção como âmbito", + "Tanlanganini hudud qilish", + "Таңдалғанды аймақ ету", + ], + [ + "End scope here", + "Завершить облаÑ�ть здеÑ�ÑŒ", + "Terminer la zone ici", + "Bereich hier beenden", + "Terminar ámbito aquí", + "Termina ambito qui", + "Terminar âmbito aqui", + "Hududni shu yerda tugatish", + "Ð�ймақты оÑ�Ñ‹ жерде аÑ�қтау", + ], + [ + "Replay automatic context", + "Показывать автоматичеÑ�кий контекÑ�Ñ‚", + "Rejouer le contexte automatique", + "Automatischen Kontext abspielen", + "Reproducir contexto automático", + "Riproduci contesto automatico", + "Reproduzir contexto automático", + "Avtomatik kontekstni ko‘rsatish", + "Ð�втоматты контекÑ�тті көрÑ�ету", + ], + [ + "Paths completed: {completed} of {total}", + "Завершено путей: {completed} из {total}", + "Chemins terminés : {completed} sur {total}", + "Abgeschlossene Pfade: {completed} von {total}", + "Rutas completadas: {completed} de {total}", + "Percorsi completati: {completed} di {total}", + "Caminhos concluídos: {completed} de {total}", + "Yakunlangan yo‘llar: {completed} / {total}", + "Ð�Ñ�қталған жолдар: {completed} / {total}", + ], + [ + "Start review: {n}", + "Ð�ачать обзор: {n}", + "Commencer la révision : {n}", + "Wiederholung starten: {n}", + "Empezar repaso: {n}", + "Inizia ripasso: {n}", + "Começar revisão: {n}", + "Takrorlashni boshlash: {n}", + "Қайталауды баÑ�тау: {n}", + ], + [ + " [scope end]", + " [конец облаÑ�ти]", + " [fin de zone]", + " [Bereichsende]", + " [fin del ámbito]", + " [fine ambito]", + " [fim do âmbito]", + " [hudud oxiri]", + " [аймақ аÑ�Ò“Ñ‹]", + ], + [ + "Whole repertoire", + "ВеÑ�ÑŒ репертуар", + "Tout le répertoire", + "Gesamtes Repertoire", + "Todo el repertorio", + "Tutto il repertorio", + "Todo o repertório", + "Butun repertuar", + "Бүкіл репертуар", + ], + [ + "From {path}", + "От {path}", + "À partir de {path}", + "Ab {path}", + "Desde {path}", + "Da {path}", + "A partir de {path}", + "{path}dan", + "{path}тан", + ], + [ + " · end {path}", + " · конец {path}", + " · fin {path}", + " · Ende {path}", + " · fin {path}", + " · fine {path}", + " · fim {path}", + " · oxir {path}", + " · аÑ�Ò› {path}", + ], + [ + "· Automatic move/context", + "· Ð�втоматичеÑ�кий ход/контекÑ�Ñ‚", + "· Coup/contexte automatique", + "· Automatischer Zug/Kontext", + "· Jugada/contexto automático", + "· Mossa/contesto automatico", + "· Lance/contexto automático", + "· Avtomatik yurish/kontekst", + "· Ð�втоматты жүріÑ�/контекÑ�Ñ‚", + ], + [ + "Early review · schedule unchanged", + "ДоÑ�рочный обзор · Ñ�роки не менÑ�ÑŽÑ‚Ñ�Ñ�", + "Révision anticipée · calendrier inchangé", + "Vorzeitige Wiederholung · Zeitplan unverändert", + "Repaso anticipado · calendario sin cambios", + "Ripasso anticipato · calendario invariato", + "Revisão antecipada · calendário inalterado", + "Erta takrorlash · jadval o‘zgarmaydi", + "Ерте қайталау · кеÑ�те өзгермейді", + ], + [ + "Due now: {n}", + "К повторению Ñ�ейчаÑ�: {n}", + "À réviser maintenant : {n}", + "Jetzt fällig: {n}", + "Por repasar ahora: {n}", + "Da ripassare ora: {n}", + "Por revisar agora: {n}", + "Hozir takrorlash: {n}", + "Қазір қайталау: {n}", + ], + [ + "Introduce new: {batch} of {remaining}", + "Добавить новые: {batch} из {remaining}", + "Introduire de nouveaux : {batch} sur {remaining}", + "Neue hinzufügen: {batch} von {remaining}", + "Introducir nuevas: {batch} de {remaining}", + "Introduci nuove: {batch} di {remaining}", + "Introduzir novos: {batch} de {remaining}", + "Yangilarini qo‘shish: {batch} / {remaining}", + "Жаңаларын қоÑ�у: {batch} / {remaining}", + ], + [ + "Review future moves early", + "Повторить будущие раньше", + "Réviser les coups futurs plus tôt", + "Künftige Züge früher wiederholen", + "Repasar jugadas futuras antes", + "Ripassa prima le mosse future", + "Revisar lances futuros mais cedo", + "Kelajakdagi yurishlarni erta takrorlash", + "Болашақ жүріÑ�терді ерте қайталау", + ], + [ + "Review due moves", + "Повторить текущие", + "Réviser les coups à réviser", + "Fällige Züge wiederholen", + "Repasar jugadas pendientes", + "Ripassa mosse da ripassare", + "Revisar lances por revisar", + "Takrorlanadigan yurishlarni takrorlash", + "Қайталанатын жүріÑ�терді қайталау", + ], + [ + "Paths", + "Пути", + "Chemins", + "Pfade", + "Rutas", + "Percorsi", + "Caminhos", + "Yo‘llar", + "Жолдар", + ], + [ + "Path", "Путь", "Chemin", "Pfad", "Ruta", "Percorso", "Caminho", "Yo‘l", "Жол", + ], + [ + "Completions", + "ЗавершениÑ�", + "Achèvements", + "Abschlüsse", + "Finalizaciones", + "Completamenti", + "Conclusões", + "Yakunlashlar", + "Ð�Ñ�қтаулар", + ], + [ + "Last completion", + "ПоÑ�леднее завершение", + "Dernier achèvement", + "Letzter Abschluss", + "Última finalización", + "Ultimo completamento", + "Última conclusão", + "Oxirgi yakunlash", + "Соңғы аÑ�қтау", + ], + [ + "No paths", + "Ð�ет путей", + "Aucun chemin", + "Keine Pfade", + "No hay rutas", + "Nessun percorso", + "Não há caminhos", + "Yo‘llar yo‘q", + "Жолдар жоқ", + ], + [ + "{n} new paths", + "Ð�овых путей: {n}", + "{n} nouveaux chemins", + "Neue Pfade: {n}", + "{n} rutas nuevas", + "{n} nuovi percorsi", + "{n} novos caminhos", + "{n} yangi yo‘l", + "{n} жаңа жол", + ], + [ + "In order", + "По порÑ�дку", + "Dans l’ordre", + "Der Reihe nach", + "En orden", + "In ordine", + "Em ordem", + "Tartib bilan", + "Ретімен", + ], + [ + "With review", + "С повторениÑ�ми", + "Avec révision", + "Mit Wiederholung", + "Con repaso", + "Con ripasso", + "Com revisão", + "Takrorlash bilan", + "Қайталаумен", + ], + [ + "No moves for this color in the PGN file", + "Ð’ PGN-файле нет ходов длÑ� Ñ�того цвета", + "Aucun coup pour cette couleur dans le fichier PGN", + "Keine Züge für diese Farbe in der PGN-Datei", + "No hay jugadas para este color en el archivo PGN", + "Nessuna mossa per questo colore nel file PGN", + "Não há lances para esta cor no arquivo PGN", + "PGN faylda bu rang uchun yurishlar yo‘q", + "PGN файлда бұл түÑ� үшін жүріÑ�тер жоқ", + ], + [ + "Add PGN…", + "Добавить PGN…", + "Ajouter un PGN…", + "PGN hinzufügen…", + "Añadir PGN…", + "Aggiungi PGN…", + "Adicionar PGN…", + "PGN qo‘shish…", + "PGN қоÑ�у…", + ], + [ + "Create new PGN…", + "Создать новый PGN…", + "Créer un nouveau PGN…", + "Neue PGN erstellen…", + "Crear un PGN nuevo…", + "Crea un nuovo PGN…", + "Criar novo PGN…", + "Yangi PGN yaratish…", + "Жаңа PGN жаÑ�ау…", + ], + [ + "Save as PGN and link…", + "Сохранить как PGN и привÑ�зать…", + "Enregistrer en PGN et lier…", + "Als PGN speichern und verknüpfen…", + "Guardar como PGN y vincular…", + "Salva come PGN e collega…", + "Guardar como PGN e vincular…", + "PGN saqlash va bog‘lash…", + "PGN Ñ�ақтау және байланыÑ�тыру…", + ], + [ + "New PGN…", + "Ð�овый PGN…", + "Nouveau PGN…", + "Neue PGN…", + "Nuevo PGN…", + "Nuovo PGN…", + "Novo PGN…", + "Yangi PGN…", + "Жаңа PGN…", + ], + [ + "Other PGN…", + "Другой PGN…", + "Autre PGN…", + "Andere PGN…", + "Otro PGN…", + "Altro PGN…", + "Outro PGN…", + "Boshqa PGN…", + "БаÑ�қа PGN…", + ], + [ + "Choose a PGN file", + "Выберите PGN-файл", + "Choisissez un fichier PGN", + "PGN-Datei auswählen", + "Elige un archivo PGN", + "Scegli un file PGN", + "Escolha um arquivo PGN", + "PGN faylni tanlang", + "PGN файлды таңдаңыз", + ], + [ + "Start training", + "Ð�ачать", + "Commencer l’entraînement", + "Training starten", + "Empezar entrenamiento", + "Inizia allenamento", + "Iniciar treino", + "Mashg‘ulotni boshlash", + "Жаттығуды баÑ�тау", + ], + [ + "The PGN file itself is not deleted", + "Сам PGN-файл не удалÑ�етÑ�Ñ�", + "Le fichier PGN lui-même n’est pas supprimé", + "Die PGN-Datei selbst wird nicht gelöscht", + "El archivo PGN no se elimina", + "Il file PGN non viene eliminato", + "O arquivo PGN em si não é excluído", + "PGN faylning o‘zi o‘chirilmaydi", + "PGN файлдың өзі өшірілмейді", + ], + [ + "No PGN files yet. Add an existing file or create a new one.", + "PGN-файлов пока нет. Добавьте Ñ�ущеÑ�твующий файл или Ñ�оздайте новый.", + "Aucun fichier PGN pour le moment. Ajoutez un fichier existant ou créez-en un nouveau.", + "Noch keine PGN-Dateien. Fügen Sie eine vorhandene Datei hinzu oder erstellen Sie eine neue.", + "Aún no hay archivos PGN. Añade uno existente o crea uno nuevo.", + "Ancora nessun file PGN. Aggiungi un file esistente o creane uno nuovo.", + "Ainda não há arquivos PGN. Adicione um existente ou crie um novo.", + "Hozircha PGN fayllar yo‘q. Mavjud faylni qo‘shing yoki yangisini yarating.", + "Әзірге PGN файлдар жоқ. Бар файлды қоÑ�ыңыз немеÑ�е жаңаÑ�ын жаÑ�аңыз.", + ], + [ + "Legacy records without PGN", + "Старые запиÑ�и без PGN", + "Anciens enregistrements sans PGN", + "Alte Einträge ohne PGN", + "Registros antiguos sin PGN", + "Vecchi record senza PGN", + "Registros antigos sem PGN", + "PGN-siz eski yozuvlar", + "PGN-Ñ�із еÑ�кі жазбалар", + ], + [ + "Choose a PGN file, then choose a color and start.", + "Выберите PGN-файл, затем цвет и начните тренировку.", + "Choisissez un fichier PGN, puis une couleur, et commencez.", + "Wählen Sie eine PGN-Datei, dann eine Farbe, und starten Sie.", + "Elige un archivo PGN, después un color y empieza.", + "Scegli un file PGN, poi un colore e inizia.", + "Escolha um arquivo PGN, depois uma cor e comece.", + "PGN faylni, so‘ng rangni tanlab boshlang.", + "PGN файлды, Ñ�одан Ñ�оң түÑ�ті таңдап баÑ�таңыз.", + ], + [ + "The file could not be read; its cached copy will not be used", + "Файл не удалоÑ�ÑŒ прочитать; Ñ�тарый Ñ�нимок не будет иÑ�пользован", + "Le fichier n’a pas pu être lu ; sa copie en cache ne sera pas utilisée", + "Die Datei konnte nicht gelesen werden; ihre zwischengespeicherte Kopie wird nicht verwendet", + "No se pudo leer el archivo; no se usará su copia en caché", + "Impossibile leggere il file; la copia nella cache non verrà usata", + "Não foi possível ler o arquivo; sua cópia em cache não será usada", + "Faylni o‘qib bo‘lmadi; keshdagi nusxasi ishlatilmaydi", + "Файлды оқу мүмкін емеÑ�; кÑ�штегі нұÑ�қаÑ�Ñ‹ қолданылмайды", + ], + [ + "Color", "Цвет", "Couleur", "Farbe", "Color", "Colore", "Cor", "Rang", "ТүÑ�", + ], + [ + "Both: you play every move; only moves from this PGN are accepted", + "Обе Ñ�тороны: вÑ�е ходы делаете вы; принимаютÑ�Ñ� только ходы из Ñ�того PGN", + "Les deux : vous jouez chaque coup ; seuls les coups de ce PGN sont acceptés", + "Beide: Sie spielen jeden Zug; nur Züge aus dieser PGN werden akzeptiert", + "Ambos: juegas cada jugada; solo se aceptan jugadas de este PGN", + "Entrambi: giochi ogni mossa; sono accettate solo mosse di questo PGN", + "Ambos: você joga cada lance; apenas lances deste PGN são aceitos", + "Ikkala rang: har yurishni o‘zingiz qilasiz; faqat shu PGN dagi yurishlar qabul qilinadi", + "Екі түÑ�: әр жүріÑ�ті өзіңіз жаÑ�айÑ�ыз; тек оÑ�Ñ‹ PGN дегі жүріÑ�тер қабылданады", + ], + [ + "White/Black: you play your color; the program answers from this PGN", + "Белые/чёрные: вы играете Ñ�воим цветом, программа отвечает ходами из Ñ�того PGN", + "Blancs/Noirs : vous jouez votre couleur ; le programme répond avec ce PGN", + "Weiß/Schwarz: Sie spielen Ihre Farbe; das Programm antwortet aus dieser PGN", + "Blancas/Negras: juegas tu color; el programa responde con este PGN", + "Bianco/Nero: giochi il tuo colore; il programma risponde con questo PGN", + "Brancas/Pretas: você joga sua cor; o programa responde com este PGN", + "Oq/Qora: o‘z rangingiz bilan yurasiz; dastur shu PGN dan javob beradi", + "Ð�Ò›/Қара: өз түÑ�іңізбен жүріÑ�Ñ�із; бағдарлама оÑ�Ñ‹ PGN нан жауап береді", + ], + [ + "No training yet", + "Тренировок ещё не было", + "Aucun entraînement pour le moment", + "Noch kein Training", + "Aún sin entrenamiento", + "Ancora nessun allenamento", + "Ainda sem treino", + "Hozircha mashg‘ulot bo‘lmadi", + "Әзірге жаттығу болмады", + ], + [ + "Target PGN", + "Целевой PGN", + "PGN cible", + "Ziel-PGN", + "PGN de destino", + "PGN di destinazione", + "PGN de destino", + "Maqsad PGN", + "МақÑ�ат PGN", + ], + [ + "The new file will be created only after Add", + "Ð�овый файл будет Ñ�оздан только поÑ�ле нажатиÑ� «Добавить»", + "Le nouveau fichier sera créé seulement après « Ajouter »", + "Die neue Datei wird erst nach „Hinzufügen“ erstellt", + "El nuevo archivo se creará solo después de «Añadir»", + "Il nuovo file sarà creato solo dopo «Aggiungi»", + "O novo arquivo será criado somente após «Adicionar»", + "Yangi fayl faqat «Qo‘shish»dan so‘ng yaratiladi", + "Жаңа файл тек «ҚоÑ�у»дан кейін жаÑ�алады", + ], + [ + "This exact PGN file will be changed. The source game and its database will not change.", + "Будет изменён именно Ñ�тот PGN-файл. ИÑ�ходнаÑ� партиÑ� и её база не изменÑ�Ñ‚Ñ�Ñ�.", + "Ce fichier PGN précis sera modifié. La partie source et sa base ne changeront pas.", + "Genau diese PGN-Datei wird geändert. Die Ausgangspartie und ihre Datenbank bleiben unverändert.", + "Se modificará exactamente este archivo PGN. La partida original y su base no cambiarán.", + "Sarà modificato proprio questo file PGN. La partita di origine e il suo database non cambieranno.", + "Exatamente este arquivo PGN será alterado. A partida de origem e sua base não serão alteradas.", + "Aynan shu PGN fayl o‘zgaradi. Manba partiya va uning bazasi o‘zgarmaydi.", + "Дәл оÑ�Ñ‹ PGN файл өзгереді. БаÑ�тапқы партиÑ� және оның базаÑ�Ñ‹ өзгермейді.", + ], + [ + "Attempts: {attempts} · Mistakes: {mistakes} · Clean streak: {streak} · Last: {last}", + "Попытки: {attempts} · ошибки: {mistakes} · чиÑ�таÑ� Ñ�ериÑ�: {streak} · поÑ�леднÑ�Ñ�: {last}", + "Tentatives : {attempts} · erreurs : {mistakes} · série sans erreur : {streak} · dernière : {last}", + "Versuche: {attempts} · Fehler: {mistakes} · fehlerfreie Serie: {streak} · zuletzt: {last}", + "Intentos: {attempts} · errores: {mistakes} · racha sin errores: {streak} · última: {last}", + "Tentativi: {attempts} · errori: {mistakes} · serie senza errori: {streak} · ultima: {last}", + "Tentativas: {attempts} · erros: {mistakes} · sequência sem erros: {streak} · última: {last}", + "Urinishlar: {attempts} · xatolar: {mistakes} · xatosiz seriya: {streak} · so‘nggi: {last}", + "Әрекеттер: {attempts} · қателер: {mistakes} · қатеÑ�із Ñ�ериÑ�: {streak} · Ñ�оңғыÑ�Ñ‹: {last}", + ], + [ + "New moves: {added} · annotation additions: {annotations}", + "Ð�овых ходов: {added} · добавлено аннотаций: {annotations}", + "Nouveaux coups : {added} · annotations ajoutées : {annotations}", + "Neue Züge: {added} · hinzugefügte Anmerkungen: {annotations}", + "Jugadas nuevas: {added} · anotaciones añadidas: {annotations}", + "Nuove mosse: {added} · annotazioni aggiunte: {annotations}", + "Novos lances: {added} · anotações adicionadas: {annotations}", + "Yangi yurishlar: {added} · qo‘shilgan izohlar: {annotations}", + "Жаңа жүріÑ�тер: {added} · қоÑ�ылған түÑ�ініктемелер: {annotations}", + ], + [ + "Play every move from this PGN", + "Сыграйте каждый ход из Ñ�того PGN", + "Jouez chaque coup de ce PGN", + "Spielen Sie jeden Zug aus dieser PGN", + "Juega cada jugada de este PGN", + "Gioca ogni mossa di questo PGN", + "Jogue cada lance deste PGN", + "Shu PGN dagi har yurishni o‘ynang", + "ОÑ�Ñ‹ PGN дегі әр жүріÑ�ті орындаңыз", + ], + [ + "The program answers from this PGN", + "Программа отвечает ходами из Ñ�того PGN", + "Le programme répond avec ce PGN", + "Das Programm antwortet aus dieser PGN", + "El programa responde con este PGN", + "Il programma risponde con questo PGN", + "O programa responde com este PGN", + "Dastur shu PGN dan javob beradi", + "Бағдарлама оÑ�Ñ‹ PGN нан жауап береді", + ], + [ + "Back to files", + "К файлам", + "Retour aux fichiers", + "Zurück zu Dateien", + "Volver a archivos", + "Torna ai file", + "Voltar aos arquivos", + "Fayllarga qaytish", + "Файлдарға қайту", + ], + [ + "â†� Back to files", + "â†� К файлам", + "â†� Retour aux fichiers", + "â†� Zurück zu Dateien", + "â†� Volver a archivos", + "â†� Torna ai file", + "â†� Voltar aos arquivos", + "â†� Fayllarga qaytish", + "â†� Файлдарға қайту", + ], + [ + "The library changed; import the PGN again", + "Библиотека изменилаÑ�ÑŒ; импортируйте PGN заново", + "La bibliothèque a changé ; importez à nouveau le PGN", + "Die Bibliothek wurde geändert; importieren Sie die PGN erneut", + "La biblioteca ha cambiado; importe el PGN de nuevo", + "La raccolta è cambiata; importa nuovamente il PGN", + "A biblioteca mudou; importe o PGN novamente", + "Kutubxona o‘zgardi; PGN faylni qayta import qiling", + "Кітапхана өзгерді; PGN файлын қайта импорттаңыз", + ], + [ + "Enable the parent branch first", + "Сначала включите родительÑ�кую ветку", + "Activez d’abord la variante parente", + "Aktivieren Sie zuerst die übergeordnete Variante", + "Active primero la variante superior", + "Attiva prima la variante principale", + "Ative primeiro a variante superior", + "Avval yuqori variantni yoqing", + "Ð�лдымен жоғарғы нұÑ�қаны қоÑ�ыңыз", + ], + [ + "No games", + "Ð�ет партий", + "Aucune partie", + "Keine Partien", + "No hay partidas", + "Nessuna partita", + "Nenhuma partida", + "Partiyalar yo‘q", + "ПартиÑ�лар жоқ", + ], + [ + "Delete repertoire and its statistics? Source PGN files will not change.", + "Удалить репертуар и его Ñ�татиÑ�тику? ИÑ�Ñ…Ð¾Ð´Ð½Ñ‹Ðµ PGN-файлы не изменÑ�Ñ‚Ñ�Ñ�.", + "Supprimer le répertoire et ses statistiques ? Les fichiers PGN sources ne seront pas modifiés.", + "Repertoire und seine Statistik löschen? PGN-Quelldateien bleiben unverändert.", + "¿Eliminar el repertorio y sus estadísticas? Los archivos PGN originales no cambiarán.", + "Eliminare il repertorio e le sue statistiche? I file PGN originali non cambieranno.", + "Excluir o repertório e suas estatísticas? Os arquivos PGN originais não serão alterados.", + "Repertuar va uning statistikasini o‘chirasizmi? Asl PGN fayllar o‘zgarmaydi.", + "Репертуар мен оның Ñ�татиÑ�тикаÑ�ын жою керек пе? БаÑ�тапқы PGN файлдары өзгермейді.", + ], + [ + "Save", + "Сохранить", + "Enregistrer", + "Speichern", + "Guardar", + "Salva", + "Salvar", + "Saqlash", + "Сақтау", + ], + [ + "Introduce new moves", + "Добавить новые ходы", + "Introduire de nouveaux coups", + "Neue Züge einführen", + "Introducir nuevas jugadas", + "Introduci nuove mosse", + "Introduzir novos lances", + "Yangi yurishlarni qo‘shish", + "Жаңа жүріÑ�терді қоÑ�у", + ], + [ + "Move statistics", + "СтатиÑ�тика хода", + "Statistiques du coup", + "Zugstatistik", + "Estadísticas de la jugada", + "Statistiche della mossa", + "Estatísticas do lance", + "Yurish statistikasi", + "ЖүріÑ� Ñ�татиÑ�тикаÑ�Ñ‹", + ], + [ + "Next review", + "Следующее повторение", + "Prochaine révision", + "Nächste Wiederholung", + "Próximo repaso", + "Prossimo ripasso", + "Próxima revisão", + "Keyingi takrorlash", + "КелеÑ�Ñ– қайталау", + ], + [ + "Last attempt", + "ПоÑ�леднÑ�Ñ� попытка", + "Dernier essai", + "Letzter Versuch", + "Último intento", + "Ultimo tentativo", + "Última tentativa", + "Oxirgi urinish", + "Соңғы әрекет", + ], + [ + "Branch statistics", + "СтатиÑ�тика веток", + "Statistiques des variantes", + "Variantenstatistik", + "Estadísticas de variantes", + "Statistiche delle varianti", + "Estatísticas das variantes", + "Variantlar statistikasi", + "Ð�Ò±Ñ�қалар Ñ�татиÑ�тикаÑ�Ñ‹", + ], + [ + "Play through variations", + "Пройти варианты", + "Play through variations", + "Varianten durchspielen", + "Play through variations", + "Play through variations", + "Play through variations", + "Play through variations", + "Play through variations", + ], + [ + "Review individual moves", + "ПовторÑ�ть отдельные позиции", + "Review individual moves", + "Einzelne Stellungen wiederholen", + "Review individual moves", + "Review individual moves", + "Review individual moves", + "Review individual moves", + "Review individual moves", + ], + [ + "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", + "Пройдите ветку от начала до конца. Любой включённый ход принимаетÑ�Ñ�; за Ñ�оперника отвечает программа.", + "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", + "Spielen Sie eine Variante bis zum Ende. Jeder aktivierte Zug wird akzeptiert; das Programm spielt die Gegenseite.", + "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", + "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", + "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", + "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", + "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", + ], + [ + "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", + "ЗдеÑ�ÑŒ повторÑ�ÑŽÑ‚Ñ�Ñ� отдельные позиции. Любой ход репертуара принимаетÑ�Ñ�; учитываетÑ�Ñ� только Ñ�ыгранный вами ход.", + "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", + "Hier werden einzelne Stellungen wiederholt. Jeder Repertoirezug wird akzeptiert; nur Ihr gespielter Zug wird erfasst.", + "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", + "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", + "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", + "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", + "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", + ], + // --- strict learning session --- + [ + "Spaced repetition (SRS)", + "Интервальные повторениÑ� (SRS)", + "Répétition espacée (SRS)", + "Verteilte Wiederholung (SRS)", + "Repetición espaciada (SRS)", + "Ripetizione spaziata (SRS)", + "Repetição espaçada (SRS)", + "Oraliq takrorlash (SRS)", + "Ð�ралық қайталау (SRS)", + ], + [ + "Hint", + "ПодÑ�казка", + "Indice", + "Hinweis", + "Pista", + "Suggerimento", + "Dica", + "Maslahat", + "КеңеÑ�", + ], + [ + "Next", + "Далее", + "Suivant", + "Weiter", + "Siguiente", + "Avanti", + "Avançar", + "Keyingisi", + "КелеÑ�Ñ–", + ], + [ + "Your turn: play the main repertoire move.", + "Ваш ход: Ñ�ыграйте оÑ�новной ход репертуара.", + "À vous de jouer : jouez le coup principal du répertoire.", + "Sie sind am Zug: Spielen Sie den Hauptzug des Repertoires.", + "Tu turno: juega la jugada principal del repertorio.", + "Tocca a te: gioca la mossa principale del repertorio.", + "Sua vez: jogue o lance principal do repertório.", + "Sizning yurishingiz: repertuardagi asosiy yurishni o‘ynang.", + "Сіздің жүріÑ�іңіз: репертуардың негізгі жүріÑ�ін жаÑ�аңыз.", + ], + ["T", "T", "T", "T", "T", "T", "T", "T", "T"], + [ + "Context and move speed", + "КонтекÑ�Ñ‚ и Ñ�короÑ�ть ходов", + "Contexte et vitesse des coups", + "Kontext und Zuggeschwindigkeit", + "Contexto y velocidad de las jugadas", + "Contesto e velocità delle mosse", + "Contexto e velocidade dos lances", + "Kontekst va yurish tezligi", + "КонтекÑ�Ñ‚ және жүріÑ� жылдамдығы", + ], + [ + "Reinforce minimum correct", + "Минимум правильных длÑ� закреплениÑ�", + "Minimum de réponses correctes pour renforcer", + "Mindestzahl richtiger Antworten zur Festigung", + "Mínimo de respuestas correctas para reforzar", + "Minimo di risposte corrette per rinforzare", + "Mínimo de respostas corretas para reforçar", + "Mustahkamlash uchun minimal to‘g‘ri javoblar", + "Бекіту үшін дұрыÑ� жауаптардың ең аз Ñ�аны", + ], + [ + "Reinforce minimum days", + "Минимум дней длÑ� закреплениÑ�", + "Nombre minimal de jours pour renforcer", + "Mindesttage zur Festigung", + "Días mínimos para reforzar", + "Giorni minimi per rinforzare", + "Dias mínimos para reforçar", + "Mustahkamlash uchun minimal kunlar", + "Бекіту үшін ең аз күндер", + ], + [ + "Don't show start moves threshold", + "Порог пропуÑ�ка начальных ходов", + "Seuil pour masquer les coups initiaux", + "Schwelle zum Überspringen der Anfangszüge", + "Umbral para omitir las jugadas iniciales", + "Soglia per saltare le mosse iniziali", + "Limite para ocultar os lances iniciais", + "Boshlang‘ich yurishlarni o‘tkazib yuborish chegarasi", + "БаÑ�тапқы жүріÑ�терді өткізіп жіберу шегі", + ], + [ + "Use fixed piece movement speed", + "ФикÑ�ированнаÑ� Ñ�короÑ�ть движениÑ� фигур", + "Utiliser une vitesse de déplacement fixe des pièces", + "Feste Figurenbewegungsgeschwindigkeit verwenden", + "Usar velocidad fija de movimiento de las piezas", + "Usa velocità di movimento fissa dei pezzi", + "Usar velocidade fixa de movimento das peças", + "Figuralarning harakat tezligini belgilash", + "Фигуралардың қозғалыÑ� жылдамдығын белгілеу", + ], + [ + "Move speed adjustment", + "Ð�аÑ�тройка Ñ�короÑ�ти ходов", + "Ajustement de la vitesse des coups", + "Anpassung der Zuggeschwindigkeit", + "Ajuste de velocidad de las jugadas", + "Regolazione della velocità delle mosse", + "Ajuste da velocidade dos lances", + "Yurish tezligini sozlash", + "ЖүріÑ� жылдамдығын реттеу", + ], + [ + "Consider leadup moves when training branch", + "ПроверÑ�ть предшеÑ�твующие ходы при изучении ветки", + "Tenir compte des coups précédents lors de l’apprentissage d’une variante", + "Vorangehende Züge beim Training einer Variante berücksichtigen", + "Considerar jugadas previas al entrenar una variante", + "Considera le mosse precedenti durante l’apprendimento di una variante", + "Considerar lances anteriores ao treinar uma variante", + "Variantni o‘rganda oldingi yurishlarni hisobga olish", + "Ð�Ò±Ñ�қаны үйренгенде алдыңғы жүріÑ�терді еÑ�керу", + ], + [ + "plies", + "полуходов", + "demi-coups", + "Halbzüge", + "semimovimientos", + "semimosse", + "meios lances", + "yarim yurishlar", + "жарты жүріÑ�тер", + ], + [ + "Main answer", + "ОÑ�новной ответ", + "Réponse principale", + "Hauptzug", + "Respuesta principal", + "Risposta principale", + "Resposta principal", + "Asosiy javob", + "Ð�егізгі жауап", + ], + [ + "Make main answer", + "Сделать оÑ�новным ответом", + "Définir comme réponse principale", + "Als Hauptzug festlegen", + "Establecer como respuesta principal", + "Imposta come risposta principale", + "Definir como resposta principal", + "Asosiy javob qilib belgilash", + "Ð�егізгі жауап етіп белгілеу", + ], + [ + "Clear override", + "Убрать переопределение", + "Supprimer la surcharge", + "Überschreibung aufheben", + "Quitar anulación", + "Rimuovi sostituzione", + "Remover substituição", + "Almashtirishni bekor qilish", + "Қайта анықтауды жою", + ], + [ + "main", + "оÑ�новной", + "principal", + "Hauptzug", + "principal", + "principale", + "principal", + "asosiy", + "негізгі", + ], + [ + "Learning analytics is kept for the current main answer", + "Ð�налитика обучениÑ� ведётÑ�Ñ� длÑ� текущего оÑ�новного ответа", + "Les statistiques d’apprentissage sont conservées pour la réponse principale actuelle", + "Lernstatistik wird für den aktuellen Hauptzug geführt", + "Las estadísticas de aprendizaje se guardan para la respuesta principal actual", + "Le statistiche di apprendimento sono conservate per la risposta principale attuale", + "As estatísticas de aprendizagem são mantidas para a resposta principal atual", + "O‘rganish statistikasi joriy asosiy javob uchun saqlanadi", + "Үйрену Ñ�татиÑ�тикаÑ�Ñ‹ ағымдағы негізгі жауап үшін Ñ�ақталады", + ], + // --- learning dashboard --- + [ + "Learning dashboard", + "Панель обучениÑ�", + "Tableau d’apprentissage", + "Lernübersicht", + "Panel de aprendizaje", + "Pannello di apprendimento", + "Painel de aprendizagem", + "O‘rganish paneli", + "Үйрену панелі", + ], + [ + "All repertoires (union)", + "Ð’Ñ�е репертуары (объединение)", + "Tous les répertoires (union)", + "Alle Repertoires (Vereinigung)", + "Todos los repertorios (unión)", + "Tutti i repertori (unione)", + "Todos os repertórios (união)", + "Barcha repertuarlar (birleshma)", + "Барлық репертуар (біріктіру)", + ], + [ + "Total moves", + "Ð’Ñ�его ходов", + "Coups au total", + "Züge insgesamt", + "Jugadas totales", + "Mosse totali", + "Lances totais", + "Jami yurishlar", + "Барлық жүріÑ�тер", + ], + [ + "Save the current numbers for the selected scope and side. PGN and learning progress do not change.", + "Сохранить текущие показатели длÑ� выбранной облаÑ�ти и Ñ�тороны. PGN и прогреÑ�Ñ� обучениÑ� не изменÑ�Ñ‚Ñ�Ñ�.", + "Enregistrer les valeurs actuelles pour la portée et le camp sélectionnés. Le PGN et la progression de l’apprentissage ne changent pas.", + "Die aktuellen Werte für den ausgewählten Bereich und die ausgewählte Seite speichern. PGN und Lernfortschritt bleiben unverändert.", + "Guardar las cifras actuales para el ámbito y el lado seleccionados. El PGN y el progreso de aprendizaje no cambian.", + "Salva i valori attuali per l’ambito e il lato selezionati. PGN e progressi di apprendimento non cambiano.", + "Salvar os números atuais para o escopo e o lado selecionados. O PGN e o progresso de aprendizagem não mudam.", + "Tanlangan doira va tomon uchun joriy ko‘rsatkichlarni saqlash. PGN va o‘rganish jarayoni o‘zgarmaydi.", + "Таңдалған аумақ пен тараптың ағымдағы көрÑ�еткіштерін Ñ�ақтау. PGN және үйрену барыÑ�Ñ‹ өзгермейді.", + ], + [ + "Capture snapshot", + "Сохранить Ñ�нимок", + "Capturer un instantané", + "Snapshot aufnehmen", + "Capturar instantánea", + "Cattura istantanea", + "Capturar instantâneo", + "O‘lchovni saqlash", + "ТүÑ�ірімді Ñ�ақтау", + ], + [ + "Summary", + "Сводка", + "Résumé", + "Übersicht", + "Resumen", + "Riepilogo", + "Resumo", + "Qisqacha", + "Қорытынды", + ], + [ + "T = Unseen + Learning + Learnt. Uncertain is already included in Learnt.", + "T = новые + изучаемые + изученные. Ð�еподтверждённые уже входÑ�Ñ‚ в изученные.", + "T = nouveaux + en apprentissage + acquis. Les incertains sont déjà compris dans les acquis.", + "T = Neu + Lernen + Gelernt. Unsichere sind bereits in Gelernt enthalten.", + "T = nuevas + en aprendizaje + aprendidas. Las inciertas ya están incluidas en aprendidas.", + "T = nuove + in apprendimento + apprese. Le incerte sono già incluse nelle apprese.", + "T = novos + em aprendizagem + aprendidos. Os incertos já estão incluídos nos aprendidos.", + "T = yangi + o‘rganilayotgan + o‘rganilgan. Noaniqlar o‘rganilganga kiradi.", + "T = жаңа + үйренілуде + үйренілген. РаÑ�талмағандар үйренілгенге кіреді.", + ], + [ + "Uncertain is already included in Learnt and is never added to T.", + "Ð�еподтверждённые уже входÑ�Ñ‚ в изученные и отдельно не прибавлÑ�ÑŽÑ‚Ñ�Ñ� к T.", + "Les incertains sont déjà compris dans les acquis et ne sont jamais ajoutés à T.", + "Unsichere sind bereits in Gelernt enthalten und werden nie zu T addiert.", + "Las inciertas ya están incluidas en aprendidas y nunca se suman a T.", + "Le incerte sono già incluse nelle apprese e non vengono mai aggiunte a T.", + "Os incertos já estão incluídos nos aprendidos e nunca são somados a T.", + "Noaniqlar o‘rganilganga kiradi va T ga alohida qo‘shilmaydi.", + "РаÑ�талмағандар үйренілгенге кіреді және T Ñ�анына бөлек қоÑ�ылмайды.", + ], + [ + "Next due at", + "Следующее повторение", + "Prochaine révision", + "Nächste Wiederholung", + "Próximo repaso", + "Prossima ripetizione", + "Próxima revisão", + "Keyingi takrorlash", + "КелеÑ�Ñ– қайталау", + ], + [ + "No snapshots yet. Save statistics to History to record the current scope.", + "Снимков пока нет. Ð�ажмите «Сохранить Ñ�татиÑ�тику в иÑ�торию», чтобы запиÑ�ать текущую облаÑ�ть.", + "Aucun instantané. Utilisez « Enregistrer les statistiques dans l’historique » pour enregistrer la portée actuelle.", + "Noch keine Snapshots. Mit „Statistiken im Verlauf speichern“ den aktuellen Bereich speichern.", + "Aún no hay instantáneas. Usa «Guardar estadísticas en el historial» para registrar el ámbito actual.", + "Nessuna istantanea. Usa «Salva statistiche nella cronologia» per registrare l’ambito attuale.", + "Ainda não há instantâneos. Use «Salvar estatísticas no histórico» para registrar o escopo atual.", + "Hali o‘lchovlar yo‘q. Joriy doirani yozish uchun «Statistikani tarixga saqlash» bosing.", + "Әзірге түÑ�ірім жоқ. Ð�ғымдағы аумақты жазу үшін «СтатиÑ�тиканы тарихқа Ñ�ақтау» баÑ�ыңыз.", + ], + [ + "Today", + "СегоднÑ�", + "Aujourd’hui", + "Heute", + "Hoy", + "Oggi", + "Hoje", + "Bugun", + "Бүгін", + ], + [ + "Branches", + "Ветки", + "Branches", + "Varianten", + "Ramas", + "Rami", + "Ramos", + "Tarmoqlar", + "Тармақтар", + ], + [ + "Branch", + "Ветка", + "Branche", + "Variante", + "Rama", + "Ramo", + "Ramo", + "Tarmoq", + "Тармақ", + ], + [ + "Total = Unseen + Learning + Learnt.", + "Ð’Ñ�его = не начато + изучаетÑ�Ñ� + изучено.", + "Total = non vus + en cours + acquis.", + "Gesamt = ungesehen + laufend + gelernt.", + "Total = sin ver + aprendiendo + aprendidas.", + "Totale = non viste + in apprendimento + apprese.", + "Total = não vistos + em aprendizado + aprendidos.", + "Jami = ko‘rilmagan + o‘rganilmoqda + o‘rganilgan.", + "Барлығы = баÑ�талмаған + үйренілуде + үйренілген.", + ], + [ + "Last trained", + "ПоÑ�леднÑ�Ñ� тренировка", + "Dernier entraînement", + "Letztes Training", + "Último entrenamiento", + "Ultimo allenamento", + "Último treino", + "Oxirgi mashg‘ulot", + "Соңғы жаттығу", + ], + [ + "Selected: {n}", + "Выбрано: {n}", + "Sélection : {n}", + "Ausgewählt: {n}", + "Seleccionadas: {n}", + "Selezionate: {n}", + "Selecionadas: {n}", + "Tanlangan: {n}", + "Таңдалды: {n}", + ], + [ + "Selected: {n} ({k} hidden by the filter)", + "Выбрано: {n} ({k} Ñ�крыто фильтром)", + "Sélection : {n} ({k} masquées par le filtre)", + "Ausgewählt: {n} ({k} vom Filter verborgen)", + "Seleccionadas: {n} ({k} ocultas por el filtro)", + "Selezionate: {n} ({k} nascoste dal filtro)", + "Selecionadas: {n} ({k} ocultas pelo filtro)", + "Tanlangan: {n} ({k} tasi filtr bilan yashirilgan)", + "Таңдалды: {n} ({k} Ñ�үзгімен жаÑ�ырылған)", + ], + [ + "Deselect", + "СнÑ�ть", + "Désélectionner", + "Abwählen", + "Deseleccionar", + "Deseleziona", + "Desmarcar", + "Bekor qilish", + "Ð�лып таÑ�тау", + ], + [ + "Clear the selection (Esc)", + "СнÑ�ть выделение (Esc)", + "Annuler la sélection (Échap)", + "Auswahl aufheben (Esc)", + "Quitar la selección (Esc)", + "Annulla la selezione (Esc)", + "Limpar a seleção (Esc)", + "Tanlovni bekor qilish (Esc)", + "Таңдауды алып таÑ�тау (Esc)", + ], + [ + "Games hidden by the filter will be copied too. Esc clears the selection", + "Скрытые фильтром партии тоже будут Ñ�копированы. СнÑ�ть выделение — Esc", + "Les parties masquées par le filtre seront aussi copiées. Échap annule la sélection", + "Vom Filter verborgene Partien werden mitkopiert. Esc hebt die Auswahl auf", + "Las partidas ocultas por el filtro también se copiarán. Esc quita la selección", + "Anche le partite nascoste dal filtro saranno copiate. Esc annulla la selezione", + "As partidas ocultas pelo filtro também serão copiadas. Esc limpa a seleção", + "Filtr yashirgan partiyalar ham nusxalanadi. Esc — tanlovni bekor qilish", + "Сүзгі жаÑ�ырған партиÑ�лар да көшіріледі. Esc — таңдауды алып таÑ�тау", + ], + [ + "Games selected: {n}", + "Выбрано партий: {n}", + "Parties sélectionnées : {n}", + "Ausgewählte Partien: {n}", + "Partidas seleccionadas: {n}", + "Partite selezionate: {n}", + "Partidas selecionadas: {n}", + "Tanlangan partiyalar: {n}", + "Таңдалған партиÑ�лар: {n}", + ], + [ + "New database from selected…", + "Ð�оваÑ� база из выбранных…", + "Nouvelle base à partir de la sélection…", + "Neue Datenbank aus Auswahl…", + "Nueva base con las seleccionadas…", + "Nuovo database dalle selezionate…", + "Nova base a partir das selecionadas…", + "Tanlanganlardan yangi baza…", + "Таңдалғандардан жаңа база…", + ], + [ + "Select all (Ctrl+A)", + "Выделить вÑ�е (Ctrl+A)", + "Tout sélectionner (Ctrl+A)", + "Alle auswählen (Strg+A)", + "Seleccionar todo (Ctrl+A)", + "Seleziona tutto (Ctrl+A)", + "Selecionar tudo (Ctrl+A)", + "Hammasini tanlash (Ctrl+A)", + "Барлығын таңдау (Ctrl+A)", + ], + [ + "Clear selection (Esc)", + "СнÑ�ть выделение (Esc)", + "Annuler la sélection (Échap)", + "Auswahl aufheben (Esc)", + "Quitar selección (Esc)", + "Annulla selezione (Esc)", + "Limpar seleção (Esc)", + "Tanlovni bekor qilish (Esc)", + "Таңдауды алып таÑ�тау (Esc)", + ], + [ + "Writing to «{name}» — wait until it finishes", + "Идёт запиÑ�ÑŒ в «{name}» — дождитеÑ�ÑŒ окончаниÑ�", + "Écriture dans « {name} » — attendez la fin", + "Schreibe in «{name}» — warten Sie, bis es fertig ist", + "Escribiendo en «{name}»: espere a que termine", + "Scrittura in «{name}» — attendi la fine", + "Gravando em «{name}» — aguarde o fim", + "«{name}» ga yozilmoqda — tugashini kuting", + "«{name}» ішіне жазылуда — аÑ�қталуын күтіңіз", + ], + [ + "From the selection: {games} from «{src}»", + "Из выбранных: {games} из «{src}»", + "De la sélection : {games} de « {src} »", + "Aus der Auswahl: {games} aus «{src}»", + "De la selección: {games} de «{src}»", + "Dalla selezione: {games} da «{src}»", + "Da seleção: {games} de «{src}»", + "Tanlovdan: «{src}» dan {games}", + "Таңдаудан: «{src}» ішінен {games}", + ], + [ + "{k} of them are hidden by the filter now", + "из них {k} Ñ�ейчаÑ� Ñ�крыты фильтром", + "dont {k} masquées par le filtre", + "davon {k} gerade vom Filter verborgen", + "{k} de ellas ocultas ahora por el filtro", + "di cui {k} ora nascoste dal filtro", + "{k} delas ocultas agora pelo filtro", + "ulardan {k} tasi hozir filtr bilan yashirilgan", + "олардың {k} қазір Ñ�үзгімен жаÑ�ырылған", + ], + [ + "Many games: writing may take a few minutes; you can cancel it", + "Много партий: запиÑ�ÑŒ может занÑ�ть неÑ�колько минут, её можно отменить", + "Beaucoup de parties : l’écriture peut prendre quelques minutes ; vous pouvez l’annuler", + "Viele Partien: das Schreiben kann einige Minuten dauern; Sie können es abbrechen", + "Muchas partidas: la escritura puede tardar unos minutos; se puede cancelar", + "Molte partite: la scrittura può richiedere alcuni minuti; puoi annullarla", + "Muitas partidas: a gravação pode levar alguns minutos; pode cancelá-la", + "Partiyalar ko‘p: yozish bir necha daqiqa olishi mumkin, uni bekor qilish mumkin", + "ПартиÑ�лар көп: жазу бірнеше минутқа Ñ�озылуы мүмкін, оны тоқтатуға болады", + ], + [ + "Create and copy", + "Создать и Ñ�копировать", + "Créer et copier", + "Erstellen und kopieren", + "Crear y copiar", + "Crea e copia", + "Criar e copiar", + "Yaratish va nusxalash", + "ЖаÑ�ау және көшіру", + ], + [ + "Writing to «{name}»: {i} of {n}", + "ЗапиÑ�ÑŒ в «{name}»: {i} из {n}", + "Écriture dans « {name} » : {i} sur {n}", + "Schreibe in «{name}»: {i} von {n}", + "Escribiendo en «{name}»: {i} de {n}", + "Scrittura in «{name}»: {i} di {n}", + "Gravando em «{name}»: {i} de {n}", + "«{name}» ga yozilmoqda: {n} dan {i}", + "«{name}» ішіне жазу: {n} ішінен {i}", + ], + [ + "Cancelling…", + "Отмена…", + "Annulation…", + "Wird abgebrochen…", + "Cancelando…", + "Annullamento…", + "Cancelando…", + "Bekor qilinmoqda…", + "Тоқтатылуда…", + ], + [ + "{name}: copied {n}, skipped {m}", + "{name}: Ñ�копировано {n}, пропущено {m}", + "{name} : {n} copiées, {m} ignorées", + "{name}: {n} kopiert, {m} übersprungen", + "{name}: copiadas {n}, omitidas {m}", + "{name}: copiate {n}, saltate {m}", + "{name}: copiadas {n}, ignoradas {m}", + "{name}: {n} ta nusxalandi, {m} ta o‘tkazildi", + "{name}: {n} көшірілді, {m} өткізілді", + ], + [ + "{name}: copied {n}, skipped {m} — duplicates {d}{dl}, unreadable {u}{ul}", + "{name}: Ñ�копировано {n}, пропущено {m} — дубли {d}{dl}, не прочитано {u}{ul}", + "{name} : {n} copiées, {m} ignorées — doublons {d}{dl}, illisibles {u}{ul}", + "{name}: {n} kopiert, {m} übersprungen — Duplikate {d}{dl}, unlesbar {u}{ul}", + "{name}: copiadas {n}, omitidas {m} — duplicadas {d}{dl}, ilegibles {u}{ul}", + "{name}: copiate {n}, saltate {m} — duplicati {d}{dl}, illeggibili {u}{ul}", + "{name}: copiadas {n}, ignoradas {m} — duplicadas {d}{dl}, ilegíveis {u}{ul}", + "{name}: {n} ta nusxalandi, {m} ta o‘tkazildi — takrorlar {d}{dl}, o‘qilmadi {u}{ul}", + "{name}: {n} көшірілді, {m} өткізілді — қайталанған {d}{dl}, оқылмады {u}{ul}", + ], + [ + "No. {list}", + "â„– {list}", + "n° {list}", + "Nr. {list}", + "n.º {list}", + "n. {list}", + "n.º {list}", + "â„– {list}", + "â„– {list}", + ], + [ + "and {n} more", + "и ещё {n}", + "et {n} de plus", + "und {n} weitere", + "y {n} más", + "e altre {n}", + "e mais {n}", + "va yana {n} ta", + "және тағы {n}", + ], + [ + "Copying cancelled: «{name}» was not created", + "Копирование отменено: база «{name}» не Ñ�оздана", + "Copie annulée : « {name} » n’a pas été créée", + "Kopieren abgebrochen: «{name}» wurde nicht erstellt", + "Copia cancelada: «{name}» no se ha creado", + "Copia annullata: «{name}» non è stato creato", + "Cópia cancelada: «{name}» não foi criada", + "Nusxalash bekor qilindi: «{name}» yaratilmadi", + "Көшіру тоқтатылды: «{name}» жаÑ�алмады", + ], + [ + "Could not write «{name}»: {reason}. Nothing was written", + "Ð�е удалоÑ�ÑŒ запиÑ�ать «{name}»: {reason}. Ð�ичего не запиÑ�ано", + "Impossible d’écrire « {name} » : {reason}. Rien n’a été écrit", + "«{name}» konnte nicht geschrieben werden: {reason}. Nichts wurde geschrieben", + "No se pudo escribir «{name}»: {reason}. No se escribió nada", + "Impossibile scrivere «{name}»: {reason}. Non è stato scritto nulla", + "Não foi possível gravar «{name}»: {reason}. Nada foi gravado", + "«{name}» ni yozib bo‘lmadi: {reason}. Hech narsa yozilmadi", + "«{name}» жазылмады: {reason}. Ештеңе жазылған жоқ", + ], + [ + "«{src}» changed while copying. Nothing was written", + "База «{src}» изменилаÑ�ÑŒ во времÑ� копированиÑ�. Ð�ичего не запиÑ�ано", + "« {src} » a changé pendant la copie. Rien n’a été écrit", + "«{src}» hat sich beim Kopieren geändert. Nichts wurde geschrieben", + "«{src}» cambió durante la copia. No se escribió nada", + "«{src}» è cambiato durante la copia. Non è stato scritto nulla", + "«{src}» mudou durante a cópia. Nada foi gravado", + "«{src}» nusxalash paytida o‘zgardi. Hech narsa yozilmadi", + "«{src}» көшіру кезінде өзгерді. Ештеңе жазылған жоқ", + ], + [ + "Games are deleted one at a time: clear the selection (Esc)", + "УдалÑ�ть можно по одной партии: Ñ�нимите выделение (Esc)", + "Les parties se suppriment une par une : annulez la sélection (Échap)", + "Partien werden einzeln gelöscht: heben Sie die Auswahl auf (Esc)", + "Las partidas se borran de una en una: quite la selección (Esc)", + "Le partite si eliminano una alla volta: annulla la selezione (Esc)", + "As partidas são apagadas uma de cada vez: limpe a seleção (Esc)", + "Partiyalar bittadan o‘chiriladi: tanlovni bekor qiling (Esc)", + "ПартиÑ�лар бір-бірден жойылады: таңдауды алып таÑ�таңыз (Esc)", + ], + [ + "a file with this name is already there", + "файл Ñ� таким именем уже еÑ�ть", + "un fichier de ce nom existe déjà", + "eine Datei mit diesem Namen gibt es schon", + "ya existe un archivo con ese nombre", + "esiste già un file con questo nome", + "já existe um ficheiro com este nome", + "bu nomli fayl allaqachon bor", + "мұндай атаулы файл бар", + ], + [ + "the source changed", + "иÑ�точник изменилÑ�Ñ�", + "la source a changé", + "die Quelle hat sich geändert", + "el origen cambió", + "la sorgente è cambiata", + "a origem mudou", + "manba o‘zgardi", + "көз өзгерді", + ], + [ + "no space left on the disk", + "на диÑ�ке нет меÑ�та", + "plus d’espace sur le disque", + "kein Platz mehr auf dem Datenträger", + "no queda espacio en el disco", + "spazio su disco esaurito", + "sem espaço no disco", + "diskda joy qolmadi", + "диÑ�кіде орын жоқ", + ], + [ + "no permission to write", + "нет прав на запиÑ�ÑŒ", + "pas de droit d’écriture", + "keine Schreibrechte", + "sin permiso de escritura", + "nessun permesso di scrittura", + "sem permissão de escrita", + "yozishga ruxsat yo‘q", + "жазуға Ñ€Ò±Ò›Ñ�ат жоқ", + ], + [ + "Another copy is being written: wait until it finishes", + "Идёт другаÑ� запиÑ�ÑŒ: дождитеÑ�ÑŒ окончаниÑ�", + "Une autre copie est en cours d’écriture : attendez la fin", + "Eine andere Kopie wird geschrieben: warten Sie, bis sie fertig ist", + "Se está escribiendo otra copia: espere a que termine", + "È in corso un’altra copia: attendi la fine", + "Outra cópia está a ser gravada: aguarde o fim", + "Boshqa nusxa yozilmoqda: tugashini kuting", + "БаÑ�қа көшірме жазылуда: аÑ�қталуын күтіңіз", + ], + [ + "Selection cleared: the database changed", + "Выделение Ñ�нÑ�то: база изменилаÑ�ÑŒ", + "Sélection annulée : la base a changé", + "Auswahl aufgehoben: die Datenbank hat sich geändert", + "Selección quitada: la base cambió", + "Selezione annullata: il database è cambiato", + "Seleção limpa: a base mudou", + "Tanlov bekor qilindi: baza o‘zgardi", + "Таңдау алынды: база өзгерді", + ], + [ + "The engine is busy searching opening errors in a preparation: wait or stop it", + "Движок занÑ�Ñ‚: идёт поиÑ�к ошибок дебюта в подготовке — дождитеÑ�ÑŒ или оÑ�тановите его", + "Le moteur est occupé à chercher les erreurs d’ouverture d’une préparation : attendez ou arrêtez-le", + "Die Engine sucht gerade Eröffnungsfehler in einer Vorbereitung: warten oder anhalten", + "El motor está buscando errores de apertura en una preparación: espere o deténgalo", + "Il motore sta cercando errori d’apertura in una preparazione: attendi o fermalo", + "O motor está a procurar erros de abertura numa preparação: aguarde ou pare-o", + "Dvigatel tayyorgarlikda debyut xatolarini qidirmoqda — kuting yoki to‘xtating", + "Қозғалтқыш дайындықта дебют қателерін іздеуде — күтіңіз не тоқтатыңыз", + ], + [ + "all games", + "вÑ�е партии базы", + "toutes les parties", + "alle Partien", + "todas las partidas", + "tutte le partite", + "todas as partidas", + "bazadagi barcha partiyalar", + "базаның барлық партиÑ�лары", + ], + [ + "matching the conditions", + "по уÑ�ловиÑ�м", + "selon les conditions", + "nach den Bedingungen", + "según las condiciones", + "secondo le condizioni", + "segundo as condições", + "shartlar bo‘yicha", + "шарттар бойынша", + ], + [ + "The search needs Stockfish 19: start «Analyse game» once to get it", + "ДлÑ� поиÑ�ка нужен Stockfish 19: один раз запуÑ�тите «Ð�нализ партии», чтобы его получить", + "La recherche a besoin de Stockfish 19 : lancez une fois « Analyser la partie » pour l’obtenir", + "Die Suche braucht Stockfish 19: einmal «Partie analysieren» starten, um ihn zu bekommen", + "La búsqueda necesita Stockfish 19: inicie una vez «Analizar partida» para obtenerlo", + "La ricerca richiede Stockfish 19: avvia una volta «Analizza partita» per ottenerlo", + "A pesquisa precisa do Stockfish 19: inicie uma vez «Analisar partida» para o obter", + "Qidiruv uchun Stockfish 19 kerak: uni olish uchun bir marta «Partiya tahlili»ni ishga tushiring", + "Іздеуге Stockfish 19 керек: оны алу үшін бір рет «ПартиÑ� талдауын» Ñ–Ñ�ке қоÑ�ыңыз", + ], + [ + "Search stopped: no game was reviewed", + "ПоиÑ�к оÑ�тановлен: ни одна партиÑ� не разобрана", + "Recherche arrêtée : aucune partie n’a été analysée", + "Suche angehalten: keine Partie wurde analysiert", + "Búsqueda detenida: no se analizó ninguna partida", + "Ricerca fermata: nessuna partita analizzata", + "Pesquisa parada: nenhuma partida foi analisada", + "Qidiruv to‘xtatildi: birorta ham partiya tahlil qilinmadi", + "Іздеу тоқтатылды: бірде-бір партиÑ� талданбады", + ], + [ + "The engine is busy reviewing {game}", + "Движок занÑ�Ñ‚: идёт разбор партии {game}", + "Le moteur est occupé à analyser {game}", + "Die Engine analysiert gerade {game}", + "El motor está analizando {game}", + "Il motore sta analizzando {game}", + "O motor está a analisar {game}", + "Dvigatel {game} partiyasini tahlil qilmoqda", + "Қозғалтқыш {game} партиÑ�Ñ�ын талдауда", + ], + [ + "Searching for great moves in «{db}»: {i} of {n}. Stop it in the library", + "Идёт поиÑ�к замечательных ходов в «{db}»: {i} из {n}. ОÑ�тановить — в библиотеке", + "Recherche de très bons coups dans « {db} » : {i} sur {n}. Arrêtez-la dans la bibliothèque", + "Suche nach starken Zügen in «{db}»: {i} von {n}. Anhalten in der Bibliothek", + "Buscando jugadas notables en «{db}»: {i} de {n}. Deténgala en la biblioteca", + "Ricerca di mosse notevoli in «{db}»: {i} di {n}. Fermala nella libreria", + "A procurar lances notáveis em «{db}»: {i} de {n}. Pare-a na biblioteca", + "«{db}» da ajoyib yurishlar qidirilmoqda: {n} dan {i}. To‘xtatish — kutubxonada", + "«{db}» ішінде тамаша жүріÑ�тер ізделуде: {n} ішінен {i}. Тоқтату — кітапханада", + ], + [ + "The engine failed: {reason}. {i} of {n} reviewed", + "Движок оÑ�тановилÑ�Ñ� Ñ� ошибкой: {reason}. Разобрано {i} из {n}", + "Le moteur a échoué : {reason}. {i} sur {n} analysées", + "Die Engine ist ausgefallen: {reason}. {i} von {n} analysiert", + "El motor falló: {reason}. Analizadas {i} de {n}", + "Il motore si è fermato con un errore: {reason}. Analizzate {i} di {n}", + "O motor falhou: {reason}. Analisadas {i} de {n}", + "Dvigatel xato bilan to‘xtadi: {reason}. {n} dan {i} tasi tahlil qilindi", + "Қозғалтқыш қатемен тоқтады: {reason}. {n} ішінен {i} талданды", + ], + [ + "«{db}» changed; the search stopped. {i} of {n} reviewed", + "База «{db}» изменилаÑ�ÑŒ — поиÑ�к оÑ�тановлен. Разобрано {i} из {n}", + "« {db} » a changé ; la recherche s’est arrêtée. {i} sur {n} analysées", + "«{db}» hat sich geändert; die Suche wurde angehalten. {i} von {n} analysiert", + "«{db}» cambió; la búsqueda se detuvo. Analizadas {i} de {n}", + "«{db}» è cambiato; la ricerca si è fermata. Analizzate {i} di {n}", + "«{db}» mudou; a pesquisa parou. Analisadas {i} de {n}", + "«{db}» bazasi o‘zgardi — qidiruv to‘xtatildi. {n} dan {i} tasi tahlil qilindi", + "«{db}» базаÑ�Ñ‹ өзгерді — іздеу тоқтатылды. {n} ішінен {i} талданды", + ], + [ + "Wait: the games are still being filtered", + "Подождите — партии ещё отбираютÑ�Ñ�", + "Patientez : les parties sont encore en cours de filtrage", + "Bitte warten: die Partien werden noch gefiltert", + "Espere: las partidas todavía se están filtrando", + "Attendi: le partite sono ancora in fase di filtro", + "Aguarde: as partidas ainda estão a ser filtradas", + "Kuting — partiyalar hali tanlanmoqda", + "Күтіңіз — партиÑ�лар әлі іріктелуде", + ], + [ + "No games match these conditions", + "Ð�ет партий по Ñ�тим уÑ�ловиÑ�м", + "Aucune partie ne correspond à ces conditions", + "Keine Partien passen zu diesen Bedingungen", + "Ninguna partida cumple estas condiciones", + "Nessuna partita corrisponde a queste condizioni", + "Nenhuma partida corresponde a estas condições", + "Bu shartlar bo‘yicha partiya yo‘q", + "Бұл шарттар бойынша партиÑ� жоқ", + ], + [ + "Filter the games down to 100 or fewer", + "Отфильтруйте партии, чтобы их было не больше 100", + "Filtrez les parties pour en avoir 100 au plus", + "Filtern Sie auf höchstens 100 Partien", + "Filtre las partidas hasta 100 como máximo", + "Filtra le partite fino a non più di 100", + "Filtre as partidas até no máximo 100", + "Partiyalar 100 tadan ko‘p bo‘lmasin — filtrlang", + "ПартиÑ�лар 100-ден аÑ�пайтындай Ñ�үзіңіз", + ], + [ + "!! Find moves", + "!! Ð�айти ходы", + "!! Trouver des coups", + "!! Züge finden", + "!! Buscar jugadas", + "!! Trova mosse", + "!! Procurar lances", + "!! Yurishlarni topish", + "!! ЖүріÑ�терді табу", + ], + [ + "!! Find great moves", + "!! Ð�айти замечательные ходы", + "!! Trouver de très bons coups", + "!! Starke Züge finden", + "!! Buscar jugadas notables", + "!! Trova mosse notevoli", + "!! Procurar lances notáveis", + "!! Ajoyib yurishlarni topish", + "!! Тамаша жүріÑ�терді табу", + ], + [ + "Stopping…", + "ОÑ�танавливаю…", + "Arrêt…", + "Wird angehalten…", + "Deteniendo…", + "Arresto…", + "A parar…", + "To‘xtatilmoqda…", + "Тоқтатылуда…", + ], + [ + "Stop the search; the reviewed games are kept", + "ОÑ�тановить поиÑ�к; разобранные партии Ñ�охранÑ�Ñ‚Ñ�Ñ�", + "Arrêter la recherche ; les parties analysées sont conservées", + "Suche anhalten; analysierte Partien bleiben erhalten", + "Detener la búsqueda; las partidas analizadas se conservan", + "Ferma la ricerca; le partite analizzate restano", + "Parar a pesquisa; as partidas analisadas são guardadas", + "Qidiruvni to‘xtatish; tahlil qilingan partiyalar saqlanadi", + "Іздеуді тоқтату; талданған партиÑ�лар Ñ�ақталады", + ], + [ + "Brilliant and great moves found by the engine: sort by them", + "БлеÑ�Ñ‚Ñ�щие и замечательные ходы, найденные движком: Ñ�ортировать по ним", + "Coups brillants et très bons trouvés par le moteur : trier par eux", + "Von der Engine gefundene brillante und starke Züge: danach sortieren", + "Jugadas brillantes y notables halladas por el motor: ordenar por ellas", + "Mosse brillanti e notevoli trovate dal motore: ordina per esse", + "Lances brilhantes e notáveis encontrados pelo motor: ordenar por eles", + "Dvigatel topgan ajoyib va zo‘r yurishlar: ular bo‘yicha saralash", + "Қозғалтқыш тапқан керемет және тамаша жүріÑ�тер: Ñ�олар бойынша Ñ�ұрыптау", + ], + [ + "Being reviewed…", + "РазбираетÑ�Ñ�…", + "En cours d’analyse…", + "Wird analysiert…", + "Analizándose…", + "In analisi…", + "A ser analisada…", + "Tahlil qilinmoqda…", + "Талдануда…", + ], + [ + "Reviewed: no brilliant or great moves", + "Разобрана: блеÑ�Ñ‚Ñ�щих и замечательных ходов нет", + "Analysée : aucun coup brillant ou très bon", + "Analysiert: keine brillanten oder starken Züge", + "Analizada: sin jugadas brillantes ni notables", + "Analizzata: nessuna mossa brillante o notevole", + "Analisada: sem lances brilhantes ou notáveis", + "Tahlil qilingan: ajoyib va zo‘r yurishlar yo‘q", + "Талданды: керемет және тамаша жүріÑ�тер жоқ", + ], + [ + "Reviewed with the previous engine settings", + "Разбор прежними наÑ�тройками движка", + "Analysée avec les anciens réglages du moteur", + "Mit den früheren Engine-Einstellungen analysiert", + "Analizada con los ajustes anteriores del motor", + "Analizzata con le impostazioni precedenti del motore", + "Analisada com as definições anteriores do motor", + "Dvigatelning avvalgi sozlamalari bilan tahlil", + "Қозғалтқыштың бұрынғы баптауларымен талданған", + ], + [ + "Searching in «{db}»: {i} of {n}; stop it there", + "Идёт поиÑ�к в «{db}»: {i} из {n} — оÑ�тановите его там", + "Recherche dans « {db} » : {i} sur {n} ; arrêtez-la là-bas", + "Suche in «{db}»: {i} von {n}; dort anhalten", + "Buscando en «{db}»: {i} de {n}; deténgala allí", + "Ricerca in «{db}»: {i} di {n}; fermala lì", + "A pesquisar em «{db}»: {i} de {n}; pare-a lá", + "«{db}» da qidiruv: {n} dan {i} — uni o‘sha yerda to‘xtating", + "«{db}» ішінде іздеу: {n} ішінен {i} — оны Ñ�онда тоқтатыңыз", + ], + [ + "Now: {n}", + "СейчаÑ�: {n}", + "Actuellement : {n}", + "Jetzt: {n}", + "Ahora: {n}", + "Ora: {n}", + "Agora: {n}", + "Hozir: {n}", + "Қазір: {n}", + ], + [ + "Analysed {i} of {n} · ≈ {time} left", + "Проанализировано {i} из {n} · оÑ�талоÑ�ÑŒ ≈ {time}", + "Analysées {i} sur {n} · encore ≈ {time}", + "Analysiert {i} von {n} · noch ≈ {time}", + "Analizadas {i} de {n} · quedan ≈ {time}", + "Analizzate {i} di {n} · restano ≈ {time}", + "Analisadas {i} de {n} · faltam ≈ {time}", + "{n} dan {i} tasi tahlil qilindi · qoldi ≈ {time}", + "{n} ішінен {i} талданды · қалды ≈ {time}", + ], + [ + "{i} of {n}", + "{i} из {n}", + "{i} sur {n}", + "{i} von {n}", + "{i} de {n}", + "{i} di {n}", + "{i} de {n}", + "{n} dan {i}", + "{n} ішінен {i}", + ], + [ + "In «{db}»: {i} of {n}", + "Ð’ «{db}»: {i} из {n}", + "Dans « {db} » : {i} sur {n}", + "In «{db}»: {i} von {n}", + "En «{db}»: {i} de {n}", + "In «{db}»: {i} di {n}", + "Em «{db}»: {i} de {n}", + "«{db}» da: {n} dan {i}", + "«{db}» ішінде: {n} ішінен {i}", + ], + [ + "Review {games} with the engine and mark the !! and ! moves found (Shift+A)", + "Разобрать движком {games} и отметить найденные !! и ! (Shift+A)", + "Analyser {games} avec le moteur et marquer les !! et ! trouvés (Maj+A)", + "{games} mit der Engine analysieren und gefundene !! und ! markieren (Umschalt+A)", + "Analizar {games} con el motor y marcar los !! y ! hallados (Mayús+A)", + "Analizza {games} con il motore e segna i !! e ! trovati (Maiusc+A)", + "Analisar {games} com o motor e marcar os !! e ! encontrados (Shift+A)", + "{games}ni dvigatel bilan tahlil qilib, topilgan !! va ! ni belgilash (Shift+A)", + "{games} қозғалтқышпен талдап, табылған !! және ! белгілеу (Shift+A)", + ], + [ + "Open at {move}", + "Открыть на ходе {move}", + "Ouvrir au coup {move}", + "Bei {move} öffnen", + "Abrir en {move}", + "Apri alla mossa {move}", + "Abrir no lance {move}", + "{move} yurishida ochish", + "{move} жүріÑ�інде ашу", + ], + [ + "Cannot be reviewed: {reason}", + "Ð�е разбираетÑ�Ñ�: {reason}", + "Analyse impossible : {reason}", + "Kann nicht analysiert werden: {reason}", + "No se puede analizar: {reason}", + "Non analizzabile: {reason}", + "Não pode ser analisada: {reason}", + "Tahlil qilinmaydi: {reason}", + "Талданбайды: {reason}", + ], + [ + "Brilliant moves: {n}: {moves}", + "БлеÑ�Ñ‚Ñ�щих ходов: {n} — {moves}", + "Coups brillants : {n} — {moves}", + "Brillante Züge: {n} — {moves}", + "Jugadas brillantes: {n} — {moves}", + "Mosse brillanti: {n} — {moves}", + "Lances brilhantes: {n} — {moves}", + "Ajoyib yurishlar: {n} — {moves}", + "Керемет жүріÑ�тер: {n} — {moves}", + ], + [ + "Great moves: {n}: {moves}", + "Замечательных: {n} — {moves}", + "Très bons coups : {n} — {moves}", + "Starke Züge: {n} — {moves}", + "Jugadas notables: {n} — {moves}", + "Mosse notevoli: {n} — {moves}", + "Lances notáveis: {n} — {moves}", + "Zo‘r yurishlar: {n} — {moves}", + "Тамаша жүріÑ�тер: {n} — {moves}", + ], + [ + "the engine is no longer the Stockfish 19 that was checked", + "движок уже не тот Stockfish 19, что был проверен", + "le moteur n’est plus le Stockfish 19 vérifié", + "die Engine ist nicht mehr der geprüfte Stockfish 19", + "el motor ya no es el Stockfish 19 comprobado", + "il motore non è più lo Stockfish 19 verificato", + "o motor já não é o Stockfish 19 verificado", + "dvigatel endi tekshirilgan Stockfish 19 emas", + "қозғалтқыш енді текÑ�ерілген Stockfish 19 емеÑ�", + ], + [ + "Chess960", "Chess960", "Chess960", "Chess960", "Chess960", "Chess960", "Chess960", + "Chess960", "Chess960", + ], + [ + "a null move in the main line", + "пуÑ�той ход в оÑ�новной линии", + "un coup nul dans la ligne principale", + "ein Nullzug in der Hauptvariante", + "una jugada nula en la línea principal", + "una mossa nulla nella linea principale", + "um lance nulo na linha principal", + "asosiy liniyada bo‘sh yurish", + "негізгі линиÑ�да боÑ� жүріÑ�", + ], + [ + "the game cannot be read", + "партию не удалоÑ�ÑŒ прочитать", + "la partie est illisible", + "die Partie ist nicht lesbar", + "la partida no se puede leer", + "la partita non è leggibile", + "a partida não pode ser lida", + "partiyani o‘qib bo‘lmadi", + "партиÑ� оқылмады", + ], + [ + "Find great moves", + "Ð�айти замечательные ходы", + "Trouver de très bons coups", + "Starke Züge finden", + "Buscar jugadas notables", + "Trova mosse notevoli", + "Procurar lances notáveis", + "Ajoyib yurishlarni topish", + "Тамаша жүріÑ�терді табу", + ], + [ + "Counting the games already reviewed…", + "Считаю, Ñ�колько партий уже разобрано…", + "Décompte des parties déjà analysées…", + "Zähle bereits analysierte Partien…", + "Contando las partidas ya analizadas…", + "Conto le partite già analizzate…", + "A contar as partidas já analisadas…", + "Allaqachon tahlil qilingan partiyalar sanalmoqda…", + "Талданып қойған партиÑ�лар Ñ�аналуда…", + ], + [ + "The engine will review {games}: about {time}.", + "Движок разберёт {games} — примерно {time}.", + "Le moteur analysera {games} : environ {time}.", + "Die Engine analysiert {games}: etwa {time}.", + "El motor analizará {games}: unos {time}.", + "Il motore analizzerà {games}: circa {time}.", + "O motor vai analisar {games}: cerca de {time}.", + "Dvigatel {games}ni tahlil qiladi — taxminan {time}.", + "Қозғалтқыш {games} талдайды — шамамен {time}.", + ], + [ + "{k} are already reviewed: their marks come from the saved review.", + "{k} уже разобраны: их отметки возьмутÑ�Ñ� из Ñ�охранённого разбора.", + "{k} sont déjà analysées : leurs marques viennent de l’analyse enregistrée.", + "{k} sind bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", + "{k} ya están analizadas: sus marcas salen del análisis guardado.", + "{k} sono già analizzate: i loro segni vengono dall’analisi salvata.", + "{k} já estão analisadas: as suas marcas vêm da análise guardada.", + "{k} tasi allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", + "{k} талданып қойған: белгілері Ñ�ақталған талдаудан алынады.", + ], + [ + "The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept.", + "Компьютер будет загружен (до {p} процеÑ�Ñ�ов Stockfish 19). Работать Ñ� программой можно; оÑ�тановить — в любой момент, разобранные партии Ñ�охранÑ�Ñ‚Ñ�Ñ�.", + "L’ordinateur sera occupé (jusqu’à {p} processus Stockfish 19). Vous pouvez continuer à travailler et arrêter à tout moment ; les parties analysées sont conservées.", + "Der Computer wird ausgelastet (bis zu {p} Stockfish-19-Prozesse). Sie können weiterarbeiten und jederzeit anhalten; analysierte Partien bleiben erhalten.", + "El ordenador estará ocupado (hasta {p} procesos de Stockfish 19). Puede seguir trabajando y detenerlo en cualquier momento; las partidas analizadas se conservan.", + "Il computer sarà occupato (fino a {p} processi Stockfish 19). Puoi continuare a lavorare e fermare in qualsiasi momento; le partite analizzate restano.", + "O computador ficará ocupado (até {p} processos Stockfish 19). Pode continuar a trabalhar e parar a qualquer momento; as partidas analisadas são guardadas.", + "Kompyuter band bo‘ladi ({p} tagacha Stockfish 19 jarayoni). Dastur bilan ishlash mumkin; istalgan payt to‘xtatish mumkin, tahlil qilinganlar saqlanadi.", + "Компьютер жүктеледі ({p} дейін Stockfish 19 процеÑ�Ñ–). Бағдарламамен жұмыÑ� Ñ–Ñ�теуге болады; кез келген уақытта тоқтатуға болады, талданғандар Ñ�ақталады.", + ], + [ + "Start", + "Ð�ачать", + "Commencer", + "Starten", + "Empezar", + "Avvia", + "Começar", + "Boshlash", + "БаÑ�тау", + ], + [ + "Summary of the reviewed ({k})", + "Итог по разобранным ({k})", + "Bilan des analysées ({k})", + "Übersicht der analysierten ({k})", + "Resumen de las analizadas ({k})", + "Riepilogo delle analizzate ({k})", + "Resumo das analisadas ({k})", + "Tahlil qilinganlar yakuni ({k})", + "Талданғандар қорытындыÑ�Ñ‹ ({k})", + ], + [ + "Search stopped · reviewed: {i} of {n}", + "ПоиÑ�к оÑ�тановлен · разобрано: {i} из {n}", + "Recherche arrêtée · analysées : {i} sur {n}", + "Suche angehalten · analysiert: {i} von {n}", + "Búsqueda detenida · analizadas: {i} de {n}", + "Ricerca fermata · analizzate: {i} di {n}", + "Pesquisa parada · analisadas: {i} de {n}", + "Qidiruv to‘xtatildi · tahlil qilindi: {n} dan {i}", + "Іздеу тоқтатылды · талданды: {n} ішінен {i}", + ], + [ + "Summary · reviewed: {games}", + "Итог · разобрано: {games}", + "Bilan · analysées : {games}", + "Übersicht · analysiert: {games}", + "Resumen · analizadas: {games}", + "Riepilogo · analizzate: {games}", + "Resumo · analisadas: {games}", + "Yakun · tahlil qilindi: {games}", + "Қорытынды · талданды: {games}", + ], + [ + "Only the moves of «{name}» count: as White {w}, as Black {b}", + "СчитаютÑ�Ñ� только ходы игрока «{name}»: белыми {w}, чёрными {b}", + "Seuls les coups de « {name} » comptent : avec les Blancs {w}, avec les Noirs {b}", + "Nur die Züge von «{name}» zählen: mit Weiß {w}, mit Schwarz {b}", + "Solo cuentan las jugadas de «{name}»: con blancas {w}, con negras {b}", + "Contano solo le mosse di «{name}»: col Bianco {w}, col Nero {b}", + "Só contam os lances de «{name}»: de brancas {w}, de pretas {b}", + "Faqat «{name}» yurishlari hisoblanadi: oq bilan {w}, qora bilan {b}", + "Тек «{name}» жүріÑ�тері еÑ�ептеледі: ақпен {w}, қарамен {b}", + ], + [ + "Not reviewed: {k} ({reason})", + "Ð�е разобраны: {k} ({reason})", + "Non analysées : {k} ({reason})", + "Nicht analysiert: {k} ({reason})", + "No analizadas: {k} ({reason})", + "Non analizzate: {k} ({reason})", + "Não analisadas: {k} ({reason})", + "Tahlil qilinmagan: {k} ({reason})", + "Талданбаған: {k} ({reason})", + ], + [ + "{k} of them were reviewed with the previous engine settings", + "{k} из них разобраны прежними наÑ�тройками движка", + "{k} d’entre elles ont été analysées avec les anciens réglages du moteur", + "{k} davon wurden mit den früheren Engine-Einstellungen analysiert", + "{k} de ellas se analizaron con los ajustes anteriores del motor", + "{k} di esse sono state analizzate con le impostazioni precedenti", + "{k} delas foram analisadas com as definições anteriores do motor", + "Ulardan {k} tasi dvigatelning avvalgi sozlamalari bilan tahlil qilingan", + "Олардың {k} қозғалтқыштың бұрынғы баптауларымен талданған", + ], + [ + "In {k} games the player was not found by name: their moves did not count", + "Ð’ {k} партиÑ�Ñ… игрок не найден по имени — их ходы не Ñ�читалиÑ�ÑŒ", + "Dans {k} parties le joueur n’a pas été trouvé par son nom : leurs coups ne comptent pas", + "In {k} Partien wurde der Spieler nicht am Namen erkannt: ihre Züge zählen nicht", + "En {k} partidas no se encontró al jugador por el nombre: sus jugadas no cuentan", + "In {k} partite il giocatore non è stato trovato per nome: le loro mosse non contano", + "Em {k} partidas o jogador não foi encontrado pelo nome: os seus lances não contam", + "{k} ta partiyada o‘yinchi nomi bo‘yicha topilmadi — ularning yurishlari hisoblanmadi", + "{k} партиÑ�да ойыншы аты бойынша табылмады — олардың жүріÑ�тері еÑ�ептелмеді", + ], + [ + "{k} games are not reviewed: «Continue» reviews only them", + "{k} партий не разобраны — «Продолжить» разберёт только их", + "{k} parties ne sont pas analysées : « Continuer » n’analyse qu’elles", + "{k} Partien sind nicht analysiert: «Fortsetzen» analysiert nur sie", + "{k} partidas sin analizar: «Continuar» analiza solo esas", + "{k} partite non analizzate: «Continua» analizza solo quelle", + "{k} partidas não analisadas: «Continuar» analisa só essas", + "{k} ta partiya tahlil qilinmagan — «Davom etish» faqat ularni tahlil qiladi", + "{k} партиÑ� талданбаған — «ЖалғаÑ�тыру» тек Ñ�оларды талдайды", + ], + [ + "Average accuracy", + "СреднÑ�Ñ� точноÑ�ть", + "Précision moyenne", + "Durchschnittliche Genauigkeit", + "Precisión media", + "Precisione media", + "Precisão média", + "O‘rtacha aniqlik", + "Орташа дәлдік", + ], + [ + "Average over {k}: from {min}% to {max}%", + "Среднее по {k}: от {min}% до {max}%", + "Moyenne sur {k} : de {min} % à {max} %", + "Durchschnitt über {k}: von {min} % bis {max} %", + "Media de {k}: del {min} % al {max} %", + "Media su {k}: dal {min}% al {max}%", + "Média de {k}: de {min}% a {max}%", + "{k} bo‘yicha o‘rtacha: {min}% dan {max}% gacha", + "{k} бойынша орташа: {min}%-дан {max}%-ға дейін", + ], + [ + "No brilliant moves. Games with ! — sort by the «!!» column", + "БлеÑ�Ñ‚Ñ�щих ходов нет. Партии Ñ� ! — Ñ�ортировка по колонке «!!»", + "Aucun coup brillant. Parties avec ! — tri par la colonne « !! »", + "Keine brillanten Züge. Partien mit ! — nach der Spalte «!!» sortieren", + "Sin jugadas brillantes. Partidas con ! — ordenar por la columna «!!»", + "Nessuna mossa brillante. Partite con ! — ordina per la colonna «!!»", + "Sem lances brilhantes. Partidas com ! — ordenar pela coluna «!!»", + "Ajoyib yurishlar yo‘q. ! li partiyalar — «!!» ustuni bo‘yicha saralash", + "Керемет жүріÑ�тер жоқ. ! бар партиÑ�лар — «!!» бағаны бойынша Ñ�ұрыптау", + ], + [ + "Sort", + "ОтÑ�ортировать", + "Trier", + "Sortieren", + "Ordenar", + "Ordina", + "Ordenar", + "Saralash", + "Сұрыптау", + ], + [ + "No brilliant or great moves", + "БлеÑ�Ñ‚Ñ�щих и замечательных ходов нет", + "Aucun coup brillant ou très bon", + "Keine brillanten oder starken Züge", + "Sin jugadas brillantes ni notables", + "Nessuna mossa brillante o notevole", + "Sem lances brilhantes ou notáveis", + "Ajoyib va zo‘r yurishlar yo‘q", + "Керемет және тамаша жүріÑ�тер жоқ", + ], + [ + "Games with !! ({n})", + "Партии Ñ� !! ({n})", + "Parties avec !! ({n})", + "Partien mit !! ({n})", + "Partidas con !! ({n})", + "Partite con !! ({n})", + "Partidas com !! ({n})", + "!! li partiyalar ({n})", + "!! бар партиÑ�лар ({n})", + ], + [ + "Click: choose the row in the table; double click: open at this move", + "Щелчок — выбрать Ñ�троку в таблице, двойной щелчок — открыть на Ñ�том ходе", + "Clic : choisir la ligne dans le tableau ; double clic : ouvrir à ce coup", + "Klick: Zeile in der Tabelle wählen; Doppelklick: bei diesem Zug öffnen", + "Clic: elegir la fila en la tabla; doble clic: abrir en esta jugada", + "Clic: scegli la riga nella tabella; doppio clic: apri a questa mossa", + "Clique: escolher a linha na tabela; duplo clique: abrir neste lance", + "Bosish — jadvalda qatorni tanlash, ikki marta bosish — shu yurishda ochish", + "Шерту — кеÑ�теде жолды таңдау, екі рет шерту — оÑ�Ñ‹ жүріÑ�те ашу", + ], + [ + "Open game", + "Открыть партию", + "Ouvrir la partie", + "Partie öffnen", + "Abrir partida", + "Apri partita", + "Abrir partida", + "Partiyani ochish", + "ПартиÑ�ны ашу", + ], + [ + "Stockfish installed — the search for great moves started", + "Stockfish уÑ�тановлен — поиÑ�к замечательных ходов начат", + "Stockfish installé — la recherche de très bons coups a commencé", + "Stockfish installiert — die Suche nach starken Zügen läuft", + "Stockfish instalado: la búsqueda de jugadas notables ha empezado", + "Stockfish installato — la ricerca di mosse notevoli è iniziata", + "Stockfish instalado — a pesquisa de lances notáveis começou", + "Stockfish o‘rnatildi — ajoyib yurishlarni qidirish boshlandi", + "Stockfish орнатылды — тамаша жүріÑ�терді іздеу баÑ�талды", + ], + [ + "The search for great moves will start by itself when the download finishes.", + "ПоиÑ�к замечательных ходов начнётÑ�Ñ� Ñ�ам, когда загрузка закончитÑ�Ñ�.", + "La recherche de très bons coups commencera d’elle-même à la fin du téléchargement.", + "Die Suche nach starken Zügen beginnt von selbst, wenn der Download fertig ist.", + "La búsqueda de jugadas notables empezará sola cuando termine la descarga.", + "La ricerca di mosse notevoli partirà da sola al termine del download.", + "A pesquisa de lances notáveis começa sozinha quando a transferência terminar.", + "Yuklab olish tugagach, ajoyib yurishlarni qidirish o‘zi boshlanadi.", + "Жүктеу аÑ�қталғанда тамаша жүріÑ�терді іздеу өзі баÑ�талады.", + ], + [ + "A game against the engine waits until the search for great moves ends.", + "Игра Ñ� движком подождёт, пока идёт поиÑ�к замечательных ходов.", + "Une partie contre le moteur attend la fin de la recherche de très bons coups.", + "Eine Partie gegen die Engine wartet, bis die Suche nach starken Zügen endet.", + "Una partida contra el motor espera a que termine la búsqueda de jugadas notables.", + "Una partita contro il motore attende la fine della ricerca di mosse notevoli.", + "Uma partida contra o motor espera pelo fim da pesquisa de lances notáveis.", + "Ajoyib yurishlar qidiruvi tugaguncha dvigatel bilan o‘yin kutadi.", + "Тамаша жүріÑ�терді іздеу аÑ�қталғанша қозғалтқышпен ойын күтеді.", + ], + [ + "matching: {list}", + "по уÑ�ловиÑ�м: {list}", + "selon : {list}", + "nach: {list}", + "según: {list}", + "secondo: {list}", + "segundo: {list}", + "shartlar: {list}", + "шарттар: {list}", + ], + [ + "less than a minute", + "меньше минуты", + "moins d’une minute", + "weniger als eine Minute", + "menos de un minuto", + "meno di un minuto", + "menos de um minuto", + "bir daqiqadan kam", + "бір минуттан аз", + ], + [ + "about {n} min", + "примерно {n} мин", + "environ {n} min", + "etwa {n} Min.", + "unos {n} min", + "circa {n} min", + "cerca de {n} min", + "taxminan {n} daq", + "шамамен {n} мин", + ], + [ + "about {h} h {m} min", + "примерно {h} ч {m} мин", + "environ {h} h {m} min", + "etwa {h} Std. {m} Min.", + "unas {h} h {m} min", + "circa {h} h {m} min", + "cerca de {h} h {m} min", + "taxminan {h} soat {m} daq", + "шамамен {h} Ñ�ағ {m} мин", + ], + [ + "the engine did not start", + "движок не запуÑ�тилÑ�Ñ�", + "le moteur n’a pas démarré", + "die Engine ist nicht gestartet", + "el motor no arrancó", + "il motore non è partito", + "o motor não arrancou", + "dvigatel ishga tushmadi", + "қозғалтқыш Ñ–Ñ�ке қоÑ�ылмады", + ], + [ + "the engine stopped answering", + "движок переÑ�тал отвечать", + "le moteur ne répond plus", + "die Engine antwortet nicht mehr", + "el motor dejó de responder", + "il motore ha smesso di rispondere", + "o motor deixou de responder", + "dvigatel javob bermay qo‘ydi", + "қозғалтқыш жауап бермей қалды", + ], + [ + "The engine will review {games} — {time}.", + "Движок разберёт {games} — {time}.", + "Le moteur analysera {games} : {time}.", + "Die Engine analysiert {games}: {time}.", + "El motor analizará {games}: {time}.", + "Il motore analizzerà {games}: {time}.", + "O motor vai analisar {games}: {time}.", + "Dvigatel {games}ni tahlil qiladi — {time}.", + "Қозғалтқыш {games} талдайды — {time}.", + ], + [ + "{games} is already reviewed: its marks come from the saved review.", + "{games} уже разобрана: её отметки возьмутÑ�Ñ� из Ñ�охранённого разбора.", + "{games} est déjà analysée : ses marques viennent de l’analyse enregistrée.", + "{games} ist bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", + "{games} ya está analizada: sus marcas salen del análisis guardado.", + "{games} è già analizzata: i suoi segni vengono dall’analisi salvata.", + "{games} já está analisada: as suas marcas vêm da análise guardada.", + "{games} allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", + "{games} талданып қойған: белгілері Ñ�ақталған талдаудан алынады.", + ], + [ + "{games} are already reviewed: their marks come from the saved review.", + "{games} уже разобраны: их отметки возьмутÑ�Ñ� из Ñ�охранённого разбора.", + "{games} sont déjà analysées : leurs marques viennent de l’analyse enregistrée.", + "{games} sind bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", + "{games} ya están analizadas: sus marcas salen del análisis guardado.", + "{games} sono già analizzate: i loro segni vengono dall’analisi salvata.", + "{games} já estão analisadas: as suas marcas vêm da análise guardada.", + "{games} allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", + "{games} талданып қойған: белгілері Ñ�ақталған талдаудан алынады.", + ], + [ + "Search stopped · reviewed: {i} of {n} game", + "ПоиÑ�к оÑ�тановлен · разобрана: {i} из {n}", + "Recherche arrêtée · analysée : {i} sur {n}", + "Suche angehalten · analysiert: {i} von {n}", + "Búsqueda detenida · analizada: {i} de {n}", + "Ricerca fermata · analizzata: {i} di {n}", + "Pesquisa parada · analisada: {i} de {n}", + "Qidiruv to‘xtatildi · tahlil qilindi: {n} dan {i}", + "Іздеу тоқтатылды · талданды: {n} ішінен {i}", + ], + [ + "{k} cannot be reviewed ({reason})", + "{k} нельзÑ� разобрать ({reason})", + "{k} ne peuvent pas être analysées ({reason})", + "{k} können nicht analysiert werden ({reason})", + "{k} no se pueden analizar ({reason})", + "{k} non si possono analizzare ({reason})", + "{k} não podem ser analisadas ({reason})", + "{k} tasini tahlil qilib bo‘lmaydi ({reason})", + "{k} талдауға болмайды ({reason})", + ], + [ + "Wait: counting how many selected games are hidden by the current filter", + "Подождите — Ñ�читаю, Ñ�колько выделенных партий Ñ�крыто текущим фильтром", + "Patientez : comptage des parties sélectionnées masquées par le filtre actuel", + "Bitte warten: ausgewählte, vom aktuellen Filter verborgene Partien werden gezählt", + "Espere: contando las partidas seleccionadas ocultas por el filtro actual", + "Attendi: conteggio delle partite selezionate nascoste dal filtro attuale", + "Aguarde: contando as partidas selecionadas ocultas pelo filtro atual", + "Kuting — joriy filtr yashirgan tanlangan partiyalar soni hisoblanmoqda", + "Күтіңіз — ағымдағы Ñ�үзгі жаÑ�ырған таңдалған партиÑ�лар Ñ�аны еÑ�ептелуде", + ], + [ + "Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)", + "Выбрано: {games}. Разобрать их движком и отметить !! и ! (Shift+A)", + "Sélection : {games}. Analysez-les avec le moteur et marquez les !! et ! (Maj+A)", + "Ausgewählt: {games}. Mit der Engine analysieren und !! und ! markieren (Umschalt+A)", + "Seleccionadas: {games}. Analízalas con el motor y marca !! y ! (Mayús+A)", + "Selezionate: {games}. Analizzale con il motore e segna !! e ! (Maiusc+A)", + "Selecionadas: {games}. Analise-as com o motor e marque !! e ! (Shift+A)", + "Tanlangan: {games}. Ularni dvigatel bilan tahlil qilib, !! va ! ni belgilang (Shift+A)", + "Таңдалды: {games}. Оларды қозғалтқышпен талдап, !! және ! белгілеңіз (Shift+A)", + ], + [ + "{k} hidden by the current filter; these games are included too.", + "Скрыто текущим фильтром: {k}; Ñ�ти партии тоже входÑ�Ñ‚.", + "{k} masquées par le filtre actuel ; ces parties sont incluses aussi.", + "{k} vom aktuellen Filter verborgen; diese Partien sind ebenfalls enthalten.", + "{k} ocultas por el filtro actual; estas partidas también se incluyen.", + "{k} nascoste dal filtro attuale; anche queste partite sono incluse.", + "{k} ocultas pelo filtro atual; estas partidas também estão incluídas.", + "Joriy filtr {k} tasini yashirdi; bu partiyalar ham kiradi.", + "Ð�ғымдағы Ñ�үзгі {k} партиÑ�ны жаÑ�ырды; олар да кіреді.", + ], + [ + "The filter does not change this run's games.", + "Фильтр не менÑ�ет Ñ�оÑ�тав Ñ�того запуÑ�ка.", + "Le filtre ne change pas les parties de ce lancement.", + "Der Filter ändert die Partien dieses Laufs nicht.", + "El filtro no cambia las partidas de este análisis.", + "Il filtro non cambia le partite di questa analisi.", + "O filtro não altera as partidas desta análise.", + "Filtr bu ishga tushirishdagi partiyalarni o‘zgartirmaydi.", + "Сүзгі бұл Ñ–Ñ�ке қоÑ�удғы партиÑ�ларды өзгертпейді.", + ], + [ + "Selected: {games} — more than 100.", + "Выбрано: {games} — больше 100.", + "Sélection : {games} — plus de 100.", + "Ausgewählt: {games} — mehr als 100.", + "Seleccionadas: {games} — más de 100.", + "Selezionate: {games} — più di 100.", + "Selecionadas: {games} — mais de 100.", + "Tanlangan: {games} — 100 tadan ko‘p.", + "Таңдалды: {games} — 100-ден аÑ�там.", + ], + [ + "Keep no more than 100 selected; the filter is not used.", + "ОÑ�тавьте не больше 100 выделенных; фильтр не иÑ�пользуетÑ�Ñ�.", + "Gardez au plus 100 parties sélectionnées ; le filtre n’est pas utilisé.", + "Behalten Sie höchstens 100 ausgewählte Partien; der Filter wird nicht verwendet.", + "Deje no más de 100 seleccionadas; el filtro no se usa.", + "Mantieni non più di 100 selezionate; il filtro non viene usato.", + "Mantenha no máximo 100 selecionadas; o filtro não é usado.", + "100 tadan oshiq tanlangan partiya qoldirmang; filtr ishlatilmaydi.", + "100-ден артық таңдалған партиÑ� қалдырмаңыз; Ñ�үзгі қолданылмайды.", + ], + [ + "Source: selected {games}; hidden by the filter at start: {k}.", + "ИÑ�точник: выбранные {games}; Ñ�крыто фильтром при запуÑ�ке: {k}.", + "Source : {games} sélectionnées ; masquées par le filtre au lancement : {k}.", + "Quelle: {games} ausgewählt; beim Start vom Filter verborgen: {k}.", + "Origen: {games} seleccionadas; ocultas por el filtro al iniciar: {k}.", + "Origine: {games} selezionate; nascoste dal filtro all'avvio: {k}.", + "Origem: {games} selecionadas; ocultas pelo filtro no início: {k}.", + "Manba: tanlangan {games}; boshlang‘ichda filtr yashirganni: {k}.", + "Көз: таңдалған {games}; баÑ�ында Ñ�үзгі жаÑ�ырғаны: {k}.", + ], + [ + "Source: selected {games}.", + "ИÑ�точник: выбранные {games}.", + "Source : {games} sélectionnées.", + "Quelle: {games} ausgewählt.", + "Origen: {games} seleccionadas.", + "Origine: {games} selezionate.", + "Origem: {games} selecionadas.", + "Manba: tanlangan {games}.", + "Көз: таңдалған {games}.", + ], + [ + "Selection and filter changes do not change this pass.", + "ИзменениÑ� выделениÑ� и фильтра не менÑ�ÑŽÑ‚ Ñ�тот проход.", + "Les changements de sélection et de filtre ne modifient pas ce passage.", + "Änderungen an Auswahl und Filter ändern diesen Durchlauf nicht.", + "Los cambios de selección y filtro no cambian este recorrido.", + "Le modifiche a selezione e filtro non cambiano questa analisi.", + "As alterações de seleção e filtro não mudam esta passagem.", + "Tanlov va filtr o‘zgarishlari bu o‘tishni o‘zgartirmaydi.", + "Таңдау мен Ñ�үзгі өзгеріÑ�тері бұл өтуді өзгертпейді.", + ], + [ + "Selected: {games}", + "Выбрано: {games}", + "Sélection : {games}", + "Ausgewählt: {games}", + "Seleccionadas: {games}", + "Selezionate: {games}", + "Selecionadas: {games}", + "Tanlangan: {games}", + "Таңдалды: {games}", + ], + [ + "{k} hidden by the current filter", + "{k} Ñ�крыто текущим фильтром", + "{k} masquées par le filtre actuel", + "{k} vom aktuellen Filter verborgen", + "{k} ocultas por el filtro actual", + "{k} nascoste dal filtro attuale", + "{k} ocultas pelo filtro atual", + "Joriy filtr {k} tasini yashirdi", + "Ð�ғымдағы Ñ�үзгі {k} партиÑ�ны жаÑ�ырды", + ], + [ + "Only the moves of «{name}» count.", + "СчитаютÑ�Ñ� только ходы игрока «{name}».", + "Seuls les coups de « {name} » comptent.", + "Nur die Züge von «{name}» zählen.", + "Solo cuentan las jugadas de «{name}».", + "Contano solo le mosse di «{name}».", + "Só contam os lances de «{name}».", + "Faqat «{name}» yurishlari hisoblanadi.", + "Тек «{name}» жүріÑ�тері еÑ�ептеледі.", + ], + [ + "Only the moves of «{name}» as White count.", + "СчитаютÑ�Ñ� только ходы игрока «{name}» белыми.", + "Seuls les coups de « {name} » avec les Blancs comptent.", + "Nur die Züge von «{name}» mit Weiß zählen.", + "Solo cuentan las jugadas de «{name}» con blancas.", + "Contano solo le mosse di «{name}» col Bianco.", + "Só contam os lances de «{name}» de brancas.", + "Faqat «{name}» ning oq bilan yurishlari hisoblanadi.", + "Тек «{name}» ақпен жүрген жүріÑ�тері еÑ�ептеледі.", + ], + [ + "Only the moves of «{name}» as Black count.", + "СчитаютÑ�Ñ� только ходы игрока «{name}» чёрными.", + "Seuls les coups de « {name} » avec les Noirs comptent.", + "Nur die Züge von «{name}» mit Schwarz zählen.", + "Solo cuentan las jugadas de «{name}» con negras.", + "Contano solo le mosse di «{name}» col Nero.", + "Só contam os lances de «{name}» de pretas.", + "Faqat «{name}» ning qora bilan yurishlari hisoblanadi.", + "Тек «{name}» қарамен жүрген жүріÑ�тері еÑ�ептеледі.", + ], + [ + "The player condition limits the moves counted, but does not exclude selected games from review.", + "УÑ�ловие игрока ограничивает Ñ�читаемые ходы, но не иÑ�ключает выбранные партии из разбора.", + "La condition du joueur limite les coups comptés, mais n’exclut pas les parties sélectionnées de l’analyse.", + "Die Spielerbedingung begrenzt die gezählten Züge, schließt ausgewählte Partien aber nicht aus der Analyse aus.", + "La condición del jugador limita las jugadas contadas, pero no excluye las partidas seleccionadas del análisis.", + "La condizione del giocatore limita le mosse contate, ma non esclude le partite selezionate dall'analisi.", + "A condição do jogador limita os lances contados, mas não exclui as partidas selecionadas da análise.", + "O‘yinchi sharti hisoblanadigan yurishlarni cheklaydi, ammo tanlangan partiyalarni tahlildan chiqarmaydi.", + "Ойыншы шарты еÑ�ептелетін жүріÑ�терді шектейді, бірақ таңдалған партиÑ�ларды талдаудан шығармайды.", + ], + [ + "Hidden by the filter at start: {k}", + "Скрыто фильтром при запуÑ�ке: {k}", + "Masquées par le filtre au lancement : {k}", + "Beim Start vom Filter verborgen: {k}", + "Ocultas por el filtro al iniciar: {k}", + "Nascoste dal filtro all'avvio: {k}", + "Ocultas pelo filtro no início: {k}", + "Boshlang‘ichda filtr yashirganni: {k}", + "БаÑ�ында Ñ�үзгі жаÑ�ырғаны: {k}", + ], +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn system_language() { + assert_eq!(Lang::from_locales(["ru-RU"]), Lang::Ru); + assert_eq!(Lang::from_locales(["ru_RU.UTF-8"]), Lang::Ru); + assert_eq!(Lang::from_locales(["uk-UA", "ru-RU", "en-US"]), Lang::Ru); + assert_eq!(Lang::from_locales(["de-CH"]), Lang::De); + assert_eq!(Lang::from_locales(["es-419"]), Lang::Es); + assert_eq!(Lang::from_locales(["fr"]), Lang::Fr); + assert_eq!(Lang::from_locales(["it_IT@euro"]), Lang::It); + assert_eq!(Lang::from_locales(["en-GB", "ru-RU"]), Lang::En); + assert_eq!(Lang::from_locales(["ja-JP", "pt-BR"]), Lang::Pt); + assert_eq!(Lang::from_locales(["pt_PT.UTF-8"]), Lang::Pt); + assert_eq!(Lang::from_locales(["uz-Latn-UZ"]), Lang::Uz); + assert_eq!(Lang::from_locales(["kk_KZ"]), Lang::Kk); + assert_eq!(Lang::from_locales(["ja-JP"]), Lang::En); + assert_eq!(Lang::from_locales(["C"]), Lang::En); + assert_eq!(Lang::from_locales(Vec::::new()), Lang::En); + } + + /// Every character the interface shows — the translations in all languages and the + /// string literals of the sources — has a glyph in the bundled fonts (no empty boxes). + #[test] + fn every_shown_character_has_a_glyph() { + let sources = [ + include_str!("app.rs"), + include_str!("assets.rs"), + include_str!("analysis.rs"), + include_str!("game_view.rs"), + include_str!("library.rs"), + include_str!("large_db.rs"), + include_str!("board_search.rs"), + include_str!("engine_offer.rs"), + include_str!("notation.rs"), + include_str!("review.rs"), + include_str!("engines.rs"), + include_str!("examples.rs"), + include_str!("settings.rs"), + include_str!("settings_ui.rs"), + include_str!("widgets.rs"), + include_str!("reference.rs"), + include_str!("online.rs"), + include_str!("online_ui.rs"), + include_str!("update.rs"), + include_str!("update_ui.rs"), + include_str!("board.rs"), + include_str!("engine_download.rs"), + include_str!("main.rs"), + include_str!("graphics.rs"), + include_str!("translate.rs"), + include_str!("translate_ui.rs"), + include_str!("chatgpt.rs"), + include_str!("san.rs"), + include_str!("prep_ui.rs"), + include_str!("opening_layout.rs"), + include_str!("opening_lines.rs"), + include_str!("opening_session.rs"), + include_str!("repertoire_ui.rs"), + include_str!("batch_copy.rs"), + include_str!("brilliant.rs"), + include_str!("brilliant_ui.rs"), + ]; + let mut chars = std::collections::BTreeSet::new(); + for row in ROWS.iter() { + for text in row.iter() { + chars.extend(text.chars()); + } + } + for src in sources { + for line in src.lines().filter(|l| !l.trim_start().starts_with("//")) { + // The parts of the line inside double quotes. + for (i, part) in line.split('"').enumerate() { + if i % 2 == 1 { + chars.extend(part.chars()); + } + } + } + } + // The characters each font of the text has (egui's own check cannot tell a + // glyph of its last fallback from the replacement box). + let fonts = crate::assets::font_definitions(); + let maps: Vec> = fonts.families + [&egui::FontFamily::Proportional] + .iter() + .map(|name| { + use skrifa::MetadataProvider as _; + let data = &fonts.font_data[name]; + let font = skrifa::FontRef::new(&data.font).expect("a font"); + font.charmap().mappings().map(|(c, _)| c).collect() + }) + .collect(); + let missing: Vec = chars + .into_iter() + .filter(|c| !c.is_ascii() && !c.is_whitespace() && *c != '\u{fe0f}') + .filter(|c| !maps.iter().any(|m| m.contains(&(*c as u32)))) + .map(|c| format!("{c} U+{:04X}", c as u32)) + .collect(); + assert!(missing.is_empty(), "no glyph for: {missing:?}"); + } + + /// Every `tr("…")` / `trf("…"` key used in the sources must have a translation row. + #[test] + fn all_used_keys_are_translated() { + let sources = [ + include_str!("app.rs"), + include_str!("assets.rs"), + include_str!("analysis.rs"), + include_str!("game_view.rs"), + include_str!("library.rs"), + include_str!("large_db.rs"), + include_str!("board_search.rs"), + include_str!("engine_offer.rs"), + include_str!("notation.rs"), + include_str!("review.rs"), + include_str!("engines.rs"), + include_str!("examples.rs"), + include_str!("settings.rs"), + include_str!("settings_ui.rs"), + include_str!("widgets.rs"), + include_str!("reference.rs"), + include_str!("online.rs"), + include_str!("online_ui.rs"), + include_str!("update.rs"), + include_str!("update_ui.rs"), + include_str!("board.rs"), + include_str!("engine_download.rs"), + include_str!("main.rs"), + include_str!("graphics.rs"), + include_str!("translate.rs"), + include_str!("translate_ui.rs"), + include_str!("chatgpt.rs"), + include_str!("san.rs"), + include_str!("prep_ui.rs"), + include_str!("opening_layout.rs"), + include_str!("opening_lines.rs"), + include_str!("opening_session.rs"), + include_str!("repertoire_ui.rs"), + include_str!("brilliant.rs"), + include_str!("brilliant_ui.rs"), + ]; + let mut missing = Vec::new(); + let mut found = 0; + for src in sources { + for marker in ["tr(", "trf("] { + for (i, _) in src.match_indices(marker) { + // Skip identifiers that merely end in `tr` (e.g. `str(`). + let prev = src[..i].chars().next_back(); + if prev.is_some_and(|c| c.is_alphanumeric() || c == '_') { + continue; + } + // rustfmt may move the literal to the next line. + let rest = src[i + marker.len()..].trim_start(); + let Some(rest) = rest.strip_prefix('"') else { + continue; + }; + let Some(end) = rest.find('"') else { continue }; + found += 1; + let key = &rest[..end]; + if !table().contains_key(key) { + missing.push(key.to_string()); + } + } + } + } + assert!(found > 100, "scanner found only {found} keys"); + assert!(missing.is_empty(), "untranslated keys: {missing:?}"); + } + + /// Rodent's styles are shown through `tr` of their fields, out of the scanner's sight. + #[test] + fn every_style_is_translated() { + for st in crate::play::STYLES { + for key in [st.title(), st.about] { + assert!( + ROWS.iter().any(|row| row[0] == key), + "untranslated style text: {key}" + ); + } + } + } + + #[test] + fn rows_are_unique_and_complete() { + let mut seen = std::collections::HashSet::new(); + for row in ROWS.iter() { + assert!(seen.insert(row[0]), "duplicate key {}", row[0]); + assert!( + row.iter().all(|s| !s.is_empty()), + "empty cell in {}", + row[0] + ); + } + } +} diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs new file mode 100644 index 0000000..8719113 --- /dev/null +++ b/apps/desktop/src/large_db.rs @@ -0,0 +1,4326 @@ +//! Game list of a large ChessBase database (millions of games): a filter panel on +//! the right and a table of the matching records. Filtering and sorting run in a +//! background thread; a newer request cancels the older one. Layout and behaviour: +//! `docs/design/large-databases.md`. + +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::mpsc::{Receiver, channel}; + +use chess_import::Database; +use chess_import::chessbase::base::{ + EloRule, Filter, NameFilter, Outcome, RecordKind, Side, SortKey, Suggestion, parse_eco, +}; +use chess_import::position::{Match, PositionOutcome, PositionQuery}; +use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; +use egui_extras::{Column, TableBuilder}; +use shakmaty::uci::UciMove; + +use crate::board_search::{self, Background, BoardEvent, SearchBoard}; +use crate::i18n::{tr, trf}; +use crate::library::LibraryAction; +use crate::prep_ui::PrepEntry; +use crate::settings::Settings; +use crate::viewed::{self, Viewed}; + +/// The × of a text field and its gap (`widgets::small_close_button` is 22 pt wide). +const CLEAR_SLOT: f32 = 26.0; + +/// Text edits are applied this long after the last key press. +const DEBOUNCE: f64 = 0.25; +/// A pass that takes longer than this dims the table and shows its progress. +const SLOW: f64 = 0.15; +const SUGGESTIONS: usize = 8; + +/// The name fields that offer suggestions. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum NameField { + Player, + Opponent, + Event, +} + +/// What the user typed and picked in the panel. +#[derive(Clone, Default)] +struct Form { + player: NameFilter, + side: Side, + opponent: NameFilter, + event: NameFilter, + annotator: String, + year_from: String, + year_to: String, + elo_min: String, + elo_rule: EloRule, + outcomes: Vec, + eco: String, + moves_from: String, + moves_to: String, + with_comments: bool, + with_variations: bool, + hide_texts: bool, + /// The result buttons are relative to the player (win / loss). + relative_outcomes: bool, + /// The quick search of the header (not a condition of the panel). + search: String, +} + +/// Number in a field: `Ok(None)` when empty, `Err` when not a number in `range`. +fn number(text: &str, range: std::ops::RangeInclusive) -> Result, ()> { + let t = text.trim(); + if t.is_empty() { + return Ok(None); + } + match t.parse::() { + Ok(n) if range.contains(&n) => Ok(Some(n)), + _ => Err(()), + } +} + +impl Form { + /// The filter for the valid fields (invalid ones are left out and shown in red). + fn filter(&self) -> Filter { + let years = ( + number(&self.year_from, 1..=2100), + number(&self.year_to, 1..=2100), + ); + let (year_from, year_to) = match years { + (Ok(a), Ok(b)) if a.zip(b).is_none_or(|(a, b)| a <= b) => (a, b), + (Ok(a), Err(())) => (a, None), + (Err(()), Ok(b)) => (None, b), + _ => (None, None), + }; + let moves = ( + number(&self.moves_from, 0..=999), + number(&self.moves_to, 0..=999), + ); + let (moves_from, moves_to) = match moves { + (Ok(a), Ok(b)) if a.zip(b).is_none_or(|(a, b)| a <= b) => (a, b), + _ => (None, None), + }; + let player_set = self.player.is_set(); + Filter { + player: self.player.clone(), + side: if player_set { self.side } else { Side::Any }, + opponent: self.opponent.clone(), + event: self.event.clone(), + annotator: self.annotator.clone(), + year_from, + year_to, + elo_min: number(&self.elo_min, 1..=3500).ok().flatten(), + elo_rule: self.elo_rule, + eco: parse_eco(&self.eco).unwrap_or_default(), + outcomes: self.outcomes.clone(), + player_relative: player_set, + moves_from, + moves_to, + with_comments: self.with_comments, + with_variations: self.with_variations, + games_only: self.hide_texts, + text: self.search.trim().to_string(), + } + } + + /// Number of conditions set (for "Reset filters (N)"). + fn active(&self) -> usize { + let text = |s: &str| usize::from(!s.trim().is_empty()); + usize::from(self.player.is_set()) + + usize::from(self.opponent.is_set()) + + usize::from(self.event.is_set()) + + text(&self.annotator) + + usize::from(!self.year_from.trim().is_empty() || !self.year_to.trim().is_empty()) + + text(&self.elo_min) + + usize::from(!self.outcomes.is_empty()) + + text(&self.eco) + + usize::from(!self.moves_from.trim().is_empty() || !self.moves_to.trim().is_empty()) + + usize::from(self.with_comments) + + usize::from(self.with_variations) + + usize::from(self.hide_texts) + } +} + +#[derive(Clone)] +struct Request { + filter: Filter, + sort: SortKey, + ascending: bool, + /// The order of the view without a position (a position not applied for lack of + /// memory sorts by it, not strongest first). + base_sort: (SortKey, bool), + /// The board's position while the board is shown or the position filters the list + /// (its continuations are counted even in the starting position). + position: Option<(u64, PositionQuery)>, + /// The position filters the list (it differs from the starting position). + use_position: bool, + only_order: bool, +} + +impl PartialEq for Request { + fn eq(&self, other: &Request) -> bool { + let pos = |r: &Request| r.position.as_ref().map(|(k, q)| (*k, q.line.clone())); + self.filter == other.filter + && self.sort == other.sort + && self.ascending == other.ascending + && self.base_sort == other.base_sort + && pos(self) == pos(other) + && self.use_position == other.use_position + && self.only_order == other.only_order + } +} + +/// The game list for a request and, with a position, its search outcome. +struct Answer { + view: Vec, + outcome: Option>, + /// Games that reached the position in the board's move order, of all found. + in_order: Option<(usize, usize)>, + /// The position was not searched: the memory its table needs (bytes) is not there. + blocked: Option, +} + +struct Job { + request: Request, + work: Background, +} + +/// What the header line says about a database (the library knows it). +pub struct Header { + /// "ChessBase, read-only", "PGN, encoding UTF-8"… + pub format: String, + pub format_hint: String, + /// A database downloaded from Lichess and Chess.com: its "⟳ New games". + pub online: Option, + /// A file the browser holds only for this visit: "Keep a copy in the browser". + pub keep_copy: bool, +} + +pub struct OnlineButton { + /// A download into it runs. + pub busy: bool, + /// The sites answered at start. + pub enabled: bool, + pub hint: String, +} + +/// What the right side of the library shows for a database. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Pane { + Hidden, + Filters, + Board, +} + +/// Widths of the narrow set of table columns (docs/design/narrow-windows.md §1): the +/// least table is built of them, so the table and its least width do not part. +const MOVE_COL: f32 = 52.0; +const ELO_COL: f32 = 44.0; +const RESULT_COL: f32 = 56.0; +const YEAR_COL: f32 = 48.0; +/// A name still recognised ("Конюшенко С…"). +const NAME_MIN: f32 = 110.0; + +/// The width of the "â„–" column: as wide as the largest number (a check mark before it). +fn number_col(db: &Database) -> f32 { + let digits = grouped(db.len()).chars().count() as f32; + (digits * 8.0 + 24.0).clamp(52.0, 84.0) +} + +/// The width of `text` in `style` on one line. +fn text_w(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { + ui.painter() + .layout_no_wrap(text.to_owned(), style.resolve(ui.style()), Color32::WHITE) + .size() + .x +} + +/// Search outcomes of the session, by filter and position with the board's move order +/// (it decides "in this move order"). +type OutcomeCache = HashMap<(u64, u64), Arc>; + +/// Matching games kept in the cache at most (16 bytes each). +const CACHE_MATCHES: usize = 20_000_000; + +/// Identity of a searched position with the board's move order. +fn position_id((key, query): &(u64, PositionQuery)) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + key.hash(&mut h); + if let Some(line) = &query.line { + for m in line { + chess_import::position::uci(m).to_string().hash(&mut h); + } + } else { + "no line".hash(&mut h); + } + h.finish() +} + +fn filter_hash(f: &Filter) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + f.hash(&mut h); + h.finish() +} + +struct SuggestJob { + field: NameField, + query: String, + rx: Receiver<(Vec, usize)>, +} + +/// The open suggestion list of a name field. +struct Suggestions { + field: NameField, + query: String, + list: Vec, + total: usize, + highlighted: Option, +} + +/// The search for great moves under way, as the conditions line shows it. +#[derive(Clone, Debug, PartialEq)] +pub struct PassStatus { + /// In this database (else in `name`). + pub here: bool, + pub name: String, + pub selected: Option, + pub done: usize, + pub total: usize, + /// The record being analysed. + pub current: Option, + pub left_secs: f64, + pub stopping: bool, +} + +/// A copy of chosen records being written, as the conditions line shows it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BatchStatus { + pub name: String, + pub done: usize, + pub total: usize, + pub cancelling: bool, +} + +/// State of one large database in the library (kept for the session). +pub struct LargeView { + form: Form, + sort: (SortKey, bool), + /// The user picked the sort order (otherwise a position sorts strongest first). + sort_chosen: bool, + /// Matching records, in display order, and the request they answer. + view: Vec, + shown: Option, + outcome: Option>, + in_order: Option<(usize, usize)>, + cache: OutcomeCache, + job: Option, + /// Building the search index of the base (our booster when `.cbb` cannot be used, + /// the opening positions), once the board is used; `booster_failed` keeps a + /// failure from being retried. + /// The job and the work it has to do (in its progress units). + booster: Option<(Background, usize)>, + booster_failed: bool, + board: SearchBoard, + only_order: bool, + /// Next move of the game under the pointer in the table (an arrow on the board). + table_hover: Option, + /// Time of the last edit of a text field (for the debounce). + typed_at: f64, + suggest_job: Option, + suggestions: Option, + /// The pointer is on the open suggestion list. + pointer_on_list: bool, + /// Record index of the row under the keyboard cursor: Enter, F2 and «Board» take it. + pub selected: Option, + /// The records chosen (task 42): one or many, kept across filters and sorting. + marked: crate::batch_copy::Selection, + /// Where a Shift range starts. + anchor: Option, + /// Changes of `marked` and of `view`, and the chosen records the list hides then. + marked_gen: u64, + view_gen: u64, + hidden: Option<(u64, u64, usize)>, + /// The copy of chosen records being written (set by the library each frame). + pub batch: Option, + /// «Cancel» of that copy was clicked. + pub cancel_batch: bool, + /// Why the last copy wrote nothing: said in red where its progress was, until `×`. + pub batch_error: Option, + /// The chosen records as the file had them before it was read again (a hash of + /// each one's bytes), to know they are still the same games; `None` for a choice too + /// large to check (it is let go when the file changes). + marked_before: Option>, + /// Said once (a toast), taken by the library. + pub notice: Option, + /// The marks of the records found by the search for great moves (task 27), set by + /// the library; what the table shows of them, checked against each record's main + /// line, by record, for the index's generation. + pub marks: Option>>, + shown_marks: std::cell::RefCell<(u64, HashMap>)>, + /// The table sorted by the «!!» column. + marks_sort: bool, + /// The database the marks are checked against (set by `table`). + marks_db: Option>, + /// The texts of the conditions of the list (for the search's question). + last_conditions: Vec, + /// Whose moves the «!!» column counts: the filter's player's (found in the background + /// for that filter), else both sides'. + marks_sides: (Option, crate::brilliant::Sides), + sides_job: Option<(Filter, Receiver)>, + /// The search under way (here or in another database), set by the library. + pub pass: Option, + /// Why the search cannot start now (the engine is busy), set by the app. + pub engine_busy: Option, + /// Why the last search stopped with an error, in red where its progress was. + pub pass_error: Option, + /// «Stop» of the search was clicked. + pub stop_pass: bool, + /// «!! Find great moves» was clicked (taken by `table`, which has the path). + find_clicked: bool, + scroll_to_selected: bool, + scroll_to_top: bool, + focus_player: bool, + pane: Pane, + /// Last text of each name field, to notice typing. + typed: [String; 3], + /// Most games have no result: the continuations count chapters (a book). + books: bool, + /// The position of the shown list could not be searched for lack of memory + /// (the memory its table needs, bytes). + blocked: Option, + /// Ctrl+F asked for the quick search. + focus_search: bool, + /// The database takes games (delete, add a copy): set by `table`. + writable: bool, + /// The file was read again: the next list is the same list, not a new filter (the + /// place in the table and the selection stay). + rereading: bool, + /// The window is too narrow for the filters beside the table: they open over it + /// (`drawer_open`), and too narrow for the board beside it: one at a time (§2). + narrow_filters: bool, + narrow_board: bool, + drawer_open: bool, + /// Something asked for the filters this frame (it was clicked, not "elsewhere"). + drawer_asked: bool, + /// Where the filters open over the table: under its header and conditions. + drawer_top: f32, + /// The quick search has the keyboard (arrows and Enter go to the table). + search_focused: bool, + /// «Prepare against…» was asked (the panel's button, a row's menu): the library + /// takes it (docs/design/opponent-prep.md §2.1). + pub prepare: Option, + /// The web page of the game whose context menu is open (its record, the link). + menu_link: Option<(usize, Option)>, +} + +impl LargeView { + pub fn new() -> LargeView { + // Dev hook (screenshots, manual checks): a player filter from the start. + let mut form = Form::default(); + if let Ok(p) = std::env::var("CP_FILTER_PLAYER") { + form.player.text = p; + } + // `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` (screenshots). + if let Ok(spec) = std::env::var("CP_FILTER") { + for part in spec.split(';') { + let Some((k, v)) = part.split_once('=') else { + continue; + }; + match k.trim() { + "player" => form.player.text = v.to_string(), + "years" => { + let (a, b) = v.split_once('-').unwrap_or((v, "")); + form.year_from = a.to_string(); + form.year_to = b.to_string(); + } + "elo" => form.elo_min = v.to_string(), + _ => {} + } + } + } + // `CP_SEARCH="carlsen 2024"`: the quick search from the start (screenshots). + if let Ok(t) = std::env::var("CP_SEARCH") { + form.search = t; + } + let (board, mut pane) = match SearchBoard::from_env() { + Some(b) => (b, Pane::Board), + None => (SearchBoard::new(), Pane::Filters), + }; + // `CP_PANE=hidden`: no panel; `=drawer`: the filters open over the table in a + // narrow window (beside it in a wide one). + let pane_env = std::env::var("CP_PANE").ok(); + if pane_env.as_deref() == Some("hidden") { + pane = Pane::Hidden; + } + let drawer = pane_env.as_deref() == Some("drawer"); + // `CP_SORT=date`: newest games first (screenshots). + // `CP_SELECT=3,7,15`: these records (their numbers in the table) chosen, the + // cursor on the last (screenshots of task 42). + let mut marked = crate::batch_copy::Selection::default(); + let mut cursor = None; + if let Ok(list) = std::env::var("CP_SELECT") { + for n in list + .split(',') + .filter_map(|n| n.trim().parse::().ok()) + { + if n > 0 { + marked.insert(n - 1); + cursor = Some(n - 1); + } + } + } + let sort = if std::env::var("CP_SORT").as_deref() == Ok("date") { + (SortKey::Date, false) + } else { + (SortKey::Number, true) + }; + LargeView { + form, + sort, + sort_chosen: sort.0 != SortKey::Number, + view: Vec::new(), + shown: None, + outcome: None, + in_order: None, + cache: HashMap::new(), + job: None, + booster: None, + booster_failed: false, + board, + only_order: false, + table_hover: None, + typed_at: f64::NEG_INFINITY, + suggest_job: None, + suggestions: None, + pointer_on_list: false, + selected: cursor, + marked, + anchor: cursor, + marked_gen: 0, + view_gen: 0, + hidden: None, + batch: None, + cancel_batch: false, + batch_error: None, + marked_before: None, + notice: None, + marks: None, + shown_marks: std::cell::RefCell::new((u64::MAX, HashMap::new())), + marks_sort: false, + marks_db: None, + last_conditions: Vec::new(), + marks_sides: (None, Default::default()), + sides_job: None, + pass: None, + engine_busy: None, + pass_error: None, + stop_pass: false, + find_clicked: false, + scroll_to_selected: false, + scroll_to_top: false, + focus_player: false, + pane, + typed: Default::default(), + books: false, + blocked: None, + focus_search: false, + writable: false, + rereading: false, + search_focused: false, + narrow_filters: drawer, + narrow_board: false, + drawer_open: drawer, + drawer_asked: false, + drawer_top: 0.0, + prepare: None, + menu_link: None, + } + } + + /// The view of a database just opened: a book's continuations count chapters, and + /// games downloaded from Lichess and Chess.com come newest first (§9.6). + pub fn for_database(db: &Database, online: bool) -> LargeView { + let mut view = LargeView::new(); + view.books = db.books(); + if online && view.sort == (SortKey::Number, true) { + view.sort = (SortKey::Date, false); + } + view + } + + /// The database was read again (it grew): the list is found anew, the conditions, + /// the position, the sort and the selection stay (§9.7). + pub fn reread(&mut self, db: &Database) { + self.job = None; + self.shown = None; + self.rereading = true; + self.outcome = None; + self.in_order = None; + self.cache.clear(); + self.blocked = None; + self.books = db.books(); + self.shown_marks.borrow_mut().1.clear(); + // Several chosen: kept only if each is still the same record (a game added at + // the end keeps them; one deleted or put back moves the numbers). Otherwise let + // go, and said: the choice never moves to other games unnoticed. + if self.marked.len() >= 2 { + let same = std::mem::take(&mut self.marked_before).is_some_and(|before| { + before.len() == self.marked.len() + && before + .iter() + .all(|&(r, h)| (r as usize) < db.len() && record_hash(db, r as usize) == h) + }); + if !same { + self.clear_marks(); + self.notice = Some(tr("Selection cleared: the database changed").to_owned()); + } + } else if self.marked.last().is_some_and(|r| r >= db.len()) { + self.mark(|m| m.clear()); + } + self.selected = self.selected.filter(|&c| c < db.len()); + } + + /// Before the file is read again: what the chosen records are now (up to + /// `CHECKED_CHOICE` of them). + pub fn before_reread(&mut self, db: &Database) { + self.marked_before = + (self.marked.len() >= 2 && self.marked.len() <= CHECKED_CHOICE).then(|| { + self.marked + .records() + .into_iter() + .map(|r| (r, record_hash(db, r as usize))) + .collect() + }); + } + + /// Selects a record and scrolls to it (returning from a game): a choice of several + /// records stays. + pub fn reveal(&mut self, index: usize) { + self.selected = Some(index); + if self.marked.len() <= 1 { + self.mark(|m| m.only(index)); + } + self.scroll_to_selected = true; + } + + /// Changes the chosen records. + fn mark(&mut self, change: impl FnOnce(&mut crate::batch_copy::Selection)) { + change(&mut self.marked); + self.marked_gen += 1; + } + + /// No record chosen any more. + pub fn clear_marks(&mut self) { + self.mark(|m| m.clear()); + self.anchor = None; + } + + /// The chosen records hidden by the list's filter, counted once per change. + fn hidden_marked(&mut self) -> usize { + let key = (self.marked_gen, self.view_gen); + match self.hidden { + Some((m, v, n)) if (m, v) == key => n, + _ => { + let n = self.marked.len() - self.marked.count_in(&self.view); + self.hidden = Some((key.0, key.1, n)); + n + } + } + } + + /// The choice comes down to the cursor's row (Esc, «Clear», a row deleted). + fn mark_cursor_only(&mut self) { + let cursor = self.selected; + self.mark(|m| match cursor { + Some(i) => m.only(i), + None => m.clear(), + }); + self.anchor = cursor; + } + + /// The records of the view from position `a` to position `b` (either order). + fn range(&self, a: usize, b: usize) -> &[u32] { + let (lo, hi) = (a.min(b), a.max(b)); + &self.view[lo..=hi.min(self.view.len().saturating_sub(1))] + } + + fn position_of(&self, record: usize) -> Option { + self.view.iter().position(|&i| i as usize == record) + } + + /// The cursor cannot stay on a record hidden by a new filter. Its mark can: marked + /// records are a separate selection, including a single hidden record. + fn clear_hidden_cursor(&mut self) { + if self + .selected + .is_some_and(|sel| !self.view.contains(&(sel as u32))) + { + self.selected = None; + } + } + + /// A click on the row of `index` with `mods` (§42.5). + fn click(&mut self, index: usize, mods: egui::Modifiers) { + // An anchor hidden by the filter: the cursor, when it is seen, starts the range. + let anchor = self + .anchor + .filter(|a| self.position_of(*a).is_some()) + .or(self.selected.filter(|c| self.position_of(*c).is_some())); + let at = self.position_of(index); + match ( + mods.command, + mods.shift, + anchor.and_then(|a| self.position_of(a)), + at, + ) { + (add, true, Some(a), Some(b)) => { + let range = self.range(a, b).to_vec(); + self.mark(|m| { + if !add { + m.clear(); + } + m.extend(&range); + }); + } + (true, false, _, _) => { + self.mark(|m| m.toggle(index)); + self.anchor = Some(index); + } + _ => { + self.mark(|m| m.only(index)); + self.anchor = Some(index); + } + } + self.selected = Some(index); + } + + /// The filter's player's sides of each record, for the «!!» column: found again in + /// the background when the filter changes; both sides without a player. + fn update_marks_sides(&mut self, db: &Arc, ctx: &egui::Context) { + let filter = self.form.filter(); + if let Some((f, rx)) = &self.sides_job + && let Ok(sides) = rx.try_recv() + { + self.marks_sides = (Some(f.clone()), sides); + self.sides_job = None; + self.shown_marks.borrow_mut().1.clear(); + if self.marks_sort { + self.sort_by_marks(); + } + } + let wanted = self.marks_sides.0.as_ref() == Some(&filter) + || self.sides_job.as_ref().is_some_and(|(f, _)| *f == filter); + if wanted { + return; + } + if !filter.player.is_set() { + self.marks_sides = (Some(filter), Default::default()); + self.sides_job = None; + self.shown_marks.borrow_mut().1.clear(); + return; + } + let (tx, rx) = channel(); + let (db, f, ctx) = (db.clone(), filter.clone(), ctx.clone()); + let spawned = std::thread::Builder::new() + .name("marks-sides".into()) + .spawn(move || { + let sides = crate::brilliant::player_sides( + &db, + &f, + &std::sync::atomic::AtomicBool::new(false), + ); + let _ = tx.send(sides); + ctx.request_repaint(); + }); + if spawned.is_ok() { + self.sides_job = Some((filter, rx)); + } + } + + /// The database the marks are checked against. + pub fn set_marks_db(&mut self, db: &Arc) { + if !self.marks_db.as_ref().is_some_and(|d| Arc::ptr_eq(d, db)) { + self.marks_db = Some(db.clone()); + } + } + + /// The table sorted by its «!!» column (the summary's «Sort»). + pub fn sort_marks_on(&mut self) { + self.marks_sort = true; + self.sort_by_marks(); + } + + /// The list by its marks (!! first), each group in the order of its numbers. + fn sort_by_marks(&mut self) { + let Some(index) = self.marks.clone() else { + return; + }; + let Ok(index) = index.lock() else { + return; + }; + let sides = &self.marks_sides.1; + // Only the entries of the games the database has there now (a deleted game's + // marks are not its successor's). + let current: std::collections::HashSet = match &self.marks_db { + Some(db) => index + .records() + .filter(|&r| crate::brilliant::current_entry(&index, db, r).is_some()) + .collect(), + None => std::collections::HashSet::new(), + }; + self.view + .sort_by_key(|&r| (index.rank(r, sides, &|r| current.contains(&r)), r)); + self.view_gen += 1; + } + + /// The marks of record `index` to show: those of the index if the record still has + /// the main line they were found in (checked once per record and index change). + fn shown_mark( + marks: &Option>>, + shown: &std::cell::RefCell<(u64, HashMap>)>, + sides: &crate::brilliant::Sides, + db: &Database, + record: u32, + ) -> Option { + let index = marks.as_ref()?.lock().ok()?; + let mut shown = shown.borrow_mut(); + if index.generation != shown.0 { + shown.1.clear(); + shown.0 = index.generation; + } + let entry = index.get(record)?.clone(); + drop(index); + shown + .1 + .entry(record) + .or_insert_with(|| { + let game = db.load_game(record as usize)?.game; + let line = game_review::GameAnalysis::new(&game, None).cache_key(); + (entry.line == line).then_some(entry) + }) + .clone() + .map(|e| { + let (w, b) = sides.of(record); + e.for_sides(w, b) + }) + } + + /// «!! Find great moves» (the button, Shift+A): a choice of records takes priority + /// over the filtered list. Both are owned snapshots: later changes in the table do + /// not change the request already sent to the library. + fn ask_search(&mut self, path: &Path, db: &Database, actions: &mut Vec) { + let selected = self.selected_games(); + let (records, about) = if selected.is_none() { + let about = if self.last_conditions.is_empty() { + tr("all games").to_owned() + } else { + trf( + "matching: {list}", + &[("list", &self.last_conditions.join(" · "))], + ) + }; + (self.view.clone(), about) + } else { + let mut records = self.marked.records(); + let (sort, ascending) = if self.blocked.is_some() { + self.sort + } else { + self.effective_sort() + }; + db.sort_records(&mut records, sort, ascending); + (records, String::new()) + }; + actions.push(LibraryAction::FindGreatMoves { + path: path.to_path_buf(), + records, + filter: self.form.filter(), + about, + selected, + }); + } + + /// «!! Find great moves»: the button, or Shift+A outside a field (a disabled button + /// says why, also over an empty list). + fn handle_find( + &mut self, + ui: &mut Ui, + path: &Path, + db: &Database, + actions: &mut Vec, + ) { + if !crate::platform::CAPS.great_moves { + return; + } + let typing = ui.ctx().egui_wants_keyboard_input(); + let shift_a = !typing + && !crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) + && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::A)); + if std::mem::take(&mut self.find_clicked) || shift_a { + match (self.pass.is_some(), self.search_blocked()) { + (false, None) => self.ask_search(path, db, actions), + (false, Some(why)) => actions.push(LibraryAction::Notice(why)), + (true, _) => {} + } + } + } + + /// How many games a search asked for now would take: the whole choice when there + /// is one, otherwise the filtered list. + fn search_len(&self) -> usize { + if self.marked.is_empty() { + self.view.len() + } else { + self.marked.len() + } + } + + /// The manual source and its hidden count, captured from the finished current view. + fn selected_games(&mut self) -> Option { + if self.marked.is_empty() { + return None; + } + let games = self.marked.len(); + let hidden = self.hidden_marked(); + Some(crate::brilliant::SelectedGames { games, hidden }) + } + + /// Why the search cannot start on the choice or the list shown, if it cannot. + fn search_blocked(&self) -> Option { + if let Some(why) = &self.engine_busy { + return Some(why.clone()); + } + if let Some(p) = self.pass.as_ref().filter(|p| !p.here) { + return Some(trf( + "Searching in «{db}»: {i} of {n}; stop it there", + &[("db", &p.name), ("i", &p.done), ("n", &p.total)], + )); + } + // Overflow is known without k and takes priority over a filter still running. + if self.marked.len() > crate::brilliant::LIMIT { + return Some(selected_limit_hint(self.marked.len())); + } + // A valid choice also waits: its hidden count is not known before this view. + if self.job.is_some() || self.shown.is_none() { + return Some( + tr(if self.marked.is_empty() { + "Wait: the games are still being filtered" + } else { + "Wait: counting how many selected games are hidden by the current filter" + }) + .to_owned(), + ); + } + match crate::brilliant::can_start(self.search_len()) { + Ok(()) => None, + Err(crate::brilliant::Blocked::NoGames) => { + Some(tr("No games match these conditions").to_owned()) + } + Err(crate::brilliant::Blocked::TooMany) if !self.marked.is_empty() => { + Some(selected_limit_hint(self.marked.len())) + } + Err(crate::brilliant::Blocked::TooMany) => Some(format!( + "{}\n{}", + tr("Filter the games down to 100 or fewer"), + trf("Now: {n}", &[("n", &grouped(self.view.len()))]) + )), + } + } + + /// Every row of the list chosen (Ctrl+A): the list's records only. + fn select_all(&mut self) { + let view = std::mem::take(&mut self.view); + self.mark(|m| m.extend(&view)); + self.view = view; + if self.selected.is_none() { + self.selected = self.view.first().map(|&i| i as usize); + } + } + + /// «New database from selected…»: the library opens the dialog (none while another + /// copy is written). + fn ask_copy(&mut self, path: &Path, actions: &mut Vec) { + if self.batch.is_some() || !crate::platform::CAPS.batch_copy { + return; + } + let (records, sort, ascending) = self.copy_request(); + actions.push(LibraryAction::CopySelection { + path: path.to_path_buf(), + records, + sort, + ascending, + hidden: self.hidden_marked(), + }); + } + + /// The chosen records for a copy, in the table's order once sorted by the copy. + fn copy_request(&self) -> (Vec, SortKey, bool) { + let (sort, ascending) = if self.blocked.is_some() { + self.sort + } else { + self.effective_sort() + }; + (self.marked.records(), sort, ascending) + } + + pub fn pane(&self) -> Pane { + self.pane + } + + /// The least width of the table with the narrow set of columns (§1): the "Move" + /// column instead of "â„–" when the list is a position's games. + pub fn table_min_width(&self, db: &Database, use_position: bool) -> f32 { + let first = if use_position { + MOVE_COL + } else { + number_col(db) + }; + first + 2.0 * ELO_COL + RESULT_COL + YEAR_COL + 2.0 * NAME_MIN + 6.0 * 8.0 + 10.0 + 16.0 + } + + /// The layout the window allows (§2.1). Narrowing closes the filters rather than + /// laying them over the table; widening docks the filters opened over it. + pub fn set_layout(&mut self, narrow_filters: bool, narrow_board: bool) { + // Called first in each frame: what asked for the filters is this frame's. + self.drawer_asked = false; + if narrow_filters && !self.narrow_filters { + self.drawer_open = false; + } + if !narrow_filters && self.narrow_filters && self.drawer_open { + // The filters opened over the list dock; opened over the board, they close + // and the board stays (beside the list now, or alone). + self.drawer_open = false; + if self.pane != Pane::Board { + self.pane = Pane::Filters; + } + } + self.narrow_filters = narrow_filters; + self.narrow_board = narrow_board; + } + + /// The filters open over the table: from where (under the header). + pub fn drawer(&self) -> Option { + (self.narrow_filters && self.drawer_open).then_some(self.drawer_top) + } + + /// A click elsewhere closes the filters over the list, unless that click asked for + /// them (a condition's chip). + pub fn close_drawer_on_click(&mut self) { + if !self.drawer_asked { + self.drawer_open = false; + } + } + + /// The board takes the place of the table (a narrow window). + pub fn board_alone(&self) -> bool { + self.narrow_board && self.pane == Pane::Board + } + + /// Escape in the library with no field typing: the filters over the table close, + /// then the board alone gives the place back to the table. + pub fn escape(&mut self) -> bool { + if self.board_alone() && self.board.is_busy() { + // A piece picked up on the board is put back first, as in a game. + self.board.drop_pick(); + true + } else if self.drawer().is_some() { + self.drawer_open = false; + true + } else if self.marked.len() >= 2 { + self.mark_cursor_only(); + true + } else if self.board_alone() { + self.pane = Pane::Hidden; + true + } else { + false + } + } + + /// Opens the filters: beside the table, or over it in a narrow window (over the + /// board alone too, which stays). + fn open_filters(&mut self) { + if self.narrow_filters { + self.drawer_open = true; + self.drawer_asked = true; + if !self.board_alone() { + self.pane = Pane::Filters; + } + } else { + self.pane = Pane::Filters; + } + } + + /// Shows the board with `line` played from `start` (a position from a game). + pub fn show_position( + &mut self, + start: shakmaty::Chess, + line: Vec, + flipped: bool, + ) { + self.board.set(start, line, flipped); + self.only_order = false; + self.pane = Pane::Board; + } + + /// Sort order in effect: a position without a chosen order sorts strongest first. + fn effective_sort(&self) -> (SortKey, bool) { + if self.board.is_set() && !self.sort_chosen { + (SortKey::AverageElo, false) + } else { + self.sort + } + } + + fn request(&self) -> Request { + let (sort, ascending) = self.effective_sort(); + let use_position = self.board.is_set(); + Request { + filter: self.form.filter(), + sort, + ascending, + base_sort: self.sort, + position: (use_position || self.pane == Pane::Board) + .then(|| (self.board.key(), self.board.query())), + use_position, + only_order: use_position && self.only_order, + } + } + + /// The search outcome for the board's current position, if the shown list has it. + fn board_outcome(&self) -> Option<&PositionOutcome> { + let shown = self.shown.as_ref()?; + let (key, query) = shown.position.as_ref()?; + let current = self.board.query(); + (*key == self.board.key() + && query.line == current.line + && shown.filter == self.form.filter()) + .then_some(self.outcome.as_deref()) + .flatten() + } + + /// Collects finished work and starts what the form asks for. + fn update(&mut self, db: &Arc, ctx: &egui::Context) { + let now = ctx.input(|i| i.time); + if let Some(job) = &self.job + && let Some(result) = job.work.poll() + { + let job = self.job.take().expect("job"); + if let Some(answer) = result { + let rereading = std::mem::take(&mut self.rereading); + let new_filter = !rereading + && self.shown.as_ref().is_none_or(|s| { + s.filter != job.request.filter + || s.use_position != job.request.use_position + || (job.request.use_position + && s.position.as_ref().map(|p| p.0) + != job.request.position.as_ref().map(|p| p.0)) + }); + if let (Some(out), Some(pos)) = (&answer.outcome, &job.request.position) { + let kept: usize = self.cache.values().map(|o| o.matches.len()).sum(); + if kept + out.matches.len() > CACHE_MATCHES { + self.cache.clear(); + } + self.cache.insert( + (filter_hash(&job.request.filter), position_id(pos)), + out.clone(), + ); + } + self.view = answer.view; + self.view_gen += 1; + if self.marks_sort { + self.sort_by_marks(); + } + self.outcome = answer.outcome; + self.in_order = answer.in_order; + self.blocked = answer.blocked; + self.shown = Some(job.request); + // A cursor that left the list is cleared, so Enter cannot open a game + // the user does not see. The marked record itself stays, also when it + // is the only one: the search and copy include hidden chosen records. + if new_filter { + self.clear_hidden_cursor(); + } + if new_filter { + // The user looks at the result of the new filter from its top. + self.scroll_to_top = true; + } else if self.selected.is_some() { + self.scroll_to_selected = true; + } + } + } + let wanted = self.request(); + let pending = self.job.as_ref().map(|j| &j.request); + let current = pending.or(self.shown.as_ref()); + if current != Some(&wanted) { + let wait = self.typed_at + DEBOUNCE - now; + if wait > 0.0 && self.shown.is_some() { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } else { + self.start(db, wanted, now, ctx); + } + } + if let Some(j) = &self.suggest_job + && let Ok((list, total)) = j.rx.try_recv() + { + let j = self.suggest_job.take().expect("suggest job"); + self.suggestions = Some(Suggestions { + field: j.field, + query: j.query, + list, + total, + highlighted: None, + }); + } + self.update_booster(db, now, ctx); + if self.job.is_some() || self.suggest_job.is_some() || self.booster.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + } + + /// Builds the search index in the background when the board is in use and the + /// base lacks something (`Base::prepare`); searches meanwhile run without it. + fn update_booster(&mut self, db: &Arc, now: f64, ctx: &egui::Context) { + if let Some((b, _)) = &self.booster + && let Some(result) = b.poll() + { + self.booster = None; + self.booster_failed = result != Some(true); + } + let wanted = self.pane == Pane::Board || self.board.is_set(); + if !wanted + || self.booster.is_some() + || self.booster_failed + || !db.as_chessbase().is_some_and(|b| b.prepare_wanted()) + { + return; + } + let work = db.as_chessbase().map_or(0, |b| b.prepare_work()); + let db = db.clone(); + let job = Background::spawn(ctx, now, move |progress, cancel| { + match db.as_chessbase()?.prepare(progress, cancel) { + Ok(true) => Some(true), + Ok(false) => None, + Err(e) => { + eprintln!("search index: {e}"); + Some(false) + } + } + }); + self.booster = job.map(|j| (j, work)); + } + + fn start(&mut self, db: &Arc, request: Request, now: f64, ctx: &egui::Context) { + // Dropping the old job cancels it. + self.job = None; + let cached = request + .position + .as_ref() + .and_then(|pos| { + self.cache + .get(&(filter_hash(&request.filter), position_id(pos))) + }) + .cloned(); + // A PGN database without the memory for its position table: the list by the + // filters only, and the board says why (checked once per request). + let blocked = request + .position + .as_ref() + .filter(|_| cached.is_none()) + .and_then(|_| db.positions_blocked()); + let (db, req) = (db.clone(), request.clone()); + let work = Background::spawn(ctx, now, move |progress, cancel| { + if blocked.is_some() { + let (sort, ascending) = req.base_sort; + return Some(Answer { + view: db.query(&req.filter, sort, ascending, progress, cancel)?, + outcome: None, + in_order: None, + blocked, + }); + } + let mut outcome = cached; + if let Some((_, query)) = &req.position + && outcome.is_none() + { + let candidates = if req.filter == Filter::default() { + None + } else { + let ignore = AtomicUsize::new(0); + Some(db.query(&req.filter, SortKey::Number, true, &ignore, cancel)?) + }; + let found = db.search_position(candidates.as_deref(), query, progress, cancel)?; + outcome = Some(Arc::new(found)); + } + let mut in_order = None; + let view = if req.use_position { + let out = outcome.as_ref()?; + let ordered = req.position.as_ref().is_some_and(|(_, q)| q.line.is_some()); + if ordered { + let same = out.matches.iter().filter(|m| m.same_order).count(); + in_order = Some((same, out.matches.len())); + } + let mut v: Vec = out + .matches + .iter() + .filter(|m| !req.only_order || m.same_order) + .map(|m| m.index) + .collect(); + db.sort_records(&mut v, req.sort, req.ascending); + v + } else { + db.query(&req.filter, req.sort, req.ascending, progress, cancel)? + }; + Some(Answer { + view, + outcome, + in_order, + blocked: None, + }) + }); + if let Some(work) = work { + self.job = Some(Job { request, work }); + } + } + + fn suggest(&mut self, db: &Arc, field: NameField, query: String) { + if query.trim().chars().count() < 2 { + self.suggestions = None; + self.suggest_job = None; + return; + } + let (tx, rx) = channel(); + let (db, q) = (db.clone(), query.clone()); + let spawned = std::thread::Builder::new() + .name("db-suggest".into()) + .spawn(move || { + let r = match field { + NameField::Event => db.suggest_events(&q, SUGGESTIONS), + _ => db.suggest_players(&q, SUGGESTIONS), + }; + let _ = tx.send(r); + }); + if spawned.is_ok() { + self.suggest_job = Some(SuggestJob { field, query, rx }); + } + } + + /// Progress of a slow pass (0–1), `None` when nothing slow is running. + fn slow_progress(&self, now: f64, total: usize) -> Option { + let j = self.job.as_ref()?; + (now - j.work.started > SLOW) + .then(|| (j.work.progress() as f32 / total.max(1) as f32).min(1.0)) + } + + /// The search board (an `egui::Panel` on the right of the library). + pub fn board_panel( + &mut self, + ui: &mut Ui, + db: &Arc, + settings: &Settings, + actions: &mut Vec, + ) { + self.update(db, ui.ctx()); + let total = db.len(); + // A PGN's first search builds its position table: the progress counts its games. + self.board.preparing = !db.positions_ready(); + self.board.unavailable = self.blocked.is_some(); + let counting = self + .job + .as_ref() + .map(|j| (j.work.progress() as f32 / total.max(1) as f32).min(1.0)); + if let Some((b, work)) = &self.booster { + let p = (b.progress() as f32 / (*work).max(1) as f32).min(1.0); + ui.horizontal(|ui| { + ui.label( + RichText::new(trf( + "Speeding up search in this database (once)… {p} %", + &[("p", &format!("{:.0}", p * 100.0))], + )) + .weak(), + ) + .on_hover_text(tr( + "An index for fast position search is built once and kept in the cache. Searching works meanwhile, only slower.", + )); + }); + } + if let Some(need) = self.blocked { + let free = chess_import::memory::available().unwrap_or(0); + let missing = (need + (256 << 20)).saturating_sub(free) / 1_000_000; + ui.label( + RichText::new(trf( + "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", + &[("n", &missing.max(1))], + )) + .color(ui.visuals().warn_fg_color), + ); + if ui.button(tr("Retry")).clicked() { + // The list is found anew; the memory is looked at again. + self.shown = None; + self.blocked = None; + } + } + let outcome = self.board_outcome().cloned(); + let mut events = Vec::new(); + self.board.keys(ui.ctx(), outcome.as_ref(), &mut events); + events.extend(self.board.panel( + ui, + settings, + outcome.as_ref(), + counting, + self.table_hover, + self.books, + )); + for e in events { + match e { + // A new position starts from the top of its list. + BoardEvent::Changed => self.scroll_to_top = true, + BoardEvent::Sound(s) => actions.push(LibraryAction::Sound(s)), + BoardEvent::CopyText(t, m) => actions.push(LibraryAction::CopyText(t, m)), + BoardEvent::OpenAsGame(pgn) => actions.push(LibraryAction::OpenPgn(pgn)), + } + } + if !self.board.is_set() { + self.only_order = false; + } + } + + /// The quick search of the header (§9.2): words found in a player, the tournament, + /// the annotator, the ECO code or the date; with the panel and the position. + fn search_field(&mut self, ui: &mut Ui, now: f64, width: f32) { + // The × has its place also when there is nothing to clear: the field stays put. + if self.form.search.is_empty() { + ui.add_space(20.0); + } else if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Clear")) + .clicked() + { + self.form.search.clear(); + self.typed_at = f64::NEG_INFINITY; + } + let resp = ui + .add( + egui::TextEdit::singleline(&mut self.form.search) + .hint_text(if width < 200.0 { + tr("ðŸ”� Search") + } else { + tr("ðŸ”� Search: player, event, ECO, year") + }) + .desired_width(width), + ) + .on_hover_text(if width < 200.0 { + format!( + "{}\n{}", + tr("ðŸ”� Search: player, event, ECO, year"), + tr("Ctrl+F; again — the filters") + ) + } else { + tr("Ctrl+F; again — the filters").to_owned() + }); + if resp.changed() { + self.typed_at = now; + } + // Escape in a non-empty field clears it (egui has just taken the focus away); + // in an empty one it leaves the field for the table. + if resp.lost_focus() + && ui.input(|i| i.key_pressed(egui::Key::Escape)) + && !self.form.search.is_empty() + { + self.form.search.clear(); + self.typed_at = f64::NEG_INFINITY; + resp.request_focus(); + } + if std::mem::take(&mut self.focus_search) { + resp.request_focus(); + // The text selected: typing replaces it. + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), resp.id) { + let range = egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(self.form.search.chars().count()), + ); + state.cursor.set_char_range(Some(range)); + state.store(ui.ctx(), resp.id); + } + } + self.search_focused = resp.has_focus(); + } + + /// The pane switch `[Filters | Board]`; a click on the shown pane hides it. + fn pane_switch(&mut self, ui: &mut Ui) { + let active = self.form.active(); + let filters_shown = if self.narrow_filters { + self.drawer_open + } else { + self.pane == Pane::Filters + }; + let filters = if active > 0 && !filters_shown { + trf("Filters ({n})", &[("n", &active)]) + } else { + tr("Filters").to_string() + }; + let board = if self.board.is_set() && self.pane != Pane::Board { + format!("{} •", tr("Board")) + } else { + tr("Board").to_string() + }; + // Right to left: the board segment first. + ui.spacing_mut().item_spacing.x = 0.0; + for (pane, label, hint, on) in [ + ( + Pane::Board, + board, + tr("Find games by position: play moves on the board (Ctrl+B)"), + self.pane == Pane::Board, + ), + ( + Pane::Filters, + filters, + tr("Filters: players, tournament, years, rating… (Ctrl+F twice)"), + filters_shown, + ), + ] { + // The search by position is not in every version. + if pane == Pane::Board && !crate::platform::CAPS.reference { + continue; + } + let hint = if on { tr("Hide the panel") } else { hint }; + if ui.selectable_label(on, label).on_hover_text(hint).clicked() { + match (pane, on) { + (Pane::Filters, false) => self.open_filters(), + (Pane::Filters, true) if self.narrow_filters => self.drawer_open = false, + (_, true) => self.pane = Pane::Hidden, + (_, false) => { + self.pane = pane; + self.drawer_open = false; + } + } + } + } + } + + /// The conditions in force, each removable; a click on one opens its pane. + fn conditions(&self, settings: &Settings) -> Vec { + let f = &self.form; + let mut out = Vec::new(); + if self.board.is_set() { + let text = if self.only_order { + trf( + "Moves: {line} (this order)", + &[("line", &self.board.chip_text())], + ) + } else { + trf("Position: {line}", &[("line", &self.board.chip_text())]) + }; + let blocked = self.blocked.is_some(); + out.push(Condition { + text: if blocked { format!("{text} âš ") } else { text }, + pane: Pane::Board, + clear: Clear::Position, + hint: blocked + .then(|| tr("Not applied: not enough memory for position search").to_string()), + mini: Some(( + self.board.position(), + self.board.flipped, + settings.board_theme, + settings.piece_set, + )), + }); + } + if !f.search.trim().is_empty() { + out.push(Condition { + text: format!("{}: {}", tr("Search"), f.search.trim()), + pane: self.pane, + clear: Clear::Search, + hint: None, + mini: None, + }); + } + let side = match f.side { + Side::White => format!(" · {}", tr("as White")), + Side::Black => format!(" · {}", tr("as Black")), + Side::Any => String::new(), + }; + let mut add = |set: bool, text: String, clear: Clear| { + if set { + out.push(Condition { + text, + pane: Pane::Filters, + clear, + hint: None, + mini: None, + }); + } + }; + add( + f.player.is_set(), + format!("{}: {}{side}", tr("Player"), f.player.text.trim()), + Clear::Player, + ); + add( + f.opponent.is_set(), + format!("{}: {}", tr("Opponent"), f.opponent.text.trim()), + Clear::Opponent, + ); + add( + f.event.is_set(), + format!("{}: {}", tr("Tournament"), f.event.text.trim()), + Clear::Event, + ); + add( + !f.annotator.trim().is_empty(), + format!("{}: {}", tr("Annotator"), f.annotator.trim()), + Clear::Annotator, + ); + add( + !f.year_from.trim().is_empty() || !f.year_to.trim().is_empty(), + format!( + "{}: {}–{}", + tr("Years"), + f.year_from.trim(), + f.year_to.trim() + ), + Clear::Years, + ); + add( + !f.elo_min.trim().is_empty(), + format!("Elo ≥ {}", f.elo_min.trim()), + Clear::Elo, + ); + add( + !f.outcomes.is_empty(), + tr("Result").to_string(), + Clear::Result, + ); + add( + !f.eco.trim().is_empty(), + format!("ECO {}", f.eco.trim()), + Clear::Eco, + ); + add( + !f.moves_from.trim().is_empty() || !f.moves_to.trim().is_empty(), + format!( + "{}: {}–{}", + tr("Length"), + f.moves_from.trim(), + f.moves_to.trim() + ), + Clear::Length, + ); + add( + f.with_comments, + tr("with comments").to_string(), + Clear::Comments, + ); + add( + f.with_variations, + tr("with variations").to_string(), + Clear::Variations, + ); + add(f.hide_texts, tr("no texts").to_string(), Clear::Texts); + out + } + + fn clear(&mut self, what: Clear) { + let f = &mut self.form; + match what { + Clear::Position => { + self.board = SearchBoard::new(); + self.only_order = false; + } + Clear::Search => f.search.clear(), + Clear::Player => { + f.player = NameFilter::default(); + f.side = Side::Any; + self.typed[0].clear(); + } + Clear::Opponent => { + f.opponent = NameFilter::default(); + self.typed[1].clear(); + } + Clear::Event => { + f.event = NameFilter::default(); + self.typed[2].clear(); + } + Clear::Annotator => f.annotator.clear(), + Clear::Years => { + f.year_from.clear(); + f.year_to.clear(); + } + Clear::Elo => f.elo_min.clear(), + Clear::Result => f.outcomes.clear(), + Clear::Eco => f.eco.clear(), + Clear::Length => { + f.moves_from.clear(); + f.moves_to.clear(); + } + Clear::Comments => f.with_comments = false, + Clear::Variations => f.with_variations = false, + Clear::Texts => f.hide_texts = false, + } + self.typed_at = f64::NEG_INFINITY; + } + + /// The line of conditions: position and filters, each with ×; on the right, how + /// many games reached the position in the board's move order. + fn chips(&mut self, ui: &mut Ui, settings: &Settings) { + let conditions = self.conditions(settings); + self.last_conditions = conditions.iter().map(|c| c.text.clone()).collect(); + let mut clear = None; + let mut goto = None; + let mut toggle_order = false; + let chosen = self.marked.len(); + let hidden = if chosen >= 2 { self.hidden_marked() } else { 0 }; + let batch = self.batch.clone(); + let batch_error = self.batch_error.clone(); + let mut close_error = false; + let mut clear_marked = false; + let mut cancel_batch = false; + ui.horizontal(|ui| { + ui.set_min_height(22.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // Right to left (docs/design/task-27-brilliant-search-2026-11-27.md §4.1): + // the slot of the far right, the move order, the choice or its copy, the + // conditions. The far right slot keeps one width whatever it shows, so what + // stands left of it does not move when it changes. + self.right_slot(ui); + if let Some((same, all)) = self.in_order + && self.board.is_set() + && (same < all || self.only_order) + { + { + let link = if self.only_order { + tr("all move orders") + } else { + tr("only this order") + }; + if ui + .link(link) + .on_hover_text(tr("Show only the games whose moves went exactly as on your board. Otherwise all games that reached this position by any path are shown.")) + .clicked() + { + toggle_order = true; + } + ui.label( + RichText::new(trf( + "in this move order: {n} of {m} ·", + &[("n", &grouped(same)), ("m", &grouped(all))], + )) + .weak() + .size(12.0), + ); + } + } + // The choice, or the copy being written, in the same place (§42.3). + if batch.is_some() || batch_error.is_some() || chosen >= 2 { + ui.add_space(SLOT_GAP); + } + if let (None, Some(e)) = (&batch, &batch_error) { + if crate::widgets::small_close_button(ui).clicked() { + close_error = true; + } + let width = (ui.available_width() - 140.0).max(80.0); + ui.scope(|ui| { + ui.set_max_width(width); + ui.add( + egui::Label::new(RichText::new(e).color(ui.visuals().error_fg_color)) + .truncate(), + ) + .on_hover_text(e); + }); + } else if let Some(b) = &batch { + if b.cancelling { + ui.spinner(); + ui.label(RichText::new(tr("Cancelling…")).weak()); + } else { + if ui.link(tr("Cancel")).clicked() { + cancel_batch = true; + } + let fraction = b.done as f32 / b.total.max(1) as f32; + ui.add(egui::ProgressBar::new(fraction).desired_width(80.0).desired_height(8.0)); + ui.label( + RichText::new(trf( + "Writing to «{name}»: {i} of {n}", + &[("name", &b.name), ("i", &grouped(b.done)), ("n", &grouped(b.total))], + )) + .weak(), + ); + } + } else if chosen >= 2 { + if ui + .link(tr("Deselect")) + .on_hover_text(tr("Clear the selection (Esc)")) + .clicked() + { + clear_marked = true; + } + let full = if hidden > 0 { + trf( + "Selected: {n} ({k} hidden by the filter)", + &[("n", &grouped(chosen)), ("k", &grouped(hidden))], + ) + } else { + trf("Selected: {n}", &[("n", &grouped(chosen))]) + }; + // Short in a narrow line: the conditions keep their 140 px. + let short = ui.available_width() + < 140.0 + ui.fonts_mut(|f| { + f.layout_no_wrap( + full.clone(), + egui::TextStyle::Body.resolve(ui.style()), + Color32::WHITE, + ) + .size() + .x + }) + 16.0; + let text = if short { format!("{} ·", grouped(chosen)) } else { format!("{full} ·") }; + let label = ui.label(text); + if hidden > 0 { + label.on_hover_text(format!( + "{full}\n{}", + tr("Games hidden by the filter will be copied too. Esc clears the selection") + )); + } else if short { + label.on_hover_text(full); + } + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if conditions.is_empty() { + ui.label(RichText::new(tr("No conditions: all games are shown")).weak()); + } + for (n, c) in conditions.iter().enumerate() { + // No room for another chip: the rest in a tooltip. + if ui.available_width() < 140.0 && n + 1 < conditions.len() { + let rest: Vec<&str> = + conditions[n..].iter().map(|c| c.text.as_str()).collect(); + if ui + .link(trf("+{n} more", &[("n", &rest.len())])) + .on_hover_text(rest.join("\n")) + .clicked() + { + goto = Some(Pane::Filters); + } + break; + } + let (open, remove) = chip(ui, c); + if open && c.clear == Clear::Search { + self.focus_search = true; + } else if open { + goto = Some(c.pane); + } + if remove { + clear = Some(c.clear); + } + } + }); + }); + }); + if toggle_order { + self.only_order = !self.only_order; + } + if clear_marked { + self.mark_cursor_only(); + } + if close_error { + self.batch_error = None; + } + if cancel_batch { + self.cancel_batch = true; + } + if let Some(c) = clear { + self.clear(c); + } + match goto { + Some(Pane::Filters) => self.open_filters(), + Some(p) => self.pane = p, + None => {} + } + } + + /// The far right slot of the conditions line: «!! Find great moves», or the search + /// under way with «Stop», or why it stopped (task 27 §4.1–4.2). Its width is that of + /// its longest form for the line's width, whatever it shows: what stands left of it + /// never moves. + fn right_slot(&mut self, ui: &mut Ui) { + if !crate::platform::CAPS.great_moves { + return; + } + let line = ui.available_width(); + let form = if line >= 1100.0 { + 2 + } else if line >= 800.0 { + 1 + } else { + 0 + }; + let body = egui::TextStyle::Body.resolve(ui.style()); + let width = |text: &str| { + ui.fonts_mut(|f| { + f.layout_no_wrap(text.to_owned(), body.clone(), Color32::WHITE) + .size() + .x + }) + }; + let progress_text = |i: usize, n: usize, left: &str| match form { + 2 => format!( + "!! {}", + trf( + "Analysed {i} of {n} · ≈ {time} left", + &[("i", &i), ("n", &n), ("time", &left)] + ) + ), + 1 => format!( + "!! {} · ≈ {left}", + trf("{i} of {n}", &[("i", &i), ("n", &n)]) + ), + _ => format!("!! {}", trf("{i} of {n}", &[("i", &i), ("n", &n)])), + }; + let bar = if form == 2 { 90.0 } else { 60.0 }; + let pad = 2.0 * ui.spacing().button_padding.x; + let gap = ui.spacing().item_spacing.x; + let button_text = if form == 0 { + tr("!! Find moves") + } else { + tr("!! Find great moves") + }; + let longest = width(&progress_text( + 100, + 100, + &crate::review::format_duration(59.0 * 60.0), + )) + gap + + bar + + gap + + width(tr("Stop")) + + pad; + let slot = longest.max(width(button_text) + pad); + let pass = self.pass.clone(); + let selected = if self.job.is_none() && self.shown.is_some() { + self.selected_games() + } else { + None + }; + let blocked = self.search_blocked(); + let error = self.pass_error.clone(); + let mut find = false; + let mut stop = false; + let mut close_error = false; + ui.allocate_ui_with_layout( + vec2(slot, 22.0), + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + ui.set_min_width(slot); + match (&pass, &error) { + (Some(p), _) => { + if p.stopping { + ui.spinner(); + ui.label(RichText::new(tr("Stopping…")).weak()); + } else { + if ui + .small_button(tr("Stop")) + .on_hover_text(tr("Stop the search; the reviewed games are kept")) + .clicked() + { + stop = true; + } + ui.add( + egui::ProgressBar::new(p.done as f32 / p.total.max(1) as f32) + .desired_width(bar) + .desired_height(8.0), + ); + let left = crate::review::format_duration(p.left_secs); + let text = if p.here { + progress_text(p.done, p.total, &left) + } else { + format!( + "!! {}", + trf( + "In «{db}»: {i} of {n}", + &[("db", &p.name), ("i", &p.done), ("n", &p.total)] + ) + ) + }; + let mut hint = String::new(); + if let Some(selected) = p.selected { + if selected.hidden > 0 { + hint.push_str(&trf( + "Source: selected {games}; hidden by the filter at start: {k}.", + &[ + ("games", &crate::i18n::games(selected.games)), + ("k", &grouped(selected.hidden)), + ], + )); + } else { + hint.push_str(&trf( + "Source: selected {games}.", + &[("games", &crate::i18n::games(selected.games))], + )); + } + hint.push('\n'); + hint.push_str(tr( + "Selection and filter changes do not change this pass.", + )); + hint.push('\n'); + } + hint.push_str(&trf( + "Analysed {i} of {n} · ≈ {time} left", + &[("i", &p.done), ("n", &p.total), ("time", &left)], + )); + ui.add(egui::Label::new(RichText::new(text).weak()).truncate()) + .on_hover_text(hint); + } + } + (None, Some(e)) => { + if crate::widgets::small_close_button(ui).clicked() { + close_error = true; + } + ui.add( + egui::Label::new(RichText::new(e).color(ui.visuals().error_fg_color)) + .truncate(), + ) + .on_hover_text(e); + } + (None, None) => { + let teal = crate::notation::assessment_text_color( + chess_core::Nag(3), + ui.visuals().dark_mode, + ) + .unwrap_or(Color32::WHITE); + let mut job = egui::text::LayoutJob::default(); + let rest = button_text.strip_prefix("!! ").unwrap_or(button_text); + let bold = egui::FontId::new(13.0, egui::FontFamily::Name("bold".into())); + let bold = if ui.fonts_mut(|f| f.families().contains(&bold.family)) { + bold + } else { + body.clone() + }; + job.append("!! ", 0.0, egui::TextFormat::simple(bold, teal)); + // The button's own text colour (it lightens under the pointer). + job.append( + rest, + 0.0, + egui::TextFormat::simple(body.clone(), Color32::PLACEHOLDER), + ); + let enabled = blocked.is_none(); + let r = ui.add_enabled(enabled, egui::Button::new(job).small()); + let r = match &blocked { + Some(why) => r.on_disabled_hover_text(why), + None => r.on_hover_text(match selected { + Some(selected) => selected_search_hint(selected), + None => trf( + "Review {games} with the engine and mark the !! and ! moves found (Shift+A)", + &[("games", &crate::i18n::games(self.search_len()))], + ), + }), + }; + if r.clicked() { + find = true; + } + } + } + }, + ); + ui.add_space(SLOT_GAP); + if find { + self.find_clicked = true; + } + if stop { + self.stop_pass = true; + } + if close_error { + self.pass_error = None; + } + } + + /// The filter panel (an `egui::Panel` on the right of the library). + pub fn panel(&mut self, ui: &mut Ui, db: &Arc) { + self.update(db, ui.ctx()); + let active = self.form.active(); + egui::Panel::bottom("filters_footer") + .show_separator_line(true) + .show(ui, |ui| { + ui.add_space(6.0); + let label = if active > 0 { + trf("Reset filters ({n})", &[("n", &active)]) + } else { + tr("Reset filters").to_string() + }; + if ui + .add_enabled(active > 0, egui::Button::new(label)) + .on_hover_text("Ctrl+Shift+Backspace") + .clicked() + { + self.reset(); + } + ui.add_space(4.0); + }); + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 6.0; + self.players_group(ui, db); + ui.add_space(4.0); + self.event_group(ui, db); + ui.add_space(4.0); + self.game_group(ui); + ui.add_space(4.0); + self.annotations_group(ui, db.texts() > 0); + }); + } + + /// Clears the conditions of the panel; the quick search and the position stay. + fn reset(&mut self) { + self.form = Form { + search: std::mem::take(&mut self.form.search), + ..Form::default() + }; + self.suggestions = None; + self.typed = Default::default(); + } + + fn group_header(ui: &mut Ui, title: &str, count: usize) { + let text = if count > 0 { + format!("{title} ({count})") + } else { + title.to_string() + }; + ui.label(RichText::new(text).strong()); + } + + fn players_group(&mut self, ui: &mut Ui, db: &Arc) { + let count = + usize::from(self.form.player.is_set()) + usize::from(self.form.opponent.is_set()); + Self::group_header(ui, tr("Players"), count); + self.name_field(ui, db, NameField::Player, tr("Player")); + let player_set = self.form.player.is_set(); + ui.add_enabled_ui(player_set, |ui| { + // Wrapped: longer words (French, Spanish) do not widen the panel. + ui.horizontal_wrapped(|ui| { + for (side, label) in [ + (Side::Any, tr("either colour")), + (Side::White, tr("as White")), + (Side::Black, tr("as Black")), + ] { + ui.selectable_value(&mut self.form.side, side, label); + } + }) + .response + .on_disabled_hover_text(tr("Enter a player first")); + }); + // Preparing against the player: with the name picked from the list, else the + // dialog offers the names that match the text (opponent-prep.md §2.1). + if player_set { + let label = match self.form.player.exact { + Some(_) => trf( + "♟ Prepare against {name}…", + &[("name", &self.form.player.text)], + ), + None => tr("♟ Prepare against an opponent…").to_owned(), + }; + if ui + .add(egui::Button::new(label).truncate()) + .on_hover_text(tr( + "The player's openings by colour, with names, and the opening errors the engine finds (Ctrl+Shift+P)", + )) + .clicked() + { + self.prepare = self.prep_entry(); + } + } + self.name_field(ui, db, NameField::Opponent, tr("Opponent")); + } + + /// «Prepare against…» for the player of the filter: the name picked from the list + /// (or the text typed) and the colour of the filter. + pub fn prep_entry(&self) -> Option { + self.form.player.is_set().then(|| PrepEntry { + query: self.form.player.text.trim().to_owned(), + exact: self.form.player.exact, + side: self.form.side, + }) + } + + fn event_group(&mut self, ui: &mut Ui, db: &Arc) { + let count = usize::from(self.form.event.is_set()) + + usize::from(!self.form.annotator.trim().is_empty()); + Self::group_header(ui, tr("Tournament"), count); + self.name_field(ui, db, NameField::Event, tr("Tournament or place")); + ui.label(tr("Annotator")); + let r = text_field(ui, &mut self.form.annotator, "", true); + if r.changed() { + self.typed_at = ui.input(|i| i.time); + } + } + + fn game_group(&mut self, ui: &mut Ui) { + let f = &self.form; + let count = usize::from(!f.year_from.trim().is_empty() || !f.year_to.trim().is_empty()) + + usize::from(!f.elo_min.trim().is_empty()) + + usize::from(!f.outcomes.is_empty()) + + usize::from(!f.eco.trim().is_empty()) + + usize::from(!f.moves_from.trim().is_empty() || !f.moves_to.trim().is_empty()); + Self::group_header(ui, tr("Game"), count); + let now = ui.input(|i| i.time); + let mut typed = false; + + // One grid (§2.6): captions in a column as wide as the longest of them, the + // fields from one edge to one edge; "from – to" and Elo with its rule in halves. + let font = egui::TextStyle::Body.resolve(ui.style()); + let label_w = [tr("Years"), tr("Elo from"), tr("Moves"), "ECO"] + .iter() + .map(|t| { + ui.painter() + .layout_no_wrap((*t).to_string(), font.clone(), Color32::WHITE) + .size() + .x + }) + .fold(0.0_f32, f32::max) + .ceil(); + let fields = (ui.available_width() - label_w - 8.0 - CLEAR_SLOT).floor(); + let half = ((fields - DASH - 8.0) / 2.0).floor().max(40.0); + + let years_ok = { + let a = number(&self.form.year_from, 1..=2100); + let b = number(&self.form.year_to, 1..=2100); + match (a, b) { + (Ok(Some(a)), Ok(Some(b))) => (a <= b, a <= b), + (a, b) => (a.is_ok(), b.is_ok()), + } + }; + form_row(ui, label_w, tr("Years"), |ui| { + typed |= number_field(ui, &mut self.form.year_from, "", years_ok.0, half).changed(); + dash(ui, "–"); + typed |= number_field(ui, &mut self.form.year_to, "", years_ok.1, half).changed(); + }); + + form_row(ui, label_w, tr("Elo from"), |ui| { + let ok = number(&self.form.elo_min, 1..=3500).is_ok(); + typed |= number_field(ui, &mut self.form.elo_min, "", ok, half).changed(); + dash(ui, ""); + let player_set = self.form.player.is_set(); + if !player_set && self.form.elo_rule == EloRule::Opponent { + self.form.elo_rule = EloRule::Both; + } + let label = |r: EloRule| match r { + EloRule::Both => tr("both"), + EloRule::Either => tr("either"), + EloRule::Average => tr("average"), + EloRule::Opponent => tr("opponent"), + }; + egui::ComboBox::from_id_salt("elo_rule") + .selected_text(label(self.form.elo_rule)) + .width(half) + .show_ui(ui, |ui| { + let mut rules = vec![EloRule::Both, EloRule::Either, EloRule::Average]; + if player_set { + rules.push(EloRule::Opponent); + } + for r in rules { + ui.selectable_value(&mut self.form.elo_rule, r, label(r)); + } + }); + }); + + let moves_ok = { + let a = number(&self.form.moves_from, 0..=999); + let b = number(&self.form.moves_to, 0..=999); + match (a, b) { + (Ok(Some(a)), Ok(Some(b))) => (a <= b, a <= b), + (a, b) => (a.is_ok(), b.is_ok()), + } + }; + form_row(ui, label_w, tr("Moves"), |ui| { + typed |= number_field(ui, &mut self.form.moves_from, "", moves_ok.0, half).changed(); + dash(ui, "–"); + typed |= number_field(ui, &mut self.form.moves_to, "", moves_ok.1, half).changed(); + }); + + form_row(ui, label_w, "ECO", |ui| { + let ok = self.form.eco.trim().is_empty() || parse_eco(&self.form.eco).is_some(); + let r = text_field(ui, &mut self.form.eco, tr("B90, B9 or C60-C99"), ok); + let r = if ok { + r + } else { + r.on_hover_text(tr( + "A code (B90), a prefix (B9) or a range (C60-C99), separated by commas", + )) + }; + typed |= r.changed(); + }); + + ui.label(tr("Result")); + let relative = self.form.player.is_set(); + if relative != self.form.relative_outcomes { + // "1-0" and "Win" mean different things: do not carry one over as the other. + self.form.relative_outcomes = relative; + self.form.outcomes.clear(); + } + ui.horizontal_wrapped(|ui| { + let buttons: [(Outcome, &str); 4] = if relative { + [ + (Outcome::WhiteWins, tr("Win")), + (Outcome::Draw, tr("Draw")), + (Outcome::BlackWins, tr("Loss")), + (Outcome::Unknown, "*"), + ] + } else { + [ + (Outcome::WhiteWins, "1-0"), + (Outcome::Draw, "½-½"), + (Outcome::BlackWins, "0-1"), + (Outcome::Unknown, "*"), + ] + }; + for (o, label) in buttons { + let on = self.form.outcomes.contains(&o); + let text = if on { + RichText::new(label).strong() + } else { + RichText::new(label) + }; + if ui.selectable_label(on, text).clicked() { + if on { + self.form.outcomes.retain(|x| *x != o); + } else { + self.form.outcomes.push(o); + } + } + } + }); + if typed { + self.typed_at = now; + } + } + + fn annotations_group(&mut self, ui: &mut Ui, texts: bool) { + let f = &self.form; + let count = usize::from(f.with_comments) + + usize::from(f.with_variations) + + usize::from(f.hide_texts); + Self::group_header(ui, tr("Annotations"), count); + ui.checkbox(&mut self.form.with_comments, tr("with comments")); + ui.checkbox(&mut self.form.with_variations, tr("with variations")); + // Only a database with guiding texts has the choice (§9.4). + if texts { + let mut show_texts = !self.form.hide_texts; + ui.checkbox(&mut show_texts, tr("show texts")) + .on_hover_text(tr("Guiding texts of the database; left out by any condition on players, dates, ratings, results or moves")); + self.form.hide_texts = !show_texts; + } + } + + /// A name field with suggestions; picking one filters by exactly that name. + fn name_field(&mut self, ui: &mut Ui, db: &Arc, field: NameField, caption: &str) { + let slot = field as usize; + let value = match field { + NameField::Player => &mut self.form.player, + NameField::Opponent => &mut self.form.opponent, + NameField::Event => &mut self.form.event, + }; + // "=" on the caption's line: the field itself does not move when a name is picked. + ui.horizontal(|ui| { + ui.label(caption); + if value.exact.is_some() { + ui.label(RichText::new("=").strong()).on_hover_text(tr( + "Exactly this name; edit the text to search by words again", + )); + } + }); + let mut picked_this_frame = None; + let resp = ui + .horizontal(|ui| { + let r = text_field(ui, &mut value.text, "", true); + if field == NameField::Player && std::mem::take(&mut self.focus_player) { + r.request_focus(); + // Select the text so typing replaces it. + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { + let range = egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(value.text.chars().count()), + ); + state.cursor.set_char_range(Some(range)); + state.store(ui.ctx(), r.id); + } + } + r + }) + .inner; + let now = ui.input(|i| i.time); + if resp.changed() { + value.exact = None; + self.typed_at = now; + } + let text = value.text.clone(); + let typing = self.typed[slot] != text; + if typing { + self.typed[slot] = text.clone(); + if resp.has_focus() { + self.suggest(db, field, text.clone()); + } + } + // A click on the list takes the focus from the field before the click is + // over: the list stays open while the pointer is on it. + let mine = self.suggestions.as_ref().is_some_and(|s| s.field == field); + let keep = resp.has_focus() || (mine && self.pointer_on_list); + let open = keep + && self + .suggestions + .as_ref() + .is_some_and(|s| s.field == field && s.query == text && !s.list.is_empty()); + if !open { + if mine && !keep { + self.suggestions = None; + self.pointer_on_list = false; + } + return; + } + // Keyboard in the list: arrows move, Enter picks, Escape closes. + let (down, up, esc) = ui.input_mut(|i| { + ( + i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown), + i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp), + i.consume_key(egui::Modifiers::NONE, egui::Key::Escape), + ) + }); + let s = self.suggestions.as_mut().expect("open list"); + let n = s.list.len(); + if down { + s.highlighted = Some(s.highlighted.map_or(0, |h| (h + 1).min(n - 1))); + } + if up { + s.highlighted = s.highlighted.and_then(|h| h.checked_sub(1)); + } + if esc { + self.suggestions = None; + return; + } + if let Some(h) = s.highlighted + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) + { + picked_this_frame = s.list.get(h).cloned(); + } + let area = egui::Area::new(egui::Id::new(("suggest", slot))) + .order(egui::Order::Foreground) + .fixed_pos(resp.rect.left_bottom() + vec2(0.0, 2.0)); + let width = resp.rect.width().max(220.0); + let shown = area.show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_width(width); + for (i, sug) in s.list.iter().enumerate() { + let label = if sug.games > 0 { + format!("{} — {}", sug.name, grouped(sug.games as usize)) + } else { + sug.name.clone() + }; + let r = ui.add( + egui::Button::selectable(s.highlighted == Some(i), label) + .truncate() + .min_size(vec2(width, 0.0)), + ); + if r.clicked() { + picked_this_frame = Some(sug.clone()); + } + } + if s.total > s.list.len() { + ui.label( + RichText::new(trf( + "{n} more matches…", + &[("n", &grouped(s.total - s.list.len()))], + )) + .weak(), + ); + } + }); + }); + self.pointer_on_list = shown.response.contains_pointer(); + if let Some(sug) = picked_this_frame { + let value = match field { + NameField::Player => &mut self.form.player, + NameField::Opponent => &mut self.form.opponent, + NameField::Event => &mut self.form.event, + }; + value.text = sug.name.clone(); + value.exact = Some(sug.id); + self.typed[slot] = sug.name; + self.suggestions = None; + self.pointer_on_list = false; + resp.request_focus(); + // Picking applies at once. + self.typed_at = f64::NEG_INFINITY; + } + } + + /// The header line and the table (in the central panel). + #[allow(clippy::too_many_arguments)] + pub fn table( + &mut self, + ui: &mut Ui, + path: &Path, + db: &Arc, + header: &Header, + viewed: &mut Viewed, + notes: usize, + settings: &Settings, + writable: bool, + actions: &mut Vec, + ) -> bool { + let mut open_notes = false; + self.update(db, ui.ctx()); + self.writable = writable; + let now = ui.input(|i| i.time); + let progress = self.slow_progress(now, db.len()); + let total = db.games() + db.texts(); + // A database with no games yet (own-databases.md §2.3): how to put one in. + if total == 0 && writable { + let name = crate::own_db::base_name(path); + // The header as for any database; nothing to search, so no field and no switch, + // and «+ Game» once: the main button in the middle. + ui.horizontal(|ui| { + ui.label(RichText::new(&name).strong()); + ui.label(RichText::new(format!("· {}", header.format)).weak()); + ui.label(format!("· {}", crate::i18n::games(0))); + }); + ui.vertical_centered(|ui| { + ui.add_space(60.0); + ui.label( + RichText::new(trf("No games in «{name}» yet", &[("name", &name)])).size(16.0), + ); + ui.add_space(10.0); + if crate::widgets::primary(ui, tr("+ Game")) + .on_hover_text(new_game_hint(&name)) + .clicked() + { + actions.push(LibraryAction::NewGameIn(path.to_path_buf())); + } + ui.add_space(6.0); + ui.label( + RichText::new(tr( + "«+ Game» opens an empty board; Ctrl+S adds the game here. Or open any game and choose «Add to database…» (Ctrl+Shift+S)", + )) + .weak(), + ); + ui.add_space(6.0); + ui.label(RichText::new(trf("File: {path}", &[("path", &crate::platform::files::shown(path))])).weak()); + }); + return open_notes; + } + + // The header (docs/design/narrow-windows.md §2.4), by importance: the pane switch, + // the quick search (220, down to 140), the counter, "⟳ New games", the import + // notes, the database's name (shortened, at least 80, else left out: it is on + // the shelf too), its format. Measured from the texts; what does not fit on one + // line goes to a second. + let name = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let format = format!("· {}", header.format); + let counter = match &self.shown { + Some(s) + if (s.use_position && self.blocked.is_none()) + || s.filter != Filter::default() + || self.form.active() > 0 => + { + trf( + "· found {n} of {total}", + &[("n", &grouped(self.view.len())), ("total", &grouped(total))], + ) + } + _ if db.texts() > 0 => format!( + "· {} · {}", + crate::i18n::games(db.games()), + crate::i18n::texts(db.texts()) + ), + _ => format!("· {}", crate::i18n::games(db.games())), + }; + // The board alone in a narrow window: the counter leads back to the list. + let counter = if self.board_alone() { + format!("{} ›", counter.trim_start_matches("· ")) + } else { + counter + }; + let gap = ui.spacing().item_spacing.x; + let pad = 2.0 * ui.spacing().button_padding.x; + let body = |t: &str| text_w(ui, t, egui::TextStyle::Body); + let switch_w = { + let active = self.form.active(); + body(&trf("Filters ({n})", &[("n", &active)])) + + body(&format!("{} •", tr("Board"))) + + 2.0 * pad + }; + let search_w = |field: f32| 20.0 + gap + field + 8.0 + 8.0 + gap; + let info_w = body(&counter) + + gap + + progress.map_or(0.0, |_| 14.0 + gap + body("100 %") + gap) + + if notes > 0 { + body(&format!("ℹ {notes}")) + pad + gap + } else { + 0.0 + } + + header.online.as_ref().map_or(0.0, |o| { + if o.busy { + 14.0 + gap + body(tr("updating…")) + gap + } else { + text_w(ui, tr("⟳ New games"), egui::TextStyle::Small) + pad + gap + } + }); + let name_w = text_w(ui, &name, egui::TextStyle::Body) + gap; + let format_w = body(&format) + gap; + let avail = ui.available_width(); + // «+ Game» (a database that takes games only), shortened to «+» after the field. + let plus_w = |full: bool| { + if !writable { + 0.0 + } else if full { + body(tr("+ Game")) + pad + 8.0 + gap + } else { + body("+") + pad + 8.0 + gap + } + }; + let right = |field: f32, full: bool| switch_w + 8.0 + search_w(field) + plus_w(full); + // One line: the widest field that leaves the counter and at least 80 of the name. + // (field, format, the name's least room: 0 leaves the name out, «+ Game» in full) + let one_line = [ + (220.0, true, name_w, true), + (220.0, false, 80.0 + gap, true), + (140.0, false, 80.0 + gap, true), + (140.0, false, 80.0 + gap, false), + (140.0, false, 0.0, false), + ] + .into_iter() + .find(|(field, with_format, name_least, full)| { + let format = if *with_format { format_w } else { 0.0 }; + avail - right(*field, *full) - info_w - format >= *name_least + }) + .map(|(field, with_format, _, full)| (field, with_format, full)); + let (field, plus_full) = match one_line { + Some((field, _, full)) => (field, full), + None if avail - right(220.0, true) >= 80.0 + gap => (220.0, true), + None => (140.0, false), + }; + let with_format = one_line.is_some_and(|(_, f, _)| f); + let mut back_to_list = false; + let mut new_game = false; + let alone = self.board_alone(); + // On a line of its own the counter loses its leading "· ". + // The name is drawn when it has its own width or at least 80 (shortened). + let name_shown = |room: f32| room >= name_w.min(80.0 + gap); + let name_room = if one_line.is_some() { + avail - right(field, plus_full) - info_w - if with_format { format_w } else { 0.0 } + } else { + avail - right(field, plus_full) + }; + let shown = name_shown(name_room); + // What starts the line loses its leading "· ". + let counter_text = if one_line.is_some() && (shown || with_format) { + counter.as_str() + } else { + counter.trim_start_matches("· ") + }; + let mut info = |ui: &mut Ui| { + let mut text = RichText::new(counter_text); + if progress.is_some() { + text = text.weak(); + } + if alone { + if ui + .link(text) + .on_hover_text(tr("Show the list of games (Esc)")) + .clicked() + { + back_to_list = true; + } + } else { + ui.label(text); + } + if let Some(p) = progress { + ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak()); + } + if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { + open_notes = true; + } + if header.keep_copy + && ui + .add(egui::Button::new(tr("📋 Keep a copy in the browser")).small()) + .on_hover_text(tr("The copy opens right away, without choosing the file. It is stored in this browser on this device and is lost if you clear the site's data. The file on disk is not changed.")) + .clicked() + { + actions.push(LibraryAction::KeepCopy(path.to_path_buf())); + } + // A database from Lichess and Chess.com: its new games. + if let Some(online) = &header.online { + if online.busy { + ui.label(RichText::new(tr("updating…")).weak()); + } else if ui + .add_enabled(online.enabled, egui::Button::new(tr("⟳ New games")).small()) + .on_hover_text(&online.hint) + .on_disabled_hover_text(&online.hint) + .clicked() + { + #[cfg(not(web))] + actions.push(LibraryAction::UpdateOnline(path.to_path_buf())); + } + } + }; + ui.horizontal(|ui| { + if shown { + ui.allocate_ui( + vec2((name_room - gap).floor(), ui.spacing().interact_size.y), + |ui| { + ui.add(egui::Label::new(RichText::new(&name).strong()).truncate()) + .on_hover_text(&name); + }, + ); + } + if with_format { + let format = if shown { + format.as_str() + } else { + format.trim_start_matches("· ") + }; + ui.label(RichText::new(format).weak()) + .on_hover_text(&header.format_hint); + } + if one_line.is_some() { + info(ui); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // The switch packs its segments; the rest keeps the usual spacing. + ui.scope(|ui| self.pane_switch(ui)); + ui.add_space(8.0); + self.search_field(ui, now, field); + if writable { + ui.add_space(8.0 - ui.spacing().item_spacing.x); + let label = if plus_full { tr("+ Game") } else { "+" }; + if ui + .button(label) + .on_hover_text(new_game_hint(&name)) + .clicked() + { + new_game = true; + } + } + }); + }); + if one_line.is_none() { + ui.horizontal_wrapped(|ui| info(ui)); + } + if back_to_list { + self.pane = Pane::Hidden; + } + if new_game { + actions.push(LibraryAction::NewGameIn(path.to_path_buf())); + } + self.chips(ui, settings); + ui.add_space(2.0); + self.drawer_top = ui.cursor().top(); + + // Ctrl+F: the quick search; once more, the filters' first field (§9.10). + if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)) { + if self.search_focused { + self.open_filters(); + self.focus_player = true; + } else { + self.focus_search = true; + } + } + if crate::platform::CAPS.reference + && ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B)) + { + self.pane = Pane::Board; + } + // Ctrl+Shift+Backspace: all conditions, the quick search and the position included. + if ui.input_mut(|i| { + i.consume_key( + egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, + egui::Key::Backspace, + ) + }) { + self.reset(); + self.form.search.clear(); + self.board = SearchBoard::new(); + self.only_order = false; + } + + // A narrow window: the board takes the place of the table (§2.3). + if self.board_alone() { + self.board_panel(ui, db, settings, actions); + return open_notes; + } + + // A position that could not be searched (no memory) does not filter the list. + let use_position = + self.shown.as_ref().is_some_and(|s| s.use_position) && self.blocked.is_none(); + // The position the shown rows were found for (the board may be ahead of it). + let shown_position = self + .shown + .as_ref() + .filter(|s| s.use_position && self.blocked.is_none()) + .and_then(|s| s.position.as_ref()) + .map(|(_, q)| q.position.clone()); + if self.shown.is_some() && self.view.is_empty() && self.job.is_none() { + let searched = !self.form.search.trim().is_empty(); + ui.vertical_centered(|ui| { + ui.add_space(40.0); + if use_position { + ui.label( + RichText::new(tr("The position does not occur in these games")).size(16.0), + ); + ui.add_space(6.0); + if (self.form.active() > 0 || searched) + && ui.button(tr("Search the whole database")).clicked() + { + self.reset(); + self.form.search.clear(); + } + } else { + ui.label(RichText::new(tr("Nothing found")).size(16.0)); + // A condition on a field no game of the database has (§9.8). + let filled = db.filled(); + let f = &self.form; + for (asked, has, text) in [ + ( + !f.eco.trim().is_empty(), + filled.eco, + tr("No game of this database has an ECO code"), + ), + ( + !f.annotator.trim().is_empty(), + filled.annotator, + tr("No game of this database has an annotator"), + ), + ( + !f.elo_min.trim().is_empty(), + filled.elo, + tr("No game of this database has a rating"), + ), + ( + !f.year_from.trim().is_empty() || !f.year_to.trim().is_empty(), + filled.year, + tr("No game of this database has a year"), + ), + ] { + if asked && !has { + ui.label(RichText::new(text).weak()); + } + } + ui.add_space(6.0); + let label = match (self.form.active() > 0, searched) { + (true, true) => tr("Reset filters and search"), + (false, true) => tr("Reset search"), + _ => tr("Reset filters"), + }; + if ui.button(label).clicked() { + self.reset(); + self.form.search.clear(); + } + } + }); + // Shift+A on an empty list still says why nothing can be searched. + self.handle_find(ui, path, db, actions); + return open_notes; + } + + self.handle_find(ui, path, db, actions); + self.update_marks_sides(db, ui.ctx()); + // `CP_MARKS_DEMO=1`: made-up marks for the first rows (screenshots of the column). + if std::env::var_os("CP_MARKS_DEMO").is_some() + && self.shown.is_some() + && self.job.is_none() + && let Some(marks) = self.marks.clone() + { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| demo_marks(db, &self.view, &marks)); + } + // `CP_BRILLIANT_RUN=1`: the search asked for once the list is there. + if std::env::var_os("CP_BRILLIANT_RUN").is_some() + && self.shown.is_some() + && self.job.is_none() + && self.search_blocked().is_none() + { + static ONCE: std::sync::Once = std::sync::Once::new(); + let mut first = false; + ONCE.call_once(|| first = true); + if first { + self.ask_search(path, db, actions); + } + } + // Records the database does not have (`CP_SELECT` on a short one) are not chosen. + if self.marked.last().is_some_and(|r| r >= db.len()) { + let len = db.len(); + self.mark(|m| m.retain_below(len)); + self.selected = self.selected.filter(|&c| c < len); + } + self.keyboard(ui, path, actions); + // `CP_BATCH=new:`: the chosen records copied into a new database once the + // list is there (screenshots, checks). + if std::env::var("CP_BATCH").is_ok_and(|b| b.starts_with("new:")) + && !self.marked.is_empty() + && !self.view.is_empty() + { + static ONCE: std::sync::Once = std::sync::Once::new(); + let mut first = false; + ONCE.call_once(|| first = true); + if first { + self.ask_copy(path, actions); + } + } + + let scroll_row = if std::mem::take(&mut self.scroll_to_selected) { + self.selected + .and_then(|r| self.view.iter().position(|&i| i as usize == r)) + } else if std::mem::take(&mut self.scroll_to_top) { + Some(0) + } else { + None + }; + // Narrow windows drop the least needed columns first. + // Narrow windows drop the least needed columns first (round, number, marks, + // length, ECO, event); the date becomes the year. + let width = ui.available_width(); + let show_round = width >= 1100.0; + let show_number = !use_position || width >= 1100.0; + let show_moves = width >= 1000.0; + let show_marks = width >= 1000.0; + let show_eco = width >= 860.0; + let show_event = width >= 720.0; + let year_only = width < 1000.0; + let mut columns: Vec<(&str, Option, Column)> = Vec::new(); + if use_position { + columns.push((tr("Move"), None, Column::exact(MOVE_COL))); + } + if show_number { + columns.push(("â„–", Some(SortKey::Number), Column::exact(number_col(db)))); + } + // Without the event the names share the rest of the width. + let name = if show_event { + Column::initial(170.0).at_least(NAME_MIN).clip(true) + } else { + Column::remainder().at_least(NAME_MIN).clip(true) + }; + columns.extend([ + (tr("White"), Some(SortKey::White), name), + ("Elo", Some(SortKey::WhiteElo), Column::exact(ELO_COL)), + (tr("Black"), Some(SortKey::Black), name), + ("Elo", Some(SortKey::BlackElo), Column::exact(ELO_COL)), + (tr("Res."), Some(SortKey::Result), Column::exact(RESULT_COL)), + // The marks of the search for great moves: in every layout (task 27 §4.3). + ("!!", None, Column::exact(MARKS_COL)), + ]); + if show_moves { + columns.push((tr("Length"), Some(SortKey::Moves), Column::exact(56.0))); + } + if show_eco { + columns.push(("ECO", Some(SortKey::Eco), Column::exact(44.0))); + } + if show_marks { + columns.push(("💬", None, Column::exact(40.0))); + } + if show_event { + columns.push(( + tr("Event"), + Some(SortKey::Event), + Column::remainder().at_least(80.0).clip(true), + )); + } + if show_round { + columns.push((tr("Round"), None, Column::exact(48.0))); + } + if year_only { + columns.push((tr("Year"), Some(SortKey::Date), Column::exact(YEAR_COL))); + } else { + columns.push((tr("Date"), Some(SortKey::Date), Column::exact(88.0))); + } + + if progress.is_some() { + ui.set_opacity(0.6); + } + // Each set of columns keeps its own widths: a resized window does not leave the + // names at the widths of another layout. + let layout = ( + show_round, + show_number, + show_moves, + show_marks, + show_eco, + show_event, + year_only, + use_position, + ); + let frame_color = ui.visuals().selection.stroke.color; + let table_clip = ui.clip_rect().intersect(ui.max_rect()); + let spacing = ui.spacing().item_spacing; + let mut table = TableBuilder::new(ui) + .id_salt(("game table", layout)) + .striped(true) + .resizable(true) + .sense(Sense::click()) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)); + for (_, _, c) in &columns { + table = table.column(*c); + } + if let Some(r) = scroll_row { + table = table.scroll_to_row(r, Some(egui::Align::Center)); + } + let mut sort_click = None; + let mut clicked = None; + let mut opened = None; + let mut toggle_viewed = None; + let mut hovered = None; + let marks_sorted = self.marks_sort; + let mut marks_click = false; + let pass_current = self + .pass + .as_ref() + .filter(|p| p.here) + .and_then(|p| p.current); + let (marks_ref, shown_ref, sides_ref) = + (&self.marks, &self.shown_marks, &self.marks_sides.1); + let view = &self.view; + let selected = self.selected; + let marked = &self.marked; + let many = marked.len() >= 2; + let batch_running = self.batch.as_ref().map(|b| b.name.clone()); + let mut batch_menu = None; + let mut secondary = None; + // A position not applied (no memory) does not sort: the arrow shows the view's own order. + let sort = if self.blocked.is_some() { + self.sort + } else { + self.effective_sort() + }; + let outcome = self.outcome.clone().filter(|_| use_position); + let ordered = self + .shown + .as_ref() + .and_then(|s| s.position.as_ref()) + .is_some_and(|(_, q)| q.line.is_some()); + let find = |index: usize| -> Option { + let out = outcome.as_ref()?; + let i = out + .matches + .binary_search_by_key(&(index as u32), |m| m.index) + .ok()?; + out.matches.get(i).copied() + }; + table + .header(26.0, |mut header| { + for (label, key, _) in &columns { + header.col(|ui| { + if *label == "!!" { + let r = crate::widgets::sort_header(ui, label, marks_sorted.then_some(true)) + .on_hover_text(tr("Brilliant and great moves found by the engine: sort by them")); + if r.clicked() { + marks_click = true; + } + return; + } + let active = key.filter(|k| sort.0 == *k && !marks_sorted).map(|_| sort.1); + let r = crate::widgets::sort_header(ui, label, active); + if let Some(k) = key + && r.clicked() + { + sort_click = Some(*k); + } + }); + } + }) + .body(|body| { + body.rows(24.0, view.len(), |mut row| { + let Some(&index) = view.get(row.index()) else { + return; + }; + let index = index as usize; + let r = db.row(index); + let is_marked = marked.contains(index); + row.set_selected(is_marked); + // Where the row's cells are: the cursor's frame follows the row's fill. + let mut cells = egui::Rect::NOTHING; + let key = viewed::key(db.identity(index)); + let seen = viewed.contains(key); + let elo = |e: u16| if e > 0 { e.to_string() } else { String::new() }; + let is_text = r.kind == Some(RecordKind::Text); + let found = find(index); + let result = match r.result { + _ if is_text => "", + "1/2-1/2" => "½-½", + x => x, + }; + for (label, key_, _) in &columns { + row.col(|ui| { + cells = cells.union(ui.max_rect()); + let cell = match (*label, *key_) { + (l, None) if l == tr("Move") => { + let Some(m) = found else { return }; + let mut text = board_search::ply_label(m.ply); + if ordered && !m.same_order { + text = format!("↪{text}"); + } + if m.in_variation { + text.push_str(" 🔀"); + } + let resp = ui.add(egui::Label::new(text).selectable(false)); + resp.on_hover_text(tr("The move after which the position arose in the game. ↪ — reached by another move order, 🔀 — in a variation")); + return; + } + (_, Some(SortKey::Number)) => { + if seen { + check_mark(ui); + } + ui.add_space(14.0); + let n = RichText::new(grouped(index + 1)).weak(); + // A game that could not be read cleanly: its number is orange. + if db.damaged(index) { + n.color(Color32::from_rgb(0xe6, 0x8f, 0x00)) + } else { + n + } + } + (_, Some(SortKey::White)) if is_text => { + RichText::new(format!("📄 {}", r.title)).italics() + } + (_, Some(SortKey::White)) => RichText::new(r.white.as_str()), + (_, Some(SortKey::WhiteElo)) => RichText::new(elo(r.white_elo)), + (_, Some(SortKey::Black)) => RichText::new(r.black.as_str()), + (_, Some(SortKey::BlackElo)) => RichText::new(elo(r.black_elo)), + (_, Some(SortKey::Result)) => RichText::new(result), + ("!!", None) => { + marks_cell(ui, Self::shown_mark(marks_ref, shown_ref, sides_ref, db, index as u32), pass_current == Some(index as u32), is_marked); + return; + } + (_, Some(SortKey::Moves)) => RichText::new(match r.moves { + 0 => String::new(), + 255 => "255+".into(), + m => m.to_string(), + }), + (_, Some(SortKey::Eco)) if r.chess960 => { + let resp = ui.add(egui::Label::new("960").selectable(false)); + resp.on_hover_text(tr("Chess960: the moves cannot be read; the header and result are shown")); + return; + } + (_, Some(SortKey::Eco)) => { + RichText::new(r.eco.clone().unwrap_or_default()) + } + ("💬", None) => { + let marks = format!( + "{}{}", + if r.has_comments { "💬" } else { "" }, + if r.has_variations { "🔀" } else { "" } + ); + RichText::new(marks).weak() + } + (_, Some(SortKey::Event)) => RichText::new(r.event.as_str()).italics(), + (_, Some(SortKey::Date)) if year_only => { + RichText::new(r.date.get(..4).filter(|y| !y.contains('?')).unwrap_or("")) + } + (_, Some(SortKey::Date)) => RichText::new(crate::library::display_date(&r.date)), + _ => RichText::new(if r.round == "?" { "" } else { r.round.as_str() }).weak(), + }; + ui.add(egui::Label::new(cell).selectable(false).truncate()); + }); + } + // Tournament · place · round · length · annotator, those it has. + let moves = if r.moves > 0 { trf("moves: {n}", &[("n", &r.moves)]) } else { String::new() }; + let round = if r.round.trim().is_empty() || r.round == "?" { + String::new() + } else { + format!("{} {}", tr("Round").to_lowercase(), r.round) + }; + let about: Vec<&str> = [r.event.as_str(), r.site.as_str(), round.as_str(), moves.as_str(), r.annotator.as_str()] + .into_iter() + .filter(|t| !t.trim().is_empty() && *t != "?" && !t.contains("://")) + .collect(); + let resp = row.response(); + // The cursor among several chosen rows, or on a row not chosen: a frame + // (a shape, not a colour; §42.4). + if selected == Some(index) && (many || !is_marked) { + ui_painter_frame(&resp, cells.expand2(spacing / 2.0), frame_color, table_clip); + } + let resp = if about.is_empty() { resp } else { resp.on_hover_text(about.join(" · ")) }; + if resp.secondary_clicked() { + secondary = Some(index); + } + // Several chosen and this one among them: the menu of the choice. + if many && is_marked { + resp.context_menu(|ui| { + if let Some(item) = batch_items(ui, marked.len(), batch_running.as_deref()) { + batch_menu = Some(item); + ui.close(); + } + }); + } else { + resp.context_menu(|ui| { + if ui.button(tr("Open")).clicked() { + opened = Some(index); + ui.close(); + } + // The first !! (else !) the search found: the game at it. + if let Some(f) = Self::shown_mark(marks_ref, shown_ref, sides_ref, db, index as u32) + .and_then(|e| { + let first = e.found.iter().find(|f| f.brilliant).or(e.found.first()); + first.cloned() + }) + && ui + .button(trf("Open at {move}", &[("move", &f.label())])) + .clicked() + { + let at = db.load_game(index).and_then(|p| { + let node = *p.game.mainline().get(f.ply as usize)?; + Some(p.game.node(node)?.position().clone()) + }); + actions.push(LibraryAction::OpenGameReport { + path: path.to_path_buf(), + index, + at, + }); + ui.close(); + } + // The game's page, when its tags have one (read once per menu). + if self.menu_link.as_ref().is_none_or(|(i, _)| *i != index) { + let link = db.load_game(index).and_then(|p| { + crate::game_link::of(|t| p.game.tag(t).map(str::to_owned)) + }); + self.menu_link = Some((index, link)); + } + if let Some((_, Some(link))) = &self.menu_link + && ui.button(link.label()).clicked() + { + ui.ctx().open_url(egui::OpenUrl::new_tab(link.at(0, false))); + ui.close(); + } + // One item per player of the game (the same name once). + let mut players: Vec<&str> = vec![r.white.as_str(), r.black.as_str()]; + players.dedup(); + for name in players { + if name.trim().is_empty() || name == "?" { + continue; + } + if ui + .button(trf("♟ Prepare against {name}…", &[("name", &name)])) + .clicked() + { + self.prepare = Some(PrepEntry { + query: name.to_owned(), + exact: None, + side: Side::Any, + }); + ui.close(); + } + } + if ui.button(tr("Game data… (F2)")).clicked() { + actions.push(LibraryAction::EditGameData { path: path.to_path_buf(), index }); + ui.close(); + } + if ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() { + actions.push(LibraryAction::AddGameToDatabase { path: path.to_path_buf(), index }); + ui.close(); + } + if ui.button(tr("Select all (Ctrl+A)")).clicked() { + batch_menu = Some(BatchItem::SelectAll); + ui.close(); + } + let label = if seen { + tr("Mark as not viewed") + } else { + tr("Mark as viewed") + }; + if ui.button(label).clicked() { + toggle_viewed = Some((key, !seen)); + ui.close(); + } + if self.writable { + ui.separator(); + if ui.button(tr("Delete from the database… (Delete)")).clicked() { + actions.push(LibraryAction::DeleteGame { path: path.to_path_buf(), index }); + ui.close(); + } + } + }); + } + if resp.hovered() { + hovered = Some(index); + } + if resp.clicked() { + clicked = Some(index); + } + if resp.double_clicked() { + opened = Some(index); + } + }); + }); + // The shown rows belong to the shown position: no arrow on another one. + let shown_here = shown_position.as_ref() == Some(&self.board.position()); + self.table_hover = hovered + .filter(|_| shown_here) + .zip(self.outcome.as_deref().filter(|_| use_position)) + .and_then(|(i, out)| board_search::next_move_of(out, i)); + if let Some((k, v)) = toggle_viewed { + viewed.set(k, v); + } + if marks_click { + self.marks_sort = !self.marks_sort; + if self.marks_sort { + self.sort_by_marks(); + } else { + // The list comes again in the sort of its columns. + self.shown = None; + } + } + if let Some(k) = sort_click { + self.marks_sort = false; + let current = self.effective_sort(); + self.sort = if current.0 == k { + (k, !current.1) + } else { + (k, true) + }; + self.sort_chosen = true; + self.typed_at = f64::NEG_INFINITY; + } + if let Some(i) = clicked { + let mods = ui.input(|i| i.modifiers); + self.click(i, mods); + } + // A right click on a row not chosen chooses it alone. + if let Some(i) = secondary + && !(self.marked.len() >= 2 && self.marked.contains(i)) + { + self.click(i, egui::Modifiers::NONE); + } + match batch_menu { + Some(BatchItem::NewBase) => self.ask_copy(path, actions), + Some(BatchItem::SelectAll) => self.select_all(), + Some(BatchItem::Clear) => self.mark_cursor_only(), + None => {} + } + if let Some(index) = opened { + self.selected = Some(index); + actions.push(LibraryAction::OpenGame { + path: path.to_path_buf(), + index, + at: shown_position.clone(), + }); + } + open_notes + } + + /// Up/Down move the cursor, Page Up/Down by a page, Home/End to the ends, Enter + /// opens. Without a modifier the choice follows the cursor, Shift chooses the range + /// from the anchor, Ctrl moves the cursor alone; Ctrl+Space toggles its row, Ctrl+A + /// chooses the whole list (§42.6). + fn keyboard(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec) { + // In a filter field the arrows still move through the table (unless the + // suggestions are open), but Enter belongs to the field. + let typing = ui.ctx().egui_wants_keyboard_input(); + if typing && self.suggestions.is_some() { + return; + } + // A question or a menu over the table takes the keys (Enter there is its button, + // not «open the game»). + if crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) { + return; + } + let (up, down, page_up, page_down, enter, mods) = ui.input(|i| { + ( + i.key_pressed(egui::Key::ArrowUp), + i.key_pressed(egui::Key::ArrowDown), + i.key_pressed(egui::Key::PageUp), + i.key_pressed(egui::Key::PageDown), + i.key_pressed(egui::Key::Enter), + i.modifiers, + ) + }); + let (home, end) = if typing { + (false, false) + } else { + ui.input(|i| { + ( + i.key_pressed(egui::Key::Home), + i.key_pressed(egui::Key::End), + ) + }) + }; + if !typing { + let (all, toggle) = ui.input_mut(|i| { + ( + i.consume_key(egui::Modifiers::COMMAND, egui::Key::A), + i.consume_key(egui::Modifiers::COMMAND, egui::Key::Space), + ) + }); + if all { + self.select_all(); + } + if toggle && let Some(c) = self.selected { + self.mark(|m| m.toggle(c)); + self.anchor = Some(c); + } + } + // The cursor's record: F2 opens it with its data, Ctrl+Shift+S adds a copy of it + // to another database (several chosen: a new database of them), Delete removes + // it (a question first; never while several are chosen). + if !typing && let Some(index) = self.selected { + let (data, add, delete) = ui.input_mut(|i| { + ( + i.consume_key(egui::Modifiers::NONE, egui::Key::F2), + i.consume_key( + egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, + egui::Key::S, + ), + i.consume_key(egui::Modifiers::NONE, egui::Key::Delete), + ) + }); + let many = self.marked.len() >= 2; + let p = path.to_path_buf(); + if data { + actions.push(LibraryAction::EditGameData { + path: p.clone(), + index, + }); + } + if add && many { + self.ask_copy(path, actions); + } else if add { + actions.push(LibraryAction::AddGameToDatabase { + path: p.clone(), + index, + }); + } + if delete && many { + actions.push(LibraryAction::Notice( + tr("Games are deleted one at a time: clear the selection (Esc)").to_owned(), + )); + } else if delete { + // Also for a database that takes no games: the app says why. + actions.push(LibraryAction::DeleteGame { path: p, index }); + } + } + // Enter belongs to a filter field, but in the quick search it opens the game. + let enter = enter && (!typing || self.search_focused); + let step = if page_up || page_down { 20 } else { 1 }; + if up || down || page_up || page_down || home || end { + let pos = self.selected.and_then(|r| self.position_of(r)); + let last = self.view.len().saturating_sub(1); + let next = match (pos, down || page_down) { + _ if home => 0, + _ if end => last, + (None, _) => 0, + (Some(p), true) => (p + step).min(last), + (Some(p), false) => p.saturating_sub(step), + }; + if let Some(&i) = self.view.get(next) { + let i = i as usize; + if mods.shift { + let from = self + .anchor + .and_then(|a| self.position_of(a)) + .or(pos) + .unwrap_or(next); + if self.anchor.and_then(|a| self.position_of(a)).is_none() { + self.anchor = self.view.get(from).map(|&r| r as usize); + } + let range = self.range(from, next).to_vec(); + self.mark(|m| { + m.clear(); + m.extend(&range); + }); + } else if !mods.command { + self.mark(|m| m.only(i)); + self.anchor = Some(i); + } + self.selected = Some(i); + self.scroll_to_selected = true; + } + } + if enter && let Some(index) = self.selected { + actions.push(LibraryAction::OpenGame { + path: path.to_path_buf(), + index, + at: self + .shown + .as_ref() + .filter(|s| s.use_position) + .and_then(|s| s.position.as_ref()) + .map(|(_, q)| q.position.clone()), + }); + } + } +} + +/// Up to this many chosen records are checked when their file is read again; a larger +/// choice is let go if the file changed. +const CHECKED_CHOICE: usize = 100_000; + +/// A hash of the bytes of record `index`. +fn record_hash(db: &Database, index: usize) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + db.identity(index).hash(&mut h); + h.finish() +} + +/// Space between the slots of the conditions line (`item_spacing.x` + 4). +const SLOT_GAP: f32 = 4.0; +/// The «!!» column. +const MARKS_COL: f32 = 28.0; + +/// An item of the menus about the chosen records. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BatchItem { + NewBase, + SelectAll, + Clear, +} + +/// The menu of several chosen rows (§42.7): how many, the copy, select all, clear. The +/// copy waits while another one is written. +fn batch_items(ui: &mut Ui, n: usize, writing: Option<&str>) -> Option { + let mut out = None; + ui.label(RichText::new(trf("Games selected: {n}", &[("n", &grouped(n))])).weak()); + ui.separator(); + let copy = ui.add_enabled( + writing.is_none() && crate::platform::CAPS.batch_copy, + egui::Button::new(tr("New database from selected…")), + ); + let copy = match writing { + Some(name) => copy.on_disabled_hover_text(trf( + "Writing to «{name}» — wait until it finishes", + &[("name", &name)], + )), + None => copy, + }; + if copy.clicked() { + out = Some(BatchItem::NewBase); + } + ui.separator(); + if ui.button(tr("Select all (Ctrl+A)")).clicked() { + out = Some(BatchItem::SelectAll); + } + if ui.button(tr("Clear selection (Esc)")).clicked() { + out = Some(BatchItem::Clear); + } + out +} + +/// Made-up marks for the first rows of `view` (`CP_MARKS_DEMO`): !!, !, none, not +/// analysable, in turn; not saved. +fn demo_marks(db: &Database, view: &[u32], marks: &std::sync::Mutex) { + use crate::brilliant::{Counts, Entry, Found, SideMarks, Skip}; + let Ok(mut index) = marks.lock() else { + return; + }; + for (n, &r) in view.iter().take(8).enumerate() { + let Some(game) = db.load_game(r as usize).map(|p| p.game) else { + continue; + }; + let line = game_review::GameAnalysis::new(&game, None).cache_key(); + let side = |brilliant, great| SideMarks { + counts: Counts { + brilliant, + great, + ..Counts::default() + }, + acpl: Some(30), + accuracy: Some(85.0), + }; + let found = |brilliant| Found { + ply: 20, + white: true, + number: 11, + san: "Rxf7".into(), + brilliant, + }; + let entry = match n % 4 { + 0 => Entry { + line, + white: side(1, 0), + black: side(0, 0), + found: vec![found(true)], + stale: false, + skip: None, + }, + 1 => Entry { + line, + white: side(0, 2), + black: side(0, 0), + found: vec![found(false)], + stale: true, + skip: None, + }, + 2 => Entry { + line, + white: side(0, 0), + black: side(0, 0), + found: Vec::new(), + stale: false, + skip: None, + }, + _ => Entry { + line, + white: SideMarks::default(), + black: SideMarks::default(), + found: Vec::new(), + stale: false, + skip: Some(Skip::NullMove), + }, + }; + index.set(r, entry); + } +} + +/// The «!!» cell of a record (task 27 §4.3): !!, !, «·» analysed without them, «—» not +/// analysable, a spinner while analysed, nothing when not analysed. Signs, not colours +/// alone; on a chosen row in the text colour of the selection. +fn marks_cell(ui: &mut Ui, entry: Option, running: bool, chosen: bool) { + ui.with_layout( + egui::Layout::centered_and_justified(egui::Direction::LeftToRight), + |ui| { + if running { + ui.add(egui::Spinner::new().size(12.0)) + .on_hover_text(tr("Being reviewed…")); + return; + } + let Some(e) = entry else { + return; + }; + let dark = ui.visuals().dark_mode; + let tint = |nag: u8| { + if chosen { + ui.visuals().selection.stroke.color + } else { + crate::notation::assessment_text_color(chess_core::Nag(nag), dark) + .unwrap_or(ui.visuals().text_color()) + } + }; + let moves = |brilliant: bool| { + let list: Vec = e + .found + .iter() + .filter(|f| f.brilliant == brilliant) + .map(|f| f.label()) + .collect(); + let shown = list.iter().take(3).cloned().collect::>().join(", "); + if list.len() > 3 { + format!( + "{shown} {}", + trf("and {n} more", &[("n", &(list.len() - 3))]) + ) + } else { + shown + } + }; + let c = e.of_sides(true, true); + let (text, color, mut hint) = if let Some(skip) = e.skip { + ( + "—", + ui.visuals().weak_text_color(), + trf( + "Cannot be reviewed: {reason}", + &[("reason", &skip.reason())], + ), + ) + } else if c.brilliant > 0 || c.great > 0 { + let mut hint = Vec::new(); + if c.brilliant > 0 { + hint.push(trf( + "Brilliant moves: {n}: {moves}", + &[("n", &c.brilliant), ("moves", &moves(true))], + )); + } + if c.great > 0 { + hint.push(trf( + "Great moves: {n}: {moves}", + &[("n", &c.great), ("moves", &moves(false))], + )); + } + if c.brilliant > 0 { + ("!!", tint(3), hint.join("\n")) + } else { + ("!", tint(1), hint.join("\n")) + } + } else { + ( + "•", + ui.visuals().weak_text_color(), + tr("Reviewed: no brilliant or great moves").to_owned(), + ) + }; + if e.stale { + hint.push('\n'); + hint.push_str(tr("Reviewed with the previous engine settings")); + } + let color = if chosen { + ui.visuals().selection.stroke.color + } else { + color + }; + // Ubuntu-B, as the other signs of moves. + let bold = egui::FontId::new(13.0, egui::FontFamily::Name("bold".into())); + let font = if ui.fonts_mut(|f| f.families().contains(&bold.family)) { + bold + } else { + egui::FontId::proportional(13.0) + }; + ui.add(egui::Label::new(RichText::new(text).font(font).color(color)).selectable(false)) + .on_hover_text(hint); + }, + ); +} + +/// The keyboard cursor's frame: 1 px inside the row. +fn ui_painter_frame(row: &egui::Response, rect: egui::Rect, color: Color32, clip: egui::Rect) { + let stroke = Stroke::new(1.0, color); + row.ctx + .layer_painter(row.layer_id) + .with_clip_rect(clip) + .rect_stroke(rect.intersect(clip), 0.0, stroke, egui::StrokeKind::Inside); +} + +/// A condition of the list, shown as a chip. +struct Condition { + text: String, + pane: Pane, + clear: Clear, + /// Said under the pointer (a condition not applied, and why). + hint: Option, + /// Position (and how to draw it) for the tooltip of the position chip. + mini: Option<( + shakmaty::Chess, + bool, + crate::assets::BoardThemeId, + crate::assets::PieceSet, + )>, +} + +/// What removing a chip clears. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Clear { + Position, + Search, + Player, + Opponent, + Event, + Annotator, + Years, + Elo, + Result, + Eco, + Length, + Comments, + Variations, + Texts, +} + +/// One chip: its text opens the condition, × removes it. Returns (opened, removed). +fn chip(ui: &mut Ui, c: &Condition) -> (bool, bool) { + let mut out = (false, false); + egui::Frame::new() + .fill(ui.visuals().faint_bg_color) + .corner_radius(4.0) + .inner_margin(egui::Margin::symmetric(6, 1)) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let r = ui.add( + egui::Label::new(RichText::new(c.text.as_str()).size(13.0)).sense(Sense::click()), + ); + let r = match &c.mini { + Some((pos, flipped, theme, pieces)) => r.on_hover_ui(|ui| { + let view = crate::board::BoardView { + pos, + orientation: if *flipped { + shakmaty::Color::Black + } else { + shakmaty::Color::White + }, + last_move: None, + arrows: &[], + circles: &[], + badge: None, + interactive: false, + temporary_shapes: false, + show_coords: false, + theme: theme.theme(), + pieces: *pieces, + animation: 0.0, + premove: None, + auto_queen: false, + alert: None, + }; + ui.allocate_ui(vec2(160.0, 160.0), |ui| { + view.show(ui, &mut crate::board::BoardState::default()) + }); + }), + None => r, + }; + let r = match &c.hint { + Some(h) => r.on_hover_text(h), + None => r, + }; + out.0 = r.clicked(); + out.1 = crate::widgets::small_close_button(ui) + .on_hover_text(tr("Remove the condition")) + .clicked(); + }); + out +} + +/// The cell between "from" and "to" (and before Elo's rule). +const DASH: f32 = 16.0; + +/// A row of the «Game» grid: the caption in a column `label_w` wide, then the fields. +fn form_row(ui: &mut Ui, label_w: f32, caption: &str, add: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let (rect, _) = + ui.allocate_exact_size(vec2(label_w, ui.spacing().interact_size.y), Sense::hover()); + ui.painter().text( + rect.left_center(), + egui::Align2::LEFT_CENTER, + caption, + egui::TextStyle::Body.resolve(ui.style()), + ui.visuals().text_color(), + ); + ui.add_space(4.0); + add(ui); + }); +} + +/// The dash between "from" and "to", centred in its cell (empty: only the gap). +fn dash(ui: &mut Ui, text: &str) { + let (rect, _) = + ui.allocate_exact_size(vec2(DASH, ui.spacing().interact_size.y), Sense::hover()); + if !text.is_empty() { + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + text, + egui::TextStyle::Body.resolve(ui.style()), + ui.visuals().text_color(), + ); + } +} + +/// A one-line text field across the panel, with a red frame when `ok` is false. +/// A non-empty field has a × to clear it (the response then reports a change). +fn text_field(ui: &mut Ui, text: &mut String, hint: &str, ok: bool) -> egui::Response { + ui.horizontal(|ui| { + // The × (22 pt) and its 4 pt gap have their place whether shown or not: the row + // never sticks out, so the panel keeps its width while one types (§2.6). + ui.spacing_mut().item_spacing.x = 4.0; + let mut edit = egui::TextEdit::singleline(text) + .hint_text(hint) + .desired_width((ui.available_width() - CLEAR_SLOT).floor().max(40.0)); + if !ok { + edit = edit.text_color(ui.visuals().error_fg_color); + } + let mut r = ui.add(edit); + if !ok { + ui.painter().rect_stroke( + r.rect, + 2.0, + Stroke::new(1.5, ui.visuals().error_fg_color), + egui::StrokeKind::Outside, + ); + } + if text.is_empty() { + ui.add_space(CLEAR_SLOT - 4.0); + } else if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Clear")) + .clicked() + { + text.clear(); + r.mark_changed(); + } + r + }) + .inner +} + +/// A short field for a number (digits only). +fn number_field( + ui: &mut Ui, + text: &mut String, + hint: &str, + ok: bool, + width: f32, +) -> egui::Response { + let mut edit = egui::TextEdit::singleline(text) + .hint_text(hint) + .desired_width(width) + .char_limit(4); + if !ok { + edit = edit.text_color(ui.visuals().error_fg_color); + } + let r = ui.add(edit); + text.retain(|c| c.is_ascii_digit()); + if !ok { + ui.painter().rect_stroke( + r.rect, + 2.0, + Stroke::new(1.5, ui.visuals().error_fg_color), + egui::StrokeKind::Outside, + ); + } + r +} + +fn check_mark(ui: &mut Ui) { + let c = ui.max_rect().left_center() + vec2(7.0, 0.0); + let stroke = Stroke::new(2.0, Color32::from_rgb(0x62, 0x9c, 0x2e)); + ui.painter() + .line_segment([c + vec2(-4.0, 0.0), c + vec2(-1.0, 3.5)], stroke); + ui.painter() + .line_segment([c + vec2(-1.0, 3.5), c + vec2(5.0, -4.0)], stroke); +} + +/// The active button's explanation of a manual source, including its hidden records. +fn selected_search_hint(selected: crate::brilliant::SelectedGames) -> String { + let mut hint = trf( + "Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)", + &[("games", &crate::i18n::games(selected.games))], + ); + hint.push('\n'); + if selected.hidden > 0 { + hint.push_str(&trf( + "{k} hidden by the current filter; these games are included too.", + &[("k", &grouped(selected.hidden))], + )); + } else { + hint.push_str(tr("The filter does not change this run's games.")); + } + hint +} + +/// More than 100 selected records: never fall back to a small enough filtered list. +fn selected_limit_hint(games: usize) -> String { + format!( + "{}\n{}", + trf( + "Selected: {games} — more than 100.", + &[("games", &crate::i18n::games(games))] + ), + tr("Keep no more than 100 selected; the filter is not used.") + ) +} + +/// "11 741 260": thousands separated by a narrow space. +pub fn grouped(n: usize) -> String { + let digits = n.to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push('\u{202f}'); + } + out.push(c); + } + out +} + +/// "49", "8 512", "250 thousand", "11.7 million" for the database card. +pub fn short_count(n: usize) -> String { + if n < 10_000 { + grouped(n) + } else if n < 1_000_000 { + trf("{n} thousand", &[("n", &(n / 1000))]) + } else { + let m = format!("{:.1}", n as f64 / 1e6); + let m = if tr("decimal comma") == "," { + m.replace('.', ",") + } else { + m + }; + trf("{n} million", &[("n", &m)]) + } +} + +/// The tooltip of «+ Game»: where its game goes. +fn new_game_hint(name: &str) -> String { + trf( + "A new game for «{name}»: Ctrl+S adds it to this database", + &[("name", &name)], + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctrl() -> egui::Modifiers { + egui::Modifiers::COMMAND + } + + fn shift() -> egui::Modifiers { + egui::Modifiers::SHIFT + } + + /// A view showing records 0..20 in the order 19, 18, … 0 (a sort). + fn table() -> LargeView { + let mut v = LargeView::new(); + v.view = (0..20).rev().collect(); + v + } + + /// A table whose filter has finished, so its search button can be evaluated. + fn ready_table() -> LargeView { + let mut v = table(); + let shown = v.request(); + v.shown = Some(shown); + v + } + + /// The owned request that the search button sends to the existing analysis path. + fn find_request( + v: &mut LargeView, + db: &Database, + ) -> (Vec, Option) { + let mut actions = Vec::new(); + v.ask_search(Path::new("/games.pgn"), db, &mut actions); + match actions.pop() { + Some(LibraryAction::FindGreatMoves { + records, selected, .. + }) => (records, selected), + _ => panic!("one great-moves request"), + } + } + + #[test] + fn clicks_choose_one_toggle_and_ranges_in_the_tables_order() { + let mut v = table(); + v.click(3, egui::Modifiers::NONE); + assert_eq!((v.marked.records(), v.selected), (vec![3], Some(3))); + v.click(7, ctrl()); + v.click(15, ctrl()); + assert_eq!(v.marked.records(), vec![3, 7, 15]); + v.click(7, ctrl()); + assert_eq!(v.marked.records(), vec![3, 15]); + // Shift: the range from the anchor (7, the last Ctrl click) in the table's order + // replaces the choice; Ctrl+Shift adds it. + v.click(10, shift()); + assert_eq!(v.marked.records(), vec![7, 8, 9, 10]); + v.click(1, ctrl()); + v.click(3, ctrl() | shift()); + assert_eq!(v.marked.records(), vec![1, 2, 3, 7, 8, 9, 10]); + v.click(5, egui::Modifiers::NONE); + assert_eq!(v.marked.records(), vec![5]); + } + + #[test] + fn an_anchor_hidden_by_the_filter_gives_way_to_the_cursor() { + let mut v = table(); + v.click(30, egui::Modifiers::NONE); + v.click(4, ctrl()); + v.anchor = Some(30); + v.click(6, shift()); + assert_eq!(v.marked.records(), vec![4, 5, 6]); + } + + #[test] + fn select_all_takes_the_list_and_escape_comes_back_to_the_cursor() { + let mut v = table(); + v.marked.insert(40); + v.click(40, ctrl()); + v.click(2, ctrl()); + v.select_all(); + assert_eq!(v.marked.len(), 20); + assert_eq!(v.hidden_marked(), 0); + v.marked.insert(40); + v.marked_gen += 1; + assert_eq!(v.hidden_marked(), 1); + assert!(v.escape()); + assert_eq!(v.marked.records(), vec![2]); + // One chosen: Escape is the next one's (here nobody's). + assert!(!v.escape()); + } + + #[test] + fn returning_from_a_game_keeps_a_choice_of_several() { + let mut v = table(); + v.click(1, egui::Modifiers::NONE); + v.reveal(9); + assert_eq!(v.marked.records(), vec![9]); + v.click(3, ctrl()); + v.reveal(3); + assert_eq!(v.marked.records(), vec![3, 9]); + } + + fn database(name: &str, games: &[&str]) -> Database { + let path = + std::env::temp_dir().join(format!("cp-reread-{}-{name}.pgn", std::process::id())); + let text: String = games + .iter() + .map(|w| format!("[White \"{w}\"]\n[Black \"x\"]\n[Result \"*\"]\n\n1. e4 *\n\n")) + .collect(); + std::fs::write(&path, text).unwrap(); + let db = chess_import::open( + &path, + &mut |_| {}, + &std::sync::atomic::AtomicBool::new(false), + ) + .unwrap() + .db; + let _ = std::fs::remove_file(&path); + db + } + + #[test] + fn a_choice_never_moves_to_other_games_when_the_file_is_read_again() { + let before = database("before", &["a", "b", "c", "d"]); + // A game added at the end: the chosen ones are the same records. + let mut v = table(); + v.click(1, egui::Modifiers::NONE); + v.click(2, ctrl()); + v.before_reread(&before); + v.reread(&database("added", &["a", "b", "c", "d", "e"])); + assert_eq!(v.marked.records(), vec![1, 2]); + assert!(v.notice.is_none()); + // A game put back at the start (undo of a delete): the numbers moved; let go, + // and said. + v.before_reread(&before); + v.reread(&database("undo", &["z", "a", "b", "c", "d"])); + assert!(v.marked.is_empty()); + assert!(v.notice.is_some()); + } + + #[test] + fn the_copy_asks_for_the_chosen_records_and_the_tables_sort() { + let mut v = table(); + v.sort = (SortKey::White, false); + v.click(5, egui::Modifiers::NONE); + v.click(2, ctrl()); + let mut actions = Vec::new(); + v.ask_copy(Path::new("/x.pgn"), &mut actions); + match actions.as_slice() { + [ + LibraryAction::CopySelection { + records, + sort, + ascending, + hidden, + .. + }, + ] => { + assert_eq!(records, &vec![2, 5]); + assert_eq!((*sort, *ascending, *hidden), (SortKey::White, false, 0)); + } + _ => panic!("one copy"), + } + // None while another copy is written. + v.batch = Some(BatchStatus { + name: "x".into(), + done: 0, + total: 1, + cancelling: false, + }); + actions.clear(); + v.ask_copy(Path::new("/x.pgn"), &mut actions); + assert!(actions.is_empty()); + } + + #[test] + fn the_search_limit_follows_the_choice_independently_of_the_filter() { + let mut v = ready_table(); + v.view = (0..101).collect(); + assert!( + v.search_blocked() + .is_some_and(|s| s.contains(tr("Filter the games down to 100 or fewer"))) + ); + + // One and one hundred selected games may start even when the filter has 101. + v.marked.only(0); + assert_eq!(v.search_len(), 1); + assert_eq!(v.search_blocked(), None); + v.marked.clear(); + for r in 0..100 { + v.marked.insert(r); + } + assert_eq!(v.search_len(), 100); + assert_eq!(v.search_blocked(), None); + v.marked.insert(100); + assert!(v.search_blocked().is_some_and(|s| s.contains(tr( + "Keep no more than 100 selected; the filter is not used." + )))); + + // The inverse: a small filtered list does not enable 101 selected games, and + // clearing that choice brings back the old filter behaviour. + v.clear_marks(); + v.view = vec![0]; + assert_eq!(v.search_blocked(), None); + for r in 0..101 { + v.marked.insert(r); + } + assert!(v.search_blocked().is_some_and(|s| s.contains(tr( + "Keep no more than 100 selected; the filter is not used." + )))); + v.clear_marks(); + assert_eq!(v.search_blocked(), None); + + // A selected game hidden by an empty filtered result is still a valid source. + v.view.clear(); + assert!( + v.search_blocked() + .is_some_and(|s| s.contains(tr("No games match these conditions"))) + ); + v.marked.only(0); + assert_eq!(v.search_blocked(), None); + v.marked.clear(); + for r in 0..100 { + v.marked.insert(r); + } + assert_eq!(v.search_len(), 100); + assert_eq!(v.search_blocked(), None); + + // Until the current view is ready, k is unknown for either source. Overflow is + // already known and takes priority over that wait. + v.shown = None; + v.marked.insert(100); + assert!(v.search_blocked().is_some_and(|s| s.contains(tr( + "Keep no more than 100 selected; the filter is not used." + )))); + v.marked.remove(100); + assert!(v.search_blocked().is_some_and(|s| s.contains(tr( + "Wait: counting how many selected games are hidden by the current filter" + )))); + v.clear_marks(); + assert!( + v.search_blocked() + .is_some_and(|s| s.contains(tr("Wait: the games are still being filtered"))) + ); + } + + #[test] + fn the_search_request_snapshots_exactly_the_selected_ids_including_hidden_ones() { + let db = database("search-source", &["a", "b", "c", "d"]); + let mut v = ready_table(); + v.view = vec![0, 2]; + + // No choice: the previous source, the filtered table, is unchanged. + let (filtered, selected) = find_request(&mut v, &db); + assert_eq!(filtered, vec![0, 2]); + assert_eq!(selected, None); + + // Inserting the same ID twice cannot duplicate it. Records 1 and 3 are hidden + // by the current table, but belong to the request just like visible record 0. + for r in [0, 1, 3, 1] { + v.marked.insert(r); + } + let (snapshot, selected) = find_request(&mut v, &db); + assert_eq!(snapshot, vec![0, 1, 3]); + assert_eq!( + selected, + Some(crate::brilliant::SelectedGames { + games: 3, + hidden: 2, + }) + ); + + // Later selection, filter and sort changes do not mutate the sent Vec. A new + // request after clearing the selection uses the new filtered table again. + v.sort = (SortKey::Date, false); + v.marked.only(2); + v.view = vec![2]; + assert_eq!(snapshot, vec![0, 1, 3]); + assert_eq!( + selected, + Some(crate::brilliant::SelectedGames { + games: 3, + hidden: 2, + }) + ); + v.clear_marks(); + let (next, _) = find_request(&mut v, &db); + assert_eq!(next, vec![2]); + } + + #[test] + fn a_single_hidden_mark_survives_the_cursor_reset() { + let mut v = ready_table(); + v.marked.only(0); + v.selected = Some(0); + v.view.clear(); + v.clear_hidden_cursor(); + assert_eq!(v.selected, None); + assert_eq!(v.marked.records(), vec![0]); + assert_eq!(v.search_blocked(), None); + } + + #[test] + fn escape_keeps_one_selected_game_as_the_search_source() { + let db = database("search-escape", &["a", "b", "c"]); + let mut v = ready_table(); + v.view = vec![0, 1, 2]; + v.click(0, egui::Modifiers::NONE); + v.click(1, ctrl()); + v.click(2, ctrl()); + assert!(v.escape()); + assert_eq!(v.marked.len(), 1); + let (one, _) = find_request(&mut v, &db); + assert_eq!(one, vec![2]); + + // The existing Ctrl+Space gesture can clear that last mark; only then does the + // command return to the filtered table. + v.marked.toggle(2); + assert!(v.marked.is_empty()); + let (filtered, _) = find_request(&mut v, &db); + assert_eq!(filtered, vec![0, 1, 2]); + } + + #[test] + fn selection_hints_explain_hidden_games_and_the_independent_limit() { + let selected = crate::brilliant::SelectedGames { + games: 3, + hidden: 2, + }; + assert_eq!( + selected_search_hint(selected), + format!( + "{}\n{}", + trf( + "Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)", + &[("games", &crate::i18n::games(3))] + ), + trf( + "{k} hidden by the current filter; these games are included too.", + &[("k", &grouped(2))] + ) + ) + ); + assert!( + selected_search_hint(crate::brilliant::SelectedGames { + games: 1, + hidden: 0, + }) + .contains(tr("The filter does not change this run's games.")) + ); + let limit = selected_limit_hint(101); + assert!(limit.contains(&crate::i18n::games(101))); + assert!(limit.contains(tr( + "Keep no more than 100 selected; the filter is not used." + ))); + } + + #[test] + fn numbers_group_and_shorten() { + assert_eq!(grouped(11_741_260), "11\u{202f}741\u{202f}260"); + assert_eq!(grouped(999), "999"); + assert_eq!(short_count(49), "49"); + } + + #[test] + fn form_builds_valid_filters_only() { + let mut f = Form { + year_from: "2020".into(), + year_to: "2010".into(), + elo_min: "abc".into(), + eco: "B9".into(), + ..Form::default() + }; + let filter = f.filter(); + assert_eq!( + (filter.year_from, filter.year_to), + (None, None), + "from > to" + ); + assert_eq!(filter.elo_min, None); + assert_eq!(filter.eco, vec![(190, 199)]); + assert_eq!(filter.side, Side::Any); + f.year_to = "2024".into(); + assert_eq!(f.filter().year_to, Some(2024)); + assert_eq!(f.active(), 3); + } +} diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs new file mode 100644 index 0000000..47362d9 --- /dev/null +++ b/apps/desktop/src/lib.rs @@ -0,0 +1,203 @@ +//! ChessPenguin's window: the library, the game, analysis, play, preparation. +//! +//! One interface for two platforms. The desktop program (`src/main.rs`) starts it in a +//! native window ([`run_native`]); the web version (`apps/web`) in a page's canvas +//! ([`start_web`]). What differs between them — files, background work, storage, +//! dialogs, the clipboard — is behind [`platform`]. Features a platform does not have +//! are not built for it (`cfg(web)`: WebAssembly in a browser, set by `build.rs`), or, +//! where the interface only needs to know, hidden by [`platform::CAPS`]. The web build +//! compiles parts of the interface it never shows: what is unused there is the desktop +//! build's to find (the platform layer, [`platform`], is checked in both). +// (A browser's `std::fs::File` has no destructor: dropping one there is no closing.) +#![cfg_attr(web, allow(unused, clippy::drop_non_drop))] + +mod adjourned; +mod analysis; +mod app; +mod assets; +mod batch_copy; +mod board; +mod board_search; +mod brilliant; +mod brilliant_ui; +mod chatgpt; +mod db_counts; +mod engine_download; +mod engine_offer; +mod engines; +mod examples; +mod file_state; +mod game_link; +mod game_view; +#[cfg(not(web))] +mod graphics; +mod i18n; +mod large_db; +mod library; +mod maia_download; +#[cfg(web)] +mod my_games; +mod notation; +mod online; +#[cfg(not(web))] +mod online_ui; +#[cfg(not(web))] +mod opening_layout; +#[cfg(not(web))] +mod opening_lines; +#[cfg(not(web))] +mod opening_session; +mod own_db; +pub mod platform; +mod play; +mod player_games; +mod prep_saved; +mod prep_ui; +mod reference; +#[cfg(not(web))] +mod repertoire_ui; +mod review; +mod review_engine; +mod rodent4_download; +mod rodent_download; +mod san; +mod settings; +mod settings_ui; +mod sound; +mod translate; +mod translate_ui; +#[cfg(not(web))] +mod update; +#[cfg(not(web))] +mod update_ui; +mod viewed; +mod widgets; + +/// Learning an opening: shared with the Android app. +use trainer as train; + +/// The web version in the page's `canvas`: the program's data is read from the +/// browser's storage first, then the interface starts. `lang`: the language the page +/// was opened in (`?lang=` of the site's link), over the one chosen before. +#[cfg(web)] +pub async fn start_web( + canvas: web_sys::HtmlCanvasElement, + lang: Option, +) -> Result<(), wasm_bindgen::JsValue> { + platform::web::vfs::load().await; + platform::web::remembered::restore().await; + platform::web::engine::probe().await; + platform::web::storage::refresh(|| {}); + let mut settings = settings::Settings::load(); + if let Some(chosen) = lang.as_deref().and_then(i18n::Lang::from_locale) + && chosen != settings.language + { + settings.language = chosen; + let _ = settings.save(); + } + i18n::set_lang(settings.language); + eframe::WebRunner::new() + .start( + canvas, + eframe::WebOptions::default(), + Box::new(|cc| { + assets::install(&cc.egui_ctx); + Ok(Box::new(app::App::new(&cc.egui_ctx))) + }), + ) + .await +} + +/// The page's reader (`import-worker.js`, a worker with an instance of its own): takes +/// the files of a database one by one ([`reader_give`]), reads it and answers with its +/// text and index, or only how many games it holds (`count`; `platform::web::import`). +#[cfg(web)] +pub fn reader_give(name: String, bytes: Vec) { + platform::web::import::give(name, bytes); +} + +#[cfg(web)] +pub fn reader_read(count: bool) -> wasm_bindgen::JsValue { + platform::web::import::answer(count) +} + +/// The desktop program: `chesspenguin [--bench [report.txt]]`. +#[cfg(not(web))] +pub fn run_native() -> eframe::Result { + // `chesspenguin --bench [report.txt]`: timings instead of the window + // (`docs/dev/import.md`, "Замер на другой машине"). + let args: Vec = std::env::args_os().skip(1).collect(); + if args.first().is_some_and(|a| a == "--bench") { + let Some(db) = args.get(1) else { + eprintln!("usage: chesspenguin --bench [report.txt]"); + std::process::exit(2); + }; + let cache = settings::Settings::cache_dir().map(|d| d.join("boosters")); + let result = match args.get(2) { + Some(file) => std::fs::File::create(file) + .and_then(|mut f| chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut f)), + None => chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut std::io::stdout()), + }; + if let Err(e) = result { + eprintln!("bench: {e}"); + std::process::exit(1); + } + return Ok(()); + } + crate::i18n::set_lang(settings::Settings::load().language); + // The runs of the opening trainer (`CP_TRAINING_FILE` elsewhere: development). + if let Some(file) = std::env::var_os("CP_TRAINING_FILE") + .map(std::path::PathBuf::from) + .or_else(|| { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("training.json")) + }) + { + train::set_file(file); + } + graphics::install_panic_hook(); + graphics::init_library_log(); + let mode = graphics::choose(); + let mut viewport = egui::ViewportBuilder::default() + .with_app_id("io.github.vrubelroman.chessPenguin") + .with_title("ChessPenguin") + .with_inner_size([1400.0, 900.0]) + .with_min_inner_size([640.0, 480.0]) + // X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id. + .with_icon( + eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png")) + .unwrap_or_default(), + ); + if let Some((width, height)) = std::env::var("CP_SCREENSHOT_SIZE").ok().and_then(|size| { + let (width, height) = size.split_once('x')?; + Some((width.parse::().ok()?, height.parse::().ok()?)) + }) { + viewport = viewport + .with_inner_size([width, height]) + .with_min_inner_size([width, height]) + .with_max_inner_size([width, height]) + .with_resizable(false) + .with_fullscreen(false) + .with_maximized(false); + } + let options = eframe::NativeOptions { + viewport, + wgpu_options: graphics::options(mode), + ..Default::default() + }; + let result = eframe::run_native( + "ChessPenguin", + options, + Box::new(|cc| { + assets::install(&cc.egui_ctx); + Ok(Box::new(app::App::new(&cc.egui_ctx))) + }), + ); + if let Err(e) = &result { + if graphics::retry(&e.to_string()) { + return Ok(()); + } + graphics::fatal(&e.to_string()); + } + result +} diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs new file mode 100644 index 0000000..85c51d3 --- /dev/null +++ b/apps/desktop/src/library.rs @@ -0,0 +1,2055 @@ +//! Library screen: shelf of databases (PGN, ChessBase, archives) and, for the chosen +//! one, the game table with its filters and position search (`large_db.rs`). + +use crate::i18n::{tr, trf}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; +use std::sync::{Arc, Mutex}; + +use chess_core::ScanProgress; +use chess_import::{Database, Format, ImportError, Opened, Unsupported}; +use egui::{RichText, Sense, Ui, vec2}; + +use crate::large_db::{self, Header, LargeView, OnlineButton, Pane}; +use crate::settings::Settings; +use crate::viewed::{self, Viewed}; + +enum Slot { + Loading { + progress: Arc>, + cancel: Arc, + rx: Receiver>, + }, + Ready(Arc), + Failed(String), +} + +pub enum LibraryAction { + /// Open a game; `at`: show the first position equal to this one. + OpenGame { + path: PathBuf, + index: usize, + at: Option, + }, + Sound(crate::assets::Sound), + CopyText(String, &'static str), + /// Open PGN text as a new game. + OpenPgn(String), + NewGame, + /// A game against Maia: the play dialog. + Play, + /// The game put aside: go on with it, or let it go (adjourned.rs). + ResumeAside, + DiscardAside, + /// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there. + NewGameIn(PathBuf), + PastePgn, + AddDatabases, + /// The window for downloading games from Lichess and Chess.com. + #[cfg(not(web))] + OnlineGames, + /// Fetch the new games of an online database. + #[cfg(not(web))] + UpdateOnline(PathBuf), + /// The window offering a newer version. + #[cfg(not(web))] + OpenUpdate, + RemoveDatabase(PathBuf), + /// A file the browser held for the last visit only: choose it again, the new one + /// taking its place on the shelf. + ChooseAgain(PathBuf), + /// Let the page read the remembered file again (the browser asks the user). + #[cfg(web)] + AllowReading(PathBuf), + /// Choose the folder of the ChessBase database whose `.cbh` alone is there. + #[cfg(web)] + ChooseFolderAgain(PathBuf), + /// Keep a copy of a file in the browser (it opens then without choosing it). + KeepCopy(PathBuf), + OpenSettings, + /// A new, empty PGN database (own-databases.md §2). + NewDatabase, + /// A UTF-8 copy of a PGN in a legacy encoding, which can take games. + Utf8Copy(PathBuf), + /// A record of a table: delete it, add a copy of it to another database, open it + /// with its data for editing. + DeleteGame { + path: PathBuf, + index: usize, + }, + AddGameToDatabase { + path: PathBuf, + index: usize, + }, + /// «New database from selected…»: the chosen records (by number) of `path`, the + /// table's order, how many of them the filter hides (task 42). + CopySelection { + path: PathBuf, + records: Vec, + sort: chess_import::chessbase::base::SortKey, + ascending: bool, + hidden: usize, + }, + /// A short message (a toast). + Notice(String), + /// Open a game at the position `at` with its report shown (a move the search for + /// great moves found). + OpenGameReport { + path: PathBuf, + index: usize, + at: Option, + }, + /// «!! Find great moves» over the list `records` of `path` (in the table's order), + /// found by `filter` (task 27). + FindGreatMoves { + path: PathBuf, + records: Vec, + filter: chess_import::chessbase::base::Filter, + /// The conditions in words, for a filtered question and summary. + about: String, + /// The manual source and its hidden count, fixed with `records`. + selected: Option, + }, + EditGameData { + path: PathBuf, + index: usize, + }, + /// «ðŸ—� Preparations»: the saved preparations against opponents. + Preparations, + #[cfg(not(web))] + OpeningTraining, + /// «Prepare against…» for a player of this database (opponent-prep.md §2). + PrepareAgainst { + path: PathBuf, + entry: crate::prep_ui::PrepEntry, + }, +} + +/// How a database was imported, and what is worth knowing about it. +struct ImportInfo { + format: Format, + notes: Vec, +} + +fn text_w(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { + ui.painter() + .layout_no_wrap( + text.to_owned(), + style.resolve(ui.style()), + egui::Color32::WHITE, + ) + .size() + .x +} + +fn button_w(ui: &Ui, text: &str) -> f32 { + text_w(ui, text, egui::TextStyle::Button) + + 2.0 * ui.spacing().button_padding.x + + ui.spacing().item_spacing.x +} + +// Toolbar contents change as background probes finish and the window narrows. +// Keep action IDs independent of the preceding widgets: egui buttons resolve +// their visual state from the previous frame's response before being allocated. +fn shelf_button(ui: &mut Ui, id: &str, label: impl Into) -> egui::Response { + ui.push_id(id, |ui| ui.button(label)).inner +} + +/// A PGN file whose beginning is in a legacy (single-byte) encoding: it takes games only +/// through a UTF-8 copy. For a file not read yet (its card's menu). +fn legacy_pgn(path: &Path) -> bool { + let pgn = path + .extension() + .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("pgn")); + if !pgn || crate::online::is_online(path) || crate::examples::is_example(path) { + return false; + } + let Ok(head) = crate::platform::fs::read_head(path, 64 << 10) else { + return false; + }; + let guess = chess_core::detect_encoding(&head); + guess.encoding != chess_core::TextEncoding::Utf8 && !guess.ascii_only +} + +/// The width of the game buttons, «Play» and the program's ones +/// (`Library::game_buttons`, `Library::play_button`, `Library::app_buttons`), with +/// the two lines between the groups. +fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 { + let texts: [&str; 4] = if icons { + ["âš™", "📋", "♟", "♞"] + } else { + [ + tr("âš™ Settings"), + tr("📋 Paste PGN"), + tr("♟ New game"), + tr("♞ Play"), + ] + }; + let play = crate::platform::CAPS.play; + let prep = crate::platform::CAPS.prep; + let training = crate::platform::CAPS.training; + let groups = 1.0 + f32::from(u8::from(play)) + f32::from(u8::from(prep || training)); + texts[..if play { 4 } else { 3 }] + .iter() + .map(|t| button_w(ui, t)) + .sum::() + + if prep { + button_w( + ui, + if icons { + "ðŸ—�" + } else { + tr("ðŸ—� Preparations") + }, + ) + } else { + 0.0 + } + + if training { + button_w(ui, tr("Opening training (α version)")) + } else { + 0.0 + } + + update.map_or(0.0, |v| button_w(ui, v)) + + groups * GROUP_GAP +} + +/// A shelf button's tooltip: with icons only, its name first. +/// What was pressed on the card of a game put aside, as the library's action. +fn push_pressed(p: Option, actions: &mut Vec) { + match p { + Some(crate::adjourned::Pressed::Continue) => actions.push(LibraryAction::ResumeAside), + Some(crate::adjourned::Pressed::Discard) => actions.push(LibraryAction::DiscardAside), + None => {} + } +} + +fn shelf_hint(icons: bool, full: &str, hint: &str) -> String { + if icons { + format!( + "{}\n{hint}", + full.trim_start_matches(|c: char| !c.is_alphabetic()) + ) + } else { + hint.to_owned() + } +} + +/// Between the database actions and the game ones in the title row. +const GROUP_GAP: f32 = 16.0; + +/// The shelf's "+ Add database", "✚ New database" and "Online games" cards: 150 wide, +/// wider when their label needs it (some languages say it longer). +fn side_card_widths(ui: &Ui) -> (f32, f32, f32) { + let w = |t: &str, size: f32| { + ui.painter() + .layout_no_wrap( + t.to_owned(), + egui::FontId::proportional(size), + egui::Color32::WHITE, + ) + .size() + .x + }; + let fit = |inner: f32| (inner + 32.0).max(150.0).ceil(); + ( + fit(w(tr("+ Add database"), 15.0)), + fit(w(tr("✚ New database"), 15.0)), + fit(w(&format!("ðŸŒ� {}", tr("Online games")), 15.0).max(w("Lichess · Chess.com", 13.0))), + ) +} + +/// The least widths of the panels beside the table (narrow-windows.md §1). +const FILTERS_MIN: f32 = 260.0; +const SEARCH_BOARD_MIN: f32 = 340.0; + +pub struct Library { + slots: HashMap, + /// The files as last found, away from the frame (a lost network drive must not hold + /// the window). + pub files: crate::file_state::FileStates, + /// The players' databases (player_games.rs) and whose: a knight on their cards. + player_dbs: Vec<(PathBuf, String)>, + /// Games the user has opened (by content). + viewed: Viewed, + /// Filters, quick search, position and game list of each database (for the session). + large: HashMap, + /// A position from a game to show once its database is open. + pending_position: Option<(PathBuf, shakmaty::Chess, Vec, bool)>, + info: HashMap, + /// Database whose import notes are shown. + notes_open: Option, + pub selected_db: Option, + /// Network probe availability for updating an existing online database. + /// The main toolbar is always available according to platform capabilities. + pub online: bool, + /// Online databases being downloaded or updated. + pub online_busy: Vec, + /// Games downloaded so far while downloads run (shown on the shelf card). + pub online_running: Option, + /// A newer version to offer (its number), next to Settings. + pub update: Option, + /// The card of the game put aside, on the shelf. + pub aside: Option, + /// The games of the databases not opened, for their cards. + counts: crate::db_counts::Counts, + /// Chosen records being copied into a new database (one copy at a time). + batch: Option, + /// The marks of great moves of each database (task 27), read once per session. + marks: HashMap>>, + /// The search for great moves under way (one engine job in the program). + pub pass: Option, +} + +/// A copy of chosen records into a new database, written in the background. +struct BatchJob { + source: PathBuf, + target: PathBuf, + total: usize, + work: crate::board_search::Background< + Result, + >, + cancelling: bool, +} + +/// How a copy of chosen records ended. +pub enum BatchEnd { + Done { + target: PathBuf, + report: crate::batch_copy::CopyReport, + }, + Cancelled { + target: PathBuf, + }, + Failed { + source: PathBuf, + target: PathBuf, + error: crate::batch_copy::CopyError, + }, +} + +impl Library { + pub fn new(ctx: &egui::Context) -> Self { + Self { + slots: HashMap::new(), + files: crate::file_state::FileStates::new(), + player_dbs: Vec::new(), + viewed: Viewed::load(), + large: HashMap::new(), + pending_position: None, + info: HashMap::new(), + notes_open: None, + selected_db: None, + online: false, + online_busy: Vec::new(), + online_running: None, + update: None, + aside: None, + counts: crate::db_counts::Counts::new(ctx), + batch: None, + marks: HashMap::new(), + pass: None, + } + } + + /// The marks of great moves of the database at `path`. + pub fn marks(&mut self, path: &Path) -> Arc> { + self.marks + .entry(path.to_path_buf()) + .or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(path)))) + .clone() + } + + /// The search under way, as each database's conditions line shows it; «Stop» of + /// any of them stops it. Called every frame. + pub fn show_pass(&mut self, estimate: impl Fn(&[u32]) -> f64) { + let status = self.pass.as_ref().map(|job| { + ( + job.source.clone(), + crate::own_db::base_name(&job.source), + job.selected, + job.done(), + job.records.len(), + job.current(), + job.left_secs(&estimate), + job.stopping, + ) + }); + let mut stop = false; + for (path, view) in self.large.iter_mut() { + view.pass = status.as_ref().map( + |(source, name, selected, done, total, current, left, stopping)| { + large_db::PassStatus { + here: source == path, + name: name.clone(), + selected: *selected, + done: *done, + total: *total, + current: *current, + left_secs: *left, + stopping: *stopping, + } + }, + ); + stop |= std::mem::take(&mut view.stop_pass); + } + if stop && let Some(job) = self.pass.as_mut() { + job.stop(); + } + } + + /// Why the search may not start now (the engine is busy elsewhere), for every + /// database's button. + pub fn set_engine_busy(&mut self, why: Option) { + for view in self.large.values_mut() { + view.engine_busy = why.clone(); + } + } + + /// Why the last search in `path` stopped with an error, where its progress was. + pub fn set_pass_error(&mut self, path: &Path, text: Option) { + if let Some(view) = self.large.get_mut(path) { + view.pass_error = text; + } + } + + /// Starts copying `records` of `source` into the new file `target` (none while + /// another copy is written). `false`: the source is not read or the thread did not + /// start. + pub fn start_batch( + &mut self, + ctx: &egui::Context, + source: &Path, + records: Vec, + sort: chess_import::chessbase::base::SortKey, + ascending: bool, + target: PathBuf, + ) -> bool { + if self.batch.is_some() { + return false; + } + let Some(db) = self.database(source) else { + return false; + }; + let total = records.len(); + let req = crate::batch_copy::CopyRequest { + records, + sort, + ascending, + target: target.clone(), + slow: std::env::var_os("CP_BATCH_SLOW").is_some(), + }; + let now = ctx.input(|i| i.time); + let Some(work) = crate::board_search::Background::spawn(ctx, now, move |p, c| { + crate::batch_copy::copy_into_new(&db, &req, p, c) + }) else { + return false; + }; + if let Some(view) = self.large.get_mut(source) { + view.batch_error = None; + } + self.batch = Some(BatchJob { + source: source.to_path_buf(), + target, + total, + work, + cancelling: false, + }); + true + } + + /// Why the copy from `path` wrote nothing, said where its progress was. + pub fn set_batch_error(&mut self, path: &Path, text: String) { + if let Some(view) = self.large.get_mut(path) { + view.batch_error = Some(text); + } + } + + /// The chosen records of `path` let go (their numbers no longer mean the same games). + pub fn clear_selection(&mut self, path: &Path) { + if let Some(view) = self.large.get_mut(path) { + view.clear_marks(); + } + } + + /// Asks the copy being written to stop. + pub fn cancel_batch(&mut self) { + if let Some(job) = &mut self.batch { + job.work.cancel(); + job.cancelling = true; + } + } + + /// Stops the copy being written and waits a little for it to clean up (closing the + /// program): its temporary file goes, no new database appears. + pub fn stop_batch(&mut self) { + if let Some(job) = self.batch.take() { + job.work.cancel(); + job.work.wait(std::time::Duration::from_secs(3)); + } + } + + /// The end of the copy being written, once it came (called every frame, whatever is + /// on the screen); while it runs the source's conditions line shows it. + pub fn poll_batch(&mut self, ctx: &egui::Context) -> Option { + let job = self.batch.as_ref()?; + // `CP_BATCH_CANCEL_AFTER=`: «Cancel» pressed that long after the start (checks, + // screenshots of the cancelling). + let cancel_after = std::env::var("CP_BATCH_CANCEL_AFTER") + .ok() + .and_then(|ms| ms.parse::().ok()); + if let Some(ms) = cancel_after + && !job.cancelling + && ctx.input(|i| i.time) - job.work.started >= ms / 1000.0 + { + self.cancel_batch(); + } + let job = self.batch.as_ref()?; + let Some(result) = job.work.poll() else { + let status = large_db::BatchStatus { + name: crate::own_db::base_name(&job.target), + done: job.work.progress(), + total: job.total, + cancelling: job.cancelling, + }; + let source = job.source.clone(); + let mut cancel = false; + if let Some(view) = self.large.get_mut(&source) { + cancel = std::mem::take(&mut view.cancel_batch); + view.batch = Some(status); + } + if cancel { + self.cancel_batch(); + } + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return None; + }; + let job = self.batch.take()?; + if let Some(view) = self.large.get_mut(&job.source) { + view.batch = None; + view.cancel_batch = false; + } + Some(match result { + None => BatchEnd::Cancelled { target: job.target }, + Some(Ok(report)) => BatchEnd::Done { + target: job.target, + report, + }, + Some(Err(error)) => BatchEnd::Failed { + source: job.source, + target: job.target, + error, + }, + }) + } + + /// Starts loading `path` in the background (no-op if already loaded/loading). + pub fn load(&mut self, path: &Path, ctx: &egui::Context) { + if matches!( + self.slots.get(path), + Some(Slot::Loading { .. } | Slot::Ready(_)) + ) { + return; + } + let progress = Arc::new(Mutex::new(ScanProgress { + bytes_done: 0, + bytes_total: 0, + games: 0, + })); + let cancel = Arc::new(AtomicBool::new(false)); + let (tx, rx) = channel(); + let (p, ctx, wake) = (progress.clone(), ctx.clone(), ctx.clone()); + let spawned = crate::platform::open_database( + path, + move |sp| { + if let Ok(mut g) = p.lock() { + *g = sp; + } + wake.request_repaint(); + }, + cancel.clone(), + move |res| { + // The filters' index of a PGN is built here, not on the screen's thread + // (a large download takes a second, §9.7; in a browser, which reads + // smaller files, it is the page's thread). + if let Ok(opened) = &res + && let Database::Pgn(pgn) = &opened.db + { + pgn.catalog(); + } + let _ = tx.send(res); + ctx.request_repaint(); + }, + ); + let slot = match spawned { + Ok(_) => Slot::Loading { + progress, + cancel, + rx, + }, + Err(e) => Slot::Failed(e.to_string()), + }; + self.slots.insert(path.to_path_buf(), slot); + } + + pub fn select_db(&mut self, path: &Path, ctx: &egui::Context) { + self.load(path, ctx); + if self.selected_db.as_deref() != Some(path) { + self.selected_db = Some(path.to_path_buf()); + } + } + + /// Chooses the row of `index` alone (any choice of several let go) and scrolls to it. + pub fn choose_only(&mut self, path: &Path, index: usize) { + if let Some(view) = self.large.get_mut(path) { + view.clear_marks(); + view.reveal(index); + } + } + + /// Sorts the table of `path` by its «!!» column. + pub fn sort_by_marks(&mut self, path: &Path) { + if let Some(view) = self.large.get_mut(path) { + view.sort_marks_on(); + } + } + + /// Selects (and scrolls to) a game row, e.g. when returning from a game. + pub fn reveal(&mut self, path: &Path, index: usize) { + if let Some(view) = self.large.get_mut(path) { + view.reveal(index); + } + } + + /// Reads a database again (its file changed), keeping it selected if it was. + pub fn reload(&mut self, path: &Path, ctx: &egui::Context) { + let selected = self.selected_db.as_deref() == Some(path); + // The conditions, the position, the sort and the selection stay (§9.7): the view + // finds its list anew once the file is read. + let mut view = self.large.remove(path); + if let (Some(v), Some(db)) = (view.as_mut(), self.database(path)) { + v.before_reread(&db); + } + self.forget(path); + if let Some(v) = view { + self.large.insert(path.to_path_buf(), v); + } + if selected { + self.select_db(path, ctx); + } else { + self.load(path, ctx); + } + } + + /// Why a database on the shelf cannot take games (own-databases.md §5); `None`: a + /// PGN that can. + pub fn write_block(&self, path: &Path) -> Option { + use crate::own_db::Block; + if crate::online::is_online(path) { + return Some(Block::Online); + } + if crate::examples::is_example(path) { + return Some(Block::Example); + } + // In a browser the user's files are only read. + if cfg!(web) && crate::platform::fs::meta(path).is_ok_and(|m| m.readonly) { + return Some(Block::ReadOnly); + } + if !self.files.exists(path) { + return Some(Block::Missing); + } + match self.info.get(path).map(|i| i.format) { + Some(Format::Pgn) => {} + Some(_) => return Some(Block::ReadOnly), + None => { + let pgn = path + .extension() + .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("pgn")); + if !pgn { + return Some(Block::ReadOnly); + } + } + } + if let Some(db) = self.database(path) { + match db.as_pgn() { + Some(p) => { + let enc = p.encoding(); + if enc != chess_core::TextEncoding::Utf8 && !p.detected_encoding().ascii_only { + return Some(Block::Encoding(enc.label())); + } + } + None => return Some(Block::ReadOnly), + } + } + if self.files.get(path).is_some_and(|s| s.readonly) { + return Some(Block::NoPermission); + } + None + } + + pub fn forget(&mut self, path: &Path) { + self.info.remove(path); + self.large.remove(path); + if let Some(Slot::Loading { cancel, .. }) = self.slots.remove(path) { + cancel.store(true, Ordering::Relaxed); + } + if self.selected_db.as_deref() == Some(path) { + self.selected_db = None; + } + } + + /// Remembers that a game was opened (shown with a check mark in the table). + pub fn mark_viewed(&mut self, path: &Path, index: usize) { + if let Some(db) = self.database(path) { + self.viewed.set(viewed::key(db.identity(index)), true); + } + } + + /// Size of a database's file (as last found; asked every frame by the reference tab). + pub fn file_size(&self, path: &Path) -> u64 { + self.files.get(path).map_or(0, |s| s.size) + } + + /// The database is being read now. + pub fn loading(&self, path: &Path) -> bool { + matches!(self.slots.get(path), Some(Slot::Loading { .. })) + } + + /// Why the database could not be opened, if it could not. + pub fn failure(&self, path: &Path) -> Option<&str> { + match self.slots.get(path) { + Some(Slot::Failed(e)) => Some(e.as_str()), + _ => None, + } + } + + pub fn database(&self, path: &Path) -> Option> { + match self.slots.get(path) { + Some(Slot::Ready(db)) => Some(db.clone()), + _ => None, + } + } + + /// Takes the databases that finished opening (also while a game is shown). + pub fn poll(&mut self) { + for (path, slot) in self.slots.iter_mut() { + if let Slot::Loading { rx, .. } = slot + && let Ok(res) = rx.try_recv() + { + *slot = match res { + Ok(o) => { + // Every database has the filters and the position search. + match self.large.get_mut(path) { + Some(view) => view.reread(&o.db), + None => { + let online = crate::online::is_online(path); + self.large + .insert(path.clone(), LargeView::for_database(&o.db, online)); + } + } + self.info.insert( + path.clone(), + ImportInfo { + format: o.format, + notes: o.notes, + }, + ); + // Position searches without a usable `.cbb` get our own + // booster, kept in the cache directory. + if let Database::ChessBase(b) = &o.db + && let Some(dir) = Settings::cache_dir() + { + b.set_booster_dir(&dir.join("boosters")); + } + self.counts.opened(path, &o.db); + Slot::Ready(Arc::new(o.db)) + } + Err(e) => Slot::Failed(import_error(&e)), + }; + } + } + self.apply_pending_position(); + } + + /// Shows the board of the large database `path` with `line` played from `start` + /// (a position taken from a game). False if the database is not a large one. + pub fn show_position( + &mut self, + path: &Path, + start: shakmaty::Chess, + line: Vec, + flipped: bool, + ctx: &egui::Context, + ) -> bool { + self.select_db(path, ctx); + self.pending_position = Some((path.to_path_buf(), start, line, flipped)); + self.apply_pending_position(); + true + } + + /// Shows a requested position once its database is open. + fn apply_pending_position(&mut self) { + let Some((path, ..)) = &self.pending_position else { + return; + }; + let Some(Slot::Ready(db)) = self.slots.get(path) else { + return; + }; + let db = db.clone(); + let (path, start, line, flipped) = self.pending_position.take().expect("pending"); + let online = crate::online::is_online(&path); + let view = self + .large + .entry(path) + .or_insert_with(|| LargeView::for_database(&db, online)); + view.show_position(start, line, flipped); + } + + pub fn show( + &mut self, + ui: &mut Ui, + databases: &[PathBuf], + settings: &Settings, + ) -> Vec { + self.poll(); + self.player_dbs = settings + .players + .iter() + .filter_map(|p| Some((p.path.clone()?, p.name.clone()))) + .collect(); + let mut actions = Vec::new(); + // A field had the keyboard when this frame began: its Escape is its own. + let typing = ui.ctx().egui_wants_keyboard_input(); + let width = ui.available_width(); + let height = ui.ctx().content_rect().height(); + // The shelf folds into one line when its cards would take more than two rows, in + // a low window, and with the search board open in a window under 760. + let board_open = self + .selected_db + .as_ref() + .is_some_and(|p| self.large.get(p).is_some_and(|v| v.pane() == Pane::Board)); + // The shelf's rows hold the databases only (their actions are in the title row). + let cards = databases.len(); + // The card of a game put aside stands right of the databases (they wrap beside + // it), or above them when not even one fits beside it. + let cards_width = match &self.aside { + Some(card) if width - 16.0 - card.width(ui) - 24.0 >= 190.0 => { + width - card.width(ui) - 24.0 + } + _ => width, + }; + let card_rows = { + let mut rows = 1; + let mut x = 0.0; + for _ in 0..cards { + let w = 190.0; + if x > 0.0 && x + w > cards_width - 16.0 { + rows += 1; + x = 0.0; + } + x += w + 8.0; + } + rows + }; + if card_rows > 2 || height < 600.0 || (board_open && height < 760.0) { + egui::Panel::top("shelf_compact").show(ui, |ui| { + self.compact_shelf(ui, databases, settings, &mut actions) + }); + } else { + egui::Panel::top("shelf") + .show(ui, |ui| self.shelf(ui, databases, settings, &mut actions)); + } + // A database has its filter panel or its search board on the right, when the + // window leaves the table its least width beside them (narrow-windows.md §2.1); + // otherwise the filters open over the table and the board takes its place. + let mut drawer = None; + if let Some(path) = self.selected_db.clone() + && let Some(Slot::Ready(db)) = self.slots.get(&path) + && let Some(view) = self.large.get_mut(&path) + { + let db = db.clone(); + let table_min = view.table_min_width(&db, false); + let table_min_pos = view.table_min_width(&db, true); + view.set_layout( + width < table_min + FILTERS_MIN, + width < table_min_pos + SEARCH_BOARD_MIN, + ); + // An empty database has nothing to filter: no panel beside it. + let empty = db.games() + db.texts() == 0; + match view.pane() { + _ if empty => {} + Pane::Filters if view.drawer().is_none() && width >= table_min + FILTERS_MIN => { + let r = egui::Panel::right("filters") + .resizable(true) + .default_size(280.0) + .size_range(FILTERS_MIN..=(width - table_min).floor().min(380.0)) + .show(ui, |ui| view.panel(ui, &db)); + crate::widgets::check_panel("filters", &r.response); + } + Pane::Board if !view.board_alone() => { + let most = (width - table_min_pos).floor().max(SEARCH_BOARD_MIN); + let r = egui::Panel::right("search_board") + .resizable(true) + .default_size((width * 0.5).clamp(SEARCH_BOARD_MIN, most)) + .size_range(SEARCH_BOARD_MIN..=most) + .show(ui, |ui| view.board_panel(ui, &db, settings, &mut actions)); + crate::widgets::check_panel("search_board", &r.response); + } + _ => {} + } + drawer = view.drawer().map(|top| (path, db, top)); + } + egui::CentralPanel::default().show(ui, |ui| self.table_area(ui, settings, &mut actions)); + // The filters over the table: on its right edge under its header, with a shadow; + // the table stays live. A click elsewhere closes them (and does what it does). + if let Some((path, db, top)) = drawer + && let Some(view) = self.large.get_mut(&path) + { + let screen = ui.ctx().content_rect(); + // As wide as the filters beside the table were left (a strip of the + // table stays visible to click). + let stored = + egui::containers::panel::PanelState::load(ui.ctx(), egui::Id::new("filters")) + .map_or(280.0, |p| p.size().x); + let size = vec2( + stored.clamp(FILTERS_MIN, 380.0).min(width - 48.0), + screen.bottom() - top, + ); + let rect = egui::Rect::from_min_size(egui::pos2(screen.right() - size.x, top), size); + let area = egui::Area::new(egui::Id::new("filters_drawer")) + .order(egui::Order::Middle) + .fixed_pos(rect.min) + .show(ui.ctx(), |ui| { + let frame = egui::Frame::side_top_panel(ui.style()) + .stroke(ui.visuals().window_stroke) + // To the left, over the list (the window's own shadow falls + // right and down, off the window). + .shadow(egui::Shadow { + offset: [-6, 0], + blur: 16, + spread: 0, + color: egui::Color32::from_black_alpha(110), + }); + frame.show(ui, |ui| { + let inner = rect.shrink2(frame.total_margin().sum() / 2.0); + ui.set_min_size(inner.size()); + ui.set_max_size(inner.size()); + view.panel(ui, &db); + }); + }); + if area.response.clicked_elsewhere() { + view.close_drawer_on_click(); + } + } + // Escape: the filters over the table close, then the board alone gives the place + // back to the table (a field takes its own Escape first). + if !typing + && !crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) + && let Some(path) = self.selected_db.clone() + && let Some(view) = self.large.get_mut(&path) + && ui.input(|i| i.key_pressed(egui::Key::Escape)) + && view.escape() + { + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); + } + for view in self.large.values_mut() { + if let Some(text) = view.notice.take() { + actions.push(LibraryAction::Notice(text)); + } + } + if let Some(path) = self.selected_db.clone() + && let Some(view) = self.large.get_mut(&path) + && let Some(entry) = view.prepare.take() + && crate::platform::CAPS.prep + { + actions.push(LibraryAction::PrepareAgainst { path, entry }); + } + self.notes_window(ui.ctx()); + actions + } + + /// Ctrl+Shift+P: the chosen database (when it is read) and the player of its + /// filter, if one is set. + pub fn prep_entry(&self) -> Option<(PathBuf, Option)> { + let path = self.selected_db.clone()?; + if !matches!(self.slots.get(&path), Some(Slot::Ready(_))) { + return None; + } + Some(( + path.clone(), + self.large.get(&path).and_then(|v| v.prep_entry()), + )) + } + + fn notes_window(&mut self, ctx: &egui::Context) { + let Some(path) = self.notes_open.clone() else { + return; + }; + let Some(info) = self.info.get(&path) else { + self.notes_open = None; + return; + }; + let mut open = true; + egui::Window::new(tr("Import notes")) + .open(&mut open) + .default_width(560.0) + .show(ctx, |ui| { + ui.label( + RichText::new(tr( + "Everything else was read. Games listed here are shown as far as they could be decoded.", + )) + .weak(), + ); + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| { + for n in &info.notes { + ui.label(format!("• {n}")); + } + }); + }); + if !open { + self.notes_open = None; + } + } + + /// The shelf as one line: a database picker, "+" and the usual buttons. + fn compact_shelf( + &mut self, + ui: &mut Ui, + databases: &[PathBuf], + settings: &Settings, + actions: &mut Vec, + ) { + let name = |p: &Path| { + p.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + }; + // The list of databases gives way first (to 180), then the buttons on the right + // show their icons, then the list goes down to 140 (narrow-windows.md §2.5). + let gap = ui.spacing().item_spacing.x; + let others = self.shelf_actions_w(ui, true) + 16.0; + let free = ui.available_width() - others; + let icons = free - shelf_buttons_w(ui, self.update.as_deref(), false) < 180.0 + gap; + let list = (free - shelf_buttons_w(ui, self.update.as_deref(), icons) - gap) + .clamp(140.0, 260.0) + .floor(); + ui.horizontal(|ui| { + let current = self.selected_db.as_deref().map(name).unwrap_or_default(); + let mut pick = None; + let icon = match self.selected_db.as_deref() { + Some(p) if self.player_dbs.iter().any(|(q, _)| q == p) => "♞", + _ => "🗄", + }; + egui::ComboBox::from_id_salt("shelf_db") + .selected_text(format!("{icon} {current}")) + .width(list) + .truncate() + .show_ui(ui, |ui| { + for p in databases { + if ui + .selectable_label(self.selected_db.as_deref() == Some(p), name(p)) + .clicked() + { + pick = Some(p.clone()); + } + } + }); + if let Some(p) = pick { + self.select_db(&p, ui.ctx()); + } + self.groups(ui, true, icons, actions); + ui.scope_builder( + egui::UiBuilder::new() + .id_salt("shelf_app_actions") + .layout(egui::Layout::right_to_left(egui::Align::Center)), + |ui| self.app_buttons(ui, icons, actions), + ); + }); + // The game put aside: a strip under the line. + if let Some(card) = &self.aside { + ui.add_space(4.0); + push_pressed(card.strip(ui, settings), actions); + ui.add_space(4.0); + } + } + + /// "âš™ Settings" and the newer version (right to left): the program's corner, the + /// same as on the game screen. Icons only, with the names in the tooltips. + fn app_buttons(&self, ui: &mut Ui, icons: bool, actions: &mut Vec) { + if crate::widgets::settings_button(ui, icons).clicked() { + actions.push(LibraryAction::OpenSettings); + } + #[cfg(not(web))] + if let Some(v) = &self.update + && crate::widgets::update_button(ui, v).clicked() + { + actions.push(LibraryAction::OpenUpdate); + } + } + + /// The three groups of the title row, apart by a line: the databases (add, new, + /// online games) | a game to enter (new, paste) | play against Maia. + fn groups(&self, ui: &mut Ui, folded: bool, icons: bool, actions: &mut Vec) { + self.shelf_actions(ui, folded, actions); + ui.separator(); + self.game_buttons(ui, icons, actions); + if crate::platform::CAPS.play { + ui.separator(); + self.play_button(ui, icons, actions); + } + if crate::platform::CAPS.prep { + ui.separator(); + let label = if icons { + "ðŸ—�" + } else { + tr("ðŸ—� Preparations") + }; + if shelf_button(ui, "preparations", label) + .on_hover_text(shelf_hint( + icons, + tr("ðŸ—� Preparations"), + tr("Preparations against opponents: the saved ones and a new one"), + )) + .clicked() + { + actions.push(LibraryAction::Preparations); + } + } + #[cfg(not(web))] + if crate::platform::CAPS.training { + if !crate::platform::CAPS.prep { + ui.separator(); + } + if shelf_button(ui, "opening_training", tr("Opening training (α version)")).clicked() { + actions.push(LibraryAction::OpeningTraining); + } + } + } + + /// "♞ Play": a game against Maia, a group of its own. + fn play_button(&self, ui: &mut Ui, icons: bool, actions: &mut Vec) { + let label = if icons { "♞" } else { tr("♞ Play") }; + if shelf_button(ui, "play", label) + .on_hover_text(shelf_hint( + icons, + tr("♞ Play"), + tr("A game against the computer: Maia, who plays like a human, or Rodent, strong and with a style (Ctrl+G)"), + )) + .clicked() + { + actions.push(LibraryAction::Play); + } + } + + /// "♟ New game · 📋 Paste PGN": a game to enter. + fn game_buttons(&self, ui: &mut Ui, icons: bool, actions: &mut Vec) { + let label = |full: &'static str, icon: &'static str| if icons { icon } else { full }; + let hint = |full: &str, hint: &str| shelf_hint(icons, full, hint); + if shelf_button(ui, "new_game", label(tr("♟ New game"), "♟")) + .on_hover_text(hint( + tr("♟ New game"), + tr("Empty board in the starting position (Ctrl+N)"), + )) + .clicked() + { + actions.push(LibraryAction::NewGame); + } + if shelf_button(ui, "paste_pgn", label(tr("📋 Paste PGN"), "📋")) + .on_hover_text(hint( + tr("📋 Paste PGN"), + tr("Open a game from the clipboard"), + )) + .clicked() + { + actions.push(LibraryAction::PastePgn); + } + } + + fn shelf( + &mut self, + ui: &mut Ui, + databases: &[PathBuf], + settings: &Settings, + actions: &mut Vec, + ) { + ui.add_space(8.0); + // The title row (library-layout.md §1.4): «Databases», then what to put in — the + // game ones first (used daily), then, apart, the database actions; the program's + // on the right. + // Narrowing: the database actions fold to «+ â–¾ ðŸŒ�» first (databases are added + // seldom), then the other buttons show icons, then the title goes. + let avail = ui.available_width(); + let heading = text_w(ui, tr("Databases"), egui::TextStyle::Heading) + 16.0; + let between = 24.0; + let update = self.update.as_deref(); + let full = self.shelf_actions_w(ui, false); + let short = self.shelf_actions_w(ui, true); + let right = |icons| shelf_buttons_w(ui, update, icons); + let (title, folded, icons) = if heading + full + between + right(false) <= avail { + (true, false, false) + } else if heading + short + between + right(false) <= avail { + (true, true, false) + } else if heading + short + between + right(true) <= avail { + (true, true, true) + } else { + (false, true, true) + }; + ui.horizontal(|ui| { + if title { + ui.heading(tr("Databases")); + ui.add_space(16.0 - ui.spacing().item_spacing.x); + } + self.groups(ui, folded, icons, actions); + ui.scope_builder( + egui::UiBuilder::new() + .id_salt("shelf_app_actions") + .layout(egui::Layout::right_to_left(egui::Align::Center)), + |ui| self.app_buttons(ui, icons, actions), + ); + }); + let card = self.aside.take(); + let card_w = card.as_ref().map_or(0.0, |c| c.width(ui)); + let width = ui.available_width(); + let beside = card.is_some() && width - card_w - 24.0 >= 190.0; + // Not even one database beside it: the card has a row of its own, above them. + if let Some(c) = card.as_ref().filter(|_| !beside) { + ui.add_space(4.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { + push_pressed(c.show(ui, card_w, settings), actions); + }); + } + if !databases.is_empty() || beside { + ui.add_space(4.0); + ui.horizontal_top(|ui| { + let dbs_w = if beside { width - card_w - 24.0 } else { width }; + ui.allocate_ui(vec2(dbs_w, 0.0), |ui| { + ui.set_max_width(dbs_w); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 8.0); + for path in databases { + self.db_card(ui, path, actions); + } + }); + }); + if let Some(c) = card.as_ref().filter(|_| beside) { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { + push_pressed(c.show(ui, card_w, settings), actions); + }); + } + }); + } + self.aside = card; + ui.add_space(8.0); + } + + /// The width of `shelf_actions`. + fn shelf_actions_w(&self, ui: &Ui, folded: bool) -> f32 { + if folded { + button_w(ui, "+ â–¾") + + if crate::platform::CAPS.online_games { + button_w(ui, "ðŸŒ�") + } else { + 0.0 + } + } else { + button_w(ui, tr("+ Add database")) + + button_w(ui, tr("✚ New database")) + + if crate::platform::CAPS.online_games { + button_w(ui, &format!("ðŸŒ� {}", tr("Online games"))) + } else { + 0.0 + } + } + } + + /// «+ Add database · ✚ New database · ðŸŒ� Online games», or folded: «+ ▾» (a menu of + /// the first two) and «ðŸŒ�». Download progress belongs in the tooltip/dialog so + /// background work never moves the toolbar's other actions. + fn shelf_actions(&self, ui: &mut Ui, folded: bool, actions: &mut Vec) { + let add_hint = tr("Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)"); + let new_hint = tr("An empty PGN file for your own games (Ctrl+Shift+N)"); + let online_hint = tr( + "Download any player's games by nickname into a database: yours, a pupil's, an opponent's", + ); + if folded { + ui.push_id("database_menu", |ui| { + ui.menu_button("+ â–¾", |ui| { + if ui + .button(tr("Add database…")) + .on_hover_text(add_hint) + .clicked() + { + actions.push(LibraryAction::AddDatabases); + ui.close(); + } + if crate::platform::CAPS.own_databases + && ui + .button(tr("New database…")) + .on_hover_text(new_hint) + .clicked() + { + actions.push(LibraryAction::NewDatabase); + ui.close(); + } + }) + }); + } else { + if shelf_button(ui, "add_database", tr("+ Add database")) + .on_hover_text(add_hint) + .clicked() + { + actions.push(LibraryAction::AddDatabases); + } + if crate::platform::CAPS.own_databases + && shelf_button(ui, "new_database", tr("✚ New database")) + .on_hover_text(new_hint) + .clicked() + { + actions.push(LibraryAction::NewDatabase); + } + } + if crate::platform::CAPS.online_games { + let label = if folded { + "ðŸŒ�".to_owned() + } else { + format!("ðŸŒ� {}", tr("Online games")) + }; + let hint = match self.online_running { + Some(n) => trf("downloading… {n}", &[("n", &crate::i18n::games(n))]), + None => online_hint.to_owned(), + }; + if shelf_button(ui, "online_games", label) + .on_hover_text(hint) + .clicked() + { + #[cfg(not(web))] + actions.push(LibraryAction::OnlineGames); + } + } + } + + /// The empty shelf's invitation: the three actions as large cards, centred. + fn action_cards(&self, ui: &mut Ui, actions: &mut Vec) { + let (add_w, new_w, online_w) = side_card_widths(ui); + let total = add_w + + new_w + + if crate::platform::CAPS.online_games { + online_w + 8.0 + } else { + 0.0 + } + + 8.0; + let card = |ui: &mut Ui, w: f32, title: &str, below: Option<&str>| { + let (rect, resp) = ui.allocate_exact_size(vec2(w, 64.0), Sense::click()); + let visuals = ui.style().interact(&resp); + ui.painter() + .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); + let up = if below.is_some() { -9.0 } else { 0.0 }; + ui.painter().text( + rect.center() + vec2(0.0, up), + egui::Align2::CENTER_CENTER, + title, + egui::FontId::proportional(15.0), + visuals.text_color(), + ); + if let Some(below) = below { + ui.painter().text( + rect.center() + vec2(0.0, 11.0), + egui::Align2::CENTER_CENTER, + below, + egui::FontId::proportional(13.0), + ui.visuals().weak_text_color(), + ); + } + resp + }; + // One row, centred; a column of them, centred, when the row does not fit. + let row = ui.available_width() >= total; + let layout = if row { + egui::Layout::left_to_right(egui::Align::Min) + } else { + egui::Layout::top_down(egui::Align::Center) + }; + ui.with_layout(layout, |ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 8.0); + if row { + ui.add_space(((ui.available_width() - total) / 2.0).max(0.0)); + } + if card(ui, add_w, tr("+ Add database"), None) + .on_hover_text(tr( + "Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)", + )) + .clicked() + { + actions.push(LibraryAction::AddDatabases); + } + if crate::platform::CAPS.own_databases + && card(ui, new_w, tr("✚ New database"), None) + .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) + .clicked() + { + actions.push(LibraryAction::NewDatabase); + } + if crate::platform::CAPS.online_games + && card( + ui, + online_w, + &format!("ðŸŒ� {}", tr("Online games")), + Some("Lichess · Chess.com"), + ) + .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) + .clicked() + { + #[cfg(not(web))] + actions.push(LibraryAction::OnlineGames); + } + }); + } + + fn db_card(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec) { + let player = self + .player_dbs + .iter() + .find(|(p, _)| p == path) + .map(|(_, n)| n.clone()); + let selected = self.selected_db.as_deref() == Some(path); + let name = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let shown = |c: crate::db_counts::Count| { + if c.locked { + format!( + "{} · 🔒", + trf("{n} games", &[("n", &large_db::short_count(c.games))]) + ) + } else { + crate::i18n::games(c.games) + } + }; + let detail = match self.slots.get(path) { + Some(Slot::Ready(db)) => shown(crate::db_counts::Count::of(db)), + Some(Slot::Loading { progress, .. }) => { + let p = progress.lock().map(|g| *g).unwrap_or(ScanProgress { + bytes_done: 0, + bytes_total: 0, + games: 0, + }); + trf("loading… {n}", &[("n", &p.games)]) + } + Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(path) => { + tr("ðŸ“� Choose the database's folder").into() + } + Some(Slot::Failed(_)) | None if crate::platform::files::waiting_to_read(path) => { + tr("🔒 Allow reading").into() + } + Some(Slot::Failed(_)) | None + if crate::platform::files::session_only(path) && !self.files.exists(path) => + { + tr("↻ Choose the file again").into() + } + Some(Slot::Failed(_)) => tr("error").into(), + None if !self.files.exists(path) => tr("file not found").into(), + // Not opened: its games once counted, nothing till then. + None => self.counts.get(path).map(shown).unwrap_or_default(), + }; + let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 64.0), Sense::click()); + let v = ui.visuals(); + let fill = if selected { + v.selection.bg_fill + } else if resp.hovered() { + v.widgets.hovered.weak_bg_fill + } else { + v.faint_bg_color + }; + ui.painter().rect_filled(rect, 6.0, fill); + let text_color = if selected { + v.selection.stroke.color + } else { + v.text_color() + }; + ui.painter().text( + rect.left_top() + vec2(12.0, 10.0), + egui::Align2::LEFT_TOP, + if crate::online::is_online(path) { + "ðŸŒ�" + } else if player.is_some() { + "♞" + } else { + "🗄" + }, + egui::FontId::proportional(22.0), + text_color, + ); + // Long names (book titles) are cut to two lines so the detail line stays readable. + let mut job = egui::text::LayoutJob::simple( + name, + egui::FontId::proportional(14.0), + text_color, + rect.width() - 52.0, + ); + job.wrap.max_rows = 2; + job.wrap.break_anywhere = false; + job.wrap.overflow_character = Some('…'); + let galley = ui.fonts_mut(|f| f.layout_job(job)); + ui.painter() + .galley(rect.left_top() + vec2(44.0, 9.0), galley, text_color); + ui.painter().text( + rect.left_bottom() + vec2(44.0, -8.0), + egui::Align2::LEFT_BOTTOM, + detail, + egui::FontId::proportional(12.0), + v.weak_text_color(), + ); + let resp = match &player { + Some(name) => { + let whose = if name.is_empty() { + tr("Games against the computer are written here").to_owned() + } else { + trf( + "{name}'s games against the computer are written here", + &[("name", name)], + ) + }; + resp.on_hover_text(format!("{whose}\n{}", crate::platform::files::shown(path))) + } + None => resp.on_hover_text(crate::platform::files::shown(path)), + }; + if resp.clicked() { + self.select_db(path, ui.ctx()); + } + let block = self.write_block(path); + let not_read = self.database(path).is_none() && block.is_none(); + resp.context_menu(|ui| { + if ui.button(tr("Show in folder")).clicked() { + crate::own_db::show_in_folder(path); + ui.close(); + } + // Games are written in UTF-8: a legacy file takes them through a copy. A file + // not read yet is looked at now (its beginning), while the menu is open. + let legacy = match &block { + Some(crate::own_db::Block::Encoding(_)) => true, + None if not_read => legacy_pgn(path), + _ => false, + }; + if legacy + && ui + .button(tr("Make a copy in UTF-8…")) + .on_hover_text(tr( + "A copy of the file in UTF-8, next to it: games can be added to the copy", + )) + .clicked() + { + actions.push(LibraryAction::Utf8Copy(path.to_path_buf())); + ui.close(); + } + if ui.button(tr("Remove from list")).clicked() { + actions.push(LibraryAction::RemoveDatabase(path.to_path_buf())); + ui.close(); + } + if ui.button(tr("Reload file")).clicked() { + self.slots.remove(path); + self.load(path, ui.ctx()); + ui.close(); + } + }); + } + + fn table_area(&mut self, ui: &mut Ui, settings: &Settings, actions: &mut Vec) { + let Some(path) = self.selected_db.clone() else { + if settings.databases.is_empty() { + // The empty shelf (library-layout.md §1.5): its actions where a newcomer + // looks, large. + ui.vertical_centered(|ui| { + ui.add_space(60.0); + ui.label(RichText::new(tr("No databases yet")).size(16.0)); + ui.add_space(12.0); + }); + self.action_cards(ui, actions); + ui.vertical_centered(|ui| { + ui.add_space(12.0); + ui.horizontal(|ui| { + let w = text_w(ui, tr("or"), egui::TextStyle::Body) + + button_w(ui, tr("♟ New game")); + ui.add_space(((ui.available_width() - w) / 2.0).max(0.0)); + ui.label(RichText::new(tr("or")).weak()); + if ui.button(tr("♟ New game")).clicked() { + actions.push(LibraryAction::NewGame); + } + }); + }); + } else { + ui.centered_and_justified(|ui| { + ui.label( + RichText::new(tr("Choose a database above")) + .weak() + .size(16.0), + ); + }); + } + return; + }; + let db = match self.slots.get(&path) { + Some(Slot::Ready(db)) => db.clone(), + Some(Slot::Loading { + progress, cancel, .. + }) => { + let p = progress.lock().map(|g| *g).unwrap_or(ScanProgress { + bytes_done: 0, + bytes_total: 0, + games: 0, + }); + let frac = if p.bytes_total > 0 { + p.bytes_done as f32 / p.bytes_total as f32 + } else { + 0.0 + }; + let cancel = cancel.clone(); + ui.vertical_centered(|ui| { + ui.add_space(40.0); + ui.label(trf( + "Reading {path} — games found: {n}", + &[ + ("path", &crate::platform::files::shown(&path)), + ("n", &p.games), + ], + )); + ui.add(egui::ProgressBar::new(frac).desired_width(400.0)); + if ui.button(tr("Cancel")).clicked() { + cancel.store(true, Ordering::Relaxed); + } + }); + return; + } + #[cfg(web)] + Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(&path) => { + // A ChessBase database's .cbh without its other files (one chosen + // alone at an earlier visit): its folder or all its files. + ui.vertical_centered(|ui| { + ui.add_space(40.0); + ui.label(tr( + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("ðŸ“� Choose the database's folder")).clicked() { + actions.push(LibraryAction::ChooseFolderAgain(path.clone())); + } + if ui.button(tr("Choose the database's files")).clicked() { + actions.push(LibraryAction::ChooseAgain(path.clone())); + } + if ui.button(tr("Remove from list")).clicked() { + actions.push(LibraryAction::RemoveDatabase(path.clone())); + } + }); + }); + return; + } + #[cfg(web)] + Some(Slot::Failed(_)) if crate::platform::files::waiting_to_read(&path) => { + // Chrome, Edge: the file is remembered; the browser asks before the + // page reads it again. + ui.vertical_centered(|ui| { + ui.add_space(40.0); + ui.label(tr( + "The browser remembers this file and asks before the page reads it again.", + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("🔒 Allow reading")).clicked() { + actions.push(LibraryAction::AllowReading(path.clone())); + } + if ui.button(tr("Remove from list")).clicked() { + actions.push(LibraryAction::RemoveDatabase(path.clone())); + } + }); + }); + return; + } + Some(Slot::Failed(_)) + if crate::platform::files::session_only(&path) && !self.files.exists(&path) => + { + // A browser keeps no way back to a file the user chose (Firefox, Safari). + ui.vertical_centered(|ui| { + ui.add_space(40.0); + // Chrome and Edge remember chosen files, not dropped ones. + ui.label(if crate::platform::files::remembers_chosen() { + tr("A dropped file is not remembered: after a reload, choose the file again or keep a copy in the browser.") + } else { + tr("This browser doesn't remember files: after a reload, choose the file again or keep a copy in the browser.") + }); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("↻ Choose the file again")).clicked() { + actions.push(LibraryAction::ChooseAgain(path.clone())); + } + if ui.button(tr("Remove from list")).clicked() { + actions.push(LibraryAction::RemoveDatabase(path.clone())); + } + }); + }); + return; + } + Some(Slot::Failed(e)) => { + let e = e.clone(); + ui.vertical_centered(|ui| { + ui.add_space(40.0); + ui.label( + RichText::new(trf( + "Could not open {path}: {e}", + &[("path", &crate::platform::files::shown(&path)), ("e", &e)], + )) + .color(ui.visuals().error_fg_color), + ); + if ui.button(tr("Retry")).clicked() { + self.slots.remove(&path); + self.load(&path, ui.ctx()); + } + }); + return; + } + None => { + self.load(&path, ui.ctx()); + return; + } + }; + + let online = crate::online::is_online(&path); + let header = self.header(&path, &db, online); + let writable = self.write_block(&path).is_none(); + let view = self + .large + .entry(path.clone()) + .or_insert_with(|| LargeView::for_database(&db, online)); + let notes = self.info.get(&path).map_or(0, |i| i.notes.len()); + view.set_marks_db(&db); + if view.marks.is_none() { + let marks = self + .marks + .entry(path.clone()) + .or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(&path)))) + .clone(); + view.marks = Some(marks); + } + if view.table( + ui, + &path, + &db, + &header, + &mut self.viewed, + notes, + settings, + writable, + actions, + ) { + self.notes_open = Some(path.clone()); + } + } + + /// What the header says about a database: its format, and for one downloaded from + /// Lichess and Chess.com, its "⟳ New games". + fn header(&self, path: &Path, db: &Database, online: bool) -> Header { + let (format, format_hint) = match (db, self.info.get(path)) { + (Database::ChessBase(_), _) => ( + tr("ChessBase, read-only").to_string(), + tr("Read in place; the original files are not changed. Save a game to keep your edits.").to_string(), + ), + (Database::Pgn(_), Some(info)) if info.format != Format::Pgn => ( + trf("{format}, read-only", &[("format", &info.format.label())]), + tr("Converted to PGN when opened; the original files are not changed. Save a game to keep your edits.").to_string(), + ), + (Database::Pgn(pgn), _) => ( + trf("PGN, encoding {enc}", &[("enc", &pgn.encoding().label())]), + String::new(), + ), + }; + let online = online.then(|| { + let when = crate::online::State::load(path) + .and_then(|s| s.updated) + .map(crate::online::ago); + let hint = if !self.online { + tr("No connection to Lichess and Chess.com").to_owned() + } else if let Some(w) = when { + trf( + "Fetch the games played since the last download ({when})", + &[("when", &w)], + ) + } else { + tr("Fetch the games played since the last download").to_owned() + }; + OnlineButton { + busy: self.online_busy.contains(&path.to_path_buf()), + enabled: self.online, + hint, + } + }); + Header { + format, + format_hint, + online, + keep_copy: crate::platform::files::session_only(path), + } + } +} + +/// "2010.??.??" → "2010", "1997.05.??" → "05.1997", full dates as "dd.mm.yyyy". +pub fn display_date(raw: &str) -> String { + let parts: Vec<&str> = raw.split(['.', '-', '/']).collect(); + let known = |s: &&str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()); + match parts.as_slice() { + [y, m, d] if known(y) && known(m) && known(d) => format!("{d}.{m}.{y}"), + [y, m, _] if known(y) && known(m) => format!("{m}.{y}"), + [y, ..] if known(y) => (*y).to_string(), + _ => String::new(), + } +} + +/// User-facing text of an import failure. +fn import_error(e: &ImportError) -> String { + match e { + ImportError::Cancelled => tr("Loading cancelled").into(), + ImportError::Empty => tr("No PGN or ChessBase database in the archive").into(), + ImportError::Unsupported(Unsupported::Encrypted) => { + tr("Password-protected archives (.cbz, encrypted zip/7z) are not supported").into() + } + ImportError::Unsupported(Unsupported::ChessBase2) => tr( + "The ChessBase 2CBH format is not supported: export the database from ChessBase as CBH or PGN", + ) + .into(), + ImportError::Unsupported(Unsupported::ChessBaseFiles) => tr( + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + ) + .into(), + ImportError::Io { source, .. } if source.kind() == std::io::ErrorKind::OutOfMemory => tr( + "The browser doesn't have enough memory for this database. Open it in the desktop program.", + ) + .into(), + // A browser's places of files mean nothing to the user: only what happened. + #[cfg(web)] + ImportError::Io { source, .. } => source.to_string(), + e => e.to_string(), + } +} + +#[cfg(all(test, not(web)))] +mod tests { + use super::*; + + fn toolbar_frame( + library: &mut Library, + ctx: &egui::Context, + width: f32, + events: Vec, + ) -> (Vec<(String, egui::Rect, egui::Color32)>, Vec) { + toolbar_frame_at_size(library, ctx, vec2(width, 900.0), events) + } + + fn toolbar_frame_at_size( + library: &mut Library, + ctx: &egui::Context, + size: egui::Vec2, + events: Vec, + ) -> (Vec<(String, egui::Rect, egui::Color32)>, Vec) { + let mut actions = Vec::new(); + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + events, + ..Default::default() + }, + |ui| { + let databases = library.slots.keys().cloned().collect::>(); + actions = library.show(ui, &databases, &Settings::default()); + }, + ); + output.textures_delta.clear(); + let text = output + .shapes + .iter() + .filter_map(|clipped| { + if let egui::Shape::Text(shape) = &clipped.shape + && shape.pos.y < 40.0 + { + Some(( + shape.galley.text().to_owned(), + egui::Rect::from_min_size(shape.pos, shape.galley.size()), + shape.fallback_color, + )) + } else { + None + } + }) + .collect(); + output.drop_without_applying_deltas(); + (text, actions) + } + + #[test] + fn startup_download_progress_keeps_toolbar_geometry_and_style_stable() { + for height in [590.0, 900.0] { + for width in [640.0, 960.0, 1100.0, 1400.0, 1920.0] { + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let mut library = Library::new(&ctx); + let (pending, _) = + toolbar_frame_at_size(&mut library, &ctx, vec2(width, height), vec![]); + library.online = true; + library.online_running = Some(100_000); + let (ready, _) = + toolbar_frame_at_size(&mut library, &ctx, vec2(width, height), vec![]); + assert_eq!( + pending, ready, + "toolbar changed when background progress arrived at width {width}" + ); + assert!( + ready.iter().any(|(label, _, _)| label == "ðŸŒ�" + || label == &format!("ðŸŒ� {}", tr("Online games"))) + ); + } + } + } + + #[test] + fn resizing_and_update_badge_never_reuse_a_separator_as_button_style() { + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let mut library = Library::new(&ctx); + for (width, update) in [ + (1400.0, None), + (640.0, None), + (960.0, Some("⬆ Update 2.2.0")), + (1920.0, Some("⬆ Update 2.2.0")), + (1100.0, None), + (640.0, None), + (1400.0, None), + ] { + library.update = update.map(str::to_owned); + let (first, _) = toolbar_frame(&mut library, &ctx, width, vec![]); + let (settled, _) = toolbar_frame(&mut library, &ctx, width, vec![]); + assert_eq!( + first, settled, + "first resized frame had a stale response/style at {width}" + ); + for (label, rect, color) in first { + assert!( + rect.left() >= 0.0 && rect.right() <= width, + "{label}: {rect:?}" + ); + if label != tr("Databases") && !label.starts_with('⬆') { + assert_eq!( + color, + ctx.style_of(egui::Theme::Dark) + .visuals + .widgets + .inactive + .fg_stroke + .color, + "false noninteractive style for {label}" + ); + } + } + } + } + + #[test] + fn toolbar_actions_are_available_while_the_database_loads_and_afterwards() { + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let mut library = Library::new(&ctx); + let path = PathBuf::from("/tmp/chesspenguin-toolbar-regression.pgn"); + let (_tx, rx) = channel(); + library.slots.insert( + path.clone(), + Slot::Loading { + progress: Arc::new(Mutex::new(ScanProgress { + bytes_done: 0, + bytes_total: 100, + games: 0, + })), + cancel: Arc::new(AtomicBool::new(false)), + rx, + }, + ); + library.selected_db = Some(path.clone()); + let (loading, _) = toolbar_frame(&mut library, &ctx, 1400.0, vec![]); + for ready in [false, true] { + if ready { + let opened = chess_import::open_bytes( + "toolbar.pgn", + b"1. e4 e5 *".to_vec(), + &mut |_| {}, + &AtomicBool::new(false), + ) + .unwrap(); + library + .large + .insert(path.clone(), LargeView::for_database(&opened.db, false)); + library + .slots + .insert(path.clone(), Slot::Ready(Arc::new(opened.db))); + library.online = true; + library.online_running = Some(1_000_000); + } + let (texts, _) = toolbar_frame( + &mut library, + &ctx, + 1400.0, + vec![egui::Event::PointerMoved(egui::pos2(-100.0, -100.0))], + ); + assert_eq!(loading, texts, "database completion changed the toolbar"); + for (label, expected) in [ + (tr("+ Add database").to_owned(), LibraryAction::AddDatabases), + (tr("✚ New database").to_owned(), LibraryAction::NewDatabase), + ( + format!("ðŸŒ� {}", tr("Online games")), + LibraryAction::OnlineGames, + ), + (tr("♟ New game").to_owned(), LibraryAction::NewGame), + (tr("📋 Paste PGN").to_owned(), LibraryAction::PastePgn), + (tr("♞ Play").to_owned(), LibraryAction::Play), + (tr("ðŸ—� Preparations").to_owned(), LibraryAction::Preparations), + ( + tr("Opening training (α version)").to_owned(), + LibraryAction::OpeningTraining, + ), + (tr("âš™ Settings").to_owned(), LibraryAction::OpenSettings), + ] { + let pos = texts + .iter() + .find(|(text, _, _)| text == &label) + .unwrap() + .1 + .center(); + let button = |pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + toolbar_frame( + &mut library, + &ctx, + 1400.0, + vec![egui::Event::PointerMoved(pos), button(true)], + ); + let (_, actions) = toolbar_frame(&mut library, &ctx, 1400.0, vec![button(false)]); + assert!( + actions.iter().any(|action| std::mem::discriminant(action) + == std::mem::discriminant(&expected)), + "{label} did not activate, ready={ready}" + ); + } + // egui reads the previous response for styling: let the final hover + // leave before comparing the next data state. + toolbar_frame( + &mut library, + &ctx, + 1400.0, + vec![egui::Event::PointerMoved(egui::pos2(-100.0, -100.0))], + ); + } + } +} diff --git a/apps/desktop/src/maia_download.rs b/apps/desktop/src/maia_download.rs new file mode 100644 index 0000000..3ca7d00 --- /dev/null +++ b/apps/desktop/src/maia_download.rs @@ -0,0 +1,212 @@ +//! Downloading the Maia-3 weights on request: a published checkpoint of a pinned +//! revision from huggingface.co/UofTCSSLab (the large `maia3-79m.pt`; the small +//! `maia3-5m.pt` of earlier versions is still used when it is there), checked against +//! its SHA-256 and loaded once before use. Nothing is downloaded without the user +//! asking; the file is the authors' own, not redistributed by us. + +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +use sha2::{Digest, Sha256}; + +pub use maia::strength::Model; + +/// Where each model is published. +pub trait Published { + fn repo(self) -> &'static str; + fn revision(self) -> &'static str; + fn file(self) -> &'static str; + fn sha256(self) -> &'static str; + fn size(self) -> u64; +} + +impl Published for Model { + fn repo(self) -> &'static str { + match self { + Model::Small => "Maia3-5M", + Model::Large => "Maia3-79M", + } + } + + fn revision(self) -> &'static str { + match self { + Model::Small => "b6559de2398d7140b985f28fd2c19fb5e47ddabe", + Model::Large => "a107d6ceb7b298cb04ae1da4edffe2939858b894", + } + } + + fn file(self) -> &'static str { + match self { + Model::Small => "maia3-5m.pt", + Model::Large => "maia3-79m.pt", + } + } + + fn sha256(self) -> &'static str { + match self { + Model::Small => "ba14208b2992d85502f5fb501934abf6aaaeb355e9f3fdf90e326911f562524f", + Model::Large => "3fc6181d5db789b45a15305732148757ae74efa3e0028e81ba335b462dac45c2", + } + } + + fn size(self) -> u64 { + match self { + Model::Small => 20_968_049, + Model::Large => 315_651_851, + } + } +} + +/// `/maia/`. +pub fn dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("maia")) +} + +/// The weights of `model`, when they are there. `CP_MAIA` (development) points to a +/// file elsewhere: the large model when its name says 79m, else the small one. +pub fn installed(model: Model) -> Option { + if let Some(p) = std::env::var_os("CP_MAIA") { + let large = p.to_string_lossy().contains("79m"); + let p = PathBuf::from(p); + return (large == (model == Model::Large) && p.is_file()).then_some(p); + } + let p = dir()?.join(model.file()); + p.is_file().then_some(p) +} + +/// The downloaded weights did not load: removed, so that the dialog offers them again. +pub fn forget_broken(model: Model) { + if std::env::var_os("CP_MAIA").is_none() + && let Some(d) = dir() + { + let _ = std::fs::remove_file(d.join(model.file())); + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Stage { + Downloading { done: u64 }, + Checking, + Done(PathBuf), + Failed(String), +} + +/// A download in a background thread. +pub struct Download { + pub model: Model, + stage: Arc>, + cancel: Arc, +} + +impl Download { + /// A browser downloads no weights into files: there is no download for it. + #[cfg(web)] + pub fn start(_ctx: &egui::Context, model: Model) -> Download { + Download { + model, + stage: Arc::new(Mutex::new(Stage::Failed( + crate::i18n::tr("not yet for this system").to_owned(), + ))), + cancel: Arc::new(AtomicBool::new(false)), + } + } + + #[cfg(not(web))] + pub fn start(ctx: &egui::Context, model: Model) -> Download { + let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0 })); + let cancel = Arc::new(AtomicBool::new(false)); + let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone()); + let _ = std::thread::Builder::new() + .name("maia-download".into()) + .spawn(move || { + let report = |st: Stage| { + if let Ok(mut g) = s.lock() { + *g = st; + } + ctx.request_repaint(); + }; + let end = match run(model, &report, &c) { + Ok(p) => Stage::Done(p), + Err(e) => Stage::Failed(e), + }; + report(end); + }); + Download { + model, + stage, + cancel, + } + } + + pub fn stage(&self) -> Stage { + self.stage + .lock() + .map(|g| g.clone()) + .unwrap_or(Stage::Failed(String::new())) + } +} + +impl Drop for Download { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +#[cfg(not(web))] +fn run(model: Model, report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { + let dir = dir().ok_or("no data directory")?; + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let name = model.file(); + let part = dir.join(format!("{name}.part")); + let url = format!( + "https://huggingface.co/UofTCSSLab/{}/resolve/{}/{name}", + model.repo(), + model.revision() + ); + let result = (|| { + let mut response = ureq::get(&url).call().map_err(|e| e.to_string())?; + let mut body = response + .body_mut() + .with_config() + .limit(model.size() + 1) + .reader(); + let mut file = std::fs::File::create(&part).map_err(|e| e.to_string())?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + let mut done = 0u64; + loop { + if cancel.load(Ordering::Relaxed) { + return Err("cancelled".to_owned()); + } + let n = body.read(&mut buf).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]).map_err(|e| e.to_string())?; + done += n as u64; + report(Stage::Downloading { done }); + } + file.sync_all().map_err(|e| e.to_string())?; + let digest: String = hasher + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + if done != model.size() || digest != model.sha256() { + return Err(crate::i18n::tr("The file is not the published one").to_owned()); + } + report(Stage::Checking); + maia::Maia::load(&part).map_err(|e| e.to_string())?; + let dest = dir.join(name); + std::fs::rename(&part, &dest).map_err(|e| e.to_string())?; + Ok(dest) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&part); + } + result +} diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs new file mode 100644 index 0000000..ab8a1a2 --- /dev/null +++ b/apps/desktop/src/main.rs @@ -0,0 +1,6 @@ +// No console window for release builds on Windows. +#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] + +fn main() -> eframe::Result { + chesspenguin_app::run_native() +} diff --git a/apps/desktop/src/my_games.rs b/apps/desktop/src/my_games.rs new file mode 100644 index 0000000..6d18096 --- /dev/null +++ b/apps/desktop/src/my_games.rs @@ -0,0 +1,98 @@ +//! «My games» of the web version (docs/design/web-version.md §2.3): one PGN database +//! kept in the browser (the page's `/data`, in IndexedDB), always on the shelf. Saving +//! a game (Ctrl+S, 💾) puts it there — into its own record, or as a new one; the user's +//! files are only read. «Download all as PGN» gives it back as a file. + +use std::path::PathBuf; + +use crate::i18n::tr; +use crate::settings::Settings; + +const DIR: &str = "my-games"; + +/// The database: `/data/my-games/.pgn`, named in the language of the first start. +pub fn path() -> PathBuf { + let dir = crate::platform::data_dir().unwrap_or_default().join(DIR); + crate::platform::web::vfs::list(&dir) + .into_iter() + .find(|p| p.extension().is_some_and(|e| e == "pgn")) + .unwrap_or_else(|| dir.join(format!("{}.pgn", tr("My games")))) +} + +/// Makes the database at the first start and keeps it on the shelf; `true` when the +/// settings changed. +pub fn setup(settings: &mut Settings) -> bool { + let path = path(); + if !crate::platform::fs::exists(&path) { + let _ = crate::platform::fs::write_atomic(&path, b""); + } + if settings.databases.contains(&path) { + return false; + } + settings.databases.push(path); + true +} + +/// Whether `path` is «My games». +pub fn is(path: &std::path::Path) -> bool { + path == self::path() +} + +/// Gives all of «My games» as a downloaded PGN file (`ChessPenguin-my-games-.pgn`). +pub fn download_all() -> Result<(), String> { + let text = crate::platform::fs::read_to_string(&path()).map_err(|e| e.to_string())?; + let date = chrono::Local::now().format("%Y-%m-%d"); + crate::platform::files::download_pgn(&format!("ChessPenguin-my-games-{date}.pgn"), &text) +} + +/// Games in «My games» (records of its text; 0 when empty). +pub fn count() -> usize { + crate::platform::fs::read(&path()) + .ok() + .and_then(|b| { + chess_core::PgnDatabase::from_bytes( + b, + Some(chess_core::TextEncoding::Utf8), + &mut |_| {}, + &std::sync::atomic::AtomicBool::new(false), + ) + .ok() + }) + .map_or(0, |db| db.len()) +} + +/// Its size in bytes. +pub fn size() -> u64 { + crate::platform::fs::meta(&path()).map_or(0, |m| m.len) +} + +/// A game left unsaved when the page was closed (docs/design/web-version.md §2.6): one, +/// the last, written every few seconds while it has changes. It guards against a +/// closed tab; it is not a save: offered at the next start, opened or deleted. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +pub struct Draft { + pub title: String, + pub moves: usize, + pub pgn: String, +} + +fn draft_path() -> PathBuf { + crate::platform::data_dir() + .unwrap_or_default() + .join("draft.json") +} + +pub fn write_draft(draft: &Draft) { + if let Ok(json) = serde_json::to_vec(draft) { + let _ = crate::platform::fs::write_atomic(&draft_path(), &json); + } +} + +pub fn read_draft() -> Option { + let bytes = crate::platform::fs::read(&draft_path()).ok()?; + serde_json::from_slice(&bytes).ok() +} + +pub fn delete_draft() { + let _ = crate::platform::fs::remove_file(&draft_path()); +} diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs new file mode 100644 index 0000000..8850cd8 --- /dev/null +++ b/apps/desktop/src/notation.rs @@ -0,0 +1,1555 @@ +//! Move list: main line as a two-column table (Lichess style), comments and variations +//! as full-width blocks between rows; nested variations inline in parentheses. + +use std::collections::HashMap; + +use crate::i18n::tr; +use crate::review::{Mark, judgement_name, judgement_symbol, judgement_text_color}; +use crate::translate_ui::Mark as Translated; +use chess_core::shakmaty::{Color, Position}; +use chess_core::{Game, Nag, NodeId}; +use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, vec2}; + +pub struct Notation<'a> { + pub game: &'a Game, + pub cursor: NodeId, + pub scroll_to_cursor: bool, + /// Engine assessments of main-line moves (whole-game analysis), shown apart from NAGs. + pub marks: Option<&'a HashMap>, + /// Engine line shown on the board: (start node, SAN moves, moves played so far). + pub preview: Option<(NodeId, &'a [String], usize)>, + /// Translated comments by their original text (none: the original is shown). + pub translations: Option<&'a HashMap>, + /// The comment being written, drawn where the comment stands (user-comments.md §3). + pub editor: Option<&'a mut CommentEditor>, + /// A game being played: moves only show their position (no menus, no editing). + pub read_only: bool, + /// Main-line moves up to this ply are dimmed (the moves of the game a game against + /// Maia goes on from). + pub dim_until: Option, + /// Mistakes on main-line moves (learning an opening): how many, the move was shown. + pub mistakes: Option<&'a HashMap>, + /// Arrows and circles of the moves' comments (`[%cal]`, `[%csl]`): a quiet sign by + /// the move ([`shape_counts`]). + pub shapes: Option<&'a HashMap>, +} + +/// How many arrows and circles a move's comment draws on the board. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ShapeCount { + pub arrows: usize, + pub circles: usize, +} + +impl ShapeCount { + /// «Arrows: 2 · circles: 1 — shown on the board at this move»; a count of none is left out. + pub fn hint(self) -> String { + let (a, c) = (self.arrows, self.circles); + match (a, c) { + (_, 0) => crate::i18n::trf( + "Arrows: {a} — shown on the board at this move", + &[("a", &a)], + ), + (0, _) => crate::i18n::trf( + "Circles: {c} — shown on the board at this move", + &[("c", &c)], + ), + _ => crate::i18n::trf( + "Arrows: {a} · circles: {c} — shown on the board at this move", + &[("a", &a), ("c", &c)], + ), + } + } +} + +/// The nodes of the game whose comment after them draws arrows or circles. +pub fn shape_counts(game: &Game) -> HashMap { + game.all_nodes() + .filter_map(|id| { + let (arrows, circles) = chess_core::shapes(game.node(id)?.comments_after()); + let count = ShapeCount { + arrows: arrows.len(), + circles: circles.len(), + }; + (count != ShapeCount::default()).then_some((id, count)) + }) + .collect() +} + +/// The sign's box; it is drawn this far after the move. +const SIGN: f32 = 10.0; +const SIGN_GAP: f32 = 4.0; + +/// The sign of a move whose comment draws on the board: an arrow if it has one, a ring +/// otherwise. Painted (no font has both at the height of a move's text), so it is sharp +/// at any scale; it does not repeat the shapes' colours, which would argue with NAGs. +fn paint_shapes_sign( + painter: &egui::Painter, + center: egui::Pos2, + count: ShapeCount, + color: Color32, +) { + let stroke = Stroke::new(1.5, color); + if count.arrows > 0 { + let h = SIGN / 2.0 - 0.5; + let (from, tip) = (center + vec2(-h, h), center + vec2(h, -h)); + let dir = (tip - from).normalized(); + let head = 4.5; + let base = tip - dir * head; + let side = vec2(-dir.y, dir.x) * (head * 0.55); + painter.line_segment([from, base + dir * 0.5], stroke); + painter.add(egui::Shape::convex_polygon( + vec![tip, base + side, base - side], + color, + Stroke::NONE, + )); + } else { + // The ring's outer edge within the sign's box, as the arrow's. + painter.circle_stroke(center, SIGN / 2.0 - 1.0, stroke); + } +} + +/// Result of a frame of the notation panel. +#[derive(Default)] +pub struct NotationResponse { + pub clicked: Option, + pub context: Option<(NodeId, NotationCommand)>, + /// A move of the better line of this marked move was clicked: (marked node, moves to show). + pub best: Option<(NodeId, usize)>, + /// Open the editor for this comment (a double click, the menu). + pub edit: Option, + /// Delete this comment (the menu). + pub delete: Option, + /// Put or take off this symbol on this move (the menu), at once. + pub nag: Option<(NodeId, Nag)>, + /// The editor's «Done» or «Cancel». + pub editor: Option, + /// The engine line shown on the board goes into the game as a variation. + pub insert_preview: bool, +} + +#[derive(Clone, Copy, Debug)] +pub enum NotationCommand { + Promote, + Delete, + /// Paste a line from the clipboard (docs/design/paste-variation.md). + Paste, + /// A game against Maia from this position (docs/design/play-from-position.md). + PlayFrom, + /// Add the exact path through this move to an opening repertoire. + Train, +} + +/// Which comment of the game: after a move (`After(ROOT)`: the start of the game), or +/// before a move (an introduction to a line, only an existing one). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Slot { + After(NodeId), + Before(NodeId), +} + +impl Slot { + pub fn node(self) -> NodeId { + match self { + Slot::After(id) | Slot::Before(id) => id, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EditorOutcome { + Done, + Cancel, +} + +/// A comment being written: its draft text and symbols (user-comments.md §3.4). +pub struct CommentEditor { + pub slot: Slot, + pub text: String, + /// The text as the editor opened (unchanged: the comment's bytes stay). + pub initial: String, + /// The draft symbols of the move (all of them; the two groups are toggled). + pub nags: Vec, + pub initial_nags: Vec, + /// «Comment after 4…Nf6», and its short form for a narrow panel. + pub title: String, + pub short_title: String, + /// A translation of this comment was on the screen: the original is edited. + pub translated: bool, + /// Put the keyboard into the field (on opening, on Enter from the game). + pub focus: bool, + /// Scroll the editor into view (on opening). + pub scroll: bool, + /// The text field's id, to know whether it has the keyboard. + pub field_id: Option, +} + +impl CommentEditor { + /// Something to write: the text or the symbols changed. + pub fn changed(&self) -> bool { + self.text.trim() != self.initial.trim() || self.nags != self.initial_nags + } + + pub fn text_changed(&self) -> bool { + self.text.trim() != self.initial.trim() + } +} + +/// The six symbols of a move and the eight of a position, as the editor and the move's +/// menu offer them (user-comments.md §3.4): (NAG, symbol, name). +pub const MOVE_NAGS: [(Nag, &str, &str); 6] = [ + (Nag(1), "!", "Good move"), + (Nag(2), "?", "Mistake"), + (Nag(3), "!!", "Brilliant move"), + (Nag(4), "??", "Blunder"), + (Nag(5), "!?", "Interesting move"), + (Nag(6), "?!", "Dubious move"), +]; +pub const POSITION_NAGS: [(Nag, &str, &str); 8] = [ + (Nag(10), "=", "Equal position"), + (Nag(13), "∞", "Unclear position"), + (Nag(14), "⩲", "White is slightly better"), + (Nag(15), "⩱", "Black is slightly better"), + (Nag(16), "±", "White is better"), + (Nag(17), "∓", "Black is better"), + (Nag(18), "+−", "White is winning"), + (Nag(19), "−+", "Black is winning"), +]; + +fn is_position_nag(n: Nag) -> bool { + (10..=19).contains(&n.0) +} + +/// `nag` put on or taken off `nags`: one symbol of its group (move or position) at a +/// time; the same symbol again takes it off; the other symbols stay. +pub fn toggle_nag(nags: &[Nag], nag: Nag) -> Vec { + let same_group = |n: &Nag| { + if nag.is_move_assessment() { + n.is_move_assessment() + } else { + is_position_nag(*n) + } + }; + let had = nags + .iter() + .any(|n| *n == nag || (n.0 >= 10 && n.0 <= 12 && nag.0 == 10)); + let mut out: Vec = nags.iter().copied().filter(|n| !same_group(n)).collect(); + if !had { + out.push(nag); + out.sort(); + } + out +} + +/// The symbol of a group that is on: `=` for $10–$12. +fn group_current(nags: &[Nag], position: bool) -> Option { + nags.iter() + .copied() + .find(|n| { + if position { + is_position_nag(*n) + } else { + n.is_move_assessment() + } + }) + .map(|n| if (10..=12).contains(&n.0) { Nag(10) } else { n }) +} + +const ROW_H: f32 = 26.0; +const NUM_W: f32 = 38.0; +/// A move's cell is no wider than this: in a wide panel (the notation under the board) +/// the two moves of a row stay together. +const CELL_MAX: f32 = 160.0; +/// Moves of an engine's better line shown under a marked move. +const MARK_LINE_MOVES: usize = 6; + +impl Notation<'_> { + pub fn show(mut self, ui: &mut Ui) -> NotationResponse { + let mut out = NotationResponse::default(); + let mut editor = self.editor.take(); + let game = self.game; + let editing = editor.as_ref().map(|e| e.slot); + let root_comments = comment_text( + game.node(NodeId::ROOT) + .map(|n| n.comments_after()) + .unwrap_or(&[]), + ); + if editing == Some(Slot::After(NodeId::ROOT)) { + editor_block(ui, &mut editor, false, &mut out); + } else if !root_comments.is_empty() { + comment_block( + ui, + &self, + &root_comments, + Slot::After(NodeId::ROOT), + &mut out, + ); + } + + let mut row = Row::default(); + let mut node = NodeId::ROOT; + while let Some(child) = game.main_child(node) { + let Some(n) = game.node(child) else { break }; + let before = comment_text(n.comments_before()); + if editing == Some(Slot::Before(child)) { + row.flush(ui, &self, &mut out); + editor_block(ui, &mut editor, false, &mut out); + } else if !before.is_empty() { + row.flush(ui, &self, &mut out); + comment_block(ui, &self, &before, Slot::Before(child), &mut out); + } + let (num, color) = game.move_number(child).unwrap_or((0, Color::White)); + if color == Color::White { + row.flush(ui, &self, &mut out); + row.num = num; + row.white = Some(child); + } else { + if row.white.is_none() { + row.num = num; + } + row.black = Some(child); + } + let after = comment_text(n.comments_after()); + let vars = game.variations(node); + // A block under the move only for an error (its better line): !! and ! say + // all they have to say beside the move. + let mark = self + .marks + .and_then(|m| m.get(&child)) + .filter(|m| m.judgement.is_error()); + let editing_after = editing == Some(Slot::After(child)); + let interrupted = editing_after + || !after.is_empty() + || !vars.is_empty() + || !n.unparsed().is_empty() + || mark.is_some(); + if interrupted || color == Color::Black { + row.flush(ui, &self, &mut out); + if let Some(mark) = mark { + mark_block(ui, &self, child, mark, &mut out); + } + if editing_after { + editor_block(ui, &mut editor, false, &mut out); + } else if !after.is_empty() { + comment_block(ui, &self, &after, Slot::After(child), &mut out); + } + for u in n.unparsed() { + unparsed_block(ui, u); + } + for &v in vars { + variation_block(ui, &self, v, &mut editor, &mut out); + } + } + node = child; + } + row.flush(ui, &self, &mut out); + + let result = game.result().as_str(); + if result != "*" { + ui.add_space(6.0); + ui.vertical_centered(|ui| ui.label(RichText::new(result).strong().size(16.0))); + } + out + } +} + +#[derive(Default)] +struct Row { + num: u32, + white: Option, + black: Option, +} + +impl Row { + fn flush(&mut self, ui: &mut Ui, n: &Notation, out: &mut NotationResponse) { + if self.white.is_none() && self.black.is_none() { + return; + } + let width = ui.available_width(); + let (rect, _) = ui.allocate_exact_size(vec2(width, ROW_H), Sense::hover()); + let painter = ui.painter(); + let visuals = ui.visuals(); + painter.rect_filled( + egui::Rect::from_min_size(rect.min, vec2(NUM_W, ROW_H)), + 0.0, + visuals.faint_bg_color, + ); + painter.text( + rect.left_center() + vec2(NUM_W - 8.0, 0.0), + Align2::RIGHT_CENTER, + self.num.to_string(), + FontId::proportional(14.0), + visuals.weak_text_color(), + ); + let cell_w = ((width - NUM_W) / 2.0).min(CELL_MAX); + let cells = [(self.white, 0.0), (self.black, cell_w)]; + for (id, off) in cells { + let cell = + egui::Rect::from_min_size(rect.min + vec2(NUM_W + off, 0.0), vec2(cell_w, ROW_H)); + match id { + Some(id) => { + let resp = ui.interact(cell, ui.id().with(("mv", id.index())), Sense::click()); + let dim = n + .dim_until + .is_some_and(|p| n.game.node(id).is_some_and(|nd| nd.ply() <= p)); + let mark = n.marks.and_then(|m| m.get(&id)); + let text_right = paint_move_cell( + ui, + cell, + n.game, + id, + mark, + id == n.cursor, + resp.hovered(), + dim, + ); + let mut right = text_right; + if let Some(&(count, shown)) = n.mistakes.and_then(|m| m.get(&id)) { + let color = if shown { + ui.visuals().warn_fg_color + } else { + ui.visuals().error_fg_color + }; + // A pill right after the move: its own, readable on the selected one. + let galley = ui.painter().layout_no_wrap( + format!("×{count}"), + FontId::proportional(12.0), + Color32::WHITE, + ); + let pill = egui::Rect::from_min_size( + egui::pos2( + text_right + 4.0, + cell.center().y - galley.size().y / 2.0 - 1.0, + ), + galley.size() + vec2(8.0, 2.0), + ); + ui.painter().rect_filled(pill, 7.0, color); + ui.painter() + .galley(pill.min + vec2(4.0, 1.0), galley, Color32::WHITE); + right = pill.right(); + let tip = if shown { + crate::i18n::trf("Mistakes: {n}; the move was shown", &[("n", &count)]) + } else { + crate::i18n::trf("Mistakes on this move: {n}", &[("n", &count)]) + }; + resp.clone().on_hover_text(tip); + } + if let Some(&count) = n.shapes.and_then(|s| s.get(&id)) { + let color = if id == n.cursor { + ui.visuals().selection.stroke.color + } else { + ui.visuals().weak_text_color() + }; + let x = + (right + SIGN_GAP + SIGN / 2.0).min(cell.right() - SIGN / 2.0 - 2.0); + paint_shapes_sign( + ui.painter(), + egui::pos2(x, cell.center().y), + count, + color, + ); + resp.clone().on_hover_text(count.hint()); + } + handle_move_response(ui, &resp, n, id, out); + } + None => { + ui.painter().text( + cell.left_center() + vec2(10.0, 0.0), + Align2::LEFT_CENTER, + "…", + FontId::proportional(15.0), + ui.visuals().weak_text_color(), + ); + } + } + } + *self = Row::default(); + } +} + +fn handle_move_response( + ui: &Ui, + resp: &egui::Response, + n: &Notation, + id: NodeId, + out: &mut NotationResponse, +) { + if resp.clicked() { + out.clicked = Some(id); + } + if n.scroll_to_cursor && id == n.cursor { + resp.scroll_to_me(Some(egui::Align::Center)); + } + let is_variation = n.game.child_index(id).is_some_and(|i| i > 0) || !n.game.is_mainline(id); + if n.read_only { + return; + } + // The menu is about the move it opens on: the move becomes the current one. + if resp.secondary_clicked() && id != n.cursor { + out.clicked = Some(id); + } + resp.context_menu(|ui| { + let node = n.game.node(id); + let has_comment = node.is_some_and(|nd| !comment_text(nd.comments_after()).is_empty()); + let label = if has_comment { + tr("Edit comment…") + } else { + tr("Comment…") + }; + if ui + .add(egui::Button::new(label).shortcut_text("Enter")) + .clicked() + { + out.edit = Some(Slot::After(id)); + ui.close(); + } + if has_comment && ui.button(tr("Delete comment")).clicked() { + out.delete = Some(Slot::After(id)); + ui.close(); + } + // The symbols act at once and keep the menu open: «?» off, «?!» on. + let nags = node.map(|nd| nd.nags().to_vec()).unwrap_or_default(); + symbol_row(ui, &nags, &MOVE_NAGS, true, &mut |nag| { + out.nag = Some((id, nag)) + }); + symbol_row(ui, &nags, &POSITION_NAGS, false, &mut |nag| { + out.nag = Some((id, nag)) + }); + if n.game.main_child(NodeId::ROOT) == Some(id) { + ui.separator(); + if ui.button(tr("Comment at the start of the game…")).clicked() { + out.edit = Some(Slot::After(NodeId::ROOT)); + ui.close(); + } + } + ui.separator(); + if ui + .add(egui::Button::new(tr("Paste a line from the clipboard")).shortcut_text("Ctrl+V")) + .on_hover_text(tr( + "Moves or a PGN game from the clipboard, as a variation from where they part from this game", + )) + .clicked() + { + out.context = Some((id, NotationCommand::Paste)); + ui.close(); + } + if is_variation && ui.button(tr("Make main line")).clicked() { + out.context = Some((id, NotationCommand::Promote)); + ui.close(); + } + if ui.button(tr("Delete move and continuation")).clicked() { + out.context = Some((id, NotationCommand::Delete)); + ui.close(); + } + if !crate::platform::CAPS.play && !crate::platform::CAPS.training { + return; + } + ui.separator(); + if crate::platform::CAPS.play { + let over = n.game.position(id).and_then(|p| { + if p.is_checkmate() { + Some(tr("checkmate")) + } else if p.is_stalemate() { + Some(tr("stalemate")) + } else if p.is_insufficient_material() { + Some(tr("neither side can checkmate")) + } else { + None + } + }); + let play = ui + .add_enabled( + over.is_none(), + egui::Button::new(tr("Play on from here…")).shortcut_text("Ctrl+G"), + ) + .on_hover_text(tr("A game against the computer from this position")); + let play = match over { + Some(why) => play.on_disabled_hover_text(crate::i18n::trf( + "The game is over here: {why}", + &[("why", &why)], + )), + None => play, + }; + if play.clicked() { + out.context = Some((id, NotationCommand::PlayFrom)); + ui.close(); + } + } + if crate::platform::CAPS.training { + let line = crate::train::TrainStart::from_game(n.game, id); + let add = ui + .add_enabled( + line.is_some(), + egui::Button::new(tr("Add to repertoire…")), + ) + .on_hover_text(tr("Add only the path from the start through this move, with its comments and NAGs")) + .on_disabled_hover_text(if id == NodeId::ROOT { + tr("Select the move up to which to add") + } else { + tr("The line has a null move (--): it cannot be played on the board") + }); + if add.clicked() { + out.context = Some((id, NotationCommand::Train)); + ui.close(); + } + } + }); + let _ = ui; +} + +/// A row of symbol toggles: the one on is pressed; `on` gets the symbol clicked. +fn symbol_row( + ui: &mut Ui, + nags: &[Nag], + set: &[(Nag, &str, &'static str)], + moves: bool, + on: &mut dyn FnMut(Nag), +) { + symbol_row_sized(ui, nags, set, moves, SYMBOL_W, on); +} + +/// A symbol button's width; the gap between them. +const SYMBOL_W: f32 = 24.0; +const SYMBOL_GAP: f32 = 2.0; + +/// `symbol_row` with buttons `w` wide (narrower in a narrow panel). The pressed symbol +/// is drawn in the selection's text colour, not its own: on the selection fill the +/// assessment colours read badly. +fn symbol_row_sized( + ui: &mut Ui, + nags: &[Nag], + set: &[(Nag, &str, &'static str)], + moves: bool, + w: f32, + on: &mut dyn FnMut(Nag), +) { + let current = group_current(nags, !moves); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = if w < SYMBOL_W { 1.0 } else { SYMBOL_GAP }; + for (nag, sym, name) in set { + let pressed = current == Some(*nag); + let mut text = RichText::new(*sym).size(if w < SYMBOL_W { 14.0 } else { 15.0 }); + if pressed { + text = text.strong().color(ui.visuals().selection.stroke.color); + } else if moves && let Some(c) = assessment_text_color(*nag, ui.visuals().dark_mode) { + text = text.color(c); + } + let r = ui + .add_sized([w, 24.0], egui::Button::selectable(pressed, text)) + .on_hover_text(symbol_hint(*nag, name)); + if r.clicked() { + on(*nag); + } + } + }); +} + +/// «Good move (Ctrl+1)». +fn symbol_hint(nag: Nag, name: &'static str) -> String { + if nag.is_move_assessment() { + format!("{} (Ctrl+{})", tr(name), nag.0) + } else { + tr(name).to_owned() + } +} + +#[allow(clippy::too_many_arguments)] +fn paint_move_cell( + ui: &Ui, + cell: egui::Rect, + game: &Game, + id: NodeId, + mark: Option<&Mark>, + current: bool, + hovered: bool, + dim: bool, +) -> f32 { + let visuals = ui.visuals(); + if current { + ui.painter() + .rect_filled(cell, 2.0, visuals.selection.bg_fill); + } else if hovered { + ui.painter() + .rect_filled(cell, 2.0, visuals.widgets.hovered.weak_bg_fill); + } + let node = game.node(id); + let san = game.game_move(id).map(|m| m.san.as_str()).unwrap_or("?"); + let san = crate::san::show(san); + let (mut sym, mut color) = node + .map(|n| move_glyph(n.nags(), visuals.dark_mode)) + .unwrap_or((String::new(), None)); + // The engine's verdict right after the move, the move in its color (as on Lichess); + // the author's own sign stands instead when there is one. + let authored = node.is_some_and(|n| n.nags().iter().any(|g| g.is_move_assessment())); + if let Some(m) = mark + && !authored + { + sym.insert_str(0, judgement_symbol(m.judgement)); + color = Some(judgement_text_color(m.judgement, visuals.dark_mode)); + } + let text_color = if current { + visuals.selection.stroke.color + } else if dim { + visuals.weak_text_color() + } else { + color.unwrap_or(visuals.text_color()) + }; + ui.painter() + .text( + cell.left_center() + vec2(10.0, 0.0), + Align2::LEFT_CENTER, + format!("{san}{sym}"), + crate::assets::bold(16.0), + text_color, + ) + .right() +} + +/// "Mistake. Best: 23…Nf6 24.Nd5 …" under a marked main-line move. Each move opens the line +/// on the board up to it; the move shown on the board is highlighted like the game cursor. +fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut NotationResponse) { + let color = judgement_text_color(mark.judgement, ui.visuals().dark_mode); + let start = n + .game + .position(mark.base) + .map(|p| (p.fullmoves().get(), p.turn())); + let shown = n + .preview + .filter(|(base, san, _)| *base == mark.base && *san == mark.best_san.as_slice()) + .map(|(_, _, shown)| shown); + egui::Frame::new() + .fill(ui.visuals().extreme_bg_color) + .inner_margin(egui::Margin { + left: 10, + right: 10, + top: 3, + bottom: 3, + }) + .stroke(Stroke::new(1.0, color.gamma_multiply(0.6))) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(3.0, 2.0); + ui.label( + RichText::new(format!("{}.", judgement_name(mark.judgement))) + .color(color) + .strong(), + ); + if mark.best_san.is_empty() { + return; + } + ui.label(RichText::new(tr("Best:")).weak()); + // Short by default; grows while the line is stepped through on the board. + let visible = MARK_LINE_MOVES.max(shown.unwrap_or(0)); + for (i, san) in mark.best_san.iter().enumerate().take(visible) { + let label = match start { + Some((num, turn)) => { + let ply = i as u32 + u32::from(turn == Color::Black); + let num = num + ply / 2; + if ply.is_multiple_of(2) { + format!("{num}.{san}") + } else if i == 0 { + format!("{num}…{san}") + } else { + san.clone() + } + } + None => san.clone(), + }; + let label = crate::san::show(&label).into_owned(); + let current = shown == Some(i + 1); + let resp = move_chip(ui, &label, None, current, None) + .on_hover_text(tr("Show this line on the board")); + if current && n.scroll_to_cursor { + resp.scroll_to_me(Some(egui::Align::Center)); + } + if resp.clicked() { + out.best = Some((id, i + 1)); + } + } + if mark.best_san.len() > visible { + ui.label(RichText::new("…").weak()); + } + // The line being stepped through on the board: added from here (there is + // no separate strip for it). + if shown.is_some() + && ui + .small_button(tr("+ Add as variation")) + .on_hover_text(tr( + "Puts the line into the game as a variation (Ctrl+Z to undo)", + )) + .clicked() + { + out.insert_preview = true; + } + }); + }); +} + +/// Colour of a move-assessment NAG ($1-$6): the owner's palette (chess.com's), bright, +/// for badges and dark backgrounds. +pub fn assessment_color(nag: Nag) -> Option { + Some(match nag.0 { + 1 => Color32::from_rgb(0x81, 0xb6, 0x4c), + 2 => Color32::from_rgb(0xff, 0xa4, 0x59), + 3 => Color32::from_rgb(0x26, 0xc2, 0xa3), + 4 => Color32::from_rgb(0xfa, 0x41, 0x2d), + 5 => Color32::from_rgb(0xea, 0x45, 0xd8), + 6 => Color32::from_rgb(0x56, 0xb4, 0xe9), + _ => return None, + }) +} + +/// The same as text: on a light background darkened to stay readable (contrast at least +/// 4.5:1), as on Android. +pub fn assessment_text_color(nag: Nag, dark: bool) -> Option { + if dark { + return assessment_color(nag); + } + Some(match nag.0 { + 1 => Color32::from_rgb(0x5b, 0x81, 0x35), + 2 => Color32::from_rgb(0xc2, 0x57, 0x00), + 3 => Color32::from_rgb(0x1a, 0x84, 0x6f), + 4 => Color32::from_rgb(0xd2, 0x30, 0x1c), + 5 => Color32::from_rgb(0xb0, 0x25, 0x9f), + 6 => Color32::from_rgb(0x1f, 0x72, 0xa8), + _ => return None, + }) +} + +/// Move-assessment glyph (`!`, `?`, …) with its color, plus position assessments. +fn move_glyph(nags: &[Nag], dark: bool) -> (String, Option) { + let mut s = String::new(); + let mut color = None; + for nag in nags { + let Some(sym) = nag.symbol() else { + s.push_str(&format!(" ${}", nag.0)); + continue; + }; + if nag.is_move_assessment() { + let Some(c) = assessment_text_color(*nag, dark) else { + continue; + }; + color = Some(c); + s.push_str(sym); + } else { + s.push(' '); + s.push_str(sym); + } + } + (s, color) +} + +/// The text of comments as shown (see [`chess_core::comment_display_text`]). +pub fn comment_text(comments: &[String]) -> String { + chess_core::comment_display_text(comments) +} + +fn block_frame(ui: &Ui) -> egui::Frame { + egui::Frame::new() + .fill(ui.visuals().extreme_bg_color) + .inner_margin(egui::Margin::symmetric(10, 6)) + .stroke(Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) +} + +/// The text to show for a comment and its translation mark. +fn translated<'a>(n: &'a Notation, text: &'a str) -> (&'a str, Option<&'a Translated>) { + match n.translations.and_then(|t| t.get(text)) { + Some(m @ Translated::Translated(t)) => (t.as_str(), Some(m)), + m => (text, m), + } +} + +/// "⇄" (machine translation, the original in the tooltip), "⋯" (on its way), "âš " (failed). +/// "⇄" (machine translation, the original in the tooltip), "⋯" (on its way), "âš " (failed), +/// drawn at `at` without taking part in the layout (it may not widen the panel). +fn translation_mark(ui: &mut Ui, at: egui::Pos2, mark: &Translated, original: &str) { + let (sym, color, tip, name) = mark_info(ui, mark, original); + let rect = ui.painter().text( + at, + Align2::RIGHT_TOP, + sym, + FontId::proportional(13.0), + color, + ); + let id = ui.id().with(("mark", at.x as i32, at.y as i32)); + let r = ui.interact(rect.expand(2.0), id, Sense::hover()); + r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, name)); + r.on_hover_ui(|ui| { + ui.set_max_width(360.0); + ui.label(tip); + }); +} + +/// The mark after a comment inside a line of text (a variation): part of the flow. +fn inline_mark(ui: &mut Ui, mark: &Translated, original: &str) { + let (sym, color, tip, name) = mark_info(ui, mark, original); + let r = + ui.add(egui::Label::new(RichText::new(sym).size(13.0).color(color)).sense(Sense::hover())); + r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, name)); + r.on_hover_ui(|ui| { + ui.set_max_width(360.0); + ui.label(tip); + }); +} + +fn mark_info( + ui: &Ui, + mark: &Translated, + original: &str, +) -> (&'static str, Color32, String, &'static str) { + match mark { + Translated::Translated(_) => { + let mut o: String = original.chars().take(1000).collect(); + if original.chars().count() > 1000 { + o.push('…'); + } + ( + "⇄", + ui.visuals().weak_text_color(), + format!("{}\n{o}", tr("Machine translation. Original:")), + tr("Machine translation"), + ) + } + Translated::Pending => ( + "⋯", + ui.visuals().weak_text_color(), + tr("Translating…").to_owned(), + tr("Translating…"), + ), + Translated::Bad => ( + "âš ", + ui.visuals().warn_fg_color, + tr("This comment could not be translated — the original is shown. Press “Retryâ€� in the line above the notation.").to_owned(), + tr("Not translated"), + ), + } +} + +/// Room kept on the right of a comment for its translation mark. +const MARK_ROOM: f32 = 18.0; + +fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut NotationResponse) { + let (shown, mark) = translated(n, text); + // The start of the game draws on the board: the sign at the block's right edge. + let shapes = (slot == Slot::After(NodeId::ROOT)) + .then(|| n.shapes.and_then(|s| s.get(&NodeId::ROOT)).copied()) + .flatten(); + let room = MARK_ROOM * (u8::from(mark.is_some()) + u8::from(shapes.is_some())) as f32; + let mut frame = block_frame(ui); + if room > 0.0 { + frame = frame.inner_margin(egui::Margin { + left: 10, + right: 10 + room as i8, + top: 6, + bottom: 6, + }); + } + // The whole block, not only its text, takes the double click and the right button, + // and lights up under the mouse (known from the last frame). + let id = ui.id().with(( + "comment", + slot.node().index(), + matches!(slot, Slot::Before(_)), + )); + if ui.ctx().read_response(id).is_some_and(|r| r.hovered()) { + frame = frame.fill(ui.visuals().widgets.hovered.weak_bg_fill); + } + let r = frame.show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(RichText::new(shown).color(comment_color(ui)).size(14.5)); + }); + let resp = ui.interact(r.response.rect, id, Sense::click()); + comment_response(&resp, slot, out); + if let Some(m) = mark { + let at = r.response.rect.right_top() + vec2(-8.0, 7.0); + translation_mark(ui, at, m, text); + } + if let Some(count) = shapes { + let shift = if mark.is_some() { MARK_ROOM } else { 0.0 }; + let center = r.response.rect.right_top() + vec2(-8.0 - shift - SIGN / 2.0, 6.0 + 9.0); + paint_shapes_sign(ui.painter(), center, count, ui.visuals().weak_text_color()); + let id = ui.id().with("root_shapes"); + ui.interact( + egui::Rect::from_center_size(center, vec2(SIGN, SIGN) + vec2(4.0, 4.0)), + id, + Sense::hover(), + ) + .on_hover_text(count.hint()); + } +} + +/// A double click opens the comment for editing; the right button offers that and +/// deleting (user-comments.md §5.2). +fn comment_response(resp: &egui::Response, slot: Slot, out: &mut NotationResponse) { + if resp.hovered() { + resp.ctx.set_cursor_icon(egui::CursorIcon::Text); + } + if resp.double_clicked() { + out.edit = Some(slot); + } + resp.context_menu(|ui| { + if ui.button(tr("Edit comment…")).clicked() { + out.edit = Some(slot); + ui.close(); + } + if ui.button(tr("Delete comment")).clicked() { + out.delete = Some(slot); + ui.close(); + } + }); +} + +/// The comment editor on the spot of its comment (user-comments.md §3.4). +/// `in_variation`: inside a variation's frame (tighter margins). +fn editor_block( + ui: &mut Ui, + editor: &mut Option<&mut CommentEditor>, + in_variation: bool, + out: &mut NotationResponse, +) { + let Some(ed) = editor.as_deref_mut() else { + return; + }; + let focused = ed + .field_id + .is_some_and(|id| ui.ctx().memory(|m| m.focused() == Some(id))); + let sel = ui.visuals().selection; + let stroke = if focused { + Stroke::new(1.5, sel.stroke.color) + } else { + Stroke::new(1.0, ui.visuals().weak_text_color()) + }; + let width = ui.available_width(); + let narrow = width < 360.0; + let margin = if narrow { + egui::Margin::symmetric(6, 6) + } else if in_variation { + egui::Margin::symmetric(8, 6) + } else { + egui::Margin::symmetric(10, 6) + }; + // The notation's visible height: the field is capped so that the title, the buttons + // and a notation row above and below stay in view (user-comments.md §12). + let viewport_h = ui.clip_rect().height(); + let frame_top = ui.cursor().top(); + let has_symbols = ed.slot != Slot::After(NodeId::ROOT) && !matches!(ed.slot, Slot::Before(_)); + let r = egui::Frame::new() + .fill(ui.visuals().extreme_bg_color) + .inner_margin(margin) + .stroke(stroke) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + // The title and the buttons: «Done» at the far right, as in every dialog. + let mut title_id = None; + // A row 30 high (the buttons' height), the title centred on it. + let row_w = ui.available_width(); + ui.allocate_ui_with_layout( + vec2(row_w, 30.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + let buttons = if narrow { + 2.0 * 30.0 + 6.0 + } else { + crate::game_view::text_width(ui, tr("Done"), egui::TextStyle::Button) + + crate::game_view::text_width( + ui, + tr("Cancel"), + egui::TextStyle::Button, + ) + + 4.0 * ui.spacing().button_padding.x + + 3.0 * ui.spacing().item_spacing.x + }; + let room = ui.available_width() - buttons; + let title = if narrow + || crate::game_view::text_width(ui, &ed.title, egui::TextStyle::Body) > room + { + &ed.short_title + } else { + &ed.title + }; + title_id = Some(ui.add(egui::Label::new(title).truncate()).id); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 6.0; + let (done, cancel) = if narrow { + ( + crate::widgets::icon_button(ui, true, true) + .on_hover_text(tr("Done (Enter)")), + crate::widgets::icon_button(ui, false, false) + .on_hover_text(tr("Cancel (Esc)")), + ) + } else { + ( + crate::widgets::primary(ui, tr("Done")).on_hover_text("Enter"), + ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(0.0, 30.0))) + .on_hover_text("Esc"), + ) + }; + if done.clicked() { + out.editor = Some(EditorOutcome::Done); + } + if cancel.clicked() { + out.editor = Some(EditorOutcome::Cancel); + } + }); + }, + ); + // The symbols: the move's six, then the position's eight (a «±▾» menu when + // they do not fit on the line). Not for the start of the game. + if has_symbols { + let group = |n: f32| n * SYMBOL_W + (n - 1.0) * SYMBOL_GAP; + // The two groups, the separator and the gaps around it. + let both = group(6.0) + 4.0 + 12.0 + 4.0 + group(8.0) <= ui.available_width(); + // In a narrow panel (240 wide, less inside a variation) the six buttons + // are 22 wide: the row must not widen the panel. + let w = if ui.available_width() < 300.0 { + 22.0 + } else { + SYMBOL_W + }; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let mut toggled = None; + symbol_row_sized(ui, &ed.nags, &MOVE_NAGS, true, w, &mut |nag| { + toggled = Some(nag) + }); + if both { + ui.add(egui::Separator::default().spacing(12.0)); + symbol_row(ui, &ed.nags, &POSITION_NAGS, false, &mut |nag| { + toggled = Some(nag) + }); + } else { + let current = group_current(&ed.nags, true) + .and_then(|n| n.symbol()) + .unwrap_or("±"); + ui.menu_button(format!("{current}â–¾"), |ui| { + symbol_row(ui, &ed.nags, &POSITION_NAGS[..4], false, &mut |nag| { + toggled = Some(nag) + }); + symbol_row(ui, &ed.nags, &POSITION_NAGS[4..], false, &mut |nag| { + toggled = Some(nag) + }); + }) + .response + .on_hover_text(tr("Position assessment")); + } + if let Some(nag) = toggled { + ed.nags = toggle_nag(&ed.nags, nag); + } + }); + } + ui.add_space(4.0); + // The text in its own box: 2 to 12 lines, then it scrolls inside; in a low + // window fewer lines, so that a notation row stays above and below. + let color = comment_color(ui); + let font = FontId::proportional(14.5); + let row_h = ui.fonts_mut(|f| f.row_height(&font)); + let overhead = ui.cursor().top() - frame_top; + let below = + if narrow { 0.0 } else { 22.0 } + f32::from(margin.bottom) + 2.0 * ROW_H + 8.0; + let cap = (12.0 * row_h + 8.0) + .min(viewport_h - overhead - below) + .max(2.0 * row_h + 8.0); + let focus_now = std::mem::take(&mut ed.focus); + let field_fill = if ui.visuals().dark_mode { + ui.visuals().panel_fill + } else { + Color32::WHITE + }; + let mut border = ui.visuals().widgets.inactive.bg_stroke; + if border.color.a() == 0 { + border = Stroke::new(1.0, ui.visuals().weak_text_color().gamma_multiply(0.35)); + } + let resp = egui::Frame::new() + .fill(field_fill) + .stroke(border) + .corner_radius(4) + .inner_margin(egui::Margin::symmetric(6, 4)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical() + .id_salt("comment_editor_scroll") + .max_height(cap) + .auto_shrink([false, true]) + .show(ui, |ui| { + let o = egui::TextEdit::multiline(&mut ed.text) + .id_salt("comment_editor") + .frame(egui::Frame::NONE) + .desired_rows(2) + .desired_width(f32::INFINITY) + .font(font.clone()) + .text_color(color) + .hint_text(tr("Your comment…")) + .show(ui); + if focus_now { + // The cursor at the end, and the end in view: one adds to a + // comment more often than replaces it. + o.response.request_focus(); + let end = egui::text::CCursor::new(ed.text.chars().count()); + let mut state = o.state.clone(); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::one(end))); + state.store(ui.ctx(), o.response.id); + let caret = o + .galley + .pos_from_cursor(end) + .translate(o.galley_pos.to_vec2()); + ui.scroll_to_rect(caret, Some(egui::Align::Max)); + } + o.response.response + }) + .inner + }) + .inner; + ed.field_id = Some(resp.id); + if let Some(t) = title_id { + resp.clone().labelled_by(t); + } + if !narrow { + ui.add_space(4.0); + ui.label( + RichText::new(tr( + "Enter — done · Esc — cancel · Shift+Enter — new paragraph", + )) + .size(11.5) + .color(ui.visuals().weak_text_color()), + ); + } + if ed.translated { + ui.add_space(2.0); + ui.label( + RichText::new(tr( + "⇄ You are editing the original; its translation will be dropped", + )) + .size(11.5) + .color(ui.visuals().weak_text_color()), + ); + } + }); + if std::mem::take(&mut ed.scroll) { + // The move's own row above the frame stays in view too. + let rect = r.response.rect; + let with_row = egui::Rect::from_min_max(rect.min - vec2(0.0, ROW_H + 8.0), rect.max); + ui.scroll_to_rect(with_row, None); + } +} + +fn unparsed_block(ui: &mut Ui, text: &str) { + block_frame(ui).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label( + RichText::new(text) + .monospace() + .color(ui.visuals().warn_fg_color), + ) + .on_hover_text(tr("PGN fragment that could not be parsed; kept as is")); + }); +} + +fn comment_color(ui: &Ui) -> Color32 { + if ui.visuals().dark_mode { + Color32::from_rgb(0x9e, 0xc4, 0xe0) + } else { + Color32::from_rgb(0x2a, 0x5b, 0x8a) + } +} + +/// One piece of a variation's flowing text. +enum Token { + Move { + id: NodeId, + label: String, + /// The label with the move number, for the move that starts a piece of the flow. + numbered: String, + color: Option, + shapes: Option, + }, + Comment { + slot: Slot, + text: String, + }, + Unparsed(String), + Open, + Close, +} + +fn variation_block( + ui: &mut Ui, + n: &Notation, + start: NodeId, + editor: &mut Option<&mut CommentEditor>, + out: &mut NotationResponse, +) { + let mut tokens = Vec::new(); + line_tokens(n, start, ui.visuals().dark_mode, &mut tokens); + let editing = editor.as_ref().map(|e| e.slot); + // The flow is cut where the editor stands: after the move for «after», before it + // for «before»; a comment being edited is replaced by the editor. + let cut = editing.and_then(|slot| { + tokens + .iter() + .position(|t| matches!(t, Token::Comment { slot: s, .. } if *s == slot)) + .map(|i| (i, true)) + .or_else(|| match slot { + Slot::After(id) => tokens + .iter() + .position(|t| matches!(t, Token::Move { id: m, .. } if *m == id)) + .map(|i| (i + 1, false)), + Slot::Before(id) => tokens + .iter() + .position(|t| matches!(t, Token::Move { id: m, .. } if *m == id)) + .map(|i| (i, false)), + }) + }); + block_frame(ui).show(ui, |ui| { + ui.set_width(ui.available_width()); + match cut { + None => flow(ui, n, &tokens, false, out), + Some((at, replaces)) => { + flow(ui, n, &tokens[..at], false, out); + editor_block(ui, editor, true, out); + let rest = if replaces { at + 1 } else { at }; + flow(ui, n, &tokens[rest..], true, out); + } + } + }); +} + +/// A move in flowing text: the current one highlighted as in the main-line table, +/// the others lit under the mouse. Painted by hand, so its size never changes with the +/// mouse (a button's frame does). +fn move_chip( + ui: &mut Ui, + label: &str, + color: Option, + current: bool, + shapes: Option, +) -> egui::Response { + let sel = ui.visuals().selection; + let font = FontId::proportional(15.0); + let text_color = if current { + sel.stroke.color + } else { + color.unwrap_or_else(|| ui.visuals().text_color()) + }; + let galley = ui + .painter() + .layout_no_wrap(label.to_owned(), font, text_color); + let pad = vec2(4.0, 2.0); + // The sign and the chip's own right padding after it. + let sign = if shapes.is_some() { + SIGN_GAP + SIGN + 2.0 + } else { + 0.0 + }; + let (rect, resp) = + ui.allocate_exact_size(galley.size() + 2.0 * pad + vec2(sign, 0.0), Sense::click()); + if current { + ui.painter().rect( + rect, + 2.0, + sel.bg_fill, + Stroke::new(1.0, sel.stroke.color), + egui::StrokeKind::Inside, + ); + } else if resp.hovered() { + ui.painter() + .rect_filled(rect, 2.0, ui.visuals().widgets.hovered.weak_bg_fill); + } + let text_right = rect.min.x + pad.x + galley.size().x; + ui.painter().galley(rect.min + pad, galley, text_color); + if let Some(count) = shapes { + let color = if current { + sel.stroke.color + } else { + ui.visuals().weak_text_color() + }; + let center = egui::pos2(text_right + SIGN_GAP + SIGN / 2.0, rect.center().y); + paint_shapes_sign(ui.painter(), center, count, color); + return resp.on_hover_text(count.hint()); + } + resp +} + +/// Lays out tokens as flowing text. +fn flow( + ui: &mut Ui, + n: &Notation, + tokens: &[Token], + numbered_first: bool, + out: &mut NotationResponse, +) { + if tokens.is_empty() { + return; + } + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(3.0, 2.0); + for (k, t) in tokens.iter().enumerate() { + match t { + Token::Move { + id, + label, + numbered, + color, + shapes, + } => { + let current = *id == n.cursor; + // After the editor the flow starts anew: with the move number. + let label = if k == 0 && numbered_first { + numbered + } else { + label + }; + let resp = move_chip(ui, label, *color, current, *shapes); + handle_move_response(ui, &resp, n, *id, out); + } + Token::Comment { slot, text } => { + let (shown, mark) = translated(n, text); + let resp = ui.add( + egui::Label::new(RichText::new(shown).color(comment_color(ui)).size(14.5)) + .sense(Sense::click()), + ); + comment_response(&resp, *slot, out); + if let Some(m) = mark { + inline_mark(ui, m, text); + } + } + Token::Unparsed(u) => { + ui.label( + RichText::new(u) + .monospace() + .color(ui.visuals().warn_fg_color), + ); + } + Token::Open => { + ui.label(RichText::new("(").weak()); + } + Token::Close => { + ui.label(RichText::new(")").weak()); + } + } + } + }); +} + +/// The tokens of a line starting at `first` (a variation move), nested lines inside. +fn line_tokens(n: &Notation, first: NodeId, dark: bool, tokens: &mut Vec) { + let game = n.game; + let mut node = first; + let mut need_number = true; + loop { + let Some(nd) = game.node(node) else { return }; + let before = comment_text(nd.comments_before()); + if !before.is_empty() { + tokens.push(Token::Comment { + slot: Slot::Before(node), + text: before, + }); + need_number = true; + } + let (num, color) = game.move_number(node).unwrap_or((0, Color::White)); + let san = game.game_move(node).map(|m| m.san.as_str()).unwrap_or("?"); + let san = crate::san::show(san); + let (sym, sym_color) = move_glyph(nd.nags(), dark); + let label = match (color, need_number) { + (Color::White, _) => format!("{num}.{san}{sym}"), + (Color::Black, true) => format!("{num}…{san}{sym}"), + (Color::Black, false) => format!("{san}{sym}"), + }; + need_number = false; + let numbered = match color { + Color::White => label.clone(), + Color::Black => format!("{num}…{san}{sym}"), + }; + tokens.push(Token::Move { + id: node, + label, + numbered, + color: sym_color, + shapes: n.shapes.and_then(|s| s.get(&node)).copied(), + }); + let after = comment_text(nd.comments_after()); + if !after.is_empty() { + tokens.push(Token::Comment { + slot: Slot::After(node), + text: after, + }); + need_number = true; + } + for u in nd.unparsed() { + tokens.push(Token::Unparsed(u.clone())); + } + // Alternatives to this move are printed right after it (PGN order), + // except for the line's own first move whose siblings belong to the outer level. + if node != first + && let Some(parent) = game.parent(node) + { + for &v in game.variations(parent) { + tokens.push(Token::Open); + line_tokens(n, v, dark, tokens); + tokens.push(Token::Close); + need_number = true; + } + } + match game.main_child(node) { + Some(next) => node = next, + None => return, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shape_counts_find_arrows_and_circles_of_comments_only() { + let game = chess_core::parse_str( + "{[%csl Re4]} 1. e4 {[%cal Gg1f3,Gf1c4] [%csl Ga8] [%clk 0:01:00]} e5 {plain} \ + (1... c5 {[%csl Yd5]}) 2. Nf3 {[%eval 0.3]} *", + ) + .game; + let counts = shape_counts(&game); + let e4 = game.main_child(NodeId::ROOT).unwrap(); + let c5 = game.variations(e4)[0]; + assert_eq!(counts.len(), 3, "{counts:?}"); + assert_eq!( + counts[&NodeId::ROOT], + ShapeCount { + arrows: 0, + circles: 1 + } + ); + assert_eq!( + counts[&e4], + ShapeCount { + arrows: 2, + circles: 1 + } + ); + assert_eq!( + counts[&c5], + ShapeCount { + arrows: 0, + circles: 1 + } + ); + } + + #[test] + fn the_sign_hint_leaves_out_a_count_of_none() { + crate::i18n::set_lang(crate::i18n::Lang::En); + let hint = |arrows, circles| ShapeCount { arrows, circles }.hint(); + assert_eq!( + hint(2, 1), + "Arrows: 2 · circles: 1 — shown on the board at this move" + ); + assert_eq!(hint(2, 0), "Arrows: 2 — shown on the board at this move"); + assert_eq!(hint(0, 1), "Circles: 1 — shown on the board at this move"); + } +} diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs new file mode 100644 index 0000000..1385d58 --- /dev/null +++ b/apps/desktop/src/online.rs @@ -0,0 +1,180 @@ +//! Games from Lichess and Chess.com on the desktop: the databases live in +//! `/online/`; the downloads themselves are the `online-games` crate's +//! (shared with the Android app). Both public APIs are probed at start; a platform that +//! does not answer as expected (offline, the API changed) is simply not offered. The +//! web version has no online games: there only the names of such databases are known. + +use std::path::{Path, PathBuf}; + +pub use online_games::{Account, Platform, State}; +#[cfg(not(web))] +pub use online_games::{ + Done, Failure, LICHESS_RATE, Lookup, Progress, download, lookup, probe_all, valid_nick, +}; + +/// Where the online databases live. +pub fn dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("online")) +} + +/// The online databases already holding `account` (see [`online_games::holding`]). +pub fn holding(account: &Account) -> Vec { + dir().map_or_else(Vec::new, |d| online_games::holding(&d, account)) +} + +/// An online database (it has a state file). +pub fn is_online(pgn: &Path) -> bool { + dir().is_some_and(|d| online_games::is_online(&d, pgn)) +} + +/// Where the found accounts go (see [`online_games::targets`]). +pub fn targets(start: &[Account], together: bool) -> Vec<(Vec, PathBuf)> { + dir().map_or_else(Vec::new, |d| online_games::targets(&d, start, together)) +} + +/// "5 min ago", "3 h ago", "2 d ago" for a time in Unix seconds. +pub fn ago(t: i64) -> String { + use crate::i18n::trf; + let s = (online_games::now_secs() - t).max(0); + match s { + 0..3600 => trf("{n} min ago", &[("n", &(s / 60).max(1))]), + 3600..86400 => trf("{n} h ago", &[("n", &(s / 3600))]), + _ => trf("{n} d ago", &[("n", &(s / 86400))]), + } +} + +#[cfg(not(web))] +/// The probe results and what the window shows, kept by the application. +pub struct Probe { + job: Option>, + pub available: [bool; 2], + /// When the last probe finished (a platform that did not answer is asked again + /// after [`Probe::RETRY`]: the machine may have come online). + last: Option, + ctx: egui::Context, +} + +#[cfg(not(web))] +impl Probe { + const RETRY: std::time::Duration = std::time::Duration::from_secs(300); + + /// Starts probing both platforms in the background. + pub fn start(ctx: &egui::Context) -> Probe { + let mut p = Probe { + job: None, + available: [false; 2], + last: None, + ctx: ctx.clone(), + }; + p.spawn(); + p + } + + fn spawn(&mut self) { + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = self.ctx.clone(); + let spawned = std::thread::Builder::new() + .name("online-probe".into()) + .spawn(move || { + let _ = tx.send(probe_all()); + ctx.request_repaint(); + }); + self.job = spawned.ok().map(|_| rx); + } + + pub fn poll(&mut self) { + if let Some(rx) = &self.job + && let Some(a) = match rx.try_recv() { + Ok(a) => Some(a), + Err(std::sync::mpsc::TryRecvError::Empty) => None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Some([false; 2]), + } + { + // A platform that answered once stays offered for the session (a later + // failure shows as an error in the window). + for (have, now) in self.available.iter_mut().zip(a) { + *have |= now; + } + self.job = None; + self.last = Some(web_time::Instant::now()); + } + if self.job.is_none() && !self.available.iter().all(|a| *a) { + match self.last { + Some(t) if t.elapsed() >= Self::RETRY => self.spawn(), + // Wake up for the retry even when nothing else repaints. + Some(t) => self.ctx.request_repaint_after(Self::RETRY - t.elapsed()), + None => {} + } + } + } + + pub fn any(&self) -> bool { + self.available.iter().any(|a| *a) + } + + pub fn pending(&self) -> bool { + self.job.is_some() + } + + /// An explicit retry from the online-games dialog, without duplicate jobs. + pub fn retry(&mut self) { + if !self.pending() { + self.spawn(); + } + } + + #[cfg(test)] + pub(crate) fn pending_for_test( + ctx: &egui::Context, + ) -> (Self, std::sync::mpsc::Sender<[bool; 2]>) { + let (tx, rx) = std::sync::mpsc::channel(); + ( + Self { + job: Some(rx), + available: [false; 2], + last: None, + ctx: ctx.clone(), + }, + tx, + ) + } + + pub fn has(&self, p: Platform) -> bool { + self.available[p.index()] + } +} + +#[cfg(all(test, not(web)))] +mod tests { + use super::*; + + #[test] + fn probe_distinguishes_pending_unavailable_ready_and_disconnected() { + let ctx = egui::Context::default(); + let (mut probe, tx) = Probe::pending_for_test(&ctx); + assert!(probe.pending()); + assert!(!probe.any()); + probe.retry(); // An in-flight request is kept, never duplicated. + tx.send([false, false]).unwrap(); + probe.poll(); + assert!(!probe.pending()); + assert!(!probe.any()); + + let (mut probe, tx) = Probe::pending_for_test(&ctx); + tx.send([true, false]).unwrap(); + probe.poll(); + assert!(!probe.pending()); + assert!(probe.has(Platform::Lichess)); + assert!(!probe.has(Platform::ChessCom)); + + let (mut probe, tx) = Probe::pending_for_test(&ctx); + drop(tx); + probe.poll(); + assert!( + !probe.pending(), + "a failed worker must not leave a perpetual check" + ); + assert!(!probe.any()); + } +} diff --git a/apps/desktop/src/online_ui.rs b/apps/desktop/src/online_ui.rs new file mode 100644 index 0000000..3186754 --- /dev/null +++ b/apps/desktop/src/online_ui.rs @@ -0,0 +1,783 @@ +//! The window "Games from Lichess and Chess.com": a player's nickname (anyone's: the +//! user's own, a pupil's, an opponent's; another one for Chess.com if it differs), the +//! platforms to look on, what was found, then the downloads with their progress. Only the +//! platforms that answered the probe at start are offered (`online::Probe`). + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use egui::{RichText, Ui}; + +use crate::board_search::Background; +use crate::i18n::{games, tr, trf}; +use crate::online::{self, Account, Done, Failure, Lookup, Platform, Probe}; + +/// What the window asks of the application. +pub enum OnlineEvent { + /// A database was downloaded (or partly, then cancelled): put it on the shelf. + Added(PathBuf), + /// A database got new games: reload it. + Updated(PathBuf), + /// Show this database (and the window closes). + Open(PathBuf), + /// A download finished while the window was closed: say how it went. + Message(String), +} + +struct Job { + /// One account, or several downloaded into one database. + accounts: Vec, + path: PathBuf, + /// Updating a database already on the shelf (not a first download). + update: bool, + /// The database is new (so the totals of the accounts are what is left to fetch). + fresh: bool, + status: Arc, + work: Background>, + /// When Stop was pressed: a download that does not stop soon (a stalled + /// connection) leaves the list; its database stays claimed until it ends. + stopped: Option, + /// Started on its own at the program's start: says something only when it added + /// games (no "no new games" on every start, no error over a network that is off). + quiet: bool, +} + +/// A finished download. +struct Outcome { + accounts: Vec, + path: PathBuf, + update: bool, + /// The platform that failed (`None`: the disk, or not known). + platform: Option, + result: Result, +} + +#[derive(Default)] +pub struct OnlineDialog { + pub open: bool, + nick: String, + /// A different nickname on Chess.com, when asked for. + other: Option, + pick: [bool; 2], + lookup: Option>>, + found: Vec<(Platform, Lookup)>, + /// The nicknames `found` answers. + found_for: (String, String), + jobs: Vec, + results: Vec, + /// Two accounts found: download them into separate databases (one by default). + separate: bool, + /// Dev hook (screenshots): look the nickname up once the probe answered, and + /// download what was found. + auto_find: bool, + auto_download: bool, + /// Put the cursor into the nickname field (the window was just opened). + focus: bool, + /// Online databases to update on their own (at the start), one after another: the + /// sites ask for one export at a time. + queued: std::collections::VecDeque, +} + +/// Where the found accounts go (see [`online_games::targets`]). +fn targets(start: &[Account], together: bool) -> Vec<(Vec, PathBuf)> { + online::targets(start, together) +} + +/// The file name of a database without the extension. +fn db_name(path: &Path) -> String { + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +/// What went wrong, in words for a chess player (the technical text goes under +/// "Details"). +fn failure_text(platform: Option, e: &Failure) -> String { + let p = platform.map_or("—", Platform::name); + match e { + Failure::Network(_) => trf( + "{p} does not answer. Check the internet connection and try again.", + &[("p", &p)], + ), + Failure::RateLimited => trf( + "{p} asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.", + &[("p", &p)], + ), + Failure::Unexpected(_) => trf( + "{p} answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.", + &[("p", &p)], + ), + Failure::Disk(_) => { + tr("Could not write the database: no permission to write or the disk is full.") + .to_owned() + } + Failure::Busy => tr("This database is being downloaded already.").to_owned(), + } +} + +/// "“Nameâ€�: +12 games, 6 600 in all" and the like. +fn outcome_text(o: &Outcome) -> String { + let name = db_name(&o.path); + match &o.result { + Ok(d) if d.cancelled => trf( + "“{name}â€�: stopped, {total} in the database", + &[("name", &name), ("total", &games(d.total as usize))], + ), + Ok(d) if d.added == 0 => trf("“{name}â€�: no new games", &[("name", &name)]), + Ok(d) => trf( + "“{name}â€�: +{added}, {total} in all", + &[ + ("name", &name), + ("added", &games(d.added as usize)), + ("total", &games(d.total as usize)), + ], + ), + Err(e) => trf( + "“{name}â€�: {e}", + &[("name", &name), ("e", &failure_text(o.platform, e))], + ), + } +} + +impl OnlineDialog { + /// Opens the window with an empty nickname, ready to type: the databases already + /// downloaded fetch their new games with "⟳ New games", so the next search is + /// usually for another player. A search still running keeps its nickname. + pub fn open(&mut self) { + if !self.open && self.lookup.is_none() { + self.nick.clear(); + self.other = None; + self.pick = [true, true]; + self.found.clear(); + self.focus = true; + } + self.open = true; + } + + /// Dev hook: `CP_ONLINE=` (`,` for two nicknames) opens the + /// window and looks the nickname up, `CP_ONLINE_DOWNLOAD=1` then downloads + /// (screenshots, manual checks). + pub fn from_env() -> OnlineDialog { + let mut d = OnlineDialog::default(); + if let Ok(nick) = std::env::var("CP_ONLINE") { + d.open = true; + let (nick, other) = match nick.split_once(',') { + Some((a, b)) => (a.to_owned(), Some(b.to_owned())), + None => (nick, None), + }; + d.nick = nick; + d.other = other; + d.pick = [true, true]; + d.auto_find = true; + d.auto_download = std::env::var("CP_ONLINE_DOWNLOAD").is_ok(); + } + d + } + + /// Databases being downloaded or updated. + pub fn busy(&self) -> Vec { + self.jobs.iter().map(|j| j.path.clone()).collect() + } + + /// The games downloaded so far by the running jobs (for the shelf card), if any run. + pub fn running(&self) -> Option { + (!self.jobs.is_empty()).then(|| self.jobs.iter().map(|j| j.work.progress()).sum()) + } + + /// Stops the downloads and waits a little for them to save what they fetched (on + /// quitting: the next update then continues without duplicates). Returns the new + /// databases among them, to put on the shelf with what they got so far. + pub fn stop_all(&mut self) -> Vec { + let new = self + .jobs + .iter() + .filter(|j| !j.update) + .map(|j| j.path.clone()) + .collect(); + for j in &self.jobs { + j.work.cancel(); + } + let start = web_time::Instant::now(); + while !self.jobs.is_empty() && start.elapsed() < std::time::Duration::from_secs(3) { + self.jobs.retain(|j| j.work.poll().is_none()); + std::thread::sleep(std::time::Duration::from_millis(30)); + } + new + } + + /// Fetches the new games of an online database on the shelf. + pub fn update(&mut self, path: &Path, ctx: &egui::Context) { + let Some(state) = online::State::load(path) else { + return; + }; + self.start(state.accounts(), path.to_owned(), true, ctx); + } + + /// Updates these online databases on their own, one after another, once a site + /// answers (the program's start: every downloaded database gets its new games). + pub fn update_quietly(&mut self, paths: impl IntoIterator) { + for p in paths { + if !self.queued.contains(&p) { + self.queued.push_back(p); + } + } + } + + /// The next queued update, when nothing else is being downloaded. + fn next_queued(&mut self, probe: &Probe, ctx: &egui::Context) { + if !self.jobs.is_empty() || !probe.any() { + return; + } + while let Some(path) = self.queued.pop_front() { + if let Some(state) = online::State::load(&path) { + self.start(state.accounts(), path, true, ctx); + if let Some(j) = self.jobs.last_mut() { + j.quiet = true; + } + return; + } + } + } + + fn start(&mut self, accounts: Vec, path: PathBuf, update: bool, ctx: &egui::Context) { + if self.jobs.iter().any(|j| j.path == path) { + return; + } + let fresh = online::State::load(&path).is_none(); + let now = ctx.input(|i| i.time); + let a = accounts.clone(); + let status = Arc::new(online::Progress::default()); + let (s, p) = (status.clone(), path.clone()); + if let Some(work) = Background::spawn(ctx, now, move |progress, cancel| { + Some(online::download(&a, &p, progress, cancel, &s)) + }) { + self.results.retain(|o| o.path != path); + self.jobs.push(Job { + accounts, + path, + update, + fresh, + status, + work, + stopped: None, + quiet: false, + }); + } + } + + fn nick_for(&self, p: Platform) -> String { + match (p, &self.other) { + (Platform::ChessCom, Some(o)) => o.trim().to_owned(), + _ => self.nick.trim().to_owned(), + } + } + + /// Collects finished work; the window itself when open. + pub fn show(&mut self, ctx: &egui::Context, probe: &mut Probe) -> Vec { + probe.poll(); + let mut events = Vec::new(); + if let Some(l) = &self.lookup + && let Some(r) = l.poll() + { + self.found = r.unwrap_or_default(); + self.lookup = None; + } + let mut i = 0; + while i < self.jobs.len() { + if let Some(r) = self.jobs[i].work.poll() { + let job = self.jobs.remove(i); + let result = r.unwrap_or(Err(Failure::Network("stopped".into()))); + // What a failed download got before the failure is kept: a new + // database goes on the shelf with it, an updated one is reloaded. + let total = match &result { + Ok(d) => d.total, + Err(_) => online::State::load(&job.path).map_or(0, |s| s.games), + }; + if job.update { + if result.as_ref().map_or(true, |d| d.added > 0) { + events.push(OnlineEvent::Updated(job.path.clone())); + } + } else if total > 0 { + events.push(OnlineEvent::Added(job.path.clone())); + } + let platform = match &result { + Err(Failure::Disk(_)) | Ok(_) => None, + Err(_) => job + .accounts + .get(job.status.account.load(Ordering::Relaxed)) + .map(|a| a.platform), + }; + let outcome = Outcome { + accounts: job.accounts, + path: job.path, + update: job.update, + platform, + result, + }; + // An update of its own speaks only of new games. + let worth = !job.quiet || outcome.result.as_ref().is_ok_and(|d| d.added > 0); + if worth { + if !self.open { + events.push(OnlineEvent::Message(outcome_text(&outcome))); + } + self.results.push(outcome); + } + } else if self.jobs[i] + .stopped + .is_some_and(|t| t.elapsed() > std::time::Duration::from_secs(10)) + { + self.jobs.remove(i); + } else { + i += 1; + } + } + self.next_queued(probe, ctx); + if !self.jobs.is_empty() || self.lookup.is_some() || !self.queued.is_empty() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } + if !self.open { + return events; + } + let mut open = true; + egui::Window::new(tr("Games from Lichess and Chess.com")) + .open(&mut open) + .default_width(540.0) + .collapsible(false) + .pivot(egui::Align2::CENTER_TOP) + .default_pos(ctx.content_rect().center_top() + egui::vec2(0.0, 120.0)) + .show(ctx, |ui| { + self.body(ui, probe, &mut events); + }); + if !open || events.iter().any(|e| matches!(e, OnlineEvent::Open(_))) { + self.open = false; + } + events + } + + fn body(&mut self, ui: &mut Ui, probe: &mut Probe, events: &mut Vec) { + ui.label( + RichText::new(tr( + "Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.", + )) + .weak(), + ); + ui.add_space(6.0); + if !probe.any() { + if probe.pending() { + ui.add(egui::Label::new(tr("Checking access to Lichess and Chess.com…")).wrap()); + } else { + ui.add( + egui::Label::new(tr( + "Couldn't connect. Check your internet connection and try again.", + )) + .wrap(), + ); + if ui.button(tr("Retry")).clicked() { + probe.retry(); + } + } + ui.add_space(6.0); + } + let both = probe.has(Platform::Lichess) && probe.has(Platform::ChessCom); + let mut enter = false; + ui.horizontal(|ui| { + ui.label(tr("Player's nickname")); + let r = ui.add( + egui::TextEdit::singleline(&mut self.nick) + .hint_text(tr("as on the site")) + .desired_width(220.0), + ); + if std::mem::take(&mut self.focus) { + r.request_focus(); + } + if r.changed() { + self.found.clear(); + } + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + }); + ui.horizontal(|ui| { + for p in Platform::ALL { + if probe.has(p) { + let i = p as usize; + if ui.checkbox(&mut self.pick[i], p.name()).changed() { + self.found.clear(); + } + } + } + }); + if both && self.pick[1] { + let mut clear = false; + let mut same = false; + match &mut self.other { + Some(o) => { + ui.horizontal(|ui| { + ui.label(tr("Nickname on Chess.com")); + let r = ui.add(egui::TextEdit::singleline(o).desired_width(180.0)); + clear |= r.changed(); + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + same = ui + .small_button("🗙") + .on_hover_text(tr("The same nickname")) + .clicked(); + }); + } + None => { + if ui.link(tr("A different nickname on Chess.com")).clicked() { + self.other = Some(self.nick.clone()); + clear = true; + } + } + } + if same { + self.other = None; + clear = true; + } + if clear { + self.found.clear(); + } + } + let wanted: Vec = Platform::ALL + .into_iter() + .filter(|p| probe.has(*p) && self.pick[*p as usize]) + .collect(); + let nicks = ( + self.nick_for(Platform::Lichess), + self.nick_for(Platform::ChessCom), + ); + let valid = wanted + .iter() + .all(|p| online::valid_nick(&self.nick_for(*p))); + ui.add_space(4.0); + ui.horizontal(|ui| { + let searching = self.lookup.is_some(); + let auto = self.auto_find && probe.any(); + if auto { + self.auto_find = false; + } + let can = !wanted.is_empty() && valid && !searching; + if ui.add_enabled(can, egui::Button::new(tr("Find"))).clicked() + || ((auto || enter) && can) + { + let list: Vec<(Platform, String)> = + wanted.iter().map(|p| (*p, self.nick_for(*p))).collect(); + self.found_for = nicks.clone(); + let now = ui.input(|i| i.time); + self.lookup = Background::spawn(ui.ctx(), now, move |_, _| { + Some( + list.into_iter() + .map(|(p, n)| (p, online::lookup(p, &n))) + .collect(), + ) + }); + } + if searching { + ui.add(egui::Spinner::new()); + } else if !self.nick.trim().is_empty() && !valid { + ui.label( + RichText::new(tr("Letters, digits, _ and -, 2 to 30 characters")) + .color(ui.visuals().warn_fg_color), + ); + } + }); + if self.found_for == nicks && !self.found.is_empty() { + self.found_ui(ui); + } + self.jobs_ui(ui); + self.results_ui(ui, events); + } + + /// What was found, the choice of one database or separate ones, and Download. + fn found_ui(&mut self, ui: &mut Ui) { + ui.add_space(4.0); + let start: Vec = self + .found + .iter() + .filter_map(|(_, l)| match l { + Lookup::Found(a) + if !self + .jobs + .iter() + .any(|j| j.accounts.iter().any(|x| x.same(a))) => + { + Some(a.clone()) + } + _ => None, + }) + .collect(); + // Accounts some database already holds (then the "first time" estimate is wrong). + let held = |a: &Account| !online::holding(a).is_empty(); + for (p, l) in &self.found { + match l { + Lookup::Found(a) => { + let what = match (a.games, a.months) { + (Some(g), _) if !held(a) => { + let secs = g / online::LICHESS_RATE; + trf( + "{p}: {name} — {games}, about {m} min the first time", + &[ + ("p", &p.name()), + ("name", &a.username), + ("games", &games(g as usize)), + ("m", &secs.div_ceil(60).max(1)), + ], + ) + } + (Some(g), _) => trf( + "{p}: {name} — {games}", + &[ + ("p", &p.name()), + ("name", &a.username), + ("games", &games(g as usize)), + ], + ), + (_, Some(m)) => trf( + "{p}: {name} — months with games: {m}", + &[("p", &p.name()), ("name", &a.username), ("m", &m)], + ), + _ => format!("{}: {}", p.name(), a.username), + }; + ui.label(format!("✔ {what}")); + } + Lookup::NotFound => { + ui.label( + RichText::new(trf( + "✖ {p}: no player with this nickname — check the spelling", + &[("p", &p.name())], + )) + .weak(), + ); + } + Lookup::Failed(e) => { + ui.label( + RichText::new(format!("✖ {}", failure_text(Some(*p), e))) + .color(ui.visuals().warn_fg_color), + ); + } + } + } + if start.is_empty() { + return; + } + // Both platforms: one database by default (the player's games together). + let together = start.len() > 1 && !self.separate; + if start.len() > 1 { + let mut one = !self.separate; + if ui + .checkbox( + &mut one, + tr("Merge the games of both sites into one database"), + ) + .on_hover_text(tr("Otherwise each site gets a database of its own")) + .changed() + { + self.separate = !one; + } + } + // Where the games go, and what is there already. + let targets = targets(&start, together); + for (_, path) in &targets { + let text = match online::State::load(path) { + Some(s) => trf( + "Into “{name}â€� (already {n} there; only new games are added)", + &[("name", &db_name(path)), ("n", &games(s.games as usize))], + ), + None => trf( + "Into the new database “{name}â€�", + &[("name", &db_name(path))], + ), + }; + ui.label(RichText::new(text).weak()); + } + ui.add_space(4.0); + let auto = std::mem::take(&mut self.auto_download); + if crate::widgets::primary(ui, tr("⬇ Download")).clicked() || auto { + // From the window the database goes (back) on the shelf, also when it was + // downloaded before and only gets the new games now. + for (t, path) in targets { + self.start(t, path, false, ui.ctx()); + } + } + } + + /// The running downloads: the database, the site and how far it got, Stop. + fn jobs_ui(&mut self, ui: &mut Ui) { + if self.jobs.is_empty() { + return; + } + ui.separator(); + let mut stop = None; + for (k, j) in self.jobs.iter().enumerate() { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(db_name(&j.path)).strong()); + if ui + .small_button(tr("Stop")) + .on_hover_text(tr( + "What is downloaded is kept; downloading again continues from there", + )) + .clicked() + { + stop = Some(k); + } + }); + let s = &j.status; + let Some(a) = j.accounts.get(s.account.load(Ordering::Relaxed)) else { + continue; + }; + let n = s.games.load(Ordering::Relaxed) as u64; + match (a.platform, a.games) { + (Platform::Lichess, Some(total)) if j.fresh && total > 0 => { + let left = total.saturating_sub(n) / online::LICHESS_RATE; + ui.label(trf( + "Lichess: {n} of about {t} · about {m} min left", + &[ + ("n", &crate::large_db::grouped(n as usize)), + ("t", &crate::large_db::grouped(total as usize)), + ("m", &left.div_ceil(60).max(1)), + ], + )); + ui.add(egui::ProgressBar::new((n as f32 / total as f32).min(1.0))); + } + (Platform::ChessCom, _) if s.months_total.load(Ordering::Relaxed) > 0 => { + let (done, all) = ( + s.months_done.load(Ordering::Relaxed), + s.months_total.load(Ordering::Relaxed), + ); + ui.label(trf( + "Chess.com: month {i} of {n} · {games}", + &[("i", &done), ("n", &all), ("games", &games(n as usize))], + )); + ui.add(egui::ProgressBar::new(done as f32 / all as f32)); + } + (p, _) => { + ui.label(format!("{}: {}", p.name(), games(n as usize))); + } + } + } + if let Some(k) = stop { + self.jobs[k].work.cancel(); + self.jobs[k] + .stopped + .get_or_insert_with(web_time::Instant::now); + } + ui.label( + RichText::new(tr( + "You can close the window: the download goes on, and what is downloaded is kept.", + )) + .weak(), + ); + } + + /// The finished downloads: how they went, Open the database / Try again. + fn results_ui(&mut self, ui: &mut Ui, events: &mut Vec) { + if self.results.is_empty() { + return; + } + ui.separator(); + let mut retry = None; + for (k, o) in self.results.iter().enumerate() { + match &o.result { + Ok(d) => { + ui.horizontal_wrapped(|ui| { + ui.label(format!("✔ {}", outcome_text(o))); + if d.total > 0 && ui.button(tr("Open the database")).clicked() { + events.push(OnlineEvent::Open(o.path.clone())); + } + }); + } + Err(e) => { + ui.label( + RichText::new(format!("âš  {}", outcome_text(o))) + .color(ui.visuals().warn_fg_color), + ); + ui.horizontal(|ui| { + if ui.button(tr("Try again")).clicked() { + retry = Some(k); + } + egui::CollapsingHeader::new(tr("Details")) + .id_salt(("online-details", k)) + .show(ui, |ui| { + ui.label(RichText::new(e.to_string()).small().weak()); + }); + }); + } + } + } + if let Some(k) = retry { + let o = self.results.remove(k); + self.start(o.accounts, o.path, o.update, ui.ctx()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rendered_text(dialog: &mut OnlineDialog, probe: &mut Probe) -> Vec { + let ctx = egui::Context::default(); + let mut text = Vec::new(); + for frame in 0..2 { + let output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(960.0, 900.0), + )), + time: Some(f64::from(frame)), + ..Default::default() + }, + |ui| { + egui::CentralPanel::default().show(ui, |ui| { + dialog.body(ui, probe, &mut Vec::new()); + }); + }, + ); + text = output + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.text().to_owned()), + _ => None, + }) + .collect(); + output.drop_without_applying_deltas(); + } + text + } + + #[test] + fn early_online_entry_explains_probe_state_and_only_offers_ready_platforms() { + let ctx = egui::Context::default(); + let (mut probe, tx) = Probe::pending_for_test(&ctx); + let mut dialog = OnlineDialog::default(); + dialog.open(); + dialog.nick = "SomePlayer".to_owned(); + let text = rendered_text(&mut dialog, &mut probe); + assert!( + text.iter() + .any(|t| t == tr("Checking access to Lichess and Chess.com…")) + ); + assert!(!text.iter().any(|t| t == "Lichess" || t == "Chess.com")); + tx.send([false, false]).unwrap(); + probe.poll(); + let text = rendered_text(&mut dialog, &mut probe); + assert!(text.iter().any(|t| t == tr("Couldn't connect. Check your internet connection and try again."))); + assert!(text.iter().any(|t| t == tr("Retry"))); + assert_eq!(dialog.nick, "SomePlayer"); + + let (mut probe, tx) = Probe::pending_for_test(&ctx); + tx.send([true, false]).unwrap(); + probe.poll(); + let text = rendered_text(&mut dialog, &mut probe); + assert!(text.iter().any(|t| t == "Lichess")); + assert!(!text.iter().any(|t| t == "Chess.com")); + assert!( + !text + .iter() + .any(|t| t == tr("Checking access to Lichess and Chess.com…")) + ); + assert_eq!(dialog.nick, "SomePlayer"); + } +} diff --git a/apps/desktop/src/opening_layout.rs b/apps/desktop/src/opening_layout.rs new file mode 100644 index 0000000..c79ce6e --- /dev/null +++ b/apps/desktop/src/opening_layout.rs @@ -0,0 +1,600 @@ +//! What the three opening-training screens share (docs/design/opening-trainer-v2-spec.md +//! §1): the frame of the game screen, the card, the board's PGN marks and the texts +//! about moves, sides and dates. + +use chess_core::shakmaty::{Color, Square, uci::UciMove}; +use chess_core::{Annotation, CommentPart, Game, MoveKind, NodeId, parse_comment}; +use egui::{Color32, RichText, Ui, vec2}; +use trainer::repertoire::{LearningSide, RepertoireId, TrainingMode}; + +use crate::board::{Arrow, Badge}; +use crate::i18n::{tr, trf}; +use crate::settings::Settings; + +/// The panel's least width: the table of repertoires still shows its numbers whole. +pub(crate) const SIDE_LEAST: f32 = 360.0; +/// Where the width the user dragged the panel to is kept for the app to save +/// (`Settings::opening_side_width`). +pub(crate) const SIDE_WIDTH_ID: &str = "opening_side_width"; +/// Under a stacked board: the panel's least height (`STACK_BOTTOM_MIN`). +const STACK_BOTTOM_MIN: f32 = 300.0; +const BOARD_MIN: f32 = 220.0; +/// Space between the blocks of the panel. +pub(crate) const GAP: f32 = 6.0; +/// The new moves of one session and of "10 more new". +pub(crate) const NEW_PER_SESSION: usize = 10; + +/// Header, side panel and board in the places of the game screen. The same panel id on +/// every screen of the section: switching screens never moves the board. +pub(crate) fn screen( + ui: &mut Ui, + this: &mut T, + header: impl FnOnce(&mut T, &mut Ui), + side: impl FnOnce(&mut T, &mut Ui), + board: impl FnOnce(&mut T, &mut Ui), +) { + egui::Panel::top("opening_header").show(ui, |ui| header(this, ui)); + let width = ui.available_width(); + let height = ui.available_height(); + let board_side = (height - 16.0).min(width - SIDE_LEAST - 24.0); + let board_stack = (width - 16.0).min(height - STACK_BOTTOM_MIN - 16.0); + let stacked = board_stack >= 1.25 * board_side; + let panel = if stacked { + let most = (height - BOARD_MIN - 16.0).max(STACK_BOTTOM_MIN); + let rest = (height - board_stack - 16.0).clamp(STACK_BOTTOM_MIN, most); + egui::Panel::bottom("opening_side_stacked") + .resizable(true) + .default_size(rest) + .size_range(STACK_BOTTOM_MIN..=most) + .show(ui, |ui| side(this, ui)) + } else { + let board = height - 16.0; + let most = (width - BOARD_MIN - 24.0).max(SIDE_LEAST); + let room = (width - board - 24.0).clamp(SIDE_LEAST, most); + let id = egui::Id::new(SIDE_WIDTH_ID); + let kept = ui.ctx().data(|d| d.get_temp::(id)); + let default = kept.unwrap_or_else(|| side_default(width, room)); + let handle = egui::Id::new("opening_side").with("__resize"); + // Until the user drags it, the panel follows the window: a window that opens + // small and grows gets the width of its final size, not of its first frame. + let dragging = ui + .ctx() + .read_response(handle) + .is_some_and(|r| r.dragged() || r.drag_stopped()); + if kept.is_none() && !dragging { + ui.ctx().data_mut(|d| { + d.remove::(egui::Id::new("opening_side")) + }); + } + let panel = egui::Panel::right("opening_side") + .resizable(true) + .default_size(default.clamp(SIDE_LEAST, most)) + .size_range(SIDE_LEAST..=most) + .show(ui, |ui| side(this, ui)); + // The width the user dragged to is kept; a window that squeezes the panel does + // not change it. + if ui + .ctx() + .read_response(handle) + .is_some_and(|r| r.drag_stopped()) + { + let shown = panel.response.rect.width().round(); + ui.ctx().data_mut(|d| d.insert_temp(id, shown)); + } + panel + }; + crate::widgets::check_panel("opening_side", &panel.response); + egui::CentralPanel::default().show(ui, |ui| { + let area = ui.available_rect_before_wrap(); + let side = area.width().min(area.height()).max(1.0).floor(); + let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor(); + let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor(); + let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side)); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| board(this, ui)); + }); +} + +/// The panel's width before the user drags it: about a third of the window, the board +/// keeping its room. +pub(crate) fn side_default(width: f32, room: f32) -> f32 { + (width * 0.36).clamp(380.0, 560.0).min(room) +} + +/// The frame of a state card (the player's card of a game against the computer). +pub(crate) fn card(ui: &Ui, active: bool, alert: bool) -> egui::Frame { + let mut frame = egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 6)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )); + if active { + frame = frame.fill(ui.visuals().selection.bg_fill.gamma_multiply(0.35)); + } + if alert { + frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color)); + } + frame +} + +/// The content size of a [`card`] filling a block of `height`: the frame's margins and +/// its stroke stay inside the block. +pub(crate) fn card_inner(ui: &Ui, height: f32) -> egui::Vec2 { + vec2(ui.available_width() - 22.0, height - 14.0).max(egui::Vec2::ZERO) +} + +/// A block of a fixed height: whatever it holds, what follows never moves. +pub(crate) fn fixed_block(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui) -> R) -> R { + let width = ui.available_width().max(1.0); + let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); + let mut child = ui.new_child( + egui::UiBuilder::new() + .max_rect(rect) + .layout(egui::Layout::top_down(egui::Align::Min)), + ); + child.set_clip_rect(rect.intersect(ui.clip_rect())); + add(&mut child) +} + +/// One line of text cut with "…", the whole text on hover. +pub(crate) fn line(ui: &mut Ui, text: impl Into) -> egui::Response { + let text = text.into(); + let hover = text.text().to_owned(); + let response = ui.add(egui::Label::new(text).truncate()); + if hover.is_empty() { + response + } else { + response.on_hover_text(hover) + } +} + +/// `text` cut on the left by whole words ("… 4. Ba4 Nf6") to fit `width` in `font`: +/// the last moves of a path matter most. +pub(crate) fn cut_left(ui: &Ui, text: &str, font: &egui::FontId, width: f32) -> String { + let fits = |text: &str| { + ui.fonts_mut(|fonts| { + fonts + .layout_no_wrap(text.to_owned(), font.clone(), Color32::WHITE) + .size() + .x + }) <= width + }; + if fits(text) { + return text.to_owned(); + } + let mut rest = text; + while let Some((_, tail)) = rest.split_once(' ') { + rest = tail; + let cut = format!("… {rest}"); + if fits(&cut) { + return cut; + } + } + format!("… {rest}") +} + +/// One line cut on the left ([`cut_left`]), the whole text on hover. +pub(crate) fn line_left(ui: &mut Ui, text: &str, strong: bool) -> egui::Response { + let font = egui::TextStyle::Body.resolve(ui.style()); + let shown = cut_left(ui, text, &font, ui.available_width()); + let mut rich = RichText::new(shown); + if strong { + rich = rich.strong(); + } + let response = ui.add(egui::Label::new(rich).truncate()); + if text.is_empty() { + response + } else { + response.on_hover_text(text) + } +} + +/// The trained colour of a repertoire, kept in the settings since 2.2.0 (an old "both +/// colours" repertoire opens for White). +pub(crate) fn side_of(settings: &Settings, id: &RepertoireId) -> LearningSide { + match settings.repertoire_modes.get(id.as_str()) { + Some((TrainingMode::Black, _)) => LearningSide::Black, + _ => LearningSide::White, + } +} + +pub(crate) fn set_side(settings: &mut Settings, id: &RepertoireId, side: LearningSide) { + let mode = match side { + LearningSide::White => TrainingMode::White, + LearningSide::Black => TrainingMode::Black, + }; + settings.repertoire_modes.insert( + id.to_string(), + (mode, trainer::repertoire::QueueMode::SpacedRepetition), + ); +} + +pub(crate) fn king(side: LearningSide) -> egui::Image<'static> { + crate::widgets::side_king(side == LearningSide::White, KING) +} + +/// The side of the king of [`king`] (as a 14-point â™” took). +pub(crate) const KING: f32 = 16.0; + +pub(crate) fn you_play(side: LearningSide) -> &'static str { + tr(match side { + LearningSide::White => "You play White", + LearningSide::Black => "You play Black", + }) +} + +pub(crate) fn orientation(side: LearningSide) -> Color { + side.color() +} + +/// "4. Ba4" or "4… Nf6" in the notation of the application. +pub(crate) fn move_text(game: &Game, node: NodeId) -> Option { + let (number, color) = game.move_number(node)?; + let san = crate::san::show(&game.game_move(node)?.san).into_owned(); + Some(match color { + Color::White => format!("{number}. {san}"), + Color::Black => format!("{number}… {san}"), + }) +} + +/// "1. e4 e5 2. Nf3": the moves from the start to `node` with move numbers. +pub(crate) fn path_text(game: &Game, node: NodeId) -> String { + let mut words = Vec::new(); + for id in game.path(node).into_iter().skip(1) { + let Some(mv) = game.game_move(id) else { + continue; + }; + let san = crate::san::show(&mv.san).into_owned(); + match game.move_number(id) { + Some((number, Color::White)) => words.push(format!("{number}. {san}")), + Some((number, Color::Black)) if words.is_empty() => { + words.push(format!("{number}… {san}")) + } + _ => words.push(san), + } + } + words.join(" ") +} + +/// The symbol of a move's assessment (`!`, `?!` …) and its colour for text. +pub(crate) fn assessment(game: &Game, node: NodeId, dark: bool) -> Option<(&'static str, Color32)> { + let nag = game + .node(node)? + .nags() + .iter() + .copied() + .find(|nag| nag.is_move_assessment())?; + Some(( + nag.symbol()?, + crate::notation::assessment_text_color(nag, dark)?, + )) +} + +/// The node reached from the root by these UCI moves. +pub(crate) fn node_at(game: &Game, path: &[String]) -> Option { + let mut at = NodeId::ROOT; + for uci in path { + let mv = uci + .parse::() + .ok()? + .to_move(game.position(at)?) + .ok()?; + at = game.find_child(at, mv)?; + } + Some(at) +} + +/// The UCI moves from the root to a node. +pub(crate) fn uci_path(game: &Game, node: NodeId) -> Vec { + game.path(node) + .into_iter() + .skip(1) + .filter_map(|id| game.game_move(id).and_then(|mv| mv.uci())) + .collect() +} + +/// "C84 · Ruy Lopez: Closed": the most precise named position on the way to `node`. +pub(crate) fn opening_text(game: &Game, node: NodeId) -> String { + let keys: Vec = game + .path(node) + .into_iter() + .filter_map(|id| game.position(id)) + .map(chess_openings::key) + .collect(); + match chess_openings::deepest(&keys) { + Some((_, id)) => { + let opening = chess_openings::get(id); + format!("{} · {}", opening.eco, opening.name) + } + None => String::new(), + } +} + +/// The start a repertoire's lines share: the last move before the first branching. +pub(crate) fn common_start(game: &Game) -> NodeId { + let mut at = NodeId::ROOT; + while let [only] = game.children(at) { + at = *only; + } + at +} + +pub(crate) fn last_move(game: &Game, node: NodeId) -> Option<(Square, Square)> { + match game.game_move(node)?.kind { + MoveKind::Normal(mv) => Some(( + mv.from().unwrap_or_else(|| mv.to()), + crate::board::ui_target(&mv), + )), + MoveKind::Null => None, + } +} + +/// The lines of a repertoire: the paths of its last moves, without switched-off +/// branches, in PGN order. +pub(crate) fn lines(game: &Game, disabled: impl Fn(&[String]) -> bool) -> Vec> { + let mut out = Vec::new(); + let mut stack = vec![(NodeId::ROOT, Vec::new())]; + while let Some((node, path)) = stack.pop() { + let children: Vec<_> = game + .children(node) + .iter() + .filter_map(|child| { + let uci = game.game_move(*child)?.uci()?; + let mut next = path.clone(); + next.push(uci); + (!disabled(&next)).then_some((*child, next)) + }) + .collect(); + if children.is_empty() { + if !path.is_empty() { + out.push(path); + } + } else { + stack.extend(children.into_iter().rev()); + } + } + out +} + +/// The end of the local day: "today" in the counts includes everything due before it. +pub(crate) fn end_of_today() -> i64 { + use chrono::{Local, TimeZone}; + let now = Local::now(); + let tomorrow = now.date_naive().succ_opt().unwrap_or(now.date_naive()); + tomorrow + .and_hms_opt(0, 0, 0) + .and_then(|midnight| Local.from_local_datetime(&midnight).earliest()) + .map_or(now.timestamp() + 24 * 60 * 60, |midnight| { + midnight.timestamp() - 1 + }) +} + +pub(crate) fn now() -> i64 { + chrono::Local::now().timestamp() +} + +/// "today at 18:40", "tomorrow", "in 3 days", then a date as in the library. +pub(crate) fn when(at: i64, now: i64) -> String { + use chrono::{Local, TimeZone}; + let (Some(at), Some(now)) = ( + Local.timestamp_opt(at, 0).single(), + Local.timestamp_opt(now, 0).single(), + ) else { + return String::new(); + }; + let days = (at.date_naive() - now.date_naive()).num_days(); + match days { + ..=0 => trf("today at {time}", &[("time", &at.format("%H:%M"))]), + 1 => tr("tomorrow").to_owned(), + 2..=6 => trf("in {days} days", &[("days", &days)]), + _ => at.format("%d.%m.%Y").to_string(), + } +} + +#[derive(Default)] +pub(crate) struct BoardAnnotations { + pub(crate) arrows: Vec, + pub(crate) circles: Vec<(Square, Color32)>, + pub(crate) badge: Option, +} + +/// The marks of a PGN move on the board: its assessment badge, `[%cal]` arrows and +/// `[%csl]` squares. +pub(crate) fn pgn_annotations_at(game: &Game, at: NodeId) -> BoardAnnotations { + let mut out = BoardAnnotations::default(); + let Some(node) = game.node(at) else { + return out; + }; + let square = node.game_move().and_then(|game_move| match game_move.kind { + MoveKind::Normal(mv) => Some(crate::board::ui_target(&mv)), + MoveKind::Null => None, + }); + if let Some(square) = square { + out.badge = node + .nags() + .iter() + .copied() + .find(|nag| nag.is_move_assessment()) + .and_then(|nag| { + Some(Badge { + square, + text: nag.symbol()?, + color: crate::notation::assessment_color(nag)?, + }) + }); + } + for comment in node.comments_after() { + for part in parse_comment(comment) { + match part { + CommentPart::Annotation(Annotation::Arrows(list)) => { + out.arrows + .extend(list.into_iter().map(|(color, from, to)| Arrow { + from, + to, + color: crate::game_view::shape_color(color), + weight: 0.9, + })); + } + CommentPart::Annotation(Annotation::Squares(list)) => { + out.circles.extend( + list.into_iter() + .map(|(color, square)| (square, crate::game_view::shape_color(color))), + ); + } + CommentPart::Text(_) | CommentPart::Annotation(_) => {} + } + } + } + out +} + +/// The position after a node, for a board that only shows it. +pub(crate) fn position_of(game: &Game, node: NodeId) -> chess_core::shakmaty::Chess { + game.position(node) + .or_else(|| game.position(NodeId::ROOT)) + .cloned() + .unwrap_or_default() +} + +/// A board that only shows a position. +pub(crate) fn still_board( + ui: &mut Ui, + state: &mut crate::board::BoardState, + settings: &Settings, + pos: &chess_core::shakmaty::Chess, + orientation: Color, + last_move: Option<(Square, Square)>, + annotations: &BoardAnnotations, +) { + crate::board::BoardView { + pos, + orientation, + last_move, + arrows: &annotations.arrows, + circles: &annotations.circles, + badge: annotations.badge, + interactive: false, + temporary_shapes: false, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: settings.animation.seconds(), + premove: None, + auto_queen: false, + alert: None, + } + .show(ui, state); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pgn_node_badges_keep_the_existing_palette_and_special_move_destinations() { + for (nag, symbol) in [ + (1, "!"), + (2, "?"), + (3, "!!"), + (4, "??"), + (5, "!?"), + (6, "?!"), + ] { + let game = chess_core::parse_str(&format!("1. e4 ${nag} *")).game; + let node = game.main_child(NodeId::ROOT).unwrap(); + let badge = pgn_annotations_at(&game, node).badge.unwrap(); + assert_eq!(badge.text, symbol); + assert_eq!(badge.square, Square::E4); + assert_eq!( + badge.color, + crate::notation::assessment_color(chess_core::Nag(nag)).unwrap() + ); + } + for (fen, san, expected) in [ + ("4k3/8/8/8/8/8/8/4K2R w K - 0 1", "O-O!!", Square::G1), + ("4k3/P7/8/8/8/8/8/4K3 w - - 0 1", "a8=Q+!", Square::A8), + ] { + let game = + chess_core::parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *")) + .game; + let node = game.main_child(NodeId::ROOT).unwrap(); + assert_eq!( + pgn_annotations_at(&game, node).badge.unwrap().square, + expected + ); + } + let game = chess_core::parse_str("1. e4 $14 *").game; + let node = game.main_child(NodeId::ROOT).unwrap(); + assert!( + pgn_annotations_at(&game, node).badge.is_none(), + "position assessments are not move badges" + ); + } + + #[test] + fn pgn_shapes_of_a_move_become_arrows_and_circles() { + let game = chess_core::parse_str("1. e4 {[%cal Re2e4,Ge7e5] [%csl Ye4]} *").game; + let node = game.main_child(NodeId::ROOT).unwrap(); + let marks = pgn_annotations_at(&game, node); + assert_eq!(marks.arrows.len(), 2); + assert_eq!( + marks.arrows[0].color, + crate::game_view::shape_color(chess_core::ShapeColor::Red) + ); + assert_eq!( + marks.circles, + [( + Square::E4, + crate::game_view::shape_color(chess_core::ShapeColor::Yellow) + )] + ); + assert!(pgn_annotations_at(&game, NodeId::ROOT).badge.is_none()); + } + + #[test] + fn common_start_stops_before_the_first_branching() { + let game = chess_core::parse_str("1. e4 e5 2. Nf3 (2. Bc4) Nc6 *").game; + let start = common_start(&game); + assert_eq!(uci_path(&game, start), ["e2e4", "e7e5"]); + let game = chess_core::parse_str("1. e4 (1. d4) *").game; + assert_eq!(common_start(&game), NodeId::ROOT); + let game = chess_core::parse_str("*").game; + assert_eq!(common_start(&game), NodeId::ROOT); + } + + #[test] + fn lines_are_the_last_moves_in_pgn_order_without_switched_off_branches() { + let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *").game; + let all = lines(&game, |_| false); + assert_eq!( + all, + [ + vec!["e2e4", "e7e5", "g1f3"], + vec!["e2e4", "e7e5", "f1c4"], + vec!["e2e4", "c7c5", "g1f3"], + ] + .map(|line| line.into_iter().map(str::to_owned).collect::>()) + ); + let without_c5 = lines(&game, |path| { + path.starts_with(&["e2e4".into(), "c7c5".into()]) + }); + assert_eq!(without_c5.len(), 2); + let node = node_at(&game, &all[1]).unwrap(); + assert_eq!(uci_path(&game, node), all[1]); + assert_eq!(move_text(&game, node).as_deref(), Some("2. Bc4")); + let black = node_at(&game, &all[2][..2]).unwrap(); + assert_eq!(move_text(&game, black).as_deref(), Some("1… c5")); + } + + #[test] + fn dates_read_as_today_tomorrow_days_then_a_date() { + let at = 1_800_000_000; + assert!(when(at + 60, at).contains(':')); + assert_eq!(when(at + 24 * 3600, at), tr("tomorrow")); + assert!(when(at + 3 * 24 * 3600, at).contains('3')); + assert_eq!(when(at + 30 * 24 * 3600, at).len(), 10); + assert!(end_of_today() >= now()); + assert!(end_of_today() - now() < 24 * 3600 + 3600); + } +} diff --git a/apps/desktop/src/opening_lines.rs b/apps/desktop/src/opening_lines.rs new file mode 100644 index 0000000..48f0f58 --- /dev/null +++ b/apps/desktop/src/opening_lines.rs @@ -0,0 +1,566 @@ +//! The «Lines» screen of opening training (spec §6.3): the repertoire's tree, read only, +//! to choose what to train and which branches to leave out. + +use std::collections::BTreeSet; +use std::sync::mpsc; + +use chess_core::shakmaty::Color; +use chess_core::{Game, NodeId}; +use egui::{Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; +use trainer::repertoire::{ + LearningData, LearningItemKey, LearningSide, Library, Repertoire, RepertoireId, StatsScope, + active_learning_memberships, +}; + +use crate::board::BoardState; +use crate::i18n::{tr, trf}; +use crate::opening_layout::{self as layout, GAP, pgn_annotations_at}; +use crate::settings::Settings; + +const SELECTED_H: f32 = 92.0; +const TOOL_H: f32 = 28.0; +const MAIN_W: f32 = 170.0; + +pub enum LinesAction { + Back, + OpenSettings, + /// Train the lines through this move (empty: every line). + Train { + through: Vec, + label: String, + }, + /// Switch a branch off (`true`) or on again, from the move at this path. + SetDisabled { + path: Vec, + disabled: bool, + }, +} + +/// The repertoire's own moves with their paths and which of them are learnt; computed +/// off the frame. +struct Counts { + moves: Vec<(Vec, LearningItemKey)>, + learnt: BTreeSet, +} + +pub struct OpeningLinesUi { + id: RepertoireId, + name: String, + side: LearningSide, + repertoire: Repertoire, + game: Game, + lines: Vec>, + cursor: NodeId, + scroll: bool, + orientation: Color, + board: BoardState, + counts: Option, + counting: Option>>, + error: Option, +} + +impl OpeningLinesUi { + pub fn new( + library: &Library, + learning: &LearningData, + id: RepertoireId, + side: LearningSide, + cursor: Option>, + ) -> Option { + let repertoire = library.repertoire(&id)?.clone(); + let game = repertoire.game(); + let cursor = cursor + .and_then(|path| layout::node_at(&game, &path)) + .unwrap_or(NodeId::ROOT); + let lines = layout::lines(&game, |path| repertoire.is_prefix_disabled(path)); + let mut this = Self { + id, + name: repertoire.name.clone(), + side, + repertoire, + game, + lines, + cursor, + scroll: true, + orientation: layout::orientation(side), + board: BoardState::default(), + counts: None, + counting: None, + error: None, + }; + this.count(library, learning); + Some(this) + } + + pub fn id(&self) -> &RepertoireId { + &self.id + } + + pub fn cursor_path(&self) -> Vec { + layout::uci_path(&self.game, self.cursor) + } + + /// The library changed (a branch switched off or on): recount, keep the move. + pub fn refresh(&mut self, library: &Library, learning: &LearningData) { + if let Some(repertoire) = library.repertoire(&self.id) { + self.repertoire = repertoire.clone(); + self.name = repertoire.name.clone(); + self.lines = layout::lines(&self.game, |path| repertoire.is_prefix_disabled(path)); + } + self.count(library, learning); + } + + fn count(&mut self, library: &Library, learning: &LearningData) { + let library = library.clone(); + let learning = learning.clone(); + let scope = StatsScope::for_repertoire(self.id.clone(), self.side, layout::now()); + let (tx, rx) = mpsc::channel(); + self.counting = Some(rx); + if let Err(error) = crate::platform::spawn("repertoire-lines-count", move || { + let result = active_learning_memberships(&library, &scope) + .map(|memberships| { + let learnt = memberships + .iter() + .filter(|membership| { + learning + .item(&membership.key) + .is_some_and(|item| item.is_learnt()) + }) + .map(|membership| membership.key.clone()) + .collect(); + Counts { + moves: memberships + .into_iter() + .map(|membership| (membership.path, membership.key)) + .collect(), + learnt, + } + }) + .map_err(|error| error.to_string()); + let _ = tx.send(result); + }) { + self.counting = None; + self.error = Some(error.to_string()); + } + } + + fn poll(&mut self) { + let Some(rx) = &self.counting else { + return; + }; + match rx.try_recv() { + Ok(Ok(counts)) => { + self.counts = Some(counts); + self.counting = None; + } + Ok(Err(error)) => { + self.error = Some(error); + self.counting = None; + } + Err(mpsc::TryRecvError::Empty) => {} + Err(mpsc::TryRecvError::Disconnected) => self.counting = None, + } + } + + /// The prefix that switches this path off, if any. + fn disabled_by(&self, path: &[String]) -> Option> { + self.repertoire + .disabled_prefixes + .iter() + .filter(|prefix| path.starts_with(prefix)) + .min_by_key(|prefix| prefix.len()) + .cloned() + } + + fn goto(&mut self, node: NodeId) { + if self.game.node(node).is_some() { + self.cursor = node; + self.scroll = true; + } + } + + fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { + return; + } + let mut command = None; + ui.input_mut(|input| { + for (key, name) in [ + (Key::ArrowLeft, "back"), + (Key::ArrowRight, "forward"), + (Key::ArrowUp, "previous"), + (Key::ArrowDown, "next"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::Enter, "train"), + (Key::Escape, "back_screen"), + ] { + if command.is_none() + && (input.consume_key(Modifiers::NONE, key) + || input.consume_key(Modifiers::SHIFT, key)) + { + command = Some(name); + } + } + if command.is_none() + && input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + { + command = Some("back_screen"); + } + }); + let game = &self.game; + let cursor = self.cursor; + match command { + Some("back") => { + if let Some(parent) = game.parent(cursor) { + self.goto(parent); + } + } + Some("forward") => { + if let Some(next) = game.main_child(cursor) { + self.goto(next); + } + } + Some("previous") => { + if let Some(other) = game.prev_sibling(cursor) { + self.goto(other); + } + } + Some("next") => { + if let Some(other) = game.next_sibling(cursor) { + self.goto(other); + } + } + Some("home") => self.goto(NodeId::ROOT), + Some("end") => { + let end = game.line_end(cursor); + self.goto(end); + } + Some("flip") => self.orientation = self.orientation.other(), + Some("train") => actions.push(self.train_action()), + Some("back_screen") => actions.push(LinesAction::Back), + _ => {} + } + } + + fn train_action(&self) -> LinesAction { + let through = self.cursor_path(); + let label = self.path_label(self.cursor); + LinesAction::Train { through, label } + } + + /// "… 4. Ba4 Nf6": the moves to a node in the notation of the application. + fn path_label(&self, node: NodeId) -> String { + layout::path_text(&self.game, node) + } + + fn below(&self, path: &[String]) -> Option<(usize, usize, usize)> { + let counts = self.counts.as_ref()?; + let lines = self + .lines + .iter() + .filter(|line| line.starts_with(path)) + .count(); + let mine: Vec<_> = counts + .moves + .iter() + .filter(|(move_path, _)| move_path.starts_with(path)) + .collect(); + let learnt = mine + .iter() + .filter(|(_, key)| counts.learnt.contains(key)) + .count(); + Some((lines, mine.len(), learnt)) + } + + fn selected_block(&self, ui: &mut Ui, actions: &mut Vec) { + let path = self.cursor_path(); + let disabled = self.disabled_by(&path); + layout::fixed_block(ui, SELECTED_H, |ui| { + let inner = layout::card_inner(ui, SELECTED_H); + layout::card(ui, false, false).show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.spacing_mut().item_spacing.y = 4.0; + if self.cursor == NodeId::ROOT { + layout::line(ui, RichText::new(tr("Start position")).strong()); + } else { + layout::line_left(ui, &self.path_label(self.cursor), true); + } + if disabled.is_some() { + layout::line( + ui, + RichText::new(tr("Not trained")).color(ui.visuals().warn_fg_color), + ); + } else { + let text = match self.below(&path) { + Some((lines, mine, learnt)) => trf( + "Below: {n} lines · {y} your moves · consolidated {x}", + &[("n", &lines), ("y", &mine), ("x", &learnt)], + ), + None => tr("Counting moves…").to_owned(), + }; + layout::line(ui, RichText::new(text).weak()); + } + ui.horizontal(|ui| { + let label = if self.cursor == NodeId::ROOT { + tr("Review all lines") + } else { + tr("Train this branch") + }; + let width = MAIN_W.min(ui.available_width() / 2.0 - 4.0); + let can_train = disabled.is_none() && !self.lines.is_empty(); + if ui + .add_enabled_ui(can_train, |ui| { + crate::widgets::primary_wide(ui, label, width) + }) + .inner + .on_hover_text("Enter") + .clicked() + { + actions.push(self.train_action()); + } + if self.cursor != NodeId::ROOT { + let (label, action) = match &disabled { + Some(prefix) => ( + tr("Train again"), + LinesAction::SetDisabled { + path: prefix.clone(), + disabled: false, + }, + ), + None => ( + tr("Don't train"), + LinesAction::SetDisabled { + path: path.clone(), + disabled: true, + }, + ), + }; + if ui + .add( + egui::Button::new(label) + .truncate() + .min_size(vec2(width, 30.0)), + ) + .clicked() + { + actions.push(action); + } + } + }); + }); + }); + } + + fn side(&mut self, ui: &mut Ui, actions: &mut Vec) { + let rect = ui.available_rect_before_wrap(); + let footer_h = TOOL_H + 12.0; + let footer = egui::Rect::from_min_max( + egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())), + rect.max, + ); + let body = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); + let mut clicked = None; + ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { + ui.set_clip_rect(body.intersect(ui.clip_rect())); + ui.spacing_mut().item_spacing.y = GAP; + ui.add_space(4.0); + let opening = layout::opening_text(&self.game, self.cursor); + layout::fixed_block(ui, 20.0, |ui| { + layout::line(ui, RichText::new(opening).weak()); + }); + let tree = (ui.available_height() - SELECTED_H - GAP).max(0.0); + let scroll = std::mem::take(&mut self.scroll); + let game = &self.game; + let cursor = self.cursor; + let response = layout::fixed_block(ui, tree, |ui| { + egui::ScrollArea::vertical() + .id_salt("opening_lines_tree") + .auto_shrink([false, false]) + .show(ui, |ui| { + crate::notation::Notation { + game, + cursor, + scroll_to_cursor: scroll, + marks: None, + preview: None, + translations: None, + editor: None, + read_only: true, + dim_until: None, + mistakes: None, + shapes: None, + } + .show(ui) + }) + .inner + }); + clicked = response.clicked; + if let Some(error) = &self.error { + ui.colored_label(ui.visuals().warn_fg_color, error); + } + self.selected_block(ui, actions); + }); + if let Some(node) = clicked { + self.cursor = node; + } + ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { + ui.separator(); + ui.horizontal(|ui| { + let icon = |s: &str| { + egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H)) + }; + let game = &self.game; + let mut target = None; + if ui.add(icon("â�®")).clicked() { + target = Some(NodeId::ROOT); + } + if ui.add(icon("â—€")).clicked() { + target = game.parent(self.cursor); + } + if ui.add(icon("â–¶")).clicked() { + target = game.main_child(self.cursor); + } + if ui.add(icon("â�­")).clicked() { + target = Some(game.line_end(self.cursor)); + } + ui.separator(); + if ui + .add(icon("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.orientation = self.orientation.other(); + } + if let Some(target) = target { + self.goto(target); + } + }); + }); + } + + pub fn show(&mut self, ui: &mut Ui, settings: &Settings) -> Vec { + self.poll(); + if self.counting.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(50)); + } + let mut actions = Vec::new(); + self.keyboard(ui, &mut actions); + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + tr("⬅ Repertoires") + }; + let subtitle = trf( + "Lines · {n} lines · {y} your moves", + &[ + ("n", &self.lines.len()), + ( + "y", + &self + .counts + .as_ref() + .map_or_else(|| "…".to_owned(), |counts| counts.moves.len().to_string()), + ), + ], + ); + let name = self.name.clone(); + let mut header = (false, false); + layout::screen( + ui, + self, + |_, ui| header = crate::widgets::section_header_sub(ui, back, &name, &subtitle), + |this, ui| this.side(ui, &mut actions), + |this, ui| { + let position = layout::position_of(&this.game, this.cursor); + let marks = pgn_annotations_at(&this.game, this.cursor); + let last = layout::last_move(&this.game, this.cursor); + layout::still_board( + ui, + &mut this.board, + settings, + &position, + this.orientation, + last, + &marks, + ); + }, + ); + if header.0 { + actions.push(LinesAction::Back); + } + if header.1 { + actions.push(LinesAction::OpenSettings); + } + actions + } + + #[cfg_attr(not(test), allow(dead_code))] + pub fn debug_select(&mut self, path: &[String]) { + if let Some(node) = layout::node_at(&self.game, path) { + self.goto(node); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines_ui(pgn: &str) -> (Library, OpeningLinesUi) { + let mut library = Library::default(); + let id = library + .create("Lines", &chess_core::parse_str(pgn).game) + .unwrap(); + let mut ui = OpeningLinesUi::new( + &library, + &LearningData::default(), + id, + LearningSide::White, + None, + ) + .unwrap(); + let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5); + while ui.counting.is_some() && web_time::Instant::now() < deadline { + ui.poll(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + (library, ui) + } + + #[test] + fn counts_below_a_move_and_branches_switched_off() { + let (mut library, mut ui) = lines_ui("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *"); + assert_eq!(ui.below(&[]), Some((3, 4, 0))); + let c5 = ["e2e4".to_owned(), "c7c5".to_owned()]; + assert_eq!(ui.below(&c5), Some((1, 1, 0))); + ui.debug_select(&c5); + assert_eq!(ui.cursor_path(), c5); + assert_eq!(ui.path_label(ui.cursor), "1. e4 c5"); + assert!(matches!( + ui.train_action(), + LinesAction::Train { through, .. } if through == c5 + )); + let id = ui.id().clone(); + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&c5, true) + .unwrap(); + ui.refresh(&library, &LearningData::default()); + let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5); + while ui.counting.is_some() && web_time::Instant::now() < deadline { + ui.poll(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(ui.lines.len(), 2); + assert_eq!( + ui.disabled_by(&[c5[0].clone(), c5[1].clone(), "g1f3".into()]), + Some(c5.to_vec()) + ); + assert_eq!(ui.below(&[]), Some((2, 3, 0))); + } +} diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs new file mode 100644 index 0000000..f75ea2b --- /dev/null +++ b/apps/desktop/src/opening_session.rs @@ -0,0 +1,2519 @@ +//! The «Session» screen of opening training (docs/design/opening-trainer-v2-spec.md §4–6): +//! the program plays the line up to the next question, shows a new move before asking +//! it, takes the answer on the board and records it in the background. + +use std::{ + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, + sync::{ + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::Duration, +}; + +use chess_core::shakmaty::{CastlingMode, Chess, Color, Move, Square, fen::Fen, uci::UciMove}; +use chess_core::{Game, NodeId}; +use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; +use trainer::repertoire::{ + AttemptApplication, LearningContextStep, LearningData, LearningItem, LearningItemKey, + LearningPresentation, LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, + LearningSessionTarget, LearningSide, LearningStore, Library, PersistedSessionAttempt, + RepertoireId, SrsSettings, StatsScope, TrainingAttempt, TrainingEventType, + active_learning_keys, aggregate_scope, fen4, +}; +use web_time::{Instant, SystemTime, UNIX_EPOCH}; + +use crate::assets::Sound; +use crate::board::{Arrow, BoardState, BoardView}; +use crate::i18n::{tr, trf}; +use crate::opening_layout::{self as layout, BoardAnnotations, GAP, pgn_annotations_at}; +use crate::settings::Settings; + +const WRONG_SHOWN: Duration = Duration::from_millis(400); +/// How long «Correct» and «Got it» stay after the move's animation. +const FEEDBACK: Duration = Duration::from_millis(600); +const DEFAULT_ANIMATION: Duration = Duration::from_millis(250); +/// Mistakes listed under «Moves to remember». +const REMEMBER_ROWS: usize = 8; +const CARD_H: f32 = 64.0; +/// The words of a branch's path in the header ("4. Ba4 Nf6" is three). +const BRANCH_WORDS: usize = 12; +const LINE_H: f32 = 20.0; +const ROW_H: f32 = 30.0; +const TOOL_H: f32 = 28.0; +const LEFT_W: f32 = 150.0; +const MAIN_W: f32 = 170.0; +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +pub enum SessionAction { + /// Leave the session (to the repertoires, or to the lines it was started from). + Back, + OpenSettings, + Sound(Sound), + /// «10 more new»: the caller prepares the next new moves in the background. + MoreNew, +} + +/// What the session goes through. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SessionKind { + /// What is due today and up to ten new moves. + Daily, + /// Every move of every line, one pass. + ReviewAll, + /// Every move of the lines through `through` (UCI from the start). + Branch { through: Vec, label: String }, +} + +impl SessionKind { + pub fn subtitle(&self, side: LearningSide) -> String { + match self { + Self::Daily => match side { + LearningSide::White => tr("Training · you play White").to_owned(), + LearningSide::Black => tr("Training · you play Black").to_owned(), + }, + Self::ReviewAll => match side { + LearningSide::White => tr("Review all lines · you play White").to_owned(), + LearningSide::Black => tr("Review all lines · you play Black").to_owned(), + }, + Self::Branch { label, .. } => { + // Cut on the left: the last moves name the branch. + let words: Vec<&str> = label.split_whitespace().collect(); + let path = match words.len().checked_sub(BRANCH_WORDS) { + Some(skip) if skip > 0 => format!("… {}", words[skip..].join(" ")), + _ => label.clone(), + }; + trf("Branch: {path}", &[("path", &path)]) + } + } + } +} + +#[derive(Clone)] +struct VisualMove { + #[cfg_attr(not(test), allow(dead_code))] + uci: String, + before: Chess, + after: Chess, + from: Square, + to: Square, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PlayOutcome { + CorrectIndependent, + WrongIndependent, + WrongReplay, + ReplayAfterError, + /// The move after a hint or a revealed alternative. + PreviewedReplay, + /// A new move played after it was shown. + NewPlayed, +} + +#[derive(Clone)] +enum CommitKind { + Context, + ReusedContext, + Play { + visual: Box, + outcome: PlayOutcome, + shown_prefix: ShownPrefix, + }, + /// A hint, or the move revealed after another repertoire move. + Preview, +} + +#[derive(Clone)] +struct ShownPrefix { + repertoire_id: RepertoireId, + path: Vec, +} + +#[derive(Clone)] +struct PendingCommit { + attempts: Vec, + kind: CommitKind, + /// The question the event answers (for the session's result). + target: Option, +} + +enum Playback { + Automatic { + current: Box, + remaining: VecDeque, + started_at: Instant, + duration: Duration, + }, + Wrong { + visual: Box, + until: Instant, + }, + Alternative { + visual: Box, + until: Instant, + }, + Accepted { + started_at: Instant, + duration: Duration, + outcome: PlayOutcome, + }, +} + +/// The numbers of the session's result. +#[derive(Default)] +struct Tally { + first_time: usize, + mistakes: usize, + hints: usize, + new_moves: usize, + missed: Vec, +} + +impl Tally { + fn any(&self) -> bool { + self.first_time + self.mistakes + self.hints + self.new_moves > 0 + } + + fn miss(&mut self, target: Option) { + if let Some(target) = target + && !self.missed.iter().any(|missed| missed.key == target.key) + { + self.missed.push(target); + } + } + + fn missed_key(&self, key: &LearningItemKey) -> bool { + self.missed.iter().any(|missed| &missed.key == key) + } +} + +/// The states of spec §4.2 (S0 is the caller's: before the session exists). +#[derive(Clone, Debug, PartialEq)] +enum State { + Watch, + NextLine, + New, + Yours, + YoursMore(String), + Correct, + Wrong, + Alternative, + GotIt, + Hint, + NewDone, + SaveError(String), + Failed(String), + Summary, +} + +/// Computed once when the result is shown. +struct Summary { + next_review: String, + /// How many more moves are passed (met at least once) and consolidated than when + /// the session began. + passed_gain: usize, + consolidated_gain: usize, + /// Moves never shown yet, all of them (the «more new» button takes up to 10). + unseen: usize, + more_new: usize, +} + +pub struct OpeningSessionUi { + library: Library, + store: LearningStore, + session: LearningSessionSnapshot, + learning: LearningData, + kind: SessionKind, + presentation: Option, + completed_attempt_ids: BTreeSet, + pending_commit: Option, + /// The showing of the new move on the board, recorded together with the move once + /// it is played: a new move left unplayed stays new. + unplayed_preview: Option, + commit_in_flight: Option>>, + #[cfg(test)] + synchronous_commits: bool, + save_error: Option, + error: Option, + board: BoardState, + board_position: Chess, + // Parsed once in the training-start worker, never in a frame or save callback. + annotation_games: BTreeMap, + /// Active answers of this session's scope (a branch: of the branch). + repertoire_answers: BTreeSet, + /// Active answers of the whole repertoire, for the result. + repertoire_keys: BTreeSet, + /// The whole repertoire's scope (a branch session counts the whole repertoire too). + whole_scope: StatsScope, + /// (learned, learning) when the session began: the summary shows what it changed. + start_progress: (usize, usize), + /// The lines of a review, to count «line k of n». + lines: Vec>, + line: usize, + next_line_banner: bool, + // The visible node is independent of the session's already-advanced target. + displayed_node: Option<(RepertoireId, NodeId)>, + board_shown: bool, + pending_automatic: Option>, + shown_prefix: Option, + playback: Option, + needs_prepare: bool, + animation: Duration, + /// How long «Correct» and «Got it» stay after the move ([`FEEDBACK`]). + feedback: Duration, + ready_since: Option, + last_move: Option<(Square, Square)>, + orientation: Color, + /// The next frame puts the board in place without a slide (a skipped context). + jump: bool, + /// The move revealed after another repertoire move was played (S5a). + alternative_revealed: bool, + /// Left before the end: the result says «Session stopped». + stopped: bool, + exit_requested: bool, + /// Leave at the next frame (an exit asked during a save, nothing answered). + leave: bool, + /// Started from the «Lines» screen: going back leads there. + back_to_lines: bool, + current_key: Option, + tally: Tally, + summary: Option, + shown_state: State, + pending_sounds: Vec, + #[cfg(test)] + visual_log: Vec, +} + +impl OpeningSessionUi { + /// A new session (never a resumed one: every answer of an earlier session is already + /// recorded). Runs in a worker: it reads the store and parses the repertoire. + pub fn new( + library: Library, + store: LearningStore, + scope: StatsScope, + kind: SessionKind, + ) -> Result { + let data = store.load().map_err(|error| error.to_string())?; + let id = unique_id("learning-session"); + let srs = SrsSettings::default(); + let mut session = match &kind { + SessionKind::Daily => LearningSessionSnapshot::new_daily( + id, + &library, + &data.learning, + scope, + srs, + layout::NEW_PER_SESSION, + ), + SessionKind::ReviewAll => LearningSessionSnapshot::new_single_pass_review( + id, + &library, + &data.learning, + scope, + srs, + ), + SessionKind::Branch { through, .. } => LearningSessionSnapshot::new_branch_review( + id, + &library, + &data.learning, + scope, + srs, + through, + ), + } + .map_err(|error| error.to_string())?; + store + .save_session(&mut session) + .map_err(|error| error.to_string())?; + Self::from_session(library, store, data.learning, session, kind) + } + + /// «10 more new» after a finished daily session. Runs in a worker. + pub fn more_new( + library: Library, + store: LearningStore, + mut session: LearningSessionSnapshot, + orientation: Color, + ) -> Result { + let data = store.load().map_err(|error| error.to_string())?; + session + .introduce_more(&library, &data.learning, layout::NEW_PER_SESSION) + .map_err(|error| error.to_string())?; + store + .save_session(&mut session) + .map_err(|error| error.to_string())?; + let mut this = + Self::from_session(library, store, data.learning, session, SessionKind::Daily)?; + this.orientation = orientation; + Ok(this) + } + + fn from_session( + library: Library, + store: LearningStore, + learning: LearningData, + session: LearningSessionSnapshot, + kind: SessionKind, + ) -> Result { + let completed_attempt_ids = learning + .attempts + .iter() + .filter(|attempt| attempt.session_id == session.id()) + .map(|attempt| attempt.client_attempt_id.clone()) + .collect(); + let repertoire_answers = active_learning_keys(&library, &session.stats_scope) + .map_err(|error| error.to_string())?; + let mut whole = session.stats_scope.clone(); + whole.branch_root = None; + let repertoire_keys = if whole == session.stats_scope { + repertoire_answers.clone() + } else { + active_learning_keys(&library, &whole).map_err(|error| error.to_string())? + }; + let start_progress = progress_counts(&library, &learning, &whole); + let annotation_games: BTreeMap<_, _> = session + .stats_scope + .repertoire_ids + .iter() + .filter_map(|id| { + library + .repertoire(id) + .map(|repertoire| (id.clone(), repertoire.game())) + }) + .collect(); + let lines = session + .stats_scope + .repertoire_ids + .iter() + .filter_map(|id| Some((library.repertoire(id)?, annotation_games.get(id)?))) + .flat_map(|(repertoire, game)| { + layout::lines(game, |path| repertoire.is_prefix_disabled(path)) + }) + .filter(|line| match &kind { + SessionKind::Branch { through, .. } => line.starts_with(through), + SessionKind::Daily | SessionKind::ReviewAll => true, + }) + .collect(); + let orientation = layout::orientation(session.stats_scope.side); + Ok(Self { + library, + store, + session, + learning, + kind, + presentation: None, + completed_attempt_ids, + pending_commit: None, + unplayed_preview: None, + commit_in_flight: None, + #[cfg(test)] + synchronous_commits: false, + save_error: None, + error: None, + board: BoardState::default(), + board_position: Chess::default(), + annotation_games, + repertoire_answers, + repertoire_keys, + start_progress, + whole_scope: whole, + lines, + line: 0, + next_line_banner: false, + displayed_node: None, + board_shown: false, + pending_automatic: None, + shown_prefix: None, + playback: None, + needs_prepare: true, + animation: DEFAULT_ANIMATION, + feedback: FEEDBACK, + ready_since: None, + last_move: None, + orientation, + jump: false, + alternative_revealed: false, + stopped: false, + exit_requested: false, + leave: false, + back_to_lines: false, + current_key: None, + tally: Tally::default(), + summary: None, + shown_state: State::Watch, + pending_sounds: Vec::new(), + #[cfg(test)] + visual_log: Vec::new(), + }) + } + + pub fn has_unsaved(&self) -> bool { + self.pending_commit.is_some() || self.save_error.is_some() + } + + pub fn target_available(&self) -> bool { + self.session.current_target().is_some() + } + + pub fn set_back_to_lines(&mut self, back_to_lines: bool) { + self.back_to_lines = back_to_lines; + } + + pub fn orientation(&self) -> Color { + self.orientation + } + + /// The finished session, for «10 more new». + pub fn snapshot(&self) -> &LearningSessionSnapshot { + &self.session + } + + #[cfg_attr(not(test), allow(dead_code))] + pub fn session_id(&self) -> &str { + self.session.id() + } + + fn is_finished(&self) -> bool { + self.session.phase == LearningSessionPhase::Finished + && self.playback.is_none() + && !self.has_unsaved() + } + + fn summary_visible(&self) -> bool { + (self.stopped || self.is_finished()) && !self.has_unsaved() + } + + fn can_input(&self) -> bool { + !self.has_unsaved() + && !self.stopped + && self.error.is_none() + && !self.needs_prepare + && self.playback.is_none() + && self.pending_automatic.is_none() + && self.session.current_target().is_some() + && matches!( + self.session.phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + | LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay + ) + } + + fn can_hint(&self) -> bool { + self.can_input() + && self.session.phase == LearningSessionPhase::AwaitingIndependent + && !self.session.current_is_new(&self.learning) + } + + fn tick_at(&mut self, now: Instant, animation: Duration, happened_at: i64) { + self.animation = animation; + self.poll_commit(now); + if self.stopped || self.has_unsaved() { + return; + } + if self.board_shown + && let Some(steps) = self.pending_automatic.take() + { + self.start_next_automatic(steps, now); + } + if self.needs_prepare { + self.prepare_presentation(now); + } + loop { + if self.stopped || self.has_unsaved() || self.error.is_some() { + return; + } + if self.needs_prepare { + self.prepare_presentation(now); + continue; + } + let Some(deadline) = self.playback_deadline() else { + return; + }; + if now < deadline { + return; + } + match self.playback { + Some(Playback::Wrong { .. } | Playback::Alternative { .. }) => { + self.finish_temporary_move(now, happened_at); + } + Some(Playback::Accepted { .. }) => self.finish_accepted(now), + Some(Playback::Automatic { .. }) => { + let id = unique_id(self.session.id()); + self.advance_context_with_id_at(id, now, happened_at); + } + None => return, + } + if !animation.is_zero() { + return; + } + } + } + + fn playback_deadline(&self) -> Option { + match &self.playback { + Some(Playback::Automatic { + started_at, + duration, + .. + }) + | Some(Playback::Accepted { + started_at, + duration, + .. + }) => Some(*started_at + *duration), + Some(Playback::Wrong { until, .. } | Playback::Alternative { until, .. }) => { + Some(*until) + } + None => None, + } + } + + fn prepare_presentation(&mut self, now: Instant) { + let presentation = match self + .session + .presentation_with_learning(&self.library, &self.learning) + { + Ok(presentation) => presentation, + Err(error) => { + self.error = Some(error.to_string()); + self.needs_prepare = false; + self.ready_since = None; + return; + } + }; + self.error = None; + self.needs_prepare = false; + self.presentation = Some(presentation.clone()); + let Some(ref current) = presentation.current_position else { + self.ready_since = None; + self.pending_automatic = None; + return; + }; + let key = self + .session + .current_target() + .map(|target| target.key.clone()); + if key != self.current_key { + self.current_key = key; + self.alternative_revealed = false; + self.track_line(); + } + // A following task may extend the line that is already on the board. Keep + // its context journal, but do not rewind and animate those same moves again. + // The complete path and repertoire must match; a transposed FEN is not enough. + if self.reuse_shown_context(&presentation, now) { + return; + } + self.shown_prefix = None; + if !presentation.automatic_context.is_empty() { + let mut steps = VecDeque::new(); + for step in presentation.automatic_context { + match VisualMove::from_context(&step) { + Ok(_) => steps.push_back(step), + Err(error) => { + self.error = Some(error); + self.ready_since = None; + return; + } + } + } + self.ready_since = None; + let Some(first) = steps.front() else { + self.error = Some("automatic context has no visual step".to_owned()); + return; + }; + self.board_position = match parse_position(&first.from) { + Ok(position) => position, + Err(error) => { + self.error = Some(error); + return; + } + }; + self.set_displayed_context(self.session.context_index); + self.board_shown = false; + self.pending_automatic = Some(steps); + self.playback = None; + self.last_move = None; + return; + } + self.pending_automatic = None; + let position = match parse_position(current) { + Ok(position) => position, + Err(error) => { + self.error = Some(error); + self.ready_since = None; + return; + } + }; + if fen4(&self.board_position) != current.fen4 { + self.last_move = None; + } + self.board_position = position; + self.set_displayed_context(self.session.context_index); + self.playback = None; + self.next_line_banner = false; + match self.session.phase { + LearningSessionPhase::AwaitingIndependent + if self.session.current_is_new(&self.learning) => + { + // A new move is shown before it is asked; the showing is recorded + // only with the played move. + self.ready_since = None; + let id = unique_id(self.session.id()); + self.show_new_with_id_at(id, layout::now()); + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => { + self.ready_since = Some(now); + } + LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay => { + self.ready_since = None; + } + phase => { + self.ready_since = None; + self.error = Some(format!( + "learning session has no playable position in {phase:?}" + )); + } + } + } + + /// The line of the current question (1-based), for a review. + fn track_line(&mut self) { + if self.kind == SessionKind::Daily { + return; + } + let Some(target) = self.session.current_target() else { + return; + }; + let Some(index) = self + .lines + .iter() + .position(|line| line.starts_with(&target.path)) + else { + return; + }; + let line = index + 1; + if line > self.line { + self.next_line_banner = self.line > 0; + self.line = line; + } + } + + fn reuse_shown_context(&mut self, presentation: &LearningPresentation, at: Instant) -> bool { + let Some(prefix) = &self.shown_prefix else { + return false; + }; + let Some(target) = self.session.current_target() else { + return false; + }; + let Some(remaining) = prefix.path.len().checked_sub(self.session.context_index) else { + return false; + }; + if remaining == 0 + || target.repertoire_id != prefix.repertoire_id + || !presentation.target_path.starts_with(&prefix.path) + // An independent context question must still be asked. Only reuse a + // prefix that the core explicitly allows to be automatic in full. + || presentation.automatic_context.len() < remaining + || presentation.automatic_context[remaining - 1].to.fen4 != fen4(&self.board_position) + { + return false; + } + // These moves are already visible. Preserve each AUTO_CONTEXT event, + // but commit the whole prefix once instead of rereading/writing all + // history and rebuilding the presentation once per old move. + self.commit_context_batch(remaining, at) + } + + /// Records `count` automatic moves of the current line at once (moves already on the + /// board, or skipped by the user). + fn commit_context_batch(&mut self, count: usize, at: Instant) -> bool { + let mut next_session = self.session.clone(); + let mut attempts = Vec::with_capacity(count); + let happened_at = layout::now(); + for _ in 0..count { + let id = unique_id(next_session.id()); + match next_session.advance_context_with_learning( + &self.library, + &self.learning, + id, + happened_at, + ) { + Ok(attempt) => attempts.push(attempt), + Err(error) => { + self.error = Some(error.to_string()); + return true; + } + } + } + if attempts.is_empty() { + return false; + } + self.session = next_session; + self.ready_since = None; + self.pending_commit = Some(PendingCommit { + attempts, + kind: CommitKind::ReusedContext, + target: None, + }); + self.persist_pending(at); + true + } + + /// «Skip»: the position of the question at once, the skipped moves recorded as + /// shown. + fn skip_context(&mut self, now: Instant) -> bool { + if self.has_unsaved() || self.stopped { + return false; + } + let (count, last) = match (&self.playback, &self.pending_automatic) { + ( + Some(Playback::Automatic { + current, remaining, .. + }), + _, + ) => ( + remaining.len() + 1, + remaining + .back() + .map(VisualMove::from_context) + .unwrap_or_else(|| Ok((**current).clone())), + ), + (None, Some(steps)) => match steps.back() { + Some(step) => (steps.len(), VisualMove::from_context(step)), + None => return false, + }, + _ => return false, + }; + let last = match last { + Ok(last) => last, + Err(error) => { + self.error = Some(error); + return false; + } + }; + self.playback = None; + self.pending_automatic = None; + if !self.commit_context_batch(count, now) { + return false; + } + self.board_position = last.after.clone(); + self.set_displayed_context(self.session.context_index); + self.last_move = Some((last.from, last.to)); + self.jump = true; + true + } + + fn start_next_automatic(&mut self, mut remaining: VecDeque, now: Instant) { + let Some(step) = remaining.pop_front() else { + self.needs_prepare = true; + self.prepare_presentation(now); + return; + }; + let current = match VisualMove::from_context(&step) { + Ok(current) => current, + Err(error) => { + self.error = Some(error); + return; + } + }; + self.board_position = current.after.clone(); + self.set_displayed_context(self.session.context_index + 1); + self.last_move = Some((current.from, current.to)); + self.playback = Some(Playback::Automatic { + current: Box::new(current.clone()), + remaining, + started_at: now, + duration: self.animation.div_f32(step.speed_factor.max(0.01) as f32), + }); + #[cfg(test)] + self.visual_log.push(current.uci.clone()); + self.queue_sound(Sound::Move); + } + + fn advance_context_with_id_at( + &mut self, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if self.has_unsaved() + || !matches!(self.playback, Some(Playback::Automatic { .. })) + || self.completed_attempt_ids.contains(&client_attempt_id) + { + return false; + } + let attempt = match self.session.advance_context_with_learning( + &self.library, + &self.learning, + client_attempt_id, + happened_at, + ) { + Ok(attempt) => attempt, + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + self.begin_commit(attempt, CommitKind::Context, now); + true + } + + fn finish_context(&mut self, now: Instant) { + let Some(Playback::Automatic { remaining, .. }) = self.playback.take() else { + self.error = Some("automatic context is missing its visual step".to_owned()); + return; + }; + self.start_next_automatic(remaining, now); + } + + fn play_move_at(&mut self, mv: Move, now: Instant, happened_at: i64) -> bool { + let id = unique_id(self.session.id()); + self.play_move_with_id_at(mv, id, now, happened_at) + } + + fn play_move_with_id_at( + &mut self, + mv: Move, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let Some(expected_uci) = self.session.current_expected_uci().map(str::to_owned) else { + return false; + }; + let before = self.board_position.clone(); + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + let visual = VisualMove::new(uci.clone(), before, mv); + let phase = self.session.phase; + let independent = matches!( + phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + ); + let showing_new = self.session.showing_new; + let Some(target) = self.session.current_target().cloned() else { + return false; + }; + let Some(prefix) = target.path.get(..self.session.context_index) else { + return false; + }; + let mut path = prefix.to_vec(); + path.push(uci.clone()); + let shown_prefix = ShownPrefix { + repertoire_id: target.repertoire_id.clone(), + path, + }; + if !independent && uci != expected_uci { + let key = LearningItemKey::new(target.key.user_id.clone(), fen4(&visual.before), &uci); + if self.repertoire_answers.contains(&key) { + self.show_repertoire_alternative(visual, &shown_prefix, now); + return true; + } + self.set_displayed_path(Some(&shown_prefix)); + self.start_playback(visual, PlayOutcome::WrongReplay, now); + return true; + } + let response_time_ms = independent.then(|| { + self.ready_since.map_or(0, |ready| { + u64::try_from(now.saturating_duration_since(ready).as_millis()).unwrap_or(u64::MAX) + }) + }); + let attempt = match self.session.play_uci_with_learning_answers( + &self.library, + &self.learning, + &self.repertoire_answers, + &uci, + client_attempt_id, + happened_at, + response_time_ms, + ) { + Ok(attempt) => attempt, + Err(LearningSessionError::RepertoireAlternative { .. }) => { + self.show_repertoire_alternative(visual, &shown_prefix, now); + return true; + } + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + let outcome = match attempt.event_type { + TrainingEventType::CorrectIndependent => PlayOutcome::CorrectIndependent, + TrainingEventType::IncorrectIndependent => PlayOutcome::WrongIndependent, + TrainingEventType::ReplayAfterError => PlayOutcome::ReplayAfterError, + TrainingEventType::AutoContext if showing_new => PlayOutcome::NewPlayed, + TrainingEventType::AutoContext => PlayOutcome::PreviewedReplay, + TrainingEventType::Previewed | TrainingEventType::IllegalMove => { + self.error = Some("legal board input produced a non-play event".to_owned()); + return false; + } + }; + // The credited question: the played answer itself when it was another + // pending answer of this position. + let credited = if attempt.item_key() == target.key { + Some(target) + } else { + self.session + .queue + .iter() + .find(|candidate| candidate.key == attempt.item_key()) + .cloned() + }; + // The legal move is visible immediately, including while its event is + // being saved. Input stays blocked until persistence acknowledges it. + // In particular a dropped piece must not jump back to its source square. + self.board_position = visual.after.clone(); + self.set_displayed_path(Some(&shown_prefix)); + self.last_move = Some((visual.from, visual.to)); + self.begin_commit_for( + attempt, + CommitKind::Play { + visual: Box::new(visual), + outcome, + shown_prefix, + }, + credited, + now, + ); + true + } + + fn play_uci_with_id_at( + &mut self, + uci: &str, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let mv = uci + .parse::() + .ok() + .and_then(|uci| uci.to_move(&self.board_position).ok()); + let Some(mv) = mv else { + return false; + }; + self.play_move_with_id_at(mv, client_attempt_id, now, happened_at) + } + + fn start_playback(&mut self, visual: VisualMove, outcome: PlayOutcome, now: Instant) { + self.ready_since = None; + self.board_position = visual.after.clone(); + self.last_move = Some((visual.from, visual.to)); + match outcome { + PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay => { + self.playback = Some(Playback::Wrong { + visual: Box::new(visual), + until: now + WRONG_SHOWN, + }); + self.queue_sound(Sound::Wrong); + } + PlayOutcome::CorrectIndependent + | PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay + | PlayOutcome::NewPlayed => { + self.playback = Some(Playback::Accepted { + started_at: now, + duration: self.animation + self.feedback, + outcome, + }); + self.queue_sound(Sound::Move); + } + } + } + + fn show_repertoire_alternative( + &mut self, + visual: VisualMove, + shown_prefix: &ShownPrefix, + now: Instant, + ) { + self.ready_since = None; + self.board_position = visual.after.clone(); + self.set_displayed_path(Some(shown_prefix)); + self.last_move = Some((visual.from, visual.to)); + self.playback = Some(Playback::Alternative { + visual: Box::new(visual), + until: now + WRONG_SHOWN.max(self.animation), + }); + } + + fn finish_temporary_move(&mut self, now: Instant, happened_at: i64) { + let (visual, alternative) = match self.playback.take() { + Some(Playback::Wrong { visual, .. }) => (visual, false), + Some(Playback::Alternative { visual, .. }) => (visual, true), + _ => return, + }; + self.board_position = visual.before; + self.last_move = None; + self.needs_prepare = true; + self.prepare_presentation(now); + // Another move of the repertoire is no mistake, but «now play {san}» shows the + // answer: it is recorded as shown, not as known. + if alternative && self.session.phase == LearningSessionPhase::AwaitingIndependent { + self.alternative_revealed = true; + let id = unique_id(self.session.id()); + self.preview_with_id_at(id, now, happened_at); + } else if alternative { + self.alternative_revealed = true; + } + } + + fn finish_accepted(&mut self, now: Instant) { + let Some(Playback::Accepted { outcome, .. }) = self.playback.take() else { + return; + }; + if outcome == PlayOutcome::CorrectIndependent + && self.session.phase == LearningSessionPhase::Finished + { + self.queue_sound(Sound::Success); + } + self.alternative_revealed = false; + self.needs_prepare = true; + self.prepare_presentation(now); + } + + fn request_hint_with_id_at( + &mut self, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_hint() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + self.preview_with_id_at(client_attempt_id, now, happened_at) + } + + /// S2: the new move goes on the board with its arrow. Nothing is written yet. + fn show_new_with_id_at(&mut self, client_attempt_id: String, happened_at: i64) { + if self.has_unsaved() || self.completed_attempt_ids.contains(&client_attempt_id) { + return; + } + match self.session.preview_new(client_attempt_id, happened_at) { + Ok(attempt) => { + self.unplayed_preview = attempt; + self.board.clear(); + } + Err(error) => { + self.error = Some(error.to_string()); + return; + } + } + // The arrow comes from the presentation of the shown move. + match self + .session + .presentation_with_learning(&self.library, &self.learning) + { + Ok(presentation) => self.presentation = Some(presentation), + Err(error) => self.error = Some(error.to_string()), + } + } + + fn preview_with_id_at( + &mut self, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if self.has_unsaved() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let target = self.session.current_target().cloned(); + let attempt = match self.session.preview(client_attempt_id, happened_at) { + Ok(Some(attempt)) => attempt, + Ok(None) => return false, + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + self.board.clear(); + self.begin_commit_for(attempt, CommitKind::Preview, target, now); + true + } + + fn begin_commit(&mut self, attempt: TrainingAttempt, kind: CommitKind, now: Instant) { + self.begin_commit_for(attempt, kind, None, now); + } + + fn begin_commit_for( + &mut self, + attempt: TrainingAttempt, + kind: CommitKind, + target: Option, + now: Instant, + ) { + if self.pending_commit.is_some() { + self.save_error = + Some("another learning event is still waiting to be saved".to_owned()); + return; + } + let mut attempts: Vec<_> = self.unplayed_preview.take().into_iter().collect(); + attempts.push(attempt); + self.pending_commit = Some(PendingCommit { + attempts, + kind, + target, + }); + self.persist_pending(now); + } + + fn persist_pending(&mut self, _now: Instant) { + let Some(pending) = self.pending_commit.clone() else { + return; + }; + if self.commit_in_flight.is_some() { + return; + } + #[cfg(test)] + if self.synchronous_commits { + let result = self + .store + .apply_attempts_and_session(pending.attempts.clone(), &mut self.session) + .map_err(|error| error.to_string()); + self.finish_commit(result, _now); + return; + } + let store = self.store.clone(); + let mut session = self.session.clone(); + let (tx, rx) = mpsc::channel(); + self.commit_in_flight = Some(rx); + self.save_error = None; + if let Err(error) = crate::platform::spawn("learning-save-attempt", move || { + let result = store + .apply_attempts_and_session(pending.attempts, &mut session) + .map_err(|error| error.to_string()); + let _ = tx.send(result); + }) { + self.commit_in_flight = None; + self.save_error = Some(error.to_string()); + self.ready_since = None; + } + } + + fn poll_commit(&mut self, now: Instant) { + let Some(receiver) = &self.commit_in_flight else { + return; + }; + let result = match receiver.try_recv() { + Ok(result) => result, + Err(mpsc::TryRecvError::Empty) => return, + Err(mpsc::TryRecvError::Disconnected) => { + Err("learning save worker disconnected".to_owned()) + } + }; + self.commit_in_flight = None; + self.finish_commit(result, now); + } + + fn finish_commit(&mut self, result: Result, now: Instant) { + let Some(pending) = self.pending_commit.clone() else { + return; + }; + match result { + Ok(persisted) => { + let duplicate = persisted.application == AttemptApplication::Duplicate; + self.learning = persisted.learning; + self.session = persisted.session; + self.completed_attempt_ids.extend( + pending + .attempts + .iter() + .map(|attempt| attempt.client_attempt_id.clone()), + ); + self.pending_commit = None; + self.save_error = None; + if duplicate { + self.playback = None; + self.shown_prefix = None; + self.ready_since = None; + self.needs_prepare = true; + self.prepare_presentation(now); + self.finish_exit(); + return; + } + self.count(&pending); + match pending.kind { + CommitKind::Context => self.finish_context(now), + CommitKind::ReusedContext => self.needs_prepare = true, + CommitKind::Play { + visual, + outcome, + shown_prefix, + } => { + self.shown_prefix = (!matches!( + outcome, + PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay + )) + .then_some(shown_prefix); + self.start_playback(*visual, outcome, now); + } + CommitKind::Preview => { + self.needs_prepare = true; + self.prepare_presentation(now); + } + } + self.finish_exit(); + } + Err(error) => { + self.save_error = Some(error.to_string()); + self.ready_since = None; + } + } + } + + /// The session's result counts recorded events only. + fn count(&mut self, pending: &PendingCommit) { + let target = pending.target.clone(); + match &pending.kind { + CommitKind::Play { outcome, .. } => match outcome { + PlayOutcome::CorrectIndependent => { + if target + .as_ref() + .is_none_or(|target| !self.tally.missed_key(&target.key)) + { + self.tally.first_time += 1; + } + } + PlayOutcome::WrongIndependent => { + self.tally.mistakes += 1; + self.tally.miss(target); + } + PlayOutcome::NewPlayed => self.tally.new_moves += 1, + PlayOutcome::WrongReplay + | PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay => {} + }, + CommitKind::Preview => { + self.tally.hints += 1; + self.tally.miss(target); + } + CommitKind::Context | CommitKind::ReusedContext => {} + } + } + + fn retry_pending(&mut self, now: Instant) { + if self.pending_commit.is_some() { + self.persist_pending(now); + } + } + + fn queue_sound(&mut self, sound: Sound) { + if sound == Sound::Move && self.pending_sounds.last() == Some(&Sound::Move) { + return; + } + self.pending_sounds.push(sound); + } + + /// Esc, «⬅», «× Finish»: every answer is already recorded, so no question; after + /// an answer the result shows what was done. + fn request_exit(&mut self, actions: &mut Vec) { + if self.summary_visible() { + actions.push(SessionAction::Back); + return; + } + if self.save_error.is_some() { + // «Finish» in S9 gives up the one answer that could not be saved. + self.pending_commit = None; + self.save_error = None; + self.commit_in_flight = None; + } + if self.has_unsaved() { + self.exit_requested = true; + return; + } + if self.tally.any() { + self.stop(); + } else { + actions.push(SessionAction::Back); + } + } + + fn stop(&mut self) { + self.stopped = true; + self.unplayed_preview = None; + self.pending_automatic = None; + if let Some(Playback::Automatic { .. }) = self.playback { + self.playback = None; + } + self.ready_since = None; + } + + /// An exit asked while an answer was being saved. + fn finish_exit(&mut self) { + if std::mem::take(&mut self.exit_requested) { + if self.tally.any() { + self.stop(); + } else { + self.leave = true; + } + } + } + + fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { + return; + } + let state = self.shown_state.clone(); + let more = self.more_new_count() > 0; + let busy = self.board.is_busy(); + let mut command = None; + ui.input_mut(|input| { + if input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + || (!busy && input.consume_key(Modifiers::NONE, Key::Escape)) + { + command = Some("exit"); + } else if input.consume_key(Modifiers::NONE, Key::F) { + command = Some("flip"); + } else if input.consume_key(Modifiers::NONE, Key::H) { + command = Some("hint"); + } else if state == State::Summary && more && input.consume_key(Modifiers::NONE, Key::N) + { + command = Some("more"); + } else if matches!( + state, + State::Watch | State::NextLine | State::Summary | State::SaveError(_) + ) && (input.consume_key(Modifiers::NONE, Key::Enter) + || input.consume_key(Modifiers::NONE, Key::Space)) + { + command = Some("main"); + } + }); + match command { + Some("exit") => self.request_exit(actions), + Some("flip") => self.orientation = self.orientation.other(), + Some("hint") => { + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + Some("more") => actions.push(SessionAction::MoreNew), + Some("main") => self.main_action(&state, actions), + _ => {} + } + } + + fn main_action(&mut self, state: &State, actions: &mut Vec) { + match state { + State::Watch | State::NextLine => { + self.skip_context(Instant::now()); + } + State::Summary => actions.push(SessionAction::Back), + State::SaveError(_) => self.retry_pending(Instant::now()), + _ => {} + } + } + + fn board_animation_seconds(&mut self, settings: &Settings) -> f32 { + if self.pending_automatic.is_some() || std::mem::take(&mut self.jump) { + return 0.0; + } + match &self.playback { + Some(Playback::Automatic { duration, .. }) => duration.as_secs_f32(), + _ => settings.animation.seconds(), + } + } + + fn set_displayed_context(&mut self, played: usize) { + let prefix = self.session.current_target().and_then(|target| { + Some(ShownPrefix { + repertoire_id: target.repertoire_id.clone(), + path: target.path.get(..played)?.to_vec(), + }) + }); + self.set_displayed_path(prefix.as_ref()); + } + + fn set_displayed_path(&mut self, prefix: Option<&ShownPrefix>) { + self.displayed_node = prefix.and_then(|prefix| { + let game = self.annotation_games.get(&prefix.repertoire_id)?; + let at = layout::node_at(game, &prefix.path)?; + Some((prefix.repertoire_id.clone(), at)) + }); + } + + /// The node on the board, when the board really shows it. + fn shown_node(&self) -> Option<(&Game, NodeId)> { + let (id, at) = self.displayed_node.as_ref()?; + let game = self.annotation_games.get(id)?; + // A visual wrong move outside the source tree must never inherit the + // expected move's badge or arrows merely because the task advanced. + (game.position(*at)? == &self.board_position).then_some((game, *at)) + } + + fn displayed_annotations(&self) -> BoardAnnotations { + match self.shown_node() { + Some((game, at)) => pgn_annotations_at(game, at), + None => BoardAnnotations::default(), + } + } + + /// «1. e4 e5 2. Nf3» up to the position on the board; the asked move is not in it. + /// A wrong move on the board is not either: the line stays at the asked position. + fn path_text(&self) -> String { + let node = self.shown_node().or_else(|| { + let (game, asked) = self.expected_node()?; + Some((game, game.parent(asked)?)) + }); + node.map(|(game, node)| layout::path_text(game, node)) + .unwrap_or_default() + } + + /// The asked move's node in the PGN. + fn expected_node(&self) -> Option<(&Game, NodeId)> { + let target = self.session.current_target()?; + let game = self.annotation_games.get(&target.repertoire_id)?; + let path = target.path.get(..=self.session.context_index)?; + Some((game, layout::node_at(game, path)?)) + } + + fn expected_text(&self) -> String { + self.expected_node() + .and_then(|(game, node)| layout::move_text(game, node)) + .unwrap_or_default() + } + + /// «4. Ba4 !» of the move just played. + fn played_text(&self, dark: bool) -> String { + let Some((game, node)) = self.shown_node() else { + return String::new(); + }; + let mut text = layout::move_text(game, node).unwrap_or_default(); + if let Some((symbol, _)) = layout::assessment(game, node, dark) { + text.push_str(symbol); + } + text + } + + /// The move shown by an arrow: revealed by the core, or a new move about to be shown. + fn revealed_uci(&self) -> Option { + if self.playback.is_some() || self.pending_automatic.is_some() || self.stopped { + return None; + } + if let Some(uci) = self + .presentation + .as_ref() + .and_then(|presentation| presentation.revealed_move.clone()) + && self.session.phase != LearningSessionPhase::AwaitingIndependent + { + return Some(uci); + } + matches!(self.shown_state, State::New) + .then(|| self.session.current_expected_uci().map(str::to_owned)) + .flatten() + } + + fn state(&self) -> Option { + if let Some(error) = &self.save_error { + return Some(State::SaveError(error.clone())); + } + if let Some(error) = &self.error { + return Some(State::Failed(error.clone())); + } + if self.summary_visible() { + return Some(State::Summary); + } + match &self.playback { + Some(Playback::Automatic { .. }) => return Some(self.watch()), + Some(Playback::Wrong { .. }) => return Some(State::Wrong), + Some(Playback::Alternative { .. }) => return Some(State::Alternative), + Some(Playback::Accepted { outcome, .. }) => { + return Some(match outcome { + PlayOutcome::CorrectIndependent => State::Correct, + PlayOutcome::NewPlayed => State::NewDone, + PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay + | PlayOutcome::WrongIndependent + | PlayOutcome::WrongReplay => State::GotIt, + }); + } + None => {} + } + if self.pending_automatic.is_some() { + return Some(self.watch()); + } + if self.pending_commit.is_some() { + // Between moves: the card keeps what it said. + return None; + } + if self.needs_prepare { + return None; + } + Some(match self.session.phase { + LearningSessionPhase::AwaitingIndependent + if self.session.current_is_new(&self.learning) => + { + State::New + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => self.yours(), + LearningSessionPhase::AwaitingReplayAfterError => State::Wrong, + LearningSessionPhase::PreviewedReplay if self.session.showing_new => State::New, + LearningSessionPhase::PreviewedReplay if self.alternative_revealed => { + State::Alternative + } + LearningSessionPhase::PreviewedReplay => State::Hint, + LearningSessionPhase::AdvancingContext => self.watch(), + LearningSessionPhase::Finished => State::Summary, + }) + } + + fn watch(&self) -> State { + if self.next_line_banner { + State::NextLine + } else { + State::Watch + } + } + + /// S3, or S3a when another answer of this position was already played. + fn yours(&self) -> State { + let position = fen4(&self.board_position); + let played: Vec = self + .session + .completed_keys + .iter() + .filter(|key| key.position_fen4 == position && self.repertoire_answers.contains(key)) + .filter_map(|key| { + let mv = key + .expected_uci + .parse::() + .ok()? + .to_move(&self.board_position) + .ok()?; + let san = chess_core::shakmaty::san::San::from_move(&self.board_position, mv); + Some(crate::san::show(&san.to_string()).into_owned()) + }) + .collect(); + if played.is_empty() { + State::Yours + } else { + State::YoursMore(played.join(", ")) + } + } + + fn more_new_count(&self) -> usize { + // A stopped session still has questions: the card starts the next one. + if self.kind != SessionKind::Daily || self.stopped { + return 0; + } + self.summary.as_ref().map_or(0, |summary| summary.more_new) + } + + fn compute_summary(&mut self) { + if self.summary.is_some() { + return; + } + let items: HashMap<&LearningItemKey, &LearningItem> = self + .learning + .items + .iter() + .map(|item| (&item.key, item)) + .collect(); + let now = layout::now(); + let mut next: Option = None; + let mut unseen = 0usize; + for key in &self.repertoire_keys { + match items.get(key) { + Some(item) if item.introduced => { + if let Some(at) = item.next_review_at { + next = Some(next.map_or(at, |old| old.min(at))); + } + } + _ => unseen += 1, + } + } + let next_review = match next { + Some(at) => layout::when(at.max(now), now), + None => tr("nothing scheduled").to_owned(), + }; + let (learnt, learning) = progress_counts(&self.library, &self.learning, &self.whole_scope); + self.summary = Some(Summary { + next_review, + passed_gain: (learnt + learning) + .saturating_sub(self.start_progress.0 + self.start_progress.1), + consolidated_gain: learnt.saturating_sub(self.start_progress.0), + unseen, + more_new: unseen.min(layout::NEW_PER_SESSION), + }); + } + + fn board_ui(&mut self, ui: &mut Ui, settings: &Settings) { + let interactive = self.can_input(); + let annotations = self.displayed_annotations(); + let mut arrows = annotations.arrows; + if let Some(mv) = self.revealed_uci().and_then(|uci| { + uci.parse::() + .ok() + .and_then(|uci| uci.to_move(&self.board_position).ok()) + }) { + arrows.push(Arrow { + from: mv.from().unwrap_or_else(|| mv.to()), + to: crate::board::ui_target(&mv), + color: Color32::from_rgba_unmultiplied(21, 120, 27, 190), + weight: 1.0, + }); + } + let alert = match &self.playback { + Some(Playback::Wrong { visual, .. }) => Some((visual.from, visual.to)), + _ => None, + }; + let animation = self.board_animation_seconds(settings); + let played = BoardView { + pos: &self.board_position, + orientation: self.orientation, + last_move: self.last_move, + arrows: &arrows, + circles: &annotations.circles, + badge: annotations.badge, + interactive, + temporary_shapes: true, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation, + premove: None, + auto_queen: false, + alert, + } + .show(ui, &mut self.board); + if let Some(mv) = played { + self.play_move_at(mv, Instant::now(), layout::now()); + } + self.board_shown = true; + } + + /// The card's texts: title, instruction, title colour. + fn card_texts(&self, state: &State, dark: bool) -> (String, String, Option) { + let dash = |s: &str| s.to_owned(); + let review = self.kind != SessionKind::Daily; + match state { + State::Watch => ( + dash(tr("Watch")), + dash(tr("Moves up to your next question")), + None, + ), + State::NextLine => ( + dash(tr("Next line")), + trf("{k} of {n}", &[("k", &self.line), ("n", &self.lines.len())]), + None, + ), + State::New => ( + dash(tr("New move")), + trf( + "Play {san} — it is shown by the arrow", + &[("san", &self.expected_text())], + ), + None, + ), + State::Yours => ( + dash(tr("Your move")), + dash(tr("Play the move from your repertoire")), + None, + ), + State::YoursMore(played) => ( + dash(tr("Your move")), + trf("One more move of yours here, not {san}", &[("san", played)]), + None, + ), + State::Correct => ( + dash(tr("Correct!")), + self.played_text(dark), + crate::notation::assessment_text_color(chess_core::Nag(1), dark), + ), + State::NewDone => (dash(tr("New move")), self.played_text(dark), None), + State::Wrong => ( + dash(tr("Not this move")), + trf("Correct: {san}. Play it", &[("san", &self.expected_text())]), + None, + ), + State::Alternative => ( + dash(tr("This one is in your repertoire too")), + trf( + "Now the other one: play {san}", + &[("san", &self.expected_text())], + ), + None, + ), + State::GotIt => ( + dash(tr("Got it")), + if review { + self.played_text(dark) + } else { + trf( + "{move} will come back in this session", + &[("move", &self.played_text(dark))], + ) + }, + None, + ), + State::Hint => ( + dash(tr("Hint")), + if review { + trf("Play {san}", &[("san", &self.expected_text())]) + } else { + trf( + "Play {san}. It will come back in this session", + &[("san", &self.expected_text())], + ) + }, + None, + ), + State::SaveError(error) => { + (dash(tr("Could not save your answer")), error.clone(), None) + } + State::Failed(error) => ( + dash(tr("Could not continue the session")), + error.clone(), + None, + ), + State::Summary => ( + dash(if self.stopped { + tr("Session stopped") + } else { + tr("Session complete") + }), + dash(tr("Everything is saved")), + None, + ), + } + } + + fn counter(&self, state: &State) -> (String, &'static str) { + match &self.kind { + SessionKind::Daily => { + // A finished session has nothing left: no «0 left» on its summary. + if matches!(state, State::Summary) && !self.stopped { + return (String::new(), ""); + } + (self.session.remaining().to_string(), tr("left")) + } + SessionKind::ReviewAll | SessionKind::Branch { .. } => { + let k = if self.is_finished() { + self.lines.len() + } else { + self.line.max(1).min(self.lines.len()) + }; + (format!("{k}/{}", self.lines.len()), tr("line")) + } + } + } + + fn state_card(&self, ui: &mut Ui, state: &State) { + let dark = ui.visuals().dark_mode; + let (title, instruction, title_color) = self.card_texts(state, dark); + let active = matches!(state, State::New | State::Yours | State::YoursMore(_)); + let alert = matches!(state, State::Wrong | State::SaveError(_) | State::Failed(_)); + let (count, label) = self.counter(state); + show_card( + ui, + &CardView { + title, + instruction, + title_color, + active, + alert, + count, + label, + }, + ); + } + + /// Block D: the comment of the last move on the board (in S2, S5, S7 already of + /// the asked move), or the nearest earlier one of the line. + fn comment(&self, ui: &mut Ui, state: &State) { + let start = if matches!( + state, + State::New | State::Wrong | State::Hint | State::Alternative + ) { + self.expected_node() + } else { + self.shown_node() + }; + let Some((game, start)) = start else { + return; + }; + let dark = ui.visuals().dark_mode; + let mut path = game.path(start); + while let Some(node) = path.pop() { + let Some(data) = game.node(node) else { + continue; + }; + let text = crate::notation::comment_text(data.comments_after()); + if text.trim().is_empty() { + continue; + } + egui::ScrollArea::vertical() + .id_salt("opening_comment") + .auto_shrink([false, false]) + .show(ui, |ui| { + if let Some(label) = layout::move_text(game, node) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + ui.label(RichText::new(label).strong()); + if let Some((symbol, color)) = layout::assessment(game, node, dark) { + ui.label(RichText::new(symbol).strong().color(color)); + } + }); + } + ui.add(egui::Label::new(text).wrap()); + }); + return; + } + } + + fn summary_body(&self, ui: &mut Ui) { + let row = |ui: &mut Ui, label: &str, value: String| { + ui.allocate_ui_with_layout( + vec2(ui.available_width(), 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + let width = (ui.available_width() - 60.0).max(0.0); + ui.allocate_ui_with_layout( + vec2(width, 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| layout::line(ui, label), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + layout::line(ui, RichText::new(value).strong()); + }); + }, + ); + }; + egui::ScrollArea::vertical() + .id_salt("opening_summary") + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + if self.kind != SessionKind::Daily { + let k = if self.stopped { + self.line.saturating_sub(1) + } else { + self.lines.len() + }; + row( + ui, + tr("Lines reviewed"), + trf("{k} of {n}", &[("k", &k), ("n", &self.lines.len())]), + ); + } + row( + ui, + tr("Correct first time"), + self.tally.first_time.to_string(), + ); + row(ui, tr("Mistakes"), self.tally.mistakes.to_string()); + if self.tally.hints > 0 { + row(ui, tr("Hints"), self.tally.hints.to_string()); + } + if self.tally.new_moves > 0 { + row( + ui, + tr("New moves learned"), + self.tally.new_moves.to_string(), + ); + } + ui.add_space(4.0); + ui.separator(); + ui.add_space(4.0); + if let Some(summary) = &self.summary { + // Consolidating takes days: what the session did shows as «passed». + if summary.passed_gain > 0 { + row(ui, tr("Passed"), format!("+{}", summary.passed_gain)); + } + if summary.consolidated_gain > 0 { + row( + ui, + tr("Consolidated"), + format!("+{}", summary.consolidated_gain), + ); + } + if self.kind == SessionKind::Daily && summary.unseen > 0 { + row(ui, tr("New moves left"), summary.unseen.to_string()); + } + row(ui, tr("Next review"), summary.next_review.clone()); + } + if self.tally.missed.is_empty() { + return; + } + ui.add_space(8.0); + ui.label(RichText::new(tr("Moves to remember")).strong()); + ui.add_space(2.0); + for target in self.tally.missed.iter().take(REMEMBER_ROWS) { + let Some(game) = self.annotation_games.get(&target.repertoire_id) else { + continue; + }; + let Some(node) = layout::node_at(game, &target.path) else { + continue; + }; + let after = game + .parent(node) + .and_then(|parent| layout::move_text(game, parent)); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + ui.label( + RichText::new(layout::move_text(game, node).unwrap_or_default()) + .strong(), + ); + if let Some(after) = after { + layout::line( + ui, + RichText::new(trf("after {path}", &[("path", &after)])).weak(), + ); + } + }, + ); + } + if self.tally.missed.len() > REMEMBER_ROWS { + ui.label( + RichText::new(trf( + "and {k} more", + &[("k", &(self.tally.missed.len() - REMEMBER_ROWS))], + )) + .weak(), + ); + } + }); + } + + fn side(&mut self, ui: &mut Ui, state: &State, actions: &mut Vec) { + let opening = self + .shown_node() + .map(|(game, node)| layout::opening_text(game, node)) + .unwrap_or_default(); + let path = self.path_text(); + let (left, right) = match state { + State::Summary => { + let more = self.more_new_count(); + ( + (more > 0).then(|| { + ( + if more == layout::NEW_PER_SESSION { + tr("10 more new (N)").to_owned() + } else { + trf("{n} more new (N)", &[("n", &more)]) + }, + true, + ) + }), + Some(( + if self.back_to_lines { + tr("To lines (Enter)") + } else { + tr("To repertoires (Enter)") + } + .to_owned(), + true, + )), + ) + } + State::SaveError(_) => ( + Some((tr("Finish").to_owned(), true)), + Some((tr("Try again").to_owned(), true)), + ), + State::Watch | State::NextLine => ( + Some((tr("Hint (H)").to_owned(), false)), + Some((tr("Skip (Enter)").to_owned(), false)), + ), + _ => (Some((tr("Hint (H)").to_owned(), self.can_hint())), None), + }; + let clicked = side_panel( + ui, + |ui| self.state_card(ui, state), + &opening, + &path, + |ui| { + if *state == State::Summary { + self.summary_body(ui); + } else { + self.comment(ui, state); + } + }, + left, + right, + *state == State::Summary || matches!(state, State::SaveError(_)), + // The summary has its own way out; «× Finish» there would be a second one. + *state != State::Summary, + ); + match clicked { + Some(Clicked::Left) => match state { + State::Summary => actions.push(SessionAction::MoreNew), + State::SaveError(_) => self.request_exit(actions), + _ => { + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + }, + Some(Clicked::Right) => self.main_action(state, actions), + Some(Clicked::Flip) => self.orientation = self.orientation.other(), + Some(Clicked::Finish) => self.request_exit(actions), + None => {} + } + } + + pub fn show(&mut self, ui: &mut Ui, settings: &Settings, name: &str) -> Vec { + let animation = Duration::from_secs_f32(settings.animation.seconds()); + self.tick_at(Instant::now(), animation, layout::now()); + if self.commit_in_flight.is_some() { + ui.ctx().request_repaint_after(Duration::from_millis(16)); + } else if let Some(deadline) = self.playback_deadline() { + ui.ctx() + .request_repaint_after(deadline.saturating_duration_since(Instant::now())); + } else if self.needs_prepare || self.pending_automatic.is_some() { + ui.ctx().request_repaint(); + } + if let Some(state) = self.state() { + self.shown_state = state; + } + if self.shown_state == State::Summary { + self.compute_summary(); + } + let mut actions = Vec::new(); + self.keyboard(ui, &mut actions); + let state = self.shown_state.clone(); + let subtitle = self.kind.subtitle(self.session.stats_scope.side); + let back = if ui.available_width() < 600.0 { + "⬅" + } else if self.back_to_lines { + tr("⬅ Lines") + } else { + tr("⬅ Repertoires") + }; + let mut header = (false, false); + layout::screen( + ui, + self, + |_, ui| header = crate::widgets::section_header_sub(ui, back, name, &subtitle), + |this, ui| this.side(ui, &state, &mut actions), + |this, ui| this.board_ui(ui, settings), + ); + if header.0 { + self.request_exit(&mut actions); + } + if header.1 { + actions.push(SessionAction::OpenSettings); + } + if std::mem::take(&mut self.leave) { + actions.push(SessionAction::Back); + } + actions.extend(self.pending_sounds.drain(..).map(SessionAction::Sound)); + actions + } + + pub fn debug_settle(&mut self) { + // Only this explicit QA hook waits. Normal frames poll workers without blocking. + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if self.commit_in_flight.is_some() { + self.poll_commit(Instant::now()); + if Instant::now() >= deadline { + return; + } + if self.commit_in_flight.is_some() { + std::thread::sleep(Duration::from_millis(1)); + continue; + } + } + if self.has_unsaved() { + return; + } + if self.pending_automatic.is_some() { + self.board_shown = true; + } + let at = self + .playback_deadline() + .map_or_else(Instant::now, |at| at.max(Instant::now())); + self.tick_at(at, Duration::ZERO, layout::now()); + if self.commit_in_flight.is_none() + && self.pending_automatic.is_none() + && !self.needs_prepare + && self.playback_deadline().is_none() + { + return; + } + if Instant::now() >= deadline { + return; + } + } + } + + pub fn debug_hint(&mut self) { + if self.needs_prepare { + self.debug_settle(); + } + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + + /// QA (`CP_REPERTOIRE_MOVES`): UCI moves as from the board; `hint`, `settle`, + /// `skip`, `stop` (Esc), `answer` (the expected move), `wrong` (a move not in the + /// repertoire). + pub fn debug_moves(&mut self, moves: &str) { + if self.needs_prepare { + self.debug_settle(); + } + for text in moves.split_whitespace() { + match text { + "hint" => self.debug_hint(), + "settle" | "wait" => self.debug_settle(), + "skip" => { + self.skip_context(Instant::now()); + } + "stop" => { + let mut actions = Vec::new(); + self.request_exit(&mut actions); + } + "answer" => { + if let Some(uci) = self.session.current_expected_uci().map(str::to_owned) { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(&uci, id, Instant::now(), layout::now()); + } + } + "wrong" => { + if let Some(uci) = self.debug_wrong_move() { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(&uci, id, Instant::now(), layout::now()); + } + } + _ => { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(text, id, Instant::now(), layout::now()); + } + } + } + } + + /// A legal move that is no answer of the repertoire here. + fn debug_wrong_move(&self) -> Option { + use chess_core::shakmaty::Position; + let position = fen4(&self.board_position); + let user = self.session.current_target()?.key.user_id.clone(); + self.board_position + .legal_moves() + .into_iter() + .find_map(|mv| { + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + let key = LearningItemKey::new(user.clone(), position.clone(), &uci); + (!self.repertoire_answers.contains(&key)).then_some(uci) + }) + } +} + +/// «Preparing…» (S0): the session's screen before the session exists, so the board +/// and the panel do not move when it comes. +pub fn show_preparing( + ui: &mut Ui, + settings: &Settings, + board: &mut BoardState, + view: &PreparingView<'_>, +) -> Vec { + let mut actions = Vec::new(); + if !ui.ctx().egui_wants_keyboard_input() + && !crate::app::overlay_open(ui.ctx()) + && ui.input_mut(|input| { + input.consume_key(Modifiers::NONE, Key::Escape) + || input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + }) + { + actions.push(SessionAction::Back); + } + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + view.back + }; + let mut header = (false, false); + layout::screen( + ui, + board, + |_, ui| header = crate::widgets::section_header_sub(ui, back, view.name, view.subtitle), + |_, ui| { + let clicked = side_panel( + ui, + |ui| { + show_card( + ui, + &CardView { + title: tr("Preparing…").to_owned(), + instruction: String::new(), + title_color: None, + active: false, + alert: false, + count: "—".to_owned(), + label: if view.lines { tr("line") } else { tr("left") }, + }, + ) + }, + "", + "", + |_| {}, + Some((tr("Hint (H)").to_owned(), false)), + None, + false, + true, + ); + if clicked == Some(Clicked::Finish) { + actions.push(SessionAction::Back); + } + }, + |board, ui| { + layout::still_board( + ui, + board, + settings, + view.position, + view.orientation, + view.last_move, + &BoardAnnotations::default(), + ) + }, + ); + if header.0 { + actions.push(SessionAction::Back); + } + if header.1 { + actions.push(SessionAction::OpenSettings); + } + actions +} + +pub struct PreparingView<'a> { + pub name: &'a str, + pub subtitle: &'a str, + pub back: &'a str, + pub position: &'a Chess, + pub orientation: Color, + pub last_move: Option<(Square, Square)>, + /// A review: the counter counts lines. + pub lines: bool, +} + +struct CardView { + title: String, + instruction: String, + title_color: Option, + active: bool, + alert: bool, + count: String, + label: &'static str, +} + +/// Block A: two lines on the left, the counter on the right; always 64 pt. +fn show_card(ui: &mut Ui, view: &CardView) { + layout::fixed_block(ui, CARD_H, |ui| { + let frame = layout::card(ui, view.active, view.alert); + let inner = layout::card_inner(ui, CARD_H); + frame.show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.horizontal(|ui| { + let counter_w = 64.0; + ui.allocate_ui_with_layout( + vec2((ui.available_width() - counter_w).max(0.0), inner.y), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + let mut title = RichText::new(&view.title).strong().size(15.0); + if let Some(color) = view.title_color { + title = title.color(color); + } + layout::line(ui, title); + layout::line(ui, RichText::new(&view.instruction).size(13.0)); + }, + ); + ui.with_layout(egui::Layout::top_down(egui::Align::Max), |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.label(RichText::new(&view.count).monospace().size(24.0)); + ui.label(RichText::new(view.label).weak().size(11.0)); + }); + }); + }); + }); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Clicked { + Left, + Right, + Flip, + Finish, +} + +/// The session's panel (spec §4.1): A card · B opening · D comment or result · E +/// actions · F tool row; every block keeps its height in every state. +#[allow(clippy::too_many_arguments)] +fn side_panel( + ui: &mut Ui, + card: impl FnOnce(&mut Ui), + opening: &str, + path: &str, + body: impl FnOnce(&mut Ui), + left: Option<(String, bool)>, + right: Option<(String, bool)>, + right_primary: bool, + finish: bool, +) -> Option { + let mut clicked = None; + let rect = ui.available_rect_before_wrap(); + let footer_h = TOOL_H + 12.0; + let footer = egui::Rect::from_min_max( + egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())), + rect.max, + ); + let body_rect = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); + ui.scope_builder(egui::UiBuilder::new().max_rect(body_rect), |ui| { + ui.set_clip_rect(body_rect.intersect(ui.clip_rect())); + ui.spacing_mut().item_spacing.y = GAP; + ui.add_space(4.0); + card(ui); + layout::fixed_block(ui, LINE_H, |ui| { + layout::line(ui, RichText::new(opening).weak()); + }); + // C: the moves to the position on the board, cut on the left. + layout::fixed_block(ui, LINE_H, |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let shown = layout::cut_left(ui, path, &font, ui.available_width()); + ui.add(egui::Label::new(RichText::new(shown).weak()).truncate()); + }); + let rest = (ui.available_height() - ROW_H - GAP).max(0.0); + layout::fixed_block(ui, rest, body); + layout::fixed_block(ui, ROW_H, |ui| { + ui.horizontal(|ui| { + if let Some((label, enabled)) = left { + let response = ui.add_enabled( + enabled, + egui::Button::new(label) + .truncate() + .min_size(vec2(LEFT_W.min(ui.available_width() / 2.0), ROW_H)), + ); + if response.clicked() { + clicked = Some(Clicked::Left); + } + } + if let Some((label, enabled)) = right { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let width = MAIN_W.min(ui.available_width()); + let response = if right_primary { + ui.add_enabled_ui(enabled, |ui| { + crate::widgets::primary_wide(ui, &label, width) + }) + .inner + } else { + ui.add_enabled( + enabled, + egui::Button::new(label) + .truncate() + .min_size(vec2(width, ROW_H)), + ) + }; + if response.clicked() { + clicked = Some(Clicked::Right); + } + }); + } + }); + }); + }); + ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { + ui.separator(); + ui.horizontal(|ui| { + let icon = |s: &str| { + egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H)) + }; + if ui + .add(icon("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + clicked = Some(Clicked::Flip); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if finish + && ui + .add( + egui::Button::new(RichText::new(tr("× Finish")).size(14.0)) + .min_size(vec2(0.0, TOOL_H)), + ) + .on_hover_text(tr("Finish the session (Esc)")) + .clicked() + { + clicked = Some(Clicked::Finish); + } + }); + }); + }); + clicked +} + +impl VisualMove { + fn from_context(step: &LearningContextStep) -> Result { + let before = parse_position(&step.from)?; + let mv = step + .uci + .parse::() + .ok() + .and_then(|uci| uci.to_move(&before).ok()) + .ok_or_else(|| format!("automatic context move {} is not legal", step.uci))?; + Ok(Self::new(step.uci.clone(), before, mv)) + } + + fn new(uci: String, before: Chess, mv: Move) -> Self { + use chess_core::shakmaty::Position; + let from = mv.from().unwrap_or_else(|| mv.to()); + let to = crate::board::ui_target(&mv); + let mut after = before.clone(); + after.play_unchecked(mv); + Self { + uci, + before, + after, + from, + to, + } + } +} + +fn parse_position(position: &trainer::repertoire::LearningPosition) -> Result { + position + .fen + .parse::() + .map_err(|error| error.to_string())? + .into_position(CastlingMode::Standard) + .map_err(|error| error.to_string()) +} + +fn unique_id(prefix: &str) -> String { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_nanos()); + let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed); + format!("{prefix}-{nanos:x}-{}-{sequence:x}", std::process::id()) +} + +#[cfg(test)] +#[path = "opening_session_tests.rs"] +mod tests; + +/// (learned, learning) in a scope, by the core's statuses; zeros if it cannot be counted. +fn progress_counts( + library: &Library, + learning: &LearningData, + scope: &StatsScope, +) -> (usize, usize) { + aggregate_scope(library, learning, scope, &SrsSettings::default()).map_or((0, 0), |scoped| { + (scoped.summary.learnt, scoped.summary.learning) + }) +} diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs new file mode 100644 index 0000000..5933734 --- /dev/null +++ b/apps/desktop/src/opening_session_tests.rs @@ -0,0 +1,2260 @@ +use std::path::PathBuf; + +use super::*; +use chess_core::shakmaty::Position; +use trainer::repertoire::{LearningStoreData, active_learning_memberships}; + +#[test] +fn status_growth_does_not_move_training_controls() { + let mut positions = Vec::new(); + for message in [ + "Your turn", + "Hint\nReplay the shown move\nNo independent success", + ] { + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| { + egui::CentralPanel::default().show(ui, |ui| { + layout::fixed_block(ui, 144.0, |ui| { + ui.label(message); + }); + positions.push(ui.button("Hint").rect.top()); + }); + }); + output.drop_without_applying_deltas(); + } + assert_eq!(positions[0], positions[1]); + assert!(positions[0] >= 144.0); +} + +const NOW: i64 = 1_800_000_000; +static NEXT_TEST: AtomicU64 = AtomicU64::new(1); + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "cp-opening-session-{}-{}-{name}", + std::process::id(), + NEXT_TEST.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn store(&self) -> LearningStore { + LearningStore::new(self.0.join("learning.json")) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +struct Fixture { + _dir: TestDir, + library: Library, + scope: StatsScope, + store: LearningStore, + ui: OpeningSessionUi, +} + +impl Fixture { + /// A daily session asking exactly `due`: every other move of the side is known and + /// not due. + fn new(pgn: &str, side: LearningSide, due: &[&str], name: &str) -> Self { + Self::with(pgn, side, due, &[], name, SessionKind::Daily) + } + + /// `due` are due, `new` never shown, every other move known and not due. + fn with( + pgn: &str, + side: LearningSide, + due: &[&str], + new: &[&str], + name: &str, + kind: SessionKind, + ) -> Self { + let dir = TestDir::new(name); + let mut library = Library::default(); + let id = library + .create("Test", &chess_core::parse_str(pgn).game) + .unwrap(); + let scope = StatsScope::for_repertoire(id, side, NOW); + let mut learning = LearningData::default(); + for membership in active_learning_memberships(&library, &scope).unwrap() { + let uci = membership.key.expected_uci.as_str(); + if new.contains(&uci) { + continue; + } + let item = learning.ensure_item(membership.key.clone()); + item.introduced = true; + if due.contains(&uci) { + item.next_review_at = Some(NOW); + } else { + item.correct_streak = 1; + item.correct_count = 1; + item.last_correct_at = Some(NOW - 24 * 60 * 60); + item.next_review_at = Some(NOW + 10 * 24 * 60 * 60); + } + } + let bytes = serde_json::to_vec_pretty(&LearningStoreData { + learning, + ..LearningStoreData::default() + }) + .unwrap(); + std::fs::write(dir.0.join("learning.json"), bytes).unwrap(); + let store = dir.store(); + let mut ui = + OpeningSessionUi::new(library.clone(), store.clone(), scope.clone(), kind).unwrap(); + ui.board_shown = true; + ui.synchronous_commits = true; + ui.feedback = Duration::ZERO; + Self { + _dir: dir, + library, + scope, + store, + ui, + } + } + + fn attempts(&self) -> Vec { + self.store.load().unwrap().learning.attempts + } +} + +fn key_for(library: &Library, scope: &StatsScope, expected: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected) + .unwrap() + .key +} + +fn normal() -> Duration { + Duration::from_millis(250) +} + +fn answer_current(f: &mut Fixture, at: Instant, happened_at: i64, id: &str) { + let expected = f.ui.session.current_expected_uci().unwrap().to_owned(); + assert!(f.ui.play_uci_with_id_at(&expected, id.to_owned(), at, happened_at,)); + tick_with_prime(&mut f.ui, at, Duration::ZERO, happened_at); +} + +fn board_frame(f: &mut Fixture, ctx: &egui::Context, time: f64, settings: &Settings) { + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(800.0, 800.0), + )), + time: Some(time), + ..Default::default() + }, + |ui| f.ui.board_ui(ui, settings), + ) + .drop_without_applying_deltas(); +} + +fn tick_with_prime(ui: &mut OpeningSessionUi, at: Instant, animation: Duration, happened_at: i64) { + ui.tick_at(at, animation, happened_at); + if ui.pending_automatic.is_none() { + return; + } + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let settings = Settings::default(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(800.0, 800.0), + )), + time: Some(0.0), + ..Default::default() + }, + |root| ui.board_ui(root, &settings), + ) + .drop_without_applying_deltas(); + assert!(ui.board_shown); + assert!(ui.board.animation_at(0.0).is_none()); + ui.tick_at(at, animation, happened_at); +} + +fn automatic_duration(f: &Fixture) -> Duration { + match &f.ui.playback { + Some(Playback::Automatic { duration, .. }) => *duration, + _ => panic!("automatic playback expected"), + } +} + +fn assert_current_slide( + f: &Fixture, + time: f64, + expected_duration: Duration, + from: Square, + to: Square, +) { + let (duration, slides, remaining) = + f.ui.board + .animation_at(time) + .expect("the current BoardView transition"); + assert_eq!(remaining, 1.0, "the first visual frame must be at from"); + assert!( + (duration - f64::from(expected_duration.as_secs_f32())).abs() < 1e-6, + "animation {duration} does not match scheduler {}", + expected_duration.as_secs_f32() + ); + assert!( + slides + .iter() + .any(|(_, slide_from, slide_to)| *slide_from == from && *slide_to == to), + "missing {from}{to} in {slides:?}" + ); +} + +fn assert_adaptive_board_slides(f: &mut Fixture, first_ms: u128, last_ms: u128) { + let ctx = egui::Context::default(); + let settings = Settings::default(); + let start = Instant::now(); + f.ui.board_shown = false; + f.ui.tick_at(start, normal(), NOW); + board_frame(f, &ctx, 0.0, &settings); + assert!(f.ui.board.animation_at(0.0).is_none()); + + f.ui.tick_at(start, normal(), NOW); + let first = automatic_duration(f); + assert_eq!(first.as_millis(), first_ms); + assert_eq!(f.ui.playback_deadline(), Some(start + first)); + assert_eq!(f.ui.session.context_index, 0); + board_frame(f, &ctx, 0.01, &settings); + assert_current_slide(f, 0.01, first, Square::E2, Square::E4); + assert_eq!(f.ui.state(), Some(State::Watch)); + + tick_with_prime(&mut f.ui, start + first, normal(), NOW); + let last = automatic_duration(f); + assert_eq!(last.as_millis(), last_ms); + assert_eq!(f.ui.session.context_index, 1); + board_frame(f, &ctx, 0.02, &settings); + assert_current_slide(f, 0.02, last, Square::E7, Square::E5); + assert_eq!(f.ui.state(), Some(State::Watch)); + + tick_with_prime(&mut f.ui, start + first + last, normal(), NOW); + assert_eq!(f.ui.session.context_index, 2); + assert!(f.ui.can_input()); + board_frame(f, &ctx, 10.0, &settings); + assert!( + f.ui.board.animation_at(10.0).is_none(), + "the final position must not start a settings-duration slide" + ); + assert_eq!(f.attempts().len(), 2); +} + +#[test] +fn adaptive_board_animation_matches_actual_slides_and_starts_at_from() { + let mut fast = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "adaptive-fast", + ); + let e4 = key_for(&fast.library, &fast.scope, "e2e4"); + fast.ui.learning.ensure_item(e4).correct_streak = 3; + fast.ui.session.context_policy.use_fixed_piece_speed = false; + fast.ui.session.context_policy.move_speed_adjustment = 1.5; + assert_adaptive_board_slides(&mut fast, 83, 166); + + let mut slow = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "adaptive-slow", + ); + slow.ui.session.context_policy.use_fixed_piece_speed = false; + slow.ui.session.context_policy.move_speed_adjustment = 0.0; + assert_adaptive_board_slides(&mut slow, 1000, 1000); +} + +#[test] +fn next_target_continues_the_shown_line_without_reverse_slide() { + fn settle_to_input(f: &mut Fixture, at: Instant) { + let mut at = at; + for _ in 0..32 { + if f.ui.can_input() { + return; + } + let next = f.ui.playback_deadline().unwrap_or(at); + tick_with_prime(&mut f.ui, next, normal(), NOW); + at = next; + } + panic!("training did not reach independent input"); + } + + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::Black, + &["e7e5", "b8c6", "a7a6"], + "next-target-prime", + ); + f.ui.session.context_policy.use_fixed_piece_speed = false; + f.ui.session.context_policy.move_speed_adjustment = 0.0; + let start = Instant::now(); + settle_to_input(&mut f, start); + assert_eq!(f.ui.session.current_expected_uci(), Some("e7e5")); + answer_current( + &mut f, + start + Duration::from_secs(1), + NOW, + "first-target-e5", + ); + + settle_to_input(&mut f, start + Duration::from_secs(1) + normal()); + assert_eq!(f.ui.session.current_expected_uci(), Some("b8c6")); + answer_current( + &mut f, + start + Duration::from_secs(3), + NOW + 1, + "second-target-nc6", + ); + + let prime_at = start + Duration::from_secs(3) + normal(); + // Every old move keeps its event, but a long visible prefix requires + // only one store transaction before the next opponent move. + let before_reuse = f.store.load().unwrap(); + for _ in 0..8 { + f.ui.tick_at(prime_at, normal(), NOW); + if f.ui.pending_automatic.is_some() { + break; + } + } + assert!(f.ui.pending_automatic.is_some()); + let after_reuse = f.store.load().unwrap(); + assert_eq!(after_reuse.revision, before_reuse.revision + 1); + let added = &after_reuse.learning.attempts[before_reuse.learning.attempts.len()..]; + assert_eq!(added.len(), 4); + assert!( + added + .iter() + .all(|event| event.event_type == TrainingEventType::AutoContext) + ); + assert_eq!(f.ui.session.context_index, 4); + assert!(!f.ui.board_shown); + let ctx = egui::Context::default(); + let settings = Settings::default(); + board_frame(&mut f, &ctx, 10.0, &settings); + assert!( + f.ui.board.animation_at(10.0).is_none(), + "prime must not animate the previous target backwards" + ); + + f.ui.tick_at(prime_at, normal(), NOW); + let duration = automatic_duration(&f); + assert_eq!(duration, Duration::from_millis(1000)); + board_frame(&mut f, &ctx, 10.01, &settings); + assert_current_slide(&f, 10.01, duration, Square::F1, Square::B5); + let (_, slides, _) = f.ui.board.animation_at(10.01).unwrap(); + assert!( + slides + .iter() + .all(|(_, from, to)| !(*from == Square::F3 && *to == Square::G1)), + "next target started with a reverse slide: {slides:?}" + ); + assert!(matches!( + &f.ui.playback, + Some(Playback::Automatic { remaining, .. }) if remaining.is_empty() + )); +} + +fn emitted_sounds(f: &mut Fixture, ctx: &egui::Context, settings: &Settings) -> Vec { + let mut sounds = Vec::new(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(960.0, 600.0), + )), + ..Default::default() + }, + |ui| { + sounds.extend( + f.ui.show(ui, settings, "Test") + .into_iter() + .filter_map(|action| { + if let SessionAction::Sound(sound) = action { + Some(sound) + } else { + None + } + }), + ); + }, + ) + .drop_without_applying_deltas(); + sounds +} + +#[test] +fn accepted_move_emits_once_and_next_task_only_animates_the_opponent_reply() { + for side in [LearningSide::White, LearningSide::Black] { + for animation in [ + crate::settings::Animation::Normal, + crate::settings::Animation::Off, + ] { + for replay in [false, true] { + let (due, reply, wrong) = match side { + LearningSide::White => (["e2e4", "g1f3"], "e7e5", "d2d4"), + LearningSide::Black => (["e7e5", "b8c6"], "g1f3", "d7d5"), + }; + let mut f = + Fixture::new("1. e4 e5 2. Nf3 Nc6 *", side, &due, "continuous-feedback"); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + let ctx = egui::Context::default(); + let settings = Settings { + animation, + ..Settings::default() + }; + let at = Instant::now() + Duration::from_secs(60); + let duration = Duration::from_secs_f32(animation.seconds()); + f.ui.animation = duration; + f.ui.pending_sounds.clear(); + f.ui.visual_log.clear(); + if replay { + assert!(f.ui.play_uci_with_id_at(wrong, "wrong".into(), at - WRONG_SHOWN, NOW)); + f.ui.tick_at(at, duration, NOW); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Wrong]); + } + assert!(f.ui.play_uci_with_id_at(due[0], "accepted".into(), at, NOW)); + let accepted_position = fen4(&f.ui.board_position); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); + for _ in 0..8 { + f.ui.tick_at(at + duration, duration, NOW); + assert_eq!( + fen4(&f.ui.board_position), + accepted_position, + "accepted move must not rewind" + ); + if f.ui.pending_automatic.is_some() { + break; + } + } + assert!(f.ui.pending_automatic.is_some()); + // The prime frame is silent; a separate later frame emits the + // opponent move, so queue coalescing cannot conceal a duplicate. + assert!(emitted_sounds(&mut f, &ctx, &settings).is_empty()); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); + assert_eq!(f.ui.visual_log, [reply]); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some(due[1])); + let attempts = f.attempts(); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type.is_independent()) + .count(), + 1 + ); + assert!(attempts.iter().any(|event| event.expected_uci == due[0] + && event.event_type == TrainingEventType::AutoContext)); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type == TrainingEventType::ReplayAfterError) + .count(), + usize::from(replay) + ); + } + } + } +} + +#[test] +fn shown_context_requires_the_same_history_and_never_bypasses_a_question() { + let mut f = Fixture::new( + "1. Nf3 Nf6 2. g3 g6 3. Bg2 *", + LearningSide::White, + &["f1g2"], + "context-identity", + ); + let presentation = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + f.ui.board_position = parse_position(&presentation.automatic_context[3].to).unwrap(); + let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); + // Even with an identical final position, a different move order must not + // reuse context. A matching FEN alone cannot establish repetition history. + f.ui.shown_prefix = Some(ShownPrefix { + repertoire_id: id.clone(), + path: vec!["g2g3".into(), "g7g6".into(), "g1f3".into(), "g8f6".into()], + }); + assert!(!f.ui.reuse_shown_context(&presentation, Instant::now())); + assert!(f.attempts().is_empty()); + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "context-question", + ); + let presentation = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + f.ui.board_position = parse_position(&presentation.automatic_context[1].to).unwrap(); + f.ui.shown_prefix = Some(ShownPrefix { + repertoire_id: f.ui.session.current_target().unwrap().repertoire_id.clone(), + path: vec!["e2e4".into(), "e7e5".into()], + }); + f.ui.session.context_policy.consider_leadup_moves = true; + let question = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + assert_eq!( + question.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert!(!f.ui.reuse_shown_context(&question, Instant::now())); + f.ui.prepare_presentation(Instant::now()); + assert!(f.ui.can_input()); + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.attempts().is_empty()); +} + +fn assert_annotation_badge(ui: &OpeningSessionUi, text: &str, square: Square) { + let annotation = ui.displayed_annotations(); + let badge = annotation.badge.expect("PGN move badge"); + assert_eq!(badge.text, text); + assert_eq!(badge.square, square); +} + +#[test] +fn pgn_annotations_follow_visible_user_and_automatic_moves_not_the_next_task() { + let mut f = Fixture::with( + "1. e4!! {[%cal Re2e4,Ge7e5] [%csl Ye4,Re5]} e5?! {[%cal Bg1f3]} 2. Nf3! {[%csl Gf3]} Nc6 *", + LearningSide::White, + &["e2e4", "g1f3"], + &[], + "visible-pgn-annotations", + SessionKind::ReviewAll, + ); + let original = + f.ui.library + .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) + .unwrap() + .pgn + .clone(); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().arrows.is_empty()); + // A hint reveals the expected move, not that future node's annotations. + assert!(f.ui.request_hint_with_id_at("annotation-hint".into(), start, NOW)); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().arrows.is_empty()); + assert!(f.ui.play_uci_with_id_at("e2e4", "annotation-e4".into(), start, NOW)); + assert_eq!( + f.ui.session.current_target().unwrap().key.expected_uci, + "g1f3" + ); + assert_annotation_badge(&f.ui, "!!", Square::E4); + let annotation = f.ui.displayed_annotations(); + assert_eq!(annotation.arrows.len(), 2); + assert_eq!(annotation.circles.len(), 2); + assert!( + annotation + .arrows + .iter() + .any(|arrow| arrow.from == Square::E2 + && arrow.to == Square::E4 + && arrow.color == crate::game_view::shape_color(chess_core::ShapeColor::Red)) + ); + // Verify the helper's data actually reaches the rendered BoardView. + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let output = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &Settings::default()); + assert!(output.shapes.iter().any( + |shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "!!") + )); + output.drop_without_applying_deltas(); + f.ui.tick_at(start + normal(), normal(), NOW); + assert_annotation_badge(&f.ui, "!!", Square::E4); + assert!(f.ui.visual_log.is_empty(), "reused e4 must not play again"); + for _ in 0..8 { + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + if matches!(f.ui.playback, Some(Playback::Automatic { .. })) { + break; + } + } + assert_eq!(f.ui.visual_log, ["e7e5"]); + assert_annotation_badge(&f.ui, "?!", Square::E5); + assert_eq!(f.ui.displayed_annotations().arrows[0].from, Square::G1); + f.ui.tick_at(f.ui.playback_deadline().unwrap(), normal(), NOW); + assert!(f.ui.can_input()); + assert_annotation_badge(&f.ui, "?!", Square::E5); + assert!( + f.ui.displayed_annotations().circles.is_empty(), + "future Nf3 circle leaked before the answer" + ); + assert!(f.ui.play_uci_with_id_at( + "g1f3", + "annotation-nf3".into(), + start + Duration::from_secs(1), + NOW + )); + assert_annotation_badge(&f.ui, "!", Square::F3); + assert_eq!(f.ui.displayed_annotations().circles[0].0, Square::F3); + f.ui.debug_settle(); + assert_annotation_badge(&f.ui, "!", Square::F3); + assert_eq!( + f.ui.library + .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) + .unwrap() + .pgn, + original + ); +} + +#[test] +fn pgn_annotations_clear_for_wrong_moves_and_survive_failed_async_save_and_retry() { + let mut f = Fixture::new( + "1. e4!! {[%csl Ge4]} *", + LearningSide::White, + &["e2e4"], + "annotations-retry", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("d2d4", "annotations-wrong".into(), start, NOW)); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().circles.is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert!(f.ui.can_input()); + assert!(f.ui.displayed_annotations().badge.is_none()); + // Another wrong move during replay must not inherit the revealed e4 badge. + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "annotations-wrong-replay".into(), + start + WRONG_SHOWN, + NOW + )); + assert!(f.ui.displayed_annotations().badge.is_none()); + f.ui.tick_at(start + WRONG_SHOWN * 2, normal(), NOW); + let store = f.ui.store.clone(); + f.ui.synchronous_commits = false; + f.ui.store = LearningStore::with_legacy(store.path(), store.path()); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "annotations-replay".into(), + start + WRONG_SHOWN * 2, + NOW + )); + assert!(f.ui.has_unsaved()); + assert_annotation_badge(&f.ui, "!!", Square::E4); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert_annotation_badge(&f.ui, "!!", Square::E4); + f.ui.store = store; + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + assert_annotation_badge(&f.ui, "!!", Square::E4); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(), + 1 + ); + assert_eq!( + f.attempts().last().unwrap().event_type, + TrainingEventType::ReplayAfterError + ); +} + +#[test] +fn alternative_answer_credits_actual_move_and_completed_answer_is_silent_and_neutral() { + let mut f = Fixture::new( + "1. e4! (1. d4!! {[%csl Gd4]}) *", + LearningSide::White, + &["e2e4", "d2d4"], + "alternative-answers", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + let original = f.ui.session.current_expected_uci().unwrap().to_owned(); + let (played, badge, square) = if original == "e2e4" { + ("d2d4", "!!", Square::D4) + } else { + ("e2e4", "!", Square::E4) + }; + let initial_position = f.ui.board_position.clone(); + assert_eq!( + f.ui.session + .pending_answers_for_position(&fen4(&initial_position)) + .len(), + 2 + ); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + assert_eq!(f.ui.state(), Some(State::Yours)); + assert!(f.ui.play_uci_with_id_at(played, "actual-alternative".into(), start, NOW)); + assert_annotation_badge(&f.ui, badge, square); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].expected_uci, played); + assert_eq!( + f.attempts()[0].event_type, + TrainingEventType::CorrectIndependent + ); + assert_eq!(f.ui.session.current_expected_uci(), Some(original.as_str())); + assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); + f.ui.tick_at(start + normal(), normal(), NOW); + assert_eq!(f.ui.board_position, initial_position); + // S3a: the other answer of this position is still asked. + let played_san = if played == "d2d4" { "d4" } else { "e4" }; + assert_eq!(f.ui.state(), Some(State::YoursMore(played_san.to_owned()))); + assert!(f.ui.play_uci_with_id_at(played, "repeat-alternative".into(), start + normal(), NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert_annotation_badge(&f.ui, badge, square); + assert!(f.ui.save_error.is_none() && f.ui.error.is_none()); + assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); + f.ui.tick_at(start + normal() + WRONG_SHOWN, normal(), NOW); + assert_eq!(f.ui.board_position, initial_position); + assert!(f.ui.can_input()); + assert!(f.ui.displayed_annotations().badge.is_none()); + // «Now the other one: play …» shows the answer: recorded as shown, not as an + // error and not as known. + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!(attempts[1].event_type, TrainingEventType::Previewed); + assert_eq!(attempts[1].expected_uci, original); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert_eq!(f.ui.revealed_uci().as_deref(), Some(original.as_str())); + assert_eq!(f.ui.tally.mistakes, 0); + assert_eq!(f.ui.session.remaining(), 1); + assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); +} + +#[test] +fn move_input_uses_the_startup_answer_snapshot_in_independent_and_replay_phases() { + let mut f = Fixture::new( + "1. e4 (1. d4) *", + LearningSide::White, + &["e2e4"], + "cached-repertoire-answers", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + let key = key_for(&f.library, &f.scope, "d2d4"); + assert!(f.ui.repertoire_answers.contains(&key)); + // The production library is immutable for the UI's lifetime. Change it + // only here to detect any accidental rebuilding in the input hot path. + let id = f.scope.repertoire_ids.iter().next().unwrap(); + f.ui.library + .repertoire_mut(id) + .unwrap() + .set_prefix_disabled(&["d2d4".to_owned()], true) + .unwrap(); + assert!( + !active_learning_keys(&f.ui.library, &f.scope) + .unwrap() + .contains(&key) + ); + assert!(f.ui.play_uci_with_id_at("d2d4", "cached-independent".into(), start, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert!(f.attempts().is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + // The answer was revealed after the other move: no second preview. + assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); + assert!( + !f.ui + .request_hint_with_id_at("cached-preview".into(), start + WRONG_SHOWN, NOW) + ); + assert!(f.ui.play_uci_with_id_at("d2d4", "cached-replay".into(), start + WRONG_SHOWN, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].event_type, TrainingEventType::Previewed); + assert!(f.ui.pending_sounds.is_empty()); +} + +#[test] +fn known_unscheduled_answer_during_hint_is_neutral_but_outside_move_still_wrong() { + let mut f = Fixture::new( + "1. e4! (1. d4!! {[%csl Gd4]}) *", + LearningSide::White, + &["e2e4"], + "hint-alternative", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.request_hint_with_id_at("preview-alternative".into(), start, NOW)); + let attempts = f.attempts().len(); + let snapshot = f.ui.session.clone(); + assert!(f.ui.play_uci_with_id_at("d2d4", "unscheduled-alternative".into(), start, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_annotation_badge(&f.ui, "!!", Square::D4); + assert_eq!(f.ui.session, snapshot); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert_eq!(f.attempts().len(), attempts); + assert!(f.ui.can_input()); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert!(f.ui.play_uci_with_id_at( + "g1f3", + "outside-repertoire".into(), + start + WRONG_SHOWN, + NOW + )); + assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); + assert_eq!(f.ui.pending_sounds, [Sound::Wrong]); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert_eq!(f.attempts().len(), attempts); +} + +#[test] +fn authored_wrong_branch_has_its_own_annotations_only_after_it_is_played() { + let mut f = Fixture::new( + "1. e4! (1. d4?? {[%csl Rd4]}) e5 *", + LearningSide::White, + &["e2e4"], + "wrong-branch-annotations", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.play_uci_with_id_at("d2d4", "authored-wrong-branch".into(), start, NOW)); + assert_annotation_badge(&f.ui, "??", Square::D4); + assert_eq!( + f.ui.displayed_annotations().circles[0], + ( + Square::D4, + crate::game_view::shape_color(chess_core::ShapeColor::Red) + ) + ); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().circles.is_empty()); +} + +#[test] +fn pgn_annotation_cursor_distinguishes_transposed_paths_and_repertoire_sources() { + let mut f = Fixture::new( + "1. Nf3 (1. g3 g6 2. Nf3 Nf6? {[%csl Rf6]} 3. Bg2) Nf6 2. g3 g6! {[%csl Gg6]} 3. Bg2 *", + LearningSide::White, + &["f1g2"], + "annotations-transposition", + ); + let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); + let mut position_keys = Vec::new(); + for (path, badge, square) in [ + (["g1f3", "g8f6", "g2g3", "g7g6"], "!", Square::G6), + (["g2g3", "g7g6", "g1f3", "g8f6"], "?", Square::F6), + ] { + f.ui.set_displayed_path(Some(&ShownPrefix { + repertoire_id: id.clone(), + path: path.map(str::to_owned).to_vec(), + })); + let (_, node) = f.ui.displayed_node.as_ref().expect("exact PGN branch"); + f.ui.board_position = f.ui.annotation_games[&id].position(*node).unwrap().clone(); + position_keys.push(fen4(&f.ui.board_position)); + assert_annotation_badge(&f.ui, badge, square); + assert_eq!(f.ui.displayed_annotations().circles[0].0, square); + } + assert_eq!( + position_keys[0], position_keys[1], + "fixture must really transpose" + ); + let other_id = + f.ui.library + .create("Other annotations", &Game::new()) + .unwrap(); + f.ui.annotation_games.insert( + other_id.clone(), + chess_core::parse_str("1. Nf3 Nf6 2. g3 g6?? {[%csl Yg6]} *").game, + ); + f.ui.set_displayed_path(Some(&ShownPrefix { + repertoire_id: other_id.clone(), + path: ["g1f3", "g8f6", "g2g3", "g7g6"].map(str::to_owned).to_vec(), + })); + let (_, node) = f.ui.displayed_node.as_ref().unwrap(); + f.ui.board_position = f.ui.annotation_games[&other_id] + .position(*node) + .unwrap() + .clone(); + assert_annotation_badge(&f.ui, "??", Square::G6); +} + +#[test] +fn debug_moves_settles_prime_between_targets() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::Black, + &["e7e5", "b8c6", "a7a6"], + "debug-prime-between-targets", + ); + f.ui.debug_moves("e7e5 settle b8c6 settle"); + assert!(f.ui.can_input()); + assert_eq!(f.ui.session.current_expected_uci(), Some("a7a6")); + f.ui.debug_moves("a7a6 settle"); + assert!(f.ui.is_finished()); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(), + 3 + ); +} + +#[test] +fn automatic_context_has_three_separate_normal_timed_steps() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "context-normal", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert_eq!(f.ui.visual_log, ["e2e4"]); + assert_eq!(f.ui.session.context_index, 0); + assert!(!f.ui.can_input()); + + tick_with_prime(&mut f.ui, start + Duration::from_millis(249), normal(), NOW); + assert_eq!(f.ui.session.context_index, 0); + assert!(f.attempts().is_empty()); + + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + assert_eq!(f.ui.session.context_index, 1); + + tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW); + assert_eq!(f.ui.session.context_index, 2); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); + tick_with_prime(&mut f.ui, start + normal() * 3, normal(), NOW); + assert_eq!(f.ui.session.context_index, 3); + assert_eq!( + f.ui.session.phase, + LearningSessionPhase::AwaitingIndependent + ); + assert!(f.ui.can_input()); + assert_eq!(f.attempts().len(), 3); + assert_eq!( + trainer::repertoire::fen4(&f.ui.board_position), + key_for(&f.library, &f.scope, "b8c6").position_fen4 + ); +} + +#[test] +fn animation_off_commits_every_context_step_without_skipping_store_calls() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "context-off", + ); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); + assert_eq!(f.ui.session.context_index, 3); + assert!(f.ui.can_input()); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 3); + assert_eq!( + attempts + .iter() + .map(|attempt| attempt.actual_uci.as_deref()) + .collect::>(), + [Some("e2e4"), Some("e7e5"), Some("g1f3")] + ); + assert!(attempts.iter().all(|attempt| { + attempt.event_type == TrainingEventType::AutoContext && attempt.response_time_ms.is_none() + })); +} + +#[test] +fn legal_input_is_ignored_during_autoplay() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "autoplay-input", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(!f.ui.play_uci_with_id_at( + "e7e5", + "blocked-input".to_owned(), + start + Duration::from_millis(20), + NOW, + )); + assert_eq!(f.ui.session.context_index, 0); + assert!(f.attempts().is_empty()); + assert_eq!(f.ui.visual_log, ["e2e4"]); +} + +#[test] +fn wrong_answer_replays_without_a_second_independent_error() { + let mut f = Fixture::with( + "1. e4 *", + LearningSide::White, + &["e2e4"], + &[], + "wrong-replay", + SessionKind::ReviewAll, + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "wrong-d4".to_owned(), + start + Duration::from_millis(1500), + NOW, + )); + assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); + tick_with_prime( + &mut f.ui, + start + Duration::from_millis(1500) + WRONG_SHOWN, + normal(), + NOW, + ); + assert_eq!( + f.ui.session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + assert_eq!( + f.ui.presentation.as_ref().unwrap().revealed_move.as_deref(), + Some("e2e4") + ); + + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "wrong-replay-d4".to_owned(), + start + Duration::from_secs(3), + NOW, + )); + assert_eq!(f.attempts().len(), 1); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(3) + WRONG_SHOWN, + normal(), + NOW, + ); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "replay-e4".to_owned(), + start + Duration::from_secs(4), + NOW, + )); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(4) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!( + attempts[0].event_type, + TrainingEventType::IncorrectIndependent + ); + assert_eq!(attempts[0].response_time_ms, Some(1500)); + assert_eq!(attempts[1].event_type, TrainingEventType::ReplayAfterError); + assert_eq!(attempts[1].response_time_ms, None); + let item = f + .store + .load() + .unwrap() + .learning + .item(&key_for(&f.library, &f.scope, "e2e4")) + .unwrap() + .clone(); + assert_eq!(item.wrong_count, 1); + assert_eq!(item.correct_count, 0); +} + +#[test] +fn preview_is_idempotent_and_shown_move_is_not_success() { + let mut f = Fixture::with( + "1. e4 *", + LearningSide::White, + &["e2e4"], + &[], + "preview", + SessionKind::ReviewAll, + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(f.ui.request_hint_with_id_at( + "preview-e4".to_owned(), + start + Duration::from_millis(100), + NOW, + )); + assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); + assert!(!f.ui.request_hint_with_id_at( + "preview-e4-again".to_owned(), + start + Duration::from_millis(200), + NOW, + )); + assert_eq!(f.attempts().len(), 1); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "play-preview-e4".to_owned(), + start + Duration::from_secs(1), + NOW, + )); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(1) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.tally.hints, 1); + let data = f.store.load().unwrap(); + assert_eq!(data.learning.attempts.len(), 2); + assert_eq!( + data.learning.attempts[0].event_type, + TrainingEventType::Previewed + ); + assert_eq!( + data.learning.attempts[1].event_type, + TrainingEventType::AutoContext + ); + let item = data + .learning + .item(&key_for(&f.library, &f.scope, "e2e4")) + .unwrap(); + assert_eq!(item.correct_count, 0); + assert_eq!(item.wrong_count, 0); + assert!(item.independent_response_times_ms.is_empty()); +} + +#[test] +fn duplicate_store_response_does_not_advance_the_ui_twice() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "duplicate", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!( + f.ui.advance_context_with_id_at("duplicate-context".to_owned(), start + normal(), NOW,) + ); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.attempts().len(), 1); + + f.ui.completed_attempt_ids.remove("duplicate-context"); + assert!(f.ui.advance_context_with_id_at( + "duplicate-context".to_owned(), + start + normal() * 2, + NOW, + )); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.attempts().len(), 1); + assert!(!f.ui.visual_log.contains(&"g1f3".to_owned())); +} + +#[test] +fn store_error_is_visible_blocking_and_retryable() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "store-error"); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "save-error-e4".to_owned(), + start + Duration::from_millis(100), + NOW, + )); + assert!(f.ui.has_unsaved()); + assert!(f.ui.save_error.is_some()); + assert!(!f.ui.can_input()); + assert!(!f.ui.is_finished()); + assert!(f.attempts().is_empty()); + assert!(!f.ui.play_uci_with_id_at( + "d2d4", + "blocked-after-save-error".to_owned(), + start + Duration::from_millis(200), + NOW, + )); + + f.ui.store = valid_store; + f.ui.retry_pending(start + Duration::from_millis(300)); + assert!(!f.ui.has_unsaved()); + assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); + tick_with_prime( + &mut f.ui, + start + Duration::from_millis(300) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + assert_eq!(f.attempts().len(), 1); +} + +/// Runs one frame of the whole screen at a window size; returns the side panel's rect. +fn screen_frame( + ui: &mut OpeningSessionUi, + ctx: &egui::Context, + size: egui::Vec2, + events: Vec, +) -> (Vec, egui::Rect) { + let mut actions = Vec::new(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + time: Some(0.0), + events, + ..Default::default() + }, + |root| actions = ui.show(root, &Settings::default(), "Test repertoire"), + ) + .drop_without_applying_deltas(); + let panel = egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side")) + .or_else(|| { + egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side_stacked")) + }) + .map(|state| state.outer_rect) + .unwrap_or(egui::Rect::NOTHING); + (actions, panel) +} + +fn key(key: Key) -> egui::Event { + egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + } +} + +#[test] +fn the_panel_takes_the_game_screens_place_at_both_reference_sizes() { + for (size, left) in [ + (vec2(1920.0, 1080.0), 1360.0), + (vec2(1400.0, 900.0), 896.0), + (vec2(960.0, 600.0), 580.0), + ] { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "geometry"); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let mut rects = Vec::new(); + for _ in 0..3 { + rects.push(screen_frame(&mut f.ui, &ctx, size, Vec::new()).1); + } + assert!( + (rects[2].left() - left).abs() <= 1.0, + "panel at {} in {size:?}", + rects[2].left() + ); + assert_eq!(rects[1], rects[2]); + // A question, a wrong move and its replay: the panel never moves. + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert!(f.ui.play_uci_with_id_at("d2d4", "geometry-wrong".into(), Instant::now(), NOW)); + assert_eq!(screen_frame(&mut f.ui, &ctx, size, Vec::new()).1, rects[2]); + assert!(f.ui.state() == Some(State::Wrong)); + } +} + +#[test] +fn a_new_move_is_shown_before_it_is_asked_and_counts_once_played() { + let mut f = Fixture::with( + "1. e4 {The king's pawn.} e5 *", + LearningSide::White, + &[], + &["e2e4"], + "new-move-shown", + SessionKind::Daily, + ); + assert_eq!(f.ui.session.remaining(), 1); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + // Shown at once: the arrow and the comment visible, no hint; nothing recorded + // until it is played. + assert!(f.attempts().is_empty()); + assert!(f.ui.session.showing_new); + assert_eq!(f.ui.state(), Some(State::New)); + assert_eq!(f.ui.revealed_uci().as_deref(), Some("e2e4")); + assert!(!f.ui.can_hint()); + assert!(f.ui.can_input()); + let (game, node) = f.ui.expected_node().unwrap(); + assert_eq!( + crate::notation::comment_text(game.node(node).unwrap().comments_after()), + "The king's pawn." + ); + let (title, instruction, _) = f.ui.card_texts(&State::New, true); + assert_eq!(title, tr("New move")); + assert!(instruction.contains("1. e4"), "{instruction}"); + assert!(f.ui.play_uci_with_id_at("e2e4", "play-new".into(), Instant::now(), NOW)); + assert_eq!(f.ui.state(), Some(State::NewDone)); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.session.remaining(), 0); + assert_eq!(f.ui.tally.new_moves, 1); + assert_eq!( + f.ui.tally.mistakes + f.ui.tally.hints + f.ui.tally.first_time, + 0 + ); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!(attempts[0].event_type, TrainingEventType::Previewed); + assert_eq!(attempts[1].event_type, TrainingEventType::AutoContext); +} + +#[test] +fn a_new_move_left_unplayed_stays_new() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &[], + &["e2e4", "g1f3"], + "new-move-unplayed", + SessionKind::Daily, + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "play-e4".into(), at, NOW)); + let later = at + Duration::from_secs(5); + for _ in 0..4 { + tick_with_prime(&mut f.ui, later, Duration::ZERO, NOW); + } + assert_eq!(f.ui.state(), Some(State::New)); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + // A wrong move on a shown new move records nothing either. + assert!(f.ui.play_uci_with_id_at("d2d4", "wrong-nf3".into(), later, NOW)); + tick_with_prime(&mut f.ui, later + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.state(), Some(State::New)); + let mut actions = Vec::new(); + f.ui.request_exit(&mut actions); + assert!(f.ui.summary_visible()); + let attempts = f.attempts(); + let nf3 = attempts + .iter() + .filter(|attempt| attempt.expected_uci == "g1f3") + .count(); + assert_eq!( + nf3, + 0, + "{:?}", + attempts.iter().map(|a| a.event_type).collect::>() + ); + assert_eq!(f.ui.tally.new_moves, 1); +} + +#[test] +fn a_daily_session_brings_mistakes_and_hints_back_and_its_numbers_agree() { + // White's moves: e4, Nf3, Bb5, then O-O after a6 Ba4 Nf6 is new. + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O *"; + let mut f = Fixture::with( + pgn, + LearningSide::White, + &["e2e4", "g1f3", "f1b5"], + &["b5a4", "e1g1"], + "daily-numbers", + SessionKind::Daily, + ); + let at = Instant::now(); + assert_eq!(f.ui.session.remaining(), 5); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + // e4: a mistake, then the replay. It comes back: still 5 to go. + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.ui.play_uci_with_id_at("d2d4", "e4-wrong".into(), at, NOW)); + tick_with_prime(&mut f.ui, at + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.state(), Some(State::Wrong)); + answer_current(&mut f, at + WRONG_SHOWN, NOW, "e4-replay"); + assert_eq!(f.ui.session.remaining(), 5); + // Nf3: a hint, then the move. It comes back too. + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + assert!(f.ui.request_hint_with_id_at("nf3-hint".into(), at, NOW)); + assert_eq!(f.ui.state(), Some(State::Hint)); + answer_current(&mut f, at, NOW, "nf3-after-hint"); + assert_eq!(f.ui.session.remaining(), 5); + // Bb5 right; the new moves are shown and played. + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1b5")); + answer_current(&mut f, at, NOW, "bb5"); + assert_eq!(f.ui.session.remaining(), 4); + for _ in 0..2 { + f.ui.debug_settle(); + assert_eq!(f.ui.state(), Some(State::New)); + let uci = f.ui.session.current_expected_uci().unwrap().to_owned(); + answer_current(&mut f, at, NOW, &format!("new-{uci}")); + } + assert_eq!(f.ui.session.remaining(), 2); + // The returned two, answered right this time. + for expected in ["e2e4", "g1f3"] { + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some(expected)); + answer_current(&mut f, at, NOW, &format!("again-{expected}")); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.state(), Some(State::Summary)); + let tally = &f.ui.tally; + assert_eq!( + ( + tally.first_time, + tally.mistakes, + tally.hints, + tally.new_moves + ), + (1, 1, 1, 2) + ); + assert_eq!( + tally + .missed + .iter() + .map(|target| target.key.expected_uci.as_str()) + .collect::>(), + ["e2e4", "g1f3"] + ); + let independent = f + .attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(); + // e4 wrong, e4 right, Nf3 right, Bb5 right. + assert_eq!(independent, 4); + f.ui.compute_summary(); + let summary = f.ui.summary.as_ref().unwrap(); + assert_eq!(summary.more_new, 0); + assert!(!summary.next_review.is_empty()); + // A finished session shows no «0 left». + assert_eq!(f.ui.counter(&State::Summary).0, ""); +} + +#[test] +fn leaving_keeps_every_answer_and_shows_what_was_done() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "leave", + ); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + // Nothing answered: straight back, no question. + let mut early = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "leave-early"); + tick_with_prime(&mut early.ui, Instant::now(), Duration::ZERO, NOW); + screen_frame(&mut early.ui, &ctx, size, Vec::new()); + let (actions, _) = screen_frame(&mut early.ui, &ctx, size, vec![key(Key::Escape)]); + assert!(matches!(actions.as_slice(), [SessionAction::Back])); + // One answer: the result, «Session stopped», and the answer is in the store. + answer_current(&mut f, Instant::now(), NOW, "leave-e4"); + screen_frame(&mut f.ui, &ctx, size, Vec::new()); + let (actions, _) = screen_frame(&mut f.ui, &ctx, size, vec![key(Key::Escape)]); + assert!( + actions + .iter() + .all(|action| !matches!(action, SessionAction::Back)) + ); + screen_frame(&mut f.ui, &ctx, size, Vec::new()); + assert_eq!(f.ui.shown_state, State::Summary); + assert_eq!( + f.ui.card_texts(&State::Summary, true).0, + tr("Session stopped") + ); + assert_eq!(f.ui.counter(&State::Summary).0, "1"); + assert!(!f.ui.can_input()); + let before = f.attempts().len(); + let (actions, _) = screen_frame(&mut f.ui, &ctx, size, vec![key(Key::Enter)]); + assert!(matches!(actions.as_slice(), [SessionAction::Back])); + assert_eq!(f.attempts().len(), before); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type == TrainingEventType::CorrectIndependent) + .count(), + 1 + ); +} + +#[test] +fn skip_puts_the_question_at_once_and_records_the_moves_shown() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 *", + LearningSide::White, + &["f1b5"], + "skip", + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert_eq!(f.ui.state(), Some(State::Watch)); + assert_eq!(f.ui.visual_log, ["e2e4"]); + assert!(f.ui.skip_context(at)); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.can_input()); + assert_eq!(f.ui.state(), Some(State::Yours)); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1b5")); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 4); + assert!( + attempts + .iter() + .all(|attempt| attempt.event_type == TrainingEventType::AutoContext) + ); + assert_eq!( + fen4(&f.ui.board_position), + key_for(&f.library, &f.scope, "f1b5").position_fen4 + ); + assert_eq!(f.ui.visual_log, ["e2e4"], "skipped moves are not animated"); +} + +#[test] +fn correct_stays_six_hundred_ms_after_the_move() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "feedback", + ); + f.ui.feedback = FEEDBACK; + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "feedback-e4".into(), at, NOW)); + assert_eq!(f.ui.playback_deadline(), Some(at + normal() + FEEDBACK)); + f.ui.tick_at(at + normal(), normal(), NOW); + assert_eq!(f.ui.state(), Some(State::Correct)); + f.ui.tick_at(at + normal() + FEEDBACK, normal(), NOW); + assert_ne!(f.ui.state(), Some(State::Correct)); +} + +#[test] +fn ten_more_new_continues_the_finished_session_with_new_moves_only() { + let moves = [ + "Nf3", "Nf6", "g3", "g6", "Bg2", "Bg7", "O-O", "O-O", "d3", "d6", "e4", "e5", "Nc3", "Nc6", + "a3", "a6", "h3", "h6", "Be3", "Be6", "Qd2", "Qd7", "Rab1", "Rab8", "b4", "b5", + ]; + let mut pgn = String::new(); + for (index, pair) in moves.chunks(2).enumerate() { + pgn.push_str(&format!("{}. {} {} ", index + 1, pair[0], pair[1])); + } + pgn.push('*'); + let mut f = Fixture::with( + &pgn, + LearningSide::White, + &[], + &[ + "g1f3", "g2g3", "f1g2", "e1g1", "d2d3", "e2e4", "b1c3", "a2a3", "h2h3", "c1e3", "d1d2", + "a1b1", "b2b4", + ], + "more-new", + SessionKind::Daily, + ); + assert_eq!(f.ui.session.remaining(), layout::NEW_PER_SESSION); + for index in 0..layout::NEW_PER_SESSION { + f.ui.debug_settle(); + assert_eq!(f.ui.state(), Some(State::New), "move {index}"); + answer_current(&mut f, Instant::now(), NOW, &format!("more-{index}")); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + f.ui.compute_summary(); + assert_eq!(f.ui.more_new_count(), 3); + let snapshot = f.ui.snapshot().clone(); + let mut more = + OpeningSessionUi::more_new(f.library.clone(), f.store.clone(), snapshot, Color::Black) + .unwrap(); + assert_eq!(more.session.remaining(), 3); + assert_eq!(more.orientation(), Color::Black); + assert_eq!(more.session.id(), f.ui.session.id()); + more.synchronous_commits = true; + more.board_shown = true; + more.debug_settle(); + assert_eq!(more.state(), Some(State::New)); + assert_eq!(more.session.current_expected_uci(), Some("d1d2")); +} + +#[test] +fn a_review_counts_lines_and_announces_the_next_one() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 (2. Bc4) *", + LearningSide::White, + &[], + &[], + "review-lines", + SessionKind::ReviewAll, + ); + assert_eq!(f.ui.lines.len(), 2); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert_eq!(f.ui.counter(&State::Yours).0, "1/2"); + answer_current(&mut f, Instant::now(), NOW, "review-e4"); + f.ui.debug_settle(); + let at = Instant::now(); + assert!(f.ui.play_uci_with_id_at("g1f3", "review-nf3".into(), at, NOW)); + // Bc4 is in the second line; its context starts again from the beginning. + f.ui.tick_at(at + Duration::from_secs(1), normal(), NOW); + assert!(f.ui.pending_automatic.is_some()); + assert_eq!(f.ui.line, 2); + assert!(f.ui.next_line_banner); + assert_eq!(f.ui.state(), Some(State::NextLine)); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1c4")); + answer_current(&mut f, Instant::now(), NOW, "review-bc4"); + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.counter(&State::Summary).0, "2/2"); + f.ui.compute_summary(); + assert_eq!(f.ui.more_new_count(), 0, "no «10 more new» after a review"); +} + +#[test] +fn a_new_session_never_resumes_an_unfinished_one() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "no-resume", + ); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + answer_current(&mut f, Instant::now(), NOW, "first-e4"); + let old = f.ui.session_id().to_owned(); + let again = OpeningSessionUi::new( + f.library.clone(), + f.store.clone(), + f.scope.clone(), + SessionKind::Daily, + ) + .unwrap(); + assert_ne!(again.session_id(), old); + // The unfinished snapshot is kept in the file, untouched. + let data = f.store.load().unwrap(); + assert!(data.session_snapshot(&old).is_some()); + assert_eq!(again.session.remaining(), 1); +} + +fn wait_for_commit(ui: &mut OpeningSessionUi) { + let deadline = Instant::now() + Duration::from_secs(5); + while ui.commit_in_flight.is_some() { + assert!(Instant::now() < deadline, "commit worker did not finish"); + ui.poll_commit(Instant::now()); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn async_commit_keeps_frames_responsive_under_store_lock_and_commits_once() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-lock"); + f.ui.synchronous_commits = false; + tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); + let lock_path = f.store.path().with_file_name("learning.json.lock"); + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(lock_path) + .unwrap(); + lock.lock().unwrap(); + let unlock = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(600)); + drop(lock); + }); + let start = Instant::now(); + assert!(f.ui.play_uci_with_id_at("e2e4", "async-answer".to_owned(), start, NOW)); + assert!( + start.elapsed() < Duration::from_millis(300), + "input waited for storage lock" + ); + assert!(f.ui.has_unsaved()); + assert!(f.ui.commit_in_flight.is_some()); + assert!(!f.ui.can_input()); + assert!( + !f.ui + .play_uci_with_id_at("e2e4", "async-answer".to_owned(), Instant::now(), NOW) + ); + f.ui.retry_pending(Instant::now()); + let ctx = egui::Context::default(); + let frame = Instant::now(); + ctx.run_ui(egui::RawInput::default(), |ui| { + f.ui.show(ui, &Settings::default(), "Test"); + }) + .drop_without_applying_deltas(); + assert!( + frame.elapsed() < Duration::from_millis(300), + "frame waited for storage lock" + ); + unlock.join().unwrap(); + wait_for_commit(&mut f.ui); + assert!(!f.ui.has_unsaved()); + assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); + assert_eq!(f.attempts().len(), 1); + let revision = f.ui.session.revision; + f.ui.poll_commit(Instant::now()); + f.ui.retry_pending(Instant::now()); + assert_eq!(f.ui.session.revision, revision); + assert_eq!(f.attempts().len(), 1); +} + +fn pointer_board_frame( + f: &mut Fixture, + ctx: &egui::Context, + time: f64, + events: Vec, + settings: &Settings, +) -> egui::FullOutput { + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(800.0, 800.0), + )), + time: Some(time), + events, + ..Default::default() + }, + |ui| f.ui.board_ui(ui, settings), + ); + output.textures_delta.clear(); + output +} + +fn piece_meshes(output: &egui::FullOutput) -> Vec<(egui::TextureId, egui::Rect)> { + fn collect(shape: &egui::Shape, meshes: &mut Vec<(egui::TextureId, egui::Rect)>) { + match shape { + egui::Shape::Mesh(mesh) => meshes.push((mesh.texture_id, mesh.calc_bounds())), + egui::Shape::Rect(rect) => { + if let Some(brush) = &rect.brush { + meshes.push((brush.fill_texture_id, rect.rect)); + } + } + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, meshes); + } + } + _ => {} + } + } + let mut meshes = Vec::new(); + for shape in &output.shapes { + collect(&shape.shape, &mut meshes); + } + meshes +} + +fn pointer_button(pos: egui::Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + } +} + +#[test] +fn pointer_move_stays_at_destination_during_async_save_without_a_second_animation() { + for drag in [true, false] { + for wrong in [false, true] { + for animation in [ + crate::settings::Animation::Normal, + crate::settings::Animation::Off, + ] { + let mut f = + Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "pointer-pending"); + f.ui.synchronous_commits = false; + let settings = Settings { + animation, + ..Settings::default() + }; + let duration = Duration::from_secs_f32(animation.seconds()); + f.ui.tick_at(Instant::now(), duration, NOW); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let from = egui::pos2(450.0, 650.0); + let to = egui::pos2(450.0, if wrong { 550.0 } else { 450.0 }); + let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); + let pawn = piece_meshes(&initial) + .into_iter() + .find(|(_, rect)| rect.contains(from)) + .expect("painted pawn at e2") + .0; + initial.drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.01, + vec![egui::Event::PointerMoved(from), pointer_button(from, true)], + &settings, + ) + .drop_without_applying_deltas(); + if drag { + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![egui::Event::PointerMoved(to)], + &settings, + ) + .drop_without_applying_deltas(); + } else { + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![pointer_button(from, false)], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.03, + vec![egui::Event::PointerMoved(to), pointer_button(to, true)], + &settings, + ) + .drop_without_applying_deltas(); + } + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.store.path().with_file_name("learning.json.lock")) + .unwrap(); + lock.lock().unwrap(); + let released = pointer_board_frame( + &mut f, + &ctx, + 1.04, + vec![pointer_button(to, false)], + &settings, + ); + let assert_pawn_at_destination = |output: &egui::FullOutput| { + let meshes = piece_meshes(output); + assert!( + meshes + .iter() + .any(|(texture, rect)| *texture == pawn && rect.contains(to)), + "pawn not painted at destination" + ); + assert!( + !meshes + .iter() + .any(|(texture, rect)| *texture == pawn && rect.contains(from)), + "pawn snapped back to e2" + ); + }; + assert!(f.ui.has_unsaved(), "drag={drag} wrong={wrong}"); + assert!(!f.ui.can_input()); + assert!(f.ui.pending_sounds.is_empty()); + if drag { + assert_pawn_at_destination(&released); + } + released.drop_without_applying_deltas(); + let frame = Instant::now(); + let waiting = pointer_board_frame(&mut f, &ctx, 1.05, vec![], &settings); + assert!(frame.elapsed() < Duration::from_millis(300)); + if drag { + assert_pawn_at_destination(&waiting); + assert!( + f.ui.board + .animation_at(1.05) + .is_none_or(|(_, slides, _)| slides.is_empty()) + ); + } else if !duration.is_zero() { + assert!( + f.ui.board + .animation_at(1.05) + .unwrap() + .1 + .iter() + .any(|(_, source, _)| *source == Square::E2), + "click move must still animate" + ); + } + waiting.drop_without_applying_deltas(); + let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); + assert_pawn_at_destination(&waiting); + waiting.drop_without_applying_deltas(); + assert!( + f.ui.learning.attempts.is_empty(), + "unconfirmed answer affected learning data" + ); + drop(lock); + wait_for_commit(&mut f.ui); + let confirmed = pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings); + assert_pawn_at_destination(&confirmed); + confirmed.drop_without_applying_deltas(); + assert!( + f.ui.board.animation_at(2.01).is_none(), + "commit restarted the move animation" + ); + assert_eq!(f.attempts().len(), 1); + assert_eq!( + f.ui.pending_sounds, + [if wrong { Sound::Wrong } else { Sound::Move }] + ); + if wrong { + f.ui.tick_at(f.ui.playback_deadline().unwrap(), duration, NOW); + pointer_board_frame(&mut f, &ctx, 2.02, vec![], &settings) + .drop_without_applying_deltas(); + assert_eq!(fen4(&f.ui.board_position), fen4(&Chess::default())); + if !duration.is_zero() { + assert!( + f.ui.board + .animation_at(2.02) + .unwrap() + .1 + .iter() + .any(|(_, _, target)| *target == Square::E2), + "wrong move must return to source" + ); + } + } + } + } + } +} + +#[test] +fn dragged_special_moves_keep_auxiliary_effects_and_retry_does_not_move_again() { + let cases = [ + ( + "4k3/8/8/8/8/8/8/4K2R w K - 0 1", + "O-O", + "e1g1", + Square::E1, + Square::G1, + None, + false, + ), + ( + "4k3/8/8/3p4/4P3/8/8/4K3 w - - 0 1", + "exd5", + "e4d5", + Square::E4, + Square::D5, + Some(Square::D5), + false, + ), + ( + "4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", + "exd6", + "e5d6", + Square::E5, + Square::D6, + Some(Square::D5), + false, + ), + ( + "4k3/P7/8/8/8/8/8/4K3 w - - 0 1", + "a8=Q+", + "a7a8q", + Square::A7, + Square::A8, + None, + true, + ), + ]; + let center = |sq: Square| { + egui::pos2( + (u32::from(sq.file()) as f32 + 0.5) * 100.0, + (7.5 - u32::from(sq.rank()) as f32) * 100.0, + ) + }; + for (fen, san, uci, from, to, captured, promotion) in cases { + let pgn = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *"); + let mut f = Fixture::new(&pgn, LearningSide::White, &[uci], "special-drag"); + f.ui.synchronous_commits = false; + f.ui.tick_at(Instant::now(), normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let settings = Settings::default(); + let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); + let captured_texture = captured.map(|sq| { + piece_meshes(&initial) + .into_iter() + .find(|(_, rect)| rect.contains(center(sq))) + .unwrap() + .0 + }); + initial.drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.01, + vec![ + egui::Event::PointerMoved(center(from)), + pointer_button(center(from), true), + ], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![egui::Event::PointerMoved(center(to))], + &settings, + ) + .drop_without_applying_deltas(); + let released = pointer_board_frame( + &mut f, + &ctx, + 1.03, + vec![pointer_button(center(to), false)], + &settings, + ); + if uci == "e1g1" { + let (_, slides, _) = f.ui.board.animation_at(1.03).unwrap(); + assert_eq!(slides.len(), 1); + assert_eq!( + (slides[0].1, slides[0].2), + (Square::H1, Square::F1), + "only the rook should animate after a dragged castle" + ); + } + if let Some(texture) = captured_texture { + assert!( + piece_meshes(&released) + .iter() + .any(|(id, rect)| *id == texture && rect.contains(center(captured.unwrap()))), + "captured piece must still fade out" + ); + } + released.drop_without_applying_deltas(); + if promotion { + assert!( + !f.ui.has_unsaved(), + "promotion must wait for the chosen piece" + ); + pointer_board_frame( + &mut f, + &ctx, + 1.04, + vec![pointer_button(center(to), true)], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.05, + vec![pointer_button(center(to), false)], + &settings, + ) + .drop_without_applying_deltas(); + assert_eq!( + f.ui.board_position.board().piece_at(to).unwrap().role, + chess_core::shakmaty::Role::Queen + ); + } + assert!(f.ui.has_unsaved()); + let after = fen4(&f.ui.board_position); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(f.attempts().is_empty()); + assert!(f.ui.pending_sounds.is_empty()); + pointer_board_frame(&mut f, &ctx, 1.1, vec![], &settings).drop_without_applying_deltas(); + let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); + if let Some(texture) = captured_texture { + assert!( + !piece_meshes(&waiting) + .iter() + .any(|(id, rect)| *id == texture && rect.contains(center(captured.unwrap()))) + ); + } + waiting.drop_without_applying_deltas(); + f.ui.store = valid_store; + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings).drop_without_applying_deltas(); + assert_eq!(fen4(&f.ui.board_position), after); + assert!(f.ui.board.animation_at(2.01).is_none()); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.ui.pending_sounds, [Sound::Move]); + } +} + +#[test] +fn reused_context_retry_stays_silent_and_responsive_and_persists_once() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["e2e4", "g1f3"], + "reuse-retry", + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "own-answer".into(), at, NOW)); + let position = fen4(&f.ui.board_position); + assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); + let valid_store = f.ui.store.clone(); + f.ui.synchronous_commits = false; + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + f.ui.tick_at(at + normal(), normal(), NOW); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(matches!( + f.ui.pending_commit.as_ref().unwrap().kind, + CommitKind::ReusedContext + )); + let reused_id = f.ui.pending_commit.as_ref().unwrap().attempts[0] + .client_attempt_id + .clone(); + assert_eq!(fen4(&f.ui.board_position), position); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.store = valid_store; + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.store.path().with_file_name("learning.json.lock")) + .unwrap(); + lock.lock().unwrap(); + let unlock = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(600)); + drop(lock); + }); + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + let frame = Instant::now(); + assert!(emitted_sounds(&mut f, &egui::Context::default(), &Settings::default()).is_empty()); + assert!( + frame.elapsed() < Duration::from_millis(300), + "reused context blocked the frame" + ); + assert_eq!(fen4(&f.ui.board_position), position); + assert!(!f.ui.can_input()); + unlock.join().unwrap(); + wait_for_commit(&mut f.ui); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.debug_settle(); + assert_eq!(f.ui.visual_log, ["e7e5"]); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 3); + assert_eq!( + attempts + .iter() + .filter(|event| event.client_attempt_id == reused_id) + .count(), + 1 + ); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type.is_independent()) + .count(), + 1 + ); +} + +#[test] +fn async_failed_commit_preserves_event_for_retry_without_double_counting() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-retry"); + f.ui.synchronous_commits = false; + tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + assert!(f.ui.play_uci_with_id_at("e2e4", "async-retry".to_owned(), Instant::now(), NOW)); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(f.ui.has_unsaved()); + assert!(f.attempts().is_empty()); + f.ui.store = valid_store; + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + assert!(!f.ui.has_unsaved()); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].client_attempt_id, "async-retry"); +} + +#[test] +fn a_mistake_on_the_first_move_returns_it_once_and_keeps_the_count() { + // The next daily session after learning new moves: the learned e4 is due again + // today, Nf3 and Bb5 are still new. The count is due + new, and a mistake on the + // first move does not grow it. + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 *"; + let mut f = Fixture::with( + pgn, + LearningSide::White, + &["e2e4"], + &["g1f3", "f1b5"], + "first-move-wrong", + SessionKind::Daily, + ); + let at = Instant::now(); + assert_eq!(f.ui.session.remaining(), 3); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.ui.play_uci_with_id_at("d2d4", "e4-wrong".into(), at, NOW)); + tick_with_prime(&mut f.ui, at + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.state(), Some(State::Wrong)); + assert_eq!(f.ui.session.remaining(), 3); + answer_current(&mut f, at + WRONG_SHOWN, NOW, "e4-replay"); + assert_eq!(f.ui.session.remaining(), 3); + let mut asked = Vec::new(); + for _ in 0..4 { + f.ui.debug_settle(); + let Some(uci) = f.ui.session.current_expected_uci().map(str::to_owned) else { + break; + }; + answer_current(&mut f, at, NOW, &format!("again-{uci}-{}", asked.len())); + asked.push(uci); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(asked, ["g1f3", "f1b5", "e2e4"]); + assert_eq!(f.ui.session.remaining(), 0); + f.ui.compute_summary(); + let summary = f.ui.summary.as_ref().unwrap(); + assert_eq!((summary.unseen, summary.more_new), (0, 0)); + assert!(!summary.next_review.is_empty()); +} + +#[test] +fn the_summary_shows_learning_growth_when_nothing_is_learned_yet() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &[], + &["e2e4", "g1f3"], + "summary-learning", + SessionKind::Daily, + ); + for _ in 0..2 { + f.ui.debug_moves("answer"); + f.ui.debug_settle(); + } + assert!(f.ui.is_finished()); + f.ui.compute_summary(); + let summary = f.ui.summary.as_ref().unwrap(); + assert_eq!((summary.passed_gain, summary.consolidated_gain), (2, 0)); +} + +#[test] +fn the_line_shows_the_moves_to_the_board_without_the_asked_or_a_wrong_move() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 *", + LearningSide::White, + &["e2e4", "g1f3", "f1b5"], + &[], + "path-line", + SessionKind::Daily, + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + assert_eq!(f.ui.path_text(), ""); + answer_current(&mut f, at, NOW, "e4"); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + assert_eq!(f.ui.path_text(), "1. e4 e5"); + assert!(f.ui.play_uci_with_id_at("d2d4", "nf3-wrong".into(), at, NOW)); + assert_eq!(f.ui.path_text(), "1. e4 e5"); + tick_with_prime(&mut f.ui, at + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.path_text(), "1. e4 e5"); +} diff --git a/apps/desktop/src/own_db.rs b/apps/desktop/src/own_db.rs new file mode 100644 index 0000000..7b86c65 --- /dev/null +++ b/apps/desktop/src/own_db.rs @@ -0,0 +1,1032 @@ +//! The user's own databases (docs/design/own-databases.md): the dialogs of creating a +//! PGN database, choosing one to add a game to, the game's data, a duplicate, deleting +//! a game, a copy in UTF-8, errors of writing. Each dialog draws itself and tells what +//! was chosen; the flows between them live in `app.rs`. + +use std::path::{Path, PathBuf}; + +use chess_core::{Game, GameResult}; +use egui::{Key, RichText, Ui}; + +use crate::i18n::{tr, trf}; + +/// Files bigger than this are rewritten with a progress window and, once a session, +/// the advice to keep one's own games in a smaller database (§6.4). +pub const BIG_REWRITE_BYTES: u64 = 50 << 20; + +/// Why a database cannot take a game (§5). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Block { + /// Downloaded from Lichess and Chess.com: updating it would drop added games. + Online, + /// A ChessBase database or an archive: read only. + ReadOnly, + /// A sample database of the program: read only. + Example, + /// A PGN in another encoding: a UTF-8 copy can take games. + Encoding(&'static str), + /// The file cannot be written (permissions). + NoPermission, + /// The file is not on the disk any more. + Missing, +} + +impl Block { + /// The explanation when the user tries anyway. + pub fn long(&self) -> String { + match self { + Block::Online => tr("This database is downloaded from Lichess and Chess.com and updates itself: a game added by hand would be lost at the next update. Add the game to a database of your own.").to_owned(), + Block::ReadOnly => tr("ChessBase databases and archives are only read. Add the game to a PGN database of your own.").to_owned(), + Block::Encoding(enc) => trf("This file is in the {enc} encoding; games are written in UTF-8. Make a copy of it in UTF-8 and add games to the copy — the original stays as it is.", &[("enc", enc)]), + Block::Example => tr("This is a sample database of the program; it is only read. Make a database of your own for your games.").to_owned(), + Block::NoPermission => tr("The file cannot be written: no permission.").to_owned(), + Block::Missing => tr("The file is not on the disk any more.").to_owned(), + } + } +} + +/// The user's Documents folder (else the home folder). +pub fn documents_dir() -> PathBuf { + let dirs = directories::UserDirs::new(); + dirs.as_ref() + .and_then(|u| u.document_dir().map(Path::to_owned)) + .or_else(|| dirs.as_ref().map(|u| u.home_dir().to_owned())) + .unwrap_or_else(std::env::temp_dir) +} + +/// Where new databases go unless the user chose another folder. +pub fn default_base_dir(chosen: Option<&Path>) -> PathBuf { + chosen + .map(Path::to_owned) + .unwrap_or_else(|| documents_dir().join("ChessPenguin")) +} + +/// The name of a database as the shelf shows it: the file's stem. +pub fn base_name(path: &Path) -> String { + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +/// Characters a file name cannot have (on any of the three systems). +pub const FORBIDDEN: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|']; + +// --- New database ------------------------------------------------------------------------ + +/// What to do once the database is created. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AfterCreate { + /// Just put it on the shelf. + Shelf, + /// Add the current game to it (the chooser led here). + AddGame, + /// Add a copy of a record of a table to it. + AddRecord { path: PathBuf, index: usize }, + /// Copy the chosen records of a table into it, in the table's order (task 42): the + /// file is made by the copy, only when whole. + CopySelection { + path: PathBuf, + records: Vec, + sort: chess_import::chessbase::base::SortKey, + ascending: bool, + hidden: usize, + }, +} + +/// From this many chosen games on, the dialog says the copy may take a while. +const MANY_GAMES: usize = 50_000; + +pub struct NewBaseDialog { + pub name: String, + pub dir: PathBuf, + pub after: AfterCreate, + /// Creating the file failed: said under the name, the dialog stays open. + pub error: Option, + focus: bool, +} + +pub enum NewBaseOutcome { + Create(PathBuf), + /// The file exists: put it on the shelf as it is. + AddExisting(PathBuf), + PickFolder, + Cancel, +} + +impl NewBaseDialog { + pub fn new(dir: PathBuf, after: AfterCreate) -> Self { + Self { + name: String::new(), + dir, + after, + error: None, + focus: true, + } + } + + /// The name as typed, without a ".pgn" the user may have added. + fn stem(&self) -> &str { + let name = self.name.trim(); + match name.get(name.len().saturating_sub(4)..) { + Some(ext) if ext.eq_ignore_ascii_case(".pgn") => name[..name.len() - 4].trim_end(), + _ => name, + } + } + + pub fn path(&self) -> PathBuf { + self.dir.join(format!("{}.pgn", self.stem())) + } + + /// What is wrong with the name, if anything; `Ok(true)` when a file with this name + /// exists already. + fn check(&self) -> Result { + let name = self.stem(); + if name.is_empty() { + return Err(String::new()); + } + if name.contains(FORBIDDEN) || name.chars().all(|c| c == '.') { + return Err(tr("A name cannot have / \\ : * ? \" < > |").to_owned()); + } + Ok(self.path().exists()) + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("new_base")).show(ctx, |ui| { + ui.set_width(440.0); + ui.heading(tr("New database")); + let copy = matches!(self.after, AfterCreate::CopySelection { .. }); + if let AfterCreate::CopySelection { + path, + records, + hidden, + .. + } = &self.after + { + let weak = |ui: &mut egui::Ui, text: String| { + ui.add(egui::Label::new(RichText::new(text).weak()).truncate()); + }; + weak( + ui, + trf( + "From the selection: {games} from «{src}»", + &[ + ("games", &crate::i18n::games(records.len())), + ("src", &base_name(path)), + ], + ), + ); + if *hidden > 0 { + weak( + ui, + trf("{k} of them are hidden by the filter now", &[("k", hidden)]), + ); + } + if records.len() >= MANY_GAMES { + weak( + ui, + tr("Many games: writing may take a few minutes; you can cancel it") + .to_owned(), + ); + } + } + ui.add_space(8.0); + ui.label(tr("Title")); + let check = self.check(); + let mut edit = egui::TextEdit::singleline(&mut self.name) + .hint_text(tr("e.g. Petrov, My games, Sicilian")) + .desired_width(f32::INFINITY); + if matches!(&check, Err(e) if !e.is_empty()) { + edit = edit.text_color(ui.visuals().error_fg_color); + } + let edit = ui.add(edit); + if edit.changed() { + self.error = None; + } + if std::mem::take(&mut self.focus) { + edit.request_focus(); + } + ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tr("File:")).weak()); + // The folder alone until a name is typed. + let shown = if self.name.trim().is_empty() { + format!("{}{}", self.dir.display(), std::path::MAIN_SEPARATOR) + } else { + self.path().display().to_string() + }; + ui.label(RichText::new(shown).weak()); + }); + // On a line of its own: typing the name does not move it. + if ui.small_button(tr("Change folder…")).clicked() { + out = Some(NewBaseOutcome::PickFolder); + } + match &check { + Err(e) if !e.is_empty() => { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + Ok(true) => { + ui.label( + RichText::new(tr("A file with this name is already there.")) + .color(ui.visuals().warn_fg_color), + ); + } + _ => {} + } + if let Some(e) = &self.error { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let enter = ui.input(|i| i.key_pressed(Key::Enter)); + match &check { + Ok(false) => { + let label = if copy { + tr("Create and copy") + } else { + tr("Create") + }; + if crate::widgets::primary(ui, label).clicked() || enter { + out = Some(NewBaseOutcome::Create(self.path())); + } + } + // The copy goes into a new file only: the one there is not touched. + Ok(true) if copy => { + ui.add_enabled_ui(false, |ui| { + crate::widgets::primary(ui, tr("Create and copy")) + }); + } + Ok(true) => { + if crate::widgets::primary(ui, tr("Put it on the shelf")).clicked() + || enter + { + out = Some(NewBaseOutcome::AddExisting(self.path())); + } + } + // The same main button, only disabled: the row does not jump + // when the first letter is typed. + Err(_) => { + let label = if copy { + tr("Create and copy") + } else { + tr("Create") + }; + ui.add_enabled_ui(false, |ui| crate::widgets::primary(ui, label)); + } + } + if ui.button(tr("Cancel")).clicked() { + out = Some(NewBaseOutcome::Cancel); + } + }); + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(NewBaseOutcome::Cancel); + } + out + } +} + +// --- Add to database -------------------------------------------------------------------- + +/// A database on the shelf, as the chooser lists it. +pub struct ChooserRow { + pub path: PathBuf, + pub name: String, + /// `None`: not read yet (its encoding is not known either). + pub games: Option, + pub block: Option, +} + +impl ChooserRow { + /// Read, and nothing blocks it: can be chosen. + pub fn takes_games(&self) -> bool { + self.games.is_some() && self.block.is_none() + } +} + +/// What the chooser is for: the game on the screen, or a record of a table. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ChooserFor { + CurrentGame, + Record { path: PathBuf, index: usize }, +} + +pub struct Chooser { + pub rows: Vec, + pub selected: Option, + pub search: String, + pub purpose: ChooserFor, + /// The game's title, for the heading. + pub title: String, + focus: bool, +} + +pub enum ChooserOutcome { + Pick(PathBuf), + NewBase, + SaveAsFile, + Cancel, +} + +impl Chooser { + pub fn new( + rows: Vec, + preselect: Option<&Path>, + purpose: ChooserFor, + title: String, + ) -> Self { + let selected = preselect + .and_then(|p| rows.iter().position(|r| r.path == p && r.takes_games())) + .or_else(|| rows.iter().position(ChooserRow::takes_games)); + Self { + rows, + selected, + search: String::new(), + purpose, + title, + focus: true, + } + } + + /// The shelf as it is now (databases get read while the dialog is open): the + /// chosen row stays chosen by its path. + pub fn refresh(&mut self, rows: Vec) { + let chosen = self + .selected + .and_then(|i| self.rows.get(i)) + .map(|r| r.path.clone()); + self.rows = rows; + self.selected = chosen + .and_then(|p| { + self.rows + .iter() + .position(|r| r.path == p && r.takes_games()) + }) + .or_else(|| self.rows.iter().position(ChooserRow::takes_games)); + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("add_to_base")).show(ctx, |ui| { + ui.set_width(440.0); + ui.heading(tr("Add to database")); + if !self.title.is_empty() { + ui.label(RichText::new(&self.title).weak()); + } + ui.add_space(6.0); + // The field that narrows the list, for a long list only (of the databases + // offered, not of the whole shelf). + let many = self.rows.iter().filter(|r| r.block.is_none()).count() > 8; + if many { + let edit = ui.add( + egui::TextEdit::singleline(&mut self.search) + .hint_text(tr("ðŸ”� Find a database")) + .desired_width(f32::INFINITY), + ); + if std::mem::take(&mut self.focus) { + edit.request_focus(); + } + } + let needle = self.search.trim().to_lowercase(); + let shown: Vec = (0..self.rows.len()) + .filter(|&i| { + needle.is_empty() || self.rows[i].name.to_lowercase().contains(&needle) + }) + .collect(); + // Only the databases that take games, in shelf order; those still being read + // after them (they may turn out to take games). Online, ChessBase, legacy + // encodings, read-only files are not offered at all. + let order: Vec = shown + .iter() + .copied() + .filter(|&i| self.rows[i].takes_games()) + .chain(shown.iter().copied().filter(|&i| { + let r = &self.rows[i]; + r.block.is_none() && r.games.is_none() + })) + .collect(); + 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 writable: Vec = order + .iter() + .copied() + .filter(|&i| self.rows[i].takes_games()) + .collect(); + let pos = self + .selected + .and_then(|s| writable.iter().position(|&i| i == s)); + let next = match (pos, down) { + (None, _) => 0, + (Some(p), true) => (p + 1).min(writable.len().saturating_sub(1)), + (Some(p), false) => p.saturating_sub(1), + }; + self.selected = writable.get(next).copied(); + } + egui::ScrollArea::vertical() + .max_height(320.0) + .show(ui, |ui| { + if order.is_empty() { + ui.label( + RichText::new(tr("No databases of your own yet: create one below.")) + .weak(), + ); + } + // Rows the whole width, their text from the left. + ui.with_layout(egui::Layout::top_down_justified(egui::Align::Min), |ui| { + for i in order { + let row = &self.rows[i]; + let selected = self.selected == Some(i); + let text = match row.games { + Some(n) => format!("{} · {}", row.name, crate::i18n::games(n)), + None => format!("{} · {}", row.name, tr("reading…")), + }; + let folder = row + .path + .parent() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + match (&row.block, row.games) { + (None, Some(_)) => { + let resp = ui + .add(egui::Button::selectable(selected, text)) + .on_hover_text(&folder); + if resp.clicked() { + self.selected = Some(i); + } + if resp.double_clicked() { + out = Some(ChooserOutcome::Pick(row.path.clone())); + } + } + (None, None) => { + ui.label(RichText::new(text).weak()); + } + (Some(_), _) => {} + } + } + }); + }); + ui.separator(); + // Nothing to choose: the new database is the main way, not «Add». + let none = !self.rows.iter().any(|r| r.block.is_none()); + let new_base = if none { + crate::widgets::primary(ui, tr("✚ New database…")) + } else { + ui.button(tr("✚ New database…")) + }; + if new_base.clicked() || (none && ui.input(|i| i.key_pressed(Key::Enter))) { + out = Some(ChooserOutcome::NewBase); + } + if self.purpose == ChooserFor::CurrentGame + && ui + .button(tr("Save as a file…")) + .on_hover_text(tr( + "A separate PGN file with this game only; it is not put on the shelf", + )) + .clicked() + { + out = Some(ChooserOutcome::SaveAsFile); + } + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let pick = self.selected.map(|i| self.rows[i].path.clone()); + if !none { + let add = ui + .add_enabled_ui(pick.is_some(), |ui| crate::widgets::primary(ui, tr("Add"))) + .inner; + if (add.clicked() || enter) + && let Some(p) = pick + { + out = Some(ChooserOutcome::Pick(p)); + } + } + if ui.button(tr("Cancel")).clicked() { + out = Some(ChooserOutcome::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(ChooserOutcome::Cancel); + } + out + } +} + +// --- Game data -------------------------------------------------------------------------- + +/// What the main button of the editor does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EditorMode { + /// Changes the game (Ctrl+S saves them). + Done, + /// Then the game is added to this database. + Add(PathBuf), +} + +pub struct DataEditor { + pub white: String, + pub white_elo: String, + pub black: String, + pub black_elo: String, + pub event: String, + pub site: String, + pub date: String, + pub round: String, + pub result: GameResult, + pub annotator: String, + /// The tags the editor does not show (kept as they are). + pub others: Vec, + pub mode: EditorMode, + /// The fields as the editor opened (nothing changed: nothing written). + initial: String, + focus: bool, +} + +pub enum EditorOutcome { + Done, + Cancel, +} + +fn shown(value: Option<&str>) -> String { + value + .filter(|v| !v.is_empty() && !v.chars().all(|c| c == '?' || c == '.')) + .unwrap_or("") + .to_owned() +} + +impl DataEditor { + pub fn from_game(game: &Game, your_name: &str, mode: EditorMode) -> Self { + let t = |n: &str| shown(game.tag(n)); + let known = [ + "Event", + "Site", + "Date", + "Round", + "White", + "Black", + "Result", + "WhiteElo", + "BlackElo", + "Annotator", + "FEN", + "SetUp", + "PlyCount", + ]; + let others: Vec = game + .tags() + .iter() + .filter(|(k, _)| !known.contains(&k.as_str())) + .map(|(k, _)| k.clone()) + .collect(); + let annotator = { + let a = t("Annotator"); + if a.is_empty() && game.tag("Annotator").is_none() { + your_name.to_owned() + } else { + a + } + }; + let mut editor = Self { + white: t("White"), + white_elo: t("WhiteElo"), + black: t("Black"), + black_elo: t("BlackElo"), + event: t("Event"), + site: t("Site"), + date: t("Date"), + round: t("Round"), + result: game.result(), + annotator, + others, + mode, + initial: String::new(), + focus: true, + }; + editor.initial = editor.state(); + editor + } + + fn state(&self) -> String { + [ + &self.white, + &self.white_elo, + &self.black, + &self.black_elo, + &self.event, + &self.site, + &self.date, + &self.round, + &self.annotator, + ] + .iter() + .map(|s| s.trim()) + .collect::>() + .join("\u{1}") + + self.result.as_str() + } + + /// Something was edited. + pub fn changed(&self) -> bool { + self.state() != self.initial + } + + fn date_ok(&self) -> bool { + chess_core::pgn::store::pgn_date(&self.date).is_some() + } + + /// Writes the fields into the game (empty fields as PGN's "?"). Opened and closed + /// without an edit, it writes nothing — unless the game is being added: then the + /// annotator and the standard tags go in. + pub fn apply(&self, game: &mut Game) { + if !self.changed() && self.mode == EditorMode::Done { + return; + } + let set = |game: &mut Game, name: &str, value: &str, unknown: &str| { + let v = value.trim(); + if v.is_empty() { + // A cleared field: the seven PGN tags say "?", an optional one goes away. + if unknown.is_empty() { + game.remove_tag(name); + } else if game.tag(name) != Some(unknown) { + game.set_tag(name, unknown); + } + } else if game.tag(name) != Some(v) { + game.set_tag(name, v); + } + }; + set(game, "White", &self.white, "?"); + set(game, "Black", &self.black, "?"); + set(game, "Event", &self.event, "?"); + set(game, "Site", &self.site, "?"); + set(game, "Round", &self.round, "?"); + let date = + chess_core::pgn::store::pgn_date(&self.date).unwrap_or_else(|| "????.??.??".to_owned()); + if game.tag("Date") != Some(date.as_str()) { + game.set_tag("Date", &date); + } + set(game, "WhiteElo", &self.white_elo, ""); + set(game, "BlackElo", &self.black_elo, ""); + set(game, "Annotator", &self.annotator, ""); + if game.result() != self.result { + game.set_result(self.result); + } + game.order_roster(); + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("game_data")).show(ctx, |ui| { + ui.set_width(460.0); + match &self.mode { + EditorMode::Done => ui.heading(tr("Game data")), + EditorMode::Add(p) => { + ui.heading(trf("Game data → «{name}»", &[("name", &base_name(p))])) + } + }; + ui.add_space(8.0); + let label_w = 90.0; + let field = |ui: &mut Ui, text: &mut String, hint: &str, width: f32| { + ui.add( + egui::TextEdit::singleline(text) + .hint_text(hint) + .desired_width(width), + ) + }; + let row = |ui: &mut Ui, label: &str, add: &mut dyn FnMut(&mut Ui)| { + ui.horizontal(|ui| { + ui.add_sized([label_w, 20.0], egui::Label::new(label)); + add(ui); + }); + }; + let wide = 460.0 - label_w - 24.0; + let mut first = None; + let elo_w = 56.0; + let elo_label = crate::game_view::text_width(ui, "Elo", egui::TextStyle::Body) + 16.0; + row(ui, tr("White"), &mut |ui| { + let r = field( + ui, + &mut self.white, + tr("Surname, Name"), + wide - elo_w - elo_label, + ); + first = Some(r); + ui.label("Elo"); + field(ui, &mut self.white_elo, "", elo_w); + }); + row(ui, tr("Black"), &mut |ui| { + field( + ui, + &mut self.black, + tr("Surname, Name"), + wide - elo_w - elo_label, + ); + ui.label("Elo"); + field(ui, &mut self.black_elo, "", elo_w); + }); + row(ui, tr("Event"), &mut |ui| { + field(ui, &mut self.event, "", wide); + }); + row(ui, tr("Site"), &mut |ui| { + field(ui, &mut self.site, "", wide); + }); + let date_ok = self.date_ok(); + row(ui, tr("Date"), &mut |ui| { + let mut edit = egui::TextEdit::singleline(&mut self.date) + .hint_text(tr("YYYY.MM.DD")) + .desired_width(120.0); + if !date_ok { + edit = edit.text_color(ui.visuals().error_fg_color); + } + ui.add(edit) + .on_hover_text(tr("2026.10.18, 18.10.2026, 2026.10, 2026 or empty")); + ui.add_space(8.0); + ui.label(tr("Round")); + field(ui, &mut self.round, "", 60.0); + }); + row(ui, tr("Result"), &mut |ui| { + for (r, label) in [ + (GameResult::WhiteWins, "1-0"), + (GameResult::Draw, "½-½"), + (GameResult::BlackWins, "0-1"), + (GameResult::Unknown, "*"), + ] { + ui.selectable_value(&mut self.result, r, label); + } + }); + row(ui, tr("Annotator"), &mut |ui| { + field(ui, &mut self.annotator, "", wide); + }); + if !self.others.is_empty() { + ui.add_space(4.0); + ui.label( + RichText::new(trf( + "Other tags stay as they are: {tags}", + &[("tags", &self.others.join(", "))], + )) + .weak(), + ); + } + if std::mem::take(&mut self.focus) + && let Some(r) = first + { + // White's name selected: typing replaces it. + r.request_focus(); + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { + let range = egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(self.white.chars().count()), + ); + state.cursor.set_char_range(Some(range)); + state.store(ui.ctx(), r.id); + } + } + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let label = match &self.mode { + EditorMode::Done => tr("Done").to_owned(), + EditorMode::Add(p) => trf("Add to «{name}»", &[("name", &base_name(p))]), + }; + let enter = ui.input(|i| i.key_pressed(Key::Enter)); + let ok = ui + .add_enabled_ui(date_ok, |ui| crate::widgets::primary(ui, &label)) + .inner; + if ok.clicked() || (enter && date_ok) { + out = Some(EditorOutcome::Done); + } + if ui.button(tr("Cancel")).clicked() { + out = Some(EditorOutcome::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(EditorOutcome::Cancel); + } + out + } +} + +// --- Small questions -------------------------------------------------------------------- + +/// "Yes / no / cancel" questions, each with its own heading, text and buttons. +pub struct Question { + pub kind: QuestionKind, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum QuestionKind { + /// The same game is in the target already (record `index`). + Duplicate { + target: PathBuf, + index: usize, + title: String, + }, + /// Delete record `index` of `path`. + Delete { + path: PathBuf, + index: usize, + title: String, + }, + /// Make a UTF-8 copy of `path` at `dest` and add the game to it. + Utf8Copy { + path: PathBuf, + dest: PathBuf, + encoding: &'static str, + }, + /// Writing failed. + WriteFailed { + path: PathBuf, + error: String, + deleting: bool, + }, + /// The file was changed by another program since it was read. + ChangedOnDisk { path: PathBuf, deleting: bool }, + /// The file is big: replacing a record rewrites it all. + BigBase { path: PathBuf, bytes: u64 }, +} + +/// What was chosen in a question, by its meaning. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Answer { + /// Replace the duplicate / delete / make the copy / retry / save anyway / reread. + Primary, + /// Add as a new game / add to another database. + Secondary, + Cancel, +} + +impl Question { + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("own_db_question")).show(ctx, |ui| { + ui.set_width(420.0); + let (heading, text, primary, secondary, cancel): (String, String, Option, Option, &str) = match &self.kind { + QuestionKind::Duplicate { target, index, title } => ( + tr("This game is already there").to_owned(), + trf("«{name}» already has this game: No. {n}, {title} — the same players, date and moves.", &[("title", title), ("name", &base_name(target)), ("n", &(index + 1))]), + Some(trf("Replace No. {n}", &[("n", &(index + 1))])), + Some(tr("Add as new").to_owned()), + tr("Cancel"), + ), + QuestionKind::Delete { path, index, title } => ( + tr("Delete the game from the database?").to_owned(), + trf("«{title}» (No. {n}) is removed from the file «{file}»; other databases are not touched. Undo is offered for a few seconds.", &[("title", title), ("n", &(index + 1)), ("file", &path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())]), + Some(tr("Delete").to_owned()), + None, + tr("Cancel"), + ), + QuestionKind::Utf8Copy { path, dest, encoding } => ( + tr("A copy in UTF-8").to_owned(), + trf("«{name}» is in the {enc} encoding, and games are written in UTF-8. A copy «{copy}» will be made next to it with all its games; the game is added to the copy, the original stays as it is.", &[("name", &base_name(path)), ("enc", encoding), ("copy", &dest.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())]), + Some(tr("Make the copy").to_owned()), + None, + tr("Cancel"), + ), + QuestionKind::WriteFailed { path, error, deleting } => ( + if *deleting { tr("Could not delete").to_owned() } else { tr("Could not save").to_owned() }, + format!("{}\n{}", path.display(), error), + Some(tr("Try again").to_owned()), + (!deleting).then(|| tr("Add to another database…").to_owned()), + tr("Close"), + ), + QuestionKind::ChangedOnDisk { path, deleting } => ( + tr("The file changed on disk").to_owned(), + if *deleting { + trf("«{name}» was changed by another program since it was read. Reread it and look again.", &[("name", &base_name(path))]) + } else { + trf("«{name}» was changed by another program since it was read. The game can be added to it as a new one; replacing a record in it would need a fresh read first.", &[("name", &base_name(path))]) + }, + if *deleting { Some(tr("Reread").to_owned()) } else { Some(tr("Add as new").to_owned()) }, + None, + tr("Cancel"), + ), + QuestionKind::BigBase { path, bytes } => ( + tr("A big database").to_owned(), + trf("«{name}» is {mb} MB: saving a game into it rewrites the whole file, which takes a while. Your own games are handier in a smaller database of their own.", &[("name", &base_name(path)), ("mb", &(bytes >> 20))]), + Some(tr("Save anyway").to_owned()), + Some(tr("Add to another database…").to_owned()), + tr("Cancel"), + ), + }; + ui.heading(heading); + ui.add_space(6.0); + ui.label(text); + ui.add_space(10.0); + // Replacing a record is never one Enter away: the duplicate question has no + // main button (own-databases.md §5.5). + let plain = matches!(self.kind, QuestionKind::Duplicate { .. }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let enter = !plain && ui.input(|i| i.key_pressed(Key::Enter)); + if let Some(p) = primary { + let clicked = if plain { + ui.add(egui::Button::new(&p).min_size(egui::vec2(0.0, 30.0))) + .clicked() + } else { + crate::widgets::primary(ui, &p).clicked() + }; + if clicked || enter { + out = Some(Answer::Primary); + } + } + if let Some(s) = secondary + && ui.button(s).clicked() + { + out = Some(Answer::Secondary); + } + if ui.button(cancel).clicked() { + out = Some(Answer::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(Answer::Cancel); + } + out + } +} + +/// Shows the file in the system's file manager. +pub fn show_in_folder(path: &Path) { + let path = path.to_path_buf(); + let _ = std::thread::Builder::new() + .name("show-in-folder".into()) + .spawn(move || { + #[cfg(target_os = "windows")] + { + let _ = std::process::Command::new("explorer") + .arg(format!("/select,{}", path.display())) + .spawn(); + } + #[cfg(target_os = "macos")] + { + let _ = std::process::Command::new("open") + .arg("-R") + .arg(&path) + .spawn(); + } + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + { + // The file manager selects the file when it can (the portal's ShowItems), + // else its folder opens. + let shown = std::process::Command::new("dbus-send") + .args([ + "--session", + "--print-reply", + "--dest=org.freedesktop.FileManager1", + "/org/freedesktop/FileManager1", + "org.freedesktop.FileManager1.ShowItems", + &format!("array:string:file://{}", path.display()), + "string:", + ]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()); + if !shown && let Some(dir) = path.parent() { + let _ = std::process::Command::new("xdg-open").arg(dir).spawn(); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn editor_writes_tags_and_result() { + let mut g = chess_core::parse_str("[Event \"?\"]\n[White \"?\"]\n\n1. e4 *\n").game; + let mut e = DataEditor::from_game(&g, "Coach", EditorMode::Done); + assert_eq!(e.annotator, "Coach"); + e.white = "Petrov, Ivan".into(); + e.white_elo = "1500".into(); + e.date = "18.10.2026".into(); + e.result = GameResult::WhiteWins; + e.apply(&mut g); + assert_eq!(g.tag("White"), Some("Petrov, Ivan")); + assert_eq!(g.tag("WhiteElo"), Some("1500")); + assert_eq!(g.tag("Date"), Some("2026.10.18")); + assert_eq!(g.tag("Black"), Some("?")); + assert_eq!(g.tag("Annotator"), Some("Coach")); + assert_eq!(g.result(), GameResult::WhiteWins); + // The seven standard tags first, in their order; Result among them. + let names: Vec<&str> = g.tags().iter().map(|(k, _)| k.as_str()).collect(); + assert_eq!( + &names[..7], + &["Event", "Site", "Date", "Round", "White", "Black", "Result"] + ); + assert_eq!(g.tag("Result"), Some("1-0")); + assert!(g.is_modified()); + // Nothing changed: the game is not marked modified again. + g.mark_saved(); + let e2 = DataEditor::from_game(&g, "Coach", EditorMode::Done); + e2.apply(&mut g); + assert!(!g.is_modified()); + } +} diff --git a/apps/desktop/src/platform/clipboard.rs b/apps/desktop/src/platform/clipboard.rs new file mode 100644 index 0000000..82c8cd3 --- /dev/null +++ b/apps/desktop/src/platform/clipboard.rs @@ -0,0 +1,50 @@ +//! Reading the clipboard on request («Paste PGN», «Paste a line»): at once on a +//! computer; in a browser asked of it (it may ask the user, and answers later). +//! Writing needs nothing of this: `egui::Context::copy_text` works everywhere. + +use std::sync::{Arc, Mutex}; + +/// A reading of the clipboard under way. +pub struct Reading { + text: Arc>>>, +} + +impl Reading { + /// The text once read (`Some(None)`: empty, refused or unavailable). + pub fn poll(&self) -> Option> { + self.text.lock().ok()?.take() + } +} + +/// Starts reading the clipboard's text; `ctx` is woken when it is there. +pub fn read_text(ctx: &egui::Context) -> Reading { + let text = Arc::new(Mutex::new(None)); + #[cfg(not(web))] + { + let _ = ctx; + let read = arboard::Clipboard::new() + .and_then(|mut c| c.get_text()) + .ok(); + if let Ok(mut t) = text.lock() { + *t = Some(read); + } + } + #[cfg(web)] + { + let (slot, ctx) = (text.clone(), ctx.clone()); + wasm_bindgen_futures::spawn_local(async move { + let read = match web_sys::window().map(|w| w.navigator().clipboard()) { + Some(c) => wasm_bindgen_futures::JsFuture::from(c.read_text()) + .await + .ok() + .and_then(|v| v.as_string()), + None => None, + }; + if let Ok(mut t) = slot.lock() { + *t = Some(read); + } + ctx.request_repaint(); + }); + } + Reading { text } +} diff --git a/apps/desktop/src/platform/files.rs b/apps/desktop/src/platform/files.rs new file mode 100644 index 0000000..a67d224 --- /dev/null +++ b/apps/desktop/src/platform/files.rs @@ -0,0 +1,475 @@ +//! The files the user opens and saves: the system's dialogs on a computer; in a +//! browser its file chooser, files dropped on the page, and downloads. A file the user +//! gives the page is only read (decisions «Веб-верÑ�иÑ�»): it gets a path of the page's +//! file tree for the session and is opened by that path like a file on a disk. Chrome +//! and Edge remember a chosen file for the next visit ([`super::web::remembered`]). + +use std::path::PathBuf; + +/// The extensions of the databases the program opens (both cases for the dialogs of +/// systems that tell them apart). +const DATABASES: [&str; 10] = [ + "pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z", +]; + +/// Databases a browser does not open: their files together larger than this (the +/// program for the computer opens them). +pub const TOO_BIG: u64 = 2_000_000_000; + +/// What the user chose or dropped: the databases to open, the ones left out because +/// they are too big for a browser (name, bytes of their files), the ChessBase +/// databases not all files of which were given (the name of their `.cbh`), whether a +/// chosen (or, on a computer, dropped) folder held no database, and the files dropped +/// on a computer's window that are no databases (their names). +#[derive(Debug, Default, PartialEq)] +pub struct Picked { + pub paths: Vec, + pub too_big: Vec<(String, u64)>, + pub incomplete: Vec, + pub empty_folder: bool, + pub unsupported: Vec, + /// Files dropped on a computer's window that are no longer there (their names). + pub missing: Vec, +} + +/// The files the user gave the page, made databases: the ChessBase ones of their +/// several files (`chess_import::group_chosen`), each kept for the session in a folder +/// of its own. Also the files of each database kept (its path, their places in +/// `files`), for the browser to remember. +#[cfg(web)] +pub(super) fn gather( + files: &[web_sys::File], + folder: bool, +) -> (Picked, Vec<(PathBuf, Vec)>) { + let names: Vec = files.iter().map(|f| f.name()).collect(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let chosen = chess_import::group_chosen(&refs, folder); + let mut picked = Picked { + incomplete: chosen.incomplete, + ..Picked::default() + }; + let mut kept = Vec::new(); + for db in chosen.databases { + let size: u64 = db.iter().map(|&i| files[i].size() as u64).sum(); + if size > TOO_BIG { + picked.too_big.push((names[db[0]].clone(), size)); + continue; + } + let path = super::web::vfs::add_opened(db.iter().map(|&i| files[i].clone()).collect()); + picked.paths.push(path.clone()); + kept.push((path, db)); + } + picked.empty_folder = folder + && picked.paths.is_empty() + && picked.too_big.is_empty() + && picked.incomplete.is_empty(); + (picked, kept) +} + +/// A ChessBase database's `.cbh` given without the files it cannot be read without +/// (a browser has only the files the user gave it). +pub fn chessbase_incomplete(path: &std::path::Path) -> bool { + #[cfg(web)] + { + let cbh = path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("cbh")); + cbh && super::web::vfs::database_files(path).is_ok_and(|files| { + !files + .iter() + .any(|(name, _)| name.to_lowercase().ends_with(".cbg")) + }) + } + #[cfg(not(web))] + { + let _ = path; + false + } +} + +/// How the user's file `path` is named to the user: on a computer its path, in a +/// browser its name (the page's own places, `/opened/…`, mean nothing to the user). +pub fn shown(path: &std::path::Path) -> String { + #[cfg(web)] + return path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + #[cfg(not(web))] + path.display().to_string() +} + +/// A file the browser holds for this visit only (one the user chose or dropped): after +/// a reload it is gone, the user chooses it again or keeps a copy. Never on a computer. +pub fn session_only(path: &std::path::Path) -> bool { + #[cfg(web)] + return path.starts_with(super::web::vfs::OPENED); + #[cfg(not(web))] + { + let _ = path; + false + } +} + +/// Keeps a copy of the session database `path` (all its files) in the browser's +/// storage, where it stays between visits; `then` gets the copy's path. Refused when +/// the browser gives the site too little room (the size and what is free, for the +/// message). +#[cfg(web)] +pub fn keep_copy(path: &std::path::Path, then: impl FnOnce(Result) + 'static) { + use wasm_bindgen::JsCast; + let parts = match super::web::vfs::database_files(path) { + Ok(p) => p, + Err(e) => return then(Err(KeepCopy::Failed(e.to_string()))), + }; + let need: u64 = parts + .iter() + .map(|(_, s)| match s.dyn_ref::() { + Some(b) => b.size() as u64, + None => js_sys::Reflect::get(s, &"length".into()) + .ok() + .and_then(|l| l.as_f64()) + .unwrap_or(0.0) as u64, + }) + .sum(); + if let Some(free) = super::storage_free() + && need + need / 10 > free + { + return then(Err(KeepCopy::NoRoom { need, free })); + } + // A folder of its own, as the database had: the names stay as they were. + let dir = super::data_dir() + .unwrap_or_default() + .join("copies") + .join((js_sys::Date::now() as u64).to_string()); + let first = dir.join(&parts[0].0); + wasm_bindgen_futures::spawn_local(async move { + for (name, source) in parts { + let bytes = match source.dyn_into::() { + Ok(blob) => match wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await { + Ok(buf) => js_sys::Uint8Array::new(&buf).to_vec(), + Err(e) => return then(Err(KeepCopy::Failed(format!("{e:?}")))), + }, + Err(array) => js_sys::Uint8Array::new(&array).to_vec(), + }; + if let Err(e) = super::fs::write_atomic(&dir.join(name), &bytes) { + return then(Err(KeepCopy::Failed(e.to_string()))); + } + } + then(Ok(first)); + }); +} + +/// Why no copy was kept. +#[cfg(web)] +pub enum KeepCopy { + NoRoom { need: u64, free: u64 }, + Failed(String), +} + +/// Asks the user for databases to open; `then` gets what was chosen (nothing when the +/// user cancelled). The dialog does not hold the screen: `then` comes later. +pub fn pick_databases(then: impl FnOnce(Picked) + Send + 'static) { + #[cfg(not(web))] + { + use crate::i18n::tr; + let _ = std::thread::Builder::new() + .name("dialog".into()) + .spawn(move || { + let picked = rfd::FileDialog::new() + .set_title(tr("Open database")) + .add_filter(tr("Chess databases"), &DATABASES) + .add_filter("PGN", &["pgn", "PGN"]) + .add_filter(tr("All files"), &["*"]) + .pick_files(); + then(Picked { + paths: picked.unwrap_or_default(), + ..Picked::default() + }); + }); + } + #[cfg(web)] + { + let extensions: Vec = DATABASES + .iter() + .step_by(2) + .map(|e| format!(".{e}")) + .collect(); + if super::web::remembered::supported() { + super::web::remembered::pick(&extensions, then); + } else { + super::web::page::pick_files(&extensions.join(","), move |files| { + then(gather(&files, false).0) + }); + } + } +} + +/// Asks the user for a database's folder (a ChessBase database is several files): its +/// databases are found by their files' names. Chrome and Edge remember the folder. +#[cfg(web)] +pub fn pick_database_folder(then: impl FnOnce(Picked) + Send + 'static) { + if super::web::remembered::supported_folder() { + super::web::remembered::pick_folder(then); + } else { + super::web::page::pick_folder(move |files| then(gather(&files, true).0)); + } +} + +/// The browser remembers the files chosen in its dialog for the next visit (Chrome, +/// Edge); the others, and a computer, have no need or no way. +pub fn remembers_chosen() -> bool { + #[cfg(web)] + return super::web::remembered::supported(); + #[cfg(not(web))] + false +} + +/// The browser remembers the file `path` of an earlier visit and asks the user before +/// the page reads it again ([`allow_reading`]). Never on a computer. +pub fn waiting_to_read(path: &std::path::Path) -> bool { + #[cfg(web)] + return super::web::remembered::waiting(path); + #[cfg(not(web))] + { + let _ = path; + false + } +} + +/// Asks the browser to let the page read the remembered file `path` again (soon after +/// the user's click); `then`: whether it is back. +#[cfg(web)] +pub fn allow_reading(path: &std::path::Path, then: impl FnOnce(bool) + 'static) { + super::web::remembered::allow(path, then); +} + +/// The file `path` left the library: a browser forgets it too. +pub fn forget(path: &std::path::Path) { + #[cfg(web)] + super::web::remembered::forget(path); + #[cfg(not(web))] + let _ = path; +} + +/// The files dropped on the window in this frame, as databases to open: `then` gets +/// their paths once read (in a browser they are kept for the session like chosen +/// ones; on a computer they are opened where they are, as «Add database» does). +pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Picked) + Send + 'static) { + #[cfg(not(web))] + { + let paths: Vec = ctx.input(|i| { + i.raw + .dropped_files + .iter() + .map(|f| f.path().to_path_buf()) + .filter(|p| p.is_absolute()) + .collect() + }); + if paths.is_empty() { + return; + } + // Folders are listed and files' neighbours looked at: off the screen's thread. + let _ = std::thread::Builder::new() + .name("dropped".into()) + .spawn(move || then(sort_dropped(&paths))); + } + #[cfg(web)] + { + let files: Vec = ctx.input(|i| { + i.raw + .dropped_files + .iter() + .filter_map(|f| f.web_file().cloned()) + .collect() + }); + if files.is_empty() { + return; + } + then(gather(&files, false).0); + } +} + +/// Files are dragged over the window now (the page shows where they go). +pub fn dragging(ctx: &egui::Context) -> bool { + ctx.input(|i| !i.raw.hovered_files.is_empty()) +} + +/// The extensions of the other files of a ChessBase database (beside its `.cbh`). +#[cfg(not(web))] +const CHESSBASE_PARTS: [&str; 14] = [ + "cbg", "cba", "cbp", "cbt", "cbc", "cbs", "cbj", "cbe", "cbm", "cbb", "cbgi", "cbtt", "cbpi", + "cbl", +]; + +/// The databases of the files and folders dropped on a computer's window: a file of +/// [`chess_import::EXTENSIONS`] is one; another file of a ChessBase database (its +/// `.cbg`, `.cba`, …: [`CHESSBASE_PARTS`]) stands for the `.cbh` of the same name +/// beside it; a folder gives the databases in it. Each database once (its real file), +/// in the order dropped; a file no longer there and a file of no database are named. +#[cfg(not(web))] +fn sort_dropped(paths: &[PathBuf]) -> Picked { + use std::collections::{HashMap, HashSet}; + let mut picked = Picked::default(); + let mut seen = HashSet::new(); + // Each folder is listed once, however many of its files were dropped. + let mut listed: HashMap> = HashMap::new(); + let mut list = |dir: &std::path::Path| -> Vec { + listed + .entry(dir.to_path_buf()) + .or_insert_with(|| { + let mut files: Vec = std::fs::read_dir(dir) + .map(|entries| { + entries + .flatten() + .map(|e| e.path()) + .filter(|f| f.is_file()) + .collect() + }) + .unwrap_or_default(); + files.sort(); + files + }) + .clone() + }; + let name = |p: &std::path::Path| { + p.file_name() + .map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into()) + }; + for p in paths { + let found = if p.is_dir() { + let found: Vec = list(p) + .into_iter() + .filter(|f| chess_import::EXTENSIONS.contains(&extension(f).as_str())) + .collect(); + if found.is_empty() { + picked.empty_folder = true; + } + found + } else if !p.is_file() { + picked.missing.push(name(p)); + continue; + } else { + let ext = extension(p); + if chess_import::EXTENSIONS.contains(&ext.as_str()) { + vec![p.clone()] + } else if CHESSBASE_PARTS.contains(&ext.as_str()) + && let Some(cbh) = p.parent().and_then(|dir| cbh_beside(p, &list(dir))) + { + vec![cbh] + } else { + picked.unsupported.push(name(p)); + continue; + } + }; + for f in found { + if seen.insert(f.canonicalize().unwrap_or_else(|_| f.clone())) { + picked.paths.push(f); + } + } + } + picked +} + +/// The extension of `p`, in lower case. +#[cfg(not(web))] +fn extension(p: &std::path::Path) -> String { + p.extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_default() +} + +/// The `.cbh` of the ChessBase database the file `part` belongs to, among the files +/// of its folder (names differ in case in sets copied from Windows). +#[cfg(not(web))] +fn cbh_beside(part: &std::path::Path, folder: &[PathBuf]) -> Option { + let stem = part.file_stem()?.to_string_lossy().to_lowercase(); + let want = format!("{stem}.cbh"); + folder + .iter() + .find(|f| { + f.file_name() + .is_some_and(|n| n.to_string_lossy().to_lowercase() == want) + }) + .cloned() +} + +/// Gives `pgn` to the user as the file `name` (a download, where the browser puts +/// them). Only a browser does this: the desktop program saves into files it chose. +#[cfg(web)] +pub fn download_pgn(name: &str, pgn: &str) -> Result<(), String> { + super::web::page::download(name, "application/x-chess-pgn", pgn.as_bytes()) + .map_err(|e| format!("{e:?}")) +} + +#[cfg(all(test, not(web)))] +mod tests { + use super::*; + + #[test] + fn dropped_files_are_sorted_into_databases() { + let dir = std::env::temp_dir().join(format!("cp-dropped-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let base = dir.join("Mega"); + std::fs::create_dir_all(&base).unwrap(); + let touch = |p: &std::path::Path| std::fs::write(p, b"x").unwrap(); + let games = dir.join("games.PGN"); + let archive = dir.join("set.7z"); + let notes = dir.join("notes.txt"); + let cbh = base.join("Mega.CBH"); + let parts = ["Mega.cbg", "Mega.cba", "Mega.cbj", "Mega.CBTT"].map(|n| base.join(n)); + let ini = base.join("Mega.ini"); + let lonely = dir.join("lost.cbg"); + for p in [&games, &archive, ¬es, &cbh, &lonely, &ini] { + touch(p); + } + for p in &parts { + touch(p); + } + let cbv = base.join("Other.cbv"); + touch(&cbv); + let empty = dir.join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + touch(&empty.join("readme.md")); + + // Files of each kind; all the files of a ChessBase database give it once. + let mut dropped = vec![games.clone(), archive.clone()]; + dropped.extend(parts.iter().cloned()); + dropped.push(cbh.clone()); + let picked = sort_dropped(&dropped); + assert_eq!( + picked.paths, + vec![games.clone(), archive.clone(), cbh.clone()] + ); + assert!(picked.unsupported.is_empty() && picked.missing.is_empty()); + assert!(!picked.empty_folder); + + // What is no database is named: another file, a ChessBase part without its + // .cbh, a file of an unknown kind beside a .cbh. + let picked = sort_dropped(&[notes.clone(), lonely.clone(), ini.clone(), games.clone()]); + assert_eq!(picked.paths, vec![games.clone()]); + assert_eq!(picked.unsupported, ["notes.txt", "lost.cbg", "Mega.ini"]); + + // A file no longer there: named, not taken. + let picked = sort_dropped(&[dir.join("gone.pgn"), games.clone()]); + assert_eq!(picked.paths, vec![games.clone()]); + assert_eq!(picked.missing, ["gone.pgn"]); + assert!(picked.unsupported.is_empty()); + + // A folder: its databases (by name); one without any is told. + let picked = sort_dropped(&[base.clone(), empty.clone()]); + assert_eq!(picked.paths, vec![cbh.clone(), cbv.clone()]); + assert!(picked.empty_folder); + + // The same file by a link and by its own path: once. + #[cfg(unix)] + { + let link = dir.join("link.pgn"); + std::os::unix::fs::symlink(&games, &link).unwrap(); + let picked = sort_dropped(&[link.clone(), games.clone()]); + assert_eq!(picked.paths, vec![link]); + } + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/platform/fs.rs b/apps/desktop/src/platform/fs.rs new file mode 100644 index 0000000..fe980d1 --- /dev/null +++ b/apps/desktop/src/platform/fs.rs @@ -0,0 +1,105 @@ +//! Files of the program and the files the user opened: the disk on a computer; in a +//! browser the page's files ([`super::web::vfs`]): the program's data kept in the +//! browser's storage, the user's files in memory for the session. + +use std::io; +use std::path::Path; + +/// What is known of a file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Meta { + pub len: u64, + /// Last change, ms since the Unix epoch (0: not known). + pub modified_ms: u64, + pub readonly: bool, +} + +pub fn read(path: &Path) -> io::Result> { + #[cfg(not(web))] + { + std::fs::read(path) + } + #[cfg(web)] + { + super::web::vfs::read(path) + } +} + +pub fn read_to_string(path: &Path) -> io::Result { + String::from_utf8(read(path)?).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) +} + +/// The first `len` bytes of the file (fewer when it is shorter). +pub fn read_head(path: &Path, len: usize) -> io::Result> { + #[cfg(not(web))] + { + use std::io::Read; + let mut head = Vec::with_capacity(len); + std::fs::File::open(path)? + .take(len as u64) + .read_to_end(&mut head)?; + Ok(head) + } + #[cfg(web)] + { + let mut all = super::web::vfs::read(path)?; + all.truncate(len); + Ok(all) + } +} + +/// Writes the file whole: a reader sees the old text or the new one, never a part +/// (on a computer through a temporary file and a rename; its folder is made). +pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + #[cfg(not(web))] + { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path).inspect_err(|_| { + let _ = std::fs::remove_file(&tmp); + }) + } + #[cfg(web)] + { + super::web::vfs::write(path, bytes.to_vec()) + } +} + +pub fn exists(path: &Path) -> bool { + meta(path).is_ok() +} + +pub fn meta(path: &Path) -> io::Result { + #[cfg(not(web))] + { + let m = std::fs::metadata(path)?; + let modified_ms = m + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_millis() as u64); + Ok(Meta { + len: m.len(), + modified_ms, + readonly: m.permissions().readonly(), + }) + } + #[cfg(web)] + { + super::web::vfs::meta(path) + } +} + +pub fn remove_file(path: &Path) -> io::Result<()> { + #[cfg(not(web))] + { + std::fs::remove_file(path) + } + #[cfg(web)] + { + super::web::vfs::remove(path) + } +} diff --git a/apps/desktop/src/platform/mod.rs b/apps/desktop/src/platform/mod.rs new file mode 100644 index 0000000..0e24de6 --- /dev/null +++ b/apps/desktop/src/platform/mod.rs @@ -0,0 +1,172 @@ +//! What differs between the desktop program and the web version (`docs/dev/web.md`). +//! +//! The interface asks this module, never the system, for: where the program keeps its +//! data ([`config_dir`] and the others), files ([`fs`]), background work ([`spawn`]), +//! the files the user opens or saves ([`files`]), the clipboard ([`clipboard`]) and +//! what the platform offers at all ([`CAPS`]). On a computer it is the system's +//! (`native.rs`); in a browser (`cfg(web)`) the page's (`web/`): the program's data in +//! the browser's storage (IndexedDB), the files the user opened in memory, background +//! work between frames. +#![cfg_attr(web, warn(unused))] + +use std::path::PathBuf; + +#[cfg(not(web))] +mod native; +#[cfg(not(web))] +use native as imp; +#[cfg(web)] +pub mod web; +#[cfg(web)] +use web as imp; + +pub mod clipboard; +pub mod files; +pub mod fs; +pub mod page; +pub mod pgn_store; + +/// What the platform offers the interface: a feature it lacks is not shown. +#[derive(Clone, Copy, Debug)] +pub struct Caps { + /// Checking for a new version and installing it (the web version is always the + /// latest: a reload brings it). + pub updates: bool, + /// Downloading games from Lichess and Chess.com. + pub online_games: bool, + /// Games against the computer (Maia, Rodent). + pub play: bool, + /// Preparing against an opponent. + pub prep: bool, + /// Machine translation of comments. + pub translation: bool, + /// The user's own PGN databases on the disk: new ones, games added and replaced. + pub own_databases: bool, + /// Engines as programs on the disk: chosen, downloaded, started. + pub engine_programs: bool, + /// The opening trainer. + pub training: bool, + /// Saving a game is a download of its PGN (the browser's files are not written). + pub download_pgn: bool, + /// The reference tab (what was played here in the databases) and the search of a + /// position in a database (not in the light web version). + pub reference: bool, + /// Several chosen games copied into a new database in the background (task 42). + pub batch_copy: bool, + /// The search for great moves over a database's list (task 27). + pub great_moves: bool, +} + +/// The features of this platform. +#[cfg(not(web))] +pub const CAPS: Caps = Caps { + updates: true, + online_games: true, + play: true, + prep: true, + translation: true, + own_databases: true, + engine_programs: true, + training: true, + download_pgn: false, + reference: true, + batch_copy: true, + great_moves: true, +}; + +/// The features of this platform: the light web version (`docs/decisions.md`, «Веб-верÑ�иÑ�»). +#[cfg(web)] +pub const CAPS: Caps = Caps { + updates: false, + online_games: false, + play: false, + prep: false, + translation: false, + own_databases: false, + engine_programs: false, + training: false, + download_pgn: true, + reference: false, + batch_copy: false, + great_moves: false, +}; + +/// The program's settings (`~/.config/chesspenguin`; in a browser, its storage). +pub fn config_dir() -> Option { + imp::config_dir() +} + +/// The program's data kept for good (`~/.local/share/chesspenguin`). +pub fn data_dir() -> Option { + imp::data_dir() +} + +/// Data the program can make again (`~/.cache/chesspenguin`). +pub fn cache_dir() -> Option { + imp::cache_dir() +} + +/// The sample databases: files of the program, written at the first start on a +/// computer; built in and only read in a browser. +pub fn examples_dir() -> Option { + imp::examples_dir() +} + +/// Runs `job` in the background and returns at once: on a thread of its own named +/// `name` on a computer; in a browser (which gives a page no threads) on the page's +/// thread after the current frame, so a job there is one finite piece of work, never a +/// loop that waits. The error: the job could not be started. +pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + imp::spawn(name, job) +} + +/// Bytes the browser still gives the site to keep (its quota less what is used); `None` +/// on a computer and until the browser answered. +pub fn storage_free() -> Option { + #[cfg(web)] + return web::storage::usage().map(|(used, quota)| quota.saturating_sub(used)); + #[cfg(not(web))] + None +} + +/// A size for people in the interface's language: "340 KB", "96 MB", "9.6 GB" +/// («9,6 ГБ», «9,6 Go»: its units and its decimal sign). +pub fn size_text(bytes: u64) -> String { + use crate::i18n::{tr, trf}; + let b = bytes as f64; + let (n, unit) = if b >= 1e9 { + (format!("{:.1}", b / 1e9), "{n} GB") + } else if b >= 1e6 { + (format!("{:.0}", b / 1e6), "{n} MB") + } else { + (format!("{:.0}", (b / 1e3).max(1.0)), "{n} KB") + }; + // The key's own text where the language writes a decimal point. + let n = if tr("decimal comma") == "," { + n.replace('.', ",") + } else { + n + }; + trf(unit, &[("n", &n)]) +} + +/// A line for the program's log (`chesspenguin.log`; in a browser its console). +pub fn log(line: &str) { + #[cfg(not(web))] + crate::graphics::log(line); + #[cfg(web)] + log::info!("{line}"); +} + +/// Reads a database the library shows away from the screen's thread: its file on the +/// disk on a thread of its own (`progress` follows the reading), or in a browser the +/// file the user gave the page (or a sample built in) in the page's reader, a worker +/// (no progress). `done` gets the database: on that thread, or on the page's. +pub fn open_database( + path: &std::path::Path, + progress: impl FnMut(chess_core::ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + imp::open_database(path, progress, cancel, done) +} diff --git a/apps/desktop/src/platform/native.rs b/apps/desktop/src/platform/native.rs new file mode 100644 index 0000000..b416015 --- /dev/null +++ b/apps/desktop/src/platform/native.rs @@ -0,0 +1,46 @@ +//! The desktop program: the system's folders, files and threads. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::ScanProgress; +use chess_import::{ImportError, Opened}; + +fn project() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") +} + +pub fn config_dir() -> Option { + project().map(|d| d.config_dir().to_path_buf()) +} + +pub fn data_dir() -> Option { + project().map(|d| d.data_dir().to_path_buf()) +} + +pub fn cache_dir() -> Option { + project().map(|d| d.cache_dir().to_path_buf()) +} + +pub fn examples_dir() -> Option { + project().map(|d| d.data_local_dir().join("examples")) +} + +pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + std::thread::Builder::new() + .name(name.to_owned()) + .spawn(job) + .map(drop) +} + +pub fn open_database( + path: &Path, + mut progress: impl FnMut(ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + let path = path.to_owned(); + spawn("db-open", move || { + done(chess_import::open(&path, &mut progress, &cancel)); + }) +} diff --git a/apps/desktop/src/platform/page.rs b/apps/desktop/src/platform/page.rs new file mode 100644 index 0000000..ea73823 --- /dev/null +++ b/apps/desktop/src/platform/page.rs @@ -0,0 +1,110 @@ +//! The program as a page of a browser (docs/design/web-version.md §1.1, §1.3): a game +//! on the screen is an entry of the browser's history, so its «Back» means «â†� Library»; +//! unsaved work makes the browser ask before the page is left. A desktop program has +//! neither: nothing happens there. + +#[cfg(web)] +mod imp { + use std::cell::Cell; + + use wasm_bindgen::JsCast; + use wasm_bindgen::prelude::*; + + thread_local! { + /// The history has our entry for the game on the screen. + static IN_GAME: Cell = const { Cell::new(false) }; + /// «Back» was pressed (the entry left) and not taken yet. + static BACK: Cell = const { Cell::new(false) }; + /// Our own `history.back()`: its `popstate` is not the user's. + static OWN_BACK: Cell = const { Cell::new(false) }; + static LISTENING: Cell = const { Cell::new(false) }; + static WARN: Cell = const { Cell::new(false) }; + /// The page's `beforeunload`: the browser asks before the page is left. + static ASK: Closure = + Closure::new(|e: web_sys::BeforeUnloadEvent| { + e.prevent_default(); + e.set_return_value(""); + }); + } + + fn listen(ctx: &egui::Context) { + if LISTENING.replace(true) { + return; + } + let ctx = ctx.clone(); + let on_pop = Closure::::new(move || { + if OWN_BACK.replace(false) { + return; + } + if IN_GAME.replace(false) { + BACK.set(true); + ctx.request_repaint(); + } + }); + if let Some(w) = web_sys::window() { + let _ = w.add_event_listener_with_callback("popstate", on_pop.as_ref().unchecked_ref()); + } + // Listens as long as the page lives. + on_pop.forget(); + } + + pub fn game_shown(ctx: &egui::Context, shown: bool) { + listen(ctx); + let Some(history) = web_sys::window().and_then(|w| w.history().ok()) else { + return; + }; + if shown && !IN_GAME.get() { + let state = js_sys::Object::new(); + let _ = js_sys::Reflect::set(&state, &"cpGame".into(), &JsValue::TRUE); + if history.push_state(&state, "").is_ok() { + IN_GAME.set(true); + } + } else if !shown && IN_GAME.get() { + // The game left by the program's own button: its entry goes too. + IN_GAME.set(false); + OWN_BACK.set(true); + let _ = history.back(); + } + } + + pub fn take_back() -> bool { + BACK.replace(false) + } + + pub fn warn_on_leave(warn: bool) { + if WARN.replace(warn) == warn { + return; + } + let Some(w) = web_sys::window() else { return }; + if warn { + ASK.with(|ask| w.set_onbeforeunload(Some(ask.as_ref().unchecked_ref()))); + } else { + w.set_onbeforeunload(None); + } + } +} + +/// The game is on the screen (`true`) or not: kept in step with the browser's history. +pub fn game_shown(ctx: &egui::Context, shown: bool) { + #[cfg(web)] + imp::game_shown(ctx, shown); + #[cfg(not(web))] + let _ = (ctx, shown); +} + +/// The browser's «Back» left the game since the last call (then it is «â†� Library»). +pub fn take_back() -> bool { + #[cfg(web)] + return imp::take_back(); + #[cfg(not(web))] + false +} + +/// Whether leaving the page (closing the tab, reloading) should be asked about: the +/// browser asks in its own words. +pub fn warn_on_leave(warn: bool) { + #[cfg(web)] + imp::warn_on_leave(warn); + #[cfg(not(web))] + let _ = warn; +} diff --git a/apps/desktop/src/platform/pgn_store.rs b/apps/desktop/src/platform/pgn_store.rs new file mode 100644 index 0000000..3f85435 --- /dev/null +++ b/apps/desktop/src/platform/pgn_store.rs @@ -0,0 +1,86 @@ +//! Writing games into a PGN database the library has open: its file on a computer +//! (`chess_core::pgn::store`, as before); in a browser the page's file of that path +//! (only the program's own: «My games»; the user's files are only read). The text +//! written is the same byte for byte. + +use std::path::Path; + +use chess_core::PgnDatabase; +use chess_core::pgn::store::{self, Appended, Removed, WriteError}; + +#[cfg(web)] +fn write(path: &Path, bytes: Vec) -> Result<(), WriteError> { + super::web::vfs::write(path, bytes).map_err(WriteError::Io) +} + +#[cfg(web)] +fn utf8(db: &PgnDatabase) -> Result<(), WriteError> { + if db.encoding() != chess_core::TextEncoding::Utf8 && !db.detected_encoding().ascii_only { + return Err(WriteError::Encoding); + } + Ok(()) +} + +/// Adds `record` at the end of `db` (the file `path`). +pub fn append(db: &PgnDatabase, path: &Path, record: &str) -> Result { + #[cfg(not(web))] + { + let _ = path; + store::append(db, record) + } + #[cfg(web)] + { + utf8(db)?; + let (bytes, offset) = store::appended(db, record); + write(path, bytes)?; + Ok(Appended { offset }) + } +} + +/// Replaces record `index` of `db` with `record`. +pub fn replace( + db: &PgnDatabase, + path: &Path, + index: usize, + record: &str, +) -> Result<(), WriteError> { + #[cfg(not(web))] + { + let _ = path; + store::replace(db, index, record) + } + #[cfg(web)] + { + utf8(db)?; + write(path, store::replaced(db, index, record)?) + } +} + +/// Removes record `index` of `db`; [`restore`] puts it back. +pub fn remove(db: &PgnDatabase, path: &Path, index: usize) -> Result { + #[cfg(not(web))] + { + let _ = path; + store::remove(db, index) + } + #[cfg(web)] + { + utf8(db)?; + let (bytes, gone) = store::removed(db, index)?; + write(path, bytes)?; + Ok(gone) + } +} + +/// Puts a removed record back at its place. +pub fn restore(db: &PgnDatabase, path: &Path, removed: &Removed) -> Result<(), WriteError> { + #[cfg(not(web))] + { + let _ = path; + store::restore(db, removed) + } + #[cfg(web)] + { + write(path, store::restored(db, removed)?) + } +} diff --git a/apps/desktop/src/platform/web/engine.rs b/apps/desktop/src/platform/web/engine.rs new file mode 100644 index 0000000..94d15df --- /dev/null +++ b/apps/desktop/src/platform/web/engine.rs @@ -0,0 +1,199 @@ +//! Stockfish 19 for the web version (npm `stockfish@19.0.1`, nmrugg/stockfish.js, +//! GPL-3.0): the single-threaded build, served by our site beside the program +//! (`/app/engine/`, apps/web/build.sh). Its `.wasm` (99 MB, 78 MB in Brotli) is +//! downloaded only when the user agrees (decisions «Веб-верÑ�иÑ�»), checked against its +//! SHA-256 and kept in the browser's Cache Storage. A worker of the engine gets it as a +//! `blob:` address after `#` (the script takes the wasm's address from there): no worker +//! downloads it again. +//! +//! Its search is that of the official Stockfish 19 (the same evaluations, node for node: +//! docs/research/web-version-tech.md §2.2), so a game review gives the same marks. + +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use sha2::{Digest, Sha256}; +use wasm_bindgen::JsCast; +use wasm_bindgen::JsValue; +use wasm_bindgen_futures::JsFuture; + +/// The engine's worker script and its WebAssembly, relative to the page. +pub const SCRIPT: &str = "engine/stockfish-19-single.js"; +const WASM: &str = "engine/stockfish-19-single.wasm"; +/// The wasm as published (`stockfish@19.0.1`, `bin/stockfish-19-single.wasm`). +pub const WASM_BYTES: u64 = 99_169_054; +const WASM_SHA256: &str = "991bede2f253ebb08ff01fcc48270f4b9c8e66b12d5bd5f8d6f52eb3e3b3a740"; +/// What travels over the network (the site sends it in Brotli). +pub const DOWNLOAD_MB: u64 = 78; +/// The cache of the engine; another version of it gets another name. +const CACHE: &str = "chesspenguin-engine-sf19.0.1"; + +thread_local! { + /// The cached wasm as a `blob:` address, once it is there. + static BLOB: RefCell> = const { RefCell::new(None) }; +} + +/// Why the engine could not be downloaded. +#[derive(Debug)] +pub enum Fetch { + Network(String), + Server(u16), + /// Not the published file. + Checksum, + /// The browser would not keep it (space, a private window). + Storage(String), + Cancelled, +} + +fn js(e: JsValue) -> String { + e.as_string() + .or_else(|| { + e.dyn_ref::() + .map(|e| String::from(e.message())) + }) + .unwrap_or_else(|| format!("{e:?}")) +} + +fn caches() -> Result { + web_sys::window().ok_or("no window")?.caches().map_err(js) +} + +async fn open() -> Result { + JsFuture::from(caches()?.open(CACHE)) + .await + .map_err(js)? + .dyn_into() + .map_err(js) +} + +/// Makes the cached engine usable (a `blob:` address); called at the start. +pub async fn probe() { + let found = async { + let cache = open().await?; + let hit = JsFuture::from(cache.match_with_str(WASM)) + .await + .map_err(js)?; + let Ok(response) = hit.dyn_into::() else { + return Ok::<_, String>(None); + }; + let blob: web_sys::Blob = JsFuture::from(response.blob().map_err(js)?) + .await + .map_err(js)? + .dyn_into() + .map_err(js)?; + if blob.size() as u64 != WASM_BYTES { + return Ok(None); + } + web_sys::Url::create_object_url_with_blob(&blob) + .map(Some) + .map_err(js) + }; + match found.await { + Ok(url) => BLOB.with_borrow_mut(|b| *b = url), + Err(e) => log::warn!("the engine's cache: {e}"), + } +} + +/// The address of a worker of the engine, once it is downloaded. +pub fn worker_script() -> Option { + BLOB.with_borrow(|b| b.as_ref().map(|url| format!("{SCRIPT}#{url}"))) +} + +/// Downloads the engine into the cache; `progress(done, total)` on the way. +pub async fn download(progress: impl Fn(u64, u64), cancel: Arc) -> Result<(), Fetch> { + let window = web_sys::window().ok_or_else(|| Fetch::Network("no window".into()))?; + let response: web_sys::Response = JsFuture::from(window.fetch_with_str(WASM)) + .await + .map_err(|e| Fetch::Network(js(e)))? + .dyn_into() + .map_err(|e| Fetch::Network(js(e)))?; + if !response.ok() { + return Err(Fetch::Server(response.status())); + } + let body = response + .body() + .ok_or_else(|| Fetch::Network("no body".into()))?; + let reader: web_sys::ReadableStreamDefaultReader = body + .get_reader() + .dyn_into() + .map_err(|e| Fetch::Network(js(e.into())))?; + let mut bytes: Vec = Vec::with_capacity(WASM_BYTES as usize); + let mut hasher = Sha256::new(); + loop { + if cancel.load(Ordering::Relaxed) { + let _ = reader.cancel(); + return Err(Fetch::Cancelled); + } + let chunk = JsFuture::from(reader.read()) + .await + .map_err(|e| Fetch::Network(js(e)))?; + let done = js_sys::Reflect::get(&chunk, &"done".into()) + .map(|d| d.is_truthy()) + .unwrap_or(true); + if done { + break; + } + let value: js_sys::Uint8Array = js_sys::Reflect::get(&chunk, &"value".into()) + .map_err(|e| Fetch::Network(js(e)))? + .dyn_into() + .map_err(|e| Fetch::Network(js(e)))?; + let start = bytes.len(); + bytes.resize(start + value.length() as usize, 0); + value.copy_to(&mut bytes[start..]); + hasher.update(&bytes[start..]); + if bytes.len() as u64 > WASM_BYTES { + return Err(Fetch::Checksum); + } + progress(bytes.len() as u64, WASM_BYTES); + } + let digest: String = hasher + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + if bytes.len() as u64 != WASM_BYTES || digest != WASM_SHA256 { + return Err(Fetch::Checksum); + } + let storage = |e: JsValue| Fetch::Storage(js(e)); + let init = web_sys::ResponseInit::new(); + let headers = web_sys::Headers::new().map_err(storage)?; + headers + .set("Content-Type", "application/wasm") + .map_err(storage)?; + init.set_headers(&headers); + let stored = web_sys::Response::new_with_opt_u8_array_and_init(Some(&mut bytes), &init) + .map_err(storage)?; + let cache = open().await.map_err(Fetch::Storage)?; + JsFuture::from(cache.put_with_str(WASM, &stored)) + .await + .map_err(storage)?; + drop(bytes); + probe().await; + if worker_script().is_none() { + return Err(Fetch::Storage("the browser did not keep the engine".into())); + } + Ok(()) +} + +/// Removes the downloaded engine from the browser. +pub fn remove() { + if let Some(url) = BLOB.with_borrow_mut(Option::take) { + let _ = web_sys::Url::revoke_object_url(&url); + } + if let Ok(c) = caches() { + let _ = c.delete(CACHE); + } +} + +/// Whether the engine is downloaded and ready. +pub fn ready() -> bool { + BLOB.with_borrow(Option::is_some) +} + +/// Engines working at once for a game review: one per logical processor, as on a +/// computer, at most `limit` (each worker holds its own copy of the engine, ≈ 130 MB). +pub fn workers(limit: usize) -> usize { + let cpus = web_sys::window().map_or(1.0, |w| w.navigator().hardware_concurrency()) as usize; + cpus.clamp(1, limit) +} diff --git a/apps/desktop/src/platform/web/idb.rs b/apps/desktop/src/platform/web/idb.rs new file mode 100644 index 0000000..3641f1c --- /dev/null +++ b/apps/desktop/src/platform/web/idb.rs @@ -0,0 +1,167 @@ +//! The program's data in the browser's storage: one IndexedDB database, a store of +//! files by path, read whole at the start (settings and marks are small), every write +//! going there behind the interface, in the order made; and a store of the user's files +//! a Chromium browser remembers (their handles, by the page's path: [`super::remembered`]). + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +const DB: &str = "chesspenguin"; +const STORE: &str = "files"; +const HANDLES: &str = "handles"; +/// 2: the store of handles. +const VERSION: u32 = 2; + +/// The request's outcome once it is done. +async fn done(request: &web_sys::IdbRequest) -> Result { + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let ok = Closure::once_into_js(move |ev: web_sys::Event| { + let r = ev + .target() + .and_then(|t| t.dyn_into::().ok()) + .and_then(|r| r.result().ok()) + .unwrap_or(JsValue::UNDEFINED); + let _ = resolve.call1(&JsValue::NULL, &r); + }); + let err = Closure::once_into_js(move |ev: web_sys::Event| { + let _ = reject.call1(&JsValue::NULL, &ev); + }); + request.set_onsuccess(Some(ok.unchecked_ref())); + request.set_onerror(Some(err.unchecked_ref())); + }); + wasm_bindgen_futures::JsFuture::from(promise).await +} + +async fn open() -> Result { + let factory = web_sys::window() + .ok_or("no window")? + .indexed_db()? + .ok_or("no IndexedDB")?; + let request = factory.open_with_u32(DB, VERSION)?; + let upgrade = Closure::once_into_js(move |ev: web_sys::Event| { + if let Some(db) = ev + .target() + .and_then(|t| t.dyn_into::().ok()) + .and_then(|r| r.result().ok()) + .and_then(|r| r.dyn_into::().ok()) + { + for store in [STORE, HANDLES] { + if !db.object_store_names().contains(store) { + let _ = db.create_object_store(store); + } + } + } + }); + request.set_onupgradeneeded(Some(upgrade.unchecked_ref())); + done(&request).await?.dyn_into() +} + +thread_local! { + /// The database once opened (`None` until then, or when the browser refused it: + /// a private window of some browsers; then nothing is kept between visits). + static OPENED: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Everything kept: (path, bytes). Empty when the browser keeps nothing for the page. +pub async fn load_all() -> Vec<(String, Vec)> { + let db = match open().await { + Ok(db) => db, + Err(e) => { + log::warn!("browser storage unavailable: {e:?}"); + return Vec::new(); + } + }; + let read = async { + let tx = db.transaction_with_str(STORE)?; + let store = tx.object_store(STORE)?; + let keys = done(&store.get_all_keys()?).await?; + let values = done(&store.get_all()?).await?; + let keys: js_sys::Array = keys.dyn_into()?; + let values: js_sys::Array = values.dyn_into()?; + Ok::<_, JsValue>( + keys.iter() + .zip(values.iter()) + .filter_map(|(k, v)| { + let bytes = v.dyn_into::().ok()?.to_vec(); + Some((k.as_string()?, bytes)) + }) + .collect(), + ) + }; + let files = read.await.unwrap_or_else(|e| { + log::warn!("browser storage unreadable: {e:?}"); + Vec::new() + }); + OPENED.with_borrow_mut(|o| *o = Some(db)); + files +} + +fn store_named(name: &str) -> Option { + OPENED.with_borrow(|db| { + let tx = db + .as_ref()? + .transaction_with_str_and_mode(name, web_sys::IdbTransactionMode::Readwrite) + .ok()?; + tx.object_store(name).ok() + }) +} + +fn store() -> Option { + store_named(STORE) +} + +/// The handles kept: (the page's path, the handle). Read after [`load_all`]. +pub async fn handles() -> Vec<(String, JsValue)> { + let Some(db) = OPENED.with_borrow(|db| db.clone()) else { + return Vec::new(); + }; + let read = async { + let tx = db.transaction_with_str(HANDLES)?; + let store = tx.object_store(HANDLES)?; + let keys: js_sys::Array = done(&store.get_all_keys()?).await?.dyn_into()?; + let values: js_sys::Array = done(&store.get_all()?).await?.dyn_into()?; + Ok::<_, JsValue>( + keys.iter() + .zip(values.iter()) + .filter_map(|(k, v)| Some((k.as_string()?, v))) + .collect(), + ) + }; + read.await.unwrap_or_else(|e: JsValue| { + log::warn!("browser storage: remembered files unreadable: {e:?}"); + Vec::new() + }) +} + +pub fn put_handle(path: &str, handle: &JsValue) { + if let Some(store) = store_named(HANDLES) + && let Err(e) = store.put_with_key(handle, &JsValue::from_str(path)) + { + log::warn!("browser storage: cannot remember {path}: {e:?}"); + } +} + +pub fn delete_handle(path: &str) { + if let Some(store) = store_named(HANDLES) { + let _ = store.delete(&JsValue::from_str(path)); + } +} + +/// Keeps `bytes` as `path` (transactions of one page run in the order made). +pub fn put(path: String, bytes: Vec) { + if let Some(store) = store() { + let value = js_sys::Uint8Array::from(bytes.as_slice()); + if let Err(e) = store.put_with_key(&value, &JsValue::from_str(&path)) { + log::warn!("browser storage: cannot keep {path}: {e:?}"); + } + } +} + +pub fn delete(path: String) { + if let Some(store) = store() + && let Err(e) = store.delete(&JsValue::from_str(&path)) + { + log::warn!("browser storage: cannot delete {path}: {e:?}"); + } +} diff --git a/apps/desktop/src/platform/web/import.rs b/apps/desktop/src/platform/web/import.rs new file mode 100644 index 0000000..dde9afd --- /dev/null +++ b/apps/desktop/src/platform/web/import.rs @@ -0,0 +1,316 @@ +//! Opening a database without holding the page: a Web Worker runs a second instance of +//! the program (`import-worker.js` → [`answer`]) that reads the file — PGN, CBV, ZIP, +//! 7Z, converted and indexed — and gives back its text and index; the page puts the +//! database together from them without reading it again +//! (`chess_core::PgnDatabase::from_index`); the cards of the shelf only ask it how many +//! games a file holds. One worker serves the visit and reads the files one after +//! another, in the order they were given. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use chess_core::{PgnDatabase, PgnIndex}; +use chess_import::{Database, Format, ImportError, Opened, PgnDb, Unsupported}; +use serde::{Deserialize, Serialize}; +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The worker's script, beside the page. +const SCRIPT: &str = "import-worker.js"; + +/// What the worker gives back besides the text. +#[derive(Serialize, Deserialize)] +struct Read { + index: PgnIndex, + /// Its place in [`Format::ALL`]. + format: usize, + notes: Vec, +} + +/// Why the worker could not read a file: [`ImportError`] in serde's terms. +#[derive(Serialize, Deserialize)] +enum Failure { + Io(String), + Corrupt(String), + Encrypted, + ChessBase2, + ChessBaseFiles, + Empty, + Cancelled, +} + +impl Failure { + fn of(e: ImportError) -> Failure { + match e { + ImportError::Io { source, .. } => Failure::Io(source.to_string()), + ImportError::Corrupt(s) => Failure::Corrupt(s), + ImportError::Unsupported(Unsupported::Encrypted) => Failure::Encrypted, + ImportError::Unsupported(Unsupported::ChessBase2) => Failure::ChessBase2, + ImportError::Unsupported(Unsupported::ChessBaseFiles) => Failure::ChessBaseFiles, + ImportError::Empty => Failure::Empty, + ImportError::Cancelled => Failure::Cancelled, + } + } + + fn error(self, path: &Path) -> ImportError { + match self { + Failure::Io(e) => io_error(path, e), + Failure::Corrupt(s) => ImportError::Corrupt(s), + Failure::Encrypted => ImportError::Unsupported(Unsupported::Encrypted), + Failure::ChessBase2 => ImportError::Unsupported(Unsupported::ChessBase2), + Failure::ChessBaseFiles => ImportError::Unsupported(Unsupported::ChessBaseFiles), + Failure::Empty => ImportError::Empty, + Failure::Cancelled => ImportError::Cancelled, + } + } +} + +fn io_error(path: &Path, e: impl ToString) -> ImportError { + ImportError::Io { + path: path.to_owned(), + source: std::io::Error::other(e.to_string()), + } +} + +fn set(object: &js_sys::Object, key: &str, value: &JsValue) { + let _ = js_sys::Reflect::set(object, &key.into(), value); +} + +thread_local! { + /// The worker's side: the files of the database being given, one by one (so that + /// the worker holds each file's bytes once: in the program, not also in the page's + /// script). + static GIVEN: RefCell)>> = const { RefCell::new(Vec::new()) }; +} + +/// The worker's side: one more file of the database to read (its own file first). +pub fn give(name: String, bytes: Vec) { + // The reader's panics to the console (the page's own hook is eframe's). + static HOOK: std::sync::Once = std::sync::Once::new(); + HOOK.call_once(|| { + std::panic::set_hook(Box::new(|info| { + web_sys::console::error_1(&format!("the reader: {info}").into()); + })); + }); + GIVEN.with_borrow_mut(|g| g.push((name, bytes))); +} + +/// The worker's side: reads the database given ([`give`]). The answer: `{text, index}` +/// (the text and the index in JSON), only `{games}` when `count` is asked, or `{error}` +/// (a [`Failure`] in JSON). +pub fn answer(count: bool) -> JsValue { + let never = std::sync::atomic::AtomicBool::new(false); + let answer = js_sys::Object::new(); + let mut files = GIVEN.with_borrow_mut(std::mem::take); + if files.is_empty() { + files.push((String::new(), Vec::new())); + } + let name = files[0].0.clone(); + let chessbase = name.to_lowercase().ends_with(".cbh"); + let opened = if chessbase { + chess_import::open_chessbase_owned(&name, files, &mut |_| {}, &never) + } else { + let bytes = files.swap_remove(0).1; + chess_import::open_bytes(&name, bytes, &mut |_| {}, &never) + }; + let read = opened.and_then(|opened| { + // Read from bytes, a database is always converted to PGN. + let Database::Pgn(pgn) = opened.db else { + return Err(ImportError::Corrupt("not a PGN database".into())); + }; + Ok((pgn.db, opened.format, opened.notes)) + }); + match read { + Ok((db, _, _)) if count => set(&answer, "games", &JsValue::from(db.len() as f64)), + Ok((db, format, notes)) => { + let (text, index) = db.into_index(); + let read = Read { + index, + format: Format::ALL.iter().position(|f| *f == format).unwrap_or(0), + notes, + }; + set(&answer, "text", &js_sys::Uint8Array::from(text.as_slice())); + let json = serde_json::to_string(&read).unwrap_or_default(); + set(&answer, "index", &JsValue::from_str(&json)); + } + Err(e) => { + let json = serde_json::to_string(&Failure::of(e)).unwrap_or_default(); + set(&answer, "error", &JsValue::from_str(&json)); + } + } + answer.into() +} + +/// Who waits for an answer. +enum Waiting { + Open(PathBuf, Box)>), + Count(Box)>), +} + +impl Waiting { + fn out_of_memory(self) { + match self { + Waiting::Open(path, done) => done(Err(ImportError::Io { + path, + source: std::io::Error::from(std::io::ErrorKind::OutOfMemory), + })), + Waiting::Count(done) => done(None), + } + } + + fn failed(self, e: impl ToString) { + match self { + Waiting::Open(path, done) => done(Err(io_error(&path, e))), + Waiting::Count(done) => done(None), + } + } +} + +thread_local! { + static WORKER: RefCell> = const { RefCell::new(None) }; + static WAITING: RefCell> = RefCell::new(HashMap::new()); + static NEXT: RefCell = const { RefCell::new(0) }; +} + +/// The worker's answer to a request: the database, or why there is none. +fn answered(data: JsValue) { + let get = |k: &str| js_sys::Reflect::get(&data, &k.into()).unwrap_or(JsValue::UNDEFINED); + let id = get("id").as_f64().unwrap_or(-1.0) as u32; + if let Some(e) = get("crashed").as_string() { + // The worker's program stopped (out of its memory, most likely: a browser gives + // a page at most 4 GB): this database cannot be read here; the others waiting + // go to a new worker's program — they fail too, to be opened again. + log::warn!("the reader stopped: {e}"); + if let Some(w) = WORKER.with_borrow_mut(Option::take) { + w.terminate(); + } + for (n, waiting) in WAITING.with_borrow_mut(std::mem::take) { + if n == id { + waiting.out_of_memory(); + } else { + waiting.failed(&e); + } + } + return; + } + let (path, done) = match WAITING.with_borrow_mut(|w| w.remove(&id)) { + Some(Waiting::Open(path, done)) => (path, done), + Some(Waiting::Count(done)) => { + done(get("games").as_f64().map(|n| n as usize)); + return; + } + None => return, + }; + if let Some(json) = get("error").as_string() { + let e = serde_json::from_str::(&json) + .map_or_else(|_| io_error(&path, json.clone()), |f| f.error(&path)); + done(Err(e)); + return; + } + let text = get("text") + .dyn_into::() + .map(|a| a.to_vec()); + let read = get("index") + .as_string() + .and_then(|j| serde_json::from_str::(&j).ok()); + let (Ok(text), Some(read)) = (text, read) else { + done(Err(io_error( + &path, + "the reader's answer is not a database", + ))); + return; + }; + let db = PgnDatabase::from_index(text, read.index); + log::info!( + "database read: {} ({} games)", + path.file_name().unwrap_or_default().to_string_lossy(), + db.len() + ); + done(Ok(Opened { + db: Database::Pgn(PgnDb::new(db)), + format: Format::ALL.get(read.format).copied().unwrap_or(Format::Pgn), + notes: read.notes, + })) +} + +fn worker() -> Result { + if let Some(w) = WORKER.with_borrow(|w| w.clone()) { + return Ok(w); + } + let options = web_sys::WorkerOptions::new(); + options.set_type(web_sys::WorkerType::Module); + let w = web_sys::Worker::new_with_options(SCRIPT, &options)?; + let on_message = + Closure::::new(|e: web_sys::MessageEvent| { + answered(e.data()); + }); + w.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + // The worker serves the whole visit. + on_message.forget(); + let on_error = Closure::::new(|e: web_sys::ErrorEvent| { + // The worker itself failed (out of memory, its script not loaded): the files + // waiting for it fail, and the next one gets a new worker. + let message = e.message(); + if let Some(w) = WORKER.with_borrow_mut(Option::take) { + w.terminate(); + } + for (_, waiting) in WAITING.with_borrow_mut(std::mem::take) { + waiting.failed(&message); + } + }); + w.set_onerror(Some(on_error.as_ref().unchecked_ref())); + on_error.forget(); + WORKER.with_borrow_mut(|slot| *slot = Some(w.clone())); + Ok(w) +} + +/// Reads the page's file `path` in the worker; `done` gets the database on the page's +/// thread. +pub fn open(path: &Path, done: impl FnOnce(Result) + 'static) { + ask(path, false, Waiting::Open(path.to_owned(), Box::new(done))); +} + +/// How many games the page's file `path` holds (`None`: it cannot be read), read in +/// the worker; `done` gets it on the page's thread. +pub fn count(path: &Path, done: impl FnOnce(Option) + 'static) { + ask(path, true, Waiting::Count(Box::new(done))); +} + +fn ask(path: &Path, count: bool, waiting: Waiting) { + let files = match super::vfs::database_files(path) { + Ok(f) => f, + Err(e) => return waiting.failed(e), + }; + let w = match worker() { + Ok(w) => w, + Err(e) => return waiting.failed(format!("{e:?}")), + }; + let id = NEXT.with_borrow_mut(|n| { + *n += 1; + *n + }); + WAITING.with_borrow_mut(|m| m.insert(id, waiting)); + let names = js_sys::Array::new(); + let parts = js_sys::Array::new(); + // The bytes the page holds go over without a copy; the user's files are the + // browser's, read by the worker. + let transfer = js_sys::Array::new(); + for (name, source) in files { + names.push(&JsValue::from_str(&name)); + if let Some(array) = source.dyn_ref::() { + transfer.push(&array.buffer()); + } + parts.push(&source); + } + let message = js_sys::Object::new(); + set(&message, "id", &JsValue::from(id)); + set(&message, "names", &names); + set(&message, "parts", &parts); + set(&message, "count", &JsValue::from_bool(count)); + if let Err(e) = w.post_message_with_transfer(&message, &transfer) + && let Some(waiting) = WAITING.with_borrow_mut(|m| m.remove(&id)) + { + waiting.failed(format!("{e:?}")); + } +} diff --git a/apps/desktop/src/platform/web/mod.rs b/apps/desktop/src/platform/web/mod.rs new file mode 100644 index 0000000..4515a21 --- /dev/null +++ b/apps/desktop/src/platform/web/mod.rs @@ -0,0 +1,63 @@ +//! The web version: a page in a browser, without threads, processes or a file system. +//! +//! The program's folders are names in the page's own file tree ([`vfs`]): `/config`, +//! `/data` and `/cache` are kept in the browser's storage ([`idb`], loaded before the +//! interface starts, written behind it); `/examples` (the samples, built in) and +//! `/opened` (the files the user gave the page, only read: decisions «Веб-верÑ�иÑ�») live +//! for the session. Background work runs on the page's thread after the frame. + +pub mod engine; +pub mod idb; +pub mod import; +pub mod page; +pub mod remembered; +pub mod storage; +pub mod vfs; + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::ScanProgress; +use chess_import::{ImportError, Opened}; + +pub fn config_dir() -> Option { + Some(PathBuf::from(vfs::CONFIG)) +} + +pub fn data_dir() -> Option { + Some(PathBuf::from(vfs::DATA)) +} + +pub fn cache_dir() -> Option { + Some(PathBuf::from(vfs::CACHE)) +} + +pub fn examples_dir() -> Option { + Some(PathBuf::from(vfs::EXAMPLES)) +} + +/// The page has no threads: the job runs on its thread once the current frame is +/// done (the screen shows the state before it, «Opening…», first). +pub fn spawn(_name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + wasm_bindgen_futures::spawn_local(async move { + page::next_task().await; + job(); + }); + Ok(()) +} + +pub fn open_database( + path: &Path, + _progress: impl FnMut(ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + import::open(path, move |read| { + done(if cancel.load(std::sync::atomic::Ordering::Relaxed) { + Err(ImportError::Cancelled) + } else { + read + }) + }); + Ok(()) +} diff --git a/apps/desktop/src/platform/web/page.rs b/apps/desktop/src/platform/web/page.rs new file mode 100644 index 0000000..e00806f --- /dev/null +++ b/apps/desktop/src/platform/web/page.rs @@ -0,0 +1,144 @@ +//! The page around the program: choosing files, downloads, the next task. + +use std::cell::RefCell; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The elements through which files and a folder are chosen (one each for the page; +/// checks give them files). +pub const OPEN_INPUT_ID: &str = "cp-open-files"; +pub const OPEN_FOLDER_ID: &str = "cp-open-folder"; +/// The program's canvas (`page/index.html`). +const CANVAS_ID: &str = "cp-canvas"; + +fn document() -> Option { + web_sys::window()?.document() +} + +/// Resolves after the tasks queued now: the page draws its frame first. +pub async fn next_task() { + let promise = js_sys::Promise::new(&mut |resolve, _| { + if let Some(w) = web_sys::window() { + let _ = w.set_timeout_with_callback(&resolve); + } + }); + let _ = wasm_bindgen_futures::JsFuture::from(promise).await; +} + +type Picked = Box)>; + +thread_local! { + /// What to do with the files chosen next. + static ON_PICKED: RefCell> = const { RefCell::new(None) }; +} + +/// The page's file input `id`, made once: hidden, several files, `accept` the +/// extensions; `folder`: it chooses a folder (`webkitdirectory`, every browser has it). +fn open_input(id: &str, accept: &str, folder: bool) -> Result { + let doc = document().ok_or("no document")?; + if let Some(el) = doc.get_element_by_id(id) { + let input: web_sys::HtmlInputElement = el.dyn_into()?; + input.set_accept(accept); + return Ok(input); + } + let input: web_sys::HtmlInputElement = doc.create_element("input")?.dyn_into()?; + input.set_id(id); + input.set_type("file"); + input.set_multiple(true); + input.set_accept(accept); + if folder { + input.set_attribute("webkitdirectory", "")?; + } + input.style().set_property("display", "none")?; + let on_change = Closure::::new(move |ev: web_sys::Event| { + let Some(input) = ev + .target() + .and_then(|t| t.dyn_into::().ok()) + else { + return; + }; + let files: Vec = input + .files() + .map(|list| (0..list.length()).filter_map(|i| list.get(i)).collect()) + .unwrap_or_default(); + // The same file chosen again is a change too. + input.set_value(""); + // The keys go to the program again, not to the hidden input. + if let Some(canvas) = document() + .and_then(|d| d.get_element_by_id(CANVAS_ID)) + .and_then(|c| c.dyn_into::().ok()) + { + let _ = canvas.focus(); + } + let files = if folder { + // The folder's own files: a database's folder, not what is below it. + files + .into_iter() + .filter(|f| { + js_sys::Reflect::get(f, &"webkitRelativePath".into()) + .ok() + .and_then(|p| p.as_string()) + .is_none_or(|p| p.matches('/').count() <= 1) + }) + .collect() + } else { + files + }; + if let Some(then) = ON_PICKED.with_borrow_mut(Option::take) { + then(files); + } + }); + input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref())?; + // The input lives as long as the page. + on_change.forget(); + doc.body().ok_or("no body")?.append_child(&input)?; + Ok(input) +} + +/// Asks the user for files (the browser's dialog); `then` gets them once chosen (not +/// read: the page's reader reads them). Must run soon after the user's click or key (a +/// browser opens the dialog only then: egui handles input in the next frame, well +/// within that time). +pub fn pick_files(accept: &str, then: impl FnOnce(Vec) + 'static) { + pick(OPEN_INPUT_ID, accept, false, then); +} + +/// Asks the user for a folder; `then` gets the files right in it. +pub fn pick_folder(then: impl FnOnce(Vec) + 'static) { + pick(OPEN_FOLDER_ID, "", true, then); +} + +fn pick(id: &str, accept: &str, folder: bool, then: impl FnOnce(Vec) + 'static) { + match open_input(id, accept, folder) { + Ok(input) => { + ON_PICKED.with_borrow_mut(|p| *p = Some(Box::new(then))); + input.click(); + } + Err(e) => log::warn!("cannot choose files: {e:?}"), + } +} + +/// Gives the user `bytes` as a downloaded file named `name`. +pub fn download(name: &str, mime: &str, bytes: &[u8]) -> Result<(), JsValue> { + let doc = document().ok_or("no document")?; + let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); + let opts = web_sys::BlobPropertyBag::new(); + opts.set_type(mime); + let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts)?; + let url = web_sys::Url::create_object_url_with_blob(&blob)?; + let a: web_sys::HtmlAnchorElement = doc.create_element("a")?.dyn_into()?; + a.set_href(&url); + a.set_download(name); + a.style().set_property("display", "none")?; + let body = doc.body().ok_or("no body")?; + body.append_child(&a)?; + a.click(); + body.remove_child(&a)?; + // The download has taken the data by the next task. + wasm_bindgen_futures::spawn_local(async move { + next_task().await; + let _ = web_sys::Url::revoke_object_url(&url); + }); + Ok(()) +} diff --git a/apps/desktop/src/platform/web/remembered.rs b/apps/desktop/src/platform/web/remembered.rs new file mode 100644 index 0000000..21ae25e --- /dev/null +++ b/apps/desktop/src/platform/web/remembered.rs @@ -0,0 +1,306 @@ +//! Databases a Chromium browser remembers (Chrome, Edge: the File System Access API): +//! files chosen through `showOpenFilePicker`, or a database's folder chosen through +//! `showDirectoryPicker`, leave handles the page keeps in the browser's storage; at the +//! next visit the database is there again through them — at once when the browser still +//! allows reading, else after the user's «Allow reading» (the browser's own question). +//! Only reading: the page never writes the user's files (decisions «Веб-верÑ�иÑ�»). +//! Firefox and Safari have no such handles: there the user chooses the file again +//! ([`super::page::pick_files`]). +//! +//! What is kept for a database (its path on the page): `{handles: [file handles]}`, its +//! own file first, or `{dir: folder handle, names: [its files' names]}`; a bare file +//! handle (an earlier version) is a database of one file. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +use crate::platform::files::{Picked, gather}; + +thread_local! { + /// Databases of earlier visits the browser asks about first: the page's path, what + /// is kept for it. + static WAITING: RefCell> = RefCell::new(HashMap::new()); + /// The handle of a `.cbh` chosen alone: the folder's dialog opens where it is. + static LONE_CBH: RefCell> = const { RefCell::new(None) }; +} + +fn get(object: &JsValue, key: &str) -> JsValue { + js_sys::Reflect::get(object, &key.into()).unwrap_or(JsValue::UNDEFINED) +} + +fn set(object: &JsValue, key: &str, value: &JsValue) { + let _ = js_sys::Reflect::set(object, &key.into(), value); +} + +/// Calls `object.method(arg)` (its promise, not awaited): within the user's gesture. +fn start(object: &JsValue, method: &str, arg: &JsValue) -> Result { + let f: js_sys::Function = get(object, method).dyn_into()?; + f.call1(object, arg)?.dyn_into() +} + +/// Calls `object.method(arg)` and waits for the promise it gives. +async fn call(object: &JsValue, method: &str, arg: &JsValue) -> Result { + wasm_bindgen_futures::JsFuture::from(start(object, method, arg)?).await +} + +/// `{mode: "read"}`: the permission asked for. +fn read_mode() -> JsValue { + let o = js_sys::Object::new(); + set(&o, "mode", &"read".into()); + o.into() +} + +/// The browser remembers chosen files (it has `showOpenFilePicker`). +pub fn supported() -> bool { + web_sys::window().is_some_and(|w| get(&w, "showOpenFilePicker").is_function()) +} + +/// The browser remembers a chosen folder (it has `showDirectoryPicker`). +pub fn supported_folder() -> bool { + web_sys::window().is_some_and(|w| get(&w, "showDirectoryPicker").is_function()) +} + +async fn file_of(handle: &JsValue) -> Result { + call(handle, "getFile", &JsValue::UNDEFINED) + .await? + .dyn_into() +} + +/// Opens a dialog of the window (`showOpenFilePicker`, `showDirectoryPicker`) now, +/// within the user's gesture. +fn dialog(method: &str, options: &js_sys::Object) -> Result { + let window = web_sys::window().ok_or("no window")?; + start(&window, method, options) +} + +/// Asks the user for files (the browser's dialog, `extensions` like `.pgn`); `then` +/// gets the databases they make, each remembered. Must run soon after the user's click +/// or key, like [`super::page::pick_files`]. +pub fn pick(extensions: &[String], then: impl FnOnce(Picked) + 'static) { + let accept = js_sys::Object::new(); + let list = extensions + .iter() + .map(|e| JsValue::from_str(e)) + .collect::(); + set(&accept, "application/octet-stream", &list); + let kind = js_sys::Object::new(); + set(&kind, "accept", &accept); + let options = js_sys::Object::new(); + set(&options, "multiple", &JsValue::TRUE); + set(&options, "types", &js_sys::Array::of1(&kind)); + set(&options, "id", &"chesspenguin-databases".into()); + let chosen = dialog("showOpenFilePicker", &options); + wasm_bindgen_futures::spawn_local(async move { + // Cancelled by the user: an error, nothing chosen. + let handles: Vec = match chosen { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p) + .await + .and_then(|h| h.dyn_into::()) + .map(|a| a.to_vec()) + .unwrap_or_default(), + Err(_) => Vec::new(), + }; + let mut files = Vec::new(); + let mut kept_handles = Vec::new(); + for h in handles { + match file_of(&h).await { + Ok(f) => { + files.push(f); + kept_handles.push(h); + } + Err(e) => log::warn!("cannot read a chosen file: {e:?}"), + } + } + let (picked, kept) = gather(&files, false); + for (path, members) in kept { + let entry = js_sys::Object::new(); + let list: js_sys::Array = members.iter().map(|&i| kept_handles[i].clone()).collect(); + set(&entry, "handles", &list); + super::idb::put_handle(&path.to_string_lossy(), &entry); + } + // A .cbh alone: the folder's dialog will open beside it. + let lone = picked.incomplete.first().and_then(|name| { + files + .iter() + .position(|f| f.name() == *name) + .map(|i| kept_handles[i].clone()) + }); + LONE_CBH.with_borrow_mut(|l| *l = lone); + then(picked); + }); +} + +/// Asks the user for a database's folder; `then` gets the databases in it (the files +/// right in it, found by their names), each remembered with the folder. +pub fn pick_folder(then: impl FnOnce(Picked) + 'static) { + let options = js_sys::Object::new(); + set(&options, "id", &"chesspenguin-databases".into()); + set(&options, "mode", &"read".into()); + if let Some(cbh) = LONE_CBH.with_borrow_mut(Option::take) { + set(&options, "startIn", &cbh); + } + let chosen = dialog("showDirectoryPicker", &options); + wasm_bindgen_futures::spawn_local(async move { + let dir = match chosen { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p).await.ok(), + Err(_) => None, + }; + let Some(dir) = dir else { + return then(Picked::default()); + }; + let mut files = Vec::new(); + if let Err(e) = folder_files(&dir, &mut files).await { + log::warn!("cannot read the folder: {e:?}"); + } + let (mut picked, kept) = gather(&files, true); + for (path, members) in kept { + let entry = js_sys::Object::new(); + set(&entry, "dir", &dir); + let names: js_sys::Array = members + .iter() + .map(|&i| JsValue::from_str(&files[i].name())) + .collect(); + set(&entry, "names", &names); + super::idb::put_handle(&path.to_string_lossy(), &entry); + } + picked.empty_folder = + picked.paths.is_empty() && picked.too_big.is_empty() && picked.incomplete.is_empty(); + then(picked); + }); +} + +/// The files right in the folder `dir` (its `values()`, an asynchronous iterator). +async fn folder_files(dir: &JsValue, out: &mut Vec) -> Result<(), JsValue> { + let entries = js_sys::Reflect::apply( + &get(dir, "values").dyn_into::()?, + dir, + &js_sys::Array::new(), + )?; + loop { + let step = call(&entries, "next", &JsValue::UNDEFINED).await?; + if get(&step, "done").is_truthy() { + return Ok(()); + } + let handle = get(&step, "value"); + if get(&handle, "kind").as_string().as_deref() == Some("file") { + out.push(file_of(&handle).await?); + } + } +} + +/// What the browser is asked to let the page read: the folder, or the files. +fn targets(kept: &JsValue) -> Vec { + let dir = get(kept, "dir"); + if !dir.is_undefined() { + return vec![dir]; + } + match get(kept, "handles").dyn_into::() { + Ok(list) => list.to_vec(), + // A bare file handle. + Err(_) => vec![kept.clone()], + } +} + +/// The database's files through what is kept for it, its own first. +async fn files_of(kept: &JsValue) -> Result, JsValue> { + let dir = get(kept, "dir"); + let mut files = Vec::new(); + if dir.is_undefined() { + for h in targets(kept) { + files.push(file_of(&h).await?); + } + } else { + let names: js_sys::Array = get(kept, "names").dyn_into()?; + for name in names.iter() { + files.push(file_of(&call(&dir, "getFileHandle", &name).await?).await?); + } + } + Ok(files) +} + +/// Brings back the databases remembered at earlier visits that the browser still lets +/// the page read (nothing is read now: the page's reader reads them when opened); the +/// others wait for the user ([`waiting`], [`allow`]). Called once before the +/// interface starts. +pub async fn restore() { + if !supported() { + return; + } + for (path, kept) in super::idb::handles().await { + let path = PathBuf::from(path); + let mut granted = true; + for t in targets(&kept) { + let state = call(&t, "queryPermission", &read_mode()) + .await + .ok() + .and_then(|s| s.as_string()); + granted &= state.as_deref() == Some("granted"); + } + if !granted { + WAITING.with_borrow_mut(|w| w.insert(path, kept)); + continue; + } + match files_of(&kept).await { + Ok(files) => { + log::info!("remembered file read again: {}", path.display()); + super::vfs::put_opened(&path, files); + } + Err(e) => log::warn!("a remembered file is gone: {e:?}"), + } + } +} + +/// The browser remembers the database `path` and asks the user before it is read again. +pub fn waiting(path: &Path) -> bool { + WAITING.with_borrow(|w| w.contains_key(path)) +} + +/// Asks the browser to let the page read `path` again (its question to the user; soon +/// after the user's click). `then`: whether the database is back at its path. +pub fn allow(path: &Path, then: impl FnOnce(bool) + 'static) { + let Some(kept) = WAITING.with_borrow(|w| w.get(path).cloned()) else { + then(false); + return; + }; + let path = path.to_owned(); + // Asked now, all within the user's gesture. + let asked: Vec<_> = targets(&kept) + .iter() + .map(|t| start(t, "requestPermission", &read_mode())) + .collect(); + wasm_bindgen_futures::spawn_local(async move { + let mut granted = true; + for a in asked { + granted &= match a { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p) + .await + .ok() + .and_then(|s| s.as_string()) + .is_some_and(|s| s == "granted"), + Err(_) => false, + }; + } + let files = if granted { + files_of(&kept).await.ok() + } else { + None + }; + let back = files.is_some(); + if let Some(files) = files { + log::info!("remembered file allowed again: {}", path.display()); + WAITING.with_borrow_mut(|w| w.remove(&path)); + super::vfs::put_opened(&path, files); + } + then(back); + }); +} + +/// The database `path` is no longer the library's: the browser's handles are let go. +pub fn forget(path: &Path) { + WAITING.with_borrow_mut(|w| w.remove(path)); + super::idb::delete_handle(&path.to_string_lossy()); +} diff --git a/apps/desktop/src/platform/web/storage.rs b/apps/desktop/src/platform/web/storage.rs new file mode 100644 index 0000000..b345c95 --- /dev/null +++ b/apps/desktop/src/platform/web/storage.rs @@ -0,0 +1,72 @@ +//! What the browser gives the site to keep: the space used and left +//! (`navigator.storage.estimate()`: the site's quota, not the disk's free space) and +//! whether its data is kept for good (`persist()`: not cleared when space runs low). +//! Both are asked for in the background; the screen shows what came last. + +use std::cell::Cell; + +use wasm_bindgen::JsCast; +use wasm_bindgen_futures::JsFuture; + +thread_local! { + static USAGE: Cell> = const { Cell::new(None) }; + static PERSISTED: Cell> = const { Cell::new(None) }; +} + +fn manager() -> Option { + Some(web_sys::window()?.navigator().storage()) +} + +fn number(o: &wasm_bindgen::JsValue, key: &str) -> Option { + js_sys::Reflect::get(o, &key.into()) + .ok()? + .as_f64() + .map(|n| n as u64) +} + +/// Asks the browser again how much is used and left; `then` once it answered. +pub fn refresh(then: impl FnOnce() + 'static) { + wasm_bindgen_futures::spawn_local(async move { + if let Some(m) = manager() { + if let Ok(p) = m.estimate() + && let Ok(e) = JsFuture::from(p).await + && let (Some(usage), Some(quota)) = (number(&e, "usage"), number(&e, "quota")) + { + USAGE.set(Some((usage, quota))); + } + if let Ok(p) = m.persisted() + && let Ok(v) = JsFuture::from(p).await + { + PERSISTED.set(v.as_bool()); + } + } + then(); + }); +} + +/// (used, quota) in bytes, as the browser last said. +pub fn usage() -> Option<(u64, u64)> { + USAGE.get() +} + +/// Whether the site's data is kept for good (`None`: not known yet). +pub fn persisted() -> Option { + PERSISTED.get() +} + +/// Asks the browser to keep the site's data for good (Firefox asks the user; Chromium +/// and Safari decide themselves); `then` with the answer. +pub fn persist(then: impl FnOnce(bool) + 'static) { + wasm_bindgen_futures::spawn_local(async move { + let granted = match manager().and_then(|m| m.persist().ok()) { + Some(p) => JsFuture::from(p) + .await + .ok() + .and_then(|v| v.dyn_into::().ok()) + .is_some_and(|b| b.value_of()), + None => false, + }; + PERSISTED.set(Some(granted)); + then(granted); + }); +} diff --git a/apps/desktop/src/platform/web/vfs.rs b/apps/desktop/src/platform/web/vfs.rs new file mode 100644 index 0000000..eee561c --- /dev/null +++ b/apps/desktop/src/platform/web/vfs.rs @@ -0,0 +1,236 @@ +//! The page's file tree: files by path, in memory. The program's data (`/config`, +//! `/data`, `/cache`) is written through to the browser's storage ([`super::idb`]) and +//! read from it at the start ([`load`]); the rest lives for the session. The user's +//! files are the browser's `File`s, not their contents: the page's reader reads them +//! (`super::import`), so a database's bytes never fill the page's memory. + +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::io; +use std::path::{Path, PathBuf}; + +use crate::platform::fs::Meta; + +pub const CONFIG: &str = "/config"; +pub const DATA: &str = "/data"; +pub const CACHE: &str = "/cache"; +pub const EXAMPLES: &str = "/examples"; +pub const OPENED: &str = "/opened"; + +/// The folders kept in the browser's storage. +const KEPT: [&str; 3] = [CONFIG, DATA, CACHE]; + +struct Entry { + content: Content, + modified_ms: u64, + readonly: bool, +} + +enum Content { + Bytes(Vec), + /// A file the user gave the page: the browser reads it when asked. + File(web_sys::File), +} + +impl Content { + fn len(&self) -> u64 { + match self { + Content::Bytes(b) => b.len() as u64, + Content::File(f) => f.size() as u64, + } + } +} + +thread_local! { + static FILES: RefCell> = const { RefCell::new(BTreeMap::new()) }; + /// The number of the last file opened (each gets a folder of its own; numbered from + /// the visit's start time, so that a file of an earlier visit keeps its own). + static OPENED_COUNT: RefCell = const { RefCell::new(0) }; +} + +fn now_ms() -> u64 { + js_sys::Date::now() as u64 +} + +fn kept(path: &Path) -> bool { + KEPT.iter().any(|k| path.starts_with(k)) +} + +fn not_found(path: &Path) -> io::Error { + io::Error::new( + io::ErrorKind::NotFound, + format!("{}: no such file", path.display()), + ) +} + +/// Takes in what the browser's storage keeps; called once before the interface starts. +pub async fn load() { + let stored = super::idb::load_all().await; + FILES.with_borrow_mut(|files| { + for (path, bytes) in stored { + files.insert( + PathBuf::from(path), + Entry { + content: Content::Bytes(bytes), + modified_ms: 0, + readonly: false, + }, + ); + } + }); +} + +/// The file's bytes; a user's file is read by the page's reader instead +/// ([`source`]). +pub fn read(path: &Path) -> io::Result> { + FILES.with_borrow( + |files| match &files.get(path).ok_or_else(|| not_found(path))?.content { + Content::Bytes(b) => Ok(b.clone()), + Content::File(_) => Err(io::Error::new( + io::ErrorKind::Unsupported, + "the user's file is read by the page's reader", + )), + }, + ) +} + +/// The file for the page's reader: its bytes (a `Uint8Array`) or the user's `File`. +pub fn source(path: &Path) -> io::Result { + FILES.with_borrow(|files| { + Ok( + match &files.get(path).ok_or_else(|| not_found(path))?.content { + Content::Bytes(b) => js_sys::Uint8Array::from(b.as_slice()).into(), + Content::File(f) => f.clone().into(), + }, + ) + }) +} + +pub fn meta(path: &Path) -> io::Result { + FILES.with_borrow(|files| { + files + .get(path) + .map(|e| Meta { + len: e.content.len(), + modified_ms: e.modified_ms, + readonly: e.readonly, + }) + .ok_or_else(|| not_found(path)) + }) +} + +pub fn write(path: &Path, bytes: Vec) -> io::Result<()> { + let keep = kept(path); + FILES.with_borrow_mut(|files| { + if files.get(path).is_some_and(|e| e.readonly) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("{}: only read", path.display()), + )); + } + if keep { + super::idb::put(path.to_string_lossy().into_owned(), bytes.clone()); + } + files.insert( + path.to_owned(), + Entry { + content: Content::Bytes(bytes), + modified_ms: now_ms(), + readonly: false, + }, + ); + Ok(()) + }) +} + +pub fn remove(path: &Path) -> io::Result<()> { + FILES.with_borrow_mut(|files| { + files.remove(path).ok_or_else(|| not_found(path))?; + if kept(path) { + super::idb::delete(path.to_string_lossy().into_owned()); + } + Ok(()) + }) +} + +/// The files right in the folder `dir`. +pub fn list(dir: &Path) -> Vec { + FILES.with_borrow(|files| { + files + .keys() + .filter(|p| p.parent() == Some(dir)) + .cloned() + .collect() + }) +} + +/// A database the user gave the page (chosen, dropped, found in a chosen folder): +/// its files (its own first: a ChessBase database's `.cbh`, then its other files), +/// kept for the session, only read, in a folder of their own; the path of the first. +pub fn add_opened(files: Vec) -> PathBuf { + let n = OPENED_COUNT.with_borrow_mut(|n| { + *n = (*n + 1).max(now_ms()); + *n + }); + let path = Path::new(OPENED) + .join(n.to_string()) + .join(files.first().map(name_of).unwrap_or_default()); + put_opened(&path, files); + path +} + +/// A database of an earlier visit the browser let the page read again, at its old +/// path (its other files beside it). +pub fn put_opened(path: &Path, files: Vec) { + let dir = path.parent().unwrap_or(Path::new(OPENED)).to_owned(); + FILES.with_borrow_mut(|entries| { + for (i, f) in files.into_iter().enumerate() { + let at = if i == 0 { + path.to_owned() + } else { + dir.join(name_of(&f)) + }; + entries.insert( + at, + Entry { + content: Content::File(f), + modified_ms: now_ms(), + readonly: true, + }, + ); + } + }); +} + +/// A file's name, not a path (a browser gives no folders; this makes sure). +fn name_of(f: &web_sys::File) -> String { + let name = f.name(); + name.rsplit(['/', '\\']).next().unwrap_or(&name).to_owned() +} + +/// The files of the database `path` for the page's reader: (name, [`source`]); a +/// ChessBase database's `.cbh` with the files of its name beside it. +pub fn database_files(path: &Path) -> io::Result> { + let name = |p: &Path| { + p.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default() + }; + let mut out = vec![(name(path), source(path)?)]; + let cbh = path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("cbh")); + if cbh && let Some(dir) = path.parent() { + let stem = |p: &Path| { + p.file_stem() + .map(|s| s.to_string_lossy().to_lowercase()) + .unwrap_or_default() + }; + for p in list(dir) { + if p != path && stem(&p) == stem(path) { + out.push((name(&p), source(&p)?)); + } + } + } + Ok(out) +} diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs new file mode 100644 index 0000000..6d0055b --- /dev/null +++ b/apps/desktop/src/play.rs @@ -0,0 +1,2120 @@ +//! Playing against Maia (docs/research/play-mode.md, docs/design/play-mode.md): time +//! controls as on Lichess, the clock, the end of a game, and Maia's moves computed in a +//! background thread with a human-like pause. + +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use web_time::Instant; + +use chess_core::shakmaty::{Chess, Color, Move, Position}; +use serde::{Deserialize, Serialize}; + +use crate::i18n::tr; +use crate::maia_download::Published; +pub use ::play::rodent::{Gen, STYLES, Style, style}; +pub use ::play::{ + Ending, HOPELESS_TURNS, Judge, MAIA_MAX, MAIA_MIN, ending, hopeless, pause, random_unit, +}; +use maia::strength::Model; + +// ----- time controls -------------------------------------------------------------------- + +/// A clock: base seconds and increment seconds; `None` in the settings is "no clock". +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TimeControl { + pub base: u32, + pub increment: u32, +} + +/// The pools of Lichess (lila `PoolList.scala`) from 3+0: no bullet (the owner's choice: +/// against Maia the fastest is 3+0). +pub const PRESETS: [TimeControl; 9] = [ + TimeControl { + base: 180, + increment: 0, + }, + TimeControl { + base: 180, + increment: 2, + }, + TimeControl { + base: 300, + increment: 0, + }, + TimeControl { + base: 300, + increment: 3, + }, + TimeControl { + base: 600, + increment: 0, + }, + TimeControl { + base: 600, + increment: 5, + }, + TimeControl { + base: 900, + increment: 10, + }, + TimeControl { + base: 1800, + increment: 0, + }, + TimeControl { + base: 1800, + increment: 20, + }, +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Speed { + Blitz, + Rapid, + Classical, +} + +impl Speed { + pub fn name(self) -> &'static str { + match self { + Speed::Blitz => tr("Blitz"), + Speed::Rapid => tr("Rapid"), + Speed::Classical => tr("Classical"), + } + } +} + +impl TimeControl { + /// The category by the estimated length, base + 40 × increment (scalachess + /// `Speed.scala`; nothing here is faster than 3+0, a blitz). + pub fn speed(self) -> Speed { + match self.base + 40 * self.increment { + 0..480 => Speed::Blitz, + 480..1500 => Speed::Rapid, + _ => Speed::Classical, + } + } + + /// «5+3» as Lichess writes it (minutes + seconds). + pub fn label(self) -> String { + format!("{}+{}", self.base / 60, self.increment) + } + + /// The fastest control offered: 3+0. + pub fn allowed(self) -> bool { + self.base >= 180 + } + + /// The PGN tag `TimeControl`: seconds + increment. + pub fn pgn(self) -> String { + format!("{}+{}", self.base, self.increment) + } +} + +/// The minutes the custom control offers (Lichess `timeControl.ts` from 3), in seconds. +pub const CUSTOM_BASES: &[u32] = &[ + 180, 240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900, 960, 1020, 1080, 1140, 1200, + 1500, 1800, 2100, 2400, 2700, 3600, 4500, 5400, 6300, 7200, 8100, 9000, 9900, 10800, +]; +pub const CUSTOM_INCREMENTS: &[u32] = &[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 35, 40, 45, + 60, 90, 120, 150, 180, +]; + +/// The colour the user asks for. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ColorChoice { + White, + #[default] + Random, + Black, +} + +/// The last choices of the play dialog (settings). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PlayPrefs { + pub color: ColorChoice, + /// `None`: no clock. + pub clock: Option, + /// The opponent's strength on its own scale: Maia's rating, Rodent's UCI_Elo + /// (decisions «Сила Ñ�оперника — по шкале Ñ�амого движка»). Kept as `level`. + #[serde(rename = "level")] + pub strength: u32, + /// The opponent: Maia or Rodent, and Rodent's style (a personality file's name). + pub rival: Rival, + pub style: String, +} + +/// Who plays against the user. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Rival { + /// Maia: human moves of a strength, human mistakes (docs/research/maia-strength.md). + #[default] + Maia, + /// Rodent V: a strong engine with a style (docs/research/rodent.md). + Rodent, +} + +/// Downloading each Rodent (the engines' tables are the shared crate's, `play::rodent`). +pub trait RodentFiles { + fn available(self) -> bool; + fn installed(self) -> Option; + fn size_mb(self) -> u64; + fn start(self, ctx: &egui::Context) -> crate::engine_download::Download; + /// A file that does not start goes: the dialog offers the download again. + fn remove(self); +} + +impl RodentFiles for Gen { + fn available(self) -> bool { + match self { + Gen::V => crate::rodent_download::available(), + Gen::IV => crate::rodent4_download::available(), + } + } + + fn installed(self) -> Option { + match self { + Gen::V => crate::rodent_download::installed(), + Gen::IV => crate::rodent4_download::installed(), + } + } + + fn size_mb(self) -> u64 { + match self { + Gen::V => crate::rodent_download::size_mb(), + Gen::IV => crate::rodent4_download::size_mb(), + } + } + + fn start(self, ctx: &egui::Context) -> crate::engine_download::Download { + match self { + Gen::V => crate::rodent_download::start(ctx), + Gen::IV => crate::rodent4_download::start(ctx), + } + } + + fn remove(self) { + let _ = match self { + Gen::V => crate::rodent_download::remove(), + Gen::IV => crate::rodent4_download::remove(), + }; + } +} + +/// «Attacking — Ampere»; «Balanced», «Tal»: no name twice. +fn style_label(st: &Style) -> String { + let title = tr(st.title()); + // The default one is Rodent himself, the players' are named by their title, and so + // are Rodent IV's characters (their titles are their names, translated). + if st.player || st.id == "rodent" || st.title() == st.name { + title.to_owned() + } else { + format!("{title} — {}", st.name) + } +} + +impl Default for PlayPrefs { + fn default() -> Self { + PlayPrefs { + color: ColorChoice::Random, + clock: Some(TimeControl { + base: 600, + increment: 5, + }), + strength: 1500, + rival: Rival::Maia, + style: STYLES[0].id.to_owned(), + } + } +} + +// ----- the opponent's strength --------------------------------------------------------- + +// Each engine on its own scale, as its authors give it (the owner's decision, after the +// measurements of docs/research/maia-strength.md and rodent.md): these are not a +// person's Elo, and the dialog says so. The scales are the shared crate's (`play`). + +/// The strengths `rival` plays (Rodent's by the engine of the style chosen). +pub fn range(rival: Rival, style_id: &str) -> (u32, u32) { + match rival { + Rival::Maia => (MAIA_MIN, MAIA_MAX), + Rival::Rodent => style(style_id).rodent.range(), + } +} + +/// The Maia that plays, with its file: the large one when it is there, else the small +/// one. `Err`: the model to download. +pub fn model_for() -> Result<(Model, std::path::PathBuf), Model> { + use crate::maia_download::installed; + if let Some(p) = installed(Model::Large) { + return Ok((Model::Large, p)); + } + installed(Model::Small) + .map(|p| (Model::Small, p)) + .ok_or(Model::Large) +} + +// ----- the clock ----------------------------------------------------------------------- + +/// Both clocks. Time runs for the side to move from the moment its opponent moved; a +/// side's first move takes no time (Lichess); the increment comes after the move. +#[derive(Clone, Debug)] +pub struct Clock { + pub control: TimeControl, + left: [Duration; 2], + moved: [bool; 2], + running: Option<(Color, Instant)>, +} + +fn idx(c: Color) -> usize { + match c { + Color::White => 0, + Color::Black => 1, + } +} + +impl Clock { + pub fn new(control: TimeControl) -> Clock { + // A base of 0 starts from the increment, at least 3 s (scalachess). + let start = if control.base == 0 { + Duration::from_secs(u64::from(control.increment.max(3))) + } else { + Duration::from_secs(u64::from(control.base)) + }; + Clock { + control, + left: [start; 2], + moved: [false; 2], + running: None, + } + } + + /// A clock going on from a game put aside: the time each side had left, whether it + /// has moved (its first move is free), the side to move's clock running from `now`. + pub fn resumed( + control: TimeControl, + left: [Option; 2], + to_move: Color, + now: Instant, + ) -> Clock { + let mut c = Clock::new(control); + for side in [Color::White, Color::Black] { + if let Some(d) = left[idx(side)] { + c.left[idx(side)] = d; + c.moved[idx(side)] = true; + } + } + c.running = Some((to_move, now)); + c + } + + /// The time left of `c` at `now`. + pub fn left(&self, c: Color, now: Instant) -> Duration { + let base = self.left[idx(c)]; + match self.running { + Some((r, since)) if r == c && self.moved[idx(c)] => base.saturating_sub(now - since), + _ => base, + } + } + + /// `c` has moved: its time is taken (not on its first move), the increment added, + /// the other side's clock starts. `spent`: the time to take instead of what passed + /// (Maia's pause: the program's own computing is not her thinking). + pub fn moved(&mut self, c: Color, now: Instant, spent: Option) { + let i = idx(c); + if self.moved[i] { + self.left[i] = match spent { + Some(d) => self.left[i].saturating_sub(d), + None => self.left(c, now), + }; + } + self.moved[i] = true; + self.left[i] += Duration::from_secs(u64::from(self.control.increment)); + self.running = Some((!c, now)); + } + + /// A take-back: `side` moves now (its clock runs from `now`); `moved`: it has + /// moved before in the game left (else its next move is its first, free one). + pub fn take_back(&mut self, side: Color, moved: bool, now: Instant) { + if let Some((c, since)) = self.running + && self.moved[idx(c)] + { + self.left[idx(c)] = self.left[idx(c)].saturating_sub(now - since); + } + self.moved[idx(side)] = moved; + self.running = Some((side, now)); + } + + /// The side to move, its clock running (after its first move). + pub fn running(&self) -> Option { + self.running.map(|(c, _)| c).filter(|c| self.moved[idx(*c)]) + } + + /// The clocks waited (a question about leaving was open): the running one is moved + /// on by `d`, as if no time passed. + pub fn pause(&mut self, d: Duration) { + if let Some((_, since)) = self.running.as_mut() { + *since += d; + } + } + + pub fn stop(&mut self, now: Instant) { + if let Some((c, _)) = self.running { + self.left[idx(c)] = self.left(c, now); + } + self.running = None; + } + + /// The low-time threshold: min(60, max(10, base / 8)) seconds (scalachess). + pub fn low(&self) -> Duration { + Duration::from_secs(u64::from((self.control.base / 8).clamp(10, 60))) + } +} + +/// «4:58», «1:02:03», «0:09.4» (tenths under 10 s). +pub fn clock_text(d: Duration) -> String { + let ms = d.as_millis(); + let s = ms / 1000; + if s >= 3600 { + format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60) + } else if ms < 10_000 { + format!("0:{:02}.{}", s, ms / 100 % 10) + } else { + format!("{}:{:02}", s / 60, s % 60) + } +} + +/// `[%clk 0:04:58]` for the PGN. +pub fn clk_command(d: Duration) -> String { + let s = d.as_secs(); + format!("[%clk {}:{:02}:{:02}]", s / 3600, s / 60 % 60, s % 60) +} + +/// The time each side had left in a game put aside (white, black; `None`: it has not +/// moved): the `[%clk]` of its last move among those played after `floor` half-moves; +/// the side to move's `to_move` when it is known (its time when the game was put aside). +pub fn times_left( + game: &chess_core::Game, + floor: usize, + to_move: Option, +) -> [Option; 2] { + let mut left = [None, None]; + let line = game.mainline(); + for &id in line.iter().skip(floor) { + let mover = game.position_before(id).map(|p| p.turn()); + let clk = game + .node(id) + .and_then(|n| n.comments_after().iter().find_map(|c| clk_of(c))); + if let (Some(m), Some(t)) = (mover, clk) { + left[idx(m)] = Some(t); + } + } + let end = line.last().copied().unwrap_or(chess_core::NodeId::ROOT); + if let (Some(t), Some(p)) = (to_move, game.position(end)) { + left[idx(p.turn())] = Some(t); + } + left +} + +/// The game of a PGN text (a journal's: one game, UTF-8). +pub fn parse_game(pgn: &str) -> Option { + let never = std::sync::atomic::AtomicBool::new(false); + let db = chess_core::PgnDatabase::from_bytes( + pgn.as_bytes().to_vec(), + Some(chess_core::TextEncoding::Utf8), + &mut |_| {}, + &never, + ) + .ok()?; + db.load_game(0).map(|p| p.game) +} + +/// The time a `[%clk h:mm:ss]` of a comment says. +pub fn clk_of(comment: &str) -> Option { + // The PGN writer may break the line after «[%clk». + let rest = &comment[comment.find("[%clk")? + 5..]; + let text = &rest[..rest.find(']')?]; + let mut secs = 0u64; + for part in text.trim().split(':') { + // Seconds may have a fraction («0:03:12.4»): whole ones are enough. + let whole = part.split('.').next()?.parse::().ok()?; + secs = secs * 60 + whole; + } + Some(Duration::from_secs(secs)) +} + +// ----- the opponent's moves ------------------------------------------------------------- + +/// A request for Maia's move: the positions up to now, the ratings, the pause. +struct Request { + generation: u64, + positions: Vec, + self_elo: u32, + oppo_elo: u32, + temperature: f32, + pause: Duration, +} + +/// The engine judging a game (Stockfish at `exe`), waking `ctx` with its answers. +/// A browser starts no engine processes: there is no judge there, and the game goes +/// without resignations, as when the engine does not start. +pub fn start_judge(exe: crate::engines::EngineLocation, ctx: &egui::Context) -> Option { + #[cfg(not(web))] + { + let crate::engines::EngineLocation::Program(exe) = exe; + let ctx = ctx.clone(); + Some(Judge::start( + uci::EngineConfig::new(exe), + Vec::new(), + Box::new(move || ctx.request_repaint()), + )) + } + #[cfg(web)] + { + let _ = (exe, ctx); + None + } +} + +/// What computes the opponent's moves. +enum Worker { + /// Maia in a thread of her own; her error, if loading failed. + Maia { + tx: Sender, + rx: Receiver<(u64, Option, Duration)>, + generation: u64, + error: Arc>>, + }, + /// Rodent, a UCI engine (the shared crate's player): a process, not in a browser. + #[cfg(not(web))] + Rodent(::play::rodent::RodentPlayer), +} + +/// The engine in a thread of its own: loads Maia once (or starts Rodent), answers +/// requests after a pause. An answer for an older request (after a take-back, a +/// resignation) is dropped. +pub struct Opponent { + worker: Worker, + pub thinking: bool, +} + +impl Opponent { + pub fn start(weights: std::path::PathBuf, ctx: &egui::Context) -> Opponent { + let (tx, req_rx) = channel::(); + let (ans_tx, rx) = channel(); + let error = Arc::new(Mutex::new(None)); + let err = error.clone(); + let ctx = ctx.clone(); + let _ = std::thread::Builder::new() + .name("maia".into()) + .spawn(move || { + let maia = match maia::Maia::load(&weights) { + Ok(m) => m, + Err(e) => { + if let Ok(mut g) = err.lock() { + *g = Some(e.to_string()); + } + ctx.request_repaint(); + return; + } + }; + while let Ok(mut r) = req_rx.recv() { + // Only the newest request counts. + while let Ok(newer) = req_rx.try_recv() { + r = newer; + } + let started = Instant::now(); + let p = maia.predict(&r.positions, r.self_elo, r.oppo_elo); + let m = maia::strength::choose(&p, r.temperature, random_unit()); + let rest = r.pause.saturating_sub(started.elapsed()); + std::thread::sleep(rest); + // Her clock: the pause, or the computing when it took longer (a slow + // computer, the large model). + let spent = r.pause.max(started.elapsed()); + if ans_tx.send((r.generation, m, spent)).is_err() { + return; + } + ctx.request_repaint(); + } + }); + Opponent { + worker: Worker::Maia { + tx, + rx, + generation: 0, + error, + }, + thinking: false, + } + } + + /// Asks for a move in the last of `positions` (`engine_pos`: the same for a UCI + /// engine). + pub fn ask( + &mut self, + positions: Vec, + engine_pos: Option, + (self_elo, temperature): (u32, f32), + oppo_elo: u32, + pause: Duration, + ) { + self.thinking = true; + match &mut self.worker { + Worker::Maia { tx, generation, .. } => { + *generation += 1; + let _ = tx.send(Request { + generation: *generation, + positions, + self_elo, + oppo_elo, + temperature, + pause, + }); + } + #[cfg(not(web))] + Worker::Rodent(player) => { + if let (Some(pos), Some(now)) = (engine_pos, positions.last().cloned()) { + player.ask(pos, now, pause); + } + } + } + } + + /// Rodent (`exe` in its folder) playing in `style` at `uci_elo` (none: full + /// strength), with its opening book. + #[cfg(not(web))] + pub fn start_rodent( + exe: std::path::PathBuf, + style: String, + uci_elo: Option, + ctx: &egui::Context, + ) -> Opponent { + let config = uci::EngineConfig { + working_dir: exe.parent().map(|d| d.to_path_buf()), + ..uci::EngineConfig::new(&exe) + }; + let ctx = ctx.clone(); + let player = ::play::rodent::RodentPlayer::start( + config, + &style, + uci_elo, + true, + Box::new(move || ctx.request_repaint()), + ); + Opponent { + worker: Worker::Rodent(player), + thinking: false, + } + } + + /// An opponent that did not start, for `why`: the game ends at once with it (in a + /// browser, which starts no engine processes, Rodent). + #[cfg(web)] + pub fn not_started(why: String) -> Opponent { + let (tx, _) = channel(); + let (_, rx) = channel(); + Opponent { + worker: Worker::Maia { + tx, + rx, + generation: 0, + error: Arc::new(Mutex::new(Some(why))), + }, + thinking: false, + } + } + + /// Forgets what was asked (its answer will be dropped). + pub fn forget(&mut self) { + match &mut self.worker { + Worker::Maia { generation, .. } => *generation += 1, + #[cfg(not(web))] + Worker::Rodent(player) => player.forget(), + } + self.thinking = false; + } + + /// The move asked for last, when it has come, with the time it took (its pause, or + /// the computing when longer). + pub fn answer(&mut self) -> Option<(Move, Duration)> { + let mut out = None; + match &mut self.worker { + Worker::Maia { rx, generation, .. } => { + while let Ok((g, m, pause)) = rx.try_recv() { + if g == *generation { + self.thinking = false; + out = m.map(|m| (m, pause)); + } + } + } + #[cfg(not(web))] + Worker::Rodent(player) => { + if let Some((m, pause)) = player.answer() { + self.thinking = false; + out = m.map(|m| (m, pause)); + } + } + } + out + } + + pub fn failed(&self) -> Option { + match &self.worker { + Worker::Maia { error, .. } => error.lock().ok().and_then(|g| g.clone()), + #[cfg(not(web))] + Worker::Rodent(player) => player.failure().map(|f| match f { + ::play::rodent::Failure::Start(e) => start_failure(&e), + ::play::rodent::Failure::Stopped => tr("it stopped while playing").to_owned(), + ::play::rodent::Failure::Search(e) => e, + }), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::shakmaty::uci::UciMove; + + #[test] + fn the_time_of_a_clk_comment() { + assert_eq!(clk_of("[%clk 0:03:12]"), Some(Duration::from_secs(192))); + assert_eq!( + clk_of("Good move [%clk 1:00:05.3] [%cal Ge2e4]"), + Some(Duration::from_secs(3605)) + ); + assert_eq!( + clk_of(&clk_command(Duration::from_secs(4321))), + Some(Duration::from_secs(4321)) + ); + assert_eq!(clk_of("[%clk\n0:04:11]"), Some(Duration::from_secs(251))); + assert_eq!(clk_of("no clock"), None); + } + + #[test] + fn a_clock_goes_on_from_the_times_left() { + let now = Instant::now(); + let tc = TimeControl { + base: 300, + increment: 3, + }; + let c = Clock::resumed( + tc, + [Some(Duration::from_secs(250)), None], + Color::Black, + now, + ); + assert_eq!(c.left(Color::White, now), Duration::from_secs(250)); + // Black has not moved: its first move is free, its time the base. + assert_eq!( + c.left(Color::Black, now + Duration::from_secs(9)), + Duration::from_secs(300) + ); + assert_eq!(c.running(), None); + // Both have moved: the side to move's clock runs from the moment it goes on. + let c = Clock::resumed( + tc, + [ + Some(Duration::from_secs(250)), + Some(Duration::from_secs(200)), + ], + Color::White, + now, + ); + assert_eq!(c.running(), Some(Color::White)); + assert_eq!( + c.left(Color::White, now + Duration::from_secs(10)), + Duration::from_secs(240) + ); + assert_eq!( + c.left(Color::Black, now + Duration::from_secs(10)), + Duration::from_secs(200) + ); + } + + #[test] + fn speeds_as_lichess() { + let s = |base, increment| TimeControl { base, increment }.speed(); + assert_eq!(s(180, 0), Speed::Blitz); + assert_eq!(s(300, 3), Speed::Blitz); + assert_eq!(s(420, 0), Speed::Blitz); + assert_eq!(s(480, 0), Speed::Rapid); + assert_eq!(s(900, 10), Speed::Rapid); + assert_eq!(s(1500, 0), Speed::Classical); + assert_eq!( + TimeControl { + base: 300, + increment: 3 + } + .label(), + "5+3" + ); + // Nothing faster than 3+0; every preset and custom minute allowed. + assert!( + !TimeControl { + base: 120, + increment: 1 + } + .allowed() + ); + assert!(PRESETS.iter().all(|t| t.allowed())); + assert!(CUSTOM_BASES.iter().all(|&b| { + TimeControl { + base: b, + increment: 0, + } + .allowed() + })); + assert_eq!( + PlayPrefs::default().clock.map(|t| t.label()).as_deref(), + Some("10+5") + ); + assert_eq!( + TimeControl { + base: 300, + increment: 3 + } + .pgn(), + "300+3" + ); + } + + #[test] + fn clock_runs_after_first_moves() { + let mut c = Clock::new(TimeControl { + base: 60, + increment: 2, + }); + let t0 = Instant::now(); + c.moved(Color::White, t0, None); // the first move takes nothing + assert_eq!(c.left(Color::White, t0), Duration::from_secs(62)); + // Black's first move: no time taken either. + c.moved(Color::Black, t0 + Duration::from_secs(5), None); + assert_eq!( + c.left(Color::Black, t0 + Duration::from_secs(5)), + Duration::from_secs(62) + ); + // White thinks 10 s. + let t1 = t0 + Duration::from_secs(15); + assert_eq!(c.left(Color::White, t1), Duration::from_secs(52)); + c.moved(Color::White, t1, None); + assert_eq!(c.left(Color::White, t1), Duration::from_secs(54)); + assert_eq!(c.running(), Some(Color::Black)); + assert_eq!(clock_text(Duration::from_millis(9_450)), "0:09.4"); + assert_eq!(clock_text(Duration::from_secs(298)), "4:58"); + assert_eq!(clock_text(Duration::from_secs(3723)), "1:02:03"); + assert_eq!(clk_command(Duration::from_secs(298)), "[%clk 0:04:58]"); + assert_eq!( + Clock::new(TimeControl { + base: 180, + increment: 0 + }) + .low(), + Duration::from_secs(22) + ); + } + + fn play(moves: &[&str]) -> Vec { + let mut pos = Chess::default(); + let mut out = vec![pos.clone()]; + for m in moves { + let m = m.parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(m); + out.push(pos.clone()); + } + out + } + + #[test] + fn endings() { + let mate = play(&["f2f3", "e7e5", "g2g4", "d8h4"]); + assert_eq!( + ending(&mate), + Some(Ending::Checkmate { + winner: Color::Black + }) + ); + let rep = play(&[ + "g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8", + ]); + assert_eq!(ending(&rep), Some(Ending::Threefold)); + assert_eq!(ending(&rep[..rep.len() - 1]), None); + assert_eq!(ending(&play(&["e2e4"])), None); + assert_eq!( + Ending::Time { + loser: Color::White, + draw: false + } + .result(), + chess_core::GameResult::BlackWins + ); + } + + #[test] + fn pauses_never_lose_on_time() { + // Whole games of 300 moves at 1+0, 3+0, 5+0 with 0.1 s of computing per move. + for base in [60.0f32, 180.0, 300.0] { + for _ in 0..20 { + let mut left = base; + for ply in 0..300 { + let p = pause(Some((Duration::from_secs_f32(left), 0)), ply * 2, false); + left -= p.as_secs_f32(); + assert!(left > 0.0, "flagged at {ply} with {base}"); + } + } + } + } +} + +// ----- a game being played ------------------------------------------------------------ + +/// A game against Maia in progress (lives in the game screen while it is played). +pub struct Session { + /// The game kept for the player's database (none: not written by itself). + pub journal: Option, + pub user: Color, + /// The opponent's strength (Lichess blitz scale), what plays it and in which style. + pub strength: u32, + pub engine: Engine, + pub style: String, + pub user_elo: Option, + pub clock: Option, + pub opponent: Opponent, + /// «Resign?» waits for the second click. + pub resign_asked: bool, + /// The player's clock got low and was heard (once a game). + pub low_time_heard: bool, + /// The engine judging the game for Maia's resignation (none without an engine). + pub judge: Option, + /// Maia's turns in a row with her position hopeless. + pub hopeless: u32, + /// Maia offers to resign: since when the offer is open (the clocks wait). + pub resign_offer: Option, + /// «Play to the end»: no more offers in this game. + pub play_on: bool, + /// The last move of the game it goes on from (`ROOT`: a game from the start): the + /// moves up to it are not taken back and do not count as played. + pub floor: chess_core::NodeId, +} + +/// What a game against the computer is played with, kept in its journal so that it can +/// go on later (a game put aside, docs/design/desktop-adjourned.md). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Saved { + pub white: bool, + pub strength: u32, + pub rival: Rival, + pub style: String, + pub user_elo: Option, + pub user_name: String, + pub clock: Option, + /// Half-moves of the game it went on from (not played here: not taken back). + pub floor: usize, + /// That game and its move, as the note and a rematch name them. + pub from_game: Option, + pub from_after: Option, + pub from_after_shown: Option, +} + +impl Saved { + /// The start of the game again, with the position it went on from (rebuilt from the + /// game itself) for a rematch. + pub fn start(&self, from: Option) -> Start { + Start { + user: if self.white { + Color::White + } else { + Color::Black + }, + strength: self.strength, + rival: self.rival, + style: self.style.clone(), + user_elo: self.user_elo, + user_name: self.user_name.clone(), + clock: self.clock, + from: from.map(|mut f| { + f.game = self.from_game.clone(); + f.after = self.from_after.clone(); + f.after_shown = self.from_after_shown.clone(); + Box::new(f) + }), + } + } +} + +/// What the play dialog starts. +#[derive(Clone, Debug)] +pub struct Start { + pub user: Color, + pub strength: u32, + pub rival: Rival, + /// Rodent's style (ignored for Maia). + pub style: String, + pub user_elo: Option, + pub user_name: String, + pub clock: Option, + /// A game from a position of another game (docs/design/play-from-position.md). + pub from: Option>, +} + +impl Start { + /// What the game is played with, for its journal; `floor`: half-moves it went on from. + pub fn saved(&self, floor: usize) -> Saved { + Saved { + white: self.user == Color::White, + strength: self.strength, + rival: self.rival, + style: self.style.clone(), + user_elo: self.user_elo, + user_name: self.user_name.clone(), + clock: self.clock, + floor, + from_game: self.from.as_ref().and_then(|f| f.game.clone()), + from_after: self.from.as_ref().and_then(|f| f.after.clone()), + from_after_shown: self.from.as_ref().and_then(|f| f.after_shown.clone()), + } + } + + /// The opponent as the game names it: «Maia 1500», «Rodent V 2400 (Tal)». + pub fn rival_name(&self) -> String { + rival_name(self.rival, self.strength, &self.style) + } +} + +/// A text about the opponent in the app's language: Maia's, or Rodent's (their own +/// sentences: in Russian and other languages the words agree with her or him). +pub fn said(rival: Rival, maia: &'static str, rodent: &'static str) -> &'static str { + tr(match rival { + Rival::Maia => maia, + Rival::Rodent => rodent, + }) +} + +/// What plays a game: a Maia model, or Rodent V. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Engine { + Maia(Model), + Rodent(Gen), +} + +impl Engine { + /// Maia's rating and temperature for `strength`: the rating itself, her moves drawn + /// as she predicts them (Rodent takes its strength as UCI_Elo when it starts). + pub fn input(self, strength: u32) -> (u32, f32) { + match self { + Engine::Maia(_) => (strength, 1.0), + Engine::Rodent(_) => (0, 0.0), + } + } +} + +/// The opponent of `start`, ready to play: its engine and file; `None`: it has to be +/// downloaded first (the dialog offers it). +pub fn engine_for(start: &Start) -> Option<(Engine, std::path::PathBuf)> { + match start.rival { + Rival::Maia => model_for().ok().map(|(m, p)| (Engine::Maia(m), p)), + Rival::Rodent => { + let g = style(&start.style).rodent; + g.installed().map(|p| (Engine::Rodent(g), p)) + } + } +} + +/// Dev hook `CP_RIVAL=rodent[:style]`: the opponent of a game started by a hook. +pub fn debug_rival() -> (Rival, String) { + match std::env::var("CP_RIVAL") + .ok() + .as_deref() + .map(|v| v.split_once(':').unwrap_or((v, STYLES[0].id))) + { + Some(("rodent", style)) => (Rival::Rodent, style.to_owned()), + _ => (Rival::Maia, STYLES[0].id.to_owned()), + } +} + +/// «Maia 1500», «Rodent V 2400», «Rodent V 2400 (Tal)», «Rodent IV 2000 (Petrosian)» +/// (the default style unnamed). +pub fn rival_name(rival: Rival, strength: u32, style_id: &str) -> String { + match rival { + Rival::Maia => format!("Maia {strength}"), + Rival::Rodent => ::play::rodent::name(strength, style_id), + } +} + +impl Session { + pub fn rival(&self) -> Rival { + match self.engine { + Engine::Maia(_) => Rival::Maia, + Engine::Rodent(_) => Rival::Rodent, + } + } + + /// The opponent on its bar: «Maia 1500», «Rodent V 2400». + pub fn rival_label(&self) -> String { + match self.engine { + Engine::Maia(_) => format!("Maia {}", self.strength), + Engine::Rodent(g) => format!("{} {}", g.name(), self.strength), + } + } + + /// Rodent's style, under his name on the bar (none for Maia and the default style). + pub fn rival_style(&self) -> Option<&'static str> { + (self.rival() == Rival::Rodent && self.style != STYLES[0].id) + .then(|| tr(style(&self.style).title())) + } +} + +/// Where a game against Maia starts when it goes on from a game: its start and the +/// moves to the chosen one (the history Maia and the repetitions need). +#[derive(Clone, Debug)] +pub struct StartFrom { + /// The FEN of the game's start (`None`: the standard position) — after the last + /// null move of the path, if there is one. + pub start_fen: Option, + /// The moves from that start to the chosen position. + pub moves: Vec, + /// The position played from. + pub position: Chess, + /// Its last move, for the board (from, to). + pub last: Option<(chess_core::shakmaty::Square, chess_core::shakmaty::Square)>, + /// «14...Ke7» — the move played from (SAN, as data); `None`: the game's start. + pub after: Option, + /// The same as shown («14…Ке7»). + pub after_shown: Option, + /// «Carlsen — Caruana, Wijk aan Zee 2024», when the game says so. + pub game: Option, + /// Null moves before the position were left out. + pub null_dropped: bool, +} + +// ----- the dialog --------------------------------------------------------------------- + +/// «Play against the computer»: name and rating, colour, time, strength. +pub struct Dialog { + name: String, + rating: String, + prefs: PlayPrefs, + custom: bool, + download: Option, + /// Rodent's download (docs/design/rodent-opponent.md §6): which one, and how it goes. + rodent_download: Option<(Gen, crate::engine_download::Download)>, + /// «Download and play» was pressed: the game starts once Maia is there. + play_after: bool, + /// The game goes on from a position of another game. + from: Option, + /// The colour chosen is this game's, not a habit to remember (from a position, a + /// rematch). + keep_color: bool, + focus: bool, + /// The number of games of the players' databases read so far (the app fills it). + pub counts: std::collections::HashMap, + /// Whether the database the games go to is there (the app tells, from the files as + /// last found: no disk in the frame). + pub target_there: bool, + /// Where the games of the name typed go: for that name (found once per name). + target: Option<(String, std::path::PathBuf)>, +} + +pub enum DialogOutcome { + Play(Start), + Cancel, +} + +impl Dialog { + pub fn new(settings: &crate::settings::Settings) -> Dialog { + let mut prefs = settings.play.clone(); + // A bullet control remembered from before: the default instead. + if prefs.clock.is_some_and(|c| !c.allowed()) { + prefs.clock = PlayPrefs::default().clock; + } + // A remembered strength the opponent does not play (another build's range, an + // edited file): to the nearest one that is played. + // A style whose Rodent is not for this system: one that is, else Maia. + if prefs.rival == Rival::Rodent && !style(&prefs.style).rodent.available() { + match STYLES.iter().find(|s| s.rodent.available()) { + Some(s) => prefs.style = s.id.to_owned(), + None => prefs.rival = Rival::Maia, + } + } + let (min, max) = range(prefs.rival, &prefs.style); + prefs.strength = prefs.strength.clamp(min, max); + let custom = prefs.clock.is_some_and(|c| !PRESETS.contains(&c)); + Dialog { + name: settings.your_name.clone(), + rating: settings.rating.map(|r| r.to_string()).unwrap_or_default(), + prefs, + custom, + download: None, + rodent_download: None, + play_after: false, + focus: true, + from: None, + keep_color: false, + counts: Default::default(), + target_there: false, + target: None, + } + } + + /// The dialog for a game from a position: the side to move plays (not remembered). + pub fn new_from(settings: &crate::settings::Settings, from: StartFrom) -> Dialog { + let mut d = Dialog::new(settings); + d.prefs.color = match from.position.turn() { + Color::White => ColorChoice::White, + Color::Black => ColorChoice::Black, + }; + d.from = Some(from); + d.keep_color = true; + d + } + + /// The dialog again for a game that could not start (its Maia missing): the same + /// position, strength, colour and time. + pub fn for_start(settings: &crate::settings::Settings, start: &Start) -> Dialog { + let mut d = match &start.from { + Some(from) => Dialog::new_from(settings, (**from).clone()), + None => Dialog::new(settings), + }; + d.prefs.strength = start.strength; + d.prefs.rival = start.rival; + d.prefs.style = start.style.clone(); + d.prefs.clock = start.clock; + d.custom = start.clock.is_some_and(|c| !PRESETS.contains(&c)); + d.prefs.color = match start.user { + Color::White => ColorChoice::White, + Color::Black => ColorChoice::Black, + }; + d.keep_color = true; + d + } + + /// Where the games of the name typed go (player-games.md §3): said before the game. + fn record_line(&mut self, settings: &crate::settings::Settings) -> String { + use crate::i18n::trf; + if !settings.record_games { + return tr( + "Games are not written by themselves (Settings → Interface → Your databases).", + ) + .to_owned(); + } + let name = crate::player_games::tidy(&self.name); + if self.target.as_ref().is_none_or(|(n, _)| *n != name) { + let dir = crate::own_db::default_base_dir(settings.new_database_dir.as_deref()); + let path = crate::player_games::target(&settings.players, &name, &dir); + self.target = Some((name.clone(), path)); + } + let path = &self.target.as_ref().expect("target").1; + let db = crate::own_db::base_name(path); + if name.is_empty() { + return trf( + "Without a name games go to «{db}». Enter a name to have a database of your own.", + &[("db", &db)], + ); + } + if !self.target_there { + return trf( + "Games will be written to a new database «{db}».", + &[("db", &db)], + ); + } + match self.counts.get(path) { + Some(&n) => trf( + "Games are written to «{db}» · {n}", + &[("db", &db), ("n", &crate::i18n::games(n))], + ), + None => trf("Games are written to «{db}»", &[("db", &db)]), + } + } + + /// The database the games of the name typed go to. + pub fn record_target(&self) -> Option<&std::path::Path> { + self.target.as_ref().map(|(_, p)| p.as_path()) + } + + fn rating(&self) -> Option { + self.rating + .trim() + .parse::() + .ok() + .filter(|r| (100..=3500).contains(r)) + } + + /// Draws the dialog; on «Play» the choices are written into `settings`. + pub fn show( + &mut self, + ctx: &egui::Context, + settings: &mut crate::settings::Settings, + ) -> Option { + use egui::RichText; + let mut out = None; + let rival_before = self.prefs.rival; + let model = model_for(); + let body_h = (ctx.content_rect().height() - 140.0).max(160.0); + egui::Modal::new(egui::Id::new("play_dialog")).show(ctx, |ui| { + ui.set_width(460.0); + ui.heading(tr("Play against the computer")); + // The body scrolls in a low window; the buttons below it stay in view. + // A solid bar, seen without hovering: in a low window the time is below it. + ui.style_mut().spacing.scroll = egui::style::ScrollStyle::solid(); + let rating = egui::ScrollArea::vertical() + .max_height(body_h) + .auto_shrink([false, true]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded) + .show(ui, |ui| { + // A game from a position: that position, instead of the introduction. + if let Some(from) = &self.from { + position_block(ui, settings, from, self.prefs.color, body_h >= 420.0); + } + + // The blocks in the order of the choice: who plays, against whom, which + // colour, how long. Every choice is a framed tile; the tiles of a row share + // its width. + const W: f32 = 460.0; + const GAP: f32 = 6.0; + const TILE_H: f32 = 32.0; + let section = |ui: &mut egui::Ui, text: &str| { + ui.add_space(12.0); + ui.label(RichText::new(text).strong().size(15.0)); + ui.add_space(2.0); + }; + let choice = |ui: &mut egui::Ui, on: bool, text: &str, size: [f32; 2]| { + ui.add_sized( + size, + egui::Button::selectable(on, RichText::new(text).size(14.0)) + .frame_when_inactive(true), + ) + }; + ui.spacing_mut().item_spacing = egui::vec2(GAP, GAP); + + // You. + section(ui, tr("You")); + egui::Grid::new("play_you") + .num_columns(2) + .spacing(egui::vec2(8.0, GAP)) + .show(ui, |ui| { + ui.label(tr("Name:")); + ui.horizontal(|ui| { + // The players of this computer, for a family (each their database + // and rating). + let known: Vec<_> = settings + .players + .iter() + .filter(|p| !p.name.is_empty()) + .cloned() + .collect(); + let menu_w = if known.is_empty() { 0.0 } else { 34.0 }; + let r = ui.add( + egui::TextEdit::singleline(&mut self.name) + .desired_width(ui.available_width() - menu_w), + ); + if std::mem::take(&mut self.focus) && self.name.is_empty() { + r.request_focus(); + } + let mut pick = None; + // ↓ / ↑ in the field go through the players. + if r.has_focus() && !known.is_empty() { + let step = ui.input_mut(|i| { + if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) { + 1 + } else if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) { + -1 + } else { + 0 + } + }); + if step != 0 { + let n = known.len() as i32; + let now = crate::player_games::tidy(&self.name).to_lowercase(); + let at = known + .iter() + .position(|p| p.name.to_lowercase() == now) + .map_or(if step > 0 { -1 } else { n }, |k| k as i32); + pick = Some(known[(at + step).rem_euclid(n) as usize].clone()); + } + } + if !known.is_empty() { + let size = egui::vec2(menu_w - ui.spacing().item_spacing.x, r.rect.height()); + let (resp, _) = egui::containers::menu::MenuButton::from_button( + egui::Button::new("â–¾").min_size(size), + ) + .ui(ui, |ui| { + for p in &known { + let mut label = p.name.clone(); + if let Some(r) = p.rating { + label += &format!(" · {r}"); + } + if let Some(n) = p.path.as_ref().and_then(|q| self.counts.get(q)) { + label += &format!(" · {}", crate::i18n::games(*n)); + } + if ui.button(label).clicked() { + pick = Some(p.clone()); + ui.close(); + } + } + }); + resp.on_hover_text(tr("Players of this computer (↓ in the name field)")); + } + if let Some(p) = pick { + self.name = p.name.clone(); + self.rating = p.rating.map(|r| r.to_string()).unwrap_or_default(); + } + }); + ui.end_row(); + ui.label(""); + // As wide as the field: the line wraps, the dialog keeps its width. + let line = self.record_line(settings); + ui.scope(|ui| { + ui.set_max_width(W - 80.0); + ui.add(egui::Label::new(RichText::new(line).weak().size(12.5)).wrap()); + }); + ui.end_row(); + ui.label(tr("Rating:")); + ui.horizontal(|ui| { + let r = ui.add( + egui::TextEdit::singleline(&mut self.rating) + .desired_width(70.0), + ); + if r.changed() { + self.rating.retain(|c| c.is_ascii_digit()); + self.rating.truncate(4); + } + ui.label(RichText::new(tr("not required")).weak()); + }); + ui.end_row(); + }); + + // The opponent (docs/design/rodent-opponent.md): Maia or Rodent V, one strength + // slider for both, Rodent's style. + let rodent_ok = Gen::V.available() || Gen::IV.available(); + let rodent = self.prefs.rival == Rival::Rodent; + section( + ui, + &if rodent { + crate::i18n::trf("Opponent — Rodent {elo}", &[("elo", &self.prefs.strength)]) + } else { + crate::i18n::trf("Opponent — Maia {elo}", &[("elo", &self.prefs.strength)]) + }, + ); + ui.horizontal(|ui| { + let tile_w = (W - GAP) / 2.0; + // A selectable tile of two centred lines: the name and what it is. + let tile = |ui: &mut egui::Ui, on: bool, enabled: bool, name: &str, about: &str| { + let sense = if enabled { egui::Sense::click() } else { egui::Sense::hover() }; + let (rect, resp) = ui.allocate_exact_size(egui::vec2(tile_w, 48.0), sense); + let v = ui.style().interact_selectable(&resp, on); + let fill = if on { ui.visuals().selection.bg_fill } else { v.weak_bg_fill }; + ui.painter().rect(rect, v.corner_radius, fill, v.bg_stroke, egui::StrokeKind::Inside); + let (text, weak) = if enabled { + if on { + // On the selected fill the caption takes its text colour, softer. + let c = ui.visuals().selection.stroke.color; + (c, c.gamma_multiply(0.8)) + } else { + (v.text_color(), ui.visuals().weak_text_color()) + } + } else { + let c = ui.visuals().weak_text_color(); + (c, c) + }; + let width = tile_w - 12.0; + let line = |t: &str, size: f32, color| { + ui.painter().layout(t.to_owned(), egui::FontId::proportional(size), color, width) + }; + let (top, bottom) = (line(name, 14.0, text), line(about, 11.5, weak)); + let h = top.size().y + bottom.size().y; + let y = rect.center().y - h / 2.0; + ui.painter().galley(egui::pos2(rect.center().x - top.size().x / 2.0, y), top, text); + let y2 = y + h - bottom.size().y; + ui.painter().galley(egui::pos2(rect.center().x - bottom.size().x / 2.0, y2), bottom, weak); + resp + }; + if tile(ui, !rodent, true, "Maia", tr("plays like a human")).clicked() && rodent { + self.prefs.rival = Rival::Maia; + self.prefs.strength = self.prefs.strength.clamp(MAIA_MIN, MAIA_MAX); + } + let about = if rodent_ok { + tr("strong, with a style") + } else if cfg!(target_os = "macos") { + tr("not yet for macOS") + } else { + tr("not yet for this system") + }; + let r = tile(ui, rodent, rodent_ok, "Rodent", about).on_hover_text(if rodent_ok { "" } else { tr( + "Rodent is not available for this system yet. When it is, it will be here.", + ) }); + if r.clicked() && !rodent { + self.prefs.rival = Rival::Rodent; + if !style(&self.prefs.style).rodent.available() + && let Some(st) = STYLES.iter().find(|s| s.rodent.available()) + { + self.prefs.style = st.id.to_owned(); + } + let (min, max) = range(Rival::Rodent, &self.prefs.style); + self.prefs.strength = self.prefs.strength.clamp(min, max); + } + }); + // Each engine on its own scale (its authors'): not a person's Elo, said under it. + let (min, max) = range(self.prefs.rival, &self.prefs.style); + // Room for the rating that rides above the handle. + ui.add_space(16.0); + ui.horizontal(|ui| { + let end = |ui: &mut egui::Ui, v: u32| { + ui.add_sized([34.0, 18.0], egui::Label::new(RichText::new(v.to_string()).weak())) + }; + end(ui, min); + ui.spacing_mut().slider_width = W - 2.0 * 34.0 - 2.0 * GAP; + let r = ui.add( + egui::Slider::new(&mut self.prefs.strength, min..=max) + .step_by(50.0) + .show_value(false), + ); + // The eye is on the handle while it moves, not on the heading: the rating + // follows it (the handle's travel as egui's slider has it). + let travel = r.rect.x_range().shrink(r.rect.height() / 2.5); + let t = self.prefs.strength.saturating_sub(min) as f32 / (max - min).max(1) as f32; + ui.painter().text( + egui::pos2(travel.min + t * travel.span(), r.rect.top() - 2.0), + egui::Align2::CENTER_BOTTOM, + self.prefs.strength.to_string(), + egui::FontId::proportional(14.0), + ui.visuals().strong_text_color(), + ); + end(ui, max); + }); + ui.add_space(4.0); + let note = if self.prefs.rival == Rival::Rodent { + tr("Rodent's own rating (UCI_Elo): it does not match a person's Elo.") + } else { + tr("Maia's own rating: it does not match a person's Elo.") + }; + ui.add(egui::Label::new(RichText::new(note).weak().size(11.5)).wrap()); + // Rodent's style: always in its place (greyed for Maia), so nothing jumps. + ui.add_space(4.0); + ui.add_enabled_ui(rodent, |ui| { + // As tall as the buttons around it. + ui.spacing_mut().interact_size.y = 32.0; + let current = style(&self.prefs.style); + let shown = if rodent { + style_label(current) + } else { + tr("Like a human").to_owned() + }; + egui::ComboBox::from_id_salt("rodent_style") + .width(W) + .height(400.0) + .selected_text(shown) + .show_ui(ui, |ui| { + // Rodent V's styles, Rodent IV's characters, then the players both + // imitate; a style whose Rodent is not for this system is greyed. + let groups = [ + (tr("Style"), false, Some(Gen::V)), + (tr("Character"), false, Some(Gen::IV)), + (tr("As a player"), true, None), + ]; + for (k, (head, player, only)) in groups.into_iter().enumerate() { + // Only what this system plays, in the order of the names as shown + // (the Tals side by side). + let mut group: Vec<&Style> = STYLES + .iter() + .filter(|st| st.player == player && only.is_none_or(|g| st.rodent == g) && st.rodent.available()) + .collect(); + if group.is_empty() { + continue; + } + if player { + group.sort_by_key(|st| style_label(st).to_lowercase()); + } + if k > 0 { + ui.separator(); + } + ui.label(RichText::new(head).weak().size(11.5)); + for st in group { + ui.selectable_value(&mut self.prefs.style, st.id.to_owned(), style_label(st)) + .on_hover_text(tr(st.about)); + } + } + }) + .response + .on_disabled_hover_text(tr("The style is chosen for Rodent")); + }); + // Another Rodent may play another range. + if rodent { + let (min, max) = range(self.prefs.rival, &self.prefs.style); + self.prefs.strength = self.prefs.strength.clamp(min, max); + } + let about = if rodent { + tr(style(&self.prefs.style).about).to_owned() + } else { + tr("Maia does not pick a style: she plays like people of her rating.").to_owned() + }; + ui.add(egui::Label::new(RichText::new(about).weak().size(11.5)).truncate()); + let rating = self.rating(); + + // Colour. + section(ui, tr("Your colour")); + ui.horizontal(|ui| { + for (c, label) in [ + (ColorChoice::White, tr("White")), + (ColorChoice::Random, tr("Random")), + (ColorChoice::Black, tr("Black")), + ] { + let size = [(W - 2.0 * GAP) / 3.0, TILE_H]; + let on = self.prefs.color == c; + let king = match c { + ColorChoice::White => Some(true), + ColorChoice::Black => Some(false), + ColorChoice::Random => None, + }; + let clicked = match king { + Some(white) => ui + .add_sized( + size, + egui::Button::selectable( + on, + ( + crate::widgets::side_king(white, 16.0), + RichText::new(label).size(14.0), + ), + ) + .frame_when_inactive(true), + ) + .clicked(), + None => choice(ui, on, label, size).clicked(), + }; + if clicked { + self.prefs.color = c; + } + } + }); + + // Time: the presets four in a row, then «Custom» and «Unlimited». + section(ui, tr("Time")); + let w = (W - 3.0 * GAP) / 4.0; + let (rows, last) = PRESETS.split_at(8); + for row in rows.chunks(4).chain([last]) { + ui.horizontal(|ui| { + for tc in row { + let on = !self.custom && self.prefs.clock == Some(*tc); + if choice(ui, on, &tc.label(), [w, TILE_H]).clicked() { + self.prefs.clock = Some(*tc); + self.custom = false; + } + } + if row.len() < 4 { + if choice(ui, self.custom, tr("Custom"), [w, TILE_H]).clicked() { + self.custom = true; + if self.prefs.clock.is_none() { + self.prefs.clock = Some(TimeControl { base: 600, increment: 0 }); + } + } + // No clock at all: as long as you like (Maia answers in a second + // or two). + let none = self.prefs.clock.is_none(); + if choice(ui, none, tr("Unlimited"), [2.0 * w + GAP, TILE_H]) + .on_hover_text(tr("No clocks: think as long as you like")) + .clicked() + { + self.prefs.clock = None; + self.custom = false; + } + } + }); + } + if self.custom + && let Some(tc) = self.prefs.clock.as_mut() + { + let mut b = CUSTOM_BASES.iter().position(|&x| x >= tc.base).unwrap_or(7); + let mut i = CUSTOM_INCREMENTS + .iter() + .position(|&x| x >= tc.increment) + .unwrap_or(0); + ui.add_space(4.0); + egui::Grid::new("play_custom") + .num_columns(3) + .spacing(egui::vec2(10.0, GAP)) + .show(ui, |ui| { + ui.spacing_mut().slider_width = W - 90.0 - 28.0 - 20.0; + // Both labels flush left in one column. + let label = |ui: &mut egui::Ui, text: &str| { + ui.allocate_ui_with_layout( + egui::vec2(90.0, 18.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + ui.set_min_width(90.0); + ui.label(text); + }, + ); + }; + label(ui, tr("Minutes:")); + ui.add(egui::Slider::new(&mut b, 0..=CUSTOM_BASES.len() - 1).show_value(false)); + ui.add_sized([28.0, 18.0], egui::Label::new(RichText::new((CUSTOM_BASES[b] / 60).to_string()).strong())); + ui.end_row(); + label(ui, tr("Increment, s:")); + ui.add(egui::Slider::new(&mut i, 0..=CUSTOM_INCREMENTS.len() - 1).show_value(false)); + ui.add_sized([28.0, 18.0], egui::Label::new(RichText::new(CUSTOM_INCREMENTS[i].to_string()).strong())); + ui.end_row(); + }); + tc.base = CUSTOM_BASES[b]; + tc.increment = CUSTOM_INCREMENTS[i]; + } + rating + }) + .inner; + + // The opponent's file, downloaded once: under the body, by the buttons, always + // seen. The line stays while either Maia's large model or Rodent is missing, + // so that switching the opponent does not change the dialog's height; it is + // about the opponent chosen. + // The opponent changed: a game asked for by «Download and play» is not started + // for the other one when its file comes. + if self.prefs.rival != rival_before { + self.play_after = false; + } + let rodent = self.prefs.rival == Rival::Rodent; + let stage = self.download.as_ref().map(|d| d.stage()); + // The Rodent of the style chosen: its download, if that one is going on. + let which = style(&self.prefs.style).rodent; + let rstage = self + .rodent_download + .as_ref() + .filter(|(g, _)| *g == which) + .map(|(_, d)| d.stage()); + let other_busy = self.rodent_download.as_ref().is_some_and(|(g, d)| { + *g != which + && matches!(d.stage(), crate::engine_download::Stage::Downloading { .. } | crate::engine_download::Stage::Unpacking) + }); + let rodent_there = which.installed().is_some(); + let mut ready = if rodent { rodent_there } else { model.is_ok() }; + // A download going on: no game meanwhile (closing the dialog would cancel it). + let busy = matches!( + stage, + Some(crate::maia_download::Stage::Downloading { .. } | crate::maia_download::Stage::Checking) + ) || matches!( + rstage, + Some(crate::engine_download::Stage::Downloading { .. } | crate::engine_download::Stage::Unpacking) + ) || other_busy; + let large = crate::maia_download::installed(Model::Large).is_some(); + let rodent_missing = which.available() && !rodent_there; + if !ready || !large || rodent_missing { + ui.add_space(6.0); + if rodent { + match &rstage { + None | Some(crate::engine_download::Stage::Cancelled) if !ready => { + let note = match which { + Gen::V => crate::i18n::trf( + "Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).", + &[("mb", &which.size_mb())], + ), + Gen::IV => crate::i18n::trf( + "Rodent IV is downloaded once ({mb} MB): the engine built from its authors' sources, its characters and books from their repository.", + &[("mb", &which.size_mb())], + ), + }; + ui.label(RichText::new(note).weak()); + } + Some(crate::engine_download::Stage::Downloading { done, total }) => { + ui.add(egui::ProgressBar::new(*done as f32 / (*total).max(1) as f32).show_percentage()); + } + Some(crate::engine_download::Stage::Unpacking) => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Unpacking…")); + }); + } + Some(crate::engine_download::Stage::Done(_)) => ready = true, + Some(crate::engine_download::Stage::Failed(f)) => { + ui.label(RichText::new(crate::i18n::trf( + "Could not download Rodent: {error}", + &[("error", &download_failure(f))], + )).color(ui.visuals().error_fg_color)); + } + // Ready, but Maia's file is missing: the line keeps its place. + _ => { + ui.label(" "); + } + } + } else if ready && large { + ui.label(" "); + } else { + match stage { + None => { + ui.label(RichText::new(download_note(model.as_ref().err().copied())).weak()); + } + Some(crate::maia_download::Stage::Downloading { done }) => { + let size = self.download.as_ref().map_or(1, |d| d.model.size()); + ui.add( + egui::ProgressBar::new(done as f32 / size as f32).show_percentage(), + ); + } + Some(crate::maia_download::Stage::Checking) => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Checking…")); + }); + } + Some(crate::maia_download::Stage::Done(_)) => ready = true, + Some(crate::maia_download::Stage::Failed(ref e)) => { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + } + } + } + ui.add_space(6.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let label = if ready { tr("Play") } else { tr("Download and play") }; + // As wide as the longer label: «Cancel» stays in its place. + let width = [tr("Play"), tr("Download and play")] + .iter() + .map(|t| crate::game_view::text_width(ui, t, egui::TextStyle::Button)) + .fold(0.0, f32::max) + + 2.0 * ui.spacing().button_padding.x + + 4.0; + let main = ui + .add_enabled_ui(!busy, |ui| crate::widgets::primary_wide(ui, label, width)) + .inner; + // Enter plays unless it is meant for a focused control or the open list. + let free = ctx.memory(|m| m.focused().is_none()) && !ctx.any_popup_open(); + let pressed = !busy + && (main.clicked() || (free && ui.input(|i| i.key_pressed(egui::Key::Enter)))); + if pressed && !ready { + if rodent { + self.rodent_download = Some((which, which.start(ctx))); + self.play_after = true; + } else if let Err(m) = model { + self.download = Some(crate::maia_download::Download::start(ctx, m)); + self.play_after = true; + } + } + // After a download: the game starts when it is done, only if that opponent + // is still the one chosen (not when the choice moved meanwhile). + let downloaded = if rodent { + matches!(rstage, Some(crate::engine_download::Stage::Done(_))) + } else { + matches!(stage, Some(crate::maia_download::Stage::Done(_))) + }; + if ready && (pressed || (self.play_after && downloaded)) { + self.play_after = false; + let user = match self.prefs.color { + ColorChoice::White => Color::White, + ColorChoice::Black => Color::Black, + ColorChoice::Random => { + if random_unit() < 0.5 { + Color::White + } else { + Color::Black + } + } + }; + settings.your_name = self.name.trim().to_owned(); + settings.rating = rating; + if !self.name.trim().is_empty() { + crate::player_games::remember(&mut settings.players, &self.name, rating); + } + // From a position the colour is the side to move's, not a habit. + let color = settings.play.color; + settings.play = self.prefs.clone(); + if self.keep_color { + settings.play.color = color; + } + out = Some(DialogOutcome::Play(Start { + rival: self.prefs.rival, + style: self.prefs.style.clone(), + user, + strength: self.prefs.strength, + user_elo: rating, + user_name: self.name.trim().to_owned(), + clock: self.prefs.clock, + from: self.from.clone().map(Box::new), + })); + } + if ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(0.0, 30.0))).clicked() { + out = Some(DialogOutcome::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + out = Some(DialogOutcome::Cancel); + } + out + } +} + +/// The position a game goes on from: a small board (turned to the colour chosen) and +/// where it comes from. `board`: room for the board (not in a low window). +fn position_block( + ui: &mut egui::Ui, + settings: &crate::settings::Settings, + from: &StartFrom, + color: ColorChoice, + board: bool, +) { + use egui::RichText; + let bottom = match color { + ColorChoice::White => Color::White, + ColorChoice::Black => Color::Black, + ColorChoice::Random => from.position.turn(), + }; + egui::Frame::new() + .inner_margin(egui::Margin::same(8)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_top(|ui| { + if board { + ui.allocate_ui(egui::vec2(112.0, 112.0), |ui| { + let view = crate::board::BoardView { + pos: &from.position, + orientation: bottom, + last_move: from.last, + arrows: &[], + circles: &[], + badge: None, + interactive: false, + temporary_shapes: false, + show_coords: false, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: 0.0, + premove: None, + auto_queen: false, + alert: None, + }; + let mut state = crate::board::BoardState::default(); + view.show(ui, &mut state); + }); + ui.add_space(12.0 - ui.spacing().item_spacing.x); + } + ui.vertical(|ui| { + let top = ui.cursor().top(); + let title = match &from.after_shown { + Some(m) => { + crate::i18n::trf("From the position after {move}", &[("move", m)]) + } + None => tr("From the game's starting position").to_owned(), + }; + ui.label(RichText::new(title).strong().size(15.0)); + if let Some(g) = &from.game { + // Two lines at most; the whole of it under the pointer. + let text = crate::i18n::trf("from the game {game}", &[("game", g)]); + let mut job = egui::text::LayoutJob::simple( + text.clone(), + egui::FontId::proportional(13.0), + ui.visuals().weak_text_color(), + ui.available_width(), + ); + job.wrap.max_rows = 2; + ui.add(egui::Label::new(job)).on_hover_text(text); + } + if from.null_dropped { + ui.label( + RichText::new(tr( + "The moves before the null move (--) are not carried over", + )) + .weak() + .size(13.0), + ); + } + // The side to move level with the bottom of the board. + let room = if board { + top + 112.0 - ui.cursor().top() - 17.0 + } else { + 4.0 + }; + ui.add_space(room.max(4.0)); + ui.label( + RichText::new(match from.position.turn() { + Color::White => tr("White to move"), + Color::Black => tr("Black to move"), + }) + .size(13.0), + ); + }); + }); + }); +} + +/// The opponent of a game put aside, downloaded so that the game can go on (it was +/// removed meanwhile): the same files and words as in the play dialog. +pub enum Fetch { + Maia(crate::maia_download::Download), + Rodent(crate::engine_download::Download), +} + +/// How a `Fetch` goes. +#[derive(PartialEq)] +pub enum Fetched { + Going, + Done, + Failed, +} + +impl Fetch { + pub fn start(saved: &Saved, ctx: &egui::Context) -> Fetch { + match saved.rival { + Rival::Maia => Fetch::Maia(crate::maia_download::Download::start( + ctx, + model_for().err().unwrap_or(Model::Large), + )), + Rival::Rodent => Fetch::Rodent(style(&saved.style).rodent.start(ctx)), + } + } + + /// What is downloaded, said before it is. + pub fn note(saved: &Saved) -> String { + match saved.rival { + Rival::Maia => download_note(model_for().err()), + Rival::Rodent => { + let which = style(&saved.style).rodent; + let mb = which.size_mb(); + match which { + Gen::V => crate::i18n::trf( + "Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).", + &[("mb", &mb)], + ), + Gen::IV => crate::i18n::trf( + "Rodent IV is downloaded once ({mb} MB): the engine built from its authors' sources, its characters and books from their repository.", + &[("mb", &mb)], + ), + } + } + } + } + + /// Its progress, or why it failed. + pub fn show(&self, ui: &mut egui::Ui) -> Fetched { + use crate::engine_download::Stage as R; + use crate::maia_download::Stage as M; + let failed = |ui: &mut egui::Ui, text: String| { + ui.label(egui::RichText::new(text).color(ui.visuals().error_fg_color)); + Fetched::Failed + }; + match self { + Fetch::Maia(d) => match d.stage() { + M::Downloading { done } => { + ui.add( + egui::ProgressBar::new(done as f32 / d.model.size() as f32) + .show_percentage(), + ); + Fetched::Going + } + M::Checking => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Checking…")); + }); + Fetched::Going + } + M::Done(_) => Fetched::Done, + M::Failed(e) => failed(ui, e), + }, + Fetch::Rodent(d) => match d.stage() { + R::Downloading { done, total } => { + ui.add( + egui::ProgressBar::new(done as f32 / total.max(1) as f32).show_percentage(), + ); + Fetched::Going + } + R::Unpacking => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Unpacking…")); + }); + Fetched::Going + } + R::Done(_) => Fetched::Done, + R::Failed(f) => failed( + ui, + crate::i18n::trf( + "Could not download Rodent: {error}", + &[("error", &download_failure(&f))], + ), + ), + R::Cancelled => Fetched::Failed, + }, + } + } +} + +/// Why Rodent's download failed, in words. +fn download_failure(f: &crate::engine_download::Failure) -> String { + use crate::engine_download::Failure as F; + match f { + F::Network(e) | F::Disk(e) => e.clone(), + F::Server(code) => format!("HTTP {code}"), + F::Broken => tr("it does not start on this computer").to_owned(), + F::Checksum => tr("The file is not the published one").to_owned(), + F::Unsupported => tr("not yet for this system").to_owned(), + } +} + +/// Why an engine did not start, in words: the details go to the log. +fn start_failure(detail: &str) -> String { + eprintln!("rodent: {detail}"); + tr("it does not start on this computer").to_owned() +} + +/// What the download button brings: Maia herself, or (the small one being there) the +/// large one for the strength chosen. +fn download_note(model: Option) -> String { + let mb = model.unwrap_or(Model::Large).size().div_ceil(1_000_000); + crate::i18n::trf( + "Maia is downloaded once ({mb} MB, from huggingface.co, the authors' own file).", + &[("mb", &mb)], + ) +} + +/// A game just played: what the result strip says. +#[derive(Clone, Debug)] +pub struct End { + pub ending: Ending, + pub user: Color, + pub start: Start, + /// The clocks at the end (user, Maia). + pub left: Option<(Duration, Duration)>, +} + +impl End { + /// «You won» / «You lost» / «Draw» / «You resigned». + pub fn heading(&self) -> &'static str { + match self.ending { + Ending::Resigned { loser } if loser == self.user => tr("You resigned"), + Ending::Resigned { .. } => tr("You won"), + e => match e.result() { + chess_core::GameResult::Draw => tr("Draw"), + r if r == Ending::Checkmate { winner: self.user }.result() => tr("You won"), + _ => tr("You lost"), + }, + } + } + + pub fn detail(&self) -> &'static str { + match self.ending { + Ending::Checkmate { .. } => tr("checkmate"), + Ending::Stalemate => tr("stalemate"), + Ending::InsufficientMaterial => tr("neither side can checkmate"), + Ending::Threefold => tr("the position occurred three times"), + Ending::FiftyMoves => tr("50 moves without a capture or a pawn move"), + Ending::Time { draw: true, loser } if loser == self.user => said( + self.start.rival, + "time is up, but Maia cannot checkmate", + "time is up, but Rodent cannot checkmate", + ), + Ending::Time { draw: true, .. } => said( + self.start.rival, + "Maia's time is up, but you cannot checkmate", + "Rodent's time is up, but you cannot checkmate", + ), + Ending::Time { .. } => tr("time is up"), + Ending::Resigned { loser } if loser == self.user => "", + Ending::Resigned { .. } => said(self.start.rival, "Maia resigned", "Rodent resigned"), + Ending::DrawAgreed => tr("by agreement"), + } + } +} diff --git a/apps/desktop/src/player_games.rs b/apps/desktop/src/player_games.rs new file mode 100644 index 0000000..bdcf226 --- /dev/null +++ b/apps/desktop/src/player_games.rs @@ -0,0 +1,742 @@ +//! The player's games (docs/design/player-games.md, decisions «Партии игрока +//! запиÑ�ываютÑ�Ñ� Ñ�ами»): every game against the computer goes by itself into a database +//! of its player — «Roman — games against the computer», made by the program in the +//! folder of new databases at its first game. Only new records are appended; replacing +//! and deleting stay explicit. While a game is played it is kept in a journal after +//! every move, so that a crash loses nothing: the next start writes it (result `*`). + +use std::fs::File; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use serde::{Deserialize, Serialize}; + +use crate::i18n::{tr, trf}; + +/// A player of this computer: the name as entered, the rating, the database. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Player { + pub name: String, + pub rating: Option, + /// Their database, once a game was written (renaming it in the program keeps the + /// link). + pub path: Option, +} + +/// The name as it is kept: trimmed, inner spaces single. +pub fn tidy(name: &str) -> String { + name.split_whitespace().collect::>().join(" ") +} + +/// Names that are the same player: «Иван» and «иван ». +fn same(a: &str, b: &str) -> bool { + tidy(a).to_lowercase() == tidy(b).to_lowercase() +} + +/// The player of this name, if they played before. +pub fn player<'a>(players: &'a [Player], name: &str) -> Option<&'a Player> { + players.iter().find(|p| same(&p.name, name)) +} + +/// Remembers the player who starts a game (first in the list) and their rating. +pub fn remember(players: &mut Vec, name: &str, rating: Option) { + let mut p = match players.iter().position(|p| same(&p.name, name)) { + Some(i) => players.remove(i), + None => Player::default(), + }; + p.name = tidy(name); + p.rating = rating; + players.insert(0, p); +} + +/// Links the player to the database their game was written to. +pub fn link(players: &mut Vec, name: &str, path: &Path) { + match players.iter_mut().find(|p| same(&p.name, name)) { + Some(p) => p.path = Some(path.to_owned()), + None => players.push(Player { + name: tidy(name), + rating: None, + path: Some(path.to_owned()), + }), + } +} + +/// The database's name: «Roman — games against the computer»; without a name, one for +/// everybody. The name is not declined (in Russian it could not be done safely). +pub fn db_name(name: &str) -> String { + let name = tidy(name); + if name.is_empty() { + tr("Games against the computer").to_owned() + } else { + trf("{name} — games against the computer", &[("name", &name)]) + } +} + +/// The longest player's name a file name takes, in characters. +const NAME_CHARS: usize = 40; + +/// The longest file name, in bytes, with room for « 2.pgn» (file systems take 255). +const STEM_BYTES: usize = 114; + +/// The file name for a database name: what a file name cannot have becomes «_», the +/// player's part is cut to [`NAME_CHARS`] (and to [`STEM_BYTES`] for the whole), no dot, +/// space or hyphen left at the cut, none of the first two at the end (Windows). +fn file_stem(player: &str, db: &str) -> String { + let player = tidy(player); + let mut chars: Vec = player.chars().take(NAME_CHARS).collect(); + let rest = db.len() - player.len(); + while !chars.is_empty() && rest + chars.iter().map(|c| c.len_utf8()).sum::() > STEM_BYTES + { + chars.pop(); + } + let mut cut: String = chars.into_iter().collect(); + if cut.len() < player.len() { + cut = cut.trim_end_matches(['.', ' ', '-']).to_owned(); + } + let db = if cut.len() < player.len() { + db.replacen(&player, &cut, 1) + } else { + db.to_owned() + }; + let clean: String = db + .chars() + .map(|c| { + if crate::own_db::FORBIDDEN.contains(&c) || c.is_control() { + '_' + } else { + c + } + }) + .collect(); + clean.trim_end_matches(['.', ' ']).to_owned() +} + +/// Where the player's games go: their database, else a new one in `dir`. A file of +/// that name made otherwise is taken when it is a PGN in UTF-8 (appending keeps its +/// bytes: a database brought from another computer goes on), else «… 2». +pub fn target(players: &[Player], name: &str, dir: &Path) -> PathBuf { + if let Some(path) = player(players, name).and_then(|p| p.path.clone()) { + return path; + } + let stem = file_stem(name, &db_name(name)); + let taken = + |p: &Path| p.exists() && !std::fs::read(p).is_ok_and(|b| std::str::from_utf8(&b).is_ok()); + let mut path = dir.join(format!("{stem}.pgn")); + let mut n = 2; + while taken(&path) { + path = dir.join(format!("{stem} {n}.pgn")); + n += 1; + } + path +} + +/// A game written: its record and whether the database was made for it. +#[derive(Clone, Debug, PartialEq)] +pub struct Written { + pub path: PathBuf, + pub index: usize, + pub created: bool, +} + +/// Appends `pgn` to the database at `path`, making it (and its folder) when absent. +pub fn write(path: &Path, pgn: &str) -> Result { + let created = !path.exists(); + if created { + path.parent() + .map(std::fs::create_dir_all) + .unwrap_or(Ok(())) + .and_then(|()| File::create_new(path)) + .and_then(|f| f.sync_all()) + .map_err(|e| e.to_string())?; + } + let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) + .map_err(|e| e.to_string())?; + let index = db.len(); + chess_core::pgn::store::append(&db, pgn).map_err(|e| e.to_string())?; + Ok(Written { + path: path.to_owned(), + index, + created, + }) +} + +/// What the journal keeps of a game being played. +#[derive(Serialize, Deserialize)] +struct Entry { + /// The player's database (`None`: games are not written, the journal is only for + /// going on with it). + target: Option, + /// Whose game it is: the player is linked to the database when it is written. + #[serde(default)] + player: String, + pgn: String, + /// The database's size before the game was appended: set just before the write, so + /// that a crash right after it does not write the game twice. + before: Option, + /// What the game is played with (the opponent, the clock…): it can go on from here. + /// None in journals of older versions: their games are only written. + #[serde(default)] + game: Option, + /// Put aside on purpose (not left by a crash). + #[serde(default)] + aside: bool, + /// The side to move's time left when it was put aside, in milliseconds (its last + /// `[%clk]` does not count the time it thought since). + #[serde(default)] + to_move_left_ms: Option, + /// When the game was last played (seconds since 1970): the newest of several put + /// aside is the one offered. Older journals: the file's time. + #[serde(default)] + played_at: Option, +} + +fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// The folder of the journals. +fn journal_dir() -> Option { + directories::ProjectDirs::from("", "", "chesspenguin").map(|d| d.data_local_dir().join("play")) +} + +/// The journal of the game being played: a file rewritten after each move, and a lock +/// held while it is played (a journal whose lock is free is a game put aside, or one a +/// crash left). +pub struct Journal { + lock: Option<(File, PathBuf)>, + path: PathBuf, + target: Option, + player: String, + game: Option, +} + +impl Journal { + /// A journal for a game going to `target` (none when the folder cannot be made: the + /// game is still written at its end). + pub fn new(target: Option, player: &str, game: crate::play::Saved) -> Self { + Self::in_dir(journal_dir(), target, player, Some(game)) + } + + fn in_dir( + dir: Option, + target: Option, + player: &str, + game: Option, + ) -> Self { + let made = dir.and_then(|dir| { + std::fs::create_dir_all(&dir).ok()?; + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let stem = format!("game-{}-{stamp}", std::process::id()); + let lock_path = dir.join(format!("{stem}.lock")); + let lock = File::create(&lock_path).ok()?; + lock.try_lock().ok()?; + Some(((lock, lock_path), dir.join(format!("{stem}.json")))) + }); + let (lock, path) = match made { + Some((lock, path)) => (Some(lock), path), + None => (None, PathBuf::new()), + }; + Self { + lock, + path, + target, + player: tidy(player), + game, + } + } + + /// Where the game goes when it ends (`None`: it is not written). + pub fn target(&self) -> Option<&Path> { + self.target.as_deref() + } + + fn put(&self, pgn: &str, before: Option) { + if self.lock.is_none() { + return; + } + let entry = Entry { + target: self.target.clone(), + player: self.player.clone(), + pgn: pgn.to_owned(), + before, + game: self.game.clone(), + aside: false, + to_move_left_ms: None, + played_at: Some(now_secs()), + }; + if let Ok(json) = serde_json::to_vec(&entry) { + let _ = crate::settings::write_atomic(&self.path, &json); + } + } + + /// The game as it is now (written as it would be if the program stopped here). + pub fn save(&self, pgn: &str) { + self.put(pgn, None); + } + + /// The game is over: written into its database. The journal stays until it is + /// dropped: after a failed write a crash still leaves the game to the next start. + /// `None`: the game is not written (no database for it). + pub fn finish(&self, pgn: &str) -> Option> { + let target = self.target.as_ref()?; + let before = std::fs::metadata(target).map_or(0, |m| m.len()); + self.put(pgn, Some(before)); + Some(write(target, pgn)) + } + + /// Whether the game can be put aside: its journal is kept on disk. + pub fn can_put_aside(&self) -> bool { + self.lock.is_some() && self.game.is_some() + } + + /// The game is put aside as `pgn`: its journal stays (still ours; after the program + /// stops, the next start finds it as a crash leaves one). `None`: there was no + /// journal (its folder could not be made) or it is not a game that can go on. + /// `to_move_left`: the side to move's time left now (with a clock). + pub fn put_aside( + mut self, + pgn: &str, + to_move_left: Option, + ) -> Option { + let game = self.game.take()?; + let (lock, lock_path) = self.lock.take()?; + let entry = Entry { + target: self.target.take(), + player: std::mem::take(&mut self.player), + pgn: pgn.to_owned(), + before: None, + game: Some(game), + aside: true, + to_move_left_ms: to_move_left.map(|d| d.as_millis() as u64), + played_at: Some(now_secs()), + }; + if let Ok(json) = serde_json::to_vec(&entry) { + let _ = crate::settings::write_atomic(&self.path, &json); + } + Some(PutAside { + lock, + lock_path, + path: std::mem::take(&mut self.path), + entry, + when: std::time::SystemTime::now(), + }) + } +} + +impl Drop for Journal { + fn drop(&mut self) { + if let Some((lock, lock_path)) = self.lock.take() { + let _ = std::fs::remove_file(&self.path); + drop(lock); + let _ = std::fs::remove_file(lock_path); + } + } +} + +/// A game a crash left: whose, where to, and what came of writing it. +pub struct Recovered { + pub player: String, + pub target: PathBuf, + pub written: Result, + /// A game put aside on purpose (not one a crash left). + pub put_aside: bool, +} + +/// A game put aside (or left by a crash) that can go on: its journal, locked by us now. +pub struct PutAside { + lock: File, + lock_path: PathBuf, + path: PathBuf, + entry: Entry, + /// When it was last written (the newest is the one offered). + when: std::time::SystemTime, +} + +impl PutAside { + pub fn pgn(&self) -> &str { + &self.entry.pgn + } + + pub fn game(&self) -> &crate::play::Saved { + self.entry + .game + .as_ref() + .expect("a game put aside has its settings") + } + + /// Left by a crash, not put aside on purpose. + pub fn crashed(&self) -> bool { + !self.entry.aside + } + + /// The side to move's time left when it was put aside. + pub fn to_move_left(&self) -> Option { + self.entry + .to_move_left_ms + .map(std::time::Duration::from_millis) + } + + /// Where it goes when it ends (`None`: not written). + pub fn target(&self) -> Option<&Path> { + self.entry.target.as_deref() + } + + /// When it was put aside (its journal last written). + pub fn when(&self) -> std::time::SystemTime { + self.when + } + + /// Goes on with the game: the same journal, kept on. + pub fn resume(self) -> Journal { + Journal { + lock: Some((self.lock, self.lock_path)), + path: self.path, + target: self.entry.target, + player: self.entry.player, + game: self.entry.game, + } + } + + /// The crash that left it was said: from now on it is a game put aside. + pub fn crash_said(&mut self) { + self.entry.aside = true; + self.store(); + } + + /// Lets the game go: written into its player's database unfinished (it is a game + /// that was played), then the journal goes. `Ok(None)`: games are not written: it + /// is only deleted. `Err`: it could not be written: it stays put aside, as it was. + pub fn discard(mut self) -> Result, Box<(Recovered, PutAside)>> { + let Some(target) = self.entry.target.clone() else { + self.remove(); + return Ok(None); + }; + // The database's size first: a crash right after the write does not write it + // again (the next start sees the file grown). + self.entry.before = Some(std::fs::metadata(&target).map_or(0, |m| m.len())); + self.store(); + let r = Recovered { + written: write(&target, &self.entry.pgn), + player: self.entry.player.clone(), + target, + put_aside: self.entry.aside, + }; + if r.written.is_ok() { + self.remove(); + Ok(Some(r)) + } else { + self.entry.before = None; + self.store(); + Err(Box::new((r, self))) + } + } + + fn store(&self) { + if let Ok(json) = serde_json::to_vec(&self.entry) { + let _ = crate::settings::write_atomic(&self.path, &json); + } + } + + /// Its journal goes. + fn remove(self) { + let _ = std::fs::remove_file(&self.path); + drop(self.lock); + let _ = std::fs::remove_file(&self.lock_path); + } +} + +/// The journals no program plays now (their lock is free): the newest game that can go +/// on is put aside; finished games a crash kept from their database, games of older +/// versions and other games left are written into their databases now. +pub fn recover() -> (Vec, Option) { + journal_dir().map(|d| recover_in(&d)).unwrap_or_default() +} + +fn recover_in(dir: &Path) -> (Vec, Option) { + let Ok(read) = std::fs::read_dir(dir) else { + return (Vec::new(), None); + }; + let mut written = Vec::new(); + let mut aside: Vec = Vec::new(); + for lock_path in read.flatten().map(|e| e.path()) { + if lock_path.extension().is_none_or(|e| e != "lock") { + continue; + } + let Ok(lock) = File::open(&lock_path) else { + continue; + }; + if lock.try_lock().is_err() { + continue; // a program running now plays it + } + let path = lock_path.with_extension("json"); + let read = std::fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()); + let file_time = || { + std::fs::metadata(&path) + .and_then(|m| m.modified()) + .unwrap_or(std::time::UNIX_EPOCH) + }; + let when = match read.as_ref().and_then(|e| e.played_at) { + Some(t) => std::time::UNIX_EPOCH + std::time::Duration::from_secs(t), + None => file_time(), + }; + match read { + // Over, or of an older version: it goes into its database (once). + Some(entry) if entry.before.is_some() || entry.game.is_none() => { + if let Some(target) = entry.target { + // The write had been made (the file grew since): not again. + let done = entry + .before + .is_some_and(|b| std::fs::metadata(&target).is_ok_and(|m| m.len() > b)); + if !done { + let r = Recovered { + written: write(&target, &entry.pgn), + player: entry.player, + target, + put_aside: false, + }; + let failed = r.written.is_err(); + written.push(r); + // Not written: its journal stays for the next start. + if failed { + continue; + } + } + } + } + Some(entry) => { + aside.push(PutAside { + lock, + lock_path, + path, + entry, + when, + }); + continue; + } + // A journal that cannot be read is kept aside, said in the log. + None if path.exists() => { + eprintln!("play journal unreadable, kept as .bad: {}", path.display()); + let _ = std::fs::rename(&path, path.with_extension("json.bad")); + } + None => {} + } + let _ = std::fs::remove_file(&path); + drop(lock); + let _ = std::fs::remove_file(&lock_path); + } + // One game put aside at a time: the newest; any other is written unfinished. + aside.sort_by_key(|a| std::cmp::Reverse(a.when)); + let mut rest = aside.into_iter(); + let kept = rest.next(); + for a in rest { + match a.discard() { + Ok(r) => written.extend(r), + // Not written: it stays for the next start (its lock let go). + Err(b) => written.push(b.0), + } + } + (written, kept) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn players_are_the_same_whatever_the_case_and_spaces() { + let mut ps = Vec::new(); + remember(&mut ps, " Иван Петров ", Some(1500)); + remember(&mut ps, "Роман", None); + remember(&mut ps, "иван петров", Some(1600)); + assert_eq!(ps.len(), 2); + assert_eq!(ps[0].name, "иван петров"); + assert_eq!(ps[0].rating, Some(1600)); + link(&mut ps, "Роман", Path::new("/x/r.pgn")); + assert_eq!( + player(&ps, " роман").and_then(|p| p.path.clone()), + Some(PathBuf::from("/x/r.pgn")) + ); + } + + #[test] + fn file_names_have_no_forbidden_characters() { + let stem = file_stem("A/B: C?", "A/B: C? — games"); + assert_eq!(stem, "A_B_ C_ — games"); + let long = "Я".repeat(60); + let stem = file_stem(&long, &format!("{long} — games")); + assert_eq!(stem, format!("{} — games", "Я".repeat(NAME_CHARS))); + assert_eq!(file_stem("Dot.", "Dot."), "Dot"); + // Cut at a hyphen: none left at the cut; long letters: within the bytes. + let name = format!("{}-Сидорова", "Ж".repeat(NAME_CHARS - 1)); + let stem = file_stem(&name, &format!("{name} — партии Ñ� компьютером")); + assert!(!stem.contains("- —"), "{stem}"); + assert!(stem.len() <= STEM_BYTES, "{}", stem.len()); + } + + #[test] + fn a_new_database_takes_the_game_and_the_next_is_appended() { + let dir = std::env::temp_dir().join(format!("cp-player-games-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = target(&[], "ТеÑ�Ñ‚", &dir.join("sub")); + let game = "[Event \"?\"]\n[White \"ТеÑ�Ñ‚\"]\n[Black \"Maia 1500\"]\n[Result \"1-0\"]\n\n1. e4 e5 1-0\n"; + let w = write(&path, game).unwrap(); + assert!(w.created); + assert_eq!(w.index, 0); + let w = write(&path, game).unwrap(); + assert!(!w.created); + assert_eq!(w.index, 1); + // A file of the same name in another encoding is not written into. + let bad = target(&[], "Bad", &dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(&bad, [0xff, 0xfe, 0x00]).unwrap(); + let other = target(&[], "Bad", &dir); + assert_ne!(other, bad); + assert!(other.to_string_lossy().ends_with(" 2.pgn"), "{other:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Recovery until only the journals of games being played are left. Another test + /// starting a process holds a copy of a lock for a moment (the child gets the parent's + /// files until it runs its program); recovery then leaves that journal for later. + fn recover_until(dir: &Path, live: usize) -> Vec { + let recover_in = |d: &Path| recover_in(d).0; + let locks = || { + std::fs::read_dir(dir) + .map(|r| { + r.flatten() + .filter(|e| e.path().extension().is_some_and(|x| x == "lock")) + .count() + }) + .unwrap_or(0) + }; + let mut out = Vec::new(); + for _ in 0..200 { + out.extend(recover_in(dir)); + if locks() <= live { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + out + } + + #[test] + fn a_game_put_aside_goes_on_or_is_written_unfinished() { + let dir = std::env::temp_dir().join(format!("cp-aside-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let journals = dir.join("play"); + let db = dir.join("db.pgn"); + let game = "[Event \"?\"]\n[Result \"*\"]\n\n1. e4 e5 *\n"; + let saved = crate::play::Saved { + white: true, + strength: 1500, + rival: crate::play::Rival::Maia, + style: String::new(), + user_elo: None, + user_name: "Роман".into(), + clock: Some(crate::play::TimeControl { + base: 300, + increment: 3, + }), + floor: 0, + from_game: None, + from_after: None, + from_after_shown: None, + }; + let j = Journal::in_dir( + Some(journals.clone()), + Some(db.clone()), + "Роман", + Some(saved.clone()), + ); + let aside = j.put_aside(game, None).unwrap(); + assert_eq!(aside.game(), &saved); + assert!(!aside.crashed()); + // The program stops: the next start finds it put aside, not written. + drop(aside); + let (written, found) = recover_in(&journals); + assert!(written.is_empty()); + let found = found.unwrap(); + assert_eq!(found.pgn(), game); + // It goes on with the same journal; put aside again and let go: written. + let j = found.resume(); + let aside = j + .put_aside(game, Some(std::time::Duration::from_secs(61))) + .unwrap(); + assert_eq!( + aside.to_move_left(), + Some(std::time::Duration::from_secs(61)) + ); + let r = aside.discard().ok().flatten().unwrap(); + assert_eq!(r.written.map(|w| w.index), Ok(0)); + assert_eq!(std::fs::read_dir(&journals).unwrap().count(), 0); + // A database that cannot be written (a folder of its name): the game is not + // lost, it stays put aside, at the next start too. + let bad = dir.join("bad.pgn"); + std::fs::create_dir_all(&bad).unwrap(); + let j = Journal::in_dir( + Some(journals.clone()), + Some(bad.clone()), + "Роман", + Some(saved.clone()), + ); + let aside = j.put_aside(game, None).unwrap(); + let Err(b) = aside.discard() else { + panic!("written into a folder") + }; + let (r, aside) = *b; + assert!(r.written.is_err()); + assert_eq!(aside.pgn(), game); + drop(aside); + let (written, found) = recover_in(&journals); + assert!(written.is_empty()); + assert_eq!(found.map(|a| a.pgn().to_owned()), Some(game.to_owned())); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_game_left_by_a_crash_is_written_once() { + let dir = std::env::temp_dir().join(format!("cp-journal-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let journals = dir.join("play"); + let db = dir.join("db.pgn"); + let game = "[Event \"?\"]\n[Result \"*\"]\n\n1. d4 d5 *\n"; + // Played, then the program stopped: the lock goes, the files stay. + let j = Journal::in_dir(Some(journals.clone()), Some(db.clone()), "Роман", None); + j.save(game); + let mut j = j; + drop(j.lock.take()); + drop(j); + // A game being played now (its lock held) is left alone. + let live = Journal::in_dir(Some(journals.clone()), Some(dir.join("live.pgn")), "", None); + live.save(game); + let got = recover_until(&journals, 1); + assert_eq!(got.len(), 1); + assert_eq!(got[0].player, "Роман"); + assert_eq!(got[0].written.as_ref().map(|w| w.index), Ok(0)); + assert!(recover_in(&journals).0.is_empty()); + // Crashed right after the write: not written again. + let j = Journal::in_dir(Some(journals.clone()), Some(db.clone()), "Роман", None); + let before = std::fs::metadata(&db).unwrap().len(); + j.put(game, Some(before)); + write(&db, game).unwrap(); + let mut j = j; + drop(j.lock.take()); + drop(j); + assert!(recover_until(&journals, 1).is_empty()); + let n = chess_core::PgnDatabase::open(&db, &mut |_| {}, &AtomicBool::new(false)) + .unwrap() + .len(); + assert_eq!(n, 2); + drop(live); + assert_eq!(std::fs::read_dir(&journals).unwrap().count(), 0); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/prep_saved.rs b/apps/desktop/src/prep_saved.rs new file mode 100644 index 0000000..238b8d1 --- /dev/null +++ b/apps/desktop/src/prep_saved.rs @@ -0,0 +1,350 @@ +//! Saved preparations: a preparation against an opponent kept for good (not in the +//! cache) and opened again from «Preparations» in the library. One per player of a +//! database: saving the same player of the same database again replaces it. Each is +//! two files in `/preparations/`: `.json`, what the list shows, and +//! `.report.json`, the report with the engine's evaluations (so the errors found +//! come back without the engine, even after the cache was cleared). + +use std::path::{Path, PathBuf}; + +use prep::{ErrorCounts, Period, Player, PrepReport}; +use serde::{Deserialize, Serialize}; + +use crate::prep_ui::ColorChoice; + +/// Version of the eligibility rules used for the saved error counters. +pub const ERROR_SELECTION_VERSION: u32 = 1; + +/// What the list of preparations knows of one. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SavedPrep { + /// The name in the list (the player's at first; the user can rename it). + pub title: String, + /// The database. + pub path: PathBuf, + pub player: Player, + pub names: Vec, + pub plies: usize, + pub period: Period, + pub color: ColorChoice, + /// Unused legacy book choice, preserved when old preparations are saved again. + #[serde(default)] + pub book: PathBuf, + /// Seconds since 1970, of the last save. + pub saved: u64, + /// The report's games and errors at that save. + pub games: u32, + pub errors: ErrorCounts, + /// The errors were searched (else the counts mean nothing). + pub evaluated: bool, + #[serde(default)] + pub error_selection_version: u32, +} + +impl SavedPrep { + pub fn errors_current(&self) -> bool { + self.error_selection_version == ERROR_SELECTION_VERSION + } +} + +/// The folder of the saved preparations. +pub fn dir() -> Option { + crate::platform::data_dir().map(|d| d.join("preparations")) +} + +/// The id of the preparation of the player named `names` in the database `path`: by +/// the names, not the database's name ids, which change when a game before his first +/// one is deleted or the database is replaced by a new version. +pub fn id(path: &Path, names: &[String]) -> String { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut eat = |b: u8| { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + }; + for b in path.to_string_lossy().bytes() { + eat(b); + } + let mut names: Vec<&String> = names.iter().collect(); + names.sort(); + names.dedup(); + for n in names { + eat(0); + for b in n.bytes() { + eat(b); + } + } + format!("{h:016x}") +} + +fn meta_path(dir: &Path, id: &str) -> PathBuf { + dir.join(format!("{id}.json")) +} + +fn report_path(dir: &Path, id: &str) -> PathBuf { + dir.join(format!("{id}.report.json")) +} + +/// Writes through a file beside it, so a crash leaves the old file or the new one. +fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +/// Every saved preparation (id, what it is), the last saved first. +pub fn list(dir: &Path) -> Vec<(String, SavedPrep)> { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut out: Vec<(String, SavedPrep)> = entries + .filter_map(|e| { + let path = e.ok()?.path(); + let name = path.file_name()?.to_str()?; + let id = name.strip_suffix(".json")?; + if id.ends_with(".report") { + return None; + } + let meta = serde_json::from_slice(&std::fs::read(&path).ok()?).ok()?; + Some((id.to_owned(), meta)) + }) + .collect(); + out.sort_by(|a, b| b.1.saved.cmp(&a.1.saved).then(a.1.title.cmp(&b.1.title))); + out +} + +/// The preparation `id`, if saved. +pub fn get(dir: &Path, id: &str) -> Option { + serde_json::from_slice(&std::fs::read(meta_path(dir, id)).ok()?).ok() +} + +/// Its report, if it can be read. +pub fn report(dir: &Path, id: &str) -> Option { + let mut report: PrepReport = + serde_json::from_slice(&std::fs::read(report_path(dir, id)).ok()?).ok()?; + // Stored evaluations remain useful when the rules for selecting errors change. + report.refresh(); + Some(report) +} + +/// Keeps `meta` and `report` as the preparation of their player and database (the +/// report first: a list entry never points to a missing report). +pub fn save(dir: &Path, meta: &SavedPrep, report: &PrepReport) -> std::io::Result<()> { + let id = id(&meta.path, &meta.names); + let bytes = serde_json::to_vec(report).map_err(std::io::Error::other)?; + write_atomic(&report_path(dir, &id), &bytes)?; + save_meta(dir, meta) +} + +/// Writes only the list entry: a preparation is kept from the moment it is started, +/// before its report is built. +pub fn save_meta(dir: &Path, meta: &SavedPrep) -> std::io::Result<()> { + let bytes = serde_json::to_vec_pretty(meta).map_err(std::io::Error::other)?; + write_atomic(&meta_path(dir, &id(&meta.path, &meta.names)), &bytes) +} + +/// A new name in the list. +pub fn rename(dir: &Path, id: &str, title: &str) -> std::io::Result<()> { + let mut meta = get(dir, id).ok_or_else(|| std::io::Error::other("no such preparation"))?; + meta.title = title.to_owned(); + let bytes = serde_json::to_vec_pretty(&meta).map_err(std::io::Error::other)?; + write_atomic(&meta_path(dir, id), &bytes) +} + +/// Removes the preparation (the list entry first). +pub fn delete(dir: &Path, id: &str) -> std::io::Result<()> { + std::fs::remove_file(meta_path(dir, id))?; + let _ = std::fs::remove_file(report_path(dir, id)); + Ok(()) +} + +/// Seconds since 1970 now. +pub fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn meta(path: &str, ids: [u32; 1], title: &str, saved: u64) -> SavedPrep { + SavedPrep { + title: title.to_owned(), + path: PathBuf::from(path), + player: Player::new(ids), + names: vec![title.to_owned()], + plies: 20, + period: Period::Months(24), + color: ColorChoice::Black, + book: PathBuf::new(), + saved, + games: 3, + errors: ErrorCounts::default(), + evaluated: false, + error_selection_version: ERROR_SELECTION_VERSION, + } + } + + #[test] + fn legacy_error_counts_are_not_marked_current() { + let current = meta("/db/a.pgn", [7], "Target", 10); + assert!(current.errors_current()); + let mut json = serde_json::to_value(¤t).expect("metadata"); + json.as_object_mut() + .unwrap() + .remove("error_selection_version"); + let legacy: SavedPrep = serde_json::from_value(json).expect("legacy metadata"); + assert!(!legacy.errors_current()); + let future = SavedPrep { + error_selection_version: ERROR_SELECTION_VERSION + 1, + ..current + }; + assert!(!future.errors_current()); + } + + #[test] + fn saved_listed_replaced_renamed_and_deleted() { + let dir = std::env::temp_dir().join(format!("cp-prep-saved-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert!(list(&dir).is_empty()); + let report: PrepReport = serde_json::from_str(REPORT).expect("report"); + let a = meta("/db/a.pgn", [7], "Вафин", 10); + let b = meta("/db/a.pgn", [8], "Иванов", 20); + save(&dir, &a, &report).expect("save"); + save(&dir, &b, &report).expect("save"); + let l = list(&dir); + assert_eq!(l.len(), 2); + assert_eq!(l[0].1.title, "Иванов", "the last saved first"); + // The same player of the same database: replaced, not added. + let a2 = SavedPrep { + saved: 30, + plies: 30, + ..a.clone() + }; + save(&dir, &a2, &report).expect("save"); + let l = list(&dir); + assert_eq!(l.len(), 2); + assert_eq!(l[0].1, a2); + let ida = id(&a.path, &a.names); + assert!(report_path(&dir, &ida).exists()); + assert!(super::report(&dir, &ida).is_some()); + rename(&dir, &ida, "Вафин — финал").expect("rename"); + assert_eq!(get(&dir, &ida).unwrap().title, "Вафин — финал"); + delete(&dir, &ida).expect("delete"); + assert_eq!(list(&dir).len(), 1); + assert!(!report_path(&dir, &ida).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn legacy_book_choice_is_preserved() { + let dir = std::env::temp_dir().join(format!("cp-prep-legacy-book-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut a = meta("/db/a.pgn", [7], "Вафин", 10); + a.book = PathBuf::from("/db/book.pgn"); + save_meta(&dir, &a).expect("save_meta"); + let ida = id(&a.path, &a.names); + let path = meta_path(&dir, &ida); + let json = std::fs::read_to_string(&path).expect("metadata"); + let without_book = json.replace(&format!("\"book\": \"{}\",", a.book.display()), ""); + std::fs::write(&path, without_book).expect("legacy metadata"); + let mut loaded = get(&dir, &ida).expect("defaulted legacy book"); + assert_eq!(loaded.book, PathBuf::new()); + loaded.book = a.book.clone(); + save_meta(&dir, &loaded).expect("save legacy book"); + assert_eq!(get(&dir, &ida).expect("metadata").book, a.book); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn saved_report_rejudges_stale_errors_without_losing_evaluations() { + let dir = std::env::temp_dir().join(format!("cp-prep-rejudge-{}", std::process::id())); + let mut stale: PrepReport = serde_json::from_str(REPORT).expect("report"); + stale.search = game_review::SEARCH_VERSION; + stale.games.push(prep::GameInfo { + index: 0, + white: true, + opponent: "Other".into(), + opponent_elo: 0, + date: String::new(), + outcome: prep::Outcome::Unknown, + ucis: vec!["e2e4".into(), "e7e5".into(), "g1f3".into()], + sans: vec!["e4".into(), "e5".into(), "Nf3".into()], + keys: vec![1, 2, 3, 4], + opening: None, + named: None, + book: None, + }); + stale.white.games = vec![0]; + for (key, cp, best) in [ + (1, 0, "e2e4"), + (2, 0, "c7c5"), + (3, 150, "f1c4"), + (4, 0, "b8c6"), + ] { + stale.evals.insert( + key, + prep::PositionEval { + nodes: 1000, + eval: prep::Eval::Cp(cp), + pv: vec![best.into()], + depth: 10, + }, + ); + } + // This cached Nf3 error followed Black's earlier error, so it no longer + // belongs in preparation despite its evaluations being fully cached. + stale.white.errors.push(prep::OpeningError { + game: 0, + ply: 2, + key: 3, + uci: "g1f3".into(), + san: "Nf3".into(), + best_uci: "f1c4".into(), + best_san: "Bc4".into(), + judgement: prep::Judgement::Mistake, + before: prep::Eval::Cp(150), + after: prep::Eval::Cp(0), + opening: None, + }); + stale.white.counts.mistakes = 1; + let metadata = meta("/db/stale.pgn", [7], "Target", 10); + save(&dir, &metadata, &stale).expect("save stale report"); + let key = id(&metadata.path, &metadata.names); + let stored = std::fs::read(report_path(&dir, &key)).expect("stored bytes"); + let loaded = super::report(&dir, &key).expect("load saved report"); + assert!(loaded.white.errors.is_empty()); + assert_eq!(loaded.white.counts.total(), 0); + assert_eq!(loaded.evals, stale.evals); + assert_eq!(loaded.games, stale.games); + assert_eq!(std::fs::read(report_path(&dir, &key)).unwrap(), stored); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn started_preparation_is_listed_before_its_report_exists() { + let dir = std::env::temp_dir().join(format!("cp-prep-meta-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let a = meta("/db/a.pgn", [7], "Вафин", 10); + save_meta(&dir, &a).expect("save_meta"); + assert_eq!(list(&dir).len(), 1, "in the list from the start"); + let ida = id(&a.path, &a.names); + assert!(super::report(&dir, &ida).is_none(), "no report yet"); + let report: PrepReport = serde_json::from_str(REPORT).expect("report"); + save(&dir, &a, &report).expect("save"); + assert!(super::report(&dir, &ida).is_some()); + let _ = std::fs::remove_dir_all(&dir); + } + + const REPORT: &str = r#"{"version":4,"fingerprint":1,"player":{"ids":[7]},"names":["A"], + "plies":20,"side_white":true,"side_black":true,"games":[],"skipped":0,"openings":[], + "white":{"white":true,"games":[],"tree":{"nodes":[]},"families":[],"errors":[], + "repeated":[],"counts":{"inaccuracies":0,"mistakes":0,"blunders":0}}, + "black":{"white":false,"games":[],"tree":{"nodes":[]},"families":[],"errors":[], + "repeated":[],"counts":{"inaccuracies":0,"mistakes":0,"blunders":0}}, + "book":null,"engine":null,"evals":{}}"#; +} diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs new file mode 100644 index 0000000..78322f4 --- /dev/null +++ b/apps/desktop/src/prep_ui.rs @@ -0,0 +1,6469 @@ +//! Preparing against an opponent on the desktop (docs/design/opponent-prep.md): the +//! dialog that picks the database, the player's spellings and the colour; +//! the report screen — the repertoire tree, the openings, the errors, the board of the +//! chosen position and the games through it — and the engine run over the opening +//! positions. The data are the `prep` crate's; the engine job is the same as the game +//! analysis's (`game_review::run`), one at a time for the whole program. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; + +use chess_import::Database; +use chess_import::chessbase::base::{Side, fold}; +use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Sense, Ui, vec2}; +use egui_extras::{Column, TableBuilder}; +use game_review::{JobEvent, JobSettings, Judgement}; +use prep::{ + Candidate, ErrorCounts, GameInfo, Options, Period, Player, PositionCache, PrepReport, Tally, +}; +use serde::{Deserialize, Serialize}; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, Move, Position, Square}; + +use crate::board::{Arrow, BoardState, BoardView}; +use crate::board_search::{Background, PREVIEW_ARROW}; +use crate::i18n::{tr, trf}; +use crate::large_db::grouped; +use crate::reference::RefDb; +use crate::review; +use crate::settings::Settings; + +/// «Prepare against…» as the library asks it: the name typed or picked and the colour +/// of the filter (§2.1). +#[derive(Clone, Debug, Default)] +pub struct PrepEntry { + pub query: String, + /// The name id when it was picked from the list. + pub exact: Option, + pub side: Side, +} + +/// A table's order: the column and the direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SortBy { + pub key: K, + pub ascending: bool, +} + +impl SortBy { + /// A click on the header of `key`: the same column turns the order round, another + /// one starts in its natural direction (names A–Z, numbers and dates high first). + fn click(&mut self, key: K, ascending_first: bool) { + if self.key == key { + self.ascending = !self.ascending; + } else { + *self = SortBy { + key, + ascending: ascending_first, + }; + } + } + + /// `ord` (ascending) in this table's direction. + fn apply(&self, ord: std::cmp::Ordering) -> std::cmp::Ordering { + if self.ascending { ord } else { ord.reverse() } + } +} + +/// The columns the repertoire tree orders the moves of a position by. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TreeSort { + Games, + Share, + Score, + Last, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum OpeningSort { + Name, + Eco, + Games, + Share, + Score, + Last, + Errors, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum RepeatedSort { + Move, + Times, + Score, + Opening, +} + +/// «By opening» of the errors tab. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum VariationSort { + Games, + Errors, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum GameSort { + White, + WhiteElo, + Black, + BlackElo, + Result, + Date, + Then, + Event, + Errors, +} + +/// The order of every table of the screen (kept in the settings). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PrepSorts { + pub tree: SortBy, + pub openings: SortBy, + pub repeated: SortBy, + pub variations: SortBy, + pub games: SortBy, +} + +impl Default for PrepSorts { + fn default() -> Self { + // Most played, most repeated, worst, newest first. + PrepSorts { + tree: SortBy { + key: TreeSort::Games, + ascending: false, + }, + openings: SortBy { + key: OpeningSort::Games, + ascending: false, + }, + repeated: SortBy { + key: RepeatedSort::Times, + ascending: false, + }, + variations: SortBy { + key: VariationSort::Errors, + ascending: false, + }, + games: SortBy { + key: GameSort::Date, + ascending: false, + }, + } + } +} + +/// A sort column of the errors tab (its two parts). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SortKeyOf { + Repeated(RepeatedSort), + Variation(VariationSort), +} + +/// A value a table is ordered by. +#[derive(Clone, Debug, PartialEq, PartialOrd)] +enum SortVal { + Num(f64), + Text(String), +} + +fn num(x: impl Into) -> SortVal { + SortVal::Num(x.into()) +} + +/// `a` against `b` (a value never compared to another kind is equal). +fn cmp_val(a: &SortVal, b: &SortVal) -> std::cmp::Ordering { + a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal) +} + +/// A score for ordering: games without a result last when high first. +fn score_val(t: &Tally) -> SortVal { + num(t.score().unwrap_or(-1.0)) +} + +/// A sortable column's header: the title with â–²/â–¼ when the table is ordered by it; +/// a click is noted in `clicked`. +fn sort_col( + h: &mut egui_extras::TableRow<'_, '_>, + text: &str, + hint: &str, + key: K, + sort: SortBy, + clicked: &mut Option, +) { + h.col(|ui| { + let r = crate::widgets::sort_header(ui, text, (sort.key == key).then_some(sort.ascending)); + let r = if hint.is_empty() { + r + } else { + r.on_hover_text(hint) + }; + if r.clicked() { + *clicked = Some(key); + } + }); +} + +/// The colour switch of the report. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ColorChoice { + White, + Black, + Both, +} + +impl ColorChoice { + pub fn side(self) -> Side { + match self { + ColorChoice::White => Side::White, + ColorChoice::Black => Side::Black, + ColorChoice::Both => Side::Any, + } + } + + fn from_side(side: Side) -> Self { + match side { + Side::White => ColorChoice::White, + Side::Black => ColorChoice::Black, + Side::Any => ColorChoice::Both, + } + } + + /// The colours shown, White first. + fn colours(self) -> Vec { + match self { + ColorChoice::White => vec![true], + ColorChoice::Black => vec![false], + ColorChoice::Both => vec![true, false], + } + } + + fn label(self) -> &'static str { + match self { + ColorChoice::White => tr("White"), + ColorChoice::Black => tr("Black"), + ColorChoice::Both => tr("Both"), + } + } +} + +/// "Mega Database 2026 · 11.7M games" for the pickers. +fn db_label(d: &RefDb) -> String { + match &d.db { + Some(db) => format!("{} · {}", d.name, crate::i18n::games_short(db.len())), + None => format!("{} · {}", d.name, tr("not open")), + } +} + +// ----- the dialog ------------------------------------------------------------------ + +/// What «Open report» starts. +pub struct PrepStart { + pub path: PathBuf, + pub player: Player, + pub side: ColorChoice, +} + +// ----- the period ------------------------------------------------------------------ + +/// The periods offered, in the menu's order. +const PERIODS: [Period; 8] = [ + Period::All, + Period::Months(3), + Period::Months(6), + Period::Months(12), + Period::Months(24), + Period::Last(50), + Period::Last(100), + Period::Last(200), +]; + +/// The period in a narrow row: «3 mo.», «Last 100». +fn period_short(p: Period) -> String { + match p { + Period::All => tr("All").to_owned(), + Period::Months(12) => tr("1 yr").to_owned(), + Period::Months(24) => tr("2 yrs").to_owned(), + Period::Months(m) => trf("{n} mo.", &[("n", &m)]), + Period::Last(n) => trf("Last {n}", &[("n", &n)]), + } +} + +/// `yyyymmdd` as «18.10.2026», «10.2026», «2026». +fn shown_date(d: u32) -> String { + match (d / 10000, d / 100 % 100, d % 100) { + (0, ..) => String::new(), + (y, 0, _) => y.to_string(), + (y, m, 0) => format!("{m:02}.{y}"), + (y, m, day) => format!("{day:02}.{m:02}.{y}"), + } +} + +fn period_label(p: Period) -> String { + match p { + Period::All => tr("All games").to_owned(), + Period::Months(12) => tr("Last year").to_owned(), + Period::Months(24) => tr("Last 2 years").to_owned(), + Period::Months(3) => tr("Last 3 months").to_owned(), + Period::Months(6) => tr("Last 6 months").to_owned(), + Period::Months(m) => trf("Last {n} months", &[("n", &m)]), + Period::Last(n) => trf("Last {n} games", &[("n", &n)]), + } +} + +pub enum DialogOutcome { + Open(PrepStart), + Cancel, + /// A database of the shelf is needed but not read yet. + LoadDb(PathBuf), +} + +/// The words of a name for matching: folded, without full stops and commas. +fn name_words(s: &str) -> Vec { + fold(s) + .split(|c: char| c.is_whitespace() || c == ',') + .map(|w| w.trim_matches('.').to_owned()) + .filter(|w| !w.is_empty()) + .collect() +} + +/// Splits the names that match a query into those that match it word for word (an +/// initial like «Р.» matches the beginning of a word) and the similar ones, which +/// only start with its words («Вафин» ⊂ «Вафина»): most likely other people. +pub fn split_candidates(query: &str, list: Vec) -> (Vec, Vec) { + let folded = fold(query); + let wanted: Vec<(String, bool)> = folded + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|w| !w.is_empty()) + .map(|w| (w.trim_matches('.').to_owned(), w.ends_with('.'))) + .filter(|(w, _)| !w.is_empty()) + .collect(); + let (mut exact, mut similar) = (Vec::new(), Vec::new()); + for c in list { + let words = name_words(&c.name); + let whole = wanted.iter().all(|(q, initial)| { + words + .iter() + .any(|w| w == q || (*initial && w.starts_with(q.as_str()))) + }); + if whole { + exact.push(c); + } else { + similar.push(c); + } + } + (exact, similar) +} + +/// Up to this many names are offered. +const CANDIDATES: usize = 40; + +/// The name search in the background: the names and how many match in all. +type SearchJob = Background<(Vec, usize)>; +/// The count of the ticked names' games by colour (White, Black). +type CountJob = Background<(u32, u32)>; + +pub struct PrepDialog { + pub path: PathBuf, + /// The shelf (set by the application every frame). + pub dbs: Vec, + query: String, + /// The query the lists answer. + answered: Option, + search: Option<(String, SearchJob)>, + exact: Vec, + similar: Vec, + total: usize, + ticked: Vec, + /// The name the dialog was opened with (ticked by itself when found). + wanted: Option, + side: ColorChoice, + /// Games of the ticked names by colour, and the job counting them. + counts: Option<(Vec, (u32, u32))>, + count_job: Option<(Vec, CountJob)>, + focus_query: bool, + typed_at: f64, + /// `CP_PREP_OPEN`: «Open report» pressed by itself once a name is ticked. + auto_open: bool, +} + +impl PrepDialog { + pub fn new(path: PathBuf, entry: PrepEntry) -> Self { + PrepDialog { + path, + dbs: Vec::new(), + query: entry.query, + answered: None, + search: None, + exact: Vec::new(), + similar: Vec::new(), + total: 0, + ticked: Vec::new(), + wanted: entry.exact, + side: ColorChoice::from_side(entry.side), + counts: None, + count_job: None, + focus_query: true, + typed_at: f64::NEG_INFINITY, + auto_open: std::env::var_os("CP_PREP_OPEN").is_some(), + } + } + + fn db(&self) -> Option> { + self.dbs + .iter() + .find(|d| d.path == self.path) + .and_then(|d| d.db.clone()) + } + + /// Starts the name search for the query, when the lists do not answer it yet. + fn search(&mut self, ctx: &egui::Context, db: &Arc) { + let query = self.query.trim().to_owned(); + if self.answered.as_deref() == Some(query.as_str()) + || self.search.as_ref().is_some_and(|(q, _)| *q == query) + { + return; + } + if query.is_empty() { + self.answered = Some(query); + self.search = None; + self.exact.clear(); + self.similar.clear(); + self.total = 0; + return; + } + let (db, q) = (db.clone(), query.clone()); + let now = ctx.input(|i| i.time); + self.search = Background::spawn(ctx, now, move |_, _| { + Some(prep::candidates(&db, &q, CANDIDATES)) + }) + .map(|j| (query, j)); + } + + fn poll(&mut self, ctx: &egui::Context, db: &Arc) { + if let Some((q, job)) = &self.search + && let Some(r) = job.poll() + { + let q = q.clone(); + self.search = None; + if let Some((list, total)) = r { + let (exact, similar) = split_candidates(&q, list); + self.exact = exact; + self.similar = similar; + self.total = total; + self.answered = Some(q.clone()); + // Ticked by itself: the name the dialog was opened with, the name equal + // to the query, else the only name that matches word for word. + let folded = fold(&q); + let auto = self + .wanted + .take() + .filter(|id| self.exact.iter().any(|c| c.id == *id)) + .or_else(|| { + self.exact + .iter() + .find(|c| fold(&c.name) == folded) + .map(|c| c.id) + }) + .or_else(|| (self.exact.len() == 1).then(|| self.exact[0].id)); + self.ticked = auto.into_iter().collect(); + } + } + // The games by colour of the ticked names. + if let Some((ids, job)) = &self.count_job + && let Some(r) = job.poll() + { + let ids = ids.clone(); + self.count_job = None; + if let Some(c) = r { + self.counts = Some((ids, c)); + } + } + let mut ids = self.ticked.clone(); + ids.sort_unstable(); + if !ids.is_empty() + && self.counts.as_ref().is_none_or(|(c, _)| *c != ids) + && self.count_job.as_ref().is_none_or(|(c, _)| *c != ids) + { + let (db, player) = (db.clone(), Player::new(ids.iter().copied())); + let now = ctx.input(|i| i.time); + self.count_job = Background::spawn(ctx, now, move |_, cancel| { + let found = prep::games_of(&db, &player, Side::Any, cancel)?; + let white = found.iter().filter(|(_, w)| *w).count() as u32; + Some((white, found.len() as u32 - white)) + }) + .map(|j| (ids, j)); + } + } + + /// Draws the dialog; what was chosen, if anything. + pub fn show(&mut self, ctx: &egui::Context, _settings: &mut Settings) -> Option { + let db = self.db(); + if let Some(db) = &db { + self.search(ctx, db); + self.poll(ctx, db); + } + let own_name = base_name(&self.path); + let mut outcome = None; + let ready = db.is_some() && !self.ticked.is_empty(); + let ticked_names: Vec = self + .exact + .iter() + .chain(self.similar.iter()) + .filter(|c| self.ticked.contains(&c.id)) + .map(|c| c.name.clone()) + .collect(); + let ticked_games: u32 = self + .exact + .iter() + .chain(self.similar.iter()) + .filter(|c| self.ticked.contains(&c.id)) + .map(|c| c.games) + .sum(); + let counts = self + .counts + .as_ref() + .filter(|(ids, _)| { + let mut t = self.ticked.clone(); + t.sort_unstable(); + *ids == t + }) + .map(|(_, c)| *c); + let modal = egui::Modal::new(egui::Id::new("prep_dialog")).show(ctx, |ui| { + let screen = ctx.content_rect(); + ui.set_width((screen.width() - 40.0).min(520.0)); + ui.heading(tr("Preparing against an opponent")); + ui.add_space(6.0); + let label_w = 60.0; + // The body scrolls in a low window; the buttons stay under it. + egui::ScrollArea::vertical() + .max_height((screen.height() - 140.0).max(120.0)) + .auto_shrink([false, true]) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.add_sized([label_w, 20.0], egui::Label::new(tr("Database"))); + let width = ui.available_width() - 8.0; + let mut pick = None; + let current = self + .dbs + .iter() + .find(|d| d.path == self.path) + .map(db_label) + .unwrap_or_else(|| own_name.clone()); + egui::ComboBox::from_id_salt("prep_dialog_db") + .selected_text(current) + .width(width) + .truncate() + .show_ui(ui, |ui| { + for d in &self.dbs { + if ui + .selectable_label(d.path == self.path, db_label(d)) + .clicked() + { + pick = Some(d.path.clone()); + } + } + }); + if let Some(p) = pick.filter(|p| *p != self.path) { + self.path = p; + self.answered = None; + self.search = None; + self.ticked.clear(); + self.counts = None; + self.count_job = None; + } + }); + ui.horizontal(|ui| { + ui.add_sized([label_w, 20.0], egui::Label::new(tr("Player"))); + let r = ui.add( + egui::TextEdit::singleline(&mut self.query) + .hint_text(tr("Name or part of it")) + .desired_width(ui.available_width() - 34.0), + ); + if std::mem::take(&mut self.focus_query) && self.query.is_empty() { + r.request_focus(); + } + if r.changed() { + self.typed_at = ui.input(|i| i.time); + self.ticked.clear(); + } + if !self.query.is_empty() + && crate::widgets::small_close_button(ui) + .on_hover_text(tr("Clear")) + .clicked() + { + self.query.clear(); + self.ticked.clear(); + self.typed_at = ui.input(|i| i.time); + } + }); + ui.add_space(2.0); + match &db { + None if self + .dbs + .iter() + .any(|d| d.path == self.path && d.failed.is_some()) => + { + let why = self + .dbs + .iter() + .find(|d| d.path == self.path) + .and_then(|d| d.failed.clone()) + .unwrap_or_default(); + ui.label( + RichText::new(trf( + "This database cannot be opened: {e}", + &[("e", &why)], + )) + .color(ui.visuals().warn_fg_color), + ); + } + None => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(tr("Opening the database…")).weak()); + }); + outcome = Some(DialogOutcome::LoadDb(self.path.clone())); + } + Some(_) => self.candidate_list(ui, label_w), + } + if !self.ticked.is_empty() { + ui.add_space(2.0); + ui.label( + RichText::new(trf( + "Selected: {names} · {n}", + &[ + ("names", &ticked_names.join(", ")), + ("n", &crate::i18n::games(ticked_games as usize)), + ], + )) + .weak(), + ); + } + ui.add_space(8.0); + ui.horizontal_wrapped(|ui| { + ui.add_sized([label_w, 20.0], egui::Label::new(tr("Colour"))); + let (w, b) = match counts { + Some((w, b)) => (w.to_string(), b.to_string()), + None if self.ticked.is_empty() => ("—".to_owned(), "—".to_owned()), + None => ("…".to_owned(), "…".to_owned()), + }; + ui.radio_value( + &mut self.side, + ColorChoice::White, + trf("White — {n}", &[("n", &w)]), + ); + ui.radio_value( + &mut self.side, + ColorChoice::Black, + trf("Black — {n}", &[("n", &b)]), + ); + ui.radio_value(&mut self.side, ColorChoice::Both, tr("Both")); + }); + }); + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let open = ui + .add_enabled( + ready, + egui::Button::new(RichText::new(tr("Open report")).strong()) + .min_size(vec2(0.0, 30.0)), + ) + .on_disabled_hover_text(tr("Tick a player")); + if open.clicked() { + outcome = Some(DialogOutcome::Open(self.start())); + } + if ui.button(tr("Cancel")).clicked() { + outcome = Some(DialogOutcome::Cancel); + } + }); + }); + if modal.should_close() { + outcome = Some(DialogOutcome::Cancel); + } + if outcome.is_none() + && ready + && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) + { + outcome = Some(DialogOutcome::Open(self.start())); + } + if outcome.is_none() && ready && self.auto_open && self.search.is_none() { + self.auto_open = false; + outcome = Some(DialogOutcome::Open(self.start())); + } + if self.search.is_some() || self.count_job.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + outcome + } + + fn start(&self) -> PrepStart { + PrepStart { + path: self.path.clone(), + player: Player::new(self.ticked.iter().copied()), + side: self.side, + } + } + + /// The names that match: tick boxes, the similar names apart. + fn candidate_list(&mut self, ui: &mut Ui, indent: f32) { + if self.search.is_some() && self.answered.as_deref() != Some(self.query.trim()) { + ui.horizontal(|ui| { + ui.add_space(indent); + ui.add(egui::Spinner::new().size(12.0)); + ui.label(RichText::new(tr("Searching…")).weak()); + }); + return; + } + if self.query.trim().is_empty() { + ui.horizontal(|ui| { + ui.add_space(indent); + ui.label( + RichText::new(tr("Type a name: the players of the database are offered")) + .weak(), + ); + }); + return; + } + if self.exact.is_empty() && self.similar.is_empty() { + ui.horizontal(|ui| { + ui.add_space(indent); + ui.label(RichText::new(tr("No such player in this database")).weak()); + }); + return; + } + let rows = self.exact.len() + self.similar.len() + usize::from(!self.similar.is_empty()); + let height = (rows as f32 * 22.0).min(8.0 * 22.0) + 4.0; + egui::ScrollArea::vertical() + .id_salt("prep_candidates") + .max_height(height) + .auto_shrink([false, true]) + .show(ui, |ui| { + let row = |ui: &mut Ui, c: &Candidate, ticked: &mut Vec| { + ui.horizontal(|ui| { + ui.add_space(indent); + let mut on = ticked.contains(&c.id); + let width = ui.available_width() - 90.0; + ui.allocate_ui(vec2(width, 20.0), |ui| { + if ui.add(egui::Checkbox::new(&mut on, &c.name)).changed() { + if on { + ticked.push(c.id); + } else { + ticked.retain(|id| *id != c.id); + } + } + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(crate::i18n::games(c.games as usize)).weak()); + }); + }); + }; + for c in &self.exact { + row(ui, c, &mut self.ticked); + } + if !self.similar.is_empty() { + ui.horizontal(|ui| { + ui.add_space(indent); + ui.label( + RichText::new(tr("Similar names — most likely other people")) + .weak() + .small(), + ); + }); + for c in &self.similar { + row(ui, c, &mut self.ticked); + } + } + if self.total > self.exact.len() + self.similar.len() { + ui.horizontal(|ui| { + ui.add_space(indent); + ui.label( + RichText::new(trf( + "{n} more matches…", + &[("n", &(self.total - self.exact.len() - self.similar.len()))], + )) + .weak(), + ); + }); + } + }); + } +} + +/// The file's name without its extension. +fn base_name(path: &Path) -> String { + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +// ----- the saved preparations ----------------------------------------------------- + +/// What the «Preparations» window asks of the application. +pub enum ListOutcome { + /// The saved preparation of this id. + Open(String), + /// «New preparation…»: the dialog for the chosen database. + New, + Close, +} + +/// The library's «Preparations»: the saved ones, to open, rename or delete. +pub struct PrepList { + items: Vec<(String, crate::prep_saved::SavedPrep)>, + /// The entry being renamed and the name typed. + renaming: Option<(String, String)>, + /// The entry asked about before deleting. + deleting: Option, + error: Option, + /// When the entries were last read (a report being built in the background + /// changes them on disk while this window is open). + last_reload: f64, +} + +impl PrepList { + pub fn new() -> Self { + let mut list = PrepList { + items: Vec::new(), + renaming: None, + deleting: None, + error: None, + last_reload: 0.0, + }; + list.reload(); + list + } + + fn reload(&mut self) { + self.items = crate::prep_saved::dir() + .as_deref() + .map(crate::prep_saved::list) + .unwrap_or_default(); + } + + /// `can_new`: a database is chosen to prepare in. + pub fn show(&mut self, ctx: &egui::Context, can_new: bool) -> Option { + let mut out = None; + let now = ctx.input(|i| i.time); + if now - self.last_reload > 2.0 { + self.reload(); + self.last_reload = now; + } + // Escape while renaming ends the renaming only. + let was_renaming = self.renaming.is_some(); + let modal = egui::Modal::new(egui::Id::new("prep_list")).show(ctx, |ui| { + let screen = ctx.content_rect(); + ui.set_width((screen.width() - 40.0).min(560.0)); + ui.heading(tr("Preparations")); + ui.add_space(6.0); + if self.items.is_empty() { + ui.label( + RichText::new(tr( + "Nothing yet. A preparation is saved by itself as soon as you start it: prepare against a player.", + )) + .weak(), + ); + } + egui::ScrollArea::vertical() + .max_height((screen.height() - 180.0).max(120.0)) + .auto_shrink([false, true]) + .show(ui, |ui| { + for (id, item) in self.items.clone() { + self.row(ui, &id, &item, &mut out); + ui.separator(); + } + }); + if let Some(e) = &self.error { + ui.label(RichText::new(e).color(ui.visuals().warn_fg_color)); + } + ui.add_space(6.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Close")).clicked() { + out = Some(ListOutcome::Close); + } + if ui + .add_enabled(can_new, egui::Button::new(tr("♟ New preparation…"))) + .on_disabled_hover_text(tr("Add a database to the shelf first")) + .on_hover_text(tr("Choose a player in the current database")) + .clicked() + { + out = Some(ListOutcome::New); + } + }); + }); + if modal.should_close() && !was_renaming { + out = out.or(Some(ListOutcome::Close)); + } + out + } + + fn row( + &mut self, + ui: &mut Ui, + id: &str, + item: &crate::prep_saved::SavedPrep, + out: &mut Option, + ) { + let found = item.path.exists(); + if self.renaming.as_ref().is_some_and(|(r, _)| r == id) { + self.rename_row(ui, id); + return; + } + let deleting = self.deleting.as_deref() == Some(id); + // The buttons' room first: the texts are cut to what is left. + let gap = ui.spacing().item_spacing.x; + let pad = 2.0 * ui.spacing().button_padding.x; + let bw = |t: &str| text_width(ui, t, egui::TextStyle::Button) + pad + gap; + let buttons = if deleting { + text_width(ui, tr("Delete?"), egui::TextStyle::Body) + + gap + + bw(tr("Delete")) + + bw(tr("No")) + } else { + bw(tr("Open")) + bw("âœ�") + bw("🗑") + }; + let text_w = (ui.available_width() - buttons - 2.0 * gap).max(80.0); + ui.horizontal(|ui| { + let mut open = false; + ui.allocate_ui(vec2(text_w, 0.0), |ui| { + ui.set_max_width(text_w); + ui.vertical(|ui| { + let title = ui + .add( + egui::Label::new(RichText::new(&item.title).strong()) + .truncate() + .sense(Sense::click()), + ) + .on_hover_text(tr("Double-click to open")); + open |= found && title.double_clicked(); + let mut about = vec![base_name(&item.path)]; + // «за 2 года · 8 партий», «поÑ�ледние 100»: the number once. + match item.period { + Period::All => about.push(crate::i18n::games(item.games as usize)), + Period::Last(n) => about.push(trf("last {n}", &[("n", &n)])), + p => { + let label = period_label(p); + let mut chars = label.chars(); + let lower = chars + .next() + .map(|c| c.to_lowercase().chain(chars).collect()) + .unwrap_or_default(); + about.push(lower); + about.push(crate::i18n::games(item.games as usize)); + } + } + about.push( + match item.color { + ColorChoice::White => tr("as White"), + ColorChoice::Black => tr("as Black"), + ColorChoice::Both => tr("both colours"), + } + .to_owned(), + ); + ui.add(egui::Label::new(RichText::new(about.join(" · ")).weak()).truncate()); + let when = chrono::DateTime::::from( + std::time::UNIX_EPOCH + std::time::Duration::from_secs(item.saved), + ) + .format("%d.%m.%Y") + .to_string(); + let errors = if item.evaluated && !item.errors_current() { + String::new() + } else if item.evaluated { + let e = &item.errors; + trf( + "errors: ?? {b} · ? {m} · ?! {i}", + &[ + ("b", &e.blunders), + ("m", &e.mistakes), + ("i", &e.inaccuracies), + ], + ) + } else { + tr("errors not searched").to_owned() + }; + let path = item.path.display().to_string(); + if found { + let saved = trf("saved {date}", &[("date", &when)]); + let line = if errors.is_empty() { + saved + } else { + format!("{errors} · {saved}") + }; + ui.add(egui::Label::new(RichText::new(line).small().weak()).truncate()); + } else { + ui.add( + egui::Label::new( + RichText::new(trf( + "database not found: {path}", + &[("path", &path)], + )) + .small() + .color(ui.visuals().warn_fg_color), + ) + .truncate(), + ) + .on_hover_text(path); + } + }); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if deleting { + if ui.button(tr("No")).clicked() { + self.deleting = None; + } + if ui.button(tr("Delete")).clicked() { + self.deleting = None; + if let Some(dir) = crate::prep_saved::dir() + && let Err(e) = crate::prep_saved::delete(&dir, id) + { + self.error = Some(e.to_string()); + } + self.reload(); + } + ui.label(tr("Delete?")); + return; + } + if ui.button("🗑").on_hover_text(tr("Delete")).clicked() { + self.deleting = Some(id.to_owned()); + } + if ui.button("âœ�").on_hover_text(tr("Rename")).clicked() { + self.renaming = Some((id.to_owned(), item.title.clone())); + } + open |= ui + .add_enabled(found, egui::Button::new(tr("Open"))) + .on_disabled_hover_text(tr( + "The database is not found: put the file back or delete the preparation", + )) + .clicked(); + }); + if open { + *out = Some(ListOutcome::Open(id.to_owned())); + } + }); + } + + /// The name being typed: Enter or «OK» keeps it, Escape or «Cancel» does not. + fn rename_row(&mut self, ui: &mut Ui, id: &str) { + let mut done = None; + ui.horizontal(|ui| { + let gap = ui.spacing().item_spacing.x; + let pad = 2.0 * ui.spacing().button_padding.x; + let buttons = text_width(ui, tr("OK"), egui::TextStyle::Button) + + text_width(ui, tr("Cancel"), egui::TextStyle::Button) + + 2.0 * (pad + gap); + if let Some((_, text)) = self.renaming.as_mut() { + let r = ui.add( + egui::TextEdit::singleline(text) + .desired_width((ui.available_width() - buttons - gap).max(80.0)), + ); + r.request_focus(); + if ui.input(|i| i.key_pressed(Key::Enter)) { + done = Some(true); + } + if ui.input(|i| i.key_pressed(Key::Escape)) { + done = Some(false); + } + } + if ui.button(tr("OK")).clicked() { + done = Some(true); + } + if ui.button(tr("Cancel")).clicked() { + done = Some(false); + } + }); + if let Some(ok) = done { + let (_, text) = self.renaming.take().unwrap_or_default(); + let text = text.trim(); + if ok + && !text.is_empty() + && let Some(dir) = crate::prep_saved::dir() + { + if let Err(e) = crate::prep_saved::rename(&dir, id, text) { + self.error = Some(e.to_string()); + } + self.reload(); + } + } + } +} + +// ----- the screen ------------------------------------------------------------------ + +/// What the screen asks of the application. +pub enum PrepAction { + /// «⬅ Library»: the report stays in the stack. + Back, + OpenSettings, + /// A game of the report in the game screen, at move `ply` (0: the start). + OpenGame { + path: PathBuf, + index: usize, + ply: usize, + }, + /// The engine run started (the live engine pauses) / ended. + EngineStarted, + EngineEnded, + NeedEngine, + Toast(String), + CopyText(String, &'static str), + /// The line as a new game (no database). + OpenPgn(String), + /// The position on the search board of this database. + FindPosition(PathBuf, Chess, Vec, bool), + PlayFrom(Box), + SettingsChanged, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Tab { + Repertoire, + Openings, + Errors, +} + +/// What is chosen: a node of the tree, an opening, an error — the board and the games +/// list follow it. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Selection { + None, + Node { + white: bool, + node: u32, + }, + Opening { + white: bool, + family: usize, + variation: Option, + }, + Repeated { + white: bool, + index: usize, + }, + Error { + white: bool, + index: usize, + }, +} + +/// A row of the games list (the names and the event come from the database once). +#[derive(Clone)] +struct ListRow { + white: String, + black: String, + white_elo: u16, + black_elo: u16, + result: &'static str, + event: String, +} + +use crate::review::JobMsg; + +struct EngineJob { + runner: crate::review::JobRunner, + rx: Receiver, + cancel: Arc, + total: usize, + done: usize, + /// Engine processes of the run. + processes: usize, + /// Evaluations since the cache was saved. + unsaved: usize, +} + +impl Drop for EngineJob { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +/// The position shown on the board: the line to it and the positions along it. +struct Shown { + sans: Vec, + ucis: Vec, + positions: Vec, + /// The ply shown (`positions[ply]`); the last by default, a click on the line + /// takes the board back along it. + ply: usize, + /// Arrows at the last ply (an error: the move played and the better one). + arrows: Vec, + /// «after 3.Bb5 · better 3.d4 · +0.3 → −1.5» under the line, for an error. + note: Option, + opening: Option, + /// The player's colour the position was chosen from (the board's orientation). + white: bool, +} + +/// An error at a node of the tree: by (the key before the move, the move). +#[derive(Clone)] +struct Mark { + judgement: Judgement, + best_san: String, + before: game_review::Eval, + after: game_review::Eval, + games: u32, +} + +/// A row of the repertoire tree as laid out. +#[derive(Clone, Copy, PartialEq, Eq)] +enum TreeRow { + Node { + white: bool, + node: u32, + depth: usize, + }, + /// «other moves (n)» under a node. + Others { + white: bool, + parent: u32, + depth: usize, + count: usize, + }, +} + +/// A row of the errors tab. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ErrRow { + /// «Repeated errors — …» / «By opening». + RepeatedTitle, + OpeningsTitle, + /// A repeated error (colour, index into `repeated`) and one of its games. + Repeated { + white: bool, + index: usize, + }, + RepeatedGame { + white: bool, + index: usize, + game: u32, + }, + /// A variation with errors (colour, family, variation) and one of its errors. + Variation { + white: bool, + family: usize, + variation: usize, + }, + Error { + white: bool, + index: usize, + }, +} + +impl ErrRow { + fn is_title(self) -> bool { + matches!(self, ErrRow::RepeatedTitle | ErrRow::OpeningsTitle) + } +} + +/// The engine part of the controls. +enum EngineTexts { + Running, + /// A button to start or go on, and a note beside it. + Button { + label: String, + note: Option, + }, + /// Done: a quiet label. + Done { + label: String, + note: Option, + }, +} + +/// Where the engine run stands for the colour(s) shown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum EngineState { + Running, + /// No evaluation yet. + NotRun, + /// Some positions evaluated (a run stopped, a new depth, new games). + Partial { + done: usize, + total: usize, + }, + Complete { + total: usize, + }, +} + +/// Fewer games: the percentages are shown weak. +const FEW_GAMES: u32 = 5; +const BOARD_MIN: f32 = 220.0; +const RIGHT_MIN: f32 = 560.0; +const ROW_H: f32 = 24.0; + +/// The folder of the prep caches (the reports and the evaluations by position). +fn cache_dir() -> Option { + Settings::cache_dir().map(|d| d.join("prep")) +} + +pub struct PrepScreen { + /// This screen's own number (`engine_offer::next_serial`). + pub serial: u64, + /// The engine is taken by another job (the search for great moves, task 27): the + /// search for opening errors does not start, and says why. + pub engine_blocked: Option, + pub path: PathBuf, + db: Arc, + db_name: String, + pub player: Player, + pub names: Vec, + /// On the screen (else kept in the stack under the library). + pub shown: bool, + color: ColorChoice, + plies: usize, + period: Period, + /// Kept in «Preparations» (`prep_saved`): every change is written there too. + /// Every started preparation is kept from the start; the flag goes off only if it + /// was deleted from «Preparations» while this screen lives (not written back then). + saved: bool, + /// A period asked for where the settings are not at hand (applied in `show`). + want_period: Option, + report: Option, + rows: Vec, + /// The games read in the background (hundreds in a moment, a Mega filter in seconds). + build: Option>, + build_total: usize, + job: Option, + cache: PositionCache, + nps_per_thread: Option, + error: Option, + dialog_open: bool, + /// The report changed since it was written to the cache. + dirty: bool, + /// Evaluations came in since the last re-judging (done at most once a second). + pending_refresh: bool, + last_refresh: f64, + marks: [HashMap<(u64, String), Mark>; 2], + tab: Tab, + branches_from: u32, + expanded: HashSet<(bool, u32)>, + others_open: HashSet<(bool, u32)>, + open_families: HashSet<(bool, usize)>, + open_repeated: HashSet<(bool, usize)>, + open_variations: HashSet<(bool, usize, usize)>, + /// The row of the errors tab the keyboard is on. + err_cursor: Option, + /// Inaccuracies shown (`settings.prep.inaccuracies`, read every frame). + show_inaccuracies: bool, + /// The board stands over the lists (a narrow or low window); the window is low. + stacked: bool, + low_window: bool, + selection: Selection, + shown_pos: Option, + /// The user turned the board (else it is the player's colour). + flipped: Option, + board_state: BoardState, + /// In a low window the board is a panel over the lists, opened by a button. + board_popup: bool, + /// The order of each table (the settings' `prep.sorts`, written back on change). + sorts: PrepSorts, + /// The keyboard is in the games list (else in the tab's table). + focus_games: bool, + games_cursor: Option, + hover_arrow: Option<(Square, Square)>, + scroll_to_selected: bool, + /// The games list's height, once the user dragged the border (else 35 %). + games_height: Option, + /// The one automatic engine start of this report was considered. + auto_done: bool, +} + +/// Plays `ucis` from the start; stops at a move that cannot be read. +fn replay(ucis: &[String]) -> Vec { + let mut pos = Chess::default(); + let mut out = vec![pos.clone()]; + for u in ucis { + let Some(m) = u.parse::().ok().and_then(|u| u.to_move(&pos).ok()) else { + break; + }; + pos.play_unchecked(m); + out.push(pos.clone()); + } + out +} + +/// "3.Bb5" / "2…Nc6" for move `ply` (0-based), in the chosen notation. +fn short_label(ply: usize, san: &str) -> String { + let number = ply / 2 + 1; + let label = if ply.is_multiple_of(2) { + format!("{number}.{san}") + } else { + format!("{number}…{san}") + }; + crate::san::show(&label).into_owned() +} + +/// The line as text: "1.e4 c5 2.Nf3 Nc6". +fn line_text(sans: &[String]) -> String { + let mut out = String::new(); + for (i, san) in sans.iter().enumerate() { + if !out.is_empty() { + out.push(' '); + } + if i.is_multiple_of(2) { + out.push_str(&format!("{}.", i / 2 + 1)); + } + out.push_str(san); + } + crate::san::show_line(&out) +} + +/// The table's line ("1. e4 c5 2. Nf3") as the program writes lines: moves with +/// their numbers joined ("1.e4", "c5", "2.Nf3"). +fn table_line(line: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut number: Option<&str> = None; + for tok in line.split_whitespace() { + if tok.ends_with('.') + && tok + .trim_end_matches('.') + .chars() + .all(|c| c.is_ascii_digit()) + { + number = Some(tok); + } else { + out.push(match number.take() { + Some(n) if n.ends_with("...") => format!("{}…{tok}", n.trim_end_matches('.')), + Some(n) => format!("{n}{tok}"), + None => tok.to_owned(), + }); + } + } + out +} + +/// The moves in `width`: whole moves, the first and the last kept, «…» for the middle +/// ones that do not fit (they matter less). +fn fit_line(ui: &Ui, tokens: &[String], width: f32) -> String { + let fits = |t: &str| text_width(ui, t, egui::TextStyle::Body) <= width; + let full = crate::san::show_line(&tokens.join(" ")); + if fits(&full) || tokens.len() < 3 { + return full; + } + // Drop moves from the middle until the rest fits. + let mut head = tokens.len().div_ceil(2); + let mut tail = tokens.len() - head; + loop { + if head > 1 && head >= tail { + head -= 1; + } else if tail > 1 { + tail -= 1; + } else { + return crate::san::show_line(&format!("{} … {}", tokens[0], tokens[tokens.len() - 1])); + } + let text = format!( + "{} … {}", + tokens[..head].join(" "), + tokens[tokens.len() - tail..].join(" ") + ); + let text = crate::san::show_line(&text); + if fits(&text) { + return text; + } + } +} + +/// "01.2026 – 10.2026" from the games' dates (empty without dates). +fn period(games: &[GameInfo]) -> String { + let dated: Vec<&GameInfo> = games.iter().filter(|g| g.date_number() > 0).collect(); + let first = dated.iter().min_by_key(|g| g.date_number()); + let last = dated.iter().max_by_key(|g| g.date_number()); + let month = |g: &GameInfo| -> String { + let parts: Vec<&str> = g.date.split('.').collect(); + match parts.as_slice() { + [y, m, ..] if m.chars().all(|c| c.is_ascii_digit()) && !m.is_empty() => { + format!("{m}.{y}") + } + [y, ..] => (*y).to_string(), + _ => String::new(), + } + }; + match (first, last) { + (Some(a), Some(b)) => { + let (a, b) = (month(a), month(b)); + if a == b { a } else { format!("{a} – {b}") } + } + _ => String::new(), + } +} + +/// The results as a bar, by lightness (White's wins light, draws grey, Black's wins +/// dark, as on the search board) with no numbers in it: the score beside it is the +/// player's, the percentages are in its tooltip. Faint over few games. +fn score_bar(ui: &mut Ui, t: &Tally, white: bool, few: bool) { + let (rect, resp) = ui.allocate_exact_size(vec2(56.0, 12.0), Sense::hover()); + let (white_wins, black_wins) = if white { + (t.wins, t.losses) + } else { + (t.losses, t.wins) + }; + let decided = white_wins + t.draws + black_wins; + let fade = |c: Color32| if few { c.gamma_multiply(0.45) } else { c }; + let painter = ui.painter(); + let outline = if ui.visuals().dark_mode { + Color32::from_gray(0x70) + } else { + ui.visuals().weak_text_color() + }; + if decided > 0 { + let mut x = rect.left(); + for (n, fill) in [ + (white_wins, Color32::from_gray(0xe8)), + (t.draws, Color32::from_gray(0x8c)), + (black_wins, Color32::from_gray(0x2b)), + ] { + let w = rect.width() * n as f32 / decided as f32; + if w > 0.0 { + painter.rect_filled( + egui::Rect::from_min_max( + egui::pos2(x, rect.top()), + egui::pos2(x + w, rect.bottom()), + ), + 0.0, + fade(fill), + ); + } + x += w; + } + } + painter.rect_stroke( + rect, + 2.0, + egui::Stroke::new(1.0, fade(outline)), + egui::StrokeKind::Inside, + ); + if decided > 0 { + let pct = |n: u32| 100 * n / decided; + resp.on_hover_text(trf( + "White wins {w} % · draws {d} % · Black wins {b} %", + &[ + ("w", &pct(white_wins)), + ("d", &pct(t.draws)), + ("b", &pct(black_wins)), + ], + )); + } +} + +fn score_text(t: &Tally) -> String { + t.score() + .map_or_else(|| "—".to_owned(), |s| format!("{:.0} %", 100.0 * s)) +} + +/// "+10 =1 −3". +fn tally_hint(t: &Tally) -> String { + format!("+{} ={} −{}", t.wins, t.draws, t.losses) +} + +fn judgement_weight(j: Judgement) -> u32 { + match j { + Judgement::Blunder => 3, + Judgement::Mistake => 2, + Judgement::Inaccuracy => 1, + Judgement::Great | Judgement::Brilliant => 0, + } +} + +/// A move's mark as a pill: the symbol in white on the colour of the sign. +fn pill(ui: &mut Ui, j: Judgement) -> egui::Response { + let text = review::judgement_symbol(j); + let font = egui::FontId::proportional(11.0); + let galley = ui + .painter() + .layout_no_wrap(text.to_owned(), font, Color32::WHITE); + let size = vec2(galley.size().x + 8.0, 16.0); + let (rect, resp) = ui.allocate_exact_size(size, Sense::hover()); + ui.painter() + .rect_filled(rect, 8.0, review::judgement_color(j)); + ui.painter() + .galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE); + resp +} + +const COUNTS_GAP: f32 = 4.0; + +fn count_parts(c: &ErrorCounts) -> Vec<(u32, Judgement)> { + [ + (c.inaccuracies, Judgement::Inaccuracy), + (c.mistakes, Judgement::Mistake), + (c.blunders, Judgement::Blunder), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .collect() +} + +/// The width of [`counts_text`], including its separator Labels and gaps. +fn errors_text_width(ui: &Ui, c: &ErrorCounts) -> f32 { + let parts = count_parts(c); + let counts = parts + .iter() + .map(|(n, j)| { + text_width( + ui, + &format!("{n} {}", review::judgement_symbol(*j)), + egui::TextStyle::Body, + ) + }) + .sum::(); + let separators = parts.len().saturating_sub(1) as f32; + counts + separators * text_width(ui, "·", egui::TextStyle::Body) + 2.0 * separators * COUNTS_GAP +} + +/// "3 ? · 1 ??" in the colours of the signs (nothing when there are none). +fn counts_text(ui: &mut Ui, c: &ErrorCounts) { + let dark = ui.visuals().dark_mode; + let old_gap = ui.spacing().item_spacing.x; + ui.spacing_mut().item_spacing.x = COUNTS_GAP; + for (i, (n, j)) in count_parts(c).into_iter().enumerate() { + if i > 0 { + ui.label(RichText::new("·").weak()); + } + ui.label( + RichText::new(format!("{n} {}", review::judgement_symbol(j))) + .color(review::judgement_text_color(j, dark)), + ); + } + ui.spacing_mut().item_spacing.x = old_gap; +} + +impl PrepScreen { + pub fn new( + start: PrepStart, + db: Arc, + settings: &Settings, + ctx: &egui::Context, + ) -> Self { + let dir = cache_dir(); + let mut cache = dir.as_deref().map(PositionCache::load).unwrap_or_default(); + // A saved preparation of this player: its depth and games, its report. + let saved_dir = crate::prep_saved::dir(); + let names = start.player.names(&db); + let saved_id = crate::prep_saved::id(&start.path, &names); + let saved = saved_dir + .as_deref() + .and_then(|d| crate::prep_saved::get(d, &saved_id)); + let saved_report = saved + .as_ref() + .and(saved_dir.as_deref()) + .and_then(|d| crate::prep_saved::report(d, &saved_id)); + let had_saved_report = saved_report.is_some(); + let plies = saved + .as_ref() + .map_or(settings.prep.plies, |s| s.plies) + .clamp(2, 60); + let period = saved.as_ref().map_or(settings.prep.period, |s| s.period); + let options = Options { + plies, + side: Side::Any, + period, + }; + // The saved report as it is, when the database is the same; else its + // evaluations serve the report made again (new games of the database). + let fresh = saved_report.and_then(|r| { + if r.search != game_review::SEARCH_VERSION { + return None; + } + if r.fingerprint == prep::fingerprint(&db) + && r.options() == options + && r.player == start.player + { + return Some(r); + } + for (k, e) in r.evals { + cache.insert(k, e); + } + None + }); + let mut screen = PrepScreen { + serial: crate::engine_offer::next_serial(), + engine_blocked: None, + db_name: base_name(&start.path), + path: start.path, + db, + player: start.player, + names, + shown: true, + color: start.side, + plies, + period, + saved: crate::prep_saved::dir().is_some(), + want_period: None, + report: None, + rows: Vec::new(), + build: None, + build_total: 0, + job: None, + cache, + nps_per_thread: None, + error: None, + dialog_open: false, + dirty: false, + pending_refresh: false, + last_refresh: 0.0, + marks: [HashMap::new(), HashMap::new()], + tab: match std::env::var("CP_PREP_TAB").as_deref() { + Ok("openings") => Tab::Openings, + Ok("errors") => Tab::Errors, + _ => Tab::Repertoire, + }, + branches_from: settings.prep.branches_from.clamp(1, 20), + expanded: HashSet::new(), + others_open: HashSet::new(), + open_families: HashSet::new(), + open_repeated: HashSet::new(), + open_variations: HashSet::new(), + err_cursor: None, + show_inaccuracies: settings.prep.inaccuracies, + stacked: false, + low_window: false, + selection: Selection::None, + shown_pos: None, + flipped: None, + board_state: BoardState::default(), + board_popup: false, + sorts: settings.prep.sorts.clone(), + focus_games: false, + games_cursor: None, + hover_arrow: None, + scroll_to_selected: false, + games_height: None, + auto_done: false, + }; + let cached = fresh.or_else(|| { + dir.as_deref() + .and_then(|d| PrepReport::load(d, &screen.db, &screen.player, &options)) + }); + match cached { + Some(r) => screen.take_report(r), + None => screen.rebuild(ctx), + } + // A preparation is kept from the moment it is started: the list entry at + // once, the report as soon as it is built (then `save` writes both). + // A saved report missing on disk (a crash between the writes) is restored + // from the cache the same way. + let restore = saved.is_some() && !had_saved_report && screen.report.is_some(); + let rejudged = + saved.as_ref().is_some_and(|s| !s.errors_current()) && screen.report.is_some(); + if screen.saved && (saved.is_none() || restore || rejudged) { + let result = if screen.report.is_some() { + screen.keep() + } else { + screen.keep_meta() + }; + if let Err(e) = result { + eprintln!("prep saved: {e}"); + // Not silently unsaved: told on the screen, tried again by `save`. + screen.dirty = true; + screen.error = Some(trf("Could not save: {e}", &[("e", &e.to_string())])); + } + } + screen + } + + /// The same database and player: the report as it was. + pub fn matches(&self, path: &Path, player: &Player) -> bool { + self.path == path && self.player == *player + } + + pub fn running(&self) -> bool { + self.job.is_some() + } + + /// The background work goes on while the report is not on the screen (a game + /// opened from it, the library): its results are taken in here. + pub fn poll_quietly(&mut self, ctx: &egui::Context, settings: &Settings) { + let mut actions = Vec::new(); + self.poll(ctx, settings, &mut actions); + } + + /// The engine run after an engine was installed for it. + pub fn start_after_engine(&mut self, ctx: &egui::Context) -> Vec { + let mut actions = Vec::new(); + self.start_engine(ctx, &mut actions); + actions + } + + pub fn title(&self) -> String { + let name = self.names.first().cloned().unwrap_or_default(); + trf("Preparing against {name}", &[("name", &name)]) + } + + /// Reads the games anew (a new depth; the database read again). + fn rebuild(&mut self, ctx: &egui::Context) { + self.job = None; + let (db, player) = (self.db.clone(), self.player.clone()); + let options = self.options(); + self.build_total = 0; + let now = ctx.input(|i| i.time); + self.build = Background::spawn(ctx, now, move |progress, cancel| { + prep::build(&db, &player, &options, progress, cancel) + }); + } + + /// A report arrived (built or from the cache): the rows of the games list, the + /// cached evaluations, the default expansion. + fn take_report(&mut self, mut report: PrepReport) { + self.auto_done = false; + let taken = report.take_cached(&self.cache); + self.dirty |= taken > 0; + self.rows = report + .games + .iter() + .map(|g| { + let r = self.db.row(g.index as usize); + ListRow { + white: r.white, + black: r.black, + white_elo: r.white_elo, + black_elo: r.black_elo, + result: r.result, + event: r.event, + } + }) + .collect(); + // Everything folded: the user opens what he wants (the roots too). + self.expanded.clear(); + self.others_open.clear(); + self.open_families.clear(); + self.open_variations.clear(); + self.open_repeated.clear(); + self.report = Some(report); + self.rebuild_marks(); + self.selection = Selection::None; + self.shown_pos = None; + self.games_cursor = None; + self.err_cursor = None; + } + + /// The same player asked for again from the dialog: its colour. + pub fn reopen(&mut self, side: ColorChoice) { + self.shown = true; + // Deleted from «Preparations» while this screen was hidden: not written back. + self.saved &= crate::prep_saved::dir().is_some_and(|d| { + crate::prep_saved::get(&d, &crate::prep_saved::id(&self.path, &self.names)).is_some() + }); + self.set_color(side); + } + + fn set_color(&mut self, color: ColorChoice) { + // The colour a saved preparation opens with. + self.dirty |= self.saved && color != self.color; + self.color = color; + // A selection of a colour no longer shown is dropped. + let keep = match &self.selection { + Selection::None => true, + Selection::Node { white, .. } + | Selection::Opening { white, .. } + | Selection::Repeated { white, .. } + | Selection::Error { white, .. } => color.colours().contains(white), + }; + if !keep { + self.select(Selection::None); + } + } + + /// Games of the colour(s) shown. + fn shown_games(&self) -> usize { + self.report.as_ref().map_or(0, |r| { + self.color + .colours() + .iter() + .map(|&w| r.color(w).games.len()) + .sum() + }) + } + + /// What the report is built with. + fn options(&self) -> Options { + Options { + plies: self.plies, + side: Side::Any, + period: self.period, + } + } + + /// Another depth: the report of that depth from the cache, else built anew. + fn set_plies(&mut self, plies: usize, settings: &mut Settings, ctx: &egui::Context) { + if plies == self.plies { + return; + } + self.stop_engine(&mut Vec::new()); + self.save(); + self.plies = plies; + settings.prep.plies = plies; + self.load_or_build(ctx); + } + + /// Other games of the player: the report of them from the cache, else built anew. + fn set_period(&mut self, period: Period, settings: &mut Settings, ctx: &egui::Context) { + if period == self.period { + return; + } + self.stop_engine(&mut Vec::new()); + self.save(); + self.period = period; + settings.prep.period = period; + self.load_or_build(ctx); + } + + /// The report of the current options from the cache, else built anew. + fn load_or_build(&mut self, ctx: &egui::Context) { + self.report = None; + let options = self.options(); + let cached = cache_dir() + .as_deref() + .and_then(|d| PrepReport::load(d, &self.db, &self.player, &options)); + match cached { + Some(r) => { + self.take_report(r); + if let Some(report) = self.report.as_mut() + && report.engine_stopped + { + report.engine_stopped = false; + self.dirty = true; + } + self.dirty |= self.saved; + self.save(); + } + None => self.rebuild(ctx), + } + } + + /// The judgement is shown (inaccuracies can be hidden). + fn visible(&self, j: Judgement) -> bool { + self.show_inaccuracies || j != Judgement::Inaccuracy + } + + /// The counts as shown. + fn shown_counts(&self, c: &ErrorCounts) -> ErrorCounts { + let mut c = *c; + if !self.show_inaccuracies { + c.inaccuracies = 0; + } + c + } + + /// The engine run for the colour(s) shown. + fn engine_state(&self) -> EngineState { + if self.job.is_some() { + return EngineState::Running; + } + let Some(report) = &self.report else { + return EngineState::NotRun; + }; + let side = self.color.side(); + if !report.evaluated() { + // Stopped before the first evaluation: not «never run», but 0 of N with + // «Continue». + if report.engine_stopped { + let total = report.distinct_positions_for(side); + return EngineState::Partial { done: 0, total }; + } + return EngineState::NotRun; + } + let total = report.distinct_positions_for(side); + let missing = report.missing_for(side); + if missing == 0 { + EngineState::Complete { total } + } else { + EngineState::Partial { + done: total - missing, + total, + } + } + } + + /// Judges the errors anew (`f` changes the evaluations): the lists of errors are + /// rebuilt, so a chosen error is found again in them by what it is, not by its + /// place (else the choice is dropped). + fn rejudge(&mut self, f: impl FnOnce(&mut PrepReport)) { + let Some(report) = self.report.as_mut() else { + return; + }; + // What the selection and the errors tab's row are, by content. + let error_id = |r: &PrepReport, white: bool, i: usize| { + r.color(white).errors.get(i).map(|e| (e.game, e.ply)) + }; + let repeated_id = |r: &PrepReport, white: bool, i: usize| { + r.color(white) + .repeated + .get(i) + .map(|x| (x.key, x.uci.clone())) + }; + let sel = match &self.selection { + Selection::Error { white, index } => { + error_id(report, *white, *index).map(|id| (*white, Ok(id))) + } + Selection::Repeated { white, index } => { + repeated_id(report, *white, *index).map(|id| (*white, Err(id))) + } + _ => None, + }; + let cursor = match self.err_cursor { + Some(ErrRow::Error { white, index }) => { + error_id(report, white, index).map(|id| (white, Ok(id))) + } + Some(ErrRow::Repeated { white, index }) => { + repeated_id(report, white, index).map(|id| (white, Err(id))) + } + _ => None, + }; + let open: Vec<(bool, (u64, String))> = self + .open_repeated + .iter() + .filter_map(|&(w, i)| repeated_id(report, w, i).map(|id| (w, id))) + .collect(); + f(report); + let find = |r: &PrepReport, + white: bool, + id: &Result<(u32, u32), (u64, String)>| + -> Option { + match id { + Ok((game, ply)) => r + .color(white) + .errors + .iter() + .position(|e| e.game == *game && e.ply == *ply), + Err((key, uci)) => r + .color(white) + .repeated + .iter() + .position(|x| x.key == *key && x.uci == *uci), + } + }; + if let Some((white, id)) = &sel { + let found = find(report, *white, id); + self.selection = match (found, id) { + (Some(index), Ok(_)) => Selection::Error { + white: *white, + index, + }, + (Some(index), Err(_)) => Selection::Repeated { + white: *white, + index, + }, + (None, _) => Selection::None, + }; + if found.is_none() { + self.shown_pos = None; + } + } + if let Some((white, id)) = &cursor { + self.err_cursor = match (find(report, *white, id), id) { + (Some(index), Ok(_)) => Some(ErrRow::Error { + white: *white, + index, + }), + (Some(index), Err(_)) => Some(ErrRow::Repeated { + white: *white, + index, + }), + (None, _) => None, + }; + } else if matches!(self.err_cursor, Some(ErrRow::RepeatedGame { .. })) { + self.err_cursor = None; + } + self.open_repeated = open + .into_iter() + .filter_map(|(w, (key, uci))| { + let i = report + .color(w) + .repeated + .iter() + .position(|x| x.key == key && x.uci == uci)?; + Some((w, i)) + }) + .collect(); + self.rebuild_marks(); + } + + /// The errors by node, for the tree and the hover texts. + fn rebuild_marks(&mut self) { + let Some(report) = &self.report else { return }; + for (i, cr) in [&report.white, &report.black].into_iter().enumerate() { + let mut map: HashMap<(u64, String), Mark> = HashMap::new(); + for e in &cr.errors { + let m = map.entry((e.key, e.uci.clone())).or_insert_with(|| Mark { + judgement: e.judgement, + best_san: e.best_san.clone(), + before: e.before, + after: e.after, + games: 0, + }); + m.games += 1; + } + self.marks[i] = map; + } + } + + fn mark_of(&self, white: bool, key: u64, uci: &str) -> Option<&Mark> { + self.marks[usize::from(!white)].get(&(key, uci.to_owned())) + } + + // ----- the background work ----------------------------------------------------- + + fn poll(&mut self, ctx: &egui::Context, settings: &Settings, actions: &mut Vec) { + if let Some(job) = &self.build + && let Some(r) = job.poll() + { + self.build = None; + match r { + Some(report) => { + self.take_report(report); + // A saved preparation follows its new games and depth; the first + // report of a just started one is written at once, not on quitting. + self.dirty |= self.saved; + self.save(); + } + None => self.error = Some(tr("The games could not be read").to_owned()), + } + } + self.show_inaccuracies = settings.prep.inaccuracies; + self.poll_engine(ctx, actions); + // The one automatic engine run of this report, once it is built; a manual + // Stop forbids it. Without an engine there is no offer by itself: the Errors + // tab says so and offers the download. + if !self.auto_done && self.build.is_none() { + self.auto_done = true; + let start = self + .report + .as_ref() + .is_some_and(|r| !r.engine_stopped && !r.targets_for(self.color.side()).is_empty()); + if start { + if crate::review_engine::engine().is_some() { + self.start_engine(ctx, actions); + } else { + self.tab = Tab::Errors; + } + } + } + if self.build.is_some() || self.job.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + + // ----- the engine ---------------------------------------------------------------- + + /// Positions the next run has to evaluate, and how long it takes. + fn estimate(&self) -> (usize, f64) { + let Some(report) = &self.report else { + return (0, 0.0); + }; + let missing = report.missing_for(self.color.side()); + (missing, self.secs_for(missing, review::processes())) + } + + /// Seconds `positions` take in `processes` engine processes. + fn secs_for(&self, positions: usize, processes: usize) -> f64 { + let nps = self.nps_per_thread.unwrap_or(review::DEFAULT_NPS); + game_review::estimate_secs(positions, nps, processes) + } + + /// The button: the search at once, no dialog; the options are only the «▾» dialog. + fn engine_asked(&mut self, ctx: &egui::Context, actions: &mut Vec) { + // Nothing to evaluate: no engine offer, just the state (an empty report too). + if self + .report + .as_ref() + .is_some_and(|r| r.targets_for(self.color.side()).is_empty()) + { + self.tab = Tab::Errors; + actions.push(PrepAction::Toast( + tr("Every position is already evaluated").to_owned(), + )); + return; + } + if crate::review_engine::engine().is_none() { + actions.push(PrepAction::NeedEngine); + return; + } + self.start_engine(ctx, actions); + } + + /// Starts the search for opening errors: Stockfish 19 (`review_engine`) with the fixed + /// search of the game analysis (`game_review::run`), the same on every computer. + fn start_engine(&mut self, ctx: &egui::Context, actions: &mut Vec) { + // A running search is not restarted (e.g. «Find errors» in the options dialog). + if self.job.is_some() { + return; + } + if let Some(why) = &self.engine_blocked { + self.error = Some(why.clone()); + return; + } + self.error = None; + // A start by hand (or by the new report) clears the manual Stop of this one. + if let Some(report) = self.report.as_mut() + && report.engine_stopped + { + report.engine_stopped = false; + self.dirty = true; + } + let Some(path) = crate::review_engine::engine() else { + actions.push(PrepAction::NeedEngine); + return; + }; + let cache = std::mem::take(&mut self.cache); + let mut taken = 0; + self.rejudge(|r| taken = r.take_cached(&cache)); + self.cache = cache; + self.dirty |= taken > 0; + let Some(report) = self.report.as_ref() else { + return; + }; + let targets = report.targets_for(self.color.side()); + if targets.is_empty() { + actions.push(PrepAction::Toast( + tr("Every position is already evaluated").to_owned(), + )); + self.tab = Tab::Errors; + return; + } + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = targets.len(); + let job_settings = JobSettings::new(review::processes(), None); + let processes = job_settings.processes; + let spawned = review::spawn_job( + "prep-engine", + path, + job_settings, + targets, + cancel.clone(), + tx, + ctx.clone(), + ); + let runner = match spawned { + Ok(r) => r, + Err(e) => { + self.error = Some(e.to_string()); + return; + } + }; + self.job = Some(EngineJob { + runner, + rx, + cancel, + total, + done: 0, + processes, + unsaved: 0, + }); + self.tab = Tab::Errors; + actions.push(PrepAction::EngineStarted); + } + + fn poll_engine(&mut self, ctx: &egui::Context, actions: &mut Vec) { + let Some(job) = self.job.as_mut() else { return }; + let Some(report) = self.report.as_mut() else { + return; + }; + let mut ended = false; + let mut got = false; + job.runner.pump(); + while let Ok(msg) = job.rx.try_recv() { + match msg { + JobMsg::Event(e) => { + if let JobEvent::Eval { nps, .. } = &e { + job.done += 1; + // One engine thread per process. + if *nps > 0 { + self.nps_per_thread = Some(*nps as f64); + } + } + if let Some((k, eval)) = report.apply(&e) { + self.cache.insert(k, eval); + job.unsaved += 1; + got = true; + } + } + JobMsg::Done => ended = true, + JobMsg::Failed(e) => { + self.error = Some(e); + ended = true; + } + } + } + if got { + self.pending_refresh = true; + self.dirty = true; + } + if job.unsaved >= 200 + && let Some(dir) = cache_dir() + { + let _ = self.cache.save(&dir); + job.unsaved = 0; + } + let now = ctx.input(|i| i.time); + if self.pending_refresh && (ended || now - self.last_refresh > 1.0) { + self.pending_refresh = false; + self.last_refresh = now; + self.rejudge(PrepReport::refresh); + } + if ended { + self.job = None; + self.save(); + actions.push(PrepAction::EngineEnded); + } + } + + /// Stops the engine run (quitting): what was evaluated is kept. + pub fn stop(&mut self) { + self.stop_engine(&mut Vec::new()); + } + + /// «Stop»: what was evaluated stays, including what is already in the channel. + fn stop_engine(&mut self, actions: &mut Vec) { + if let Some(mut job) = self.job.take() { + if let Some(report) = self.report.as_mut() { + job.runner.pump(); + while let Ok(msg) = job.rx.try_recv() { + if let JobMsg::Event(e) = msg + && let Some((k, eval)) = report.apply(&e) + { + self.cache.insert(k, eval); + // The drained evaluations belong in the saved report too. + self.dirty = true; + } + } + } + self.rejudge(PrepReport::refresh); + self.pending_refresh = false; + self.save(); + actions.push(PrepAction::EngineEnded); + } + } + + /// «Stop» pressed by the user: the evaluations stay, and this report is not run + /// automatically again (a new depth/period or «Continue» clears that). + fn stop_engine_by_user(&mut self, actions: &mut Vec) { + if self.job.is_some() + && let Some(report) = self.report.as_mut() + { + report.engine_stopped = true; + // Even before the first evaluation the stop is written, not lost on exit. + self.dirty = true; + } + self.stop_engine(actions); + } + + /// Writes the report and the evaluations to the cache, and to «Preparations» when + /// the preparation is kept there. + pub fn save(&mut self) { + let Some(dir) = cache_dir() else { return }; + if let Err(e) = self.cache.save(&dir) { + eprintln!("prep cache: {}: {e}", dir.display()); + } + if self.dirty + && let Some(r) = &self.report + { + let mut ok = true; + if let Err(e) = r.save(&dir) { + ok = false; + eprintln!("prep report: {}: {e}", dir.display()); + } + // Deleted from «Preparations» meanwhile: not written back. + self.saved &= crate::prep_saved::dir().is_some_and(|d| { + crate::prep_saved::get(&d, &crate::prep_saved::id(&self.path, &self.names)) + .is_some() + }); + if self.saved + && let Err(e) = self.keep() + { + ok = false; + eprintln!("prep saved: {e}"); + } + if ok { + self.dirty = false; + } + } + } + + /// Writes the preparation to «Preparations» (its name in the list kept). + fn keep(&self) -> std::io::Result<()> { + let dir = + crate::prep_saved::dir().ok_or_else(|| std::io::Error::other("no data folder"))?; + let Some(report) = &self.report else { + return Ok(()); + }; + crate::prep_saved::save(&dir, &self.saved_meta(), report) + } + + /// Writes only the list entry: a preparation just started, its report not built yet. + fn keep_meta(&self) -> std::io::Result<()> { + let dir = + crate::prep_saved::dir().ok_or_else(|| std::io::Error::other("no data folder"))?; + crate::prep_saved::save_meta(&dir, &self.saved_meta()) + } + + /// The list entry as it is now; the counts of the report, when there is one. + fn saved_meta(&self) -> crate::prep_saved::SavedPrep { + let id = crate::prep_saved::id(&self.path, &self.names); + let previous = crate::prep_saved::dir().and_then(|d| crate::prep_saved::get(&d, &id)); + let title = previous + .as_ref() + .map(|m| m.title.clone()) + .unwrap_or_else(|| self.names.first().cloned().unwrap_or_default()); + let book = previous.map_or_else(PathBuf::new, |m| m.book); + let mut errors = ErrorCounts::default(); + let mut games = 0; + let mut evaluated = false; + if let Some(report) = &self.report { + for c in [&report.white, &report.black] { + errors.inaccuracies += c.counts.inaccuracies; + errors.mistakes += c.counts.mistakes; + errors.blunders += c.counts.blunders; + } + games = report.games.len() as u32; + evaluated = report.evaluated(); + } + crate::prep_saved::SavedPrep { + title, + path: self.path.clone(), + player: self.player.clone(), + names: self.names.clone(), + plies: self.plies, + period: self.period, + color: self.color, + book, + saved: crate::prep_saved::now(), + games, + errors, + evaluated, + error_selection_version: crate::prep_saved::ERROR_SELECTION_VERSION, + } + } + + /// The options dialog (§4.2), only by the explicit «▾». + fn engine_dialog( + &mut self, + ctx: &egui::Context, + _settings: &mut Settings, + actions: &mut Vec, + ) { + if !self.dialog_open { + return; + } + let mut start = false; + let moves = self.plies.div_ceil(2); + let (white_n, black_n) = self + .report + .as_ref() + .map_or((0, 0), |r| (r.white.games.len(), r.black.games.len())); + let modal = egui::Modal::new(egui::Id::new("prep_engine_dialog")).show(ctx, |ui| { + let screen = ctx.content_rect(); + ui.set_width((screen.width() - 40.0).min(460.0)); + ui.heading(tr("Opening errors")); + ui.label( + RichText::new(trf( + "The engine evaluates the first {n} moves of every game of the opponent. The games are not changed.", + &[("n", &moves)], + )) + .weak(), + ); + ui.add_space(8.0); + egui::ScrollArea::vertical() + .max_height((screen.height() - 160.0).max(100.0)) + .auto_shrink([false, true]) + .show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + ui.label(tr("Colour")); + for (choice, n) in [ + (ColorChoice::White, white_n), + (ColorChoice::Black, black_n), + (ColorChoice::Both, white_n + black_n), + ] { + let label = format!("{} — {}", choice.label(), crate::i18n::games(n)); + ui.radio_value(&mut self.color, choice, label); + } + }); + ui.add_space(6.0); + let (missing, secs) = self.estimate(); + let all = self + .report + .as_ref() + .map_or(0, |r| r.distinct_positions_for(self.color.side())); + ui.label(trf( + "{n} positions, about {time}", + &[("n", &grouped(missing)), ("time", &review::format_duration(secs))], + )); + let cached = all.saturating_sub(missing); + let note = if cached > 0 { + trf( + "identical positions are counted once; {n} already evaluated earlier", + &[("n", &grouped(cached))], + ) + } else { + tr("identical positions are counted once").to_owned() + }; + ui.label(RichText::new(note).weak().small()); + }); + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .button(RichText::new(tr("Find errors")).strong().size(16.0)) + .clicked() + { + start = true; + } + if ui.button(tr("Cancel")).clicked() { + self.dialog_open = false; + } + }); + }); + if modal.should_close() { + self.dialog_open = false; + } + if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) { + start = true; + } + if start { + self.dialog_open = false; + self.engine_asked(ctx, actions); + } + } + + // ----- the selection and the board --------------------------------------------- + + fn select(&mut self, sel: Selection) { + if self.selection == sel { + return; + } + self.selection = sel; + self.games_cursor = None; + self.shown_pos = self.shown_for(&self.selection); + self.board_state.clear(); + } + + /// The position of a selection and the way to it. + fn shown_for(&self, sel: &Selection) -> Option { + let report = self.report.as_ref()?; + let from_game = |g: &GameInfo, ply: usize, white: bool| -> Shown { + let ucis: Vec = g.ucis[..ply.min(g.ucis.len())].to_vec(); + let sans: Vec = g.sans[..ucis.len()].to_vec(); + let positions = replay(&ucis); + Shown { + ply: positions.len() - 1, + sans, + ucis, + positions, + arrows: Vec::new(), + note: None, + opening: None, + white, + } + }; + match sel { + Selection::None => None, + Selection::Node { white, node } => { + let cr = report.color(*white); + let n = cr.tree.nodes.get(*node as usize)?; + let g = &report.games[*n.games.first()? as usize]; + let mut s = from_game(g, usize::from(n.ply), *white); + s.opening = n.opening; + Some(s) + } + Selection::Opening { + white, + family, + variation, + } => { + let cr = report.color(*white); + let fam = cr.families.get(*family)?; + let var = match variation { + Some(v) => fam.variations.get(*v)?, + None => fam.variations.first()?, + }; + // The named position: a game of the variation at its named ply; the + // family's: the shallowest of its variations' names. + let (g, ply) = match variation { + Some(_) => { + let g = var + .games + .iter() + .map(|&g| &report.games[g as usize]) + .find(|g| g.opening == var.opening)?; + (g, g.named.unwrap_or(0) as usize) + } + None if fam.name.is_empty() => { + // No name: the start position. + let g = var.games.first().map(|&g| &report.games[g as usize])?; + (g, 0) + } + None => { + // The family's own position: where its name first appears in + // a line (the shallowest among the games). + let mut best: Option<(&GameInfo, usize)> = None; + for v in &fam.variations { + for &gi in &v.games { + let g = &report.games[gi as usize]; + if g.opening.is_none() { + continue; + } + let ply = family_ply(g, &fam.name) + .unwrap_or(g.named.unwrap_or(0) as usize); + if best.is_none_or(|(_, p)| ply < p) { + best = Some((g, ply)); + } + } + } + best? + } + }; + let mut s = from_game(g, ply, *white); + s.opening = var.opening; + Some(s) + } + Selection::Repeated { white, index } => { + let cr = report.color(*white); + let r = cr.repeated.get(*index)?; + let g = &report.games[*r.games.first()? as usize]; + let mut s = from_game(g, r.ply as usize, *white); + s.arrows = error_arrows( + &s.positions[s.ply], + &r.uci, + cr.errors + .iter() + .find(|e| e.key == r.key && e.uci == r.uci) + .map(|e| e.best_uci.as_str()), + r.judgement, + ); + s.note = cr + .errors + .iter() + .find(|e| e.key == r.key && e.uci == r.uci) + .map(error_note); + s.opening = r.opening; + Some(s) + } + Selection::Error { white, index } => { + let cr = report.color(*white); + let e = cr.errors.get(*index)?; + let g = &report.games[e.game as usize]; + let mut s = from_game(g, e.ply as usize, *white); + s.arrows = + error_arrows(&s.positions[s.ply], &e.uci, Some(&e.best_uci), e.judgement); + s.note = Some(error_note(e)); + s.opening = e.opening; + Some(s) + } + } + } + + /// The games of the selection (indices into the report), newest first. + fn games_of(&self) -> Vec { + let Some(report) = &self.report else { + return Vec::new(); + }; + let list: Vec = match &self.selection { + Selection::None => self + .color + .colours() + .iter() + .flat_map(|&w| report.color(w).games.iter().copied()) + .collect(), + // The games of the position, by any move order. + Selection::Node { white, node } => { + let tree = &report.color(*white).tree; + tree.nodes + .get(*node as usize) + .map(|n| tree.position_games(n.key)) + .unwrap_or_default() + } + Selection::Opening { + white, + family, + variation, + } => report + .color(*white) + .families + .get(*family) + .map(|f| match variation { + Some(v) => f + .variations + .get(*v) + .map(|v| v.games.clone()) + .unwrap_or_default(), + None => f + .variations + .iter() + .flat_map(|v| v.games.iter().copied()) + .collect(), + }) + .unwrap_or_default(), + Selection::Repeated { white, index } => report + .color(*white) + .repeated + .get(*index) + .map(|r| r.games.clone()) + .unwrap_or_default(), + Selection::Error { white, index } => report + .color(*white) + .errors + .get(*index) + .map(|e| vec![e.game]) + .unwrap_or_default(), + }; + let sort = self.sorts.games; + let val = |gi: u32| -> SortVal { + let g = &report.games[gi as usize]; + let r = &self.rows[gi as usize]; + match sort.key { + GameSort::White => SortVal::Text(fold(&r.white)), + GameSort::Black => SortVal::Text(fold(&r.black)), + GameSort::WhiteElo => num(r.white_elo), + GameSort::BlackElo => num(r.black_elo), + GameSort::Result => SortVal::Text(r.result.to_owned()), + GameSort::Date => num(g.date_number()), + GameSort::Then => SortVal::Text( + g.sans + .iter() + .skip(self.game_ply(gi)) + .take(3) + .cloned() + .collect::>() + .join(" "), + ), + GameSort::Event => SortVal::Text(fold(&r.event)), + GameSort::Errors => num(report + .color(g.white) + .errors + .iter() + .filter(|e| e.game == gi && self.visible(e.judgement)) + .map(|e| judgement_weight(e.judgement)) + .sum::()), + } + }; + let mut keyed: Vec<(SortVal, u32)> = list.into_iter().map(|g| (val(g), g)).collect(); + keyed.sort_by(|a, b| sort.apply(cmp_val(&a.0, &b.0))); + keyed.into_iter().map(|(_, g)| g).collect() + } + + /// The move of the selection to open a game at. + fn selection_ply(&self) -> usize { + self.shown_pos.as_ref().map_or(0, |s| s.ucis.len()) + } + + /// Where game `gi` reaches the chosen position: a node's position may come by + /// another move order (another ply) in some of its games. + fn game_ply(&self, gi: u32) -> usize { + if let (Selection::Node { white, node }, Some(report)) = (&self.selection, &self.report) + && let Some(n) = report.color(*white).tree.nodes.get(*node as usize) + && let Some(p) = report.games[gi as usize] + .keys + .iter() + .position(|k| *k == n.key) + { + return p; + } + self.selection_ply() + } + + /// The move to open game `gi` at: the chosen position, or after the error. + fn open_ply(&self, gi: u32) -> usize { + let after = matches!( + self.selection, + Selection::Error { .. } | Selection::Repeated { .. } + ); + self.game_ply(gi) + usize::from(after) + } + + /// The player's colour the board is seen from. + fn board_white(&self) -> bool { + let base = self + .shown_pos + .as_ref() + .map_or(self.color != ColorChoice::Black, |s| s.white); + match self.flipped { + Some(f) => f == base, + None => base, + } + } + + // ----- the frame ----------------------------------------------------------------- + + /// Draws the screen; what the application has to do. + pub fn show(&mut self, ui: &mut Ui, settings: &mut Settings) -> Vec { + let mut actions = Vec::new(); + let ctx = ui.ctx().clone(); + self.poll(&ctx, settings, &mut actions); + self.hover_arrow = None; + let typing = ctx.egui_wants_keyboard_input(); + let overlay = crate::app::overlay_open(&ctx) || self.dialog_open; + + egui::Panel::top("prep_header").show(ui, |ui| { + ui.add_space(4.0); + self.header(ui, &mut actions); + ui.add_space(4.0); + }); + let content = ctx.content_rect(); + let (w, h) = (content.width(), content.height() - 44.0); + let stacked = w < BOARD_MIN + 24.0 + RIGHT_MIN || h < 600.0; + let low = stacked && h < 720.0; + self.stacked = stacked; + self.low_window = h < 600.0; + egui::Panel::top("prep_controls").show(ui, |ui| { + ui.add_space(4.0); + self.controls(ui, settings, low, &mut actions); + ui.add_space(2.0); + self.summary(ui, stacked); + ui.add_space(4.0); + }); + if self.report.is_none() { + egui::CentralPanel::default().show(ui, |ui| self.building(ui, &mut actions)); + } else if stacked { + if !low { + egui::Panel::top("prep_board_stack").show(ui, |ui| { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.allocate_ui(vec2(240.0, 240.0), |ui| self.board(ui, settings, 240.0)); + ui.vertical(|ui| { + self.board_caption(ui); + self.board_info(ui, &mut actions); + }); + }); + ui.add_space(4.0); + }); + } + egui::CentralPanel::default() + .show(ui, |ui| self.right_column(ui, settings, &mut actions)); + if low && self.board_popup { + self.board_overlay(&ctx, settings, &mut actions); + } + } else { + let board_side = (h - 120.0) + .min(420.0) + .min(w - BOARD_MIN - 24.0 - RIGHT_MIN + BOARD_MIN) + .max(BOARD_MIN) + .floor(); + egui::Panel::left("prep_board") + .exact_size(board_side + 24.0) + .resizable(false) + .show(ui, |ui| { + ui.add_space(6.0); + ui.vertical(|ui| { + self.board_caption(ui); + self.board(ui, settings, board_side); + self.board_info(ui, &mut actions); + }); + }); + egui::CentralPanel::default() + .show(ui, |ui| self.right_column(ui, settings, &mut actions)); + } + self.engine_dialog(&ctx, settings, &mut actions); + if let Some(p) = self.want_period.take() { + self.set_period(p, settings, &ctx); + actions.push(PrepAction::SettingsChanged); + } + if !typing && !overlay { + self.keyboard(&ctx, settings, &mut actions); + } + if settings.prep.sorts != self.sorts { + settings.prep.sorts = self.sorts.clone(); + actions.push(PrepAction::SettingsChanged); + } + actions + } + + fn header(&mut self, ui: &mut Ui, actions: &mut Vec) { + let gap = ui.spacing().item_spacing.x; + let button_w = |ui: &Ui, text: &str| { + text_width(ui, text, egui::TextStyle::Button) + + 2.0 * ui.spacing().button_padding.x + + gap + }; + let row = ui.available_width(); + let compact = row < 700.0; + let left = button_w(ui, if compact { "⬅" } else { tr("⬅ Library") }) + 2.0 * gap; + let right = button_w(ui, if compact { "âš™" } else { tr("âš™ Settings") }); + let title_room = (row - left - right).max(80.0); + ui.horizontal(|ui| { + if ui + .button(if compact { "⬅" } else { tr("⬅ Library") }) + .on_hover_text(tr("Back to the game list (Esc, Ctrl+W)")) + .clicked() + { + actions.push(PrepAction::Back); + } + ui.separator(); + let name = self.names.first().cloned().unwrap_or_default(); + let more = self.names.len().saturating_sub(1); + let mut parts = Vec::new(); + if let Some(r) = &self.report { + parts.push(crate::i18n::games(self.shown_games())); + let p = period(&r.games); + if !p.is_empty() { + parts.push(p); + } + } + parts.push(self.db_name.clone()); + let title = if compact { + name.clone() + } else { + trf("Preparing against {name}", &[("name", &name)]) + }; + ui.allocate_ui(vec2(title_room, 24.0), |ui| { + ui.horizontal(|ui| { + ui.set_max_width(title_room); + ui.add(egui::Label::new(RichText::new(title).strong().size(15.0)).truncate()); + if more > 0 { + ui.label(RichText::new(trf("+{n} spelling", &[("n", &more)])).weak()) + .on_hover_text(self.names.join("\n")); + } + let skipped = self.report.as_ref().map_or(0, |r| r.skipped); + let r = ui.add( + egui::Label::new(RichText::new(format!("· {}", parts.join(" · "))).weak()) + .truncate(), + ); + if skipped > 0 { + r.on_hover_text(trf( + "not counted: from a set position — {n}", + &[("n", &skipped)], + )); + } + }); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .button(if compact { "âš™" } else { tr("âš™ Settings") }) + .on_hover_text(tr("Settings (Ctrl+,)")) + .clicked() + { + actions.push(PrepAction::OpenSettings); + } + }); + }); + } + + /// The colour switch, the depth and the engine button or its progress. + fn controls( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + low: bool, + actions: &mut Vec, + ) { + let width = ui.available_width(); + let gap = ui.spacing().item_spacing.x; + let pad = 2.0 * ui.spacing().button_padding.x; + let state = self.engine_state(); + // The engine part on the right is measured first: the rest gets what it leaves. + let engine = self.engine_texts(state, width); + let engine_w = match &engine { + EngineTexts::Running => { + (width * 0.35).clamp(90.0, 360.0) + + text_width(ui, tr("Stop"), egui::TextStyle::Button) + + pad + + 2.0 * gap + } + EngineTexts::Button { label, note } | EngineTexts::Done { label, note } => { + text_width(ui, label, egui::TextStyle::Button) + + pad + + note + .as_deref() + .map_or(0.0, |n| text_width(ui, n, egui::TextStyle::Body) + gap) + + gap + } + } + 26.0 + + gap; + ui.horizontal(|ui| { + for choice in [ColorChoice::White, ColorChoice::Black, ColorChoice::Both] { + if ui + .selectable_label(self.color == choice, choice.label()) + .clicked() + { + self.set_color(choice); + } + } + ui.separator(); + let moves = self.plies.div_ceil(2); + let board_w = if low { + text_width(ui, "â™™", egui::TextStyle::Button) + pad + 2.0 * gap + } else { + 0.0 + }; + // The period's and the depth's captions by the room left, shortened in one + // order at every width: the depth first, then the period, then both. + let depths = [ + trf("Opening: {n} moves", &[("n", &moves)]), + trf("{n} moves", &[("n", &moves)]), + trf("{n} m.", &[("n", &moves)]), + ]; + let periods = self.period_captions(); + let combo = |t: &str| text_width(ui, t, egui::TextStyle::Button) + pad + 20.0 + gap; + let room = + ui.available_width() - engine_w - board_w - ui.spacing().item_spacing.x * 2.0; + let (p, d) = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)] + .into_iter() + .find(|&(p, d)| combo(&periods[p]) + combo(&depths[d]) <= room) + .unwrap_or((2, 2)); + let [p0, p1, p2] = periods; + let period_label_now = [p0, p1, p2].into_iter().nth(p).unwrap_or_default(); + self.period_picker(ui, settings, period_label_now, actions); + ui.separator(); + let depth_label = depths[d].clone(); + let mut new_plies = None; + let depth_w = text_width(ui, &depth_label, egui::TextStyle::Button) + 8.0; + egui::ComboBox::from_id_salt("prep_plies") + .width(depth_w) + .selected_text(depth_label) + .show_ui(ui, |ui| { + for m in [6usize, 10, 15] { + if ui + .selectable_label( + self.plies == m * 2, + trf("Opening: {n} moves", &[("n", &m)]), + ) + .clicked() + { + new_plies = Some(m * 2); + } + } + }) + .response + .on_hover_text(tr("How deep the tree and the engine look")); + if let Some(p) = new_plies { + self.set_plies(p, settings, ui.ctx()); + actions.push(PrepAction::SettingsChanged); + } + if low { + ui.separator(); + if ui + .selectable_label(self.board_popup, "â™™") + .on_hover_text(tr("The board of the chosen position")) + .clicked() + { + self.board_popup = !self.board_popup; + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + self.engine_control(ui, settings, engine, width, actions); + }); + }); + } + + /// The period shown: a period by months over games without dates takes all. + fn period_shown(&self) -> Period { + let dated = self + .report + .as_ref() + .is_some_and(|r| r.pool.iter().any(|g| g.date != 0)); + match self.period { + Period::Months(_) if self.report.is_some() && !dated => Period::All, + p => p, + } + } + + /// How many games `p` takes of the colour(s) shown: «80», «100 + 100». + fn period_number(&self, p: Period) -> String { + let Some(r) = &self.report else { + return "…".to_owned(); + }; + let side = self.color.side(); + match (p, side) { + // The last N of each colour, not N in all. + (Period::Last(_), Side::Any) => format!( + "{} + {}", + grouped(r.count(p, Side::White).games), + grouped(r.count(p, Side::Black).games) + ), + _ => grouped(r.count(p, side).games), + } + } + + /// The period's captions, longest first: «Last 2 years · 80», «2 yrs · 80», «80». + fn period_captions(&self) -> [String; 3] { + let p = self.period_shown(); + let n = self.period_number(p); + [ + format!("{} · {n}", period_label(p)), + format!("{} · {n}", period_short(p)), + n, + ] + } + + /// «Last 2 years · 80 ▾»: which of the player's games, with how many each takes of + /// the colour(s) shown; `selected` is the caption the row has room for. + fn period_picker( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + selected: String, + actions: &mut Vec, + ) { + let side = self.color.side(); + let report = self.report.as_ref(); + let dated = report.is_some_and(|r| r.pool.iter().any(|g| g.date != 0)); + let shown = self.period_shown(); + let number = |p: Period| self.period_number(p); + let mut picked = None; + // As wide as its text: the room is the row's. + let width = text_width(ui, &selected, egui::TextStyle::Button) + 8.0; + let r = egui::ComboBox::from_id_salt("prep_period") + .width(width) + .selected_text(selected) + .show_ui(ui, |ui| { + for p in PERIODS { + // Without dates: by number only. + if matches!(p, Period::Months(_)) && !dated { + continue; + } + let text = format!("{} · {}", period_label(p), number(p)); + if ui.selectable_label(shown == p, text).clicked() { + picked = Some(p); + } + } + let note = |ui: &mut Ui, text: String| { + ui.label(RichText::new(text).weak().small()); + }; + if !dated { + note(ui, tr("The games have no dates: by number only").to_owned()); + } else if let Some(r) = report { + let newest = prep::period_newest(&r.pool); + note( + ui, + trf( + "Counted back from his newest game — {date}", + &[("date", &shown_date(newest))], + ), + ); + let out = r.count(Period::Months(12), side).undated_out; + if out > 0 { + note( + ui, + trf( + "Without a date: {n} — taken only with all games", + &[("n", &grouped(out))], + ), + ); + } + } + }) + .response; + r.on_hover_text(tr( + "Which of his games: by date — counted back from his newest game; by number — the newest of each colour", + )); + if let Some(p) = picked { + self.set_period(p, settings, ui.ctx()); + actions.push(PrepAction::SettingsChanged); + } + } + + /// What the engine part of the controls says, by the room there is. + fn engine_texts(&self, state: EngineState, width: f32) -> EngineTexts { + let (missing, secs) = self.estimate(); + let time = review::format_duration(secs); + match state { + EngineState::Running => EngineTexts::Running, + EngineState::NotRun => EngineTexts::Button { + label: if width < 700.0 { + format!("â–¶ ≈ {time}") + } else if width < 900.0 { + trf("â–¶ Errors ≈ {time}", &[("time", &time)]) + } else { + trf("â–¶ Find opening errors ≈ {time}", &[("time", &time)]) + }, + note: None, + }, + EngineState::Partial { done, total } => EngineTexts::Button { + label: if width < 700.0 { + format!("â–¶ ≈ {time}") + } else { + trf("Continue ≈ {time}", &[("time", &time)]) + }, + note: (width >= 900.0).then(|| { + trf( + "Checked {done} of {total} positions", + &[("done", &grouped(done)), ("total", &grouped(total))], + ) + }), + }, + EngineState::Complete { .. } => { + let _ = missing; + EngineTexts::Done { + label: tr("Errors found").to_owned(), + note: None, + } + } + } + } + + /// The engine button, the progress while it runs, the state after; «▾» (the + /// options) at the right end. + fn engine_control( + &mut self, + ui: &mut Ui, + _settings: &Settings, + texts: EngineTexts, + width: f32, + actions: &mut Vec, + ) { + if ui.button("â–¾").on_hover_text(tr("Options…")).clicked() { + self.dialog_open = true; + } + if let Some(job) = &self.job { + let (done, total) = (job.done, job.total); + if ui.button(tr("Stop")).on_hover_text("Shift+A").clicked() { + self.stop_engine_by_user(actions); + return; + } + let secs = self.secs_for(total.saturating_sub(done), job.processes); + let text = if width < 760.0 { + format!("{}/{}", grouped(done), grouped(total)) + } else { + trf( + "Finding errors: {done} of {total} positions · ≈ {time}", + &[ + ("done", &grouped(done)), + ("total", &grouped(total)), + ("time", &review::format_duration(secs)), + ], + ) + }; + ui.add( + egui::ProgressBar::new(done as f32 / total.max(1) as f32) + .desired_width((width * 0.35).clamp(90.0, 360.0)) + .text(text), + ); + return; + } + let Some(report) = &self.report else { return }; + let hint = self.engine_status().unwrap_or_else(|| { + tr("The engine finds the opening errors in his games (Shift+A)").to_owned() + }); + let _ = report; + match texts { + EngineTexts::Done { label, .. } => { + ui.label(RichText::new(label).weak()).on_hover_text(hint); + } + EngineTexts::Button { label, note } => { + // Nothing to search in no games. + let some = self.shown_games() > 0; + if ui + .add_enabled_ui(some, |ui| crate::widgets::primary(ui, &label)) + .inner + .on_hover_text(hint) + .clicked() + { + self.engine_asked(ui.ctx(), actions); + } + if let Some(n) = note { + ui.label(RichText::new(n).weak()); + } + } + EngineTexts::Running => {} + } + if let Some(e) = &self.error { + ui.label(RichText::new("âš ").color(ui.visuals().error_fg_color)) + .on_hover_text(e); + } + } + + /// «Errors found · Stockfish 19 · 2 947 positions», once evaluated. + fn engine_status(&self) -> Option { + let report = self.report.as_ref()?; + if !report.evaluated() { + return None; + } + let n = grouped(report.distinct_positions_for(self.color.side())); + Some( + match report.engine.as_ref().filter(|e| !e.name.is_empty()) { + Some(e) => trf( + "Errors found · {engine} · {n} positions", + &[("engine", &e.name), ("n", &n)], + ), + None => trf("Errors found · {n} positions", &[("n", &n)]), + }, + ) + } + + /// The summary: a row per colour in columns — colour, games, score, opponents, + /// the last game, then separate error counts and percentages. Secondary columns + /// give way from the right (the last game, then the opponents) instead of wrapping. + fn summary(&self, ui: &mut Ui, stacked: bool) { + let Some(report) = &self.report else { return }; + let colours = if stacked { + self.color.colours() + } else { + vec![true, false] + }; + let evaluated = report.evaluated() && !stacked; + // Texts per colour: [colour, games, score, opponents, last]. + let mut rows: Vec<(bool, [String; 5], String, ErrorCounts, usize)> = Vec::new(); + for &white in &colours { + let cr = report.color(white); + let root = &cr.tree.nodes[0]; + let tally = &root.tally; + let title = if white { + tr("As White") + } else { + tr("As Black") + } + .to_owned(); + let score = if tally.games > 0 { + format!("{} ({})", score_text(tally), tally_hint(tally)) + } else { + String::new() + }; + let compact_score = if tally.games > 0 { + score_text(tally) + } else { + String::new() + }; + let opponents = root + .average_elo() + .map(|elo| trf("opponents ≈ {elo}", &[("elo", &elo)])) + .unwrap_or_default(); + let last = crate::library::display_date(&root.last_date); + let last = if last.is_empty() { + String::new() + } else { + trf("last {date}", &[("date", &last)]) + }; + let with_errors: HashSet = cr + .errors + .iter() + .filter(|e| self.visible(e.judgement)) + .map(|e| e.game) + .collect(); + let p = 100 * with_errors.len() / cr.games.len().max(1); + rows.push(( + white, + [title, tally.games.to_string(), score, opponents, last], + compact_score, + self.shown_counts(&cr.counts), + p, + )); + } + // The colour, games and score percentage stay; secondary columns give way. + let gap = 14.0; + let col_w = |k: usize, compact_score: bool| -> f32 { + rows.iter() + .map(|r| { + let text = if k == 2 && compact_score { + &r.2 + } else { + &r.1[k] + }; + text_width(ui, text, egui::TextStyle::Body) + }) + .fold(0.0, f32::max) + }; + let no_errors_w = text_width(ui, tr("no errors"), egui::TextStyle::Body); + let counts_w = if evaluated { + rows.iter() + .map(|(_, _, _, counts, _)| { + if counts.total() > 0 { + errors_text_width(ui, counts) + } else { + no_errors_w + } + }) + .fold(0.0, f32::max) + } else { + 0.0 + }; + let percent_w = if evaluated { + rows.iter() + .filter(|(_, _, _, counts, _)| counts.total() > 0) + .map(|(_, _, _, _, p)| { + text_width( + ui, + &trf("in {p} % of games", &[("p", p)]), + egui::TextStyle::Body, + ) + }) + .fold(0.0, f32::max) + } else { + 0.0 + }; + let has_percent = percent_w > 0.0; + let width = ui.available_width(); + let mut shown = [true; 5]; + if stacked { + shown[3] = false; + shown[4] = false; + } + let used = |shown: &[bool; 5], compact_score: bool| -> f32 { + let base_cells = shown.iter().filter(|&&show| show).count(); + let cells = base_cells + usize::from(evaluated) + usize::from(has_percent); + let base_w = (0..5) + .filter(|&k| shown[k]) + .map(|k| col_w(k, compact_score)) + .sum::(); + base_w + counts_w + percent_w + cells.saturating_sub(1) as f32 * gap + }; + for k in [4, 3] { + if used(&shown, stacked) <= width { + break; + } + shown[k] = false; + } + let compact_score = stacked || used(&shown, false) > width; + let grid_columns = shown.iter().filter(|&&show| show).count() + + usize::from(evaluated) + + usize::from(has_percent); + egui::Grid::new("prep_summary") + .num_columns(grid_columns) + .spacing(vec2(gap, 2.0)) + .show(ui, |ui| { + for (white, texts, short_score, counts, p) in &rows { + let weak = !self.color.colours().contains(white); + for k in 0..5 { + if !shown[k] { + continue; + } + let text = if k == 2 && compact_score { + short_score + } else { + &texts[k] + }; + let rt = RichText::new(text); + let rt = if k <= 1 { rt.strong() } else { rt }; + if k == 1 { + ui.with_layout( + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + ui.label(if weak { rt.weak() } else { rt }); + }, + ); + } else { + ui.label(if weak { rt.weak() } else { rt }); + } + } + if evaluated { + ui.horizontal(|ui| { + if counts.total() > 0 { + counts_text(ui, counts); + } else { + ui.label(RichText::new(tr("no errors")).weak()); + } + }); + } + if has_percent { + if counts.total() > 0 { + ui.label(RichText::new(trf("in {p} % of games", &[("p", p)])).weak()); + } else { + ui.label(""); + } + } + ui.end_row(); + } + }); + let n: usize = self + .color + .colours() + .iter() + .map(|&w| report.color(w).games.len()) + .sum(); + if let Period::Months(_) = report.period { + let out = report.count(report.period, self.color.side()).undated_out; + if out > 0 { + ui.label( + RichText::new(trf( + "Without a date, not counted: {n} (only with all games)", + &[("n", &grouped(out))], + )) + .weak(), + ); + } + } + if n > 0 && n < 10 { + ui.label( + RichText::new(trf( + "Few games ({n}): percentages and scores are unreliable", + &[("n", &n)], + )) + .color(ui.visuals().warn_fg_color), + ); + } + } + + /// The report is being built: its progress. + fn building(&mut self, ui: &mut Ui, actions: &mut Vec) { + ui.add_space(40.0); + ui.vertical_centered(|ui| { + if let Some(e) = &self.error { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + if ui.button(tr("Try again")).clicked() { + self.error = None; + self.rebuild(ui.ctx()); + } + return; + } + let Some(job) = &self.build else { return }; + let done = job.progress(); + let total = self.build_total.max(done).max(1); + ui.add(egui::Spinner::new().size(18.0)); + let p = 100 * done / total; + ui.label(trf("Collecting games… {p} %", &[("p", &p.min(99))])); + if ui.button(tr("Cancel")).clicked() { + actions.push(PrepAction::Back); + } + }); + } + + // ----- the board ----------------------------------------------------------------- + + /// «Black to move · after 3.Bb5» over the board. + fn board_caption(&self, ui: &mut Ui) { + let text = match &self.shown_pos { + Some(s) => { + let pos = &s.positions[s.ply]; + let side = if pos.turn() == Color::White { + tr("White to move") + } else { + tr("Black to move") + }; + match s + .ply + .checked_sub(1) + .and_then(|p| s.sans.get(p).map(|san| short_label(p, san))) + { + Some(m) => format!("{side} · {}", trf("after {move}", &[("move", &m)])), + None => side.to_owned(), + } + } + None => tr("Start position").to_owned(), + }; + ui.label(RichText::new(text).weak()); + } + + fn board(&mut self, ui: &mut Ui, settings: &Settings, side: f32) { + let start = Chess::default(); + let (pos, last_move, arrows): (&Chess, Option<(Square, Square)>, Vec) = + match &self.shown_pos { + Some(s) => { + let pos = &s.positions[s.ply]; + let last = s + .ply + .checked_sub(1) + .and_then(|p| s.ucis.get(p)) + .and_then(|u| u.parse::().ok()) + .and_then(|u| u.to_move(&s.positions[s.ply - 1]).ok()) + .and_then(|m| Some((m.from()?, crate::board::ui_target(&m)))); + let mut arrows = if s.ply + 1 == s.positions.len() { + s.arrows.clone() + } else { + Vec::new() + }; + if let Some((from, to)) = self.hover_arrow { + arrows.push(Arrow { + from, + to, + color: PREVIEW_ARROW, + weight: 1.0, + }); + } + (pos, last, arrows) + } + None => { + let mut arrows = Vec::new(); + if let Some((from, to)) = self.hover_arrow { + arrows.push(Arrow { + from, + to, + color: PREVIEW_ARROW, + weight: 1.0, + }); + } + (&start, None, arrows) + } + }; + let view = BoardView { + pos, + orientation: if self.board_white() { + Color::White + } else { + Color::Black + }, + last_move, + arrows: &arrows, + circles: &[], + badge: None, + interactive: false, + temporary_shapes: false, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: settings.animation.seconds(), + premove: None, + auto_queen: settings.auto_queen, + alert: None, + }; + ui.allocate_ui(vec2(side, side), |ui| { + view.show(ui, &mut self.board_state); + }); + } + + /// Under the board: the line (a click takes the board along it), the opening, the + /// note of an error, «Open as a game» and the menu. + fn board_info(&mut self, ui: &mut Ui, actions: &mut Vec) { + ui.add_space(4.0); + let Some(report) = &self.report else { return }; + let Some(s) = &self.shown_pos else { + ui.label( + RichText::new(tr( + "Choose a move in the tree, an opening or an error: its position is shown here", + )) + .weak(), + ); + return; + }; + let mut goto = None; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if s.sans.is_empty() { + ui.label(RichText::new(tr("Start position")).weak()); + } + for (i, san) in s.sans.iter().enumerate() { + // Numbers at White's moves only: «1.e4 c5 2.Nf3 d6». + let label = if i.is_multiple_of(2) { + short_label(i, san) + } else { + crate::san::show(san).into_owned() + }; + let current = i + 1 == s.ply; + let text = if current { + RichText::new(label).strong() + } else { + RichText::new(label) + }; + if ui + .add(egui::Label::new(text).sense(Sense::click())) + .clicked() + { + goto = Some(i + 1); + } + } + }); + if let Some(o) = s.opening.and_then(|o| report.openings.get(o)) { + ui.label( + RichText::new(format!("{} · {}", o.name, o.eco)) + .weak() + .small(), + ); + } + if let Some(note) = &s.note { + ui.label(RichText::new(note).small()); + } + let (sans, ucis, pos, white, ply) = ( + s.sans.clone(), + s.ucis.clone(), + s.positions[s.ply].clone(), + s.white, + s.ply, + ); + ui.horizontal(|ui| { + if ui + .button(tr("Open as a game")) + .on_hover_text(tr("The line as a new game, to add moves and comments")) + .clicked() + { + actions.push(PrepAction::OpenPgn(self.line_pgn(&sans[..ply], white))); + } + ui.menu_button("⋯", |ui| { + if ui.button(tr("Play on from here…")).clicked() { + let moves: Vec = { + let mut p = Chess::default(); + ucis[..ply] + .iter() + .filter_map(|u| { + let m = u.parse::().ok()?.to_move(&p).ok()?; + p.play_unchecked(m); + Some(m) + }) + .collect() + }; + let last = moves + .last() + .and_then(|m| Some((m.from()?, crate::board::ui_target(m)))); + let after = ply.checked_sub(1).map(|p| prep::move_label(p, &sans[p])); + actions.push(PrepAction::PlayFrom(Box::new(crate::play::StartFrom { + start_fen: None, + moves, + position: pos.clone(), + last, + after: after.clone(), + after_shown: after.map(|a| crate::san::show(&a).into_owned()), + game: Some(self.title()), + null_dropped: false, + }))); + ui.close(); + } + if ui + .button(tr("Find this position in a database (Ctrl+Shift+F)")) + .clicked() + { + let mut p = Chess::default(); + let moves: Vec = ucis[..ply] + .iter() + .filter_map(|u| { + let m = u.parse::().ok()?.to_move(&p).ok()?; + p.play_unchecked(m); + Some(m) + }) + .collect(); + actions.push(PrepAction::FindPosition( + self.path.clone(), + Chess::default(), + moves, + !self.board_white(), + )); + ui.close(); + } + if ui.button(tr("Copy FEN")).clicked() { + let fen = + shakmaty::fen::Fen::from_position(&pos, shakmaty::EnPassantMode::Legal) + .to_string(); + actions.push(PrepAction::CopyText(fen, tr("FEN copied"))); + ui.close(); + } + if ui.button(tr("Copy moves (PGN)")).clicked() { + actions.push(PrepAction::CopyText( + self.line_pgn(&sans[..ply], white), + tr("PGN copied"), + )); + ui.close(); + } + }); + }); + if let Some(p) = goto + && let Some(s) = self.shown_pos.as_mut() + { + s.ply = p; + self.board_state.clear(); + } + } + + /// The line as a PGN game: the player on his side, the opponent unnamed. + fn line_pgn(&self, sans: &[String], white: bool) -> String { + let name = self.names.first().cloned().unwrap_or_default(); + let (w, b) = if white { + (name, "?".to_owned()) + } else { + ("?".to_owned(), name) + }; + let mut moves = String::new(); + for (i, san) in sans.iter().enumerate() { + if i.is_multiple_of(2) { + moves.push_str(&format!("{}. ", i / 2 + 1)); + } + moves.push_str(san); + moves.push(' '); + } + format!( + "[Event \"{}\"]\n[White \"{w}\"]\n[Black \"{b}\"]\n[Result \"*\"]\n\n{moves}*\n", + self.title() + ) + } + + /// In a low window: the board over the right bottom of the screen. + fn board_overlay( + &mut self, + ctx: &egui::Context, + settings: &Settings, + actions: &mut Vec, + ) { + let screen = ctx.content_rect(); + let size = vec2(264.0, 300.0); + let rect = egui::Rect::from_min_size(screen.right_bottom() - size, size); + let area = egui::Area::new(egui::Id::new("prep_board_overlay")) + .order(egui::Order::Middle) + .fixed_pos(rect.min) + .show(ctx, |ui| { + let frame = egui::Frame::side_top_panel(ui.style()) + .stroke(ui.visuals().window_stroke) + .shadow(egui::Shadow { + offset: [-6, -6], + blur: 16, + spread: 0, + color: Color32::from_black_alpha(110), + }); + frame.show(ui, |ui| { + ui.set_min_size(size - vec2(16.0, 16.0)); + ui.set_max_size(size - vec2(16.0, 16.0)); + self.board_caption(ui); + self.board(ui, settings, 240.0); + ui.horizontal(|ui| { + if ui.button(tr("Open as a game")).clicked() + && let Some(s) = &self.shown_pos + { + actions.push(PrepAction::OpenPgn( + self.line_pgn(&s.sans[..s.ply], s.white), + )); + } + }); + }); + }); + if area.response.clicked_elsewhere() { + self.board_popup = false; + } + } + + // ----- the right column --------------------------------------------------------- + + /// The tabs over the games list, the border between them draggable. (A nested + /// bottom panel would not do: in a top-down `Ui` egui's available rect ignores + /// the cursor's bottom, so the content above overlaps it.) + fn right_column( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { + let height = ui.available_height(); + let width = ui.available_width(); + // In a low window the tabs keep the most: two rows of games at least, a quarter. + let (rows, share) = if self.low_window { + (2.0, 0.25) + } else { + (4.0, 0.35) + }; + let least = rows * ROW_H + 60.0; + let most = (height - 160.0).max(least); + let games_h = self + .games_height + .unwrap_or(height * share) + .clamp(least, most) + .floor(); + let tabs_h = (height - games_h - 10.0).max(0.0); + ui.allocate_ui_with_layout( + vec2(width, tabs_h), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.set_min_height(tabs_h); + ui.set_max_height(tabs_h); + self.tabs(ui, settings, actions); + }, + ); + // The border: dragged, it gives the games list more or less. + let (rect, resp) = ui.allocate_exact_size(vec2(width, 10.0), Sense::drag()); + if resp.hovered() || resp.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); + } + if resp.dragged() { + self.games_height = Some((games_h - resp.drag_delta().y).clamp(least, most)); + } + let stroke = if resp.hovered() || resp.dragged() { + ui.visuals().widgets.hovered.fg_stroke + } else { + ui.visuals().widgets.noninteractive.bg_stroke + }; + ui.painter().hline(rect.x_range(), rect.center().y, stroke); + ui.allocate_ui_with_layout( + vec2(width, games_h), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.set_min_height(games_h); + ui.set_max_height(games_h); + self.games_list(ui, actions); + }, + ); + } + + fn tabs(&mut self, ui: &mut Ui, settings: &mut Settings, actions: &mut Vec) { + { + ui.horizontal(|ui| { + for (tab, label, key) in [ + (Tab::Repertoire, tr("Repertoire"), "Ctrl+1"), + (Tab::Openings, tr("Openings"), "Ctrl+2"), + (Tab::Errors, tr("Errors"), "Ctrl+3"), + ] { + ui.selectable_value(&mut self.tab, tab, label) + .on_hover_text(key); + } + if self.tab == Tab::Repertoire { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.small_button(tr("Collapse")).clicked() { + self.collapse_selected(); + } + if ui.small_button(tr("Expand all")).clicked() { + self.expand_selected(); + } + let mut n = self.branches_from; + egui::ComboBox::from_id_salt("prep_branches") + .selected_text(trf("Branches from {n} games", &[("n", &n)])) + .show_ui(ui, |ui| { + for k in [2u32, 3, 5] { + ui.selectable_value( + &mut n, + k, + trf("Branches from {n} games", &[("n", &k)]), + ); + } + }) + .response + .on_hover_text(tr("Moves with fewer games fold into «other moves»")); + if n != self.branches_from { + self.branches_from = n; + settings.prep.branches_from = n; + actions.push(PrepAction::SettingsChanged); + } + }); + } + }); + ui.add_space(2.0); + match self.tab { + Tab::Repertoire => self.tree_table(ui), + Tab::Openings => self.openings_table(ui), + Tab::Errors => self.errors_tab(ui, settings, actions), + } + } + } + + fn expand_selected(&mut self) { + let Some(report) = &self.report else { return }; + let roots: Vec<(bool, u32)> = match &self.selection { + Selection::Node { white, node } => vec![(*white, *node)], + _ => self.color.colours().iter().map(|&w| (w, 0)).collect(), + }; + for (white, root) in roots { + let tree = &report.color(white).tree; + let mut stack = vec![root]; + while let Some(n) = stack.pop() { + self.expanded.insert((white, n)); + self.others_open.insert((white, n)); + stack.extend(tree.nodes[n as usize].children.iter().copied()); + } + } + } + + fn collapse_selected(&mut self) { + let Some(report) = &self.report else { return }; + match &self.selection { + Selection::Node { white, node } => { + let tree = &report.color(*white).tree; + let mut stack = vec![*node]; + while let Some(n) = stack.pop() { + self.expanded.remove(&(*white, n)); + self.others_open.remove(&(*white, n)); + stack.extend(tree.nodes[n as usize].children.iter().copied()); + } + } + _ => { + self.expanded.retain(|(_, n)| *n == 0); + self.others_open.clear(); + } + } + } + + /// The rows of the tree as laid out for the colour switch and the expansion. + fn tree_rows(&self) -> Vec { + let Some(report) = &self.report else { + return Vec::new(); + }; + let mut rows = Vec::new(); + for white in self.color.colours() { + let tree = &report.color(white).tree; + if tree.nodes.is_empty() { + continue; + } + // (node, depth, after the main children: the others) + let mut stack: Vec = vec![TreeRow::Node { + white, + node: 0, + depth: 0, + }]; + while let Some(row) = stack.pop() { + rows.push(row); + let (node, depth, listed) = match row { + TreeRow::Node { node, depth, .. } => { + if !self.expanded.contains(&(white, node)) { + continue; + } + (node, depth, false) + } + TreeRow::Others { parent, depth, .. } => { + if !self.others_open.contains(&(white, parent)) { + continue; + } + // The folded moves go under the «other moves» row. + (parent, depth, true) + } + }; + let n = &tree.nodes[node as usize]; + let mut children = n.children.clone(); + let sort = self.sorts.tree; + let val = |c: u32| -> SortVal { + let m = &tree.nodes[c as usize]; + match sort.key { + TreeSort::Games => num(tree.position_tally(m.key).games), + TreeSort::Share => num(m.tally.games), + TreeSort::Score => score_val(&tree.position_tally(m.key)), + TreeSort::Last => num(chess_import::pgn_catalog::date_number( + tree.position_last_date(m.key), + )), + } + }; + // Ties: most played first, as the tree has them. + children.sort_by(|&a, &b| sort.apply(cmp_val(&val(a), &val(b)))); + let (main, rest): (Vec, Vec) = children + .into_iter() + .partition(|&c| tree.nodes[c as usize].tally.games >= self.branches_from); + // Pushed in reverse: the stack pops the first child first. + if listed { + for &c in rest.iter().rev() { + stack.push(TreeRow::Node { + white, + node: c, + depth: depth + 1, + }); + } + } else { + if !rest.is_empty() { + stack.push(TreeRow::Others { + white, + parent: node, + depth: depth + 1, + count: rest.len(), + }); + } + for &c in main.iter().rev() { + stack.push(TreeRow::Node { + white, + node: c, + depth: depth + 1, + }); + } + } + } + } + rows + } + + fn tree_table(&mut self, ui: &mut Ui) { + let rows = self.tree_rows(); + if rows.len() <= 1 { + self.no_games_note(ui); + } + let Some(report) = self.report.as_ref() else { + return; + }; + let width = ui.available_width(); + let gap = ui.spacing().item_spacing.x; + let mut used = 180.0 + 76.0 + 48.0 + 50.0 + 4.0 * gap; + let mut fits = |w: f32, wanted: bool| { + let ok = wanted && used + w + gap <= width; + if ok { + used += w + gap; + } + ok + }; + let show_opening = fits(160.0, true); + let show_bar = fits(64.0, true); + let show_last = fits(84.0, true); + ui.style_mut().interaction.selectable_labels = false; + let mut table = TableBuilder::new(ui) + .id_salt("prep_tree") + .striped(true) + .sense(Sense::click()) + .auto_shrink([false, false]) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::remainder().at_least(180.0).clip(true)); + if show_opening { + table = table.column(Column::remainder().at_least(160.0).clip(true)); + } + table = table + .column(Column::exact(76.0)) + .column(Column::exact(48.0)); + table = table.column(Column::exact(if show_bar { 110.0 } else { 50.0 })); + if show_last { + table = table.column(Column::exact(84.0)); + } + let selected_row = rows.iter().position(|r| match (r, &self.selection) { + ( + TreeRow::Node { white, node, .. }, + Selection::Node { + white: sw, + node: sn, + }, + ) => white == sw && node == sn, + _ => false, + }); + if self.scroll_to_selected + && let Some(i) = selected_row + { + table = table.scroll_to_row(i, None); + } + self.scroll_to_selected = false; + let mut clicked: Option = None; + let mut toggled: Option = None; + let mut hovered: Option<(bool, u32)> = None; + let mut tree_click = None; + table + .header(ROW_H, |mut h| { + head_col(&mut h, tr("Move"), tr("His moves plain, the opponents' weak; ⇄ — the position is reached by another move order too")); + if show_opening { + head_col(&mut h, tr("Opening"), ""); + } + let sort = self.sorts.tree; + sort_col(&mut h, tr("Games"), "", TreeSort::Games, sort, &mut tree_click); + sort_col(&mut h, "%", tr("Share of the games of the move above"), TreeSort::Share, sort, &mut tree_click); + sort_col(&mut h, tr("Score"), tr("The opponent's points in these games"), TreeSort::Score, sort, &mut tree_click); + if show_last { + sort_col(&mut h, tr("Last"), "", TreeSort::Last, sort, &mut tree_click); + } + }) + .body(|body| { + body.rows(ROW_H, rows.len(), |mut row| { + let r = rows[row.index()]; + row.set_selected(Some(row.index()) == selected_row); + match r { + TreeRow::Others { white, parent, depth, count } => { + let open = self.others_open.contains(&(white, parent)); + row.col(|ui| { + ui.add_space(depth as f32 * 14.0); + let glyph = if open { "â–¾" } else { "â–¸" }; + if ui.add(egui::Label::new(RichText::new(glyph).weak()).sense(Sense::click())).clicked() { + toggled = Some(r); + } + // Short when the column is narrow at this depth. + let full = trf("other moves ({n})", &[("n", &count)]); + let text = if text_width(ui, &full, egui::TextStyle::Body) > ui.available_width() { + trf("others ({n})", &[("n", &count)]) + } else { + full + }; + ui.label(RichText::new(text).weak()); + }); + let rest = 2 + usize::from(show_opening) + 1 + usize::from(show_last); + for _ in 0..rest { + row.col(|_| {}); + } + } + TreeRow::Node { white, node, depth } => { + let cr = report.color(white); + let n = &cr.tree.nodes[node as usize]; + let parent = n.parent.map(|p| &cr.tree.nodes[p as usize]); + let has_children = !n.children.is_empty(); + let open = self.expanded.contains(&(white, node)); + // The statistics are the position's, whatever the move order. + let tally = cr.tree.position_tally(n.key); + let few = tally.games < FEW_GAMES; + row.col(|ui| { + ui.add_space(depth as f32 * 14.0); + let glyph = if !has_children { " " } else if open { "â–¾" } else { "â–¸" }; + let g = ui.add(egui::Label::new(RichText::new(glyph).weak()).sense(Sense::click())); + if g.clicked() && has_children { + toggled = Some(r); + } + if n.parent.is_none() { + let title = if white { tr("As White") } else { tr("As Black") }; + ui.label(RichText::new(format!("{title} · {}", n.tally.games)).strong()); + return; + } + let ply = usize::from(n.ply) - 1; + let players = ply.is_multiple_of(2) == white; + let label = short_label(ply, &n.san); + let text = if players { RichText::new(label) } else { RichText::new(label).weak() }; + let l = ui.add(egui::Label::new(text).truncate()); + if !show_opening + && let Some(o) = n.opening.filter(|_| n.named).and_then(|o| report.openings.get(o)) + { + l.on_hover_text(format!("{} · {}", o.name, o.eco)); + } + if n.transposition { + let others: Vec = cr + .tree + .nodes + .iter() + .enumerate() + .filter(|(i, m)| m.key == n.key && *i != node as usize) + .map(|(i, _)| line_text(&cr.tree.path(i).iter().map(|s| (*s).to_owned()).collect::>())) + .collect(); + ui.label(RichText::new("⇄").weak()).on_hover_text(trf( + "Reached by another move order too: {orders}", + &[("orders", &others.join("; "))], + )); + } + if let Some(p) = parent + && let Some(m) = self.mark_of(white, p.key, &n.uci) + && self.visible(m.judgement) + { + let best = crate::san::show(&m.best_san).into_owned(); + pill(ui, m.judgement).on_hover_text(trf( + "{judgement}: better {best} ({before} → {after}) · in {n} games", + &[ + ("judgement", &review::judgement_name(m.judgement)), + ("best", &best), + ("before", &m.before.format()), + ("after", &m.after.format()), + ("n", &m.games), + ], + )); + if m.games > 1 { + ui.label(RichText::new(format!("×{}", m.games)).weak().small()); + } + } + }); + if show_opening { + row.col(|ui| { + // The name where it changes (`named`); the ECO keeps + // its place at the right, the name takes the rest. + if n.named && let Some(o) = n.opening.and_then(|o| report.openings.get(o)) { + let eco = RichText::new(&o.eco).weak().small(); + let eco_w = text_width(ui, &o.eco, egui::TextStyle::Small) + ui.spacing().item_spacing.x; + let name_w = (ui.available_width() - eco_w).max(0.0); + ui.allocate_ui(vec2(name_w, ROW_H), |ui| { + ui.add(egui::Label::new(RichText::new(&o.name).weak()).truncate()) + .on_hover_text(format!("{} · {}", o.name, o.eco)); + }); + ui.label(eco); + } + }); + } + row.col(|ui| { + ui.label(tally.games.to_string()); + }); + row.col(|ui| { + // The move's share where the games were (this order). + if let Some(p) = parent { + let pct = 100 * n.tally.games / p.tally.games.max(1); + let t = RichText::new(format!("{pct}")); + let l = ui.label(if few { t.weak() } else { t }); + if few { + l.on_hover_text(tr("Few games: percentages are unreliable")); + } + } + }); + row.col(|ui| { + let t = RichText::new(score_text(&tally)); + let l = ui.label(if few { t.weak() } else { t }); + l.on_hover_text(tally_hint(&tally)); + if show_bar { + score_bar(ui, &tally, white, few); + } + }); + if show_last { + row.col(|ui| { + let d = crate::library::display_date(cr.tree.position_last_date(n.key)); + ui.label(RichText::new(if d.is_empty() { "—".to_owned() } else { d }).weak()); + }); + } + let resp = row.response(); + if resp.hovered() { + hovered = Some((white, node)); + } + if resp.double_clicked() && has_children { + toggled = Some(r); + } else if resp.clicked() { + clicked = Some(r); + } + } + } + }); + }); + if let Some(k) = tree_click { + self.sorts.tree.click(k, false); + } + // A child of the chosen node under the pointer: its move as an arrow. + if let ( + Some((white, node)), + Selection::Node { + white: sw, + node: sn, + }, + ) = (hovered, &self.selection) + && white == *sw + { + let cr = report.color(white); + let n = &cr.tree.nodes[node as usize]; + if n.parent == Some(*sn) + && let Some(s) = &self.shown_pos + && s.ply + 1 == s.positions.len() + && let Some(m) = n + .uci + .parse::() + .ok() + .and_then(|u| u.to_move(&s.positions[s.ply]).ok()) + { + self.hover_arrow = m.from().map(|f| (f, crate::board::ui_target(&m))); + } + } + if let Some(t) = toggled { + match t { + TreeRow::Node { white, node, .. } => { + if !self.expanded.remove(&(white, node)) { + self.expanded.insert((white, node)); + } + } + TreeRow::Others { white, parent, .. } => { + if !self.others_open.remove(&(white, parent)) { + self.others_open.insert((white, parent)); + } + } + } + } else if let Some(TreeRow::Node { white, node, .. }) = clicked { + self.focus_games = false; + self.select(Selection::Node { white, node }); + } else if let Some(TreeRow::Others { white, parent, .. }) = clicked + && !self.others_open.remove(&(white, parent)) + { + self.others_open.insert((white, parent)); + } + } + + /// «No games as Black. As White — 138 · Show White» when the colour has none. + fn no_games_note(&mut self, ui: &mut Ui) { + let Some(report) = &self.report else { return }; + // No game in the period at all: the way back to all of them. + let side = self.color.side(); + if report.period != Period::All && report.count(report.period, side).games == 0 { + let all = report.count(Period::All, side).games; + ui.add_space(12.0); + ui.label(match self.color { + ColorChoice::White => tr("No games as White in this period"), + ColorChoice::Black => tr("No games as Black in this period"), + ColorChoice::Both => tr("No games in this period"), + }); + if all > 0 + && ui + .button(format!("{} · {}", period_label(Period::All), grouped(all))) + .clicked() + { + self.want_period = Some(Period::All); + } + return; + } + let (shown, other) = match self.color { + ColorChoice::White => (true, false), + ColorChoice::Black => (false, true), + ColorChoice::Both => return, + }; + if !report.color(shown).games.is_empty() { + return; + } + let other_n = report.color(other).games.len(); + let (colour, other_name) = if shown { + (tr("White"), tr("Black")) + } else { + (tr("Black"), tr("White")) + }; + ui.add_space(12.0); + ui.horizontal_wrapped(|ui| { + ui.label(trf( + "No games as {colour}. As {other} — {n}", + &[("colour", &colour), ("other", &other_name), ("n", &other_n)], + )); + if other_n > 0 + && ui + .link(trf("Show {other}", &[("other", &other_name)])) + .clicked() + { + self.set_color(ColorChoice::from_side(if other { + Side::White + } else { + Side::Black + })); + } + }); + } + + // ----- the openings -------------------------------------------------------------- + + /// The value of a family (`v` None) or a variation for the openings' order. + fn opening_val(&self, white: bool, f: usize, v: Option, key: OpeningSort) -> SortVal { + let Some(report) = &self.report else { + return num(0); + }; + let cr = report.color(white); + let fam = &cr.families[f]; + let vars: Vec<&prep::Variation> = match v { + Some(v) => vec![&fam.variations[v]], + None => fam.variations.iter().collect(), + }; + let tally = match v { + Some(v) => fam.variations[v].tally, + None => fam.tally, + }; + let opening = |var: &prep::Variation| var.opening.and_then(|o| report.openings.get(o)); + match key { + OpeningSort::Name => SortVal::Text(match v { + Some(_) => vars[0] + .opening + .map_or_else(String::new, |o| report.openings[o].name.clone()), + None => fam.name.clone(), + }), + OpeningSort::Eco => SortVal::Text( + vars.iter() + .filter_map(|x| opening(x)) + .map(|o| o.eco.clone()) + .min() + .unwrap_or_default(), + ), + OpeningSort::Games | OpeningSort::Share => num(tally.games), + OpeningSort::Score => score_val(&tally), + OpeningSort::Last => num(vars + .iter() + .flat_map(|x| x.games.iter()) + .map(|&g| report.games[g as usize].date_number()) + .max() + .unwrap_or(0)), + OpeningSort::Errors => num(vars + .iter() + .flat_map(|x| x.error_list.iter()) + .map(|&e| cr.errors[e as usize].judgement) + .filter(|j| self.visible(*j)) + .map(judgement_weight) + .sum::()), + } + } + + /// The rows of the openings table: (white, family, variation) — families in the + /// chosen order, the variations of an open one under it in the same order. + fn opening_rows(&self) -> Vec<(bool, usize, Option)> { + let Some(report) = &self.report else { + return Vec::new(); + }; + let sort = self.sorts.openings; + let mut rows = Vec::new(); + for white in self.color.colours() { + let cr = report.color(white); + let mut fams: Vec = (0..cr.families.len()).collect(); + fams.sort_by(|&a, &b| { + sort.apply(cmp_val( + &self.opening_val(white, a, None, sort.key), + &self.opening_val(white, b, None, sort.key), + )) + }); + for f in fams { + rows.push((white, f, None)); + if self.open_families.contains(&(white, f)) { + let mut vars: Vec = (0..cr.families[f].variations.len()).collect(); + vars.sort_by(|&a, &b| { + sort.apply(cmp_val( + &self.opening_val(white, f, Some(a), sort.key), + &self.opening_val(white, f, Some(b), sort.key), + )) + }); + rows.extend(vars.into_iter().map(|v| (white, f, Some(v)))); + } + } + } + rows + } + + fn openings_table(&mut self, ui: &mut Ui) { + let rows = self.opening_rows(); + let Some(report) = self.report.as_ref() else { + return; + }; + if rows.is_empty() { + self.no_games_note(ui); + return; + } + let both = self.color == ColorChoice::Both; + let width = ui.available_width(); + let gap = ui.spacing().item_spacing.x; + let mut used = 180.0 + 76.0 + 48.0 + 50.0 + 4.0 * gap + if both { 24.0 + gap } else { 0.0 }; + let mut fits = |w: f32, wanted: bool| { + let ok = wanted && used + w + gap <= width; + if ok { + used += w + gap; + } + ok + }; + // The errors stay as long as possible; the first moves give way first. + let show_errors = fits(90.0, report.evaluated()); + let show_bar = fits(64.0, true); + let show_eco = fits(64.0, true); + let show_last = fits(84.0, true); + let show_moves = fits(140.0, true); + ui.style_mut().interaction.selectable_labels = false; + let mut table = TableBuilder::new(ui) + .id_salt("prep_openings") + .striped(true) + .sense(Sense::click()) + .auto_shrink([false, false]) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)); + if both { + table = table.column(Column::exact(24.0)); + } + table = table.column(Column::remainder().at_least(180.0).clip(true)); + if show_eco { + table = table.column(Column::exact(64.0)); + } + if show_moves { + table = table.column(Column::remainder().at_least(140.0).clip(true)); + } + table = table + .column(Column::exact(76.0)) + .column(Column::exact(48.0)); + table = table.column(Column::exact(if show_bar { 110.0 } else { 50.0 })); + if show_last { + table = table.column(Column::exact(84.0)); + } + if show_errors { + table = table.column(Column::exact(90.0)); + } + let selected_row = rows.iter().position(|&(w, f, v)| { + self.selection + == Selection::Opening { + white: w, + family: f, + variation: v, + } + }); + if self.scroll_to_selected + && let Some(i) = selected_row + { + table = table.scroll_to_row(i, None); + } + self.scroll_to_selected = false; + let mut clicked = None; + let mut opening_click = None; + let mut toggled = None; + table + .header(ROW_H, |mut h| { + if both { + head_col(&mut h, "", ""); + } + let sort = self.sorts.openings; + let c = &mut opening_click; + sort_col(&mut h, tr("Opening"), "", OpeningSort::Name, sort, c); + if show_eco { + sort_col(&mut h, "ECO", "", OpeningSort::Eco, sort, c); + } + if show_moves { + head_col(&mut h, tr("First moves"), ""); + } + sort_col(&mut h, tr("Games"), "", OpeningSort::Games, sort, c); + sort_col( + &mut h, + "%", + tr("Share of the colour's games; a variation's — of its family's"), + OpeningSort::Share, + sort, + c, + ); + sort_col( + &mut h, + tr("Score"), + tr("The opponent's points in these games"), + OpeningSort::Score, + sort, + c, + ); + if show_last { + sort_col(&mut h, tr("Last"), "", OpeningSort::Last, sort, c); + } + if show_errors { + sort_col(&mut h, tr("Errors"), "", OpeningSort::Errors, sort, c); + } + }) + .body(|body| { + body.rows(ROW_H, rows.len(), |mut row| { + let (white, f, v) = rows[row.index()]; + row.set_selected(Some(row.index()) == selected_row); + let cr = report.color(white); + let fam = &cr.families[f]; + let colour_games = cr.games.len() as u32; + let (tally, errors, games): (&Tally, &ErrorCounts, Vec) = match v { + Some(v) => { + let var = &fam.variations[v]; + (&var.tally, &var.errors, var.games.clone()) + } + None => ( + &fam.tally, + &fam.errors, + fam.variations + .iter() + .flat_map(|v| v.games.iter().copied()) + .collect(), + ), + }; + let few = tally.games < FEW_GAMES; + if both { + row.col(|ui| { + if v.is_none() { + ui.label(RichText::new(if white { "â™™" } else { "♟" }).weak()) + .on_hover_text(if white { + tr("As White") + } else { + tr("As Black") + }); + } + }); + } + row.col(|ui| match v { + None => { + let open = self.open_families.contains(&(white, f)); + let glyph = if open { "â–¾" } else { "â–¸" }; + if ui + .add( + egui::Label::new(RichText::new(glyph).weak()) + .sense(Sense::click()), + ) + .clicked() + { + toggled = Some((white, f)); + } + let name = if fam.name.is_empty() { + tr("no name").to_owned() + } else { + fam.name.clone() + }; + ui.add(egui::Label::new(RichText::new(name).strong()).truncate()); + } + Some(v) => { + ui.add_space(18.0); + let name = fam.variations[v] + .opening + .and_then(|o| report.openings.get(o)) + .map(|o| { + o.variation().map_or_else(|| o.name.clone(), str::to_owned) + }); + match name { + Some(n) => { + ui.add(egui::Label::new(n).truncate()); + } + None => { + ui.label(RichText::new(tr("no deeper name")).weak()); + } + } + } + }); + if show_eco { + row.col(|ui| { + let eco = match v { + Some(v) => fam.variations[v] + .opening + .and_then(|o| report.openings.get(o)) + .map(|o| o.eco.clone()), + None => { + let mut ecos: Vec<&str> = fam + .variations + .iter() + .filter_map(|v| { + v.opening.and_then(|o| report.openings.get(o)) + }) + .map(|o| o.eco.as_str()) + .collect(); + ecos.sort_unstable(); + ecos.dedup(); + match (ecos.first(), ecos.last()) { + (Some(a), Some(b)) if a != b => Some(format!("{a}–{b}")), + (Some(a), _) => Some((*a).to_owned()), + _ => None, + } + } + }; + if let Some(e) = eco { + ui.label(RichText::new(e).weak()); + } + }); + } + if show_moves { + row.col(|ui| { + let line = match v { + Some(v) => fam.variations[v] + .opening + .and_then(|o| report.openings.get(o)) + .map(|o| o.line.clone()), + None => family_line(report, fam), + }; + if let Some(l) = line { + let tokens = table_line(&l); + let full = crate::san::show_line(&tokens.join(" ")); + let shown = fit_line(ui, &tokens, ui.available_width()); + ui.label(RichText::new(shown).weak()).on_hover_text(full); + } + }); + } + row.col(|ui| { + ui.label(tally.games.to_string()); + }); + row.col(|ui| { + let of = match v { + Some(_) => fam.tally.games, + None => colour_games, + }; + let pct = 100 * tally.games / of.max(1); + let t = RichText::new(format!("{pct}")); + ui.label(if few { t.weak() } else { t }); + }); + row.col(|ui| { + let t = RichText::new(score_text(tally)); + ui.label(if few { t.weak() } else { t }) + .on_hover_text(tally_hint(tally)); + if show_bar { + score_bar(ui, tally, white, few); + } + }); + if show_last { + row.col(|ui| { + let last = games + .iter() + .map(|&g| &report.games[g as usize]) + .max_by_key(|g| g.date_number()) + .map(|g| crate::library::display_date(&g.date)) + .unwrap_or_default(); + ui.label( + RichText::new(if last.is_empty() { + "—".to_owned() + } else { + last + }) + .weak(), + ); + }); + } + if show_errors { + row.col(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + counts_text(ui, &self.shown_counts(errors)); + }); + } + let resp = row.response(); + if resp.double_clicked() && v.is_none() { + toggled = Some((white, f)); + } else if resp.clicked() { + clicked = Some((white, f, v)); + } + }); + }); + if let Some(k) = opening_click { + self.sorts + .openings + .click(k, matches!(k, OpeningSort::Name | OpeningSort::Eco)); + } + if let Some(key) = toggled { + if !self.open_families.remove(&key) { + self.open_families.insert(key); + } + } else if let Some((white, family, variation)) = clicked { + self.focus_games = false; + self.select(Selection::Opening { + white, + family, + variation, + }); + } + } + + // ----- the errors ---------------------------------------------------------------- + + fn errors_tab(&mut self, ui: &mut Ui, settings: &mut Settings, actions: &mut Vec) { + let Some(report) = self.report.as_ref() else { + return; + }; + let moves = self.plies.div_ceil(2); + let state = self.engine_state(); + if state == EngineState::NotRun { + // The download is offered only when there is something to evaluate. + if crate::review_engine::engine().is_none() + && !report.targets_for(self.color.side()).is_empty() + { + // No offer by itself on the automatic run: told here, downloaded by hand. + ui.add_space(40.0); + ui.vertical_centered(|ui| { + ui.set_max_width(520.0); + ui.label(tr( + "No engine yet. Stockfish finds the opening errors in his games; add it to start the search.", + )); + ui.add_space(12.0); + if crate::widgets::primary(ui, tr("Download Stockfish")).clicked() { + actions.push(PrepAction::NeedEngine); + } + }); + return; + } + // The invitation (§5). + let (positions, secs) = self.estimate(); + let games: usize = self + .color + .colours() + .iter() + .map(|&w| report.color(w).games.len()) + .sum(); + let colour = match self.color { + ColorChoice::White => tr("as White"), + ColorChoice::Black => tr("as Black"), + ColorChoice::Both => tr("in both colours"), + }; + ui.add_space(40.0); + ui.vertical_centered(|ui| { + ui.set_max_width(520.0); + ui.label(trf( + "The engine has not searched for errors yet. It will check the first {n} moves of {games} games {colour} — {positions} positions, about {time}.", + &[ + ("n", &moves), + ("games", &games), + ("colour", &colour), + ("positions", &grouped(positions)), + ("time", &review::format_duration(secs)), + ], + )); + ui.add_space(12.0); + if crate::widgets::primary(ui, tr("â–¶ Find opening errors")).clicked() { + self.engine_asked(ui.ctx(), actions); + } + }); + return; + } + let mut ask_engine = false; + let mut inaccuracies = settings.prep.inaccuracies; + // The state line: how far the engine got; the switch of the inaccuracies. + ui.horizontal_wrapped(|ui| { + match state { + EngineState::Running => { + let mut stop = false; + if let Some(job) = &self.job { + let secs = self.secs_for(job.total.saturating_sub(job.done), job.processes); + ui.label( + RichText::new(trf( + "Checked {done} of {total} positions", + &[("done", &grouped(job.done)), ("total", &grouped(job.total))], + )) + .weak(), + ); + ui.label( + RichText::new(format!("· ≈ {}", review::format_duration(secs))).weak(), + ); + if ui.button(tr("Stop")).clicked() { + stop = true; + } + } + if stop { + self.stop_engine_by_user(actions); + } + } + EngineState::Partial { done, total } => { + let (_, secs) = self.estimate(); + ui.label( + RichText::new(trf( + "Checked {done} of {total} positions", + &[("done", &grouped(done)), ("total", &grouped(total))], + )) + .weak(), + ) + .on_hover_text(tr("The counts are of the checked positions")); + ui.label(RichText::new("·").weak()); + if ui + .link(trf( + "Continue ≈ {time}", + &[("time", &review::format_duration(secs))], + )) + .clicked() + { + ask_engine = true; + } + } + EngineState::Complete { .. } => { + if let Some(status) = self.engine_status() { + ui.label(RichText::new(status).weak()); + } + } + EngineState::NotRun => {} + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.checkbox(&mut inaccuracies, tr("Inaccuracies")) + .on_hover_text(tr( + "Show the inaccuracies (?!) with the mistakes and blunders", + )); + }); + }); + if inaccuracies != settings.prep.inaccuracies { + settings.prep.inaccuracies = inaccuracies; + self.show_inaccuracies = inaccuracies; + self.rebuild_marks(); + actions.push(PrepAction::SettingsChanged); + } + if ask_engine { + self.engine_asked(ui.ctx(), actions); + return; + } + let Some(report) = self.report.as_ref() else { + return; + }; + // The lines per colour: in the stack only (beside the board the summary has them). + if self.stacked { + for white in self.color.colours() { + let cr = report.color(white); + let with: HashSet = cr + .errors + .iter() + .filter(|e| self.visible(e.judgement)) + .map(|e| e.game) + .collect(); + let p = 100 * with.len() / cr.games.len().max(1); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + ui.label( + RichText::new(if white { + tr("As White") + } else { + tr("As Black") + }) + .strong(), + ); + counts_text(ui, &self.shown_counts(&cr.counts)); + ui.label(RichText::new(trf("in {p} % of games", &[("p", &p)])).weak()); + }); + } + } + let serious: u32 = self + .color + .colours() + .iter() + .map(|&w| { + let c = &report.color(w).counts; + c.mistakes + c.blunders + }) + .sum(); + let inacc: u32 = self + .color + .colours() + .iter() + .map(|&w| report.color(w).counts.inaccuracies) + .sum(); + if matches!(state, EngineState::Complete { .. }) && serious == 0 { + let mut deeper = false; + ui.add_space(8.0); + ui.horizontal_wrapped(|ui| { + ui.label(trf( + "No errors in the first {n} moves ({i} inaccuracies).", + &[("n", &moves), ("i", &inacc)], + )); + if self.plies < 30 && ui.link(trf("Deeper: {n} moves", &[("n", &15)])).clicked() { + deeper = true; + } + }); + if deeper { + // As if chosen in the depth list. + self.set_plies(30, settings, ui.ctx()); + actions.push(PrepAction::SettingsChanged); + return; + } + } + ui.add_space(4.0); + self.errors_table(ui, actions); + } + + /// The repeated errors (the same position and move in several games) and the + /// errors by opening (the variations, the worst first), the inaccuracies left out + /// when they are hidden. + fn repeated_shown(&self) -> Vec<(bool, usize)> { + let Some(report) = &self.report else { + return Vec::new(); + }; + let mut list: Vec<(bool, usize)> = self + .color + .colours() + .into_iter() + .flat_map(|w| { + report + .color(w) + .repeated + .iter() + .enumerate() + .filter(|(_, r)| self.visible(r.judgement)) + .map(move |(i, _)| (w, i)) + }) + .collect(); + let sort = self.sorts.repeated; + let val = |&(w, i): &(bool, usize)| -> SortVal { + let r = &report.color(w).repeated[i]; + match sort.key { + RepeatedSort::Move => num(r.ply), + RepeatedSort::Times => num(r.games.len() as u32), + RepeatedSort::Score => score_val(&r.tally), + RepeatedSort::Opening => SortVal::Text( + r.opening + .map_or_else(String::new, |o| report.openings[o].name.clone()), + ), + } + }; + // Ties: the worst first. + list.sort_by(|a, b| { + let (ra, rb) = ( + &report.color(a.0).repeated[a.1], + &report.color(b.0).repeated[b.1], + ); + sort.apply(cmp_val(&val(a), &val(b))) + .then(judgement_weight(rb.judgement).cmp(&judgement_weight(ra.judgement))) + }); + list + } + + /// The games of a repeated error, the newest first. + fn repeated_games(&self, white: bool, index: usize) -> Vec { + let Some(report) = &self.report else { + return Vec::new(); + }; + let mut games = report.color(white).repeated[index].games.clone(); + games.sort_by_key(|&g| std::cmp::Reverse(report.games[g as usize].date_number())); + games + } + + fn err_rows(&self) -> Vec { + let Some(report) = &self.report else { + return Vec::new(); + }; + let mut rows = vec![ErrRow::RepeatedTitle]; + for (white, index) in self.repeated_shown() { + rows.push(ErrRow::Repeated { white, index }); + if self.open_repeated.contains(&(white, index)) { + for game in self.repeated_games(white, index) { + rows.push(ErrRow::RepeatedGame { white, index, game }); + } + } + } + rows.push(ErrRow::OpeningsTitle); + // (white, family, variation, weight) + let mut vars: Vec<(bool, usize, usize, u32)> = Vec::new(); + for white in self.color.colours() { + let cr = report.color(white); + for (f, fam) in cr.families.iter().enumerate() { + for (v, var) in fam.variations.iter().enumerate() { + let weight: u32 = var + .error_list + .iter() + .map(|&e| cr.errors[e as usize].judgement) + .filter(|j| self.visible(*j)) + .map(judgement_weight) + .sum(); + if weight > 0 { + vars.push((white, f, v, weight)); + } + } + } + } + let sort = self.sorts.variations; + let val = |v: &(bool, usize, usize, u32)| -> u32 { + match sort.key { + VariationSort::Games => { + report.color(v.0).families[v.1].variations[v.2].games.len() as u32 + } + VariationSort::Errors => v.3, + } + }; + vars.sort_by(|a, b| sort.apply(val(a).cmp(&val(b))).then(b.3.cmp(&a.3))); + for (white, family, variation, _) in vars { + rows.push(ErrRow::Variation { + white, + family, + variation, + }); + if self.open_variations.contains(&(white, family, variation)) { + let cr = report.color(white); + for &e in &cr.families[family].variations[variation].error_list { + if self.visible(cr.errors[e as usize].judgement) { + rows.push(ErrRow::Error { + white, + index: e as usize, + }); + } + } + } + } + rows + } + + /// The error of a repeated error in one of its games. + fn error_in(&self, white: bool, index: usize, game: u32) -> Option { + let cr = self.report.as_ref()?.color(white); + let r = cr.repeated.get(index)?; + cr.errors + .iter() + .position(|e| e.game == game && e.key == r.key && e.uci == r.uci) + } + + /// What a row of the errors tab chooses. + fn err_select(&mut self, row: ErrRow) { + self.err_cursor = Some(row); + self.focus_games = false; + let sel = match row { + ErrRow::Repeated { white, index } => Selection::Repeated { white, index }, + ErrRow::RepeatedGame { white, index, game } => { + match self.error_in(white, index, game) { + Some(e) => Selection::Error { white, index: e }, + None => return, + } + } + ErrRow::Variation { + white, + family, + variation, + } => Selection::Opening { + white, + family, + variation: Some(variation), + }, + ErrRow::Error { white, index } => Selection::Error { white, index }, + ErrRow::RepeatedTitle | ErrRow::OpeningsTitle => return, + }; + self.select(sel); + } + + /// The game a row opens, at the move after the error: (record, ply). A repeated + /// error opens its newest game. + fn err_open(&self, row: ErrRow) -> Option<(usize, usize)> { + let report = self.report.as_ref()?; + let (white, e) = match row { + ErrRow::Repeated { white, index } => { + let game = *self.repeated_games(white, index).first()?; + (white, self.error_in(white, index, game)?) + } + ErrRow::RepeatedGame { white, index, game } => { + (white, self.error_in(white, index, game)?) + } + ErrRow::Error { white, index } => (white, index), + _ => return None, + }; + let e = report.color(white).errors.get(e)?; + Some(( + report.games[e.game as usize].index as usize, + e.ply as usize + 1, + )) + } + + fn err_toggle(&mut self, row: ErrRow) { + match row { + ErrRow::Repeated { white, index } => { + if !self.open_repeated.remove(&(white, index)) { + self.open_repeated.insert((white, index)); + } + } + ErrRow::Variation { + white, + family, + variation, + } => { + let k = (white, family, variation); + if !self.open_variations.remove(&k) { + self.open_variations.insert(k); + } + } + _ => {} + } + } + + /// The errors tab as one table: the repeated errors, then by opening; a click + /// chooses, a double click (Enter) opens the game at the error. + fn errors_table(&mut self, ui: &mut Ui, actions: &mut Vec) { + let rows = self.err_rows(); + let Some(report) = self.report.as_ref() else { + return; + }; + let both = self.color == ColorChoice::Both; + let width = ui.available_width(); + let show_last = width > 640.0; + let cursor = self + .err_cursor + .and_then(|c| rows.iter().position(|r| *r == c)); + ui.style_mut().interaction.selectable_labels = false; + let mut table = TableBuilder::new(ui) + .id_salt("prep_errors") + .striped(true) + .sense(Sense::click()) + .auto_shrink([false, false]) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::remainder().at_least(180.0).clip(true)) + .column(Column::exact(110.0)) + .column(Column::exact(80.0)) + .column(Column::exact(70.0)) + .column(Column::exact(120.0).clip(true)); + if show_last { + table = table.column(Column::exact((width * 0.24).clamp(120.0, 260.0)).clip(true)); + } + if self.scroll_to_selected + && let Some(i) = cursor + { + table = table.scroll_to_row(i, None); + } + self.scroll_to_selected = false; + let mut clicked = None; + let mut toggled = None; + let mut opened = None; + let colour_icon = |ui: &mut Ui, white: bool| { + if both { + ui.label(RichText::new(if white { "â™™" } else { "♟" }).weak()) + .on_hover_text(if white { + tr("As White") + } else { + tr("As Black") + }); + } + }; + let repeated_n = rows + .iter() + .filter(|r| matches!(r, ErrRow::Repeated { .. })) + .count(); + let sorts = self.sorts.clone(); + let mut sort_click: Option = None; + let openings_n = rows + .iter() + .filter(|r| matches!(r, ErrRow::Variation { .. })) + .count(); + table.body(|body| { + body.rows(ROW_H, rows.len(), |mut row| { + let r = rows[row.index()]; + row.set_selected(Some(row.index()) == cursor); + let weak = |t: &str| RichText::new(t).weak(); + match r { + ErrRow::RepeatedTitle | ErrRow::OpeningsTitle => { + let repeated = r == ErrRow::RepeatedTitle; + let (title, empty) = if repeated { + ( + tr("Repeated errors — the same position, the same move"), + repeated_n == 0, + ) + } else { + (tr("By opening"), openings_n == 0) + }; + row.col(|ui| { + ui.label(RichText::new(title).strong()); + if empty { + ui.label(weak(tr("none"))); + } + }); + // The captions of the part's columns; those it can be ordered by + // are sort buttons. + let captions: [(&str, Option); 5] = if repeated { + [ + (tr("Played"), Some(SortKeyOf::Repeated(RepeatedSort::Move))), + (tr("Better"), None), + ("×", Some(SortKeyOf::Repeated(RepeatedSort::Times))), + (tr("Score"), Some(SortKeyOf::Repeated(RepeatedSort::Score))), + ( + tr("Opening"), + Some(SortKeyOf::Repeated(RepeatedSort::Opening)), + ), + ] + } else { + [ + (tr("Played"), None), + (tr("Better"), None), + ( + tr("Games"), + Some(SortKeyOf::Variation(VariationSort::Games)), + ), + ( + tr("Errors"), + Some(SortKeyOf::Variation(VariationSort::Errors)), + ), + (tr("Date"), None), + ] + }; + for (k, (c, key)) in captions.iter().enumerate() { + if k < 4 || show_last { + row.col(|ui| match key { + Some(key) => { + let active = match key { + SortKeyOf::Repeated(k) => (sorts.repeated.key == *k) + .then_some(sorts.repeated.ascending), + SortKeyOf::Variation(k) => (sorts.variations.key == *k) + .then_some(sorts.variations.ascending), + }; + if crate::widgets::sort_header(ui, c, active).clicked() { + sort_click = Some(*key); + } + } + None => { + ui.label(weak(c)); + } + }); + } + } + } + ErrRow::Repeated { white, index } => { + let cr = report.color(white); + let rep = &cr.repeated[index]; + let g = &report.games[rep.games[0] as usize]; + let open = self.open_repeated.contains(&(white, index)); + row.col(|ui| { + if ui + .add( + egui::Label::new(weak(if open { "â–¾" } else { "â–¸" })) + .sense(Sense::click()), + ) + .clicked() + { + toggled = Some(r); + } + colour_icon(ui, white); + let before = (rep.ply as usize) + .checked_sub(1) + .map(|p| short_label(p, &g.sans[p])) + .map_or_else( + || tr("start").to_owned(), + |m| trf("after {move}", &[("move", &m)]), + ); + let side = if rep.ply.is_multiple_of(2) { + tr("White to move") + } else { + tr("Black to move") + }; + ui.add(egui::Label::new(format!("{before} · {side}")).truncate()); + }); + row.col(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + ui.label(short_label(rep.ply as usize, &rep.san)); + pill(ui, rep.judgement) + .on_hover_text(review::judgement_name(rep.judgement)); + }); + row.col(|ui| { + ui.label(short_label(rep.ply as usize, &rep.best_san)); + }); + row.col(|ui| { + ui.label(rep.times().to_string()); + }); + row.col(|ui| { + ui.label(weak(&tally_hint(&rep.tally))); + }); + if show_last { + row.col(|ui| { + let name = rep + .opening + .and_then(|o| report.openings.get(o)) + .map(|o| format!("{} · {}", o.name, o.eco)) + .unwrap_or_default(); + ui.add(egui::Label::new(weak(&name)).truncate()) + .on_hover_text(name); + }); + } + } + ErrRow::RepeatedGame { white, index, game } => { + let g = &report.games[game as usize]; + let lr = &self.rows[game as usize]; + let _ = (white, index); + row.col(|ui| { + ui.add_space(28.0); + ui.add( + egui::Label::new(format!("{} — {}", lr.white, lr.black)).truncate(), + ); + }); + row.col(|_| {}); + row.col(|_| {}); + row.col(|_| {}); + row.col(|ui| { + ui.label(result_text(lr.result)); + }); + if show_last { + row.col(|ui| { + ui.label(weak(&crate::library::display_date(&g.date))); + }); + } + } + ErrRow::Variation { + white, + family, + variation, + } => { + let cr = report.color(white); + let var = &cr.families[family].variations[variation]; + let open = self.open_variations.contains(&(white, family, variation)); + let mut counts = ErrorCounts::default(); + for &e in &var.error_list { + counts.add(cr.errors[e as usize].judgement); + } + row.col(|ui| { + if ui + .add( + egui::Label::new(weak(if open { "â–¾" } else { "â–¸" })) + .sense(Sense::click()), + ) + .clicked() + { + toggled = Some(r); + } + colour_icon(ui, white); + let name = var + .opening + .and_then(|o| report.openings.get(o)) + .map_or_else( + || tr("no name").to_owned(), + |o| format!("{} · {}", o.name, o.eco), + ); + ui.add(egui::Label::new(name.as_str()).truncate()) + .on_hover_text(name); + }); + row.col(|_| {}); + row.col(|_| {}); + row.col(|ui| { + ui.label(weak(&var.games.len().to_string())); + }); + row.col(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + counts_text(ui, &self.shown_counts(&counts)); + }); + if show_last { + row.col(|_| {}); + } + } + ErrRow::Error { white, index } => { + let e = &report.color(white).errors[index]; + let g = &report.games[e.game as usize]; + let lr = &self.rows[e.game as usize]; + row.col(|ui| { + ui.add_space(28.0); + ui.add( + egui::Label::new(format!("{} — {}", lr.white, lr.black)).truncate(), + ); + }); + row.col(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + ui.label(short_label(e.ply as usize, &e.san)); + pill(ui, e.judgement).on_hover_text(format!( + "{} · {} → {}", + review::judgement_name(e.judgement), + e.before.format(), + e.after.format() + )); + }); + row.col(|ui| { + ui.label(short_label(e.ply as usize, &e.best_san)); + }); + row.col(|_| {}); + row.col(|ui| { + ui.label(result_text(lr.result)); + }); + if show_last { + row.col(|ui| { + ui.label(weak(&crate::library::display_date(&g.date))); + }); + } + } + } + if !r.is_title() { + let resp = row.response(); + if resp.double_clicked() { + match r { + ErrRow::Repeated { .. } | ErrRow::Variation { .. } => toggled = Some(r), + _ => opened = Some(r), + } + clicked = Some(r); + } else if resp.clicked() { + clicked = Some(r); + } + } + }); + }); + match sort_click { + Some(SortKeyOf::Repeated(k)) => { + // Indices into the lists do not change: the rows only reorder. + self.sorts + .repeated + .click(k, matches!(k, RepeatedSort::Move | RepeatedSort::Opening)) + } + Some(SortKeyOf::Variation(k)) => self.sorts.variations.click(k, false), + None => {} + } + if let Some(r) = toggled { + self.err_toggle(r); + } + if let Some(r) = clicked { + self.err_select(r); + } + if let Some((index, ply)) = opened.and_then(|r| self.err_open(r)) { + actions.push(PrepAction::OpenGame { + path: self.path.clone(), + index, + ply, + }); + } + } + + /// The keyboard in the errors tab: ↑/↓ the rows, →/â†� open and close, Enter the game. + #[allow(clippy::too_many_arguments)] + fn errors_keys( + &mut self, + up: bool, + down: bool, + left: bool, + right: bool, + enter: bool, + space: bool, + home: bool, + end: bool, + actions: &mut Vec, + ) { + let rows: Vec = self + .err_rows() + .into_iter() + .filter(|r| !r.is_title()) + .collect(); + if rows.is_empty() { + return; + } + let at = self + .err_cursor + .and_then(|c| rows.iter().position(|r| *r == c)); + let Some(at) = at else { + if up || down || home || end { + self.err_select(rows[0]); + self.scroll_to_selected = true; + } + return; + }; + let r = rows[at]; + let next = if down { + Some((at + 1).min(rows.len() - 1)) + } else if up { + Some(at.saturating_sub(1)) + } else if home { + Some(0) + } else if end { + Some(rows.len() - 1) + } else { + None + }; + if let Some(i) = next { + self.err_select(rows[i]); + self.scroll_to_selected = true; + return; + } + let open = match r { + ErrRow::Repeated { white, index } => Some(self.open_repeated.contains(&(white, index))), + ErrRow::Variation { + white, + family, + variation, + } => Some(self.open_variations.contains(&(white, family, variation))), + _ => None, + }; + if (right && open == Some(false)) + || (left && open == Some(true)) + || (space && open.is_some()) + { + self.err_toggle(r); + } else if left { + // A game or an error row: to the row it is under. + if let Some(parent) = rows[..at] + .iter() + .rev() + .find(|p| matches!(p, ErrRow::Repeated { .. } | ErrRow::Variation { .. })) + { + self.err_select(*parent); + self.scroll_to_selected = true; + } + } else if enter { + match self.err_open(r) { + Some((index, ply)) => actions.push(PrepAction::OpenGame { + path: self.path.clone(), + index, + ply, + }), + None => { + self.focus_games = true; + self.games_cursor = Some(0); + } + } + } + } + + // ----- the games list ------------------------------------------------------------ + + fn games_list(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(report) = self.report.as_ref() else { + return; + }; + let list = self.games_of(); + let title = match &self.selection { + Selection::None => trf("Games · {n}", &[("n", &list.len())]), + Selection::Node { white, node } => { + let n = &report.color(*white).tree.nodes[*node as usize]; + match n.ply { + 0 => trf("Games · {n}", &[("n", &list.len())]), + p => trf( + "Games · after {move} · {n}", + &[ + ("move", &short_label(usize::from(p) - 1, &n.san)), + ("n", &list.len()), + ], + ), + } + } + Selection::Opening { + white, + family, + variation, + } => { + let fam = &report.color(*white).families[*family]; + let name = match variation { + Some(v) => fam.variations[*v] + .opening + .and_then(|o| report.openings.get(o)) + .map(|o| o.name.clone()) + .unwrap_or_else(|| fam.name.clone()), + None => fam.name.clone(), + }; + trf( + "Games · {opening} · {n}", + &[("opening", &name), ("n", &list.len())], + ) + } + Selection::Repeated { white, index } => { + let r = &report.color(*white).repeated[*index]; + trf( + "Games · {move} · {n}", + &[ + ( + "move", + &format!( + "{} {}", + short_label(r.ply as usize, &r.san), + review::judgement_symbol(r.judgement) + ), + ), + ("n", &list.len()), + ], + ) + } + Selection::Error { white, index } => { + let e = &report.color(*white).errors[*index]; + trf( + "Games · {move} · {n}", + &[ + ( + "move", + &format!( + "{} {}", + short_label(e.ply as usize, &e.san), + review::judgement_symbol(e.judgement) + ), + ), + ("n", &list.len()), + ], + ) + } + }; + let mut clear = false; + ui.horizontal(|ui| { + ui.label(RichText::new(title).strong()); + if self.selection != Selection::None + && crate::widgets::small_close_button(ui) + .on_hover_text(tr("All games")) + .clicked() + { + clear = true; + } + }); + if clear { + self.select(Selection::None); + return; + } + if list.is_empty() { + return; + } + let width = ui.available_width(); + // The names first (at least 110 each): the event, «Then», the ratings (they go + // into the name cell), the errors and the date give way in turn. + let mut show_event = true; + let mut show_then = true; + let mut show_elo = true; + let mut show_errors = report.evaluated(); + let mut show_date = true; + let gap = ui.spacing().item_spacing.x; + let player_w_of = |event: bool, then: bool, elo: bool, errors: bool, date: bool| -> f32 { + let columns = 3 + + 2 * usize::from(elo) + + usize::from(date) + + usize::from(then) + + usize::from(event) + + usize::from(errors); + let fixed = 44.0 + + if elo { 88.0 } else { 0.0 } + + if date { 84.0 } else { 0.0 } + + if errors { 80.0 } else { 0.0 } + + match (then, event) { + (true, true) => 150.0, + (true, false) => 100.0, + _ => 0.0, + } + + if event { 100.0 } else { 0.0 } + + gap * columns as f32; + (width - fixed) / 2.0 + }; + for drop in 0..5 { + if player_w_of(show_event, show_then, show_elo, show_errors, show_date) >= 110.0 { + break; + } + match drop { + 0 => show_event = false, + 1 => show_then = false, + 2 => show_elo = false, + 3 => show_errors = false, + _ => show_date = false, + } + } + let player_w = + player_w_of(show_event, show_then, show_elo, show_errors, show_date).clamp(60.0, 170.0); + let plies: HashMap = list.iter().map(|&g| (g, self.game_ply(g))).collect(); + ui.style_mut().interaction.selectable_labels = false; + let mut table = TableBuilder::new(ui) + .id_salt("prep_games_table") + .striped(true) + .sense(Sense::click()) + .auto_shrink([false, false]) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::exact(player_w).clip(true)); + if show_elo { + table = table.column(Column::exact(44.0)); + } + table = table.column(Column::exact(player_w).clip(true)); + if show_elo { + table = table.column(Column::exact(44.0)); + } + table = table.column(Column::exact(44.0)); + if show_date { + table = table.column(Column::exact(84.0)); + } + if show_then && show_event { + table = table.column(Column::exact(150.0).clip(true)); + } else if show_then { + table = table.column(Column::remainder().at_least(100.0).clip(true)); + } + if show_event { + table = table.column(Column::remainder().at_least(100.0).clip(true)); + } + if show_errors { + table = table.column(Column::exact(80.0).clip(true)); + } + if self.scroll_to_selected + && let Some(c) = self.games_cursor + { + table = table.scroll_to_row(c, None); + self.scroll_to_selected = false; + } + let mut hovered = None; + let mut clicked = None; + let mut opened = None; + let mut game_click = None; + let sort = self.sorts.games; + let player_names: HashSet<&str> = self.names.iter().map(String::as_str).collect(); + table + .header(ROW_H, |mut h| { + let c = &mut game_click; + sort_col(&mut h, tr("White"), "", GameSort::White, sort, c); + if show_elo { + sort_col(&mut h, "Elo", "", GameSort::WhiteElo, sort, c); + } + sort_col(&mut h, tr("Black"), "", GameSort::Black, sort, c); + if show_elo { + sort_col(&mut h, "Elo", "", GameSort::BlackElo, sort, c); + } + sort_col(&mut h, tr("Res."), "", GameSort::Result, sort, c); + if show_date { + sort_col(&mut h, tr("Date"), "", GameSort::Date, sort, c); + } + if show_then { + sort_col( + &mut h, + tr("Then"), + tr("How the game went on from this position"), + GameSort::Then, + sort, + c, + ); + } + if show_event { + sort_col(&mut h, tr("Event"), "", GameSort::Event, sort, c); + } + if show_errors { + sort_col( + &mut h, + tr("Errors"), + tr("His marked moves in the opening of this game"), + GameSort::Errors, + sort, + c, + ); + } + }) + .body(|body| { + body.rows(ROW_H, list.len(), |mut row| { + let gi = list[row.index()]; + let g = &report.games[gi as usize]; + let r = &self.rows[gi as usize]; + row.set_selected(self.games_cursor == Some(row.index())); + let name = |ui: &mut Ui, n: &str| { + let t = RichText::new(n); + ui.add( + egui::Label::new(if player_names.contains(n) { + t.strong() + } else { + t + }) + .truncate(), + ); + }; + let elo = |e: u16| if e > 0 { e.to_string() } else { String::new() }; + let ply = plies.get(&gi).copied().unwrap_or(0); + // Without their column the ratings go after the names, weak. + let name = |ui: &mut Ui, n: &str, e: u16| { + name(ui, n); + if !show_elo && e > 0 { + ui.label(RichText::new(e.to_string()).weak().small()); + } + }; + row.col(|ui| name(ui, &r.white, r.white_elo)); + if show_elo { + row.col(|ui| { + ui.label(RichText::new(elo(r.white_elo)).weak()); + }); + } + row.col(|ui| name(ui, &r.black, r.black_elo)); + if show_elo { + row.col(|ui| { + ui.label(RichText::new(elo(r.black_elo)).weak()); + }); + } + row.col(|ui| { + ui.label(result_text(r.result)); + }); + if show_date { + row.col(|ui| { + ui.label(RichText::new(crate::library::display_date(&g.date)).weak()); + }); + } + if show_then { + row.col(|ui| { + let then: Vec = + g.sans.iter().skip(ply).take(3).cloned().collect(); + let mut text = String::new(); + for (k, san) in then.iter().enumerate() { + let p = ply + k; + if k == 0 || p.is_multiple_of(2) { + text.push_str(&short_label(p, san)); + } else { + text.push_str(san); + } + text.push(' '); + } + ui.add( + egui::Label::new(crate::san::show_line(text.trim_end())).truncate(), + ); + }); + } + if show_event { + row.col(|ui| { + ui.add( + egui::Label::new(RichText::new(&r.event).italics().weak()) + .truncate(), + ); + }); + } + if show_errors { + row.col(|ui| { + ui.spacing_mut().item_spacing.x = 3.0; + let cr = report.color(g.white); + for e in cr + .errors + .iter() + .filter(|e| e.game == gi && self.visible(e.judgement)) + { + let number = e.ply as usize / 2 + 1; + ui.label(RichText::new(format!("{number}.")).small()); + pill(ui, e.judgement).on_hover_text(format!( + "{} {} — {}", + short_label(e.ply as usize, &e.san), + review::judgement_name(e.judgement), + trf( + "better {best}", + &[("best", &crate::san::show(&e.best_san))] + ) + )); + } + }); + } + let resp = row + .response() + .on_hover_text(tr("Double click: open this game at this position")); + if resp.hovered() { + hovered = Some(gi); + } + if resp.double_clicked() { + opened = Some(gi); + } else if resp.clicked() { + clicked = Some(row.index()); + } + }); + }); + if let Some(k) = game_click { + let names = matches!( + k, + GameSort::White + | GameSort::Black + | GameSort::Result + | GameSort::Then + | GameSort::Event + ); + self.sorts.games.click(k, names); + // The keyboard's row is a place in the list: it goes back to the top. + self.games_cursor = None; + } + // The game's move from the shown position, as an arrow. + if let Some(gi) = hovered + && let Some(s) = &self.shown_pos + && s.ply + 1 == s.positions.len() + { + let g = &report.games[gi as usize]; + let ply = plies.get(&gi).copied().unwrap_or(0); + if let Some(m) = g + .ucis + .get(ply) + .and_then(|u| u.parse::().ok()) + .and_then(|u| u.to_move(&s.positions[s.ply]).ok()) + { + self.hover_arrow = m.from().map(|f| (f, crate::board::ui_target(&m))); + } + } + if let Some(i) = clicked { + self.games_cursor = Some(i); + self.focus_games = true; + } + if let Some(gi) = opened { + actions.push(PrepAction::OpenGame { + path: self.path.clone(), + index: report.games[gi as usize].index as usize, + ply: self.open_ply(gi), + }); + } + } + + // ----- the keyboard -------------------------------------------------------------- + + fn keyboard( + &mut self, + ctx: &egui::Context, + _settings: &Settings, + actions: &mut Vec, + ) { + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let alt = |k| KeyboardShortcut::new(Modifiers::ALT, k); + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Num1))) { + self.tab = Tab::Repertoire; + } + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Num2))) { + self.tab = Tab::Openings; + } + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Num3))) { + self.tab = Tab::Errors; + } + if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num1))) { + self.set_color(ColorChoice::White); + } + if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num2))) { + self.set_color(ColorChoice::Black); + } + if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num3))) { + self.set_color(ColorChoice::Both); + } + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::W))) { + actions.push(PrepAction::Back); + } + if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::F)) { + let base = self + .shown_pos + .as_ref() + .map_or(self.color != ColorChoice::Black, |s| s.white); + self.flipped = Some(!self.board_white() == base); + } + if ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::A)) { + if self.job.is_some() { + self.stop_engine_by_user(actions); + } else if self.report.is_some() { + self.engine_asked(ctx, actions); + } + } + if ctx.input_mut(|i| { + i.consume_shortcut(&KeyboardShortcut::new( + Modifiers::COMMAND | Modifiers::SHIFT, + Key::F, + )) + }) && let Some(s) = &self.shown_pos + { + let mut p = Chess::default(); + let moves: Vec = s.ucis[..s.ply] + .iter() + .filter_map(|u| { + let m = u.parse::().ok()?.to_move(&p).ok()?; + p.play_unchecked(m); + Some(m) + }) + .collect(); + actions.push(PrepAction::FindPosition( + self.path.clone(), + Chess::default(), + moves, + !self.board_white(), + )); + } + if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { + if self.board_popup { + self.board_popup = false; + } else if self.selection != Selection::None { + self.select(Selection::None); + } else { + actions.push(PrepAction::Back); + } + } + if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) { + self.focus_games = !self.focus_games; + if self.focus_games && self.games_cursor.is_none() { + self.games_cursor = Some(0); + } + } + let (up, down, left, right, enter, space, home, end) = ctx.input_mut(|i| { + ( + i.consume_key(Modifiers::NONE, Key::ArrowUp), + i.consume_key(Modifiers::NONE, Key::ArrowDown), + i.consume_key(Modifiers::NONE, Key::ArrowLeft), + i.consume_key(Modifiers::NONE, Key::ArrowRight), + i.consume_key(Modifiers::NONE, Key::Enter), + i.consume_key(Modifiers::NONE, Key::Space), + i.consume_key(Modifiers::NONE, Key::Home), + i.consume_key(Modifiers::NONE, Key::End), + ) + }); + if !(up || down || left || right || enter || space || home || end) { + return; + } + if self.focus_games { + let list = self.games_of(); + if list.is_empty() { + return; + } + let cur = self.games_cursor.unwrap_or(0); + let next = if up { + cur.saturating_sub(1) + } else if down { + (cur + 1).min(list.len() - 1) + } else if home { + 0 + } else if end { + list.len() - 1 + } else { + cur + }; + if next != cur || self.games_cursor.is_none() { + self.games_cursor = Some(next); + self.scroll_to_selected = true; + } + if enter && let Some(r) = &self.report { + actions.push(PrepAction::OpenGame { + path: self.path.clone(), + index: r.games[list[next] as usize].index as usize, + ply: self.open_ply(list[next]), + }); + } + return; + } + match self.tab { + Tab::Repertoire => self.tree_keys(up, down, left, right, enter, space, home, end), + Tab::Openings => self.openings_keys(up, down, left, right, enter, space, home, end), + Tab::Errors => { + self.errors_keys(up, down, left, right, enter, space, home, end, actions) + } + } + } + + #[allow(clippy::too_many_arguments)] + fn tree_keys( + &mut self, + up: bool, + down: bool, + left: bool, + right: bool, + enter: bool, + space: bool, + home: bool, + end: bool, + ) { + let rows = self.tree_rows(); + if rows.is_empty() { + return; + } + let at = rows.iter().position(|r| match (r, &self.selection) { + ( + TreeRow::Node { white, node, .. }, + Selection::Node { + white: sw, + node: sn, + }, + ) => white == sw && node == sn, + _ => false, + }); + let go = |screen: &mut Self, i: usize| { + if let Some(TreeRow::Node { white, node, .. }) = rows.get(i).copied() { + screen.select(Selection::Node { white, node }); + screen.scroll_to_selected = true; + } + }; + let Some(at) = at else { + if up || down || home || end || right { + go(self, 0); + } + return; + }; + let Some(TreeRow::Node { white, node, .. }) = rows.get(at).copied() else { + return; + }; + let has_children = self + .report + .as_ref() + .is_some_and(|r| !r.color(white).tree.nodes[node as usize].children.is_empty()); + let open = self.expanded.contains(&(white, node)); + if down { + let mut next = at + 1; + while next < rows.len() && matches!(rows[next], TreeRow::Others { .. }) { + next += 1; + } + if next < rows.len() { + go(self, next); + } + } else if up { + let mut prev = at; + while prev > 0 { + prev -= 1; + if matches!(rows[prev], TreeRow::Node { .. }) { + go(self, prev); + break; + } + } + } else if home { + go(self, 0); + } else if end { + let last = rows + .iter() + .rposition(|r| matches!(r, TreeRow::Node { .. })) + .unwrap_or(0); + go(self, last); + } else if right { + if has_children && !open { + self.expanded.insert((white, node)); + } else if has_children { + go(self, at + 1); + } + } else if left { + if open { + self.expanded.remove(&(white, node)); + } else if let Some(p) = self + .report + .as_ref() + .and_then(|r| r.color(white).tree.nodes[node as usize].parent) + { + self.select(Selection::Node { white, node: p }); + self.scroll_to_selected = true; + } + } else if space { + if has_children && !self.expanded.remove(&(white, node)) { + self.expanded.insert((white, node)); + } + } else if enter { + self.focus_games = true; + self.games_cursor = Some(0); + } + } + + #[allow(clippy::too_many_arguments)] + fn openings_keys( + &mut self, + up: bool, + down: bool, + left: bool, + right: bool, + enter: bool, + space: bool, + home: bool, + end: bool, + ) { + let rows = self.opening_rows(); + if rows.is_empty() { + return; + } + let at = rows.iter().position(|&(w, f, v)| { + self.selection + == Selection::Opening { + white: w, + family: f, + variation: v, + } + }); + let go = |screen: &mut Self, i: usize| { + if let Some(&(white, family, variation)) = rows.get(i) { + screen.select(Selection::Opening { + white, + family, + variation, + }); + screen.scroll_to_selected = true; + } + }; + let Some(at) = at else { + if up || down || home || end || right { + go(self, 0); + } + return; + }; + let (white, f, v) = rows[at]; + if down { + go(self, (at + 1).min(rows.len() - 1)); + } else if up { + go(self, at.saturating_sub(1)); + } else if home { + go(self, 0); + } else if end { + go(self, rows.len() - 1); + } else if right || space { + if v.is_none() && !self.open_families.remove(&(white, f)) { + self.open_families.insert((white, f)); + } + } else if left { + if v.is_some() { + go( + self, + rows.iter() + .position(|&(w, ff, vv)| w == white && ff == f && vv.is_none()) + .unwrap_or(at), + ); + } else { + self.open_families.remove(&(white, f)); + } + } else if enter { + self.focus_games = true; + self.games_cursor = Some(0); + } + } +} + +/// The arrows of an error: the move played in the colour of its sign, the better move +/// in green. +fn error_arrows(pos: &Chess, played: &str, best: Option<&str>, j: Judgement) -> Vec { + let mut out = Vec::new(); + let to_arrow = |u: &str, color: Color32| -> Option { + let m = u.parse::().ok()?.to_move(pos).ok()?; + Some(Arrow { + from: m.from()?, + to: crate::board::ui_target(&m), + color, + weight: 1.0, + }) + }; + if let Some(a) = to_arrow(played, review::judgement_color(j).gamma_multiply(0.85)) { + out.push(a); + } + if let Some(a) = best.and_then(|b| { + to_arrow( + b, + crate::board::shape_preview_color(chess_core::ShapeColor::Green), + ) + }) { + out.push(a); + } + out +} + +/// «6…Nb6 ? — better 6…e6 · 0.0 → −1.2». +fn error_note(e: &prep::OpeningError) -> String { + let played = format!( + "{} {}", + short_label(e.ply as usize, &e.san), + review::judgement_symbol(e.judgement) + ); + trf( + "{played} — better {best} · {before} → {after}", + &[ + ("played", &played), + ("best", &short_label(e.ply as usize, &e.best_san)), + ("before", &e.before.format()), + ("after", &e.after.format()), + ], + ) +} + +/// The table's line to the family's own position: the shallowest position of the +/// family's games whose name is of the family ("1. e4 c5" for the Sicilian, whatever +/// the variations); the shortest variation's line when there is none. +fn family_line(report: &PrepReport, fam: &prep::Family) -> Option { + let mut best: Option<&'static prep::Opening> = None; + for v in &fam.variations { + for &gi in &v.games { + let g = &report.games[gi as usize]; + for &k in &g.keys { + let Some(o) = prep::openings::by_position(k).map(prep::openings::get) else { + continue; + }; + if o.family() == fam.name && best.is_none_or(|b| o.plies < b.plies) { + best = Some(o); + } + } + } + } + best.map(|o| o.line.clone()).or_else(|| { + fam.variations + .iter() + .filter_map(|v| v.opening.and_then(|o| report.openings.get(o))) + .min_by_key(|o| o.plies) + .map(|o| o.line.clone()) + }) +} + +/// The ply of the first position of a game's line named with `family`. +fn family_ply(g: &GameInfo, family: &str) -> Option { + (0..g.keys.len()).find(|&i| { + prep::openings::by_position(g.keys[i]) + .map(prep::openings::get) + .is_some_and(|o| o.family() == family) + }) +} + +/// A header cell: the title in bold, a tooltip when there is one. +fn head_col(h: &mut egui_extras::TableRow<'_, '_>, text: &str, hint: &str) { + h.col(|ui| { + let l = ui.label(RichText::new(text).strong()); + if !hint.is_empty() { + l.on_hover_text(hint); + } + }); +} + +fn result_text(r: &str) -> &str { + if r == "1/2-1/2" { "½-½" } else { r } +} + +fn text_width(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { + let font = style.resolve(ui.style()); + ui.painter() + .layout_no_wrap(text.to_owned(), font, Color32::WHITE) + .size() + .x +} + +#[cfg(test)] +mod tests { + use super::*; + + fn c(id: u32, name: &str) -> Candidate { + Candidate { + id, + name: name.to_owned(), + games: 1, + } + } + + #[test] + fn candidates_split_into_whole_words_and_similar_names() { + let list = vec![ + c(1, "Вафин Радель"), + c(2, "Vafin, Radel"), + c(3, "Вафина РаÑ�на"), + c(4, "Вафин Р."), + ]; + let (exact, similar) = split_candidates("Вафин", list.clone()); + assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![1, 4]); + assert_eq!(similar.iter().map(|c| c.id).collect::>(), vec![2, 3]); + // An initial matches the beginning of a word; the full stop is ignored. + let (exact, _) = split_candidates("Вафин Р.", list.clone()); + assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![1, 4]); + let (exact, similar) = split_candidates("вафин радель", list.clone()); + assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![1]); + assert_eq!(similar.len(), 3); + // Commas and case do not matter. + let (exact, _) = split_candidates("radel vafin", list); + assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![2]); + } + + #[test] + fn a_header_click_sorts_then_turns_the_order_round() { + let mut s = PrepSorts::default().games; + assert_eq!( + (s.key, s.ascending), + (GameSort::Date, false), + "newest first" + ); + s.click(GameSort::Date, false); + assert!(s.ascending, "the same column again: the other way"); + s.click(GameSort::White, true); + assert_eq!( + (s.key, s.ascending), + (GameSort::White, true), + "a name column starts A–Z" + ); + assert_eq!(s.apply(std::cmp::Ordering::Less), std::cmp::Ordering::Less); + s.click(GameSort::White, true); + assert_eq!( + s.apply(std::cmp::Ordering::Less), + std::cmp::Ordering::Greater + ); + assert_eq!(cmp_val(&num(2), &num(10)), std::cmp::Ordering::Less); + assert_eq!( + cmp_val(&SortVal::Text("b".into()), &SortVal::Text("a".into())), + std::cmp::Ordering::Greater + ); + // Kept in the settings as they are. + let json = serde_json::to_string(&PrepSorts::default()).unwrap(); + assert_eq!( + serde_json::from_str::(&json).unwrap(), + PrepSorts::default() + ); + } + + #[test] + fn labels_and_lines() { + assert_eq!(short_label(0, "e4"), "1.e4"); + assert_eq!(short_label(1, "c5"), "1…c5"); + assert_eq!(short_label(4, "Bb5"), "3.Bb5"); + let sans: Vec = ["e4", "c5", "Nf3"] + .iter() + .map(|s| (*s).to_owned()) + .collect(); + assert_eq!(line_text(&sans), "1.e4 c5 2.Nf3"); + assert_eq!( + table_line("1. e4 c5 2. Nf3 Nc6 3. Bb5"), + vec!["1.e4", "c5", "2.Nf3", "Nc6", "3.Bb5"] + ); + assert_eq!(table_line("1... e5"), vec!["1…e5"]); + let ucis: Vec = ["e2e4", "c7c5", "g1f3"] + .iter() + .map(|s| (*s).to_owned()) + .collect(); + assert_eq!(replay(&ucis).len(), 4); + assert_eq!(replay(&["zz".to_owned()]).len(), 1); + } + + #[test] + fn the_period_of_the_games() { + use prep::Outcome; + let game = |date: &str| GameInfo { + index: 0, + white: true, + opponent: String::new(), + opponent_elo: 0, + date: date.to_owned(), + outcome: Outcome::Unknown, + ucis: Vec::new(), + sans: Vec::new(), + keys: Vec::new(), + opening: None, + named: None, + book: None, + }; + assert_eq!( + period(&[game("2026.10.18"), game("2026.01.03"), game("")]), + "01.2026 – 10.2026" + ); + assert_eq!(period(&[game("2026.10.18")]), "10.2026"); + assert_eq!(period(&[game("")]), ""); + } + + #[test] + fn error_count_parts_skip_zeroes_and_keep_the_order() { + let counts = ErrorCounts { + inaccuracies: 30, + mistakes: 0, + blunders: 13, + }; + assert_eq!( + count_parts(&counts), + vec![(30, Judgement::Inaccuracy), (13, Judgement::Blunder)] + ); + assert!(count_parts(&ErrorCounts::default()).is_empty()); + } +} diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs new file mode 100644 index 0000000..84326ca --- /dev/null +++ b/apps/desktop/src/reference.rs @@ -0,0 +1,1642 @@ +//! The "Reference" tab of a game («Справочник»): what was played in the current +//! position in a database of the shelf (Mega for theory, an opening collection, a +//! pupil's games), following the game's moves. Two tables, as in ChessBase: the moves +//! played from the position with their statistics, and the strongest games that +//! reached it. The database is picked in the panel and remembered; by default the +//! largest one on the shelf. The same position search as the library's search board +//! (`docs/dev/import.md`), run in the background for each new position. It also tells +//! how long the game's main line stays in the database ("theory") and whether the game +//! itself is there. Layout: `docs/design/reference.md`. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use chess_core::{Game, NodeId}; +use chess_import::Database; +use chess_import::position::{Match, MoveStat, PositionOutcome, PositionQuery, Tally, theory_end}; +use egui::{RichText, Sense, Ui, vec2}; +use egui_extras::{Column, TableBuilder}; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, Move, Position}; + +use crate::board_search::{self, Background}; +use crate::i18n::{tr, trf}; +use crate::large_db::grouped; + +/// A database of the shelf as the panel offers it. +pub struct RefDb { + pub path: PathBuf, + pub name: String, + /// Loaded (with its number of records), or not yet. + pub db: Option>, + /// It could not be opened (why). + pub failed: Option, + /// Size of its file, to pick the largest one before any is opened. + pub bytes: u64, +} + +/// What the panel asks of the game view and the application. +pub enum RefAction { + /// Play this move in the game (as a move on the board: added, undoable). + Play(Move), + /// Use this database from now on. + Choose(PathBuf), + /// Load the chosen database (it is on the shelf but not open yet). + Load(PathBuf), + /// Open a game of the reference database at this position. + OpenGame(PathBuf, usize, Chess), + /// Go to this node of the game (the last move still in the database). + Goto(NodeId), + /// Show the position on the library's search board of this database. + FindInLibrary(PathBuf), +} + +/// A game of the games table. +#[derive(Clone, Debug)] +struct GameRow { + index: usize, + white: String, + white_elo: u16, + black: String, + black_elo: u16, + result: String, + year: u16, + event: String, + /// The move the game played from the position in the line it is listed for + /// (`None`: it ends here). + next: Option, + /// The three half-moves from the position, "5.Nc3 a6 6.Be2". + then: String, +} + +#[cfg(test)] +impl GameRow { + fn average(&self) -> u32 { + average(self.white_elo, self.black_elo) + } +} + +fn average(w: u16, b: u16) -> u32 { + if w > 0 && b > 0 { + (u32::from(w) + u32::from(b)) / 2 + } else { + 0 + } +} + +/// A search result with what the tables show already worked out (picking the strongest +/// of millions of matches, reading the games' moves: work for the background). +pub struct Found { + out: PositionOutcome, + /// The strongest games, the newest games; per move the strongest that played it. + strongest: Vec, + newest: Vec, + by_move: HashMap>, + by_move_newest: HashMap>, + /// Per move: the strongest players who played it (their own rating). + players: HashMap, + /// Most games have no result: a book of chapters (counts are chapters, no results). + books: bool, +} + +/// Identity of a request: database, position and the moves that reached it. +#[derive(Clone, PartialEq, Eq, Hash)] +struct Key { + path: PathBuf, + position: u64, + line: Option>, +} + +/// How far a game's main line stays in the database. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BookEnd { + /// The last node of the main line still found in other games (`None`: not even + /// the start position). + pub last: Option, + /// The whole main line is in the database (a game with moves). + pub to_the_end: bool, + /// Copies of this very game in the database (same players and year, same final + /// position), and the game itself when it comes from it: left out of "theory" and + /// of the games table. + pub copies: Vec, +} + +/// The theory of one game: the main line it was worked out for (UCI moves) and the +/// answer. A longer line that starts with it keeps the answer when the theory ended +/// inside it. +struct Book { + path: PathBuf, + line: Vec, + end: BookEnd, +} + +/// Database and main line (UCI) of a theory request. +type BookKey = (PathBuf, Vec); + +/// Results kept per database and position, at most this many matches in all; a single +/// bigger result is shown but not kept. +const CACHE_MATCHES: usize = 5_000_000; +/// Games listed: overall and per move; "then" is read for the most played moves. +const GAMES_SHOWN: usize = 100; +const GAMES_PER_MOVE: usize = 40; +const MOVES_WITH_GAMES: usize = 12; +/// A PGN database up to this many matches has the continuations of every game read +/// from its tree (a game can reach the position in several variations). +const PGN_TREE_MATCHES: usize = 5_000; +/// Results bigger than the cache kept apart (the start position, 1.e4). +const BIG_KEPT: usize = 2; + +/// Sort of the games table. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +enum GameSort { + #[default] + Strongest, + Newest, +} + +#[derive(Default)] +pub struct Reference { + /// Databases of the shelf (set by the application every frame). + pub dbs: Vec, + job: Option<(Key, Background)>, + shown: Option<(Key, Arc)>, + cache: HashMap>, + /// The fast-search files of a large base, built when it is first used here. + prepare: Option<(PathBuf, Background)>, + prepared: Vec, + /// The theory of the game shown, the job working it out, and a request that failed + /// (not retried until the game or the database changes). + book: Option, + book_job: Option<(BookKey, Background)>, + book_failed: Option, + /// The move of the moves table under the pointer; the selected one (it filters the + /// games), for its database and position. + hover: Option, + selected: Option<(PathBuf, u64, UciMove)>, + sort: GameSort, + /// A request that could not be answered (no memory for a PGN table…): not retried. + failed: Option, + /// The last results too big for the cache (the start position of Mega: 11.7 + /// million matches), kept apart so going back to them is instant. + big: Vec<(Key, Arc)>, +} + +/// The position of `node` and the moves that reach it from the usual start (`None` +/// for a game from a set-up position, or a line with a null move). +fn query_for(game: &Game, node: NodeId) -> Option { + let pos = game.position(node)?.clone(); + let line = board_search::line_to(game, node).and_then(|(start, line)| { + chess_import::position::same_position(&start, &Chess::default()).then_some(line) + }); + Some(PositionQuery::new(pos, line)) +} + +fn key(path: &Path, q: &PositionQuery) -> Key { + Key { + path: path.to_owned(), + position: q.key(), + line: q.line.as_ref().map(|l| { + l.iter() + .map(|m| chess_import::position::uci(m).to_string()) + .collect() + }), + } +} + +/// The main line as UCI moves (a null move as "--"). +fn main_line(game: &Game) -> Vec { + let mut out = Vec::new(); + let mut node = game.root(); + while let Some(next) = game.main_child(node) { + out.push( + game.game_move(next) + .and_then(|m| m.uci()) + .unwrap_or_else(|| "--".into()), + ); + node = next; + } + out +} + +/// "40…Ke5": a move of the game with the number and side of the position before it +/// (games from a set-up position count from their FEN). +fn node_label(game: &Game, node: NodeId) -> Option { + let m = game.game_move(node)?; + let before = game.position(game.parent(node)?)?; + let n = before.fullmoves().get(); + let san = crate::san::show(&m.san); + Some(match before.turn() { + Color::White => format!("{n}.{san}"), + Color::Black => format!("{n}…{san}"), + }) +} + +/// "5.Nc3" / "5…Nc6". +fn move_label(pos: &Chess, m: Move) -> String { + let san = shakmaty::san::SanPlus::from_move(pos.clone(), m).to_string(); + let san = crate::san::show(&san); + let n = pos.fullmoves().get(); + match pos.turn() { + Color::White => format!("{n}.{san}"), + Color::Black => format!("{n}…{san}"), + } +} + +/// The surname of "Carlsen, Magnus" / "Alekhine Alexander (RUS)" (the first word, as +/// databases write names surname first); empty for an unknown player. +fn surname(name: &str) -> String { + let name = match name.find('(') { + Some(i) => &name[..i], + None => name, + } + .trim(); + // The first word before a comma: "Carlsen, Magnus", "Duke of Brunswick, Count" + // and "Duke Karl / Count Isouard" all compare by it. + let before = name.split_once(',').map_or(name, |(s, _)| s); + let s = before.split_whitespace().next().unwrap_or(""); + if s == "?" || s == "NN" { + String::new() + } else { + s.to_owned() + } +} + +/// Ratings and year of a match without reading names (cheap for millions). +fn ratings(db: &Database, index: usize) -> (u16, u16, u16) { + match db { + Database::ChessBase(b) => { + let r = b.record(index); + let u = |at: usize, n: usize| -> u32 { + r.get(at..at + n) + .map_or(0, |s| s.iter().fold(0, |a, x| (a << 8) | u32::from(*x))) + }; + ( + u(0x1f, 2) as u16, + u(0x21, 2) as u16, + ((u(0x18, 3) >> 9) & 0xfff) as u16, + ) + } + Database::Pgn(p) => { + let e = &p.entries()[index]; + let elo = |k: &str| e.tag(k).and_then(|v| v.parse().ok()).unwrap_or(0); + let year = e + .tag("Date") + .and_then(|d| d.get(..4)) + .and_then(|y| y.parse().ok()) + .unwrap_or(0); + (elo("WhiteElo"), elo("BlackElo"), year) + } + } +} + +/// The header fields of a game of the database (no moves). +fn row_of(db: &Database, index: usize, next: Option) -> GameRow { + let (white_elo, black_elo, year) = ratings(db, index); + let (white, black, result, event) = match db { + Database::ChessBase(b) => { + let r = b.row(index); + (r.white, r.black, r.result.to_owned(), r.event) + } + Database::Pgn(p) => { + let e = &p.entries()[index]; + let t = |k: &str| e.tag(k).unwrap_or("").to_owned(); + (t("White"), t("Black"), t("Result"), t("Event")) + } + }; + GameRow { + index, + white, + white_elo, + black, + black_elo, + result, + year, + event, + next, + then: String::new(), + } +} + +/// "5.Nc3 a6 6.Be2" from `node` on: its child playing `next`, then the main line. +fn then_from(game: &Game, node: NodeId, next: Option) -> String { + let Some(next) = next else { + return String::new(); + }; + let next = next.to_string(); + let Some(mut child) = game.children(node).iter().copied().find(|c| { + game.game_move(*c) + .and_then(|m| m.uci()) + .is_some_and(|u| u == next) + }) else { + return String::new(); + }; + let mut out = Vec::new(); + for k in 0..3 { + let Some(m) = game.game_move(child) else { + break; + }; + let Some(before) = game.parent(child).and_then(|p| game.position(p)) else { + break; + }; + let n = before.fullmoves().get(); + // Latin here (made in the background, kept): shown through `san::show_line`. + out.push(match before.turn() { + Color::White => format!("{n}.{}", m.san), + Color::Black if k == 0 => format!("{n}…{}", m.san), + Color::Black => m.san.clone(), + }); + match game.main_child(child) { + Some(c) => child = c, + None => break, + } + } + out.join(" ") +} + +/// The nodes of `game` in the position `key`, in tree order (main line first). +fn occurrences(game: &Game, key: u64) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![game.root()]; + while let Some(n) = stack.pop() { + if game + .position(n) + .is_some_and(|p| chess_import::position::key(p) == key) + { + out.push(n); + } + stack.extend(game.children(n).iter().rev().copied()); + } + out +} + +/// What a game of a PGN database played from the position, in every branch, each +/// with its "then": `(next, then)`; the game's own `Match::next` first. +fn pgn_continuations(db: &Database, m: &Match, key: u64) -> Vec<(Option, String)> { + let Some(parsed) = db.load_game(m.index as usize) else { + return vec![(m.next, String::new())]; + }; + let g = &parsed.game; + let mut out: Vec<(Option, String)> = Vec::new(); + for node in occurrences(g, key) { + let children = g.children(node); + if children.is_empty() { + if !out.iter().any(|(n, _)| n.is_none()) { + out.push((None, String::new())); + } + continue; + } + for c in children { + let Some(u) = g + .game_move(*c) + .and_then(|x| x.uci()) + .and_then(|u| u.parse::().ok()) + else { + continue; + }; + if !out.iter().any(|(n, _)| *n == Some(u)) { + out.push((Some(u), then_from(g, node, Some(u)))); + } + } + } + // The match's own continuation leads (it is the one counted for the game first). + if let Some(i) = out.iter().position(|(n, _)| *n == m.next) { + out.swap(0, i); + } + if out.is_empty() { + out.push((m.next, String::new())); + } + out +} + +/// "Then" of a game whose main line reaches the position at `m.ply` (a ChessBase +/// search looks at main lines only). +fn main_line_then(db: &Database, m: &Match) -> String { + let Some(parsed) = db.load_game(m.index as usize) else { + return String::new(); + }; + let g = &parsed.game; + let mut node = g.root(); + for _ in 0..m.ply { + match g.main_child(node) { + Some(n) => node = n, + None => return String::new(), + } + } + then_from(g, node, m.next) +} + +/// The `n` best of `items` by `score` (highest first), without sorting all of them. +fn best(mut items: Vec, n: usize, score: impl Fn(&T) -> K) -> Vec { + if items.len() > n { + items.select_nth_unstable_by(n, |a, b| score(b).cmp(&score(a))); + items.truncate(n); + } + items.sort_by_key(|x| std::cmp::Reverse(score(x))); + items +} + +/// One match for picking: its number among the matches, average rating, year and the +/// rating of the player to move. +type Fact = (usize, u32, u16, u16); + +/// Works out what the tables show for an outcome. `None` when cancelled (a newer +/// position was asked for). +fn tables( + db: &Database, + position: &Chess, + out: PositionOutcome, + cancel: &AtomicBool, +) -> Option { + use std::sync::atomic::Ordering; + let stopped = || cancel.load(Ordering::Relaxed); + let key = chess_import::position::key(position); + let mover_white = position.turn() == Color::White; + let facts: Vec = out + .matches + .iter() + .enumerate() + .map(|(k, m)| { + let (w, b, y) = ratings(db, m.index as usize); + (k, average(w, b), y, if mover_white { w } else { b }) + }) + .collect(); + if stopped() { + return None; + } + let by_strength = |x: &Fact| (x.1, x.2, std::cmp::Reverse(x.0)); + let by_year = |x: &Fact| (x.2, x.1, std::cmp::Reverse(x.0)); + let pgn = matches!(db, Database::Pgn(_)); + // What each match played from the position: every branch of a PGN game when the + // result is small enough to read them all, else the chosen occurrence's move. + let mut continuations: HashMap, String)>> = HashMap::new(); + if pgn && out.matches.len() <= PGN_TREE_MATCHES { + for (k, m) in out.matches.iter().enumerate() { + if k % 256 == 0 && stopped() { + return None; + } + continuations.insert(k, pgn_continuations(db, m, key)); + } + } + let moves_of = |k: usize| -> Vec> { + match continuations.get(&k) { + Some(c) => c.iter().map(|(n, _)| *n).collect(), + None => vec![out.matches[k].next], + } + }; + // A row of the games table; "then" (reading the game's moves) only when asked. + let row = |k: usize, next: Option, then: bool| -> GameRow { + let m = &out.matches[k]; + let mut r = row_of(db, m.index as usize, next); + if !then { + return r; + } + r.then = match continuations.get(&k) { + Some(c) => c + .iter() + .find(|(n, _)| *n == next) + .map(|(_, t)| t.clone()) + .unwrap_or_default(), + None if pgn => pgn_continuations(db, m, key) + .into_iter() + .find(|(n, _)| *n == next) + .map(|(_, t)| t) + .unwrap_or_default(), + None => main_line_then(db, m), + }; + r + }; + let strongest = best(facts.clone(), GAMES_SHOWN, by_strength) + .into_iter() + .map(|f| row(f.0, out.matches[f.0].next, true)) + .collect(); + if stopped() { + return None; + } + let newest = best(facts.clone(), GAMES_SHOWN, by_year) + .into_iter() + .map(|f| row(f.0, out.matches[f.0].next, true)) + .collect(); + // Per move of the table: its strongest and newest games and its strongest players + // ("then" for the most played moves; the rest are rarely looked at). + let main_moves: Vec = out + .moves + .iter() + .take(MOVES_WITH_GAMES) + .map(|m| m.uci) + .collect(); + let mut groups: HashMap> = HashMap::new(); + for f in &facts { + for n in moves_of(f.0).into_iter().flatten() { + groups.entry(n).or_default().push(*f); + } + } + let mut by_move = HashMap::new(); + let mut by_move_newest = HashMap::new(); + let mut players = HashMap::new(); + for (mv, list) in groups { + if stopped() { + return None; + } + let then = main_moves.contains(&mv); + let mut names: Vec = Vec::new(); + for f in best(list.clone(), 400, |x: &Fact| { + (x.3, x.2, std::cmp::Reverse(x.0)) + }) { + let r = row_of(db, out.matches[f.0].index as usize, None); + let s = surname(if mover_white { &r.white } else { &r.black }); + if !s.is_empty() && !names.contains(&s) { + names.push(s); + } + if names.len() == 2 { + break; + } + } + players.insert(mv, names.join(", ")); + let rows: Vec = best(list.clone(), GAMES_PER_MOVE, by_strength) + .into_iter() + .map(|f| row(f.0, Some(mv), then)) + .collect(); + by_move.insert(mv, rows); + let rows: Vec = best(list, GAMES_PER_MOVE, by_year) + .into_iter() + .map(|f| row(f.0, Some(mv), then)) + .collect(); + by_move_newest.insert(mv, rows); + } + let books = match db { + Database::Pgn(p) => { + let decided = p + .entries() + .iter() + .filter(|e| matches!(e.result(), Some("1-0" | "0-1" | "1/2-1/2"))) + .count(); + decided * 2 < p.len() + } + Database::ChessBase(_) => false, + }; + Some(Found { + out, + strongest, + newest, + by_move, + by_move_newest, + players, + books, + }) +} + +/// Games among `matches` with the players and year of `game` (the same game, maybe +/// from another source). +fn same_game(db: &Database, game: &Game, matches: &[Match]) -> Vec { + let (w, b) = ( + surname(game.tag("White").unwrap_or("")).to_lowercase(), + surname(game.tag("Black").unwrap_or("")).to_lowercase(), + ); + if w.is_empty() || b.is_empty() { + return Vec::new(); + } + let year: u16 = game + .tag("Date") + .and_then(|d| d.get(..4)) + .and_then(|y| y.parse().ok()) + .unwrap_or(0); + matches + .iter() + .filter(|m| { + let r = row_of(db, m.index as usize, None); + surname(&r.white).to_lowercase() == w + && surname(&r.black).to_lowercase() == b + && (year == 0 || r.year == 0 || r.year == year) + }) + .map(|m| m.index as usize) + .collect() +} + +/// The theory of `game`'s main line in `db`. `exclude`: the game itself when it comes +/// from this database. +fn book_end( + db: &Database, + game: &Game, + exclude: Option, + from: usize, + cancel: &AtomicBool, +) -> Option { + let mut nodes = vec![game.root()]; + while let Some(n) = game.main_child(*nodes.last()?) { + nodes.push(n); + } + let search = |q: &PositionQuery| db.search_position(None, q, &Default::default(), cancel); + // Copies: games with the same players and year that reach the final position. + let mut copies: Vec = exclude.into_iter().collect(); + if nodes.len() > 1 + && let Some(q) = query_for(game, *nodes.last()?) + { + let out = search(&q)?; + if out.matches.len() <= 10_000 { + copies.extend(same_game(db, game, &out.matches)); + } + } + copies.sort_unstable(); + copies.dedup(); + let known = |ply: usize| -> Option { + let Some(q) = query_for(game, nodes[ply]) else { + return Some(false); + }; + let out = search(&q)?; + Some( + out.matches + .iter() + .any(|m| copies.binary_search(&(m.index as usize)).is_err()), + ) + }; + // The first plies one by one (the opening index answers them at once), then by + // doubling and halving (`theory_end`). `from`: the plies before it are known + // already (the game grew past a theory that reached its end). + let end = theory_end(nodes.len(), from, known)?; + Some(BookEnd { + last: end.last_known.map(|p| nodes[p]), + to_the_end: nodes.len() > 1 && end.first_unknown.is_none(), + copies, + }) +} + +/// "Mega Database 2026 · 11,7 млн партий" for the database picker. +fn db_label(d: &RefDb) -> String { + match &d.db { + Some(db) => format!("{} · {}", d.name, crate::i18n::games_short(db.len())), + None => format!("{} · {}", d.name, tr("not open")), + } +} + +impl Reference { + /// The move under the pointer, or the selected one (an arrow on the board). + pub fn hover(&self) -> Option { + self.hover.or(self.selected.as_ref().map(|(_, _, m)| *m)) + } + + /// The database in use: the chosen one if it is on the shelf, else the largest + /// file on the shelf. + fn current<'a>(&'a self, chosen: Option<&Path>) -> Option<&'a RefDb> { + chosen + .and_then(|c| self.dbs.iter().find(|d| d.path == c)) + .or_else(|| self.dbs.iter().max_by_key(|d| d.bytes)) + } + + /// Collects finished work. + fn poll(&mut self) { + if let Some((k, job)) = &self.job + && let Some(r) = job.poll() + { + let k = k.clone(); + self.job = None; + match r { + Some(found) => { + let found = Arc::new(found); + let n = found.out.matches.len(); + if n <= CACHE_MATCHES { + let kept: usize = self.cache.values().map(|o| o.out.matches.len()).sum(); + if kept + n > CACHE_MATCHES { + self.cache.clear(); + } + self.cache.insert(k.clone(), found.clone()); + } else { + self.big.retain(|(bk, _)| *bk != k); + self.big.push((k.clone(), found.clone())); + if self.big.len() > BIG_KEPT { + self.big.remove(0); + } + } + self.shown = Some((k, found)); + } + None => self.failed = Some(k), + } + } + if let Some((path, job)) = &self.prepare + && job.poll().is_some() + { + self.prepared.push(path.clone()); + self.prepare = None; + } + if let Some(((path, line), job)) = &self.book_job + && let Some(r) = job.poll() + { + let (path, line) = (path.clone(), line.clone()); + self.book_job = None; + match r { + Some(end) => self.book = Some(Book { path, line, end }), + None => self.book_failed = Some((path, line)), + } + } + } + + /// The theory for this game and database, if worked out: also for a longer line + /// when the theory ended inside the one it was worked out for. + fn book_for(&self, path: &Path, line: &[String]) -> Option<&BookEnd> { + let b = self.book.as_ref().filter(|b| b.path == path)?; + if b.line == line { + return Some(&b.end); + } + (!b.line.is_empty() && line.starts_with(&b.line) && !b.end.to_the_end).then_some(&b.end) + } + + /// Starts what the position and the database need. + fn request( + &mut self, + ctx: &egui::Context, + path: &Path, + db: &Arc, + game: &Game, + query: &PositionQuery, + exclude: Option, + ) { + let now = ctx.input(|i| i.time); + // A large base gets its search index once (as the search board does). + if let Some(b) = db.as_chessbase() + && self.prepare.is_none() + && !self.prepared.iter().any(|p| p == path) + && b.prepare_wanted() + { + let db2 = db.clone(); + if let Some(job) = Background::spawn(ctx, now, move |progress, cancel| { + db2.as_chessbase()?.prepare(progress, cancel).ok() + }) { + self.prepare = Some((path.to_owned(), job)); + } + } + let k = key(path, query); + let kept = self + .cache + .get(&k) + .or_else(|| self.big.iter().find(|(bk, _)| *bk == k).map(|(_, f)| f)); + if let Some(found) = kept { + self.shown = Some((k.clone(), found.clone())); + self.job = None; + } else if self.failed.as_ref() != Some(&k) + && self.shown.as_ref().is_none_or(|(sk, _)| *sk != k) + && self.job.as_ref().is_none_or(|(jk, _)| *jk != k) + { + let (db2, q) = (db.clone(), query.clone()); + self.job = Background::spawn(ctx, now, move |progress, cancel| { + let out = db2.search_position(None, &q, progress, cancel)?; + tables(&db2, &q.position, out, cancel) + }) + .map(|j| (k, j)); + } + // The theory of the main line, once per game and database (kept while the + // game grows past its end). + let line = main_line(game); + let bk = (path.to_owned(), line.clone()); + let known = self.book_for(path, &line).is_some() + || self.book_job.as_ref().is_some_and(|(k, _)| *k == bk) + || self.book_failed.as_ref() == Some(&bk); + if !known && line.is_empty() { + // An empty game: no theory and no copies to look for. + self.book = Some(Book { + path: path.to_owned(), + line, + end: BookEnd { + last: None, + to_the_end: false, + copies: exclude.into_iter().collect(), + }, + }); + } else if !known && self.job.is_none() { + // After the tables (both searching at once would compete for the machine). + // A game grown past a theory that reached its end checks the new moves only. + let from = self + .book + .as_ref() + .filter(|b| b.path == path && b.end.to_the_end && line.starts_with(&b.line)) + .map_or(0, |b| b.line.len() + 1); + let (db2, g) = (db.clone(), game.clone()); + self.book_job = Background::spawn(ctx, now, move |_, cancel| { + book_end(&db2, &g, exclude, from, cancel) + }) + .map(|j| (bk, j)); + } + } + + /// The panel. `chosen`: the database picked last time; `source`: where the game + /// comes from (it is left out of "theory" when it is the same database). + pub fn ui( + &mut self, + ui: &mut Ui, + game: &Game, + cursor: NodeId, + chosen: Option<&Path>, + source: Option<(&Path, usize)>, + ) -> Option { + self.poll(); + self.hover = None; + let mut action = None; + let Some(current) = self.current(chosen) else { + ui.add_space(8.0); + ui.label( + RichText::new(tr( + "Add a database to the library to see what was played here.", + )) + .weak(), + ); + return None; + }; + let path = current.path.clone(); + let db = current.db.clone(); + let failed = current.failed.clone(); + let current_label = db_label(current); + let query = query_for(game, cursor); + let exclude = source.filter(|(p, _)| *p == path).map(|(_, i)| i); + if let (Some(db), Some(q)) = (&db, &query) { + self.request(ui.ctx(), &path, db, game, q, exclude); + if self.job.is_some() || self.prepare.is_some() || self.book_job.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(100)); + } + } + // The novelty (the first move of the game no other game of the database played) + // and a copy of the game in the database, once worked out. + let line = main_line(game); + let book = db + .is_some() + .then(|| self.book_for(&path, &line).cloned()) + .flatten(); + let novelty = book.as_ref().and_then(|b| match b.last { + _ if b.to_the_end || line.is_empty() => None, + Some(last) => game.main_child(last), + None => game.main_child(game.root()), + }); + let copy = book + .as_ref() + .and_then(|b| b.copies.iter().copied().find(|c| Some(*c) != exclude)); + // The first line: the database, then the novelty and the copy beside it (they + // come a moment later; on this line they take no room of their own). + ui.horizontal_wrapped(|ui| { + ui.label(tr("Database")); + // What is left of the row after the label, and the box shortens its text to + // that: in a wrapping row `available_width` is the whole row (with it a long + // name pushed the side panel out under the board). + let width = ui.available_size_before_wrap().x.min(340.0); + ui.allocate_ui(vec2(width, ui.spacing().interact_size.y), |ui| { + egui::ComboBox::from_id_salt("reference_db") + .selected_text(current_label) + .width(width) + .truncate() + .show_ui(ui, |ui| { + for d in &self.dbs { + if ui.selectable_label(d.path == path, db_label(d)).clicked() + && d.path != path + { + action = Some(RefAction::Choose(d.path.clone())); + } + } + }); + }); + if let Some(node) = novelty { + row_gap(ui, 8.0); + ui.label(RichText::new(tr("Novelty:")).weak()); + if ui + .link(node_label(game, node).unwrap_or_default()) + .on_hover_text(tr( + "The first move of this game that no other game of this database played; before it the game followed games of the database", + )) + .clicked() + { + action = Some(RefAction::Goto(node)); + } + } + if let (Some(c), Some(q)) = (copy, &query) { + row_gap(ui, 8.0); + ui.label(RichText::new(tr("This game is in the database")).weak()); + if ui + .link(tr("open it")) + .on_hover_text(tr( + "Open the copy of this game from the database at this position", + )) + .clicked() + { + action = Some(RefAction::OpenGame(path.clone(), c, q.position.clone())); + } + } + }); + if let Some(e) = &failed { + ui.add_space(8.0); + ui.label( + RichText::new(trf("This database cannot be opened: {e}", &[("e", e)])) + .color(ui.visuals().warn_fg_color), + ); + return action; + } + let Some(db) = db else { + ui.add_space(8.0); + ui.horizontal_wrapped(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(tr("Opening the database…")).weak()); + }); + return action.or(Some(RefAction::Load(path))); + }; + let Some(query) = query else { + return action; + }; + let pos = query.position.clone(); + if let Some((p, job)) = &self.prepare + && *p == path + { + let work = db.as_chessbase().map_or(1, |b| b.prepare_work()).max(1); + let pct = 100.0 * job.progress() as f32 / work as f32; + ui.horizontal_wrapped(|ui| { + ui.add(egui::Spinner::new().size(12.0)); + ui.label( + RichText::new(trf( + "Speeding up search in this database (once)… {p} %", + &[("p", &format!("{:.0}", pct.min(100.0)))], + )) + .weak(), + ) + .on_hover_text(tr( + "An index for fast position search is built once and kept in the cache. Searching works meanwhile, only slower.", + )); + }); + } + // Where we are: the position and what the game played from it. + let side = if pos.turn() == Color::White { + tr("White to move") + } else { + tr("Black to move") + }; + let mut context = match node_label(game, cursor) { + Some(m) => format!("{side} · {}", trf("after {move}", &[("move", &m)])), + None => side.to_owned(), + }; + let played = game + .main_child(cursor) + .and_then(|n| game.game_move(n)) + .and_then(|m| m.uci()) + .and_then(|u| u.parse::().ok()); + if let Some(m) = played.and_then(|u| u.to_move(&pos).ok()) { + context.push_str(&format!( + " · {}", + trf("in the game {m}", &[("m", &move_label(&pos, m))]) + )); + } + ui.label(RichText::new(context).weak()); + ui.separator(); + let current_key = key(&path, &query); + let shown = self + .shown + .as_ref() + .filter(|(k, _)| *k == current_key) + .map(|(_, o)| o.clone()); + let Some(found) = shown else { + if self.failed.as_ref() == Some(¤t_key) { + let text = match db.positions_blocked() { + Some(need) => { + let free = chess_import::memory::available().unwrap_or(0); + let missing = (need + (256 << 20)).saturating_sub(free) / 1_000_000; + trf( + "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", + &[("n", &missing.max(1))], + ) + } + None => tr("This position could not be counted").to_owned(), + }; + ui.label(RichText::new(text).color(ui.visuals().warn_fg_color)); + if ui.small_button(tr("Try again")).clicked() { + self.failed = None; + self.book_failed = None; + } + return action; + } + // A short search shows nothing at all rather than a blinking spinner. + let started = self.job.as_ref().map_or(0.0, |(_, j)| j.started); + if ui.input(|i| i.time) - started > 0.3 { + let total = db.len().max(1); + let p = self.job.as_ref().map_or(0, |(_, j)| j.progress()); + ui.horizontal_wrapped(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + let text = if p > 0 { + trf( + "Counting… {p} %", + &[("p", &format!("{:.0}", (100 * p / total).min(100)))], + ) + } else { + tr("Counting…").to_owned() + }; + ui.label(RichText::new(text).weak()); + }); + } + return action; + }; + if found.out.matches.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new(tr("This position is not in this database")).weak()); + return action; + } + // A selection belongs to its database and position. + let pos_key = query.key(); + if self + .selected + .as_ref() + .is_some_and(|(p, k, _)| *p != path || *k != pos_key) + { + self.selected = None; + } + if let Some(a) = self.moves_table(ui, &path, &pos, &found, pos_key, played) { + action = Some(a); + } + ui.add_space(4.0); + ui.separator(); + ui.add_space(4.0); + let copies = book.map(|b| b.copies).unwrap_or_default(); + if let Some(a) = self.games_table(ui, &path, &pos, &found, &copies) { + action = Some(a); + } + action + } + + /// The moves from the position: statistics, click selects, double click plays. + /// `played`: the move the game played here (marked). + fn moves_table( + &mut self, + ui: &mut Ui, + path: &Path, + pos: &Chess, + found: &Found, + pos_key: u64, + played: Option, + ) -> Option { + let out = &found.out; + let books = found.books; + let total: u32 = out.moves.iter().map(|m| m.tally.games).sum::() + out.ended.games; + let mut action = None; + let start = chess_import::position::same_position(pos, &Chess::default()); + let rows = out.moves.len() + usize::from(out.ended.games > 0); + if rows == 0 { + // The games go on with a null move (a teaching "--"), which is not a move. + ui.label(RichText::new(tr("Nothing was played here in this database")).weak()); + return None; + } + // As tall as its rows, but at most 40 % of the panel (at least 120 px of it). + let natural = 26.0 * (rows as f32 + 1.0) + 8.0; + let height = natural.min((ui.available_height() * 0.4).max(120.0)); + // Columns that give way in a narrow panel: players, year, White's score, rating, + // the result bar. Each is shown only while the table still fits the panel (in + // this order): a wider table would push the whole side panel under the board. + let width = ui.available_width(); + let gap = ui.spacing().item_spacing.x; + let mut used = 96.0 + 64.0 + 44.0 + 2.0 * gap; + let mut fits = |w: f32, wanted: bool| { + let ok = wanted && used + w + gap <= width; + if ok { + used += w + gap; + } + ok + }; + let show_bar = fits(86.0, !books); + let show_elo = fits(56.0, !books); + let show_score = fits(48.0, !books); + let show_year = fits(44.0, true); + let show_players = fits(80.0, !books); + // Text in the rows must not take the clicks meant for the row. + ui.style_mut().interaction.selectable_labels = false; + let mut table = TableBuilder::new(ui) + .id_salt("reference_moves") + .striped(true) + .sense(Sense::click()) + .max_scroll_height(height) + .min_scrolled_height(height) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + // "12…Крxe2+" and figurines are wider than Latin letters. + .column(Column::exact(96.0).clip(true)) + .column(Column::exact(64.0)) + .column(Column::exact(44.0)); + if show_bar { + table = table.column(Column::exact(86.0)); + } + if show_score { + table = table.column(Column::exact(48.0)); + } + if show_elo { + table = table.column(Column::exact(56.0)); + } + if show_year { + table = table.column(Column::exact(44.0)); + } + if show_players { + table = table.column(Column::remainder().at_least(80.0).clip(true)); + } + let selected = self + .selected + .as_ref() + .filter(|(p, k, _)| p == path && *k == pos_key) + .map(|(_, _, m)| *m); + let mut hovered = None; + let mut clicked = None; + let mut play = None; + table + .header(24.0, |mut h| { + let mut head = |text: &str, hint: &str| { + h.col(|ui| { + ui.label(RichText::new(text).strong()).on_hover_text(hint); + }); + }; + head( + tr("Move"), + tr("Click: show its games and an arrow. Double click: play the move (it is added to the game as a variation if the game has another move; Ctrl+Z undoes it)"), + ); + if books { + head(tr("Chapters"), tr("Chapters that play the move")); + } else { + head(tr("Games"), tr("Games that played the move")); + } + head("%", tr("Share of the games in this position")); + if show_bar { + head(tr("Result"), tr("White wins · draws · Black wins")); + } + if show_score { + head(tr("White"), tr("White's score")); + } + if show_elo { + head(tr("Avg Elo"), tr("Average rating, games where both are known")); + } + if show_year { + head(tr("Year"), tr("The latest game")); + } + if show_players { + head(tr("Best players"), tr("The strongest players who played the move")); + } + }) + .body(|body| { + body.rows(24.0, rows, |mut row| { + let i = row.index(); + let stat: Option<&MoveStat> = out.moves.get(i); + let tally: &Tally = stat.map_or(&out.ended, |s| &s.tally); + row.set_selected(stat.is_some_and(|s| Some(s.uci) == selected)); + let in_game = stat.is_some_and(|s| Some(s.uci) == played); + let label = match stat { + Some(s) => s + .uci + .to_move(pos) + .map(|m| move_label(pos, m)) + .unwrap_or_else(|_| crate::san::show(&s.san).into_owned()), + // In the start position "ended" are games recorded without moves. + None if start => tr("Without moves").to_owned(), + None => tr("Game over").to_owned(), + }; + row.col(|ui| { + let text = if in_game { + RichText::new(format!("â�µ {label}")).strong() + } else if stat.is_some() { + RichText::new(format!(" {label}")) + } else { + RichText::new(format!(" {label}")).weak() + }; + let r = ui.add(egui::Label::new(text).selectable(false)); + if in_game { + r.on_hover_text(tr("The move played in this game")); + } else if stat.is_none() && start { + r.on_hover_text(tr( + "Games of the database with only the players and the result, no moves", + )); + } else if stat.is_none() { + r.on_hover_text(tr( + "Games that ended in this position (resignation, draw, mate, time)", + )); + } + }); + row.col(|ui| { + ui.label(grouped(tally.games as usize)); + }); + row.col(|ui| { + let pct = 100.0 * tally.games as f32 / total.max(1) as f32; + ui.label(RichText::new(format!("{pct:.0}%")).weak()); + }); + if show_bar { + row.col(|ui| { + let (rect, _) = + ui.allocate_exact_size(vec2(78.0, 14.0), Sense::hover()); + board_search::results_bar(ui, rect, tally, ui.visuals().text_color()); + }); + } + if show_score { + row.col(|ui| { + let decided = tally.white_wins + tally.draws + tally.black_wins; + if decided > 0 { + let score = (tally.white_wins as f32 + tally.draws as f32 / 2.0) + / decided as f32; + ui.label(format!("{:.0}%", 100.0 * score)); + } + }); + } + if show_elo { + row.col(|ui| { + if let Some(avg) = tally.average_elo() { + ui.label(avg.to_string()); + } + }); + } + if show_year { + row.col(|ui| { + if tally.last_year > 0 { + ui.label(RichText::new(tally.last_year.to_string()).weak()); + } + }); + } + if show_players { + row.col(|ui| { + if let Some(p) = stat.and_then(|s| found.players.get(&s.uci)) { + ui.label(RichText::new(p).weak()); + } + }); + } + let r = row.response(); + if let Some(s) = stat { + if r.hovered() { + hovered = Some(s.uci); + } + if r.double_clicked() { + play = Some(s.uci); + } else if r.clicked() { + clicked = Some(s.uci); + } + } + }); + }); + self.hover = hovered; + if let Some(m) = clicked { + self.selected = if selected == Some(m) { + None + } else { + Some((path.to_owned(), pos_key, m)) + }; + } + if let Some(m) = play.and_then(|u| u.to_move(pos).ok()) { + self.selected = None; + action = Some(RefAction::Play(m)); + } + action + } + + /// The strongest (or newest) games that reached the position, of the selected move + /// if one is; without this game and its copies. + fn games_table( + &mut self, + ui: &mut Ui, + path: &Path, + pos: &Chess, + found: &Found, + copies: &[usize], + ) -> Option { + let selected = self + .selected + .as_ref() + .filter(|(p, _, _)| p == path) + .map(|(_, _, m)| *m); + let is_copy = |i: usize| copies.binary_search(&i).is_ok(); + // The games counted, without this game and its copies. + let (list, count): (Vec<&GameRow>, usize) = match selected { + Some(m) => { + let lists = match self.sort { + GameSort::Strongest => &found.by_move, + GameSort::Newest => &found.by_move_newest, + }; + let rows: Vec<&GameRow> = lists + .get(&m) + .map(|v| v.iter().collect()) + .unwrap_or_default(); + let n = found + .out + .moves + .iter() + .find(|s| s.uci == m) + .map_or(0, |s| s.tally.games as usize); + let own = found + .out + .matches + .iter() + .filter(|x| x.next == Some(m) && is_copy(x.index as usize)) + .count(); + (rows, n.saturating_sub(own)) + } + None => { + let rows = match self.sort { + GameSort::Strongest => &found.strongest, + GameSort::Newest => &found.newest, + }; + let own = found + .out + .matches + .iter() + .filter(|x| is_copy(x.index as usize)) + .count(); + ( + rows.iter().collect(), + found.out.matches.len().saturating_sub(own), + ) + } + }; + let rows: Vec<&GameRow> = list.into_iter().filter(|g| !is_copy(g.index)).collect(); + let mut action = None; + ui.horizontal_wrapped(|ui| { + match selected.and_then(|m| m.to_move(pos).ok()) { + Some(m) => { + ui.label( + RichText::new(trf("Games with {m}", &[("m", &move_label(pos, m))])) + .strong(), + ); + ui.label(RichText::new(format!("· {}", crate::i18n::games(count))).weak()); + if ui + .small_button("🗙") + .on_hover_text(tr("All moves")) + .clicked() + { + self.selected = None; + } + } + None if count == 0 => { + ui.label(RichText::new(tr("No other games reached this position")).weak()); + } + None => { + ui.label(RichText::new(crate::i18n::games(count)).strong()); + } + } + if count > rows.len() && !rows.is_empty() { + let text = match self.sort { + GameSort::Strongest => trf("· the {n} strongest shown", &[("n", &rows.len())]), + GameSort::Newest => trf("· the {n} newest shown", &[("n", &rows.len())]), + }; + ui.label(RichText::new(text).weak()); + } + if ui + .link(tr("all in the library âž¡")) + .on_hover_text(tr( + "Open this position on the search board of this database", + )) + .clicked() + { + action = Some(RefAction::FindInLibrary(path.to_owned())); + } + }); + if rows.is_empty() { + return action; + } + let width = ui.available_width(); + let show_event = width > 720.0; + let show_then = width > 520.0; + let show_year = width > 380.0; + // The table never gets wider than the panel: wider content pushes the whole side + // panel out to the left, under the board (a 1440-point-wide laptop screen). + let columns = 5 + usize::from(show_year) + usize::from(show_then) + usize::from(show_event); + let fixed = 3.0 * 44.0 + + if show_year { 52.0 } else { 0.0 } + + match (show_then, show_event) { + (true, true) => 150.0, + (true, false) => 80.0, + _ => 0.0, + } + + if show_event { 80.0 } else { 0.0 } + + ui.spacing().item_spacing.x * columns as f32; + let player = ((width - fixed) / 2.0).clamp(60.0, 150.0); + ui.style_mut().interaction.selectable_labels = false; + let mut table = TableBuilder::new(ui) + .id_salt("reference_games") + .striped(true) + .sense(Sense::click()) + .auto_shrink([false, false]) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::exact(player).clip(true)) + .column(Column::exact(44.0)) + .column(Column::exact(player).clip(true)) + .column(Column::exact(44.0)) + .column(Column::exact(44.0)); + if show_year { + table = table.column(Column::exact(52.0)); + } + if show_then && show_event { + table = table.column(Column::exact(150.0).clip(true)); + } else if show_then { + table = table.column(Column::remainder().at_least(80.0).clip(true)); + } + if show_event { + table = table.column(Column::remainder().at_least(80.0).clip(true)); + } + let mut hovered = None; + let mut opened = None; + let mut sort_click = None; + let sort = self.sort; + table + .header(24.0, |mut h| { + h.col(|ui| { + ui.label(RichText::new(tr("White")).strong()); + }); + h.col(|ui| { + let arrow = if sort == GameSort::Strongest { + " â�·" + } else { + "" + }; + if ui + .add( + egui::Button::new(RichText::new(format!("Elo{arrow}")).strong()) + .frame(false), + ) + .on_hover_text(tr("Strongest first")) + .clicked() + { + sort_click = Some(GameSort::Strongest); + } + }); + h.col(|ui| { + ui.label(RichText::new(tr("Black")).strong()); + }); + h.col(|ui| { + ui.label(RichText::new("Elo").strong()); + }); + h.col(|ui| { + ui.label(RichText::new(tr("Res.")).strong()); + }); + if show_year { + h.col(|ui| { + let arrow = if sort == GameSort::Newest { " â�·" } else { "" }; + if ui + .add( + egui::Button::new( + RichText::new(format!("{}{arrow}", tr("Year"))).strong(), + ) + .frame(false), + ) + .on_hover_text(tr("Newest first")) + .clicked() + { + sort_click = Some(GameSort::Newest); + } + }); + } + if show_then { + h.col(|ui| { + ui.label(RichText::new(tr("Then")).strong()) + .on_hover_text(tr("How the game went on from this position")); + }); + } + if show_event { + h.col(|ui| { + ui.label(RichText::new(tr("Event")).strong()); + }); + } + }) + .body(|body| { + body.rows(24.0, rows.len(), |mut row| { + let g = rows[row.index()]; + let elo = |e: u16| if e > 0 { e.to_string() } else { String::new() }; + row.col(|ui| { + ui.label(&g.white); + }); + row.col(|ui| { + ui.label(RichText::new(elo(g.white_elo)).weak()); + }); + row.col(|ui| { + ui.label(&g.black); + }); + row.col(|ui| { + ui.label(RichText::new(elo(g.black_elo)).weak()); + }); + row.col(|ui| { + ui.label(if g.result == "1/2-1/2" { + "½-½" + } else { + g.result.as_str() + }); + }); + if show_year { + row.col(|ui| { + if g.year > 0 { + ui.label(RichText::new(g.year.to_string()).weak()); + } + }); + } + if show_then { + row.col(|ui| { + ui.label(crate::san::show_line(&g.then)); + }); + } + if show_event { + row.col(|ui| { + ui.label(RichText::new(&g.event).italics().weak()); + }); + } + let r = row + .response() + .on_hover_text(tr("Double click: open this game at this position")); + if r.hovered() { + hovered = g.next; + } + if r.double_clicked() { + opened = Some(g.index); + } + }); + }); + if let Some(s) = sort_click { + self.sort = s; + } + if hovered.is_some() { + self.hover = hovered; + } + if let Some(i) = opened { + action = Some(RefAction::OpenGame(path.to_owned(), i, pos.clone())); + } + action + } +} + +/// A gap between items of a wrapping row, only where the row goes on: at the end of a +/// full row a plain `add_space` does not wrap but sticks out of the panel. +fn row_gap(ui: &mut Ui, gap: f32) { + if ui.available_size_before_wrap().x > gap + ui.spacing().item_spacing.x { + ui.add_space(gap); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn surnames() { + assert_eq!(surname("Carlsen, Magnus"), "Carlsen"); + assert_eq!(surname("Alekhine Alexander (RUS)"), "Alekhine"); + assert_eq!(surname("Kasparov"), "Kasparov"); + assert_eq!( + surname("Duke Karl / Count Isouard"), + surname("Duke of Brunswick, Count") + ); + assert_eq!(surname("?"), ""); + assert_eq!(surname("NN"), ""); + } + + #[test] + fn best_of_many() { + let v: Vec = (0..1000).collect(); + let top = best(v, 5, |x| (*x % 97, *x)); + assert_eq!(top.len(), 5); + assert!(top.iter().all(|x| x % 97 == 96)); + assert!(top.windows(2).all(|w| w[0] > w[1])); + } + + fn classics() -> Arc { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/classics.pgn"); + let db = chess_core::PgnDatabase::open(&path, &mut |_| {}, &AtomicBool::new(false)) + .expect("opens"); + Arc::new(Database::Pgn(chess_import::PgnDb::new(db))) + } + + /// The tables of a small database: every listed game reaches the position, the + /// games of a move played it, strongest first, and "then" starts with that move. + #[test] + fn tables_of_the_classics() { + let db = classics(); + let mut pos = Chess::default(); + let e4: Move = "e2e4".parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(e4); + let q = PositionQuery::new(pos.clone(), Some(vec![e4])); + let out = db + .search_position(None, &q, &Default::default(), &Default::default()) + .expect("searches"); + let n = out.matches.len(); + let found = tables(&db, &pos, out, &AtomicBool::new(false)).expect("not cancelled"); + assert_eq!(found.strongest.len(), n.min(GAMES_SHOWN)); + for w in found.strongest.windows(2) { + assert!((w[0].average(), w[0].year) >= (w[1].average(), w[1].year)); + } + for w in found.newest.windows(2) { + assert!(w[0].year >= w[1].year); + } + for (m, rows) in &found.by_move { + let first = move_label(&pos, m.to_move(&pos).unwrap()); + let stat = found.out.moves.iter().find(|s| s.uci == *m).unwrap(); + assert_eq!(rows.len(), (stat.tally.games as usize).min(GAMES_PER_MOVE)); + for r in rows { + assert_eq!(r.next, Some(*m)); + assert!(r.then.starts_with(&first), "{} vs {first}", r.then); + } + } + } + + /// Theory and copies: a game of the database against the same database. + #[test] + fn book_of_a_game_of_the_database() { + let db = classics(); + let parsed = db.load_game(0).expect("game"); + let never = AtomicBool::new(false); + // The game itself excluded, nothing else is the same game. + let end = book_end(&db, &parsed.game, Some(0), 0, &never).expect("theory"); + assert_eq!(end.copies, vec![0]); + assert!(!end.to_the_end); + // Not excluded: the game is its own copy (same players, year, final position). + let end = book_end(&db, &parsed.game, None, 0, &never).expect("theory"); + assert_eq!(end.copies, vec![0]); + // An empty game has no theory and no copies. + let empty = Game::new(); + let end = book_end(&db, &empty, None, 0, &never).expect("theory"); + assert!(end.copies.is_empty() && !end.to_the_end); + } +} diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs new file mode 100644 index 0000000..ff6dac8 --- /dev/null +++ b/apps/desktop/src/repertoire_ui.rs @@ -0,0 +1,3349 @@ +//! Opening training (docs/design/opening-trainer-v2-spec.md): the «Repertoires» screen +//! with its card and dialogs, and the way to the «Session» and «Lines» screens. + +use std::collections::{BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicU64, Ordering}, + mpsc::{self, Receiver, Sender}, +}; +use std::time::Duration; + +use chess_core::shakmaty::{Chess, Color, Position, Square}; +use chess_core::{Game, NodeId, PgnDatabase, Severity}; +use egui::{Color32, Key, Modifiers, RichText, Ui, vec2}; +use trainer::repertoire::{ + LearningData, LearningItemKey, LearningSide, LearningStore, LearningStoreData, Library, + LibraryStore, MergeReport, RepertoireId, ResetImpactProjection, SrsSettings, StatsScope, + StoreError, active_learning_keys, aggregate_scope, fen4, reset_impact, +}; +use web_time::Instant; + +use crate::board::BoardState; +use crate::i18n::{tr, trf}; +use crate::opening_layout::{self as layout, BoardAnnotations, GAP, NEW_PER_SESSION}; +use crate::opening_lines::{LinesAction, OpeningLinesUi}; +use crate::opening_session::{ + OpeningSessionUi, PreparingView, SessionAction, SessionKind, show_preparing, +}; +use crate::settings::Settings; + +pub enum RepertoireAction { + Close, + OpenSettings, + Sound(crate::assets::Sound), + #[allow(dead_code)] + Toast(String), + SettingsChanged, + Added { + id: RepertoireId, + name: String, + report: MergeReport, + }, +} + +const CARD_H: f32 = 168.0; +const BUTTON_ROW_H: f32 = 30.0; +const ROW_H: f32 = 24.0; +const HEADER_H: f32 = 26.0; +const MESSAGE_H: f32 = 20.0; +const BOTTOM_H: f32 = 30.0; +const BOTTOM_W: f32 = 150.0; +const MAIN_W: f32 = 170.0; +const LINES_W: f32 = 110.0; +const THIRD_W: f32 = 150.0; +/// The bar in the «Passed» column, left of «A/Y». +const MINI_BAR_W: f32 = 44.0; +/// The bar of a narrow panel (under `NARROW_TABLE`) whose name would keep under +/// `NAME_WANTED`. +const MINI_BAR_NARROW: f32 = 28.0; +const NARROW_TABLE: f32 = 420.0 - 16.0; +const NAME_WANTED: f32 = 60.0; +/// The room kept for the number of «Passed». +const NUMBER_SAMPLE: &str = "00/000"; +const MINI_BAR_GAP: f32 = 6.0; +/// The name keeps up to this much; only it is ever cut, down to `NAME_FLOOR`. +const NAME_LEAST: f32 = 120.0; +const NAME_FLOOR: f32 = 30.0; +/// Space from «Today» to the «Passed» bar, the columns' own gap included: the bar +/// never reads as part of «Today». +const PASSED_GAP: f32 = 16.0; +/// The fixed columns besides «Today» and «Passed»: the colour and `⋯`. +const KING_W: f32 = 22.0; +const MENU_W: f32 = 26.0; +const DIALOG_W: f32 = 460.0; +/// A session appears at once when it is ready this fast; otherwise «Preparing…». +const PREPARING_SHOWN_AFTER: Duration = Duration::from_millis(300); +const MESSAGE_SHOWN: Duration = Duration::from_secs(6); +/// Seconds per question in «About {t} min». +const SECONDS_PER_MOVE: usize = 20; +const WARNING_ROWS: usize = 3; +static NEXT_JOB: AtomicU64 = AtomicU64::new(1); + +/// What the table and the board need of a repertoire, from its PGN (indexed off the +/// frame). +#[derive(Clone)] +struct RowIndex { + start: Chess, + /// The position a session starts from (S0 shows it, not the library's preview). + initial: Chess, + last_move: Option<(Square, Square)>, + has_moves: bool, +} + +/// The counts of a repertoire for its colour, "today" meaning until the end of the day. +#[derive(Clone, Debug, Default, PartialEq)] +struct RowStats { + total: usize, + due: usize, + unseen: usize, + learning: usize, + learnt: usize, + /// The next review after today and how many moves are due that day. + next: Option<(i64, usize)>, +} + +impl RowStats { + /// Moves met in training at least once: learning and learned. + fn passed(&self) -> usize { + self.learning + self.learnt + } + + fn new_today(&self) -> usize { + self.unseen.min(NEW_PER_SESSION) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct StatsKey { + library_revision: u64, + learning_revision: u64, + sides: Vec<(RepertoireId, LearningSide)>, + day: i64, +} + +/// The card's states (spec §3). +#[derive(Clone, Debug, PartialEq)] +enum CardState { + Review { due: usize, new: usize }, + OnlyNew { new: usize }, + Done { next: Option<(i64, usize)> }, + Empty, + OtherColor, + Counting, + Failed(String), +} + +fn card_state(has_moves: Option, stats: Option<&Result>) -> CardState { + match stats { + None => CardState::Counting, + Some(Err(error)) => CardState::Failed(error.clone()), + Some(Ok(stats)) if stats.total == 0 => { + if has_moves == Some(true) { + CardState::OtherColor + } else { + CardState::Empty + } + } + Some(Ok(stats)) if stats.due > 0 => CardState::Review { + due: stats.due, + new: stats.new_today(), + }, + Some(Ok(stats)) if stats.unseen > 0 => CardState::OnlyNew { + new: stats.new_today(), + }, + Some(Ok(stats)) => CardState::Done { next: stats.next }, + } +} + +/// A PGN read for «Import PGN» or «Add PGN to this repertoire». +struct ImportPreview { + library: Library, + id: RepertoireId, + base_revision: u64, + games: usize, + /// Lines of the result, and before the merge (an added file). + lines: usize, + lines_before: usize, + /// Own moves for White and for Black. + own: [usize; 2], + suggested: LearningSide, + default_name: String, + warnings: Vec, + report: MergeReport, +} + +impl ImportPreview { + fn own(&self, side: LearningSide) -> usize { + match side { + LearningSide::White => self.own[0], + LearningSide::Black => self.own[1], + } + } +} + +struct ImportDialog { + job: u64, + /// `None`: a new repertoire. + target: Option, + preview: Option, + name: String, + side: LearningSide, + error: Option, + cancel: Arc, +} + +enum Dialog { + Import(ImportDialog), + New { + name: String, + side: LearningSide, + error: Option, + }, + Rename { + id: RepertoireId, + name: String, + error: Option, + select_all: bool, + }, + Color { + id: RepertoireId, + to: LearningSide, + job: u64, + count: Option, + }, + Reset { + id: RepertoireId, + job: u64, + impact: Option<(ResetImpactProjection, BTreeSet)>, + busy: bool, + }, + Delete { + id: RepertoireId, + }, +} + +enum Screen { + Repertoires, + Session(Box), + Lines(Box), +} + +struct Preparing { + job: u64, + since: Instant, + id: RepertoireId, + name: String, + kind: SessionKind, +} + +struct Message { + text: String, + error: bool, + until: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MenuItem { + Train, + ReviewAll, + Lines, + Rename, + SwitchColor, + AddPgn, + Export, + Reset, + Delete, +} + +enum Event { + Indexed(u64, HashMap), + Stats(StatsKey, HashMap>), + Imported(u64, Result), + Exported(Result, String>), + SessionReady(u64, Result, String>), + LinesReady(u64, Option>), + LearningLoaded(Result), + OtherSide(u64, Result), + ResetImpact( + u64, + Result<(ResetImpactProjection, BTreeSet), String>, + ), + ResetDone(u64, Result), +} + +struct AddFromGame { + source: Game, + at: NodeId, + selected: Option, + name: String, + side: LearningSide, +} + +pub struct RepertoireUi { + library_store: LibraryStore, + learning_store: LearningStore, + library: Library, + learning: LearningStoreData, + library_error: Option, + learning_error: Option, + selected: Option, + index: HashMap, + index_job: u64, + stats: HashMap>, + stats_key: Option, + /// The key of the counts shown (older than `stats_key` while counting). + stats_shown: Option, + screen: Screen, + /// The «Lines» screen a branch session was started from. + lines_return: Option>, + preparing: Option, + lines_job: Option, + /// The answers are being read again after a session. + learning_loading: bool, + dialog: Option, + message: Option, + search: String, + scroll_to_selected: bool, + return_to_game: Option, + add: Option, + board: BoardState, + tx: Sender, + rx: Receiver, + initial_selection_pending: bool, + debug_start: Option, + debug_pending_moves: Option, + debug_menu: bool, + /// Colours of the starter repertoires created on the first opening, written to the + /// settings by the next `show`. + starter_sides: Vec<(RepertoireId, LearningSide)>, +} + +impl RepertoireUi { + pub fn new() -> Self { + let (library_store, learning_store) = stores(); + let starter = seed_starter(&library_store); + let mut this = Self::with_stores(library_store, learning_store); + match starter { + Ok(sides) => this.starter_sides = sides, + Err(error) => this.show_message(error, true), + } + this + } + + fn with_stores(library_store: LibraryStore, learning_store: LearningStore) -> Self { + let (library, library_error) = match load_library(&library_store) { + Ok(data) => (data, None), + Err(error) => (Library::default(), Some(error)), + }; + let (learning, learning_error) = match learning_store.load() { + Ok(data) => (data, None), + Err(error) => (LearningStoreData::default(), Some(error.to_string())), + }; + let (tx, rx) = mpsc::channel(); + let mut this = Self { + library_store, + learning_store, + library, + learning, + library_error, + learning_error, + selected: None, + index: HashMap::new(), + index_job: 0, + stats: HashMap::new(), + stats_key: None, + stats_shown: None, + screen: Screen::Repertoires, + lines_return: None, + preparing: None, + lines_job: None, + learning_loading: false, + dialog: None, + message: None, + search: String::new(), + scroll_to_selected: true, + return_to_game: None, + add: None, + board: BoardState::default(), + tx, + rx, + initial_selection_pending: true, + debug_start: None, + debug_pending_moves: None, + debug_menu: false, + starter_sides: Vec::new(), + }; + this.selected = this.sorted_ids().first().cloned(); + this.reindex(); + this + } + + pub fn has_unsaved(&self) -> bool { + match &self.screen { + Screen::Session(session) => session.has_unsaved(), + Screen::Repertoires | Screen::Lines(_) => false, + } + } + + /// The window is being closed with an answer not saved: show the session. + pub fn resolve_unsaved(&mut self) {} + + pub fn open_library(&mut self) { + self.scroll_to_selected = true; + if !matches!(self.screen, Screen::Session(_)) { + self.screen = Screen::Repertoires; + } + } + + pub fn open_from_toast(&mut self, id: RepertoireId, title: String, _settings: &Settings) { + self.return_to_game = Some(title); + self.select(id); + } + + pub fn open_add_from_game(&mut self, source: Game, at: NodeId, title: String) { + self.return_to_game = Some(title); + let start = fen4(source.start().position()); + let selected = self + .library + .repertoires + .iter() + .find(|r| fen4(r.game().start().position()) == start) + .map(|r| r.id.clone()); + // The colour of the move chosen in the game. + let side = match source.position_before(at).map(|p| p.turn()) { + Some(Color::Black) => LearningSide::Black, + _ => LearningSide::White, + }; + self.add = Some(AddFromGame { + source, + at, + selected, + name: String::new(), + side, + }); + } + + fn sorted_ids(&self) -> Vec { + let mut rows: Vec<_> = self + .library + .repertoires + .iter() + .map(|r| (r.name.to_lowercase(), r.id.clone())) + .collect(); + rows.sort(); + rows.into_iter().map(|(_, id)| id).collect() + } + + fn select(&mut self, id: RepertoireId) { + self.initial_selection_pending = false; + if self.library.repertoire(&id).is_some() { + self.selected = Some(id); + self.scroll_to_selected = true; + } + } + + fn selected_name(&self) -> String { + self.selected + .as_ref() + .and_then(|id| self.library.repertoire(id)) + .map(|r| r.name.clone()) + .unwrap_or_default() + } + + fn show_message(&mut self, text: impl Into, error: bool) { + self.message = Some(Message { + text: text.into(), + error, + until: (!error).then(|| Instant::now() + MESSAGE_SHOWN), + }); + } + + fn reindex(&mut self) { + self.index_job = next_job(); + let job = self.index_job; + let repertoires = self.library.repertoires.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-index", move || { + let index = repertoires + .into_iter() + .map(|r| { + let game = r.game(); + let start = layout::common_start(&game); + ( + r.id.clone(), + RowIndex { + start: layout::position_of(&game, start), + initial: layout::position_of(&game, NodeId::ROOT), + last_move: layout::last_move(&game, start), + has_moves: !game.children(NodeId::ROOT).is_empty(), + }, + ) + }) + .collect(); + let _ = tx.send(Event::Indexed(job, index)); + }) { + self.show_message(error.to_string(), true); + } + } + + fn sides(&self, settings: &Settings) -> Vec<(RepertoireId, LearningSide)> { + self.sorted_ids() + .into_iter() + .map(|id| { + let side = layout::side_of(settings, &id); + (id, side) + }) + .collect() + } + + /// Recount in the background when the library, the answers, a colour or the day + /// changed; the previous numbers stay meanwhile. + fn request_stats(&mut self, settings: &Settings) { + if self.library_error.is_some() || self.learning_error.is_some() { + return; + } + let today = layout::end_of_today(); + let key = StatsKey { + library_revision: self.library.revision, + learning_revision: self.learning.revision, + sides: self.sides(settings), + day: today, + }; + if self.stats_key.as_ref() == Some(&key) { + return; + } + self.stats_key = Some(key.clone()); + let library = self.library.clone(); + let learning = self.learning.learning.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-stats", move || { + let stats = key + .sides + .iter() + .map(|(id, side)| (id.clone(), row_stats(&library, &learning, id, *side, today))) + .collect(); + let _ = tx.send(Event::Stats(key, stats)); + }) { + self.show_message(error.to_string(), true); + } + } + + fn reload_learning(&mut self) { + self.learning_loading = true; + let store = self.learning_store.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-learning-load", move || { + let _ = tx.send(Event::LearningLoaded( + store.load().map_err(|error| error.to_string()), + )); + }) { + self.learning_loading = false; + self.show_message(error.to_string(), true); + } + } + + /// Writes the library; on success it is the one shown. + fn persist(&mut self, mut library: Library) -> bool { + if self.library_error.is_some() { + return false; + } + match self.library_store.save(&mut library) { + Ok(()) => { + self.library = library; + self.reindex(); + true + } + Err(error) => { + self.show_message( + trf("Could not save: {e}", &[("e", &error.to_string())]), + true, + ); + false + } + } + } + + fn checked_name(&self, name: &str, excluding: Option<&RepertoireId>) -> Result { + let name = name.split_whitespace().collect::>().join(" "); + if name.is_empty() { + return Err(tr("The repertoire name must not be empty").to_owned()); + } + if name.chars().count() > 120 { + return Err(tr("The repertoire name is longer than 120 characters").to_owned()); + } + if self.library.repertoires.iter().any(|r| { + Some(&r.id) != excluding + && r.name + .split_whitespace() + .collect::>() + .join(" ") + .to_lowercase() + == name.to_lowercase() + }) { + return Err(tr("A repertoire with this name already exists").to_owned()); + } + Ok(name) + } + + fn start(&mut self, kind: SessionKind, settings: &Settings) { + if self.preparing.is_some() || self.has_unsaved() { + return; + } + let Some(id) = self.selected.clone() else { + return; + }; + let name = self.selected_name(); + let side = layout::side_of(settings, &id); + let scope = StatsScope::for_repertoire(id.clone(), side, layout::end_of_today()); + let library = self.library.clone(); + let store = self.learning_store.clone(); + let job = next_job(); + let tx = self.tx.clone(); + let session_kind = kind.clone(); + let slow = debug_slow(); + if let Err(error) = crate::platform::spawn("repertoire-session-start", move || { + if let Some(slow) = slow { + std::thread::sleep(slow); + } + let result = OpeningSessionUi::new(library, store, scope, session_kind).map(Box::new); + let _ = tx.send(Event::SessionReady(job, result)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.preparing = Some(Preparing { + job, + since: Instant::now(), + id, + name, + kind, + }); + } + + fn more_new(&mut self) { + let Screen::Session(session) = &self.screen else { + return; + }; + let Some(id) = self.selected.clone() else { + return; + }; + let snapshot = session.snapshot().clone(); + let orientation = session.orientation(); + let library = self.library.clone(); + let store = self.learning_store.clone(); + let job = next_job(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-session-more", move || { + let result = + OpeningSessionUi::more_new(library, store, snapshot, orientation).map(Box::new); + let _ = tx.send(Event::SessionReady(job, result)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.preparing = Some(Preparing { + job, + since: Instant::now(), + id, + name: self.selected_name(), + kind: SessionKind::Daily, + }); + } + + fn open_lines(&mut self, settings: &Settings, cursor: Option>) { + let Some(id) = self.selected.clone() else { + return; + }; + let side = layout::side_of(settings, &id); + let library = self.library.clone(); + let learning = self.learning.learning.clone(); + let job = next_job(); + self.lines_job = Some(job); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-lines", move || { + let lines = OpeningLinesUi::new(&library, &learning, id, side, cursor).map(Box::new); + let _ = tx.send(Event::LinesReady(job, lines)); + }) { + self.lines_job = None; + self.show_message(error.to_string(), true); + } + } + + fn pick_import(&mut self, target: Option, ctx: &egui::Context) { + let job = next_job(); + let cancel = Arc::new(AtomicBool::new(false)); + let base = self.library.clone(); + let tx = self.tx.clone(); + let ctx = ctx.clone(); + let worker_cancel = cancel.clone(); + let worker_target = target.clone(); + if let Err(error) = crate::platform::spawn("repertoire-import-dialog", move || { + let picked = rfd::FileDialog::new() + .add_filter("PGN", &["pgn", "PGN"]) + .pick_file(); + let Some(path) = picked else { + let _ = tx.send(Event::Imported(job, Err(String::new()))); + ctx.request_repaint(); + return; + }; + let _ = tx.send(Event::Imported( + job, + read_import(&path, worker_target, base, &worker_cancel), + )); + ctx.request_repaint(); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Import(ImportDialog { + job, + target, + preview: None, + name: String::new(), + side: LearningSide::White, + error: None, + cancel, + })); + } + + fn import_path(&mut self, path: PathBuf, target: Option) { + let job = next_job(); + let cancel = Arc::new(AtomicBool::new(false)); + let base = self.library.clone(); + let tx = self.tx.clone(); + let worker_cancel = cancel.clone(); + let worker_target = target.clone(); + if let Err(error) = crate::platform::spawn("repertoire-import", move || { + let _ = tx.send(Event::Imported( + job, + read_import(&path, worker_target, base, &worker_cancel), + )); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Import(ImportDialog { + job, + target, + preview: None, + name: String::new(), + side: LearningSide::White, + error: None, + cancel, + })); + } + + /// Imports what the dialog shows. Returns whether it was saved. + fn confirm_import(&mut self, settings: &mut Settings) -> bool { + let Some(Dialog::Import(dialog)) = &self.dialog else { + return false; + }; + let Some(preview) = &dialog.preview else { + return false; + }; + if preview.base_revision != self.library.revision { + let error = tr("The library changed; import the PGN again").to_owned(); + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error); + } + return false; + } + let mut library = preview.library.clone(); + let id = preview.id.clone(); + let target = dialog.target.clone(); + let side = dialog.side; + if target.is_none() { + match self.checked_name(&dialog.name, None) { + Ok(name) => { + if let Err(error) = library.rename(&id, name) { + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error.to_string()); + } + return false; + } + } + Err(error) => { + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error); + } + return false; + } + } + } + if !self.persist(library) { + return false; + } + if target.is_none() { + layout::set_side(settings, &id, side); + } + self.dialog = None; + self.select(id); + true + } + + fn export(&mut self, ctx: Option) { + let Some(r) = self + .selected + .as_ref() + .and_then(|id| self.library.repertoire(id)) + else { + return; + }; + let pgn = r.pgn.clone(); + let name = format!("{}.pgn", r.name.replace(['/', '\\'], "_")); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-export", move || { + let path = std::env::var_os("CP_REPERTOIRE_EXPORT_FILE") + .map(PathBuf::from) + .or_else(|| { + rfd::FileDialog::new() + .set_file_name(name) + .add_filter("PGN", &["pgn"]) + .save_file() + }); + let result = match path { + Some(path) => chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) + .map(|()| Some(path)) + .map_err(|error| error.to_string()), + None => Ok(None), + }; + let _ = tx.send(Event::Exported(result)); + if let Some(ctx) = ctx { + ctx.request_repaint(); + } + }) { + self.show_message(error.to_string(), true); + } + } + + fn open_color_dialog(&mut self, settings: &Settings) { + let Some(id) = self.selected.clone() else { + return; + }; + let to = match layout::side_of(settings, &id) { + LearningSide::White => LearningSide::Black, + LearningSide::Black => LearningSide::White, + }; + let job = next_job(); + let library = self.library.clone(); + let tx = self.tx.clone(); + let scope = StatsScope::for_repertoire(id.clone(), to, layout::now()); + if let Err(error) = crate::platform::spawn("repertoire-other-side", move || { + let count = active_learning_keys(&library, &scope) + .map(|keys| keys.len()) + .map_err(|error| error.to_string()); + let _ = tx.send(Event::OtherSide(job, count)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Color { + id, + to, + job, + count: None, + }); + } + + fn open_reset_dialog(&mut self, settings: &Settings) { + let Some(id) = self.selected.clone() else { + return; + }; + let scope = + StatsScope::for_repertoire(id.clone(), layout::side_of(settings, &id), layout::now()); + let job = next_job(); + let library = self.library.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-reset-impact", move || { + let result = reset_impact(&library, &scope) + .and_then(|impact| { + active_learning_keys(&library, &scope).map(|keys| (impact, keys)) + }) + .map_err(|error| error.to_string()); + let _ = tx.send(Event::ResetImpact(job, result)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Reset { + id, + job, + impact: None, + busy: false, + }); + } + + fn confirm_reset(&mut self) { + let Some(Dialog::Reset { + job, + impact: Some((_, keys)), + busy, + .. + }) = &mut self.dialog + else { + return; + }; + if *busy { + return; + } + *busy = true; + let job = *job; + let keys = keys.clone(); + let store = self.learning_store.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-reset", move || { + let result = store + .reset_learning(keys) + .map_err(|error| error.to_string()) + .and_then(|_| store.load().map_err(|error| error.to_string())); + let _ = tx.send(Event::ResetDone(job, result)); + }) { + self.dialog = None; + self.show_message(error.to_string(), true); + } + } + + fn delete_selected(&mut self) { + let Some(Dialog::Delete { id }) = &self.dialog else { + return; + }; + let id = id.clone(); + let order = self.sorted_ids(); + let position = order.iter().position(|other| *other == id); + let mut library = self.library.clone(); + if let Err(error) = library.delete(&id) { + self.show_message(error.to_string(), true); + return; + } + if !self.persist(library) { + return; + } + self.dialog = None; + let order = self.sorted_ids(); + self.selected = position + .and_then(|position| order.get(position.min(order.len().saturating_sub(1)))) + .cloned(); + self.scroll_to_selected = true; + } + + fn poll(&mut self, settings: &mut Settings) { + if self.initial_selection_pending { + self.initial_selection_pending = false; + } + while let Ok(event) = self.rx.try_recv() { + match event { + Event::Indexed(job, index) => { + if job == self.index_job { + self.index = index; + } + } + Event::Stats(key, stats) => { + if self.stats_key.as_ref() == Some(&key) { + self.stats = stats; + self.stats_shown = Some(key); + } + } + Event::Imported(job, result) => { + let Some(Dialog::Import(dialog)) = &mut self.dialog else { + continue; + }; + if dialog.job != job { + continue; + } + match result { + Ok(preview) => { + dialog.name = preview.default_name.clone(); + dialog.side = preview.suggested; + if let Some(target) = &dialog.target { + dialog.side = layout::side_of(settings, target); + } + dialog.preview = Some(preview); + } + // The file chooser was closed. + Err(error) if error.is_empty() => self.dialog = None, + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + Event::Exported(Ok(Some(path))) => { + self.show_message(trf("Saved to {path}", &[("path", &path.display())]), false) + } + Event::Exported(Ok(None)) => {} + Event::Exported(Err(error)) => { + self.show_message(trf("Could not save: {e}", &[("e", &error)]), true) + } + Event::SessionReady(job, result) => { + if self.preparing.as_ref().is_none_or(|p| p.job != job) { + continue; + } + self.preparing = None; + match result { + Ok(mut session) if session.target_available() => { + if let Screen::Lines(lines) = + std::mem::replace(&mut self.screen, Screen::Repertoires) + { + self.lines_return = Some(lines); + } + session.set_back_to_lines(self.lines_return.is_some()); + self.screen = Screen::Session(session); + if let Some(moves) = self.debug_pending_moves.take() { + self.debug_moves(&moves); + } + } + Ok(_) => { + self.screen_back_from_session(); + self.show_message(tr("Nothing to train here right now"), false); + } + Err(error) => { + self.screen_back_from_session(); + self.show_message(error, true); + } + } + } + Event::LinesReady(job, lines) => { + if self.lines_job != Some(job) { + continue; + } + self.lines_job = None; + if let Some(mut lines) = lines { + if let Ok(path) = std::env::var("CP_REPERTOIRE_LINE") { + let path: Vec = + path.split_whitespace().map(str::to_owned).collect(); + lines.debug_select(&path); + } + self.screen = Screen::Lines(lines); + } + } + Event::LearningLoaded(Ok(data)) => { + self.learning_loading = false; + self.learning = data; + self.learning_error = None; + } + Event::LearningLoaded(Err(error)) => { + self.learning_loading = false; + self.learning_error = Some(error); + } + Event::OtherSide(job, result) => { + if let Some(Dialog::Color { + job: expected, + count, + .. + }) = &mut self.dialog + && *expected == job + { + match result { + Ok(value) => *count = Some(value), + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + } + Event::ResetImpact(job, result) => { + if let Some(Dialog::Reset { + job: expected, + impact, + .. + }) = &mut self.dialog + && *expected == job + { + match result { + Ok(value) => *impact = Some(value), + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + } + Event::ResetDone(job, result) => { + if !matches!(&self.dialog, Some(Dialog::Reset { job: expected, .. }) if *expected == job) + { + continue; + } + self.dialog = None; + match result { + Ok(data) => { + self.learning = data; + self.learning_error = None; + } + Err(error) => self.show_message(error, true), + } + } + } + } + if std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some() + && matches!(&self.dialog, Some(Dialog::Import(d)) if d.preview.is_some()) + { + self.confirm_import(settings); + } + if let Some(message) = &self.message + && message.until.is_some_and(|until| Instant::now() >= until) + { + self.message = None; + } + if self.preparing.is_none() + && self.dialog.is_none() + && let Some(what) = self.debug_start.take() + { + self.debug_open(&what, settings); + } + self.request_stats(settings); + } + + fn screen_back_from_session(&mut self) { + self.screen = match self.lines_return.take() { + Some(lines) => Screen::Lines(lines), + None if matches!(self.screen, Screen::Lines(_)) => { + std::mem::replace(&mut self.screen, Screen::Repertoires) + } + None => Screen::Repertoires, + }; + } + + pub fn show(&mut self, ui: &mut Ui, settings: &mut Settings) -> Vec { + self.poll(settings); + let mut actions = Vec::new(); + if !self.starter_sides.is_empty() { + for (id, side) in self.starter_sides.drain(..) { + layout::set_side(settings, &id, side); + } + actions.push(RepertoireAction::SettingsChanged); + } + let available = ui.available_rect_before_wrap(); + let background = ui.visuals().window_fill(); + ui.painter_at(available) + .rect_filled(available, 0.0, background); + if self.preparing.is_some() || self.lines_job.is_some() { + ui.ctx().request_repaint_after(Duration::from_millis(50)); + } + if let Some(preparing) = &self.preparing + && preparing.since.elapsed() >= PREPARING_SHOWN_AFTER + { + let side = layout::side_of(settings, &preparing.id); + let index = self.index.get(&preparing.id); + let start = index.map(|row| row.initial.clone()).unwrap_or_default(); + let subtitle = preparing.kind.subtitle(side); + let view = PreparingView { + name: &preparing.name, + subtitle: &subtitle, + back: if matches!(self.screen, Screen::Lines(_)) { + tr("⬅ Lines") + } else { + tr("⬅ Repertoires") + }, + position: &start, + orientation: layout::orientation(side), + last_move: None, + lines: preparing.kind != SessionKind::Daily, + }; + for action in show_preparing(ui, settings, &mut self.board, &view) { + match action { + SessionAction::Back => { + self.preparing = None; + self.screen_back_from_session(); + } + SessionAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + SessionAction::Sound(_) | SessionAction::MoreNew => {} + } + } + return actions; + } + match std::mem::replace(&mut self.screen, Screen::Repertoires) { + Screen::Session(mut session) => { + let name = self.selected_name(); + let emitted = session.show(ui, settings, &name); + self.screen = Screen::Session(session); + for action in emitted { + match action { + SessionAction::Back => { + self.reload_learning(); + self.screen_back_from_session(); + if let Screen::Lines(lines) = &mut self.screen { + lines.refresh(&self.library, &self.learning.learning); + } + self.scroll_to_selected = true; + } + SessionAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + SessionAction::Sound(sound) => actions.push(RepertoireAction::Sound(sound)), + SessionAction::MoreNew => self.more_new(), + } + } + return actions; + } + Screen::Lines(mut lines) => { + let emitted = lines.show(ui, settings); + self.screen = Screen::Lines(lines); + for action in emitted { + self.lines_action(action, settings, &mut actions); + } + return actions; + } + Screen::Repertoires => {} + } + self.repertoires_screen(ui, settings, &mut actions); + self.show_dialog(ui.ctx(), settings, &mut actions); + self.show_add(ui, settings, &mut actions); + actions + } + + fn lines_action( + &mut self, + action: LinesAction, + settings: &mut Settings, + actions: &mut Vec, + ) { + match action { + LinesAction::Back => { + self.screen = Screen::Repertoires; + self.scroll_to_selected = true; + } + LinesAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + LinesAction::Train { through, label } => { + let kind = if through.is_empty() { + SessionKind::ReviewAll + } else { + SessionKind::Branch { through, label } + }; + self.start(kind, settings); + } + LinesAction::SetDisabled { path, disabled } => { + let Screen::Lines(lines) = &self.screen else { + return; + }; + let id = lines.id().clone(); + let mut library = self.library.clone(); + let Some(repertoire) = library.repertoire_mut(&id) else { + return; + }; + if let Err(error) = repertoire.set_prefix_disabled(&path, disabled) { + self.show_message(error.to_string(), true); + return; + } + if self.persist(library) + && let Screen::Lines(lines) = &mut self.screen + { + lines.refresh(&self.library, &self.learning.learning); + } + } + } + } + + fn keyboard(&mut self, ui: &Ui, settings: &mut Settings, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() + || crate::app::overlay_open(ui.ctx()) + || self.dialog.is_some() + || self.add.is_some() + { + return; + } + let mut command = None; + ui.input_mut(|input| { + if input.consume_key(Modifiers::NONE, Key::Escape) { + command = Some("close"); + } else if input.consume_key(Modifiers::NONE, Key::ArrowDown) { + command = Some("down"); + } else if input.consume_key(Modifiers::NONE, Key::ArrowUp) { + command = Some("up"); + } else if input.consume_key(Modifiers::NONE, Key::Enter) { + command = Some("main"); + } + }); + let rows = self.visible_ids(); + let current = self + .selected + .as_ref() + .and_then(|id| rows.iter().position(|row| row == id)); + match command { + Some("close") => actions.push(RepertoireAction::Close), + Some("down") => { + let next = current.map_or(0, |i| (i + 1).min(rows.len().saturating_sub(1))); + if let Some(id) = rows.get(next).cloned() { + self.select(id); + } + } + Some("up") => { + let next = current.map_or(0, |i| i.saturating_sub(1)); + if let Some(id) = rows.get(next).cloned() { + self.select(id); + } + } + Some("main") => self.main_action(ui.ctx(), settings), + _ => {} + } + } + + fn visible_ids(&self) -> Vec { + let search = self.search.to_lowercase(); + self.sorted_ids() + .into_iter() + .filter(|id| { + self.library + .repertoire(id) + .is_some_and(|r| r.name.to_lowercase().contains(&search)) + }) + .collect() + } + + fn selected_card(&self) -> CardState { + let Some(id) = &self.selected else { + return CardState::Counting; + }; + if let Some(error) = self.library_error.clone().or(self.learning_error.clone()) { + return CardState::Failed(error); + } + card_state( + self.index.get(id).map(|row| row.has_moves), + self.stats.get(id), + ) + } + + /// The card's main button. + fn main_action(&mut self, ctx: &egui::Context, settings: &mut Settings) { + match self.selected_card() { + CardState::Review { .. } | CardState::OnlyNew { .. } => { + self.start(SessionKind::Daily, settings) + } + CardState::Done { .. } => self.start(SessionKind::ReviewAll, settings), + CardState::Empty => { + let target = self.selected.clone(); + self.pick_import(target, ctx); + } + CardState::OtherColor => self.open_color_dialog(settings), + CardState::Counting => {} + CardState::Failed(_) => self.retry_load(), + } + } + + fn retry_load(&mut self) { + match load_library(&self.library_store) { + Ok(library) => { + self.library = library; + self.library_error = None; + self.reindex(); + } + Err(error) => self.library_error = Some(error), + } + match self.learning_store.load() { + Ok(data) => { + self.learning = data; + self.learning_error = None; + } + Err(error) => self.learning_error = Some(error.to_string()), + } + self.stats_key = None; + self.stats.clear(); + } + + fn menu_item(&mut self, item: MenuItem, ctx: &egui::Context, settings: &mut Settings) { + match item { + MenuItem::Train => self.main_action(ctx, settings), + MenuItem::ReviewAll => self.start(SessionKind::ReviewAll, settings), + MenuItem::Lines => self.open_lines(settings, None), + MenuItem::Rename => { + if let Some(id) = self.selected.clone() { + self.dialog = Some(Dialog::Rename { + name: self.selected_name(), + id, + error: None, + select_all: true, + }); + } + } + MenuItem::SwitchColor => self.open_color_dialog(settings), + MenuItem::AddPgn => { + let target = self.selected.clone(); + self.pick_import(target, ctx); + } + MenuItem::Export => self.export(Some(ctx.clone())), + MenuItem::Reset => self.open_reset_dialog(settings), + MenuItem::Delete => { + if let Some(id) = self.selected.clone() { + self.dialog = Some(Dialog::Delete { id }); + } + } + } + } + + fn repertoires_screen( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { + self.keyboard(ui, settings, actions); + let back = if self.return_to_game.is_some() { + tr("⬅ To game") + } else { + tr("⬅ Library") + }; + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + back + }; + let count = self.library.repertoires.len(); + let subtitle = if count == 0 { + String::new() + } else { + trf("{n} repertoires", &[("n", &count)]) + }; + let mut header = (false, false); + let mut menu = None; + layout::screen( + ui, + self, + |_, ui| { + header = crate::widgets::section_header_sub( + ui, + back, + tr("Opening training (α version)"), + &subtitle, + ) + }, + |this, ui| menu = this.panel(ui, settings), + |this, ui| this.preview_board(ui, settings), + ); + if header.0 { + actions.push(RepertoireAction::Close); + } + if header.1 { + actions.push(RepertoireAction::OpenSettings); + } + if let Some(item) = menu { + self.menu_item(item, ui.ctx(), settings); + } + } + + fn preview_board(&mut self, ui: &mut Ui, settings: &Settings) { + let row = self.selected.as_ref().and_then(|id| self.index.get(id)); + let position = row.map(|row| row.start.clone()).unwrap_or_default(); + let last_move = row.and_then(|row| row.last_move); + let side = self + .selected + .as_ref() + .map_or(LearningSide::White, |id| layout::side_of(settings, id)); + layout::still_board( + ui, + &mut self.board, + settings, + &position, + layout::orientation(side), + last_move, + &BoardAnnotations::default(), + ); + } + + /// The right panel; returns a chosen menu item (or the card's buttons). + fn panel(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let mut chosen = None; + let rect = ui.available_rect_before_wrap(); + ui.spacing_mut().item_spacing.y = GAP; + if self.library.repertoires.is_empty() { + self.empty_panel(ui, rect); + return None; + } + ui.add_space(4.0); + chosen = chosen.or(self.card(ui, settings)); + if self.library.repertoires.len() > 8 { + layout::fixed_block(ui, 24.0, |ui| { + ui.add( + egui::TextEdit::singleline(&mut self.search) + .hint_text(tr("Search")) + .desired_width(f32::INFINITY), + ); + }); + } + let table_h = (ui.available_height() - MESSAGE_H - BOTTOM_H - 3.0 * GAP).max(HEADER_H); + let table = layout::fixed_block(ui, table_h, |ui| self.table(ui, settings)); + chosen = chosen.or(table); + layout::fixed_block(ui, MESSAGE_H, |ui| self.message_strip(ui)); + layout::fixed_block(ui, BOTTOM_H, |ui| { + ui.horizontal(|ui| { + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("Import PGN…")) + .truncate() + .min_size(vec2(BOTTOM_W, BOTTOM_H)), + ) + .clicked() + { + self.pick_import(None, ui.ctx()); + } + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("New repertoire")) + .truncate() + .min_size(vec2(BOTTOM_W, BOTTOM_H)), + ) + .clicked() + { + self.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + } + }); + }); + chosen + } + + fn empty_panel(&mut self, ui: &mut Ui, rect: egui::Rect) { + let height = 200.0; + let top = rect.top() + ((rect.height() - height) / 2.0).max(0.0); + let area = + egui::Rect::from_min_size(egui::pos2(rect.left(), top), vec2(rect.width(), height)); + ui.scope_builder( + egui::UiBuilder::new() + .max_rect(area) + .layout(egui::Layout::top_down(egui::Align::Center)), + |ui| { + ui.heading(tr("No repertoires yet")); + ui.add_space(6.0); + ui.add( + egui::Label::new(RichText::new(tr("A repertoire is your opening moves as a PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…â€�.")).weak()) + .wrap(), + ); + ui.add_space(12.0); + if ui + .add_enabled_ui(self.library_error.is_none(), |ui| { + crate::widgets::primary_wide(ui, tr("Import PGN…"), BOTTOM_W) + }) + .inner + .clicked() + { + self.pick_import(None, ui.ctx()); + } + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("New repertoire")).min_size(vec2(BOTTOM_W, 30.0)), + ) + .clicked() + { + self.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + } + if let Some(error) = &self.library_error { + ui.add_space(8.0); + ui.add( + egui::Label::new( + RichText::new(trf("Could not read the repertoires: {e}", &[("e", error)])) + .color(ui.visuals().warn_fg_color), + ) + .wrap(), + ); + } + }, + ); + } + + fn card(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let two_rows = card_buttons_two_rows(ui, ui.available_width() - 22.0); + let card_h = if two_rows { + CARD_H + BUTTON_ROW_H + 6.0 + } else { + CARD_H + }; + let Some(id) = self.selected.clone() else { + layout::fixed_block(ui, card_h, |_| {}); + return None; + }; + let state = self.selected_card(); + let stats = self + .stats + .get(&id) + .and_then(|stats| stats.as_ref().ok()) + .cloned(); + let side = layout::side_of(settings, &id); + let name = self.selected_name(); + let mut chosen = None; + layout::fixed_block(ui, card_h, |ui| { + let inner = layout::card_inner(ui, card_h); + layout::card(ui, false, false).show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.spacing_mut().item_spacing.y = 6.0; + let width = ui.available_width(); + // 1. The name and the colour. + layout::fixed_block(ui, 26.0, |ui| { + ui.horizontal(|ui| { + // The colour gives way first: down to the king, the words on + // hover; only then is the name cut. + let gap = ui.spacing().item_spacing.x; + let words = layout::you_play(side); + let name_w = style_width(ui, &name, egui::TextStyle::Heading); + let king_w = layout::KING + gap; + let full_w = king_w + style_width(ui, words, egui::TextStyle::Body) + gap; + let short = name_w + full_w > width; + let you_w = if short { king_w } else { full_w }; + ui.allocate_ui_with_layout( + vec2((width - you_w - gap).max(0.0), 26.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| layout::line(ui, RichText::new(&name).heading()), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if !short { + ui.label(RichText::new(words).weak()); + } + let king = ui.add(layout::king(side).sense(egui::Sense::hover())); + if short { + king.on_hover_text(words); + } + }); + }); + }); + // 2. Today. + let (today, note) = card_texts(&state, side); + layout::fixed_block(ui, 22.0, |ui| { + let mut text = RichText::new(today).strong().size(15.0); + if matches!(state, CardState::Failed(_)) { + text = text.color(ui.visuals().warn_fg_color); + } + layout::line(ui, text); + }); + // 3. Progress. + layout::fixed_block(ui, 30.0, |ui| progress(ui, stats.as_ref())); + // 4. A quiet explanation. + layout::fixed_block(ui, 20.0, |ui| { + layout::line(ui, RichText::new(note).weak()); + }); + // 5. Buttons: one row when the widest row fits, else the main button + // on a row of its own. Which one depends on the width alone, so the + // card keeps its height whatever is selected. + let (label, enabled, item) = main_button(&state, side); + // «Review all» is there in every state with moves unless the main button + // already is it. + let third = !matches!( + state, + CardState::Empty + | CardState::Failed(_) + | CardState::Counting + | CardState::OtherColor + ) && !matches!(item, Some(MenuItem::ReviewAll)); + let gap = ui.spacing().item_spacing.x; + let mut main = |ui: &mut Ui, width: f32| { + let response = ui + .add_enabled_ui(enabled, |ui| { + crate::widgets::primary_wide(ui, &label, width) + }) + .inner; + let response = if matches!(state, CardState::Counting) { + response.on_disabled_hover_text(tr("Counting moves…")) + } else { + response + }; + if response.clicked() { + chosen = item; + } + }; + let lines_enabled = !matches!(state, CardState::Empty | CardState::Failed(_)); + let rest = |ui: &mut Ui, lines_w: f32, third_w: f32| -> Option { + let mut picked = None; + if ui + .add_enabled( + lines_enabled, + egui::Button::new(tr("Lines…")) + .truncate() + .min_size(vec2(lines_w, BUTTON_ROW_H)), + ) + .clicked() + { + picked = Some(MenuItem::Lines); + } + if third + && ui + .add( + egui::Button::new(tr("Review all")) + .truncate() + .min_size(vec2(third_w, BUTTON_ROW_H)), + ) + .on_hover_text(tr("Review all lines")) + .clicked() + { + picked = Some(MenuItem::ReviewAll); + } + picked + }; + let mut picked = None; + if two_rows { + // In a row, as in the one-row layout: the label is centred. + layout::fixed_block(ui, BUTTON_ROW_H, |ui| { + ui.horizontal(|ui| { + let width = ui.available_width(); + main(ui, width); + }); + }); + layout::fixed_block(ui, BUTTON_ROW_H, |ui| { + ui.horizontal(|ui| { + let half = ((ui.available_width() - gap) / 2.0).max(0.0); + picked = rest(ui, half, half); + }); + }); + } else { + layout::fixed_block(ui, BUTTON_ROW_H, |ui| { + ui.horizontal(|ui| { + let pad = 2.0 * ui.spacing().button_padding.x + 2.0; + let room = ui.available_width(); + let need = + |text: &str| style_width(ui, text, egui::TextStyle::Button) + pad; + let main_need = need(&label); + let lines_need = need(tr("Lines…")); + let third_need = need(tr("Review all")); + let (main_w, lines_w, third_w) = if third { + let mut spare = + room - main_need - lines_need - third_need - 2.0 * gap; + let grow = |need: f32, most: f32, spare: &mut f32| { + let add = (most - need).max(0.0).min(spare.max(0.0)); + *spare -= add; + need + add + }; + let main_w = grow(main_need, MAIN_W, &mut spare); + let lines_w = grow(lines_need, LINES_W, &mut spare); + (main_w, lines_w, grow(third_need, THIRD_W, &mut spare)) + } else { + let lines_w = lines_need.max(LINES_W.min(room / 3.0)); + ( + (room - lines_w - gap).max(0.0).min(MAIN_W.max(main_need)), + lines_w, + 0.0, + ) + }; + main(ui, main_w); + picked = rest(ui, lines_w, third_w); + }); + }); + } + if picked.is_some() { + chosen = picked; + } + }); + }); + chosen + } + + fn table(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let rows = self.visible_ids(); + let scroll_row = if std::mem::take(&mut self.scroll_to_selected) { + rows.iter() + .position(|id| Some(id) == self.selected.as_ref()) + } else { + None + }; + let mut clicked = None; + let mut double = false; + let mut chosen = None; + let open_menu = std::mem::take(&mut self.debug_menu); + ui.style_mut().interaction.selectable_labels = false; + let columns = table_widths(ui, ui.available_width()); + let (today_w, passed_w) = (columns.today, columns.passed); + let bar_w = columns.bar; + let mut table = egui_extras::TableBuilder::new(ui) + .id_salt("opening_repertoires") + .striped(true) + .sense(egui::Sense::click()) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column( + egui_extras::Column::remainder() + .at_least(columns.name_least) + .clip(true), + ) + .column(egui_extras::Column::exact(KING_W)) + .column(egui_extras::Column::exact(today_w)) + .column(egui_extras::Column::exact(passed_w)) + .column(egui_extras::Column::exact(MENU_W)); + if let Some(index) = scroll_row { + table = table.scroll_to_row(index, None); + } + table + .header(HEADER_H, |mut header| { + header.col(|ui| { + ui.add(egui::Label::new(RichText::new(tr("Name")).strong()).truncate()); + }); + header.col(|_| {}); + header.col(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(tr("Today")).strong()).truncate()); + }); + }); + // «Passed» heads the bar and the number together. + header.col(|ui| { + // From the left edge of the bars. + ui.add_space(columns.start); + ui.add(egui::Label::new(RichText::new(tr("Passed")).strong()).truncate()); + }); + header.col(|_| {}); + }) + .body(|body| { + body.rows(ROW_H, rows.len(), |mut row| { + let id = &rows[row.index()]; + let Some(repertoire) = self.library.repertoire(id) else { + return; + }; + let side = layout::side_of(settings, id); + let stats = self.stats.get(id); + let selected = self.selected.as_ref() == Some(id); + row.set_selected(selected); + row.col(|ui| { + layout::line(ui, repertoire.name.as_str()); + }); + row.col(|ui| { + ui.add(layout::king(side).sense(egui::Sense::hover())) + .on_hover_text(layout::you_play(side)); + }); + let has_moves = self.index.get(id).is_none_or(|row| row.has_moves); + row.col(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + match stats { + Some(Ok(_)) if !has_moves => {} + Some(Ok(stats)) => { + // A call to action in the normal colour; the rest quiet. + let text = if stats.due > 0 { + RichText::new(trf("review {n}", &[("n", &stats.due)])) + } else if stats.new_today() > 0 { + RichText::new(trf("new: {n}", &[("n", &stats.new_today())])) + .weak() + } else if let Some((at, _)) = stats.next { + RichText::new(when_short(at, layout::now())).weak() + } else { + RichText::new("—").weak() + }; + let mut hint = trf( + "To review {n}, new in the session {m}", + &[("n", &stats.due), ("m", &stats.new_today())], + ); + if let Some((at, _)) = stats.next + && stats.due == 0 + && stats.new_today() == 0 + { + hint = format!("{}\n{hint}", layout::when(at, layout::now())); + } + ui.add(egui::Label::new(text).truncate()).on_hover_text(hint); + } + Some(Err(_)) => { + ui.label(RichText::new("—").weak()); + } + None => { + ui.label(RichText::new("…").weak()); + } + } + }); + }); + let passed = matches!(stats, Some(Ok(stats)) if has_moves && stats.total > 0); + // [bar][6][number from the left]: neither moves with the counts. + row.col(|ui| { + ui.add_space(columns.start); + match stats { + Some(Ok(stats)) if passed => { + let room = ui.available_rect_before_wrap(); + let bar = egui::Rect::from_min_size( + egui::pos2(room.left(), room.center().y - 3.0), + vec2(bar_w, 6.0), + ); + progress_bar(ui, bar, Some(stats), selected); + ui.interact( + bar.expand2(vec2(0.0, 6.0)), + ui.id().with("bar"), + egui::Sense::hover(), + ) + .on_hover_text(passed_hint(stats)); + ui.add_space(bar_w + MINI_BAR_GAP); + ui.label(format!("{}/{}", stats.passed(), stats.total)) + .on_hover_text(passed_hint(stats)); + } + Some(Ok(_)) if !has_moves => { + ui.add( + egui::Label::new(RichText::new(tr("no moves")).weak()) + .truncate(), + ) + .on_hover_text(tr("The repertoire has no moves yet: import a PGN or add a line from a game")); + } + Some(_) => { + ui.label(RichText::new("—").weak()); + } + None => { + ui.label(RichText::new("…").weak()); + } + } + }); + let mut opened = false; + row.col(|ui| { + let button = ui.add(egui::Button::new("⋯").frame(false)); + let mut popup = egui::Popup::menu(&button); + if open_menu && self.selected.as_ref() == Some(id) { + popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); + } + if let Some(item) = + popup + .show(|ui| menu_items(ui, side, stats)) + .and_then(|inner| { + opened = true; + inner.inner + }) + { + chosen = Some(item); + } + }); + let response = row.response(); + if let Some(item) = egui::Popup::context_menu(&response) + .show(|ui| menu_items(ui, side, stats)) + .and_then(|inner| { + opened = true; + inner.inner + }) + { + chosen = Some(item); + } + if opened && self.selected.as_ref() != Some(id) { + clicked = Some(id.clone()); + } + if response.clicked() { + clicked = Some(id.clone()); + } + if response.double_clicked() { + clicked = Some(id.clone()); + double = true; + } + }); + }); + if let Some(id) = clicked { + self.selected = Some(id); + } + if double { + chosen = Some(MenuItem::Train); + } + chosen + } + + fn message_strip(&mut self, ui: &mut Ui) { + let Some(message) = &self.message else { + return; + }; + let mut close = false; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + close = crate::widgets::small_close_button(ui).clicked(); + let mut text = RichText::new(&message.text); + text = if message.error { + text.color(ui.visuals().warn_fg_color) + } else { + text.weak() + }; + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + layout::line(ui, text); + }); + }); + }); + if close { + self.message = None; + } + } + + fn show_dialog( + &mut self, + ctx: &egui::Context, + settings: &mut Settings, + actions: &mut Vec, + ) { + let Some(dialog) = self.dialog.take() else { + return; + }; + let names: HashMap = self + .library + .repertoires + .iter() + .map(|r| (r.id.clone(), r.name.clone())) + .collect(); + let name_of = |id: &RepertoireId| names.get(id).cloned().unwrap_or_default(); + let mut keep = true; + let mut result = None; + let enter = ctx.input(|input| input.key_pressed(Key::Enter)); + let mut dialog = dialog; + let modal = egui::Modal::new(egui::Id::new("opening_dialog")).show(ctx, |ui| { + ui.set_width(DIALOG_W); + match &mut dialog { + Dialog::Import(import) => { + result = import_dialog(ui, import, name_of, enter); + } + Dialog::New { name, side, error } => { + ui.heading(tr("New repertoire")); + ui.add_space(8.0); + name_field(ui, name, error, false); + side_choice(ui, side); + ui.add_space(4.0); + ui.add( + egui::Label::new(RichText::new(tr("Moves are added from a PGN file or with “Add to repertoire…â€� in any game.")).weak()) + .wrap(), + ); + result = dialog_buttons(ui, tr("Create"), true, None, enter); + } + Dialog::Rename { + name, + error, + select_all, + .. + } => { + ui.heading(tr("Rename repertoire")); + ui.add_space(8.0); + name_field(ui, name, error, std::mem::take(select_all)); + result = dialog_buttons(ui, tr("Save"), true, None, enter); + } + Dialog::Color { id, to, count, .. } => { + let name = name_of(id); + ui.heading(match to { + LearningSide::Black => trf("Play “{name}â€� as Black?", &[("name", &name)]), + LearningSide::White => trf("Play “{name}â€� as White?", &[("name", &name)]), + }); + ui.add_space(8.0); + let count = count.map_or_else(|| "…".to_owned(), |n| n.to_string()); + ui.add( + egui::Label::new(match to { + LearningSide::Black => trf( + "You will be asked Black's moves: {y}. Progress for White is kept and comes back if you switch again.", + &[("y", &count)], + ), + LearningSide::White => trf( + "You will be asked White's moves: {y}. Progress for Black is kept and comes back if you switch again.", + &[("y", &count)], + ), + }) + .wrap(), + ); + result = dialog_buttons(ui, tr("Switch"), true, None, enter); + } + Dialog::Reset { id, impact, busy, .. } => { + let name = name_of(id); + ui.heading(trf("Reset progress of “{name}â€�?", &[("name", &name)])); + ui.add_space(8.0); + match impact { + None => { + ui.label(RichText::new(tr("Counting moves…")).weak()); + } + Some((impact, keys)) => { + ui.add( + egui::Label::new(trf( + "All {y} moves of this repertoire become new again: answers and review dates are erased.", + &[("y", &keys.len())], + )) + .wrap(), + ); + ui.add( + egui::Label::new(tr("The moves themselves and PGN files do not change.")) + .wrap(), + ); + let others: Vec<_> = impact + .affected_repertoires + .iter() + .filter(|other| other.id != *id) + .collect(); + if impact.shared_count > 0 && !others.is_empty() { + let names = others + .iter() + .map(|other| other.name.as_str()) + .collect::>() + .join(", "); + ui.add( + egui::Label::new( + RichText::new(trf( + "{s} of these moves are also in: {names}. They become new there too.", + &[("s", &impact.shared_count), ("names", &names)], + )) + .color(ui.visuals().warn_fg_color), + ) + .wrap(), + ); + } + } + } + let ready = impact.as_ref().is_some_and(|(_, keys)| !keys.is_empty()) && !*busy; + result = dialog_buttons(ui, tr("Reset"), ready, Some(()), enter); + } + Dialog::Delete { id } => { + let name = name_of(id); + ui.heading(trf("Delete “{name}â€�?", &[("name", &name)])); + ui.add_space(8.0); + ui.add( + egui::Label::new(tr( + "The repertoire leaves this list. PGN files on disk do not change.", + )) + .wrap(), + ); + ui.add( + egui::Label::new(tr( + "Your answers are kept: import the same PGN again and the progress returns.", + )) + .wrap(), + ); + result = dialog_buttons(ui, tr("Delete"), true, Some(()), enter); + } + } + }); + if modal.should_close() && result.is_none() { + result = Some(false); + } + match result { + Some(false) => { + if let Dialog::Import(import) = &dialog { + import.cancel.store(true, Ordering::Relaxed); + } + keep = false; + } + Some(true) => { + self.dialog = Some(dialog); + self.confirm_dialog(settings, actions); + return; + } + None => {} + } + if keep { + self.dialog = Some(dialog); + } + } + + fn confirm_dialog(&mut self, settings: &mut Settings, actions: &mut Vec) { + match self.dialog.take() { + Some(Dialog::Import(import)) => { + self.dialog = Some(Dialog::Import(import)); + self.confirm_import(settings); + } + Some(Dialog::New { name, side, .. }) => match self.checked_name(&name, None) { + Ok(name) => { + let mut library = self.library.clone(); + match library.create_empty(name.clone()) { + Ok(id) => { + if self.persist(library) { + layout::set_side(settings, &id, side); + actions.push(RepertoireAction::SettingsChanged); + self.select(id); + } else { + self.dialog = Some(Dialog::New { + name, + side, + error: None, + }); + } + } + Err(error) => { + self.dialog = Some(Dialog::New { + name, + side, + error: Some(error.to_string()), + }) + } + } + } + Err(error) => { + self.dialog = Some(Dialog::New { + name, + side, + error: Some(error), + }) + } + }, + Some(Dialog::Rename { id, name, .. }) => match self.checked_name(&name, Some(&id)) { + Ok(checked) => { + let mut library = self.library.clone(); + match library.rename(&id, checked) { + Ok(()) => { + if !self.persist(library) { + self.dialog = Some(Dialog::Rename { + id, + name, + error: None, + select_all: false, + }); + } + } + Err(error) => { + self.dialog = Some(Dialog::Rename { + id, + name, + error: Some(error.to_string()), + select_all: false, + }) + } + } + } + Err(error) => { + self.dialog = Some(Dialog::Rename { + id, + name, + error: Some(error), + select_all: false, + }) + } + }, + Some(Dialog::Color { id, to, .. }) => { + layout::set_side(settings, &id, to); + actions.push(RepertoireAction::SettingsChanged); + } + Some(dialog @ Dialog::Reset { .. }) => { + self.dialog = Some(dialog); + self.confirm_reset(); + } + Some(dialog @ Dialog::Delete { .. }) => { + self.dialog = Some(dialog); + self.delete_selected(); + } + None => {} + } + } + + fn show_add( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { + let Some(mut add) = self.add.take() else { + return; + }; + let mut cancel = false; + let mut commit = false; + let start = fen4(add.source.start().position()); + let candidates: Vec<(RepertoireId, String)> = self + .library + .repertoires + .iter() + .filter(|r| { + self.index.contains_key(&r.id) && fen4(r.game().start().position()) == start + }) + .map(|r| (r.id.clone(), r.name.clone())) + .collect(); + egui::Modal::new(egui::Id::new("add_to_repertoire")).show(ui.ctx(), |ui| { + ui.set_max_width(450.0); + ui.heading(tr("Add to repertoire")); + ui.label(prefix_label(&add.source, add.at)); + for (id, name) in &candidates { + ui.radio_value(&mut add.selected, Some(id.clone()), name); + } + ui.radio_value(&mut add.selected, None, tr("New repertoire")); + if add.selected.is_none() { + ui.add( + egui::TextEdit::singleline(&mut add.name) + .char_limit(120) + .hint_text(tr("Name")), + ); + side_choice(ui, &mut add.side); + } + ui.horizontal(|ui| { + cancel = ui.button(tr("Cancel")).clicked(); + commit = ui.button(tr("Add")).clicked(); + }); + }); + if commit { + let result = (|| { + let mut library = self.library.clone(); + let new = add.selected.is_none(); + let id = if let Some(id) = &add.selected { + id.clone() + } else { + let name = self.checked_name(&add.name, None)?; + library + .create(name, &Game::from_start(add.source.start().clone())) + .map_err(|e| e.to_string())? + }; + let report = library + .add_prefix(&id, &add.source, add.at) + .map_err(|e| e.to_string())?; + let name = library + .repertoire(&id) + .map(|r| r.name.clone()) + .unwrap_or_default(); + Ok::<_, String>((library, id, name, report, new)) + })(); + match result { + Ok((library, id, name, report, new)) if self.persist(library.clone()) => { + if new { + layout::set_side(settings, &id, add.side); + actions.push(RepertoireAction::SettingsChanged); + } + actions.push(RepertoireAction::Added { id, name, report }); + return; + } + Ok(_) => {} + Err(error) => self.show_message(error, true), + } + } + if !cancel { + self.add = Some(add); + } + } + + pub fn debug_import(&mut self, path: PathBuf) { + let target = + std::env::var_os("CP_REPERTOIRE_IMPORT_INTO").and_then(|_| self.selected.clone()); + self.import_path(path, target); + } + + /// `CP_REPERTOIRE_CONFIRM_IMPORT`: confirmed in `poll`, where the chosen colour can + /// be written to the settings. + pub fn debug_confirm_import(&mut self, _settings: &Settings) -> bool { + false + } + + pub fn debug_export(&mut self) { + self.export(None); + } + + pub fn debug_rename(&mut self, name: String, _settings: &Settings) -> bool { + let Some(id) = self.selected.clone() else { + return false; + }; + let mut library = self.library.clone(); + if let Err(error) = library.rename(&id, name) { + self.show_message(error.to_string(), true); + return false; + } + self.persist(library) + } + + pub fn debug_delete(&mut self, _settings: &Settings) -> bool { + let Some(id) = self.selected.clone() else { + return false; + }; + self.dialog = Some(Dialog::Delete { id }); + self.delete_selected(); + self.dialog.is_none() + } + + pub fn debug_add_from_game(&mut self, source: Game, at: NodeId, title: String, target: String) { + self.open_add_from_game(source, at, title); + if let Some(add) = &mut self.add { + add.name = target; + add.selected = None; + } + } + + /// QA hooks (docs/qa/opening-trainer-v2-devhooks.md): `CP_REPERTOIRE=`, after + /// `CP_REPERTOIRE_SELECT=`. + pub fn debug_open(&mut self, what: &str, settings: &mut Settings) { + if let Ok(name) = std::env::var("CP_REPERTOIRE_SELECT") { + let name = name.to_lowercase(); + if let Some(id) = self + .library + .repertoires + .iter() + .find(|r| r.name.to_lowercase().contains(&name)) + .map(|r| r.id.clone()) + { + self.select(id); + } + } + let ready = self + .selected + .as_ref() + .is_some_and(|id| self.stats.contains_key(id) && self.index.contains_key(id)); + let needs_stats = !matches!(what, "library" | "detail" | "new" | "message"); + if needs_stats && !ready && !self.library.repertoires.is_empty() { + self.debug_start = Some(what.to_owned()); + return; + } + let ctx = egui::Context::default(); + match what { + "white" | "black" => { + if let Some(id) = self.selected.clone() { + let side = if what == "black" { + LearningSide::Black + } else { + LearningSide::White + }; + if layout::side_of(settings, &id) != side { + layout::set_side(settings, &id, side); + self.debug_start = Some("train".to_owned()); + return; + } + self.start(SessionKind::Daily, settings); + } + } + "train" => self.start(SessionKind::Daily, settings), + "main" => self.main_action(&ctx, settings), + "review" => self.start(SessionKind::ReviewAll, settings), + "lines" => { + let path = std::env::var("CP_REPERTOIRE_LINE") + .ok() + .map(|path| path.split_whitespace().map(str::to_owned).collect()); + self.open_lines(settings, path); + } + "branch" => { + let through: Vec = std::env::var("CP_REPERTOIRE_LINE") + .unwrap_or_default() + .split_whitespace() + .map(str::to_owned) + .collect(); + // The label in the notation of the application, as «Lines» gives it. + let label = self + .selected + .as_ref() + .and_then(|id| self.library.repertoire(id)) + .map(|r| r.game()) + .and_then(|game| { + layout::node_at(&game, &through).map(|at| layout::path_text(&game, at)) + }) + .unwrap_or_else(|| through.join(" ")); + self.start(SessionKind::Branch { through, label }, settings); + } + "menu" => self.debug_menu = true, + "new" => { + self.dialog = Some(Dialog::New { + name: std::env::var("CP_REPERTOIRE_NAME").unwrap_or_default(), + side: LearningSide::White, + error: None, + }); + if std::env::var_os("CP_REPERTOIRE_NAME").is_some() { + self.confirm_dialog(settings, &mut Vec::new()); + } + } + "rename" => self.menu_item(MenuItem::Rename, &ctx, settings), + "color" => self.open_color_dialog(settings), + "reset" => self.open_reset_dialog(settings), + "delete" => self.menu_item(MenuItem::Delete, &ctx, settings), + "message" => self.show_message( + trf( + "Could not save: {e}", + &[("e", &"Permission denied (os error 13)")], + ), + true, + ), + _ => {} + } + } + + pub fn debug_moves(&mut self, moves: &str) { + if let Screen::Session(session) = &mut self.screen { + session.debug_moves(moves); + } else { + self.debug_pending_moves = Some(moves.to_owned()); + } + } + + pub fn debug_hint(&mut self) { + if let Screen::Session(session) = &mut self.screen { + session.debug_hint(); + } + } +} + +impl Drop for RepertoireUi { + fn drop(&mut self) { + if let Some(Dialog::Import(import)) = &self.dialog { + import.cancel.store(true, Ordering::Relaxed); + } + } +} + +fn next_job() -> u64 { + NEXT_JOB.fetch_add(1, Ordering::Relaxed) +} + +/// `CP_REPERTOIRE_SLOW=`: a session takes this long to prepare (to see «Preparing…»). +fn debug_slow() -> Option { + std::env::var("CP_REPERTOIRE_SLOW") + .ok()? + .parse() + .ok() + .map(Duration::from_millis) +} + +fn row_stats( + library: &Library, + learning: &LearningData, + id: &RepertoireId, + side: LearningSide, + today: i64, +) -> Result { + let scope = StatsScope::for_repertoire(id.clone(), side, today); + let scoped = aggregate_scope(library, learning, &scope, &SrsSettings::default()) + .map_err(|error| error.to_string())?; + let summary = &scoped.summary; + let next = summary.next_due_at.map(|at| { + let day_end = end_of_day(at); + let count = scoped + .items + .iter() + .filter(|item| { + item.introduced + && item + .next_review_at + .is_some_and(|next| next > today && next <= day_end) + }) + .count(); + (at, count) + }); + Ok(RowStats { + total: summary.total, + due: summary.due, + unseen: summary.unseen, + learning: summary.learning, + learnt: summary.learnt, + next, + }) +} + +fn end_of_day(at: i64) -> i64 { + use chrono::{Local, TimeZone}; + Local + .timestamp_opt(at, 0) + .single() + .and_then(|time| time.date_naive().succ_opt()) + .and_then(|day| day.and_hms_opt(0, 0, 0)) + .and_then(|midnight| Local.from_local_datetime(&midnight).earliest()) + .map_or(at, |midnight| midnight.timestamp() - 1) +} + +/// Lines 2 and 4 of the card. +fn card_texts(state: &CardState, side: LearningSide) -> (String, String) { + match state { + CardState::Review { due, new } => { + let today = if *new > 0 { + trf("Today: {n} to review · {m} new", &[("n", due), ("m", new)]) + } else { + trf("Today: {n} to review", &[("n", due)]) + }; + let seconds = (due + new) * SECONDS_PER_MOVE; + let note = if seconds >= 60 { + trf("About {t} min", &[("t", &seconds.div_ceil(60))]) + } else { + String::new() + }; + (today, note) + } + CardState::OnlyNew { new } => ( + trf("Today: {m} new moves", &[("m", new)]), + tr("Nothing to review today").to_owned(), + ), + CardState::Done { next } => ( + tr("Done for today").to_owned(), + next.map(|(at, count)| { + trf( + "Next review: {when} · {n} moves", + &[("when", &layout::when(at, layout::now())), ("n", &count)], + ) + }) + .unwrap_or_default(), + ), + CardState::Empty => ( + tr("No moves yet").to_owned(), + tr("Add a PGN, or use “Add to repertoire…â€� in any game").to_owned(), + ), + CardState::OtherColor => ( + match side { + LearningSide::White => tr("No moves for White here"), + LearningSide::Black => tr("No moves for Black here"), + } + .to_owned(), + tr("This PGN may be a repertoire for the other colour").to_owned(), + ), + CardState::Counting => (tr("Counting moves…").to_owned(), String::new()), + CardState::Failed(error) => (tr("Cannot read this repertoire").to_owned(), error.clone()), + } +} + +/// The card's main button: label, enabled, what it does. +fn main_button(state: &CardState, side: LearningSide) -> (String, bool, Option) { + match state { + CardState::Review { .. } => (tr("Train").to_owned(), true, Some(MenuItem::Train)), + CardState::OnlyNew { new } => ( + trf("Learn {m} new", &[("m", new)]), + true, + Some(MenuItem::Train), + ), + CardState::Done { .. } => ( + tr("Review all lines").to_owned(), + true, + Some(MenuItem::ReviewAll), + ), + CardState::Empty => (tr("Add PGN…").to_owned(), true, Some(MenuItem::AddPgn)), + CardState::OtherColor => ( + match side { + LearningSide::White => tr("Switch colour to Black"), + LearningSide::Black => tr("Switch colour to White"), + } + .to_owned(), + true, + Some(MenuItem::SwitchColor), + ), + CardState::Counting => (tr("Train").to_owned(), false, None), + CardState::Failed(_) => (tr("Try again").to_owned(), true, Some(MenuItem::Train)), + } +} + +/// Row 3 of the card: learnt, in progress, the rest. +/// «Learned 3, learning 10, 75 moves in all» and what «learned» takes. +fn passed_hint(stats: &RowStats) -> String { + trf( + "Passed {a} of {y} moves, {l} of them consolidated. A move is consolidated after three correct answers in a row without a hint — usually over several days of reviews.", + &[ + ("a", &stats.passed()), + ("y", &stats.total), + ("l", &stats.learnt), + ], + ) +} + +/// Blue — passed, green inside it — consolidated. +/// Learned — the green of a correct move; learning — the accent blue; the track stands +/// out from the row. On a selected dark row: white, half-white and a dark track. +fn progress_bar(ui: &Ui, bar: egui::Rect, stats: Option<&RowStats>, selected: bool) { + let visuals = ui.visuals(); + let (track, learnt_fill, learning_fill) = if selected && visuals.dark_mode { + ( + Color32::from_black_alpha(90), + Color32::WHITE, + Color32::from_white_alpha(128), + ) + } else if selected { + // The light selection is pale: white would vanish, the selection's text colour shows. + let ink = visuals.selection.stroke.color; + (Color32::from_white_alpha(170), ink, ink.gamma_multiply(0.5)) + } else { + let green = crate::notation::assessment_text_color(chess_core::Nag(1), visuals.dark_mode) + .unwrap_or(visuals.selection.bg_fill); + let track = if visuals.dark_mode { + visuals.widgets.inactive.bg_fill + } else { + visuals.widgets.inactive.bg_fill.gamma_multiply(0.9) + }; + (track, green, visuals.hyperlink_color) + }; + let painter = ui.painter(); + painter.rect_filled(bar, 2.0, track); + if let Some(stats) = stats.filter(|stats| stats.total > 0) { + let total = stats.total as f32; + let learnt = bar.width() * stats.learnt as f32 / total; + let learning = bar.width() * stats.learning as f32 / total; + painter.rect_filled( + egui::Rect::from_min_size(bar.min, vec2(learnt, bar.height())), + 2.0, + learnt_fill, + ); + painter.rect_filled( + egui::Rect::from_min_size(bar.min + vec2(learnt, 0.0), vec2(learning, bar.height())), + 0.0, + learning_fill, + ); + } +} + +fn progress(ui: &mut Ui, stats: Option<&RowStats>) { + let width = ui.available_width(); + let (bar, _) = ui.allocate_exact_size(vec2(width, 8.0), egui::Sense::hover()); + progress_bar(ui, bar, stats, false); + ui.spacing_mut().item_spacing.y = 4.0; + ui.horizontal(|ui| { + ui.set_height(18.0); + if let Some(stats) = stats { + let text = trf( + "Passed {a} of {y} moves · consolidated {l}", + &[ + ("a", &stats.passed()), + ("y", &stats.total), + ("l", &stats.learnt), + ], + ); + ui.add(egui::Label::new(text).truncate()) + .on_hover_text(passed_hint(stats)); + } + }); +} + +fn menu_items( + ui: &mut Ui, + side: LearningSide, + stats: Option<&Result>, +) -> Option { + let has_moves = matches!(stats, Some(Ok(stats)) if stats.total > 0); + let mut chosen = None; + let mut item = |ui: &mut Ui, enabled: bool, label: &str, value: MenuItem| { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + chosen = Some(value); + ui.close(); + } + }; + item(ui, has_moves, tr("Train"), MenuItem::Train); + item(ui, has_moves, tr("Review all lines"), MenuItem::ReviewAll); + item(ui, true, tr("Lines…"), MenuItem::Lines); + ui.separator(); + item(ui, true, tr("Rename…"), MenuItem::Rename); + item( + ui, + true, + match side { + LearningSide::White => tr("Switch colour to Black"), + LearningSide::Black => tr("Switch colour to White"), + }, + MenuItem::SwitchColor, + ); + item( + ui, + true, + tr("Add PGN to this repertoire…"), + MenuItem::AddPgn, + ); + item(ui, true, tr("Export PGN…"), MenuItem::Export); + ui.separator(); + item(ui, has_moves, tr("Reset progress…"), MenuItem::Reset); + item(ui, true, tr("Delete…"), MenuItem::Delete); + chosen +} + +/// The dialog's buttons on the right: «Cancel», then the main one. `danger`: both are +/// plain and Enter means «Cancel». Returns `Some(true)` to confirm, `Some(false)` to +/// cancel. +fn dialog_buttons( + ui: &mut Ui, + label: &str, + enabled: bool, + danger: Option<()>, + enter: bool, +) -> Option { + let mut result = None; + ui.add_space(12.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let main = if danger.is_some() { + ui.add_enabled(enabled, egui::Button::new(label).min_size(vec2(0.0, 30.0))) + } else { + ui.add_enabled_ui(enabled, |ui| crate::widgets::primary(ui, label)) + .inner + }; + if main.clicked() { + result = Some(true); + } + let cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(0.0, 30.0))); + if danger.is_some() && !ui.ctx().memory(|m| m.focused().is_some()) { + cancel.request_focus(); + } + if cancel.clicked() { + result = Some(false); + } + }); + if result.is_none() && enter { + if danger.is_some() { + result = Some(false); + } else if enabled { + result = Some(true); + } + } + result +} + +fn name_field(ui: &mut Ui, name: &mut String, error: &mut Option, select_all: bool) { + ui.label(RichText::new(tr("Name")).strong().size(15.0)); + let output = egui::TextEdit::singleline(name) + .char_limit(120) + .desired_width(f32::INFINITY) + .show(ui); + if select_all { + let mut state = output.state.clone(); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(name.chars().count()), + ))); + state.store(ui.ctx(), output.response.id); + output.response.request_focus(); + } + if output.response.changed() { + *error = None; + } + // The place of the error is kept: the dialog does not grow when it appears. + ui.allocate_ui(vec2(ui.available_width(), 18.0), |ui| { + if let Some(error) = error.as_deref() { + ui.label(RichText::new(error).color(ui.visuals().warn_fg_color)); + } + }); +} + +fn side_choice(ui: &mut Ui, side: &mut LearningSide) { + ui.add_space(4.0); + ui.label(RichText::new(tr("You play")).strong().size(15.0)); + ui.add_space(2.0); + ui.horizontal(|ui| { + for (value, label) in [ + (LearningSide::White, tr("White")), + (LearningSide::Black, tr("Black")), + ] { + if ui + .add_sized( + [222.0, 34.0], + egui::Button::selectable( + *side == value, + (layout::king(value), RichText::new(label).size(14.0)), + ) + .frame_when_inactive(true), + ) + .clicked() + { + *side = value; + } + } + }); +} + +fn import_dialog( + ui: &mut Ui, + dialog: &mut ImportDialog, + name_of: impl Fn(&RepertoireId) -> String, + enter: bool, +) -> Option { + let adding = dialog.target.is_some(); + ui.heading(match &dialog.target { + Some(id) => trf("Add PGN to “{name}â€�", &[("name", &name_of(id))]), + None => tr("Import PGN").to_owned(), + }); + ui.add_space(8.0); + if !adding { + name_field(ui, &mut dialog.name, &mut dialog.error, false); + side_choice(ui, &mut dialog.side); + ui.label(RichText::new(tr("Chosen from the PGN — check it")).weak()); + ui.add_space(6.0); + } + let mut enabled = false; + let mut hover = None; + match &dialog.preview { + None => { + ui.label(RichText::new(tr("Reading the file…")).weak()); + ui.ctx().request_repaint_after(Duration::from_millis(50)); + } + Some(preview) => { + if adding { + let lines = preview.lines.saturating_sub(preview.lines_before); + if preview.report.added_nodes == 0 { + ui.label(RichText::new(tr("Nothing new in this file")).weak()); + } else { + ui.label( + RichText::new(trf( + "{m} new moves · {v} new lines", + &[("m", &preview.report.added_nodes), ("v", &lines)], + )) + .weak(), + ); + enabled = true; + } + } else { + let own = preview.own(dialog.side); + ui.label( + RichText::new(trf( + "{g} games · {v} lines · {y} your moves", + &[("g", &preview.games), ("v", &preview.lines), ("y", &own)], + )) + .weak(), + ); + enabled = own > 0 && !dialog.name.trim().is_empty(); + if own == 0 { + hover = Some(tr("No moves for this colour")); + } + } + for warning in preview.warnings.iter().take(WARNING_ROWS) { + layout::line(ui, RichText::new(warning).color(ui.visuals().warn_fg_color)); + } + if preview.warnings.len() > WARNING_ROWS { + ui.label( + RichText::new(trf( + "and {k} more", + &[("k", &(preview.warnings.len() - WARNING_ROWS))], + )) + .color(ui.visuals().warn_fg_color), + ); + } + if adding && let Some(error) = &dialog.error { + ui.label(RichText::new(error).color(ui.visuals().warn_fg_color)); + } + } + } + let label = if adding { tr("Add") } else { tr("Import") }; + let result = dialog_buttons(ui, label, enabled, None, enter); + if let Some(hover) = hover { + ui.label(RichText::new(hover).weak()); + } + result +} + +/// Whether the card's buttons take two rows at this inner width of the card: the widest +/// one-row set (a main button of the states with «Review all») does not fit. +fn card_buttons_two_rows(ui: &Ui, width: f32) -> bool { + let pad = 2.0 * ui.spacing().button_padding.x + 2.0; + let need = |text: &str| style_width(ui, text, egui::TextStyle::Button) + pad; + let main = need(tr("Train")).max(need(&trf("Learn {m} new", &[("m", &NEW_PER_SESSION)]))); + let gap = ui.spacing().item_spacing.x; + main + need(tr("Lines…")) + need(tr("Review all")) + 2.0 * gap > width +} + +/// The width of `text` in the font of `style`, as a label or a button draws it. +fn style_width(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { + ui.painter() + .layout_no_wrap( + text.to_owned(), + style.resolve(ui.style()), + egui::Color32::WHITE, + ) + .size() + .x +} + +/// The widths of the table's columns. +#[derive(Clone, Copy, Debug)] +struct TableColumns { + /// What the name keeps at the least: `NAME_LEAST`, less in a narrow panel so that + /// the fixed columns always fit. + name_least: f32, + today: f32, + passed: f32, + /// The bar of «Passed». + bar: f32, + /// Where the bar and the header of «Passed» start in its column. + start: f32, +} + +impl TableColumns { + /// All columns at their least, with the spaces between them. + fn least(&self, gap: f32) -> f32 { + self.name_least + KING_W + self.today + self.passed + MENU_W + 4.0 * gap + } +} + +/// The table's columns for a table `width` wide, measured once a frame from the texts +/// they may show, never from the rows on screen: counting or scrolling moves no column. +fn table_widths(ui: &Ui, width: f32) -> TableColumns { + let body = |text: &str| style_width(ui, text, egui::TextStyle::Body); + let now = layout::now(); + let today = [ + trf("review {n}", &[("n", &99)]), + trf("new: {n}", &[("n", &10)]), + when_short(now, now), + when_short(now + 24 * 60 * 60, now), + when_short(now + 3 * 24 * 60 * 60, now), + when_short(now + 30 * 24 * 60 * 60, now), + ] + .iter() + .map(|t| body(t)) + .fold(0.0, f32::max); + // A strong header is the body font in a brighter colour: as wide. + let today = (today.max(body(tr("Today"))) + 4.0).ceil(); + // The lead keeps the bar off «Today»; the header and «no moves» may use it. + let gap = ui.spacing().item_spacing.x; + let lead = (PASSED_GAP - gap).max(0.0); + let columns = |bar: f32| { + // The group of the bar and the room of «00/000», or the header if wider; the + // lead before it unless the header needs that room. + let group = bar + MINI_BAR_GAP + body(NUMBER_SAMPLE); + let content = group.max(body(tr("Passed"))).max(body(tr("no moves"))); + let passed = ((lead + group).max(content) + 4.0).ceil(); + let start = (passed - 4.0 - content).max(0.0); + let fixed = KING_W + today + passed + MENU_W + 4.0 * gap; + TableColumns { + name_least: (width - fixed).clamp(NAME_FLOOR, NAME_LEAST), + today, + passed, + bar, + start, + } + }; + let wide = columns(MINI_BAR_W); + if width < NARROW_TABLE && width - wide.least(gap) + wide.name_least < NAME_WANTED { + columns(MINI_BAR_NARROW) + } else { + wide + } +} + +/// The date of the next review in a table cell: «12:30» today, «tomorrow», «in 3 days», +/// then «dd.mm». The card and the hint say it in full. +fn when_short(at: i64, now: i64) -> String { + use chrono::{Local, TimeZone}; + let (Some(at), Some(now)) = ( + Local.timestamp_opt(at, 0).single(), + Local.timestamp_opt(now, 0).single(), + ) else { + return String::new(); + }; + match (at.date_naive() - now.date_naive()).num_days() { + ..=0 => at.format("%H:%M").to_string(), + 1..=6 => layout::when(at.timestamp(), now.timestamp()), + _ => at.format("%d.%m").to_string(), + } +} + +/// The colour whose moves a PGN repertoire gives: the side with fewer positions where +/// the PGN has several moves (one answer to many replies). White on a tie. +fn suggested_side(game: &Game) -> LearningSide { + let mut branching = [0usize; 2]; + let mut stack = vec![NodeId::ROOT]; + while let Some(node) = stack.pop() { + let children = game.children(node); + if children.len() > 1 + && let Some(position) = game.position(node) + { + branching[usize::from(position.turn() == Color::Black)] += 1; + } + stack.extend(children.iter().copied()); + } + if branching[1] < branching[0] { + LearningSide::Black + } else { + LearningSide::White + } +} + +fn read_import( + path: &Path, + target: Option, + mut library: Library, + cancel: &AtomicBool, +) -> Result { + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + let db = + PgnDatabase::from_bytes(bytes, None, &mut |_| {}, cancel).map_err(|e| e.to_string())?; + if db.is_empty() { + return Err(tr("No games").to_owned()); + } + let base_revision = library.revision; + let stem = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_else(|| tr("New repertoire").to_owned()); + let mut warnings = Vec::new(); + let mut id = target.clone(); + let mut report = MergeReport::default(); + let mut event = None; + let lines_before = target + .as_ref() + .and_then(|id| library.repertoire(id)) + .map_or(0, |r| layout::lines(&r.game(), |_| false).len()); + for index in 0..db.len() { + if cancel.load(Ordering::Relaxed) { + return Err(String::new()); + } + let Some(parsed) = db.load_game(index) else { + warnings.push(trf("Game {n}: could not be read", &[("n", &(index + 1))])); + continue; + }; + if let Some(d) = parsed + .diagnostics + .iter() + .find(|d| d.severity == Severity::Error) + { + warnings.push(trf( + "Game {n}: {message}", + &[("n", &(index + 1)), ("message", &d.message)], + )); + } + if event.is_none() { + event = parsed + .game + .tag("Event") + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty() && value != "?"); + } + if parsed.game.children(NodeId::ROOT).is_empty() { + warnings.push(trf("Game {n} has no moves", &[("n", &(index + 1))])); + continue; + } + let current = match &id { + Some(id) => id.clone(), + None => { + let new_id = library + .create(stem.clone(), &Game::from_start(parsed.game.start().clone())) + .map_err(|e| e.to_string())?; + id = Some(new_id.clone()); + new_id + } + }; + match library.add_game(¤t, &parsed.game) { + Ok(added) => { + report.added_nodes += added.added_nodes; + report.merged_nodes += added.merged_nodes; + report.annotation_changes += added.annotation_changes; + } + Err(error) => warnings.push(trf( + "Game {n}: {message}", + &[("n", &(index + 1)), ("message", &error.to_string())], + )), + } + } + let id = id.ok_or_else(|| tr("No games with moves in this file").to_owned())?; + let game = library + .repertoire(&id) + .map(|r| r.game()) + .ok_or_else(|| tr("No games").to_owned())?; + let own = [LearningSide::White, LearningSide::Black].map(|side| { + active_learning_keys(&library, &StatsScope::for_repertoire(id.clone(), side, 0)) + .map_or(0, |keys| keys.len()) + }); + let mut name = event.unwrap_or(stem); + let base = name.clone(); + let mut suffix = 2; + while library + .repertoires + .iter() + .any(|r| r.id != id && r.name.to_lowercase() == name.to_lowercase()) + { + name = format!("{base} ({suffix})"); + suffix += 1; + } + Ok(ImportPreview { + lines: layout::lines(&game, |_| false).len(), + lines_before, + suggested: suggested_side(&game), + library, + id, + base_revision, + games: db.len(), + own, + default_name: name, + warnings, + report, + }) +} + +/// Stable key, name, PGN and colour of each example repertoire. +/// An example repertoire: a stable key, its name and its PGN with English comments and +/// with Russian ones (the same moves). +struct Starter { + key: &'static str, + name: &'static str, + pgn: &'static str, + pgn_ru: &'static str, + side: LearningSide, +} + +impl Starter { + /// The PGN in the interface language at the moment it is given: Russian comments + /// for Russian, English for every other language. + fn pgn(&self) -> &'static str { + match crate::i18n::current() { + crate::i18n::Lang::Ru => self.pgn_ru, + _ => self.pgn, + } + } +} + +const STARTER_REPERTOIRES: [Starter; 4] = [ + Starter { + key: "spanish-white", + name: "Spanish Opening", + pgn: include_str!("../assets/repertoires/spanish-white.pgn"), + pgn_ru: include_str!("../assets/repertoires/spanish-white.ru.pgn"), + side: LearningSide::White, + }, + Starter { + key: "sicilian-black", + name: "Sicilian Defence: Najdorf", + pgn: include_str!("../assets/repertoires/sicilian-black.pgn"), + pgn_ru: include_str!("../assets/repertoires/sicilian-black.ru.pgn"), + side: LearningSide::Black, + }, + Starter { + key: "queens-gambit-white", + name: "Queen's Gambit", + pgn: include_str!("../assets/repertoires/queens-gambit-white.pgn"), + pgn_ru: include_str!("../assets/repertoires/queens-gambit-white.ru.pgn"), + side: LearningSide::White, + }, + Starter { + key: "triangle-black", + name: "Semi-Slav: Triangle", + pgn: include_str!("../assets/repertoires/triangle-black.pgn"), + pgn_ru: include_str!("../assets/repertoires/triangle-black.ru.pgn"), + side: LearningSide::Black, + }, +]; + +const STARTER_MARKS_VERSION: u32 = 1; + +/// Keys of the example repertoires already given to the user, in a file of its own next +/// to the library: the library format read by 2.4.0 stays as it is. +#[derive(serde::Serialize, serde::Deserialize)] +struct StarterMarks { + version: u32, + given: BTreeSet, +} + +#[derive(serde::Deserialize)] +struct StarterMarksVersion { + version: u32, +} + +fn starter_marks_path(store: &LibraryStore) -> PathBuf { + store.path().with_file_name("repertoire-starters.json") +} + +/// Marks read from the file. `None`: no file yet. A file of a newer version means every +/// example was given: it is neither reissued nor overwritten. +enum StarterMarksState { + Missing, + Given(BTreeSet), + Newer, +} + +fn read_starter_marks(path: &Path) -> Result { + let damaged = + || tr("The record of example repertoires is damaged; examples were not added").to_owned(); + let bytes = match crate::platform::fs::read(path) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Ok(StarterMarksState::Missing); + } + Err(e) => { + eprintln!("{}: {e}", path.display()); + return Err(damaged()); + } + }; + let version = serde_json::from_slice::(&bytes).map_err(|e| { + eprintln!("{}: {e}", path.display()); + damaged() + })?; + if version.version != STARTER_MARKS_VERSION { + eprintln!( + "{}: unknown version {}, examples are not added", + path.display(), + version.version + ); + return Ok(StarterMarksState::Newer); + } + let marks = serde_json::from_slice::(&bytes).map_err(|e| { + eprintln!("{}: {e}", path.display()); + damaged() + })?; + Ok(StarterMarksState::Given(marks.given)) +} + +/// Each example repertoire is given once. An example also counts as given whenever a +/// repertoire carries its name in any language: the examples of 2.4.0 had no marks, and a +/// lost write of the marks must not double them. Examples deleted after that do not come +/// back; the user's own repertoires are not touched. The library is read again right +/// before the examples are added, and a save that lost a race with another copy of the +/// program is retried on the fresh library. +fn seed_starter(store: &LibraryStore) -> Result, String> { + let marks_path = starter_marks_path(store); + let (mut given, marked) = match read_starter_marks(&marks_path)? { + StarterMarksState::Newer => return Ok(Vec::new()), + StarterMarksState::Missing => (BTreeSet::new(), false), + StarterMarksState::Given(given) => (given, true), + }; + let mut attempts = 0; + let sides = loop { + attempts += 1; + let mut library = store.load().map_err(|e| e.to_string())?; + for Starter { key, name, .. } in &STARTER_REPERTOIRES { + let names = crate::i18n::all_languages(name); + if library + .repertoires + .iter() + .any(|r| names.contains(&r.name.as_str())) + { + given.insert((*key).to_owned()); + } + } + let missing: Vec<_> = STARTER_REPERTOIRES + .iter() + .filter(|starter| !given.contains(starter.key)) + .collect(); + if missing.is_empty() { + break Vec::new(); + } + let mut sides = Vec::new(); + let cancel = AtomicBool::new(false); + for starter in &missing { + let (name, pgn, side) = (starter.name, starter.pgn(), &starter.side); + let db = PgnDatabase::from_bytes(pgn.as_bytes().to_vec(), None, &mut |_| {}, &cancel) + .map_err(|e| e.to_string())?; + let mut id = None; + for index in 0..db.len() { + let Some(parsed) = db.load_game(index) else { + continue; + }; + let current = match &id { + Some(id) => id, + None => id.insert( + library + .create(tr(name), &Game::from_start(parsed.game.start().clone())) + .map_err(|e| e.to_string())?, + ), + }; + library + .add_game(current, &parsed.game) + .map_err(|e| e.to_string())?; + } + if let Some(id) = id { + sides.push((id, *side)); + } + } + match store.save(&mut library) { + Ok(()) => { + given.extend(missing.iter().map(|starter| starter.key.to_owned())); + break sides; + } + Err(StoreError::Conflict { .. }) if attempts < 3 => continue, + Err(e) => return Err(e.to_string()), + } + }; + if marked && sides.is_empty() { + return Ok(sides); + } + let marks = StarterMarks { + version: STARTER_MARKS_VERSION, + given, + }; + let bytes = serde_json::to_vec_pretty(&marks).map_err(|e| e.to_string())?; + // The library is already saved; without the marks the names still keep the examples + // from being added again. + if let Err(e) = crate::settings::write_atomic(&marks_path, &bytes) { + eprintln!("{}: {e}", marks_path.display()); + } + Ok(sides) +} + +fn load_library(store: &LibraryStore) -> Result { + let mut library = store.load().map_err(|error| error.to_string())?; + // The depth limit of 2.2 is not a user's choice: trained lines go to their ends. + // The PGN does not change. + for repertoire in &mut library.repertoires { + repertoire.set_max_plies(u32::MAX); + } + Ok(library) +} + +fn prefix_label(game: &Game, at: NodeId) -> String { + game.path(at) + .into_iter() + .skip(1) + .filter_map(|id| game.move_label(id)) + .map(|s| crate::san::show(&s).into_owned()) + .collect::>() + .join(" ") +} + +fn stores() -> (LibraryStore, LearningStore) { + let legacy = std::env::var_os("CP_TRAINING_FILE") + .map(PathBuf::from) + .or_else(|| { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("training.json")) + }) + .unwrap_or_else(|| PathBuf::from("training.json")); + let dir = std::env::var_os("CP_REPERTOIRE_DIR") + .map(PathBuf::from) + .or_else(|| legacy.parent().map(Path::to_path_buf)) + .unwrap_or_else(|| PathBuf::from(".")); + ( + LibraryStore::new(dir.join("repertoires.json")), + LearningStore::with_legacy(dir.join("repertoire-training.json"), legacy), + ) +} + +#[cfg(test)] +#[path = "repertoire_ui_tests.rs"] +mod tests; diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs new file mode 100644 index 0000000..98f35ac --- /dev/null +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -0,0 +1,911 @@ +use std::sync::atomic::AtomicU64; + +use super::*; +use trainer::repertoire::{QueueMode, TrainingMode, active_learning_memberships}; + +static NEXT_DIR: AtomicU64 = AtomicU64::new(1); +const DAY: i64 = 24 * 60 * 60; + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "cp-repertoire-ui-{}-{}-{name}", + std::process::id(), + NEXT_DIR.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn stores(&self) -> (LibraryStore, LearningStore) { + ( + LibraryStore::new(self.0.join("repertoires.json")), + LearningStore::new(self.0.join("repertoire-training.json")), + ) + } + + fn ui(&self) -> RepertoireUi { + let (library, learning) = self.stores(); + RepertoireUi::with_stores(library, learning) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn save_library(dir: &TestDir, repertoires: &[(&str, &str)]) -> Vec { + let mut library = Library::default(); + let ids = repertoires + .iter() + .map(|(name, pgn)| { + library + .create(*name, &chess_core::parse_str(pgn).game) + .unwrap() + }) + .collect(); + dir.stores().0.save(&mut library).unwrap(); + ids +} + +/// Frames until the background index and counts are in. +fn settle(ui: &mut RepertoireUi, ctx: &egui::Context, settings: &mut Settings, size: egui::Vec2) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + frame(ui, ctx, settings, size, Vec::new()); + let ready = ui.preparing.is_none() + && ui.lines_job.is_none() + && !ui.learning_loading + && ui + .library + .repertoires + .iter() + .all(|r| ui.index.contains_key(&r.id) && ui.stats.contains_key(&r.id)) + && ui.stats_key.as_ref().is_some_and(|key| { + key.library_revision == ui.library.revision + && key.learning_revision == ui.learning.revision + }) + && ui.stats_shown == ui.stats_key; + if ready || Instant::now() > deadline { + frame(ui, ctx, settings, size, Vec::new()); + return; + } + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn frame( + ui: &mut RepertoireUi, + ctx: &egui::Context, + settings: &mut Settings, + size: egui::Vec2, + events: Vec, +) -> Vec { + let mut actions = Vec::new(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + events, + ..Default::default() + }, + |root| actions = ui.show(root, settings), + ) + .drop_without_applying_deltas(); + actions +} + +fn panel_rect(ctx: &egui::Context) -> egui::Rect { + egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side")) + .map(|state| state.outer_rect) + .unwrap_or(egui::Rect::NOTHING) +} + +fn key(key: Key) -> egui::Event { + egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + } +} + +#[test] +fn the_card_says_what_to_do_in_every_state() { + let stats = |due, unseen, total| RowStats { + total, + due, + unseen, + learning: 0, + learnt: total - unseen, + next: None, + }; + assert_eq!(card_state(Some(true), None), CardState::Counting); + assert_eq!( + card_state(Some(true), Some(&Err("broken".into()))), + CardState::Failed("broken".into()) + ); + assert_eq!( + card_state(Some(false), Some(&Ok(stats(0, 0, 0)))), + CardState::Empty + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 0, 0)))), + CardState::OtherColor + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(3, 40, 50)))), + CardState::Review { due: 3, new: 10 } + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 4, 50)))), + CardState::OnlyNew { new: 4 } + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 0, 50)))), + CardState::Done { next: None } + ); + // Every state has a main button that does something, but «Counting». + for (state, side) in [ + (CardState::Review { due: 3, new: 10 }, LearningSide::White), + (CardState::OnlyNew { new: 4 }, LearningSide::White), + ( + CardState::Done { + next: Some((1_800_000_000, 2)), + }, + LearningSide::White, + ), + (CardState::Empty, LearningSide::White), + (CardState::OtherColor, LearningSide::White), + (CardState::Failed("x".into()), LearningSide::Black), + ] { + let (label, enabled, item) = main_button(&state, side); + assert!(enabled && item.is_some() && !label.is_empty(), "{state:?}"); + let (today, _) = card_texts(&state, side); + assert!(!today.is_empty(), "{state:?}"); + } + assert!(!main_button(&CardState::Counting, LearningSide::White).1); + assert_eq!( + main_button(&CardState::OtherColor, LearningSide::White).0, + tr("Switch colour to Black") + ); + assert_eq!( + card_texts(&CardState::Review { due: 3, new: 10 }, LearningSide::White), + ( + trf("Today: {n} to review · {m} new", &[("n", &3), ("m", &10)]), + trf("About {t} min", &[("t", &5)]) + ) + ); + // Under a minute the time is not shown; a part with zero is left out. + assert_eq!( + card_texts(&CardState::Review { due: 2, new: 0 }, LearningSide::White), + (trf("Today: {n} to review", &[("n", &2)]), String::new()) + ); +} + +#[test] +fn today_counts_until_the_end_of_the_day_and_at_most_ten_new() { + let mut library = Library::default(); + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 \ + 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 *"; + let id = library + .create("Ruy", &chess_core::parse_str(pgn).game) + .unwrap(); + let today = layout::end_of_today(); + let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, today); + let keys: Vec<_> = active_learning_memberships(&library, &scope) + .unwrap() + .into_iter() + .map(|membership| membership.key) + .collect(); + assert_eq!(keys.len(), 12); + let mut learning = LearningData::default(); + let now = layout::now(); + for (index, key) in keys.iter().take(3).enumerate() { + let item = learning.ensure_item(key.clone()); + item.introduced = true; + item.correct_streak = 3; + // Due later today, due long ago, due in two days. + item.next_review_at = Some(match index { + 0 => today - 1, + 1 => now - 10 * DAY, + _ => now + 2 * DAY, + }); + } + let stats = row_stats(&library, &learning, &id, LearningSide::White, today).unwrap(); + assert_eq!( + (stats.total, stats.due, stats.unseen, stats.learnt), + (12, 2, 9, 3) + ); + assert_eq!(stats.new_today(), 9); + assert_eq!(stats.passed(), 3 + stats.learning); + assert_eq!( + card_state(Some(true), Some(&Ok(stats.clone()))), + CardState::Review { due: 2, new: 9 } + ); + let black = row_stats(&library, &learning, &id, LearningSide::Black, today).unwrap(); + assert_eq!(black.total, 11); + assert_eq!(black.new_today(), NEW_PER_SESSION); +} + +#[test] +fn loading_lifts_the_old_depth_limit_without_touching_the_pgn() { + let dir = TestDir::new("depth"); + let ids = save_library(&dir, &[("Limited", "1. e4 e5 2. Nf3 *")]); + let (store, _) = dir.stores(); + let stored = store.load().unwrap(); + assert_eq!( + stored.repertoires[0].max_plies, + trainer::repertoire::DEFAULT_MAX_PLIES + ); + let ui = dir.ui(); + let repertoire = ui.library.repertoire(&ids[0]).unwrap(); + assert_eq!(repertoire.max_plies, u32::MAX); + assert_eq!(repertoire.pgn, stored.repertoires[0].pgn); + // Nothing is written until the user changes something. + assert_eq!( + store.load().unwrap().repertoires[0].max_plies, + stored.repertoires[0].max_plies + ); +} + +#[test] +fn an_import_reads_name_colour_counts_and_warnings() { + let dir = TestDir::new("import"); + let path = dir.0.join("caro.pgn"); + std::fs::write( + &path, + "[Event \"Caro-Kann for Black\"]\n\n1. e4 c6 2. d4 (2. Nc3 d5) (2. c4 d5) d5 *\n\n\ + [Event \"Empty\"]\n\n*\n", + ) + .unwrap(); + let preview = read_import(&path, None, Library::default(), &AtomicBool::new(false)).unwrap(); + assert_eq!(preview.default_name, "Caro-Kann for Black"); + assert_eq!(preview.suggested, LearningSide::Black); + assert_eq!(preview.games, 2); + assert_eq!(preview.lines, 3); + assert_eq!(preview.own(LearningSide::Black), 4); + assert_eq!(preview.own(LearningSide::White), 4); + assert_eq!( + preview.warnings, + [trf("Game {n} has no moves", &[("n", &2)])] + ); + // The source file is only read. + assert!( + std::fs::read_to_string(&path) + .unwrap() + .starts_with("[Event \"Caro-Kann") + ); + + let mut ui = dir.ui(); + let mut settings = Settings::default(); + ui.dialog = Some(Dialog::Import(ImportDialog { + job: 1, + target: None, + name: preview.default_name.clone(), + side: preview.suggested, + preview: Some(preview), + error: None, + cancel: Arc::new(AtomicBool::new(false)), + })); + assert!(ui.confirm_import(&mut settings)); + let id = ui.selected.clone().unwrap(); + assert_eq!( + ui.library.repertoire(&id).unwrap().name, + "Caro-Kann for Black" + ); + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + assert_eq!( + settings.repertoire_modes.get(id.as_str()), + Some(&(TrainingMode::Black, QueueMode::SpacedRepetition)) + ); + assert_eq!(dir.stores().0.load().unwrap().repertoires.len(), 1); +} + +#[test] +fn a_white_repertoire_is_suggested_for_white() { + let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) (1... e6 2. d4) 2. Nf3 *").game; + assert_eq!(suggested_side(&game), LearningSide::White); + let even = chess_core::parse_str("1. e4 e5 *").game; + assert_eq!(suggested_side(&even), LearningSide::White); +} + +#[test] +fn old_colours_open_as_before_and_both_opens_as_white() { + let mut settings = Settings::default(); + let id = Library::default().create_empty("Any").unwrap(); + assert_eq!(layout::side_of(&settings, &id), LearningSide::White); + settings.repertoire_modes.insert( + id.to_string(), + (TrainingMode::Black, QueueMode::ReviewInOrder), + ); + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + settings + .repertoire_modes + .insert(id.to_string(), (TrainingMode::Both, QueueMode::LeastRecent)); + assert_eq!(layout::side_of(&settings, &id), LearningSide::White); + layout::set_side(&mut settings, &id, LearningSide::Black); + assert_eq!( + settings.repertoire_modes[id.as_str()], + (TrainingMode::Black, QueueMode::SpacedRepetition) + ); +} + +#[test] +fn the_three_screens_keep_the_board_and_the_panel_in_one_place() { + let dir = TestDir::new("geometry"); + save_library( + &dir, + &[ + ("Italian", "1. e4 e5 2. Nf3 Nc6 3. Bc4 *"), + ("London", "1. d4 d5 2. Bf4 *"), + ], + ); + for (size, left) in [ + (vec2(1920.0, 1080.0), 1360.0), + (vec2(1400.0, 900.0), 896.0), + (vec2(960.0, 600.0), 580.0), + ] { + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + settle(&mut ui, &ctx, &mut settings, size); + let repertoires = panel_rect(&ctx); + assert!( + (repertoires.left() - left).abs() <= 1.0, + "{repertoires:?} in {size:?}" + ); + // Selecting another row moves nothing. + frame( + &mut ui, + &ctx, + &mut settings, + size, + vec![key(Key::ArrowDown)], + ); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert_eq!(panel_rect(&ctx), repertoires); + // Lines. + ui.open_lines(&settings, None); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Lines(_))); + assert_eq!(panel_rect(&ctx), repertoires); + // A session started from Lines, and back to Lines. + ui.start(SessionKind::ReviewAll, &settings); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Session(_))); + assert_eq!(panel_rect(&ctx), repertoires); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(matches!(ui.screen, Screen::Lines(_))); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(matches!(ui.screen, Screen::Repertoires)); + assert_eq!(panel_rect(&ctx), repertoires); + } +} + +#[test] +fn keys_of_the_screen_do_nothing_under_a_dialog() { + let dir = TestDir::new("dialog-keys"); + save_library(&dir, &[("A", "1. e4 *"), ("B", "1. d4 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + settle(&mut ui, &ctx, &mut settings, size); + let selected = ui.selected.clone(); + ui.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + let actions = frame( + &mut ui, + &ctx, + &mut settings, + size, + vec![key(Key::ArrowDown)], + ); + assert!(actions.is_empty()); + assert_eq!(ui.selected, selected); + let actions = frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + assert!( + actions + .iter() + .all(|action| !matches!(action, RepertoireAction::Close)), + "Esc closes the dialog, not the screen" + ); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(ui.dialog.is_none()); + let actions = frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + assert!(matches!(actions.as_slice(), [RepertoireAction::Close])); +} + +#[test] +fn names_are_checked_and_a_new_repertoire_keeps_its_colour() { + let dir = TestDir::new("names"); + save_library(&dir, &[("Najdorf", "1. e4 c5 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let mut actions = Vec::new(); + for (name, error) in [ + (" ", tr("The repertoire name must not be empty")), + ("najdorf", tr("A repertoire with this name already exists")), + ] { + ui.dialog = Some(Dialog::New { + name: name.into(), + side: LearningSide::Black, + error: None, + }); + ui.confirm_dialog(&mut settings, &mut actions); + assert!( + matches!(&ui.dialog, Some(Dialog::New { error: Some(e), .. }) if e == error), + "{name:?}" + ); + } + ui.dialog = Some(Dialog::New { + name: "Sveshnikov".into(), + side: LearningSide::Black, + error: None, + }); + ui.confirm_dialog(&mut settings, &mut actions); + assert!(ui.dialog.is_none()); + let id = ui.selected.clone().unwrap(); + assert_eq!(ui.library.repertoire(&id).unwrap().name, "Sveshnikov"); + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + assert!(matches!( + actions.as_slice(), + [RepertoireAction::SettingsChanged] + )); +} + +#[test] +fn delete_keeps_the_answers_and_selects_the_neighbour() { + let dir = TestDir::new("delete"); + let ids = save_library( + &dir, + &[("A", "1. e4 *"), ("B", "1. d4 *"), ("C", "1. c4 *")], + ); + let mut learning = LearningData::default(); + let library = dir.stores().0.load().unwrap(); + let scope = StatsScope::for_repertoire(ids[1].clone(), LearningSide::White, 0); + let key = active_learning_keys(&library, &scope) + .unwrap() + .into_iter() + .next() + .unwrap(); + learning.ensure_item(key.clone()).introduced = true; + let data = LearningStoreData { + learning, + ..LearningStoreData::default() + }; + std::fs::write( + dir.0.join("repertoire-training.json"), + serde_json::to_vec(&data).unwrap(), + ) + .unwrap(); + let mut ui = dir.ui(); + ui.select(ids[1].clone()); + ui.dialog = Some(Dialog::Delete { id: ids[1].clone() }); + ui.delete_selected(); + assert!(ui.dialog.is_none()); + assert_eq!(ui.selected, Some(ids[2].clone())); + assert!(ui.library.repertoire(&ids[1]).is_none()); + let kept = dir.stores().1.load().unwrap(); + assert!(kept.learning.item(&key).is_some_and(|item| item.introduced)); +} + +#[test] +fn a_session_needs_no_question_to_go_back_and_counts_refresh_after_it() { + let dir = TestDir::new("session-back"); + save_library(&dir, &[("Scotch", "1. e4 e5 2. Nf3 Nc6 3. d4 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + settle(&mut ui, &ctx, &mut settings, size); + let id = ui.selected.clone().unwrap(); + assert_eq!(ui.selected_card(), CardState::OnlyNew { new: 3 }); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Session(_))); + ui.debug_moves("settle answer settle"); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Repertoires)); + // e4 was shown and played: it is due again today. Nf3 was on the board, unplayed, + // when the session stopped: like d4 it is still new. + let stats = ui.stats.get(&id).unwrap().as_ref().unwrap(); + assert_eq!((stats.unseen, stats.due), (2, 1)); +} + +#[test] +fn starter_repertoires_are_created_once_with_their_colours() { + let dir = TestDir::new("starter"); + let (store, _) = dir.stores(); + let sides = seed_starter(&store).unwrap(); + let library = store.load().unwrap(); + assert_eq!(library.repertoires.len(), 4); + assert_eq!( + sides.iter().map(|(_, side)| *side).collect::>(), + [ + LearningSide::White, + LearningSide::Black, + LearningSide::White, + LearningSide::Black + ] + ); + for (id, _) in &sides { + let repertoire = library.repertoire(id).unwrap(); + assert!(!layout::lines(&repertoire.game(), |_| false).is_empty()); + } + assert_eq!( + library + .repertoires + .iter() + .map(|r| r.name.as_str()) + .collect::>(), + [ + "Spanish Opening", + "Sicilian Defence: Najdorf", + "Queen's Gambit", + "Semi-Slav: Triangle" + ] + ); + + let mut settings = Settings::default(); + let mut ui = dir.ui(); + ui.starter_sides = sides; + egui::__run_test_ui(|egui_ui| { + ui.show(egui_ui, &mut settings); + }); + let black = &library.repertoires[1].id; + assert_eq!(layout::side_of(&settings, black), LearningSide::Black); + + assert!(seed_starter(&store).unwrap().is_empty()); + assert_eq!(store.load().unwrap().repertoires.len(), 4); +} + +#[test] +fn starter_repertoires_come_to_an_empty_library_of_2_3() { + let dir = TestDir::new("starter-existing"); + let (store, _) = dir.stores(); + store.save(&mut Library::default()).unwrap(); + assert_eq!(seed_starter(&store).unwrap().len(), 4); + assert_eq!(store.load().unwrap().repertoires.len(), 4); +} + +#[test] +fn starter_examples_of_2_4_0_are_not_doubled() { + let dir = TestDir::new("starter-240"); + // 2.4.0 created the examples in the interface language and kept no marks. + save_library( + &dir, + &[ + ("ИÑ�панÑ�каÑ� партиÑ�", "1. e4 e5 *"), + ("Sicilian Defence: Najdorf", "1. e4 c5 *"), + ], + ); + let (store, _) = dir.stores(); + let sides = seed_starter(&store).unwrap(); + assert_eq!( + sides.iter().map(|(_, side)| *side).collect::>(), + [LearningSide::White, LearningSide::Black] + ); + let names: Vec<_> = store + .load() + .unwrap() + .repertoires + .into_iter() + .map(|r| r.name) + .collect(); + assert_eq!( + names, + [ + "ИÑ�панÑ�каÑ� партиÑ�", + "Sicilian Defence: Najdorf", + "Queen's Gambit", + "Semi-Slav: Triangle" + ] + ); + assert!(seed_starter(&store).unwrap().is_empty()); +} + +#[test] +fn a_deleted_starter_does_not_come_back() { + let dir = TestDir::new("starter-deleted"); + let (store, _) = dir.stores(); + seed_starter(&store).unwrap(); + let mut library = store.load().unwrap(); + let id = library.repertoires[2].id.clone(); + library.delete(&id).unwrap(); + store.save(&mut library).unwrap(); + assert!(seed_starter(&store).unwrap().is_empty()); + let library = store.load().unwrap(); + assert_eq!(library.repertoires.len(), 3); + assert!( + library + .repertoires + .iter() + .all(|r| r.name != "Queen's Gambit") + ); +} + +#[test] +fn starters_leave_own_repertoires_and_progress_alone() { + let dir = TestDir::new("starter-own"); + let ids = save_library(&dir, &[("Mine", "1. d4 d5 2. c4 e6 *")]); + let (store, learning) = dir.stores(); + std::fs::write(learning.path(), b"progress bytes").unwrap(); + let before = serde_json::to_value(store.load().unwrap().repertoire(&ids[0]).unwrap()).unwrap(); + assert_eq!(seed_starter(&store).unwrap().len(), 4); + let library = store.load().unwrap(); + assert_eq!(library.repertoires.len(), 5); + assert_eq!( + serde_json::to_value(library.repertoire(&ids[0]).unwrap()).unwrap(), + before + ); + assert_eq!(std::fs::read(learning.path()).unwrap(), b"progress bytes"); +} + +#[test] +fn starters_are_not_doubled_when_their_marks_were_lost() { + let dir = TestDir::new("starter-lost-marks"); + let (store, _) = dir.stores(); + seed_starter(&store).unwrap(); + // A failed write of the marks, or marks from another copy that did not see them. + std::fs::remove_file(starter_marks_path(&store)).unwrap(); + assert!(seed_starter(&store).unwrap().is_empty()); + std::fs::write(starter_marks_path(&store), br#"{"version":1,"given":[]}"#).unwrap(); + assert!(seed_starter(&store).unwrap().is_empty()); + assert_eq!(store.load().unwrap().repertoires.len(), 4); +} + +#[test] +fn two_copies_starting_together_give_the_starters_once() { + for round in 0..20 { + let dir = TestDir::new(&format!("starter-race-{round}")); + let (store, _) = dir.stores(); + let results: Vec<_> = std::thread::scope(|s| { + let a = s.spawn(|| seed_starter(&store.clone())); + let b = s.spawn(|| seed_starter(&store.clone())); + vec![a.join().unwrap(), b.join().unwrap()] + }); + let added: usize = results.iter().map(|r| r.as_ref().unwrap().len()).sum(); + assert_eq!(added, 4); + assert_eq!(store.load().unwrap().repertoires.len(), 4); + } +} + +#[test] +fn damaged_starter_marks_give_a_short_message_and_change_nothing() { + let dir = TestDir::new("starter-damaged"); + let (store, _) = dir.stores(); + store.save(&mut Library::default()).unwrap(); + let path = starter_marks_path(&store); + std::fs::write(&path, br#"{"version":1,"given":["#).unwrap(); + let error = seed_starter(&store).unwrap_err(); + assert_eq!( + error, + "The record of example repertoires is damaged; examples were not added" + ); + assert!(!error.contains(&*dir.0.to_string_lossy())); + assert_eq!(std::fs::read(&path).unwrap(), br#"{"version":1,"given":["#); + assert!(store.load().unwrap().repertoires.is_empty()); +} + +#[test] +fn starter_marks_of_an_unknown_version_are_left_alone() { + let dir = TestDir::new("starter-newer"); + let (store, _) = dir.stores(); + store.save(&mut Library::default()).unwrap(); + let path = starter_marks_path(&store); + std::fs::write(&path, br#"{"version":99,"given":5}"#).unwrap(); + assert!(seed_starter(&store).unwrap().is_empty()); + assert_eq!( + std::fs::read(&path).unwrap(), + br#"{"version":99,"given":5}"# + ); + assert!(store.load().unwrap().repertoires.is_empty()); +} + +#[test] +fn the_panel_opens_at_the_width_the_user_dragged_it_to() { + let dir = TestDir::new("side-width"); + save_library(&dir, &[("Italian", "1. e4 e5 2. Nf3 Nc6 3. Bc4 *")]); + let size = vec2(1920.0, 1080.0); + for (kept, width) in [ + (Some(400.0_f32), 400.0), + (Some(100.0), 360.0), + (None, 560.0), + ] { + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + // As the app does: the saved width is given once the context runs. + ctx.run_ui(egui::RawInput::default(), |_| {}) + .drop_without_applying_deltas(); + if let Some(kept) = kept { + ctx.data_mut(|d| { + d.insert_temp(egui::Id::new(crate::opening_layout::SIDE_WIDTH_ID), kept) + }); + } + settle(&mut ui, &ctx, &mut settings, size); + let rect = panel_rect(&ctx); + assert!((rect.width() - width).abs() <= 1.0, "{rect:?} for {kept:?}"); + } +} + +#[test] +fn a_window_that_grows_gives_the_panel_the_width_of_its_final_size() { + let dir = TestDir::new("side-grow"); + save_library(&dir, &[("Italian", "1. e4 e5 2. Nf3 Nc6 3. Bc4 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + settle(&mut ui, &ctx, &mut settings, vec2(960.0, 600.0)); + settle(&mut ui, &ctx, &mut settings, vec2(1920.0, 1080.0)); + let rect = panel_rect(&ctx); + assert!((rect.width() - 560.0).abs() <= 1.0, "{rect:?}"); +} + +#[test] +fn the_table_fits_the_least_panel_in_every_language() { + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + for lang in crate::i18n::Lang::ALL { + crate::i18n::set_lang(lang); + ctx.run_ui(egui::RawInput::default(), |root| { + egui::CentralPanel::default().show(root, |ui| { + // The table's width in a panel at its least: its frame takes 8 on each side. + let width = crate::opening_layout::SIDE_LEAST - 16.0; + let columns = table_widths(ui, width); + let gap = ui.spacing().item_spacing.x; + assert!( + columns.least(gap) <= width, + "{lang:?}: {columns:?} + gaps > {width}" + ); + assert!(columns.name_least >= NAME_WANTED, "{lang:?}: {columns:?}"); + // The bar, 6 px and the number from the left fit for any count, the + // header from the bar's left edge too; the bar keeps off «Today». + let body = |text: &str| style_width(ui, text, egui::TextStyle::Body); + for number in ["0/22", "12/22", "00/000"] { + assert!( + columns.start + columns.bar + MINI_BAR_GAP + body(number) + <= columns.passed - 4.0 + 0.5, + "{lang:?}: {number} in {columns:?}" + ); + } + assert!(columns.start + body(tr("Passed")) <= columns.passed - 4.0 + 0.5); + assert!( + // Unless the header itself takes the whole column. + columns.start + gap >= PASSED_GAP - 0.5 || columns.start < 1.0, + "{lang:?}: {columns:?}" + ); + }); + }) + .drop_without_applying_deltas(); + } + crate::i18n::set_lang(crate::i18n::Lang::En); +} + +#[test] +fn a_review_date_is_short_in_the_table() { + use chrono::{Local, TimeZone}; + let now = Local + .with_ymd_and_hms(2026, 11, 27, 9, 0, 0) + .single() + .unwrap() + .timestamp(); + assert_eq!(when_short(now + 3 * 60 * 60 + 30 * 60, now), "12:30"); + assert_eq!(when_short(now + 40 * 24 * 60 * 60, now), "06.01"); +} + +/// The comments of a PGN text: what stands in braces. +fn pgn_comments(pgn: &str) -> String { + let mut out = String::new(); + let mut depth = 0; + for c in pgn.chars() { + match c { + '{' => depth += 1, + '}' => depth -= 1, + c if depth > 0 => out.push(c), + _ => {} + } + } + out +} + +fn cyrillic(text: &str) -> bool { + text.chars() + .any(|c| ('а'..='Ñ�').contains(&c.to_lowercase().next().unwrap_or(c))) +} + +#[test] +fn starter_comments_follow_the_interface_language() { + for (lang, russian) in [ + (crate::i18n::Lang::Ru, true), + (crate::i18n::Lang::En, false), + (crate::i18n::Lang::De, false), + ] { + crate::i18n::set_lang(lang); + let dir = TestDir::new(&format!("starter-lang-{lang:?}")); + let (store, _) = dir.stores(); + assert_eq!(seed_starter(&store).unwrap().len(), 4); + for repertoire in store.load().unwrap().repertoires { + let comments = pgn_comments(&repertoire.pgn); + assert!(!comments.trim().is_empty(), "{lang:?} {}", repertoire.name); + assert_eq!( + cyrillic(&comments), + russian, + "{lang:?} {}: {comments}", + repertoire.name + ); + } + } + crate::i18n::set_lang(crate::i18n::Lang::En); +} + +#[test] +fn a_given_starter_keeps_its_comments_when_the_language_changes() { + let dir = TestDir::new("starter-lang-kept"); + let (store, _) = dir.stores(); + crate::i18n::set_lang(crate::i18n::Lang::En); + seed_starter(&store).unwrap(); + let before = std::fs::read(store.path()).unwrap(); + crate::i18n::set_lang(crate::i18n::Lang::Ru); + assert!(seed_starter(&store).unwrap().is_empty()); + assert_eq!(std::fs::read(store.path()).unwrap(), before); + crate::i18n::set_lang(crate::i18n::Lang::En); +} + +/// Every line of moves of a PGN, as UCI paths from the start, comments aside. +fn move_tree(pgn: &str) -> Vec> { + let cancel = AtomicBool::new(false); + let db = PgnDatabase::from_bytes(pgn.as_bytes().to_vec(), None, &mut |_| {}, &cancel).unwrap(); + let mut lines = Vec::new(); + for index in 0..db.len() { + let game = db.load_game(index).unwrap().game; + let mut stack = vec![(NodeId::ROOT, Vec::new())]; + while let Some((node, path)) = stack.pop() { + let children = game.children(node); + if children.is_empty() { + lines.push(path); + continue; + } + for child in children { + let mut next = path.clone(); + next.push(game.move_label(*child).unwrap_or_default()); + stack.push((*child, next)); + } + } + } + lines.sort(); + lines +} + +#[test] +fn russian_and_english_starters_have_the_same_moves() { + for starter in &STARTER_REPERTOIRES { + assert_eq!( + move_tree(starter.pgn), + move_tree(starter.pgn_ru), + "{}", + starter.key + ); + assert!(!move_tree(starter.pgn).is_empty(), "{}", starter.key); + } +} diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs new file mode 100644 index 0000000..56181ee --- /dev/null +++ b/apps/desktop/src/review.rs @@ -0,0 +1,1058 @@ +//! Whole-game analysis on the desktop: the background engine job over the main line, +//! the evaluation graph under the board and the report tab. The +//! evaluations, judgements, cache and the job itself are the `game-review` crate's, +//! shared with the Android app. +//! +//! The job uses engine processes of its own — Stockfish 19 (ChessPenguin's, or the user's +//! that searches the same, `review_engine`) with the fixed search of `game_review::run`, +//! the same on every computer — and +//! never touches the game; writing the results into the game is a separate, undoable +//! action ([`Review::write_to_game`]). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; + +use chess_core::shakmaty::{Color, Move}; +use chess_core::{Game, Nag, NodeId}; +use egui::{Color32, RichText, Sense, Stroke, Ui, pos2, vec2}; +use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement}; + +pub use game_review::Mark; + +use crate::i18n::{tr, trf}; +use crate::settings::Settings; + +pub enum ReportAction { + Goto(NodeId), + Write, + /// Evaluate what is missing (all of it for a stale analysis). + Update, + /// The engine over evaluations read from the PGN. + Analyse, +} + +/// What an engine job sends to the screen. +pub enum JobMsg { + Event(JobEvent), + Done, + Failed(String), +} + +/// An engine job under way. On a computer its thread sends everything through the +/// channel; in a browser its engines are Web Workers driven from the frames: +/// [`JobRunner::pump`] passes on what they gave. +pub struct JobRunner { + #[cfg(web)] + dispatcher: game_review::Dispatcher, + #[cfg(web)] + tx: std::sync::mpsc::Sender, + #[cfg(web)] + cancel: Arc, +} + +impl JobRunner { + /// Call every frame (nothing to do on a computer). + pub fn pump(&mut self) { + #[cfg(web)] + { + if self.cancel.load(Ordering::Relaxed) { + self.dispatcher.cancel(); + } + let (events, end) = self.dispatcher.poll(); + for e in events { + let _ = self.tx.send(JobMsg::Event(e)); + } + if let Some(end) = end { + let _ = self.tx.send(job_end(end)); + } + } + } +} + +/// The last message of a job. +fn job_end(result: Result<(), JobFailure>) -> JobMsg { + match result { + Ok(()) => JobMsg::Done, + Err(JobFailure::Start(e) | JobFailure::Engine(e)) => JobMsg::Failed(e), + Err(JobFailure::Terminated(reason)) => { + JobMsg::Failed(crate::analysis::termination_message(&reason)) + } + } +} + +/// Engines working at once for a job: one per logical CPU, as many as fit. +pub fn processes() -> usize { + #[cfg(web)] + return crate::platform::web::engine::workers(game_review::MAX_PROCESSES); + #[cfg(not(web))] + game_review::processes(game_review::MAX_PROCESSES) +} + +/// Runs the engine job over `targets` with ChessPenguin's Stockfish at `path` (in a +/// browser: the address of its worker) named `name`: its events and its end come +/// through `tx`, each waking `ctx`. +pub fn spawn_job( + name: &str, + engine: crate::engines::EngineLocation, + settings: JobSettings, + targets: Vec, + cancel: Arc, + tx: std::sync::mpsc::Sender, + ctx: egui::Context, +) -> std::io::Result { + #[cfg(not(web))] + { + let crate::engines::EngineLocation::Program(path) = engine; + std::thread::Builder::new() + .name(name.to_owned()) + .spawn(move || { + // A user's engine must still be the Stockfish 19 probed (a wrapper may + // start another program now): else the job stops at once, before any + // evaluation is taken, and the engine is probed again next time. + let mut changed = false; + let result = game_review::run( + engine_config(&path), + &settings, + targets, + &cancel, + &mut |e| { + if changed { + return; + } + if let JobEvent::Engine(name) = &e + && !crate::review_engine::name_fits(&path, name) + { + changed = true; + cancel.store(true, Ordering::Relaxed); + return; + } + let _ = tx.send(JobMsg::Event(e)); + ctx.request_repaint(); + }, + ); + let end = if changed { + JobMsg::Failed( + tr("The engine is no longer the Stockfish 19 that was checked. Start the analysis again.") + .into(), + ) + } else { + job_end(result) + }; + let _ = tx.send(end); + ctx.request_repaint(); + }) + .map(|_| JobRunner {}) + } + #[cfg(web)] + { + let _ = name; + let crate::engines::EngineLocation::Worker(script) = engine; + let wake: Arc = Arc::new(move || ctx.request_repaint()); + game_review::Dispatcher::start(&script, &settings, targets, wake) + .map(|dispatcher| JobRunner { + dispatcher, + tx, + cancel, + }) + .map_err(|e| match e { + JobFailure::Start(e) | JobFailure::Engine(e) => std::io::Error::other(e), + JobFailure::Terminated(r) => { + std::io::Error::other(crate::analysis::termination_message(&r)) + } + }) + } +} + +struct Job { + runner: JobRunner, + rx: Receiver, + cancel: Arc, + total: usize, + done: usize, +} + +impl Drop for Job { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +pub struct Review { + /// Evaluations of the main line and the report built from them. + pub analysis: GameAnalysis, + job: Option, + pub error: Option, + /// Graph and report tab are shown. + pub visible: bool, + /// Measured speed of one engine thread, for time estimates. + nps_per_thread: Option, + /// Report tab: index of the last visited error per side and kind. + cycle: HashMap<(Color, Judgement), usize>, +} + +/// The folder of the cached analyses. +pub fn cache_dir() -> Option { + Settings::cache_dir().map(|d| d.join("analysis")) +} + +/// The cached analyses in the program's files (the platform's: a folder of the disk, or +/// the browser's storage). +pub struct Cache(pub PathBuf); + +impl game_review::CacheStore for Cache { + fn read(&self, name: &str) -> Option> { + crate::platform::fs::read(&self.0.join(name)).ok() + } + + fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> { + crate::platform::fs::write_atomic(&self.0.join(name), bytes) + } +} + +impl Review { + pub fn new(game: &Game) -> Self { + let cache = cache_dir().map(Cache); + let analysis = GameAnalysis::with_store( + game, + cache.as_ref().map(|c| c as &dyn game_review::CacheStore), + ); + Review { + visible: analysis.has_data(), + analysis, + job: None, + error: None, + nps_per_thread: None, + cycle: HashMap::new(), + } + } + + pub fn has_data(&self) -> bool { + self.analysis.has_data() + } + + pub fn running(&self) -> bool { + self.job.is_some() + } + + pub fn progress(&self) -> Option<(usize, usize)> { + self.job.as_ref().map(|j| (j.done, j.total)) + } + + /// Positions of the current main line without an evaluation. + pub fn missing(&self) -> usize { + self.analysis.missing() + } + + /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. + pub fn refresh(&mut self, game: &Game) { + self.analysis.refresh(game); + } + + /// Starts the engine job with the engine at `path` (ChessPenguin's Stockfish). `full` + /// discards earlier results; otherwise only positions without an evaluation are + /// analysed (all of them for a stale analysis). Returns false if there is nothing to do. + pub fn start( + &mut self, + game: &Game, + engine: &crate::engines::EngineLocation, + full: bool, + ctx: &egui::Context, + ) -> bool { + self.job = None; + self.error = None; + let targets = self.analysis.begin(game, full); + if targets.is_empty() { + return false; + } + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = targets.len(); + let settings = JobSettings::new(processes(), None); + let spawned = spawn_job( + "game-review", + engine.clone(), + settings, + targets, + cancel.clone(), + tx, + ctx.clone(), + ); + let runner = match spawned { + Ok(r) => r, + Err(e) => { + self.error = Some(e.to_string()); + return false; + } + }; + self.job = Some(Job { + runner, + rx, + cancel, + total, + done: 0, + }); + self.visible = true; + true + } + + pub fn cancel(&mut self) { + if self.job.take().is_some() { + self.save_cache(); + } + } + + /// Collects job results; returns true when the job has just ended. + pub fn poll(&mut self) -> bool { + let Some(job) = &mut self.job else { + return false; + }; + let mut ended = false; + job.runner.pump(); + while let Ok(msg) = job.rx.try_recv() { + match msg { + JobMsg::Event(e) => { + if let JobEvent::Eval { nps, .. } = &e { + job.done += 1; + // One engine thread per process. + if *nps > 0 { + self.nps_per_thread = Some(*nps as f64); + } + } + self.analysis.apply(e); + } + JobMsg::Done => ended = true, + JobMsg::Failed(e) => { + self.error = Some(e); + ended = true; + } + } + } + if ended { + self.job = None; + self.save_cache(); + } + ended + } + + /// Engine speed per thread for estimates: measured here, else from the live engine. + pub fn note_live_speed(&mut self, nps: u64, threads: u32) { + if self.nps_per_thread.is_none() && nps > 0 { + self.nps_per_thread = Some(nps as f64 / f64::from(threads.max(1))); + } + } + + /// "64 positions, about 20 s": what a full analysis of the game takes. + pub fn estimate(&self) -> String { + let secs = game_review::estimate_secs( + self.analysis.searches(), + self.nps_per_thread.unwrap_or(DEFAULT_NPS), + processes(), + ); + trf( + "{n} positions, about {time}", + &[ + ("n", &self.analysis.positions()), + ("time", &format_duration(secs)), + ], + ) + } + + /// After an inaccuracy, mistake or blunder: how the opponent punishes it and how + /// the player best answers (shown as arrows, as on Lichess). + pub fn refutation(&self, node: NodeId, game: &Game) -> Vec { + self.analysis.refutation(node, game) + } + + fn save_cache(&self) { + if let Some(dir) = cache_dir() + && let Err(e) = self.analysis.save_to(&Cache(dir.clone())) + { + eprintln!("review cache: {}: {e}", dir.display()); + } + } + + // ----- writing into the game ------------------------------------------------- + + /// Adds `[%eval]` to every main-line move and, for marked moves, a move-assessment + /// NAG (unless the author gave one) and a comment; for errors also the better line as + /// a variation. One undo step. Returns the number of marked moves. + pub fn write_to_game(&self, game: &mut Game) -> usize { + game.edit_group(|g| { + let mut errors = 0; + for i in 1..self.analysis.line().len() { + let id = self.analysis.line()[i]; + let Some(node) = g.node(id) else { continue }; + let mut nags = node.nags().to_vec(); + let mut comments: Vec = node + .comments_after() + .iter() + .map(|c| strip_eval(c)) + .filter(|c| !c.trim().is_empty()) + .collect(); + if let Some(e) = self.analysis.values()[i] + && !matches!(e, Eval::Mate { moves: 0, .. }) + { + comments.insert(0, format!("[%eval {}]", e.pgn())); + } + if let Some(mark) = self.analysis.marks.get(&id) { + // The author's own sign stands; praise over it would contradict it. + let authored = nags.iter().any(|n| n.is_move_assessment()); + if !mark.judgement.is_error() && authored { + let _ = g.annotate(id, nags, comments); + continue; + } + errors += 1; + if !authored { + nags.push(judgement_nag(mark.judgement)); + } + let name = judgement_name(mark.judgement); + let text = match &mark.best_label { + Some(best) => trf( + "{judgement}. {best} was best.", + // Written into the game: Latin, as PGN always is. + &[("judgement", &name), ("best", best)], + ), + None => format!("{name}."), + }; + if !comments.contains(&text) { + comments.push(text); + } + if !mark.best.is_empty() { + let _ = g.add_line(mark.base, &mark.best[..mark.best.len().min(8)]); + } + } + let _ = g.annotate(id, nags, comments); + } + errors + }) + } + + // ----- UI -------------------------------------------------------------------- + + /// Evaluation graph; returns a main-line node to go to (click or drag). + pub fn graph( + &self, + ui: &mut Ui, + size: egui::Vec2, + cursor: NodeId, + game: &Game, + ) -> Option { + let (rect, resp) = ui.allocate_exact_size(size, Sense::click_and_drag()); + let painter = ui.painter_at(rect); + let visuals = ui.visuals(); + painter.rect_filled(rect, 4.0, visuals.extreme_bg_color); + let n = self.analysis.values().len(); + if n < 2 { + return None; + } + let inner = rect.shrink2(vec2(6.0, 6.0)); + let x_of = |i: usize| inner.left() + inner.width() * i as f32 / (n - 1) as f32; + let y_of = |wp: f64| inner.bottom() - inner.height() * (wp / 100.0) as f32; + let mid = y_of(50.0); + let wp: Vec> = self + .analysis + .values() + .iter() + .map(|v| v.map(|e| e.win_percent(Color::White))) + .collect(); + let (white_fill, black_fill) = if visuals.dark_mode { + (Color32::from_gray(150), Color32::from_gray(8)) + } else { + (Color32::from_gray(255), Color32::from_gray(70)) + }; + + // Phase boundaries. + let phase_line = Stroke::new(1.0, visuals.weak_text_color().gamma_multiply(0.6)); + let font = egui::FontId::proportional(11.0); + // Labels go right of their boundary, or left of it when they would not fit. + let label = |x: f32, text: &str| { + let galley = + painter.layout_no_wrap(text.to_string(), font.clone(), visuals.weak_text_color()); + let w = galley.size().x; + let left = if x + 4.0 + w > rect.right() - 4.0 { + x - 4.0 - w + } else { + x + 4.0 + }; + painter.galley( + pos2(left, rect.top() + 3.0), + galley, + visuals.weak_text_color(), + ); + }; + if self + .analysis + .report + .phases + .middlegame + .is_some_and(|m| m > 0) + { + label(inner.left(), tr("Opening")); + } + for (idx, name) in [ + (self.analysis.report.phases.middlegame, tr("Middlegame")), + (self.analysis.report.phases.endgame, tr("Endgame")), + ] { + if let Some(i) = idx { + let x = x_of(i); + if i > 0 { + painter.vline(x, rect.y_range(), phase_line); + } + label(x, name); + } + } + + // Advantage areas between the curve and the middle line. + for i in 0..n - 1 { + let (Some(a), Some(b)) = (wp[i], wp[i + 1]) else { + continue; + }; + let (x0, x1, y0, y1) = (x_of(i), x_of(i + 1), y_of(a), y_of(b)); + let fill = |pts: Vec, above: bool| { + painter.add(egui::Shape::convex_polygon( + pts, + if above { white_fill } else { black_fill }, + Stroke::NONE, + )); + }; + if (a >= 50.0) == (b >= 50.0) { + fill( + vec![pos2(x0, mid), pos2(x0, y0), pos2(x1, y1), pos2(x1, mid)], + a >= 50.0, + ); + } else { + let t = ((50.0 - a) / (b - a)) as f32; + let xc = x0 + (x1 - x0) * t; + fill(vec![pos2(x0, mid), pos2(x0, y0), pos2(xc, mid)], a >= 50.0); + fill(vec![pos2(xc, mid), pos2(x1, y1), pos2(x1, mid)], b >= 50.0); + } + } + painter.hline( + inner.x_range(), + mid, + Stroke::new(1.0, visuals.weak_text_color().gamma_multiply(0.5)), + ); + + // The curve, broken where positions are not evaluated yet. + let curve = Stroke::new(1.6, Color32::from_rgb(0xe0, 0x7b, 0x1f)); + let mut run: Vec = Vec::new(); + for (i, v) in wp.iter().enumerate() { + match v { + Some(w) => run.push(pos2(x_of(i), y_of(*w))), + None => { + if run.len() > 1 { + painter.add(egui::Shape::line(std::mem::take(&mut run), curve)); + } + run.clear(); + } + } + } + if run.len() > 1 { + painter.add(egui::Shape::line(run, curve)); + } + for (i, j) in self.analysis.report.judgements.iter().enumerate() { + if let (Some(j), Some(w)) = (j, wp[i + 1]) { + painter.circle_filled(pos2(x_of(i + 1), y_of(w)), 3.5, judgement_color(*j)); + } + } + + // Current move. + if let Some(ci) = self.line_index(cursor, game) { + painter.vline(x_of(ci), rect.y_range(), Stroke::new(1.5, curve.color)); + } + if let Some((done, total)) = self.progress() { + painter.text( + rect.right_top() + vec2(-6.0, 3.0), + egui::Align2::RIGHT_TOP, + format!("{done}/{total}"), + egui::FontId::proportional(11.0), + visuals.text_color(), + ); + } + + let index_at = |x: f32| { + let t = ((x - inner.left()) / inner.width()).clamp(0.0, 1.0); + (t * (n - 1) as f32).round() as usize + }; + if let Some(p) = resp.hover_pos() { + let i = index_at(p.x); + painter.vline( + x_of(i), + rect.y_range(), + Stroke::new(1.0, visuals.weak_text_color()), + ); + let label = if i == 0 { + tr("Start position").to_string() + } else { + crate::san::show(&game.move_label(self.analysis.line()[i]).unwrap_or_default()) + .into_owned() + }; + let eval = self.analysis.values()[i] + .map(Eval::format) + .unwrap_or_else(|| "…".into()); + let mark = self + .analysis + .report + .judgements + .get(i.wrapping_sub(1)) + .copied() + .flatten(); + resp.clone().on_hover_ui_at_pointer(|ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(label).strong()); + ui.label(eval); + if let Some(j) = mark { + ui.label( + RichText::new(judgement_name(j)) + .color(judgement_text_color(j, ui.visuals().dark_mode)), + ); + } + }); + }); + } + if (resp.clicked() || resp.dragged()) + && let Some(p) = resp.interact_pointer_pos() + { + let target = self.analysis.line()[index_at(p.x)]; + if target != cursor { + return Some(target); + } + } + None + } + + /// Index in the main line of `cursor`, or of the main-line move a variation leaves from. + fn line_index(&self, cursor: NodeId, game: &Game) -> Option { + self.analysis.line_index(cursor, game) + } + + /// Report tab: per-player statistics in the Lichess layout. + pub fn report_ui(&mut self, ui: &mut Ui, game: &Game) -> Option { + let mut action = None; + ui.add_space(6.0); + for color in [Color::White, Color::Black] { + if let Some(a) = self.side_block(ui, game, color) { + action = Some(a); + } + ui.add_space(10.0); + } + ui.separator(); + if let Some(meta) = &self.analysis.meta { + let source = if meta.nodes == 0 { + tr("Evaluations from the PGN ([%eval])").to_string() + } else { + trf( + "{engine} · {nodes} nodes per move", + &[ + ("engine", &meta.engine), + ("nodes", &format_count(meta.nodes)), + ], + ) + }; + ui.label(RichText::new(source).small().weak()); + if meta.nodes == 0 { + ui.label( + RichText::new(tr("!! and ! need the engine: the PGN has evaluations only")) + .small() + .weak(), + ); + } + } + if let Some(e) = &self.error { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + let missing = self.missing(); + // An analysis from before !! and !: "Update" looks for them, nothing else. + let seconds = self.analysis.seconds_missing(); + // An analysis of another search: "Update" makes it again. + let stale = self.analysis.stale(); + if (stale || missing > 0 || seconds > 0) && !self.running() { + ui.horizontal_wrapped(|ui| { + let text = if stale { + tr("This analysis was made with other engine settings").to_string() + } else if missing > 0 { + trf("Positions without evaluation: {n}", &[("n", &missing)]) + } else { + tr("!! and ! were not looked for in this analysis").to_string() + }; + ui.label(RichText::new(text).color(ui.visuals().warn_fg_color)); + let can_update = self.analysis.meta.as_ref().is_some_and(|m| m.nodes > 0); + if can_update { + // Stale: everything again («Обновить»); otherwise the gaps («Дополнить»). + let mut button = ui.button(if stale { + tr("Analyse again") + } else { + tr("Update") + }); + if stale { + button = button.on_hover_text(tr( + "Every position is analysed again, the same way on every computer", + )); + } + if button.clicked() { + action = Some(ReportAction::Update); + } + } + }); + } + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + if ui + .add_enabled( + !self.running() && self.has_data(), + egui::Button::new(tr("Write analysis to the game")), + ) + .on_hover_text(tr( + "Adds evaluations, !!/!/?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", + )) + .clicked() + { + action = Some(ReportAction::Write); + } + // Evaluations of the PGN: the engine can make its own (an engine analysis + // made again would only repeat itself). + let pgn_only = self.analysis.meta.as_ref().is_some_and(|m| m.nodes == 0); + if pgn_only + && ui + .add_enabled(!self.running(), egui::Button::new(tr("Analyse with the engine"))) + .on_hover_text(self.estimate()) + .clicked() + { + action = Some(ReportAction::Analyse); + } + }); + action + } + + fn side_block(&mut self, ui: &mut Ui, game: &Game, color: Color) -> Option { + let mut action = None; + let name = game + .tag(if color == Color::White { + "White" + } else { + "Black" + }) + .filter(|s| !s.is_empty() && *s != "?") + .unwrap_or(if color == Color::White { + tr("White") + } else { + tr("Black") + }) + .to_string(); + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); + let stroke = Stroke::new(1.5, ui.visuals().text_color()); + if color == Color::White { + ui.painter() + .circle(r.center(), 6.0, Color32::from_gray(235), stroke); + } else { + ui.painter() + .circle(r.center(), 6.0, Color32::TRANSPARENT, stroke); + } + ui.label(RichText::new(name).strong().size(16.0)); + }); + let s = self.analysis.report.side(color).clone(); + let pgn_only = self.analysis.meta.as_ref().is_some_and(|m| m.nodes == 0); + egui::Grid::new(("review_side", color as u8)) + .num_columns(2) + .spacing(vec2(10.0, 3.0)) + .show(ui, |ui| { + for (j, count) in [ + (Judgement::Brilliant, s.brilliant), + (Judgement::Great, s.great), + (Judgement::Inaccuracy, s.inaccuracies), + (Judgement::Mistake, s.mistakes), + (Judgement::Blunder, s.blunders), + ] { + // From the PGN's evaluations alone !! and ! are not known: a dash, + // not a zero. A row with nothing in it stays quiet. + let unknown = !j.is_error() && pgn_only; + let c = if count > 0 { + judgement_text_color(j, ui.visuals().dark_mode) + } else { + ui.visuals().weak_text_color() + }; + let shown = if unknown { + "—".to_string() + } else { + count.to_string() + }; + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(shown).strong().size(15.0).color(c)); + }); + let text = RichText::new(judgement_plural(j)).size(15.0).color(c); + if count > 0 { + let resp = ui + .add(egui::Button::new(text).frame_when_inactive(false)) + .on_hover_text(tr("Go to the next one")); + if resp.clicked() + && let Some(id) = self.next_error(color, j) + { + action = Some(ReportAction::Goto(id)); + } + } else { + ui.label(text); + } + ui.end_row(); + } + let value_row = + |ui: &mut Ui, value: String, label: &str, color: Option| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut t = RichText::new(value).strong().size(15.0); + if let Some(c) = color { + t = t.color(c); + } + ui.label(t); + }); + let mut t = RichText::new(label).size(15.0); + if let Some(c) = color { + t = t.color(c); + } + // A long name ("Average centipawn loss") wraps in a narrow panel. + ui.add(egui::Label::new(t).wrap()); + ui.end_row(); + }; + let dash = || "—".to_string(); + value_row( + ui, + s.acpl.map_or_else(dash, |v| v.to_string()), + tr("Average centipawn loss"), + None, + ); + value_row( + ui, + s.accuracy.map_or_else(dash, percent), + tr("Accuracy"), + None, + ); + for (i, label) in [tr("Opening"), tr("Middlegame"), tr("Endgame")] + .into_iter() + .enumerate() + { + if let Some(a) = s.phase_accuracy[i] { + value_row( + ui, + percent(a), + label, + Some(accuracy_color(a, ui.visuals().dark_mode)), + ); + } + } + }); + action + } + + /// Next main-line move of `color` with judgement `j` (cycles). + fn next_error(&mut self, color: Color, j: Judgement) -> Option { + let hits = self.analysis.errors(color, j); + if hits.is_empty() { + return None; + } + let k = self.cycle.entry((color, j)).or_insert(usize::MAX); + *k = k.wrapping_add(1) % hits.len(); + Some(hits[*k]) + } +} + +impl Drop for Review { + fn drop(&mut self) { + // Leaving the game mid-analysis keeps what was computed. + self.cancel(); + } +} + +/// Nodes per second of one engine thread assumed until an engine was measured. +pub const DEFAULT_NPS: f64 = 700_000.0; + +/// ChessPenguin's Stockfish at `path` for an analysis job: below the program (nice 10), +/// so that the program stays smooth while every CPU works. +#[cfg(not(web))] +pub fn engine_config(path: &Path) -> uci::EngineConfig { + uci::EngineConfig { + nice: 10, + ..uci::EngineConfig::new(path) + } +} + +/// Removes `[%eval …]` commands from a comment. +fn strip_eval(c: &str) -> String { + let mut out = String::new(); + let mut rest = c; + while let Some(i) = rest.find("[%eval") { + out.push_str(&rest[..i]); + match rest[i..].find(']') { + Some(j) => rest = &rest[i + j + 1..], + None => { + rest = ""; + } + } + } + out.push_str(rest); + out.trim().to_string() +} + +/// A judgement's color: the same as its sign's NAG (`notation::assessment_color`). +pub fn judgement_color(j: Judgement) -> Color32 { + crate::notation::assessment_color(judgement_nag(j)).unwrap_or(Color32::GRAY) +} + +/// The color of a judgement as text: on a light background darker than the bright one +/// of the badges, as on Android. +pub fn judgement_text_color(j: Judgement, dark: bool) -> Color32 { + crate::notation::assessment_text_color(judgement_nag(j), dark).unwrap_or(Color32::GRAY) +} + +/// The NAG of the same sign. +pub fn judgement_nag(j: Judgement) -> Nag { + match j { + Judgement::Inaccuracy => Nag::DUBIOUS_MOVE, + Judgement::Mistake => Nag::MISTAKE, + Judgement::Blunder => Nag::BLUNDER, + Judgement::Great => Nag::GOOD_MOVE, + Judgement::Brilliant => Nag::BRILLIANT_MOVE, + } +} + +pub fn judgement_symbol(j: Judgement) -> &'static str { + match j { + Judgement::Inaccuracy => "?!", + Judgement::Mistake => "?", + Judgement::Blunder => "??", + Judgement::Great => "!", + Judgement::Brilliant => "!!", + } +} + +pub fn judgement_name(j: Judgement) -> &'static str { + match j { + Judgement::Inaccuracy => tr("Inaccuracy"), + Judgement::Mistake => tr("Mistake"), + Judgement::Blunder => tr("Blunder"), + Judgement::Great => tr("Great move"), + Judgement::Brilliant => tr("Brilliant move"), + } +} + +pub fn judgement_plural(j: Judgement) -> &'static str { + match j { + Judgement::Inaccuracy => tr("Inaccuracies"), + Judgement::Mistake => tr("Mistakes"), + Judgement::Blunder => tr("Blunders"), + Judgement::Great => tr("Great moves"), + Judgement::Brilliant => tr("Brilliant moves"), + } +} + +/// Accuracy in the colors of the move marks: green, blue, orange, red. +pub fn accuracy_color(a: f64, dark: bool) -> Color32 { + let j = if a >= 85.0 { + Judgement::Great + } else if a >= 70.0 { + Judgement::Inaccuracy + } else if a >= 50.0 { + Judgement::Mistake + } else { + Judgement::Blunder + }; + judgement_text_color(j, dark) +} + +fn percent(a: f64) -> String { + format!("{}%", a.round() as i64) +} + +/// 250 000 → "250k", 1 000 000 → "1M". +pub fn format_count(n: u64) -> String { + if n >= 1_000_000 && n.is_multiple_of(100_000) { + let m = n as f64 / 1e6; + if n.is_multiple_of(1_000_000) { + format!("{m:.0}M") + } else { + format!("{m:.1}M") + } + } else if n >= 1000 { + format!("{}k", n / 1000) + } else { + n.to_string() + } +} + +pub fn format_duration(secs: f64) -> String { + let s = secs.ceil().max(1.0) as u64; + if s < 60 { + trf("{n} s", &[("n", &s)]) + } else { + trf("{n} min", &[("n", &s.div_ceil(60))]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strip_eval_keeps_other_text() { + assert_eq!(strip_eval("[%eval 0.35] Good move"), "Good move"); + assert_eq!( + strip_eval("A [%eval #-3] B [%clk 0:01:00]"), + "A B [%clk 0:01:00]" + ); + assert_eq!(strip_eval("[%eval 1.0"), ""); + } + + #[test] + fn counts_are_compact() { + assert_eq!(format_count(250_000), "250k"); + assert_eq!(format_count(1_000_000), "1M"); + assert_eq!(format_count(1_500_000), "1.5M"); + } + + #[test] + fn pgn_evals_and_written_analysis_roundtrip() { + let mut game = chess_core::parse_str( + "1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} 2. Qh5 {[%eval -0.2]} Ke7 {[%eval 6.5]} \ + 3. Qxe5# 1-0", + ) + .game; + let mut r = Review::new(&game); + assert!(r.has_data() && r.visible); + assert_eq!(r.missing(), 0); + assert!(r.analysis.report.complete); + // 2…Ke7 throws the game away; 3.Qxe5# is a terminal position. + let ke7 = game.mainline()[3]; + assert_eq!( + r.analysis.marks.get(&ke7).map(|m| m.judgement), + Some(Judgement::Blunder) + ); + assert_eq!(r.analysis.report.black.blunders, 1); + + let errors = r.write_to_game(&mut game); + assert_eq!(errors, r.analysis.marks.len()); + let node = game.node(ke7).expect("node"); + assert!(node.nags().contains(&Nag::BLUNDER)); + assert!(node.comments_after()[0].starts_with("[%eval 6.50]")); + r.refresh(&game); + // Writing again replaces evaluations instead of duplicating them. + r.write_to_game(&mut game); + let n = game.node(ke7).expect("node"); + assert_eq!( + n.comments_after() + .iter() + .filter(|c| c.contains("[%eval")) + .count(), + 1 + ); + assert_eq!( + n.nags().iter().filter(|x| x.is_move_assessment()).count(), + 1 + ); + // Both writes are single undo steps. + game.undo(); + game.undo(); + assert!(!game.is_modified()); + r.cancel(); + } +} diff --git a/apps/desktop/src/review_engine.rs b/apps/desktop/src/review_engine.rs new file mode 100644 index 0000000..6ed3d12 --- /dev/null +++ b/apps/desktop/src/review_engine.rs @@ -0,0 +1,715 @@ +//! The engine of the game analysis and the search for opening errors: ChessPenguin's +//! Stockfish 19, or else a Stockfish 19 of the user's (from the settings, or the one in +//! `PATH`) that searches exactly as ours (decision of 2026-10-31). Whether it does is +//! told by `game_review::probe` on a thread of its own: an engine not called +//! «Stockfish 19» is turned down at its `uci` answer, without a search; one that is +//! makes three short searches of the analysis's fixed mode. The verdict is remembered +//! for the real file (links followed) with its size and time, and with the probe's +//! reference: a file is probed once, again when it or the reference changes. An engine +//! that did not start is not remembered: it is tried again at the next request. + +use crate::engines::EngineLocation; + +/// Why the user's engine does not do for the analysis. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Why { + /// Another engine, or another version of Stockfish. + Other, + /// It calls itself Stockfish 19 but searches otherwise (another build or network). + Differs, + /// It did not start or did not answer. + NotStarted, + /// It calls itself Stockfish 19 but did not finish the check in time (a slow or + /// stuck machine): not remembered, checked again at the next request. + TimedOut, +} + +/// The user's engine that does not do: its name (`id name`, else what the settings +/// call it, else its file's name), where it is from, and why. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Unfit { + pub name: String, + /// From the settings (else `stockfish` found in `PATH`). + pub from_settings: bool, + pub why: Why, +} + +/// The engine to analyse with, now. +#[derive(Debug, PartialEq, Eq)] +pub enum Lookup { + Ready(EngineLocation), + /// An engine of the user's is being probed: asked again when it is done (the + /// screen is repainted then). + Checking, + /// The user's engines do not do: the first of them. + Unfit(Unfit), + /// No engine at all. + None, +} + +/// The engine to analyse with, from what is known (nothing is probed here): ours, or a +/// user's engine already found to be the same. +pub fn engine() -> Option { + #[cfg(not(web))] + return crate::engines::own_stockfish().or_else(native::verified); + #[cfg(web)] + crate::engines::own_stockfish() +} + +/// The engines of the user's to consider, in this order: the active one, the others of +/// the settings, `stockfish` from `PATH`. Called at the start, when the settings are +/// saved and when an analysis asks for an engine (not every frame). +#[cfg_attr(web, allow(unused_variables))] +pub fn set_candidates(settings: &crate::settings::Settings) { + #[cfg(not(web))] + native::set_candidates(native::candidates(settings)); +} + +/// The engine to analyse with; an engine of the user's not probed yet (or changed since) +/// is probed now, in the background. +#[cfg_attr(web, allow(unused_variables))] +pub fn lookup(ctx: &egui::Context) -> Lookup { + #[cfg(not(web))] + return native::lookup(ctx); + #[cfg(web)] + match engine() { + Some(l) => Lookup::Ready(l), + None => Lookup::None, + } +} + +/// Whether the engine at `path`, which said it is `name` at the start of a job, is the +/// one probed: ours always is; a user's one must still call itself Stockfish 19 (a +/// wrapper script may start another program than it did). One that does not is +/// forgotten, to be probed again. +#[cfg(not(web))] +pub fn name_fits(path: &std::path::Path, name: &str) -> bool { + native::name_fits(path, name) +} + +/// The program quits: the probes under way stop, their engines quit (or are killed). +pub fn shutdown() { + #[cfg(not(web))] + native::shutdown(); +} + +#[cfg(not(web))] +mod native { + use std::collections::{HashMap, HashSet}; + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Mutex, OnceLock}; + use std::thread::JoinHandle; + + use game_review::probe::{ProbeLimits, STOCKFISH_19, reference_key}; + use serde::{Deserialize, Serialize}; + + use super::{Lookup, Unfit, Why}; + use crate::engines::EngineLocation; + + /// A probe's verdict on a file as it was. + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] + pub(super) struct Verdict { + pub size: u64, + pub modified: u64, + pub same: bool, + pub name: Option, + } + + /// What is kept on the disk: the verdicts and the reference they were made with. + #[derive(Serialize, Deserialize)] + pub(super) struct Kept { + pub reference: String, + pub engines: HashMap, + } + + /// An engine of the user's: its file as given, the real file (links followed), + /// what the settings call it, and whether it is from them. + #[derive(Clone, Debug, PartialEq)] + pub(super) struct Candidate { + pub path: PathBuf, + pub real: PathBuf, + pub label: String, + pub from_settings: bool, + } + + impl Candidate { + pub(super) fn new(path: PathBuf, label: String, from_settings: bool) -> Candidate { + Candidate { + real: path.canonicalize().unwrap_or_else(|_| path.clone()), + path, + label, + from_settings, + } + } + } + + #[derive(Default)] + pub(super) struct State { + pub candidates: Vec, + /// By the real file. + pub known: HashMap, + /// Files that did not start or did not finish the check, until it is said (by + /// the real file): why, and the name the engine gave. + pub failed: HashMap)>, + pub checking: HashSet, + pub threads: Vec>, + /// How long a probe may take (shorter in the tests). + pub limits: ProbeLimits, + /// Where the verdicts are kept (`None`: nowhere). + pub file: Option, + pub loaded: bool, + } + + fn state() -> &'static Mutex { + static STATE: OnceLock> = OnceLock::new(); + STATE.get_or_init(Default::default) + } + + /// Set when the program quits: the probes give up. + static QUITTING: AtomicBool = AtomicBool::new(false); + + fn with(f: impl FnOnce(&mut State) -> T) -> T { + let mut s = state().lock().unwrap_or_else(|e| e.into_inner()); + if !s.loaded { + s.loaded = true; + s.file = crate::settings::Settings::cache_dir().map(|d| d.join("review-engines.json")); + if let Some(bytes) = s.file.as_ref().and_then(|f| std::fs::read(f).ok()) { + s.known = read_kept(&bytes); + } + } + f(&mut s) + } + + /// The verdicts kept, if they were made with the probe of this program. + pub(super) fn read_kept(bytes: &[u8]) -> HashMap { + serde_json::from_slice::(bytes) + .ok() + .filter(|k| k.reference == reference_key()) + .map(|k| k.engines) + .unwrap_or_default() + } + + fn save(s: &State) { + let Some(f) = &s.file else { return }; + let kept = Kept { + reference: reference_key(), + engines: s.known.clone(), + }; + if let Ok(json) = serde_json::to_vec(&kept) { + let _ = crate::platform::fs::write_atomic(f, &json); + } + } + + pub(super) fn candidates(settings: &crate::settings::Settings) -> Vec { + let active = settings.active_engine.and_then(|i| settings.engines.get(i)); + let others = settings.engines.iter().filter(|e| Some(*e) != active); + let mut out: Vec = active + .into_iter() + .chain(others) + .filter(|e| !e.builtin) + .map(|e| Candidate::new(e.path.clone(), e.name.clone(), true)) + .collect(); + if let Some(p) = crate::engines::system_stockfish() { + let label = p.display().to_string(); + out.push(Candidate::new(p, label, false)); + } + // The same file twice (the system's Stockfish added in the settings): once. + let mut seen = HashSet::new(); + out.retain(|c| seen.insert(c.real.clone())); + // The engines of the games against the computer (Rodent, Maia) are never + // analysis engines, whatever the settings say: never probed. + let play = play_dirs(); + out.retain(|c| !play.iter().any(|d| c.real.starts_with(d))); + out + } + + /// The folders of the engines ChessPenguin plays with (links followed). + pub(super) fn play_dirs() -> Vec { + [ + crate::rodent_download::dir(), + crate::rodent4_download::dir(), + crate::maia_download::dir(), + ] + .into_iter() + .flatten() + .map(|d| d.canonicalize().unwrap_or(d)) + .collect() + } + + pub(super) fn set_candidates(candidates: Vec) { + with(|s| { + if s.candidates != candidates { + s.candidates = candidates; + } + }); + } + + /// The file's size and time (seconds), when it is there. + pub(super) fn stamp(path: &Path) -> Option<(u64, u64)> { + let m = std::fs::metadata(path).ok()?; + if !m.is_file() { + return None; + } + let modified = m + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs()); + Some((m.len(), modified)) + } + + /// The verdict on the real file as it is now, if there is one. + fn fresh<'a>(s: &'a State, real: &Path) -> Option<&'a Verdict> { + let (size, modified) = stamp(real)?; + s.known + .get(real) + .filter(|v| (v.size, v.modified) == (size, modified)) + } + + pub(super) fn verified() -> Option { + with(|s| { + s.candidates + .iter() + .find(|c| fresh(s, &c.real).is_some_and(|v| v.same)) + .map(|c| EngineLocation::Program(c.path.clone())) + }) + } + + pub(super) fn lookup(ctx: &egui::Context) -> Lookup { + match crate::engines::own_stockfish() { + Some(own) => Lookup::Ready(own), + None => lookup_without_own(ctx), + } + } + + /// [`lookup`] among the user's engines only. + pub(super) fn lookup_without_own(ctx: &egui::Context) -> Lookup { + match with(decide) { + Decision::Done(l) => l, + Decision::Probe(candidates) => { + for c in candidates { + spawn_probe(c, ctx.clone()); + } + Lookup::Checking + } + } + } + + pub(super) enum Decision { + Done(Lookup), + /// These candidates are to be probed (their real files are marked as being + /// probed). + Probe(Vec), + } + + /// What the verdicts say of the candidates; files without one are to be probed. + /// The files that did not start are said once (then tried again). + pub(super) fn decide(s: &mut State) -> Decision { + let mut unfit = None; + let mut checking = false; + let mut to_probe = Vec::new(); + for c in &s.candidates { + if stamp(&c.real).is_none() { + continue; + } + let said = |name: Option<&String>, why| Unfit { + name: name.cloned().unwrap_or_else(|| c.label.clone()), + from_settings: c.from_settings, + why, + }; + if s.checking.contains(&c.real) { + checking = true; + } else if let Some((why, name)) = s.failed.get(&c.real) { + unfit.get_or_insert_with(|| said(name.as_ref(), *why)); + } else { + match fresh(s, &c.real) { + Some(v) if v.same => { + let ready = EngineLocation::Program(c.path.clone()); + return Decision::Done(Lookup::Ready(ready)); + } + Some(v) => { + let why = if v.name.as_deref() == Some(STOCKFISH_19) { + Why::Differs + } else { + Why::Other + }; + unfit.get_or_insert_with(|| said(v.name.as_ref(), why)); + } + None => to_probe.push(c.clone()), + } + } + } + if !to_probe.is_empty() { + s.checking.extend(to_probe.iter().map(|c| c.real.clone())); + return Decision::Probe(to_probe); + } + if checking { + return Decision::Done(Lookup::Checking); + } + s.failed.clear(); + Decision::Done(unfit.map_or(Lookup::None, Lookup::Unfit)) + } + + /// Probes the engine on a thread of its own, started by the path it is known by + /// (a snap or a wrapper looks at the name it is started by), and keeps the verdict + /// for its real file. The engine dies with that thread (the program quitting in + /// the middle of a handshake leaves no process behind). + fn spawn_probe(c: Candidate, ctx: egui::Context) { + let real = c.real.clone(); + let limits = with(|s| s.limits); + let spawned = std::thread::Builder::new() + .name("review-engine-probe".into()) + .spawn({ + let real = real.clone(); + move || { + let stamp = stamp(&real); + let config = uci::EngineConfig { + nice: 10, + kill_with_parent: true, + ..uci::EngineConfig::new(&c.path) + }; + let quitting = || QUITTING.load(Ordering::Relaxed); + let probe = game_review::probe::probe(config, limits, &quitting); + if !quitting() { + record(&real, stamp, probe); + ctx.request_repaint(); + } + } + }); + match spawned { + Ok(t) => with(|s| { + s.threads.retain(|t| !t.is_finished()); + s.threads.push(t); + }), + Err(e) => record( + &real, + stamp(&real), + Err(game_review::JobFailure::Start(e.to_string())), + ), + } + } + + pub(super) fn record( + real: &Path, + stamp: Option<(u64, u64)>, + probe: Result, + ) { + with(|s| { + s.checking.remove(real); + let Some((size, modified)) = stamp else { + return; + }; + match probe { + // Not remembered: tried again at the next request. + Ok(p) if p.timed_out => { + s.failed.insert(real.to_path_buf(), (Why::TimedOut, p.name)); + } + Ok(p) => { + s.known.insert( + real.to_path_buf(), + Verdict { + size, + modified, + same: p.same(), + name: p.name, + }, + ); + save(s); + } + Err(_) => { + s.failed.insert(real.to_path_buf(), (Why::NotStarted, None)); + } + } + }); + } + + pub(super) fn name_fits(path: &Path, name: &str) -> bool { + let own = crate::engines::own_stockfish() + .is_some_and(|EngineLocation::Program(p)| p.as_path() == path); + if own || name == STOCKFISH_19 { + return true; + } + let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + with(|s| { + if s.known.remove(&real).is_some() { + save(s); + } + }); + false + } + + /// How long the program waits for the probes when it quits. + const QUIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2); + + pub(super) fn shutdown() { + QUITTING.store(true, Ordering::Relaxed); + let threads = with(|s| std::mem::take(&mut s.threads)); + // A probe in a search gives up within a tenth of a second and quits its engine; + // one in a hung handshake is not waited for: its engine dies with its thread + // when the program ends (`kill_with_parent`). + let deadline = std::time::Instant::now() + QUIT_WAIT; + for t in threads { + while !t.is_finished() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + if t.is_finished() { + let _ = t.join(); + } + } + } + + #[cfg(test)] + pub(super) fn reset(candidates: Vec) { + let mut s = state().lock().unwrap_or_else(|e| e.into_inner()); + *s = State { + candidates, + loaded: true, + limits: ProbeLimits { + search: std::time::Duration::from_millis(300), + total: std::time::Duration::from_secs(2), + }, + ..State::default() + }; + } +} + +#[cfg(all(test, not(web)))] +mod tests { + use super::native::{Candidate, Kept, Verdict, lookup_without_own, read_kept, reset, verified}; + use super::{EngineLocation, Lookup, Unfit, Why, name_fits}; + use std::path::{Path, PathBuf}; + use std::time::{Duration, Instant}; + + fn fake() -> PathBuf { + let fake = PathBuf::from(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../target/debug/fake_uci" + )); + assert!( + fake.exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + fake + } + + /// A script starting the fake engine named `name` that answers the probe with the + /// reference, `nodes_delta` nodes more. + fn engine(dir: &Path, file: &str, name: &str, nodes_delta: u64) -> PathBuf { + use game_review::probe::{PROBE_POSITIONS, REFERENCE}; + let mut args = vec![format!("--name '{name}'")]; + for (fen, (best, score, nodes)) in PROBE_POSITIONS.iter().zip(REFERENCE) { + let uci::Score::Cp(cp) = score else { + unreachable!("the reference scores are in centipawns") + }; + let marker = fen.split(' ').next().unwrap_or_default(); + args.push(format!( + "--answer '{marker}' 'cp {cp} nodes {} pv {best}'", + nodes + nodes_delta + )); + } + let path = dir.join(file); + let script = format!( + "#!/bin/sh\nexec '{}' {}\n", + fake().display(), + args.join(" ") + ); + std::fs::write(&path, script).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + path + } + + fn settle(ctx: &egui::Context) -> Lookup { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let l = lookup_without_own(ctx); + if l != Lookup::Checking || Instant::now() > deadline { + return l; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn unfit(name: &str, from_settings: bool, why: Why) -> Lookup { + Lookup::Unfit(Unfit { + name: name.into(), + from_settings, + why, + }) + } + + /// One test: the state is global. + #[test] + fn a_users_stockfish_19_is_taken_only_when_it_searches_as_ours() { + let dir = std::env::temp_dir().join(format!("cp-review-engine-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ctx = egui::Context::default(); + let differs = engine(&dir, "sf-other", "Stockfish 19", 1); + let same = engine(&dir, "sf-same", "Stockfish 19", 0); + let named = engine(&dir, "sf-18", "Stockfish 18", 0); + let settings = |p: &PathBuf, label: &str| Candidate::new(p.clone(), label.into(), true); + + // No engine of the user's. + reset(Vec::new()); + assert_eq!(settle(&ctx), Lookup::None); + + // A Stockfish 19 searching otherwise (one node more): not taken. + reset(vec![settings(&differs, "My engine")]); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::Differs)); + assert_eq!(verified(), None); + + // Another name: turned down (without a search); from `PATH` it says so. + reset(vec![Candidate::new( + named.clone(), + "/usr/bin/x".into(), + false, + )]); + assert_eq!(settle(&ctx), unfit("Stockfish 18", false, Why::Other)); + + // An engine that does not start: its name from the settings; not remembered, + // so the next request tries it again. + let broken = dir.join("broken"); + std::fs::write(&broken, "not a program").unwrap(); + reset(vec![settings(&broken, "Broken one")]); + assert_eq!(settle(&ctx), unfit("Broken one", true, Why::NotStarted)); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), unfit("Broken one", true, Why::NotStarted)); + + // A «Stockfish 19» that does not finish in time: said once, not remembered. + let slow = dir.join("sf-slow"); + let script = format!( + "#!/bin/sh\nexec '{}' --name 'Stockfish 19' --ignore-nodes\n", + fake().display() + ); + std::fs::write(&slow, script).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&slow, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + reset(vec![settings(&slow, "Slow")]); + assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::TimedOut)); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::TimedOut)); + + // Started by the name it is known by (a wrapper looking at its name), the + // verdict kept for the real file. + #[cfg(unix)] + { + let picky = dir.join("picky"); + let script = format!( + "#!/bin/sh\n[ \"$(basename \"$0\")\" = sf-launch ] || exit 3\nexec '{}'\n", + same.display() + ); + std::fs::write(&picky, script).unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&picky, std::fs::Permissions::from_mode(0o755)).unwrap(); + let launch = dir.join("sf-launch"); + std::os::unix::fs::symlink(&picky, &launch).unwrap(); + reset(vec![settings(&launch, "Launcher")]); + assert_eq!( + settle(&ctx), + Lookup::Ready(EngineLocation::Program(launch.clone())) + ); + } + + // The reference answers: taken, even after another engine in the list. + reset(vec![settings(&differs, "A"), settings(&same, "B")]); + let ready = Lookup::Ready(EngineLocation::Program(same.clone())); + assert_eq!(settle(&ctx), ready); + assert_eq!(verified(), Some(EngineLocation::Program(same.clone()))); + // Remembered: no second probe. + assert_eq!(lookup_without_own(&ctx), ready); + + // A link to it: the real file's verdict, nothing probed again. + #[cfg(unix)] + { + let link = dir.join("link-to-same"); + std::os::unix::fs::symlink(&same, &link).unwrap(); + super::native::set_candidates(vec![settings(&link, "Link")]); + assert_eq!( + lookup_without_own(&ctx), + Lookup::Ready(EngineLocation::Program(link.clone())) + ); + super::native::set_candidates(vec![settings(&same, "B")]); + } + + // At a job's start it says another name (a wrapper changed): forgotten. + assert!(name_fits(&same, "Stockfish 19")); + assert!(!name_fits(&same, "Stockfish 18")); + assert_eq!(verified(), None); + assert_eq!(settle(&ctx), ready); + + // The file changed: probed again (a changed size). + let text = std::fs::read_to_string(&same).unwrap(); + std::fs::write(&same, format!("{text}\n")).unwrap(); + assert_eq!(verified(), None); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), ready); + + let _ = std::fs::remove_dir_all(&dir); + } + + /// The engines of the games against the computer are never candidates, whatever + /// the settings say; the analysis engines are, the active one first. + #[test] + fn play_engines_are_never_probed() { + use crate::settings::{EngineConfig, Settings}; + let rodent = crate::rodent_download::dir() + .expect("a data folder") + .join("rodent_v"); + let rodent4 = crate::rodent4_download::dir() + .expect("a data folder") + .join("rodent4"); + let mine = PathBuf::from("/opt/engines/stockfish-19"); + let other = PathBuf::from("/opt/engines/komodo"); + let settings = Settings { + engines: vec![ + EngineConfig::new("Rodent".into(), rodent), + EngineConfig::new("Komodo".into(), other.clone()), + EngineConfig::new("Rodent IV".into(), rodent4), + EngineConfig::new("Mine".into(), mine.clone()), + ], + active_engine: Some(3), + ..Settings::default() + }; + let found: Vec<(PathBuf, bool)> = super::native::candidates(&settings) + .into_iter() + .map(|c| (c.path, c.from_settings)) + .filter(|(_, from_settings)| *from_settings) + .collect(); + assert_eq!(found, vec![(mine, true), (other, true)]); + } + + /// Verdicts kept with another reference (another probe) are not trusted. + #[test] + fn verdicts_of_another_reference_are_dropped() { + let verdict = Verdict { + size: 1, + modified: 2, + same: true, + name: Some("Stockfish 19".into()), + }; + let kept = |reference: String| { + serde_json::to_vec(&Kept { + reference, + engines: [(PathBuf::from("/x/stockfish"), verdict.clone())].into(), + }) + .unwrap() + }; + let ours = read_kept(&kept(game_review::probe::reference_key())); + assert_eq!(ours.get(Path::new("/x/stockfish")), Some(&verdict)); + assert!(read_kept(&kept("0000000000000000".into())).is_empty()); + // The first version's file (a bare map): dropped too. + assert!( + read_kept(br#"{"/x/stockfish":{"size":1,"modified":2,"same":true,"name":null}}"#) + .is_empty() + ); + } +} diff --git a/apps/desktop/src/rodent4_download.rs b/apps/desktop/src/rodent4_download.rs new file mode 100644 index 0000000..6138de4 --- /dev/null +++ b/apps/desktop/src/rodent4_download.rs @@ -0,0 +1,184 @@ +//! Downloading Rodent IV on request (docs/decisions.md «Rodent IV»): its authors publish +//! no builds for Linux and Windows, so the engine is built from their sources at a pinned +//! commit by our workflow (.github/workflows/rodent-iv.yml) and published as a release of +//! its own; its personalities and opening books come from the authors' repository at the +//! same commit. Every file is checked against its SHA-256. Nothing is downloaded without +//! the user asking. + +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; + +#[cfg(not(web))] +use crate::engine_download::fetch; +use crate::engine_download::{Asset, Download, Failure, Stage, already, disk}; +use ::play::rodent::{BOOK_NAMES, FILES, file_url}; + +/// This platform's build: the release of our builds it is in (the macOS build of +/// `rodent-iv-0.33` searched garbage, `think-thread.patch`; the one of `rodent-iv-0.33-2` +/// had no home folder and offered no personality, `home-dir.patch`; the GCC builds of +/// Linux and Windows had neither fault) and the file there, checked against its SHA-256. +fn binary() -> Option<(&'static str, Asset)> { + let (tag, file, sha256, size) = match (std::env::consts::OS, std::env::consts::ARCH) { + ("linux", "x86_64") => ( + "rodent-iv-0.33", + "rodent-iv-linux-x86_64", + "bb2cd533d89d6431e50a101242a74806d5c022f4d5893fe0d16dbd24b2f62efd", + 1_291_352, + ), + ("windows", "x86_64") => ( + "rodent-iv-0.33", + "rodent-iv-windows-x86_64.exe", + "aa0f58ee10a2366cf86064d152a29ab344faf02e1d199934232eb98f813aac4b", + 1_288_192, + ), + ("macos", "aarch64") => ( + "rodent-iv-0.33-3", + "rodent-iv-macos-arm64", + "4e84159598196e164400c056eff04baebcaf1a045a9b7aaf63ffabe98b9df6af", + 249_096, + ), + _ => return None, + }; + (!sha256.is_empty()).then_some(( + tag, + Asset { + file, + sha256, + size, + zip: false, + }, + )) +} + +#[cfg(windows)] +const EXE: &str = "rodent_iv.exe"; +#[cfg(not(windows))] +const EXE: &str = "rodent_iv"; + +/// Whether Rodent IV can be had on this platform (or is at hand for development). +pub fn available() -> bool { + std::env::var_os("CP_RODENT4").is_some() || binary().is_some() +} + +/// The download in all: the engine, its personalities and books. +fn total() -> u64 { + binary().map_or(0, |(_, b)| b.size) + FILES.iter().map(|f| f.1).sum::() +} + +pub fn size_mb() -> u64 { + (total() + 500_000) / 1_000_000 +} + +/// `/engines/rodent_iv_0.33/` (`CP_RODENT4` elsewhere: development). +pub fn dir() -> Option { + if let Some(d) = std::env::var_os("CP_RODENT4") { + return Some(PathBuf::from(d)); + } + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("engines").join("rodent_iv_0.33")) +} + +/// Written last, once the engine started from its folder with everything beside it: the +/// release its build came from. +const COMPLETE: &str = ".complete"; + +/// The installed engine, if it is all there and its build is this version's (an older +/// one is downloaded again; the files that did not change are kept). +pub fn installed() -> Option { + let d = dir()?; + let exe = d.join(EXE); + let whole = d.join("personalities").join("basic.ini").is_file(); + let marked = std::env::var_os("CP_RODENT4").is_some() + || binary().is_some_and(|(tag, _)| { + std::fs::read_to_string(d.join(COMPLETE)).is_ok_and(|m| m.trim() == tag) + }); + (exe.is_file() && whole && marked).then_some(exe) +} + +/// Removes the downloaded engine (a broken one). +pub fn remove() -> std::io::Result<()> { + if std::env::var_os("CP_RODENT4").is_some() { + return Ok(()); + } + match dir() { + Some(d) if d.exists() => std::fs::remove_dir_all(d), + _ => Ok(()), + } +} + +#[cfg(not(web))] +pub fn start(ctx: &egui::Context) -> Download { + Download::spawn(ctx, total(), run) +} + +/// A browser downloads no engine programs. +#[cfg(web)] +pub fn start(_ctx: &egui::Context) -> Download { + Download::unsupported() +} + +#[cfg(not(web))] +fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { + let (tag, bin) = binary().ok_or(Failure::Unsupported)?; + let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; + std::fs::create_dir_all(&dir).map_err(disk)?; + let grand = total(); + let mut base = 0u64; + // One file's progress as part of the whole. + let step = |base: u64| { + move |s: Stage| match s { + Stage::Downloading { done, .. } => report(Stage::Downloading { + done: base + done, + total: grand, + }), + other => report(other), + } + }; + let result = (|| { + let exe = dir.join(EXE); + let url = format!( + "https://github.com/vrubelroman/chessPenguin/releases/download/{tag}/{}", + bin.file + ); + if !already(&exe, &bin) { + fetch(&url, &exe, &bin, &step(base), cancel)?; + } + base += bin.size; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).map_err(disk)?; + } + for &(path, size, sha256) in FILES { + let dest = dir.join(path); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent).map_err(disk)?; + } + let asset = Asset { + file: path, + sha256, + size, + zip: false, + }; + if !already(&dest, &asset) { + fetch(&file_url(path), &dest, &asset, &step(base), cancel)?; + } + base += size; + } + report(Stage::Unpacking); + for (file, name) in BOOK_NAMES { + // Where names do not differ by case (Windows, macOS) it is the same file. + if !dir.join(name).exists() { + std::fs::copy(dir.join(file), dir.join(name)).map_err(disk)?; + } + } + crate::rodent_download::check_runs(&exe)?; + std::fs::write(dir.join(COMPLETE), tag).map_err(disk)?; + Ok(exe) + })(); + if result.is_err() { + // Nothing half-installed is left behind. + let _ = std::fs::remove_dir_all(&dir); + } + result +} diff --git a/apps/desktop/src/rodent_download.rs b/apps/desktop/src/rodent_download.rs new file mode 100644 index 0000000..6df8893 --- /dev/null +++ b/apps/desktop/src/rodent_download.rs @@ -0,0 +1,214 @@ +//! Downloading Rodent V on request (docs/decisions.md «Соперник Ñ� характером»): the +//! official release 1.2 of github.com/nescitus/Rodent-V (GPL-3.0), checked against its +//! SHA-256, unpacked into the user's data directory with its personalities, networks and +//! opening books (the engine finds them from its own folder). Linux and Windows on x86-64 +//! only: the release has no other builds. Nothing is downloaded without the user asking. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +#[cfg(not(web))] +use crate::engine_download::fetch; +use crate::engine_download::{Asset, Download, Failure, Stage, disk}; + +const TAG: &str = "Rodent_v_1.2"; + +const ARCHIVE: Asset = Asset { + file: "release-1-2.zip", + sha256: "81c46c45d3f26393b375f6be03d60f4207bb79f4f924156e53fee6ac75a7be6d", + size: 48_241_374, + zip: true, +}; + +/// The engine's file in the archive for this platform, if there is one. +fn binary() -> Option<&'static str> { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("linux", "x86_64") => Some("rodent_v_1.2"), + ("windows", "x86_64") => Some("rodent_v_1.2.exe"), + _ => None, + } +} + +#[cfg(windows)] +const EXE: &str = "rodent_v.exe"; +#[cfg(not(windows))] +const EXE: &str = "rodent_v"; + +/// Whether Rodent can be had on this platform. +pub fn available() -> bool { + binary().is_some() +} + +pub fn size_mb() -> u64 { + (ARCHIVE.size + 500_000) / 1_000_000 +} + +/// `/engines/rodent_v_1.2/` (`CP_RODENT` elsewhere: development). +pub fn dir() -> Option { + if let Some(d) = std::env::var_os("CP_RODENT") { + return Some(PathBuf::from(d)); + } + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("engines").join("rodent_v_1.2")) +} + +/// Written last, once the engine started from its unpacked folder: a folder cut short +/// (the program closed while unpacking) is not taken for an installed engine. +const COMPLETE: &str = ".complete"; + +/// The installed engine, if it is all there (its personalities, nets and books beside +/// it; a development folder of `CP_RODENT` needs no mark). +pub fn installed() -> Option { + let d = dir()?; + let exe = d.join(EXE); + let whole = ["personalities", "nets", "books"] + .iter() + .all(|f| d.join(f).is_dir()); + let marked = std::env::var_os("CP_RODENT").is_some() || d.join(COMPLETE).is_file(); + (exe.is_file() && whole && marked).then_some(exe) +} + +/// Removes the downloaded engine (a broken one, or to free its space). +pub fn remove() -> std::io::Result<()> { + if std::env::var_os("CP_RODENT").is_some() { + return Ok(()); + } + match dir() { + Some(d) if d.exists() => std::fs::remove_dir_all(d), + _ => Ok(()), + } +} + +#[cfg(not(web))] +pub fn start(ctx: &egui::Context) -> Download { + Download::spawn(ctx, ARCHIVE.size, run) +} + +/// A browser downloads no engine programs. +#[cfg(web)] +pub fn start(_ctx: &egui::Context) -> Download { + Download::unsupported() +} + +#[cfg(not(web))] +fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { + let bin = binary().ok_or(Failure::Unsupported)?; + let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; + std::fs::create_dir_all(&dir).map_err(disk)?; + let archive = dir.join(format!("{}.part", ARCHIVE.file)); + let url = format!( + "https://github.com/nescitus/Rodent-V/releases/download/{TAG}/{}", + ARCHIVE.file + ); + let result = fetch(&url, &archive, &ARCHIVE, report, cancel) + .and_then(|()| { + report(Stage::Unpacking); + unpack(&archive, &dir, bin) + }) + .and_then(|exe| check_runs(&exe).map(|()| exe)) + .and_then(|exe| { + std::fs::write(dir.join(COMPLETE), TAG).map_err(disk)?; + Ok(exe) + }); + let _ = std::fs::remove_file(&archive); + if result.is_err() { + // Nothing half-installed is left behind. + let _ = std::fs::remove_dir_all(&dir); + } + result +} + +#[cfg(not(web))] +/// Takes this platform's engine and the folders it reads (personalities, nets, books) +/// out of the archive; the other builds and the pictures of the manual stay out. +fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result { + let exe = dir.join(EXE); + let file = std::fs::File::open(archive).map_err(disk)?; + let mut z = zip::ZipArchive::new(file).map_err(|e| Failure::Disk(e.to_string()))?; + for i in 0..z.len() { + let mut entry = z.by_index(i).map_err(|e| Failure::Disk(e.to_string()))?; + if !entry.is_file() { + continue; + } + let name = entry + .name() + .map_err(|e| Failure::Disk(e.to_string()))? + .into_owned(); + // "release-1-2/personalities/tal_nnue.txt" → ["personalities", "tal_nnue.txt"]. + let parts: Vec<&str> = name.split(['/', '\\']).filter(|p| !p.is_empty()).collect(); + let dest = match parts.as_slice() { + [_, b] if *b == bin => exe.clone(), + [_, folder, f] + if ["personalities", "nets", "books"].contains(folder) && !f.contains("..") => + { + let d = dir.join(folder); + std::fs::create_dir_all(&d).map_err(disk)?; + d.join(f) + } + _ => continue, + }; + let mut out = std::fs::File::create(&dest).map_err(disk)?; + std::io::copy(&mut entry, &mut out).map_err(disk)?; + } + if !exe.is_file() || !dir.join("personalities").is_dir() { + return Err(Failure::Disk("no engine in the archive".into())); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).map_err(disk)?; + } + Ok(exe) +} + +/// Starts the engine once from its folder and waits for its name: it runs here (the +/// release needs AVX2: an older processor fails this). +#[cfg(not(web))] +pub(crate) fn check_runs(exe: &Path) -> Result<(), Failure> { + use std::io::Write; + let mut cmd = std::process::Command::new(exe); + if let Some(d) = exe.parent() { + cmd.current_dir(d); + } + cmd.stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); + } + let mut child = cmd.spawn().map_err(|_| Failure::Broken)?; + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(b"uci\nquit\n"); + } + let out = child.wait_with_output().map_err(|_| Failure::Broken)?; + if String::from_utf8_lossy(&out.stdout).contains("Rodent") { + Ok(()) + } else { + Err(Failure::Broken) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Unpacks the real archive when it is at hand (`RODENT_ZIP=…/release-1-2.zip`). + #[test] + #[ignore = "needs the release archive (RODENT_ZIP)"] + fn unpacks_the_engine_and_its_folders() { + let zip = std::env::var("RODENT_ZIP").expect("RODENT_ZIP"); + let dir = std::env::temp_dir().join(format!("cp-rodent-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let exe = unpack(Path::new(&zip), &dir, "rodent_v_1.2").unwrap(); + assert!(exe.is_file()); + assert!(dir.join("personalities/tal_nnue.txt").is_file()); + assert!(dir.join("nets/rodent_4kb_768hl_8ob_v2.bin").is_file()); + assert!(dir.join("books/rodent.bin").is_file()); + assert!(!dir.join("rodent_v_1.2.exe").exists()); + check_runs(&exe).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/san.rs b/apps/desktop/src/san.rs new file mode 100644 index 0000000..8265e59 --- /dev/null +++ b/apps/desktop/src/san.rs @@ -0,0 +1,196 @@ +//! How moves look on screen (docs/design/move-notation.md): Latin letters, figurines as +//! on Lichess, or the piece letters of the interface language. Only the shown label +//! changes — the game, PGN, the clipboard and everything compared stay Latin SAN. + +use std::borrow::Cow; +use std::sync::atomic::{AtomicU8, Ordering}; + +use serde::{Deserialize, Deserializer, Serialize}; + +use crate::i18n::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Default)] +#[serde(rename_all = "lowercase")] +pub enum MoveNotation { + /// K Q R B N, as in PGN files and engine output. + #[default] + Latin, + /// â™” ♕ â™– â™— ♘ (one outline style for both colours, no pawn sign). + Figurine, + /// The letters of the interface language (Кр Ф Л С К in Russian); Latin in English. + Local, +} + +/// An unknown value (a newer version) is read as Latin, not as broken settings. +impl<'de> Deserialize<'de> for MoveNotation { + fn deserialize>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(match v.as_str().unwrap_or("") { + "figurine" => MoveNotation::Figurine, + "local" => MoveNotation::Local, + _ => MoveNotation::Latin, + }) + } +} + +static MODE: AtomicU8 = AtomicU8::new(0); + +/// The notation chosen in the settings (set by the application every frame). +pub fn set(mode: MoveNotation) { + MODE.store(mode as u8, Ordering::Relaxed); +} + +fn mode() -> MoveNotation { + match MODE.load(Ordering::Relaxed) { + 1 => MoveNotation::Figurine, + 2 => MoveNotation::Local, + _ => MoveNotation::Latin, + } +} + +/// King, queen, rook, bishop, knight in a language (`None`: as Latin). +pub fn local_letters(lang: Lang) -> Option<[&'static str; 5]> { + match lang { + Lang::En => None, + Lang::Ru => Some(["Кр", "Ф", "Л", "С", "К"]), + Lang::De => Some(["K", "D", "T", "L", "S"]), + Lang::Fr => Some(["R", "D", "T", "F", "C"]), + Lang::Es | Lang::It => Some(["R", "D", "T", "A", "C"]), + // Rei, Dama, Torre, Bispo, Cavalo. + Lang::Pt => Some(["R", "D", "T", "B", "C"]), + // Uzbek and Kazakh books print moves with the Latin letters. + Lang::Uz | Lang::Kk => None, + } +} + +fn piece(c: char, mode: MoveNotation, lang: Lang) -> Option<&'static str> { + let i = "KQRBN".find(c)?; + match mode { + MoveNotation::Latin => None, + MoveNotation::Figurine => Some(["â™”", "♕", "â™–", "â™—", "♘"][i]), + MoveNotation::Local => local_letters(lang).map(|l| l[i]), + } +} + +/// A SAN move as shown: the piece letter at the start and after "=" replaced. +pub fn display_san(san: &str, mode: MoveNotation, lang: Lang) -> Cow<'_, str> { + if mode == MoveNotation::Latin || (mode == MoveNotation::Local && lang == Lang::En) { + return Cow::Borrowed(san); + } + let mut out = String::with_capacity(san.len() + 4); + let mut first = true; + let mut after_eq = false; + let mut changed = false; + for c in san.chars() { + match (first || after_eq).then(|| piece(c, mode, lang)).flatten() { + Some(p) => { + out.push_str(p); + changed = true; + } + None => out.push(c), + } + first = false; + after_eq = c == '='; + } + if changed { + Cow::Owned(out) + } else { + Cow::Borrowed(san) + } +} + +/// A label as shown: "12.Nf3", "12…Nf3", "12...Nf3" or "Nf3", in the chosen notation. +pub fn show(label: &str) -> Cow<'_, str> { + show_in(label, mode(), crate::i18n::current()) +} + +/// A line of labels separated by spaces ("5.Nc3 a6 6.Be2"), as shown. +pub fn show_line(line: &str) -> String { + line.split(' ') + .map(|w| show(w)) + .collect::>() + .join(" ") +} + +pub fn show_in(label: &str, mode: MoveNotation, lang: Lang) -> Cow<'_, str> { + let number = label + .char_indices() + .find(|(_, c)| !(c.is_ascii_digit() || matches!(c, '.' | '…' | ' '))) + .map_or(label.len(), |(i, _)| i); + let (prefix, san) = label.split_at(number); + match display_san(san, mode, lang) { + Cow::Borrowed(_) => Cow::Borrowed(label), + Cow::Owned(s) => Cow::Owned(format!("{prefix}{s}")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_piece_letters_change() { + let f = |s| display_san(s, MoveNotation::Figurine, Lang::Ru).into_owned(); + assert_eq!(f("Nf3"), "♘f3"); + assert_eq!(f("Qxd8+"), "♕xd8+"); + assert_eq!(f("exd8=Q#"), "exd8=♕#"); + assert_eq!(f("e8=N"), "e8=♘"); + assert_eq!(f("O-O-O"), "O-O-O"); + assert_eq!(f("--"), "--"); + assert_eq!(f("Nbd7"), "♘bd7"); + assert_eq!(f("Rxb7"), "â™–xb7"); + assert_eq!(f("e4"), "e4"); + let r = |s| display_san(s, MoveNotation::Local, Lang::Ru).into_owned(); + assert_eq!(r("Kxe2+"), "Крxe2+"); + assert_eq!(r("Bb5"), "Сb5"); + assert_eq!(r("a8=Q"), "a8=Ф"); + let de = |s| display_san(s, MoveNotation::Local, Lang::De).into_owned(); + assert_eq!(de("Nf3"), "Sf3"); + assert_eq!(de("Qd1"), "Dd1"); + let fr = |s| display_san(s, MoveNotation::Local, Lang::Fr).into_owned(); + assert_eq!(fr("Kg1"), "Rg1"); + assert_eq!(fr("Rg1"), "Tg1"); + // Applied once, to Latin: a shown label is never shown again. + assert_eq!(show_in("Kg1", MoveNotation::Local, Lang::Fr), "Rg1"); + } + + #[test] + fn latin_and_english_borrow() { + assert!(matches!( + display_san("Nf3", MoveNotation::Latin, Lang::Ru), + Cow::Borrowed(_) + )); + assert!(matches!( + display_san("Nf3", MoveNotation::Local, Lang::En), + Cow::Borrowed(_) + )); + assert!(matches!( + display_san("e4", MoveNotation::Figurine, Lang::Ru), + Cow::Borrowed(_) + )); + } + + #[test] + fn labels_keep_their_numbers() { + let s = |l| show_in(l, MoveNotation::Figurine, Lang::En).into_owned(); + assert_eq!(s("12.Nf3"), "12.♘f3"); + assert_eq!(s("12…Nf6"), "12…♘f6"); + assert_eq!(s("12...Bb4+"), "12...â™—b4+"); + assert_eq!(s("Kh1"), "â™”h1"); + assert_eq!(s("3.e4"), "3.e4"); + assert_eq!(s("12. Nf3"), "12. ♘f3"); + assert_eq!(s("12... Nf6"), "12... ♘f6"); + } + + #[test] + fn settings_values() { + let v: MoveNotation = serde_json::from_str("\"figurine\"").unwrap(); + assert_eq!(v, MoveNotation::Figurine); + let v: MoveNotation = serde_json::from_str("\"klingon\"").unwrap(); + assert_eq!(v, MoveNotation::Latin); + assert_eq!( + serde_json::to_string(&MoveNotation::Local).unwrap(), + "\"local\"" + ); + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs new file mode 100644 index 0000000..e35a903 --- /dev/null +++ b/apps/desktop/src/settings.rs @@ -0,0 +1,602 @@ +//! Persistent user settings (JSON in the XDG config dir), written atomically. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::assets::{BoardThemeId, PieceSet, SoundSet}; +use crate::i18n::Lang; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct EngineConfig { + pub name: String, + pub path: PathBuf, + #[serde(default = "default_threads")] + pub threads: u32, + #[serde(default = "default_hash")] + pub hash_mb: u32, + #[serde(default = "default_multipv")] + pub multipv: u32, + /// Search time per position in seconds; `None` = infinite. + #[serde(default)] + pub search_secs: Option, + /// ChessPenguin's Stockfish (bundled in the Flatpak, otherwise downloaded on + /// request); `path` is unused and resolved at start. + #[serde(default)] + pub builtin: bool, +} + +fn default_threads() -> u32 { + std::thread::available_parallelism() + .map(|n| (n.get() as u32 / 2).max(1)) + .unwrap_or(1) +} +fn default_hash() -> u32 { + 256 +} +fn default_multipv() -> u32 { + 3 +} + +impl EngineConfig { + pub fn new(name: String, path: PathBuf) -> Self { + Self { + name, + path, + threads: default_threads(), + hash_mb: default_hash(), + multipv: default_multipv(), + search_secs: None, + builtin: false, + } + } + + /// Executable to start; `None` if ChessPenguin's Stockfish is neither bundled nor + /// downloaded yet (it is offered for download then). + pub fn executable(&self) -> Option { + if self.builtin { + crate::engines::own_stockfish() + } else { + // A browser runs no engine programs: there are none but its own. + #[cfg(not(web))] + return Some(crate::engines::EngineLocation::Program(self.path.clone())); + #[cfg(web)] + None + } + } + + /// Whether the engine can be started: ChessPenguin's Stockfish is there (in a + /// browser: downloaded into it), or the file of another engine. + pub fn present(&self) -> bool { + self.executable().is_some_and(|l| l.present()) + } +} + +/// Piece animation, with Lichess's durations. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Animation { + Off, + Fast, + #[default] + Normal, + Slow, +} + +impl Animation { + pub const ALL: [Animation; 4] = [Self::Off, Self::Fast, Self::Normal, Self::Slow]; + + pub fn seconds(self) -> f32 { + match self { + Self::Off => 0.0, + Self::Fast => 0.12, + Self::Normal => 0.25, + Self::Slow => 0.5, + } + } + + pub fn label(self) -> &'static str { + crate::i18n::tr(match self { + Self::Off => "Off", + Self::Fast => "Fast", + Self::Normal => "Normal", + Self::Slow => "Slow", + }) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct Settings { + pub piece_set: PieceSet, + pub board_theme: BoardThemeId, + pub show_coords: bool, + /// How fast moves slide on the board. + pub animation: Animation, + /// A pawn reaching the last rank becomes a queen without the choice of a piece. + pub auto_queen: bool, + /// How moves are shown: Latin letters, figurines or the interface language's letters. + pub move_notation: crate::san::MoveNotation, + /// Translating game comments (docs/design/translation.md). + pub translation: crate::translate::TranslationSettings, + pub sound_enabled: bool, + pub sound_set: SoundSet, + pub volume: f32, + pub dark_mode: bool, + /// The width of the opening-training panel dragged by the user, in points; `None`: + /// the default for the window. + pub opening_side_width: Option, + pub language: Lang, + pub engines: Vec, + pub active_engine: Option, + pub show_best_arrow: bool, + /// Recently opened PGN files, most recent first. + pub databases: Vec, + /// The first-start engine discovery has run (see `engines::first_run_setup`). + pub engines_discovered: bool, + /// The sample databases were put on the shelf (see `examples::setup`). + pub examples_added: bool, + /// Ask GitHub for a newer release at start (Settings → About). + pub check_updates: bool, + /// A version the user chose to skip (its button is not shown). + pub skipped_version: Option, + /// The version that ran last (to say "updated to …" once). + pub last_version: Option, + /// A random id of this installation, sent with the update check (the site counts + /// installations that run; nothing else identifies the user). + pub install_id: String, + /// The database of the reference tab (`None`: the largest one on the shelf). + pub reference_db: Option, + /// The user's name: the annotator of games they add (own-databases.md §7). + pub your_name: String, + /// Where new databases are made (`None`: Documents/ChessPenguin). + pub new_database_dir: Option, + /// The database a game was last added to (preselected in the chooser). + pub last_target: Option, + /// The user's rating (optional): the strength of Maia is chosen relative to it. + pub rating: Option, + /// The last choices of the play dialog. + pub play: crate::play::PlayPrefs, + /// Games against the computer go by themselves into the player's database. + pub record_games: bool, + /// Who played on this computer, the last first (`player_games.rs`). + pub players: Vec, + /// Preparing against an opponent (docs/design/opponent-prep.md). + pub prep: PrepSettings, + pub repertoire_flow_version: u8, + /// Last training mode and queue of each opening repertoire. + pub repertoire_modes: std::collections::HashMap< + String, + ( + trainer::repertoire::TrainingMode, + trainer::repertoire::QueueMode, + ), + >, + #[serde(default)] + pub repertoire_priorities: + std::collections::HashMap, + #[serde(default)] + pub repertoire_context_policies: + std::collections::HashMap, + /// Hints shown until the user reacts (docs/design/tasks-42-43-2026-11-27.md §43.3). + pub hints: Hints, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Hints { + /// «Arrows and circles: the right mouse button on the board» above the notation. + pub board_shapes: Hint, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Hint { + /// Closed, or what it tells was done: never shown again. + pub done: bool, + /// Games it was shown in without a reaction. + pub shown: u32, +} + +impl Hint { + /// Shown in this many games without a reaction, the hint goes by itself. + pub const SHOWS: u32 = 3; + + /// A game opens where the hint can stand: whether it is shown there. A show counts + /// once per game (`fresh`: the game was not shown the hint before in this session); + /// such a game keeps it, the last counted one too. + pub fn offer(&mut self, fresh: bool) -> bool { + if self.done { + return false; + } + if !fresh { + return true; + } + if self.shown >= Self::SHOWS { + return false; + } + self.shown += 1; + true + } +} + +/// Options of the opponent preparation; its engine search is the game analysis's. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PrepSettings { + /// Unused legacy book choice, preserved when old settings are saved again. + pub book: Option, + /// Plies of the opening the report looks at. + pub plies: usize, + /// Which of the player's games. + pub period: prep::Period, + /// Moves with fewer games fold into «other moves». + pub branches_from: u32, + /// Inaccuracies (?!) are shown with the mistakes and blunders. + pub inaccuracies: bool, + /// The order of each table of the screen. + pub sorts: crate::prep_ui::PrepSorts, +} + +impl Default for PrepSettings { + fn default() -> Self { + Self { + book: None, + plies: 20, + period: prep::Period::All, + branches_from: 3, + inaccuracies: true, + sorts: Default::default(), + } + } +} + +impl Default for Settings { + fn default() -> Self { + Self { + piece_set: PieceSet::default(), + board_theme: BoardThemeId::default(), + show_coords: true, + animation: Animation::default(), + auto_queen: false, + move_notation: Default::default(), + translation: Default::default(), + sound_enabled: true, + sound_set: SoundSet::default(), + volume: 0.7, + dark_mode: true, + opening_side_width: None, + language: Lang::default(), + engines: Vec::new(), + active_engine: None, + show_best_arrow: true, + databases: Vec::new(), + engines_discovered: false, + examples_added: false, + check_updates: true, + skipped_version: None, + last_version: None, + install_id: String::new(), + reference_db: None, + your_name: String::new(), + new_database_dir: None, + last_target: None, + record_games: true, + players: Vec::new(), + rating: None, + play: Default::default(), + prep: PrepSettings::default(), + repertoire_modes: Default::default(), + repertoire_priorities: Default::default(), + repertoire_context_policies: Default::default(), + repertoire_flow_version: 0, + hints: Hints::default(), + } + } +} + +impl Settings { + pub fn migrate_repertoire_flow(&mut self) -> bool { + if self.repertoire_flow_version >= 1 { + return false; + } + for (_, queue) in self.repertoire_modes.values_mut() { + if matches!( + queue, + trainer::repertoire::QueueMode::Practice + | trainer::repertoire::QueueMode::SpacedRepetition + ) { + *queue = trainer::repertoire::QueueMode::SpacedRepetition; + } + } + self.repertoire_flow_version = 1; + true + } + pub fn config_dir() -> Option { + crate::platform::config_dir() + } + + /// `~/.cache/chesspenguin` (derived data that can be deleted at any time). + pub fn cache_dir() -> Option { + crate::platform::cache_dir() + } + + fn file() -> Option { + Self::config_dir().map(|d| d.join("settings.json")) + } + + pub fn load() -> Self { + let Some(path) = Self::file() else { + return Self::first_start(); + }; + migrate_legacy_config(&path); + match crate::platform::fs::read(&path) { + Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| { + eprintln!( + "settings: cannot parse {}: {e}; using defaults", + path.display() + ); + Self::default() + }), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::first_start(), + Err(_) => Self::default(), + } + } + + /// Settings of the very first start: the defaults in the system's language (if it + /// is one of ours, otherwise English). + fn first_start() -> Self { + Self { + language: Lang::system(), + ..Self::default() + } + } + + pub fn save(&self) -> std::io::Result<()> { + let Some(path) = Self::file() else { + return Ok(()); + }; + let json = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?; + write_atomic(&path, &json) + } + + pub fn active_engine(&self) -> Option<&EngineConfig> { + self.active_engine.and_then(|i| self.engines.get(i)) + } + + /// Puts the database first on the shelf; a database there already by another path + /// to the same file (a link) keeps its path. Returns the path on the shelf. + /// Puts `path` at the end of the shelf, unless it is there: a database made in the + /// background appears without moving the cards (task 42). + pub fn add_database_last(&mut self, path: &Path) { + let real = |p: &Path| std::fs::canonicalize(p).ok(); + let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path)); + if !self.databases.iter().any(same) { + self.databases.push(path.to_path_buf()); + } + } + + pub fn touch_database(&mut self, path: &Path) -> PathBuf { + let real = |p: &Path| std::fs::canonicalize(p).ok(); + let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path)); + let kept = match self.databases.iter().position(same) { + Some(i) => self.databases.remove(i), + None => path.to_path_buf(), + }; + self.databases.insert(0, kept.clone()); + kept + } +} + +/// Copies settings of the pre-rename build (`chessbase-linux`) once, if the new file is absent. +fn migrate_legacy_config(new_file: &Path) { + if crate::platform::fs::exists(new_file) { + return; + } + let legacy = directories::ProjectDirs::from("org", "chessbase-linux", "chessbase-linux") + .map(|d| d.config_dir().join("settings.json")); + if let Some(old) = legacy.filter(|p| p.is_file()) + && let Ok(bytes) = std::fs::read(&old) + { + let _ = write_atomic(new_file, &bytes); + } +} + +/// Writes via a temp file in the same directory and renames over the target. +pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + crate::platform::fs::write_atomic(path, bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A database made in the background goes to the end; opening it brings it first. + #[test] + fn a_copied_database_goes_to_the_end_of_the_shelf() { + let mut s = Settings { + databases: vec![PathBuf::from("/a.pgn"), PathBuf::from("/b.pgn")], + ..Default::default() + }; + s.add_database_last(Path::new("/new.pgn")); + s.add_database_last(Path::new("/a.pgn")); + assert_eq!( + s.databases, + [ + PathBuf::from("/a.pgn"), + PathBuf::from("/b.pgn"), + PathBuf::from("/new.pgn") + ] + ); + s.touch_database(Path::new("/new.pgn")); + assert_eq!(s.databases[0], PathBuf::from("/new.pgn")); + } + + #[test] + fn a_hint_goes_after_three_games_without_a_reaction() { + let mut hint = Hint::default(); + assert!(hint.offer(true)); + // The same game opened again in the session: shown, not counted. + assert!(hint.offer(false)); + assert!(hint.offer(true)); + assert!(hint.offer(true)); + assert_eq!(hint.shown, 3); + // A fourth game: gone; a game already shown in the session keeps it. + assert!(!hint.offer(true)); + assert!(hint.offer(false)); + assert_eq!(hint.shown, 3); + } + + #[test] + fn a_hint_done_is_never_shown() { + let mut hint = Hint { + done: true, + shown: 0, + }; + assert!(!hint.offer(true)); + assert_eq!(hint.shown, 0); + } + + #[test] + fn hints_survive_saving_and_old_settings_have_none() { + let mut s = Settings::default(); + s.hints.board_shapes = Hint { + done: false, + shown: 2, + }; + let json = serde_json::to_string(&s).unwrap(); + let back: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(back.hints, s.hints); + let old: Settings = serde_json::from_str(r#"{"show_coords": false}"#).unwrap(); + assert_eq!(old.hints, Hints::default()); + } + + /// A database put on the shelf again by a link to its file stays itself, once. + #[cfg(unix)] + #[test] + fn a_link_to_a_database_on_the_shelf_does_not_add_it_twice() { + let dir = std::env::temp_dir().join(format!("cp-shelf-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (base, other, link) = (dir.join("a.pgn"), dir.join("b.pgn"), dir.join("link.pgn")); + std::fs::write(&base, "").unwrap(); + std::fs::write(&other, "").unwrap(); + std::os::unix::fs::symlink(&base, &link).unwrap(); + let mut s = Settings::default(); + s.databases.clear(); + assert_eq!(s.touch_database(&base), base); + assert_eq!(s.touch_database(&other), other); + assert_eq!(s.touch_database(&link), base); + assert_eq!(s.databases, vec![base.clone(), other.clone()]); + // A database gone from the disk is still told by its path. + let gone = dir.join("gone.pgn"); + s.touch_database(&gone); + assert_eq!(s.touch_database(&gone), gone); + assert_eq!(s.databases.len(), 3); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The settings of 1.x kept the engine options of the game analysis and the + /// quality of the preparation: they are read without them now. + #[test] + fn settings_with_the_old_analysis_options_are_read() { + let old = r#"{ + "language": "Ru", + "review": {"quality": 2, "threads": 12, "hash_mb": 1024, "chosen": true}, + "prep": {"quality": 1, "plies": 16, "chosen": true, "book": "/db/book.pgn"} + }"#; + let s: Settings = serde_json::from_str(old).expect("read"); + assert_eq!(s.language, Lang::Ru); + assert_eq!(s.prep.plies, 16); + assert_eq!(s.prep.book, Some(PathBuf::from("/db/book.pgn"))); + let json = serde_json::to_string(&s).expect("written"); + assert!(!json.contains("\"review\"") && !json.contains("quality")); + assert!(!json.contains("\"chosen\"")); + assert!(json.contains("\"book\":\"/db/book.pgn\"")); + } +} + +#[cfg(test)] +mod repertoire_flow_tests { + use super::*; + use trainer::repertoire::{LearningPriority, QueueMode, TrainingMode}; + #[test] + fn old_training_preferences_migrate_once_without_resetting_color_or_custom_settings() { + let mut settings = Settings::default(); + settings.repertoire_modes.insert( + "old".into(), + (TrainingMode::Black, QueueMode::SpacedRepetition), + ); + assert!(settings.migrate_repertoire_flow()); + assert_eq!( + settings.repertoire_modes["old"], + (TrainingMode::Black, QueueMode::SpacedRepetition) + ); + settings.repertoire_modes.insert( + "review".into(), + (TrainingMode::White, QueueMode::ReviewInOrder), + ); + settings.repertoire_modes.get_mut("old").unwrap().1 = QueueMode::SpacedRepetition; + assert!(!settings.migrate_repertoire_flow()); + assert_eq!( + settings.repertoire_modes["old"].1, + QueueMode::SpacedRepetition + ); + assert_eq!( + settings.repertoire_modes["review"].1, + QueueMode::ReviewInOrder + ); + } + + #[test] + fn learning_mode_and_priority_roundtrip_and_default_for_legacy_settings() { + let mut settings = Settings::default(); + settings.repertoire_modes.insert( + "opening".into(), + (TrainingMode::Black, QueueMode::LeastRecent), + ); + settings + .repertoire_priorities + .insert("opening".into(), LearningPriority::MainLinesFirst); + + let json = serde_json::to_string(&settings).unwrap(); + let restored: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!( + restored.repertoire_modes["opening"], + (TrainingMode::Black, QueueMode::LeastRecent) + ); + assert_eq!( + restored.repertoire_priorities["opening"], + LearningPriority::MainLinesFirst + ); + + let legacy: Settings = serde_json::from_str("{}").unwrap(); + assert!(legacy.repertoire_priorities.is_empty()); + } + + #[test] + fn context_policies_roundtrip_and_default_for_legacy_json() { + let policy = trainer::repertoire::LearningContextPolicy { + reinforce_minimum_correct: 5, + reinforce_minimum_days: Some(14), + dont_show_start_moves_threshold: 8, + use_fixed_piece_speed: false, + move_speed_adjustment: 1.5, + consider_leadup_moves: true, + }; + let mut settings = Settings::default(); + settings + .repertoire_context_policies + .insert("opening".into(), policy); + + let json = serde_json::to_string_pretty(&settings).unwrap(); + let restored: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(restored.repertoire_context_policies["opening"], policy); + + let legacy = r#"{ + "repertoire_modes": {}, + "repertoire_priorities": {} + }"#; + let restored: Settings = serde_json::from_str(legacy).unwrap(); + assert!(restored.repertoire_context_policies.is_empty()); + } +} diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs new file mode 100644 index 0000000..e6cea5f --- /dev/null +++ b/apps/desktop/src/settings_ui.rs @@ -0,0 +1,1025 @@ +//! Settings window: engines, board & pieces, sound, interface, about. + +use crate::i18n::{Lang, tr, trf}; +use egui::{RichText, Sense, Ui, vec2}; +use shakmaty::{Color, Piece, Role}; + +use crate::assets::{BoardThemeId, PieceSet, SoundSet}; +use crate::settings::Settings; + +#[derive(Clone, Copy, PartialEq, Eq, Default)] +pub enum Tab { + #[default] + Engines, + Board, + Sound, + Interface, + Translation, + /// What the web version keeps in the browser. + #[cfg(web)] + BrowserData, + About, +} + +pub enum SettingsAction { + /// All of «My games» as a downloaded PGN. + #[cfg(web)] + DownloadMyGames, + /// Ask the browser to keep the site's data for good. + #[cfg(web)] + KeepData, + #[cfg(not(web))] + AddEngine, + /// Download the official Stockfish (decision 14). + DownloadEngine, + CancelDownload, + /// Delete the downloaded Stockfish from the disk (it was removed from the list). + RemoveDownloaded, + TestSound, + /// The active engine (or its options) changed; a running analysis should restart. + EngineChanged, + /// Ask now whether a newer version is out. + #[cfg(not(web))] + CheckUpdates, + /// Choose the folder for new databases. + #[cfg(not(web))] + PickBaseFolder, + /// Open the update window. + #[cfg(not(web))] + OpenUpdate, +} + +pub struct SettingsWindow { + pub open: bool, + pub tab: Tab, + pub checking_engine: bool, + /// The running (or last) Stockfish download, set by the application every frame. + pub download: Option, + /// Engine whose removal (with its downloaded files) waits for confirmation. + confirm_remove: Option, + /// What the update check found, set by the application every frame, and the newer + /// version if there is one. + pub update_status: Option, + pub update_available: Option, +} + +impl SettingsWindow { + pub fn new() -> Self { + Self { + open: false, + tab: Tab::default(), + checking_engine: false, + download: None, + confirm_remove: None, + update_status: None, + update_available: None, + } + } + + /// Returns actions and whether settings changed (to be saved). + pub fn show( + &mut self, + ctx: &egui::Context, + s: &mut Settings, + translation: &mut crate::translate_ui::Hub, + ) -> (Vec, bool) { + let mut actions = Vec::new(); + let mut changed = false; + let mut open = self.open; + // A real, unpainted click target: the opening click belongs to its + // original widget, and the dismissing click never belongs to the board. + let backdrop = open.then(|| { + let rect = ctx.viewport_rect(); + egui::Area::new(egui::Id::new("settings_backdrop")) + .fixed_pos(rect.min) + .sense(Sense::click()) + .show(ctx, |ui| ui.set_min_size(rect.size())) + .response + }); + let window = egui::Window::new(tr("Settings")) + .open(&mut open) + .default_size(vec2(560.0, 680.0)) + // Open at the right edge so the board stays visible for live preview. + .pivot(egui::Align2::RIGHT_TOP) + .default_pos(ctx.content_rect().right_top() + vec2(-16.0, 60.0)) + .collapsible(false) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.selectable_value(&mut self.tab, Tab::Engines, tr("Engines")); + ui.selectable_value(&mut self.tab, Tab::Board, tr("Board & pieces")); + ui.selectable_value(&mut self.tab, Tab::Sound, tr("Sound")); + ui.selectable_value(&mut self.tab, Tab::Interface, tr("Interface")); + if crate::platform::CAPS.translation { + ui.selectable_value(&mut self.tab, Tab::Translation, tr("Translation")); + } + #[cfg(web)] + ui.selectable_value(&mut self.tab, Tab::BrowserData, tr("Browser data")); + ui.selectable_value(&mut self.tab, Tab::About, tr("About")); + }); + ui.separator(); + egui::ScrollArea::vertical().show(ui, |ui| match self.tab { + Tab::Engines => self.engines(ui, s, &mut actions, &mut changed), + Tab::Board => board_tab(ui, s, &mut changed), + Tab::Translation => changed |= translation.settings_tab(ui, s), + #[cfg(web)] + Tab::BrowserData => browser_data(ui, &mut actions), + Tab::Sound => sound_tab(ui, s, &mut actions, &mut changed), + Tab::About => { + let (status, available) = + (self.update_status.clone(), self.update_available.clone()); + about_tab(ui, s.language, |ui| { + // Updates, right under the version (the web version is + // always the latest: a reload brings it). + #[cfg(not(web))] + updates(ui, s, &status, &available, &mut actions, &mut changed); + #[cfg(web)] + let _ = (ui, &status, &available); + }); + } + Tab::Interface => { + ui.horizontal(|ui| { + ui.label(tr("Language:")); + egui::ComboBox::from_id_salt("language") + .selected_text(s.language.label()) + .show_ui(ui, |ui| { + for lang in Lang::ALL { + if ui + .selectable_value(&mut s.language, lang, lang.label()) + .changed() + { + crate::i18n::set_lang(lang); + changed = true; + } + } + }); + }); + ui.horizontal(|ui| { + ui.label(tr("Theme:")); + changed |= ui + .selectable_value(&mut s.dark_mode, true, tr("Dark")) + .changed(); + changed |= ui + .selectable_value(&mut s.dark_mode, false, tr("Light")) + .changed(); + }); + ui.add_space(12.0); + ui.label(RichText::new(tr("Your databases")).strong()); + ui.horizontal(|ui| { + ui.label(tr("Your name:")); + changed |= ui + .add( + egui::TextEdit::singleline(&mut s.your_name) + .desired_width(220.0), + ) + .changed(); + }); + ui.label( + RichText::new(tr("Written as the annotator of the games you add")) + .weak(), + ); + // A browser has no folders for databases. + #[cfg(not(web))] + ui.horizontal(|ui| { + ui.label(tr("Folder for new databases:")); + let dir = + crate::own_db::default_base_dir(s.new_database_dir.as_deref()); + // Short, under the home folder; the whole path on hover. + let home = + directories::UserDirs::new().map(|u| u.home_dir().to_path_buf()); + let short = match home.as_ref().and_then(|h| dir.strip_prefix(h).ok()) { + Some(rest) => { + format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()) + } + None => dir.display().to_string(), + }; + ui.label(RichText::new(short).weak()) + .on_hover_text(dir.display().to_string()); + if ui.button(tr("Change…")).clicked() { + actions.push(SettingsAction::PickBaseFolder); + } + }); + changed |= ui + .checkbox( + &mut s.record_games, + tr("Write games against the computer to the player's database"), + ) + .changed(); + } + }); + }); + if let (Some(backdrop), Some(window)) = (backdrop, window) { + ctx.set_sublayer(backdrop.layer_id, window.response.layer_id); + if backdrop.clicked_by(egui::PointerButton::Primary) { + open = false; + } + } + self.open = open; + (actions, changed) + } + + fn engines( + &mut self, + ui: &mut Ui, + s: &mut Settings, + actions: &mut Vec, + changed: &mut bool, + ) { + ui.label( + RichText::new(tr("UCI engines. The active one is used for game analysis. Time, lines, threads and memory are set with âš™ in the analysis panel.")).weak(), + ); + ui.add_space(6.0); + let downloading = self.download.as_ref().is_some_and(|d| { + matches!( + d, + crate::engine_download::Stage::Downloading { .. } + | crate::engine_download::Stage::Unpacking + ) + }); + // No engine yet: the two ways to get one, plainly. + if s.engines.is_empty() { + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(RichText::new(tr("No engine yet")).strong()); + ui.label( + RichText::new(tr("An engine evaluates positions and suggests moves. Stockfish is the strongest free one.")) + .weak(), + ); + ui.add_space(4.0); + ui.horizontal(|ui| { + if downloading { + self.download_progress(ui, actions); + } else if crate::engine_download::available() + && ui + .button(RichText::new(tr("⬇ Download Stockfish 19")).strong()) + .on_hover_text(trf( + "{mb} MB from the official Stockfish page; installed for your account only", + &[("mb", &crate::engine_download::size_mb())], + )) + .clicked() + { + actions.push(SettingsAction::DownloadEngine); + } + // A browser has no engine programs. + #[cfg(not(web))] + if ui.button(tr("Choose engine file…")).clicked() { + actions.push(SettingsAction::AddEngine); + } + }); + }); + } + let mut remove = None; + for i in 0..s.engines.len() { + let active = s.active_engine == Some(i); + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + if ui + .radio(active, "") + .on_hover_text(tr("Make active")) + .clicked() + && !active + { + s.active_engine = Some(i); + *changed = true; + actions.push(SettingsAction::EngineChanged); + } + let e = &mut s.engines[i]; + *changed |= ui + .add(egui::TextEdit::singleline(&mut e.name).desired_width(220.0)) + .changed(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let downloaded = + s.engines[i].builtin && crate::engines::bundled_stockfish().is_none(); + let hint = if downloaded { + tr("Remove (and delete the downloaded files)") + } else { + tr("Remove from list") + }; + if ui.button("🗑").on_hover_text(hint).clicked() { + if downloaded && crate::engine_download::installed().is_some() { + self.confirm_remove = Some(i); + } else { + remove = Some(i); + } + } + }); + }); + let e = &s.engines[i]; + if e.builtin { + if let Some(p) = crate::engines::bundled_stockfish() { + ui.label( + RichText::new(tr("Included with ChessPenguin")) + .small() + .weak(), + ) + .on_hover_text(p.display().to_string()); + } else if let Some(p) = crate::engine_download::installed() { + let mb = crate::engine_download::installed_mb(); + ui.label( + RichText::new(trf( + "Downloaded by ChessPenguin · {mb} MB", + &[("mb", &mb)], + )) + .small() + .weak(), + ) + .on_hover_text(p.to_string()); + } else { + ui.horizontal(|ui| { + ui.label( + RichText::new(tr("âš  File not found")) + .small() + .color(ui.visuals().warn_fg_color), + ); + if downloading { + self.download_progress(ui, actions); + } else if crate::engine_download::available() + && ui.small_button(tr("Download again")).clicked() + { + actions.push(SettingsAction::DownloadEngine); + } + }); + } + } else { + ui.label(RichText::new(e.path.display().to_string()).small().weak()); + } + }); + } + if let Some(i) = self.confirm_remove { + let mut answer = None; + let modal = egui::Modal::new(egui::Id::new("remove_engine")).show(ui.ctx(), |ui| { + ui.set_width(360.0); + let mb = crate::engine_download::installed_mb(); + ui.label(trf( + "Remove Stockfish 19? This frees {mb} MB. You can download it again at any time.", + &[("mb", &mb)], + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let cancel = ui.button(tr("Cancel")); + cancel.request_focus(); + if cancel.clicked() { + answer = Some(false); + } + if ui.button(tr("Remove")).clicked() { + answer = Some(true); + } + }); + }); + }); + if modal.should_close() { + answer = Some(false); + } + match answer { + Some(true) => { + remove = Some(i); + actions.push(SettingsAction::RemoveDownloaded); + self.confirm_remove = None; + } + Some(false) => self.confirm_remove = None, + None => {} + } + } + if let Some(i) = remove { + s.engines.remove(i); + s.active_engine = match s.active_engine { + Some(a) if a == i => (!s.engines.is_empty()).then_some(0), + Some(a) if a > i => Some(a - 1), + a => a, + }; + *changed = true; + actions.push(SettingsAction::EngineChanged); + } + let found = crate::engines::suggestions(s); + if !found.is_empty() { + ui.add_space(6.0); + ui.label(RichText::new(tr("Found on this computer:")).strong()); + for cfg in found { + ui.horizontal(|ui| { + let path = cfg.executable().map(|l| l.to_string()).unwrap_or_default(); + ui.label(&cfg.name).on_hover_text(path); + if ui.button(tr("Add")).clicked() { + s.engines.push(cfg); + if s.active_engine.is_none() { + s.active_engine = Some(s.engines.len() - 1); + actions.push(SettingsAction::EngineChanged); + } + *changed = true; + } + }); + } + } + // ChessPenguin's Stockfish can always be (re)downloaded from here. + // Not when a Stockfish of the user's is there already (it would be the same + // engine twice). + let own = crate::engines::own_stockfish().is_some(); + let has_stockfish = s + .engines + .iter() + .any(|e| e.name.to_lowercase().contains("stockfish") && e.executable().is_some()); + if !s.engines.is_empty() && !own && !has_stockfish && crate::engine_download::available() { + ui.add_space(6.0); + ui.horizontal(|ui| { + if downloading { + self.download_progress(ui, actions); + } else if ui + .button(trf( + "⬇ Download Stockfish 19 · {mb} MB", + &[("mb", &crate::engine_download::size_mb())], + )) + .on_hover_text(tr( + "From the official Stockfish page; installed for your account only", + )) + .clicked() + { + actions.push(SettingsAction::DownloadEngine); + } + }); + } + ui.add_space(6.0); + // A browser has no engine programs. + #[cfg(not(web))] + ui.horizontal(|ui| { + if ui + .add_enabled( + !self.checking_engine, + egui::Button::new(tr("+ Choose engine file…")), + ) + .clicked() + { + actions.push(SettingsAction::AddEngine); + } + if self.checking_engine { + ui.spinner(); + ui.label(tr("Checking engine…")); + } + }); + } +} + +impl SettingsWindow { + /// The download's progress in place of its button, with a cancel button. + fn download_progress(&self, ui: &mut Ui, actions: &mut Vec) { + match &self.download { + Some(crate::engine_download::Stage::Downloading { done, total }) => { + let frac = if *total > 0 { + *done as f32 / *total as f32 + } else { + 0.0 + }; + ui.add(egui::ProgressBar::new(frac).desired_width(200.0).text(trf( + "{done} of {total} MB", + &[ + ("done", &(done / 1_000_000)), + ("total", &(total / 1_000_000)), + ], + ))); + } + _ => { + ui.spinner(); + ui.label(tr("Checking and installing…")); + } + } + if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Cancel download")) + .clicked() + { + actions.push(SettingsAction::CancelDownload); + } + } +} + +fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) { + ui.label(RichText::new(tr("Piece set")).strong()); + ui.horizontal_wrapped(|ui| { + for set in PieceSet::ALL { + let selected = s.piece_set == set; + let (rect, resp) = ui.allocate_exact_size(vec2(110.0, 64.0), Sense::click()); + let v = ui.visuals(); + let fill = if selected { + v.selection.bg_fill + } else if resp.hovered() { + v.widgets.hovered.weak_bg_fill + } else { + v.faint_bg_color + }; + ui.painter().rect_filled(rect, 6.0, fill); + let size = 44.0; + let board = s.board_theme.theme(); + for (k, role) in [Role::Knight, Role::Queen].into_iter().enumerate() { + let color = if k == 0 { Color::White } else { Color::Black }; + let r = egui::Rect::from_min_size( + rect.left_top() + vec2(8.0 + k as f32 * 48.0, 2.0), + vec2(size, size), + ); + // Preview on the current board colours so dark sets stay readable. + let square = if k == 0 { board.light } else { board.dark }; + ui.painter().rect_filled(r, 3.0, square); + set.paint(ui, Piece { color, role }, r); + } + ui.painter().text( + rect.center_bottom() - vec2(0.0, 4.0), + egui::Align2::CENTER_BOTTOM, + set.name(), + egui::FontId::proportional(12.0), + v.text_color(), + ); + if resp.clicked() { + s.piece_set = set; + *changed = true; + } + } + }); + ui.add_space(8.0); + notation_section(ui, s, changed); + ui.add_space(8.0); + ui.label(RichText::new(tr("Board")).strong()); + // The hint above the notation goes away; what it told stays here, in sight. + ui.label( + RichText::new(tr( + "Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]).", + )) + .weak(), + ); + ui.horizontal_wrapped(|ui| { + for id in BoardThemeId::ALL { + let t = id.theme(); + let selected = s.board_theme == id; + let (rect, resp) = ui.allocate_exact_size(vec2(64.0, 64.0), Sense::click()); + let sq = rect.width() / 2.0; + if let Some(uri) = t.texture { + // A quarter of the full-board image = 2×2 squares, like the flat swatches. + egui::Image::new(uri) + .uv(egui::Rect::from_min_max( + egui::pos2(0.0, 0.75), + egui::pos2(0.25, 1.0), + )) + .paint_at(ui, rect); + } + for (k, c) in [t.light, t.dark, t.dark, t.light] + .into_iter() + .enumerate() + .filter(|_| t.texture.is_none()) + { + let r = egui::Rect::from_min_size( + rect.min + vec2((k % 2) as f32 * sq, (k / 2) as f32 * sq), + vec2(sq, sq), + ); + ui.painter().rect_filled(r, 0.0, c); + } + if selected { + ui.painter().rect_stroke( + rect, + 2.0, + egui::Stroke::new(3.0, ui.visuals().selection.bg_fill), + egui::StrokeKind::Outside, + ); + } + if resp.on_hover_text(id.label()).clicked() { + s.board_theme = id; + *changed = true; + } + } + }); + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(tr("Piece animation")); + for a in crate::settings::Animation::ALL { + *changed |= ui + .selectable_value(&mut s.animation, a, a.label()) + .changed(); + } + }); + *changed |= ui + .checkbox(&mut s.show_coords, tr("Show coordinates")) + .changed(); + *changed |= ui + .checkbox(&mut s.auto_queen, tr("Always promote to a queen")) + .on_hover_text(tr( + "Off: a pawn on the last rank asks which piece it becomes", + )) + .changed(); + *changed |= ui + .checkbox(&mut s.show_best_arrow, tr("Show engine best-move arrows")) + .changed(); +} + +/// "Move notation": Latin letters, figurines, the interface language's letters, with a +/// sample for each and a line of a game as it will look. +fn notation_section(ui: &mut Ui, s: &mut Settings, changed: &mut bool) { + use crate::san::{MoveNotation, local_letters, show_in}; + let lang = crate::i18n::current(); + ui.label(RichText::new(tr("Move notation")).strong()); + // In English the language's letters are the Latin ones: that option is not shown. + let local = local_letters(lang); + let shown = if s.move_notation == MoveNotation::Local && local.is_none() { + MoveNotation::Latin + } else { + s.move_notation + }; + let sample = |m: MoveNotation| { + ["Nf3", "Qxd8+", "e8=Q"] + .map(|x| show_in(x, m, lang).into_owned()) + .join(" ") + }; + let mut options = vec![ + ( + MoveNotation::Latin, + tr("Letters (K Q R B N)").to_owned(), + tr("International notation, as in PGN files and engine output"), + ), + ( + MoveNotation::Figurine, + tr("Figurines").to_owned(), + tr("Piece symbols, as on Lichess. They look the same in every language."), + ), + ]; + if let Some(l) = local { + options.push(( + MoveNotation::Local, + format!("{} ({})", tr("Interface language letters"), l.join(" ")), + tr("Follows the interface language"), + )); + } + egui::Grid::new("move_notation") + .num_columns(2) + .spacing(vec2(24.0, 4.0)) + .show(ui, |ui| { + for (mode, label, tip) in options { + let r = ui.radio(shown == mode, label).on_hover_text(tip); + let r2 = ui + .add( + egui::Label::new(RichText::new(sample(mode)).size(15.0)) + .sense(Sense::click()), + ) + .on_hover_text(tip); + if (r.clicked() || r2.clicked()) && s.move_notation != mode { + s.move_notation = mode; + *changed = true; + } + ui.end_row(); + } + }); + // A line of a game, the current move highlighted as in the notation. + let line = "1.e4 e5 2.Nf3 Nc6 3.Bb5 a6 4.Ba4 Nf6 5.O-O Be7 6.Re1 b5"; + let mode = shown; + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + for word in line.split(' ') { + let text = RichText::new(show_in(word, mode, lang).into_owned()).size(16.0); + if word == "3.Bb5" { + let sel = ui.visuals().selection; + let galley = egui::Label::new(text.color(sel.stroke.color).strong()); + egui::Frame::new() + .fill(sel.bg_fill) + .corner_radius(2.0) + .inner_margin(egui::Margin::symmetric(3, 0)) + .show(ui, |ui| ui.add(galley)); + } else { + ui.label(text); + } + } + }); + }); + ui.label( + RichText::new(tr( + "Only how moves look on screen. PGN files and copied games always use K Q R B N.", + )) + .weak(), + ); +} + +const SITE: &str = "https://chess.vrubel.xyz"; +const REPO: &str = "https://github.com/vrubelroman/chessPenguin"; +const EMAIL: &str = "vrubelroman@gmail.com"; + +/// Version, links to the website and the sources, support contacts. +fn about_tab(ui: &mut Ui, lang: Lang, updates: impl FnOnce(&mut Ui)) { + let version = env!("CARGO_PKG_VERSION"); + // The website page in the interface language. + let site = match lang { + Lang::En => format!("{SITE}/"), + Lang::Ru => format!("{SITE}/ru/"), + Lang::Fr => format!("{SITE}/fr/"), + Lang::De => format!("{SITE}/de/"), + Lang::Es => format!("{SITE}/es/"), + Lang::It => format!("{SITE}/it/"), + Lang::Pt => format!("{SITE}/pt/"), + Lang::Uz => format!("{SITE}/uz/"), + Lang::Kk => format!("{SITE}/kk/"), + }; + ui.add_space(6.0); + ui.label(RichText::new("ChessPenguin").size(22.0).strong()); + ui.label(format!("{} {version}", tr("Version"))); + updates(ui); + ui.label( + RichText::new(tr( + "Free chess database software for Windows, macOS and Linux.", + )) + .weak(), + ); + ui.add_space(8.0); + ui.horizontal_wrapped(|ui| { + ui.hyperlink_to(tr("Website"), &site); + ui.label("·"); + ui.hyperlink_to(tr("What's new"), format!("{REPO}/releases/tag/v{version}")); + ui.label("·"); + ui.hyperlink_to(tr("Source code"), REPO); + }); + ui.add_space(14.0); + ui.label(RichText::new(tr("Found a problem or have an idea? Write to us:")).strong()); + ui.horizontal_wrapped(|ui| { + // Copied rather than opened: a mailto link does nothing useful without a mail app. + let copied_at = egui::Id::new("about_email_copied"); + let now = ui.input(|i| i.time); + let copied = ui + .data(|d| d.get_temp::(copied_at)) + .is_some_and(|t| now - t < 2.0); + let link = ui + .link(EMAIL) + .on_hover_text(tr("Click to copy the address")); + if link.clicked() { + ui.ctx().copy_text(EMAIL.to_owned()); + ui.data_mut(|d| d.insert_temp(copied_at, now)); + } + if copied { + ui.label(RichText::new(tr("Copied")).weak()); + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(250)); + } + ui.label("·"); + ui.hyperlink_to("Telegram @vrubelr", "https://t.me/vrubelr"); + }); + ui.add_space(14.0); + ui.label( + RichText::new(tr("Free software under GPL-3.0-or-later. Piece sets, boards and sounds come from Lichess under their own free licences.")) + .weak() + .small(), + ); +} + +fn sound_tab(ui: &mut Ui, s: &mut Settings, actions: &mut Vec, changed: &mut bool) { + *changed |= ui + .checkbox(&mut s.sound_enabled, tr("Move sounds")) + .changed(); + ui.add_enabled_ui(s.sound_enabled, |ui| { + ui.horizontal(|ui| { + ui.label(tr("Set:")); + for set in SoundSet::ALL { + if ui + .selectable_value(&mut s.sound_set, set, set.label()) + .changed() + { + *changed = true; + actions.push(SettingsAction::TestSound); + } + } + }); + ui.horizontal(|ui| { + ui.label(tr("Volume:")); + let r = ui.add(egui::Slider::new(&mut s.volume, 0.0..=1.0).show_value(false)); + *changed |= r.changed(); + if r.drag_stopped() { + actions.push(SettingsAction::TestSound); + } + if ui.button(tr("â–¶ Test")).clicked() { + actions.push(SettingsAction::TestSound); + } + }); + }); +} + +/// Updates in the About tab: the version out, «Check now», the check at start. +#[cfg(not(web))] +fn updates( + ui: &mut Ui, + s: &mut Settings, + status: &Option, + available: &Option, + actions: &mut Vec, + changed: &mut bool, +) { + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + match (available, status) { + (Some(v), _) => { + let label = RichText::new(trf("⬆ Update to {v}…", &[("v", v)])) + .color(ui.visuals().hyperlink_color); + if ui.button(label).clicked() { + actions.push(SettingsAction::OpenUpdate); + } + } + (None, Some(st)) => { + ui.label(RichText::new(st).weak()); + } + (None, None) => {} + } + if ui.button(tr("Check now")).clicked() { + actions.push(SettingsAction::CheckUpdates); + } + }); + *changed |= ui + .checkbox(&mut s.check_updates, tr("Check for updates at start")) + .on_hover_text(tr( + "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", + )) + .changed(); +} + +/// Settings → Browser data (docs/design/web-version.md §2.3): what is kept only in this +/// browser, how much room it takes and is left, and the way to take «My games» along. +#[cfg(web)] +fn browser_data(ui: &mut Ui, actions: &mut Vec) { + use crate::platform::{size_text, web}; + ui.label(tr( + "Everything below is stored only here, on this device. Files on disk are not changed.", + )); + ui.add_space(6.0); + if let Some((used, quota)) = web::storage::usage() { + ui.label(trf( + "Used {used} · free for the site {free}", + &[ + ("used", &size_text(used)), + ("free", &size_text(quota.saturating_sub(used))), + ], + )); + } + ui.horizontal(|ui| match web::storage::persisted() { + Some(true) => { + ui.label(tr("Persistent storage: on")); + } + _ => { + ui.label( + RichText::new(tr("Persistent storage: not allowed by the browser")) + .color(ui.visuals().warn_fg_color), + ); + if ui.button(tr("Ask the browser")).clicked() { + actions.push(SettingsAction::KeepData); + } + } + }); + ui.add_space(8.0); + egui::Grid::new("browser data") + .num_columns(3) + .spacing([16.0, 6.0]) + .show(ui, |ui| { + ui.label(trf( + "My games · {n}", + &[("n", &crate::i18n::games(crate::my_games::count()))], + )); + ui.label(size_text(crate::my_games::size())); + if ui.button(tr("Download all as PGN")).clicked() { + actions.push(SettingsAction::DownloadMyGames); + } + ui.end_row(); + if web::engine::ready() { + ui.label(tr("Stockfish 19 engine")); + ui.label(size_text(web::engine::WASM_BYTES)); + if ui.button(tr("Delete")).clicked() { + actions.push(SettingsAction::RemoveDownloaded); + } + ui.end_row(); + } + }); + ui.add_space(8.0); + ui.label( + RichText::new(tr( + "If you clear the site's data in the browser, all of this is lost. Download your games as PGN to keep them.", + )) + .weak(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{Event, Modifiers, PointerButton, Pos2, Rect}; + + struct Screen { + ctx: egui::Context, + window: SettingsWindow, + settings: Settings, + opener: Rect, + clicks: usize, + } + + impl Screen { + fn new() -> Self { + let mut screen = Self { + ctx: Default::default(), + window: SettingsWindow::new(), + settings: Settings { + language: Lang::En, + ..Default::default() + }, + opener: Rect::NOTHING, + clicks: 0, + }; + screen.window.tab = Tab::Sound; + screen.frame(vec![]); + screen.click(screen.opener.center()); + screen.frame(vec![]); + assert!(screen.window.open); + assert_eq!(screen.clicks, 1); + screen + } + + fn frame(&mut self, events: Vec) -> egui::FullOutput { + let mut output = self.ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 900.0))), + events, + ..Default::default() + }, + |ui| { + let r = ui.button("Open settings"); + self.opener = r.rect; + if r.clicked() { + self.clicks += 1; + self.window.open = true; + } + self.window + .show(ui.ctx(), &mut self.settings, &mut Default::default()); + }, + ); + output.textures_delta.clear(); + output + } + + fn pointer(&mut self, pos: Pos2, button: PointerButton, pressed: bool) { + self.frame(vec![ + Event::PointerMoved(pos), + Event::PointerButton { + pos, + button, + pressed, + modifiers: Modifiers::NONE, + }, + ]); + } + + fn click(&mut self, pos: Pos2) { + self.pointer(pos, PointerButton::Primary, true); + self.pointer(pos, PointerButton::Primary, false); + } + + fn text(&mut self, label: &str) -> Pos2 { + self.frame(vec![]) + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(t) if t.galley.text() == label => { + Some(t.pos + 0.5 * t.galley.size()) + } + _ => None, + }) + .unwrap_or_else(|| panic!("missing visible label: {label}")) + } + } + + #[test] + fn only_an_outside_primary_click_dismisses_and_it_never_reaches_the_opener() { + let mut s = Screen::new(); + let outside = s.opener.center(); + s.pointer(outside, PointerButton::Secondary, true); + s.pointer(outside, PointerButton::Secondary, false); + assert!(s.window.open); + + let inside = s.text(tr("Move sounds")); + s.pointer(inside, PointerButton::Primary, true); + s.frame(vec![Event::PointerMoved(outside)]); + s.pointer(outside, PointerButton::Primary, false); + assert!(s.window.open); + s.pointer(outside, PointerButton::Primary, true); + assert!(s.window.open); + s.pointer(outside, PointerButton::Primary, false); + assert!(!s.window.open); + assert_eq!(s.clicks, 1); + } + + #[test] + fn settings_tabs_popup_items_and_titlebar_close_still_receive_clicks() { + let mut s = Screen::new(); + let interface = s.text(tr("Interface")); + s.click(interface); + assert!(s.window.tab == Tab::Interface); + let combo = s.text(Lang::En.label()); + let layer = s.ctx.layer_id_at(combo).unwrap(); + let rect = s.ctx.memory(|m| m.area_rect(layer.id)).unwrap(); + s.click(combo); + let choice = s.text(Lang::Kk.label()); + assert!(!rect.contains(choice), "exercise the overhanging popup"); + s.click(choice); + assert_eq!(s.settings.language, Lang::Kk); + assert!(s.window.open); + + s.frame(vec![]); + let title = s.text(tr("Settings")); + let layer = s.ctx.layer_id_at(title).unwrap(); + let rect = s.ctx.memory(|m| m.area_rect(layer.id)).unwrap(); + s.click(egui::pos2(rect.right() - 15.0, title.y)); + assert!(!s.window.open); + } +} diff --git a/apps/desktop/src/sound.rs b/apps/desktop/src/sound.rs new file mode 100644 index 0000000..9474fb1 --- /dev/null +++ b/apps/desktop/src/sound.rs @@ -0,0 +1,99 @@ +//! Sound playback: on a computer on a dedicated thread (missing audio devices are +//! tolerated silently); in a browser by its audio elements, each sound's file made once. + +#[cfg(not(web))] +use std::io::Cursor; +#[cfg(not(web))] +use std::sync::mpsc::{Sender, channel}; + +use crate::assets::{Sound, SoundSet, sound_bytes}; + +#[cfg(not(web))] +pub struct SoundPlayer { + tx: Option>, +} + +#[cfg(not(web))] +impl SoundPlayer { + pub fn new() -> Self { + let (tx, rx) = channel::<(SoundSet, Sound, f32)>(); + let spawned = std::thread::Builder::new() + .name("sound".into()) + .spawn(move || { + let sink = match rodio::DeviceSinkBuilder::open_default_sink() { + Ok(mut s) => { + s.log_on_drop(false); + s + } + Err(e) => { + eprintln!("sound disabled: {e}"); + // Drain so senders never block; nothing is played. + for _ in rx {} + return; + } + }; + for (set, sound, volume) in rx { + let Ok(decoder) = + rodio::Decoder::try_from(Cursor::new(sound_bytes(set, sound))) + else { + continue; + }; + let player = rodio::Player::connect_new(sink.mixer()); + player.set_volume(volume); + player.append(decoder); + player.detach(); + } + }); + Self { + tx: spawned.ok().map(|_| tx), + } + } + + pub fn play(&self, set: SoundSet, sound: Sound, volume: f32) { + if let Some(tx) = &self.tx { + let _ = tx.send((set, sound, volume)); + } + } +} + +/// The sounds' files for the page's audio elements (`blob:` addresses), by the sound's +/// bytes (each sound is a file of its own). +#[cfg(web)] +pub struct SoundPlayer { + urls: std::cell::RefCell>, +} + +#[cfg(web)] +impl SoundPlayer { + pub fn new() -> Self { + Self { + urls: Default::default(), + } + } + + fn url(&self, bytes: &'static [u8]) -> Option { + let key = bytes.as_ptr() as usize; + if let Some(u) = self.urls.borrow().get(&key) { + return Some(u.clone()); + } + let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); + let opts = web_sys::BlobPropertyBag::new(); + opts.set_type("audio/ogg"); + let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).ok()?; + let url = web_sys::Url::create_object_url_with_blob(&blob).ok()?; + self.urls.borrow_mut().insert(key, url.clone()); + Some(url) + } + + /// Plays the sound; a browser that cannot (no audio, not allowed yet) stays silent. + pub fn play(&self, set: SoundSet, sound: Sound, volume: f32) { + let Some(url) = self.url(sound_bytes(set, sound)) else { + return; + }; + if let Ok(audio) = web_sys::HtmlAudioElement::new_with_src(&url) { + audio.set_volume(f64::from(volume.clamp(0.0, 1.0))); + // The promise fails when the page may not play yet: nothing to do then. + let _ = audio.play(); + } + } +} diff --git a/apps/desktop/src/translate.rs b/apps/desktop/src/translate.rs new file mode 100644 index 0000000..ad63370 --- /dev/null +++ b/apps/desktop/src/translate.rs @@ -0,0 +1,1736 @@ +//! Translating game annotations into the reader's language (docs/design/translation.md). +//! +//! Only the text of comments goes to the language model: board commands are cut out by +//! `notation::comment_text`, moves stay in the text and must come back unchanged (a +//! translation that loses or alters a move is not shown). Translations live in a cache +//! beside the program's other caches, never in the PGN. + +use std::collections::HashMap; +use std::io::{BufRead, BufReader, Write as _}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use chess_core::{Game, NodeId}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use crate::i18n::Lang; + +// --- Connections ----------------------------------------------------------------------- + +/// How the program reaches a language model. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Connection { + /// The user's ChatGPT subscription (Sign in with ChatGPT). + #[default] + ChatGpt, + /// A service with an OpenAI-compatible API: a key, or a model on this computer. + Key, +} + +/// Services with an OpenAI-compatible API. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Preset { + #[default] + DeepSeek, + OpenAi, + Gemini, + Ollama, + LmStudio, + Custom, +} + +impl Preset { + pub const ALL: [Preset; 6] = [ + Preset::DeepSeek, + Preset::OpenAi, + Preset::Gemini, + Preset::Ollama, + Preset::LmStudio, + Preset::Custom, + ]; + + pub fn name(self) -> &'static str { + match self { + Preset::DeepSeek => "DeepSeek", + Preset::OpenAi => "OpenAI", + Preset::Gemini => "Google Gemini", + Preset::Ollama => "Ollama", + Preset::LmStudio => "LM Studio", + Preset::Custom => crate::i18n::tr("Another address"), + } + } + + /// The id the key and the consent are kept under. + pub fn id(self) -> &'static str { + match self { + Preset::DeepSeek => "deepseek", + Preset::OpenAi => "openai", + Preset::Gemini => "gemini", + Preset::Ollama => "ollama", + Preset::LmStudio => "lmstudio", + Preset::Custom => "custom", + } + } + + pub fn base(self) -> &'static str { + match self { + Preset::DeepSeek => "https://api.deepseek.com", + Preset::OpenAi => "https://api.openai.com/v1", + Preset::Gemini => "https://generativelanguage.googleapis.com/v1beta/openai", + Preset::Ollama => "http://127.0.0.1:11434/v1", + Preset::LmStudio => "http://127.0.0.1:1234/v1", + Preset::Custom => "", + } + } + + /// The model used until the user picks another one ("" — the first the service lists). + pub fn model(self) -> &'static str { + match self { + Preset::DeepSeek => "deepseek-chat", + Preset::Gemini => "gemini-2.5-flash", + Preset::Ollama => crate::translate_ui::OLLAMA_MODEL, + _ => "", + } + } + + /// Where to get a key (none for a model on this computer). + pub fn key_page(self) -> Option<&'static str> { + match self { + Preset::DeepSeek => Some("https://platform.deepseek.com/api_keys"), + Preset::OpenAi => Some("https://platform.openai.com/api-keys"), + Preset::Gemini => Some("https://aistudio.google.com/apikey"), + _ => None, + } + } + + /// The service's privacy policy (none for a model on this computer or another address). + pub fn privacy(self) -> Option<&'static str> { + match self { + Preset::DeepSeek => { + Some("https://cdn.deepseek.com/policies/en-US/deepseek-privacy-policy.html") + } + Preset::OpenAi => Some("https://openai.com/policies/privacy-policy/"), + Preset::Gemini => Some("https://ai.google.dev/gemini-api/terms"), + _ => None, + } + } + + pub fn needs_key(self) -> bool { + self.key_page().is_some() + } + + /// `response_format: json_object` is understood (the others may reject it). + fn json_mode(self) -> bool { + matches!(self, Preset::DeepSeek | Preset::OpenAi | Preset::Gemini) + } +} + +/// The translation part of the settings. +#[derive(Clone, Debug, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct TranslationSettings { + /// The language to translate into (`None`: the interface language). + pub target: Option, + pub connection: Connection, + pub preset: Preset, + /// The address of `Preset::Custom`, or another address of a preset. + pub base: String, + /// The model chosen for the key connection ("" — the preset's). + pub model: String, + /// The model chosen for ChatGPT ("" — picked from the list after sign-in). + pub chatgpt_model: String, + /// Do not offer translations at all. + pub never_offer: bool, + /// The user agreed once: comments in another language are translated right away. + pub auto: bool, + /// Services the user allowed to receive comments (`Preset::id`, "chatgpt"). + pub allowed: Vec, + /// Sign in with ChatGPT: the stable id of this installation, the client id issued at + /// the first sign-in, and the account shown in the settings. + pub host_id: String, + pub client_id: String, + pub account: String, + /// How many times the offer was closed (from the second time: "Don't offer"). + pub declined: u32, +} + +impl TranslationSettings { + pub fn target(&self) -> Lang { + self.target.unwrap_or_else(crate::i18n::current) + } + + pub fn base(&self) -> String { + let b = if self.base.trim().is_empty() { + self.preset.base() + } else { + self.base.trim() + }; + b.trim_end_matches('/').to_owned() + } + + pub fn model(&self) -> String { + if self.model.trim().is_empty() { + self.preset.model().to_owned() + } else { + self.model.trim().to_owned() + } + } + + /// The id consent is given for. + pub fn service_id(&self) -> String { + match self.connection { + Connection::ChatGpt => "chatgpt".into(), + Connection::Key if self.is_local() => "local".into(), + Connection::Key if self.preset == Preset::Custom => format!("custom:{}", self.base()), + Connection::Key => self.preset.id().into(), + } + } + + /// The name of the service shown to the user. + pub fn service_name(&self) -> String { + match self.connection { + Connection::ChatGpt => "ChatGPT".into(), + Connection::Key if self.preset == Preset::Custom => host_of(&self.base()), + Connection::Key => self.preset.name().into(), + } + } + + /// The model runs on this computer: no consent asked. + pub fn is_local(&self) -> bool { + self.connection == Connection::Key && is_local_address(&self.base()) + } + + pub fn allowed(&self) -> bool { + self.is_local() || self.allowed.contains(&self.service_id()) + } + + /// Everything needed to send a request is there. + pub fn ready(&self) -> bool { + match self.connection { + Connection::ChatGpt => credentials().chatgpt.is_some(), + Connection::Key => { + !self.base().is_empty() + && (!self.preset.needs_key() || credentials().key(self.preset.id()).is_some()) + } + } + } +} + +pub fn host_of(url: &str) -> String { + let rest = url.split("://").nth(1).unwrap_or(url); + rest.split('/').next().unwrap_or(rest).to_owned() +} + +pub fn is_local_address(url: &str) -> bool { + let host = host_of(url); + let host = host + .rsplit_once(':') + .filter(|(h, p)| !h.is_empty() && p.chars().all(|c| c.is_ascii_digit())) + .map_or(host.as_str(), |(h, _)| h); + matches!(host, "127.0.0.1" | "localhost" | "[::1]" | "::1") +} + +// --- Credentials --------------------------------------------------------------------------- + +/// Keys and ChatGPT tokens, apart from the settings, in a file only the user can read +/// (as the Codex CLI keeps its sign-in). +#[derive(Clone, Debug, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Credentials { + /// API keys by `Preset::id`. + pub keys: HashMap, + pub chatgpt: Option, +} + +impl Credentials { + pub fn key(&self, id: &str) -> Option<&str> { + self.keys + .get(id) + .map(|k| k.trim()) + .filter(|k| !k.is_empty()) + } +} + +static CREDENTIALS: Mutex> = Mutex::new(None); + +fn credentials_file() -> Option { + crate::settings::Settings::config_dir().map(|d| d.join("credentials.json")) +} + +pub fn credentials() -> Credentials { + let mut c = CREDENTIALS.lock().unwrap_or_else(|e| e.into_inner()); + c.get_or_insert_with(|| { + credentials_file() + .and_then(|f| std::fs::read_to_string(f).ok()) + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + }) + .clone() +} + +/// Changes the credentials and writes them, under one lock (a token refresh in the +/// background and a key typed in the settings must not undo each other). +pub fn update_credentials(change: impl FnOnce(&mut Credentials)) { + let mut guard = CREDENTIALS.lock().unwrap_or_else(|e| e.into_inner()); + let c = guard.get_or_insert_with(|| { + credentials_file() + .and_then(|f| std::fs::read_to_string(f).ok()) + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + }); + change(c); + let c = c.clone(); + if let Some(f) = credentials_file() { + if let Some(d) = f.parent() { + let _ = std::fs::create_dir_all(d); + } + if let Ok(text) = serde_json::to_string_pretty(&c) { + let tmp = f.with_extension("json.tmp"); + if write_private(&tmp, &text).is_ok() { + let _ = std::fs::rename(&tmp, &f); + } + } + } +} + +fn write_private(path: &std::path::Path, text: &str) -> std::io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(path)?; + // A file left from before keeps its mode on open: set it again. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + file.write_all(text.as_bytes()) +} + +// --- Which comments to translate -------------------------------------------------------- + +/// The comments of a game in reading order (the text the notation shows), each once. +pub fn comments(game: &Game) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |c: &[String]| { + let t = crate::notation::comment_text(c); + if !t.is_empty() && !out.contains(&t) { + out.push(t); + } + }; + let mut ids = vec![NodeId::ROOT]; + ids.extend(game.attached_nodes()); + for id in ids { + if let Some(n) = game.node(id) { + push(n.comments_before()); + push(n.comments_after()); + } + } + out +} + +/// Letters of the words that are not moves, squares or numbers: what tells the language. +fn prose(text: &str) -> String { + text.split_whitespace() + .filter(|w| moves_in(w).is_empty()) + .flat_map(|w| w.chars().filter(|c| c.is_alphabetic()).chain([' '])) + .collect() +} + +/// The languages comments are told apart in (others are rare in chess texts and make +/// short English look like Afrikaans or Tagalog). +const LANGUAGES: &[whatlang::Lang] = { + use whatlang::Lang::*; + &[ + Eng, Rus, Deu, Fra, Spa, Ita, Por, Nld, Ukr, Bel, Pol, Ces, Slk, Slv, Hrv, Srp, Bul, Mkd, + Ron, Hun, Ell, Tur, Swe, Dan, Nob, Fin, Est, Lav, Lit, Cat, Epo, Lat, Kat, Hye, Aze, Heb, + Ara, Pes, Cmn, Jpn, Kor, Vie, Hin, Ind, Uzb, + ] +}; + +fn detect_info(text: &str) -> Option { + static DETECTOR: std::sync::OnceLock = std::sync::OnceLock::new(); + DETECTOR + .get_or_init(|| whatlang::Detector::with_allowlist(LANGUAGES.to_vec())) + .detect(text) +} + +/// The language of one comment for the plan: a short text in the script of `target` +/// that the detector cannot tell apart reliably (Russian notes read as Ukrainian or +/// Bulgarian) is taken for `target` — the reader's own notes are not translated. +fn comment_lang(text: &str, target: Option) -> Option { + let info = detect_info(text)?; + if let Some(t) = target + && info.lang() != t + && !info.is_reliable() + && info.script() == script_of(t) + { + return Some(t); + } + Some(info.lang()) +} + +/// The script a language is written in, as the detector names it. +fn script_of(lang: whatlang::Lang) -> whatlang::Script { + use whatlang::Lang::*; + match lang { + Rus | Ukr | Bel | Bul | Mkd | Srp => whatlang::Script::Cyrillic, + Ell => whatlang::Script::Greek, + Kat => whatlang::Script::Georgian, + Hye => whatlang::Script::Armenian, + Heb => whatlang::Script::Hebrew, + Ara | Pes => whatlang::Script::Arabic, + Cmn => whatlang::Script::Mandarin, + Jpn => whatlang::Script::Katakana, + Kor => whatlang::Script::Hangul, + Hin => whatlang::Script::Devanagari, + _ => whatlang::Script::Latin, + } +} + +/// The language as the detector knows it (`None`: it does not tell Kazakh, so every +/// comment counts as another language). +pub fn language_of(lang: Lang) -> Option { + Some(match lang { + Lang::En => whatlang::Lang::Eng, + Lang::Ru => whatlang::Lang::Rus, + Lang::Fr => whatlang::Lang::Fra, + Lang::De => whatlang::Lang::Deu, + Lang::Es => whatlang::Lang::Spa, + Lang::It => whatlang::Lang::Ita, + Lang::Pt => whatlang::Lang::Por, + Lang::Uz => whatlang::Lang::Uzb, + Lang::Kk => return None, + }) +} + +/// What a game's comments need. +#[derive(Clone, Debug, PartialEq)] +pub struct Plan { + /// The language of most of the foreign text. + pub source: whatlang::Lang, + /// The comments to translate. + pub texts: Vec, + /// All the comments with text. + pub total: usize, +} + +/// A comment shorter than this (in letters) takes the language of the game. +const SHORT: usize = 25; + +/// The comments not in `target`, if there are enough of them to offer a translation: +/// three comments or 150 letters. Short ones ("Weak.", "Better was") follow the language +/// of the game. +pub fn plan(texts: &[String], target: Lang) -> Option { + let target = language_of(target); + let mut letters: HashMap = HashMap::new(); + let detected: Vec<(usize, Option, Option)> = texts + .iter() + .map(|t| { + let p = prose(t); + let n = p.chars().filter(|c| c.is_alphabetic()).count(); + let lang = (n >= SHORT).then(|| comment_lang(&p, target)).flatten(); + if let Some(l) = lang { + *letters.entry(l).or_default() += n; + } + (n, lang, whatlang::detect_script(&p)) + }) + .collect(); + let mut game_lang = letters.iter().max_by_key(|(_, n)| **n).map(|(l, _)| *l); + // Only short comments: their text together tells the language. + if game_lang.is_none() { + let all: String = texts.iter().map(|t| prose(t)).collect::>().join(" "); + if all.chars().filter(|c| c.is_alphabetic()).count() >= SHORT { + // Short phrases glued together: only the usual languages of chess books. + use whatlang::Lang::*; + game_lang = whatlang::Detector::with_allowlist(vec![Eng, Rus, Deu, Fra, Spa, Ita]) + .detect(&all) + .map(|i| i.lang()); + if let Some(l) = game_lang { + letters.insert(l, all.chars().filter(|c| c.is_alphabetic()).count()); + } + } + } + // A short note in the script of the interface language, in a book of another + // script ("Размен в пользу белых" in a Dutch book), is the reader's own: not foreign. + let own_script = |script: Option| { + target.is_some_and(|t| script == Some(script_of(t))) + && game_lang.is_some_and(|g| script != Some(script_of(g))) + }; + let foreign: Vec = detected + .iter() + .enumerate() + .filter(|(_, (n, lang, script))| { + *n > 0 + && match lang { + Some(l) => Some(*l) != target, + None => game_lang.is_some_and(|g| Some(g) != target) && !own_script(*script), + } + }) + .map(|(i, _)| i) + .collect(); + let foreign_letters: usize = foreign.iter().map(|&i| detected[i].0).sum(); + if foreign.len() < 3 && foreign_letters < 60 { + return None; + } + let source = letters + .iter() + .filter(|(l, _)| Some(**l) != target) + .max_by_key(|(_, n)| **n) + .map(|(l, _)| *l)?; + Some(Plan { + source, + texts: foreign.into_iter().map(|i| texts[i].clone()).collect(), + total: texts.len(), + }) +} + +// --- Moves must come back unchanged -------------------------------------------------------- + +/// Piece letters a move may start with: Latin, figurines, and the Russian ones (a +/// translation must not swap one for another). +const PIECES: &[&str] = &[ + "Кр", "K", "Q", "R", "B", "N", "â™”", "♕", "â™–", "â™—", "♘", "♚", "â™›", "♜", "â™�", "♞", "Ф", "Л", "С", + "К", +]; + +fn file(c: char) -> bool { + ('a'..='h').contains(&c) +} + +fn rank(c: char) -> bool { + ('1'..='8').contains(&c) +} + +/// A move or a square starting at `c[i]` (a word boundary): its length in chars. +fn move_at(c: &[char], i: usize) -> Option { + let rest: String = c[i..c.len().min(i + 7)].iter().collect(); + for castle in ["O-O-O", "0-0-0", "O-O", "0-0"] { + if rest.starts_with(castle) { + return Some(castle.chars().count()); + } + } + let mut j = i; + if let Some(p) = PIECES.iter().find(|p| rest.starts_with(**p)) { + j += p.chars().count(); + } + // [file][rank][x] before the target square: the longest form that ends on a square. + let at = |k: usize| c.get(k).copied().unwrap_or(' '); + let square_at = |k: usize| file(at(k)) && rank(at(k + 1)); + let mut found = None; + for len in [2usize, 1, 0] { + let ok = match len { + 2 => file(at(j)) && rank(at(j + 1)), + 1 => file(at(j)) || rank(at(j)), + _ => true, + }; + if !ok { + continue; + } + let mut k = j + len; + if at(k) == 'x' { + k += 1; + } + // Without a capture, a lone square is the move itself (len 0), not a disambiguation. + if square_at(k) && (len == 0 || at(j + len) == 'x' || len < 2 || square_at(j + 2)) { + found = Some(k); + break; + } + } + let mut k = found? + 2; + // Promotion: "=Q", or "Q" right after the last rank ("e8Q"). + if at(k) == '=' && "QRBN".contains(at(k + 1)) { + k += 2; + } else if "QRBN".contains(at(k)) + && !at(k + 1).is_alphanumeric() + && matches!(at(k - 1), '1' | '8') + { + k += 1; + } + Some(k - i) +} + +/// The moves and squares of a text, normalized ("0-0" → "O-O", "e8Q" → "e8=Q") and +/// sorted. Words are cut at any non-letter: "a4-a5", "Nf3/Ng5", "the e5-square", +/// "12.Nf3," all give their moves. +fn moves_in(text: &str) -> Vec { + let c: Vec = text.chars().collect(); + let mut v = Vec::new(); + let mut i = 0; + while i < c.len() { + let boundary = i == 0 || !c[i - 1].is_alphabetic(); + if boundary && let Some(n) = move_at(&c, i) { + let end = i + n; + if c.get(end).is_none_or(|x| !x.is_alphanumeric()) { + let mut m: String = c[i..end].iter().collect(); + m = m.replace('0', "O"); + if let Some(q) = m.chars().last() + && "QRBN".contains(q) + && !m.contains('=') + && m.chars().count() >= 3 + && m.chars().rev().nth(1).is_some_and(|r| r == '1' || r == '8') + { + m.insert(m.len() - 1, '='); + } + v.push(m); + i = end; + continue; + } + } + i += 1; + } + v.sort(); + v +} + +/// A translation keeps every move and square of the original. +pub fn same_moves(original: &str, translation: &str) -> bool { + !translation.trim().is_empty() && moves_in(original) == moves_in(translation) +} + +// --- The instructions --------------------------------------------------------------------- + +/// English name of the target language for the model. +fn english_name(lang: Lang) -> &'static str { + match lang { + Lang::En => "English", + Lang::Ru => "Russian", + Lang::Fr => "French", + Lang::De => "German", + Lang::Es => "Spanish", + Lang::It => "Italian", + Lang::Pt => "Brazilian Portuguese", + Lang::Uz => "Uzbek (Latin script)", + Lang::Kk => "Kazakh (Cyrillic script)", + } +} + +/// Chess terms as players of the language say them (English → target). +fn glossary(lang: Lang) -> &'static str { + match lang { + Lang::Ru => { + "exchange (rook for a minor piece) — качеÑ�тво; to win the exchange — выиграть качеÑ�тво; trade, exchange of pieces — размен; passed pawn — проходнаÑ� пешка; isolated pawn — изолированнаÑ� пешка; doubled pawns — Ñ�двоенные пешки; backward pawn — отÑ�талаÑ� пешка; pawn chain — пешечнаÑ� цепь; outpost — форпоÑ�Ñ‚; open file — открытаÑ� линиÑ�; half-open file — полуоткрытаÑ� линиÑ�; diagonal — диагональ; back rank — поÑ�леднÑ�Ñ� горизонталь; fork — вилка; pin — Ñ�вÑ�зка; skewer — Ñ�квозной удар (рентген); discovered attack — вÑ�крытое нападение; double attack — двойной удар; zwischenzug, intermediate move — промежуточный ход; sacrifice — жертва; combination — комбинациÑ�; initiative — инициатива; tempo — темп; zugzwang — цугцванг; stalemate — пат; perpetual check — вечный шах; opposition — оппозициÑ�; fianchetto — фианкетто; bishop pair — два Ñ�лона (преимущеÑ�тво двух Ñ�лонов); minor piece — лёгкаÑ� фигура; major piece — Ñ‚Ñ�жёлаÑ� фигура; development — развитие; castling — рокировка; endgame — Ñ�ндшпиль; middlegame — миттельшпиль; opening — дебют; blunder — грубаÑ� ошибка (зевок); inaccuracy — неточноÑ�ть; time trouble — цейтнот; resigns — Ñ�даётÑ�Ñ�; draw — ничьÑ�; decisive advantage — решающий перевеÑ�; compensation — компенÑ�ациÑ�" + } + Lang::De => { + "exchange (rook for a minor piece) — Qualität; passed pawn — Freibauer; isolated pawn — isolierter Bauer (Isolani); doubled pawns — Doppelbauern; backward pawn — rückständiger Bauer; outpost — Vorposten; open file — offene Linie; back rank — Grundreihe; fork — Gabel; pin — Fesselung; skewer — Spieß; discovered attack — Abzugsangriff; zwischenzug — Zwischenzug; sacrifice — Opfer; initiative — Initiative; tempo — Tempo; zugzwang — Zugzwang; stalemate — Patt; perpetual check — Dauerschach; opposition — Opposition; fianchetto — Fianchetto; bishop pair — Läuferpaar; minor piece — Leichtfigur; major piece — Schwerfigur; development — Entwicklung; endgame — Endspiel; middlegame — Mittelspiel; opening — Eröffnung; blunder — grober Fehler (Patzer); time trouble — Zeitnot" + } + Lang::Fr => { + "exchange (rook for a minor piece) — la qualité; passed pawn — pion passé; isolated pawn — pion isolé; doubled pawns — pions doublés; backward pawn — pion arriéré; outpost — avant-poste; open file — colonne ouverte; back rank — dernière rangée; fork — fourchette; pin — clouage; skewer — enfilade; discovered attack — attaque à la découverte; zwischenzug — coup intermédiaire; sacrifice — sacrifice; initiative — initiative; tempo — temps; zugzwang — zugzwang; stalemate — pat; perpetual check — échec perpétuel; opposition — opposition; fianchetto — fianchetto; bishop pair — paire de fous; minor piece — pièce mineure; major piece — pièce lourde; development — développement; endgame — finale; middlegame — milieu de partie; opening — ouverture; blunder — gaffe; time trouble — zeitnot (crise de temps)" + } + Lang::Es => { + "exchange (rook for a minor piece) — la calidad; passed pawn — peón pasado; isolated pawn — peón aislado; doubled pawns — peones doblados; backward pawn — peón retrasado; outpost — puesto avanzado; open file — columna abierta; back rank — última fila; fork — horquilla (doble ataque); pin — clavada; skewer — ataque en rayos X (pincho); discovered attack — ataque a la descubierta; zwischenzug — jugada intermedia; sacrifice — sacrificio; initiative — iniciativa; tempo — tiempo; zugzwang — zugzwang; stalemate — ahogado; perpetual check — jaque perpetuo; opposition — oposición; fianchetto — fianchetto; bishop pair — pareja de alfiles; minor piece — pieza menor; major piece — pieza mayor; development — desarrollo; endgame — final; middlegame — medio juego; opening — apertura; blunder — error grave; time trouble — apuros de tiempo" + } + Lang::It => { + "exchange (rook for a minor piece) — la qualità; passed pawn — pedone passato; isolated pawn — pedone isolato; doubled pawns — pedoni doppiati; backward pawn — pedone arretrato; outpost — avamposto; open file — colonna aperta; back rank — ultima traversa; fork — forchetta; pin — inchiodatura; skewer — infilata; discovered attack — attacco di scoperta; zwischenzug — mossa intermedia; sacrifice — sacrificio; initiative — iniziativa; tempo — tempo; zugzwang — zugzwang; stalemate — stallo; perpetual check — scacco perpetuo; opposition — opposizione; fianchetto — fianchetto; bishop pair — coppia degli alfieri; minor piece — pezzo leggero; major piece — pezzo pesante; development — sviluppo; endgame — finale; middlegame — mediogioco; opening — apertura; blunder — svista; time trouble — zeitnot" + } + Lang::Pt => { + "exchange (rook for a minor piece) — a qualidade; passed pawn — peão passado; isolated pawn — peão isolado; doubled pawns — peões dobrados; backward pawn — peão atrasado; outpost — posto avançado; open file — coluna aberta; back rank — última fileira; fork — garfo; pin — cravada; skewer — espeto; discovered attack — ataque descoberto; zwischenzug — lance intermediário; sacrifice — sacrifício; initiative — iniciativa; tempo — tempo; zugzwang — zugzwang; stalemate — afogamento; perpetual check — xeque perpétuo; opposition — oposição; fianchetto — fianqueto; bishop pair — par de bispos; minor piece — peça menor; major piece — peça maior; development — desenvolvimento; endgame — final; middlegame — meio-jogo; opening — abertura; blunder — erro grave (capivarada); time trouble — apuro de tempo" + } + Lang::Uz => { + "exchange (rook for a minor piece) — sifat; passed pawn — o‘tar piyoda; isolated pawn — yakkalangan piyoda; doubled pawns — qo‘shaloq piyodalar; open file — ochiq vertikal; fork — vilka; pin — bog‘lash; sacrifice — qurbonlik; initiative — tashabbus; tempo — temp; zugzwang — sugsvang; stalemate — pat; perpetual check — abadiy shoh; castling — roqirovka; endgame — endshpil; middlegame — mittelshpil; opening — debyut; blunder — qo‘pol xato; time trouble — vaqt tanqisligi (seytnot); draw — durang" + } + Lang::Kk => { + "exchange (rook for a minor piece) — Ñ�апа; passed pawn — өтпелі Ñ�арбаз; isolated pawn — оқшау Ñ�арбаз; doubled pawns — қоÑ�арланған Ñ�арбаздар; open file — ашық тік Ñ�ызық; fork — шанышқы; pin — байлау; sacrifice — құрбандық; initiative — баÑ�тама; tempo — темп; zugzwang — цугцванг; stalemate — пат; perpetual check — мәңгі шах; castling — рокировка; endgame — Ñ�ндшпиль; middlegame — миттельшпиль; opening — дебют; blunder — өреÑ�кел қате; time trouble — уақыт тапшылығы (цейтнот); draw — тең ойын" + } + Lang::En => { + "Russian качеÑ�тво — the exchange (rook for a minor piece); размен — exchange of pieces, trade; проходнаÑ� — passed pawn; цугцванг — zugzwang; вилка — fork; Ñ�вÑ�зка — pin; вечный шах — perpetual check; цейтнот — time trouble; German Qualität — the exchange; Freibauer — passed pawn; Fesselung — pin; Gabel — fork; Abzug — discovered attack; Läuferpaar — bishop pair; Spanish/Italian calidad/qualità — the exchange; clavada/inchiodatura — pin; horquilla/forchetta — fork" + } + } +} + +fn instructions(target: Lang) -> String { + let lang = english_name(target); + format!( + "You translate the annotations (comments) of chess games into {lang} for chess players.\n\ + The input is JSON: {{\"game\": {{…}}, \"comments\": [{{\"id\": number, \"text\": string}}]}}. \ + \"game\" names the players, the event and the opening: use it to get names and terms right; do not translate it.\n\ + Rules:\n\ + 1. Translate only the natural-language text of each comment into {lang}.\n\ + 2. Copy every chess move and square exactly as written, character for character: e4, Nf3, Bxe5+, exd8=Q#, O-O, O-O-O, 12.Nf3, 12...Nf6, the d-file, the e5-square. Never translate, transliterate or replace the piece letters K, Q, R, B, N inside moves, and never add or remove moves.\n\ + 3. Keep the names of people, events and places as written; keep numbers, results (1-0, ½-½), evaluation symbols (+-, =, ±, ∓, !, ?, !?, ?!) and URLs. Text in brackets is text: translate it too.\n\ + 4. A part that is already in {lang} stays as it is.\n\ + 5. Use the chess terms {lang}-speaking players use. Glossary: {glossary}.\n\ + 6. Do not add, drop, explain, summarize or comment on anything. Keep the tone, the paragraph breaks and the meaning.\n\ + 7. Answer with JSON only, no other text: {{\"translations\": [{{\"id\": number, \"text\": string}}]}} with every id of the input exactly once.", + glossary = glossary(target) + ) +} + +/// The players, the event and the opening, for the model. +#[derive(Clone, Debug, Default, Serialize)] +pub struct GameContext { + pub white: String, + pub black: String, + pub event: String, + pub opening: String, +} + +impl GameContext { + pub fn of(game: &Game) -> GameContext { + let tag = |t| game.tag(t).unwrap_or("").to_owned(); + let opening = [tag("Opening"), tag("Variation")] + .into_iter() + .filter(|s| !s.is_empty()) + .collect::>() + .join(", "); + GameContext { + white: tag("White"), + black: tag("Black"), + event: tag("Event"), + opening: if opening.is_empty() { + tag("ECO") + } else { + opening + }, + } + } +} + +fn request(context: &GameContext, batch: &[(usize, &str)]) -> String { + let comments: Vec = batch + .iter() + .map(|(id, text)| json!({"id": id, "text": text})) + .collect(); + json!({"game": context, "comments": comments}).to_string() +} + +/// The translations in an answer, by id. Models sometimes wrap JSON in prose or a code +/// fence, give ids as strings, or a map instead of a list: the first object with +/// translations is taken. +fn parse_answer(answer: &str) -> HashMap { + let mut out = HashMap::new(); + let id = |v: &Value| { + v.as_u64() + .or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())) + .map(|n| n as usize) + }; + for (start, _) in answer.match_indices('{') { + let Some(Ok(v)) = serde_json::Deserializer::from_str(&answer[start..]) + .into_iter::() + .next() + else { + continue; + }; + let Some(list) = v.get("translations").or_else(|| v.get("comments")) else { + continue; + }; + if let Some(items) = list.as_array() { + for item in items { + if let (Some(n), Some(text)) = ( + item.get("id").and_then(id), + item.get("text").and_then(Value::as_str), + ) { + out.insert(n, text.trim().to_owned()); + } + } + } else if let Some(map) = list.as_object() { + for (k, t) in map { + if let (Ok(n), Some(text)) = (k.trim().parse::(), t.as_str()) { + out.insert(n, text.trim().to_owned()); + } + } + } + if !out.is_empty() { + break; + } + } + out +} + +// --- Errors ------------------------------------------------------------------------------ + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Failure { + /// The key (or the sign-in) is not accepted. + Key, + /// The account has no money left (DeepSeek: 402). + Money, + /// Too many requests even after waiting. + RateLimited, + /// The ChatGPT limit for ChessPenguin is used up. + PlanLimit, + /// The ChatGPT account cannot use its plan here (a free plan, a region). + NotEligible(String), + /// Signed out of ChatGPT (revoked, expired): sign in again. + SignedOut, + /// No connection to the service. + Offline(String), + /// The model on this computer does not answer (Ollama, LM Studio not running). + LocalDown, + /// The service has no such model. + NoModel(String), + /// Another error from the service: status and what it said. + Service(u16, String), +} + +impl std::fmt::Display for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Failure::Key => write!(f, "the key is not accepted"), + Failure::Money => write!(f, "insufficient balance"), + Failure::RateLimited => write!(f, "rate limited"), + Failure::PlanLimit => write!(f, "subscription_sharing_usage_limit_exceeded"), + Failure::NotEligible(e) => write!(f, "not eligible: {e}"), + Failure::SignedOut => write!(f, "signed out"), + Failure::Offline(e) => write!(f, "network: {e}"), + Failure::LocalDown => write!(f, "the local model does not answer"), + Failure::NoModel(m) => write!(f, "no model {m}"), + Failure::Service(code, body) => write!(f, "HTTP {code}: {body}"), + } + } +} + +#[cfg(not(web))] +pub fn agent(body_timeout: Duration) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .user_agent(format!( + "ChessPenguin/{} (+https://chess.vrubel.xyz)", + env!("CARGO_PKG_VERSION") + )) + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + // A model on a slow computer may think for minutes. + .timeout_recv_response(Some(body_timeout)) + .timeout_recv_body(Some(body_timeout)) + .build(); + ureq::Agent::new_with_config(config) +} + +/// What a service said in an error answer (OpenAI style `error.message`, or `detail`). +fn error_text(body: &str) -> String { + let v: Option = serde_json::from_str(body).ok(); + let msg = v.as_ref().and_then(|v| { + v.pointer("/error/message") + .or_else(|| v.get("error")) + .or_else(|| v.get("detail")) + .and_then(|m| m.as_str().map(str::to_owned)) + }); + let text = msg.unwrap_or_else(|| body.trim().to_owned()); + text.chars().take(300).collect() +} + +// --- Backends ---------------------------------------------------------------------------- + +/// Where one translation job sends its requests. +#[derive(Clone, Debug)] +pub enum Backend { + Chat { + base: String, + key: Option, + model: String, + json_mode: bool, + local: bool, + }, + ChatGpt { + model: String, + }, +} + +impl Backend { + /// From the settings (`None`: not set up yet). + pub fn from(s: &TranslationSettings) -> Option { + if !s.ready() { + return None; + } + Some(match s.connection { + Connection::ChatGpt => Backend::ChatGpt { + model: s.chatgpt_model.clone(), + }, + Connection::Key => Backend::Chat { + base: s.base(), + key: credentials().key(s.preset.id()).map(str::to_owned), + model: s.model(), + json_mode: s.preset.json_mode(), + local: s.is_local(), + }, + }) + } + + /// The model's answer to one request. + pub fn complete( + &self, + system: &str, + user: &str, + cancel: &AtomicBool, + ) -> Result { + match self { + Backend::Chat { + base, + key, + model, + json_mode, + local, + } => chat( + base, + key.as_deref(), + model, + *json_mode, + *local, + system, + user, + cancel, + ), + Backend::ChatGpt { model } => crate::chatgpt::respond(model, system, user, cancel), + } + } +} + +/// Why nothing is asked of a service in a browser: the web version has no machine +/// translation (its requests would block a thread the page does not have). +#[cfg(web)] +pub fn no_requests() -> Failure { + Failure::Offline("the web version makes no requests to translation services".into()) +} + +#[cfg(web)] +pub fn list_models(_base: &str, _key: Option<&str>, _local: bool) -> Result, Failure> { + Err(no_requests()) +} + +#[cfg(web)] +#[allow(clippy::too_many_arguments)] +fn chat( + _base: &str, + _key: Option<&str>, + _model: &str, + _json_mode: bool, + _local: bool, + _system: &str, + _user: &str, + _cancel: &AtomicBool, +) -> Result { + Err(no_requests()) +} + +#[cfg(not(web))] +/// The models a key connection offers (`GET {base}/models`). +pub fn list_models(base: &str, key: Option<&str>, local: bool) -> Result, Failure> { + let mut req = agent(Duration::from_secs(30)).get(format!("{base}/models")); + if let Some(k) = key { + req = req.header("Authorization", format!("Bearer {k}")); + } + let mut resp = req.call().map_err(|e| net_failure(e, local))?; + let status = resp.status().as_u16(); + let body = resp + .body_mut() + .with_config() + .limit(16 << 20) + .read_to_string() + .unwrap_or_default(); + if status != 200 { + return Err(status_failure(status, &body, "")); + } + let v: Value = + serde_json::from_str(&body).map_err(|e| Failure::Service(status, e.to_string()))?; + let mut ids: Vec = v + .get("data") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|m| m.get("id").and_then(Value::as_str)) + // Gemini lists "models/gemini-…". + .map(|id| id.trim_start_matches("models/").to_owned()) + .collect(); + ids.sort(); + Ok(ids) +} + +#[cfg(not(web))] +fn net_failure(e: ureq::Error, local: bool) -> Failure { + if local { + Failure::LocalDown + } else { + Failure::Offline(e.to_string()) + } +} + +fn status_failure(status: u16, body: &str, model: &str) -> Failure { + let text = error_text(body); + let lower = text.to_lowercase(); + match status { + 401 | 403 => Failure::Key, + 402 => Failure::Money, + 429 if lower.contains("quota") || lower.contains("balance") => Failure::Money, + 429 => Failure::RateLimited, + 404 if lower.contains("model") => Failure::NoModel(model.to_owned()), + 400 if lower.contains("model") && lower.contains("not") => { + Failure::NoModel(model.to_owned()) + } + _ => Failure::Service(status, text), + } +} + +#[cfg(not(web))] +#[allow(clippy::too_many_arguments)] +fn chat( + base: &str, + key: Option<&str>, + model: &str, + json_mode: bool, + local: bool, + system: &str, + user: &str, + cancel: &AtomicBool, +) -> Result { + let mut body = json!({ + "model": model, + "messages": [ + {"role": "system", "content": system}, + {"role": "user", "content": user}, + ], + "temperature": 0.2, + "stream": false, + }); + if json_mode { + body["response_format"] = json!({"type": "json_object"}); + } + let text = body.to_string(); + with_waits(cancel, || { + let mut req = agent(Duration::from_secs(if local { 300 } else { 180 })) + .post(format!("{base}/chat/completions")) + .header("Content-Type", "application/json"); + if let Some(k) = key { + req = req.header("Authorization", format!("Bearer {k}")); + } + let mut resp = req.send(&text).map_err(|e| net_failure(e, local))?; + let status = resp.status().as_u16(); + let answer = resp + .body_mut() + .with_config() + .limit(16 << 20) + .read_to_string() + .map_err(|e| net_failure(e, local))?; + if status != 200 { + return Err(status_failure(status, &answer, model)); + } + let v: Value = + serde_json::from_str(&answer).map_err(|e| Failure::Service(status, e.to_string()))?; + v.pointer("/choices/0/message/content") + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| Failure::Service(status, error_text(&answer))) + }) +} + +/// Seconds to wait before the next attempt after "too many requests" or a passing failure. +const WAITS: [u64; 3] = [5, 20, 40]; + +/// Status of a waiting job (seconds left), read by the interface. +pub static WAITING: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Repeats a request after a rate limit or a server hiccup, with waits; gives up on the +/// others at once. +pub fn with_waits( + cancel: &AtomicBool, + mut request: impl FnMut() -> Result, +) -> Result { + let mut waits = WAITS.iter(); + loop { + match request() { + Err(e @ (Failure::RateLimited | Failure::Service(500..=599, _))) => { + let Some(&secs) = waits.next() else { + return Err(e); + }; + for left in (1..=secs * 10).rev() { + if cancel.load(Ordering::Relaxed) { + WAITING.store(0, Ordering::Relaxed); + return Err(e); + } + WAITING.store(left.div_ceil(10), Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(100)); + } + WAITING.store(0, Ordering::Relaxed); + } + other => return other, + } + } +} + +/// A fixed sentence translated to check a connection (not the user's text). +pub fn sample(target: Lang) -> &'static str { + if target == Lang::En { + "Der Springer ist auf d5 stark." + } else { + "The knight is strong on d5." + } +} + +/// Translates the check sentence: the connection works when it comes back with its move. +pub fn check(backend: &Backend, target: Lang, cancel: &AtomicBool) -> Result { + let text = sample(target); + let answer = backend.complete( + &instructions(target), + &request(&GameContext::default(), &[(0, text)]), + cancel, + )?; + parse_answer(&answer) + .remove(&0) + .filter(|t| same_moves(text, t)) + .ok_or_else(|| Failure::Service(200, answer.chars().take(300).collect())) +} + +// --- The cache --------------------------------------------------------------------------- + +/// Translations by target language, then by the hash of the original text. +static CACHE: Mutex>>> = Mutex::new(None); + +fn cache_dir() -> Option { + if cfg!(test) { + return Some(std::env::temp_dir().join(format!("cp-translations-{}", std::process::id()))); + } + crate::settings::Settings::cache_dir().map(|d| d.join("translations")) +} + +fn lang_code(l: Lang) -> &'static str { + match l { + Lang::En => "en", + Lang::Ru => "ru", + Lang::Fr => "fr", + Lang::De => "de", + Lang::Es => "es", + Lang::It => "it", + Lang::Pt => "pt", + Lang::Uz => "uz", + Lang::Kk => "kk", + } +} + +/// The format version is part of the key: new instructions give new translations. +fn key(text: &str) -> String { + let mut h = Sha256::new(); + h.update(b"v2\0"); + h.update(text.as_bytes()); + h.finalize().iter().map(|b| format!("{b:02x}")).collect() +} + +#[derive(Serialize, Deserialize)] +struct CacheLine { + k: String, + t: String, + #[serde(default)] + via: String, +} + +fn with_cache(target: Lang, f: impl FnOnce(&mut HashMap) -> R) -> R { + let mut all = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let all = all.get_or_insert_with(HashMap::new); + let map = all.entry(target).or_insert_with(|| { + let mut m = HashMap::new(); + if let Some(f) = cache_dir().map(|d| d.join(format!("{}.jsonl", lang_code(target)))) + && let Ok(file) = std::fs::File::open(f) + { + for line in BufReader::new(file).lines().map_while(Result::ok) { + if let Ok(l) = serde_json::from_str::(&line) { + m.insert(l.k, l.t); + } + } + } + m + }); + f(map) +} + +pub fn cached(target: Lang, text: &str) -> Option { + with_cache(target, |m| m.get(&key(text)).cloned()) +} + +fn store(target: Lang, pairs: &[(String, String)], via: &str) { + with_cache(target, |m| { + let Some(dir) = cache_dir() else { return }; + let _ = std::fs::create_dir_all(&dir); + let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join(format!("{}.jsonl", lang_code(target)))) + else { + return; + }; + for (orig, t) in pairs { + let k = key(orig); + if let Ok(line) = serde_json::to_string(&CacheLine { + k: k.clone(), + t: t.clone(), + via: via.to_owned(), + }) { + let _ = writeln!(file, "{line}"); + } + m.insert(k, t.clone()); + } + }); +} + +/// Bytes the cache takes on the disk. +pub fn cache_size() -> u64 { + let Some(dir) = cache_dir() else { return 0 }; + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| e.metadata().ok()) + .map(|m| m.len()) + .sum() +} + +pub fn clear_cache() { + if let Some(dir) = cache_dir() { + let _ = std::fs::remove_dir_all(dir); + } + *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +// --- A translation job --------------------------------------------------------------------- + +pub enum Event { + /// Translated: (original, translation). + Done(Vec<(String, String)>), + /// These could not be translated (the answer lost or changed moves, or was empty). + Bad(Vec), + /// The job stopped on this error; what was done is kept. + Failed(Failure), + Finished, +} + +pub struct Job { + rx: Receiver, + cancel: Arc, +} + +/// About this much text goes in one request. +const BATCH_CHARS: usize = 5000; +const BATCH_ITEMS: usize = 40; + +/// These texts go in one request (then a count "n of total" says nothing). +pub fn one_batch(texts: &[String]) -> bool { + texts.len() <= BATCH_ITEMS && texts.iter().map(|t| t.len()).sum::() <= BATCH_CHARS +} + +impl Job { + pub fn start( + ctx: &egui::Context, + backend: Backend, + target: Lang, + via: String, + context: GameContext, + texts: Vec, + ) -> Job { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let c = cancel.clone(); + let ctx = ctx.clone(); + let _ = crate::platform::spawn("translate", move || { + run(&backend, target, &via, &context, texts, &c, &tx, &ctx); + let _ = tx.send(Event::Finished); + ctx.request_repaint(); + }); + Job { rx, cancel } + } + + pub fn poll(&self) -> Vec { + self.rx.try_iter().collect() + } + + pub fn stop(&self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +impl Drop for Job { + fn drop(&mut self) { + self.stop(); + } +} + +#[allow(clippy::too_many_arguments)] +fn run( + backend: &Backend, + target: Lang, + via: &str, + context: &GameContext, + texts: Vec, + cancel: &AtomicBool, + tx: &Sender, + ctx: &egui::Context, +) { + let system = instructions(target); + // No model chosen yet (a model on this computer never checked): the first listed. + let mut backend = backend.clone(); + if let Backend::Chat { + base, + key, + model, + local, + .. + } = &mut backend + && model.is_empty() + { + match list_models(base, key.as_deref(), *local) { + Ok(m) if !m.is_empty() => *model = m[0].clone(), + Ok(_) => { + let _ = tx.send(Event::Failed(Failure::NoModel(String::new()))); + return; + } + Err(e) => { + let _ = tx.send(Event::Failed(e)); + return; + } + } + } + // ChatGPT without a model yet (the check after the sign-in did not get that far). + if let Backend::ChatGpt { model } = &mut backend + && model.is_empty() + { + match crate::chatgpt::models() { + Ok(m) => match crate::chatgpt::default_model(&m) { + Some(d) => *model = d, + None => { + let _ = tx.send(Event::Failed(Failure::NoModel(String::new()))); + return; + } + }, + Err(e) => { + let _ = tx.send(Event::Failed(e)); + return; + } + } + } + let backend = &backend; + let mut batches: Vec> = Vec::new(); + let mut chars = 0; + for (i, t) in texts.iter().enumerate() { + let last = batches.last().map_or(0, Vec::len); + if batches.is_empty() || chars + t.len() > BATCH_CHARS || last >= BATCH_ITEMS { + batches.push(Vec::new()); + chars = 0; + } + chars += t.len(); + if let Some(b) = batches.last_mut() { + b.push((i, t.as_str())); + } + } + let send = |e: Event| { + let _ = tx.send(e); + ctx.request_repaint(); + }; + // A few requests at once: each waits for its whole answer, so one after another + // a long game took minutes. The first error stops the rest. + let next = AtomicUsize::new(0); + let failed = AtomicBool::new(false); + let stopped = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed); + let fail = |e: Failure| { + if !cancel.load(Ordering::Relaxed) && !failed.swap(true, Ordering::Relaxed) { + send(Event::Failed(e)); + } + }; + let worker = || { + while let Some(batch) = batches.get(next.fetch_add(1, Ordering::Relaxed)) { + if stopped() { + return; + } + let answer = match backend.complete(&system, &request(context, batch), cancel) { + Ok(a) => a, + Err(e) => return fail(e), + }; + let got = parse_answer(&answer); + let mut done = Vec::new(); + let mut again = Vec::new(); + for &(id, text) in batch { + match got.get(&id) { + Some(t) if same_moves(text, t) => done.push((text.to_owned(), t.clone())), + _ => again.push((id, text)), + } + } + // One more try for each comment that came back wrong, alone. + let mut bad = Vec::new(); + for (id, text) in again { + if stopped() { + break; + } + let retry = backend + .complete(&system, &request(context, &[(id, text)]), cancel) + .map(|a| parse_answer(&a)); + match retry { + Ok(got) => match got.get(&id) { + Some(t) if same_moves(text, t) => done.push((text.to_owned(), t.clone())), + _ => bad.push(text.to_owned()), + }, + Err(e) => { + store(target, &done, via); + send(Event::Done(done)); + return fail(e); + } + } + } + store(target, &done, via); + send(Event::Done(done)); + if !bad.is_empty() { + send(Event::Bad(bad)); + } + } + }; + std::thread::scope(|scope| { + for _ in 1..AT_ONCE.min(batches.len()) { + scope.spawn(worker); + } + worker(); + }); +} + +/// Requests sent at once. +const AT_ONCE: usize = 3; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore = "prints the instructions for a manual check"] + fn print_instructions() { + // TRANSLATE_LANG=en|ru|fr|de|es|it (Russian by default). + let lang = match std::env::var("TRANSLATE_LANG").as_deref() { + Ok("en") => Lang::En, + Ok("fr") => Lang::Fr, + Ok("de") => Lang::De, + Ok("es") => Lang::Es, + Ok("it") => Lang::It, + _ => Lang::Ru, + }; + println!("{}", instructions(lang)); + } + + #[test] + fn moves_are_found_in_text() { + let t = "After 12.Nf3 Bxe5+ 13.dxe5 (13.O-O!?) the e5-square is weak; 14...Kh8."; + assert_eq!( + moves_in(t), + vec!["Bxe5", "Kh8", "Nf3", "O-O", "dxe5", "e5"] + .into_iter() + .map(String::from) + .collect::>() + ); + let one = |w: &str| moves_in(w); + assert_eq!(one("exd8=Q#"), vec!["exd8=Q"]); + assert_eq!(one("Nbd7"), vec!["Nbd7"]); + assert_eq!(one("R1e2"), vec!["R1e2"]); + assert_eq!(one("Nf3xe5"), vec!["Nf3xe5"]); + assert_eq!(one("e4"), vec!["e4"]); + assert_eq!(one("0-0-0"), vec!["O-O-O"]); + assert_eq!(one("e8Q"), vec!["e8=Q"]); + assert_eq!(one("a4-a5"), vec!["a4", "a5"]); + assert_eq!(one("Nf3/Ng5"), vec!["Nf3", "Ng5"]); + assert_eq!(one("the e5-square"), vec!["e5"]); + assert_eq!(one("13.Qd2,Rd1"), vec!["Qd2", "Rd1"]); + assert_eq!(one("♘f3"), vec!["♘f3"]); + assert_eq!(one("Крg1 Фd8"), vec!["Крg1", "Фd8"]); + for word in ["Be", "the", "1-0", "12.", "a", "h9", "Zf3", "lead4", "Bb"] { + assert!(one(word).is_empty(), "{word}: {:?}", one(word)); + } + } + + #[test] + fn a_translation_must_keep_the_moves() { + let orig = "White should play 12.Nf3, not 12.Bd3?"; + assert!(same_moves( + orig, + "Белым Ñ�ледовало играть 12.Nf3, а не 12.Bd3?" + )); + assert!(!same_moves( + orig, + "Белым Ñ�ледовало играть 12.Кf3, а не 12.Bd3?" + )); + assert!(!same_moves(orig, "Белым Ñ�ледовало играть 12.Nf3.")); + assert!(!same_moves(orig, " ")); + assert!(same_moves("The e5-square is weak.", "Поле e5 Ñ�лабое.")); + assert!(same_moves("13.Qd2,Rd1", "13.Qd2, Rd1")); + assert!(same_moves("Nf3— strong", "Nf3 — Ñ�ильно")); + assert!(!same_moves("Nf3/Ng5", "Nf3/Nh5")); + assert!(!same_moves("a4-a5", "a4-a6")); + assert!(!same_moves("♘f3!", "Кf3!")); + } + + #[test] + fn foreign_comments_are_offered_and_short_ones_follow_the_game() { + let texts: Vec = [ + "White has a clear advantage because the knight on d5 dominates the board.", + "Weak.", + "Black should have played for the initiative on the queenside instead.", + "A typical mistake: the pawn structure is ruined and the endgame is lost.", + "+-", + ] + .map(String::from) + .to_vec(); + let p = plan(&texts, Lang::Ru).expect("English comments for a Russian reader"); + assert_eq!(p.source, whatlang::Lang::Eng); + assert_eq!(p.texts.len(), 4, "{:?}", p.texts); + assert!(p.texts.contains(&"Weak.".to_string())); + assert!(!p.texts.contains(&"+-".to_string())); + assert_eq!(plan(&texts, Lang::En), None); + } + + #[test] + fn a_game_of_short_comments_is_still_understood() { + let texts: Vec = [ + "Weak move.", + "Better was this.", + "The only move.", + "A blunder now.", + "Good idea here.", + "White wins.", + "Black is lost.", + "Too slow.", + "Much stronger.", + "A draw then.", + ] + .map(String::from) + .to_vec(); + let p = plan(&texts, Lang::Ru).expect("short English comments"); + assert_eq!(p.source, whatlang::Lang::Eng); + assert_eq!(p.texts.len(), 10); + } + + #[test] + fn one_foreign_word_is_not_offered() { + let texts = vec!["Zugzwang!".to_string(), "1-0".to_string()]; + assert_eq!(plan(&texts, Lang::Ru), None); + } + + #[test] + fn russian_comments_stay_for_a_russian_reader() { + let texts: Vec = [ + "Белые получают Ñ�вный перевеÑ�, конь на d5 гоÑ�подÑ�твует на доÑ�ке.", + "Слабо.", + "Черным Ñ�ледовало иÑ�кать контригру на ферзевом фланге.", + "ТипичнаÑ� ошибка: пешечнаÑ� Ñ�труктура иÑ�порчена, Ñ�ндшпиль проигран.", + ] + .map(String::from) + .to_vec(); + assert_eq!(plan(&texts, Lang::Ru), None); + assert_eq!(plan(&texts, Lang::En).map(|p| p.texts.len()), Some(4)); + } + + #[test] + fn answers_are_read_also_from_prose_and_fences() { + let a = "Sure!\n```json\n{\"translations\": [{\"id\": 0, \"text\": \" Конь Ñ�илён \"}, {\"id\": 2, \"text\": \"Слабо\"}]}\n```"; + let got = parse_answer(a); + assert_eq!(got.get(&0).map(String::as_str), Some("Конь Ñ�илён")); + assert_eq!(got.get(&2).map(String::as_str), Some("Слабо")); + assert!(parse_answer("no json here").is_empty()); + let a = r#"Here {note}: {"translations": [{"id": "1", "text": "Да"}]} {:)}"#; + assert_eq!(parse_answer(a).get(&1).map(String::as_str), Some("Да")); + let a = r#"{"translations": {"0": "Конь", "3": "Слон"}}"#; + let got = parse_answer(a); + assert_eq!(got.get(&3).map(String::as_str), Some("Слон")); + assert_eq!(got.len(), 2); + } + + #[test] + fn local_addresses() { + assert!(is_local_address("http://127.0.0.1:11434/v1")); + assert!(is_local_address("http://localhost:1234/v1")); + assert!(!is_local_address("https://api.deepseek.com")); + assert!(!is_local_address("http://192.168.1.5:11434/v1")); + } + + #[test] + fn batches_name_each_comment() { + let r = request(&GameContext::default(), &[(0, "a"), (1, "b")]); + let v: Value = serde_json::from_str(&r).unwrap(); + assert_eq!(v["comments"][1]["id"], 1); + assert_eq!(v["comments"][1]["text"], "b"); + } + /// An OpenAI-compatible server on 127.0.0.1 that "translates" by prefixing each + /// comment, and breaks the moves of comments containing "BREAK". + fn fake_service(requests: usize) -> (String, std::thread::JoinHandle>) { + use std::io::Read as _; + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let base = format!( + "http://127.0.0.1:{}/v1", + listener.local_addr().unwrap().port() + ); + let server = std::thread::spawn(move || { + let mut seen = Vec::new(); + for _ in 0..requests { + let (mut s, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut len = 0; + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap(); + } + if line == "\r\n" { + break; + } + } + let mut body = vec![0; len]; + reader.read_exact(&mut body).unwrap(); + let req: Value = serde_json::from_slice(&body).unwrap(); + let user: Value = + serde_json::from_str(req["messages"][1]["content"].as_str().unwrap()).unwrap(); + let out: Vec = user["comments"] + .as_array() + .unwrap() + .iter() + .map(|c| { + let t = c["text"].as_str().unwrap(); + let t = if t.contains("BREAK") { + t.replace("Nf3", "Кf3") + } else { + t.to_owned() + }; + json!({"id": c["id"], "text": format!("RU {t}")}) + }) + .collect(); + let content = json!({"translations": out}).to_string(); + let answer = json!({"choices": [{"message": {"content": content}}]}).to_string(); + write!( + s, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", + answer.len() + ) + .unwrap(); + seen.push(req); + } + seen + }); + (base, server) + } + + #[test] + fn a_job_translates_checks_moves_and_caches() { + // One batch, then the broken comment alone once more. + let (base, server) = fake_service(2); + let backend = Backend::Chat { + base, + key: None, + model: "m".into(), + json_mode: false, + local: true, + }; + let texts = vec![ + "After 12.Nf3 White is better.".to_string(), + "BREAK after 12.Nf3 the game is over.".to_string(), + ]; + let job = Job::start( + &egui::Context::default(), + backend, + Lang::It, + "test".into(), + GameContext::default(), + texts.clone(), + ); + let mut done = Vec::new(); + let mut bad = Vec::new(); + let start = web_time::Instant::now(); + 'wait: while start.elapsed() < Duration::from_secs(20) { + for e in job.poll() { + match e { + Event::Done(d) => done.extend(d), + Event::Bad(b) => bad.extend(b), + Event::Failed(f) => panic!("{f}"), + Event::Finished => break 'wait, + } + } + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(done, vec![(texts[0].clone(), format!("RU {}", texts[0]))]); + assert_eq!(bad, vec![texts[1].clone()]); + assert_eq!( + cached(Lang::It, &texts[0]), + Some(format!("RU {}", texts[0])) + ); + assert_eq!(cached(Lang::It, &texts[1]), None); + let seen = server.join().unwrap(); + assert!( + seen[0]["messages"][0]["content"] + .as_str() + .unwrap() + .contains("Italian") + ); + assert!(seen[0].get("response_format").is_none()); + } + + #[test] + fn a_long_game_goes_in_requests_at_once_and_every_comment_comes_back() { + // 100 comments: three requests (40, 40, 20), sent together. + let (base, server) = fake_service(3); + let backend = Backend::Chat { + base, + key: None, + model: "m".into(), + json_mode: false, + local: true, + }; + let texts: Vec = (0..100) + .map(|i| format!("Comment {i} on 12.Nf3.")) + .collect(); + let job = Job::start( + &egui::Context::default(), + backend, + Lang::Es, + "test".into(), + GameContext::default(), + texts.clone(), + ); + let mut done = Vec::new(); + let start = web_time::Instant::now(); + 'wait: while start.elapsed() < Duration::from_secs(20) { + for e in job.poll() { + match e { + Event::Done(d) => done.extend(d), + Event::Bad(b) => panic!("bad {b:?}"), + Event::Failed(f) => panic!("{f}"), + Event::Finished => break 'wait, + } + } + std::thread::sleep(Duration::from_millis(20)); + } + done.sort(); + let mut want: Vec<_> = texts + .iter() + .map(|t| (t.clone(), format!("RU {t}"))) + .collect(); + want.sort(); + assert_eq!(done, want); + assert_eq!(server.join().unwrap().len(), 3); + } +} + +#[cfg(test)] +mod own_comment_tests { + use super::*; + + #[test] + fn a_comment_in_the_interface_language_is_not_translated() { + // A Dutch book with the reader's own Russian notes: the notes stay. + let texts: Vec = [ + "Wit heeft een klein voordeel dankzij het loperpaar en de betere pionnenstructuur.", + "Zwart moet nu actief spelen, anders wordt de stelling langzaam slechter.", + "Een rustige zet die de spanning in het centrum handhaaft.", + "Ñ� не знаю наÑ�колько хорош Ñ�тот ход", + "Размен в пользу белых", + ] + .into_iter() + .map(String::from) + .collect(); + let plan = plan(&texts, Lang::Ru).expect("the Dutch comments need a translation"); + assert_eq!(plan.source, whatlang::Lang::Nld); + assert!( + !plan + .texts + .iter() + .any(|t| t.starts_with("Ñ� не знаю") || t.starts_with("Размен")), + "own Russian notes in the plan: {:?}", + plan.texts + ); + } +} diff --git a/apps/desktop/src/translate_ui.rs b/apps/desktop/src/translate_ui.rs new file mode 100644 index 0000000..fe85b0c --- /dev/null +++ b/apps/desktop/src/translate_ui.rs @@ -0,0 +1,2002 @@ +//! Translation in the interface (docs/design/translation-ui.md): the strip above the +//! notation and the marks on comments (`GameTranslation`, one per open game), and what +//! the whole program shares (`Hub`): the "How to translate?" window, the consent, the +//! ChatGPT sign-in, the connection check and the Settings › Translation tab. + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::Ordering; + +use egui::{RichText, Ui}; + +use crate::board_search::Background; +use crate::chatgpt::{SignIn, SignedIn}; +use crate::i18n::{Lang, tr, trf}; +use crate::settings::Settings; +use crate::translate::{ + self, Backend, Connection, Event, Failure, GameContext, Job, Plan, Preset, TranslationSettings, +}; + +/// The model suggested for Ollama (`ollama pull …`). +pub const OLLAMA_MODEL: &str = "qwen3:8b"; +/// Above this much foreign text a game waits for "Translate" even in automatic mode. +const BIG: usize = 60_000; +const CHATGPT_SETTINGS: &str = "https://chatgpt.com/#settings"; + +/// The name of a language in the interface language ("английÑ�кий"). +pub fn lang_name(l: whatlang::Lang) -> &'static str { + tr(l.eng_name()) +} + +fn thousands(chars: usize) -> String { + format!("{}", chars.div_ceil(1000).max(1)) +} + +// --- Marks in the notation --------------------------------------------------------------- + +/// What the notation shows for a comment. +#[derive(Clone, Debug, PartialEq)] +pub enum Mark { + Translated(String), + Pending, + Bad, +} + +// --- The program-wide part ---------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +enum Step { + #[default] + Choose, + /// Signing in with ChatGPT in the browser. + Waiting, + /// The check sentence is on its way. + Checking, + /// What will be sent, and "Start translating". + Consent, +} + +/// What the check found. +struct Checked { + models: Vec, + model: String, + result: Result, +} + +/// The state of the ChatGPT connection as last seen. +#[derive(Clone, Debug, PartialEq, Default)] +pub enum ChatGptState { + #[default] + Unknown, + Works(String), + NoPlan, + NotEligible, + Limit, + SignedOut, +} + +/// A message about the last sign-in attempt. +#[derive(Clone, Debug, PartialEq)] +enum SignInNote { + TimedOut, + Declined, + Failed(String), + NotPrepared(String), +} + +#[derive(Default)] +pub struct Hub { + /// The "How to translate?" window. + pub setup_open: bool, + step: Step, + /// The choice in the window (the settings change only once it works). + choice: Connection, + preset: Option, + key: String, + show_key: bool, + check: Option>, + check_result: Option>, + /// Models of the key connection, from the last check. + models: Vec, + sign_in: Option, + note: Option, + copied: Option, + pub chatgpt: ChatGptState, + /// The consent window, standing alone (the connection was ready already). + consent_open: bool, + /// The comments of the game asking: how many, how many characters. + consent_for: (usize, usize), + /// A game may start translating now (consent given, or set up). + start: bool, + clear_confirm: bool, + /// The settings tab should show the translation tab. + pub open_settings: bool, + /// A sign-in was started from the strip: it waits there. + sign_in_from_strip: bool, + /// The running sign-in or check belongs to a "Translate" (strip or setup window): when + /// it works, consent is asked if needed and the translation goes on by itself. + resume: bool, + /// The setup or the consent was turned down: the game hides its offer. + declined: bool, + /// Bumped when the cache is cleared: open games look at their comments again. + pub cache_epoch: u32, + /// The connection was fixed in the settings: a game that failed tries again. + retry_failed: bool, +} + +impl Hub { + /// The game asks to translate: set up first, ask for consent, or go. + fn request(&mut self, s: &mut TranslationSettings, n: usize, chars: usize) -> bool { + self.consent_for = (n, chars); + if !s.ready() { + self.open_setup(s); + false + } else if !s.allowed() { + self.consent_open = true; + false + } else { + true + } + } + + pub fn open_setup(&mut self, s: &TranslationSettings) { + if !self.setup_open { + self.step = Step::Choose; + self.choice = s.connection; + self.preset = Some(s.preset); + self.key = translate::credentials() + .key(s.preset.id()) + .unwrap_or("") + .to_owned(); + self.check_result = None; + } + self.setup_open = true; + } + + /// Dev hook (screenshots): opens the setup window. + pub fn debug_open_setup(&mut self, s: &TranslationSettings, key: bool) { + self.open_setup(s); + if key { + self.choice = Connection::Key; + } + } + + fn take_start(&mut self) -> bool { + std::mem::take(&mut self.start) + } + + fn take_retry_failed(&mut self) -> bool { + std::mem::take(&mut self.retry_failed) + } + + fn take_declined(&mut self) -> bool { + std::mem::take(&mut self.declined) + } + + /// A sign-in or check is going on for a "Translate" while its window is closed. + fn busy_in_strip(&self) -> bool { + !self.setup_open && self.resume && (self.sign_in.is_some() || self.check.is_some()) + } + + fn signing_in(&self) -> bool { + self.sign_in.is_some() + } + + /// Opens the browser for the sign-in (one at a time). + fn sign_in(&mut self, ctx: &egui::Context, s: &mut TranslationSettings) { + if self.sign_in.is_some() { + return; + } + if s.host_id.is_empty() { + s.host_id = crate::chatgpt::new_host_id(); + } + self.note = None; + match SignIn::start(ctx, &s.host_id, &s.client_id) { + Ok(sign_in) => { + ctx.open_url(egui::OpenUrl::new_tab(&sign_in.url)); + self.sign_in = Some(sign_in); + self.step = Step::Waiting; + self.copied = None; + } + Err(e) => self.note = Some(SignInNote::NotPrepared(e)), + } + } + + fn cancel_sign_in(&mut self) { + if let Some(s) = self.sign_in.take() { + s.cancel(); + } + if self.step == Step::Waiting { + self.step = Step::Choose; + } + self.sign_in_from_strip = false; + } + + /// Checks the connection the window (or the settings) set up with the sentence. + fn start_check(&mut self, ctx: &egui::Context, s: &TranslationSettings, now: f64) { + let target = s.target(); + let preset = s.preset; + let connection = s.connection; + let base = s.base(); + let local = s.is_local(); + let wanted = match connection { + Connection::ChatGpt => s.chatgpt_model.clone(), + Connection::Key => s.model(), + }; + let key = translate::credentials().key(preset.id()).map(str::to_owned); + self.check_result = None; + self.check = Background::spawn(ctx, now, move |_, cancel| { + let (models, model) = match connection { + Connection::ChatGpt => match crate::chatgpt::models() { + Ok(m) => { + let pick = crate::chatgpt::default_model(&m).or(Some(wanted)); + (m, pick.unwrap_or_default()) + } + Err(e) => { + return Some(Checked { + models: Vec::new(), + model: wanted, + result: Err(e), + }); + } + }, + Connection::Key => { + let listed = translate::list_models(&base, key.as_deref(), local); + match listed { + Ok(m) => { + let pick = + if !wanted.is_empty() && (m.is_empty() || m.contains(&wanted)) { + wanted + } else if preset == Preset::Ollama + && let Some(r) = m.iter().find(|x| x.starts_with(OLLAMA_MODEL)) + { + r.clone() + } else { + m.first().cloned().unwrap_or(wanted) + }; + (m, pick) + } + // Some services do not list models: try the request anyway. + Err(Failure::Service(..)) if !wanted.is_empty() => (Vec::new(), wanted), + Err(e) => { + return Some(Checked { + models: Vec::new(), + model: wanted, + result: Err(e), + }); + } + } + } + }; + if model.is_empty() { + return Some(Checked { + models, + model, + result: Err(Failure::NoModel(String::new())), + }); + } + let backend = match connection { + Connection::ChatGpt => Backend::ChatGpt { + model: model.clone(), + }, + Connection::Key => Backend::Chat { + base: base.clone(), + key: key.clone(), + model: model.clone(), + json_mode: matches!(preset, Preset::DeepSeek | Preset::OpenAi | Preset::Gemini), + local, + }, + }; + let result = translate::check(&backend, target, cancel); + Some(Checked { + models, + model, + result, + }) + }); + } + + /// Collects finished work: the sign-in and the check. `changed`: settings to save. + pub fn poll(&mut self, ctx: &egui::Context, settings: &mut Settings) -> bool { + let s = &mut settings.translation; + let mut changed = false; + let now = ctx.input(|i| i.time); + if let Some(r) = self.sign_in.as_ref().and_then(SignIn::poll) { + self.sign_in = None; + match r { + SignedIn::Ok { account, client_id } => { + s.account = account; + s.client_id = client_id; + s.connection = Connection::ChatGpt; + self.choice = Connection::ChatGpt; + changed = true; + self.step = Step::Checking; + self.start_check(ctx, s, now); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + SignedIn::NoPlan { account, client_id } => { + s.account = account; + s.client_id = client_id; + changed = true; + self.chatgpt = ChatGptState::NoPlan; + self.step = Step::Choose; + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + SignedIn::Declined => { + self.resume = false; + self.note = Some(SignInNote::Declined); + self.step = Step::Choose; + } + SignedIn::TimedOut => { + self.resume = false; + self.note = Some(SignInNote::TimedOut); + self.step = Step::Choose; + } + SignedIn::Failed(e) => { + self.resume = false; + if e != "cancelled" { + self.note = Some(SignInNote::Failed(e)); + } + self.step = Step::Choose; + } + } + self.sign_in_from_strip = false; + } + if let Some(r) = self.check.as_ref().and_then(Background::poll) { + self.check = None; + let Some(c) = r else { return changed }; + match s.connection { + Connection::ChatGpt => { + self.chatgpt = match &c.result { + Ok(_) => ChatGptState::Works(c.model.clone()), + Err(Failure::NotEligible(_)) => ChatGptState::NotEligible, + Err(Failure::PlanLimit) => ChatGptState::Limit, + Err(Failure::SignedOut) => ChatGptState::SignedOut, + Err(_) => self.chatgpt.clone(), + }; + if c.result.is_ok() && s.chatgpt_model != c.model { + s.chatgpt_model = c.model.clone(); + changed = true; + } + } + Connection::Key => { + self.models = c.models.clone(); + if c.result.is_ok() && s.model() != c.model { + s.model = c.model.clone(); + changed = true; + } + } + } + let ok = c.result.is_ok(); + if let Err(e) = &c.result { + crate::platform::log(&format!("translation check via {}: {e}", s.service_id())); + } + self.check_result = Some(c.result); + let flow = self.resume || (self.setup_open && self.step == Step::Checking); + self.resume = false; + if !ok { + if self.step == Step::Checking { + self.step = Step::Choose; + } + } else if flow { + if s.allowed() { + // A model on this computer, or allowed before: translating starts. + s.auto = true; + s.never_offer = false; + changed = true; + self.setup_open = false; + self.start = true; + } else if self.setup_open { + self.step = Step::Consent; + } else { + self.consent_open = true; + } + } else if s.allowed() { + // Fixed in the settings (a new key): a game that failed goes on. + self.retry_failed = true; + } + } + if self.sign_in.is_some() || self.check.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } + changed + } + + /// The consent was given: remember it and start. + fn allow(&mut self, s: &mut TranslationSettings) { + let id = s.service_id(); + if !s.allowed.contains(&id) { + s.allowed.push(id); + } + s.auto = true; + s.never_offer = false; + self.consent_open = false; + self.setup_open = false; + self.start = true; + } + + /// The windows: "How to translate?" and the consent. `changed`: settings to save. + pub fn windows(&mut self, ctx: &egui::Context, settings: &mut Settings) -> bool { + let mut changed = false; + if self.setup_open { + let mut open = true; + let title = if self.step == Step::Consent { + trf( + "Send comments to {service}?", + &[("service", &settings.translation.service_name())], + ) + } else { + tr("How to translate?").to_owned() + }; + egui::Window::new(title) + .id(egui::Id::new("translation_setup")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .default_width(460.0) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.set_max_width(460.0); + changed |= self.setup_ui(ui, &mut settings.translation); + }); + if !open + || ctx.input(|i| i.key_pressed(egui::Key::Escape)) + && !ctx.egui_wants_keyboard_input() + { + self.setup_open = false; + // Closed while signing in or checking: that goes on (`resume`). + if self.sign_in.is_none() && self.check.is_none() { + self.declined = true; + self.resume = false; + settings.translation.declined += 1; + changed = true; + } + } + } + if self.consent_open { + let mut close = false; + egui::Modal::new(egui::Id::new("translation_consent")).show(ctx, |ui| { + ui.set_max_width(440.0); + ui.label( + RichText::new(trf( + "Send comments to {service}?", + &[("service", &settings.translation.service_name())], + )) + .strong() + .size(16.0), + ); + ui.add_space(6.0); + let (go, cancel) = self.consent_ui(ui, &settings.translation); + if go { + self.allow(&mut settings.translation); + changed = true; + } + if cancel { + close = true; + } + }); + if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + self.consent_open = false; + self.declined = true; + self.resume = false; + settings.translation.declined += 1; + changed = true; + } + } + changed + } + + /// The text of the consent and its buttons: (start, cancel). + fn consent_ui(&mut self, ui: &mut Ui, s: &TranslationSettings) -> (bool, bool) { + let service = s.service_name(); + let host = match s.connection { + Connection::ChatGpt => "OpenAI".to_owned(), + Connection::Key => translate::host_of(&s.base()), + }; + ui.label(trf( + "To translate, these will be sent to {service} ({host}):", + &[("service", &service), ("host", &host)], + )); + let (n, chars) = self.consent_for; + ui.label(trf( + "• comment texts — {n} in this game, about {k} thousand characters;", + &[("n", &n), ("k", &thousands(chars))], + )); + ui.label(tr( + "• player names, the event and the opening — for accurate terms.", + )); + ui.label(tr( + "The game's moves are not sent; moves written inside comments are.", + )); + let privacy = match s.connection { + Connection::ChatGpt => Some("https://openai.com/policies/privacy-policy/"), + Connection::Key => s.preset.privacy(), + }; + if let Some(url) = privacy { + ui.hyperlink_to( + trf( + "How {service} stores data: privacy policy ↗", + &[("service", &service)], + ), + url, + ); + } + if s.connection == Connection::ChatGpt { + ui.label(tr("Translation uses part of your subscription's limit.")); + } + ui.add_space(6.0); + ui.label( + RichText::new(tr("From now on, comments in other languages will be translated by themselves when you open a game. To turn it off or withdraw the permission: Settings › Translation.")).weak(), + ); + ui.add_space(8.0); + let mut go = false; + let mut cancel = false; + let row = egui::vec2(ui.available_width(), 32.0); + ui.allocate_ui_with_layout( + row, + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + let r = crate::widgets::primary(ui, tr("Start translating")); + if r.clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) { + go = true; + } + if self.setup_open && self.step == Step::Consent { + if ui.button(tr("Back")).clicked() { + self.step = Step::Choose; + } + } else if ui.button(tr("Cancel")).clicked() { + cancel = true; + } + }, + ); + (go, cancel) + } + + fn setup_ui(&mut self, ui: &mut Ui, s: &mut TranslationSettings) -> bool { + let mut changed = false; + match self.step { + Step::Consent => { + let (go, _) = self.consent_ui(ui, s); + if go { + self.allow(s); + changed = true; + } + return changed; + } + Step::Waiting => { + self.waiting_ui(ui, true); + return changed; + } + // A key is checked with the window as it is (the button waits). + Step::Checking if s.connection == Connection::Key => {} + Step::Checking => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(if s.connection == Connection::ChatGpt { + tr("Checking the subscription…") + } else { + tr("Checking…") + }); + }); + return changed; + } + Step::Choose => {} + } + ui.label(tr( + "Comments are translated by a language model. Choose which:", + )); + ui.add_space(6.0); + ui.radio_value( + &mut self.choice, + Connection::ChatGpt, + tr("I have ChatGPT Plus or Pro"), + ); + ui.indent("chatgpt_choice", |ui| { + ui.label(RichText::new(tr("The easiest way: sign in, no key needed.")).weak()); + ui.label(RichText::new(tr("Uses part of your subscription's limit.")).weak()); + self.chatgpt_problem_ui(ui); + }); + ui.add_space(4.0); + ui.radio_value( + &mut self.choice, + Connection::Key, + tr("No subscription — an API key"), + ); + if self.choice == Connection::Key { + ui.indent("key_choice", |ui| changed |= self.key_steps_ui(ui, s)); + } else { + ui.indent("key_hint", |ui| { + ui.label( + RichText::new(tr("A service with a key, or a model on this computer.")).weak(), + ); + }); + } + ui.add_space(8.0); + ui.label( + RichText::new(tr("From now on, comments in other languages will be translated by themselves when you open a game. To change: Settings › Translation.")).weak(), + ); + ui.add_space(8.0); + let row = egui::vec2(ui.available_width(), 32.0); + ui.allocate_ui_with_layout( + row, + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + let now = ui.input(|i| i.time); + match self.choice { + Connection::ChatGpt => { + if crate::widgets::primary(ui, tr("Sign in with ChatGPT")).clicked() { + s.connection = Connection::ChatGpt; + changed = true; + self.resume = true; + if s.ready() + && translate::credentials().chatgpt.is_some_and(|t| t.plan()) + { + // Signed in already: check and go on. + self.step = Step::Checking; + self.start_check(ui.ctx(), s, now); + } else { + self.sign_in(ui.ctx(), s); + } + } + } + Connection::Key => { + let preset = self.preset.unwrap_or(s.preset); + let missing = if preset.needs_key() { + self.key.trim().is_empty() + } else { + preset == Preset::Custom && s.base.trim().is_empty() + }; + let checking = self.check.is_some(); + let r = ui + .add_enabled_ui(!missing && !checking, |ui| { + crate::widgets::primary(ui, tr("Check and continue")) + }) + .inner; + let r = if missing { + r.on_disabled_hover_text(tr("Paste the key first")) + } else { + r + }; + if r.clicked() { + s.connection = Connection::Key; + s.preset = preset; + if preset.needs_key() { + let key = self.key.trim().to_owned(); + translate::update_credentials(|c| { + c.keys.insert(preset.id().to_owned(), key); + }); + } + changed = true; + self.step = Step::Checking; + self.resume = true; + self.start_check(ui.ctx(), s, now); + } + } + } + if ui + .add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(0.0, 30.0))) + .clicked() + { + self.setup_open = false; + self.declined = true; + self.resume = false; + s.declined += 1; + changed = true; + } + }, + ); + changed + } + + /// Why ChatGPT does not work, when known (a free plan, no permission, a sign-in note). + fn chatgpt_problem_ui(&self, ui: &mut Ui) { + let warn = ui.visuals().warn_fg_color; + let text = match (&self.chatgpt, &self.note) { + (_, Some(SignInNote::TimedOut)) => Some(tr("Sign-in was not finished in 10 minutes.").to_owned()), + (_, Some(SignInNote::Declined)) => Some(tr("Sign-in was cancelled in the browser.").to_owned()), + (_, Some(SignInNote::Failed(_))) => Some(tr("âš  Sign-in could not be finished.").to_owned()), + (_, Some(SignInNote::NotPrepared(_))) => Some( + tr("âš  Sign-in could not be prepared: ChessPenguin cannot receive the browser's answer.").to_owned(), + ), + (ChatGptState::NoPlan, _) => Some(tr("âš  You signed in, but did not allow ChessPenguin to use the subscription's limit. Without it, translation with ChatGPT does not work.").to_owned()), + (ChatGptState::NotEligible, _) => Some(tr("âš  This ChatGPT account cannot translate in ChessPenguin: a Plus or Pro subscription is needed.").to_owned()), + _ => None, + }; + if let Some(t) = text { + let r = ui.label(RichText::new(t).color(warn)); + if let Some(SignInNote::Failed(e) | SignInNote::NotPrepared(e)) = &self.note { + r.on_hover_text(e); + } + if self.chatgpt == ChatGptState::NoPlan { + ui.label( + RichText::new(tr("On the OpenAI site, leave the permission to use the subscription turned on")) + .weak() + .small(), + ); + } + } + } + + /// The service list and how to get a key for it. + fn key_steps_ui(&mut self, ui: &mut Ui, s: &mut TranslationSettings) -> bool { + let mut changed = false; + let mut preset = self.preset.unwrap_or(s.preset); + ui.horizontal(|ui| { + ui.label(tr("Service:")); + egui::ComboBox::from_id_salt("translation_preset_setup") + .selected_text(preset_label(preset)) + .width(260.0) + .show_ui(ui, |ui| { + for p in Preset::ALL { + ui.selectable_value(&mut preset, p, preset_label(p)); + } + }); + }); + if Some(preset) != self.preset { + self.preset = Some(preset); + self.key = translate::credentials() + .key(preset.id()) + .unwrap_or("") + .to_owned(); + self.check_result = None; + } + let site = |ui: &mut Ui, name: &str, url: &str, key: &'static str| { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let text = trf(key, &[("service", &name)]); + ui.hyperlink_to(text, url); + }); + }; + match preset { + Preset::DeepSeek => { + site( + ui, + "DeepSeek", + preset.key_page().unwrap_or(""), + "1. Open the {service} website ↗ and sign in.", + ); + ui.label(tr("2. Top up the balance: DeepSeek works with prepayment.")); + ui.label(tr( + "3. Press “Create new API keyâ€� and copy the key — it is shown only once.", + )); + ui.label(tr("4. Paste the key here:")); + } + Preset::OpenAi => { + site( + ui, + "OpenAI", + preset.key_page().unwrap_or(""), + "1. Open the {service} website ↗ and sign in.", + ); + ui.label(tr("2. Top up the balance in the Billing section.")); + ui.label(tr("3. Press “Create new secret keyâ€� and copy the key.")); + ui.label(tr("4. Paste the key here:")); + ui.label( + RichText::new(tr( + "The API key is paid separately from the ChatGPT subscription.", + )) + .weak(), + ); + } + Preset::Gemini => { + ui.hyperlink_to( + tr("1. Open Google AI Studio ↗ and sign in with your Google account."), + preset.key_page().unwrap_or(""), + ); + ui.label(tr("2. Press “Create API keyâ€� and copy the key.")); + ui.label(tr("3. Paste the key here:")); + ui.label( + RichText::new(tr("Free with a Google account, but Google may use the texts to train its models.")) + .color(ui.visuals().warn_fg_color), + ); + } + Preset::Ollama => { + ui.hyperlink_to( + tr("1. Install Ollama from ollama.com ↗ and start it."), + "https://ollama.com/download", + ); + ui.horizontal(|ui| { + ui.label(tr("2. Download a model:")); + let cmd = format!("ollama pull {OLLAMA_MODEL}"); + ui.label(RichText::new(&cmd).monospace()); + if ui.small_button(tr("Copy")).clicked() { + ui.ctx().copy_text(cmd); + } + }); + ui.label(tr("3. Press “Check and continueâ€�.")); + } + Preset::LmStudio => { + ui.hyperlink_to( + tr("1. Install LM Studio from lmstudio.ai ↗."), + "https://lmstudio.ai", + ); + ui.label(tr("2. Download a model in LM Studio.")); + ui.label(tr( + "3. Turn on the server: the Developer tab › Start Server.", + )); + ui.label(tr("4. Press “Check and continueâ€�.")); + } + Preset::Custom => { + ui.horizontal(|ui| { + ui.label(tr("Address:")); + changed |= ui + .add( + egui::TextEdit::singleline(&mut s.base) + .hint_text("https://…/v1") + .desired_width(260.0), + ) + .on_hover_text(tr("The address of an OpenAI-compatible service, with /v1")) + .changed(); + }); + ui.horizontal(|ui| { + ui.label(tr("Model:")); + changed |= ui + .add(egui::TextEdit::singleline(&mut s.model).desired_width(200.0)) + .changed(); + }); + } + } + if preset.needs_key() || preset == Preset::Custom { + ui.horizontal(|ui| { + ui.label(if preset == Preset::Custom { + tr("Key (if needed):") + } else { + tr("Key:") + }); + let r = ui.add( + egui::TextEdit::singleline(&mut self.key) + .password(!self.show_key) + .desired_width(240.0), + ); + if r.changed() { + self.check_result = None; + } + ui.toggle_value(&mut self.show_key, "ðŸ‘�"); + if preset == Preset::Custom && r.lost_focus() { + let key = self.key.trim().to_owned(); + translate::update_credentials(|c| { + c.keys.insert(Preset::Custom.id().to_owned(), key); + }); + } + }); + } + if self.check.is_some() { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Checking…")); + }); + } + match &self.check_result { + Some(Ok(t)) => { + ui.label(trf( + "✔ Works: “{sample}â€� → “{result}â€�", + &[("sample", &translate::sample(s.target())), ("result", t)], + )); + } + Some(Err(e)) if self.check.is_none() => { + ui.label(RichText::new(failure_text(e, s)).color(ui.visuals().warn_fg_color)); + } + _ => {} + } + changed + } + + /// Waiting for the browser: what to do there, the link to copy, cancel. + fn waiting_ui(&mut self, ui: &mut Ui, in_window: bool) { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Waiting for sign-in in the browser…")); + }); + if in_window { + ui.add_space(4.0); + ui.label(tr("A page from OpenAI has opened in the browser. Sign in to your ChatGPT account and allow access for ChessPenguin. Then come back here — everything goes on by itself.")); + ui.add_space(4.0); + } + let now = ui.input(|i| i.time); + ui.horizontal_wrapped(|ui| { + if ui + .link(tr("The browser did not open? Copy the link")) + .clicked() + && let Some(s) = &self.sign_in + { + ui.ctx().copy_text(s.url.clone()); + self.copied = Some(now); + } + if !in_window && ui.button(tr("Cancel")).clicked() { + self.cancel_sign_in(); + } + }); + if self.copied.is_some_and(|t| now - t < 6.0) { + ui.label( + RichText::new(tr("Copied. Paste the link into the browser's address bar.")).weak(), + ); + } + if in_window { + ui.add_space(4.0); + ui.label(RichText::new(tr("You can close this window: the sign-in goes on.")).weak()); + let row = egui::vec2(ui.available_width(), 32.0); + ui.allocate_ui_with_layout( + row, + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + if ui.button(tr("Cancel")).clicked() { + self.cancel_sign_in(); + } + }, + ); + } + } + + /// Settings › Translation. + pub fn settings_tab(&mut self, ui: &mut Ui, settings: &mut Settings) -> bool { + let mut changed = false; + let now = ui.input(|i| i.time); + let s = &mut settings.translation; + ui.label( + RichText::new(tr("Comments in other languages are translated by a language model. Moves are not translated. The translation is not written to PGN files.")).weak(), + ); + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(tr("Translate into:")); + let current = s.target; + let label = |t: Option| match t { + None => trf( + "As the interface ({lang})", + &[("lang", &crate::i18n::current().label())], + ), + Some(l) => l.label().to_owned(), + }; + egui::ComboBox::from_id_salt("translation_target") + .selected_text(label(current)) + .show_ui(ui, |ui| { + changed |= ui + .selectable_value(&mut s.target, None, label(None)) + .changed(); + for l in Lang::ALL { + changed |= ui + .selectable_value(&mut s.target, Some(l), l.label()) + .changed(); + } + }); + }); + ui.add_space(4.0); + ui.label(tr("When comments are in another language:")); + ui.horizontal(|ui| { + let mode = if s.never_offer { + 2 + } else if s.auto { + 0 + } else { + 1 + }; + let mut m = mode; + ui.radio_value(&mut m, 0, tr("Translate at once")); + ui.radio_value(&mut m, 1, tr("Ask")); + ui.radio_value(&mut m, 2, tr("Do nothing")); + if m != mode { + s.auto = m == 0; + s.never_offer = m == 2; + changed = true; + } + }); + ui.add_space(10.0); + ui.label(RichText::new(tr("How to translate")).strong()); + changed |= ui + .radio_value( + &mut s.connection, + Connection::ChatGpt, + tr("ChatGPT sign-in"), + ) + .changed(); + ui.indent("settings_chatgpt", |ui| { + ui.label( + RichText::new(tr( + "For a Plus or Pro subscription. Uses part of its limit.", + )) + .weak(), + ); + changed |= self.chatgpt_block(ui, s, now); + }); + changed |= ui + .radio_value(&mut s.connection, Connection::Key, tr("API key")) + .changed(); + ui.indent("settings_key", |ui| changed |= self.key_block(ui, s, now)); + ui.add_space(10.0); + ui.horizontal_wrapped(|ui| { + ui.label(tr("Comments may be sent to:")); + if s.allowed.iter().all(|a| a == "local") { + ui.label(RichText::new(tr("Nowhere yet.")).weak()); + } + let mut remove = None; + for (i, a) in s.allowed.iter().enumerate().filter(|(_, a)| *a != "local") { + let name = allowed_name(a); + ui.label(&name); + if crate::widgets::small_close_button(ui) + .on_hover_text(trf( + "Stop sending comments to {service}", + &[("service", &name)], + )) + .clicked() + { + remove = Some(i); + } + } + if let Some(i) = remove { + s.allowed.remove(i); + changed = true; + } + }); + ui.add_space(6.0); + ui.horizontal(|ui| { + let size = translate::cache_size(); + ui.label(trf( + "Saved translations: {size}", + &[("size", &human_size(size))], + )); + if self.clear_confirm { + ui.label(tr("Delete all saved translations?")); + if ui.button(tr("Cancel")).clicked() { + self.clear_confirm = false; + } + if ui.button(tr("Delete")).clicked() { + translate::clear_cache(); + self.cache_epoch += 1; + self.clear_confirm = false; + } + } else if ui + .add_enabled(size > 0, egui::Button::new(tr("Clear"))) + .clicked() + { + self.clear_confirm = true; + } + }); + ui.label( + RichText::new(tr( + "So that translated games open without the internet and without cost.", + )) + .weak(), + ); + changed + } + + fn chatgpt_block(&mut self, ui: &mut Ui, s: &mut TranslationSettings, now: f64) -> bool { + let mut changed = false; + let active = s.connection == Connection::ChatGpt; + if self.sign_in.is_some() { + self.waiting_ui(ui, false); + return false; + } + if self.check.is_some() && active { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Checking the subscription…")); + }); + return false; + } + let signed_in = translate::credentials().chatgpt.is_some(); + if !signed_in { + if self.chatgpt == ChatGptState::SignedOut { + ui.label( + RichText::new(tr("âš  The sign-in is no longer valid.")) + .color(ui.visuals().warn_fg_color), + ); + } + if ui.button(tr("Sign in with ChatGPT")).clicked() { + s.connection = Connection::ChatGpt; + changed = true; + self.sign_in(ui.ctx(), s); + } + self.chatgpt_problem_ui(ui); + return changed; + } + ui.horizontal_wrapped(|ui| { + let who = if s.account.is_empty() { + "ChatGPT".to_owned() + } else { + s.account.clone() + }; + ui.label(trf("You are signed in: {account}", &[("account", &who)])); + if ui.link(tr("Sign out")).clicked() { + crate::chatgpt::sign_out(); + s.account.clear(); + s.allowed.retain(|a| a != "chatgpt"); + self.chatgpt = ChatGptState::Unknown; + changed = true; + } + }); + ui.hyperlink_to(tr("Manage access on the OpenAI site ↗"), CHATGPT_SETTINGS); + let warn = ui.visuals().warn_fg_color; + match &self.chatgpt { + ChatGptState::Works(m) => { + ui.label(trf("✔ Works, model {model}", &[("model", m)])); + } + ChatGptState::NoPlan => { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(tr( + "âš  You did not allow ChessPenguin to use the subscription's limit.", + )) + .color(warn), + ); + if ui.button(tr("Sign in again")).clicked() { + self.sign_in(ui.ctx(), s); + } + }); + } + ChatGptState::NotEligible => { + ui.label( + RichText::new(tr("âš  This account needs a Plus or Pro subscription.")) + .color(warn), + ); + } + ChatGptState::Limit => { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(tr( + "âš  The subscription's limit for ChessPenguin is used up.", + )) + .color(warn), + ); + ui.hyperlink_to(tr("ChatGPT settings ↗"), CHATGPT_SETTINGS); + }); + } + ChatGptState::SignedOut | ChatGptState::Unknown => { + if let Some(Err(e)) = &self.check_result + && active + { + ui.label(RichText::new(failure_text(e, s)).color(warn)) + .on_hover_text(e.to_string()); + } + if active && ui.button(tr("Check")).clicked() { + self.start_check(ui.ctx(), s, now); + } + } + } + changed + } + + fn key_block(&mut self, ui: &mut Ui, s: &mut TranslationSettings, now: f64) -> bool { + let mut changed = false; + let before = s.preset; + ui.horizontal(|ui| { + ui.label(tr("Service:")); + egui::ComboBox::from_id_salt("translation_preset") + .selected_text(preset_label(s.preset)) + .width(260.0) + .show_ui(ui, |ui| { + for p in Preset::ALL { + changed |= ui + .selectable_value(&mut s.preset, p, preset_label(p)) + .changed(); + } + }); + }); + if s.preset != before { + s.base.clear(); + s.model.clear(); + self.models.clear(); + self.check_result = None; + } + let checking = self.check.is_some() && s.connection == Connection::Key; + if s.preset.needs_key() || s.preset == Preset::Custom { + let mut key = translate::credentials() + .key(s.preset.id()) + .unwrap_or("") + .to_owned(); + ui.horizontal(|ui| { + ui.label(if s.preset == Preset::Custom { + tr("Key (if needed):") + } else { + tr("Key:") + }); + let r = ui.add( + egui::TextEdit::singleline(&mut key) + .password(!self.show_key) + .desired_width(220.0), + ); + if r.changed() { + let id = s.preset.id().to_owned(); + let k = key.trim().to_owned(); + translate::update_credentials(|c| { + c.keys.insert(id, k); + }); + self.check_result = None; + } + ui.toggle_value(&mut self.show_key, "ðŸ‘�"); + if ui + .add_enabled( + !checking && !key.trim().is_empty(), + egui::Button::new(tr("Check")), + ) + .clicked() + { + s.connection = Connection::Key; + changed = true; + self.start_check(ui.ctx(), s, now); + } + }); + if let Some(url) = s.preset.key_page() { + ui.hyperlink_to( + trf( + "Get a key on the {service} website ↗", + &[("service", &s.preset.name())], + ), + url, + ); + } + } else { + ui.horizontal(|ui| { + if ui + .add_enabled(!checking, egui::Button::new(tr("Check"))) + .clicked() + { + s.connection = Connection::Key; + changed = true; + self.start_check(ui.ctx(), s, now); + } + }); + } + if s.preset == Preset::Gemini { + ui.label( + RichText::new(tr( + "Free with a Google account, but Google may use the texts to train its models.", + )) + .color(ui.visuals().warn_fg_color), + ); + } + let custom = s.preset == Preset::Custom; + let mut fields = |ui: &mut Ui, s: &mut TranslationSettings, models: &[String]| { + ui.horizontal(|ui| { + ui.label(tr("Address:")); + let mut base = if s.base.is_empty() { + s.preset.base().to_owned() + } else { + s.base.clone() + }; + if ui + .add(egui::TextEdit::singleline(&mut base).desired_width(260.0)) + .on_hover_text(tr("The address of an OpenAI-compatible service, with /v1")) + .changed() + { + s.base = base; + changed = true; + } + }); + ui.horizontal(|ui| { + ui.label(tr("Model:")); + if models.is_empty() { + changed |= ui + .add( + egui::TextEdit::singleline(&mut s.model) + .hint_text(s.preset.model()) + .desired_width(200.0), + ) + .changed(); + } else { + let current = s.model(); + egui::ComboBox::from_id_salt("translation_model") + .selected_text(¤t) + .show_ui(ui, |ui| { + for m in models { + if ui.selectable_label(*m == current, m).clicked() { + s.model = m.clone(); + changed = true; + } + } + }); + } + }); + }; + let models = self.models.clone(); + if custom || !s.preset.needs_key() { + fields(ui, s, &models); + } else { + egui::CollapsingHeader::new(tr("Advanced")) + .id_salt("translation_advanced") + .show(ui, |ui| fields(ui, s, &models)); + } + if checking { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Checking…")); + }); + } else if let Some(r) = &self.check_result + && s.connection == Connection::Key + { + match r { + Ok(t) => { + ui.label(trf( + "✔ Works: “{sample}â€� → “{result}â€�", + &[("sample", &translate::sample(s.target())), ("result", t)], + )); + } + Err(e) => { + ui.label(RichText::new(failure_text(e, s)).color(ui.visuals().warn_fg_color)); + } + } + } + changed + } +} + +fn preset_label(p: Preset) -> String { + match p { + Preset::Ollama => tr("Ollama — on this computer").to_owned(), + Preset::LmStudio => tr("LM Studio — on this computer").to_owned(), + _ => p.name().to_owned(), + } +} + +fn allowed_name(id: &str) -> String { + if id == "chatgpt" { + return "ChatGPT".into(); + } + if let Some(base) = id.strip_prefix("custom:") { + return translate::host_of(base); + } + Preset::ALL + .into_iter() + .find(|p| p.id() == id) + .map_or_else(|| id.to_owned(), |p| p.name().to_owned()) +} + +fn human_size(bytes: u64) -> String { + if bytes == 0 { + tr("none").to_owned() + } else if bytes >= 1 << 20 { + let mb = format!("{:.1}", bytes as f64 / (1u64 << 20) as f64); + // A decimal comma where the language writes one. + let mb = if crate::i18n::current() == Lang::En { + mb + } else { + mb.replace('.', ",") + }; + trf("{n} MB", &[("n", &mb)]) + } else { + trf("{n} KB", &[("n", &bytes.div_ceil(1024))]) + } +} + +/// The plain words for a failure. +pub fn failure_text(e: &Failure, s: &TranslationSettings) -> String { + let service = s.service_name(); + match e { + Failure::Key => tr("âš  The key was not accepted. Perhaps it was copied incompletely or deleted on the site.").to_owned(), + Failure::Money => trf("âš  The {service} account has run out of money. Top up the balance on the site.", &[("service", &service)]), + Failure::RateLimited => tr("âš  The service is overloaded. What is translated is saved.").to_owned(), + Failure::PlanLimit => tr("âš  The ChatGPT subscription's limit for ChessPenguin is used up. When it comes back is shown in the ChatGPT settings.").to_owned(), + Failure::NotEligible(_) => tr("âš  This ChatGPT account cannot translate in ChessPenguin: a Plus or Pro subscription is needed.").to_owned(), + Failure::SignedOut => tr("âš  The ChatGPT sign-in is no longer valid. Sign in again.").to_owned(), + Failure::Offline(_) => trf("No connection to {service}. We will translate when the connection is back.", &[("service", &service)]), + Failure::LocalDown => trf("âš  {service} does not answer. Start {service} and press “Retryâ€�.", &[("service", &service)]), + Failure::NoModel(m) if s.preset == Preset::Ollama && s.connection == Connection::Key => { + if m.is_empty() { + tr("There are no models in Ollama. Download one with the command below.").to_owned() + } else { + trf("âš  Ollama has no model {model}. Download it with the command: ollama pull {model}", &[("model", m)]) + } + } + Failure::NoModel(m) => trf( + "âš  {service} has no model {model}. Choose another one in the translation settings.", + &[("service", &service), ("model", m)], + ), + Failure::Service(code, _) => trf("âš  The service answered with an error ({code}).", &[("code", code)]), + } +} + +// --- One game ------------------------------------------------------------------------------ + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +enum State { + /// Nothing to translate (or not looked yet). + #[default] + None, + Offer, + /// Much foreign text: waits for "Translate" even in automatic mode. + Big, + Running, + Done, + Stopped, + Failed, +} + +/// What the strip asks the game view to do. +pub enum StripAction { + OpenSettings, + Toast(String), +} + +#[derive(Default)] +pub struct GameTranslation { + revision: Option<(u64, Lang)>, + plan: Option, + context: GameContext, + /// Comment text → what the notation shows. + pub marks: HashMap, + bad: HashSet, + job: Option, + state: State, + failure: Option, + /// The original text is shown. + pub original: bool, + dismissed: bool, + details: bool, + /// Characters sent by this game's jobs. + sent: usize, + /// Everything shown came from the cache. + from_cache: bool, + job_started: f64, + service: String, + /// The automatic start was tried for this plan. + tried: bool, + /// The service the running job sends to (it stops when that changes). + job_service: String, + /// "Translate comments" was chosen: the cache is shown even with "Do nothing". + forced: bool, + /// The game was put aside while translating: it goes on when shown again. + suspended: bool, + cache_epoch: u32, +} + +impl GameTranslation { + /// The marks to show (none in the original mode). + pub fn shown(&self) -> Option<&HashMap> { + (!self.original && !self.marks.is_empty()).then_some(&self.marks) + } + + pub fn has_translation(&self) -> bool { + self.marks + .values() + .any(|m| matches!(m, Mark::Translated(_))) + } + + /// The game has comments still to translate and nothing is going on. + pub fn can_translate(&self) -> bool { + self.job.is_none() + && self.plan.as_ref().is_some_and(|p| { + p.texts + .iter() + .any(|t| !matches!(self.marks.get(t), Some(Mark::Translated(_)))) + }) + } + + pub fn toggle(&mut self) { + if self.has_translation() { + self.original = !self.original; + } + } + + /// Stops the work of a game that is not shown any more (it goes on when shown again). + pub fn suspend(&mut self) { + if self.job.take().is_some() && self.state == State::Running { + self.marks.retain(|_, m| *m != Mark::Pending); + self.state = State::Stopped; + self.suspended = true; + } + } + + fn translated(&self) -> usize { + self.marks + .values() + .filter(|m| matches!(m, Mark::Translated(_))) + .count() + } + + fn total(&self) -> usize { + self.plan.as_ref().map_or(0, |p| p.texts.len()) + } + + fn foreign_chars(&self) -> usize { + self.plan + .as_ref() + .map_or(0, |p| p.texts.iter().map(|t| t.len()).sum()) + } + + /// Takes what the cache has for the plan; true when that is everything. + fn take_cached(&mut self, target: Lang) -> bool { + let Some(plan) = &self.plan else { return false }; + let mut all = true; + for t in &plan.texts { + if matches!(self.marks.get(t), Some(Mark::Translated(_))) { + continue; + } + match translate::cached(target, t) { + Some(tr) => { + self.marks.insert(t.clone(), Mark::Translated(tr)); + } + None => all = false, + } + } + all + } + + /// Looks at the game again when it, the target language or the cache changed. + fn refresh(&mut self, game: &chess_core::Game, s: &TranslationSettings, epoch: u32) { + let target = s.target(); + let key = (game.revision(), target); + if self.revision == Some(key) && self.cache_epoch == epoch { + return; + } + let reset = self.revision.is_some_and(|(_, l)| l != target) + || self.plan.is_none() + || self.cache_epoch != epoch; + self.revision = Some(key); + self.cache_epoch = epoch; + if reset { + self.job = None; + self.marks.clear(); + self.bad.clear(); + self.state = State::None; + self.failure = None; + self.tried = false; + } + let texts = translate::comments(game); + let before: HashSet = self + .plan + .as_ref() + .map(|p| p.texts.iter().cloned().collect()) + .unwrap_or_default(); + self.plan = translate::plan(&texts, target); + self.context = GameContext::of(game); + let Some(plan) = &self.plan else { + self.state = State::None; + return; + }; + let wanted: HashSet<&String> = plan.texts.iter().collect(); + self.marks.retain(|t, _| wanted.contains(t)); + // "Do nothing": not even the cache, until "Translate comments". + let all = if s.never_offer && !self.forced { + false + } else { + self.take_cached(target) + }; + if all { + if self.job.is_none() { + self.state = State::Done; + self.from_cache = self.sent == 0; + } + } else if matches!(self.state, State::None) { + self.state = State::Offer; + } else if self.state == State::Done + && self + .plan + .as_ref() + .is_some_and(|p| p.texts.iter().any(|t| !before.contains(t))) + { + // New comments to translate (the game changed); failed ones are not sent again. + self.state = State::Stopped; + self.tried = false; + } + } + + /// Sends what is not translated yet (or `only` these). Never without the consent. + fn start(&mut self, ctx: &egui::Context, s: &TranslationSettings, only: Option>) { + if !s.ready() || !s.allowed() { + return; + } + let target = s.target(); + self.take_cached(target); + let Some(plan) = &self.plan else { return }; + let Some(backend) = Backend::from(s) else { + return; + }; + let texts: Vec = match only { + Some(t) => t, + None => plan + .texts + .iter() + .filter(|t| !matches!(self.marks.get(*t), Some(Mark::Translated(_)))) + .cloned() + .collect(), + }; + if texts.is_empty() { + self.state = State::Done; + return; + } + for t in &texts { + self.marks.insert(t.clone(), Mark::Pending); + self.bad.remove(t); + } + self.sent += texts.iter().map(|t| t.len()).sum::(); + self.from_cache = false; + self.failure = None; + self.details = false; + self.service = s.service_name(); + self.job_service = s.service_id(); + self.suspended = false; + self.job_started = ctx.input(|i| i.time); + self.job = Some(Job::start( + ctx, + backend, + target, + format!( + "{} {}", + s.service_id(), + match s.connection { + Connection::ChatGpt => s.chatgpt_model.clone(), + Connection::Key => s.model(), + } + ), + self.context.clone(), + texts, + )); + self.state = State::Running; + } + + fn poll(&mut self, hub: &mut Hub) { + let Some(job) = &self.job else { return }; + let mut finished = false; + for e in job.poll() { + match e { + Event::Done(pairs) => { + for (o, t) in pairs { + self.marks.insert(o, Mark::Translated(t)); + } + } + Event::Bad(list) => { + for o in list { + self.marks.insert(o.clone(), Mark::Bad); + self.bad.insert(o); + } + } + Event::Failed(f) => { + crate::platform::log(&format!("translation via {}: {f}", self.job_service)); + match f { + Failure::PlanLimit => hub.chatgpt = ChatGptState::Limit, + Failure::SignedOut => hub.chatgpt = ChatGptState::SignedOut, + Failure::NotEligible(_) => hub.chatgpt = ChatGptState::NotEligible, + _ => {} + } + self.failure = Some(f); + } + Event::Finished => finished = true, + } + } + if finished { + self.job = None; + // What is still pending was not reached (stopped or failed). + self.marks.retain(|_, m| *m != Mark::Pending); + self.state = if self.failure.is_some() { + State::Failed + } else { + State::Done + }; + } + } + + /// Per frame: looks at the game, collects results, starts automatically. + pub fn update( + &mut self, + ctx: &egui::Context, + game: &chess_core::Game, + settings: &Settings, + hub: &mut Hub, + ) { + let s = &settings.translation; + self.refresh(game, s, hub.cache_epoch); + self.poll(hub); + if hub.take_declined() { + self.dismissed = true; + } + // Permission withdrawn, signed out or another service chosen: stop sending. + if self.job.is_some() && (!s.allowed() || !s.ready() || s.service_id() != self.job_service) + { + self.job = None; + self.marks.retain(|_, m| *m != Mark::Pending); + self.state = State::Stopped; + } + if self.job.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(500)); + } + // Taken every frame, so a request never waits for another game. + let start = hub.take_start(); + let retry = hub.take_retry_failed(); + if self.plan.is_none() { + return; + } + if start + && matches!( + self.state, + State::Offer | State::Big | State::Stopped | State::Failed + ) + || retry && self.state == State::Failed + { + self.dismissed = false; + self.start(ctx, s, None); + return; + } + let automatic = s.auto && !s.never_offer && s.ready() && s.allowed(); + if self.suspended && automatic { + self.start(ctx, s, None); + } else if !self.tried + && matches!(self.state, State::Offer | State::Stopped) + && s.auto + && !s.never_offer + { + self.tried = true; + if self.foreign_chars() > BIG { + self.state = State::Big; + } else if automatic { + self.start(ctx, s, None); + } + } + } + + /// The "Translate" button (strip, menu, Ctrl+Shift+T): set up and ask first if needed. + pub fn translate(&mut self, ctx: &egui::Context, settings: &mut Settings, hub: &mut Hub) { + self.translate_only(ctx, settings, hub, None); + } + + fn translate_only( + &mut self, + ctx: &egui::Context, + settings: &mut Settings, + hub: &mut Hub, + only: Option>, + ) { + self.forced = true; + self.dismissed = false; + let n = self.total(); + let chars = self.foreign_chars(); + if hub.request(&mut settings.translation, n, chars) { + self.start(ctx, &settings.translation, only); + } else { + hub.resume = true; + } + } + + /// The strip above the notation. + pub fn strip( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + hub: &mut Hub, + ) -> Option { + if self.plan.is_none() && self.marks.is_empty() { + return None; + } + let s = &settings.translation; + let hidden = match self.state { + State::None => true, + State::Offer | State::Big => self.dismissed || (s.never_offer && !self.forced), + _ => false, + }; + let ready = s.ready() && s.allowed(); + let service_name = s.service_name(); + let local = s.is_local(); + let waiting_sign_in = hub.busy_in_strip() || (hub.signing_in() && hub.sign_in_from_strip); + if hidden && !waiting_sign_in { + return None; + } + let mut action = None; + let warn = ui.visuals().warn_fg_color; + egui::Frame::new() + .fill(ui.visuals().faint_bg_color) + .inner_margin(egui::Margin::symmetric(8, 4)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + // The text and its buttons wrap on the left; the toggle keeps its place on + // the right, or goes to a line of its own in a narrow panel. + let toggle = self.has_translation() && !waiting_sign_in; + let narrow = ui.available_width() < 360.0; + let toggle_w = if toggle && !narrow { 170.0 } else { 0.0 }; + let row_h = ui.spacing().interact_size.y; + let spinner = egui::Spinner::new().size(ui.text_style_height(&egui::TextStyle::Body)); + ui.horizontal_top(|ui| { + let left = (ui.available_width() - toggle_w).max(120.0); + ui.allocate_ui_with_layout( + egui::vec2(left, 0.0), + egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), + |ui| { + ui.set_min_height(row_h); + // Buttons and links stay whole; only the texts wrap. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + let text = |ui: &mut Ui, t: RichText| ui.add(egui::Label::new(t).wrap()); + if waiting_sign_in { + ui.add(spinner); + if hub.signing_in() { + text(ui, tr("Waiting for sign-in in the browser…").into()); + if ui.button(tr("Cancel")).clicked() { + hub.cancel_sign_in(); + } + } else { + text(ui, tr("Checking…").into()); + } + return; + } + let lang = self.plan.as_ref().map_or("", |p| lang_name(p.source)); + let (n, total) = (self.translated(), self.total()); + match self.state { + State::Offer | State::Big => { + if self.has_translation() { + text(ui, trf("Translated: {n} of {total}", &[("n", &n), ("total", &total)]).into()); + } else if self.state == State::Big { + text(ui, trf( + "Many comments in another language ({lang}), about {k} thousand characters", + &[("lang", &lang), ("k", &thousands(self.foreign_chars()))], + ).into()); + } else { + text(ui, trf("Comments in another language ({lang})", &[("lang", &lang)]).into()); + } + let hint = if ready { + trf("Translate with {service}", &[("service", &service_name)]) + } else { + tr("Choose how to translate").to_owned() + }; + if ui.button(tr("Translate")).on_hover_text(hint).clicked() { + self.translate(ui.ctx(), settings, hub); + } + if settings.translation.declined >= 2 + && ui.link(tr("Don't offer")).on_hover_text(tr("Never offer to translate comments. You can turn it back on in Settings › Translation.")).clicked() + { + settings.translation.never_offer = true; + self.dismissed = true; + action = Some(StripAction::Toast(tr("Translation will not be offered again. To turn it back on: Settings › Translation.").to_owned())); + } + if crate::widgets::small_close_button(ui).on_hover_text(tr("Hide for this game")).clicked() { + self.dismissed = true; + settings.translation.declined += 1; + } + } + State::Running => { + ui.add(spinner); + let waiting = translate::WAITING.load(Ordering::Relaxed); + let now = ui.input(|i| i.time); + if waiting > 0 { + text(ui, trf("The service asks to wait… {s} s", &[("s", &waiting)]).into()); + } else if n == 0 && local && now - self.job_started > 8.0 { + text(ui, tr("The model is loading into memory — this can take up to a minute…").into()); + } else if self.plan.as_ref().is_some_and(|p| translate::one_batch(&p.texts)) { + // One request: a count would only jump from 0 to all. + text(ui, tr("Translating…").into()); + } else { + text(ui, trf("Translating… {n} of {total}", &[("n", &n), ("total", &total)]).into()); + } + if ui.button(tr("Stop")).clicked() { + self.job = None; + self.marks.retain(|_, m| *m != Mark::Pending); + self.state = State::Stopped; + } + } + State::Done => { + if self.bad.is_empty() { + let tip = if self.from_cache { + tr("Saved translation shown — nothing was sent. The translation is not written to the PGN file.").to_owned() + } else { + trf( + "Translated: {n} of {total}. Sent now: about {k} thousand characters. The translation is not written to the PGN file.", + &[("n", &n), ("total", &total), ("k", &thousands(self.sent))], + ) + }; + let service = if self.service.is_empty() { service_name.clone() } else { self.service.clone() }; + text(ui, trf("Machine translation ({service})", &[("service", &service)]).into()).on_hover_text(tip); + } else { + text(ui, RichText::new(format!("âš  {}", trf( + "Translated: {n} of {total}, failed: {bad}", + &[("n", &n), ("total", &total), ("bad", &self.bad.len())], + ))) + .color(warn)); + if ui.button(tr("Retry")).clicked() { + let only: Vec = self.bad.iter().cloned().collect(); + self.translate_only(ui.ctx(), settings, hub, Some(only)); + } + } + } + State::Stopped => { + text(ui, trf("Translated: {n} of {total}", &[("n", &n), ("total", &total)]).into()); + if ui.button(tr("Continue")).clicked() { + self.translate(ui.ctx(), settings, hub); + } + } + State::Failed => { + let f = self.failure.clone().unwrap_or(Failure::Service(0, String::new())); + let calm = matches!(f, Failure::Offline(_)); + let shown = failure_text(&f, &settings.translation); + if calm { + text(ui, RichText::new(shown)); + } else { + text(ui, RichText::new(shown).color(warn)); + } + match &f { + Failure::Key | Failure::NoModel(_) if !(settings.translation.preset == Preset::Ollama) => { + if ui.button(tr("Translation settings")).clicked() { + action = Some(StripAction::OpenSettings); + } + } + Failure::NoModel(m) => { + if ui.button(tr("Copy the command")).clicked() { + let m = if m.is_empty() { OLLAMA_MODEL } else { m }; + ui.ctx().copy_text(format!("ollama pull {m}")); + } + } + Failure::Money => { + if let Some(url) = settings.translation.preset.key_page() { + ui.hyperlink_to(tr("Open the site ↗"), url); + } + } + Failure::PlanLimit => { + ui.hyperlink_to(tr("ChatGPT settings ↗"), CHATGPT_SETTINGS); + if ui.button(tr("Another way")).clicked() { + hub.choice = Connection::Key; + hub.open_setup(&settings.translation); + hub.choice = Connection::Key; + } + } + Failure::NotEligible(_) => { + if ui.button(tr("Use an API key")).clicked() { + hub.open_setup(&settings.translation); + hub.choice = Connection::Key; + } + } + Failure::SignedOut if ui.button(tr("Sign in again")).clicked() => { + hub.sign_in_from_strip = true; + hub.resume = true; + hub.sign_in(ui.ctx(), &mut settings.translation); + } + _ => {} + } + if ui.button(tr("Retry")).clicked() { + self.translate(ui.ctx(), settings, hub); + } + if !calm && ui.link(tr("Details")).clicked() { + self.details = !self.details; + } + if crate::widgets::small_close_button(ui).on_hover_text(tr("Hide for this game")).clicked() { + self.state = if self.has_translation() { State::Done } else { State::Offer }; + self.dismissed = true; + } + } + State::None => {} + } + }, + ); + if toggle && !narrow { + self.toggle_ui(ui); + } + }); + if toggle && narrow { + self.toggle_ui(ui); + } + if self.details + && let Some(f) = &self.failure + { + let text = f.to_string(); + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(&text).monospace().small()); + if ui.small_button(tr("Copy")).clicked() { + ui.ctx().copy_text(text.clone()); + } + }); + } + if self.state == State::Running && self.total() > 40 { + let frac = self.translated() as f32 / self.total().max(1) as f32; + ui.add(egui::ProgressBar::new(frac).desired_height(3.0)); + } + }); + action + } + + fn toggle_ui(&mut self, ui: &mut Ui) { + if !self.has_translation() { + return; + } + let row = egui::vec2(ui.available_width(), 24.0); + ui.allocate_ui_with_layout( + row, + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + ui.spacing_mut().item_spacing.x = 2.0; + // Right to left: "Translation" first. + if ui + .selectable_label(!self.original, tr("Translation")) + .clicked() + { + self.original = false; + } + if ui.selectable_label(self.original, tr("Original")).clicked() { + self.original = true; + } + }, + ); + } +} diff --git a/apps/desktop/src/update.rs b/apps/desktop/src/update.rs new file mode 100644 index 0000000..a728696 --- /dev/null +++ b/apps/desktop/src/update.rs @@ -0,0 +1,890 @@ +//! Updates: at start the program asks its site (else GitHub) for the latest release +//! (once, in the background; can be turned off in Settings → About; the site counts the +//! installation, see `releases::check_latest`). When it is newer, a button next to +//! Settings offers it. What "update" does depends on how ChessPenguin was installed: +//! +//! - the Windows zip, the AppImage and the Linux tarball: the new file is downloaded, +//! checked against `SHA256SUMS.txt` and put in place of the running one; the program +//! offers to restart (Windows can rename a running executable, Linux can replace it); +//! - macOS: the disk image is downloaded, checked and opened; the user drags the app +//! over the old one, as at the first installation; +//! - deb, rpm, Arch and Flatpak packages: their files belong to the system's package +//! manager, so the package is downloaded into Downloads, checked, and the one command +//! that installs it is shown with a Copy button; +//! - the AUR package: it is updated with the AUR helper (the command is shown); +//! - anything else (a build from the sources): a link to the download page. +//! +//! `CP_UPDATE_SOURCE=` reads `latest.json` (the GitHub answer) and the assets from +//! a directory instead (tests, manual checks); `CP_UPDATE_KIND=` pretends another +//! kind of installation. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use releases::Asset; +pub use releases::{DOWNLOAD_PAGE, Release, parse_version}; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +/// How this copy of ChessPenguin was installed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Install { + /// The Windows zip: the executable can be replaced. + Windows(PathBuf), + /// macOS: the app bundle (replaced by the user from the disk image). + Mac, + /// An AppImage at this path (replaced in place). + AppImage(PathBuf), + /// The Linux tarball unpacked here: its `chesspenguin` is replaced. + Tarball(PathBuf), + Deb, + Rpm, + Arch, + /// The AUR package `chesspenguin-bin`. + Aur, + Flatpak, + /// A build from the sources, or a place we cannot write to. + Other, +} + +impl Install { + /// The suffix of the release asset for this installation. + fn asset_suffix(&self) -> Option<&'static str> { + Some(match self { + Install::Windows(_) => "-windows-x86_64.zip", + Install::Mac => "-macos-arm64.dmg", + Install::AppImage(_) => "-x86_64.AppImage", + Install::Tarball(_) => "-linux-x86_64.tar.gz", + Install::Deb => "_amd64.deb", + Install::Rpm => ".x86_64.rpm", + Install::Arch => "-x86_64.pkg.tar.zst", + Install::Flatpak => "-x86_64.flatpak", + Install::Aur | Install::Other => return None, + }) + } + + /// The program replaces its own files. + pub fn replaces_itself(&self) -> bool { + matches!( + self, + Install::Windows(_) | Install::AppImage(_) | Install::Tarball(_) + ) + } + + /// Short name for the dialog ("deb package"). + pub fn label(&self) -> &'static str { + match self { + Install::Windows(_) => "Windows", + Install::Mac => "macOS", + Install::AppImage(_) => "AppImage", + Install::Tarball(_) => "tar.gz", + Install::Deb => "deb", + Install::Rpm => "rpm", + Install::Arch => "Arch Linux", + Install::Aur => "AUR", + Install::Flatpak => "Flatpak", + Install::Other => "—", + } + } +} + +fn writable_dir(dir: &Path) -> bool { + let probe = dir.join(".chesspenguin-write-test"); + let ok = std::fs::File::create(&probe).is_ok(); + let _ = std::fs::remove_file(&probe); + ok +} + +/// How this copy was installed (see [`Install`]). +pub fn detect() -> Install { + if let Ok(kind) = std::env::var("CP_UPDATE_KIND") { + let exe = std::env::current_exe().unwrap_or_default(); + return match kind.as_str() { + "windows" => Install::Windows(exe), + "mac" => Install::Mac, + "appimage" => { + Install::AppImage(std::env::var_os("APPIMAGE").map_or(exe, PathBuf::from)) + } + "tarball" => Install::Tarball(exe.parent().map(Path::to_owned).unwrap_or_default()), + "deb" => Install::Deb, + "rpm" => Install::Rpm, + "arch" => Install::Arch, + "aur" => Install::Aur, + "flatpak" => Install::Flatpak, + _ => Install::Other, + }; + } + let Ok(exe) = std::env::current_exe() else { + return Install::Other; + }; + if cfg!(windows) { + return match exe.parent() { + Some(d) if writable_dir(d) => Install::Windows(exe), + _ => Install::Other, + }; + } + if cfg!(target_os = "macos") { + return if exe.to_string_lossy().contains(".app/Contents/MacOS/") { + Install::Mac + } else { + Install::Other + }; + } + if std::env::var_os("FLATPAK_ID").is_some() { + return Install::Flatpak; + } + // An AppImage of ours: the AppImage runtime sets APPIMAGE and APPDIR, and this + // executable lies inside APPDIR (a variable inherited from another AppImage, such + // as a terminal started from one, must not make us replace that one). + if let (Some(p), Some(appdir)) = ( + std::env::var_os("APPIMAGE").map(PathBuf::from), + std::env::var_os("APPDIR").map(PathBuf::from), + ) && exe.starts_with(&appdir) + { + let p = std::fs::canonicalize(&p).unwrap_or(p); + return match p.parent() { + Some(d) if p.is_file() && writable_dir(d) => Install::AppImage(p), + _ => Install::Other, + }; + } + if exe == Path::new("/usr/bin/chesspenguin") { + return package_kind(); + } + // The tarball: the executable next to the files it was unpacked with. + if let Some(dir) = exe.parent() + && dir.join("THIRD_PARTY_NOTICES.md").is_file() + && dir.join("examples").is_dir() + && !dir.join("Cargo.toml").exists() + && writable_dir(dir) + { + return Install::Tarball(dir.to_owned()); + } + Install::Other +} + +/// Which package manager owns `/usr/bin/chesspenguin`. +fn package_kind() -> Install { + if let Ok(entries) = std::fs::read_dir("/var/lib/pacman/local") { + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if name.starts_with("chesspenguin-bin-") { + return Install::Aur; + } + if name + .strip_prefix("chesspenguin-") + .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) + { + return Install::Arch; + } + } + } + if Path::new("/var/lib/dpkg/info/chesspenguin.list").is_file() { + return Install::Deb; + } + let rpm = std::process::Command::new("rpm") + .args(["-q", "chesspenguin"]) + .output(); + if rpm.is_ok_and(|o| o.status.success()) { + return Install::Rpm; + } + Install::Other +} + +/// The file of a release for a kind of installation. +pub trait ReleaseExt { + fn asset_for(&self, kind: &Install) -> Option<&Asset>; +} + +impl ReleaseExt for Release { + fn asset_for(&self, kind: &Install) -> Option<&Asset> { + self.asset_ending(kind.asset_suffix()?) + } +} + +/// A local directory standing in for GitHub (tests). +fn source_dir() -> Option { + std::env::var_os("CP_UPDATE_SOURCE").map(PathBuf::from) +} + +/// Who asks the site and GitHub. +fn client() -> String { + format!("ChessPenguin/{}", env!("CARGO_PKG_VERSION")) +} + +static INSTALL_ID: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// This installation's id for the update check (`Settings::install_id`). +pub fn set_install_id(id: &str) { + let _ = INSTALL_ID.set(id.to_owned()); +} + +/// A new random installation id: 32 hex digits. +pub fn new_install_id() -> String { + let mut b = [0u8; 16]; + if getrandom::fill(&mut b).is_err() { + // No randomness: no id; the check then goes to GitHub, uncounted. + return String::new(); + } + b.iter().map(|x| format!("{x:02x}")).collect() +} + +impl Install { + /// The platform the site counts this installation under. + fn platform(&self) -> &'static str { + match self { + Install::Windows(_) => "windows", + Install::Mac => "macos", + Install::AppImage(_) => "appimage", + Install::Tarball(_) => "tarball", + Install::Deb => "deb", + Install::Rpm => "rpm", + Install::Arch => "arch", + Install::Aur => "aur", + Install::Flatpak => "flatpak", + Install::Other => "other", + } + } +} + +/// Asks for the latest release (through the site, which counts this installation; see +/// `releases::check_latest`). `Err` with a short reason when there is no answer. +pub fn latest() -> Result { + match source_dir() { + Some(dir) => { + let text = + std::fs::read_to_string(dir.join("latest.json")).map_err(|e| e.to_string())?; + let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + releases::parse_release(&v).ok_or_else(|| "unexpected answer".to_owned()) + } + None => match INSTALL_ID.get().filter(|id| !id.is_empty()) { + Some(id) => releases::check_latest(id, detect().platform(), &client()), + None => releases::fetch_latest(releases::API, &client()), + }, + } +} + +/// Opens an asset for reading (from GitHub or from the test directory). +fn open(asset: &Asset) -> Result, String> { + match source_dir() { + Some(dir) => Ok(Box::new( + std::fs::File::open(dir.join(&asset.name)).map_err(|e| e.to_string())?, + )), + None => releases::open(asset, &client()), + } +} + +/// The SHA-256 of `name` in the release's `SHA256SUMS.txt`. +fn expected_sum(release: &Release, name: &str) -> Result { + let sums = release.sums().ok_or("the release has no SHA256SUMS.txt")?; + let mut text = String::new(); + open(sums)? + .take(1 << 20) + .read_to_string(&mut text) + .map_err(|e| e.to_string())?; + releases::sum_in(&text, name).ok_or_else(|| format!("{name} is not in SHA256SUMS.txt")) +} + +/// Downloads `asset` into `to` (a `.part` file first), checking its SHA-256; +/// `progress` counts the bytes. +fn download( + release: &Release, + asset: &Asset, + to: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result<(), String> { + let expected = expected_sum(release, &asset.name)?; + if let Some(d) = to.parent() { + std::fs::create_dir_all(d).map_err(|e| e.to_string())?; + } + let part = to.with_extension("part"); + let result = (|| { + let mut input = open(asset)?; + let mut file = std::fs::File::create(&part).map_err(|e| e.to_string())?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + loop { + if cancel.load(Ordering::Relaxed) { + return Err("cancelled".to_owned()); + } + let n = input.read(&mut buf).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]).map_err(|e| e.to_string())?; + progress.fetch_add(n, Ordering::Relaxed); + } + file.sync_all().map_err(|e| e.to_string())?; + let got = hasher + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + if got != expected { + return Err("checksum".to_owned()); + } + std::fs::rename(&part, to).map_err(|e| e.to_string()) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&part); + } + result +} + +/// What an update ended with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Applied { + /// The program's files are replaced: restarting runs the new version. + Restart(PathBuf), + /// The package is in Downloads: this command installs it. + Command { file: PathBuf, command: String }, + /// The macOS disk image is open: drag the app over the old one. + DiskImageOpened(PathBuf), +} + +#[cfg(unix)] +fn make_executable(p: &Path) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)) +} + +#[cfg(not(unix))] +fn make_executable(_: &Path) -> std::io::Result<()> { + Ok(()) +} + +/// Puts `new` in place of `target` (the running program): `new` is moved next to it +/// first, so the switch is one rename on the same disk. On Windows the running +/// executable cannot be overwritten but can be renamed: it becomes `.old` (removed +/// at the next start, see [`clean_leftovers`]). +pub fn replace_file(new: &Path, target: &Path) -> std::io::Result<()> { + let name = target + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let staged = target.with_file_name(format!(".{name}.new")); + std::fs::copy(new, &staged)?; + // The permissions of the file it replaces (an executable stays one). + match std::fs::metadata(target) { + Ok(m) => std::fs::set_permissions(&staged, m.permissions())?, + Err(_) => make_executable(&staged)?, + } + if cfg!(windows) { + let old = target.with_file_name(format!("{name}.old")); + let _ = std::fs::remove_file(&old); + if target.exists() { + std::fs::rename(target, &old)?; + } + if let Err(e) = std::fs::rename(&staged, target) { + // Put the old one back rather than leave nothing. + let _ = std::fs::rename(&old, target); + return Err(e); + } + Ok(()) + } else { + std::fs::rename(&staged, target) + } +} + +/// Removes what an update left: the previous Windows executable, a staged file. +pub fn clean_leftovers() { + let Ok(exe) = std::env::current_exe() else { + return; + }; + let name = exe + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let _ = std::fs::remove_file(exe.with_file_name(format!("{name}.old"))); + let _ = std::fs::remove_file(exe.with_file_name(format!(".{name}.new"))); +} + +fn cache_dir() -> PathBuf { + if let Some(d) = std::env::var_os("CP_UPDATE_CACHE") { + return PathBuf::from(d); + } + crate::settings::Settings::cache_dir() + .unwrap_or_else(std::env::temp_dir) + .join("update") +} + +/// `XDG_DOWNLOAD_DIR` of the user's own `~/.config/user-dirs.dirs` (a Flatpak has its +/// own config folder, where the file is not). +fn host_download_dir(home: &Path) -> Option { + let text = std::fs::read_to_string(home.join(".config/user-dirs.dirs")).ok()?; + let line = text + .lines() + .find_map(|l| l.trim().strip_prefix("XDG_DOWNLOAD_DIR="))?; + let v = line + .trim() + .trim_matches('"') + .replace("$HOME", &home.to_string_lossy()); + let p = PathBuf::from(v); + p.is_dir().then_some(p) +} + +/// Downloads (the system's, else `~/Downloads` when it exists, else the home folder). +fn downloads_dir() -> PathBuf { + let dirs = directories::UserDirs::new(); + dirs.as_ref() + .and_then(|u| u.download_dir().map(Path::to_owned)) + .or_else(|| dirs.as_ref().and_then(|u| host_download_dir(u.home_dir()))) + .or_else(|| { + dirs.as_ref() + .map(|u| u.home_dir().join("Downloads")) + .filter(|d| d.is_dir()) + }) + .or_else(|| dirs.as_ref().map(|u| u.home_dir().to_owned())) + .unwrap_or_else(std::env::temp_dir) +} + +/// A word for a shell command: as it is when it has only safe characters, else in +/// single quotes (nothing is expanded inside them in sh, bash, zsh and fish). +fn shell_word(s: &str) -> String { + let safe = |c: char| c.is_ascii_alphanumeric() || "/._-+:@%,".contains(c); + if !s.is_empty() && s.chars().all(safe) { + s.to_owned() + } else { + format!("'{}'", s.replace('\'', "'\\''")) + } +} + +/// The executable inside a downloaded Windows zip or Linux tarball. +fn unpack_executable(archive: &Path, kind: &Install, into: &Path) -> Result { + std::fs::create_dir_all(into).map_err(|e| e.to_string())?; + let out = into.join(if matches!(kind, Install::Windows(_)) { + "ChessPenguin.exe" + } else { + "chesspenguin" + }); + match kind { + Install::Windows(_) => { + let file = std::fs::File::open(archive).map_err(|e| e.to_string())?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + let mut found = false; + for i in 0..zip.len() { + let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; + let name = entry.name().map_err(|e| e.to_string())?.into_owned(); + if entry.is_file() + && (name.ends_with("/ChessPenguin.exe") || name == "ChessPenguin.exe") + { + let mut f = std::fs::File::create(&out).map_err(|e| e.to_string())?; + std::io::copy(&mut entry, &mut f).map_err(|e| e.to_string())?; + found = true; + break; + } + } + if !found { + return Err("ChessPenguin.exe is not in the archive".into()); + } + } + _ => { + let file = std::fs::File::open(archive).map_err(|e| e.to_string())?; + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file)); + let mut found = false; + for entry in tar.entries().map_err(|e| e.to_string())? { + let mut entry = entry.map_err(|e| e.to_string())?; + let path = entry.path().map_err(|e| e.to_string())?.into_owned(); + if path.file_name().is_some_and(|n| n == "chesspenguin") + && entry.header().entry_type().is_file() + { + let mut f = std::fs::File::create(&out).map_err(|e| e.to_string())?; + std::io::copy(&mut entry, &mut f).map_err(|e| e.to_string())?; + found = true; + break; + } + } + if !found { + return Err("chesspenguin is not in the archive".into()); + } + } + } + make_executable(&out).map_err(|e| e.to_string())?; + Ok(out) +} + +/// Downloads and applies the update for this installation (in a background thread). +pub fn update( + release: &Release, + kind: &Install, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + let asset = release + .asset_for(kind) + .ok_or("the release has no file for this installation")? + .clone(); + match kind { + Install::Windows(_) | Install::AppImage(_) | Install::Tarball(_) => { + let dir = cache_dir(); + let archive = dir.join(&asset.name); + download(release, &asset, &archive, progress, cancel)?; + let result = (|| { + let (new, target) = match kind { + Install::AppImage(path) => (archive.clone(), path.clone()), + Install::Windows(exe) => ( + unpack_executable(&archive, kind, &dir.join("unpacked"))?, + exe.clone(), + ), + Install::Tarball(folder) => ( + unpack_executable(&archive, kind, &dir.join("unpacked"))?, + folder.join("chesspenguin"), + ), + _ => unreachable!("kinds that replace themselves"), + }; + replace_file(&new, &target).map_err(|e| e.to_string())?; + Ok(Applied::Restart(target)) + })(); + let _ = std::fs::remove_dir_all(&dir); + result + } + Install::Mac => { + let file = downloads_dir().join(&asset.name); + download(release, &asset, &file, progress, cancel)?; + let _ = std::process::Command::new("open").arg(&file).spawn(); + Ok(Applied::DiskImageOpened(file)) + } + Install::Deb | Install::Rpm | Install::Arch | Install::Flatpak => { + let file = downloads_dir().join(&asset.name); + download(release, &asset, &file, progress, cancel)?; + Ok(Applied::Command { + command: install_command(kind, &file).unwrap_or_default(), + file, + }) + } + Install::Aur | Install::Other => Err("no automatic update for this installation".into()), + } +} + +/// openSUSE installs rpm packages with zypper, the others with dnf. +fn suse() -> bool { + std::fs::read_to_string("/etc/os-release").is_ok_and(|t| { + t.lines() + .any(|l| (l.starts_with("ID=") || l.starts_with("ID_LIKE=")) && l.contains("suse")) + }) +} + +/// A Flatpak installed for the user (not system-wide): `/.flatpak-info` says where. +fn flatpak_user() -> bool { + std::fs::read_to_string("/.flatpak-info").map_or(true, |t| t.contains("/.local/share/flatpak")) +} + +/// The command that installs a downloaded package (`None`: nothing to download): it +/// goes to the package's folder first, so the command stays short. +pub fn install_command(kind: &Install, file: &Path) -> Option { + let dir = shell_word(&file.parent()?.to_string_lossy()); + let name = shell_word(&format!("./{}", file.file_name()?.to_string_lossy())); + let install = match kind { + Install::Deb => "sudo apt install", + Install::Rpm if suse() => "sudo zypper install", + Install::Rpm => "sudo dnf install", + Install::Arch => "sudo pacman -U", + Install::Flatpak if flatpak_user() => "flatpak install --user --reinstall -y", + Install::Flatpak => "flatpak install --system --reinstall -y", + _ => return None, + }; + Some(format!("cd {dir} && {install} {name}")) +} + +/// The command for the AUR package (no download: the helper builds it). +pub const AUR_COMMAND: &str = "yay -Syu chesspenguin-bin"; +/// The same with the other common AUR helper. +pub const AUR_COMMAND_PARU: &str = "paru -Syu chesspenguin-bin"; + +/// The release check at start, in the background. +pub struct Check { + rx: Option>>, + pub release: Option, + pub error: Option, + pub done: bool, +} + +impl Check { + pub fn idle() -> Check { + Check { + rx: None, + release: None, + error: None, + done: false, + } + } + + /// Asks again, keeping what the previous check found until the answer comes (a + /// failed second check does not take an offer away). + pub fn again(&self, ctx: &egui::Context) -> Check { + let mut c = Check::start(ctx); + c.release = self.release.clone(); + c + } + + pub fn start(ctx: &egui::Context) -> Check { + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new() + .name("update-check".into()) + .spawn(move || { + let _ = tx.send(latest()); + ctx.request_repaint(); + }); + Check { + rx: spawned.ok().map(|_| rx), + ..Check::idle() + } + } + + pub fn poll(&mut self) { + if let Some(rx) = &self.rx + && let Ok(r) = rx.try_recv() + { + match r { + Ok(rel) => { + self.release = Some(rel); + self.error = None; + } + Err(e) => self.error = Some(e), + } + self.rx = None; + self.done = true; + } + } + + pub fn running(&self) -> bool { + self.rx.is_some() + } + + /// A newer release, if one was found. + pub fn newer(&self) -> Option<&Release> { + self.release.as_ref().filter(|r| r.newer()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn versions() { + assert_eq!(parse_version("v0.7.1"), Some((0, 7, 1))); + assert_eq!(parse_version("0.8"), Some((0, 8, 0))); + assert_eq!(parse_version("1.2.3-beta"), Some((1, 2, 3))); + assert_eq!(parse_version("x"), None); + assert!((0, 10, 0) > (0, 9, 9)); + } + + fn release() -> Release { + let names = [ + "ChessPenguin-9.9.9-windows-x86_64.zip", + "ChessPenguin-9.9.9-macos-arm64.dmg", + "ChessPenguin-9.9.9-x86_64.AppImage", + "ChessPenguin-9.9.9-linux-x86_64.tar.gz", + "chesspenguin_9.9.9_amd64.deb", + "chesspenguin-9.9.9-1.x86_64.rpm", + "chesspenguin-9.9.9-1-x86_64.pkg.tar.zst", + "ChessPenguin-9.9.9-x86_64.flatpak", + "SHA256SUMS.txt", + ]; + Release { + version: "9.9.9".into(), + page: String::new(), + assets: names + .iter() + .map(|n| Asset { + name: (*n).into(), + url: format!("https://example.org/{n}"), + size: 1, + }) + .collect(), + } + } + + #[test] + fn an_asset_for_every_installation() { + let r = release(); + assert!(r.newer()); + for (kind, name) in [ + ( + Install::Windows(PathBuf::new()), + "ChessPenguin-9.9.9-windows-x86_64.zip", + ), + (Install::Mac, "ChessPenguin-9.9.9-macos-arm64.dmg"), + ( + Install::AppImage(PathBuf::new()), + "ChessPenguin-9.9.9-x86_64.AppImage", + ), + ( + Install::Tarball(PathBuf::new()), + "ChessPenguin-9.9.9-linux-x86_64.tar.gz", + ), + (Install::Deb, "chesspenguin_9.9.9_amd64.deb"), + (Install::Rpm, "chesspenguin-9.9.9-1.x86_64.rpm"), + (Install::Arch, "chesspenguin-9.9.9-1-x86_64.pkg.tar.zst"), + (Install::Flatpak, "ChessPenguin-9.9.9-x86_64.flatpak"), + ] { + assert_eq!(r.asset_for(&kind).map(|a| a.name.as_str()), Some(name)); + } + assert!(r.asset_for(&Install::Aur).is_none()); + } + + #[test] + fn commands() { + let f = Path::new("/home/u/Downloads/chesspenguin_9.9.9_amd64.deb"); + assert_eq!( + install_command(&Install::Deb, f).unwrap(), + "cd /home/u/Downloads && sudo apt install ./chesspenguin_9.9.9_amd64.deb" + ); + let spaced = Path::new("/home/u/My Downloads/x.flatpak"); + assert!( + install_command(&Install::Flatpak, spaced) + .unwrap() + .starts_with("cd '/home/u/My Downloads' && flatpak install") + ); + // Nothing in a path is expanded by the shell. + for nasty in [ + "/home/a`id`/x.deb", + "/home/$USER/x.deb", + "/home/O'Brien/x.deb", + "/h/a b/!x.deb", + ] { + let c = install_command(&Install::Deb, Path::new(nasty)).unwrap(); + let out = std::process::Command::new("sh") + .arg("-c") + .arg( + c.replace("cd ", "printf '%s\\n' ") + .replace(" && sudo apt install ", " "), + ) + .output() + .unwrap(); + let text = String::from_utf8(out.stdout).unwrap(); + let p = Path::new(nasty); + assert_eq!( + text, + format!( + "{}\n./{}\n", + p.parent().unwrap().display(), + p.file_name().unwrap().to_string_lossy() + ), + "{nasty}" + ); + } + } + + /// The running test executable can be put aside and back: what an update does to + /// the running program (on Windows the rename is the point of the scheme). + #[test] + fn replacing_the_running_executable() { + let exe = std::env::current_exe().unwrap(); + let dir = std::env::temp_dir().join(format!("cp-update-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // A copy of the running executable stands for the program in its folder. + let target = dir.join(exe.file_name().unwrap()); + std::fs::copy(&exe, &target).unwrap(); + let new = dir.join("new-version"); + std::fs::write(&new, b"new version").unwrap(); + replace_file(&new, &target).unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"new version"); + if cfg!(windows) { + let name = target.file_name().unwrap().to_string_lossy().into_owned(); + assert!(target.with_file_name(format!("{name}.old")).exists()); + } + assert!( + !dir.join(format!( + ".{}.new", + target.file_name().unwrap().to_string_lossy() + )) + .exists() + ); + // And the running executable itself can be renamed and put back. + let aside = exe.with_extension("cp-test-aside"); + std::fs::rename(&exe, &aside).unwrap(); + std::fs::rename(&aside, &exe).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A whole update from a local "release": the tarball's executable replaced, the + /// checksum checked, a wrong checksum refused. + #[test] + fn tarball_update_from_a_local_release() { + let root = std::env::temp_dir().join(format!("cp-update-tar-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let src = root.join("release"); + let installed = root.join("installed"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::create_dir_all(&installed).unwrap(); + std::fs::write(installed.join("chesspenguin"), b"old").unwrap(); + // The release tarball: a folder with the new executable. + let name = "ChessPenguin-9.9.9-linux-x86_64.tar.gz"; + { + let f = std::fs::File::create(src.join(name)).unwrap(); + let gz = flate2::write::GzEncoder::new(f, flate2::Compression::fast()); + let mut tar = tar::Builder::new(gz); + let mut h = tar::Header::new_gnu(); + h.set_size(3); + h.set_mode(0o755); + h.set_cksum(); + tar.append_data( + &mut h, + "ChessPenguin-9.9.9-linux-x86_64/chesspenguin", + &b"new"[..], + ) + .unwrap(); + tar.into_inner().unwrap().finish().unwrap(); + } + let sum = |p: &Path| { + Sha256::digest(std::fs::read(p).unwrap()) + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + }; + std::fs::write( + src.join("SHA256SUMS.txt"), + format!("{} {name}\n", sum(&src.join(name))), + ) + .unwrap(); + let rel = Release { + version: "9.9.9".into(), + page: String::new(), + assets: [name, "SHA256SUMS.txt"] + .iter() + .map(|n| Asset { + name: (*n).into(), + url: String::new(), + size: 0, + }) + .collect(), + }; + // SAFETY of the test: the variable is only read by this process's update code. + unsafe { + std::env::set_var("CP_UPDATE_SOURCE", &src); + std::env::set_var("CP_UPDATE_CACHE", root.join("cache")); + } + let kind = Install::Tarball(installed.clone()); + let progress = AtomicUsize::new(0); + let applied = update(&rel, &kind, &progress, &AtomicBool::new(false)).unwrap(); + assert_eq!(applied, Applied::Restart(installed.join("chesspenguin"))); + assert_eq!( + std::fs::read(installed.join("chesspenguin")).unwrap(), + b"new" + ); + assert!(progress.load(Ordering::Relaxed) > 0); + // A damaged download is refused and nothing is replaced. + std::fs::write(installed.join("chesspenguin"), b"old").unwrap(); + std::fs::write( + src.join("SHA256SUMS.txt"), + format!("{} {name}\n", "0".repeat(64)), + ) + .unwrap(); + let err = update(&rel, &kind, &AtomicUsize::new(0), &AtomicBool::new(false)).unwrap_err(); + assert_eq!(err, "checksum"); + assert_eq!( + std::fs::read(installed.join("chesspenguin")).unwrap(), + b"old" + ); + unsafe { + std::env::remove_var("CP_UPDATE_SOURCE"); + std::env::remove_var("CP_UPDATE_CACHE"); + } + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/apps/desktop/src/update_ui.rs b/apps/desktop/src/update_ui.rs new file mode 100644 index 0000000..9d83bc3 --- /dev/null +++ b/apps/desktop/src/update_ui.rs @@ -0,0 +1,416 @@ +//! The update window: the new version and the one step this installation needs (see +//! `update.rs`): update and restart; download and open the disk image; or download the +//! package and copy the command that installs it. Closing the window does not stop a +//! download (the button next to Settings shows its progress). + +use egui::{RichText, Ui}; + +use crate::board_search::Background; +use crate::i18n::{tr, trf}; +use crate::update::{self, Applied, Install, Release, ReleaseExt}; + +/// What the window asks of the application. +pub enum UpdateEvent { + /// Quit (asking about unsaved games as usual) and start this executable. + Restart(std::path::PathBuf), + /// Quit (to replace the app from the disk image, or to start the installed package). + Quit, + CopyText(String), + /// Hide the offer of this version. + Skip(String), +} + +#[derive(Default)] +pub struct UpdateDialog { + pub open: bool, + /// Dev hook (screenshots, manual checks): `CP_UPDATE_OPEN=1` opens the window once a + /// newer release is known, `=start` also starts the update. + auto: Option, + job: Option<(u64, Background>)>, + result: Option>, +} + +fn mb(bytes: u64) -> String { + if bytes < 1_000_000 { + tr("less than 1").to_owned() + } else { + format!("{:.0}", bytes as f64 / 1e6) + } +} + +/// The installation for the footnote (for support, not for the decision). +fn install_name(kind: &Install) -> String { + match kind { + Install::Deb => tr("deb package").to_owned(), + Install::Rpm => tr("rpm package").to_owned(), + Install::Arch => tr("Arch Linux package").to_owned(), + Install::Tarball(_) => tr("archive (tar.gz)").to_owned(), + Install::Flatpak => "Flatpak".to_owned(), + Install::Aur => "AUR (chesspenguin-bin)".to_owned(), + other => other.label().to_owned(), + } +} + +/// A failure in words a chess player can act on; the technical text goes under +/// "Details". +fn failure_text(e: &str) -> String { + let lower = e.to_lowercase(); + if e == "checksum" { + tr("The file got damaged while downloading, so it was not installed. Try again.").to_owned() + } else if e == "cancelled" { + tr("The download was cancelled.").to_owned() + } else if lower.contains("no file for this installation") + || lower.contains("not in sha256sums") + || lower.contains("no sha256sums") + { + tr("This release has no file for your system yet. Download the new version from the website.").to_owned() + } else if lower.contains("permission denied") + || lower.contains("no space") + || lower.contains("read-only") + || lower.contains("os error 13") + || lower.contains("os error 28") + || lower.contains("os error 30") + { + tr("The file could not be saved: no permission to write there, or the disk is full.") + .to_owned() + } else { + tr("The new version could not be downloaded: no connection to the server. Check the internet and try again.").to_owned() + } +} + +impl UpdateDialog { + pub fn from_env() -> UpdateDialog { + let auto = std::env::var("CP_UPDATE_OPEN").ok().map(|v| v == "start"); + UpdateDialog { + auto, + ..UpdateDialog::default() + } + } + + /// The update is under way or done (its button stays even for a skipped version). + pub fn active(&self) -> bool { + self.job.is_some() || matches!(self.result, Some(Ok(_))) + } + + /// What the button next to Settings says: the offer, the download's progress, or + /// that the new version waits for a restart / for its command. + pub fn badge(&self, release: &Release) -> String { + if let Some((size, job)) = &self.job { + let pct = if *size > 0 { + (100 * job.progress() as u64 / size).min(100) + } else { + 0 + }; + return trf("⬇ {v}: {p} %", &[("v", &release.version), ("p", &pct)]); + } + match &self.result { + Some(Ok(Applied::Restart(_))) => trf("⟳ Restart for {v}", &[("v", &release.version)]), + Some(Ok(Applied::Command { .. } | Applied::DiskImageOpened(_))) => { + trf("⬆ {v}: install", &[("v", &release.version)]) + } + _ => trf("⬆ Update {v}", &[("v", &release.version)]), + } + } + + fn start(&mut self, release: &Release, kind: &Install, ctx: &egui::Context) { + let size = release.asset_for(kind).map_or(0, |a| a.size); + let (r, k) = (release.clone(), kind.clone()); + let now = ctx.input(|i| i.time); + self.result = None; + self.job = Background::spawn(ctx, now, move |progress, cancel| { + Some(update::update(&r, &k, progress, cancel)) + }) + .map(|j| (size, j)); + } + + pub fn show( + &mut self, + ctx: &egui::Context, + release: Option<&Release>, + kind: &Install, + ) -> Vec { + let mut events = Vec::new(); + if let Some((_, job)) = &self.job + && let Some(r) = job.poll() + { + self.result = Some(r.unwrap_or_else(|| Err("cancelled".into()))); + self.job = None; + } + if self.job.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } + let Some(release) = release else { + return events; + }; + if let Some(start) = self.auto.take() { + self.open = true; + if start { + self.start(release, kind, ctx); + } + } + if !self.open { + return events; + } + let mut open = true; + egui::Window::new(tr("ChessPenguin update")) + .open(&mut open) + .collapsible(false) + .default_width(560.0) + .max_width(620.0) + .pivot(egui::Align2::CENTER_TOP) + .default_pos(ctx.content_rect().center_top() + egui::vec2(0.0, 110.0)) + .show(ctx, |ui| self.body(ui, release, kind, &mut events)); + if !open { + // A running download goes on; the button next to Settings shows it. + self.open = false; + } + events + } + + fn body( + &mut self, + ui: &mut Ui, + release: &Release, + kind: &Install, + events: &mut Vec, + ) { + let asset = release.asset_for(kind); + // Running. + if let Some((size, job)) = &self.job { + heading(ui, release); + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(trf( + "Downloading… {done} of {total} MB", + &[ + ("done", &format!("{:.0}", job.progress() as f64 / 1e6)), + ("total", &mb(*size)), + ], + )); + if ui.button(tr("Cancel")).clicked() { + job.cancel(); + } + }); + if *size > 0 { + ui.add(egui::ProgressBar::new( + (job.progress() as f32 / *size as f32).min(1.0), + )); + } + ui.label(RichText::new(tr("You can close this window: the download goes on.")).weak()); + return; + } + // Finished. + match &self.result { + Some(Ok(Applied::Restart(exe))) => { + ui.label( + RichText::new(trf("Version {v} is installed", &[("v", &release.version)])) + .heading(), + ); + ui.label(tr("It starts after a restart. Unsaved games are asked about first; databases and settings stay as they are.")); + ui.add_space(6.0); + ui.horizontal(|ui| { + if crate::widgets::primary(ui, tr("⟳ Restart now")).clicked() { + events.push(UpdateEvent::Restart(exe.clone())); + } + if ui.button(tr("Later")).clicked() { + self.open = false; + } + }); + return; + } + Some(Ok(Applied::DiskImageOpened(_))) => { + ui.label(RichText::new(tr("The disk image is open")).heading()); + ui.label(tr( + "1. Quit ChessPenguin (the button below): a running app cannot be replaced.", + )); + ui.label(tr("2. In the window of the disk image, drag the ChessPenguin icon onto the Applications folder and choose Replace.")); + ui.label(tr("3. Start ChessPenguin from Applications.")); + ui.add_space(6.0); + if crate::widgets::primary(ui, tr("Quit ChessPenguin")).clicked() { + events.push(UpdateEvent::Quit); + } + return; + } + Some(Ok(Applied::Command { file, command })) => { + ui.label(RichText::new(tr("The new version is downloaded")).heading()); + ui.horizontal_wrapped(|ui| { + let dir = file + .parent() + .and_then(|d| d.file_name()) + .map(|n| format!("«{}»", n.to_string_lossy())) + .unwrap_or_default(); + ui.label(trf("The file is in the folder {dir}.", &[("dir", &dir)])); + if ui.link(tr("Open the folder")).clicked() + && let Some(d) = file.parent() + { + open_folder(d); + } + }); + ui.add_space(4.0); + ui.label(tr("1. Copy the command.")); + command_line(ui, command, events); + if matches!(kind, Install::Flatpak) { + ui.label(tr("2. Open the Terminal of your system (not inside the Flatpak), paste the command (Ctrl+Shift+V) and press Enter.")); + } else { + ui.label(tr("2. Open the Terminal, paste the command (Ctrl+Shift+V) and press Enter. It asks for your password: while you type it nothing is shown, that is normal.")); + } + ui.label(tr( + "3. When the command has finished, start ChessPenguin again.", + )); + ui.add_space(6.0); + if ui.button(tr("Quit ChessPenguin")).clicked() { + events.push(UpdateEvent::Quit); + } + return; + } + _ => {} + } + heading(ui, release); + let mut retry = false; + if let Some(Err(e)) = &self.result { + ui.label(RichText::new(failure_text(e)).color(ui.visuals().warn_fg_color)); + if e != "cancelled" && e != "checksum" { + egui::CollapsingHeader::new(tr("Details")) + .id_salt("update_details") + .show(ui, |ui| { + ui.label(RichText::new(e).monospace().weak()); + }); + } + ui.add_space(4.0); + retry = true; + } + let action = |retry: bool, first: &'static str| if retry { tr("Try again") } else { first }; + // What to do. + match (kind, asset) { + (Install::Aur, _) => { + ui.label(tr( + "ChessPenguin is installed from the AUR. Update it as usual, for example:", + )); + command_line(ui, update::AUR_COMMAND, events); + ui.label(RichText::new(trf("or: {c}", &[("c", &update::AUR_COMMAND_PARU)])).weak()); + } + (k, Some(a)) if k.replaces_itself() => { + ui.label(trf( + "ChessPenguin downloads the new version ({mb} MB), checks it and puts it in place of this one. Databases, games and settings are not touched.", + &[("mb", &mb(a.size))], + )); + ui.add_space(6.0); + ui.horizontal(|ui| { + if crate::widgets::primary(ui, action(retry, tr("⬆ Update"))).clicked() { + self.start(release, k, ui.ctx()); + } + self.not_now(ui, release, events); + }); + } + (Install::Mac, Some(a)) => { + ui.label(trf( + "ChessPenguin downloads the disk image ({mb} MB), checks it and opens it; then you drag the app over the old one, as when you installed it.", + &[("mb", &mb(a.size))], + )); + ui.add_space(6.0); + ui.horizontal(|ui| { + if crate::widgets::primary(ui, action(retry, tr("⬇ Download"))).clicked() { + self.start(release, kind, ui.ctx()); + } + self.not_now(ui, release, events); + }); + } + (k, Some(a)) => { + ui.label(trf( + "ChessPenguin was installed through the system (its package manager), so it cannot replace itself. It downloads the new version ({mb} MB) into Downloads; to install it you run one command in a terminal, which you can copy.", + &[("mb", &mb(a.size))], + )); + ui.add_space(6.0); + ui.horizontal(|ui| { + if crate::widgets::primary(ui, action(retry, tr("⬇ Download"))).clicked() { + self.start(release, k, ui.ctx()); + } + self.not_now(ui, release, events); + }); + } + (Install::Mac | Install::Windows(_), None) => { + ui.label(tr("This release has no file for your system yet. Download the new version from the website:")); + ui.hyperlink_to(update::DOWNLOAD_PAGE, update::DOWNLOAD_PAGE); + } + _ => { + ui.label(tr("Download the new version from the website:")); + ui.hyperlink_to(update::DOWNLOAD_PAGE, update::DOWNLOAD_PAGE); + } + } + if !matches!(kind, Install::Other) { + ui.add_space(4.0); + ui.label( + RichText::new(trf( + "Installation: {kind}", + &[("kind", &install_name(kind))], + )) + .small() + .weak(), + ); + } + } + + /// "Not now" and "Skip this version". + fn not_now(&mut self, ui: &mut Ui, release: &Release, events: &mut Vec) { + if ui.button(tr("Not now")).clicked() { + self.open = false; + } + if ui + .link(tr("Skip this version")) + .on_hover_text(tr( + "The button next to Settings is hidden until the next version; Settings → About still offers this one", + )) + .clicked() + { + events.push(UpdateEvent::Skip(release.version.clone())); + self.open = false; + } + } +} + +/// "Version 0.8.0 is out" with the current version and the release notes under it. +fn heading(ui: &mut Ui, release: &Release) { + ui.label(RichText::new(trf("Version {v} is out", &[("v", &release.version)])).heading()); + ui.horizontal(|ui| { + ui.label( + RichText::new(trf( + "You have {old}", + &[("old", &env!("CARGO_PKG_VERSION"))], + )) + .weak(), + ); + ui.label(RichText::new("·").weak()); + ui.hyperlink_to(tr("What's new"), &release.page); + }); + ui.add_space(6.0); +} + +/// A command in a monospace box with a Copy button beside it. +fn command_line(ui: &mut Ui, command: &str, events: &mut Vec) { + ui.horizontal(|ui| { + let width = (ui.available_width() - 110.0).max(200.0); + egui::Frame::new() + .fill(ui.visuals().extreme_bg_color) + .inner_margin(egui::Margin::symmetric(8, 6)) + .corner_radius(4.0) + .show(ui, |ui| { + ui.set_max_width(width); + ui.add(egui::Label::new(RichText::new(command).monospace()).wrap()); + }); + if crate::widgets::primary(ui, tr("Copy")).clicked() { + events.push(UpdateEvent::CopyText(command.to_owned())); + } + }); +} + +/// Shows a folder in the file manager. +fn open_folder(dir: &std::path::Path) { + let program = if cfg!(target_os = "macos") { + "open" + } else if cfg!(windows) { + "explorer" + } else { + "xdg-open" + }; + let _ = std::process::Command::new(program).arg(dir).spawn(); +} diff --git a/apps/desktop/src/viewed.rs b/apps/desktop/src/viewed.rs new file mode 100644 index 0000000..9f3cf91 --- /dev/null +++ b/apps/desktop/src/viewed.rs @@ -0,0 +1,87 @@ +//! Games the user has opened, remembered by their content (so a mark follows the game +//! when a file is re-sorted or other games are added) in +//! `$XDG_DATA_HOME/chesspenguin/viewed.json`. + +use std::collections::HashSet; +use std::path::PathBuf; + +#[derive(Default)] +pub struct Viewed { + games: HashSet, +} + +impl Viewed { + fn file() -> Option { + crate::platform::data_dir().map(|d| d.join("viewed.json")) + } + + pub fn load() -> Viewed { + let games = Self::file() + .and_then(|p| crate::platform::fs::read(&p).ok()) + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default(); + Viewed { + games: games.into_iter().collect(), + } + } + + fn save(&self) { + let Some(path) = Self::file() else { return }; + let mut list: Vec = self.games.iter().copied().collect(); + list.sort_unstable(); + match serde_json::to_vec(&list) { + Ok(bytes) => { + if let Err(e) = crate::settings::write_atomic(&path, &bytes) { + eprintln!("viewed games: {}: {e}", path.display()); + } + } + Err(e) => eprintln!("viewed games: {e}"), + } + } + + pub fn contains(&self, key: u64) -> bool { + self.games.contains(&key) + } + + pub fn set(&mut self, key: u64, viewed: bool) { + let changed = if viewed { + self.games.insert(key) + } else { + self.games.remove(&key) + }; + if changed { + self.save(); + } + } +} + +/// Identity of a game: FNV-1a 64 of its PGN text without surrounding whitespace. +pub fn key(raw: &[u8]) -> u64 { + let start = raw + .iter() + .position(|b| !b.is_ascii_whitespace()) + .unwrap_or(raw.len()); + let end = raw + .iter() + .rposition(|b| !b.is_ascii_whitespace()) + .map_or(start, |i| i + 1); + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in &raw[start..end.max(start)] { + h ^= u64::from(*b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + h +} + +#[cfg(test)] +mod tests { + #[test] + fn key_ignores_surrounding_whitespace() { + assert_eq!( + super::key(b"\n[Event \"x\"]\n1. e4 *\n\n"), + super::key(b"[Event \"x\"]\n1. e4 *") + ); + assert_ne!(super::key(b"1. e4 *"), super::key(b"1. d4 *")); + assert_eq!(super::key(b" "), super::key(b"")); + } +} diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs new file mode 100644 index 0000000..abac255 --- /dev/null +++ b/apps/desktop/src/widgets.rs @@ -0,0 +1,247 @@ +//! Small shared widgets. + +use egui::{Color32, Sense, Stroke, Ui, vec2}; + +/// The application's settings action, shared by screen headers. +pub fn settings_button(ui: &mut Ui, compact: bool) -> egui::Response { + let tr = crate::i18n::tr; + ui.button(if compact { "âš™" } else { tr("âš™ Settings") }) + .on_hover_text(format!("{} (Ctrl+,)", tr("Settings"))) +} + +/// A section header: reserve global actions before laying out a long title. +/// Returns (back, settings). +#[allow(dead_code)] +pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) { + let mut clicked = (false, false); + let compact = ui.available_width() < 600.0; + ui.horizontal(|ui| { + ui.set_min_height(26.0); + clicked.0 = ui.button(back).clicked(); + ui.separator(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + clicked.1 = settings_button(ui, compact).clicked(); + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add(egui::Label::new(egui::RichText::new(title).heading()).truncate()) + .on_hover_text(title); + }); + }); + }); + clicked +} + +/// A two-line section header in the places of the game's (title and a quiet line under +/// it; an empty subtitle keeps its line, so the header never changes height). +/// Returns (back, settings). +pub fn section_header_sub(ui: &mut Ui, back: &str, title: &str, subtitle: &str) -> (bool, bool) { + let mut clicked = (false, false); + let compact = ui.available_width() < 600.0; + ui.add_space(4.0); + ui.horizontal(|ui| { + clicked.0 = ui.button(back).clicked(); + ui.separator(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + clicked.1 = settings_button(ui, compact).clicked(); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + // The rows of the game screen's header (game_view.rs): the same height. + ui.horizontal(|ui| { + ui.add( + egui::Label::new(egui::RichText::new(title).strong().size(16.0)).truncate(), + ) + .on_hover_text(title); + }); + let sub = ui.add( + egui::Label::new( + egui::RichText::new(if subtitle.is_empty() { " " } else { subtitle }) + .weak(), + ) + .truncate(), + ); + if !subtitle.is_empty() { + sub.on_hover_text(subtitle); + } + }); + }); + }); + ui.add_space(4.0); + clicked +} + +/// A dev check (`CP_PANEL_CHECK=1`): a panel whose content is wider than the panel. egui +/// then moves a right panel out (its left part under the central panel, its right part +/// off the window); the content of every panel must fit its least width +/// (docs/design/narrow-windows.md). +pub fn check_panel(name: &str, panel: &egui::Response) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| { + let on = std::env::var_os("CP_PANEL_CHECK").is_some(); + // In a debug build egui also marks (red) what makes its parent wider. + #[cfg(debug_assertions)] + if on { + panel + .ctx + .all_styles_mut(|s| s.debug.show_expand_width = true); + } + on + }); + if !on { + return; + } + let window = panel.ctx.content_rect(); + let over = (panel.rect.right() - window.right()).max(window.left() - panel.rect.left()); + if over > 0.5 { + eprintln!( + "CP_PANEL_CHECK: panel {name} is {over:.0} pt wider than its place (window {:.0} pt)", + window.width() + ); + } +} + +/// A sortable column's header: the title in bold, â–²/â–¼ when the table is ordered by +/// it (`Some(ascending)`); click to sort. +pub fn sort_header(ui: &mut Ui, label: &str, ascending: Option) -> egui::Response { + let arrow = match ascending { + Some(true) => " â�¶", + Some(false) => " â�·", + None => "", + }; + ui.add(egui::Button::new(egui::RichText::new(format!("{label}{arrow}")).strong()).frame(false)) +} + +/// Compact ✕ (e.g. to cancel a running task); the caller adds the tooltip. +pub fn small_close_button(ui: &mut Ui) -> egui::Response { + x_button(ui, vec2(22.0, 20.0), 4.5) +} + +fn x_button(ui: &mut Ui, size: egui::Vec2, d: f32) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); + if resp.hovered() { + ui.painter() + .rect_filled(rect, 4.0, Color32::from_rgb(0xc4, 0x2b, 0x1c)); + } + let color = if resp.hovered() { + Color32::WHITE + } else { + ui.visuals().text_color() + }; + let c = rect.center(); + let stroke = Stroke::new(1.6, color); + ui.painter() + .line_segment([c + vec2(-d, -d), c + vec2(d, d)], stroke); + ui.painter() + .line_segment([c + vec2(-d, d), c + vec2(d, -d)], stroke); + resp +} + +/// The quiet "ℹ n" of import notes: minor remarks, so no colour and no frame. +pub fn notes_button(ui: &mut egui::Ui, notes: usize) -> egui::Response { + ui.add(egui::Button::new(egui::RichText::new(format!("ℹ {notes}")).weak().small()).frame(false)) + .on_hover_text(crate::i18n::tr("Import notes")) +} + +/// "⬆ Update 0.8.0" (or the download's progress, "⟳ Restart for 0.8.0"): opens the +/// update window. +pub fn update_button(ui: &mut egui::Ui, label: &str) -> egui::Response { + ui.button(egui::RichText::new(label).color(ui.visuals().hyperlink_color)) + .on_hover_text(crate::i18n::tr("A new version of ChessPenguin is out")) +} + +/// The main button of a window: filled, a little taller. +pub fn primary(ui: &mut egui::Ui, label: &str) -> egui::Response { + primary_wide(ui, label, 0.0) +} + +/// The king of a side, `size` points square: White's light with a dark outline, +/// Black's dark with a light one, the same in both themes (task 45; a font's â™”/♚ read +/// the other way round on a dark background). From the classic set, whatever the board's. +pub fn side_king(white: bool, size: f32) -> egui::Image<'static> { + let color = if white { + shakmaty::Color::White + } else { + shakmaty::Color::Black + }; + crate::assets::PieceSet::Cburnett + .image(shakmaty::Piece { + color, + role: shakmaty::Role::King, + }) + .fit_to_exact_size(egui::vec2(size, size)) +} + +/// `primary()` at least `width` wide (a button whose label changes keeps its place). +pub fn primary_wide(ui: &mut egui::Ui, label: &str, width: f32) -> egui::Response { + ui.add( + egui::Button::new(egui::RichText::new(label).strong()) + .fill(ui.visuals().selection.bg_fill) + .min_size(egui::vec2(width, 30.0)), + ) +} + +/// A 30 × 30 button with a painted ✓ (`check`) or ✕: the font has no such glyphs. The +/// main one (`primary`) is filled like `primary()`. +pub fn icon_button(ui: &mut Ui, check: bool, primary: bool) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(vec2(30.0, 30.0), Sense::click()); + let visuals = ui.style().interact(&resp); + let sel = ui.visuals().selection; + let (fill, color) = if primary { + ( + if resp.hovered() { + sel.bg_fill.gamma_multiply(1.15) + } else { + sel.bg_fill + }, + sel.stroke.color, + ) + } else { + (visuals.weak_bg_fill, visuals.text_color()) + }; + ui.painter().rect_filled(rect, 4.0, fill); + if !primary { + ui.painter() + .rect_stroke(rect, 4.0, visuals.bg_stroke, egui::StrokeKind::Inside); + } + let c = rect.center(); + let stroke = Stroke::new(2.0, color); + if check { + ui.painter().add(egui::Shape::line( + vec![ + c + vec2(-5.0, 0.0), + c + vec2(-1.5, 4.0), + c + vec2(5.5, -4.5), + ], + stroke, + )); + } else { + let d = 4.5; + ui.painter() + .line_segment([c + vec2(-d, -d), c + vec2(d, d)], stroke); + ui.painter() + .line_segment([c + vec2(-d, d), c + vec2(d, -d)], stroke); + } + resp +} + +/// `text` cut to `max` characters, with «…» in the middle when longer (a file's or an +/// engine's name keeps its start and its end, where versions and extensions are). +pub fn shorten(text: &str, max: usize) -> String { + let n = text.chars().count(); + if n <= max || max < 3 { + return text.to_owned(); + } + let head = (max - 1) / 2; + let tail = max - 1 - head; + let start: String = text.chars().take(head).collect(); + let end: String = text.chars().skip(n - tail).collect(); + format!("{start}…{end}") +} + +#[cfg(test)] +mod shorten_tests { + #[test] + fn long_names_are_cut_in_the_middle() { + assert_eq!(super::shorten("Stockfish 19", 48), "Stockfish 19"); + assert_eq!(super::shorten("abcdefghij", 5), "ab…ij"); + assert_eq!(super::shorten("абвгдежзик", 7), "абв…зик"); + assert_eq!(super::shorten("abcdefghij", 7).chars().count(), 7); + } +} diff --git a/apps/web/Cargo.toml b/apps/web/Cargo.toml new file mode 100644 index 0000000..889099e --- /dev/null +++ b/apps/web/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "chesspenguin-web" +description = "ChessPenguin in a browser: the entry point of the web version (the interface is apps/desktop's)" +version.workspace = true +authors.workspace = true +repository.workspace = true +homepage.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish = false + +# Built for WebAssembly only (apps/web/build.sh); elsewhere the crate is empty. +[lib] +crate-type = ["cdylib"] + +[target.'cfg(target_family = "wasm")'.dependencies] +chesspenguin = { path = "../desktop" } +wasm-bindgen = "0.2.129" +wasm-bindgen-futures = "0.4" +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "UrlSearchParams"] } +log = "0.4" +eframe.workspace = true diff --git a/apps/web/build.sh b/apps/web/build.sh new file mode 100755 index 0000000..b17514a --- /dev/null +++ b/apps/web/build.sh @@ -0,0 +1,79 @@ +#!/bin/sh +# Builds the web version into a folder served as the site's /app/ (docs/dev/web.md): +# +# apps/web/build.sh [out-dir] (default: target/web/app) +# PROFILE=release apps/web/build.sh (the default profile is `web`: small, slower to build) +# +# Needs: the target wasm32-unknown-unknown (rustup target add wasm32-unknown-unknown), +# wasm-bindgen-cli of the version in Cargo.lock (cargo install wasm-bindgen-cli --version …; +# WASM_BINDGEN= points at another binary), python3. wasm-opt (binaryen) makes the program +# smaller when it is there. +set -eu + +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../.." && pwd) +out=${1:-$root/target/web/app} +profile=${PROFILE:-web} +bindgen=${WASM_BINDGEN:-wasm-bindgen} + +want=$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' "$root/Cargo.lock") +have=$("$bindgen" --version | awk '{ print $2 }') +if [ "$want" != "$have" ]; then + echo "wasm-bindgen $have, but Cargo.lock has $want: cargo install wasm-bindgen-cli --version $want" >&2 + exit 1 +fi + +cd "$root" +cargo build -p chesspenguin-web --target wasm32-unknown-unknown --profile "$profile" +wasm="$root/target/wasm32-unknown-unknown/$profile/chesspenguin_web.wasm" + +rm -rf "$out" +mkdir -p "$out" +"$bindgen" --target web --no-typescript --out-dir "$out" --out-name chesspenguin_web "$wasm" +if command -v wasm-opt >/dev/null 2>&1; then + wasm-opt -Os --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext \ + --enable-mutable-globals --enable-reference-types \ + "$out/chesspenguin_web_bg.wasm" -o "$out/chesspenguin_web_bg.wasm" +fi + +cp "$here/page/device.js" "$here/page/page.js" "$here/page/import-worker.js" "$out/" + +# The engine: Stockfish.js 19.0.1 (npm `stockfish`, GPL-3.0), its single-threaded build, +# checked against the registry's integrity (THIRD_PARTY_NOTICES.md). STOCKFISH_TGZ= points +# at a copy of the package; otherwise it is downloaded once into target/web/. +sf_url=https://registry.npmjs.org/stockfish/-/stockfish-19.0.1.tgz +sf_sha512=bTwsO4e9HAwPBKls1+szcfibmaWRNzTF20rQE/XPdB3LOSoT6XTZDr1zYwriwSRRFT5MkvqrglPmJrKEVXGnyQ== +tgz=${STOCKFISH_TGZ:-$root/target/web/stockfish-19.0.1.tgz} +if [ ! -f "$tgz" ]; then + mkdir -p "$(dirname "$tgz")" + curl -fsSL --retry 3 -o "$tgz.part" "$sf_url" + mv "$tgz.part" "$tgz" +fi +have_sha=$(openssl dgst -sha512 -binary "$tgz" | base64 -w0) +if [ "$have_sha" != "$sf_sha512" ]; then + echo "$tgz is not stockfish@19.0.1 (sha512 $have_sha)" >&2 + exit 1 +fi +mkdir -p "$out/engine" +tar -xzf "$tgz" -C "$out/engine" --strip-components=2 \ + package/bin/stockfish-19-single.js package/bin/stockfish-19-single.wasm +tar -xzf "$tgz" -C "$out/engine" --strip-components=1 package/Copying.txt +for size in 32 64 180; do + cp "$root/website/static/img/icon-$size.png" "$out/" +done +# The page's texts in the site's languages: the app_* keys and the shared ones it uses. +python3 -I - "$here/page/index.html" "$root/website/site/i18n" "$out/index.html" <<'PY' +import json, pathlib, sys +template, i18n, target = sys.argv[1], pathlib.Path(sys.argv[2]), sys.argv[3] +shared = ["btn_android", "and_light_title", "and_full_title", "and_requires", "next_android", + "copy_link", "link_copied", "email", "language"] +texts = {} +for f in sorted(i18n.glob("*.json")): + d = json.loads(f.read_text(encoding="utf-8")) + texts[f.stem] = {k: v for k, v in d.items() if k.startswith("app_") or k in shared} +page = pathlib.Path(template).read_text(encoding="utf-8") +blob = json.dumps(texts, ensure_ascii=False, separators=(",", ":")).replace("; what is checked is printed. +// +// node apps/web/check/app.mjs (app-dir: apps/web/build.sh's) +import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; + +const [appDir, outDir] = process.argv.slice(2).map((p) => resolve(p)); +const root = fileURLToPath(new URL('../../..', import.meta.url)); +mkdirSync(outDir, { recursive: true }); +let failures = 0; +const check = (ok, what) => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); + if (!ok) failures++; +}; +// Places of buttons in a 1400×860 window. +const DOWNLOAD = [Number(process.env.DOWNLOAD_X || 1263), Number(process.env.DOWNLOAD_Y || 24)]; +const E2 = [519, 703]; +const E4 = [519, 505]; +// The card of «Test games» on the shelf after a reload (the draft's strip above it) and +// «Allow reading» on its pane. +const TEST_CARD = [300, 88]; +const ALLOW = [70, 232]; + +const s = await session(appDir, 18766); +const { t } = s; +const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot()); +const text = () => t.evaluate(`document.getElementById('cp-device').innerText`); +const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); +try { + // ----- the page for phones and tablets, without the program ---------------------------- + await t.navigate(`${s.base}?phone=1&lang=ru`); + await sleep(800); + check(/ChessPenguin на телефоне и планшете/.test(await text()), 'the device page in Russian'); + check(/Ð’Ñ�Ñ‘ равно открыть веб-верÑ�ию/.test(await text()), 'with «open the web version anyway»'); + const wasm = await t.evaluate(`performance.getEntriesByType('resource').some(e => e.name.endsWith('.wasm'))`); + check(!wasm, 'the program is not downloaded on it'); + await shot('web-phone-ru.png'); + await t.navigate(`${s.base}?phone=1&lang=de`); + await sleep(500); + check(/auf Handy und Tablet/.test(await text()), 'the device page in German'); + await t.navigate(`${s.base}?phone=android&lang=ru`); + await sleep(800); + check(/Скачать длÑ� Android/.test(await text()), 'the Android variant'); + await t.navigate(`${s.base}?phone=ios&lang=en`); + await sleep(800); + check(/iPhone and iPad app is coming soon/.test(await text()), 'the iPhone and iPad variant'); + + // ----- the program ------------------------------------------------------------------------- + await t.navigate(`${s.base}?lang=en`); + await started(); + await sleep(2500); + check(true, `the program started in ${s.b.name}`); + await shot('web-1-library.png'); + + // Open a PGN by the button's shortcut: the browser's file chooser gets the file. + const pgn = join(s.b.profile, 'Test games.pgn'); + copyFileSync(join(root, 'examples/alekhine.pgn'), pgn); + await t.choose([pgn], () => t.key('o', ['ctrl'])); + await sleep(3000); + await shot('web-2-opened.png'); + + // Drop a file on the window. + const dropped = readFileSync(join(root, 'examples/classics.pgn'), 'utf8'); + await t.evaluate(`(() => { + const dt = new DataTransfer(); + dt.items.add(new File([${JSON.stringify(dropped)}], 'Dropped classics.pgn', { type: 'application/x-chess-pgn' })); + const c = document.getElementById('cp-canvas'); + for (const type of ['dragenter', 'dragover', 'drop']) + c.dispatchEvent(new DragEvent(type, { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 700, clientY: 400 })); + return true; + })()`); + await sleep(3000); + await shot('web-3-dropped.png'); + + // A game from the table (double click), its moves on the board. + await t.click(300, 322, { double: true }); + await sleep(1500); + await shot('web-4-game.png'); + await t.key('right', [], 12); + await sleep(800); + await shot('web-5-moves.png'); + + // Download the PGN of the game (the header's button). + await t.click(...DOWNLOAD); + await sleep(2500); + const files = existsSync(s.b.downloads) ? readdirSync(s.b.downloads).filter((f) => f.endsWith('.pgn')) : []; + check(files.length === 1, `a PGN downloaded: ${files.join(', ') || 'none'}`); + if (files.length) { + const body = readFileSync(join(s.b.downloads, files[0]), 'utf8'); + check(/\[White "/.test(body) && /1\. /.test(body), 'the download is the game in PGN'); + } + + // The browser's Back is «â†� Library». + await t.evaluate(`history.back()`); + await sleep(1500); + await shot('web-6-back.png'); + check(await t.evaluate(`history.state === null || !history.state.cpGame`), 'Back left the game for the library'); + + // A move on the board of a new game (Ctrl+N; N in a browser): e2–e4 by two clicks. + await t.key('n'); + await sleep(1200); + await t.click(...E2); + await sleep(300); + await t.click(...E4); + await sleep(1000); + await shot('web-8-e4.png'); + + // An unsaved game: the browser asks before the page is left, and its draft is kept. + check(await t.evaluate(`typeof window.onbeforeunload === 'function'`), 'unsaved: the browser asks before leaving'); + await sleep(1500); + const draft = () => t.evaluate(`new Promise((ok) => { + const q = indexedDB.open('chesspenguin'); + q.onsuccess = () => { + const r = q.result.transaction('files').objectStore('files').get('/data/draft.json'); + r.onsuccess = () => ok(r.result ? JSON.parse(new TextDecoder().decode(r.result)).pgn : ''); + }; + q.onerror = () => ok(''); + })`); + check(/1\. e4/.test(await draft()), 'the draft of the unsaved game is kept'); + + // The settings and the shelf after a reload (the browser's storage). The question on + // leaving is answered «Leave». + await t.evaluate(`(window.onbeforeunload = null, true)`); + await t.navigate(`${s.base}?lang=en`); + await started(); + await sleep(2500); + await shot('web-9-reloaded.png'); + check(/1\. e4/.test(await draft()), 'the draft is there after the reload (offered over the library)'); + if (await t.evaluate(`typeof window.showOpenFilePicker === 'function'`)) { + // Chrome, Edge: the file chosen before the reload is read again by itself. + check(s.logs.some((l) => /remembered file read again: .*Test games\.pgn/.test(l)), 'the chosen file is remembered (File System Access)'); + // When the browser asks first (its permission not kept): the card offers «Allow + // reading», the browser's question is answered «Allow», the file is read. + await t.beforeLoad(`FileSystemHandle.prototype.queryPermission = async () => 'prompt'; + FileSystemHandle.prototype.requestPermission = async () => 'granted';`); + await t.navigate(`${s.base}?lang=en`); + await started(); + await sleep(2500); + await t.click(...TEST_CARD); + await sleep(1500); + await shot('web-10-allow.png'); + await t.click(...ALLOW); + await sleep(2500); + await shot('web-11-allowed.png'); + check(s.logs.some((l) => /remembered file allowed again: .*Test games\.pgn/.test(l)), '«Allow reading» reads the remembered file again'); + } +} finally { + await s.stop(); +} +for (const e of s.errors) console.log('console:', e); +check(s.errors.length === 0, 'no panic or error in the console'); +console.log(failures ? `${failures} failed` : 'all ok'); +process.exit(failures ? 1 : 0); diff --git a/apps/web/check/bidi.mjs b/apps/web/check/bidi.mjs new file mode 100644 index 0000000..c73a929 --- /dev/null +++ b/apps/web/check/bidi.mjs @@ -0,0 +1,78 @@ +// A minimal WebDriver BiDi client for headless Firefox (Node 22+: global WebSocket). +// Used by the web checks (docs/dev/web.md, «Проверки»); no windows are opened. + +export async function connect(port) { + const ws = new WebSocket(`ws://127.0.0.1:${port}/session`); + let id = 0; + const pending = new Map(); + const listeners = []; + ws.onmessage = (m) => { + const d = JSON.parse(m.data); + if (d.id && pending.has(d.id)) { + const p = pending.get(d.id); + pending.delete(d.id); + if (d.type === 'error') p.rej(new Error(`${d.error}: ${d.message}`)); + else p.res(d.result); + } else if (d.method) { + for (const l of listeners) l(d.method, d.params); + } + }; + await new Promise((res, rej) => { + ws.onopen = res; + ws.onerror = () => rej(new Error('cannot connect to Firefox')); + }); + const send = (method, params) => + new Promise((res, rej) => { + const i = ++id; + pending.set(i, { res, rej }); + ws.send(JSON.stringify({ id: i, method, params })); + }); + await send('session.new', { capabilities: {} }); + return { + send, + on: (f) => listeners.push(f), + close: async () => { + await send('session.end', {}).catch(() => {}); + ws.close(); + }, + }; +} + +export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// A tab of `width`×`height` CSS pixels with the console forwarded to `log`. +export async function tab(b, width, height, log = console.log) { + await b.send('session.subscribe', { events: ['log.entryAdded'] }); + b.on((method, p) => { + if (method === 'log.entryAdded') log(`[${p.level}] ${p.text}`); + }); + const { context } = await b.send('browsingContext.create', { type: 'tab' }); + await b.send('browsingContext.setViewport', { context, viewport: { width, height } }); + const evaluate = async (expression) => { + const r = await b.send('script.evaluate', { + expression, + target: { context }, + awaitPromise: true, + }); + if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed'); + return r.result?.value; + }; + return { + context, + evaluate, + navigate: (url) => b.send('browsingContext.navigate', { context, url, wait: 'complete' }), + screenshot: async () => + Buffer.from((await b.send('browsingContext.captureScreenshot', { context })).data, 'base64'), + actions: (actions) => b.send('input.performActions', { context, actions }), + // Waits until `expression` is truthy (polled), or throws after `ms`. + waitFor: async (expression, ms = 10000) => { + const end = Date.now() + ms; + for (;;) { + const v = await evaluate(expression).catch(() => undefined); + if (v) return v; + if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`); + await sleep(100); + } + }, + }; +} diff --git a/apps/web/check/browser.mjs b/apps/web/check/browser.mjs new file mode 100644 index 0000000..45ae52a --- /dev/null +++ b/apps/web/check/browser.mjs @@ -0,0 +1,296 @@ +// One way to drive a headless browser for the web checks: Firefox over WebDriver BiDi +// (firefox.mjs, bidi.mjs) or Chromium / Chrome for Testing over the DevTools protocol. +// The browser: CP_BROWSER=firefox (default) | chromium, the Chromium binary in +// CP_CHROME. No window is ever shown; the browser is stopped by its PID. +// +// const b = await open(port); const t = await b.tab(1400, 860, log); +// t.navigate(url) · t.evaluate(js) · t.waitFor(js, ms) · t.screenshot() +// t.click(x, y, {double, right}) · t.key(key, mods, times) · t.setFiles(inputId, paths) +// t.choose(paths, open): the user chooses the files in the dialog open() brings up +// t.chooseFolder(dir, open): … the folder +// t.beforeLoad(js): js runs in every page loaded later, before its scripts +import { spawn } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, join } from 'node:path'; +import { launch as launchFirefox } from './firefox.mjs'; +import { sleep, tab as bidiTab } from './bidi.mjs'; + +// WebDriver key values (BiDi) and their DevTools descriptions. +const KEYS = { + ctrl: { bidi: '', key: 'Control', code: 'ControlLeft', vk: 17, mod: 2 }, + shift: { bidi: '', key: 'Shift', code: 'ShiftLeft', vk: 16, mod: 8 }, + alt: { bidi: '', key: 'Alt', code: 'AltLeft', vk: 18, mod: 1 }, + esc: { bidi: '', key: 'Escape', code: 'Escape', vk: 27 }, + enter: { bidi: '', key: 'Enter', code: 'Enter', vk: 13, text: '\r' }, + right: { bidi: '', key: 'ArrowRight', code: 'ArrowRight', vk: 39 }, + left: { bidi: '', key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 }, +}; + +function keyOf(k) { + if (KEYS[k]) return KEYS[k]; + if (k === ',') return { bidi: ',', key: ',', code: 'Comma', vk: 188, text: ',' }; + if (/^[0-9]$/.test(k)) return { bidi: k, key: k, code: `Digit${k}`, vk: 48 + Number(k), text: k }; + return { bidi: k, key: k, code: `Key${k.toUpperCase()}`, vk: k.toUpperCase().charCodeAt(0), text: k }; +} + +const waitFor = (evaluate) => async (expression, ms = 10000) => { + const end = Date.now() + ms; + for (;;) { + const v = await evaluate(expression).catch(() => undefined); + if (v) return v; + if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`); + await sleep(100); + } +}; + +// ----- Firefox -------------------------------------------------------------------------- + +async function firefox(port) { + const ff = await launchFirefox(port); + return { + name: 'firefox', + profile: ff.profile, + downloads: ff.downloads, + stop: ff.stop, + tab: async (width, height, log) => { + const t = await bidiTab(ff.browser, width, height, log); + const evaluate = async (expression) => { + const r = await ff.browser.send('script.evaluate', { + expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, + target: { context: t.context }, + awaitPromise: true, + }); + if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed'); + return JSON.parse(r.result.value); + }; + return { + evaluate, + waitFor: waitFor(evaluate), + navigate: t.navigate, + screenshot: t.screenshot, + // `js` runs in every page loaded from now on, before the page's own scripts. + beforeLoad: (js) => ff.browser.send('script.addPreloadScript', { functionDeclaration: `() => { ${js} }`, contexts: [t.context] }), + click: async (x, y, { double = false, right = false } = {}) => { + const acts = [{ type: 'pointerMove', x, y }]; + for (let i = 0; i < (double ? 2 : 1); i++) { + acts.push({ type: 'pointerDown', button: right ? 2 : 0 }, { type: 'pointerUp', button: right ? 2 : 0 }); + } + await t.actions([{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]); + }, + key: async (key, mods = [], times = 1) => { + const m = mods.map((x) => KEYS[x].bidi); + const v = keyOf(key).bidi; + const acts = [...m.map((value) => ({ type: 'keyDown', value })), { type: 'keyDown', value: v }, { type: 'keyUp', value: v }, ...[...m].reverse().map((value) => ({ type: 'keyUp', value }))]; + for (let i = 0; i < times; i++) await t.actions([{ type: 'key', id: 'kb', actions: acts }]); + }, + setFiles: async (id, files) => { + const node = await ff.browser.send('script.evaluate', { + expression: `document.getElementById(${JSON.stringify(id)})`, target: { context: t.context }, awaitPromise: false, + }); + await ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: node.result.sharedId }, files }); + }, + // The user chooses `files` in the dialog `open()` brings up (the page's file input). + async choose(files, open) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); + await this.setFiles('cp-open-files', files); + }, + // The user chooses the folder `dir` (the page's folder input, webkitdirectory). + // WebDriver gives such an input no folder in Firefox ("Is directory"): the + // folder's own files are given, as the browser would give them. + async chooseFolder(dir, open) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000); + const files = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => join(dir, e.name)); + await this.setFiles('cp-open-folder', files); + }, + }; + }, + }; +} + +// ----- Chromium (DevTools protocol) ----------------------------------------------------------- + +async function chromium(port) { + const binary = process.env.CP_CHROME; + if (!binary) throw new Error('CP_CHROME: the Chromium / Chrome for Testing binary'); + const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-chrome-')); + const downloads = join(profile, 'downloads'); + mkdirSync(downloads, { recursive: true }); + const proc = spawn(binary, [ + '--headless=new', `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, + '--no-first-run', '--no-default-browser-check', '--disable-gpu-sandbox', '--use-angle=swiftshader', + '--enable-unsafe-swiftshader', 'about:blank', + ], { stdio: process.env.CP_CHROME_LOG ? 'inherit' : 'ignore' }); + let ws; + for (let i = 0; i < 300 && !ws; i++) { + try { + const v = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json(); + ws = v.webSocketDebuggerUrl; + } catch { + await sleep(100); + } + } + if (!ws) throw new Error('Chromium did not start'); + const sock = new WebSocket(ws); + await new Promise((res) => (sock.onopen = res)); + let id = 0; + const pending = new Map(); + const listeners = []; + sock.onmessage = (m) => { + const d = JSON.parse(m.data); + if (d.id && pending.has(d.id)) { + const p = pending.get(d.id); + pending.delete(d.id); + d.error ? p.rej(new Error(d.error.message)) : p.res(d.result); + } else if (d.method) for (const l of listeners) l(d); + }; + const send = (method, params = {}, sessionId) => + new Promise((res, rej) => { + const i = ++id; + pending.set(i, { res, rej }); + sock.send(JSON.stringify({ id: i, method, params, sessionId })); + }); + await send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }); + return { + name: 'chromium', + profile, + downloads, + send, + on: (f) => listeners.push(f), + stop: async () => { + try { sock.close(); } catch {} + try { process.kill(proc.pid); } catch {} + await sleep(500); + rmSync(profile, { recursive: true, force: true }); + }, + tab: async (width, height, log = console.log) => { + const { targetId } = await send('Target.createTarget', { url: 'about:blank' }); + const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }); + const s = (method, params) => send(method, params, sessionId); + listeners.push((d) => { + if (d.sessionId !== sessionId) return; + if (d.method === 'Runtime.consoleAPICalled') { + log(`[${d.params.type}] ${d.params.args.map((a) => a.value ?? a.description ?? '').join(' ')}`); + } else if (d.method === 'Runtime.exceptionThrown') { + log(`[error] ${d.params.exceptionDetails.exception?.description || d.params.exceptionDetails.text}`); + } else if (d.method === 'Log.entryAdded' && d.params.entry.level === 'error') { + log(`[error] ${d.params.entry.text}`); + } + }); + await s('Page.enable'); + await s('Runtime.enable'); + await s('Log.enable'); + await s('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }); + const evaluate = async (expression) => { + const r = await s('Runtime.evaluate', { expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, awaitPromise: true, returnByValue: true }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text); + return JSON.parse(r.result.value); + }; + let modifiers = 0; + return { + sessionId, + send: s, + evaluate, + waitFor: waitFor(evaluate), + beforeLoad: (js) => s('Page.addScriptToEvaluateOnNewDocument', { source: js }), + navigate: async (url) => { + await s('Page.navigate', { url }); + await waitFor(evaluate)(`document.readyState === 'complete'`, 30000); + }, + screenshot: async () => Buffer.from((await s('Page.captureScreenshot', { format: 'png' })).data, 'base64'), + click: async (x, y, { double = false, right = false } = {}) => { + const button = right ? 'right' : 'left'; + await s('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }); + for (let i = 1; i <= (double ? 2 : 1); i++) { + await s('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button, clickCount: i }); + await s('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button, clickCount: i }); + } + }, + key: async (key, mods = [], times = 1) => { + for (let n = 0; n < times; n++) { + for (const m of mods) { + modifiers |= KEYS[m].mod; + await s('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); + } + const k = keyOf(key); + const text = modifiers & 3 ? undefined : k.text; + await s('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers, text }); + await s('Input.dispatchKeyEvent', { type: 'keyUp', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers }); + for (const m of [...mods].reverse()) { + modifiers &= ~KEYS[m].mod; + await s('Input.dispatchKeyEvent', { type: 'keyUp', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); + } + } + }, + setFiles: async (id, files) => { + const { result } = await s('Runtime.evaluate', { expression: `document.getElementById(${JSON.stringify(id)})` }); + await s('DOM.setFileInputFiles', { objectId: result.objectId, files }); + }, + // The user chooses `files` in the dialog `open()` brings up. Chrome's own dialog + // (showOpenFilePicker, the files remembered) cannot be driven headless: the files + // are put into the site's private file system and its handles are what the + // dialog gives — the same kind of handle, kept and read again the same way. + async choose(files, open) { + const picker = await this.evaluate(`typeof window.showOpenFilePicker === 'function'`); + if (!picker) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); + return this.setFiles('cp-open-files', files); + } + const given = files.map((f) => ({ name: basename(f), b64: readFileSync(f).toString('base64') })); + await this.evaluate(`(() => { + const given = ${JSON.stringify(given)}; + window.showOpenFilePicker = async () => { + const root = await navigator.storage.getDirectory(); + const handles = []; + for (const g of given) { + const h = await root.getFileHandle(g.name, { create: true }); + const w = await h.createWritable(); + await w.write(Uint8Array.from(atob(g.b64), (c) => c.charCodeAt(0))); + await w.close(); + handles.push(h); + } + return handles; + }; + return true; + })()`); + await open(); + }, + // The user chooses the folder `dir`: in Chromium showDirectoryPicker, its files + // put into a folder of the site's private file system (as for choose()). + async chooseFolder(dir, open) { + const picker = await this.evaluate(`typeof window.showDirectoryPicker === 'function'`); + if (!picker) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000); + return this.setFiles('cp-open-folder', [dir]); + } + const given = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()) + .map((e) => ({ name: e.name, b64: readFileSync(join(dir, e.name)).toString('base64') })); + await this.evaluate(`(() => { + const given = ${JSON.stringify(given)}; + window.showDirectoryPicker = async () => { + const root = await navigator.storage.getDirectory(); + const d = await root.getDirectoryHandle(${JSON.stringify(basename(dir))}, { create: true }); + for (const g of given) { + const h = await d.getFileHandle(g.name, { create: true }); + const w = await h.createWritable(); + await w.write(Uint8Array.from(atob(g.b64), (c) => c.charCodeAt(0))); + await w.close(); + } + return d; + }; + return true; + })()`); + await open(); + }, + }; + }, + }; +} + +export async function open(port, kind = process.env.CP_BROWSER || 'firefox') { + return kind === 'chromium' ? chromium(port) : firefox(port); +} diff --git a/apps/web/check/chessbase.mjs b/apps/web/check/chessbase.mjs new file mode 100644 index 0000000..96e925c --- /dev/null +++ b/apps/web/check/chessbase.mjs @@ -0,0 +1,80 @@ +// ChessBase databases in the browser (several files): a .cbh chosen alone asks for its +// folder, the folder's files make the database; all its files chosen at once; one too +// big for a browser is refused politely; Chrome remembers the folder. +// +// node apps/web/check/chessbase.mjs [] +// +// : a small ChessBase database's folder (.cbh, .cbg, …), only that +// database in it. Firefox by default, Chromium with CP_BROWSER=chromium (browser.mjs). +import { readdirSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; + +const [appDir, outDir, baseDir, bigDir] = process.argv.slice(2).map((p) => p && resolve(p)); +let failures = 0; +const check = (ok, what) => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); + if (!ok) failures++; +}; +// «ðŸ“� Choose the database's folder» in the window about a .cbh chosen alone (1400×860). +const ADD = [155, 20]; +const FOLDER = (process.env.FOLDER || '833,471').split(',').map(Number); +const s = await session(appDir, 18768); +const { t } = s; +const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot()); +const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); +const read = (name) => s.logs.filter((l) => l.includes(`database read: ${name}`)); +const cbh = readdirSync(baseDir).find((n) => n.toLowerCase().endsWith('.cbh')); +const stem = cbh.slice(0, -4); +try { + await t.navigate(`${s.base}?lang=${process.env.CP_LANG || "en"}`); + await started(); + await sleep(2500); + + // A .cbh alone: the window asks for the database's folder; nothing is opened yet. + await t.choose([join(baseDir, cbh)], () => t.key('o', ['ctrl'])); + await sleep(2000); + await shot('cb-1-lone.png'); + check(read(stem).length === 0, 'a .cbh alone is not opened'); + // The folder: the database's files are found by their names. + await t.chooseFolder(baseDir, () => t.click(...FOLDER)); + await sleep(4000); + await shot('cb-2-folder.png'); + check(read(stem).length === 1, `the folder makes the database: ${read(stem)[0] || 'not read'}`); + + // All its files chosen at once. + const all = readdirSync(baseDir).map((n) => join(baseDir, n)); + // By the shelf's «+ Add database». + await t.choose(all, () => t.click(...ADD)); + await sleep(4000); + await shot('cb-3-files.png'); + check(read(stem).length === 2, 'all its files chosen at once make the database'); + + if (bigDir) { + // A database over the limit: refused before it is read, with the way to the + // desktop program. + const big = readdirSync(bigDir).find((n) => n.toLowerCase().endsWith('.cbh')); + await t.choose([join(bigDir, big)], () => t.click(...ADD)); + await sleep(2000); + await t.chooseFolder(bigDir, () => t.click(...FOLDER)); + await sleep(3000); + await shot('cb-4-too-big.png'); + check(read(big.slice(0, -4)).length === 0, 'a database over 2 GB is not read'); + } + + // The next visit: Chrome reads the remembered folder's database again by itself. + await t.navigate(`${s.base}?lang=${process.env.CP_LANG || "en"}`); + await started(); + await sleep(3000); + await shot('cb-5-reloaded.png'); + if (await t.evaluate(`typeof window.showDirectoryPicker === 'function'`)) { + check(s.logs.some((l) => l.includes('remembered file read again') && l.includes(cbh)), 'the folder is remembered (File System Access)'); + } +} finally { + await s.stop(); +} +for (const e of s.errors) console.log('console:', e); +check(s.errors.length === 0, 'no panic or error in the console'); +console.log(failures ? `${failures} failed` : 'all ok'); +process.exit(failures ? 1 : 0); diff --git a/apps/web/check/device.test.mjs b/apps/web/check/device.test.mjs new file mode 100644 index 0000000..f41d1bc --- /dev/null +++ b/apps/web/check/device.test.mjs @@ -0,0 +1,49 @@ +// Which devices get the program and which the page about the apps (page/device.js): +// +// node apps/web/check/device.test.mjs +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import vm from 'node:vm'; + +const source = readFileSync(fileURLToPath(new URL('../page/device.js', import.meta.url)), 'utf8'); + +// device.js in a window that looks like `d`. +function classOf(d) { + const media = { '(pointer: coarse)': d.coarse, '(any-pointer: fine)': d.fine }; + const window = { + navigator: { userAgent: d.ua, platform: d.platform || '', maxTouchPoints: d.touch || 0, userAgentData: d.uad }, + screen: { width: d.screen[0], height: d.screen[1] }, + matchMedia: (q) => ({ matches: !!media[q] }), + }; + window.window = window; + vm.runInNewContext(source, window); + return window.CPDevice.deviceClass(); +} + +const MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15'; +const cases = [ + ['Windows laptop', { ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/159.0', screen: [1920, 1080], fine: true }, 'computer'], + ['Mac', { ua: MAC, platform: 'MacIntel', screen: [1512, 982], fine: true }, 'computer'], + ['laptop with a touch screen', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [1366, 768], touch: 10, coarse: false, fine: true }, 'computer'], + ['Chromebook', { ua: 'Mozilla/5.0 (X11; CrOS x86_64 15000.0.0) Chrome/140.0', screen: [1366, 768], touch: 5, coarse: true }, 'computer'], + ['iPhone', { ua: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Mobile/15E148', screen: [390, 844], touch: 5, coarse: true }, 'iphone'], + ['iPhone asking for the desktop site', { ua: MAC, platform: 'MacIntel', screen: [390, 844], touch: 5, coarse: true }, 'iphone'], + ['iPad (says it is a Mac)', { ua: MAC, platform: 'MacIntel', screen: [820, 1180], touch: 5, coarse: true }, 'ipad'], + ['iPad mini', { ua: MAC, platform: 'MacIntel', screen: [744, 1133], touch: 5, coarse: true }, 'ipad'], + ['Android phone', { ua: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) Chrome/140.0 Mobile', screen: [412, 915], touch: 5, coarse: true }, 'android-phone'], + ['Android tablet', { ua: 'Mozilla/5.0 (Linux; Android 14; SM-X710) Chrome/140.0', screen: [800, 1280], touch: 10, coarse: true }, 'android-tablet'], + ['Galaxy Fold folded', { ua: 'Mozilla/5.0 (Linux; Android 14; SM-F946B) Chrome/140.0 Mobile', screen: [344, 882], touch: 5, coarse: true }, 'android-phone'], + ['tablet asking for the desktop site', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [800, 1280], touch: 10, coarse: true, fine: false }, 'tablet'], + ['phone asking for the desktop site', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [412, 915], touch: 5, coarse: true, fine: false }, 'phone'], + ['a mobile Chromium by its client hints', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', uad: { mobile: true, platform: 'Linux' }, screen: [412, 915], touch: 5, coarse: true }, 'phone'], +]; + +let failed = 0; +for (const [name, device, want] of cases) { + const got = classOf(device); + const ok = got === want; + if (!ok) failed++; + console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${got}${ok ? '' : ` (want ${want})`}`); +} +console.log(failed ? `${failed} of ${cases.length} failed` : `all ${cases.length} ok`); +process.exit(failed ? 1 : 0); diff --git a/apps/web/check/firefox.mjs b/apps/web/check/firefox.mjs new file mode 100644 index 0000000..088ec12 --- /dev/null +++ b/apps/web/check/firefox.mjs @@ -0,0 +1,51 @@ +// Starts a headless Firefox with a temporary profile and WebDriver BiDi; stops it by +// its PID. No window is ever shown (MOZ_HEADLESS). +import { spawn } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { connect, sleep } from './bidi.mjs'; + +export async function launch(port = 19222) { + const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-firefox-')); + writeFileSync( + join(profile, 'user.js'), + [ + 'user_pref("remote.active-protocols", 1);', + 'user_pref("browser.shell.checkDefaultBrowser", false);', + 'user_pref("datareporting.policy.dataSubmissionEnabled", false);', + 'user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);', + // Downloads go to the profile without asking. + 'user_pref("browser.download.folderList", 2);', + `user_pref("browser.download.dir", "${join(profile, 'downloads')}");`, + 'user_pref("browser.download.useDownloadDir", true);', + 'user_pref("browser.download.always_ask_before_handling_new_types", false);', + '', + ].join('\n'), + ); + const log = join(profile, 'firefox.log'); + const out = (await import('node:fs')).openSync(log, 'a'); + const ff = spawn( + 'firefox', + ['--headless', '--no-remote', '--profile', profile, '--remote-debugging-port', String(port), 'about:blank'], + { env: { ...process.env, MOZ_HEADLESS: '1' }, stdio: ['ignore', out, out] }, + ); + for (let i = 0; i < 100; i++) { + if (readFileSync(log, 'utf8').includes('WebDriver BiDi listening')) break; + await sleep(100); + } + const browser = await connect(port); + return { + browser, + profile, + downloads: join(profile, 'downloads'), + stop: async () => { + await browser.close().catch(() => {}); + try { + process.kill(ff.pid); + } catch {} + await sleep(300); + rmSync(profile, { recursive: true, force: true }); + }, + }; +} diff --git a/apps/web/check/review.mjs b/apps/web/check/review.mjs new file mode 100644 index 0000000..c6e8892 --- /dev/null +++ b/apps/web/check/review.mjs @@ -0,0 +1,95 @@ +// The game review of the web version against the desktop program's, on games of the +// chess.com check set (crates/game-review/chesscom/): the browser reviews them (Stockfish +// 19 wasm in workers), its evaluations are read out of its storage and compared with the +// ones `chesscom_check` keeps (target/chesscom-check/v1): the same search must give the +// same evaluations, so the same !!/!. +// +// node apps/web/check/review.mjs ... +import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { basename, join } from 'node:path'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; + +const [appDir, outDir, nativeDir, ...games] = process.argv.slice(2); +mkdirSync(outDir, { recursive: true }); +const all = join(outDir, 'chesscom-games.pgn'); +writeFileSync(all, games.map((g) => readFileSync(g, 'utf8').trim()).join('\n\n') + '\n'); + +const s = await session(appDir); +const { t } = s; +const stored = `new Promise((ok, no) => { + const q = indexedDB.open('chesspenguin'); + q.onerror = () => no('no db'); + q.onsuccess = () => { + const st = q.result.transaction('files').objectStore('files'); + const keys = st.getAllKeys(), values = st.getAll(); + values.onsuccess = () => ok(keys.result.map((k, i) => [k, new TextDecoder().decode(values.result[i])]) + .filter(([k]) => k.startsWith('/cache/analysis/'))); + }; +}).then((r) => JSON.stringify(r))`; +const readStored = async () => JSON.parse(await t.evaluate(stored)); +let failed = 0; +try { + await s.run({ url: '?lang=en' }, outDir); + await sleep(2000); + // The games in one file, reviewed one by one. + await t.choose([all], () => s.run({ key: 'o', mods: ['ctrl'] }, outDir)); + await sleep(3000); + await s.run({ shot: 'review-0-opened.png' }, outDir); + for (let i = 0; i < games.length; i++) { + const before = (await readStored()).length; + await s.run({ click: [300, 214 + 27 * i], double: true }, outDir); + await sleep(1500); + await s.run({ key: 'a', mods: ['shift'] }, outDir); + // The first time the engine is offered: downloaded, the review starts by itself. + if (i === 0) { + await sleep(1000); + await s.run({ shot: 'review-0-offer.png' }, outDir); + await s.run({ key: 'enter' }, outDir); + await sleep(5000); + await s.run({ shot: 'review-0-downloading.png' }, outDir); + } + const t0 = Date.now(); + for (;;) { + await sleep(2000); + if ((await readStored()).length > before) break; + if (Date.now() - t0 > 600000) throw new Error(`no review of ${games[i]}`); + } + console.log(`${basename(games[i])}: reviewed in ${((Date.now() - t0) / 1000).toFixed(0)} s`); + await s.run({ shot: `review-${i + 1}.png` }, outDir); + await s.run({ click: [55, 15] }, outDir); + await sleep(1000); + } + // The comparison. + const fromBrowser = await readStored(); + for (const [key, text] of fromBrowser) { + const name = basename(key); + writeFileSync(join(outDir, name), text); + const web = JSON.parse(text); + const nativePath = join(nativeDir, name); + if (!existsSync(nativePath)) { + console.log(`FAIL ${name}: no native evaluations to compare with`); + failed++; + continue; + } + const native = new Map(JSON.parse(readFileSync(nativePath, 'utf8')).evals); + let same = 0, differ = 0, missing = 0; + for (const [k, e] of web.evals) { + const n = native.get(k); + if (!n) { missing++; continue; } + if (JSON.stringify(n) === JSON.stringify(e)) same++; + else { + differ++; + if (differ <= 3) console.log(' differs', k.slice(-40), JSON.stringify(n).slice(0, 160), '|', JSON.stringify(e).slice(0, 160)); + } + } + const ok = differ === 0 && missing === 0 && same > 0; + if (!ok) failed++; + console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${same} positions the same${differ ? `, ${differ} differ` : ''}${missing ? `, ${missing} not in the native set` : ''} (engine ${web.meta.engine}, ${web.meta.nodes} nodes)`); + } +} finally { + await s.stop(); +} +for (const e of s.errors) console.log('console:', e); +console.log(failed ? `${failed} failed` : 'all the same'); +process.exit(failed ? 1 : 0); diff --git a/apps/web/check/serve.py b/apps/web/check/serve.py new file mode 100644 index 0000000..122b287 --- /dev/null +++ b/apps/web/check/serve.py @@ -0,0 +1,37 @@ +"""The site's layout for the web version, locally: the built program at /app/ and the +site's static files at /static/ (screenshots of the device page). Only for checks: +the site itself serves /app/ when the web version is published (docs/dev/web.md). + + python3 -I apps/web/check/serve.py [port] +""" + +import functools +import http.server +import pathlib +import sys + +APP, STATIC = pathlib.Path(sys.argv[1]).resolve(), pathlib.Path(sys.argv[2]).resolve() +PORT = int(sys.argv[3]) if len(sys.argv) > 3 else 18765 + + +class Handler(http.server.SimpleHTTPRequestHandler): + extensions_map = { + **http.server.SimpleHTTPRequestHandler.extensions_map, + ".wasm": "application/wasm", + ".js": "text/javascript", + } + + def translate_path(self, path): + path = path.split("?", 1)[0].split("#", 1)[0] + for prefix, base in (("/app/", APP), ("/static/", STATIC), ("/screenshots/", STATIC / "screenshots")): + if path.startswith(prefix): + target = (base / path[len(prefix):]).resolve() + if target == base or base in target.parents: + return str(target / "index.html" if target.is_dir() else target) + return str(APP / "__missing__") + + def log_message(self, *args): + pass + + +http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/apps/web/check/stage2.mjs b/apps/web/check/stage2.mjs new file mode 100644 index 0000000..ab3588e --- /dev/null +++ b/apps/web/check/stage2.mjs @@ -0,0 +1,83 @@ +// «My games», the data in the browser and the files of a visit in headless Firefox: +// Ctrl+S puts a game of the samples into «My games» (kept in IndexedDB), a file kept as +// a copy opens after a reload, a file only opened asks to be chosen again. +// +// node apps/web/check/stage2.mjs +// (KEEP_X, KEEP_Y: where «Keep a copy in the browser» is, for a 1400×860 window) +import { copyFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; + +const [appDir, outDir] = process.argv.slice(2); +mkdirSync(outDir, { recursive: true }); +const root = fileURLToPath(new URL('../../..', import.meta.url)); +let failures = 0; +const check = (ok, what) => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); + if (!ok) failures++; +}; + +const s = await session(appDir, 18810); +const { t } = s; +const kept = `new Promise((ok) => { + const q = indexedDB.open('chesspenguin'); + q.onsuccess = () => { + const st = q.result.transaction('files').objectStore('files'); + const keys = st.getAllKeys(), values = st.getAll(); + values.onsuccess = () => ok(JSON.stringify(keys.result.map((k, i) => [k, new TextDecoder().decode(values.result[i]).slice(0, 2000)]))); + }; +})`; +const files = async () => new Map(JSON.parse(await t.evaluate(kept))); +const step = (x) => s.run(x, outDir); +try { + await step({ url: '?lang=en' }); + await sleep(2500); + await step({ shot: 's2-1-library.png' }); + // A game of the samples into «My games». + await step({ click: [300, 322], double: true }); + await sleep(1500); + await step({ key: 's', mods: ['ctrl'] }); + await sleep(3000); + await step({ shot: 's2-2-saved.png' }); + let f = await files(); + const mine = [...f.keys()].find((k) => k.startsWith('/data/my-games/')); + check(!!mine && /Anderssen/.test(f.get(mine)), `the game is in «My games» in the browser's storage (${mine})`); + await step({ click: [55, 15] }); + await sleep(1500); + await step({ shot: 's2-3-my-games.png' }); + await step({ key: ',', mods: ['ctrl'] }); + await sleep(1000); + await step({ shot: 's2-4-settings.png' }); + await step({ click: [1366, 77] }); + // Two files opened; one kept as a copy. + const a = join(s.b.profile, 'Kept games.pgn'); + const b = join(s.b.profile, 'Visit games.pgn'); + copyFileSync(join(root, 'examples/alekhine.pgn'), a); + copyFileSync(join(root, 'examples/classics.pgn'), b); + for (const file of [b, a]) { + await t.choose([file], () => step({ key: 'o', mods: ['ctrl'] })); + await sleep(2500); + } + await step({ shot: 's2-5-opened.png' }); + if (process.env.KEEP_X) { + await step({ click: [Number(process.env.KEEP_X), Number(process.env.KEEP_Y)] }); + await sleep(2000); + await step({ shot: 's2-6-kept.png' }); + f = await files(); + check([...f.keys()].some((k) => /^\/data\/copies\/[0-9]+\/Kept games\.pgn$/.test(k)), 'a copy of the file is kept in the browser'); + } + // After a reload: «My games» and the copy are there, the other file is to be chosen again. + await step({ url: '?lang=en' }); + await sleep(3000); + await step({ shot: 's2-7-reloaded.png' }); + f = await files(); + check(!!mine && /Anderssen/.test(f.get(mine) || ''), '«My games» after a reload'); +} finally { + await s.stop(); +} +for (const e of s.errors) console.log('console:', e); +check(s.errors.length === 0, 'no panic or error in the console'); +console.log(failures ? `${failures} failed` : 'all ok'); +process.exit(failures ? 1 : 0); diff --git a/apps/web/check/steps.mjs b/apps/web/check/steps.mjs new file mode 100644 index 0000000..559cbbf --- /dev/null +++ b/apps/web/check/steps.mjs @@ -0,0 +1,64 @@ +// A session of the web version in a headless browser (browser.mjs: Firefox, or +// Chromium with CP_BROWSER=chromium) over the site's layout (serve.py), and a runner of +// step lists — for finding the places of buttons, and for the scenario checks. +// +// node apps/web/check/steps.mjs +// +// A step: {"url": "?lang=en"} | {"wait": ms} | {"click": [x, y], "double": true} +// | {"key": "l", "mods": ["ctrl"], "times": 3} | {"shot": "name.png"} | {"eval": "js"} +// | {"until": "js expression", "ms": 60000} +import { spawn } from 'node:child_process'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { open } from './browser.mjs'; +import { sleep } from './bidi.mjs'; + +export async function session(appDir, port = Number(process.env.CP_CHECK_PORT || 18767)) { + const root = fileURLToPath(new URL('../../..', import.meta.url)); + const server = spawn('python3', ['-I', join(root, 'apps/web/check/serve.py'), resolve(appDir), join(root, 'website/static'), String(port)], { stdio: 'ignore' }); + const b = await open(port + 457); + const errors = []; + const logs = []; + const t = await b.tab(1400, 860, (line) => { + logs.push(line); + if (/panicked|RuntimeError|\[error\]/.test(line) && !/favicon|404/.test(line)) errors.push(line); + if (process.env.CONSOLE) console.log(line); + }); + const base = `http://127.0.0.1:${port}/app/`; + const run = async (step, outDir) => { + if (step.url !== undefined) { + await t.navigate(base + step.url); + await t.waitFor(`document.getElementById('cp-status').hidden || !document.getElementById('cp-device').hidden`, 30000); + } + if (step.wait) await sleep(step.wait); + if (step.click) { + await t.click(step.click[0], step.click[1], step); + await sleep(300); + } + if (step.key) { + await t.key(step.key, step.mods || [], step.times || 1); + await sleep(300); + } + if (step.eval) console.log('eval:', JSON.stringify(await t.evaluate(step.eval)).slice(0, 2000)); + if (step.until) await t.waitFor(step.until, step.ms || 60000); + if (step.shot) writeFileSync(join(outDir, step.shot), await t.screenshot()); + }; + return { + t, b, base, errors, logs, run, + stop: async () => { await b.stop(); server.kill(); }, + }; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const [appDir, outDir, stepsFile] = process.argv.slice(2); + mkdirSync(outDir, { recursive: true }); + const steps = JSON.parse(readFileSync(stepsFile, 'utf8')); + const s = await session(appDir); + try { + for (const step of steps) await s.run(step, outDir); + } finally { + await s.stop(); + } + for (const e of s.errors) console.log('console:', e); +} diff --git a/apps/web/check/uci-worker.mjs b/apps/web/check/uci-worker.mjs new file mode 100644 index 0000000..6288a65 --- /dev/null +++ b/apps/web/check/uci-worker.mjs @@ -0,0 +1,60 @@ +// The tests of uci's worker transport (crates/uci/tests/worker.rs) in headless +// Firefox. wasm-bindgen-test-runner serves them (NO_HEADLESS: it does not look for a +// WebDriver) and this script opens its page and reads the outcome. +// +// node apps/web/check/uci-worker.mjs +// +// Needs wasm-bindgen-test-runner of the wasm-bindgen version in Cargo.lock in PATH +// or in WASM_BINDGEN_TEST_RUNNER. +import { spawn } from 'node:child_process'; +import { launch } from './firefox.mjs'; +import { sleep, tab } from './bidi.mjs'; + +const runner = process.env.WASM_BINDGEN_TEST_RUNNER || 'wasm-bindgen-test-runner'; +const address = '127.0.0.1:18731'; +const cargo = spawn( + 'cargo', + ['test', '-p', 'uci', '--target', 'wasm32-unknown-unknown', '--test', 'worker'], + { + env: { + ...process.env, + CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: runner, + NO_HEADLESS: '1', + WASM_BINDGEN_TEST_ADDRESS: address, + }, + stdio: ['ignore', 'pipe', 'inherit'], + // Its own process group: the runner it starts is stopped with it. + detached: true, + }, +); +const stopCargo = () => { + try { + process.kill(-cargo.pid); + } catch {} +}; +let served = false; +cargo.stdout.on('data', (d) => { + if (String(d).includes(address)) served = true; +}); +for (let i = 0; i < 1200 && !served; i++) await sleep(100); +if (!served) { + console.error('the test runner did not start'); + stopCargo(); + process.exit(1); +} +const ff = await launch(); +let failed = true; +try { + const t = await tab(ff.browser, 1000, 800, () => {}); + await t.navigate(`http://${address}/`); + const text = await t.waitFor( + `(() => { const t = document.body.innerText; return /test result: /.test(t) && t; })()`, + 60000, + ); + console.log(text.trim()); + failed = !/test result: ok\./.test(text); +} finally { + await ff.stop(); + stopCargo(); +} +process.exit(failed ? 1 : 0); diff --git a/apps/web/page/device.js b/apps/web/page/device.js new file mode 100644 index 0000000..a8ccbb3 --- /dev/null +++ b/apps/web/page/device.js @@ -0,0 +1,43 @@ +// What device opened the page (docs/design/web-version.md §3.6.1; decisions «Веб-верÑ�иÑ�»: +// the web application is for computers only, phones and tablets get the app page). +// Decided by the page itself before anything large is loaded: a server cannot tell an +// iPad (it says "Macintosh") nor see the size of the screen. +// +// One function for the site and /app/, so that they never disagree whom to send where +// (the site takes this file over when the web version is published). +(function (global) { + "use strict"; + + // "computer" | "iphone" | "ipad" | "android-phone" | "android-tablet" | "phone" | "tablet" + function deviceClass() { + var ua = navigator.userAgent || ""; + var uad = navigator.userAgentData; + var plat = (uad && uad.platform) || navigator.platform || ""; + var touch = navigator.maxTouchPoints > 0; + // CSS pixels of the whole screen, not of the window: a narrow window of a computer + // stays a computer; min() removes the orientation. + var short = Math.min(screen.width, screen.height); + var coarse = matchMedia("(pointer: coarse)").matches; + var finePresent = matchMedia("(any-pointer: fine)").matches; + + // iPadOS (and an iPhone asking for the desktop site) says "Mac"; a Mac has no touch. + var ios = /iPhone|iPod|iPad/.test(ua) || (/Mac/.test(plat) && navigator.maxTouchPoints > 1); + if (ios) return short < 600 ? "iphone" : "ipad"; + if (/Android/i.test(ua)) return short < 600 ? "android-phone" : "android-tablet"; + if (uad && uad.mobile) return short < 600 ? "phone" : "tablet"; + if (/CrOS/.test(ua)) return "computer"; + // A phone or tablet asking for the desktop site (Chrome on large tablets does by + // default): a touch screen and no fine pointer. A laptop with a touch screen has its + // touchpad, so it stays a computer. + if (touch && coarse && !finePresent) return short < 600 ? "phone" : "tablet"; + return "computer"; + } + + // The Android version of an Android device (0: not said). + function androidVersion() { + var m = /Android (\d+)/.exec(navigator.userAgent || ""); + return m ? Number(m[1]) : 0; + } + + global.CPDevice = { deviceClass: deviceClass, androidVersion: androidVersion }; +})(window); diff --git a/apps/web/page/import-worker.js b/apps/web/page/import-worker.js new file mode 100644 index 0000000..49365f9 --- /dev/null +++ b/apps/web/page/import-worker.js @@ -0,0 +1,29 @@ +// The page's reader: a second instance of the program that reads the databases the user +// opens, so that the page does not stop while a large one is read +// (apps/desktop/src/platform/web/import.rs). One database at a time, in order: its files +// one by one (the user's are the browser's File objects, read here), then the reading. +import init, { reader_give, reader_read } from './chesspenguin_web.js'; + +const ready = init(); + +self.onmessage = async (e) => { + await ready; + const { id, names, parts, count } = e.data; + let answer; + try { + for (let i = 0; i < names.length; i++) { + const part = parts[i]; + const bytes = part instanceof Blob ? new Uint8Array(await part.arrayBuffer()) : part; + parts[i] = null; + reader_give(names[i], bytes); + } + answer = reader_read(count); + } catch (err) { + // The program stopped (out of memory, most likely): this instance is spent. + self.postMessage({ id, crashed: String(err) }); + self.close(); + return; + } + answer.id = id; + self.postMessage(answer, answer.text ? [answer.text.buffer] : []); +}; diff --git a/apps/web/page/index.html b/apps/web/page/index.html new file mode 100644 index 0000000..2d20d55 --- /dev/null +++ b/apps/web/page/index.html @@ -0,0 +1,58 @@ + + + + + +ChessPenguin + + + + + + + + + +
+ + + + + + diff --git a/apps/web/page/page.js b/apps/web/page/page.js new file mode 100644 index 0000000..142f0c3 --- /dev/null +++ b/apps/web/page/page.js @@ -0,0 +1,211 @@ +// The page /app/: a computer gets ChessPenguin (the WebAssembly program, loaded only +// then); a phone or a tablet gets the page about the apps (docs/design/web-version.md +// §3.6, decisions «Веб-верÑ�иÑ�»), with a quiet way to open the web version anyway. +// +// ?phone=1 the device page on any device (checks, screenshots of the site); +// ?phone=android, ?phone=ios: that variant of it +// ?phone=0 the program on any device +// ?lang=xx the language (also of the program) +(function () { + "use strict"; + + var LANGS = [ + ["en", "English"], ["ru", "РуÑ�Ñ�кий"], ["fr", "Français"], ["de", "Deutsch"], ["es", "Español"], + ["it", "Italiano"], ["pt", "Português"], ["uz", "OÊ»zbekcha"], ["kk", "Қазақша"], + ]; + // The engine the web version downloads for analysis (Stockfish 19, brotli). + var ENGINE_MB = 78; + var ANYWAY_KEY = "cp.web.phoneAnyway"; + var SITE = "https://chess.vrubel.xyz"; + + var params = new URLSearchParams(location.search); + var texts = window.CP_TEXTS || {}; + + function pickLang() { + var asked = (params.get("lang") || "").toLowerCase(); + if (texts[asked]) return asked; + var prefs = navigator.languages || [navigator.language || ""]; + for (var i = 0; i < prefs.length; i++) { + var code = String(prefs[i]).split(/[-_]/)[0].toLowerCase(); + if (texts[code]) return code; + } + return "en"; + } + var lang = pickLang(); + + function t(key, vars) { + var s = (texts[lang] && texts[lang][key]) || (texts.en && texts.en[key]) || key; + for (var k in vars || {}) s = s.split("{" + k + "}").join(vars[k]); + return s; + } + + function el(tag, attrs, children) { + var e = document.createElement(tag); + for (var a in attrs || {}) { + if (a === "text") e.textContent = attrs[a]; + else if (a === "onclick") e.addEventListener("click", attrs[a]); + else e.setAttribute(a, attrs[a]); + } + (children || []).forEach(function (c) { if (c) e.appendChild(c); }); + return e; + } + + function storage(get, value) { + try { + if (get) return localStorage.getItem(ANYWAY_KEY); + if (value === null) localStorage.removeItem(ANYWAY_KEY); + else localStorage.setItem(ANYWAY_KEY, value); + } catch (e) {} + return null; + } + + // ----- the program -------------------------------------------------------------- + + function startApp() { + document.documentElement.lang = lang; + document.title = t("app_title"); + document.getElementById("cp-device").hidden = true; + var status = document.getElementById("cp-status"); + status.textContent = t("app_loading"); + status.hidden = false; + var failed = function (e) { + console.error("ChessPenguin did not start:", e); + document.getElementById("cp-app").hidden = true; + status.textContent = t("app_failed"); + status.className = "failed"; + status.hidden = false; + }; + import("./chesspenguin_web.js") + .then(function (m) { return m.default().then(function () { return m; }); }) + .then(function (m) { + document.getElementById("cp-app").hidden = false; + return m.start("cp-canvas"); + }) + .then(function () { + status.hidden = true; + document.getElementById("cp-canvas").focus(); + }) + .catch(failed); + } + + // ----- the page for phones and tablets --------------------------------------------- + + function shots(names) { + return el("div", { class: "shots" }, names.map(function (n) { + return el("img", { src: "/screenshots/" + n, alt: "", loading: "lazy" }); + })); + } + + function shareButton() { + var url = SITE + "/app/?lang=" + lang; + var label = navigator.share ? t("app_send_link") : t("copy_link"); + var b = el("button", { class: "btn", type: "button", text: "⇪ " + label }); + b.addEventListener("click", function () { + if (navigator.share) { + navigator.share({ title: "ChessPenguin", url: url }).catch(function () {}); + } else if (navigator.clipboard) { + navigator.clipboard.writeText(url).then(function () { b.textContent = t("link_copied"); }); + } + }); + return b; + } + + function anyway() { + var size = ENGINE_MB + (lang === "ru" || lang === "kk" ? " МБ" : " MB"); + return el("div", null, [ + el("hr"), + el("button", { + class: "anyway", type: "button", text: t("app_open_anyway"), + onclick: function () { storage(false, "1"); startApp(); }, + }), + el("p", { class: "weak", text: t("app_open_anyway_note", { size: size }) }), + ]); + } + + function androidPart() { + var v = CPDevice.androidVersion(); + if (v && v < 12) { + return [el("p", { text: t("app_and_old", { version: String(v) }) }), shareButton()]; + } + var hint = el("p", { class: "weak", text: t("next_android"), hidden: "" }); + var show = function () { hint.hidden = false; }; + return [ + el("a", { class: "btn", href: "/download/android-noengine", rel: "nofollow", onclick: show }, [ + document.createTextNode(t("btn_android")), + el("small", { text: t("and_light_title") }), + ]), + el("p", null, [ + el("a", { class: "link", href: "/download/android", rel: "nofollow", onclick: show, text: t("and_full_title") + " ›" }), + ]), + el("p", { class: "weak", text: t("and_requires") }), + hint, + shots(["phone/01-home-360.webp", "phone/03-game-360.webp", "phone/04-engine-360.webp", "phone/08-review-360.webp"]), + el("p", null, [el("a", { class: "link", href: "/" + (lang === "en" ? "" : lang + "/") + "#download-android", text: t("app_and_more") + " ›" })]), + ]; + } + + function iosPart() { + return [ + el("p", { class: "lead", text: t("app_ios_lead") }), + el("p", { text: t("app_ios_now") }), + shareButton(), + el("p", { style: "margin-top:16px", text: t("app_ios_notify") }), + el("div", { class: "contacts" }, [ + el("a", { class: "link", href: "mailto:vrubelroman@gmail.com?subject=ChessPenguin", text: "✉ " + t("email") }), + el("a", { class: "link", href: "https://t.me/vrubelr", rel: "noopener", text: "✈ Telegram" }), + ]), + shots(["01-game-640.webp", "04-review-640.webp"]), + ]; + } + + function showDevicePage(kind) { + document.documentElement.lang = lang; + document.title = t("app_phone_title"); + var page = document.getElementById("cp-device"); + page.textContent = ""; + var select = el("select", { "aria-label": t("language") }, LANGS.map(function (l) { + var o = el("option", { value: l[0], text: l[1] }); + if (l[0] === lang) o.selected = true; + return o; + })); + select.addEventListener("change", function () { + lang = select.value; + showDevicePage(kind); + }); + page.appendChild(el("header", null, [ + el("span", { class: "brand" }, [el("img", { src: "icon-64.png", alt: "" }), document.createTextNode("ChessPenguin")]), + select, + ])); + page.appendChild(el("h1", { text: t("app_phone_title") })); + var body; + if (kind === "android-phone" || kind === "android-tablet") { + body = [el("p", { text: t("app_and_lead") })].concat(androidPart()); + } else if (kind === "iphone" || kind === "ipad") { + body = iosPart(); + } else { + body = [ + el("p", { text: t("app_phone_generic") }), + el("a", { class: "btn", href: "/download/android-noengine", rel: "nofollow", text: t("btn_android") }), + el("p"), + shareButton(), + ]; + } + body.forEach(function (n) { page.appendChild(n); }); + page.appendChild(anyway()); + page.hidden = false; + } + + // ----- which one -------------------------------------------------------------------- + + var asked = params.get("phone"); + var kind = CPDevice.deviceClass(); + if (asked === "1") { + showDevicePage(kind === "computer" ? "phone" : kind); + } else if (asked === "android" || asked === "ios") { + showDevicePage(asked === "android" ? "android-phone" : "iphone"); + } else if (asked === "0" || kind === "computer" || storage(true) === "1") { + startApp(); + } else { + showDevicePage(kind); + } +})(); diff --git a/apps/web/src/lib.rs b/apps/web/src/lib.rs new file mode 100644 index 0000000..147a881 --- /dev/null +++ b/apps/web/src/lib.rs @@ -0,0 +1,37 @@ +//! ChessPenguin in a browser: the entry point the page (`page/index.html`) calls once it +//! has decided the device is a computer. The interface is the desktop program's +//! (`chesspenguin_app`), with the web platform under it (`docs/dev/web.md`). +#![cfg(target_family = "wasm")] + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The reader worker's work (`page/import-worker.js`): one more file of the database +/// to read (its own file first) … +#[wasm_bindgen] +pub fn reader_give(name: String, bytes: Vec) { + chesspenguin_app::reader_give(name, bytes); +} + +/// … and the database read and indexed away from the page (or only its games counted). +#[wasm_bindgen] +pub fn reader_read(count: bool) -> JsValue { + chesspenguin_app::reader_read(count) +} + +/// Starts ChessPenguin in the page's canvas `canvas_id`. Resolves once the interface +/// runs; an error says why it could not start (no WebGL, …). +#[wasm_bindgen] +pub async fn start(canvas_id: String) -> Result<(), JsValue> { + // The program's log and its panics go to the browser's console. + let _ = eframe::WebLogger::init(log::LevelFilter::Info); + let window = web_sys::window().ok_or("no window")?; + let canvas = window + .document() + .ok_or("no document")? + .get_element_by_id(&canvas_id) + .ok_or("no canvas")? + .dyn_into::()?; + let lang = web_sys::UrlSearchParams::new_with_str(&window.location().search()?)?.get("lang"); + chesspenguin_app::start_web(canvas, lang).await +} diff --git a/claude/memory/MEMORY.md b/claude/memory/MEMORY.md deleted file mode 100644 index f6d6341..0000000 --- a/claude/memory/MEMORY.md +++ /dev/null @@ -1,12 +0,0 @@ -- [GitHub is a filtered mirror](github-filtered-mirror.md) — never `git push github`; publish with scripts/publish-github.sh; Forgejo keeps internal docs -- [Release process](release-process.md) — version bump → tag → publish script → Actions → AUR PKGBUILD; port 22 blocked, use 443 -- [Website](website.md) — Ñ�айт в website/, Forgejo only; i18n перезапуÑ�к, геобаза Ñ� unpkg, Ñ�криншоты -- [Search performance plan](search-performance-plan.md) — booster done; next: opening index with RAM check, PGN memory guard, laptop bench -- [Use review agents](use-review-agents.md) — new UI features: independent tester + designer agents before commit (user asked) -- [Lichess API quirks](lichess-api-quirks.md) — drops connections ~1 min after an aborted export; test nick only via CP_ONLINE_NICK -- [GitHub needs approval](github-needs-approval.md) — no publish-github.sh, tags or releases without the owner's explicit «добро» each time -- [No workarounds](no-workarounds.md) — fix root causes simply and reliably; no hacks (owner's rule) -- [Android app](android-app.md) — Kotlin+Compose over Rust core via UniFFI, Android 12+, view-only, two APKs, owner keeps the signing key -- [Android signing key](android-signing-key.md) — ~/.config/chesspenguin/android/{release.jks,.env}; copy in Forgejo `private`, never on main -- [Private branch](private-branch.md) — Forgejo `private` branch: secrets, test DBs, memory, transcripts; restore.sh; never on main/GitHub -- [Second machine](second-machine.md) — 2nd box: repo ~/projects/chessbaseLinux (0.13/0.14 released there); back on this one since 2026-10-23 evening; sync memory via `private` diff --git a/claude/memory/android-app.md b/claude/memory/android-app.md deleted file mode 100644 index ee8b7f0..0000000 --- a/claude/memory/android-app.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -name: android-app -description: "Android viewer app (androidApp/): Kotlin+Compose over our Rust crates via UniFFI; Android 12+; view-only; two APKs; owner keeps the signing key" -metadata: - node_type: memory - type: project - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-21T21:22:38.448Z ---- - -Started 2026-10-22. Decisions in docs/decisions.md §16; stack research docs/research/android-stack.md; UI spec docs/design/android-ui.md (owner: «проÑ�то, понÑ�тно, Ñ�импатично», think the design through). - -- Kotlin + Jetpack Compose; Rust core (chess-core, chess-import, uci) through a thin UniFFI crate; cargo-ndk; code in androidApp/. -- View-only: databases (same formats as desktop, no Mega on phones — target ≤ ~1M games), game list, game with notation under the board, paging games. No move input/saving in v1. -- minSdk 31 (Android 12+). No iOS for now. -- Two APKs: with Stockfish + net inside, and without (engine downloaded on request); both on GitHub and the site. -- Stores later. Signing key: create it, give a copy to the owner, keep ours too — losing it means no updates. -- Tooling (2026-10-22): rustup targets aarch64/x86_64-linux-android, cargo-ndk 4.1.2, SDK cmdline-tools in ~/Android/Sdk; JDK via `sudo pacman -S jdk21-openjdk` (owner runs it). - -Status 2026-10-22 night: 0.11.0 released (GitHub, both APKs, AUR PKGBUILD) and site deployed. Android has «Добавить папку» (folders scanned two levels; .cbh sets; grants kept while an entry or a pending Undo uses them, unused grants released at start). Testing: headless emulator preferred by the owner (no window). Open: board/piece choice, a real Android 12 device test, live TalkBack check. - -**How to apply:** add androidApp/ and its workflow to the GitHub publish filter decisions before publishing; follow [[github-needs-approval]], [[use-review-agents]], [[no-workarounds]]. - -2026-10-23 (second machine): game report done (commit 1661e23, not pushed): shared crate crates/game-review (desktop report.rs + review model/cache/job moved there), mobile-api GameReview, Android ReviewSession/ReviewViews; spec android-ui.md §21–22. Reviewed by tester + designer agents. Open from QA: in-app dark theme leaves status-bar icons dark and nav bar light (pre-existing); desktop `review_next` wording «Перейти к Ñ�ледующей» could become «к Ñ�ледующему такому ходу». - -2026-10-23: games from Lichess/Chess.com on Android (commit f6072cb, local, not pushed): shared crate crates/online-games (desktop online.rs core moved; desktop keeps Probe/ago/dir wrappers), mobile-api online.rs, Android OnlineDownloads/OnlineScreen, Source.Online in files/online/; INTERNET permission now in both builds. Owner decision: downloaded databases list newest first (Database.newest_first, Library.listed). Public test nicks used: mary, john, penguin, test (small). lintFullDebug has 4 pre-existing MissingPermission errors in EngineFiles (only lintLightDebug is the project check). - -2026-10-23: in-app update (0.15.0): crates/releases (shared with desktop update.rs), mobile-api check_release, Android AppUpdates/UpdateViews, spec android-ui.md §25. Always the light APK; the full build copies its net into files/engine first. Test the whole old→new path on the emulator with a local "release": debug build with CP_UPDATE_API=http://10.0.2.2:8765/latest.json (debug-only cleartext config), a 9.9.9 debug APK + latest.json + SHA256SUMS served from the host (scratchpad scripts, not in the repo; recreate from this note). On the emulator Android installs the self-update without its question. Owner allowed this feature to be released without asking once tests passed (one-time). diff --git a/claude/memory/android-signing-key.md b/claude/memory/android-signing-key.md deleted file mode 100644 index 6c38b9f..0000000 --- a/claude/memory/android-signing-key.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -name: android-signing-key -description: Android release key lives in ~/.config/chesspenguin/android (release.jks + .env, 0600); owner must get a copy -metadata: - type: project ---- -Created 2026-10-22: `~/.config/chesspenguin/android/release.jks` (PKCS12, alias `chesspenguin`, RSA 4096, valid to 2054) and `.env` with CP_KEYSTORE, CP_KEYSTORE_PASSWORD, CP_KEY_ALIAS, CP_KEY_PASSWORD. SHA-256 of the cert: ED:F3:3A:E5:06:F2:53:80:…:3E:9A. - -**Why:** owner: «ключ дашь мне Ñ� Ñ�охраню тоже у Ñ�ебÑ�, но ты тоже не забывай». Losing it means no updates over installed APKs. - -**How to apply:** never print the passwords and never put them on `main` (it goes to GitHub). Since 2026-10-23 a copy is in the Forgejo branch `private` (owner: «можешь залить туда и ключи и Ñ�екреты»), see [[private-branch]]. For CI put them into GitHub secrets only with the owner's go-ahead. See [[android-app]]. diff --git a/claude/memory/github-filtered-mirror.md b/claude/memory/github-filtered-mirror.md deleted file mode 100644 index 4e88464..0000000 --- a/claude/memory/github-filtered-mirror.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: github-filtered-mirror -description: "GitHub is a filtered public mirror — publish only via scripts/publish-github.sh, never git push github; Forgejo (origin) has everything" -metadata: - node_type: memory - type: feedback - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-19T07:15:58.713Z ---- - -GitHub (vrubelroman/chessPenguin) must never contain internal files or have them in history: the brief (техничеÑ�кое задание.txt), AGENTS.md/.opencode/opencode.jsonc, docs/{architecture,decisions,implementation-plan,agent-team}.md, docs/{research,design,qa,dev}, draft icons/, website/, scripts/publish-github.sh. Forgejo (`origin`, 192.168.8.174:2222) keeps the full history. - -**Why:** the user does not want visitors of the public repo to see internal design/agent material ("внутрÑ�ннÑ�Ñ� инфа, у наÑ� должно быть"); history was rewritten on 2026-10-19 for this. - -**How to apply:** commit normally and `git push origin main [tags]`; publish to GitHub with `scripts/publish-github.sh` (deterministic filter-branch rewrite, pushes main + tags; `DRY_RUN=1` to check). The `github` remote's push URL is deliberately set to `DISABLED-use-scripts/publish-github.sh`. New internal paths must be added to the script's `internal` list. Release tags: push the tag to origin, then run the script so GitHub gets the rewritten tag (which triggers the release workflow). See also [[release-process]]. diff --git a/claude/memory/github-needs-approval.md b/claude/memory/github-needs-approval.md deleted file mode 100644 index 31b883e..0000000 --- a/claude/memory/github-needs-approval.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: github-needs-approval -description: "Never publish to GitHub (scripts/publish-github.sh), push tags or cut a release without the owner's explicit go-ahead each time" -metadata: - node_type: memory - type: feedback - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-21T19:37:08.683Z ---- - -Do not run scripts/publish-github.sh, push a version tag, or start a release (and its AUR update) on my own. Propose it ("готово к публикации на GitHub / выпуÑ�ку X — даёшь добро?"), wait for an explicit yes in that conversation turn, then publish. Committing locally is fine; pushing to Forgejo (origin) — ask too unless the owner said otherwise. - -**Why:** 2026-10-21 the owner objected: «зачем ты без моего добра опÑ�ть отправлÑ�ешь Ñ�разу на гитхаб? не делай так больше. предлагай, Ñ� даю добро и ты льешь». I had tagged 0.8.5 before he confirmed the test, and published a follow-up commit unasked. - -**How to apply:** an earlier approval does not carry over to the next change; "выпущу, еÑ�ли вÑ�Ñ‘ в порÑ�дке" is a proposal, not permission. See [[github-filtered-mirror]], [[release-process]]. diff --git a/claude/memory/lichess-api-quirks.md b/claude/memory/lichess-api-quirks.md deleted file mode 100644 index ed41cd9..0000000 --- a/claude/memory/lichess-api-quirks.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: lichess-api-quirks -description: "Lichess export API behaviour seen live (connection drops after an aborted export, ~16 games/s, test nick only via env)" -metadata: - node_type: memory - type: reference - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-20T05:51:43.605Z ---- - -Observed live while building online games (0.8.0, 2026-10-20): -- After an export stream is cut short, Lichess drops new connections from the same IP for about a minute ("io: unexpected end of file"). online.rs retries with waits (DOWNLOAD_WAITS); the live test `online_live` can still fail if run twice in a row. -- Anonymous export runs ~15–20 games/s (6 541 games ≈ 6–7 min). -- `POST /api/games/export/_ids` omits unknown ids silently. -- The owner's son's test account is passed only via `CP_ONLINE_NICK`; never commit or publish it. - -**How to apply:** run `online_live` at most once per few minutes; keep real downloads short when testing. See [[release-process]]. diff --git a/claude/memory/no-workarounds.md b/claude/memory/no-workarounds.md deleted file mode 100644 index cb91867..0000000 --- a/claude/memory/no-workarounds.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: no-workarounds -description: "Fix causes with simple, reliable code; no hacks or workarounds (owner's rule)" -metadata: - node_type: memory - type: feedback - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-21T19:47:47.713Z ---- - -No "коÑ�тыльные" solutions: fix only what can be fixed properly, prefer the simpler and more reliable change, and find the root cause before patching symptoms (e.g. a layout that grows every frame is a width bug, not something to clamp). - -**Why:** 2026-10-21 the owner: «запиши Ñ�ебе что не нужно пиÑ�ать коÑ�тыльных решений! делаем только то что нормально фикÑ�итÑ�Ñ� и можно Ñ�делать. лучше проще и надежнее». - -**How to apply:** before a fix, say what the cause is; if the only fix is a hack, say so and propose leaving it or redesigning instead. See [[use-review-agents]]. diff --git a/claude/memory/private-branch.md b/claude/memory/private-branch.md deleted file mode 100644 index 893b11e..0000000 --- a/claude/memory/private-branch.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -name: private-branch -description: Forgejo branch `private` (orphan) holds secrets, test DBs, assistant memory and session transcripts; never on main/GitHub -metadata: - type: project ---- -Made 2026-10-23 so the owner can continue on another machine. Branch `private` on origin (home Forgejo, the owner's personal server), no common history with `main`: `secrets/` (Android release key + .env, ~/.config/chesspenguin credentials/settings, website.env), `test-data/` (six small PGN/.cbv/.7z databases), `claude/memory/`, `claude/transcripts/` (sessions, images stripped, zstd), `claude/settings.local.json`, `emulator/` (tap.py, shot.sh), `restore.sh`, README. Setup notes for a new machine: `docs/dev/handoff.md` on main. - -**Why:** owner: «Ñ�то мой личный репозиторий на моем домашнем Ñ�ервере», asked for keys, secrets and small databases there. - -**How to apply:** publish-github.sh pushes only `main` and tags, so this branch never reaches GitHub — never merge it into main or tag it. After changing a key, a setting or the memory, update the copy there (`git worktree add ../chessBaseLinux-private private`, copy, commit, `git push origin private`). See [[github-filtered-mirror]], [[android-signing-key]]. diff --git a/claude/memory/release-process.md b/claude/memory/release-process.md deleted file mode 100644 index de9ef69..0000000 --- a/claude/memory/release-process.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -name: release-process -description: How a ChessPenguin release is cut (version bump → tag → GitHub Actions builds → AUR PKGBUILD update) and network quirks -metadata: - node_type: memory - type: project - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-19T07:16:11.171Z ---- - -Release steps that worked for 0.4–0.6 (2026-10-19): -1. Bump `version` in root Cargo.toml, rename CHANGELOG `[Unreleased]` → `[x.y.z] — date`, add a `` to packaging/*.metainfo.xml; fmt, clippy -D warnings, tests. -2. Commit, `git tag -a vX.Y.Z`, `git push origin main vX.Y.Z`, then `scripts/publish-github.sh` (pushes the rewritten tag to GitHub; the tag triggers .github/workflows/release.yml: linux, flatpak, windows, macos → publish). -3. Watch the run via the public API (no `gh` CLI): `curl https://api.github.com/repos/vrubelroman/chessPenguin/actions/runs`. -4. AUR: download the linux tar.gz, check sha256 against SHA256SUMS.txt, update packaging/aur/chesspenguin-bin/PKGBUILD (pkgver, sha256sums), `makepkg --printsrcinfo > .SRCINFO`, test `makepkg -f` in target/aur-build, commit, push origin + publish script. The AUR itself is not published yet (no account; port 22 to aur.archlinux.org is blocked from this network). - -Network: port 22 to github.com is blocked here; the `github` fetch URL uses ssh.github.com:443. Windows cross-check locally fails on `ring` (no MinGW) — rely on CI. User has no other users yet (0.6 is the "real" first release). See [[github-filtered-mirror]]. - -- 2026-10-19: подпиÑ�ывать Windows/macOS Ñ�борки решили Ð�Е (SignPath/Store/Azure обÑ�уждалиÑ�ÑŒ — «не заморачиваемÑ�Ñ�»). Ð�е предлагать Ñ�нова без повода; на Ñ�айте оÑ�таютÑ�Ñ� инÑ�трукции обхода SmartScreen/Gatekeeper. - -- 2026-10-23: one version for desktop and Android stays (owner: «оÑ�тавлÑ�ем как еÑ�ть»), even when a release changes only the phone. Discussed: desktop then offers an update with nothing new for it; skipping "phone-only" releases in the desktop update check was offered and declined. Do not propose split versions again without a new reason. diff --git a/claude/memory/search-performance-plan.md b/claude/memory/search-performance-plan.md deleted file mode 100644 index 16831d0..0000000 --- a/claude/memory/search-performance-plan.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -name: search-performance-plan -description: "Large-base search performance work (2026-10-19): own booster, opening index with RAM check, PGN memory guard, --bench — done locally, not yet pushed/released" -metadata: - node_type: memory - type: project - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-19T16:24:32.309Z ---- - -On 2026-10-19 the user asked for an audit of filtering/search algorithms and said -"делать вÑ�Ñ‘ как ты предлагаешь"; they want RAM used when available ("не жалел бы -оперативку"), a slower path otherwise, and laptops to cope. - -Done (commits a7d9d59, 1506ebd, 4b92fa3 on main, as of 2026-10-19 evening, unreleased): -- own `.cbb`-format booster in the cache when the base has no usable one (`chessbase/booster.rs`); - booster skipped for early positions (sampling the first 4096 records); -- opening index `chessbase/openings.rs` (first 10 plies, 600 MB for Mega, built in the same - pass, loaded only when `memory::available()` ≥ size + 1 GiB); misses the rare games that - reach an opening position later by a detour (23 of 5.9M for 1.e4) — documented; -- PGN position-table memory guard (`PgnDb::positions_blocked`), message on the search board; -- `chesspenguin --bench [report.txt]`, dev hook `CP_MEMORY_LIMIT=`. -- Cache dir for all of it: `~/.cache/chesspenguin/boosters/.cbb|.cpo`. - -Open: measure on a real laptop with `--bench` (4-thread taskset estimate: start 0.29 s with -the index vs 2.2 s without). Ask before pushing/releasing. - -**Why:** opening positions match millions of games and no prefilter helps. -**How to apply:** keep results identical to the pass (tests compare them); document -measurements in docs/dev/import.md. See [[release-process]] before shipping. - -2026-10-24 (0.16.0): every desktop database uses LargeView (ChessBase-style filters, quick search, position board): chess-import pgn_catalog.rs (PGN tags as Filter/sort/suggest; built in the loading thread), Filter::text quick search for PGN and ChessBase (Mega ~0.1 s via year/ECO tables), converted ChessBase texts marked with the CbText tag, PGN position-table memory estimate from all_plies (was file size ×10, 14× too high on clock-commented files). Spec: docs/design/large-databases.md §9. diff --git a/claude/memory/second-machine.md b/claude/memory/second-machine.md deleted file mode 100644 index 83e56fd..0000000 --- a/claude/memory/second-machine.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: second-machine -description: "Second machine (from 2026-10-23): repo at ~/projects/chessbaseLinux, not ~/services; tools installed; passwordless sudo; docker group needs re-login" -metadata: - type: project ---- -On 2026-10-23 the owner moved work to another machine (CachyOS, host asusCachyOS). The clone is `~/projects/chessbaseLinux` (not `~/services/chessBaseLinux` as in docs/dev/handoff.md); the `private` worktree is `~/projects/chessbaseLinux-private`. `restore.sh` was run with this path, so memory and old transcripts are under `-home-vrubel-projects-chessbaseLinux`. The `github` remote was added with push disabled. - -Set up the same day: pacman rustup (stable 1.99.1, android + windows-gnu targets, clippy), cargo-ndk 4.1.2, jdk21-openjdk, docker-buildx; Android SDK in ~/Android/Sdk (cmdline-tools latest, platform-tools, build-tools 37.0.0, platforms android-37.0, NDK 30.0.16248370, emulator, android-36 x86_64 image); AVD `cp-phone` (pixel_7, 2 GB); `androidApp/local.properties`. PATH/JAVA_HOME/ANDROID_HOME in ~/.config/fish/conf.d/dev-tools.fish and ~/.zshrc. The newer sdkmanager names packages with `/` (`ndk/30.0.16248370`). Sudo is passwordless (owner set NOPASSWD for wheel in /etc/sudoers and /etc/sudoers.d/10-installer). User added to docker group: until re-login run docker via `printf 'cmd\n' | newgrp docker` (no `sg`). - -Data: Mega2026 copied into pgnFilesforExample/ (also a copy in ~/temp/Mega2026); app settings kept local, Mega and reference_db point to the repo copy; ChatGPT tokens taken from the private copy. No engines/ or designExample/ here. - -**How to apply:** paths in memory that say ~/services/chessBaseLinux mean this repo here. See [[private-branch]]. - -Release 0.13.0 cut from here on 2026-10-23 (game report). Done once for this machine: GitHub host key for ssh.github.com:443 added to known_hosts (fingerprint checked against GitHub's published ED25519 key); repo-local git user.name/email = vrubelroman / vrubelroman@gmail.com. publish-github.sh needs the owner to leave auto mode (Shift+Tab), as on the old machine. - -2026-10-23 evening: back on the first machine (`~/services/chessBaseLinux`, slug `-home-vrubel-services-chessBaseLinux`); pulled main (0.13.0, 0.14.0) and this memory from `private`, restored the second machine's session 22810270 here. Whichever machine is used, sync memory through `private` before switching. diff --git a/claude/memory/use-review-agents.md b/claude/memory/use-review-agents.md deleted file mode 100644 index de0ecb2..0000000 --- a/claude/memory/use-review-agents.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -name: use-review-agents -description: "For new user-facing features, run independent tester and designer agents before committing — the user asked for it to keep quality up" -metadata: - node_type: memory - type: feedback - originSessionId: 86c7ee93-82be-4380-9d11-393872d0bb51 - modified: 2026-10-19T18:54:49.245Z ---- - -For every new user-facing feature (UI, behaviour), run independent review agents before -committing: a tester (correctness against an oracle, edge cases, regressions, perf) and a -designer (wording, states, consistency, light/dark, plurals), as described in AGENTS.md -roles. They report only; the orchestrator fixes. Small fixes and releases don't need it. - -**Why:** 2026-10-19 the user asked «ты же пользуешьÑ�Ñ� агентами? ну там по дизайну, -теÑ�тированию? Ñ� не хочу чтобы падало качеÑ�тво нашего продукта» after a session where all -work was done without independent review. -**How to apply:** launch both in parallel in the background with isolated XDG dirs, -outputs under target/-/, no edits to sources or pgnFilesforExample/; -merge their findings, fix, re-verify, then commit. See [[release-process]]. diff --git a/claude/memory/website.md b/claude/memory/website.md deleted file mode 100644 index ecc841a..0000000 --- a/claude/memory/website.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: website -description: Product website in website/ (Forgejo only): docker compose, i18n, /stats, screenshot pipeline gotchas -metadata: - type: project ---- -Сайт ChessPenguin — `website/` (Rust axum, docker compose за nginx пользователÑ� на домашнем Ñ�ервере, HTTPS делает пользователь). Только в Forgejo, иÑ�ключён из GitHub через [[github-filtered-mirror]]. - -- Переводы читаютÑ�Ñ� при Ñ�тарте Ñ�ервера — поÑ�ле правки i18n перезапуÑ�кать (пользователь видел «вÑ�егда en» из-за Ñ�того). -- Геобаза: официальный download.db-ip.com рвёт Ñ�оединение; брать DB-IP Lite City mmdb Ñ� unpkg `@ip-location-db/dbip-city-mmdb` (ipv4+ipv6, полÑ� country_code/state1/city), атрибуциÑ� DB-IP обÑ�зательна. -- Скриншоты: `website/shots/make-screenshots.sh` (Mega под именем «Tournament games» через hard links, только таблицы, без аннотаций), затем `shots/derive.py`. raw не коммититÑ�Ñ�. -- Headless Firefox в пеÑ�очнице не доÑ�тучитÑ�Ñ� до localhost: Ñ�нимать Ñ�траницу через file:// Ñ�нимок (curl + sed путей), бинарь `/usr/lib/firefox/firefox` Ñ� MOZ_HEADLESS=1. -- Прод: `docker-prodVM` (192.168.8.171, удалённый shell fish → `ssh host bash -s`), каталог ~/services/ChessPenguinSite (compose + .env + data/), порт **8140**. nginx на другой машине делает пользователь — про nginx не думать. -- ОбновлÑ�ть прод ТОЛЬКО поÑ�ле Ñ�вного «добро» пользователÑ�: `website/deploy/deploy.sh` (build → docker save|ssh docker load, тег = коммит; `rollback`, `status`). Требует закоммиченный website/. -- Локально docker поÑ�тавлен 2026-10-19; группа docker без перелогина: `printf 'cmd\n' | newgrp docker`. -- Домен: https://chess.vrubel.xyz (SITE_URL в .env на проде). -- СтатиÑ�тика: поÑ�етители Ñ�читаютÑ�Ñ� по JS-Ñ�игналу `POST /hit`, Ñ�троки клаÑ�Ñ�ифицируютÑ�Ñ� human/bot/owner/local, в итоги идёт только human. 2026-10-19 база на проде очищена до одной реальной запиÑ�и (МоÑ�ква, друг пользователÑ�); бÑ�кап `data/backup-before-cleanup-2026-10-19.sqlite`. diff --git a/claude/settings.local.json b/claude/settings.local.json deleted file mode 100644 index 6660eb8..0000000 --- a/claude/settings.local.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "permissions": { - "allow": [ - "Bash(newgrp docker *)", - "Bash(python3 -)", - "Bash(ssh docker-prodVM *)", - "Bash(git push *)", - "Bash(scripts/publish-github.sh)", - "Bash(sleep *)", - "Bash(S=/tmp/claude-1000/-home-vrubel-services-chessBaseLinux/86c7ee93-82be-4380-9d11-393872d0bb51/scratchpad; sed -i 's/^run=[0-9]*/run=39858491613/' $S/watch.sh && bash $S/watch.sh)", - "Bash(ip -br addr)", - "Bash(ip route *)", - "Bash(ping -c1 -W2 192.168.8.171)", - "Bash(D=target/aur-build && mkdir -p $D && cd $D && rm -f *.tar.gz SHA256SUMS.txt && curl -sLO https://github.com/vrubelroman/chessPenguin/releases/download/v0.11.1/ChessPenguin-0.11.1-linux-x86_64.tar.gz && curl -sLO https://github.com/vrubelroman/chessPenguin/releases/download/v0.11.1/SHA256SUMS.txt && grep linux-x86_64.tar.gz SHA256SUMS.txt && sha256sum ChessPenguin-0.11.1-linux-x86_64.tar.gz; grep -n \"pkgver=\\\\|sha256sums\\\\|pkgrel\" /home/vrubel/services/chessBaseLinux/packaging/aur/chesspenguin-bin/PKGBUILD)", - "Bash(S=/tmp/claude-1000/-home-vrubel-services-chessBaseLinux/86c7ee93-82be-4380-9d11-393872d0bb51/scratchpad; sed -i 's/^run=[0-9]*/run=39869880695/' $S/watch.sh && bash $S/watch.sh)", - "Read(//home/vrubel/.config/chesspenguin/**)", - "Read(//home/vrubel/.config/fish/**)", - "Bash(S=/tmp/claude-1000/-home-vrubel-services-chessBaseLinux/86c7ee93-82be-4380-9d11-393872d0bb51/scratchpad; W=$S/private; sed -i 's/| Desktop app settings, `credentials.json` \\(ChatGPT tokens of the app.s AI features\\) |/| Desktop app settings and `credentials.json` \\(ChatGPT tokens\\) |/' $W/README.md; grep -n \"credentials\" $W/README.md; chmod +x $W/restore.sh; rm -rf $S/fakehome $S/fakerepo; mkdir -p $S/fakehome $S/fakerepo; cp /home/vrubel/services/chessBaseLinux/Cargo.toml $S/fakerepo/; HOME=$S/fakehome $W/restore.sh $S/fakerepo 2>&1 | tail -8; find $S/fakehome -maxdepth 5 | head -20; ls $S/fakehome/.claude/projects/*/ | head; ls -la $S/fakehome/.config/chesspenguin/android)" - ] - } -} diff --git a/claude/transcripts/22810270-a59b-4661-8a58-dc5685ca091f.dir.tar.zst b/claude/transcripts/22810270-a59b-4661-8a58-dc5685ca091f.dir.tar.zst deleted file mode 100644 index 4b9f476..0000000 Binary files a/claude/transcripts/22810270-a59b-4661-8a58-dc5685ca091f.dir.tar.zst and /dev/null differ diff --git a/claude/transcripts/22810270-a59b-4661-8a58-dc5685ca091f.jsonl.zst b/claude/transcripts/22810270-a59b-4661-8a58-dc5685ca091f.jsonl.zst deleted file mode 100644 index 9d55ea3..0000000 Binary files a/claude/transcripts/22810270-a59b-4661-8a58-dc5685ca091f.jsonl.zst and /dev/null differ diff --git a/claude/transcripts/609da5c2-4556-43a3-a126-7594071bc9fc.jsonl.zst b/claude/transcripts/609da5c2-4556-43a3-a126-7594071bc9fc.jsonl.zst deleted file mode 100644 index d6b000c..0000000 Binary files a/claude/transcripts/609da5c2-4556-43a3-a126-7594071bc9fc.jsonl.zst and /dev/null differ diff --git a/claude/transcripts/86c7ee93-82be-4380-9d11-393872d0bb51.dir.tar.zst b/claude/transcripts/86c7ee93-82be-4380-9d11-393872d0bb51.dir.tar.zst deleted file mode 100644 index 6e93794..0000000 Binary files a/claude/transcripts/86c7ee93-82be-4380-9d11-393872d0bb51.dir.tar.zst and /dev/null differ diff --git a/claude/transcripts/86c7ee93-82be-4380-9d11-393872d0bb51.jsonl.zst b/claude/transcripts/86c7ee93-82be-4380-9d11-393872d0bb51.jsonl.zst deleted file mode 100644 index 8ae9af9..0000000 Binary files a/claude/transcripts/86c7ee93-82be-4380-9d11-393872d0bb51.jsonl.zst and /dev/null differ diff --git a/crates/chess-core/Cargo.toml b/crates/chess-core/Cargo.toml new file mode 100644 index 0000000..a66c3b8 --- /dev/null +++ b/crates/chess-core/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "chess-core" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true + +[dependencies] +shakmaty.workspace = true +encoding_rs.workspace = true +thiserror.workspace = true +# The index of a database in serde's terms: the web version reads a database in a +# worker and gives its index to the page (`PgnIndex`). +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] + +[dev-dependencies] +# Independent oracle in corpus tests: the core uses its own lexer (byte offsets, +# coverage diagnostics), pgn-reader is used only to cross-check move counts. +pgn-reader.workspace = true diff --git a/crates/chess-core/examples/pgn_dump.rs b/crates/chess-core/examples/pgn_dump.rs new file mode 100644 index 0000000..bb7682c --- /dev/null +++ b/crates/chess-core/examples/pgn_dump.rs @@ -0,0 +1,36 @@ +//! Prints diagnostics and the normalized PGN export of one record. +//! Usage: cargo run -p chess-core --example pgn_dump -- <1-based index> + +use std::sync::atomic::AtomicBool; + +fn main() { + let mut args = std::env::args().skip(1); + let (Some(path), Some(index)) = (args.next(), args.next()) else { + eprintln!("usage: pgn_dump <1-based index>"); + std::process::exit(2); + }; + let Ok(index) = index.parse::() else { + eprintln!("index must be a number"); + std::process::exit(2); + }; + let db = match chess_core::PgnDatabase::open( + std::path::Path::new(&path), + &mut |_| {}, + &AtomicBool::new(false), + ) { + Ok(db) => db, + Err(e) => { + eprintln!("{e}"); + std::process::exit(1); + } + }; + println!("{} records, encoding {}", db.len(), db.encoding().label()); + let Some(parsed) = index.checked_sub(1).and_then(|i| db.load_game(i)) else { + eprintln!("no record {index}"); + std::process::exit(1); + }; + for d in &parsed.diagnostics { + println!("# {d}"); + } + print!("{}", parsed.game.to_pgn()); +} diff --git a/crates/chess-core/src/comment.rs b/crates/chess-core/src/comment.rs new file mode 100644 index 0000000..a61849d --- /dev/null +++ b/crates/chess-core/src/comment.rs @@ -0,0 +1,360 @@ +//! Embedded comment commands (`[%csl …]`, `[%cal …]`, any `[%name …]`). +//! +//! Comments are stored verbatim in the game; this module only interprets them +//! for display. Unknown commands are returned as [`Annotation::Other`]. + +use shakmaty::Square; + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum ShapeColor { + Red, + Green, + Blue, + Yellow, + Other(char), +} + +impl ShapeColor { + /// The letter PGN writes: `R`, `G`, `B`, `Y`. + pub fn letter(self) -> char { + match self { + ShapeColor::Red => 'R', + ShapeColor::Green => 'G', + ShapeColor::Blue => 'B', + ShapeColor::Yellow => 'Y', + ShapeColor::Other(c) => c, + } + } + + fn from_char(c: char) -> ShapeColor { + match c { + 'R' => ShapeColor::Red, + 'G' => ShapeColor::Green, + 'B' => ShapeColor::Blue, + 'Y' => ShapeColor::Yellow, + c => ShapeColor::Other(c), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Annotation { + /// `[%csl Ra6,Gb7]` highlighted squares. + Squares(Vec<(ShapeColor, Square)>), + /// `[%cal Rc7b6]` arrows. + Arrows(Vec<(ShapeColor, Square, Square)>), + /// Any other command (or a malformed csl/cal), payload kept verbatim. + Other { name: String, payload: String }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CommentPart { + Text(String), + Annotation(Annotation), +} + +/// Splits a comment into plain text and commands, in order. Text parts are +/// trimmed; empty text parts are omitted. +pub fn parse_comment(text: &str) -> Vec { + let mut parts = Vec::new(); + let mut rest = text; + while let Some(start) = rest.find("[%") { + push_text(&mut parts, &rest[..start]); + let body = &rest[start + 2..]; + // Find the closing ']' outside double quotes. + let mut in_quotes = false; + let mut end = None; + for (i, c) in body.char_indices() { + match c { + '"' => in_quotes = !in_quotes, + ']' if !in_quotes => { + end = Some(i); + break; + } + _ => {} + } + } + let Some(end) = end else { + push_text(&mut parts, &rest[start..]); + return parts; + }; + let inner = body[..end].trim(); + let (name, payload) = match inner.find(char::is_whitespace) { + Some(i) => (&inner[..i], inner[i..].trim()), + None => (inner, ""), + }; + parts.push(CommentPart::Annotation(command(name, payload))); + rest = &body[end + 1..]; + } + push_text(&mut parts, rest); + parts +} + +fn push_text(parts: &mut Vec, s: &str) { + let t = s.trim(); + if !t.is_empty() { + parts.push(CommentPart::Text(t.to_owned())); + } +} + +fn command(name: &str, payload: &str) -> Annotation { + let other = || Annotation::Other { + name: name.to_owned(), + payload: payload.to_owned(), + }; + let items = payload.split(',').map(str::trim).filter(|s| !s.is_empty()); + match name { + "csl" => { + let mut v = Vec::new(); + for it in items { + let mut ch = it.chars(); + let (Some(c), sq) = (ch.next(), ch.as_str()) else { + return other(); + }; + match sq.parse::() { + Ok(sq) => v.push((ShapeColor::from_char(c), sq)), + Err(_) => return other(), + } + } + Annotation::Squares(v) + } + "cal" => { + let mut v = Vec::new(); + for it in items { + let mut ch = it.chars(); + let Some(c) = ch.next() else { return other() }; + let rest = ch.as_str(); + let (Some(a), Some(b)) = (rest.get(..2), rest.get(2..)) else { + return other(); + }; + match (a.parse::(), b.parse::()) { + (Ok(a), Ok(b)) => v.push((ShapeColor::from_char(c), a, b)), + _ => return other(), + } + } + Annotation::Arrows(v) + } + _ => other(), + } +} + +impl Annotation { + /// The command as PGN writes it: `[%cal Rc7b6]`. + pub fn to_pgn(&self) -> String { + match self { + Annotation::Squares(list) => format!( + "[%csl {}]", + list.iter() + .map(|(c, sq)| format!("{}{sq}", c.letter())) + .collect::>() + .join(",") + ), + Annotation::Arrows(list) => format!( + "[%cal {}]", + list.iter() + .map(|(c, a, b)| format!("{}{a}{b}", c.letter())) + .collect::>() + .join(",") + ), + Annotation::Other { name, payload } if payload.is_empty() => format!("[%{name}]"), + Annotation::Other { name, payload } => format!("[%{name} {payload}]"), + } + } +} + +/// The commands of a node's comments, in order. +fn commands(comments: &[String]) -> Vec { + comments + .iter() + .flat_map(|c| parse_comment(c)) + .filter_map(|p| match p { + CommentPart::Annotation(a) => Some(a), + CommentPart::Text(_) => None, + }) + .collect() +} + +/// One comment from `text` and `commands`: the text, then the commands; nothing when +/// both are empty (an empty `Vec`, so that no `{}` is written). +fn assemble(text: &str, commands: &[Annotation]) -> Vec { + let mut out = text.trim().to_owned(); + for c in commands { + if !out.is_empty() { + out.push(' '); + } + out.push_str(&c.to_pgn()); + } + if out.is_empty() { + Vec::new() + } else { + vec![out] + } +} + +/// The comments of a node with their text replaced by what the user typed: the +/// commands (`[%cal]`, `[%clk]`, …) stay, in their order, after the text. A `}` cannot +/// be in a PGN comment and becomes `)`. Paragraphs (blank lines) are kept, a single +/// line break is a space. +pub fn with_text(comments: &[String], text: &str) -> Vec { + let mut clean = String::new(); + let mut blank = false; + for line in text.replace('}', ")").lines() { + let line = line.trim(); + if line.is_empty() { + blank = !clean.is_empty(); + continue; + } + if blank { + clean.push_str("\n\n"); + } else if !clean.is_empty() { + clean.push(' '); + } + blank = false; + clean.push_str(line); + } + assemble(&clean, &commands(comments)) +} + +/// Arrows `(colour, from, to)` and squares `(colour, square)` of a node. +pub type Shapes = (Vec<(ShapeColor, Square, Square)>, Vec<(ShapeColor, Square)>); + +/// The arrows and the squares drawn on the board for a node (`[%cal]`, `[%csl]`). +pub fn shapes(comments: &[String]) -> Shapes { + let mut arrows = Vec::new(); + let mut squares = Vec::new(); + for a in commands(comments) { + match a { + Annotation::Arrows(list) => arrows.extend(list), + Annotation::Squares(list) => squares.extend(list), + Annotation::Other { .. } => {} + } + } + (arrows, squares) +} + +/// The comments of a node with these arrows and squares instead of its own: the text +/// and the other commands stay. +pub fn with_shapes( + comments: &[String], + arrows: &[(ShapeColor, Square, Square)], + squares: &[(ShapeColor, Square)], +) -> Vec { + let mut cmds: Vec = commands(comments) + .into_iter() + .filter(|a| matches!(a, Annotation::Other { .. })) + .collect(); + if !squares.is_empty() { + cmds.push(Annotation::Squares(squares.to_vec())); + } + if !arrows.is_empty() { + cmds.push(Annotation::Arrows(arrows.to_vec())); + } + assemble(&comment_display_text(comments), &cmds) +} + +/// The text of a node's comments as a reader sees it: board commands (`[%cal]`, +/// `[%clk]`, …) left out, single line breaks reflowed (they are formatting), a blank +/// line kept as a paragraph break (book chapters imported from ChessBase). +pub fn comment_display_text(comments: &[String]) -> String { + let mut out = String::new(); + for c in comments { + for part in parse_comment(c) { + if let CommentPart::Text(t) = part { + let mut blank = false; + for line in t.lines() { + if line.trim().is_empty() { + blank = true; + continue; + } + if blank && !out.is_empty() { + out.push_str("\n\n"); + } + blank = false; + for word in line.split_whitespace() { + if !out.is_empty() && !out.ends_with('\n') { + out.push(' '); + } + out.push_str(word); + } + } + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_shapes_and_keeps_unknown() { + let parts = parse_comment( + "[%csl Rc6,Gd6] Ключевые полÑ� [%cal Rc7b6] [%tqu \"Ход?\",\"\",Ka6,\"]\",1] конец", + ); + assert_eq!(parts.len(), 5); + assert_eq!( + parts[0], + CommentPart::Annotation(Annotation::Squares(vec![ + (ShapeColor::Red, Square::C6), + (ShapeColor::Green, Square::D6) + ])) + ); + assert_eq!(parts[1], CommentPart::Text("Ключевые полÑ�".into())); + assert_eq!( + parts[2], + CommentPart::Annotation(Annotation::Arrows(vec![( + ShapeColor::Red, + Square::C7, + Square::B6 + )])) + ); + assert!( + matches!(&parts[3], CommentPart::Annotation(Annotation::Other { name, .. }) if name == "tqu") + ); + assert_eq!(parts[4], CommentPart::Text("конец".into())); + } + + #[test] + fn unterminated_command_is_text() { + assert_eq!( + parse_comment("a [%csl Rc6"), + vec![ + CommentPart::Text("a".into()), + CommentPart::Text("[%csl Rc6".into()) + ] + ); + } + #[test] + fn with_text_keeps_commands_and_paragraphs() { + let c = vec!["Старый текÑ�Ñ‚ [%cal Gf3d5][%clk 0:03:12]".to_owned()]; + assert_eq!( + with_text(&c, " Ð�овый }текÑ�Ñ‚{\nещё\n\n\nабзац "), + vec!["Ð�овый )текÑ�Ñ‚{ ещё\n\nабзац [%cal Gf3d5] [%clk 0:03:12]".to_owned()] + ); + // No text: the commands alone; nothing at all: an empty Vec. + assert_eq!( + with_text(&c, " "), + vec!["[%cal Gf3d5] [%clk 0:03:12]".to_owned()] + ); + assert!(with_text(&["plain".to_owned()], "").is_empty()); + assert_eq!(with_text(&[], "a"), vec!["a".to_owned()]); + } + + #[test] + fn with_shapes_replaces_board_commands_only() { + let c = vec![ + "ТекÑ�Ñ‚ [%cal Gf3d5] [%clk 0:03:12]".to_owned(), + "[%csl Ra6]".to_owned(), + ]; + let (arrows, squares) = shapes(&c); + assert_eq!(arrows.len(), 1); + assert_eq!(squares.len(), 1); + let out = with_shapes(&c, &[(ShapeColor::Red, Square::E2, Square::E4)], &[]); + assert_eq!(out, vec!["ТекÑ�Ñ‚ [%clk 0:03:12] [%cal Re2e4]".to_owned()]); + assert_eq!( + with_shapes(&c, &[], &[]), + vec!["ТекÑ�Ñ‚ [%clk 0:03:12]".to_owned()] + ); + } +} diff --git a/crates/chess-core/src/database.rs b/crates/chess-core/src/database.rs new file mode 100644 index 0000000..34678df --- /dev/null +++ b/crates/chess-core/src/database.rs @@ -0,0 +1,414 @@ +//! A PGN source: original bytes, encoding, index and lazy parsing. +//! +//! Reading never writes the file. Writing a record into it is a separate explicit +//! operation (`crate::pgn::store`), and the file is read again after it. + +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; +use std::time::SystemTime; + +use crate::encoding::{EncodingGuess, TextEncoding, decode_text, detect_encoding}; +use crate::pgn::{ + Cancelled, GameEntry, ParseOptions, ParsedGame, ScanProgress, parse_game_range_with, scan_games, +}; +use crate::repair::{LetterRepairDetection, detect_letter_substitution}; + +#[derive(Debug, thiserror::Error)] +pub enum OpenError { + #[error("cannot read {path}: {source}")] + Io { + path: PathBuf, + #[source] + source: io::Error, + }, + #[error("import cancelled")] + Cancelled, +} + +impl From for OpenError { + fn from(_: Cancelled) -> Self { + OpenError::Cancelled + } +} + +/// What reading a database's text found: everything of a [`PgnDatabase`] but the text. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PgnIndex { + detected: EncodingGuess, + encoding: TextEncoding, + entries: Vec, + content_hash: u64, + letter_repair: LetterRepairDetection, + repair_letters: bool, +} + +/// Identity of the source content, for change detection and cache keys. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct SourceFingerprint { + pub len: u64, + pub modified: Option, + /// FNV-1a 64 of the content (stable across runs and platforms). + pub content_hash: u64, +} + +fn fnv1a(bytes: &[u8]) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in bytes { + h ^= u64::from(*b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// An opened PGN file (or in-memory text). `Send + Sync`; open it on a +/// background thread and move it to the UI. +#[derive(Clone, Debug)] +pub struct PgnDatabase { + path: Option, + bytes: Vec, + detected: EncodingGuess, + encoding: TextEncoding, + entries: Vec, + fingerprint: SourceFingerprint, + letter_repair: LetterRepairDetection, + repair_letters: bool, +} + +impl PgnDatabase { + /// Reads and indexes a file. Progress/cancellation as in [`scan_games`]. + pub fn open( + path: &Path, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, + ) -> Result { + let io_err = |source| OpenError::Io { + path: path.to_owned(), + source, + }; + // The time first: a write that lands while the bytes are read is then seen as + // a change (the time moved on). + let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok(); + let bytes = std::fs::read(path).map_err(io_err)?; + let mut db = Self::from_bytes(bytes, None, progress, cancel)?; + db.path = Some(path.to_owned()); + db.fingerprint.modified = modified; + Ok(db) + } + + /// Indexes in-memory content. `encoding: None` = auto-detect. + pub fn from_bytes( + bytes: Vec, + encoding: Option, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, + ) -> Result { + let detected = detect_encoding(&bytes); + let encoding = encoding.unwrap_or(detected.encoding); + let entries = scan_games(&bytes, encoding, progress, cancel)?; + let letter_repair = detect_letter_substitution(&bytes, encoding); + let fingerprint = SourceFingerprint { + len: bytes.len() as u64, + modified: None, + content_hash: fnv1a(&bytes), + }; + Ok(PgnDatabase { + path: None, + bytes, + detected, + encoding, + entries, + fingerprint, + letter_repair, + repair_letters: letter_repair.detected, + }) + } + + /// The database taken apart: its text and its index (to rebuild it elsewhere — + /// the web version reads a database in a worker and gives it to the page). + pub fn into_index(self) -> (Vec, PgnIndex) { + let index = PgnIndex { + detected: self.detected, + encoding: self.encoding, + entries: self.entries, + content_hash: self.fingerprint.content_hash, + letter_repair: self.letter_repair, + repair_letters: self.repair_letters, + }; + (self.bytes, index) + } + + /// The database again from its text and the index [`Self::into_index`] gave, + /// without reading the text once more. + pub fn from_index(bytes: Vec, index: PgnIndex) -> Self { + PgnDatabase { + path: None, + fingerprint: SourceFingerprint { + len: bytes.len() as u64, + modified: None, + content_hash: index.content_hash, + }, + bytes, + detected: index.detected, + encoding: index.encoding, + entries: index.entries, + letter_repair: index.letter_repair, + repair_letters: index.repair_letters, + } + } + + pub fn path(&self) -> Option<&Path> { + self.path.as_deref() + } + + pub fn entries(&self) -> &[GameEntry] { + &self.entries + } + + /// The file's bytes as read. + pub fn bytes(&self) -> &[u8] { + &self.bytes + } + + /// Size of the PGN text, in bytes. + pub fn byte_len(&self) -> usize { + self.bytes.len() + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Encoding used for decoding text. + pub fn encoding(&self) -> TextEncoding { + self.encoding + } + + /// What auto-detection found. + pub fn detected_encoding(&self) -> &EncodingGuess { + &self.detected + } + + /// Re-decodes the index with a user-chosen encoding (source untouched). + pub fn set_encoding( + &mut self, + encoding: TextEncoding, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, + ) -> Result<(), Cancelled> { + let entries = scan_games(&self.bytes, encoding, progress, cancel)?; + self.entries = entries; + self.encoding = encoding; + self.letter_repair = detect_letter_substitution(&self.bytes, encoding); + self.repair_letters = self.letter_repair.detected; + Ok(()) + } + + /// Whether the source replaces «ч/Ч/ю» by `~~`/`><`/`o^` (see [`crate::repair`]). + pub fn letter_repair(&self) -> &LetterRepairDetection { + &self.letter_repair + } + + /// Repair applied by [`Self::load_game`]; defaults to the detection result. + pub fn repair_letters_enabled(&self) -> bool { + self.repair_letters + } + + /// Turns the letter repair on or off (affects subsequent `load_game`). + pub fn set_repair_letters(&mut self, enabled: bool) { + self.repair_letters = enabled; + } + + pub fn fingerprint(&self) -> &SourceFingerprint { + &self.fingerprint + } + + /// Whether the file on disk differs (size or mtime) from what was indexed. + pub fn source_changed(&self) -> io::Result { + let Some(path) = &self.path else { + return Ok(false); + }; + let meta = std::fs::metadata(path)?; + Ok(meta.len() != self.fingerprint.len || meta.modified().ok() != self.fingerprint.modified) + } + + /// Fully parses record `index`. + pub fn load_game(&self, index: usize) -> Option { + let e = self.entries.get(index)?; + Some(parse_game_range_with( + &self.bytes, + e.byte_range.clone(), + e.first_line, + self.encoding, + &ParseOptions { + repair_letters: self.repair_letters, + }, + )) + } + + /// Original bytes of record `index` (for "copy original" and diagnostics). + pub fn raw_bytes(&self, index: usize) -> Option<&[u8]> { + let e = self.entries.get(index)?; + self.bytes.get(e.byte_range.clone()) + } + + /// Original record decoded to Unicode (line endings normalized to LF). + pub fn raw_text(&self, index: usize) -> Option { + self.raw_bytes(index) + .map(|b| decode_text(self.encoding, b).0.trim_end().to_owned() + "\n") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A database taken apart and put together again is the same database. + #[test] + fn index_round_trip() { + let text = "[White \"A\"]\n[Black \"B\"]\n\n1. e4 e5 *\n\n[White \"C\"]\n\n1. d4 {x} *\n"; + let db = PgnDatabase::from_bytes( + text.as_bytes().to_vec(), + None, + &mut |_| {}, + &AtomicBool::new(false), + ) + .unwrap(); + let (entries, hash) = (db.entries().to_vec(), db.fingerprint.content_hash); + let (bytes, index) = db.into_index(); + let again = PgnDatabase::from_index(bytes, index); + assert_eq!(again.entries(), entries.as_slice()); + assert_eq!(again.fingerprint.content_hash, hash); + assert_eq!(again.bytes(), text.as_bytes()); + assert_eq!(again.load_game(1).unwrap().game.tag("White"), Some("C")); + } + + fn assert_send_sync() {} + + #[test] + fn database_is_send_sync() { + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + } + + #[test] + fn background_scan_with_progress_and_cancel() { + use std::sync::Arc; + let text: String = (0..3000) + .map(|i| format!("[Event \"{i}\"]\n\n1. e4 e5 *\n\n")) + .collect(); + let bytes = text.into_bytes(); + + let full = { + let bytes = bytes.clone(); + std::thread::spawn(move || { + let mut reports = Vec::new(); + let db = PgnDatabase::from_bytes( + bytes, + None, + &mut |p| reports.push(p), + &AtomicBool::new(false), + ); + (db.map(|d| d.len()).ok(), reports) + }) + .join() + .expect("thread") + }; + assert_eq!(full.0, Some(3000)); + assert!(full.1.len() >= 2); + assert!( + full.1 + .windows(2) + .all(|w| w[0].bytes_done <= w[1].bytes_done) + ); + assert_eq!(full.1.last().map(|p| p.games), Some(3000)); + + let cancel = Arc::new(AtomicBool::new(false)); + let c2 = Arc::clone(&cancel); + let r = std::thread::spawn(move || { + PgnDatabase::from_bytes( + bytes, + None, + &mut |_| c2.store(true, std::sync::atomic::Ordering::Relaxed), + &cancel, + ) + .map(|d| d.len()) + }) + .join() + .expect("thread"); + assert!(matches!(r, Err(OpenError::Cancelled))); + } + + #[test] + fn letter_repair_is_detected_and_switchable() { + let record = "[White \"><ерные\"]\n\n{><ерные играo^Ñ‚, ~~то делать ~~ерным?} 1. e4 *\n\n"; + let text = record.repeat(8); + let bytes = encoding_rs::WINDOWS_1251.encode(&text).0.into_owned(); + let mut db = + PgnDatabase::from_bytes(bytes.clone(), None, &mut |_| {}, &AtomicBool::new(false)) + .expect("db"); + assert_eq!(db.encoding(), TextEncoding::Windows1251); + assert!(db.letter_repair().detected); + assert!(db.repair_letters_enabled()); + let g = db.load_game(0).expect("game"); + assert_eq!( + g.game.node(g.game.root()).expect("root").comments_after(), + &["Черные играют, что делать черным?".to_owned()] + ); + assert!( + g.diagnostics + .iter() + .any(|d| d.code == crate::DiagnosticCode::LettersRestored) + ); + // Tags and raw text are not touched. + assert_eq!(g.game.tag("White"), Some("><ерные")); + assert!(db.raw_text(0).expect("raw").contains("{><ерные играo^Ñ‚")); + assert_eq!( + db.raw_bytes(0), + bytes.get(db.entries()[0].byte_range.clone()) + ); + + db.set_repair_letters(false); + let g = db.load_game(0).expect("game"); + assert_eq!( + g.game.node(g.game.root()).expect("root").comments_after(), + &["><ерные играo^Ñ‚, ~~то делать ~~ерным?".to_owned()] + ); + + // Same text in UTF-8: never repaired. + let db = PgnDatabase::from_bytes( + text.into_bytes(), + None, + &mut |_| {}, + &AtomicBool::new(false), + ) + .expect("db"); + assert!(!db.letter_repair().detected); + let g = db.load_game(0).expect("game"); + assert!(g.game.node(g.game.root()).expect("root").comments_after()[0].contains("~~")); + } + + #[test] + fn in_memory_database() { + let text = "[White \"Hübner\"]\n\n1. e4 *\n\n[White \"B\"]\n\n1. d4 *\n"; + let bytes: Vec = text + .chars() + .map(|c| if c == 'ü' { 0xFC } else { c as u8 }) + .collect(); + let db = + PgnDatabase::from_bytes(bytes, None, &mut |_| {}, &AtomicBool::new(false)).expect("db"); + assert_eq!(db.encoding(), TextEncoding::Windows1252); + assert_eq!(db.len(), 2); + assert_eq!(db.entries()[0].white(), Some("Hübner")); + let g = db.load_game(1).expect("game"); + assert_eq!(g.game.mainline().len(), 1); + assert!(db.raw_text(0).expect("raw").contains("1. e4")); + assert!(db.load_game(5).is_none()); + } +} diff --git a/crates/chess-core/src/diagnostic.rs b/crates/chess-core/src/diagnostic.rs new file mode 100644 index 0000000..f94a82a --- /dev/null +++ b/crates/chess-core/src/diagnostic.rs @@ -0,0 +1,89 @@ +//! Import diagnostics. + +use std::fmt; + +use crate::game::NodeId; + +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Severity { + /// Tolerated deviation, data fully preserved (e.g. FEN fullmove 0). + Info, + /// Data preserved but changed in form or placement (e.g. stray text kept as comment). + Warning, + /// Data could not be interpreted as chess (e.g. illegal move); raw text kept. + Error, +} + +/// Machine-readable diagnostic kind; UI localizes by code, `message` gives details. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum DiagnosticCode { + /// UTF-8 decoding produced replacement characters. + DecodeError, + MalformedTag, + DuplicateTag, + /// FEN with fullmove number 0, normalized to 1 (original tag kept). + FenFullmoveZero, + /// FEN tag without `SetUp "1"`; FEN used anyway. + FenWithoutSetUp, + /// `SetUp "1"` without FEN; standard start position used. + SetUpWithoutFen, + /// FEN repaired (invalid castling rights/en passant square dropped, etc.). + FenRepaired, + /// FEN cannot be used; movetext preserved as raw text. + InvalidFen, + UnsupportedVariant, + /// Illegal or ambiguous SAN, or `--` while in check; the rest of the + /// branch is kept as raw text. + IllegalMove, + /// Text outside comments that is not PGN; kept as a comment. + UnrecognizedText, + /// `}` outside a comment; dropped. + StrayClosingBrace, + UnterminatedComment, + UnmatchedCloseParen, + UnclosedVariation, + /// `(` before any move; content kept as raw text. + VariationWithoutMove, + EmptyVariation, + /// `%` escape line, ignored per PGN standard. + EscapeLine, + ResultInVariation, + ResultMismatch, + MissingResult, + /// Letters replaced by ASCII sequences in the source (`~~`, `><`, `o^`) + /// were restored in comments; counts in `message`. + LettersRestored, + /// Annotation could not be placed in its original position. + CommentMoved, + /// The game was converted from another format (ChessBase) and could only be + /// read in part; details in `message`. + PartlyConverted, +} + +/// Position in the source. Offsets are bytes of the original file. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct SourceLocation { + pub byte_offset: usize, + /// 1-based line in the original file. + pub line: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnostic { + pub severity: Severity, + pub code: DiagnosticCode, + pub message: String, + pub location: Option, + /// Node the diagnostic is attached to (e.g. where recovered text was stored). + pub node: Option, +} + +impl fmt::Display for Diagnostic { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?} {:?}", self.severity, self.code)?; + if let Some(loc) = self.location { + write!(f, " at line {} (byte {})", loc.line, loc.byte_offset)?; + } + write!(f, ": {}", self.message) + } +} diff --git a/crates/chess-core/src/edit.rs b/crates/chess-core/src/edit.rs new file mode 100644 index 0000000..bb1ffdc --- /dev/null +++ b/crates/chess-core/src/edit.rs @@ -0,0 +1,602 @@ +//! Tree editing with undo/redo. +//! +//! Every edit is a [`Command`] that only re-links existing arena nodes, so +//! `NodeId`s stay valid across undo/redo. Viewing an engine line never edits the +//! game; inserting it is an explicit [`Game::add_line`] with its own undo step. + +use shakmaty::{CastlingMode, Move, Position, san::SanPlus, uci::UciMove}; + +use crate::game::{Game, GameMove, MoveKind, NodeId}; +use crate::nag::Nag; + +/// NAGs and comments of a node (what annotation edits change). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Annotations { + nags: Vec, + comments_before: Vec, + comments_after: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Command { + Attach { + parent: NodeId, + child: NodeId, + index: usize, + }, + Detach { + parent: NodeId, + child: NodeId, + index: usize, + }, + Reorder { + parent: NodeId, + from: usize, + to: usize, + }, + Annotate { + node: NodeId, + old: Annotations, + new: Annotations, + }, + /// Several commands undone and redone as one step. + Group(Vec), +} + +impl Command { + fn inverse(&self) -> Command { + match self { + &Command::Attach { + parent, + child, + index, + } => Command::Detach { + parent, + child, + index, + }, + &Command::Detach { + parent, + child, + index, + } => Command::Attach { + parent, + child, + index, + }, + &Command::Reorder { parent, from, to } => Command::Reorder { + parent, + from: to, + to: from, + }, + Command::Annotate { node, old, new } => Command::Annotate { + node: *node, + old: new.clone(), + new: old.clone(), + }, + Command::Group(cmds) => { + Command::Group(cmds.iter().rev().map(Command::inverse).collect()) + } + } + } + + /// Node the UI should select after this command has been applied. + fn cursor(&self, game: &Game) -> NodeId { + match self { + &Command::Attach { child, .. } => child, + &Command::Detach { parent, .. } => parent, + &Command::Reorder { parent, to, .. } => { + game.children(parent).get(to).copied().unwrap_or(parent) + } + Command::Annotate { node, .. } => *node, + Command::Group(cmds) => cmds.first().map_or(NodeId::ROOT, |c| c.cursor(game)), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum EditError { + #[error("unknown node")] + UnknownNode, + #[error("node is not part of the current tree")] + DetachedNode, + #[error("illegal move {0}")] + IllegalMove(String), + #[error("the root cannot be removed")] + RootNotRemovable, + #[error("node is already on the main line of its parent")] + AlreadyMain, + #[error("empty line")] + EmptyLine, + #[error("invalid UCI move {0}")] + InvalidUci(String), +} + +/// Result of undo/redo: the node to select. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct EditOutcome { + pub cursor: NodeId, +} + +impl Game { + fn check_attached(&self, id: NodeId) -> Result<(), EditError> { + match self.node(id) { + None => Err(EditError::UnknownNode), + Some(n) if !n.attached => Err(EditError::DetachedNode), + Some(_) => Ok(()), + } + } + + /// Existing child of `at` reached by `m`. + pub fn find_child(&self, at: NodeId, m: Move) -> Option { + self.children(at) + .iter() + .copied() + .find(|c| matches!(self.game_move(*c), Some(GameMove { kind: MoveKind::Normal(x), .. }) if *x == m)) + } + + /// Plays `m` from `at`. If that continuation exists, returns it (no edit); + /// otherwise appends a new branch (main line if `at` has no children). + pub fn add_move(&mut self, at: NodeId, m: Move) -> Result { + self.add_line(at, &[m]) + } + + /// Adds a line (e.g. an engine PV) from `at`, reusing existing continuations + /// and creating a new variation from the first new move. All moves are + /// validated first; on error nothing changes. One undo step. Returns the + /// last node of the line. + pub fn add_line(&mut self, at: NodeId, moves: &[Move]) -> Result { + self.check_attached(at)?; + if moves.is_empty() { + return Err(EditError::EmptyLine); + } + // Validate on a scratch position first. + let mut pos = self.position(at).ok_or(EditError::UnknownNode)?.clone(); + let mut prepared = Vec::with_capacity(moves.len()); + for &m in moves { + if !pos.is_legal(m) { + return Err(EditError::IllegalMove( + m.to_uci(CastlingMode::Standard).to_string(), + )); + } + let san = SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string(); + prepared.push((m, san, pos.clone())); + } + + let mut cur = at; + let mut iter = prepared.into_iter(); + let mut first_new = None; + for (m, san, position) in iter.by_ref() { + if let Some(existing) = self.find_child(cur, m) { + cur = existing; + continue; + } + let id = self.push_child( + cur, + GameMove { + kind: MoveKind::Normal(m), + san, + }, + position, + ); + first_new = Some((cur, id)); + cur = id; + break; + } + for (m, san, position) in iter { + cur = self.push_child( + cur, + GameMove { + kind: MoveKind::Normal(m), + san, + }, + position, + ); + } + if let Some((parent, child)) = first_new { + let index = self.child_index(child).unwrap_or(0); + self.record(Command::Attach { + parent, + child, + index, + }); + } + Ok(cur) + } + + /// Adds a line given in UCI notation (`["e2e4", "e7e5"]`). + pub fn add_uci_line>( + &mut self, + at: NodeId, + moves: &[S], + ) -> Result { + let mut pos = self.position(at).ok_or(EditError::UnknownNode)?.clone(); + let mut parsed = Vec::with_capacity(moves.len()); + for s in moves { + let s = s.as_ref(); + let uci: UciMove = s.parse().map_err(|_| EditError::InvalidUci(s.to_owned()))?; + let m = uci + .to_move(&pos) + .map_err(|_| EditError::IllegalMove(s.to_owned()))?; + pos.play_unchecked(m); + parsed.push(m); + } + self.add_line(at, &parsed) + } + + /// Removes `id` and everything after it from the tree. Returns the parent + /// (suggested new cursor). Undoable. + pub fn delete_variation(&mut self, id: NodeId) -> Result { + self.check_attached(id)?; + let parent = self.parent(id).ok_or(EditError::RootNotRemovable)?; + let index = self.child_index(id).ok_or(EditError::UnknownNode)?; + self.record(Command::Detach { + parent, + child: id, + index, + }); + Ok(parent) + } + + /// Makes the variation containing `id` the main continuation at its + /// branching point. Undoable. + pub fn promote_variation(&mut self, id: NodeId) -> Result<(), EditError> { + self.check_attached(id)?; + let start = self.variation_start(id).ok_or(EditError::AlreadyMain)?; + let parent = self.parent(start).ok_or(EditError::AlreadyMain)?; + let from = self.child_index(start).ok_or(EditError::UnknownNode)?; + self.record(Command::Reorder { + parent, + from, + to: 0, + }); + Ok(()) + } + + /// Replaces the NAGs and trailing comments of `id`. Undoable; no-op if unchanged. + pub fn annotate( + &mut self, + id: NodeId, + nags: Vec, + comments_after: Vec, + ) -> Result<(), EditError> { + self.check_attached(id)?; + let node = self.node(id).ok_or(EditError::UnknownNode)?; + let old = Annotations { + nags: node.nags.clone(), + comments_before: node.comments_before.clone(), + comments_after: node.comments_after.clone(), + }; + let new = Annotations { + nags, + comments_before: old.comments_before.clone(), + comments_after, + }; + if old != new { + self.record(Command::Annotate { node: id, old, new }); + } + Ok(()) + } + + /// Replaces the comments before the move of `id` (an introduction to a line). + /// Undoable; no-op if unchanged. + pub fn set_comments_before( + &mut self, + id: NodeId, + comments_before: Vec, + ) -> Result<(), EditError> { + self.check_attached(id)?; + let node = self.node(id).ok_or(EditError::UnknownNode)?; + let old = Annotations { + nags: node.nags.clone(), + comments_before: node.comments_before.clone(), + comments_after: node.comments_after.clone(), + }; + let new = Annotations { + nags: old.nags.clone(), + comments_before, + comments_after: old.comments_after.clone(), + }; + if old != new { + self.record(Command::Annotate { node: id, old, new }); + } + Ok(()) + } + + /// Runs `f` so that all its edits form a single undo step. + pub fn edit_group(&mut self, f: impl FnOnce(&mut Game) -> R) -> R { + let outer = self.group.replace(Vec::new()); + let result = f(self); + let cmds = std::mem::replace(&mut self.group, outer).unwrap_or_default(); + if !cmds.is_empty() { + match &mut self.group { + Some(parent) => parent.push(Command::Group(cmds)), + None => self.push_undo(Command::Group(cmds)), + } + } + result + } + + pub fn can_undo(&self) -> bool { + !self.undo_stack.is_empty() + } + + pub fn can_redo(&self) -> bool { + !self.redo_stack.is_empty() + } + + pub fn undo(&mut self) -> Option { + let cmd = self.undo_stack.pop()?; + let inv = cmd.inverse(); + self.apply(&inv); + let cursor = inv.cursor(self); + self.redo_stack.push(cmd); + self.touch(); + Some(EditOutcome { cursor }) + } + + pub fn redo(&mut self) -> Option { + let cmd = self.redo_stack.pop()?; + self.apply(&cmd); + let cursor = cmd.cursor(self); + self.undo_stack.push(cmd); + self.touch(); + Some(EditOutcome { cursor }) + } + + /// Applies a new command (the Attach of a freshly pushed node is already + /// linked by `push_child`, so it is only recorded). + pub(crate) fn record(&mut self, cmd: Command) { + if !matches!(cmd, Command::Attach { .. }) { + self.apply(&cmd); + } + if let Some(group) = &mut self.group { + group.push(cmd); + self.touch(); + return; + } + self.push_undo(cmd); + } + + fn push_undo(&mut self, cmd: Command) { + if self.saved_depth.is_some_and(|d| d > self.undo_stack.len()) { + // The saved state lived in the redo stack, which is discarded now. + self.saved_depth = None; + } + self.undo_stack.push(cmd); + self.redo_stack.clear(); + self.touch(); + } + + fn apply(&mut self, cmd: &Command) { + match cmd { + Command::Annotate { node, new, .. } => { + if let Some(n) = self.node_mut(*node) { + n.nags.clone_from(&new.nags); + n.comments_before.clone_from(&new.comments_before); + n.comments_after.clone_from(&new.comments_after); + } + return; + } + Command::Group(cmds) => { + for c in cmds { + self.apply(c); + } + return; + } + _ => {} + } + match *cmd { + Command::Attach { + parent, + child, + index, + } => { + if let Some(p) = self.node_mut(parent) { + let i = index.min(p.children.len()); + if !p.children.contains(&child) { + p.children.insert(i, child); + } + } + self.set_attached(child, true); + } + Command::Detach { parent, child, .. } => { + if let Some(p) = self.node_mut(parent) { + p.children.retain(|c| *c != child); + } + self.set_attached(child, false); + } + Command::Reorder { parent, from, to } => { + if let Some(p) = self.node_mut(parent) + && from < p.children.len() + && to < p.children.len() + { + let c = p.children.remove(from); + p.children.insert(to, c); + } + } + Command::Annotate { .. } | Command::Group(_) => {} + } + } + + fn set_attached(&mut self, id: NodeId, attached: bool) { + let mut stack = vec![id]; + while let Some(n) = stack.pop() { + if let Some(node) = self.node_mut(n) { + node.attached = attached; + stack.extend(node.children.iter().copied()); + } + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn modified_flag_follows_undo_to_saved_state() { + use shakmaty::{Position, uci::UciMove}; + let mut g = crate::Game::new(); + assert!(!g.is_modified()); + let mv = |g: &crate::Game, at, u: &str| { + u.parse::() + .ok() + .and_then(|m| m.to_move(g.position(at)?).ok()) + .expect("legal") + }; + let m = mv(&g, NodeId::ROOT, "e2e4"); + let a = g.add_move(NodeId::ROOT, m).expect("add"); + assert!(g.is_modified()); + g.undo(); + assert!(!g.is_modified(), "undo back to the imported state"); + g.redo(); + g.mark_saved(); + assert!(!g.is_modified()); + g.undo(); + assert!(g.is_modified()); + // New edit after undoing past the saved point: saved state is unreachable. + let m = mv(&g, NodeId::ROOT, "d2d4"); + g.add_move(NodeId::ROOT, m).expect("add"); + g.undo(); + assert!(g.is_modified()); + let _ = (a, g.position(NodeId::ROOT).map(|p| p.turn())); + } + + use super::*; + + fn uci(g: &Game, at: NodeId, s: &str) -> Move { + let u: UciMove = s.parse().expect("uci"); + u.to_move(g.position(at).expect("node")).expect("legal") + } + + #[test] + fn add_move_reuses_existing_and_branches() { + let mut g = Game::new(); + let e4 = g.add_move(g.root(), uci(&g, g.root(), "e2e4")).expect("e4"); + let again = g.add_move(g.root(), uci(&g, g.root(), "e2e4")).expect("e4"); + assert_eq!(e4, again); + assert_eq!(g.undo_stack.len(), 1); + let d4 = g.add_move(g.root(), uci(&g, g.root(), "d2d4")).expect("d4"); + assert_eq!(g.children(g.root()), &[e4, d4]); + assert_eq!(g.game_move(d4).map(|m| m.san.as_str()), Some("d4")); + assert!(g.add_move(e4, uci(&g, g.root(), "d2d4")).is_err()); + } + + #[test] + fn undo_redo_delete_promote() { + let mut g = Game::new(); + let e4 = g + .add_uci_line(g.root(), &["e2e4", "e7e5", "g1f3"]) + .expect("line"); + let c5 = g + .add_uci_line(g.root(), &["e2e4", "c7c5"]) + .expect("variation"); + let first = g.main_child(g.root()).expect("first"); + let e5 = g.main_child(first).expect("e5"); + assert_eq!(g.children(first).len(), 2); + assert_eq!(g.variation_start(c5), Some(c5)); + + g.promote_variation(c5).expect("promote"); + assert_eq!(g.main_child(first), Some(c5)); + assert!(g.is_mainline(c5)); + g.undo(); + assert_eq!(g.main_child(first), Some(e5)); + + let cursor = g.delete_variation(e5).expect("delete"); + assert_eq!(cursor, first); + assert!(!g.is_attached(e4)); + assert_eq!(g.children(first), &[c5]); + let out = g.undo().expect("undo"); + assert_eq!(out.cursor, e5); + assert!(g.is_attached(e4)); + assert_eq!(g.children(first), &[e5, c5]); + g.redo(); + assert!(!g.is_attached(e4)); + g.undo(); + // Undo the c5 insertion, then the first line. + g.undo(); + g.undo(); + assert_eq!(g.children(g.root()), &[] as &[NodeId]); + assert!(!g.can_undo()); + g.redo(); + assert_eq!(g.mainline().len(), 3); + assert!(g.is_modified()); + } + + #[test] + fn add_line_is_atomic() { + let mut g = Game::new(); + let err = g.add_uci_line(g.root(), &["e2e4", "e2e4"]); + assert!(err.is_err()); + assert_eq!(g.arena_len(), 1); + assert!(!g.can_undo()); + } + + #[test] + fn cannot_edit_detached() { + let mut g = Game::new(); + let e4 = g.add_uci_line(g.root(), &["e2e4"]).expect("e4"); + g.delete_variation(e4).expect("delete"); + let m = uci(&g, e4, "e7e5"); + assert_eq!(g.add_move(e4, m), Err(EditError::DetachedNode)); + assert_eq!( + g.delete_variation(g.root()), + Err(EditError::RootNotRemovable) + ); + } + + #[test] + fn annotate_is_undoable() { + let mut g = Game::new(); + let e4 = g.add_uci_line(g.root(), &["e2e4"]).expect("e4"); + g.mark_saved(); + g.annotate(e4, vec![Nag::GOOD_MOVE], vec!["[%eval 0.3]".into()]) + .expect("annotate"); + assert_eq!( + g.node(e4).map(|n| n.nags().to_vec()), + Some(vec![Nag::GOOD_MOVE]) + ); + assert!(g.is_modified()); + // Unchanged annotations do not create an undo step. + let depth = g.undo_stack.len(); + g.annotate(e4, vec![Nag::GOOD_MOVE], vec!["[%eval 0.3]".into()]) + .expect("same"); + assert_eq!(g.undo_stack.len(), depth); + assert_eq!(g.undo().map(|o| o.cursor), Some(e4)); + assert!( + g.node(e4) + .is_some_and(|n| n.nags().is_empty() && n.comments_after().is_empty()) + ); + assert!(!g.is_modified()); + g.redo(); + assert_eq!(g.node(e4).map(|n| n.comments_after().len()), Some(1)); + } + + #[test] + fn edit_group_is_one_undo_step() { + let mut g = Game::new(); + let end = g + .add_uci_line(g.root(), &["e2e4", "e7e5", "g1f3"]) + .expect("line"); + let e4 = g.main_child(g.root()).expect("e4"); + let e5 = g.main_child(e4).expect("e5"); + let before = g.canonical_tree(); + let steps = g.undo_stack.len(); + g.edit_group(|g| { + g.annotate(e5, vec![Nag::MISTAKE], vec!["better c5".into()]) + .expect("annotate"); + g.add_uci_line(e4, &["c7c5", "g1f3"]).expect("variation"); + g.edit_group(|g| g.annotate(end, vec![Nag::DUBIOUS_MOVE], Vec::new())) + .expect("nested"); + }); + assert_eq!(g.undo_stack.len(), steps + 1); + assert_eq!(g.children(e4).len(), 2); + let after = g.canonical_tree(); + g.undo(); + assert_eq!(g.canonical_tree(), before); + g.redo(); + assert_eq!(g.canonical_tree(), after); + // An empty group records nothing. + g.edit_group(|_| ()); + assert_eq!(g.undo_stack.len(), steps + 1); + } +} diff --git a/crates/chess-core/src/encoding.rs b/crates/chess-core/src/encoding.rs new file mode 100644 index 0000000..19fa4bb --- /dev/null +++ b/crates/chess-core/src/encoding.rs @@ -0,0 +1,223 @@ +//! Text encoding detection and decoding for PGN sources. +//! +//! The scanner works on raw bytes: all supported encodings are ASCII-compatible, +//! so PGN structure (`[`, `]`, `"`, `{`, `}`, `(`, `)`, newlines) is located in the +//! original bytes and byte offsets always refer to the original file. Only text +//! payloads (tag values, comments) are decoded. + +use std::borrow::Cow; + +/// Encodings supported for PGN sources. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum TextEncoding { + Utf8, + /// Cyrillic Windows code page (observed in the Dvoretsky textbook). + Windows1251, + Koi8R, + /// DOS Cyrillic. + Ibm866, + /// Western Windows code page. ISO-8859-1 text decodes identically for all + /// printable characters, so the two cannot be distinguished. + Windows1252, +} + +impl TextEncoding { + pub const ALL: [TextEncoding; 5] = [ + TextEncoding::Utf8, + TextEncoding::Windows1251, + TextEncoding::Koi8R, + TextEncoding::Ibm866, + TextEncoding::Windows1252, + ]; + + fn encoding(self) -> &'static encoding_rs::Encoding { + match self { + TextEncoding::Utf8 => encoding_rs::UTF_8, + TextEncoding::Windows1251 => encoding_rs::WINDOWS_1251, + TextEncoding::Koi8R => encoding_rs::KOI8_R, + TextEncoding::Ibm866 => encoding_rs::IBM866, + TextEncoding::Windows1252 => encoding_rs::WINDOWS_1252, + } + } + + /// Stable label for settings/UI. + pub fn label(self) -> &'static str { + match self { + TextEncoding::Utf8 => "UTF-8", + TextEncoding::Windows1251 => "windows-1251", + TextEncoding::Koi8R => "KOI8-R", + TextEncoding::Ibm866 => "IBM866", + TextEncoding::Windows1252 => "windows-1252", + } + } + + pub fn from_label(label: &str) -> Option { + TextEncoding::ALL + .into_iter() + .find(|e| e.label().eq_ignore_ascii_case(label)) + } + + /// Decodes bytes; returns the text and whether replacement characters were + /// inserted (only possible for UTF-8). A BOM is not stripped here. + pub fn decode(self, bytes: &[u8]) -> (Cow<'_, str>, bool) { + self.encoding().decode_without_bom_handling(bytes) + } +} + +/// How sure the detector is. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Confidence { + /// Valid UTF-8 (or pure ASCII), or a UTF-8 BOM. + Certain, + /// Heuristic choice among legacy code pages; the UI should allow override. + Likely, +} + +/// Result of [`detect_encoding`]. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EncodingGuess { + pub encoding: TextEncoding, + pub confidence: Confidence, + /// File starts with a UTF-8 BOM (3 bytes, skipped by the scanner). + pub has_bom: bool, + /// File contains only ASCII bytes. + pub ascii_only: bool, + /// Number of bytes >= 0x80 in the sample. + pub non_ascii_bytes: usize, +} + +const SAMPLE_LIMIT: usize = 512 * 1024; + +/// Detects the most plausible encoding. +/// +/// Policy: BOM → UTF-8; strict UTF-8 → UTF-8; otherwise a legacy code page is +/// chosen heuristically: isolated high bytes between ASCII letters indicate a +/// Western code page (windows-1252), runs of high bytes indicate Cyrillic, and +/// among Cyrillic code pages the one yielding mostly lowercase Cyrillic letters +/// wins (wrong Cyrillic decodings produce mostly uppercase or box drawing). +pub fn detect_encoding(bytes: &[u8]) -> EncodingGuess { + let has_bom = bytes.starts_with(b"\xEF\xBB\xBF"); + let non_ascii_bytes = bytes.iter().filter(|b| **b >= 0x80).count(); + if has_bom { + return EncodingGuess { + encoding: TextEncoding::Utf8, + confidence: Confidence::Certain, + has_bom, + ascii_only: false, + non_ascii_bytes, + }; + } + if std::str::from_utf8(bytes).is_ok() { + return EncodingGuess { + encoding: TextEncoding::Utf8, + confidence: Confidence::Certain, + has_bom, + ascii_only: non_ascii_bytes == 0, + non_ascii_bytes, + }; + } + + let sample = &bytes[..bytes.len().min(SAMPLE_LIMIT)]; + let mut high = 0usize; + let mut high_adjacent = 0usize; + for (i, b) in sample.iter().enumerate() { + if *b >= 0x80 { + high += 1; + let prev = i.checked_sub(1).and_then(|p| sample.get(p)); + let next = sample.get(i + 1); + if prev.is_some_and(|p| *p >= 0x80) || next.is_some_and(|n| *n >= 0x80) { + high_adjacent += 1; + } + } + } + + let encoding = if high_adjacent * 2 < high { + TextEncoding::Windows1252 + } else { + [ + TextEncoding::Windows1251, + TextEncoding::Koi8R, + TextEncoding::Ibm866, + ] + .into_iter() + .max_by_key(|enc| cyrillic_score(&enc.decode(sample).0)) + .unwrap_or(TextEncoding::Windows1251) + }; + + EncodingGuess { + encoding, + confidence: Confidence::Likely, + has_bom, + ascii_only: false, + non_ascii_bytes, + } +} + +fn cyrillic_score(text: &str) -> i64 { + let mut score = 0i64; + for ch in text.chars() { + match ch { + 'а'..='Ñ�' | 'Ñ‘' => score += 2, + 'Ð�'..='Я' | 'Ð�' => score -= 1, + c if !c.is_ascii() => score -= 3, + _ => {} + } + } + score +} + +/// Decodes a payload (tag value or comment): replaces CRLF/CR by LF. +pub(crate) fn decode_text(encoding: TextEncoding, bytes: &[u8]) -> (String, bool) { + let (text, had_errors) = encoding.decode(bytes); + let text = if text.contains('\r') { + text.replace("\r\n", "\n").replace('\r', "\n") + } else { + text.into_owned() + }; + (text, had_errors) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_utf8_and_bom() { + let g = detect_encoding("[White \"Иванов\"]".as_bytes()); + assert_eq!(g.encoding, TextEncoding::Utf8); + assert_eq!(g.confidence, Confidence::Certain); + let g = detect_encoding(b"\xEF\xBB\xBF[White \"x\"]"); + assert!(g.has_bom); + assert_eq!(g.encoding, TextEncoding::Utf8); + assert!(detect_encoding(b"1. e4 e5").ascii_only); + } + + #[test] + fn detects_cyrillic_code_pages() { + let text = "{При пешке на пÑ�той горизонтали ключевыми Ñ�влÑ�ÑŽÑ‚Ñ�Ñ� полÑ�} 1. e4 *"; + for enc in [ + TextEncoding::Windows1251, + TextEncoding::Koi8R, + TextEncoding::Ibm866, + ] { + let (bytes, _, _) = enc.encoding().encode(text); + assert_eq!(detect_encoding(&bytes).encoding, enc, "{enc:?}"); + } + } + + #[test] + fn detects_western() { + let bytes = b"[White \"H\xFCbner, R.\"]\n[Site \"Troms\xF8\"]\n1. e4 *"; + assert_eq!(detect_encoding(bytes).encoding, TextEncoding::Windows1252); + } + + #[test] + fn decode_text_normalizes_newlines() { + let (t, err) = decode_text(TextEncoding::Utf8, b"a\r\nb\rc"); + assert_eq!(t, "a\nb\nc"); + assert!(!err); + } +} diff --git a/crates/chess-core/src/game.rs b/crates/chess-core/src/game.rs new file mode 100644 index 0000000..436cb99 --- /dev/null +++ b/crates/chess-core/src/game.rs @@ -0,0 +1,694 @@ +//! Game document: tags, start position and the move tree. + +use shakmaty::{ + CastlingMode, Chess, Color, EnPassantMode, FromSetup, Move, Position, fen::Fen, san::SanPlus, +}; + +use crate::edit::Command; +use crate::nag::Nag; +use crate::start::StartPosition; + +/// Stable node identifier inside one [`Game`]. Never reused: deleting a +/// variation detaches nodes but keeps their ids valid (needed for undo/redo). +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct NodeId(u32); + +impl NodeId { + /// The root (start position, no move). + pub const ROOT: NodeId = NodeId(0); + + pub fn index(self) -> usize { + self.0 as usize + } +} + +/// What was played to reach a node. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum MoveKind { + /// A legal move in the parent position. + Normal(Move), + /// Teaching null move `--` (side to move passes). Not a legal chess move: + /// never generated by user move input; histories containing it are not + /// ordinary games (see [`Game::engine_history`]). + Null, +} + +/// A move with its display SAN (`"Nf3+"`, `"O-O"`, `"--"`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct GameMove { + pub kind: MoveKind, + pub san: String, +} + +impl GameMove { + pub fn is_null(&self) -> bool { + matches!(self.kind, MoveKind::Null) + } + + /// UCI notation (`e1g1` for castling), `None` for a null move. + pub fn uci(&self) -> Option { + match self.kind { + MoveKind::Normal(m) => Some(m.to_uci(CastlingMode::Standard).to_string()), + MoveKind::Null => None, + } + } +} + +/// Game termination marker. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum GameResult { + WhiteWins, + BlackWins, + Draw, + Unknown, +} + +impl GameResult { + pub fn as_str(self) -> &'static str { + match self { + GameResult::WhiteWins => "1-0", + GameResult::BlackWins => "0-1", + GameResult::Draw => "1/2-1/2", + GameResult::Unknown => "*", + } + } + + pub fn from_pgn(s: &str) -> Option { + Some(match s.trim() { + "1-0" => GameResult::WhiteWins, + "0-1" => GameResult::BlackWins, + "1/2-1/2" | "½-½" => GameResult::Draw, + "*" => GameResult::Unknown, + _ => return None, + }) + } +} + +/// A node of the move tree. The root has no move. +#[derive(Clone, Debug)] +pub struct Node { + pub(crate) parent: Option, + pub(crate) children: Vec, + pub(crate) mv: Option, + pub(crate) position: Chess, + pub(crate) ply: u32, + pub(crate) attached: bool, + pub(crate) nags: Vec, + pub(crate) comments_before: Vec, + pub(crate) comments_after: Vec, + pub(crate) unparsed: Vec, +} + +impl Node { + pub fn parent(&self) -> Option { + self.parent + } + /// Continuations; the first is the main line, others are variations. + pub fn children(&self) -> &[NodeId] { + &self.children + } + /// `None` only for the root. + pub fn game_move(&self) -> Option<&GameMove> { + self.mv.as_ref() + } + /// Position after this node's move. + pub fn position(&self) -> &Chess { + &self.position + } + /// Half-moves from the start position. + pub fn ply(&self) -> u32 { + self.ply + } + pub fn nags(&self) -> &[Nag] { + &self.nags + } + /// Comments printed before the move (e.g. the starting comment of a variation). + pub fn comments_before(&self) -> &[String] { + &self.comments_before + } + /// Comments after the move. For the root: the game's starting comment. + pub fn comments_after(&self) -> &[String] { + &self.comments_after + } + /// Raw PGN text that could not be interpreted (e.g. the rest of a branch + /// after an illegal move). Written back verbatim on export. + pub fn unparsed(&self) -> &[String] { + &self.unparsed + } + pub fn is_attached(&self) -> bool { + self.attached + } +} + +/// Starting point and moves for a UCI `position` command. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EngineHistory { + /// `None` = `startpos`; otherwise a normalized FEN (fullmove ≥ 1). + pub start_fen: Option, + /// UCI moves from `start_fen` to the node. + pub moves: Vec, + /// Normalized FEN of the node's position (fallback). + pub current_fen: String, + pub kind: HistoryKind, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum HistoryKind { + /// Real move history from the game's start position. + Complete, + /// The path contains teaching null moves. `start_fen` is the position right + /// after the last null move and `moves` follow it; earlier history is not + /// sent because it is not an ordinary game. + AfterNullMove { null_moves: usize }, +} + +/// Position after a teaching null move: side to move passes, en passant is +/// cleared, halfmove clock and (after Black) fullmove number advance. +/// Fails if the side to move is in check. +pub(crate) fn play_null(pos: &Chess) -> Result { + let mut setup = pos.to_setup(EnPassantMode::Legal); + let was_black = setup.turn == Color::Black; + setup.swap_turn(); + setup.halfmoves = setup.halfmoves.saturating_add(1); + if was_black { + setup.fullmoves = setup.fullmoves.saturating_add(1); + } + Chess::from_setup(setup, CastlingMode::Standard).map_err(|e| e.to_string()) +} + +/// A chess game document. +#[derive(Clone, Debug)] +pub struct Game { + pub(crate) tags: Vec<(String, String)>, + pub(crate) start: StartPosition, + pub(crate) nodes: Vec, + pub(crate) result: Option, + pub(crate) undo_stack: Vec, + pub(crate) redo_stack: Vec, + pub(crate) revision: u64, + /// Undo-stack depth at the last save; `None` once that state is unreachable + /// (a new edit was made after undoing past it). + pub(crate) saved_depth: Option, + /// Changes outside the undo history (tags, result) since the last save. + pub(crate) unsaved_meta: bool, + /// Commands collected by an open [`Game::edit_group`]. + pub(crate) group: Option>, +} + +impl Default for Game { + fn default() -> Self { + Self::new() + } +} + +const SEVEN_TAG_ROSTER: [(&str, &str); 7] = [ + ("Event", "?"), + ("Site", "?"), + ("Date", "????.??.??"), + ("Round", "?"), + ("White", "?"), + ("Black", "?"), + ("Result", "*"), +]; + +impl Game { + /// New game from the standard position with the Seven Tag Roster. + pub fn new() -> Self { + let mut g = Self::with_start(StartPosition::standard(), Vec::new()); + g.tags = SEVEN_TAG_ROSTER + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + g + } + + /// New game from an arbitrary position (adds `SetUp`/`FEN` tags if not standard). + pub fn from_start(start: StartPosition) -> Self { + let mut g = Self::new(); + if let Some(fen) = start.original_fen() { + g.tags.push(("SetUp".into(), "1".into())); + g.tags.push(("FEN".into(), fen.to_owned())); + } + g.reset_root(start); + g + } + + pub(crate) fn with_start(start: StartPosition, tags: Vec<(String, String)>) -> Self { + let root = Node { + parent: None, + children: Vec::new(), + mv: None, + position: start.position().clone(), + ply: 0, + attached: true, + nags: Vec::new(), + comments_before: Vec::new(), + comments_after: Vec::new(), + unparsed: Vec::new(), + }; + Game { + tags, + start, + nodes: vec![root], + result: None, + undo_stack: Vec::new(), + redo_stack: Vec::new(), + revision: 0, + saved_depth: Some(0), + unsaved_meta: false, + group: None, + } + } + + fn reset_root(&mut self, start: StartPosition) { + if let Some(root) = self.nodes.first_mut() { + root.position = start.position().clone(); + } + self.start = start; + } + + // ----- tags ------------------------------------------------------------- + + /// Tags in source order, including non-standard ones. + pub fn tags(&self) -> &[(String, String)] { + &self.tags + } + + /// First tag with this name (case-sensitive, as in PGN). + pub fn tag(&self, name: &str) -> Option<&str> { + self.tags + .iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.as_str()) + } + + /// Drops a tag (not part of undo history); nothing when it is not there. + pub fn remove_tag(&mut self, name: &str) { + let before = self.tags.len(); + self.tags.retain(|(k, _)| k != name); + if self.tags.len() != before { + self.unsaved_meta = true; + self.touch(); + } + } + + /// Sets or appends a tag (not part of undo history). + pub fn set_tag(&mut self, name: &str, value: &str) { + match self.tags.iter_mut().find(|(k, _)| k == name) { + Some(slot) => slot.1 = value.to_owned(), + None => self.tags.push((name.to_owned(), value.to_owned())), + } + self.unsaved_meta = true; + self.touch(); + } + + pub fn start(&self) -> &StartPosition { + &self.start + } + + /// Termination marker from movetext (falls back to the `Result` tag). + pub fn result(&self) -> GameResult { + self.result + .or_else(|| self.tag("Result").and_then(GameResult::from_pgn)) + .unwrap_or(GameResult::Unknown) + } + + pub fn set_result(&mut self, result: GameResult) { + self.result = Some(result); + self.set_tag("Result", result.as_str()); + } + + /// The seven tags of the PGN standard, first and in their order, with "?" for the + /// unknown ones (a game written by hand gets a proper tag roster); the other tags + /// follow as they were. Not part of undo history. + pub fn order_roster(&mut self) { + let result = self.result().as_str().to_owned(); + let roster = [ + ("Event", "?"), + ("Site", "?"), + ("Date", "????.??.??"), + ("Round", "?"), + ("White", "?"), + ("Black", "?"), + ("Result", result.as_str()), + ]; + let mut tags: Vec<(String, String)> = Vec::with_capacity(self.tags.len() + 7); + for (name, unknown) in roster { + let value = self + .tags + .iter() + .find(|(k, _)| k == name) + .map_or(unknown, |(_, v)| v.as_str()); + tags.push((name.to_owned(), value.to_owned())); + } + tags.extend( + self.tags + .iter() + .filter(|(k, _)| !roster.iter().any(|(name, _)| k == name)) + .cloned(), + ); + if tags != self.tags { + self.tags = tags; + self.unsaved_meta = true; + self.touch(); + } + } + + // ----- node access ------------------------------------------------------ + + pub fn root(&self) -> NodeId { + NodeId::ROOT + } + + pub fn node(&self, id: NodeId) -> Option<&Node> { + self.nodes.get(id.index()) + } + + pub(crate) fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> { + self.nodes.get_mut(id.index()) + } + + /// Number of nodes in the arena (including detached ones). + pub fn arena_len(&self) -> usize { + self.nodes.len() + } + + /// Every node ever made, by id (detached ones too: an id never changes and is never + /// reused, so it can name a move across edits). + pub fn all_nodes(&self) -> impl Iterator + '_ { + (0..self.nodes.len()).map(|i| NodeId(i as u32)) + } + + /// Ids of all attached nodes in depth-first PGN order (root first). + pub fn attached_nodes(&self) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![NodeId::ROOT]; + while let Some(id) = stack.pop() { + out.push(id); + if let Some(n) = self.node(id) { + stack.extend(n.children.iter().rev().copied()); + } + } + out + } + + pub fn is_attached(&self, id: NodeId) -> bool { + self.node(id).is_some_and(|n| n.attached) + } + + /// Position after the node's move (root: start position). + pub fn position(&self, id: NodeId) -> Option<&Chess> { + self.node(id).map(|n| &n.position) + } + + /// Position before the node's move (root: start position). + pub fn position_before(&self, id: NodeId) -> Option<&Chess> { + let parent = self.node(id)?.parent.unwrap_or(NodeId::ROOT); + self.position(parent) + } + + pub fn fen(&self, id: NodeId) -> Option { + self.position(id) + .map(|p| Fen::from_position(p, EnPassantMode::Legal).to_string()) + } + + pub fn game_move(&self, id: NodeId) -> Option<&GameMove> { + self.node(id)?.mv.as_ref() + } + + /// Move number and the side that made the move, for display (`12.` / `12...`). + pub fn move_number(&self, id: NodeId) -> Option<(u32, Color)> { + self.node(id)?.mv.as_ref()?; + let before = self.position_before(id)?; + Some((before.fullmoves().get(), before.turn())) + } + + /// `"12. Nf3"` or `"12... Nf6"`. + pub fn move_label(&self, id: NodeId) -> Option { + let (n, color) = self.move_number(id)?; + let san = &self.game_move(id)?.san; + Some(match color { + Color::White => format!("{n}. {san}"), + Color::Black => format!("{n}... {san}"), + }) + } + + // ----- navigation ------------------------------------------------------- + + pub fn parent(&self, id: NodeId) -> Option { + self.node(id)?.parent + } + + pub fn children(&self, id: NodeId) -> &[NodeId] { + self.node(id).map(|n| n.children.as_slice()).unwrap_or(&[]) + } + + /// Main continuation (next move). + pub fn main_child(&self, id: NodeId) -> Option { + self.children(id).first().copied() + } + + /// Alternatives to the main continuation of `id`. + pub fn variations(&self, id: NodeId) -> &[NodeId] { + self.children(id).get(1..).unwrap_or(&[]) + } + + /// Position of `id` among its siblings (0 = main). + pub fn child_index(&self, id: NodeId) -> Option { + let parent = self.parent(id)?; + self.children(parent).iter().position(|c| *c == id) + } + + /// Next sibling (switch to the next variation at the same move). + pub fn next_sibling(&self, id: NodeId) -> Option { + let parent = self.parent(id)?; + let i = self.child_index(id)?; + self.children(parent).get(i + 1).copied() + } + + pub fn prev_sibling(&self, id: NodeId) -> Option { + let parent = self.parent(id)?; + let i = self.child_index(id)?.checked_sub(1)?; + self.children(parent).get(i).copied() + } + + /// Follows main continuations to the end of the current line. + pub fn line_end(&self, id: NodeId) -> NodeId { + let mut cur = id; + while let Some(next) = self.main_child(cur) { + cur = next; + } + cur + } + + /// Path from the root to `id`, inclusive (`[ROOT, …, id]`). + pub fn path(&self, id: NodeId) -> Vec { + let mut path = Vec::new(); + let mut cur = Some(id); + while let Some(c) = cur { + if self.node(c).is_none() { + break; + } + path.push(c); + cur = self.parent(c); + } + path.reverse(); + path + } + + /// Main line nodes, excluding the root. + pub fn mainline(&self) -> Vec { + let mut out = Vec::new(); + let mut cur = NodeId::ROOT; + while let Some(next) = self.main_child(cur) { + out.push(next); + cur = next; + } + out + } + + /// True if every node on the path is a main continuation. + pub fn is_mainline(&self, id: NodeId) -> bool { + self.is_attached(id) + && self + .path(id) + .iter() + .all(|n| self.child_index(*n).unwrap_or(0) == 0) + } + + /// First node of the innermost variation containing `id` (the child that is + /// not a main continuation); `None` if `id` is on the main line. + pub fn variation_start(&self, id: NodeId) -> Option { + let mut cur = id; + loop { + match self.child_index(cur) { + Some(0) => cur = self.parent(cur)?, + Some(_) => return Some(cur), + None => return None, + } + } + } + + /// Number of variation branchings on the path (0 = main line); for indentation. + pub fn variation_depth(&self, id: NodeId) -> usize { + self.path(id) + .iter() + .filter(|n| self.child_index(**n).unwrap_or(0) > 0) + .count() + } + + // ----- engine ----------------------------------------------------------- + + /// History for UCI `position [startpos|fen F] moves …`. + pub fn engine_history(&self, id: NodeId) -> Option { + let node = self.node(id)?; + let current_fen = Fen::from_position(&node.position, EnPassantMode::Legal).to_string(); + let path = self.path(id); + let mut start_fen = if self.start.is_standard() { + None + } else { + Some(self.start.fen()) + }; + let mut moves = Vec::new(); + let mut null_moves = 0; + for n in path.iter().skip(1) { + let Some(mv) = self.game_move(*n) else { + continue; + }; + match mv.uci() { + Some(u) => moves.push(u), + None => { + null_moves += 1; + moves.clear(); + start_fen = self.fen(*n); + } + } + } + let kind = if null_moves == 0 { + HistoryKind::Complete + } else { + HistoryKind::AfterNullMove { null_moves } + }; + Some(EngineHistory { + start_fen, + moves, + current_fen, + kind, + }) + } + + /// SAN for a candidate move in the node's position (e.g. to render an engine PV). + pub fn san_for(&self, id: NodeId, m: Move) -> Option { + let pos = self.position(id)?; + pos.is_legal(m) + .then(|| SanPlus::from_move(pos.clone(), m).to_string()) + } + + // ----- revision tracking ------------------------------------------------ + + /// Incremented on each document change; usable as a cache key by the UI. + pub fn revision(&self) -> u64 { + self.revision + } + + /// True if the document differs from the last saved (or imported) state. + /// Undoing back to the saved state clears it. + pub fn is_modified(&self) -> bool { + self.unsaved_meta || self.saved_depth != Some(self.undo_stack.len()) + } + + /// Forgets the undo and redo history (the moves of a game played against the + /// computer are not edits to undo); whether the game is saved stays as it is. + pub fn forget_history(&mut self) { + let saved = self.saved_depth == Some(self.undo_stack.len()); + self.undo_stack.clear(); + self.redo_stack.clear(); + self.saved_depth = saved.then_some(0); + } + + pub fn mark_saved(&mut self) { + self.saved_depth = Some(self.undo_stack.len()); + self.unsaved_meta = false; + } + + pub(crate) fn touch(&mut self) { + self.revision = self.revision.wrapping_add(1); + } + + // ----- construction helpers (import) ----------------------------------- + + /// Appends a new child without dedup (import keeps the source tree as is). + pub(crate) fn push_child(&mut self, parent: NodeId, mv: GameMove, position: Chess) -> NodeId { + let id = NodeId(u32::try_from(self.nodes.len()).unwrap_or(u32::MAX)); + let ply = self.node(parent).map(|p| p.ply + 1).unwrap_or(1); + self.nodes.push(Node { + parent: Some(parent), + children: Vec::new(), + mv: Some(mv), + position, + ply, + attached: true, + nags: Vec::new(), + comments_before: Vec::new(), + comments_after: Vec::new(), + unparsed: Vec::new(), + }); + if let Some(p) = self.node_mut(parent) { + p.children.push(id); + } + id + } + + /// Canonical textual dump of the attached tree (moves, NAGs, comments with + /// collapsed whitespace, variation structure). Two games with equal dumps + /// and equal tags/start are semantically equivalent; used by roundtrip tests. + pub fn canonical_tree(&self) -> String { + fn norm(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") + } + fn walk(g: &Game, id: NodeId, depth: usize, out: &mut String) { + let Some(n) = g.node(id) else { return }; + out.push_str(&" ".repeat(depth)); + match &n.mv { + Some(m) => out.push_str(&m.san), + None => out.push_str(""), + } + for nag in &n.nags { + out.push_str(&format!(" ${}", nag.0)); + } + for c in &n.comments_before { + out.push_str(&format!(" B{{{}}}", norm(c))); + } + for c in &n.comments_after { + out.push_str(&format!(" A{{{}}}", norm(c))); + } + for u in &n.unparsed { + out.push_str(&format!(" U[{}]", norm(u))); + } + out.push('\n'); + for c in &n.children { + walk(g, *c, depth + 1, out); + } + } + let mut out = String::new(); + walk(self, NodeId::ROOT, 0, &mut out); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn new_game_has_roster() { + let g = Game::new(); + assert_eq!(g.tags().len(), 7); + assert_eq!(g.tag("Result"), Some("*")); + assert!(g.start().is_standard()); + assert_eq!(g.mainline(), Vec::::new()); + let h = g.engine_history(g.root()).expect("root"); + assert_eq!(h.start_fen, None); + assert!(h.moves.is_empty()); + } +} diff --git a/crates/chess-core/src/lib.rs b/crates/chess-core/src/lib.rs new file mode 100644 index 0000000..94c0e7e --- /dev/null +++ b/crates/chess-core/src/lib.rs @@ -0,0 +1,36 @@ +//! Chess model, game tree and PGN import/export. +//! +//! No UI dependencies. See `docs/dev/chess-core.md` for the API overview and +//! the compatibility policy for real-world PGN. + +pub mod comment; +pub mod database; +pub mod diagnostic; +pub mod edit; +pub mod encoding; +pub mod game; +pub mod nag; +pub mod paste; +pub mod pgn; +pub mod repair; +pub mod start; + +pub use comment::{ + Annotation, CommentPart, ShapeColor, comment_display_text, parse_comment, shapes, with_shapes, + with_text, +}; +pub use database::{OpenError, PgnDatabase, PgnIndex, SourceFingerprint}; +pub use diagnostic::{Diagnostic, DiagnosticCode, Severity, SourceLocation}; +pub use edit::{EditError, EditOutcome}; +pub use encoding::{Confidence, EncodingGuess, TextEncoding, detect_encoding}; +pub use game::{EngineHistory, Game, GameMove, GameResult, HistoryKind, MoveKind, Node, NodeId}; +pub use nag::Nag; +pub use pgn::{ + Cancelled, EntryFlags, GameEntry, ParseOptions, ParsedGame, ScanProgress, WriteOptions, + parse_game, parse_str, scan_games, write_game, +}; +pub use repair::{LetterRepairCounts, LetterRepairDetection}; +pub use start::{FenError, FenRepair, StartPosition}; + +/// Re-export of the rules library used in the public API. +pub use shakmaty; diff --git a/crates/chess-core/src/nag.rs b/crates/chess-core/src/nag.rs new file mode 100644 index 0000000..17e88e9 --- /dev/null +++ b/crates/chess-core/src/nag.rs @@ -0,0 +1,85 @@ +//! Numeric Annotation Glyphs. + +use std::fmt; + +/// A PGN NAG (`$n`). Unknown codes are preserved and shown as `$n`. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Nag(pub u8); + +impl Nag { + pub const GOOD_MOVE: Nag = Nag(1); + pub const MISTAKE: Nag = Nag(2); + pub const BRILLIANT_MOVE: Nag = Nag(3); + pub const BLUNDER: Nag = Nag(4); + pub const SPECULATIVE_MOVE: Nag = Nag(5); + pub const DUBIOUS_MOVE: Nag = Nag(6); + + /// Display symbol, if a conventional one exists. + pub fn symbol(self) -> Option<&'static str> { + Some(match self.0 { + 1 => "!", + 2 => "?", + 3 => "!!", + 4 => "??", + 5 => "!?", + 6 => "?!", + 7 | 8 => "â–¡", + 10..=12 => "=", + 13 => "∞", + 14 => "⩲", + 15 => "⩱", + 16 => "±", + 17 => "∓", + 18 => "+−", + 19 => "−+", + 22 | 23 => "⨀", + 32 | 33 => "⟳", + 36 | 37 => "↑", + 40 | 41 => "→", + 44 | 45 => "=/∞", + 132 | 133 => "⇆", + 138 | 139 => "⊕", + 140 => "∆", + 142 => "⌓", + 145 => "RR", + 146 => "N", + _ => return None, + }) + } + + /// Move-quality glyphs ($1..$6) are shown glued to the move; others separated. + pub fn is_move_assessment(self) -> bool { + (1..=6).contains(&self.0) + } + + /// Parses a symbolic annotation as it may appear in PGN import (`!?`, `+-`, ...). + pub fn from_symbol(s: &str) -> Option { + Some(Nag(match s { + "!" => 1, + "?" => 2, + "!!" => 3, + "??" => 4, + "!?" => 5, + "?!" => 6, + "â–¡" => 7, + "=" => 10, + "∞" => 13, + "+=" | "+/=" | "⩲" => 14, + "=+" | "=/+" | "⩱" => 15, + "+/-" | "±" => 16, + "-/+" | "∓" => 17, + "+-" | "+−" => 18, + "-+" | "−+" => 19, + _ => return None, + })) + } +} + +impl fmt::Display for Nag { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.symbol() { + Some(s) => f.write_str(s), + None => write!(f, "${}", self.0), + } + } +} diff --git a/crates/chess-core/src/paste.rs b/crates/chess-core/src/paste.rs new file mode 100644 index 0000000..ffb7215 --- /dev/null +++ b/crates/chess-core/src/paste.rs @@ -0,0 +1,809 @@ +//! Pasting moves or a PGN game from the clipboard into a game as a variation +//! (docs/research/paste-variation.md §4, docs/design/paste-variation.md). +//! +//! [`plan`] reads the text and finds where it fits without touching the game; +//! [`Game::apply_paste`] then grafts the new moves — with their comments, NAGs and +//! nested variations — as one undo step. +//! +//! What the clipboard may hold: +//! - a PGN game (tags, or numbers from move 1): it hangs where its moves part from +//! this game, along any branch; with no common start, where one of its positions +//! occurs here (another move order); with neither it does not fit; +//! - a fragment (`Nf3 d5`, `12...Rd8`, UCI `e2e4 e7e5`): after the selected move, +//! instead of it, or at the position of its move number on the current line. +//! +//! Nothing is inserted when any move of the line is impossible. + +use shakmaty::fen::Fen; +use shakmaty::san::SanPlus; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, EnPassantMode, Position}; + +use crate::edit::{Command, EditError}; +use crate::encoding::TextEncoding; +use crate::game::{Game, GameMove, MoveKind, NodeId, play_null}; +use crate::pgn::{parse_game_range, parse_str, scan_games}; + +/// Where and what to insert: the subtree of `source` from `from` hangs from `at`. +#[derive(Clone, Debug)] +pub struct PastePlan { + /// The node of this game the new moves follow. + pub at: NodeId, + source: Game, + from: NodeId, + /// The variations of the pasted game this one lacks, along the way: (where here, + /// the pasted move) — inserted too. + extra: Vec<(NodeId, NodeId)>, + /// `at` has no continuation: the moves continue the line instead of branching. + pub continuation: bool, + /// The moves of the new line (its main line): number, side, SAN. + pub line: Vec<(u32, Color, String)>, + /// The game reached this position by another move order: those moves + /// (`1.Nf3 c5 2.e4`), noted before the first move of the line. + pub transposition: Option, + /// «White – Black» of the pasted game, noted after the last move of the line. + pub source_ref: Option, + /// Games in the clipboard (the first one is pasted). + pub games: usize, +} + +/// Why nothing is pasted. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PasteError { + /// The clipboard is empty or holds no moves. + NoMoves, + /// A fragment fits neither after the selected move nor instead of it (nor at + /// its move number). + DoesNotFit, + /// A move in the middle of the line is impossible. + Illegal { + number: u32, + side: Color, + san: String, + }, + /// The game shares no position with this one. + Unrelated, + /// All the moves are here already: the end of that line; `comments` — the + /// pasted moves had comments or symbols (not carried over). + AlreadyThere { at: NodeId, comments: bool }, +} + +/// Finds where `text` fits in `target` (the user stands on `cursor`). +pub fn plan(target: &Game, cursor: NodeId, text: &str) -> Result { + // «12…Rd8» as the program itself writes black's moves. + let text = text.trim().replace('…', "..."); + let text = text.as_str(); + if text.is_empty() { + return Err(PasteError::NoMoves); + } + if text.starts_with('[') { + // The games are only counted; the first one is read. + let never = std::sync::atomic::AtomicBool::new(false); + let entries = scan_games(text.as_bytes(), TextEncoding::Utf8, &mut |_| {}, &never) + .unwrap_or_default(); + let source = match entries.first() { + Some(e) => parse_game_range( + text.as_bytes(), + e.byte_range.clone(), + e.first_line, + TextEncoding::Utf8, + ), + None => parse_str(text), + }; + return whole_game(target, source, entries.len().max(1)); + } + let uci = uci_moves(text); + let number = leading_number(text); + // «1.e4 …» from the standard start: a game, with all its rules (a «1.d4» into a + // Sicilian is refused, not hung at the start). + if uci.is_none() && number == Some((1, Color::White)) && target.start().is_standard() { + return whole_game(target, parse_str(text), 1); + } + // A fragment: after the selected move, instead of it, at its move number. + let mut candidates = vec![cursor]; + if let Some(parent) = target.parent(cursor) { + candidates.push(parent); + } + if let Some(n) = number + && let Some(at) = by_number(target, cursor, n) + && !candidates.contains(&at) + { + candidates.push(at); + } + for at in candidates { + let Some(pos) = target.position(at) else { + continue; + }; + if number.is_some_and(|(n, side)| (pos.fullmoves().get(), pos.turn()) != (n, side)) { + continue; + } + let movetext = match &uci { + Some(moves) => match uci_to_san(pos, moves) { + Ok(san) => san, + Err(0) => continue, + Err(k) => return Err(illegal_at(pos, moves, k)), + }, + None => text.to_owned(), + }; + let fen = target.fen(at).unwrap_or_default(); + let source = parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n{movetext}\n")).game; + if source.main_child(NodeId::ROOT).is_none() { + continue; // its first move is impossible here + } + if let Some(e) = illegal_in_main_line(&source) { + return Err(e); + } + return from_node(target, at, &source, NodeId::ROOT, None, 1); + } + // Numbers or not, plain SAN may still be a game from the start. + if uci.is_none() && number.is_none() { + return match whole_game(target, parse_str(text), 1) { + Err(PasteError::Unrelated | PasteError::NoMoves) => Err(PasteError::DoesNotFit), + other => other, + }; + } + Err(PasteError::DoesNotFit) +} + +/// A whole game: where its moves part from this game; else where one of its +/// positions occurs here; else it does not fit. +fn whole_game( + target: &Game, + parsed: crate::pgn::ParsedGame, + games: usize, +) -> Result { + let source = parsed.game; + if source.main_child(NodeId::ROOT).is_none() { + return Err(PasteError::NoMoves); + } + if let Some(e) = illegal_in_main_line(&source) { + return Err(e); + } + let same_start = key(source.start().position()) == key(target.start().position()); + // An empty game takes it all. + if same_start && target.main_child(NodeId::ROOT).is_none() { + return from_node(target, NodeId::ROOT, &source, NodeId::ROOT, None, games); + } + // The moves in common, along any branch. + if same_start && walk(target, NodeId::ROOT, &source, NodeId::ROOT).matched > 0 { + return from_node(target, NodeId::ROOT, &source, NodeId::ROOT, None, games); + } + // Another move order: the first of its positions that occurs here. + let mut path = vec![NodeId::ROOT]; + path.extend(source.mainline()); + let targets: Vec = std::iter::once(NodeId::ROOT) + .chain(target.mainline()) + .chain(target.attached_nodes()) + .collect(); + for (k, &s) in path.iter().enumerate() { + if k == 0 && same_start { + continue; + } + let Some(sp) = source.position(s) else { + continue; + }; + let want = key(sp); + let Some(&t) = targets + .iter() + .find(|&&t| target.position(t).is_some_and(|tp| key(tp) == want)) + else { + continue; + }; + let note = (k > 0).then(|| line_text(&source, &path[1..=k])); + return from_node(target, t, &source, s, note, games); + } + Err(PasteError::Unrelated) +} + +/// The plan for the moves of `source` after `s`, matched along `target` from `t`. +fn from_node( + target: &Game, + t: NodeId, + source: &Game, + s: NodeId, + transposition: Option, + games: usize, +) -> Result { + let Walk { + last, + next, + mut extra, + .. + } = walk(target, t, source, s); + // The main line is all here: its variations this game lacks may still be new. + let (at, from) = match next { + Some(from) => (last, from), + None if !extra.is_empty() => extra.remove(0), + None => { + let comments = commented(source, s); + return Err(PasteError::AlreadyThere { at: last, comments }); + } + }; + let mut line = Vec::new(); + let mut cur = Some(from); + while let Some(c) = cur { + if let (Some(before), Some(mv)) = (source.position_before(c), source.game_move(c)) { + line.push((before.fullmoves().get(), before.turn(), mv.san.clone())); + } + cur = source.main_child(c); + } + let name = |tag: &str| { + source + .tag(tag) + .map(str::trim) + .filter(|v| !v.is_empty() && *v != "?") + }; + let source_ref = match (name("White"), name("Black")) { + (None, None) => None, + (w, b) => Some(format!("{} – {}", w.unwrap_or("?"), b.unwrap_or("?"))), + }; + Ok(PastePlan { + at, + source: source.clone(), + from, + extra, + continuation: target.children(at).is_empty(), + line, + transposition, + source_ref, + games, + }) +} + +/// What [`walk`] found. +struct Walk { + /// The last node in common. + last: NodeId, + /// The first move of the pasted main line that is not here. + next: Option, + /// How many moves matched. + matched: usize, + /// The pasted game's alternatives along the way that are not here: (where here, + /// the pasted move). + extra: Vec<(NodeId, NodeId)>, +} + +/// Follows the main line of `source` from `s` through `target` from `t` while the +/// moves are there (by any branch). +fn walk(target: &Game, mut t: NodeId, source: &Game, mut s: NodeId) -> Walk { + let child = |t: NodeId, kind: MoveKind| { + target + .children(t) + .iter() + .copied() + .find(|&c| target.game_move(c).is_some_and(|m| m.kind == kind)) + }; + let mut matched = 0; + let mut extra = Vec::new(); + while let Some(next) = source.main_child(s) { + // The pasted game's variations here: kept unless this game has the move. + for &alt in &source.children(s)[1..] { + if let Some(kind) = source.game_move(alt).map(|m| m.kind) + && child(t, kind).is_none() + { + extra.push((t, alt)); + } + } + let Some(kind) = source.game_move(next).map(|m| m.kind) else { + break; + }; + match child(t, kind) { + Some(c) => { + t = c; + s = next; + matched += 1; + } + None => { + return Walk { + last: t, + next: Some(next), + matched, + extra, + }; + } + } + } + Walk { + last: t, + next: None, + matched, + extra, + } +} + +/// The moves walked from `s` on had comments or symbols (lost when all are here). +fn commented(source: &Game, s: NodeId) -> bool { + let mut cur = source.main_child(s); + while let Some(c) = cur { + if let Some(n) = source.node(c) + && (!n.nags().is_empty() + || !n.comments_after().is_empty() + || !n.comments_before().is_empty()) + { + return true; + } + cur = source.main_child(c); + } + false +} + +/// An impossible move on the main line of a parsed game (its variations may keep +/// raw text: it is carried over as it is). +fn illegal_in_main_line(source: &Game) -> Option { + let mut main = vec![NodeId::ROOT]; + main.extend(source.mainline()); + let last = *main.last()?; + let node = source.node(last)?; + let raw = node.unparsed().first()?; + // The first move word, without a number glued to it («3.Qh8»). + let san = raw + .split_whitespace() + .find(|w| !is_number(w))? + .trim_start_matches(|c: char| c.is_ascii_digit() || c == '.' || c == '…') + .to_owned(); + let pos = source.position(last)?; + Some(PasteError::Illegal { + number: pos.fullmoves().get(), + side: pos.turn(), + san, + }) +} + +/// The position key: pieces, side to move, castling, en passant (no counters). +fn key(pos: &Chess) -> String { + Fen::from_position(pos, EnPassantMode::Legal) + .to_string() + .split(' ') + .take(4) + .collect::>() + .join(" ") +} + +/// `1.Nf3 c5 2.e4` for the given nodes of `game`. +fn line_text(game: &Game, nodes: &[NodeId]) -> String { + let mut out = String::new(); + for (i, &n) in nodes.iter().enumerate() { + let (Some(before), Some(mv)) = (game.position_before(n), game.game_move(n)) else { + continue; + }; + let num = before.fullmoves().get(); + if !out.is_empty() { + out.push(' '); + } + match before.turn() { + Color::White => out.push_str(&format!("{num}.{}", mv.san)), + Color::Black if i == 0 => out.push_str(&format!("{num}...{}", mv.san)), + Color::Black => out.push_str(&mv.san), + } + } + out +} + +/// The number of a move (`12.`, `12...`, `12…`), as a word of the text. +fn is_number(w: &str) -> bool { + let digits = w.trim_end_matches(['.', '…']); + !digits.is_empty() && digits.len() < w.len() && digits.chars().all(|c| c.is_ascii_digit()) +} + +/// `12.` → (12, White), `12...` / `12…` → (12, Black), when the text starts so. +fn leading_number(text: &str) -> Option<(u32, Color)> { + let first = text.split_whitespace().next()?; + let digits: String = first.chars().take_while(char::is_ascii_digit).collect(); + let rest = &first[digits.len()..]; + let n: u32 = digits.parse().ok()?; + if rest.starts_with("...") || rest.starts_with('…') { + Some((n, Color::Black)) + } else if rest.starts_with('.') { + Some((n, Color::White)) + } else { + None + } +} + +/// The words of a UCI line (`e2e4 e7e5 g1f3`, numbers allowed), if the text is one. +fn uci_moves(text: &str) -> Option> { + let words: Vec<&str> = text + .split_whitespace() + .filter(|w| !is_number(w) && !matches!(*w, "1-0" | "0-1" | "1/2-1/2" | "*")) + .collect(); + let is_uci = |w: &str| { + let b = w.as_bytes(); + (b.len() == 4 || b.len() == 5) + && (b'a'..=b'h').contains(&b[0]) + && (b'1'..=b'8').contains(&b[1]) + && (b'a'..=b'h').contains(&b[2]) + && (b'1'..=b'8').contains(&b[3]) + && (b.len() == 4 || b"qrbn".contains(&b[4])) + }; + (!words.is_empty() && words.iter().all(|w| is_uci(w))) + .then(|| words.iter().map(|w| (*w).to_owned()).collect()) +} + +/// UCI moves played from `pos` as SAN; `Err(k)`: the `k`-th move is impossible. +fn uci_to_san(pos: &Chess, moves: &[String]) -> Result { + let mut pos = pos.clone(); + let mut out = Vec::new(); + for (k, w) in moves.iter().enumerate() { + let m = w + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + .ok_or(k)?; + out.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); + } + Ok(out.join(" ")) +} + +/// The error for the `k`-th UCI move from `pos`. +fn illegal_at(pos: &Chess, moves: &[String], k: usize) -> PasteError { + let mut pos = pos.clone(); + for w in &moves[..k] { + if let Some(m) = w.parse::().ok().and_then(|u| u.to_move(&pos).ok()) { + pos.play_unchecked(m); + } + } + PasteError::Illegal { + number: pos.fullmoves().get(), + side: pos.turn(), + san: moves[k].clone(), + } +} + +/// The node of the current line (the path to `cursor`, then on by the main line) +/// where the move of number `n` is to be made. +fn by_number(target: &Game, cursor: NodeId, (n, side): (u32, Color)) -> Option { + let mut line = target.path(cursor); + let mut cur = cursor; + while let Some(next) = target.main_child(cur) { + line.push(next); + cur = next; + } + line.into_iter().find(|&id| { + target + .position(id) + .is_some_and(|p| (p.fullmoves().get(), p.turn()) == (n, side)) + }) +} + +impl Game { + /// Inserts what [`plan`] found: the new moves with their comments, symbols and + /// variations, the move-order note and the source, as one undo step. Returns the + /// first inserted node. + pub fn apply_paste(&mut self, plan: &PastePlan) -> Result { + let pos = self + .position(plan.at) + .ok_or(EditError::UnknownNode)? + .clone(); + // Every move is checked before the game changes. + check(&plan.source, plan.from, &pos)?; + for &(at, from) in &plan.extra { + let pos = self.position(at).ok_or(EditError::UnknownNode)?.clone(); + check(&plan.source, from, &pos)?; + } + self.edit_group(|g| g.paste_grafts(plan)) + } + + /// The grafts of [`Game::apply_paste`], checked already. + fn paste_grafts(&mut self, plan: &PastePlan) -> Result { + let first = self.graft(plan.at, &plan.source, plan.from)?; + if let Some(note) = &plan.transposition + && let Some(n) = self.node_mut(first) + { + n.comments_before.insert(0, note.clone()); + } + if let Some(r) = &plan.source_ref { + let end = self.line_end(first); + if let Some(n) = self.node_mut(end) { + n.comments_after.push(r.clone()); + } + } + let index = self.child_index(first).unwrap_or(0); + self.record(Command::Attach { + parent: plan.at, + child: first, + index, + }); + for &(at, from) in &plan.extra { + let id = self.graft(at, &plan.source, from)?; + let index = self.child_index(id).unwrap_or(0); + self.record(Command::Attach { + parent: at, + child: id, + index, + }); + } + Ok(first) + } + + /// Copies the subtree of `source` from `s` under `parent`, positions replayed + /// here (the counters may differ from the source's). + fn graft(&mut self, parent: NodeId, source: &Game, s: NodeId) -> Result { + let pos = self.position(parent).ok_or(EditError::UnknownNode)?.clone(); + let node = source.node(s).ok_or(EditError::UnknownNode)?; + let mv = node.game_move().ok_or(EditError::UnknownNode)?; + let (gm, after) = play(&pos, mv)?; + let id = self.push_child(parent, gm, after); + if let Some(n) = self.node_mut(id) { + n.nags = node.nags().to_vec(); + n.comments_before = node.comments_before().to_vec(); + n.comments_after = node.comments_after().to_vec(); + n.unparsed = node.unparsed().to_vec(); + } + for &c in source.children(s) { + self.graft(id, source, c)?; + } + Ok(id) + } +} + +/// The move `mv` from `pos`: the node's move and the position after it. +fn play(pos: &Chess, mv: &GameMove) -> Result<(GameMove, Chess), EditError> { + match mv.kind { + MoveKind::Normal(m) => { + if !pos.is_legal(m) { + return Err(EditError::IllegalMove(mv.san.clone())); + } + let mut after = pos.clone(); + let san = SanPlus::from_move_and_play_unchecked(&mut after, m).to_string(); + Ok((GameMove { kind: mv.kind, san }, after)) + } + MoveKind::Null => { + let after = play_null(pos).map_err(|_| EditError::IllegalMove("--".into()))?; + Ok(( + GameMove { + kind: MoveKind::Null, + san: "--".into(), + }, + after, + )) + } + } +} + +/// Every move of the subtree of `source` from `s` can be made from `pos`. +fn check(source: &Game, s: NodeId, pos: &Chess) -> Result<(), EditError> { + let mut stack = vec![(s, pos.clone())]; + while let Some((id, pos)) = stack.pop() { + let mv = source.game_move(id).ok_or(EditError::UnknownNode)?; + let (_, after) = play(&pos, mv)?; + for &c in source.children(id) { + stack.push((c, after.clone())); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn game(pgn: &str) -> Game { + parse_str(pgn).game + } + + /// The node reached by the SAN moves from the root (along any branch). + fn at(g: &Game, sans: &[&str]) -> NodeId { + let mut cur = NodeId::ROOT; + for s in sans { + cur = *g + .children(cur) + .iter() + .find(|&&c| g.game_move(c).is_some_and(|m| m.san == *s)) + .unwrap_or_else(|| panic!("no {s}")); + } + cur + } + + fn sans(p: &PastePlan) -> Vec<&str> { + p.line.iter().map(|(_, _, s)| s.as_str()).collect() + } + + const SICILIAN: &str = "1. e4 c5 2. Nf3 d6 3. d4 *"; + + #[test] + fn a_game_hangs_where_it_parts_and_undoes_whole() { + let mut g = game(SICILIAN); + let before = g.canonical_tree(); + let cursor = at(&g, &["e4", "c5", "Nf3", "d6", "d4"]); + let p = plan(&g, cursor, "1.e4 c5 2.Nf3 Nc6 3.d4").unwrap(); + assert_eq!(p.at, at(&g, &["e4", "c5", "Nf3"])); + assert_eq!(sans(&p), ["Nc6", "d4"]); + assert!(!p.continuation); + let first = g.apply_paste(&p).unwrap(); + assert_eq!(g.game_move(first).unwrap().san, "Nc6"); + // The main line is the same; the variation is the last child. + assert_eq!(g.mainline().len(), 5); + assert_eq!(g.children(p.at).last(), Some(&first)); + g.undo(); + assert_eq!(g.canonical_tree(), before); + } + + #[test] + fn an_unrelated_game_is_refused() { + let g = game(SICILIAN); + let cursor = at(&g, &["e4", "c5"]); + assert_eq!( + plan(&g, cursor, "1.d4 d5 2.c4").unwrap_err(), + PasteError::Unrelated + ); + assert_eq!( + plan(&g, cursor, "[White \"A\"]\n[Black \"B\"]\n\n1.d4 d5 2.c4 *").unwrap_err(), + PasteError::Unrelated + ); + } + + #[test] + fn another_move_order_is_found_and_noted() { + let g = game(SICILIAN); + let cursor = at(&g, &["e4", "c5", "Nf3"]); + // All there by another order. + assert!(matches!( + plan(&g, cursor, "1.Nf3 c5 2.e4 d6 3.d4").unwrap_err(), + PasteError::AlreadyThere { .. } + )); + let p = plan(&g, cursor, "1.Nf3 c5 2.e4 Nc6").unwrap(); + assert_eq!(p.at, at(&g, &["e4", "c5", "Nf3"])); + assert_eq!(sans(&p), ["Nc6"]); + assert_eq!(p.transposition.as_deref(), Some("1.Nf3 c5 2.e4")); + } + + #[test] + fn fragments_after_instead_of_or_by_number() { + let g = game("1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. f3 Bf5 6. Ng3 *"); + let bf5 = at( + &g, + &[ + "e4", "c6", "d4", "d5", "Nc3", "dxe4", "Nxe4", "Nf6", "f3", "Bf5", + ], + ); + // Instead of the selected move. + let p = plan(&g, bf5, "5...Nxe4 6.fxe4").unwrap(); + assert_eq!(p.at, g.parent(bf5).unwrap()); + assert_eq!(sans(&p), ["Nxe4", "fxe4"]); + // After it. + let p = plan(&g, bf5, "6.Qd3 e6").unwrap(); + assert_eq!(p.at, bf5); + // Without numbers. + let p = plan(&g, bf5, "Qd3 e6").unwrap(); + assert_eq!(p.at, bf5); + // By the number on the current line. + let e4 = at(&g, &["e4"]); + let p = plan(&g, e4, "4...e5").unwrap(); + assert_eq!( + p.at, + at(&g, &["e4", "c6", "d4", "d5", "Nc3", "dxe4", "Nxe4"]) + ); + // Nowhere. + assert_eq!(plan(&g, bf5, "Ke3").unwrap_err(), PasteError::DoesNotFit); + } + + #[test] + fn uci_lines_and_impossible_moves() { + let g = Game::new(); + let p = plan(&g, NodeId::ROOT, "e2e4 e7e5 g1f3").unwrap(); + assert_eq!(sans(&p), ["e4", "e5", "Nf3"]); + assert!(p.continuation); + assert_eq!( + plan(&g, NodeId::ROOT, "e2e4 e7e5 e1e3").unwrap_err(), + PasteError::Illegal { + number: 2, + side: Color::White, + san: "e1e3".into() + } + ); + let s = game(SICILIAN); + assert_eq!( + plan(&s, NodeId::ROOT, "1.e4 c5 2.Nf3 Nc6 3.Qh8").unwrap_err(), + PasteError::Illegal { + number: 3, + side: Color::White, + san: "Qh8".into() + } + ); + } + + #[test] + fn comments_variations_and_the_source_come_along() { + let mut g = game(SICILIAN); + let text = "[White \"Mellado Trivino,J\"]\n[Black \"Garcia Albarracin,F\"]\n[Result \"0-1\"]\n\n\ + 1.e4 c5 2.Nf3 Nc6 {Old.} 3.d4 $1 (3.Bb5 g6) cxd4 0-1"; + let p = plan(&g, NodeId::ROOT, text).unwrap(); + assert_eq!( + p.source_ref.as_deref(), + Some("Mellado Trivino,J – Garcia Albarracin,F") + ); + let first = g.apply_paste(&p).unwrap(); + let after = g.to_pgn(); + assert!(after.contains("{Old.}"), "{after}"); + assert!(after.contains("Bb5"), "{after}"); + assert_eq!( + g.node(g.line_end(first)).unwrap().comments_after(), + ["Mellado Trivino,J – Garcia Albarracin,F"] + ); + assert_eq!( + g.node(at(&g, &["e4", "c5", "Nf3", "Nc6", "d4"])) + .unwrap() + .nags() + .len(), + 1 + ); + // Written and read again: the same tree. + let again = game(&after); + assert_eq!(again.canonical_tree(), g.canonical_tree()); + assert!(g.is_attached(first)); + } + + #[test] + fn the_pasted_games_variations_come_along() { + let mut g = game(SICILIAN); + let before = g.canonical_tree(); + // An alternative at the parting point and one on a move in common. + let text = + "[White \"A\"]\n[Black \"B\"]\n\n1.e4 c5 (1...e5 2.Nf3) 2.Nf3 Nc6 (2...e6 3.d4) 3.d4 *"; + let p = plan(&g, NodeId::ROOT, text).unwrap(); + g.apply_paste(&p).unwrap(); + let nf3 = at(&g, &["e4", "c5", "Nf3"]); + let kids = |g: &Game, id| -> Vec { + g.children(id) + .iter() + .map(|&c| g.game_move(c).unwrap().san.clone()) + .collect() + }; + assert_eq!(kids(&g, nf3), ["d6", "Nc6", "e6"]); + assert_eq!(kids(&g, at(&g, &["e4"])), ["c5", "e5"]); + // One undo step for all of it. + g.undo(); + assert_eq!(g.canonical_tree(), before); + // Only a variation is new: it is pasted, not «already there». + let p = plan(&g, NodeId::ROOT, "1.e4 c5 (1...e6) 2.Nf3 d6 3.d4").unwrap(); + assert_eq!(p.at, at(&g, &["e4"])); + assert_eq!(sans(&p), ["e6"]); + } + + #[test] + fn black_numbers_with_an_ellipsis_character() { + let g = game(SICILIAN); + let p = plan(&g, at(&g, &["e4"]), "1…e5 2.Nf3").unwrap(); + assert_eq!(sans(&p), ["e5", "Nf3"]); + } + + #[test] + fn the_same_game_or_line_is_already_there() { + let g = game(SICILIAN); + match plan(&g, NodeId::ROOT, SICILIAN).unwrap_err() { + PasteError::AlreadyThere { at: end, comments } => { + assert_eq!(end, *g.mainline().last().unwrap()); + assert!(!comments); + } + e => panic!("{e:?}"), + } + assert!(matches!( + plan(&g, NodeId::ROOT, "1.e4 c5 {Sicilian}").unwrap_err(), + PasteError::AlreadyThere { comments: true, .. } + )); + assert_eq!( + plan(&g, NodeId::ROOT, " ").unwrap_err(), + PasteError::NoMoves + ); + } + + #[test] + fn a_game_from_a_position_with_fullmove_zero() { + let fen = "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0"; + let mut g = game(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. e4 Kd7 *")); + let e4 = at(&g, &["e4"]); + let p = plan(&g, e4, "1...Ke7").unwrap(); + assert_eq!(p.at, e4); + g.apply_paste(&p).unwrap(); + assert_eq!(g.children(e4).len(), 2); + } + + #[test] + fn several_games_paste_the_first() { + let g = game(SICILIAN); + let text = "[White \"A\"]\n\n1.e4 c5 2.Nf3 Nc6 *\n\n[White \"B\"]\n\n1.e4 e5 *\n"; + let p = plan(&g, NodeId::ROOT, text).unwrap(); + assert_eq!(p.games, 2); + assert_eq!(sans(&p), ["Nc6"]); + } +} diff --git a/crates/chess-core/src/pgn/lexer.rs b/crates/chess-core/src/pgn/lexer.rs new file mode 100644 index 0000000..990fa2f --- /dev/null +++ b/crates/chess-core/src/pgn/lexer.rs @@ -0,0 +1,377 @@ +//! Byte-level PGN lexer shared by the index scanner and the game parser. +//! +//! Works on raw bytes of the original file (all supported encodings are +//! ASCII-compatible), so token spans are byte offsets in the original file. +//! Every non-whitespace byte belongs to exactly one token: nothing is skipped +//! silently, which is what makes coverage diagnostics possible. + +use crate::encoding::{TextEncoding, decode_text}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum TokKind { + /// `[Name "value"]`; `malformed` if the line could not be parsed as a tag. + Tag { + malformed: bool, + }, + /// `{…}`. Content is `start+1..end-1` if terminated, else `start+1..end`. + Comment { + terminated: bool, + }, + /// `;…` to end of line. + LineComment, + /// `%…` line at column 0. + Escape, + Open, + Close, + StrayCloseBrace, + /// `$digits`. + Nag, + /// Any other run of non-delimiter bytes (moves, numbers, results, garbage). + Word, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Token { + pub kind: TokKind, + pub start: usize, + pub end: usize, + /// 1-based line of `start`. + pub line: u32, +} + +impl Token { + pub fn comment_content(&self) -> (usize, usize) { + match self.kind { + TokKind::Comment { terminated: true } => (self.start + 1, self.end.saturating_sub(1)), + _ => (self.start + 1, self.end), + } + } +} + +pub(crate) struct Lexer<'a> { + bytes: &'a [u8], + pos: usize, + end: usize, + line: u32, + /// Only whitespace (or tags) since the last newline. + line_blank: bool, + /// Directly after a newline (column 0). + col0: bool, +} + +fn is_delim(b: u8) -> bool { + matches!(b, b'{' | b'}' | b'(' | b')' | b';' | b'$') || b.is_ascii_whitespace() +} + +impl<'a> Lexer<'a> { + pub fn new(bytes: &'a [u8], start: usize, end: usize, first_line: u32) -> Self { + let end = end.min(bytes.len()); + let start = start.min(end); + Lexer { + bytes, + pos: start, + end, + line: first_line, + line_blank: true, + col0: true, + } + } + + pub fn line(&self) -> u32 { + self.line + } + + fn peek(&self) -> Option { + (self.pos < self.end).then(|| self.bytes[self.pos]) + } + + fn at(&self, i: usize) -> Option { + (i < self.end).then(|| self.bytes[i]) + } + + fn bump(&mut self) { + if let Some(b) = self.peek() { + self.pos += 1; + if b == b'\n' { + self.line += 1; + self.line_blank = true; + self.col0 = true; + } else { + self.col0 = false; + if !b.is_ascii_whitespace() { + self.line_blank = false; + } + } + } + } + + fn skip_to_eol(&mut self) { + while let Some(b) = self.peek() { + if b == b'\n' { + break; + } + self.bump(); + } + } + + /// After a game's result a header may follow on the same line (`… 1-0 [Event "B"]`, + /// as pasted or joined text has it): a tag there counts as at a line's start. + pub fn allow_tag(&mut self) { + self.line_blank = true; + } + + /// Is there a tag-looking line (`[Name "`) at `i`? + fn tag_like_at(&self, mut i: usize) -> bool { + if self.at(i) != Some(b'[') { + return false; + } + i += 1; + let name_start = i; + while let Some(b) = self.at(i) { + if b.is_ascii_alphanumeric() || b == b'_' { + i += 1; + } else { + break; + } + } + if i == name_start { + return false; + } + while let Some(b' ' | b'\t') = self.at(i) { + i += 1; + } + self.at(i) == Some(b'"') + } + + /// Inside a comment: does a blank line followed by a header line start at `i` + /// (which points at a `\n`)? Used to stop runaway unterminated comments. + fn header_after_blank_line(&self, i: usize) -> bool { + let mut j = i + 1; + let mut saw_blank = false; + loop { + match self.at(j) { + Some(b' ' | b'\t' | b'\r') => j += 1, + Some(b'\n') => { + saw_blank = true; + j += 1; + } + _ => break, + } + } + saw_blank && self.tag_like_at(j) + } + + pub fn next_token(&mut self) -> Option { + // Skip whitespace. + while let Some(b) = self.peek() { + if b.is_ascii_whitespace() { + self.bump(); + } else { + break; + } + } + let b = self.peek()?; + let start = self.pos; + let line = self.line; + let kind = match b { + b'%' if self.col0 => { + self.skip_to_eol(); + TokKind::Escape + } + b'[' if self.line_blank && self.tag_like_at(self.pos) => self.lex_tag(), + b'{' => { + self.bump(); + let mut terminated = false; + while let Some(c) = self.peek() { + if c == b'}' { + self.bump(); + terminated = true; + break; + } + if c == b'\n' && self.header_after_blank_line(self.pos) { + break; + } + self.bump(); + } + TokKind::Comment { terminated } + } + b';' => { + self.skip_to_eol(); + TokKind::LineComment + } + b'(' => { + self.bump(); + TokKind::Open + } + b')' => { + self.bump(); + TokKind::Close + } + b'}' => { + self.bump(); + TokKind::StrayCloseBrace + } + b'$' if self.at(self.pos + 1).is_some_and(|d| d.is_ascii_digit()) => { + self.bump(); + while self.peek().is_some_and(|d| d.is_ascii_digit()) { + self.bump(); + } + TokKind::Nag + } + _ => { + self.bump(); + while self.peek().is_some_and(|c| !is_delim(c)) { + self.bump(); + } + TokKind::Word + } + }; + Some(Token { + kind, + start, + end: self.pos, + line, + }) + } + + fn lex_tag(&mut self) -> TokKind { + // Called at '['. Parse `[Name "value"]` with escapes; tolerate missing ']'. + self.bump(); + while self.peek().is_some_and(|c| c != b'"' && c != b'\n') { + self.bump(); + } + if self.peek() != Some(b'"') { + return TokKind::Tag { malformed: true }; + } + self.bump(); + let mut closed_quote = false; + while let Some(c) = self.peek() { + match c { + b'\\' => { + self.bump(); + if self.peek().is_some_and(|n| n != b'\n') { + self.bump(); + } + } + b'"' => { + self.bump(); + closed_quote = true; + break; + } + b'\n' => break, + _ => self.bump(), + } + } + if !closed_quote { + return TokKind::Tag { malformed: true }; + } + while let Some(b' ' | b'\t' | b'\r') = self.peek() { + self.bump(); + } + let malformed = if self.peek() == Some(b']') { + self.bump(); + false + } else { + true + }; + // A tag line counts as "blank" so that several tags may share a line. + self.line_blank = true; + TokKind::Tag { malformed } + } +} + +/// Parses a `Tag` token into name and decoded value. +pub(crate) fn parse_tag( + bytes: &[u8], + tok: &Token, + encoding: TextEncoding, +) -> Option<(String, String, bool)> { + let raw = bytes.get(tok.start..tok.end)?; + let raw = raw.strip_prefix(b"[")?; + let name_len = raw + .iter() + .position(|b| !(b.is_ascii_alphanumeric() || *b == b'_'))?; + if name_len == 0 { + return None; + } + let name = String::from_utf8_lossy(&raw[..name_len]).into_owned(); + let rest = &raw[name_len..]; + let q = rest.iter().position(|b| *b == b'"')?; + let mut value = Vec::new(); + let mut i = q + 1; + while let Some(&c) = rest.get(i) { + match c { + b'\\' => { + if let Some(&n) = rest.get(i + 1) { + value.push(n); + } + i += 2; + } + b'"' => break, + b'\r' | b'\n' => break, + _ => { + value.push(c); + i += 1; + } + } + } + let (value, had_errors) = decode_text(encoding, &value); + Some((name, value, had_errors)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(s: &str) -> Vec<(TokKind, String)> { + let b = s.as_bytes(); + let mut lx = Lexer::new(b, 0, b.len(), 1); + let mut out = Vec::new(); + while let Some(t) = lx.next_token() { + out.push((t.kind, s[t.start..t.end].to_owned())); + } + out + } + + #[test] + fn lexes_movetext() { + let k = kinds("[White \"A \\\"q\\\"\"]\n1. e4 {c (x)} (1. d4 $1) ; rest\n%esc\n} *"); + let names: Vec<_> = k.iter().map(|(k, _)| *k).collect(); + assert_eq!( + names, + vec![ + TokKind::Tag { malformed: false }, + TokKind::Word, + TokKind::Word, + TokKind::Comment { terminated: true }, + TokKind::Open, + TokKind::Word, + TokKind::Word, + TokKind::Nag, + TokKind::Close, + TokKind::LineComment, + TokKind::Escape, + TokKind::StrayCloseBrace, + TokKind::Word, + ] + ); + } + + #[test] + fn tag_value_unescaped() { + let s = "[White \"A \\\"q\\\" \\\\\"]"; + let b = s.as_bytes(); + let mut lx = Lexer::new(b, 0, b.len(), 1); + let t = lx.next_token().expect("tag"); + let (n, v, _) = parse_tag(b, &t, TextEncoding::Utf8).expect("parse"); + assert_eq!(n, "White"); + assert_eq!(v, "A \"q\" \\"); + } + + #[test] + fn runaway_comment_stops_at_header() { + let k = kinds("1. e4 {open\n\n[Event \"x\"]\n1. d4 *"); + assert_eq!(k[2].0, TokKind::Comment { terminated: false }); + assert_eq!(k[3].0, TokKind::Tag { malformed: false }); + } +} diff --git a/crates/chess-core/src/pgn/mod.rs b/crates/chess-core/src/pgn/mod.rs new file mode 100644 index 0000000..e04865c --- /dev/null +++ b/crates/chess-core/src/pgn/mod.rs @@ -0,0 +1,29 @@ +//! PGN import (scan + lazy parse) and export. + +mod lexer; +pub mod parse; +pub mod scan; +pub mod store; +pub mod write; + +pub use parse::{ + ParseOptions, ParsedGame, parse_game, parse_game_range, parse_game_range_with, parse_str, +}; +pub use scan::{Cancelled, EntryFlags, GameEntry, ScanProgress, scan_games}; +pub use write::{WriteOptions, write_game}; + +use crate::encoding::TextEncoding; +use std::sync::atomic::AtomicBool; + +/// Scans and parses every record (convenience for tests and small inputs). +pub fn parse_all(bytes: &[u8], encoding: TextEncoding) -> Vec<(GameEntry, ParsedGame)> { + let entries = + scan_games(bytes, encoding, &mut |_| {}, &AtomicBool::new(false)).unwrap_or_default(); + entries + .into_iter() + .map(|e| { + let parsed = parse_game_range(bytes, e.byte_range.clone(), e.first_line, encoding); + (e, parsed) + }) + .collect() +} diff --git a/crates/chess-core/src/pgn/parse.rs b/crates/chess-core/src/pgn/parse.rs new file mode 100644 index 0000000..2fb4f8b --- /dev/null +++ b/crates/chess-core/src/pgn/parse.rs @@ -0,0 +1,859 @@ +//! Full parse of one PGN record into a [`Game`] with diagnostics. + +use std::ops::Range; + +use shakmaty::{ + Chess, Position, + san::{San, SanError, SanPlus}, +}; + +use crate::diagnostic::{Diagnostic, DiagnosticCode, Severity, SourceLocation}; +use crate::encoding::{TextEncoding, decode_text}; +use crate::game::{Game, GameMove, GameResult, MoveKind, NodeId, play_null}; +use crate::nag::Nag; +use crate::pgn::lexer::{Lexer, TokKind, Token, parse_tag}; +use crate::repair::{LetterRepairCounts, repair_letters}; +use crate::start::{FenRepair, StartPosition}; + +/// A parsed record: the game tree plus everything noticed on the way. +#[derive(Clone, Debug)] +pub struct ParsedGame { + pub game: Game, + pub diagnostics: Vec, +} + +impl ParsedGame { + pub fn max_severity(&self) -> Option { + self.diagnostics.iter().map(|d| d.severity).max() + } +} + +/// Parses the first record in `bytes` (offsets relative to `bytes`). +pub fn parse_game(bytes: &[u8], encoding: TextEncoding) -> ParsedGame { + let start = if bytes.starts_with(b"\xEF\xBB\xBF") { + 3 + } else { + 0 + }; + parse_game_range(bytes, start..bytes.len(), 1, encoding) +} + +/// Parses UTF-8 text (e.g. clipboard). +pub fn parse_str(text: &str) -> ParsedGame { + parse_game(text.as_bytes(), TextEncoding::Utf8) +} + +/// Parses the record at `range` of a file; diagnostics use absolute offsets and +/// lines (`first_line` is the line at `range.start`). +pub fn parse_game_range( + bytes: &[u8], + range: Range, + first_line: u32, + encoding: TextEncoding, +) -> ParsedGame { + parse_game_range_with(bytes, range, first_line, encoding, &ParseOptions::default()) +} + +/// Options for [`parse_game_range_with`]. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct ParseOptions { + /// Restore letters replaced by ASCII sequences in comments + /// (see [`crate::repair`]). Enable only for sources where + /// [`crate::repair::detect_letter_substitution`] reported the pattern. + pub repair_letters: bool, +} + +/// Like [`parse_game_range`] with options. +pub fn parse_game_range_with( + bytes: &[u8], + range: Range, + first_line: u32, + encoding: TextEncoding, + options: &ParseOptions, +) -> ParsedGame { + let mut lx = Lexer::new(bytes, range.start, range.end, first_line); + let mut diags = Vec::new(); + let mut decode_errors = false; + + // --- header ----------------------------------------------------------- + let mut tags: Vec<(String, String)> = Vec::new(); + let mut first_movetext: Option = None; + while let Some(tok) = lx.next_token() { + match tok.kind { + TokKind::Tag { malformed } => { + let loc = Some(SourceLocation { + byte_offset: tok.start, + line: tok.line, + }); + match parse_tag(bytes, &tok, encoding) { + Some((name, value, err)) => { + decode_errors |= err; + if malformed { + diags.push(diag( + Severity::Warning, + DiagnosticCode::MalformedTag, + format!("tag {name} is not properly closed"), + loc, + None, + )); + } + if tags.iter().any(|(k, _)| *k == name) { + diags.push(diag( + Severity::Info, + DiagnosticCode::DuplicateTag, + format!("duplicate tag {name} (all occurrences kept)"), + loc, + None, + )); + } + tags.push((name, value)); + } + None => { + let (raw, _) = decode_text(encoding, &bytes[tok.start..tok.end]); + diags.push(diag( + Severity::Warning, + DiagnosticCode::MalformedTag, + format!("unparsable tag line dropped: {raw}"), + loc, + None, + )); + } + } + } + TokKind::Escape => {} + _ => { + first_movetext = Some(tok); + break; + } + } + } + + // --- start position --------------------------------------------------- + let tag = |name: &str| { + tags.iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.as_str()) + }; + let header_loc = Some(SourceLocation { + byte_offset: range.start, + line: first_line, + }); + let mut fen_failed = false; + let start = match tag("FEN") { + Some(fen) => { + if tag("SetUp").map(str::trim) != Some("1") { + diags.push(diag( + Severity::Info, + DiagnosticCode::FenWithoutSetUp, + "FEN tag without SetUp \"1\"; FEN used".into(), + header_loc, + None, + )); + } + match StartPosition::from_fen(fen) { + Ok(start) => { + for r in start.repairs() { + let (sev, code, msg) = match r { + FenRepair::FullmoveZero => ( + Severity::Info, + DiagnosticCode::FenFullmoveZero, + "FEN fullmove number 0 treated as 1; tag kept unchanged", + ), + FenRepair::InvalidCastlingRightsDropped => ( + Severity::Warning, + DiagnosticCode::FenRepaired, + "invalid castling rights in FEN ignored", + ), + FenRepair::InvalidEnPassantDropped => ( + Severity::Warning, + DiagnosticCode::FenRepaired, + "invalid en passant square in FEN ignored", + ), + FenRepair::ImpossibleCheckAccepted => ( + Severity::Warning, + DiagnosticCode::FenRepaired, + "FEN has an impossible check; accepted", + ), + FenRepair::TooMuchMaterialAccepted => ( + Severity::Warning, + DiagnosticCode::FenRepaired, + "FEN has too much material; accepted", + ), + }; + diags.push(diag(sev, code, msg.into(), header_loc, None)); + } + start + } + Err(e) => { + fen_failed = true; + diags.push(diag( + Severity::Error, + DiagnosticCode::InvalidFen, + format!("{e}: {fen}; movetext kept as raw text"), + header_loc, + None, + )); + StartPosition::standard() + } + } + } + None => { + if tag("SetUp").map(str::trim) == Some("1") { + diags.push(diag( + Severity::Warning, + DiagnosticCode::SetUpWithoutFen, + "SetUp \"1\" without FEN; standard position used".into(), + header_loc, + None, + )); + } + StartPosition::standard() + } + }; + if let Some(v) = tag("Variant") { + let v = v.trim().to_ascii_lowercase(); + if !matches!( + v.as_str(), + "" | "standard" | "chess" | "from position" | "normal" + ) { + diags.push(diag( + Severity::Warning, + DiagnosticCode::UnsupportedVariant, + format!("variant {v} is not supported; parsed as standard chess"), + header_loc, + None, + )); + } + } + + let game = Game::with_start(start, tags); + let mut b = Builder { + bytes, + encoding, + game, + diags, + cur: NodeId::ROOT, + line_moves: 0, + stack: Vec::new(), + pending: Vec::new(), + fresh: false, + unknown: None, + decode_errors, + unclosed_reported: false, + repair_letters: options.repair_letters, + repaired: LetterRepairCounts::default(), + }; + + if let Some(first) = first_movetext { + if fen_failed { + b.skip_raw(&mut lx, first); + } else { + b.run(&mut lx, first); + } + } + b.finish(range.end, lx.line()) +} + +fn diag( + severity: Severity, + code: DiagnosticCode, + message: String, + location: Option, + node: Option, +) -> Diagnostic { + Diagnostic { + severity, + code, + message, + location, + node, + } +} + +struct Frame { + resume: NodeId, + line_moves: usize, +} + +struct Builder<'a> { + bytes: &'a [u8], + encoding: TextEncoding, + game: Game, + diags: Vec, + cur: NodeId, + /// Moves played in the current line (variation or main line). + line_moves: usize, + stack: Vec, + /// Comments waiting for the next move (after `(` or `)`). + pending: Vec, + fresh: bool, + /// Accumulated unrecognized words: (start, end, line). + unknown: Option<(usize, usize, u32)>, + decode_errors: bool, + unclosed_reported: bool, + repair_letters: bool, + repaired: LetterRepairCounts, +} + +enum Word { + Result(GameResult), + MoveNumber, + Move { san: SanPlus, nag: Option }, + SymbolNag(Nag), + Unknown, +} + +fn classify(word: &[u8]) -> Word { + match word { + b"1-0" => return Word::Result(GameResult::WhiteWins), + b"0-1" => return Word::Result(GameResult::BlackWins), + b"1/2-1/2" => return Word::Result(GameResult::Draw), + b"*" => return Word::Result(GameResult::Unknown), + _ => {} + } + if word == "½-½".as_bytes() { + return Word::Result(GameResult::Draw); + } + if let Ok(s) = std::str::from_utf8(word) + && let Some(nag) = Nag::from_symbol(s) + { + return Word::SymbolNag(nag); + } + // Castling written with zeros (`0-0`, `0-0-0`), possibly after a move number. + if let Some(i) = find_zero_castling(word) { + let mut fixed = word.to_vec(); + for b in &mut fixed[i..] { + if *b == b'0' { + *b = b'O'; + } + } + return classify_owned(&fixed); + } + // Strip a move number prefix: digits followed by dots, or leading dots. + let digits = word.iter().take_while(|b| b.is_ascii_digit()).count(); + let rest = &word[digits..]; + let dots = rest.iter().take_while(|b| **b == b'.').count(); + let rest = &rest[dots..]; + if rest.is_empty() { + return if digits > 0 || dots > 0 { + Word::MoveNumber + } else { + Word::Unknown + }; + } + if digits > 0 && dots == 0 { + return Word::Unknown; + } + classify_san(rest) +} + +/// Index where a zero-castling (`0-0`) starts: at 0 or after `.`. +fn find_zero_castling(word: &[u8]) -> Option { + if word.starts_with(b"0-0") && !matches!(word, b"0-1") { + return Some(0); + } + let digits = word.iter().take_while(|b| b.is_ascii_digit()).count(); + let dots = word[digits..].iter().take_while(|b| **b == b'.').count(); + (dots > 0 && word[digits + dots..].starts_with(b"0-0")).then_some(digits + dots) +} + +fn classify_owned(word: &[u8]) -> Word { + // Same as `classify` without the zero-castling rewrite (already applied). + let digits = word.iter().take_while(|b| b.is_ascii_digit()).count(); + let rest = &word[digits..]; + let dots = rest.iter().take_while(|b| **b == b'.').count(); + classify_san(&rest[dots..]) +} + +fn classify_san(rest: &[u8]) -> Word { + match SanPlus::from_ascii_prefix(rest) { + Ok((san, n)) => { + let suffix = &rest[n..]; + if suffix.is_empty() { + return Word::Move { san, nag: None }; + } + match std::str::from_utf8(suffix).ok().and_then(Nag::from_symbol) { + Some(nag) if nag.is_move_assessment() => Word::Move { + san, + nag: Some(nag), + }, + _ => Word::Unknown, + } + } + Err(_) => Word::Unknown, + } +} + +impl Builder<'_> { + fn loc(tok: &Token) -> Option { + Some(SourceLocation { + byte_offset: tok.start, + line: tok.line, + }) + } + + fn text(&mut self, start: usize, end: usize) -> String { + let (t, err) = decode_text(self.encoding, self.bytes.get(start..end).unwrap_or(&[])); + self.decode_errors |= err; + t + } + + fn node_mut(&mut self, id: NodeId) -> &mut crate::game::Node { + // `cur` and stack entries are always valid ids created by this builder. + let len = self.game.nodes.len(); + &mut self.game.nodes[id.index().min(len - 1)] + } + + fn place_comment(&mut self, text: String) { + let text = if self.repair_letters { + let (fixed, counts) = repair_letters(&text); + self.repaired.add(&counts); + fixed + } else { + text + }; + if self.fresh { + self.pending.push(text); + } else { + let cur = self.cur; + self.node_mut(cur).comments_after.push(text); + } + } + + fn flush_unknown(&mut self) { + if let Some((start, end, line)) = self.unknown.take() { + let raw = self.text(start, end); + let text = raw.split_whitespace().collect::>().join(" "); + let preview: String = text + .chars() + .take(80) + .collect::() + .trim_end() + .to_owned(); + self.place_comment(text); + let node = Some(self.cur); + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::UnrecognizedText, + format!("text outside comment braces kept as a comment: {preview}"), + Some(SourceLocation { + byte_offset: start, + line, + }), + node, + )); + } + } + + fn run(&mut self, lx: &mut Lexer<'_>, first: Token) { + let mut next = Some(first); + while let Some(tok) = next.take().or_else(|| lx.next_token()) { + if tok.kind != TokKind::Word && !matches!(tok.kind, TokKind::Tag { .. }) { + self.flush_unknown(); + } + match tok.kind { + TokKind::Tag { .. } => self.add_unknown(&tok), + TokKind::Comment { terminated } => { + let (s, e) = tok.comment_content(); + let text = self.text(s, e).trim().to_owned(); + if !terminated { + let node = Some(self.cur); + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::UnterminatedComment, + "comment without closing brace; kept up to the end of the record" + .into(), + Self::loc(&tok), + node, + )); + } + self.place_comment(text); + } + TokKind::LineComment => { + let text = self.text(tok.start + 1, tok.end).trim().to_owned(); + self.place_comment(text); + } + TokKind::Escape => { + let text = self.text(tok.start, tok.end); + self.diags.push(diag( + Severity::Info, + DiagnosticCode::EscapeLine, + format!("escape line ignored: {}", text.trim_end()), + Self::loc(&tok), + None, + )); + } + TokKind::StrayCloseBrace => { + let node = Some(self.cur); + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::StrayClosingBrace, + "'}' outside a comment ignored; the comment was probably closed early" + .into(), + Self::loc(&tok), + node, + )); + } + TokKind::Nag => { + let digits = &self.bytes[tok.start + 1..tok.end]; + match std::str::from_utf8(digits) + .ok() + .and_then(|s| s.parse::().ok()) + { + Some(n) => { + let cur = self.cur; + self.node_mut(cur).nags.push(Nag(n)); + } + None => self.add_unknown(&tok), + } + } + TokKind::Open => { + if self.line_moves == 0 { + // Nothing to vary: keep the whole parenthesized text raw. + let node = Some(self.cur); + self.diags.push(diag( + Severity::Error, + DiagnosticCode::VariationWithoutMove, + "variation before any move; kept as raw text".into(), + Self::loc(&tok), + node, + )); + self.skip_group(lx, tok); + continue; + } + let resume = self.cur; + let base = self.game.parent(resume).unwrap_or(NodeId::ROOT); + self.stack.push(Frame { + resume, + line_moves: self.line_moves, + }); + self.cur = base; + self.line_moves = 0; + self.fresh = true; + } + TokKind::Close => self.close_variation(&tok), + TokKind::Word => { + let class = classify(&self.bytes[tok.start..tok.end]); + if matches!(class, Word::Unknown) { + self.add_unknown(&tok); + continue; + } + self.flush_unknown(); + match class { + Word::Result(r) => { + if self.stack.is_empty() { + if self.game.result.is_some() { + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::ResultMismatch, + "second termination marker ignored".into(), + Self::loc(&tok), + None, + )); + } else { + self.game.result = Some(r); + } + } else { + self.diags.push(diag( + Severity::Info, + DiagnosticCode::ResultInVariation, + format!("result {} inside a variation ignored", r.as_str()), + Self::loc(&tok), + Some(self.cur), + )); + } + } + Word::MoveNumber => {} + Word::SymbolNag(n) => { + let cur = self.cur; + self.node_mut(cur).nags.push(n); + } + Word::Move { san, nag } => { + if !self.play(san, nag, &tok) + && let Some(close) = self.skip_raw(lx, tok) + { + self.close_variation(&close); + } + } + Word::Unknown => {} + } + } + } + } + } + + fn add_unknown(&mut self, tok: &Token) { + self.unknown = Some(match self.unknown { + Some((s, _, line)) => (s, tok.end, line), + None => (tok.start, tok.end, tok.line), + }); + } + + fn close_variation(&mut self, tok: &Token) { + let Some(frame) = self.stack.pop() else { + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::UnmatchedCloseParen, + "')' without matching '(' ignored".into(), + Self::loc(tok), + Some(self.cur), + )); + return; + }; + let target = if self.line_moves == 0 { + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::EmptyVariation, + "empty variation".into(), + Self::loc(tok), + Some(frame.resume), + )); + frame.resume + } else { + self.cur + }; + if !self.pending.is_empty() { + let pending = std::mem::take(&mut self.pending); + self.diags.push(diag( + Severity::Info, + DiagnosticCode::CommentMoved, + "comment after a nested variation at the end of a line attached to the last move" + .into(), + Self::loc(tok), + Some(target), + )); + self.node_mut(target).comments_after.extend(pending); + } + self.cur = frame.resume; + self.line_moves = frame.line_moves; + self.fresh = true; + } + + /// Plays a SAN in the current position. Returns false if illegal. + fn play(&mut self, san: SanPlus, nag: Option, tok: &Token) -> bool { + let pos: Chess = match self.game.position(self.cur) { + Some(p) => p.clone(), + None => return false, + }; + let (kind, display, position) = if san.san == San::Null { + match play_null(&pos) { + Ok(p) => (MoveKind::Null, "--".to_owned(), p), + Err(e) => { + self.report_illegal(tok, &format!("null move impossible ({e}):")); + return false; + } + } + } else { + match san.san.to_move(&pos) { + Ok(m) => { + let display = SanPlus::from_move(pos.clone(), m).to_string(); + let mut after = pos; + after.play_unchecked(m); + (MoveKind::Normal(m), display, after) + } + Err(err) => { + let why = match err { + SanError::AmbiguousSan => "ambiguous move", + _ => "illegal move", + }; + self.report_illegal(tok, why); + return false; + } + } + }; + let id = self + .game + .push_child(self.cur, GameMove { kind, san: display }, position); + let pending = std::mem::take(&mut self.pending); + let node = self.node_mut(id); + node.comments_before = pending; + if let Some(n) = nag { + node.nags.push(n); + } + self.cur = id; + self.line_moves += 1; + self.fresh = false; + true + } + + fn report_illegal(&mut self, tok: &Token, why: &str) { + let word = self.text(tok.start, tok.end); + let fen = self.game.fen(self.cur).unwrap_or_default(); + self.diags.push(diag( + Severity::Error, + DiagnosticCode::IllegalMove, + format!("{why} {word} in position {fen}; rest of the line kept as raw text"), + Self::loc(tok), + Some(self.cur), + )); + } + + /// For `(` without a move: keeps the balanced group including its `)` raw. + fn skip_group(&mut self, lx: &mut Lexer<'_>, open: Token) { + let mut depth = 0usize; + let mut end = open.end; + while let Some(t) = lx.next_token() { + end = t.end; + match t.kind { + TokKind::Open => depth += 1, + TokKind::Close => { + if depth == 0 { + break; + } + depth -= 1; + } + _ => {} + } + } + let raw = self.text(open.start, end).trim().to_owned(); + let cur = self.cur; + self.node_mut(cur).unparsed.push(raw); + } + + /// Skips from `first` (inclusive) to the end of the current line, keeping + /// the text verbatim in `cur.unparsed`. Returns the `)` that closes the + /// current variation (not consumed into the raw text), if any. A trailing + /// top-level result is not part of the raw text. + fn skip_raw(&mut self, lx: &mut Lexer<'_>, first: Token) -> Option { + let mut depth = 0usize; + let mut end = first.end; + let mut trailing_result: Option<(usize, GameResult)> = None; + let mut close = None; + let mut tok = Some(first); + // `first` itself may be `(`/`)` only when called for an invalid FEN. + while let Some(t) = tok.take().or_else(|| lx.next_token()) { + match t.kind { + TokKind::Open => depth += 1, + TokKind::Close => { + if depth == 0 && !self.stack.is_empty() { + close = Some(t); + break; + } + depth = depth.saturating_sub(1); + } + _ => {} + } + trailing_result = None; + if t.kind == TokKind::Word + && depth == 0 + && self.stack.is_empty() + && let Word::Result(r) = classify(&self.bytes[t.start..t.end]) + { + trailing_result = Some((t.start, r)); + } + end = t.end; + } + let raw_end = match trailing_result { + Some((start, r)) => { + if self.game.result.is_none() { + self.game.result = Some(r); + } + start + } + None => end, + }; + let raw = self.text(first.start, raw_end).trim().to_owned(); + if !raw.is_empty() { + let cur = self.cur; + self.node_mut(cur).unparsed.push(raw); + } + close + } + + fn finish(mut self, end: usize, line: u32) -> ParsedGame { + self.flush_unknown(); + let loc = Some(SourceLocation { + byte_offset: end, + line, + }); + while !self.stack.is_empty() { + if !self.unclosed_reported { + self.unclosed_reported = true; + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::UnclosedVariation, + "variation not closed before the end of the record".into(), + loc, + Some(self.cur), + )); + } + let tok = Token { + kind: TokKind::Close, + start: end, + end, + line, + }; + self.close_variation(&tok); + } + if !self.pending.is_empty() { + let pending = std::mem::take(&mut self.pending); + let cur = self.cur; + self.diags.push(diag( + Severity::Info, + DiagnosticCode::CommentMoved, + "comment after the last variation of the game attached to the last move".into(), + loc, + Some(cur), + )); + self.node_mut(cur).comments_after.extend(pending); + } + if self.repaired.total() > 0 { + let c = self.repaired; + self.diags.push(diag( + Severity::Info, + DiagnosticCode::LettersRestored, + format!( + "restored letters replaced in the source: {} (ч {}, Ч {}, ÑŽ {}, Ю {}); original kept in raw text", + c.total(), + c.ch_lower, + c.ch_upper, + c.yu_lower, + c.yu_upper + ), + None, + None, + )); + } + if self.decode_errors { + self.diags.push(diag( + Severity::Warning, + DiagnosticCode::DecodeError, + format!( + "text is not valid {}; replacement characters inserted", + self.encoding.label() + ), + None, + None, + )); + } + let tag_result = self.game.tag("Result").map(str::to_owned); + match ( + self.game.result, + tag_result.as_deref().and_then(GameResult::from_pgn), + ) { + (Some(m), Some(t)) if m != t => self.diags.push(diag( + Severity::Warning, + DiagnosticCode::ResultMismatch, + format!( + "Result tag {} differs from termination marker {}", + t.as_str(), + m.as_str() + ), + loc, + None, + )), + (None, _) => self.diags.push(diag( + Severity::Info, + DiagnosticCode::MissingResult, + "no termination marker".into(), + loc, + None, + )), + _ => {} + } + ParsedGame { + game: self.game, + diagnostics: self.diags, + } + } +} diff --git a/crates/chess-core/src/pgn/scan.rs b/crates/chess-core/src/pgn/scan.rs new file mode 100644 index 0000000..87b1c9e --- /dev/null +++ b/crates/chess-core/src/pgn/scan.rs @@ -0,0 +1,392 @@ +//! Fast index scan of a multi-game PGN file (no move parsing). + +use std::ops::Range; +use std::sync::atomic::{AtomicBool, Ordering}; + +use crate::encoding::TextEncoding; +use crate::pgn::lexer::{Lexer, TokKind, parse_tag}; + +/// Summary flags computed while scanning. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct EntryFlags { + pub has_fen: bool, + pub has_comments: bool, + /// A comment with words in it, not only commands such as `[%clk 0:10:07]` or + /// `[%eval 0.3]` (clocks of online games are no comments to look for). + pub has_text_comments: bool, + pub has_variations: bool, + pub has_nags: bool, + /// A `--` token outside comments (teaching null move). + pub has_null_moves: bool, + /// Structural problems found by the scanner (unbalanced parentheses, + /// stray `}`, unterminated comment, malformed tag). Full parse gives details. + pub has_structure_issues: bool, + /// Text could not be decoded cleanly (UTF-8 replacement characters). + pub has_decode_errors: bool, + /// No movetext tokens at all (tags only). + pub empty_movetext: bool, +} + +/// One record of a PGN file. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GameEntry { + /// 0-based ordinal in the file. + pub index: usize, + /// Byte range in the original file (includes trailing whitespace). + pub byte_range: Range, + /// 1-based line where the record starts. + pub first_line: u32, + /// All tags in source order (decoded). + pub tags: Vec<(String, String)>, + pub flags: EntryFlags, + /// Half-moves of the main line (outside variations), as written. + pub main_plies: u32, + /// Half-moves of the whole tree, variations included. + pub all_plies: u32, +} + +impl GameEntry { + pub fn tag(&self, name: &str) -> Option<&str> { + self.tags + .iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.as_str()) + } + pub fn white(&self) -> Option<&str> { + self.tag("White") + } + pub fn black(&self) -> Option<&str> { + self.tag("Black") + } + pub fn white_elo(&self) -> Option { + self.tag("WhiteElo").and_then(|v| v.trim().parse().ok()) + } + pub fn black_elo(&self) -> Option { + self.tag("BlackElo").and_then(|v| v.trim().parse().ok()) + } + pub fn result(&self) -> Option<&str> { + self.tag("Result") + } + pub fn date(&self) -> Option<&str> { + self.tag("Date") + } + pub fn event(&self) -> Option<&str> { + self.tag("Event") + } + pub fn eco(&self) -> Option<&str> { + self.tag("ECO") + } + /// Moves of the main line: the `PlyCount` tag when the file has it, else counted. + pub fn moves(&self) -> u32 { + self.ply_count().unwrap_or(self.main_plies).div_ceil(2) + } + + /// When the game was played, as text that sorts by time: `UTCDate` and `UTCTime` + /// when both are there (Lichess, Chess.com), else `Date`. + pub fn played_at(&self) -> String { + match (self.tag("UTCDate"), self.tag("UTCTime")) { + (Some(d), Some(t)) => format!("{d} {t}"), + _ => self.date().unwrap_or("").to_owned(), + } + } + + pub fn ply_count(&self) -> Option { + self.tag("PlyCount").and_then(|v| v.trim().parse().ok()) + } +} + +/// Progress report, called roughly every 64 KiB and at the end. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ScanProgress { + pub bytes_done: usize, + pub bytes_total: usize, + pub games: usize, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("scan cancelled")] +pub struct Cancelled; + +const PROGRESS_STEP: usize = 64 * 1024; + +/// Splits `bytes` into records. Thread-safe to call from a background thread; +/// `cancel` is polled between tokens. +/// +/// Record boundaries: a tag line (`[Name "`, at the start of a line, outside +/// comments) after movetext; or a new movetext token after a top-level result. +pub fn scan_games( + bytes: &[u8], + encoding: TextEncoding, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result, Cancelled> { + #[derive(PartialEq)] + enum State { + Between, + Header, + Movetext, + } + + let start = if bytes.starts_with(b"\xEF\xBB\xBF") { + 3 + } else { + 0 + }; + let mut lx = Lexer::new(bytes, start, bytes.len(), 1); + let mut entries: Vec = Vec::new(); + let mut state = State::Between; + let mut cur: Option = None; + let mut depth: i64 = 0; + let mut result_seen = false; + let mut movetext_tokens = 0usize; + let mut next_report = PROGRESS_STEP; + + let finish = |cur: &mut Option, + entries: &mut Vec, + end: usize, + depth: i64, + movetext_tokens: usize| { + if let Some(mut e) = cur.take() { + e.byte_range.end = end; + if depth != 0 { + e.flags.has_structure_issues = true; + } + e.flags.empty_movetext = movetext_tokens == 0; + entries.push(e); + } + }; + + while let Some(tok) = lx.next_token() { + if cancel.load(Ordering::Relaxed) { + return Err(Cancelled); + } + if tok.start >= next_report { + next_report = tok.start + PROGRESS_STEP; + progress(ScanProgress { + bytes_done: tok.start, + bytes_total: bytes.len(), + games: entries.len(), + }); + } + + if tok.kind == TokKind::Escape && state == State::Between { + continue; + } + let is_tag = matches!(tok.kind, TokKind::Tag { .. }); + let new_game = match state { + State::Between => true, + State::Header => false, + State::Movetext => { + is_tag || (result_seen && matches!(tok.kind, TokKind::Word | TokKind::Open)) + } + }; + if new_game { + finish(&mut cur, &mut entries, tok.start, depth, movetext_tokens); + cur = Some(GameEntry { + index: entries.len(), + byte_range: tok.start..tok.start, + first_line: tok.line, + tags: Vec::new(), + flags: EntryFlags::default(), + main_plies: 0, + all_plies: 0, + }); + depth = 0; + result_seen = false; + movetext_tokens = 0; + state = if is_tag { + State::Header + } else { + State::Movetext + }; + } else if !is_tag && state == State::Header { + state = State::Movetext; + } + let Some(entry) = cur.as_mut() else { continue }; + + match tok.kind { + TokKind::Tag { malformed } => { + if state == State::Movetext { + // Unreachable by construction (tag in movetext starts a new game). + continue; + } + match parse_tag(bytes, &tok, encoding) { + Some((name, value, had_errors)) => { + if name == "FEN" { + entry.flags.has_fen = true; + } + entry.flags.has_decode_errors |= had_errors; + entry.tags.push((name, value)); + } + None => entry.flags.has_structure_issues = true, + } + if malformed { + entry.flags.has_structure_issues = true; + } + } + TokKind::Comment { terminated } => { + movetext_tokens += 1; + entry.flags.has_comments = true; + let (from, to) = tok.comment_content(); + if !entry.flags.has_text_comments && has_words(&bytes[from..to.max(from)]) { + entry.flags.has_text_comments = true; + } + if !terminated { + entry.flags.has_structure_issues = true; + } + } + TokKind::LineComment => { + movetext_tokens += 1; + entry.flags.has_comments = true; + entry.flags.has_text_comments = true; + } + TokKind::Escape => {} + TokKind::Open => { + movetext_tokens += 1; + entry.flags.has_variations = true; + depth += 1; + } + TokKind::Close => { + movetext_tokens += 1; + depth -= 1; + if depth < 0 { + entry.flags.has_structure_issues = true; + depth = 0; + } + } + TokKind::StrayCloseBrace => { + movetext_tokens += 1; + entry.flags.has_structure_issues = true; + } + TokKind::Nag => { + movetext_tokens += 1; + entry.flags.has_nags = true; + } + TokKind::Word => { + movetext_tokens += 1; + let w = &bytes[tok.start..tok.end]; + if w == b"--" || w.ends_with(b".--") { + entry.flags.has_null_moves = true; + } + if depth == 0 && matches!(w, b"1-0" | b"0-1" | b"1/2-1/2" | b"*") { + result_seen = true; + lx.allow_tag(); + } else if is_move(w) { + entry.all_plies += 1; + if depth == 0 { + entry.main_plies += 1; + } + } + } + } + } + finish(&mut cur, &mut entries, bytes.len(), depth, movetext_tokens); + progress(ScanProgress { + bytes_done: bytes.len(), + bytes_total: bytes.len(), + games: entries.len(), + }); + Ok(entries) +} + +/// A word of movetext that is a move: not a move number ("12.", "12..."), with or +/// without the move glued to it ("12.e4"), and not the "e.p." of an en passant capture. +fn is_move(w: &[u8]) -> bool { + let rest = &w[w + .iter() + .position(|c| !c.is_ascii_digit() && *c != b'.') + .unwrap_or(w.len())..]; + !rest.is_empty() && rest != b"e.p." +} + +/// Text in a comment besides commands in square brackets (`[%clk …]`, `[%eval …]`, +/// `[%cal …]`). +fn has_words(text: &[u8]) -> bool { + let mut depth = 0usize; + for &c in text { + match c { + b'[' => depth += 1, + b']' => depth = depth.saturating_sub(1), + c if depth == 0 && !c.is_ascii_whitespace() => return true, + _ => {} + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scan(s: &str) -> Vec { + scan_games( + s.as_bytes(), + TextEncoding::Utf8, + &mut |_| {}, + &AtomicBool::new(false), + ) + .expect("scan") + } + + #[test] + fn splits_games_and_reads_tags() { + let s = "[Event \"A\"]\r\n[White \"W\"]\r\n\r\n1. e4 {x\r\n[%cal Ge2e4]} (1. d4) 1-0\r\n\r\n[Event \"B\"]\n[FEN \"8/8/8/8/8/8/8/K1k5 w - - 0 1\"]\n\n1. -- *\n"; + let e = scan(s); + assert_eq!(e.len(), 2); + assert_eq!(e[0].event(), Some("A")); + assert_eq!(e[0].white(), Some("W")); + assert!(e[0].flags.has_comments && e[0].flags.has_variations); + assert!(!e[0].flags.has_structure_issues); + assert_eq!(e[0].byte_range.start, 0); + assert_eq!(e[0].byte_range.end, e[1].byte_range.start); + assert_eq!(e[1].first_line, 7); + assert!(e[1].flags.has_fen && e[1].flags.has_null_moves); + assert_eq!(e[1].byte_range.end, s.len()); + } + + #[test] + fn tagless_games_split_after_result() { + let e = scan("1. e4 e5 1-0\n\n1. d4 d5 *\n"); + assert_eq!(e.len(), 2); + assert!(e[0].tags.is_empty()); + } + + #[test] + fn a_header_on_the_line_of_the_last_result_starts_the_next_game() { + let e = scan("[White \"Aaa\"] 1. e4 e5 * [White \"Ccc\"][Black \"Ddd\"] 1. d4 d5 *\n"); + assert_eq!(e.len(), 2); + assert_eq!(e[1].white(), Some("Ccc")); + assert_eq!(e[1].black(), Some("Ddd")); + } + + #[test] + fn main_line_moves_and_text_comments() { + let e = scan(concat!( + "1. e4 { [%clk 0:10:07] } e5 { [%clk 0:10:08] } 2.Nf3 (2. f4 exf4) 2...Nc6 *\n", + "1. d4 { A quiet start. [%eval 0.2] } d5 1-0\n", + "[PlyCount \"81\"] 1. c4 *\n", + )); + assert_eq!(e[0].main_plies, 4); + assert_eq!(e[0].all_plies, 6); + assert_eq!(e[0].moves(), 2); + assert!(e[0].flags.has_comments && !e[0].flags.has_text_comments); + assert!(e[1].flags.has_text_comments); + assert_eq!(e[1].moves(), 1); + assert_eq!(e[2].moves(), 41); + } + + #[test] + fn cancellation() { + let cancel = AtomicBool::new(true); + let r = scan_games(b"[A \"b\"]\n*", TextEncoding::Utf8, &mut |_| {}, &cancel); + assert_eq!(r, Err(Cancelled)); + } + + #[test] + fn empty_input() { + assert!(scan("").is_empty()); + assert!(scan(" \n\n").is_empty()); + } +} diff --git a/crates/chess-core/src/pgn/store.rs b/crates/chess-core/src/pgn/store.rs new file mode 100644 index 0000000..3985be2 --- /dev/null +++ b/crates/chess-core/src/pgn/store.rs @@ -0,0 +1,675 @@ +//! Writing records into a PGN file the user keeps (docs/design/own-databases.md): one +//! record appended to the end, a record replaced or removed, a removed record put +//! back (undo). Every write is explicit, and the other records stay byte for byte as +//! they were: an append only adds at the end; a replacement or a removal writes the +//! whole file anew into a temporary file beside it and renames it over the old one, +//! after `sync_all`. A file that changed on disk since it was read is not touched. +//! +//! Only files the program decodes as UTF-8 (or plain ASCII) are written: a record is +//! written as UTF-8, so a file in another encoding would end up mixed. The line endings +//! of a new record follow the file's (CRLF when its first line ends so). + +use std::io::{self, Write as _}; +use std::path::Path; + +use crate::database::PgnDatabase; + +/// Why a write did not happen. +#[derive(Debug, thiserror::Error)] +pub enum WriteError { + /// The file on disk is not what was read: another program wrote it meanwhile. + #[error("the file changed on disk since it was read")] + Changed, + /// The database was opened from memory, not from a file. + #[error("the database has no file")] + NoFile, + /// The database's text is not UTF-8: appending UTF-8 would mix encodings. + #[error("the file is not in UTF-8")] + Encoding, + #[error("no record {0}")] + NoRecord(usize), + #[error(transparent)] + Io(#[from] io::Error), +} + +/// What an append tells about the record it wrote: where it starts in the file (after +/// the file is read again, the record whose range starts here is the new one). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Appended { + pub offset: u64, +} + +/// A record removed from the file, enough to put it back where it was (undo). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Removed { + pub index: usize, + pub bytes: Vec, +} + +/// `"\r\n"` when the first line of `bytes` ends so, else `"\n"`. +fn line_ending(bytes: &[u8]) -> &'static str { + match bytes.iter().position(|b| *b == b'\n') { + Some(i) if i > 0 && bytes[i - 1] == b'\r' => "\r\n", + _ => "\n", + } +} + +/// `record` with its line endings as the file has them, ending with one blank line. +fn record_bytes(record: &str, eol: &str) -> Vec { + let text = record.trim_end(); + let mut out = String::with_capacity(text.len() + 4); + for line in text.split('\n') { + out.push_str(line.trim_end_matches('\r')); + out.push_str(eol); + } + out.push_str(eol); + out.into_bytes() +} + +/// What to put between the end of `bytes` and an appended record, so that the record +/// starts after a blank line: nothing, one or two line endings. +fn separator(bytes: &[u8], eol: &str) -> &'static str { + let ends_with = |suffix: &str| bytes.ends_with(suffix.as_bytes()); + if bytes.is_empty() || ends_with(&format!("{eol}{eol}")) { + "" + } else if ends_with(eol) { + if eol == "\r\n" { "\r\n" } else { "\n" } + } else if eol == "\r\n" { + "\r\n\r\n" + } else { + "\n\n" + } +} + +fn check_writable(db: &PgnDatabase) -> Result<&Path, WriteError> { + let path = db.path().ok_or(WriteError::NoFile)?; + if db.encoding() != crate::encoding::TextEncoding::Utf8 && !db.detected_encoding().ascii_only { + return Err(WriteError::Encoding); + } + if db.source_changed()? { + return Err(WriteError::Changed); + } + Ok(path) +} + +/// Appends `record` (PGN text of one game) to the file of `db`. The file is opened for +/// appending, so a record added by someone else meanwhile is not lost; the file's bytes +/// before the new record stay as they were. +pub fn append(db: &PgnDatabase, record: &str) -> Result { + let path = check_writable(db)?; + let (data, sep) = tail_for(db.bytes(), record); + let mut file = std::fs::OpenOptions::new().append(true).open(path)?; + let offset = file.metadata()?.len() + sep as u64; + file.write_all(&data)?; + file.sync_all()?; + Ok(Appended { offset }) +} + +/// What goes at the end of `bytes` to add `record` after a blank line, and how many of +/// its bytes come before the record. +fn tail_for(bytes: &[u8], record: &str) -> (Vec, usize) { + let eol = line_ending(bytes); + let sep = separator(bytes, eol); + let mut data = sep.as_bytes().to_vec(); + data.extend(record_bytes(record, eol)); + (data, sep.len()) +} + +/// The text of `db` with `record` added at the end, and where the record starts: the +/// same bytes [`append`] writes, for a database kept elsewhere than in a file (the web +/// version's games in the browser). +pub fn appended(db: &PgnDatabase, record: &str) -> (Vec, u64) { + let bytes = db.bytes(); + let (tail, sep) = tail_for(bytes, record); + let mut out = Vec::with_capacity(bytes.len() + tail.len()); + out.extend_from_slice(bytes); + out.extend(tail); + (out, (bytes.len() + sep) as u64) +} + +/// The text of `db` with record `index` replaced by `record` (what [`replace`] writes). +pub fn replaced(db: &PgnDatabase, index: usize, record: &str) -> Result, WriteError> { + let bytes = db.bytes(); + let range = db + .entries() + .get(index) + .ok_or(WriteError::NoRecord(index))? + .byte_range + .clone(); + let eol = line_ending(bytes); + let mut out = Vec::with_capacity(bytes.len() + record.len()); + out.extend_from_slice(&bytes[..range.start]); + out.extend(record_bytes(record, eol)); + out.extend_from_slice(&bytes[range.end..]); + Ok(out) +} + +/// The text of `db` without record `index` (what [`remove`] writes) and the record. +pub fn removed(db: &PgnDatabase, index: usize) -> Result<(Vec, Removed), WriteError> { + let bytes = db.bytes(); + let range = db + .entries() + .get(index) + .ok_or(WriteError::NoRecord(index))? + .byte_range + .clone(); + let mut out = Vec::with_capacity(bytes.len()); + out.extend_from_slice(&bytes[..range.start]); + out.extend_from_slice(&bytes[range.end..]); + Ok(( + out, + Removed { + index, + bytes: bytes[range].to_vec(), + }, + )) +} + +/// Replaces record `index` with `record`; every other byte of the file stays. +pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> { + let path = check_writable(db)?; + write_atomic(path, &replaced(db, index, record)?)?; + Ok(()) +} + +/// Removes record `index`; the bytes before and after it stay. What was removed comes +/// back with [`restore`]. +pub fn remove(db: &PgnDatabase, index: usize) -> Result { + let path = check_writable(db)?; + let (out, gone) = removed(db, index)?; + write_atomic(path, &out)?; + Ok(gone) +} + +/// Puts a removed record back at its place: the file is byte for byte what it was +/// before the removal, as long as nothing else was written in between. `db` is the +/// database as read after the removal. +pub fn restore(db: &PgnDatabase, removed: &Removed) -> Result<(), WriteError> { + let path = check_writable(db)?; + write_atomic(path, &restored(db, removed)?)?; + Ok(()) +} + +/// The text of `db` with a removed record back at its place (what [`restore`] writes). +pub fn restored(db: &PgnDatabase, removed: &Removed) -> Result, WriteError> { + let bytes = db.bytes(); + let at = match db.entries().get(removed.index) { + Some(e) => e.byte_range.start, + None if removed.index == db.len() => bytes.len(), + None => return Err(WriteError::NoRecord(removed.index)), + }; + let mut out = Vec::with_capacity(bytes.len() + removed.bytes.len()); + out.extend_from_slice(&bytes[..at]); + out.extend_from_slice(&removed.bytes); + out.extend_from_slice(&bytes[at..]); + Ok(out) +} + +/// Writes every record of `db` into `dest` as UTF-8 (LF, one blank line between +/// records): a copy of a file in another encoding, which can then be written to. `db` +/// itself is not touched. `dest` must not exist. +pub fn write_utf8_copy(db: &PgnDatabase, dest: &Path) -> io::Result<()> { + if dest.exists() { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!("{} exists", dest.display()), + )); + } + let mut out = Vec::with_capacity(db.byte_len()); + // Letters the source writes as `~~`/`o^` (see repair.rs) are restored in the copy, + // as they are on the screen: the copy is read as UTF-8, where nothing is restored. + let restore = db.repair_letters_enabled(); + for i in 0..db.len() { + if let Some(text) = db.raw_text(i) { + let text = if restore { + crate::repair::repair_letters(&text).0 + } else { + text + }; + out.extend(record_bytes(&text, "\n")); + } + } + write_atomic(dest, &out) +} + +/// What makes two records the same game for [`find_same_game`]: the players (without +/// case) and the date, the start position and the moves of the main line. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct SameGame { + white: String, + black: String, + date: String, + fen: Option, + moves: Vec, +} + +fn same_name(v: Option<&str>) -> String { + v.unwrap_or("?").trim().to_lowercase() +} + +fn same_date(v: Option<&str>) -> String { + // An unknown date in any spelling is one value. + match v.map(str::trim) { + None | Some("" | "?") => "????.??.??".to_owned(), + Some(d) => d.to_owned(), + } +} + +/// The identity of `game` for finding the same game (see [`SameGame`]). +pub fn same_game(game: &crate::Game) -> SameGame { + SameGame { + white: same_name(game.tag("White")), + black: same_name(game.tag("Black")), + date: same_date(game.tag("Date")), + fen: game.tag("FEN").map(str::to_owned), + moves: game + .mainline() + .iter() + .filter_map(|id| game.game_move(*id).map(|m| m.san.clone())) + .collect(), + } +} + +/// The bytes an append writes for `record` into a file that holds only records written +/// so (starting empty): a new database filled in one go has the same bytes as one +/// filled by [`append`] record after record. +pub fn record_for_new_file(record: &str) -> Vec { + record_bytes(record, "\n") +} + +/// The record of `db` that is the same game as `game`: the same players and date, and +/// the same moves of the main line. `None` when there is none. +pub fn find_same_game(db: &PgnDatabase, game: &crate::Game) -> Option { + let key = same_game(game); + (0..db.len()).find(|&i| { + let e = &db.entries()[i]; + if same_name(e.white()) != key.white + || same_name(e.black()) != key.black + || same_date(e.date()) != key.date + { + return false; + } + // Two studies from different positions are different games. + db.load_game(i) + .is_some_and(|parsed| same_game(&parsed.game) == key) + }) +} + +/// A date as the user types it — `2026.10.18`, `18.10.2026`, `2026-10-18`, `2026.10`, +/// `2026`, nothing — as PGN writes it (`2026.10.18`, `2026.10.??`, `????.??.??`). +/// `None` for text that is not a date. +pub fn pgn_date(input: &str) -> Option { + let t = input.trim(); + if t.is_empty() || t.chars().all(|c| c == '?' || c == '.') { + return Some("????.??.??".to_owned()); + } + let parts: Vec<&str> = t.split(['.', '-', '/']).map(str::trim).collect(); + let num = |s: &str| s.parse::().ok(); + // A month or day may be unknown, as PGN writes it: "1910.??.??". + let part = |s: &str| -> Option> { + if !s.is_empty() && s.chars().all(|c| c == '?') { + Some(None) + } else { + num(s).map(Some) + } + }; + // A year is written with four digits: "12.10" is not a date. + let (y, m, d) = match parts.as_slice() { + [y] if y.len() == 4 => (num(y)?, None, None), + [y, m] if y.len() == 4 => (num(y)?, part(m)?, None), + [_] | [_, _] => return None, + [a, b, c] => { + if a.len() == 4 && a.chars().all(|c| c.is_ascii_digit()) { + (num(a)?, part(b)?, part(c)?) + } else if c.len() == 4 { + (num(c)?, part(b)?, part(a)?) + } else { + return None; + } + } + _ => return None, + }; + if !(1..=9999).contains(&y) + || m.is_some_and(|m| !(1..=12).contains(&m)) + || d.is_some_and(|d| !(1..=31).contains(&d)) + { + return None; + } + Some(format!( + "{y:04}.{}.{}", + m.map_or("??".to_owned(), |m| format!("{m:02}")), + d.map_or("??".to_owned(), |d| format!("{d:02}")) + )) +} + +/// Writes `bytes` to `path` through a temporary file in the same directory: the old +/// file stays whole until the new one is on disk (`sync_all`), then is replaced. +pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + // A link to the file is a way to it, not the file: the target is rewritten. + let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned()); + let path = target.as_path(); + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir)?; + } + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let tmp = path.with_file_name(format!(".{name}.tmp{}", std::process::id())); + let result = (|| { + let mut file = std::fs::File::create(&tmp)?; + // The file keeps its permissions (a private 600 stays 600). + if let Ok(meta) = std::fs::metadata(path) { + file.set_permissions(meta.permissions())?; + } + file.write_all(bytes)?; + file.sync_all()?; + std::fs::rename(&tmp, path)?; + // The rename itself reaches the disk with the folder. + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) + && let Ok(d) = std::fs::File::open(dir) + { + let _ = d.sync_all(); + } + Ok(()) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pgn::parse_str; + use std::sync::atomic::AtomicBool; + + fn open(path: &Path) -> PgnDatabase { + PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)).expect("opens") + } + + fn dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("cp-store-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + const G1: &str = "[Event \"One\"]\n[White \"A\"]\n[Black \"B\"]\n\n1. e4 e5 *\n"; + const G2: &str = + "[Event \"Two\"]\n[White \"C\"]\n[Black \"D\"]\n\n1. d4 d5 {a comment} 1/2-1/2\n"; + const G3: &str = "[Event \"Three\"]\n[White \"E\"]\n[Black \"F\"]\n\n1. c4 1-0\n"; + + fn new_record() -> String { + parse_str("[Event \"New\"]\n[White \"X\"]\n[Black \"Y\"]\n\n1. Nf3 d5 2. g3 *\n") + .game + .to_pgn() + } + + fn records(db: &PgnDatabase) -> Vec> { + (0..db.len()) + .map(|i| db.raw_bytes(i).unwrap().to_vec()) + .collect() + } + + /// Records without their trailing whitespace: an append adds a blank line after + /// the last one, which is still the same record. + fn trimmed(records: &[Vec]) -> Vec> { + records + .iter() + .map(|r| { + r[..r.len() + - r.iter() + .rev() + .take_while(|b| b.is_ascii_whitespace()) + .count()] + .to_vec() + }) + .collect() + } + + #[test] + fn append_to_files_of_every_shape() { + for (name, content) in [ + ("blank-line", format!("{G1}\n{G2}\n")), + ("one-newline", format!("{G1}\n{G2}")), + ("no-newline", format!("{G1}\n{}", G2.trim_end())), + ("crlf", format!("{G1}\n{G2}").replace('\n', "\r\n")), + ("empty", String::new()), + ] { + let d = dir(name); + let path = d.join("base.pgn"); + std::fs::write(&path, &content).unwrap(); + let db = open(&path); + let before = records(&db); + let added = append(&db, &new_record()).unwrap(); + let after_bytes = std::fs::read(&path).unwrap(); + assert!( + after_bytes.starts_with(content.as_bytes()), + "{name}: old bytes kept" + ); + let db2 = open(&path); + assert_eq!(db2.len(), before.len() + 1, "{name}"); + assert_eq!( + trimmed(&records(&db2)[..before.len()]), + trimmed(&before), + "{name}: old records same" + ); + let new = db2.entries().last().unwrap(); + assert_eq!(new.byte_range.start as u64, added.offset, "{name}: offset"); + assert_eq!(new.white(), Some("X")); + let parsed = db2.load_game(db2.len() - 1).unwrap(); + assert_eq!( + parsed.game.canonical_tree(), + parse_str(&new_record()).game.canonical_tree() + ); + if name == "crlf" { + let text = String::from_utf8(after_bytes).unwrap(); + assert!(!text.contains("[^\r]\n"), "no bare LF"); + assert!(text.ends_with("\r\n\r\n")); + } else { + assert!(after_bytes.ends_with(b"\n\n")); + } + // A second append starts after a blank line too. + let db3 = open(&path); + append(&db3, &new_record()).unwrap(); + assert_eq!(open(&path).len(), before.len() + 2, "{name}: twice"); + } + } + + #[test] + fn replace_keeps_the_other_records() { + for k in 0..3 { + let d = dir(&format!("replace{k}")); + let path = d.join("base.pgn"); + std::fs::write(&path, format!("{G1}\n{G2}\n{G3}\n")).unwrap(); + let db = open(&path); + let before = records(&db); + replace(&db, k, &new_record()).unwrap(); + let db2 = open(&path); + assert_eq!(db2.len(), 3); + let after = records(&db2); + for i in 0..3 { + if i != k { + assert_eq!( + after[i], before[i], + "record {i} unchanged when {k} replaced" + ); + } + } + assert_eq!(db2.entries()[k].white(), Some("X")); + } + // The only record. + let d = dir("replace-only"); + let path = d.join("base.pgn"); + std::fs::write(&path, G1).unwrap(); + replace(&open(&path), 0, &new_record()).unwrap(); + let db = open(&path); + assert_eq!(db.len(), 1); + assert_eq!(db.entries()[0].white(), Some("X")); + } + + #[test] + fn remove_and_restore_are_exact() { + for k in 0..3 { + let d = dir(&format!("remove{k}")); + let path = d.join("base.pgn"); + let content = format!("{G1}\n{G2}\n{G3}\n"); + std::fs::write(&path, &content).unwrap(); + let db = open(&path); + let before = records(&db); + let removed = remove(&db, k).unwrap(); + let db2 = open(&path); + assert_eq!(db2.len(), 2); + let after = records(&db2); + let expected: Vec<_> = before + .iter() + .enumerate() + .filter(|(i, _)| *i != k) + .map(|(_, r)| r.clone()) + .collect(); + assert_eq!(after, expected, "others kept when {k} removed"); + restore(&db2, &removed).unwrap(); + assert_eq!( + std::fs::read(&path).unwrap(), + content.as_bytes(), + "restored byte for byte" + ); + } + } + + #[test] + fn a_changed_file_is_not_written() { + let d = dir("changed"); + let path = d.join("base.pgn"); + std::fs::write(&path, format!("{G1}\n{G2}\n")).unwrap(); + let db = open(&path); + // Another program appends; the modification time moves on. + std::thread::sleep(std::time::Duration::from_millis(20)); + std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(G3.as_bytes()) + .unwrap(); + assert!(db.source_changed().unwrap()); + assert!(matches!( + replace(&db, 0, &new_record()), + Err(WriteError::Changed) + )); + assert!(matches!(remove(&db, 0), Err(WriteError::Changed))); + assert!(matches!( + append(&db, &new_record()), + Err(WriteError::Changed) + )); + } + + /// A crash in the middle of an append leaves a broken tail; the next append goes + /// after it, never into it, and the records before it stay whole. + #[test] + fn a_broken_tail_is_appended_after() { + let d = dir("broken"); + let path = d.join("base.pgn"); + let half = &G2[..G2.len() - 8]; + let content = format!("{G1}\n{half}"); + std::fs::write(&path, &content).unwrap(); + let db = open(&path); + assert_eq!(db.len(), 2); + let added = append(&db, &new_record()).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert!(bytes.starts_with(content.as_bytes())); + assert_eq!( + &bytes[added.offset as usize..], + &record_bytes(&new_record(), "\n")[..] + ); + let db2 = open(&path); + assert_eq!(db2.len(), 3); + assert_eq!(db2.entries()[0].white(), Some("A")); + assert_eq!(db2.entries()[2].white(), Some("X")); + } + + #[test] + fn other_encodings_are_refused_and_copied() { + let d = dir("cp1251"); + let path = d.join("base.pgn"); + let (bytes, _, _) = encoding_rs::WINDOWS_1251 + .encode("[Event \"Турнир\"]\n[White \"Иванов\"]\n[Black \"Петров\"]\n\n1. e4 e5 *\n"); + std::fs::write(&path, &bytes).unwrap(); + let db = open(&path); + assert_eq!(db.encoding(), crate::encoding::TextEncoding::Windows1251); + assert!(matches!( + append(&db, &new_record()), + Err(WriteError::Encoding) + )); + let copy = d.join("base (UTF-8).pgn"); + write_utf8_copy(&db, ©).unwrap(); + assert_eq!( + std::fs::read(&path).unwrap(), + bytes.as_ref(), + "original untouched" + ); + let db2 = open(©); + assert_eq!(db2.encoding(), crate::encoding::TextEncoding::Utf8); + assert_eq!(db2.len(), 1); + assert_eq!(db2.entries()[0].white(), Some("Иванов")); + assert_eq!(db2.raw_text(0), db.raw_text(0)); + assert!( + matches!(write_utf8_copy(&db, ©), Err(e) if e.kind() == io::ErrorKind::AlreadyExists) + ); + } + + #[test] + fn an_empty_file_is_a_database() { + let d = dir("empty"); + let path = d.join("new.pgn"); + std::fs::write(&path, "").unwrap(); + let db = open(&path); + assert_eq!(db.len(), 0); + append(&db, &new_record()).unwrap(); + assert_eq!(open(&path).len(), 1); + } + + #[test] + fn dates_as_typed() { + assert_eq!(pgn_date("").as_deref(), Some("????.??.??")); + assert_eq!(pgn_date("?").as_deref(), Some("????.??.??")); + assert_eq!(pgn_date("2026.10.18").as_deref(), Some("2026.10.18")); + assert_eq!(pgn_date("18.10.2026").as_deref(), Some("2026.10.18")); + assert_eq!(pgn_date("2026-10-18").as_deref(), Some("2026.10.18")); + assert_eq!(pgn_date("2026.10").as_deref(), Some("2026.10.??")); + assert_eq!(pgn_date(" 2026 ").as_deref(), Some("2026.??.??")); + assert_eq!(pgn_date("1.1.2026").as_deref(), Some("2026.01.01")); + assert_eq!(pgn_date("tomorrow"), None); + assert_eq!(pgn_date("2026.13.01"), None); + assert_eq!(pgn_date("12.10"), None); + // PGN's own unknown parts. + assert_eq!(pgn_date("1910.??.??").as_deref(), Some("1910.??.??")); + assert_eq!(pgn_date("1910.05.??").as_deref(), Some("1910.05.??")); + assert_eq!(pgn_date("1910.??.05").as_deref(), Some("1910.??.05")); + } + + #[test] + fn the_same_game_is_found() { + let d = dir("same"); + let path = d.join("base.pgn"); + std::fs::write(&path, format!("{G1}\n{G2}\n")).unwrap(); + let db = open(&path); + let same = parse_str("[White \"C\"]\n[Black \"D\"]\n[Date \"?\"]\n\n1. d4 d5 *\n").game; + assert_eq!(find_same_game(&db, &same), Some(1)); + let other_moves = parse_str("[White \"C\"]\n[Black \"D\"]\n\n1. d4 Nf6 *\n").game; + assert_eq!(find_same_game(&db, &other_moves), None); + let other_player = parse_str("[White \"C\"]\n[Black \"Z\"]\n\n1. d4 d5 *\n").game; + assert_eq!(find_same_game(&db, &other_player), None); + } + + #[test] + fn tag_values_with_quotes_survive() { + let mut g = parse_str("[Event \"?\"]\n\n*\n").game; + g.set_tag("White", "Smith \"Jr\" \\ O'Neil"); + g.set_tag("Event", "Cup"); + let text = g.to_pgn(); + let again = parse_str(&text).game; + assert_eq!(again.tag("White"), Some("Smith \"Jr\" \\ O'Neil")); + } +} diff --git a/crates/chess-core/src/pgn/write.rs b/crates/chess-core/src/pgn/write.rs new file mode 100644 index 0000000..5035c7b --- /dev/null +++ b/crates/chess-core/src/pgn/write.rs @@ -0,0 +1,249 @@ +//! PGN export. +//! +//! Normalization (documented, intentional): LF line endings, movetext wrapped +//! at ~80 columns, whitespace inside comments collapsed, SAN regenerated from +//! the move, NAGs written as `$n`. Tags keep their order and values (including +//! the original FEN text, e.g. fullmove 0). + +use shakmaty::{Color, Position}; + +use crate::game::{Game, NodeId}; + +#[derive(Clone, Debug)] +pub struct WriteOptions { + pub max_line: usize, +} + +impl Default for WriteOptions { + fn default() -> Self { + WriteOptions { max_line: 80 } + } +} + +struct Out { + buf: String, + line_len: usize, + max: usize, + glue_next: bool, +} + +impl Out { + fn token(&mut self, t: &str) { + let len = t.chars().count(); + if self.glue_next { + self.glue_next = false; + } else if self.line_len > 0 { + if self.line_len + 1 + len > self.max { + self.buf.push('\n'); + self.line_len = 0; + } else { + self.buf.push(' '); + self.line_len += 1; + } + } + self.buf.push_str(t); + self.line_len += len; + } + + /// Appended directly to the previous token (`)`). + fn glued(&mut self, t: &str) { + self.buf.push_str(t); + self.line_len += t.chars().count(); + } + + fn open_paren(&mut self) { + self.token("("); + self.glue_next = true; + } + + fn newline(&mut self) { + if self.line_len > 0 { + self.buf.push('\n'); + self.line_len = 0; + } + } + + fn words(&mut self, text: &str) { + for w in text.split_whitespace() { + self.token(w); + } + } + + fn comment(&mut self, text: &str) { + if text.contains('}') { + // Cannot be represented in braces: write as `;` line comments. + for line in text.lines() { + self.token(&format!(";{}", line.trim())); + self.newline(); + } + return; + } + // Lines are reflowed, paragraphs (blank lines) kept: a book's comment keeps its + // shape (comment_display_text shows a blank line as a paragraph break). + let mut paragraphs: Vec> = vec![Vec::new()]; + for line in text.lines() { + if line.trim().is_empty() { + if paragraphs.last().is_some_and(|p| !p.is_empty()) { + paragraphs.push(Vec::new()); + } + } else { + paragraphs + .last_mut() + .expect("one paragraph") + .extend(line.split_whitespace()); + } + } + paragraphs.retain(|p| !p.is_empty()); + let total: usize = paragraphs.iter().map(Vec::len).sum(); + if total == 0 { + self.token("{}"); + return; + } + let mut n = 0; + for (k, words) in paragraphs.iter().enumerate() { + if k > 0 { + // A blank line inside the braces. + self.newline(); + self.buf.push('\n'); + } + for w in words { + n += 1; + let open = if n == 1 { "{" } else { "" }; + let close = if n == total { "}" } else { "" }; + self.token(&format!("{open}{w}{close}")); + } + } + } +} + +fn escape_tag(v: &str) -> String { + let mut s = String::with_capacity(v.len()); + for c in v.chars() { + match c { + '\\' => s.push_str("\\\\"), + '"' => s.push_str("\\\""), + '\n' | '\r' => s.push(' '), + c => s.push(c), + } + } + s +} + +/// Serializes a game to PGN (UTF-8, LF). +pub fn write_game(game: &Game, options: &WriteOptions) -> String { + let mut out = Out { + buf: String::new(), + line_len: 0, + max: options.max_line.max(20), + glue_next: false, + }; + for (k, v) in game.tags() { + out.buf.push_str(&format!("[{k} \"{}\"]\n", escape_tag(v))); + } + if game.tag("FEN").is_none() + && let Some(fen) = game.start().original_fen() + { + if game.tag("SetUp").is_none() { + out.buf.push_str("[SetUp \"1\"]\n"); + } + out.buf + .push_str(&format!("[FEN \"{}\"]\n", escape_tag(fen))); + } + out.buf.push('\n'); + + let root = game.root(); + if let Some(r) = game.node(root) { + for c in r.comments_before() { + out.comment(c); + } + for c in r.comments_after() { + out.comment(c); + } + for n in r.nags() { + out.token(&format!("${}", n.0)); + } + for u in r.unparsed() { + out.words(u); + } + } + write_line(game, root, true, &mut out); + out.token(game.result().as_str()); + out.buf.push('\n'); + out.buf +} + +/// Writes one move: comments before, number, SAN, NAGs, comments after. +/// Returns whether the next black move needs an explicit number. +fn write_move(game: &Game, id: NodeId, force_number: bool, out: &mut Out) -> bool { + let Some(node) = game.node(id) else { + return true; + }; + let mut force = force_number; + for c in node.comments_before() { + out.comment(c); + force = true; + } + let Some(mv) = node.game_move() else { + return true; + }; + if let Some(before) = game.position_before(id) { + let n = before.fullmoves().get(); + match before.turn() { + Color::White => out.token(&format!("{n}.")), + Color::Black if force => out.token(&format!("{n}...")), + Color::Black => {} + } + } + out.token(&mv.san); + for nag in node.nags() { + out.token(&format!("${}", nag.0)); + } + let mut after = false; + for c in node.comments_after() { + out.comment(c); + after = true; + } + after +} + +/// Writes the continuation of `parent` (main child, its alternatives, and so on). +fn write_line(game: &Game, parent: NodeId, force_first: bool, out: &mut Out) { + let mut cur = parent; + let mut force = force_first; + loop { + let children = game.children(cur); + let Some(&main) = children.first() else { + break; + }; + force = write_move(game, main, force, out); + for &alt in &children[1..] { + out.open_paren(); + let f = write_move(game, alt, true, out); + write_unparsed(game, alt, out); + write_line(game, alt, f, out); + out.glued(")"); + force = true; + } + if write_unparsed(game, main, out) { + force = true; + } + cur = main; + } +} + +fn write_unparsed(game: &Game, id: NodeId, out: &mut Out) -> bool { + let Some(node) = game.node(id) else { + return false; + }; + for u in node.unparsed() { + out.words(u); + } + !node.unparsed().is_empty() +} + +impl Game { + /// PGN text with default options. + pub fn to_pgn(&self) -> String { + write_game(self, &WriteOptions::default()) + } +} diff --git a/crates/chess-core/src/repair.rs b/crates/chess-core/src/repair.rs new file mode 100644 index 0000000..77f0831 --- /dev/null +++ b/crates/chess-core/src/repair.rs @@ -0,0 +1,242 @@ +//! Compatibility repair of letters replaced by ASCII sequences in the source. +//! +//! Observed in the Dvoretsky textbook (windows-1251): the letters «ч», «Ч» and +//! «ю» never occur; instead comments contain `~~` (ч), `><` (Ч) and `o^` +//! (ÑŽ, with a Latin `o`). The original bytes are never changed; the repair is +//! applied only to comment text of parsed games, only when detected for the +//! whole source, and can be switched off. + +use crate::encoding::TextEncoding; + +/// Replacement table: (sequence, letter). Longer/specific sequences first. +const TABLE: [(&str, char); 6] = [ + ("><", 'Ч'), + ("~~", 'ч'), + ("O^", 'Ю'), + ("О^", 'Ю'), // Cyrillic О + ("o^", 'ÑŽ'), + ("о^", 'ÑŽ'), // Cyrillic о +]; + +/// Counts of restored letters. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct LetterRepairCounts { + /// `~~` → «ч». + pub ch_lower: usize, + /// `><` → «Ч», plus `~~` at the start of a sentence/comment → «Ч». + pub ch_upper: usize, + /// `o^`/`о^` → «ю». + pub yu_lower: usize, + /// `O^`/`О^` → «Ю». + pub yu_upper: usize, +} + +impl LetterRepairCounts { + pub fn total(&self) -> usize { + self.ch_lower + self.ch_upper + self.yu_lower + self.yu_upper + } + + pub fn add(&mut self, o: &LetterRepairCounts) { + self.ch_lower += o.ch_lower; + self.ch_upper += o.ch_upper; + self.yu_lower += o.yu_lower; + self.yu_upper += o.yu_upper; + } +} + +/// Source-level detection result. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct LetterRepairDetection { + /// Substitution pattern found (see [`detect_letter_substitution`]). + pub detected: bool, + /// Sequences found in the whole source (before repair). + pub sequences: usize, + /// Genuine «ч», «Ч», «ю», «Ю» found in the whole source. + pub genuine_letters: usize, +} + +/// Minimum number of substitution sequences to consider the pattern real. +const MIN_SEQUENCES: usize = 20; + +/// Detects the substitution for a whole source. +/// +/// Rule: the encoding is a legacy Cyrillic code page (windows-1251, KOI8-R, +/// IBM866); at least 20 sequences from the table occur directly next to a +/// Cyrillic letter (e.g. `и~~ÑŒ`, `{><е`, `o^Ñ‚`); genuine «ч/Ч/ÑŽ/Ю» occur less +/// than once per 50 sequences (in the textbook: 0); and at least 90 % of all +/// `~~`/`^` occurrences are such sequences (ASCII art or real tildes elsewhere +/// disable the repair). +pub fn detect_letter_substitution(bytes: &[u8], encoding: TextEncoding) -> LetterRepairDetection { + if !matches!( + encoding, + TextEncoding::Windows1251 | TextEncoding::Koi8R | TextEncoding::Ibm866 + ) { + return LetterRepairDetection::default(); + } + // The source's letters as they come, never all at once: a large file's text is + // twice its size in UTF-8, four times as `char`s (more than a browser's memory). + let chars = || source_chars(bytes, encoding); + let genuine_letters = chars() + .filter(|c| matches!(c, 'ч' | 'Ч' | 'ÑŽ' | 'Ю')) + .count(); + let sequences = sequences(chars()); + let markers = chars().filter(|c| matches!(c, '~' | '^')).count(); + // Each `~~` has two markers, each `x^` one; `><` has none. + let detected = sequences >= MIN_SEQUENCES + && genuine_letters * 50 < sequences + && markers * 9 <= sequence_markers(chars()) * 10; + LetterRepairDetection { + detected, + sequences, + genuine_letters, + } +} + +/// The letters of `bytes` in a single-byte `encoding`, decoded a piece at a time (a +/// byte is a letter: any place splits the text). +fn source_chars(bytes: &[u8], encoding: TextEncoding) -> impl Iterator + '_ { + bytes.chunks(1 << 20).flat_map(move |piece| { + let (text, _) = encoding.decode(piece); + text.chars().collect::>() + }) +} + +/// The sequences of the table next to a Cyrillic letter (a pair taken is not looked at +/// again). +fn sequences(chars: impl Iterator) -> usize { + let is_cyr = + |c: Option| c.is_some_and(|c| matches!(c, 'а'..='Ñ�' | 'Ð�'..='Я' | 'Ñ‘' | 'Ð�')); + let mut chars = chars.peekable(); + let mut n = 0; + let mut before = None; + while let Some(a) = chars.next() { + let Some(&b) = chars.peek() else { break }; + if TABLE.iter().any(|(s, _)| s.chars().eq([a, b])) { + chars.next(); + if is_cyr(before) || is_cyr(chars.peek().copied()) { + n += 1; + } + before = Some(b); + } else { + before = Some(a); + } + } + n +} + +fn sequence_markers(chars: impl Iterator) -> usize { + let mut chars = chars.peekable(); + let mut n = 0; + while let Some(a) = chars.next() { + let Some(&b) = chars.peek() else { break }; + match (a, b) { + ('~', '~') => { + n += 2; + chars.next(); + } + ('o' | 'о' | 'O' | 'О', '^') => { + n += 1; + chars.next(); + } + _ => {} + } + } + n +} + +/// Restores letters in one text. `~~` at the start of the text or of a +/// sentence (after `.`, `!`, `?` and whitespace) becomes «Ч». +pub fn repair_letters(text: &str) -> (String, LetterRepairCounts) { + let mut counts = LetterRepairCounts::default(); + if !text.contains(['~', '^', '<']) { + return (text.to_owned(), counts); + } + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while !rest.is_empty() { + let hit = TABLE.iter().find(|(s, _)| rest.starts_with(s)); + match hit { + Some((seq, letter)) => { + let letter = if *seq == "~~" && at_sentence_start(&out) { + counts.ch_upper += 1; + 'Ч' + } else { + match letter { + 'Ч' => counts.ch_upper += 1, + 'ч' => counts.ch_lower += 1, + 'Ю' => counts.yu_upper += 1, + _ => counts.yu_lower += 1, + } + *letter + }; + out.push(letter); + rest = &rest[seq.len()..]; + } + None => { + let mut it = rest.chars(); + if let Some(c) = it.next() { + out.push(c); + } + rest = it.as_str(); + } + } + } + (out, counts) +} + +fn at_sentence_start(before: &str) -> bool { + let trimmed = before.trim_end(); + if trimmed.is_empty() { + return true; + } + // Require whitespace between the punctuation and the word. + trimmed.len() < before.len() && trimmed.ends_with(['.', '!', '?']) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn repairs_table() { + let (s, c) = repair_letters("><ерные играo^Ñ‚. ~~то делать ~~ерным? Оппозицио^ O^г"); + assert_eq!(s, "Черные играют. Что делать черным? Оппозицию Юг"); + assert_eq!( + c, + LetterRepairCounts { + ch_lower: 1, + ch_upper: 2, + yu_lower: 2, + yu_upper: 1 + } + ); + let (s, _) = repair_letters("о^г, кл\u{43e}^~~евые"); + assert_eq!(s, "юг, ключевые"); + let (s, c) = repair_letters("1. e4 {plain}"); + assert_eq!((s.as_str(), c.total()), ("1. e4 {plain}", 0)); + } + + fn enc1251(s: &str) -> Vec { + encoding_rs::WINDOWS_1251.encode(s).0.into_owned() + } + + #[test] + fn detection() { + let bad = "{Клo^~~евые полÑ�, ><ерные играo^Ñ‚, ~~ерные} ".repeat(10); + let d = detect_letter_substitution(&enc1251(&bad), TextEncoding::Windows1251); + assert!(d.detected, "{d:?}"); + assert_eq!(d.genuine_letters, 0); + // Genuine letters present: no repair. + let mixed = format!("{bad} {}", "ключевые черные ".repeat(5)); + assert!(!detect_letter_substitution(&enc1251(&mixed), TextEncoding::Windows1251).detected); + // UTF-8 or Western sources are never repaired. + assert!(!detect_letter_substitution(bad.as_bytes(), TextEncoding::Utf8).detected); + // Too few sequences. + let few = "{Клo^~~евые}"; + assert!(!detect_letter_substitution(&enc1251(few), TextEncoding::Windows1251).detected); + // Many unrelated tildes (ASCII art) disable the repair. + let art = format!("{bad}{}", "~~~~~~~~ ^^^^ ".repeat(40)); + assert!(!detect_letter_substitution(&enc1251(&art), TextEncoding::Windows1251).detected); + } +} diff --git a/crates/chess-core/src/start.rs b/crates/chess-core/src/start.rs new file mode 100644 index 0000000..67ee814 --- /dev/null +++ b/crates/chess-core/src/start.rs @@ -0,0 +1,159 @@ +//! Tolerant start-position (FEN) handling. + +use shakmaty::{CastlingMode, Chess, EnPassantMode, Position, fen::Fen}; + +/// Deviations from a strict FEN that were tolerated. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FenRepair { + /// Fullmove field was `0`; position uses 1. + FullmoveZero, + InvalidCastlingRightsDropped, + InvalidEnPassantDropped, + /// Side not to move is in check (kept; e.g. composed diagrams). + ImpossibleCheckAccepted, + TooMuchMaterialAccepted, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum FenError { + #[error("FEN syntax error: {0}")] + Syntax(String), + #[error("{0}")] + IllegalPosition(String), +} + +/// The game's initial position. +#[derive(Clone, Debug, Default)] +pub struct StartPosition { + position: Chess, + /// FEN text as given by the source (unchanged), `None` for the standard start. + original_fen: Option, + repairs: Vec, +} + +impl StartPosition { + pub fn standard() -> Self { + Self::default() + } + + /// Parses a FEN tolerantly (see [`FenRepair`]). + pub fn from_fen(fen: &str) -> Result { + let fen_trimmed = fen.trim(); + let mut repairs = Vec::new(); + let fields: Vec<&str> = fen_trimmed.split_whitespace().collect(); + if fields.get(5) == Some(&"0") { + repairs.push(FenRepair::FullmoveZero); + } + let parsed = + Fen::from_ascii(fen_trimmed.as_bytes()).map_err(|e| FenError::Syntax(e.to_string()))?; + let position = match parsed.into_position::(CastlingMode::Standard) { + Ok(p) => p, + Err(err) => { + use shakmaty::PositionErrorKinds as K; + let kinds = err.kinds(); + let mut state = Err(err); + for (kind, repair) in [ + ( + K::INVALID_CASTLING_RIGHTS, + FenRepair::InvalidCastlingRightsDropped, + ), + (K::INVALID_EP_SQUARE, FenRepair::InvalidEnPassantDropped), + (K::IMPOSSIBLE_CHECK, FenRepair::ImpossibleCheckAccepted), + (K::TOO_MUCH_MATERIAL, FenRepair::TooMuchMaterialAccepted), + ] { + let Err(err) = state else { break }; + if !kinds.contains(kind) { + state = Err(err); + continue; + } + state = match repair { + FenRepair::InvalidCastlingRightsDropped => { + err.ignore_invalid_castling_rights() + } + FenRepair::InvalidEnPassantDropped => err.ignore_invalid_ep_square(), + FenRepair::ImpossibleCheckAccepted => err.ignore_impossible_check(), + _ => err.ignore_too_much_material(), + }; + repairs.push(repair); + } + state.map_err(|e| FenError::IllegalPosition(e.to_string()))? + } + }; + let original_fen = if fen_trimmed.is_empty() { + None + } else { + Some(fen_trimmed.to_owned()) + }; + Ok(StartPosition { + position, + original_fen, + repairs, + }) + } + + pub fn from_position(position: Chess) -> Self { + let fen = Fen::from_position(&position, EnPassantMode::Legal).to_string(); + let original_fen = (position != Chess::default()).then_some(fen); + StartPosition { + position, + original_fen, + repairs: Vec::new(), + } + } + + pub fn position(&self) -> &Chess { + &self.position + } + + /// FEN as given by the source/user (`None` = standard initial position). + pub fn original_fen(&self) -> Option<&str> { + self.original_fen.as_deref() + } + + /// Normalized FEN of the playable position (fullmove ≥ 1). + pub fn fen(&self) -> String { + Fen::from_position(&self.position, EnPassantMode::Legal).to_string() + } + + pub fn is_standard(&self) -> bool { + self.position == Chess::default() && self.position.fullmoves().get() == 1 + } + + pub fn repairs(&self) -> &[FenRepair] { + &self.repairs + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fullmove_zero_is_tolerated() { + let s = StartPosition::from_fen("8/3k4/8/3K4/3P4/8/8/8 w - - 0 0").expect("fen"); + assert_eq!(s.repairs(), &[FenRepair::FullmoveZero]); + assert_eq!(s.position().fullmoves().get(), 1); + assert_eq!(s.original_fen(), Some("8/3k4/8/3K4/3P4/8/8/8 w - - 0 0")); + } + + #[test] + fn bad_castling_is_repaired() { + let s = StartPosition::from_fen("4k3/8/8/8/8/8/8/4K3 w KQkq - 0 1").expect("fen"); + assert!( + s.repairs() + .contains(&FenRepair::InvalidCastlingRightsDropped) + ); + } + + #[test] + fn missing_king_is_error() { + assert!(matches!( + StartPosition::from_fen("8/8/8/8/8/8/8/4K3 w - - 0 1"), + Err(FenError::IllegalPosition(_)) + )); + assert!(matches!( + StartPosition::from_fen("garbage"), + Err(FenError::Syntax(_)) + )); + } +} diff --git a/crates/chess-core/tests/corpus.rs b/crates/chess-core/tests/corpus.rs new file mode 100644 index 0000000..3f3e9cc --- /dev/null +++ b/crates/chess-core/tests/corpus.rs @@ -0,0 +1,313 @@ +//! Runs the user's real PGN files from `pgnFilesforExample/` if present +//! (skipped otherwise; the files are not part of the fixtures). +//! Run with `cargo test -p chess-core --test corpus -- --nocapture` for stats. + +use std::collections::BTreeMap; +use std::ops::ControlFlow; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; + +use chess_core::shakmaty::Position; +use chess_core::{DiagnosticCode, Game, GameEntry, PgnDatabase, Severity, TextEncoding, parse_str}; +use pgn_reader::{Reader, SanPlus, Visitor}; + +const RUY: &str = "The Ruy Lopez - Move by Move.pgn"; +const TEXTBOOK: &str = "Дворецкий. Учебник жндшпилÑ�.pgn"; + +fn corpus_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample") +} + +/// Independent oracle: main-line move count per record via pgn-reader. +struct MainlineCounter; + +impl Visitor for MainlineCounter { + type Tags = (); + type Movetext = usize; + type Output = usize; + + fn begin_tags(&mut self) -> ControlFlow { + ControlFlow::Continue(()) + } + fn begin_movetext(&mut self, _tags: ()) -> ControlFlow { + ControlFlow::Continue(0) + } + fn san(&mut self, n: &mut usize, _san: SanPlus) -> ControlFlow { + *n += 1; + ControlFlow::Continue(()) + } + fn end_game(&mut self, n: usize) -> usize { + n + } +} + +#[derive(Default, Debug)] +struct Stats { + games: usize, + nodes: usize, + null_moves: usize, + nags: usize, + comments: usize, + fen_games: usize, + black_to_move: usize, + max_depth: usize, + unparsed_fragments: usize, + diagnostics: BTreeMap, + roundtrip_failures: Vec, + plycount_mismatch: Vec, + oracle_mismatch: Vec, +} + +fn walk_stats(g: &Game, s: &mut Stats) { + for id in g.attached_nodes() { + let Some(n) = g.node(id) else { continue }; + if let Some(m) = n.game_move() { + s.nodes += 1; + if m.is_null() { + s.null_moves += 1; + } + s.max_depth = s.max_depth.max(g.variation_depth(id)); + } + s.nags += n.nags().len(); + s.comments += n.comments_before().len() + n.comments_after().len(); + s.unparsed_fragments += n.unparsed().len(); + } +} + +fn run_file(name: &str) -> Option<(Stats, PgnDatabase)> { + let path = corpus_dir().join(name); + if !path.exists() { + eprintln!("SKIP: {} not found", path.display()); + return None; + } + let before = std::fs::read(&path).expect("read"); + let mtime_before = std::fs::metadata(&path).and_then(|m| m.modified()).ok(); + + let mut reports = 0; + let db = + PgnDatabase::open(&path, &mut |_| reports += 1, &AtomicBool::new(false)).expect("open"); + assert!(reports >= 1); + + // Oracle counts. + let mut reader = Reader::new(before.as_slice()); + let mut oracle = Vec::new(); + while let Ok(Some(n)) = reader.read_game(&mut MainlineCounter) { + oracle.push(n); + } + + let mut s = Stats::default(); + for (i, e) in db.entries().iter().enumerate() { + s.games += 1; + let parsed = db.load_game(i).expect("entry"); + let g = &parsed.game; + for d in &parsed.diagnostics { + *s.diagnostics + .entry(format!("{:?}/{:?}", d.severity, d.code)) + .or_default() += 1; + } + if g.tag("FEN").is_some() { + s.fen_games += 1; + } + if g.position(g.root()).map(|p| p.turn()) == Some(chess_core::shakmaty::Color::Black) { + s.black_to_move += 1; + } + walk_stats(g, &mut s); + + let plies = g.mainline().len(); + if e.ply_count().is_some_and(|pc| pc as usize != plies) { + s.plycount_mismatch.push(i + 1); + } + if oracle.get(i) != Some(&plies) { + s.oracle_mismatch.push(i + 1); + } + + let text = g.to_pgn(); + let back = parse_str(&text); + if back.game.canonical_tree() != g.canonical_tree() + || back.game.tags() != g.tags() + || back.game.to_pgn() != text + { + s.roundtrip_failures.push(i + 1); + } + } + + let after = std::fs::read(&path).expect("read"); + let mtime_after = std::fs::metadata(&path).and_then(|m| m.modified()).ok(); + assert!(before == after, "source file changed"); + assert_eq!(mtime_before, mtime_after, "source mtime changed"); + assert_eq!( + db.entries().len(), + oracle.len(), + "record count differs from pgn-reader" + ); + eprintln!( + "== {name}: encoding {:?} ({:?})", + db.encoding(), + db.detected_encoding().confidence + ); + eprintln!("{s:#?}"); + Some((s, db)) +} + +#[derive(Debug, Default, PartialEq)] +struct LetterStats { + tilde: usize, + angle: usize, + caret: usize, + sequences: usize, + genuine: usize, + upper_ch: usize, + restored_diags: usize, +} + +/// Counts substitution sequences and genuine ч/Ч/ÑŽ/Ю in all comments, +/// with the repair off (`.0`) and on (`.1`). +fn letter_stats(db: &PgnDatabase) -> (LetterStats, LetterStats) { + let mut db = db.clone(); + let mut out = Vec::new(); + for enabled in [false, true] { + db.set_repair_letters(enabled); + let mut st = LetterStats::default(); + for i in 0..db.len() { + let p = db.load_game(i).expect("game"); + st.restored_diags += p + .diagnostics + .iter() + .filter(|d| d.code == DiagnosticCode::LettersRestored) + .count(); + for id in p.game.attached_nodes() { + let Some(n) = p.game.node(id) else { continue }; + for c in n.comments_before().iter().chain(n.comments_after()) { + st.tilde += c.matches("~~").count(); + st.angle += c.matches("><").count(); + st.caret += c.matches("o^").count() + c.matches("о^").count(); + st.upper_ch += c.matches('Ч').count(); + st.genuine += c + .chars() + .filter(|ch| matches!(ch, 'ч' | 'Ч' | 'ÑŽ' | 'Ю')) + .count(); + } + } + } + st.sequences = st.tilde + st.angle + st.caret; + out.push(st); + } + let after = out.pop().unwrap_or_default(); + let before = out.pop().unwrap_or_default(); + (before, after) +} + +fn entry_tag<'a>(e: &'a GameEntry, t: &str) -> &'a str { + e.tag(t).unwrap_or("") +} + +#[test] +fn real_corpus() { + let ruy = run_file(RUY); + let book = run_file(TEXTBOOK); + + if let Some((s, db)) = &ruy { + assert_eq!(db.encoding(), TextEncoding::Windows1252); + assert!(!db.letter_repair().detected); + assert!(!db.repair_letters_enabled()); + assert_eq!(s.games, 49); + assert!( + db.entries() + .iter() + .any(|e| entry_tag(e, "White") == "Hübner, R.") + ); + assert!( + s.roundtrip_failures.is_empty(), + "{:?}", + s.roundtrip_failures + ); + assert!(s.plycount_mismatch.is_empty(), "{:?}", s.plycount_mismatch); + assert!(s.oracle_mismatch.is_empty(), "{:?}", s.oracle_mismatch); + assert!(!s.diagnostics.keys().any(|k| k.starts_with("Error"))); + // Figures from the independent audit (docs/research/requirements-and-pgn.md). + assert_eq!( + (s.nodes, s.null_moves, s.nags, s.comments), + (8340, 23, 835, 3040) + ); + assert_eq!((s.fen_games, s.max_depth), (1, 4)); + assert!(s.diagnostics.is_empty(), "{:?}", s.diagnostics); + } + if let Some((s, db)) = &book { + // 9192 comment blocks + 1 fragment recovered from record â„–335. + assert_eq!( + (s.nodes, s.null_moves, s.nags, s.comments), + (53923, 246, 12705, 9193) + ); + assert_eq!((s.fen_games, s.black_to_move), (845, 268)); + assert_eq!(s.diagnostics.get("Info/FenFullmoveZero"), Some(&72)); + assert_eq!(db.encoding(), TextEncoding::Windows1251); + assert_eq!(s.games, 847); + assert!( + s.roundtrip_failures.is_empty(), + "{:?}", + s.roundtrip_failures + ); + assert!(s.plycount_mismatch.is_empty(), "{:?}", s.plycount_mismatch); + assert!(s.oracle_mismatch.is_empty(), "{:?}", s.oracle_mismatch); + assert!(!s.diagnostics.keys().any(|k| k.starts_with("Error"))); + assert_eq!(s.max_depth, 7); + + // Record â„–335: a comment closed early; the text must not vanish silently. + let parsed = db.load_game(334).expect("335"); + assert_eq!(db.entries()[334].white(), Some("Averbakh, Yuri L")); + let codes: Vec<_> = parsed.diagnostics.iter().map(|d| d.code).collect(); + assert!( + codes.contains(&DiagnosticCode::UnrecognizedText), + "{codes:?}" + ); + assert!( + codes.contains(&DiagnosticCode::StrayClosingBrace), + "{codes:?}" + ); + let d = parsed + .diagnostics + .iter() + .find(|d| d.code == DiagnosticCode::UnrecognizedText) + .expect("diag"); + assert_eq!(d.severity, Severity::Warning); + assert_eq!(d.location.map(|l| l.line), Some(8264)); + let all_comments: String = parsed + .game + .attached_nodes() + .iter() + .filter_map(|id| parsed.game.node(*id)) + .flat_map(|n| n.comments_after().iter().chain(n.comments_before())) + .cloned() + .collect::>() + .join(" "); + assert!(all_comments.contains("то иÑ�ход"), "{all_comments}"); + assert!(all_comments.contains("вытеÑ�нению."), "{all_comments}"); + assert!(all_comments.contains("При короле на a1")); + // Letter repair (~~ → ч, >< → Ч, o^ → ÑŽ). + assert!(db.letter_repair().detected, "{:?}", db.letter_repair()); + let (before, after) = letter_stats(db); + eprintln!("letter repair: before {before:?}\nafter {after:?}"); + assert_eq!(before.genuine, 0); + assert_eq!(after.sequences, 0, "sequences left in comments"); + assert_eq!(after.genuine, before.sequences); + assert_eq!( + (before.tilde, before.angle, before.caret), + (5702, 339, 2974) + ); + eprintln!("#335 diagnostics:"); + for d in &parsed.diagnostics { + eprintln!(" {d}"); + } + } + if let (Some((a, _)), Some((b, _))) = (&ruy, &book) { + assert_eq!(a.games + b.games, 896); + eprintln!( + "TOTAL: games {}, move nodes {}, null moves {}, NAG {}, FEN {}", + a.games + b.games, + a.nodes + b.nodes, + a.null_moves + b.null_moves, + a.nags + b.nags, + a.fen_games + b.fen_games + ); + } +} diff --git a/crates/chess-core/tests/pgn_fixtures.rs b/crates/chess-core/tests/pgn_fixtures.rs new file mode 100644 index 0000000..f7090c6 --- /dev/null +++ b/crates/chess-core/tests/pgn_fixtures.rs @@ -0,0 +1,441 @@ +//! Synthetic PGN fixtures (written for this project, not taken from books). + +use chess_core::shakmaty::{Color, Move, Position, Role, Square}; +use chess_core::{ + DiagnosticCode, Game, GameResult, HistoryKind, MoveKind, Nag, NodeId, ParsedGame, Severity, + TextEncoding, parse_game, parse_str, +}; + +fn parse_ok(pgn: &str) -> ParsedGame { + let p = parse_str(pgn); + for d in &p.diagnostics { + eprintln!("{d}"); + } + p +} + +fn sans(g: &Game, ids: &[NodeId]) -> Vec { + ids.iter() + .filter_map(|id| g.game_move(*id).map(|m| m.san.clone())) + .collect() +} + +fn child_sans(g: &Game, id: NodeId) -> Vec { + sans(g, g.children(id)) +} + +fn has(p: &ParsedGame, code: DiagnosticCode) -> bool { + p.diagnostics.iter().any(|d| d.code == code) +} + +/// import → export → import gives the same tree, tags and start; export is idempotent. +fn assert_roundtrip(p: &ParsedGame) -> String { + let first = p.game.to_pgn(); + let again = parse_str(&first); + assert_eq!( + p.game.canonical_tree(), + again.game.canonical_tree(), + "tree changed on roundtrip:\n{first}" + ); + assert_eq!(p.game.tags(), again.game.tags()); + assert_eq!(p.game.start().fen(), again.game.start().fen()); + assert_eq!(p.game.result(), again.game.result()); + assert_eq!(first, again.game.to_pgn(), "export not idempotent"); + first +} + +const NESTED: &str = r#"[Event "Synthetic nested"] +[Site "?"] +[Date "2026.10.17"] +[Round "1"] +[White "ТеÑ�тов, Ð�."] +[Black "Test, B."] +[Result "1-0"] +[Annotator "fixture"] +[MyCustomTag "with \"quotes\" and \\ backslash"] + +{Start comment} 1. e4 $1 {after e4} e5 (1... c5 {Sicilian} 2. Nf3 (2. Nc3 Nc6 +(2... d6 3. f4 $5) 3. f4) 2... d6) ({Before French} 1... e6 $2 2. d4 d5) 2. Nf3 +Nc6 3. Bb5 a6 $6 4. Ba4 Nf6 5. O-O Be7 $14 1-0 +"#; + +#[test] +fn nested_variations_comments_and_tags() { + let p = parse_ok(NESTED); + assert!( + p.max_severity() <= Some(Severity::Info), + "{:?}", + p.diagnostics + ); + let g = &p.game; + assert_eq!( + g.tag("MyCustomTag"), + Some("with \"quotes\" and \\ backslash") + ); + assert_eq!(g.tag("White"), Some("ТеÑ�тов, Ð�.")); + assert_eq!(g.tags()[7].0, "Annotator"); + assert_eq!(g.result(), GameResult::WhiteWins); + + let root = g.node(g.root()).expect("root"); + assert_eq!(root.comments_after(), &["Start comment".to_owned()]); + + let main = g.mainline(); + assert_eq!( + sans(g, &main), + [ + "e4", "e5", "Nf3", "Nc6", "Bb5", "a6", "Ba4", "Nf6", "O-O", "Be7" + ] + ); + let e4 = main[0]; + assert_eq!(g.node(e4).expect("e4").nags(), &[Nag(1)]); + assert_eq!( + g.node(e4).expect("e4").comments_after(), + &["after e4".to_owned()] + ); + assert_eq!(child_sans(g, e4), ["e5", "c5", "e6"]); + + let c5 = g.children(e4)[1]; + let e6 = g.children(e4)[2]; + assert_eq!( + g.node(c5).expect("c5").comments_after(), + &["Sicilian".to_owned()] + ); + assert_eq!( + g.node(e6).expect("e6").comments_before(), + &["Before French".to_owned()] + ); + assert_eq!(g.node(e6).expect("e6").nags(), &[Nag(2)]); + assert_eq!(child_sans(g, c5), ["Nf3", "Nc3"]); + let nc3 = g.children(c5)[1]; + assert_eq!(child_sans(g, nc3), ["Nc6", "d6"]); + let d6 = g.children(nc3)[1]; + assert_eq!(g.variation_depth(d6), 3); + let f4 = g.main_child(d6).expect("f4"); + assert_eq!(g.node(f4).expect("f4").nags(), &[Nag(5)]); + assert_eq!(g.move_label(f4).as_deref(), Some("3. f4")); + assert_eq!(g.move_label(d6).as_deref(), Some("2... d6")); + assert_eq!(g.variation_start(f4), Some(d6)); + assert!(!g.is_mainline(f4)); + assert_eq!(g.path(f4), vec![g.root(), e4, c5, nc3, d6, f4]); + assert_eq!(g.next_sibling(c5), Some(e6)); + assert_eq!(g.prev_sibling(c5), Some(main[1])); + + let castle = main[8]; + assert!(matches!( + g.game_move(castle).map(|m| m.kind), + Some(MoveKind::Normal(Move::Castle { .. })) + )); + let h = g.engine_history(castle).expect("history"); + assert_eq!(h.kind, HistoryKind::Complete); + assert_eq!(h.start_fen, None); + assert_eq!(h.moves.last().map(String::as_str), Some("e1g1")); + assert_eq!(h.moves.len(), 9); + + let out = assert_roundtrip(&p); + assert!(out.contains("[MyCustomTag \"with \\\"quotes\\\" and \\\\ backslash\"]")); + assert!(out.lines().all(|l| l.chars().count() <= 80), "{out}"); +} + +#[test] +fn fen_black_to_move_fullmove_zero() { + let pgn = "[Event \"?\"]\n[SetUp \"1\"]\n[FEN \"8/8/8/4k3/8/8/4P3/4K3 b - - 0 0\"]\n\n1... Kd5 2. e4+ Kxe4 *\n"; + let p = parse_ok(pgn); + assert!(has(&p, DiagnosticCode::FenFullmoveZero)); + assert!(p.max_severity() <= Some(Severity::Info)); + let g = &p.game; + assert_eq!(g.position(g.root()).expect("root").turn(), Color::Black); + let main = g.mainline(); + assert_eq!(sans(g, &main), ["Kd5", "e4+", "Kxe4"]); + assert_eq!(g.move_number(main[0]), Some((1, Color::Black))); + assert_eq!(g.move_label(main[1]).as_deref(), Some("2. e4+")); + let h = g.engine_history(main[2]).expect("h"); + assert_eq!( + h.start_fen.as_deref(), + Some("8/8/8/4k3/8/8/4P3/4K3 b - - 0 1") + ); + assert_eq!(h.moves, ["e5d5", "e2e4", "d5e4"]); + let out = assert_roundtrip(&p); + assert!(out.contains("[FEN \"8/8/8/4k3/8/8/4P3/4K3 b - - 0 0\"]")); + assert!(out.contains("1... Kd5 2. e4+ Kxe4 *"), "{out}"); +} + +#[test] +fn en_passant_and_promotions() { + let pgn = "[FEN \"4k3/8/8/3pP3/8/8/1p6/4K3 w - d6 0 1\"]\n[SetUp \"1\"]\n\n1. exd6 b1=N (1... b1=Q+ 2. Kd2) 2. d7+ Kxd7 *\n"; + let p = parse_ok(pgn); + let g = &p.game; + let main = g.mainline(); + assert_eq!(sans(g, &main), ["exd6", "b1=N", "d7+", "Kxd7"]); + assert!(matches!( + g.game_move(main[0]).map(|m| m.kind), + Some(MoveKind::Normal(Move::EnPassant { .. })) + )); + assert!(matches!( + g.game_move(main[1]).map(|m| m.kind), + Some(MoveKind::Normal(Move::Normal { + promotion: Some(Role::Knight), + .. + })) + )); + let q = g.children(main[0])[1]; + assert_eq!(g.game_move(q).map(|m| m.san.as_str()), Some("b1=Q+")); + assert_eq!(g.engine_history(q).expect("h").moves, ["e5d6", "b2b1q"]); + assert_roundtrip(&p); +} + +#[test] +fn teaching_null_moves() { + let pgn = "[SetUp \"1\"]\n[FEN \"4k3/8/4K3/4P3/8/8/8/8 w - - 0 1\"]\n\n{[%csl Rd7,Rf7]} 1. -- Kd8 (1... Kf8 2. Kd7) (1... -- 2. Kf6) 2. Kf7 *\n"; + let p = parse_ok(pgn); + assert!(p.max_severity() <= Some(Severity::Info)); + let g = &p.game; + let main = g.mainline(); + assert_eq!(sans(g, &main), ["--", "Kd8", "Kf7"]); + assert!(g.game_move(main[0]).expect("null").is_null()); + assert_eq!(g.position(main[0]).expect("p").turn(), Color::Black); + let h = g.engine_history(main[2]).expect("h"); + assert_eq!(h.kind, HistoryKind::AfterNullMove { null_moves: 1 }); + assert_eq!(h.start_fen, g.fen(main[0])); + assert_eq!(h.moves, ["e8d8", "e6f7"]); + assert_eq!(h.current_fen, g.fen(main[2]).expect("fen")); + let black_null = g.children(main[0])[2]; + assert!(g.game_move(black_null).expect("null").is_null()); + let kf6 = g.main_child(black_null).expect("Kf6"); + assert_eq!(g.move_number(kf6), Some((2, Color::White))); + let h = g.engine_history(kf6).expect("h"); + assert_eq!(h.kind, HistoryKind::AfterNullMove { null_moves: 2 }); + assert_eq!(h.moves, ["e6f6"]); + assert!( + h.start_fen + .as_deref() + .is_some_and(|f| f.ends_with(" w - - 2 2")) + ); + let out = assert_roundtrip(&p); + assert!( + out.contains("1. -- Kd8 (1... Kf8 2. Kd7) (1... -- 2. Kf6) 2. Kf7 *"), + "{out}" + ); +} + +#[test] +fn null_move_in_check_is_not_played() { + let pgn = "[SetUp \"1\"]\n[FEN \"4k3/8/8/8/8/8/8/r3K3 w - - 0 1\"]\n\n1. -- Ra2 *\n"; + let p = parse_ok(pgn); + assert!(has(&p, DiagnosticCode::IllegalMove)); + let root = p.game.node(p.game.root()).expect("root"); + assert_eq!(root.unparsed(), &["-- Ra2".to_owned()]); + assert_eq!(p.game.result(), GameResult::Unknown); + let out = assert_roundtrip(&p); + assert!(out.contains("-- Ra2 *")); +} + +#[test] +fn illegal_move_keeps_rest_of_branch() { + let pgn = + "[Result \"1-0\"]\n\n1. e4 (1. d4 Ke5 2. c4 (2. Nf3)) e5 2. Ke3 Nc6 (2... d6) 3. d4 1-0\n"; + let p = parse_ok(pgn); + let errors: Vec<_> = p + .diagnostics + .iter() + .filter(|d| d.code == DiagnosticCode::IllegalMove) + .collect(); + assert_eq!(errors.len(), 2); + assert_eq!(errors[0].location.map(|l| l.line), Some(3)); + let g = &p.game; + let main = g.mainline(); + assert_eq!(sans(g, &main), ["e4", "e5"]); + let d4 = g.children(g.root())[1]; + assert_eq!( + g.node(d4).expect("d4").unparsed(), + &["Ke5 2. c4 (2. Nf3)".to_owned()] + ); + assert_eq!( + g.node(main[1]).expect("e5").unparsed(), + &["Ke3 Nc6 (2... d6) 3. d4".to_owned()] + ); + assert_eq!(g.result(), GameResult::WhiteWins); + let out = assert_roundtrip(&p); + assert!(out.contains("Ke3 Nc6 (2... d6) 3. d4 1-0"), "{out}"); +} + +#[test] +fn early_closed_comment_text_is_not_lost() { + // Shape of a real defect: '}' closes the comment early, text continues + // outside braces, then a stray '}'. + let pgn = "[Event \"?\"]\n\n{ЕÑ�ли Ñ�лон не Ñ�правлÑ�етÑ�Ñ� (а так бывает чаще вÑ�его}, то иÑ�ход\nборьбы завиÑ�ит от королÑ�.} {При короле на a1} 1. e4 *\n"; + let p = parse_ok(pgn); + assert!(has(&p, DiagnosticCode::UnrecognizedText)); + assert!(has(&p, DiagnosticCode::StrayClosingBrace)); + let root = p.game.node(p.game.root()).expect("root"); + assert_eq!( + root.comments_after(), + &[ + "ЕÑ�ли Ñ�лон не Ñ�правлÑ�етÑ�Ñ� (а так бывает чаще вÑ�его".to_owned(), + ", то иÑ�ход борьбы завиÑ�ит от королÑ�.".to_owned(), + "При короле на a1".to_owned(), + ] + ); + let d = p + .diagnostics + .iter() + .find(|d| d.code == DiagnosticCode::UnrecognizedText) + .expect("diag"); + assert_eq!(d.location.map(|l| l.line), Some(3)); + assert_eq!(d.node, Some(p.game.root())); + assert_roundtrip(&p); +} + +#[test] +fn symbolic_annotations_and_legacy_syntax() { + let pgn = "[SetUp \"1\"]\n[FEN \"r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1\"]\n\n1.0-0! 0-0-0?! ; line comment\n%escaped line\n2.Rf7 +- $146 *"; + let p = parse_ok(pgn); + let g = &p.game; + let main = g.mainline(); + assert_eq!(sans(g, &main), ["O-O", "O-O-O", "Rf7"]); + assert_eq!(g.node(main[0]).expect("n").nags(), &[Nag(1)]); + assert_eq!(g.node(main[1]).expect("n").nags(), &[Nag(6)]); + assert_eq!( + g.node(main[1]).expect("n").comments_after(), + &["line comment".to_owned()] + ); + assert_eq!(g.node(main[2]).expect("n").nags(), &[Nag(18), Nag(146)]); + assert!(has(&p, DiagnosticCode::EscapeLine)); + assert_eq!( + g.engine_history(main[1]).expect("h").moves, + ["e1g1", "e8c8"] + ); + assert_roundtrip(&p); +} + +#[test] +fn truncated_and_garbage_inputs_do_not_panic() { + let cases: &[&[u8]] = &[ + b"", + b"[Event \"x\"", + b"[Event \"x\"]\n\n1. e4 {never closed", + b"[Event \"x\"]\n\n1. e4 (1. d4 d5 (1... Nf6", + b"1. e4 ) ) e5 *", + b"( 1. e4 ) 1. d4 *", + b"1. e4 () e5 *", + b"[FEN \"8/8/8/8/8/8/8/8 w - - 0 1\"]\n\n1. e4 *", + b"[FEN \"not a fen\"]\n\n1. e4 {c} *", + b"\xff\xfe\x00garbage {\xc3\x28} 1. e4 $999 $ e5 ***", + b"1. e4 1-0 0-1", + b"1. e4 e5 2. Qh5 Nc6 3. Bc4 Nf6 4. Qxf7# 1-0 {after}", + b"[White \"\xe0\xe1\"]\n\n1. e8=Q *", + ]; + for c in cases { + for enc in [TextEncoding::Utf8, TextEncoding::Windows1251] { + let p = parse_game(c, enc); + let _ = p.game.to_pgn(); + assert_roundtrip(&parse_str(&p.game.to_pgn())); + } + } + let p = parse_game(b"[Event \"x\"]\n\n1. e4 {never closed", TextEncoding::Utf8); + assert!(has(&p, DiagnosticCode::UnterminatedComment)); + assert_eq!( + p.game + .node(p.game.mainline()[0]) + .expect("e4") + .comments_after(), + &["never closed".to_owned()] + ); + let p = parse_game(b"1. e4 (1. d4 d5 (1... Nf6", TextEncoding::Utf8); + assert!(has(&p, DiagnosticCode::UnclosedVariation)); + assert_eq!(p.game.children(p.game.root()).len(), 2); + let p = parse_game(b"[FEN \"not a fen\"]\n\n1. e4 {c} *", TextEncoding::Utf8); + assert!(has(&p, DiagnosticCode::InvalidFen)); + assert_eq!( + p.game.node(p.game.root()).expect("root").unparsed(), + &["1. e4 {c}".to_owned()] + ); + assert!(p.game.to_pgn().contains("[FEN \"not a fen\"]")); + let p = parse_game(b"( 1. e4 ) 1. d4 *", TextEncoding::Utf8); + assert!(has(&p, DiagnosticCode::VariationWithoutMove)); + assert_eq!(p.game.mainline().len(), 1); +} + +#[test] +fn tags_only_record() { + let p = parse_ok( + "[Event \"Diagram\"]\n[SetUp \"1\"]\n[FEN \"8/8/8/8/8/8/k7/2K5 w - - 0 1\"]\n\n{ПозициÑ� без ходов} *\n", + ); + assert!(p.game.mainline().is_empty()); + assert_eq!( + p.game.node(p.game.root()).expect("r").comments_after(), + &["ПозициÑ� без ходов".to_owned()] + ); + assert_roundtrip(&p); +} + +#[test] +fn edited_game_exports_and_reimports() { + let mut g = Game::new(); + let root = g.root(); + let last = g + .add_uci_line(root, &["e2e4", "e7e5", "g1f3", "b8c6"]) + .expect("line"); + let e4 = g.main_child(root).expect("e4"); + let pv_end = g.add_uci_line(e4, &["c7c5", "g1f3", "d7d6"]).expect("pv"); + assert_eq!(g.variation_depth(pv_end), 1); + let ep_pos = g.position(last).expect("pos").clone(); + let m = Move::Normal { + role: Role::Bishop, + from: Square::F1, + capture: None, + to: Square::B5, + promotion: None, + }; + assert!(ep_pos.is_legal(m)); + g.add_move(last, m).expect("Bb5"); + g.set_result(GameResult::Draw); + let text = g.to_pgn(); + assert!( + text.contains("1. e4 e5 (1... c5 2. Nf3 d6) 2. Nf3 Nc6 3. Bb5 1/2-1/2"), + "{text}" + ); + let back = parse_str(&text); + assert!( + back.max_severity() <= Some(Severity::Info), + "{:?}", + back.diagnostics + ); + assert_eq!(back.game.canonical_tree(), g.canonical_tree()); + assert_eq!(back.game.result(), GameResult::Draw); + + let from_fen = Game::from_start( + chess_core::StartPosition::from_fen("4k3/8/8/8/8/8/4P3/4K3 b - - 3 40").expect("fen"), + ); + let text = from_fen.to_pgn(); + assert!( + text.contains("[SetUp \"1\"]") + && text.contains("[FEN \"4k3/8/8/8/8/8/4P3/4K3 b - - 3 40\"]") + ); +} + +#[test] +fn utf8_bom_and_crlf() { + let pgn = "\u{feff}[Event \"Ü\"]\r\n\r\n{Комментарий\r\nв две Ñ�троки} 1. d4 *\r\n"; + let p = parse_game(pgn.as_bytes(), TextEncoding::Utf8); + assert_eq!(p.game.tag("Event"), Some("Ü")); + assert_eq!( + p.game.node(p.game.root()).expect("r").comments_after(), + &["Комментарий\nв две Ñ�троки".to_owned()] + ); +} + +#[test] +fn comment_paragraphs_survive_writing() { + // A book comment with paragraphs: lines are reflowed, blank lines kept. + let p = parse_ok( + "[Event \"?\"]\n\n1. e4 {First paragraph\nstill the first.\n\nSecond paragraph.\n\n\nThird.} e5 *\n", + ); + let out = assert_roundtrip(&p); + let again = parse_ok(&out); + let e4 = again.game.mainline()[0]; + let text = chess_core::comment_display_text(again.game.node(e4).unwrap().comments_after()); + assert_eq!( + text, + "First paragraph still the first.\n\nSecond paragraph.\n\nThird." + ); +} diff --git a/crates/chess-import/Cargo.toml b/crates/chess-import/Cargo.toml new file mode 100644 index 0000000..9be31a6 --- /dev/null +++ b/crates/chess-import/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "chess-import" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Opens chess databases other than plain PGN: ChessBase (.cbh, .cbv) and zip/7z archives" + +[dependencies] +chess-core.workspace = true +shakmaty.workspace = true +encoding_rs.workspace = true +thiserror.workspace = true +zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs", "deflate64", "bzip2"] } +sysinfo = { version = "0.39.6", default-features = false, features = ["system"] } +sevenz-rust2 = { version = "0.24.1", default-features = false, features = ["bzip2", "ppmd", "deflate"] } diff --git a/crates/chess-import/examples/convert.rs b/crates/chess-import/examples/convert.rs new file mode 100644 index 0000000..5e676c5 --- /dev/null +++ b/crates/chess-import/examples/convert.rs @@ -0,0 +1,32 @@ +//! Converts a database to PGN on stdout; notes go to stderr. +//! +//! cargo run -p chess-import --example convert -- "Some Book.cbv" > book.pgn + +use std::io::Write; +use std::sync::atomic::AtomicBool; + +fn main() { + let Some(path) = std::env::args_os().nth(1) else { + eprintln!("usage: convert "); + std::process::exit(2); + }; + let never = AtomicBool::new(false); + match chess_import::open(std::path::Path::new(&path), &mut |_| {}, &never) { + Ok(o) => { + eprintln!("{}: {} games", o.format.label(), o.db.len()); + for n in &o.notes { + eprintln!("note: {n}"); + } + let mut out = std::io::stdout().lock(); + for i in 0..o.db.len() { + if let Some(text) = o.db.raw_text(i) { + let _ = writeln!(out, "{}\n", text.trim_end()); + } + } + } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } + } +} diff --git a/crates/chess-import/examples/position_search.rs b/crates/chess-import/examples/position_search.rs new file mode 100644 index 0000000..9808010 --- /dev/null +++ b/crates/chess-import/examples/position_search.rs @@ -0,0 +1,116 @@ +//! Measures the position search of a PGN database: building the table and queries. +//! +//! cargo run --release -p chess-import --example position_search -- "Book.pgn" [copies] +//! +//! `copies` > 1 joins that many copies of the database's games (a synthetic large +//! database). + +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::time::Instant; + +use chess_core::PgnDatabase; +use chess_import::pgn_positions::PositionTable; +use chess_import::position::PositionQuery; +use shakmaty::san::San; +use shakmaty::{Chess, Position}; + +fn rss_mb() -> f64 { + std::fs::read_to_string("/proc/self/statm") + .ok() + .and_then(|s| s.split_whitespace().nth(1)?.parse::().ok()) + .map_or(0.0, |pages| pages * 4096.0 / 1e6) +} + +/// Peak resident memory of the process. +fn peak_mb() -> f64 { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|s| { + let l = s.lines().find(|l| l.starts_with("VmHWM:"))?; + l.split_whitespace().nth(1)?.parse::().ok() + }) + .map_or(0.0, |kb| kb * 1024.0 / 1e6) +} + +fn line(moves: &str) -> PositionQuery { + let mut pos = Chess::default(); + let mut line = Vec::new(); + for s in moves.split_whitespace() { + let m = s.parse::().unwrap().to_move(&pos).unwrap(); + line.push(m); + pos.play_unchecked(m); + } + PositionQuery::new(pos, Some(line)) +} + +fn main() { + let mut args = std::env::args().skip(1); + let Some(path) = args.next() else { + eprintln!("usage: position_search [copies]"); + std::process::exit(2); + }; + let copies: usize = args.next().and_then(|s| s.parse().ok()).unwrap_or(1); + let never = AtomicBool::new(false); + let opened = + chess_import::open(std::path::Path::new(&path), &mut |_| {}, &never).expect("opens"); + let mut text = String::new(); + for i in 0..opened.db.len() { + if let Some(t) = opened.db.raw_text(i) { + text.push_str(t.trim_end()); + text.push_str("\n\n"); + } + } + let one = text.clone(); + for _ in 1..copies { + text.push_str(&one); + } + drop(opened); + let db = PgnDatabase::from_bytes(text.into_bytes(), None, &mut |_| {}, &never).unwrap(); + let before = rss_mb(); + let peak_before = peak_mb(); + let t0 = Instant::now(); + let table = PositionTable::build(&db, &AtomicUsize::new(0), &never).unwrap(); + println!( + "{} games, {} positions; build {:.2?}; table {:.1} MB (RSS +{:.1} MB, peak +{:.1} MB)", + table.games(), + table.positions(), + t0.elapsed(), + table.memory() as f64 / 1e6, + rss_mb() - before, + peak_mb() - peak_before, + ); + let queries = [ + "", + "e4", + "d4 Nf6 c4 g6", + "e4 e5 Nf3 Nc6 Bb5 a6 Ba4 Nf6 O-O Be7", + "e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6", + ]; + for q in queries { + let q = line(q); + let t0 = Instant::now(); + let runs = 20; + let mut out = None; + for _ in 0..runs { + out = table.search(&db, None, &q, &never); + } + let out = out.unwrap(); + println!( + "{:>4} matches, {:>2} moves: {:.2?} [{}]", + out.matches.len(), + out.moves.len(), + t0.elapsed() / runs, + q.line.as_ref().map_or(0, |l| l.len()), + ); + } + // Candidates: every other game. + let half: Vec = (0..db.len() as u32).step_by(2).collect(); + let q = line("e4"); + let t0 = Instant::now(); + let out = table.search(&db, Some(&half), &q, &never).unwrap(); + println!( + "1.e4 among half the games: {} matches, {:.2?}", + out.matches.len(), + t0.elapsed() + ); +} diff --git a/crates/chess-import/src/archive.rs b/crates/chess-import/src/archive.rs new file mode 100644 index 0000000..c530b4b --- /dev/null +++ b/crates/chess-import/src/archive.rs @@ -0,0 +1,105 @@ +//! `.zip` and `.7z` archives, read into memory. + +use std::io::{Cursor, Read}; + +use crate::ImportError; + +/// A file of an archive (directories are left out). +pub struct Entry { + /// Path inside the archive with `/` separators. + pub name: String, + pub data: Vec, +} + +/// Total size an archive may unpack to: protection against archive bombs. +const MAX_TOTAL: u64 = 2 << 30; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Zip, + SevenZip, +} + +pub fn sniff(bytes: &[u8]) -> Option { + if bytes.starts_with(b"PK\x03\x04") || bytes.starts_with(b"PK\x05\x06") { + Some(Kind::Zip) + } else if bytes.starts_with(&[0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c]) { + Some(Kind::SevenZip) + } else { + None + } +} + +/// Reads the members whose name `wanted` accepts (by lower-case name). +pub fn read( + bytes: &[u8], + kind: Kind, + wanted: &dyn Fn(&str) -> bool, +) -> Result, ImportError> { + match kind { + Kind::Zip => read_zip(bytes, wanted), + Kind::SevenZip => read_7z(bytes, wanted), + } +} + +fn too_large() -> ImportError { + ImportError::Corrupt("the archive unpacks to more than 2 GB".into()) +} + +fn read_zip(bytes: &[u8], wanted: &dyn Fn(&str) -> bool) -> Result, ImportError> { + let bad = |e: zip::result::ZipError| ImportError::Corrupt(format!("zip archive: {e}")); + let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(bad)?; + let mut out = Vec::new(); + let mut total = 0u64; + for i in 0..zip.len() { + let mut f = zip.by_index(i).map_err(bad)?; + let name = f.name().map_err(bad)?.replace('\\', "/"); + if f.is_dir() || !wanted(&name.to_lowercase()) { + continue; + } + if f.encrypted() { + return Err(ImportError::Unsupported(crate::Unsupported::Encrypted)); + } + total += f.size(); + if total > MAX_TOTAL { + return Err(too_large()); + } + let mut data = Vec::with_capacity(f.size().min(MAX_TOTAL) as usize); + f.by_ref() + .take(MAX_TOTAL) + .read_to_end(&mut data) + .map_err(|e| ImportError::Corrupt(format!("zip archive, {name}: {e}")))?; + out.push(Entry { name, data }); + } + Ok(out) +} + +fn read_7z(bytes: &[u8], wanted: &dyn Fn(&str) -> bool) -> Result, ImportError> { + let bad = |e: sevenz_rust2::Error| match e { + sevenz_rust2::Error::PasswordRequired => { + ImportError::Unsupported(crate::Unsupported::Encrypted) + } + e => ImportError::Corrupt(format!("7z archive: {e}")), + }; + let mut reader = + sevenz_rust2::ArchiveReader::new(Cursor::new(bytes), sevenz_rust2::Password::empty()) + .map_err(bad)?; + let declared: u64 = reader.archive().files.iter().map(|f| f.size()).sum(); + if declared > MAX_TOTAL { + return Err(too_large()); + } + let mut out = Vec::new(); + reader + .for_each_entries(|entry, r| { + let name = entry.name().replace('\\', "/"); + // Solid archives decode in order: entries that are not wanted are still read. + let mut data = Vec::new(); + r.take(MAX_TOTAL).read_to_end(&mut data)?; + if !entry.is_directory() && wanted(&name.to_lowercase()) { + out.push(Entry { name, data }); + } + Ok(true) + }) + .map_err(bad)?; + Ok(out) +} diff --git a/crates/chess-import/src/bench.rs b/crates/chess-import/src/bench.rs new file mode 100644 index 0000000..a9071ed --- /dev/null +++ b/crates/chess-import/src/bench.rs @@ -0,0 +1,246 @@ +//! `chesspenguin --bench [report.txt]`: timings of opening, filtering and +//! position search in one database, to compare machines (laptops in particular) with +//! the numbers in `docs/dev/import.md`. Every search runs twice, so the first run +//! shows the cost of a cold file cache and the second the warm one. Nothing of the +//! database is written; a large ChessBase base without a usable `.cbb` gets our own +//! booster built in `booster_dir` (timed), as the application would do. + +use std::io::{self, Write}; +use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::time::Instant; + +use shakmaty::san::SanPlus; +use shakmaty::{Chess, Move, Position}; + +use crate::chessbase::base::{Filter, NameFilter, OpeningsStatus, SortKey}; +use crate::position::PositionQuery; +use crate::{Database, ScanProgress}; + +/// (name, moves from the start position). +const LINES: [(&str, &str); 5] = [ + ("start", ""), + ("1.e4", "e4"), + ("Najdorf, ply 10", "e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6"), + ( + "Nimzo-Indian, ply 20", + "d4 Nf6 c4 e6 Nc3 Bb4 e3 O-O Bd3 d5 Nf3 c5 O-O Nc6 a3 Bxc3 bxc3 dxc4 Bxc4 Qc7", + ), + ( + "Ruy Lopez, ply 40", + "e4 e5 Nf3 Nc6 Bb5 a6 Ba4 Nf6 O-O Be7 Re1 b5 Bb3 d6 c3 O-O h3 Nb8 d4 Nbd7 \ + Nbd2 Bb7 Bc2 Re8 Nf1 Bf8 Ng3 g6 a4 c5 d5 c4 Bg5 h6 Be3 Nc5 Qd2 h5", + ), +]; + +fn san_line(line: &str) -> Option<(Chess, Vec)> { + let mut pos = Chess::default(); + let mut moves = Vec::new(); + for s in line.split_whitespace() { + let m = s.parse::().ok()?.san.to_move(&pos).ok()?; + moves.push(m); + pos.play_unchecked(m); + } + Some((pos, moves)) +} + +/// Peak resident memory of this process, where the system tells (Linux). +fn peak_memory() -> String { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|s| { + s.lines() + .find(|l| l.starts_with("VmHWM")) + .map(|l| l.trim_start_matches("VmHWM:").trim().to_owned()) + }) + .unwrap_or_else(|| "n/a".into()) +} + +fn mb(bytes: u64) -> String { + format!("{:.0} MB", bytes as f64 / 1e6) +} + +/// Runs the measurements on the database at `path` and writes the report to `out`. +pub fn run(path: &Path, booster_dir: Option<&Path>, out: &mut dyn Write) -> io::Result<()> { + let never = AtomicBool::new(false); + let counter = AtomicUsize::new(0); + writeln!( + out, + "ChessPenguin {} bench · {} {} · {} threads · memory total {}, available {}", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + std::env::consts::ARCH, + std::thread::available_parallelism().map_or(0, |n| n.get()), + crate::memory::total().map_or("n/a".into(), mb), + crate::memory::available().map_or("n/a".into(), mb), + )?; + writeln!(out, "{}", path.display())?; + + let t = Instant::now(); + let opened = crate::open(path, &mut |_: ScanProgress| {}, &never) + .map_err(|e| io::Error::other(e.to_string()))?; + let db = opened.db; + writeln!( + out, + "open: {:.2} s · {:?} · {} records · peak memory {}", + t.elapsed().as_secs_f64(), + opened.format, + db.len(), + peak_memory() + )?; + + match &db { + Database::ChessBase(base) => { + if let Some(dir) = booster_dir { + base.set_booster_dir(dir); + } + let mut prepared = String::new(); + if base.prepare_wanted() { + let t = Instant::now(); + prepared = match base.prepare(&counter, &never) { + Ok(true) => format!(" (prepared in {:.1} s)", t.elapsed().as_secs_f64()), + Ok(false) => " (cancelled)".into(), + Err(e) => format!(" (preparing failed: {e})"), + }; + } + let openings = match base.openings_status() { + OpeningsStatus::Loaded(bytes) => format!("loaded, {}", mb(bytes as u64)), + OpeningsStatus::OnDisk { bytes, room } => format!( + "on disk, {}, not loaded ({})", + mb(bytes), + if room { + "room for it" + } else { + "not enough memory" + } + ), + OpeningsStatus::Missing { room: true } => "not built".into(), + OpeningsStatus::Missing { room: false } => "not built: not enough memory".into(), + OpeningsStatus::NoCache => "no cache directory".into(), + }; + writeln!( + out, + "search booster (.cbb or our own): {} · opening index: {openings}{prepared}", + if base.booster_ready() { "yes" } else { "no" } + )?; + + let carlsen = Filter { + player: NameFilter { + text: "carlsen, magnus".into(), + ..NameFilter::default() + }, + ..Filter::default() + }; + let t = Instant::now(); + let selected = base + .query(&carlsen, SortKey::Date, false, &counter, &never) + .unwrap_or_default(); + writeln!( + out, + "filter player \"carlsen, magnus\", newest first: {} games in {:.1} ms", + selected.len(), + t.elapsed().as_secs_f64() * 1e3 + )?; + let quick = Filter { + text: "carlsen 2020".into(), + ..Filter::default() + }; + let t = Instant::now(); + let found = base + .query(&quick, SortKey::Number, true, &counter, &never) + .map_or(0, |v| v.len()); + writeln!( + out, + "quick search \"carlsen 2020\": {found} games in {:.1} ms", + t.elapsed().as_secs_f64() * 1e3 + )?; + let t = Instant::now(); + let all = base + .query(&Filter::default(), SortKey::White, true, &counter, &never) + .unwrap_or_default(); + writeln!( + out, + "all {} records sorted by White: {:.1} ms", + all.len(), + t.elapsed().as_secs_f64() * 1e3 + )?; + drop(all); + let mut candidates: Vec = selected; + candidates.sort_unstable(); + + writeln!( + out, + "position search (all games: first run, second run; then among the filtered games):" + )?; + for (name, line) in LINES { + let Some((pos, moves)) = san_line(line) else { + continue; + }; + let query = PositionQuery::new(pos, Some(moves)); + let mut cells = Vec::new(); + let mut games = 0; + for cands in [None, None, Some(candidates.as_slice())] { + let t = Instant::now(); + let found = db.search_position(cands, &query, &counter, &never); + let ms = t.elapsed().as_secs_f64() * 1e3; + let n = found.as_ref().map_or(0, |o| o.matches.len()); + if cands.is_none() { + games = n; + } + cells.push(format!("{ms:8.1} ms")); + } + writeln!( + out, + " {name:22} {games:9} games {} {} filtered {}", + cells[0], cells[1], cells[2] + )?; + } + } + Database::Pgn(pgn) => { + writeln!( + out, + "games: {} · position table estimated at {}{}", + pgn.db.len(), + mb(pgn.positions_estimate()), + match pgn.positions_blocked() { + Some(_) => " · not built: not enough memory", + None => "", + } + )?; + let t = Instant::now(); + let Some(table) = pgn.positions(&counter, &never) else { + return Ok(()); + }; + writeln!( + out, + "position table: {:.2} s · {} positions · {} · peak memory {}", + t.elapsed().as_secs_f64(), + table.positions(), + mb(table.memory() as u64), + peak_memory() + )?; + writeln!(out, "position search (first run, second run):")?; + for (name, line) in LINES { + let Some((pos, moves)) = san_line(line) else { + continue; + }; + let query = PositionQuery::new(pos, Some(moves)); + let mut cells = Vec::new(); + let mut games = 0; + for _ in 0..2 { + let t = Instant::now(); + let found = db.search_position(None, &query, &counter, &never); + cells.push(format!("{:8.1} ms", t.elapsed().as_secs_f64() * 1e3)); + games = found.map_or(0, |o| o.matches.len()); + } + writeln!( + out, + " {name:22} {games:9} games {} {}", + cells[0], cells[1] + )?; + } + } + } + writeln!(out, "peak memory: {}", peak_memory())?; + Ok(()) +} diff --git a/crates/chess-import/src/cbv.rs b/crates/chess-import/src/cbv.rs new file mode 100644 index 0000000..bcfd7fc --- /dev/null +++ b/crates/chess-import/src/cbv.rs @@ -0,0 +1,270 @@ +//! ChessBase archives (`.cbv`): a container of the files of one database, each +//! compressed in blocks with an LZ77-style scheme and an optional Huffman stage. +//! +//! Layout (little-endian), as implemented by uncbv (GPL-3.0-or-later, Antoni +//! Boucher), rewritten here without unsafe code and with bounds checks: +//! +//! - header: `08 00`, file count (u16), size of a directory entry (u8), 3 bytes; +//! - directory: per file, a zero-terminated name in a 132-byte field, the +//! compressed and the decompressed size (i32), padded to the entry size; +//! - data: per file, blocks of `size (u16), unknown (u16), flag (u8), payload`, +//! where flag bit 1 = Huffman-coded payload, bit 0 = LZ-compressed payload. +//! +//! Password-protected archives (`.cbz`, DES) are not supported. + +use crate::ImportError; + +/// One file of an archive, decompressed. +#[derive(Clone, Debug)] +pub struct Member { + /// Name as stored (Windows-1252), `\` replaced by `/`. + pub name: String, + pub data: Vec, +} + +const NAME_FIELD: usize = 132; +/// Upper bound for one decompressed member (a corrupt size must not exhaust memory). +const MAX_MEMBER: usize = 1 << 30; + +/// True if `bytes` start like a CBV archive. +pub fn looks_like_cbv(bytes: &[u8]) -> bool { + bytes.len() >= 8 && bytes[0] == 0x08 && bytes[1] == 0x00 && bytes[4] as usize >= NAME_FIELD + 8 +} + +/// Unpacks every member of the archive. +pub fn unpack(bytes: &[u8]) -> Result, ImportError> { + let corrupt = |what: &str| ImportError::Corrupt(format!("CBV archive: {what}")); + if !looks_like_cbv(bytes) { + return Err(corrupt("not a ChessBase archive")); + } + let count = usize::from(u16::from_le_bytes([bytes[2], bytes[3]])); + let entry = usize::from(bytes[4]); + let mut pos = 8; + let mut directory = Vec::with_capacity(count); + for _ in 0..count { + let e = bytes + .get(pos..pos + entry) + .ok_or_else(|| corrupt("truncated directory"))?; + let name_bytes = &e[..NAME_FIELD]; + let end = name_bytes + .iter() + .position(|b| *b == 0) + .unwrap_or(NAME_FIELD); + let (name, _, _) = encoding_rs::WINDOWS_1252.decode(&name_bytes[..end]); + let compressed = i32::from_le_bytes([e[132], e[133], e[134], e[135]]); + let decompressed = i32::from_le_bytes([e[136], e[137], e[138], e[139]]); + let (Ok(compressed), Ok(decompressed)) = + (usize::try_from(compressed), usize::try_from(decompressed)) + else { + return Err(corrupt("negative size")); + }; + if decompressed > MAX_MEMBER { + return Err(corrupt("member too large")); + } + directory.push((name.replace('\\', "/"), compressed, decompressed)); + pos += entry; + } + let mut members = Vec::with_capacity(count); + for (name, compressed, decompressed) in directory { + let data = bytes + .get(pos..pos + compressed) + .ok_or_else(|| corrupt("truncated data"))?; + pos += compressed; + let out = unpack_member(data, decompressed) + .map_err(|e| ImportError::Corrupt(format!("CBV archive, {name}: {e}")))?; + members.push(Member { name, data: out }); + } + Ok(members) +} + +fn unpack_member(mut data: &[u8], expected: usize) -> Result, String> { + let mut out = Vec::with_capacity(expected); + while !data.is_empty() { + if data.len() < 4 { + return Err("truncated block header".into()); + } + let size = usize::from(u16::from_le_bytes([data[0], data[1]])); + let block = data.get(4..4 + size).ok_or("truncated block")?; + data = &data[4 + size..]; + let (&flag, payload) = block.split_first().ok_or("empty block")?; + if flag > 3 { + return Err(format!("unknown block flag {flag}")); + } + let decoded; + let payload = if flag & 0b10 != 0 { + decoded = huffman(payload)?; + &decoded[..] + } else { + payload + }; + if flag & 0b01 != 0 { + lz_decompress(payload, &mut out)?; + } else { + out.extend_from_slice(payload); + } + if out.len() > MAX_MEMBER { + return Err("member too large".into()); + } + } + if out.len() != expected { + return Err(format!( + "size {} instead of the declared {expected}", + out.len() + )); + } + Ok(out) +} + +/// LZ77 with run-length codes. Groups of 16 items are preceded by a 16-bit mask +/// (bit 15 first); a set bit marks a coded item, a clear bit a literal byte. +fn lz_decompress(mut input: &[u8], out: &mut Vec) -> Result<(), String> { + // The block's output starts a new window: references never reach into earlier blocks. + let base = out.len(); + let take = |input: &mut &[u8], n: usize| -> Result, String> { + let s = input.get(..n).ok_or("truncated LZ data")?.to_vec(); + *input = &input[n..]; + Ok(s) + }; + 'outer: while !input.is_empty() { + let m = take(&mut input, 2)?; + let mut mask = u16::from_le_bytes([m[0], m[1]]); + for _ in 0..16 { + if input.is_empty() { + break 'outer; + } + if mask & 0x8000 == 0 { + out.push(input[0]); + input = &input[1..]; + } else { + let b = take(&mut input, 1)?[0]; + let (high, low) = (usize::from(b >> 4), usize::from(b & 0x0f)); + match high { + 0 => { + // Short run: low + 3 copies of the next byte. + let v = take(&mut input, 1)?[0]; + out.extend(std::iter::repeat_n(v, low + 3)); + } + 1 => { + // Long run: low + (next byte << 4) + 0x13 copies. + let x = take(&mut input, 2)?; + let n = low + (usize::from(x[0]) << 4) + 0x13; + out.extend(std::iter::repeat_n(x[1], n)); + } + _ => { + // Back reference: offset from the next byte and `low`; the length + // is `high`, or a following byte + 0x10 when `high` is 2. + let x = take(&mut input, 1)?[0]; + let offset = (usize::from(x) << 4) + low + 3; + let len = if high == 2 { + usize::from(take(&mut input, 1)?[0]) + 0x10 + } else { + high + }; + if offset > out.len() - base { + return Err("LZ reference before the start of the block".into()); + } + let start = out.len() - offset; + // Byte by byte: the copy may overlap what it produces. + for i in 0..len { + let v = out[start + i]; + out.push(v); + } + } + } + } + mask <<= 1; + } + } + Ok(()) +} + +/// Huffman stage: decompressed size (u16, big-endian), then a bit stream (most +/// significant bit first) with, for each of the 256 byte values, a 4-bit code +/// length and the code itself, followed by the coded data. +fn huffman(payload: &[u8]) -> Result, String> { + let size = usize::from(u16::from_be_bytes([ + *payload.first().ok_or("truncated Huffman block")?, + *payload.get(1).ok_or("truncated Huffman block")?, + ])); + let mut bits = Bits { + data: &payload[2..], + pos: 0, + }; + // codes[len] maps a code of that length to its byte value. + let mut codes: Vec> = vec![Default::default(); 16]; + for value in 0..=255u8 { + let len = bits.read(4).ok_or("truncated Huffman table")? as usize; + if len > 0 { + let code = bits.read(len).ok_or("truncated Huffman table")?; + codes[len].insert(code, value); + } + } + let mut out = Vec::with_capacity(size); + while out.len() < size { + let (mut code, mut len) = (0u16, 0usize); + loop { + code = (code << 1) | bits.read(1).ok_or("truncated Huffman data")?; + len += 1; + if len >= 16 { + return Err("invalid Huffman code".into()); + } + if let Some(v) = codes[len].get(&code) { + out.push(*v); + break; + } + } + } + Ok(out) +} + +struct Bits<'a> { + data: &'a [u8], + pos: usize, +} + +impl Bits<'_> { + fn read(&mut self, n: usize) -> Option { + let mut v = 0u16; + for _ in 0..n { + let byte = *self.data.get(self.pos / 8)?; + let bit = (byte >> (7 - self.pos % 8)) & 1; + v = (v << 1) | u16::from(bit); + self.pos += 1; + } + Some(v) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lz_runs_and_overlapping_references() { + // mask: literal 'a', literal 'b', run of 4 'x', reference (offset 3, len 3) + // Items: 'a' (0), 'b' (0), coded 0x01 'x' (1), coded 0x30 0x00 (1). + let mask: u16 = 0b0011_0000_0000_0000; + let mut input = mask.to_le_bytes().to_vec(); + input.extend_from_slice(b"ab"); + input.extend_from_slice(&[0x01, b'x']); + input.extend_from_slice(&[0x30, 0x00]); + let mut out = Vec::new(); + lz_decompress(&input, &mut out).expect("valid"); + assert_eq!(out, b"abxxxxxxx"); + } + + #[test] + fn rejects_garbage() { + assert!(unpack(b"PK\x03\x04").is_err()); + let mut fake = vec![0x08, 0x00, 0x01, 0x00, 0x95, 0, 0, 0]; + let mut entry = b"a.cbh".to_vec(); + entry.resize(NAME_FIELD, 0); + entry.extend_from_slice(&100i32.to_le_bytes()); + entry.extend_from_slice(&10i32.to_le_bytes()); + entry.resize(0x95, 0); + fake.extend(entry); + assert!(unpack(&fake).is_err(), "member data past the end"); + fake.truncate(60); + assert!(unpack(&fake).is_err(), "truncated directory"); + } +} diff --git a/crates/chess-import/src/chessbase/annotations.rs b/crates/chess-import/src/chessbase/annotations.rs new file mode 100644 index 0000000..b84ff86 --- /dev/null +++ b/crates/chess-import/src/chessbase/annotations.rs @@ -0,0 +1,207 @@ +//! `.cba`: the annotations of a game, each attached to a move by its position in the +//! stored move order (−1 = the game as a whole). Big-endian. + +use std::collections::BTreeMap; + +use super::be; +use super::headers::Record; +use super::text::Decoder; + +/// What can be shown in PGN. Other annotation types (training, game quotations, +/// pictures, clocks, …) are skipped. +#[derive(Clone, Debug, PartialEq)] +pub enum Item { + Before(String), + After(String), + Nags(Vec), + /// (colour letter, square index a1 = 0) + Squares(Vec<(char, u8)>), + Arrows(Vec<(char, u8, u8)>), + /// Time spent on the move: h, m, s. + TimeSpent(u8, u8, u8), +} + +#[derive(Clone, Debug, Default)] +pub struct Annotations { + pub at: BTreeMap>, +} + +struct Raw<'a> { + position: i32, + kind: u8, + data: &'a [u8], +} + +const RECORD_HEADER: usize = 14; + +fn parse(cba: &[u8], offset: u32) -> Result<(u32, Vec>), String> { + let at = offset as usize; + let (Some(game), Some(size)) = (be(cba, at, 3), be(cba, at + 10, 4)) else { + return Err("annotations outside the .cba file".into()); + }; + let record = cba + .get(at..at + size as usize) + .filter(|r| r.len() >= RECORD_HEADER) + .ok_or("annotations outside the .cba file")?; + let mut items = Vec::new(); + let mut i = RECORD_HEADER; + while i + 6 <= record.len() { + let pos = be(record, i, 3).unwrap_or(0); + // Sign-extend the 24-bit position. + let position = ((pos << 8) as i32) >> 8; + let kind = record[i + 3]; + let len = be(record, i + 4, 2).unwrap_or(0) as usize; + if len < 6 || i + len > record.len() { + return Err("damaged annotation record".into()); + } + items.push(Raw { + position, + kind, + data: &record[i + 6..i + len], + }); + i += len; + } + Ok((game, items)) +} + +/// Adds the text bytes of every game's annotations to `buf` (for code page detection). +pub fn sample_texts(cba: &[u8], records: &[Record], buf: &mut Vec) { + for r in records { + if let Record::Game(h) = r + && h.annotations_offset > 0 + { + sample_at(cba, h.annotations_offset, buf); + } + } +} + +/// Adds the text bytes of one annotation record (starting at byte 0) to `buf`. +pub fn sample_record(record: &[u8], buf: &mut Vec) { + sample_at(record, 0, buf); +} + +fn sample_at(cba: &[u8], offset: u32, buf: &mut Vec) { + if let Ok((_, items)) = parse(cba, offset) { + for it in items { + if matches!(it.kind, 0x02 | 0x82) && it.data.len() > 2 { + super::text::add_sample(buf, &it.data[2..]); + } + } + } +} + +pub fn read(cba: &[u8], offset: u32, game_id: usize, d: &Decoder) -> Result { + let (game, items) = parse(cba, offset)?; + if game as usize != game_id { + return Err("annotations belong to another game".into()); + } + let mut out = Annotations::default(); + for it in items { + let item = match it.kind { + 0x02 | 0x82 => { + let text = d + .decode(it.data.get(2..).unwrap_or(&[])) + .replace(super::text::OBJECT, " ") + .replace("\r\n", "\n") + .replace('\r', "\n"); + let text = text.trim(); + if text.is_empty() { + continue; + } + if it.kind == 0x02 { + Item::After(text.to_owned()) + } else { + Item::Before(text.to_owned()) + } + } + 0x03 => { + let nags: Vec = it.data.iter().copied().filter(|n| *n != 0).collect(); + if nags.is_empty() { + continue; + } + Item::Nags(nags) + } + 0x04 => Item::Squares( + it.data + .as_chunks::<2>() + .0 + .iter() + .filter_map(|c| Some((colour(c[0])?, c[1].checked_sub(1)?))) + .filter(|(_, sq)| *sq < 64) + .collect(), + ), + 0x05 => Item::Arrows( + it.data + .as_chunks::<3>() + .0 + .iter() + .filter_map(|c| { + Some((colour(c[0])?, c[1].checked_sub(1)?, c[2].checked_sub(1)?)) + }) + .filter(|(_, a, b)| *a < 64 && *b < 64) + .collect(), + ), + 0x07 if it.data.len() >= 3 => Item::TimeSpent(it.data[0], it.data[1], it.data[2]), + _ => continue, + }; + out.at.entry(it.position).or_default().push(item); + } + Ok(out) +} + +/// ChessBase colours 2 green, 3 yellow, 4 red as PGN `%csl`/`%cal` letters. +fn colour(c: u8) -> Option { + match c { + 2 => Some('G'), + 3 => Some('Y'), + 4 => Some('R'), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::TextEncoding; + + fn ann(position: i32, kind: u8, data: &[u8]) -> Vec { + let mut v = (position as u32).to_be_bytes()[1..].to_vec(); + v.push(kind); + v.extend_from_slice(&((data.len() + 6) as u16).to_be_bytes()); + v.extend_from_slice(data); + v + } + + #[test] + fn reads_texts_symbols_and_graphics() { + let mut body = Vec::new(); + body.extend(ann(-1, 0x02, b"\x00\x00Intro")); + body.extend(ann(0, 0x03, &[1, 0, 0])); + body.extend(ann(0, 0x02, &[0, 0, 0xd0, 0xe0, 0xe7, 0x9e])); + body.extend(ann(1, 0x04, &[2, 1, 4, 64])); + body.extend(ann(1, 0x05, &[3, 13, 29, 9, 1, 2])); + let size = (RECORD_HEADER + body.len()) as u32; + let mut cba = vec![0u8; 26]; + let offset = cba.len() as u32; + cba.extend_from_slice(&[0, 0, 7, 1, 0, 0x0e, 0x0e, 0, 0, 6]); + cba.extend_from_slice(&size.to_be_bytes()); + cba.extend(body); + let d = Decoder::new(TextEncoding::Windows1251); + let a = read(&cba, offset, 7, &d).expect("record"); + assert_eq!(a.at[&-1], vec![Item::After("Intro".into())]); + assert_eq!( + a.at[&0], + vec![Item::Nags(vec![1]), Item::After("Раз".into())], + "cp1251 text, diagram marker removed" + ); + assert_eq!( + a.at[&1], + vec![ + Item::Squares(vec![('G', 0), ('R', 63)]), + Item::Arrows(vec![('Y', 12, 28)]), + ], + "unknown colour 9 dropped" + ); + assert!(read(&cba, offset, 8, &d).is_err(), "wrong game id"); + } +} diff --git a/crates/chess-import/src/chessbase/base.rs b/crates/chess-import/src/chessbase/base.rs new file mode 100644 index 0000000..4a649e0 --- /dev/null +++ b/crates/chess-import/src/chessbase/base.rs @@ -0,0 +1,1534 @@ +//! A ChessBase database read in place, for databases of any size (Mega Database: +//! 11.7 million games). Only the `.cbh` records and the player, tournament and +//! annotator lists are kept in memory; the moves and annotations of a game are read +//! from `.cbg` / `.cba` when the game is opened. Nothing is ever written. + +use std::collections::HashMap; +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use super::entities::{self, Entities, Kind}; +use super::headers::{self, GameHeader, Record}; +use super::text::{self, Decoder}; +use super::{annotations, be, booster, moves, openings, writer}; +use crate::ImportError; + +const RECORD: usize = 46; +/// Game flags of a `.cbh` record (offset 0x27). +const FLAG_VARIATIONS: u32 = 0x2; +const FLAG_COMMENTS: u32 = 0x4; + +/// What a record of the database is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RecordKind { + Game, + Text, + Deleted, +} + +/// A ChessBase database opened for reading. +pub struct Base { + path: PathBuf, + /// The `.cbh` records after the header record, `RECORD` bytes each. + cbh: Vec, + records: usize, + games: usize, + texts: usize, + players: Names, + tournaments: Names, + annotators: Entities, + tournament_entities: Entities, + player_entities: Entities, + decoder: Decoder, + cbg_path: PathBuf, + cbg: Mutex, + /// Records in the `.cbh` file, trailing empty ones included (the `.cbb` booster + /// counts them). + file_records: usize, + /// The `.cbb` search booster, when present and consistent (checked on first use). + cbb: OnceLock>, + /// Where our own booster is kept when `.cbb` cannot be used (set by the + /// application), and that booster once found or built. + booster_dir: OnceLock, + own_booster: OnceLock, + /// The opening index, once loaded (`openings.rs`; kept in the same directory). + openings: Mutex>>, + /// Held by [`Base::prepare`]: two callers (the search board, the reference panel) + /// never build the same files at once; the second finds them done. + preparing: Mutex<()>, + cba: Option>, + /// Titles of guiding texts read so far (they are stored with the text). + text_titles: Mutex>, + /// Remarks about the database as a whole, one line each. + notes: Vec, +} + +/// Decoded names of a list, folded copies for searching (see [`fold`]), the +/// alphabetical rank of each (for sorting by name) and the number of games of each. +pub(crate) struct Names { + shown: Vec, + folded: Vec, + rank: Vec, + games: Vec, + white_games: Vec, + black_games: Vec, +} + +impl Names { + pub(crate) fn new(shown: Vec) -> Names { + let folded: Vec = shown.iter().map(|s| fold(s)).collect(); + let mut order: Vec = (0..folded.len() as u32).collect(); + order.sort_by(|&a, &b| folded[a as usize].cmp(&folded[b as usize])); + let mut rank = vec![0; folded.len()]; + for (r, id) in order.into_iter().enumerate() { + // An empty name has no value: it sorts last, like a missing rating. + rank[id as usize] = if folded[id as usize].trim().is_empty() { + u32::MAX + } else { + r as u32 + }; + } + let games = vec![0; shown.len()]; + let white_games = vec![0; shown.len()]; + let black_games = vec![0; shown.len()]; + Names { + shown, + folded, + rank, + games, + white_games, + black_games, + } + } + + pub(crate) fn count(&mut self, id: u32) { + if let Some(n) = self.games.get_mut(id as usize) { + *n += 1; + } + } + + /// Counts one game of a player. A player on both sides still has one game in + /// total, while each colour has that game in its own count. + pub(crate) fn count_player_game(&mut self, white: u32, black: u32) { + self.count(white); + if black != white { + self.count(black); + } + if let Some(n) = self.white_games.get_mut(white as usize) { + *n += 1; + } + if let Some(n) = self.black_games.get_mut(black as usize) { + *n += 1; + } + } + + pub(crate) fn player_counts(&self, id: u32) -> (u32, u32, u32) { + let at = |values: &[u32]| values.get(id as usize).copied().unwrap_or(0); + ( + at(&self.games), + at(&self.white_games), + at(&self.black_games), + ) + } + + pub(crate) fn get(&self, id: u32) -> &str { + self.shown.get(id as usize).map_or("", String::as_str) + } + + /// Alphabetical place of a name for sorting; an empty name has none (`u64::MAX`: + /// last in both directions, like a missing rating). + pub(crate) fn rank(&self, id: u32) -> u64 { + match self.rank.get(id as usize) { + Some(&r) if r != u32::MAX => u64::from(r), + _ => u64::MAX, + } + } + + /// Ids whose name contains every word of `query`, as a lookup table. + pub(crate) fn matching(&self, query: &str) -> Vec { + let words = words(query); + self.folded + .iter() + .map(|n| words.iter().all(|w| n.contains(w.as_str()))) + .collect() + } + + /// Up to `limit` names containing every word of `query`: names starting with + /// the first word first, then by number of games. Also the number of matches. + pub(crate) fn suggest(&self, query: &str, limit: usize) -> (Vec, usize) { + self.suggest_page(query, 0, limit, false) + } + + /// A page of suggestions. With `all_when_empty`, an empty query lists every + /// non-empty name alphabetically (the Android player picker); otherwise it has + /// the old behaviour and returns no suggestions. + pub(crate) fn suggest_page( + &self, + query: &str, + start: usize, + limit: usize, + all_when_empty: bool, + ) -> (Vec, usize) { + let words = words(query); + let all = words.is_empty() && all_when_empty; + if words.is_empty() && !all { + return (Vec::new(), 0); + } + let mut hits: Vec<(bool, u32, u32)> = self + .folded + .iter() + .enumerate() + .filter(|(_, n)| { + !n.trim().is_empty() && (all || words.iter().all(|w| n.contains(w.as_str()))) + }) + .map(|(id, n)| { + let id = id as u32; + ( + !all && !n.starts_with(words[0].as_str()), + id, + self.games[id as usize], + ) + }) + .collect(); + let total = hits.len(); + hits.sort_by(|a, b| { + if all { + self.rank(a.1).cmp(&self.rank(b.1)).then(a.1.cmp(&b.1)) + } else { + a.0.cmp(&b.0) + .then(b.2.cmp(&a.2)) + .then(self.rank(a.1).cmp(&self.rank(b.1))) + .then(a.1.cmp(&b.1)) + } + }); + let list = hits + .into_iter() + .skip(start) + .take(limit) + .map(|(_, id, games)| Suggestion { + id, + name: self.get(id).to_owned(), + games, + }) + .collect(); + (list, total) + } +} + +/// A name offered while typing a filter. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Suggestion { + pub id: u32, + pub name: String, + pub games: u32, +} + +/// Lower case without diacritics ("Hübner" → "hubner", "Å�" → "l"), for searching. +pub fn fold(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars().flat_map(char::to_lowercase) { + let base = match c { + 'à'..='Ã¥' | 'Ä�' | 'ă' | 'Ä…' => "a", + 'æ' => "ae", + 'ç' | 'ć' | 'ĉ' | 'Ä‹' | 'Ä�' => "c", + 'Ä�' | 'Ä‘' | 'ð' => "d", + 'è'..='ë' | 'Ä“' | 'Ä•' | 'Ä—' | 'Ä™' | 'Ä›' => "e", + // «Ð�ртём» is typed «Ð�ртем». + 'Ñ‘' => "е", + 'Ä�' | 'ÄŸ' | 'Ä¡' | 'Ä£' => "g", + 'Ä¥' | 'ħ' => "h", + 'ì'..='ï' | 'Ä©' | 'Ä«' | 'Ä­' | 'į' | 'ı' => "i", + 'ĵ' => "j", + 'Ä·' => "k", + 'ĺ' | 'ļ' | 'ľ' | 'Å€' | 'Å‚' => "l", + 'ñ' | 'Å„' | 'ņ' | 'ň' => "n", + 'ò'..='ö' | 'ø' | 'Å�' | 'Å�' | 'Å‘' => "o", + 'Å“' => "oe", + 'Å•' | 'Å—' | 'Å™' => "r", + 'Å›' | 'Å�' | 'ÅŸ' | 'Å¡' | 'È™' => "s", + 'ß' => "ss", + 'Å£' | 'Å¥' | 'ŧ' | 'È›' => "t", + 'ù'..='ü' | 'Å©' | 'Å«' | 'Å­' | 'ů' | 'ű' | 'ų' => "u", + 'ŵ' => "w", + 'ý' | 'ÿ' | 'Å·' => "y", + 'ź' | 'ż' | 'ž' => "z", + 'þ' => "th", + _ => { + out.push(c); + continue; + } + }; + out.push_str(base); + } + out +} + +/// Folded words of a search query; commas separate words too ("Carlsen, M"), and so +/// does the full stop of an initial ("Carlsen, M." finds "Carlsen, Magnus"). +pub(crate) fn words(query: &str) -> Vec { + fold(query) + .split(|c: char| c.is_whitespace() || c == ',' || c == '.') + .filter(|w| !w.is_empty()) + .map(str::to_owned) + .collect() +} + +/// One row of the game table. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Row { + pub kind: Option, + pub white: String, + pub black: String, + pub white_elo: u16, + pub black_elo: u16, + /// "1-0", "0-1", "1/2-1/2" or "*". + pub result: &'static str, + pub eco: Option, + /// A Chess960 game (its moves cannot be read). + pub chess960: bool, + pub event: String, + pub site: String, + /// PGN date ("1997.05.??"). + pub date: String, + pub round: String, + pub annotator: String, + /// Moves of the main line (255: 255 or more; 0: none). + pub moves: u8, + pub has_variations: bool, + pub has_comments: bool, + /// The title of a guiding text. + pub title: String, +} + +/// Fields of the table a game list can be sorted by. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum SortKey { + Number, + White, + WhiteElo, + Black, + BlackElo, + Result, + Moves, + Eco, + Event, + Date, + /// Average rating of the two players (only when both are known); equal averages + /// by date. + AverageElo, +} + +/// Which side a player filter applies to. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Side { + #[default] + Any, + White, + Black, +} + +/// A game result. With a player filter, [`Filter::player_relative`] makes +/// `WhiteWins` mean "the player won" and `BlackWins` "the player lost". +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Outcome { + WhiteWins, + Draw, + BlackWins, + Unknown, +} + +/// Whose rating [`Filter::elo_min`] applies to. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum EloRule { + #[default] + Both, + Either, + Average, + /// The opponent of the player given in the filter. + Opponent, +} + +/// A name filter: words to look for, or one entity picked from the suggestions. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct NameFilter { + pub text: String, + pub exact: Option, +} + +impl NameFilter { + pub fn is_set(&self) -> bool { + self.exact.is_some() || !words(&self.text).is_empty() + } +} + +/// A game filter; empty fields match everything. Guiding texts have no players, +/// results, ratings or dates: any such condition leaves them out. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Filter { + pub player: NameFilter, + pub side: Side, + pub opponent: NameFilter, + /// The tournament's title or place. + pub event: NameFilter, + pub annotator: String, + pub year_from: Option, + pub year_to: Option, + pub elo_min: Option, + pub elo_rule: EloRule, + /// ECO ranges as numbers 0 (A00) … 499 (E99), inclusive (see [`parse_eco`]). + pub eco: Vec<(u16, u16)>, + pub outcomes: Vec, + pub player_relative: bool, + /// Main-line moves, inclusive. + pub moves_from: Option, + pub moves_to: Option, + pub with_comments: bool, + pub with_variations: bool, + /// Leave guiding texts out. + pub games_only: bool, + /// The quick search: every word in some field of the game — a player, the + /// tournament (title, place, year), the annotator, the ECO code, the date. + pub text: String, +} + +/// ECO ranges of a filter: codes ("B90"), prefixes ("B9" = B90-B99, "B" = B00-B99) +/// and ranges ("C60-C99"), separated by commas. `None` if the text is not valid. +pub fn parse_eco(text: &str) -> Option> { + let one = |s: &str| -> Option<(u16, u16)> { + let s = s.trim().to_ascii_uppercase(); + let mut chars = s.chars(); + let letter = chars.next()?; + if !('A'..='E').contains(&letter) { + return None; + } + let base = (letter as u16 - 'A' as u16) * 100; + let digits: String = chars.collect(); + if !digits.chars().all(|c| c.is_ascii_digit()) { + return None; + } + match digits.len() { + 0 => Some((base, base + 99)), + 1 => { + let d = digits.parse::().ok()? * 10; + Some((base + d, base + d + 9)) + } + 2 => { + let d = digits.parse::().ok()?; + Some((base + d, base + d)) + } + _ => None, + } + }; + let mut out = Vec::new(); + for part in text.split(',').map(str::trim).filter(|p| !p.is_empty()) { + let part = part.replace(['–', '—'], "-"); + let range = match part.split_once('-') { + Some((a, b)) => { + let (a, b) = (one(a)?, one(b)?); + (a.0 <= b.1).then_some((a.0, b.1))? + } + None => one(&part)?, + }; + out.push(range); + } + (!out.is_empty()).then_some(out) +} + +impl Base { + /// Opens the database whose `.cbh` file is `cbh`. `progress` gets (bytes read, + /// bytes total) of the record file. + pub fn open( + cbh: &Path, + progress: &mut dyn FnMut(u64, u64), + cancel: &AtomicBool, + ) -> Result { + let io = |path: &Path| { + let path = path.to_owned(); + move |source| ImportError::Io { path, source } + }; + let companion = |ext: &str| find_companion(cbh, ext); + let cbh_bytes = read_with_progress(cbh, progress, cancel)?; + if cbh_bytes.len() < RECORD || be(&cbh_bytes, 3, 2) != Some(RECORD as u32) { + return Err(ImportError::Corrupt( + "ChessBase database: the .cbh file has an unknown layout".into(), + )); + } + let truncated = (cbh_bytes.len() % RECORD) != 0; + let mut body = cbh_bytes; + body.drain(..RECORD); + let file_records = body.len() / RECORD; + // All-zero records lie past the last game; a damaged record in between is + // treated as deleted (see `kind`), so the records after it stay readable. + let records = body + .as_chunks::() + .0 + .iter() + .rposition(|r| r[0] & 1 != 0) + .map_or(0, |last| last + 1); + body.truncate(records * RECORD); + body.shrink_to_fit(); + + let cbg_path = companion("cbg").ok_or_else(|| missing(cbh, "cbg"))?; + let cbg = File::open(&cbg_path).map_err(io(&cbg_path))?; + let cba = companion("cba") + .map(|p| File::open(&p).map_err(io(&p))) + .transpose()?; + let read_list = |ext: &str| -> Result>, ImportError> { + companion(ext) + .map(|p| std::fs::read(&p).map_err(io(&p))) + .transpose() + }; + let player_entities = entities::read(read_list("cbp")?.as_deref(), Kind::Player); + let tournament_entities = entities::read(read_list("cbt")?.as_deref(), Kind::Tournament); + let annotators = entities::read(read_list("cbc")?.as_deref(), Kind::Annotator); + if cancel.load(Ordering::Relaxed) { + return Err(ImportError::Cancelled); + } + + let mut base = Base { + path: cbh.to_owned(), + cbh: body, + records, + games: 0, + texts: 0, + players: Names::new(Vec::new()), + tournaments: Names::new(Vec::new()), + annotators, + tournament_entities, + player_entities, + decoder: Decoder::new(chess_core::TextEncoding::Windows1252), + cbg_path, + cbg: Mutex::new(cbg), + file_records, + cbb: OnceLock::new(), + booster_dir: OnceLock::new(), + own_booster: OnceLock::new(), + openings: Mutex::new(None), + preparing: Mutex::new(()), + cba: cba.map(Mutex::new), + text_titles: Mutex::new(HashMap::new()), + notes: Vec::new(), + }; + if truncated { + base.notes + .push("the .cbh file ends inside a record; the last record is left out".into()); + } + base.decoder = Decoder::new(base.detect_encoding()); + let d = &base.decoder; + let players = (0..base.player_entities.len() as u32) + .map(|id| base.player_entities.name(id, d).unwrap_or_default()) + .collect(); + let tournaments = (0..base.tournament_entities.len() as u32) + .map(|id| { + let title = base.tournament_entities.name(id, d).unwrap_or_default(); + let mut name = match base.tournament_entities.place(id, d) { + Some(place) if !title.contains(&place) => format!("{title} ({place})"), + _ => title, + }; + // Tournaments of the same name in different years: tell them apart. + let year = (base.tournament_entities.date(id) >> 9) & 0xfff; + if year > 0 && !name.contains(&year.to_string()) { + name = format!("{name} {year}"); + } + name.trim().to_owned() + }) + .collect(); + base.players = Names::new(players); + base.tournaments = Names::new(tournaments); + // Counts: records by kind, games by player and tournament (for suggestions). + let (mut games, mut texts, mut chess960, mut damaged) = (0, 0, 0, 0); + for r in base.cbh.as_chunks::().0 { + let u = |at, n| be(r.as_slice(), at, n).unwrap_or(0); + if r[0] & 1 == 0 { + damaged += 1; + continue; + } + if r[0] & 0x80 != 0 { + continue; + } + if r[0] & 0x02 != 0 { + texts += 1; + continue; + } + games += 1; + if u(0x23, 2) >= 64576 { + chess960 += 1; + } + base.players.count_player_game(u(0x09, 3), u(0x0c, 3)); + base.tournaments.count(u(0x0f, 3)); + } + base.games = games; + base.texts = texts; + if chess960 > 0 { + base.notes.push(format!( + "Chess960 games are not supported: {chess960} games are shown without moves" + )); + } + if damaged > 0 { + base.notes.push(format!( + "{damaged} damaged records in the .cbh file are left out" + )); + } + Ok(base) + } + + /// Code page of the single-byte texts, from the names and the comments of the + /// first annotated games. + fn detect_encoding(&self) -> chess_core::TextEncoding { + let mut sample = Vec::new(); + for e in [ + &self.player_entities, + &self.tournament_entities, + &self.annotators, + ] { + e.sample(&mut sample); + } + let mut annotated = 0; + for i in 0..self.records { + if annotated >= 500 || sample.len() > 4 << 20 { + break; + } + let offset = be(self.record(i), 5, 4).unwrap_or(0); + if self.kind(i) == RecordKind::Game + && offset > 0 + && let Some(bytes) = self.read_annotations(offset) + { + annotations::sample_record(&bytes, &mut sample); + annotated += 1; + } + } + text::detect(&sample) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// The `.cbg` file, for readers that open their own handle (position search). + pub(super) fn cbg_path(&self) -> &Path { + &self.cbg_path + } + + /// Makes position searches run without the `.cbb` booster (for measurements). + #[cfg(test)] + pub(super) fn without_booster(&self) { + let _ = self.cbb.set(None); + } + + /// Offset of the record's moves in `.cbg` (games and texts). + pub(super) fn moves_offset(&self, index: usize) -> u32 { + be(self.record(index), 1, 4).unwrap_or(0) + } + + /// The search booster to use: `.cbb` if it can be trusted (its record count is + /// that of the `.cbh` file plus one, it holds that many 52-byte records and it is + /// not older than `.cbg`: a program that does not maintain it may have changed the + /// games since), else our own one (see [`Base::build_booster`]). + pub(super) fn cbb_path(&self) -> Option<&Path> { + self.cbb + .get_or_init(|| { + let path = find_companion(&self.path, "cbb")?; + let cbg_time = std::fs::metadata(&self.cbg_path).ok()?.modified().ok()?; + let fresh = std::fs::metadata(&path).ok()?.modified().ok()? >= cbg_time; + (fresh && booster_consistent(&path, self.file_records)).then_some(path) + }) + .as_deref() + .or_else(|| self.own_booster.get().map(PathBuf::as_path)) + } + + /// Records in the `.cbh` file, trailing empty ones included. + pub(super) fn file_records(&self) -> usize { + self.file_records + } + + /// Tells where our own booster lives (a cache directory), and takes the one + /// built earlier for this database if it is there. + pub fn set_booster_dir(&self, dir: &Path) { + let _ = self.booster_dir.set(dir.to_owned()); + if let Some(p) = self.own_booster_path() + && booster_consistent(&p, self.file_records) + { + let _ = self.own_booster.set(p); + } + } + + /// Where the files of this database go in the cache directory, without the + /// extension: named after the database and the size and date of its games, so a + /// changed database gets new ones. + fn cache_stem(&self) -> Option { + let dir = self.booster_dir.get()?; + let path = std::fs::canonicalize(&self.path).unwrap_or_else(|_| self.path.clone()); + let meta = std::fs::metadata(&self.cbg_path).ok()?; + let modified = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_nanos()); + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in path + .to_string_lossy() + .bytes() + .chain(meta.len().to_le_bytes()) + .chain(modified.to_le_bytes()) + .chain((self.file_records as u64).to_le_bytes()) + { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + Some(dir.join(format!("{h:016x}"))) + } + + fn own_booster_path(&self) -> Option { + self.cache_stem().map(|p| p.with_extension("cbb")) + } + + fn openings_path(&self) -> Option { + self.cache_stem().map(|p| p.with_extension("cpo")) + } + + /// The opening index, when it is loaded. + pub fn openings(&self) -> Option> { + self.openings.lock().ok()?.clone() + } + + /// Where the opening index stands. + pub fn openings_status(&self) -> OpeningsStatus { + if let Some(index) = self.openings() { + return OpeningsStatus::Loaded(index.memory()); + } + let Some(path) = self.openings_path() else { + return OpeningsStatus::NoCache; + }; + match openings::Index::file_size(&path) { + Some(bytes) => OpeningsStatus::OnDisk { + bytes, + room: room_for(bytes), + }, + None => OpeningsStatus::Missing { + room: room_for(self.records as u64 * openings::BYTES_PER_GAME), + }, + } + } + + /// Something is left to build or load for fast position searches + /// ([`Base::prepare`]). + pub fn prepare_wanted(&self) -> bool { + self.booster_wanted() + || matches!( + self.openings_status(), + OpeningsStatus::Missing { room: true } | OpeningsStatus::OnDisk { room: true, .. } + ) + } + + /// The work [`Base::prepare`] has to do, in the units of its `progress`: the + /// records of the pass, and as many again for sorting the opening index. + pub fn prepare_work(&self) -> usize { + let pass = self.booster_wanted() || self.openings_to_build(); + let sort = self.openings_to_build(); + self.records * (usize::from(pass) + usize::from(sort)) + } + + fn openings_to_build(&self) -> bool { + matches!( + self.openings_status(), + OpeningsStatus::Missing { room: true } + ) + } + + /// Builds what is missing for fast position searches — our booster when `.cbb` + /// cannot be used, the opening index when the machine has room for it — in one + /// pass over the games (`progress` counts the records done, and again while the + /// index is sorted), then loads the index. `Ok(false)` when cancelled. + pub fn prepare(&self, progress: &AtomicUsize, cancel: &AtomicBool) -> std::io::Result { + let _one_at_a_time = self + .preparing + .lock() + .map_err(|_| std::io::Error::other("prepare lock"))?; + if cancel.load(Ordering::Relaxed) { + return Ok(false); + } + let Some(stem) = self.cache_stem() else { + return Err(std::io::Error::other("no cache directory")); + }; + let booster_path = self.booster_wanted().then(|| stem.with_extension("cbb")); + let openings_path = stem.with_extension("cpo"); + let build_openings = matches!( + self.openings_status(), + OpeningsStatus::Missing { room: true } + ); + if booster_path.is_some() || build_openings { + let built = booster::build( + self, + booster_path.as_deref(), + build_openings.then_some(openings_path.as_path()), + progress, + cancel, + )?; + if !built { + return Ok(false); + } + if let Some(p) = booster_path { + let _ = self.own_booster.set(p); + } + } + if self.openings().is_none() + && let Some(bytes) = openings::Index::file_size(&openings_path) + && room_for(bytes) + { + match openings::Index::load(&openings_path, self.records) { + Some(index) => { + if let Ok(mut o) = self.openings.lock() { + *o = Some(Arc::new(index)); + } + } + // Not an index for this database (an older layout): built anew next time. + None => { + let _ = std::fs::remove_file(&openings_path); + } + } + } + Ok(true) + } + + /// Position searches have a booster (ChessBase's or ours). + pub fn booster_ready(&self) -> bool { + self.cbb_path().is_some() + } + + /// A booster of our own would help and can be built ([`Base::set_booster_dir`]). + pub fn booster_wanted(&self) -> bool { + !self.booster_ready() && self.booster_dir.get().is_some() + } + + /// Builds our own booster (one pass over all the games; `progress` counts the + /// records done) and uses it from then on. `Ok(false)` when cancelled. + pub fn build_booster( + &self, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> std::io::Result { + let Some(path) = self.own_booster_path() else { + return Err(std::io::Error::other("no booster directory")); + }; + if !booster::build(self, Some(&path), None, progress, cancel)? { + return Ok(false); + } + let _ = self.own_booster.set(path); + Ok(true) + } + + /// Number of records (games, texts and deleted records); a record's index is its + /// game number minus one. + pub fn records(&self) -> usize { + self.records + } + + pub fn games(&self) -> usize { + self.games + } + + pub fn texts(&self) -> usize { + self.texts + } + + pub fn encoding(&self) -> chess_core::TextEncoding { + self.decoder.single_byte() + } + + /// The raw 46-byte record (also a stable identity of the game). + pub fn record(&self, index: usize) -> &[u8] { + self.cbh + .get(index * RECORD..(index + 1) * RECORD) + .unwrap_or(&[]) + } + + /// Remarks about the database as a whole (Chess960 games, damaged records). + pub fn notes(&self) -> &[String] { + &self.notes + } + + pub fn kind(&self, index: usize) -> RecordKind { + match self.record(index).first() { + Some(k) if k & 0x80 != 0 || k & 1 == 0 => RecordKind::Deleted, + Some(k) if k & 0x02 != 0 => RecordKind::Text, + Some(_) => RecordKind::Game, + None => RecordKind::Deleted, + } + } + + fn header(&self, index: usize) -> Option { + // `headers::read` expects the file header first. + let mut buf = [0u8; 2 * RECORD]; + buf[3..5].copy_from_slice(&(RECORD as u16).to_be_bytes()); + buf[RECORD..].copy_from_slice(self.record(index).get(..RECORD)?); + headers::read(&buf).ok()?.into_iter().next() + } + + pub fn row(&self, index: usize) -> Row { + match self.header(index) { + Some(Record::Game(h)) => self.game_row(&h), + Some(Record::Text(t)) => Row { + kind: Some(RecordKind::Text), + event: self.tournaments.get(t.tournament).to_owned(), + annotator: self + .annotators + .name(t.annotator, &self.decoder) + .unwrap_or_default(), + round: headers::round_tag(t.round, t.subround), + result: "*", + date: "????.??.??".into(), + title: self.text_title(index, t.text_offset), + ..Row::default() + }, + _ => Row { + kind: Some(RecordKind::Deleted), + result: "*", + ..Row::default() + }, + } + } + + fn game_row(&self, h: &GameHeader) -> Row { + let d = &self.decoder; + Row { + kind: Some(RecordKind::Game), + white: self.players.get(h.white).to_owned(), + black: self.players.get(h.black).to_owned(), + white_elo: h.white_elo, + black_elo: h.black_elo, + result: h.result_tag(), + eco: h.eco_tag(), + chess960: h.eco >= 64576, + event: self + .tournament_entities + .name(h.tournament, d) + .unwrap_or_default(), + site: self + .tournament_entities + .place(h.tournament, d) + .unwrap_or_default(), + date: headers::date_tag(h.date), + round: headers::round_tag(h.round, h.subround), + annotator: self.annotators.name(h.annotator, d).unwrap_or_default(), + moves: h.moves, + has_variations: h.flags & FLAG_VARIATIONS != 0, + has_comments: h.flags & FLAG_COMMENTS != 0, + title: String::new(), + } + } + + fn text_title(&self, index: usize, offset: u32) -> String { + if let Ok(cache) = self.text_titles.lock() + && let Some(t) = cache.get(&index) + { + return t.clone(); + } + let title = self + .read_moves(offset) + .and_then(|b| text::guiding_text(&b, 0, &self.decoder).ok()) + .map(|b| b.title) + .unwrap_or_default(); + if let Ok(mut cache) = self.text_titles.lock() { + cache.insert(index, title.clone()); + } + title + } + + /// The record as PGN text (UTF-8), and a problem when the game could only be read + /// in part. `None` for a deleted record. + pub fn pgn(&self, index: usize) -> Option<(String, Option)> { + let game_id = index + 1; + let mut out = String::new(); + match self.header(index)? { + Record::Game(h) => { + let d = &self.decoder; + let tags = writer::tags( + &h, + &self.player_entities, + &self.tournament_entities, + &self.annotators, + d, + ); + let (tree, mut problem) = match self.read_moves(h.moves_offset) { + None => ( + moves::Tree::start(), + Some("moves outside the .cbg file".to_owned()), + ), + Some(bytes) => match moves::decode(&bytes, 0) { + Ok(t) => (t, None), + Err(e) => (e.partial, Some(e.reason)), + }, + }; + let notes = if h.annotations_offset > 0 { + self.read_annotations(h.annotations_offset) + .ok_or_else(|| "annotations outside the .cba file".to_owned()) + .and_then(|b| annotations::read(&b, 0, game_id, d)) + .unwrap_or_else(|reason| { + problem.get_or_insert(reason); + annotations::Annotations::default() + }) + } else { + annotations::Annotations::default() + }; + writer::game(&mut out, &tags, &tree, ¬es, h.result_tag()); + Some((out, problem)) + } + Record::Text(t) => { + let d = &self.decoder; + let body = self + .read_moves(t.text_offset) + .ok_or_else(|| "text outside the .cbg file".to_owned()) + .and_then(|b| text::guiding_text(&b, 0, d)); + let (body, problem) = match body { + Ok(b) => (b, None), + Err(e) => ( + text::Body { + title: String::new(), + text: String::new(), + }, + Some(e), + ), + }; + let tags = writer::text_tags( + &t, + &body.title, + &self.tournament_entities, + &self.annotators, + d, + ); + writer::text_game(&mut out, &tags, &body.text); + Some((out, problem)) + } + Record::Deleted => None, + } + } + + /// The first `max_plies` moves of the main line of game `index`, decoded without + /// building the move tree (see [`moves::main_line`]). `None` for a text, a deleted + /// record or unreadable moves. + pub fn main_line(&self, index: usize, max_plies: usize) -> Option { + let Record::Game(h) = self.header(index)? else { + return None; + }; + let bytes = self.read_moves(h.moves_offset)?; + let walk = |fast: bool| -> Result { + let mut line = crate::MainLine::default(); + let mut first = true; + moves::main_line(&bytes, 0, fast, |pos, step| { + if std::mem::take(&mut first) { + line.standard_start = + crate::position::same_position(pos, &shakmaty::Chess::default()); + if !line.standard_start { + return false; + } + } + match step { + moves::Step::Move(m) => { + line.moves.push(*m); + line.moves.len() < max_plies + } + // A null move or the end: the opening line stops here. + moves::Step::Null | moves::Step::End => false, + } + })?; + Ok(line) + }; + // The fast decoder trusts the data: a damaged game is read again carefully. + walk(true).or_else(|_| walk(false)).ok() + } + + /// The `.cbg` record at `offset` (its size is in bytes 1-3). + fn read_moves(&self, offset: u32) -> Option> { + let mut f = self.cbg.lock().ok()?; + read_sized(&mut f, offset, 0, 1, 3) + } + + /// The `.cba` record at `offset` (its size is in bytes 10-13). + fn read_annotations(&self, offset: u32) -> Option> { + let mut f = self.cba.as_ref()?.lock().ok()?; + read_sized(&mut f, offset, 14, 10, 4) + } + + /// Player names for a filter being typed, and the number of matches. + pub fn suggest_players(&self, query: &str, limit: usize) -> (Vec, usize) { + self.players.suggest(query, limit) + } + + /// A page of player names; an empty query lists every named player. + pub fn suggest_players_page( + &self, + query: &str, + start: usize, + limit: usize, + ) -> (Vec, usize) { + self.players.suggest_page(query, start, limit, true) + } + + /// Total, white and black games of a player (a self-game counts once in total). + pub fn player_counts(&self, id: u32) -> (u32, u32, u32) { + self.players.player_counts(id) + } + + /// Tournament names ("Title (Place)") for a filter being typed. + pub fn suggest_events(&self, query: &str, limit: usize) -> (Vec, usize) { + self.tournaments.suggest(query, limit) + } + + pub fn player_name(&self, id: u32) -> &str { + self.players.get(id) + } + + pub fn event_name(&self, id: u32) -> &str { + self.tournaments.get(id) + } + + /// Indices of the records that pass `filter`, sorted. `scanned` counts the + /// records looked at so far (for a progress display). `None` when cancelled. + pub fn query( + &self, + filter: &Filter, + sort: SortKey, + ascending: bool, + scanned: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option> { + let player_ids = name_table(&self.players, &filter.player); + let opponent_ids = name_table(&self.players, &filter.opponent); + let event_ids = name_table(&self.tournaments, &filter.event); + let annotator = words(&filter.annotator); + let annotator_ids = (!annotator.is_empty()).then(|| { + (0..self.annotators.len() as u32) + .map(|id| { + let name = fold(&self.annotators.name(id, &self.decoder).unwrap_or_default()); + annotator.iter().all(|w| name.contains(w.as_str())) + }) + .collect::>() + }); + let has = |ids: &Option>, id: u32| { + ids.as_ref() + .is_none_or(|t| t.get(id as usize).copied().unwrap_or(false)) + }; + // The quick search, word by word: the names it is in. + let quick: Vec = words(&filter.text) + .into_iter() + .map(|w| QuickWord { + players: self.players.matching(&w), + events: self.tournaments.matching(&w), + annotators: (0..self.annotators.len() as u32) + .map(|id| { + fold(&self.annotators.name(id, &self.decoder).unwrap_or_default()) + .contains(w.as_str()) + }) + .collect(), + // A record's year has 12 bits and its ECO 500 values: tables, not text. + years: (0..4096u32) + .map(|y| y > 0 && y.to_string().contains(w.as_str())) + .collect(), + ecos: (0..500u16) + .map(|c| fold(&eco_text(c)).contains(w.as_str())) + .collect(), + }) + .collect(); + let names = player_ids.is_some() || opponent_ids.is_some(); + let game_only_conditions = names + || filter.year_from.is_some() + || filter.year_to.is_some() + || filter.elo_min.is_some() + || !filter.eco.is_empty() + || !filter.outcomes.is_empty() + || filter.moves_from.is_some() + || filter.moves_to.is_some() + || filter.with_comments + || filter.with_variations; + let relative = filter.player_relative && player_ids.is_some(); + + let mut out: Vec = Vec::new(); + for (i, r) in self.cbh.as_chunks::().0.iter().enumerate() { + if i % 65536 == 0 { + if cancel.load(Ordering::Relaxed) { + return None; + } + scanned.store(i, Ordering::Relaxed); + } + let u = |at, n| be(r.as_slice(), at, n).unwrap_or(0); + let kind = r[0]; + if kind & 0x80 != 0 || kind & 1 == 0 { + continue; + } + if kind & 0x02 != 0 { + // A guiding text: only the tournament and the annotator apply. + // The quick search looks in its tournament and annotator. + let at = |t: &Vec, id: u32| t.get(id as usize).copied().unwrap_or(false); + if !filter.games_only + && !game_only_conditions + && has(&event_ids, u(0x07, 3)) + && has(&annotator_ids, u(0x0d, 3)) + && quick + .iter() + .all(|q| at(&q.events, u(0x07, 3)) || at(&q.annotators, u(0x0d, 3))) + { + out.push(i as u32); + } + continue; + } + let (white, black) = (u(0x09, 3), u(0x0c, 3)); + // Which side the player of the filter is on (both: either way round). + let mut player_white = true; + let mut player_black = true; + if names { + let as_white = has(&player_ids, white) && has(&opponent_ids, black); + let as_black = has(&player_ids, black) && has(&opponent_ids, white); + player_white = as_white && filter.side != Side::Black; + player_black = as_black && filter.side != Side::White; + if !player_white && !player_black { + continue; + } + } + if !has(&event_ids, u(0x0f, 3)) || !has(&annotator_ids, u(0x12, 3)) { + continue; + } + if filter.year_from.is_some() || filter.year_to.is_some() { + let year = (u(0x18, 3) >> 9) & 0xfff; + if year == 0 + || filter.year_from.is_some_and(|y| year < u32::from(y)) + || filter.year_to.is_some_and(|y| year > u32::from(y)) + { + continue; + } + } + if let Some(min) = filter.elo_min.map(u32::from) { + let (we, bl) = (u(0x1f, 2), u(0x21, 2)); + let ok = match filter.elo_rule { + EloRule::Both => we >= min && bl >= min, + EloRule::Either => we >= min || bl >= min, + EloRule::Average => we > 0 && bl > 0 && (we + bl) / 2 >= min, + EloRule::Opponent if player_ids.is_some() => { + (player_white && bl >= min) || (player_black && we >= min) + } + EloRule::Opponent => we >= min || bl >= min, + }; + if !ok { + continue; + } + } + if !filter.eco.is_empty() { + let Some(code) = eco_number(u(0x23, 2) as u16) else { + continue; + }; + if !filter.eco.iter().any(|&(a, b)| (a..=b).contains(&code)) { + continue; + } + } + if !filter.outcomes.is_empty() { + let board = match r[0x1b] { + 0 | 4 => Outcome::BlackWins, + 1 | 5 => Outcome::Draw, + 2 | 6 => Outcome::WhiteWins, + _ => Outcome::Unknown, + }; + let wanted = |o: Outcome| filter.outcomes.contains(&o); + let ok = if relative && matches!(board, Outcome::WhiteWins | Outcome::BlackWins) { + // WhiteWins = the player won, BlackWins = the player lost. + let flipped = match board { + Outcome::WhiteWins => Outcome::BlackWins, + _ => Outcome::WhiteWins, + }; + (player_white && wanted(board)) || (player_black && wanted(flipped)) + } else { + wanted(board) + }; + if !ok { + continue; + } + } + if filter.moves_from.is_some() || filter.moves_to.is_some() { + let moves = u32::from(r[0x2d]); + if filter.moves_from.is_some_and(|m| moves < u32::from(m)) + || filter.moves_to.is_some_and(|m| moves > u32::from(m)) + { + continue; + } + } + let flags = u(0x27, 4); + if (filter.with_comments && flags & FLAG_COMMENTS == 0) + || (filter.with_variations && flags & FLAG_VARIATIONS == 0) + { + continue; + } + if !quick.is_empty() { + let year = (u(0x18, 3) >> 9) & 0xfff; + let eco = eco_number(u(0x23, 2) as u16); + let found = quick.iter().all(|q| { + let at = |t: &Vec, id: u32| t.get(id as usize).copied().unwrap_or(false); + at(&q.players, white) + || at(&q.players, black) + || at(&q.events, u(0x0f, 3)) + || at(&q.annotators, u(0x12, 3)) + || eco.is_some_and(|c| at(&q.ecos, u32::from(c))) + || at(&q.years, year) + }); + if !found { + continue; + } + } + out.push(i as u32); + } + scanned.store(self.records, Ordering::Relaxed); + if cancel.load(Ordering::Relaxed) { + return None; + } + self.sort_records(&mut out, sort, ascending); + Some(out) + } + + /// Sorts record indices (in record order on entry) by `sort`; records without a + /// value (no rating, no date, a text) stay at the end in both directions. + pub fn sort_records(&self, records: &mut Vec, sort: SortKey, ascending: bool) { + if sort != SortKey::Number { + let mut keyed: Vec<(u64, u32)> = records + .iter() + .map(|&i| (self.sort_key(i as usize, sort), i)) + .collect(); + keyed.sort_unstable(); + *records = keyed.into_iter().map(|(_, i)| i).collect(); + } else { + records.sort_unstable(); + } + if !ascending { + let split = records + .iter() + .position(|&i| self.sort_key(i as usize, sort) == u64::MAX) + .unwrap_or(records.len()); + records[..split].reverse(); + } + } + + /// Sort value of a record; `u64::MAX` for no value (no rating, no date, a text). + fn sort_key(&self, index: usize, sort: SortKey) -> u64 { + let r = self.record(index); + let u = |at, n| be(r, at, n).unwrap_or(0); + let text = r.first().is_some_and(|k| k & 0x02 != 0); + if text && !matches!(sort, SortKey::Number | SortKey::Event) { + return u64::MAX; + } + let none_if_zero = |v: u32| if v == 0 { u64::MAX } else { u64::from(v) }; + match sort { + SortKey::Number => index as u64, + SortKey::White => self.players.rank(u(0x09, 3)), + SortKey::Black => self.players.rank(u(0x0c, 3)), + SortKey::WhiteElo => none_if_zero(u(0x1f, 2)), + SortKey::BlackElo => none_if_zero(u(0x21, 2)), + SortKey::Result => match r.get(0x1b) { + Some(2 | 6) => 0, + Some(1 | 5) => 1, + Some(0 | 4) => 2, + _ => u64::MAX, + }, + SortKey::Moves => none_if_zero(u32::from(r.get(0x2d).copied().unwrap_or(0))), + SortKey::Eco => eco_number(u(0x23, 2) as u16).map_or(u64::MAX, u64::from), + SortKey::Event => self + .tournaments + .rank(if text { u(0x07, 3) } else { u(0x0f, 3) }), + SortKey::Date => none_if_zero(u(0x18, 3)), + SortKey::AverageElo => { + let (w, b) = (u(0x1f, 2), u(0x21, 2)); + if w == 0 || b == 0 { + u64::MAX + } else { + // The average first, then the date. + (u64::from((w + b) / 2) << 32) | u64::from(u(0x18, 3)) + } + } + } + } +} + +/// A word of the quick search and the names it is in. +struct QuickWord { + players: Vec, + events: Vec, + annotators: Vec, + /// Years (0–4095) whose number holds the word. + years: Vec, + /// ECO codes (0 = A00 … 499 = E99) that hold it. + ecos: Vec, +} + +/// 190 → "B90". +pub(crate) fn eco_text(code: u16) -> String { + format!("{}{:02}", char::from(b'A' + (code / 100) as u8), code % 100) +} + +/// Ids matching a name filter (`None`: no condition). +pub(crate) fn name_table(names: &Names, f: &NameFilter) -> Option> { + if let Some(id) = f.exact { + let mut t = vec![false; names.shown.len()]; + if let Some(x) = t.get_mut(id as usize) { + *x = true; + } + return Some(t); + } + (!words(&f.text).is_empty()).then(|| names.matching(&f.text)) +} + +/// Where the opening index of a database stands (see [`Base::openings_status`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OpeningsStatus { + /// In memory, this many bytes. + Loaded(usize), + /// Built, but not loaded; `room`: the machine has memory for it now. + OnDisk { bytes: u64, room: bool }, + /// Not built; `room`: the machine has memory to build and hold it. + Missing { room: bool }, + /// No cache directory was given. + NoCache, +} + +/// Whether `bytes` more can be held in memory with a gigabyte to spare. Unknown +/// memory counts as no room. +fn room_for(bytes: u64) -> bool { + crate::memory::available().is_some_and(|free| free >= bytes + (1 << 30)) +} + +/// A booster file holds a record per `.cbh` record (plus its header) and says so. +fn booster_consistent(path: &Path, file_records: usize) -> bool { + let Ok(mut f) = File::open(path) else { + return false; + }; + let mut head = [0u8; 4]; + if f.read_exact(&mut head).is_err() { + return false; + } + let count = u32::from_be_bytes(head) as u64; + count == file_records as u64 + 1 && f.metadata().is_ok_and(|m| m.len() >= 52 * count) +} + +/// ECO code number 0 (A00) … 499 (E99) of a `.cbh` ECO field. +fn eco_number(eco: u16) -> Option { + if eco == 0 || eco >= 64576 { + return None; + } + (eco / 128).checked_sub(1).filter(|c| *c < 500) +} + +/// Reads a record whose size is stored as a `size_len`-byte big-endian number at +/// `size_at`; `head` bytes are read first (at least enough to hold the size). +fn read_sized( + f: &mut File, + offset: u32, + head: usize, + size_at: usize, + size_len: usize, +) -> Option> { + let head = head.max(size_at + size_len); + f.seek(SeekFrom::Start(u64::from(offset))).ok()?; + let mut buf = vec![0u8; head]; + f.read_exact(&mut buf).ok()?; + let size = be(&buf, size_at, size_len)? as usize; + // Records hold at most a few megabytes; a larger size means damaged data. + if size < head || size > 64 << 20 { + return None; + } + buf.resize(size, 0); + f.read_exact(&mut buf[head..]).ok()?; + Some(buf) +} + +/// `/.`, whatever the case of the extension. +fn find_companion(cbh: &Path, ext: &str) -> Option { + let dir = cbh.parent().unwrap_or(Path::new(".")); + let stem = cbh.file_stem()?; + std::fs::read_dir(dir) + .ok()? + .flatten() + .map(|e| e.path()) + .find(|p| { + p.file_stem() == Some(stem) + && p.extension() + .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case(ext)) + }) +} + +fn missing(cbh: &Path, ext: &str) -> ImportError { + ImportError::Corrupt(format!( + "ChessBase database {}: the .{ext} file is missing", + cbh.file_stem().unwrap_or_default().to_string_lossy() + )) +} + +fn read_with_progress( + path: &Path, + progress: &mut dyn FnMut(u64, u64), + cancel: &AtomicBool, +) -> Result, ImportError> { + let io = |source| ImportError::Io { + path: path.to_owned(), + source, + }; + let mut f = File::open(path).map_err(io)?; + let total = f.metadata().map_err(io)?.len(); + let mut out = Vec::with_capacity(total as usize); + let mut chunk = vec![0u8; 8 << 20]; + loop { + if cancel.load(Ordering::Relaxed) { + return Err(ImportError::Cancelled); + } + let n = f.read(&mut chunk).map_err(io)?; + if n == 0 { + break; + } + out.extend_from_slice(&chunk[..n]); + progress(out.len() as u64, total); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eco_filters() { + assert_eq!(parse_eco("B90"), Some(vec![(190, 190)])); + assert_eq!(parse_eco("b9"), Some(vec![(190, 199)])); + assert_eq!(parse_eco("E"), Some(vec![(400, 499)])); + assert_eq!(parse_eco("C60-C99, A00"), Some(vec![(260, 299), (0, 0)])); + assert_eq!(parse_eco("C6–D"), Some(vec![(260, 399)])); + assert_eq!(parse_eco("C99-C60"), None); + assert_eq!(parse_eco("F00"), None); + assert_eq!(parse_eco("B901"), None); + assert_eq!(parse_eco(""), None); + } + + #[test] + fn folding_and_words() { + assert_eq!(fold("Hübner, Robert"), "hubner, robert"); + assert_eq!(fold("Å�ukasz ĆwikÅ‚a"), "lukasz cwikla"); + assert_eq!(words(" Carlsen,Magnus "), vec!["carlsen", "magnus"]); + // An initial with its full stop finds the full name. + assert_eq!(words("Вафин, Р."), vec!["вафин", "Ñ€"]); + assert_eq!(words("J.R. Capablanca"), vec!["j", "r", "capablanca"]); + let names = Names::new(vec![ + "Carlsen, Magnus".into(), + "Carlsen, Henrik".into(), + "Hübner, Robert".into(), + ]); + assert_eq!(names.matching("magnus carlsen"), vec![true, false, false]); + assert_eq!(names.matching("hubner"), vec![false, false, true]); + let (list, total) = names.suggest("carl", 1); + assert_eq!((list.len(), total), (1, 2)); + let (list, total) = names.suggest("Carlsen, M.", 5); + assert_eq!((list.len(), total), (1, 1)); + assert_eq!(list[0].name, "Carlsen, Magnus"); + } + + #[test] + fn eco_numbers() { + assert_eq!(eco_number((201 + 1) * 128 + 5), Some(201)); + assert_eq!(eco_number(0), None); + assert_eq!(eco_number(64576), None); + } +} diff --git a/crates/chess-import/src/chessbase/booster.rs b/crates/chess-import/src/chessbase/booster.rs new file mode 100644 index 0000000..a08b3ea --- /dev/null +++ b/crates/chess-import/src/chessbase/booster.rs @@ -0,0 +1,283 @@ +//! Our own search booster for a large ChessBase database whose `.cbb` is missing or +//! stale: the same 52-byte record per game (what was ever on the board in the main +//! line, see `Signature` in `search.rs`), computed from `.cbg` once and kept in the +//! user's cache directory under a name derived from the database (path, size and +//! date of `.cbg`), so a changed database gets a new file. The format is that of +//! `.cbb`, header included, so the search reads both the same way; our record matched +//! ChessBase's byte for byte on Mega (`docs/research/position-index.md`, section 1.1). +//! +//! The same pass over the main lines also collects the opening index (`openings.rs`) +//! when it is wanted: [`build`] makes either or both. + +use std::fs::File; +use std::io; +use std::path::Path; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use shakmaty::{Board, Chess, Color, Position, Role}; + +use super::base::{Base, RecordKind}; +use super::be; +use super::moves::{self, Step, WalkError}; +use super::openings::{self, GameEntry}; +use super::search::{BLOCK, CBB_RECORD, read_games}; + +/// Marks in `r` what stands on `b`: the layout of a `.cbb` record. +fn mark(b: &Board, r: &mut [u8; CBB_RECORD]) { + for (sq, piece) in b.clone() { + let file = 1u8 << (sq.file() as u32); + let rank = sq.rank() as usize; + let white = piece.color == Color::White; + match piece.role { + Role::Pawn if white && (2..=6).contains(&rank) => r[0x06 + rank - 2] |= file, + Role::Pawn if !white && (1..=5).contains(&rank) => r[0x0b + rank - 1] |= file, + Role::Pawn => {} + Role::King => { + let (rk, f) = if white { (0x10, 0x12) } else { (0x11, 0x13) }; + r[rk] |= 1 << rank; + r[f] |= file; + } + Role::Rook | Role::Queen => r[if white { 0x14 } else { 0x1c } + rank] |= file, + Role::Knight | Role::Bishop => r[if white { 0x24 } else { 0x2c } + rank] |= file, + } + } + for (c, shift) in [(Color::White, 0), (Color::Black, 4)] { + let count = |role: Role| (b.by_color(c) & b.by_role(role)).count(); + let (q, rook, bishop, knight) = ( + count(Role::Queen), + count(Role::Rook), + count(Role::Bishop), + count(Role::Knight), + ); + // "Was without" (byte 5) and "had at most one" (byte 4); for the queen + // ChessBase sets the bit of byte 4 together with that of byte 5. + if q == 0 { + r[0x05] |= 1 << shift; + r[0x04] |= 1 << shift; + } + for (flag, n) in [(2u8, rook), (4, bishop), (8, knight)] { + if n == 0 { + r[0x05] |= flag << shift; + } + if n <= 1 { + r[0x04] |= flag << shift; + } + } + if q + rook + bishop + knight == 0 { + r[0x03] |= 8 << shift; + } + } +} + +/// What one walk of a game's main line yields. +pub(super) struct GameData { + pub record: [u8; CBB_RECORD], + /// The opening entries, when asked for; `None` for a game from a set-up position. + pub opening: Option, + /// The game starts from a set-up position (with `opening` asked for). + pub set_up: bool, +} + +fn walk(cbg: &[u8], offset: u32, fast: bool, opening: Option) -> Result { + let mut r = [0u8; CBB_RECORD]; + let mut end_pawns = 0u8; + let mut entry = opening.map(GameEntry::new); + let mut ply = 0usize; + moves::main_line(cbg, offset, fast, |pos: &Chess, step| { + let b = pos.board(); + mark(b, &mut r); + if matches!(step, Step::End) { + let pawns = |c: Color| (b.by_color(c) & b.pawns()).count().min(7) as u8; + end_pawns = pawns(Color::White) | (pawns(Color::Black) << 4); + } + if let Some(e) = entry.as_mut() { + e.visit(pos, ply, &step); + } + ply += 1; + true + })?; + r[0x03] |= end_pawns; + let set_up = entry.as_ref().is_some_and(|e| !e.standard); + Ok(GameData { + record: r, + opening: entry.filter(|e| e.standard), + set_up, + }) +} + +/// The booster record of the game at `offset` in `cbg` (and its opening entries when +/// `opening` names the game): the fast walk, and the checked one when the fast one +/// stumbles. `None` when the game cannot be read (a position search cannot find it +/// either). +pub(super) fn game_data(cbg: &[u8], offset: u32, opening: Option) -> Option { + match walk(cbg, offset, true, opening) { + Ok(d) => Some(d), + Err(WalkError::Moves(_)) => walk(cbg, offset, false, opening).ok(), + Err(WalkError::Unsupported(_)) => None, + } +} + +/// The booster record alone. +#[cfg(test)] +pub(super) fn record_of(cbg: &[u8], offset: u32) -> Option<[u8; CBB_RECORD]> { + game_data(cbg, offset, None).map(|d| d.record) +} + +fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> { + #[cfg(unix)] + { + std::os::unix::fs::FileExt::write_all_at(f, buf, at) + } + #[cfg(windows)] + { + let (mut buf, mut at) = (buf, at); + while !buf.is_empty() { + match std::os::windows::fs::FileExt::seek_write(f, buf, at)? { + 0 => return Err(io::ErrorKind::WriteZero.into()), + n => { + buf = &buf[n..]; + at += n as u64; + } + } + } + Ok(()) + } + // Elsewhere (WebAssembly) through the cursor: such a target has no threads to + // share it with. + #[cfg(not(any(unix, windows)))] + { + use std::io::{Seek, SeekFrom, Write}; + let mut f = f; + f.seek(SeekFrom::Start(at))?; + f.write_all(buf) + } +} + +/// One pass over the main lines of `base`, in parallel, writing the booster to +/// `booster` and the opening index to `openings` (each when given; `.part` files +/// first, renamed when complete). `progress` counts the records done, then the +/// records again while the index is sorted. `Ok(false)` when cancelled; then nothing +/// is left behind. +pub(super) fn build( + base: &Base, + booster: Option<&Path>, + openings: Option<&Path>, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> io::Result { + let total = base.records(); + let count = base.file_records() + 1; + let part = booster.map(|p| p.with_extension("part")); + if let (Some(out), Some(part)) = (booster, &part) { + if let Some(dir) = out.parent() { + std::fs::create_dir_all(dir)?; + } + File::create(part)?.set_len((count * CBB_RECORD) as u64)?; + } + let sink = match openings { + Some(out) => Some(openings::Sink::new(&out.with_extension("build"), total)?), + None => None, + }; + let next = AtomicUsize::new(0); + let threads = crate::parallel::threads(4) + .min(total.div_ceil(BLOCK)) + .max(1); + let failure: Mutex> = Mutex::new(None); + crate::parallel::map(vec![(); threads], |()| { + let run = || -> io::Result<()> { + let cbg = File::open(base.cbg_path())?; + let file = part + .as_ref() + .map(|p| File::options().write(true).open(p)) + .transpose()?; + let mut games: Vec<(u32, u32)> = Vec::new(); + let (mut span, mut single) = (Vec::new(), Vec::new()); + let mut block = vec![0u8; BLOCK * CBB_RECORD]; + let mut entries: Vec = Vec::new(); + let mut set_up: Vec = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return Ok(()); + } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Ok(()); + } + let to = (from + BLOCK).min(total); + let bytes = &mut block[..(to - from) * CBB_RECORD]; + bytes.fill(0); + entries.clear(); + set_up.clear(); + games.clear(); + for i in from..to { + // Texts and Chess960 games (ECO field ≥ 64576) have no + // record, like in ChessBase's own file. + if base.kind(i) == RecordKind::Game + && be(base.record(i), 0x23, 2).is_some_and(|eco| eco < 64576) + { + games.push((i as u32, base.moves_offset(i))); + } + } + read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| { + let opening = sink.is_some().then_some(index); + if let Some(d) = game_data(data, rel, opening) { + let at = (index as usize - from) * CBB_RECORD; + bytes[at..at + CBB_RECORD].copy_from_slice(&d.record); + entries.extend(d.opening); + if d.set_up { + set_up.push(index); + } + } + }); + if let Some(f) = &file { + write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?; + } + if let Some(sink) = &sink { + sink.add(&entries, &set_up)?; + } + progress.fetch_add(to - from, Ordering::Relaxed); + } + }; + if let Err(e) = run() { + cancel.store(true, Ordering::Relaxed); + if let Ok(mut f) = failure.lock() { + f.get_or_insert(e); + } + } + }); + let clean = || { + if let Some(p) = &part { + let _ = std::fs::remove_file(p); + } + }; + if let Some(e) = failure.into_inner().unwrap_or(None) { + clean(); + if let Some(s) = sink { + let _ = s.discard(); + } + return Err(e); + } + if cancel.load(Ordering::Relaxed) { + clean(); + if let Some(s) = sink { + let _ = s.discard(); + } + return Ok(false); + } + if let (Some(out), Some(part)) = (booster, &part) { + // The header last: a file without the count is never taken for a booster. + let mut header = [0u8; CBB_RECORD]; + header[..4].copy_from_slice(&(count as u32).to_be_bytes()); + { + let file = File::options().write(true).open(part)?; + write_all_at(&file, &header, 0)?; + file.sync_all()?; + } // Closed before the rename. + std::fs::rename(part, out)?; + } + if let (Some(out), Some(sink)) = (openings, sink) { + return sink.finish(out, total, progress, cancel); + } + Ok(true) +} diff --git a/crates/chess-import/src/chessbase/entities.rs b/crates/chess-import/src/chessbase/entities.rs new file mode 100644 index 0000000..38ecbcd --- /dev/null +++ b/crates/chess-import/src/chessbase/entities.rs @@ -0,0 +1,112 @@ +//! `.cbp` players, `.cbt` tournaments, `.cbc` annotators: fixed-size records after a +//! small little-endian header; an entity id is the record's index. + +use super::le_i32; +use super::text::Decoder; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Player, + Tournament, + Annotator, +} + +/// Raw string fields of every record (decoded later, once the code page is known). +#[derive(Clone, Debug, Default)] +pub struct Entities { + kind: Option, + records: Vec>>, + /// Tournament start dates (packed), by id. + dates: Vec, +} + +/// Node of the tree (9 bytes) before the data of each record. +const NODE: usize = 9; + +pub fn read(bytes: Option<&[u8]>, kind: Kind) -> Entities { + let mut out = Entities { + kind: Some(kind), + ..Entities::default() + }; + let Some(bytes) = bytes else { return out }; + let (Some(count), Some(data_size), Some(extra)) = + (le_i32(bytes, 0), le_i32(bytes, 0x0c), le_i32(bytes, 0x18)) + else { + return out; + }; + let header = 28 + usize::try_from(extra).unwrap_or(0).min(4); + let Ok(record) = usize::try_from(data_size).map(|d| d + NODE) else { + return out; + }; + // Fields: (offset in data, length). + let fields: &[(usize, usize)] = match kind { + Kind::Player => &[(0x00, 30), (0x1e, 20)], + Kind::Tournament => &[(0x00, 40), (0x28, 30)], + Kind::Annotator => &[(0x00, 45)], + }; + for i in 0..usize::try_from(count).unwrap_or(0) { + let Some(rec) = bytes.get(header + i * record..header + (i + 1) * record) else { + break; + }; + let data = &rec[NODE..]; + out.records.push( + fields + .iter() + .map(|&(at, len)| { + let f = data.get(at..at + len).unwrap_or(&[]); + let end = f.iter().position(|b| *b == 0).unwrap_or(f.len()); + f[..end].to_vec() + }) + .collect(), + ); + if kind == Kind::Tournament { + out.dates.push( + le_i32(data, 0x46) + .and_then(|d| u32::try_from(d).ok()) + .unwrap_or(0), + ); + } + } + out +} + +impl Entities { + pub fn len(&self) -> usize { + self.records.len() + } + + pub fn sample(&self, buf: &mut Vec) { + for rec in &self.records { + for f in rec { + super::text::add_sample(buf, f); + } + } + } + + fn field(&self, id: u32, i: usize, d: &Decoder) -> Option { + let f = self.records.get(id as usize)?.get(i)?; + let s = d.decode_name(f).trim().to_owned(); + (!s.is_empty()).then_some(s) + } + + /// "Last, First" for a player; the title of a tournament; an annotator's name. + pub fn name(&self, id: u32, d: &Decoder) -> Option { + let first = self.field(id, 0, d); + if self.kind == Some(Kind::Player) { + return match (first, self.field(id, 1, d)) { + (Some(last), Some(given)) => Some(format!("{last}, {given}")), + (last, given) => last.or(given), + }; + } + first + } + + /// Tournament place. + pub fn place(&self, id: u32, d: &Decoder) -> Option { + self.field(id, 1, d) + } + + pub fn date(&self, id: u32) -> u32 { + self.dates.get(id as usize).copied().unwrap_or(0) + } +} diff --git a/crates/chess-import/src/chessbase/headers.rs b/crates/chess-import/src/chessbase/headers.rs new file mode 100644 index 0000000..65e5644 --- /dev/null +++ b/crates/chess-import/src/chessbase/headers.rs @@ -0,0 +1,155 @@ +//! `.cbh`: one 46-byte record per game or guiding text (big-endian). + +use super::be; +use crate::ImportError; + +const RECORD: usize = 46; + +#[derive(Clone, Debug)] +pub enum Record { + Game(GameHeader), + Text(TextHeader), + Deleted, +} + +#[derive(Clone, Debug, Default)] +pub struct GameHeader { + pub moves_offset: u32, + pub annotations_offset: u32, + pub white: u32, + pub black: u32, + pub tournament: u32, + pub annotator: u32, + pub date: u32, + pub result: u8, + pub round: u8, + pub subround: u8, + pub white_elo: u16, + pub black_elo: u16, + pub eco: u16, + /// Annotation flags (variations, comments, symbols, …). + pub flags: u32, + /// Main-line moves (255: 255 or more). + pub moves: u8, +} + +#[derive(Clone, Debug, Default)] +pub struct TextHeader { + pub text_offset: u32, + pub tournament: u32, + pub annotator: u32, + pub round: u8, + pub subround: u8, +} + +pub fn read(cbh: &[u8]) -> Result, ImportError> { + if cbh.len() < RECORD || be(cbh, 3, 2) != Some(RECORD as u32) { + return Err(ImportError::Corrupt( + "ChessBase database: the .cbh file has an unknown layout".into(), + )); + } + let mut out = Vec::new(); + for rec in cbh[RECORD..].as_chunks::().0 { + let kind = rec[0]; + if kind & 1 == 0 { + // All-zero records lie past the last game. + break; + } + let u = |at, n| be(rec.as_slice(), at, n).unwrap_or(0); + out.push(if kind & 0x80 != 0 { + Record::Deleted + } else if kind & 0x02 != 0 { + Record::Text(TextHeader { + text_offset: u(0x01, 4), + tournament: u(0x07, 3), + annotator: u(0x0d, 3), + round: rec[0x10], + subround: rec[0x11], + }) + } else { + Record::Game(GameHeader { + moves_offset: u(0x01, 4), + annotations_offset: u(0x05, 4), + white: u(0x09, 3), + black: u(0x0c, 3), + tournament: u(0x0f, 3), + annotator: u(0x12, 3), + date: u(0x18, 3), + result: rec[0x1b], + round: rec[0x1d], + subround: rec[0x1e], + white_elo: u(0x1f, 2) as u16, + black_elo: u(0x21, 2) as u16, + eco: u(0x23, 2) as u16, + flags: u(0x27, 4), + moves: rec[0x2d], + }) + }); + } + Ok(out) +} + +impl GameHeader { + pub fn result_tag(&self) -> &'static str { + match self.result { + 0 | 4 => "0-1", + 1 | 5 => "1/2-1/2", + 2 | 6 => "1-0", + _ => "*", + } + } + + /// "C41" (sub-codes are ChessBase-specific and dropped); `None` for no ECO or Chess960. + pub fn eco_tag(&self) -> Option { + if self.eco == 0 || self.eco >= 64576 { + return None; + } + let code = usize::from(self.eco / 128).checked_sub(1)?; + let letter = *b"ABCDE".get(code / 100)?; + Some(format!("{}{:02}", letter as char, code % 100)) + } +} + +/// "1858.??.??" from a packed date (day bits 0-4, month 5-8, year 9-20). +pub fn date_tag(packed: u32) -> String { + let (day, month, year) = (packed & 31, (packed >> 5) & 15, (packed >> 9) & 0xfff); + let part = |v: u32, w: usize| { + if v == 0 { + "?".repeat(w) + } else { + format!("{v:0w$}") + } + }; + format!("{}.{}.{}", part(year, 4), part(month, 2), part(day, 2)) +} + +pub fn round_tag(round: u8, subround: u8) -> String { + match (round, subround) { + (0, _) => "?".into(), + (r, 0) => r.to_string(), + (r, s) => format!("{r}.{s}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dates_eco_and_rounds() { + assert_eq!(date_tag((1905 << 9) | (8 << 5) | 31), "1905.08.31"); + assert_eq!(date_tag(1907 << 9), "1907.??.??"); + assert_eq!(date_tag(0), "????.??.??"); + let h = |eco| GameHeader { + eco, + ..GameHeader::default() + }; + assert_eq!(h((201 + 1) * 128 + 5).eco_tag().as_deref(), Some("C01")); + assert_eq!(h(128).eco_tag().as_deref(), Some("A00")); + assert_eq!(h(0).eco_tag(), None); + assert_eq!(h(64576).eco_tag(), None); + assert_eq!(round_tag(0, 0), "?"); + assert_eq!(round_tag(3, 0), "3"); + assert_eq!(round_tag(3, 2), "3.2"); + } +} diff --git a/crates/chess-import/src/chessbase/mod.rs b/crates/chess-import/src/chessbase/mod.rs new file mode 100644 index 0000000..8bdf4de --- /dev/null +++ b/crates/chess-import/src/chessbase/mod.rs @@ -0,0 +1,285 @@ +//! ChessBase databases (`.cbh` and companion files) converted to PGN text. +//! +//! The layout follows the public format description of the Morphy project +//! (`format/v1` in github.com/Yarin78/morphy), used as a source of facts; no code is taken +//! from it. Only reading is supported, and the source files are never written. + +mod annotations; +pub mod base; +mod booster; +mod entities; +mod headers; +mod moves; +pub mod openings; +pub mod search; +mod text; +mod writer; + +use std::collections::HashMap; +use std::path::Path; + +use chess_core::TextEncoding; + +use crate::ImportError; + +/// The files of one database, by lower-case extension (`cbh`, `cbg`, …). +#[derive(Clone, Debug, Default)] +pub struct Files { + pub name: String, + files: HashMap>, +} + +impl Files { + /// Reads `/.` for every extension the reader uses. + pub fn from_dir(cbh: &Path) -> Result { + let dir = cbh.parent().unwrap_or(Path::new(".")); + let stem = cbh + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let mut files = Files { + name: stem.clone(), + files: HashMap::new(), + }; + let entries = std::fs::read_dir(dir).map_err(|source| ImportError::Io { + path: dir.to_owned(), + source, + })?; + for e in entries.flatten() { + let p = e.path(); + let (Some(s), Some(ext)) = (p.file_stem(), p.extension()) else { + continue; + }; + let ext = ext.to_string_lossy().to_ascii_lowercase(); + if s.to_string_lossy() == stem && USED.contains(&ext.as_str()) { + let bytes = std::fs::read(&p).map_err(|source| ImportError::Io { + path: p.clone(), + source, + })?; + files.files.insert(ext, bytes); + } + } + Ok(files) + } + + /// The database whose `.cbh` file is `cbh_name` from files given as (name, content), + /// taking the contents (others are left out). + pub fn from_owned(cbh_name: &str, members: Vec<(String, Vec)>) -> Files { + let stem = stem_of(cbh_name).to_owned(); + let mut files = Files { + name: stem.rsplit('/').next().unwrap_or(&stem).to_owned(), + files: HashMap::new(), + }; + for (name, data) in members { + if let Some(ext) = part_of(&name, &stem) { + files.files.insert(ext, data); + } + } + files + } + + /// Picks the files of the database whose `.cbh` member is `cbh_name` from archive + /// members (`name`, bytes). + pub fn from_members<'a>( + cbh_name: &str, + members: impl IntoIterator, + ) -> Files { + let stem = stem_of(cbh_name).to_owned(); + let mut files = Files { + name: stem.rsplit('/').next().unwrap_or(&stem).to_owned(), + files: HashMap::new(), + }; + for (name, data) in members { + if let Some(ext) = part_of(name, &stem) { + files.files.insert(ext, data.to_vec()); + } + } + files + } + + fn get(&self, ext: &str) -> Option<&[u8]> { + self.files.get(ext).map(Vec::as_slice) + } + + fn required(&self, ext: &str) -> Result<&[u8], ImportError> { + self.get(ext).ok_or_else(|| { + ImportError::Corrupt(format!( + "ChessBase database {}: the .{ext} file is missing", + self.name + )) + }) + } +} + +/// Files the reader uses; the others (search boosters, settings, media) are ignored. +pub const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"]; + +/// The files a database cannot be read without (the others hold names and comments). +pub const REQUIRED: [&str; 2] = ["cbh", "cbg"]; + +/// The extension of `name` when it is a file of the database `stem` the reader uses +/// (names differ in case in sets copied from Windows: "Base.CBH", "base.cbg"). +fn part_of(name: &str, stem: &str) -> Option { + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())?; + (stem_of(name).to_lowercase() == stem.to_lowercase() && USED.contains(&ext.as_str())) + .then_some(ext) +} + +fn stem_of(name: &str) -> &str { + name.rsplit_once('.').map_or(name, |(s, _)| s) +} + +/// Result of converting one database. +#[derive(Clone, Debug, Default)] +pub struct Conversion { + /// UTF-8 PGN text, games and guiding texts in game id order. + pub pgn: String, + pub games: usize, + pub texts: usize, + /// Single-byte code page of the database's texts (UTF-8 texts are recognized + /// individually). + pub encoding: Option, + /// Problems worth showing to the user, one line each. + pub notes: Vec, +} + +/// Converts a database to PGN. Games that cannot be decoded completely are kept up +/// to the last readable move and reported in the notes. +pub fn convert(files: &Files) -> Result { + let cbh = files.required("cbh")?; + let cbg = files.required("cbg")?; + let cba = files.get("cba").unwrap_or(&[]); + let records = headers::read(cbh)?; + let players = entities::read(files.get("cbp"), entities::Kind::Player); + let tournaments = entities::read(files.get("cbt"), entities::Kind::Tournament); + let annotators = entities::read(files.get("cbc"), entities::Kind::Annotator); + + // One code page for the whole database, detected from all its single-byte texts. + let mut sample = Vec::new(); + for e in [&players, &tournaments, &annotators] { + e.sample(&mut sample); + } + annotations::sample_texts(cba, &records, &mut sample); + let encoding = text::detect(&sample); + let decoder = text::Decoder::new(encoding); + + let mut out = Conversion { + encoding: Some(encoding), + ..Conversion::default() + }; + let mut problems = Problems::default(); + for (id, rec) in records.iter().enumerate() { + let game_id = id + 1; + match rec { + headers::Record::Game(h) => { + let tags = writer::tags(h, &players, &tournaments, &annotators, &decoder); + let decoded = moves::decode(cbg, h.moves_offset); + let (tree, error) = match decoded { + Ok(t) => (t, None), + Err(moves::DecodeError { partial, reason }) => (partial, Some(reason)), + }; + if let Some(reason) = &error { + problems.add(game_id, &tags, reason); + } + let notes = if h.annotations_offset > 0 { + annotations::read(cba, h.annotations_offset, game_id, &decoder) + } else { + Ok(annotations::Annotations::default()) + }; + let notes = notes.unwrap_or_else(|reason| { + problems.add(game_id, &tags, &reason); + annotations::Annotations::default() + }); + writer::game(&mut out.pgn, &tags, &tree, ¬es, h.result_tag()); + out.games += 1; + } + headers::Record::Text(t) => match text::guiding_text(cbg, t.text_offset, &decoder) { + Ok(body) => { + let mut tags = + writer::text_tags(t, &body.title, &tournaments, &annotators, &decoder); + // The PGN of the library knows a guiding text by this tag (§9.4). + tags.push((crate::pgn_catalog::TEXT_TAG.into(), "1".into())); + writer::text_game(&mut out.pgn, &tags, &body.text); + out.texts += 1; + } + Err(reason) => problems.add(game_id, &[], &reason), + }, + headers::Record::Deleted => {} + } + } + out.notes = problems.into_notes(); + Ok(out) +} + +/// Collects per-game problems; reports each kind once with the number of games. +#[derive(Default)] +struct Problems { + by_reason: Vec<(String, Vec)>, +} + +impl Problems { + fn add(&mut self, game_id: usize, tags: &[(String, String)], reason: &str) { + let tag = |k: &str| { + tags.iter() + .find(|(n, _)| n == k) + .map(|(_, v)| v.as_str()) + .unwrap_or("?") + }; + let who = if tags.is_empty() { + format!("#{game_id}") + } else { + format!("#{game_id} {} – {}", tag("White"), tag("Black")) + }; + match self.by_reason.iter_mut().find(|(r, _)| r == reason) { + Some((_, games)) => games.push(who), + None => self.by_reason.push((reason.to_owned(), vec![who])), + } + } + + fn into_notes(self) -> Vec { + self.by_reason + .into_iter() + .map(|(reason, games)| { + let shown: Vec<&str> = games.iter().take(5).map(String::as_str).collect(); + let more = if games.len() > 5 { + format!(" (+{})", games.len() - 5) + } else { + String::new() + }; + format!("{reason}: {}{more}", shown.join("; ")) + }) + .collect() + } +} + +/// Big-endian unsigned integer of `n` bytes at `at`. +fn be(bytes: &[u8], at: usize, n: usize) -> Option { + let s = bytes.get(at..at + n)?; + Some(s.iter().fold(0u32, |acc, b| (acc << 8) | u32::from(*b))) +} + +/// Little-endian signed 32-bit integer at `at`. +fn le_i32(bytes: &[u8], at: usize) -> Option { + let s = bytes.get(at..at + 4)?; + Some(i32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn members_whose_names_differ_in_case_belong_to_the_database() { + let members = [ + ("Base.CBH", &b"h"[..]), + ("base.cbg", &b"g"[..]), + ("BASE.Cba", &b"a"[..]), + ("Other.cbg", &b"x"[..]), + ]; + let files = Files::from_members("Base.CBH", members); + assert_eq!(files.get("cbh"), Some(&b"h"[..])); + assert_eq!(files.get("cbg"), Some(&b"g"[..])); + assert_eq!(files.get("cba"), Some(&b"a"[..])); + assert_eq!(files.files.len(), 3); + } +} diff --git a/crates/chess-import/src/chessbase/moves.rs b/crates/chess-import/src/chessbase/moves.rs new file mode 100644 index 0000000..40e46c7 --- /dev/null +++ b/crates/chess-import/src/chessbase/moves.rs @@ -0,0 +1,1250 @@ +//! `.cbg` game records: the start position and the move tree. +//! +//! Every byte of the move stream goes through a per-mode permutation together with +//! the number of moves decoded so far. The compact encoder then names a piece by +//! its index among the pieces of its kind (in the order they were found on the start +//! board) and gives a displacement modulo 8; the simple encoder stores squares. + +use shakmaty::fen::Fen; +use shakmaty::san::SanPlus; +use shakmaty::{ + Bitboard, CastlingMode, CastlingSide, Chess, Color, EnPassantMode, File, FromSetup, Move, + Piece, Position, Rank, Role, Setup, Square, +}; + +use super::be; + +/// The decoded move tree of one game. +#[derive(Clone, Debug, Default)] +pub struct Tree { + /// FEN of the start position when it is not the usual one. + pub start_fen: Option, + /// `nodes[0]` is the start; every other node is a move. + pub nodes: Vec, + /// Node of each move in stored order (the annotation position numbering). + pub order: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct Node { + /// SAN with check marks, or `--` for a null move. + pub san: String, + /// Move number and whether white made the move. + pub number: u32, + pub white: bool, + /// The first child is the main continuation. + pub children: Vec, +} + +impl Tree { + /// The start node alone: a game without moves. + pub fn start() -> Tree { + Tree { + nodes: vec![Node::default()], + ..Tree::default() + } + } +} + +/// A game that could only be read in part. +pub struct DecodeError { + pub partial: Tree, + pub reason: String, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Encoder { + Compact, + Simple, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Modifier { + Pre, + Post, +} + +pub fn decode(cbg: &[u8], offset: u32) -> Result { + let r = open_record(cbg, offset).map_err(|e| DecodeError { + // The game is kept with its tags and no moves. + partial: Tree::start(), + reason: e.reason().to_owned(), + })?; + let start_fen = r + .setup + .then(|| Fen::from_position(&r.start, EnPassantMode::Legal).to_string()); + let mut d = Decoder { + tree: Tree { + start_fen, + nodes: vec![Node::default()], + order: Vec::new(), + }, + table: r.table, + modifier: r.modifier, + count: 0, + }; + let result = match r.encoder { + Encoder::Compact => d.compact(r.body, r.start), + Encoder::Simple => d.simple(r.body, r.start), + }; + match result { + Ok(()) => Ok(d.tree), + Err(reason) => Err(DecodeError { + partial: d.tree, + reason, + }), + } +} + +/// Why a record's main line could not be walked. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WalkError { + /// A variant the reader does not support (Chess960, losing chess), or a record + /// outside the file: a retry cannot help. + Unsupported(String), + /// Damaged or untrusted moves. + Moves(String), +} + +impl WalkError { + pub fn reason(&self) -> &str { + match self { + WalkError::Unsupported(r) | WalkError::Moves(r) => r, + } + } +} + +/// A `.cbg` game record with its encoding settled and its start position read. +struct GameRecord<'a> { + encoder: Encoder, + modifier: Modifier, + table: &'static [u8; 256], + /// The move stream. + body: &'a [u8], + start: Chess, + /// The start position is set (flag 0x40), not the usual one. + setup: bool, +} + +fn open_record(cbg: &[u8], offset: u32) -> Result, WalkError> { + let unsupported = |reason: &str| WalkError::Unsupported(reason.into()); + let at = offset as usize; + let (Some(flags), Some(size)) = (cbg.get(at).copied(), be(cbg, at + 1, 3)) else { + return Err(unsupported("moves outside the .cbg file")); + }; + let record = cbg + .get(at..at + size as usize) + .filter(|r| r.len() >= 4) + .ok_or_else(|| unsupported("moves outside the .cbg file"))?; + let mode = flags & 0x3f; + let (encoder, modifier, table) = match mode { + 0 => (Encoder::Compact, Modifier::Pre, &TABLE_0), + 4 => (Encoder::Compact, Modifier::Post, &TABLE_4), + 5 => (Encoder::Simple, Modifier::Post, &TABLE_5), + 10 | 11 => return Err(unsupported("Chess960 games are not supported")), + 8 | 9 => return Err(unsupported("losing chess games are not supported")), + m => return Err(unsupported(&format!("move encoding {m} is not supported"))), + }; + let mut body = &record[4..]; + let setup = flags & 0x40 != 0; + let start = if setup { + let s = body + .get(..28) + .ok_or_else(|| WalkError::Moves("truncated start position".into()))?; + body = &body[28..]; + start_position(s).ok_or_else(|| WalkError::Moves("invalid start position".into()))? + } else { + Chess::default() + }; + Ok(GameRecord { + encoder, + modifier, + table, + body, + start, + setup, + }) +} + +/// A step of a main line, as given to the [`main_line`] callback. +#[derive(Clone, Copy, Debug)] +pub enum Step<'a> { + /// The move played from the position. + Move(&'a Move), + /// A null move (`--`) played from the position. + Null, + /// The main line ends in the position. + End, +} + +/// Walks the main line of the game record at `offset` without building a tree: +/// `f(position, step)` is called for the start position and after every move, the +/// last call with [`Step::End`]; `f` returns false to stop early. +/// +/// The main line ends at the first end-of-variation marker (all variations are +/// stored after it), so variations are never read. `fast` builds each move from the +/// board instead of looking it up among the legal moves (about three times faster); +/// the data is then trusted beyond basic checks, so a [`WalkError::Moves`] in that +/// mode is worth a retry without it. +pub fn main_line(cbg: &[u8], offset: u32, fast: bool, mut f: F) -> Result<(), WalkError> +where + F: FnMut(&Chess, Step<'_>) -> bool, +{ + let r = open_record(cbg, offset)?; + let mut walk = Walk { + table: r.table, + modifier: r.modifier, + count: 0, + fast, + }; + let mut state = State::new(r.start); + let end = match r.encoder { + Encoder::Compact => walk.compact(r.body, &mut state, &mut f), + Encoder::Simple => walk.simple(r.body, &mut state, &mut f), + } + .map_err(WalkError::Moves)?; + if end { + f(&state.pos, Step::End); + } + Ok(()) +} + +/// Main-line decoding state: the byte translation and how moves are found. +struct Walk { + table: &'static [u8; 256], + modifier: Modifier, + count: u32, + fast: bool, +} + +impl Walk { + /// Ok(true) when the main line was read to its end, Ok(false) when `f` stopped. + fn compact(&mut self, data: &[u8], state: &mut State, f: &mut F) -> Result + where + F: FnMut(&Chess, Step<'_>) -> bool, + { + let mut i = 0; + while i < data.len() { + let raw = translate(self.table, self.modifier, self.count, data[i]); + i += 1; + let code = classify(raw).ok_or_else(|| format!("unknown move code {raw}"))?; + let m = match code { + // A variation starts after the main line: nothing to save. + Code::Push | Code::Ignore => continue, + Code::Pop => return Ok(true), + Code::Null => None, + Code::TwoBytes => { + let (Some(&a), Some(&b)) = (data.get(i), data.get(i + 1)) else { + return Err("truncated move".into()); + }; + i += 2; + let t = |x| u16::from(translate(self.table, self.modifier, self.count, x)); + Some(self.square_move(&state.pos, (t(a) << 8) | t(b))?) + } + Code::Castle { short } => Some(if self.fast { + fast_castle(&state.pos, short)? + } else { + castle(&state.pos, short)? + }), + Code::Piece(role, index, delta) => { + let from = piece_square(&state.sides[state.pos.turn() as usize], role, index) + .ok_or("move of a piece that is not on the board")?; + Some(self.find(&state.pos, from, displaced(from, delta), None)?) + } + Code::Pawn(index, kind) => { + let from = state.sides[state.pos.turn() as usize].pawns[index] + .ok_or("move of a pawn that is not on the board")?; + let delta = pawn_step(kind, state.pos.turn()); + Some(self.find(&state.pos, from, displaced(from, delta), None)?) + } + }; + if !self.play(state, m, f)? { + return Ok(false); + } + } + Ok(true) + } + + fn simple(&mut self, data: &[u8], state: &mut State, f: &mut F) -> Result + where + F: FnMut(&Chess, Step<'_>) -> bool, + { + for pair in data.as_chunks::<2>().0 { + let t = |x| u16::from(translate(self.table, self.modifier, self.count, x)); + let v = (t(pair[0]) << 8) | t(pair[1]); + let m = if (v & 63) == ((v >> 6) & 63) { + None + } else { + Some(self.square_move(&state.pos, v & 0x3fff)?) + }; + if !self.play(state, m, f)? { + return Ok(false); + } + // The move that closes a line is the last of the main line. + if v & 0x4000 != 0 { + return Ok(true); + } + } + Ok(true) + } + + /// Reports the move to `f` and plays it; Ok(false) when `f` stops. + fn play(&mut self, state: &mut State, m: Option, f: &mut F) -> Result + where + F: FnMut(&Chess, Step<'_>) -> bool, + { + let step = match &m { + Some(m) => Step::Move(m), + None => Step::Null, + }; + if !f(&state.pos, step) { + return Ok(false); + } + match m { + Some(m) => { + state.track(&m); + state.pos.play_unchecked(m); + } + None => state.pos = null_move(&state.pos).ok_or("null move while in check")?, + } + self.count += 1; + Ok(true) + } + + fn square_move(&self, pos: &Chess, v: u16) -> Result { + let (from, to, promotion) = square_fields(v); + self.find(pos, from, to, Some(promotion)) + } + + fn find( + &self, + pos: &Chess, + from: Square, + to: Square, + promotion: Option, + ) -> Result { + if self.fast { + build_move(pos, from, to, promotion) + } else { + find_move(pos, from, to, promotion) + } + } +} + +/// The move from `from` to `to` built from the board, without legal move generation: +/// the piece on `from` must be ours and `to` must not hold one of ours or a king. A +/// pawn going diagonally to an empty square takes en passant; a pawn reaching the +/// last rank becomes `promotion` (a queen if not given); a king going two files +/// castles. +fn build_move( + pos: &Chess, + from: Square, + to: Square, + promotion: Option, +) -> Result { + let board = pos.board(); + let us = pos.turn(); + let piece = board + .piece_at(from) + .filter(|p| p.color == us) + .ok_or("move of a piece that is not on the board")?; + let target = board.piece_at(to); + if target.is_some_and(|t| t.color == us || t.role == Role::King) { + return Err("illegal move".into()); + } + let capture = target.map(|t| t.role); + Ok(match piece.role { + Role::Pawn if from.file() != to.file() && target.is_none() => Move::EnPassant { from, to }, + Role::Pawn => { + let last = if us == Color::White { + Rank::Eighth + } else { + Rank::First + }; + Move::Normal { + role: Role::Pawn, + from, + capture, + to, + promotion: (to.rank() == last).then(|| promotion.unwrap_or(Role::Queen)), + } + } + Role::King if from.rank() == to.rank() && from.file().distance(to.file()) == 2 => { + fast_castle(pos, to.file() > from.file())? + } + role => Move::Normal { + role, + from, + capture, + to, + promotion: None, + }, + }) +} + +/// Castling from the castling rights, without legal move generation. +fn fast_castle(pos: &Chess, short: bool) -> Result { + let us = pos.turn(); + let side = if short { + CastlingSide::KingSide + } else { + CastlingSide::QueenSide + }; + match (pos.castles().rook(us, side), pos.board().king_of(us)) { + (Some(rook), Some(king)) => Ok(Move::Castle { king, rook }), + _ => Err("illegal castling".into()), + } +} + +/// The 28-byte start position: marker, en passant file and side to move, castling +/// rights, move number, then 192 bits of board, square by square from a1, a2, … h8. +fn start_position(s: &[u8]) -> Option { + let mut setup = Setup::empty(); + let mut bits = BitReader { + data: &s[4..], + pos: 0, + }; + for idx in 0..64 { + if bits.read(1)? == 0 { + continue; + } + let color = if bits.read(1)? == 0 { + Color::White + } else { + Color::Black + }; + let role = match bits.read(3)? { + 1 => Role::King, + 2 => Role::Queen, + 3 => Role::Knight, + 4 => Role::Bishop, + 5 => Role::Rook, + 6 => Role::Pawn, + _ => return None, + }; + setup + .board + .set_piece_at(cb_square(idx), Piece { color, role }); + } + setup.turn = if s[1] & 0x10 != 0 { + Color::Black + } else { + Color::White + }; + let mut rights = Bitboard::EMPTY; + for (bit, sq) in [ + (0, Square::A1), + (1, Square::H1), + (2, Square::A8), + (3, Square::H8), + ] { + if s[2] & (1 << bit) != 0 { + rights.add(sq); + } + } + setup.castling_rights = rights; + let ep = u32::from(s[1] & 0x0f); + if (1..=8).contains(&ep) { + let rank = if setup.turn == Color::White { + Rank::Sixth + } else { + Rank::Third + }; + setup.ep_square = Some(Square::from_coords(File::new(ep - 1), rank)); + } + setup.fullmoves = std::num::NonZeroU32::new(u32::from(s[3]).max(1))?; + // Positions with doubtful castling rights or en passant squares are still usable. + let pos = match Chess::from_setup(setup, CastlingMode::Standard) { + Ok(p) => p, + Err(e) => match e.ignore_invalid_castling_rights() { + Ok(p) => p, + Err(e) => e.ignore_invalid_ep_square().ok()?, + }, + }; + Some(pos) +} + +/// ChessBase numbers squares file by file: a1 = 0, a2 = 1, … h8 = 63. +fn cb_square(idx: u32) -> Square { + Square::from_coords(File::new(idx / 8), Rank::new(idx % 8)) +} + +struct BitReader<'a> { + data: &'a [u8], + pos: usize, +} + +impl BitReader<'_> { + fn read(&mut self, n: usize) -> Option { + let mut v = 0; + for _ in 0..n { + let byte = *self.data.get(self.pos / 8)?; + v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1); + self.pos += 1; + } + Some(v) + } +} + +/// Which square each piece of a side is on, in ChessBase's numbering. +#[derive(Clone, Default)] +struct Side { + king: Option, + queens: Vec, + rooks: Vec, + bishops: Vec, + knights: Vec, + /// Pawns keep their number for the whole game; a captured pawn leaves a gap. + pawns: [Option; 8], +} + +#[derive(Clone)] +struct State { + pos: Chess, + sides: [Side; 2], + node: usize, +} + +impl State { + fn new(pos: Chess) -> State { + let mut sides: [Side; 2] = Default::default(); + let mut pawn_count = [0usize; 2]; + for idx in 0..64 { + let sq = cb_square(idx); + let Some(p) = pos.board().piece_at(sq) else { + continue; + }; + let c = p.color as usize; + let s = &mut sides[c]; + match p.role { + Role::King => s.king = Some(sq), + Role::Queen => s.queens.push(sq), + Role::Rook => s.rooks.push(sq), + Role::Bishop => s.bishops.push(sq), + Role::Knight => s.knights.push(sq), + Role::Pawn => { + if let Some(slot) = s.pawns.get_mut(pawn_count[c]) { + *slot = Some(sq); + } + pawn_count[c] += 1; + } + } + } + State { + pos, + sides, + node: 0, + } + } + + fn side(&mut self, c: Color) -> &mut Side { + &mut self.sides[c as usize] + } + + /// Keeps the piece lists in step with a move about to be played. + fn track(&mut self, m: &Move) { + let us = self.pos.turn(); + match *m { + Move::Normal { + from, + to, + capture, + promotion, + .. + } => { + if capture.is_some() { + self.side(!us).remove(to); + } + self.side(us).relocate(from, to); + if let Some(role) = promotion { + let s = self.side(us); + s.remove(to); + s.list(role).push(to); + } + } + Move::EnPassant { from, to } => { + self.side(!us) + .remove(Square::from_coords(to.file(), from.rank())); + self.side(us).relocate(from, to); + } + Move::Castle { king, rook } => { + let short = rook.file() > king.file(); + let rank = king.rank(); + let (k, r) = if short { + (File::G, File::F) + } else { + (File::C, File::D) + }; + let s = self.side(us); + s.relocate(rook, Square::from_coords(r, rank)); + s.relocate(king, Square::from_coords(k, rank)); + } + Move::Put { .. } => {} + } + } +} + +impl Side { + fn list(&mut self, role: Role) -> &mut Vec { + match role { + Role::Queen => &mut self.queens, + Role::Rook => &mut self.rooks, + Role::Bishop => &mut self.bishops, + _ => &mut self.knights, + } + } + + /// A captured piece: later pieces of its kind move down one; a pawn leaves a gap. + fn remove(&mut self, sq: Square) { + for list in [ + &mut self.queens, + &mut self.rooks, + &mut self.bishops, + &mut self.knights, + ] { + if let Some(i) = list.iter().position(|s| *s == sq) { + list.remove(i); + return; + } + } + for p in &mut self.pawns { + if *p == Some(sq) { + *p = None; + return; + } + } + } + + fn relocate(&mut self, from: Square, to: Square) { + if self.king == Some(from) { + self.king = Some(to); + return; + } + for list in [ + &mut self.queens, + &mut self.rooks, + &mut self.bishops, + &mut self.knights, + ] { + if let Some(s) = list.iter_mut().find(|s| **s == from) { + *s = to; + return; + } + } + for p in self.pawns.iter_mut().flatten() { + if *p == from { + *p = to; + return; + } + } + } +} + +struct Decoder { + tree: Tree, + table: &'static [u8; 256], + modifier: Modifier, + /// Moves decoded so far, variations and null moves included. + count: u32, +} + +/// What a byte of the compact encoder asks for. +enum Code { + Null, + /// Piece kind, its index, displacement. + Piece(Role, usize, (i32, i32)), + Pawn(usize, u8), + Castle { + short: bool, + }, + TwoBytes, + Ignore, + Push, + Pop, +} + +const KING: [(i32, i32); 8] = [ + (0, 1), + (1, 1), + (1, 0), + (1, -1), + (0, -1), + (-1, -1), + (-1, 0), + (-1, 1), +]; +const KNIGHT: [(i32, i32); 8] = [ + (2, 1), + (1, 2), + (-1, 2), + (-2, 1), + (-2, -1), + (-1, -2), + (1, -2), + (2, -1), +]; + +/// Displacement of the `i`-th step of a line piece: groups of 7 steps in the +/// directions `dirs`. +fn line_step(i: usize, dirs: &[(i32, i32)]) -> (i32, i32) { + let (dx, dy) = dirs[i / 7]; + let n = (i % 7 + 1) as i32; + (dx * n, dy * n) +} + +const QUEEN_DIRS: [(i32, i32); 4] = [(0, 1), (1, 0), (1, 1), (1, -1)]; +const ROOK_DIRS: [(i32, i32); 2] = [(0, 1), (1, 0)]; +const BISHOP_DIRS: [(i32, i32); 2] = [(1, 1), (1, -1)]; + +fn classify(code: u8) -> Option { + let c = usize::from(code); + Some(match c { + 0 => Code::Null, + 1..=8 => Code::Piece(Role::King, 0, KING[c - 1]), + 9 => Code::Castle { short: true }, + 10 => Code::Castle { short: false }, + 11..=38 => Code::Piece(Role::Queen, 0, line_step(c - 11, &QUEEN_DIRS)), + 39..=52 => Code::Piece(Role::Rook, 0, line_step(c - 39, &ROOK_DIRS)), + 53..=66 => Code::Piece(Role::Rook, 1, line_step(c - 53, &ROOK_DIRS)), + 67..=80 => Code::Piece(Role::Bishop, 0, line_step(c - 67, &BISHOP_DIRS)), + 81..=94 => Code::Piece(Role::Bishop, 1, line_step(c - 81, &BISHOP_DIRS)), + 95..=102 => Code::Piece(Role::Knight, 0, KNIGHT[c - 95]), + 103..=110 => Code::Piece(Role::Knight, 1, KNIGHT[c - 103]), + 111..=142 => Code::Pawn((c - 111) / 4, ((c - 111) % 4) as u8), + 143..=170 => Code::Piece(Role::Queen, 1, line_step(c - 143, &QUEEN_DIRS)), + 171..=198 => Code::Piece(Role::Queen, 2, line_step(c - 171, &QUEEN_DIRS)), + 199..=212 => Code::Piece(Role::Rook, 2, line_step(c - 199, &ROOK_DIRS)), + 213..=226 => Code::Piece(Role::Bishop, 2, line_step(c - 213, &BISHOP_DIRS)), + 227..=234 => Code::Piece(Role::Knight, 2, KNIGHT[c - 227]), + 235 => Code::TwoBytes, + 236 => Code::Ignore, + 254 => Code::Push, + 255 => Code::Pop, + _ => return None, + }) +} + +/// A byte of the move stream after `count` moves, through the mode's permutation. +fn translate(table: &[u8; 256], modifier: Modifier, count: u32, byte: u8) -> u8 { + let n = (count % 256) as u8; + match modifier { + Modifier::Pre => table[usize::from(byte.wrapping_sub(n))], + Modifier::Post => table[usize::from(byte)].wrapping_sub(n), + } +} + +/// Square of the `index`-th piece of a kind. +fn piece_square(side: &Side, role: Role, index: usize) -> Option { + match role { + Role::King => side.king, + Role::Queen => side.queens.get(index).copied(), + Role::Rook => side.rooks.get(index).copied(), + Role::Bishop => side.bishops.get(index).copied(), + _ => side.knights.get(index).copied(), + } +} + +/// Displacement of a pawn move of the compact encoder: 0 one step, 1 two steps, 2 +/// and 3 captures. +fn pawn_step(kind: u8, turn: Color) -> (i32, i32) { + match (kind, turn == Color::White) { + (0, true) => (0, 1), + (1, true) => (0, 2), + (2, true) => (1, 1), + (_, true) => (-1, 1), + (0, false) => (0, -1), + (1, false) => (0, -2), + (2, false) => (-1, -1), + (_, false) => (1, -1), + } +} + +impl Decoder { + fn translate(&self, byte: u8) -> u8 { + translate(self.table, self.modifier, self.count, byte) + } + + fn compact(&mut self, data: &[u8], start: Chess) -> Result<(), String> { + let mut state = State::new(start); + let mut stack: Vec = Vec::new(); + let mut i = 0; + while i < data.len() { + let raw = self.translate(data[i]); + i += 1; + let code = classify(raw).ok_or_else(|| format!("unknown move code {raw}"))?; + let m = match code { + Code::Push => { + stack.push(state.clone()); + continue; + } + Code::Pop => match stack.pop() { + Some(s) => { + state = s; + continue; + } + None => return Ok(()), + }, + Code::Ignore => continue, + Code::Null => None, + Code::TwoBytes => { + let (Some(&a), Some(&b)) = (data.get(i), data.get(i + 1)) else { + return Err("truncated move".into()); + }; + i += 2; + let v = (u16::from(self.translate(a)) << 8) | u16::from(self.translate(b)); + Some(square_move(&state.pos, v)?) + } + Code::Castle { short } => Some(castle(&state.pos, short)?), + Code::Piece(role, index, delta) => { + let from = piece_square(&state.sides[state.pos.turn() as usize], role, index) + .ok_or("move of a piece that is not on the board")?; + Some(find_move(&state.pos, from, displaced(from, delta), None)?) + } + Code::Pawn(index, kind) => { + let from = state.sides[state.pos.turn() as usize].pawns[index] + .ok_or("move of a pawn that is not on the board")?; + let delta = pawn_step(kind, state.pos.turn()); + Some(find_move(&state.pos, from, displaced(from, delta), None)?) + } + }; + self.play(&mut state, m)?; + } + // A stream without its final end marker: keep what was read. + Ok(()) + } + + fn simple(&mut self, data: &[u8], start: Chess) -> Result<(), String> { + let mut state = State::new(start); + let mut stack: Vec = Vec::new(); + for pair in data.as_chunks::<2>().0 { + let v = (u16::from(self.translate(pair[0])) << 8) | u16::from(self.translate(pair[1])); + if v & 0x8000 != 0 { + stack.push(state.clone()); + } + // A move from a square to itself is a null move. + let m = if (v & 63) == ((v >> 6) & 63) { + None + } else { + Some(square_move(&state.pos, v & 0x3fff)?) + }; + self.play(&mut state, m)?; + if v & 0x4000 != 0 { + match stack.pop() { + Some(s) => state = s, + None => return Ok(()), + } + } + } + Ok(()) + } + + /// Adds the move (`None` = null move) as a child of the current node and plays it. + fn play(&mut self, state: &mut State, m: Option) -> Result<(), String> { + let pos = &state.pos; + let node = Node { + san: match m { + Some(m) => SanPlus::from_move(pos.clone(), m).to_string(), + None => "--".into(), + }, + number: pos.fullmoves().get(), + white: pos.turn() == Color::White, + children: Vec::new(), + }; + let next = match m { + Some(m) => { + state.track(&m); + let mut p = state.pos.clone(); + p.play_unchecked(m); + p + } + None => null_move(&state.pos).ok_or("null move while in check")?, + }; + let id = self.tree.nodes.len(); + self.tree.nodes.push(node); + self.tree.nodes[state.node].children.push(id); + self.tree.order.push(id); + state.node = id; + state.pos = next; + self.count += 1; + Ok(()) + } +} + +fn displaced(from: Square, (dx, dy): (i32, i32)) -> Square { + let x = (from.file() as i32 + dx).rem_euclid(8) as u32; + let y = (from.rank() as i32 + dy).rem_euclid(8) as u32; + Square::from_coords(File::new(x), Rank::new(y)) +} + +/// Move given by squares: bits 0-5 from, 6-11 to, 12-13 promotion piece. +fn square_move(pos: &Chess, v: u16) -> Result { + let (from, to, promotion) = square_fields(v); + find_move(pos, from, to, Some(promotion)) +} + +fn square_fields(v: u16) -> (Square, Square, Role) { + let from = cb_square(u32::from(v & 63)); + let to = cb_square(u32::from((v >> 6) & 63)); + let promotion = + [Role::Queen, Role::Rook, Role::Bishop, Role::Knight][usize::from((v >> 12) & 3)]; + (from, to, promotion) +} + +/// The legal move from `from` to `to` (the king's destination for castling); a +/// promotion takes `promotion`, or a queen. +fn find_move( + pos: &Chess, + from: Square, + to: Square, + promotion: Option, +) -> Result { + let wanted = promotion.unwrap_or(Role::Queen); + pos.legal_moves() + .into_iter() + .find(|m| { + m.from() == Some(from) + && king_target(m) == to + && m.promotion().is_none_or(|p| p == wanted) + }) + .ok_or_else(|| "illegal move".to_owned()) +} + +fn castle(pos: &Chess, short: bool) -> Result { + pos.legal_moves() + .into_iter() + .find(|m| matches!(m, Move::Castle { king, rook } if (rook.file() > king.file()) == short)) + .ok_or_else(|| "illegal castling".to_owned()) +} + +/// Destination as a player sees it: castling goes to the g or c file. +fn king_target(m: &Move) -> Square { + match *m { + Move::Castle { king, rook } => { + let file = if rook.file() > king.file() { + File::G + } else { + File::C + }; + Square::from_coords(file, king.rank()) + } + _ => m.to(), + } +} + +/// Teaching null move: the side to move passes (as `--` in PGN). +fn null_move(pos: &Chess) -> Option { + if pos.is_check() { + return None; + } + let mut setup = pos.to_setup(EnPassantMode::Legal); + let was_black = setup.turn == Color::Black; + setup.swap_turn(); + setup.ep_square = None; + setup.halfmoves = setup.halfmoves.saturating_add(1); + if was_black { + setup.fullmoves = setup.fullmoves.saturating_add(1); + } + Chess::from_setup(setup, CastlingMode::Standard).ok() +} + +const TABLE_0: [u8; 256] = [ + 0xa2, 0x95, 0x43, 0xf5, 0xc1, 0x3d, 0x4a, 0x6c, 0x53, 0x83, 0xcc, 0x7c, 0xff, 0xae, 0x68, 0xad, + 0xd1, 0x92, 0x8b, 0x8d, 0x35, 0x81, 0x5e, 0x74, 0x26, 0x8e, 0xab, 0xca, 0xfd, 0x9a, 0xf3, 0xa0, + 0xa5, 0x15, 0xfc, 0xb1, 0x1e, 0xed, 0x30, 0xea, 0x22, 0xeb, 0xa7, 0xcd, 0x4e, 0x6f, 0x2e, 0x24, + 0x32, 0x94, 0x41, 0x8c, 0x6e, 0x58, 0x82, 0x50, 0xbb, 0x02, 0x8a, 0xd8, 0xfa, 0x60, 0xde, 0x52, + 0xba, 0x46, 0xac, 0x29, 0x9d, 0xd7, 0xdf, 0x08, 0x21, 0x01, 0x66, 0xa3, 0xf1, 0x19, 0x27, 0xb5, + 0x91, 0xd5, 0x42, 0x0e, 0xb4, 0x4c, 0xd9, 0x18, 0x5f, 0xbc, 0x25, 0xa6, 0x96, 0x04, 0x56, 0x6a, + 0xaa, 0x33, 0x1c, 0x2b, 0x73, 0xf0, 0xdd, 0xa4, 0x37, 0xd3, 0xc5, 0x10, 0xbf, 0x5a, 0x23, 0x34, + 0x75, 0x5b, 0xb8, 0x55, 0xd2, 0x6b, 0x09, 0x3a, 0x57, 0x12, 0xb3, 0x77, 0x48, 0x85, 0x9b, 0x0f, + 0x9e, 0xc7, 0xc8, 0xa1, 0x7f, 0x7a, 0xc0, 0xbd, 0x31, 0x6d, 0xf6, 0x3e, 0xc3, 0x11, 0x71, 0xce, + 0x7d, 0xda, 0xa8, 0x54, 0x90, 0x97, 0x1f, 0x44, 0x40, 0x16, 0xc9, 0xe3, 0x2c, 0xcb, 0x84, 0xec, + 0x9f, 0x3f, 0x5c, 0xe6, 0x76, 0x0b, 0x3c, 0x20, 0xb7, 0x36, 0x00, 0xdc, 0xe7, 0xf9, 0x4f, 0xf7, + 0xaf, 0x06, 0x07, 0xe0, 0x1a, 0x0a, 0xa9, 0x4b, 0x0c, 0xd6, 0x63, 0x87, 0x89, 0x1d, 0x13, 0x1b, + 0xe4, 0x70, 0x05, 0x47, 0x67, 0x7b, 0x2f, 0xee, 0xe2, 0xe8, 0x98, 0x0d, 0xef, 0xcf, 0xc4, 0xf4, + 0xfb, 0xb0, 0x17, 0x99, 0x64, 0xf2, 0xd4, 0x2a, 0x03, 0x4d, 0x78, 0xc6, 0xfe, 0x65, 0x86, 0x88, + 0x79, 0x45, 0x3b, 0xe5, 0x49, 0x8f, 0x2d, 0xb9, 0xbe, 0x62, 0x93, 0x14, 0xe9, 0xd0, 0x38, 0x9c, + 0xb2, 0xc2, 0x59, 0x5d, 0xb6, 0x72, 0x51, 0xf8, 0x28, 0x7e, 0x61, 0x39, 0xe1, 0xdb, 0x69, 0x80, +]; + +const TABLE_4: [u8; 256] = [ + 0x58, 0xa3, 0xee, 0x72, 0x47, 0xb9, 0x1f, 0xa0, 0x26, 0xfd, 0xdc, 0x6d, 0xf1, 0xe3, 0xcb, 0xc5, + 0xe2, 0xd0, 0x29, 0xe7, 0x89, 0xe1, 0xae, 0x7b, 0x34, 0x41, 0x35, 0x4b, 0xa5, 0x7c, 0xf6, 0xe5, + 0xdb, 0x8c, 0x5f, 0x37, 0x05, 0xbb, 0x32, 0x54, 0x4c, 0xef, 0x5d, 0x2a, 0x7f, 0xd3, 0x81, 0x86, + 0xdf, 0x18, 0xc3, 0x44, 0x16, 0xf7, 0x85, 0x0f, 0x4d, 0x30, 0x79, 0x14, 0x45, 0xaa, 0xa2, 0x6c, + 0x15, 0x92, 0xa6, 0x62, 0x48, 0x19, 0xe9, 0x3c, 0x38, 0x94, 0x28, 0xa8, 0x66, 0x09, 0x03, 0x63, + 0x20, 0x7d, 0x36, 0xd7, 0x2e, 0x98, 0xec, 0xda, 0x01, 0x13, 0x24, 0x73, 0xcd, 0x9e, 0xcf, 0xd9, + 0xd5, 0x68, 0x8b, 0xd2, 0xab, 0x5b, 0x69, 0xb0, 0x27, 0xfc, 0x31, 0x1b, 0x53, 0x7e, 0x65, 0x76, + 0x55, 0x75, 0xaf, 0x0a, 0xcc, 0xc7, 0xc4, 0xb2, 0xb5, 0x22, 0xe8, 0xa7, 0xbe, 0xf5, 0x00, 0x5a, + 0x21, 0xd1, 0x74, 0x8e, 0xde, 0x9c, 0xe4, 0x42, 0x2b, 0xb1, 0x9b, 0x93, 0xc1, 0x78, 0x70, 0xd6, + 0xb6, 0xad, 0x4e, 0x6a, 0x64, 0x7a, 0x57, 0x49, 0x11, 0x9d, 0x12, 0xc0, 0x3a, 0x2f, 0xe6, 0x84, + 0xc6, 0x07, 0xce, 0x08, 0x82, 0x04, 0x90, 0xb8, 0x87, 0xca, 0x6e, 0x1e, 0x40, 0x1a, 0x50, 0xb4, + 0x10, 0xbc, 0x43, 0x8a, 0x71, 0x0b, 0x8d, 0x5c, 0x3b, 0x3f, 0x88, 0xba, 0xf4, 0xf3, 0x61, 0x1d, + 0xf9, 0xfe, 0x25, 0x51, 0x0d, 0xeb, 0xc8, 0x59, 0x17, 0x46, 0xa4, 0xf2, 0x56, 0xb7, 0x02, 0x2d, + 0x33, 0x9f, 0xd8, 0x83, 0xfb, 0xbf, 0xea, 0xed, 0xac, 0x60, 0x67, 0x39, 0xdd, 0x96, 0x6b, 0xa9, + 0xc2, 0x77, 0x0c, 0x0e, 0x91, 0xfa, 0x99, 0x9a, 0xe0, 0xa1, 0xf0, 0x5e, 0xc9, 0x06, 0x4f, 0xbd, + 0x52, 0x80, 0xd4, 0xf8, 0x97, 0x23, 0x3e, 0x1c, 0x2c, 0x95, 0x4a, 0x8f, 0x3d, 0x6f, 0xff, 0xb3, +]; + +const TABLE_5: [u8; 256] = [ + 0xe0, 0x1b, 0x97, 0x86, 0xa2, 0x48, 0xf0, 0x23, 0x01, 0x37, 0xfa, 0xeb, 0x50, 0x76, 0x5d, 0xcd, + 0x80, 0x1a, 0x31, 0x5c, 0xff, 0xbc, 0x78, 0xda, 0xe5, 0xa3, 0x75, 0xb3, 0x71, 0xe1, 0xa1, 0x0e, + 0x56, 0x41, 0x3f, 0xe3, 0x0d, 0xc4, 0x25, 0xe6, 0x88, 0x89, 0x70, 0xdc, 0x99, 0xa6, 0x0b, 0x9a, + 0x14, 0x2c, 0x57, 0x9e, 0x69, 0x7a, 0xdf, 0x55, 0xad, 0x73, 0x7c, 0xc5, 0x03, 0x72, 0xf5, 0x45, + 0x62, 0x8e, 0xaf, 0x5f, 0xcc, 0xc0, 0x5e, 0xf3, 0x18, 0x13, 0xb5, 0x38, 0x09, 0x28, 0x3c, 0xbd, + 0x10, 0x8b, 0xe9, 0xdd, 0x8c, 0x94, 0x08, 0x81, 0xa7, 0xfe, 0x24, 0x79, 0x44, 0x2b, 0xc1, 0x36, + 0x32, 0x7f, 0x67, 0xe4, 0xfd, 0x49, 0x4b, 0x21, 0xa9, 0x5b, 0x77, 0x1f, 0x1c, 0xf6, 0x40, 0x65, + 0x3d, 0xf9, 0x5a, 0xf8, 0x47, 0x26, 0x53, 0xd4, 0x20, 0xd2, 0xd8, 0x4f, 0x27, 0xae, 0xfb, 0xb6, + 0x9b, 0x74, 0xb8, 0x42, 0xfc, 0x16, 0x6f, 0xd7, 0x9f, 0xb9, 0x7b, 0x60, 0xde, 0xc2, 0x46, 0x06, + 0x9c, 0xd3, 0x2a, 0xc7, 0x05, 0x85, 0x3e, 0xb1, 0x00, 0x15, 0xd1, 0x96, 0xce, 0x90, 0x95, 0x11, + 0x33, 0x8f, 0xc6, 0x82, 0x84, 0xb7, 0x39, 0xa0, 0xe8, 0x34, 0x1e, 0x7d, 0xa8, 0xd0, 0xea, 0xe2, + 0xef, 0x4c, 0xc3, 0x58, 0x4e, 0x02, 0x1d, 0xb2, 0x7e, 0x98, 0x2d, 0x07, 0xd5, 0xca, 0x68, 0xcb, + 0x30, 0xb4, 0xac, 0x83, 0x63, 0xec, 0x87, 0xee, 0x2e, 0xbe, 0xcf, 0x6d, 0x4d, 0x8a, 0xd6, 0x04, + 0xb0, 0x35, 0xc8, 0xc9, 0x12, 0x17, 0x61, 0x8d, 0x64, 0x0f, 0xa5, 0x54, 0x29, 0x3a, 0x4a, 0x6b, + 0xbb, 0x2f, 0xd9, 0x3b, 0x93, 0x6a, 0xaa, 0xa4, 0x22, 0xf4, 0x19, 0x43, 0x6e, 0xf1, 0xf7, 0xdb, + 0x92, 0xed, 0x66, 0x59, 0x0a, 0xbf, 0x6c, 0x51, 0x91, 0x52, 0xf2, 0x0c, 0x9d, 0xab, 0xba, 0xe7, +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tables_are_permutations() { + for t in [&TABLE_0, &TABLE_4, &TABLE_5] { + let mut seen = [false; 256]; + for v in t.iter() { + assert!(!seen[usize::from(*v)]); + seen[usize::from(*v)] = true; + } + } + } + + #[test] + fn start_board_bits() { + // The example from the format description: white pawn a2, black rook b1, + // white knight b4 (bits 0 10110 000000 11101 00 10011), plus both kings. + let mut s = vec![1, 0, 0, 1]; + let mut board = vec![0x58, 0x0e, 0x93]; + board.resize(24, 0); + s.extend(board); + // Kings are needed for a valid position: add them on h1 (white) and h8 (black). + let mut bits: Vec = Vec::new(); + let mut pos = BitReader { + data: &s[4..], + pos: 0, + }; + for _ in 0..24 { + bits.push(pos.read(1).unwrap_or(0) as u8); + } + assert_eq!(bits[..6], [0, 1, 0, 1, 1, 0]); + assert!(start_position(&s).is_none(), "no kings: invalid"); + } + + #[test] + fn displacement_wraps_modulo_8() { + // A queen on c2 moving (+7, 0) reaches b2. + assert_eq!(displaced(Square::C2, (7, 0)), Square::B2); + assert_eq!(displaced(Square::A1, (-1, -1)), Square::H8); + assert_eq!(line_step(7, &QUEEN_DIRS), (1, 0)); + assert_eq!(line_step(13, &QUEEN_DIRS), (7, 0)); + assert_eq!(line_step(27, &QUEEN_DIRS), (7, -7)); + } + + #[test] + fn unreadable_game_keeps_the_start_node() { + // A Chess960 record (mode 10) of 4 bytes: rejected before any move, as in Mega 2026. + let err = decode(&[10, 0, 0, 4], 0).expect_err("Chess960 is not supported"); + assert_eq!(err.partial.nodes.len(), 1); + let mut out = String::new(); + let notes = super::super::annotations::Annotations::default(); + super::super::writer::game(&mut out, &Vec::new(), &err.partial, ¬es, "*"); + assert_eq!(out.trim(), "*"); + } + + #[test] + fn piece_numbering_follows_the_start_board() { + let s = State::new(Chess::default()); + let w = &s.sides[Color::White as usize]; + assert_eq!(w.rooks, vec![Square::A1, Square::H1]); + assert_eq!(w.knights, vec![Square::B1, Square::G1]); + assert_eq!(w.pawns[0], Some(Square::A2)); + assert_eq!(w.pawns[7], Some(Square::H2)); + let b = &s.sides[Color::Black as usize]; + assert_eq!(b.rooks, vec![Square::A8, Square::H8]); + assert_eq!(b.pawns[0], Some(Square::A7)); + } + + /// Main line by [`main_line`]: SAN of every move (`--` for a null move) and + /// the final position. + fn walked(cbg: &[u8], offset: u32, fast: bool) -> Result<(Vec, Chess), WalkError> { + let mut sans = Vec::new(); + let mut end = None; + main_line(cbg, offset, fast, |pos, step| { + match step { + Step::Move(m) => sans.push(SanPlus::from_move(pos.clone(), *m).to_string()), + Step::Null => sans.push("--".into()), + Step::End => end = Some(pos.clone()), + } + true + })?; + Ok((sans, end.expect("the walk reaches the end"))) + } + + /// Main line of a decoded tree: the first children. + fn tree_line(tree: &Tree) -> Vec { + let mut out = Vec::new(); + let mut node = 0; + while let Some(&c) = tree.nodes[node].children.first() { + out.push(tree.nodes[c].san.clone()); + node = c; + } + out + } + + /// A simple-encoder (mode 5) record of moves given as (from, to, flags), flags + /// being 0x8000 (a variation starts) and 0x4000 (a line ends). + fn simple_record(moves: &[(Square, Square, u16)]) -> Vec { + let sq = |s: Square| (s.file() as u16) * 8 + s.rank() as u16; + let encode = |value: u8, count: usize| -> u8 { + let wanted = value.wrapping_add((count % 256) as u8); + TABLE_5.iter().position(|&t| t == wanted).unwrap() as u8 + }; + let mut body = Vec::new(); + for (count, &(from, to, flags)) in moves.iter().enumerate() { + let v = sq(from) | (sq(to) << 6) | flags; + body.push(encode((v >> 8) as u8, count)); + body.push(encode(v as u8, count)); + } + let size = (body.len() + 4) as u32; + let mut rec = vec![5, (size >> 16) as u8, (size >> 8) as u8, size as u8]; + rec.extend(body); + rec + } + + #[test] + fn main_line_stops_before_the_variations() { + use Square::*; + // 1. e4 e5 (1... c5) 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O -- 5. d3, the variation + // stored after the main line; a null move is a move from a square to itself. + let rec = simple_record(&[ + (E2, E4, 0), + (E7, E5, 0x8000), + (G1, F3, 0), + (B8, C6, 0), + (F1, C4, 0), + (G8, F6, 0), + (E1, G1, 0), + (A1, A1, 0), + (D2, D3, 0x4000), + (C7, C5, 0x4000), + ]); + let tree = decode(&rec, 0).ok().expect("decodes"); + let expected = ["e4", "e5", "Nf3", "Nc6", "Bc4", "Nf6", "O-O", "--", "d3"]; + assert_eq!(tree_line(&tree), expected); + assert_eq!(tree.nodes[1].children.len(), 2, "1... c5 is a variation"); + for fast in [true, false] { + let (sans, end) = walked(&rec, 0, fast).expect("walks"); + assert_eq!(sans, expected); + assert_eq!(end.turn(), Color::Black); + assert_eq!( + Fen::from_position(&end, EnPassantMode::Legal).to_string(), + "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/3P1N2/PPP2PPP/RNBQ1RK1 b kq - 0 5" + ); + } + // Stopping early: the callback sees the positions in order. + let mut seen = 0; + main_line(&rec, 0, true, |_, _| { + seen += 1; + seen < 3 + }) + .expect("walks"); + assert_eq!(seen, 3); + } + + #[test] + fn fast_walk_rejects_what_the_board_does_not_allow() { + use Square::*; + // A move from an empty square, and a capture of an own piece. + for bad in [(E3, E4, 0x4000), (D1, D2, 0x4000)] { + let rec = simple_record(&[bad]); + assert!(matches!(walked(&rec, 0, true), Err(WalkError::Moves(_)))); + assert!(matches!(walked(&rec, 0, false), Err(WalkError::Moves(_)))); + } + // Chess960 is not a damaged record. + assert!(matches!( + main_line(&[10, 0, 0, 4], 0, true, |_, _| true), + Err(WalkError::Unsupported(_)) + )); + // A game without moves: only the start position, as the end. + let (sans, end) = walked(&simple_record(&[]), 0, true).expect("walks"); + assert!(sans.is_empty()); + assert_eq!(end, Chess::default()); + } + + /// Fast and checked walks give the main line of `decode` for every game of a + /// database. + pub(crate) fn check_walks(cbh: &[u8], cbg: &[u8], step: usize) -> (usize, usize) { + let records = super::super::headers::read(cbh).expect("records"); + let (mut games, mut skipped) = (0, 0); + for rec in records.iter().step_by(step.max(1)) { + let super::super::headers::Record::Game(h) = rec else { + continue; + }; + let Ok(tree) = decode(cbg, h.moves_offset) else { + skipped += 1; + continue; + }; + let line = tree_line(&tree); + for fast in [true, false] { + let (sans, _) = walked(cbg, h.moves_offset, fast).expect("a decodable game walks"); + assert_eq!(sans, line, "game at {} (fast: {fast})", h.moves_offset); + } + games += 1; + } + (games, skipped) + } + + #[test] + fn walks_match_the_decoder_on_sample_databases() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample"); + for name in [ + "Rubinstein russian.cbv", + "Anand 01-14.cbv", + "Endgame Manual.cbv", + ] { + let Ok(bytes) = std::fs::read(dir.join(name)) else { + eprintln!("skipped: {name} not found"); + continue; + }; + let members = crate::cbv::unpack(&bytes).expect("unpacks"); + let pick = |ext: &str| { + members + .iter() + .find(|m| m.name.to_ascii_lowercase().ends_with(ext)) + .map(|m| m.data.as_slice()) + .expect("member") + }; + let (games, _) = check_walks(pick(".cbh"), pick(".cbg"), 1); + assert!(games > 100, "{name}: {games} games"); + } + } + + /// Mega Database 2026 (not in the repository), every 97th game. Run with + /// `cargo test --release -p chess-import walks_match_the_decoder_on_mega -- --ignored`. + #[test] + #[ignore] + fn walks_match_the_decoder_on_mega() { + let stem = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026"); + let (Ok(cbh), Ok(cbg)) = ( + std::fs::read(stem.with_extension("cbh")), + std::fs::read(stem.with_extension("cbg")), + ) else { + eprintln!("skipped: Mega Database 2026 not found"); + return; + }; + let (games, skipped) = check_walks(&cbh, &cbg, 97); + eprintln!("{games} games walked, {skipped} unreadable (Chess960)"); + assert!(games > 120_000); + } +} diff --git a/crates/chess-import/src/chessbase/openings.rs b/crates/chess-import/src/chessbase/openings.rs new file mode 100644 index 0000000..d4911a3 --- /dev/null +++ b/crates/chess-import/src/chessbase/openings.rs @@ -0,0 +1,618 @@ +//! Opening index of a large ChessBase database: the positions of the first `PLIES` +//! half-moves of every game, so a position of the opening is found without a pass +//! over the games (the booster cannot rule games out there: nearly every game passes +//! through 1.e4). Built in the same pass as the booster, kept in the cache directory +//! next to it, and held in memory only when the machine has room for it. +//! +//! Contents. Per game from the usual start position, its first `PLIES` moves as 16-bit +//! codes (`prefix`; `END` after the last move, `NULL` for a null move) — they give the +//! move a game played from a position, whether it came by the same move order and the +//! games that end there. Then one entry per (position, game) for plies 0..=`PLIES`: +//! the distinct position keys sorted (`keys`), and per key its games in ascending +//! order with the ply at which each reaches it (`games`: record index as a varint +//! delta, then the ply). A game that reaches a position twice within the opening +//! counts at its first ply. Games from a set-up position and the unreadable ones have +//! no entries (a search finds them in the pass, as before; the index answers only for +//! positions reached by at most `PLIES` moves from the usual start). +//! +//! File. `.cpo` in the cache directory (same hash as the booster): a 48-byte +//! header (magic, plies, records, section lengths), the prefixes, the keys, the +//! games, the games from a set-up position (u32 each, ascending: a search walks +//! them as before); all little-endian. It is read whole into memory ([`Index::load`]), so its +//! size is what it costs to keep. + +use std::fs::File; +use std::io::{self, BufWriter, Read, Write}; +use std::path::Path; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Role, Square}; + +use super::base::Base; +use crate::position::{self, Collector, GameResult, Match, PositionQuery, uci}; + +/// Half-moves of each game in the index. +pub const PLIES: usize = 10; +/// Moves kept per game: one more than the indexed plies, so that the move played +/// from the deepest indexed position is known too. +const PREFIX: usize = PLIES + 1; +/// Rough size of the index per game, to tell beforehand whether it fits in memory +/// (Mega: about 50 bytes). +pub const BYTES_PER_GAME: u64 = 60; +/// Prefix code: the game's main line ended before this move. +const END: u16 = u16::MAX; +/// Prefix code: a null move. +const NULL: u16 = u16::MAX - 1; +const MAGIC: &[u8; 8] = b"CPOPEN02"; +/// Header: magic, plies, records, then the lengths of the four sections. +const HEADER: usize = 48; +/// Temporary files the entries are spread over by the top bits of the key, so that +/// no more than a fraction of them is sorted in memory at a time. +const BUCKETS: usize = 64; +/// Bytes of a raw entry in a bucket file: key (8), game (4), ply (1). +const RAW: usize = 13; + +/// A move in 16 bits: from (6), to (6), promotion role (3). +fn encode(m: UciMove) -> u16 { + match m { + UciMove::Normal { + from, + to, + promotion, + } => { + u16::from(u8::from(from)) + | u16::from(u8::from(to)) << 6 + | u16::from(promotion.map_or(0, |r| r as u8)) << 12 + } + _ => NULL, + } +} + +fn decode(v: u16) -> Option { + match v { + END => None, + NULL => Some(UciMove::Null), + v => Some(UciMove::Normal { + from: Square::new(u32::from(v & 63)), + to: Square::new(u32::from((v >> 6) & 63)), + promotion: Role::try_from(v >> 12).ok(), + }), + } +} + +/// What the build pass collects for one game (see [`Sink`]). +pub(super) struct GameEntry { + pub index: u32, + /// The first `PREFIX` moves, `END`-padded. + pub prefix: [u16; PREFIX], + /// (position key, ply) for plies 0..=`PLIES`, up to the end of the line. + pub keys: Vec<(u64, u8)>, + /// The game starts from the usual position (else it gets no entries). + pub standard: bool, +} + +impl GameEntry { + pub(super) fn new(index: u32) -> GameEntry { + GameEntry { + index, + prefix: [END; PREFIX], + keys: Vec::with_capacity(PLIES + 1), + standard: true, + } + } + + /// Called by the pass for the position at `ply` and the step from it. + pub(super) fn visit(&mut self, pos: &Chess, ply: usize, step: &super::moves::Step<'_>) { + use super::moves::Step; + if !self.standard || ply > PLIES { + return; + } + if ply == 0 && !position::same_position(pos, &Chess::default()) { + self.standard = false; + return; + } + self.keys.push((position::key(pos), ply as u8)); + self.prefix[ply] = match step { + Step::Move(m) => encode(uci(m)), + Step::Null => NULL, + Step::End => END, + }; + } +} + +/// Collects the entries of the build pass into bucket files. +pub(super) struct Sink { + buckets: Vec>>, + prefix: Mutex>, + /// Games from a set-up position (the index has no entries for them). + set_up: Mutex>, + dir: std::path::PathBuf, +} + +impl Sink { + pub(super) fn new(dir: &Path, records: usize) -> io::Result { + std::fs::create_dir_all(dir)?; + let mut buckets = Vec::with_capacity(BUCKETS); + for b in 0..BUCKETS { + let f = File::create(dir.join(format!("bucket-{b:02}")))?; + buckets.push(Mutex::new(BufWriter::with_capacity(1 << 16, f))); + } + Ok(Sink { + buckets, + prefix: Mutex::new(vec![END; records * PREFIX]), + set_up: Mutex::new(Vec::new()), + dir: dir.to_owned(), + }) + } + + /// Adds the entries of a block of games (`entries` hold distinct games) and the + /// games of the block that start from a set-up position. + pub(super) fn add(&self, entries: &[GameEntry], set_up: &[u32]) -> io::Result<()> { + if !set_up.is_empty() + && let Ok(mut s) = self.set_up.lock() + { + s.extend_from_slice(set_up); + } + if let Ok(mut p) = self.prefix.lock() { + for e in entries { + let at = e.index as usize * PREFIX; + p[at..at + PREFIX].copy_from_slice(&e.prefix); + } + } + // Group by bucket so that each lock is taken once per block. + let mut raw: Vec> = vec![Vec::new(); BUCKETS]; + for e in entries { + for &(key, ply) in &e.keys { + let b = &mut raw[(key >> 58) as usize]; + b.extend_from_slice(&key.to_le_bytes()); + b.extend_from_slice(&e.index.to_le_bytes()); + b.push(ply); + } + } + for (b, bytes) in raw.iter().enumerate() { + if !bytes.is_empty() { + let mut w = self + .buckets + .get(b) + .and_then(|m| m.lock().ok()) + .ok_or_else(|| io::Error::other("bucket lock"))?; + w.write_all(bytes)?; + } + } + Ok(()) + } + + /// Removes the bucket files (a cancelled or failed pass). + pub(super) fn discard(self) -> io::Result<()> { + self.remove_buckets(); + Ok(()) + } + + fn remove_buckets(&self) { + for b in 0..BUCKETS { + let _ = std::fs::remove_file(self.dir.join(format!("bucket-{b:02}"))); + } + let _ = std::fs::remove_dir(&self.dir); + } + + /// Sorts the entries and writes the index to `out` (`.part` first). `progress` + /// grows by `records` over the sort. The bucket files are removed either way. + /// `Ok(false)` when cancelled. + pub(super) fn finish( + self, + out: &Path, + records: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> io::Result { + let result = self.write(out, records, progress, cancel); + self.remove_buckets(); + if !matches!(result, Ok(true)) { + let _ = std::fs::remove_file(out.with_extension("part")); + let _ = std::fs::remove_file(out.with_extension("games")); + } + result + } + + fn write( + &self, + out: &Path, + records: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> io::Result { + for w in &self.buckets { + w.lock() + .map_err(|_| io::Error::other("bucket lock"))? + .flush()?; + } + let part = out.with_extension("part"); + let mut file = BufWriter::with_capacity(1 << 20, File::create(&part)?); + // Header: magic, plies, records, then the section lengths filled in at the end. + file.write_all(MAGIC)?; + file.write_all(&(PLIES as u32).to_le_bytes())?; + file.write_all(&(records as u32).to_le_bytes())?; + file.write_all(&[0u8; HEADER - 16])?; + // The prefix section: records × PREFIX × u16. + let prefix = self.prefix.lock().map_err(|_| io::Error::other("lock"))?; + let mut bytes = Vec::with_capacity(prefix.len() * 2); + for m in prefix.iter() { + bytes.extend_from_slice(&m.to_le_bytes()); + } + drop(prefix); + let prefix_len = bytes.len() as u64; + file.write_all(&bytes)?; + drop(bytes); + // The keys (kept in memory: a few dozen bytes per position) and the games + // (streamed to a file, appended after the keys), bucket by bucket: the + // buckets are in key order. + let games_path = out.with_extension("games"); + let mut games = BufWriter::with_capacity( + 1 << 20, + File::options() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(&games_path)?, + ); + let mut games_len = 0u64; + let mut keys: Vec = Vec::new(); + let mut raw = Vec::new(); + let mut list = Vec::new(); + for b in 0..BUCKETS { + if cancel.load(Ordering::Relaxed) { + return Ok(false); + } + raw.clear(); + File::open(self.dir.join(format!("bucket-{b:02}")))?.read_to_end(&mut raw)?; + let mut entries: Vec<(u64, u32, u8)> = raw + .as_chunks::() + .0 + .iter() + .map(|e| { + ( + u64::from_le_bytes(e[..8].try_into().expect("8 bytes")), + u32::from_le_bytes(e[8..12].try_into().expect("4 bytes")), + e[12], + ) + }) + .collect(); + entries.sort_unstable(); + let mut i = 0; + while i < entries.len() { + let key = entries[i].0; + list.clear(); + let mut last = 0u32; + let mut count = 0u32; + while i < entries.len() && entries[i].0 == key { + let (_, game, ply) = entries[i]; + i += 1; + // The same game twice (a repeated position): its first ply. + if count > 0 && game == last { + continue; + } + varint(&mut list, game - if count == 0 { 0 } else { last + 1 }); + list.push(ply); + last = game; + count += 1; + } + keys.extend_from_slice(&key.to_le_bytes()); + keys.extend_from_slice(&games_len.to_le_bytes()[..5]); + keys.extend_from_slice(&count.to_le_bytes()); + games.write_all(&list)?; + games_len += list.len() as u64; + } + // In all exactly `records` over the buckets. + progress.fetch_add( + records * (b + 1) / BUCKETS - records * b / BUCKETS, + Ordering::Relaxed, + ); + } + let keys_len = keys.len() as u64; + file.write_all(&keys)?; + drop(keys); + { + use std::io::Seek; + let mut games = games.into_inner().map_err(|e| e.into_error())?; + games.seek(io::SeekFrom::Start(0))?; + io::copy(&mut games, &mut file)?; + } // Closed before it is removed. + let _ = std::fs::remove_file(&games_path); + // The games from a set-up position, ascending. + let mut set_up = + std::mem::take(&mut *self.set_up.lock().map_err(|_| io::Error::other("lock"))?); + set_up.sort_unstable(); + for g in &set_up { + file.write_all(&g.to_le_bytes())?; + } + let set_up_len = set_up.len() as u64 * 4; + { + use std::io::Seek; + let mut file = file.into_inner().map_err(|e| e.into_error())?; + file.seek(io::SeekFrom::Start(16))?; + file.write_all(&prefix_len.to_le_bytes())?; + file.write_all(&keys_len.to_le_bytes())?; + file.write_all(&games_len.to_le_bytes())?; + file.write_all(&set_up_len.to_le_bytes())?; + file.sync_all()?; + } // Closed before the rename. + std::fs::rename(&part, out)?; + Ok(true) + } +} + +fn varint(out: &mut Vec, mut v: u32) { + while v >= 0x80 { + out.push((v as u8) | 0x80); + v >>= 7; + } + out.push(v as u8); +} + +fn read_varint(bytes: &[u8], at: &mut usize) -> Option { + let mut v = 0u32; + let mut shift = 0; + loop { + let b = *bytes.get(*at)?; + *at += 1; + v |= u32::from(b & 0x7f) << shift; + if b & 0x80 == 0 { + return Some(v); + } + shift += 7; + if shift > 28 { + return None; + } + } +} + +/// Size of a key record: key (8), offset into the games (5), count (4). +const KEY: usize = 17; + +/// The index in memory: the file's bytes and where its sections are. +pub struct Index { + bytes: Vec, + records: usize, + prefix: std::ops::Range, + keys: std::ops::Range, + games: std::ops::Range, + set_up: std::ops::Range, +} + +impl Index { + /// Size of the index file (what loading it takes in memory), if it is there. + pub fn file_size(path: &Path) -> Option { + std::fs::metadata(path).ok().map(|m| m.len()) + } + + /// Reads the whole file; `None` when it is not an index for `records` records. + pub fn load(path: &Path, records: usize) -> Option { + let bytes = std::fs::read(path).ok()?; + let head = bytes.get(..HEADER)?; + if &head[..8] != MAGIC { + return None; + } + let u32_at = |at: usize| -> Option { + Some(u64::from(u32::from_le_bytes( + head[at..at + 4].try_into().ok()?, + ))) + }; + let u64_at = |at: usize| -> Option { + Some(u64::from_le_bytes(head[at..at + 8].try_into().ok()?) as usize) + }; + if u32_at(8) != Some(PLIES as u64) || u32_at(12) != Some(records as u64) { + return None; + } + let (p, k, g, u) = (u64_at(16)?, u64_at(24)?, u64_at(32)?, u64_at(40)?); + let prefix = HEADER..HEADER + p; + let keys = prefix.end..prefix.end + k; + let games = keys.end..keys.end + g; + let set_up = games.end..games.end + u; + if set_up.end != bytes.len() || p != records * PREFIX * 2 || k % KEY != 0 || u % 4 != 0 { + return None; + } + Some(Index { + bytes, + records, + prefix, + keys, + games, + set_up, + }) + } + + pub fn memory(&self) -> usize { + self.bytes.len() + } + + pub fn positions(&self) -> usize { + self.keys.len() / KEY + } + + fn key_at(&self, i: usize) -> u64 { + let at = self.keys.start + i * KEY; + u64::from_le_bytes(self.bytes[at..at + 8].try_into().expect("8 bytes")) + } + + /// Where `key` is among the keys, if it is. + fn find(&self, key: u64) -> Option { + let n = self.positions(); + let (mut lo, mut hi) = (0, n); + while lo < hi { + let mid = (lo + hi) / 2; + if self.key_at(mid) < key { + lo = mid + 1; + } else { + hi = mid; + } + } + (lo < n && self.key_at(lo) == key).then_some(lo) + } + + /// Number of games that reach the position with `key` within the opening. + pub fn count(&self, key: u64) -> usize { + self.find(key).map_or(0, |i| { + let at = self.keys.start + i * KEY + 13; + u32::from_le_bytes(self.bytes[at..at + 4].try_into().expect("4 bytes")) as usize + }) + } + + /// The games of the position with `key`: (record index, ply), ascending. + fn games_of(&self, key: u64) -> Vec<(u32, u8)> { + let Some(lo) = self.find(key) else { + return Vec::new(); + }; + let at = self.keys.start + lo * KEY + 8; + let mut off = [0u8; 8]; + off[..5].copy_from_slice(&self.bytes[at..at + 5]); + let offset = u64::from_le_bytes(off) as usize; + let count = u32::from_le_bytes(self.bytes[at + 5..at + 9].try_into().expect("4 bytes")); + let games = &self.bytes[self.games.clone()]; + let mut out = Vec::with_capacity(count as usize); + let mut pos = offset; + let mut last = 0u32; + for i in 0..count { + let Some(delta) = read_varint(games, &mut pos) else { + break; + }; + let game = if i == 0 { delta } else { last + 1 + delta }; + let Some(&ply) = games.get(pos) else { + break; + }; + pos += 1; + out.push((game, ply)); + last = game; + } + out + } + + /// The first `PREFIX` moves of a game (`END`-padded). + fn prefix_of(&self, game: u32) -> [u16; PREFIX] { + let at = self.prefix.start + game as usize * PREFIX * 2; + let mut out = [END; PREFIX]; + for (i, m) in out.iter_mut().enumerate() { + let b = at + i * 2; + *m = u16::from_le_bytes([self.bytes[b], self.bytes[b + 1]]); + } + out + } + + /// Whether the index should answer `query`: a position reached from the usual + /// start by at most `PLIES` moves (then every game that reaches it within the + /// opening is in the index), unless `candidates` are so few against the games of + /// the position that walking them is cheaper than decoding its list. + pub fn answers(&self, query: &PositionQuery, candidates: Option<&[u32]>) -> bool { + let opening = query + .line + .as_ref() + .is_some_and(|l| l.len() <= PLIES && self.records > 0); + opening && candidates.is_none_or(|c| c.len() * 32 >= self.count(query.key())) + } + + /// Records `games` (record index, ply) that reach the position: what each played + /// next and its result, ratings and year. + fn tally(&self, base: &Base, games: &[(u32, u8)], line: &[u16]) -> Collector { + let mut out = Collector::default(); + for &(game, ply) in games { + let prefix = self.prefix_of(game); + let ply = usize::from(ply); + let same_order = ply == line.len() && prefix[..ply] == line[..]; + let next = decode(prefix[ply]); + let r = base.record(game as usize); + let u = |at, n| super::be(r, at, n).unwrap_or(0); + let result = match r.get(0x1b) { + Some(2 | 6) => GameResult::WhiteWins, + Some(1 | 5) => GameResult::Draw, + Some(0 | 4) => GameResult::BlackWins, + _ => GameResult::Unknown, + }; + let year = ((u(0x18, 3) >> 9) & 0xfff) as u16; + out.add( + Match { + index: game, + ply: ply as u32, + same_order, + in_variation: false, + next: None, + }, + next, + result, + u(0x1f, 2) as u16, + u(0x21, 2) as u16, + year, + ); + } + out + } + + /// The games (among `candidates`, ascending; `None`: all) that reach the position, + /// with what they played next, as the pass would find them. + pub fn collect( + &self, + base: &Base, + candidates: Option<&[u32]>, + query: &PositionQuery, + ) -> Collector { + let line: Vec = query + .line + .as_deref() + .unwrap_or_default() + .iter() + .map(|m| encode(uci(m))) + .collect(); + // The games asked for, in record order. + let mut games = self.games_of(query.key()); + if let Some(c) = candidates { + let mut i = 0; + games.retain(|&(g, _)| { + while i < c.len() && c[i] < g { + i += 1; + } + i < c.len() && c[i] == g + }); + } + // Millions of games for an early position: tallied in parallel, each part + // keeping its order. + let threads = crate::parallel::threads(1) + .min(games.len().div_ceil(1 << 16)) + .max(1); + let chunk = games.len().div_ceil(threads).max(1); + let line = &line; + let parts: Vec = crate::parallel::map(games.chunks(chunk).collect(), |part| { + self.tally(base, part, line) + }) + .into_iter() + .map(Option::unwrap_or_default) + .collect(); + let mut out = Collector::default(); + for part in parts { + out.merge(part); + } + out + } + + /// The games from a set-up position (not in the index) among `candidates`. + pub fn set_up_games(&self, candidates: Option<&[u32]>) -> Vec { + let all = self + .set_up + .clone() + .step_by(4) + .map(|at| u32::from_le_bytes(self.bytes[at..at + 4].try_into().expect("4 bytes"))); + match candidates { + None => all.collect(), + Some(c) => { + let mut i = 0; + all.filter(|&g| { + while i < c.len() && c[i] < g { + i += 1; + } + i < c.len() && c[i] == g + }) + .collect() + } + } + } +} diff --git a/crates/chess-import/src/chessbase/search.rs b/crates/chess-import/src/chessbase/search.rs new file mode 100644 index 0000000..c680eeb --- /dev/null +++ b/crates/chess-import/src/chessbase/search.rs @@ -0,0 +1,1574 @@ +//! Position search in a large ChessBase database: the main line of every candidate +//! game is walked with a fast decoder (moves built from the board, no legal move +//! generation), games that can no longer reach the position are dropped early, and +//! the `.cbb` search booster rules out games beforehand when it is valid. +//! Research and measurements: `docs/research/position-index.md`. + +use std::fs::File; +use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use shakmaty::uci::UciMove; +use shakmaty::{Bitboard, Board, Chess, Color, Position, Rank, Role}; + +use super::base::{Base, RecordKind}; +use super::be; +use super::moves::{self, Step, WalkError}; +use crate::position::{ + Collector, GameResult, Match, PositionOutcome, PositionQuery, same_position, uci, +}; + +/// Candidates handed to a thread at a time; cancellation is checked between blocks. +pub(super) const BLOCK: usize = 2048; +/// Games whose moves lie closer than this are read with one `pread`. +const GAP: u32 = 64 << 10; +/// Longest span of `.cbg` read at once. +const SPAN: u32 = 4 << 20; +/// Read past the last record start of a span (most records are shorter). +const TAIL: u32 = 4096; +/// Size of a `.cbb` record (the file starts with a header of the same size). +pub(super) const CBB_RECORD: usize = 52; +/// Booster records sampled before a search; when most of them admit the target the +/// booster is left out (it would read its whole file to rule out almost nothing). +const SAMPLE: usize = 4096; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SearchMode { + Explorer, + PlayedLine, +} + +/// Games among `candidates` (record indices in ascending order; `None`: all records) +/// whose main line reaches the position. `scanned` counts the candidates looked at. +/// `None` when cancelled. +fn search_inner( + base: &Base, + mode: SearchMode, + candidates: Option<&[u32]>, + query: &PositionQuery, + scanned: &AtomicUsize, + cancel: &AtomicBool, +) -> Option { + // A position of the opening: the index knows its games, except those from a + // set-up position, which the pass looks at. + if mode == SearchMode::Explorer + && let Some(index) = base.openings() + && index.answers(query, candidates) + { + let others = index.set_up_games(candidates); + let mut out = collect(base, Some(&others), query, scanned, cancel, false)?; + if cancel.load(Ordering::Relaxed) { + return None; + } + out.merge(index.collect(base, candidates, query)); + let total = candidates.map_or(base.records(), <[u32]>::len); + scanned.fetch_add(total.saturating_sub(others.len()), Ordering::Relaxed); + return Some(out.finish(&query.position)); + } + collect( + base, + candidates, + query, + scanned, + cancel, + mode == SearchMode::PlayedLine, + ) + .map(|c| c.finish(&query.position)) +} + +/// The position explorer: it may use the opening index. +pub fn search( + base: &Base, + candidates: Option<&[u32]>, + query: &PositionQuery, + scanned: &AtomicUsize, + cancel: &AtomicBool, +) -> Option { + search_inner( + base, + SearchMode::Explorer, + candidates, + query, + scanned, + cancel, + ) +} + +/// The played-line preparation: never take the bounded opening index shortcut. +pub fn search_first( + base: &Base, + candidates: Option<&[u32]>, + query: &PositionQuery, + scanned: &AtomicUsize, + cancel: &AtomicBool, +) -> Option { + search_inner( + base, + SearchMode::PlayedLine, + candidates, + query, + scanned, + cancel, + ) +} + +/// The pass of [`search`]: the matches in record order and the statistics, not yet +/// finished. `None` when cancelled. +fn collect( + base: &Base, + candidates: Option<&[u32]>, + query: &PositionQuery, + scanned: &AtomicUsize, + cancel: &AtomicBool, + played_line: bool, +) -> Option { + let total = candidates.map_or(base.records(), <[u32]>::len); + if total == 0 { + return Some(Collector::default()); + } + let target = Target::new(query, played_line); + let cbb = base + .cbb_path() + .filter(|p| booster_helps(p, &target.signature)); + let next = AtomicUsize::new(0); + let threads = crate::parallel::threads(4) + .min(total.div_ceil(BLOCK)) + .max(1); + // Per thread: its collector and, per block, (first candidate, first match). + type Part = (Collector, Vec<(usize, usize)>); + let parts: Vec> = crate::parallel::map(vec![(); threads], |()| { + let mut worker = Worker { + base, + target: &target, + cbg: File::open(base.cbg_path()).ok()?, + cbb: cbb.and_then(|p| File::open(p).ok()), + games: Vec::new(), + span: Vec::new(), + single: Vec::new(), + out: Collector::default(), + }; + let mut blocks = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return None; + } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Some((worker.out, blocks)); + } + let to = (from + BLOCK).min(total); + blocks.push((from, worker.out.matches.len())); + match candidates { + Some(c) => worker.block(c[from..to].iter().copied()), + None => worker.block(from as u32..to as u32), + } + scanned.fetch_add(to - from, Ordering::Relaxed); + } + }) + .into_iter() + .map(Option::flatten) + .collect(); + if cancel.load(Ordering::Relaxed) { + return None; + } + // A thread without a result could not open `.cbg`: the other threads could not + // either, so there is simply nothing found. + let mut parts: Vec = parts.into_iter().flatten().collect(); + // Matches in record order by putting the blocks in order (the start position + // matches every game: 11.7 million in Mega, too many to sort and grow casually). + let mut order: Vec<(usize, usize, usize, usize)> = Vec::new(); + for (p, (c, blocks)) in parts.iter().enumerate() { + for (k, &(from, start)) in blocks.iter().enumerate() { + let end = blocks.get(k + 1).map_or(c.matches.len(), |b| b.1); + order.push((from, p, start, end)); + } + } + order.sort_unstable(); + let mut matches = Vec::with_capacity(parts.iter().map(|p| p.0.matches.len()).sum()); + for (_, p, start, end) in order { + matches.extend_from_slice(&parts[p].0.matches[start..end]); + } + let mut all = Collector::default(); + for (mut c, _) in parts.drain(..) { + c.matches = Vec::new(); + all.merge(c); + } + all.matches = matches; + Some(all) +} + +/// The searched position, prepared for cheap checks. +struct Target { + pos: Chess, + occupied: Bitboard, + /// Men of each side, pawns of each side (none of them can grow in number). + men: [usize; 2], + pawns: [usize; 2], + /// Pawns on their start squares (a pawn that has left cannot come back). + home: [Bitboard; 2], + line: Option>, + start: Chess, + signature: Signature, + played_line: bool, +} + +impl Target { + fn new(query: &PositionQuery, played_line: bool) -> Target { + let b = query.position.board(); + let side = |c: Color| b.by_color(c); + let pawns = |c: Color| side(c) & b.pawns(); + Target { + pos: query.position.clone(), + occupied: b.occupied(), + men: [side(Color::White).count(), side(Color::Black).count()], + pawns: [pawns(Color::White).count(), pawns(Color::Black).count()], + home: [ + pawns(Color::White) & Bitboard::from_rank(Rank::Second), + pawns(Color::Black) & Bitboard::from_rank(Rank::Seventh), + ], + line: query.line.as_ref().map(|l| l.iter().map(uci).collect()), + start: Chess::default(), + signature: Signature::new(b), + played_line, + } + } + + /// Whether a game in this position may still reach the target. + fn reachable(&self, b: &Board) -> bool { + let (w, bl) = (b.white(), b.black()); + let (wp, bp) = (w & b.pawns(), bl & b.pawns()); + w.count() >= self.men[0] + && bl.count() >= self.men[1] + && wp.count() >= self.pawns[0] + && bp.count() >= self.pawns[1] + && (wp & self.home[0]) == self.home[0] + && (bp & self.home[1]) == self.home[1] + } + + /// The first time the main line of the record at `offset` reaches the target. + fn find(&self, cbg: &[u8], offset: u32, fast: bool) -> Result, WalkError> { + let mut ply = 0u32; + let mut in_order = self.line.is_some(); + let mut after_null = false; + let mut hit = None; + moves::main_line(cbg, offset, fast, |pos, step| { + if self.played_line && after_null { + return false; + } + if self.played_line && matches!(step, Step::Null) { + after_null = true; + } + if ply == 0 && in_order && !same_position(pos, &self.start) { + in_order = false; + } + let b = pos.board(); + if b.occupied() == self.occupied && same_position(pos, &self.pos) { + hit = Some(Hit { + ply, + same_order: in_order + && self.line.as_ref().is_some_and(|l| l.len() == ply as usize), + next: match step { + Step::Move(m) => Some(uci(m)), + Step::Null => Some(UciMove::Null), + Step::End => None, + }, + }); + return false; + } + if !self.reachable(b) { + return false; + } + if in_order { + let wanted = self.line.as_ref().and_then(|l| l.get(ply as usize)); + in_order = matches!((step, wanted), (Step::Move(m), Some(w)) if uci(m) == *w); + } + ply += 1; + true + })?; + Ok(hit) + } +} + +struct Hit { + ply: u32, + same_order: bool, + next: Option, +} + +/// What the `.cbb` record of a game that passes through the target must hold. +/// +/// A `.cbb` record (52 bytes, per game) accumulates what was ever on the board in +/// the main line, start and final positions included: the squares of white pawns +/// on ranks 3-7 (bytes 6-10, one byte per rank, bit = file) and of black pawns on +/// ranks 2-6 (11-15), the ranks and files of each king (16-19), the squares of +/// rooks and queens (white 20-27, black 28-35) and of knights and bishops (36-43, +/// 44-51), one byte per rank; per side (low nibble white, high black) "was without +/// a queen / rook / bishop / knight" (byte 5, bits 0-3), "had at most one rook / +/// bishop / knight" (byte 4, bits 1-3), "had only pawns and the king" (byte 3, bit 3) +/// and the number of pawns at the end, 7 meaning 7 or 8 (byte 3, bits 0-2). Our own +/// computation matched the Mega file byte for byte (research, section 1.1). +struct Signature { + need: [u8; CBB_RECORD], + end_pawns: [u8; 2], +} + +impl Signature { + fn new(b: &Board) -> Signature { + let mut need = [0u8; CBB_RECORD]; + for (sq, piece) in b.clone() { + let file = 1u8 << (sq.file() as u32); + let rank = sq.rank() as usize; + let white = piece.color == Color::White; + match piece.role { + Role::Pawn if white && rank >= 2 => need[0x06 + rank - 2] |= file, + Role::Pawn if !white && (1..=5).contains(&rank) => need[0x0b + rank - 1] |= file, + Role::Pawn => {} + Role::King => { + let (r, f) = if white { (0x10, 0x12) } else { (0x11, 0x13) }; + need[r] |= 1 << rank; + need[f] |= file; + } + Role::Rook | Role::Queen => need[if white { 0x14 } else { 0x1c } + rank] |= file, + Role::Knight | Role::Bishop => need[if white { 0x24 } else { 0x2c } + rank] |= file, + } + } + let mut end_pawns = [0; 2]; + for (c, shift) in [(Color::White, 0), (Color::Black, 4)] { + let count = |role: Role| (b.by_color(c) & b.by_role(role)).count(); + let (q, r, bi, n) = ( + count(Role::Queen), + count(Role::Rook), + count(Role::Bishop), + count(Role::Knight), + ); + for (flag, none) in [(1u8, q), (2, r), (4, bi), (8, n)] { + if none == 0 { + need[0x05] |= flag << shift; + } + } + for (flag, most) in [(2u8, r), (4, bi), (8, n)] { + if most <= 1 { + need[0x04] |= flag << shift; + } + } + if q + r + bi + n == 0 { + need[0x03] |= 8 << shift; + } + end_pawns[shift / 4] = count(Role::Pawn).min(7) as u8; + } + Signature { need, end_pawns } + } + + /// False when the game cannot have passed through the target. + fn admits(&self, rec: &[u8]) -> bool { + rec.len() >= CBB_RECORD + && self.need.iter().zip(rec).all(|(n, r)| r & n == *n) + && rec[3] & 7 <= self.end_pawns[0] + && (rec[3] >> 4) & 7 <= self.end_pawns[1] + } +} + +/// One search thread: its own file handles and buffers. +struct Worker<'a> { + base: &'a Base, + target: &'a Target, + cbg: File, + cbb: Option, + /// Games of the current block: record index and moves offset. + games: Vec<(u32, u32)>, + span: Vec, + single: Vec, + out: Collector, +} + +impl Worker<'_> { + fn block(&mut self, indices: impl Iterator) { + self.games.clear(); + for i in indices { + let r = self.base.record(i as usize); + // Chess960 games (ECO field ≥ 64576) cannot be read. + if self.base.kind(i as usize) == RecordKind::Game + && be(r, 0x23, 2).is_some_and(|eco| eco < 64576) + { + self.games.push((i, self.base.moves_offset(i as usize))); + } + } + self.booster(); + let Worker { + base, + target, + cbg, + games, + span, + single, + out, + .. + } = self; + read_games(cbg, games, span, single, |index, data, rel| { + if let Some(h) = find(target, data, rel) { + add(base, out, index, h); + } + }); + } + + /// Drops the games of the block that the `.cbb` booster rules out. + fn booster(&mut self) { + let (Some(cbb), Some(&(first, _)), Some(&(last, _))) = + (&self.cbb, self.games.first(), self.games.last()) + else { + return; + }; + let at = |i: u32| (i as u64 + 1) * CBB_RECORD as u64; + let records = (last - first) as usize + 1; + let sig = &self.target.signature; + if records <= 4 * self.games.len() + 64 { + // Dense candidates: one read for the whole block. + read_span(cbb, at(first), &mut self.span, records * CBB_RECORD); + let span = &self.span; + self.games.retain(|&(i, _)| { + let r = (i - first) as usize * CBB_RECORD; + span.get(r..r + CBB_RECORD) + .is_none_or(|rec| sig.admits(rec)) + }); + } else { + let mut rec = [0u8; CBB_RECORD]; + self.games + .retain(|&(i, _)| read_exact_at(cbb, &mut rec, at(i)).is_err() || sig.admits(&rec)); + } + } +} + +/// Records the game `index` that reached the target as `hit`. +fn add(base: &Base, out: &mut Collector, index: u32, hit: Hit) { + let r = base.record(index as usize); + let u = |at, n| be(r, at, n).unwrap_or(0); + let result = match r.get(0x1b) { + Some(2 | 6) => GameResult::WhiteWins, + Some(1 | 5) => GameResult::Draw, + Some(0 | 4) => GameResult::BlackWins, + _ => GameResult::Unknown, + }; + let year = ((u(0x18, 3) >> 9) & 0xfff) as u16; + out.add( + Match { + index, + ply: hit.ply, + same_order: hit.same_order, + in_variation: false, + next: None, + }, + hit.next, + result, + u(0x1f, 2) as u16, + u(0x21, 2) as u16, + year, + ); +} + +/// Calls `f(index, data, offset)` with the moves of every game of `games` (record +/// index and `.cbg` offset, in file order within a run): games whose records lie +/// close together are read with one `pread` into `span`, a record running past the +/// span is read alone into `single`. +pub(super) fn read_games( + cbg: &File, + games: &[(u32, u32)], + span: &mut Vec, + single: &mut Vec, + mut f: impl FnMut(u32, &[u8], u32), +) { + let mut start = 0; + while start < games.len() { + // A run of games whose moves lie close together, in file order. + let lo = games[start].1; + let mut end = start + 1; + while let Some(&(_, off)) = games.get(end) { + let prev = games[end - 1].1; + if off < prev || off - prev > GAP || off - lo > SPAN { + break; + } + end += 1; + } + let hi = games[end - 1].1; + let len = (hi - lo) as usize + TAIL as usize; + read_span(cbg, u64::from(lo), span, len); + for &(index, off) in &games[start..end] { + let rel = off - lo; + let size = be(span, rel as usize + 1, 3).unwrap_or(u32::MAX) as usize; + if rel as usize + size <= span.len() { + f(index, span, rel); + } else { + // A record running past the span: read it alone. + if read_record(cbg, off, single) == 0 { + continue; + } + f(index, single, 0); + } + } + start = end; + } +} + +/// Whether the booster at `path` rules out a worthwhile share of games for `sig`, +/// judged on its first records: early positions (the start, 1.e4) pass nearly every +/// game, and reading the file for them only costs time. +fn booster_helps(path: &Path, sig: &Signature) -> bool { + let Ok(f) = File::open(path) else { + return false; + }; + let mut buf = Vec::new(); + read_span(&f, CBB_RECORD as u64, &mut buf, SAMPLE * CBB_RECORD); + let records = buf.as_chunks::().0; + if records.is_empty() { + return false; + } + let admitted = records.iter().filter(|r| sig.admits(*r)).count(); + admitted * 2 < records.len() +} + +/// The fast walk, and the checked one when the fast one stumbles (damaged moves). +/// A game that neither can read is not found. +fn find(target: &Target, cbg: &[u8], offset: u32) -> Option { + match target.find(cbg, offset, true) { + Ok(hit) => hit, + Err(WalkError::Moves(_)) => target.find(cbg, offset, false).ok().flatten(), + Err(WalkError::Unsupported(_)) => None, + } +} + +/// Reads at a position without moving a shared cursor (`pread` on Unix; on Windows +/// the handle's cursor moves, but every thread has its own handle). +fn read_at(f: &File, buf: &mut [u8], at: u64) -> std::io::Result { + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_at(f, buf, at) + } + #[cfg(windows)] + { + std::os::windows::fs::FileExt::seek_read(f, buf, at) + } + // Elsewhere (WebAssembly) through the cursor: such a target has no threads to + // share it with. + #[cfg(not(any(unix, windows)))] + { + use std::io::{Read, Seek, SeekFrom}; + let mut f = f; + f.seek(SeekFrom::Start(at))?; + f.read(buf) + } +} + +fn read_exact_at(f: &File, mut buf: &mut [u8], mut at: u64) -> std::io::Result<()> { + while !buf.is_empty() { + match read_at(f, buf, at)? { + 0 => return Err(std::io::ErrorKind::UnexpectedEof.into()), + n => { + buf = &mut buf[n..]; + at += n as u64; + } + } + } + Ok(()) +} + +/// Reads up to `len` bytes at `at` into `buf` (shorter at the end of the file). +fn read_span(f: &File, at: u64, buf: &mut Vec, len: usize) { + buf.resize(len, 0); + let mut done = 0; + while done < len { + match read_at(f, &mut buf[done..], at + done as u64) { + Ok(0) | Err(_) => break, + Ok(n) => done += n, + } + } + buf.truncate(done); +} + +/// Reads the `.cbg` record at `offset` into `buf`; its size, 0 when unreadable. +fn read_record(f: &File, offset: u32, buf: &mut Vec) -> usize { + let mut head = [0u8; 4]; + if read_exact_at(f, &mut head, u64::from(offset)).is_err() { + return 0; + } + let size = be(&head, 1, 3).unwrap_or(0) as usize; + // Records hold at most a few megabytes; a larger size means damaged data. + if !(4..=64 << 20).contains(&size) { + return 0; + } + buf.resize(size, 0); + if read_exact_at(f, buf, u64::from(offset)).is_err() { + return 0; + } + size +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + use super::*; + use crate::position::Tally; + use shakmaty::san::SanPlus; + use shakmaty::{CastlingMode, EnPassantMode, FromSetup, Move, fen::Fen}; + + /// A sample `.cbv` unpacked into a fresh temporary directory (removed on drop). + struct Sample { + dir: PathBuf, + cbh: PathBuf, + } + + impl Sample { + fn unpack(name: &str) -> Option { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample") + .join(name); + let Ok(bytes) = std::fs::read(&path) else { + eprintln!("skipped: {} not found", path.display()); + return None; + }; + let dir = std::env::temp_dir().join(format!( + "chess-import-search-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).expect("temp dir"); + let mut cbh = None; + for m in crate::cbv::unpack(&bytes).expect("unpacks") { + let file = m.name.rsplit('/').next().unwrap_or(&m.name).to_owned(); + let p = dir.join(&file); + std::fs::write(&p, &m.data).expect("write"); + if file.to_ascii_lowercase().ends_with(".cbh") { + cbh = Some(p); + } + } + Some(Sample { + dir, + cbh: cbh.expect("a .cbh member"), + }) + } + + fn open(&self) -> Base { + Base::open(&self.cbh, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens") + } + } + + impl Drop for Sample { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } + } + + /// Main-line positions with the move played from each. + type Line = Vec<(Chess, Option)>; + + /// Main-line positions of a record by the tree decoder, with the move played + /// from each (`None` after the last); `None` for an unreadable game. + fn oracle_line(base: &Base, index: usize) -> Option { + if base.kind(index) != RecordKind::Game { + return None; + } + let cbg = std::fs::read(base.cbg_path()).expect("cbg"); + let tree = moves::decode(&cbg, base.moves_offset(index)).ok()?; + let mut pos: Chess = match &tree.start_fen { + Some(f) => { + let setup = f.parse::().ok()?.into_setup(); + match Chess::from_setup(setup, CastlingMode::Standard) { + Ok(p) => p, + Err(e) => match e.ignore_invalid_castling_rights() { + Ok(p) => p, + Err(e) => e.ignore_invalid_ep_square().ok()?, + }, + } + } + None => Chess::default(), + }; + let mut out = Vec::new(); + let mut node = 0; + while let Some(&c) = tree.nodes[node].children.first() { + let san = &tree.nodes[c].san; + if san == "--" { + out.push((pos.clone(), Some(UciMove::Null))); + let mut setup = pos.to_setup(EnPassantMode::Legal); + setup.swap_turn(); + setup.ep_square = None; + pos = Chess::from_setup(setup, CastlingMode::Standard).ok()?; + } else { + let m: Move = san.parse::().ok()?.san.to_move(&pos).ok()?; + out.push((pos.clone(), Some(uci(&m)))); + pos.play_unchecked(m); + } + node = c; + } + out.push((pos, None)); + Some(out) + } + + /// Expected (index, ply, next move) of the games that reach `target`. + fn oracle( + lines: &[Option], + candidates: Option<&[u32]>, + target: &Chess, + ) -> Vec<(u32, u32, Option)> { + let mut out = Vec::new(); + for (i, line) in lines.iter().enumerate() { + if candidates.is_some_and(|c| !c.contains(&(i as u32))) { + continue; + } + let Some(line) = line else { continue }; + if let Some(ply) = line.iter().position(|(p, _)| same_position(p, target)) { + out.push((i as u32, ply as u32, line[ply].1)); + } + } + out + } + + fn run(base: &Base, candidates: Option<&[u32]>, query: &PositionQuery) -> PositionOutcome { + let scanned = AtomicUsize::new(0); + let out = search(base, candidates, query, &scanned, &AtomicBool::new(false)) + .expect("not cancelled"); + assert_eq!( + scanned.load(Ordering::Relaxed), + candidates.map_or(base.records(), <[u32]>::len) + ); + out + } + + /// Search results as (index, ply), with the total of continuations. + fn summary(out: &PositionOutcome) -> (Vec<(u32, u32)>, u32) { + let pairs = out.matches.iter().map(|m| (m.index, m.ply)).collect(); + let next: u32 = out.moves.iter().map(|m| m.tally.games).sum(); + (pairs, next + out.ended.games) + } + + /// Targets: the start position and positions along a few games, the last one + /// included. + fn targets(lines: &[Option]) -> Vec { + let mut out = vec![Chess::default()]; + for line in lines.iter().flatten().step_by(37).take(6) { + for ply in [4, 11, 24, line.len() - 1] { + if let Some((p, _)) = line.get(ply) { + out.push(p.clone()); + } + } + } + out + } + + fn check_sample(name: &str) { + let Some(sample) = Sample::unpack(name) else { + return; + }; + let base = sample.open(); + let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect(); + let every_third: Vec = (0..base.records() as u32).step_by(3).collect(); + for target in targets(&lines) { + let query = PositionQuery::new(target.clone(), None); + for candidates in [None, Some(every_third.as_slice())] { + let want = oracle(&lines, candidates, &target); + let out = run(&base, candidates, &query); + let (got, continuations) = summary(&out); + let want_pairs: Vec<(u32, u32)> = want.iter().map(|w| (w.0, w.1)).collect(); + assert_eq!( + got, + want_pairs, + "{name}: {}", + Fen::from_position(&target, EnPassantMode::Legal) + ); + // Null moves have no SAN and are left out of the continuations. + let nulls = want.iter().filter(|w| w.2 == Some(UciMove::Null)).count(); + assert_eq!(continuations as usize + nulls, want.len()); + let ended = want.iter().filter(|w| w.2.is_none()).count(); + assert_eq!(out.ended.games as usize, ended); + let first = search_first( + &base, + candidates, + &query, + &AtomicUsize::new(0), + &AtomicBool::new(false), + ) + .expect("played-line search"); + let actual: Vec<(u32, u32, Option)> = first + .matches + .iter() + .map(|m| (m.index, m.ply, m.next)) + .collect(); + let expected: Vec<(u32, u32, Option)> = want + .iter() + .filter(|(index, ply, _)| { + !lines[*index as usize].as_ref().is_some_and(|line| { + line[..*ply as usize] + .iter() + .any(|(_, next)| *next == Some(UciMove::Null)) + }) + }) + .cloned() + .collect(); + assert_eq!(actual, expected, "{name}: played-line first occurrence"); + } + } + } + + #[test] + fn finds_what_the_tree_decoder_finds() { + // Games from the usual start (Anand) and from set positions (Endgame Manual). + check_sample("Anand 01-14.cbv"); + check_sample("Endgame Manual.cbv"); + } + + #[test] + fn move_order_and_cancel() { + let Some(sample) = Sample::unpack("Anand 01-14.cbv") else { + return; + }; + let base = sample.open(); + let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect(); + // The moves of a game, as the user's line: that game is in the same order. + let (index, line) = lines + .iter() + .enumerate() + .find_map(|(i, l)| l.as_ref().filter(|l| l.len() > 16).map(|l| (i, l))) + .expect("a long game"); + let mut pos = Chess::default(); + let mut moves = Vec::new(); + for (_, m) in &line[..14] { + let m = m.as_ref().expect("a move").to_move(&pos).expect("legal"); + moves.push(m); + pos.play_unchecked(m); + } + let out = run( + &base, + None, + &PositionQuery::new(pos.clone(), Some(moves.clone())), + ); + let m = out + .matches + .iter() + .find(|m| m.index == index as u32) + .expect("the game itself"); + assert!(m.same_order && m.ply == 14 && !m.in_variation); + for m in &out.matches { + // Every game in the same order played exactly these moves. + let l = lines[m.index as usize].as_ref().expect("readable"); + let prefix: Vec = l[..m.ply as usize].iter().filter_map(|(_, u)| *u).collect(); + let same = m.ply == 14 && prefix == moves.iter().map(uci).collect::>(); + assert_eq!(m.same_order, same, "game {}", m.index); + } + // Without a line nothing is "in the same order". + let out = run(&base, None, &PositionQuery::new(pos.clone(), None)); + assert!(out.matches.iter().all(|m| !m.same_order)); + let cancel = AtomicBool::new(true); + let query = PositionQuery::new(pos, None); + assert!(search(&base, None, &query, &AtomicUsize::new(0), &cancel).is_none()); + } + + /// Our own `.cbb` record of a game (what the booster holds), from the main line. + fn own_cbb(line: &[(Chess, Option)]) -> [u8; CBB_RECORD] { + let mut r = [0u8; CBB_RECORD]; + for (pos, _) in line { + let sig = Signature::new(pos.board()); + // What a position requires is what it leaves in the record, except the + // final pawn count. + for (r, n) in r.iter_mut().zip(sig.need) { + *r |= n; + } + } + let (fin, _) = line.last().expect("a position"); + let b = fin.board(); + let pawns = |c: Color| (b.by_color(c) & b.pawns()).count().min(7) as u8; + r[3] |= pawns(Color::White) | (pawns(Color::Black) << 4); + r + } + + #[test] + fn booster_rules_out_games_but_loses_none() { + let Some(sample) = Sample::unpack("Anand 01-14.cbv") else { + return; + }; + let base = sample.open(); + let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect(); + // A booster as ChessBase writes it: a header record with the count, then a + // record per game (zeros for texts and unreadable games). + let count = base.records() as u32 + 1; + let mut cbb = vec![0u8; CBB_RECORD]; + cbb[..4].copy_from_slice(&count.to_be_bytes()); + for line in &lines { + cbb.extend(line.as_deref().map_or([0; CBB_RECORD], own_cbb)); + } + let path = sample.cbh.with_extension("cbb"); + let targets = targets(&lines); + let without: Vec<_> = targets + .iter() + .map(|t| summary(&run(&base, None, &PositionQuery::new(t.clone(), None)))) + .collect(); + + // A booster with the wrong count, or older than the games, is not used. + std::fs::write(&path, &cbb[..cbb.len() - CBB_RECORD]).expect("write"); + assert!(sample.open().cbb_path().is_none()); + std::fs::write(&path, &cbb).expect("write"); + let older = std::fs::metadata(base.cbg_path()) + .expect("cbg") + .modified() + .expect("time") + - std::time::Duration::from_secs(60); + File::options() + .write(true) + .open(&path) + .expect("open") + .set_modified(older) + .expect("touch"); + assert!(sample.open().cbb_path().is_none()); + std::fs::write(&path, &cbb).expect("write"); + let base = sample.open(); + assert!(base.cbb_path().is_some()); + + for (t, want) in targets.iter().zip(&without) { + let got = summary(&run(&base, None, &PositionQuery::new(t.clone(), None))); + assert_eq!(&got, want); + // And it does rule games out. + let sig = Signature::new(t.board()); + let admitted = (0..base.records()) + .filter(|&i| sig.admits(&cbb[(i + 1) * CBB_RECORD..])) + .count(); + assert!(admitted >= want.0.len()); + } + let deep = targets.last().expect("a target"); + let sig = Signature::new(deep.board()); + let admitted = (0..base.records()) + .filter(|&i| sig.admits(&cbb[(i + 1) * CBB_RECORD..])) + .count(); + assert!( + admitted < base.records() / 2, + "{admitted} of {}", + base.records() + ); + } + + fn san_line(line: &str) -> (Chess, Vec) { + let mut pos = Chess::default(); + let mut moves = Vec::new(); + for s in line.split_whitespace() { + let m = s + .parse::() + .expect("SAN") + .san + .to_move(&pos) + .expect("legal"); + moves.push(m); + pos.play_unchecked(m); + } + (pos, moves) + } + + fn peak_memory() -> String { + std::fs::read_to_string("/proc/self/status") + .unwrap_or_default() + .lines() + .find(|l| l.starts_with("VmHWM")) + .map(|l| l.trim_start_matches("VmHWM:").trim().to_owned()) + .unwrap_or_default() + } + + #[test] + fn own_booster_when_cbb_is_missing() { + let Some(sample) = Sample::unpack("Anand 01-14.cbv") else { + return; + }; + let base = sample.open(); + assert!(base.cbb_path().is_none() && !base.booster_wanted()); + let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect(); + let targets = targets(&lines); + let without: Vec<_> = targets + .iter() + .map(|t| summary(&run(&base, None, &PositionQuery::new(t.clone(), None)))) + .collect(); + + let dir = sample.dir.join("cache"); + base.set_booster_dir(&dir); + assert!(base.booster_wanted() && !base.booster_ready()); + // Cancelled: nothing is left behind. + let cancelled = AtomicBool::new(true); + assert!( + !base + .build_booster(&AtomicUsize::new(0), &cancelled) + .expect("builds") + ); + assert!(std::fs::read_dir(&dir).map_or(true, |d| d.count() == 0)); + let progress = AtomicUsize::new(0); + assert!( + base.build_booster(&progress, &AtomicBool::new(false)) + .expect("builds") + ); + assert_eq!(progress.load(Ordering::Relaxed), base.records()); + let path = base.cbb_path().expect("our booster").to_owned(); + assert!(path.starts_with(&dir) && !base.booster_wanted()); + let cbb = std::fs::read(&path).expect("file"); + assert_eq!(cbb.len(), (base.records() + 1) * CBB_RECORD); + assert_eq!(be(&cbb, 0, 4), Some(base.records() as u32 + 1)); + // Our record holds everything the search may require of a game's record. + for (i, line) in lines.iter().enumerate() { + let rec = &cbb[(i + 1) * CBB_RECORD..(i + 2) * CBB_RECORD]; + match line { + Some(l) => { + let want = own_cbb(l); + assert!( + rec.iter().zip(want).all(|(r, w)| r & w == w), + "game {}", + i + 1 + ); + assert_eq!(rec[3] & 0x77, want[3] & 0x77, "game {}", i + 1); + } + None => assert!(rec.iter().all(|b| *b == 0), "record {}", i + 1), + } + } + for (t, want) in targets.iter().zip(&without) { + let got = summary(&run(&base, None, &PositionQuery::new(t.clone(), None))); + assert_eq!(&got, want); + } + // Opened again, the booster is found and not built anew. + let again = sample.open(); + again.set_booster_dir(&dir); + assert_eq!(again.cbb_path(), Some(path.as_path())); + // A `.cbb` that can be trusted comes first. + let cbb_path = sample.cbh.with_extension("cbb"); + std::fs::write(&cbb_path, &cbb).expect("write"); + let with_cbb = sample.open(); + with_cbb.set_booster_dir(&dir); + assert_eq!(with_cbb.cbb_path(), Some(cbb_path.as_path())); + } + + /// Mega Database 2026 (not in the repository): our booster record equals + /// ChessBase's byte for byte. Run with + /// `cargo test --release -p chess-import mega_own_booster -- --ignored --nocapture`. + #[test] + #[ignore] + fn mega_own_booster() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026.cbh"); + if !path.exists() { + eprintln!("skipped: no Mega"); + return; + } + let base = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + let cbb = File::open(base.cbb_path().expect(".cbb")).expect("open"); + let cbg = File::open(base.cbg_path()).expect("open"); + let (mut buf, mut rec) = (Vec::new(), [0u8; CBB_RECORD]); + let (mut checked, mut differ, mut unreadable, mut chess960) = (0, 0, 0, 0); + for i in (0..base.records()).step_by(97) { + read_exact_at(&cbb, &mut rec, ((i + 1) * CBB_RECORD) as u64).expect("read"); + if base.kind(i) == RecordKind::Game + && be(base.record(i), 0x23, 2).is_some_and(|eco| eco >= 64576) + { + // Chess960: no search reads these games, their record does not matter. + chess960 += 1; + continue; + } + let ours = if base.kind(i) == RecordKind::Game + && read_record(&cbg, base.moves_offset(i), &mut buf) > 0 + { + match super::super::booster::record_of(&buf, 0) { + Some(r) => r, + None => { + // A game our decoder does not read: no search finds it, and + // its record does not matter. + let why = moves::main_line(&buf, 0, false, |_, _| true) + .err() + .map(|e| e.reason().to_owned()); + unreadable += 1; + if unreadable <= 5 { + eprintln!("game {}: unreadable ({why:?})", i + 1); + } + continue; + } + } + } else { + [0; CBB_RECORD] + }; + checked += 1; + if ours != rec { + differ += 1; + if differ <= 5 { + eprintln!("game {}: ours {ours:02x?}\n cbb {rec:02x?}", i + 1); + } + } + } + eprintln!( + "{checked} records checked, {differ} differ; skipped: {unreadable} unreadable, {chess960} Chess960" + ); + assert_eq!(differ, 0); + } + + /// Everything of an outcome that the index must reproduce. + fn full(out: &PositionOutcome) -> (Vec, Vec<(UciMove, Tally)>, Tally) { + ( + out.matches.clone(), + out.moves.iter().map(|m| (m.uci, m.tally.clone())).collect(), + out.ended.clone(), + ) + } + + #[test] + fn opening_index_matches_the_pass() { + let Some(sample) = Sample::unpack("Anand 01-14.cbv") else { + return; + }; + let base = sample.open(); + let dir = sample.dir.join("cache"); + base.set_booster_dir(&dir); + assert!(base.prepare_wanted()); + let progress = AtomicUsize::new(0); + assert!( + base.prepare(&progress, &AtomicBool::new(false)) + .expect("prepares") + ); + assert!(progress.load(Ordering::Relaxed) >= base.records()); + let Some(index) = base.openings() else { + eprintln!("skipped: no memory for the index"); + return; + }; + assert!(index.positions() > 0 && !base.prepare_wanted()); + let plain = sample.open(); + assert!(plain.openings().is_none()); + let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect(); + let every_third: Vec = (0..base.records() as u32).step_by(3).collect(); + let mut checked = 0; + for line in lines.iter().flatten().step_by(23) { + for ply in [0, 1, 3, 6, super::super::openings::PLIES] { + let Some((pos, _)) = line.get(ply) else { + continue; + }; + let moves: Vec = line[..ply] + .iter() + .scan(Chess::default(), |p, (_, m)| { + let m = m.as_ref()?.to_move(p).ok()?; + p.play_unchecked(m); + Some(m) + }) + .collect(); + if moves.len() != ply { + continue; + } + let query = PositionQuery::new(pos.clone(), Some(moves)); + assert!(index.answers(&query, None)); + for cands in [None, Some(every_third.as_slice())] { + let fast = run(&base, cands, &query); + let slow = run(&plain, cands, &query); + assert_eq!(full(&fast), full(&slow), "ply {ply}"); + checked += 1; + } + } + } + assert!(checked > 10, "{checked} queries"); + // Deeper than the index: the pass answers. + let line = lines + .iter() + .flatten() + .find(|l| l.len() > 20) + .expect("a game"); + let deep = PositionQuery::new(line[15].0.clone(), None); + assert!(!index.answers(&deep, None)); + // Opened again: the index on disk is loaded without a build. + let again = sample.open(); + again.set_booster_dir(&dir); + let progress = AtomicUsize::new(0); + assert!( + again + .prepare(&progress, &AtomicBool::new(false)) + .expect("loads") + ); + assert_eq!(progress.load(Ordering::Relaxed), 0); + assert!(again.openings().is_some()); + } + + #[test] + fn opening_index_leaves_set_up_games_to_the_pass() { + let Some(sample) = Sample::unpack("Endgame Manual.cbv") else { + return; + }; + let base = sample.open(); + base.set_booster_dir(&sample.dir.join("cache")); + assert!(base.prepare_work() > 0); + let progress = AtomicUsize::new(0); + assert!( + base.prepare(&progress, &AtomicBool::new(false)) + .expect("prepares") + ); + let Some(index) = base.openings() else { + eprintln!("skipped: no memory for the index"); + return; + }; + let lines: Vec<_> = (0..base.records()).map(|i| oracle_line(&base, i)).collect(); + let set_up: Vec = lines + .iter() + .enumerate() + .filter(|(_, l)| { + l.as_ref() + .and_then(|l| l.first()) + .is_some_and(|(p, _)| !same_position(p, &Chess::default())) + }) + .map(|(i, _)| i as u32) + .collect(); + assert!(!set_up.is_empty()); + assert_eq!(index.set_up_games(None), set_up); + let some: Vec = set_up.iter().copied().step_by(2).collect(); + assert_eq!(index.set_up_games(Some(&some)), some); + // A position of the opening, also reached by a set-up game: what the pass finds. + let plain = sample.open(); + let (pos, _) = &lines[set_up[0] as usize].as_ref().expect("readable")[0]; + for query in [ + PositionQuery::new(pos.clone(), Some(Vec::new())), + PositionQuery::new(Chess::default(), Some(Vec::new())), + ] { + let (fast, slow) = (run(&base, None, &query), run(&plain, None, &query)); + assert_eq!(full(&fast), full(&slow)); + } + // The set-up start itself is found (by the pass, through the index's list). + let query = PositionQuery::new(pos.clone(), Some(Vec::new())); + assert!( + run(&base, None, &query) + .matches + .iter() + .any(|m| m.index == set_up[0]) + ); + } + + /// Mega Database 2026 (not in the repository): the opening index against the pass + /// on positions of the opening taken from games all over the base. The index may + /// only miss games that reach the position later than its plies (by a detour), + /// and finds nothing the pass does not; the rest of every match is the same. Run + /// with `cargo test --release -p chess-import mega_openings_random -- --ignored --nocapture`. + #[test] + #[ignore] + fn mega_openings_random() { + use super::super::openings::PLIES; + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026.cbh"); + if !path.exists() { + eprintln!("skipped: no Mega"); + return; + } + let base = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + let dir = std::env::temp_dir().join(format!("chess-import-random-{}", std::process::id())); + base.set_booster_dir(&dir); + assert!( + base.prepare(&AtomicUsize::new(0), &AtomicBool::new(false)) + .expect("prepares") + ); + assert!(base.openings().is_some(), "no memory for the index"); + let plain = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + let cbg = File::open(base.cbg_path()).expect("cbg"); + let mut buf = Vec::new(); + let (mut queries, mut detours, mut games_seen) = (0, 0, 0usize); + let mut i = 7usize; + while queries < 120 { + i = (i * 7_919 + 104_729) % base.records(); + if base.kind(i) != RecordKind::Game + || read_record(&cbg, base.moves_offset(i), &mut buf) == 0 + { + continue; + } + let mut line: Vec<(Chess, Option)> = Vec::new(); + let walked = moves::main_line(&buf, 0, false, |pos, step| { + line.push(( + pos.clone(), + match step { + Step::Move(m) => Some(*m), + _ => None, + }, + )); + line.len() <= PLIES + }); + if walked.is_err() + || line + .first() + .is_none_or(|(p, _)| !same_position(p, &Chess::default())) + { + continue; + } + let ply = (queries * 3) % (PLIES + 1); + if ply >= line.len() || line[..ply].iter().any(|(_, m)| m.is_none()) { + continue; + } + let moves: Vec = line[..ply].iter().filter_map(|(_, m)| *m).collect(); + let query = PositionQuery::new(line[ply].0.clone(), Some(moves)); + let fast = run(&base, None, &query); + let slow = run(&plain, None, &query); + let mut j = 0; + for m in &slow.matches { + if fast.matches.get(j) == Some(m) { + j += 1; + } else { + assert!( + m.ply as usize > PLIES, + "game {} at ply {} missing from the index (query ply {ply})", + m.index + 1, + m.ply + ); + detours += 1; + } + } + assert_eq!( + j, + fast.matches.len(), + "the index found games the pass did not" + ); + games_seen += slow.matches.len(); + queries += 1; + } + eprintln!( + "{queries} positions, {games_seen} matches of the pass, {detours} reached only by a detour after ply {PLIES}" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Mega Database 2026 (not in the repository): the opening index against the + /// pass, with timings. Run with + /// `cargo test --release -p chess-import mega_openings -- --ignored --nocapture`. + #[test] + #[ignore] + fn mega_openings() { + use super::super::base::{Filter, NameFilter, OpeningsStatus, SortKey}; + use std::time::Instant; + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026.cbh"); + if !path.exists() { + eprintln!("skipped: no Mega"); + return; + } + let base = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + let dir = + std::env::temp_dir().join(format!("chess-import-openings-{}", std::process::id())); + base.set_booster_dir(&dir); + let t = Instant::now(); + let progress = AtomicUsize::new(0); + assert!( + base.prepare(&progress, &AtomicBool::new(false)) + .expect("prepares") + ); + eprintln!( + "prepared in {:.2?}: {:?}, peak memory {}", + t.elapsed(), + base.openings_status(), + peak_memory() + ); + let index = base.openings().expect("loaded"); + eprintln!( + "{} positions, {} MB", + index.positions(), + index.memory() / 1_000_000 + ); + let plain = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + let never = AtomicBool::new(false); + let carlsen = plain + .query( + &Filter { + player: NameFilter { + text: "carlsen, magnus".into(), + ..NameFilter::default() + }, + ..Filter::default() + }, + SortKey::Number, + true, + &AtomicUsize::new(0), + &never, + ) + .expect("query"); + for (name, line) in [ + ("start", ""), + ("1.e4", "e4"), + ("1.d4 Nf6 2.c4 e6", "d4 Nf6 c4 e6"), + ("Najdorf", "e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6"), + ] { + let (pos, moves) = san_line(line); + let query = PositionQuery::new(pos, Some(moves)); + for cands in [None, Some(carlsen.as_slice())] { + let t = Instant::now(); + let fast = run(&base, cands, &query); + let fast_ms = t.elapsed().as_secs_f64() * 1e3; + let t = Instant::now(); + let slow = run(&plain, cands, &query); + let slow_ms = t.elapsed().as_secs_f64() * 1e3; + let same = |o: &PositionOutcome| o.matches.iter().filter(|m| m.same_order).count(); + eprintln!( + "{name:18} {:8}: index {:9} games ({:9} same order) {fast_ms:8.1} ms · pass {:9} games ({:9} same order) {slow_ms:8.1} ms · ended {} / {}", + if cands.is_some() { "Carlsen" } else { "all" }, + fast.matches.len(), + same(&fast), + slow.matches.len(), + same(&slow), + fast.ended.games, + slow.ended.games + ); + // Both lists are in record order: one merge tells the differences. + let (mut missing, mut extra) = (0, 0); + let (mut i, mut j) = (0, 0); + while i < slow.matches.len() || j < fast.matches.len() { + match (slow.matches.get(i), fast.matches.get(j)) { + (Some(a), Some(b)) if a == b => { + i += 1; + j += 1; + } + (Some(a), Some(b)) if a.index < b.index => { + missing += 1; + i += 1; + } + (Some(a), Some(b)) if a.index > b.index => { + extra += 1; + j += 1; + } + (Some(_), Some(_)) => { + // Same game, different details. + missing += 1; + extra += 1; + i += 1; + j += 1; + } + (Some(_), None) => { + missing += 1; + i += 1; + } + (None, _) => { + extra += 1; + j += 1; + } + } + } + if missing + extra > 0 { + eprintln!(" differ: {missing} only in the pass, {extra} only in the index"); + } + assert!(matches!(base.openings_status(), OpeningsStatus::Loaded(_))); + } + } + eprintln!("peak memory {}", peak_memory()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Mega Database 2026 (not in the repository): builds our booster for the whole + /// base into a temporary directory and times it, then searches with it. Run with + /// `cargo test --release -p chess-import mega_build_booster -- --ignored --nocapture`. + #[test] + #[ignore] + fn mega_build_booster() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026.cbh"); + if !path.exists() { + eprintln!("skipped: no Mega"); + return; + } + let base = Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + base.without_booster(); + let dir = std::env::temp_dir().join(format!("chess-import-booster-{}", std::process::id())); + base.set_booster_dir(&dir); + assert!(base.booster_wanted()); + let t = std::time::Instant::now(); + let progress = AtomicUsize::new(0); + assert!( + base.build_booster(&progress, &AtomicBool::new(false)) + .expect("builds") + ); + let built = t.elapsed(); + let own = base.cbb_path().expect("ours").to_owned(); + let size = std::fs::metadata(&own).expect("file").len(); + eprintln!( + "built in {built:.2?}: {} ({size} bytes), peak memory {}", + own.display(), + peak_memory() + ); + let (pos, line) = san_line("e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6"); + let t = std::time::Instant::now(); + let out = run(&base, None, &PositionQuery::new(pos, Some(line))); + eprintln!( + "Najdorf with our booster: {} games in {:.1?}", + out.matches.len(), + t.elapsed() + ); + assert_eq!(out.matches.len(), 291_273); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Mega Database 2026 (not in the repository): the counts of the research + /// (`docs/research/position-index.md`, section 3) and timings. Run with + /// `cargo test --release -p chess-import mega_position_search -- --ignored --nocapture`. + #[test] + #[ignore] + fn mega_position_search() { + use super::super::base::{Filter, NameFilter, SortKey}; + use std::time::Instant; + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../pgnFilesforExample/Mega2026/Mega Database 2026.cbh"); + if !path.exists() { + eprintln!("skipped: {} not found", path.display()); + return; + } + let t = Instant::now(); + let open = || Base::open(&path, &mut |_, _| {}, &AtomicBool::new(false)).expect("opens"); + let base = open(); + let plain = open(); + plain.without_booster(); + println!( + "open (twice): {:.2} s, booster: {}, peak memory {}", + t.elapsed().as_secs_f64(), + base.cbb_path().is_some(), + peak_memory() + ); + assert!(base.cbb_path().is_some()); + let never = AtomicBool::new(false); + let filter = Filter { + player: NameFilter { + text: "carlsen, magnus".into(), + ..NameFilter::default() + }, + ..Filter::default() + }; + let carlsen = base + .query(&filter, SortKey::Number, true, &AtomicUsize::new(0), &never) + .expect("query"); + println!("Carlsen: {} games", carlsen.len()); + let nimzo = "d4 Nf6 c4 e6 Nc3 Bb4 e3 O-O Bd3 d5 Nf3 c5 O-O Nc6 a3 Bxc3 bxc3 dxc4 Bxc4 Qc7"; + let ruy = "e4 e5 Nf3 Nc6 Bb5 a6 Ba4 Nf6 O-O Be7 Re1 b5 Bb3 d6 c3 O-O h3 Nb8 d4 Nbd7 \ + Nbd2 Bb7 Bc2 Re8 Nf1 Bf8 Ng3 g6 a4 c5 d5 c4 Bg5 h6 Be3 Nc5 Qd2 h5"; + // (name, line, (games reaching the position, of them in the same order)): + // the research's linear pass plus the games that end in the position (127, + // 13 and 3), the same order as its move-prefix index. + let queries = [ + ("start", "", None), + ("1.e4", "e4", None), + ( + "Najdorf", + "e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6", + Some((291_273, 273_875)), + ), + ("Nimzo-Indian, ply 20", nimzo, Some((2_208, 665))), + ("Ruy Lopez, ply 40", ruy, Some((406, 325))), + ]; + for (name, line, expected) in queries { + let (pos, moves) = san_line(line); + let query = PositionQuery::new(pos, Some(moves)); + let mut found = Vec::new(); + for (label, b, cands) in [ + ("all, .cbb", &base, None), + ("all, no .cbb", &plain, None), + ("Carlsen, .cbb", &base, Some(carlsen.as_slice())), + ("Carlsen, no .cbb", &plain, Some(carlsen.as_slice())), + ] { + let t = Instant::now(); + let out = search(b, cands, &query, &AtomicUsize::new(0), &never).expect("runs"); + let ms = t.elapsed().as_secs_f64() * 1e3; + let same = out.matches.iter().filter(|m| m.same_order).count(); + println!( + "{name:22} {label:17} {:9} games, {same:9} same order, {:3} moves, {ms:7.1} ms", + out.matches.len(), + out.moves.len() + ); + found.push(out.matches); + } + println!(" peak memory {}", peak_memory()); + assert_eq!(found[0], found[1], "{name}: the booster loses nothing"); + assert_eq!(found[2], found[3], "{name}: the booster loses nothing"); + if let Some((games, same)) = expected { + assert_eq!(found[0].len(), games, "{name}"); + assert_eq!(found[0].iter().filter(|m| m.same_order).count(), same); + } + } + println!("peak memory: {}", peak_memory()); + } +} diff --git a/crates/chess-import/src/chessbase/text.rs b/crates/chess-import/src/chessbase/text.rs new file mode 100644 index 0000000..79ce390 --- /dev/null +++ b/crates/chess-import/src/chessbase/text.rs @@ -0,0 +1,400 @@ +//! Text decoding and guiding texts. +//! +//! ChessBase does not record the code page of its texts: a text is UTF-8 or a +//! single-byte code page. A database is decoded with one single-byte code page, +//! detected from all its texts at once, while each text that is valid UTF-8 (and +//! not plain ASCII) is taken as UTF-8. + +use chess_core::{TextEncoding, detect_encoding}; + +use super::be; + +/// The byte ChessBase uses in single-byte texts to place a diagram. +const DIAGRAM: u8 = 0x9e; +/// The same marker in UTF-8 texts (a private-use character). +const DIAGRAM_UTF8: char = '\u{e005}'; +/// Where a text embeds an object (a diagram, a picture, a link to a game or chapter); +/// what the object is lies in formatting data whose layout is unknown. +pub const OBJECT: char = '\u{4}'; + +/// Piece figurines in single-byte texts: bytes 0xa2-0xa7 stand for K Q N B R and a pawn +/// when a square or a capture follows ("¤f3", "Â¥:g4"). +const FIGURINES_SINGLE: [&str; 6] = ["K", "Q", "N", "B", "R", ""]; +/// Piece figurines in UTF-8 texts: U+E024-U+E029 stand for K Q R B N and a pawn. +const FIGURINES_UTF8: [&str; 6] = ["K", "Q", "R", "B", "N", ""]; + +/// Adds a text to a code page detection sample. UTF-8 texts are decoded as such one +/// by one (see [`Decoder`]) and would only mislead the detection of the single-byte +/// code page, so they are left out, as is plain ASCII. +pub fn add_sample(buf: &mut Vec, text: &[u8]) { + if !text.is_ascii() && std::str::from_utf8(text).is_err() { + buf.extend_from_slice(text); + buf.push(b' '); + } +} + +pub fn detect(sample: &[u8]) -> TextEncoding { + match detect_encoding(sample).encoding { + // All ASCII or UTF-8: single-byte texts (if any) are most likely Western. + TextEncoding::Utf8 => TextEncoding::Windows1252, + e => e, + } +} + +pub struct Decoder { + single_byte: TextEncoding, +} + +impl Decoder { + pub fn new(single_byte: TextEncoding) -> Decoder { + Decoder { single_byte } + } + + pub fn single_byte(&self) -> TextEncoding { + self.single_byte + } + + /// A comment or a guiding text. Control characters are dropped, apart from line + /// breaks, tabs and [`OBJECT`]. + pub fn decode(&self, bytes: &[u8]) -> String { + let mut s = self.decode_raw(bytes); + s.retain(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t' | OBJECT)); + s + } + + fn decode_raw(&self, bytes: &[u8]) -> String { + if !bytes.is_ascii() + && let Ok(s) = std::str::from_utf8(bytes) + { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + DIAGRAM_UTF8 => {} + '\u{e024}'..='\u{e029}' => { + out.push_str(FIGURINES_UTF8[(c as u32 - 0xe024) as usize]); + } + c => out.push(c), + } + } + return out; + } + let mut cleaned = Vec::with_capacity(bytes.len()); + for (i, &b) in bytes.iter().enumerate() { + let next = bytes.get(i + 1).copied().unwrap_or(0); + match b { + DIAGRAM => {} + 0xa2..=0xa7 if matches!(next, b'a'..=b'h' | b'x' | b':') => { + cleaned.extend_from_slice(FIGURINES_SINGLE[usize::from(b - 0xa2)].as_bytes()); + } + b => cleaned.push(b), + } + } + self.single_byte.decode(&cleaned).0.into_owned() + } + + /// A name of a player, tournament or annotator. ChessBase stores names in a Western + /// code page even in a database whose texts are Cyrillic, but a name may also be + /// typed in Cyrillic: the reading that does not mix Latin and Cyrillic letters + /// within a word wins ("Nürnberg", not "NÑŒrnberg"). + pub fn decode_name(&self, bytes: &[u8]) -> String { + let own = self.decode(bytes).replace(OBJECT, " "); + if bytes.is_ascii() + || std::str::from_utf8(bytes).is_ok() + || !matches!( + self.single_byte, + TextEncoding::Windows1251 | TextEncoding::Koi8R | TextEncoding::Ibm866 + ) + { + return own; + } + let mut western = TextEncoding::Windows1252.decode(bytes).0.into_owned(); + western.retain(|c| !c.is_control()); + if mixed_words(&western) < mixed_words(&own) { + western + } else { + own + } + } +} + +/// Words that contain both Latin and Cyrillic letters. +fn mixed_words(s: &str) -> usize { + s.split(|c: char| !c.is_alphanumeric()) + .filter(|w| { + let latin = w.chars().any(|c| c.is_alphabetic() && (c as u32) < 0x250); + let cyrillic = w.chars().any(|c| ('\u{400}'..='\u{4ff}').contains(&c)); + latin && cyrillic + }) + .count() +} + +pub struct Body { + pub title: String, + pub text: String, +} + +/// Reads a guiding text record from `.cbg`: titles and contents in one or more +/// languages; the first of each is used. +pub fn guiding_text(cbg: &[u8], offset: u32, d: &Decoder) -> Result { + let at = offset as usize; + let size = be(cbg, at + 1, 3).ok_or("text outside the .cbg file")? as usize; + let rec = cbg.get(at..at + size).ok_or("text outside the .cbg file")?; + let mut r = Le { data: rec, pos: 4 }; + let bad = || "damaged guiding text".to_owned(); + let version = r.u16().ok_or_else(bad)?; + let mut title = String::new(); + for i in 0..r.u16().ok_or_else(bad)? { + let _lang = r.u16().ok_or_else(bad)?; + let len = usize::from(r.u16().ok_or_else(bad)?); + let t = r.take(len).ok_or_else(bad)?; + if i == 0 { + title = d.decode(t).trim().to_owned(); + } + } + r.take(1).ok_or_else(bad)?; + let mut text = String::new(); + for i in 0..r.u16().ok_or_else(bad)? { + let _lang = r.u16().ok_or_else(bad)?; + let body = match version { + 1 => { + let len = usize::from(r.u16().ok_or_else(bad)?); + let t = r.take(len).ok_or_else(bad)?; + let fmt = usize::from(r.u16().ok_or_else(bad)?); + r.take(fmt).ok_or_else(bad)?; + tidy(&objects_to_breaks(&d.decode(t))) + } + 2 => { + let len = r.u32().ok_or_else(bad)? as usize; + let t = r.take(len).ok_or_else(bad)?; + let fmt = r.u32().ok_or_else(bad)? as usize; + r.take(fmt).ok_or_else(bad)?; + tidy(&objects_to_breaks(&d.decode(t))) + } + 3 => { + let len = r.u32().ok_or_else(bad)? as usize; + let t = r.take(len).ok_or_else(bad)?; + r.take(4); + html_to_text(&d.decode(t).replace(OBJECT, " ")) + } + v => return Err(format!("guiding text format {v} is not supported")), + }; + if i == 0 { + text = body; + } + } + Ok(Body { title, text }) +} + +struct Le<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Le<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let s = self.data.get(self.pos..self.pos + n)?; + self.pos += n; + Some(s) + } + + fn u16(&mut self) -> Option { + self.take(2).map(|b| u16::from_le_bytes([b[0], b[1]])) + } + + fn u32(&mut self) -> Option { + self.take(4) + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + } +} + +/// Readable text from the HTML of a guiding text: block elements become line +/// breaks, scripts and styles are dropped, entities are decoded. +pub fn html_to_text(html: &str) -> String { + let mut out = String::new(); + let mut rest = html; + while let Some(lt) = rest.find('<') { + out.push_str(&decode_entities(&rest[..lt])); + let Some(gt) = rest[lt..].find('>') else { + rest = ""; + break; + }; + let tag = rest[lt + 1..lt + gt].trim().to_ascii_lowercase(); + rest = &rest[lt + gt + 1..]; + let name: String = tag + .trim_start_matches('/') + .chars() + .take_while(|c| c.is_ascii_alphanumeric()) + .collect(); + if !tag.starts_with('/') && matches!(name.as_str(), "script" | "style" | "head" | "title") { + let close = format!(" { + rest = &rest[end..]; + if let Some(gt) = rest.find('>') { + rest = &rest[gt + 1..]; + } + } + None => rest = "", + } + continue; + } + if matches!( + name.as_str(), + "br" | "p" | "div" | "li" | "tr" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "table" + ) && !out.ends_with('\n') + { + out.push('\n'); + } + } + out.push_str(&decode_entities(rest)); + tidy(&out) +} + +/// Plain guiding texts carry no line breaks: paragraphs start after an embedded +/// object (a diagram, a link). A run of objects becomes a paragraph break when a +/// capital letter or a digit follows, and a space otherwise ("games (• and •)"). +pub fn objects_to_breaks(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c != OBJECT { + out.push(c); + continue; + } + while chars + .peek() + .is_some_and(|c| *c == OBJECT || c.is_whitespace()) + { + chars.next(); + } + let next = chars.peek().copied(); + if next.is_none_or(|n| n.is_uppercase() || n.is_ascii_digit()) { + out.push('\n'); + } else { + out.push(' '); + } + } + out +} + +/// One paragraph per non-empty line, separated by a blank line; whitespace inside a +/// line collapsed. +pub fn tidy(text: &str) -> String { + // Line breaks may be "\r\n", "\n" or a lone "\r" (older ChessBase texts). + text.replace("\r\n", "\n") + .replace('\r', "\n") + .lines() + .map(|l| l.split_whitespace().collect::>().join(" ")) + .filter(|l| !l.is_empty()) + .collect::>() + .join("\n\n") +} + +fn decode_entities(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(amp) = rest.find('&') { + out.push_str(&rest[..amp]); + let tail = &rest[amp..]; + let Some(semi) = tail.find(';').filter(|i| *i <= 10) else { + out.push('&'); + rest = &tail[1..]; + continue; + }; + let name = &tail[1..semi]; + let ch = match name { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + "nbsp" => Some(' '), + _ => name + .strip_prefix("#x") + .or_else(|| name.strip_prefix("#X")) + .and_then(|h| u32::from_str_radix(h, 16).ok()) + .or_else(|| name.strip_prefix('#').and_then(|n| n.parse().ok())) + .and_then(char::from_u32), + }; + match ch { + Some(c) => { + out.push(c); + rest = &tail[semi + 1..]; + } + None => { + out.push('&'); + rest = &tail[1..]; + } + } + } + out.push_str(rest); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utf8_texts_win_over_the_code_page() { + let d = Decoder::new(TextEncoding::Windows1251); + assert_eq!(d.decode("Привет".as_bytes()), "Привет"); + assert_eq!(d.decode(&[0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]), "Привет"); + assert_eq!(d.decode(b"plain"), "plain"); + } + + #[test] + fn figurines_and_diagrams() { + let d = Decoder::new(TextEncoding::Windows1252); + assert_eq!( + d.decode(b"3...\xa5g4 4 \xa4:e5 \xa6xh5 \xa7b2+ \x9e"), + "3...Bg4 4 N:e5 Rxh5 b2+ " + ); + assert_eq!( + d.decode(b"price \xa3 5"), + "price £ 5", + "not before a square" + ); + assert_eq!( + d.decode("plan \u{e027}e3, \u{e025}d2 \u{e028}c6 \u{e005}".as_bytes()), + "plan Be3, Qd2 Nc6 " + ); + } + + #[test] + fn names_pick_the_code_page_per_name() { + let d = Decoder::new(TextEncoding::Windows1251); + assert_eq!(d.decode_name(b"N\xfcrnberg"), "Nürnberg"); + assert_eq!(d.decode_name(b"\xc0\xeb\xe5\xf5\xe8\xed"), "Ð�лехин"); + assert_eq!( + d.decode_name(b"1.7.\xe0"), + "1.7.а", + "a tie keeps the database code page" + ); + // Comments keep the database code page even when Latin squares follow Cyrillic. + assert_eq!(d.decode(b"\xcaf3"), "Кf3"); + } + + #[test] + fn embedded_objects_split_paragraphs() { + let t = + "Title! \u{4} Body text (\u{4} and \u{4}) here. \u{4}\u{4} \u{4}УПРÐ�ЖÐ�ЕÐ�ИЯ \u{4} \u{4}"; + assert_eq!( + tidy(&objects_to_breaks(t)), + "Title!\n\nBody text ( and ) here.\n\nУПРÐ�ЖÐ�ЕÐ�ИЯ" + ); + let d = Decoder::new(TextEncoding::Windows1252); + assert_eq!(d.decode(b"a\x01b\x81c\x04d"), "abc\u{4}d"); + } + + #[test] + fn html_becomes_text() { + let html = "x\ +

First line & more

Second
third ч

\ + "; + assert_eq!(html_to_text(html), "First line & more\n\nSecond\n\nthird ч"); + assert_eq!(tidy("\t\n A b \n\n\n\tc\n "), "A b\n\nc"); + assert_eq!(tidy("One\r\rTwo\r\nThree"), "One\n\nTwo\n\nThree"); + assert_eq!(html_to_text("a & b; c"), "a & b; c"); + } +} diff --git a/crates/chess-import/src/chessbase/writer.rs b/crates/chess-import/src/chessbase/writer.rs new file mode 100644 index 0000000..3433048 --- /dev/null +++ b/crates/chess-import/src/chessbase/writer.rs @@ -0,0 +1,345 @@ +//! PGN text for decoded games and guiding texts. + +use std::fmt::Write as _; + +use super::annotations::{Annotations, Item}; +use super::entities::Entities; +use super::headers::{GameHeader, TextHeader, date_tag, round_tag}; +use super::moves::Tree; +use super::text::Decoder; + +pub type Tags = Vec<(String, String)>; + +pub fn tags( + h: &GameHeader, + players: &Entities, + tournaments: &Entities, + annotators: &Entities, + d: &Decoder, +) -> Tags { + let or_q = |s: Option| s.unwrap_or_else(|| "?".into()); + let event_date = tournaments.date(h.tournament); + let mut t: Tags = vec![ + ("Event".into(), or_q(tournaments.name(h.tournament, d))), + ("Site".into(), or_q(tournaments.place(h.tournament, d))), + ("Date".into(), date_tag(h.date)), + ("Round".into(), round_tag(h.round, h.subround)), + ("White".into(), or_q(players.name(h.white, d))), + ("Black".into(), or_q(players.name(h.black, d))), + ("Result".into(), h.result_tag().into()), + ]; + if h.white_elo > 0 { + t.push(("WhiteElo".into(), h.white_elo.to_string())); + } + if h.black_elo > 0 { + t.push(("BlackElo".into(), h.black_elo.to_string())); + } + if let Some(eco) = h.eco_tag() { + t.push(("ECO".into(), eco)); + } + if let Some(a) = annotators.name(h.annotator, d) { + t.push(("Annotator".into(), a)); + } + if event_date != 0 { + t.push(("EventDate".into(), date_tag(event_date))); + } + t +} + +/// A guiding text is shown as a game without moves: the title in place of the +/// players and the text as the opening comment. +pub fn text_tags( + h: &TextHeader, + title: &str, + tournaments: &Entities, + annotators: &Entities, + d: &Decoder, +) -> Tags { + let mut t: Tags = vec![ + ( + "Event".into(), + tournaments + .name(h.tournament, d) + .unwrap_or_else(|| "?".into()), + ), + ("Site".into(), "?".into()), + ("Date".into(), "????.??.??".into()), + ("Round".into(), round_tag(h.round, h.subround)), + ( + "White".into(), + if title.is_empty() { + "?".into() + } else { + title.into() + }, + ), + ("Black".into(), String::new()), + ("Result".into(), "*".into()), + ]; + if let Some(a) = annotators.name(h.annotator, d) { + t.push(("Annotator".into(), a)); + } + t +} + +pub fn text_game(out: &mut String, tags: &Tags, text: &str) { + write_tags(out, tags, None); + let mut w = Movetext::default(); + if !text.trim().is_empty() { + w.comment(text); + } + w.token("*"); + out.push_str(&w.finish()); +} + +pub fn game(out: &mut String, tags: &Tags, tree: &Tree, notes: &Annotations, result: &str) { + // Main-line length, for the library's move count. + let mut plies = 0; + let mut node = 0; + while let Some(&next) = tree.nodes[node].children.first() { + plies += 1; + node = next; + } + let mut tags = tags.clone(); + if plies > 0 { + tags.push(("PlyCount".into(), plies.to_string())); + } + write_tags(out, &tags, tree.start_fen.as_deref()); + // Annotation position of each node. + let mut position = vec![None; tree.nodes.len()]; + for (i, n) in tree.order.iter().enumerate() { + position[*n] = i32::try_from(i).ok(); + } + let mut w = Movetext::default(); + if let Some(items) = notes.at.get(&-1) { + // Before-move texts of the whole game read as an introduction too. + let mut intro: Vec<&Item> = items.iter().collect(); + intro.sort_by_key(|i| !matches!(i, Item::Before(_))); + w.after_comment(&intro); + } + let ctx = Ctx { + tree, + notes, + position: &position, + }; + ctx.line(&mut w, 0); + w.token(result); + out.push_str(&w.finish()); +} + +struct Ctx<'a> { + tree: &'a Tree, + notes: &'a Annotations, + position: &'a [Option], +} + +impl Ctx<'_> { + /// Writes the continuation of `node`: its main move, the alternatives to that + /// move as variations, then the rest of the main line. + fn line(&self, w: &mut Movetext, mut node: usize) { + loop { + let children = &self.tree.nodes[node].children; + let Some(&main) = children.first() else { + return; + }; + self.write_move(w, main); + for &alt in &children[1..] { + w.open(); + self.write_move(w, alt); + self.line(w, alt); + w.close(); + } + node = main; + } + } + + fn write_move(&self, w: &mut Movetext, id: usize) { + let n = &self.tree.nodes[id]; + let items: &[Item] = self.position[id] + .and_then(|p| self.notes.at.get(&p)) + .map(Vec::as_slice) + .unwrap_or(&[]); + for it in items { + if let Item::Before(t) = it { + w.comment(t); + } + } + // The number and the move stay on one line. + let number = if n.white { + format!("{}. ", n.number) + } else if w.need_number { + format!("{}... ", n.number) + } else { + String::new() + }; + w.need_number = false; + w.token(&format!("{number}{}", n.san)); + for it in items { + if let Item::Nags(nags) = it { + for nag in nags { + w.token(&format!("${nag}")); + } + } + } + let after: Vec<&Item> = items + .iter() + .filter(|i| !matches!(i, Item::Before(_) | Item::Nags(_))) + .collect(); + w.after_comment(&after); + } +} + +fn write_tags(out: &mut String, tags: &Tags, fen: Option<&str>) { + for (k, v) in tags { + let _ = writeln!(out, "[{k} \"{}\"]", escape_tag(v)); + } + if let Some(fen) = fen { + let _ = writeln!(out, "[SetUp \"1\"]"); + let _ = writeln!(out, "[FEN \"{}\"]", escape_tag(fen)); + } + out.push('\n'); +} + +fn escape_tag(v: &str) -> String { + v.replace('\\', "\\\\") + .replace('"', "\\\"") + .replace(['\r', '\n'], " ") +} + +/// Movetext builder with line wrapping at 80 columns. +#[derive(Default)] +struct Movetext { + lines: Vec, + current: String, + need_number: bool, +} + +impl Movetext { + fn token(&mut self, t: &str) { + if !self.current.is_empty() && self.current.chars().count() + 1 + t.chars().count() > 80 { + self.lines.push(std::mem::take(&mut self.current)); + } + if !self.current.is_empty() && !self.current.ends_with('(') { + self.current.push(' '); + } + self.current.push_str(t); + } + + fn comment(&mut self, text: &str) { + // '}' would end the comment early; ChessBase texts rarely contain it. + let clean = text.replace('}', ")"); + self.token(&format!("{{{clean}}}")); + self.need_number = true; + } + + /// One comment with the graphics as `[%csl]`/`[%cal]`/`[%emt]` commands and the texts. + fn after_comment(&mut self, items: &[&Item]) { + let mut parts: Vec = Vec::new(); + for it in items { + match it { + Item::Squares(list) if !list.is_empty() => parts.push(format!( + "[%csl {}]", + list.iter() + .map(|(c, s)| format!("{c}{}", square(*s))) + .collect::>() + .join(",") + )), + Item::Arrows(list) if !list.is_empty() => parts.push(format!( + "[%cal {}]", + list.iter() + .map(|(c, a, b)| format!("{c}{}{}", square(*a), square(*b))) + .collect::>() + .join(",") + )), + Item::TimeSpent(h, m, s) => parts.push(format!("[%emt {h}:{m:02}:{s:02}]")), + Item::After(t) | Item::Before(t) => parts.push(t.clone()), + _ => {} + } + } + if !parts.is_empty() { + self.comment(&parts.join(" ")); + } + } + + fn open(&mut self) { + self.token("("); + self.need_number = true; + } + + fn close(&mut self) { + self.current.push(')'); + self.need_number = true; + } + + fn finish(mut self) -> String { + if !self.current.is_empty() { + self.lines.push(self.current); + } + let mut s = self.lines.join("\n"); + s.push_str("\n\n"); + s + } +} + +/// Square name from ChessBase numbering (a1 = 0, a2 = 1, … h8 = 63). +fn square(idx: u8) -> String { + let file = (b'a' + idx / 8) as char; + let rank = (b'1' + idx % 8) as char; + format!("{file}{rank}") +} + +#[cfg(test)] +mod tests { + use super::super::moves::Node; + use super::*; + + fn node(san: &str, number: u32, white: bool, children: Vec) -> Node { + Node { + san: san.into(), + number, + white, + children, + } + } + + #[test] + fn variations_comments_and_graphics() { + // 1. e4 c5 (1... c6 2. d4) 2. Nf3 + let tree = Tree { + start_fen: None, + nodes: vec![ + node("", 0, true, vec![1]), + node("e4", 1, true, vec![2, 4]), + node("c5", 1, false, vec![3]), + node("Nf3", 2, true, vec![]), + node("c6", 1, false, vec![5]), + node("d4", 2, true, vec![]), + ], + order: vec![1, 2, 3, 4, 5], + }; + let mut notes = Annotations::default(); + notes.at.insert(-1, vec![Item::After("Intro".into())]); + notes.at.insert( + 0, + vec![ + Item::Nags(vec![1]), + Item::Arrows(vec![('G', 35, 36)]), + Item::After("Best by test }".into()), + ], + ); + notes.at.insert(3, vec![Item::Before("Also".into())]); + let mut out = String::new(); + game( + &mut out, + &vec![("Event".into(), "Test \"x\"".into())], + &tree, + ¬es, + "*", + ); + assert_eq!( + out, + "[Event \"Test \\\"x\\\"\"]\n[PlyCount \"3\"]\n\n{Intro} 1. e4 $1 {[%cal Ge4e5] Best by test )} 1... c5 ({Also} 1... c6 2. d4)\n\ + 2. Nf3 *\n\n" + ); + } +} diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs new file mode 100644 index 0000000..7bc2f33 --- /dev/null +++ b/crates/chess-import/src/lib.rs @@ -0,0 +1,899 @@ +//! Opening chess databases that are not plain PGN files: ChessBase databases +//! (`.cbh` with its companion files), ChessBase archives (`.cbv`), and `.zip` / +//! `.7z` archives holding any of these or PGN files. +//! +//! Small databases are converted to PGN text in memory and indexed as a +//! [`PgnDatabase`]. A large ChessBase database (Mega Database: millions of games) is +//! read in place as a [`chessbase::base::Base`]: its game list comes from the `.cbh` +//! records and a game is converted to PGN when it is opened. Sources are only read. + +mod archive; +// Timings of a database on disk: a command of the desktop program. +#[cfg(not(target_family = "wasm"))] +pub mod bench; +pub mod cbv; +pub mod chessbase; +pub mod memory; +mod parallel; +pub mod pgn_catalog; +pub mod pgn_positions; +pub mod position; + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::sync::{Arc, Mutex}; + +use chess_core::{ + OpenError, ParsedGame, PgnDatabase, ScanProgress, TextEncoding, detect_encoding, parse_game, +}; + +use chessbase::base::Base; + +/// File extensions the application can open (lower case). +pub const EXTENSIONS: [&str; 5] = ["pgn", "cbh", "cbv", "zip", "7z"]; + +#[derive(Debug, thiserror::Error)] +pub enum ImportError { + #[error("cannot read {path}: {source}")] + Io { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("{0}")] + Corrupt(String), + #[error("{0}")] + Unsupported(Unsupported), + #[error("no PGN or ChessBase database in the archive")] + Empty, + #[error("import cancelled")] + Cancelled, +} + +impl From for ImportError { + fn from(e: OpenError) -> Self { + match e { + OpenError::Io { path, source } => ImportError::Io { path, source }, + OpenError::Cancelled => ImportError::Cancelled, + } + } +} + +/// Sources that are recognized but cannot be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Unsupported { + #[error("password-protected archives (.cbz, encrypted zip/7z) are not supported")] + Encrypted, + #[error("the ChessBase 2CBH format is not supported; export the database as CBH or PGN")] + ChessBase2, + /// A ChessBase database's `.cbh` given alone: its other files are needed too. + #[error("a ChessBase database is several files: open its folder")] + ChessBaseFiles, +} + +/// What a database was read from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + Pgn, + ChessBase, + ChessBaseArchive, + Zip, + SevenZip, +} + +impl Format { + pub const ALL: [Format; 5] = [ + Format::Pgn, + Format::ChessBase, + Format::ChessBaseArchive, + Format::Zip, + Format::SevenZip, + ]; + + pub fn label(self) -> &'static str { + match self { + Format::Pgn => "PGN", + Format::ChessBase => "ChessBase", + Format::ChessBaseArchive => "ChessBase CBV", + Format::Zip => "ZIP", + Format::SevenZip => "7z", + } + } +} + +/// ChessBase databases with at least this many records are read in place +/// ([`Database::ChessBase`]); smaller ones are converted to PGN. +pub const LARGE_CHESSBASE: u64 = 20_000; + +/// A PGN database and, once a position search asked for it, the positions of its +/// games. +pub struct PgnDb { + pub db: PgnDatabase, + positions: Mutex>>, + /// The filters' index of the tags, built on first use. + catalog: std::sync::OnceLock>, +} + +impl PgnDb { + pub fn new(db: PgnDatabase) -> PgnDb { + PgnDb { + db, + positions: Mutex::new(None), + catalog: std::sync::OnceLock::new(), + } + } + + /// The filters' index of the games' tags (see [`pgn_catalog`]). + pub fn catalog(&self) -> &pgn_catalog::Catalog { + self.catalog + .get_or_init(|| Box::new(pgn_catalog::Catalog::build(self.db.entries()))) + } + + /// Memory the position table would need while it is built: about 20 bytes per + /// position, and two to three times that during the build (`docs/dev/import.md`). + /// Counted from the moves of the games (variations included): the size of the text + /// says little when every move carries a clock comment. + pub fn positions_estimate(&self) -> u64 { + let positions: u64 = self + .db + .entries() + .iter() + .map(|e| u64::from(e.all_plies) + 1) + .sum(); + positions * 20 * 3 + } + + /// Why the position table cannot be built now: the memory it would need + /// ([`PgnDb::positions_estimate`]) is not there. `None` once it is built. + pub fn positions_blocked(&self) -> Option { + if self.positions.lock().ok()?.is_some() { + return None; + } + let need = self.positions_estimate(); + let room = memory::available().is_some_and(|free| free >= need + (256 << 20)); + (!room).then_some(need) + } + + /// The position table, built on first use. `None` when cancelled, or when the + /// machine has no memory for it ([`PgnDb::positions_blocked`]). + pub(crate) fn positions( + &self, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option> { + if let Some(t) = self.positions.lock().ok()?.as_ref() { + return Some(t.clone()); + } + if self.positions_blocked().is_some() { + return None; + } + let table = Arc::new(pgn_positions::PositionTable::build( + &self.db, progress, cancel, + )?); + if let Ok(mut slot) = self.positions.lock() { + *slot = Some(table.clone()); + } + Some(table) + } +} + +impl std::ops::Deref for PgnDb { + type Target = PgnDatabase; + + fn deref(&self) -> &PgnDatabase { + &self.db + } +} + +/// The beginning of a game's main line (see [`Database::main_line`]). +#[derive(Clone, Debug, Default)] +pub struct MainLine { + /// The game starts from the usual position; otherwise `moves` is empty. + pub standard_start: bool, + pub moves: Vec, +} + +/// An opened database. +pub enum Database { + Pgn(PgnDb), + ChessBase(Box), +} + +impl Database { + /// Number of records; an index below it identifies a game (or a deleted record + /// of a ChessBase database). + pub fn len(&self) -> usize { + match self { + Database::Pgn(db) => db.len(), + Database::ChessBase(b) => b.records(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Fully parses record `index`. A ChessBase game that could only be read in part + /// carries the problem as a diagnostic. + pub fn load_game(&self, index: usize) -> Option { + match self { + Database::Pgn(db) => db.load_game(index), + Database::ChessBase(b) => { + let (pgn, problem) = b.pgn(index)?; + let mut parsed = parse_game(pgn.as_bytes(), TextEncoding::Utf8); + if let Some(p) = problem { + parsed.diagnostics.push(chess_core::Diagnostic { + severity: chess_core::Severity::Warning, + code: chess_core::DiagnosticCode::PartlyConverted, + message: format!("ChessBase: {p}"), + location: None, + node: None, + }); + } + Some(parsed) + } + } + } + + /// The first `max_plies` moves of the main line of record `index`, for passes + /// over the openings of many games: a ChessBase game is decoded without its tree + /// (microseconds), a PGN game is parsed. The line stops at a teaching null move. + /// `None` for a text, a deleted record or unreadable moves. + pub fn main_line(&self, index: usize, max_plies: usize) -> Option { + match self { + Database::Pgn(db) => { + let parsed = db.load_game(index)?; + let game = &parsed.game; + let mut line = MainLine { + standard_start: game.start().is_standard(), + moves: Vec::new(), + }; + if !line.standard_start { + return Some(line); + } + for id in game.mainline().into_iter().take(max_plies) { + match game.game_move(id).map(|m| &m.kind) { + Some(chess_core::MoveKind::Normal(m)) => line.moves.push(*m), + _ => break, + } + } + Some(line) + } + Database::ChessBase(b) => b.main_line(index, max_plies), + } + } + + /// Bytes that identify record `index` (its content for PGN, its `.cbh` record for + /// ChessBase), for remembering viewed games. + pub fn identity(&self, index: usize) -> &[u8] { + match self { + Database::Pgn(db) => db.raw_bytes(index).unwrap_or_default(), + Database::ChessBase(b) => b.record(index), + } + } + + /// Record `index` as PGN text (the original text of a PGN file). + pub fn raw_text(&self, index: usize) -> Option { + match self { + Database::Pgn(db) => db.raw_text(index), + Database::ChessBase(b) => b.pgn(index).map(|(pgn, _)| pgn), + } + } + + pub fn as_pgn(&self) -> Option<&PgnDatabase> { + match self { + Database::Pgn(db) => Some(&db.db), + Database::ChessBase(_) => None, + } + } + + /// Games among `candidates` (record indices in ascending order; `None`: all) + /// that reach the position, with what was played next. `progress` counts the + /// records looked at (or, the first time for a PGN database, the games prepared). + /// `None` when cancelled. + pub fn search_position( + &self, + candidates: Option<&[u32]>, + query: &position::PositionQuery, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option { + match self { + Database::Pgn(db) => { + let table = db.positions(progress, cancel)?; + table.search(&db.db, candidates, query, cancel) + } + Database::ChessBase(b) => { + chessbase::search::search(b, candidates, query, progress, cancel) + } + } + } + + /// Search the main line, counting each played game once at its first occurrence. + pub fn search_position_first( + &self, + candidates: Option<&[u32]>, + query: &position::PositionQuery, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option { + match self { + Database::Pgn(db) => { + let table = db.positions(progress, cancel)?; + table.search_first(&db.db, candidates, query, cancel) + } + Database::ChessBase(b) => { + chessbase::search::search_first(b, candidates, query, progress, cancel) + } + } + } + + /// Memory a position search would need first and does not have (a PGN + /// database's table, see [`PgnDb::positions_blocked`]). + pub fn positions_blocked(&self) -> Option { + match self { + Database::Pgn(db) => db.positions_blocked(), + Database::ChessBase(_) => None, + } + } + + /// Games (not guiding texts). + pub fn games(&self) -> usize { + match self { + Database::Pgn(db) => db.len() - db.catalog().texts(), + Database::ChessBase(b) => b.games(), + } + } + + /// Guiding texts (of a ChessBase database, or of one converted to PGN). + pub fn texts(&self) -> usize { + match self { + Database::Pgn(db) => db.catalog().texts(), + Database::ChessBase(b) => b.texts(), + } + } + + /// The table row of record `index`. + pub fn row(&self, index: usize) -> chessbase::base::Row { + match self { + Database::Pgn(db) => db + .entries() + .get(index) + .map(|e| pgn_catalog::Catalog::row(e, e.moves())) + .unwrap_or_default(), + Database::ChessBase(b) => b.row(index), + } + } + + /// Records that pass `filter`, sorted; `None` when cancelled. + pub fn query( + &self, + filter: &chessbase::base::Filter, + sort: chessbase::base::SortKey, + ascending: bool, + scanned: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option> { + match self { + Database::Pgn(db) => { + db.catalog() + .query(db.entries(), filter, sort, ascending, scanned, cancel) + } + Database::ChessBase(b) => b.query(filter, sort, ascending, scanned, cancel), + } + } + + pub fn sort_records( + &self, + records: &mut Vec, + sort: chessbase::base::SortKey, + ascending: bool, + ) { + match self { + Database::Pgn(db) => db.catalog().sort_records(records, sort, ascending), + Database::ChessBase(b) => b.sort_records(records, sort, ascending), + } + } + + pub fn suggest_players( + &self, + query: &str, + limit: usize, + ) -> (Vec, usize) { + match self { + Database::Pgn(db) => db.catalog().suggest_players(query, limit), + Database::ChessBase(b) => b.suggest_players(query, limit), + } + } + + /// The name of player `id` (from a suggestion), as the game list shows it. + pub fn player_name(&self, id: u32) -> &str { + match self { + Database::Pgn(db) => db.catalog().player_name(id), + Database::ChessBase(b) => b.player_name(id), + } + } + + pub fn suggest_events( + &self, + query: &str, + limit: usize, + ) -> (Vec, usize) { + match self { + Database::Pgn(db) => db.catalog().suggest_events(query, limit), + Database::ChessBase(b) => b.suggest_events(query, limit), + } + } + + /// Most games have no result: a book of chapters (continuations count chapters). + pub fn books(&self) -> bool { + match self { + Database::Pgn(db) => db.catalog().books(), + Database::ChessBase(_) => false, + } + } + + /// The record could not be read cleanly (structure or encoding problems). + pub fn damaged(&self, index: usize) -> bool { + match self { + Database::Pgn(db) => db + .entries() + .get(index) + .is_some_and(|e| e.flags.has_structure_issues || e.flags.has_decode_errors), + Database::ChessBase(_) => false, + } + } + + /// The position search is ready (a PGN database builds its table on first use). + pub fn positions_ready(&self) -> bool { + match self { + Database::Pgn(db) => db.positions.lock().is_ok_and(|t| t.is_some()), + Database::ChessBase(_) => true, + } + } + + /// Which fields at least one game has (ChessBase databases: all of them). + pub fn filled(&self) -> pgn_catalog::Filled { + match self { + Database::Pgn(db) => db.catalog().filled(), + Database::ChessBase(_) => pgn_catalog::Filled { + eco: true, + annotator: true, + elo: true, + year: true, + }, + } + } + + pub fn as_chessbase(&self) -> Option<&Base> { + match self { + Database::ChessBase(b) => Some(b), + Database::Pgn(_) => None, + } + } +} + +/// Number of records of the ChessBase database whose `.cbh` file is `path`, from the +/// file size (each record and the header take 46 bytes). +pub fn chessbase_records(path: &Path) -> Option { + let len = std::fs::metadata(path).ok()?.len(); + Some((len / 46).saturating_sub(1)) +} + +/// An opened database with what is worth telling the user about the conversion. +pub struct Opened { + pub db: Database, + pub format: Format, + /// Problems and remarks, one line each (empty for a clean import). + pub notes: Vec, +} + +/// True if the file's extension is one [`open`] handles. +pub fn is_supported(path: &Path) -> bool { + path.extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .is_some_and(|e| EXTENSIONS.contains(&e.as_str())) +} + +/// Opens `path`. Plain PGN files are read as before; other formats are recognized +/// by extension and by content. +pub fn open( + path: &Path, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let ext = path + .extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + let io_err = |source| ImportError::Io { + path: path.to_owned(), + source, + }; + match ext.as_str() { + "cbz" => return Err(ImportError::Unsupported(Unsupported::Encrypted)), + "2cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBase2)), + "cbh" if chessbase_records(path).is_some_and(|n| n >= LARGE_CHESSBASE) => { + let base = Base::open( + path, + &mut |done, total| { + progress(ScanProgress { + bytes_done: done as usize, + bytes_total: total as usize, + games: 0, + }) + }, + cancel, + )?; + let notes = base.notes().to_vec(); + return Ok(Opened { + db: Database::ChessBase(Box::new(base)), + format: Format::ChessBase, + notes, + }); + } + "cbh" => { + let files = chessbase::Files::from_dir(path)?; + let part = convert_chessbase(&files)?; + return finish(part.pgn, Format::ChessBase, part.notes, progress, cancel); + } + _ => {} + } + // Content decides for archives (whatever their extension); anything else is PGN. + let mut head = [0u8; 8]; + { + use std::io::Read; + let mut f = std::fs::File::open(path).map_err(io_err)?; + let n = f.read(&mut head).map_err(io_err)?; + if n < head.len() { + head[n..].fill(0); + } + } + if let Some(kind) = archive::sniff(&head) { + let bytes = std::fs::read(path).map_err(io_err)?; + let format = match kind { + archive::Kind::Zip => Format::Zip, + archive::Kind::SevenZip => Format::SevenZip, + }; + let (pgn, notes) = open_archive(&bytes, kind, cancel)?; + return finish(pgn, format, notes, progress, cancel); + } + if ext == "cbv" || cbv::looks_like_cbv(&head) && ext != "pgn" { + let bytes = std::fs::read(path).map_err(io_err)?; + let part = open_cbv(&bytes)?; + return finish( + part.pgn, + Format::ChessBaseArchive, + part.notes, + progress, + cancel, + ); + } + let db = PgnDatabase::open(path, progress, cancel)?; + Ok(Opened { + db: Database::Pgn(PgnDb::new(db)), + format: Format::Pgn, + notes: Vec::new(), + }) +} + +/// Opens a database given as its content, without the file system (Android hands +/// over file descriptors, not paths): PGN, `.zip`, `.7z` and `.cbv`; `name` is the file +/// name, for its extension. A ChessBase database is several files: see +/// [`open_chessbase_files`]. +pub fn open_bytes( + name: &str, + bytes: Vec, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let ext = name + .rsplit_once('.') + .map(|(_, e)| e.to_lowercase()) + .unwrap_or_default(); + match ext.as_str() { + "cbz" => return Err(ImportError::Unsupported(Unsupported::Encrypted)), + "2cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBase2)), + "cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBaseFiles)), + _ => {} + } + if let Some(kind) = archive::sniff(&bytes) { + let format = match kind { + archive::Kind::Zip => Format::Zip, + archive::Kind::SevenZip => Format::SevenZip, + }; + let (pgn, notes) = open_archive(&bytes, kind, cancel)?; + return finish(pgn, format, notes, progress, cancel); + } + if ext == "cbv" || cbv::looks_like_cbv(&bytes) && ext != "pgn" { + let part = open_cbv(&bytes)?; + return finish( + part.pgn, + Format::ChessBaseArchive, + part.notes, + progress, + cancel, + ); + } + let db = PgnDatabase::from_bytes(bytes, None, progress, cancel)?; + Ok(Opened { + db: Database::Pgn(PgnDb::new(db)), + format: Format::Pgn, + notes: Vec::new(), + }) +} + +/// Opens a ChessBase database from the contents of its files (`.cbh`, `.cbg`, +/// `.cba`, …: `files` are (file name, content)), converted into PGN in memory like the +/// databases inside archives. Meant for databases of a phone's size, not Mega. +pub fn open_chessbase_files( + cbh_name: &str, + files: &[(String, Vec)], + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let members = chessbase::Files::from_members( + cbh_name, + files.iter().map(|(n, d)| (n.as_str(), d.as_slice())), + ); + let part = convert_chessbase(&members)?; + finish(part.pgn, Format::ChessBase, part.notes, progress, cancel) +} + +/// [`open_chessbase_files`] taking the contents: each file's bytes are let go once +/// the database is converted (the browser reads databases near its memory's limit). +pub fn open_chessbase_owned( + cbh_name: &str, + files: Vec<(String, Vec)>, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let members = chessbase::Files::from_owned(cbh_name, files); + let part = convert_chessbase(&members)?; + drop(members); + finish(part.pgn, Format::ChessBase, part.notes, progress, cancel) +} + +/// What files the user chose (or found in a chosen folder) make: databases, each its +/// files' places in the list (the database's own file first: its `.cbh` for a +/// ChessBase one, with the files the reader uses after it), and ChessBase databases +/// some files of which are not among them. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Chosen { + pub databases: Vec>, + /// The database's name (the `.cbh` file's, or a part's when it is not there). + pub incomplete: Vec, +} + +/// Groups the files `names` into databases (see [`Chosen`]). A ChessBase database is +/// its `.cbh` and the files of the same name beside it; files of other kinds are +/// databases of their own — in a folder only those of [`EXTENSIONS`], when the user +/// chose them, any (the content decides, as in [`open`]). +pub fn group_chosen(names: &[&str], folder: bool) -> Chosen { + let lower: Vec = names.iter().map(|n| n.to_lowercase()).collect(); + let ext = |i: usize| { + lower[i] + .rsplit_once('.') + .map(|(_, e)| e.to_owned()) + .unwrap_or_default() + }; + let stem = |i: usize| { + lower[i] + .rsplit_once('.') + .map_or(lower[i].as_str(), |(s, _)| s) + .to_owned() + }; + let bases: Vec = (0..names.len()).filter(|&i| ext(i) == "cbh").collect(); + let mut chosen = Chosen::default(); + let mut taken = vec![false; names.len()]; + for &cbh in &bases { + let parts: Vec = (0..names.len()) + .filter(|&j| j != cbh && stem(j) == stem(cbh)) + .collect(); + for &j in &parts { + taken[j] = true; + } + taken[cbh] = true; + let has = |e: &str| e == "cbh" || parts.iter().any(|&j| ext(j) == e); + if chessbase::REQUIRED.iter().all(|e| has(e)) { + let mut db = vec![cbh]; + db.extend( + parts + .into_iter() + .filter(|&j| chessbase::USED.contains(&ext(j).as_str())), + ); + chosen.databases.push(db); + } else { + chosen.incomplete.push(names[cbh].to_owned()); + } + } + for i in 0..names.len() { + if taken[i] { + continue; + } + let e = ext(i); + if chessbase::USED.contains(&e.as_str()) { + // A part of a ChessBase database without its .cbh: one note per database. + taken[i] = true; + let own = names[i].rsplit_once('.').map_or(names[i], |(s, _)| s); + let name = format!("{own}.cbh"); + if !chosen.incomplete.contains(&name) { + chosen.incomplete.push(name); + } + } else if !folder || EXTENSIONS.contains(&e.as_str()) { + chosen.databases.push(vec![i]); + } + } + chosen +} + +/// A converted part of a database: UTF-8 PGN and notes. +struct Part { + pgn: String, + notes: Vec, +} + +fn convert_chessbase(files: &chessbase::Files) -> Result { + let c = chessbase::convert(files)?; + Ok(Part { + pgn: c.pgn, + notes: c.notes, + }) +} + +fn open_cbv(bytes: &[u8]) -> Result { + let members = cbv::unpack(bytes)?; + let cbh: Vec<&str> = members + .iter() + .map(|m| m.name.as_str()) + .filter(|n| n.to_lowercase().ends_with(".cbh")) + .collect(); + let Some(first) = cbh.first() else { + return Err(ImportError::Corrupt( + "the ChessBase archive holds no database (.cbh)".into(), + )); + }; + let files = chessbase::Files::from_members( + first, + members.iter().map(|m| (m.name.as_str(), m.data.as_slice())), + ); + convert_chessbase(&files) +} + +/// Every database in an archive: PGN files, ChessBase databases and ChessBase +/// archives, in the order they are stored. A database whose games are exactly those +/// of one already taken (an archive often holds a ChessBase database both unpacked +/// and as `.cbv`) is left out. +fn open_archive( + bytes: &[u8], + kind: archive::Kind, + cancel: &AtomicBool, +) -> Result<(String, Vec), ImportError> { + let wanted = |name: &str| { + let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or(""); + ext == "pgn" || ext == "cbv" || chessbase_member(ext) + }; + let entries = archive::read(bytes, kind, &wanted)?; + let mut parts: Vec<(String, Part)> = Vec::new(); + let mut skipped = Vec::new(); + for e in &entries { + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + return Err(ImportError::Cancelled); + } + let lower = e.name.to_lowercase(); + let part = if lower.ends_with(".pgn") { + Ok(Part { + pgn: decode_pgn(&e.data), + notes: Vec::new(), + }) + } else if lower.ends_with(".cbv") { + open_cbv(&e.data) + } else if lower.ends_with(".cbh") { + let files = chessbase::Files::from_members( + &e.name, + entries.iter().map(|m| (m.name.as_str(), m.data.as_slice())), + ); + convert_chessbase(&files) + } else { + continue; + }; + match part { + Ok(p) if parts.iter().any(|(_, q)| q.pgn == p.pgn) => skipped.push(e.name.clone()), + Ok(p) => parts.push((e.name.clone(), p)), + Err(err) => parts.push(( + e.name.clone(), + Part { + pgn: String::new(), + notes: vec![err.to_string()], + }, + )), + } + } + if parts.iter().all(|(_, p)| p.pgn.is_empty()) { + if let Some((_, p)) = parts.into_iter().find(|(_, p)| !p.notes.is_empty()) { + return Err(ImportError::Corrupt(p.notes.join("; "))); + } + return Err(ImportError::Empty); + } + let several = parts.len() > 1; + let mut pgn = String::new(); + let mut notes = Vec::new(); + for (name, p) in parts { + for n in p.notes { + notes.push(if several { format!("{name}: {n}") } else { n }); + } + if !p.pgn.is_empty() { + pgn.push_str(&p.pgn); + if !pgn.ends_with("\n\n") { + pgn.push_str("\n\n"); + } + } + } + for s in skipped { + notes.push(format!( + "{s}: the same games as another database in the archive, skipped" + )); + } + Ok((pgn, notes)) +} + +fn chessbase_member(ext: &str) -> bool { + matches!(ext, "cbh" | "cbg" | "cba" | "cbp" | "cbt" | "cbc") +} + +/// PGN from an archive member, as UTF-8 (its own encoding detected). +fn decode_pgn(bytes: &[u8]) -> String { + let enc = detect_encoding(bytes).encoding; + enc.decode(bytes).0.into_owned() +} + +fn finish( + pgn: String, + format: Format, + notes: Vec, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let db = PgnDatabase::from_bytes(pgn.into_bytes(), Some(TextEncoding::Utf8), progress, cancel)?; + Ok(Opened { + db: Database::Pgn(PgnDb::new(db)), + format, + notes, + }) +} + +#[cfg(test)] +mod chosen_tests { + use super::*; + + #[test] + fn files_chosen_make_databases() { + // A whole ChessBase set (case of Windows copies), a PGN, a text file. + let names = [ + "Base.CBH", + "base.cbg", + "Base.cba", + "Base.cbj", + "Base.ini", + "games.pgn", + "x.txt", + ]; + let c = group_chosen(&names, false); + // The settings file is the database's (ignored); a file chosen opens by content. + assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5], vec![6]]); + assert!(c.incomplete.is_empty()); + // In a folder only databases: no text files. + let c = group_chosen(&names, true); + assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5]]); + } + + #[test] + fn a_cbh_alone_or_parts_alone_are_incomplete() { + let c = group_chosen(&["Mega Database 2026.cbh"], false); + assert!(c.databases.is_empty()); + assert_eq!(c.incomplete, vec!["Mega Database 2026.cbh".to_owned()]); + let c = group_chosen(&["Mega.cbg", "Mega.cba"], false); + assert!(c.databases.is_empty()); + assert_eq!(c.incomplete, vec!["Mega.cbh".to_owned()]); + } +} diff --git a/crates/chess-import/src/memory.rs b/crates/chess-import/src/memory.rs new file mode 100644 index 0000000..71a20d1 --- /dev/null +++ b/crates/chess-import/src/memory.rs @@ -0,0 +1,27 @@ +//! What the machine has: total and available memory, for choosing between keeping +//! an index in memory and reading it from disk (and for the bench report). + +use sysinfo::{MemoryRefreshKind, RefreshKind, System}; + +fn system() -> System { + System::new_with_specifics(RefreshKind::nothing().with_memory(MemoryRefreshKind::everything())) +} + +/// Bytes of memory the system reports as available to new allocations without +/// swapping (Linux `MemAvailable`; the other systems' equivalent). `None` when unknown. +/// `CP_MEMORY_LIMIT=` caps it (a dev hook: the low-memory paths on a big machine). +pub fn available() -> Option { + let real = Some(system().available_memory()).filter(|n| *n > 0); + match std::env::var("CP_MEMORY_LIMIT") + .ok() + .and_then(|v| v.trim().parse::().ok()) + { + Some(limit) => Some(real.unwrap_or(u64::MAX).min(limit * 1_000_000)), + None => real, + } +} + +/// Bytes of physical memory. +pub fn total() -> Option { + Some(system().total_memory()).filter(|n| *n > 0) +} diff --git a/crates/chess-import/src/parallel.rs b/crates/chess-import/src/parallel.rs new file mode 100644 index 0000000..99c0c30 --- /dev/null +++ b/crates/chess-import/src/parallel.rs @@ -0,0 +1,58 @@ +//! Worker threads of the parallel passes (booster, position search, opening tallies). +//! +//! A target without threads (WebAssembly in a browser: `std::thread::spawn` panics +//! there) runs every pass on the calling thread; so does a pass with one worker. + +/// Workers for a parallel pass: the threads the system offers, `fallback` when it +/// cannot tell; always one where there are no threads. +pub(crate) fn threads(fallback: usize) -> usize { + if cfg!(target_family = "wasm") { + return 1; + } + std::thread::available_parallelism().map_or(fallback, |n| n.get()) +} + +/// `work` for every item, each on its own scoped thread, results in the items' order +/// (`None`: that worker panicked). One item runs on the calling thread. +pub(crate) fn map(items: Vec, work: F) -> Vec> +where + I: Send, + T: Send, + F: Fn(I) -> T + Sync, +{ + if items.len() <= 1 { + return items.into_iter().map(|i| Some(work(i))).collect(); + } + let work = &work; + std::thread::scope(|s| { + let handles: Vec<_> = items + .into_iter() + .map(|i| s.spawn(move || work(i))) + .collect(); + handles.into_iter().map(|h| h.join().ok()).collect() + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_order_and_runs_one_inline() { + let out = map(vec![3, 1, 2], |n| n * 10); + assert_eq!(out, vec![Some(30), Some(10), Some(20)]); + let here = std::thread::current().id(); + let one = map(vec![()], |()| std::thread::current().id()); + assert_eq!(one, vec![Some(here)]); + assert!(map(Vec::::new(), |n| n).is_empty()); + } + + #[test] + fn a_panicking_worker_gives_none() { + let out = map(vec![0, 1], |n| { + assert!(n == 0, "worker {n}"); + n + }); + assert_eq!(out, vec![Some(0), None]); + } +} diff --git a/crates/chess-import/src/pgn_catalog.rs b/crates/chess-import/src/pgn_catalog.rs new file mode 100644 index 0000000..6acfc21 --- /dev/null +++ b/crates/chess-import/src/pgn_catalog.rs @@ -0,0 +1,1031 @@ +//! The game list of a PGN database with the filters, sorting and name suggestions of a +//! ChessBase database ([`crate::chessbase::base`]): built from the tags read when the +//! file was opened, so a filter is a pass over a few arrays in memory. Fields a file +//! does not have (no ECO, no Annotator) simply match nothing when filtered on. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use chess_core::pgn::GameEntry; + +use crate::chessbase::base::{ + EloRule, Filter, Names, Outcome, RecordKind, Row, Side, SortKey, Suggestion, fold, name_table, + words, +}; + +/// The tag the ChessBase converter gives a guiding text (its title is the `White` +/// tag): such a record is a text, not a game, as in the ChessBase database. +pub const TEXT_TAG: &str = "CbText"; + +/// A record of a PGN converted from ChessBase that was a guiding text. +pub fn is_text(e: &GameEntry) -> bool { + e.tag(TEXT_TAG).is_some() +} + +/// What a filter and a sort need of each game, one array per field. +pub struct Catalog { + players: Names, + events: Names, + white: Vec, + black: Vec, + event: Vec, + /// Folded `Annotator` tags. + annotator: Vec, + /// `yyyymmdd` with unknown parts 0; 0 for no date. + date: Vec, + /// When the game was played, for sorting: `yyyymmdd` × 100 000 + seconds of the day + /// (`UTCDate` and `UTCTime` when both are there, as online games have them). + when: Vec, + white_elo: Vec, + black_elo: Vec, + result: Vec, + /// ECO as a number 0 (A00) … 499 (E99). + eco: Vec>, + moves: Vec, + comments: Vec, + variations: Vec, + /// Which fields at least one game has (an empty result says so, §9.8). + filled: Filled, + /// Most games have no result: a book, whose continuations count chapters. + books: bool, + /// Guiding texts (from a converted ChessBase database). + text: Vec, + texts: usize, +} + +/// Fields at least one game of the database has. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Filled { + pub eco: bool, + pub annotator: bool, + pub elo: bool, + pub year: bool, +} + +/// "2026.10.18", "2026-10-18", "2026/10/18", "1997.05.??", "2010" → yyyymmdd (unknown +/// parts 0); 0 without a year. +pub fn date_number(date: &str) -> u32 { + let mut parts = date.trim().split(['.', '-', '/']); + let num = |s: Option<&str>, max: u32| -> u32 { + s.filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())) + .and_then(|s| s.parse::().ok()) + .filter(|n| *n <= max) + .unwrap_or(0) + }; + let year = num(parts.next(), 9999); + if !(1..=9999).contains(&year) { + return 0; + } + year * 10000 + num(parts.next(), 12) * 100 + num(parts.next(), 31) +} + +/// yyyymmdd → the date as the table shows it ("18.10.2026", "10.2026", "2026"), for the +/// quick search. +fn shown_date(d: u32) -> String { + let (y, m, day) = (d / 10000, d / 100 % 100, d % 100); + match (y, m, day) { + (0, ..) => String::new(), + (y, 0, _) => y.to_string(), + (y, m, 0) => format!("{m:02}.{y}"), + (y, m, day) => format!("{day:02}.{m:02}.{y}"), + } +} + +/// "13:05:09" → seconds of the day. +fn seconds(time: &str) -> Option { + let mut parts = time.trim().split(':').map(|p| p.parse::().ok()); + let (h, m, s) = ( + parts.next()??, + parts.next()??, + parts.next().flatten().unwrap_or(0), + ); + (h < 24 && m < 60 && s < 61).then_some(h * 3600 + m * 60 + s) +} + +/// "2026-10-18" → "2026.10.18": the PGN way, as the table shows dates. +fn pgn_date(date: &str) -> String { + date.trim().replace(['-', '/'], ".") +} + +/// "B90", "b90a", "B90 Sicilian" → 190 (A00 = 0 … E99 = 499): the first three +/// characters. +fn eco_of(tag: &str) -> Option { + let t = tag.trim().as_bytes(); + let t = t.get(..3)?; + if !(b'A'..=b'E').contains(&t[0].to_ascii_uppercase()) || !t[1..].iter().all(u8::is_ascii_digit) + { + return None; + } + Some( + u16::from(t[0].to_ascii_uppercase() - b'A') * 100 + + u16::from(t[1] - b'0') * 10 + + u16::from(t[2] - b'0'), + ) +} + +fn outcome(result: Option<&str>) -> Outcome { + match result.map(str::trim) { + Some("1-0") => Outcome::WhiteWins, + Some("0-1") => Outcome::BlackWins, + Some("1/2-1/2" | "½-½") => Outcome::Draw, + _ => Outcome::Unknown, + } +} + +/// A name the way a list shows it, spaces squeezed; none for "?", "-" and "" (PGN's +/// unknown). +fn known(name: Option<&str>) -> String { + let n = name + .unwrap_or("") + .split_whitespace() + .collect::>() + .join(" "); + if n == "?" || n == "-" { + String::new() + } else { + n + } +} + +/// When the game was played as yyyymmdd: `Date`, or `UTCDate` when `Date` has no year. +fn game_date(e: &GameEntry) -> u32 { + let d = date_number(e.date().unwrap_or("")); + if d / 10000 > 0 { + d + } else { + date_number(e.tag("UTCDate").unwrap_or("")) + } +} + +/// The place of a game, from `Site`: not "?", not a link (Lichess and Chess.com put the +/// game's address there). +fn place(e: &GameEntry) -> String { + let site = known(e.tag("Site")); + if site.contains("://") { + String::new() + } else { + site + } +} + +/// A tournament as ChessBase names it: "Title (place) year", the place and the year +/// only when the title does not have them already. +fn event_name(e: &GameEntry) -> String { + let title = known(e.event()); + let place = place(e); + let mut name = if !place.is_empty() && !title.contains(&place) { + if title.is_empty() { + place + } else { + format!("{title} ({place})") + } + } else { + title + }; + if name.is_empty() { + return name; + } + let year = game_date(e) / 10000; + if year > 0 && !name.contains(&year.to_string()) { + name = format!("{name} {year}"); + } + name +} + +/// Ids of the distinct names, in first-seen order, and each game's id. +fn intern(values: impl Iterator) -> (Vec, Vec) { + let mut ids = std::collections::HashMap::new(); + let mut shown = Vec::new(); + let of = values + .map(|v| { + *ids.entry(v.clone()).or_insert_with(|| { + shown.push(v); + shown.len() as u32 - 1 + }) + }) + .collect(); + (shown, of) +} + +impl Catalog { + pub fn build(entries: &[GameEntry]) -> Catalog { + // White and Black share one list: a player is the same whichever colour. + // A text has a title, not players. + let player = |e: &GameEntry, name: Option<&str>| { + if is_text(e) { + String::new() + } else { + known(name) + } + }; + let (names, ids) = intern( + entries + .iter() + .flat_map(|e| [player(e, e.white()), player(e, e.black())]), + ); + let white: Vec = ids.iter().step_by(2).copied().collect(); + let black: Vec = ids.iter().skip(1).step_by(2).copied().collect(); + let mut players = Names::new(names); + for sides in ids.as_chunks::<2>().0 { + players.count_player_game(sides[0], sides[1]); + } + let (event_names, event) = intern(entries.iter().map(event_name)); + let mut events = Names::new(event_names); + for &id in &event { + events.count(id); + } + let elo = |v: Option| v.and_then(|v| u16::try_from(v).ok()).unwrap_or(0); + let date: Vec = entries.iter().map(game_date).collect(); + let when: Vec = entries + .iter() + .zip(&date) + .map( + |(e, &d)| match (e.tag("UTCDate"), e.tag("UTCTime").and_then(seconds)) { + (Some(u), Some(t)) if date_number(u) > 0 => { + u64::from(date_number(u)) * 100_000 + u64::from(t) + } + _ => u64::from(d) * 100_000, + }, + ) + .collect(); + let text: Vec = entries.iter().map(is_text).collect(); + let texts = text.iter().filter(|&&t| t).count(); + let decided = entries + .iter() + .filter(|e| outcome(e.result()) != Outcome::Unknown) + .count(); + let eco: Vec> = entries.iter().map(|e| e.eco().and_then(eco_of)).collect(); + let annotator: Vec = entries + .iter() + .map(|e| fold(e.tag("Annotator").unwrap_or(""))) + .collect(); + let white_elo: Vec = entries.iter().map(|e| elo(e.white_elo())).collect(); + let black_elo: Vec = entries.iter().map(|e| elo(e.black_elo())).collect(); + let filled = Filled { + eco: eco.iter().any(Option::is_some), + annotator: annotator.iter().any(|a| !a.trim().is_empty()), + elo: white_elo.iter().chain(&black_elo).any(|&e| e > 0), + year: date.iter().any(|&d| d / 10000 > 0), + }; + Catalog { + players, + events, + white, + black, + event, + annotator, + date, + when, + books: decided * 2 < entries.len() - texts, + text, + texts, + white_elo, + black_elo, + result: entries.iter().map(|e| outcome(e.result())).collect(), + eco, + moves: entries + .iter() + .map(|e| u16::try_from(e.moves()).unwrap_or(u16::MAX)) + .collect(), + comments: entries.iter().map(|e| e.flags.has_text_comments).collect(), + variations: entries.iter().map(|e| e.flags.has_variations).collect(), + filled, + } + } + + /// Which fields at least one game has. + pub fn filled(&self) -> Filled { + self.filled + } + + /// Guiding texts among the records. + pub fn texts(&self) -> usize { + self.texts + } + + /// Most games have no result (a book of chapters). + pub fn books(&self) -> bool { + self.books + } + + pub fn suggest_players(&self, query: &str, limit: usize) -> (Vec, usize) { + self.players.suggest(query, limit) + } + + /// A page of player names; an empty query lists every named player. + pub fn suggest_players_page( + &self, + query: &str, + start: usize, + limit: usize, + ) -> (Vec, usize) { + self.players.suggest_page(query, start, limit, true) + } + + /// Total, white and black games of a player (a self-game counts once in total). + pub fn player_counts(&self, id: u32) -> (u32, u32, u32) { + self.players.player_counts(id) + } + + /// Games of exactly player `id` on one side, in record order. Ids come from + /// [`Catalog::suggest_players_page`] and represent normalized distinct names; + /// a self-game is returned once for either selected side. + pub fn player_games( + &self, + id: u32, + side: Side, + scanned: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option> { + if self.player_name(id).is_empty() || !matches!(side, Side::White | Side::Black) { + return Some(Vec::new()); + } + let mut games = Vec::new(); + for i in 0..self.white.len() { + if i % 4096 == 0 { + if cancel.load(Ordering::Relaxed) { + return None; + } + scanned.store(i, Ordering::Relaxed); + } + let player = match side { + Side::White => self.white[i], + Side::Black => self.black[i], + Side::Any => continue, + }; + if !self.text[i] && player == id { + games.push(i as u32); + } + } + scanned.store(self.white.len(), Ordering::Relaxed); + (!cancel.load(Ordering::Relaxed)).then_some(games) + } + + pub fn suggest_events(&self, query: &str, limit: usize) -> (Vec, usize) { + self.events.suggest(query, limit) + } + + pub fn player_name(&self, id: u32) -> &str { + self.players.get(id) + } + + pub fn event_name(&self, id: u32) -> &str { + self.events.get(id) + } + + /// The table row of game `index`. + pub fn row(entry: &GameEntry, moves: u32) -> Row { + if is_text(entry) { + return Row { + kind: Some(RecordKind::Text), + title: known(entry.white()), + event: known(entry.event()), + round: known(entry.tag("Round")), + annotator: entry.tag("Annotator").unwrap_or("").trim().to_owned(), + result: "*", + ..Row::default() + }; + } + Row { + kind: Some(RecordKind::Game), + white: known(entry.white()), + black: known(entry.black()), + white_elo: entry + .white_elo() + .and_then(|v| u16::try_from(v).ok()) + .unwrap_or(0), + black_elo: entry + .black_elo() + .and_then(|v| u16::try_from(v).ok()) + .unwrap_or(0), + result: match outcome(entry.result()) { + Outcome::WhiteWins => "1-0", + Outcome::BlackWins => "0-1", + Outcome::Draw => "1/2-1/2", + Outcome::Unknown => "*", + }, + eco: entry + .eco() + .and_then(eco_of) + .map(crate::chessbase::base::eco_text), + chess960: entry.tag("Variant").is_some_and(|v| v.contains("960")), + event: known(entry.event()), + site: known(entry.tag("Site")), + date: pgn_date(if date_number(entry.date().unwrap_or("")) / 10000 > 0 { + entry.date().unwrap_or("") + } else { + entry.tag("UTCDate").unwrap_or("") + }), + round: known(entry.tag("Round")), + annotator: entry.tag("Annotator").unwrap_or("").trim().to_owned(), + moves: u8::try_from(moves).unwrap_or(u8::MAX), + has_variations: entry.flags.has_variations, + has_comments: entry.flags.has_text_comments, + title: String::new(), + } + } + + /// Indices of the games that pass `filter`, sorted (see `Base::query`). + pub fn query( + &self, + entries: &[GameEntry], + filter: &Filter, + sort: SortKey, + ascending: bool, + scanned: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option> { + let player_ids = name_table(&self.players, &filter.player); + let opponent_ids = name_table(&self.players, &filter.opponent); + let event_ids = name_table(&self.events, &filter.event); + let annotator = words(&filter.annotator); + // The quick search, word by word: the names it is in; the place, ECO and date of + // a game are looked at only when no name has the word. + let quick: Vec<(String, Vec, Vec)> = words(&filter.text) + .into_iter() + .map(|w| { + let (p, e) = (self.players.matching(&w), self.events.matching(&w)); + (w, p, e) + }) + .collect(); + let has = |ids: &Option>, id: u32| { + ids.as_ref() + .is_none_or(|t| t.get(id as usize).copied().unwrap_or(false)) + }; + let names = player_ids.is_some() || opponent_ids.is_some(); + let relative = filter.player_relative && player_ids.is_some(); + // A guiding text has only a tournament and an annotator: any other condition + // leaves it out, as in a ChessBase database. + let game_only = names + || filter.year_from.is_some() + || filter.year_to.is_some() + || filter.elo_min.is_some() + || !filter.eco.is_empty() + || !filter.outcomes.is_empty() + || filter.moves_from.is_some() + || filter.moves_to.is_some() + || filter.with_comments + || filter.with_variations; + let mut out = Vec::new(); + for i in 0..self.white.len() { + if i % 65536 == 0 { + if cancel.load(Ordering::Relaxed) { + return None; + } + scanned.store(i, Ordering::Relaxed); + } + if self.text[i] { + let at = |t: &Vec, id: u32| t.get(id as usize).copied().unwrap_or(false); + if !filter.games_only + && !game_only + && has(&event_ids, self.event[i]) + && annotator + .iter() + .all(|w| self.annotator[i].contains(w.as_str())) + && quick.iter().all(|(w, _, events)| { + at(events, self.event[i]) || self.annotator[i].contains(w.as_str()) + }) + { + out.push(i as u32); + } + continue; + } + let (white, black) = (self.white[i], self.black[i]); + let mut player_white = true; + let mut player_black = true; + if names { + let as_white = has(&player_ids, white) && has(&opponent_ids, black); + let as_black = has(&player_ids, black) && has(&opponent_ids, white); + player_white = as_white && filter.side != Side::Black; + player_black = as_black && filter.side != Side::White; + if !player_white && !player_black { + continue; + } + } + if !has(&event_ids, self.event[i]) + || !annotator + .iter() + .all(|w| self.annotator[i].contains(w.as_str())) + { + continue; + } + if filter.year_from.is_some() || filter.year_to.is_some() { + let year = self.date[i] / 10000; + if year == 0 + || filter.year_from.is_some_and(|y| year < u32::from(y)) + || filter.year_to.is_some_and(|y| year > u32::from(y)) + { + continue; + } + } + if let Some(min) = filter.elo_min { + let (we, bl) = (self.white_elo[i], self.black_elo[i]); + let ok = match filter.elo_rule { + EloRule::Both => we >= min && bl >= min, + EloRule::Either => we >= min || bl >= min, + EloRule::Average => { + we > 0 && bl > 0 && (u32::from(we) + u32::from(bl)) / 2 >= u32::from(min) + } + EloRule::Opponent if player_ids.is_some() => { + (player_white && bl >= min) || (player_black && we >= min) + } + EloRule::Opponent => we >= min || bl >= min, + }; + if !ok { + continue; + } + } + if !filter.eco.is_empty() { + let Some(code) = self.eco[i] else { continue }; + if !filter.eco.iter().any(|&(a, b)| (a..=b).contains(&code)) { + continue; + } + } + if !filter.outcomes.is_empty() { + let board = self.result[i]; + let wanted = |o: Outcome| filter.outcomes.contains(&o); + let ok = if relative && matches!(board, Outcome::WhiteWins | Outcome::BlackWins) { + // WhiteWins = the player won, BlackWins = the player lost. + let flipped = match board { + Outcome::WhiteWins => Outcome::BlackWins, + _ => Outcome::WhiteWins, + }; + (player_white && wanted(board)) || (player_black && wanted(flipped)) + } else { + wanted(board) + }; + if !ok { + continue; + } + } + let moves = self.moves[i]; + if filter.moves_from.is_some_and(|m| moves < m) + || filter.moves_to.is_some_and(|m| moves > m) + { + continue; + } + if (filter.with_comments && !self.comments[i]) + || (filter.with_variations && !self.variations[i]) + { + continue; + } + if !quick.is_empty() { + let at = |t: &Vec, id: u32| t.get(id as usize).copied().unwrap_or(false); + let e = entries.get(i); + let found = quick.iter().all(|(w, players, events)| { + at(players, white) + || at(players, black) + || at(events, self.event[i]) + || self.annotator[i].contains(w.as_str()) + || shown_date(self.date[i]).contains(w.as_str()) + || e.is_some_and(|e| { + ["Site", "ECO", "Date", "UTCDate"] + .iter() + .any(|t| e.tag(t).is_some_and(|v| fold(v).contains(w.as_str()))) + }) + }); + if !found { + continue; + } + } + out.push(i as u32); + } + scanned.store(self.white.len(), Ordering::Relaxed); + self.sort_records(&mut out, sort, ascending); + Some(out) + } + + /// Sorts game indices (in file order on entry) by `sort`; games without a value + /// (no rating, no date) stay at the end in both directions. + pub fn sort_records(&self, records: &mut Vec, sort: SortKey, ascending: bool) { + if sort == SortKey::Number { + records.sort_unstable(); + } else { + let mut keyed: Vec<(u64, u32)> = records + .iter() + .map(|&i| (self.sort_key(i as usize, sort), i)) + .collect(); + keyed.sort_unstable(); + *records = keyed.into_iter().map(|(_, i)| i).collect(); + } + if !ascending { + let split = records + .iter() + .position(|&i| self.sort_key(i as usize, sort) == u64::MAX) + .unwrap_or(records.len()); + records[..split].reverse(); + } + } + + fn sort_key(&self, i: usize, sort: SortKey) -> u64 { + if self.text[i] && !matches!(sort, SortKey::Number | SortKey::Event) { + return u64::MAX; + } + let none_if_zero = |v: u32| if v == 0 { u64::MAX } else { u64::from(v) }; + match sort { + SortKey::Number => i as u64, + SortKey::White => self.players.rank(self.white[i]), + SortKey::Black => self.players.rank(self.black[i]), + SortKey::WhiteElo => none_if_zero(self.white_elo[i].into()), + SortKey::BlackElo => none_if_zero(self.black_elo[i].into()), + SortKey::Result => match self.result[i] { + Outcome::WhiteWins => 0, + Outcome::Draw => 1, + Outcome::BlackWins => 2, + Outcome::Unknown => u64::MAX, + }, + SortKey::Moves => none_if_zero(self.moves[i].into()), + SortKey::Eco => self.eco[i].map_or(u64::MAX, u64::from), + SortKey::Event => self.events.rank(self.event[i]), + SortKey::Date => { + if self.when[i] == 0 { + u64::MAX + } else { + self.when[i] + } + } + SortKey::AverageElo => { + let (w, b) = (u64::from(self.white_elo[i]), u64::from(self.black_elo[i])); + if w == 0 || b == 0 { + u64::MAX + } else { + // The average first, then the date. + (((w + b) / 2) << 32) | u64::from(self.date[i]) + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::chessbase::base::NameFilter; + use chess_core::pgn::scan_games; + + fn catalog(pgn: &str) -> (Vec, Catalog) { + let e = scan_games( + pgn.as_bytes(), + chess_core::TextEncoding::Utf8, + &mut |_| {}, + &AtomicBool::new(false), + ) + .unwrap(); + let c = Catalog::build(&e); + (e, c) + } + + fn find(e: &[GameEntry], c: &Catalog, f: &Filter) -> Vec { + c.query( + e, + f, + SortKey::Number, + true, + &AtomicUsize::new(0), + &AtomicBool::new(false), + ) + .unwrap() + } + + fn name(t: &str) -> NameFilter { + NameFilter { + text: t.into(), + exact: None, + } + } + + const GAMES: &str = concat!( + "[Event \"Рапид 42, до 11 лет\"][Date \"2026-10-18\"][White \"Вафин Радель\"][WhiteElo \"1887\"]", + "[Black \"Макаров Ð�ртём\"][BlackElo \"1542\"][Result \"1-0\"]\n1. e4 { [%clk 0:10:07] } c5 2. Nf3 1-0\n", + "[Event \"Блиц\"][Site \"МоÑ�ква\"][Date \"2024.05.??\"][White \"Макаров Ð�ртём\"][WhiteElo \"1600\"]", + "[Black \"Hübner, Robert\"][BlackElo \"2600\"][Result \"0-1\"][ECO \"B90a\"]\n1. e4 { A long fight. } c5 (1... e5) 0-1\n", + "[Event \"Rated Blitz game\"][Site \"https://lichess.org/abc\"][Date \"????.??.??\"][UTCDate \"2023.01.02\"]", + "[White \"?\"][Black \"-\"][Result \"½-½\"]\n1. d4 1/2-1/2\n", + ); + + #[test] + fn names_events_and_sides() { + let (e, c) = catalog(GAMES); + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("макаров"), + ..Filter::default() + } + ), + vec![0, 1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("макаров"), + side: Side::White, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("hubner"), + ..Filter::default() + } + ), + vec![1] + ); + // «Ð�ртём» is typed «Ð�ртем»; the order of the words does not matter. + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("артем, макаров"), + ..Filter::default() + } + ), + vec![0, 1] + ); + // Spaces squeezed: «Вафин Радель» is one name. + assert_eq!(c.suggest_players("вафин", 5).0[0].name, "Вафин Радель"); + // "?" and "-" are no player. + assert_eq!(c.suggest_players("?", 5).1, 0); + // Tournaments as ChessBase names them; a link in Site is no place. + assert_eq!(c.suggest_events("блиц", 5).0[0].name, "Блиц (МоÑ�ква) 2024"); + assert_eq!( + c.suggest_events("rated", 5).0[0].name, + "Rated Blitz game 2023" + ); + assert_eq!( + find( + &e, + &c, + &Filter { + event: name("рапид 2026"), + ..Filter::default() + } + ), + vec![0] + ); + let (list, total) = c.suggest_players("макар", 5); + assert_eq!(total, 1); + assert_eq!(list[0].games, 2); + } + + #[test] + fn years_ratings_results_eco_moves_and_comments() { + let (e, c) = catalog(GAMES); + assert_eq!( + find( + &e, + &c, + &Filter { + year_from: Some(2025), + ..Filter::default() + } + ), + vec![0] + ); + // The year from UTCDate when Date has none. + assert_eq!( + find( + &e, + &c, + &Filter { + year_to: Some(2023), + ..Filter::default() + } + ), + vec![2] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + elo_min: Some(1550), + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + elo_min: Some(2000), + elo_rule: EloRule::Either, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + outcomes: vec![Outcome::Draw], + ..Filter::default() + } + ), + vec![2] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + eco: vec![(190, 199)], + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + moves_from: Some(2), + ..Filter::default() + } + ), + vec![0] + ); + // A clock is no comment. + assert_eq!( + find( + &e, + &c, + &Filter { + with_comments: true, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + with_variations: true, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + c.filled(), + Filled { + eco: true, + annotator: false, + elo: true, + year: true + } + ); + } + + #[test] + fn quick_search_finds_each_word_in_some_field() { + let (e, c) = catalog(GAMES); + let text = |t: &str| Filter { + text: t.into(), + ..Filter::default() + }; + assert_eq!(find(&e, &c, &text("макаров 2024")), vec![1]); + assert_eq!(find(&e, &c, &text("моÑ�ква b90")), vec![1]); + assert_eq!(find(&e, &c, &text("lichess")), vec![2]); + assert_eq!(find(&e, &c, &text("вафин блиц")), Vec::::new()); + } + + #[test] + fn sorting_and_rows() { + let (e, c) = catalog(GAMES); + let mut v = vec![0, 1, 2]; + c.sort_records(&mut v, SortKey::WhiteElo, false); + assert_eq!(v, vec![0, 1, 2]); + c.sort_records(&mut v, SortKey::WhiteElo, true); + // No rating: last in both directions. + assert_eq!(v, vec![1, 0, 2]); + c.sort_records(&mut v, SortKey::Date, true); + assert_eq!(v, vec![2, 1, 0]); + let r = Catalog::row(&e[0], e[0].moves()); + assert_eq!(r.date, "2026.10.18"); + assert_eq!(r.result, "1-0"); + assert!(!r.has_comments); + assert_eq!(Catalog::row(&e[1], 1).eco.as_deref(), Some("B90")); + let r = Catalog::row(&e[2], 1); + assert_eq!( + ( + r.white.as_str(), + r.black.as_str(), + r.result, + r.date.as_str() + ), + ("", "", "1/2-1/2", "2023.01.02") + ); + } + + #[test] + fn downloaded_games_by_the_time_they_were_played() { + // As a download writes them: one site's games oldest first, then the other's; + // two games of one day differ by their time. + let (_, c) = catalog(concat!( + "[UTCDate \"2026.01.01\"][UTCTime \"10:00:00\"] 1. e4 *\n", + "[UTCDate \"2026.03.01\"][UTCTime \"09:00:00\"] 1. d4 *\n", + "[UTCDate \"2026.03.01\"][UTCTime \"21:30:00\"] 1. c4 *\n", + "[UTCDate \"2026.02.01\"][UTCTime \"10:00:00\"] 1. Nf3 *\n", + )); + let mut v = vec![0, 1, 2, 3]; + c.sort_records(&mut v, SortKey::Date, false); + assert_eq!(v, vec![2, 1, 3, 0]); + } + + #[test] + fn guiding_texts_of_a_converted_chessbase_database() { + let (e, c) = catalog(concat!( + "[Event \"Course\"][White \"Strong and weak squares\"][Black \"\"][CbText \"1\"][Result \"*\"]\n{ A chapter. } *\n", + "[Event \"Course\"][White \"Karpov\"][Black \"Kasparov\"][Date \"1985.??.??\"][Result \"1-0\"]\n1. e4 1-0\n", + )); + assert_eq!(c.texts(), 1); + let r = Catalog::row(&e[0], 0); + assert_eq!( + (r.kind, r.title.as_str(), r.white.as_str()), + (Some(RecordKind::Text), "Strong and weak squares", "") + ); + // A text's title is no player. + assert_eq!(c.suggest_players("squares", 5).1, 0); + // Only the tournament and the annotator apply to a text. + assert_eq!( + find( + &e, + &c, + &Filter { + event: name("course"), + ..Filter::default() + } + ), + vec![0, 1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + year_from: Some(1900), + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + games_only: true, + ..Filter::default() + } + ), + vec![1] + ); + } + + #[test] + fn empty_names_come_last_both_ways() { + let (_, c) = catalog("[White \"B\"][Black \"?\"] *\n[White \"A\"][Black \"Z\"] *\n"); + let mut v = vec![0, 1]; + c.sort_records(&mut v, SortKey::Black, false); + assert_eq!(v, vec![1, 0]); + c.sort_records(&mut v, SortKey::Black, true); + assert_eq!(v, vec![1, 0]); + } + + #[test] + fn the_quick_search_finds_a_date_as_the_table_shows_it() { + let (e, c) = catalog(GAMES); + let text = |t: &str| Filter { + text: t.into(), + ..Filter::default() + }; + assert_eq!(find(&e, &c, &text("18.10.2026")), vec![0]); + assert_eq!(find(&e, &c, &text("2026-10")), vec![0]); + } + + #[test] + fn dates() { + assert_eq!(date_number("2026-10-18"), 20261018); + assert_eq!(date_number("1997.05.??"), 19970500); + assert_eq!(date_number("2010"), 20100000); + assert_eq!(date_number("????.??.??"), 0); + assert_eq!(date_number(""), 0); + } +} diff --git a/crates/chess-import/src/pgn_positions.rs b/crates/chess-import/src/pgn_positions.rs new file mode 100644 index 0000000..400c66c --- /dev/null +++ b/crates/chess-import/src/pgn_positions.rs @@ -0,0 +1,1008 @@ +//! Position search in a PGN database (books, collections: up to some hundred thousand +//! games): the positions of every game, variations included, are kept in memory once +//! built, so a search is a binary search in a sorted index plus a walk over the games +//! that reach the position. +//! +//! Layout. Every attached node of every game is a [`Node`] (8 bytes: parent, the move +//! that led to it, ply), games one after another, each in the order of its PGN text. +//! The index holds one entry per move of the tree (the key of the position before the +//! move, the node the move leads to) and one per line end (the key of the last +//! position, that node), sorted by key and node, so the entries of a game are +//! contiguous inside the range of a key. Per game: the first node and the tag values +//! the statistics need. About 20 bytes per node. +//! +//! Statistics. A game counts once among the matches, at its main line occurrence if +//! there is one, else (preferably reached by the moves of the query) at the first in +//! text order. Each distinct move the game plays from the position, in any branch, +//! adds the game once to that move; a game "ends here" when its main line ends in the +//! position (variation ends are not counted). See `docs/dev/import.md`. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use chess_core::{Game, MoveKind, PgnDatabase}; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Role, Square}; + +use crate::position::{self, Collector, GameResult, Match, PositionOutcome, PositionQuery}; + +/// `Node::parent` of a game's root. +const NO_PARENT: u32 = u32::MAX >> 1; +/// Flag in `Node::parent`: the node is in a variation (not the main line). +const VARIATION: u32 = 1 << 31; +/// Encoded teaching null move `--` (and anything that is not a normal move). +const NULL_MOVE: u16 = u16::MAX; +/// Nodes are numbered with 31 bits (an index entry keeps a flag in the lowest bit). +const MAX_NODES: usize = (1 << 31) - 1; +/// Games handed to a build thread at a time. +const CHUNK: usize = 32; +/// Index size from which it is sorted in parallel. +const PARALLEL_SORT: usize = 1 << 16; + +/// A position of a game: the node of the move tree that reaches it. +#[derive(Clone, Copy, Debug)] +struct Node { + /// Index of the parent node (`NO_PARENT` for the root), with the `VARIATION` flag. + parent: u32, + /// The move from the parent (see [`encode`]); unused for the root. + mv: u16, + /// Half-moves from the game's start (saturating). + ply: u16, +} + +impl Node { + fn parent(self) -> Option { + let p = self.parent & !VARIATION; + (p != NO_PARENT).then_some(p as usize) + } + + fn in_variation(self) -> bool { + self.parent & VARIATION != 0 + } +} + +/// What the statistics need from a game's tags, and whether it starts from the usual +/// position (only such a game can follow the query's move order). +#[derive(Clone, Copy, Debug)] +struct Meta { + result: GameResult, + white_elo: u16, + black_elo: u16, + year: u16, + standard_start: bool, +} + +/// The positions of all games of a database. +pub struct PositionTable { + nodes: Vec, + /// First node of each game, and the total at the end (`games + 1` values). + starts: Vec, + meta: Vec, + /// Index: position keys in ascending order ... + keys: Vec, + /// ... and per key `node << 1 | end`: the node a move from the position leads to, + /// or (`end` = 1) the node of the position itself where its line ends. + refs: Vec, +} + +/// Part of the table built by one thread: consecutive games from `first`, with node +/// numbers local to the chunk. +struct Chunk { + first: usize, + nodes: Vec, + starts: Vec, + meta: Vec, + entries: Vec<(u64, u32)>, +} + +impl PositionTable { + /// Parses every game (`progress` counts the games done). `None` when cancelled. + pub fn build( + db: &PgnDatabase, + progress: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option { + let games = db.len(); + let next = AtomicUsize::new(0); + let total = AtomicUsize::new(0); + let work = || -> Option> { + let mut chunks = Vec::new(); + loop { + let first = next.fetch_add(CHUNK, Ordering::Relaxed); + if first >= games { + return Some(chunks); + } + let mut chunk = Chunk { + first, + nodes: Vec::new(), + starts: Vec::new(), + meta: Vec::new(), + entries: Vec::new(), + }; + for index in first..(first + CHUNK).min(games) { + if cancel.load(Ordering::Relaxed) { + return None; + } + chunk.add_game(db, index, &total); + progress.fetch_add(1, Ordering::Relaxed); + } + chunks.push(chunk); + } + }; + let threads = std::thread::available_parallelism() + .map_or(1, |n| n.get()) + .min(games.div_ceil(CHUNK)) + .max(1); + let mut chunks = if threads == 1 { + work()? + } else { + let parts: Vec>> = std::thread::scope(|s| { + let handles: Vec<_> = (0..threads).map(|_| s.spawn(work)).collect(); + handles + .into_iter() + .map(|h| h.join().ok().flatten()) + .collect() + }); + let mut all = Vec::new(); + for part in parts { + all.extend(part?); + } + all + }; + if cancel.load(Ordering::Relaxed) { + return None; + } + chunks.sort_unstable_by_key(|c| c.first); + Self::assemble(chunks, cancel) + } + + /// Joins the chunks (in game order) into one table and sorts the index. + fn assemble(chunks: Vec, cancel: &AtomicBool) -> Option { + let total_nodes: usize = chunks.iter().map(|c| c.nodes.len()).sum(); + let total_entries: usize = chunks.iter().map(|c| c.entries.len()).sum(); + let games: usize = chunks.iter().map(|c| c.meta.len()).sum(); + let mut table = PositionTable { + nodes: Vec::with_capacity(total_nodes), + starts: Vec::with_capacity(games + 1), + meta: Vec::with_capacity(games), + keys: Vec::new(), + refs: Vec::new(), + }; + let mut parts = Vec::with_capacity(chunks.len()); + for chunk in chunks { + let offset = table.nodes.len() as u32; + table.nodes.extend(chunk.nodes.into_iter().map(|mut n| { + if n.parent().is_some() { + n.parent += offset; + } + n + })); + table.starts.extend(chunk.starts.iter().map(|s| s + offset)); + table.meta.extend(chunk.meta); + let mut entries = chunk.entries; + for e in &mut entries { + e.1 += offset << 1; + } + parts.push(entries); + } + table.starts.push(table.nodes.len() as u32); + if cancel.load(Ordering::Relaxed) { + return None; + } + let entries = sort_entries(parts, total_entries); + table.keys = entries.iter().map(|e| e.0).collect(); + table.refs = entries.iter().map(|e| e.1).collect(); + Some(table) + } + + /// Number of games. + pub fn games(&self) -> usize { + self.meta.len() + } + + /// Number of positions (nodes of all game trees, roots included). + pub fn positions(&self) -> usize { + self.nodes.len() + } + + /// Memory held by the table, in bytes. + pub fn memory(&self) -> usize { + self.nodes.capacity() * size_of::() + + self.starts.capacity() * size_of::() + + self.meta.capacity() * size_of::() + + self.keys.capacity() * size_of::() + + self.refs.capacity() * size_of::() + } + + /// Games among `candidates` (record indices in ascending order; `None`: all) + /// that reach the position, in the main line or a variation. + pub fn search( + &self, + db: &PgnDatabase, + candidates: Option<&[u32]>, + query: &PositionQuery, + cancel: &AtomicBool, + ) -> Option { + let _ = db; + let key = query.key(); + let lo = self.keys.partition_point(|&k| k < key); + let hi = lo + self.keys[lo..].partition_point(|&k| k == key); + let line: Option> = query + .line + .as_ref() + .map(|l| l.iter().map(|m| encode(position::uci(m))).collect()); + let mut collector = Collector::default(); + let mut cand = 0; + let mut game = 0; + let mut i = lo; + while i < hi { + if (i - lo) % 4096 == 0 && cancel.load(Ordering::Relaxed) { + return None; + } + let node = self.refs[i] >> 1; + if node >= self.starts[game + 1] { + game += self.starts[game..].partition_point(|&s| s <= node) - 1; + } + let end = self.starts[game + 1]; + let mut j = i + 1; + while j < hi && self.refs[j] >> 1 < end { + j += 1; + } + let wanted = match candidates { + None => true, + Some(c) => { + cand += c[cand..].partition_point(|&g| (g as usize) < game); + c.get(cand).is_some_and(|&g| g as usize == game) + } + }; + if wanted { + self.collect(game, &self.refs[i..j], line.as_deref(), &mut collector); + } + i = j; + } + Some(collector.finish(&query.position)) + } + + /// The first main-line occurrence of every game, not a variation or a repetition. + pub fn search_first( + &self, + db: &PgnDatabase, + candidates: Option<&[u32]>, + query: &PositionQuery, + cancel: &AtomicBool, + ) -> Option { + let _ = db; + let key = query.key(); + let lo = self.keys.partition_point(|&k| k < key); + let hi = lo + self.keys[lo..].partition_point(|&k| k == key); + let line: Option> = query + .line + .as_ref() + .map(|l| l.iter().map(|m| encode(position::uci(m))).collect()); + let mut collector = Collector::default(); + let mut cand = 0; + let mut game = 0; + let mut i = lo; + while i < hi { + if (i - lo) % 4096 == 0 && cancel.load(Ordering::Relaxed) { + return None; + } + let node = self.refs[i] >> 1; + if node >= self.starts[game + 1] { + game += self.starts[game..].partition_point(|&s| s <= node) - 1; + } + let end = self.starts[game + 1]; + let mut j = i + 1; + while j < hi && self.refs[j] >> 1 < end { + j += 1; + } + let wanted = match candidates { + None => true, + Some(c) => { + cand += c[cand..].partition_point(|&g| (g as usize) < game); + c.get(cand).is_some_and(|&g| g as usize == game) + } + }; + if wanted { + self.collect_first(game, &self.refs[i..j], line.as_deref(), &mut collector); + } + i = j; + } + Some(collector.finish(&query.position)) + } + + /// Adds game `game` whose entries for the position are `refs`. + fn collect(&self, game: usize, refs: &[u32], line: Option<&[u16]>, out: &mut Collector) { + let meta = self.meta[game]; + // Best occurrence: main line first, then reached by the query's moves, then + // the first in text order (smallest node). + let mut best: Option<(bool, bool, usize)> = None; + // Distinct moves played from the position, with "in the main line". + let mut moves: Vec<(u16, bool)> = Vec::new(); + let mut ended = false; + for &r in refs { + let node = (r >> 1) as usize; + let at = if r & 1 == 1 { + if !self.nodes[node].in_variation() { + ended = true; + } + node + } else { + let n = self.nodes[node]; + let main = !n.in_variation(); + match moves.iter_mut().find(|m| m.0 == n.mv) { + Some(m) => m.1 |= main, + None => moves.push((n.mv, main)), + } + n.parent().unwrap_or(node) + }; + let rank = ( + self.nodes[at].in_variation(), + !self.same_order(at, meta, line), + at, + ); + if best.is_none_or(|b| rank < b) { + best = Some(rank); + } + } + let Some((in_variation, other_order, at)) = best else { + return; + }; + let index = game as u32; + // The move after the chosen occurrence is the game's `next` (none when the + // game ends there, whatever its other branches play). + let first = self.first_child_move(at, refs); + out.add_match_with_next(Match { + index, + ply: u32::from(self.nodes[at].ply), + same_order: !other_order, + in_variation, + next: first.map(decode), + }); + if let Some(pos) = moves.iter().position(|m| Some(m.0) == first) { + moves.swap(0, pos); + } + let result = meta.result; + for (mv, main) in moves { + out.add_continuation( + index, + Some(decode(mv)), + main, + result, + meta.white_elo, + meta.black_elo, + meta.year, + ); + } + if ended { + out.add_continuation( + index, + None, + true, + result, + meta.white_elo, + meta.black_elo, + meta.year, + ); + } + } + + fn collect_first(&self, game: usize, refs: &[u32], line: Option<&[u16]>, out: &mut Collector) { + let meta = self.meta[game]; + let mut occurrences = refs.iter().filter_map(|&r| { + let node = (r >> 1) as usize; + (!self.nodes[node].in_variation()).then_some((node, r & 1 == 1)) + }); + let Some((raw_at, ended)) = occurrences.next() else { + return; + }; + let at = if ended { + raw_at + } else { + self.nodes[raw_at].parent().unwrap_or(raw_at) + }; + let next = if ended { + None + } else { + Some(decode(self.nodes[raw_at].mv)) + }; + if self.after_teaching_null(at) { + return; + } + let same_order = self.same_order(at, meta, line); + let index = game as u32; + out.add( + Match { + index, + ply: u32::from(self.nodes[at].ply), + same_order, + in_variation: false, + next, + }, + next, + meta.result, + meta.white_elo, + meta.black_elo, + meta.year, + ); + } + + /// A position after a teaching null move is not part of the played opening line. + fn after_teaching_null(&self, at: usize) -> bool { + let mut current = Some(at); + while let Some(node) = current { + let n = self.nodes[node]; + if n.parent().is_some() && n.mv == NULL_MOVE { + return true; + } + current = n.parent(); + } + false + } + + /// The move of the first child of node `at` among the entries `refs` of its game + /// (children come in text order, so the smallest node is the main continuation). + fn first_child_move(&self, at: usize, refs: &[u32]) -> Option { + refs.iter() + .filter(|&&r| r & 1 == 0) + .map(|&r| (r >> 1) as usize) + .find(|&n| self.nodes[n].parent() == Some(at)) + .map(|n| self.nodes[n].mv) + } + + /// Whether node `at` is reached from the usual start position by exactly `line`. + fn same_order(&self, at: usize, meta: Meta, line: Option<&[u16]>) -> bool { + let Some(line) = line else { + return false; + }; + if !meta.standard_start || usize::from(self.nodes[at].ply) != line.len() { + return false; + } + let mut cur = at; + for &mv in line.iter().rev() { + let n = self.nodes[cur]; + if n.mv != mv { + return false; + } + match n.parent() { + Some(p) => cur = p, + None => return false, + } + } + self.nodes[cur].parent().is_none() + } +} + +impl Chunk { + /// Parses record `index` and appends its positions (a record that does not parse, + /// or one past `MAX_NODES` nodes counted in `total` over all chunks, adds a game + /// without nodes). + fn add_game(&mut self, db: &PgnDatabase, index: usize, total: &AtomicUsize) { + let base = self.nodes.len(); + self.starts.push(base as u32); + let entry = &db.entries()[index]; + let tag = |name| entry.tag(name).unwrap_or(""); + let elo = |name| tag(name).trim().parse::().unwrap_or(0); + let mut meta = Meta { + result: GameResult::from_tag(tag("Result")), + white_elo: elo("WhiteElo"), + black_elo: elo("BlackElo"), + year: tag("Date") + .get(..4) + .and_then(|y| y.parse::().ok()) + .unwrap_or(0), + standard_start: false, + }; + if let Some(parsed) = db.load_game(index) { + let game = &parsed.game; + meta.standard_start = + game.position(game.root()).map(position::key) == Some(standard_key()); + let len = game.arena_len(); + if total.fetch_add(len, Ordering::Relaxed) + len < MAX_NODES { + self.add_tree(game); + } + } + self.meta.push(meta); + } + + /// Appends the attached nodes of `game` in text order (the order of the node + /// arena) and their index entries. + fn add_tree(&mut self, game: &Game) { + let base = self.nodes.len(); + let preorder = game.attached_nodes(); + // Variation flags (parents come first in preorder). + let mut variation = vec![false; game.arena_len()]; + for &id in &preorder { + if let Some(p) = game.parent(id) { + variation[id.index()] = variation[p.index()] || game.main_child(p) != Some(id); + } + } + let mut order = preorder; + order.sort_unstable(); + let mut local = vec![NO_PARENT; game.arena_len()]; + for (k, id) in order.iter().enumerate() { + local[id.index()] = (base + k) as u32; + } + for &id in &order { + let Some(node) = game.node(id) else { continue }; + let parent = node + .parent() + .map_or(NO_PARENT, |p| local[p.index()].min(NO_PARENT)); + let mv = match node.game_move().map(|m| m.kind) { + Some(MoveKind::Normal(m)) => encode(position::uci(&m)), + _ => NULL_MOVE, + }; + self.nodes.push(Node { + parent: if variation[id.index()] { + parent | VARIATION + } else { + parent + }, + mv, + ply: u16::try_from(node.ply()).unwrap_or(u16::MAX), + }); + let key = position::key(node.position()); + let children = node.children(); + if children.is_empty() { + self.entries.push((key, (local[id.index()] << 1) | 1)); + } + for c in children { + self.entries.push((key, local[c.index()] << 1)); + } + } + } +} + +fn standard_key() -> u64 { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + *KEY.get_or_init(|| position::key(&Chess::default())) +} + +/// Joins the index entries of the chunks (`total` in all) sorted by key and node; in +/// parallel for a large index. +fn sort_entries(parts: Vec>, total: usize) -> Vec<(u64, u32)> { + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + if threads == 1 || total < PARALLEL_SORT { + let mut entries = parts.concat(); + entries.sort_unstable(); + return entries; + } + // Keys are uniform: distribute by their top bits into buckets (freeing each part + // once copied), then sort the buckets in parallel; no merge is needed. + let buckets = (threads * 4).next_power_of_two(); + let shift = 64 - buckets.trailing_zeros(); + let bucket = |e: &(u64, u32)| (e.0 >> shift) as usize; + let mut counts = vec![0usize; buckets]; + for e in parts.iter().flatten() { + counts[bucket(e)] += 1; + } + let mut offsets: Vec = counts + .iter() + .scan(0, |sum, c| { + let start = *sum; + *sum += c; + Some(start) + }) + .collect(); + let mut sorted = vec![(0u64, 0u32); total]; + for part in parts { + for e in part { + let b = bucket(&e); + sorted[offsets[b]] = e; + offsets[b] += 1; + } + } + let mut groups: Vec> = (0..threads).map(|_| Vec::new()).collect(); + let mut rest = sorted.as_mut_slice(); + for (b, c) in counts.iter().enumerate() { + let (part, tail) = rest.split_at_mut(*c); + groups[b % threads].push(part); + rest = tail; + } + std::thread::scope(|s| { + for group in groups { + s.spawn(move || { + for part in group { + part.sort_unstable(); + } + }); + } + }); + sorted +} + +/// A move in 16 bits: from (6), to (6), promotion role (3). Anything else (the null +/// move) is `NULL_MOVE`, which no normal move encodes to. +fn encode(m: UciMove) -> u16 { + match m { + UciMove::Normal { + from, + to, + promotion, + } => { + u16::from(u8::from(from)) + | u16::from(u8::from(to)) << 6 + | u16::from(promotion.map_or(0, |r| r as u8)) << 12 + } + _ => NULL_MOVE, + } +} + +fn decode(v: u16) -> UciMove { + if v == NULL_MOVE { + return UciMove::Null; + } + UciMove::Normal { + from: Square::new(u32::from(v & 63)), + to: Square::new(u32::from((v >> 6) & 63)), + promotion: Role::try_from(v >> 12).ok(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use shakmaty::fen::Fen; + use shakmaty::san::San; + use shakmaty::{CastlingMode, Move, Position}; + + const PGN: &str = r#"[Event "0: other order"] +[Result "1-0"] +[WhiteElo "2600"] +[BlackElo "2400"] +[Date "2020.01.01"] + +1. Nf3 d5 2. d4 Nf6 1-0 + +[Event "1: same order"] +[Result "0-1"] +[Date "2024.??.??"] + +1. d4 d5 2. Nf3 e6 0-1 + +[Event "2: only in a variation"] +[Result "*"] + +1. e4 (1. d4 d5 2. Nf3 c5) 1... e5 * + +[Event "3: ends here"] +[Result "1/2-1/2"] + +1. d4 d5 2. Nf3 1/2-1/2 + +[Event "4: set up"] +[SetUp "1"] +[FEN "rnbqkbnr/ppp1pppp/8/3p4/3P4/5N2/PPP1PPPP/RNBQKB1R b KQkq - 1 2"] +[Result "1-0"] + +2... Nf6 1-0 + +[Event "5: null move"] +[Result "*"] + +1. e4 -- 2. d4 * + +[Event "6: two branches"] +[Result "0-1"] + +1. d4 d5 2. Nf3 (2. c4 e6) 2... Nf6 (2... c6 3. e3) 3. e3 0-1 +"#; + + fn db(text: &str) -> PgnDatabase { + let never = AtomicBool::new(false); + PgnDatabase::from_bytes(text.as_bytes().to_vec(), None, &mut |_| {}, &never).unwrap() + } + + fn table(db: &PgnDatabase) -> PositionTable { + let never = AtomicBool::new(false); + PositionTable::build(db, &AtomicUsize::new(0), &never).unwrap() + } + + fn line(moves: &[&str]) -> (Chess, Vec) { + let mut pos = Chess::default(); + let mut line = Vec::new(); + for s in moves { + let m = s.parse::().unwrap().to_move(&pos).unwrap(); + line.push(m); + pos.play_unchecked(m); + } + (pos, line) + } + + fn search(t: &PositionTable, db: &PgnDatabase, q: &PositionQuery) -> PositionOutcome { + t.search(db, None, q, &AtomicBool::new(false)).unwrap() + } + + fn query(moves: &[&str]) -> PositionQuery { + let (pos, l) = line(moves); + PositionQuery::new(pos, Some(l)) + } + + #[test] + fn finds_transpositions_variations_and_set_up_games() { + let db = db(PGN); + let t = table(&db); + assert_eq!(t.games(), 7); + let out = search(&t, &db, &query(&["d4", "d5", "Nf3"])); + let m = |index, ply, same_order, in_variation| Match { + index, + ply, + same_order, + in_variation, + next: None, + }; + // Compared without the next moves (checked in `counts_each_move_of_a_game_once`). + let found: Vec = out + .matches + .iter() + .map(|x| Match { next: None, ..*x }) + .collect(); + assert_eq!( + found, + vec![ + m(0, 3, false, false), + m(1, 3, true, false), + m(2, 3, true, true), + m(3, 3, true, false), + m(4, 0, false, false), + m(6, 3, true, false), + ] + ); + } + + #[test] + fn the_played_line_counts_only_its_first_occurrence() { + let db = db(PGN); + let t = table(&db); + let out = t + .search_first( + &db, + None, + &query(&["d4", "d5", "Nf3"]), + &AtomicBool::new(false), + ) + .unwrap(); + let found: Vec<(u32, u32)> = out.matches.iter().map(|m| (m.index, m.ply)).collect(); + assert_eq!(found, vec![(0, 3), (1, 3), (3, 3), (4, 0), (6, 3)]); + assert_eq!( + out.moves + .iter() + .map(|m| (m.san.as_str(), m.tally.games, m.main_line_games)) + .collect::>(), + vec![("Nf6", 3, 3), ("e6", 1, 1)] + ); + assert_eq!(out.ended.games, 1); + assert_eq!(out.ended.draws, 1); + let nf6 = &out.moves[0]; + assert_eq!((nf6.tally.white_wins, nf6.tally.black_wins), (2, 1)); + assert!(out.matches.iter().all(|m| !m.in_variation)); + assert_eq!( + out.matches + .iter() + .map(|m| m.index) + .filter(|&i| i == 2) + .count(), + 0 + ); + assert_eq!(out.matches[0].next, Some(nf6.uci)); + assert_eq!(out.matches[2].next, None); + let candidates = t + .search_first( + &db, + Some(&[0, 2, 6]), + &query(&["d4", "d5", "Nf3"]), + &AtomicBool::new(false), + ) + .unwrap(); + assert_eq!( + candidates + .matches + .iter() + .map(|m| m.index) + .collect::>(), + vec![0, 6] + ); + let after_null: Chess = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2" + .parse::() + .unwrap() + .into_position(shakmaty::CastlingMode::Standard) + .unwrap(); + let after_null = t + .search_first( + &db, + None, + &PositionQuery::new(after_null, None), + &AtomicBool::new(false), + ) + .unwrap(); + assert!( + after_null.matches.is_empty(), + "a teaching null move is not a played continuation" + ); + // A repeated position must not choose a later transposition branch. + let repeat = crate::pgn_positions::tests::db( + "[Event \"repeat\"]\n1. Nf3 d5 2. d4 Nf6 3. Ng1 Ng8 4. Nf3 e6 *\n", + ); + let table = table(&repeat); + let q = query(&["Nf3", "d5", "d4", "Nf6", "Ng1", "Ng8", "Nf3"]); + let out = table + .search_first(&repeat, None, &q, &AtomicBool::new(false)) + .unwrap(); + assert_eq!(out.matches[0].ply, 3); + assert!(!out.matches[0].same_order); + assert_eq!(out.moves[0].san, "Nf6"); + assert_eq!(out.moves.len(), 1); + } + + #[test] + fn next_move_belongs_to_the_chosen_occurrence() { + // The main line ends in the position; a variation reaches it and goes on. + let db = db("1. e4 (1. Nf3 e5 2. e4 Nc6) 1... e5 2. Nf3 *\n"); + let t = table(&db); + let out = search(&t, &db, &query(&["e4", "e5", "Nf3"])); + assert_eq!(out.matches.len(), 1); + assert!(!out.matches[0].in_variation); + assert_eq!(out.matches[0].next, None); + } + + #[test] + fn counts_each_move_of_a_game_once() { + let db = db(PGN); + let t = table(&db); + let out = search(&t, &db, &query(&["d4", "d5", "Nf3"])); + let stat = |san: &str| { + out.moves + .iter() + .find(|s| s.san == san) + .unwrap_or_else(|| panic!("{san} in {:?}", out.moves)) + }; + let nf6 = stat("Nf6"); + assert_eq!( + (nf6.tally.games, nf6.main_line_games), + (3, 3), + "games 0, 4, 6" + ); + assert_eq!( + (nf6.tally.white_wins, nf6.tally.black_wins, nf6.tally.draws), + (2, 1, 0) + ); + assert_eq!(nf6.tally.average_elo(), Some(2500)); + assert_eq!(nf6.tally.last_year, 2020); + let e6 = stat("e6"); + assert_eq!((e6.tally.games, e6.tally.last_year), (1, 2024)); + assert_eq!((stat("c5").tally.games, stat("c5").main_line_games), (1, 0)); + assert_eq!((stat("c6").tally.games, stat("c6").main_line_games), (1, 0)); + assert_eq!(out.moves[0].san, "Nf6"); + assert_eq!(out.moves.len(), 4); + assert_eq!(out.ended.games, 1); + assert_eq!(out.ended.draws, 1); + // The move after the chosen occurrence is the game's next move. + let nf6_uci = stat("Nf6").uci; + let next = |index: u32| { + out.matches + .iter() + .find(|m| m.index == index) + .and_then(|m| m.next) + }; + assert_eq!(next(6), Some(nf6_uci)); + assert_eq!(next(2), Some(stat("c5").uci)); + assert_eq!(next(3), None); + } + + #[test] + fn a_variation_end_is_not_a_game_end() { + let db = db(PGN); + let t = table(&db); + // After 2...c6 3.e3 in game 6 (a variation end) and 2...Nf6 3.e3 (main line + // end): one game, which ends here in its main line. + let out = search(&t, &db, &query(&["d4", "d5", "Nf3", "c6", "e3"])); + assert_eq!(out.matches.len(), 1); + assert!(out.matches[0].in_variation && out.matches[0].same_order); + assert_eq!(out.ended.games, 0); + let out = search(&t, &db, &query(&["d4", "d5", "Nf3", "Nf6", "e3"])); + assert_eq!(out.ended.games, 1); + assert!(!out.matches[0].in_variation); + } + + #[test] + fn positions_after_a_null_move_are_found() { + let db = db(PGN); + let t = table(&db); + let fen: Fen = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2" + .parse() + .unwrap(); + let pos: Chess = fen.into_position(CastlingMode::Standard).unwrap(); + let out = search(&t, &db, &PositionQuery::new(pos, None)); + assert_eq!(out.matches.len(), 1); + assert_eq!(out.matches[0].index, 5); + assert_eq!(out.matches[0].ply, 2); + assert!(!out.matches[0].same_order); + assert_eq!(out.moves.len(), 1); + assert_eq!(out.moves[0].san, "d4"); + // The null move itself is not a move of the position before it. + let out = search(&t, &db, &query(&["e4"])); + assert_eq!( + out.matches.iter().map(|m| m.index).collect::>(), + vec![2, 5] + ); + assert_eq!(out.moves.len(), 1, "{:?}", out.moves); + assert_eq!(out.moves[0].san, "e5"); + } + + #[test] + fn start_position_and_candidates() { + let db = db(PGN); + let t = table(&db); + let out = search(&t, &db, &query(&[])); + assert_eq!( + out.matches.iter().map(|m| m.index).collect::>(), + vec![0, 1, 2, 3, 5, 6] + ); + assert!(out.matches.iter().all(|m| m.same_order && m.ply == 0)); + let e4 = out.moves.iter().find(|s| s.san == "e4").unwrap(); + assert_eq!((e4.tally.games, e4.main_line_games), (2, 2)); + let d4 = out.moves.iter().find(|s| s.san == "d4").unwrap(); + assert_eq!((d4.tally.games, d4.main_line_games), (4, 3)); + + let q = query(&["d4", "d5", "Nf3"]); + let never = AtomicBool::new(false); + let out = t.search(&db, Some(&[1, 2, 5, 9]), &q, &never).unwrap(); + assert_eq!( + out.matches.iter().map(|m| m.index).collect::>(), + vec![1, 2] + ); + let out = t.search(&db, Some(&[]), &q, &never).unwrap(); + assert!(out.matches.is_empty() && out.moves.is_empty()); + let out = search(&t, &db, &query(&["h4", "h5"])); + assert!(out.matches.is_empty()); + } + + #[test] + fn cancel_stops_build_and_search() { + let db = db(PGN); + let t = table(&db); + let cancel = AtomicBool::new(true); + let progress = AtomicUsize::new(0); + assert!(PositionTable::build(&db, &progress, &cancel).is_none()); + assert!(t.search(&db, None, &query(&[]), &cancel).is_none()); + let progress = AtomicUsize::new(0); + PositionTable::build(&db, &progress, &AtomicBool::new(false)).unwrap(); + assert_eq!(progress.load(Ordering::Relaxed), 7); + } + + #[test] + fn many_games_build_in_parallel_like_one() { + // Enough games for several threads and the bucket sort. + let mut text = String::new(); + for _ in 0..3000 { + text.push_str(PGN); + text.push('\n'); + } + let db = db(&text); + let t = table(&db); + assert_eq!(t.games(), 21_000); + assert!(t.keys.len() >= PARALLEL_SORT, "the bucket sort is used"); + assert!( + t.keys + .iter() + .zip(&t.refs) + .collect::>() + .windows(2) + .all(|w| w[0] <= w[1]) + ); + let out = search(&t, &db, &query(&["d4", "d5", "Nf3"])); + assert_eq!(out.matches.len(), 6 * 3000); + assert_eq!(out.moves[0].tally.games, 3 * 3000); + assert_eq!(out.matches[6 * 1000 + 2].index, 7 * 1000 + 2); + assert!(out.matches[6 * 1000 + 2].in_variation); + } + + #[test] + fn moves_encode_reversibly() { + for uci in ["e2e4", "e1g1", "a7a8q", "h2h1n", "b7c8r", "g7h8b"] { + let m: UciMove = uci.parse().unwrap(); + assert_eq!(decode(encode(m)), m); + assert_ne!(encode(m), NULL_MOVE); + } + assert_eq!(decode(encode(UciMove::Null)), UciMove::Null); + } +} diff --git a/crates/chess-import/src/position.rs b/crates/chess-import/src/position.rs new file mode 100644 index 0000000..6678f45 --- /dev/null +++ b/crates/chess-import/src/position.rs @@ -0,0 +1,467 @@ +//! Position search: the games of a database that reach a given position (by any move +//! order), and what was played next. Shared by both kinds of database: a large +//! ChessBase database walks the main lines of its games (`chessbase::search`), a PGN +//! database keeps the positions of all its games, variations included, in memory +//! (`pgn_positions`). Decision 13 in `docs/decisions.md`. + +use std::collections::HashMap; + +use shakmaty::uci::UciMove; +use shakmaty::zobrist::Zobrist64; +use shakmaty::{Chess, EnPassantMode, Move, Position}; + +/// What to look for. +#[derive(Clone, Debug)] +pub struct PositionQuery { + /// The position to find. + pub position: Chess, + /// Moves the user played to reach it from the usual start position, when known; + /// a game that reaches the position by exactly these moves is "in this move order". + pub line: Option>, +} + +impl PositionQuery { + pub fn new(position: Chess, line: Option>) -> PositionQuery { + PositionQuery { position, line } + } + + /// Identity of the target position. + pub fn key(&self) -> u64 { + key(&self.position) + } +} + +/// Identity of a position for searching: board, side to move, castling rights and a +/// legal en passant square (the move counters do not matter). +pub fn key(pos: &Chess) -> u64 { + pos.zobrist_hash::(EnPassantMode::Legal).0 +} + +/// The same position as far as a search is concerned (see [`key`]). +pub fn same_position(a: &Chess, b: &Chess) -> bool { + a.board() == b.board() + && a.turn() == b.turn() + && a.castles().castling_rights() == b.castles().castling_rights() + && a.ep_square(EnPassantMode::Legal) == b.ep_square(EnPassantMode::Legal) +} + +/// A game that reaches the position. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Match { + /// Record index in the database. + pub index: u32, + /// Half-moves from the game's start to the first time the position appears. + pub ply: u32, + /// Reached by exactly the moves of [`PositionQuery::line`]. + pub same_order: bool, + /// Found in a variation, not in the main line (PGN databases only). + pub in_variation: bool, + /// The move the game played next (`None`: it ends in the position); filled in by + /// [`Collector`]. + pub next: Option, +} + +/// Results of games after a move (or of games ending in the position). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Tally { + pub games: u32, + pub white_wins: u32, + pub draws: u32, + pub black_wins: u32, + /// Sum and number of the ratings of the games' players (for the average). + pub elo_sum: u64, + pub elo_count: u32, + /// Latest year among the games (0: unknown). + pub last_year: u16, +} + +impl Tally { + /// Adds one game: its result ("1-0", "1/2-1/2", "0-1", other), the players' + /// ratings (0 = unknown) and its year (0 = unknown). + pub fn add(&mut self, result: GameResult, white_elo: u16, black_elo: u16, year: u16) { + self.games += 1; + match result { + GameResult::WhiteWins => self.white_wins += 1, + GameResult::Draw => self.draws += 1, + GameResult::BlackWins => self.black_wins += 1, + GameResult::Unknown => {} + } + // The average rating counts games where both ratings are known, like the + // "strongest first" sort. + if white_elo > 0 && black_elo > 0 { + self.elo_sum += u64::from(white_elo) + u64::from(black_elo); + self.elo_count += 2; + } + self.last_year = self.last_year.max(year); + } + + pub fn merge(&mut self, other: &Tally) { + self.games += other.games; + self.white_wins += other.white_wins; + self.draws += other.draws; + self.black_wins += other.black_wins; + self.elo_sum += other.elo_sum; + self.elo_count += other.elo_count; + self.last_year = self.last_year.max(other.last_year); + } + + /// Average rating of the players, if any is known. + pub fn average_elo(&self) -> Option { + (self.elo_count > 0).then(|| (self.elo_sum / u64::from(self.elo_count)) as u32) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GameResult { + WhiteWins, + Draw, + BlackWins, + Unknown, +} + +impl GameResult { + pub fn from_tag(tag: &str) -> GameResult { + match tag.trim() { + "1-0" => GameResult::WhiteWins, + "0-1" => GameResult::BlackWins, + "1/2-1/2" | "½-½" => GameResult::Draw, + _ => GameResult::Unknown, + } + } +} + +/// A move played in the position, with the games that played it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MoveStat { + pub uci: UciMove, + /// SAN in the searched position ("Nf3", "O-O"). + pub san: String, + pub tally: Tally, + /// Games among [`Tally::games`] that played the move in their main line; 0 when + /// it was only seen in variations (PGN databases). + pub main_line_games: u32, +} + +/// The answer to a [`PositionQuery`]. +#[derive(Clone, Debug, Default)] +pub struct PositionOutcome { + /// Matching games in record order. + pub matches: Vec, + /// Moves played next, most played first. + pub moves: Vec, + /// Games whose main line ends in the position. + pub ended: Tally, +} + +/// Collects matches and continuation statistics; one per search thread, then merged. +#[derive(Default)] +pub struct Collector { + pub matches: Vec, + moves: HashMap, + /// Per move: games that played it in their main line. + main_line: HashMap, + ended: Tally, + /// The last match whose first continuation was recorded (it decides `next`). + continued: Option, +} + +impl Collector { + /// Records a matching game: what it played next (`None`: the game ends here) and + /// its result, ratings and year. + #[allow(clippy::too_many_arguments)] + pub fn add( + &mut self, + m: Match, + next: Option, + result: GameResult, + white_elo: u16, + black_elo: u16, + year: u16, + ) { + self.add_match(m); + self.add_continuation(m.index, next, true, result, white_elo, black_elo, year); + } + + /// Records a matching game without what it played next; its continuations follow + /// with [`Collector::add_continuation`] (a PGN game can reach the position in + /// several branches and continue differently in each). + pub fn add_match(&mut self, m: Match) { + self.matches.push(m); + } + + /// Records a matching game whose [`Match::next`] is already decided (the move + /// after its chosen occurrence); its continuations do not change it. + pub fn add_match_with_next(&mut self, m: Match) { + self.matches.push(m); + self.continued = Some(m.index); + } + + /// Records one continuation of game `index` (added with [`Collector::add_match`]): + /// a move played next (`main_line`: in the game's main line) or `None` when the + /// game ends here. The first move recorded for a game is its [`Match::next`]. + #[allow(clippy::too_many_arguments)] + pub fn add_continuation( + &mut self, + index: u32, + next: Option, + main_line: bool, + result: GameResult, + white_elo: u16, + black_elo: u16, + year: u16, + ) { + // The first continuation belongs to the chosen occurrence: it is the game's + // next move, even when it is the end of the game (later ones come from other + // branches of a PGN game). + if self.continued != Some(index) + && let Some(m) = self.matches.last_mut() + && m.index == index + { + m.next = next; + self.continued = Some(index); + } + let tally = match next { + Some(uci) => { + if main_line { + *self.main_line.entry(uci).or_default() += 1; + } + self.moves.entry(uci).or_default() + } + None => &mut self.ended, + }; + tally.add(result, white_elo, black_elo, year); + } + + pub fn merge(&mut self, other: Collector) { + self.matches.extend(other.matches); + for (uci, t) in other.moves { + self.moves.entry(uci).or_default().merge(&t); + } + for (uci, n) in other.main_line { + *self.main_line.entry(uci).or_default() += n; + } + self.ended.merge(&other.ended); + } + + /// The outcome for `position`: matches in record order, moves by popularity with + /// SAN. Moves that are not legal in the position are left out. + pub fn finish(mut self, position: &Chess) -> PositionOutcome { + self.matches.sort_unstable_by_key(|m| m.index); + let mut moves: Vec = self + .moves + .into_iter() + .filter_map(|(uci, tally)| { + let m = uci.to_move(position).ok()?; + let san = shakmaty::san::SanPlus::from_move(position.clone(), m).to_string(); + let main_line_games = self.main_line.get(&uci).copied().unwrap_or(0); + Some(MoveStat { + uci, + san, + tally, + main_line_games, + }) + }) + .collect(); + moves.sort_by(|a, b| { + b.tally + .games + .cmp(&a.tally.games) + .then_with(|| a.san.cmp(&b.san)) + }); + PositionOutcome { + matches: self.matches, + moves, + ended: self.ended, + } + } +} + +/// UCI notation of a move as played in standard chess (castling as the king's move). +pub fn uci(m: &Move) -> UciMove { + m.to_uci(shakmaty::CastlingMode::Standard) +} + +/// Plies of a line checked one by one by [`theory_end`] before the end of the theory is +/// found by halving (an opening index answers the first plies at once). +pub const THEORY_LINEAR: usize = 12; + +/// Where a line of `total` positions leaves the "theory" of a database, as +/// [`theory_end`] finds it: indices into the line. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TheoryEnd { + /// The last position still known to the database. + pub last_known: Option, + /// The first position it does not know; `None` when the whole line is known. + pub first_unknown: Option, +} + +/// Finds how far a line of `total` positions is known to a database, with as few +/// searches as possible: `known(i)` says whether position `i` is (`None`: cancelled, +/// the search stops too). A position is nearly always known when a later one of the +/// same line is, so the first plies are checked one by one, then the end is found by +/// doubling and halving. `from`: the positions before it are known already (a game +/// that grew past a theory reaching its end checks only the new moves). +pub fn theory_end( + total: usize, + from: usize, + mut known: impl FnMut(usize) -> Option, +) -> Option { + let from = from.min(total); + let linear_end = if from > 0 { + from + } else { + total.min(THEORY_LINEAR) + }; + let mut last_known: Option = from.checked_sub(1); + let mut first_unknown = None; + for ply in from..linear_end { + if known(ply)? { + last_known = Some(ply); + } else { + first_unknown = Some(ply); + break; + } + } + if first_unknown.is_none() && total > linear_end { + let mut lo = linear_end - 1; + let mut step = 2; + let mut hi = total; + while lo + step < total { + if known(lo + step)? { + lo += step; + step *= 2; + } else { + hi = lo + step; + break; + } + } + if hi == total && lo + 1 < total { + // Past the last doubling: the end of the line itself. + if known(total - 1)? { + lo = total - 1; + } + } + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if known(mid)? { + lo = mid; + } else { + hi = mid; + } + } + last_known = Some(lo); + if hi < total { + first_unknown = Some(hi); + } + } + Some(TheoryEnd { + last_known, + first_unknown, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use shakmaty::san::San; + + fn play(moves: &[&str]) -> Chess { + let mut pos = Chess::default(); + for s in moves { + let m = s.parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(m); + } + pos + } + + #[test] + fn transpositions_are_the_same_position() { + let a = play(&["Nf3", "d5", "d4"]); + let b = play(&["d4", "d5", "Nf3"]); + assert!(same_position(&a, &b)); + assert_eq!(key(&a), key(&b)); + assert!(!same_position(&a, &play(&["d4", "d5"]))); + } + + #[test] + fn theory_end_finds_the_boundary_with_few_searches() { + for total in [1usize, 5, 12, 13, 20, 40, 100] { + for boundary in 0..=total { + // Positions before `boundary` are known. + let mut asked = 0; + let end = theory_end(total, 0, |i| { + asked += 1; + Some(i < boundary) + }) + .expect("not cancelled"); + let expect_last = boundary.checked_sub(1); + let expect_first = (boundary < total).then_some(boundary); + assert_eq!( + (end.last_known, end.first_unknown), + (expect_last, expect_first), + "total {total}, boundary {boundary}" + ); + assert!(asked <= THEORY_LINEAR + 2 * 8, "{asked} searches"); + } + } + // Cancelled: no answer. + assert_eq!(theory_end(10, 0, |_| None), None); + // Continuing from a known prefix. + let end = theory_end(10, 4, |i| Some(i < 7)).expect("end"); + assert_eq!( + end, + TheoryEnd { + last_known: Some(6), + first_unknown: Some(7) + } + ); + let end = theory_end(10, 4, |_| Some(true)).expect("end"); + assert_eq!( + end, + TheoryEnd { + last_known: Some(9), + first_unknown: None + } + ); + } + + #[test] + fn collector_counts_and_names_moves() { + let pos = Chess::default(); + let e4 = uci(&"e4".parse::().unwrap().to_move(&pos).unwrap()); + let d4 = uci(&"d4".parse::().unwrap().to_move(&pos).unwrap()); + let m = |index| Match { + index, + ply: 0, + same_order: true, + in_variation: false, + next: None, + }; + let mut a = Collector::default(); + a.add(m(3), Some(e4), GameResult::WhiteWins, 2700, 2600, 2020); + a.add(m(1), Some(d4), GameResult::Draw, 0, 0, 0); + let mut b = Collector::default(); + b.add(m(2), Some(e4), GameResult::BlackWins, 2500, 0, 2024); + b.add(m(5), None, GameResult::Unknown, 0, 0, 0); + // A game ending in its chosen occurrence keeps no next move, whatever its other + // branches play. + b.add_match(m(7)); + b.add_continuation(7, None, true, GameResult::Draw, 0, 0, 0); + b.add_continuation(7, Some(e4), false, GameResult::Draw, 0, 0, 0); + a.merge(b); + let out = a.finish(&pos); + assert_eq!( + out.matches.iter().map(|m| m.index).collect::>(), + vec![1, 2, 3, 5, 7] + ); + assert_eq!(out.matches[4].next, None, "ends in its chosen occurrence"); + assert_eq!(out.matches[2].next, Some(e4)); + assert_eq!(out.moves[0].san, "e4"); + assert_eq!(out.moves[0].tally.games, 3); + // Only game 3 has both ratings. + assert_eq!(out.moves[0].tally.average_elo(), Some(2650)); + assert_eq!(out.moves[0].tally.last_year, 2024); + assert_eq!(out.moves[1].san, "d4"); + assert_eq!(out.ended.games, 2); + } +} diff --git a/crates/chess-import/tests/formats.rs b/crates/chess-import/tests/formats.rs new file mode 100644 index 0000000..3903e43 --- /dev/null +++ b/crates/chess-import/tests/formats.rs @@ -0,0 +1,219 @@ +//! Every way into the importer: plain PGN, zip archives (with PGN in a legacy code +//! page and in folders), an unpacked ChessBase database on disk. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_import::{Format, ImportError, Opened}; + +/// A fresh directory under the system temp dir, removed on drop. +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> TempDir { + let p = std::env::temp_dir().join(format!( + "chess-import-{tag}-{}-{:?}", + std::process::id(), + std::time::SystemTime::now() + )); + std::fs::create_dir_all(&p).expect("temp dir"); + TempDir(p) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn open(path: &Path) -> Result { + let never = AtomicBool::new(false); + chess_import::open(path, &mut |_| {}, &never) +} + +const GAME: &str = "[Event \"Test\"]\n[White \"A\"]\n[Black \"B\"]\n[Result \"1-0\"]\n\n1. e4 e5 2. Qh5 Nc6 3. Bc4 Nf6 4. Qxf7# 1-0\n"; + +#[test] +fn plain_pgn_is_unchanged() { + let dir = TempDir::new("pgn"); + let p = dir.0.join("game.pgn"); + std::fs::write(&p, GAME).expect("write"); + let o = open(&p).expect("opens"); + assert_eq!(o.format, Format::Pgn); + assert_eq!(o.db.len(), 1); + assert!(o.notes.is_empty()); +} + +#[test] +fn pgn_and_archives_open_from_bytes() { + let never = AtomicBool::new(false); + let pgn = chess_import::open_bytes("game.pgn", GAME.as_bytes().to_vec(), &mut |_| {}, &never) + .expect("opens"); + assert_eq!(pgn.format, Format::Pgn); + assert_eq!(pgn.db.len(), 1); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("one.pgn", zip::write::SimpleFileOptions::default()) + .expect("entry"); + zip.write_all(GAME.as_bytes()).expect("data"); + let bytes = zip.finish().expect("zip").into_inner(); + let z = chess_import::open_bytes("games.zip", bytes, &mut |_| {}, &never).expect("opens"); + assert_eq!(z.format, Format::Zip); + assert_eq!(z.db.raw_text(0), pgn.db.raw_text(0)); + // A .cbh alone is not a database: its other files are needed. + assert!(matches!( + chess_import::open_bytes("base.cbh", vec![0; 46], &mut |_| {}, &never), + Err(ImportError::Unsupported( + chess_import::Unsupported::ChessBaseFiles + )) + )); +} + +#[test] +fn zip_with_legacy_pgn_and_folders() { + let dir = TempDir::new("zip"); + let p = dir.0.join("games.zip"); + let file = std::fs::File::create(&p).expect("create"); + let mut zip = zip::ZipWriter::new(file); + let stored = + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + zip.start_file("one.pgn", stored).expect("entry"); + zip.write_all(GAME.as_bytes()).expect("data"); + // A Russian comment in Windows-1251, inside a folder. + let (cp1251, _, _) = encoding_rs::WINDOWS_1251.encode( + "[Event \"ТеÑ�Ñ‚\"]\n[White \"Ð�лехин\"]\n[Black \"Капабланка\"]\n[Result \"*\"]\n\n1. d4 {Хороший ход} d5 *\n", + ); + zip.add_directory("sub/", stored).expect("dir"); + zip.start_file("sub/two.PGN", stored).expect("entry"); + zip.write_all(&cp1251).expect("data"); + zip.start_file("readme.txt", stored).expect("entry"); + zip.write_all(b"not a database").expect("data"); + zip.finish().expect("finish"); + + let o = open(&p).expect("opens"); + assert_eq!(o.format, Format::Zip); + assert_eq!(o.db.len(), 2); + let second = o.db.raw_text(1).expect("text"); + assert!( + second.contains("Ð�лехин") && second.contains("Хороший ход"), + "{second}" + ); + + // The same archive under another extension is still recognized by its content. + let renamed = dir.0.join("games.bin"); + std::fs::copy(&p, &renamed).expect("copy"); + assert_eq!(open(&renamed).expect("opens").format, Format::Zip); +} + +#[test] +fn zip_without_databases_and_unsupported_files() { + let dir = TempDir::new("empty"); + let p = dir.0.join("empty.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&p).expect("create")); + zip.start_file("notes.txt", zip::write::SimpleFileOptions::default()) + .expect("entry"); + zip.write_all(b"hello").expect("data"); + zip.finish().expect("finish"); + assert!(matches!(open(&p), Err(ImportError::Empty))); + + let cbz = dir.0.join("locked.cbz"); + std::fs::write(&cbz, b"whatever").expect("write"); + assert!(matches!( + open(&cbz), + Err(ImportError::Unsupported( + chess_import::Unsupported::Encrypted + )) + )); + let broken = dir.0.join("broken.cbv"); + std::fs::write(&broken, [8u8, 0, 1, 0, 0x95, 0, 0, 0, 1, 2, 3]).expect("write"); + assert!(matches!(open(&broken), Err(ImportError::Corrupt(_)))); +} + +#[test] +fn unpacked_chessbase_database_matches_its_archive() { + // Unpack a book archive from the samples to disk and open its .cbh directly. + let samples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample"); + let Some(archive) = std::fs::read_dir(&samples).ok().and_then(|d| { + d.flatten() + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "7z")) + }) else { + eprintln!("skipped: no .7z sample"); + return; + }; + let dir = TempDir::new("cbh"); + let mut cbh = None; + let mut reader = sevenz_rust2::ArchiveReader::new( + std::fs::File::open(&archive).expect("open"), + sevenz_rust2::Password::empty(), + ) + .expect("7z"); + reader + .for_each_entries(|entry, r| { + let mut data = Vec::new(); + r.read_to_end(&mut data)?; + let name = entry + .name() + .rsplit(['/', '\\']) + .next() + .unwrap_or("") + .to_owned(); + if !entry.is_directory() && !name.is_empty() && !name.ends_with(".cbv") { + let p = dir.0.join(&name); + std::fs::write(&p, data)?; + if name.ends_with(".cbh") { + cbh = Some(p); + } + } + Ok(true) + }) + .expect("unpack"); + let cbh = cbh.expect("archive holds a .cbh"); + let from_disk = open(&cbh).expect("opens"); + assert_eq!(from_disk.format, Format::ChessBase); + let from_archive = open(&archive).expect("opens"); + assert_eq!(from_disk.db.len(), from_archive.db.len()); + // The same without the file system (Android): the archive as bytes, the database + // as the contents of its files. + let never = AtomicBool::new(false); + let name = archive.file_name().unwrap().to_string_lossy().into_owned(); + let bytes = std::fs::read(&archive).expect("read"); + let archive_bytes = chess_import::open_bytes(&name, bytes, &mut |_| {}, &never).expect("opens"); + let files: Vec<(String, Vec)> = std::fs::read_dir(&dir.0) + .expect("dir") + .flatten() + .map(|e| { + let p = e.path(); + ( + p.file_name().unwrap().to_string_lossy().into_owned(), + std::fs::read(&p).expect("read"), + ) + }) + .collect(); + let cbh_name = cbh.file_name().unwrap().to_string_lossy().into_owned(); + let from_files = + chess_import::open_chessbase_files(&cbh_name, &files, &mut |_| {}, &never).expect("opens"); + assert_eq!(from_files.format, Format::ChessBase); + assert_eq!(from_files.db.len(), from_disk.db.len()); + assert_eq!(archive_bytes.db.len(), from_archive.db.len()); + for i in 0..from_disk.db.len() { + assert_eq!( + from_files.db.raw_text(i), + from_disk.db.raw_text(i), + "record {i}" + ); + assert_eq!( + archive_bytes.db.raw_text(i), + from_archive.db.raw_text(i), + "record {i}" + ); + } + for i in 0..from_disk.db.len() { + assert_eq!( + from_disk.db.raw_text(i), + from_archive.db.raw_text(i), + "record {i}" + ); + } +} diff --git a/crates/chess-import/tests/pgn_positions.rs b/crates/chess-import/tests/pgn_positions.rs new file mode 100644 index 0000000..296d7f0 --- /dev/null +++ b/crates/chess-import/tests/pgn_positions.rs @@ -0,0 +1,106 @@ +//! Position search over the real databases in `pgnFilesforExample/` (not in the +//! repository: the tests skip what is missing), checked against a brute force walk +//! of every game tree. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::time::Instant; + +use chess_core::NodeId; +use chess_import::pgn_positions::PositionTable; +use chess_import::position::{PositionQuery, key}; + +fn samples() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample") +} + +const FILES: [&str; 9] = [ + "The Ruy Lopez - Move by Move.pgn", + "Дворецкий. Учебник жндшпилÑ�.pgn", + "10 Great Ways to Get Better at Chess [Everyman 2010] - Davies Nigel.7z", + "A Ferocious Opening Repertoire [Everyman 2011] - Lakdawala Cyrus.7z", + "Attacking Chess - The King's Indian - Volume 1 [Everyman 2010] - Vigorito David.7z", + "Chess Developments - The Modern Benoni [Everyman 2011] - Palliser Richard.7z", + "Rubinstein russian.cbv", + "Anand 01-14.cbv", + "Endgame Manual.cbv", +]; + +#[test] +fn search_agrees_with_walking_every_game() { + let never = AtomicBool::new(false); + for name in FILES { + let path = samples().join(name); + if !path.exists() { + eprintln!("skipped: {} not found", path.display()); + continue; + } + let opened = chess_import::open(&path, &mut |_| {}, &never).expect("opens"); + let db = opened.db.as_pgn().expect("a small database is PGN"); + let t0 = Instant::now(); + let table = PositionTable::build(db, &AtomicUsize::new(0), &never).expect("built"); + let built = t0.elapsed(); + + // Per game: keys of all positions and of the main line positions; some + // positions to ask for (main line and variation nodes). + let mut all: Vec> = Vec::new(); + let mut main: Vec> = Vec::new(); + let mut queries = Vec::new(); + for i in 0..db.len() { + let game = db.load_game(i).expect("game").game; + let nodes = game.attached_nodes(); + all.push( + nodes + .iter() + .map(|&n| key(game.position(n).unwrap())) + .collect(), + ); + let mut line = vec![NodeId::ROOT]; + line.extend(game.mainline()); + main.push( + line.iter() + .map(|&n| key(game.position(n).unwrap())) + .collect(), + ); + if i % 7 == 0 { + for n in nodes.iter().step_by(23) { + queries.push(game.position(*n).unwrap().clone()); + } + } + } + let mut searching = std::time::Duration::ZERO; + let mut found = 0; + for pos in &queries { + let q = PositionQuery::new(pos.clone(), None); + let t0 = Instant::now(); + let out = table.search(db, None, &q, &never).expect("searched"); + searching += t0.elapsed(); + let k = key(pos); + let expected: Vec = (0..all.len() as u32) + .filter(|&i| all[i as usize].contains(&k)) + .collect(); + let got: Vec = out.matches.iter().map(|m| m.index).collect(); + assert_eq!(got, expected, "{name}: {pos:?}"); + for m in &out.matches { + assert_eq!(m.in_variation, !main[m.index as usize].contains(&k)); + } + // Every move of the statistics is played by at most the matching games. + for s in &out.moves { + assert!(s.tally.games as usize <= got.len()); + assert!(s.main_line_games <= s.tally.games); + } + found += got.len(); + } + let per_query = searching / queries.len().max(1) as u32; + eprintln!( + "{name}: {} games, {} positions, {:.1} MB; build {built:.1?}; \ + {} queries, {per_query:.1?} each, {found} matches", + table.games(), + table.positions(), + table.memory() as f64 / 1e6, + queries.len(), + ); + assert_eq!(table.games(), db.len()); + } +} diff --git a/crates/chess-import/tests/samples.rs b/crates/chess-import/tests/samples.rs new file mode 100644 index 0000000..a626731 --- /dev/null +++ b/crates/chess-import/tests/samples.rs @@ -0,0 +1,123 @@ +//! Conversion of the real databases in `pgnFilesforExample/` (not in the repository: +//! the tests skip what is missing). +//! +//! Every converted game must parse back without warnings, a ChessBase database must +//! convert the same from its `.cbv` archive as unpacked, and texts must keep their +//! letters. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::Severity; +use chess_import::{Format, Opened}; + +fn samples() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample") +} + +fn open(name: &str) -> Option { + let path = samples().join(name); + if !path.exists() { + eprintln!("skipped: {} not found", path.display()); + return None; + } + let never = AtomicBool::new(false); + Some(chess_import::open(&path, &mut |_| {}, &never).expect("opens")) +} + +/// Parses every game; returns (games with moves, all PGN text joined). +fn check_all(o: &Opened) -> (usize, String) { + let mut with_moves = 0; + let mut text = String::new(); + for i in 0..o.db.len() { + let g = o.db.load_game(i).expect("game"); + assert!( + g.max_severity().is_none_or(|s| s < Severity::Warning), + "game {i}: {:?}\n{}", + g.diagnostics, + o.db.raw_text(i).unwrap_or_default() + ); + if !g.game.mainline().is_empty() { + with_moves += 1; + } + let raw = o.db.raw_text(i).unwrap_or_default(); + assert!( + !raw.chars() + .any(|c| c.is_control() && c != '\n' && c != '\t'), + "game {i}: control characters in {raw:?}" + ); + text.push_str(&raw); + } + (with_moves, text) +} + +#[test] +fn chessbase_archives_convert_cleanly() { + for (name, games, texts) in [ + ("Rubinstein russian.cbv", 129, 9), + ("Anand 01-14.cbv", 399, 0), + ("Endgame Manual.cbv", 847, 134), + ] { + let Some(o) = open(name) else { continue }; + assert_eq!(o.format, Format::ChessBaseArchive); + assert!(o.notes.is_empty(), "{name}: {:?}", o.notes); + assert_eq!(o.db.len(), games + texts, "{name}: records"); + let (with_moves, _) = check_all(&o); + // A few games of a book may be only a position with a comment. + assert!( + with_moves + texts + 5 >= games + texts, + "{name}: {with_moves} games with moves" + ); + } +} + +#[test] +fn texts_keep_their_letters() { + if let Some(o) = open("Rubinstein russian.cbv") { + let (_, text) = check_all(&o); + assert!(text.contains("Размены необходимы, чтобы уравнÑ�ть игру.")); + assert!(!text.contains('\u{fffd}')); + } + if let Some(o) = open("Endgame Manual.cbv") { + let (_, text) = check_all(&o); + assert!( + text.contains("Nürnberg"), + "Western tournament names in a Russian database" + ); + assert!(!text.contains("NÑŒrnberg")); + } + if let Some(o) = open("Anand 01-14.cbv") { + let (_, text) = check_all(&o); + assert!(text.contains("3...Bg4"), "figurines become letters"); + // Only figurines before a square or a capture are converted; of the ~2600 in + // the book two are typos ("19 Â¥5", "5...Â¥Ne7") and stay as they are. + assert!(text.matches('\u{a5}').count() <= 2); + assert!(!text.contains('\u{e027}')); + } +} + +#[test] +fn archives_with_both_forms_of_a_database() { + // Each book archive holds the database unpacked and as .cbv: the two conversions + // must be identical, so the archive yields one copy. + let dir = samples(); + let Ok(entries) = std::fs::read_dir(&dir) else { + eprintln!("skipped: no samples"); + return; + }; + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if !name.ends_with(".7z") { + continue; + } + let o = open(&name).expect("present"); + assert_eq!(o.format, Format::SevenZip); + assert!( + o.notes.len() == 1 && o.notes[0].contains("skipped"), + "{name}: {:?}", + o.notes + ); + let (with_moves, _) = check_all(&o); + assert!(with_moves > 10, "{name}"); + } +} diff --git a/crates/game-review/Cargo.toml b/crates/game-review/Cargo.toml new file mode 100644 index 0000000..97583ee --- /dev/null +++ b/crates/game-review/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "game-review" +description = "Whole-game analysis of ChessPenguin: engine evaluations of the main line, move judgements, accuracy (the desktop and Android apps share it)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +chess-core.workspace = true +shakmaty.workspace = true +uci.workspace = true +chess-openings.workspace = true +serde.workspace = true +serde_json.workspace = true +web-time.workspace = true diff --git a/crates/game-review/chesscom/README.md b/crates/game-review/chesscom/README.md new file mode 100644 index 0000000..24c3287 --- /dev/null +++ b/crates/game-review/chesscom/README.md @@ -0,0 +1,44 @@ +# Партии Ñ�о Ñ�веркой по chess.com + +Партии, в которых отметки нашего разбора (!! и !) Ñ�верены Ñ� Game Review chess.com. ПоÑ�ле +каждой калибровки правил (`src/features.rs`, `src/report.rs`) прогонÑ�ть **вÑ�е**: + +``` +cargo run --release -p game-review --example chesscom_check -- +``` + +- Отметки chess.com запиÑ�аны в партию как NAG: `$3` — !!, `$1` — !. Других NAG здеÑ�ÑŒ нет. +- Тег `ChessComMarks` — какие отметки Ñ�верÑ�лиÑ�ÑŒ: `"!! !"` — обе, `"!!"` — только блеÑ�Ñ‚Ñ�щие + (отметки ! chess.com длÑ� Ñ�той партии неизвеÑ�тны, наши ! не Ñ�читаютÑ�Ñ� раÑ�хождением). +- Движок Ñ�читает так же, как программа (фикÑ�ированный поиÑ�к разбора, `docs/decisions.md` + 2026-10-28): Stockfish 19 из ChessPenguin, 1 000 000 узлов (`SEARCH_NODES`), один поток, + Hash 32 МБ, `ucinewgame` перед каждым поиÑ�ком, процеÑ�Ñ�ов — по чиÑ�лу ЦП (до 8). Оценки + поÑ�тому одинаковы на любой машине. КÑ�ш — `target/chesscom-check/v/`: + повторный прогон поÑ�ле правки правил идёт без движка. +- `CP_REVIEW_NODES=N` — другое чиÑ�ло узлов, только длÑ� подбора конÑ�танты (кÑ�ш в + `target/chesscom-check/v<верÑ�иÑ�>-N/`); программа так не Ñ�читает. +- `CP_SHALLOW_NODES`, `CP_GREAT_HARD`, `CP_BRILLIANT_HARD`, `CP_GREAT_GAP`, + `CP_BRILLIANT_GAP`, `CP_GREAT_BANS`, `CP_HARD_DEPTH` — опыты Ñ� «трудноÑ�тью» хода + (неглубокий поиÑ�к, `Hardness`; 2026-10-29, программа их пока не иÑ�пользует), Ñ�м. + `examples/chesscom_check.rs`. Ð�еглубокие поиÑ�ки хранÑ�Ñ‚Ñ�Ñ� в том же кÑ�ше. +- Ð�овую партию от владельца — Ñ�юда же, Ñ� иÑ�точником в теге `Annotator`. + +## ПорÑ�док калибровки + +1. Ð�овую партию Ñ�начала добавить и прогнать **без правок правил** — Ñ�то чеÑ�тнаÑ� проверка + (партиÑ� не учаÑ�твовала в наÑ�тройке). ЗапиÑ�ать: Ñ�колько !! и ! chess.com нашлоÑ�ÑŒ. +2. Только потом иÑ�кать причины раÑ�хождений и править. Правка — общее правило о том, что + делает ход (жертва, отыгрыш, мат), а не иÑ�ключение длÑ� хода; пороги не двигать ради + одной партии. +3. Прогнать веÑ�ÑŒ набор: ничего из прежнего не должно Ñ�ломатьÑ�Ñ�. + +Итог прогона — долÑ� найденных !! и ! chess.com и долÑ� наших !! и !, которые Ñ�овпали Ñ� +chess.com. ЧиÑ�ла завиÑ�Ñ�Ñ‚ только от правил и верÑ�ии поиÑ�ка: калибровки 1–7 делалиÑ�ÑŒ на +3M узлов и 12 потоках, поÑ�ле перехода на фикÑ�ированный поиÑ�к (1M, один поток) они +переÑ�читаны (`docs/decisions.md`). + +## Вердикты владельца + +Партии `owner-*.pgn` — без отметок chess.com: тег `OwnerPlain` перечиÑ�лÑ�ет ходы (SAN), которые +владелец Ñ�читает очевидными; ни «!», ни «!!» на них быть не должно. Прогон печатает такие +нарушениÑ� Ñ�трокой `OWNER` и Ñ�читает их в итоговой Ñ�троке. diff --git a/crates/game-review/chesscom/aronian-anand.pgn b/crates/game-review/chesscom/aronian-anand.pgn new file mode 100644 index 0000000..99c4aea --- /dev/null +++ b/crates/game-review/chesscom/aronian-anand.pgn @@ -0,0 +1,14 @@ +[Event "Tata Steel-A 75th"] +[Site "Wijk aan Zee"] +[Date "2013.01.15"] +[Round "4"] +[White "Aronian, Levon"] +[Black "Anand, Viswanathan"] +[Result "0-1"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] + +1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 +Bd6 9. O-O O-O 10. Qc2 Bb7 11. a3 Rc8 12. Ng5 c5 13. Nxh7 Ng4 $3 14. f4 cxd4 $1 15. +exd4 Bc5 $3 16. Be2 Nde5 $3 17. Bxg4 Bxd4+ 18. Kh1 Nxg4 $1 19. Nxf8 f5 $1 20. Ng6 Qf6 21. h3 +Qxg6 22. Qe2 Qh5 23. Qd3 Be3 $3 0-1 diff --git a/crates/game-review/chesscom/byrne-fischer-2.pgn b/crates/game-review/chesscom/byrne-fischer-2.pgn new file mode 100644 index 0000000..277851f --- /dev/null +++ b/crates/game-review/chesscom/byrne-fischer-2.pgn @@ -0,0 +1,16 @@ +[Event "Third Rosenwald Trophy"] +[Site "New York, NY USA"] +[Date "1956.10.17"] +[White "Byrne, Donald"] +[Black "Fischer, Robert James"] +[Result "0-1"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28): another move order of the opening"] + +1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 c6 7. Rd1 dxc4 8. Qxc4 +Nbd7 9. e4 $1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 $3 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 +Qb6 15. Bc4 Nxc3 $3 16. Bc5 Rfe8+ 17. Kf1 Be6 $3 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ $1 +20. Kf1 Nxd4+ 21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 +26. h3 Rxa2 27. Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. +Qb8 b5 33. h4 h5 34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ +39. Kc1 Ne2+ 40. Kb1 Nc3+ 41. Kc1 Rc2# 0-1 diff --git a/crates/game-review/chesscom/byrne-fischer.pgn b/crates/game-review/chesscom/byrne-fischer.pgn new file mode 100644 index 0000000..127e90a --- /dev/null +++ b/crates/game-review/chesscom/byrne-fischer.pgn @@ -0,0 +1,17 @@ +[Event "Third Rosenwald Trophy"] +[Site "New York, NY USA"] +[Date "1956.10.17"] +[Round "8"] +[White "Byrne, Donald"] +[Black "Fischer, Robert James"] +[Result "0-1"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 dxc4 7. Qxc4 c6 8. e4 +Nbd7 9. Rd1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 $3 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 Qb6 +15. Bc4 Nxc3 $3 16. Bc5 Rfe8+ 17. Kf1 Be6 $3 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ $1 20. Kf1 Nxd4+ +21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 26. h3 Rxa2 27. +Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. Qb8 b5 33. h4 h5 +34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ 39. Kc1 Ne2+ 40. +Kb1 Nc3+ 41. Kc1 Rc2# 0-1 diff --git a/crates/game-review/chesscom/capablanca-marshall.pgn b/crates/game-review/chesscom/capablanca-marshall.pgn new file mode 100644 index 0000000..2396faf --- /dev/null +++ b/crates/game-review/chesscom/capablanca-marshall.pgn @@ -0,0 +1,15 @@ +[Event "New York"] +[Site "New York USA"] +[Date "1918.10.23"] +[White "Capablanca, Jose Raul"] +[Black "Marshall, Frank James"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 +d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 Nf6 12. Re1 Bd6 13. h3 Ng4 14. Qf3 Qh4 +15. d4 Nxf2 16. Re2 Bg4 17. hxg4 Bh2+ 18. Kf1 Bg3 19. Rxf2 Qh1+ 20. Ke2 Bxf2 +21. Bd2 Bh4 22. Qh3 Rae8+ 23. Kd3 Qf1+ 24. Kc2 Bf2 25. Qf3 Qg1 26. Bd5 c5 27. +dxc5 Bxc5 28. b4 Bd6 29. a4 a5 30. axb5 axb4 31. Ra6 bxc3 32. Nxc3 Bb4 33. b6 +Bxc3 34. Bxc3 h6 35. b7 Re3 36. Bxf7+ $3 1-0 diff --git a/crates/game-review/chesscom/evergreen.pgn b/crates/game-review/chesscom/evergreen.pgn new file mode 100644 index 0000000..eaff13e --- /dev/null +++ b/crates/game-review/chesscom/evergreen.pgn @@ -0,0 +1,13 @@ +[Event "Berlin casual game"] +[Site "Berlin"] +[Date "1852.??.??"] +[White "Anderssen, Adolf"] +[Black "Dufresne, Jean"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshots, 2026-10-28)"] + +1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d3 8. Qb3 +Qf6 $1 9. e5 Qg6 10. Re1 Nge7 $1 11. Ba3 b5 12. Qxb5 Rb8 13. Qa4 $1 Bb6 14. Nbd2 +Bb7 15. Ne4 Qf5 16. Bxd3 Qh5 17. Nf6+ gxf6 18. exf6 Rg8 $1 19. Rad1 Qxf3 20. +Rxe7+ $1 Nxe7 21. Qxd7+ $3 Kxd7 22. Bf5+ $1 Ke8 23. Bd7+ $1 Kf8 24. Bxe7# 1-0 diff --git a/crates/game-review/chesscom/immortal.pgn b/crates/game-review/chesscom/immortal.pgn new file mode 100644 index 0000000..7717673 --- /dev/null +++ b/crates/game-review/chesscom/immortal.pgn @@ -0,0 +1,13 @@ +[Event "London casual game"] +[Site "London ENG"] +[Date "1851.06.21"] +[White "Anderssen, Adolf"] +[Black "Kieseritzky, Lionel"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 b5 5. Bxb5 Nf6 6. Nf3 Qh6 7. d3 Nh5 8. +Nh4 Qg5 9. Nf5 $1 c6 10. g4 Nf6 11. Rg1 cxb5 12. h4 $1 Qg6 13. h5 $1 Qg5 14. Qf3 +$1 Ng8 15. Bxf4 Qf6 16. Nc3 $1 Bc5 17. Nd5 Qxb2 18. Bd6 Bxg1 19. e5 Qxa1+ 20. +Ke2 $1 Na6 21. Nxg7+ Kd8 22. Qf6+ $3 Nxf6 23. Be7# 1-0 diff --git a/crates/game-review/chesscom/kasparov-topalov.pgn b/crates/game-review/chesscom/kasparov-topalov.pgn new file mode 100644 index 0000000..b7078fc --- /dev/null +++ b/crates/game-review/chesscom/kasparov-topalov.pgn @@ -0,0 +1,17 @@ +[Event "Hoogovens"] +[Site "Wijk aan Zee NED"] +[Date "1999.01.20"] +[Round "4"] +[White "Kasparov, Garry"] +[Black "Topalov, Veselin"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 Bg7 5. Qd2 c6 6. f3 b5 7. Nge2 Nbd7 8. Bh6 +Bxh6 9. Qxh6 Bb7 10. a3 e5 11. O-O-O Qe7 12. Kb1 a6 13. Nc1 O-O-O 14. Nb3 exd4 +15. Rxd4 c5 16. Rd1 Nb6 17. g3 Kb8 18. Na5 Ba8 19. Bh3 d5 20. Qf4+ Ka7 21. Rhe1 +d4 $1 22. Nd5 Nbxd5 23. exd5 Qd6 $1 24. Rxd4 cxd4 25. Re7+ $3 Kb6 $1 26. Qxd4+ Kxa5 27. b4+ $1 +Ka4 28. Qc3 Qxd5 29. Ra7 Bb7 $1 30. Rxb7 $3 Qc4 31. Qxf6 Kxa3 32. Qxa6+ $1 Kxb4 33. c3+ $3 +Kxc3 34. Qa1+ $1 Kd2 35. Qb2+ $1 Kd1 36. Bf1 $3 Rd2 37. Rd7 $3 Rxd7 38. Bxc4 bxc4 39. Qxh8 +Rd3 40. Qa8 c3 41. Qa4+ Ke1 42. f4 f5 43. Kc1 Rd2 44. Qa7 1-0 diff --git a/crates/game-review/chesscom/lasker-thomas.pgn b/crates/game-review/chesscom/lasker-thomas.pgn new file mode 100644 index 0000000..abf3085 --- /dev/null +++ b/crates/game-review/chesscom/lasker-thomas.pgn @@ -0,0 +1,12 @@ +[Event "London"] +[Site "London ENG"] +[Date "1912.10.29"] +[White "Lasker, Edward"] +[Black "Thomas, George Alan"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. d4 e6 2. Nf3 f5 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 Bxf6 6. e4 fxe4 7. Nxe4 b6 8. +Ne5 O-O 9. Bd3 Bb7 10. Qh5 Qe7 11. Qxh7+ $3 Kxh7 12. Nxf6+ Kh6 13. Neg4+ $1 Kg5 +14. h4+ Kf4 15. g3+ Kf3 16. Be2+ Kg2 17. Rh2+ Kg1 18. Kd2# 1-0 diff --git a/crates/game-review/chesscom/levitsky-marshall.pgn b/crates/game-review/chesscom/levitsky-marshall.pgn new file mode 100644 index 0000000..c00989d --- /dev/null +++ b/crates/game-review/chesscom/levitsky-marshall.pgn @@ -0,0 +1,14 @@ +[Event "Breslau"] +[Site "Breslau GER"] +[Date "1912.07.20"] +[White "Levitsky, Stepan Mikhailovich"] +[Black "Marshall, Frank James"] +[Result "0-1"] +[ChessComMarks "counts"] +[ChessComCounts "white !! 0 ! 1, black !! 2 ! 1"] +[Annotator "chess.com Game Review summary only (owner's screenshot, 2026-10-28)"] + +1. d4 e6 2. e4 d5 3. Nc3 c5 4. Nf3 Nc6 5. exd5 exd5 6. Be2 Nf6 7. O-O Be7 8. +Bg5 O-O 9. dxc5 Be6 10. Nd4 Bxc5 11. Nxe6 fxe6 12. Bg4 Qd6 13. Bh3 Rae8 14. Qd2 +Bb4 15. Bxf6 Rxf6 16. Rad1 Qc5 17. Qe2 Bxc3 18. bxc3 Qxc3 19. Rxd5 Nd4 20. Qh5 +Ref8 21. Re5 Rh6 22. Qg5 Rxh3 23. Rc5 Qg3 0-1 diff --git a/crates/game-review/chesscom/morphy-opera.pgn b/crates/game-review/chesscom/morphy-opera.pgn new file mode 100644 index 0000000..f547169 --- /dev/null +++ b/crates/game-review/chesscom/morphy-opera.pgn @@ -0,0 +1,12 @@ +[Event "Paris Opera"] +[Site "Paris FRA"] +[Date "1858.??.??"] +[White "Morphy, Paul"] +[Black "Duke Karl / Count Isouard"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 7. Qb3 $1 Qe7 8. +Nc3 c6 9. Bg5 b5 10. Nxb5 $3 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 13. Rxd7 $3 Rxd7 14. +Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+ $3 Nxb8 17. Rd8# 1-0 diff --git a/crates/game-review/chesscom/owner-matovalov-1.pgn b/crates/game-review/chesscom/owner-matovalov-1.pgn new file mode 100644 index 0000000..a4a07b2 --- /dev/null +++ b/crates/game-review/chesscom/owner-matovalov-1.pgn @@ -0,0 +1,15 @@ +[Event "rated rapid game"] +[Site "https://lichess.org/game/GPGwoXk9"] +[Date "2026.10.29"] +[White "Matovalov"] +[Black "SrihasSM"] +[Result "1-0"] +[OwnerPlain "Be2"] +[Annotator "The owner: 10.Be2 is no ! (2026-10-29)"] + +1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Nge7 6. Na3 Bd7 7. Nc2 Nf5 8. Bd3 +Nh4 9. O-O c4 10. Be2 Nxf3+ 11. Bxf3 Be7 12. Bf4 b5 13. a3 Qb6 14. Be3 O-O-O 15. +a4 b4 16. a5 Nxa5 17. cxb4 Nb3 18. Ra3 Kc7 19. Bd2 Bb5 20. Bc3 g5 21. Na1 Nxa1 +22. Qxa1 a6 23. Qd1 Qc6 24. Bh5 Qe8 25. Qa1 Kb7 26. Bd1 Qf8 27. Ba4 Ra8 28. Bxb5 +axb5 29. Ra5 Kb6 30. Qa3 Rxa5 31. Qxa5+ Kc6 32. Qa6+ Kc7 33. Qa7+ Kc8 34. Ra1 +Bd8 35. Qa6+ Kc7 36. Qxb5 1-0 diff --git a/crates/game-review/chesscom/owner-matovalov-2.pgn b/crates/game-review/chesscom/owner-matovalov-2.pgn new file mode 100644 index 0000000..59214f5 --- /dev/null +++ b/crates/game-review/chesscom/owner-matovalov-2.pgn @@ -0,0 +1,27 @@ +[Event "rated rapid game"] +[Site "https://lichess.org/game/Sc0SWXkI"] +[Date "2026.10.29"] +[White "Matovalov"] +[Black "Karataschessnew"] +[Result "1-0"] +[OwnerPlain "Ra7 Ra7+"] +[Annotator "The owner: Ra7 is no ! (2026-10-29)"] + +1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. e5 Ne4 6. O-O d5 7. exd6 Nxd6 8. +Re1+ Be7 9. Bb3 Bg4 10. h3 Bxf3 11. Qxf3 Qd7 12. Bf4 O-O 13. Nd2 Bf6 14. Bxd6 +Qxd6 15. Ne4 Qe7 16. Nxf6+ Qxf6 17. Qxf6 gxf6 18. Rad1 Rad8 19. Rd2 Rd6 20. Red1 +Kg7 21. Ba4 f5 22. Rd3 Kf6 23. R1d2 Rfd8 24. Bxc6 Rxc6 25. Re2 Re6 26. Red2 Re1+ +27. Kh2 c5 28. b4 cxb4 29. Rxd4 Rxd4 30. Rxd4 a5 31. Rd5 a4 32. Rb5 Rb1 33. Rxb7 +Rb2 34. f4 a3 35. Rb6+ Kg7 36. Rb5 Rxa2 37. Rxb4 Rxc2 38. Ra4 Ra2 39. Ra6 Ra1 +40. h4 a2 41. h5 f6 42. Ra7+ Kh6 43. Kg3 Kxh5 44. Rxh7+ Kg6 45. Ra7 Kh6 46. Kh2 +Rf1 47. Rxa2 Rxf4 48. Ra8 Rg4 49. Kg1 Kg5 50. Kf2 f4 51. Ra5+ Kg6 52. Kf3 f5 53. +Ra8 Kg7 54. Ra7+ Kf6 55. Ra6+ Ke5 56. Ra5+ Kd4 57. Rxf5 Rg3+ 58. Kxf4 Rxg2 59. +Rg5 Rf2+ 60. Kg4 Rf1 61. Ra5 Rf8 62. Ra4+ Kd5 63. Ra5+ Ke6 64. Ra6+ Kf7 65. Ra7+ +Kg8 66. Kg5 Rf1 67. Ra8+ Kg7 68. Ra7+ Kf8 69. Ra8+ Ke7 70. Ra7+ Kd8 71. Ra8+ Kc7 +72. Ra7+ Kb8 73. Rg7 Ka8 74. Kg6 Re1 75. Kh7 Kb8 76. Kg6 Ra1 77. Kf6 Ra6+ 78. +Ke5 Ka8 79. Re7 Ra1 80. Rg7 Kb8 81. Kf6 Ra2 82. Rg5 Ra1 83. Re5 Kc7 84. Re7+ Kd6 +85. Re6+ Kd5 86. Re5+ Kd4 87. Rh5 Rf1+ 88. Kg7 Rf4 89. Ra5 Kc4 90. Ra4+ Kd5 91. +Rxf4 Ke5 92. Rf6 Kd5 93. Kf7 Kd4 94. Rf5 Ke4 95. Ke6 Kd4 96. Rh5 Ke4 97. Rh4+ +Ke3 98. Kf5 Kd3 99. Ke5 Ke3 100. Rh3+ Kd2 101. Ke4 Kc2 102. Kd4 Kb2 103. Kc4 Kc2 +104. Rh2+ Kd1 105. Kc3 Ke1 106. Rg2 Kf1 107. Ra2 Ke1 108. Kd3 Kf1 109. Ke3 Kg1 +110. Kf3 Kh1 111. Kg3 1-0 diff --git a/crates/game-review/chesscom/pending/README.md b/crates/game-review/chesscom/pending/README.md new file mode 100644 index 0000000..a7c439d --- /dev/null +++ b/crates/game-review/chesscom/pending/README.md @@ -0,0 +1,49 @@ +# Партии, отданные владельцу длÑ� chess.com + +Ð�аш прогноз запиÑ�ан **до** ответа chess.com — чеÑ�тнаÑ� проверка (партиÑ� не учаÑ�твовала в +наÑ�тройке). Когда ответ придёт: отметки chess.com впиÑ�ать NAG-ами, файл перенеÑ�ти в +`chesscom/`, Ñ�равнить Ñ� прогнозом. + +## giri-gukesh-2024.pgn (отдана 2026-10-28) + +Прогноз (фикÑ�ированный режим, Ñ�трогие «!»), запиÑ�ан до ответа chess.com: + +- 20... Rxd3 !! +- 24. Bxc6 !! + +## ПÑ�ть партий из вÑ�троенной клаÑ�Ñ�ики (отданы 2026-10-29) + +Прогноз (фикÑ�ированный режим, правила поÑ�ле «тихого отÑ�туплениÑ�»), запиÑ�ан до ответов chess.com: + +- polugaevsky-nezhmetdinov.pgn: 19.f4 !, 21…Qh2+ !, 22.Ke3 !, 24…Rxf4 !!, 25…Rf3+ ! +- tal-larsen.pgn: 32.Kd2 !, 34.Bc5 !!, 35.Re8+ !, 36.Qe6+ ! +- short-timman.pgn: отметок нет +- topalov-shirov.pgn: 26…Nb4 !!, 40.Re3 !!, 47…Bh3 !!, 48…Kf5 !, 49…Ke4 !, 50…d4 !, 51…Kd3 !, 52…Kc4 ! +- aronian-anand.pgn: 15…Bc5 !!, 16…Nde5 !!, 23…Be3 !! + +## Итоги прошлых партий + +- **byrne-fischer.pgn** (2026-10-28): прогноз до ответа — !! 2 из 3 (17…Be6!! не нашли: ферзь + виÑ�ел и до хода), ! 1 из 1, лишних ! 4 (12…Nxc3, 13…Nxe4, 18…Bxc4+, 17…Be6 как «!»). + ПеренеÑ�ена в набор. +- **kasparov-topalov.pgn** (2026-10-28): прогноз до ответа — !! 3 из 5 (нет 33.c3+, 37.Rd7; + лишний 24.Rxd4), ! 6 из 8 (лишних 6). ПеренеÑ�ена в набор. +- **morphy-opera.pgn** (2026-10-28): прогноз до ответа (Ñ�трогие «!») — !! 2 из 3 (нет + 10.Nxb5 — конь за две пешки, чиÑ�таÑ� потерÑ� 1 при пороге 2), лишних нет; ! 0 из 1 (7.Qb3). + Порог жертвы 1 вмеÑ�то 2 пробовали: находит 10.Nxb5 и 22…Rxh3, но даёт ложные !! на + 22.Nd5 (КаÑ�паров) и 17…Rxc3 (ПиллÑ�бери) — отброшен. ПеренеÑ�ена в набор. +- **byrne-fischer-2.pgn**: та же партиÑ� в другом порÑ�дке ходов дебюта, отметки chess.com + те же плюÑ� 9.e4!. +- **polugaevsky-nezhmetdinov.pgn** (2026-10-29): прогноз до ответа — !! 1 из 2 (нет 19…Be6!!), + ! 4 из 10, лишних нет (вÑ�е 5 наших отметок — у chess.com). 22.Ke3 (уход из-под шаха) у + chess.com тоже «!». ПеренеÑ�ена в набор. +- **tal-larsen.pgn** (2026-10-29): прогноз до ответа — !! 1 из 1 (34.Bc5), ! 2 из 9, лишний 1 + (32.Kd2 — уход королÑ� из-под шаха; 22.Ke3 у ПолугаевÑ�кого chess.com отметил). ПеренеÑ�ена. +- **short-timman.pgn** (2026-10-29): прогноз до ответа — отметок нет; у chess.com 34.Kg5!! (поход + королÑ�, не жертва материала) и Ñ�емь «!» белых. !! 0 из 1, ! 0 из 7, лишних нет. ПеренеÑ�ена. +- **topalov-shirov.pgn** (2026-10-29): прогноз до ответа — !! 2 из 2 (40.Re3, 47…Bh3), лишний !! + 26…Nb4 (у chess.com «!»); ! 4 из 12, лишний 50…d4. Снимок chess.com — Ñ� 14-го хода. ПеренеÑ�ена. +- **aronian-anand.pgn** (2026-10-29): прогноз до ответа — !! 3 из 4 (нет 13…Ng4), лишних нет; ! 0 из 3. + ПеренеÑ�ена. +- **Итог пÑ�ти партий до правок:** !! найдено 7 из 10, наших верных 7 из 8; ! найдено 10 из 41, наших + верных 10 из 12. Следующий шаг (одобрен владельцем): «неочевидноÑ�ть» хода по неглубокому поиÑ�ку. diff --git a/crates/game-review/chesscom/pending/giri-gukesh-2024.pgn b/crates/game-review/chesscom/pending/giri-gukesh-2024.pgn new file mode 100644 index 0000000..0b5ee6a --- /dev/null +++ b/crates/game-review/chesscom/pending/giri-gukesh-2024.pgn @@ -0,0 +1,19 @@ +[Event "Tata Steel Chess 2024"] +[Site "Wijk aan Zee NED"] +[Date "2024.01.16"] +[Round "4"] +[White "Giri, Anish"] +[Black "Gukesh, Dommaraju"] +[Result "1-0"] + +1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d3 d5 5. cxd5 Nxd5 6. g3 Nf6 7. Bg5 Be7 8. Bg2 +O-O 9. O-O h6 10. Bxf6 Bxf6 11. Rb1 a5 12. a3 Nd4 13. e3 Nxf3+ 14. Bxf3 c6 15. +Qc2 Bf5 16. Rfd1 Qd7 17. Na4 Qc7 18. b4 axb4 19. axb4 Rfd8 20. b5 Rxd3 21. Rxd3 +Bxd3 22. Qxd3 Rxa4 23. bxc6 bxc6 24. Bxc6 Ra7 25. Bd5 Qd8 26. h4 h5 27. Rb5 Rd7 +28. Qb3 Qe7 29. Bc6 Rd6 30. Rb8+ Rd8 31. Rb7 Qe6 32. Qxe6 fxe6 33. Be4 g5 34. +Bh7+ Kh8 35. hxg5 Bxg5 36. Bg6 Rd1+ 37. Kg2 Rd2 38. Kf1 h4 39. gxh4 Bf6 40. Rf7 +Bg7 41. h5 Rd8 42. Re7 Bf6 43. Rxe6 Rf8 44. Bf5 Kg7 45. Kg2 Kh6 46. Bg4 Kg5 47. +Kg3 Rf7 48. Rb6 Rf8 49. Rb7 Kh6 50. Ra7 Bg7 51. Bf3 Rf5 52. Rb7 Rf8 53. Be4 Rf6 +54. Rd7 Rf8 55. Ra7 Rf6 56. Ra2 Rf8 57. Kg4 Rf6 58. Bf5 Rb6 59. Ra7 Rc6 60. Kf3 +Rc4 61. Bd3 Rc6 62. Ke4 Rf6 63. f3 Bh8 64. Bc4 Rb6 65. Bf7 Bg7 66. Bg6 Rb4+ 67. +Kf5 Rb3 68. Ra6 Rb8 69. Bf7+ Kh7 70. Kg5 Bf8 71. Bg6+ Kh8 72. Re6 1-0 diff --git a/crates/game-review/chesscom/pillsbury-lasker.pgn b/crates/game-review/chesscom/pillsbury-lasker.pgn new file mode 100644 index 0000000..3262a1f --- /dev/null +++ b/crates/game-review/chesscom/pillsbury-lasker.pgn @@ -0,0 +1,15 @@ +[Event "St. Petersburg"] +[Site "St. Petersburg RUE"] +[Date "1896.01.04"] +[White "Pillsbury, Harry Nelson"] +[Black "Lasker, Emanuel"] +[Result "0-1"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. Bg5 cxd4 6. Qxd4 Nc6 7. Qh4 Be7 8. +O-O-O Qa5 9. e3 Bd7 10. Kb1 h6 11. cxd5 exd5 12. Nd4 O-O 13. Bxf6 Bxf6 14. Qh5 +Nxd4 15. exd4 Be6 16. f4 Rac8 17. f5 Rxc3 18. fxe6 $1 Ra3 $3 19. exf7+ Rxf7 20. +bxa3 Qb6+ $1 21. Bb5 Qxb5+ 22. Ka1 Rc7 23. Rd2 $1 Rc4 24. Rhd1 Rc3 25. Qf5 Qc4 +26. Kb2 Rxa3 $3 27. Qe6+ Kh7 28. Kxa3 Qc3+ $1 29. Ka4 b5+ $3 30. Kxb5 Qc4+ $1 31. +Ka5 Bd8+ $1 32. Qb6 Bxb6# 0-1 diff --git a/crates/game-review/chesscom/polugaevsky-nezhmetdinov.pgn b/crates/game-review/chesscom/polugaevsky-nezhmetdinov.pgn new file mode 100644 index 0000000..391e28d --- /dev/null +++ b/crates/game-review/chesscom/polugaevsky-nezhmetdinov.pgn @@ -0,0 +1,16 @@ +[Event "RSFSR-ch18"] +[Site "Sochi"] +[Date "1958.??.??"] +[Round "?"] +[White "Polugaevsky, Lev"] +[Black "Nezhmetdinov, Rashid"] +[Result "0-1"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] + +1. d4 Nf6 2. c4 d6 3. Nc3 e5 4. e4 exd4 5. Qxd4 Nc6 6. Qd2 g6 7. b3 Bg7 8. Bb2 +O-O 9. Bd3 Ng4 10. Nge2 Qh4 11. Ng3 Nge5 12. O-O f5 13. f3 Bh6 $1 14. Qd1 f4 15. +Nge2 g5 16. Nd5 $1 g4 17. g3 $1 fxg3 18. hxg3 Qh3 $1 19. f4 $1 Be6 $3 20. Bc2 Rf7 21. Kf2 Qh2+ $1 +22. Ke3 $1 Bxd5 23. cxd5 Nb4 $1 24. Rh1 Rxf4 $3 25. Rxh2 Rf3+ $1 26. Kd4 Bg7 27. a4 c5+ $1 28. +dxc6 bxc6 29. Bd3 Nexd3+ 30. Kc4 d5+ 31. exd5 cxd5+ 32. Kb5 Rb8+ 33. Ka5 Nc6+ +0-1 diff --git a/crates/game-review/chesscom/reti-tartakower.pgn b/crates/game-review/chesscom/reti-tartakower.pgn new file mode 100644 index 0000000..dc995b4 --- /dev/null +++ b/crates/game-review/chesscom/reti-tartakower.pgn @@ -0,0 +1,11 @@ +[Event "Vienna"] +[Site "Vienna AUT"] +[Date "1910.??.??"] +[White "Reti, Richard"] +[Black "Tartakower, Saviely"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Qd3 e5 6. dxe5 Qa5+ 7. Bd2 $1 Qxe5 +8. O-O-O $1 Nxe4 9. Qd8+ $3 Kxd8 10. Bg5+ $1 Kc7 11. Bd8# 1-0 diff --git a/crates/game-review/chesscom/rodent-roman-2026-10-27.pgn b/crates/game-review/chesscom/rodent-roman-2026-10-27.pgn new file mode 100644 index 0000000..f42e595 --- /dev/null +++ b/crates/game-review/chesscom/rodent-roman-2026-10-27.pgn @@ -0,0 +1,18 @@ +[Event "ПартиÑ� Ñ� компьютером"] +[Site "ChessPenguin"] +[Date "2026.10.27"] +[White "Rodent IV 2200 (Spassky)"] +[Black "Roman"] +[Result "0-1"] +[ChessComMarks "!!"] +[Annotator "chess.com Game Review (owner, 2026-10-28): only !! compared; 18.Bxa7 is no !!"] + +1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 Qa5 8. +O-O O-O 9. Bb3 d6 10. f3 Bd7 11. Qe1 Nxd4 12. Bxd4 Bc6 13. Nd5 Qd8 14. Nxf6+ +exf6 15. Qc3 d5 16. Rad1 dxe4 17. fxe4 Bxe4 18. Bxa7 Qc8 19. Bd4 Qg4 20. Rd2 +Rad8 21. h3 Qg5 22. Rff2 Rxd4 $3 23. Rxd4 f5 24. Qd2 Qg3 25. Rd8 Qc7 26. Rxf8+ +Bxf8 27. Kf1 Bc5 28. Qc3 Qd6 29. Rd2 Qf4+ 30. Ke1 Bxg2 $3 31. Rd8+ Bf8 32. Ke2 +Qf1+ 33. Kd2 Qf4+ 34. Qe3 Qxe3+ 35. Kxe3 Bxh3 36. Kf4 Kg7 37. Rd7 Kh6 38. Bxf7 +g5+ 39. Kg3 Bf1 40. Rxb7 g4 41. Bg8 Kg5 42. Kf2 Bh3 43. Rb5 Kh4 44. Bxh7 g3+ 45. +Kg1 f4 46. Be4 Kg4 47. Bf5+ Kh4 48. Bxh3 Kxh3 49. Rf5 Bd6 50. a4 Kg4 51. Rd5 Bb8 +52. c4 f3 53. b4 g2 54. c5 Kh3 55. b5 Bh2+ 56. Kf2 g1=Q+ 0-1 diff --git a/crates/game-review/chesscom/rotlewi-rubinstein.pgn b/crates/game-review/chesscom/rotlewi-rubinstein.pgn new file mode 100644 index 0000000..d8d5734 --- /dev/null +++ b/crates/game-review/chesscom/rotlewi-rubinstein.pgn @@ -0,0 +1,13 @@ +[Event "Lodz"] +[Site "Lodz POL"] +[Date "1907.12.26"] +[White "Rotlewi, Georg A"] +[Black "Rubinstein, Akiba"] +[Result "0-1"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. d4 d5 2. Nf3 e6 3. e3 c5 4. c4 Nc6 5. Nc3 Nf6 6. dxc5 Bxc5 7. a3 a6 8. b4 Bd6 +9. Bb2 O-O 10. Qd2 Qe7 11. Bd3 dxc4 12. Bxc4 b5 13. Bd3 Rd8 14. Qe2 Bb7 15. O-O +Ne5 16. Nxe5 Bxe5 17. f4 Bc7 18. e4 Rac8 19. e5 Bb6+ 20. Kh1 Ng4 $3 21. Be4 Qh4 +22. g3 Rxc3 $3 23. gxh4 Rd2 $3 24. Qxd2 Bxe4+ 25. Qg2 Rh3 0-1 diff --git a/crates/game-review/chesscom/short-timman.pgn b/crates/game-review/chesscom/short-timman.pgn new file mode 100644 index 0000000..910eb79 --- /dev/null +++ b/crates/game-review/chesscom/short-timman.pgn @@ -0,0 +1,16 @@ +[Event "Tilburg"] +[Site "Tilburg"] +[Date "1991.10.??"] +[Round "4"] +[White "Short, Nigel D"] +[Black "Timman, Jan H"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] + +1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 g6 5. Bc4 Nb6 6. Bb3 Bg7 7. Qe2 Nc6 8. O-O +O-O 9. h3 a5 10. a4 $1 dxe5 11. dxe5 Nd4 12. Nxd4 $1 Qxd4 13. Re1 e6 14. Nd2 Nd5 15. +Nf3 Qc5 16. Qe4 Qb4 17. Bc4 Nb6 18. b3 $1 Nxc4 19. bxc4 Re8 20. Rd1 Qc5 21. Qh4 b6 +22. Be3 $1 Qc6 23. Bh6 $1 Bh8 24. Rd8 Bb7 25. Rad1 $1 Bg7 26. R8d7 $1 Rf8 27. Bxg7 Kxg7 28. +R1d4 Rae8 29. Qf6+ Kg8 30. h4 h5 31. Kh2 Rc8 32. Kg3 Rce8 33. Kf4 Bc8 34. Kg5 $3 +1-0 diff --git a/crates/game-review/chesscom/steinitz-bardeleben.pgn b/crates/game-review/chesscom/steinitz-bardeleben.pgn new file mode 100644 index 0000000..1c06c14 --- /dev/null +++ b/crates/game-review/chesscom/steinitz-bardeleben.pgn @@ -0,0 +1,14 @@ +[Event "Hastings"] +[Site "Hastings ENG"] +[Date "1895.08.17"] +[White "Steinitz, William"] +[Black "Von Bardeleben, Curt"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] + +1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 d5 8. +exd5 Nxd5 9. O-O $1 Be6 10. Bg5 Be7 11. Bxd5 Bxd5 12. Nxd5 Qxd5 13. Bxe7 Nxe7 +14. Re1 f6 15. Qe2 Qd7 $1 16. Rac1 c6 17. d5 cxd5 18. Nd4 Kf7 $1 19. Ne6 Rhc8 +20. Qg4 $1 g6 21. Ng5+ $1 Ke8 22. Rxe7+ $3 Kf8 23. Rf7+ Kg8 24. Rg7+ $3 Kh8 25. +Rxh7+ 1-0 diff --git a/crates/game-review/chesscom/tal-larsen.pgn b/crates/game-review/chesscom/tal-larsen.pgn new file mode 100644 index 0000000..1067831 --- /dev/null +++ b/crates/game-review/chesscom/tal-larsen.pgn @@ -0,0 +1,16 @@ +[Event "Candidats sf1"] +[Site "Bled"] +[Date "1965.??.??"] +[Round "10"] +[White "Tal, Mihail"] +[Black "Larsen, Bent"] +[Result "1-0"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] + +1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 e6 5. Nc3 d6 6. Be3 Nf6 7. f4 Be7 8. Qf3 +O-O 9. O-O-O Qc7 10. Ndb5 Qb8 $1 11. g4 a6 12. Nd4 $1 Nxd4 13. Bxd4 b5 14. g5 Nd7 $1 15. +Bd3 b4 16. Nd5 exd5 17. exd5 f5 18. Rde1 Rf7 19. h4 $1 Bb7 20. Bxf5 Rxf5 21. Rxe7 +Ne5 22. Qe4 $1 Qf8 23. fxe5 Rf4 24. Qe3 $1 Rf3 25. Qe2 Qxe7 26. Qxf3 dxe5 27. Re1 $1 Rd8 +28. Rxe5 Qd6 29. Qf4 Rf8 30. Qe4 b3 31. axb3 Rf1+ 32. Kd2 Qb4+ 33. c3 Qd6 34. +Bc5 $3 Qxc5 35. Re8+ $1 Rf8 36. Qe6+ $1 Kh8 37. Qf7 1-0 diff --git a/crates/game-review/chesscom/topalov-shirov.pgn b/crates/game-review/chesscom/topalov-shirov.pgn new file mode 100644 index 0000000..b6c93b8 --- /dev/null +++ b/crates/game-review/chesscom/topalov-shirov.pgn @@ -0,0 +1,18 @@ +[Event "Linares"] +[Site "Linares"] +[Date "1998.03.04"] +[Round "10"] +[White "Topalov, Veselin"] +[Black "Shirov, Alexei"] +[Result "0-1"] +[ChessComMarks "!! !"] +[Annotator "chess.com Game Review (owner's screenshot from move 14, 2026-10-29)"] + +1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bb5+ c6 8. +Ba4 O-O 9. Ne2 Nd7 10. O-O e5 11. f3 Qe7 12. Be3 Rd8 13. Qc2 Nb6 14. Bb3 $1 Be6 15. +Rad1 Nc4 16. Bc1 b5 17. f4 $1 exd4 18. Nxd4 Bg4 19. Rde1 $1 Qc5 20. Kh1 a5 21. h3 Bd7 +22. a4 $1 bxa4 23. Ba2 $1 Be8 24. e5 Nb6 25. f5 Nd5 26. Bd2 Nb4 $1 27. Qxa4 Nxa2 28. Qxa2 +Bxe5 29. fxg6 hxg6 30. Bg5 Rd5 31. Re3 $1 Qd6 32. Qe2 Bd7 33. c4 Bxd4 34. cxd5 Bxe3 +35. Qxe3 Re8 36. Qc3 Qxd5 37. Bh6 Re5 38. Rf3 $1 Qc5 39. Qa1 Bf5 40. Re3 $3 f6 41. +Rxe5 Qxe5 42. Qa2+ Qd5 43. Qxd5+ cxd5 44. Bd2 a4 45. Bc3 Kf7 46. h4 Ke6 $1 47. Kg1 +Bh3 $3 48. gxh3 Kf5 $1 49. Kf2 Ke4 $1 50. Bxf6 d4 51. Be7 Kd3 $1 52. Bc5 Kc4 $1 53. Be7 Kb3 0-1 diff --git a/crates/game-review/examples/chesscom_check.rs b/crates/game-review/examples/chesscom_check.rs new file mode 100644 index 0000000..31be3d8 --- /dev/null +++ b/crates/game-review/examples/chesscom_check.rs @@ -0,0 +1,289 @@ +//! Our !! and ! against chess.com's on every game of `chesscom/` (see its README): run it +//! after each change of the rules, to see that a fix for one game broke no other. +//! +//! `cargo run --release -p game-review --example chesscom_check -- ` +//! +//! The engine searches as in the program: the fixed search of the game analysis +//! (`game_review::SEARCH_NODES` nodes, one thread, a clear hash), in one engine process +//! per CPU. `` is ChessPenguin's Stockfish 19. +//! +//! `CP_REVIEW_NODES=N` searches N nodes instead, for choosing the program's nodes (the +//! program itself never does): its evaluations are cached apart. +//! +//! How hard a move is to find (`game_review::Hardness`, being tried out; the program +//! does not use it yet), only for choosing its rules here: +//! - `CP_GREAT_HARD=P` — ! only for a move at least P % (win) hard to find; +//! - `CP_BRILLIANT_HARD=P` — !! also for the only good move at least P % hard; +//! - `CP_GREAT_GAP=P` — the gap of ! (default 25); +//! - `CP_BRILLIANT_GAP=P` — the gap of a hard move's !! (default 25); +//! - `CP_GREAT_BANS=0` — captures and quiet retreats can be ! too; +//! - `CP_HARD_DEPTH=1` — difficulty as the shallow search's underrating of the move +//! against the deep one (`Measure::Depth`), not against its own best move; +//! - `CP_SHALLOW_NODES=S` — the shallow search's nodes (default +//! `game_review::SHALLOW_NODES`), kept with the evaluations (other nodes are searched +//! again). + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::shakmaty::Color; +use chess_core::{Game, Nag}; +use game_review::{ + GameAnalysis, Hardness, JobSettings, Judgement, Measure, SEARCH_NODES, SEARCH_VERSION, + SHALLOW_NODES, +}; + +fn main() { + let args: Vec = std::env::args().collect(); + let (Some(engine), 2) = (args.get(1), args.len()) else { + eprintln!("usage: chesscom_check "); + std::process::exit(2); + }; + let nodes: u64 = std::env::var("CP_REVIEW_NODES").map_or(SEARCH_NODES, |n| { + n.parse().expect("CP_REVIEW_NODES: a number") + }); + let number = |name: &str| { + std::env::var(name).ok().map(|v| { + v.parse::() + .unwrap_or_else(|_| panic!("{name}: a number")) + }) + }; + let defaults = Hardness::default(); + let hardness = Hardness { + great: number("CP_GREAT_HARD").or(defaults.great), + gap: number("CP_GREAT_GAP").unwrap_or(defaults.gap), + bans: number("CP_GREAT_BANS").is_none_or(|b| b != 0.0), + // `CP_BRILLIANT_HARD=0`: off. + brilliant: number("CP_BRILLIANT_HARD") + .map(Some) + .unwrap_or(defaults.brilliant) + .filter(|p| *p > 0.0), + brilliant_gap: number("CP_BRILLIANT_GAP").unwrap_or(defaults.brilliant_gap), + measure: if number("CP_HARD_DEPTH").is_some_and(|d| d != 0.0) { + Measure::Depth + } else { + Measure::Choice + }, + }; + let shallow = number("CP_SHALLOW_NODES").map_or(SHALLOW_NODES, |n| n as u64); + if hardness != defaults { + println!("{hardness:?}, shallow search {shallow} nodes"); + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + // Evaluations of one version of the fixed search are the same on every machine; + // those of other nodes go apart. + let folder = if nodes == SEARCH_NODES { + format!("v{SEARCH_VERSION}") + } else { + format!("v{SEARCH_VERSION}-{nodes}") + }; + let cache = root.join("../../target/chesscom-check").join(folder); + println!("{nodes} nodes per search"); + std::fs::create_dir_all(&cache).expect("cache folder"); + + let mut files: Vec = std::fs::read_dir(root.join("chesscom")) + .expect("chesscom/") + .filter_map(|e| Some(e.ok()?.path())) + .filter(|p| p.extension().is_some_and(|x| x == "pgn")) + .collect(); + files.sort(); + + let (mut agree, mut differ) = (0, 0); + let mut owner_wrong = 0; + // Per mark ("!!", "!"): chess.com's, found by us, ours chess.com has not. + let mut tally = [Tally::default(), Tally::default()]; + for file in files { + let text = std::fs::read_to_string(&file).expect("pgn"); + let game = chess_core::parse_str(&text).game; + let mut a = GameAnalysis::new(&game, Some(&cache)); + a.set_hardness(hardness); + a.set_shallow_nodes(shallow); + review(&mut a, &game, engine, nodes); + a.save_cache(&cache).expect("cache"); + let compared = game.tag("ChessComMarks").unwrap_or("!! !").to_owned(); + println!( + "## {} — {} ({}; compared: {compared})", + game.tag("White").unwrap_or("?"), + game.tag("Black").unwrap_or("?"), + file.file_name().unwrap().to_string_lossy(), + ); + let line = a.line().to_vec(); + // The owner's verdict, no chess.com marks: these moves (SAN, as in the game) must + // not get ! or !! — obvious moves the owner called out ("10.Be2 — какой же Ñ�то !"). + if let Some(plain) = game.tag("OwnerPlain") { + let plain: Vec<&str> = plain.split_whitespace().collect(); + for (i, j) in a.report.judgements.iter().enumerate() { + let Some(j @ (Judgement::Brilliant | Judgement::Great)) = j else { + continue; + }; + let label = game.move_label(line[i + 1]).unwrap_or_default(); + let san = label.rsplit(' ').next().unwrap_or_default(); + let mark = if *j == Judgement::Brilliant { + "!!" + } else { + "!" + }; + if plain.contains(&san) { + owner_wrong += 1; + println!(" OWNER {label:<14} ours {mark}, the owner: plain"); + } else { + println!(" ours {label:<14} {mark}"); + } + } + continue; + } + // Only chess.com's totals are known ("white !! 0 ! 1, black !! 2 ! 1"): compare + // counts, list our marks, leave the game out of the shares. + if let Some(counts) = game.tag("ChessComCounts") { + let ours = |white: bool, j: Judgement| { + a.report + .judgements + .iter() + .enumerate() + .filter(|(i, x)| **x == Some(j) && (a.movers()[*i] == Color::White) == white) + .count() + }; + println!(" chess.com: {counts}"); + println!( + " ours: white !! {} ! {}, black !! {} ! {}", + ours(true, Judgement::Brilliant), + ours(true, Judgement::Great), + ours(false, Judgement::Brilliant), + ours(false, Judgement::Great), + ); + for (i, j) in a.report.judgements.iter().enumerate() { + if let Some(j @ (Judgement::Brilliant | Judgement::Great)) = j { + let mark = if *j == Judgement::Brilliant { + "!!" + } else { + "!" + }; + let label = game.move_label(line[i + 1]).unwrap_or_default(); + println!(" ours {label:<14} {mark}"); + } + } + continue; + } + for i in 0..line.len() - 1 { + let node = line[i + 1]; + let theirs = game.node(node).map_or("", |n| mark_of_nags(n.nags())); + let ours = match a.report.judgements[i] { + Some(Judgement::Brilliant) => "!!", + Some(Judgement::Great) => "!", + _ => "", + }; + // Only the marks chess.com was compared on: with "!!" alone our ! says nothing. + let ours_compared = if ours == "!" && !compared.split(' ').any(|m| m == "!") { + "" + } else { + ours + }; + if theirs.is_empty() && ours_compared.is_empty() { + continue; + } + for (k, mark) in ["!!", "!"].into_iter().enumerate() { + let t = &mut tally[k]; + t.theirs += u32::from(theirs == mark); + t.found += u32::from(theirs == mark && ours_compared == mark); + t.extra += u32::from(ours_compared == mark && theirs != mark); + } + let label = game.move_label(node).unwrap_or_default(); + // How hard the move was to find, when the shallow search was made. + let hard = a + .eval_at(i) + .and_then(|e| Some((e.eval, e.shallow.as_ref()?))) + .filter(|(_, s)| s.nodes == shallow) + .map_or(String::new(), |(deep, s)| { + let [choice, depth] = [Measure::Choice, Measure::Depth] + .map(|m| m.difficulty(deep, s.best_eval, s.played_eval, a.movers()[i])); + format!( + " (hard: choice {choice:.1} %, depth {depth:.1} %; shallow {} {}, \ + played {}, deep {})", + s.best, + s.best_eval.format(), + s.played_eval.format(), + deep.format() + ) + }); + if theirs == ours_compared { + agree += 1; + println!(" ok {label:<14} {theirs}{hard}"); + } else { + differ += 1; + println!( + " DIFF {label:<14} chess.com {:<3} ours {}{hard}", + or_dash(theirs), + or_dash(ours_compared) + ); + } + } + } + println!("\nagree {agree}, differ {differ}, owner's plain moves marked {owner_wrong}"); + for (t, mark) in tally.iter().zip(["!!", "!"]) { + println!( + "{mark:<2} chess.com {:>3} found {:>3} ({}) ours not chess.com's {:>3} (ours {}, {} of them chess.com's)", + t.theirs, + t.found, + percent(t.found, t.theirs), + t.extra, + t.found + t.extra, + percent(t.found, t.found + t.extra), + ); + } + if differ > 0 { + std::process::exit(1); + } +} + +/// Fills in what the cache lacks (all of it the first time) at `nodes`. +fn review(a: &mut GameAnalysis, game: &Game, engine: &str, nodes: u64) { + let targets = a.begin(game, false); + if let Some(m) = &mut a.meta { + m.nodes = nodes; + } + if !targets.is_empty() { + let settings = JobSettings { + nodes, + ..JobSettings::new(game_review::processes(game_review::MAX_PROCESSES), None) + }; + let cancel = AtomicBool::new(false); + game_review::run( + uci::EngineConfig::new(engine), + &settings, + targets, + &cancel, + &mut |e| a.apply(e), + ) + .expect("engine"); + } + a.refresh(game); +} + +fn mark_of_nags(nags: &[Nag]) -> &'static str { + if nags.contains(&Nag::BRILLIANT_MOVE) { + "!!" + } else if nags.contains(&Nag::GOOD_MOVE) { + "!" + } else { + "" + } +} + +#[derive(Default)] +struct Tally { + theirs: u32, + found: u32, + extra: u32, +} + +fn percent(part: u32, whole: u32) -> String { + if whole == 0 { + "—".into() + } else { + format!("{:.0} %", 100.0 * f64::from(part) / f64::from(whole)) + } +} + +fn or_dash(mark: &str) -> &str { + if mark.is_empty() { "—" } else { mark } +} diff --git a/crates/game-review/examples/review_bench.rs b/crates/game-review/examples/review_bench.rs new file mode 100644 index 0000000..d7ce1fc --- /dev/null +++ b/crates/game-review/examples/review_bench.rs @@ -0,0 +1,73 @@ +//! Time of the fixed game analysis of one game, and a check that it is the same at any +//! number of engine processes: prints the time and a digest of every evaluation. +//! +//! `cargo run --release -p game-review --example review_bench -- ...` +//! +//! `CP_SHALLOW_NODES=S` adds the shallow searches of S nodes (for how hard a move was to +//! find, `game_review::Hardness`), as rules that use them would. + +use std::sync::atomic::AtomicBool; +use std::time::Instant; + +use game_review::{GameAnalysis, Hardness, JobSettings}; + +fn main() { + let args: Vec = std::env::args().collect(); + if args.len() < 4 { + eprintln!("usage: review_bench ..."); + std::process::exit(2); + } + let text = std::fs::read_to_string(&args[2]).expect("pgn"); + let game = chess_core::parse_str(&text).game; + let shallow: Option = std::env::var("CP_SHALLOW_NODES") + .ok() + .map(|n| n.parse().expect("CP_SHALLOW_NODES: a number")); + let mut digests = Vec::new(); + for p in &args[3..] { + let processes: usize = p.parse().expect("processes"); + let mut a = GameAnalysis::new(&game, None); + if let Some(nodes) = shallow { + a.set_shallow_nodes(nodes); + a.set_hardness(Hardness { + brilliant: Some(100.0), + ..Hardness::default() + }); + } + let targets = a.begin(&game, true); + let positions = targets.len(); + let (mut searches, mut shallows) = (0, 0); + let started = Instant::now(); + game_review::run( + uci::EngineConfig::new(&args[1]), + &JobSettings::new(processes, None), + targets, + &AtomicBool::new(false), + &mut |e| { + if let game_review::JobEvent::Eval { eval, .. } = &e { + searches += 1 + usize::from(eval.second.is_some()); + if let Some(s) = &eval.shallow { + shallows += 1 + usize::from(s.best != s.played); + } + } + a.apply(e); + }, + ) + .expect("engine"); + let secs = started.elapsed().as_secs_f64(); + // Every evaluation, line and second search, in the order of the game. + let all: Vec<_> = (0..a.line().len()).map(|i| a.eval_at(i).cloned()).collect(); + let bytes = serde_json::to_vec(&all).expect("json"); + let digest = bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3) + }); + println!( + "processes {processes:>2}: {positions} positions, {searches} searches \ + (+{shallows} shallow), {secs:.1} s, evaluations {digest:016x}" + ); + digests.push(digest); + } + if digests.windows(2).any(|w| w[0] != w[1]) { + println!("DIFFERENT evaluations"); + std::process::exit(1); + } +} diff --git a/crates/game-review/src/features.rs b/crates/game-review/src/features.rs new file mode 100644 index 0000000..2de9eb2 --- /dev/null +++ b/crates/game-review/src/features.rs @@ -0,0 +1,524 @@ +//! What a move does on the board, without an engine: a piece offered (a sacrifice), a +//! piece taken back or saved, a mate (docs/research/brilliant-moves.md §3.1, §4). The +//! engine's evaluations then say whether it was brilliant (!!) or great (!). + +use chess_core::shakmaty::{Bitboard, Board, Chess, Color, Move, Position, Role, Square}; + +/// The move as the rules of !! and ! see it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MoveFeatures { + /// Legal moves in the position: one is a forced move, never marked. + pub legal: usize, + /// The mover was in check. + pub check: bool, + pub promotion: bool, + /// The move mates. + pub mates: bool, + /// Takes back on the square where the opponent has just taken. + pub recapture: bool, + /// After the move the opponent can win a piece (a knight or more) for at least two + /// points more than the move took; not a piece selling itself (an attacked piece + /// taking something on its way, a desperado), nor one whose capture loses as much + /// back at once (the move uncovered an attack on a bigger piece: taking is no answer + /// to it). An attacked piece moved quietly to another square where it is lost is + /// offered: it could have stepped away (18…Ra3!! of Pillsbury — Lasker). + pub sacrifice: bool, + /// A pawn moved (not taking) to a square where the opponent wins it: offered, but + /// brilliant only for a quicker mate (29…b5+!! of Pillsbury — Lasker). + pub pawn_offered: bool, + pub capture: bool, + /// A capture that wins two points or more. + pub winning_capture: bool, + /// The capture only wins back what the opponent has just taken, elsewhere (18.fxe6! + /// of Pillsbury — Lasker after 17…Rxc3): no gain, so it can be great. + pub takes_back: bool, + /// The first rules' sacrifice ([`Rules::Strict`]): any piece the opponent can win + /// after the move, also one that hung before it. + pub sacrifice_any: bool, + /// A piece (not the king) under attack moves away without loss. + pub escape: bool, + /// The move goes into a position of the opening table (chess.com's «book»). + pub book: bool, + /// The move gives check. + pub gives_check: bool, + /// The king moves. + pub king_move: bool, +} + +/// Which rules decide !! and !. Both stay, to compare them and to go back. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Rules { + /// The first rules (docs/research/brilliant-moves.md §3–4): any piece left to be won + /// is a sacrifice; the move must change the outcome to be great; a piece saving + /// itself is never great; one mark a combination. + Strict, + /// Calibrated on chess.com's marks (2026-10-28): only what the move gives up is a + /// sacrifice; the only good move is great; every move of a combination counts. + #[default] + ChessCom, +} + +impl MoveFeatures { + /// `prev`: the opponent's move just before (for a recapture); `own`: the mover's move + /// before that. + pub fn of(before: &Chess, m: &Move, prev: Option<&Move>, own: Option<&Move>) -> MoveFeatures { + let mover = before.turn(); + let mut after = before.clone(); + after.play_unchecked(*m); + let taken = m.capture().map_or(0, value); + // The opponent's best gain on each of the mover's pieces after the move. + let threats = threats(&after); + // Offered by this move: the piece moved, or one the move left open to a bigger + // loss than before; a piece that hung already was not given by it (chess.com's + // reading: 18…Rg8 of the Evergreen game, the knight on e7 under the pawn on f6 + // before and after, is no sacrifice). + let given: Vec<&(i32, i32, Square)> = threats + .iter() + .filter(|t| t.2 == m.to() || pseudo_threat(before.board(), t.2, mover.other()) < t.0) + .collect(); + // The heaviest loss among `pieces` and the value of the piece lost there. + let worst = |pieces: &[&(i32, i32, Square)]| { + let threat = pieces.iter().map(|t| t.0).max().unwrap_or(0); + let offered = pieces + .iter() + .filter(|t| t.0 == threat) + .map(|t| t.1) + .max() + .unwrap_or(0); + (threat, offered) + }; + let (threat, offered) = worst(&given); + // Taking the offered piece loses at least as much straight away: 18.Bxa7 opening + // the d-file on the queen (18…Rxa7 19.Rxd8) offers nothing — chess.com gives no !!. + let taking_loses = given + .iter() + .filter(|t| t.0 == threat && t.1 == offered) + .any(|t| taking_loses(before.board(), &after, t.2, threat)); + let (threat_any, offered_any) = worst(&threats.iter().collect::>()); + // The moved piece was hanging where it stood: losing it is no sacrifice. + let from_threat = m + .from() + .map_or(0, |f| pseudo_threat(before.board(), f, mover.other())); + let lost_anyway = from_threat >= 2; + let desperado = lost_anyway && m.is_capture(); + let on_target = threats.iter().find(|t| t.2 == m.to()).map_or(0, |t| t.0); + let gain = taken - on_target; + MoveFeatures { + legal: before.legal_moves().len(), + check: before.is_check(), + promotion: m.is_promotion(), + mates: after.is_checkmate(), + recapture: m.is_capture() && prev.is_some_and(|p| p.is_capture() && p.to() == m.to()), + sacrifice: offered >= 3 && taken - threat <= -2 && !desperado && !taking_loses, + pawn_offered: m.role() == Role::Pawn + && !m.is_capture() + && pseudo_threat(after.board(), m.to(), mover.other()) > 0, + capture: m.is_capture(), + winning_capture: m.is_capture() && gain >= 2, + takes_back: m.is_capture() + && prev.is_some_and(|p| { + // Not the piece the mover had just put there: taking it accepted an + // offer, and winning something now goes on with the combination + // (24…Bxe4+ of Rotlewi — Rubinstein after 23…Rd2 24.Qxd2). + p.capture().is_some_and(|r| gain - value(r) < 2) + && own.is_none_or(|o| o.to() != p.to()) + }), + sacrifice_any: offered_any >= 3 && taken - threat_any <= -2 && !lost_anyway, + escape: lost_anyway && from_threat < 900 && gain >= 0, + book: chess_openings::in_book(chess_openings::key(&after)), + gives_check: after.is_check(), + king_move: m.role() == Role::King, + } + } + + /// Could be brilliant: a sacrifice by choice. + pub fn brilliant_shape(&self, rules: Rules) -> bool { + let sacrifice = match rules { + Rules::Strict => self.sacrifice_any, + Rules::ChessCom => self.sacrifice, + }; + sacrifice + && self.legal > 1 + && !self.check + && !self.promotion + && !(rules == Rules::ChessCom && self.book) + } + + /// Could be great: not a forced, obvious or finishing move. With [`Rules::ChessCom`] + /// a piece saving itself on the only good square can be (13.Qa4 of the Evergreen + /// game), a book move cannot (6…Bb4+ of Steinitz — von Bardeleben). `bans`: the + /// quiet retreat is not ([`crate::report::Hardness::bans`]). + pub fn great_shape(&self, rules: Rules, bans: bool) -> bool { + self.legal > 1 + && !(rules == Rules::ChessCom && self.book) + && !self.mates + && !self.recapture + && !(self.winning_capture && !(rules == Rules::ChessCom && self.takes_back)) + && !(rules == Rules::Strict && self.escape) + // An attacked piece stepping quietly to its one good square is plain, not + // great (10.Be2 of an online game, the owner: «какой же Ñ�то !»); stepping away + // with check is an attack (19…Ne2+ of Byrne — Fischer, chess.com's !). + && !(rules == Rules::ChessCom && bans && self.escape && !self.gives_check) + // The king stepping out of check is plain too (the owner, 2026-10-29: 23.Kd3 of + // Capablanca — Marshall, 20…Ka7 of Kasparov — Topalov, 32.Kd2 of Tal — Larsen). + && !(rules == Rules::ChessCom && bans && self.check && self.king_move) + } + + /// Worth asking the engine for the best other move (under either rules: one analysis + /// serves both); `bans` as for [`Self::great_shape`]. + pub fn candidate(&self, bans: bool) -> bool { + [Rules::Strict, Rules::ChessCom].into_iter().any(|r| { + self.brilliant_shape(r) + || self.pawn_shape(r) + || self.great_shape(r, r == Rules::Strict || bans) + }) + } + + /// Could be brilliant for a quicker mate only: a pawn offered ([`Rules::ChessCom`]). + pub fn pawn_shape(&self, rules: Rules) -> bool { + rules == Rules::ChessCom + && self.pawn_offered + && self.legal > 1 + && !self.check + && !self.promotion + && !self.book + } +} + +/// Exchange values; the king's makes taking into a defended square never pay. +fn value(r: Role) -> i32 { + match r { + Role::Pawn => 1, + Role::Knight | Role::Bishop => 3, + Role::Rook => 5, + Role::Queen => 9, + Role::King => 1000, + } +} + +/// Static exchange on `sq`: what `side` gains taking first with the piece on `first`, +/// both sides then taking with their cheapest piece and free to stop (x-rays count). +fn see(board: &Board, sq: Square, first: Square, side: Color) -> i32 { + let (Some(target), Some(attacker)) = (board.role_at(sq), board.role_at(first)) else { + return 0; + }; + let mut gains = vec![value(target)]; + let mut occupied = board.occupied() ^ Bitboard::from_square(first); + let mut on_square = value(attacker); + let mut turn = side.other(); + loop { + let cheapest = (board.attacks_to(sq, turn, occupied) & occupied) + .into_iter() + .filter_map(|a| Some((value(board.role_at(a)?), a))) + .min(); + let Some((v, a)) = cheapest else { break }; + let last = gains[gains.len() - 1]; + gains.push(on_square - last); + on_square = v; + occupied ^= Bitboard::from_square(a); + turn = turn.other(); + } + for d in (1..gains.len()).rev() { + gains[d - 1] = -(-gains[d - 1]).max(gains[d]); + } + gains[0] +} + +/// The pieces (a knight or more) the side to move can win, with legal first captures: +/// (gain, value of the piece, its square). +fn threats(pos: &Chess) -> Vec<(i32, i32, Square)> { + let us = pos.turn(); + let board = pos.board(); + let legal = pos.legal_moves(); + let mut out = Vec::new(); + for sq in board.by_color(us.other()) { + let Some(r) = board.role_at(sq) else { continue }; + if matches!(r, Role::King | Role::Pawn) { + continue; + } + let first = legal + .iter() + .filter(|m| m.to() == sq && m.is_capture() && !m.is_en_passant()) + .filter_map(|m| Some((value(m.role()), m.from()?))) + .min(); + if let Some((_, from)) = first { + let g = see(board, sq, from, us); + if g > 0 { + out.push((g, value(r), sq)); + } + } + } + out +} + +/// In `pos` (the opponent to move), taking on `sq` with the cheapest piece lets the +/// mover win at least `threat` elsewhere at once, with a threat the move itself made: +/// there after the move (before the capture), not before it (`before`: the board before +/// the move). One the capture opens is the point of a real sacrifice: 22.Rxe7+!! of +/// Steinitz — von Bardeleben, 22…Qxe7 23.Rxc8+ (the queen left d7); one standing +/// already is too: 37.Rd7!! of Kasparov — Topalov (the queen on c4 under the bishop since +/// 36.Bf1). chess.com marks both. +fn taking_loses(before: &Board, pos: &Chess, sq: Square, threat: i32) -> bool { + let Some(take) = pos + .legal_moves() + .into_iter() + .filter(|m| m.to() == sq && m.is_capture()) + .min_by_key(|m| value(m.role())) + else { + return false; + }; + let mut after = pos.clone(); + after.play_unchecked(take); + let mover = after.turn(); + threats(&after).iter().any(|t| { + t.2 != sq + && t.0 >= threat + && pseudo_threat(pos.board(), t.2, mover) >= threat + && pseudo_threat(before, t.2, mover) < threat + }) +} + +/// What `by` would win taking on `sq`, whoever is to move (a piece already hanging). +fn pseudo_threat(board: &Board, sq: Square, by: Color) -> i32 { + let first = board + .attacks_to(sq, by, board.occupied()) + .into_iter() + .filter_map(|a| Some((value(board.role_at(a)?), a))) + .min(); + first.map_or(0, |(_, a)| see(board, sq, a, by).max(0)) +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::shakmaty::fen::Fen; + use chess_core::shakmaty::san::San; + use chess_core::shakmaty::{CastlingMode, Chess}; + + fn position(fen: &str) -> Chess { + fen.parse::() + .unwrap() + .into_position(CastlingMode::Standard) + .unwrap() + } + + /// The features of the last of `moves` (SAN) played from `start`. + fn last(start: Chess, moves: &str) -> MoveFeatures { + let mut pos = start; + let mut prev = None; + let mut own = None; + let sans: Vec<&str> = moves + .split_whitespace() + .filter(|t| !t.ends_with('.')) + .collect(); + for (i, san) in sans.iter().enumerate() { + let m = san.parse::().unwrap().to_move(&pos).unwrap(); + if i + 1 == sans.len() { + return MoveFeatures::of(&pos, &m, prev.as_ref(), own.as_ref()); + } + pos.play_unchecked(m); + own = prev; + prev = Some(m); + } + unreachable!() + } + + fn features(fen: &str, san: &str) -> MoveFeatures { + last(position(fen), san) + } + + const OPERA: &str = "1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 \ + 7. Qb3 Qe7 8. Nc3 c6 9. Bg5 b5 10. Nxb5 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 \ + 13. Rxd7 Rxd7 14. Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+"; + + #[test] + fn a_queen_offered_for_mate_is_a_sacrifice() { + let f = last(Chess::default(), OPERA); + assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); + assert!(!f.mates && f.candidate(true)); + // 15.Bxd7+ Nxd7: taken back, not a move of note. + let f = last(Chess::default(), &OPERA[..OPERA.find(" 16.").unwrap()]); + assert!( + f.recapture && !f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); + } + + #[test] + fn trades_and_good_captures_are_not_sacrifices() { + let f = last( + Chess::default(), + "1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nxd4", + ); + assert!(!f.sacrifice && f.recapture, "{f:?}"); + // A free knight taken: a winning capture, never !. + let f = features("4k3/8/8/3n4/8/8/8/3QK3 w - - 0 1", "Qxd5"); + assert!( + f.winning_capture && !f.great_shape(Rules::ChessCom, true) && !f.sacrifice, + "{f:?}" + ); + } + + #[test] + fn a_piece_saved_or_lost_anyway_is_no_sacrifice() { + // The bishop on c4 attacked by the pawn on d5: Bb3 saves it — never a sacrifice, + // and a quiet step away is not great either. + let f = features("4k3/8/8/3p4/2B5/8/8/4K3 w - - 0 1", "Bb3"); + assert!( + f.escape && !f.sacrifice && !f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); + // Taking the pawn instead, into the knight: it was lost anyway (desperado). + let f = features("4k3/8/5n2/3p4/2B5/8/8/4K3 w - - 0 1", "Bxd5"); + assert!(!f.sacrifice, "{f:?}"); + } + + #[test] + fn only_what_the_move_gives_up_is_offered() { + // The knight on e5 hangs to the pawn on d6 before and after Ra2: not given by it. + // (Counting a piece left hanging as given would mark 17…Be6!! of Byrne — Fischer, + // but also 11.Rg1, 19.e5 of the Immortal game and more that chess.com does not.) + let f = features("4k3/8/3p4/4N3/8/8/8/R3K3 w - - 0 1", "Ra2"); + assert!(!f.sacrifice, "{f:?}"); + // The rook on e1 guards it; Ra1 takes the guard away: the knight is given up. + let f = features("4k3/8/3p4/4N3/8/8/8/4RK2 w - - 0 1", "Ra1"); + assert!(f.sacrifice, "{f:?}"); + } + + #[test] + fn a_piece_whose_capture_loses_more_is_not_offered() { + // 18.Bxa7 (a game against Rodent, 2026-10-27): the bishop under the rook on a8, but + // the move opens the d-file on the queen: 18…Rxa7 19.Rxd8. chess.com: no !!. + let f = last( + Chess::default(), + "1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 Qa5 \ + 8. O-O O-O 9. Bb3 d6 10. f3 Bd7 11. Qe1 Nxd4 12. Bxd4 Bc6 13. Nd5 Qd8 \ + 14. Nxf6+ exf6 15. Qc3 d5 16. Rad1 dxe4 17. fxe4 Bxe4 18. Bxa7", + ); + assert!(!f.sacrifice && !f.brilliant_shape(Rules::ChessCom), "{f:?}"); + assert!(f.sacrifice_any, "the first rules stay as they were: {f:?}"); + } + + #[test] + fn a_threat_the_capture_opens_keeps_the_sacrifice() { + // 22.Rxe7+!! (Steinitz — von Bardeleben): 22…Qxe7 23.Rxc8+ wins back, but only + // because the queen left d7. chess.com: !!. + let f = last( + Chess::default(), + "1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 d5 \ + 8. exd5 Nxd5 9. O-O Be6 10. Bg5 Be7 11. Bxd5 Bxd5 12. Nxd5 Qxd5 13. Bxe7 Nxe7 \ + 14. Re1 f6 15. Qe2 Qd7 16. Rac1 c6 17. d5 cxd5 18. Nd4 Kf7 19. Ne6 Rhc8 \ + 20. Qg4 g6 21. Ng5+ Ke8 22. Rxe7+", + ); + assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); + } + + const PILLSBURY: &str = "1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. Bg5 cxd4 6. Qxd4 Nc6 \ + 7. Qh4 Be7 8. O-O-O Qa5 9. e3 Bd7 10. Kb1 h6 11. cxd5 exd5 12. Nd4 O-O 13. Bxf6 Bxf6 \ + 14. Qh5 Nxd4 15. exd4 Be6 16. f4 Rac8 17. f5 Rxc3 18. fxe6 Ra3"; + + #[test] + fn an_attacked_piece_moved_into_another_attack_is_offered() { + // 18…Ra3!! (Pillsbury — Lasker): the rook on c3 under the pawn could step away. + let f = last(Chess::default(), PILLSBURY); + assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); + // 18.fxe6! just before: takes back the knight taken on c3, no gain. + let f = last( + Chess::default(), + &PILLSBURY[..PILLSBURY.rfind(" Ra3").unwrap()], + ); + assert!( + f.winning_capture && f.takes_back && f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); + assert!( + !f.great_shape(Rules::Strict, true), + "the first rules stay: {f:?}" + ); + } + + #[test] + fn taking_back_an_offered_piece_is_no_trade() { + // 24…Bxe4+ (Rotlewi — Rubinstein) after 23…Rd2 24.Qxd2: the combination goes on. + let f = last( + Chess::default(), + "1. d4 d5 2. Nf3 e6 3. e3 c5 4. c4 Nc6 5. Nc3 Nf6 6. dxc5 Bxc5 7. a3 a6 8. b4 Bd6 \ + 9. Bb2 O-O 10. Qd2 Qe7 11. Bd3 dxc4 12. Bxc4 b5 13. Bd3 Rd8 14. Qe2 Bb7 \ + 15. O-O Ne5 16. Nxe5 Bxe5 17. f4 Bc7 18. e4 Rac8 19. e5 Bb6+ 20. Kh1 Ng4 \ + 21. Be4 Qh4 22. g3 Rxc3 23. gxh4 Rd2 24. Qxd2 Bxe4+", + ); + assert!( + f.winning_capture && !f.takes_back && !f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); + } + + #[test] + fn a_pawn_offered_is_only_for_a_quicker_mate() { + // 29…b5+!! (Pillsbury — Lasker): the pawn under the king. + let line = format!( + "{PILLSBURY} 19. exf7+ Rxf7 20. bxa3 Qb6+ 21. Bb5 Qxb5+ 22. Ka1 Rc7 23. Rd2 Rc4 \ + 24. Rhd1 Rc3 25. Qf5 Qc4 26. Kb2 Rxa3 27. Qe6+ Kh7 28. Kxa3 Qc3+ 29. Ka4 b5+" + ); + let f = last(Chess::default(), &line); + assert!(f.pawn_offered && f.pawn_shape(Rules::ChessCom), "{f:?}"); + assert!(!f.sacrifice && !f.brilliant_shape(Rules::ChessCom), "{f:?}"); + assert!(!f.pawn_shape(Rules::Strict)); + } + + #[test] + fn a_quiet_escape_is_not_great_but_one_with_check_can_be() { + // 10.Be2 (an online game): the bishop on d3 under the pawn steps to its one good + // square — plain. + let f = last( + Chess::default(), + "1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Nge7 6. Na3 Bd7 7. Nc2 Nf5 \ + 8. Bd3 Nh4 9. O-O c4 10. Be2", + ); + assert!(f.escape && !f.gives_check, "{f:?}"); + assert!(!f.great_shape(Rules::ChessCom, true), "{f:?}"); + assert!(!f.candidate(true), "{f:?}"); + // Without the bans it is up to how hard it was to find. + assert!( + f.great_shape(Rules::ChessCom, false) && f.candidate(false), + "{f:?}" + ); + // Stepping away with check can be great. + let f = features("4k3/8/8/8/2p5/1B6/8/4K3 w - - 0 1", "Ba4+"); + assert!( + f.escape && f.gives_check && f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); + } + + #[test] + fn the_king_out_of_check_is_not_great() { + // The king in check from the rook steps to the side: plain. + let f = features("4k3/8/8/8/8/8/8/r3K3 w - - 0 1", "Ke2"); + assert!(f.check && f.king_move, "{f:?}"); + assert!(!f.great_shape(Rules::ChessCom, true), "{f:?}"); + assert!( + f.great_shape(Rules::Strict, true), + "the first rules stay: {f:?}" + ); + } + + #[test] + fn a_piece_no_one_can_legally_take_is_not_offered() { + // The rook on d7 is pinned by the bishop: the knight on d5 is no offer to it. + let f = features("4k3/3r4/8/8/B7/2N5/8/4K3 w - - 0 1", "Nd5"); + assert!(!f.sacrifice, "{f:?}"); + let f = features("4k3/3r4/8/8/8/2N5/8/4K3 w - - 0 1", "Nd5"); + assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); + } + + #[test] + fn exchanges_follow_the_cheapest_piece_and_x_rays() { + // Rook takes a pawn defended by a pawn: loses four. + let b = position("4k3/8/2p5/3p4/8/8/8/3RK3 w - - 0 1"); + assert_eq!(see(b.board(), Square::D5, Square::D1, Color::White), -4); + // Two rooks behind each other against one defender: the pawn is won. + let b = position("3rk3/8/8/3p4/8/8/3R4/3RK3 w - - 0 1"); + assert_eq!(see(b.board(), Square::D5, Square::D2, Color::White), 1); + } +} diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs new file mode 100644 index 0000000..d215e20 --- /dev/null +++ b/crates/game-review/src/job.rs @@ -0,0 +1,410 @@ +//! The engine job of a game analysis: one node-limited search per position, in engine +//! processes of its own, results reported as they come. Runs on the caller's thread +//! until it is done or cancelled; the game is never touched. +//! +//! The search is the same everywhere (decision of 2026-10-28): every position is +//! searched to [`SEARCH_NODES`] nodes by an engine with one thread and a hash of +//! [`SEARCH_HASH_MB`], cleared (`ucinewgame`) before each search. One thread and a +//! clear hash make a search depend on its position alone — not on the machine, the +//! order of the positions or what was searched before — so every computer and phone +//! gets the same evaluations, and the same marks. Speed comes from several engine +//! processes, each taking the next position; their number changes nothing but the time. + +use uci::{EnginePosition, Side}; + +use crate::PosEval; + +// What the job does for one target, whatever drives it. +mod work; +// The job in engine processes, each on a thread of its own: a computer's and a +// phone's. +#[cfg(not(target_family = "wasm"))] +mod engines; +#[cfg(not(target_family = "wasm"))] +pub use engines::run; +// Whether an engine is the Stockfish 19 of the analysis (a user's own one). +#[cfg(not(target_family = "wasm"))] +pub mod probe; +// The job in Web Workers: a browser's. +#[cfg(target_family = "wasm")] +mod workers; +#[cfg(target_family = "wasm")] +pub use workers::Dispatcher; + +/// Nodes of every search of a game analysis (0.85 s on one thread of an i7-13700KF, +/// depth about 24). +pub const SEARCH_NODES: u64 = 1_000_000; + +/// Nodes of the shallow search, for how hard a move is to find ([`crate::Measure`]): +/// made only for a move that could be brilliant or great and was the engine's best, and +/// only when the rules ask for it ([`crate::Hardness`]). At 5 000 nodes (depth about 10) +/// Stockfish already finds nearly every move of note itself; above 10 000 hardly any is +/// hard (the chess.com check set, 2026-10-29). Its time is lost in that of the full +/// searches (+0.2 % for a game). +pub const SHALLOW_NODES: u64 = 5_000; + +/// The engine's hash of every search, in MB. Part of the search: another size gives +/// other evaluations. +pub const SEARCH_HASH_MB: u32 = 32; + +/// The version of the fixed search: [`SEARCH_NODES`], [`SEARCH_HASH_MB`], one thread, a +/// clear hash, and the engine (ChessPenguin's Stockfish 19). Raised when any of them +/// changes: evaluations of another version are stale and are made again, never mixed. +pub const SEARCH_VERSION: u32 = 1; + +/// Engine processes of a job on a computer at most. +pub const MAX_PROCESSES: usize = 8; + +/// Engine processes of a job on a phone at most. +pub const PHONE_PROCESSES: usize = 4; + +/// Memory of the engine's network, shared by all its processes (Stockfish 19 keeps it +/// in shared memory), in MB. +const SHARED_MB: u64 = 200; + +/// Memory of one engine process of its own (the hash of [`SEARCH_HASH_MB`] included), +/// in MB. +const PROCESS_MB: u64 = 70; + +/// Engine processes for a job on this machine: one per logical CPU, at most `limit` +/// (and [`MAX_PROCESSES`]), and no more than the free memory holds. +pub fn processes(limit: usize) -> usize { + let cpus = std::thread::available_parallelism().map_or(1, |n| n.get()); + let memory = available_mb().map_or(usize::MAX, |mb| { + (mb.saturating_sub(SHARED_MB) / PROCESS_MB) + .try_into() + .unwrap_or(usize::MAX) + }); + cpus.min(limit).min(memory).clamp(1, MAX_PROCESSES) +} + +/// Memory available to new processes (`MemAvailable` of Linux and Android), in MB; +/// `None` where it is not known. +fn available_mb() -> Option { + let info = std::fs::read_to_string("/proc/meminfo").ok()?; + let line = info.lines().find(|l| l.starts_with("MemAvailable:"))?; + let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?; + Some(kb / 1024) +} + +/// Seconds `searches` take at `nps` nodes per second of one engine process (one +/// thread), in `processes` of them: the time estimate of a run. +pub fn estimate_secs(searches: usize, nps: f64, processes: usize) -> f64 { + let rate = nps.max(1.0) * processes.clamp(1, MAX_PROCESSES) as f64; + searches as f64 * SEARCH_NODES as f64 / rate +} + +/// A position to evaluate (from [`crate::GameAnalysis::begin`]). +#[derive(Clone, Debug)] +pub struct Target { + pub key: String, + pub pos: EnginePosition, + pub turn: Side, + /// The move played here (UCI), when it could be brilliant or great: if it is the + /// engine's best, a second search among `others` finds the best of the rest. + pub played: Option, + /// The other legal moves (UCI). + pub others: Vec, + /// The evaluation already there: only the second or shallow search is left. + pub known: Option, + /// Nodes of the shallow search of `played`, when the rules want it. + pub shallow: Option, +} + +/// How the job runs; the search itself is fixed (see the module). +#[derive(Clone, Debug)] +pub struct JobSettings { + /// Engine processes working at once (see [`processes`]). + pub processes: usize, + /// The network file of the engine (Stockfish `EvalFile`), when it is not beside it. + pub eval_file: Option, + /// Nodes per search: [`SEARCH_NODES`] in the programs. Only an experiment (the + /// chess.com check, choosing the nodes) searches otherwise, never mixing its + /// evaluations with the programs'. + pub nodes: u64, +} + +impl JobSettings { + /// The fixed search in `processes` engine processes. + pub fn new(processes: usize, eval_file: Option) -> JobSettings { + JobSettings { + processes, + eval_file, + nodes: SEARCH_NODES, + } + } +} + +/// What the job reports, for [`crate::GameAnalysis::apply`]. +#[derive(Clone, Debug)] +pub enum JobEvent { + /// The engine's own name. + Engine(String), + Eval { + key: String, + eval: PosEval, + /// The speed of the engine process in this search (one thread; 0 if it did + /// not say). + nps: u64, + }, +} + +/// Why the job stopped before the end. +#[derive(Debug)] +pub enum JobFailure { + /// The engine did not start or did not accept its settings. + Start(String), + /// Talking to the engine failed. + Engine(String), + /// The engine process ended (crashed, or hung and was killed). + Terminated(uci::TerminationReason), +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Eval; + use crate::GameAnalysis; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). + fn fake() -> &'static str { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + fake + } + + fn settings(processes: usize) -> JobSettings { + JobSettings::new(processes, None) + } + + /// The fake engine answers like Stockfish: every position gets an evaluation. + #[test] + fn the_job_evaluates_every_position() { + let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game; + let mut a = GameAnalysis::new(&game, None); + let targets = a.begin(&game, false); + let n = targets.len(); + let mut evals = 0; + let cancel = AtomicBool::new(false); + run( + uci::EngineConfig::new(fake()), + &settings(2), + targets, + &cancel, + &mut |e| { + if matches!(e, JobEvent::Eval { .. }) { + evals += 1; + } + a.apply(e); + }, + ) + .expect("the job runs"); + assert_eq!(evals, n); + a.refresh(&game); + assert_eq!(a.missing(), 0); + assert!(a.report.complete); + assert_eq!(a.meta.as_ref().map(|m| m.engine.as_str()), Some("Fake UCI")); + + // A cancelled job ends at once, without results. + let mut b = GameAnalysis::new(&game, None); + let targets = b.begin(&game, false); + cancel.store(true, Ordering::Relaxed); + let mut got = 0; + run( + uci::EngineConfig::new(fake()), + &settings(3), + targets, + &cancel, + &mut |e| { + if matches!(e, JobEvent::Eval { .. }) { + got += 1; + } + }, + ) + .expect("cancelled cleanly"); + assert_eq!(got, 0); + } + + /// The evaluations depend on the positions alone: not on the number of engine + /// processes, nor on the order of the positions. The fake engine with `--hash-memory` + /// lets earlier searches change a score, as a hash kept between searches does: only + /// a clear hash before every search gives the same results. + #[test] + fn the_evaluations_do_not_depend_on_processes_or_order() { + let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 *").game; + let evaluate = |processes: usize, reverse: bool| { + let mut a = GameAnalysis::new(&game, None); + let mut targets = a.begin(&game, false); + if reverse { + targets.reverse(); + } + let mut config = uci::EngineConfig::new(fake()); + config.args = vec!["--hash-memory".into()]; + run( + config, + &settings(processes), + targets, + &AtomicBool::new(false), + &mut |e| a.apply(e), + ) + .expect("the job runs"); + a.refresh(&game); + (0..a.line().len()) + .map(|i| a.eval_at(i).cloned()) + .collect::>() + }; + let one = evaluate(1, false); + assert!(one.iter().all(Option::is_some)); + // The fake scores differ by position: the comparison means something. + assert!(one.windows(2).any(|w| w[0] != w[1])); + assert_eq!(evaluate(1, true), one); + assert_eq!(evaluate(3, false), one); + assert_eq!(evaluate(8, true), one); + } + + /// The shallow search is made only when the rules ask how hard a move was to find, + /// for the engine's best move that could be brilliant or great; an analysis without + /// it is filled in, without evaluating anything again. The fake engine (from a FEN + /// it always says e2e4) honours `searchmoves`, and below the nodes given prefers + /// d2d4 (+0.40) to e2e4 (+0.10 searched alone). + #[test] + fn the_shallow_search_says_how_hard_the_move_was() { + let game = chess_core::parse_str( + "[FEN \"rnbqkbnr/1ppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\"] 1. e4 e5 *", + ) + .game; + let engine = |shallow_best: bool| { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec!["--searchmoves".into()]; + if shallow_best { + config.args.extend([ + "--shallow".into(), + (SHALLOW_NODES + 1).to_string().into(), + "d2d4".into(), + ]); + } + config + }; + let job = |a: &mut GameAnalysis, shallow_best: bool| { + let targets = a.begin(&game, false); + let n = targets.len(); + run( + engine(shallow_best), + &settings(2), + targets, + &AtomicBool::new(false), + &mut |e| a.apply(e), + ) + .expect("the job runs"); + a.refresh(&game); + n + }; + let mut a = GameAnalysis::new(&game, None); + // Rules that do not ask how hard a move was: no shallow search. + a.set_hardness(crate::Hardness { + brilliant: None, + ..Default::default() + }); + assert_eq!(job(&mut a, true), 3); + let e = a.eval_at(0).expect("evaluated").clone(); + assert_eq!(e.pv.first().map(String::as_str), Some("e2e4")); + assert_eq!(e.second.as_ref().map(|s| s.eval), Some(Eval::Cp(10))); + assert!(e.shallow.is_none(), "the rules do not ask for it"); + assert_eq!(a.seconds_missing(), 0); + + // Rules that ask for it: the earlier analysis wants the shallow search only. + let hard = crate::Hardness { + great: Some(1.0), + gap: 1.0, + ..Default::default() + }; + a.set_hardness(hard); + a.refresh(&game); + assert_eq!(a.seconds_missing(), 1); + assert_eq!(a.report.judgements[0], None, "not known to be hard"); + assert_eq!(job(&mut a, true), 1); + assert_eq!(a.seconds_missing(), 0); + let e = a.eval_at(0).expect("evaluated"); + let s = e.shallow.as_ref().expect("the shallow search"); + assert_eq!( + (s.nodes, s.played.as_str(), s.best.as_str()), + (SHALLOW_NODES, "e2e4", "d2d4") + ); + assert_eq!((s.best_eval, s.played_eval), (Eval::Cp(40), Eval::Cp(10))); + assert_eq!(e.second.as_ref().map(|s| s.eval), Some(Eval::Cp(10))); + // 2.8 % harder than the shallow best: great at 1 %, not at 5 %, brilliant at 2 %. + let d = crate::Measure::Choice.difficulty( + e.eval, + s.best_eval, + s.played_eval, + chess_core::shakmaty::Color::White, + ); + assert!((2.0..5.0).contains(&d), "{d}"); + assert_eq!(a.report.judgements[0], Some(crate::Judgement::Great)); + a.set_hardness(crate::Hardness { + great: Some(5.0), + ..hard + }); + a.refresh(&game); + assert_eq!(a.report.judgements[0], None); + a.set_hardness(crate::Hardness { + brilliant: Some(2.0), + brilliant_gap: 1.0, + ..hard + }); + a.refresh(&game); + assert_eq!(a.report.judgements[0], Some(crate::Judgement::Brilliant)); + // Shallow searches of other nodes are made again. + a.set_shallow_nodes(SHALLOW_NODES / 2); + a.refresh(&game); + assert_eq!(a.seconds_missing(), 1); + assert_eq!(a.report.judgements[0], None); + + // The shallow search finding the move itself: not hard at all. + let mut b = GameAnalysis::new(&game, None); + b.set_hardness(hard); + assert_eq!(job(&mut b, false), 3); + let s = b + .eval_at(0) + .and_then(|e| e.shallow.clone()) + .expect("shallow"); + assert_eq!( + (s.best.as_str(), s.best_eval, s.played_eval), + ("e2e4", Eval::Cp(40), Eval::Cp(40)) + ); + assert_eq!(b.report.judgements[0], None, "0 % is below 1 %"); + } + + #[test] + fn a_failing_engine_fails_the_job() { + let game = chess_core::parse_str("1. e4 e5 *").game; + let mut a = GameAnalysis::new(&game, None); + let targets = a.begin(&game, false); + let result = run( + uci::EngineConfig::new("/nonexistent/engine"), + &settings(2), + targets, + &AtomicBool::new(false), + &mut |_| {}, + ); + assert!(matches!(result, Err(JobFailure::Start(_)))); + } + + #[test] + fn processes_are_bounded() { + assert_eq!(processes(1), 1); + assert!((1..=MAX_PROCESSES).contains(&processes(usize::MAX))); + assert_eq!(processes(0), 1); + assert!(processes(PHONE_PROCESSES) <= PHONE_PROCESSES); + } + + #[test] + fn the_estimate_counts_every_process() { + assert_eq!(estimate_secs(10, 1_000_000.0, 1), 10.0); + assert_eq!(estimate_secs(10, 1_000_000.0, 4), 2.5); + } +} diff --git a/crates/game-review/src/job/engines.rs b/crates/game-review/src/job/engines.rs new file mode 100644 index 0000000..8e5b5ea --- /dev/null +++ b/crates/game-review/src/job/engines.rs @@ -0,0 +1,191 @@ +//! The engine job in engine processes, each driven from a thread of its own. + +use std::collections::HashSet; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::channel; +use std::time::{Duration, Instant}; + +use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits}; + +use super::work::{Answer, Next, Work}; +use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target}; + +/// A node-limited search should never take this long; stop it if it does. +const SEARCH_GUARD: Duration = Duration::from_secs(300); + +enum WorkerMsg { + Event(JobEvent), + Failed(JobFailure), +} + +/// Evaluates `targets` in `settings.processes` engine processes; `on_event` gets every +/// result, on the caller's thread, in the order they come. Returns when all are done, +/// or soon after `cancel` is set (then with `Ok`). When an engine fails, the others +/// stop too and the first failure is returned; what came before it was reported. +pub fn run( + config: uci::EngineConfig, + settings: &JobSettings, + targets: Vec, + cancel: &AtomicBool, + on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + if targets.is_empty() { + return Ok(()); + } + let workers = settings + .processes + .clamp(1, MAX_PROCESSES) + .min(targets.len()); + let next = AtomicUsize::new(0); + let failed = AtomicBool::new(false); + let halted = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed); + let (tx, rx) = channel(); + let mut failure = None; + std::thread::scope(|s| { + for _ in 0..workers { + let tx = tx.clone(); + let (config, targets, next, halted) = (config.clone(), &targets, &next, &halted); + s.spawn(move || { + let mut send = |e| { + let _ = tx.send(WorkerMsg::Event(e)); + }; + if let Err(e) = worker(config, settings, targets, next, halted, &mut send) { + let _ = tx.send(WorkerMsg::Failed(e)); + } + }); + } + drop(tx); + let mut names = HashSet::new(); + for msg in rx { + match msg { + WorkerMsg::Event(JobEvent::Engine(name)) => { + if names.insert(name.clone()) { + on_event(JobEvent::Engine(name)); + } + } + WorkerMsg::Event(e) => on_event(e), + WorkerMsg::Failed(e) => { + failed.store(true, Ordering::Relaxed); + failure.get_or_insert(e); + } + } + } + }); + match failure { + Some(e) if !cancel.load(Ordering::Relaxed) => Err(e), + _ => Ok(()), + } +} + +/// One engine process: takes the next target until there is none or `halted`. +fn worker( + config: uci::EngineConfig, + settings: &JobSettings, + targets: &[Target], + next: &AtomicUsize, + halted: &dyn Fn() -> bool, + on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + let handle = uci::Engine::spawn_with(config, Box::new(|| {})) + .map_err(|e| JobFailure::Start(e.to_string()))?; + if let Some(name) = &handle.info().name { + on_event(JobEvent::Engine(name.clone())); + } + if let Some(file) = &settings.eval_file { + handle + .set_option("EvalFile", Some(file)) + .map_err(|e| JobFailure::Start(e.to_string()))?; + } + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = handle.set_threads(1); + let _ = handle.set_hash_mb(SEARCH_HASH_MB); + let _ = handle.set_multipv(1); + let mut next_id = 0; + // Every search starts from a clear hash, so that it depends on its position alone. + let mut search = |pos: &EnginePosition, among: Vec, nodes: u64| { + next_id += 1; + let _ = handle.new_game(); + search_once( + &handle, + pos, + SearchId(next_id), + among, + nodes, + SEARCH_GUARD, + halted, + ) + }; + 'targets: while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) { + if halted() { + break; + } + let mut work = Work::new(t.clone(), settings.nodes); + loop { + match work.next() { + Next::Search { pos, among, nodes } => { + let answer = search(&pos, among, nodes)?; + if answer.is_none() && halted() { + break 'targets; + } + work.answer(answer); + } + Next::Done(event) => { + if let Some(e) = event { + on_event(e); + } + break; + } + } + } + } + handle.quit(); + Ok(()) +} + +/// One node-limited search: its last full line and the best move. `None` when it gave +/// no line or the job was halted. After `guard` the search is stopped (an engine that +/// ignores `stop` is killed by the `uci` crate's stop timeout: `Terminated`). +pub(super) fn search_once( + handle: &uci::EngineHandle, + pos: &EnginePosition, + id: SearchId, + among: Vec, + nodes: u64, + guard: Duration, + halted: &dyn Fn() -> bool, +) -> Result { + handle + .search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among) + .map_err(|e| JobFailure::Engine(e.to_string()))?; + let started = Instant::now(); + let mut stopping = false; + let mut last: Option = None; + loop { + if halted() { + return Ok(None); + } + if !stopping && started.elapsed() > guard { + let _ = handle.stop(); + stopping = true; + } + match handle.recv_timeout(Duration::from_millis(100)) { + Some(EngineEvent::Info { search_id, info }) if search_id == id => { + if info.multipv_index() == 1 && info.score.is_some() { + let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); + if exact || last.is_none() { + last = Some(info); + } + } + } + Some(EngineEvent::BestMove { + search_id, best, .. + }) if search_id == id => { + return Ok(last.map(|info| (info, best.map(|b| b.to_string())))); + } + Some(EngineEvent::Terminated(reason)) => { + return Err(JobFailure::Terminated(reason)); + } + _ => {} + } + } +} diff --git a/crates/game-review/src/job/probe.rs b/crates/game-review/src/job/probe.rs new file mode 100644 index 0000000..b0956f2 --- /dev/null +++ b/crates/game-review/src/job/probe.rs @@ -0,0 +1,312 @@ +//! Whether an engine is the Stockfish 19 of the game analysis: its search gives the same +//! evaluations as ChessPenguin's, so a user's own Stockfish 19 can do the analysis and +//! the marks stay the same on every computer. +//! +//! Its name is not enough (a build of another commit, another network or a patched one +//! says the same). A few short searches in the fixed mode of the analysis — one +//! thread, a hash of [`SEARCH_HASH_MB`], `ucinewgame` before each, [`PROBE_NODES`] +//! nodes — are compared with those of ChessPenguin's Stockfish 19 ([`REFERENCE`]): the +//! best move, the score and the nodes of the line taken must all be the same. Stockfish +//! with one thread and a node limit is deterministic, whatever the CPU's instruction +//! set: its own check of the universal build (`scripts/check_universal.sh` of the +//! release) requires the same `bench` node count from every per-CPU build. + +use std::time::{Duration, Instant}; + +use uci::{EnginePosition, Score}; + +use super::engines::search_once; +use super::{JobFailure, SEARCH_HASH_MB}; + +/// Nodes of each probe search (about 0.1 s each). +pub const PROBE_NODES: u64 = 100_000; + +/// The name Stockfish 19 gives itself (`id name`). +pub const STOCKFISH_19: &str = "Stockfish 19"; + +/// What a probe search gives: the best move, the score of the line taken (the side to +/// move's) and its nodes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProbeAnswer { + pub best: String, + pub score: Score, + pub nodes: u64, +} + +/// The positions of the probe: an opening, a middlegame full of tactics, an endgame. +pub const PROBE_POSITIONS: [&str; 3] = [ + "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3", + "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", + "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", +]; + +/// ChessPenguin's Stockfish 19 (the official `stockfish-linux-x86-64-universal`, sha256 +/// of its archive in `engine_download`) on [`PROBE_POSITIONS`], taken 2026-10-31. The +/// same from its x86-64-avxvnni slice and from builds of its source for x86-64 (SSE2) +/// and x86-64-bmi2. +pub const REFERENCE: [(&str, Score, u64); 3] = [ + ("a7a6", Score::Cp(-36), 76_994), + ("e2a6", Score::Cp(-196), 49_328), + ("b4f4", Score::Cp(176), 38_955), +]; + +/// What the probe found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Probe { + /// The engine's name (`id name`). + pub name: Option, + /// The answers, one per position of [`PROBE_POSITIONS`] (fewer when one gave none, + /// took too long, or the engine is not called Stockfish 19: then none is searched). + pub answers: Vec, + /// A search took longer than allowed (an engine that ignores `go nodes`). + pub timed_out: bool, +} + +impl Probe { + /// Whether the engine is the Stockfish 19 of the analysis: its name and every answer. + pub fn same(&self) -> bool { + self.name.as_deref() == Some(STOCKFISH_19) + && self.answers.len() == REFERENCE.len() + && self + .answers + .iter() + .zip(REFERENCE) + .all(|(a, (best, score, nodes))| { + a.best == best && a.score == score && a.nodes == nodes + }) + } +} + +/// How long the probe may take: a search (Stockfish needs about 0.1 s) and all of it. +#[derive(Clone, Copy, Debug)] +pub struct ProbeLimits { + pub search: Duration, + pub total: Duration, +} + +impl Default for ProbeLimits { + fn default() -> Self { + ProbeLimits { + search: Duration::from_secs(10), + total: Duration::from_secs(30), + } + } +} + +/// What [`REFERENCE`] is a reference of — the positions, the nodes, the hash, the +/// answers — as a short text kept with the verdicts: a verdict of another probe is +/// not trusted. (FNV-1a of their text: the same in every build.) +pub fn reference_key() -> String { + let text = format!("{PROBE_POSITIONS:?}|{PROBE_NODES}|{SEARCH_HASH_MB}|{REFERENCE:?}"); + let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3) + }); + format!("{hash:016x}") +} + +/// Runs the probe in a process of the engine; `halted` gives it up (the program +/// quits). An engine not called Stockfish 19 is not searched at all. The engine is +/// quit at the end (killed if it does not go). +pub fn probe( + config: uci::EngineConfig, + limits: ProbeLimits, + halted: &dyn Fn() -> bool, +) -> Result { + let started = Instant::now(); + let handle = uci::Engine::spawn_with(config, Box::new(|| {})) + .map_err(|e| JobFailure::Start(e.to_string()))?; + let mut probe = Probe { + name: handle.info().name.clone(), + answers: Vec::new(), + timed_out: false, + }; + if probe.name.as_deref() != Some(STOCKFISH_19) { + handle.quit(); + return Ok(probe); + } + let _ = handle.set_threads(1); + let _ = handle.set_hash_mb(SEARCH_HASH_MB); + let _ = handle.set_multipv(1); + let over = || halted() || started.elapsed() > limits.total; + for (i, fen) in PROBE_POSITIONS.iter().enumerate() { + let _ = handle.new_game(); + let pos = EnginePosition::fen(*fen, Vec::::new()); + let id = uci::SearchId(i as u64 + 1); + let search_started = Instant::now(); + let answer = search_once( + &handle, + &pos, + id, + Vec::new(), + PROBE_NODES, + limits.search, + &over, + )?; + if search_started.elapsed() > limits.search || started.elapsed() > limits.total { + probe.timed_out = true; + break; + } + let Some((info, best)) = answer else { break }; + let (Some(best), Some(score), Some(nodes)) = ( + best.or_else(|| info.pv.first().cloned()), + info.score, + info.nodes, + ) else { + break; + }; + probe.answers.push(ProbeAnswer { + best, + score: score.score, + nodes, + }); + } + handle.quit(); + Ok(probe) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(config: uci::EngineConfig) -> Result { + probe(config, ProbeLimits::default(), &|| false) + } + + fn fake() -> &'static str { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + fake + } + + /// A fake engine answering every probe position as `answers` say. + fn engine(name: &str, answers: &[(&str, Score, u64)]) -> uci::EngineConfig { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec!["--name".into(), name.into()]; + for (fen, (best, score, nodes)) in PROBE_POSITIONS.iter().zip(answers) { + let score = match score { + Score::Cp(cp) => format!("cp {cp}"), + Score::Mate(n) => format!("mate {n}"), + }; + let marker = fen.split(' ').next().unwrap_or_default(); + config.args.extend([ + "--answer".into(), + marker.into(), + format!("{score} nodes {nodes} pv {best}").into(), + ]); + } + config + } + + #[test] + fn the_reference_answers_pass() { + let p = run(engine(STOCKFISH_19, &REFERENCE)).expect("the probe runs"); + assert_eq!(p.name.as_deref(), Some(STOCKFISH_19)); + assert_eq!(p.answers.len(), 3); + assert!(p.same(), "{p:?}"); + } + + #[test] + fn other_answers_or_names_do_not() { + // Another network or version: one score differs. + let mut other = REFERENCE; + other[1].1 = Score::Cp(-117); + let p = run(engine(STOCKFISH_19, &other)).expect("the probe runs"); + assert!(!p.same()); + // The nodes differ (another search), the move and score the same. + let mut other = REFERENCE; + other[2].2 += 1; + assert!(!run(engine(STOCKFISH_19, &other)).unwrap().same()); + // Another best move. + let mut other = REFERENCE; + other[0].0 = "g8f6"; + assert!(!run(engine(STOCKFISH_19, &other)).unwrap().same()); + // The same answers under another name. + let p = run(engine("Stockfish 18", &REFERENCE)).unwrap(); + assert_eq!(p.name.as_deref(), Some("Stockfish 18")); + assert!(!p.same()); + // An engine that answers nothing of the kind (the fake's own lines). + let mut plain = uci::EngineConfig::new(fake()); + plain.args = vec!["--name".into(), STOCKFISH_19.into()]; + assert!(!run(plain).unwrap().same()); + } + + /// A real Stockfish 19 gives [`REFERENCE`] (run when the reference is taken again + /// or another build is checked): + /// `CP_PROBE_ENGINE=/path/to/stockfish cargo test -p game-review probe -- --ignored`. + #[test] + #[ignore = "needs a Stockfish 19 in CP_PROBE_ENGINE"] + fn a_real_stockfish_19_gives_the_reference() { + let path = std::env::var("CP_PROBE_ENGINE").expect("CP_PROBE_ENGINE"); + let p = run(uci::EngineConfig::new(path)).expect("the probe runs"); + println!("{p:?}"); + assert!(p.same(), "{p:?}"); + } + + /// An engine not called Stockfish 19 is not searched (Rodent searches on past + /// `go nodes`): its name is the verdict, at once. + #[test] + fn another_engine_is_not_searched() { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec![ + "--name".into(), + "Rodent V 1.2".into(), + "--ignore-nodes".into(), + ]; + let started = Instant::now(); + let p = run(config).expect("the probe runs"); + assert_eq!(p.name.as_deref(), Some("Rodent V 1.2")); + assert!(p.answers.is_empty() && !p.timed_out && !p.same()); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + /// A «Stockfish 19» that ignores `go nodes`: stopped by the guard, not the same. + #[test] + fn an_endless_search_is_cut_short() { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec![ + "--name".into(), + STOCKFISH_19.into(), + "--ignore-nodes".into(), + ]; + let limits = ProbeLimits { + search: Duration::from_millis(300), + total: Duration::from_secs(2), + }; + let started = Instant::now(); + let p = probe(config, limits, &|| false).expect("the probe runs"); + assert!(p.timed_out && !p.same(), "{p:?}"); + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + // Halted from outside (the program quits): at once. + let mut config = uci::EngineConfig::new(fake()); + config.args = vec![ + "--name".into(), + STOCKFISH_19.into(), + "--ignore-nodes".into(), + ]; + let started = Instant::now(); + let p = probe(config, ProbeLimits::default(), &|| true).expect("the probe runs"); + assert!(!p.same()); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + #[test] + fn the_reference_key_is_stable() { + assert_eq!(reference_key(), reference_key()); + assert_eq!(reference_key().len(), 16); + } + + #[test] + fn an_engine_that_does_not_start_fails() { + assert!(matches!( + run(uci::EngineConfig::new("/nonexistent/engine")), + Err(JobFailure::Start(_)) + )); + } +} diff --git a/crates/game-review/src/job/work.rs b/crates/game-review/src/job/work.rs new file mode 100644 index 0000000..bb1fb1a --- /dev/null +++ b/crates/game-review/src/job/work.rs @@ -0,0 +1,223 @@ +//! What the job does for one target, as a machine without I/O: it names the next +//! search (the full one, the second best without the move played, the shallow ones) +//! and takes its answer; at the end it gives the target's [`JobEvent::Eval`]. Engine +//! processes on a computer and Web Workers in a browser drive the same machine, so the +//! evaluations — and the marks — are the same everywhere. + +use uci::{EnginePosition, SearchInfo, Side}; + +use super::{JobEvent, Target}; +use crate::{Eval, PosEval, Second, Shallow}; + +/// A search's answer: its last full line and the best move; `None` when it gave none. +pub(crate) type Answer = Option<(SearchInfo, Option)>; + +/// What the machine wants now. +pub(crate) enum Next { + /// A node-limited search of `pos` (among these moves only; empty: all), from a + /// clear hash. + Search { + pos: EnginePosition, + among: Vec, + nodes: u64, + }, + /// The target is done: its evaluation (`None`: the engine gave nothing to use). + Done(Option), +} + +enum Stage { + Full, + Second, + ShallowBest, + ShallowPlayed { best: String, best_eval: Eval }, + Finish, +} + +pub(crate) struct Work { + t: Target, + nodes: u64, + stage: Stage, + eval: Option, + nps: u64, + /// The move played, when it is the engine's best and worth a second search. + played: Option, +} + +impl Work { + pub(crate) fn new(t: Target, nodes: u64) -> Self { + let mut w = Work { + t, + nodes, + stage: Stage::Full, + eval: None, + nps: 0, + played: None, + }; + if let Some(e) = w.t.known.clone() { + w.got_eval(e, 0); + } + w + } + + fn eval_of(&self, info: &SearchInfo) -> Option { + info.score + .map(|s| Eval::from_white_eval(s.to_white(self.t.turn).eval)) + } + + /// The full evaluation is there: the second search, if it is worth one. + fn got_eval(&mut self, eval: PosEval, nps: u64) { + let t = &self.t; + // The move played is the engine's best: what the best of the others gives says + // whether it was the only good move, or a sacrifice when nothing else won. + let mover = match t.turn { + Side::White => chess_core::shakmaty::Color::White, + Side::Black => chess_core::shakmaty::Color::Black, + }; + self.played = t + .played + .as_ref() + .filter(|p| { + eval.pv.first() == Some(*p) + && !t.others.is_empty() + && crate::report::worth_second(eval.eval, mover) + }) + .cloned(); + let second_known = eval.second.as_ref().map(|s| &s.without) == self.played.as_ref(); + self.eval = Some(eval); + self.nps = nps; + self.stage = if self.played.is_some() && !second_known { + Stage::Second + } else { + Stage::ShallowBest + }; + if matches!(self.stage, Stage::ShallowBest) { + self.after_second(); + } + } + + /// The shallow search, when the rules want one and it is not there yet. + fn after_second(&mut self) { + let wanted = match (&self.played, self.t.shallow, &self.eval) { + (Some(played), Some(nodes), Some(eval)) => !eval + .shallow + .as_ref() + .is_some_and(|s| &s.played == played && s.nodes == nodes), + _ => false, + }; + self.stage = if wanted { + Stage::ShallowBest + } else { + Stage::Finish + }; + } + + pub(crate) fn next(&self) -> Next { + let t = &self.t; + match &self.stage { + Stage::Full => Next::Search { + pos: t.pos.clone(), + among: Vec::new(), + nodes: self.nodes, + }, + Stage::Second => Next::Search { + pos: t.pos.clone(), + among: t.others.clone(), + nodes: self.nodes, + }, + Stage::ShallowBest => Next::Search { + pos: t.pos.clone(), + among: Vec::new(), + nodes: t.shallow.unwrap_or_default(), + }, + Stage::ShallowPlayed { .. } => Next::Search { + pos: t.pos.clone(), + among: self.played.iter().cloned().collect(), + nodes: t.shallow.unwrap_or_default(), + }, + Stage::Finish => Next::Done(self.eval.clone().map(|eval| JobEvent::Eval { + key: t.key.clone(), + eval, + nps: self.nps, + })), + } + } + + /// The answer to the search [`Self::next`] asked for. + pub(crate) fn answer(&mut self, answer: Answer) { + match std::mem::replace(&mut self.stage, Stage::Finish) { + Stage::Full => { + let Some((info, best)) = answer else { return }; + let Some(score) = info.score else { return }; + let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); + if let Some(b) = best + && pv.first() != Some(&b) + { + pv = vec![b]; + } + let eval = PosEval { + eval: Eval::from_white_eval(score.to_white(self.t.turn).eval), + pv, + depth: info.depth.unwrap_or(0), + second: None, + shallow: None, + }; + self.got_eval(eval, info.nps.unwrap_or(0)); + } + Stage::Second => { + let played = self.played.clone(); + // An engine that ignores `searchmoves` answers with the move played: no + // second move then. + if let Some((info, best)) = answer + && best.as_ref() != played.as_ref() + && info.pv.first() != played.as_ref() + && let (Some(score), Some(played), Some(eval)) = + (info.score, played, self.eval.as_mut()) + { + eval.second = Some(Second { + without: played, + eval: Eval::from_white_eval(score.to_white(self.t.turn).eval), + }); + } + self.after_second(); + } + Stage::ShallowBest => { + let Some((info, best)) = answer else { return }; + let (Some(best), Some(best_eval)) = ( + best.or_else(|| info.pv.first().cloned()), + self.eval_of(&info), + ) else { + return; + }; + if self.played.as_ref() == Some(&best) { + self.shallow(best, best_eval, best_eval); + } else { + self.stage = Stage::ShallowPlayed { best, best_eval }; + } + } + Stage::ShallowPlayed { best, best_eval } => { + if let Some((info, b)) = answer + && b.as_deref() + .is_none_or(|b| Some(b) == self.played.as_deref()) + && let Some(played_eval) = self.eval_of(&info) + { + self.shallow(best, best_eval, played_eval); + } + } + Stage::Finish => {} + } + } + + fn shallow(&mut self, best: String, best_eval: Eval, played_eval: Eval) { + if let (Some(eval), Some(played), Some(nodes)) = + (self.eval.as_mut(), self.played.clone(), self.t.shallow) + { + eval.shallow = Some(Shallow { + nodes, + played, + best, + best_eval, + played_eval, + }); + } + } +} diff --git a/crates/game-review/src/job/workers.rs b/crates/game-review/src/job/workers.rs new file mode 100644 index 0000000..cb099f9 --- /dev/null +++ b/crates/game-review/src/job/workers.rs @@ -0,0 +1,220 @@ +//! The engine job in a browser: engines in Web Workers, each taking the next target, +//! driven from the page's frames by their messages — nothing here blocks. The search +//! of every target is the same machine as on a computer ([`super::work`]). + +use std::collections::HashSet; +use std::sync::Arc; +use std::time::Duration; + +use uci::{ + EngineEvent, EngineHandle, ScoreBound, SearchId, SearchInfo, SearchLimits, Starting, + WorkerConfig, +}; +use web_time::Instant; + +use super::work::{Next, Work}; +use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target}; + +/// A node-limited search should never take this long; stop it if it does. +const SEARCH_GUARD: Duration = Duration::from_secs(300); + +/// How long an engine may take to start: a worker compiles the whole engine (≈ 100 MB +/// of WebAssembly), several at once. +const START_TIMEOUT: Duration = Duration::from_secs(120); + +enum Engine { + Starting(Starting), + Ready(EngineHandle), + Done, +} + +struct Running { + id: SearchId, + last: Option, + started: Instant, + stopping: bool, +} + +struct Slot { + engine: Engine, + work: Option, + search: Option, + next_id: u64, +} + +/// The job: started by [`Dispatcher::start`], driven by [`Dispatcher::poll`]. +pub struct Dispatcher { + slots: Vec, + targets: std::vec::IntoIter, + nodes: u64, + names: HashSet, + events: Vec, + failure: Option, + halted: bool, +} + +impl Dispatcher { + /// Starts `settings.processes` engines of the worker script `script`; `wake` is + /// called whenever one of them has something new. + pub fn start( + script: &str, + settings: &JobSettings, + targets: Vec, + wake: Arc, + ) -> Result { + let workers = settings + .processes + .clamp(1, MAX_PROCESSES) + .min(targets.len().max(1)); + let mut slots = Vec::with_capacity(workers); + if !targets.is_empty() { + for _ in 0..workers { + let mut config = WorkerConfig::new(script); + config.timeouts.uciok = START_TIMEOUT; + config.timeouts.readyok = START_TIMEOUT; + let wake = wake.clone(); + let starting = uci::Engine::start_worker(config, Box::new(move || wake())) + .map_err(|e| JobFailure::Start(e.to_string()))?; + slots.push(Slot { + engine: Engine::Starting(starting), + work: None, + search: None, + next_id: 0, + }); + } + } + Ok(Dispatcher { + slots, + targets: targets.into_iter(), + nodes: settings.nodes, + names: HashSet::new(), + events: Vec::new(), + failure: None, + halted: false, + }) + } + + /// Stops the job: the engines are stopped, what came stays. + pub fn cancel(&mut self) { + self.halted = true; + for s in &mut self.slots { + s.engine = Engine::Done; + } + } + + /// What came since the last call, and the end once the job is over (`Ok` also when + /// cancelled). Call it every frame and when woken. + pub fn poll(&mut self) -> (Vec, Option>) { + for i in 0..self.slots.len() { + if let Err(e) = self.step(i) { + self.failure.get_or_insert(e); + self.cancel(); + } + } + let events = std::mem::take(&mut self.events); + let over = self.slots.iter().all(|s| matches!(s.engine, Engine::Done)); + let end = over.then(|| match self.failure.take() { + Some(e) => Err(e), + None => Ok(()), + }); + (events, end) + } + + fn step(&mut self, i: usize) -> Result<(), JobFailure> { + let slot = &mut self.slots[i]; + if let Engine::Starting(s) = &mut slot.engine { + match s.poll() { + None => return Ok(()), + Some(Err(e)) => return Err(JobFailure::Start(e.to_string())), + Some(Ok(h)) => { + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = h.set_threads(1); + let _ = h.set_hash_mb(SEARCH_HASH_MB); + let _ = h.set_multipv(1); + if let Some(name) = &h.info().name + && self.names.insert(name.clone()) + { + self.events.push(JobEvent::Engine(name.clone())); + } + slot.engine = Engine::Ready(h); + } + } + } + let Engine::Ready(h) = &slot.engine else { + return Ok(()); + }; + // The answer of the running search, once it is there. + let mut answer = None; + for ev in h.drain_events() { + let Some(run) = slot.search.as_mut() else { + continue; + }; + match ev { + EngineEvent::Info { search_id, info } if search_id == run.id => { + if info.multipv_index() == 1 && info.score.is_some() { + let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); + if exact || run.last.is_none() { + run.last = Some(info); + } + } + } + EngineEvent::BestMove { + search_id, best, .. + } if search_id == run.id => { + let last = run.last.take(); + answer = Some(last.map(|info| (info, best))); + slot.search = None; + } + EngineEvent::Terminated(reason) => return Err(JobFailure::Terminated(reason)), + _ => {} + } + } + if let Some(run) = slot.search.as_mut() { + if !run.stopping && run.started.elapsed() > SEARCH_GUARD { + let _ = h.stop(); + run.stopping = true; + } + return Ok(()); + } + if let (Some(answer), Some(work)) = (answer, slot.work.as_mut()) { + work.answer(answer); + } + // The next search: of this target, or of the next one. + loop { + if slot.work.is_none() { + match self.targets.next().filter(|_| !self.halted) { + Some(t) => slot.work = Some(Work::new(t, self.nodes)), + None => { + slot.engine = Engine::Done; + return Ok(()); + } + } + } + let Some(work) = slot.work.as_ref() else { + continue; + }; + match work.next() { + Next::Search { pos, among, nodes } => { + slot.next_id += 1; + let id = SearchId(slot.next_id); + // Every search starts from a clear hash, so that it depends on its + // position alone. + let _ = h.new_game(); + h.search_among(pos, id, SearchLimits::Nodes(nodes), among) + .map_err(|e| JobFailure::Engine(e.to_string()))?; + slot.search = Some(Running { + id, + last: None, + started: Instant::now(), + stopping: false, + }); + return Ok(()); + } + Next::Done(event) => { + self.events.extend(event); + slot.work = None; + } + } + } + } +} diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs new file mode 100644 index 0000000..76a2497 --- /dev/null +++ b/crates/game-review/src/lib.rs @@ -0,0 +1,906 @@ +//! Whole-game analysis, shared by the desktop and the Android app: the engine evaluates +//! every position of the main line, and the evaluations give the move judgements +//! (inaccuracy, mistake, blunder), the accuracy and the evaluation graph. +//! +//! [`GameAnalysis`] holds the evaluations of one game and what follows from them; it +//! never changes the game. [`run`] is the engine job (its own engine process) that +//! produces them. Results are cached per main line, and `[%eval]` comments of the PGN +//! are used without an engine. + +use std::collections::HashMap; +use std::path::Path; + +use chess_core::shakmaty::san::SanPlus; +use chess_core::shakmaty::uci::UciMove; +use chess_core::shakmaty::{CastlingMode, Chess, Color, Move, Position}; +use chess_core::{Annotation, CommentPart, Game, NodeId, parse_comment}; +use serde::{Deserialize, Serialize}; +use uci::{EnginePosition, Side}; + +mod features; +mod job; +pub mod report; + +pub use features::{MoveFeatures, Rules}; +#[cfg(target_family = "wasm")] +pub use job::Dispatcher; +pub use job::{ + JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB, + SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes, +}; +#[cfg(not(target_family = "wasm"))] +pub use job::{probe, run}; +pub use report::{ + Eval, Hardness, Judgement, Measure, Phase, Phases, Ply, Report, SideStats, judge, +}; + +/// Engine result for one position of the main line. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct PosEval { + pub eval: Eval, + /// Principal variation in UCI; the first move is the engine's best move. + #[serde(default)] + pub pv: Vec, + #[serde(default)] + pub depth: u32, + /// The best move but the one played, when that one was the engine's best and could + /// be brilliant or great (older analyses have none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub second: Option, + /// What a shallow search makes of the move played, for how hard it was to find + /// (when the rules ask for it, see [`Hardness`]; older analyses have none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub shallow: Option, +} + +/// The shallow search of a position whose move could be brilliant or great and was the +/// engine's best: the same fixed search as every other, to `nodes` nodes only. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Shallow { + /// Nodes of the search ([`SHALLOW_NODES`] in the programs). + pub nodes: u64, + /// The move played (UCI), as [`Second::without`]. + pub played: String, + /// The shallow search's best move (UCI) and its evaluation. + pub best: String, + pub best_eval: Eval, + /// The move played at the same nodes: `best_eval` when it is `best`, else a search + /// of the move played alone. + pub played_eval: Eval, +} + +/// The best of the other moves: how the position stood without the move played. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Second { + /// The move left out (UCI). + pub without: String, + pub eval: Eval, +} + +/// Where the evaluations came from. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ReviewMeta { + pub engine: String, + /// Nodes per position; 0 = read from `[%eval]` comments of the PGN. + pub nodes: u64, + /// The version of the fixed search the engine made ([`SEARCH_VERSION`]); 0 for an + /// analysis from before it, whose user-chosen engine settings gave other results. + #[serde(default)] + pub search: u32, +} + +impl ReviewMeta { + /// Evaluations of the fixed search of today (see [`run`]); the engine's name comes + /// with the job's [`JobEvent::Engine`]. + pub fn fixed_search() -> ReviewMeta { + ReviewMeta { + engine: String::new(), + nodes: SEARCH_NODES, + search: SEARCH_VERSION, + } + } + + /// Engine evaluations of another search than today's: shown, but never completed + /// with new ones — an update makes them all again. + pub fn is_stale(&self) -> bool { + self.nodes > 0 && self.search != SEARCH_VERSION + } +} + +#[derive(Serialize, Deserialize)] +struct CacheFile { + version: u32, + meta: ReviewMeta, + evals: Vec<(String, PosEval)>, +} + +const CACHE_VERSION: u32 = 1; + +/// An engine assessment of a main-line move: an error, or a move of note (!!, !). +#[derive(Clone, Debug)] +pub struct Mark { + pub judgement: Judgement, + /// Node before the move (where the better line starts). + pub base: NodeId, + pub best: Vec, + /// The better line in SAN (Latin letters, as in PGN). + pub best_san: Vec, + /// "23…Nf6". + pub best_label: Option, +} + +/// The evaluations of a game's main line and the report built from them. +pub struct GameAnalysis { + evals: HashMap, + pub meta: Option, + built_rev: Option, + dirty: bool, + /// Root and main-line nodes: the analysed positions. + line: Vec, + keys: Vec, + /// Side making each move of the line. + movers: Vec, + /// Evaluation per position (engine result or a terminal position). + values: Vec>, + /// Positions without legal moves (mate, stalemate): no engine needed. + terminal: Vec, + /// What each move of the line does on the board (`features[i]`: the move from + /// position `i`); `None` for a null move. + features: Vec>, + /// The move played from each position of the line (UCI; `None` for a null move). + played: Vec>, + pub report: Report, + pub marks: HashMap, + /// The rules of !! and ! the report follows. + rules: Rules, + /// How the difficulty of a move counts in them. + hardness: Hardness, + /// Nodes of the shallow search ([`SHALLOW_NODES`]; another only in an experiment). + shallow_nodes: u64, +} + +/// Where cached analyses are kept, one file per main line by name: a folder (`Path`), +/// or whatever else a program keeps files in (the web version's browser storage). +pub trait CacheStore { + fn read(&self, name: &str) -> Option>; + fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()>; +} + +/// The cache in a folder of the disk. +pub struct CacheDir<'a>(pub &'a Path); + +impl CacheStore for CacheDir<'_> { + fn read(&self, name: &str) -> Option> { + std::fs::read(self.0.join(name)).ok() + } + + fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> { + write_atomic(&self.0.join(name), bytes) + } +} + +impl GameAnalysis { + /// The analysis of `game`: from the cache in `cache_dir` (the folder of the cached + /// analyses) when this main line was analysed before, else from `[%eval]` comments + /// when every move has one, else empty. + pub fn new(game: &Game, cache_dir: Option<&Path>) -> Self { + let dir = cache_dir.map(CacheDir); + Self::with_store(game, dir.as_ref().map(|d| d as &dyn CacheStore)) + } + + /// [`Self::new`] with the cache in `store`. + pub fn with_store(game: &Game, store: Option<&dyn CacheStore>) -> Self { + let mut a = GameAnalysis { + evals: HashMap::new(), + meta: None, + built_rev: None, + dirty: false, + line: Vec::new(), + keys: Vec::new(), + movers: Vec::new(), + values: Vec::new(), + terminal: Vec::new(), + features: Vec::new(), + played: Vec::new(), + report: Report::default(), + marks: HashMap::new(), + rules: Rules::default(), + hardness: Hardness::default(), + shallow_nodes: SHALLOW_NODES, + }; + a.rebuild(game); + if store.is_some_and(|s| a.load_cache(s)) || a.load_pgn_evals(game) { + a.rebuild(game); + } + a + } + + pub fn has_data(&self) -> bool { + !self.evals.is_empty() + } + + /// The evaluations come from another engine search than today's fixed one (an + /// analysis made before it): shown as they are until an update makes them again. + pub fn stale(&self) -> bool { + self.has_data() && self.meta.as_ref().is_some_and(ReviewMeta::is_stale) + } + + /// Root and main-line nodes, in order: index `i` of [`Self::values`] belongs here. + pub fn line(&self) -> &[NodeId] { + &self.line + } + + /// Evaluation per position of [`Self::line`]. + pub fn values(&self) -> &[Option] { + &self.values + } + + /// The side making each move of the line (`movers[i]` plays from position `i`). + pub fn movers(&self) -> &[Color] { + &self.movers + } + + /// The engine result for position `i` of the line, if there is one. + pub fn eval_at(&self, i: usize) -> Option<&PosEval> { + self.keys.get(i).and_then(|k| self.evals.get(k)) + } + + /// Positions of the current main line without an evaluation. + pub fn missing(&self) -> usize { + self.values.iter().filter(|v| v.is_none()).count() + } + + /// Positions an engine would look at in a full analysis (not a final mate or + /// stalemate). + pub fn positions(&self) -> usize { + self.terminal.iter().filter(|t| !**t).count() + } + + /// Engine searches a full analysis is expected to make, for its time: one per + /// position, and a second one for about half of the moves that could be brilliant or + /// great (those the engine finds best too). + pub fn searches(&self) -> usize { + let candidates = self + .features + .iter() + .flatten() + .filter(|f| f.candidate(self.hardness.bans)) + .count(); + self.positions() + candidates / 2 + } + + /// Follows `rules` for !! and ! from the next [`Self::refresh`] on (the evaluations + /// serve both). + pub fn set_rules(&mut self, rules: Rules) { + if self.rules != rules { + self.rules = rules; + self.dirty = true; + } + } + + /// Counts the difficulty of a move as `hardness` says from the next + /// [`Self::refresh`] on; when it asks for it, [`Self::begin`] wants the shallow + /// searches. + pub fn set_hardness(&mut self, hardness: Hardness) { + if self.hardness != hardness { + self.hardness = hardness; + self.dirty = true; + } + } + + /// Shallow searches of `nodes` instead of [`SHALLOW_NODES`]: only for an experiment + /// (choosing the nodes); those of other nodes are made again. + pub fn set_shallow_nodes(&mut self, nodes: u64) { + if self.shallow_nodes != nodes { + self.shallow_nodes = nodes; + self.dirty = true; + } + } + + /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. + pub fn refresh(&mut self, game: &Game) { + if self.dirty || self.built_rev != Some(game.revision()) { + self.rebuild(game); + } + } + + /// Prepares an engine run of the fixed search: `full` drops the earlier results, and + /// so does an analysis of another search ([`Self::stale`]), so that one report never + /// mixes two. Returns the positions without an evaluation, for [`run`]. + pub fn begin(&mut self, game: &Game, full: bool) -> Vec { + // Evaluations read from the PGN are no engine analysis to fill in: the engine + // analyses the whole game (else they would pass for the fixed search). + let from_pgn = self.meta.as_ref().is_some_and(|m| m.nodes == 0); + if full || from_pgn || self.stale() { + self.evals.clear(); + } + let engine = self + .meta + .take() + .filter(|m| !m.is_stale() && m.nodes > 0) + .map(|m| m.engine) + .unwrap_or_default(); + self.meta = Some(ReviewMeta { + engine, + ..ReviewMeta::fixed_search() + }); + self.rebuild(game); + (0..self.line.len()) + .filter_map(|i| { + let known = self.evals.get(&self.keys[i]).cloned(); + // Already evaluated: only the second or shallow search can be left. + if known.is_some() && !self.extra_missing(i) + || known.is_none() && self.values[i].is_some() + { + return None; + } + let here = game.position(self.line[i])?; + // The move played, when it could be brilliant or great. + let played = self + .features + .get(i) + .copied() + .flatten() + .filter(|f| f.candidate(self.hardness.bans)) + .and_then(|_| self.played.get(i).cloned().flatten()); + let others = match &played { + Some(p) => here + .legal_moves() + .iter() + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + .filter(|u| u != p) + .collect(), + None => Vec::new(), + }; + let (key, pos) = position_key(game, self.line[i])?; + let turn = match here.turn() { + Color::White => Side::White, + Color::Black => Side::Black, + }; + Some(Target { + key, + pos, + turn, + played, + others, + known, + shallow: self.hardness.uses_shallow().then_some(self.shallow_nodes), + }) + }) + .collect() + } + + /// Position `i` is evaluated, its move could be brilliant or great and was the + /// engine's best, but the best other move was never searched for (an analysis from + /// before !! and !), or the shallow search the rules ask for was not made. + fn extra_missing(&self, i: usize) -> bool { + let (Some(e), Some(Some(played)), Some(Some(f))) = ( + self.evals.get(&self.keys[i]), + self.played.get(i), + self.features.get(i), + ) else { + return false; + }; + let shallow_missing = || { + self.hardness.uses_shallow() + && !e + .shallow + .as_ref() + .is_some_and(|s| &s.played == played && s.nodes == self.shallow_nodes) + }; + f.candidate(self.hardness.bans) + && e.pv.first() == Some(played) + && report::worth_second(e.eval, self.movers[i]) + && (e.second.as_ref().map(|s| &s.without) != Some(played) || shallow_missing()) + } + + /// Positions whose evaluation is there but which still want the second (or shallow) + /// search of !! and ! ("Update" fills them in without evaluating anything again). + /// None for evaluations from the PGN, which have no engine lines. + pub fn seconds_missing(&self) -> usize { + if self + .meta + .as_ref() + .is_none_or(|m| m.nodes == 0 || m.is_stale()) + { + return 0; + } + (0..self.played.len()) + .filter(|i| self.extra_missing(*i)) + .count() + } + + /// Takes in what the engine job reported. + pub fn apply(&mut self, event: JobEvent) { + match event { + JobEvent::Engine(name) => { + if let Some(m) = &mut self.meta { + m.engine = name; + } + } + JobEvent::Eval { key, eval, .. } => { + self.evals.insert(key, eval); + self.dirty = true; + } + } + } + + fn rebuild(&mut self, game: &Game) { + self.line = std::iter::once(NodeId::ROOT) + .chain(game.mainline()) + .collect(); + let positions: Vec = self + .line + .iter() + .filter_map(|id| game.position(*id).cloned()) + .collect(); + self.keys = self + .line + .iter() + .map(|id| position_key(game, *id).map(|k| k.0).unwrap_or_default()) + .collect(); + self.terminal = (0..self.line.len()) + .map(|i| positions.get(i).and_then(terminal_eval).is_some()) + .collect(); + self.values = (0..self.line.len()) + .map(|i| { + self.evals + .get(&self.keys[i]) + .map(|e| e.eval) + .or_else(|| positions.get(i).and_then(terminal_eval)) + }) + .collect(); + let moves: Vec> = (1..self.line.len()) + .map(|i| match game.game_move(self.line[i]).map(|m| m.kind) { + Some(chess_core::MoveKind::Normal(m)) => Some(m), + _ => None, + }) + .collect(); + self.features = (0..moves.len()) + .map(|i| { + let (m, before) = (moves[i].as_ref()?, positions.get(i)?); + let prev = i.checked_sub(1).and_then(|p| moves[p].as_ref()); + let own = i.checked_sub(2).and_then(|p| moves[p].as_ref()); + Some(MoveFeatures::of(before, m, prev, own)) + }) + .collect(); + self.played = (1..self.line.len()) + .map(|i| game.game_move(self.line[i]).and_then(|m| m.uci())) + .collect(); + let mut plies = Vec::with_capacity(self.line.len().saturating_sub(1)); + for i in 1..self.line.len() { + let mv = game.game_move(self.line[i]); + let e = self.evals.get(&self.keys[i - 1]); + let best = e.and_then(|e| e.pv.first()); + let played = mv.and_then(|m| m.uci()); + plies.push(Ply { + mover: positions.get(i - 1).map_or(Color::White, |p| p.turn()), + null: mv.is_none_or(|m| m.is_null()), + best: best.is_some() && played.as_ref() == best, + features: self.features[i - 1], + // Only for the move played now (the line may have changed since). + second: e + .and_then(|e| e.second.as_ref()) + .filter(|s| Some(&s.without) == played.as_ref()) + .map(|s| s.eval), + difficulty: e + .and_then(|e| Some((e.eval, e.shallow.as_ref()?))) + .filter(|(_, s)| { + Some(&s.played) == played.as_ref() && s.nodes == self.shallow_nodes + }) + .zip(positions.get(i - 1)) + .map(|((deep, s), p)| { + self.hardness + .measure + .difficulty(deep, s.best_eval, s.played_eval, p.turn()) + }), + }); + } + self.movers = plies.iter().map(|p| p.mover).collect(); + self.report = Report::build_tuned( + &self.values, + &plies, + Phases::divide(&positions), + self.rules, + self.hardness, + ); + self.marks.clear(); + for (i, j) in self.report.judgements.iter().enumerate() { + let Some(judgement) = *j else { continue }; + let (base, node) = (self.line[i], self.line[i + 1]); + // A better line only for an error: a good move was the best one. + let (best, best_san) = match (self.evals.get(&self.keys[i]), positions.get(i)) { + (Some(e), Some(root)) if judgement.is_error() => parse_pv(root, &e.pv), + _ => (Vec::new(), Vec::new()), + }; + let best_label = best_san.first().and_then(|san| { + let (num, color) = game.move_number(node)?; + Some(match color { + Color::White => format!("{num}.{san}"), + Color::Black => format!("{num}…{san}"), + }) + }); + self.marks.insert( + node, + Mark { + judgement, + base, + best, + best_san, + best_label, + }, + ); + } + self.built_rev = Some(game.revision()); + self.dirty = false; + } + + /// After an inaccuracy, mistake or blunder: how the opponent punishes it and how + /// the player best answers, the first two moves of the engine line from the position + /// after the move (shown as arrows, as on Lichess). + pub fn refutation(&self, node: NodeId, game: &Game) -> Vec { + if !self + .marks + .get(&node) + .is_some_and(|m| m.judgement.is_error()) + { + return Vec::new(); + } + let (Some(i), Some(pos)) = ( + self.line.iter().position(|n| *n == node), + game.position(node), + ) else { + return Vec::new(); + }; + let Some(e) = self.eval_at(i) else { + return Vec::new(); + }; + let (mut moves, _) = parse_pv(pos, &e.pv); + moves.truncate(2); + moves + } + + /// Index in the main line of `cursor`, or of the main-line move a variation leaves from. + pub fn line_index(&self, cursor: NodeId, game: &Game) -> Option { + let mut id = cursor; + loop { + if let Some(i) = self.line.iter().position(|n| *n == id) { + return Some(i); + } + id = game.parent(id)?; + } + } + + /// The main-line moves of `color` judged `j`, in order. + pub fn errors(&self, color: Color, j: Judgement) -> Vec { + self.report + .judgements + .iter() + .enumerate() + .filter(|(i, x)| **x == Some(j) && self.movers.get(*i) == Some(&color)) + .map(|(i, _)| self.line[i + 1]) + .collect() + } + + // ----- cache ----------------------------------------------------------------- + + /// The name of the cache file of this main line. + /// The name of this main line's file in the cache: equal for equal main lines (the + /// same positions), whatever the rest of the game. + pub fn cache_key(&self) -> String { + self.cache_name() + } + + fn cache_name(&self) -> String { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for k in &self.keys { + for b in k.bytes().chain(std::iter::once(b'\n')) { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + } + format!("{h:016x}.json") + } + + /// Keeps engine results in `dir` (nothing for evaluations read from the PGN). + pub fn save_cache(&self, dir: &Path) -> std::io::Result<()> { + self.save_to(&CacheDir(dir)) + } + + /// Keeps engine results in `store` (nothing for evaluations read from the PGN). + pub fn save_to(&self, store: &dyn CacheStore) -> std::io::Result<()> { + let Some(meta) = self.meta.clone().filter(|m| m.nodes > 0) else { + return Ok(()); + }; + // A game without moves has nothing to report, and every such game would share + // this one file. + if self.evals.is_empty() || self.line.len() < 2 { + return Ok(()); + } + let file = CacheFile { + version: CACHE_VERSION, + meta, + evals: self + .evals + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect(), + }; + let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?; + store.write(&self.cache_name(), &bytes) + } + + fn load_cache(&mut self, store: &dyn CacheStore) -> bool { + let Some(bytes) = store.read(&self.cache_name()) else { + return false; + }; + let Ok(file) = serde_json::from_slice::(&bytes) else { + return false; + }; + if file.version != CACHE_VERSION || file.evals.is_empty() { + return false; + } + self.meta = Some(file.meta); + self.evals = file.evals.into_iter().collect(); + true + } + + /// Uses `[%eval]` comments (Lichess exports, or our own written analysis) when every + /// main-line move has one. + fn load_pgn_evals(&mut self, game: &Game) -> bool { + let mut found = Vec::new(); + for (i, id) in self.line.iter().enumerate().skip(1) { + let Some(node) = game.node(*id) else { + return false; + }; + let e = node + .comments_after() + .iter() + .flat_map(|c| parse_comment(c)) + .find_map(|p| match p { + CommentPart::Annotation(Annotation::Other { name, payload }) + if name == "eval" => + { + Eval::parse_pgn(&payload) + } + _ => None, + }); + match e { + Some(e) => found.push((i, e)), + None if self.values[i].is_some() => {} + None => return false, + } + } + let Some(&(_, first)) = found.first() else { + return false; + }; + // The start position carries no comment: Lichess assumes +0.15 for the initial one. + let root = if game.start().is_standard() { + Eval::Cp(15) + } else { + first + }; + found.insert(0, (0, root)); + for (i, eval) in found { + self.evals.insert( + self.keys[i].clone(), + PosEval { + eval, + pv: Vec::new(), + depth: 0, + second: None, + shallow: None, + }, + ); + } + self.meta = Some(ReviewMeta { + engine: "PGN".into(), + nodes: 0, + search: 0, + }); + true + } +} + +/// Cache key and UCI position of a node (full history, see [`Game::engine_history`]). +fn position_key(game: &Game, id: NodeId) -> Option<(String, EnginePosition)> { + let h = game.engine_history(id)?; + let key = format!( + "{}|{}", + h.start_fen.as_deref().unwrap_or("startpos"), + h.moves.join(" ") + ); + let pos = match h.start_fen { + None => EnginePosition::startpos(h.moves), + Some(fen) => EnginePosition::fen(fen, h.moves), + }; + Some((key, pos)) +} + +/// Evaluation of a position without legal moves (checkmate or stalemate): no engine +/// is needed for it. +pub fn terminal_eval(pos: &Chess) -> Option { + if pos.is_checkmate() { + Some(Eval::Mate { + white: pos.turn() == Color::Black, + moves: 0, + }) + } else if pos.is_stalemate() { + Some(Eval::Cp(0)) + } else { + None + } +} + +/// The legal beginning of an engine line from `root`: its moves and their SAN. +pub fn parse_pv(root: &Chess, pv: &[String]) -> (Vec, Vec) { + let mut pos = root.clone(); + let (mut moves, mut san) = (Vec::new(), Vec::new()); + for u in pv { + let Some(m) = u + .parse::() + .ok() + .and_then(|um| um.to_move(&pos).ok()) + else { + break; + }; + san.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); + moves.push(m); + } + (moves, san) +} + +/// Writes through a temporary file, so a crash never leaves half a cache file. +fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn game(pgn: &str) -> Game { + chess_core::parse_str(pgn).game + } + + #[test] + fn pgn_evals_give_the_report() { + let g = game( + "1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} 2. Qh5 {[%eval -0.2]} Ke7 {[%eval 6.5]} \ + 3. Qxe5# 1-0", + ); + let a = GameAnalysis::new(&g, None); + assert!(a.has_data()); + assert_eq!(a.missing(), 0); + assert!(a.report.complete); + assert_eq!(a.meta.as_ref().map(|m| m.nodes), Some(0)); + let ke7 = g.mainline()[3]; + assert_eq!( + a.marks.get(&ke7).map(|m| m.judgement), + Some(Judgement::Blunder) + ); + assert_eq!(a.errors(Color::Black, Judgement::Blunder), vec![ke7]); + assert!(a.errors(Color::White, Judgement::Blunder).is_empty()); + // The final mate is evaluated without an engine and not counted for one. + assert_eq!(a.positions(), a.line().len() - 1); + // So is a final stalemate. + let stale = game("[FEN \"7k/8/6K1/8/8/8/8/5Q2 w - - 0 1\"] 1. Qf7 *"); + let s = GameAnalysis::new(&stale, None); + assert_eq!(s.line().len(), 2); + assert_eq!(s.positions(), 1); + assert_eq!(s.values()[1], Some(Eval::Cp(0))); + } + + /// Fake engine results for `targets`: the evaluations fall by 3 pawns a move. + fn fake_results(a: &mut GameAnalysis, targets: Vec) { + for (i, t) in targets.into_iter().enumerate() { + a.apply(JobEvent::Eval { + key: t.key, + eval: PosEval { + eval: Eval::Cp(20 - i as i32 * 300), + pv: vec!["e2e4".into()], + depth: 10, + second: None, + shallow: None, + }, + nps: 0, + }); + } + } + + #[test] + fn engine_results_are_cached_per_main_line() { + let dir = std::env::temp_dir().join(format!("game-review-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let g = game("1. e4 e5 2. Nf3 *"); + let mut a = GameAnalysis::new(&g, Some(&dir)); + assert!(!a.has_data()); + let targets = a.begin(&g, false); + assert_eq!(targets.len(), 4); + a.apply(JobEvent::Engine("Fake".into())); + fake_results(&mut a, targets); + a.refresh(&g); + assert_eq!(a.missing(), 0); + a.save_cache(&dir).expect("saved"); + let b = GameAnalysis::new(&g, Some(&dir)); + let fixed = ReviewMeta { + engine: "Fake".into(), + ..ReviewMeta::fixed_search() + }; + assert_eq!(b.meta, Some(fixed.clone())); + assert!(!b.stale()); + assert_eq!(b.values(), a.values()); + // 1.e4 was the engine's own move: never an error, whatever the evaluations say. + assert!(!b.marks.contains_key(&g.mainline()[0])); + // Another main line has its own file. + assert!(!GameAnalysis::new(&game("1. d4 *"), Some(&dir)).has_data()); + // Nothing left to evaluate; 1.e4, the engine's best, still wants the best other + // move (an analysis from before !! and !): filling in searches only that. + let mut c = GameAnalysis::new(&g, Some(&dir)); + assert_eq!(c.seconds_missing(), 1); + let left = c.begin(&g, false); + assert_eq!(left.len(), 1); + assert!(left[0].known.is_some() && left[0].played.as_deref() == Some("e2e4")); + assert!(!left[0].others.is_empty() && !left[0].others.contains(&"e2e4".to_string())); + assert_eq!(c.meta, Some(fixed)); + // A game without moves is never cached. + let empty = game("*"); + let mut e = GameAnalysis::new(&empty, Some(&dir)); + let t = e.begin(&empty, false); + fake_results(&mut e, t); + e.save_cache(&dir).expect("nothing to save is fine"); + assert!( + !GameAnalysis::new( + &game("[FEN \"8/8/8/8/8/8/8/K1k5 w - - 0 1\"] *"), + Some(&dir) + ) + .has_data() + ); + assert!(!GameAnalysis::new(&empty, Some(&dir)).has_data()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// An analysis cached before the fixed search (its meta without `search`, the nodes + /// the user chose) is shown, but stale: an update makes every evaluation again. + #[test] + fn an_analysis_of_another_search_is_stale() { + let dir = std::env::temp_dir().join(format!("game-review-stale-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let g = game("1. e4 e5 2. Nf3 *"); + let mut a = GameAnalysis::new(&g, None); + let targets = a.begin(&g, false); + fake_results(&mut a, targets); + a.refresh(&g); + let path = dir.join(a.cache_name()); + a.save_cache(&dir).expect("saved"); + // The file as 1.x wrote it: no `search` in the meta, 3M nodes. + let mut json: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).expect("cache")).expect("json"); + let meta = json["meta"].as_object_mut().expect("meta"); + meta.remove("search"); + meta.insert("nodes".into(), 3_000_000.into()); + meta.insert("engine".into(), "Stockfish 17".into()); + std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written"); + + let mut old = GameAnalysis::new(&g, Some(&dir)); + assert!(old.has_data() && old.stale()); + assert_eq!(old.meta.as_ref().map(|m| m.search), Some(0)); + assert_eq!(old.missing(), 0); + assert!(old.report.complete, "the old report is still shown"); + assert_eq!(old.seconds_missing(), 0, "not filled in: made again"); + let targets = old.begin(&g, false); + assert_eq!(targets.len(), 4, "every position again"); + assert!(targets.iter().all(|t| t.known.is_none())); + assert!(!old.has_data() && !old.stale()); + assert_eq!(old.meta, Some(ReviewMeta::fixed_search())); + // Evaluations of the PGN are not an engine search: never stale. + let pgn = game("1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} *"); + assert!(!GameAnalysis::new(&pgn, None).stale()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs new file mode 100644 index 0000000..543aa8b --- /dev/null +++ b/crates/game-review/src/report.rs @@ -0,0 +1,999 @@ +//! Game review metrics: win percentage, move and game accuracy, inaccuracy/mistake/blunder +//! judgements, average centipawn loss and game phases. +//! +//! The method follows Lichess (lila `WinPercent`, `AccuracyPercent`, `Advice`, and the +//! scalachess `Divider`, see ); this is an independent +//! reimplementation of the published formulas. + +use chess_core::shakmaty::{Bitboard, Chess, Color, Position, Rank}; +use serde::{Deserialize, Serialize}; + +use crate::Rules; + +/// Engine evaluation from White's point of view. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Eval { + Cp(i32), + /// Forced mate; `moves == 0` in a checkmate position. + Mate { + white: bool, + moves: u32, + }, +} + +/// Centipawn ceiling: larger advantages (and mates) count as this much. +const CP_CEILING: i32 = 1000; + +impl Eval { + pub fn from_white_eval(e: uci::WhiteEval) -> Eval { + match e { + uci::WhiteEval::Cp(cp) => Eval::Cp(cp), + uci::WhiteEval::Mate { winner, moves } => Eval::Mate { + white: winner == uci::Side::White, + moves, + }, + } + } + + /// Centipawns for `side`, mates folded into the ceiling. + fn cp_for(self, side: Color) -> i32 { + let white = match self { + Eval::Cp(cp) => cp.clamp(-CP_CEILING, CP_CEILING), + Eval::Mate { white: true, .. } => CP_CEILING, + Eval::Mate { white: false, .. } => -CP_CEILING, + }; + if side == Color::White { white } else { -white } + } + + /// `Some(true)` if `side` has a forced mate, `Some(false)` if it is being mated. + fn mate_for(self, side: Color) -> Option { + match self { + Eval::Cp(_) => None, + Eval::Mate { white, .. } => Some(white == (side == Color::White)), + } + } + + /// Chance of winning for `side`, 0..100. + pub fn win_percent(self, side: Color) -> f64 { + 50.0 + 50.0 * winning_chances(self.cp_for(side)) + } + + /// "+0.35", "−1.20", "#3", "#-2", "1-0". + pub fn format(self) -> String { + match self { + Eval::Cp(cp) => format!("{:+.2}", f64::from(cp) / 100.0), + Eval::Mate { white, moves: 0 } => if white { "1-0" } else { "0-1" }.into(), + Eval::Mate { white: true, moves } => format!("#{moves}"), + Eval::Mate { + white: false, + moves, + } => format!("#-{moves}"), + } + } + + /// Value for a PGN `[%eval …]` command (pawns or `#n`). + pub fn pgn(self) -> String { + match self { + Eval::Cp(cp) => format!("{:.2}", f64::from(cp) / 100.0), + Eval::Mate { white, moves } => { + format!("#{}{moves}", if white { "" } else { "-" }) + } + } + } + + /// Parses a PGN `[%eval …]` payload ("0.35", "-1.2", "#3", "#-2"). + pub fn parse_pgn(s: &str) -> Option { + let s = s.split([',', ' ']).next()?.trim(); + if let Some(m) = s.strip_prefix('#') { + let n: i32 = m.parse().ok()?; + return Some(Eval::Mate { + white: !m.starts_with('-'), + moves: n.unsigned_abs(), + }); + } + let pawns: f64 = s.parse().ok()?; + pawns + .is_finite() + .then(|| Eval::Cp((pawns * 100.0).round().clamp(-100_000.0, 100_000.0) as i32)) + } +} + +/// Lichess winning chances, −1..1. +fn winning_chances(cp: i32) -> f64 { + 2.0 / (1.0 + (-0.003_682_08 * f64::from(cp)).exp()) - 1.0 +} + +/// Accuracy of a move given the mover's win percentage before and after it, 0..100. +fn move_accuracy(before: f64, after: f64) -> f64 { + if after >= before { + return 100.0; + } + let raw = 103.166_810_071_164_9 * (-0.043_544_153_867_539_51 * (before - after)).exp() + - 3.166_924_740_191_411; + // +1: uncertainty bonus for imperfect analysis, as on Lichess. + (raw + 1.0).clamp(0.0, 100.0) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub enum Judgement { + Inaccuracy, + Mistake, + Blunder, + /// The only good move, or one that turned the game (!). + Great, + /// A sound sacrifice of a piece (!!). + Brilliant, +} + +impl Judgement { + /// An error (?!, ?, ??), not a move of note. + pub fn is_error(self) -> bool { + matches!( + self, + Judgement::Inaccuracy | Judgement::Mistake | Judgement::Blunder + ) + } +} + +/// The thresholds of !! and ! in the mover's win % (docs/research/brilliant-moves.md §10). +mod good { + /// At most this behind the engine's best move. + pub const NEAR_BEST: f64 = 2.0; + /// !!: the position after the sacrifice is at least this good. + pub const SOUND_AFTER: f64 = 45.0; + /// !! ([`Rules::Strict`]): without the move the game was not won anyway. + pub const WON_ANYWAY: f64 = 90.0; + /// !: every other move loses at least this much. + pub const GAP: f64 = 10.0; + /// [`Rules::ChessCom`]: stricter — the owner wants few ! and right ones (2026-10-28): + /// with 25 the check set's ! are chess.com's 87 % of the time (54 % of theirs found). + pub const GAP_CHESSCOM: f64 = 25.0; + /// !: the position after the move is not lost, and the best other move did not win. + pub const GREAT_AFTER: f64 = 40.0; + pub const GREAT_ALT: f64 = 75.0; + /// [`Rules::ChessCom`]: nor keep a clear edge. chess.com's ! in the check set + /// (`chesscom/`, 2026-10-28) all have the best other move at 59 % or less; above it + /// it gives none (18.Nd4, 23.Rf7+, 25.Rxh7+ of Steinitz — von Bardeleben). + pub const GREAT_ALT_CHESSCOM: f64 = 60.0; + /// [`Rules::Strict`]: lost below, won above; a great move changes which. + pub const LOST: f64 = 33.0; + pub const WON: f64 = 67.0; + /// [`Rules::Strict`]: an opponent's move losing this much (or judged a mistake or a + /// blunder) starts a new combination. + pub const OPPONENT_ERROR: f64 = 10.0; + /// Below this the mover's position is too bad for either mark: no second search. + /// (The lower of the two floors after the move, !'s, less the step from the best.) + pub const SECOND_FROM: f64 = GREAT_AFTER - NEAR_BEST; +} + +/// How hard a move is to find, in the mover's win %, from a shallow search +/// ([`crate::SHALLOW_NODES`]) of the engine's own best move. A move the strong search +/// plays and a weak one underrates is what people call brilliant (Zaidi & Guerzhoy 2024, +/// arXiv 2406.11895); an obvious only move (10.Be2 of an online game, 32.Kd2 of Tal — +/// Larsen) the shallow search finds too. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Measure { + /// How much worse than its own best move the shallow search finds the move played + /// (0 when it finds this move best). + #[default] + Choice, + /// How much worse the shallow search finds the move played than the deep one. + Depth, +} + +impl Measure { + /// The difficulty of a move the deep search finds `deep`, the shallow search + /// `played` and its own best move `best`. + pub fn difficulty(self, deep: Eval, best: Eval, played: Eval, mover: Color) -> f64 { + let top = match self { + Measure::Choice => best, + Measure::Depth => deep, + }; + (top.win_percent(mover) - played.win_percent(mover)).max(0.0) + } +} + +/// The say of a move's difficulty ([`Measure`]) in !! and ! ([`Rules::ChessCom`] only), +/// being tried out (2026-10-29) and off by default: the default is the rules without it, +/// and no shallow search is made for them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hardness { + /// !: only a move at least this hard to find (win %). + pub great: Option, + /// !: every other move loses at least this much (win %). + pub gap: f64, + /// !: never a capture nor an attacked piece stepping quietly away (the rules of + /// 2026-10-28 and 2026-10-29 against obvious !). + pub bans: bool, + /// !!: also the only good move (as for !, with [`Self::brilliant_gap`]) at least this + /// hard to find, sacrifice or not (in the check set at 5 000 nodes: 17…Be6!! of + /// Byrne — Fischer, 33.c3+!! of Kasparov — Topalov). + pub brilliant: Option, + /// !! of a hard move: every other move loses at least this much (win %). + pub brilliant_gap: f64, + /// How the difficulty is measured. + pub measure: Measure, +} + +impl Default for Hardness { + fn default() -> Hardness { + Hardness { + great: None, + gap: good::GAP_CHESSCOM, + bans: true, + // On by the owner's word (2026-10-29): +2 !! of chess.com's in the check set + // (90 % found, 95 % right), no wrong one added; the same over 2 000–5 000 + // nodes and thresholds 20–40 %. + brilliant: Some(30.0), + brilliant_gap: 10.0, + measure: Measure::Choice, + } + } +} + +impl Hardness { + /// The rules ask how hard a move was to find: the shallow search is wanted. + pub fn uses_shallow(&self) -> bool { + self.great.is_some() || self.brilliant.is_some() + } +} + +/// Whether the best other move is worth searching for: the move played was the engine's +/// best (`eval` the position's evaluation), and the position is good enough for !! or !. +pub fn worth_second(eval: Eval, mover: Color) -> bool { + eval.win_percent(mover) >= good::SECOND_FROM +} + +/// Lost, equal, won (0, 1, 2), for [`Rules::Strict`]. +fn outcome(win: f64) -> u8 { + if win < good::LOST { + 0 + } else if win > good::WON { + 2 + } else { + 1 + } +} + +/// Brilliant or great, from the evaluations around the move (before the combination rule +/// of [`Rules::Strict`]). +fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules, hard: Hardness) -> Option { + let f = ply.features?; + let (wb, wa) = (before.win_percent(ply.mover), after.win_percent(ply.mover)); + let loss = wb - wa; + let second = ply.second.map(|e| e.win_percent(ply.mover)); + // Without the move: the best other move, or the best move when another was played. + let without = if ply.best { second } else { Some(wb) }; + // With [`Rules::ChessCom`] a sacrifice that mates sooner than any other move was not + // won anyway: 22.Qf6+!! of the Immortal game mates in 2, 22.Qf7 only in 4 (chess.com + // marks it; win % cannot tell the two apart). + let mates_sooner = rules == Rules::ChessCom + && ply.best + && ply + .second + .is_some_and(|s| mates_sooner(after, s, ply.mover)); + // Won anyway without the move: [`Rules::Strict`] by win %, [`Rules::ChessCom`] only + // with a forced mate there — every sacrifice of the check set whose best other move + // still won (to 93 %) is chess.com's !! (23…Qg3 of Levitsky — Marshall, 22…Rxc3 of + // Rotlewi — Rubinstein). + let without_eval = if ply.best { ply.second } else { Some(before) }; + let won_anyway = match rules { + Rules::Strict => without.is_none_or(|w| w >= good::WON_ANYWAY), + Rules::ChessCom => without_eval.is_none_or(|e| e.mate_for(ply.mover) == Some(true)), + }; + if f.brilliant_shape(rules) + && (ply.best || loss <= good::NEAR_BEST) + && wa >= good::SOUND_AFTER + && (!won_anyway || mates_sooner) + { + return Some(Judgement::Brilliant); + } + if f.pawn_shape(rules) && mates_sooner { + return Some(Judgement::Brilliant); + } + let w2 = second?; + let bans = rules == Rules::Strict || hard.bans; + // [`Rules::ChessCom`]: a capture is the natural move, never great (12…Nxc3, 13…Nxe4 of + // Byrne — Fischer, 22…Nbxd5, 26.Qxd4+ of Kasparov — Topalov are not chess.com's !; the + // few captures it marks — 20.Rxe7+, 18.fxe6 — are given up for fewer wrong ones). + if rules == Rules::ChessCom && bans && f.capture { + return None; + } + // The engine's own best move loses nothing: a drop to the next position is the noise + // of two searches (9.Nf5! of the Immortal game, −0.51 then −0.82 at 3M nodes); the + // first rules still count it. + let only_move = |gap: f64| { + ply.best + && (rules == Rules::ChessCom || loss <= good::NEAR_BEST) + && wb - w2 >= gap + && (rules == Rules::ChessCom || outcome(wa) > outcome(w2)) + && wa >= good::GREAT_AFTER + && w2 + < match rules { + Rules::Strict => good::GREAT_ALT, + Rules::ChessCom => good::GREAT_ALT_CHESSCOM, + } + }; + // Tried and dropped (2026-10-28): a pawn offered as the only good move brilliant too — + // finds 33.c3+!! of Kasparov — Topalov, but also marks 17.d5 of Steinitz — von + // Bardeleben, which chess.com leaves unmarked. + if !f.great_shape(rules, bans) { + return None; + } + if rules == Rules::Strict { + return only_move(good::GAP).then_some(Judgement::Great); + } + // How hard the move was to find: unknown (no shallow search) is not hard. + let at_least = |t: Option| t.is_some_and(|t| ply.difficulty.is_some_and(|d| d >= t)); + if at_least(hard.brilliant) && only_move(hard.brilliant_gap) { + Some(Judgement::Brilliant) + } else if only_move(hard.gap) && (hard.great.is_none() || at_least(hard.great)) { + Some(Judgement::Great) + } else { + None + } +} + +/// `after` (the move played) mates `mover`'s opponent in fewer moves than `other` (the +/// best other move), or `other` does not mate at all. +fn mates_sooner(after: Eval, other: Eval, mover: Color) -> bool { + let mine = |e: Eval| match e { + Eval::Mate { white, moves } if white == (mover == Color::White) => Some(moves), + _ => None, + }; + match (mine(after), mine(other)) { + (Some(a), Some(o)) => a < o, + (Some(_), None) => true, + _ => false, + } +} + +/// Judgement of a move from the evaluations before and after it: an inaccuracy, a +/// mistake or a blunder by the drop of the mover's winning chances (never for the +/// engine's own best move: the caller rules that out). +pub fn judge(before: Eval, after: Eval, mover: Color) -> Option { + use Judgement::*; + let (mb, ma) = (before.mate_for(mover), after.mate_for(mover)); + if ma == Some(false) && mb != Some(false) { + // The move allows a forced mate. + let cp = before.cp_for(mover); + return Some(if cp < -999 { + Inaccuracy + } else if cp < -700 { + Mistake + } else { + Blunder + }); + } + if mb == Some(true) && ma != Some(true) { + // A forced mate was let go. + let cp = after.cp_for(mover); + return Some(if cp > 999 { + Inaccuracy + } else if cp > 700 { + Mistake + } else { + Blunder + }); + } + if mb.is_some() || ma.is_some() { + return None; + } + let delta = winning_chances(before.cp_for(mover)) - winning_chances(after.cp_for(mover)); + if delta >= 0.3 { + Some(Blunder) + } else if delta >= 0.2 { + Some(Mistake) + } else if delta >= 0.1 { + Some(Inaccuracy) + } else { + None + } +} + +/// Game phases as indices of the first position of each phase. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Phases { + pub middlegame: Option, + pub endgame: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Opening, + Middlegame, + Endgame, +} + +impl Phases { + /// Splits a sequence of positions: the middlegame starts once few pieces are left or + /// a back rank is sparse; the endgame once at most six queens, rooks and minor pieces remain. + pub fn divide(positions: &[Chess]) -> Phases { + let majors_minors = |p: &Chess| { + let b = p.board(); + (b.knights() | b.bishops() | b.rooks() | b.queens()).count() + }; + let backrank_sparse = |p: &Chess| { + let b = p.board(); + (b.by_color(Color::White) & Bitboard::from_rank(Rank::First)).count() < 4 + || (b.by_color(Color::Black) & Bitboard::from_rank(Rank::Eighth)).count() < 4 + }; + let middlegame = positions + .iter() + .position(|p| majors_minors(p) <= 10 || backrank_sparse(p)); + let endgame = middlegame.and_then(|m| { + positions[m..] + .iter() + .position(|p| majors_minors(p) <= 6) + .map(|i| i + m) + }); + Phases { + middlegame, + endgame, + } + } + + pub fn of(self, position: usize) -> Phase { + if self.endgame.is_some_and(|e| position >= e) { + Phase::Endgame + } else if self.middlegame.is_some_and(|m| position >= m) { + Phase::Middlegame + } else { + Phase::Opening + } + } +} + +/// A move of the analysed line. +#[derive(Clone, Copy, Debug)] +pub struct Ply { + pub mover: Color, + /// Teaching null move `--`: not graded. + pub null: bool, + /// The move played equals the engine's best move (never judged as an error). + pub best: bool, + /// What the move does on the board (`None`: not known, never !! or !). + pub features: Option, + /// The best other move's evaluation, when the move played was the best. + pub second: Option, + /// How hard the move was to find ([`Hardness::measure`]), when a shallow search was + /// made. + pub difficulty: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SideStats { + pub inaccuracies: u32, + pub mistakes: u32, + pub blunders: u32, + pub great: u32, + pub brilliant: u32, + /// Average centipawn loss. + pub acpl: Option, + pub accuracy: Option, + /// Opening, middlegame, endgame. + pub phase_accuracy: [Option; 3], +} + +#[derive(Clone, Debug, Default)] +pub struct Report { + /// Per ply of the line. + pub judgements: Vec>, + pub white: SideStats, + pub black: SideStats, + pub phases: Phases, + /// All positions are evaluated. + pub complete: bool, +} + +impl Report { + pub fn side(&self, c: Color) -> &SideStats { + match c { + Color::White => &self.white, + Color::Black => &self.black, + } + } + + /// `evals[i]` belongs to the position before ply `i`; `evals.len() == plies.len() + 1`. + pub fn build(evals: &[Option], plies: &[Ply], phases: Phases) -> Report { + Self::build_with(evals, plies, phases, Rules::default()) + } + + /// [`Report::build`] with these rules for !! and !. + pub fn build_with( + evals: &[Option], + plies: &[Ply], + phases: Phases, + rules: Rules, + ) -> Report { + Self::build_tuned(evals, plies, phases, rules, Hardness::default()) + } + + /// [`Report::build_with`] where the difficulty of a move counts as `hard` says. + pub fn build_tuned( + evals: &[Option], + plies: &[Ply], + phases: Phases, + rules: Rules, + hard: Hardness, + ) -> Report { + let n = plies.len().min(evals.len().saturating_sub(1)); + let mut report = Report { + judgements: vec![None; plies.len()], + phases, + complete: evals.iter().take(n + 1).all(Option::is_some), + ..Report::default() + }; + let mut losses: [Vec; 2] = [Vec::new(), Vec::new()]; + // For the combination rule of [`Rules::Strict`]: the moves that passed !! or !, + // and each move's loss. + let mut noted = vec![false; n]; + let mut lost = vec![0.0; n]; + for i in 0..n { + let mut ply = plies[i]; + // Winning back after the opponent took the mover's sacrifice goes on with the + // combination: no trade (18…Bxc4+ of Byrne — Fischer after 17…Be6 18.Bxb6). + if let (Some(f), Some(own)) = ( + ply.features.as_mut(), + i.checked_sub(2).and_then(|k| plies[k].features), + ) && own.sacrifice + { + f.takes_back = false; + } + let (Some(before), Some(after)) = (evals[i], evals[i + 1]) else { + continue; + }; + if ply.null { + continue; + } + lost[i] = before.win_percent(ply.mover) - after.win_percent(ply.mover); + let error = if ply.best { + None + } else { + judge(before, after, ply.mover) + }; + let good = if error.is_none() { + note(before, after, &ply, rules, hard) + } else { + None + }; + noted[i] = good.is_some(); + // [`Rules::ChessCom`] marks every move of a combination on its own (21.Qxd7+!! + // 22.Bf5+! 23.Bd7+! in the Evergreen game); [`Rules::Strict`] the first one, + // unless the opponent erred in between. + let erred = |k: usize| { + lost[k] >= good::OPPONENT_ERROR + || matches!( + report.judgements[k], + Some(Judgement::Mistake | Judgement::Blunder) + ) + }; + let goes_on = rules == Rules::Strict && i >= 2 && noted[i - 2] && !erred(i - 1); + let j = error.or(good.filter(|_| !goes_on)); + report.judgements[i] = j; + let stats = match ply.mover { + Color::White => &mut report.white, + Color::Black => &mut report.black, + }; + match j { + Some(Judgement::Inaccuracy) => stats.inaccuracies += 1, + Some(Judgement::Mistake) => stats.mistakes += 1, + Some(Judgement::Blunder) => stats.blunders += 1, + Some(Judgement::Great) => stats.great += 1, + Some(Judgement::Brilliant) => stats.brilliant += 1, + None => {} + } + let loss = (before.cp_for(ply.mover) - after.cp_for(ply.mover)).max(0); + losses[ply.mover as usize].push(loss); + } + for color in [Color::White, Color::Black] { + let l = &losses[color as usize]; + if !l.is_empty() { + let avg = l.iter().map(|x| i64::from(*x)).sum::() as f64 / l.len() as f64; + let stats = match color { + Color::White => &mut report.white, + Color::Black => &mut report.black, + }; + stats.acpl = Some(avg.round() as u32); + } + } + if report.complete && n > 0 { + let wp: Vec = evals[..=n] + .iter() + .map(|e| e.map_or(50.0, |e| e.win_percent(Color::White))) + .collect(); + report.fill_accuracy(&wp, &plies[..n]); + } + report + } + + /// Lichess game accuracy: mean of the volatility-weighted mean and the harmonic mean + /// of move accuracies. + fn fill_accuracy(&mut self, wp: &[f64], plies: &[Ply]) { + let window = (wp.len() / 10).clamp(2, 8).min(wp.len()); + let mut windows: Vec<&[f64]> = vec![&wp[..window]; window.saturating_sub(2)]; + windows.extend(wp.windows(window)); + let weights: Vec = windows + .iter() + .map(|w| std_dev(w).clamp(0.5, 12.0)) + .collect(); + // (color, phase, accuracy, weight) + let mut moves = Vec::new(); + for (i, ply) in plies.iter().enumerate() { + if ply.null { + continue; + } + let (before, after) = (wp[i], wp[i + 1]); + let (before, after) = match ply.mover { + Color::White => (before, after), + Color::Black => (100.0 - before, 100.0 - after), + }; + let weight = weights.get(i).copied().unwrap_or(0.5); + moves.push(( + ply.mover, + self.phases.of(i), + move_accuracy(before, after), + weight, + )); + } + for color in [Color::White, Color::Black] { + let all: Vec<(f64, f64)> = moves + .iter() + .filter(|m| m.0 == color) + .map(|m| (m.2, m.3)) + .collect(); + let phase = |p: Phase| { + let v: Vec<(f64, f64)> = moves + .iter() + .filter(|m| m.0 == color && m.1 == p) + .map(|m| (m.2, m.3)) + .collect(); + // Too few moves in a phase say nothing about it. + if v.len() >= 3 { mixed_mean(&v) } else { None } + }; + let stats = match color { + Color::White => &mut self.white, + Color::Black => &mut self.black, + }; + stats.accuracy = mixed_mean(&all); + stats.phase_accuracy = [ + phase(Phase::Opening), + phase(Phase::Middlegame), + phase(Phase::Endgame), + ]; + } + } +} + +fn std_dev(xs: &[f64]) -> f64 { + if xs.is_empty() { + return 0.0; + } + let mean = xs.iter().sum::() / xs.len() as f64; + (xs.iter().map(|x| (x - mean).powi(2)).sum::() / xs.len() as f64).sqrt() +} + +/// Average of the weighted mean and the harmonic mean of `(accuracy, weight)`. +fn mixed_mean(v: &[(f64, f64)]) -> Option { + if v.is_empty() { + return None; + } + let wsum: f64 = v.iter().map(|x| x.1).sum(); + let weighted = v.iter().map(|x| x.0 * x.1).sum::() / wsum.max(f64::EPSILON); + let harmonic = v.len() as f64 / v.iter().map(|x| 1.0 / x.0.max(1.0)).sum::(); + Some((weighted + harmonic) / 2.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ply(mover: Color) -> Ply { + Ply { + mover, + null: false, + best: false, + features: None, + second: None, + difficulty: None, + } + } + + fn alternating(n: usize) -> Vec { + (0..n) + .map(|i| { + ply(if i % 2 == 0 { + Color::White + } else { + Color::Black + }) + }) + .collect() + } + + #[test] + fn win_percent_matches_lichess_curve() { + assert!((Eval::Cp(0).win_percent(Color::White) - 50.0).abs() < 1e-9); + let w = Eval::Cp(100).win_percent(Color::White); + assert!((w - 59.1).abs() < 0.1, "{w}"); + assert!((Eval::Cp(100).win_percent(Color::Black) - (100.0 - w)).abs() < 1e-9); + // Mates count as the centipawn ceiling. + let m = Eval::Mate { + white: true, + moves: 3, + }; + assert_eq!( + m.win_percent(Color::White), + Eval::Cp(5000).win_percent(Color::White) + ); + } + + #[test] + fn move_accuracy_bounds() { + assert_eq!(move_accuracy(50.0, 60.0), 100.0); + assert_eq!(move_accuracy(50.0, 50.0), 100.0); + let small = move_accuracy(60.0, 55.0); + let big = move_accuracy(60.0, 20.0); + assert!(small > 75.0 && small < 100.0, "{small}"); + assert!(big < 20.0, "{big}"); + assert_eq!(move_accuracy(100.0, 0.0), 0.0); + } + + #[test] + fn judgements_follow_win_chance_drop() { + let w = Color::White; + assert_eq!(judge(Eval::Cp(0), Eval::Cp(-30), w), None); + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(-60), w), + Some(Judgement::Inaccuracy) + ); + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(-150), w), + Some(Judgement::Mistake) + ); + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(-500), w), + Some(Judgement::Blunder) + ); + // Black's point of view: White's eval going up is Black's loss. + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(500), Color::Black), + Some(Judgement::Blunder) + ); + // Already winning by a lot: losing a pawn changes nothing. + assert_eq!(judge(Eval::Cp(900), Eval::Cp(800), w), None); + let mated = Eval::Mate { + white: false, + moves: 4, + }; + let mating = Eval::Mate { + white: true, + moves: 4, + }; + assert_eq!(judge(Eval::Cp(0), mated, w), Some(Judgement::Blunder)); + assert_eq!( + judge(Eval::Cp(-1200), mated, w), + Some(Judgement::Inaccuracy) + ); + assert_eq!(judge(mating, Eval::Cp(300), w), Some(Judgement::Blunder)); + assert_eq!( + judge(mating, Eval::Cp(1500), w), + Some(Judgement::Inaccuracy) + ); + assert_eq!(judge(mating, mating, w), None); + assert_eq!(judge(mated, mated, w), None); + assert_eq!(judge(Eval::Cp(0), mating, w), None); + } + + #[test] + fn report_counts_and_accuracy() { + // White blunders on ply 2; everything else is quiet. + let cps = [20, 25, 20, -400, -390, -400, -395]; + let evals: Vec> = cps.iter().map(|c| Some(Eval::Cp(*c))).collect(); + let plies = alternating(cps.len() - 1); + let r = Report::build(&evals, &plies, Phases::default()); + assert!(r.complete); + assert_eq!(r.judgements[2], Some(Judgement::Blunder)); + assert_eq!(r.white.blunders, 1); + assert_eq!( + r.black.blunders + r.black.mistakes + r.black.inaccuracies, + 0 + ); + let (wa, ba) = (r.white.accuracy.expect("w"), r.black.accuracy.expect("b")); + assert!(wa < ba, "white {wa} black {ba}"); + assert!(ba > 90.0); + assert!(r.white.acpl.expect("acpl") > r.black.acpl.expect("acpl")); + } + + #[test] + fn partial_and_special_plies() { + let evals = vec![Some(Eval::Cp(0)), Some(Eval::Cp(-500)), None, None]; + let mut plies = alternating(3); + let r = Report::build(&evals, &plies, Phases::default()); + assert!(!r.complete); + assert_eq!(r.white.blunders, 1); + assert_eq!(r.white.accuracy, None); + // The engine's own best move is never an error; null moves are not graded. + plies[0].best = true; + let r = Report::build(&evals, &plies, Phases::default()); + assert_eq!(r.white.blunders, 0); + plies[0].best = false; + plies[0].null = true; + let r = Report::build(&evals, &plies, Phases::default()); + assert_eq!(r.white.blunders, 0); + assert_eq!(r.white.acpl, None); + } + + #[test] + fn pgn_eval_roundtrip() { + for e in [ + Eval::Cp(35), + Eval::Cp(-120), + Eval::Mate { + white: true, + moves: 3, + }, + Eval::Mate { + white: false, + moves: 2, + }, + ] { + assert_eq!(Eval::parse_pgn(&e.pgn()), Some(e)); + } + assert_eq!(Eval::parse_pgn("0.17,22"), Some(Eval::Cp(17))); + assert_eq!(Eval::parse_pgn("abc"), None); + } + + #[test] + fn phases_of_a_real_game() { + // The Opera Game: queens and rooks stay until the very end, so no endgame. + let game = chess_core::parse_str( + "1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 7. Qb3 Qe7 \ + 8. Nc3 c6 9. Bg5 b5 10. Nxb5 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 13. Rxd7 Rxd7 \ + 14. Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+ Nxb8 17. Rd8# 1-0", + ) + .game; + let positions: Vec = std::iter::once(chess_core::NodeId::ROOT) + .chain(game.mainline()) + .filter_map(|n| game.position(n).cloned()) + .collect(); + assert_eq!(positions.len(), 34); + let p = Phases::divide(&positions); + let mid = p.middlegame.expect("middlegame"); + assert!(mid > 4 && mid < 25, "{mid}"); + assert_eq!(p.of(0), Phase::Opening); + assert_eq!(p.of(mid), Phase::Middlegame); + } + + fn noted(mover: Color, sacrifice: bool, second: Option) -> Ply { + Ply { + mover, + null: false, + best: true, + features: Some(crate::MoveFeatures { + legal: 30, + sacrifice, + ..Default::default() + }), + second, + difficulty: None, + } + } + + #[test] + fn a_sound_sacrifice_is_brilliant_unless_the_game_was_won_anyway() { + let w = Color::White; + let evals = [Some(Eval::Cp(100)), Some(Eval::Cp(100))]; + let r = Report::build( + &evals, + &[noted(w, true, Some(Eval::Cp(-100)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], Some(Judgement::Brilliant)); + assert_eq!(r.white.brilliant, 1); + // Another move won as well: still !! by chess.com's marks, no !! by the first + // rules; with a forced mate there: no !! either way. + let r = Report::build( + &evals, + &[noted(w, true, Some(Eval::Cp(800)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], Some(Judgement::Brilliant)); + let r = Report::build_with( + &evals, + &[noted(w, true, Some(Eval::Cp(800)))], + Phases::default(), + Rules::Strict, + ); + assert_eq!(r.judgements[0], None); + let mate = Some(Eval::Mate { + white: true, + moves: 5, + }); + let r = Report::build(&evals, &[noted(w, true, mate)], Phases::default()); + assert_eq!(r.judgements[0], None); + // No best other move known (an older analysis): nothing said. + let r = Report::build(&evals, &[noted(w, true, None)], Phases::default()); + assert_eq!(r.judgements[0], None); + // Unsound: the position after it is bad. + let bad = [Some(Eval::Cp(-200)), Some(Eval::Cp(-200))]; + let r = Report::build( + &bad, + &[noted(w, true, Some(Eval::Cp(-400)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], None); + } + + #[test] + fn the_only_move_that_turns_the_game_is_great() { + let w = Color::White; + let evals = [Some(Eval::Cp(300)), Some(Eval::Cp(300))]; + let r = Report::build( + &evals, + &[noted(w, false, Some(Eval::Cp(-300)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], Some(Judgement::Great)); + assert_eq!(r.white.great, 1); + // Others are worse but still win: not great. + let r = Report::build( + &evals, + &[noted(w, false, Some(Eval::Cp(250)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], None); + // Not the engine's move: never great. + let mut p = noted(w, false, Some(Eval::Cp(-300))); + p.best = false; + assert_eq!( + Report::build(&evals, &[p], Phases::default()).judgements[0], + None + ); + } + + #[test] + fn every_move_of_a_combination_is_marked() { + // As on chess.com: 21.Qxd7+!! 22.Bf5+! 23.Bd7+! in the Evergreen game. + let (w, b) = (Color::White, Color::Black); + let great = || noted(w, false, Some(Eval::Cp(-300))); + let evals = [Some(Eval::Cp(300)); 4]; + let r = Report::build(&evals, &[great(), ply(b), great()], Phases::default()); + assert_eq!( + r.judgements, + vec![Some(Judgement::Great), None, Some(Judgement::Great)] + ); + // Only the best move of a position where the others fall clearly behind. + let mut close = great(); + close.second = Some(Eval::Cp(250)); + let r = Report::build(&evals, &[close], Phases::default()); + assert_eq!(r.judgements[0], None); + } + + #[test] + fn the_strict_rules_want_a_turn_of_the_game_and_one_mark_a_combination() { + let (w, b) = (Color::White, Color::Black); + // The only good move of an equal position: great by chess.com, not by the first rules. + let equal = [Some(Eval::Cp(0)), Some(Eval::Cp(0))]; + let only = || noted(w, false, Some(Eval::Cp(-400))); + let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::ChessCom); + assert_eq!(r.judgements[0], Some(Judgement::Great)); + // Others still equal-ish (−1.5): no turn of the game for the first rules, and + // short of the stricter gap of chess.com's rules. + let only = || noted(w, false, Some(Eval::Cp(-150))); + let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::ChessCom); + assert_eq!(r.judgements[0], None); + let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::Strict); + assert_eq!(r.judgements[0], None); + // A combination: marked once by the first rules. + let great = || noted(w, false, Some(Eval::Cp(-300))); + let evals = [Some(Eval::Cp(300)); 4]; + let r = Report::build_with( + &evals, + &[great(), ply(b), great()], + Phases::default(), + Rules::Strict, + ); + assert_eq!(r.judgements, vec![Some(Judgement::Great), None, None]); + } +} diff --git a/crates/maia/Cargo.toml b/crates/maia/Cargo.toml new file mode 100644 index 0000000..449af32 --- /dev/null +++ b/crates/maia/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "maia" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "A human-like chess move predictor (the Maia-3 network), computed in plain Rust" + +[dependencies] +shakmaty.workspace = true +thiserror.workspace = true + +[dev-dependencies] +serde_json.workspace = true diff --git a/crates/maia/src/checkpoint.rs b/crates/maia/src/checkpoint.rs new file mode 100644 index 0000000..def50f6 --- /dev/null +++ b/crates/maia/src/checkpoint.rs @@ -0,0 +1,354 @@ +//! Reads the published PyTorch checkpoint (`maia3-5m.pt`) directly: a zip archive with +//! stored (uncompressed) members — a pickle describing the tensors (`data.pkl`) and +//! their raw little-endian f32 storages (`data/`). Only what such a checkpoint +//! uses is understood; anything else is refused, nothing is executed. + +use std::collections::HashMap; + +use crate::weights::{Tensor, WeightsError}; + +/// The members of a zip archive stored without compression: name → bytes. +fn zip_members(b: &[u8]) -> Result, WeightsError> { + let u16_at = |i: usize| -> Result { + Ok(u16::from_le_bytes( + b.get(i..i + 2) + .ok_or(WeightsError::Format)? + .try_into() + .unwrap(), + ) as usize) + }; + let u32_at = |i: usize| -> Result { + Ok(u32::from_le_bytes( + b.get(i..i + 4) + .ok_or(WeightsError::Format)? + .try_into() + .unwrap(), + ) as usize) + }; + // The end of central directory record, searched from the end (a comment may follow). + let eocd = (0..b.len().saturating_sub(21)) + .rev() + .take(65_557) + .find(|&i| b[i..].starts_with(b"PK\x05\x06")) + .ok_or(WeightsError::Format)?; + let count = u16_at(eocd + 10)?; + let mut at = u32_at(eocd + 16)?; + let mut out = HashMap::new(); + for _ in 0..count { + if !b.get(at..).is_some_and(|r| r.starts_with(b"PK\x01\x02")) { + return Err(WeightsError::Format); + } + let method = u16_at(at + 10)?; + let size = u32_at(at + 20)?; + let (name_len, extra_len, comment_len) = + (u16_at(at + 28)?, u16_at(at + 30)?, u16_at(at + 32)?); + let local = u32_at(at + 42)?; + let name = std::str::from_utf8( + b.get(at + 46..at + 46 + name_len) + .ok_or(WeightsError::Format)?, + ) + .map_err(|_| WeightsError::Format)? + .to_owned(); + at += 46 + name_len + extra_len + comment_len; + if method != 0 { + return Err(WeightsError::Format); + } + let data = local + 30 + u16_at(local + 26)? + u16_at(local + 28)?; + out.insert(name, b.get(data..data + size).ok_or(WeightsError::Format)?); + } + Ok(out) +} + +/// A value of the pickle machine (only what a checkpoint holds). +#[derive(Clone, Debug)] +enum Value { + Int(i64), + Str(String), + Bool, + Tuple(Vec), + Global(String), + /// A storage: its key in `data/`. + Storage(String), + /// A tensor: storage key, offset, shape, strides. + Tensor(String, usize, Vec, Vec), + Dict(Vec<(Value, Value)>), + Mark, + None, +} + +/// How many values `v` holds (a value too big to be a checkpoint's is refused: clones +/// of the memo could otherwise grow without end). +fn size(v: &Value) -> usize { + match v { + Value::Tuple(items) => 1 + items.iter().map(size).sum::(), + Value::Dict(items) => 1 + items.iter().map(|(k, v)| size(k) + size(v)).sum::(), + _ => 1, + } +} + +const MAX_VALUE: usize = 100_000; + +fn as_usizes(v: &Value) -> Result, WeightsError> { + match v { + Value::Tuple(items) => items + .iter() + .map(|i| match i { + Value::Int(n) if *n >= 0 => Ok(*n as usize), + _ => Err(WeightsError::Format), + }) + .collect(), + _ => Err(WeightsError::Format), + } +} + +/// Runs the pickle `p` (protocol 2, the opcodes `torch.save` writes for a state dict). +fn unpickle(p: &[u8]) -> Result { + let bad = || WeightsError::Format; + let mut stack: Vec = Vec::new(); + let mut memo: HashMap = HashMap::new(); + let mut i = 0; + let byte = |i: usize| p.get(i).copied().ok_or(WeightsError::Format); + let le = |i: usize, n: usize| -> Result { + let s = p.get(i..i + n).ok_or(WeightsError::Format)?; + Ok(s.iter() + .rev() + .fold(0usize, |a, b| (a << 8) | usize::from(*b))) + }; + let pop_mark = |stack: &mut Vec| -> Result, WeightsError> { + let at = stack + .iter() + .rposition(|v| matches!(v, Value::Mark)) + .ok_or(WeightsError::Format)?; + let items = stack.split_off(at + 1); + stack.pop(); + Ok(items) + }; + loop { + let op = byte(i)?; + i += 1; + match op { + 0x80 => i += 1, // PROTO + b'}' => stack.push(Value::Dict(vec![])), // EMPTY_DICT + b')' => stack.push(Value::Tuple(vec![])), // EMPTY_TUPLE + b'(' => stack.push(Value::Mark), // MARK + b'q' => { + // BINPUT + let v = stack.last().ok_or_else(bad)?; + if size(v) > MAX_VALUE { + return Err(bad()); + } + memo.insert(usize::from(byte(i)?), v.clone()); + i += 1; + } + b'r' => { + // LONG_BINPUT + let v = stack.last().ok_or_else(bad)?; + if size(v) > MAX_VALUE { + return Err(bad()); + } + memo.insert(le(i, 4)?, v.clone()); + i += 4; + } + b'h' => { + // BINGET + stack.push(memo.get(&usize::from(byte(i)?)).ok_or_else(bad)?.clone()); + i += 1; + } + b'j' => { + // LONG_BINGET + stack.push(memo.get(&le(i, 4)?).ok_or_else(bad)?.clone()); + i += 4; + } + b'K' => { + stack.push(Value::Int(i64::from(byte(i)?))); + i += 1; + } + b'M' => { + stack.push(Value::Int(le(i, 2)? as i64)); + i += 2; + } + b'J' => { + stack.push(Value::Int(i64::from(le(i, 4)? as u32 as i32))); + i += 4; + } + b'X' => { + // BINUNICODE + let n = le(i, 4)?; + let s = std::str::from_utf8(p.get(i + 4..i + 4 + n).ok_or_else(bad)?) + .map_err(|_| bad())?; + stack.push(Value::Str(s.to_owned())); + i += 4 + n; + } + b'c' => { + // GLOBAL "module\nname\n" + let end1 = p[i..].iter().position(|&c| c == b'\n').ok_or_else(bad)? + i; + let end2 = p[end1 + 1..] + .iter() + .position(|&c| c == b'\n') + .ok_or_else(bad)? + + end1 + + 1; + let module = std::str::from_utf8(&p[i..end1]).map_err(|_| bad())?; + let name = std::str::from_utf8(&p[end1 + 1..end2]).map_err(|_| bad())?; + stack.push(Value::Global(format!("{module}.{name}"))); + i = end2 + 1; + } + 0x88 => stack.push(Value::Bool), // NEWTRUE + 0x89 => stack.push(Value::Bool), // NEWFALSE + b'N' => stack.push(Value::None), + b't' => { + let items = pop_mark(&mut stack)?; + stack.push(Value::Tuple(items)); + } + 0x85..=0x87 => { + // TUPLE1/2/3 + let n = usize::from(op - 0x84); + if stack.len() < n { + return Err(bad()); + } + let items = stack.split_off(stack.len() - n); + stack.push(Value::Tuple(items)); + } + b'Q' => { + // BINPERSID: ('storage', FloatStorage, key, location, numel) + let Value::Tuple(pid) = stack.pop().ok_or_else(bad)? else { + return Err(bad()); + }; + match pid.as_slice() { + [Value::Str(kind), Value::Global(t), Value::Str(key), ..] + if kind == "storage" && t == "torch.FloatStorage" => + { + stack.push(Value::Storage(key.clone())); + } + _ => return Err(bad()), + } + } + b'R' => { + // REDUCE: only the constructors of a state dict. + let Value::Tuple(args) = stack.pop().ok_or_else(bad)? else { + return Err(bad()); + }; + let Value::Global(f) = stack.pop().ok_or_else(bad)? else { + return Err(bad()); + }; + match f.as_str() { + "torch._utils._rebuild_tensor_v2" => match args.as_slice() { + [Value::Storage(key), Value::Int(offset), shape, stride, ..] + if *offset >= 0 => + { + stack.push(Value::Tensor( + key.clone(), + *offset as usize, + as_usizes(shape)?, + as_usizes(stride)?, + )); + } + _ => return Err(bad()), + }, + "torch._utils._rebuild_parameter" => { + stack.push(args.into_iter().next().ok_or_else(bad)?); + } + "collections.OrderedDict" => stack.push(Value::Dict(vec![])), + _ => return Err(bad()), + } + } + b'u' => { + // SETITEMS + let items = pop_mark(&mut stack)?; + let Some(Value::Dict(d)) = stack.last_mut() else { + return Err(bad()); + }; + for kv in items.chunks(2) { + if let [k, v] = kv { + d.push((k.clone(), v.clone())); + } + } + } + b's' => { + // SETITEM + let v = stack.pop().ok_or_else(bad)?; + let k = stack.pop().ok_or_else(bad)?; + let Some(Value::Dict(d)) = stack.last_mut() else { + return Err(bad()); + }; + d.push((k, v)); + } + b'.' => return stack.pop().ok_or_else(bad), + _ => return Err(bad()), + } + } +} + +/// The tensors of a checkpoint: name → shape and f32 data. +pub fn read(bytes: &[u8]) -> Result, WeightsError> { + let members = zip_members(bytes)?; + let (pkl_name, pkl) = members + .iter() + .find(|(n, _)| n.ends_with("/data.pkl")) + .ok_or(WeightsError::Format)?; + let root = pkl_name.trim_end_matches("data.pkl"); + let Value::Dict(mut items) = unpickle(pkl)? else { + return Err(WeightsError::Format); + }; + // A checkpoint may wrap the state dict: {"model_state_dict": {...}, ...}. + if let Some((_, Value::Dict(inner))) = items + .iter() + .find(|(k, _)| matches!(k, Value::Str(s) if s == "model_state_dict")) + { + items = inner.clone(); + } + let mut out = HashMap::new(); + for (k, v) in items { + let (Value::Str(name), Value::Tensor(key, offset, shape, stride)) = (k, v) else { + continue; + }; + let n = shape + .iter() + .try_fold(1usize, |a, &d| a.checked_mul(d)) + .ok_or(WeightsError::Format)?; + // Contiguous, row-major: what a saved state dict holds. + let mut want = vec![1usize; shape.len()]; + for d in (0..shape.len().saturating_sub(1)).rev() { + want[d] = want[d + 1].saturating_mul(shape[d + 1]); + } + if n > 1 && stride != want { + return Err(WeightsError::Format); + } + let raw = members + .get(&format!("{root}data/{key}")) + .ok_or(WeightsError::Format)? + .get( + offset.checked_mul(4).ok_or(WeightsError::Format)? + ..offset + .checked_add(n) + .and_then(|e| e.checked_mul(4)) + .ok_or(WeightsError::Format)?, + ) + .ok_or(WeightsError::Format)?; + let data = raw + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)) + .collect(); + out.insert(name.replace("smolgen", "gab"), Tensor { shape, data }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refuses_what_is_not_a_checkpoint() { + assert!(read(b"").is_err()); + assert!(read(b"PK\x05\x06garbage").is_err()); + assert!(read(&[0u8; 100]).is_err()); + // A pickle that calls anything but the state-dict constructors is refused. + assert!( + unpickle(b"\x80\x02cos\nsystem\nq\x00X\x02\x00\x00\x00lsq\x01\x85q\x02R.").is_err() + ); + assert!(unpickle(b"\x80\x02}q\x00.").is_ok()); + } +} diff --git a/crates/maia/src/lib.rs b/crates/maia/src/lib.rs new file mode 100644 index 0000000..6776d3d --- /dev/null +++ b/crates/maia/src/lib.rs @@ -0,0 +1,90 @@ +//! A human-like move predictor: the Maia-3 network (CSSLab, University of Toronto, +//! "Chessformer", ICLR 2026) computed in plain Rust, without a machine-learning runtime. +//! +//! The network sees the position (and up to seven positions before it) from the side to +//! move and the ratings of both players, and gives the probability of each legal move +//! as a player of that rating would play it, plus the chances of win, draw and loss. +//! +//! The weights are the published checkpoint itself (`maia3-5m.pt`, PyTorch's zip of a +//! pickle and raw f32 storages), read without PyTorch: the network shares one bias +//! tensor between its blocks. + +mod checkpoint; +mod net; +pub mod strength; +mod weights; + +pub use net::Prediction; +pub use weights::WeightsError; + +use shakmaty::{Chess, Move, Position}; + +/// The network, loaded. +pub struct Maia { + net: net::Net, +} + +impl Maia { + /// Reads the checkpoint (`maia3-5m.pt`). + pub fn load(path: &std::path::Path) -> Result { + // The file's bytes are let go once read into tensors, and the tensors move into + // the network: at most two copies of the weights at once (the large model: its + // 316 MB twice, not three times). + let w = { + let bytes = std::fs::read(path).map_err(WeightsError::Io)?; + weights::Weights::parse(&bytes)? + }; + Maia::from_weights(w) + } + + pub fn from_bytes(bytes: &[u8]) -> Result { + Maia::from_weights(weights::Weights::parse(bytes)?) + } + + fn from_weights(mut w: weights::Weights) -> Result { + Ok(Maia { + net: net::Net::new(&mut w)?, + }) + } + + /// The moves a player rated `self_elo` would play in `history.last()` against one + /// rated `oppo_elo`, most likely first. `history`: the positions of the game up to + /// and including the current one (the last eight are used; fewer are padded with + /// the earliest given). Empty when there is no legal move. + pub fn predict(&self, history: &[Chess], self_elo: u32, oppo_elo: u32) -> Prediction { + self.net.predict(history, self_elo, oppo_elo) + } +} + +/// A move to play from a prediction: the most likely one with `temperature` 0, +/// otherwise drawn at random with probabilities sharpened (< 1) or flattened (> 1). +/// `random` is a number in [0, 1). +pub fn pick(prediction: &Prediction, temperature: f32, random: f32) -> Option { + let moves = &prediction.moves; + if moves.is_empty() { + return None; + } + if temperature <= 0.0 { + return Some(moves[0].0); + } + let weights: Vec = moves + .iter() + .map(|(_, p)| p.max(1e-12).powf(1.0 / temperature)) + .collect(); + let total: f32 = weights.iter().sum(); + let mut target = random.clamp(0.0, 0.999_999) * total; + for ((m, _), w) in moves.iter().zip(&weights) { + if target < *w { + return Some(*m); + } + target -= w; + } + moves.last().map(|(m, _)| *m) +} + +/// The position after `m`, for building the history. +pub fn after(pos: &Chess, m: Move) -> Chess { + let mut p = pos.clone(); + p.play_unchecked(m); + p +} diff --git a/crates/maia/src/net.rs b/crates/maia/src/net.rs new file mode 100644 index 0000000..9f4deed --- /dev/null +++ b/crates/maia/src/net.rs @@ -0,0 +1,523 @@ +//! The forward pass of Maia-3: post-norm transformer blocks over the 64 squares, with +//! an attention bias generated from the position (GAB), a source-destination policy +//! head and a win/draw/loss head. Plain loops over f32 slices. The sizes come from the +//! checkpoint, so one code serves the published 5M, 23M and 79M models. + +use shakmaty::uci::UciMove; +use shakmaty::{CastlingMode, Chess, Color, Move, Position, Role, Square}; + +use crate::weights::{Weights, WeightsError}; + +const EMB: usize = 128; // rating embedding +const HISTORY: usize = 8; +const PLANES: usize = 12; +const INPUT: usize = PLANES * HISTORY + 2 * EMB; + +/// The sizes of one model, read from its tensors. +struct Dims { + d: usize, // width of the squares' vectors + heads: usize, + ff: usize, + gab_square: usize, // per-square width before the bias generator; 0: the squares' mean + gab_hid: usize, + gab_gen: usize, + head: usize, + blocks: usize, +} + +impl Dims { + fn read(w: &Weights) -> Result { + let l0 = "transformer.layers.0"; + let gab_gen = w.dim("gab_shared_weight", 1)?; + let heads = w.dim(&format!("{l0}.self_attn.sm3.weight"), 0)? / gab_gen.max(1); + let d = w.dim("token_projection.weight", 0)?; + if heads == 0 || d % heads != 0 { + return Err(WeightsError::Format); + } + let blocks = (0..) + .take_while(|i| { + w.shape(&format!("transformer.layers.{i}.linear1.weight")) + .is_some() + }) + .count(); + Ok(Dims { + d, + heads, + ff: w.dim(&format!("{l0}.linear1.weight"), 0)?, + gab_square: match w.shape(&format!("{l0}.self_attn.sm1.weight")) { + Some(s) => s[0], + None => 0, + }, + gab_hid: w.dim(&format!("{l0}.self_attn.sm2.weight"), 0)?, + gab_gen, + head: w.dim("proj_sq_from.weight", 0)?, + blocks, + }) + } +} + +struct Linear { + w: Vec, // out × in + b: Option>, + inp: usize, + out: usize, +} + +impl Linear { + fn load( + w: &mut Weights, + name: &str, + out: usize, + inp: usize, + bias: bool, + ) -> Result { + Ok(Linear { + w: w.get(&format!("{name}.weight"), &[out, inp])?, + b: if bias { + Some(w.get(&format!("{name}.bias"), &[out])?) + } else { + None + }, + inp, + out, + }) + } + + /// `rows` vectors of `inp` → `rows` vectors of `out`. + fn apply(&self, x: &[f32], rows: usize) -> Vec { + let mut y = vec![0.0; rows * self.out]; + par_rows(&mut y, self.out, rows * self.out * self.inp, |r, yr| { + let xr = &x[r * self.inp..(r + 1) * self.inp]; + for (o, slot) in yr.iter_mut().enumerate() { + let wo = &self.w[o * self.inp..(o + 1) * self.inp]; + *slot = dot(xr, wo) + self.b.as_ref().map_or(0.0, |b| b[o]); + } + }); + y + } +} + +/// Fills `y`, rows of `width`, calling `row(index, row)` for each: on several threads when +/// the work (multiplications) is large enough to pay for them. +fn par_rows(y: &mut [f32], width: usize, work: usize, row: impl Fn(usize, &mut [f32]) + Sync) { + let rows = y.len() / width; + let threads = threads().min(rows).min(work / PAR_WORK + 1); + if threads <= 1 { + for (r, yr) in y.chunks_mut(width).enumerate() { + row(r, yr); + } + return; + } + let per = rows.div_ceil(threads); + std::thread::scope(|s| { + for (c, part) in y.chunks_mut(per * width).enumerate() { + let row = &row; + s.spawn(move || { + for (k, yr) in part.chunks_mut(width).enumerate() { + row(c * per + k, yr); + } + }); + } + }); +} + +/// Work below this many multiplications per thread is not split further. +const PAR_WORK: usize = 1 << 18; + +/// The threads a prediction uses: half the machine's, the rest stays for the rest. +fn threads() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::thread::available_parallelism().map_or(1, |n| (n.get() / 2).max(1))) +} + +fn dot(a: &[f32], b: &[f32]) -> f32 { + // Eight running sums: the compiler turns this into vector code. + let mut s = [0.0f32; 8]; + let chunks = a.len() / 8; + for i in 0..chunks { + for k in 0..8 { + s[k] += a[i * 8 + k] * b[i * 8 + k]; + } + } + let mut t: f32 = s.iter().sum(); + for i in chunks * 8..a.len() { + t += a[i] * b[i]; + } + t +} + +struct LayerNorm { + w: Vec, + b: Vec, +} + +impl LayerNorm { + fn load(w: &mut Weights, name: &str, n: usize) -> Result { + Ok(LayerNorm { + w: w.get(&format!("{name}.weight"), &[n])?, + b: w.get(&format!("{name}.bias"), &[n])?, + }) + } + + fn apply(&self, x: &mut [f32]) { + let n = self.w.len(); + for row in x.chunks_mut(n) { + let mean = row.iter().sum::() / n as f32; + let var = row.iter().map(|v| (v - mean) * (v - mean)).sum::() / n as f32; + let inv = 1.0 / (var + 1e-5).sqrt(); + for (i, v) in row.iter_mut().enumerate() { + *v = (*v - mean) * inv * self.w[i] + self.b[i]; + } + } + } +} + +fn rms_norm(x: &mut [f32], w: &[f32]) { + let n = w.len(); + for row in x.chunks_mut(n) { + let ms = row.iter().map(|v| v * v).sum::() / n as f32; + let inv = 1.0 / (ms + f32::EPSILON).sqrt(); + for (i, v) in row.iter_mut().enumerate() { + *v *= inv * w[i]; + } + } +} + +/// The error function (Abramowitz–Stegun 7.1.26 refined: |error| < 1.2e-7). +fn erf(x: f32) -> f32 { + let x = f64::from(x); + let t = 1.0 / (1.0 + 0.5 * x.abs()); + let y = 1.0 + - t * (-x * x - 1.265_512_23 + + t * (1.000_023_68 + + t * (0.374_091_96 + + t * (0.096_784_18 + + t * (-0.186_288_06 + + t * (0.278_868_07 + + t * (-1.135_203_98 + + t * (1.488_515_87 + + t * (-0.822_152_23 + t * 0.170_872_77))))))))) + .exp(); + (if x >= 0.0 { y } else { -y }) as f32 +} + +fn gelu(x: &mut [f32]) { + for v in x { + *v = 0.5 * *v * (1.0 + erf(*v / std::f32::consts::SQRT_2)); + } +} + +struct Block { + in_proj: Linear, // 3D × D, no bias + out_proj: Linear, // D × D, no bias + gab_square: Option, // sm1: d → gab_square per square (larger models) + gab_in: Linear, // sm2: the squares' mean or 64 × gab_square → gab_hid + gab_ln1: LayerNorm, + gab_out: Linear, // sm3: gab_hid → heads × gab_gen + gab_ln2: LayerNorm, + ff1: Linear, + ff2: Linear, + norm1: Vec, + norm2: Vec, +} + +pub struct Net { + dims: Dims, + elo_low: Vec, + elo_high: Vec, + projection: Linear, + gab_weight: Vec, // 4096 × gab_gen, shared by the blocks + blocks: Vec, + final_norm: LayerNorm, + last_ln: LayerNorm, + value_hid: Linear, + value: Linear, + sq_from: Linear, + sq_to: Linear, + promo: Linear, +} + +/// The moves with their probabilities (most likely first) and the chances of the side +/// to move: win, draw, loss. +#[derive(Clone, Debug, Default)] +pub struct Prediction { + pub moves: Vec<(Move, f32)>, + pub wdl: [f32; 3], +} + +impl Net { + pub fn new(w: &mut Weights) -> Result { + let dims = Dims::read(w)?; + let Dims { + d, + heads, + ff, + gab_square, + gab_hid, + gab_gen, + head, + blocks: count, + } = dims; + let mut blocks = Vec::with_capacity(count); + for i in 0..count { + let p = format!("transformer.layers.{i}"); + let gab_in_width = if gab_square == 0 { d } else { 64 * gab_square }; + blocks.push(Block { + in_proj: Linear { + w: w.get(&format!("{p}.self_attn.mha.in_proj_weight"), &[3 * d, d])?, + b: None, + inp: d, + out: 3 * d, + }, + out_proj: Linear::load(w, &format!("{p}.self_attn.mha.out_proj"), d, d, false)?, + gab_square: if gab_square == 0 { + None + } else { + Some(Linear::load( + w, + &format!("{p}.self_attn.sm1"), + gab_square, + d, + true, + )?) + }, + gab_in: Linear::load( + w, + &format!("{p}.self_attn.sm2"), + gab_hid, + gab_in_width, + true, + )?, + gab_ln1: LayerNorm::load(w, &format!("{p}.self_attn.ln1"), gab_hid)?, + gab_out: Linear::load( + w, + &format!("{p}.self_attn.sm3"), + heads * gab_gen, + gab_hid, + true, + )?, + gab_ln2: LayerNorm::load(w, &format!("{p}.self_attn.ln2"), heads * gab_gen)?, + ff1: Linear::load(w, &format!("{p}.linear1"), ff, d, true)?, + ff2: Linear::load(w, &format!("{p}.linear2"), d, ff, true)?, + norm1: w.get(&format!("{p}.norm1.weight"), &[d])?, + norm2: w.get(&format!("{p}.norm2.weight"), &[d])?, + }); + } + Ok(Net { + elo_low: w.get("elo_embedding_low.weight", &[1, EMB])?, + elo_high: w.get("elo_embedding_high.weight", &[1, EMB])?, + projection: Linear::load(w, "token_projection", d, INPUT, true)?, + gab_weight: w.get("gab_shared_weight", &[64 * 64, gab_gen])?, + blocks, + final_norm: LayerNorm::load(w, "transformer.norm", d)?, + last_ln: LayerNorm::load(w, "last_ln", d)?, + value_hid: Linear::load(w, "fc_value_hid", head, d, true)?, + value: Linear::load(w, "fc_value", 3, head, true)?, + sq_from: Linear::load(w, "proj_sq_from", head, d, false)?, + sq_to: Linear::load(w, "proj_sq_to", head, d, false)?, + promo: Linear::load(w, "promo_bias_proj", 4, head, false)?, + dims, + }) + } + + fn elo(&self, elo: u32) -> Vec { + let low = elo.min(5000) as f32 / 5000.0; + (0..EMB) + .map(|i| low * self.elo_low[i] + (1.0 - low) * self.elo_high[i]) + .collect() + } + + pub fn predict(&self, history: &[Chess], self_elo: u32, oppo_elo: u32) -> Prediction { + let Some(pos) = history.last() else { + return Prediction::default(); + }; + let legal = pos.legal_moves(); + if legal.is_empty() { + return Prediction::default(); + } + // The input: per square, 12 planes of each of the last 8 positions (each seen + // from its own side to move; the earliest repeated in front when there are + // fewer), then the two ratings. + let start = history.len().saturating_sub(HISTORY); + let shown = &history[start..]; + let mut x = vec![0.0f32; 64 * INPUT]; + for slot in 0..HISTORY { + let p = &shown[slot.saturating_sub(HISTORY - shown.len())]; + let turn = p.turn(); + for (sq, piece) in p.board().clone() { + let s = if turn == Color::Black { + sq.flip_vertical() + } else { + sq + }; + let role = match piece.role { + Role::Pawn => 0, + Role::Knight => 1, + Role::Bishop => 2, + Role::Rook => 3, + Role::Queen => 4, + Role::King => 5, + }; + let plane = role + if piece.color == turn { 0 } else { 6 }; + x[usize::from(s) * INPUT + slot * PLANES + plane] = 1.0; + } + } + let (se, oe) = (self.elo(self_elo), self.elo(oppo_elo)); + for sq in 0..64 { + let row = &mut x[sq * INPUT + PLANES * HISTORY..(sq + 1) * INPUT]; + row[..EMB].copy_from_slice(&se); + row[EMB..].copy_from_slice(&oe); + } + let mut h = self.projection.apply(&x, 64); + for b in &self.blocks { + h = self.block(b, h); + } + self.final_norm.apply(&mut h); + + // Moves: from-square × to-square scores, and promotions with a bias per piece. + let (d, head) = (self.dims.d, self.dims.head); + let from = self.sq_from.apply(&h, 64); + let to = self.sq_to.apply(&h, 64); + let scale = (head as f32).sqrt(); + let score = |i: usize, j: usize| { + dot( + &from[i * head..(i + 1) * head], + &to[j * head..(j + 1) * head], + ) / scale + }; + let promo_bias = self.promo.apply(&to[56 * head..64 * head], 8); // 8 × 4 + let black = pos.turn() == Color::Black; + let mut logits: Vec<(Move, f32)> = Vec::with_capacity(legal.len()); + for m in &legal { + let UciMove::Normal { + from: f, + to: t, + promotion, + } = m.to_uci(CastlingMode::Standard) + else { + continue; + }; + let flip = |s: Square| if black { s.flip_vertical() } else { s }; + let (f, t) = (usize::from(flip(f)), usize::from(flip(t))); + let logit = match promotion { + None => score(f, t), + Some(role) => { + let piece = match role { + Role::Queen => 0, + Role::Rook => 1, + Role::Bishop => 2, + _ => 3, + }; + score(f, t) + promo_bias[(t - 56) * 4 + piece] * scale + } + }; + logits.push((*m, logit)); + } + let max = logits + .iter() + .map(|(_, l)| *l) + .fold(f32::NEG_INFINITY, f32::max); + let sum: f32 = logits.iter().map(|(_, l)| (l - max).exp()).sum(); + let mut moves: Vec<(Move, f32)> = logits + .into_iter() + .map(|(m, l)| (m, (l - max).exp() / sum)) + .collect(); + moves.sort_by(|a, b| b.1.total_cmp(&a.1)); + + // Win, draw, loss of the side to move (the network gives loss, draw, win). + let mut mean = vec![0.0f32; d]; + for row in h.chunks(d) { + for (m, v) in mean.iter_mut().zip(row) { + *m += v / 64.0; + } + } + self.last_ln.apply(&mut mean); + let mut hid = self.value_hid.apply(&mean, 1); + for v in &mut hid { + *v = v.max(0.0); + } + let v = self.value.apply(&hid, 1); + let vmax = v.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let e: Vec = v.iter().map(|x| (x - vmax).exp()).collect(); + let s: f32 = e.iter().sum(); + Prediction { + moves, + wdl: [e[2] / s, e[1] / s, e[0] / s], + } + } + + /// One post-norm block: attention with the generated bias, then the feed-forward. + fn block(&self, b: &Block, x: Vec) -> Vec { + let Dims { + d, heads, gab_gen, .. + } = self.dims; + let hd = d / heads; + // The attention bias from the squares, each compressed (larger models) or their + // mean. + let summary = match &b.gab_square { + Some(compress) => compress.apply(&x, 64), // 64 × gab_square, square by square + None => { + let mut mean = vec![0.0f32; d]; + for row in x.chunks(d) { + for (m, v) in mean.iter_mut().zip(row) { + *m += v / 64.0; + } + } + mean + } + }; + let mut g = b.gab_in.apply(&summary, 1); + gelu(&mut g); + b.gab_ln1.apply(&mut g); + let mut g = b.gab_out.apply(&g, 1); + gelu(&mut g); + b.gab_ln2.apply(&mut g); // heads × gab_gen + // bias[h][q][k] = g[h] · gab_weight[q*64 + k] + let mut bias = vec![0.0f32; heads * 64 * 64]; + par_rows(&mut bias, 4096, heads * 4096 * gab_gen, |hh, bh| { + let gh = &g[hh * gab_gen..(hh + 1) * gab_gen]; + for (o, slot) in bh.iter_mut().enumerate() { + *slot = dot(gh, &self.gab_weight[o * gab_gen..(o + 1) * gab_gen]); + } + }); + + let qkv = b.in_proj.apply(&x, 64); // 64 × 3d: queries, keys, values + let mut att = vec![0.0f32; 64 * d]; + let scale = 1.0 / (hd as f32).sqrt(); + // Square by square (the rows of `att`), every head. + par_rows(&mut att, d, 64 * 64 * 2 * d, |i, out| { + let mut scores = [0.0f32; 64]; + for hh in 0..heads { + let q = &qkv[i * 3 * d + hh * hd..i * 3 * d + (hh + 1) * hd]; + let mut max = f32::NEG_INFINITY; + for (j, slot) in scores.iter_mut().enumerate() { + let k = &qkv[j * 3 * d + d + hh * hd..j * 3 * d + d + (hh + 1) * hd]; + *slot = dot(q, k) * scale + bias[hh * 4096 + i * 64 + j]; + max = max.max(*slot); + } + let mut sum = 0.0; + for s in scores.iter_mut() { + *s = (*s - max).exp(); + sum += *s; + } + let oh = &mut out[hh * hd..(hh + 1) * hd]; + for (j, s) in scores.iter().enumerate() { + let w = s / sum; + let v = &qkv[j * 3 * d + 2 * d + hh * hd..j * 3 * d + 2 * d + (hh + 1) * hd]; + for (o, v) in oh.iter_mut().zip(v) { + *o += w * v; + } + } + } + }); + let sa = b.out_proj.apply(&att, 64); + let mut x: Vec = x.iter().zip(&sa).map(|(a, b)| a + b).collect(); + rms_norm(&mut x, &b.norm1); + let mut f = b.ff1.apply(&x, 64); + gelu(&mut f); + let f = b.ff2.apply(&f, 64); + let mut x: Vec = x.iter().zip(&f).map(|(a, b)| a + b).collect(); + rms_norm(&mut x, &b.norm2); + x + } +} diff --git a/crates/maia/src/strength.rs b/crates/maia/src/strength.rs new file mode 100644 index 0000000..d565e5d --- /dev/null +++ b/crates/maia/src/strength.rs @@ -0,0 +1,147 @@ +//! How strong Maia plays (docs/research/maia-strength.md): the measured tables of the +//! published models, from a strength on the Lichess blitz scale to the rating to give +//! the network and how surely to choose, and the choice of the move itself. The desktop +//! and the Android apps play by these. + +use shakmaty::Move; + +use crate::{Prediction, pick}; + +/// The published models. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Model { + /// 5M parameters: plays up to about 1800. + Small, + /// 79M parameters: stronger and closer to people, several times slower. + Large, +} + +/// The strongest the small model plays (with the large one missing). +pub const SMALL_MAX: u32 = 1800; + +/// Measured (docs/research/maia-strength.md): Maia's rating input → her strength on +/// the Lichess blitz scale, as she plays here (temperature 1, rare moves dropped). +const SMALL: &[(u32, u32)] = &[ + (600, 1043), + (800, 1154), + (1100, 1333), + (1300, 1426), + (1500, 1485), + (1700, 1563), + (1900, 1632), + (2100, 1683), + (2300, 1737), + (2600, 1767), +]; +const LARGE: &[(u32, u32)] = &[ + (600, 1078), + (1100, 1375), + (1500, 1605), + (1900, 1794), + (2300, 1964), + (2600, 2000), +]; + +/// Above what a model plays choosing among the likely moves (temperature 1), it is made +/// stronger by choosing more surely: measured strength at its top rating input → the +/// temperature (0: always the most likely move). +const SMALL_SURE: &[(u32, f32)] = &[(1767, 1.0), (1854, 0.5)]; +const LARGE_SURE: &[(u32, f32)] = &[(1976, 1.0), (2053, 0.5), (2126, 0.0)]; + +/// How surely `model` chooses its move to play at `strength` (1 below its top). +pub fn temperature(model: Model, strength: u32) -> f32 { + let table = match model { + Model::Small => SMALL_SURE, + Model::Large => LARGE_SURE, + }; + let (first, last) = (table[0], table[table.len() - 1]); + if strength <= first.0 { + return first.1; + } + if strength >= last.0 { + return last.1; + } + let i = table + .iter() + .position(|p| p.0 >= strength) + .unwrap_or(table.len() - 1); + let ((a_s, a_t), (b_s, b_t)) = (table[i - 1], table[i]); + let k = (strength - a_s) as f32 / (b_s - a_s) as f32; + a_t + k * (b_t - a_t) +} + +/// The rating to give `model` for it to play at `strength` (between the measured +/// points, in proportion; outside them, the nearest). +pub fn rating_input(model: Model, strength: u32) -> u32 { + let table = match model { + Model::Small => SMALL, + Model::Large => LARGE, + }; + let (first, last) = (table[0], table[table.len() - 1]); + if strength <= first.1 { + return first.0; + } + if strength >= last.1 { + return last.0; + } + let i = table + .iter() + .position(|p| p.1 >= strength) + .unwrap_or(table.len() - 1); + let ((a_in, a_out), (b_in, b_out)) = (table[i - 1], table[i]); + let t = f64::from(strength - a_out) / f64::from(b_out - a_out); + (f64::from(a_in) + t * f64::from(b_in - a_in)).round() as u32 +} + +/// The move to play from a prediction: a move less than a tenth as likely as the most +/// likely one is not played (human mistakes, not accidents: a 2600 does not hang the +/// queen one time in five thousand), the rest drawn at `temperature`. `random` is in +/// [0, 1). +pub fn choose(prediction: &Prediction, temperature: f32, random: f32) -> Option { + let top = prediction.moves.first().map_or(0.0, |(_, p)| *p); + let likely = Prediction { + moves: prediction + .moves + .iter() + .filter(|(_, p)| *p >= 0.1 * top) + .cloned() + .collect(), + wdl: prediction.wdl, + }; + pick(&likely, temperature, random) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strength_turns_into_the_rating_to_give() { + // The measured points themselves, in proportion between them, the ends held. + assert_eq!(rating_input(Model::Large, 1605), 1500); + assert_eq!(rating_input(Model::Large, 2000), 2600); + assert_eq!(rating_input(Model::Small, 1485), 1500); + assert_eq!(rating_input(Model::Small, SMALL_MAX), 2600); + assert_eq!(rating_input(Model::Small, 900), 600); + // Above the top input: surer choices, down to the most likely move. + assert_eq!(temperature(Model::Large, 1900), 1.0); + assert!((temperature(Model::Large, 2053) - 0.5).abs() < 1e-6); + assert_eq!(temperature(Model::Large, 2200), 0.0); + assert!(temperature(Model::Small, SMALL_MAX) < 1.0); + } + + #[test] + fn rare_moves_are_not_chosen() { + use shakmaty::{Chess, Position}; + let pos = Chess::default(); + let moves = pos.legal_moves(); + let p = Prediction { + moves: vec![(moves[0], 0.9), (moves[1], 0.05)], + wdl: [0.0; 3], + }; + // Whatever the draw: under a tenth of the best is never played. + for r in [0.0, 0.5, 0.99] { + assert_eq!(choose(&p, 5.0, r), Some(moves[0])); + } + } +} diff --git a/crates/maia/src/weights.rs b/crates/maia/src/weights.rs new file mode 100644 index 0000000..dbc0dc3 --- /dev/null +++ b/crates/maia/src/weights.rs @@ -0,0 +1,62 @@ +//! The network's tensors by name, read from the published checkpoint. + +use std::collections::HashMap; + +#[derive(Debug, thiserror::Error)] +pub enum WeightsError { + #[error("cannot read the weights: {0}")] + Io(std::io::Error), + #[error("not a Maia checkpoint")] + Format, + #[error("the weights lack {0}")] + Missing(String), + #[error("{0} has the shape {1:?}, expected {2:?}")] + Shape(String, Vec, Vec), +} + +pub struct Tensor { + pub shape: Vec, + pub data: Vec, +} + +pub struct Weights { + tensors: HashMap, +} + +impl Weights { + /// The tensors of a PyTorch checkpoint (`maia3-5m.pt`, `maia3-79m.pt`). + pub fn parse(bytes: &[u8]) -> Result { + Ok(Weights { + tensors: crate::checkpoint::read(bytes)?, + }) + } + + /// The shape of the tensor `name`, if there is one. + pub fn shape(&self, name: &str) -> Option<&[usize]> { + self.tensors.get(name).map(|t| t.shape.as_slice()) + } + + /// The size `axis` of the tensor `name`. + pub fn dim(&self, name: &str, axis: usize) -> Result { + let shape = self + .shape(name) + .ok_or_else(|| WeightsError::Missing(name.to_owned()))?; + shape.get(axis).copied().ok_or(WeightsError::Format) + } + + /// The tensor `name` of this shape, taken out (each is used once: no copy). + pub fn get(&mut self, name: &str, shape: &[usize]) -> Result, WeightsError> { + let t = self + .tensors + .remove(name) + .ok_or_else(|| WeightsError::Missing(name.to_owned()))?; + if t.shape != shape { + return Err(WeightsError::Shape( + name.to_owned(), + t.shape.clone(), + shape.to_vec(), + )); + } + Ok(t.data) + } +} diff --git a/crates/maia/tests/reference.json b/crates/maia/tests/reference.json new file mode 100644 index 0000000..c8d2ee5 --- /dev/null +++ b/crates/maia/tests/reference.json @@ -0,0 +1,466 @@ +[ + { + "start": "startpos", + "moves": [], + "self": 1500, + "oppo": 1500, + "history": false, + "top": [ + [ + "e2e4", + 0.6428141593933105 + ], + [ + "d2d4", + 0.24165238440036774 + ], + [ + "c2c4", + 0.02500966005027294 + ], + [ + "g1f3", + 0.02293243445456028 + ], + [ + "e2e3", + 0.01666972041130066 + ] + ], + "value": [ + 0.46951544284820557, + 0.02639029733836651, + 0.5040943026542664 + ], + "raw0": [ + 17.96485710144043, + 16.6794490814209, + 16.10539436340332, + 16.205459594726562, + 16.171382904052734, + 15.7096529006958, + 15.763495445251465, + 17.529438018798828 + ] + }, + { + "start": "startpos", + "moves": [], + "self": 1500, + "oppo": 1500, + "history": true, + "top": [ + [ + "e2e4", + 0.6428141593933105 + ], + [ + "d2d4", + 0.24165238440036774 + ], + [ + "c2c4", + 0.02500966005027294 + ], + [ + "g1f3", + 0.02293243445456028 + ], + [ + "e2e3", + 0.01666972041130066 + ] + ], + "value": [ + 0.46951544284820557, + 0.02639029733836651, + 0.5040943026542664 + ], + "raw0": [ + 17.96485710144043, + 16.6794490814209, + 16.10539436340332, + 16.205459594726562, + 16.171382904052734, + 15.7096529006958, + 15.763495445251465, + 17.529438018798828 + ] + }, + { + "start": "startpos", + "moves": [ + "e2e4" + ], + "self": 1100, + "oppo": 1900, + "history": false, + "top": [ + [ + "e7e5", + 0.5098167657852173 + ], + [ + "d7d5", + 0.10851354151964188 + ], + [ + "e7e6", + 0.07479658722877502 + ], + [ + "b8c6", + 0.05990195646882057 + ], + [ + "g8f6", + 0.04459626227617264 + ] + ], + "value": [ + 0.9185879826545715, + 0.010597583837807178, + 0.07081437855958939 + ], + "raw0": [ + 17.965129852294922, + 17.195894241333008, + 16.70180892944336, + 16.798877716064453, + 16.936298370361328, + 16.677993774414062, + 16.85038948059082, + 17.817380905151367 + ] + }, + { + "start": "startpos", + "moves": [ + "e2e4" + ], + "self": 1100, + "oppo": 1900, + "history": true, + "top": [ + [ + "e7e5", + 0.5989676713943481 + ], + [ + "d7d5", + 0.09050962328910828 + ], + [ + "c7c5", + 0.06970801949501038 + ], + [ + "e7e6", + 0.06950542330741882 + ], + [ + "c7c6", + 0.04271207004785538 + ] + ], + "value": [ + 0.8865634202957153, + 0.014099491760134697, + 0.09933703392744064 + ], + "raw0": [ + 17.63120460510254, + 16.954700469970703, + 16.370296478271484, + 16.56428337097168, + 16.249225616455078, + 16.13113021850586, + 16.44071388244629, + 17.29722785949707 + ] + }, + { + "start": "startpos", + "moves": [ + "e2e4", + "c7c5", + "g1f3", + "d7d6", + "d2d4", + "c5d4", + "f3d4", + "g8f6", + "b1c3" + ], + "self": 2200, + "oppo": 2200, + "history": false, + "top": [ + [ + "a7a6", + 0.5752860903739929 + ], + [ + "g7g6", + 0.20385423302650452 + ], + [ + "b8c6", + 0.137393519282341 + ], + [ + "e7e6", + 0.04321761801838875 + ], + [ + "e7e5", + 0.030146829783916473 + ] + ], + "value": [ + 0.47310107946395874, + 0.047588150948286057, + 0.4793107807636261 + ], + "raw0": [ + 13.955000877380371, + 12.096322059631348, + 12.530537605285645, + 14.173426628112793, + 7.782149791717529, + 10.2383451461792, + 9.525634765625, + 10.798513412475586 + ] + }, + { + "start": "startpos", + "moves": [ + "e2e4", + "c7c5", + "g1f3", + "d7d6", + "d2d4", + "c5d4", + "f3d4", + "g8f6", + "b1c3" + ], + "self": 2200, + "oppo": 2200, + "history": true, + "top": [ + [ + "a7a6", + 0.6279764771461487 + ], + [ + "g7g6", + 0.23256923258304596 + ], + [ + "b8c6", + 0.1010085865855217 + ], + [ + "e7e6", + 0.02482432685792446 + ], + [ + "e7e5", + 0.008920162916183472 + ] + ], + "value": [ + 0.5037455558776855, + 0.04437554255127907, + 0.45187896490097046 + ], + "raw0": [ + 12.511881828308105, + 11.150140762329102, + 12.161564826965332, + 12.897330284118652, + 6.544604301452637, + 8.874947547912598, + 8.683369636535645, + 9.639089584350586 + ] + }, + { + "start": "fen 8/P7/8/8/8/8/k6K/8 w - - 0 1", + "moves": [], + "self": 1500, + "oppo": 1500, + "history": false, + "top": [ + [ + "a7a8q", + 0.9182716608047485 + ], + [ + "a7a8r", + 0.03917168453335762 + ], + [ + "h2g3", + 0.016565073281526566 + ], + [ + "h2g2", + 0.011097817681729794 + ], + [ + "h2h3", + 0.005251244641840458 + ] + ], + "value": [ + 0.00018489087233319879, + 0.049978870898485184, + 0.949836254119873 + ], + "raw0": [ + 14.094833374023438, + 13.721369743347168, + 13.231900215148926, + 13.434931755065918, + 13.439070701599121, + 13.142637252807617, + 13.611973762512207, + 14.30400276184082 + ] + }, + { + "start": "fen 8/P7/8/8/8/8/k6K/8 w - - 0 1", + "moves": [], + "self": 1500, + "oppo": 1500, + "history": true, + "top": [ + [ + "a7a8q", + 0.9182716608047485 + ], + [ + "a7a8r", + 0.03917168453335762 + ], + [ + "h2g3", + 0.016565073281526566 + ], + [ + "h2g2", + 0.011097817681729794 + ], + [ + "h2h3", + 0.005251244641840458 + ] + ], + "value": [ + 0.00018489087233319879, + 0.049978870898485184, + 0.949836254119873 + ], + "raw0": [ + 14.094833374023438, + 13.721369743347168, + 13.231900215148926, + 13.434931755065918, + 13.439070701599121, + 13.142637252807617, + 13.611973762512207, + 14.30400276184082 + ] + }, + { + "start": "fen r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1", + "moves": [], + "self": 800, + "oppo": 2500, + "history": false, + "top": [ + [ + "h8h1", + 0.31233590841293335 + ], + [ + "a8a1", + 0.2531071901321411 + ], + [ + "e8g8", + 0.06834959983825684 + ], + [ + "h8g8", + 0.04700848460197449 + ], + [ + "a8b8", + 0.04312087222933769 + ] + ], + "value": [ + 0.5288083553314209, + 0.41402319073677063, + 0.057168520987033844 + ], + "raw0": [ + 15.851913452148438, + 16.566537857055664, + 15.628592491149902, + 15.896244049072266, + 15.539383888244629, + 15.94222354888916, + 16.599716186523438, + 15.779669761657715 + ] + }, + { + "start": "fen r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1", + "moves": [], + "self": 800, + "oppo": 2500, + "history": true, + "top": [ + [ + "h8h1", + 0.31233590841293335 + ], + [ + "a8a1", + 0.2531071901321411 + ], + [ + "e8g8", + 0.06834959983825684 + ], + [ + "h8g8", + 0.04700848460197449 + ], + [ + "a8b8", + 0.04312087222933769 + ] + ], + "value": [ + 0.5288083553314209, + 0.41402319073677063, + 0.057168520987033844 + ], + "raw0": [ + 15.851913452148438, + 16.566537857055664, + 15.628592491149902, + 15.896244049072266, + 15.539383888244629, + 15.94222354888916, + 16.599716186523438, + 15.779669761657715 + ] + } +] \ No newline at end of file diff --git a/crates/maia/tests/reference.rs b/crates/maia/tests/reference.rs new file mode 100644 index 0000000..0362c42 --- /dev/null +++ b/crates/maia/tests/reference.rs @@ -0,0 +1,80 @@ +//! Agreement with the original PyTorch model (tests/reference.json, written by +//! scripts/maia-reference.py): the same top moves with close probabilities. Needs the +//! weights: `MAIA_WEIGHTS=/path/maia3-5m.pt cargo test -p maia -- --ignored`. Another +//! model: its reference file in `MAIA_REFERENCE`. + +use maia::Maia; +use shakmaty::fen::Fen; +use shakmaty::uci::UciMove; +use shakmaty::{CastlingMode, Chess}; + +#[test] +#[ignore = "needs the weights file (MAIA_WEIGHTS)"] +fn matches_the_original_model() { + let path = std::env::var("MAIA_WEIGHTS").expect("MAIA_WEIGHTS"); + let maia = Maia::load(std::path::Path::new(&path)).expect("weights"); + let reference = match std::env::var("MAIA_REFERENCE") { + Ok(file) => std::fs::read_to_string(file).expect("MAIA_REFERENCE"), + Err(_) => include_str!("reference.json").to_owned(), + }; + let cases: serde_json::Value = serde_json::from_str(&reference).expect("json"); + for case in cases.as_array().unwrap() { + let start = case["start"].as_str().unwrap(); + let mut pos: Chess = if start == "startpos" { + Chess::default() + } else { + start[4..] + .parse::() + .unwrap() + .into_position(CastlingMode::Standard) + .unwrap() + }; + let mut history = vec![pos.clone()]; + for m in case["moves"].as_array().unwrap() { + let m = m + .as_str() + .unwrap() + .parse::() + .unwrap() + .to_move(&pos) + .unwrap(); + pos = maia::after(&pos, m); + history.push(pos.clone()); + } + if !case["history"].as_bool().unwrap() { + history = vec![pos.clone()]; + } + let t = std::time::Instant::now(); + let p = maia.predict( + &history, + case["self"].as_u64().unwrap() as u32, + case["oppo"].as_u64().unwrap() as u32, + ); + let ms = t.elapsed().as_millis(); + let ours: Vec<(String, f32)> = p + .moves + .iter() + .take(5) + .map(|(m, pr)| (m.to_uci(CastlingMode::Standard).to_string(), *pr)) + .collect(); + let want: Vec<(String, f32)> = case["top"] + .as_array() + .unwrap() + .iter() + .map(|t| { + ( + t[0].as_str().unwrap().to_owned(), + t[1].as_f64().unwrap() as f32, + ) + }) + .collect(); + println!( + "{start} {:?} hist={} {ms} ms\n ours {ours:?}\n want {want:?}\n wdl {:?} want {:?}", + case["moves"], case["history"], p.wdl, case["value"] + ); + for (k, (m, pr)) in want.iter().enumerate().take(3) { + assert_eq!(&ours[k].0, m, "move {k} of {start}"); + assert!((ours[k].1 - pr).abs() < 0.02, "{m}: {} vs {pr}", ours[k].1); + } + } +} diff --git a/crates/mobile-api/Cargo.toml b/crates/mobile-api/Cargo.toml new file mode 100644 index 0000000..3b48d2a --- /dev/null +++ b/crates/mobile-api/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "mobile-api" +description = "The ChessPenguin core for the Android app: databases, game lists, games (UniFFI)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lib] +crate-type = ["cdylib", "lib"] +name = "mobile_api" + +[[bin]] +# Generates the Kotlin bindings from the built library (`cargo run --bin uniffi-bindgen`). +name = "uniffi-bindgen" +path = "src/bin/uniffi-bindgen.rs" +required-features = ["bindgen"] + +[features] +bindgen = ["uniffi/cli"] + +[dependencies] +chess-core.workspace = true +chess-import.workspace = true +game-review.workspace = true +maia.workspace = true +play.workspace = true +online-games.workspace = true +releases.workspace = true +shakmaty.workspace = true +thiserror.workspace = true +trainer.workspace = true +uci.workspace = true +uniffi = "0.32.2" diff --git a/crates/mobile-api/src/bin/uniffi-bindgen.rs b/crates/mobile-api/src/bin/uniffi-bindgen.rs new file mode 100644 index 0000000..f6cff6c --- /dev/null +++ b/crates/mobile-api/src/bin/uniffi-bindgen.rs @@ -0,0 +1,3 @@ +fn main() { + uniffi::uniffi_bindgen_main() +} diff --git a/crates/mobile-api/src/engine.rs b/crates/mobile-api/src/engine.rs new file mode 100644 index 0000000..7ff2016 --- /dev/null +++ b/crates/mobile-api/src/engine.rs @@ -0,0 +1,421 @@ +//! The engine for the Android app: Stockfish as a child process supervised by the `uci` +//! crate (timeouts, `stop`, killing a hung engine), as on the desktop. The app asks for +//! the analysis of a position and polls; lines of an older position are never shown +//! for a newer one: every snapshot names its search, and events of earlier searches are +//! dropped. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use shakmaty::fen::Fen; +use shakmaty::san::SanPlus; +use shakmaty::uci::UciMove; +use shakmaty::{CastlingMode, Chess, Color, Position}; +use uci::{ + Engine, EngineConfig, EngineEvent, EngineHandle, EnginePosition, Score, SearchId, Side, + WhiteEval, +}; + +/// Why the engine cannot serve. +#[derive(Debug, thiserror::Error, uniffi::Error)] +pub enum EngineFailure { + /// The engine did not start or did not answer the handshake. + #[error("{detail}")] + Start { detail: String }, + /// The position cannot be sent (a bad FEN or move). + #[error("{detail}")] + Input { detail: String }, + /// The engine has stopped (it crashed, hung and was killed, or was quit). + #[error("{detail}")] + Stopped { detail: String }, +} + +/// One line of the analysis, from White's point of view. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct EngineLine { + /// 1 for the best line. + pub multipv: u32, + /// "+0.45", "−1.20", "0.00", "#3" (White mates), "#−2" (Black mates). + pub eval: String, + /// Centipawns for White, when the score is not a mate. + pub cp: Option, + /// Moves to mate: positive when White mates, negative when Black mates. + pub mate: Option, + /// The line in SAN with move numbers: "14.Nd5 Bxd5 15.exd5". + pub text: String, + /// The squares of its first move, for an arrow on the board. + pub from_square: Option, + pub to_square: Option, + /// The line move by move, to show it on the board without touching the game. + pub steps: Vec, +} + +/// A move of an engine line and the position after it. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct LineStep { + /// "14.Nd5", "14…Bxd5". + pub label: String, + pub fen: String, + pub from_square: String, + pub to_square: String, +} + +/// What the engine says about the position of `search`. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct Analysis { + pub search: u64, + pub depth: u32, + pub nodes_per_second: u64, + /// Ordered by `multipv`. + pub lines: Vec, +} + +struct Current { + id: SearchId, + root: Chess, + depth: u32, + nps: u64, + lines: BTreeMap, + changed: bool, +} + +struct State { + next: u64, + multipv: u32, + current: Option, + stopped: Option, +} + +/// A running engine. +#[derive(uniffi::Object)] +pub struct Analyzer { + handle: Mutex>, + state: Mutex, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +#[uniffi::export] +impl Analyzer { + /// Starts the engine at `path` with its network `eval_file`. Blocks for the + /// handshake (seconds at most): call it off the main thread. + #[uniffi::constructor] + pub fn start( + path: String, + eval_file: String, + threads: u32, + hash_mb: u32, + ) -> Result, EngineFailure> { + let start = |e: uci::EngineError| EngineFailure::Start { + detail: e.to_string(), + }; + // Below the app (nice 10): the phone's interface comes first while it thinks. + let config = EngineConfig { + nice: 10, + ..EngineConfig::new(path) + }; + let handle = Engine::spawn_with(config, Box::new(|| {})).map_err(start)?; + if !eval_file.is_empty() { + handle + .set_option("EvalFile", Some(&eval_file)) + .map_err(start)?; + } + handle.set_threads(threads.max(1)).map_err(start)?; + handle.set_hash_mb(hash_mb.max(1)).map_err(start)?; + Ok(Arc::new(Analyzer { + handle: Mutex::new(Some(handle)), + state: Mutex::new(State { + next: 0, + multipv: 1, + current: None, + stopped: None, + }), + })) + } + + /// Analyses the position reached from `start_fen` by `moves` (UCI), with `lines` + /// lines, until [`Analyzer::stop`] or the next call. Returns the search's number: + /// only snapshots with it belong to this position. + pub fn analyze( + &self, + start_fen: String, + moves: Vec, + lines: u32, + ) -> Result { + let input = |detail: String| EngineFailure::Input { detail }; + let fen: Fen = start_fen.parse().map_err(|e| input(format!("{e}")))?; + let mut root: Chess = fen + .into_position(CastlingMode::Standard) + .map_err(|e| input(format!("{e}")))?; + for u in &moves { + let m = u + .parse::() + .ok() + .and_then(|m| m.to_move(&root).ok()) + .ok_or_else(|| input(format!("illegal move {u}")))?; + root.play_unchecked(m); + } + let guard = lock(&self.handle); + let handle = guard.as_ref().ok_or_else(|| self.stopped())?; + let mut st = lock(&self.state); + let lines = lines.clamp(1, 5); + if st.multipv != lines { + handle.set_multipv(lines).map_err(|e| self.failed(e))?; + st.multipv = lines; + } + st.next += 1; + let id = SearchId(st.next); + handle + .analyze(EnginePosition::fen(start_fen, moves), id) + .map_err(|e| self.failed(e))?; + st.current = Some(Current { + id, + root, + depth: 0, + nps: 0, + lines: BTreeMap::new(), + changed: false, + }); + Ok(id.0) + } + + /// Stops the search (its last lines stay valid for its position). + pub fn stop(&self) { + if let Some(h) = lock(&self.handle).as_ref() { + let _ = h.stop(); + } + lock(&self.state).current = None; + } + + /// Waits up to `timeout_ms` for the engine; returns the analysis of the current + /// search when it has changed, `None` otherwise. Fails once the engine has stopped. + pub fn poll(&self, timeout_ms: u32) -> Result, EngineFailure> { + let mut events = Vec::new(); + { + let guard = lock(&self.handle); + let handle = guard.as_ref().ok_or_else(|| self.stopped())?; + if let Some(e) = handle.recv_timeout(Duration::from_millis(timeout_ms.into())) { + events.push(e); + events.extend(handle.drain_events()); + } + } + let mut st = lock(&self.state); + for e in events { + match e { + EngineEvent::Info { search_id, info } => { + let Some(cur) = st.current.as_mut().filter(|c| c.id == search_id) else { + continue; + }; + if let Some(d) = info.depth { + cur.depth = d; + } + if let Some(n) = info.nps { + cur.nps = n; + } + if let (Some(score), false) = (info.score, info.pv.is_empty()) { + let k = info.multipv_index(); + let line = engine_line(&cur.root, k, score.score, &info.pv); + cur.lines.insert(k, line); + cur.changed = true; + } + } + EngineEvent::Terminated(reason) => { + st.stopped = Some(format!("{reason:?}")); + } + _ => {} + } + } + if let Some(reason) = st.stopped.clone() { + *lock(&self.handle) = None; + return Err(EngineFailure::Stopped { detail: reason }); + } + let multipv = st.multipv; + Ok(st.current.as_mut().filter(|c| c.changed).map(|c| { + c.changed = false; + Analysis { + search: c.id.0, + depth: c.depth, + nodes_per_second: c.nps, + lines: c + .lines + .values() + .filter(|l| l.multipv <= multipv) + .cloned() + .collect(), + } + })) + } + + /// Quits the engine (and kills it if it does not leave in time). + pub fn quit(&self) { + if let Some(h) = lock(&self.handle).take() { + h.quit(); + } + } +} + +impl Analyzer { + fn stopped(&self) -> EngineFailure { + EngineFailure::Stopped { + detail: lock(&self.state) + .stopped + .clone() + .unwrap_or_else(|| "the engine has stopped".into()), + } + } + + fn failed(&self, e: uci::EngineError) -> EngineFailure { + EngineFailure::Stopped { + detail: e.to_string(), + } + } +} + +/// A line of the engine in SAN, its score for White. +fn engine_line(root: &Chess, multipv: u32, score: Score, pv: &[String]) -> EngineLine { + let side = if root.turn() == Color::White { + Side::White + } else { + Side::Black + }; + let white = uci::EngineScore { + score, + bound: uci::ScoreBound::Exact, + } + .to_white(side); + let (cp, mate) = match white.eval { + WhiteEval::Cp(cp) => (Some(cp), None), + WhiteEval::Mate { winner, moves } => { + let n = moves as i32; + (None, Some(if winner == Side::White { n } else { -n })) + } + }; + line_with(root, multipv, cp, mate, pv) +} + +/// The line `pv` (UCI) from `root` with its evaluation for White: centipawns, or moves +/// to mate (positive when White mates). Stops at the first move that is not legal. +pub(crate) fn line_with( + root: &Chess, + multipv: u32, + cp: Option, + mate: Option, + pv: &[String], +) -> EngineLine { + let eval = match (mate, cp) { + (Some(n), _) if n < 0 => format!("#\u{2212}{}", -n), + (Some(n), _) => format!("#{n}"), + (None, cp) => pawns(cp.unwrap_or(0)), + }; + let mut pos = root.clone(); + let mut words = Vec::new(); + let mut steps = Vec::new(); + let mut squares = None; + for (i, u) in pv.iter().enumerate() { + let Some(m) = u.parse::().ok().and_then(|m| m.to_move(&pos).ok()) else { + break; + }; + if i == 0 { + squares = Some((u[0..2].to_owned(), u[2..4].to_owned())); + } + let number = pos.fullmoves().get(); + let white = pos.turn() == Color::White; + let san = SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string(); + let label = if white { + format!("{number}.{san}") + } else { + format!("{number}\u{2026}{san}") + }; + words.push(if white || i == 0 { label.clone() } else { san }); + steps.push(LineStep { + label, + fen: Fen::from_position(&pos, shakmaty::EnPassantMode::Legal).to_string(), + from_square: u[0..2].to_owned(), + to_square: u[2..4].to_owned(), + }); + } + EngineLine { + multipv, + eval, + cp, + mate, + text: words.join(" "), + from_square: squares.as_ref().map(|s| s.0.clone()), + to_square: squares.map(|s| s.1), + steps, + } +} + +/// Centipawns as pawns with a sign: "+0.45", "−1.20", "0.00". +pub(crate) fn pawns(cp: i32) -> String { + let sign = match cp.signum() { + 1 => "+", + -1 => "\u{2212}", + _ => "", + }; + let a = cp.unsigned_abs(); + format!("{sign}{}.{:02}", a / 100, a % 100) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scores_read_for_white() { + let black_to_move: Chess = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1" + .parse::() + .unwrap() + .into_position(CastlingMode::Standard) + .unwrap(); + let l = engine_line( + &black_to_move, + 1, + Score::Cp(-30), + &["e7e5".into(), "g1f3".into()], + ); + assert_eq!(l.eval, "+0.30"); + assert_eq!(l.text, "1\u{2026}e5 2.Nf3"); + assert_eq!( + (l.from_square.as_deref(), l.to_square.as_deref()), + (Some("e7"), Some("e5")) + ); + let m = engine_line(&black_to_move, 1, Score::Mate(2), &[]); + assert_eq!((m.eval.as_str(), m.mate), ("#\u{2212}2", Some(-2))); + assert_eq!(pawns(0), "0.00"); + assert_eq!(pawns(-120), "\u{2212}1.20"); + } + + /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`) answers + /// like Stockfish; lines of an older search never show up for a newer one. + #[test] + fn analysis_belongs_to_its_position() { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + let a = Analyzer::start(fake.into(), String::new(), 1, 16).unwrap(); + let start = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1".to_owned(); + let first = a.analyze(start.clone(), vec![], 1).unwrap(); + let second = a.analyze(start, vec!["e2e4".into()], 1).unwrap(); + assert!(second > first); + let mut seen = 0; + for _ in 0..50 { + if let Some(s) = a.poll(100).unwrap() { + assert_eq!(s.search, second); + seen += 1; + } + if seen >= 3 { + break; + } + } + assert!(seen >= 3, "no analysis arrived"); + a.stop(); + a.quit(); + assert!(a.poll(10).is_err()); + } +} diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs new file mode 100644 index 0000000..73ffb39 --- /dev/null +++ b/crates/mobile-api/src/lib.rs @@ -0,0 +1,725 @@ +//! The ChessPenguin core for the Android app (docs/research/android-stack.md): open a +//! database the way Android hands files over (a file descriptor, or the files of a +//! ChessBase folder), list its games a page at a time, give a game as a tree of moves +//! with the positions, ready for the board and the notation. Bindings: UniFFI. +//! +//! Databases are read only, except the user's own ones in the app's folder +//! (`session.rs`): a game is changed in a [`GameSession`] and saved there. + +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use chess_core::{Game, MoveKind, NodeId}; +use shakmaty::Position; + +mod engine; +mod online; +mod play; +mod prep; +mod review; +mod session; +mod train; +mod update; + +pub use engine::{Analysis, Analyzer, EngineFailure, EngineLine, LineStep}; +pub use online::{ + AccountLookup, DownloadState, OnlineAccount, OnlineDatabase, OnlineDownload, OnlineFailure, + OnlineProblem, OnlineTarget, Site, +}; +pub use play::{ + GameEnding, MaiaPlayer, ResignJudge, Rival, RodentBook, RodentFailure, RodentPlayer, + RodentStyle, computer_game_tags, hopeless_turns, maia_range, move_pause_ms, rival_label, + rival_name, rodent_book_pack, rodent_range, rodent_styles, rodent_version, +}; +pub use prep::{ + PlayerSuggestion, PlayerSuggestions, PrepContinuation, PrepMatch, PrepPhase, PrepResult, + PrepSearch, PrepState, +}; +pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview}; +pub use session::{Edited, GameSession, own_create, own_remove, own_save}; +pub use train::{TrainState, TrainStats, TrainVerdict, Trainer, trainer_set_file}; +pub use update::{ApkFile, AppRelease, ReleaseCheck}; + +uniffi::setup_scaffolding!(); + +/// What went wrong opening or reading a database, in words for the user (the Kotlin +/// side shows them as they are, or picks its own text by kind). +#[derive(Debug, thiserror::Error, uniffi::Error)] +pub enum ApiError { + /// The file could not be read. + #[error("{detail}")] + Io { detail: String }, + /// A known format that cannot be read (password, ChessBase 2CBH). + #[error("{detail}")] + Unsupported { detail: String }, + /// The file is damaged or not a database. + #[error("{detail}")] + Corrupt { detail: String }, + /// An archive without a database inside. + #[error("no PGN or ChessBase database in the archive")] + Empty, + /// No game with this number. + #[error("no game {index}")] + NoGame { index: u32 }, + /// No move at this place of the game's list. + #[error("no move {place}")] + NoNode { place: u32 }, + /// A change of the game that cannot be made (an illegal move, …). + #[error("{detail}")] + Edit { detail: String }, +} + +impl From for ApiError { + fn from(e: chess_import::ImportError) -> Self { + use chess_import::ImportError as E; + match e { + E::Io { source, .. } => ApiError::Io { + detail: source.to_string(), + }, + // A .cbh alone: reported as before (the app opens a ChessBase database + // by all its files, `open_chessbase`). + E::Unsupported(u @ chess_import::Unsupported::ChessBaseFiles) => ApiError::Corrupt { + detail: u.to_string(), + }, + E::Unsupported(u) => ApiError::Unsupported { + detail: u.to_string(), + }, + E::Corrupt(m) => ApiError::Corrupt { detail: m }, + E::Empty => ApiError::Empty, + E::Cancelled => ApiError::Io { + detail: "cancelled".into(), + }, + } + } +} + +/// An open database. +#[derive(uniffi::Object)] +pub struct Database { + db: Arc, + format: String, + notes: Vec, + /// At most one opponent-preparation worker per open database. + prep: std::sync::Mutex>>, +} + +/// One line of the game list. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct GameRow { + /// The game's number in the database (0-based), for [`Database::game`]. + pub index: u32, + pub white: String, + pub black: String, + /// "1-0", "0-1", "1/2-1/2" or "*". + pub result: String, + /// As in PGN: "1858.??.??". + pub date: String, + pub event: String, + pub eco: String, + pub white_elo: String, + pub black_elo: String, +} + +/// A PGN tag. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct Tag { + pub name: String, + pub value: String, +} + +/// A position in the game: the root (the start position) or the one after a move. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct MoveNode { + /// The node's id (the root is 0); `children` and `parent` refer to these. + pub id: u32, + pub parent: Option, + /// The moves from here: the main line first, then the variations. + pub children: Vec, + /// SAN of the move that led here ("" for the root), always Latin letters. + pub san: String, + /// The move's number and side: 12 and true for "12.Nf3", 12 and false for "12…Nf6". + pub move_number: u32, + pub white: bool, + /// Numeric annotation glyphs ($1 = "!") and their symbols ("!", "+-", …). + pub nags: Vec, + pub nag_symbols: String, + /// Comments as shown: board commands left out, lines reflowed. + pub comment_before: String, + pub comment_after: String, + /// The position here, and the squares of the move that led to it (for highlighting). + pub fen: String, + pub from_square: Option, + pub to_square: Option, + /// A null move ("--") of a study. + pub null_move: bool, + /// The move in UCI notation, for the engine's history; empty for the root and a + /// null move (after which the engine gets the position as a FEN). + pub uci: String, + /// Arrows (`[%cal]`) and marked squares (`[%csl]`) of the comments after the move. + pub marks: Vec, + /// "checkmate" or "stalemate" when the game cannot go on from here; "" otherwise. + pub end: String, + /// On the main line of the game (not inside a variation). + pub main_line: bool, +} + +/// An arrow (`to` set) or a marked square of a comment, in a comment color: +/// 'R', 'G', 'B', 'Y' or another letter. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct Mark { + pub color: String, + pub from: String, + pub to: Option, +} + +/// A game ready to show. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct GameData { + pub tags: Vec, + pub result: String, + /// Every node: `nodes[0]` is the root; a node's id is its place in this list. + pub nodes: Vec, + /// Problems found reading the game, one line each. + pub notes: Vec, +} + +fn never() -> AtomicBool { + AtomicBool::new(false) +} + +fn wrap(opened: chess_import::Opened) -> Arc { + Arc::new(Database { + db: Arc::new(opened.db), + format: opened.format.label().to_owned(), + notes: opened.notes, + prep: std::sync::Mutex::new(None), + }) +} + +/// Opens a database file (PGN, `.zip`, `.7z`, `.cbv`) from a file descriptor; the +/// descriptor is taken over and closed (on Android: `ParcelFileDescriptor.detachFd()`). +/// `name` is the file's name, for its extension. +#[cfg(unix)] +#[uniffi::export] +pub fn open_file(name: String, fd: i32) -> Result, ApiError> { + let bytes = read_fd(fd)?; + open_bytes(name, bytes) +} + +#[cfg(unix)] +fn read_fd(fd: i32) -> Result, ApiError> { + use std::os::fd::FromRawFd; + if fd < 0 { + return Err(ApiError::Io { + detail: "no file".into(), + }); + } + // SAFETY: the caller hands the descriptor over (detached from its owner); the File + // owns and closes it. + read_all(unsafe { std::fs::File::from_raw_fd(fd) }) +} + +fn read_all(mut file: std::fs::File) -> Result, ApiError> { + use std::io::Read; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).map_err(|e| ApiError::Io { + detail: e.to_string(), + })?; + Ok(bytes) +} + +/// Opens a database file given as its content. +#[uniffi::export] +pub fn open_bytes(name: String, bytes: Vec) -> Result, ApiError> { + Ok(wrap(chess_import::open_bytes( + &name, + bytes, + &mut |_| {}, + &never(), + )?)) +} + +/// A file of a ChessBase database folder: its name and descriptor (taken over). +#[derive(Debug, Clone, uniffi::Record)] +pub struct FolderFile { + pub name: String, + pub fd: i32, +} + +/// Opens the ChessBase database `cbh_name` from the files of its folder (the `.cbh` +/// and the files beside it with the same name; others are closed unread). +#[cfg(unix)] +#[uniffi::export] +pub fn open_chessbase(cbh_name: String, files: Vec) -> Result, ApiError> { + let stem = cbh_name + .rsplit_once('.') + .map_or(cbh_name.as_str(), |(s, _)| s); + // Every descriptor is owned (and so closed) from here on, also when one fails. + let owned: Vec<(String, Option)> = files + .into_iter() + .map(|f| (f.name, owned_fd(f.fd))) + .collect(); + let mut contents = Vec::new(); + for (name, file) in owned { + if name + .rsplit_once('.') + .is_some_and(|(s, _)| s.to_lowercase() == stem.to_lowercase()) + { + let Some(file) = file else { + return Err(ApiError::Io { + detail: format!("no file {name}"), + }); + }; + contents.push((name, read_all(file)?)); + } + } + Ok(wrap(chess_import::open_chessbase_files( + &cbh_name, + &contents, + &mut |_| {}, + &never(), + )?)) +} + +#[cfg(unix)] +fn owned_fd(fd: i32) -> Option { + use std::os::fd::FromRawFd; + // SAFETY: as in `read_fd`: the descriptor is ours to close. + (fd >= 0).then(|| unsafe { std::fs::File::from_raw_fd(fd) }) +} + +/// Opens a database by its path (tests, tools; the app uses descriptors). +#[uniffi::export] +pub fn open_path(path: String) -> Result, ApiError> { + Ok(wrap(chess_import::open( + std::path::Path::new(&path), + &mut |_| {}, + &never(), + )?)) +} + +#[uniffi::export] +impl Database { + /// The number of games. + pub fn len(&self) -> u32 { + self.db.len() as u32 + } + + pub fn is_empty(&self) -> bool { + self.db.is_empty() + } + + /// What the database was read from ("PGN", "ChessBase", "zip", …). + pub fn format(&self) -> String { + self.format.clone() + } + + /// Remarks about the conversion, one line each. + pub fn notes(&self) -> Vec { + self.notes.clone() + } + + /// Up to `count` lines of the game list from `start` on. + pub fn rows(&self, start: u32, count: u32) -> Vec { + let Some(pgn) = self.db.as_pgn() else { + return Vec::new(); + }; + pgn.entries() + .iter() + .skip(start as usize) + .take(count as usize) + .map(row) + .collect() + } + + /// The numbers of the games whose players, event, site, date or opening code (ECO) + /// contain every word of `text` (case does not matter); all games for an empty text. + pub fn find(&self, text: String) -> Vec { + let Some(pgn) = self.db.as_pgn() else { + return Vec::new(); + }; + let words: Vec = text.split_whitespace().map(str::to_lowercase).collect(); + pgn.entries() + .iter() + .filter(|e| { + words.is_empty() || { + let hay = ["White", "Black", "Event", "Site", "Date", "ECO"] + .iter() + .filter_map(|t| e.tag(t)) + .collect::>() + .join(" ") + .to_lowercase(); + words.iter().all(|w| hay.contains(w.as_str())) + } + }) + .map(|e| e.index as u32) + .collect() + } + + /// These games (from [`Database::find`]) from the most recent to the oldest, by the + /// time they were played (`UTCDate` and `UTCTime` when there, else `Date`); games of + /// the same time keep the newer place in the file first. For downloaded databases, + /// where both sites' games are appended oldest first. + pub fn newest_first(&self, indices: Vec) -> Vec { + let Some(pgn) = self.db.as_pgn() else { + return indices; + }; + let entries = pgn.entries(); + let when = |i: u32| { + entries + .get(i as usize) + .map(|e| e.played_at()) + .unwrap_or_default() + }; + let mut keyed: Vec<(String, u32)> = indices.into_iter().map(|i| (when(i), i)).collect(); + keyed.sort_by(|a, b| b.cmp(a)); + keyed.into_iter().map(|(_, i)| i).collect() + } + + /// The rows of these games (from [`Database::find`]), in this order. + pub fn rows_of(&self, indices: Vec) -> Vec { + let Some(pgn) = self.db.as_pgn() else { + return Vec::new(); + }; + let entries = pgn.entries(); + indices + .iter() + .filter_map(|&i| entries.get(i as usize)) + .map(row) + .collect() + } + + /// The game `index` as PGN text, as it is in the file (to copy or share). + pub fn pgn(&self, index: u32) -> Option { + self.db.raw_text(index as usize) + } + + /// The game `index`, ready to show. + pub fn game(&self, index: u32) -> Result { + let parsed = self + .db + .load_game(index as usize) + .ok_or(ApiError::NoGame { index })?; + Ok(game_data(&parsed.game, &parsed.diagnostics)) + } + + /// The game `index`, to change (moves, variations, its data) and save. + pub fn session(&self, index: u32) -> Result, ApiError> { + let parsed = self + .db + .load_game(index as usize) + .ok_or(ApiError::NoGame { index })?; + let mut game = parsed.game; + game.mark_saved(); + Ok(GameSession::wrap(game)) + } + + /// The analysis of the game `index` (its report), with earlier results from the + /// cache folder `cache_dir` ("" for none) or from `[%eval]` comments of the game. + pub fn review(&self, index: u32, cache_dir: String) -> Result, ApiError> { + let parsed = self + .db + .load_game(index as usize) + .ok_or(ApiError::NoGame { index })?; + Ok(GameReview::new(parsed.game, cache_dir)) + } +} + +/// The nodes of [`GameData::nodes`]: every node the game ever had, by its id. A move +/// keeps its place when the game is changed (new moves come at the end, a removed one +/// stays as an unreachable entry), so a cursor or a report's marks stay on their moves. +fn order(game: &Game) -> Vec { + game.all_nodes().collect() +} + +/// The place in [`GameData::nodes`] of every node of the game. +fn places(game: &Game) -> std::collections::HashMap { + order(game) + .iter() + .enumerate() + .map(|(i, id)| (*id, i as u32)) + .collect() +} + +fn row(e: &chess_core::GameEntry) -> GameRow { + let tag = |name: &str| e.tag(name).unwrap_or("").to_owned(); + GameRow { + index: e.index as u32, + white: tag("White"), + black: tag("Black"), + result: tag("Result"), + date: tag("Date"), + event: tag("Event"), + eco: tag("ECO"), + white_elo: tag("WhiteElo"), + black_elo: tag("BlackElo"), + } +} + +fn marks(comments: &[String]) -> Vec { + use chess_core::{Annotation, CommentPart, ShapeColor}; + let letter = |c: ShapeColor| { + match c { + ShapeColor::Red => 'R', + ShapeColor::Green => 'G', + ShapeColor::Blue => 'B', + ShapeColor::Yellow => 'Y', + ShapeColor::Other(c) => c, + } + .to_string() + }; + let mut out = Vec::new(); + for c in comments { + for part in chess_core::parse_comment(c) { + match part { + CommentPart::Annotation(Annotation::Arrows(list)) => { + out.extend(list.into_iter().map(|(c, from, to)| Mark { + color: letter(c), + from: from.to_string(), + to: Some(to.to_string()), + })) + } + CommentPart::Annotation(Annotation::Squares(list)) => { + out.extend(list.into_iter().map(|(c, sq)| Mark { + color: letter(c), + from: sq.to_string(), + to: None, + })) + } + _ => {} + } + } + } + out +} + +fn game_data(game: &Game, diagnostics: &[chess_core::Diagnostic]) -> GameData { + let order = order(game); + let places = places(game); + let place = |id: NodeId| places.get(&id).copied(); + let main: std::collections::HashSet = game.mainline().into_iter().collect(); + let nodes = order + .iter() + .map(|&id| { + let node = game.node(id); + let mv = game.game_move(id); + let (move_number, color) = game.move_number(id).unwrap_or((0, shakmaty::Color::White)); + let uci = mv.and_then(|m| m.uci()); + let squares = uci + .as_deref() + .filter(|u| u.len() >= 4) + .map(|u| (u[0..2].to_owned(), u[2..4].to_owned())); + let nags: Vec = node + .map(|n| n.nags().iter().map(|g| g.0).collect()) + .unwrap_or_default(); + // A removed move: kept in its place, reached from nowhere. + let attached = game.is_attached(id); + MoveNode { + id: place(id).unwrap_or(0), + parent: game.parent(id).filter(|_| attached).and_then(place), + children: if attached { + game.children(id).iter().filter_map(|c| place(*c)).collect() + } else { + Vec::new() + }, + san: mv.map(|m| m.san.clone()).unwrap_or_default(), + move_number, + white: color == shakmaty::Color::White, + nag_symbols: node + .map(|n| { + n.nags() + .iter() + .filter_map(|g| g.symbol()) + .collect::>() + .join("") + }) + .unwrap_or_default(), + nags, + comment_before: node + .map(|n| chess_core::comment_display_text(n.comments_before())) + .unwrap_or_default(), + comment_after: node + .map(|n| chess_core::comment_display_text(n.comments_after())) + .unwrap_or_default(), + fen: game.fen(id).unwrap_or_default(), + from_square: squares.as_ref().map(|s| s.0.clone()), + to_square: squares.map(|s| s.1), + null_move: mv.is_some_and(|m| matches!(m.kind, MoveKind::Null)), + uci: uci.clone().unwrap_or_default(), + marks: node.map(|n| marks(n.comments_after())).unwrap_or_default(), + end: game + .position(id) + .map(|p| { + if p.is_checkmate() { + "checkmate" + } else if p.is_stalemate() { + "stalemate" + } else { + "" + } + }) + .unwrap_or("") + .to_owned(), + main_line: id == NodeId::ROOT || main.contains(&id), + } + }) + .collect(); + GameData { + tags: game + .tags() + .iter() + .map(|(n, v)| Tag { + name: n.clone(), + value: v.clone(), + }) + .collect(), + result: game.result().as_str().to_owned(), + nodes, + notes: diagnostics.iter().map(|d| d.message.clone()).collect(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn classics() -> Arc { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn"); + open_path(path.into()).expect("the sample opens") + } + + #[test] + fn rows_come_a_page_at_a_time() { + let db = classics(); + assert!(db.len() >= 2); + let first = db.rows(0, 1); + assert_eq!(first.len(), 1); + assert_eq!(first[0].index, 0); + assert!(!first[0].white.is_empty()); + assert_eq!(db.rows(1, 100).len() as u32, db.len() - 1); + assert!(db.rows(db.len(), 10).is_empty()); + } + + #[test] + fn comment_marks_and_uci_moves_reach_the_app() { + let pgn = b"[Event \"t\"]\n\n1. e4 {[%cal Ge2e4,Rd7d5] [%csl Yd5] Center} e5 *\n".to_vec(); + let db = open_bytes("t.pgn".into(), pgn).unwrap(); + let g = db.game(0).unwrap(); + let e4 = &g.nodes[1]; + assert_eq!(e4.uci, "e2e4"); + assert_eq!(e4.comment_after, "Center"); + let m = |c: &str, f: &str, t: Option<&str>| Mark { + color: c.into(), + from: f.into(), + to: t.map(Into::into), + }; + assert_eq!( + e4.marks, + vec![ + m("G", "e2", Some("e4")), + m("R", "d7", Some("d5")), + m("Y", "d5", None) + ] + ); + assert!(g.nodes[0].uci.is_empty()); + assert!(g.nodes.iter().all(|n| n.end.is_empty())); + let mate = open_bytes("m.pgn".into(), b"1. f3 e5 2. g4 Qh4# 0-1\n".to_vec()).unwrap(); + let g = mate.game(0).unwrap(); + assert_eq!(g.nodes.last().unwrap().end, "checkmate"); + assert!(db.pgn(0).unwrap().contains("[%cal Ge2e4,Rd7d5]")); + } + + #[test] + fn games_are_found_by_words() { + let db = classics(); + assert_eq!(db.find(String::new()).len() as u32, db.len()); + let morphy = db.find("MORPHY opera".into()); + assert!(!morphy.is_empty()); + let rows = db.rows_of(morphy.clone()); + assert!( + rows.iter() + .all(|r| r.white.contains("Morphy") || r.black.contains("Morphy")) + ); + assert!(db.find("no such player anywhere".into()).is_empty()); + // By the opening code too: the Opera game is a Philidor (C41). + let c41 = db.find("c41".into()); + assert!(!c41.is_empty()); + assert!(db.rows_of(c41).iter().all(|r| r.eco == "C41")); + } + + #[test] + fn a_game_is_a_tree_with_positions() { + let db = classics(); + let g = db.game(0).expect("a game"); + let root = &g.nodes[0]; + assert_eq!(root.id, 0); + assert_eq!(root.parent, None); + assert!(root.fen.starts_with("rnbqkbnr/pppppppp")); + let first = &g.nodes[root.children[0] as usize]; + assert_eq!(first.parent, Some(0)); + assert!(first.white && first.move_number == 1); + assert!(first.from_square.is_some() && first.to_square.is_some()); + assert!(first.main_line); + // Every child points back to its parent, ids are places in the list. + for (i, n) in g.nodes.iter().enumerate() { + assert_eq!(n.id as usize, i); + for &c in &n.children { + assert_eq!(g.nodes[c as usize].parent, Some(n.id)); + } + } + assert!(matches!(db.game(db.len()), Err(ApiError::NoGame { .. }))); + } + + #[test] + fn comments_and_variations_come_along() { + // The Opera game of the samples has comments and a variation. + let db = classics(); + let g = (0..db.len()) + .map(|i| db.game(i).expect("a game")) + .find(|g| g.nodes.iter().any(|n| n.san == "Qb8+")) + .expect("the Opera game"); + assert!( + g.nodes + .iter() + .any(|n| !n.comment_after.is_empty() && !n.comment_after.contains("[%")) + ); + assert!(g.nodes.iter().any(|n| !n.main_line)); + } + + #[test] + fn downloaded_games_come_newest_first() { + let pgn = b"[White \"a\"][UTCDate \"2020.01.02\"][UTCTime \"10:00:00\"]\n\n1. e4 *\n\n\ + [White \"b\"][UTCDate \"2020.01.02\"][UTCTime \"09:00:00\"]\n\n1. e4 *\n\n\ + [White \"c\"][Date \"2021.05.01\"]\n\n1. e4 *\n\n\ + [White \"d\"][UTCDate \"2019.12.31\"][UTCTime \"23:59:59\"]\n\n1. e4 *\n" + .to_vec(); + let db = open_bytes("t.pgn".into(), pgn).unwrap(); + let order = db.newest_first(db.find(String::new())); + let names: Vec = db.rows_of(order).into_iter().map(|r| r.white).collect(); + assert_eq!(names, ["c", "a", "b", "d"]); + } + + #[test] + fn bytes_open_like_files() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn"); + let bytes = std::fs::read(path).expect("read"); + let db = open_bytes("classics.pgn".into(), bytes).expect("opens"); + assert_eq!(db.len(), classics().len()); + assert_eq!(db.format(), classics().format()); + assert!(matches!( + open_bytes("x.cbh".into(), vec![0; 46]), + Err(ApiError::Corrupt { .. }) + )); + } + + #[cfg(unix)] + #[test] + fn a_descriptor_is_read_and_closed() { + use std::os::fd::IntoRawFd; + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn"); + let fd = std::fs::File::open(path).expect("open").into_raw_fd(); + let db = open_file("classics.pgn".into(), fd).expect("opens"); + assert_eq!(db.len(), classics().len()); + assert!(open_file("x.pgn".into(), -1).is_err()); + } +} diff --git a/crates/mobile-api/src/online.rs b/crates/mobile-api/src/online.rs new file mode 100644 index 0000000..75e3d4c --- /dev/null +++ b/crates/mobile-api/src/online.rs @@ -0,0 +1,362 @@ +//! A player's games from Lichess and Chess.com for the Android app: the `online-games` +//! crate (the same downloads, state files and resuming as on the desktop) with its +//! download on a thread of its own. The app looks accounts up, starts a download into a +//! file of its own folder, asks for the progress while it runs, and can stop it; what +//! was fetched stays, and the next download continues without duplicates. +//! +//! Every call that talks to a site blocks: call it off the main thread. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use online_games::{Account, Done, Failure, Lookup, Platform, Progress, State}; + +/// A site. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum Site { + Lichess, + ChessCom, +} + +impl From for Platform { + fn from(s: Site) -> Self { + match s { + Site::Lichess => Platform::Lichess, + Site::ChessCom => Platform::ChessCom, + } + } +} + +impl From for Site { + fn from(p: Platform) -> Self { + match p { + Platform::Lichess => Site::Lichess, + Platform::ChessCom => Site::ChessCom, + } + } +} + +/// An account on a site. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct OnlineAccount { + pub site: Site, + /// As the site spells it. + pub username: String, + /// Lichess: the games of the account (of all kinds, so at most this many). + pub games: Option, + /// Chess.com: the months with games. + pub months: Option, +} + +impl From<&Account> for OnlineAccount { + fn from(a: &Account) -> Self { + OnlineAccount { + site: a.platform.into(), + username: a.username.clone(), + games: a.games, + months: a.months.map(|m| m as u32), + } + } +} + +impl From<&OnlineAccount> for Account { + fn from(a: &OnlineAccount) -> Self { + Account { + platform: a.site.into(), + username: a.username.clone(), + games: a.games, + months: a.months.map(|m| m as usize), + } + } +} + +/// What went wrong talking to a site. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum OnlineProblem { + /// No answer (offline, a timeout). + Network, + /// The site asks for a pause: too many requests. + RateLimited, + /// An answer this version does not understand (the site changed). + Unexpected, + /// The database could not be written (the phone is full). + Disk, + /// The database is being downloaded already. + Busy, +} + +/// A problem, the site it came from (when known), and the technical text. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct OnlineFailure { + pub problem: OnlineProblem, + pub site: Option, + pub detail: String, +} + +fn failure(e: &Failure, site: Option) -> OnlineFailure { + let problem = match e { + Failure::Network(_) => OnlineProblem::Network, + Failure::RateLimited => OnlineProblem::RateLimited, + Failure::Unexpected(_) => OnlineProblem::Unexpected, + Failure::Disk(_) => OnlineProblem::Disk, + Failure::Busy => OnlineProblem::Busy, + }; + OnlineFailure { + problem, + site, + detail: e.to_string(), + } +} + +/// What looking a nickname up on a site gave. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum AccountLookup { + Found { account: OnlineAccount }, + NotFound, + Failed { failure: OnlineFailure }, +} + +/// A nickname both sites could have: 2–30 letters, digits, `_` or `-`. +#[uniffi::export] +pub fn valid_nickname(nick: String) -> bool { + online_games::valid_nick(nick.trim()) +} + +/// Looks the nickname up on the site (blocks: it asks the site). +#[uniffi::export] +pub fn find_account(site: Site, nick: String) -> AccountLookup { + match online_games::lookup(site.into(), &nick) { + Lookup::Found(a) => AccountLookup::Found { + account: (&a).into(), + }, + Lookup::NotFound => AccountLookup::NotFound, + Lookup::Failed(e) => AccountLookup::Failed { + failure: failure(&e, Some(site)), + }, + } +} + +/// Accounts and the database file they are downloaded into. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct OnlineTarget { + pub accounts: Vec, + pub path: String, + /// The file is there already (its new games are fetched). + pub exists: bool, +} + +/// Where the found accounts go in `dir`: all into one database (`together`) or each into +/// its own; a database already holding them is kept. +#[uniffi::export] +pub fn online_targets( + dir: String, + accounts: Vec, + together: bool, +) -> Vec { + let accounts: Vec = accounts.iter().map(Into::into).collect(); + online_games::targets(Path::new(&dir), &accounts, together) + .into_iter() + .map(|(group, path)| OnlineTarget { + accounts: group.iter().map(Into::into).collect(), + exists: path.exists(), + path: path.to_string_lossy().into_owned(), + }) + .collect() +} + +/// What a downloaded database holds. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct OnlineDatabase { + pub accounts: Vec, + /// Games written into it. + pub games: u64, + /// When the last download finished (Unix seconds); none while it never finished. + pub updated: Option, +} + +/// The state of the database at `path`, when it is a downloaded one. +#[uniffi::export] +pub fn online_database(path: String) -> Option { + let s = State::load(Path::new(&path))?; + Some(OnlineDatabase { + accounts: s.accounts().iter().map(Into::into).collect(), + games: s.games, + updated: s.updated, + }) +} + +/// Deletes a downloaded database and the files beside it (its state). +#[uniffi::export] +pub fn delete_online_database(path: String) { + let p = PathBuf::from(path); + for f in [ + p.clone(), + p.with_extension("online.json"), + p.with_extension("online.lock"), + ] { + let _ = std::fs::remove_file(f); + } +} + +/// How a download stands. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct DownloadState { + pub running: bool, + /// The account being fetched (an index into the download's accounts). + pub account: u32, + /// Games of that account so far. + pub account_games: u64, + /// Games added by this download so far. + pub added: u64, + /// Chess.com: months done of all. + pub months_done: u32, + pub months_total: u32, + /// When it has ended: the games added and in the database now; stopped by the user. + pub total: Option, + pub cancelled: bool, + pub failure: Option, +} + +struct Shared { + progress: AtomicUsize, + status: Progress, + cancel: AtomicBool, + result: Mutex>>, +} + +/// A download of accounts into one database. +#[derive(uniffi::Object)] +pub struct OnlineDownload { + shared: Arc, +} + +#[uniffi::export] +impl OnlineDownload { + /// Starts fetching the games of `accounts` new since the last time into the database + /// at `path` (created when it is not there). Returns at once. + #[uniffi::constructor] + pub fn start(accounts: Vec, path: String) -> Arc { + let shared = Arc::new(Shared { + progress: AtomicUsize::new(0), + status: Progress::default(), + cancel: AtomicBool::new(false), + result: Mutex::new(None), + }); + let work = shared.clone(); + let accounts: Vec = accounts.iter().map(Into::into).collect(); + let spawned = std::thread::Builder::new() + .name("online-download".into()) + .spawn(move || { + let r = online_games::download( + &accounts, + Path::new(&path), + &work.progress, + &work.cancel, + &work.status, + ); + // The account being fetched when it failed: the site to name. + let site = accounts + .get(work.status.account.load(Ordering::Relaxed)) + .map(|a| a.platform.into()); + *lock(&work.result) = Some(r.map_err(|e| failure(&e, site))); + }); + if let Err(e) = spawned { + *lock(&shared.result) = Some(Err(OnlineFailure { + problem: OnlineProblem::Disk, + site: None, + detail: e.to_string(), + })); + } + Arc::new(OnlineDownload { shared }) + } + + /// Stops it soon; what was fetched is kept. + pub fn cancel(&self) { + self.shared.cancel.store(true, Ordering::Relaxed); + } + + pub fn state(&self) -> DownloadState { + let s = &self.shared; + let result = lock(&s.result).clone(); + let (total, cancelled, failure) = match &result { + Some(Ok(d)) => (Some(d.total), d.cancelled, None), + Some(Err(f)) => (None, false, Some(f.clone())), + None => (None, false, None), + }; + DownloadState { + running: result.is_none(), + account: s.status.account.load(Ordering::Relaxed) as u32, + account_games: s.status.games.load(Ordering::Relaxed) as u64, + added: result + .as_ref() + .and_then(|r| r.as_ref().ok()) + .map_or(s.progress.load(Ordering::Relaxed) as u64, |d| d.added), + months_done: s.status.months_done.load(Ordering::Relaxed) as u32, + months_total: s.status.months_total.load(Ordering::Relaxed) as u32, + total, + cancelled, + failure, + } + } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nicknames_and_targets() { + assert!(valid_nickname(" Magnus_C-1 ".into())); + assert!(!valid_nickname("../etc".into())); + let dir = std::env::temp_dir().join(format!("mobile-online-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let li = OnlineAccount { + site: Site::Lichess, + username: "Magnus".into(), + games: Some(10), + months: None, + }; + let cc = OnlineAccount { + site: Site::ChessCom, + username: "magnus".into(), + games: None, + months: Some(3), + }; + let d = dir.to_string_lossy().into_owned(); + let one = online_targets(d.clone(), vec![li.clone(), cc.clone()], true); + assert_eq!(one.len(), 1); + assert!(one[0].path.ends_with("Magnus (Lichess + Chess.com).pgn")); + assert!(!one[0].exists); + let two = online_targets(d, vec![li, cc], false); + assert_eq!(two.len(), 2); + assert!(online_database(two[0].path.clone()).is_none()); + } + + #[test] + fn a_download_that_cannot_write_says_so() { + // A folder that cannot be made: the download ends with a disk problem. + let acc = OnlineAccount { + site: Site::Lichess, + username: "someone".into(), + games: None, + months: None, + }; + let d = OnlineDownload::start(vec![acc], "/proc/cp-no-such-dir/db.pgn".into()); + let mut s = d.state(); + for _ in 0..100 { + if !s.running { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + s = d.state(); + } + assert!(!s.running); + assert_eq!(s.failure.map(|f| f.problem), Some(OnlineProblem::Disk)); + assert_eq!(s.total, None); + } +} diff --git a/crates/mobile-api/src/play.rs b/crates/mobile-api/src/play.rs new file mode 100644 index 0000000..2862142 --- /dev/null +++ b/crates/mobile-api/src/play.rs @@ -0,0 +1,504 @@ +//! A game against the computer on the phone (docs/design/android-play.md §31, +//! android-rodent.md): Maia's small model (5M) chooses her moves at a strength of her +//! own scale, by the same tables and rule as on the desktop (`maia::strength`); Rodent IV +//! plays in a style, as on the desktop (`play::rodent`). No clocks on the phone. + +use std::sync::Arc; + +use maia::strength::choose; +use shakmaty::{CastlingMode, Chess}; + +use std::sync::Mutex; + +use crate::ApiError; +use crate::session::GameSession; + +/// How a game stands at a position: over or not. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum GameEnding { + /// The side named won by mate. + Checkmate { + white_won: bool, + }, + Stalemate, + InsufficientMaterial, + Threefold, + FiftyMoves, +} + +#[uniffi::export] +impl GameSession { + /// How the game stands at the move at place `at` (its line from the start counts + /// for repetitions); none while it goes on. + pub fn ending(&self, at: u32) -> Option { + let line = self.read(|g| { + let id = crate::order(g).get(at as usize).copied()?; + Some( + g.path(id) + .iter() + .filter_map(|n| g.position(*n).cloned()) + .collect::>(), + ) + })?; + Some(match ::play::ending(&line)? { + ::play::Ending::Checkmate { winner } => GameEnding::Checkmate { + white_won: winner == shakmaty::Color::White, + }, + ::play::Ending::Stalemate => GameEnding::Stalemate, + ::play::Ending::InsufficientMaterial => GameEnding::InsufficientMaterial, + ::play::Ending::Threefold => GameEnding::Threefold, + ::play::Ending::FiftyMoves => GameEnding::FiftyMoves, + // No clocks and no resignations here: the app knows those itself. + ::play::Ending::Time { .. } + | ::play::Ending::Resigned { .. } + | ::play::Ending::DrawAgreed => return None, + }) + } +} + +/// How long the computer "thinks" before its move `ply` of an untimed game +/// (milliseconds): as a person would, quicker with one legal move. +#[uniffi::export] +pub fn move_pause_ms(ply: u32, only_move: bool) -> u64 { + ::play::pause(None, ply as usize, only_move).as_millis() as u64 +} + +/// Who plays against the user. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum Rival { + Maia, + /// Rodent IV in a style of its list (`iv_tal`…). + Rodent { + style_id: String, + }, +} + +/// The opponent as the game's record names it: «Maia 1500», «Rodent IV 1800 (Tal)». +#[uniffi::export] +pub fn rival_name(rival: Rival, strength: u32) -> String { + match rival { + Rival::Maia => format!("Maia {strength}"), + Rival::Rodent { style_id } => { + ::play::rodent::name(strength, ::play::rodent::iv_style(&style_id).id) + } + } +} + +/// The opponent as the app shows it, without the style: «Maia 1500», «Rodent IV 1800». +#[uniffi::export] +pub fn rival_label(rival: Rival, strength: u32) -> String { + match rival { + Rival::Maia => format!("Maia {strength}"), + Rival::Rodent { style_id } => format!( + "{} {strength}", + ::play::rodent::iv_style(&style_id).rodent.name() + ), + } +} + +/// The tags of a game against the computer on the phone (no clocks): `event` in the +/// app's language; the user plays White when `user_white`. +#[uniffi::export] +pub fn computer_game_tags( + event: String, + user_white: bool, + user_name: String, + rival: Rival, + strength: u32, +) -> Vec { + let user = if user_white { + shakmaty::Color::White + } else { + shakmaty::Color::Black + }; + ::play::game_tags( + &event, + user, + &user_name, + None, + &rival_name(rival, strength), + "-", + ) + .into_iter() + .map(|(name, value)| crate::Tag { name, value }) + .collect() +} + +/// Maia's turns in a row with her position hopeless before she offers to resign. +#[uniffi::export] +pub fn hopeless_turns() -> u32 { + ::play::HOPELESS_TURNS +} + +/// Stockfish judging the positions where Maia is to move (unseen by the user), for her +/// resignation; one for the whole game. +#[derive(uniffi::Object)] +pub struct ResignJudge { + judge: Mutex<::play::Judge>, +} + +#[uniffi::export] +impl ResignJudge { + /// The engine at `path` with its network `eval_file`. + #[uniffi::constructor] + pub fn start(path: String, eval_file: String) -> Arc { + let config = uci::EngineConfig { + nice: 10, + ..uci::EngineConfig::new(path) + }; + let options = if eval_file.is_empty() { + Vec::new() + } else { + vec![("EvalFile".to_owned(), eval_file)] + }; + Arc::new(ResignJudge { + judge: Mutex::new(::play::Judge::start(config, options, Box::new(|| {}))), + }) + } + + /// Judges the position at place `at` of the game (Maia to move there). + pub fn ask(&self, game: Arc, at: u32) { + let pos = game.read(|g| { + let id = crate::order(g).get(at as usize).copied()?; + g.engine_history(id) + }); + if let Some(h) = pos { + let p = match h.start_fen { + None => uci::EnginePosition::startpos(h.moves), + Some(fen) => uci::EnginePosition::fen(fen, h.moves), + }; + self.judge.lock().unwrap_or_else(|e| e.into_inner()).ask(p); + } + } + + /// Whether the position asked last is hopeless for Maia, once the answer came. + pub fn hopeless(&self) -> Option { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .answer() + .map(::play::hopeless) + } + + /// Drops the request in flight (its position is gone). + pub fn forget(&self) { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .forget(); + } + + /// Moves were taken back: the scores of Maia's turns gone are forgotten. + pub fn forget_scores(&self) { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .forget_scores(); + } + + /// A draw may be offered now (not right after a refusal). + pub fn may_offer_draw(&self) -> bool { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .may_offer_draw() + } + + /// The user offers a draw: whether Maia accepts (the shared rule, `play::accepts_draw`). + pub fn offer_draw(&self) -> bool { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .offer_draw() + } +} + +/// The strengths Maia plays on her own scale, as on the desktop: (weakest, strongest). +#[uniffi::export] +pub fn maia_range() -> Vec { + vec![::play::MAIA_MIN, ::play::MAIA_MAX] +} + +/// Maia, loaded once for a game. +#[derive(uniffi::Object)] +pub struct MaiaPlayer { + maia: maia::Maia, +} + +#[uniffi::export] +impl MaiaPlayer { + /// Reads the weights (`maia3-5m.pt`). + #[uniffi::constructor] + pub fn load(path: String) -> Result, ApiError> { + let maia = + maia::Maia::load(std::path::Path::new(&path)).map_err(|e| ApiError::Corrupt { + detail: e.to_string(), + })?; + Ok(Arc::new(MaiaPlayer { maia })) + } + + /// Maia's move (UCI) in the position at place `at` of the game, playing at + /// `strength` against a player rated `opponent` (her own strength when unknown). + /// `random` is in [0, 1). None when the game is over there. + pub fn choose( + &self, + game: Arc, + at: u32, + strength: u32, + opponent: Option, + random: f32, + ) -> Option { + let history: Vec = game.read(|g| { + let id = crate::order(g).get(at as usize).copied()?; + Some( + g.path(id) + .iter() + .filter_map(|n| g.position(*n).cloned()) + .collect(), + ) + })?; + let strength = strength.clamp(::play::MAIA_MIN, ::play::MAIA_MAX); + let p = self + .maia + .predict(&history, strength, opponent.unwrap_or(strength)); + choose(&p, 1.0, random).map(|m| m.to_uci(CastlingMode::Standard).to_string()) + } +} + +// ----- Rodent IV --------------------------------------------------------------------- + +/// A character of Rodent IV: its id, its English name (for PGN), its title and what it +/// does (English: the app shows its own translations), a great player or not. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct RodentStyle { + pub id: String, + pub name: String, + pub title: String, + pub about: String, + pub player: bool, +} + +/// Rodent IV's characters (the desktop's list; Rodent V is not on the phone). +#[uniffi::export] +pub fn rodent_styles() -> Vec { + use ::play::rodent::{Gen, STYLES}; + STYLES + .iter() + .filter(|s| s.rodent == Gen::IV) + .map(|s| RodentStyle { + id: s.id.to_owned(), + name: s.name.to_owned(), + title: s.title().to_owned(), + about: s.about.to_owned(), + player: s.player, + }) + .collect() +} + +/// The strengths Rodent IV plays (its UCI_Elo): (weakest, strongest). +#[uniffi::export] +pub fn rodent_range() -> Vec { + let (lo, hi) = ::play::rodent::Gen::IV.range(); + vec![lo, hi] +} + +/// The version of Rodent IV's files (the authors' commit): the personalities copied out +/// of the APK are copied again when it changes. +#[uniffi::export] +pub fn rodent_version() -> String { + ::play::rodent::COMMIT.to_owned() +} + +/// A file of the book pack: where it comes from, where it goes (under the engine's +/// home), its size and SHA-256. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct RodentBook { + pub url: String, + pub local: String, + pub size: u64, + pub sha256: String, +} + +/// The opening books Rodent IV's characters open, downloaded as one pack +/// (android-rodent.md §5). +#[uniffi::export] +pub fn rodent_book_pack() -> Vec { + ::play::rodent::book_pack() + .into_iter() + .map(|b| RodentBook { + url: ::play::rodent::file_url(b.file), + local: b.local, + size: b.size, + sha256: b.sha256.to_owned(), + }) + .collect() +} + +/// Rodent IV playing one game (a UCI child process, the shared crate's player). +#[derive(uniffi::Object)] +pub struct RodentPlayer { + player: ::play::rodent::RodentPlayer, +} + +#[uniffi::export] +impl RodentPlayer { + /// The engine at `exe` with its personalities and books in `home`, playing + /// `style_id` at `strength` (its UCI_Elo), with its opening book when `use_book`. + /// It starts in the background: a failure is told by [`RodentPlayer::failure`]. + #[uniffi::constructor] + pub fn start( + exe: String, + home: String, + style_id: String, + strength: u32, + use_book: bool, + ) -> Arc { + // Below the app (nice 10), as the analysis: the interface comes first. The + // engine finds its files by RODENT4HOME (packaging/rodent-iv/android.patch). + let config = uci::EngineConfig { + working_dir: Some(home.clone().into()), + nice: 10, + env: vec![("RODENT4HOME".into(), home.into())], + ..uci::EngineConfig::new(exe) + }; + Arc::new(RodentPlayer { + player: ::play::rodent::RodentPlayer::start( + config, + ::play::rodent::iv_style(&style_id).id, + Some(strength), + use_book, + Box::new(|| {}), + ), + }) + } + + /// Rodent's move (UCI) in the position at place `at` of the game, given after + /// `pause_ms` (it thinks meanwhile). Blocks: called off the main thread. None when + /// the game is over there, a newer request or `forget` passed it over, or Rodent + /// failed. + pub fn choose(&self, game: Arc, at: u32, pause_ms: u64) -> Option { + let (history, now) = game.read(|g| { + let id = crate::order(g).get(at as usize).copied()?; + Some((g.engine_history(id)?, g.position(id)?.clone())) + })?; + let pos = match history.start_fen { + None => uci::EnginePosition::startpos(history.moves), + Some(fen) => uci::EnginePosition::fen(fen, history.moves), + }; + let generation = self + .player + .ask(pos, now, std::time::Duration::from_millis(pause_ms)); + let (m, _) = self.player.wait(generation)?; + m.map(|m| m.to_uci(CastlingMode::Standard).to_string()) + } + + /// Drops the request in flight (its position is gone): its `choose` returns none. + pub fn forget(&self) { + self.player.forget(); + } + + /// Why Rodent does not play, if it does not. + pub fn failure(&self) -> Option { + use ::play::rodent::Failure; + self.player.failure().map(|f| match f { + Failure::Start(detail) => RodentFailure::DidNotStart { detail }, + // A search not taken: the process is gone in the middle of the game. + Failure::Stopped | Failure::Search(_) => RodentFailure::Stopped, + }) + } +} + +/// Why Rodent does not play: it did not start (the engine's words), or it stopped +/// during the game (android-rodent.md §6.6). +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum RodentFailure { + DidNotStart { detail: String }, + Stopped, +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Needs the weights: `MAIA_WEIGHTS=/path/maia3-5m.pt cargo test -p mobile-api -- --ignored`. + #[test] + #[ignore = "needs the weights file (MAIA_WEIGHTS)"] + fn maia_answers_with_a_legal_move() { + let path = std::env::var("MAIA_WEIGHTS").expect("MAIA_WEIGHTS"); + let m = MaiaPlayer::load(path).unwrap(); + let s = GameSession::from_pgn("1. e4 *".into()).unwrap(); + let e4 = s.data().nodes.iter().find(|n| n.san == "e4").unwrap().id; + let uci = m.choose(s.clone(), e4, 1500, None, 0.3).unwrap(); + assert!(s.legal_moves(e4).contains(&uci), "{uci}"); + let mated = GameSession::from_pgn("1. f3 e5 2. g4 Qh4# *".into()).unwrap(); + let end_id = mated + .data() + .nodes + .iter() + .find(|n| n.san == "Qh4#") + .unwrap() + .id; + assert_eq!( + mated.ending(end_id), + Some(GameEnding::Checkmate { white_won: false }) + ); + assert_eq!(mated.ending(0), None); + let end = mated + .data() + .nodes + .iter() + .find(|n| n.san == "Qh4#") + .unwrap() + .id; + assert!(m.choose(mated, end, 1500, None, 0.3).is_none()); + } + + #[test] + fn rodent_is_named_and_listed_as_on_the_desktop() { + let tags = computer_game_tags( + "Game".into(), + true, + "Roman".into(), + Rival::Rodent { + style_id: "iv_tal".into(), + }, + 1800, + ); + let black = tags.iter().find(|t| t.name == "Black").unwrap(); + assert_eq!(black.value, "Rodent IV 1800 (Tal)"); + assert_eq!(rival_name(Rival::Maia, 1500), "Maia 1500"); + let tal = Rival::Rodent { + style_id: "iv_tal".into(), + }; + assert_eq!(rival_label(tal, 1800), "Rodent IV 1800"); + let styles = rodent_styles(); + assert_eq!(styles.len(), 35); + assert_eq!(styles.iter().filter(|s| s.player).count(), 22); + assert_eq!(rodent_range(), vec![800, 2800]); + let pack = rodent_book_pack(); + assert!( + pack.iter() + .all(|b| b.url.starts_with("https://raw.githubusercontent.com/") + && b.local.starts_with("books/") + && b.sha256.len() == 64) + ); + } + + /// Needs Rodent IV beside its files: `RODENT4=/path/rodent_iv cargo test -p mobile-api -- --ignored`. + #[test] + #[ignore = "needs Rodent IV (RODENT4)"] + fn rodent_answers_with_a_legal_move() { + let exe = std::env::var("RODENT4").expect("RODENT4"); + let home = std::path::Path::new(&exe) + .parent() + .unwrap() + .display() + .to_string(); + let r = RodentPlayer::start(exe, home, "iv_karpov".into(), 1600, false); + let s = GameSession::from_pgn("1. e4 *".into()).unwrap(); + let e4 = s.data().nodes.iter().find(|n| n.san == "e4").unwrap().id; + let uci = r.choose(s.clone(), e4, 300).expect("a move"); + assert!(s.legal_moves(e4).contains(&uci), "{uci}"); + assert_eq!(r.failure(), None); + } +} diff --git a/crates/mobile-api/src/prep.rs b/crates/mobile-api/src/prep.rs new file mode 100644 index 0000000..d373f96 --- /dev/null +++ b/crates/mobile-api/src/prep.rs @@ -0,0 +1,812 @@ +//! Simple opponent preparation: exact players, their games on one colour, and the +//! continuations from the first main-line occurrence of a position. Searches run on +//! one worker per database and never start an engine or change the source database. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use chess_core::StartPosition; +use chess_import::chessbase::base::{Filter, NameFilter, Side, SortKey}; +use chess_import::position::{GameResult, PositionOutcome, PositionQuery}; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, Position, san::SanPlus}; + +use crate::{ApiError, Database, GameRow}; + +/// Keeps a search response bounded even when the position occurs in a whole book. +const MATCH_LIMIT: usize = 100; +const SUGGESTION_LIMIT: u32 = 200; + +/// One exact player name from the database catalogue. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct PlayerSuggestion { + /// Stable within this open database; used by [`Database::prepare_position`]. + pub id: u32, + pub name: String, + /// Distinct games. A game with this name on both sides counts once here. + pub games: u32, + pub white_games: u32, + pub black_games: u32, +} + +/// A page of [`PlayerSuggestion`] and the total number of matching names. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct PlayerSuggestions { + pub players: Vec, + pub total: u32, +} + +/// A move played next, with the selected player's results (not the mover's). +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct PrepContinuation { + pub uci: String, + pub san: String, + pub count: u32, + pub wins: u32, + pub draws: u32, + pub losses: u32, + /// Games with `Result "*"` (or another unknown result); not a loss. + pub unknown: u32, +} + +/// One matching game. `ply` opens its first main-line occurrence of the position. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct PrepMatch { + pub index: u32, + pub ply: u32, + pub row: GameRow, +} + +/// Continuations and results at one position. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct PrepResult { + /// Matching games, each counted once at its first main-line occurrence. + pub games: u32, + pub wins: u32, + pub draws: u32, + pub losses: u32, + pub unknown: u32, + /// Whether the selected player (rather than their opponents) moves here. + pub player_to_move: bool, + /// By count descending, then SAN ascending. + pub continuations: Vec, + pub ended: u32, + /// A teaching null move or a continuation that is not a normal legal move. + pub no_normal_continuation: u32, + /// At most 100 rows in record order; `matches_total` is the unpaginated count. + pub matches: Vec, + pub matches_total: u32, +} + +/// The phase of a [`PrepSearch`]. Terminal phases are `Ready`, `Cancelled`, +/// `NoMemory` and `Failed`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum PrepPhase { + Games, + Index, + Search, + Ready, + Cancelled, + NoMemory, + Failed, +} + +/// A snapshot of a preparation worker. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct PrepState { + pub phase: PrepPhase, + /// Progress inside the current phase (`total == 0` means not applicable). + pub done: u32, + pub total: u32, + pub running: bool, + pub result: Option, + /// Empty except for `Failed` and `NoMemory`. + pub failure: String, +} + +#[derive(Clone, Default)] +struct Score { + count: u32, + wins: u32, + draws: u32, + losses: u32, + unknown: u32, +} + +impl Score { + fn add(&mut self, result: &str, selected_white: bool) { + self.count = self.count.saturating_add(1); + match GameResult::from_tag(result) { + GameResult::WhiteWins => { + if selected_white { + self.wins = self.wins.saturating_add(1); + } else { + self.losses = self.losses.saturating_add(1); + } + } + GameResult::BlackWins => { + if selected_white { + self.losses = self.losses.saturating_add(1); + } else { + self.wins = self.wins.saturating_add(1); + } + } + GameResult::Draw => self.draws = self.draws.saturating_add(1), + GameResult::Unknown => self.unknown = self.unknown.saturating_add(1), + } + } +} + +#[derive(Clone)] +struct Snapshot { + phase: PrepPhase, + total: u32, + result: Option, + failure: String, +} + +pub(crate) struct Shared { + cancel: AtomicBool, + progress: AtomicUsize, + snapshot: Mutex, +} + +impl Shared { + fn new(total: usize) -> Self { + Self { + cancel: AtomicBool::new(false), + progress: AtomicUsize::new(0), + snapshot: Mutex::new(Snapshot { + phase: PrepPhase::Games, + total: as_u32(total), + result: None, + failure: String::new(), + }), + } + } + + fn phase(&self, phase: PrepPhase, total: usize) { + if self.cancel.load(Ordering::Relaxed) { + return; + } + self.progress.store(0, Ordering::Relaxed); + let mut snapshot = lock(&self.snapshot); + snapshot.phase = phase; + snapshot.total = as_u32(total); + } + + fn ready(&self, result: PrepResult) { + if self.cancel.load(Ordering::Relaxed) { + self.cancelled(); + return; + } + let mut snapshot = lock(&self.snapshot); + self.progress + .store(snapshot.total as usize, Ordering::Relaxed); + snapshot.phase = PrepPhase::Ready; + snapshot.result = Some(result); + } + + fn cancelled(&self) { + let mut snapshot = lock(&self.snapshot); + if matches!( + snapshot.phase, + PrepPhase::Games | PrepPhase::Index | PrepPhase::Search + ) { + snapshot.phase = PrepPhase::Cancelled; + snapshot.result = None; + } + } + + fn failed(&self, phase: PrepPhase, failure: String) { + if self.cancel.load(Ordering::Relaxed) { + self.cancelled(); + return; + } + let mut snapshot = lock(&self.snapshot); + snapshot.phase = phase; + snapshot.failure = failure; + snapshot.result = None; + } + + fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + self.cancelled(); + } + + fn state(&self) -> PrepState { + let snapshot = lock(&self.snapshot).clone(); + let running = matches!( + snapshot.phase, + PrepPhase::Games | PrepPhase::Index | PrepPhase::Search + ); + PrepState { + phase: snapshot.phase, + done: as_u32( + self.progress + .load(Ordering::Relaxed) + .min(snapshot.total as usize), + ), + total: snapshot.total, + running, + result: snapshot.result, + failure: snapshot.failure, + } + } +} + +/// One running or finished position search. Dropping it requests cancellation. +#[derive(uniffi::Object)] +pub struct PrepSearch { + shared: Arc, +} + +#[uniffi::export] +impl PrepSearch { + pub fn state(&self) -> PrepState { + self.shared.state() + } + + /// Stops soon; an old worker cannot publish its result afterwards. + pub fn cancel(&self) { + self.shared.cancel(); + } +} + +impl Drop for PrepSearch { + fn drop(&mut self) { + self.shared.cancel(); + } +} + +impl Drop for Database { + fn drop(&mut self) { + if let Some(shared) = lock(&self.prep).as_ref().and_then(|old| old.upgrade()) { + shared.cancel(); + } + } +} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn as_u32(n: usize) -> u32 { + u32::try_from(n).unwrap_or(u32::MAX) +} + +#[uniffi::export] +impl Database { + /// Exact-name suggestions, `count` at most 200. An empty query lists all named + /// players alphabetically; a non-empty one keeps the catalogue's prefix/games order. + pub fn suggest_players(&self, query: String, start: u32, count: u32) -> PlayerSuggestions { + let limit = count.min(SUGGESTION_LIMIT) as usize; + let (list, total) = match self.db.as_ref() { + chess_import::Database::Pgn(db) => { + db.catalog() + .suggest_players_page(&query, start as usize, limit) + } + chess_import::Database::ChessBase(db) => { + db.suggest_players_page(&query, start as usize, limit) + } + }; + let players = list + .into_iter() + .map(|suggestion| { + let (games, white_games, black_games) = match self.db.as_ref() { + chess_import::Database::Pgn(db) => db.catalog().player_counts(suggestion.id), + chess_import::Database::ChessBase(db) => db.player_counts(suggestion.id), + }; + PlayerSuggestion { + id: suggestion.id, + name: suggestion.name, + games, + white_games, + black_games, + } + }) + .collect(); + PlayerSuggestions { + players, + total: as_u32(total), + } + } + + /// Starts preparation for an exact player and colour at `query_fen` (empty means + /// the usual initial position). Only the first main-line occurrence in each game + /// counts; transpositions count and variations in the database do not. The thread + /// is bounded to one active request per database: a new request cancels the old one. + pub fn prepare_position( + &self, + player_id: u32, + white: bool, + query_fen: String, + ) -> Result, ApiError> { + let position = parse_position(&query_fen)?; + let shared = Arc::new(Shared::new(self.db.len())); + let previous = lock(&self.prep).replace(Arc::downgrade(&shared)); + if let Some(previous) = previous.and_then(|old| old.upgrade()) { + previous.cancel(); + } + + let worker = shared.clone(); + let db = self.db.clone(); + let spawned = std::thread::Builder::new() + .name("opponent-prep".into()) + .spawn(move || run(db, player_id, white, position, worker)); + if let Err(error) = spawned { + shared.failed(PrepPhase::Failed, error.to_string()); + } + Ok(Arc::new(PrepSearch { shared })) + } +} + +fn parse_position(fen: &str) -> Result { + if fen.trim().is_empty() { + return Ok(Chess::default()); + } + StartPosition::from_fen(fen) + .map(|start| start.position().clone()) + .map_err(|error| ApiError::Edit { + detail: error.to_string(), + }) +} + +fn player_games( + db: &chess_import::Database, + player_id: u32, + white: bool, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Option> { + let side = if white { Side::White } else { Side::Black }; + match db { + chess_import::Database::Pgn(db) => { + db.catalog().player_games(player_id, side, progress, cancel) + } + chess_import::Database::ChessBase(db) => db.query( + &Filter { + player: NameFilter { + text: String::new(), + exact: Some(player_id), + }, + side, + games_only: true, + ..Filter::default() + }, + SortKey::Number, + true, + progress, + cancel, + ), + } +} + +fn run( + db: Arc, + player_id: u32, + white: bool, + position: Chess, + shared: Arc, +) { + if shared.cancel.load(Ordering::Relaxed) { + shared.cancelled(); + return; + } + // This may build the PGN catalogue; it deliberately runs here, not on the caller's + // thread. An invalid id is a failed request, not a valid empty repertoire. + if db.player_name(player_id).trim().is_empty() { + shared.failed(PrepPhase::Failed, format!("unknown player {player_id}")); + return; + } + let Some(games) = player_games(&db, player_id, white, &shared.progress, &shared.cancel) else { + shared.cancelled(); + return; + }; + if games.is_empty() { + shared.phase(PrepPhase::Search, 0); + shared.ready(result(&db, &position, white, PositionOutcome::default())); + return; + } + if let Some(needed) = db.positions_blocked() { + shared.failed( + PrepPhase::NoMemory, + format!("not enough memory for the position index ({needed} bytes needed)"), + ); + return; + } + + let preparing = !db.positions_ready(); + shared.phase( + if preparing { + PrepPhase::Index + } else { + PrepPhase::Search + }, + if preparing { db.len() } else { games.len() }, + ); + let query = PositionQuery::new(position.clone(), None); + let outcome = db.search_position_first(Some(&games), &query, &shared.progress, &shared.cancel); + match outcome { + Some(outcome) => shared.ready(result(&db, &position, white, outcome)), + None if shared.cancel.load(Ordering::Relaxed) => shared.cancelled(), + None => shared.failed( + PrepPhase::Failed, + "position search ended without a result".into(), + ), + } +} + +fn result( + db: &chess_import::Database, + position: &Chess, + selected_white: bool, + outcome: PositionOutcome, +) -> PrepResult { + let mut total = Score::default(); + let mut continuations: HashMap = HashMap::new(); + let mut ended = 0u32; + let mut no_normal = 0u32; + let mut matches = Vec::with_capacity(outcome.matches.len().min(MATCH_LIMIT)); + + for (place, found) in outcome.matches.iter().enumerate() { + let row = game_row(db, found.index); + total.add(&row.result, selected_white); + match found.next { + None => ended = ended.saturating_add(1), + Some(UciMove::Null) => no_normal = no_normal.saturating_add(1), + Some(uci) => match uci.to_move(position) { + Ok(_) => continuations + .entry(uci) + .or_default() + .add(&row.result, selected_white), + Err(_) => no_normal = no_normal.saturating_add(1), + }, + } + if place < MATCH_LIMIT { + matches.push(PrepMatch { + index: found.index, + ply: found.ply, + row, + }); + } + } + + let mut continuations: Vec = continuations + .into_iter() + .filter_map(|(uci, score)| { + let mv = uci.to_move(position).ok()?; + let san = SanPlus::from_move(position.clone(), mv).to_string(); + Some(PrepContinuation { + uci: uci.to_string(), + san, + count: score.count, + wins: score.wins, + draws: score.draws, + losses: score.losses, + unknown: score.unknown, + }) + }) + .collect(); + continuations.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.san.cmp(&b.san))); + let continuation_games = continuations.iter().fold(0u32, |sum, continuation| { + sum.saturating_add(continuation.count) + }); + debug_assert_eq!( + continuation_games + .saturating_add(ended) + .saturating_add(no_normal), + total.count + ); + PrepResult { + games: total.count, + wins: total.wins, + draws: total.draws, + losses: total.losses, + unknown: total.unknown, + player_to_move: position.turn() + == if selected_white { + Color::White + } else { + Color::Black + }, + continuations, + ended, + no_normal_continuation: no_normal, + matches_total: total.count, + matches, + } +} + +fn game_row(db: &chess_import::Database, index: u32) -> GameRow { + let row = db.row(index as usize); + let elo = |value: u16| { + if value == 0 { + String::new() + } else { + value.to_string() + } + }; + GameRow { + index, + white: row.white, + black: row.black, + result: row.result.to_owned(), + date: row.date, + event: row.event, + eco: row.eco.unwrap_or_default(), + white_elo: elo(row.white_elo), + black_elo: elo(row.black_elo), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use shakmaty::EnPassantMode; + use shakmaty::fen::Fen; + use shakmaty::san::San; + + use crate::open_bytes; + + fn database(pgn: &str) -> Arc { + open_bytes("prep.pgn".into(), pgn.as_bytes().to_vec()).expect("fixture opens") + } + + fn fen(line: &[&str]) -> String { + let mut position = Chess::default(); + for san in line { + let mv = san + .parse::() + .expect("fixture SAN") + .to_move(&position) + .expect("legal fixture move"); + position.play_unchecked(mv); + } + Fen::from_position(&position, EnPassantMode::Legal).to_string() + } + + fn player(db: &Database, name: &str) -> PlayerSuggestion { + db.suggest_players(name.into(), 0, SUGGESTION_LIMIT) + .players + .into_iter() + .find(|player| player.name == name) + .expect("exact fixture player") + } + + fn search(db: &Database, player_id: u32, white: bool, fen: String) -> PrepState { + let search = db + .prepare_position(player_id, white, fen) + .expect("search starts"); + for _ in 0..1000 { + let state = search.state(); + if !state.running { + return state; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("preparation did not finish") + } + + fn ready(state: PrepState) -> PrepResult { + assert_eq!(state.phase, PrepPhase::Ready, "{}", state.failure); + assert_eq!(state.done, state.total); + state.result.expect("ready result") + } + + #[test] + fn suggestions_are_paged_normalized_and_count_each_colour() { + let db = database(concat!( + "[White \"Vafin Radel\"][Black \"Other A\"][Result \"1-0\"]\n\n1. e4 c5 1-0\n\n", + "[White \"Other B\"][Black \"Vafin Radel\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n", + "[White \"Vafin Radel\"][Black \"Vafin Radel\"][Result \"0-1\"]\n\n1. e4 e5 0-1\n\n", + "[White \"Vafina Rayana\"][Black \"Other C\"][Result \"*\"]\n\n1. e4 c5 *\n", + )); + let first = db.suggest_players("vafin".into(), 0, 1); + assert_eq!(first.total, 2); + assert_eq!(first.players.len(), 1); + let vafin = &first.players[0]; + assert_eq!(vafin.name, "Vafin Radel"); + assert_eq!( + (vafin.games, vafin.white_games, vafin.black_games), + (3, 2, 2) + ); + let second = db.suggest_players("vafin".into(), 1, 1); + assert_eq!(second.players[0].name, "Vafina Rayana"); + assert!(db.suggest_players("vafin".into(), 2, 1).players.is_empty()); + let all = db.suggest_players(String::new(), 0, 200); + assert_eq!(all.total, 5); + assert!( + all.players + .windows(2) + .all(|pair| pair[0].name <= pair[1].name) + ); + + let after_e4 = fen(&["e4"]); + let white = ready(search(&db, vafin.id, true, after_e4.clone())); + assert_eq!((white.games, white.wins, white.losses), (2, 1, 1)); + assert_eq!( + white.matches.iter().map(|m| m.index).collect::>(), + [0, 2] + ); + let black = ready(search(&db, vafin.id, false, after_e4)); + assert_eq!((black.games, black.wins, black.losses), (2, 2, 0)); + assert_eq!( + black.matches.iter().map(|m| m.index).collect::>(), + [1, 2] + ); + } + + #[test] + fn first_main_line_occurrence_wins_over_repetition_and_rav() { + let db = database(concat!( + "[White \"Repeat\"][Black \"X\"][Result \"1-0\"]\n\n", + "1. Nf3 (1. e4 e5) Nf6 2. Ng1 Ng8 3. d4 d5 1-0\n", + )); + let id = player(&db, "Repeat").id; + let result = ready(search(&db, id, true, fen(&[]))); + assert_eq!(result.games, 1); + assert_eq!(result.matches[0].ply, 0); + assert_eq!(result.continuations.len(), 1); + assert_eq!(result.continuations[0].san, "Nf3"); + assert_eq!(result.continuations[0].count, 1); + assert_eq!(result.ended, 0); + + let db = database(concat!( + "[White \"Main\"][Black \"X\"][Result \"1-0\"]\n\n", + "1. e4 c5 (1... e5) 2. Nf3 1-0\n\n", + "[White \"Main\"][Black \"X\"][Result \"0-1\"]\n\n", + "1. e4 e5 (1... c5 2. Nf3) 2. Nf3 0-1\n", + )); + let id = player(&db, "Main").id; + let result = ready(search(&db, id, true, fen(&["e4", "c5"]))); + assert_eq!( + result.games, 1, + "a RAV-only occurrence is not a played game" + ); + assert_eq!(result.matches[0].index, 0); + assert_eq!(result.matches[0].ply, 2); + assert_eq!(result.continuations.len(), 1); + assert_eq!(result.continuations[0].san, "Nf3"); + assert_eq!((result.wins, result.losses), (1, 0)); + } + + #[test] + fn transpositions_have_the_same_games_and_continuations() { + let db = database(concat!( + "[White \"T\"][Black \"X\"][Result \"1-0\"]\n\n1. Nf3 d5 2. d4 e6 1-0\n\n", + "[White \"T\"][Black \"X\"][Result \"0-1\"]\n\n1. d4 d5 2. Nf3 c6 0-1\n", + )); + let id = player(&db, "T").id; + let a = ready(search(&db, id, true, fen(&["Nf3", "d5", "d4"]))); + let b = ready(search(&db, id, true, fen(&["d4", "d5", "Nf3"]))); + assert_eq!(a, b); + assert_eq!(a.games, 2); + assert_eq!(a.matches.iter().map(|m| m.ply).collect::>(), [3, 3]); + assert_eq!( + a.continuations + .iter() + .map(|m| m.san.as_str()) + .collect::>(), + ["c6", "e6"] + ); + assert_eq!((a.wins, a.losses), (1, 1)); + } + + #[test] + fn continuation_results_belong_to_the_selected_player() { + let db = database(concat!( + "[White \"W1\"][Black \"B\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n", + "[White \"W2\"][Black \"B\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n", + "[White \"W3\"][Black \"B\"][Result \"1-0\"]\n\n1. e4 c5 1-0\n\n", + "[White \"W4\"][Black \"B\"][Result \"*\"]\n\n1. e4 c5 *\n", + )); + let id = player(&db, "B").id; + let result = ready(search(&db, id, false, fen(&["e4"]))); + assert_eq!( + ( + result.games, + result.wins, + result.draws, + result.losses, + result.unknown + ), + (4, 2, 0, 1, 1) + ); + let c5 = &result.continuations[0]; + assert_eq!(c5.san, "c5"); + assert_eq!( + (c5.count, c5.wins, c5.draws, c5.losses, c5.unknown), + (4, 2, 0, 1, 1) + ); + assert!( + result.player_to_move, + "Black moves after 1.e4, so the selected player moves here" + ); + } + + #[test] + fn a_fen_game_starts_at_ply_zero_with_black_to_move() { + let query = "8/3k4/8/3K4/3P4/8/8/8 b - - 0 0"; + let pgn = format!( + "[White \"X\"][Black \"FEN player\"][Result \"*\"][SetUp \"1\"][FEN \"{query}\"]\n\n1... Kc7 *\n" + ); + let db = database(&pgn); + let id = player(&db, "FEN player").id; + let result = ready(search(&db, id, false, query.into())); + assert_eq!(result.games, 1); + assert_eq!(result.matches[0].ply, 0); + assert_eq!(result.continuations[0].san, "Kc7"); + assert!(result.player_to_move); + assert_eq!( + (result.wins, result.draws, result.losses, result.unknown), + (0, 0, 0, 1) + ); + } + + #[test] + fn ended_and_teaching_null_moves_balance_the_game_count() { + let db = database(concat!( + "[White \"N\"][Black \"X\"][Result \"*\"]\n\n1. e4 *\n\n", + "[White \"N\"][Black \"X\"][Result \"*\"]\n\n1. e4 -- *\n", + )); + let id = player(&db, "N").id; + let result = ready(search(&db, id, true, fen(&["e4"]))); + assert_eq!(result.games, 2); + assert!(result.continuations.is_empty()); + assert_eq!(result.ended, 1); + assert_eq!(result.no_normal_continuation, 1); + assert_eq!(result.unknown, 2); + } + + #[test] + fn matches_are_bounded_and_a_new_request_cancels_the_old_one() { + let pgn = std::iter::repeat_n( + "[White \"Many\"][Black \"X\"][Result \"*\"]\n\n1. e4 *\n\n", + 105, + ) + .collect::(); + let db = database(&pgn); + let id = player(&db, "Many").id; + let first = db + .prepare_position(id, true, fen(&[])) + .expect("first starts"); + let second = db + .prepare_position(id, true, fen(&[])) + .expect("second starts"); + assert!(first.shared.cancel.load(Ordering::Relaxed)); + let mut state = second.state(); + for _ in 0..1000 { + if !state.running { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + state = second.state(); + } + let result = ready(state); + assert_eq!(result.games, 105); + assert_eq!(result.matches_total, 105); + assert_eq!(result.matches.len(), MATCH_LIMIT); + assert_eq!(result.unknown, 105); + + let cancelled = Arc::new(Shared::new(db.db.len())); + cancelled.cancel(); + run(db.db.clone(), id, true, Chess::default(), cancelled.clone()); + assert_eq!(cancelled.state().phase, PrepPhase::Cancelled); + assert!(cancelled.state().result.is_none()); + } + + #[test] + fn invalid_fen_is_an_input_error_not_a_worker_panic() { + let db = database("[White \"P\"][Black \"X\"] *\n"); + let id = player(&db, "P").id; + assert!(matches!( + db.prepare_position(id, true, "not a fen".into()), + Err(ApiError::Edit { .. }) + )); + let unknown = search(&db, u32::MAX, true, fen(&[])); + assert_eq!(unknown.phase, PrepPhase::Failed); + assert!(unknown.failure.contains("unknown player")); + } +} diff --git a/crates/mobile-api/src/review.rs b/crates/mobile-api/src/review.rs new file mode 100644 index 0000000..523a779 --- /dev/null +++ b/crates/mobile-api/src/review.rs @@ -0,0 +1,533 @@ +//! The game report for the Android app: the analysis of a game's main line by the +//! `game-review` crate (the same evaluations, judgements, accuracy and cache as on the +//! desktop), with its engine job on a thread of its own. The app starts it, asks for +//! the state while it runs, and gets everything the graph, the report and the marks in +//! the notation need, in the node numbers of [`crate::GameData`]. +//! +//! The game is never changed. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use chess_core::{Game, NodeId}; +use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, SideStats}; +use shakmaty::Color; + +use crate::EngineLine; +use crate::engine::{line_with, pawns}; + +/// How bad a move was, or that it was of note. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum MoveJudgement { + Inaccuracy, + Mistake, + Blunder, + /// The only good move, or one that turned the game (!). + Great, + /// A sound sacrifice of a piece (!!). + Brilliant, +} + +impl From for MoveJudgement { + fn from(j: Judgement) -> Self { + match j { + Judgement::Inaccuracy => MoveJudgement::Inaccuracy, + Judgement::Mistake => MoveJudgement::Mistake, + Judgement::Blunder => MoveJudgement::Blunder, + Judgement::Great => MoveJudgement::Great, + Judgement::Brilliant => MoveJudgement::Brilliant, + } + } +} + +/// A position of the main line: the start, then the one after each move. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ReviewPoint { + /// The node (of [`crate::GameData`]) of this position. + pub node: u32, + /// White's chance of winning, 0..100, when the position is evaluated. + pub white_win: Option, + /// "+0.35", "−1.20", "#3", "#−2", "1-0" ("" while not evaluated). + pub eval: String, + /// The judgement of the move that led here. + pub judgement: Option, +} + +/// One player's numbers. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct SideReview { + pub inaccuracies: u32, + pub mistakes: u32, + pub blunders: u32, + pub great: u32, + pub brilliant: u32, + /// Average centipawn loss. + pub acpl: Option, + /// Accuracy 0..100 (only when every position is evaluated). + pub accuracy: Option, + pub opening: Option, + pub middlegame: Option, + pub endgame: Option, +} + +/// A marked move of the main line: an inaccuracy, mistake or blunder, or a great or +/// brilliant move (these have no better line and no reply). +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ReviewMove { + /// The node of the move. + pub node: u32, + pub judgement: MoveJudgement, + /// White made the move. + pub white: bool, + /// The engine's line from the position before the move (its first move was + /// better), to show on the board; `None` when the evaluation came from the PGN. + pub best: Option, + /// The better move with its number, Latin letters: "23…Nf6" ("" when unknown). + pub best_label: String, + /// How the opponent punishes the move: the engine's reply, for an arrow. + pub reply_from: Option, + pub reply_to: Option, +} + +/// Everything about the analysis of the game at this moment. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ReviewState { + /// The engine job is running. + pub running: bool, + /// Positions evaluated by this run, of `total`. + pub done: u32, + pub total: u32, + /// Why the last run stopped early (the engine crashed, did not start). + pub failure: Option, + /// Some evaluations exist (from the engine, the cache or the PGN). + pub has_data: bool, + /// The engine's name; "PGN" when the evaluations come from `[%eval]` comments. + pub engine: String, + /// Nodes per position; 0 for evaluations from the PGN. + pub nodes: u64, + /// The evaluations come from another engine search than today's fixed one (an + /// analysis made before it): shown, but "update" makes them all again. + pub stale: bool, + /// Positions of the main line without an evaluation. + pub missing: u32, + /// Evaluated positions still waiting for the second search of !! and ! (an analysis + /// from before them): "fill in" does it. + pub seconds_missing: u32, + /// Positions a full analysis looks at (for the time estimate). + pub positions: u32, + /// Engine searches a full analysis is expected to make (for the time estimate: a + /// second search for moves that could be brilliant or great). + pub searches: u32, + /// The speed of one engine process in the last run (0 when unknown). + pub nps_per_process: u64, + /// The start position and the position after every main-line move. + pub points: Vec, + /// Where the middlegame and the endgame begin, as indices of `points`. + pub middlegame: Option, + pub endgame: Option, + pub white: SideReview, + pub black: SideReview, + /// The marked moves, in the order of the game. + pub moves: Vec, +} + +enum Msg { + Event(JobEvent), + Done, + Failed(String), +} + +struct Job { + rx: Receiver, + cancel: Arc, +} + +impl Drop for Job { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +struct Inner { + game: Game, + /// Node ids of the game → node numbers of [`crate::GameData`]. + places: HashMap, + analysis: GameAnalysis, + cache_dir: Option, + job: Option, + done: u32, + total: u32, + failure: Option, + nps_per_process: u64, + /// When the cache was last written: a long run is kept now and then, so that a + /// crash or a killed app loses little of it. + saved: Instant, +} + +/// How often a running analysis is written to the cache. +const SAVE_EVERY: Duration = Duration::from_secs(10); + +/// The analysis of one game. +#[derive(uniffi::Object)] +pub struct GameReview { + inner: Mutex, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, Inner> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl GameReview { + /// The analysis of `game`; earlier results come from `cache_dir` (empty: no cache). + pub(crate) fn new(game: Game, cache_dir: String) -> Arc { + let cache_dir = (!cache_dir.is_empty()).then(|| PathBuf::from(cache_dir)); + let analysis = GameAnalysis::new(&game, cache_dir.as_deref()); + Arc::new(GameReview { + inner: Mutex::new(Inner { + places: crate::places(&game), + game, + analysis, + cache_dir, + job: None, + done: 0, + total: 0, + failure: None, + nps_per_process: 0, + saved: Instant::now(), + }), + }) + } +} + +#[uniffi::export] +impl GameReview { + /// Starts the engine at `path` (with its network `eval_file`, if not empty) on the + /// positions without an evaluation, or on all of them when `full` (or when the + /// analysis is stale). The search is the fixed one of every game analysis, the same + /// as on the desktop. Returns false when there is nothing to analyse. Returns at + /// once: the engine starts on its own thread. + pub fn start(&self, path: String, eval_file: String, full: bool) -> bool { + let mut st = lock(&self.inner); + stop(&mut st); + st.failure = None; + let Inner { game, analysis, .. } = &mut *st; + let targets = analysis.begin(game, full); + if targets.is_empty() { + return false; + } + let settings = JobSettings::new( + phone_processes(), + (!eval_file.is_empty()).then_some(eval_file), + ); + // Below the app (nice 10), as the live engine: the phone stays smooth. + let config = uci::EngineConfig { + nice: 10, + ..uci::EngineConfig::new(path) + }; + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let stop = cancel.clone(); + st.total = targets.len() as u32; + st.done = 0; + let spawned = std::thread::Builder::new() + .name("game-review".into()) + .spawn(move || { + let result = game_review::run(config, &settings, targets, &stop, &mut |e| { + let _ = tx.send(Msg::Event(e)); + }); + let _ = tx.send(match result { + Ok(()) => Msg::Done, + Err(JobFailure::Start(e) | JobFailure::Engine(e)) => Msg::Failed(e), + Err(JobFailure::Terminated(reason)) => Msg::Failed(format!("{reason:?}")), + }); + }); + if let Err(e) = spawned { + st.failure = Some(e.to_string()); + return false; + } + st.job = Some(Job { rx, cancel }); + true + } + + /// Stops the engine; what it has evaluated is kept (and cached). + pub fn cancel(&self) { + stop(&mut lock(&self.inner)); + } + + /// The state now, with what the engine has said since the last call. + pub fn state(&self) -> ReviewState { + let mut st = lock(&self.inner); + drain(&mut st); + let Inner { game, analysis, .. } = &mut *st; + analysis.refresh(game); + snapshot(&st) + } +} + +impl Drop for GameReview { + fn drop(&mut self) { + // Leaving the game mid-analysis keeps what was computed. + stop(&mut lock(&self.inner)); + } +} + +/// Ends the running job, keeping every result it has sent. +fn stop(st: &mut Inner) { + if st.job.is_none() { + return; + } + drain(st); + if st.job.take().is_some() { + save(st); + } +} + +fn drain(st: &mut Inner) { + let Some(job) = &st.job else { return }; + let mut events = Vec::new(); + let mut ended = None; + while let Ok(msg) = job.rx.try_recv() { + match msg { + Msg::Event(e) => events.push(e), + Msg::Done => ended = Some(None), + Msg::Failed(e) => ended = Some(Some(e)), + } + } + let got = !events.is_empty(); + for e in events { + if let JobEvent::Eval { nps, .. } = &e { + st.done += 1; + if *nps > 0 { + st.nps_per_process = *nps; + } + } + st.analysis.apply(e); + } + if let Some(failure) = ended { + st.job = None; + st.failure = failure; + save(st); + } else if got && st.saved.elapsed() >= SAVE_EVERY { + save(st); + } +} + +/// Seconds `searches` engine searches of the game analysis take at `nps_per_process` +/// nodes per second of one engine process (measured before, or a guess), in this +/// phone's engine processes. +#[uniffi::export] +pub fn review_estimate_secs(searches: u32, nps_per_process: u64) -> u32 { + game_review::estimate_secs(searches as usize, nps_per_process as f64, phone_processes()).ceil() + as u32 +} + +/// Engine processes of a game analysis on a phone: one per core, at most +/// [`game_review::PHONE_PROCESSES`] and what the free memory holds; all below the app +/// (nice 10). +fn phone_processes() -> usize { + game_review::processes(game_review::PHONE_PROCESSES) +} + +fn save(st: &mut Inner) { + st.saved = Instant::now(); + if let Some(dir) = &st.cache_dir { + // A cache that cannot be written only means analysing again next time. + let _ = st.analysis.save_cache(dir); + } +} + +/// "+0.35", "−1.20", "#3", "#−2", "1-0". +fn eval_text(e: Eval) -> String { + match e { + Eval::Cp(cp) => pawns(cp), + Eval::Mate { white, moves: 0 } => if white { "1-0" } else { "0-1" }.into(), + Eval::Mate { white: true, moves } => format!("#{moves}"), + Eval::Mate { + white: false, + moves, + } => format!("#\u{2212}{moves}"), + } +} + +fn side(s: &SideStats) -> SideReview { + SideReview { + inaccuracies: s.inaccuracies, + mistakes: s.mistakes, + blunders: s.blunders, + great: s.great, + brilliant: s.brilliant, + acpl: s.acpl, + accuracy: s.accuracy, + opening: s.phase_accuracy[0], + middlegame: s.phase_accuracy[1], + endgame: s.phase_accuracy[2], + } +} + +fn snapshot(st: &Inner) -> ReviewState { + let a = &st.analysis; + let place = |id: NodeId| st.places.get(&id).copied().unwrap_or(0); + let line = a.line(); + let points = line + .iter() + .enumerate() + .map(|(i, id)| { + let v = a.values().get(i).copied().flatten(); + ReviewPoint { + node: place(*id), + white_win: v.map(|e| e.win_percent(Color::White) as f32), + eval: v.map(eval_text).unwrap_or_default(), + judgement: i + .checked_sub(1) + .and_then(|p| a.report.judgements.get(p).copied().flatten()) + .map(Into::into), + } + }) + .collect(); + let mut moves = Vec::new(); + for (i, id) in line.iter().enumerate().skip(1) { + let Some(mark) = a.marks.get(id) else { + continue; + }; + let best = a + .eval_at(i - 1) + .filter(|e| !e.pv.is_empty() && mark.judgement.is_error()) + .and_then(|e| { + let root = st.game.position(mark.base)?; + let (cp, mate) = match e.eval { + Eval::Cp(cp) => (Some(cp), None), + Eval::Mate { white, moves } => ( + None, + Some(if white { moves as i32 } else { -(moves as i32) }), + ), + }; + Some(line_with(root, 1, cp, mate, &e.pv)) + }); + // The reply is the first move of the engine line after the bad move. + let reply = a + .eval_at(i) + .and_then(|e| e.pv.first()) + .filter(|_| !a.refutation(*id, &st.game).is_empty()) + .filter(|u| u.len() >= 4) + .map(|u| (u[0..2].to_owned(), u[2..4].to_owned())); + moves.push(ReviewMove { + node: place(*id), + judgement: mark.judgement.into(), + white: a.movers().get(i - 1) == Some(&Color::White), + best, + best_label: mark.best_label.clone().unwrap_or_default(), + reply_from: reply.as_ref().map(|r| r.0.clone()), + reply_to: reply.map(|r| r.1), + }); + } + let meta = a.meta.clone().unwrap_or_default(); + ReviewState { + running: st.job.is_some(), + done: st.done, + total: st.total, + failure: st.failure.clone(), + has_data: a.has_data(), + engine: meta.engine, + nodes: meta.nodes, + stale: a.stale(), + missing: a.missing() as u32, + seconds_missing: a.seconds_missing() as u32, + positions: a.positions() as u32, + searches: a.searches() as u32, + nps_per_process: st.nps_per_process, + points, + middlegame: a.report.phases.middlegame.map(|i| i as u32), + endgame: a.report.phases.endgame.map(|i| i as u32), + white: side(&a.report.white), + black: side(&a.report.black), + moves, + } +} + +#[cfg(test)] +mod tests { + use crate::open_bytes; + + #[test] + fn evaluations_of_the_pgn_make_a_report() { + let pgn = b"[Event \"t\"]\n\n1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} 2. Qh5 {[%eval -0.2]} \ + Ke7 {[%eval 6.5]} 3. Qxe5# 1-0\n" + .to_vec(); + let db = open_bytes("t.pgn".into(), pgn).unwrap(); + let data = db.game(0).unwrap(); + let review = db.review(0, String::new()).unwrap(); + let s = review.state(); + assert!(s.has_data && !s.running); + assert_eq!((s.engine.as_str(), s.nodes, s.missing), ("PGN", 0, 0)); + assert_eq!(s.points.len(), 6); + assert_eq!(s.points[0].node, 0); + assert_eq!(s.points.last().unwrap().eval, "1-0"); + assert_eq!(s.black.blunders, 1); + assert_eq!(s.moves.len(), 1); + let ke7 = &s.moves[0]; + assert!(!ke7.white); + assert_eq!(data.nodes[ke7.node as usize].san, "Ke7"); + // Evaluations from the PGN have no lines: nothing to show on the board. + assert!(ke7.best.is_none() && ke7.reply_from.is_none()); + assert!(s.white.accuracy.is_some()); + // The engine never fills in evaluations from the PGN: it would analyse the whole + // game (GameAnalysis::begin), so nothing is started here. + } + + /// With the fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). + #[test] + fn the_engine_job_runs_and_is_cached() { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + let dir = std::env::temp_dir().join(format!("mobile-review-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let cache = dir.to_string_lossy().into_owned(); + let db = open_bytes("t.pgn".into(), b"1. e4 e5 2. Nf3 Nc6 *\n".to_vec()).unwrap(); + let review = db.review(0, cache.clone()).unwrap(); + assert!(!review.state().has_data); + assert!(review.start(fake.into(), String::new(), false)); + let mut s = review.state(); + for _ in 0..200 { + if !s.running { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + s = review.state(); + } + assert!(!s.running, "the job did not end"); + assert_eq!(s.failure, None); + assert_eq!((s.done, s.total, s.missing), (5, 5, 0)); + assert!(s.points.iter().all(|p| p.white_win.is_some())); + drop(review); + // The next time the game opens, the results are there without the engine. + let again = db.review(0, cache).unwrap().state(); + assert!(again.has_data && again.missing == 0 && !again.stale); + assert_eq!(again.nodes, game_review::SEARCH_NODES); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_failing_engine_is_reported() { + let db = open_bytes("t.pgn".into(), b"1. e4 e5 *\n".to_vec()).unwrap(); + let review = db.review(0, String::new()).unwrap(); + assert!(review.start("/nonexistent/engine".into(), String::new(), false)); + let mut s = review.state(); + for _ in 0..200 { + if !s.running { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + s = review.state(); + } + assert!(!s.running); + assert!(s.failure.is_some()); + assert!(!s.has_data); + } +} diff --git a/crates/mobile-api/src/session.rs b/crates/mobile-api/src/session.rs new file mode 100644 index 0000000..8555821 --- /dev/null +++ b/crates/mobile-api/src/session.rs @@ -0,0 +1,466 @@ +//! A game being entered or changed (docs/design/android-play.md §29–30): moves played +//! on the board go into its tree (a new move at the end extends the line, an existing +//! one is followed, any other becomes a variation; nothing is overwritten), with undo, +//! the game's data and its PGN for saving. And the user's own databases: PGN files in +//! the app's folder, created, added to and changed here (never a file of someone else). + +use std::sync::{Arc, Mutex}; + +use chess_core::{EditError, Game, GameResult, NodeId}; +use shakmaty::uci::UciMove; +use shakmaty::{CastlingMode, Position}; + +use crate::{ApiError, GameData, Tag, game_data, order, places}; + +/// A game after a change: all of it again (the ids are places in `data.nodes`, which a +/// change may move) and the node to show. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct Edited { + pub data: GameData, + pub cursor: u32, +} + +/// A game that can be changed. +#[derive(uniffi::Object)] +pub struct GameSession { + game: Mutex, +} + +impl GameSession { + pub(crate) fn wrap(game: Game) -> Arc { + Arc::new(GameSession { + game: Mutex::new(game), + }) + } + + fn with(&self, f: impl FnOnce(&mut Game) -> R) -> R { + let mut g = self.game.lock().unwrap_or_else(|e| e.into_inner()); + f(&mut g) + } + + pub(crate) fn read(&self, f: impl FnOnce(&Game) -> R) -> R { + let g = self.game.lock().unwrap_or_else(|e| e.into_inner()); + f(&g) + } +} + +/// The node at place `at` of the game's list. +fn node(game: &Game, at: u32) -> Result { + order(game) + .get(at as usize) + .copied() + .ok_or(ApiError::NoNode { place: at }) +} + +fn edited(game: &Game, cursor: NodeId) -> Edited { + Edited { + data: game_data(game, &[]), + cursor: places(game).get(&cursor).copied().unwrap_or(0), + } +} + +impl From for ApiError { + fn from(e: EditError) -> Self { + ApiError::Edit { + detail: e.to_string(), + } + } +} + +#[uniffi::export] +impl GameSession { + /// A new game from the start position, dated today (`date`: "2026.10.26"). + #[uniffi::constructor] + pub fn new_game(date: String) -> Arc { + let mut g = Game::new(); + if !date.is_empty() { + g.set_tag("Date", &date); + } + g.mark_saved(); + GameSession::wrap(g) + } + + /// The first game of a PGN text. + #[uniffi::constructor] + pub fn from_pgn(pgn: String) -> Result, ApiError> { + let parsed = chess_core::pgn::parse_game(pgn.as_bytes(), chess_core::TextEncoding::Utf8); + let mut g = parsed.game; + g.mark_saved(); + Ok(GameSession::wrap(g)) + } + + /// The whole game, ready to show. + pub fn data(&self) -> GameData { + self.with(|g| game_data(g, &[])) + } + + /// The legal moves in the position at place `at`, in UCI ("e2e4", "e7e8q"); none + /// after a null move's position cannot go on, at checkmate or stalemate. + pub fn legal_moves(&self, at: u32) -> Vec { + self.with(|g| { + let Ok(id) = node(g, at) else { + return Vec::new(); + }; + g.position(id) + .map(|p| { + p.legal_moves() + .iter() + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + .collect() + }) + .unwrap_or_default() + }) + } + + /// Plays `uci` from the node at place `at`: the existing continuation when there is + /// one (nothing changes), else a new move — the main line where the line ends, a + /// variation elsewhere. One undo step. + pub fn play(&self, at: u32, uci: String) -> Result { + self.with(|g| { + let id = node(g, at)?; + let pos = g + .position(id) + .ok_or(ApiError::NoNode { place: at })? + .clone(); + let m = uci + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + .ok_or_else(|| ApiError::Edit { + detail: format!("illegal move {uci}"), + })?; + let new = g.add_move(id, m)?; + Ok(edited(g, new)) + }) + } + + /// Removes the move at place `at` with all that follows it; shows its parent. + pub fn delete_from(&self, at: u32) -> Result { + self.with(|g| { + let id = node(g, at)?; + let parent = g.delete_variation(id)?; + Ok(edited(g, parent)) + }) + } + + /// Makes the line of the move at place `at` the main one at its branch. + pub fn make_main(&self, at: u32) -> Result { + self.with(|g| { + let id = node(g, at)?; + g.promote_variation(id)?; + Ok(edited(g, id)) + }) + } + + /// Adds a line of moves (an engine's) from place `at`, as `play` does each move. + pub fn add_line(&self, at: u32, uci: Vec) -> Result { + self.with(|g| { + let id = node(g, at)?; + let last = g.add_uci_line(id, &uci)?; + Ok(edited(g, last)) + }) + } + + pub fn can_undo(&self) -> bool { + self.with(|g| g.can_undo()) + } + + pub fn can_redo(&self) -> bool { + self.with(|g| g.can_redo()) + } + + /// Takes the last change back; `None` when there is none. + pub fn undo(&self) -> Option { + self.with(|g| g.undo().map(|o| edited(g, o.cursor))) + } + + pub fn redo(&self) -> Option { + self.with(|g| g.redo().map(|o| edited(g, o.cursor))) + } + + /// Sets the game's tags (an empty value removes the tag; one of the Seven Tag Roster + /// becomes "?") and its result ("1-0", "0-1", "1/2-1/2", "*"). + pub fn set_data(&self, tags: Vec, result: String) { + self.with(|g| { + for t in tags { + if t.value.trim().is_empty() { + g.remove_tag(&t.name); + } else { + g.set_tag(&t.name, t.value.trim()); + } + } + if let Some(r) = GameResult::from_pgn(&result) { + g.set_result(r); + } + // The Seven Tag Roster first, in its order, "?" where unknown (as the desktop). + g.order_roster(); + }) + } + + /// Adds `text` to the comments after the move at place `at` (its symbols kept). + pub fn add_comment(&self, at: u32, text: String) -> Result { + self.with(|g| { + let id = node(g, at)?; + let n = g.node(id).ok_or(ApiError::NoNode { place: at })?; + let nags = n.nags().to_vec(); + let mut comments = n.comments_after().to_vec(); + comments.push(text); + g.annotate(id, nags, comments)?; + Ok(edited(g, id)) + }) + } + + /// Changed since it was opened or last saved. + pub fn is_modified(&self) -> bool { + self.with(|g| g.is_modified()) + } + + pub fn mark_saved(&self) { + self.with(|g| g.mark_saved()) + } + + /// The game as PGN, for saving or sharing. + pub fn pgn(&self) -> String { + self.with(|g| g.to_pgn()) + } + + /// The analysis of the game as it is now (its report), with earlier results from + /// the cache folder `cache_dir` ("" for none). + pub fn review(&self, cache_dir: String) -> Arc { + crate::GameReview::new(self.read(|g| g.clone()), cache_dir) + } + + /// A new game of the moves from the start to the move at place `at` (to play on from + /// there, android-play.md §31.6): the same start position, no tags but those of the + /// position. Refused on a null move on the way (a position the board cannot reach). + pub fn play_from(&self, at: u32) -> Result, ApiError> { + self.read(|g| { + let id = node(g, at)?; + let mut game = Game::from_start(g.start().clone()); + let mut cur = NodeId::ROOT; + for &n in &g.path(id)[1..] { + match g.game_move(n).map(|m| &m.kind) { + Some(chess_core::MoveKind::Normal(m)) => cur = game.add_move(cur, *m)?, + _ => { + return Err(ApiError::Edit { + detail: "a null move on the way".into(), + }); + } + } + } + game.forget_history(); + game.mark_saved(); + Ok(GameSession::wrap(game)) + }) + } +} + +// ----- own databases ---------------------------------------------------------------- + +fn io(e: impl std::fmt::Display) -> ApiError { + ApiError::Io { + detail: e.to_string(), + } +} + +/// Opens the own database at `path` for writing (read just now, so it is current). +fn own(path: &str) -> Result { + Ok(chess_import::open(std::path::Path::new(path), &mut |_| {}, &crate::never())?.db) +} + +/// Makes a new empty own database at `path` (refused when the file exists). +#[uniffi::export] +pub fn own_create(path: String) -> Result<(), ApiError> { + let path = std::path::Path::new(&path); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(io)?; + } + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .and_then(|f| f.sync_all()) + .map_err(io) +} + +/// Saves the game `pgn` into the own database at `path`: as game `index` (replacing +/// it), or added at the end when `index` is `None`. Returns the game's number. +#[uniffi::export] +pub fn own_save(path: String, index: Option, pgn: String) -> Result { + let db = own(&path)?; + let file = db.as_pgn().ok_or_else(|| ApiError::Unsupported { + detail: "not a PGN file".into(), + })?; + match index { + Some(i) => { + chess_core::pgn::store::replace(file, i as usize, &pgn).map_err(io)?; + Ok(i) + } + None => { + chess_core::pgn::store::append(file, &pgn).map_err(io)?; + Ok(file.len() as u32) + } + } +} + +/// Removes game `index` from the own database at `path`. +#[uniffi::export] +pub fn own_remove(path: String, index: u32) -> Result<(), ApiError> { + let db = own(&path)?; + let file = db.as_pgn().ok_or_else(|| ApiError::Unsupported { + detail: "not a PGN file".into(), + })?; + chess_core::pgn::store::remove(file, index as usize) + .map(|_| ()) + .map_err(io) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn san_line(d: &GameData) -> Vec { + let mut out = Vec::new(); + let mut at = 0usize; + while let Some(&c) = d.nodes[at].children.first() { + out.push(d.nodes[c as usize].san.clone()); + at = c as usize; + } + out + } + + #[test] + fn moves_extend_the_line_and_branch_into_variations() { + let s = GameSession::new_game("2026.10.26".into()); + let e = s.play(0, "e2e4".into()).unwrap(); + let e = s.play(e.cursor, "e7e5".into()).unwrap(); + assert_eq!(san_line(&e.data), ["e4", "e5"]); + // The same move again: followed, not added. + let again = s.play(0, "e2e4".into()).unwrap(); + assert_eq!(again.data.nodes.len(), 3); + // Another first move: a variation, the main line kept. + let v = s.play(0, "d2d4".into()).unwrap(); + assert_eq!(san_line(&v.data), ["e4", "e5"]); + assert_eq!(v.data.nodes[0].children.len(), 2); + assert!(!v.data.nodes[v.cursor as usize].main_line); + // Undo takes the variation back; redo brings it again. + let u = s.undo().unwrap(); + assert_eq!(u.data.nodes[0].children.len(), 1); + assert!(s.redo().is_some()); + assert!(s.is_modified()); + } + + #[test] + fn a_move_keeps_its_id_when_the_game_changes() { + let s = GameSession::from_pgn("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *".into()).unwrap(); + let before = s.data(); + let nf3 = before.nodes.iter().find(|n| n.san == "Nf3").unwrap().id; + // A variation at the first move, then removed: Nf3 stays where it was. + let v = s.play(0, "d2d4".into()).unwrap(); + assert_eq!(v.data.nodes[nf3 as usize].san, "Nf3"); + let gone = s.delete_from(v.cursor).unwrap(); + assert_eq!(gone.data.nodes[nf3 as usize].san, "Nf3"); + // The removed move is reached from nowhere. + assert!(gone.data.nodes[v.cursor as usize].parent.is_none()); + assert!(!gone.data.nodes[0].children.contains(&v.cursor)); + // Undo brings it back under the same id. + let back = s.undo().unwrap(); + assert!(back.data.nodes[0].children.contains(&v.cursor)); + } + + #[test] + fn a_game_goes_on_from_a_move_of_another() { + let s = + GameSession::from_pgn("[White \"A\"]\n\n1. e4 e5 (1... c5) 2. Nf3 *".into()).unwrap(); + let c5 = s.data().nodes.iter().find(|n| n.san == "c5").unwrap().id; + let p = s.play_from(c5).unwrap(); + assert_eq!(san_line(&p.data()), ["e4", "c5"]); + assert!(!p.is_modified()); + assert!( + !p.data() + .tags + .iter() + .any(|t| t.name == "White" && t.value == "A") + ); + let n = GameSession::from_pgn("1. e4 -- 2. d4 *".into()).unwrap(); + let d4 = n.data().nodes.iter().find(|x| x.san == "d4").unwrap().id; + assert!(n.play_from(d4).is_err()); + } + + #[test] + fn an_illegal_move_changes_nothing() { + let s = GameSession::new_game(String::new()); + assert!(s.play(0, "e2e5".into()).is_err()); + assert!(!s.can_undo()); + assert_eq!(s.legal_moves(0).len(), 20); + } + + #[test] + fn variations_become_main_and_go() { + let s = GameSession::new_game(String::new()); + s.play(0, "e2e4".into()).unwrap(); + let d4 = s.play(0, "d2d4".into()).unwrap(); + let m = s.make_main(d4.cursor).unwrap(); + assert_eq!(san_line(&m.data), ["d4"]); + let gone = s.delete_from(m.data.nodes[0].children[0]).unwrap(); + assert_eq!(san_line(&gone.data), ["e4"]); + assert_eq!(gone.cursor, 0); + } + + #[test] + fn games_are_saved_into_own_databases() { + let dir = std::env::temp_dir().join(format!("cp-own-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("own").join("Мои партии.pgn"); + let p = path.to_string_lossy().into_owned(); + own_create(p.clone()).unwrap(); + assert!( + own_create(p.clone()).is_err(), + "an existing file is not replaced" + ); + + let s = GameSession::new_game("2026.10.26".into()); + s.play(0, "e2e4".into()).unwrap(); + s.set_data( + vec![Tag { + name: "White".into(), + value: "КоÑ�Ñ‚Ñ�".into(), + }], + "1-0".into(), + ); + assert_eq!(own_save(p.clone(), None, s.pgn()).unwrap(), 0); + assert_eq!(own_save(p.clone(), None, s.pgn()).unwrap(), 1); + let s2 = GameSession::from_pgn(s.pgn()).unwrap(); + s2.play(1, "e7e5".into()).unwrap(); + assert_eq!(own_save(p.clone(), Some(0), s2.pgn()).unwrap(), 0); + + // The roster stays whole and in order, unknown values "?". + let pgn = s.pgn(); + let order: Vec<&str> = pgn + .lines() + .take(7) + .map(|l| l.split(' ').next().unwrap()) + .collect(); + assert_eq!( + order, + [ + "[Event", "[Site", "[Date", "[Round", "[White", "[Black", "[Result" + ] + ); + assert!(pgn.contains("[Event \"?\"]")); + let db = crate::open_path(p.clone()).unwrap(); + assert_eq!(db.len(), 2); + let first = db.game(0).unwrap(); + assert_eq!(san_line(&first), ["e4", "e5"]); + assert_eq!(first.result, "1-0"); + assert!( + first + .tags + .iter() + .any(|t| t.name == "White" && t.value == "КоÑ�Ñ‚Ñ�") + ); + own_remove(p.clone(), 1).unwrap(); + assert_eq!(crate::open_path(p).unwrap().len(), 1); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/mobile-api/src/train.rs b/crates/mobile-api/src/train.rs new file mode 100644 index 0000000..d0fef03 --- /dev/null +++ b/crates/mobile-api/src/train.rs @@ -0,0 +1,312 @@ +//! Learning an opening on the phone (docs/design/android-play.md §32): the shared +//! trainer (`crates/trainer`) over a line of a game; the app draws, this judges. + +use std::sync::{Arc, Mutex}; + +use chess_core::NodeId; +use shakmaty::fen::Fen; +use shakmaty::uci::UciMove; +use shakmaty::{CastlingMode, Chess, EnPassantMode, Position}; +use trainer::{LineStats, TrainStart, Training, Verdict}; + +use crate::session::GameSession; + +/// Where the runs are kept (`training.json` in the app's files). +#[uniffi::export] +pub fn trainer_set_file(path: String) { + trainer::set_file(path.into()); +} + +/// The runs of a line so far. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TrainStats { + pub runs: u32, + pub last: Option, + pub best: Option, + pub clean_streak: u32, + /// The last runs, oldest first: their mistakes and whether the move was shown. + pub recent_mistakes: Vec, + pub recent_hinted: Vec, +} + +impl From<&LineStats> for TrainStats { + fn from(s: &LineStats) -> Self { + TrainStats { + runs: s.runs, + last: s.last, + best: s.best, + clean_streak: s.clean_streak, + recent_mistakes: s.recent.iter().map(|r| r.0).collect(), + recent_hinted: s.recent.iter().map(|r| r.1).collect(), + } + } +} + +/// What a move made was. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum TrainVerdict { + Right, + Finished, + Wrong, + Done, +} + +/// The state of the run after `ply` half-moves. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct TrainState { + /// The position now, and the move that led here (none at the start). + pub fen: String, + pub from_square: Option, + pub to_square: Option, + /// The moves played so far, in SAN (Latin letters). + pub played: Vec, + /// Half-moves in the line. + pub length: u32, + pub mistakes_here: u32, + pub mistakes: u32, + /// The user may ask to see this move; it is shown now (from, to). + pub may_show: bool, + pub hint: Option>, + pub hinted: bool, + pub done: bool, + pub before: TrainStats, + pub after: Option, +} + +/// A training of one line. +#[derive(uniffi::Object)] +pub struct Trainer { + training: Mutex, + start: Chess, +} + +impl Trainer { + fn with(&self, f: impl FnOnce(&mut Training) -> R) -> R { + f(&mut self.training.lock().unwrap_or_else(|e| e.into_inner())) + } + + /// The position after `ply` moves of the line. + fn position(&self, t: &Training, ply: usize) -> Chess { + let mut pos = self.start.clone(); + for m in t.start.line.iter().take(ply) { + pos.play_unchecked(*m); + } + pos + } +} + +fn fen(pos: &Chess) -> String { + Fen::from_position(pos, EnPassantMode::Legal).to_string() +} + +/// The squares of a move as the board shows them (castling: the king's two squares). +fn squares(m: &shakmaty::Move) -> (String, String) { + let to = match (m.castling_side(), m.from()) { + (Some(side), Some(from)) => side.king_to(if from.rank() == shakmaty::Rank::First { + shakmaty::Color::White + } else { + shakmaty::Color::Black + }), + _ => m.to(), + }; + (m.from().unwrap_or(m.to()).to_string(), to.to_string()) +} + +#[uniffi::export] +impl GameSession { + /// A training of the line from the start to the move at place `at` (none: no move + /// there, or a null move on the way). + pub fn trainer(&self, at: u32) -> Option> { + let start = self.read(|g| { + let id = crate::order(g).get(at as usize).copied()?; + (id != NodeId::ROOT) + .then(|| TrainStart::from_game(g, id)) + .flatten() + })?; + let pos = match start.start_fen.as_deref() { + Some(f) => f + .parse::() + .ok()? + .into_position::(CastlingMode::Standard) + .ok()?, + None => Chess::default(), + }; + Some(Arc::new(Trainer { + training: Mutex::new(Training::new(start)), + start: pos, + })) + } + + /// How many times the line up to the move at place `at` was trained. + pub fn training_runs(&self, at: u32) -> Option { + self.read(|g| { + let id = crate::order(g).get(at as usize).copied()?; + trainer::runs_to(g, id) + }) + } +} + +#[uniffi::export] +impl Trainer { + /// «Carlsen — Caruana», when the game names its players. + pub fn game(&self) -> Option { + self.with(|t| t.start.game.clone()) + } + + /// «Wijk aan Zee 2024», when the game says so. + pub fn event(&self) -> Option { + self.with(|t| t.start.event.clone()) + } + + /// The line's last move («12…Rd8», SAN in Latin letters). + pub fn up_to(&self) -> String { + self.with(|t| t.start.up_to.clone()) + } + + /// The run after `ply` half-moves. + pub fn state(&self, ply: u32) -> TrainState { + let k = ply as usize; + self.with(|t| { + let pos = self.position(t, k); + let mut played = Vec::new(); + let mut p = self.start.clone(); + for m in t.start.line.iter().take(k) { + played.push(shakmaty::san::San::from_move(&p, *m).to_string()); + p.play_unchecked(*m); + } + let last = k + .checked_sub(1) + .and_then(|i| t.start.line.get(i)) + .map(squares); + TrainState { + fen: fen(&pos), + from_square: last.as_ref().map(|s| s.0.clone()), + to_square: last.map(|s| s.1), + played, + length: t.start.line.len() as u32, + mistakes_here: t.mistakes_on(k), + mistakes: t.total(), + may_show: t.may_show(k), + hint: (t.hint && t.shown.get(k).copied().unwrap_or(false)) + .then(|| { + t.wanted(k).map(|m| { + let (a, b) = squares(&m); + vec![a, b] + }) + }) + .flatten(), + hinted: t.hinted(), + done: t.done, + before: (&t.before).into(), + after: t.after.as_ref().map(Into::into), + } + }) + } + + /// The legal moves after `ply` half-moves (UCI). + pub fn legal_moves(&self, ply: u32) -> Vec { + self.with(|t| { + if t.done { + return Vec::new(); + } + self.position(t, ply as usize) + .legal_moves() + .iter() + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + .collect() + }) + } + + /// The line's move on half-move `ply` in UCI: its piece where a pawn promotes (the + /// phone promotes to a queen otherwise, android-play.md §29.4). + pub fn promotion_at(&self, ply: u32) -> Option { + self.with(|t| { + t.wanted(ply as usize) + .filter(|m| m.promotion().is_some()) + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + }) + } + + /// Judges `uci` made after `ply` half-moves. + pub fn judge(&self, ply: u32, uci: String) -> TrainVerdict { + self.with(|t| { + let pos = self.position(t, ply as usize); + let Some(m) = uci + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + else { + return TrainVerdict::Wrong; + }; + match t.judge(ply as usize, m) { + Verdict::Right => TrainVerdict::Right, + Verdict::Finished => TrainVerdict::Finished, + Verdict::Wrong => TrainVerdict::Wrong, + Verdict::Done => TrainVerdict::Done, + } + }) + } + + /// The position after a wrong `uci` made after `ply` half-moves (shown a moment). + pub fn fen_after(&self, ply: u32, uci: String) -> Option { + self.with(|t| { + let mut pos = self.position(t, ply as usize); + let m = uci.parse::().ok()?.to_move(&pos).ok()?; + pos.play_unchecked(m); + Some(fen(&pos)) + }) + } + + /// Shows the move of half-move `ply` (the run is then «with a hint»). + pub fn show(&self, ply: u32) { + self.with(|t| t.show(ply as usize)) + } + + /// The same line again from the start. + pub fn again(&self) { + self.with(|t| t.again()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_line_is_trained_on_the_phone() { + let dir = std::env::temp_dir().join(format!("cp-mtrain-{}", std::process::id())); + trainer_set_file(dir.join("training.json").to_string_lossy().into_owned()); + let s = GameSession::from_pgn("[White \"A\"]\n\n1. e4 e5 2. Nf3 Nc6 *".into()).unwrap(); + let d = s.data(); + let nc6 = d.nodes.iter().find(|n| n.san == "Nc6").unwrap().id; + let t = s.trainer(nc6).unwrap(); + assert_eq!(t.up_to(), "2…Nc6"); + assert_eq!(t.state(0).length, 4); + assert_eq!(t.judge(0, "d2d4".into()), TrainVerdict::Wrong); + assert!( + t.fen_after(0, "d2d4".into()) + .unwrap() + .starts_with("rnbqkbnr/pppppppp/8/8/3P4") + ); + assert_eq!(t.state(0).mistakes_here, 1); + for (k, m) in ["e2e4", "e7e5", "g1f3"].iter().enumerate() { + assert_eq!(t.judge(k as u32, (*m).into()), TrainVerdict::Right); + } + assert_eq!(t.state(3).played, ["e4", "e5", "Nf3"]); + assert_eq!(t.judge(3, "b8c6".into()), TrainVerdict::Finished); + let st = t.state(4); + assert!(st.done); + assert_eq!(st.after.unwrap().runs, 1); + assert_eq!(s.training_runs(nc6), Some(1)); + // Castling is shown on the king's squares. + let c = GameSession::from_pgn("1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O *".into()).unwrap(); + let oo = c.data().nodes.iter().find(|n| n.san == "O-O").unwrap().id; + let tc = c.trainer(oo).unwrap(); + let last = tc.state(7); + assert_eq!( + (last.from_square.as_deref(), last.to_square.as_deref()), + (Some("e1"), Some("g1")) + ); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/mobile-api/src/update.rs b/crates/mobile-api/src/update.rs new file mode 100644 index 0000000..a749dd1 --- /dev/null +++ b/crates/mobile-api/src/update.rs @@ -0,0 +1,166 @@ +//! A newer release for the Android app: the `releases` crate (the same check as the +//! desktop's) with the two APKs of the release and their SHA-256. The app downloads and +//! installs the file itself (Android's download service and package installer). +//! +//! The check talks to GitHub (or to a test server in a debug build) and blocks: call it +//! off the main thread. + +use releases::{Release, VERSION, check_latest, fetch_latest, fetch_sums, sum_in}; + +/// GitHub's answer for the latest release (a debug build may ask a test server). +#[uniffi::export] +pub fn release_api() -> String { + releases::API.to_owned() +} + +/// An APK of a release. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ApkFile { + pub name: String, + pub url: String, + pub size: u64, + /// From the release's `SHA256SUMS.txt`, lowercase hex. + pub sha256: String, +} + +/// A release newer than this app. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct AppRelease { + pub version: String, + /// Its page: what is new in it. + pub page: String, + /// The build without the engine's network (the network already in the app stays). + pub light: Option, + /// The build with the network inside. + pub full: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum ReleaseCheck { + /// This app is the latest release (or newer: a build from the sources), or the newer + /// release has nothing for Android (a desktop-only one). + UpToDate { + latest: String, + }, + Newer { + release: AppRelease, + }, + /// A newer release whose light APK cannot be checked: no `SHA256SUMS.txt`, or no sum + /// for the file in it. + Unverifiable { + release: AppRelease, + }, + /// No answer: `detail` for the log. + Failed { + detail: String, + }, +} + +const LIGHT: &str = "-android-noengine.apk"; +const FULL: &str = "-android.apk"; + +/// Asks `api` (a test server) for the latest release; a newer one comes with its APKs. +#[uniffi::export] +pub fn check_release(api: String) -> ReleaseCheck { + let client = format!("ChessPenguin/{VERSION} (Android)"); + checked(fetch_latest(&api, &client), &client) +} + +/// Asks the site for the latest release, counting this installation for the day (its +/// random `install` id and `platform`: "android" or "android-noengine"); without the +/// site, GitHub. A newer release comes with its APKs. +#[uniffi::export] +pub fn check_release_counted(install: String, platform: String) -> ReleaseCheck { + let client = format!("ChessPenguin/{VERSION} (Android)"); + checked(check_latest(&install, &platform, &client), &client) +} + +fn checked(found: Result, client: &str) -> ReleaseCheck { + let release = match found { + Ok(r) => r, + Err(detail) => return ReleaseCheck::Failed { detail }, + }; + if !release.newer() || release.asset_ending(LIGHT).is_none() { + return ReleaseCheck::UpToDate { + latest: release.version, + }; + } + let sums = if release.sums().is_some() { + match fetch_sums(&release, client) { + Ok(s) => s, + Err(detail) => return ReleaseCheck::Failed { detail }, + } + } else { + String::new() + }; + let found = app_release(&release, &sums); + if found.light.as_ref().is_some_and(|a| !a.sha256.is_empty()) { + ReleaseCheck::Newer { release: found } + } else { + ReleaseCheck::Unverifiable { release: found } + } +} + +/// The release's APKs with their sums ("" when `sums` has none for a file). +fn app_release(release: &Release, sums: &str) -> AppRelease { + let apk = |suffix: &str| { + let a = release.asset_ending(suffix)?; + Some(ApkFile { + name: a.name.clone(), + url: a.url.clone(), + size: a.size, + sha256: sum_in(sums, &a.name).unwrap_or_default(), + }) + }; + AppRelease { + version: release.version.clone(), + page: release.page.clone(), + light: apk(LIGHT), + full: apk(FULL), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use releases::Asset; + + fn release(names: &[&str]) -> Release { + Release { + version: "9.9.9".into(), + page: "https://example.org/v9.9.9".into(), + assets: names + .iter() + .map(|n| Asset { + name: (*n).into(), + url: format!("https://example.org/{n}"), + size: 7, + }) + .collect(), + } + } + + #[test] + fn both_apks_with_their_sums() { + let r = release(&[ + "ChessPenguin-9.9.9-android.apk", + "ChessPenguin-9.9.9-android-noengine.apk", + "SHA256SUMS.txt", + ]); + let sums = + "aa ChessPenguin-9.9.9-android.apk\nbb ChessPenguin-9.9.9-android-noengine.apk\n"; + let a = app_release(&r, sums); + let light = a.light.unwrap(); + assert_eq!(light.name, "ChessPenguin-9.9.9-android-noengine.apk"); + assert_eq!(light.sha256, "bb"); + assert_eq!(a.full.unwrap().sha256, "aa"); + } + + #[test] + fn an_apk_without_its_sum_has_none() { + let r = release(&["ChessPenguin-9.9.9-android-noengine.apk", "SHA256SUMS.txt"]); + assert_eq!(app_release(&r, "").light.unwrap().sha256, ""); + let r = release(&["ChessPenguin-9.9.9-windows-x86_64.zip"]); + assert!(app_release(&r, "").light.is_none()); + } +} diff --git a/crates/mobile-api/uniffi.toml b/crates/mobile-api/uniffi.toml new file mode 100644 index 0000000..72d3319 --- /dev/null +++ b/crates/mobile-api/uniffi.toml @@ -0,0 +1,3 @@ +# Kotlin bindings for Android: the cleaner of the system on Android 13+, JNA before. +[bindings.kotlin] +android = true diff --git a/crates/online-games/Cargo.toml b/crates/online-games/Cargo.toml new file mode 100644 index 0000000..da2d8d7 --- /dev/null +++ b/crates/online-games/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "online-games" +description = "A player's games from Lichess and Chess.com by nickname, kept as a PGN database that later fetches only the new games (the desktop and Android apps share it)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +serde.workspace = true +serde_json.workspace = true + +# Requests that block a thread: not in a browser (net.rs). +[target.'cfg(not(target_family = "wasm"))'.dependencies] +ureq = "3.4" + +[dev-dependencies] +chess-core.workspace = true diff --git a/crates/online-games/src/lib.rs b/crates/online-games/src/lib.rs new file mode 100644 index 0000000..a287ab2 --- /dev/null +++ b/crates/online-games/src/lib.rs @@ -0,0 +1,299 @@ +//! A player's games from Lichess and Chess.com, by nickname (no login; anyone's: the +//! user's own, a pupil's, an opponent's): they become a PGN database in a folder of the +//! app (one per site, or both sites in one), with a small state file next to it so that +//! "Update" fetches only the new games (and continues an interrupted download). The +//! desktop and the Android app share this; each passes its own folder. +//! +//! Lichess: `GET /api/games/user/{name}` as NDJSON (`pgnInJson`), oldest first, from +//! `since`; anonymous requests are throttled to 20 games a second. Chess.com: the list of +//! monthly archives, then each month's games as JSON (their PGN inside), from the last +//! month already fetched. Only standard chess is kept (variants are not supported). +//! +//! The network part (`net.rs`: lookups, downloads) is built where requests can block +//! a thread: not in a browser. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicUsize; + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Platform { + Lichess, + ChessCom, +} + +impl Platform { + pub const ALL: [Platform; 2] = [Platform::Lichess, Platform::ChessCom]; + + pub fn name(self) -> &'static str { + match self { + Platform::Lichess => "Lichess", + Platform::ChessCom => "Chess.com", + } + } + + pub fn index(self) -> usize { + match self { + Platform::Lichess => 0, + Platform::ChessCom => 1, + } + } +} + +/// Lichess's anonymous export rate (games per second), for the time estimate. +pub const LICHESS_RATE: u64 = 20; + +#[cfg(not(target_family = "wasm"))] +mod net; +#[cfg(not(target_family = "wasm"))] +pub use net::{download, lookup, probe, probe_all}; + +/// What went wrong talking to a platform. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Failure { + /// No answer (offline, DNS, TLS, timeout). + Network(String), + /// "Too many requests": the platform asks to wait. + RateLimited, + /// An answer we do not understand (the API changed). + Unexpected(String), + /// Writing the database failed. + Disk(String), + /// The database is being downloaded already. + Busy, +} + +impl std::fmt::Display for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Failure::Network(e) => write!(f, "network: {e}"), + Failure::RateLimited => write!(f, "rate limited"), + Failure::Unexpected(e) => write!(f, "unexpected answer: {e}"), + Failure::Disk(e) => write!(f, "{e}"), + Failure::Busy => write!(f, "the database is being downloaded already"), + } + } +} + +/// A nickname both platforms could have: 2–30 letters, digits, `_` or `-`. +pub fn valid_nick(nick: &str) -> bool { + (2..=30).contains(&nick.len()) + && nick + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +/// An account found by nickname. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Account { + pub platform: Platform, + /// As the platform spells it. + pub username: String, + /// Lichess: games of the account (all kinds, so an upper bound for ours). + pub games: Option, + /// Chess.com: months with games. + pub months: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Lookup { + Found(Account), + NotFound, + Failed(Failure), +} + +/// The database file of one account in `dir`: "Name (Lichess).pgn". +pub fn database_path(dir: &Path, p: Platform, username: &str) -> PathBuf { + dir.join(format!("{username} ({}).pgn", p.name())) +} + +/// The database of several accounts in one: "Name (Lichess + Chess.com).pgn" when the +/// nicknames are the same, "Name (Lichess) + Other (Chess.com).pgn" otherwise (so that +/// another set of accounts never lands in the same file). +pub fn combined_path(dir: &Path, accounts: &[Account]) -> Option { + let first = accounts.first()?; + if accounts.len() == 1 { + return Some(database_path(dir, first.platform, &first.username)); + } + let same = accounts + .iter() + .all(|a| a.username.eq_ignore_ascii_case(&first.username)); + let name = if same { + let platforms = accounts + .iter() + .map(|a| a.platform.name()) + .collect::>() + .join(" + "); + format!("{} ({platforms})", first.username) + } else { + accounts + .iter() + .map(|a| format!("{} ({})", a.username, a.platform.name())) + .collect::>() + .join(" + ") + }; + Some(dir.join(format!("{name}.pgn"))) +} + +/// The online databases already holding `account` (several when it was downloaded +/// alone and together with another one), those with more accounts first. +pub fn holding(dir: &Path, account: &Account) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found: Vec<(usize, PathBuf)> = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "pgn")) + .filter_map(|p| { + let s = State::load(&p)?; + s.holds(account).then_some((s.accounts.len(), p)) + }) + .collect(); + found.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); + found.into_iter().map(|(_, p)| p).collect() +} + +fn state_path(pgn: &Path) -> PathBuf { + pgn.with_extension("online.json") +} + +/// What has been fetched from one account into a database. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct AccountState { + pub platform: Option, + pub username: String, + /// Lichess: creation time (ms) of the newest game fetched. + pub lichess_last: Option, + /// Lichess: games still being played when last fetched (id, creation time ms): + /// the next update asks again from the oldest of them, so that a long + /// (correspondence) game is fetched once it ends. + #[serde(default)] + pub lichess_pending: Vec<(String, i64)>, + /// Chess.com: the newest month fetched ("2026/10") and the end time (s) of its + /// last game fetched. + pub chesscom_month: Option, + pub chesscom_last_end: Option, +} + +/// What has been fetched into a database (from one account or several), for the next +/// update. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct State { + pub accounts: Vec, + /// Games written so far. + pub games: u64, + /// When the last download finished (Unix seconds). + #[serde(default)] + pub updated: Option, + /// The length of the database file when the state was saved, and its last bytes: + /// what a crash appended after that is cut off before the next download (only if + /// the file still ends the same way there, i.e. nobody else changed it). + #[serde(default)] + pub bytes: Option, + #[serde(default)] + pub tail: Vec, +} + +impl State { + pub fn load(pgn: &Path) -> Option { + let text = std::fs::read_to_string(state_path(pgn)).ok()?; + serde_json::from_str::(&text) + .ok() + .filter(|s| !s.accounts.is_empty() && s.accounts.iter().all(|a| a.platform.is_some())) + } + + fn holds(&self, a: &Account) -> bool { + self.accounts.iter().any(|s| s.is(a)) + } + + /// The accounts of the database, to update it. + pub fn accounts(&self) -> Vec { + self.accounts + .iter() + .filter_map(|a| { + Some(Account { + platform: a.platform?, + username: a.username.clone(), + games: None, + months: None, + }) + }) + .collect() + } +} + +impl AccountState { + fn is(&self, a: &Account) -> bool { + self.platform == Some(a.platform) && self.username.eq_ignore_ascii_case(&a.username) + } +} + +impl Account { + /// The same account (the counts aside). + pub fn same(&self, other: &Account) -> bool { + self.platform == other.platform && self.username.eq_ignore_ascii_case(&other.username) + } +} + +/// An online database of `dir` (it has a state file). +pub fn is_online(dir: &Path, pgn: &Path) -> bool { + pgn.parent() == Some(dir) && state_path(pgn).exists() +} + +/// Where the found accounts go: all into one database (`together`) or each into its +/// own. A database already holding the accounts is kept (also when one site does not +/// answer this time: its partner's games still go where they went before). +pub fn targets(dir: &Path, start: &[Account], together: bool) -> Vec<(Vec, PathBuf)> { + let groups: Vec> = if together { + vec![start.to_vec()] + } else { + start.iter().map(|a| vec![a.clone()]).collect() + }; + // Only one account found: any database holding it (the merged one first). + let any = start.len() == 1; + groups + .into_iter() + .filter_map(|g| { + let existing = holding(dir, &g[0]).into_iter().find(|p| { + State::load(p).is_some_and(|s| { + let mine = s.accounts(); + any || (mine.len() == g.len() + && g.iter().all(|a| mine.iter().any(|m| m.same(a)))) + }) + }); + let path = existing.or_else(|| combined_path(dir, &g))?; + Some((g, path)) + }) + .collect() +} + +/// What a running download is doing, for the progress line: the account (its index in +/// the accounts passed to [`download`]), the games of that account so far, and for +/// Chess.com the months done of all. +#[derive(Debug, Default)] +pub struct Progress { + pub account: AtomicUsize, + pub games: AtomicUsize, + pub months_done: AtomicUsize, + pub months_total: AtomicUsize, +} + +/// Now, in Unix seconds. +pub fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) +} + +/// The result of a download. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Done { + pub path: PathBuf, + /// Games added by this run, and in the database now. + pub added: u64, + pub total: u64, + /// Stopped by the user; what was fetched is kept and the next update continues. + pub cancelled: bool, +} diff --git a/crates/online-games/src/net.rs b/crates/online-games/src/net.rs new file mode 100644 index 0000000..d20cfff --- /dev/null +++ b/crates/online-games/src/net.rs @@ -0,0 +1,978 @@ +//! Talking to Lichess and Chess.com: lookups, probes, downloads into the database. + +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use serde_json::Value; + +use super::*; + +/// How many last bytes of the file the state remembers. +const TAIL: usize = 64; + +impl State { + fn save(&self, pgn: &Path) -> Result<(), Failure> { + let text = serde_json::to_string_pretty(self).map_err(|e| Failure::Disk(e.to_string()))?; + let path = state_path(pgn); + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, text) + .and_then(|_| std::fs::rename(&tmp, &path)) + .map_err(|e| Failure::Disk(e.to_string())) + } +} + +fn agent(stream: bool) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .user_agent(format!( + "ChessPenguin/{} (+https://chess.vrubel.xyz)", + env!("CARGO_PKG_VERSION") + )) + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(30))) + // A long export is one response: hours for the body (a stalled one ends). + .timeout_recv_body(if stream { + Some(Duration::from_secs(4 * 3600)) + } else { + Some(Duration::from_secs(60)) + }) + .build(); + ureq::Agent::new_with_config(config) +} + +/// Makes a request again when the connection broke (Lichess drops connections for a +/// minute or so after an export was cut short), waiting `waits` seconds in between; +/// stops waiting when cancelled. +fn retrying( + waits: &[u64], + cancel: &AtomicBool, + mut request: impl FnMut() -> Result, +) -> Result { + let mut waits = waits.iter(); + loop { + match request() { + Ok(r) => return Ok(r), + Err(e) => { + let Some(&secs) = waits.next() else { + return Err(Failure::Network(e.to_string())); + }; + for _ in 0..secs * 10 { + if cancel.load(Ordering::Relaxed) { + return Err(Failure::Network(e.to_string())); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + } + } +} + +/// Waits before the attempts of a download request: about a minute in all. +const DOWNLOAD_WAITS: &[u64] = &[3, 10, 20, 30]; + +/// GET returning (status, body); the body of an error status is not read. +fn get(url: &str) -> Result<(u16, String), Failure> { + let never = AtomicBool::new(false); + // The whole exchange is repeated: a connection may also break in the body. + retrying(&[2, 5], &never, || { + let mut resp = agent(false) + .get(url) + .header("Accept", "application/json") + .call()?; + let status = resp.status().as_u16(); + if status != 200 { + return Ok((status, String::new())); + } + let body = resp + .body_mut() + .with_config() + .limit(64 << 20) + .read_to_string()?; + Ok((status, body)) + }) + .and_then(|(status, body)| { + if status == 429 { + Err(Failure::RateLimited) + } else { + Ok((status, body)) + } + }) +} + +fn json(url: &str) -> Result, Failure> { + match get(url)? { + (200, body) => serde_json::from_str(&body) + .map(Some) + .map_err(|e| Failure::Unexpected(e.to_string())), + (404, _) => Ok(None), + (code, _) => Err(Failure::Unexpected(format!("HTTP {code}"))), + } +} + +/// Whether the platform answers the way this code expects: the profile of an account +/// that has always existed (Lichess's own, Chess.com's founder's). +pub fn probe(p: Platform) -> bool { + let url = match p { + Platform::Lichess => "https://lichess.org/api/user/lichess", + Platform::ChessCom => "https://api.chess.com/pub/player/erik", + }; + matches!(json(url), Ok(Some(v)) if probe_answer_ok(p, &v)) +} + +/// The probe's answer has the fields this code relies on. +fn probe_answer_ok(p: Platform, v: &Value) -> bool { + match p { + Platform::Lichess => { + v["id"] == "lichess" && v["username"].is_string() && v["count"]["all"].is_u64() + } + Platform::ChessCom => v["player_id"].is_u64() && v["username"] == "erik", + } +} + +/// Both platforms probed (in parallel); `[lichess, chess.com]`. +pub fn probe_all() -> [bool; 2] { + std::thread::scope(|s| { + let l = s.spawn(|| probe(Platform::Lichess)); + let c = s.spawn(|| probe(Platform::ChessCom)); + [l.join().unwrap_or(false), c.join().unwrap_or(false)] + }) +} + +/// Looks the nickname up on the platform. +pub fn lookup(p: Platform, nick: &str) -> Lookup { + let nick = nick.trim(); + if !valid_nick(nick) { + return Lookup::NotFound; + } + let result = match p { + Platform::Lichess => json(&format!("https://lichess.org/api/user/{nick}")).map(|v| { + v.filter(|v| v["disabled"] != true).and_then(|v| { + Some(Account { + platform: p, + username: v["username"].as_str()?.to_owned(), + games: v["count"]["all"].as_u64(), + months: None, + }) + }) + }), + Platform::ChessCom => { + let lower = nick.to_ascii_lowercase(); + json(&format!("https://api.chess.com/pub/player/{lower}")).and_then(|v| { + let Some(username) = v.and_then(|v| v["username"].as_str().map(str::to_owned)) + else { + return Ok(None); + }; + // Chess.com answers in lower case; the user's spelling reads better. + let username = if username.eq_ignore_ascii_case(nick) { + nick.to_owned() + } else { + username + }; + let months = archives(&lower)?.len(); + Ok(Some(Account { + platform: p, + username, + games: None, + months: Some(months), + })) + }) + } + }; + match result { + Ok(Some(a)) => Lookup::Found(a), + Ok(None) => Lookup::NotFound, + Err(e) => Lookup::Failed(e), + } +} + +/// Chess.com's monthly archive URLs of a player, oldest first. +fn archives(lower: &str) -> Result, Failure> { + let v = json(&format!( + "https://api.chess.com/pub/player/{lower}/games/archives" + ))? + .ok_or_else(|| Failure::Unexpected("no archives".into()))?; + let list = v["archives"] + .as_array() + .ok_or_else(|| Failure::Unexpected("archives".into()))?; + Ok(list + .iter() + .filter_map(|u| u.as_str().map(str::to_owned)) + .collect()) +} + +/// The databases being written now: one download per file at a time. +static WRITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Holds a database for one download; released when dropped. +struct Claim(PathBuf); + +impl Claim { + fn take(path: &Path) -> Option { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + if w.iter().any(|p| p == path) { + return None; + } + w.push(path.to_owned()); + Some(Claim(path.to_owned())) + } +} + +impl Drop for Claim { + fn drop(&mut self) { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + w.retain(|p| *p != self.0); + } +} + +/// Appends games to the database file and keeps the state in step. +struct Writer { + path: PathBuf, + file: std::io::BufWriter, + state: State, + added: u64, + /// The file's length and last bytes as written (flushed or not). + len: u64, + tail: Vec, +} + +impl Writer { + /// Opens the database for appending; a state that does not match the file (the file + /// is gone, or a crash left games after the state) is put right first. + fn open(path: &Path, mut state: State) -> Result { + let disk = |e: std::io::Error| Failure::Disk(e.to_string()); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(disk)?; + } + let file = std::fs::OpenOptions::new() + .create(true) + .read(true) + .append(true) + .open(path) + .map_err(disk)?; + let mut len = file.metadata().map_err(disk)?.len(); + if let Some(b) = state.bytes + && len > b + && b as usize >= state.tail.len() + { + let mut end = vec![0; state.tail.len()]; + use std::io::{Read, Seek, SeekFrom}; + let mut f = &file; + f.seek(SeekFrom::Start(b - state.tail.len() as u64)) + .and_then(|_| f.read_exact(&mut end)) + .map_err(disk)?; + if end == state.tail { + file.set_len(b).map_err(disk)?; + len = b; + } + } + let tail = if len == state.bytes.unwrap_or(u64::MAX) { + std::mem::take(&mut state.tail) + } else { + Vec::new() + }; + Ok(Writer { + path: path.to_owned(), + file: std::io::BufWriter::new(file), + state, + added: 0, + len, + tail, + }) + } + + fn game(&mut self, pgn: &str) -> Result<(), Failure> { + let pgn = pgn.trim(); + if pgn.is_empty() { + return Ok(()); + } + for part in [pgn.as_bytes(), b"\n\n"] { + self.file + .write_all(part) + .map_err(|e| Failure::Disk(e.to_string()))?; + self.len += part.len() as u64; + self.tail.extend_from_slice(part); + } + if self.tail.len() > TAIL { + self.tail.drain(..self.tail.len() - TAIL); + } + self.added += 1; + self.state.games += 1; + Ok(()) + } + + /// Makes what was written durable, the state last (it never runs ahead of the file). + fn commit(&mut self) -> Result<(), Failure> { + self.file + .flush() + .map_err(|e| Failure::Disk(e.to_string()))?; + self.state.bytes = Some(self.len); + self.state.tail = self.tail.clone(); + self.state.save(&self.path) + } + + fn done(mut self, cancelled: bool) -> Result { + if !cancelled { + self.state.updated = Some(now_secs()); + } + self.commit()?; + Ok(Done { + path: self.path, + added: self.added, + total: self.state.games, + cancelled, + }) + } +} + +/// Fetches the games of `accounts` new since the last run into the database at `path` +/// (one database for all of them); `progress` counts the games added, `status` tells +/// what is being fetched. Cancelling keeps what was fetched. One download per database +/// at a time ([`Failure::Busy`] otherwise). +pub fn download( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let _claim = Claim::take(path).ok_or(Failure::Busy)?; + // Another ChessPenguin running may download into the same database: a file lock + // (released when the file closes, also if the process dies). + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(|e| Failure::Disk(e.to_string()))?; + } + let lock = std::fs::File::create(path.with_extension("online.lock")) + .map_err(|e| Failure::Disk(e.to_string()))?; + if let Err(e) = lock.try_lock() { + return Err(match e { + std::fs::TryLockError::WouldBlock => Failure::Busy, + std::fs::TryLockError::Error(e) => Failure::Disk(e.to_string()), + }); + } + let path = path.to_owned(); + let mut state = State::load(&path) + // The games are gone (the file was deleted): fetch them again. + .filter(|s| path.exists() || s.games == 0) + .unwrap_or_else(|| { + // A database without its state: start it anew rather than append duplicates. + let _ = std::fs::remove_file(&path); + State::default() + }); + // Accounts not in the database yet start from their first game. + for a in accounts { + if !state.holds(a) { + state.accounts.push(AccountState { + platform: Some(a.platform), + username: a.username.clone(), + ..AccountState::default() + }); + } + } + let mut w = Writer::open(&path, state)?; + let mut result = Ok(false); + for i in 0..w.state.accounts.len() { + let Some(k) = accounts.iter().position(|a| w.state.accounts[i].is(a)) else { + continue; + }; + status.account.store(k, Ordering::Relaxed); + status.games.store(0, Ordering::Relaxed); + result = match w.state.accounts[i].platform { + Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel, status), + Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status), + None => Ok(false), + }; + if !matches!(result, Ok(false)) { + break; + } + } + match result { + Ok(c) => w.done(c), + Err(e) => { + // Keep what arrived before the failure; the next update continues. + let _ = w.commit(); + Err(e) + } + } +} + +#[cfg(test)] +fn download_to( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + download(accounts, path, progress, cancel, &Progress::default()) +} + +/// Lichess's answer for one game, as far as the download cares. +struct LichessGame<'a> { + id: &'a str, + created: i64, + /// Still being played (not exported as a game yet). + playing: bool, + standard: bool, + /// Present for finished games (an unfinished one may come without it). + pgn: Option<&'a str>, +} + +fn lichess_game(v: &Value) -> Option> { + let g = LichessGame { + id: v["id"].as_str()?, + created: v["createdAt"].as_i64()?, + playing: matches!(v["status"].as_str(), Some("created" | "started")), + standard: v["variant"] + .as_str() + .is_none_or(|x| x == "standard" || x == "fromPosition"), + pgn: v["pgn"].as_str(), + }; + (g.playing || g.pgn.is_some()).then_some(g) +} + +/// Whether to write a game of the Lichess export; an unfinished one is remembered as +/// pending instead (asked about by id next time), a pending one that ended is written. +fn lichess_keep(a: &mut AccountState, g: &LichessGame) -> bool { + let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id); + if g.playing { + if pending.is_none() && g.standard { + a.lichess_pending.push((g.id.to_owned(), g.created)); + } + return false; + } + if let Some(k) = pending { + a.lichess_pending.remove(k); + } + g.standard +} + +/// A pending game Lichess no longer returns is given up after a year. +const PENDING_DAYS: i64 = 365; + +/// Reads a Lichess NDJSON answer line by line. `Ok(true)` when cancelled. +fn lichess_lines( + resp: ureq::http::Response, + cancel: &AtomicBool, + mut each: impl FnMut(usize, &Value) -> Result<(), Failure>, +) -> Result { + match resp.status().as_u16() { + 200 => {} + 429 => return Err(Failure::RateLimited), + code => return Err(Failure::Unexpected(format!("HTTP {code}"))), + } + let reader = BufReader::new(resp.into_body().into_reader()); + for (n, line) in reader.lines().enumerate() { + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let line = line.map_err(|e| Failure::Network(e.to_string()))?; + if line.trim().is_empty() { + continue; + } + let v: Value = + serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; + each(n, &v)?; + } + Ok(false) +} + +const LICHESS_PARAMS: &str = "pgnInJson=true&clocks=false&evals=false&opening=true"; + +/// The games of account `i` of the writer's database from Lichess: first the pending +/// (unfinished last time) ones by id, then the new ones. `Ok(true)` when cancelled. +fn lichess( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let write = |w: &mut Writer, v: &Value| -> Result { + let g = lichess_game(v) + .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; + if lichess_keep(&mut w.state.accounts[i], &g) + && let Some(pgn) = g.pgn + { + let pgn = pgn.to_owned(); + w.game(&pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + } + Ok(g.created) + }; + let pending: Vec = w.state.accounts[i] + .lichess_pending + .iter() + .map(|(id, _)| id.clone()) + .collect(); + for chunk in pending.chunks(300) { + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .post(&format!( + "https://lichess.org/api/games/export/_ids?{LICHESS_PARAMS}" + )) + .header("Accept", "application/x-ndjson") + .send(chunk.join(",")) + })?; + if lichess_lines(resp, cancel, |_, v| write(w, v).map(|_| ()))? { + return Ok(true); + } + } + let year_ago = now_secs() * 1000 - PENDING_DAYS * 86_400_000; + w.state.accounts[i] + .lichess_pending + .retain(|(_, created)| *created > year_ago); + w.commit()?; + + let a = &w.state.accounts[i]; + let mut url = format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&{LICHESS_PARAMS}", + a.username + ); + if let Some(last) = a.lichess_last { + url.push_str(&format!("&since={}", last + 1)); + } + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .get(&url) + .header("Accept", "application/x-ndjson") + .call() + })?; + lichess_lines(resp, cancel, |n, v| { + let created = write(w, v)?; + let a = &mut w.state.accounts[i]; + a.lichess_last = Some(a.lichess_last.map_or(created, |l| l.max(created))); + if n % 100 == 99 { + w.commit()?; + } + Ok(()) + }) +} + +/// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when +/// cancelled. +fn chesscom( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let lower = w.state.accounts[i].username.to_ascii_lowercase(); + let months = archives(&lower)?; + status.months_total.store(months.len(), Ordering::Relaxed); + status.months_done.store(0, Ordering::Relaxed); + for url in months { + status.months_done.fetch_add(1, Ordering::Relaxed); + // ".../games/2026/10" → "2026/10"; months before the last fetched are done. + let month = url.rsplitn(3, '/').take(2).collect::>(); + let month = format!( + "{}/{}", + month.get(1).unwrap_or(&""), + month.first().unwrap_or(&"") + ); + let a = &w.state.accounts[i]; + if a.chesscom_month.as_ref().is_some_and(|m| month < *m) { + continue; + } + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let v = json(&url)?.ok_or_else(|| Failure::Unexpected(format!("{month}: not found")))?; + let games = v["games"] + .as_array() + .ok_or_else(|| Failure::Unexpected(format!("{month}: no games")))?; + let mut list: Vec<(i64, &str)> = games + .iter() + .filter(|g| g["rules"] == "chess") + .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) + .collect(); + list.sort_by_key(|(t, _)| *t); + let a = &w.state.accounts[i]; + let same_month = a.chesscom_month.as_deref() == Some(month.as_str()); + let last = if same_month { + a.chesscom_last_end + } else { + None + }; + for (end, pgn) in list { + if last.is_some_and(|l| end <= l) { + continue; + } + w.game(pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + w.state.accounts[i].chesscom_last_end = Some(end); + } + // The mark moves to this month even when it had no standard games (the end + // time then still belongs to an earlier month and is not compared). + w.state.accounts[i].chesscom_month = Some(month); + w.commit()?; + } + Ok(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("cp-online-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn account(p: Platform, name: &str) -> Account { + Account { + platform: p, + username: name.into(), + games: None, + months: None, + } + } + + const GAME: &str = "[Event \"x\"]\n\n1. e4 e5 1-0"; + + #[test] + fn a_crash_leaves_no_duplicates() { + let dir = temp_dir("crash"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + ..AccountState::default() + }], + ..State::default() + }; + let mut w = Writer::open(&path, state).unwrap(); + w.game(GAME).unwrap(); + w.game(GAME).unwrap(); + w.commit().unwrap(); + let good = std::fs::read(&path).unwrap(); + // Games written after the last commit, then the process died. + w.game(GAME).unwrap(); + w.file.flush().unwrap(); + drop(w); + assert!(std::fs::read(&path).unwrap().len() > good.len()); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + assert_eq!(w.state.games, 2); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), good, "cut back to the state"); + + // Somebody else changed the file: it is left alone. + let mut other = good.clone(); + other[0] = b' '; + other.extend_from_slice(GAME.as_bytes()); + std::fs::write(&path, &other).unwrap(); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), other); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_deleted_database_is_downloaded_again() { + let dir = temp_dir("deleted"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + lichess_last: Some(5), + ..AccountState::default() + }], + games: 7, + ..State::default() + }; + state.save(&path).unwrap(); + let never = AtomicBool::new(false); + // No account asked for: nothing fetched, only the state put right. + let d = download_to(&[], &path, &AtomicUsize::new(0), &never).unwrap(); + assert_eq!(d.total, 0); + let s = State::load(&path).unwrap_or_default(); + assert!(s.accounts.iter().all(|a| a.lichess_last.is_none())); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn one_download_per_database() { + let path = PathBuf::from("/nonexistent/cp-claim.pgn"); + let first = Claim::take(&path).expect("free"); + assert!(Claim::take(&path).is_none()); + let never = AtomicBool::new(false); + assert_eq!( + download_to(&[], &path, &AtomicUsize::new(0), &never), + Err(Failure::Busy) + ); + drop(first); + assert!(Claim::take(&path).is_some()); + } + + #[test] + fn names_of_merged_databases() { + let name = |a: &[Account]| { + combined_path(Path::new("/online"), a) + .unwrap() + .file_name() + .unwrap() + .to_string_lossy() + .into_owned() + }; + let li = account(Platform::Lichess, "Magnus"); + assert_eq!(name(std::slice::from_ref(&li)), "Magnus (Lichess).pgn"); + let cc = account(Platform::ChessCom, "magnus"); + assert_eq!(name(&[li.clone(), cc]), "Magnus (Lichess + Chess.com).pgn"); + let other = account(Platform::ChessCom, "MagnusCarlsen"); + assert_eq!( + name(&[li, other]), + "Magnus (Lichess) + MagnusCarlsen (Chess.com).pgn" + ); + } + + #[test] + fn unfinished_lichess_games_come_later() { + let mut a = AccountState::default(); + let g = |id: &'static str, playing: bool| LichessGame { + id, + created: 10, + playing, + standard: true, + pgn: (!playing).then_some("1. e4 *"), + }; + // First run: a correspondence game is still on, another one is over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert!(lichess_keep(&mut a, &g("blitz", false))); + assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); + // Asked about by id: still on, then over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert_eq!(a.lichess_pending.len(), 1); + assert!(lichess_keep(&mut a, &g("corr", false))); + assert!(a.lichess_pending.is_empty()); + // A variant game is neither kept nor waited for. + let mut v = g("960", true); + v.standard = false; + assert!(!lichess_keep(&mut a, &v)); + assert!(a.lichess_pending.is_empty()); + // An unfinished game may come without its PGN, a finished one may not. + let json = |s: &str| serde_json::from_str::(s).unwrap(); + let on = json(r#"{"id":"a","createdAt":1,"status":"started"}"#); + assert!(lichess_game(&on).is_some_and(|g| g.playing)); + let over = json(r#"{"id":"a","createdAt":1,"status":"mate"}"#); + assert!(lichess_game(&over).is_none()); + } + + /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of + /// the repository): lookup, an interrupted Lichess download continued without gaps + /// or duplicates, a full Chess.com download, and an update that adds nothing. Run + /// with `CP_ONLINE_NICK= cargo test -p online-games online_live -- --ignored --nocapture`. + #[test] + #[ignore] + fn online_live() { + let Ok(nick) = std::env::var("CP_ONLINE_NICK") else { + eprintln!("skipped: no CP_ONLINE_NICK"); + return; + }; + assert_eq!(probe_all(), [true, true], "both platforms answer"); + assert_eq!( + lookup(Platform::Lichess, "no-such-player-cp-x9"), + Lookup::NotFound + ); + let dir = std::env::temp_dir().join(format!("cp-online-live-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let read_db = |path: &Path| { + let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) + .expect("opens"); + let mut sites = Vec::new(); + let mut problems = 0; + for i in 0..db.len() { + let g = db.load_game(i).expect("game"); + problems += usize::from(!g.diagnostics.is_empty()); + let e = &db.entries()[i]; + let site = e.tag("Link").or_else(|| e.tag("Site")).unwrap_or_default(); + sites.push(site.to_owned()); + } + (db.len(), sites, problems) + }; + + // Lichess: stop after about 150 games, twice, then compare with what the + // site says about those games: no gaps, no duplicates. + let Lookup::Found(li) = lookup(Platform::Lichess, &nick) else { + panic!("not on Lichess"); + }; + let path = dir.join("li.pgn"); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let done = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(std::slice::from_ref(&li), &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("lichess round {round}: {done:?}"); + assert!(done.cancelled && done.added >= 150); + } + let (n, sites, problems) = read_db(&path); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + assert_eq!(State::load(&path).unwrap().games as usize, n); + eprintln!("lichess: {n} games after two interrupted runs, {problems} with diagnostics"); + // The same games as one uninterrupted request for that many. + let (code, body) = get(&format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&max={n}\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&moves=false", + li.username + )) + .expect("answers"); + assert_eq!(code, 200); + // Asked for JSON, Lichess answers one game per line. + let expected: Vec = body + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) + .collect(); + // Ours are the reference's first games, in its order (the reference may hold a + // few more: Lichess does not count `max` exactly as we count games). + if expected.len() < sites.len() || sites[..] != expected[..sites.len()] { + let only_ours: Vec<_> = sites.iter().filter(|x| !expected.contains(x)).collect(); + let only_ref: Vec<_> = expected.iter().filter(|x| !sites.contains(x)).collect(); + let first = sites.iter().zip(&expected).position(|(a, b)| a != b); + panic!( + "differ: first at {first:?}, ours {} ref {}, only ours {only_ours:?}, only in the reference {only_ref:?}", + sites.len(), + expected.len() + ); + } + + // Chess.com: everything, then an update that finds nothing new. + let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { + panic!("not on Chess.com"); + }; + let path = dir.join("cc.pgn"); + let never = AtomicBool::new(false); + let done = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("downloads"); + eprintln!("chess.com: {done:?}"); + assert!(!done.cancelled && done.total > 0); + let again = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("updates"); + assert_eq!((again.added, again.total), (0, done.total)); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, done.total); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + eprintln!("chess.com: {n} games, {problems} with diagnostics"); + + // Both into one database: Chess.com whole, then Lichess stopped twice; the + // second run adds Lichess games only, without duplicates. + let path = dir.join("both.pgn"); + let accounts = [cc.clone(), li.clone()]; + let mut totals = Vec::new(); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let goal = if round == 1 { + done.total as usize + 100 + } else { + 100 + }; + let d = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < goal && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(&accounts, &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("both, round {round}: {d:?}"); + assert!(d.cancelled); + totals.push(d.total); + } + let state = State::load(&path).unwrap(); + assert_eq!(state.accounts.len(), 2); + assert_eq!(state.accounts[0].platform, Some(Platform::ChessCom)); + assert!(state.accounts[0].chesscom_month.is_some()); + assert!(state.accounts[1].lichess_last.is_some()); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, totals[1]); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + let chesscom = sites.iter().filter(|s| s.contains("chess.com")).count() as u64; + assert_eq!(chesscom, done.total, "all of Chess.com, once"); + eprintln!("both: {n} games ({chesscom} from Chess.com), {problems} with diagnostics"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn probe_answers() { + let li: Value = serde_json::from_str( + r#"{"id":"lichess","username":"Lichess","count":{"all":0,"rated":0}}"#, + ) + .unwrap(); + assert!(probe_answer_ok(Platform::Lichess, &li)); + // A changed API (renamed or missing fields) is not offered. + let changed: Value = + serde_json::from_str(r#"{"id":"lichess","username":"Lichess","games":0}"#).unwrap(); + assert!(!probe_answer_ok(Platform::Lichess, &changed)); + let cc: Value = + serde_json::from_str(r#"{"player_id":41,"username":"erik","status":"staff"}"#).unwrap(); + assert!(probe_answer_ok(Platform::ChessCom, &cc)); + let html = Value::String("maintenance".into()); + assert!(!probe_answer_ok(Platform::ChessCom, &html)); + assert!(!probe_answer_ok(Platform::Lichess, &html)); + } + + #[test] + fn nicknames() { + assert!(valid_nick("Magnus_C-1")); + assert!(!valid_nick("a")); + assert!(!valid_nick("bad nick")); + assert!(!valid_nick("../etc")); + assert!(!valid_nick(&"x".repeat(31))); + } + + #[test] + fn state_round_trip() { + let dir = std::env::temp_dir().join(format!("cp-online-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let pgn = dir.join("Someone (Lichess).pgn"); + let s = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "Someone".into(), + lichess_last: Some(1_700_000_000_000), + ..AccountState::default() + }], + games: 3, + ..State::default() + }; + s.save(&pgn).unwrap(); + assert_eq!(State::load(&pgn), Some(s)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/openings/Cargo.toml b/crates/openings/Cargo.toml new file mode 100644 index 0000000..d54a971 --- /dev/null +++ b/crates/openings/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "chess-openings" +description = "Opening names of ChessPenguin: the Lichess chess-openings table (CC0), looked up by position; also tells a book move" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +shakmaty.workspace = true +serde.workspace = true + +[dev-dependencies] +chess-import.workspace = true diff --git a/crates/openings/data/a.tsv b/crates/openings/data/a.tsv new file mode 100644 index 0000000..5610998 --- /dev/null +++ b/crates/openings/data/a.tsv @@ -0,0 +1,824 @@ +eco name pgn +A00 Amar Opening 1. Nh3 +A00 Amar Opening: Paris Gambit 1. Nh3 d5 2. g3 e5 3. f4 +A00 Amar Opening: Paris Gambit, Gent Gambit 1. Nh3 d5 2. g3 e5 3. f4 Bxh3 4. Bxh3 exf4 5. O-O fxg3 6. hxg3 +A00 Amsterdam Attack 1. e3 e5 2. c4 d6 3. Nc3 Nc6 4. b3 Nf6 +A00 Anderssen's Opening 1. a3 +A00 Anderssen's Opening: Polish Gambit 1. a3 a5 2. b4 +A00 Barnes Opening 1. f3 +A00 Barnes Opening: Fool's Mate 1. f3 e5 2. g4 Qh4# +A00 Barnes Opening: Gedult Gambit 1. f3 d5 2. e4 g6 3. d4 dxe4 4. c3 +A00 Barnes Opening: Gedult Gambit 1. f3 f5 2. e4 fxe4 3. Nc3 +A00 Barnes Opening: Hammerschlag 1. f3 e5 2. Kf2 +A00 Clemenz Opening 1. h3 +A00 Clemenz Opening: Spike Lee Gambit 1. h3 h5 2. g4 +A00 Creepy Crawly Formation: Classical Defense 1. h3 d5 2. a3 e5 +A00 Formation: Hippopotamus Attack 1. a3 e5 2. b3 d5 3. c3 Nf6 4. d3 Nc6 5. e3 Bd6 6. f3 O-O 7. g3 +A00 Formation: Shy Attack 1. a3 e5 2. g3 d5 3. Bg2 Nf6 4. d3 Nc6 5. Nd2 Bd6 6. e3 O-O 7. h3 +A00 Global Opening 1. h3 e5 2. a3 +A00 Grob Opening 1. g4 +A00 Grob Opening: Alessi Gambit 1. g4 f5 +A00 Grob Opening: Double Grob 1. g4 g5 +A00 Grob Opening: Double Grob, Coca-Cola Gambit 1. g4 g5 2. f4 +A00 Grob Opening: Grob Gambit 1. g4 d5 2. Bg2 +A00 Grob Opening: Grob Gambit Declined 1. g4 d5 2. Bg2 c6 +A00 Grob Opening: Grob Gambit, Basman Gambit 1. g4 d5 2. Bg2 h5 3. gxh5 +A00 Grob Opening: Grob Gambit, Fritz Gambit 1. g4 d5 2. Bg2 Bxg4 3. c4 +A00 Grob Opening: Grob Gambit, Fritz Gambit, Romford Countergambit 1. g4 d5 2. Bg2 Bxg4 3. c4 d4 4. Bxb7 Nd7 5. Bxa8 Qxa8 +A00 Grob Opening: Grob Gambit, Keres Gambit 1. g4 d5 2. Bg2 e5 3. d4 exd4 4. c3 +A00 Grob Opening: Grob Gambit, Richter-Grob Gambit 1. g4 d5 2. Bg2 c6 3. c4 dxc4 4. b3 +A00 Grob Opening: Keene Defense 1. g4 d5 2. h3 e5 3. Bg2 c6 +A00 Grob Opening: Keene Defense, Main Line 1. g4 d5 2. h3 e5 3. Bg2 c6 4. d4 e4 5. c4 Bd6 6. Nc3 Ne7 +A00 Grob Opening: London Defense 1. g4 e5 2. h3 Nc6 +A00 Grob Opening: Romford Countergambit 1. g4 d5 2. Bg2 Bxg4 3. c4 d4 +A00 Grob Opening: Spike Attack 1. g4 d5 2. Bg2 c6 3. g5 +A00 Grob Opening: Spike, Hurst Attack 1. g4 e5 2. Bg2 d5 3. c4 +A00 Grob Opening: Zilbermints Gambit 1. g4 d5 2. e4 dxe4 3. Nc3 +A00 Grob Opening: Zilbermints Gambit, Schiller Defense 1. g4 d5 2. e4 dxe4 3. Nc3 h5 +A00 Grob Opening: Zilbermints Gambit, Zilbermints-Hartlaub Gambit 1. g4 d5 2. e4 dxe4 3. Nc3 e5 4. d3 +A00 Hungarian Opening 1. g3 +A00 Hungarian Opening: Asten Gambit 1. g3 Nc6 2. Nc3 d5 3. d4 e5 4. dxe5 d4 5. Ne4 f5 +A00 Hungarian Opening: Burk Gambit 1. g3 e5 2. a3 d5 3. Nf3 e4 4. Nh4 Be7 5. d3 +A00 Hungarian Opening: Bücker Gambit 1. g3 d5 2. Bg2 e5 3. b4 +A00 Hungarian Opening: Catalan Formation 1. g3 d5 2. Bg2 e6 +A00 Hungarian Opening: Dutch Defense 1. g3 f5 +A00 Hungarian Opening: Indian Defense 1. g3 Nf6 +A00 Hungarian Opening: Myers Defense 1. g3 g5 +A00 Hungarian Opening: Pachman Gambit 1. g3 f5 2. e4 fxe4 3. Qh5+ g6 +A00 Hungarian Opening: Paris Gambit 1. g3 e5 2. Nh3 d5 3. f4 Bxh3 4. Bxh3 exf4 5. O-O +A00 Hungarian Opening: Reversed Alekhine 1. g3 e5 2. Nf3 +A00 Hungarian Opening: Reversed Brooklyn Defense, Brooklyn Benko Gambit 1. g3 e5 2. Nf3 e4 3. Ng1 Nf6 4. b4 +A00 Hungarian Opening: Reversed Modern Defense 1. g3 d5 2. Bg2 c5 +A00 Hungarian Opening: Reversed Norwegian Defense 1. g3 e5 2. Nf3 e4 3. Nh4 +A00 Hungarian Opening: Sicilian Invitation 1. g3 c5 +A00 Hungarian Opening: Slav Formation 1. g3 d5 2. Bg2 c6 +A00 Hungarian Opening: Symmetrical Variation 1. g3 g6 +A00 Hungarian Opening: Van Kuijk Gambit 1. g3 h5 2. Nf3 h4 +A00 Hungarian Opening: Winterberg Gambit 1. g3 d5 2. Bg2 e5 3. c4 dxc4 4. b3 +A00 Kádas Opening 1. h4 +A00 Kádas Opening: Beginner's Trap 1. h4 d5 2. Rh3 +A00 Kádas Opening: Koola-Koola Variation 1. h4 a5 +A00 Kádas Opening: Kádas Gambit 1. h4 c5 2. b4 +A00 Kádas Opening: Kádas Gambit 1. h4 d5 2. d4 c5 3. Nf3 cxd4 4. c3 +A00 Kádas Opening: Kádas Gambit 1. h4 e5 2. d4 exd4 3. c3 +A00 Kádas Opening: Myers Variation 1. h4 d5 2. d4 c5 3. e4 +A00 Kádas Opening: Schneider Gambit 1. h4 g5 +A00 Kádas Opening: Steinbok Gambit 1. h4 f5 2. e4 fxe4 3. d3 +A00 Lasker Simul Special 1. g3 h5 +A00 Mieses Opening 1. d3 +A00 Mieses Opening: Myers Spike Attack 1. d3 g6 2. g4 +A00 Mieses Opening: Reversed Rat 1. d3 e5 +A00 Mieses Opening: Venezolana Variation 1. d3 c5 2. Nc3 Nc6 3. g3 +A00 Polish Opening 1. b4 +A00 Polish Opening, with d5 1. b4 d5 +A00 Polish Opening, with d5 1. b4 d5 2. Bb2 Nf6 3. Nf3 +A00 Polish Opening: Baltic Defense 1. b4 d5 2. Bb2 Bf5 +A00 Polish Opening: Birmingham Gambit 1. b4 c5 +A00 Polish Opening: Bugayev Advance Variation 1. b4 e5 2. Bb2 f6 3. b5 +A00 Polish Opening: Bugayev Attack 1. b4 e5 2. a3 +A00 Polish Opening: Czech Defense 1. b4 e5 2. Bb2 d6 +A00 Polish Opening: Dutch Defense 1. b4 f5 +A00 Polish Opening: German Defense 1. b4 d5 2. Bb2 Qd6 +A00 Polish Opening: Grigorian Variation 1. b4 Nc6 +A00 Polish Opening: Karniewski Variation 1. b4 Nh6 +A00 Polish Opening: King's Indian Variation 1. b4 Nf6 2. Bb2 g6 +A00 Polish Opening: King's Indian Variation, Schiffler Attack 1. b4 Nf6 2. Bb2 g6 3. e4 +A00 Polish Opening: King's Indian Variation, Sokolsky Attack 1. b4 Nf6 2. Bb2 g6 3. c4 Bg7 4. e3 d6 5. Nf3 O-O 6. d4 +A00 Polish Opening: Myers Variation 1. b4 d5 2. Bb2 c6 3. a4 +A00 Polish Opening: Outflank Variation 1. b4 c6 +A00 Polish Opening: Outflank Variation, Schuehler Gambit 1. b4 c6 2. Bb2 a5 3. b5 +A00 Polish Opening: Queen's Indian Variation 1. b4 e6 2. Bb2 Nf6 3. b5 b6 +A00 Polish Opening: Queenside Defense 1. b4 e6 2. Bb2 Nf6 3. b5 a6 +A00 Polish Opening: Rooks Swap Line 1. b4 e6 2. Bb2 Nf6 3. b5 a6 4. a4 axb5 5. axb5 Rxa1 6. Bxa1 +A00 Polish Opening: Schiffler-Sokolsky Variation 1. b4 e6 2. Bb2 Nf6 3. b5 d5 4. e3 +A00 Polish Opening: Schuehler Gambit 1. b4 c6 2. Bb2 a5 3. b5 cxb5 4. e4 +A00 Polish Opening: Symmetrical Variation 1. b4 b5 +A00 Polish Opening: Tartakower Gambit 1. b4 e5 2. Bb2 f6 3. e4 +A00 Polish Opening: Wolferts Gambit 1. b4 e5 2. Bb2 c5 +A00 Saragossa Opening 1. c3 +A00 Sodium Attack 1. Na3 +A00 Sodium Attack: Celadon Variation 1. Na3 e5 2. d3 Bxa3 3. bxa3 d5 4. e3 c5 5. Rb1 +A00 Sodium Attack: Chenoboskion Variation 1. Na3 g6 2. g4 +A00 Sodium Attack: Durkin Gambit 1. Na3 e5 2. Nc4 Nc6 3. e4 f5 +A00 Valencia Opening 1. d3 e5 2. Nd2 +A00 Van Geet Opening 1. Nc3 +A00 Van Geet Opening: Battambang Variation 1. a3 e5 2. Nc3 +A00 Van Geet Opening: Billockus-Johansen Gambit 1. Nc3 e5 2. Nf3 Bc5 +A00 Van Geet Opening: Damhaug Gambit 1. Nc3 d5 2. f4 e5 +A00 Van Geet Opening: Dougherty Gambit 1. Nc3 d5 2. e4 dxe4 3. f3 +A00 Van Geet Opening: Dunst-Perrenet Gambit 1. Nc3 d5 2. e4 dxe4 3. d3 +A00 Van Geet Opening: Düsseldorf Gambit 1. Nc3 c5 2. b4 +A00 Van Geet Opening: Gladbacher Gambit 1. Nc3 e5 2. b3 d5 3. e4 dxe4 4. d3 +A00 Van Geet Opening: Hector Gambit 1. Nc3 d5 2. e4 dxe4 3. Bc4 +A00 Van Geet Opening: Hergert Gambit 1. Nc3 d6 2. f4 e5 3. fxe5 Nc6 +A00 Van Geet Opening: Hulsemann Gambit 1. Nc3 e5 2. e3 d5 3. Qh5 Be6 +A00 Van Geet Opening: Jendrossek Gambit 1. Nc3 d5 2. f4 d4 3. Ne4 f5 4. Nf2 Nf6 5. Nf3 c5 6. b4 +A00 Van Geet Opening: Kluever Gambit 1. Nc3 f5 2. e4 fxe4 3. d3 +A00 Van Geet Opening: Laroche Gambit 1. Nc3 b5 +A00 Van Geet Opening: Liebig Gambit 1. Nc3 e5 2. e3 d5 3. Qh5 Nf6 +A00 Van Geet Opening: Melleby Gambit 1. Nc3 d5 2. f4 d4 3. Ne4 c5 +A00 Van Geet Opening: Myers Attack 1. Nc3 g6 2. h4 +A00 Van Geet Opening: Napoleon Attack 1. Nc3 e5 2. Nf3 Nc6 3. d4 +A00 Van Geet Opening: Novosibirsk Variation 1. Nc3 c5 2. d4 cxd4 3. Qxd4 Nc6 4. Qh4 +A00 Van Geet Opening: Nowokunski Gambit 1. Nc3 e5 2. f4 exf4 3. e4 +A00 Van Geet Opening: Pfeiffer Gambit 1. Nc3 d5 2. f4 d4 3. Ne4 e5 +A00 Van Geet Opening: Pfeiffer Gambit, Sleipnir Countergambit 1. Nc3 d5 2. f4 d4 3. Ne4 e5 4. Nf3 +A00 Van Geet Opening: Reversed Nimzowitsch 1. Nc3 e5 +A00 Van Geet Opening: Reversed Scandinavian 1. Nc3 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qa4 +A00 Van Geet Opening: Sicilian Two Knights 1. Nc3 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 +A00 Van Geet Opening: Sleipnir Gambit 1. Nc3 d5 2. e3 e5 3. d4 Bb4 +A00 Van Geet Opening: Twyble Attack 1. Nc3 c5 2. Rb1 +A00 Van Geet Opening: Tübingen Gambit 1. Nc3 Nf6 2. g4 +A00 Van Geet Opening: Venezolana Variation 1. Nc3 d5 2. d3 Nf6 3. g3 +A00 Van Geet Opening: Warsteiner Gambit 1. Nc3 d5 2. f4 g5 +A00 Van't Kruijs Opening 1. e3 +A00 Van't Kruijs Opening: Bouncing Bishop Variation 1. e3 e5 2. Bc4 b5 3. Bb3 +A00 Van't Kruijs Opening: Keoni-Hiva Gambit, Akahi Variation 1. e3 e5 2. Nc3 Nf6 3. f4 exf4 4. Nf3 +A00 Van't Kruijs Opening: Keoni-Hiva Gambit, Alua Variation 1. e3 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 +A00 Van't Kruijs Opening: Keoni-Hiva Gambit, Ekolu Variation 1. e3 e5 2. Nc3 d5 3. f4 exf4 4. Nf3 +A00 Ware Opening 1. a4 +A00 Ware Opening: Cologne Gambit 1. a4 b6 2. d4 d5 3. Nc3 Nd7 +A00 Ware Opening: Crab Variation 1. a4 e5 2. h4 +A00 Ware Opening: Meadow Hay Trap 1. a4 e5 2. Ra3 +A00 Ware Opening: Symmetric Variation 1. a4 a5 +A00 Ware Opening: Ware Gambit 1. a4 e5 2. a5 d5 3. e3 f5 4. a6 +A00 Ware Opening: Wing Gambit 1. a4 b5 2. axb5 Bb7 +A01 Nimzo-Larsen Attack 1. b3 +A01 Nimzo-Larsen Attack: Classical Variation 1. b3 d5 +A01 Nimzo-Larsen Attack: Dutch Variation 1. b3 f5 +A01 Nimzo-Larsen Attack: English Variation 1. b3 c5 +A01 Nimzo-Larsen Attack: Graz Attack 1. b3 d5 2. Ba3 +A01 Nimzo-Larsen Attack: Indian Variation 1. b3 Nf6 +A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 +A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 2. Bb2 Nc6 +A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 2. Bb2 Nc6 3. e3 +A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 2. Bb2 Nc6 3. c4 Nf6 +A01 Nimzo-Larsen Attack: Pachman Gambit 1. b3 e5 2. Bb2 Nc6 3. f4 +A01 Nimzo-Larsen Attack: Polish Variation 1. b3 b5 +A01 Nimzo-Larsen Attack: Ringelbach Gambit 1. b3 f5 2. Bb2 e6 3. e4 +A01 Nimzo-Larsen Attack: Spike Variation 1. b3 Nf6 2. Bb2 g6 3. g4 +A01 Nimzo-Larsen Attack: Symmetrical Variation 1. b3 b6 +A02 Bird Opening 1. f4 +A02 Bird Opening: Batavo-Polish Attack 1. f4 Nf6 2. Nf3 g6 3. b4 +A02 Bird Opening: Double Duck Formation 1. f4 f5 2. d4 d5 +A02 Bird Opening: From's Gambit 1. f4 e5 +A02 Bird Opening: From's Gambit, Bahr Gambit 1. f4 e5 2. Nc3 +A02 Bird Opening: From's Gambit, Langheld Gambit 1. f4 e5 2. fxe5 d6 3. exd6 Nf6 +A02 Bird Opening: From's Gambit, Lasker Variation 1. f4 e5 2. fxe5 d6 3. exd6 Bxd6 4. Nf3 g5 +A02 Bird Opening: From's Gambit, Lipke Variation 1. f4 e5 2. fxe5 d6 3. exd6 Bxd6 4. Nf3 Nh6 5. d4 +A02 Bird Opening: Hobbs Gambit 1. f4 g5 +A02 Bird Opening: Hobbs-Zilbermints Gambit 1. f4 h6 2. Nf3 g5 +A02 Bird Opening: Horsefly Defense 1. f4 Nh6 +A02 Bird Opening: Lasker Gambit 1. f4 e5 2. fxe5 f6 +A02 Bird Opening: Mujannah 1. f4 Nf6 2. c4 +A02 Bird Opening: Myers Defense 1. f4 b5 +A02 Bird Opening: Platz Gambit 1. f4 e5 2. fxe5 Ne7 +A02 Bird Opening: Schlechter Gambit 1. f4 e5 2. fxe5 Nc6 +A02 Bird Opening: Siegener Gambit 1. f4 e5 2. d4 exd4 3. Nf3 c5 4. c3 +A02 Bird Opening: Swiss Gambit 1. f4 f5 2. e4 fxe4 3. Nc3 Nf6 4. g4 +A02 Bird Opening: Wagner-Zwitersch Gambit 1. f4 f5 2. e4 +A03 Bird Opening: Dutch Variation 1. f4 d5 +A03 Bird Opening: Dutch Variation, Dudweiler Gambit 1. f4 d5 2. g4 +A03 Bird Opening: Lasker Variation 1. f4 d5 2. Nf3 Nf6 3. e3 c5 +A03 Bird Opening: Sturm Gambit 1. f4 d5 2. c4 +A03 Bird Opening: Thomas Gambit 1. f4 d5 2. b3 Nf6 3. Bb2 d4 4. Nf3 c5 5. e3 +A03 Bird Opening: Williams Gambit 1. f4 d5 2. e4 +A03 Bird Opening: Williams Gambit 1. f4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Qe2 +A03 Bird Opening: Williams-Zilbermints Gambit 1. f4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Nge2 +A04 Colle System: Rhamphorhynchus Variation 1. Nf3 c5 2. e3 g6 3. d4 Bg7 4. dxc5 Qa5+ +A04 Modern Defense: Semi-Averbakh Variation, Polish Variation 1. Nf3 c5 2. c4 g6 3. d4 Bg7 4. e4 Qb6 +A04 Modern Defense: Semi-Averbakh Variation, Pterodactyl Variation 1. Nf3 c5 2. c4 g6 3. d4 Bg7 4. e4 Qa5+ +A04 Modern Defense: Semi-Averbakh Variation, Pterodactyl Variation Accepted 1. Nf3 g6 2. d4 Bg7 3. e4 d6 4. c4 c5 5. dxc5 Qa5+ +A04 Zukertort Defense: Kingside Variation 1. Nf3 Nh6 2. d4 g6 +A04 Zukertort Defense: Sicilian Knight Variation 1. Nf3 Na6 2. e4 c5 +A04 Zukertort Opening 1. Nf3 +A04 Zukertort Opening: Arctic Defense 1. Nf3 f6 +A04 Zukertort Opening: Arctic Defense, Drunken Knight Variation 1. Nf3 f6 2. e4 Nh6 3. d4 Nf7 +A04 Zukertort Opening: Basman Defense 1. Nf3 h6 +A04 Zukertort Opening: Black Mustang Defense 1. Nf3 Nc6 +A04 Zukertort Opening: Drunken Cavalry Variation 1. Nf3 Na6 2. e4 Nh6 +A04 Zukertort Opening: Dutch Variation 1. Nf3 f5 +A04 Zukertort Opening: Herrstrom Gambit 1. Nf3 g5 +A04 Zukertort Opening: Kingside Fianchetto 1. Nf3 g6 +A04 Zukertort Opening: Lisitsyn Gambit 1. Nf3 f5 2. e4 +A04 Zukertort Opening: Lisitsyn Gambit Deferred 1. Nf3 f5 2. d3 Nf6 3. e4 +A04 Zukertort Opening: Pirc Invitation 1. Nf3 d6 +A04 Zukertort Opening: Polish Defense 1. Nf3 b5 +A04 Zukertort Opening: Queen's Gambit Invitation 1. Nf3 e6 +A04 Zukertort Opening: Queenside Fianchetto Variation 1. Nf3 b6 +A04 Zukertort Opening: Ross Gambit 1. Nf3 e5 +A04 Zukertort Opening: Shabalov Gambit 1. Nf3 e6 2. c4 a6 3. Nc3 c5 4. g3 b5 +A04 Zukertort Opening: Sicilian Invitation 1. Nf3 c5 +A04 Zukertort Opening: Slav Invitation 1. Nf3 c6 +A04 Zukertort Opening: Speelsmet Gambit 1. Nf3 c5 2. d4 cxd4 3. e3 +A04 Zukertort Opening: St. George Defense 1. Nf3 a6 +A04 Zukertort Opening: The Walrus 1. Nf3 e5 2. Nxe5 Nc6 3. Nxc6 dxc6 +A04 Zukertort Opening: Vos Gambit 1. Nf3 d6 2. d4 e5 +A04 Zukertort Opening: Wade Defense 1. Nf3 d6 2. e4 Bg4 +A04 Zukertort Opening: Ware Defense 1. Nf3 a5 +A05 King's Indian Attack 1. Nf3 Nf6 2. g3 d5 +A05 King's Indian Attack: Smyslov Variation 1. Nf3 Nf6 2. g3 g6 3. b4 +A05 King's Indian Attack: Spassky Variation 1. Nf3 Nf6 2. g3 b5 +A05 King's Indian Attack: Symmetrical Defense 1. Nf3 Nf6 2. g3 g6 +A05 King's Indian Attack: Wahls Defense 1. Nf3 Nf6 2. g3 g6 3. Bg2 Bg7 4. O-O O-O 5. d3 d5 +A05 Polish Opening: Zukertort System 1. Nf3 Nf6 2. b4 g6 3. Bb2 +A05 Zukertort Opening 1. Nf3 Nf6 +A05 Zukertort Opening 1. Nf3 Nf6 2. Nc3 Nc6 +A05 Zukertort Opening: Double Fianchetto Attack 1. Nf3 Nf6 2. g3 g6 3. b3 Bg7 4. Bb2 O-O 5. Bg2 d6 6. O-O +A05 Zukertort Opening: Lemberger Gambit 1. Nf3 Nf6 2. e4 +A05 Zukertort Opening: Myers Polish Attack 1. Nf3 Nf6 2. a4 g6 3. b4 +A05 Zukertort Opening: Nimzo-Larsen Variation 1. Nf3 Nf6 2. b3 +A05 Zukertort Opening: Quiet System 1. Nf3 Nf6 2. e3 +A06 Nimzo-Larsen Attack: Classical Variation 1. Nf3 d5 2. b3 +A06 Nimzo-Larsen Attack: Norfolk Gambit 1. Nf3 d5 2. b3 c5 3. e4 +A06 Nimzo-Larsen Attack: Norfolk Gambit 1. Nf3 d5 2. b3 Nf6 3. Bb2 c5 4. e4 +A06 Zukertort Opening 1. Nf3 d5 +A06 Zukertort Opening: Ampel Variation 1. Nf3 d5 2. Rg1 +A06 Zukertort Opening: Old Indian Attack 1. Nf3 d5 2. d3 +A06 Zukertort Opening: Pachman Gambit 1. Nf3 d5 2. e3 c5 3. c4 dxc4 4. b3 +A06 Zukertort Opening: Regina-Nu Gambit 1. Nf3 d5 2. b3 c5 3. c4 dxc4 4. Nc3 +A06 Zukertort Opening: Reversed Mexican Defense 1. Nf3 d5 2. Nc3 +A06 Zukertort Opening: Santasiere's Folly 1. b4 d5 2. Nf3 +A06 Zukertort Opening: Tennison Gambit 1. e4 d5 2. Nf3 +A06 Zukertort Opening: Tennison Gambit, Brigg's Trap 1. e4 d5 2. Nf3 dxe4 3. Ng5 Nf6 4. Nc3 Bf5 5. Qe2 Qd4 +A06 Zukertort Opening: The Potato 1. Nf3 d5 2. a4 +A07 Hungarian Opening: Wiedenhagen-Beta Gambit 1. g3 d5 2. Nf3 g5 +A07 King's Indian Attack 1. Nf3 d5 2. g3 +A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 +A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 h6 +A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 h6 6. c4 dxc4 +A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 e6 6. Nbd2 +A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 e6 6. Nh4 +A07 King's Indian Attack, with e6 1. Nf3 Nf6 2. g3 d5 3. Bg2 e6 +A07 King's Indian Attack, with e6 1. Nf3 Nf6 2. g3 d5 3. Bg2 e6 4. O-O Be7 +A07 King's Indian Attack: Double Fianchetto 1. Nf3 d5 2. g3 g6 +A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 Bg4 +A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 Bg4 3. Bg2 Nd7 +A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 c6 3. Bg2 Bg4 4. O-O Nd7 +A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 c6 3. Bg2 Bg4 4. O-O Nd7 5. d4 Ngf6 6. c4 e6 7. cxd5 exd5 8. Nc3 Bd6 +A07 King's Indian Attack: Omega-Delta Gambit 1. Nf3 d5 2. g3 e5 +A07 King's Indian Attack: Pachman System 1. Nf3 d5 2. g3 g6 3. Bg2 Bg7 4. O-O e5 5. d3 Ne7 +A07 King's Indian Attack: Sicilian Variation 1. Nf3 d5 2. g3 c5 +A07 King's Indian Attack: Yugoslav Variation 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bg4 +A07 King's Indian Attack: Yugoslav Variation 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 b6 5. O-O +A08 King's Indian Attack: French Variation 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 +A08 King's Indian Attack: Sicilian Variation 1. e4 e6 2. d3 d5 3. Nd2 Nf6 4. Ngf3 c5 5. g3 Nc6 6. Bg2 Be7 7. O-O O-O 8. Re1 +A08 King's Indian Attack: Sicilian Variation 1. Nf3 d5 2. g3 c5 3. Bg2 +A08 King's Indian Attack: Sicilian Variation 1. Nf3 d5 2. g3 c5 3. Bg2 Nf6 4. O-O e6 5. d3 +A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 +A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 Nf6 +A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 Nf6 5. O-O +A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 e6 5. O-O +A09 Réti Opening 1. Nf3 d5 2. c4 +A09 Réti Opening: Advance Variation 1. Nf3 d5 2. c4 d4 +A09 Réti Opening: Advance Variation, Michel Gambit 1. Nf3 d5 2. c4 d4 3. b4 c5 +A09 Réti Opening: Advance Variation, Navara Gambit 1. Nf3 d5 2. c4 d4 3. b4 g5 +A09 Réti Opening: Penguin Variation 1. Nf3 d5 2. c4 d4 3. Rg1 +A09 Réti Opening: Reversed Blumenfeld Gambit 1. Nf3 d5 2. c4 d4 3. e3 c5 4. b4 +A09 Réti Opening: Réti Accepted 1. Nf3 d5 2. c4 dxc4 +A09 Réti Opening: Réti Gambit, Keres Variation 1. Nf3 d5 2. c4 dxc4 3. e3 Be6 +A09 Réti Opening: Zilbermints Gambit 1. Nf3 d5 2. c4 b5 +A10 English Opening 1. c4 +A10 English Opening: Achilles-Omega Gambit 1. c4 Nf6 2. e4 +A10 English Opening: Adorjan Defense 1. c4 g6 2. e4 e5 +A10 English Opening: Anglo-Dutch Defense 1. c4 f5 +A10 English Opening: Anglo-Dutch Defense, Hickmann Gambit 1. c4 f5 2. e4 +A10 English Opening: Anglo-Dutch Variation, Chabanon Gambit 1. c4 f5 2. Nf3 d6 3. e4 +A10 English Opening: Anglo-Dutch Variation, Ferenc Gambit 1. c4 f5 2. Nc3 Nf6 3. e4 +A10 English Opening: Anglo-Lithuanian Variation 1. c4 Nc6 +A10 English Opening: Anglo-Scandinavian Defense 1. c4 d5 +A10 English Opening: Anglo-Scandinavian Defense, Löhn Gambit 1. c4 d5 2. cxd5 e6 +A10 English Opening: Anglo-Scandinavian Defense, Malvinas Variation 1. c4 d5 2. cxd5 Qxd5 3. Nc3 Qa5 +A10 English Opening: Anglo-Scandinavian Defense, Schulz Gambit 1. c4 d5 2. cxd5 Nf6 +A10 English Opening: Great Snake Variation 1. c4 g6 +A10 English Opening: Jaenisch Gambit 1. c4 b5 +A10 English Opening: King's English Variation, Botvinnik System, Prickly Pawn Pass System 1. c4 g6 2. Nc3 Bg7 3. g3 Nf6 4. Bg2 O-O 5. e4 d6 6. Nge2 e5 7. O-O c6 8. d3 a6 +A10 English Opening: Myers Defense 1. c4 g5 +A10 English Opening: Myers Gambit 1. c4 g5 2. d4 Bg7 +A10 English Opening: Porcupine Variation 1. c4 f5 2. Nc3 Nf6 3. e4 fxe4 4. g4 +A10 English Opening: Wade Gambit 1. c4 f5 2. g4 +A10 English Opening: Zilbermints Gambit 1. c4 g5 2. d4 e5 +A11 English Opening: Caro-Kann Defensive System 1. c4 c6 +A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 +A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Qc2 +A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Nc3 Nbd7 5. Qc2 +A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Nc3 Nbd7 5. b3 e5 +A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Nc3 e6 5. b3 Bd6 +A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. b3 g6 +A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 +A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 dxc4 +A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Bf5 +A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Bf5 5. O-O e6 6. d3 +A11 Réti Opening: Anglo-Slav Variation, with g3 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 h6 6. c4 e6 +A12 Réti Opening: Anglo-Slav Variation 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 +A12 Réti Opening: Anglo-Slav Variation, Bled Variation 1. Nf3 d5 2. b3 Nf6 3. Bb2 g6 4. c4 c6 +A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 +A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 Bg4 +A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 Bf5 +A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 Bf5 4. Bb2 +A12 Réti Opening: Anglo-Slav Variation, Capablanca Variation 1. c4 Nf6 2. Nf3 c6 3. b3 d5 4. Bb2 Bg4 +A12 Réti Opening: Anglo-Slav Variation, Capablanca Variation 1. c4 Nf6 2. Nf3 c6 3. b3 d5 4. Bb2 Bg4 5. e3 +A12 Réti Opening: Anglo-Slav Variation, Capablanca Variation 1. c4 Nf6 2. Nf3 c6 3. b3 d5 4. Bb2 Bg4 5. d3 +A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 +A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 5. Bg2 +A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 5. Bg2 e6 6. Bb2 +A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 5. Bb2 +A12 Réti Opening: Anglo-Slav Variation, New York System 1. Nf3 Nf6 2. c4 c6 3. b3 d5 4. Bb2 Bf5 +A12 Réti Opening: Anglo-Slav Variation, New York System 1. Nf3 Nf6 2. c4 c6 3. b3 d5 4. Bb2 Bf5 5. e3 +A12 Réti Opening: Anglo-Slav Variation, New York System 1. Nf3 Nf6 2. c4 c6 3. b3 d5 4. Bb2 Bf5 5. d3 +A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 +A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 5. Bg2 +A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 5. Bg2 e6 6. Bb2 +A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 5. Bb2 +A12 Réti Opening: Anglo-Slav Variation, with dxc4 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 dxc4 +A13 English Opening: Agincourt Defense 1. c4 e6 +A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 +A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 d5 +A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 d5 3. b3 Nf6 4. Bb2 Be7 5. e3 O-O +A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 d5 3. b3 Nf6 4. Bb2 Be7 5. e3 O-O 6. d4 +A13 English Opening: Agincourt Defense, Bogoljubow Defense 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Bd6 +A13 English Opening: Agincourt Defense, Catalan Defense 1. c4 e6 2. Nf3 d5 3. g3 b6 4. Bg2 Bb7 5. O-O +A13 English Opening: Agincourt Defense, Catalan Defense 1. c4 e6 2. Nf3 d5 3. g3 c5 +A13 English Opening: Agincourt Defense, Catalan Defense Accepted 1. c4 e6 2. Nf3 Nf6 3. g3 d5 4. Bg2 dxc4 +A13 English Opening: Agincourt Defense, Catalan Defense, Semi-Slav Defense 1. c4 e6 2. Nf3 Nf6 3. g3 d5 4. Bg2 c6 +A13 English Opening: Agincourt Defense, Kurajica Defense 1. c4 e6 2. Nf3 d5 3. g3 c6 +A13 English Opening: Agincourt Defense, Tarrasch Defense 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 c5 5. b3 Nc6 6. O-O Be7 +A13 English Opening: Agincourt Defense, Wimpy System 1. c4 e6 2. Nf3 Nf6 3. b3 d5 4. Bb2 c5 5. e3 +A13 English Opening: Neo-Catalan 1. c4 e6 2. Nf3 d5 3. g3 Nf6 +A13 English Opening: Neo-Catalan Declined 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 +A13 English Opening: Romanishin Gambit 1. c4 Nf6 2. Nf3 e6 3. g3 a6 4. Bg2 b5 +A14 English Opening: Agincourt Defense, Keres Defense 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. O-O c5 6. cxd5 Nxd5 7. Nc3 Nc6 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. O-O +A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. O-O O-O 6. b3 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 7. e3 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 7. e3 d4 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 7. e3 Nc6 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined, Early b3 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. b3 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined, Early b3 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. b3 b6 +A14 English Opening: Agincourt Defense, Neo-Catalan Declined, Early b3 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. b3 c5 +A14 Réti Opening: Anglo-Slav Variation 1. Nf3 d5 2. c4 c6 3. g3 Nf6 4. Bg2 e6 5. b3 Be7 6. Bb2 +A14 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation, Stonewall Line 1. Nf3 d5 2. c4 e6 3. g3 Nf6 4. Bg2 Be7 5. O-O O-O 6. b3 c6 7. Bb2 +A15 English Opening: Anglo-Indian Defense 1. c4 Nf6 +A15 English Opening: Anglo-Indian Defense, Anti-Anti-Grünfeld 1. c4 Nf6 2. Nc3 g6 3. Nf3 Bg7 4. e4 +A15 English Opening: Anglo-Indian Defense, Grünfeld Formation 1. c4 Nf6 2. Nf3 g6 3. g3 d5 +A15 English Opening: Anglo-Indian Defense, King's Indian Formation 1. c4 Nf6 2. Nf3 g6 +A15 English Opening: Anglo-Indian Defense, King's Indian Formation, Double Fianchetto 1. c4 Nf6 2. Nf3 g6 3. g3 b6 4. Bg2 Bb7 +A15 English Opening: Anglo-Indian Defense, King's Knight Variation 1. c4 Nf6 2. Nf3 +A15 English Opening: Anglo-Indian Defense, Old Indian Formation 1. c4 Nf6 2. Nf3 d6 +A15 English Opening: Anglo-Indian Defense, Queen's Indian Formation 1. c4 Nf6 2. Nf3 b6 +A15 English Opening: Anglo-Indian Defense, Queen's Indian Formation 1. c4 e6 2. Nf3 Nf6 3. g3 b6 4. Bg2 Bb7 +A15 English Opening: Anglo-Indian Defense, Romanishin Variation 1. c4 e6 2. Nf3 Nf6 3. g3 a6 +A15 English Opening: Anglo-Indian Defense, Scandinavian Defense 1. c4 Nf6 2. Nf3 d5 +A15 English Opening: Anglo-Indian Defense, Scandinavian Defense, Exchange Variation 1. c4 Nf6 2. Nf3 d5 3. cxd5 Nxd5 +A15 English Opening: Anglo-Indian Defense, Slav Formation 1. c4 Nf6 2. Nf3 g6 3. g3 c6 +A15 English Orangutan 1. c4 Nf6 2. b4 +A15 English Orangutan 1. c4 Nf6 2. Nf3 g6 3. b4 +A16 English Opening: Anglo-Grünfeld Defense 1. c4 Nf6 2. Nc3 d5 +A16 English Opening: Anglo-Grünfeld Defense, Korchnoi Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 g6 5. g3 Bg7 6. Bg2 e5 +A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 +A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 g6 +A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. g3 g6 5. Bg2 Nb6 +A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. g3 g6 5. Bg2 Nxc3 +A16 English Opening: Anglo-Indian Defense, Queen's Knight Variation 1. c4 Nf6 2. Nc3 +A17 English Opening: Anglo-Indian Defense 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 c5 5. e3 e6 +A17 English Opening: Anglo-Indian Defense, Hedgehog System 1. c4 Nf6 2. Nc3 e6 +A17 English Opening: Anglo-Indian Defense, Nimzo-English 1. c4 Nf6 2. Nc3 e6 3. Nf3 Bb4 +A17 English Opening: Anglo-Indian Defense, Queen's Indian Formation 1. c4 e6 2. Nc3 Nf6 3. Nf3 b6 +A17 English Opening: Anglo-Indian Defense, Queen's Indian Variation 1. c4 e6 2. Nc3 Nf6 3. Nf3 b6 4. e4 Bb7 5. Bd3 +A17 English Opening: Anglo-Indian Defense, Zvjaginsev-Krasenkow Attack 1. c4 e6 2. Nc3 Nf6 3. Nf3 Bb4 4. g4 +A18 English Opening: Mikenas-Carls Variation 1. c4 e6 2. Nc3 Nf6 3. e4 +A18 English Opening: Mikenas-Carls Variation 1. c4 e6 2. Nc3 Nf6 3. e4 Nc6 +A18 English Opening: Mikenas-Carls Variation 1. c4 e6 2. Nc3 Nf6 3. e4 d5 4. e5 +A19 English Opening: Anglo-Indian Defense, Flohr-Mikenas-Carls Variation, Nei Gambit 1. c4 e6 2. Nc3 Nf6 3. e4 c5 4. e5 Ng8 +A19 English Opening: Mikenas-Carls, Sicilian 1. c4 e6 2. Nc3 Nf6 3. e4 c5 +A20 English Opening: Drill Variation 1. c4 e5 2. g3 h5 +A20 English Opening: King's English Variation 1. c4 e5 +A20 English Opening: King's English Variation, Kahiko-Hula Gambit 1. c4 e5 2. e3 Nf6 3. f4 exf4 4. Nf3 +A20 English Opening: King's English Variation, Nimzowitsch Variation 1. c4 e5 2. Nf3 +A20 English Opening: King's English Variation, Nimzowitsch-Flohr Variation 1. c4 e5 2. Nf3 e4 +A21 English Opening: King's English Variation 1. c4 e5 2. Nc3 d6 3. Nf3 +A21 English Opening: King's English Variation, Keres Defense 1. c4 e5 2. Nc3 d6 3. g3 c6 +A21 English Opening: King's English Variation, Kramnik-Shirov Counterattack 1. c4 e5 2. Nc3 Bb4 +A21 English Opening: King's English Variation, Reversed Sicilian 1. c4 e5 2. Nc3 +A21 English Opening: King's English Variation, Smyslov Defense 1. c4 e5 2. Nc3 d6 3. Nf3 Bg4 +A21 English Opening: King's English Variation, Troger Defense 1. c4 e5 2. Nc3 Nc6 3. g3 d6 4. Bg2 Be6 +A22 English Opening: Carls-Bremen System 1. c4 e5 2. Nc3 Nf6 3. g3 +A22 English Opening: King's English Variation, Adhiban Gambit 1. c4 e5 2. Nc3 Nf6 3. Nf3 e4 4. Ng5 c6 +A22 English Opening: King's English Variation, Bellon Gambit 1. c4 e5 2. Nc3 Nf6 3. Nf3 e4 4. Ng5 b5 +A22 English Opening: King's English Variation, Two Knights Variation 1. c4 e5 2. Nc3 Nf6 +A22 English Opening: King's English Variation, Two Knights Variation, Reversed Dragon 1. c4 e5 2. Nc3 Nf6 3. g3 d5 +A22 English Opening: King's English Variation, Two Knights Variation, Smyslov System 1. c4 e5 2. Nc3 Nf6 3. g3 Bb4 +A22 English Opening: King's English, Erbenheimer Gambit 1. c4 e5 2. Nc3 Nf6 3. Nf3 e4 4. Ng5 Ng4 +A22 English Opening: King's English, Mazedonisch 1. c4 e5 2. Nc3 Nf6 3. f4 +A23 English Opening: King's English Variation, Two Knights Variation, Keres Variation 1. c4 e5 2. Nc3 Nf6 3. g3 c6 +A23 English Opening: King's English Variation, Two Knights Variation, Keres Variation 1. c4 e5 2. Nc3 Nf6 3. g3 Bc5 4. Bg2 c6 +A24 English Opening: King's English Variation, Two Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. g3 g6 +A25 English Opening: Closed, Taimanov Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Rb1 Nh6 5. Bg2 Bg7 +A25 English Opening: Closed, Taimanov Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. e3 d6 6. Nge2 Nh6 +A25 English Opening: King's English Variation, Bremen-Hort Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. e3 d6 6. Nge2 Be6 +A25 English Opening: King's English Variation, Closed System 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 +A25 English Opening: King's English Variation, Hungarian Attack 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Rb1 +A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. Nc3 Nc6 +A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. g3 Nf6 3. Bg2 Nc6 4. Nc3 Bb4 5. Nd5 +A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. g3 Nf6 3. Bg2 Nc6 4. Nc3 Bb4 5. e4 d6 6. Nge2 +A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. g3 Nf6 3. Bg2 Nc6 4. Nc3 Bb4 5. e4 d6 6. Nge2 Bg4 +A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. Nc3 Nf6 3. g3 Bb4 4. e4 O-O 5. Nge2 Nc6 6. Bg2 +A25 English Opening: King's English Variation, Taimanov Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 +A26 English Opening: King's English Variation, Botvinnik System 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. e4 +A26 English Opening: King's English Variation, Closed System, Full Symmetry 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 +A27 English Opening: King's English Variation, Three Knights System 1. c4 e5 2. Nc3 Nc6 3. Nf3 +A28 English Opening: Four Knights System, Nimzowitsch Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e4 +A28 English Opening: King's English Variation, Four Knights Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 +A28 English Opening: King's English Variation, Four Knights Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d4 exd4 5. Nxd4 Bb4 6. Bg5 h6 7. Bh4 Bxc3+ 8. bxc3 Ne5 +A28 English Opening: King's English Variation, Four Knights Variation, Bradley Beach Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d4 e4 +A28 English Opening: King's English Variation, Four Knights Variation, Flexible Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d3 +A28 English Opening: King's English Variation, Four Knights Variation, Korchnoi Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. a3 +A28 English Opening: King's English Variation, Four Knights Variation, Quiet Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e3 +A28 English Opening: King's English Variation, Four Knights Variation, Quiet Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e3 Bb4 5. Qc2 Bxc3 +A28 English Opening: King's English Variation, Four Knights Variation, Quiet Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e3 Bb4 5. Qc2 O-O 6. Nd5 Re8 7. Qf5 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bb4 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bb4 5. Bg2 Bxc3 6. dxc3 d6 7. O-O O-O +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. g3 Nf6 3. Bg2 d5 4. cxd5 Nxd5 5. Nf3 Nc6 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. g3 Nf6 3. Bg2 d5 4. cxd5 Nxd5 5. Nf3 Nc6 6. d3 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. g3 Nf6 3. Bg2 d5 4. cxd5 Nxd5 5. Nf3 Nc6 6. d3 Be7 7. O-O O-O +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, Delayed .. Nc6 1. c4 e5 2. Nc3 Nf6 3. g3 Bb4 4. Bg2 O-O 5. Nf3 Re8 6. O-O e4 7. Nd4 Nc6 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 O-O 7. O-O +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6, Be7 1. c4 e5 2. Nc3 Nf6 3. g3 Nc6 4. Bg2 d6 5. d3 Be7 6. Nf3 O-O +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6, a6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 a6 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6, h6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 h6 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with Bc5 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 d5 5. cxd5 Nxd5 6. Bg2 Bc5 +A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with Nb6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 d5 5. cxd5 Nxd5 6. Bg2 Nb6 +A30 English Opening: Symmetrical Variation 1. c4 c5 +A30 English Opening: Symmetrical Variation 1. c4 c5 2. Nf3 +A30 English Opening: Symmetrical Variation, Hedgehog Defense 1. c4 e6 2. Nf3 Nf6 3. Nc3 c5 4. g3 b6 5. Bg2 Bb7 6. O-O Be7 +A30 English Opening: Symmetrical Variation, Napolitano Gambit 1. c4 c5 2. Nf3 Nf6 3. b4 +A30 English Opening: Symmetrical, Hedgehog, Flexible Formation 1. c4 e6 2. Nf3 c5 3. Nc3 Nf6 4. g3 b6 5. Bg2 Bb7 6. O-O Be7 7. d4 cxd4 8. Qxd4 d6 9. Rd1 a6 10. b3 Nbd7 +A30 English Opening: Wing Gambit 1. c4 c5 2. b4 +A31 English Opening: Symmetrical Variation, Anti-Benoni Variation 1. c4 Nf6 2. d4 c5 3. Nf3 +A31 English Opening: Symmetrical Variation, Anti-Benoni Variation, Kasparov-Vaganian Gambit 1. d4 Nf6 2. c4 c5 3. Nf3 cxd4 4. Nxd4 e5 5. Nb5 d5 +A32 English Opening: Symmetrical Variation, Anti-Benoni Variation, Spielmann Defense 1. c4 e6 2. d4 c5 3. Nf3 cxd4 4. Nxd4 Nf6 +A33 English Opening: Symmetrical Variation, Anti-Benoni Variation, Geller Variation 1. c4 e6 2. Nf3 Nf6 3. Nc3 c5 4. d4 Nc6 5. g3 cxd4 6. Nxd4 Qb6 +A33 English Opening: Symmetrical Variation, Anti-Benoni Variation, Spielmann Defense 1. c4 e6 2. Nf3 Nf6 3. Nc3 c5 4. d4 cxd4 5. Nxd4 Nc6 +A34 English Opening: Symmetrical Variation 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 4. g3 d5 5. d4 cxd4 +A34 English Opening: Symmetrical Variation, Fianchetto Variation 1. c4 Nf6 2. Nc3 c5 3. g3 +A34 English Opening: Symmetrical Variation, Normal Variation 1. c4 c5 2. Nc3 +A34 English Opening: Symmetrical Variation, Rubinstein Variation 1. c4 Nf6 2. Nc3 c5 3. g3 d5 4. cxd5 Nxd5 5. Bg2 Nc7 +A34 English Opening: Symmetrical Variation, Rubinstein Variation 1. c4 c5 2. Nf3 Nf6 3. Nc3 d5 4. cxd5 Nxd5 5. g3 Nc6 6. Bg2 Nc7 +A34 English Opening: Symmetrical Variation, Three Knights Variation 1. c4 c5 2. Nc3 Nf6 3. Nf3 +A35 English Opening: Symmetrical Variation 1. c4 c5 2. Nc3 Nf6 3. Nf3 e5 +A35 English Opening: Symmetrical Variation, Four Knights Variation 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 +A35 English Opening: Symmetrical Variation, Four Knights Variation, Keres-Parma System 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 4. g3 e6 +A35 English Opening: Symmetrical Variation, Two Knights Variation 1. c4 c5 2. Nc3 Nc6 +A36 English Opening: Symmetrical Variation, Botvinnik System 1. c4 c5 2. e4 Nc6 3. Nc3 g6 4. g3 Bg7 5. Bg2 +A36 English Opening: Symmetrical Variation, Botvinnik System Reversed, with e3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. e3 e5 +A36 English Opening: Symmetrical Variation, Two Knights, Fianchetto Variation 1. c4 c5 2. Nc3 Nc6 3. g3 +A36 English Opening: Symmetrical Variation, Ultra-Symmetrical Variation 1. c4 c5 2. g3 g6 3. Bg2 Bg7 4. Nc3 Nc6 +A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 +A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O d6 +A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 +A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 7. a3 +A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 7. d3 +A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 7. d3 d6 +A37 English Opening: Symmetrical Variation, Three Knights, Fianchetto Variation 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 +A37 English Opening: Symmetrical Variation, Three Knights, Fianchetto Variation 1. c4 c5 2. Nf3 Nc6 3. g3 g6 4. Bg2 Bg7 5. O-O d6 6. Nc3 +A37 English Opening: Symmetrical Variation, Three Knights, Fianchetto Variation 1. c4 c5 2. Nf3 Nc6 3. g3 g6 4. Bg2 Bg7 5. O-O e6 6. Nc3 +A38 English Opening: Symmetrical Variation, Double Fianchetto 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 Nf6 6. O-O O-O 7. b3 +A38 English Opening: Symmetrical Variation, Duchamp Variation 1. c4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O c5 6. Nc3 Nc6 7. d3 +A38 English Opening: Symmetrical Variation, Full Symmetry Line 1. c4 Nf6 2. Nf3 c5 3. Nc3 Nc6 4. g3 g6 5. Bg2 Bg7 +A39 English Opening: Symmetrical Variation, Mecking Variation 1. c4 Nf6 2. Nf3 c5 3. Nc3 Nc6 4. g3 g6 5. Bg2 Bg7 6. O-O O-O 7. d4 +A40 Australian Defense 1. d4 Na6 +A40 Benoni Defense: Franco-Sicilian Hybrid 1. d4 e6 2. c4 c5 3. d5 exd5 4. cxd5 d6 5. Nc3 g6 6. e4 Bg7 7. Nf3 Ne7 +A40 Borg Defense: Borg Gambit 1. d4 g5 +A40 Colle System: Pterodactyl Variation 1. d4 g6 2. Nf3 Bg7 3. e3 c5 4. Bd3 Qa5+ +A40 Colle System: Siroccopteryx Variation 1. d4 g6 2. Nf3 Bg7 3. e3 c5 4. Bd3 cxd4 5. Nxd4 Qa5+ +A40 English Defense 1. d4 b6 +A40 English Defense 1. d4 e6 2. c4 b6 +A40 English Defense: Eastbourne Gambit 1. d4 b6 2. c4 Bb7 3. Nc3 e5 +A40 English Defense: Hartlaub Gambit Accepted 1. c4 e6 2. d4 b6 3. Nc3 Bb7 4. e4 f5 5. exf5 Nf6 +A40 English Defense: Hartlaub Gambit Declined 1. c4 e6 2. d4 b6 3. Nc3 Bb7 4. e4 f5 5. d5 +A40 English Defense: Perrin Variation 1. d4 e6 2. c4 b6 3. e4 Bb7 4. Bd3 Nc6 +A40 English Defense: Poli Gambit 1. d4 e6 2. c4 b6 3. e4 Bb7 4. f3 f5 5. exf5 Nh6 +A40 Englund Gambit 1. d4 e5 +A40 Englund Gambit Declined 1. d4 e5 2. d5 +A40 Englund Gambit Declined: Diemer Counterattack 1. d4 e5 2. d5 Bc5 3. e4 Qh4 +A40 Englund Gambit Declined: Reversed Alekhine 1. d4 e5 2. Nf3 +A40 Englund Gambit Declined: Reversed Brooklyn 1. d4 e5 2. Nf3 e4 3. Ng1 +A40 Englund Gambit Declined: Reversed French 1. d4 e5 2. e3 +A40 Englund Gambit Declined: Reversed Krebs 1. d4 e5 2. Nf3 e4 +A40 Englund Gambit Declined: Reversed Mokele Mbembe 1. d4 e5 2. Nf3 e4 3. Ne5 +A40 Englund Gambit: Felbecker Gambit 1. d4 e5 2. dxe5 Nc6 3. Nf3 Bc5 +A40 Englund Gambit: Hartlaub-Charlick Gambit 1. d4 e5 2. dxe5 d6 +A40 Englund Gambit: Main Line 1. d4 e5 2. dxe5 Nc6 3. Nf3 Qe7 +A40 Englund Gambit: Mosquito Gambit 1. d4 e5 2. dxe5 Qh4 +A40 Englund Gambit: Soller Gambit 1. d4 e5 2. dxe5 f6 +A40 Englund Gambit: Soller Gambit Deferred 1. d4 e5 2. dxe5 Nc6 3. Nf3 f6 +A40 Englund Gambit: Stockholm Variation 1. d4 e5 2. dxe5 Nc6 3. Nf3 Qe7 4. Qd5 +A40 Englund Gambit: Zilbermints Gambit 1. d4 e5 2. dxe5 Nc6 3. Nf3 Nge7 +A40 Horwitz Defense 1. d4 e6 +A40 Horwitz Defense: Zilbermints Gambit 1. d4 e6 2. c4 e5 +A40 Kangaroo Defense 1. d4 e6 2. c4 Bb4+ +A40 Kangaroo Defense: Keres Defense, Transpositional Variation 1. d4 e6 2. c4 Bb4+ 3. Nc3 +A40 Mikenas Defense 1. d4 Nc6 +A40 Mikenas Defense: Cannstatter Variation 1. d4 Nc6 2. c4 e5 3. d5 Nd4 +A40 Mikenas Defense: Lithuanian Variation 1. d4 Nc6 2. c4 e5 3. d5 Nce7 +A40 Mikenas Defense: Pozarek Gambit 1. d4 Nc6 2. c4 e5 3. dxe5 Nxe5 4. Nc3 Nxc4 +A40 Modern Defense: Beefeater Variation 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 Bxc3+ 5. bxc3 f5 +A40 Modern Defense: Lizard Defense, Pirc-Diemer Gambit 1. d4 g6 2. h4 Nf6 3. h5 +A40 Montevideo Defense 1. d4 Nc6 2. d5 Nb8 +A40 Polish Defense 1. d4 b5 +A40 Polish Defense: Spassky Gambit Accepted 1. d4 b5 2. e4 Bb7 3. Bxb5 +A40 Pterodactyl Defense: Central, Benoni Beefeater Pterodactyl 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 d6 5. e4 Bxc3+ 6. bxc3 Qa5 +A40 Pterodactyl Defense: Central, Benoni Pterodactyl 1. d4 g6 2. c4 Bg7 3. e4 c5 4. d5 Qa5+ +A40 Pterodactyl Defense: Fianchetto, Queen Benoni Pterodactyl 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 Qa5 +A40 Pterodactyl Defense: Fianchetto, Queen Pteranodon 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 Bxc3+ 5. bxc3 Qa5 +A40 Pterodactyl Defense: Fianchetto, Queen Pterodactyl 1. d4 g6 2. Nf3 Bg7 3. g3 c5 4. Bg2 Qa5+ +A40 Pterodactyl Defense: Queen Pterodactyl, Quiet Line 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. e3 +A40 Queen's Pawn Game 1. d4 +A40 Queen's Pawn Game: Anglo-Slav Opening 1. d4 c6 2. c4 d6 +A40 Queen's Pawn Game: Modern Defense 1. d4 g6 +A40 Slav Indian: Kudischewitsch Gambit 1. d4 c6 2. Nf3 Nf6 3. c4 b5 +A40 Zaire Defense 1. d4 Nc6 2. d5 Nb8 3. e4 Nf6 4. e5 Ng8 +A41 Modern Defense 1. d4 g6 2. c4 Bg7 3. Nc3 d6 +A41 Modern Defense: Neo-Modern Defense 1. d4 g6 2. c4 Bg7 3. e4 e5 +A41 Old Indian Defense 1. d4 d6 2. c4 +A41 Queen's Pawn Game 1. d4 d6 +A41 Queen's Pawn Game: Rossolimo Variation 1. d4 d6 2. Nf3 g6 +A41 Rat Defense: English Rat 1. d4 d6 2. c4 e5 +A41 Rat Defense: English Rat, Lisbon Gambit 1. d4 d6 2. c4 e5 3. dxe5 Nc6 +A41 Rat Defense: English Rat, Pounds Gambit 1. d4 d6 2. c4 e5 3. dxe5 Be6 +A41 Robatsch Defense: Rossolimo Variation 1. d4 d6 2. Nf3 g6 3. c4 Bg7 4. e4 Bg4 +A41 Wade Defense 1. d4 d6 2. Nf3 Bg4 +A41 Zukertort Opening: Wade Defense, Chigorin Plan 1. d4 d6 2. Nf3 Bg4 3. c4 Nd7 4. Qb3 Rb8 +A42 Modern Defense: Averbakh System 1. d4 g6 2. c4 Bg7 3. Nc3 d6 4. e4 +A42 Modern Defense: Averbakh Variation, Pseudo-Sämisch 1. d4 g6 2. c4 Bg7 3. e4 d6 4. Be3 Nf6 5. f3 +A42 Modern Defense: Kotov Variation 1. d4 g6 2. c4 Bg7 3. Nc3 d6 4. e4 Nc6 +A42 Modern Defense: Randspringer Variation 1. d4 g6 2. c4 Bg7 3. Nc3 d6 4. e4 f5 +A42 Pterodactyl Defense 1. Nf3 c5 2. c4 g6 3. d4 Bg7 4. e4 Qa5+ 5. Nc3 d6 +A42 Pterodactyl Defense: Central, Bogolubovia 1. d4 g6 2. c4 Bg7 3. e4 d6 4. Nc3 c5 5. Nge2 Qa5 +A43 Benoni Defense: Benoni Gambit Accepted 1. d4 c5 2. dxc5 +A43 Benoni Defense: Benoni Gambit, Schlenker Defense 1. d4 c5 2. dxc5 Na6 +A43 Benoni Defense: Benoni-Indian Defense 1. d4 c5 2. d5 Nf6 +A43 Benoni Defense: Benoni-Indian Defense, Kingside Move Order 1. d4 c5 2. d5 Nf6 3. Nf3 +A43 Benoni Defense: Benoni-Staunton Gambit 1. d4 c5 2. d5 f5 3. e4 +A43 Benoni Defense: Cormorant Gambit 1. d4 c5 2. dxc5 b6 +A43 Benoni Defense: French Benoni 1. e4 e6 2. d4 c5 3. d5 +A43 Benoni Defense: Hawk Variation 1. d4 Nf6 2. Nf3 c5 3. d5 c4 +A43 Benoni Defense: Old Benoni 1. d4 c5 +A43 Benoni Defense: Old Benoni 1. d4 c5 2. d5 +A43 Benoni Defense: Old Benoni 1. d4 c5 2. d5 d6 +A43 Benoni Defense: Old Benoni, Mujannah Formation 1. d4 c5 2. d5 f5 +A43 Benoni Defense: Old Benoni, Schmid Variation 1. d4 c5 2. d5 d6 3. Nc3 g6 +A43 Benoni Defense: Snail Variation 1. d4 c5 2. d5 Na6 +A43 Benoni Defense: Woozle 1. d4 c5 2. d5 Nf6 3. Nc3 Qa5 +A43 Benoni Defense: Zilbermints-Benoni Gambit 1. d4 c5 2. b4 +A43 Benoni Defense: Zilbermints-Benoni Gambit 1. d4 c5 2. Nf3 cxd4 3. b4 +A43 Benoni Defense: Zilbermints-Benoni Gambit, Tamarkin Countergambit 1. d4 c5 2. Nf3 cxd4 3. b4 e5 +A43 Indian Defense: Pseudo-Benko 1. d4 Nf6 2. Nf3 c5 3. d5 b5 +A43 Queen's Pawn Game: Liedmann Gambit 1. d4 c5 2. c4 cxd4 3. e3 +A44 Benoni Defense: Old Benoni 1. d4 c5 2. d5 e5 +A44 Benoni Defense: Semi-Benoni 1. d4 c5 2. d5 e5 3. e4 d6 +A45 Amazon Attack: Siberian Attack 1. d4 Nf6 2. Nc3 d5 3. Qd3 +A45 Basque Opening 1. d4 Nf6 2. b3 +A45 Canard Opening 1. d4 Nf6 2. f4 +A45 Indian Defense 1. d4 Nf6 +A45 Indian Defense: Accelerated London System 1. d4 Nf6 2. Bf4 +A45 Indian Defense: Gedult Attack 1. d4 Nf6 2. f3 d5 3. g4 +A45 Indian Defense: Gibbins-Weidenhagen Gambit 1. d4 Nf6 2. g4 +A45 Indian Defense: Gibbins-Weidenhagen Gambit Accepted 1. d4 Nf6 2. g4 Nxg4 +A45 Indian Defense: Gibbins-Weidenhagen Gambit, Maltese Falcon 1. d4 Nf6 2. g4 Nxg4 3. f3 Nf6 4. e4 +A45 Indian Defense: Gibbins-Weidenhagen Gambit, Oshima Defense 1. d4 Nf6 2. g4 e5 +A45 Indian Defense: Gibbins-Weidenhagen Gambit, Stummer Gambit 1. d4 Nf6 2. g4 Nxg4 3. e4 d6 4. Be2 Nf6 5. Nc3 +A45 Indian Defense: Lazard Gambit 1. d4 Nf6 2. Nd2 e5 +A45 Indian Defense: Maddigan Gambit 1. d4 Nf6 2. Nc3 e5 +A45 Indian Defense: Omega Gambit 1. d4 Nf6 2. e4 +A45 Indian Defense: Omega Gambit, Arafat Gambit 1. d4 Nf6 2. e4 Nxe4 3. Bd3 Nf6 4. Bg5 +A45 Indian Defense: Paleface Attack, Blackmar-Diemer Gambit Deferred 1. d4 Nf6 2. f3 d5 3. e4 +A45 Indian Defense: Pawn Push Variation 1. d4 Nf6 2. d5 +A45 Indian Defense: Reversed Chigorin Defense 1. d4 Nf6 2. Nc3 c5 +A45 Indian Defense: Tartakower Attack 1. d4 Nf6 2. g3 +A45 Paleface Attack 1. d4 Nf6 2. f3 +A45 Queen's Pawn Game: Chigorin Variation 1. d4 Nf6 2. Nc3 d5 +A45 Queen's Pawn Game: Veresov, Richter Attack 1. d4 Nf6 2. f3 d5 3. Nc3 +A45 Trompowsky Attack 1. d4 Nf6 2. Bg5 +A45 Trompowsky Attack: Borg Variation 1. d4 Nf6 2. Bg5 Ne4 3. Bf4 g5 +A45 Trompowsky Attack: Classical Defense 1. d4 Nf6 2. Bg5 e6 +A45 Trompowsky Attack: Classical Defense, Big Center Variation 1. d4 Nf6 2. Bg5 e6 3. e4 +A45 Trompowsky Attack: Edge Variation 1. d4 Nf6 2. Bg5 Ne4 3. Bh4 +A45 Trompowsky Attack: Edge Variation, Hergert Gambit 1. d4 Nf6 2. Bg5 Ne4 3. Bh4 c6 4. Nd2 Qa5 5. c3 Nxd2 6. Qxd2 d5 7. e4 +A45 Trompowsky Attack: Edge Variation, Hergert Gambit 1. d4 Nf6 2. Bg5 Ne4 3. Bh4 d5 4. f3 Nf6 5. Nc3 Bf5 6. e4 +A45 Trompowsky Attack: Poisoned Pawn Variation 1. d4 Nf6 2. Bg5 c5 3. d5 Qb6 4. Nc3 +A45 Trompowsky Attack: Raptor Variation 1. d4 Nf6 2. Bg5 Ne4 3. h4 +A45 Trompowsky Attack: Raptor Variation, Hergert Gambit 1. d4 Nf6 2. Bg5 Ne4 3. h4 Nxg5 4. hxg5 e5 +A46 Döry Defense 1. d4 Nf6 2. Nf3 Ne4 +A46 Indian Defense: Czech-Indian 1. d4 Nf6 2. Nf3 c6 +A46 Indian Defense: Knights Variation 1. d4 Nf6 2. Nf3 +A46 Indian Defense: Knights Variation, Alburt-Miles Variation 1. d4 Nf6 2. Nf3 a6 +A46 Indian Defense: London System 1. d4 Nf6 2. Nf3 e6 3. Bf4 +A46 Indian Defense: Polish Variation 1. d4 Nf6 2. Nf3 b5 +A46 Indian Defense: Spielmann-Indian 1. d4 Nf6 2. Nf3 c5 +A46 Indian Defense: Wade-Tartakower Defense 1. d4 Nf6 2. Nf3 d6 +A46 Queen's Pawn Game: Torre Attack, Breyer Variation 1. d4 Nf6 2. Nf3 e6 3. Bg5 d5 4. e3 c5 5. c3 Qb6 +A46 Queen's Pawn Game: Veresov Attack, Classical Defense 1. d4 Nf6 2. Nf3 e6 3. Nc3 d5 4. Bg5 +A46 Torre Attack: Classical Defense 1. d4 Nf6 2. Nf3 e6 3. Bg5 +A46 Torre Attack: Classical Defense, Nimzowitsch Variation 1. d4 Nf6 2. Nf3 e6 3. Bg5 h6 +A46 Torre Attack: Classical Defense, Petrosian Gambit 1. d4 Nf6 2. Nf3 e6 3. Bg5 c5 4. e3 b6 5. d5 +A46 Torre Attack: Wagner Gambit 1. d4 Nf6 2. Nf3 e6 3. Bg5 c5 4. e4 +A46 Yusupov-Rubinstein System 1. d4 Nf6 2. Nf3 e6 3. e3 +A47 Indian Defense: Schnepper Gambit 1. d4 Nf6 2. Nf3 b6 3. c3 e5 +A47 Marienbad System 1. d4 Nf6 2. Nf3 b6 3. g3 Bb7 4. Bg2 c5 +A47 Marienbad System: Berg Variation 1. d4 Nf6 2. Nf3 b6 3. g3 Bb7 4. Bg2 c5 5. c4 cxd4 6. Qxd4 +A47 Pseudo Queen's Indian Defense 1. d4 Nf6 2. Nf3 b6 +A47 Pseudo Queen's Indian Defense 1. d4 Nf6 2. Nf3 b6 3. e3 Bb7 4. Bd3 e6 5. Nbd2 c5 6. b3 Be7 +A48 East Indian Defense 1. d4 Nf6 2. Nf3 g6 +A48 Indian Defense: Colle System, King's Indian Variation 1. d4 Nf6 2. Nf3 g6 3. e3 Bg7 4. Bd3 d6 +A48 London System 1. d4 Nf6 2. Nf3 g6 3. Bf4 +A48 London System 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 +A48 London System 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 +A48 London System, with Bd3 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. Bd3 +A48 London System, with Be2 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. Be2 +A48 London System, with Be2 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. Be2 O-O +A48 London System, with Be2 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. h3 c5 6. Be2 +A48 Queen's Pawn Game: Barry Attack 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 +A48 Queen's Pawn Game: Barry Attack 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 Bg7 +A48 Queen's Pawn Game: Barry Attack, Grünfeld Variation 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. Be2 +A48 Queen's Pawn Game: Barry Attack, Tarzan Attack 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 Bg7 5. Qd2 +A48 Queen's Pawn Game: Torre Attack, Grünfeld Variation, Main Line 1. d4 Nf6 2. Nf3 g6 3. Bg5 Bg7 4. Nbd2 d5 5. e3 O-O +A48 Torre Attack: Fianchetto Defense 1. d4 Nf6 2. Nf3 g6 3. Bg5 +A48 Torre Attack: Fianchetto Defense, Euwe Variation 1. d4 Nf6 2. Nf3 g6 3. Bg5 Bg7 4. Nbd2 c5 +A49 Indian Defense: Przepiorka Variation 1. d4 Nf6 2. Nf3 g6 3. g3 +A50 Indian Defense: Medusa Gambit 1. d4 Nf6 2. c4 g5 +A50 Indian Defense: Normal Variation 1. d4 Nf6 2. c4 +A50 Indian Defense: Pyrenees Gambit 1. d4 Nf6 2. c4 b5 +A50 Mexican Defense 1. d4 Nf6 2. c4 Nc6 +A50 Mexican Defense: Horsefly Gambit 1. d4 Nf6 2. c4 Nc6 3. d5 Ne5 4. f4 +A50 Queen's Indian Accelerated 1. d4 Nf6 2. c4 b6 +A50 Slav Indian 1. d4 Nf6 2. c4 c6 +A51 Indian Defense: Budapest Gambit 1. d4 Nf6 2. c4 e5 +A51 Indian Defense: Budapest Gambit Accepted 1. d4 Nf6 2. c4 e5 3. dxe5 +A51 Indian Defense: Budapest Gambit Accepted, Fajarowicz Defense 1. d4 Nf6 2. c4 e5 3. dxe5 Ne4 +A51 Indian Defense: Budapest Gambit Accepted, Fajarowicz Defense, Bonsdorf Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ne4 4. a3 +A51 Indian Defense: Budapest Gambit Accepted, Fajarowicz Defense, Steiner Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ne4 4. Qc2 +A52 Indian Defense: Budapest Gambit Accepted, Main Line 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 +A52 Indian Defense: Budapest Gambit Accepted, Main Line, Adler Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. Nf3 +A52 Indian Defense: Budapest Gambit Accepted, Main Line, Alekhine Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. e4 +A52 Indian Defense: Budapest Gambit Accepted, Main Line, Alekhine Variation, Abonyi Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. e4 Nxe5 +A52 Indian Defense: Budapest Gambit Accepted, Main Line, Alekhine Variation, Tartakower Defense 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. e4 d6 +A52 Indian Defense: Budapest Gambit Accepted, Main Line, Rubinstein Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. Bf4 +A53 Old Indian Defense 1. d4 Nf6 2. c4 d6 +A53 Old Indian Defense: Aged Gibbon Gambit 1. d4 Nf6 2. c4 d6 3. g4 +A53 Old Indian Defense: Czech Variation, with Nc3 1. d4 Nf6 2. c4 d6 3. Nc3 c6 +A53 Old Indian Defense: Czech Variation, with Nf3 1. d4 Nf6 2. c4 d6 3. Nf3 c6 +A53 Old Indian Defense: Janowski Variation 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 +A53 Old Indian Defense: Janowski Variation, Fianchetto Variation 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 4. g3 +A53 Old Indian Defense: Janowski Variation, Grinberg Gambit 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 4. e4 +A53 Old Indian Defense: Janowski Variation, Main Line 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 4. f3 +A54 Old Indian Defense: Duz-Khotimirsky Variation 1. d4 Nf6 2. c4 d6 3. Nc3 e5 4. e3 Nbd7 5. Bd3 +A54 Old Indian Defense: Tartakower-Indian 1. d4 Nf6 2. c4 d6 3. Nf3 Bg4 +A54 Old Indian Defense: Two Knights Variation 1. d4 Nf6 2. c4 d6 3. Nc3 e5 4. Nf3 +A54 Old Indian Defense: Ukrainian Variation 1. d4 Nf6 2. c4 d6 3. Nc3 e5 +A55 Old Indian Defense: Normal Variation 1. d4 Nf6 2. c4 d6 3. Nc3 Nbd7 4. e4 e5 5. Nf3 +A56 Benoni Defense 1. d4 Nf6 2. c4 c5 +A56 Benoni Defense: Czech Benoni Defense 1. d4 Nf6 2. c4 c5 3. d5 e5 +A56 Benoni Defense: Hromádka System 1. d4 Nf6 2. c4 c5 3. d5 d6 +A56 Benoni Defense: King's Indian System 1. d4 Nf6 2. c4 c5 3. d5 e5 4. Nc3 d6 5. e4 g6 +A56 Benoni Defense: Weenink Variation 1. d4 Nf6 2. c4 c5 3. dxc5 e6 +A56 Grünfeld Defense: Three Knights Variation, Burille Variation, Reversed Tarrasch 1. d4 Nf6 2. c4 c5 3. e3 g6 4. Nc3 Bg7 5. Nf3 O-O 6. Be2 cxd4 7. exd4 d5 8. O-O Nc6 +A56 Vulture Defense 1. d4 Nf6 2. c4 c5 3. d5 Ne4 +A57 Benko Gambit 1. d4 Nf6 2. c4 c5 3. d5 b5 +A57 Benko Gambit Accepted 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 +A57 Benko Gambit Accepted: Dlugy Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. f3 +A57 Benko Gambit Accepted: Modern Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. e3 +A57 Benko Gambit Accepted: Pawn Return Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. b6 +A57 Benko Gambit Declined: Bishop Attack 1. d4 Nf6 2. c4 c5 3. d5 b5 4. Bg5 +A57 Benko Gambit Declined: Hjørring Countergambit 1. d4 Nf6 2. c4 c5 3. d5 b5 4. e4 +A57 Benko Gambit Declined: Main Line 1. d4 Nf6 2. c4 c5 3. d5 b5 4. Nf3 +A57 Benko Gambit Declined: Pseudo-Sämisch 1. d4 Nf6 2. c4 c5 3. d5 b5 4. f3 +A57 Benko Gambit Declined: Quiet Line 1. d4 Nf6 2. c4 c5 3. d5 b5 4. Nd2 +A57 Benko Gambit Declined: Sosonko Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. a4 +A57 Benko Gambit: Mutkin Countergambit 1. d4 Nf6 2. c4 c5 3. d5 b5 4. g4 +A57 Benko Gambit: Nescafe Frappe Attack 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. Nc3 axb5 6. e4 b4 7. Nb5 d6 8. Bc4 +A57 Benko Gambit: Zaitsev System 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. Nc3 +A57 Benko Gambit: Zaitsev Variation, Nescafe Frappe Attack 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. Nc3 axb5 6. e4 b4 7. Nb5 +A58 Benko Gambit Accepted: Central Storming Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. f4 +A58 Benko Gambit Accepted: Fianchetto Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. g3 d6 8. Bg2 Bg7 9. Nf3 +A58 Benko Gambit Accepted: Fully Accepted Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 +A58 Benko Gambit: Fianchetto Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 Bxa6 6. Nc3 d6 7. Nf3 g6 8. g3 +A58 Benko Gambit: Nd2 Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 Bxa6 6. Nc3 d6 7. Nf3 g6 8. Nd2 +A59 Benko Gambit 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. e4 Bxf1 8. Kxf1 d6 9. g3 +A59 Benko Gambit Accepted: King Walk Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. Nf3 d6 8. e4 Bxf1 9. Kxf1 Bg7 10. g3 O-O 11. Kg2 +A59 Benko Gambit Accepted: Yugoslav 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 Bxa6 6. Nc3 d6 7. e4 +A59 Benko Gambit Accepted: Yugoslav 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. e4 Bxf1 8. Kxf1 d6 9. Nge2 +A60 Benoni Defense: Modern Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 +A60 Benoni Defense: Modern Variation, Snake Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 Bd6 +A61 Benoni Defense 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 +A61 Benoni Defense: Fianchetto Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. g3 +A61 Benoni Defense: Knight's Tour Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Nd2 +A61 Benoni Defense: Uhlmann Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg5 +A62 Benoni Defense: Fianchetto Variation 1. d4 Nf6 2. c4 e6 3. g3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg2 Bg7 8. Nf3 O-O +A63 Benoni Defense: Fianchetto Variation, Hastings Defense 1. d4 Nf6 2. c4 e6 3. g3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg2 Bg7 8. Nf3 O-O 9. O-O Nbd7 +A64 Benoni Defense: Fianchetto Variation, Hastings Defense, Main Line 1. d4 Nf6 2. c4 e6 3. g3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg2 Bg7 8. Nf3 O-O 9. O-O a6 10. a4 Nbd7 11. Nd2 Re8 +A65 Benoni Defense: King's Pawn Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 +A65 Benoni Defense: King's Pawn Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 +A65 Benoni Defense: King's Pawn Line 1. d4 Nf6 2. c4 g6 3. f3 c5 4. d5 d6 5. e4 Bg7 6. Nc3 e6 7. Be3 O-O 8. Qd2 exd5 9. cxd5 +A65 Benoni Defense: King's Pawn Line, with Be3 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 8. Be3 +A65 Benoni Defense: King's Pawn Line, with Bg5 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 +A65 Benoni Defense: King's Pawn Line, with Bg5 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 8. Bg5 +A65 Benoni Defense: King's Pawn Line, with Bg5 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 e6 8. Qd2 exd5 9. exd5 +A65 Benoni Defense: King's Pawn Line, with Nge2 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 8. Nge2 +A65 Benoni Defense: King's Pawn Line, with Nge2 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Nge2 c5 7. d5 e6 8. Ng3 exd5 9. cxd5 +A66 Benoni Defense: Mikenas Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. e5 +A66 Benoni Defense: Pawn Storm Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 +A67 Benoni Defense: Taimanov Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Bb5+ +A68 Benoni Defense: Four Pawns Attack 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O +A68 Benoni Defense: Four Pawns Attack 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 +A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 Re8 +A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 Nbd7 10. O-O Re8 +A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 Nbd7 10. O-O Re8 11. Nd2 +A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 a6 10. a4 Re8 11. Nd2 +A70 Benoni Defense: Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 +A70 Benoni Defense: Classical Variation, New York Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. h3 +A70 Benoni Defense: Classical Variation, Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Be2 +A71 Benoni Defense: Classical Variation, Averbakh-Grivas Attack 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Bg5 +A72 Benoni Defense: Classical Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O +A73 Benoni Defense: Classical Variation, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O +A74 Benoni Defense: Classical Variation, Full Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O a6 10. a4 +A75 Benoni Defense: Classical Variation, Argentine Counterattack 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Be2 O-O 9. O-O a6 10. a4 Bg4 +A76 Benoni Defense: Classical Variation, Czerniak Defense 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 +A77 Benoni Defense: Classical Variation, Czerniak Defense, Tal Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 +A77 Benoni Defense: Classical Variation, Czerniak Defense, Tal Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 Nbd7 +A78 Benoni Defense: Classical Variation, Czerniak Defense 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 Na6 +A79 Benoni Defense: Classical Variation, Czerniak Defense 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 Na6 11. f3 +A80 Dutch Defense 1. d4 f5 +A80 Dutch Defense: Alapin Variation 1. d4 f5 2. Qd3 +A80 Dutch Defense: Barcza Variation 1. d4 f5 2. Nf3 Nf6 3. c3 +A80 Dutch Defense: Hevendehl Gambit 1. d4 f5 2. g4 e5 +A80 Dutch Defense: Hopton Attack 1. d4 f5 2. Bg5 +A80 Dutch Defense: Janzen-Korchnoi Gambit 1. d4 f5 2. h3 Nf6 3. g4 +A80 Dutch Defense: Kingfisher Gambit 1. d4 f5 2. Nc3 d5 3. e4 +A80 Dutch Defense: Korchnoi Attack 1. d4 f5 2. h3 +A80 Dutch Defense: Krejcik Gambit 1. d4 f5 2. g4 +A80 Dutch Defense: Krejcik Gambit, Tate Gambit 1. d4 f5 2. g4 fxg4 3. e4 d5 4. Nc3 +A80 Dutch Defense: Manhattan Gambit, Anti-Classical Line 1. d4 f5 2. Qd3 e6 3. g4 +A80 Dutch Defense: Manhattan Gambit, Anti-Leningrad 1. d4 f5 2. Qd3 g6 3. g4 +A80 Dutch Defense: Manhattan Gambit, Anti-Modern 1. d4 f5 2. Qd3 d6 3. g4 +A80 Dutch Defense: Manhattan Gambit, Anti-Stonewall 1. d4 f5 2. Qd3 d5 3. g4 +A80 Dutch Defense: Omega-Isis Gambit 1. d4 f5 2. Nf3 e5 +A80 Dutch Defense: Raphael Variation 1. d4 f5 2. Nc3 +A80 Dutch Defense: Senechaud Gambit 1. d4 f5 2. Bf4 e6 3. g4 +A80 Dutch Defense: Spielmann Gambit 1. d4 f5 2. Nc3 Nf6 3. g4 +A80 Queen's Pawn Game: Veresov Attack, Dutch System 1. d4 f5 2. Nc3 d5 +A81 Dutch Defense: Blackburne Variation 1. d4 f5 2. g3 Nf6 3. Bg2 e6 4. Nh3 +A81 Dutch Defense: Fianchetto Attack 1. d4 f5 2. g3 +A81 Dutch Defense: Leningrad Variation, Carlsbad Variation 1. d4 f5 2. g3 g6 3. Bg2 Bg7 4. Nh3 +A81 Dutch Defense: Leningrad, Basman System 1. d4 f5 2. g3 c6 3. Bg2 g6 4. Nf3 Bg7 5. O-O Nh6 +A81 Dutch Defense: Semi-Leningrad Variation 1. d4 f5 2. g3 Nf6 3. Bg2 g6 +A82 Dutch Defense: Blackmar's Second Gambit 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. f3 +A82 Dutch Defense: Staunton Gambit 1. d4 f5 2. e4 +A82 Dutch Defense: Staunton Gambit Accepted 1. d4 f5 2. e4 fxe4 +A82 Dutch Defense: Staunton Gambit, American Attack 1. d4 f5 2. e4 fxe4 3. Nd2 +A82 Dutch Defense: Staunton Gambit, Tartakower Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. g4 +A82 Rat Defense: Balogh Defense 1. e4 d6 2. d4 f5 +A83 Dutch Defense: Staunton Gambit 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 +A83 Dutch Defense: Staunton Gambit, Alekhine Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 g6 5. h4 +A83 Dutch Defense: Staunton Gambit, Chigorin Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 c6 +A83 Dutch Defense: Staunton Gambit, Lasker Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 g6 5. f3 +A83 Dutch Defense: Staunton Gambit, Nimzowitsch Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 b6 +A84 Dutch Defense 1. d4 f5 2. c4 +A84 Dutch Defense: Bellon Gambit 1. d4 f5 2. c4 e6 3. e4 +A84 Dutch Defense: Bladel Variation 1. d4 f5 2. c4 g6 3. Nc3 Nh6 +A84 Dutch Defense: Classical Variation 1. d4 f5 2. c4 e6 +A84 Dutch Defense: Krause Variation 1. d4 f5 2. c4 Nf6 3. Nc3 d6 4. Nf3 Nc6 +A84 Dutch Defense: Normal Variation 1. d4 f5 2. c4 Nf6 +A84 Dutch Defense: Rubinstein Variation 1. d4 f5 2. c4 e6 3. Nc3 +A85 Dutch Defense: Queen's Knight Variation 1. d4 f5 2. c4 Nf6 3. Nc3 +A86 Dutch Defense: Fianchetto Variation 1. d4 f5 2. c4 Nf6 3. g3 +A86 Dutch Defense: Hort-Antoshin System 1. d4 f5 2. c4 Nf6 3. g3 d6 4. Bg2 c6 5. Nc3 Qc7 +A86 Dutch Defense: Leningrad Variation 1. d4 f5 2. c4 Nf6 3. g3 g6 +A87 Dutch Defense: Leningrad Variation 1. d4 f5 2. c4 Nf6 3. g3 g6 4. Bg2 Bg7 5. Nf3 +A88 Dutch Defense: Leningrad Variation, Warsaw Variation 1. d4 f5 2. g3 Nf6 3. Bg2 g6 4. Nf3 Bg7 5. O-O O-O 6. c4 d6 7. Nc3 c6 +A89 Dutch Defense: Leningrad Variation, Matulovic Variation 1. d4 f5 2. g3 Nf6 3. Bg2 g6 4. Nf3 Bg7 5. O-O O-O 6. c4 d6 7. Nc3 Nc6 +A90 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 +A90 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 d5 5. Nf3 +A90 Dutch Defense: Nimzo-Dutch Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Bb4+ +A90 Dutch Defense: Nimzo-Dutch Variation, Alekhine Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Bb4+ 5. Bd2 Be7 +A90 Dutch Defense: Stonewall Variation, Modern Variation 1. d4 f5 2. c4 e6 3. Nf3 Nf6 4. g3 c6 5. Bg2 d5 6. O-O Bd6 +A91 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 +A91 Dutch Defense: Classical Variation, Blackburne Attack 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nh3 +A92 Dutch Defense: Alekhine Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O Ne4 +A92 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O +A92 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. Nc3 +A92 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 +A93 Dutch Defense: Stonewall Variation, Botvinnik Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. b3 +A94 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. b3 c6 8. Ba3 +A95 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. Nc3 c6 +A95 Dutch Defense: Stonewall Variation, Chekhover Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. Nc3 c6 8. Qc2 Qe8 9. Bg5 +A96 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 +A96 Dutch Defense: Classical Variation, Buenos Aires Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 a5 +A96 Dutch Defense: Classical Variation, Huisl Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Ne4 +A97 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 +A97 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation, Winter Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 8. Re1 +A98 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation, Alatortsev-Lisitsyn Line 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 8. Qc2 +A99 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation, Modern Main Line 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 8. b3 diff --git a/crates/openings/data/b.tsv b/crates/openings/data/b.tsv new file mode 100644 index 0000000..ea15fb3 --- /dev/null +++ b/crates/openings/data/b.tsv @@ -0,0 +1,782 @@ +eco name pgn +B00 Barnes Defense 1. e4 f6 +B00 Borg Defense 1. e4 g5 +B00 Borg Defense: Borg Gambit 1. e4 g5 2. d4 Bg7 +B00 Borg Defense: Troon Gambit 1. e4 g5 2. d4 h6 3. h4 g4 +B00 Borg Defense: Zilbermints Gambit 1. e4 g5 2. d4 e5 +B00 Carr Defense 1. e4 h6 +B00 Carr Defense: Zilbermints Gambit 1. e4 h6 2. d4 e5 +B00 Duras Gambit 1. e4 f5 +B00 Fried Fox Defense 1. e4 f6 2. d4 Kf7 +B00 Goldsmith Defense 1. e4 h5 +B00 Goldsmith Defense: Picklepuss Defense 1. e4 h5 2. d4 Nf6 +B00 Hippopotamus Defense 1. e4 Nh6 +B00 Hippopotamus Defense 1. e4 Nh6 2. d4 g6 3. c4 f6 +B00 King's Pawn Game 1. e4 +B00 Lemming Defense 1. e4 Na6 +B00 Lion Defense: Lion's Jaw 1. e4 d6 2. d4 Nf6 3. f3 +B00 Nimzowitsch Defense 1. e4 Nc6 +B00 Nimzowitsch Defense 1. e4 Nc6 2. d4 +B00 Nimzowitsch Defense: Breyer Variation 1. e4 Nc6 2. Nc3 Nf6 3. d4 e5 +B00 Nimzowitsch Defense: Colorado Countergambit 1. e4 Nc6 2. Nf3 f5 +B00 Nimzowitsch Defense: Colorado Countergambit Accepted 1. e4 Nc6 2. Nf3 f5 3. exf5 +B00 Nimzowitsch Defense: Declined Variation 1. e4 Nc6 2. Nf3 +B00 Nimzowitsch Defense: El Columpio Defense 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 +B00 Nimzowitsch Defense: El Columpio Defense, El Columpio Gambit 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 4. d4 d6 5. h3 Nh6 6. e6 +B00 Nimzowitsch Defense: El Columpio Defense, Exchange Variation 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 4. d4 d6 5. h3 Nh6 6. exd6 +B00 Nimzowitsch Defense: El Columpio Defense, Pin Variation 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 4. d4 d6 5. h3 Nh6 6. Bb5 +B00 Nimzowitsch Defense: Franco-Nimzowitsch Variation 1. e4 Nc6 2. Nf3 e6 +B00 Nimzowitsch Defense: French Connection 1. e4 Nc6 2. Nc3 e6 +B00 Nimzowitsch Defense: Hornung Gambit 1. e4 Nc6 2. d4 d5 3. Be3 +B00 Nimzowitsch Defense: Kennedy Variation 1. e4 Nc6 2. d4 e5 +B00 Nimzowitsch Defense: Kennedy Variation, Bielefelder Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 Bc5 +B00 Nimzowitsch Defense: Kennedy Variation, Hammer Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 f6 +B00 Nimzowitsch Defense: Kennedy Variation, Herford Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 Qh4 +B00 Nimzowitsch Defense: Kennedy Variation, Keres Attack 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. Nc3 +B00 Nimzowitsch Defense: Kennedy Variation, Linksspringer Variation 1. e4 Nc6 2. d4 e5 3. d5 +B00 Nimzowitsch Defense: Kennedy Variation, Main Line 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. f4 Ng6 +B00 Nimzowitsch Defense: Kennedy Variation, Paulsen Attack 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. Nf3 +B00 Nimzowitsch Defense: Kennedy Variation, Riemann Defense 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. f4 Nc6 +B00 Nimzowitsch Defense: Kennedy Variation, de Smet Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 d6 +B00 Nimzowitsch Defense: Mikenas Variation 1. e4 Nc6 2. d4 d6 +B00 Nimzowitsch Defense: Neo-Mongoloid Defense 1. e4 Nc6 2. d4 f6 +B00 Nimzowitsch Defense: Pirc Connection 1. e4 Nc6 2. Nc3 g6 +B00 Nimzowitsch Defense: Pseudo-Spanish Variation 1. e4 Nc6 2. Bb5 +B00 Nimzowitsch Defense: Scandinavian Variation 1. e4 Nc6 2. d4 d5 +B00 Nimzowitsch Defense: Scandinavian Variation, Aachen Gambit 1. e4 Nc6 2. d4 d5 3. exd5 Nb4 +B00 Nimzowitsch Defense: Scandinavian Variation, Advance Variation 1. e4 Nc6 2. d4 d5 3. e5 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation 1. e4 Nc6 2. d4 d5 3. Nc3 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Brandics Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 a6 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Erben Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 g6 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Heinola-Deppe Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 e5 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Nimzowitsch Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 4. d5 Ne5 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Richter Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 4. d5 Nb8 5. f3 +B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Vehre Variation 1. e4 Nc6 2. d4 d5 3. Nc3 Nf6 +B00 Nimzowitsch Defense: Scandinavian Variation, Exchange Variation 1. e4 Nc6 2. d4 d5 3. exd5 Qxd5 +B00 Nimzowitsch Defense: Scandinavian Variation, Exchange Variation, Marshall Gambit 1. e4 Nc6 2. d4 d5 3. exd5 Qxd5 4. Nc3 +B00 Nimzowitsch Defense: Wheeler Gambit 1. e4 Nc6 2. b4 +B00 Nimzowitsch Defense: Williams Variation 1. e4 Nc6 2. Nf3 d6 +B00 Nimzowitsch Defense: Woodchuck Variation 1. e4 Nc6 2. d4 a6 +B00 Owen Defense 1. e4 b6 +B00 Owen Defense: Guatemala Defense 1. e4 b6 2. d4 Ba6 +B00 Owen Defense: Hekili-Loa Gambit 1. e4 b6 2. d4 c5 3. dxc5 Nc6 +B00 Owen Defense: Matovinsky Gambit 1. e4 b6 2. d4 Bb7 3. Bd3 f5 4. exf5 Bxg2 5. Qh5+ g6 +B00 Owen Defense: Naselwaus Gambit 1. e4 b6 2. d4 Bb7 3. Bg5 +B00 Owen Defense: Smith Gambit 1. e4 b6 2. d4 Bb7 3. Nf3 +B00 Owen Defense: Unicorn Variation 1. e4 f6 2. d4 b6 3. c4 Bb7 +B00 Owen Defense: Wind Gambit 1. e4 b6 2. d4 Bb7 3. f3 e5 +B00 Pirc Defense 1. e4 d6 +B00 Pirc Defense 1. e4 d6 2. d4 +B00 Pirc Defense 1. e4 d6 2. d4 Nf6 +B00 Pirc Defense: Roscher Gambit 1. e4 d6 2. d4 Nf6 3. Nf3 +B00 Rat Defense: Antal Defense 1. e4 d6 2. d4 Nd7 +B00 Rat Defense: Fuller Gambit 1. e4 d6 2. f4 d5 3. exd5 Nf6 +B00 Rat Defense: Harmonist 1. e4 d6 2. f4 +B00 Rat Defense: Petruccioli Attack 1. e4 d6 2. h4 +B00 Rat Defense: Spike Attack 1. e4 d6 2. g4 +B00 St. George Defense 1. e4 a6 +B00 St. George Defense: Polish Variation 1. e4 a6 2. d4 b5 3. Nf3 Bb7 4. Bd3 e6 +B00 St. George Defense: San Jorge Variation 1. e4 a6 2. d4 b5 3. Nf3 Bb7 4. Bd3 d6 5. O-O g6 6. c3 Bg7 +B00 St. George Defense: Zilbermints Gambit 1. e4 a6 2. d4 e5 +B00 Van Geet Opening: Berlin Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 4. d5 +B00 Ware Defense 1. e4 a5 +B00 Ware Defense: Snagglepuss Defense 1. e4 a5 2. d4 Nc6 +B01 Scandinavian Defense 1. e4 d5 +B01 Scandinavian Defense 1. e4 d5 2. b3 +B01 Scandinavian Defense: Anderssen Counterattack 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 +B01 Scandinavian Defense: Anderssen Counterattack, Collijn Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 5. Nf3 Bg4 +B01 Scandinavian Defense: Anderssen Counterattack, Goteborg System 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 5. Nf3 +B01 Scandinavian Defense: Anderssen Counterattack, Orthodox Attack 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 5. dxe5 Nc6 6. Nf3 Bb4 7. Bd2 +B01 Scandinavian Defense: Blackburne Gambit 1. e4 d5 2. exd5 c6 3. dxc6 Nxc6 +B01 Scandinavian Defense: Blackburne-Kloosterboer Gambit 1. e4 d5 2. exd5 c6 +B01 Scandinavian Defense: Boehnke Gambit 1. e4 d5 2. exd5 e5 3. dxe6 Bxe6 +B01 Scandinavian Defense: Bronstein Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 4. d4 Nf6 5. Nf3 a6 +B01 Scandinavian Defense: Classical Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 5. Nf3 Bf5 +B01 Scandinavian Defense: Grünfeld Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 5. Nf3 Bf5 6. Ne5 c6 7. g4 +B01 Scandinavian Defense: Gubinsky-Melts Defense 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 +B01 Scandinavian Defense: Icelandic-Palme Gambit 1. e4 d5 2. exd5 Nf6 3. c4 e6 +B01 Scandinavian Defense: Kiel Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 4. c4 Nb4 +B01 Scandinavian Defense: Kloosterboer Gambit 1. e4 d5 2. exd5 c6 3. dxc6 e5 +B01 Scandinavian Defense: Kádas Gambit 1. e4 d5 2. exd5 Nf6 3. d4 c6 4. dxc6 e5 +B01 Scandinavian Defense: Lasker Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 5. Nf3 Bg4 6. h3 +B01 Scandinavian Defense: Main Line 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 +B01 Scandinavian Defense: Main Line, Leonhardt Gambit 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. b4 +B01 Scandinavian Defense: Main Line, Mieses Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 +B01 Scandinavian Defense: Marshall Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 +B01 Scandinavian Defense: Mieses-Kotroc Variation 1. e4 d5 2. exd5 Qxd5 +B01 Scandinavian Defense: Modern Variation 1. e4 d5 2. exd5 Nf6 +B01 Scandinavian Defense: Modern Variation 1. e4 d5 2. exd5 Nf6 3. d4 +B01 Scandinavian Defense: Modern Variation, Gipslis Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 4. Nf3 Bg4 +B01 Scandinavian Defense: Modern Variation, Wing Gambit 1. e4 d5 2. exd5 Nf6 3. d4 g6 4. c4 b5 +B01 Scandinavian Defense: Panov Transfer 1. e4 d5 2. exd5 Nf6 3. c4 c6 +B01 Scandinavian Defense: Portuguese Gambit 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 +B01 Scandinavian Defense: Portuguese Gambit, Banker Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. c4 +B01 Scandinavian Defense: Portuguese Gambit, Classical Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Nf3 +B01 Scandinavian Defense: Portuguese Gambit, Correspondence Refutation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. g4 +B01 Scandinavian Defense: Portuguese Gambit, Elbow Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Bb5+ c6 +B01 Scandinavian Defense: Portuguese Gambit, Jadoul Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. Bb5+ Nbd7 6. c4 +B01 Scandinavian Defense: Portuguese Gambit, Lusophobe Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Bb5+ Nbd7 5. Be2 +B01 Scandinavian Defense: Portuguese Gambit, Melbourne Shuffle Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. Bb5+ Nbd7 6. Nc3 +B01 Scandinavian Defense: Portuguese Gambit, Wuss Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Be2 +B01 Scandinavian Defense: Richter Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 4. Nf3 g6 +B01 Scandinavian Defense: Richter Variation 1. e4 d5 2. exd5 Nf6 3. d4 g6 +B01 Scandinavian Defense: Schiller-Pytel Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 4. d4 c6 +B01 Scandinavian Defense: Schiller-Pytel Variation, Modern Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 4. d4 Nf6 5. Bc4 c6 6. Nge2 Bf5 7. Bf4 Qb4 +B01 Scandinavian Defense: Valencian Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd8 +B01 Scandinavian Defense: Valencian Variation, Ilundain Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd8 4. d4 Nf6 5. Nf3 c6 +B01 Scandinavian Defense: Valencian Variation, Main Line 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd8 4. d4 Nf6 5. Nf3 Bg4 +B01 Scandinavian Defense: Zilbermints Gambit 1. e4 d5 2. b4 +B01 Van Geet Opening: Grünfeld Defense 1. e4 d5 2. Nc3 dxe4 3. Nxe4 e5 +B02 Alekhine Defense 1. e4 Nf6 +B02 Alekhine Defense: Brooklyn Variation 1. e4 Nf6 2. e5 Ng8 +B02 Alekhine Defense: Brooklyn Variation, Everglades Variation 1. e4 Nf6 2. e5 Ng8 3. d4 f5 +B02 Alekhine Defense: Buckley Attack 1. e4 Nf6 2. e5 Nd5 3. Na3 +B02 Alekhine Defense: Hunt Variation, Lasker Simul Gambit 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Bc4 e6 6. Nc3 +B02 Alekhine Defense: Hunt Variation, Matsukevich Gambit 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Nc3 Nxc3 6. dxc3 d6 7. Bg5 +B02 Alekhine Defense: Hunt Variation, Mikenas Gambit 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Bc4 e6 6. Nc3 d6 7. Nxd5 exd5 8. Bxd5 +B02 Alekhine Defense: Kmoch Variation 1. e4 Nf6 2. e5 Nd5 3. Bc4 Nb6 4. Bb3 c5 5. d3 +B02 Alekhine Defense: Krejcik Variation 1. e4 Nf6 2. Bc4 +B02 Alekhine Defense: Krejcik Variation, Krejcik Gambit 1. e4 Nf6 2. Bc4 Nxe4 3. Bxf7+ +B02 Alekhine Defense: Maróczy Variation 1. e4 Nf6 2. d3 +B02 Alekhine Defense: Mokele Mbembe 1. e4 Nf6 2. e5 Ne4 +B02 Alekhine Defense: Mokele Mbembe, Modern Line 1. e4 Nf6 2. e5 Ne4 3. d4 f6 +B02 Alekhine Defense: Mokele Mbembe, Vavra Defense 1. e4 Nf6 2. e5 Ne4 3. d4 e6 +B02 Alekhine Defense: Normal Variation 1. e4 Nf6 2. e5 Nd5 +B02 Alekhine Defense: Scandinavian Variation 1. e4 Nf6 2. Nc3 d5 +B02 Alekhine Defense: Scandinavian Variation, Geschev Gambit 1. e4 Nf6 2. Nc3 d5 3. exd5 c6 +B02 Alekhine Defense: Scandinavian Variation, Myers Gambit 1. e4 Nf6 2. Nc3 d5 3. d3 dxe4 4. Bg5 +B02 Alekhine Defense: Spielmann Gambit 1. e4 Nf6 2. Nc3 d5 3. e5 Nfd7 4. e6 +B02 Alekhine Defense: Steiner Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. b3 +B02 Alekhine Defense: Sämisch Attack 1. e4 Nf6 2. e5 Nd5 3. Nc3 +B02 Alekhine Defense: The Squirrel 1. e4 Nf6 2. e5 Nd5 3. c4 Nf4 +B02 Alekhine Defense: Two Pawns Attack 1. e4 Nf6 2. e5 Nd5 3. c4 +B02 Alekhine Defense: Two Pawns Attack, Lasker Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 +B02 Alekhine Defense: Two Pawns Attack, Mikenas Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Bc4 e6 6. Nc3 d6 +B02 Alekhine Defense: Two Pawns Attack, Tate Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. a4 +B02 Alekhine Defense: Welling Variation 1. e4 Nf6 2. e5 Nd5 3. b3 +B03 Alekhine Defense 1. e4 Nf6 2. e5 Nd5 3. d4 +B03 Alekhine Defense 1. e4 Nf6 2. e5 Nd5 3. d4 d6 +B03 Alekhine Defense 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 +B03 Alekhine Defense: Balogh Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Bc4 +B03 Alekhine Defense: Exchange Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. exd6 +B03 Alekhine Defense: Exchange Variation, Karpov Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. exd6 cxd6 6. Nc3 g6 7. h3 Bg7 8. Nf3 O-O 9. Be2 Nc6 10. O-O Bf5 11. Bf4 +B03 Alekhine Defense: Exchange Variation, Voronezh Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. exd6 cxd6 6. Nc3 g6 7. Be3 Bg7 8. Rc1 O-O 9. b3 +B03 Alekhine Defense: Four Pawns Attack 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 +B03 Alekhine Defense: Four Pawns Attack, Cambridge Gambit 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 g5 +B03 Alekhine Defense: Four Pawns Attack, Fianchetto Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 g6 +B03 Alekhine Defense: Four Pawns Attack, Ilyin-Zhenevsky Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Nc6 7. Nf3 Bg4 8. e6 fxe6 9. c5 +B03 Alekhine Defense: Four Pawns Attack, Korchnoi Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Bf5 7. Nc3 e6 8. Nf3 Be7 9. Be2 O-O 10. O-O f6 +B03 Alekhine Defense: Four Pawns Attack, Main Line 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Nc6 7. Be3 +B03 Alekhine Defense: Four Pawns Attack, Tartakower Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Nc6 7. Be3 Bf5 8. Nc3 e6 9. Nf3 Qd7 10. Be2 O-O-O 11. O-O Be7 +B03 Alekhine Defense: Four Pawns Attack, Trifunovic Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 Bf5 +B03 Alekhine Defense: Hunt Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. c5 +B03 Alekhine Defense: Modern Variation, Alekhine Gambit 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. Nf3 Bg4 6. Be2 +B03 Alekhine Defense: O'Sullivan Gambit 1. e4 Nf6 2. e5 Nd5 3. d4 b5 +B04 Alekhine Defense: Modern Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 +B04 Alekhine Defense: Modern Variation, Alburt Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 g6 +B04 Alekhine Defense: Modern Variation, Keres Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 g6 5. Bc4 Nb6 6. Bb3 Bg7 7. a4 +B04 Alekhine Defense: Modern Variation, Larsen Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 dxe5 +B04 Alekhine Defense: Modern Variation, Larsen-Haakert Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Nc6 +B04 Alekhine Defense: Modern Variation, Schmid Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Nb6 +B05 Alekhine Defense: Modern Variation, Alekhine Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. c4 +B05 Alekhine Defense: Modern Variation, Flohr Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. Be2 c6 +B05 Alekhine Defense: Modern Variation, Main Line 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 +B05 Alekhine Defense: Modern Variation, Panov Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. h3 +B05 Alekhine Defense: Modern Variation, Vitolins Attack 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. c4 Nb6 6. d5 +B06 Modern Defense 1. e4 g6 +B06 Modern Defense 1. e4 g6 2. d4 Bg7 +B06 Modern Defense: Anti-Modern 1. e4 g6 2. d4 Bg7 3. Nc3 c6 4. Bc4 d6 5. Qe2 +B06 Modern Defense: Bishop Attack 1. e4 g6 2. d4 Bg7 3. Bc4 +B06 Modern Defense: Bishop Attack, Bücker Gambit 1. e4 g6 2. d4 Bg7 3. Bc4 b5 +B06 Modern Defense: Bishop Attack, Monkey's Bum 1. e4 g6 2. Bc4 Bg7 3. Qf3 e6 4. d4 Bxd4 +B06 Modern Defense: Dunworthy Variation 1. e4 g6 2. d4 Bg7 3. c4 d5 4. exd5 c6 5. dxc6 Bxd4 +B06 Modern Defense: Fianchetto Gambit 1. e4 g6 2. d4 f5 +B06 Modern Defense: Gurgenidze Defense 1. e4 g6 2. d4 Bg7 3. Nc3 c6 4. f4 d5 5. e5 h5 +B06 Modern Defense: Lizard Defense, Mittenberger Gambit 1. e4 g6 2. d4 Bg7 3. Nc3 d5 +B06 Modern Defense: Masur Gambit 1. e4 g6 2. d4 Nh6 3. Nc3 f5 4. Bxh6 Bxh6 5. exf5 O-O +B06 Modern Defense: Modern Pterodactyl 1. e4 g6 2. d4 Bg7 3. Nc3 c5 +B06 Modern Defense: Mongredien Defense, with Nc3 1. e4 g6 2. d4 Bg7 3. Nc3 b6 +B06 Modern Defense: Mongredien Defense, with Nf3 1. e4 g6 2. d4 Bg7 3. Nf3 b6 +B06 Modern Defense: Norwegian Defense 1. e4 g6 2. d4 Nf6 +B06 Modern Defense: Norwegian Defense, Norwegian Gambit 1. e4 g6 2. d4 Nf6 3. e5 Nh5 4. Be2 d6 +B06 Modern Defense: Pseudo-Austrian Attack 1. e4 g6 2. d4 Bg7 3. Nc3 d6 4. f4 +B06 Modern Defense: Semi-Averbakh Variation, Pterodactyl Variation Declined 1. e4 g6 2. d4 Bg7 3. c4 c5 4. Nf3 d6 5. Be2 Qa5+ +B06 Modern Defense: Standard Defense 1. e4 g6 2. d4 Bg7 3. Nc3 d6 +B06 Modern Defense: Standard Line 1. e4 g6 2. d4 Bg7 3. Nc3 +B06 Modern Defense: Three Pawns Attack 1. e4 g6 2. d4 Bg7 3. f4 +B06 Modern Defense: Two Knights Variation 1. e4 g6 2. d4 Bg7 3. Nc3 d6 4. Nf3 +B06 Modern Defense: Two Knights Variation, Suttles Variation 1. e4 g6 2. d4 Bg7 3. Nc3 c6 4. Nf3 d6 +B06 Modern Defense: Two Knights Variation, Suttles Variation, Tal Gambit 1. e4 g6 2. d4 Bg7 3. Nc3 d6 4. Nf3 c6 5. Bg5 Qb6 6. Qd2 Qxb2 +B06 Modern Defense: Westermann Gambit 1. e4 g6 2. d4 Bg7 3. Bd2 +B06 Modern Defense: Wind Gambit 1. e4 g6 2. d4 Bg7 3. Bd3 +B06 Pterodactyl Defense: Austrian, Austriadactylus Western 1. e4 g6 2. d4 Bg7 3. f4 c5 4. Nf3 Qa5+ +B06 Pterodactyl Defense: Austrian, Grand Prix Pterodactyl 1. e4 g6 2. Nc3 Bg7 3. f4 c5 4. Nf3 Qa5 +B06 Pterodactyl Defense: Austrian, Pteranodon 1. e4 g6 2. d4 Bg7 3. f4 c5 4. c3 Qa5 +B06 Pterodactyl Defense: Central, Anhanguera 1. e4 g6 2. d4 Bg7 3. c4 c5 4. Nc3 d6 5. Be3 Qa5 +B06 Pterodactyl Defense: Central, Benoni Quetzalcoatlus 1. e4 g6 2. d4 Bg7 3. c4 c5 4. d5 d6 5. Nc3 Qa5 +B06 Pterodactyl Defense: Central, Quetzalcoatlus Gambit 1. e4 g6 2. d4 Bg7 3. c4 c5 4. Nc3 d6 5. dxc5 Qa5 +B06 Pterodactyl Defense: Eastern, Anhanguera 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. Be3 +B06 Pterodactyl Defense: Eastern, Benoni 1. d4 g6 2. e4 Bg7 3. Nc3 c5 4. d5 +B06 Pterodactyl Defense: Eastern, Benoni Pteranodon 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. d5 Bxc3+ 5. bxc3 Qa5 +B06 Pterodactyl Defense: Eastern, Benoni Pterodactyl 1. d4 g6 2. Nc3 Bg7 3. e4 c5 4. d5 Qa5 +B06 Pterodactyl Defense: Eastern, Pteranodon 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. dxc5 Bxc3+ 5. bxc3 Qa5 +B06 Pterodactyl Defense: Eastern, Rhamphorhynchus 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. dxc5 Qa5 +B06 Pterodactyl Defense: Fianchetto, King Pterodactyl 1. e4 g6 2. d4 Bg7 3. g3 c5 4. Nf3 Qa5+ +B06 Pterodactyl Defense: Fianchetto, Rhamphorhynchus 1. e4 g6 2. d4 Bg7 3. g3 c5 4. dxc5 Qa5+ +B06 Pterodactyl Defense: Sicilian, Quetzalcoatlus 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. Nf3 Qa5 5. Be2 d6 +B06 Pterodactyl Defense: Sicilian, Siroccopteryx 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. Nf3 Qa5 5. Bc4 +B06 Pterodactyl Defense: Western, Anhanguera 1. e4 g6 2. d4 Bg7 3. Nf3 c5 4. Be3 Qa5+ +B06 Pterodactyl Defense: Western, Siroccopteryx 1. e4 g6 2. Nf3 Bg7 3. d4 c5 4. Bc4 cxd4 5. Nxd4 Qa5+ +B06 Rat Defense: Accelerated Gurgenidze 1. e4 g6 2. d4 d6 3. Nc3 c6 +B07 Czech Defense 1. e4 d6 2. d4 Nf6 3. Nc3 c6 +B07 King's Pawn Game: Maróczy Defense 1. e4 d6 2. d4 e5 +B07 Lion Defense 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 +B07 Lion Defense: Anti-Philidor 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. f4 +B07 Lion Defense: Anti-Philidor, Lion's Cave 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. f4 e5 +B07 Lion Defense: Anti-Philidor, Lion's Cave, Lion Claw Gambit 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. f4 e5 5. Nf3 exd4 6. Qxd4 c6 7. Bc4 d5 +B07 Lion Defense: Bayonet Attack 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. g4 +B07 Modern Defense: Geller's System 1. e4 g6 2. d4 Bg7 3. Nf3 d6 4. c3 +B07 Pirc Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 +B07 Pirc Defense: 150 Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 c6 5. Qd2 +B07 Pirc Defense: 150 Attack, Inner Doll Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 c6 5. Qd2 Bg4 +B07 Pirc Defense: 150 Attack, Sveshnikov-Jansa Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 c6 5. h3 +B07 Pirc Defense: Bayonet Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be2 Bg7 5. h4 +B07 Pirc Defense: Byrne Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Bg5 +B07 Pirc Defense: Chinese Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be2 Bg7 5. g4 +B07 Pirc Defense: Kholmov System 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Bc4 +B07 Pirc Defense: Sveshnikov System 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. g3 +B08 Pirc Defense: Classical Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 +B08 Pirc Defense: Classical Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 +B08 Pirc Defense: Classical Variation, Quiet System 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 +B08 Pirc Defense: Classical Variation, Quiet System, Chigorin Line 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 O-O 6. O-O Nc6 +B08 Pirc Defense: Classical Variation, Quiet System, Czech Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 O-O 6. O-O c6 +B08 Pirc Defense: Classical Variation, Quiet System, Parma Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 O-O 6. O-O Bg4 +B08 Pirc Defense: Classical Variation, Schlechter Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. h3 +B09 Pirc Defense: Austrian Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 +B09 Pirc Defense: Austrian Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O +B09 Pirc Defense: Austrian Attack, Dragon Formation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 c5 +B09 Pirc Defense: Austrian Attack, Kurajica Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. Be3 +B09 Pirc Defense: Austrian Attack, Ljubojevic Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Bc4 +B09 Pirc Defense: Austrian Attack, Unzicker Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. e5 +B09 Pirc Defense: Austrian Attack, Unzicker Attack, Bronstein Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. e5 Nfd7 7. h4 +B09 Pirc Defense: Austrian Attack, Weiss Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. Bd3 +B10 Caro-Kann Defense 1. e4 c6 +B10 Caro-Kann Defense 1. e4 c6 2. Nc3 +B10 Caro-Kann Defense 1. e4 c6 2. Nc3 d5 +B10 Caro-Kann Defense: Accelerated Panov Attack 1. e4 c6 2. c4 +B10 Caro-Kann Defense: Accelerated Panov Attack 1. e4 c6 2. c4 d5 +B10 Caro-Kann Defense: Accelerated Panov Attack, Modern Variation 1. e4 c6 2. c4 d5 3. exd5 cxd5 4. cxd5 Nf6 +B10 Caro-Kann Defense: Accelerated Panov Attack, Open Variation 1. e4 c6 2. c4 e5 +B10 Caro-Kann Defense: Accelerated Panov Attack, Pseudo-Scandinavian 1. e4 c6 2. c4 d5 3. exd5 cxd5 4. cxd5 Qxd5 +B10 Caro-Kann Defense: Accelerated Panov Attack, Van Weersel Attack 1. e4 c6 2. c4 d5 3. cxd5 cxd5 4. Qb3 +B10 Caro-Kann Defense: Apocalypse Attack 1. e4 c6 2. Nf3 d5 3. exd5 cxd5 4. Ne5 +B10 Caro-Kann Defense: Breyer Variation 1. e4 c6 2. d3 +B10 Caro-Kann Defense: Breyer Variation, Stein Attack 1. e4 c6 2. d3 d5 3. Nd2 g6 4. Ngf3 Bg7 5. g3 e5 6. Bg2 Ne7 7. O-O O-O 8. b4 +B10 Caro-Kann Defense: Dinic Gambit 1. e4 c6 2. Nf3 d5 3. d3 dxe4 4. Ng5 +B10 Caro-Kann Defense: Endgame Offer 1. e4 c6 2. Nf3 d5 3. d3 +B10 Caro-Kann Defense: Endgame Variation 1. e4 c6 2. Nf3 d5 3. d3 dxe4 4. dxe4 Qxd1+ 5. Kxd1 +B10 Caro-Kann Defense: Euwe Attack 1. e4 c6 2. b3 +B10 Caro-Kann Defense: Goldman Variation 1. e4 c6 2. Nc3 d5 3. Qf3 +B10 Caro-Kann Defense: Hector Gambit 1. e4 c6 2. Nc3 d5 3. Nf3 dxe4 4. Ng5 +B10 Caro-Kann Defense: Hillbilly Attack 1. e4 c6 2. Bc4 +B10 Caro-Kann Defense: Hillbilly Attack, Schaeffer Gambit 1. e4 c6 2. Bc4 d5 3. Bb3 dxe4 4. Qh5 +B10 Caro-Kann Defense: Labahn Attack 1. e4 c6 2. b4 +B10 Caro-Kann Defense: Labahn Attack, Double Gambit 1. e4 c6 2. b4 d5 3. b5 +B10 Caro-Kann Defense: Labahn Attack, Polish Variation 1. e4 c6 2. b4 e5 3. Bb2 +B10 Caro-Kann Defense: Scorpion-Horus Gambit 1. e4 c6 2. Nc3 d5 3. d3 dxe4 4. Bg5 +B10 Caro-Kann Defense: Spike Variation 1. e4 c6 2. g4 +B10 Caro-Kann Defense: Spike Variation, Scorpion-Grob Gambit 1. e4 c6 2. g4 d5 3. Nc3 dxe4 4. d3 +B10 Caro-Kann Defense: St. Patrick's Attack 1. e4 c6 2. Nc3 d5 3. h3 +B10 Caro-Kann Defense: Toikkanen Gambit 1. e4 c6 2. c4 d5 3. e5 +B10 Caro-Kann Defense: Two Knights Attack 1. e4 c6 2. Nc3 d5 3. Nf3 +B11 Caro-Kann Defense: Two Knights Attack, Mindeno Variation 1. e4 c6 2. Nc3 d5 3. Nf3 Bg4 +B11 Caro-Kann Defense: Two Knights Attack, Mindeno Variation, Exchange Line 1. e4 c6 2. Nc3 d5 3. Nf3 Bg4 4. h3 Bxf3 +B11 Caro-Kann Defense: Two Knights Attack, Mindeno Variation, Retreat Line 1. e4 c6 2. Nc3 d5 3. Nf3 Bg4 4. h3 Bh5 +B12 Caro-Kann Defense 1. e4 c6 2. d4 +B12 Caro-Kann Defense 1. e4 c6 2. d4 d5 +B12 Caro-Kann Defense: Advance Variation 1. e4 c6 2. d4 d5 3. e5 +B12 Caro-Kann Defense: Advance Variation, Bayonet Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. g4 +B12 Caro-Kann Defense: Advance Variation, Botvinnik-Carls Defense 1. e4 c6 2. d4 d5 3. e5 c5 +B12 Caro-Kann Defense: Advance Variation, Bronstein Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Ne2 +B12 Caro-Kann Defense: Advance Variation, Prins Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. b4 +B12 Caro-Kann Defense: Advance Variation, Short Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nf3 +B12 Caro-Kann Defense: Advance Variation, Tal Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. h4 +B12 Caro-Kann Defense: Advance Variation, Van der Wiel Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nc3 +B12 Caro-Kann Defense: Advance Variation, Van der Wiel Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nc3 e6 5. g4 Bg6 6. Nge2 c5 7. h4 +B12 Caro-Kann Defense: Advance Variation, Van der Wiel Attack, Dreyev Defense 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nc3 Qb6 +B12 Caro-Kann Defense: Advance, Short Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. c3 e6 5. Be2 +B12 Caro-Kann Defense: De Bruycker Defense 1. e4 c6 2. d4 Na6 +B12 Caro-Kann Defense: De Bruycker Defense 1. e4 c6 2. d4 Na6 3. Nc3 Nc7 +B12 Caro-Kann Defense: Edinburgh Variation 1. e4 c6 2. d4 d5 3. Nd2 Qb6 +B12 Caro-Kann Defense: Maróczy Variation 1. e4 c6 2. d4 d5 3. f3 +B12 Caro-Kann Defense: Maróczy Variation, Maróczy Gambit 1. e4 c6 2. d4 d5 3. f3 dxe4 4. fxe4 e5 5. Nf3 exd4 6. Bc4 +B12 Caro-Kann Defense: Masi Variation 1. e4 c6 2. d4 Nf6 +B12 Caro-Kann Defense: Massachusetts Defense 1. e4 c6 2. d4 f5 +B12 Caro-Kann Defense: Mieses Attack, Landau Gambit 1. e4 c6 2. d4 d5 3. Bd3 Nf6 4. e5 Nfd7 5. e6 +B12 Caro-Kann Defense: Mieses Gambit 1. e4 c6 2. d4 d5 3. Be3 +B12 Caro-Kann Defense: Modern Variation 1. e4 c6 2. d4 d5 3. Nd2 +B12 Caro-Kann Defense: Ulysses Gambit 1. e4 c6 2. d4 d5 3. Nf3 dxe4 4. Ng5 +B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 +B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 +B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. Bf4 +B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. Nf3 Nc6 +B13 Caro-Kann Defense: Exchange Variation, Bulla Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. g4 +B13 Caro-Kann Defense: Exchange Variation, Rubinstein Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. Bd3 Nc6 5. c3 Nf6 6. Bf4 +B13 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 +B13 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 +B13 Caro-Kann Defense: Panov Attack, Gunderam Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. c5 +B13 Caro-Kann Defense: Panov Attack, Modern Defense 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 +B13 Caro-Kann Defense: Panov Attack, Modern Defense, Carlsbad Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 e6 +B13 Caro-Kann Defense: Panov Attack, Modern Defense, Czerniak Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 Qa5 +B13 Caro-Kann Defense: Panov Attack, Modern Defense, Mieses Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Nf3 Bg4 +B13 Caro-Kann Defense: Panov Attack, Modern Defense, Reifir-Spielmann Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 Qb6 +B13 Caro-Kann Defense: Panov-Botvinnik, Herzog Defense 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 dxc4 7. d5 Na5 +B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 e6 +B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nc6 5. Nc3 Nf6 6. Nf3 e6 7. cxd5 exd5 8. Bb5 Bg4 +B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nc6 5. Nc3 Nf6 6. Nf3 e6 7. cxd5 exd5 8. Bb5 Bd6 9. Bg5 O-O 10. O-O +B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Nf3 e6 7. c5 +B14 Caro-Kann Defense: Panov Attack, Fianchetto Defense 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 g6 +B14 Caro-Kann Defense: Panov Attack, Fianchetto Defense, Fianchetto Gambit 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 g6 6. cxd5 Bg7 +B14 Caro-Kann Defense: Panov Attack, Main Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 e6 6. Nf3 Bb4 +B15 Caro-Kann Defense 1. e4 c6 2. d4 d5 3. Nc3 +B15 Caro-Kann Defense 1. e4 c6 2. d4 d5 3. Nc3 dxe4 +B15 Caro-Kann Defense: Alekhine Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Bd3 +B15 Caro-Kann Defense: Alien Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Ng5 h6 6. Nxf7 +B15 Caro-Kann Defense: Campomanes Attack 1. e4 c6 2. d4 d5 3. Nc3 Nf6 +B15 Caro-Kann Defense: Forgacs Variation 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ exf6 6. Bc4 +B15 Caro-Kann Defense: Gurgenidze Counterattack 1. e4 c6 2. d4 d5 3. Nc3 b5 +B15 Caro-Kann Defense: Gurgenidze System 1. e4 c6 2. d4 d5 3. Nc3 g6 +B15 Caro-Kann Defense: Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 +B15 Caro-Kann Defense: Rasa-Studier Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. f3 +B15 Caro-Kann Defense: Tartakower Variation 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ exf6 +B15 Caro-Kann Defense: Tartakower Variation, Perlis Line 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ exf6 6. c3 Bd6 7. Bd3 O-O 8. Qc2 h6 +B15 Caro-Kann Defense: von Hennig Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Bc4 +B16 Caro-Kann Defense: Bronstein-Larsen Variation 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ gxf6 +B16 Caro-Kann Defense: Finnish Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 h6 +B17 Caro-Kann Defense: Karpov Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 +B17 Caro-Kann Defense: Karpov Variation, Modern Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Ng5 Ngf6 6. Bd3 e6 7. N1f3 Bd6 8. Qe2 h6 9. Ne4 Nxe4 10. Qxe4 +B17 Caro-Kann Defense: Karpov Variation, Modern Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Ng5 +B17 Caro-Kann Defense: Karpov Variation, Modern Variation, Ivanchuk Defense 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Ng5 Ndf6 +B17 Caro-Kann Defense: Karpov Variation, Modern Variation, Kasparov Attack 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nd7 5. Nf3 Ngf6 6. Ng3 +B17 Caro-Kann Defense: Karpov Variation, Smyslov Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Bc4 Ngf6 6. Ng5 e6 7. Qe2 Nb6 +B17 Caro-Kann Defense: Karpov Variation, Smyslov Variation, Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Bc4 Ngf6 6. Ng5 e6 7. Qe2 Nb6 8. Bb3 +B17 Caro-Kann Defense: Karpov Variation, Tiviakov-Fischer Attack 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Bc4 Ngf6 6. Nxf6+ Nxf6 +B18 Caro-Kann Defense: Classical Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 +B18 Caro-Kann Defense: Classical Variation, Flohr Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. Nh3 +B18 Caro-Kann Defense: Classical Variation, Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 +B18 Caro-Kann Defense: Classical Variation, Maróczy Attack 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. f4 +B18 Caro-Kann Defense: Martian Gambit 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng5 Bg6 6. N1f3 h6 7. Ne6 +B19 Caro-Kann Defense: Classical Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 +B19 Caro-Kann Defense: Classical Variation, Lobron System 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 8. h5 Bh7 9. Bd3 Bxd3 10. Qxd3 e6 11. Bd2 Ngf6 12. O-O-O Be7 +B19 Caro-Kann Defense: Classical Variation, Seirawan Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 8. h5 Bh7 9. Bd3 Bxd3 10. Qxd3 Ngf6 11. Bd2 e6 12. O-O-O Bd6 +B19 Caro-Kann Defense: Classical Variation, Spassky Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 8. h5 +B20 Sicilian Defense 1. e4 c5 +B20 Sicilian Defense: Amazon Attack 1. e4 c5 2. Qg4 +B20 Sicilian Defense: Big Clamp Formation 1. e4 c5 2. d3 Nc6 3. c3 d6 4. f4 +B20 Sicilian Defense: Bowdler Attack 1. e4 c5 2. Bc4 +B20 Sicilian Defense: Brick Variation 1. e4 c5 2. Nh3 +B20 Sicilian Defense: Czerniak Attack 1. e4 c5 2. b3 +B20 Sicilian Defense: Czerniak Attack, Queen Fianchetto Variation 1. e4 c5 2. b3 b6 +B20 Sicilian Defense: Euwe Attack, Prins Gambit 1. e4 c5 2. b3 d5 3. Bb2 +B20 Sicilian Defense: Gloria Variation 1. e4 c5 2. c4 d6 3. Nc3 Nc6 4. g3 h5 +B20 Sicilian Defense: Grob Variation 1. e4 c5 2. g4 +B20 Sicilian Defense: Keres Variation 1. e4 c5 2. Ne2 +B20 Sicilian Defense: King David's Opening 1. e4 c5 2. Ke2 +B20 Sicilian Defense: Kronberger Variation 1. e4 c5 2. Na3 +B20 Sicilian Defense: Kronberger Variation, Nemeth Gambit 1. e4 c5 2. Na3 Nc6 3. d4 cxd4 4. Bc4 +B20 Sicilian Defense: Lasker-Dunne Attack 1. e4 c5 2. g3 +B20 Sicilian Defense: Mengarini Variation 1. e4 c5 2. a3 +B20 Sicilian Defense: Myers Attack, with a4 1. e4 c5 2. a4 +B20 Sicilian Defense: Myers Attack, with h4 1. e4 c5 2. h4 +B20 Sicilian Defense: Staunton-Cochrane Variation 1. e4 c5 2. c4 +B20 Sicilian Defense: Wing Gambit 1. e4 c5 2. b4 +B20 Sicilian Defense: Wing Gambit, Abrahams Variation 1. e4 c5 2. b4 cxb4 3. Bb2 +B20 Sicilian Defense: Wing Gambit, Carlsbad Variation 1. e4 c5 2. b4 cxb4 3. a3 bxa3 +B20 Sicilian Defense: Wing Gambit, Marienbad Variation 1. e4 c5 2. b4 cxb4 3. a3 d5 4. exd5 Qxd5 5. Bb2 +B20 Sicilian Defense: Wing Gambit, Marshall Variation 1. e4 c5 2. b4 cxb4 3. a3 +B20 Sicilian Defense: Wing Gambit, Nanu Gambit 1. e4 c5 2. b4 cxb4 3. a3 d5 4. exd5 Qxd5 5. Nf3 e5 6. c4 Qe6 7. Bd3 +B20 Sicilian Defense: Wing Gambit, Romanian Defense 1. e4 c5 2. b4 cxb4 3. a3 d5 4. exd5 Qxd5 5. Nf3 e5 6. Bb2 Nc6 7. c4 Qe6 +B20 Sicilian Defense: Wing Gambit, Santasiere Variation 1. e4 c5 2. b4 cxb4 3. c4 +B21 Bird Opening: Dutch Variation, Batavo Gambit 1. e4 c5 2. f4 d5 3. Nf3 dxe4 +B21 Sicilian Defense: Coles Sicilian Gambit 1. e4 c5 2. d4 cxd4 3. Qxd4 Nc6 4. Qd1 Nf6 5. Bc4 +B21 Sicilian Defense: Halasz Gambit 1. e4 c5 2. d4 cxd4 3. f4 +B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 +B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 e6 +B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 e6 4. d3 +B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 g6 4. Bb5 Bg7 +B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 g6 4. Bb5 Bg7 5. c3 Nf6 +B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 g6 4. Bb5 Bg7 5. Bxc6 bxc6 6. O-O d6 7. d3 Nf6 +B21 Sicilian Defense: McDonnell Attack, Tal Gambit 1. e4 c5 2. f4 d5 3. exd5 Nf6 +B21 Sicilian Defense: McDonnell Attack, Toilet Variation 1. e4 c5 2. f4 d5 3. Nc3 +B21 Sicilian Defense: Morphy Gambit 1. e4 c5 2. d4 cxd4 3. Nf3 +B21 Sicilian Defense: Morphy Gambit, Andreaschek Gambit 1. e4 c5 2. d4 cxd4 3. Nf3 e5 4. c3 +B21 Sicilian Defense: Smith-Morra Gambit 1. e4 c5 2. d4 +B21 Sicilian Defense: Smith-Morra Gambit 1. e4 c5 2. d4 cxd4 3. c3 +B21 Sicilian Defense: Smith-Morra Gambit Accepted 1. e4 c5 2. d4 cxd4 3. c3 dxc3 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Chicago Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Bc4 e6 6. Nf3 d6 7. O-O a6 8. Qe2 b5 9. Bb3 Ra7 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Chicago Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 d6 5. Nf3 e6 6. Bc4 Nf6 7. O-O a6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Classical Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 d6 6. Bc4 a6 7. O-O Nf6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Danish Variation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nf3 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 g6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 g6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 d6 6. Bc4 g6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 d6 5. Nf3 g6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Finegold Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 e6 5. Nf3 d6 6. Bc4 a6 7. O-O Be7 8. Qe2 Nf6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Kan Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 e6 5. Nf3 a6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Larsen Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Qc7 7. Qe2 a6 8. O-O Bd6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Morphy Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Bc5 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Morphy Defense Deferred 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 a6 7. O-O b5 8. Bb3 Bc5 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Paulsen Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 a6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Pin Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Bb4 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Scheveningen Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 d6 6. Bc4 e6 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Siberian Variation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Qc7 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Siberian Variation, Siberian Trap 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Qc7 7. Qe2 Nf6 8. O-O Ng4 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Sozin Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Bc4 e6 6. Nf3 d6 7. O-O a6 8. Qe2 b5 +B21 Sicilian Defense: Smith-Morra Gambit Accepted, Taimanov Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 e6 5. Bc4 a6 6. Nf3 Ne7 +B21 Sicilian Defense: Smith-Morra Gambit Declined, Alapin Formation 1. e4 c5 2. d4 cxd4 3. c3 Nf6 +B21 Sicilian Defense: Smith-Morra Gambit Declined, Center Formation 1. e4 c5 2. d4 cxd4 3. c3 e5 +B21 Sicilian Defense: Smith-Morra Gambit Declined, Dubois Variation 1. e4 c5 2. d4 cxd4 3. c3 d3 4. c4 +B21 Sicilian Defense: Smith-Morra Gambit Declined, Push Variation 1. e4 c5 2. d4 cxd4 3. c3 d3 +B21 Sicilian Defense: Smith-Morra Gambit Declined, Scandinavian Formation 1. e4 c5 2. d4 cxd4 3. c3 d5 +B21 Sicilian Defense: Smith-Morra Gambit Declined, Wing Formation 1. e4 c5 2. d4 cxd4 3. c3 Qa5 +B22 Sicilian Defense: Alapin Variation 1. e4 c5 2. c3 +B22 Sicilian Defense: Alapin Variation, Anti-Alapin Gambit 1. e4 c5 2. c3 d5 3. exd5 Nf6 +B22 Sicilian Defense: Alapin Variation, Barmen Defense 1. e4 c5 2. c3 d5 3. exd5 Qxd5 +B22 Sicilian Defense: Alapin Variation, Barmen Defense 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 g6 5. Nf3 +B22 Sicilian Defense: Alapin Variation, Barmen Defense 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 Nc6 5. Nf3 +B22 Sicilian Defense: Alapin Variation, Barmen Defense, Central Exchange 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 cxd4 5. cxd4 Nc6 6. Nf3 Bg4 +B22 Sicilian Defense: Alapin Variation, Barmen Defense, Endgame Variation 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 cxd4 5. cxd4 Nc6 6. Nf3 Bg4 7. Nc3 Bxf3 8. gxf3 Qxd4 9. Qxd4 Nxd4 +B22 Sicilian Defense: Alapin Variation, Barmen Defense, Milner-Barry Attack 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 Nc6 5. Nf3 cxd4 6. cxd4 e5 7. Nc3 Bb4 8. Be2 +B22 Sicilian Defense: Alapin Variation, Barmen Defense, Modern Line 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 Nf6 5. Nf3 Bg4 +B22 Sicilian Defense: Alapin Variation, Smith-Morra Declined 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. d4 cxd4 +B22 Sicilian Defense: Alapin Variation, Stoltz Attack 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. Nf3 Nc6 5. Bc4 Nb6 6. Bb3 +B22 Sicilian Defense: Alapin Variation, Stoltz Attack, Ivanchuk Line 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. Nf3 Nc6 5. Bc4 Nb6 6. Bb3 c4 7. Bc2 Qc7 8. Qe2 g5 +B22 Sicilian Defense: Delayed Alapin Variation 1. e4 c5 2. Nf3 e6 3. c3 d5 4. exd5 Qxd5 5. d4 Nf6 +B22 Sicilian Defense: Delayed Alapin Variation 1. e4 c5 2. Nf3 e6 3. c3 d5 4. exd5 exd5 5. Bb5+ Nc6 6. O-O Bd6 7. d4 +B22 Sicilian Defense: Heidenfeld Variation 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. Nf3 Nc6 5. Na3 +B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 +B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 +B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. g3 +B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. f4 Nc6 4. Nf3 d5 +B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. f4 Nc6 4. Nf3 d5 5. Bb5 +B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. Nge2 a6 4. g3 +B23 Sicilian Defense: Closed, Carlsen Variation 1. e4 c5 2. Nc3 d6 3. d4 cxd4 4. Qxd4 Nc6 5. Qd2 +B23 Sicilian Defense: Closed, Chameleon Variation 1. e4 c5 2. Nc3 Nc6 3. Nge2 +B23 Sicilian Defense: Closed, Grob Attack 1. e4 c5 2. Nc3 Nc6 3. g4 +B23 Sicilian Defense: Closed, Korchnoi Defense 1. e4 c5 2. Nc3 e6 3. g3 d5 +B23 Sicilian Defense: Closed, Portland Attack 1. e4 c5 2. Nc3 Nc6 3. d3 g6 4. g4 +B23 Sicilian Defense: Closed, Traditional 1. e4 c5 2. Nc3 Nc6 +B23 Sicilian Defense: Grand Prix Attack 1. e4 c5 2. Nc3 Nc6 3. f4 +B23 Sicilian Defense: Grand Prix Attack, Schofman Variation 1. e4 c5 2. Nc3 Nc6 3. f4 g6 4. Nf3 Bg7 5. Bc4 e6 6. f5 +B24 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 +B24 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 +B24 Sicilian Defense: Closed, Fianchetto Variation 1. e4 c5 2. Nc3 Nc6 3. g3 +B24 Sicilian Defense: Closed, Smyslov Variation 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 e6 6. Be3 Nd4 7. Nce2 +B25 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 +B25 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. f4 +B25 Sicilian Defense: Closed, Botvinnik Defense, Edge Variation 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. f4 e5 7. Nh3 Nge7 +B25 Sicilian Defense: Closed, Botvinnik Defense, with Nge2 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. Nge2 e5 +B25 Sicilian Defense: Closed, Botvinnik Defense, with f4 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. f4 e5 +B26 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. Be3 +B27 Modern Defense: Pterodactyl Variation 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 +B27 Pterodactyl Defense: Sicilian, Anhanguera 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 5. Be3 +B27 Pterodactyl Defense: Sicilian, Benoni Gambit 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 5. d5 +B27 Pterodactyl Defense: Sicilian, Pteranodon 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ 5. Nc3 Bxc3+ 6. bxc3 +B27 Pterodactyl Defense: Sicilian, Rhamphorhynchus 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ 5. Nc3 +B27 Pterodactyl Defense: Sicilian, Unpin 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 5. Bd2 +B27 Pterodactyl Defense: Western, Pterodactyl 1. e4 c5 2. Nf3 g6 3. c3 Bg7 4. d4 Qa5 +B27 Pterodactyl Defense: Western, Rhamphorhynchus 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ +B27 Sicilian Defense 1. e4 c5 2. Nf3 +B27 Sicilian Defense: Acton Extension 1. e4 c5 2. Nf3 g6 3. c4 Bh6 +B27 Sicilian Defense: Brussels Gambit 1. e4 c5 2. Nf3 f5 +B27 Sicilian Defense: Bücker Variation 1. e4 c5 2. Nf3 h6 +B27 Sicilian Defense: Double-Dutch Gambit 1. e4 c5 2. Nf3 f5 3. exf5 Nh6 +B27 Sicilian Defense: Frederico Variation 1. e4 c5 2. Nf3 g6 3. d4 f5 +B27 Sicilian Defense: Hyperaccelerated Dragon 1. e4 c5 2. Nf3 g6 +B27 Sicilian Defense: Hyperaccelerated Dragon 1. e4 c5 2. Nf3 g6 3. d4 +B27 Sicilian Defense: Hyperaccelerated Pterodactyl 1. e4 c5 2. Nf3 g6 3. d4 Bg7 +B27 Sicilian Defense: Hyperaccelerated Pterodactyl, Exchange Variation 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ 5. Nc3 Bxc3+ 6. bxc3 Qxc3+ +B27 Sicilian Defense: Jalalabad Variation 1. e4 c5 2. Nf3 e5 +B27 Sicilian Defense: Katalimov Variation 1. e4 c5 2. Nf3 b6 +B27 Sicilian Defense: Mongoose Variation 1. e4 c5 2. Nf3 Qa5 +B27 Sicilian Defense: Polish Gambit 1. e4 c5 2. Nf3 b5 +B27 Sicilian Defense: Quinteros Variation 1. e4 c5 2. Nf3 Qc7 +B28 Sicilian Defense: O'Kelly Variation 1. e4 c5 2. Nf3 a6 +B28 Sicilian Defense: O'Kelly Variation, Aronin System 1. e4 c5 2. Nf3 a6 3. Be2 +B28 Sicilian Defense: O'Kelly Variation, Kieseritzky System 1. e4 c5 2. Nf3 a6 3. b3 +B28 Sicilian Defense: O'Kelly Variation, Maróczy Bind 1. e4 c5 2. Nf3 a6 3. c4 +B28 Sicilian Defense: O'Kelly Variation, Maróczy Bind, Paulsen Line 1. e4 c5 2. Nf3 a6 3. c4 e6 +B28 Sicilian Defense: O'Kelly Variation, Maróczy Bind, Robatsch Line 1. e4 c5 2. Nf3 a6 3. c4 d6 +B28 Sicilian Defense: O'Kelly Variation, Normal System 1. e4 c5 2. Nf3 a6 3. d4 +B28 Sicilian Defense: O'Kelly Variation, Normal System, Cortlever Gambit 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. Bc4 +B28 Sicilian Defense: O'Kelly Variation, Normal System, Smith-Morra Line 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. c3 +B28 Sicilian Defense: O'Kelly Variation, Normal System, Taimanov Line 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. Nxd4 e5 +B28 Sicilian Defense: O'Kelly Variation, Normal System, Zagorovsky Line 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. Qxd4 +B28 Sicilian Defense: O'Kelly Variation, Quiet System 1. e4 c5 2. Nf3 a6 3. d3 +B28 Sicilian Defense: O'Kelly Variation, Réti System 1. e4 c5 2. Nf3 a6 3. g3 +B28 Sicilian Defense: O'Kelly Variation, Venice System 1. e4 c5 2. Nf3 a6 3. c3 +B28 Sicilian Defense: O'Kelly Variation, Venice System, Barcza Line 1. e4 c5 2. Nf3 a6 3. c3 Nf6 +B28 Sicilian Defense: O'Kelly Variation, Venice System, Gambit Line 1. e4 c5 2. Nf3 a6 3. c3 d5 4. exd5 Nf6 +B28 Sicilian Defense: O'Kelly Variation, Venice System, Ljubojevic Line 1. e4 c5 2. Nf3 a6 3. c3 b5 +B28 Sicilian Defense: O'Kelly Variation, Venice System, Steiner Line 1. e4 c5 2. Nf3 a6 3. c3 d6 +B28 Sicilian Defense: O'Kelly Variation, Wing Gambit 1. e4 c5 2. Nf3 a6 3. b4 +B28 Sicilian Defense: O'Kelly Variation, Yerevan System 1. e4 c5 2. Nf3 a6 3. Nc3 +B29 Sicilian Defense: Nimzowitsch Variation 1. e4 c5 2. Nf3 Nf6 +B29 Sicilian Defense: Nimzowitsch Variation, Advance Variation 1. e4 c5 2. Nf3 Nf6 3. e5 +B29 Sicilian Defense: Nimzowitsch Variation, Closed Variation 1. e4 c5 2. Nf3 Nf6 3. Nc3 +B29 Sicilian Defense: Nimzowitsch Variation, Exchange Variation 1. e4 c5 2. Nf3 Nf6 3. e5 Nd5 4. Nc3 Nxc3 +B29 Sicilian Defense: Nimzowitsch Variation, Main Line 1. e4 c5 2. Nf3 Nf6 3. e5 Nd5 4. Nc3 e6 5. Nxd5 exd5 6. d4 Nc6 +B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 +B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation, Kharlov-Kramnik Line 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 4. Bc4 Be7 5. d3 d6 6. Nd2 Bg5 +B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation, with Nf6 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 4. Bc4 Be7 5. d3 Nf6 +B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation, with d6 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 4. Bc4 Be7 5. d3 d6 +B30 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack 1. e4 c5 2. Nf3 Nc6 3. Bb5 +B30 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Brooklyn Retreat Defense 1. e4 c5 2. Nf3 Nc6 3. Bb5 Nb8 +B30 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, San Francisco Gambit 1. e4 c5 2. Nf3 Nc6 3. Bb5 Na5 4. b4 +B30 Sicilian Defense: Old Sicilian 1. e4 c5 2. Nf3 Nc6 +B30 Sicilian Defense: Portsmouth Gambit 1. e4 c5 2. Nf3 Nc6 3. b4 +B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 +B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation, Gufeld Gambit 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. c3 e5 6. d4 +B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation, Lutikov Gambit 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. c3 Nf6 6. d4 +B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation, Totsky Attack 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. c3 Nf6 6. Qa4 +B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Gurgenidze Variation 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. Re1 e5 6. b4 +B32 Sicilian Defense: Accelerated Dragon 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 +B32 Sicilian Defense: Flohr Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Qc7 +B32 Sicilian Defense: Franco-Sicilian Variation 1. e4 c5 2. Nf3 Nc6 3. d4 e6 +B32 Sicilian Defense: Godiva Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Qb6 +B32 Sicilian Defense: Kalashnikov Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 e5 5. Nb5 d6 +B32 Sicilian Defense: Löwenthal Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 e5 +B32 Sicilian Defense: Nimzo-American Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 d5 +B32 Sicilian Defense: O'Kelly Variation, Maróczy Bind, Geller Line 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 a6 5. c4 e5 +B32 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 +B32 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 +B32 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 +B33 Sicilian Defense: Lasker-Pelikan Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 +B33 Sicilian Defense: Lasker-Pelikan Variation, Bird Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 Be6 +B33 Sicilian Defense: Lasker-Pelikan Variation, Exchange Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Nxc6 +B33 Sicilian Defense: Lasker-Pelikan Variation, Retreat Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Nf3 +B33 Sicilian Defense: Lasker-Pelikan Variation, Schlechter Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Nb3 +B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 +B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Bxf6 gxf6 10. Nd5 f5 +B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation, Chelyabinsk Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Nd5 +B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation, Novosibirsk Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Bxf6 gxf6 10. Nd5 Bg7 +B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation, Peresypkin's Sacrifice 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Bxf6 gxf6 10. Nd5 f5 11. Bxb5 +B33 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 +B34 Sicilian Defense: Accelerated Dragon, Exchange Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nxc6 +B34 Sicilian Defense: Accelerated Dragon, Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 +B35 Sicilian Defense: Accelerated Dragon, Modern Bc4 Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 +B35 Sicilian Defense: Dragon Variation, Modern Bc4 Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 d6 +B36 Sicilian Defense: Accelerated Dragon, Maróczy Bind 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 +B36 Sicilian Defense: Accelerated Dragon, Maróczy Bind, Gurgenidze Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Nf6 6. Nc3 Nxd4 7. Qxd4 d6 +B37 Sicilian Defense: Accelerated Dragon, Maróczy Bind 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 +B37 Sicilian Defense: Accelerated Dragon, Simagin Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 6. Nc2 d6 7. Be2 Nh6 +B38 Sicilian Defense: Accelerated Dragon, Maróczy Bind 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 6. Be3 +B39 Sicilian Defense: Accelerated Dragon, Maróczy Bind, Breyer Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 6. Be3 Nf6 7. Nc3 Ng4 +B40 Sicilian Defense: Alapin Variation, Sherzer Variation 1. e4 c5 2. Nf3 e6 3. c3 Nf6 4. e5 Nd5 5. d4 Nc6 +B40 Sicilian Defense: Delayed Alapin Variation, with e6 1. e4 c5 2. Nf3 e6 3. c3 +B40 Sicilian Defense: Drazic Variation 1. e4 c5 2. Nf3 e6 3. d4 a6 +B40 Sicilian Defense: French Variation 1. e4 c5 2. Nf3 e6 +B40 Sicilian Defense: French Variation, Normal 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 +B40 Sicilian Defense: French Variation, Open 1. e4 c5 2. Nf3 e6 3. d4 cxd4 +B40 Sicilian Defense: French Variation, Westerinen Attack 1. e4 c5 2. Nf3 e6 3. b3 +B40 Sicilian Defense: Gaw-Paw Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Qb6 +B40 Sicilian Defense: Kan Variation, Wing Attack, Fianchetto Variation 1. e4 c5 2. Nf3 e6 3. Nc3 a6 4. g3 b5 5. d4 cxd4 6. Nxd4 +B40 Sicilian Defense: Kramnik Variation 1. e4 c5 2. Nf3 e6 3. c4 +B40 Sicilian Defense: Kveinis Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Qb6 +B40 Sicilian Defense: Marshall Counterattack 1. e4 c5 2. Nf3 e6 3. d4 d5 +B40 Sicilian Defense: Paulsen-Basman Defense 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Bc5 +B40 Sicilian Defense: Pin Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bb4 +B40 Sicilian Defense: Pin Variation, Jaffe Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bb4 6. Bd3 e5 +B40 Sicilian Defense: Pin Variation, Koch Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bb4 6. e5 +B40 Sicilian Defense: Smith-Morra Gambit Deferred 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. c3 +B40 Sicilian Defense: Wing Gambit Deferred 1. e4 c5 2. Nf3 e6 3. b4 +B41 Sicilian Defense: Kan Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 +B41 Sicilian Defense: Kan Variation, Maróczy Bind, Bronstein Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 Nf6 6. Nc3 Bb4 7. Bd3 Nc6 +B41 Sicilian Defense: Kan Variation, Maróczy Bind, Bronstein Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 Nf6 6. Nc3 Bb4 7. Bd3 Nc6 8. Bc2 +B41 Sicilian Defense: Kan Variation, Maróczy Bind, Hedgehog Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 g6 +B41 Sicilian Defense: Kan Variation, Maróczy Bind, Réti Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 +B42 Sicilian Defense: Kan Variation, Gipslis Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 Nf6 6. O-O d6 7. c4 g6 +B42 Sicilian Defense: Kan Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 +B42 Sicilian Defense: Kan Variation, Polugaevsky Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 Bc5 +B42 Sicilian Defense: Kan Variation, Swiss Cheese Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 g6 +B43 Sicilian Defense: Kan Variation, Knight Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 +B43 Sicilian Defense: Kan Variation, Knight Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 6. g3 Bb7 7. Bg2 +B43 Sicilian Defense: Kan Variation, Wing Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 +B43 Sicilian Defense: Kan Variation, Wing Attack, Christiansen's Dream 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 6. Bd3 Qb6 7. Be3 Bc5 8. Qg4 +B43 Sicilian Defense: Kan Variation, Wing Attack, Spraggett Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 6. Bd3 Qb6 7. Nf3 +B44 Sicilian Defense: Taimanov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 +B44 Sicilian Defense: Taimanov Variation, Gary Gambit 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nb5 d6 6. c4 Nf6 7. N1c3 a6 8. Na3 d5 +B44 Sicilian Defense: Taimanov Variation, Modern Line 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nb5 d6 6. c4 Nf6 7. N1c3 a6 8. Na3 Be7 9. Be2 O-O 10. O-O b6 +B44 Sicilian Defense: Taimanov Variation, Szén Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nb5 +B45 Sicilian Defense: Four Knights Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 +B45 Sicilian Defense: Four Knights Variation, American Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Ndb5 Bb4 7. Nd6+ +B45 Sicilian Defense: Four Knights Variation, Cobra Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Ndb5 Bc5 +B45 Sicilian Defense: Four Knights Variation, Exchange Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Nxc6 +B45 Sicilian Defense: Four Knights Variation, Sveshnikov Transfer 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Ndb5 d6 +B45 Sicilian Defense: Taimanov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 +B46 Sicilian Defense: Taimanov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 a6 +B47 Sicilian Defense: Taimanov Variation, Bastrikov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 +B47 Sicilian Defense: Taimanov Variation, Bastrikov Variation, Ponomariov Gambit 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Ndb5 Qb8 7. Be3 a6 8. Bb6 +B48 Sicilian Defense: Taimanov Variation, Bastrikov Variation, English Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be3 +B49 Sicilian Defense: Taimanov Variation, Bastrikov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be3 a6 7. Be2 +B50 Sicilian Defense 1. e4 c5 2. Nf3 d6 3. d4 +B50 Sicilian Defense 1. e4 c5 2. Nf3 d6 3. d4 cxd4 +B50 Sicilian Defense: Delayed Alapin Variation, Basman-Palatnik Double Gambit 1. e4 c5 2. Nf3 d6 3. c3 Nf6 4. Be2 Nc6 5. d4 cxd4 6. cxd4 Nxe4 7. d5 Qa5+ 8. Nc3 Nxc3 9. bxc3 +B50 Sicilian Defense: Delayed Alapin Variation, Basman-Palatnik Gambit 1. e4 c5 2. Nf3 d6 3. c3 Nf6 4. Be2 Nc6 5. d4 cxd4 6. cxd4 Nxe4 +B50 Sicilian Defense: Delayed Alapin Variation, with d6 1. e4 c5 2. Nf3 d6 3. c3 +B50 Sicilian Defense: Kopec System 1. e4 c5 2. Nf3 d6 3. Bd3 +B50 Sicilian Defense: Kotov Gambit 1. e4 c5 2. Nf3 d6 3. g3 b5 +B50 Sicilian Defense: Modern Variations 1. e4 c5 2. Nf3 d6 +B50 Sicilian Defense: Modern Variations, Anti-Qxd4 Move Order 1. e4 c5 2. Nf3 d6 3. d4 Nf6 +B50 Sicilian Defense: Modern Variations, Anti-Qxd4 Move Order Accepted 1. e4 c5 2. Nf3 d6 3. d4 Nf6 4. dxc5 Nxe4 +B50 Sicilian Defense: Modern Variations, Tartakower 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. c3 +B50 Sicilian Defense: Wing Gambit, Deferred Variation 1. e4 c5 2. Nf3 d6 3. b4 +B51 Sicilian Defense: Moscow Variation 1. e4 c5 2. Nf3 d6 3. Bb5+ +B51 Sicilian Defense: Moscow Variation, Dorfman Gambit 1. e4 c5 2. Nf3 d6 3. Bb5+ Nc6 4. O-O Bd7 5. Qe2 g6 6. e5 +B51 Sicilian Defense: Moscow Variation, Moscow Gambit 1. e4 c5 2. Nf3 d6 3. Bb5+ Nc6 4. O-O Bd7 5. c3 Nf6 6. Re1 a6 7. Bxc6 Bxc6 8. d4 Bxe4 9. Bg5 +B52 Sicilian Defense: Moscow Variation, Haag Gambit 1. e4 c5 2. Nf3 d6 3. Bb5+ Bd7 4. Bxd7+ Qxd7 5. O-O Nc6 6. c3 Nf6 7. d4 +B52 Sicilian Defense: Moscow Variation, Main Line 1. e4 c5 2. Nf3 d6 3. Bb5+ Bd7 +B52 Sicilian Defense: Moscow Variation, Sokolsky Variation 1. e4 c5 2. Nf3 d6 3. Bb5+ Bd7 4. Bxd7+ Qxd7 5. c4 +B53 Sicilian Defense: Chekhover Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Qxd4 +B53 Sicilian Defense: Chekhover Variation, Zaitsev Defense 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Qxd4 Nc6 5. Bb5 Qd7 +B54 Sicilian Defense: Dragon Variation, Accelerated Dragon 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 g6 +B54 Sicilian Defense: Modern Variations, Ginsberg Gambit 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Bc4 +B54 Sicilian Defense: Modern Variations, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 +B54 Sicilian Defense: Prins Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. f3 +B55 Sicilian Defense: Prins Variation, Venice Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. f3 e5 6. Bb5+ +B56 Sicilian Defense: Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 +B56 Sicilian Defense: Classical Variation, Fianchetto Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. g3 +B56 Sicilian Defense: Kupreichik Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bd7 +B56 Sicilian Defense: Spielmann Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Nde2 +B56 Sicilian Defense: Venice Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Bb5+ +B57 Sicilian Defense: Classical Variation, Anti-Sozin Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 Qb6 +B57 Sicilian Defense: Classical Variation, Sozin Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bc4 +B57 Sicilian Defense: Magnus Smith Trap 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 g6 7. Nxc6 bxc6 8. e5 +B58 Sicilian Defense: Boleslavsky Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Be2 e5 +B58 Sicilian Defense: Boleslavsky Variation, Louma Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 e5 7. Nxc6 +B58 Sicilian Defense: Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Be2 +B58 Sicilian Defense: Classical Variation, Dragon Transfer 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Be2 Nxd4 7. Qxd4 g6 +B59 Sicilian Defense: Boleslavsky Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 e5 7. Nb3 +B60 Sicilian Defense: Richter-Rauzer Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 +B60 Sicilian Defense: Richter-Rauzer Variation, Dragon Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 g6 +B60 Sicilian Defense: Richter-Rauzer Variation, Modern Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 Bd7 +B61 Sicilian Defense: Richter-Rauzer Variation, Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 Bd7 7. Qd2 +B62 Sicilian Defense: Richter-Rauzer Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 +B62 Sicilian Defense: Richter-Rauzer Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd3 +B62 Sicilian Defense: Richter-Rauzer Variation, Exchange Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Nxc6 +B62 Sicilian Defense: Richter-Rauzer Variation, Podebrady Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Nb3 +B62 Sicilian Defense: Richter-Rauzer Variation, Vitolins Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Bb5 +B63 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 +B63 Sicilian Defense: Richter-Rauzer Variation, Classical Variation, Kantscher Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O Nxd4 9. Qxd4 a6 10. f4 b5 +B63 Sicilian Defense: Richter-Rauzer Variation, Ivanov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Qb6 +B63 Sicilian Defense: Richter-Rauzer Variation, Traditional Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 +B64 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 e5 +B64 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 +B65 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 Nxd4 10. Qxd4 +B65 Sicilian Defense: Richter-Rauzer Variation, Rauzer Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 Nxd4 +B66 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation, Early Deviations 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 a6 +B67 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 a6 8. O-O-O Bd7 +B68 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 a6 8. O-O-O Bd7 9. f4 Be7 +B69 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation, Nyezhmetdinov Attack 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 a6 8. O-O-O Bd7 9. f4 Be7 10. Nf3 b5 11. Bxf6 +B70 Sicilian Defense: Dragon Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 +B70 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 +B70 Sicilian Defense: Dragon Variation, Fianchetto Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. g3 +B71 Sicilian Defense: Dragon Variation, Levenfish Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. f4 +B71 Sicilian Defense: Dragon Variation, Levenfish Variation, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. f4 Nbd7 +B72 Sicilian Defense: Dragon Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 +B72 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. Be2 +B72 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. Be2 Nc6 +B72 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. Be2 Nc6 8. Nb3 +B72 Sicilian Defense: Dragon Variation, Classical Variation, Amsterdam Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 g6 7. Be3 Bg7 8. Qd2 +B72 Sicilian Defense: Dragon Variation, Classical Variation, Grigoriev Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 g6 7. Be3 Bg7 8. Qd2 O-O 9. O-O-O +B73 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O Nc6 8. Be3 +B73 Sicilian Defense: Dragon Variation, Classical Variation, Battery Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Qd2 +B73 Sicilian Defense: Dragon Variation, Classical Variation, Zollner Gambit 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Be3 Bg7 6. Be2 Nf6 7. Nc3 O-O 8. O-O d6 9. f4 Qb6 10. e5 +B74 Sicilian Defense: Dragon Variation, Classical Variation, Alekhine Line 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Be2 O-O 8. O-O d6 9. Nb3 a5 +B74 Sicilian Defense: Dragon Variation, Classical Variation, Bernard Defense 1. e4 c5 2. Nf3 g6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 Be6 10. f4 Na5 11. f5 Bc4 12. Bd3 Bxd3 13. cxd3 d5 +B74 Sicilian Defense: Dragon Variation, Classical Variation, Maróczy Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 Be6 10. f4 Na5 +B74 Sicilian Defense: Dragon Variation, Classical Variation, Normal Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 +B74 Sicilian Defense: Dragon Variation, Classical Variation, Spielmann Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Be2 O-O 8. Nb3 d6 9. O-O Be6 10. f4 Na5 11. f5 Bc4 12. Bd3 +B74 Sicilian Defense: Dragon Variation, Classical Variation, Stockholm Attack 1. e4 c5 2. Nc3 d6 3. f4 Nc6 4. Nf3 g6 5. d4 cxd4 6. Nxd4 Bg7 7. Be3 Nf6 8. Be2 O-O 9. Nb3 Be6 10. O-O Na5 11. f5 Bc4 12. Nxa5 Bxe2 13. Qxe2 Qxa5 14. g4 +B74 Sicilian Defense: Dragon Variation, Classical Variation, Tartakower Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 Be6 10. f4 Qc8 +B75 Sicilian Defense: Dragon Variation, Yugoslav Attack, Belezky Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 +B75 Sicilian Defense: Dragon Variation, Yugoslav Attack, Early Deviations 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 +B75 Sicilian Defense: Dragon Variation, Yugoslav Attack, Hungarian Dragon 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Nc6 7. f3 h5 +B76 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O +B76 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 +B76 Sicilian Defense: Dragon Variation, Yugoslav Attack, Modern Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. O-O-O +B76 Sicilian Defense: Dragon Variation, Yugoslav Attack, Panov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. g4 +B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Byrne Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 a5 +B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Czerniak Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. Bc4 Nxd4 10. Bxd4 Be6 +B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Czerniak Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. Bc4 Nxd4 10. Bxd4 Be6 11. Bb3 Qa5 +B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 +B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 +B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. Bb3 +B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Sosonko Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. Bc4 Nd7 +B78 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O +B78 Sicilian Defense: Dragon Variation, Yugoslav Attack, Chinese Dragon 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Rb8 +B78 Sicilian Defense: Dragon Variation, Yugoslav Attack, Old Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Rc8 +B78 Sicilian Defense: Dragon Variation, Yugoslav Attack, Topalov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Rc8 11. Bb3 Nxd4 12. Bxd4 +B79 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. h4 Qa5 11. O-O-O Rfc8 12. Bb3 +B79 Sicilian Defense: Dragon Variation, Yugoslav Attack, Soltis Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Qa5 11. h4 Rfc8 12. Bb3 h5 +B80 Sicilian Defense: Scheveningen Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 +B80 Sicilian Defense: Scheveningen Variation, English Attack, with Qd2 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. Qd2 +B80 Sicilian Defense: Scheveningen Variation, Fianchetto Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. g3 +B80 Sicilian Defense: Scheveningen Variation, Vitolins Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bb5+ +B81 Sicilian Defense: Scheveningen Variation, Keres Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. g4 +B82 Sicilian Defense: Scheveningen Variation, Matanovic Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. f4 +B82 Sicilian Defense: Scheveningen Variation, Tal Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. f4 Nc6 7. Be3 Be7 8. Qf3 +B83 Sicilian Defense: Scheveningen Variation, Classical Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 +B83 Sicilian Defense: Scheveningen Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 d6 6. Be2 Nf6 +B83 Sicilian Defense: Scheveningen Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 Be7 7. O-O O-O 8. f4 Nc6 9. Be3 +B83 Sicilian Defense: Scheveningen Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 Be7 7. O-O O-O 8. f4 Nc6 9. Be3 Bd7 10. Nb3 +B84 Sicilian Defense: Najdorf Variation, Scheveningen Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e6 7. O-O Nbd7 +B84 Sicilian Defense: Scheveningen Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e6 +B84 Sicilian Defense: Scheveningen Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e6 7. O-O Qc7 +B85 Sicilian Defense: Scheveningen Variation, Classical Main Line 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be2 a6 7. O-O Nf6 8. Be3 Be7 9. f4 d6 10. Qe1 O-O +B85 Sicilian Defense: Scheveningen Variation, Classical Variation, Paulsen Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. f4 e6 7. Be2 Qc7 8. O-O Nc6 +B85 Sicilian Defense: Scheveningen Variation, Classical Variation, Paulsen Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be2 a6 7. O-O Nf6 8. Be3 d6 9. f4 +B85 Sicilian Defense: Scheveningen Variation, Classical Variation, Paulsen Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be2 a6 7. O-O Nf6 8. Kh1 Be7 9. f4 d6 10. a4 +B86 Sicilian Defense: Sozin Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 +B87 Sicilian Defense: Sozin Attack, Flank Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bc4 e6 7. Bb3 b5 +B88 Sicilian Defense: Sozin Attack, Fischer Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 7. Bb3 Be7 8. Be3 O-O 9. f4 +B88 Sicilian Defense: Sozin Attack, Leonhardt Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 +B89 Sicilian Defense: Sozin Attack, Main Line 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 7. Be3 +B89 Sicilian Defense: Sozin Attack, Main Line, Sherbakov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bc4 e6 7. Be3 Be7 8. Bb3 O-O 9. O-O Na5 10. f4 b6 +B89 Sicilian Defense: Velimirovic Attack 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 7. Be3 Be7 8. Qe2 +B90 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 +B90 Sicilian Defense: Najdorf Variation, Adams Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. h3 +B90 Sicilian Defense: Najdorf Variation, Dekker Gambit 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. g4 +B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 +B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be6 8. f3 +B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be7 8. f3 +B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be6 8. h3 +B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be7 8. h3 +B90 Sicilian Defense: Najdorf Variation, English Attack, Anti-English 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 Ng4 +B90 Sicilian Defense: Najdorf Variation, Lipnitsky Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bc4 +B90 Sicilian Defense: Najdorf Variation, Petronić Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Rg1 +B90 Sicilian Defense: Najdorf Variation, Yates Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bd3 +B90 Sicilian Defense: Scheveningen Variation, Delayed Keres Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. g4 +B90 Sicilian Defense: Scheveningen Variation, Delayed Keres Attack, Perenyi Gambit 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. g4 e5 8. Nf5 g6 9. g5 +B90 Sicilian Defense: Scheveningen Variation, English Attack, with f3 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. f3 +B91 Sicilian Defense: Najdorf Variation, Zagreb Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. g3 +B92 Sicilian Defense: Najdorf Variation, Opocensky Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 +B92 Sicilian Defense: Najdorf Variation, Opocensky Variation 1. e4 c5 2. Nf3 Nf6 3. Nc3 d6 4. d4 cxd4 5. Nxd4 a6 6. Be2 e5 7. Nb3 Be6 8. Be3 +B92 Sicilian Defense: Najdorf Variation, Opocensky Variation, Modern Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e5 7. Nb3 Be7 8. O-O Be6 +B92 Sicilian Defense: Najdorf Variation, Opocensky Variation, Traditional Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e5 7. Nb3 Be7 8. O-O O-O +B93 Sicilian Defense: Najdorf Variation, Amsterdam Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. f4 +B94 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 +B94 Sicilian Defense: Najdorf Variation, Ivkov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 Nbd7 7. Bc4 Qa5 8. Qd2 e6 9. O-O-O b5 10. Bb3 Bb7 11. Rhe1 Nc5 12. e5 +B95 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 +B96 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 +B96 Sicilian Defense: Najdorf Variation, Neo-Classical Defense 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Nc6 +B96 Sicilian Defense: Najdorf Variation, Polugaevsky Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 b5 +B96 Sicilian Defense: Najdorf Variation, Polugaevsky Variation, Simagin Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 b5 8. e5 dxe5 9. fxe5 Qc7 10. Qe2 +B97 Sicilian Defense: Najdorf Variation, Poisoned Pawn Accepted 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Qb6 8. Qd2 Qxb2 9. Rb1 Qa3 +B97 Sicilian Defense: Najdorf Variation, Poisoned Pawn Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Qb6 +B98 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 +B98 Sicilian Defense: Najdorf Variation, Browne Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 h6 9. Bh4 Qc7 +B98 Sicilian Defense: Najdorf Variation, Goteborg Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 h6 9. Bh4 g5 +B98 Sicilian Defense: Najdorf Variation, Traditional Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 +B99 Sicilian Defense: Najdorf Variation, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 diff --git a/crates/openings/data/c.tsv b/crates/openings/data/c.tsv new file mode 100644 index 0000000..4b3d9c9 --- /dev/null +++ b/crates/openings/data/c.tsv @@ -0,0 +1,1251 @@ +eco name pgn +C00 French Defense 1. e4 e6 +C00 French Defense 1. e4 e6 2. d4 d5 +C00 French Defense: Alapin Gambit 1. e4 e6 2. d4 d5 3. Be3 +C00 French Defense: Baeuerle Gambit 1. e4 e6 2. d4 b5 +C00 French Defense: Banzai-Leong Gambit 1. e4 e6 2. b4 +C00 French Defense: Banzai-Leong Gambit, Pinova Gambit 1. e4 e6 2. b4 Bxb4 3. e5 +C00 French Defense: Bird Invitation 1. e4 e6 2. Bb5 +C00 French Defense: Carlson Gambit 1. e4 e6 2. d4 d5 3. Nf3 dxe4 4. Ne5 +C00 French Defense: Chigorin Variation 1. e4 e6 2. Qe2 +C00 French Defense: Diemer-Duhm Gambit 1. e4 e6 2. d4 d5 3. c4 +C00 French Defense: Diemer-Duhm Gambit Accepted 1. e4 e6 2. d4 d5 3. c4 dxe4 +C00 French Defense: Franco-Hiva Gambit 1. e4 e6 2. d4 f5 +C00 French Defense: Franco-Hiva Gambit Accepted 1. e4 e6 2. d4 f5 3. exf5 +C00 French Defense: Franco-Sicilian Defense 1. e4 e6 2. d4 c5 +C00 French Defense: Hoffmann Gambit 1. e4 e6 2. d4 d5 3. Qe2 e5 4. f4 exf4 +C00 French Defense: Horwitz Attack 1. e4 e6 2. b3 +C00 French Defense: Horwitz Attack, Papa-Ticulat Gambit 1. e4 e6 2. b3 d5 3. Bb2 +C00 French Defense: King's Indian Attack 1. e4 e6 2. d3 +C00 French Defense: King's Indian Attack, Franco-Hiva Gambit 1. e4 e6 2. d3 f5 +C00 French Defense: Knight Variation 1. e4 e6 2. Nf3 +C00 French Defense: Knight Variation, Franco-Hiva Gambit 1. e4 e6 2. Nf3 f5 +C00 French Defense: La Bourdonnais Variation 1. e4 e6 2. f4 +C00 French Defense: La Bourdonnais Variation, Reuter Gambit 1. e4 e6 2. f4 d5 3. Nf3 dxe4 +C00 French Defense: Mediterranean Defense 1. e4 e6 2. d4 Nf6 +C00 French Defense: Morphy Gambit 1. e4 e6 2. d4 d5 3. Nh3 +C00 French Defense: Normal Variation 1. e4 e6 2. d4 +C00 French Defense: Orthoschnapp Gambit 1. e4 e6 2. c4 d5 3. cxd5 exd5 4. Qb3 +C00 French Defense: Pelikan Variation 1. e4 e6 2. Nc3 d5 3. f4 +C00 French Defense: Perseus Gambit 1. e4 e6 2. d4 d5 3. Nf3 +C00 French Defense: Queen's Knight 1. e4 e6 2. Nc3 +C00 French Defense: Reversed Philidor Formation 1. e4 e6 2. d3 d5 3. Nd2 Nf6 4. Ngf3 Nc6 5. Be2 +C00 French Defense: Réti-Spielmann Attack 1. e4 e6 2. g3 +C00 French Defense: Schlechter Variation 1. e4 e6 2. d4 d5 3. Bd3 +C00 French Defense: St. George Defense 1. e4 e6 2. d4 a6 +C00 French Defense: St. George Defense, Sanky-George Gambit 1. e4 e6 2. d4 a6 3. c4 b5 +C00 French Defense: St. George Defense, St. George Gambit 1. e4 e6 2. d4 a6 3. c4 b5 4. cxb5 axb5 +C00 French Defense: St. George Defense, Three Pawn Attack 1. e4 e6 2. d4 a6 3. c4 +C00 French Defense: St. George Defense, Traditional Line 1. e4 e6 2. d4 a6 3. Nf3 b5 4. Bd3 c5 5. c3 Bb7 6. O-O Nf6 +C00 French Defense: Steiner Variation 1. e4 e6 2. c4 +C00 French Defense: Steinitz Attack 1. e4 e6 2. e5 +C00 French Defense: Two Knights Variation 1. e4 e6 2. Nf3 d5 3. Nc3 +C00 French Defense: Wing Gambit 1. e4 e6 2. Nf3 d5 3. e5 c5 4. b4 +C00 Rat Defense: Small Center Defense 1. d4 e6 2. e4 d6 +C01 French Defense: Exchange Variation 1. e4 e6 2. d4 d5 3. exd5 +C01 French Defense: Exchange Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. Nf3 +C01 French Defense: Exchange Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. Nc3 +C01 French Defense: Exchange Variation, Bogoljubow Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. Nc3 Nf6 5. Bg5 Nc6 +C01 French Defense: Exchange Variation, Monte Carlo Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. c4 +C01 French Defense: Exchange Variation, Svenonius Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. exd5 exd5 5. Bg5 +C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 +C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 c5 +C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 +C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 +C02 French Defense: Advance Variation, Euwe Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Bd7 +C02 French Defense: Advance Variation, Extended Bishop Swap 1. e4 e6 2. d4 d5 3. e5 Bd7 +C02 French Defense: Advance Variation, Frenkel Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. b4 +C02 French Defense: Advance Variation, Kupreichik Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Be3 +C02 French Defense: Advance Variation, Lputian Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. a3 Nh6 +C02 French Defense: Advance Variation, Main Line 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. a3 +C02 French Defense: Advance Variation, Milner-Barry Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 +C02 French Defense: Advance Variation, Milner-Barry Gambit, Hector Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. O-O +C02 French Defense: Advance Variation, Milner-Barry Gambit, Hector Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. O-O Bd7 8. Re1 +C02 French Defense: Advance Variation, Milner-Barry Gambit, Main Line 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. cxd4 Bd7 8. O-O +C02 French Defense: Advance Variation, Milner-Barry Gambit, Sørensen Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. cxd4 Bd7 8. O-O Nxd4 9. Ng5 +C02 French Defense: Advance Variation, Nimzowitsch Attack 1. e4 e6 2. d4 d5 3. e5 c5 4. Qg4 +C02 French Defense: Advance Variation, Nimzowitsch Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. Qg4 cxd4 5. Nf3 +C02 French Defense: Advance Variation, Nimzowitsch System 1. e4 e6 2. d4 d5 3. e5 c5 4. Nf3 +C02 French Defense: Advance Variation, Paulsen Attack 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 +C02 French Defense: Advance Variation, Ruisdonk Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. Nf3 cxd4 5. Bd3 +C02 French Defense: Advance Variation, Steinitz Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. dxc5 +C02 French Defense: Advance Variation, Wade Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Qb6 5. Nf3 Bd7 +C03 French Defense: Tarrasch Variation 1. e4 e6 2. d4 d5 3. Nd2 +C03 French Defense: Tarrasch Variation, Guimard Defense 1. e4 e6 2. d4 d5 3. Nd2 Nc6 +C03 French Defense: Tarrasch Variation, Guimard Defense, Thunderbunny Variation 1. e4 e6 2. d4 d5 3. Nd2 Nc6 4. c3 dxe4 5. Nxe4 e5 +C03 French Defense: Tarrasch Variation, Haberditz Variation 1. e4 e6 2. d4 d5 3. Nd2 f5 +C03 French Defense: Tarrasch Variation, Modern System 1. e4 e6 2. d4 d5 3. Nd2 a6 +C03 French Defense: Tarrasch Variation, Morozevich Variation 1. e4 e6 2. d4 d5 3. Nd2 Be7 +C04 French Defense: Tarrasch Variation, Guimard Defense, Main Line 1. e4 e6 2. d4 d5 3. Nd2 Nc6 4. Ngf3 Nf6 +C05 French Defense: Tarrasch Variation, Botvinnik Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 b6 +C05 French Defense: Tarrasch Variation, Closed Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 +C05 French Defense: Tarrasch Variation, Closed Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 Nc6 +C05 French Defense: Tarrasch Variation, Pawn Center Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. f4 +C06 French Defense: Tarrasch Variation, Closed Variation, Main Line 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 Nc6 7. Ne2 cxd4 8. cxd4 +C06 French Defense: Tarrasch Variation, Leningrad Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 Nc6 7. Ne2 cxd4 8. cxd4 Nb6 +C07 French Defense: Tarrasch Variation, Chistyakov Defense 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Qxd5 +C07 French Defense: Tarrasch Variation, Chistyakov Defense, Modern Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Qxd5 5. Ngf3 cxd4 6. Bc4 Qd6 7. O-O Nf6 8. Nb3 Nc6 9. Nbxd4 Nxd4 10. Nxd4 a6 +C07 French Defense: Tarrasch Variation, Eliskases Variation 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Qxd5 5. Ngf3 cxd4 6. Bc4 Qd8 +C07 French Defense: Tarrasch Variation, Open System 1. e4 e6 2. d4 d5 3. Nd2 c5 +C07 French Defense: Tarrasch Variation, Open System, Euwe-Keres Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. Ngf3 +C07 French Defense: Tarrasch Variation, Open System, Shaposhnikov Gambit 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Nf6 +C07 French Defense: Tarrasch Variation, Open System, Süchting Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. c3 +C08 French Defense: Tarrasch Variation, Open System 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 +C08 French Defense: Tarrasch Variation, Open System, Advance Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 5. Ngf3 c4 +C09 French Defense: Tarrasch Variation, Open System, Main Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 5. Ngf3 Nc6 +C09 French Defense: Tarrasch Variation, Open System, Main Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 5. Ngf3 Nc6 6. Bb5 Bd6 7. dxc5 Bxc5 8. O-O Ne7 9. c3 +C10 French Defense: Hecht-Reefschläger Variation 1. e4 e6 2. d4 d5 3. Nc3 Nc6 +C10 French Defense: Marshall Gambit 1. e4 e6 2. d4 d5 3. Nc3 c5 +C10 French Defense: Paulsen Variation 1. e4 e6 2. d4 d5 3. Nc3 +C10 French Defense: Rubinstein Variation 1. e4 e6 2. d4 d5 3. Nc3 dxe4 +C10 French Defense: Rubinstein Variation, Blackburne Defense 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nd7 +C10 French Defense: Rubinstein Variation, Capablanca Line 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nd7 5. Nf3 Ngf6 6. Nxf6+ Nxf6 7. Ne5 +C10 French Defense: Rubinstein Variation, Ellis Gambit 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 e5 +C10 French Defense: Rubinstein Variation, Fort Knox Variation 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Bd7 5. Nf3 Bc6 +C10 French Defense: Rubinstein Variation, Kasparov Attack 1. e4 e6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Nf3 Ngf6 6. Nxf6+ Nxf6 7. c3 +C10 French Defense: Rubinstein Variation, Maric Variation 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Qd5 +C11 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 +C11 French Defense: Classical Variation, Delayed Exchange Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. exd5 +C11 French Defense: Classical Variation, Shirov-Anand Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. Nce2 +C11 French Defense: Classical Variation, Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 +C11 French Defense: Classical Variation, Swiss Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bd3 +C11 French Defense: Henneberger Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Be3 +C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 +C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 6. a3 +C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 6. Ne2 +C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. dxc5 Nc6 +C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. Nf3 +C11 French Defense: Steinitz Variation, Boleslavsky Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. Nf3 Nc6 7. Be3 +C11 French Defense: Steinitz Variation, Bradford Attack Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. dxc5 Bxc5 7. Qg4 +C11 French Defense: Steinitz Variation, Brodsky-Jones Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. dxc5 Nc6 7. a3 Bxc5 8. Qg4 O-O 9. Nf3 f6 +C11 French Defense: Steinitz Variation, Gledhill Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. Qg4 +C12 French Defense, Classical, 4. Bg5 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 +C12 French Defense: McCutcheon Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 +C12 French Defense: McCutcheon Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 +C12 French Defense: McCutcheon Variation, Bernstein Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bh4 +C12 French Defense: McCutcheon Variation, Bogoljubow Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. exd5 Qxd5 6. Bxf6 gxf6 7. Qd2 Qa5 +C12 French Defense: McCutcheon Variation, Chigorin Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. exf6 +C12 French Defense: McCutcheon Variation, Dr. Olland Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bc1 +C12 French Defense: McCutcheon Variation, Duras Variation 1. e4 e6 2. Nc3 d5 3. d4 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Bxc3 7. bxc3 Ne4 8. Qg4 Kf8 9. Bc1 +C12 French Defense: McCutcheon Variation, Exchange Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. exd5 +C12 French Defense: McCutcheon Variation, Grigoriev Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. exf6 hxg5 7. fxg7 Rg8 8. h4 gxh4 9. Qg4 +C12 French Defense: McCutcheon Variation, Janowski Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Be3 +C12 French Defense: McCutcheon Variation, Lasker Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Bxc3 +C12 French Defense: McCutcheon Variation, Lasker Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Bxc3 7. bxc3 Ne4 8. Qg4 g6 +C12 French Defense: McCutcheon Variation, Tartakower Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Nfd7 +C13 French Defense: Alekhine-Chatard Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 +C13 French Defense: Alekhine-Chatard Attack, Albin-Chatard Gambit 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 Bxg5 7. hxg5 Qxg5 +C13 French Defense: Alekhine-Chatard Attack, Breyer Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 c5 +C13 French Defense: Alekhine-Chatard Attack, Maróczy Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 a6 +C13 French Defense: Alekhine-Chatard Attack, Spielmann Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 O-O +C13 French Defense: Alekhine-Chatard Attack, Teichmann Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 f6 +C13 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 5. Nxe4 Be7 +C13 French Defense: Classical Variation, Burn Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 +C13 French Defense: Classical Variation, Burn Variation, Main Line 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 5. Nxe4 Be7 6. Bxf6 Bxf6 7. Nf3 O-O +C13 French Defense: Classical Variation, Burn Variation, Morozevich Line 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 5. Nxe4 Be7 6. Bxf6 gxf6 +C13 French Defense: Classical Variation, Frankfurt Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Ng8 6. Be3 b6 +C13 French Defense: Classical Variation, Normal Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 +C13 French Defense: Classical Variation, Richter Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 +C13 French Defense: Classical Variation, Richter Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 Bxf6 6. e5 Be7 7. Qg4 +C13 French Defense: Classical Variation, Tartakower Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Ne4 +C13 French Defense: Classical Variation, Vistaneckis Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Ng8 +C14 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 6. Bg5 +C14 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 +C14 French Defense: Classical Variation, Alapin Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Nb5 +C14 French Defense: Classical Variation, Pollock Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Qg4 +C14 French Defense: Classical Variation, Rubinstein Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Qd2 +C14 French Defense: Classical Variation, Stahlberg Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. f4 O-O 8. Nf3 c5 9. Qd2 Nc6 10. O-O-O c4 +C14 French Defense: Classical Variation, Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. f4 +C14 French Defense: Classical Variation, Tarrasch Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Bd3 +C15 French Defense: McCutcheon Variation, Wolf Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 Nf6 5. Bg5 +C15 French Defense: Winawer Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 +C15 French Defense: Winawer Variation, Alekhine Gambit Accepted 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 dxe4 5. a3 Bxc3+ +C15 French Defense: Winawer Variation, Alekhine Gambit, Alatortsev Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 dxe4 5. a3 Be7 6. Nxe4 Nf6 7. N2g3 O-O 8. Be2 Nc6 +C15 French Defense: Winawer Variation, Alekhine Gambit, Kan Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 dxe4 5. a3 Bxc3+ 6. Nxc3 Nc6 +C15 French Defense: Winawer Variation, Alekhine-Maróczy Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 +C15 French Defense: Winawer Variation, Delayed Exchange Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. exd5 +C15 French Defense: Winawer Variation, Exchange Variation, Canal Attack 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. exd5 exd5 5. Bd3 Ne7 6. Qh5 +C15 French Defense: Winawer Variation, Fingerslip Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 +C15 French Defense: Winawer Variation, Fingerslip Variation, Kunin Double Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 dxe4 5. Qg4 Qxd4 +C15 French Defense: Winawer Variation, Fingerslip Variation, Main Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 dxe4 5. Qg4 Nf6 6. Qxg7 Rg8 7. Qh6 +C15 French Defense: Winawer Variation, Fingerslip Variation, Schwarz's Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 Ne7 5. Nb1 +C15 French Defense: Winawer Variation, Kondratiyev Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd3 c5 5. exd5 Qxd5 6. Bd2 +C15 French Defense: Winawer Variation, Winckelmann-Reimer Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 dxe4 6. f3 +C16 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 +C16 French Defense: Winawer Variation, Petrosian Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 Qd7 +C17 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 +C17 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 +C17 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 cxd4 6. axb4 dxc3 7. Nf3 +C17 French Defense: Winawer Variation, Advance Variation, Moscow Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. Qg4 +C17 French Defense: Winawer Variation, Bogoljubow Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. Bd2 +C17 French Defense: Winawer Variation, Bogoljubow Variation, Icelandic Defense 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. Bd2 Ne7 6. f4 +C17 French Defense: Winawer Variation, Maróczy-Wallis Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 cxd4 6. axb4 dxc3 +C17 French Defense: Winawer Variation, Retreat Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Ba5 +C17 French Defense: Winawer Variation, Retreat Variation, Armenian Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Ba5 6. b4 cxd4 +C18 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 +C18 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 +C18 French Defense: Winawer Variation, Advance Variation, with Bd3 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Bd3 +C18 French Defense: Winawer Variation, Advance Variation, with Bd3 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Bd3 Qc7 +C18 French Defense: Winawer Variation, Advance Variation, with h4 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. h4 +C18 French Defense: Winawer Variation, Advance Variation, with h4 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. h4 Qc7 +C18 French Defense: Winawer Variation, Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Qc7 +C18 French Defense: Winawer Variation, Eingorn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Kf8 +C18 French Defense: Winawer Variation, Poisoned Pawn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 +C18 French Defense: Winawer Variation, Poisoned Pawn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 cxd4 8. Qxg7 +C18 French Defense: Winawer Variation, Poisoned Pawn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 cxd4 8. Qxg7 Rg8 9. Qxh7 Nbc6 +C18 French Defense: Winawer Variation, Poisoned Pawn Variation Declined 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 8. Bd3 +C18 French Defense: Winawer Variation, Poisoned Pawn Variation, Main Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 8. Qxg7 Rg8 9. Qxh7 cxd4 10. Ne2 +C18 French Defense: Winawer Variation, Poisoned Pawn Variation, Paoli Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 8. Qxg7 Rg8 9. Qxh7 cxd4 10. Kd1 +C18 French Defense: Winawer Variation, Portisch-Hook Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Qa5 +C18 French Defense: Winawer Variation, Warsaw Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 O-O +C19 French Defense: Winawer Variation, Advance Variation, Smyslov Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 Ne7 5. a3 Bxc3+ 6. bxc3 c5 7. a4 +C19 French Defense: Winawer Variation, Advance Variation, Smyslov Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 Ne7 5. a3 Bxc3+ 6. bxc3 c5 7. a4 Qc7 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Qd2 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Qd2 Bd7 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Bd2 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Bd2 Bd7 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Bd2 c4 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Nf3 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Nc6 7. Nf3 Nge7 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Nf3 Qc7 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Nf3 Qc7 8. h4 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Bd3 Nbc6 8. Nf3 +C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Nc6 7. Nf3 Qa5 8. Bd2 Nge7 +C20 Barnes Opening: Walkerling 1. f3 e5 2. e4 Nf6 3. Bc4 +C20 Bongcloud Attack 1. e4 e5 2. Ke2 +C20 Center Game 1. e4 e5 2. d4 +C20 English Opening: The Whale 1. e4 e5 2. c4 +C20 King's Pawn Game 1. e4 e5 +C20 King's Pawn Game: Alapin Opening 1. e4 e5 2. Ne2 +C20 King's Pawn Game: Bavarian Gambit 1. e4 e5 2. c4 d5 +C20 King's Pawn Game: Beyer Gambit 1. e4 e5 2. d4 d5 +C20 King's Pawn Game: Clam Variation, King's Gambit Reversed 1. e4 e5 2. d3 f5 +C20 King's Pawn Game: Clam Variation, Radisch Gambit 1. e4 e5 2. d3 Nf6 3. f4 Bc5 +C20 King's Pawn Game: King's Head Opening 1. e4 e5 2. f3 +C20 King's Pawn Game: King's Head Opening 1. e4 e5 2. f3 Nf6 3. Nc3 +C20 King's Pawn Game: Leonardis Variation 1. e4 e5 2. d3 +C20 King's Pawn Game: MacLeod Attack 1. e4 e5 2. c3 +C20 King's Pawn Game: MacLeod Attack, Lasa Gambit 1. e4 e5 2. c3 f5 +C20 King's Pawn Game: MacLeod Attack, Norwalde Gambit 1. e4 e5 2. c3 d5 3. Qh5 Bd6 +C20 King's Pawn Game: Mengarini's Opening 1. e4 e5 2. a3 +C20 King's Pawn Game: Napoleon Attack 1. e4 e5 2. Qf3 +C20 King's Pawn Game: Philidor Gambit 1. e4 e5 2. d4 d6 3. dxe5 Bd7 +C20 King's Pawn Game: Tortoise Opening 1. e4 e5 2. Bd3 +C20 King's Pawn Game: Wayward Queen Attack 1. e4 e5 2. Qh5 +C20 King's Pawn Game: Wayward Queen Attack, Kiddie Countergambit 1. e4 e5 2. Qh5 Nf6 +C20 King's Pawn Game: Wayward Queen Attack, Mellon Gambit 1. e4 e5 2. Qh5 Nc6 3. Bc4 Nh6 4. d3 g6 5. Qf3 f6 6. Ne2 d5 +C20 King's Pawn Game: Weber Gambit 1. e4 e5 2. d3 d5 3. exd5 c6 4. dxc6 Nxc6 +C20 King's Pawn Opening 1. e4 e5 2. b3 +C20 King's Pawn Opening: Speers 1. e4 e5 2. Qg4 Nf6 3. Qf5 +C20 King's Pawn Opening: Van Hooydoon Gambit 1. e4 e5 2. Qe2 Nc6 3. c3 Nf6 4. Nf3 Bc5 5. d4 exd4 6. cxd4 Nxd4 +C20 Portuguese Opening 1. e4 e5 2. Bb5 +C20 Portuguese Opening: Miguel Gambit 1. e4 e5 2. Bb5 Bc5 3. b4 +C20 Portuguese Opening: Portuguese Gambit 1. e4 e5 2. Bb5 Nf6 3. d4 +C21 Center Game 1. e4 e5 2. d4 exd4 3. Qxd4 +C21 Center Game Accepted 1. e4 e5 2. d4 exd4 +C21 Center Game: Halasz-McDonnell Gambit 1. e4 e5 2. d4 exd4 3. f4 +C21 Center Game: Halasz-McDonnell Gambit, Crocodile Variation 1. e4 e5 2. d4 exd4 3. f4 Bc5 4. Nf3 Nc6 5. c3 +C21 Center Game: Kieseritzky Variation 1. e4 e5 2. d4 exd4 3. Nf3 +C21 Center Game: Kieseritzky Variation 1. e4 e5 2. d4 exd4 3. Nf3 c5 +C21 Center Game: Kieseritzky Variation 1. e4 e5 2. d4 exd4 3. Nf3 c5 4. Bc4 +C21 Center Game: Lanc-Arnold Gambit 1. e4 e5 2. d4 exd4 3. Nf3 Bc5 4. c3 +C21 Center Game: Lanc-Arnold Gambit, Schippler Gambit 1. e4 e5 2. d4 exd4 3. Nf3 Bc5 4. c3 dxc3 5. Bc4 +C21 Center Game: Ross Gambit 1. e4 e5 2. d4 exd4 3. Bd3 +C21 Center Game: von der Lasa Gambit 1. e4 e5 2. d4 exd4 3. Bc4 +C21 Danish Gambit 1. e4 e5 2. d4 exd4 3. c3 +C21 Danish Gambit Accepted 1. e4 e5 2. d4 exd4 3. c3 dxc3 +C21 Danish Gambit Accepted: Chigorin Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 Qe7 +C21 Danish Gambit Accepted: Classical Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 Nf6 +C21 Danish Gambit Accepted: Copenhagen Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 Bb4+ +C21 Danish Gambit Accepted: Schlechter Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 d5 +C21 Danish Gambit Accepted: Svenonius Defense 1. e4 e5 2. d4 exd4 3. c3 Ne7 +C21 Danish Gambit Declined: Sörensen Defense 1. e4 e5 2. d4 exd4 3. c3 d5 +C22 Center Game: Berger Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 Nf6 +C22 Center Game: Charousek Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 Bb4+ 5. c3 Be7 +C22 Center Game: Hall Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qc4 +C22 Center Game: Kupreichik Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 Nf6 5. Nc3 Bb4 6. Bd2 O-O 7. O-O-O Re8 8. Bc4 d6 9. Nh3 +C22 Center Game: Normal Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 +C22 Center Game: Paulsen Attack Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 +C22 Center Game: l'Hermet Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 f5 +C23 Bishop's Opening 1. e4 e5 2. Bc4 +C23 Bishop's Opening: Anderssen Gambit 1. e4 e5 2. Bc4 b5 3. Bxb5 c6 +C23 Bishop's Opening: Boi Variation 1. e4 e5 2. Bc4 Bc5 +C23 Bishop's Opening: Calabrese Countergambit 1. e4 e5 2. Bc4 f5 +C23 Bishop's Opening: Calabrese Countergambit, Jaenisch Variation 1. e4 e5 2. Bc4 f5 3. d3 +C23 Bishop's Opening: Four Pawns Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 Bxb4 4. f4 exf4 5. Nf3 Be7 6. d4 Bh4+ 7. g3 fxg3 8. O-O gxh2+ 9. Kh1 +C23 Bishop's Opening: Khan Gambit 1. e4 e5 2. Bc4 d5 +C23 Bishop's Opening: Lewis Countergambit 1. e4 e5 2. Bc4 Bc5 3. c3 d5 +C23 Bishop's Opening: Lewis Countergambit 1. e4 e5 2. Bc4 Bc5 3. c3 d5 4. Bxd5 Nf6 +C23 Bishop's Opening: Lewis Countergambit, Walker Variation 1. e4 e5 2. Bc4 Bc5 3. c3 d5 4. Bxd5 Nf6 5. d4 +C23 Bishop's Opening: Lewis Gambit 1. e4 e5 2. Bc4 Bc5 3. d4 +C23 Bishop's Opening: Lisitsyn Variation 1. e4 e5 2. Bc4 c6 3. d4 d5 4. exd5 cxd5 5. Bb5+ Bd7 6. Bxd7+ Nxd7 7. dxe5 Nxe5 8. Ne2 +C23 Bishop's Opening: Lopez Gambit 1. e4 e5 2. Bc4 Bc5 3. Qe2 Nc6 4. c3 Nf6 5. f4 +C23 Bishop's Opening: Lopez Variation 1. e4 e5 2. Bc4 Bc5 3. Qe2 +C23 Bishop's Opening: Lopez Variation, Lopez Gambit 1. e4 e5 2. Bc4 Bc5 3. Qe2 Nf6 4. f4 +C23 Bishop's Opening: McDonnell Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 +C23 Bishop's Opening: McDonnell Gambit, La Bourdonnais-Denker Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 Bxb4 4. c3 +C23 Bishop's Opening: McDonnell Gambit, McDonnell Double Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 Bxb4 4. f4 +C23 Bishop's Opening: Philidor Counterattack 1. e4 e5 2. Bc4 c6 +C23 Bishop's Opening: Philidor Variation 1. e4 e5 2. Bc4 Bc5 3. c3 +C23 Bishop's Opening: Pratt Variation 1. e4 e5 2. Bc4 Bc5 3. c3 Nf6 4. d4 exd4 5. e5 d5 6. exf6 dxc4 7. Qh5 O-O +C23 Bishop's Opening: Stein Gambit 1. e4 e5 2. Bc4 Bc5 3. f4 +C23 Bishop's Opening: Thorold Gambit 1. e4 e5 2. Bc4 b5 3. Bxb5 f5 +C23 Bishop's Opening: del Rio Variation 1. e4 e5 2. Bc4 Bc5 3. c3 Qg5 +C24 Bishop's Opening: Berlin Defense 1. e4 e5 2. Bc4 Nf6 +C24 Bishop's Opening: Berlin Defense, Greco Gambit 1. e4 e5 2. Bc4 Nf6 3. f4 +C24 Bishop's Opening: Kitchener Folly 1. e4 e5 2. Bc4 Nf6 3. d3 Be7 4. Nf3 O-O +C24 Bishop's Opening: Krejcik Gambit 1. e4 e5 2. Bc4 Nf6 3. f3 Bc5 4. Ne2 Nc6 5. b4 +C24 Bishop's Opening: Pachman Gambit 1. e4 e5 2. Bc4 Nf6 3. Ne2 Nxe4 4. Nec3 +C24 Bishop's Opening: Paulsen Defense 1. e4 e5 2. Bc4 Nf6 3. d3 c6 +C24 Bishop's Opening: Ponziani Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 +C24 Bishop's Opening: Urusov Gambit, Panov Variation 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. Nf3 d5 5. exd5 Bb4+ 6. c3 Qe7+ +C24 Bishop's Opening: Vienna Hybrid 1. e4 e5 2. Bc4 Nf6 3. d3 Nc6 4. Nc3 +C24 Bishop's Opening: Warsaw Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. c3 +C25 Vienna Gambit, with Max Lange Defense 1. e4 e5 2. Nc3 Nc6 3. f4 +C25 Vienna Gambit, with Max Lange Defense: Cunningham Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 Be7 +C25 Vienna Gambit, with Max Lange Defense: Hamppe-Allgaier Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. h4 g4 6. Ng5 +C25 Vienna Gambit, with Max Lange Defense: Hamppe-Allgaier Gambit, Alapin Variation 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. h4 g4 6. Ng5 d6 +C25 Vienna Gambit, with Max Lange Defense: Hamppe-Allgaier Gambit, Thorold Variation 1. e4 e5 2. f4 exf4 3. Nf3 Nc6 4. Nc3 g5 5. h4 g4 6. Ng5 h6 7. Nxf7 Kxf7 8. d4 +C25 Vienna Gambit, with Max Lange Defense: Hamppe-Muzio Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. Bc4 g4 6. O-O gxf3 +C25 Vienna Gambit, with Max Lange Defense: Knight Variation 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 +C25 Vienna Gambit, with Max Lange Defense: Pierce Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. d4 +C25 Vienna Gambit, with Max Lange Defense: Quelle Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 Bc5 4. fxe5 d6 +C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 +C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Fraser-Minckwitz Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 b6 +C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Main Line 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 +C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Paulsen Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 d6 +C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Sörensen Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 g5 +C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Zukertort Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 d5 +C25 Vienna Game 1. e4 e5 2. Nc3 +C25 Vienna Game: Anderssen Defense 1. e4 e5 2. Nc3 Bc5 +C25 Vienna Game: Fyfe Gambit 1. e4 e5 2. Nc3 Nc6 3. d4 +C25 Vienna Game: Giraffe Attack 1. e4 e5 2. Nc3 Bc5 3. Qg4 +C25 Vienna Game: Hamppe-Meitner Variation 1. e4 e5 2. Nc3 Bc5 3. Na4 +C25 Vienna Game: Hamppe-Muzio Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. Bc4 g4 6. O-O +C25 Vienna Game: Hamppe-Muzio, Dubois Variation 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. Bc4 g4 6. O-O gxf3 7. Qxf3 Ne5 8. Qxf4 Qf6 +C25 Vienna Game: Max Lange Defense 1. e4 e5 2. Nc3 Nc6 +C25 Vienna Game: Omaha Gambit 1. e4 e5 2. Nc3 d6 3. f4 +C25 Vienna Game: Paulsen Variation 1. e4 e5 2. Nc3 Nc6 3. g3 +C25 Vienna Game: Paulsen Variation 1. e4 e5 2. Nc3 Nc6 3. g3 Nf6 4. Bg2 Bc5 5. Nge2 d5 +C25 Vienna Game: Paulsen Variation, Mariotti Gambit 1. e4 e5 2. Nc3 Nc6 3. g3 Bc5 4. Bg2 h5 5. Nf3 h4 +C25 Vienna Game: Philidor Countergambit 1. e4 e5 2. Nc3 Nc6 3. d4 f5 +C25 Vienna Game: Pierce Gambit, Rushmere Attack 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. d4 g4 6. Bc4 gxf3 7. O-O d5 8. exd5 Bg4 9. dxc6 +C25 Vienna Game: Stanley Variation, Meitner-Mieses Gambit 1. e4 e5 2. Nc3 Nc6 3. Bc4 Bc5 4. Qg4 Qf6 5. Nd5 +C25 Vienna Game: Zhuravlev Countergambit 1. e4 e5 2. Nc3 Bb4 3. Qg4 Nf6 +C26 Bishop's Opening: Horwitz Gambit 1. e4 e5 2. Bc4 Nf6 3. Nc3 b5 +C26 Bishop's Opening: Vienna Hybrid, Spielmann Attack 1. e4 e5 2. Nc3 Nf6 3. Bc4 Bc5 4. d3 +C26 Vienna Game: Falkbeer Variation 1. e4 e5 2. Nc3 Nf6 +C26 Vienna Game: Mengarini Variation 1. e4 e5 2. Nc3 Nf6 3. a3 +C26 Vienna Game: Mieses Variation 1. e4 e5 2. Nc3 Nf6 3. g3 +C26 Vienna Game: Mieses Variation, Erben Gambit 1. e4 e5 2. Nc3 Nf6 3. g3 d5 4. exd5 c6 +C26 Vienna Game: Paulsen Variation, Pollock Gambit 1. e4 e5 2. Nc3 Nf6 3. g3 Bc5 4. Bg2 Nc6 5. Nge2 d5 6. exd5 +C26 Vienna Game: Stanley Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 +C26 Vienna Game: Stanley Variation, Eifel Gambit 1. e4 e5 2. Nc3 Nf6 3. Bc4 Bc5 4. Nge2 b5 +C26 Vienna Game: Stanley Variation, Reversed Spanish 1. e4 e5 2. Nc3 Nf6 3. Bc4 Bb4 +C27 Bishop's Opening: Boden-Kieseritzky Gambit 1. e4 e5 2. Nf3 Nf6 3. Bc4 Nxe4 4. Nc3 +C27 Bishop's Opening: Boden-Kieseritzky Gambit, Lichtenhein Defense 1. e4 e5 2. Nf3 Nf6 3. Bc4 Nxe4 4. Nc3 d5 +C27 Vienna Game: Adams' Gambit 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Nc6 6. d4 +C27 Vienna Game: Frankenstein-Dracula Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 +C27 Vienna Game: Stanley Variation, Alekhine Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Be7 6. Nf3 Nc6 7. Nxe5 +C27 Vienna Game: Stanley Variation, Frankenstein-Dracula Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Nc6 6. Nb5 g6 7. Qf3 f5 8. Qd5 Qe7 9. Nxc7+ Kd8 10. Nxa8 b6 +C27 Vienna Game: Stanley Variation, Monster Declined 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Be7 +C28 Bishop's Opening: Vienna Hybrid, Hromádka Variation 1. e4 e5 2. Nc3 Nc6 3. Bc4 Nf6 4. d3 Bb4 5. Ne2 +C28 Vienna Game: Stanley Variation, Bronstein Gambit 1. e4 e5 2. Nc3 Nc6 3. Bc4 Nf6 4. f4 Nxe4 5. Nf3 +C28 Vienna Game: Stanley Variation, Three Knights Variation 1. e4 e5 2. Nc3 Nc6 3. Bc4 Nf6 +C29 Vienna Game: Heyde Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Qf3 f5 6. d4 +C29 Vienna Game: Vienna Gambit 1. e4 e5 2. Nc3 Nf6 3. f4 +C29 Vienna Game: Vienna Gambit, Bardeleben Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Qf3 f5 +C29 Vienna Game: Vienna Gambit, Breyer Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Nf3 Be7 +C29 Vienna Game: Vienna Gambit, Kaufmann Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Nf3 Bg4 6. Qe2 +C29 Vienna Game: Vienna Gambit, Main Line 1. e4 e5 2. Nc3 Nf6 3. f4 d5 +C29 Vienna Game: Vienna Gambit, Modern Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. d3 +C29 Vienna Game: Vienna Gambit, Paulsen Attack 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Qf3 +C29 Vienna Game: Vienna Gambit, Steinitz Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. d3 +C29 Vienna Game: Vienna Gambit, Wurzburger Trap 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. d3 Qh4+ 6. g3 Nxg3 7. Nf3 Qh5 8. Nxd5 +C30 King's Gambit 1. e4 e5 2. f4 +C30 King's Gambit Declined: Classical Variation 1. e4 e5 2. f4 Bc5 +C30 King's Gambit Declined: Classical Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 +C30 King's Gambit Declined: Classical Variation, Euwe Attack 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 Bg4 5. fxe5 dxe5 6. Qa4+ +C30 King's Gambit Declined: Classical Variation, Rotlewi Countergambit 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. b4 +C30 King's Gambit Declined: Classical Variation, Rubinstein Countergambit 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 f5 +C30 King's Gambit Declined: Classical Variation, Walthoffen Attack 1. e4 e5 2. f4 Bc5 3. Qh5 +C30 King's Gambit Declined: Classical, Hanham Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. Nc3 Nd7 +C30 King's Gambit Declined: Classical, Réti Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 f5 5. fxe5 dxe5 6. d4 exd4 7. Bc4 +C30 King's Gambit Declined: Classical, Soldatenkov Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. fxe5 +C30 King's Gambit Declined: Classical, Svenonius Variation 1. e4 e5 2. Bc4 Nc6 3. Nc3 Nf6 4. d3 Bc5 5. f4 d6 6. Nf3 Bg4 7. h3 Bxf3 8. Qxf3 exf4 +C30 King's Gambit Declined: Hobbs-Zilbermints Gambit 1. e4 e5 2. f4 Nc6 3. Nf3 g5 4. fxg5 h6 +C30 King's Gambit Declined: Keene Defense 1. e4 e5 2. f4 Qh4+ 3. g3 Qe7 +C30 King's Gambit Declined: Keene's Defense 1. e4 e5 2. f4 Qh4+ +C30 King's Gambit Declined: Keene's Defense 1. e4 e5 2. f4 Qh4+ 3. g3 +C30 King's Gambit Declined: Mafia Defense 1. e4 c5 2. f4 e5 +C30 King's Gambit Declined: Miles Defense 1. e4 e5 2. f4 Nc6 3. Nf3 f5 +C30 King's Gambit Declined: Norwalde Variation 1. e4 e5 2. f4 Qf6 +C30 King's Gambit Declined: Norwalde Variation, Bücker Gambit 1. e4 e5 2. f4 Qf6 3. Nc3 Qxf4 4. Nf3 Bb4 5. Bc4 +C30 King's Gambit Declined: Norwalde Variation, Schubert Variation 1. e4 e5 2. f4 Qf6 3. Nc3 Qxf4 4. d4 +C30 King's Gambit Declined: Panteldakis Countergambit 1. e4 e5 2. f4 f5 +C30 King's Gambit Declined: Panteldakis Countergambit, Greco Variation 1. e4 e5 2. f4 f5 3. exf5 Qh4+ +C30 King's Gambit Declined: Panteldakis Countergambit, Pawn Sacrifice Line 1. e4 e5 2. f4 f5 3. exf5 exf4 4. Qh5+ g6 5. fxg6 Qe7+ 6. Kd1 +C30 King's Gambit Declined: Panteldakis Countergambit, Schiller's Defense 1. e4 e5 2. f4 f5 3. exf5 Bc5 +C30 King's Gambit Declined: Panteldakis Countergambit, Shirazi Line 1. e4 e5 2. f4 f5 3. exf5 exf4 4. Qh5+ Ke7 +C30 King's Gambit Declined: Panteldakis Countergambit, Symmetrical Variation 1. e4 e5 2. f4 f5 3. exf5 exf4 4. Nf3 d5 5. d4 Bd6 6. Bd3 +C30 King's Gambit Declined: Petrov's Defense 1. e4 e5 2. f4 Nf6 +C30 King's Gambit Declined: Queen's Knight Defense 1. e4 e5 2. f4 Nc6 +C30 King's Gambit Declined: Senechaud Countergambit 1. e4 e5 2. f4 Bc5 3. Nf3 g5 +C30 King's Gambit Declined: Soller-Zilbermints Gambit 1. e4 e5 2. f4 f6 3. fxe5 Nc6 +C30 King's Gambit Declined: Zilbermints Double Countergambit 1. e4 e5 2. f4 g5 +C30 King's Gambit Declined: Zilbermints Double Gambit 1. e4 e5 2. f4 Nc6 3. Nf3 g5 +C31 King's Gambit Declined: Falkbeer Countergambit 1. e4 e5 2. f4 d5 +C31 King's Gambit Declined: Falkbeer Countergambit Accepted 1. e4 e5 2. f4 d5 3. exd5 +C31 King's Gambit Declined: Falkbeer Countergambit, Anderssen Attack 1. e4 e5 2. f4 d5 3. exd5 e4 4. Bb5+ +C31 King's Gambit Declined: Falkbeer Countergambit, Blackburne Attack 1. e4 e5 2. f4 d5 3. Nf3 +C31 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 +C31 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Morphy Defense 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. exd5 e4 5. d3 Bb4 6. Bd2 e3 +C31 King's Gambit Declined: Falkbeer Countergambit, Hinrichsen Gambit 1. e4 e5 2. f4 d5 3. d4 +C31 King's Gambit Declined: Falkbeer Countergambit, Miles Gambit 1. e4 e5 2. f4 d5 3. exd5 Bc5 +C31 King's Gambit Declined: Falkbeer Countergambit, Milner-Barry Variation 1. e4 e5 2. f4 d5 3. Nc3 +C31 King's Gambit Declined: Falkbeer Countergambit, Modern Transfer 1. e4 e5 2. f4 d5 3. exd5 exf4 +C31 King's Gambit Declined: Falkbeer Countergambit, Nimzowitsch-Marshall Countergambit 1. e4 e5 2. f4 d5 3. exd5 c6 +C31 King's Gambit Declined: Falkbeer Countergambit, Pickler Gambit 1. e4 e5 2. f4 d5 3. exd5 c6 4. dxc6 Bc5 +C31 King's Gambit Declined: Falkbeer Countergambit, Rubinstein Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. Nc3 Nf6 5. Qe2 +C31 King's Gambit Declined: Falkbeer Countergambit, Staunton Line 1. e4 e5 2. f4 d5 3. exd5 e4 +C31 Van Geet Opening: Grünfeld Defense, Steiner Gambit 1. e4 e5 2. f4 d5 3. Nc3 dxe4 4. Nxe4 +C32 King's Gambit Declined: Falkbeer Countergambit, Alapin Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Nf3 Bc5 7. Qe2 Bf2+ 8. Kd1 Qxd5+ 9. Nfd2 +C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Qe2 +C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit Accepted 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 +C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Keres Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. Nd2 +C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Main Line 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Nf3 Bc5 7. Qe2 Bf5 +C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Old Line 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. Qe2 +C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Qe2 Qxd5 7. Nd2 f5 8. g4 +C32 King's Gambit Declined: Falkbeer Countergambit, Tarrasch Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Nf3 Bc5 7. Qe2 Bf5 8. g4 O-O +C33 King's Gambit Accepted 1. e4 e5 2. f4 exf4 +C33 King's Gambit Accepted: Basman Gambit 1. e4 e5 2. f4 exf4 3. Qe2 +C33 King's Gambit Accepted: Bishop's Gambit 1. e4 e5 2. f4 exf4 3. Bc4 +C33 King's Gambit Accepted: Bishop's Gambit, Anderssen Defense 1. e4 e5 2. f4 exf4 3. Bc4 g5 +C33 King's Gambit Accepted: Bishop's Gambit, Anderssen Variation 1. e4 e5 2. f4 exf4 3. Bc4 d5 4. Bxd5 c6 +C33 King's Gambit Accepted: Bishop's Gambit, Bledow Countergambit 1. e4 e5 2. f4 exf4 3. Bc4 d5 4. Bxd5 Nf6 +C33 King's Gambit Accepted: Bishop's Gambit, Bledow Variation 1. e4 e5 2. f4 exf4 3. Bc4 d5 +C33 King's Gambit Accepted: Bishop's Gambit, Boden Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Nc6 +C33 King's Gambit Accepted: Bishop's Gambit, Bogoljubow Defense 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 4. Nc3 c6 +C33 King's Gambit Accepted: Bishop's Gambit, Bogoljubow Variation 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 4. Nc3 +C33 King's Gambit Accepted: Bishop's Gambit, Boren-Svenonius Variation 1. e4 e5 2. f4 exf4 3. Bc4 d5 4. Bxd5 Qh4+ 5. Kf1 Bd6 +C33 King's Gambit Accepted: Bishop's Gambit, Bryan Countergambit 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 b5 +C33 King's Gambit Accepted: Bishop's Gambit, Chigorin's Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 d5 5. Bxd5 g5 6. g3 +C33 King's Gambit Accepted: Bishop's Gambit, Classical Defense 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Ne7 5. Nc3 g5 6. d4 Bg7 +C33 King's Gambit Accepted: Bishop's Gambit, Classical Defense, Cozio Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Qf3 +C33 King's Gambit Accepted: Bishop's Gambit, Cozio Defense 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 +C33 King's Gambit Accepted: Bishop's Gambit, Cozio Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 d6 +C33 King's Gambit Accepted: Bishop's Gambit, First Jaenisch Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Nf6 +C33 King's Gambit Accepted: Bishop's Gambit, Fraser Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. g3 fxg3 7. Qf3 +C33 King's Gambit Accepted: Bishop's Gambit, Gianutio Gambit 1. e4 e5 2. f4 exf4 3. Bc4 f5 +C33 King's Gambit Accepted: Bishop's Gambit, Greco Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Bc5 +C33 King's Gambit Accepted: Bishop's Gambit, Grimm Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. d4 d6 7. e5 +C33 King's Gambit Accepted: Bishop's Gambit, Kieseritzky Gambit 1. e4 e5 2. f4 exf4 3. Bc4 b5 +C33 King's Gambit Accepted: Bishop's Gambit, Lopez Defense 1. e4 e5 2. f4 exf4 3. Bc4 c6 +C33 King's Gambit Accepted: Bishop's Gambit, Lopez Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 +C33 King's Gambit Accepted: Bishop's Gambit, Maurian Defense 1. e4 e5 2. f4 exf4 3. Bc4 Nc6 +C33 King's Gambit Accepted: Bishop's Gambit, McDonnell Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. d4 Ne7 7. g3 +C33 King's Gambit Accepted: Bishop's Gambit, McDonnell Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. g3 +C33 King's Gambit Accepted: Bishop's Gambit, Paulsen Attack 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 4. Nc3 Bb4 5. e5 +C33 King's Gambit Accepted: Bishop's Gambit, Steinitz Defense 1. e4 e5 2. f4 exf4 3. Bc4 Ne7 +C33 King's Gambit Accepted: Breyer Gambit 1. e4 e5 2. f4 exf4 3. Qf3 +C33 King's Gambit Accepted: Carrera Gambit 1. e4 e5 2. f4 exf4 3. Qh5 +C33 King's Gambit Accepted: Dodo Variation 1. e4 e5 2. f4 exf4 3. Qg4 +C33 King's Gambit Accepted: Eisenberg Variation 1. e4 e5 2. f4 exf4 3. Nh3 +C33 King's Gambit Accepted: Gaga Gambit 1. e4 e5 2. f4 exf4 3. g3 +C33 King's Gambit Accepted: Lopez-Gianutio Countergambit, Hein Variation 1. e4 e5 2. f4 exf4 3. Bc4 f5 4. Qe2 Qh4+ 5. Kd1 fxe4 6. Nc3 Kd8 +C33 King's Gambit Accepted: Mason-Keres Gambit 1. e4 e5 2. f4 exf4 3. Nc3 +C33 King's Gambit Accepted: Orsini Gambit 1. e4 e5 2. f4 exf4 3. b3 +C33 King's Gambit Accepted: Paris Gambit 1. e4 e5 2. f4 exf4 3. Ne2 +C33 King's Gambit Accepted: Schurig Gambit, with Bb5 1. e4 e5 2. f4 exf4 3. Bb5 +C33 King's Gambit Accepted: Schurig Gambit, with Bd3 1. e4 e5 2. f4 exf4 3. Bd3 +C33 King's Gambit Accepted: Stamma Gambit 1. e4 e5 2. f4 exf4 3. h4 +C33 King's Gambit Accepted: Tartakower Gambit 1. e4 e5 2. f4 exf4 3. Be2 +C33 King's Gambit Accepted: Tartakower Gambit, Weiss Defense 1. e4 e5 2. f4 exf4 3. Be2 f5 4. exf5 d6 +C33 King's Gambit Accepted: Tumbleweed 1. e4 e5 2. f4 exf4 3. Kf2 +C33 King's Gambit Accepted: Villemson Gambit 1. e4 e5 2. f4 exf4 3. d4 +C34 King's Gambit Accepted: Becker Defense 1. e4 e5 2. f4 exf4 3. Nf3 h6 +C34 King's Gambit Accepted: Bonsch-Osmolovsky Variation 1. e4 e5 2. f4 exf4 3. Nf3 Ne7 +C34 King's Gambit Accepted: Fischer Defense 1. e4 e5 2. f4 exf4 3. Nf3 d6 +C34 King's Gambit Accepted: Fischer Defense, Schulder Gambit 1. e4 e5 2. f4 exf4 3. Nf3 d6 4. b4 +C34 King's Gambit Accepted: Fischer Defense, Spanish Variation 1. e4 e5 2. f4 exf4 3. Nf3 d6 4. d4 Nf6 5. Bd3 +C34 King's Gambit Accepted: Gianutio Countergambit 1. e4 e5 2. f4 exf4 3. Nf3 f5 +C34 King's Gambit Accepted: Greco Gambit 1. e4 e5 2. f4 exf4 3. Nf3 d6 4. Bc4 h6 5. d4 g5 6. h4 Bg7 +C34 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 +C34 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 +C34 King's Gambit Accepted: MacLeod Defense 1. e4 e5 2. f4 exf4 3. Nf3 Nc6 +C34 King's Gambit Accepted: Schallopp Defense 1. e4 e5 2. f4 exf4 3. Nf3 Nf6 +C34 King's Gambit Accepted: Schallopp Defense, Tashkent Attack 1. e4 e5 2. f4 exf4 3. Nf3 Nf6 4. e5 Nh5 5. g4 +C34 King's Gambit Accepted: Wagenbach Defense 1. e4 e5 2. f4 exf4 3. Nf3 h5 +C35 King's Gambit Accepted: Cunningham Defense 1. e4 e5 2. f4 exf4 3. Nf3 Be7 +C35 King's Gambit Accepted: Cunningham Defense, Bertin Gambit 1. e4 e5 2. f4 exf4 3. Nf3 Be7 4. Bc4 Bh4+ 5. g3 +C35 King's Gambit Accepted: Cunningham Defense, Bertin Gambit 1. e4 e5 2. f4 exf4 3. Nf3 Be7 4. Bc4 Bh4+ 5. g3 fxg3 6. O-O gxh2+ 7. Kh1 +C35 King's Gambit Accepted: Cunningham Defense, McCormick Defense 1. e4 e5 2. f4 exf4 3. Nf3 Be7 4. Bc4 Nf6 +C36 King's Gambit Accepted: Abbazia Defense 1. e4 e5 2. f4 exf4 3. Nf3 d5 4. exd5 Nf6 +C36 King's Gambit Accepted: Abbazia Defense, Main Line 1. e4 e5 2. f4 exf4 3. Nf3 d5 4. exd5 Nf6 5. Bb5+ c6 6. dxc6 bxc6 7. Bc4 Nd5 +C36 King's Gambit Accepted: Modern Defense 1. e4 e5 2. f4 exf4 3. Nf3 d5 +C36 King's Gambit Accepted: Modern Defense 1. e4 e5 2. f4 exf4 3. Nf3 d5 4. exd5 +C37 King's Gambit Accepted: Australian Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. h4 +C37 King's Gambit Accepted: Blachly Gambit 1. e4 e5 2. f4 exf4 3. Nf3 Nc6 4. Bc4 g5 +C37 King's Gambit Accepted: Double Muzio Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. e5 Qxe5 8. Bxf7+ +C37 King's Gambit Accepted: Double Muzio Gambit, Baldwin Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. Nc3 Qd4+ 8. Kh1 Qxc4 9. Nd5 +C37 King's Gambit Accepted: Double Muzio Gambit, Bello Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. Nc3 +C37 King's Gambit Accepted: Double Muzio Gambit, Paulsen Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. e5 Qxe5 8. d3 Bh6 9. Nc3 Ne7 10. Bd2 Nbc6 11. Rae1 +C37 King's Gambit Accepted: Double Muzio Gambit, Young Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. Bxf7+ Kxf7 8. d4 Qxd4+ 9. Be3 Qf6 10. Nc3 fxe3 +C37 King's Gambit Accepted: Ghulam-Kassim Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. d4 +C37 King's Gambit Accepted: Ghulam-Kassim Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. d4 gxf3 6. Qxf3 +C37 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 +C37 King's Gambit Accepted: Kotov Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. d4 gxf3 6. Bxf4 +C37 King's Gambit Accepted: Lolli Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Bxf7+ +C37 King's Gambit Accepted: Lolli Gambit, Young Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Bxf7+ Kxf7 6. O-O gxf3 7. Qxf3 Qf6 8. d4 Qxd4+ 9. Be3 Qf6 10. Nc3 +C37 King's Gambit Accepted: McDonnell Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Nc3 +C37 King's Gambit Accepted: Middleton Countergambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 d6 5. O-O Bg4 6. h3 h5 7. hxg4 hxg4 +C37 King's Gambit Accepted: Muzio Gambit Accepted, From's Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qe7 +C37 King's Gambit Accepted: Muzio Gambit, Brentano Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O d5 +C37 King's Gambit Accepted: Muzio Gambit, Holloway Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Nc6 +C37 King's Gambit Accepted: Muzio Gambit, Kling and Horwitz Counterattack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O Qe7 +C37 King's Gambit Accepted: Muzio Gambit, Sarratt Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 +C37 King's Gambit Accepted: Muzio Gambit, Wild Muzio Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O +C37 King's Gambit Accepted: Quaade Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Nc3 +C37 King's Gambit Accepted: Rosentreter Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 +C37 King's Gambit Accepted: Rosentreter Gambit, Bird Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Ne5 Qh4+ 6. g3 +C37 King's Gambit Accepted: Rosentreter Gambit, Sörensen Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Nc3 +C37 King's Gambit Accepted: Rosentreter Gambit, Testa Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Bxf4 +C37 King's Gambit Accepted: Salvio Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 +C37 King's Gambit Accepted: Salvio Gambit, Anderssen Counterattack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nh6 7. d4 d6 +C37 King's Gambit Accepted: Salvio Gambit, Cochrane Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 f3 +C37 King's Gambit Accepted: Salvio Gambit, Santa Maria Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nf6 +C37 King's Gambit Accepted: Salvio Gambit, Silberschmidt Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nh6 +C37 King's Gambit Accepted: Salvio Gambit, Viennese Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nc6 +C37 King's Gambit Accepted: Silberschmidt Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nh6 7. d4 f3 +C37 King's Gambit Accepted: Sörensen Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Ne5 +C38 King's Gambit Accepted: Greco Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. h4 h6 6. d4 d6 7. Nc3 c6 8. hxg5 hxg5 9. Rxh8 Bxh8 10. Ne5 +C38 King's Gambit Accepted: Hanstein Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. O-O +C38 King's Gambit Accepted: Mayet Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. d4 d6 6. c3 +C38 King's Gambit Accepted: Philidor Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. h4 +C38 King's Gambit Accepted: Philidor Gambit, Schultz Variation 1. e4 e5 2. f4 exf4 3. Nf3 h6 4. Bc4 d6 5. d4 g5 6. h4 Bg7 7. Qd3 +C38 King's Gambit Accepted: Traditional Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 +C39 King's Gambit Accepted: Allgaier Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 +C39 King's Gambit Accepted: Allgaier Gambit, Thorold Attack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. d4 +C39 King's Gambit Accepted: Allgaier Gambit, Urusov Attack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Bc4+ +C39 King's Gambit Accepted: Allgaier, Blackburne Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Nc3 +C39 King's Gambit Accepted: Allgaier, Cook Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. d4 d5 8. Bxf4 dxe4 9. Bc4+ Kg7 10. Be5+ +C39 King's Gambit Accepted: Allgaier, Horny Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Qxg4 Nf6 8. Qxf4 Bd6 +C39 King's Gambit Accepted: Allgaier, Schlechter Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 Nf6 +C39 King's Gambit Accepted: Allgaier, Urusov Attack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Bc4+ d5 8. Bxd5+ Kg7 9. d4 +C39 King's Gambit Accepted: Kieseritzky Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 +C39 King's Gambit Accepted: Kieseritzky Gambit, Anderssen Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 +C39 King's Gambit Accepted: Kieseritzky Gambit, Anderssen-Cordel Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 8. d4 Nh5 9. Bxf4 Nxf4 +C39 King's Gambit Accepted: Kieseritzky Gambit, Berlin Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 +C39 King's Gambit Accepted: Kieseritzky Gambit, Berlin Defense, Rubinstein Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. d4 +C39 King's Gambit Accepted: Kieseritzky Gambit, Berlin Defense, de Riviere Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Nxg4 d5 +C39 King's Gambit Accepted: Kieseritzky Gambit, Brentano Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d5 +C39 King's Gambit Accepted: Kieseritzky Gambit, Brentano Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d5 6. d4 Nf6 7. Bxf4 +C39 King's Gambit Accepted: Kieseritzky Gambit, Brentano Defense, Caro Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d5 6. d4 Nf6 7. Bxf4 Nxe4 8. Nd2 +C39 King's Gambit Accepted: Kieseritzky Gambit, Cotter Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 +C39 King's Gambit Accepted: Kieseritzky Gambit, Kolisch Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d6 +C39 King's Gambit Accepted: Kieseritzky Gambit, Long Whip 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 h5 +C39 King's Gambit Accepted: Kieseritzky Gambit, Neumann Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nc6 +C39 King's Gambit Accepted: Kieseritzky Gambit, Paulsen Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Bg7 +C39 King's Gambit Accepted: Kieseritzky Gambit, Paulsen Defense Deferred 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bg7 +C39 King's Gambit Accepted: Kieseritzky Gambit, Rice Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 8. O-O Bxe5 +C39 King's Gambit Accepted: Kieseritzky Gambit, Rosenthal Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Qe7 +C39 King's Gambit Accepted: Kieseritzky, Long Whip Defense, Jaenisch Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 h5 6. Bc4 Rh7 7. d4 Bh6 8. Nc3 +C39 King's Gambit Accepted: Kieseritzky, Polerio Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Be7 +C39 King's Gambit Accepted: Kieseritzky, Rice Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 8. O-O +C39 King's Gambit Accepted: Kieseritzky, Salvio Defense, Cozio Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Qe7 6. d4 f5 7. Bc4 +C39 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 +C40 Elephant Gambit 1. e4 e5 2. Nf3 d5 +C40 Elephant Gambit: Maróczy Gambit 1. e4 e5 2. Nf3 d5 3. exd5 Bd6 +C40 Elephant Gambit: Paulsen Countergambit 1. e4 e5 2. Nf3 d5 3. exd5 e4 +C40 Elephant Gambit: Wasp Variation 1. e4 e5 2. Nf3 d5 3. Nxe5 dxe4 4. Bc4 Qg5 +C40 Gunderam Defense 1. e4 e5 2. Nf3 Qe7 +C40 King's Knight Opening 1. e4 e5 2. Nf3 +C40 King's Pawn Game: Busch-Gass Gambit 1. e4 e5 2. Nf3 Bc5 +C40 King's Pawn Game: Busch-Gass Gambit, Chiodini Gambit 1. e4 e5 2. Nf3 Bc5 3. Nxe5 Nc6 +C40 King's Pawn Game: Damiano Defense 1. e4 e5 2. Nf3 f6 +C40 King's Pawn Game: Damiano Defense, Damiano Gambit 1. e4 e5 2. Nf3 f6 3. Nxe5 fxe5 4. Qh5+ g6 5. Qxe5+ Qe7 6. Qxh8 +C40 King's Pawn Game: Damiano Defense, Damiano Gambit, Chigorin Gambit 1. e4 e5 2. Nf3 f6 3. Nxe5 Qe7 4. Nf3 d5 +C40 King's Pawn Game: Gunderam Defense, Gunderam Gambit 1. e4 e5 2. Nf3 Qe7 3. Bc4 f5 +C40 King's Pawn Game: Gunderam Gambit 1. e4 e5 2. Nf3 c6 +C40 King's Pawn Game: La Bourdonnais Gambit 1. e4 e5 2. Nf3 Qf6 3. Bc4 Qg6 4. O-O +C40 King's Pawn Game: McConnell Defense 1. e4 e5 2. Nf3 Qf6 +C40 Latvian Gambit 1. e4 e5 2. Nf3 f5 +C40 Latvian Gambit Accepted 1. e4 e5 2. Nf3 f5 3. exf5 +C40 Latvian Gambit Accepted: Bilguer Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 +C40 Latvian Gambit Accepted: Bronstein Attack 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 fxe4 6. Be2 +C40 Latvian Gambit Accepted: Bronstein Gambit 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 fxe4 6. Qh5+ g6 7. Qe2 +C40 Latvian Gambit Accepted: Foltys Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. Nc4 fxe4 5. d3 +C40 Latvian Gambit Accepted: Foltys-Leonhardt Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. Nc4 +C40 Latvian Gambit Accepted: Leonhardt Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. Nc4 fxe4 5. Nc3 +C40 Latvian Gambit Accepted: Main Line 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 +C40 Latvian Gambit Accepted: Nimzowitsch Attack 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 fxe4 6. Ne3 +C40 Latvian Gambit: Behting Variation 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 Qg5 5. Nf7 Qxg2 6. Rf1 d5 7. Nxh8 Nf6 +C40 Latvian Gambit: Corkscrew Countergambit 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 Nf6 +C40 Latvian Gambit: Corkscrew Gambit 1. e4 e5 2. Nf3 f5 3. Nxe5 Nf6 4. Bc4 fxe4 5. Nf7 Qe7 6. Nxh8 d5 +C40 Latvian Gambit: Diepstraten Countergambit 1. e4 e5 2. Nf3 f5 3. c4 +C40 Latvian Gambit: Fraser Defense 1. e4 e5 2. Nf3 f5 3. Nxe5 Nc6 +C40 Latvian Gambit: Greco Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qe7 +C40 Latvian Gambit: Lobster Gambit 1. e4 e5 2. Nf3 f5 3. g4 +C40 Latvian Gambit: Mason Countergambit 1. e4 e5 2. Nf3 f5 3. d4 +C40 Latvian Gambit: Mayet Attack 1. e4 e5 2. Nf3 f5 3. Bc4 +C40 Latvian Gambit: Mayet Attack, Morgado Defense 1. e4 e5 2. Nf3 f5 3. Bc4 Nf6 +C40 Latvian Gambit: Mayet Attack, Poisoned Pawn Variation 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 Qg5 5. d4 Qxg2 +C40 Latvian Gambit: Mayet Attack, Polerio-Svedenborg Variation 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 d5 +C40 Latvian Gambit: Mayet Attack, Strautins Gambit 1. e4 e5 2. Nf3 f5 3. Bc4 b5 +C40 Latvian Gambit: Mlotkowski Variation 1. e4 e5 2. Nf3 f5 3. Nc3 +C40 Latvian Gambit: Senechaud Gambit 1. e4 e5 2. Nf3 f5 3. b4 +C41 Philidor Defense 1. e4 e5 2. Nf3 d6 +C41 Philidor Defense 1. e4 e5 2. Nf3 d6 3. d4 +C41 Philidor Defense 1. e4 e5 2. Nf3 d6 3. Bc4 +C41 Philidor Defense 1. e4 e5 2. Nf3 d6 3. Bc4 Be7 +C41 Philidor Defense: Albin-Blackburne Gambit 1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Nd7 +C41 Philidor Defense: Berger Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 Nf6 5. Nc3 Be7 6. Be2 O-O 7. O-O c5 8. Nf3 Nc6 9. Bg5 Be6 10. Re1 +C41 Philidor Defense: Bird Gambit 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. c3 +C41 Philidor Defense: Boden Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Qxd4 Bd7 +C41 Philidor Defense: Exchange Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 +C41 Philidor Defense: Exchange Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 +C41 Philidor Defense: Exchange Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 Nf6 +C41 Philidor Defense: Hanham Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 +C41 Philidor Defense: Hanham Variation, Delmar Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. c3 +C41 Philidor Defense: Hanham Variation, Krause Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. O-O +C41 Philidor Defense: Hanham Variation, Schlechter Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. Nc3 +C41 Philidor Defense: Hanham Variation, Sharp Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 Nb6 +C41 Philidor Defense: Hanham Variation, Steiner Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. O-O Be7 6. dxe5 +C41 Philidor Defense: Hanham, Kmoch Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. Ng5 +C41 Philidor Defense: Larsen Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 g6 +C41 Philidor Defense: Lion Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 +C41 Philidor Defense: Lion Variation, Bishop Sacrifice 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. Bxf7+ +C41 Philidor Defense: Lion Variation, Delayed Bishop Sacrifice 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. Nf3 e5 5. Bc4 Be7 6. dxe5 dxe5 7. Bxf7+ +C41 Philidor Defense: Lion Variation, Forcing Line 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. Ng5 O-O 7. Bxf7+ Rxf7 8. Ne6 +C41 Philidor Defense: Lion Variation, Lion's Claw, with Bc4 and h6 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. O-O h6 +C41 Philidor Defense: Lion Variation, Lion's Claw, with Be2 and c6 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Be2 Be7 6. O-O c6 +C41 Philidor Defense: Lion Variation, Shirov Gambit 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Nc3 Ngf6 5. g4 +C41 Philidor Defense: Lion Variation, Sozin Variation 1. e4 d6 2. d4 Nf6 3. Nc3 e5 4. Nf3 Nbd7 5. Bc4 Be7 6. O-O O-O 7. Qe2 c6 8. a4 exd4 +C41 Philidor Defense: Lopez Countergambit 1. e4 e5 2. Nf3 d6 3. Bc4 f5 +C41 Philidor Defense: Lopez Countergambit, Jaenisch Variation 1. e4 e5 2. Nf3 d6 3. d4 f5 4. Bc4 exd4 5. Ng5 Nh6 6. Nxh7 +C41 Philidor Defense: Morphy Gambit 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Bc4 +C41 Philidor Defense: Nimzowitsch Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 +C41 Philidor Defense: Nimzowitsch Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. dxe5 +C41 Philidor Defense: Nimzowitsch Variation, Klein Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Bc4 +C41 Philidor Defense: Nimzowitsch Variation, Rellstab Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. dxe5 Nxe4 5. Qd5 +C41 Philidor Defense: Nimzowitsch Variation, Sokolsky Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. dxe5 Nxe4 5. Nbd2 +C41 Philidor Defense: Nimzowitsch, Larobok Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. Ng5 O-O 7. Bxf7+ +C41 Philidor Defense: Nimzowitsch, Locock Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Ng5 +C41 Philidor Defense: Paulsen Attack 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 d5 5. exd5 +C41 Philidor Defense: Philidor Countergambit 1. e4 e5 2. Nf3 d6 3. d4 f5 +C41 Philidor Defense: Philidor Countergambit, Berger Variation 1. e4 e5 2. Nf3 d6 3. d4 f5 4. dxe5 fxe4 5. Ng5 d5 6. e6 Bc5 7. Nc3 +C41 Philidor Defense: Philidor Countergambit, Zukertort Variation 1. e4 e5 2. Nf3 d6 3. d4 f5 4. Nc3 +C41 Philidor Defense: Philidor Countergambit, del Rio Attack 1. e4 e5 2. Nf3 d6 3. d4 f5 4. dxe5 fxe4 5. Ng5 d5 6. e6 +C41 Philidor Defense: Philidor Gambit 1. e4 e5 2. Nf3 d6 3. d4 Bd7 +C41 Philidor Defense: Steinitz Variation 1. e4 e5 2. Nf3 d6 3. Bc4 Be7 4. c3 +C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 +C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 +C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 +C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 +C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 +C42 Petrov's Defense: Classical Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 +C42 Petrov's Defense: Classical Attack, Berger Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O Nc6 8. Re1 Bg4 9. c3 f5 10. Nbd2 +C42 Petrov's Defense: Classical Attack, Chigorin Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O Nc6 8. Re1 +C42 Petrov's Defense: Classical Attack, Chigorin Variation, Browne Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. c4 Nb4 9. cxd5 +C42 Petrov's Defense: Classical Attack, Chigorin Variation, Main Line 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. c4 Nb4 9. Be2 +C42 Petrov's Defense: Classical Attack, Closed Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 Nf6 +C42 Petrov's Defense: Classical Attack, Jaenisch Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. c4 +C42 Petrov's Defense: Classical Attack, Krause Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. Re1 Bg4 9. c3 f5 10. c4 +C42 Petrov's Defense: Classical Attack, Marshall Trap 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 Bg4 9. cxd5 f5 10. Re1 Bxh2+ +C42 Petrov's Defense: Classical Attack, Marshall Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 +C42 Petrov's Defense: Classical Attack, Marshall Variation, Chinese Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 c6 9. Re1 Bg4 +C42 Petrov's Defense: Classical Attack, Maróczy Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O Nc6 8. Re1 Bg4 9. c3 f5 10. c4 Bh4 +C42 Petrov's Defense: Classical Attack, Mason Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O O-O +C42 Petrov's Defense: Classical Attack, Mason-Showalter Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 +C42 Petrov's Defense: Classical Attack, Staunton Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 c6 +C42 Petrov's Defense: Classical Attack, Tarrasch Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 Bg4 +C42 Petrov's Defense: Cochrane Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nxf7 +C42 Petrov's Defense: Cochrane Gambit, Bishop Check Line 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nxf7 Kxf7 5. Bc4+ +C42 Petrov's Defense: Cochrane Gambit, Center Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nxf7 Kxf7 5. d4 +C42 Petrov's Defense: Cozio Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. Qe2 +C42 Petrov's Defense: Damiano Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nxe4 +C42 Petrov's Defense: Damiano Variation, Kholmov Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nxe4 4. Qe2 Qe7 +C42 Petrov's Defense: French Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d3 +C42 Petrov's Defense: Italian Variation 1. e4 e5 2. Nf3 Nf6 3. Bc4 +C42 Petrov's Defense: Karklins-Martinovsky Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nd3 +C42 Petrov's Defense: Kaufmann Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. c4 +C42 Petrov's Defense: Millennium Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. Bd3 +C42 Petrov's Defense: Moody Gambit 1. e4 e5 2. Nf3 Nf6 3. Qe2 Nc6 4. d4 +C42 Petrov's Defense: Nimzowitsch Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. Nc3 +C42 Petrov's Defense: Paulsen Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nc4 +C42 Petrov's Defense: Stafford Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 +C42 Petrov's Defense: Stafford Gambit Accepted 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 +C42 Petrov's Defense: Stafford Gambit Accepted 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 5. Nc3 Bc5 +C42 Petrov's Defense: Stafford Gambit Accepted 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 5. d3 Bc5 +C42 Petrov's Defense: Three Knights Game 1. e4 e5 2. Nf3 Nf6 3. Nc3 +C43 Bishop's Opening: Urusov Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. Nf3 +C43 Bishop's Opening: Urusov Gambit, Keidansky Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. Nf3 Nxe4 5. Qxd4 +C43 Petrov's Defense: Modern Attack 1. e4 e5 2. Nf3 Nf6 3. d4 +C43 Petrov's Defense: Modern Attack 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 +C43 Petrov's Defense: Modern Attack, Bardeleben Variation 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Qe2 Nc5 6. Nxd4 Nc6 +C43 Petrov's Defense: Modern Attack, Center Attack 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Qxd4 +C43 Petrov's Defense: Modern Attack, Center Variation 1. e4 e5 2. Nf3 Nf6 3. d4 Nxe4 4. Bd3 +C43 Petrov's Defense: Modern Attack, Murrey Variation 1. e4 e5 2. Nf3 Nf6 3. d4 Nxe4 4. Bd3 Nc6 +C43 Petrov's Defense: Modern Attack, Steinitz Variation 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Qe2 +C43 Petrov's Defense: Modern Attack, Symmetrical Variation 1. e4 e5 2. Nf3 Nf6 3. d4 d5 +C43 Petrov's Defense: Modern Attack, Tal Gambit 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Bb5 +C43 Petrov's Defense: Modern Attack, Trifunovic Variation 1. e4 e5 2. Nf3 Nf6 3. d4 Nxe4 4. Bd3 d5 5. Nxe5 Bd6 6. O-O O-O 7. c4 Bxe5 +C44 Dresden Opening: The Goblin 1. e4 e5 2. Nf3 Nc6 3. c4 Nf6 4. Nxe5 +C44 Irish Gambit 1. e4 e5 2. Nf3 Nc6 3. Nxe5 +C44 King's Knight Opening: Konstantinopolsky 1. e4 e5 2. Nf3 Nc6 3. g3 +C44 King's Knight Opening: Normal Variation 1. e4 e5 2. Nf3 Nc6 +C44 King's Pawn Game: Dresden Opening 1. e4 e5 2. Nf3 Nc6 3. c4 +C44 King's Pawn Game: Pachman Wing Gambit 1. e4 e5 2. Nf3 Nc6 3. b4 +C44 King's Pawn Game: Schulze-Müller Gambit 1. e4 e5 2. Nf3 Nc6 3. Nxe5 Nxe5 4. d4 +C44 King's Pawn Game: Tayler Opening 1. e4 e5 2. Nf3 Nc6 3. Be2 +C44 King's Pawn Game: Tayler Opening 1. e4 e5 2. Nf3 Nc6 3. Be2 Nf6 4. d4 +C44 King's Pawn Game: Tayler Opening, Basman Gambit 1. e4 e5 2. Nf3 Nc6 3. Be2 Nf6 4. d4 exd4 5. e5 +C44 King's Pawn Game: Tayler Opening, Inverted Hanham 1. e4 e5 2. Nf3 Nc6 3. Be2 Nf6 4. d3 d5 5. Nbd2 +C44 Latvian Gambit: Clam Gambit 1. e4 e5 2. Nf3 Nc6 3. d3 f5 4. exf5 +C44 Ponziani Opening 1. e4 e5 2. Nf3 Nc6 3. c3 +C44 Ponziani Opening: Caro Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Qa4 Bd7 +C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 +C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d3 +C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d3 d5 +C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d3 d5 5. Nbd2 +C44 Ponziani Opening: Leonhardt Variation 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Qa4 Nf6 +C44 Ponziani Opening: Neumann Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. Bc4 +C44 Ponziani Opening: Ponziani Countergambit 1. e4 e5 2. Nf3 Nc6 3. c3 f5 +C44 Ponziani Opening: Ponziani Countergambit, Schmidt Attack 1. e4 e5 2. Nf3 Nc6 3. c3 f5 4. d4 d6 5. d5 +C44 Ponziani Opening: Romanishin Variation 1. e4 e5 2. Nf3 Nc6 3. c3 Be7 +C44 Ponziani Opening: Réti Variation 1. e4 e5 2. Nf3 Nc6 3. c3 Nge7 +C44 Ponziani Opening: Spanish Variation 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Bb5 +C44 Ponziani Opening: Spanish Variation, Harrwitz Attack, Nikitin Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Bb5 dxe4 5. Nxe5 Qd5 6. Qa4 +C44 Ponziani Opening: Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Qa4 f6 +C44 Ponziani Opening: Vukovic Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d4 Nxe4 5. d5 Bc5 +C44 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 +C44 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 +C44 Scotch Game: Benima Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Be7 4. d4 exd4 +C44 Scotch Game: Cochrane Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bb4+ 5. c3 dxc3 6. bxc3 Ba5 7. e5 +C44 Scotch Game: Cochrane-Shumov Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. Ng5 Nh6 6. Nxf7 Nxf7 7. Bxf7+ Kxf7 8. Qh5+ g6 9. Qxc5 d5 +C44 Scotch Game: Göring Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 +C44 Scotch Game: Göring Gambit, Bardeleben Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Bc4 Nf6 6. Nxc3 Bb4 +C44 Scotch Game: Göring Gambit, Double Pawn Sacrifice 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Bc4 +C44 Scotch Game: Göring Gambit, Main Line 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Nxc3 Bb4 +C44 Scotch Game: Hanneken Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bb4+ 5. c3 dxc3 6. O-O cxb2 7. Bxb2 Nf6 8. Ng5 O-O 9. e5 Nxe5 +C44 Scotch Game: Haxo Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 +C44 Scotch Game: Lolli Variation 1. e4 e5 2. Nf3 Nc6 3. d4 Nxd4 +C44 Scotch Game: Lolli Variation 1. e4 e5 2. Nf3 Nc6 3. d4 Nxd4 4. Nxd4 exd4 5. Qxd4 +C44 Scotch Game: Napoleon Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 Nxd4 4. Nxd4 exd4 5. Bc4 +C44 Scotch Game: Relfsson Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bb5 +C44 Scotch Game: Scotch Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 +C44 Scotch Game: Scotch Gambit, Advance Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. e5 +C44 Scotch Game: Scotch Gambit, Cochrane-Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. O-O d6 6. c3 Bg4 +C44 Scotch Game: Scotch Gambit, Dubois Réti Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 +C44 Scotch Game: Scotch Gambit, Göring Gambit Declined 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 d5 +C44 Scotch Game: Scotch Gambit, Kingside Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. e5 Ng4 +C44 Scotch Game: Scotch Gambit, London Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bb4+ +C44 Scotch Game: Scotch Gambit, Sarratt Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. Ng5 +C44 Scotch Game: Sea-Cadet Mate 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Nxc3 d6 6. Bc4 Bg4 7. O-O Ne5 8. Nxe5 Bxd1 9. Bxf7+ Ke7 10. Nd5# +C44 Scotch Game: Vitzthum Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. Ng5 Nh6 6. Qh5 +C45 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 +C45 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 Bb4+ 6. Bd2 +C45 Scotch Game: Alekhine Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 5. e5 +C45 Scotch Game: Blumenfeld Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. Nb5 +C45 Scotch Game: Braune Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Be3 +C45 Scotch Game: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 +C45 Scotch Game: Classical Variation, Blackburne Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Qd2 +C45 Scotch Game: Classical Variation, Intermezzo Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Nxc6 Qf6 +C45 Scotch Game: Classical Variation, Millennium Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Qg6 +C45 Scotch Game: Fraser Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nf3 +C45 Scotch Game: Ghulam-Kassim Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nxd4 5. Qxd4 d6 6. Bd3 +C45 Scotch Game: Gottschall Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Qd2 d5 8. Nb5 Bxe3 9. Qxe3 O-O 10. Nxc7 Rb8 11. Nxd5 Nxd5 12. exd5 Nb4 +C45 Scotch Game: Horwitz Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 +C45 Scotch Game: Horwitz Attack, Blackburne Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 Bb4+ 6. Bd2 Qxe4+ 7. Be2 Kd8 8. O-O Bxd2 9. Qxd2 +C45 Scotch Game: Malaniuk Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bb4+ +C45 Scotch Game: Meitner Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Nc2 +C45 Scotch Game: Mieses Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 5. Nxc6 bxc6 6. e5 +C45 Scotch Game: Modern Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nc3 Bb4 +C45 Scotch Game: Paulsen Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Bb5 +C45 Scotch Game: Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nf5 +C45 Scotch Game: Paulsen, Gunsberg Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Bb5 Nd8 +C45 Scotch Game: Potter Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Nb3 +C45 Scotch Game: Romanishin Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Nb3 Bb4+ +C45 Scotch Game: Rosenthal Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 Bb4+ 6. Bd2 Qxe4+ 7. Be2 Kd8 8. O-O Bxd2 9. Nxd2 Qg6 +C45 Scotch Game: Schmidt Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 +C45 Scotch Game: Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 +C45 Scotch Game: Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nc3 +C45 Scotch Game: Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 5. Nxc6 bxc6 6. Nd2 +C46 Three Knights Opening 1. e4 e5 2. Nf3 Nc6 3. Nc3 +C46 Three Knights Opening 1. e4 e5 2. Nf3 Nc6 3. Nc3 Bb4 +C46 Three Knights Opening: Schlechter Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Bb4 4. Nd5 Nf6 +C46 Three Knights Opening: Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 g6 +C46 Three Knights Opening: Steinitz-Rosenthal Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 g6 4. d4 exd4 5. Nd5 +C46 Three Knights Opening: Winawer Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 f5 +C47 Four Knights Game 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 +C47 Four Knights Game: Glek System 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. g3 +C47 Four Knights Game: Glek System 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. g3 d5 5. exd5 Nxd5 6. Bg2 Nxc3 7. bxc3 +C47 Four Knights Game: Gunsberg Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. a3 +C47 Four Knights Game: Gunsberg Variation, Provincial Opening 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. a3 d6 5. h3 +C47 Four Knights Game: Halloween Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nxe5 +C47 Four Knights Game: Halloween Gambit, Oldtimer Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nxe5 Nxe5 5. d4 Ng6 6. e5 Ng8 7. Bc4 Bb4 8. Qf3 f5 +C47 Four Knights Game: Halloween Gambit, Plasma Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nxe5 Nxe5 5. d4 Nc6 6. d5 Ne5 7. f4 Ng6 8. e5 Ng8 9. d6 cxd6 10. exd6 Qf6 11. Nb5 Rb8 +C47 Four Knights Game: Italian Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Nc3 +C47 Four Knights Game: Italian Variation, Noa Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Nc3 Nxe4 5. Bxf7+ +C47 Four Knights Game: Naroditsky Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nd5 +C47 Four Knights Game: Scotch Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 +C47 Four Knights Game: Scotch Variation Accepted 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 +C47 Four Knights Game: Scotch Variation Accepted, Main Line 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nxd4 Bb4 6. Nxc6 bxc6 7. Bd3 d5 8. exd5 O-O 9. O-O +C47 Four Knights Game: Scotch Variation, Belgrade Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nd5 +C47 Four Knights Game: Scotch Variation, Belgrade Gambit, Modern Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nd5 Nxe4 6. Qe2 f5 +C47 Four Knights Game: Scotch Variation, Krause Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 Bb4 5. Nxe5 +C47 Four Knights Game: Scotch Variation, Krause Gambit, Leonhardt Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 Bb4 5. Nxe5 Qe7 +C47 Four Knights Game: Scotch Variation, Oxford Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 Bb4 5. d5 Nd4 +C47 Four Knights Game: Scotch Variation, Schmid Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nxd4 Nxe4 +C48 Four Knights Game: Spanish Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 +C48 Four Knights Game: Spanish Variation, Bardeleben Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bc5 5. O-O O-O 6. Nxe5 Nxe5 7. d4 Bd6 8. f4 Nc6 9. e5 Bb4 +C48 Four Knights Game: Spanish Variation, Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bc5 +C48 Four Knights Game: Spanish Variation, Ranken Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 a6 5. Bxc6 +C48 Four Knights Game: Spanish Variation, Rubinstein Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 +C48 Four Knights Game: Spanish Variation, Rubinstein Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Be2 +C48 Four Knights Game: Spanish Variation, Rubinstein Variation 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Nd4 5. Nxe5 Qe7 6. f4 +C48 Four Knights Game: Spanish Variation, Rubinstein Variation Accepted 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Nxd4 +C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Henneberger Variation 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Nd4 5. O-O +C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Marshall Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Ba4 Bc5 6. Nxe5 O-O +C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Marshall Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Nxe5 Bc5 6. O-O O-O +C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Maróczy Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Be2 Nxf3+ 6. Bxf3 Bc5 7. O-O O-O 8. d3 d6 9. Na4 Bb6 +C48 Four Knights Game: Spanish Variation, Spielmann Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 a6 5. Bxc6 dxc6 6. Nxe5 Nxe4 7. Nxe4 Qd4 8. O-O Qxe5 9. Re1 Be6 10. d4 Qd5 +C49 Four Knights Game: Spanish Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Bxc3 +C49 Four Knights Game: Spanish Variation, Alatortsev Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Qe7 7. Ne2 d5 +C49 Four Knights Game: Spanish Variation, Double Spanish 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 +C49 Four Knights Game: Spanish Variation, Double Spanish 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 +C49 Four Knights Game: Spanish Variation, Gunsberg Counterattack 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Bb4 5. O-O O-O 6. Nd5 Nxd5 7. exd5 e4 +C49 Four Knights Game: Spanish Variation, Janowski Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Bxc3 7. bxc3 d6 8. Re1 +C49 Four Knights Game: Spanish Variation, Nimzowitsch Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. Bxc6 +C49 Four Knights Game: Spanish Variation, Svenonius Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Bxc3 7. bxc3 d5 +C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 +C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Bxc3 8. bxc3 Qe7 9. Re1 Nd8 10. d4 Bg4 +C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Ne7 +C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Ne2 +C49 Four Knights Game: Spanish Variation, Symmetrical Variation, Blake Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Ne7 8. Nh4 c6 9. Bc4 d5 10. Bb3 Qd6 +C49 Four Knights Game: Spanish Variation, Symmetrical Variation, Metger Unpin 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Bxc3 8. bxc3 Qe7 +C49 Four Knights Game: Spanish Variation, Symmetrical Variation, Tarrasch Variation 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Be6 +C50 Four Knights Game: Italian Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Nc3 Nf6 +C50 Italian Game 1. e4 e5 2. Nf3 Nc6 3. Bc4 +C50 Italian Game: Anti-Fried Liver Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 h6 +C50 Italian Game: Blackburne-Kostić Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nd4 +C50 Italian Game: Classical Variation, Albin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. c3 +C50 Italian Game: Deutz Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d4 +C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 +C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. Nc3 d6 6. d3 +C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Nc3 Nf6 5. O-O O-O +C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Nc3 Nf6 5. O-O O-O 6. d3 +C50 Italian Game: Giuoco Pianissimo, Canal Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 Nf6 5. Nc3 d6 6. Bg5 +C50 Italian Game: Giuoco Pianissimo, Dubois Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 f5 5. Ng5 f4 +C50 Italian Game: Giuoco Pianissimo, Italian Four Knights Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 Nf6 5. Nc3 +C50 Italian Game: Giuoco Pianissimo, Lucchini Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 f5 +C50 Italian Game: Giuoco Pianissimo, Normal 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 Bc5 +C50 Italian Game: Giuoco Piano 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 +C50 Italian Game: Hungarian Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Be7 +C50 Italian Game: Hungarian Defense, Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Be7 4. d4 exd4 5. c3 Nf6 6. e5 Ne4 +C50 Italian Game: Jerome Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Bxf7+ +C50 Italian Game: Paris Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 d6 +C50 Italian Game: Rosentreter Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d4 +C50 Italian Game: Rousseau Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 f5 +C51 Italian Game: Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 +C51 Italian Game: Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 +C51 Italian Game: Evans Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 +C51 Italian Game: Evans Gambit Declined 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 +C51 Italian Game: Evans Gambit Declined 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. a4 +C51 Italian Game: Evans Gambit Declined, Cordel Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. Bb2 +C51 Italian Game: Evans Gambit Declined, Hicken Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Qg5 7. Qf3 Qxe5 8. Qxf7+ Kd8 9. Bb2 +C51 Italian Game: Evans Gambit Declined, Hirschbach Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Qg5 +C51 Italian Game: Evans Gambit Declined, Lange Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Nh6 +C51 Italian Game: Evans Gambit Declined, Pavlov Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Nh6 7. d4 d6 8. Bxh6 dxe5 9. Bxg7 Rg8 10. Bxf7+ Kxf7 11. Bxe5 Qg5 12. Nd2 +C51 Italian Game: Evans Gambit Declined, Showalter Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. a4 a6 6. Nc3 +C51 Italian Game: Evans Gambit Declined, Vasquez Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Qg5 7. Bxf7+ Ke7 8. Qh5 +C51 Italian Game: Evans Gambit, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Be7 +C51 Italian Game: Evans Gambit, Anderssen Variation, Cordel Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Be7 6. d4 Na5 +C51 Italian Game: Evans Gambit, Fontaine Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 b5 +C51 Italian Game: Evans Gambit, Fraser Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 10. Qa4 +C51 Italian Game: Evans Gambit, Fraser-Mortimer Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 10. Qa4 Bd7 11. Qb3 Na5 12. Bxf7+ Kf8 13. Qc2 +C51 Italian Game: Evans Gambit, Göring Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Na5 10. Bg5 +C51 Italian Game: Evans Gambit, Harding Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. cxd4 Bb4+ 8. Bd2 +C51 Italian Game: Evans Gambit, Hein Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 d5 +C51 Italian Game: Evans Gambit, Mayet Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bf8 +C51 Italian Game: Evans Gambit, McDonnell Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 +C51 Italian Game: Evans Gambit, McDonnell Defense, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 +C51 Italian Game: Evans Gambit, Morphy Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 +C51 Italian Game: Evans Gambit, Mortimer-Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 10. Qa4 Bd7 11. Qb3 Na5 12. Bxf7+ Kf8 13. Qc2 Kxf7 +C51 Italian Game: Evans Gambit, Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. d5 Na5 10. Bb2 Ne7 +C51 Italian Game: Evans Gambit, Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Na5 10. Bg5 f6 11. Be3 +C51 Italian Game: Evans Gambit, Stone-Ware Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bd6 +C51 Italian Game: Evans Gambit, Ulvestad Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. d5 Na5 10. Bb2 +C52 Italian Game: Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 +C52 Italian Game: Evans Gambit, Alapin-Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 7. d4 Bg4 +C52 Italian Game: Evans Gambit, Anderssen Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O Nf6 7. d4 exd4 +C52 Italian Game: Evans Gambit, Bronstein Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 +C52 Italian Game: Evans Gambit, Compromised Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O dxc3 +C52 Italian Game: Evans Gambit, Compromised Defense, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O dxc3 8. Qb3 Qf6 9. e5 Qg6 10. Nxc3 Nge7 11. Ba3 +C52 Italian Game: Evans Gambit, Compromised Defense, Potter Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O dxc3 8. Qb3 Qf6 9. e5 Qg6 10. Nxc3 Nge7 11. Rd1 +C52 Italian Game: Evans Gambit, Dufresne Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d3 +C52 Italian Game: Evans Gambit, Johner Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O b5 +C52 Italian Game: Evans Gambit, Laroche Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 Nf6 +C52 Italian Game: Evans Gambit, Lasker Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 7. d4 Bb6 +C52 Italian Game: Evans Gambit, Leonhardt Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 b5 +C52 Italian Game: Evans Gambit, Levenfish Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 7. Qb3 Qd7 8. dxe5 dxe5 9. O-O Bb6 10. Ba3 Na5 11. Nxe5 +C52 Italian Game: Evans Gambit, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 +C52 Italian Game: Evans Gambit, Mieses Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O Nge7 +C52 Italian Game: Evans Gambit, Pierce Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 +C52 Italian Game: Evans Gambit, Richardson Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O Nf6 7. d4 O-O 8. Nxe5 +C52 Italian Game: Evans Gambit, Sanders-Alapin Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 7. d4 Bd7 +C52 Italian Game: Evans Gambit, Slow Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O +C52 Italian Game: Evans Gambit, Sokolsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 7. Bg5 +C52 Italian Game: Evans Gambit, Tartakower Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 7. Qb3 +C52 Italian Game: Evans Gambit, Waller Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d6 8. Qb3 +C53 Italian Game: Bird's Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. b4 +C53 Italian Game: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 +C53 Italian Game: Classical Variation, Center Holding Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 +C53 Italian Game: Classical Variation, Closed Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 +C53 Italian Game: Classical Variation, Eisinger Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 6. d5 Nb8 7. d6 +C53 Italian Game: Classical Variation, La Bourdonnais Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 d6 5. d4 exd4 6. cxd4 Bb6 +C53 Italian Game: Classical Variation, Mestel Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 6. Bg5 +C53 Italian Game: Classical Variation, Tarrasch Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 6. O-O d6 7. a4 a6 8. h3 Nf6 9. Re1 +C54 Italian Game: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 +C54 Italian Game: Classical Variation, Center Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 +C54 Italian Game: Classical Variation, Ghulam-Kassim Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 Ne4 7. Bd5 Nxf2 8. Kxf2 dxc3+ 9. Kg3 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. Nbd2 O-O 7. O-O +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 h6 6. c3 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a5 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 Bb6 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 O-O +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. a4 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. a4 Ba7 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. a4 O-O +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. Re1 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. Re1 Ba7 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 h6 7. Re1 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 h6 7. Nbd2 +C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 O-O 6. c3 d5 +C54 Italian Game: Classical Variation, Giuoco Pianissimo, Albin Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. b4 +C54 Italian Game: Classical Variation, Giuoco Pianissimo, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. O-O O-O 7. Re1 a6 8. Bb3 Ba7 9. h3 +C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a4 a5 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. O-O O-O 7. a4 a5 +C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a5 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 a5 6. c3 +C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a6 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 a6 +C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a6 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. Nbd2 a6 +C54 Italian Game: Classical Variation, Giuoco Pianissimo, with h6 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 h6 +C54 Italian Game: Classical Variation, Greco Gambit, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 d5 7. Bb5 Ne4 8. cxd4 Bb4+ +C54 Italian Game: Classical Variation, Greco Gambit, Dubov Italian 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. b4 +C54 Italian Game: Classical Variation, Greco Gambit, Greco Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Nxc3 +C54 Italian Game: Classical Variation, Greco Gambit, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 +C54 Italian Game: Classical Variation, Greco Gambit, Modern Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 +C54 Italian Game: Classical Variation, Greco Gambit, Modern Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 d5 +C54 Italian Game: Classical Variation, Greco Gambit, Moeller-Bayonet Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. d5 Bf6 10. Re1 Ne7 11. Rxe4 d6 12. g4 +C54 Italian Game: Classical Variation, Greco Gambit, Moeller-Therkatz Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. d5 +C54 Italian Game: Classical Variation, Greco Gambit, Traditional Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 +C54 Italian Game: Classical Variation, with d5 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d5 +C54 Italian Game: Giuoco Piano, Aitken Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Nxc3 9. bxc3 Bxc3 10. Ba3 +C54 Italian Game: Giuoco Piano, Bernstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Nxc3 9. bxc3 Bxc3 10. Qb3 d5 +C54 Italian Game: Giuoco Piano, Cracow Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Kf1 +C54 Italian Game: Giuoco Piano, Greco's Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 +C54 Italian Game: Giuoco Piano, Holzhausen Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. d4 Bxd4 6. Nxd4 Nxd4 7. Bg5 d6 8. f4 Qe7 9. fxe5 dxe5 10. Nc3 +C54 Italian Game: Giuoco Piano, Krause Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Bd2 Nxe4 8. Bxb4 Nxb4 9. Bxf7+ Kxf7 10. Qb3+ d5 11. Ne5+ Kf6 12. f3 +C54 Italian Game: Giuoco Piano, Rosentreter Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. d4 Bxd4 6. Nxd4 Nxd4 7. Bg5 h6 8. Bh4 g5 9. f4 +C54 Italian Game: Giuoco Piano, Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. bxc3 d5 10. Ba3 +C54 Italian Game: Giuoco Piano, Therkatz-Herzog Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. d5 Bf6 10. Re1 Ne7 11. Rxe4 d6 12. Bg5 Bxg5 13. Nxg5 O-O 14. Nxh7 +C55 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 +C55 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. d4 Bxd4 6. Nxd4 Nxd4 7. Bg5 d6 +C55 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Nc3 Nxe4 5. Nxe4 d5 +C55 Italian Game: Two Knights Defense, Modern Bishop's Opening 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 +C55 Italian Game: Two Knights Defense, Modern Bishop's Opening 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 Be7 +C55 Italian Game: Two Knights Defense, Modern Bishop's Opening 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 h6 5. O-O d6 +C56 Italian Game: Scotch Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O +C56 Italian Game: Scotch Gambit, Anderssen Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 6. Re1 d5 7. Bxd5 Qxd5 8. Nc3 +C56 Italian Game: Scotch Gambit, Anderssen Attack, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 6. Re1 d5 7. Bxd5 Qxd5 8. Nc3 Qa5 9. Nxe4 Be6 10. Bd2 Qd5 11. Bg5 +C56 Italian Game: Scotch Gambit, Canal Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Nxe4 6. Re1 d5 7. Nc3 +C56 Italian Game: Scotch Gambit, Double Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 +C56 Italian Game: Scotch Gambit, Janowski Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O d6 +C56 Italian Game: Scotch Gambit, Max Lange Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 +C56 Italian Game: Scotch Gambit, Max Lange Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. e5 d5 6. Bb5 Ne4 +C56 Italian Game: Scotch Gambit, Max Lange Attack Accepted 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d4 exd4 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. fxg7 +C56 Italian Game: Scotch Gambit, Max Lange Attack, Long Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 Qd5 10. Nc3 Qf5 11. Nce4 +C56 Italian Game: Scotch Gambit, Max Lange Attack, Spielmann Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 6. e5 Ng4 +C56 Italian Game: Scotch Gambit, Nakhmanson Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 6. Nc3 +C56 Italian Game: Scotch Gambit, Walbrodt-Baird Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. O-O +C56 Italian Game: Scotch Gambit, de Riviere Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Be7 +C56 Italian Game: Scotch Invitation Declined 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 d6 +C56 Italian Game: Two Knights Defense, Keidansky Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. e5 d5 6. Bb5 Ne4 7. Nxd4 Bc5 8. Nxc6 Bxf2+ 9. Kf1 Qh4 +C56 Italian Game: Two Knights Defense, Max Lange Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 6. e5 +C56 Italian Game: Two Knights Defense, Max Lange Attack, Berger Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Bc5 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 Qd5 10. Nc3 Qf5 11. g4 Qg6 12. Nce4 Bb6 13. f4 O-O-O +C56 Italian Game: Two Knights Defense, Max Lange Attack, Krause Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Bc5 6. e5 Ng4 7. c3 +C56 Italian Game: Two Knights Defense, Max Lange Attack, Loman Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. O-O Nf6 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 g6 +C56 Italian Game: Two Knights Defense, Max Lange Attack, Rubinstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Bc5 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 Qd5 10. Nc3 Qf5 11. Nce4 Bf8 +C56 Italian Game: Two Knights Defense, Open Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 +C56 Italian Game: Two Knights Defense, Perreux Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. Ng5 +C56 Italian Game: Two Knights Defense, Yurdansky Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Nxe4 6. Re1 d5 7. Bxd5 Qxd5 8. Nc3 Qa5 9. Nxe4 Be6 10. Bg5 h6 11. Bh4 g5 12. Nf6+ Ke7 13. b4 +C57 Italian Game: Two Knights Defense, Fegatello Attack, Leonhardt Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. Nxf7 Kxf7 7. Qf3+ Ke6 8. Nc3 Nb4 9. Qe4 c6 10. a3 Na6 11. d4 Nc7 +C57 Italian Game: Two Knights Defense, Fried Liver Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. Nxf7 +C57 Italian Game: Two Knights Defense, Fritz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nd4 +C57 Italian Game: Two Knights Defense, Fritz, Gruber Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nd4 6. c3 b5 7. Bf1 Nxd5 8. Ne4 +C57 Italian Game: Two Knights Defense, Kloss Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nb4 +C57 Italian Game: Two Knights Defense, Knight Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 +C57 Italian Game: Two Knights Defense, Knight Attack, Normal Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 +C57 Italian Game: Two Knights Defense, Lolli Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. d4 +C57 Italian Game: Two Knights Defense, Pincus Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. d4 Bb4+ +C57 Italian Game: Two Knights Defense, Ponziani-Steinitz Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Nxe4 +C57 Italian Game: Two Knights Defense, Traxler Counterattack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 +C57 Italian Game: Two Knights Defense, Traxler Counterattack, Bishop Sacrifice Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Bxf7+ +C57 Italian Game: Two Knights Defense, Traxler Counterattack, King March Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Nxf7 Bxf2+ 6. Kxf2 Nxe4+ 7. Ke3 +C57 Italian Game: Two Knights Defense, Traxler Counterattack, Knight Sacrifice Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Nxf7 +C57 Italian Game: Two Knights Defense, Traxler Variation, Trencianske-Teplice Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Bxf7+ Ke7 6. d4 +C57 Italian Game: Two Knights Defense, Ulvestad Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 b5 +C57 Italian Game: Two Knights Defense, Ulvestad Variation, Kurkin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 b5 6. Bf1 h6 7. Nxf7 +C58 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 +C58 Italian Game: Two Knights Defense, Blackburne Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 cxb5 +C58 Italian Game: Two Knights Defense, Colman Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 Rb8 +C58 Italian Game: Two Knights Defense, Maróczy Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. d3 h6 7. Nf3 e4 8. Qe2 Nxc4 9. dxc4 Be7 +C58 Italian Game: Two Knights Defense, Paoli Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 Qc7 9. Bd3 +C58 Italian Game: Two Knights Defense, Polerio Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 +C58 Italian Game: Two Knights Defense, Polerio Defense, Bishop Check Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ +C58 Italian Game: Two Knights Defense, Polerio Defense, Bogoljubow Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 +C58 Italian Game: Two Knights Defense, Polerio Defense, Kieseritzky Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. d3 +C58 Italian Game: Two Knights Defense, Polerio Defense, Yankovich Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. d3 h6 7. Nf3 e4 8. Qe2 Nxc4 9. dxc4 Bc5 10. Nfd2 +C59 Italian Game: Two Knights Defense, Knorre Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 9. Nf3 e4 10. Ne5 Bd6 11. d4 Qc7 12. Bd2 +C59 Italian Game: Two Knights Defense, Polerio Defense, Göring Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 9. Nf3 e4 10. Ne5 Qc7 +C59 Italian Game: Two Knights Defense, Polerio Defense, Suhle Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 +C59 Italian Game: Two Knights Defense, Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 9. Nh3 +C60 Ruy Lopez 1. e4 e5 2. Nf3 Nc6 3. Bb5 +C60 Ruy Lopez: Alapin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bb4 +C60 Ruy Lopez: Alapin Defense, Alapin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bb4 4. c3 Ba5 5. Bxc6 dxc6 +C60 Ruy Lopez: Brentano Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 g5 +C60 Ruy Lopez: Bulgarian Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a5 +C60 Ruy Lopez: Cozio Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nge7 +C60 Ruy Lopez: Cozio Defense, Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nge7 4. Nc3 g6 +C60 Ruy Lopez: Cozio Defense, Tartakower Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 4. d4 exd4 5. Nxd4 Bg7 6. Be3 Nge7 7. Nc3 O-O 8. Qd2 d5 +C60 Ruy Lopez: Fianchetto Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 +C60 Ruy Lopez: Fianchetto Defense, Kevitz Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 4. c3 f5 +C60 Ruy Lopez: Lucena Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Be7 +C60 Ruy Lopez: Nürnberg Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f6 +C60 Ruy Lopez: Pollock Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Na5 +C60 Ruy Lopez: Retreat Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nb8 +C60 Ruy Lopez: Rotary-Albany Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 b6 +C60 Ruy Lopez: Spanish Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d5 +C60 Ruy Lopez: Spanish Countergambit, Harding Countergambit, Fricke Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d5 4. Nxe5 Qg5 5. O-O +C60 Ruy Lopez: Spanish Countergambit, Harding Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d5 4. Nxe5 Qg5 5. Nxc6 +C60 Ruy Lopez: Vinogradov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Qe7 +C61 Ruy Lopez: Bird Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nd4 +C61 Ruy Lopez: Bird Variation, Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nd4 4. Nxd4 exd4 5. O-O Ne7 +C62 Ruy Lopez: Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 +C62 Ruy Lopez: Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 +C62 Ruy Lopez: Steinitz Defense, Center Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 exd4 5. O-O +C62 Ruy Lopez: Steinitz Defense, Nimzowitsch Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 Bd7 5. Nc3 Nf6 6. Bxc6 +C62 Ruy Lopez: Steinitz Defense, Semi-Duras Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 Bd7 5. c4 +C63 Ruy Lopez: Schliemann Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 +C63 Ruy Lopez: Schliemann Defense, Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 d5 6. Nxe5 dxe4 7. Nxc6 Qg5 +C63 Ruy Lopez: Schliemann Defense, Dyckhoff Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 +C63 Ruy Lopez: Schliemann Defense, Exchange Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Bxc6 +C63 Ruy Lopez: Schliemann Defense, Jaenisch Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. exf5 +C63 Ruy Lopez: Schliemann Defense, Kostić Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 Be7 +C63 Ruy Lopez: Schliemann Defense, Möhring Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 d5 6. Nxe5 dxe4 7. Nxc6 Qd5 +C63 Ruy Lopez: Schliemann Defense, Schönemann Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. d4 +C63 Ruy Lopez: Schliemann Defense, Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 Nf6 +C64 Ruy Lopez: Classical Defense, Benelux Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 5. c3 O-O 6. d4 Bb6 +C64 Ruy Lopez: Classical Defense, Boden Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 Qe7 +C64 Ruy Lopez: Classical Defense, Zaitsev Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. O-O Nd4 5. b4 +C64 Ruy Lopez: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 +C64 Ruy Lopez: Classical Variation, Central Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 +C64 Ruy Lopez: Classical Variation, Charousek Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 Bb6 +C64 Ruy Lopez: Classical Variation, Cordel Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 f5 +C64 Ruy Lopez: Classical Variation, Konikowski Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 d5 +C64 Ruy Lopez: Classical Variation, Modern Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 5. c3 O-O 6. d4 Bb6 7. Bg5 +C64 Ruy Lopez: Classical Variation, Spanish Wing Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. b4 +C65 Ruy Lopez: Berlin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 +C65 Ruy Lopez: Berlin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O +C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 +C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 d6 5. Bxc6+ +C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Duras Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 d6 5. c4 +C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Kaufmann Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 Bc5 5. Be3 +C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Mortimer Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 Ne7 5. Nxe5 c6 +C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Mortimer Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 Ne7 +C65 Ruy Lopez: Berlin Defense, Beverwijk Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 +C65 Ruy Lopez: Berlin Defense, Fishing Pole Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Ng4 +C65 Ruy Lopez: Berlin Defense, Nyholm Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d4 exd4 5. O-O +C65 Ruy Lopez: Classical Variation, Zukertort Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 5. c3 +C65 Ruy Lopez: Halloween Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. Nxe5 +C66 Ruy Lopez: Berlin Defense, Closed Bernstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 Be7 7. Bg5 +C66 Ruy Lopez: Berlin Defense, Closed Showalter Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 Be7 7. Bxc6 +C66 Ruy Lopez: Berlin Defense, Closed Wolf Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 exd4 +C66 Ruy Lopez: Berlin Defense, Hedgehog Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 Be7 +C66 Ruy Lopez: Berlin Defense, Improved Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 +C66 Ruy Lopez: Berlin Defense, Tarrasch Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 Bd7 5. Nc3 Nf6 6. O-O Be7 7. Re1 O-O +C66 Ruy Lopez: Closed Berlin Defense, Chigorin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Nd7 +C67 Ruy Lopez: Berlin Defense, Berlin Wall 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 8. Qxd8+ Kxd8 9. Nc3 Bd7 +C67 Ruy Lopez: Berlin Defense, Cordel Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nf5 +C67 Ruy Lopez: Berlin Defense, Minckwitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. dxe5 +C67 Ruy Lopez: Berlin Defense, Pillsbury Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. b3 +C67 Ruy Lopez: Berlin Defense, Rio Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 +C67 Ruy Lopez: Berlin Defense, Rio de Janeiro Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 +C67 Ruy Lopez: Berlin Defense, Rio de Janeiro Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. Nc3 O-O 10. Re1 Nc5 11. Nd4 Ne6 12. Be3 Nxd4 13. Bxd4 c5 +C67 Ruy Lopez: Berlin Defense, Rosenthal Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 a6 +C67 Ruy Lopez: Berlin Defense, Trifunovic Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 d5 +C67 Ruy Lopez: Berlin Defense, Winawer Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. Nd4 +C67 Ruy Lopez: Berlin Defense, Zukertort Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. c4 +C67 Ruy Lopez: Berlin Defense, l'Hermet Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 +C67 Ruy Lopez: Berlin Defense, l'Hermet Variation, Berlin Wall Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 8. Qxd8+ Kxd8 +C67 Ruy Lopez: Berlin Defense, l'Hermet Variation, Westerinen Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Ne4 +C67 Ruy Lopez: Open Berlin Defense, Showalter Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Ba4 +C67 Ruy Lopez: Open Berlin Defense, l'Hermet Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. dxe5 +C68 Ruy Lopez: Exchange Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 +C68 Ruy Lopez: Exchange Variation, Alekhine Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. d4 exd4 6. Qxd4 Qxd4 7. Nxd4 Bd6 +C68 Ruy Lopez: Exchange Variation, Keres Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. Nc3 +C68 Ruy Lopez: Exchange Variation, Lutikov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 bxc6 +C68 Ruy Lopez: Exchange Variation, Romanovsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. Nc3 f6 6. d3 +C68 Ruy Lopez: Exchange, Alekhine Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. d4 exd4 6. Qxd4 Qxd4 7. Nxd4 Bd7 +C69 Ruy Lopez: Exchange Variation, Alapin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O Bg4 6. h3 h5 +C69 Ruy Lopez: Exchange Variation, Bronstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O Qd6 +C69 Ruy Lopez: Exchange Variation, Gligoric Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O f6 +C69 Ruy Lopez: Exchange Variation, King's Bishop Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O Bd6 +C69 Ruy Lopez: Exchange Variation, Normal Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O +C70 Ruy Lopez: Bird's Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nd4 +C70 Ruy Lopez: Morphy Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 +C70 Ruy Lopez: Morphy Defense, Alapin's Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bb4 +C70 Ruy Lopez: Morphy Defense, Caro Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 +C70 Ruy Lopez: Morphy Defense, Classical Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 +C70 Ruy Lopez: Morphy Defense, Cozio Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nge7 +C70 Ruy Lopez: Morphy Defense, Fianchetto Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 g6 +C70 Ruy Lopez: Morphy Defense, Graz Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 Bc5 +C70 Ruy Lopez: Morphy Defense, Norwegian Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 Na5 +C70 Ruy Lopez: Morphy Defense, Norwegian Variation, Nightingale Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 Na5 6. Bxf7+ +C70 Ruy Lopez: Morphy Defense, Schliemann Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 f5 +C70 Ruy Lopez: Morphy Defense, Schliemann Defense Deferred, Jaenisch Gambit Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 f5 5. exf5 +C71 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 +C71 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. Nc3 +C71 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c4 +C71 Ruy Lopez: Noah's Ark Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 d6 6. d4 Nxd4 7. Nxd4 exd4 8. Qxd4 c5 +C72 Ruy Lopez: Closed, Kecskemet Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. O-O Bd7 6. c3 Nf6 7. d4 Be7 8. Nbd2 O-O 9. Re1 Be8 +C72 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. O-O +C73 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. Bxc6+ bxc6 6. d4 +C73 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. Bxc6+ bxc6 6. d4 f6 +C74 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 +C74 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 f5 6. exf5 Bxf5 7. O-O +C74 Ruy Lopez: Morphy Defense, Modern Steinitz Defense, Siesta Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 f5 +C75 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 Bd7 +C75 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 Bd7 6. d4 Nge7 +C76 Ruy Lopez: Morphy Defense, Modern Steinitz Defense, Fianchetto Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 4. c3 a6 5. Ba4 d6 6. d4 Bd7 +C77 Ruy Lopez: Morphy Defense, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. d3 +C77 Ruy Lopez: Morphy Defense, Bayreuth Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Bxc6 +C77 Ruy Lopez: Morphy Defense, Duras Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. d3 d6 6. c4 +C77 Ruy Lopez: Morphy Defense, Jaffe Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. c3 +C77 Ruy Lopez: Morphy Defense, Mackenzie Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. d4 +C77 Ruy Lopez: Morphy Defense, Tarrasch Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Nc3 +C77 Ruy Lopez: Morphy Defense, Wormald Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Qe2 +C77 Ruy Lopez: Wormald Attack, Grünfeld Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Qe2 b5 6. Bb3 Be7 7. d4 d6 8. c3 Bg4 +C78 Ruy Lopez: Brix Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O g6 +C78 Ruy Lopez: Central Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d5 +C78 Ruy Lopez: Morphy Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O +C78 Ruy Lopez: Morphy Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 d6 +C78 Ruy Lopez: Morphy Defense, Arkhangelsk Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 Bb7 +C78 Ruy Lopez: Morphy Defense, Møller Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Bc5 +C78 Ruy Lopez: Morphy Defense, Neo-Arkhangelsk Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 Bc5 +C78 Ruy Lopez: Morphy Defense, Wing Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 Be7 7. a4 +C78 Ruy Lopez: Rabinovich Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 d6 7. Ng5 d5 8. exd5 Nd4 9. Re1 Bc5 10. Rxe5+ Kf8 +C79 Ruy Lopez: Morphy Defense, Steinitz Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 +C79 Ruy Lopez: Morphy Defense, Steinitz Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 6. Bxc6+ bxc6 7. d4 Nxe4 +C79 Ruy Lopez: Steinitz Defense Deferred, Boleslavsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 6. Bxc6+ bxc6 7. d4 Nxe4 8. Re1 f5 9. dxe5 d5 10. Nc3 +C79 Ruy Lopez: Steinitz Defense Deferred, Lipnitsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 6. Bxc6+ bxc6 7. d4 Bg4 +C80 Ruy Lopez: Morphy Defense, Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. Qe2 +C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 +C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 +C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 +C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 +C80 Ruy Lopez: Open, Berger Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. a4 Nxd4 9. Nxd4 exd4 10. Nc3 +C80 Ruy Lopez: Open, Bernstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 +C80 Ruy Lopez: Open, Bernstein Variation, Luther Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 Bc5 10. Qe1 +C80 Ruy Lopez: Open, Friess Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Nxe5 +C80 Ruy Lopez: Open, Harksen Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. c4 +C80 Ruy Lopez: Open, Karpov Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 Nc5 10. c3 d4 11. Ng5 +C80 Ruy Lopez: Open, Knorre Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. Nc3 +C80 Ruy Lopez: Open, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 +C80 Ruy Lopez: Open, Richter Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. d5 +C80 Ruy Lopez: Open, Riga Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 exd4 +C80 Ruy Lopez: Open, Schlechter Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. a4 Nxd4 +C80 Ruy Lopez: Open, Skipworth Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. Re1 d5 +C80 Ruy Lopez: Open, Zukertort Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Ne7 +C81 Ruy Lopez: Open, Howell Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Qe2 +C81 Ruy Lopez: Open, Howell Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Qe2 Be7 10. c4 +C81 Ruy Lopez: Open, Howell Attack, Ekstrom Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Qe2 Be7 10. Rd1 O-O 11. c4 bxc4 12. Bxc4 Qd7 +C82 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 +C82 Ruy Lopez: Open, Berlin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Nc5 +C82 Ruy Lopez: Open, Dilworth Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Nbd2 O-O 11. Bc2 Nxf2 +C82 Ruy Lopez: Open, Italian Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 +C82 Ruy Lopez: Open, Motzko Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Qd3 +C82 Ruy Lopez: Open, Motzko Attack, Nenarokov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Qd3 Ne7 +C82 Ruy Lopez: Open, St. Petersburg Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Nbd2 +C83 Ruy Lopez: Open, Breslau Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 10. Re1 O-O 11. Nd4 Nxe5 +C83 Ruy Lopez: Open, Classical Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 +C83 Ruy Lopez: Open, Classical Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 Nc5 10. c3 Be7 +C83 Ruy Lopez: Open, Classical Defense, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 Be7 7. Re1 b5 8. Bb3 d5 9. dxe5 Be6 10. c3 +C83 Ruy Lopez: Open, Malkin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 10. Nbd2 O-O 11. Qe2 +C83 Ruy Lopez: Open, Tarrasch Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 10. Re1 O-O 11. Nd4 Qd7 12. Nxe6 fxe6 13. Rxe4 +C84 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 +C84 Ruy Lopez: Closed, Basque Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d4 exd4 7. e5 Ne4 8. c3 +C84 Ruy Lopez: Closed, Center Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d4 +C84 Ruy Lopez: Closed, Center Attack, Basque Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d4 exd4 7. e5 Ne4 8. c3 dxc3 +C84 Ruy Lopez: Closed, Martinez Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d3 +C84 Ruy Lopez: Closed, Morphy Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Nc3 +C85 Ruy Lopez: Closed, Delayed Exchange 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Bxc6 +C86 Ruy Lopez: Closed, Worrall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Qe2 +C86 Ruy Lopez: Closed, Worrall Attack, Castling Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Qe2 b5 7. Bb3 O-O +C86 Ruy Lopez: Closed, Worrall Attack, Castling Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Qe2 Be7 6. O-O b5 7. Bb3 O-O 8. c3 d5 9. d3 +C86 Ruy Lopez: Closed, Worrall Attack, Delayed Castling Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Qe2 b5 7. Bb3 d6 +C87 Ruy Lopez: Closed, Averbakh Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 d6 +C88 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 +C88 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O +C88 Ruy Lopez: Closed, Alekhine Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 Na5 9. Bc2 c5 10. d4 Qc7 11. Nbd2 O-O 12. Nf1 Bg4 13. Ne3 Bxf3 14. Qxf3 +C88 Ruy Lopez: Closed, Anti-Marshall 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. a4 +C88 Ruy Lopez: Closed, Balla Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 Na5 9. Bc2 c5 10. d4 Qc7 11. a4 +C88 Ruy Lopez: Closed, Leonhardt Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 Na5 9. Bc2 c5 10. d4 Qc7 11. h3 Nc6 12. d5 Nb8 13. Nbd2 g5 +C88 Ruy Lopez: Closed, Rosen Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. d4 +C88 Ruy Lopez: Closed, Trajkovic Counterattack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 Bb7 +C88 Ruy Lopez: Noah's Ark Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. d4 Nxd4 9. Nxd4 exd4 10. Qxd4 c5 +C89 Ruy Lopez: Marshall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 +C89 Ruy Lopez: Marshall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. a4 Bb7 +C89 Ruy Lopez: Marshall Attack, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 +C89 Ruy Lopez: Marshall Attack, Main Line, Spassky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 Bd6 13. Re1 Qh4 14. g3 Qh3 15. Be3 Bg4 16. Qd3 Rae8 17. Nd2 Re6 18. a4 Qh5 +C89 Ruy Lopez: Marshall Attack, Modern Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 Bd6 13. Re1 Qh4 14. g3 Qh3 +C89 Ruy Lopez: Marshall Attack, Modern Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 +C89 Ruy Lopez: Marshall Attack, Original Marshall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 Nf6 +C89 Ruy Lopez: Marshall Attack, Re3 Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. Bxd5 cxd5 13. d4 Bd6 14. Re3 +C89 Ruy Lopez: Marshall Attack, Steiner Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 e4 +C90 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O +C90 Ruy Lopez: Closed, Lutikov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. Bc2 +C90 Ruy Lopez: Closed, Pilnik Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. d3 d6 9. c3 +C90 Ruy Lopez: Closed, Suetin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. a3 +C91 Ruy Lopez: Closed, Bogoljubow Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. d4 Bg4 +C91 Ruy Lopez: Closed, Yates Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. d4 +C91 Ruy Lopez: Closed, Yates Variation, Short Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. d4 Bg4 10. a4 +C92 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 +C92 Ruy Lopez: Closed, Flohr System 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Bb7 +C92 Ruy Lopez: Closed, Karpov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nd7 +C92 Ruy Lopez: Closed, Kholmov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Be6 +C92 Ruy Lopez: Closed, Smyslov-Breyer-Zaitsev Hybrid 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Bb7 10. d4 Re8 11. Nbd2 Bf8 12. a3 h6 +C92 Ruy Lopez: Closed, Zaitsev System 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Re8 +C93 Ruy Lopez: Closed, Smyslov Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 h6 +C94 Ruy Lopez: Closed, Breyer Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 +C94 Ruy Lopez: Closed, Breyer Defense, Quiet Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d3 +C95 Ruy Lopez: Closed, Breyer 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 +C95 Ruy Lopez: Closed, Breyer Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7 11. Nbd2 Bb7 12. Bc2 c5 +C95 Ruy Lopez: Closed, Breyer Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7 11. Nh4 +C95 Ruy Lopez: Closed, Breyer Defense, Zaitsev Hybrid 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7 +C96 Ruy Lopez: Closed, Borisenko Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Nc6 +C96 Ruy Lopez: Closed, Chigorin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 +C96 Ruy Lopez: Closed, Chigorin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 +C96 Ruy Lopez: Closed, Chigorin Defense, Gajewski Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 d5 +C96 Ruy Lopez: Closed, Keres Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Nd7 +C96 Ruy Lopez: Closed, Rossolimo Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c6 11. d4 Qc7 +C97 Ruy Lopez: Closed, Chigorin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 +C97 Ruy Lopez: Closed, Chigorin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 +C97 Ruy Lopez: Closed, Chigorin, Yugoslav System 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 Bd7 13. Nf1 Rfe8 14. Ne3 g6 +C98 Ruy Lopez: Closed, Chigorin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 Nc6 +C98 Ruy Lopez: Closed, Chigorin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 Nc6 13. dxc5 +C99 Ruy Lopez: Closed, Chigorin Defense, Panov System 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 cxd4 13. cxd4 diff --git a/crates/openings/data/d.tsv b/crates/openings/data/d.tsv new file mode 100644 index 0000000..a829bac --- /dev/null +++ b/crates/openings/data/d.tsv @@ -0,0 +1,645 @@ +eco name pgn +D00 Amazon Attack 1. d4 d5 2. Qd3 +D00 Blackmar-Diemer Gambit 1. d4 d5 2. e4 +D00 Blackmar-Diemer Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 +D00 Blackmar-Diemer Gambit Accepted 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 +D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 +D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Kloss Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. O-O O-O 8. Kh1 +D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Mad Dog Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. h4 +D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Nimzowitsch Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. Ne5 +D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Studier Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. O-O O-O 8. Qe1 +D00 Blackmar-Diemer Gambit Accepted: Euwe Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 e6 +D00 Blackmar-Diemer Gambit Accepted: Euwe Defense, Duthilleul Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 e6 6. Bd3 +D00 Blackmar-Diemer Gambit Accepted: Euwe Defense, Zilbermints Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 e6 6. Bg5 Be7 7. Bd3 Nc6 8. O-O Nxd4 9. Kh1 +D00 Blackmar-Diemer Gambit Accepted: Gunderam Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bf5 +D00 Blackmar-Diemer Gambit Accepted: Gunderam Defense, Stader Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bf5 6. Ne5 e6 7. g4 Be4 +D00 Blackmar-Diemer Gambit Accepted: Holwell Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Qd6 +D00 Blackmar-Diemer Gambit Accepted: Kaulich Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 c5 +D00 Blackmar-Diemer Gambit Accepted: Pietrowsky Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Nc6 +D00 Blackmar-Diemer Gambit Accepted: Ritter Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 b6 +D00 Blackmar-Diemer Gambit Accepted: Ryder Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Qxf3 +D00 Blackmar-Diemer Gambit Accepted: Schlutter Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Nbd7 +D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 +D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense, Ciesielski Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 6. h3 Bxf3 7. Qxf3 c6 8. Qf2 +D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense, Classical Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 6. h3 Bxf3 7. Qxf3 c6 8. Be3 +D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense, Seidel-Hall Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 6. h3 Bxf3 7. Qxf3 c6 8. g4 +D00 Blackmar-Diemer Gambit Accepted: Ziegler Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 c6 +D00 Blackmar-Diemer Gambit Declined: Brombacher Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 c5 +D00 Blackmar-Diemer Gambit Declined: Elbert Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e5 +D00 Blackmar-Diemer Gambit Declined: Gedult Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 a6 +D00 Blackmar-Diemer Gambit Declined: Lamb Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 Nc6 +D00 Blackmar-Diemer Gambit Declined: Langeheinicke Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e3 +D00 Blackmar-Diemer Gambit Declined: O'Kelly Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 c6 +D00 Blackmar-Diemer Gambit Declined: Vienna Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 Bf5 +D00 Blackmar-Diemer Gambit Declined: Weinsbach Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e6 +D00 Blackmar-Diemer Gambit Declined: Weinsbach Defense, Pfrang Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e6 5. fxe4 +D00 Blackmar-Diemer Gambit: Blackmar Gambit 1. d4 d5 2. e4 dxe4 3. f3 +D00 Blackmar-Diemer Gambit: Diemer-Rosenberg Attack 1. d4 d5 2. e4 dxe4 3. Be3 +D00 Blackmar-Diemer Gambit: Fritz Attack 1. d4 d5 2. e4 dxe4 3. Bc4 +D00 Blackmar-Diemer Gambit: Lemberger Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 e5 +D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Endgame Variation 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. dxe5 +D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Lange Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Nxe4 +D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Rasmussen Attack 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Nge2 +D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Sneiders Attack 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Qh5 +D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Soller Attack 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Be3 +D00 Blackmar-Diemer Gambit: Netherlands Variation 1. d4 d5 2. e4 dxe4 3. Nc3 f5 +D00 Blackmar-Diemer Gambit: Rasa-Studier Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Be3 +D00 Blackmar-Diemer Gambit: Reversed Albin Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 c5 +D00 Blackmar-Diemer Gambit: Zeller Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Bf5 +D00 Blackmar-Diemer Gambit: Zeller Defense, Soller Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Bf5 4. f3 Nf6 5. Bc4 +D00 Blackmar-Diemer Gambit: von Popiel Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Bg5 +D00 Blackmar-Diemer Gambit: von Popiel Gambit, Zilbermints Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Bg5 Bf5 5. Bxf6 exf6 6. g4 Bg6 7. Qe2 Bb4 8. Qb5+ +D00 Queen's Pawn Game 1. d4 d5 +D00 Queen's Pawn Game 1. d4 d5 2. e3 +D00 Queen's Pawn Game 1. d4 d5 2. e3 Nf6 +D00 Queen's Pawn Game: Accelerated London System 1. d4 d5 2. Bf4 +D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit 1. d4 d5 2. Bf4 c5 +D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit Accepted 1. d4 d5 2. Bf4 c5 3. dxc5 +D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit, Morris Countergambit 1. d4 d5 2. Bf4 c5 3. e4 +D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit, Morris Countergambit Accepted 1. d4 d5 2. Bf4 c5 3. e4 dxe4 +D00 Queen's Pawn Game: Chigorin Variation 1. d4 d5 2. Nc3 +D00 Queen's Pawn Game: Chigorin Variation 1. d4 d5 2. Nc3 e6 +D00 Queen's Pawn Game: Chigorin Variation, Alburt Defense 1. d4 d5 2. Nc3 Bf5 +D00 Queen's Pawn Game: Chigorin Variation, Anti-Veresov 1. d4 d5 2. Nc3 Bg4 +D00 Queen's Pawn Game: Chigorin Variation, Fianchetto Defense 1. d4 g6 2. Nf3 Bg7 3. Nc3 d5 +D00 Queen's Pawn Game: Chigorin Variation, Irish Gambit 1. d4 d5 2. Nc3 c5 +D00 Queen's Pawn Game: Chigorin Variation, Shaviliuk Gambit 1. d4 d5 2. Nc3 e5 +D00 Queen's Pawn Game: Chigorin Variation, Shropshire Defense 1. d4 d5 2. Nc3 h5 +D00 Queen's Pawn Game: Hübsch Gambit 1. d4 Nf6 2. Nc3 d5 3. e4 +D00 Queen's Pawn Game: Levitsky Attack 1. d4 d5 2. Bg5 +D00 Queen's Pawn Game: Levitsky Attack, Welling Variation 1. d4 d5 2. Bg5 Bg4 +D00 Queen's Pawn Game: Mason Attack 1. d4 d5 2. f4 +D00 Queen's Pawn Game: Stonewall Attack 1. d4 d5 2. e3 Nf6 3. Bd3 +D00 Queen's Pawn Game: Zurich Gambit 1. d4 d5 2. g4 +D01 Rapport-Jobava System 1. d4 d5 2. Nc3 Nf6 3. Bf4 +D01 Rapport-Jobava System 1. d4 d5 2. Nc3 Nf6 3. Bf4 e6 +D01 Rapport-Jobava System 1. d4 d5 2. Nc3 Nf6 3. Bf4 g6 +D01 Rapport-Jobava System, with e6 1. d4 d5 2. Nc3 e6 3. Bf4 +D01 Richter-Veresov Attack 1. d4 Nf6 2. Nc3 d5 3. Bg5 +D01 Richter-Veresov Attack 1. d4 Nf6 2. Nc3 d5 3. Bg5 Bf5 +D01 Richter-Veresov Attack: Boyce Defense 1. d4 Nf6 2. Nc3 d5 3. Bg5 Ne4 +D01 Richter-Veresov Attack: Malich Gambit 1. d4 Nf6 2. Nc3 d5 3. Bg5 c5 4. Bxf6 gxf6 5. e4 dxe4 6. d5 +D01 Richter-Veresov Attack: Richter Variation 1. d4 Nf6 2. Nc3 d5 3. Bg5 Bf5 4. f3 +D01 Richter-Veresov Attack: Two Knights System 1. d4 Nf6 2. Nc3 d5 3. Bg5 Nbd7 4. Nf3 +D01 Richter-Veresov Attack: Two Knights System, Grünfeld Defense 1. d4 Nf6 2. Nc3 d5 3. Bg5 Nbd7 4. Nf3 g6 +D01 Richter-Veresov Attack: Veresov Variation 1. d4 Nf6 2. Nc3 d5 3. Bg5 Bf5 4. Bxf6 +D02 London System: Poisoned Pawn Variation 1. d4 Nf6 2. Nf3 d5 3. Bf4 c5 4. e3 Qb6 5. Nc3 +D02 Queen's Gambit Declined: Baltic Defense, Pseudo-Slav 1. d4 d5 2. Nf3 Bf5 3. c4 e6 4. Nc3 c6 +D02 Queen's Pawn Game: Anti-Torre 1. Nf3 d5 2. d4 Bg4 +D02 Queen's Pawn Game: Chandler Gambit 1. d4 d5 2. Nf3 c5 3. g3 cxd4 4. Bg2 +D02 Queen's Pawn Game: Chigorin Variation 1. d4 d5 2. Nf3 Nc6 +D02 Queen's Pawn Game: Krause Variation 1. d4 d5 2. Nf3 c5 +D02 Queen's Pawn Game: Levitsky Attack, Euwe Variation, Modern Line 1. d4 d5 2. Nf3 c6 3. Bg5 h6 4. Bh4 Qb6 +D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 +D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 c5 4. e3 +D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 c5 4. e3 Nc6 5. Nbd2 +D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 c5 4. e3 Nc6 5. Nbd2 e6 6. c3 +D02 Queen's Pawn Game: London System, Pterodactyl Variation 1. d4 g6 2. Nf3 Bg7 3. Bf4 c5 4. c3 cxd4 5. cxd4 Qa5+ +D02 Queen's Pawn Game: London System, with e6 1. d4 d5 2. Nf3 e6 3. Bf4 +D02 Queen's Pawn Game: London System, with e6 1. d4 d5 2. Nf3 e6 3. Bf4 Nf6 +D02 Queen's Pawn Game: Symmetrical Variation 1. d4 d5 2. Nf3 Nf6 +D02 Queen's Pawn Game: Symmetrical Variation, Pseudo-Catalan 1. d4 d5 2. Nf3 Nf6 3. g3 +D02 Queen's Pawn Game: Symmetrical Variation, Pseudo-Catalan 1. d4 d5 2. Nf3 Nf6 3. g3 c6 4. Bg2 Bg4 +D02 Queen's Pawn Game: Symmetrical Variation, Pseudo-Catalan 1. Nf3 d5 2. g3 c6 3. Bg2 Nf6 4. O-O Bg4 5. d4 e6 +D02 Queen's Pawn Game: Zilbermints Countergambit 1. d4 d5 2. Nf3 Nf6 3. c4 b5 +D02 Queen's Pawn Game: Zukertort Variation 1. d4 d5 2. Nf3 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. Nbd2 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. Nbd2 Nc6 6. c3 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 6. Nbd2 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 6. Nbd2 Bd6 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 6. Nbd2 Be7 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nc6 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nc6 6. Bd3 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 Nbd7 5. Bd3 +D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. Nbd2 Be7 5. c3 Nbd7 6. e3 +D03 Queen's Pawn Game: Torre Attack, Gossip Variation 1. d4 d5 2. Nf3 Nf6 3. Bg5 Ne4 +D03 Queen's Pawn Game: Torre Attack, Grünfeld Variation 1. d4 d5 2. Nf3 Nf6 3. Bg5 g6 +D03 Queen's Pawn Game: Torre Attack, Grünfeld Variation 1. d4 d5 2. Nf3 Nf6 3. Bg5 g6 4. e3 +D04 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 +D04 Queen's Pawn Game: Colle System, Anti-Colle 1. d4 d5 2. Nf3 Nf6 3. e3 Bf5 +D04 Queen's Pawn Game: Colle System, Grünfeld Formation 1. d4 d5 2. Nf3 Nf6 3. e3 g6 4. Bd3 Bg7 +D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 +D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 +D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 +D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 c5 5. Bb2 Nc6 +D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 c5 5. Bb2 Nc6 6. Bd3 +D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 c5 5. Bb2 Nc6 6. Nbd2 +D05 Queen's Pawn Game: Colle System 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. b3 Be7 7. Bb2 O-O 8. Nbd2 d5 +D05 Queen's Pawn Game: Colle System, Traditional Colle 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. c3 +D05 Queen's Pawn Game: Zukertort Variation 1. d4 d5 2. Nf3 c5 3. e3 Nf6 4. Nbd2 e6 5. b3 +D05 Rubinstein Opening 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. b3 +D05 Rubinstein Opening: Bogoljubow Defense 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. b3 Nc6 6. O-O Bd6 7. Bb2 O-O +D05 Rubinstein Opening: Classical Defense 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. b3 Nc6 6. O-O Be7 7. Bb2 O-O +D05 Rubinstein Opening: Semi-Slav Defense 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 Bd6 5. O-O O-O 6. b3 Nbd7 7. Bb2 +D05 Rubinstein Opening: Semi-Slav Defense 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 Bd6 5. O-O O-O 6. b3 Nbd7 7. Bb2 c6 +D05 Rubinstein Opening: Semi-Slav Defense 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 Bd6 5. O-O O-O 6. b3 Nbd7 7. Bb2 c6 8. Nbd2 +D06 Queen's Gambit 1. d4 d5 2. c4 +D06 Queen's Gambit Declined: Austrian Attack, Salvio Countergambit 1. d4 d5 2. c4 c5 3. dxc5 d4 +D06 Queen's Gambit Declined: Austrian Defense 1. d4 d5 2. c4 c5 +D06 Queen's Gambit Declined: Austrian Defense, Gusev Countergambit 1. d4 d5 2. c4 c5 3. cxd5 Nf6 +D06 Queen's Gambit Declined: Austrian Defense, Haberditz Variation 1. d4 d5 2. c4 c5 3. cxd5 Nf6 4. e4 Nxe4 5. dxc5 Qa5+ +D06 Queen's Gambit Declined: Baltic Defense 1. d4 d5 2. c4 Bf5 +D06 Queen's Gambit Declined: Baltic Defense, Argentinian Gambit 1. d4 d5 2. c4 Bf5 3. cxd5 Bxb1 4. Qa4+ c6 5. dxc6 Nxc6 +D06 Queen's Gambit Declined: Baltic Defense, Pseudo-Chigorin 1. d4 d5 2. c4 Bf5 3. Nc3 e6 4. Nf3 Nc6 +D06 Queen's Gambit Declined: Baltic Defense, Queen Attack 1. d4 d5 2. c4 Bf5 3. Qb3 +D06 Queen's Gambit Declined: Baltic Defense, Queen Attack Deferred 1. d4 d5 2. c4 Bf5 3. Nc3 e6 4. Qb3 +D06 Queen's Gambit Declined: Marshall Defense 1. d4 d5 2. c4 Nf6 +D06 Queen's Gambit Declined: Marshall Defense, Tan Gambit 1. d4 d5 2. c4 Nf6 3. cxd5 c6 +D06 Queen's Gambit Declined: Zilbermints Gambit 1. d4 d5 2. c4 b5 +D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 +D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 +D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 dxc4 +D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 e6 4. Nf3 Nf6 +D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 e6 4. Nf3 Nf6 5. a3 +D07 Queen's Gambit Declined: Chigorin Defense, Exchange Variation 1. d4 d5 2. c4 Nc6 3. cxd5 Qxd5 +D07 Queen's Gambit Declined: Chigorin Defense, Exchange Variation, Costa's Line 1. d4 d5 2. c4 Nc6 3. cxd5 Qxd5 4. e3 e5 5. Nc3 Bb4 6. Bd2 Bxc3 7. Bxc3 exd4 8. Ne2 +D07 Queen's Gambit Declined: Chigorin Defense, Janowski Variation 1. d4 d5 2. c4 Nc6 3. Nc3 dxc4 4. Nf3 +D07 Queen's Gambit Declined: Chigorin Defense, Lazard Gambit 1. d4 d5 2. c4 Nc6 3. Nf3 e5 +D07 Queen's Gambit Declined: Chigorin Defense, Main Line 1. d4 d5 2. c4 Nc6 3. Nf3 Bg4 +D07 Queen's Gambit Declined: Chigorin Defense, Main Line, Alekhine Variation 1. d4 d5 2. c4 Nc6 3. Nf3 Bg4 4. Qa4 +D07 Queen's Gambit Declined: Chigorin Defense, Modern Gambit 1. d4 d5 2. c4 Nc6 3. Nc3 dxc4 4. Nf3 Nf6 +D07 Queen's Gambit Declined: Chigorin Defense, Tartakower Gambit 1. d4 d5 2. c4 Nc6 3. Nc3 e5 +D08 Queen's Gambit Declined: Albin Countergambit 1. d4 d5 2. c4 e5 +D08 Queen's Gambit Declined: Albin Countergambit, Balogh Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 Qe7 +D08 Queen's Gambit Declined: Albin Countergambit, Janowski Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 f6 +D08 Queen's Gambit Declined: Albin Countergambit, Krenosz Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 Bg4 6. h3 Bxf3 7. Nxf3 Bb4+ 8. Bd2 Qe7 +D08 Queen's Gambit Declined: Albin Countergambit, Lasker Trap 1. d4 d5 2. c4 e5 3. dxe5 d4 4. e3 Bb4+ 5. Bd2 dxe3 +D08 Queen's Gambit Declined: Albin Countergambit, Modern Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 +D08 Queen's Gambit Declined: Albin Countergambit, Normal Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 +D08 Queen's Gambit Declined: Albin Countergambit, Spassky Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. e4 +D08 Queen's Gambit Declined: Albin Countergambit, Tartakower Defense 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 c5 +D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 +D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation, Be6 Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 Be6 +D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation, Bf5 Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 Bf5 +D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation, Bg4 Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 Bg4 +D10 Slav Defense 1. d4 d5 2. c4 c6 +D10 Slav Defense 1. d4 d5 2. c4 c6 3. Nc3 +D10 Slav Defense 1. d4 d5 2. c4 c6 3. Nc3 dxc4 +D10 Slav Defense: Diemer Gambit 1. d4 d5 2. c4 c6 3. e4 +D10 Slav Defense: Exchange Variation 1. d4 d5 2. c4 c6 3. cxd5 +D10 Slav Defense: Exchange Variation, Boor Attack 1. d4 d5 2. c4 c6 3. cxd5 cxd5 4. Nc3 Nf6 5. f3 +D10 Slav Defense: Slav Gambit, Alekhine Attack 1. d4 d5 2. c4 c6 3. Nc3 dxc4 4. e4 +D10 Slav Defense: Winawer Countergambit 1. d4 d5 2. c4 c6 3. Nc3 e5 +D10 Slav Defense: Winawer Countergambit, Anti-Winawer Gambit 1. d4 d5 2. c4 c6 3. Nc3 e5 4. e4 +D11 Slav Defense: Bonet Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Bg5 +D11 Slav Defense: Breyer Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nbd2 +D11 Slav Defense: Modern Line 1. d4 d5 2. c4 c6 3. Nf3 +D11 Slav Defense: Modern Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. g3 dxc4 5. Bg2 g6 +D11 Slav Defense: Modern Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. g3 Bg4 5. Bg2 e6 6. O-O +D11 Slav Defense: Modern Line 1. d4 d5 2. Nf3 Nf6 3. g3 c6 4. Bg2 Bg4 5. O-O Nbd7 6. c4 +D11 Slav Defense: Quiet Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 +D11 Slav Defense: Quiet Variation, Pin Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bg4 +D12 Slav Defense: Quiet Variation, Amsterdam Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. cxd5 cxd5 6. Nc3 e6 7. Ne5 Nfd7 +D12 Slav Defense: Quiet Variation, Landau Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. cxd5 cxd5 6. Qb3 Qc8 7. Bd2 e6 8. Na3 +D12 Slav Defense: Quiet Variation, Schallopp Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 +D12 Slav Defense: Quiet Variation, Schallopp Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. Nc3 e6 +D13 Slav Defense: Exchange Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. cxd5 cxd5 +D13 Slav Defense: Exchange Variation, Schallopp Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. cxd5 cxd5 6. Nc3 +D14 Slav Defense: Exchange Variation, Symmetrical Line 1. d4 d5 2. c4 c6 3. cxd5 cxd5 4. Nc3 Nf6 5. Nf3 Nc6 6. Bf4 Bf5 +D14 Slav Defense: Exchange Variation, Trifunovic Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. cxd5 cxd5 5. Nc3 Nc6 6. Bf4 Bf5 7. e3 e6 8. Qb3 Bb4 +D15 Slav Defense: Alekhine Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. e3 +D15 Slav Defense: Chebanenko Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 a6 +D15 Slav Defense: Chebanenko Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 a6 5. e3 Bf5 +D15 Slav Defense: Chebanenko Variation, Advance System 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 a6 5. c5 +D15 Slav Defense: Geller Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. e4 +D15 Slav Defense: Geller Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. e4 b5 6. e5 +D15 Slav Defense: Schlechter Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 g6 +D15 Slav Defense: Süchting Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 Qb6 +D15 Slav Defense: Three Knights Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 +D15 Slav Defense: Two Knights Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 +D16 Slav Defense: Alapin Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 +D16 Slav Defense: Smyslov Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Na6 +D16 Slav Defense: Soultanbeieff Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 e6 +D16 Slav Defense: Steiner Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bg4 +D17 Slav Defense: Czech Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 +D17 Slav Defense: Czech Variation, Bled Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Nh4 +D17 Slav Defense: Czech Variation, Carlsbad Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 Nbd7 7. Nxc4 Qc7 8. g3 e5 +D17 Slav Defense: Czech Variation, Carlsbad Variation, Morozevich Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 Nbd7 7. Nxc4 Qc7 8. g3 e5 9. dxe5 Nxe5 10. Bf4 Nfd7 11. Bg2 g5 +D17 Slav Defense: Czech Variation, Krause Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 +D17 Slav Defense: Czech Variation, Krause Attack, Fazekas Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 Na6 7. e4 +D17 Slav Defense: Czech Variation, Wiesbaden Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 e6 +D17 Slav Defense: Czech Variation, Wiesbaden Variation, Sharp Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 e6 7. f3 Bb4 8. e4 +D18 Slav Defense: Czech Variation, Classical System 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 +D18 Slav Defense: Czech Variation, Lasker Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 Na6 +D19 Slav Defense: Czech Variation, Classical System, Main Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O O-O 9. Qe2 +D19 Slav Defense: Czech Variation, Dutch Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O +D19 Slav Defense: Czech Variation, Dutch Variation, Sämisch Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O O-O 9. Qe2 Ne4 10. g4 +D20 Queen's Gambit Accepted 1. d4 d5 2. c4 dxc4 +D20 Queen's Gambit Accepted: Accelerated Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Qa4+ +D20 Queen's Gambit Accepted: Central Variation, Alekhine System 1. d4 d5 2. c4 dxc4 3. e4 Nf6 +D20 Queen's Gambit Accepted: Central Variation, Greco Variation 1. d4 d5 2. c4 dxc4 3. e4 b5 +D20 Queen's Gambit Accepted: Central Variation, McDonnell Defense 1. d4 d5 2. c4 dxc4 3. e4 e5 +D20 Queen's Gambit Accepted: Central Variation, McDonnell Defense, Somov Gambit 1. d4 d5 2. c4 dxc4 3. e4 e5 4. Bxc4 +D20 Queen's Gambit Accepted: Central Variation, Modern Defense 1. d4 d5 2. c4 dxc4 3. e4 Nc6 +D20 Queen's Gambit Accepted: Central Variation, Rubinstein Defense 1. d4 d5 2. c4 dxc4 3. e4 c5 +D20 Queen's Gambit Accepted: Central Variation, Rubinstein Defense, Yefimov Gambit 1. d4 d5 2. c4 dxc4 3. e4 c5 4. d5 b5 +D20 Queen's Gambit Accepted: Linares Variation 1. d4 d5 2. c4 dxc4 3. e4 c5 4. d5 Nf6 5. Nc3 b5 +D20 Queen's Gambit Accepted: Old Variation 1. d4 d5 2. c4 dxc4 3. e3 +D20 Queen's Gambit Accepted: Old Variation, Billinger Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. a3 +D20 Queen's Gambit Accepted: Old Variation, Christensen Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. Nf3 +D20 Queen's Gambit Accepted: Old Variation, Korchnoi Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. Kf1 +D20 Queen's Gambit Accepted: Old Variation, Novikov Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. Nd2 +D20 Queen's Gambit Accepted: Saduleto Variation 1. d4 d5 2. c4 dxc4 3. e4 +D20 Queen's Gambit Accepted: Schwartz Defense 1. d4 d5 2. c4 dxc4 3. e4 f5 +D21 Queen's Gambit Accepted: Alekhine Defense, Borisenko-Furman Variation 1. d4 d5 2. c4 dxc4 3. Nf3 a6 4. e4 +D21 Queen's Gambit Accepted: Godes Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nd7 +D21 Queen's Gambit Accepted: Gunsberg Defense 1. d4 d5 2. c4 dxc4 3. Nf3 c5 +D21 Queen's Gambit Accepted: Normal Variation 1. d4 d5 2. c4 dxc4 3. Nf3 +D21 Queen's Gambit Accepted: Rosenthal Variation 1. d4 d5 2. c4 dxc4 3. Nf3 e6 +D21 Queen's Gambit Accepted: Slav Gambit 1. d4 d5 2. c4 dxc4 3. Nf3 b5 +D22 Queen's Gambit Accepted: Alekhine Defense 1. d4 d5 2. c4 dxc4 3. Nf3 a6 +D22 Queen's Gambit Accepted: Alekhine Defense, Alatortsev Variation 1. d4 d5 2. c4 dxc4 3. Nf3 a6 4. e3 Bg4 5. Bxc4 e6 6. d5 +D22 Queen's Gambit Accepted: Alekhine Defense, Haberditz Variation 1. d4 d5 2. c4 dxc4 3. Nf3 a6 4. e3 b5 +D23 Queen's Gambit Accepted 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 +D23 Queen's Gambit Accepted: Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Qa4+ +D23 Queen's Gambit Accepted: Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Qa4+ c6 5. Qxc4 +D23 Queen's Gambit Accepted: Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Qa4+ c6 5. Qxc4 e6 6. Qc2 +D24 Queen's Gambit Accepted 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. e4 +D24 Queen's Gambit Accepted 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. Bg5 +D24 Queen's Gambit Accepted: Bogoljubow Defense 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Nc3 a6 5. e4 +D24 Queen's Gambit Accepted: Gunsberg Defense, Prianishenmo Gambit 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Nc3 c5 5. d5 e6 6. e4 exd5 7. e5 +D24 Queen's Gambit Accepted: Showalter Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Nc3 +D25 Queen's Gambit Accepted: Janowski-Larsen Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 Bg4 +D25 Queen's Gambit Accepted: Normal Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 +D25 Queen's Gambit Accepted: Smyslov Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 g6 +D25 Queen's Gambit Accepted: Winawer Defense 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 Be6 +D26 Queen's Gambit Accepted: Classical Defense 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 +D26 Queen's Gambit Accepted: Classical Defense, Normal Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O +D26 Queen's Gambit Accepted: Classical Defense, Steinitz Variation, Development Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O Nc6 +D26 Queen's Gambit Accepted: Classical Defense, Steinitz Variation, Exchange Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O cxd4 +D26 Queen's Gambit Accepted: Classical, Furman Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. Qe2 a6 7. dxc5 Bxc5 8. O-O Nc6 9. e4 b5 10. e5 +D26 Queen's Gambit Accepted: Normal Variation, .. a6 Sideline 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 a6 6. Nc3 b5 +D26 Queen's Gambit Accepted: Normal Variation, .. a6 Sideline 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 a6 6. Nc3 b5 7. Bb3 Bb7 8. O-O +D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 +D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 Be7 6. O-O a6 +D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 Be7 6. O-O O-O +D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 Be7 6. O-O O-O 7. Nc3 +D27 Queen's Gambit Accepted: Classical Defense, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 +D27 Queen's Gambit Accepted: Classical Defense, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Nc3 +D27 Queen's Gambit Accepted: Classical Defense, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 a6 6. Nc3 b5 7. Bb3 Bb7 8. O-O c5 +D27 Queen's Gambit Accepted: Classical Defense, Rubinstein Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. a4 +D27 Queen's Gambit Accepted: Classical Defense, Rubinstein Variation 1. d4 d5 2. c4 dxc4 3. Nf3 e6 4. e3 Nf6 5. Bxc4 Be7 6. O-O O-O 7. Nc3 a6 8. a4 c5 +D27 Queen's Gambit Accepted: Classical Defense, Russian Gambit 1. d4 d5 2. c4 dxc4 3. e3 Nf6 4. Bxc4 e6 5. Nf3 c5 6. O-O a6 7. e4 +D27 Queen's Gambit Accepted: Furman Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 +D28 Queen's Gambit Accepted: Classical Defense, Alekhine System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 +D28 Queen's Gambit Accepted: Classical Defense, Alekhine System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 +D28 Queen's Gambit Accepted: Classical, Flohr Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Nc6 9. Rd1 c4 10. Bc2 Nb4 11. Nc3 Nxc2 12. Qxc2 Bb7 13. d5 Qc7 +D29 Queen's Gambit Accepted: Classical Defense, Alekhine System, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Bb7 +D29 Queen's Gambit Accepted: Classical Defense, Alekhine System, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Bb7 9. Nc3 +D29 Queen's Gambit Accepted: Classical Defense, Alekhine System, Smyslov Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Bb7 9. Rd1 Nbd7 10. Nc3 Bd6 +D30 Queen's Gambit Declined 1. d4 d5 2. c4 e6 +D30 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 c6 4. Qc2 dxc4 5. Qxc4 Nf6 6. g3 +D30 Queen's Gambit Declined: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 h6 +D30 Queen's Gambit Declined: Capablanca Variation 1. d4 Nf6 2. Nf3 e6 3. c4 d5 4. Bg5 c6 5. Nbd2 Nbd7 6. e3 +D30 Queen's Gambit Declined: Semmering Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 Nbd7 6. Bd3 c5 +D30 Queen's Gambit Declined: Spielmann Variation 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. e3 c6 5. Nbd2 g6 +D30 Queen's Gambit Declined: Stonewall Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 Ne4 6. Bd3 f5 +D30 Queen's Gambit Declined: Tarrasch Defense, Pseudo-Tarrasch 1. d4 d5 2. c4 e6 3. Nf3 c5 +D30 Queen's Gambit Declined: Tarrasch Defense, Pseudo-Tarrasch Bishop Attack 1. d4 d5 2. c4 e6 3. Nf3 c5 4. cxd5 exd5 5. Bg5 +D30 Queen's Gambit Declined: Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 +D30 Queen's Gambit Declined: Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 dxc4 5. Qa4+ c6 6. Qxc4 +D30 Queen's Gambit Declined: Vienna Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 Bb4+ +D30 Semi-Slav Defense: Quiet Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 +D30 Semi-Slav Defense: Quiet Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 Nbd7 +D31 Queen's Gambit Declined: Alapin Variation 1. d4 e6 2. c4 b6 3. Nc3 d5 +D31 Queen's Gambit Declined: Charousek Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 +D31 Queen's Gambit Declined: Charousek Variation, Miladinovic Gambit 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. e4 dxe4 5. f3 +D31 Queen's Gambit Declined: Janowski Variation 1. d4 d5 2. c4 e6 3. Nc3 a6 +D31 Queen's Gambit Declined: Queen's Knight Variation 1. d4 d5 2. c4 e6 3. Nc3 +D31 Queen's Gambit Declined: Semi-Slav, Abrahams Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. a4 Bb4 6. e3 b5 7. Bd2 a5 +D31 Queen's Gambit Declined: Semi-Slav, Junge Variation 1. d4 d5 2. c4 e6 3. Nf3 c6 4. Nc3 dxc4 5. a4 Bb4 6. e3 b5 7. Bd2 Qb6 +D31 Queen's Gambit Declined: Semi-Slav, Koomen Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. e3 b5 6. a4 Bb4 7. Bd2 Qe7 +D31 Semi-Slav Defense: Accelerated Move Order 1. d4 d5 2. c4 e6 3. Nc3 c6 +D31 Semi-Slav Defense: Anti-Noteboom, Stonewall Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 f5 +D31 Semi-Slav Defense: Anti-Noteboom, Stonewall Variation, Portisch Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 f5 5. g4 +D31 Semi-Slav Defense: Gunderam Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. f3 +D31 Semi-Slav Defense: Marshall Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 +D31 Semi-Slav Defense: Marshall Gambit, Forgotten Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. Nxe4 Bb4+ 6. Nc3 +D31 Semi-Slav Defense: Marshall Gambit, Main Line 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. Nxe4 Bb4+ 6. Bd2 +D31 Semi-Slav Defense: Marshall Gambit, Tolush Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. Nxe4 Bb4+ 6. Bd2 Qxd4 7. Bxb4 Qxe4+ 8. Be2 c5 9. Bxc5 Qxg2 +D31 Semi-Slav Defense: Noteboom Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 +D31 Semi-Slav Defense: Noteboom Variation, Abrahams Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. a4 Bb4 6. e3 Bxc3+ 7. bxc3 b5 8. axb5 cxb5 +D31 Semi-Slav Defense: Noteboom Variation, Anti-Noteboom Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. g3 +D31 Semi-Slav Defense: Noteboom Variation, Anti-Noteboom Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. Bg5 +D31 Semi-Slav Defense: Noteboom Variation, Anti-Noteboom Variation, Belyavsky Line 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. Bg5 f6 +D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 +D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. Bg5 Be7 +D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. Bg5 Be7 7. Bxe7 Ngxe7 +D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 c5 5. cxd5 exd5 6. Nc3 a6 7. Be2 Nc6 +D32 Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 +D32 Tarrasch Defense: Grünfeld Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. dxc5 d4 7. Na4 b5 +D32 Tarrasch Defense: Marshall Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. e4 +D32 Tarrasch Defense: Schara Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 cxd4 +D32 Tarrasch Defense: Symmetrical Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. e3 Nf6 5. Nf3 Nc6 +D32 Tarrasch Defense: Symmetrical Variation 1. c4 c5 2. Nf3 Nc6 3. Nc3 Nf6 4. e3 e6 5. d4 d5 6. cxd5 exd5 +D32 Tarrasch Defense: Tarrasch Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. dxc5 d4 6. Na4 b5 +D32 Tarrasch Defense: Two Knights Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 +D32 Tarrasch Defense: von Hennig Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 cxd4 5. Qxd4 Nc6 6. Qd1 exd5 7. Qxd5 Be6 +D33 Tarrasch Defense: Dubov Tarrasch 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 cxd4 8. Nxd4 Bc5 +D33 Tarrasch Defense: Prague Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 +D33 Tarrasch Defense: Rubinstein System 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 +D33 Tarrasch Defense: Swedish Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 c4 +D33 Tarrasch Defense: Swedish Variation, Central Break 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 c4 7. e4 +D33 Tarrasch Defense: Wagner Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Bg4 +D34 Queen's Gambit Declined: Tarrasch Defense, Stoltz Variation 1. d4 d5 2. c4 e6 3. Nf3 c5 4. cxd5 exd5 5. g3 Nc6 6. Bg2 Nf6 7. O-O Be7 8. Nc3 O-O 9. Bg5 Be6 10. Rc1 b6 +D34 Tarrasch Defense: Classical Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O +D34 Tarrasch Defense: Classical Variation, Advance Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 c4 +D34 Tarrasch Defense: Classical Variation, Bogoljubow Variation 1. d4 Nf6 2. c4 e6 3. Nc3 c5 4. Nf3 d5 5. cxd5 exd5 6. g3 Nc6 7. Bg2 Be7 8. O-O O-O 9. Bg5 Be6 10. Rc1 c4 +D34 Tarrasch Defense: Classical Variation, Carlsbad Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 +D34 Tarrasch Defense: Classical Variation, Chandler Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 h6 11. Be3 Re8 12. Rc1 Be6 +D34 Tarrasch Defense: Classical Variation, Classical Tarrasch Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. dxc5 d4 +D34 Tarrasch Defense: Classical Variation, Endgame Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 Be6 +D34 Tarrasch Defense: Classical Variation, Main Line 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 h6 11. Be3 Re8 +D34 Tarrasch Defense: Classical Variation, Petursson Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 Re8 +D34 Tarrasch Defense: Classical Variation, Réti Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. dxc5 Bxc5 10. Na4 +D34 Tarrasch Defense: Classical Variation, Spassky Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 h6 11. Be3 Bg4 +D34 Tarrasch Defense: Prague Variation, Main Line 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 +D35 Queen's Gambit Declined: Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 +D35 Queen's Gambit Declined: Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bd6 6. cxd5 exd5 +D35 Queen's Gambit Declined: Exchange Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. e3 Be7 5. cxd5 exd5 6. Bd3 O-O 7. Nf3 c6 +D35 Queen's Gambit Declined: Exchange Variation 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. cxd5 exd5 6. Bg5 Be7 7. e3 +D35 Queen's Gambit Declined: Exchange Variation, Carlsen Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 Be7 6. e3 h6 7. Bh4 Bg4 +D35 Queen's Gambit Declined: Exchange Variation, Chameleon Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 Be7 6. e3 O-O 7. Bd3 Nbd7 8. Qc2 Re8 9. Nge2 Nf8 10. O-O-O +D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 +D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 +D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 +D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 +D35 Queen's Gambit Declined: Exchange Variation, Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bf4 +D35 Queen's Gambit Declined: Harrwitz Attack 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bf4 +D35 Queen's Gambit Declined: Normal Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 Be7 7. e3 Nbd7 8. Bd3 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 Be7 7. e3 O-O 8. Bd3 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 Be7 7. e3 O-O 8. Bd3 h6 9. Bh4 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 8. Qc2 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 8. Bd3 O-O 9. Qc2 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 8. Bd3 Nf8 9. Qc2 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 7. Bd3 Nbd7 8. Nge2 O-O 9. O-O Re8 10. Qc2 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 7. Bd3 Nbd7 8. Nge2 O-O 9. O-O Re8 10. Qc2 Nf8 +D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 7. Bd3 Nbd7 8. Nge2 O-O 9. O-O h6 10. Bh4 Re8 11. Qc2 +D37 Queen's Gambit Declined: Barmen Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 +D37 Queen's Gambit Declined: Harrwitz Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 +D37 Queen's Gambit Declined: Harrwitz Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 c5 7. dxc5 Bxc5 8. Qc2 Nc6 9. Rd1 Qa5 10. a3 +D37 Queen's Gambit Declined: Harrwitz Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 c5 7. dxc5 Bxc5 8. Qc2 Nc6 9. a3 Qa5 10. O-O-O +D37 Queen's Gambit Declined: Harrwitz Attack, Fianchetto Defense 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bf4 O-O 6. e3 b6 +D37 Queen's Gambit Declined: Harrwitz Attack, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 c5 7. dxc5 Bxc5 +D37 Queen's Gambit Declined: Harrwitz Attack, Orthodox Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 O-O 6. e3 c6 +D37 Queen's Gambit Declined: Harrwitz Attack, Two Knights Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 Nbd7 +D37 Queen's Gambit Declined: Harrwitz Attack, Two Knights Defense, Blockade Line 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Nf3 Be7 5. Bf4 O-O 6. e3 Nbd7 7. c5 +D37 Queen's Gambit Declined: Knight Defense, Alekhine Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. Bg5 h6 6. Bh4 dxc4 +D37 Queen's Gambit Declined: Miles Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. Qc2 +D37 Queen's Gambit Declined: Three Knights Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 +D37 Queen's Gambit Declined: Three Knights Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 Be7 5. e3 O-O +D37 Queen's Gambit Declined: Three Knights, Vienna Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 dxc4 +D37 Queen's Gambit Declined: Vienna Variation, Quiet Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 dxc4 5. e3 +D38 Queen's Gambit Declined: Ragozin Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 +D38 Queen's Gambit Declined: Ragozin Defense, Alekhine Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 5. Qa4+ +D38 Queen's Gambit Declined: Westphalian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 5. Bg5 Nbd7 6. e3 c5 +D39 Queen's Gambit Declined: Ragozin Defense, Vienna Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 5. Bg5 dxc4 +D40 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 +D40 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. e3 Nc6 6. a3 cxd4 7. exd4 Bd6 +D40 Queen's Gambit Declined: Semi-Tarrasch Defense, Levenfish Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. e3 Nc6 6. Bd3 Bd6 7. O-O O-O 8. Qe2 Qe7 9. dxc5 Bxc5 10. e4 +D40 Queen's Gambit Declined: Semi-Tarrasch Defense, Pillsbury Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. Bg5 +D40 Queen's Gambit Declined: Semi-Tarrasch Defense, Symmetrical Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. e3 Nc6 6. Bd3 Bd6 7. O-O O-O +D40 Queen's Gambit Declined: Semi-Tarrasch Defense, with e3 1. d4 d5 2. c4 c5 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nc6 6. Bd3 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 4. g3 d5 5. d4 e6 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. g3 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. g3 Nc6 7. Bg2 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Endgame Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 cxd4 6. Qxd4 exd5 7. e4 dxe4 8. Qxd8+ +D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e4 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Kmoch Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 cxd4 8. cxd4 Bb4+ 9. Bd2 Bxd2+ 10. Qxd2 O-O 11. Bb5 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Pillsbury Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e3 +D41 Queen's Gambit Declined: Semi-Tarrasch Defense, San Sebastian Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 c5 7. Nf3 cxd4 8. cxd4 Bb4+ 9. Bd2 Qa5 +D42 Queen's Gambit Declined: Semi-Tarrasch Defense, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e3 Nc6 7. Bd3 +D43 Semi-Slav Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 +D43 Semi-Slav Defense: Anti-Moscow Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 h6 6. Bh4 +D43 Semi-Slav Defense: Hastings Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 h6 6. Bxf6 Qxf6 7. Qb3 +D43 Semi-Slav Defense: Moscow Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 h6 6. Bxf6 Qxf6 +D44 Semi-Slav Defense Accepted 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 +D44 Semi-Slav Defense: Botvinnik Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 +D44 Semi-Slav Defense: Botvinnik Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 +D44 Semi-Slav Defense: Botvinnik Variation, Alatortsev System 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 Nd5 +D44 Semi-Slav Defense: Botvinnik Variation, Ekstrom Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. exf6 gxh4 10. Ne5 +D44 Semi-Slav Defense: Botvinnik Variation, Lilienthal Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 hxg5 10. Bxg5 Nbd7 11. g3 +D44 Semi-Slav Defense: Botvinnik Variation, Szabo Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 hxg5 10. Bxg5 Nbd7 11. Qf3 +D45 Semi-Slav Defense: Accelerated Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 a6 +D45 Semi-Slav Defense: Main Line 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 +D45 Semi-Slav Defense: Normal Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 +D45 Semi-Slav Defense: Normal Variation 1. Nf3 d5 2. e3 Nf6 3. c4 c6 4. Nc3 e6 5. b3 Bd6 6. Bb2 O-O 7. d4 Nbd7 +D45 Semi-Slav Defense: Normal Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 Nf6 5. e3 Nbd7 6. b3 Bd6 7. Bb2 O-O 8. Be2 +D45 Semi-Slav Defense: Rubinstein System 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 Nf6 5. e3 Nbd7 6. Ne5 +D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 +D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 +D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 Bb7 +D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. e3 e6 5. Nc3 Nbd7 6. Qc2 Bd6 7. b3 +D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. e3 e6 5. Nc3 Nbd7 6. Qc2 Bd6 7. b3 O-O 8. Bb2 +D45 Semi-Slav Defense: Stoltz Variation, Center Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Qc2 Bd6 7. e4 +D45 Semi-Slav Defense: Stoltz Variation, Center Variation, Mikhalchishin Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Qc2 Bd6 7. e4 dxe4 8. Nxe4 Nxe4 9. Qxe4 e5 10. dxe5 +D45 Semi-Slav Defense: Stoltz Variation, Shabalov Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Qc2 Bd6 7. g4 +D45 Semi-Slav Defense: Stonewall Defense 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. Nc3 e6 5. e3 Ne4 6. Bd3 f5 +D46 Semi-Slav Defense: Bogoljubow Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Be7 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Bd6 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Bd6 7. Qc2 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. b3 Bd6 7. Bb2 O-O 8. Bd3 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 Bb7 8. Bd3 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 Bd6 7. b3 O-O 8. Bb2 Re8 9. Bd3 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 Bd6 7. b3 O-O 8. Bb2 Qe7 9. Bd3 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nf3 e6 4. e3 Nf6 5. Nc3 Bd6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Nbd7 9. O-O O-O 10. Qc2 +D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bd6 9. O-O Bb7 10. a3 O-O 11. Qc2 +D46 Semi-Slav Defense: Main Line 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 +D46 Semi-Slav Defense: Main Line 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 Bb7 8. Bd3 Be7 9. O-O O-O 10. Bb2 +D46 Semi-Slav Defense: Romih Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Bb4 +D47 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 +D47 Semi-Slav Defense: Meran Variation, Lundin Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 b4 +D47 Semi-Slav Defense: Meran Variation, Wade Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bb7 +D47 Semi-Slav Defense: Meran Variation, Wade Variation, Kaidanov Gambit 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bb7 9. e4 b4 10. Na4 c5 11. e5 Nd5 12. O-O cxd4 13. Nxd4 +D47 Semi-Slav Defense: Meran Variation, Wade Variation, Larsen Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bb7 9. e4 b4 10. Na4 c5 11. e5 Nd5 +D47 Semi-Slav Defense: Semi-Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 +D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 +D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 +D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 a6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 c5 9. O-O Bb7 10. Qe2 +D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 a6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 c5 9. O-O Bb7 10. Qe2 Nbd7 +D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 a6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 c5 9. a4 +D48 Semi-Slav Defense: Meran Variation, Old Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 +D48 Semi-Slav Defense: Meran Variation, Pirc Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 b4 +D48 Semi-Slav Defense: Meran Variation, Reynolds' Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. d5 +D49 Semi-Slav Defense: Meran Variation, Blumenfeld Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 +D49 Semi-Slav Defense: Meran Variation, Rabinovich Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Ng4 +D49 Semi-Slav Defense: Meran Variation, Rellstab Attack 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. Nf3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 12. Nxe5 axb5 13. O-O Qd5 14. Qe2 Ba6 15. Bg5 +D49 Semi-Slav Defense: Meran Variation, Sozin Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 +D49 Semi-Slav Defense: Meran Variation, Sozin Variation 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 12. Nxe5 axb5 13. O-O +D49 Semi-Slav Defense: Meran Variation, Stahlberg Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 12. Nxe5 axb5 13. Qf3 +D50 Queen's Gambit Declined: Been-Koomen Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 +D50 Queen's Gambit Declined: Modern Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 +D50 Queen's Gambit Declined: Pseudo-Tarrasch Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. cxd5 +D50 Queen's Gambit Declined: Pseudo-Tarrasch Variation, Canal Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. cxd5 Qb6 +D50 Queen's Gambit Declined: Pseudo-Tarrasch Variation, Primitive Pillsbury Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. Nf3 cxd4 6. Qxd4 +D50 Queen's Gambit Declined: Semi-Tarrasch Defense, Krause Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. Nf3 cxd4 6. Nxd4 e5 7. Ndb5 a6 8. Qa4 +D51 Queen's Gambit Declined: Alekhine Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. Nf3 c6 6. e4 +D51 Queen's Gambit Declined: Capablanca Variation, Anti-Cambridge Springs Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 6. a3 +D51 Queen's Gambit Declined: Manhattan Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 Bb4 +D51 Queen's Gambit Declined: Modern Variation, Knight Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 +D51 Queen's Gambit Declined: Modern Variation, Knight Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 +D51 Queen's Gambit Declined: Modern Variation, Knight Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 +D51 Queen's Gambit Declined: Rochlin Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. Nf3 c6 6. Rc1 Qa5 7. Bd2 +D52 Queen's Gambit Declined 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 +D52 Queen's Gambit Declined: Cambridge Springs Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 +D52 Queen's Gambit Declined: Cambridge Springs Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. cxd5 +D52 Queen's Gambit Declined: Cambridge Springs Defense, Argentine Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 6. Nf3 Qa5 7. Nd2 Bb4 8. Qc2 O-O 9. Bh4 +D52 Queen's Gambit Declined: Cambridge Springs Defense, Bogoljubow Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. Nd2 Bb4 8. Qc2 +D52 Queen's Gambit Declined: Cambridge Springs Defense, Capablanca Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 6. Nf3 Qa5 7. Bxf6 +D52 Queen's Gambit Declined: Cambridge Springs Defense, Rubinstein Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. Nd2 dxc4 +D52 Queen's Gambit Declined: Cambridge Springs Defense, Yugoslav Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. cxd5 Nxd5 +D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 +D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. Nf3 +D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. Nf3 c6 6. e3 dxc4 7. Bxc4 +D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. Bg5 Be7 +D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. Bg5 Be7 6. e4 +D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. Bg5 Be7 6. e3 O-O +D53 Queen's Gambit Declined: Lasker Defense 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 Ne4 +D53 Queen's Gambit Declined: Modern Variation, Heral Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 +D53 Queen's Gambit Declined: Uhlmann Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. Rc1 dxc4 +D54 Queen's Gambit Declined: Neo-Orthodox Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 O-O 6. Rc1 +D55 Queen's Gambit Declined: Anti-Tartakower Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 h6 7. Bxf6 +D55 Queen's Gambit Declined: Anti-Tartakower Variation, Petrosian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bxf6 Bxf6 7. e3 O-O 8. Rc1 c6 9. Bd3 Nd7 10. O-O dxc4 11. Bxc4 +D55 Queen's Gambit Declined: Modern Variation, Normal Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 +D55 Queen's Gambit Declined: Neo-Orthodox Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 h6 +D55 Queen's Gambit Declined: Neo-Orthodox Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bh4 O-O 7. e3 +D55 Queen's Gambit Declined: Pillsbury Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 d5 5. cxd5 exd5 6. Bg5 Be7 7. e3 O-O 8. Bd3 Bb7 9. Ne5 +D56 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. Bg5 Be7 6. e3 O-O 7. Rc1 h6 8. Bh4 +D56 Queen's Gambit Declined: Lasker Defense 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 Ne4 +D56 Queen's Gambit Declined: Lasker Defense 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. Bg5 Be7 6. e3 O-O 7. Rc1 h6 8. Bh4 Ne4 +D56 Queen's Gambit Declined: Lasker Defense, Russian Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 h6 7. Bh4 Ne4 8. Bxe7 Qxe7 9. Qc2 Nf6 10. Bd3 dxc4 11. Bxc4 c5 12. O-O Nc6 13. Rfd1 Bd7 +D56 Queen's Gambit Declined: Lasker Defense, Teichmann Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bh4 O-O 7. e3 Ne4 8. Bxe7 Qxe7 9. Qc2 +D57 Queen's Gambit Declined: Lasker Defense, Bernstein Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 h6 6. Bh4 O-O 7. Nf3 Ne4 8. Bxe7 Qxe7 9. cxd5 Nxc3 10. bxc3 exd5 11. Qb3 Qd6 +D57 Queen's Gambit Declined: Lasker Defense, Bernstein Variation, Mar del Plata Gambit 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 h6 7. Bh4 Ne4 8. Bxe7 Qxe7 9. cxd5 Nxc3 10. bxc3 exd5 11. Qb3 Rd8 12. c4 Be6 +D57 Queen's Gambit Declined: Lasker Defense, Main Line 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 Ne4 8. Bxe7 Qxe7 9. cxd5 Nxc3 10. bxc3 +D58 Queen's Gambit Declined: Tartakower Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 +D58 Queen's Gambit Declined: Tartakower Defense, Exchange Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 8. cxd5 exd5 +D59 Queen's Gambit Declined: Tartakower Defense 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 8. cxd5 Nxd5 9. Bxe7 Qxe7 10. Nxd5 exd5 11. Rc1 Be6 +D59 Queen's Gambit Declined: Tartakower Defense, Makogonov Exchange Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 8. cxd5 Nxd5 +D60 Queen's Gambit Declined: Orthodox Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 +D60 Queen's Gambit Declined: Orthodox Defense, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Bd3 +D60 Queen's Gambit Declined: Orthodox Defense, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Bd3 c6 +D60 Queen's Gambit Declined: Orthodox Defense, Rauzer Variation 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Qb3 +D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 +D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c5 +D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c6 +D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c6 8. a3 +D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 a6 8. cxd5 exd5 9. Bd3 Re8 +D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c6 8. Rd1 a6 +D62 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation, Flohr Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Qc2 c5 8. cxd5 +D63 Queen's Gambit Declined: Orthodox Defense, Capablanca Variation 1. Nf3 d5 2. d4 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 b6 8. cxd5 exd5 9. Bb5 +D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 +D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. c5 +D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. c5 c6 +D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. c5 c6 9. Bd3 +D63 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 +D63 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 +D63 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 Nbd7 6. Nf3 O-O 7. Rc1 h6 8. Bh4 c5 +D63 Queen's Gambit Declined: Orthodox Defense, Pillsbury Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 b6 8. cxd5 exd5 9. Bd3 +D63 Queen's Gambit Declined: Orthodox Defense, Swiss, Carlsbad Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. cxd5 +D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Nf3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. a3 a6 9. Qc2 +D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 +D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 a6 +D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. Nf3 d5 2. d4 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 Ne4 +D65 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 a6 9. cxd5 +D65 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 a6 9. cxd5 exd5 10. Bd3 +D66 Queen's Gambit Declined: Orthodox Defense, Bd3 Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 +D66 Queen's Gambit Declined: Orthodox Defense, Bd3 Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 h6 9. Bh4 +D66 Queen's Gambit Declined: Orthodox Defense, Fianchetto Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c6 5. Nf3 Be7 6. e3 Nbd7 7. Rc1 O-O 8. Bd3 dxc4 9. Bxc4 b5 +D67 Queen's Gambit Declined: Orthodox Defense, Alekhine Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. Ne4 +D67 Queen's Gambit Declined: Orthodox Defense, Bd3 Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 +D67 Queen's Gambit Declined: Orthodox Defense, Capablanca System 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 +D67 Queen's Gambit Declined: Orthodox Defense, Janowski Variation 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. h4 +D67 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O +D68 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 +D68 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 13. Qb1 +D68 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 13. Qc2 +D69 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 13. dxe5 Nxe5 14. Nxe5 Qxe5 +D70 Neo-Grünfeld Defense: Goglidze Attack 1. d4 Nf6 2. c4 g6 3. f3 d5 +D70 Neo-Grünfeld Defense: with Nf3 1. d4 Nf6 2. c4 g6 3. Nf3 d5 +D70 Neo-Grünfeld Defense: with g3 1. d4 Nf6 2. c4 g6 3. g3 d5 +D71 Neo-Grünfeld Defense: Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 d5 5. cxd5 Nxd5 +D71 Neo-Grünfeld Defense: Exchange Variation 1. c4 Nf6 2. g3 g6 3. Bg2 Bg7 4. d4 d5 5. cxd5 Nxd5 6. Nf3 +D72 Neo-Grünfeld Defense: with g3 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. cxd5 Nxd5 6. e4 Nb6 7. Ne2 +D73 Neo-Grünfeld Defense: with g3 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 +D74 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d5 6. cxd5 Nxd5 7. O-O +D75 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. g3 d5 6. cxd5 Nxd5 7. Bg2 c5 8. O-O +D75 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. g3 O-O 5. Bg2 d5 6. cxd5 Nxd5 7. O-O c5 8. dxc5 +D76 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d5 6. cxd5 Nxd5 7. O-O Nb6 +D77 Neo-Grünfeld Defense: Classical Variation 1. d4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O d5 6. c4 +D77 Neo-Grünfeld Defense: Classical Variation, Modern Defense 1. d4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O d5 6. c4 dxc4 +D77 Neo-Grünfeld Defense: Classical Variation, Polgar Variation 1. d4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O d5 6. c4 Nc6 +D78 Neo-Grünfeld Defense: Classical Variation, Original Defense 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Nc3 Nc6 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Nc3 Nc6 9. Bf4 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Nc3 Ne4 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Ne5 Nc6 9. Nc3 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 e6 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 e6 9. Nc3 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 Bf5 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 Bf5 9. Nc3 +D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 Ng4 +D80 Grünfeld Defense 1. d4 Nf6 2. c4 g6 3. Nc3 d5 +D80 Grünfeld Defense: Gibbon Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. g4 +D80 Grünfeld Defense: Lundin Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bg5 Ne4 5. Nxe4 dxe4 6. Qd2 c5 +D80 Grünfeld Defense: Lutikov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. f3 +D80 Grünfeld Defense: Lutikov Variation, Murrey Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. f3 c5 5. cxd5 Nxd5 6. Na4 +D80 Grünfeld Defense: Stockholm Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bg5 +D80 Grünfeld Defense: Zaitsev Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. h4 +D81 Grünfeld Defense: Russian Variation, Accelerated Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Qb3 +D82 Grünfeld Defense: Brinckmann Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 +D83 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O +D83 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit, Botvinnik Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. Rc1 c5 7. dxc5 Be6 +D83 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit, Capablanca Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. Rc1 +D83 Grünfeld Defense: Brinckmann Attack, Reshevsky Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. Rc1 O-O 6. e3 c5 7. dxc5 Qa5 +D84 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit Accepted 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. cxd5 Nxd5 7. Nxd5 Qxd5 8. Bxc7 +D85 Grünfeld Defense: Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 +D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Nf3 +D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Nf3 c5 +D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. Nc3 d5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 c5 8. Rb1 +D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation, Kramnik's Line 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. Nc3 d5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 c5 8. h3 +D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation, Pawn Grab Line 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Nf3 c5 8. Rb1 O-O 9. Be2 Nc6 10. d5 Bxc3+ +D85 Grünfeld Defense: Exchange Variation, Nadanian Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. Na4 +D86 Grünfeld Defense: Exchange Variation, Classical Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 +D86 Grünfeld Defense: Exchange Variation, Larsen Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 Qd7 +D86 Grünfeld Defense: Exchange Variation, Larsen Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 Qd7 9. O-O b6 +D86 Grünfeld Defense: Exchange Variation, Simagin's Improved Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 Nc6 +D86 Grünfeld Defense: Exchange Variation, Simagin's Lesser Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 b6 +D87 Grünfeld Defense: Exchange Variation, Seville Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 Nc6 9. Be3 O-O 10. O-O Bg4 11. f3 Na5 12. Bxf7+ +D87 Grünfeld Defense: Exchange Variation, Spassky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 O-O +D88 Grünfeld Defense: Exchange Variation, Spassky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 Nc6 9. Be3 O-O 10. O-O cxd4 11. cxd4 +D89 Grünfeld Defense: Exchange Variation, Sokolsky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 O-O 9. O-O Nc6 10. Be3 Bg4 11. f3 Na5 12. Bd3 cxd4 13. cxd4 Be6 14. d5 +D89 Grünfeld Defense: Exchange Variation, Spassky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 Nc6 9. Be3 O-O 10. O-O Bg4 11. f3 Na5 12. Bd3 cxd4 13. cxd4 Be6 +D90 Grünfeld Defense: Flohr Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qa4+ +D90 Grünfeld Defense: Three Knights Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 +D90 Grünfeld Defense: Three Knights Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 +D91 Grünfeld Defense: Three Knights Variation, Petrosian System 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Bg5 +D92 Grünfeld Defense: Three Knights Variation, Hungarian Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Bf4 +D93 Grünfeld Defense: Three Knights Variation, Hungarian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Bf4 O-O 6. e3 +D94 Grünfeld Defense: Flohr Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 g6 5. Nf3 Bg7 6. Bd3 O-O 7. O-O Bf5 +D94 Grünfeld Defense: Makogonov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. b4 +D94 Grünfeld Defense: Opocensky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Bd2 +D94 Grünfeld Defense: Smyslov Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 g6 5. Nf3 Bg7 6. Bd3 O-O 7. O-O Bg4 +D94 Grünfeld Defense: Three Knights Variation, Burille Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 +D94 Grünfeld Defense: Three Knights Variation, Paris Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Bd3 +D95 Grünfeld Defense: Botvinnik Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Qb3 e6 +D95 Grünfeld Defense: Pachman Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. e3 Bg7 5. Qb3 dxc4 6. Bxc4 O-O 7. Nf3 Nbd7 8. Ng5 +D95 Grünfeld Defense: Three Knights Variation, Vienna Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Qb3 +D96 Grünfeld Defense: Russian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 +D97 Grünfeld Defense: Russian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 +D97 Grünfeld Defense: Russian Variation, Byrne Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Nc6 +D97 Grünfeld Defense: Russian Variation, Hungarian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 a6 +D97 Grünfeld Defense: Russian Variation, Levenfish Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 b6 +D97 Grünfeld Defense: Russian Variation, Prins Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Na6 +D97 Grünfeld Defense: Russian Variation, Szabo Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 c6 +D98 Grünfeld Defense: Russian Variation, Keres Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 8. Be3 Nfd7 9. Be2 Nb6 10. Qd3 Nc6 11. O-O-O +D98 Grünfeld Defense: Russian Variation, Smyslov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 +D99 Grünfeld Defense: Russian Variation, Smyslov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 8. Be3 Nfd7 9. Qb3 +D99 Grünfeld Defense: Russian Variation, Yugoslav Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 8. Be3 Nfd7 9. Qb3 c5 diff --git a/crates/openings/data/e.tsv b/crates/openings/data/e.tsv new file mode 100644 index 0000000..93a82e1 --- /dev/null +++ b/crates/openings/data/e.tsv @@ -0,0 +1,368 @@ +eco name pgn +E00 Catalan Opening 1. d4 Nf6 2. c4 e6 3. g3 +E00 Catalan Opening 1. d4 Nf6 2. c4 e6 3. g3 d5 +E00 Catalan Opening: Hungarian Gambit 1. d4 Nf6 2. c4 e6 3. g3 e5 +E00 Indian Defense 1. d4 Nf6 2. c4 e6 3. Qb3 +E00 Indian Defense: Devin Gambit 1. d4 Nf6 2. c4 e6 3. g4 +E00 Indian Defense: Seirawan Attack 1. d4 Nf6 2. c4 e6 3. Bg5 +E01 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 +E01 Catalan Opening: Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 c5 5. Nf3 Nc6 +E02 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 +E03 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Qa4+ Nbd7 6. Qxc4 +E03 Catalan Opening: Open Defense, Alekhine Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Qa4+ Nbd7 6. Qxc4 a6 7. Qc2 +E04 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Nf3 +E04 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 c6 5. Bg2 dxc4 +E04 Catalan Opening: Open Defense, Modern Sharp Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Nf3 Nc6 6. Qa4 Bb4+ +E05 Catalan Opening: Open Defense, Classical Line 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Nf3 Be7 +E05 Catalan Opening: Open Defense, Classical Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O dxc4 +E06 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 +E06 Catalan Opening: Closed 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. d4 O-O 6. O-O c6 +E06 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Bb4+ 5. Bd2 Be7 6. Bg2 O-O 7. O-O c6 8. Bf4 b6 +E06 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O c6 7. Qc2 b6 8. Nbd2 Bb7 9. e4 Na6 +E07 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 +E07 Catalan Opening: Closed, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Nc3 c6 8. Qd3 +E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 +E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. b3 +E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. b3 b6 +E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O c6 7. Qc2 b6 8. Rd1 Nbd7 9. Bf4 +E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. Bf4 b6 9. Nbd2 Bb7 10. e4 +E08 Catalan Opening: Closed, Spassky Gambit 1. d4 Nf6 2. c4 e6 3. g3 Be7 4. Bg2 d5 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. b3 b6 9. Rd1 Bb7 10. Nc3 b5 +E08 Catalan Opening: Closed, Zagoryansky Variation 1. d4 e6 2. c4 Nf6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Rd1 b6 9. a4 +E09 Catalan Opening: Closed Variation, Rabinovich Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Qc2 e6 5. Nbd2 Be7 6. g3 Nbd7 7. Bg2 O-O 8. O-O b5 +E09 Catalan Opening: Closed Variation, Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Nbd2 b6 +E09 Catalan Opening: Closed, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Nbd2 +E09 Catalan Opening: Closed, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O c6 7. Qc2 b6 8. Nbd2 Bb7 9. e4 Nbd7 +E09 Catalan Opening: Closed, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Bf4 b6 9. Nbd2 Bb7 10. e4 dxe4 11. Nxe4 Nxe4 12. Qxe4 +E09 Catalan Opening: Closed, Sokolsky Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. Nbd2 b6 9. b3 a5 10. Bb2 Ba6 +E10 Blumenfeld Countergambit 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 +E10 Blumenfeld Countergambit Accepted 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 5. dxe6 fxe6 6. cxb5 d5 +E10 Blumenfeld Countergambit: Duz-Khotimirsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 5. Bg5 +E10 Blumenfeld Countergambit: Spielmann Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 5. Bg5 exd5 6. cxd5 h6 +E10 Indian Defense: Anti-Nimzo-Indian 1. d4 Nf6 2. c4 e6 3. Nf3 +E10 Indian Defense: Dzindzi-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nf3 a6 +E10 Indian Defense: Döry Indian 1. d4 Nf6 2. c4 e6 3. Nf3 Ne4 +E11 Bogo-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ +E11 Bogo-Indian Defense: Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Bxd2+ +E11 Bogo-Indian Defense: Grünfeld Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nbd2 +E11 Bogo-Indian Defense: Haiti Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Nc6 +E11 Bogo-Indian Defense: Monticelli Trap 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Bxd2+ 7. Qxd2 O-O 8. Nc3 Ne4 9. Qc2 Nxc3 10. Ng5 +E11 Bogo-Indian Defense: New England Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nfd2 +E11 Bogo-Indian Defense: Nimzowitsch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Qe7 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Be7 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 O-O +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 O-O 7. O-O +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 O-O 7. Qc2 c6 8. O-O +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. b3 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. Rc1 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. Rd1 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. Rd1 h6 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Bb4+ 5. Bd2 Be7 6. Bg2 O-O 7. O-O c6 8. Qc2 Nbd7 9. Bf4 b6 10. Nbd2 +E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Bb4+ 5. Bd2 Be7 6. Bg2 O-O 7. O-O c6 8. Qc2 Nbd7 9. Bf4 b6 10. Nbd2 Ba6 +E11 Bogo-Indian Defense: Vitolins Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 c5 +E11 Bogo-Indian Defense: Wade-Smyslov Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 a5 +E12 Queen's Indian Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 +E12 Queen's Indian Defense: Kasparov Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 +E12 Queen's Indian Defense: Kasparov Variation, Botvinnik Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 Bb7 5. Bg5 h6 6. Bh4 g5 7. Bg3 Nh5 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Andersson Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 Ne4 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 exd5 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Hedgehog Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 g6 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Kasparov Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. Qc2 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Marco Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 Be7 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Modern Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Petrosian Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. e3 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Polovodin Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 Bb7 5. a3 d5 6. cxd5 Nxd5 7. e4 +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Rashkovsky Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. Qa4+ +E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Romanishin Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. Bd2 +E12 Queen's Indian Defense: Miles Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Bf4 +E12 Queen's Indian Defense: Petrosian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 +E12 Queen's Indian Defense: Petrosian Variation, Farago Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Ba6 5. Qc2 Bb7 +E13 Queen's Indian Defense: Kasparov Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 Bb4 5. Bg5 h6 6. Bh4 Bb7 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. c4 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. c4 Be7 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. c4 g6 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O Be7 6. c4 O-O 7. Nc3 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. Nbd2 c5 6. b3 Be7 7. Bb2 d6 8. O-O O-O 9. c4 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bb7 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bd6 6. Bd3 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bd6 6. Bd3 O-O 7. O-O Bb7 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 Be7 5. Nc3 O-O 6. b3 b6 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 Be7 5. b3 O-O 6. Bd3 b6 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 Be7 5. b3 O-O 6. Bb2 b6 7. Nbd2 Bb7 8. Bd3 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nbd2 b6 5. a3 Bxd2+ 6. Qxd2 Bb7 7. e3 +E14 Queen's Indian Defense, with e3 1. Nf3 d5 2. e3 Nf6 3. c4 e6 4. Nc3 Be7 5. d4 O-O 6. b3 b6 7. cxd5 exd5 8. Bb2 Bb7 9. Bd3 +E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 d5 3. c4 e6 4. e3 b6 5. b3 Bb7 6. Bd3 Nbd7 7. O-O Bd6 8. Bb2 O-O 9. Nbd2 +E14 Queen's Indian Defense, with e3, Bb4+ Line 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nbd2 b6 5. e3 Bb7 +E14 Queen's Indian Defense: Averbakh Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 c5 6. O-O Be7 7. b3 O-O 8. Bb2 cxd4 9. Nxd4 +E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 +E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 +E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 +E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 d5 +E14 Queen's Indian Defense: Spassky System3 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 c5 +E14 Queen's Indian Defense: Spassky System3 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 c5 6. Nc3 cxd4 7. exd4 Be7 8. O-O d5 9. cxd5 Nxd5 +E15 Queen's Indian Defense: Buerger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 c5 6. d5 exd5 7. Ng5 +E15 Queen's Indian Defense: Fianchetto Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 +E15 Queen's Indian Defense: Fianchetto Variation, Check Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 Bb4+ +E15 Queen's Indian Defense: Fianchetto Variation, Check Variation, Intermezzo Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 Bb4+ 6. Bd2 Be7 +E15 Queen's Indian Defense: Fianchetto Variation, Check Variation, Modern Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 Bb4+ 6. Bd2 Qe7 +E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 +E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation, Nimzowitsch Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. Qa4 +E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation, Quiet Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 +E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation, Timman's Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. Qb3 +E15 Queen's Indian Defense: Fianchetto Variation, Rubinstein Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 c5 6. d5 exd5 7. Nh4 +E15 Queen's Indian Defense: Fianchetto Variation, Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 c5 +E15 Queen's Indian Defense: Fianchetto Variation, Traditional Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 +E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ +E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Nbd2 O-O 7. O-O +E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Nbd2 O-O 7. O-O d5 +E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Nbd2 O-O 7. O-O a5 +E16 Queen's Indian Defense: Riumin Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Be7 +E16 Queen's Indian Defense: Riumin Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Be7 7. O-O O-O 8. Nc3 +E16 Queen's Indian Defense: Riumin Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Be7 7. O-O O-O 8. Nc3 d5 +E16 Queen's Indian Defense: Yates Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 a5 5. g3 b6 6. Bg2 Bb7 +E17 Queen's Indian Defense: Anti-Queen's Indian System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. Nc3 +E17 Queen's Indian Defense: Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O +E17 Queen's Indian Defense: Classical Variation, Polugaevsky Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. d5 exd5 8. Nh4 +E17 Queen's Indian Defense: Classical Variation, Taimanov Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. d5 exd5 8. Nd4 +E17 Queen's Indian Defense: Euwe Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. b3 +E17 Queen's Indian Defense: Fianchetto Variation, Kramnik Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Re1 +E17 Queen's Indian Defense: Opocensky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. Nc3 Ne4 7. Bd2 +E17 Queen's Indian Defense: Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 +E18 Queen's Indian Defense: Classical Variation, Tiviakov Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 Na6 +E18 Queen's Indian Defense: Classical Variation, Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 +E18 Queen's Indian Defense: Classical Variation, Traditional Variation, Nimzowitsch Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 d5 +E19 Queen's Indian Defense: Classical Variation, Traditional Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 Ne4 8. Qc2 Nxc3 9. Qxc3 +E20 Nimzo-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 +E20 Nimzo-Indian Defense: Dilworth Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e4 +E20 Nimzo-Indian Defense: Kmoch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 +E20 Nimzo-Indian Defense: Mikenas Attack 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qd3 +E20 Nimzo-Indian Defense: Romanishin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. g3 +E20 Nimzo-Indian Defense: Romanishin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. g3 O-O 6. Bg2 +E20 Nimzo-Indian Defense: Romanishin Variation, English Hybrid 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. g3 cxd4 6. Nxd4 O-O 7. Bg2 d5 8. cxd5 Nxd5 +E21 Nimzo-Indian Defense: Three Knights Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 +E21 Nimzo-Indian Defense: Three Knights Variation, Euwe Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. d5 Ne4 +E21 Nimzo-Indian Defense: Three Knights Variation, Korchnoi Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. d5 +E21 Nimzo-Indian Defense: Three Knights Variation, Shocron Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nc3 c5 5. d5 b5 +E22 Nimzo-Indian Defense: Spielmann Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 +E23 Nimzo-Indian Defense: Spielmann Variation, Carlsbad Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 6. Nf3 Ne4 7. Bd2 Nxd2 +E23 Nimzo-Indian Defense: Spielmann Variation, Romanovsky Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 +E23 Nimzo-Indian Defense: Spielmann Variation, Stahlberg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 6. Nf3 Ne4 7. Bd2 Nxc5 +E23 Nimzo-Indian Defense: Spielmann Variation, Stahlberg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 6. Nf3 Ne4 7. Bd2 Nxc5 8. Qc2 f5 9. g3 +E24 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 +E24 Nimzo-Indian Defense: Sämisch Variation, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. e3 O-O 8. cxd5 Nxd5 +E25 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. cxd5 +E25 Nimzo-Indian Defense: Sämisch Variation, Keres Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. cxd5 Nxd5 8. dxc5 +E25 Nimzo-Indian Defense: Sämisch Variation, Romanovsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. cxd5 Nxd5 8. dxc5 f5 +E26 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 c5 6. e3 +E26 Nimzo-Indian Defense: Sämisch Variation, O'Kelly Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 c5 6. e3 b6 +E27 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 O-O +E28 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. a3 Bxc3+ 6. bxc3 +E29 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. a3 Bxc3+ 7. bxc3 O-O +E29 Nimzo-Indian Defense: Sämisch Variation, Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. a3 Bxc3+ 7. bxc3 O-O 8. Ne2 b6 9. e4 Ne8 +E30 Nimzo-Indian Defense: Leningrad Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Bg5 +E30 Nimzo-Indian Defense: Leningrad Variation, Averbakh Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Bg5 h6 5. Bh4 c5 6. d5 b5 +E31 Nimzo-Indian Defense: Leningrad Variation, Benoni Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Bg5 h6 5. Bh4 c5 6. d5 d6 +E32 Nimzo-Indian Defense: Classical Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 +E32 Nimzo-Indian Defense: Classical Variation, Keres Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 O-O 5. a3 Bxc3+ 6. Qxc3 b6 +E32 Nimzo-Indian Defense: Classical Variation, Vitolins-Adorjan Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 O-O 5. a3 Bxc3+ 6. Qxc3 b5 +E33 Nimzo-Indian Defense: Classical Variation, Milner-Barry Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 d6 +E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 +E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 +E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 O-O 6. e3 +E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 d6 6. Bd2 +E34 Nimzo-Indian Defense: Classical Variation, Belyavsky Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. cxd5 Qxd5 6. Nf3 Qf5 7. Qd1 e5 +E34 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 +E35 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. cxd5 exd5 +E36 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 +E36 Nimzo-Indian Defense: Classical Variation, Noa Variation, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Nc6 +E36 Nimzo-Indian Defense: Classical Variation, Noa Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 +E36 Nimzo-Indian Defense: Classical Variation, Romanishin Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 c5 +E37 Nimzo-Indian Defense: Classical Variation, Modern Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 7. Qc2 c5 +E37 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 7. Qc2 +E37 Nimzo-Indian Defense: Classical Variation, Noa Variation, San Remo Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 7. Qc2 Nc6 8. e3 e5 +E38 Nimzo-Indian Defense: Classical Variation, Berlin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 +E38 Nimzo-Indian Defense: Classical Variation, Berlin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 O-O 5. e3 d5 6. Nf3 c5 +E38 Nimzo-Indian Defense: Classical Variation, Berlin Variation, Steiner Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 5. dxc5 Bxc3+ +E39 Nimzo-Indian Defense: Classical Variation, Berlin Variation, Macieja System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 5. dxc5 O-O 6. a3 Bxc5 7. Nf3 b6 +E39 Nimzo-Indian Defense: Classical Variation, Berlin Variation, Pirc Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 5. dxc5 O-O +E40 Nimzo-Indian Defense: Rubinstein System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 +E40 Nimzo-Indian Defense: Rubinstein System, Taimanov Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 Nc6 +E41 Nimzo-Indian Defense: Rubinstein System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 +E41 Nimzo-Indian Defense: Rubinstein System, Hübner Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. Nf3 Bxc3+ 7. bxc3 d6 +E41 Nimzo-Indian Defense: Rubinstein System, Hübner Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. Nf3 Bxc3+ 7. bxc3 d6 8. O-O O-O +E42 Nimzo-Indian Defense: Rubinstein System, Rubinstein Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Ne2 +E42 Nimzo-Indian Defense: Rubinstein System, Rubinstein Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Ne2 cxd4 6. exd4 O-O 7. a3 +E42 Nimzo-Indian Defense: Rubinstein System, Rubinstein Variation, Sherbakov Attack 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Ne2 cxd4 6. exd4 O-O 7. c5 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O c5 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O c5 8. Na4 cxd4 9. a3 Be7 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 Ne4 5. Qc2 f5 6. Nf3 b6 7. Bd3 Bb7 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 c5 6. Nf3 b6 7. O-O Bb7 8. Na4 Qe7 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 Bxc3+ 5. bxc3 b6 6. e3 Bb7 7. Bd3 O-O 8. O-O +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 b6 5. e3 Ne4 6. Qc2 +E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 b6 5. e3 Ne4 6. Qc2 Bb7 7. Bd3 Bxc3+ 8. bxc3 f5 9. O-O +E43 Nimzo-Indian Defense: St. Petersburg Variation, with Ne4 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 Ne4 +E44 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 +E44 Nimzo-Indian Defense: St. Petersburg Variation, American Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 Ne4 +E44 Nimzo-Indian Defense: St. Petersburg Variation, Romanishin-Psakhis Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 c5 6. a3 Ba5 +E45 Nimzo-Indian Defense: St. Petersburg Variation, Fischer Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 Ba6 +E46 Nimzo-Indian Defense: Normal Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O +E46 Nimzo-Indian Defense: Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Ne2 +E46 Nimzo-Indian Defense: Simagin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Ne2 d5 6. a3 Bd6 +E47 Nimzo-Indian Defense: Normal Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 +E48 Nimzo-Indian Defense: Normal Variation, Classical Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 +E48 Nimzo-Indian Defense: Ragozin Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 Nc6 7. O-O +E49 Nimzo-Indian Defense: Normal Variation, Botvinnik System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. a3 Bxc3+ 7. bxc3 +E50 Nimzo-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 +E51 Nimzo-Indian Defense: Normal Variation, Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 +E51 Nimzo-Indian Defense: Normal Variation, Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 6. Bd2 Nc6 +E51 Nimzo-Indian Defense: Normal Variation, Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 6. Bd2 Nc6 7. a3 +E51 Nimzo-Indian Defense: Normal Variation, Sämisch Deferred 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 6. a3 +E51 Nimzo-Indian Defense: Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 Nc6 7. O-O dxc4 +E52 Nimzo-Indian Defense: Normal Variation, Schlechter Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 b6 +E52 Nimzo-Indian Defense: Normal Variation, Schlechter Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O d5 +E53 Nimzo-Indian Defense: Normal Variation, Gligoric System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 +E53 Nimzo-Indian Defense: Normal Variation, Gligoric System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nbd7 +E53 Nimzo-Indian Defense: Normal Variation, Gligoric System, Keres Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O b6 +E54 Nimzo-Indian Defense: Normal Variation, Gligoric System, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 +E54 Nimzo-Indian Defense: Normal Variation, Gligoric System, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 cxd4 9. exd4 +E54 Nimzo-Indian Defense: Normal Variation, Gligoric System, Smyslov Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 Qe7 +E55 Nimzo-Indian Defense: Normal Variation, Gligoric System, Bronstein Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 Nbd7 +E56 Nimzo-Indian Defense: Normal Variation, Gligoric System, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 +E57 Nimzo-Indian Defense: Normal Variation, Gligoric System, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 8. a3 dxc4 9. Bxc4 cxd4 +E58 Nimzo-Indian Defense: Normal Variation, Bernstein Defense, Exchange Line 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 8. a3 Bxc3 9. bxc3 +E59 Nimzo-Indian Defense: Normal Variation, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 8. a3 Bxc3 9. bxc3 dxc4 10. Bxc4 +E59 Nimzo-Indian Defense: Normal Variation, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. a3 Bxc3+ 7. bxc3 dxc4 8. Bxc4 c5 9. Nf3 Nc6 10. O-O Qc7 11. Qc2 +E60 Grünfeld Defense: Counterthrust Variation 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 d5 +E60 Indian Defense: Anti-Grünfeld, Adorjan Gambit 1. d4 Nf6 2. c4 g6 3. d5 b5 +E60 Indian Defense: Anti-Grünfeld, Advance Variation 1. d4 Nf6 2. c4 g6 3. d5 +E60 Indian Defense: Anti-Grünfeld, Alekhine Variation 1. d4 Nf6 2. c4 g6 3. f3 +E60 Indian Defense: Anti-Grünfeld, Alekhine Variation, Leko Gambit 1. d4 Nf6 2. c4 g6 3. f3 e5 +E60 Indian Defense: Anti-Grünfeld, Basman-Williams Attack 1. d4 Nf6 2. c4 g6 3. h4 +E60 Indian Defense: West Indian Defense 1. d4 Nf6 2. c4 g6 +E60 King's Indian Defense: Fianchetto Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 +E60 King's Indian Defense: Fianchetto Variation, Immediate Fianchetto 1. d4 Nf6 2. c4 g6 3. g3 +E60 King's Indian Defense: Normal Variation, King's Knight Variation 1. d4 Nf6 2. Nf3 g6 3. c4 +E60 King's Indian Defense: Santasiere Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. b4 +E60 King's Indian Defense: Semi-Classical Variation, Benoni Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 c6 +E60 King's Indian Defense: Semi-Classical Variation, Hollywood Variation 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. Nc3 O-O 5. e3 d6 6. Be2 Nc6 +E60 Queen's Pawn, Mengarini Attack 1. d4 Nf6 2. c4 g6 3. Qc2 +E61 King's Indian Defense 1. d4 Nf6 2. c4 g6 3. Nc3 +E61 King's Indian Defense: Fianchetto Variation, Benjamin Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 c6 7. O-O Qb6 +E61 King's Indian Defense: Semi-Classical Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 +E61 King's Indian Defense: Semi-Classical Variation, Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 Nbd7 7. O-O e5 8. dxe5 dxe5 +E61 King's Indian Defense: Semi-Classical Variation, Queenside Storm Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 Nbd7 7. O-O e5 8. b4 +E61 King's Indian Defense: Smyslov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. Bg5 +E62 King's Indian Defense: Fianchetto Variation, Carlsbad Variation 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 Nc6 +E62 King's Indian Defense: Fianchetto Variation, Delayed Fianchetto 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 +E62 King's Indian Defense: Fianchetto Variation, Kavalek Defense 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c6 7. Nc3 Qa5 +E62 King's Indian Defense: Fianchetto Variation, Larsen Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 c6 7. O-O Bf5 +E62 King's Indian Defense: Fianchetto Variation, Lesser Simagin (Spassky) 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 Nc6 7. O-O Bf5 +E62 King's Indian Defense: Fianchetto Variation, Simagin Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 Nc6 7. O-O Bg4 +E62 King's Indian Defense: Fianchetto Variation, Uhlmann-Szabo System 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 e5 +E63 King's Indian Defense: Fianchetto Variation, Panno Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 +E63 King's Indian Defense: Fianchetto Variation, Panno Variation, Blockade Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 8. d5 Na5 9. Nd2 c5 10. Qc2 e5 +E63 King's Indian Defense: Fianchetto Variation, Panno Variation, Donner Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 8. d5 Na5 9. Nd2 c5 10. Qc2 Rb8 11. b3 b5 12. Bb2 bxc4 13. bxc4 Bh6 +E63 King's Indian Defense: Fianchetto Variation, Panno Variation, Korchnoi Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 8. h3 Rb8 9. Be3 b5 10. Nd2 +E64 King's Indian Defense: Fianchetto Variation, Double Fianchetto Attack 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 d6 5. Bg2 O-O 6. O-O Nbd7 7. Nc3 e5 8. b3 +E64 King's Indian Defense: Fianchetto Variation, Hungarian Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 d6 5. Bg2 O-O 6. O-O Nbd7 7. Nc3 a6 +E64 King's Indian Defense: Fianchetto Variation, Pterodactyl Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 c5 5. Bg2 Qa5+ +E64 King's Indian Defense: Fianchetto Variation, Yugoslav System 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 d6 5. Bg2 O-O 6. O-O c5 +E64 King's Indian Defense: Fianchetto Variation, Yugoslav Variation, Rare Line 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 c5 +E65 King's Indian Defense: Fianchetto Variation, Yugoslav Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c5 7. Nc3 +E65 King's Indian Defense: Fianchetto Variation, Yugoslav Variation, Exchange Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c5 7. Nc3 Nc6 8. dxc5 dxc5 +E66 King's Indian Defense: Fianchetto Variation, Yugoslav Variation, Advance Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c5 7. Nc3 Nc6 8. d5 +E67 King's Indian Defense: Fianchetto Variation, Classical Fianchetto 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nbd7 7. Nc3 e5 +E67 King's Indian Defense: Fianchetto Variation, Debrecen Defense 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 Nbd7 +E68 King's Indian Defense: Fianchetto Variation, Classical Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nbd7 7. Nc3 e5 8. e4 +E68 King's Indian Defense: Fianchetto Variation, Long Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 Nbd7 7. O-O e5 8. e4 Re8 9. h3 exd4 10. Nxd4 Nc5 11. Re1 a5 +E69 King's Indian Defense: Fianchetto Variation, Classical Main Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nbd7 7. Nc3 e5 8. e4 c6 9. h3 +E70 King's Indian Defense: Accelerated Averbakh Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Bg5 +E70 King's Indian Defense: Kramer Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nge2 +E70 King's Indian Defense: Normal Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 +E70 King's Indian Defense: Normal Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 +E71 King's Indian Defense: Karpov System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. h3 O-O 6. Be3 +E71 King's Indian Defense: Makogonov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. h3 +E72 King's Indian Defense: Normal Variation, Deferred Fianchetto 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. g3 +E72 King's Indian Defense: Pomar System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. g3 O-O 6. Bg2 e5 7. Nge2 +E73 King's Indian Defense: Averbakh Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 +E73 King's Indian Defense: Averbakh Variation, Flexible Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 h6 +E73 King's Indian Defense: Averbakh Variation, Geller Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Nbd7 +E73 King's Indian Defense: Averbakh Variation, Modern Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Na6 +E73 King's Indian Defense: Averbakh Variation, Modern Defense, Burgess Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Na6 7. Qd2 c6 +E73 King's Indian Defense: Averbakh Variation, Nc6 Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Nc6 +E73 King's Indian Defense: Averbakh Variation, Spanish Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 a6 +E73 King's Indian Defense: Normal Variation, Standard Development 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 +E73 King's Indian Defense: Semi-Averbakh System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Be3 +E74 King's Indian Defense: Averbakh Variation, Benoni Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 +E74 King's Indian Defense: Averbakh Variation, Benoni Defense, Advance Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 7. d5 +E74 King's Indian Defense: Averbakh Variation, Benoni Defense, Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 7. dxc5 +E75 King's Indian Defense: Averbakh Variation, Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 7. d5 e6 +E76 King's Indian Defense: Four Pawns Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 +E76 King's Indian Defense: Four Pawns Attack, Dynamic Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. d5 +E76 King's Indian Defense: Four Pawns Attack, Modern Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 Na6 +E77 King's Indian Defense: Four Pawns Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. f4 +E77 King's Indian Defense: Four Pawns Attack, Florentine Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. d5 e6 8. Be2 exd5 9. e5 +E77 King's Indian Defense: Four Pawns Attack, Normal Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. d5 e6 8. Be2 +E77 King's Indian Defense: Six Pawns Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Be2 c5 7. d5 e6 8. dxe6 fxe6 9. g4 Nc6 10. h4 +E78 King's Indian Defense: Four Pawns Attack, Fluid Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. Be2 +E79 King's Indian Defense: Four Pawns Attack, Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. Be2 cxd4 8. Nxd4 Nc6 9. Be3 +E80 King's Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 +E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 +E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 h6 8. Bf4 +E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 e6 8. Qd2 exd5 9. Nxd5 +E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 e6 8. Qd2 h6 9. Bxh6 +E81 King's Indian Defense: Sämisch Variation, Bobotsov-Korchnoi-Petrosian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Nge2 +E81 King's Indian Defense: Sämisch Variation, Byrne Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 c6 7. Bd3 a6 +E81 King's Indian Defense: Sämisch Variation, Normal Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O +E81 King's Indian Defense: Sämisch Variation, Sämisch Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 c5 +E81 King's Indian Defense: Sämisch Variation, Sämisch Gambit Accepted 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 c5 7. dxc5 dxc5 8. Qxd8 Rxd8 9. Bxc5 +E82 King's Indian Defense: Sämisch Variation, Double Fianchetto 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 b6 +E83 King's Indian Defense: Sämisch Variation, Panno Formation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 7. Nge2 a6 +E83 King's Indian Defense: Sämisch Variation, Ruban Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 7. Nge2 Rb8 +E83 King's Indian Defense: Sämisch Variation, Yates Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 +E84 King's Indian Defense: Sämisch Variation, Panno Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 7. Nge2 a6 8. Qd2 Rb8 +E85 King's Indian Defense: Sämisch Variation, Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 +E86 King's Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. Nge2 c6 +E87 King's Indian Defense: Sämisch Variation, Bronstein Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 Nh5 8. Qd2 Qh4+ 9. g3 Nxg3 10. Qf2 Nxf1 11. Qxh4 Nxe3 12. Ke2 +E87 King's Indian Defense: Sämisch Variation, Closed Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 +E87 King's Indian Defense: Sämisch Variation, Orthodox Variation, Bronstein Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 Nh5 8. Qd2 Qh4+ 9. g3 Nxg3 10. Qf2 Nxf1 11. Qxh4 Nxe3 12. Ke2 Nxc4 +E88 King's Indian Defense: Sämisch Variation, Closed Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 c6 +E89 King's Indian Defense: Sämisch Variation, Closed Variation, Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. Nge2 c6 8. d5 cxd5 +E90 King's Indian Defense: Larsen Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be3 +E90 King's Indian Defense: Normal Variation, Rare Defenses 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 +E90 King's Indian Defense: Zinnowitz Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Bg5 +E91 King's Indian Defense: Kazakh Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 Na6 +E91 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 +E92 King's Indian Defense: Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. dxe5 +E92 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 +E92 King's Indian Defense: Orthodox Variation, Gligoric-Taimanov System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. Be3 +E92 King's Indian Defense: Petrosian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 +E92 King's Indian Defense: Petrosian Variation, Stein Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 a5 +E93 King's Indian Defense: Petrosian Variation, Keres Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 Nbd7 8. Bg5 h6 9. Bh4 g5 10. Bg3 Nh5 11. h4 +E93 King's Indian Defense: Petrosian Variation, Normal Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 Nbd7 +E94 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O +E94 King's Indian Defense: Orthodox Variation, Donner Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O c6 +E94 King's Indian Defense: Orthodox Variation, Glek Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Na6 +E94 King's Indian Defense: Orthodox Variation, Positional Defense 1. d4 Nf6 2. c4 d6 3. Nc3 Nbd7 4. e4 e5 5. Nf3 g6 6. Be2 Bg7 7. O-O O-O +E94 King's Indian Defense: Orthodox Variation, Positional Defense, Closed Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 Nbd7 7. O-O e5 8. d5 +E94 King's Indian Defense: Orthodox Variation, Ukrainian Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O a5 +E95 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nbd7 8. Re1 +E96 King's Indian Defense: Orthodox Variation, Positional Defense, Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nbd7 8. Re1 c6 9. Bf1 a5 +E97 King's Indian Defense: Orthodox Variation, Aronin-Taimanov Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 +E97 King's Indian Defense: Orthodox Variation, Bayonet Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. b4 +E97 King's Indian Defense: Orthodox Variation, Bayonet Attack, Sokolov's Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. b4 Nh5 10. Re1 +E97 King's Indian Defense: Orthodox Variation, Bayonet Attack, Yepishin's Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. b4 Nh5 10. Qc2 +E97 King's Indian Defense: Orthodox Variation, Korchnoi Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Bd2 +E97 King's Indian Defense: Orthodox Variation, Modern System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Nd2 +E98 King's Indian Defense: Orthodox Variation, Classical System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 +E98 King's Indian Defense: Orthodox Variation, Classical System, Kozul Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. Be3 f5 11. f3 f4 12. Bf2 g5 13. Rc1 Ng6 14. c5 +E98 King's Indian Defense: Orthodox Variation, Classical System, Neo-Classical Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. Be3 +E99 King's Indian Defense: Orthodox Variation, Classical System, Benko Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. f3 f5 11. g4 +E99 King's Indian Defense: Orthodox Variation, Classical System, Traditional Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. f3 f5 diff --git a/crates/openings/src/lib.rs b/crates/openings/src/lib.rs new file mode 100644 index 0000000..5c719eb --- /dev/null +++ b/crates/openings/src/lib.rs @@ -0,0 +1,273 @@ +//! Opening names from the Lichess `chess-openings` table: a position's ECO code and +//! name, looked up by the position itself, so a line reaching a named position by +//! another move order gets its name too. A line is named by its deepest named +//! position, as the table's README says ("go back through the moves until a named +//! position is found"). +//! +//! The five TSV files in `data/` (`eco`, `name`, `pgn`) were downloaded unmodified from +//! at revision +//! `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27), on 2026-10-28; the data set is +//! in the public domain (CC0 1.0). Their SHA-256 sums are in `THIRD_PARTY_NOTICES.md`. +//! The table is parsed on first use (3 865 lines, a fraction of a second). +//! +//! Every position on the way to a named one is a book position: the game review gives +//! no !! or ! for a move into it (chess.com's «book» moves). + +use std::collections::{HashMap, HashSet}; +use std::sync::OnceLock; + +use serde::{Deserialize, Serialize}; +use shakmaty::san::SanPlus; +use shakmaty::zobrist::Zobrist64; +use shakmaty::{Chess, EnPassantMode, Position}; + +const FILES: [&str; 5] = [ + include_str!("../data/a.tsv"), + include_str!("../data/b.tsv"), + include_str!("../data/c.tsv"), + include_str!("../data/d.tsv"), + include_str!("../data/e.tsv"), +]; + +/// A named opening position of the table. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Opening { + /// "B30". + pub eco: String, + /// "Sicilian Defense: Nyezhmetdinov-Rossolimo Attack". + pub name: String, + /// The table's moves to the position, in SAN ("1. e4 c5 2. Nf3 Nc6 3. Bb5"). + pub line: String, + /// Half-moves of `line`. + pub plies: u8, +} + +impl Opening { + /// The part of the name before the colon ("Sicilian Defense"). + pub fn family(&self) -> &str { + self.name.split(':').next().unwrap_or(&self.name).trim() + } + + /// The part after the colon ("Nyezhmetdinov-Rossolimo Attack"), if any. + pub fn variation(&self) -> Option<&str> { + self.name.split_once(':').map(|(_, v)| v.trim()) + } +} + +/// The key of a position for the table: the same as `chess_import::position::key` +/// (Zobrist, en passant only when legal), so keys from either side match. +pub fn key(pos: &Chess) -> u64 { + pos.zobrist_hash::(EnPassantMode::Legal).0 +} + +struct Table { + entries: Vec, + /// Position key → entry. A position reached by two lines of the table keeps the + /// first (the files are in ECO order). + by_key: HashMap, + /// Every position of every line after its first move, named or not. + book: HashSet, +} + +fn table() -> &'static Table { + static TABLE: OnceLock = OnceLock::new(); + TABLE.get_or_init(|| { + let mut t = Table { + entries: Vec::with_capacity(4000), + by_key: HashMap::with_capacity(4000), + book: HashSet::with_capacity(20000), + }; + for text in FILES { + for line in text.lines().skip(1) { + let mut cols = line.split('\t'); + let (Some(eco), Some(name), Some(pgn)) = (cols.next(), cols.next(), cols.next()) + else { + continue; + }; + let Some((pos, plies)) = play(pgn, &mut t.book) else { + continue; + }; + let k = key(&pos); + if t.by_key.contains_key(&k) { + continue; + } + t.by_key.insert(k, t.entries.len()); + t.entries.push(Opening { + eco: eco.to_owned(), + name: name.to_owned(), + line: pgn.to_owned(), + plies, + }); + } + } + t + }) +} + +/// Plays a table line ("1. e4 c5 2. Nf3"), adding its positions to `book`; `None` if a +/// move is not legal. +fn play(pgn: &str, book: &mut HashSet) -> Option<(Chess, u8)> { + let mut pos = Chess::default(); + let mut plies = 0u8; + for tok in pgn.split_whitespace() { + if tok.ends_with('.') { + continue; + } + let m = tok.parse::().ok()?.san.to_move(&pos).ok()?; + pos.play_unchecked(m); + book.insert(key(&pos)); + plies = plies.checked_add(1)?; + } + Some((pos, plies)) +} + +/// Number of named positions. +pub fn count() -> usize { + table().entries.len() +} + +/// The entry of a named position (by its [`key`]). +pub fn by_position(k: u64) -> Option { + table().by_key.get(&k).copied() +} + +/// The position (by its [`key`]) lies on a line of the table: a move into it is a book +/// move. +pub fn in_book(k: u64) -> bool { + table().book.contains(&k) +} + +/// Entry `id` (from [`by_position`] or [`deepest`]). +pub fn get(id: usize) -> &'static Opening { + &table().entries[id] +} + +/// The name of a line (the positions `keys`, in order): its deepest named position, +/// its index in `keys` and its entry — but a deeper position whose name is only a +/// more general one ("Sicilian Defense" after 3.d4 in the "Modern Variations") does +/// not take the name back: the most precise name met stays. +pub fn deepest(keys: &[u64]) -> Option<(usize, usize)> { + let mut out: Option<(usize, usize)> = None; + for (i, k) in keys.iter().enumerate() { + if let Some(id) = by_position(*k) + && out.is_none_or(|(_, cur)| !more_general(id, cur)) + { + out = Some((i, id)); + } + } + out +} + +/// Entry `a`'s name is a more general form of entry `b`'s ("Sicilian Defense" of +/// "Sicilian Defense: Modern Variations"; "…: Najdorf Variation" of "…: Najdorf +/// Variation, English Attack"). +pub fn more_general(a: usize, b: usize) -> bool { + is_prefix_name(&get(a).name, &get(b).name) +} + +/// `general` names a family or a variation `precise` is part of. +pub fn is_prefix_name(general: &str, precise: &str) -> bool { + precise.len() > general.len() + && precise.starts_with(general) + && matches!(precise[general.len()..].chars().next(), Some(':' | ',')) +} + +#[cfg(test)] +mod tests { + use super::*; + use shakmaty::san::San; + + fn keys(moves: &[&str]) -> Vec { + let mut pos = Chess::default(); + let mut out = vec![key(&pos)]; + for s in moves { + let m = s.parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(m); + out.push(key(&pos)); + } + out + } + + #[test] + fn the_table_loads() { + // 3 865 lines; a few positions are reached by two lines of the table. + assert!(count() > 3800, "{}", count()); + let start = by_position(key(&Chess::default())); + assert!(start.is_none(), "the start position has no name"); + } + + #[test] + fn the_deepest_named_position_names_the_line_whatever_the_move_order() { + // 1.e4 c5 2.Nf3 Nc6 3.Bb5: the Rossolimo; 3...g6 is named too, 4.O-O is not. + let k = keys(&["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O"]); + let (at, id) = deepest(&k).expect("named"); + let o = get(id); + assert_eq!(o.eco, "B31"); + assert!( + o.name + .starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), + "{}", + o.name + ); + assert_eq!(at, 6, "the position after 3...g6"); + assert_eq!(o.family(), "Sicilian Defense"); + assert!( + o.variation() + .is_some_and(|v| v.starts_with("Nyezhmetdinov")) + ); + assert_eq!(o.plies, 6); + assert_eq!(o.line, "1. e4 c5 2. Nf3 Nc6 3. Bb5 g6"); + // A transposition: 1.Nf3 d5 2.d4 reaches the table's 1.d4 d5 2.Nf3. + let a = deepest(&keys(&["Nf3", "d5", "d4"])).expect("named"); + let b = deepest(&keys(&["d4", "d5", "Nf3"])).expect("named"); + assert_eq!(a.1, b.1); + assert_eq!(get(a.1).line, "1. d4 d5 2. Nf3"); + // A family without a variation. + let o = get(deepest(&keys(&["e4", "c5"])).expect("named").1); + assert_eq!(o.name, "Sicilian Defense"); + assert_eq!(o.variation(), None); + // Nothing before the first move. + assert_eq!(deepest(&keys(&[])), None); + // A deeper position with a more general name keeps the precise one: the + // table names 1.e4 c5 2.Nf3 d6 3.d4 just «Sicilian Defense». + let line = keys(&["e4", "c5", "Nf3", "d6", "d4"]); + let after_d4 = by_position(line[5]).map(|id| get(id).name.clone()); + assert_eq!(after_d4.as_deref(), Some("Sicilian Defense")); + let (at, id) = deepest(&line).expect("named"); + assert_eq!( + (at, get(id).name.as_str()), + (4, "Sicilian Defense: Modern Variations") + ); + assert!(is_prefix_name( + "Sicilian Defense", + "Sicilian Defense: Modern Variations" + )); + assert!(is_prefix_name("A: B", "A: B, C")); + assert!(!is_prefix_name("Sicilian Defense", "Sicilian Defense")); + assert!(!is_prefix_name("English", "English Opening")); + } + + #[test] + fn book_positions_and_keys() { + // The Greco Gambit lines pass 6...Bb4+; 7...d5 is on none of them. + let k = keys(&[ + "e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+", + ]); + assert!( + in_book(k[12]) && by_position(k[12]).is_none(), + "on the way, not named" + ); + let more = keys(&[ + "e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+", + "Nc3", "d5", + ]); + assert!(in_book(more[13]) && !in_book(more[14])); + assert!( + !in_book(k[0]), + "the start position is no move into the book" + ); + // The key is the one the rest of the program uses. + let pos = Chess::default(); + assert_eq!(key(&pos), chess_import::position::key(&pos)); + } +} diff --git a/crates/play/Cargo.toml b/crates/play/Cargo.toml new file mode 100644 index 0000000..9764312 --- /dev/null +++ b/crates/play/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "play" +description = "A game against the computer in ChessPenguin: how it ends, the pause, resignation judged by an engine, Rodent and its files (the desktop and Android apps share it)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +chess-core.workspace = true +shakmaty.workspace = true +uci.workspace = true +getrandom = "0.3" + +# Random numbers in a browser (crypto.getRandomValues). +[target.'cfg(target_family = "wasm")'.dependencies] +getrandom = { version = "0.3", features = ["wasm_js"] } diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs new file mode 100644 index 0000000..dd344bb --- /dev/null +++ b/crates/play/src/lib.rs @@ -0,0 +1,464 @@ +//! A game against the computer (docs/design/play-mode.md, android-play.md §31): how it +//! ends, how long the opponent "thinks", its resignation judged by an engine, and Rodent +//! (`rodent`). Shared by the desktop and the Android apps; nothing here draws. The +//! engines that play or judge run as processes, each driven from a thread: a browser +//! cannot start them. + +pub mod rodent; +mod rodent4_files; + +use std::sync::mpsc::{Receiver, Sender}; +use std::time::Duration; +#[cfg(not(target_family = "wasm"))] +use std::{sync::mpsc::channel, time::Instant}; + +use shakmaty::zobrist::Zobrist64; +use shakmaty::{Chess, Color, EnPassantMode, Position}; + +/// Maia's ratings: what her network was trained on (her own scale, not a person's Elo; +/// decisions «Сила Ñ�оперника — по шкале Ñ�амого движка»). +pub const MAIA_MIN: u32 = 600; +pub const MAIA_MAX: u32 = 2600; + +// ----- the end of a game --------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ending { + Checkmate { + winner: Color, + }, + Stalemate, + InsufficientMaterial, + Threefold, + FiftyMoves, + /// `loser` ran out of time; a draw when the other side cannot mate. + Time { + loser: Color, + draw: bool, + }, + Resigned { + loser: Color, + }, + /// The user offered a draw and Maia accepted. + DrawAgreed, +} + +impl Ending { + pub fn result(self) -> chess_core::GameResult { + use chess_core::GameResult as R; + let win = |c: Color| match c { + Color::White => R::WhiteWins, + Color::Black => R::BlackWins, + }; + match self { + Ending::Checkmate { winner } => win(winner), + Ending::Time { draw: true, .. } => R::Draw, + Ending::Time { loser, .. } | Ending::Resigned { loser } => win(!loser), + Ending::Stalemate + | Ending::InsufficientMaterial + | Ending::Threefold + | Ending::FiftyMoves + | Ending::DrawAgreed => R::Draw, + } + } + + /// The tag `Termination` (as Lichess writes it). + pub fn termination(self) -> &'static str { + match self { + Ending::Time { .. } => "Time forfeit", + _ => "Normal", + } + } +} + +/// How the game stands after the last of `positions` (the positions of the main line +/// from the start): mate, stalemate, no material, threefold repetition, fifty moves. +pub fn ending(positions: &[Chess]) -> Option { + let pos = positions.last()?; + if pos.is_checkmate() { + return Some(Ending::Checkmate { + winner: !pos.turn(), + }); + } + if pos.is_stalemate() { + return Some(Ending::Stalemate); + } + if pos.is_insufficient_material() { + return Some(Ending::InsufficientMaterial); + } + let key = |p: &Chess| p.zobrist_hash::(EnPassantMode::Legal); + let now = key(pos); + // Only positions since the last capture or pawn move can repeat. + let span = (pos.halfmoves() as usize + 1).min(positions.len()); + let repeats = positions[positions.len() - span..] + .iter() + .filter(|p| key(p) == now) + .count(); + if repeats >= 3 { + return Some(Ending::Threefold); + } + if pos.halfmoves() >= 100 { + return Some(Ending::FiftyMoves); + } + None +} + +/// A number in [0, 1). +pub fn random_unit() -> f32 { + let mut b = [0u8; 4]; + let _ = getrandom::fill(&mut b); + (u32::from_le_bytes(b) >> 8) as f32 / (1u32 << 24) as f32 +} + +/// How long Maia "thinks" (it computes in a tenth of a second): about 1/30 of its time +/// plus most of the increment, varied at random; fast in the opening and with one +/// legal move; never so long that it could lose on time (docs/research/play-mode.md R15). +pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Duration { + let r = random_unit(); + // A log-normal-ish factor between 0.4 and 2.5. + let factor = (0.4f32 * (2.5f32 / 0.4).powf(r)).clamp(0.4, 2.5); + let secs = match clock { + None => 0.5 + 1.5 * r, + Some((left, inc)) => { + let left = left.as_secs_f32(); + let inc = inc as f32; + let mut t = (left / 30.0 + 0.75 * inc) * factor; + if ply < 10 { + t *= 0.3; + } + // Never more than a fortieth of the time left plus most of the increment: + // the clock only shrinks geometrically and never runs out, however long the + // game (a move also costs about 0.1 s of computing). + let most = (left / 40.0 + 0.8 * inc).min(60.0); + t.min(most).max(0.4f32.min(most)) + } + }; + let secs = if only_move { + secs.min(0.3 + 0.5 * r) + } else { + secs + }; + Duration::from_secs_f32(secs) +} + +// ----- the game's tags ----------------------------------------------------------------- + +/// The tags of a game against a program (as Lichess writes one): `event` in the app's +/// language, the user's name ("?" unknown) and rating, the program's name with its +/// strength («Maia 1500», «Rodent V 2400 (Tal)»: the engine's own scale, so no Elo tag +/// for it — the owner's decision), the time control in PGN ("-": none). The rest (date, +/// result) is the game's. +pub fn game_tags( + event: &str, + user: Color, + user_name: &str, + user_elo: Option, + program: &str, + time_control: &str, +) -> Vec<(String, String)> { + let maia = program.to_owned(); + let you = if user_name.trim().is_empty() { + "?".to_owned() + } else { + user_name.trim().to_owned() + }; + let (white, black, we, be, wt, bt) = match user { + Color::White => (you, maia, user_elo, None, "human", "program"), + Color::Black => (maia, you, None, user_elo, "program", "human"), + }; + let mut tags = vec![ + ("Event".to_owned(), event.to_owned()), + ("Site".to_owned(), "ChessPenguin".to_owned()), + ("White".to_owned(), white), + ("Black".to_owned(), black), + ]; + if let Some(e) = we { + tags.push(("WhiteElo".to_owned(), e.to_string())); + } + if let Some(e) = be { + tags.push(("BlackElo".to_owned(), e.to_string())); + } + tags.push(("WhiteType".to_owned(), wt.to_owned())); + tags.push(("BlackType".to_owned(), bt.to_owned())); + tags.push(("TimeControl".to_owned(), time_control.to_owned())); + tags +} + +// ----- a draw offered ------------------------------------------------------------------- + +/// Maia's turns whose scores must agree for a level position to be called settled. +pub const DRAW_STABLE_TURNS: usize = 3; +/// She accepts a draw when she is not better by more than this (centipawns)… +const DRAW_MAX_CP: i32 = 20; +/// …the position settled (her last scores no further apart than this)… +const DRAW_SPREAD_CP: i32 = 30; +/// …or at once when she is worse by this much. +const DRAW_WORSE_CP: i32 = -50; +/// After a refusal, her turns before the next offer counts. +pub const DRAW_AGAIN_AFTER: usize = 2; + +/// Whether Maia accepts a draw, from the scores of her latest turns (oldest first, each +/// for her as the side to move): when clearly worse or mated, at once; when about level +/// (at most +0.2 for her), if the game has kept its character — her last three scores +/// within 0.3 of each other. Never when she mates or is better by more. +pub fn accepts_draw(scores: &[uci::Score]) -> bool { + let Some(&last) = scores.last() else { + return false; + }; + match last { + uci::Score::Mate(n) => return n < 0, + uci::Score::Cp(cp) if cp <= DRAW_WORSE_CP => return true, + uci::Score::Cp(cp) if cp > DRAW_MAX_CP => return false, + uci::Score::Cp(_) => {} + } + if scores.len() < DRAW_STABLE_TURNS { + return false; + } + let recent: Option> = scores[scores.len() - DRAW_STABLE_TURNS..] + .iter() + .map(|s| match s { + uci::Score::Cp(cp) => Some(*cp), + uci::Score::Mate(_) => None, + }) + .collect(); + recent.is_some_and(|v| { + let (lo, hi) = (v.iter().min().unwrap(), v.iter().max().unwrap()); + hi - lo <= DRAW_SPREAD_CP + }) +} + +// ----- Maia resigns -------------------------------------------------------------------- + +/// Nodes the judge searches a position: a tenth of a second or two, enough to see that +/// a position is lost by twelve pawns. +pub const JUDGE_NODES: u64 = 150_000; + +/// Maia resigns when her position is worse than this (centipawns) or she is mated… +const HOPELESS_CP: i32 = -1200; +/// …on this many of her turns in a row (one tactic in passing is not a lost game). +pub const HOPELESS_TURNS: u32 = 2; + +/// A position lost for the side to move: twelve pawns down, or mated by force. +pub fn hopeless(score: uci::Score) -> bool { + match score { + uci::Score::Cp(cp) => cp <= HOPELESS_CP, + uci::Score::Mate(n) => n < 0, + } +} + +/// The engine (Stockfish, unseen by the user) judging the positions where Maia is to +/// move, in its own thread for the whole game: the newest request is searched, older +/// ones are dropped; an engine that does not start or dies leaves the game without +/// resignations. +pub struct Judge { + tx: Sender<(u64, uci::EnginePosition)>, + rx: Receiver<(u64, uci::Score)>, + generation: u64, + /// The scores of Maia's turns so far (for a draw offered), oldest first. + scores: Vec, + /// A draw refused when this many scores were in. + refused_at: Option, +} + +impl Judge { + /// The engine of `config` with `options` set (an Android Stockfish: its `EvalFile`); + /// `wake` is called when an answer comes (the app draws again). + /// (A process driven from a thread: not in a browser.) + #[cfg(not(target_family = "wasm"))] + pub fn start( + config: uci::EngineConfig, + options: Vec<(String, String)>, + wake: Box, + ) -> Judge { + let (tx, req_rx) = channel::<(u64, uci::EnginePosition)>(); + let (ans_tx, rx) = channel(); + let _ = std::thread::Builder::new() + .name("maia-judge".into()) + .spawn(move || { + let Ok(engine) = uci::Engine::spawn_with(config, Box::new(|| {})) else { + return; + }; + for (name, value) in &options { + if engine.set_option(name, Some(value)).is_err() { + return; + } + } + let _ = engine.set_threads(1); + let _ = engine.set_hash_mb(16); + let _ = engine.set_multipv(1); + let _ = engine.new_game(); + while let Ok(mut req) = req_rx.recv() { + while let Ok(newer) = req_rx.try_recv() { + req = newer; + } + let (generation, pos) = req; + let id = uci::SearchId(generation); + if engine + .search(pos, id, uci::SearchLimits::Nodes(JUDGE_NODES)) + .is_err() + { + break; + } + let started = Instant::now(); + let mut stopping = false; + let mut last = None; + loop { + if !stopping && started.elapsed() > Duration::from_secs(10) { + let _ = engine.stop(); + stopping = true; + } + match engine.recv_timeout(Duration::from_millis(100)) { + Some(uci::EngineEvent::Info { search_id, info }) if search_id == id => { + if let Some(s) = info.score + && (s.bound == uci::ScoreBound::Exact || last.is_none()) + { + last = Some(s.score); + } + } + Some(uci::EngineEvent::BestMove { search_id, .. }) + if search_id == id => + { + if let Some(score) = last { + if ans_tx.send((generation, score)).is_err() { + engine.quit(); + return; + } + wake(); + } + break; + } + Some(uci::EngineEvent::Terminated(_)) => return, + _ => {} + } + } + } + engine.quit(); + }); + Judge { + tx, + rx, + generation: 0, + scores: Vec::new(), + refused_at: None, + } + } + + /// Judges `pos` (Maia to move); the answer to an older request is dropped. + pub fn ask(&mut self, pos: uci::EnginePosition) { + self.generation += 1; + let _ = self.tx.send((self.generation, pos)); + } + + /// Drops the request in flight: its answer would be about a position gone. + pub fn forget(&mut self) { + self.generation += 1; + } + + /// The score of the position asked last, for the side to move, once it has come. + pub fn answer(&mut self) -> Option { + let mut out = None; + while let Ok((g, s)) = self.rx.try_recv() { + if g == self.generation { + out = Some(s); + } + } + if let Some(s) = out { + self.scores.push(s); + } + out + } + + /// Moves were taken back: the scores of positions gone are forgotten. + pub fn forget_scores(&mut self) { + self.scores.clear(); + self.refused_at = None; + } + + /// A draw may be offered (not right after a refusal: two of her turns later). + pub fn may_offer_draw(&self) -> bool { + self.refused_at + .is_none_or(|n| self.scores.len() >= n + DRAW_AGAIN_AFTER) + } + + /// The user offers a draw: whether Maia accepts (by [`accepts_draw`]). + pub fn offer_draw(&mut self) -> bool { + let yes = accepts_draw(&self.scores); + if !yes { + self.refused_at = Some(self.scores.len()); + } + yes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_engine_has_its_strength_in_its_name_and_no_elo() { + let tags = game_tags("Game", Color::Black, "Roman", Some(1500), "Maia 1550", "-"); + let get = |k: &str| tags.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()); + assert_eq!(get("White"), Some("Maia 1550")); + assert_eq!(get("WhiteElo"), None); + assert_eq!(get("BlackElo"), Some("1500")); + assert_eq!(get("WhiteType"), Some("program")); + } + + #[test] + fn maia_resigns_only_when_hopeless() { + use uci::Score; + assert!(hopeless(Score::Cp(-1200))); + assert!(hopeless(Score::Cp(-3000))); + assert!(!hopeless(Score::Cp(-1199))); + assert!(!hopeless(Score::Cp(900))); + // Mated by force: hopeless; mating: not. + assert!(hopeless(Score::Mate(-3))); + assert!(!hopeless(Score::Mate(2))); + } + + #[test] + fn maia_accepts_a_draw_when_level_and_settled_or_worse() { + use uci::Score::{Cp, Mate}; + // Level and settled: yes; level but just changed: no. + assert!(accepts_draw(&[Cp(10), Cp(-5), Cp(15)])); + assert!(!accepts_draw(&[Cp(-120), Cp(-5), Cp(15)])); + // Too few turns to call it settled. + assert!(!accepts_draw(&[Cp(0), Cp(0)])); + // Better by more than 0.2: no; clearly worse or mated: at once. + assert!(!accepts_draw(&[Cp(25), Cp(25), Cp(25)])); + assert!(accepts_draw(&[Cp(-60)])); + assert!(accepts_draw(&[Mate(-4)])); + assert!(!accepts_draw(&[Mate(3)])); + assert!(!accepts_draw(&[])); + } + + #[test] + fn games_end_as_the_rules_say() { + let line = |moves: &[&str]| { + let mut pos = Chess::default(); + let mut out = vec![pos.clone()]; + for m in moves { + let m = m + .parse::() + .unwrap() + .to_move(&pos) + .unwrap(); + pos.play_unchecked(m); + out.push(pos.clone()); + } + out + }; + assert_eq!( + ending(&line(&["f3", "e5", "g4", "Qh4#"])), + Some(Ending::Checkmate { + winner: Color::Black + }) + ); + assert_eq!(ending(&line(&["e4", "e5"])), None); + let knights = ["Nf3", "Nf6", "Ng1", "Ng8", "Nf3", "Nf6", "Ng1", "Ng8"]; + assert_eq!(ending(&line(&knights)), Some(Ending::Threefold)); + // An untimed game: Maia thinks between half a second and two. + let p = pause(None, 20, false); + assert!(p >= Duration::from_millis(500) && p <= Duration::from_secs(2)); + } +} diff --git a/crates/play/src/rodent.rs b/crates/play/src/rodent.rs new file mode 100644 index 0000000..9341a24 --- /dev/null +++ b/crates/play/src/rodent.rs @@ -0,0 +1,867 @@ +//! Rodent, the opponent with a style (docs/research/rodent.md, docs/design/rodent-opponent.md, +//! android-rodent.md): its styles and characters, its scales of strength, the files of +//! Rodent IV with the books its characters open, and the engine playing a game in a +//! thread of its own. Shared by the desktop and the Android apps; nothing here draws. + +use std::collections::BTreeMap; +use std::time::Duration; +#[cfg(not(target_family = "wasm"))] +use std::{ + sync::mpsc::{Sender, channel}, + sync::{Arc, Condvar, Mutex, MutexGuard}, + time::Instant, +}; + +use shakmaty::Move; + +pub use crate::rodent4_files::{COMMIT, FILES, PERSONALITY_BOOKS}; + +// ----- styles and characters ------------------------------------------------------------- + +/// Rodent's styles: its personality files, the personality's name (for PGN), what the +/// style is called and does (English: the apps translate it). The players' imitations +/// are marked `player`. +pub struct Style { + pub id: &'static str, + pub name: &'static str, + title: &'static str, + pub about: &'static str, + pub player: bool, + /// Which Rodent plays it: V (a personality file of its own) or IV (a personality of + /// its list, `personality`; docs/decisions.md «Rodent IV»). + pub rodent: Gen, + pub personality: &'static str, +} + +impl Style { + /// The style's name to translate («Attacking»). + pub fn title(&self) -> &'static str { + self.title + } +} + +/// Rodent V or Rodent IV: each downloaded on its own, each on its own scale of strength. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Gen { + V, + IV, +} + +impl Gen { + /// «Rodent V», «Rodent IV»: in the game's record and on the bar. + pub fn name(self) -> &'static str { + match self { + Gen::V => "Rodent V", + Gen::IV => "Rodent IV", + } + } + + /// Its UCI_Elo. + pub fn range(self) -> (u32, u32) { + match self { + Gen::V => (RODENT_MIN, RODENT_MAX), + Gen::IV => (RODENT_MIN, RODENT_IV_MAX), + } + } +} + +// Each engine on its own scale, as its authors give it (decisions «Сила Ñ�оперника — по +// шкале Ñ�амого движка»): not a person's Elo. + +/// Rodent's UCI_Elo. +pub const RODENT_MIN: u32 = 800; +pub const RODENT_MAX: u32 = 3000; +/// Rodent IV's UCI_Elo goes to 2800 (and plays at full strength there). +pub const RODENT_IV_MAX: u32 = 2800; + +pub const STYLES: &[Style] = &[ + Style { + id: "rodent", + name: "Rodent", + title: "Balanced", + about: "Even, all-round play with no bias.", + player: false, + rodent: Gen::V, + personality: "", + }, + Style { + id: "ampere", + name: "Ampere", + title: "Attacking", + about: "Active pieces and attack, sound pawn structure.", + player: false, + rodent: Gen::V, + personality: "", + }, + Style { + id: "chaotic", + name: "Chaotic", + title: "Chaotic", + about: "Aggressive, tricky openings, careless with pawns.", + player: false, + rodent: Gen::V, + personality: "", + }, + Style { + id: "nimzoid", + name: "Nimzoid", + title: "Restricting", + about: "Closed positions, cramping the opponent, old openings.", + player: false, + rodent: Gen::V, + personality: "", + }, + Style { + id: "hector", + name: "Hector", + title: "Classical", + about: "Hand-written evaluation, no neural network.", + player: false, + rodent: Gen::V, + personality: "", + }, + Style { + id: "tal_hybrid", + name: "Tal", + title: "Tal", + about: "Attacking style tuned on Tal's games.", + player: true, + rodent: Gen::V, + personality: "", + }, + Style { + id: "tal_nnue", + name: "Tal NNUE", + title: "Tal (network)", + about: "A neural network trained on Tal's games.", + player: true, + rodent: Gen::V, + personality: "", + }, + // Rodent IV's characters, then the players it imitates (its personality list). + Style { + id: "iv_amanda", + name: "Amanda", + title: "Amanda", + about: "Attacks first, then plays for active pieces.", + player: false, + rodent: Gen::IV, + personality: "Amanda", + }, + Style { + id: "iv_cloe", + name: "Cloe", + title: "Cloe", + about: "Likes closed positions.", + player: false, + rodent: Gen::IV, + personality: "Cloe", + }, + Style { + id: "iv_deborah", + name: "Deborah", + title: "Deborah", + about: "Defends well and likes her bishops.", + player: false, + rodent: Gen::IV, + personality: "Deborah", + }, + Style { + id: "iv_defender", + name: "Defender", + title: "Defender", + about: "Solid and careful; content with a draw.", + player: false, + rodent: Gen::IV, + personality: "Defender", + }, + Style { + id: "iv_dynamic", + name: "Dynamic", + title: "Dynamic", + about: "Attacks, likes bishops, sacrifices now and then.", + player: false, + rodent: Gen::IV, + personality: "Dynamic", + }, + Style { + id: "iv_grumpy", + name: "Grumpy", + title: "Grumpy", + about: "Attack and restraint; likes blocked positions, avoids draws.", + player: false, + rodent: Gen::IV, + personality: "Grumpy", + }, + Style { + id: "iv_partisan", + name: "Partisan", + title: "Partisan", + about: "Attacks after quiet, stealthy openings.", + player: false, + rodent: Gen::IV, + personality: "Partisan", + }, + Style { + id: "iv_pawnsacker", + name: "Pawnsacker", + title: "Pawnsacker", + about: "Balanced, but gives up pawns more readily.", + player: false, + rodent: Gen::IV, + personality: "Pawnsacker", + }, + Style { + id: "iv_pedrita", + name: "Pedrita", + title: "Pedrita", + about: "Pawns, defence and restraint.", + player: false, + rodent: Gen::IV, + personality: "Pedrita", + }, + Style { + id: "iv_preston", + name: "Preston", + title: "Preston", + about: "A materialistic, moderate attacker.", + player: false, + rodent: Gen::IV, + personality: "Preston", + }, + Style { + id: "iv_simple", + name: "Simple", + title: "Simple", + about: "The most computer-like: plain, sound chess.", + player: false, + rodent: Gen::IV, + personality: "Simple", + }, + Style { + id: "iv_spitfire", + name: "Spitfire", + title: "Spitfire", + about: "Sharp and aggressive.", + player: false, + rodent: Gen::IV, + personality: "Spitfire", + }, + Style { + id: "iv_strangler", + name: "Strangler", + title: "Strangler", + about: "A boa constrictor: squeezes slowly, very human-like.", + player: false, + rodent: Gen::IV, + personality: "Strangler", + }, + Style { + id: "iv_alekhine", + name: "Alekhine", + title: "Alekhine", + about: "Dynamic attacks and deep combinations.", + player: true, + rodent: Gen::IV, + personality: "Alekhine", + }, + Style { + id: "iv_anand", + name: "Anand", + title: "Anand", + about: "Quick, universal play with sharp openings.", + player: true, + rodent: Gen::IV, + personality: "Anand", + }, + Style { + id: "iv_anderssen", + name: "Anderssen", + title: "Anderssen", + about: "A romantic attacker of the 19th century: sacrifices.", + player: true, + rodent: Gen::IV, + personality: "Anderssen", + }, + Style { + id: "iv_bosboom", + name: "Bosboom", + title: "Bosboom", + about: "Offbeat openings and creative blitz play.", + player: true, + rodent: Gen::IV, + personality: "Bosboom.txt", + }, + Style { + id: "iv_botvinnik", + name: "Botvinnik", + title: "Botvinnik", + about: "Scientific, strategic play from deep preparation.", + player: true, + rodent: Gen::IV, + personality: "Botvinnik", + }, + Style { + id: "iv_fischer", + name: "Fischer", + title: "Fischer", + about: "Clear, classical and precise.", + player: true, + rodent: Gen::IV, + personality: "Fischer", + }, + Style { + id: "iv_karpov", + name: "Karpov", + title: "Karpov", + about: "Positional squeeze, prophylaxis and technique.", + player: true, + rodent: Gen::IV, + personality: "Karpov", + }, + Style { + id: "iv_kasparov", + name: "Kasparov", + title: "Kasparov", + about: "Initiative and powerful attack.", + player: true, + rodent: Gen::IV, + personality: "Kasparov", + }, + Style { + id: "iv_kortchnoi", + name: "Kortchnoi", + title: "Kortchnoi", + about: "A tenacious defender and counter-attacker.", + player: true, + rodent: Gen::IV, + personality: "Kortchnoi", + }, + Style { + id: "iv_larsen", + name: "Larsen", + title: "Larsen", + about: "Original and risky, with offbeat openings.", + player: true, + rodent: Gen::IV, + personality: "Larsen", + }, + Style { + id: "iv_lasker", + name: "Lasker", + title: "Lasker", + about: "A practical, psychological fighter.", + player: true, + rodent: Gen::IV, + personality: "Lasker", + }, + Style { + id: "iv_marshall", + name: "Marshall", + title: "Marshall", + about: "A swashbuckling attacker with gambits.", + player: true, + rodent: Gen::IV, + personality: "Marshall", + }, + Style { + id: "iv_morphy", + name: "Morphy", + title: "Morphy", + about: "Quick development and open lines.", + player: true, + rodent: Gen::IV, + personality: "Morphy", + }, + Style { + id: "iv_nimzowitsch", + name: "Nimzowitsch", + title: "Nimzowitsch", + about: "Restraint, blockade and overprotection.", + player: true, + rodent: Gen::IV, + personality: "Nimzowitsch", + }, + Style { + id: "iv_petrosian", + name: "Petrosian", + title: "Petrosian", + about: "Prophylaxis and safety first.", + player: true, + rodent: Gen::IV, + personality: "Petrosian", + }, + Style { + id: "iv_reti", + name: "Reti", + title: "Reti", + about: "Hypermodern: controls the centre from afar.", + player: true, + rodent: Gen::IV, + personality: "Reti", + }, + Style { + id: "iv_rubinstein", + name: "Rubinstein", + title: "Rubinstein", + about: "Classical positional play, great in endgames.", + player: true, + rodent: Gen::IV, + personality: "Rubinstein", + }, + Style { + id: "iv_spassky", + name: "Spassky", + title: "Spassky", + about: "A universal player, at home in any position.", + player: true, + rodent: Gen::IV, + personality: "Spassky", + }, + Style { + id: "iv_steinitz", + name: "Steinitz", + title: "Steinitz", + about: "The founder of positional play, a stubborn defender.", + player: true, + rodent: Gen::IV, + personality: "Steinitz", + }, + Style { + id: "iv_tal", + name: "Tal", + title: "Tal (classic)", + about: "The magician from Riga: sacrifices and attack.", + player: true, + rodent: Gen::IV, + personality: "Tal", + }, + Style { + id: "iv_tarrasch", + name: "Tarrasch", + title: "Tarrasch", + about: "Classical rules: space, development, active pieces.", + player: true, + rodent: Gen::IV, + personality: "Tarrasch", + }, + Style { + id: "iv_topalov", + name: "Topalov", + title: "Topalov", + about: "Aggressive and dynamic, sacrifices the exchange.", + player: true, + rodent: Gen::IV, + personality: "Topalov", + }, +]; + +/// The style of this id (the default one for an unknown id). +pub fn style(id: &str) -> &'static Style { + STYLES.iter().find(|s| s.id == id).unwrap_or(&STYLES[0]) +} + +/// Rodent IV's character of this id (Tal for an unknown one, or one of Rodent V: a +/// phone has Rodent IV only, android-rodent.md §7.1). +pub fn iv_style(id: &str) -> &'static Style { + STYLES + .iter() + .find(|s| s.id == id && s.rodent == Gen::IV) + .unwrap_or_else(|| style("iv_tal")) +} + +/// Rodent as a game names it: «Rodent V 2400» (the default style unnamed), «Rodent V 2400 +/// (Tal)», «Rodent IV 1800 (Tal)» — the personality's English name: PGN is not translated. +pub fn name(strength: u32, style_id: &str) -> String { + let st = style(style_id); + if st.id == STYLES[0].id { + format!("{} {strength}", st.rodent.name()) + } else { + format!("{} {strength} ({})", st.rodent.name(), st.name) + } +} + +// ----- Rodent IV's files --------------------------------------------------------------- + +/// Books three personalities name by a path not in the authors' files (a case or a dash +/// off): they are read under that name (the engine takes books only from the +/// personality's file). (file in the repository, name it is read by) +pub const BOOK_NAMES: &[(&str, &str)] = &[ + ("books/guide/Strangler.bin", "books/guide/strangler.bin"), + ( + "books/players/ph-spassky2.bin", + "books/players/ph_spassky2.bin", + ), + ("books/guide.bin", "books/guide/guide.bin"), +]; + +/// A path of the repository as it goes into a URL («#readme.txt» has a «#»). +pub fn url_path(path: &str) -> String { + path.replace('#', "%23").replace(' ', "%20") +} + +/// Where a file of the authors' repository is downloaded from (at `COMMIT`). +pub fn file_url(path: &str) -> String { + format!( + "https://raw.githubusercontent.com/nescitus/rodent-iv/{COMMIT}/{}", + url_path(path) + ) +} + +/// An opening book of Rodent IV to download: its file in the authors' repository, where +/// the engine reads it (relative to its home folder), its size and SHA-256. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Book { + pub file: &'static str, + pub local: String, + pub size: u64, + pub sha256: &'static str, +} + +/// The books Rodent IV's characters open (the guide and the main book of each), each +/// once, under the name it is read by: the phone's book pack (android-rodent.md §5), not +/// the books nobody uses. +pub fn book_pack() -> Vec { + let mut books = BTreeMap::new(); + for st in STYLES.iter().filter(|s| s.rodent == Gen::IV) { + let Some(&(_, guide, main)) = PERSONALITY_BOOKS.iter().find(|p| p.0 == st.personality) + else { + continue; + }; + for book in [guide, main] { + let local = format!("books/{book}"); + let file = BOOK_NAMES + .iter() + .find(|(_, name)| *name == local) + .map_or(local.as_str(), |(file, _)| file); + if let Some(&(file, size, sha256)) = FILES.iter().find(|f| f.0 == file) { + books.entry(local.clone()).or_insert(Book { + file, + local, + size, + sha256, + }); + } + } + } + books.into_values().collect() +} + +// ----- Rodent playing a game ----------------------------------------------------------- + +/// Why Rodent does not play. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Failure { + /// It did not start, or did not take its options (the engine's words). + Start(String), + /// Its process ended during the game. + Stopped, + /// A search could not be asked for (the engine's words). + Search(String), +} + +#[cfg(not(target_family = "wasm"))] +/// A move asked for: the game for the engine, its position now, the pause. +struct Request { + generation: u64, + pos: uci::EnginePosition, + now: shakmaty::Chess, + pause: Duration, +} + +/// Rodent's move, or none (no legal move it gave), and the time it took. +pub type Answer = (Option, Duration); + +#[cfg(not(target_family = "wasm"))] +#[derive(Default)] +struct State { + /// The request asked last (bumped by `forget`). + generation: u64, + /// The newest request answered or passed over, and the answer of the newest. + answered: u64, + answer: Option<(u64, Answer)>, + failure: Option, +} + +#[cfg(not(target_family = "wasm"))] +#[derive(Default)] +struct Shared { + state: Mutex, + changed: Condvar, +} + +#[cfg(not(target_family = "wasm"))] +impl Shared { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn fail(&self, f: Failure) { + self.lock().failure = Some(f); + self.changed.notify_all(); + } +} + +#[cfg(not(target_family = "wasm"))] +/// Rodent playing one game, in its own thread (a UCI child process): it thinks during +/// the pause a move should take (a game's own clock is not its business: Maia's pause +/// rule paces it) and answers after it. Only the newest request counts; the answer to +/// an older one (after a take-back) is dropped. +pub struct RodentPlayer { + tx: Sender, + shared: Arc, +} + +#[cfg(not(target_family = "wasm"))] +impl RodentPlayer { + /// The engine of `config` (its folder, or its home in the environment: Android) + /// playing `style_id` at `uci_elo` (none: full strength), with its opening book when + /// `use_book`. `wake` is called when an answer or a failure comes (the app draws again). + pub fn start( + config: uci::EngineConfig, + style_id: &str, + uci_elo: Option, + use_book: bool, + wake: Box, + ) -> RodentPlayer { + let (tx, rx) = channel::(); + let shared = Arc::new(Shared::default()); + let sh = shared.clone(); + let st = style(style_id); + let _ = std::thread::Builder::new() + .name("rodent".into()) + .spawn(move || { + let fail = |f: Failure| { + sh.fail(f); + wake(); + }; + let engine = match uci::Engine::spawn_with(config, Box::new(|| {})) { + Ok(e) => e, + Err(e) => return fail(Failure::Start(e.to_string())), + }; + // V reads a personality file; IV picks one of its list (with its books). + let book = use_book.to_string(); + let mut setup = match st.rodent { + Gen::V => vec![ + ("PersonalityFile", format!("personalities/{}.txt", st.id)), + ("OwnBook", book), + ], + Gen::IV => vec![ + ("Personality", st.personality.to_owned()), + ("UseBook", book), + ], + }; + if let Some(elo) = uci_elo { + setup.push(("UCI_LimitStrength", "true".to_owned())); + setup.push(("UCI_Elo", elo.to_string())); + } + let ready = engine.set_threads(1).and_then(|()| engine.set_hash_mb(64)); + if let Err(e) = ready { + return fail(Failure::Start(e.to_string())); + } + for (name, value) in &setup { + if let Err(e) = engine.set_option(name, Some(value)) { + return fail(Failure::Start(e.to_string())); + } + } + let _ = engine.new_game(); + while let Ok(mut r) = rx.recv() { + while let Ok(newer) = rx.try_recv() { + r = newer; + } + let started = Instant::now(); + let id = uci::SearchId(r.generation); + // Its own limit (from UCI_Elo) ends the search early; at full strength + // it thinks for the pause. + let think = r.pause.max(Duration::from_millis(300)); + if let Err(e) = engine.search(r.pos, id, uci::SearchLimits::MoveTime(think)) { + return fail(Failure::Search(e.to_string())); + } + let mut stopped: Option = None; + let best = loop { + match engine.recv_timeout(Duration::from_millis(200)) { + Some(uci::EngineEvent::BestMove { + search_id, best: b, .. + }) if search_id == id => break b, + Some(uci::EngineEvent::Terminated(_)) => { + return fail(Failure::Stopped); + } + // A search that does not end: stopped, then given up on. + _ => match stopped { + None if started.elapsed() > think + Duration::from_secs(20) => { + let _ = engine.stop(); + stopped = Some(Instant::now()); + } + Some(t) if t.elapsed() > Duration::from_secs(5) => { + return fail(Failure::Stopped); + } + _ => {} + }, + } + }; + let m = best + .and_then(|b| b.parse::().ok()) + .and_then(|u| u.to_move(&r.now).ok()); + std::thread::sleep(r.pause.saturating_sub(started.elapsed())); + let spent = r.pause.max(started.elapsed()); + { + let mut s = sh.lock(); + s.answered = s.answered.max(r.generation); + s.answer = Some((r.generation, (m, spent))); + } + sh.changed.notify_all(); + wake(); + } + engine.quit(); + }); + RodentPlayer { tx, shared } + } + + /// Asks for a move in `now` (`pos`: the game to it for the engine) after `pause`; + /// the request's number, for [`RodentPlayer::wait`]. + pub fn ask(&self, pos: uci::EnginePosition, now: shakmaty::Chess, pause: Duration) -> u64 { + let generation = { + let mut s = self.shared.lock(); + s.generation += 1; + s.generation + }; + let _ = self.tx.send(Request { + generation, + pos, + now, + pause, + }); + generation + } + + /// Forgets what was asked (its answer will be dropped; a wait for it ends). + pub fn forget(&self) { + self.shared.lock().generation += 1; + self.shared.changed.notify_all(); + } + + /// The answer to the request asked last, once it has come (given once). + pub fn answer(&self) -> Option { + let mut s = self.shared.lock(); + let generation = s.generation; + match s.answer { + Some((g, _)) if g == generation => s.answer.take().map(|(_, a)| a), + _ => None, + } + } + + /// Waits for the answer to request `generation`: none when it was forgotten or + /// passed over by a newer one, or Rodent failed. + pub fn wait(&self, generation: u64) -> Option { + let mut s = self.shared.lock(); + while s.generation == generation && s.answered < generation && s.failure.is_none() { + s = self + .shared + .changed + .wait(s) + .unwrap_or_else(|e| e.into_inner()); + } + match s.answer { + Some((g, _)) if g == generation && s.generation == generation => { + s.answer.take().map(|(_, a)| a) + } + _ => None, + } + } + + /// Why Rodent does not play, if it does not. + pub fn failure(&self) -> Option { + self.shared.lock().failure.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_file_is_where_the_engine_looks_for_it() { + assert_eq!(COMMIT.len(), 40); + assert!(FILES.iter().any(|f| f.0 == "personalities/basic.ini")); + assert!(FILES.iter().any(|f| f.0 == "personalities/tal.txt")); + assert!(FILES.iter().any(|f| f.0 == "books/rodent.bin")); + assert!(FILES.iter().all(|f| f.2.len() == 64 && !f.0.contains(".."))); + assert_eq!(url_path("books/#readme.txt"), "books/%23readme.txt"); + // The books read under another name are in the authors' files. + for (file, _) in BOOK_NAMES { + assert!(FILES.iter().any(|f| f.0 == *file), "{file}"); + } + } + + #[test] + fn the_pack_has_the_books_of_every_character_and_no_other() { + let pack = book_pack(); + let has = |local: &str| pack.iter().any(|b| b.local == local); + let iv: Vec<&Style> = STYLES.iter().filter(|s| s.rodent == Gen::IV).collect(); + assert_eq!(iv.len(), 35); + for st in iv { + let (_, guide, main) = PERSONALITY_BOOKS + .iter() + .find(|p| p.0 == st.personality) + .unwrap_or_else(|| panic!("no books for {}", st.personality)); + assert!(has(&format!("books/{guide}")), "{guide}"); + assert!(has(&format!("books/{main}")), "{main}"); + } + // The three named otherwise come from their files in the repository. + let spassky = pack + .iter() + .find(|b| b.local == "books/players/ph_spassky2.bin") + .unwrap(); + assert_eq!(spassky.file, "books/players/ph-spassky2.bin"); + assert!(has("books/guide/strangler.bin") && has("books/guide/guide.bin")); + // Nobody's books stay out: 59 MB of the 69. + assert!(!has("books/guide/ph-exoticbook.bin")); + let total: u64 = pack.iter().map(|b| b.size).sum(); + assert_eq!((total + 500_000) / 1_000_000, 59); + assert!( + file_url(spassky.file).ends_with(&format!("/{COMMIT}/books/players/ph-spassky2.bin")) + ); + } + + #[test] + fn rodent_is_named_with_its_strength_and_personality() { + assert_eq!(name(1800, "iv_tal"), "Rodent IV 1800 (Tal)"); + assert_eq!(name(2400, "rodent"), "Rodent V 2400"); + assert_eq!(name(2400, "tal_hybrid"), "Rodent V 2400 (Tal)"); + assert_eq!(style("iv_spassky").rodent.range(), (800, 2800)); + // An unknown style (of a later version) is the default one; of Rodent IV, Tal. + assert_eq!(style("nobody").id, "rodent"); + assert_eq!(iv_style("nobody").id, "iv_tal"); + assert_eq!(iv_style("ampere").id, "iv_tal"); + assert_eq!(iv_style("iv_karpov").id, "iv_karpov"); + } + + /// Needs Rodent IV and its files: `RODENT4=/path/rodent_iv cargo test -p play -- --ignored` + /// (the folder of the executable has `personalities/` and `books/`). + #[test] + #[ignore = "needs Rodent IV (RODENT4)"] + fn rodent_answers_the_newest_request_only() { + let exe = std::env::var("RODENT4").expect("RODENT4"); + let player = RodentPlayer::start( + uci::EngineConfig::new(exe), + "iv_tal", + Some(1800), + true, + Box::new(|| {}), + ); + let start = || uci::EnginePosition::startpos(Vec::::new()); + let pause = Duration::from_millis(400); + // Asked twice: the first is passed over, the second answered with a legal move. + let first = player.ask(start(), shakmaty::Chess::default(), pause); + let second = player.ask(start(), shakmaty::Chess::default(), pause); + assert_eq!(player.wait(first), None); + let (m, spent) = player.wait(second).expect("an answer"); + assert!(m.is_some(), "{:?}", player.failure()); + assert!(spent >= pause); + // A request forgotten ends its wait at once. + let third = player.ask(start(), shakmaty::Chess::default(), pause); + player.forget(); + assert_eq!(player.wait(third), None); + assert_eq!(player.failure(), None); + } +} diff --git a/crates/play/src/rodent4_files.rs b/crates/play/src/rodent4_files.rs new file mode 100644 index 0000000..aaf115f --- /dev/null +++ b/crates/play/src/rodent4_files.rs @@ -0,0 +1,499 @@ +//! Generated by scripts/rodent4-manifest.py: the personalities and opening books of +//! Rodent IV as they are in the authors' repository at `COMMIT`, with their sizes and +//! SHA-256 (each is checked as it is downloaded). + +pub const COMMIT: &str = "e8d84c8c8c189a1cf4eb27c578fc573af3b916d2"; + +/// (path in the repository, bytes, SHA-256). +pub const FILES: &[(&str, u64, &str)] = &[ + ( + "books/#readme.txt", + 190, + "48d94c1e55cb6f98476bccaf9432166d3bb07aea664bf595c4b85a65ef43a714", + ), + ( + "books/guide.bin", + 3056, + "168abc6dc0af6cf5c1719403e51e367cc56c5929531c8f35b8000dcda0de84ba", + ), + ( + "books/guide/#readme.txt", + 1263, + "7a73f72ac924f4988b88da2ea6ad3168c99107202a690905e011b0f3e66f1875", + ), + ( + "books/guide/Strangler.bin", + 10144, + "35303138aacbea4ce768414f4b7c709e5705e7d17f57a487136d6575634dfbf1", + ), + ( + "books/guide/active.bin", + 298368, + "4ce06ffe8208ea462623d4aa2cd76e5fffb43fee568eec926dda58c49de39a74", + ), + ( + "books/guide/cat.bin", + 3280, + "6b38a429a10d9214b2bef03ddff3f1d07ba29486e47d2b23a52ca256b7af4929", + ), + ( + "books/guide/closed.bin", + 1312, + "eb663e1ed1e6cffbfcc33f2aed8b080df70dd6fe3e0f549a3ad20938f37f2da6", + ), + ( + "books/guide/cs.bin", + 4336, + "ea213e6c49e32b0b0e6ab1ce48b91fff354a05893d3a7fcaef595c1b82c8ee32", + ), + ( + "books/guide/empty.bin", + 16, + "60c69a3e87bf5c4f1e546bec45f262690bcf5494c4ecac2616bf2f731afa152a", + ), + ( + "books/guide/exchange.bin", + 1824, + "98b191cbb8426bf4098c7330861d441315687325e5f27d7f9dc623c163c2ff39", + ), + ( + "books/guide/flank.bin", + 186144, + "da019cc249e2f5e9559067faa7cbfeadde405cdd5f77dabd8059589329d88243", + ), + ( + "books/guide/grandpa.bin", + 11584, + "2c2d177e4695e32e22915dc4d2d624e834d59a75aef889f9a3d2190b6d9de71e", + ), + ( + "books/guide/low.bin", + 2432, + "549b341172c980aa7b47750b8caafa9e5e4df8161f9e9a3ae84df65a7db135a5", + ), + ( + "books/guide/ph-exoticbook.bin", + 9361568, + "fa0f55de6bd345521633f1ad0f3171823f4ff36c8784b123c9963278bc0cac13", + ), + ( + "books/guide/ph-gambitbook.bin", + 8407936, + "f2dddc37343b155624fddb08a7743965e806b717ac87985f887643e126119f14", + ), + ( + "books/guide/simple.bin", + 1136, + "5c5655286dfb7828ecdc516ec5a04bc7ff82ee6d4d6d3b1e6737eea0a2a3f01c", + ), + ( + "books/guide/solid.bin", + 702704, + "b6ed13b48ede300b9c33944e12d899daaab1fc120d129379bfe234f2f65dffc8", + ), + ( + "books/guide/tricky.bin", + 236128, + "ea008c67e321c3460298777be6b4ad6d21384589c148bec16c8295b84870ab63", + ), + ( + "books/hist/#readme.txt", + 285, + "7997dfcd3f1f1afd8da16ddddada703eca0a74c0e57b7ef7357e90f075c0b6e3", + ), + ( + "books/hist/_31to80.bin", + 588640, + "c51764eab0ad6ab0659c6aba8bdfa7cec930e88dfc5887efce1e31a5ca80e81f", + ), + ( + "books/hist/_81to06.bin", + 1393952, + "ddd3fe064d17ee52e6653dbafbd6280d2d85f09da50352366c3515585c0c8d19", + ), + ( + "books/hist/_post06.bin", + 1474384, + "b3b1fb48054e4737b80acebe8851c152188243439bc7194b3faa01be85116ee9", + ), + ( + "books/hist/_pre30.bin", + 169856, + "77aeca2bd8ee5996cd95683531f008b4e038c6f8a1d41550d5b02c73d4f17257", + ), + ( + "books/main/micro.bin", + 76400, + "40b063b1a2dfff9964b3e43f76e321863a3bc40d79c9ec71d604116d5cb0fb0e", + ), + ( + "books/main/mini.bin", + 154576, + "cde1a83f2f8d067920d9bd63bd6e66840ec8b74b4e85ed43b26e3dfcb5c0ba1d", + ), + ( + "books/main/small.bin", + 311296, + "ef9c73df2d1df15cfd70bea5f6ed074298a583fb2248a2ea626f008bbad55148", + ), + ( + "books/players/#readme.txt", + 908, + "fb5a69bee93feec68ee8ca24a86f7877b008a01b8438ffe5d0ae8f6874a387ad", + ), + ( + "books/players/bn-bosboom.bin", + 538960, + "c75133dc14d07034d73e7faace7adbe6a2f8ea3a5b55ff6e2f3b6cd8b3c13b48", + ), + ( + "books/players/morphy.bin", + 1440, + "57e6e7619ac7647acaf561e0ebc2f065c32835cadca2029386ea4bbb347f58b0", + ), + ( + "books/players/nimzowitsch.bin", + 261040, + "64f43e651515f68c5a8e5eb1c970cfc6b49b47e30abf3a078659b5465bf79459", + ), + ( + "books/players/petrosian.bin", + 850048, + "0393a98eaa0a86203066494447d9a90255518499ba702933118b72af281a364e", + ), + ( + "books/players/ph-anand2.bin", + 1998384, + "ca5d7a52b33f78e857fb44f6157ac83b943dcd2e36c630c77e107a7c8d5f94ad", + ), + ( + "books/players/ph-anderssen2.bin", + 8539632, + "7edf078361d6462584107b0b37d9c24ee6dec297936bacc6f4085069687256eb", + ), + ( + "books/players/ph-botvinnik2.bin", + 1764656, + "dd041dad209ae2278f94ea3bd3d59aa280b07ee5b6f5e856aef87cb800bdd7e7", + ), + ( + "books/players/ph-fischer2.bin", + 1728896, + "1b8bc31b15a135c0cef705e633524583cea304f4c44cf705bb7b0a58d0be1279", + ), + ( + "books/players/ph-karpov2.bin", + 2287088, + "aed5d14526826482414ae9a8334cf84ee812de6da01e9f50ad14b48d3ebd7668", + ), + ( + "books/players/ph-larsen2.bin", + 2086640, + "c88749872fa2d8f99b699d21c30e8e4b61b1a5cd84feef9eebd3354be70f37c3", + ), + ( + "books/players/ph-lasker2.bin", + 1752464, + "7c11cc10212424fb8dd24da6e6e4fabdb6f9689d5e0eb9cd4c8d7b7494a44ef9", + ), + ( + "books/players/ph-reti2.bin", + 1644768, + "50837dc5bed4f94a35449732c676dba3bafde132b219b63ea683b1159988f9f2", + ), + ( + "books/players/ph-rubinstein2.bin", + 1705984, + "3dd2f06df72c2666d37ef3e397bec296add5d4e3de45bfeed6c07823de21cb36", + ), + ( + "books/players/ph-spassky2.bin", + 2021984, + "d0c981ea25e3ab6e48984bcdd587e74d08aa6bced545b15b0d4cf3d29b8e2e3b", + ), + ( + "books/players/ph-tal2.bin", + 2062464, + "2e7923a363a4d24fa10cda6991dc5c289cde57d536b358b45b29a157690c9c04", + ), + ( + "books/players/ph-tarrasch2.bin", + 1677472, + "16954ddd54e2aa82dddd418fba651a6f19052205d7aa203fe9d6098a60c700b4", + ), + ( + "books/players/ph-topalov2.bin", + 1828864, + "5a07a21d75424b59b7c1a51387868bbd0f55cf0e3eb83d223b9f0bdac410dfdf", + ), + ( + "books/players/rj-alekhine.bin", + 865072, + "df46561ddcd723f3f01fc7c6fbab290b0c9eb2a3594a87c79eadbd87fdcc2737", + ), + ( + "books/players/rj-kasparov.bin", + 1617072, + "06e06f3b061f31002a58a39ddf26a9fd5064b827522b06cedde25198d54d9d45", + ), + ( + "books/players/rj-kortchnoi.bin", + 135424, + "4e2ff5a5be4aee43c56998015cc800f3537d16371dfab4be3726734b252727c9", + ), + ( + "books/players/rj-marshall.bin", + 300688, + "c11f9dab58a0ef1efe655ca92ef010b4384e819affc7116c6ba110f33622312c", + ), + ( + "books/players/steinitz.bin", + 81280, + "14d96f0b54b578bdead1cd214bc8fc6442f5a09a7a99f3a9ea129f47df17aa2b", + ), + ( + "books/rodent.bin", + 10179008, + "4a65869ba4081398bfa0804b953502352815dcfae49ad5af9726a69d46047786", + ), + ( + "personalities/alekhine.txt", + 3517, + "3d618e0a35cbcdc2467f5f114790646fe40050bea78c62c5520e888a02553bb8", + ), + ( + "personalities/amanda.txt", + 2510, + "ff04a71cd2f1eb626d8805d37f2dd3a6904d93a1c93c5290553431453fea26b6", + ), + ( + "personalities/ampere.txt", + 2498, + "a9ce7312c0fb8f3b0c46e3ff58e79cb10a6fd092f1cb69c480e102461861e912", + ), + ( + "personalities/anand.txt", + 3366, + "f01b264bf221118af21f8576c8234fc7259ee32b008d7f604764f14abd38965a", + ), + ( + "personalities/anderssen.txt", + 3274, + "5d4235febae596783c0d68c2567900440addfebf6697c48ad5d0ada2eb94cceb", + ), + ( + "personalities/basic.ini", + 2719, + "abe0ebe031c00009d3d3bbce7daf218e54f0422a8e6ded3c29d6e9c3350551bd", + ), + ( + "personalities/bosboom.txt", + 2904, + "172d473052ee04141235b90bceb2eace235c1c33f7c46aae292a22ceeebbaa85", + ), + ( + "personalities/botvinnik.txt", + 3385, + "e4de674084b289e6a5eca65edce542c948e3e75ffa25c155c7af56069ff8816e", + ), + ( + "personalities/cloe.txt", + 2483, + "dfe5a303071440c531b91437d81a47a0be1d51b4e63bdeb64794a7c2d4f504a9", + ), + ( + "personalities/deborah.txt", + 2489, + "7d2203efdd3972a1b9bd836dc9237121873de26200f515378bc24850446f85f7", + ), + ( + "personalities/default.txt", + 1091, + "1470a3e385b26efdd37d7ba30aae50e008a35eea78f03f683db82d02d1a2df2e", + ), + ( + "personalities/defender.txt", + 2455, + "7b0d1e377d0862d18f8101e2068eed8486558416997fe596c42f589c525aae7c", + ), + ( + "personalities/dynamic.txt", + 2543, + "1edd02be3baddba2f5056db8fdabfe549488c0f9832e553677227e98b3a0f404", + ), + ( + "personalities/fischer.txt", + 3333, + "ee2ab4e175f0dbee88f2f12595393d14001915670e086198139d15ad86eae577", + ), + ( + "personalities/grumpy.txt", + 2531, + "0ff254a3439d947756fdf748b94fcceb82cc202b46ded10e839a7204fbce3c03", + ), + ( + "personalities/karpov.txt", + 2893, + "9ea8a26ddd30ebb7085193d2c94119bdeb9535cd7b43a283741ad27244c78aee", + ), + ( + "personalities/kasparov.txt", + 2949, + "0167481c1a12c5ee50dcaae8d9a5de80ca5baccb44114e603ae8395cd4244f43", + ), + ( + "personalities/kortchnoi.txt", + 3084, + "36fa917d841447df9aa2168f4f736c80d1506afe270c015ceba6a013c80802ad", + ), + ( + "personalities/larsen.txt", + 3430, + "e0ae364f22630da9bfbe4a415ad05555a19c526a8efba2e0e716c23b603bc60b", + ), + ( + "personalities/lasker.txt", + 2850, + "2f522070cc68bede8c77d6e7040939c0ba24aba7017988d417b37ec9a424c388", + ), + ( + "personalities/marshall.txt", + 2960, + "38dfc223a8067f5a041e011c25c914e56bebbfd78e0dc10648c6a73a228f5711", + ), + ( + "personalities/morphy.txt", + 2486, + "8e6d9aa1658deda43c280bef69ec6e0914c883e57f118a22c7a5edbe7cfef7de", + ), + ( + "personalities/nimzowitsch.txt", + 2475, + "53b1825b4dd6ea709b5fcfc401ce9ab920ffcd03b9e54936e8fa3c36812ceae1", + ), + ( + "personalities/partisan.txt", + 2504, + "483d94226b4d5b42105db4c28c0f078ae096a6f26777ee558e5c7afabc8730fe", + ), + ( + "personalities/pawnsacker.txt", + 2563, + "bf92b869e67fce75d967f8c385787ef52ac62ffa612917184d7b6f75caff7941", + ), + ( + "personalities/pedrita.txt", + 2482, + "3f9858b2e7912e666d4b48b6f6509d712b63428db06902b83e45aadef2988ad3", + ), + ( + "personalities/petrosian.txt", + 3350, + "e4558a9035d0e21afa9bbd453f5ded76d22fb274ca39889cf2163d7472879ef4", + ), + ( + "personalities/preston.txt", + 2487, + "a232ea602749587fbd15889a8948403c5ac2687234caca538d3aa6b641741944", + ), + ( + "personalities/reti.txt", + 3327, + "8d15e479e118903309afe215cd070faaa2e4337b2b62809a26476113a9469d20", + ), + ( + "personalities/rubinstein.txt", + 3384, + "efb9dda6d01b824ba39260881deb18a22c22774d7946eeb6adbd3d4d4c18ca39", + ), + ( + "personalities/simple.txt", + 2510, + "19f83fb05f96039a34e0e9a36bf66fc841693f70d73ee2a243df42e90caf1613", + ), + ( + "personalities/spassky.txt", + 3347, + "000da9c591c8e63fe5e4b11c812c42d3e700032e034f75934d67faba089b4bbd", + ), + ( + "personalities/spitfire.txt", + 2448, + "5b42cac56aa4fbab4b6dff48e86fbfec8744e27bb310475b9bc9e91746e519f6", + ), + ( + "personalities/steinitz.txt", + 2572, + "f7ab0efd23c94f96f025104dc82eab993163d7a7523cab8b612add1d85d1b338", + ), + ( + "personalities/strangler.txt", + 2526, + "3ed1809e19ba622c165b9fbf8eb10f056a3acbb3a0ee2a4c32b9488919d85409", + ), + ( + "personalities/swapper.txt", + 2513, + "d1b8ec5e016452f002609c32bc575fb9ee47ba4e0db671f82215009c731187fc", + ), + ( + "personalities/tal.txt", + 2459, + "f6b58d7cc9e7d2fcdbbc24a20ea72035d05ca5ed5e3401bda240b1b298ce149d", + ), + ( + "personalities/tarrasch.txt", + 2546, + "6fafaf4cb8ec37439c2471a26b9be471a35d5e14faf1a624bb2fe9edb6f3f496", + ), + ( + "personalities/topalov.txt", + 3358, + "0e5a9fc33d3ade50d7eaa68a06d29131151d270d5d0f3afd5d408bfb9081e4d8", + ), +]; + +/// The personalities of the engine's list: (name, guide book, main book), the books +/// as the personality's file names them (under `books/`). +pub const PERSONALITY_BOOKS: &[(&str, &str, &str)] = &[ + ("Alekhine", "players/rj-alekhine.bin", "hist/_pre30.bin"), + ("Amanda", "guide/ph-gambitbook.bin", "rodent.bin"), + ("Ampere", "guide/active.bin", "rodent.bin"), + ("Anand", "players/ph-anand2.bin", "hist/_post06.bin"), + ("Anderssen", "players/ph-anderssen2.bin", "hist/_pre30.bin"), + ("Bosboom.txt", "players/bn-bosboom.bin", "hist/_post06.bin"), + ("Botvinnik", "players/ph-botvinnik2.bin", "hist/_31to80.bin"), + ("Cloe", "guide/closed.bin", "rodent.bin"), + ("Deborah", "guide/guide.bin", "rodent.bin"), + ("Defender", "guide/solid.bin", "rodent.bin"), + ("Dynamic", "guide/active.bin", "rodent.bin"), + ("Fischer", "players/ph-fischer2.bin", "hist/_31to80.bin"), + ("Grumpy", "guide/grandpa.bin", "rodent.bin"), + ("Karpov", "players/ph-karpov2.bin", "hist/_81to06.bin"), + ("Kasparov", "players/rj-kasparov.bin", "hist/_81to06.bin"), + ("Kortchnoi", "players/rj-kortchnoi.bin", "hist/_31to80.bin"), + ("Larsen", "players/ph-larsen2.bin", "hist/_31to80.bin"), + ("Lasker", "players/ph-lasker2.bin", "hist/_pre30.bin"), + ("Marshall", "players/rj-marshall.bin", "hist/_pre30.bin"), + ("Morphy", "players/morphy.bin", "hist/_pre30.bin"), + ("Nimzowitsch", "players/nimzowitsch.bin", "hist/_pre30.bin"), + ("Partisan", "guide/low.bin", "rodent.bin"), + ("Pawnsacker", "rodent.bin", "rodent.bin"), + ("Pedrita", "guide/solid.bin", "rodent.bin"), + ("Petrosian", "players/petrosian.bin", "hist/_31to80.bin"), + ("Preston", "guide/cs.bin", "rodent.bin"), + ("Reti", "players/ph-reti2.bin", "hist/_pre30.bin"), + ( + "Rubinstein", + "players/ph-rubinstein2.bin", + "hist/_pre30.bin", + ), + ("Simple", "guide/simple.bin", "rodent.bin"), + ("Spassky", "players/ph_spassky2.bin", "hist/_31to80.bin"), + ("Spitfire", "guide/active.bin", "rodent.bin"), + ("Steinitz", "players/steinitz.bin", "hist/_pre30.bin"), + ("Strangler", "guide/strangler.bin", "rodent.bin"), + ("Tal", "players/ph-tal2.bin", "hist/_31to80.bin"), + ("Tarrasch", "players/ph-tarrasch2.bin", "hist/_pre30.bin"), + ("Topalov", "players/ph-topalov2.bin", "hist/_post06.bin"), +]; diff --git a/crates/prep/Cargo.toml b/crates/prep/Cargo.toml new file mode 100644 index 0000000..9ada134 --- /dev/null +++ b/crates/prep/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "prep" +description = "Preparing against an opponent: a player's opening repertoire in a database, the names of the openings, and the opening errors the engine finds (the desktop and Android apps share it)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +chess-core.workspace = true +chess-import.workspace = true +game-review.workspace = true +uci.workspace = true +chess-openings.workspace = true +serde.workspace = true +serde_json.workspace = true diff --git a/crates/prep/examples/prep_report.rs b/crates/prep/examples/prep_report.rs new file mode 100644 index 0000000..04debab --- /dev/null +++ b/crates/prep/examples/prep_report.rs @@ -0,0 +1,337 @@ +//! A check of the `prep` crate on a real database, printed as text: the candidates +//! for a name, the repertoire tree of each colour, the opening table, and, with an +//! engine, the opening errors by opening and the repeated ones. +//! +//! ```text +//! cargo run --release -p prep --example prep_report -- "" \ +//! [--engine ] [--plies 20] [--processes N] [--min-games 3] [--no-cache] +//! ``` +//! +//! The report and the evaluations are cached under `~/.cache/chesspenguin/prep/` +//! like the application would (`--no-cache` ignores and does not write it). + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::time::Instant; + +use prep::{ColorReport, Options, Player, PositionCache, PrepReport, Side, Tree}; + +struct Args { + db: PathBuf, + player: String, + engine: Option, + plies: usize, + processes: usize, + min_games: u32, + cache: bool, +} + +fn args() -> Args { + let mut it = std::env::args().skip(1); + let mut a = Args { + db: PathBuf::new(), + player: String::new(), + engine: None, + plies: prep::DEFAULT_PLIES, + processes: game_review::processes(game_review::MAX_PROCESSES), + min_games: 3, + cache: true, + }; + let mut positional = Vec::new(); + while let Some(arg) = it.next() { + match arg.as_str() { + "--engine" => a.engine = it.next().map(PathBuf::from), + "--plies" => a.plies = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.plies), + "--processes" => { + a.processes = it + .next() + .and_then(|v| v.parse().ok()) + .unwrap_or(a.processes) + } + "--min-games" => { + a.min_games = it + .next() + .and_then(|v| v.parse().ok()) + .unwrap_or(a.min_games) + } + "--no-cache" => a.cache = false, + _ => positional.push(arg), + } + } + if positional.len() < 2 { + eprintln!("usage: prep_report [--engine path] …"); + std::process::exit(2); + } + a.db = PathBuf::from(&positional[0]); + a.player = positional[1].clone(); + a +} + +fn open(path: &Path) -> chess_import::Database { + let t = Instant::now(); + let opened = + chess_import::open(path, &mut |_| {}, &AtomicBool::new(false)).unwrap_or_else(|e| { + eprintln!("cannot open {}: {e}", path.display()); + std::process::exit(1); + }); + println!( + "[open] {} ({}): {} games, {:.2} s", + path.display(), + opened.format.label(), + opened.db.games(), + t.elapsed().as_secs_f64() + ); + opened.db +} + +fn tally(t: &prep::Tally) -> String { + format!("{} (+{} ={} -{})", t.games, t.wins, t.draws, t.losses) +} + +fn print_tree(tree: &Tree, node: usize, depth: usize, min_games: u32, report: &PrepReport) { + for &c in &tree.nodes[node].children { + let n = &tree.nodes[c as usize]; + if n.tally.games < min_games { + continue; + } + let name = match (n.named, n.opening) { + (true, Some(o)) => format!(" — {}", report.openings[o].name), + _ => String::new(), + }; + println!( + "{:indent$}{} {} {}{}{}{}", + "", + prep::move_label(usize::from(n.ply) - 1, &n.san), + tally(&n.tally), + n.last_date, + n.average_elo() + .map_or(String::new(), |e| format!(" Elo {e}")), + if n.transposition { " ↔" } else { "" }, + name, + indent = depth * 2 + ); + if depth < 8 { + print_tree(tree, c as usize, depth + 1, min_games, report); + } + } +} + +fn print_color(report: &PrepReport, cr: &ColorReport, min_games: u32) { + let colour = if cr.white { "White" } else { "Black" }; + println!( + "\n==== {colour}: {} games, {} tree nodes ====", + cr.games.len(), + cr.tree.nodes.len() + ); + println!("-- repertoire (nodes with at least {min_games} games; ↔ = transposition)"); + print_tree(&cr.tree, 0, 0, min_games, report); + println!("-- openings"); + for f in &cr.families { + println!( + "{} {}{}", + tally(&f.tally), + if f.name.is_empty() { + "(unnamed)" + } else { + &f.name + }, + errors_text(&f.errors) + ); + for v in &f.variations { + let (name, line, eco) = match v.opening { + Some(o) => { + let o = &report.openings[o]; + (o.name.as_str(), o.line.as_str(), o.eco.as_str()) + } + None => ("(unnamed)", "", ""), + }; + let games: Vec = v + .games + .iter() + .map(|&g| format!("#{}", report.games[g as usize].index + 1)) + .collect(); + println!( + " {} {eco} {name} [{line}]{} — {}", + tally(&v.tally), + errors_text(&v.errors), + games.join(" ") + ); + } + } + if !cr.errors.is_empty() || report.engine.is_some() { + println!( + "-- errors: {} inaccuracies, {} mistakes, {} blunders in the player's moves", + cr.counts.inaccuracies, cr.counts.mistakes, cr.counts.blunders + ); + for e in &cr.errors { + let g = &report.games[e.game as usize]; + println!( + " #{} {} {:?}: {} (best {}) {} → {} [{}]", + g.index + 1, + g.move_label(e.ply as usize), + e.judgement, + e.san, + e.best_san, + e.before.format(), + e.after.format(), + e.opening.map_or("", |o| report.openings[o].name.as_str()) + ); + } + println!("-- repeated errors (same position, same move, two or more games)"); + for r in &cr.repeated { + let games: Vec = r + .games + .iter() + .map(|&g| format!("#{}", report.games[g as usize].index + 1)) + .collect(); + println!( + " {}× {} {:?} (best {}) {} — {} [{}]", + r.times(), + prep::move_label(r.ply as usize, &r.san), + r.judgement, + r.best_san, + tally(&r.tally), + games.join(" "), + r.opening.map_or("", |o| report.openings[o].name.as_str()) + ); + } + } +} + +fn errors_text(e: &prep::ErrorCounts) -> String { + if e.total() == 0 { + String::new() + } else { + format!(" ?!{} ?{} ??{}", e.inaccuracies, e.mistakes, e.blunders) + } +} + +fn main() { + let a = args(); + let db = open(&a.db); + let never = AtomicBool::new(false); + let cache_dir = a.cache.then(|| { + std::env::home_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join(".cache/chesspenguin/prep") + }); + + let t = Instant::now(); + let (list, total) = prep::candidates(&db, &a.player, 10); + println!( + "[candidates] {total} for «{}», {:.1} ms:", + a.player, + t.elapsed().as_secs_f64() * 1000.0 + ); + for c in &list { + println!(" {} · {} games (id {})", c.name, c.games, c.id); + } + let Some(chosen) = list + .iter() + .find(|c| c.name.to_lowercase() == a.player.to_lowercase()) + .or(list.first()) + else { + eprintln!("no such player"); + std::process::exit(1); + }; + let player = Player::new([chosen.id]); + println!("[player] {} ({} games)", chosen.name, chosen.games); + + let options = Options { + plies: a.plies, + side: Side::Any, + period: prep::Period::All, + }; + let t = Instant::now(); + let cached = cache_dir + .as_deref() + .and_then(|d| PrepReport::load(d, &db, &player, &options)); + let mut report = match cached { + Some(r) => { + println!( + "[report] from the cache, {:.1} ms", + t.elapsed().as_secs_f64() * 1000.0 + ); + r + } + None => { + let progress = AtomicUsize::new(0); + let r = prep::build(&db, &player, &options, &progress, &never).expect("not cancelled"); + println!( + "[report] built: {} games ({} skipped), {} plies, {} openings named, {:.1} ms", + r.games.len(), + r.skipped, + r.plies, + r.openings.len(), + t.elapsed().as_secs_f64() * 1000.0 + ); + r + } + }; + + for cr in [&report.white, &report.black] { + print_color(&report, cr, a.min_games); + } + + if let Some(engine) = &a.engine { + let mut cache = cache_dir + .as_deref() + .map(PositionCache::load) + .unwrap_or_default(); + println!( + "\n[engine] {} positions, {} distinct; {} cached evaluations on disk", + report.games.iter().map(|g| g.keys.len()).sum::(), + report.distinct_positions(), + cache.len() + ); + let settings = game_review::JobSettings::new(a.processes, None); + let t = Instant::now(); + let mut last_shown = Instant::now(); + let mut first = true; + let result = prep::analyse( + &mut report, + &mut cache, + cache_dir.as_deref(), + uci::EngineConfig::new(engine.clone()), + &settings, + &never, + &mut |p| { + if first { + println!( + "[engine] {} positions to evaluate, {} engine processes", + p.total, a.processes + ); + first = false; + } + if last_shown.elapsed().as_secs_f64() >= 5.0 { + println!( + " {} / {} ({:.0} s, nps {})", + p.done, + p.total, + t.elapsed().as_secs_f64(), + p.nps + ); + last_shown = Instant::now(); + } + }, + ); + match result { + Ok(()) => println!( + "[engine] done in {:.1} s; {} evaluations in the cache; engine {}", + t.elapsed().as_secs_f64(), + cache.len(), + report.engine.as_ref().map_or("?", |e| e.name.as_str()) + ), + Err(e) => println!("[engine] failed: {e:?}"), + } + for cr in [&report.white, &report.black] { + print_color(&report, cr, u32::MAX); + } + } + if let Some(dir) = &cache_dir { + match report.save(dir) { + Ok(()) => println!("[cache] report saved in {}", dir.display()), + Err(e) => println!("[cache] not saved: {e}"), + } + } +} diff --git a/crates/prep/src/errors.rs b/crates/prep/src/errors.rs new file mode 100644 index 0000000..b213644 --- /dev/null +++ b/crates/prep/src/errors.rs @@ -0,0 +1,550 @@ +//! Opening errors found by the engine: every distinct position of the first plies of +//! the player's games is evaluated once (the games repeat their openings, so about +//! half the positions are shared), and the player's moves are judged from the +//! evaluations before and after them with the rules of the game analysis. The same +//! error in several games — the same position and the same move — is what matters +//! most for preparation, so those are listed on their own. +//! +//! Evaluations are kept per position in a cache file shared by every report: another +//! player of the same database, or the same player later, is judged from the cache. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use chess_core::shakmaty::san::SanPlus; +use chess_core::shakmaty::uci::UciMove; +use chess_core::shakmaty::{Chess, Position}; +use game_review::{Eval, Judgement, PosEval, SEARCH_VERSION}; +use serde::{Deserialize, Serialize}; + +use crate::games::{GameInfo, Tally}; + +/// Nodes of an evaluation that needs no engine (checkmate, stalemate): better than any +/// search. +pub const EXACT: u64 = u64::MAX; + +/// The engine's result for one position. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct PositionEval { + /// Nodes of the search ([`EXACT`] for a position without legal moves). + pub nodes: u64, + pub eval: Eval, + /// The engine's line in UCI; the first move is its best move. + pub pv: Vec, + pub depth: u32, +} + +impl PositionEval { + pub fn from_engine(nodes: u64, e: &PosEval) -> PositionEval { + PositionEval { + nodes, + eval: e.eval, + pv: e.pv.iter().take(8).cloned().collect(), + depth: e.depth, + } + } + + pub fn best(&self) -> Option<&str> { + self.pv.first().map(String::as_str) + } +} + +/// How many inaccuracies, mistakes and blunders. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ErrorCounts { + pub inaccuracies: u32, + pub mistakes: u32, + pub blunders: u32, +} + +impl ErrorCounts { + pub fn add(&mut self, j: Judgement) { + match j { + Judgement::Inaccuracy => self.inaccuracies += 1, + Judgement::Mistake => self.mistakes += 1, + Judgement::Blunder => self.blunders += 1, + Judgement::Great | Judgement::Brilliant => {} + } + } + + pub fn total(&self) -> u32 { + self.inaccuracies + self.mistakes + self.blunders + } +} + +/// A move of the player judged an inaccuracy, a mistake or a blunder. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct OpeningError { + /// Index into [`crate::PrepReport::games`]. + pub game: u32, + /// The move's place in the line (0-based; see [`GameInfo::move_label`]). + pub ply: u32, + /// The position before the move. + pub key: u64, + pub uci: String, + pub san: String, + /// The engine's move instead. + pub best_uci: String, + pub best_san: String, + pub judgement: Judgement, + pub before: Eval, + pub after: Eval, + /// The game's opening ([`crate::PrepReport::openings`]). + pub opening: Option, +} + +/// The same error in several games: the same position and the same move. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct RepeatedError { + pub key: u64, + pub ply: u32, + pub uci: String, + pub san: String, + pub best_san: String, + pub judgement: Judgement, + /// The games (indices into [`crate::PrepReport::games`]), in order. + pub games: Vec, + /// How those games ended. + pub tally: Tally, + /// The opening of the first of them. + pub opening: Option, +} + +impl RepeatedError { + pub fn times(&self) -> u32 { + self.games.len() as u32 + } +} + +/// Judges the player's moves in `games[g]` for `g` in `which` from `evals`: the +/// move is not the engine's best, and the evaluations before and after it say it +/// lost enough (the rules of the game analysis, [`game_review::judge`]). Only the +/// prefix before the opponent's first inaccuracy/mistake/blunder is eligible. +/// A missing opponent evaluation or best move stops the prefix too: later player +/// errors are not published until those preceding moves have been checked. +pub fn judge_games( + games: &[GameInfo], + which: &[u32], + evals: &HashMap, +) -> Vec { + let mut out = Vec::new(); + for &g in which { + let game = &games[g as usize]; + let mut pos = Chess::default(); + for (i, uci) in game.ucis.iter().enumerate() { + let Some(m) = uci + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + else { + break; + }; + let evaluated = evals + .get(&game.keys[i]) + .and_then(|before| Some((before, evals.get(&game.keys[i + 1])?, before.best()?))); + if !game.player_moves_at(i) && evaluated.is_none() { + break; + } + if let Some((before, after, best)) = evaluated + && best != uci + && let Some(judgement) = game_review::judge(before.eval, after.eval, pos.turn()) + { + if !game.player_moves_at(i) { + break; + } + let best_san = best + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + .map(|bm| SanPlus::from_move(pos.clone(), bm).to_string()) + .unwrap_or_else(|| best.to_owned()); + out.push(OpeningError { + game: g, + ply: i as u32, + key: game.keys[i], + uci: uci.clone(), + san: game.sans.get(i).cloned().unwrap_or_default(), + best_uci: best.to_owned(), + best_san, + judgement, + before: before.eval, + after: after.eval, + opening: game.opening, + }); + } + pos.play_unchecked(m); + } + } + out +} + +/// The errors made in two or more games (same position, same move), most repeated +/// first, then the worst first. +pub fn repeated(errors: &[OpeningError], games: &[GameInfo]) -> Vec { + let mut groups: HashMap<(u64, &str), Vec<&OpeningError>> = HashMap::new(); + for e in errors { + groups.entry((e.key, e.uci.as_str())).or_default().push(e); + } + let mut out: Vec = groups + .into_values() + .filter(|g| g.len() >= 2) + .map(|g| { + let first = g[0]; + let mut tally = Tally::default(); + let mut list: Vec = g.iter().map(|e| e.game).collect(); + list.sort_unstable(); + list.dedup(); + for &game in &list { + tally.add(games[game as usize].outcome); + } + RepeatedError { + key: first.key, + ply: first.ply, + uci: first.uci.clone(), + san: first.san.clone(), + best_san: first.best_san.clone(), + judgement: first.judgement, + games: list, + tally, + opening: first.opening, + } + }) + .filter(|r| r.games.len() >= 2) + .collect(); + out.sort_by(|a, b| { + b.games + .len() + .cmp(&a.games.len()) + .then(b.judgement.cmp(&a.judgement)) + .then(a.ply.cmp(&b.ply)) + .then(a.games.cmp(&b.games)) + }); + out +} + +// ----- the cache of evaluations by position -------------------------------------- + +const CACHE_FILE: &str = "positions.json"; +const CACHE_VERSION: u32 = 1; +/// Positions kept at most (about 100 bytes each on disk). +const CACHE_LIMIT: usize = 1_000_000; + +#[derive(Serialize, Deserialize)] +struct CacheFile { + version: u32, + /// The version of the fixed search the evaluations come from ([`SEARCH_VERSION`]; + /// 0: from before it). Those of another one are not used. + #[serde(default)] + search: u32, + positions: Vec<(u64, PositionEval)>, +} + +/// Engine evaluations by position, shared by every report: the best quality (most +/// nodes) seen for each position is kept. +#[derive(Default)] +pub struct PositionCache { + entries: HashMap, + dirty: bool, +} + +impl PositionCache { + fn path(dir: &Path) -> PathBuf { + dir.join(CACHE_FILE) + } + + /// The cache in `dir` (empty when there is none, or it cannot be read). + pub fn load(dir: &Path) -> PositionCache { + let entries = std::fs::read(Self::path(dir)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|f| f.version == CACHE_VERSION && f.search == SEARCH_VERSION) + .map(|f| f.positions.into_iter().collect()) + .unwrap_or_default(); + PositionCache { + entries, + dirty: false, + } + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn get(&self, key: u64) -> Option<&PositionEval> { + self.entries.get(&key) + } + + /// Keeps `eval` unless the cache has one with more nodes; says whether it was kept. + pub fn insert(&mut self, key: u64, eval: PositionEval) -> bool { + if self + .entries + .get(&key) + .is_some_and(|e| e.nodes >= eval.nodes) + { + return false; + } + self.entries.insert(key, eval); + self.dirty = true; + true + } + + /// Something was added since the load or the last save. + pub fn dirty(&self) -> bool { + self.dirty + } + + /// Writes the cache to `dir` (through a temporary file, so a crash never leaves + /// half a file); nothing when nothing changed. + pub fn save(&mut self, dir: &Path) -> std::io::Result<()> { + if !self.dirty { + return Ok(()); + } + let mut positions: Vec<(u64, PositionEval)> = + self.entries.iter().map(|(k, v)| (*k, v.clone())).collect(); + if positions.len() > CACHE_LIMIT { + // Over the limit the searches with the fewest nodes go first. + positions.sort_by_key(|a| std::cmp::Reverse(a.1.nodes)); + positions.truncate(CACHE_LIMIT); + } + let file = CacheFile { + version: CACHE_VERSION, + search: SEARCH_VERSION, + positions, + }; + let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?; + write_atomic(&Self::path(dir), &bytes)?; + self.dirty = false; + Ok(()) + } +} + +/// Writes through a temporary file and a rename. +pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tree::tests::game; + + fn eval(nodes: u64, cp: i32, best: &str) -> PositionEval { + PositionEval { + nodes, + eval: Eval::Cp(cp), + pv: vec![best.to_owned()], + depth: 10, + } + } + + #[test] + fn the_same_error_in_two_games_is_repeated() { + // Three games of the player with White: 1.e4 e5 2.Qh5?! twice, 2.Nf3 once. + let games = vec![ + game(0, true, &["e4", "e5", "Qh5", "Nc6"], "1-0", "", 0), + game(1, true, &["e4", "e5", "Qh5", "Nf6"], "0-1", "", 0), + game(2, true, &["e4", "e5", "Nf3", "Nc6"], "1/2-1/2", "", 0), + game(3, false, &["e4", "e5", "Qh5", "Nc6"], "0-1", "", 0), + ]; + let mut evals = HashMap::new(); + evals.insert(games[0].keys[0], eval(1000, 30, "e2e4")); + evals.insert(games[0].keys[1], eval(1000, 30, "e7e5")); + // 2.Qh5 drops from +0.3 to −1.0: a mistake; 2.Nf3 is the engine's move. + evals.insert(games[0].keys[2], eval(1000, 30, "g1f3")); + evals.insert(games[0].keys[3], eval(1000, -100, "b8c6")); + evals.insert(games[1].keys[3], eval(1000, -100, "g8f6")); + evals.insert(games[2].keys[3], eval(1000, 30, "b8c6")); + let errors = judge_games(&games, &[0, 1, 2], &evals); + assert_eq!(errors.len(), 2); + assert_eq!(errors[0].game, 0); + assert_eq!(errors[0].ply, 2); + assert_eq!(errors[0].san, "Qh5"); + assert_eq!(errors[0].best_san, "Nf3"); + assert_eq!(errors[0].judgement, Judgement::Mistake); + assert_eq!(errors[1].game, 1); + let rep = repeated(&errors, &games); + assert_eq!(rep.len(), 1); + assert_eq!(rep[0].games, vec![0, 1]); + assert_eq!(rep[0].times(), 2); + assert_eq!((rep[0].tally.wins, rep[0].tally.losses), (1, 1)); + // Black's moves in game 3 are the player's: 2.Qh5 is the opponent's there. + let evals_black = evals.clone(); + assert!(judge_games(&games, &[3], &evals_black).is_empty()); + // A position without an evaluation after the move is not judged (the two + // games share the position after 2.Qh5). + let mut partial = evals.clone(); + partial.remove(&games[1].keys[3]); + assert!(judge_games(&games, &[0, 1, 2], &partial).is_empty()); + // One game less: nothing repeats. + assert!(repeated(&judge_games(&games, &[0, 2], &evals), &games).is_empty()); + } + + fn line_evals(game: &GameInfo, values: &[i32]) -> HashMap { + game.keys + .iter() + .enumerate() + .map(|(ply, &key)| { + ( + key, + eval( + 1000, + values[ply], + game.ucis.get(ply).map_or("", String::as_str), + ), + ) + }) + .collect() + } + + #[test] + fn every_opponent_error_category_stops_later_errors_for_both_colours() { + for white in [true, false] { + for (loss, category) in [ + (60, Judgement::Inaccuracy), + (150, Judgement::Mistake), + (500, Judgement::Blunder), + ] { + let game = game(0, white, &["e4", "e5", "Qh5", "Nc6"], "*", "", 0); + let (opponent_ply, player_ply, values) = if white { + (1, 2, vec![0, 0, loss, -150, -150]) + } else { + (0, 1, vec![0, -loss, 150, 150, 150]) + }; + let mut evals = line_evals(&game, &values); + evals.get_mut(&game.keys[opponent_ply]).unwrap().pv = + vec![if white { "c7c5" } else { "d2d4" }.to_owned()]; + evals.get_mut(&game.keys[player_ply]).unwrap().pv = + vec![if white { "g1f3" } else { "c7c5" }.to_owned()]; + let mover = if white { + chess_core::shakmaty::Color::Black + } else { + chess_core::shakmaty::Color::White + }; + assert_eq!( + game_review::judge( + Eval::Cp(values[opponent_ply]), + Eval::Cp(values[opponent_ply + 1]), + mover + ), + Some(category) + ); + assert!(judge_games(std::slice::from_ref(&game), &[0], &evals).is_empty()); + // The engine's own best move is exempt even if evaluations differ. + evals.get_mut(&game.keys[opponent_ply]).unwrap().pv = + vec![game.ucis[opponent_ply].clone()]; + let errors = judge_games(std::slice::from_ref(&game), &[0], &evals); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].ply, player_ply as u32); + } + } + } + + #[test] + fn earlier_player_errors_survive_but_the_whole_later_suffix_is_excluded() { + for white in [true, false] { + let game = game( + 0, + white, + &["e4", "e5", "Qh5", "Nc6", "Bc4", "Nf6"], + "*", + "", + 0, + ); + let values = if white { + vec![0, -150, 0, -150, -150, -300, -300] + } else { + vec![0, 0, 150, 0, 150, 0, 150] + }; + let mut evals = line_evals(&game, &values); + let first_player = usize::from(!white); + let opponent = first_player + 1; + let alternatives = if white { + ["d2d4", "c7c5", "g1f3", "d2d3"] + } else { + ["c7c5", "g1f3", "g8f6", "d7d6"] + }; + for (ply, best) in [first_player, opponent, first_player + 2, first_player + 4] + .into_iter() + .zip(alternatives) + { + evals.get_mut(&game.keys[ply]).unwrap().pv = vec![best.to_owned()]; + } + let errors = judge_games(std::slice::from_ref(&game), &[0], &evals); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].ply, first_player as u32); + } + } + + #[test] + fn incomplete_opponent_prefix_withholds_errors_until_checked() { + let game = game(0, true, &["e4", "e5", "Qh5", "Nc6"], "*", "", 0); + let mut complete = line_evals(&game, &[0, 0, 0, -150, -150]); + complete.get_mut(&game.keys[2]).unwrap().pv = vec!["g1f3".to_owned()]; + for missing in [game.keys[1], game.keys[2]] { + let mut partial = complete.clone(); + partial.remove(&missing); + assert!(judge_games(std::slice::from_ref(&game), &[0], &partial).is_empty()); + } + let mut missing_best = complete.clone(); + missing_best.get_mut(&game.keys[1]).unwrap().pv.clear(); + assert!(judge_games(std::slice::from_ref(&game), &[0], &missing_best).is_empty()); + assert_eq!( + judge_games(std::slice::from_ref(&game), &[0], &complete).len(), + 1 + ); + } + + #[test] + fn opponent_allowing_mate_is_judged_from_the_actual_mover() { + for white in [true, false] { + let game = game(0, white, &["e4", "e5", "Qh5", "Nc6"], "*", "", 0); + let opponent = usize::from(white); + let mut evals = line_evals(&game, &[0, 0, 0, 0, 0]); + evals.get_mut(&game.keys[opponent]).unwrap().pv = + vec![if white { "c7c5" } else { "d2d4" }.to_owned()]; + evals.get_mut(&game.keys[opponent + 1]).unwrap().eval = Eval::Mate { white, moves: 3 }; + evals.get_mut(&game.keys[opponent + 1]).unwrap().pv = + vec![if white { "g1f3" } else { "c7c5" }.to_owned()]; + // The player's next move lets that forced mate go, normally an error. + assert!(judge_games(std::slice::from_ref(&game), &[0], &evals).is_empty()); + } + } + + #[test] + fn the_position_cache_keeps_the_best_quality_and_survives_a_save() { + let dir = std::env::temp_dir().join(format!("prep-cache-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut c = PositionCache::load(&dir); + assert!(c.is_empty()); + assert!(c.insert(1, eval(1000, 10, "e2e4"))); + assert!(!c.insert(1, eval(250, 20, "d2d4")), "fewer nodes: not kept"); + assert!(c.insert(1, eval(3000, 30, "c2c4"))); + assert!(c.insert(2, eval(EXACT, 0, ""))); + assert_eq!(c.get(1).map(|e| e.nodes), Some(3000)); + assert!(c.dirty()); + c.save(&dir).expect("saved"); + assert!(!c.dirty()); + let d = PositionCache::load(&dir); + assert_eq!(d.len(), 2); + assert_eq!(d.get(1), c.get(1)); + assert_eq!(d.get(2).map(|e| e.nodes), Some(EXACT)); + assert_eq!(d.get(3), None); + // A cache from before the fixed search of the game analysis is not used. + let path = PositionCache::path(&dir); + let mut json: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).expect("cache")).expect("json"); + json.as_object_mut().expect("cache").remove("search"); + std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written"); + assert!(PositionCache::load(&dir).is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/prep/src/games.rs b/crates/prep/src/games.rs new file mode 100644 index 0000000..1ceddc6 --- /dev/null +++ b/crates/prep/src/games.rs @@ -0,0 +1,230 @@ +//! The player's games as the report sees them: the first plies of the main line with +//! the keys of its positions, the result from the player's side, the date and the +//! opponent's rating. Games from a set-up position are left out. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use chess_core::shakmaty::san::SanPlus; +use chess_core::shakmaty::{Chess, Position}; +use chess_import::Database; +use chess_import::pgn_catalog::date_number; +use chess_import::position::{key, uci}; +use serde::{Deserialize, Serialize}; + +use crate::openings::{self, OpeningSet}; + +/// A game's result from the player's side. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Outcome { + Win, + Draw, + Loss, + Unknown, +} + +impl Outcome { + /// From the result tag and the player's colour. + pub fn of(result: &str, white: bool) -> Outcome { + match (result.trim(), white) { + ("1-0", true) | ("0-1", false) => Outcome::Win, + ("1-0", false) | ("0-1", true) => Outcome::Loss, + ("1/2-1/2" | "½-½", _) => Outcome::Draw, + _ => Outcome::Unknown, + } + } +} + +/// Games and their results from the player's side. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Tally { + pub games: u32, + pub wins: u32, + pub draws: u32, + pub losses: u32, +} + +impl Tally { + pub fn add(&mut self, outcome: Outcome) { + self.games += 1; + match outcome { + Outcome::Win => self.wins += 1, + Outcome::Draw => self.draws += 1, + Outcome::Loss => self.losses += 1, + Outcome::Unknown => {} + } + } + + /// Points per game, 0..1, over the games with a result. + pub fn score(&self) -> Option { + let decided = self.wins + self.draws + self.losses; + (decided > 0) + .then(|| (f64::from(self.wins) + 0.5 * f64::from(self.draws)) / f64::from(decided)) + } +} + +/// Legacy book data kept so old reports still round-trip. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BookExit { + pub ply: u32, + pub by_player: bool, + pub count: u32, +} + +/// One game of the player. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GameInfo { + /// Record index in the database. + pub index: u32, + /// The player had White. + pub white: bool, + pub opponent: String, + /// 0: unknown. + pub opponent_elo: u16, + /// PGN form ("2026.10.18", "1997.05.??"), empty when unknown. + pub date: String, + pub outcome: Outcome, + /// The first moves of the main line (at most the report's plies), UCI and SAN. + pub ucis: Vec, + pub sans: Vec, + /// Keys of the positions before each move and after the last: `ucis.len() + 1`. + pub keys: Vec, + /// The deepest named position of the line ([`crate::PrepReport::openings`]). + pub opening: Option, + /// Plies of the line up to the named position (`keys[named]` is it). + pub named: Option, + /// Unused legacy book data, preserved when old reports are saved again. + #[serde(default)] + pub book: Option, +} + +impl GameInfo { + /// `yyyymmdd` for ordering (0: no date). + pub fn date_number(&self) -> u32 { + date_number(&self.date) + } + + /// Move `ply` (0-based) was the player's. + pub fn player_moves_at(&self, ply: usize) -> bool { + ply.is_multiple_of(2) == self.white + } + + /// "12. Nf3" / "12... Nf6" for move `ply` (0-based). + pub fn move_label(&self, ply: usize) -> String { + let san = self.sans.get(ply).map_or("", String::as_str); + move_label(ply, san) + } +} + +/// "12. Nf3" / "12... Nf6" for move `ply` (0-based from the usual start position). +pub fn move_label(ply: usize, san: &str) -> String { + let number = ply / 2 + 1; + if ply.is_multiple_of(2) { + format!("{number}. {san}") + } else { + format!("{number}... {san}") + } +} + +/// What a pass over the games produced. +pub struct Collected { + pub games: Vec, + pub openings: OpeningSet, + /// Games left out: from a set-up position, or unreadable. + pub skipped: u32, + /// Final positions of lines that end in checkmate or stalemate: (key, position). + pub terminal: Vec<(u64, Chess)>, +} + +/// Reads the first `plies` of each of `found` (record, the player had White); +/// `progress` counts the games done. `None` when cancelled. +pub fn collect( + db: &Database, + found: &[(u32, bool)], + plies: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Option { + let mut out = Collected { + games: Vec::with_capacity(found.len()), + openings: OpeningSet::default(), + skipped: 0, + terminal: Vec::new(), + }; + for &(index, white) in found { + if cancel.load(Ordering::Relaxed) { + return None; + } + progress.fetch_add(1, Ordering::Relaxed); + let Some(line) = db.main_line(index as usize, plies) else { + out.skipped += 1; + continue; + }; + if !line.standard_start { + out.skipped += 1; + continue; + } + let row = db.row(index as usize); + let mut pos = Chess::default(); + let mut keys = Vec::with_capacity(line.moves.len() + 1); + let mut ucis = Vec::with_capacity(line.moves.len()); + let mut sans = Vec::with_capacity(line.moves.len()); + keys.push(key(&pos)); + for m in &line.moves { + ucis.push(uci(m).to_string()); + sans.push(SanPlus::from_move_and_play_unchecked(&mut pos, *m).to_string()); + keys.push(key(&pos)); + } + if pos.is_checkmate() || pos.is_stalemate() { + out.terminal.push((key(&pos), pos)); + } + let (opening, named) = match openings::deepest(&keys) { + Some((at, id)) => (Some(out.openings.intern(id)), Some(at as u32)), + None => (None, None), + }; + out.games.push(GameInfo { + index, + white, + opponent: if white { row.black } else { row.white }, + opponent_elo: if white { row.black_elo } else { row.white_elo }, + date: row.date, + outcome: Outcome::of(row.result, white), + ucis, + sans, + keys, + opening, + named, + book: None, + }); + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn outcomes_and_tallies() { + assert_eq!(Outcome::of("1-0", true), Outcome::Win); + assert_eq!(Outcome::of("1-0", false), Outcome::Loss); + assert_eq!(Outcome::of("0-1", false), Outcome::Win); + assert_eq!(Outcome::of("1/2-1/2", true), Outcome::Draw); + assert_eq!(Outcome::of("*", true), Outcome::Unknown); + let mut t = Tally::default(); + for o in [ + Outcome::Win, + Outcome::Win, + Outcome::Draw, + Outcome::Loss, + Outcome::Unknown, + ] { + t.add(o); + } + assert_eq!((t.games, t.wins, t.draws, t.losses), (5, 2, 1, 1)); + assert_eq!(t.score(), Some(0.625)); + assert_eq!(Tally::default().score(), None); + assert_eq!(move_label(0, "e4"), "1. e4"); + assert_eq!(move_label(1, "c5"), "1... c5"); + assert_eq!(move_label(22, "Nf3"), "12. Nf3"); + } +} diff --git a/crates/prep/src/lib.rs b/crates/prep/src/lib.rs new file mode 100644 index 0000000..9e746e6 --- /dev/null +++ b/crates/prep/src/lib.rs @@ -0,0 +1,1254 @@ +//! Preparing against an opponent on the desktop: what a player of a database plays +//! in the opening and where in the opening he goes wrong. +//! +//! The [`PrepReport`] is built in a moment from the player's games ([`build`]): his +//! main lines up to a number of plies, the repertoire tree of each colour with +//! transpositions marked, and the openings named from the Lichess `chess-openings` +//! table (family → variation → games). The engine step is apart and optional: every +//! distinct position of +//! the lines is evaluated once ([`PrepReport::targets`], run by +//! [`game_review::run`], results taken in by [`PrepReport::apply`]), the player's +//! moves are judged with the rules of the game analysis, and the errors are listed by +//! opening and, when the same error was made in several games, as repeated. The +//! report is cached by database, player and plies; evaluations by position, across +//! reports ([`PositionCache`]). +//! +//! Nothing here touches the database or the games; no user interface. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::time::SystemTime; + +use chess_import::Database; +use game_review::{JobEvent, SEARCH_NODES, SEARCH_VERSION, Target}; +#[cfg(not(target_family = "wasm"))] +use game_review::{JobFailure, JobSettings}; +use serde::{Deserialize, Serialize}; +use uci::EnginePosition; + +mod errors; +mod games; +pub mod openings; +mod period; +mod players; +mod tree; + +pub use chess_import::chessbase::base::Side; +pub use errors::{EXACT, ErrorCounts, OpeningError, PositionCache, PositionEval, RepeatedError}; +pub use game_review::{Eval, Judgement}; +pub use games::{BookExit, GameInfo, Outcome, Tally, move_label}; +pub use openings::Opening; +pub use period::{Chosen, Period, PoolGame, newest as period_newest}; +pub use players::{Candidate, Player, candidates, games_of}; +pub use tree::{Node, Tree}; + +/// Plies of the opening a report looks at unless told otherwise. +pub const DEFAULT_PLIES: usize = 20; + +/// What a report covers. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Options { + /// Plies of each game's main line. + pub plies: usize, + /// The player's colour(s). + pub side: Side, + /// Which of his games. + pub period: Period, +} + +impl Default for Options { + fn default() -> Self { + Options { + plies: DEFAULT_PLIES, + side: Side::Any, + period: Period::All, + } + } +} + +/// An opening as played by the player: the games with the same name. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Variation { + /// Index into [`PrepReport::openings`]; `None`: no named position in the line. + pub opening: Option, + pub tally: Tally, + /// Indices into [`PrepReport::games`], in order. + pub games: Vec, + pub errors: ErrorCounts, + /// Indices into [`ColorReport::errors`]. + pub error_list: Vec, +} + +/// The openings with the same family name ("Sicilian Defense"), most played first. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Family { + /// Empty for games without a named position. + pub name: String, + pub tally: Tally, + /// Most played first. + pub variations: Vec, + pub errors: ErrorCounts, +} + +/// The report for one colour of the player. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ColorReport { + pub white: bool, + /// Indices into [`PrepReport::games`], in record order. + pub games: Vec, + pub tree: Tree, + pub families: Vec, + /// The player's opening errors, by game and ply (after the engine step). + pub errors: Vec, + /// The errors made in two or more games. + pub repeated: Vec, + pub counts: ErrorCounts, +} + +/// The engine the evaluations came from. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct EngineInfo { + pub name: String, + /// Nodes per position. + pub nodes: u64, +} + +/// Legacy book data kept so old reports still round-trip. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct BookInfo { + pub fingerprint: u64, + pub threshold: u32, + pub left: u32, +} + +// 4: the period and the pool of the player's games. +const REPORT_VERSION: u32 = 4; + +/// Everything the preparation knows about the player. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PrepReport { + pub version: u32, + /// Of the database ([`fingerprint`]). + pub fingerprint: u64, + pub player: Player, + /// The player's names in the database. + pub names: Vec, + pub plies: usize, + pub side_white: bool, + pub side_black: bool, + /// Which of the player's games the report took. + #[serde(default)] + pub period: Period, + /// All the player's games of the side(s), before the period's choice (for the + /// counts of the other periods). + #[serde(default)] + pub pool: Vec, + pub games: Vec, + /// Games left out: from a set-up position, or unreadable. + pub skipped: u32, + /// The openings the games and trees refer to. + pub openings: Vec, + pub white: ColorReport, + pub black: ColorReport, + /// Unused legacy book data, preserved when old reports are saved again. + #[serde(default)] + pub book: Option, + #[serde(default)] + pub book_counts: HashMap, + pub engine: Option, + /// Engine evaluations by position key. + pub evals: HashMap, + /// The version of the fixed search of the game analysis the evaluations come from + /// ([`SEARCH_VERSION`]; 0: from before it, made with the user's engine settings). + #[serde(default)] + pub search: u32, + /// A manual Stop forbids another automatic run of this report. + #[serde(default)] + pub engine_stopped: bool, +} + +/// Identity of a database for the report cache: the content of a PGN file, the +/// path, size and time of a ChessBase database. +pub fn fingerprint(db: &Database) -> u64 { + match db { + Database::Pgn(p) => { + let f = p.fingerprint(); + fnv(f + .content_hash + .to_le_bytes() + .iter() + .chain(f.len.to_le_bytes().iter())) + } + Database::ChessBase(b) => { + let meta = std::fs::metadata(b.path()).ok(); + let len = meta.as_ref().map_or(0, std::fs::Metadata::len); + let modified = meta + .and_then(|m| m.modified().ok()) + .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs()); + fnv(b + .path() + .to_string_lossy() + .bytes() + .chain(len.to_le_bytes()) + .chain(modified.to_le_bytes()) + .collect::>() + .iter()) + } + } +} + +fn fnv<'a>(bytes: impl Iterator) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in bytes { + h ^= u64::from(*b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// Builds the report of `player` in `db`: his games ([`games_of`]), their first +/// plies, the trees, the names and the opening tables. `progress` counts the games +/// read. `None` when cancelled. Milliseconds for hundreds of games. +pub fn build( + db: &Database, + player: &Player, + options: &Options, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Option { + let found = games_of(db, player, options.side, cancel)?; + // Every game is read (its first plies: a moment), so that the pool and the counts of + // the periods are of the games a report can take: not those from a set-up position. + let collected = games::collect(db, &found, options.plies, progress, cancel)?; + let pool: Vec = collected + .games + .iter() + .map(|g| PoolGame { + index: g.index, + white: g.white, + date: g.date_number(), + }) + .collect(); + let chosen: std::collections::HashSet<(u32, bool)> = + period::choose(&pool, options.period).into_iter().collect(); + let mut openings = collected.openings; + let games: Vec = collected + .games + .into_iter() + .filter(|g| chosen.contains(&(g.index, g.white))) + .collect(); + let mut evals = HashMap::new(); + for (key, pos) in &collected.terminal { + if let Some(eval) = game_review::terminal_eval(pos) { + evals.insert( + *key, + PositionEval { + nodes: EXACT, + eval, + pv: Vec::new(), + depth: 0, + }, + ); + } + } + let color = |white: bool, openings: &mut openings::OpeningSet| -> ColorReport { + let which: Vec = games + .iter() + .enumerate() + .filter(|(_, g)| g.white == white) + .map(|(i, _)| i as u32) + .collect(); + let tree = Tree::build(&games, &which, options.plies, openings); + let families = families(&games, &which, &openings.list); + ColorReport { + white, + games: which, + tree, + families, + errors: Vec::new(), + repeated: Vec::new(), + counts: ErrorCounts::default(), + } + }; + let white = color(true, &mut openings); + let black = color(false, &mut openings); + let mut report = PrepReport { + version: REPORT_VERSION, + fingerprint: fingerprint(db), + player: player.clone(), + names: player.names(db), + plies: options.plies, + side_white: options.side != Side::Black, + side_black: options.side != Side::White, + period: options.period, + pool, + games, + skipped: collected.skipped, + openings: openings.list, + white, + black, + book: None, + book_counts: HashMap::new(), + engine: None, + evals, + search: SEARCH_VERSION, + engine_stopped: false, + }; + report.refresh(); + Some(report) +} + +/// Groups `games[g]` for `g` in `which` by opening name: families, most played +/// first, each with its variations, most played first. A name the table gives to +/// several positions ("Sicilian Defense: Closed" after 2.Nc3 and after 2...e6) is one +/// variation, shown with its shortest line. +fn families(games: &[GameInfo], which: &[u32], openings: &[Opening]) -> Vec { + let mut out: Vec = Vec::new(); + let mut family_of: HashMap = HashMap::new(); + let mut variation_of: HashMap<(usize, String), usize> = HashMap::new(); + for &g in which { + let game = &games[g as usize]; + let opening = game.opening.map(|o| &openings[o]); + let name = opening.map(|o| o.family().to_owned()).unwrap_or_default(); + let f = *family_of.entry(name.clone()).or_insert_with(|| { + out.push(Family { + name, + ..Family::default() + }); + out.len() - 1 + }); + let full = opening.map(|o| o.name.clone()).unwrap_or_default(); + let v = *variation_of.entry((f, full)).or_insert_with(|| { + out[f].variations.push(Variation { + opening: game.opening, + ..Variation::default() + }); + out[f].variations.len() - 1 + }); + out[f].tally.add(game.outcome); + let var = &mut out[f].variations[v]; + if let (Some(o), Some(shown)) = (game.opening, var.opening) + && openings[o].plies < openings[shown].plies + { + var.opening = Some(o); + } + var.tally.add(game.outcome); + var.games.push(g); + } + let variation_name = |v: &Variation| -> String { + v.opening + .map(|o| openings[o].name.clone()) + .unwrap_or_default() + }; + for f in &mut out { + f.variations.sort_by(|a, b| { + b.tally + .games + .cmp(&a.tally.games) + .then_with(|| variation_name(a).cmp(&variation_name(b))) + }); + } + out.sort_by(|a, b| { + b.tally + .games + .cmp(&a.tally.games) + .then_with(|| a.name.cmp(&b.name)) + }); + out +} + +impl PrepReport { + /// The colour(s) the report was built for. + pub fn side(&self) -> Side { + match (self.side_white, self.side_black) { + (true, false) => Side::White, + (false, true) => Side::Black, + _ => Side::Any, + } + } + + /// The options the report was built with. + pub fn options(&self) -> Options { + Options { + plies: self.plies, + side: self.side(), + period: self.period, + } + } + + /// How many games `period` would take of the colour(s) `side`. + pub fn count(&self, period: Period, side: Side) -> Chosen { + period::count(&self.pool, period, side) + } + + pub fn color(&self, white: bool) -> &ColorReport { + if white { &self.white } else { &self.black } + } + + // ----- the engine ----------------------------------------------------------- + + /// Every distinct position of the lines (the one after the last move included), + /// first met first; those without legal moves left out. + fn positions(&self) -> Vec<(u64, &GameInfo, usize)> { + self.positions_for(Side::Any) + } + + /// [`PrepReport::positions`] of the games the player had `side` in. + fn positions_for(&self, side: Side) -> Vec<(u64, &GameInfo, usize)> { + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::new(); + for g in &self.games { + if (side == Side::White && !g.white) || (side == Side::Black && g.white) { + continue; + } + for (i, &k) in g.keys.iter().enumerate() { + if self.evals.get(&k).is_some_and(|e| e.nodes == EXACT) { + continue; + } + if seen.insert(k) { + out.push((k, g, i)); + } + } + } + out + } + + /// Some position has an engine evaluation (from a run or from the cache): the + /// errors are judged. + pub fn evaluated(&self) -> bool { + self.evals.values().any(|e| e.nodes != EXACT) + } + + /// Distinct positions an engine run looks at. + pub fn distinct_positions(&self) -> usize { + self.positions().len() + } + + /// Distinct positions of the games the player had `side` in. + pub fn distinct_positions_for(&self, side: Side) -> usize { + self.positions_for(side).len() + } + + /// Positions without an evaluation. + pub fn missing(&self) -> usize { + self.missing_for(Side::Any) + } + + /// [`PrepReport::missing`] among the games the player had `side` in. + pub fn missing_for(&self, side: Side) -> usize { + self.positions_for(side) + .iter() + .filter(|(k, _, _)| !self.evals.contains_key(k)) + .count() + } + + /// Takes from `cache` the evaluations the report lacks; returns how many. + pub fn take_cached(&mut self, cache: &PositionCache) -> usize { + let keys: Vec = self.positions().iter().map(|(k, _, _)| *k).collect(); + let mut taken = 0; + for k in keys { + if self.evals.contains_key(&k) { + continue; + } + if let Some(e) = cache.get(k) { + self.evals.insert(k, e.clone()); + taken += 1; + } + } + if taken > 0 { + self.refresh(); + } + taken + } + + /// The positions still to evaluate, for [`game_review::run`] (one search each, no + /// second search for !! and !). Their keys are the position keys in hexadecimal, as + /// [`PrepReport::apply`] reads them. + pub fn targets(&self) -> Vec { + self.targets_for(Side::Any) + } + + /// [`PrepReport::targets`] of the games the player had `side` in (the dialog's + /// «Black — 133 games» halves the work). + pub fn targets_for(&self, side: Side) -> Vec { + self.positions_for(side) + .into_iter() + .filter(|(k, _, _)| !self.evals.contains_key(k)) + .map(|(k, g, i)| Target { + key: format!("{k:016x}"), + pos: EnginePosition::startpos(g.ucis[..i].iter().cloned()), + turn: if i.is_multiple_of(2) { + uci::Side::White + } else { + uci::Side::Black + }, + played: None, + others: Vec::new(), + known: None, + shallow: None, + }) + .collect() + } + + /// Takes in what the engine job reported; the evaluation it carried (to cache), if + /// any. The errors are re-judged on the next [`PrepReport::refresh`]. + pub fn apply(&mut self, event: &JobEvent) -> Option<(u64, PositionEval)> { + let nodes = SEARCH_NODES; + match event { + JobEvent::Engine(name) => { + self.engine = Some(EngineInfo { + name: name.clone(), + nodes, + }); + None + } + JobEvent::Eval { key, eval, .. } => { + let k = u64::from_str_radix(key, 16).ok()?; + let e = PositionEval::from_engine(nodes, eval); + self.engine.get_or_insert_with(|| EngineInfo { + name: String::new(), + nodes, + }); + self.evals.insert(k, e.clone()); + Some((k, e)) + } + } + } + + /// Re-judges the player's moves from the evaluations: the errors by colour, + /// opening and repetition. Cheap (the lines of the games). + pub fn refresh(&mut self) { + let PrepReport { + games, + evals, + white, + black, + .. + } = self; + for cr in [white, black] { + let errors = errors::judge_games(games, &cr.games, evals); + cr.repeated = errors::repeated(&errors, games); + cr.counts = ErrorCounts::default(); + let mut at: HashMap = HashMap::new(); + for (f, fam) in cr.families.iter_mut().enumerate() { + fam.errors = ErrorCounts::default(); + for (v, var) in fam.variations.iter_mut().enumerate() { + var.errors = ErrorCounts::default(); + var.error_list.clear(); + for &g in &var.games { + at.insert(g, (f, v)); + } + } + } + for (i, e) in errors.iter().enumerate() { + cr.counts.add(e.judgement); + if let Some(&(f, v)) = at.get(&e.game) { + let fam = &mut cr.families[f]; + fam.errors.add(e.judgement); + fam.variations[v].errors.add(e.judgement); + fam.variations[v].error_list.push(i as u32); + } + } + cr.errors = errors; + } + } + + // ----- the report cache ----------------------------------------------------- + + /// The cache file of a report in `dir`. + pub fn cache_path(dir: &Path, fingerprint: u64, player: &Player, options: &Options) -> PathBuf { + let mut bytes = fingerprint.to_le_bytes().to_vec(); + for id in &player.ids { + bytes.extend(id.to_le_bytes()); + } + bytes.extend((options.plies as u64).to_le_bytes()); + bytes.push(match options.side { + Side::Any => 0, + Side::White => 1, + Side::Black => 2, + }); + // All the games: as before periods were chosen (the reports cached then). + match options.period { + Period::All => {} + Period::Months(m) => { + bytes.push(1); + bytes.extend(u32::from(m).to_le_bytes()); + } + Period::Last(n) => { + bytes.push(2); + bytes.extend(n.to_le_bytes()); + } + } + dir.join(format!("{:016x}.json", fnv(bytes.iter()))) + } + + /// The report cached in `dir` for this database, player and options, if any. + pub fn load( + dir: &Path, + db: &Database, + player: &Player, + options: &Options, + ) -> Option { + let fp = fingerprint(db); + let bytes = std::fs::read(Self::cache_path(dir, fp, player, options)).ok()?; + let mut report: PrepReport = serde_json::from_slice(&bytes).ok()?; + let same = report.version == REPORT_VERSION + && report.fingerprint == fp + && report.player == *player + && report.plies == options.plies + && report.side() == options.side + && report.period == options.period; + if !same { + return None; + } + // Evaluations of another search are not mixed with today's: the errors are + // found again. + if report.search != SEARCH_VERSION { + report.evals.retain(|_, e| e.nodes == EXACT); + report.engine = None; + report.search = SEARCH_VERSION; + } + // Errors and their aggregates are derived data. Reapply current eligibility + // rules even when cached evaluations came from the same engine search. + report.refresh(); + Some(report) + } + + /// Keeps the report in `dir` (atomically). + pub fn save(&self, dir: &Path) -> std::io::Result<()> { + let options = self.options(); + let path = Self::cache_path(dir, self.fingerprint, &self.player, &options); + let bytes = serde_json::to_vec(self).map_err(std::io::Error::other)?; + errors::write_atomic(&path, &bytes) + } +} + +/// Progress of [`analyse`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Progress { + /// Positions evaluated in this run. + pub done: usize, + /// Positions the run has to evaluate. + pub total: usize, + /// The engine's speed in the last search (0 if it did not say). + pub nps: u64, +} + +// The engines run as processes, each driven from a thread: not in a browser. +#[cfg(not(target_family = "wasm"))] +/// Runs the engine over the positions `report` lacks (the cache +/// is consulted first and fed as results come; `cache_dir` saves it every few +/// hundred positions and at the end), updating the report as results come in. +/// Returns when done, or soon after `cancel` is set (what was evaluated stays). +pub fn analyse( + report: &mut PrepReport, + cache: &mut PositionCache, + cache_dir: Option<&Path>, + config: uci::EngineConfig, + settings: &JobSettings, + cancel: &AtomicBool, + on_progress: &mut dyn FnMut(Progress), +) -> Result<(), JobFailure> { + report.take_cached(cache); + let targets = report.targets(); + let total = targets.len(); + let mut progress = Progress { + done: 0, + total, + nps: 0, + }; + on_progress(progress); + if total == 0 { + return Ok(()); + } + let mut since_save = 0; + let result = game_review::run(config, settings, targets, cancel, &mut |event| { + if let JobEvent::Eval { nps, .. } = &event { + progress.done += 1; + progress.nps = *nps; + } + if let Some((key, eval)) = report.apply(&event) { + cache.insert(key, eval); + since_save += 1; + if since_save >= 200 + && let Some(dir) = cache_dir + { + let _ = cache.save(dir); + since_save = 0; + } + } + if matches!(event, JobEvent::Eval { .. }) { + on_progress(progress); + } + }); + report.refresh(); + if let Some(dir) = cache_dir { + let _ = cache.save(dir); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::PgnDatabase; + use chess_import::PgnDb; + + fn database(pgn: &str) -> Database { + let db = PgnDatabase::from_bytes( + pgn.as_bytes().to_vec(), + None, + &mut |_| {}, + &AtomicBool::new(false), + ) + .expect("pgn"); + Database::Pgn(PgnDb::new(db)) + } + + const PGN: &str = "\ +[White \"Вафин Радель\"] +[Black \"Иванов Иван\"] +[Date \"2026.01.10\"] +[BlackElo \"1500\"] +[Result \"1-0\"] + +1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 1-0 + +[White \"Петров Пётр\"] +[Black \"Вафин Радель\"] +[Date \"2026.02.11\"] +[WhiteElo \"1700\"] +[Result \"0-1\"] + +1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 0-1 + +[White \"Вафин Радель\"] +[Black \"Вафина РаÑ�на\"] +[Date \"2026.03.12\"] +[Result \"1/2-1/2\"] + +1. e4 c5 2. Nf3 Nc6 3. Bb5 e6 1/2-1/2 + +[White \"Вафин Р.\"] +[Black \"Сидоров\"] +[Date \"2026.04.01\"] +[Result \"0-1\"] + +1. d4 d5 2. c4 0-1 + +[White \"Вафин Радель\"] +[Black \"Set Up\"] +[FEN \"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1\"] +[SetUp \"1\"] +[Result \"*\"] + +1... e5 * +"; + + #[test] + fn candidates_games_and_openings_of_a_player() { + let db = database(PGN); + // Every name with both words ("Вафина РаÑ�на" has them too): the user picks. + let (list, total) = candidates(&db, "Вафин Р.", 10); + assert_eq!(total, 3, "{list:?}"); + assert_eq!(list[0].name, "Вафин Радель"); + assert_eq!(list[0].games, 4); + assert_eq!(list[1].name, "Вафин Р."); + assert_eq!(list[2].name, "Вафина РаÑ�на"); + let (one, _) = candidates(&db, "Радель", 10); + assert_eq!(one.len(), 1); + // Two spellings merged. + let player = Player::new([list[0].id, list[1].id]); + let never = AtomicBool::new(false); + let found = games_of(&db, &player, Side::Any, &never).expect("games"); + assert_eq!( + found, + vec![(0, true), (1, false), (2, true), (3, true), (4, true)] + ); + assert_eq!( + games_of(&db, &player, Side::Black, &never).expect("games"), + vec![(1, false)] + ); + let report = build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &never, + ) + .expect("report"); + assert_eq!(report.games.len(), 4, "the set-up game is left out"); + assert_eq!(report.skipped, 1); + assert_eq!(report.names, vec!["Вафин Радель", "Вафин Р."]); + let g = &report.games[0]; + assert_eq!( + (g.index, g.white, g.opponent.as_str(), g.opponent_elo), + (0, true, "Иванов Иван", 1500) + ); + assert_eq!(g.date, "2026.01.10"); + assert_eq!(g.outcome, Outcome::Win); + assert_eq!( + g.sans, + vec!["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O", "Bg7"] + ); + assert_eq!(g.keys.len(), 9); + let o = &report.openings[g.opening.expect("named")]; + assert!( + o.name + .starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), + "{}", + o.name + ); + assert_eq!(g.named, Some(6)); + assert_eq!(report.games[1].outcome, Outcome::Win); + assert_eq!(report.games[1].opponent_elo, 1700); + // White: two Rossolimo games and one Queen's Gambit; the family first. + let w = &report.white; + assert_eq!(w.games, vec![0, 2, 3]); + assert_eq!(w.families.len(), 2); + assert_eq!(w.families[0].name, "Sicilian Defense"); + assert_eq!(w.families[0].tally.games, 3 - 1); + assert_eq!( + w.families[0].variations.len(), + 2, + "3...g6 and 3...e6 are named apart" + ); + assert_eq!(w.families[1].name, "Queen's Gambit"); + assert_eq!(w.tree.nodes[0].tally.games, 3); + assert_eq!(w.tree.nodes[0].last_date, "2026.04.01"); + assert_eq!(w.tree.nodes[0].average_elo(), Some(1500)); + let b = &report.black; + assert_eq!(b.games, vec![1]); + assert_eq!(b.families[0].name, "Sicilian Defense"); + let name = &report.openings[b.families[0].variations[0].opening.unwrap()].name; + assert!(name.contains("Najdorf"), "{name}"); + assert!(report.evals.is_empty() && report.engine.is_none()); + assert_eq!(report.side(), Side::Any); + // Only White. + let white_only = build( + &db, + &player, + &Options { + plies: 4, + side: Side::White, + period: Period::All, + }, + &AtomicUsize::new(0), + &never, + ) + .expect("report"); + assert_eq!(white_only.games.len(), 3); + assert!(white_only.black.games.is_empty()); + assert!(white_only.games.iter().all(|g| g.ucis.len() <= 4)); + assert_eq!(white_only.side(), Side::White); + // The last two months before his newest game (2026.04.01): from 2026.02.01. + let recent = build( + &db, + &player, + &Options { + period: Period::Months(2), + ..Options::default() + }, + &AtomicUsize::new(0), + &never, + ) + .expect("report"); + let dates: Vec<&str> = recent.games.iter().map(|g| g.date.as_str()).collect(); + assert_eq!(dates, ["2026.02.11", "2026.03.12", "2026.04.01"]); + // The pool: the games a report can take (not the set-up one it skips). + let all = report.games.len(); + assert_eq!(report.skipped, 1); + assert_eq!(recent.pool.len(), all); + assert_eq!(recent.count(Period::All, Side::Any).games, all); + assert_eq!(recent.count(Period::Months(2), Side::Any).games, 3); + assert_eq!(recent.count(Period::Last(1), Side::White).games, 1); + // Cancelled. + let cancelled = AtomicBool::new(true); + assert!( + build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &cancelled + ) + .is_none() + ); + } + + #[test] + fn one_name_for_several_positions_is_one_variation() { + // "Sicilian Defense: Closed" is the table's name after 2.Nc3 and after 2...e6. + let db = database( + "[White \"A\"]\n[Black \"B\"]\n[Result \"1-0\"]\n\n1. e4 c5 2. Nc3 e6 1-0\n\n\ + [White \"A\"]\n[Black \"C\"]\n[Result \"0-1\"]\n\n1. e4 c5 2. Nc3 0-1\n\n", + ); + let player = Player::new([candidates(&db, "A", 1).0[0].id]); + let report = build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &AtomicBool::new(false), + ) + .expect("report"); + let fam = &report.white.families[0]; + assert_eq!(fam.name, "Sicilian Defense"); + assert_eq!(fam.variations.len(), 1); + let v = &fam.variations[0]; + assert_eq!(v.games, vec![0, 1]); + let o = &report.openings[v.opening.unwrap()]; + assert_eq!( + (o.name.as_str(), o.line.as_str()), + ("Sicilian Defense: Closed", "1. e4 c5 2. Nc3") + ); + } + + #[test] + fn legacy_book_fields_survive_report_serde() { + let db = database(PGN); + let (list, _) = candidates(&db, "Вафин Р.", 2); + let player = Player::new([list[0].id, list[1].id]); + let mut report = build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &AtomicBool::new(false), + ) + .expect("report"); + assert!(report.book.is_none() && report.book_counts.is_empty()); + let exit = BookExit { + ply: 6, + by_player: false, + count: 1, + }; + report.games[0].book = Some(exit); + report.book = Some(BookInfo { + fingerprint: 17, + threshold: 5, + left: 1, + }); + report.book_counts.insert(report.games[0].keys[0], 4); + let json = serde_json::to_string(&report).expect("serialize"); + let restored: PrepReport = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(restored.games[0].book, Some(exit)); + assert_eq!(restored.book, report.book); + assert_eq!(restored.book_counts, report.book_counts); + } + + #[test] + fn evaluations_give_the_errors_by_opening_and_the_report_is_cached() { + let db = database(PGN); + let (list, _) = candidates(&db, "Вафин Радель", 1); + let player = Player::new([list[0].id]); + let never = AtomicBool::new(false); + let mut report = build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &never, + ) + .expect("report"); + let total = report.distinct_positions(); + // 9 + 11 + 7 positions; the start and 1.e4 c5 2.Nf3 shared by three games, + // 2...Nc6 3.Bb5 by two. + assert_eq!(total, 27 - 10); + let targets = report.targets(); + assert_eq!(targets.len(), total); + // One colour: the positions of its games only (the start position is in both). + let black = report.targets_for(Side::Black); + assert_eq!(black.len(), report.games[1].keys.len()); + assert_eq!(report.distinct_positions_for(Side::Black), black.len()); + assert!(report.distinct_positions_for(Side::White) < total); + assert_eq!(report.missing_for(Side::Black), black.len()); + assert_eq!(targets[0].key, format!("{:016x}", report.games[0].keys[0])); + assert!(targets[0].pos.moves.is_empty()); + assert_eq!(targets[3].pos.moves, vec!["e2e4", "c7c5", "g1f3"]); + assert_eq!(targets[3].turn, uci::Side::Black); + assert!( + targets + .iter() + .all(|t| t.played.is_none() && t.known.is_none()) + ); + // The engine says: every move fine but 3.Bb5, a blunder (+0.3 → −1.5). + let mut cache = PositionCache::default(); + for t in &targets { + let key = u64::from_str_radix(&t.key, 16).unwrap(); + let after_bb5 = report.games[0].keys[5]; + let eval = if key == after_bb5 { + Eval::Cp(-150) + } else { + Eval::Cp(30) + }; + let before_bb5 = report.games[0].keys[4]; + let pv = if key == before_bb5 { + vec!["d2d4".to_owned()] + } else { + report + .games + .iter() + .find_map(|game| { + game.keys + .iter() + .position(|&k| k == key) + .and_then(|ply| game.ucis.get(ply)) + .map(|uci| vec![uci.clone()]) + }) + .unwrap_or_default() + }; + let event = JobEvent::Eval { + key: t.key.clone(), + eval: game_review::PosEval { + eval, + pv, + depth: 12, + second: None, + shallow: None, + }, + nps: 0, + }; + let (k, e) = report.apply(&event).expect("an evaluation"); + cache.insert(k, e); + } + assert_eq!(report.missing(), 0); + assert!(report.evaluated()); + report.refresh(); + assert_eq!(report.engine.as_ref().map(|e| e.nodes), Some(SEARCH_NODES)); + let w = &report.white; + assert_eq!(w.counts.blunders, 2); + assert_eq!(w.errors.len(), 2); + assert_eq!(w.errors[0].san, "Bb5"); + assert_eq!(w.errors[0].best_san, "d4"); + assert_eq!(w.errors[0].ply, 4); + assert_eq!( + report.games[w.errors[0].game as usize].move_label(4), + "3. Bb5" + ); + assert_eq!(w.families[0].errors.blunders, 2); + assert_eq!(w.families[0].variations[0].errors.blunders, 1); + assert_eq!(w.families[0].variations[0].error_list.len(), 1); + assert_eq!(w.families.len(), 1); + assert_eq!(w.repeated.len(), 1); + assert_eq!(w.repeated[0].games, vec![0, 2]); + assert_eq!(w.repeated[0].tally.draws, 1); + assert!(report.black.errors.is_empty()); + // Cached: the report by database, player and options; the evaluations by + // position, for anyone. + let dir = std::env::temp_dir().join(format!("prep-report-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert!(PrepReport::load(&dir, &db, &player, &Options::default()).is_none()); + report.save(&dir).expect("saved"); + let again = PrepReport::load(&dir, &db, &player, &Options::default()).expect("cached"); + assert_eq!(again.white.errors, report.white.errors); + assert_eq!(again.evals.len(), report.evals.len()); + assert!( + PrepReport::load( + &dir, + &db, + &player, + &Options { + plies: 10, + side: Side::Any, + period: Period::All, + } + ) + .is_none() + ); + let other = Player::new([list[0].id + 1]); + assert!(PrepReport::load(&dir, &db, &other, &Options::default()).is_none()); + let mut fresh = build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &never, + ) + .expect("report"); + assert!(!fresh.evaluated()); + assert_eq!(fresh.take_cached(&cache), total); + assert!( + fresh.evaluated(), + "evaluations from the cache judge the errors too" + ); + assert_eq!(fresh.white.repeated, report.white.repeated); + assert_eq!(fresh.take_cached(&cache), 0); + // A report of another search (from before the fixed one) keeps its games but + // not its evaluations. + let path = PrepReport::cache_path(&dir, report.fingerprint, &player, &Options::default()); + let mut json: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).expect("report")).expect("json"); + json.as_object_mut().expect("report").remove("search"); + std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written"); + let old = PrepReport::load(&dir, &db, &player, &Options::default()).expect("still read"); + assert!(!old.evaluated() && old.white.errors.is_empty()); + assert_eq!(old.missing(), total); + assert_eq!(old.search, SEARCH_VERSION); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn cached_errors_and_all_aggregates_are_rejudged_after_opponent_error() { + let db = database( + r#"[White "Target"] +[Black "A"] +[Result "1-0"] + +1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 1-0 + +[White "Target"] +[Black "B"] +[Result "0-1"] + +1. Nf3 Nc6 2. e4 e5 3. Bb5 a6 0-1 +"#, + ); + let (list, _) = candidates(&db, "Target", 1); + let player = Player::new([list[0].id]); + let options = Options::default(); + let mut report = build( + &db, + &player, + &options, + &AtomicUsize::new(0), + &AtomicBool::new(false), + ) + .unwrap(); + for game in &report.games { + for (ply, &key) in game.keys.iter().enumerate() { + report.evals.insert( + key, + PositionEval { + nodes: SEARCH_NODES, + eval: Eval::Cp(0), + pv: game.ucis.get(ply).cloned().into_iter().collect(), + depth: 12, + }, + ); + } + } + let first = &report.games[0]; + let before_bb5 = first.keys[4]; + report.evals.get_mut(&before_bb5).unwrap().pv = vec!["d2d4".to_owned()]; + report.evals.get_mut(&first.keys[5]).unwrap().eval = Eval::Cp(-150); + report.refresh(); + assert_eq!(report.white.errors.len(), 2); + assert_eq!(report.white.repeated.len(), 1); + assert_eq!(report.white.repeated[0].times(), 2); + let eval_count = report.evals.len(); + // Only the first move order contains this earlier error by Black. The + // second game transposes into the same Bb5 error through a clean prefix. + report.evals.get_mut(&report.games[0].keys[1]).unwrap().pv = vec!["c7c5".to_owned()]; + report.evals.get_mut(&report.games[0].keys[2]).unwrap().eval = Eval::Cp(150); + // Persist intentionally stale derived errors with current search metadata. + let dir = std::env::temp_dir().join(format!("prep-prefix-cache-{}", std::process::id())); + report.save(&dir).unwrap(); + let mut loaded = PrepReport::load(&dir, &db, &player, &options).unwrap(); + assert_eq!(loaded.search, SEARCH_VERSION); + assert_eq!(loaded.evals.len(), eval_count); + assert_eq!(loaded.take_cached(&PositionCache::default()), 0); + assert_eq!(loaded.white.errors.len(), 1); + assert_eq!(loaded.white.errors[0].game, 1); + assert!(loaded.white.repeated.is_empty()); + assert_eq!(loaded.white.counts.total(), 1); + assert_eq!( + loaded + .white + .families + .iter() + .map(|f| f.errors.total()) + .sum::(), + 1 + ); + let variants: Vec<_> = loaded + .white + .families + .iter() + .flat_map(|f| &f.variations) + .collect(); + assert_eq!(variants.iter().map(|v| v.errors.total()).sum::(), 1); + assert_eq!( + variants + .iter() + .flat_map(|v| &v.error_list) + .copied() + .collect::>(), + vec![0] + ); + assert_eq!( + loaded.games.len(), + 2, + "the repertoire itself is not filtered" + ); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). + #[test] + fn the_engine_run_fills_the_report_and_the_cache() { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + let db = database(PGN); + let (list, _) = candidates(&db, "Вафин Радель", 1); + let player = Player::new([list[0].id]); + let never = AtomicBool::new(false); + let mut report = build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &never, + ) + .expect("report"); + let total = report.distinct_positions(); + let settings = JobSettings::new(2, None); + let mut cache = PositionCache::default(); + let mut last = Progress::default(); + analyse( + &mut report, + &mut cache, + None, + uci::EngineConfig::new(fake), + &settings, + &never, + &mut |p| last = p, + ) + .expect("the job runs"); + assert_eq!((last.done, last.total), (total, total)); + assert_eq!(report.missing(), 0); + assert_eq!(cache.len(), total); + assert_eq!( + report.engine.as_ref().map(|e| e.name.as_str()), + Some("Fake UCI") + ); + // A second run has nothing to do; a cancelled one ends at once. + let mut again = build( + &db, + &player, + &Options::default(), + &AtomicUsize::new(0), + &never, + ) + .expect("report"); + let cancelled = AtomicBool::new(true); + let mut calls = 0; + analyse( + &mut again, + &mut cache, + None, + uci::EngineConfig::new(fake), + &settings, + &cancelled, + &mut |_| calls += 1, + ) + .expect("nothing to do"); + assert_eq!(again.missing(), 0, "all from the cache"); + assert_eq!(calls, 1); + } +} diff --git a/crates/prep/src/openings.rs b/crates/prep/src/openings.rs new file mode 100644 index 0000000..7827354 --- /dev/null +++ b/crates/prep/src/openings.rs @@ -0,0 +1,55 @@ +//! Opening names: the table lives in the `chess-openings` crate (the game review uses it +//! too); here only what a report keeps of it. + +use std::collections::HashMap; + +pub use chess_openings::*; + +/// The openings a report refers to, each once, in the order they were first met. +#[derive(Default)] +pub struct OpeningSet { + pub list: Vec, + by_table: HashMap, +} + +impl OpeningSet { + /// The place of table entry `id` in [`OpeningSet::list`]. + pub fn intern(&mut self, id: usize) -> usize { + if let Some(&i) = self.by_table.get(&id) { + return i; + } + self.list.push(get(id).clone()); + self.by_table.insert(id, self.list.len() - 1); + self.list.len() - 1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::shakmaty::Chess; + use chess_core::shakmaty::Position; + use chess_core::shakmaty::san::San; + + fn keys(moves: &[&str]) -> Vec { + let mut pos = Chess::default(); + let mut out = vec![key(&pos)]; + for s in moves { + let m = s.parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(m); + out.push(key(&pos)); + } + out + } + + #[test] + fn a_set_keeps_each_opening_once() { + let mut set = OpeningSet::default(); + let id = deepest(&keys(&["e4", "c5"])).unwrap().1; + let other = deepest(&keys(&["d4"])).unwrap().1; + assert_eq!(set.intern(id), 0); + assert_eq!(set.intern(other), 1); + assert_eq!(set.intern(id), 0); + assert_eq!(set.list.len(), 2); + } +} diff --git a/crates/prep/src/period.rs b/crates/prep/src/period.rs new file mode 100644 index 0000000..4798015 --- /dev/null +++ b/crates/prep/src/period.rs @@ -0,0 +1,250 @@ +//! Which of the player's games a report takes: all, those of the last months (counted +//! back from his newest game, so an old database is not left empty), or his last games +//! of each colour. Games without a date are taken by «all» only; by number they count +//! as the oldest, in the order of the database (so a database without dates gives its +//! last records). When no game has a date, a period by months takes them all: it +//! cannot choose, and an empty report would explain nothing. + +use serde::{Deserialize, Serialize}; + +use chess_import::chessbase::base::Side; + +/// The games a report takes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Period { + #[default] + All, + /// Played within this many months before the player's newest game. + Months(u16), + /// The newest this many games of each colour. + Last(u32), +} + +/// One game of the player before the choice. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PoolGame { + /// Record index in the database. + pub index: u32, + pub white: bool, + /// `yyyymmdd` (month or day 0 when unknown); 0: no date. + pub date: u32, +} + +/// What a period takes of the games of the colour(s) looked at. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Chosen { + pub games: usize, + /// Of all the games: undated ones a period by months leaves out. + pub undated_out: usize, +} + +/// The latest day a PGN date can mean: «2026.??.??» → 2026.12.31, «2026.02.??» → +/// 2026.02.31 (only compared, never shown). +fn latest(date: u32) -> u32 { + match (date / 100 % 100, date % 100) { + (0, _) => date / 10000 * 10000 + 1231, + (_, 0) => date + 31, + _ => date, + } +} + +/// Today as `yyyymmdd` (UTC). +fn today() -> u32 { + let days = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() / 86_400) as i64; + // Days since 1970 to the civil date (H. Hinnant's algorithm). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + (y * 10000 + m * 100 + d) as u32 +} + +/// The date as the choice sees it: one after `today` is a typo («2206») and counts as +/// no date. +fn known(date: u32, today: u32) -> u32 { + if date > today { 0 } else { date } +} + +/// The date of the player's newest game as written (0: none dated): by its earliest +/// day, so that one game of «2026.??.??» does not move the period past the exactly +/// dated ones. +fn newest_at(pool: &[PoolGame], today: u32) -> u32 { + pool.iter().map(|g| known(g.date, today)).max().unwrap_or(0) +} + +/// The date of the player's newest game as written (0: none dated). +pub fn newest(pool: &[PoolGame]) -> u32 { + newest_at(pool, today()) +} + +/// The first day within `months` before the day `end` (`yyyymmdd`). +fn cutoff(end: u32, months: u16) -> u32 { + let (y, m, d) = (end / 10000, end / 100 % 100, end % 100); + let total = (y * 12 + m - 1).saturating_sub(u32::from(months)); + (total / 12) * 10000 + (total % 12 + 1) * 100 + d +} + +/// The games `period` takes: (record, the player had White), in record order. +pub fn choose(pool: &[PoolGame], period: Period) -> Vec<(u32, bool)> { + choose_at(pool, period, today()) +} + +/// [`choose`] on the day `today`. A partly known date is in a period when any day it +/// can mean is. +fn choose_at(pool: &[PoolGame], period: Period, today: u32) -> Vec<(u32, bool)> { + let mut out: Vec<(u32, bool)> = match period { + Period::All => pool.iter().map(|g| (g.index, g.white)).collect(), + Period::Months(months) => { + let newest = newest_at(pool, today); + if newest == 0 { + return choose_at(pool, Period::All, today); + } + let from = cutoff(latest(newest).min(today), months); + pool.iter() + .filter(|g| known(g.date, today) != 0 && latest(g.date) >= from) + .map(|g| (g.index, g.white)) + .collect() + } + Period::Last(n) => { + let mut out = Vec::new(); + for white in [true, false] { + let mut games: Vec<&PoolGame> = pool.iter().filter(|g| g.white == white).collect(); + // Newest first; the undated (0) last, later records counted newer. + games.sort_by(|a, b| { + known(b.date, today) + .cmp(&known(a.date, today)) + .then(b.index.cmp(&a.index)) + }); + out.extend(games.iter().take(n as usize).map(|g| (g.index, g.white))); + } + out + } + }; + out.sort_unstable(); + out +} + +/// How many games of `side` `period` takes, and the undated ones it leaves out. +pub fn count(pool: &[PoolGame], period: Period, side: Side) -> Chosen { + let of_side = |white: bool| match side { + Side::Any => true, + Side::White => white, + Side::Black => !white, + }; + let games = choose(pool, period) + .iter() + .filter(|(_, w)| of_side(*w)) + .count(); + let undated_out = match period { + Period::Months(_) if newest(pool) != 0 => pool + .iter() + .filter(|g| g.date == 0 && of_side(g.white)) + .count(), + _ => 0, + }; + Chosen { games, undated_out } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn g(index: u32, white: bool, date: u32) -> PoolGame { + PoolGame { index, white, date } + } + + #[test] + fn months_count_back_from_the_newest_game() { + let pool = [ + g(0, true, 20200105), + g(1, false, 20240301), + g(2, true, 20250228), + g(3, true, 20250301), + g(4, false, 0), + g(5, true, 20260301), + ]; + assert_eq!(cutoff(20260301, 12), 20250301); + assert_eq!(cutoff(20260115, 1), 20251215); + // Partly known dates. + assert_eq!(latest(20260000), 20261231); + assert_eq!(latest(20260200), 20260231); + let today = 20261031; + let year_only = [ + g(0, true, 20260000), + g(1, true, 20250301), + g(2, true, 20260700), + ]; + // From «2026.07.??», the newest: its last day 2026.07.31, three months back + // 2026.04.31; «2026» may be any day of the year, so it is in. + assert_eq!( + choose_at(&year_only, Period::Months(3), today), + vec![(0, true), (2, true)] + ); + // A typo from the future is not the newest game. + let typo = [ + g(0, true, 22060101), + g(1, true, 20260301), + g(2, true, 20250101), + ]; + assert_eq!(newest_at(&typo, today), 20260301); + assert_eq!(choose_at(&typo, Period::Months(6), today), vec![(1, true)]); + assert_eq!(choose_at(&typo, Period::Last(1), today), vec![(1, true)]); + // One game of «2026» does not push out the exactly dated newest ones. + let mixed = [ + g(0, true, 20260510), + g(1, true, 20260000), + g(2, true, 20260301), + ]; + assert_eq!(newest_at(&mixed, today), 20260510); + assert_eq!(choose_at(&mixed, Period::Months(3), today).len(), 3); + assert_eq!( + choose(&pool, Period::Months(12)), + vec![(3, true), (5, true)] + ); + assert_eq!( + choose(&pool, Period::Months(24)), + vec![(1, false), (2, true), (3, true), (5, true)] + ); + assert_eq!(choose(&pool, Period::All).len(), 6); + let c = count(&pool, Period::Months(24), Side::Black); + assert_eq!((c.games, c.undated_out), (1, 1)); + assert_eq!(count(&pool, Period::All, Side::Any).undated_out, 0); + // Nothing dated: a period by months takes all. + let undated = [g(0, true, 0), g(1, false, 0)]; + assert_eq!(choose(&undated, Period::Months(12)).len(), 2); + assert_eq!( + count(&undated, Period::Months(12), Side::Any).undated_out, + 0 + ); + } + + #[test] + fn the_last_games_of_each_colour() { + let pool = [ + g(0, true, 20200101), + g(1, true, 0), + g(2, true, 20230101), + g(3, false, 20240101), + g(4, true, 20220101), + g(5, false, 20190101), + ]; + assert_eq!( + choose(&pool, Period::Last(2)), + vec![(2, true), (3, false), (4, true), (5, false)] + ); + // Without dates: the last records. + let undated = [g(0, true, 0), g(1, true, 0), g(2, true, 0)]; + assert_eq!( + choose(&undated, Period::Last(2)), + vec![(1, true), (2, true)] + ); + assert_eq!(count(&pool, Period::Last(1), Side::Any).games, 2); + } +} diff --git a/crates/prep/src/players.rs b/crates/prep/src/players.rs new file mode 100644 index 0000000..e9cb84b --- /dev/null +++ b/crates/prep/src/players.rs @@ -0,0 +1,92 @@ +//! The player: picked from the names of the database (never free text, so that +//! "Вафин" offers "Вафин Радель · 271" and "Вафина РаÑ�на · 10" and the user chooses), +//! as one or several name ids when the database spells the same person in several +//! ways ("Kasparov, G." and "Kasparov, Garry"), and the player's games by colour. + +use std::sync::atomic::{AtomicBool, AtomicUsize}; + +use chess_import::Database; +use chess_import::chessbase::base::{Filter, NameFilter, Side, SortKey}; +use serde::{Deserialize, Serialize}; + +/// A name of the database that matches a query, with its number of games. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Candidate { + pub id: u32, + pub name: String, + pub games: u32, +} + +/// Up to `limit` names containing every word of `query` (an initial with its full +/// stop finds the full name), names starting with the first word first, then by +/// number of games; and the number of all matches. +pub fn candidates(db: &Database, query: &str, limit: usize) -> (Vec, usize) { + let (list, total) = db.suggest_players(query, limit); + let list = list + .into_iter() + .map(|s| Candidate { + id: s.id, + name: s.name, + games: s.games, + }) + .collect(); + (list, total) +} + +/// The player of a report: one or more name ids of the database. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Player { + pub ids: Vec, +} + +impl Player { + pub fn new(ids: impl IntoIterator) -> Player { + let mut ids: Vec = ids.into_iter().collect(); + ids.sort_unstable(); + ids.dedup(); + Player { ids } + } + + /// The names behind the ids, as the game list shows them. + pub fn names(&self, db: &Database) -> Vec { + self.ids + .iter() + .map(|&id| db.player_name(id).to_owned()) + .collect() + } +} + +/// The player's games for `side`: (record index, the player had White), in record +/// order. `None` when cancelled. +pub fn games_of( + db: &Database, + player: &Player, + side: Side, + cancel: &AtomicBool, +) -> Option> { + let mut out = Vec::new(); + for &id in &player.ids { + for (s, white) in [(Side::White, true), (Side::Black, false)] { + if side != Side::Any && side != s { + continue; + } + let filter = Filter { + player: NameFilter { + text: String::new(), + exact: Some(id), + }, + side: s, + games_only: true, + ..Filter::default() + }; + let found = db.query(&filter, SortKey::Number, true, &AtomicUsize::new(0), cancel)?; + out.extend(found.into_iter().map(|i| (i, white))); + } + } + // The same record with the same colour twice: two ids of the player on one side + // cannot happen, but two ids on both sides of one game can (a game against + // oneself in a spelling-merged list): it is kept once per colour. + out.sort_unstable(); + out.dedup(); + Some(out) +} diff --git a/crates/prep/src/tree.rs b/crates/prep/src/tree.rs new file mode 100644 index 0000000..50dc250 --- /dev/null +++ b/crates/prep/src/tree.rs @@ -0,0 +1,370 @@ +//! The repertoire tree of one colour: the player's games laid over each other by +//! move order (it reads as a repertoire: 1.e4 c5 2.Nf3 …), every node carrying the +//! key of its position, so that two nodes reached by different move orders are seen +//! to be the same position (a transposition) and get the same opening name. + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use crate::games::{GameInfo, Tally}; +use crate::openings::{self, OpeningSet}; + +/// A position of the tree: the move that led to it from its parent, and the games +/// that went through it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Node { + pub key: u64, + /// Half-moves from the start (0: the root). + pub ply: u8, + /// The move from the parent (empty for the root). + pub uci: String, + pub san: String, + pub parent: Option, + /// Most played first. + pub children: Vec, + pub tally: Tally, + /// The latest date among the games (PGN form; empty when none has one). + pub last_date: String, + /// Sum and number of the known opponent ratings, for the average. + pub elo_sum: u64, + pub elo_count: u32, + /// Games through the node: indices into [`crate::PrepReport::games`], in order. + pub games: Vec, + /// The same position is reached elsewhere in the tree by another move order. + pub transposition: bool, + /// The deepest named position on the path to the node + /// ([`crate::PrepReport::openings`]); `named` when it is this one. + pub opening: Option, + pub named: bool, +} + +impl Node { + pub fn average_elo(&self) -> Option { + (self.elo_count > 0).then(|| (self.elo_sum / u64::from(self.elo_count)) as u32) + } +} + +/// The tree of one colour; `nodes[0]` is the root (the start position). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Tree { + pub nodes: Vec, +} + +impl Tree { + /// Lays the lines of `games[g]` for `g` in `which` over each other, `plies` deep. + pub fn build( + games: &[GameInfo], + which: &[u32], + plies: usize, + openings: &mut OpeningSet, + ) -> Tree { + let mut tree = Tree { + nodes: vec![Node { + key: games + .first() + .and_then(|g| g.keys.first().copied()) + .unwrap_or_default(), + ply: 0, + uci: String::new(), + san: String::new(), + parent: None, + children: Vec::new(), + tally: Tally::default(), + last_date: String::new(), + elo_sum: 0, + elo_count: 0, + games: Vec::new(), + transposition: false, + opening: None, + named: false, + }], + }; + for &g in which { + let game = &games[g as usize]; + if let Some(&k) = game.keys.first() { + tree.nodes[0].key = k; + } + tree.count(0, g, game); + let mut at = 0usize; + for i in 0..game.ucis.len().min(plies) { + let next = match tree.nodes[at] + .children + .iter() + .find(|&&c| tree.nodes[c as usize].uci == game.ucis[i]) + { + Some(&c) => c as usize, + None => { + let key = game.keys[i + 1]; + // A more general name than the path's keeps the path's + // (see `openings::deepest`). + let parent = tree.nodes[at] + .opening + .map(|o| openings.list[o].name.clone()); + let named = openings::by_position(key).filter(|&id| { + parent.as_deref().is_none_or(|p| { + !openings::is_prefix_name(&openings::get(id).name, p) + }) + }); + let opening = named + .map(|id| openings.intern(id)) + .or(tree.nodes[at].opening); + tree.nodes.push(Node { + key, + ply: u8::try_from(i + 1).unwrap_or(u8::MAX), + uci: game.ucis[i].clone(), + san: game.sans[i].clone(), + parent: Some(at as u32), + children: Vec::new(), + tally: Tally::default(), + last_date: String::new(), + elo_sum: 0, + elo_count: 0, + games: Vec::new(), + transposition: false, + opening, + named: named.is_some(), + }); + let c = tree.nodes.len() - 1; + tree.nodes[at].children.push(c as u32); + c + } + }; + tree.count(next, g, game); + at = next; + } + } + // Most played first among the children. + let played: Vec = tree.nodes.iter().map(|n| n.tally.games).collect(); + for n in &mut tree.nodes { + n.children + .sort_by(|a, b| played[*b as usize].cmp(&played[*a as usize]).then(a.cmp(b))); + } + // Transpositions: one key in several nodes. + let mut seen: HashMap = HashMap::new(); + for n in &tree.nodes { + *seen.entry(n.key).or_default() += 1; + } + for n in &mut tree.nodes { + n.transposition = seen.get(&n.key).is_some_and(|c| *c > 1); + } + // One position, one name: the most precise of its move orders' names; a node + // is «named» where its name differs from its parent's. + let mut best: HashMap = HashMap::new(); + for n in tree.nodes.iter().filter(|n| n.transposition) { + if let Some(o) = n.opening { + let e = best.entry(n.key).or_insert(o); + if openings::is_prefix_name(&openings.list[*e].name, &openings.list[o].name) { + *e = o; + } + } + } + for i in 0..tree.nodes.len() { + if let Some(&o) = best.get(&tree.nodes[i].key) { + tree.nodes[i].opening = Some(o); + } + let parent = tree.nodes[i] + .parent + .and_then(|p| tree.nodes[p as usize].opening); + let name = |o: Option| o.map(|o| openings.list[o].name.as_str()); + tree.nodes[i].named = + tree.nodes[i].opening.is_some() && name(tree.nodes[i].opening) != name(parent); + } + tree + } + + /// The games through the position `key` by any move order (indices into + /// [`crate::PrepReport::games`], in order). + pub fn position_games(&self, key: u64) -> Vec { + let mut out: Vec = self + .nodes + .iter() + .filter(|n| n.key == key) + .flat_map(|n| n.games.iter().copied()) + .collect(); + out.sort_unstable(); + out.dedup(); + out + } + + /// The latest date among the games through the position `key`. + pub fn position_last_date(&self, key: u64) -> &str { + self.nodes + .iter() + .filter(|n| n.key == key) + .map(|n| n.last_date.as_str()) + .max_by_key(|d| chess_import::pgn_catalog::date_number(d)) + .unwrap_or("") + } + + fn count(&mut self, node: usize, g: u32, game: &GameInfo) { + let n = &mut self.nodes[node]; + n.tally.add(game.outcome); + n.games.push(g); + if game.opponent_elo > 0 { + n.elo_sum += u64::from(game.opponent_elo); + n.elo_count += 1; + } + if game.date_number() > chess_import::pgn_catalog::date_number(&n.last_date) { + n.last_date = game.date.clone(); + } + } + + /// The statistics of the position with `key` over all its move orders (the + /// sum of its nodes). + pub fn position_tally(&self, key: u64) -> Tally { + let mut t = Tally::default(); + for n in self.nodes.iter().filter(|n| n.key == key) { + t.games += n.tally.games; + t.wins += n.tally.wins; + t.draws += n.tally.draws; + t.losses += n.tally.losses; + } + t + } + + /// The path of moves to `node`, in SAN. + pub fn path(&self, node: usize) -> Vec<&str> { + let mut out = Vec::new(); + let mut at = Some(node); + while let Some(i) = at { + let n = &self.nodes[i]; + if n.parent.is_some() { + out.push(n.san.as_str()); + } + at = n.parent.map(|p| p as usize); + } + out.reverse(); + out + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::games::Outcome; + use chess_core::shakmaty::Chess; + use chess_core::shakmaty::san::SanPlus; + use chess_import::position::{key, uci}; + + pub(crate) fn game( + index: u32, + white: bool, + moves: &[&str], + result: &str, + date: &str, + elo: u16, + ) -> GameInfo { + let mut pos = Chess::default(); + let (mut ucis, mut sans, mut keys) = (Vec::new(), Vec::new(), vec![key(&pos)]); + for s in moves { + let m = s.parse::().unwrap().san.to_move(&pos).unwrap(); + ucis.push(uci(&m).to_string()); + sans.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); + keys.push(key(&pos)); + } + GameInfo { + index, + white, + opponent: "Opp".into(), + opponent_elo: elo, + date: date.into(), + outcome: Outcome::of(result, white), + ucis, + sans, + keys, + opening: None, + named: None, + book: None, + } + } + + #[test] + fn the_tree_counts_games_and_marks_transpositions() { + let games = vec![ + game( + 0, + true, + &["d4", "d5", "Nf3", "Nf6"], + "1-0", + "2026.01.05", + 1500, + ), + game(1, true, &["Nf3", "d5", "d4", "Nf6"], "0-1", "2026.03.01", 0), + game(2, true, &["d4", "d5", "c4"], "1/2-1/2", "2025.12.31", 1700), + game(3, false, &["e4", "c5"], "0-1", "2026.02.02", 1600), + game( + 4, + true, + &["d4", "d5", "c4", "e6", "Nc3", "Nf6", "h3"], + "1-0", + "", + 0, + ), + ]; + let mut set = OpeningSet::default(); + let tree = Tree::build(&games, &[0, 1, 2], 20, &mut set); + let root = &tree.nodes[0]; + assert_eq!(root.tally.games, 3); + assert_eq!(root.last_date, "2026.03.01"); + assert_eq!(root.average_elo(), Some(1600)); + assert_eq!(root.games, vec![0, 1, 2]); + // 1.d4 (2 games) before 1.Nf3 (1 game). + let kids: Vec<&str> = root + .children + .iter() + .map(|&c| tree.nodes[c as usize].san.as_str()) + .collect(); + assert_eq!(kids, vec!["d4", "Nf3"]); + // The position after 1.d4 d5 2.Nf3 / 1.Nf3 d5 2.d4 is in two nodes. + let shared: Vec<&Node> = tree.nodes.iter().filter(|n| n.transposition).collect(); + let keys: Vec = shared.iter().map(|n| n.key).collect(); + assert_eq!(shared.len(), 4, "{keys:?}"); + let after_nf3 = tree + .nodes + .iter() + .find(|n| n.ply == 3 && n.san == "Nf3") + .unwrap(); + let after_d4 = tree + .nodes + .iter() + .find(|n| n.ply == 3 && n.san == "d4") + .unwrap(); + assert_eq!(after_nf3.key, after_d4.key); + assert_eq!(tree.position_tally(after_nf3.key).games, 2); + assert_eq!(tree.position_games(after_nf3.key), vec![0, 1]); + assert_eq!(tree.position_last_date(after_nf3.key), "2026.03.01"); + assert!( + !tree + .nodes + .iter() + .find(|n| n.san == "c4") + .unwrap() + .transposition + ); + assert_eq!( + tree.path(after_d4.parent.unwrap() as usize), + vec!["Nf3", "d5"] + ); + // Names: 1.d4 d5 2.Nf3 is named in the table, 2...Nf6 is too (Zukertort); + // both move orders get the same name. + assert!(after_nf3.named && after_d4.named); + assert_eq!(after_nf3.opening, after_d4.opening); + let name = &set.list[after_nf3.opening.unwrap()].name; + assert!(name.starts_with("Queen's Pawn Game"), "{name}"); + // A node that is not named (4.h3 in the Queen's Gambit Declined) inherits the + // name of its path. + let tree = Tree::build(&games, &[0, 1, 2, 4], 20, &mut set); + let h3 = tree.nodes.iter().find(|n| n.san == "h3").unwrap(); + assert!(!h3.named); + assert_eq!(h3.opening, tree.nodes[h3.parent.unwrap() as usize].opening); + assert!( + set.list[h3.opening.unwrap()] + .name + .starts_with("Queen's Gambit Declined") + ); + // Depth limit. + let short = Tree::build(&games, &[0, 1, 2], 1, &mut set); + assert_eq!(short.nodes.len(), 3); + } +} diff --git a/crates/releases/Cargo.toml b/crates/releases/Cargo.toml new file mode 100644 index 0000000..b8896aa --- /dev/null +++ b/crates/releases/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "releases" +description = "The latest ChessPenguin release on GitHub: its version, files and SHA-256 sums (the desktop and Android apps share it)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +serde_json.workspace = true +ureq = "3.4" diff --git a/crates/releases/src/lib.rs b/crates/releases/src/lib.rs new file mode 100644 index 0000000..538ded1 --- /dev/null +++ b/crates/releases/src/lib.rs @@ -0,0 +1,220 @@ +//! The latest ChessPenguin release on GitHub: its version, its files and their SHA-256 +//! from the release's `SHA256SUMS.txt`. The desktop app updates itself with it, the +//! Android app offers its new APK; both are one release with one version (Cargo.toml). + +use std::io::Read; +use std::time::Duration; + +use serde_json::Value; + +/// GitHub's answer for the latest release. +pub const API: &str = "https://api.github.com/repos/vrubelroman/chessPenguin/releases/latest"; + +/// The site's update check: GitHub's answer passed on, and this installation counted for +/// the day (website/README.md, "Installations"). +pub const CHECK: &str = "https://chess.vrubel.xyz/api/update"; + +/// Where people download ChessPenguin. +pub const DOWNLOAD_PAGE: &str = "https://chess.vrubel.xyz/"; + +/// The version of this build (the workspace's: the desktop and the phone are one release). +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// The file of the release with every file's SHA-256. +pub const SUMS: &str = "SHA256SUMS.txt"; + +/// "0.7.1" / "v0.7.1" → (0, 7, 1). +pub fn parse_version(v: &str) -> Option<(u32, u32, u32)> { + let mut it = v.trim().trim_start_matches('v').split('.'); + let n = |s: Option<&str>| -> Option { + s?.chars() + .take_while(|c| c.is_ascii_digit()) + .collect::() + .parse() + .ok() + }; + Some((n(it.next())?, n(it.next())?, n(it.next()).unwrap_or(0))) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Asset { + pub name: String, + pub url: String, + pub size: u64, +} + +/// The latest release. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Release { + pub version: String, + /// Its page (what is new in it). + pub page: String, + pub assets: Vec, +} + +impl Release { + /// Newer than this build. + pub fn newer(&self) -> bool { + self.newer_than(VERSION) + } + + pub fn newer_than(&self, current: &str) -> bool { + match (parse_version(&self.version), parse_version(current)) { + (Some(v), Some(c)) => v > c, + _ => false, + } + } + + /// The file whose name ends with `suffix` ("-android-noengine.apk"). + pub fn asset_ending(&self, suffix: &str) -> Option<&Asset> { + self.assets.iter().find(|a| a.name.ends_with(suffix)) + } + + pub fn sums(&self) -> Option<&Asset> { + self.assets.iter().find(|a| a.name == SUMS) + } +} + +/// GitHub's answer for a release, as a [`Release`]. +pub fn parse_release(v: &Value) -> Option { + let tag = v["tag_name"].as_str()?; + let assets = v["assets"] + .as_array()? + .iter() + .filter_map(|a| { + Some(Asset { + name: a["name"].as_str()?.to_owned(), + url: a["browser_download_url"].as_str()?.to_owned(), + size: a["size"].as_u64().unwrap_or(0), + }) + }) + .collect(); + Some(Release { + version: tag.trim_start_matches('v').to_owned(), + page: v["html_url"].as_str().unwrap_or(DOWNLOAD_PAGE).to_owned(), + assets, + }) +} + +/// The SHA-256 of `name` in the text of a `SHA256SUMS.txt` (` ` lines, as +/// `sha256sum` writes them; a `*` before the name marks binary mode). +pub fn sum_in(sums: &str, name: &str) -> Option { + sums.lines().find_map(|l| { + let (hash, file) = l.split_once(char::is_whitespace)?; + (file.trim().trim_start_matches('*') == name).then(|| hash.to_lowercase()) + }) +} + +/// An HTTP client that says who asks (`client`: "ChessPenguin/0.15.0 (Android)"). +/// `body` bounds the time to read an answer's body: a stalled connection ends then. +fn agent(client: &str, body: Duration) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .user_agent(format!("{client} (+{DOWNLOAD_PAGE})")) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(30))) + .timeout_recv_body(Some(body)) + .build(); + ureq::Agent::new_with_config(config) +} + +/// Asks `api` (GitHub's [`API`], or a test server with the same answer) for the latest +/// release. `Err` with a short reason when there is no answer. +pub fn fetch_latest(api: &str, client: &str) -> Result { + let text = agent(client, Duration::from_secs(30)) + .get(api) + .header("Accept", "application/vnd.github+json") + .call() + .map_err(|e| e.to_string())? + .body_mut() + .with_config() + .limit(4 << 20) + .read_to_string() + .map_err(|e| e.to_string())?; + let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + parse_release(&v).ok_or_else(|| "unexpected answer".to_owned()) +} + +/// Asks the site for the latest release, counting this installation once a day: only its +/// random id (`install`, made up by the program), this version and `platform` ("windows", +/// "deb", "android"…) are sent. Without an answer from the site, GitHub is asked. +pub fn check_latest(install: &str, platform: &str, client: &str) -> Result { + // `CP_UPDATE_CHECK`: another site (a local one, to try it). + let site = std::env::var("CP_UPDATE_CHECK").unwrap_or_else(|_| CHECK.to_owned()); + let url = format!("{site}?install={install}&version={VERSION}&platform={platform}"); + fetch_latest(&url, client).or_else(|_| fetch_latest(API, client)) +} + +/// Opens a file of the release for reading; a whole download has half an hour. +pub fn open(asset: &Asset, client: &str) -> Result, String> { + let resp = agent(client, Duration::from_secs(1800)) + .get(&asset.url) + .call() + .map_err(|e| e.to_string())?; + Ok(Box::new(resp.into_body().into_reader())) +} + +/// The text of the release's `SHA256SUMS.txt`. +pub fn fetch_sums(release: &Release, client: &str) -> Result { + let sums = release.sums().ok_or("the release has no SHA256SUMS.txt")?; + let mut text = String::new(); + open(sums, client)? + .take(1 << 20) + .read_to_string(&mut text) + .map_err(|e| e.to_string())?; + Ok(text) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn versions() { + assert_eq!(parse_version("v0.7.1"), Some((0, 7, 1))); + assert_eq!(parse_version("0.10"), Some((0, 10, 0))); + assert_eq!(parse_version("1.2.3-rc1"), Some((1, 2, 3))); + assert_eq!(parse_version("x"), None); + let r = |v: &str| Release { + version: v.into(), + page: String::new(), + assets: Vec::new(), + }; + assert!(r("0.10.0").newer_than("0.9.9")); + assert!(!r("0.14.0").newer_than("0.14.0")); + assert!(!r("0.13.9").newer_than("0.14.0")); + assert!(!r("garbage").newer_than("0.14.0")); + } + + #[test] + fn github_answer() { + let v: Value = serde_json::from_str( + r#"{"tag_name":"v0.7.1","html_url":"https://github.com/x/releases/tag/v0.7.1", + "assets":[{"name":"SHA256SUMS.txt","browser_download_url":"https://x/s","size":10}, + {"name":"ChessPenguin-0.7.1-android-noengine.apk","browser_download_url":"https://x/a","size":9}]}"#, + ) + .unwrap(); + let r = parse_release(&v).unwrap(); + assert_eq!(r.version, "0.7.1"); + assert_eq!(r.page, "https://github.com/x/releases/tag/v0.7.1"); + assert_eq!(r.sums().map(|a| a.url.as_str()), Some("https://x/s")); + assert_eq!( + r.asset_ending("-android-noengine.apk").map(|a| a.size), + Some(9) + ); + assert!(r.asset_ending("-android.apk").is_none()); + } + + #[test] + fn sums() { + let text = "AB12 ChessPenguin-1-android.apk\ncd34 *ChessPenguin-1-android-noengine.apk\n"; + assert_eq!( + sum_in(text, "ChessPenguin-1-android.apk").as_deref(), + Some("ab12") + ); + assert_eq!( + sum_in(text, "ChessPenguin-1-android-noengine.apk").as_deref(), + Some("cd34") + ); + assert_eq!(sum_in(text, "other"), None); + } +} diff --git a/crates/trainer/Cargo.toml b/crates/trainer/Cargo.toml new file mode 100644 index 0000000..419cdce --- /dev/null +++ b/crates/trainer/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "trainer" +description = "Learning an opening of ChessPenguin: replaying a game's line from memory, its runs counted (the desktop and Android apps share it)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +chess-core.workspace = true +serde.workspace = true +serde_json.workspace = true +web-time.workspace = true +chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } diff --git a/crates/trainer/src/lib.rs b/crates/trainer/src/lib.rs new file mode 100644 index 0000000..8af37c7 --- /dev/null +++ b/crates/trainer/src/lib.rs @@ -0,0 +1,481 @@ +//! Learning an opening: the user replays from memory the moves of both sides of a +//! line of a game, from its start to the chosen move (docs/design/opening-trainer.md, +//! docs/research/opening-trainer.md). +//! +//! Only the move of the line is right: another move — a move of a variation or one +//! transposing — is a mistake; it is shown for a moment and taken back. From the third +//! mistake on a move the user may ask to see it (the run is then marked «with a hint»). +//! The runs of each line are kept in `training.json`, by the line itself (its start +//! position and moves), so they survive edits of the game and are shared between games +//! with the same line, in the file the app names ([`set_file`]). + +pub mod repertoire; + +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::Duration; +use web_time::Instant; + +use chess_core::shakmaty::fen::Fen; +use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Move, Square}; +use chess_core::{Game, MoveKind, NodeId}; +use serde::{Deserialize, Serialize}; + +/// How long a wrong move stays on the board before it is taken back. +pub const WRONG_SHOWN: Duration = Duration::from_millis(400); + +/// From this mistake on one move, the user may ask to see it. +pub const HINT_AFTER: u32 = 3; + +/// The runs of a line remembered for its «recent» row. +const RECENT: usize = 10; + +/// What a training starts from: the line and how to name it. +#[derive(Clone, Debug)] +pub struct TrainStart { + /// The FEN of the game's start (`None`: the standard position). + pub start_fen: Option, + pub line: Vec, + /// «Carlsen — Caruana», when the game names its players. + pub game: Option, + /// «Wijk aan Zee 2024», when the game says so. + pub event: Option, + /// The last move of the line («12…Rd8», SAN in Latin letters: the app shows it its + /// own way). + pub up_to: String, + /// Its move number. + pub last_number: u32, + /// The board as the game showed it. + pub flipped: bool, +} + +impl TrainStart { + /// The line from the start of `game` to `at` (`None`: no move there, or a null + /// move on the way — it cannot be played on the board). + pub fn from_game(game: &Game, at: NodeId) -> Option { + let path = game.path(at); + let mut line = Vec::new(); + for &n in &path[1..] { + match game.game_move(n)?.kind { + MoveKind::Normal(m) => line.push(m), + MoveKind::Null => return None, + } + } + if line.is_empty() { + return None; + } + let (n, side) = game.move_number(at)?; + let san = &game.game_move(at)?.san; + let up_to = match side { + chess_core::shakmaty::Color::White => format!("{n}.{san}"), + chess_core::shakmaty::Color::Black => format!("{n}…{san}"), + }; + let name = |t: &str| { + game.tag(t) + .map(str::trim) + .filter(|v| !v.is_empty() && *v != "?") + }; + let players = match (name("White"), name("Black")) { + (None, None) => None, + (w, b) => Some(format!("{} — {}", w.unwrap_or("?"), b.unwrap_or("?"))), + }; + let year = name("Date") + .map(|d| d.chars().take(4).collect::()) + .filter(|y| y.len() == 4 && y.chars().all(|c| c.is_ascii_digit())); + let event = [name("Event").map(str::to_owned), year] + .into_iter() + .flatten() + .collect::>() + .join(" "); + Some(TrainStart { + start_fen: (!game.start().is_standard()).then(|| game.start().fen()), + line, + game: players, + event: (!event.is_empty()).then_some(event), + up_to, + last_number: n, + flipped: false, + }) + } + + /// The key of the line in the statistics. + pub fn key(&self) -> String { + let start = match self + .start_fen + .as_deref() + .and_then(|f| f.parse::().ok()) + { + Some(fen) => fen + .into_position::(CastlingMode::Standard) + .unwrap_or_default(), + None => Chess::default(), + }; + line_key(&start, &self.line) + } +} + +/// The key of a line: its start position (no counters) and its moves in UCI. +pub fn line_key(start: &Chess, line: &[Move]) -> String { + let fen = Fen::from_position(start, EnPassantMode::Legal).to_string(); + let pos: Vec<&str> = fen.split(' ').take(4).collect(); + let moves: Vec = line + .iter() + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + .collect(); + format!("{} | {}", pos.join(" "), moves.join(" ")) +} + +/// A wrong move shown on the board for a moment. +#[derive(Clone, Debug)] +pub struct Flash { + /// The position after it. + pub after: Chess, + pub from: Square, + pub to: Square, + pub until: Instant, +} + +/// A training in progress (or done). +pub struct Training { + pub start: TrainStart, + pub key: String, + /// Mistakes on each half-move of the line in this run. + pub mistakes: Vec, + /// The move was shown (a hint) on each half-move. + pub shown: Vec, + /// The hint is on the board now (the arrow of the right move). + pub hint: bool, + pub flash: Option, + /// The run is over: all the moves made. + pub done: bool, + /// The line's runs before this one. + pub before: LineStats, + /// …and after it, once it is done. + pub after: Option, +} + +impl Training { + pub fn new(start: TrainStart) -> Training { + let key = start.key(); + let n = start.line.len(); + Training { + before: stats(&key), + key, + mistakes: vec![0; n], + shown: vec![false; n], + hint: false, + flash: None, + done: false, + after: None, + start, + } + } + + /// The same line again from the start. + pub fn again(&mut self) { + let n = self.start.line.len(); + self.before = stats(&self.key); + self.mistakes = vec![0; n]; + self.shown = vec![false; n]; + self.hint = false; + self.flash = None; + self.done = false; + self.after = None; + } + + pub fn total(&self) -> u32 { + self.mistakes.iter().sum() + } + + pub fn hinted(&self) -> bool { + self.shown.iter().any(|&s| s) + } + + /// The run is over: it counts. + pub fn finish(&mut self) { + self.done = true; + self.hint = false; + self.after = Some(record(&self.key, self.total(), self.hinted())); + } + + /// The move the line wants on half-move `k` (none past its end). + pub fn wanted(&self, k: usize) -> Option { + self.start.line.get(k).copied() + } + + /// Judges `m` played on half-move `k`: the line's move goes on (the last one ends + /// the run, counted), any other is a mistake on this move. Nothing once it is done. + pub fn judge(&mut self, k: usize, m: Move) -> Verdict { + if self.done { + return Verdict::Done; + } + let Some(want) = self.wanted(k) else { + return Verdict::Done; + }; + if m != want { + self.mistakes[k] += 1; + return Verdict::Wrong; + } + self.hint = false; + if k + 1 == self.start.line.len() { + self.finish(); + Verdict::Finished + } else { + Verdict::Right + } + } + + /// Mistakes on half-move `k` so far in this run. + pub fn mistakes_on(&self, k: usize) -> u32 { + self.mistakes.get(k).copied().unwrap_or(0) + } + + /// The user may ask to see the move of half-move `k` (enough mistakes on it). + pub fn may_show(&self, k: usize) -> bool { + !self.done && self.mistakes_on(k) >= HINT_AFTER + } + + /// Shows the move of half-move `k` (the run is then marked «with a hint»). + pub fn show(&mut self, k: usize) { + if let Some(s) = self.shown.get_mut(k) { + *s = true; + self.hint = true; + } + } +} + +/// What a move made in a training was. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// The line's move: the line goes on. + Right, + /// The line's last move: the run is over and counted. + Finished, + /// Another move: a mistake, taken back. + Wrong, + /// The run was already over. + Done, +} + +/// What is known of the runs of a line. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct LineStats { + pub runs: u32, + /// Mistakes of the last run. + pub last: Option, + /// The fewest mistakes of a run without a hint. + pub best: Option, + /// Runs without mistakes (or hints) in a row, to the last one. + pub clean_streak: u32, + /// The last runs, oldest first: mistakes, a hint. + pub recent: Vec<(u32, bool)>, + /// The day of the last run (for repetition by a schedule later). + pub last_date: String, +} + +/// The runs by line, as in the file: an entry that does not read is left as it is. +static STATS: Mutex>> = Mutex::new(None); + +/// The file of the runs, as the app names it. +static FILE: Mutex> = Mutex::new(None); + +/// Where the runs are kept (`training.json` in the app's data); read again from there +/// when next needed. Without a file nothing is kept between starts. +pub fn set_file(path: PathBuf) { + *FILE.lock().unwrap_or_else(|e| e.into_inner()) = Some(path); + *STATS.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +fn file() -> Option { + FILE.lock().ok().and_then(|f| f.clone()) +} + +/// Writes through a file beside it: a run cut short leaves the old file whole. +fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path).inspect_err(|_| { + let _ = std::fs::remove_file(&tmp); + }) +} + +fn with_stats(f: impl FnOnce(&mut serde_json::Map) -> R) -> R { + let mut guard = STATS.lock().unwrap_or_else(|e| e.into_inner()); + let map = guard.get_or_insert_with(load); + f(map) +} + +/// The file read; one that does not read as a whole is kept aside +/// (`training.json.unreadable`), not overwritten by the next run. +fn load() -> serde_json::Map { + let Some(path) = file() else { + return Default::default(); + }; + let Ok(bytes) = std::fs::read(&path) else { + return Default::default(); + }; + match serde_json::from_slice(&bytes) { + Ok(map) => map, + Err(e) => { + let aside = path.with_extension("json.unreadable"); + eprintln!( + "training: {} unreadable ({e}), kept as {}", + path.display(), + aside.display() + ); + let _ = std::fs::rename(&path, aside); + Default::default() + } + } +} + +/// The runs of the line `key` so far (an entry that does not read: none). +pub fn stats(key: &str) -> LineStats { + with_stats(|m| { + m.get(key) + .and_then(|v| serde_json::from_value(v.clone()).ok()) + .unwrap_or_default() + }) +} + +/// A run done: counted and written at once. +fn record(key: &str, mistakes: u32, hinted: bool) -> LineStats { + with_stats(|m| { + let mut s: LineStats = m + .get(key) + .and_then(|v| serde_json::from_value(v.clone()).ok()) + .unwrap_or_default(); + s.runs += 1; + s.last = Some(mistakes); + if !hinted { + s.best = Some(s.best.map_or(mistakes, |b| b.min(mistakes))); + } + s.clean_streak = if mistakes == 0 && !hinted { + s.clean_streak + 1 + } else { + 0 + }; + s.recent.push((mistakes, hinted)); + if s.recent.len() > RECENT { + s.recent.remove(0); + } + s.last_date = chrono::Local::now().format("%Y-%m-%d").to_string(); + if let Ok(v) = serde_json::to_value(&s) { + m.insert(key.to_owned(), v); + } + let out = s; + if let Some(path) = file() { + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(json) = serde_json::to_vec_pretty(m) + && let Err(e) = write_atomic(&path, &json) + { + eprintln!("training: save failed: {e}"); + } + } + out + }) +} + +/// The runs of the line from the start of `game` to `at`, for the move's menu +/// (`None`: no line there). +pub fn runs_to(game: &Game, at: NodeId) -> Option { + TrainStart::from_game(game, at).map(|t| stats(&t.key()).runs) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn a_line_is_kept_by_its_moves_and_counted() { + let dir = std::env::temp_dir().join(format!("cp-train-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + set_file(dir.join("training.json")); + let a = chess_core::parse_str("[White \"A\"]\n\n1. e4 c5 2. Nf3 d6 *").game; + let b = chess_core::parse_str("1. e4 c5 2. Nf3 d6 3. d4 (3. Bb5+) *").game; + let at = |g: &Game, k: usize| g.mainline()[k]; + let ta = TrainStart::from_game(&a, at(&a, 3)).unwrap(); + let tb = TrainStart::from_game(&b, at(&b, 3)).unwrap(); + // The same line in two games: one key. + assert_eq!(ta.key(), tb.key()); + assert_eq!(ta.game.as_deref(), Some("A — ?")); + assert_eq!(ta.up_to, "2…d6"); + let mut t = Training::new(ta); + t.mistakes[1] = 2; + t.finish(); + let s = stats(&t.key); + assert_eq!( + (s.runs, s.last, s.best, s.clean_streak), + (1, Some(2), Some(2), 0) + ); + t.again(); + t.shown[0] = true; + t.finish(); + let s = stats(&t.key); + // A hint: counted, not the best. + assert_eq!((s.runs, s.best), (2, Some(2))); + assert_eq!(s.recent, [(2, false), (0, true)]); + t.again(); + t.finish(); + let s = stats(&t.key); + assert_eq!((s.best, s.clean_streak), (Some(0), 1)); + // Written to the file. + let back: HashMap = + serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap(); + assert_eq!(back[&t.key].runs, 3); + // An entry that does not read stays in the file as it is. + let mut raw: serde_json::Map = + serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap(); + raw.insert("x".into(), serde_json::json!({"runs": "bad"})); + std::fs::write(dir.join("training.json"), serde_json::to_vec(&raw).unwrap()).unwrap(); + *STATS.lock().unwrap() = None; + t.again(); + t.finish(); + let raw: serde_json::Map = + serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap(); + assert_eq!(raw["x"], serde_json::json!({"runs": "bad"})); + assert_eq!(stats(&t.key).runs, 4); + // A file that does not read is kept aside, not lost. + std::fs::write(dir.join("training.json"), b"{ broken").unwrap(); + *STATS.lock().unwrap() = None; + t.again(); + t.finish(); + assert_eq!( + std::fs::read(dir.join("training.json.unreadable")).unwrap(), + b"{ broken" + ); + assert_eq!(stats(&t.key).runs, 1); + // The verdict of a move: a mistake counts on its move, the last right move ends. + let mut t = Training::new(tb); + let line = t.start.line.clone(); + assert_eq!(t.judge(0, line[1]), Verdict::Wrong); + assert_eq!(t.mistakes_on(0), 1); + assert!(!t.may_show(0)); + t.judge(0, line[1]); + t.judge(0, line[1]); + assert!(t.may_show(0)); + t.show(0); + assert_eq!(t.judge(0, line[0]), Verdict::Right); + assert!(!t.hint); + for (k, m) in line.iter().enumerate().skip(1).take(line.len() - 2) { + assert_eq!(t.judge(k, *m), Verdict::Right); + } + assert_eq!( + t.judge(line.len() - 1, line[line.len() - 1]), + Verdict::Finished + ); + assert!(t.done && t.hinted()); + assert_eq!(t.judge(0, line[0]), Verdict::Done); + // A null move on the way: nothing to train. + let n = chess_core::parse_str("1. e4 -- 2. d4 *").game; + assert!(TrainStart::from_game(&n, n.mainline()[2]).is_none()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/trainer/src/repertoire/acceptance_tests.rs b/crates/trainer/src/repertoire/acceptance_tests.rs new file mode 100644 index 0000000..f317ebe --- /dev/null +++ b/crates/trainer/src/repertoire/acceptance_tests.rs @@ -0,0 +1,564 @@ +use super::*; + +const DAY: i64 = 24 * 60 * 60; +const BASE: i64 = 1_800_000_000; + +fn item_key(index: usize) -> LearningItemKey { + LearningItemKey::local(format!("position-{index} w - -"), "e2e4") +} + +fn attempt( + key: &LearningItemKey, + id: impl Into, + event_type: TrainingEventType, + happened_at: i64, +) -> TrainingAttempt { + let actual_uci = match event_type { + TrainingEventType::IncorrectIndependent => "d2d4", + _ => "e2e4", + }; + TrainingAttempt { + user_id: key.user_id.clone(), + position_fen4: key.position_fen4.clone(), + client_attempt_id: id.into(), + session_id: "session-1".into(), + event_type, + expected_uci: key.expected_uci.clone(), + actual_uci: Some(actual_uci.into()), + response_time_ms: Some(750), + happened_at, + } +} + +fn record(item: &mut LearningItem, id: &str, event_type: TrainingEventType, happened_at: i64) { + apply_attempt( + item, + &attempt(&item.key, id, event_type, happened_at), + &SrsSettings::default(), + ) + .unwrap(); +} + +fn learnt_item(index: usize, reviewed_at: i64, next_review_at: i64) -> LearningItem { + let mut item = LearningItem::new(item_key(index)); + item.introduced = true; + item.correct_streak = 3; + item.correct_count = 3; + item.last_review_at = Some(reviewed_at); + item.last_correct_at = Some(reviewed_at); + item.next_review_at = Some(next_review_at); + item.previous_interval_seconds = Some(DAY); + item +} + +#[test] +fn at_02_first_independent_correct_introduces_learning_for_one_day() { + let mut item = LearningItem::new(item_key(0)); + record( + &mut item, + "at-02", + TrainingEventType::CorrectIndependent, + BASE, + ); + + assert!(item.introduced); + assert!(item.is_learning()); + assert!(!item.is_learnt()); + assert_eq!(item.correct_streak, 1); + assert_eq!(item.wrong_streak, 0); + assert_eq!(item.correct_count, 1); + assert_eq!(item.wrong_count, 0); + assert_eq!(item.last_review_at, Some(BASE)); + assert_eq!(item.last_correct_at, Some(BASE)); + assert_eq!(item.previous_interval_seconds, Some(DAY)); + assert_eq!(item.next_review_at, Some(BASE + DAY)); +} + +#[test] +fn at_03_third_independent_correct_is_learnt_and_still_scheduled() { + let mut item = LearningItem::new(item_key(0)); + for (id, at) in [("at-03-a", BASE), ("at-03-b", BASE + DAY)] { + record(&mut item, id, TrainingEventType::CorrectIndependent, at); + } + let third = BASE + 3 * DAY; + record( + &mut item, + "at-03-c", + TrainingEventType::CorrectIndependent, + third, + ); + + assert_eq!(item.correct_streak, 3); + assert!(item.is_learnt()); + assert!(!item.is_learning()); + assert_eq!(item.previous_interval_seconds, Some(4 * DAY)); + assert_eq!(item.next_review_at, Some(third + 4 * DAY)); +} + +#[test] +fn at_04_wrong_after_learnt_resets_streak_and_schedules_thirty_seconds() { + let mut item = LearningItem::new(item_key(0)); + for (id, at) in [ + ("at-04-a", BASE), + ("at-04-b", BASE + DAY), + ("at-04-c", BASE + 3 * DAY), + ] { + record(&mut item, id, TrainingEventType::CorrectIndependent, at); + } + let wrong_at = BASE + 7 * DAY; + record( + &mut item, + "at-04-wrong", + TrainingEventType::IncorrectIndependent, + wrong_at, + ); + + assert_eq!(item.correct_streak, 0); + assert_eq!(item.wrong_streak, 1); + assert!(item.is_learning()); + assert_eq!(item.last_correct_at, None); + assert_eq!(item.next_review_at, Some(wrong_at + 30)); + assert_eq!(item.last_wrong_move_uci.as_deref(), Some("d2d4")); + assert_eq!(item.last_wrong_at, Some(wrong_at)); + assert_eq!( + item.wrong_move_histogram.get("d2d4"), + Some(&WrongMoveStats { + count: 1, + last_at: wrong_at, + }) + ); +} + +#[test] +fn at_05_replay_after_error_does_not_change_knowledge_or_due() { + let mut item = LearningItem::new(item_key(0)); + record( + &mut item, + "at-05-wrong", + TrainingEventType::IncorrectIndependent, + BASE, + ); + let before = item.clone(); + record( + &mut item, + "at-05-replay", + TrainingEventType::ReplayAfterError, + BASE + 1, + ); + + assert_eq!(item, before); + assert_eq!(item.independent_attempt_count(), 1); + assert_eq!(item.correct_count, 0); + assert_eq!(item.next_review_at, Some(BASE + 30)); + assert_eq!(item.independent_response_times_ms, [750]); +} + +#[test] +fn at_06_preview_introduces_unseen_without_independent_success() { + let mut item = LearningItem::new(item_key(0)); + record(&mut item, "at-06", TrainingEventType::Previewed, BASE); + + assert!(item.introduced); + assert!(item.is_learning()); + assert_eq!(item.correct_streak, 0); + assert_eq!(item.wrong_streak, 0); + assert_eq!(item.independent_attempt_count(), 0); + assert_eq!(item.accuracy_percent(), None); + assert_eq!(item.last_correct_at, None); + assert_eq!(item.last_review_at, Some(BASE)); + assert_eq!(item.next_review_at, Some(BASE + 60)); + assert!(item.independent_response_times_ms.is_empty()); +} + +#[test] +fn at_08_learnt_item_is_also_due() { + let mut item = LearningItem::new(item_key(0)); + for (id, at) in [ + ("at-08-a", BASE), + ("at-08-b", BASE + DAY), + ("at-08-c", BASE + 3 * DAY), + ] { + record(&mut item, id, TrainingEventType::CorrectIndependent, at); + } + let now = item.next_review_at.unwrap(); + let summary = aggregate(std::slice::from_ref(&item), now, &SrsSettings::default()); + + assert_eq!(summary.total, 1); + assert_eq!(summary.learning, 0); + assert_eq!(summary.learnt, 1); + assert_eq!(summary.due, 1); + assert_eq!(summary.uncertain, 0); + assert_invariants(&summary); +} + +#[test] +fn at_12_accuracy_is_weighted_independent_accuracy_not_learning_status() { + let mut item = LearningItem::new(item_key(0)); + for index in 0..7 { + record( + &mut item, + &format!("at-12-correct-{index}"), + TrainingEventType::CorrectIndependent, + BASE + index, + ); + } + for index in 0..3 { + record( + &mut item, + &format!("at-12-wrong-{index}"), + TrainingEventType::IncorrectIndependent, + BASE + 7 + index, + ); + } + let summary = aggregate( + std::slice::from_ref(&item), + BASE + 10, + &SrsSettings::default(), + ); + + assert_eq!(item.correct_count, 7); + assert_eq!(item.wrong_count, 3); + assert_eq!(item.independent_attempt_count(), 10); + assert!((item.accuracy_percent().unwrap() - 70.0).abs() < f64::EPSILON); + assert!((summary.accuracy_percent.unwrap() - 70.0).abs() < f64::EPSILON); + assert_eq!(summary.accuracy_attempts, 10); + assert!(item.is_learning()); +} + +#[test] +fn at_13_accuracy_is_absent_without_independent_attempts() { + let item = LearningItem::new(item_key(0)); + let summary = aggregate(std::slice::from_ref(&item), BASE, &SrsSettings::default()); + + assert_eq!(item.accuracy_percent(), None); + assert_eq!(summary.accuracy_percent, None); + assert_eq!(summary.accuracy_attempts, 0); + assert_eq!(summary.repertoire_status, RepertoireStatus::NotStarted); +} + +#[test] +fn at_16_empty_scope_has_empty_status_and_no_percentages() { + let items: Vec = Vec::new(); + let summary = aggregate(items.iter(), BASE, &SrsSettings::default()); + + assert_eq!(summary.total, 0); + assert_eq!(summary.repertoire_status, RepertoireStatus::Empty); + assert_eq!(summary.next_due_at, None); + for percentage in [ + summary.coverage_percent, + summary.learnt_percent, + summary.confident_percent, + summary.learning_percent, + summary.unseen_percent, + summary.uncertain_of_learnt_percent, + summary.due_of_introduced_percent, + summary.accuracy_percent, + ] { + assert_eq!(percentage, None); + } + assert_invariants(&summary); +} + +#[test] +fn at_28_all_learnt_with_due_is_not_confirmed_current() { + let now = BASE + 20 * DAY; + let items: Vec<_> = (0..100) + .map(|index| { + let next = if index < 3 { now } else { now + DAY }; + learnt_item(index, now - DAY, next) + }) + .collect(); + let summary = aggregate(items.iter(), now, &SrsSettings::default()); + + assert_eq!(summary.total, 100); + assert_eq!(summary.learnt, 100); + assert_eq!(summary.due, 3); + assert_eq!(summary.next_due_at, None); + assert_eq!(summary.repertoire_status, RepertoireStatus::AllLearnt); + assert_invariants(&summary); +} + +#[test] +fn at_29_all_learnt_without_due_or_uncertain_is_confirmed_current() { + let now = BASE + 20 * DAY; + let items: Vec<_> = (0..100) + .map(|index| learnt_item(index, now - DAY, now + DAY)) + .collect(); + let summary = aggregate(items.iter(), now, &SrsSettings::default()); + + assert_eq!(summary.total, 100); + assert_eq!(summary.learnt, 100); + assert_eq!(summary.due, 0); + assert_eq!(summary.uncertain, 0); + assert_eq!(summary.next_due_at, Some(now + DAY)); + assert_eq!( + summary.repertoire_status, + RepertoireStatus::ConfirmedCurrent + ); + assert_invariants(&summary); +} + +#[test] +fn correct_after_four_days_schedules_eight_days() { + let settings = SrsSettings::default(); + let mut item = LearningItem::new(item_key(0)); + apply_independent_correct(&mut item, BASE, &settings); + apply_independent_correct(&mut item, BASE + 4 * DAY, &settings); + + assert_eq!(item.previous_interval_seconds, Some(8 * DAY)); + assert_eq!(item.next_review_at, Some(BASE + 12 * DAY)); +} + +#[test] +fn growth_interval_has_explicit_minimum_and_maximum() { + let settings = SrsSettings { + min_practical_interval_seconds: 3_600, + max_interval_seconds: 10 * DAY, + ..SrsSettings::default() + }; + let mut minimum = LearningItem::new(item_key(0)); + apply_independent_correct(&mut minimum, BASE, &settings); + apply_independent_correct(&mut minimum, BASE + 1, &settings); + assert_eq!(minimum.previous_interval_seconds, Some(3_600)); + assert_eq!(minimum.next_review_at, Some(BASE + 1 + 3_600)); + + let mut maximum = LearningItem::new(item_key(1)); + apply_independent_correct(&mut maximum, BASE, &settings); + apply_independent_correct(&mut maximum, BASE + 10 * DAY, &settings); + assert_eq!(maximum.previous_interval_seconds, Some(10 * DAY)); + assert_eq!(maximum.next_review_at, Some(BASE + 20 * DAY)); +} + +#[test] +fn preview_preserves_two_correct_streak_and_growth_base() { + let settings = SrsSettings::default(); + let mut item = LearningItem::new(item_key(0)); + apply_independent_correct(&mut item, BASE, &settings); + apply_independent_correct(&mut item, BASE + DAY, &settings); + let previous_interval = item.previous_interval_seconds; + let preview_at = BASE + 2 * DAY; + apply_preview(&mut item, preview_at, &settings); + + assert_eq!(item.correct_streak, 2); + assert_eq!(item.correct_count, 2); + assert_eq!(item.wrong_count, 0); + assert_eq!(item.wrong_streak, 0); + assert_eq!(item.last_correct_at, Some(BASE + DAY)); + assert_eq!(item.previous_interval_seconds, previous_interval); + assert_eq!(item.last_review_at, Some(preview_at)); + assert_eq!(item.next_review_at, Some(preview_at + 60)); +} + +#[test] +fn auto_context_and_illegal_move_create_no_independent_attempt() { + let settings = SrsSettings::default(); + let key = item_key(0); + let mut data = LearningData::default(); + assert_eq!( + data.apply_attempt( + attempt(&key, "illegal", TrainingEventType::IllegalMove, BASE), + &settings, + ), + Ok(AttemptApplication::Applied) + ); + assert_eq!( + data.apply_attempt( + attempt(&key, "auto", TrainingEventType::AutoContext, BASE + 1), + &settings, + ), + Ok(AttemptApplication::Applied) + ); + + let item = data.item(&key).unwrap(); + assert_eq!(item, &LearningItem::new(key)); + assert_eq!(item.independent_attempt_count(), 0); + assert_eq!(item.accuracy_percent(), None); + assert!(item.independent_response_times_ms.is_empty()); + assert_eq!(data.attempts.len(), 2); +} + +#[test] +fn duplicate_client_attempt_id_changes_state_only_once() { + let settings = SrsSettings::default(); + let key = item_key(0); + let first = attempt( + &key, + "duplicate-id", + TrainingEventType::CorrectIndependent, + BASE, + ); + let mut data = LearningData::default(); + assert_eq!( + data.apply_attempt(first.clone(), &settings), + Ok(AttemptApplication::Applied) + ); + let before = data.item(&key).unwrap().clone(); + assert_eq!( + data.apply_attempt(first, &settings), + Ok(AttemptApplication::Duplicate) + ); + + assert_eq!(data.item(&key), Some(&before)); + assert_eq!(data.item(&key).unwrap().correct_count, 1); + assert_eq!(data.item(&key).unwrap().correct_streak, 1); + assert_eq!(data.attempts.len(), 1); +} + +#[test] +fn uncertain_uses_strict_greater_of_grace_boundaries() { + let settings = SrsSettings::default(); + let mut item = learnt_item(0, BASE - 4 * DAY, BASE); + item.previous_interval_seconds = Some(4 * DAY); + assert!(!is_uncertain(&item, BASE + 7 * DAY, &settings)); + assert!(is_uncertain(&item, BASE + 7 * DAY + 1, &settings)); + + item.previous_interval_seconds = Some(40 * DAY); + assert!(!is_uncertain(&item, BASE + 7 * DAY + 1, &settings)); + assert!(!is_uncertain(&item, BASE + 10 * DAY, &settings)); + assert!(is_uncertain(&item, BASE + 10 * DAY + 1, &settings)); + + item.correct_streak = 2; + assert!(!is_uncertain(&item, BASE + 100 * DAY, &settings)); +} + +#[test] +fn aggregate_deduplicates_keys_and_weights_accuracy_once() { + let mut first = LearningItem::new(item_key(0)); + first.correct_count = 7; + first.wrong_count = 3; + let second = LearningItem::new(item_key(1)); + let items = [first.clone(), first, second]; + let summary = aggregate(items.iter(), BASE, &SrsSettings::default()); + + assert_eq!(summary.total, 2); + assert_eq!(summary.unseen, 2); + assert_eq!(summary.accuracy_correct, 7); + assert_eq!(summary.accuracy_wrong, 3); + assert_eq!(summary.accuracy_attempts, 10); + assert!((summary.accuracy_percent.unwrap() - 70.0).abs() < f64::EPSILON); + assert_invariants(&summary); +} + +#[test] +fn learning_data_json_round_trip_preserves_event_types_and_state() { + let settings = SrsSettings::default(); + let key = item_key(0); + let mut data = LearningData::default(); + data.apply_attempt( + attempt( + &key, + "serde-correct", + TrainingEventType::CorrectIndependent, + BASE, + ), + &settings, + ) + .unwrap(); + data.apply_attempt( + attempt( + &key, + "serde-replay", + TrainingEventType::ReplayAfterError, + BASE + 1, + ), + &settings, + ) + .unwrap(); + + let json = serde_json::to_string(&data).unwrap(); + assert!(json.contains("CORRECT_INDEPENDENT")); + assert!(json.contains("REPLAY_AFTER_ERROR")); + let restored: LearningData = serde_json::from_str(&json).unwrap(); + assert_eq!(restored, data); +} + +#[test] +fn mixed_event_sequence_preserves_aggregate_invariants() { + let events = [ + TrainingEventType::CorrectIndependent, + TrainingEventType::IncorrectIndependent, + TrainingEventType::Previewed, + TrainingEventType::ReplayAfterError, + TrainingEventType::AutoContext, + TrainingEventType::IllegalMove, + ]; + let keys: Vec<_> = (0..7).map(item_key).collect(); + let settings = SrsSettings::default(); + let mut data = LearningData::default(); + for key in &keys { + data.ensure_item(key.clone()); + } + + for step in 0..150_i64 { + let key = &keys[(step as usize * 3 + step as usize / 7) % keys.len()]; + let happened_at = BASE + step * 45; + let event = attempt( + key, + format!("property-{step}"), + events[step as usize % events.len()], + happened_at, + ); + assert_eq!( + data.apply_attempt(event.clone(), &settings), + Ok(AttemptApplication::Applied) + ); + if step % 9 == 0 { + assert_eq!( + data.apply_attempt(event, &settings), + Ok(AttemptApplication::Duplicate) + ); + } + + let as_of = happened_at + (step % 4) * 8 * DAY; + let global = aggregate(data.items.iter().chain(data.items.iter()), as_of, &settings); + assert_invariants(&global); + let left = aggregate(data.items.iter().take(4), as_of, &settings); + let right = aggregate(data.items.iter().skip(3), as_of, &settings); + assert!(global.total <= left.total + right.total); + } +} + +fn assert_invariants(summary: &LearningAggregate) { + assert_eq!( + summary.total, + summary.unseen + summary.learning + summary.learnt + ); + assert!(summary.uncertain <= summary.learnt); + assert!(summary.learnt_confident <= summary.learnt); + assert_eq!(summary.learnt_confident, summary.learnt - summary.uncertain); + assert!(summary.due <= summary.learning + summary.learnt); + assert_eq!( + summary.accuracy_attempts, + summary.accuracy_correct + summary.accuracy_wrong + ); + for percentage in [ + summary.coverage_percent, + summary.learnt_percent, + summary.confident_percent, + summary.learning_percent, + summary.unseen_percent, + summary.uncertain_of_learnt_percent, + summary.due_of_introduced_percent, + summary.accuracy_percent, + ] + .into_iter() + .flatten() + { + assert!(percentage.is_finite()); + assert!((0.0..=100.0).contains(&percentage)); + } + if let (Some(coverage), Some(learnt), Some(confident)) = ( + summary.coverage_percent, + summary.learnt_percent, + summary.confident_percent, + ) { + assert!(coverage >= learnt); + assert!(learnt >= confident); + } else { + assert_eq!(summary.total, 0); + } + if let Some(next) = summary.next_due_at { + assert!(summary.due < summary.total); + assert!(next > 0); + } +} diff --git a/crates/trainer/src/repertoire/advanced_tests.rs b/crates/trainer/src/repertoire/advanced_tests.rs new file mode 100644 index 0000000..cdc0c40 --- /dev/null +++ b/crates/trainer/src/repertoire/advanced_tests.rs @@ -0,0 +1,142 @@ +use chess_core::{Game, NodeId}; + +use super::*; + +fn repertoire(pgn: &str) -> Repertoire { + let mut library = Library::default(); + let id = library + .create("Scope", &chess_core::parse_str(pgn).game) + .unwrap(); + library.repertoire(&id).unwrap().clone() +} + +#[test] +fn simultaneous_writers_cannot_overwrite_the_same_revision() { + let path = std::env::temp_dir().join(format!("cp-trainer-race-{}.json", std::process::id())); + let _ = std::fs::remove_file(&path); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(8)); + let writers: Vec<_> = (0..8) + .map(|i| { + let path = path.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + let mut library = Library::default(); + library.create_empty(format!("Writer {i}")).unwrap(); + barrier.wait(); + LibraryStore::new(path).save(&mut library) + }) + }) + .collect(); + let results: Vec<_> = writers + .into_iter() + .map(|thread| thread.join().unwrap()) + .collect(); + assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 1); + assert_eq!( + results + .iter() + .filter(|r| matches!(r, Err(StoreError::Conflict { .. }))) + .count(), + 7 + ); + assert_eq!( + LibraryStore::new(&path).load().unwrap().repertoires.len(), + 1 + ); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn previous_both_move_keys_migrate_to_position_statistics_without_data_loss() { + let path = + std::env::temp_dir().join(format!("cp-trainer-migration-{}.json", std::process::id())); + let rep = repertoire("1. e4 (1. d4) *"); + let position_fen4 = fen4(Game::new().start().position()); + let entries = ["e2e4", "d2d4"].map(|uci| { + let mut entry = MoveStats::new(MoveKey { + repertoire_id: rep.id.clone(), + mode: TrainingMode::Both, + position_fen4: position_fen4.clone(), + expected_uci: uci.into(), + }); + entry.attempts = 2; + entry.correct = 1; + entry.wrong = 1; + entry.hints = 1; + entry + }); + let mut data = StatsData::default(); + data.move_stats = entries.into(); + std::fs::write(&path, serde_json::to_vec(&data).unwrap()).unwrap(); + let store = StatsStore::new(&path); + let mut migrated = store.load().unwrap(); + assert_eq!(migrated.move_stats.len(), 1); + let entry = &migrated.move_stats[0]; + assert!(entry.key.expected_uci.is_empty()); + assert_eq!( + (entry.attempts, entry.correct, entry.wrong, entry.hints), + (4, 2, 2, 2) + ); + store.save(&mut migrated).unwrap(); + assert_eq!(store.load().unwrap().move_stats, migrated.move_stats); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn null_subtree_grafts_under_the_exact_path_instead_of_an_earlier_transposition() { + let base = chess_core::parse_str("1. d4 (1. Nf3 d5 2. d4) d5 2. Nf3 *").game; + let source = chess_core::parse_str( + "1. Nf3 d5 2. d4 -- {teaching pass} 3. c4 $1 (3. e4 {side branch} $2) *", + ) + .game; + let original = source.canonical_tree(); + let mut library = Library::default(); + let id = library.create("Exact graft", &base).unwrap(); + let report = library.add_game(&id, &source).unwrap(); + assert_eq!(report.added_nodes, 3); + let merged = library.repertoire(&id).unwrap().game(); + let main_end = *merged.mainline().last().unwrap(); + assert!(merged.children(main_end).is_empty()); + let alternative = merged.children(NodeId::ROOT)[1]; + let d5 = merged.children(alternative)[0]; + let d4 = merged.children(d5)[0]; + let null = merged.children(d4)[0]; + assert!(merged.game_move(null).unwrap().is_null()); + assert_eq!( + merged.node(null).unwrap().comments_after(), + &["teaching pass"] + ); + let c4 = merged.children(null)[0]; + assert_eq!(merged.game_move(c4).unwrap().san, "c4"); + assert_eq!(merged.node(c4).unwrap().nags()[0].0, 1); + assert_eq!(merged.start().fen(), source.start().fen()); + // Match each complete source path, including every RAV under the null move. + // Compare position counters and annotations as well as moves: remapping the + // graft must not retain any IDs from the temporary planning document. + for source_id in source.attached_nodes() { + let mut target_id = NodeId::ROOT; + for step in source.path(source_id).into_iter().skip(1) { + let kind = source.game_move(step).unwrap().kind; + target_id = merged + .children(target_id) + .iter() + .copied() + .find(|id| merged.game_move(*id).is_some_and(|mv| mv.kind == kind)) + .expect("the complete source path survives the graft"); + } + let expected = source.node(source_id).unwrap(); + let actual = merged.node(target_id).unwrap(); + assert_eq!(actual.comments_before(), expected.comments_before()); + assert_eq!(actual.comments_after(), expected.comments_after()); + assert_eq!(actual.nags(), expected.nags()); + assert_eq!(actual.unparsed(), expected.unparsed()); + assert_eq!(merged.fen(target_id), source.fen(source_id)); + } + assert_eq!(source.canonical_tree(), original); + let canonical = merged.canonical_tree(); + assert_eq!(library.add_game(&id, &source).unwrap().added_nodes, 0); + assert_eq!( + library.repertoire(&id).unwrap().game().canonical_tree(), + canonical + ); +} diff --git a/crates/trainer/src/repertoire/aggregate.rs b/crates/trainer/src/repertoire/aggregate.rs new file mode 100644 index 0000000..1ef93fa --- /dev/null +++ b/crates/trainer/src/repertoire/aggregate.rs @@ -0,0 +1,455 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::learning::LearningItem; +use super::srs::SrsSettings; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum RepertoireStatus { + NotStarted, + InProgress, + AllLearnt, + ConfirmedCurrent, + #[default] + Empty, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct LearningAggregate { + pub total: usize, + pub unseen: usize, + pub learning: usize, + pub learnt: usize, + pub uncertain: usize, + pub learnt_confident: usize, + pub due: usize, + pub next_due_at: Option, + pub coverage_percent: Option, + pub learnt_percent: Option, + pub confident_percent: Option, + pub learning_percent: Option, + pub unseen_percent: Option, + pub uncertain_of_learnt_percent: Option, + pub due_of_introduced_percent: Option, + pub accuracy_correct: u64, + pub accuracy_wrong: u64, + pub accuracy_attempts: u64, + pub accuracy_percent: Option, + pub repertoire_status: RepertoireStatus, +} + +/// Uncertain starts strictly after the grace boundary, never at the boundary itself. +pub fn is_uncertain(item: &LearningItem, now: i64, settings: &SrsSettings) -> bool { + if !item.is_learnt() { + return false; + } + let Some(next_review_at) = item.next_review_at else { + return false; + }; + let interval_grace = item.previous_interval_seconds.unwrap_or(0).max(0) + / i64::from(settings.uncertain_interval_divisor.max(1)); + let grace = settings + .uncertain_min_grace_seconds + .max(0) + .max(interval_grace); + now > next_review_at.saturating_add(grace) +} + +/// Counts each full LearningItemKey once, even if several scopes supplied the same item. +pub fn aggregate<'a>( + items: impl IntoIterator, + now: i64, + settings: &SrsSettings, +) -> LearningAggregate { + let mut unique = BTreeMap::new(); + for item in items { + unique.entry(&item.key).or_insert(item); + } + + let mut summary = LearningAggregate::default(); + for item in unique.into_values() { + summary.total = summary.total.saturating_add(1); + if item.is_unseen() { + summary.unseen = summary.unseen.saturating_add(1); + } else if item.is_learnt() { + summary.learnt = summary.learnt.saturating_add(1); + } else { + summary.learning = summary.learning.saturating_add(1); + } + if is_uncertain(item, now, settings) { + summary.uncertain = summary.uncertain.saturating_add(1); + } + if item.is_due(now) { + summary.due = summary.due.saturating_add(1); + } + if item.introduced + && let Some(next) = item.next_review_at + && next > now + { + summary.next_due_at = Some(summary.next_due_at.map_or(next, |old| old.min(next))); + } + summary.accuracy_correct = summary.accuracy_correct.saturating_add(item.correct_count); + summary.accuracy_wrong = summary.accuracy_wrong.saturating_add(item.wrong_count); + } + + if summary.due > 0 { + summary.next_due_at = None; + } + summary.learnt_confident = summary.learnt.saturating_sub(summary.uncertain); + summary.accuracy_attempts = summary + .accuracy_correct + .saturating_add(summary.accuracy_wrong); + if summary.total > 0 { + summary.coverage_percent = Some(percent(summary.total - summary.unseen, summary.total)); + summary.learnt_percent = Some(percent(summary.learnt, summary.total)); + summary.confident_percent = Some(percent(summary.learnt_confident, summary.total)); + summary.learning_percent = Some(percent(summary.learning, summary.total)); + summary.unseen_percent = Some(percent(summary.unseen, summary.total)); + } + if summary.learnt > 0 { + summary.uncertain_of_learnt_percent = Some(percent(summary.uncertain, summary.learnt)); + } + let introduced = summary.total.saturating_sub(summary.unseen); + if introduced > 0 { + summary.due_of_introduced_percent = Some(percent(summary.due, introduced)); + } + if summary.accuracy_attempts > 0 { + summary.accuracy_percent = + Some(100.0 * summary.accuracy_correct as f64 / summary.accuracy_attempts as f64); + } + summary.repertoire_status = if summary.total == 0 { + RepertoireStatus::Empty + } else if summary.unseen == summary.total { + RepertoireStatus::NotStarted + } else if summary.learnt == summary.total && summary.uncertain == 0 && summary.due == 0 { + RepertoireStatus::ConfirmedCurrent + } else if summary.learnt == summary.total { + RepertoireStatus::AllLearnt + } else { + RepertoireStatus::InProgress + }; + for violation in learning_invariant_violations(&summary) { + eprintln!( + "training: learning aggregate invariant violation: {violation}; summary={summary:?}" + ); + } + summary +} + +pub fn learning_invariant_violations(summary: &LearningAggregate) -> Vec<&'static str> { + let mut violations = Vec::new(); + let classified_total = summary + .unseen + .checked_add(summary.learning) + .and_then(|total| total.checked_add(summary.learnt)); + if classified_total != Some(summary.total) { + violations.push("total != unseen + learning + learnt"); + } + if summary.uncertain > summary.learnt { + violations.push("uncertain > learnt"); + } + if summary.learnt.checked_sub(summary.uncertain) != Some(summary.learnt_confident) { + violations.push("learnt_confident != learnt - uncertain"); + } + if summary.due > summary.learning.saturating_add(summary.learnt) { + violations.push("due > learning + learnt"); + } + if let (Some(coverage), Some(learnt)) = (summary.coverage_percent, summary.learnt_percent) + && is_valid_percentage(coverage) + && is_valid_percentage(learnt) + && coverage < learnt + { + violations.push("coverage_percent < learnt_percent"); + } + if let (Some(learnt), Some(confident)) = (summary.learnt_percent, summary.confident_percent) + && is_valid_percentage(learnt) + && is_valid_percentage(confident) + && learnt < confident + { + violations.push("learnt_percent < confident_percent"); + } + for (percentage, violation) in [ + ( + summary.coverage_percent, + "coverage_percent is not finite or is outside 0..=100", + ), + ( + summary.learnt_percent, + "learnt_percent is not finite or is outside 0..=100", + ), + ( + summary.confident_percent, + "confident_percent is not finite or is outside 0..=100", + ), + ( + summary.learning_percent, + "learning_percent is not finite or is outside 0..=100", + ), + ( + summary.unseen_percent, + "unseen_percent is not finite or is outside 0..=100", + ), + ( + summary.uncertain_of_learnt_percent, + "uncertain_of_learnt_percent is not finite or is outside 0..=100", + ), + ( + summary.due_of_introduced_percent, + "due_of_introduced_percent is not finite or is outside 0..=100", + ), + ( + summary.accuracy_percent, + "accuracy_percent is not finite or is outside 0..=100", + ), + ] { + if percentage.is_some_and(|value| !is_valid_percentage(value)) { + violations.push(violation); + } + } + violations +} + +pub fn global_total_invariant_violation( + global_total: usize, + repertoire_totals: impl IntoIterator, +) -> Option<&'static str> { + let mut repertoire_total = 0usize; + for total in repertoire_totals { + let Some(next) = repertoire_total.checked_add(total) else { + return Some("repertoire_totals sum overflow"); + }; + repertoire_total = next; + } + (global_total > repertoire_total).then_some("global_total > sum(repertoire_totals)") +} + +pub fn log_global_total_invariant( + global_total: usize, + repertoire_totals: impl IntoIterator, +) { + if let Some(violation) = global_total_invariant_violation(global_total, repertoire_totals) { + eprintln!( + "training: global total invariant violation: {violation}; global_total={global_total}" + ); + } +} + +fn is_valid_percentage(value: f64) -> bool { + value.is_finite() && (0.0..=100.0).contains(&value) +} + +fn percent(numerator: usize, denominator: usize) -> f64 { + 100.0 * numerator as f64 / denominator as f64 +} + +#[cfg(test)] +mod tests { + use super::super::learning::LearningItemKey; + use super::*; + + fn valid_summary() -> LearningAggregate { + LearningAggregate { + total: 10, + unseen: 2, + learning: 3, + learnt: 5, + uncertain: 2, + learnt_confident: 3, + due: 4, + next_due_at: None, + coverage_percent: Some(80.0), + learnt_percent: Some(50.0), + confident_percent: Some(30.0), + learning_percent: Some(30.0), + unseen_percent: Some(20.0), + uncertain_of_learnt_percent: Some(40.0), + due_of_introduced_percent: Some(50.0), + accuracy_correct: 7, + accuracy_wrong: 3, + accuracy_attempts: 10, + accuracy_percent: Some(70.0), + repertoire_status: RepertoireStatus::InProgress, + } + } + + fn assert_has_violation(summary: &LearningAggregate, expected: &'static str) { + let violations = learning_invariant_violations(summary); + assert!( + violations.contains(&expected), + "missing {expected:?} in {violations:?}" + ); + } + + #[test] + fn valid_mixed_summary_has_no_invariant_violations() { + let mut summary = valid_summary(); + assert!(learning_invariant_violations(&summary).is_empty()); + + summary.accuracy_percent = None; + assert!(learning_invariant_violations(&summary).is_empty()); + } + + #[test] + fn detects_count_invariant_violations() { + let mut summary = valid_summary(); + summary.total = 11; + assert_has_violation(&summary, "total != unseen + learning + learnt"); + + let mut summary = valid_summary(); + summary.uncertain = 6; + assert_has_violation(&summary, "uncertain > learnt"); + + let mut summary = valid_summary(); + summary.learnt_confident = 4; + assert_has_violation(&summary, "learnt_confident != learnt - uncertain"); + + let mut summary = valid_summary(); + summary.due = 9; + assert_has_violation(&summary, "due > learning + learnt"); + } + + #[test] + fn detects_percentage_ordering_violations() { + let mut summary = valid_summary(); + summary.coverage_percent = Some(40.0); + assert_has_violation(&summary, "coverage_percent < learnt_percent"); + + let mut summary = valid_summary(); + summary.learnt_percent = Some(20.0); + assert_has_violation(&summary, "learnt_percent < confident_percent"); + } + + #[test] + fn detects_invalid_values_in_every_percentage() { + type PercentageSetter = fn(&mut LearningAggregate, f64); + + let fields: [(&str, PercentageSetter); 8] = [ + ( + "coverage_percent is not finite or is outside 0..=100", + |summary, value| summary.coverage_percent = Some(value), + ), + ( + "learnt_percent is not finite or is outside 0..=100", + |summary, value| summary.learnt_percent = Some(value), + ), + ( + "confident_percent is not finite or is outside 0..=100", + |summary, value| summary.confident_percent = Some(value), + ), + ( + "learning_percent is not finite or is outside 0..=100", + |summary, value| summary.learning_percent = Some(value), + ), + ( + "unseen_percent is not finite or is outside 0..=100", + |summary, value| summary.unseen_percent = Some(value), + ), + ( + "uncertain_of_learnt_percent is not finite or is outside 0..=100", + |summary, value| summary.uncertain_of_learnt_percent = Some(value), + ), + ( + "due_of_introduced_percent is not finite or is outside 0..=100", + |summary, value| summary.due_of_introduced_percent = Some(value), + ), + ( + "accuracy_percent is not finite or is outside 0..=100", + |summary, value| summary.accuracy_percent = Some(value), + ), + ]; + for (violation, set) in fields { + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 100.01] { + let mut summary = valid_summary(); + set(&mut summary, value); + assert_has_violation(&summary, violation); + } + } + } + + #[test] + fn global_total_invariant_allows_deduplicated_union() { + assert_eq!(global_total_invariant_violation(3, [2, 2]), None); + } + + #[test] + fn global_total_invariant_detects_global_above_repertoire_sum() { + assert_eq!( + global_total_invariant_violation(5, [2, 2]), + Some("global_total > sum(repertoire_totals)") + ); + } + + #[test] + fn global_total_invariant_detects_repertoire_sum_overflow() { + assert_eq!( + global_total_invariant_violation(0, [usize::MAX, 1]), + Some("repertoire_totals sum overflow") + ); + } + + #[test] + fn global_total_invariant_handles_empty_repertoires() { + assert_eq!(global_total_invariant_violation(0, []), None); + assert_eq!( + global_total_invariant_violation(1, []), + Some("global_total > sum(repertoire_totals)") + ); + } + + #[test] + fn aggregate_output_is_unchanged() { + fn item( + index: usize, + introduced: bool, + correct_streak: u32, + next_review_at: Option, + ) -> LearningItem { + let mut item = + LearningItem::new(LearningItemKey::local(format!("fen-{index}"), "e2e4")); + item.introduced = introduced; + item.correct_streak = correct_streak; + item.next_review_at = next_review_at; + item.previous_interval_seconds = Some(0); + item + } + + let now = 1_000_000; + let grace = 7 * 24 * 60 * 60; + let mut items = [ + item(0, false, 0, None), + item(1, true, 1, Some(now + 100)), + item(2, true, 3, Some(now + 200)), + item(3, true, 3, Some(now - grace - 1)), + ]; + items[1].correct_count = 7; + items[1].wrong_count = 3; + + let summary = aggregate(items.iter(), now, &SrsSettings::default()); + let expected = LearningAggregate { + total: 4, + unseen: 1, + learning: 1, + learnt: 2, + uncertain: 1, + learnt_confident: 1, + due: 1, + next_due_at: None, + coverage_percent: Some(75.0), + learnt_percent: Some(50.0), + confident_percent: Some(25.0), + learning_percent: Some(25.0), + unseen_percent: Some(25.0), + uncertain_of_learnt_percent: Some(50.0), + due_of_introduced_percent: Some(100.0 / 3.0), + accuracy_correct: 7, + accuracy_wrong: 3, + accuracy_attempts: 10, + accuracy_percent: Some(70.0), + repertoire_status: RepertoireStatus::InProgress, + }; + assert_eq!(summary, expected); + assert!(learning_invariant_violations(&summary).is_empty()); + } +} diff --git a/crates/trainer/src/repertoire/analytics_tests.rs b/crates/trainer/src/repertoire/analytics_tests.rs new file mode 100644 index 0000000..b38a0e2 --- /dev/null +++ b/crates/trainer/src/repertoire/analytics_tests.rs @@ -0,0 +1,524 @@ +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::*; + +const DAY: i64 = 24 * 60 * 60; +const BASE: i64 = 1_800_000_000; + +static NEXT_DIR: AtomicU64 = AtomicU64::new(1); + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let sequence = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "cp-learning-analytics-{}-{}-{name}", + std::process::id(), + sequence + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn join(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn item_key(index: usize) -> LearningItemKey { + LearningItemKey::local(format!("position-{index} w - -"), "e2e4") +} + +fn attempt( + key: &LearningItemKey, + id: impl Into, + event_type: TrainingEventType, + happened_at: i64, + response_time_ms: u64, +) -> TrainingAttempt { + let actual_uci = match event_type { + TrainingEventType::IncorrectIndependent => "d2d4", + _ => "e2e4", + }; + TrainingAttempt { + user_id: key.user_id.clone(), + position_fen4: key.position_fen4.clone(), + client_attempt_id: id.into(), + session_id: "analytics".into(), + event_type, + expected_uci: key.expected_uci.clone(), + actual_uci: Some(actual_uci.into()), + response_time_ms: Some(response_time_ms), + happened_at, + } +} + +fn record(item: &mut LearningItem, id: &str, event_type: TrainingEventType, happened_at: i64) { + apply_attempt( + item, + &attempt(&item.key, id, event_type, happened_at, 250), + &SrsSettings::default(), + ) + .unwrap(); +} + +fn learnt_item(index: usize, reviewed_at: i64, next_review_at: i64) -> LearningItem { + let mut item = LearningItem::new(item_key(index)); + item.introduced = true; + item.correct_streak = 3; + item.correct_count = 3; + item.last_review_at = Some(reviewed_at); + item.last_correct_at = Some(reviewed_at); + item.last_independent_at = Some(reviewed_at); + item.last_independent_correct_at = Some(reviewed_at); + item.last_independent_result = Some(IndependentResult::Correct); + item.next_review_at = Some(next_review_at); + item.previous_interval_seconds = Some(DAY); + item +} + +fn introduced_item(index: usize, next_review_at: Option) -> LearningItem { + let mut item = LearningItem::new(item_key(index)); + item.introduced = true; + item.next_review_at = next_review_at; + item +} + +#[test] +fn resistant_enters_on_recent_results_and_exits_after_three_independent_correct() { + let mut item = LearningItem::new(item_key(0)); + for (index, event_type) in [ + TrainingEventType::IncorrectIndependent, + TrainingEventType::CorrectIndependent, + TrainingEventType::IncorrectIndependent, + TrainingEventType::CorrectIndependent, + TrainingEventType::IncorrectIndependent, + ] + .into_iter() + .enumerate() + { + record( + &mut item, + &format!("enter-{index}"), + event_type, + BASE + index as i64, + ); + } + + assert!(is_resistant(&item)); + assert!(item.is_learning()); + let summary = aggregate( + std::slice::from_ref(&item), + BASE + 5, + &SrsSettings::default(), + ); + assert_eq!((summary.total, summary.learning, summary.learnt), (1, 1, 0)); + + for index in 0..2 { + record( + &mut item, + &format!("exit-{index}"), + TrainingEventType::CorrectIndependent, + BASE + 5 + index, + ); + assert!(item.is_resistant()); + } + record( + &mut item, + "exit-2", + TrainingEventType::CorrectIndependent, + BASE + 7, + ); + assert!(!item.is_resistant()); + assert!(item.is_learnt()); + record( + &mut item, + "exit-3", + TrainingEventType::CorrectIndependent, + BASE + 8, + ); + assert!(!item.is_resistant()); + + for index in 0..6 { + record( + &mut item, + &format!("recent-{index}"), + TrainingEventType::CorrectIndependent, + BASE + 9 + index, + ); + } + assert_eq!(item.recent_independent_outcomes.len(), 10); + assert!( + item.recent_independent_outcomes + .iter() + .all(|outcome| outcome.result == IndependentResult::Correct) + ); + assert!(!item.is_resistant()); + assert_eq!(item.wrong_count, 3); +} + +#[test] +fn non_independent_events_preserve_independent_timestamps_history_and_median() { + let mut item = LearningItem::new(item_key(0)); + for (index, response_time_ms) in [400, 100, 300, 200].into_iter().enumerate() { + let event_type = if index == 0 { + TrainingEventType::IncorrectIndependent + } else { + TrainingEventType::CorrectIndependent + }; + let training_attempt = attempt( + &item.key, + format!("independent-{index}"), + event_type, + BASE + index as i64, + response_time_ms, + ); + apply_attempt(&mut item, &training_attempt, &SrsSettings::default()).unwrap(); + } + assert_eq!(item.response_time_median_ms(), Some(250.0)); + assert_eq!(item.last_independent_at, Some(BASE + 3)); + assert_eq!(item.last_independent_correct_at, Some(BASE + 3)); + assert_eq!(item.last_independent_wrong_at, Some(BASE)); + assert_eq!( + item.last_independent_result, + Some(IndependentResult::Correct) + ); + + for (index, event_type) in [ + TrainingEventType::Previewed, + TrainingEventType::ReplayAfterError, + TrainingEventType::AutoContext, + TrainingEventType::IllegalMove, + ] + .into_iter() + .enumerate() + { + let before_outcomes = item.recent_independent_outcomes.clone(); + let before_responses = item.independent_response_times_ms.clone(); + let training_attempt = attempt( + &item.key, + format!("context-{index}"), + event_type, + BASE + 10 + index as i64, + 99_999, + ); + apply_attempt(&mut item, &training_attempt, &SrsSettings::default()).unwrap(); + assert_eq!(item.last_independent_at, Some(BASE + 3)); + assert_eq!(item.last_independent_correct_at, Some(BASE + 3)); + assert_eq!(item.last_independent_wrong_at, Some(BASE)); + assert_eq!( + item.last_independent_result, + Some(IndependentResult::Correct) + ); + assert_eq!(item.recent_independent_outcomes, before_outcomes); + assert_eq!(item.independent_response_times_ms, before_responses); + assert_eq!(item.response_time_median_ms(), Some(250.0)); + } +} + +#[test] +fn at_09_uncertain_is_subset_of_learnt_not_an_extra_total() { + let item = learnt_item(0, BASE - DAY, BASE); + let now = BASE + 7 * DAY + 1; + assert!(is_uncertain(&item, now, &SrsSettings::default())); + let summary = aggregate(std::slice::from_ref(&item), now, &SrsSettings::default()); + assert_eq!(summary.total, 1); + assert_eq!(summary.learnt, 1); + assert_eq!(summary.uncertain, 1); + assert_eq!( + summary.total, + summary.unseen + summary.learning + summary.learnt + ); + let details = move_learning_analytics(&item, now, &SrsSettings::default()); + assert_eq!(details.status, MoveLearningStatus::Uncertain); + assert_eq!(details.uncertain_grace_seconds, Some(7 * DAY)); +} + +#[test] +fn at_10_independent_correct_clears_uncertain_and_stays_learnt() { + let mut item = learnt_item(0, BASE - DAY, BASE); + let now = BASE + 7 * DAY + 1; + apply_independent_correct(&mut item, now, &SrsSettings::default()); + assert!(item.is_learnt()); + assert!(!is_uncertain(&item, now, &SrsSettings::default())); + assert_eq!(item.last_correct_at, Some(now)); + assert_eq!(item.last_independent_correct_at, Some(now)); + assert!(item.next_review_at.is_some_and(|next| next > now)); +} + +#[test] +fn at_11_independent_wrong_clears_uncertain_by_returning_to_learning() { + let mut item = learnt_item(0, BASE - DAY, BASE); + let previous_independent_correct = item.last_independent_correct_at; + let now = BASE + 7 * DAY + 1; + apply_independent_wrong(&mut item, "d2d4", now, &SrsSettings::default()); + assert!(item.is_learning()); + assert!(!is_uncertain(&item, now, &SrsSettings::default())); + assert_eq!(item.correct_streak, 0); + assert_eq!(item.last_correct_at, None); + assert_eq!( + item.last_independent_correct_at, + previous_independent_correct + ); + assert_eq!(item.last_independent_wrong_at, Some(now)); + assert_eq!(item.last_independent_result, Some(IndependentResult::Wrong)); + assert_eq!(item.next_review_at, Some(now + MISTAKE_DELAY_SECONDS)); +} + +#[test] +fn at_26_scheduled_boundaries_are_disjoint_and_cover_every_introduced_item() { + let offset = LocalDatePolicy::fixed(2 * 60 * 60); + let end_today = offset.end_of_local_day_exclusive(BASE); + assert!(BASE + 1 < end_today); + let end_week = BASE + SCHEDULED_WEEK_SECONDS; + let end_month = BASE + SCHEDULED_MONTH_SECONDS; + let end_year = BASE + SCHEDULED_YEAR_SECONDS; + let mut items = vec![ + introduced_item(0, Some(BASE)), + introduced_item(1, Some(BASE + 1)), + introduced_item(2, Some(end_today)), + introduced_item(3, Some(end_week - 1)), + introduced_item(4, Some(end_week)), + introduced_item(5, Some(end_month)), + introduced_item(6, Some(end_year)), + introduced_item(7, None), + LearningItem::new(item_key(8)), + ]; + items[8].next_review_at = Some(BASE); + + let buckets = scheduled_buckets(items.iter(), BASE, offset); + assert_eq!(buckets.overdue, 2); + assert_eq!(buckets.today, 1); + assert_eq!(buckets.week, 2); + assert_eq!(buckets.month, 1); + assert_eq!(buckets.year, 1); + assert_eq!(buckets.later, 1); + assert_eq!(buckets.introduced(), 8); +} + +#[test] +fn local_date_policy_makes_offset_and_midnight_explicit() { + assert_eq!(LocalDatePolicy::UTC.date(0), "1970-01-01"); + let east = LocalDatePolicy::fixed(3_600); + assert_eq!(east.date(0), "1970-01-01"); + assert_eq!(east.end_of_local_day_exclusive(0), 23 * 3_600); + let west = LocalDatePolicy::fixed(-3_600); + assert_eq!(west.date(0), "1969-12-31"); + assert_eq!(west.end_of_local_day_exclusive(0), 3_600); +} + +#[test] +fn sequences_include_zero_and_attempt_histogram_sums_match_total() { + let unseen = LearningItem::new(item_key(0)); + let mut learning = introduced_item(1, Some(BASE)); + learning.correct_streak = 2; + learning.correct_count = 2; + let mut wrong = introduced_item(2, Some(BASE)); + wrong.wrong_streak = 3; + wrong.wrong_count = 3; + let mut learnt = learnt_item(3, BASE - DAY, BASE); + learnt.correct_streak = 5; + learnt.correct_count = 5; + learnt.wrong_count = 2; + let items = [unseen, learning, wrong, learnt]; + + let histograms = sequence_histograms(items.iter()); + assert_eq!(histograms.correct_streak.get(&0), Some(&2)); + assert_eq!(histograms.correct_streak.get(&2), Some(&1)); + assert_eq!(histograms.correct_streak.get(&5), Some(&1)); + assert_eq!(histograms.wrong_streak.get(&0), Some(&3)); + assert_eq!(histograms.wrong_streak.get(&3), Some(&1)); + assert_eq!(histograms.attempts.get(&0), Some(&1)); + assert_eq!(histograms.attempts.get(&2), Some(&1)); + assert_eq!(histograms.attempts.get(&3), Some(&1)); + assert_eq!(histograms.attempts.get(&7), Some(&1)); + assert_eq!( + histograms.correct_streak.values().sum::(), + items.len() + ); + assert_eq!(histograms.wrong_streak.values().sum::(), items.len()); + assert_eq!(histograms.attempts.values().sum::(), items.len()); +} + +#[test] +fn per_move_analytics_include_independent_details_and_scope_membership() { + let mut library = Library::default(); + let first = library + .create("First", &chess_core::parse_str("1. e4 e5 2. Nf3 *").game) + .unwrap(); + let second = library + .create("Second", &chess_core::parse_str("1. e4 c5 *").game) + .unwrap(); + let first_scope = StatsScope::for_repertoire(first.clone(), LearningSide::White, BASE); + let key = active_learning_memberships(&library, &first_scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == "e2e4") + .unwrap() + .key; + let mut learning = LearningData::default(); + for (index, response_time_ms) in [400, 100, 300, 200].into_iter().enumerate() { + let event_type = if index == 0 { + TrainingEventType::IncorrectIndependent + } else { + TrainingEventType::CorrectIndependent + }; + learning + .apply_attempt( + attempt( + &key, + format!("details-{index}"), + event_type, + BASE - 3 + index as i64, + response_time_ms, + ), + &SrsSettings::default(), + ) + .unwrap(); + } + let scope = StatsScope::new([first, second], LearningSide::White, BASE + 1); + let details = + scoped_move_learning_analytics(&library, &learning, &scope, &SrsSettings::default()) + .unwrap(); + let e4 = details + .iter() + .find(|details| details.key.expected_uci == "e2e4") + .unwrap(); + assert_eq!(e4.status, MoveLearningStatus::LearntFresh); + assert_eq!(e4.memberships.len(), 2); + assert_eq!(e4.accuracy_percent, Some(75.0)); + assert_eq!(e4.independent_attempts, 4); + assert_eq!(e4.response_time_median_ms, Some(250.0)); + assert_eq!(e4.last_review_at, Some(BASE)); + assert_eq!(e4.last_independent_at, Some(BASE)); + assert_eq!(e4.last_independent_wrong_at, Some(BASE - 3)); + assert_eq!(e4.last_independent_result, Some(IndependentResult::Correct)); + assert_eq!(e4.wrong_move_histogram["d2d4"].count, 1); +} + +#[test] +fn at_27_daily_snapshots_capture_time_dependent_uncertain_without_rewriting_history() { + let dir = TestDir::new("snapshots"); + let path = dir.join("learning.json"); + let store = LearningStore::new(&path); + let mut library = Library::default(); + let repertoire = library + .create("Repertoire", &chess_core::parse_str("1. e4 *").game) + .unwrap(); + let first_scope = StatsScope::for_repertoire(repertoire, LearningSide::White, BASE); + let key = active_learning_keys(&library, &first_scope) + .unwrap() + .into_iter() + .next() + .unwrap(); + let mut learning = LearningData::default(); + let mut learnt = learnt_item(0, BASE - DAY, BASE); + learnt.key = key.clone(); + *learning.ensure_item(key) = learnt; + std::fs::write( + &path, + serde_json::to_vec_pretty(&LearningStoreData { + learning, + ..LearningStoreData::default() + }) + .unwrap(), + ) + .unwrap(); + + let first = store + .record_snapshot( + &library, + &first_scope, + &SrsSettings::default(), + LocalDatePolicy::UTC, + ) + .unwrap(); + assert!(first.recorded); + assert_eq!(first.revision, 1); + assert_eq!((first.snapshot.learnt, first.snapshot.uncertain), (1, 0)); + + let mut raw: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + raw["snapshots"][0]["future_snapshot_extension"] = serde_json::json!({"keep": true}); + raw["snapshots"][0]["scope"]["future_scope_extension"] = serde_json::json!({"keep": true}); + std::fs::write(&path, serde_json::to_vec_pretty(&raw).unwrap()).unwrap(); + + let mut second_scope = first_scope.clone(); + second_scope.as_of = BASE + 7 * DAY + 1; + let second = store + .record_snapshot( + &library, + &second_scope, + &SrsSettings::default(), + LocalDatePolicy::UTC, + ) + .unwrap(); + assert!(second.recorded); + assert_eq!(second.revision, 2); + assert_eq!((second.snapshot.learnt, second.snapshot.uncertain), (1, 1)); + assert_ne!(first.snapshot.date, second.snapshot.date); + + let bytes_after_second = std::fs::read(&path).unwrap(); + second_scope.as_of += 60; + let repeated = store + .record_snapshot( + &library, + &second_scope, + &SrsSettings::default(), + LocalDatePolicy::UTC, + ) + .unwrap(); + assert!(!repeated.recorded); + assert_eq!(repeated.revision, 2); + assert_eq!(repeated.snapshot, second.snapshot); + assert_eq!(std::fs::read(&path).unwrap(), bytes_after_second); + + let loaded = store.load().unwrap(); + assert_eq!(loaded.snapshots.len(), 2); + assert_eq!(loaded.snapshots[0], first.snapshot); + assert_eq!(loaded.snapshots[1], second.snapshot); + let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!( + saved["snapshots"][0]["future_snapshot_extension"], + serde_json::json!({"keep": true}) + ); + assert_eq!( + saved["snapshots"][0]["scope"]["future_scope_extension"], + serde_json::json!({"keep": true}) + ); +} + +#[test] +fn old_item_and_store_json_default_new_analytics_fields() { + let mut item_value = serde_json::to_value(LearningItem::new(item_key(0))).unwrap(); + let item_object = item_value.as_object_mut().unwrap(); + for field in [ + "last_independent_at", + "last_independent_correct_at", + "last_independent_wrong_at", + "last_independent_result", + "recent_independent_outcomes", + "resistant", + ] { + item_object.remove(field); + } + let item: LearningItem = serde_json::from_value(item_value).unwrap(); + assert_eq!(item.last_independent_at, None); + assert_eq!(item.last_independent_result, None); + assert!(item.recent_independent_outcomes.is_empty()); + assert!(!item.resistant); + + let mut store_value = serde_json::to_value(LearningStoreData::default()).unwrap(); + store_value.as_object_mut().unwrap().remove("snapshots"); + let store: LearningStoreData = serde_json::from_value(store_value).unwrap(); + assert!(store.snapshots.is_empty()); +} diff --git a/crates/trainer/src/repertoire/branch_analytics.rs b/crates/trainer/src/repertoire/branch_analytics.rs new file mode 100644 index 0000000..27e88c7 --- /dev/null +++ b/crates/trainer/src/repertoire/branch_analytics.rs @@ -0,0 +1,71 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::aggregate::{LearningAggregate, aggregate}; +use super::learning::{LearningData, LearningItem, LearningItemKey}; +use super::learning_graph::{ + LearningGraphError, StatsScope, aggregate_scope, all_path_learning_memberships, +}; +use super::model::{Library, RepertoireId}; +use super::srs::SrsSettings; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct BranchLearningAnalytics { + pub repertoire_id: RepertoireId, + pub branch_root: Vec, + pub summary: LearningAggregate, + pub last_independent_at: Option, +} + +pub fn branch_learning_analytics( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + settings: &SrsSettings, +) -> Result, LearningGraphError> { + let memberships = all_path_learning_memberships(library, scope)?; + let scoped = aggregate_scope(library, learning, scope, settings)?; + let items_by_key: BTreeMap<&LearningItemKey, &LearningItem> = + scoped.items.iter().map(|item| (&item.key, item)).collect(); + let first_prefix_len = scope + .branch_root + .as_ref() + .map_or(1, |root| root.len().max(1)); + let mut branches: BTreeMap< + (RepertoireId, Vec), + BTreeMap<&LearningItemKey, &LearningItem>, + > = BTreeMap::new(); + + for membership in memberships { + let Some((key, item)) = items_by_key.get_key_value(&membership.key) else { + continue; + }; + for prefix_len in first_prefix_len..=membership.path.len() { + branches + .entry(( + membership.repertoire_id.clone(), + membership.path[..prefix_len].to_vec(), + )) + .or_default() + .insert(*key, *item); + } + } + + Ok(branches + .into_iter() + .map(|((repertoire_id, branch_root), items)| { + let last_independent_at = items + .values() + .filter_map(|item| item.last_independent_at) + .max(); + let summary = aggregate(items.values().copied(), scope.as_of, settings); + BranchLearningAnalytics { + repertoire_id, + branch_root, + summary, + last_independent_at, + } + }) + .collect()) +} diff --git a/crates/trainer/src/repertoire/branch_tests.rs b/crates/trainer/src/repertoire/branch_tests.rs new file mode 100644 index 0000000..10885da --- /dev/null +++ b/crates/trainer/src/repertoire/branch_tests.rs @@ -0,0 +1,516 @@ +use std::collections::BTreeSet; + +use super::*; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 24 * 60 * 60; + +fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { + library + .create(name, &chess_core::parse_str(pgn).game) + .unwrap() +} + +fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { + let mut library = Library::default(); + let id = add_repertoire(&mut library, "One", pgn); + (library, id) +} + +fn scope(id: RepertoireId) -> StatsScope { + StatsScope::for_repertoire(id, LearningSide::White, NOW) +} + +fn strings(moves: &[&str]) -> Vec { + moves.iter().map(|mv| (*mv).to_owned()).collect() +} + +fn key_at_path(repertoire: &Repertoire, path: &[String], expected_uci: &str) -> LearningItemKey { + let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); + let parent = tree.node_at_path(path).unwrap(); + LearningItemKey::local(tree.position_key(parent).unwrap(), expected_uci) +} + +fn branch<'a>( + rows: &'a [BranchLearningAnalytics], + repertoire_id: &RepertoireId, + path: &[&str], +) -> Option<&'a BranchLearningAnalytics> { + rows.iter().find(|row| { + &row.repertoire_id == repertoire_id + && row + .branch_root + .iter() + .map(String::as_str) + .eq(path.iter().copied()) + }) +} + +fn learnt(item: &mut LearningItem, next_review_at: i64) { + item.introduced = true; + item.correct_streak = 3; + item.correct_count = 3; + item.last_review_at = Some(NOW - DAY); + item.last_correct_at = Some(NOW - DAY); + item.last_independent_at = Some(NOW - DAY); + item.next_review_at = Some(next_review_at); + item.previous_interval_seconds = Some(DAY); +} + +fn transposition_pgn() -> &'static str { + "1. e4 d5 (1... Nf6 2. d4 d5 3. c4) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 e6 6. g3 *" +} + +fn branching_pgn() -> &'static str { + "1. e4 e5 (1... c5 2. Nf3) 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O *" +} + +fn attempt( + key: &LearningItemKey, + id: &str, + event_type: TrainingEventType, + happened_at: i64, +) -> TrainingAttempt { + TrainingAttempt { + user_id: key.user_id.clone(), + position_fen4: key.position_fen4.clone(), + client_attempt_id: id.into(), + session_id: "branch-analytics".into(), + event_type, + expected_uci: key.expected_uci.clone(), + actual_uci: Some(if event_type == TrainingEventType::IncorrectIndependent { + "d2d4".into() + } else { + key.expected_uci.clone() + }), + response_time_ms: Some(250), + happened_at, + } +} + +#[test] +fn at_30_transposition_is_unique_per_branch_and_in_global_scope() { + let mut library = Library::default(); + let first = add_repertoire(&mut library, "First", transposition_pgn()); + let second = add_repertoire(&mut library, "Second", transposition_pgn()); + let shared = key_at_path( + library.repertoire(&first).unwrap(), + &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), + "c2c4", + ); + let mut learning = LearningData::default(); + learnt(learning.ensure_item(shared), NOW + DAY); + + let selected = scope(first.clone()); + let rows = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + let first_move = branch(&rows, &first, &["e2e4"]).unwrap(); + let main_branch = branch(&rows, &first, &["e2e4", "d7d5"]).unwrap(); + let transposing_branch = branch(&rows, &first, &["e2e4", "g8f6"]).unwrap(); + assert_eq!(first_move.summary.total, 7); + assert_eq!(first_move.summary.learnt, 1); + assert_eq!(first_move.summary.accuracy_correct, 3); + assert_eq!(first_move.summary.accuracy_attempts, 3); + assert_eq!(main_branch.summary.total, 5); + assert_eq!(main_branch.summary.learnt, 1); + assert_eq!(main_branch.summary.accuracy_correct, 3); + assert_eq!(transposing_branch.summary.total, 2); + assert_eq!(transposing_branch.summary.learnt, 1); + assert_eq!(transposing_branch.summary.accuracy_correct, 3); + assert_eq!(transposing_branch.summary.accuracy_attempts, 3); + assert_eq!( + first_move.summary.total + 1, + 1 + main_branch.summary.total + transposing_branch.summary.total + ); + assert!(rows.iter().all(|row| !row.branch_root.is_empty())); + + let global_scope = StatsScope::new([first.clone(), second.clone()], LearningSide::White, NOW); + let global_rows = + branch_learning_analytics(&library, &learning, &global_scope, &SrsSettings::default()) + .unwrap(); + let global_first_moves: Vec<_> = global_rows + .iter() + .filter(|row| row.branch_root == strings(&["e2e4"])) + .collect(); + assert_eq!(global_first_moves.len(), 2); + assert_eq!( + global_first_moves + .iter() + .map(|row| row.repertoire_id.clone()) + .collect::>(), + BTreeSet::from([first, second]) + ); + assert!( + global_first_moves + .iter() + .all(|row| row.summary.total == 7 && row.summary.accuracy_correct == 3) + ); + let global = + aggregate_scope(&library, &learning, &global_scope, &SrsSettings::default()).unwrap(); + assert_eq!(global.summary.total, 7); + assert_eq!(global.summary.learnt, 1); + assert_eq!(global.summary.accuracy_correct, 3); +} + +#[test] +fn branch_summary_uses_core_statuses_due_and_independent_accuracy() { + let (library, id) = single_repertoire(branching_pgn()); + let repertoire = library.repertoire(&id).unwrap(); + let nf3 = key_at_path(repertoire, &strings(&["e2e4", "e7e5"]), "g1f3"); + let bb5 = key_at_path( + repertoire, + &strings(&["e2e4", "e7e5", "g1f3", "b8c6"]), + "f1b5", + ); + let ba4 = key_at_path( + repertoire, + &strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6"]), + "b5a4", + ); + let castle = key_at_path( + repertoire, + &strings(&[ + "e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4", "g8f6", + ]), + "e1g1", + ); + let mut learning = LearningData::default(); + + let item = learning.ensure_item(nf3); + item.introduced = true; + item.correct_streak = 1; + item.correct_count = 1; + item.next_review_at = Some(NOW + DAY); + item.last_independent_at = Some(NOW - 40); + + let item = learning.ensure_item(bb5); + learnt(item, NOW + DAY); + item.last_independent_at = Some(NOW - 20); + + let item = learning.ensure_item(ba4); + item.introduced = true; + item.correct_streak = 3; + item.correct_count = 2; + item.wrong_count = 1; + item.next_review_at = Some(NOW - 8 * DAY); + item.previous_interval_seconds = Some(DAY); + item.last_independent_at = Some(NOW - 10); + + let item = learning.ensure_item(castle); + item.introduced = true; + item.wrong_count = 2; + item.next_review_at = Some(NOW - 1); + item.last_independent_at = Some(NOW - 30); + + let rows = branch_learning_analytics( + &library, + &learning, + &scope(id.clone()), + &SrsSettings::default(), + ) + .unwrap(); + let summary = &branch(&rows, &id, &["e2e4"]).unwrap().summary; + assert_eq!(summary.total, 6); + assert_eq!(summary.unseen, 2); + assert_eq!(summary.learning, 2); + assert_eq!(summary.learnt, 2); + assert_eq!(summary.uncertain, 1); + assert_eq!(summary.learnt_confident, 1); + assert_eq!(summary.due, 2); + assert_eq!(summary.accuracy_correct, 6); + assert_eq!(summary.accuracy_wrong, 3); + assert_eq!(summary.accuracy_attempts, 9); + assert_eq!(summary.accuracy_percent, Some(100.0 * 6.0 / 9.0)); + assert_eq!( + branch(&rows, &id, &["e2e4"]).unwrap().last_independent_at, + Some(NOW - 10) + ); + + let unseen = branch(&rows, &id, &["e2e4", "c7c5"]).unwrap(); + assert_eq!(unseen.summary.total, 1); + assert_eq!(unseen.summary.unseen, 1); + assert_eq!(unseen.summary.accuracy_attempts, 0); + assert_eq!(unseen.summary.accuracy_percent, None); + assert_eq!(unseen.last_independent_at, None); +} + +#[test] +fn branch_last_independent_ignores_preview_and_auto_context() { + let (library, id) = single_repertoire(branching_pgn()); + let repertoire = library.repertoire(&id).unwrap(); + let main = key_at_path(repertoire, &strings(&["e2e4", "e7e5"]), "g1f3"); + let sideline = key_at_path(repertoire, &strings(&["e2e4", "c7c5"]), "g1f3"); + let mut learning = LearningData::default(); + for (key, event_id, event_type, happened_at) in [ + ( + &main, + "main-independent", + TrainingEventType::CorrectIndependent, + NOW - 20, + ), + ( + &sideline, + "sideline-independent", + TrainingEventType::IncorrectIndependent, + NOW - 10, + ), + (&main, "main-preview", TrainingEventType::Previewed, NOW - 1), + ( + &sideline, + "sideline-context", + TrainingEventType::AutoContext, + NOW, + ), + ] { + learning + .apply_attempt( + attempt(key, event_id, event_type, happened_at), + &SrsSettings::default(), + ) + .unwrap(); + } + assert_eq!(learning.item(&main).unwrap().last_review_at, Some(NOW - 1)); + assert_eq!( + learning.item(&main).unwrap().last_independent_at, + Some(NOW - 20) + ); + + let rows = branch_learning_analytics( + &library, + &learning, + &scope(id.clone()), + &SrsSettings::default(), + ) + .unwrap(); + let all = branch(&rows, &id, &["e2e4"]).unwrap(); + assert_eq!(all.last_independent_at, Some(NOW - 10)); + assert_eq!(all.summary.accuracy_correct, 1); + assert_eq!(all.summary.accuracy_wrong, 1); + assert_eq!(all.summary.accuracy_attempts, 2); + assert_eq!(all.summary.accuracy_percent, Some(50.0)); + assert_eq!( + branch(&rows, &id, &["e2e4", "e7e5"]) + .unwrap() + .last_independent_at, + Some(NOW - 20) + ); + assert_eq!( + branch(&rows, &id, &["e2e4", "c7c5"]) + .unwrap() + .last_independent_at, + Some(NOW - 10) + ); +} + +#[test] +fn disabled_branch_disappears_and_reenable_restores_history() { + let (mut library, id) = single_repertoire(branching_pgn()); + let selected = scope(id.clone()); + let sideline = key_at_path( + library.repertoire(&id).unwrap(), + &strings(&["e2e4", "c7c5"]), + "g1f3", + ); + let mut learning = LearningData::default(); + learnt(learning.ensure_item(sideline.clone()), NOW + DAY); + let before = learning.item(&sideline).unwrap().clone(); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4", "c7c5"]), true) + .unwrap(); + let disabled = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert!(branch(&disabled, &id, &["e2e4", "c7c5"]).is_none()); + assert_eq!(branch(&disabled, &id, &["e2e4"]).unwrap().summary.total, 5); + assert_eq!(learning.item(&sideline), Some(&before)); + + let mut include_inactive = selected.clone(); + include_inactive.only_active = false; + let inactive = branch_learning_analytics( + &library, + &learning, + &include_inactive, + &SrsSettings::default(), + ) + .unwrap(); + assert_eq!( + branch(&inactive, &id, &["e2e4", "c7c5"]) + .unwrap() + .summary + .learnt, + 1 + ); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4", "c7c5"]), false) + .unwrap(); + let enabled = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + let restored = branch(&enabled, &id, &["e2e4", "c7c5"]).unwrap(); + assert_eq!(restored.summary.total, 1); + assert_eq!(restored.summary.learnt, 1); + assert_eq!(restored.last_independent_at, Some(NOW - DAY)); + assert_eq!(learning.item(&sideline), Some(&before)); +} + +#[test] +fn max_depth_and_branch_root_limit_candidates_and_items() { + let (library, id) = + single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 *"); + let learning = LearningData::default(); + let depth_scope = scope(id.clone()).with_max_depth(Some(4)); + let depth_rows = + branch_learning_analytics(&library, &learning, &depth_scope, &SrsSettings::default()) + .unwrap(); + assert_eq!( + branch(&depth_rows, &id, &["e2e4"]).unwrap().summary.total, + 2 + ); + assert!(depth_rows.iter().all(|row| row.branch_root.len() <= 4)); + assert!( + depth_rows + .iter() + .all(|row| !row.branch_root.contains(&"f1b5".to_owned())) + ); + + let root = strings(&["e2e4", "e7e5"]); + let rooted_scope = scope(id.clone()).with_branch_root(root.clone()); + let rooted_rows = + branch_learning_analytics(&library, &learning, &rooted_scope, &SrsSettings::default()) + .unwrap(); + assert!(!rooted_rows.is_empty()); + assert!( + rooted_rows + .iter() + .all(|row| row.branch_root.starts_with(&root)) + ); + assert!(branch(&rooted_rows, &id, &["e2e4"]).is_none()); + assert_eq!( + branch(&rooted_rows, &id, &["e2e4", "e7e5"]) + .unwrap() + .summary + .total, + 5 + ); + + let limited_scope = rooted_scope.with_max_depth(Some(4)); + let limited_rows = + branch_learning_analytics(&library, &learning, &limited_scope, &SrsSettings::default()) + .unwrap(); + assert_eq!(limited_rows.len(), 2); + assert_eq!( + branch(&limited_rows, &id, &["e2e4", "e7e5"]) + .unwrap() + .summary + .total, + 1 + ); + assert!(limited_rows.iter().all(|row| row.branch_root.len() <= 4)); +} + +#[test] +fn empty_scope_has_no_rows_or_whole_repertoire_root() { + let (library, id) = single_repertoire("1. e4 *"); + let empty = StatsScope::new([], LearningSide::White, NOW); + assert!( + branch_learning_analytics( + &library, + &LearningData::default(), + &empty, + &SrsSettings::default(), + ) + .unwrap() + .is_empty() + ); + + let no_black_moves = StatsScope::for_repertoire(id, LearningSide::Black, NOW); + assert!( + branch_learning_analytics( + &library, + &LearningData::default(), + &no_black_moves, + &SrsSettings::default(), + ) + .unwrap() + .is_empty() + ); +} + +#[test] +fn branch_projection_is_deterministic_and_sorted() { + let (library, id) = single_repertoire(branching_pgn()); + let selected = scope(id.clone()); + let mut learning = LearningData::default(); + for key in active_learning_keys(&library, &selected).unwrap() { + learning.ensure_item(key); + } + let first = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + let mut sorted = first.clone(); + sorted.sort_by(|left, right| { + (&left.repertoire_id, &left.branch_root).cmp(&(&right.repertoire_id, &right.branch_root)) + }); + assert_eq!(first, sorted); + + learning.items.reverse(); + let second = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(first, second); +} + +#[test] +fn all_path_projection_keeps_all_answers_and_honours_disabled_branches() { + let (mut library, id) = single_repertoire("1. e4 (1. d4 d5) e5 *"); + let selected = scope(id.clone()); + let learning = LearningData::default(); + let default_rows = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!( + branch(&default_rows, &id, &["e2e4"]).unwrap().summary.total, + 1 + ); + assert_eq!( + branch(&default_rows, &id, &["d2d4"]).unwrap().summary.total, + 1 + ); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4"]), true) + .unwrap(); + let active = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert!(branch(&active, &id, &["e2e4"]).is_none()); + assert_eq!(branch(&active, &id, &["d2d4"]).unwrap().summary.total, 1); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4"]), false) + .unwrap(); + let root = { + let repertoire = library.repertoire(&id).unwrap(); + let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); + tree.position_key(tree.root()).unwrap().to_owned() + }; + library + .repertoire_mut(&id) + .unwrap() + .set_main_answer_override(&root, "d2d4", LearningSide::White) + .unwrap(); + let overridden = + branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!( + branch(&overridden, &id, &["e2e4"]).unwrap().summary.total, + 1 + ); + assert_eq!( + branch(&overridden, &id, &["d2d4"]).unwrap().summary.total, + 1 + ); +} diff --git a/crates/trainer/src/repertoire/context_tests.rs b/crates/trainer/src/repertoire/context_tests.rs new file mode 100644 index 0000000..2c9df61 --- /dev/null +++ b/crates/trainer/src/repertoire/context_tests.rs @@ -0,0 +1,550 @@ +use super::*; +use crate::repertoire::learning::AttemptApplication; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 24 * 60 * 60; + +struct Fixture { + library: Library, + scope: StatsScope, + learning: LearningData, + session: LearningSessionSnapshot, +} + +fn key_for(library: &Library, scope: &StatsScope, expected_uci: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected_uci) + .unwrap() + .key +} + +fn seed( + learning: &mut LearningData, + key: LearningItemKey, + streak: u32, + next_review_at: Option, +) { + let item = learning.ensure_item(key); + item.introduced = true; + item.correct_streak = streak; + item.correct_count = u64::from(streak); + item.last_review_at = (streak > 0).then_some(NOW - DAY); + item.last_correct_at = (streak > 0).then_some(NOW - DAY); + item.next_review_at = next_review_at; +} + +fn fixture( + pgn: &str, + side: LearningSide, + mode: QueueMode, + policy: LearningContextPolicy, + items: &[(&str, u32, Option)], +) -> Fixture { + let mut library = Library::default(); + let id = library + .create("Test", &chess_core::parse_str(pgn).game) + .unwrap(); + let scope = StatsScope::for_repertoire(id, side, NOW); + let mut learning = LearningData::default(); + for (expected, streak, next) in items { + let key = key_for(&library, &scope, expected); + seed(&mut learning, key, *streak, *next); + } + let mut session = LearningSessionSnapshot::new_with_mode( + "context", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + mode, + ) + .unwrap(); + session.context_policy = policy; + Fixture { + library, + scope, + learning, + session, + } +} + +fn reinforcing_policy() -> LearningContextPolicy { + LearningContextPolicy { + consider_leadup_moves: true, + ..LearningContextPolicy::default() + } +} + +fn apply(learning: &mut LearningData, attempt: &TrainingAttempt) { + assert_eq!( + learning.apply_attempt(attempt.clone(), &SrsSettings::default()), + Ok(AttemptApplication::Applied) + ); +} + +fn play(fixture: &mut Fixture, uci: &str, id: &str) -> TrainingAttempt { + let attempt = fixture + .session + .play_uci_with_learning(&fixture.library, &fixture.learning, uci, id, NOW, Some(200)) + .unwrap(); + apply(&mut fixture.learning, &attempt); + attempt +} + +fn advance(fixture: &mut Fixture, id: &str) -> TrainingAttempt { + let attempt = fixture + .session + .advance_context_with_learning(&fixture.library, &fixture.learning, id, NOW) + .unwrap(); + apply(&mut fixture.learning, &attempt); + attempt +} + +fn automatic_uci(presentation: &LearningPresentation) -> Vec<&str> { + presentation + .automatic_context + .iter() + .map(|step| step.uci.as_str()) + .collect() +} + +#[test] +fn weak_context_is_reinforced_as_an_independent_answer() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + reinforcing_policy(), + &[("e2e4", 2, Some(NOW + 10 * DAY)), ("g1f3", 0, Some(NOW))], + ); + let e4 = key_for(&f.library, &f.scope, "e2e4"); + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!( + presentation.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert!(presentation.automatic_context.is_empty()); + assert_eq!(f.session.current_expected_uci(), Some("e2e4")); + + let answer = play(&mut f, "e2e4", "weak-e4"); + assert_eq!(answer.event_type, TrainingEventType::CorrectIndependent); + assert!(f.session.completed_keys.contains(&e4)); + assert_eq!(f.session.phase, LearningSessionPhase::AdvancingContext); + assert_eq!( + advance(&mut f, "weak-e5").event_type, + TrainingEventType::AutoContext + ); + assert_eq!(f.session.phase, LearningSessionPhase::AwaitingIndependent); + play(&mut f, "g1f3", "weak-target"); + assert_eq!(f.session.phase, LearningSessionPhase::Finished); + assert_eq!( + f.learning + .attempts + .iter() + .filter(|attempt| attempt.item_key() == e4 && attempt.event_type.is_independent()) + .count(), + 1 + ); +} + +#[test] +fn due_soon_policy_reinforces_even_a_learnt_context_move() { + let mut policy = reinforcing_policy(); + policy.reinforce_minimum_days = Some(3); + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + policy, + &[("e2e4", 3, Some(NOW + 2 * DAY)), ("g1f3", 0, Some(NOW))], + ); + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!( + presentation.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert_eq!(f.session.current_expected_uci(), Some("e2e4")); +} + +#[test] +fn well_known_context_outside_due_window_is_not_reinforced() { + let mut policy = reinforcing_policy(); + policy.reinforce_minimum_days = Some(3); + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + policy, + &[("e2e4", 3, Some(NOW + 10 * DAY)), ("g1f3", 0, Some(NOW))], + ); + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!(presentation.phase, LearningSessionPhase::AdvancingContext); + assert_eq!(automatic_uci(&presentation), ["e2e4", "e7e5"]); +} + +#[test] +fn very_well_known_start_prefix_is_omitted_without_attempts() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + reinforcing_policy(), + &[ + ("e2e4", 100, Some(NOW + 10 * DAY)), + ("g1f3", 100, Some(NOW + 10 * DAY)), + ("f1b5", 0, Some(NOW)), + ], + ); + let before = f.learning.clone(); + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!( + presentation.phase, + LearningSessionPhase::AwaitingIndependent + ); + assert!(presentation.automatic_context.is_empty()); + assert_eq!(f.session.context_index, 4); + assert_eq!(f.session.current_expected_uci(), Some("f1b5")); + assert_eq!( + presentation.current_position.unwrap().fen4, + key_for(&f.library, &f.scope, "f1b5").position_fen4 + ); + assert_eq!(f.learning, before); +} + +#[test] +fn opponent_context_stays_automatic_even_with_weak_learning_data() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + QueueMode::SpacedRepetition, + reinforcing_policy(), + &[("e7e5", 2, Some(NOW + 10 * DAY)), ("b8c6", 0, Some(NOW))], + ); + let white_scope = StatsScope::for_repertoire( + f.scope.repertoire_ids.iter().next().unwrap().clone(), + LearningSide::White, + NOW, + ); + let opponent = key_for(&f.library, &white_scope, "e2e4"); + seed(&mut f.learning, opponent, 0, Some(NOW)); + + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!(presentation.phase, LearningSessionPhase::AdvancingContext); + assert_eq!(automatic_uci(&presentation), ["e2e4"]); + let automatic = advance(&mut f, "opponent-e4"); + assert_eq!(automatic.event_type, TrainingEventType::AutoContext); + assert_eq!( + f.session.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert_eq!(f.session.current_expected_uci(), Some("e7e5")); +} + +#[test] +fn reinforcement_is_not_repeated_in_the_same_review_cycle() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + QueueMode::ReviewInOrder, + reinforcing_policy(), + &[("e2e4", 0, Some(NOW + DAY)), ("g1f3", 0, Some(NOW))], + ); + f.session.queue.reverse(); + let e4 = key_for(&f.library, &f.scope, "e2e4"); + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!( + presentation.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + play(&mut f, "e2e4", "cycle-context-e4"); + advance(&mut f, "cycle-e5"); + play(&mut f, "g1f3", "cycle-target-nf3"); + assert_eq!(f.session.cycle, 1); + assert!(f.session.completed_keys.is_empty()); + assert_eq!( + f.learning + .attempts + .iter() + .filter(|attempt| attempt.item_key() == e4 && attempt.event_type.is_independent()) + .count(), + 1 + ); + + let next_cycle = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!( + next_cycle.phase, + LearningSessionPhase::AwaitingContextIndependent + ); +} + +#[test] +fn wrong_context_replay_completes_context_without_success() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + reinforcing_policy(), + &[("e2e4", 2, Some(NOW + 10 * DAY)), ("g1f3", 0, Some(NOW))], + ); + let e4 = key_for(&f.library, &f.scope, "e2e4"); + f.session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + let wrong = play(&mut f, "d2d4", "context-wrong"); + assert_eq!(wrong.event_type, TrainingEventType::IncorrectIndependent); + assert_eq!( + f.session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + let revealed = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!(revealed.revealed_move.as_deref(), Some("e2e4")); + assert!(revealed.automatic_context.is_empty()); + + let replay = play(&mut f, "e2e4", "context-replay"); + assert_eq!(replay.event_type, TrainingEventType::ReplayAfterError); + assert!(f.session.completed_keys.contains(&e4)); + assert_eq!(f.session.phase, LearningSessionPhase::AdvancingContext); + let item = f.learning.item(&e4).unwrap(); + assert_eq!(item.correct_count, 2); + assert_eq!(item.wrong_count, 1); + assert_eq!(item.correct_streak, 0); + assert_eq!(item.last_correct_at, None); + assert_eq!( + f.learning + .attempts + .iter() + .filter(|attempt| attempt.item_key() == e4 && attempt.event_type.is_independent()) + .count(), + 1 + ); +} + +#[test] +fn leadup_off_and_legacy_methods_keep_context_automatic() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + LearningContextPolicy::default(), + &[("e2e4", 0, Some(NOW + DAY)), ("g1f3", 0, Some(NOW))], + ); + let e4 = key_for(&f.library, &f.scope, "e2e4"); + let before = f.learning.item(&e4).unwrap().clone(); + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!(presentation.phase, LearningSessionPhase::AdvancingContext); + assert_eq!(automatic_uci(&presentation), ["e2e4", "e7e5"]); + assert!( + presentation + .automatic_context + .iter() + .all(|step| step.speed_factor == 1.0) + ); + + let first = f + .session + .advance_context(&f.library, "legacy-e4", NOW) + .unwrap(); + apply(&mut f.learning, &first); + let second = f + .session + .advance_context(&f.library, "legacy-e5", NOW) + .unwrap(); + apply(&mut f.learning, &second); + assert_eq!(f.session.phase, LearningSessionPhase::AwaitingIndependent); + assert_eq!(f.learning.item(&e4), Some(&before)); +} + +#[test] +fn fixed_and_adaptive_speed_factors_are_deterministic_and_clamped() { + let mut policy = LearningContextPolicy { + use_fixed_piece_speed: true, + move_speed_adjustment: 3.0, + ..LearningContextPolicy::default() + }; + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + policy, + &[("e2e4", 3, Some(NOW + DAY)), ("g1f3", 0, Some(NOW))], + ); + let fixed = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert!( + fixed + .automatic_context + .iter() + .all(|step| step.speed_factor == 1.0) + ); + + policy = f.session.context_policy; + policy.use_fixed_piece_speed = false; + policy.move_speed_adjustment = 1.5; + f.session.context_policy = policy; + let adaptive = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!(adaptive.automatic_context[0].speed_factor, 3.0); + assert_eq!(adaptive.automatic_context[1].speed_factor, 1.5); + + f.session.context_policy.move_speed_adjustment = 100.0; + let high = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert!( + high.automatic_context + .iter() + .all(|step| step.speed_factor == 4.0) + ); + f.session.context_policy.move_speed_adjustment = 0.0; + let low = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert!( + low.automatic_context + .iter() + .all(|step| step.speed_factor == 0.25) + ); +} + +#[test] +fn resume_keeps_partial_learning_context_position() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::White, + QueueMode::SpacedRepetition, + reinforcing_policy(), + &[ + ("e2e4", 2, Some(NOW + DAY)), + ("g1f3", 3, Some(NOW + 10 * DAY)), + ("f1b5", 0, Some(NOW)), + ], + ); + f.session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + play(&mut f, "e2e4", "resume-e4"); + advance(&mut f, "resume-e5"); + assert_eq!(f.session.context_index, 2); + + let json = serde_json::to_string(&f.session).unwrap(); + let restored = serde_json::from_str::(&json) + .unwrap() + .resume(&f.library) + .unwrap(); + f.session = restored; + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!(f.session.context_index, 2); + assert_eq!(automatic_uci(&presentation), ["g1f3", "b8c6"]); + advance(&mut f, "resume-nf3"); + advance(&mut f, "resume-nc6"); + assert_eq!(f.session.phase, LearningSessionPhase::AwaitingIndependent); + assert_eq!(f.session.current_expected_uci(), Some("f1b5")); +} + +#[test] +fn old_json_unknown_fields_and_duplicate_attempts_remain_compatible() { + let mut f = fixture( + "1. e4 *", + LearningSide::White, + QueueMode::SpacedRepetition, + LearningContextPolicy::default(), + &[("e2e4", 1, Some(NOW))], + ); + let mut raw = serde_json::to_value(&f.session).unwrap(); + raw.as_object_mut().unwrap().remove("context_policy"); + raw["future_snapshot"] = serde_json::json!({"preserved": true}); + let restored: LearningSessionSnapshot = serde_json::from_value(raw).unwrap(); + assert_eq!(restored.context_policy, LearningContextPolicy::default()); + restored.clone().resume(&f.library).unwrap(); + let policy: LearningContextPolicy = serde_json::from_value(serde_json::json!({ + "future_policy_field": true + })) + .unwrap(); + assert_eq!(policy, LearningContextPolicy::default()); + f.session = restored; + + let attempt = f + .session + .play_uci_with_learning(&f.library, &f.learning, "e2e4", "at-23", NOW, Some(100)) + .unwrap(); + apply(&mut f.learning, &attempt); + assert_eq!( + f.learning.apply_attempt(attempt, &SrsSettings::default()), + Ok(AttemptApplication::Duplicate) + ); + let e4 = key_for(&f.library, &f.scope, "e2e4"); + assert_eq!(f.learning.item(&e4).unwrap().correct_count, 2); + assert_eq!( + f.learning + .attempts + .iter() + .filter(|attempt| attempt.client_attempt_id == "at-23") + .count(), + 1 + ); +} + +#[test] +fn least_recent_keeps_legacy_context_checks_with_leadup_off() { + let mut f = fixture( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::White, + QueueMode::LeastRecent, + LearningContextPolicy::default(), + &[ + ("e2e4", 0, Some(NOW + DAY)), + ("g1f3", 0, Some(NOW + DAY)), + ("f1b5", 0, Some(NOW + DAY)), + ], + ); + f.session.queue.reverse(); + f.session.phase = LearningSessionPhase::AdvancingContext; + let presentation = f + .session + .presentation_with_learning(&f.library, &f.learning) + .unwrap(); + assert_eq!( + presentation.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert_eq!(f.session.current_expected_uci(), Some("e2e4")); + assert!(presentation.automatic_context.is_empty()); +} diff --git a/crates/trainer/src/repertoire/daily_tests.rs b/crates/trainer/src/repertoire/daily_tests.rs new file mode 100644 index 0000000..8b72827 --- /dev/null +++ b/crates/trainer/src/repertoire/daily_tests.rs @@ -0,0 +1,450 @@ +//! Daily sessions (due + N new), mistakes coming back in the same session, one-pass +//! review and sessions limited to a branch. + +use super::*; + +const NOW: i64 = 1_800_000_000; +const PGN: &str = "1. e4 e5 2. Nf3 Nc6 3. Bb5 (3. Bc4 Bc5) a6 4. Ba4 *"; + +fn library(pgn: &str) -> (Library, RepertoireId) { + let mut library = Library::default(); + let id = library + .create("Test", &chess_core::parse_str(pgn).game) + .unwrap(); + (library, id) +} + +fn key_for(library: &Library, scope: &StatsScope, expected_uci: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected_uci) + .unwrap() + .key +} + +fn queue_moves(session: &LearningSessionSnapshot) -> Vec<&str> { + session + .queue + .iter() + .skip(session.current_index) + .filter(|target| !session.completed_keys.contains(&target.key)) + .map(|target| target.key.expected_uci.as_str()) + .collect() +} + +/// Plays the automatic context up to the question, applying every event. +fn to_question( + session: &mut LearningSessionSnapshot, + library: &Library, + learning: &mut LearningData, +) { + let mut step = 0; + while session + .presentation_with_learning(library, learning) + .unwrap() + .phase + == LearningSessionPhase::AdvancingContext + { + step += 1; + let attempt = session + .advance_context_with_learning( + library, + learning, + format!("ctx-{step}-{}", session.revision), + NOW, + ) + .unwrap(); + session.revision += 1; + learning + .apply_attempt(attempt, &SrsSettings::default()) + .unwrap(); + } +} + +fn answer( + session: &mut LearningSessionSnapshot, + library: &Library, + learning: &mut LearningData, + uci: &str, + id: &str, +) -> TrainingAttempt { + let attempt = session + .play_uci_with_learning(library, learning, uci, id, NOW, Some(1000)) + .unwrap(); + learning + .apply_attempt(attempt.clone(), &SrsSettings::default()) + .unwrap(); + attempt +} + +#[test] +fn daily_queue_takes_every_due_move_and_at_most_n_new_in_pgn_order() { + let (library, id) = library(PGN); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + // Due deep in the line, known and not due early in it. + for (uci, next) in [("f1b5", NOW - 10), ("e2e4", NOW + 3600)] { + let item = learning.ensure_item(key_for(&library, &scope, uci)); + item.introduced = true; + item.next_review_at = Some(next); + } + let session = LearningSessionSnapshot::new_daily( + "daily", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 2, + ) + .unwrap(); + // Own moves in PGN order: e4 Nf3 Bb5 Ba4 Bc4. Due: Bb5. New: Nf3, Ba4 (2 of 3). + assert_eq!(queue_moves(&session), ["g1f3", "f1b5", "b5a4"]); + assert!(session.return_mistakes); + assert_eq!(session.session.mode, QueueMode::SpacedRepetition); + let all = LearningSessionSnapshot::new_daily( + "daily-all", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 10, + ) + .unwrap(); + assert_eq!(queue_moves(&all), ["g1f3", "f1b5", "b5a4", "f1c4"]); + let none = LearningSessionSnapshot::new_daily( + "daily-none", + &library, + &learning, + scope, + SrsSettings::default(), + 0, + ) + .unwrap(); + assert_eq!(queue_moves(&none), ["f1b5"]); +} + +#[test] +fn a_mistake_comes_back_in_the_same_session_and_a_shown_new_move_does_not() { + let (library, id) = library("1. e4 e5 2. Nf3 Nc6 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + let e4 = key_for(&library, &scope, "e2e4"); + let item = learning.ensure_item(e4.clone()); + item.introduced = true; + item.next_review_at = Some(NOW); + let mut session = LearningSessionSnapshot::new_daily( + "return", + &library, + &learning, + scope, + SrsSettings::default(), + 10, + ) + .unwrap(); + assert_eq!(queue_moves(&session), ["e2e4", "g1f3"]); + assert_eq!(session.remaining(), 2); + assert!(!session.current_is_new(&learning)); + + let wrong = answer(&mut session, &library, &mut learning, "d2d4", "wrong"); + assert_eq!(wrong.event_type, TrainingEventType::IncorrectIndependent); + assert_eq!( + session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + assert_eq!(session.remaining(), 2); + let replay = answer(&mut session, &library, &mut learning, "e2e4", "replay"); + assert_eq!(replay.event_type, TrainingEventType::ReplayAfterError); + // e4 is not done: it waits behind Nf3. + assert_eq!(queue_moves(&session), ["g1f3", "e2e4"]); + assert_eq!(session.remaining(), 2); + assert!(!session.completed_keys.contains(&e4)); + session.validate(&library).unwrap(); + + to_question(&mut session, &library, &mut learning); + assert!(session.current_is_new(&learning)); + let shown = session.preview_new("show-nf3", NOW).unwrap().unwrap(); + assert_eq!(shown.event_type, TrainingEventType::Previewed); + assert!(session.showing_new); + learning + .apply_attempt(shown, &SrsSettings::default()) + .unwrap(); + let played = answer(&mut session, &library, &mut learning, "g1f3", "play-nf3"); + assert_eq!(played.event_type, TrainingEventType::AutoContext); + // A shown new move is played once and counts as done. + assert_eq!(queue_moves(&session), ["e2e4"]); + assert_eq!(session.remaining(), 1); + assert!(!session.showing_new); + + let correct = answer(&mut session, &library, &mut learning, "e2e4", "second-try"); + assert_eq!(correct.event_type, TrainingEventType::CorrectIndependent); + assert_eq!(session.phase, LearningSessionPhase::Finished); + assert_eq!(session.remaining(), 0); + let item = learning.item(&e4).unwrap(); + assert_eq!((item.wrong_count, item.correct_count), (1, 1)); + session.validate(&library).unwrap(); +} + +#[test] +fn a_hint_comes_back_but_not_in_a_one_pass_review() { + let (library, id) = library("1. e4 e5 2. Nf3 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + for uci in ["e2e4", "g1f3"] { + let item = learning.ensure_item(key_for(&library, &scope, uci)); + item.introduced = true; + item.next_review_at = Some(NOW); + } + let mut daily = LearningSessionSnapshot::new_daily( + "hint-daily", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 10, + ) + .unwrap(); + daily.preview("hint", NOW).unwrap().unwrap(); + assert!(!daily.showing_new); + answer(&mut daily, &library, &mut learning, "e2e4", "after-hint"); + assert_eq!(queue_moves(&daily), ["g1f3", "e2e4"]); + + let mut review = LearningSessionSnapshot::new_single_pass_review( + "hint-review", + &library, + &learning, + scope, + SrsSettings::default(), + ) + .unwrap(); + assert!(!review.return_mistakes); + answer(&mut review, &library, &mut learning, "d2d4", "review-wrong"); + answer( + &mut review, + &library, + &mut learning, + "e2e4", + "review-replay", + ); + assert_eq!(queue_moves(&review), ["g1f3"]); +} + +#[test] +fn one_pass_review_finishes_instead_of_starting_a_new_cycle() { + let (library, id) = library("1. e4 e5 2. Nf3 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + let mut review = LearningSessionSnapshot::new_single_pass_review( + "single", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + ) + .unwrap(); + assert_eq!(review.session.mode, QueueMode::ReviewInOrder); + assert_eq!(queue_moves(&review), ["e2e4", "g1f3"]); + answer(&mut review, &library, &mut learning, "e2e4", "single-e4"); + to_question(&mut review, &library, &mut learning); + answer(&mut review, &library, &mut learning, "g1f3", "single-nf3"); + assert_eq!(review.phase, LearningSessionPhase::Finished); + assert_eq!(review.cycle, 0); + review.validate(&library).unwrap(); + + // The old looping review is unchanged. + let mut looping = LearningSessionSnapshot::new_with_mode( + "loop", + &library, + &learning, + scope, + SrsSettings::default(), + QueueMode::ReviewInOrder, + ) + .unwrap(); + answer(&mut looping, &library, &mut learning, "e2e4", "loop-e4"); + to_question(&mut looping, &library, &mut learning); + answer(&mut looping, &library, &mut learning, "g1f3", "loop-nf3"); + assert_eq!(looping.cycle, 1); + assert_ne!(looping.phase, LearningSessionPhase::Finished); +} + +#[test] +fn introduce_more_takes_the_next_unseen_moves_only() { + let (library, id) = library(PGN); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + let mut session = LearningSessionSnapshot::new_daily( + "more", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 2, + ) + .unwrap(); + assert_eq!(queue_moves(&session), ["e2e4", "g1f3"]); + assert_eq!( + session.introduce_more(&library, &learning, 2), + Err(LearningSessionError::IntroductionRequiresFinished) + ); + for uci in ["e2e4", "g1f3"] { + to_question(&mut session, &library, &mut learning); + let shown = session + .preview_new(format!("show-{uci}"), NOW) + .unwrap() + .unwrap(); + learning + .apply_attempt(shown, &SrsSettings::default()) + .unwrap(); + answer( + &mut session, + &library, + &mut learning, + uci, + &format!("play-{uci}"), + ); + } + assert_eq!(session.phase, LearningSessionPhase::Finished); + // The two shown moves are due again in a minute, yet "more" means new ones only. + assert_eq!(session.introduce_more(&library, &learning, 2), Ok(2)); + assert_eq!(queue_moves(&session), ["f1b5", "b5a4"]); + assert_eq!( + session.introduce_more(&library, &learning, 2), + Err(LearningSessionError::IntroductionRequiresFinished) + ); + let mut review = LearningSessionSnapshot::new_single_pass_review( + "more-review", + &library, + &learning, + scope, + SrsSettings::default(), + ) + .unwrap(); + while review.current_target().is_some() { + review.current_index += 1; + } + review.phase = LearningSessionPhase::Finished; + assert_eq!( + review.introduce_more(&library, &learning, 2), + Err(LearningSessionError::UnsupportedMode( + QueueMode::ReviewInOrder + )) + ); +} + +#[test] +fn branch_session_asks_only_moves_of_the_branch_from_the_start_of_the_game() { + let (library, id) = library(PGN); + let through = ["e2e4", "e7e5", "g1f3", "b8c6", "f1c4"].map(str::to_owned); + let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, NOW); + let mut learning = LearningData::default(); + // Through an own move: that move is asked, its sibling Bb5 is not. + let mut session = LearningSessionSnapshot::new_branch_review( + "branch", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + &through, + ) + .unwrap(); + assert_eq!(queue_moves(&session), ["f1c4"]); + assert_eq!( + session.stats_scope.branch_root.as_deref(), + Some(&through[..4]) + ); + assert!(session.single_pass); + let target = session.current_target().unwrap(); + assert_eq!(target.path, through); + // The context is played from the start of the game, not from the branch. + let presentation = session + .presentation_with_learning(&library, &learning) + .unwrap(); + assert_eq!(presentation.automatic_context.len(), 4); + assert_eq!(presentation.automatic_context[0].uci, "e2e4"); + to_question(&mut session, &library, &mut learning); + answer(&mut session, &library, &mut learning, "f1c4", "branch-bc4"); + assert_eq!(session.phase, LearningSessionPhase::Finished); + session.validate(&library).unwrap(); + + // Through an opponent's move: every own move below it. + let below = LearningSessionSnapshot::new_branch_review( + "branch-below", + &library, + &LearningData::default(), + scope.clone(), + SrsSettings::default(), + &through[..4], + ) + .unwrap(); + assert_eq!(queue_moves(&below), ["f1b5", "b5a4", "f1c4"]); + assert!( + below + .queue + .iter() + .all(|target| target.path.starts_with(&through[..4])) + ); + + // The whole repertoire, and a daily session limited by a branch root. + let whole = LearningSessionSnapshot::new_branch_review( + "branch-whole", + &library, + &LearningData::default(), + scope.clone(), + SrsSettings::default(), + &[], + ) + .unwrap(); + assert_eq!(queue_moves(&whole).len(), 5); + let daily = LearningSessionSnapshot::new_daily( + "branch-daily", + &library, + &LearningData::default(), + scope.with_branch_root(through[..4].to_vec()), + SrsSettings::default(), + 10, + ) + .unwrap(); + assert_eq!(queue_moves(&daily), ["f1b5", "b5a4", "f1c4"]); +} + +#[test] +fn new_flags_are_optional_in_the_file_and_survive_a_roundtrip() { + let (library, id) = library("1. e4 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let learning = LearningData::default(); + let plain = LearningSessionSnapshot::new( + "plain", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + ) + .unwrap(); + let json = serde_json::to_value(&plain).unwrap(); + // 2.3.0 snapshots stay byte-compatible when no new behaviour is used. + for field in ["return_mistakes", "single_pass", "showing_new"] { + assert!( + json.get(field).is_none(), + "{field} written for an old-style session" + ); + } + let read: LearningSessionSnapshot = serde_json::from_value(json).unwrap(); + assert_eq!(read, plain); + + let mut daily = LearningSessionSnapshot::new_daily( + "flags", + &library, + &learning, + scope, + SrsSettings::default(), + 10, + ) + .unwrap(); + daily.preview_new("show", NOW).unwrap(); + daily.single_pass = true; + let json = serde_json::to_string(&daily).unwrap(); + let read: LearningSessionSnapshot = serde_json::from_str(&json).unwrap(); + assert!(read.return_mistakes && read.single_pass && read.showing_new); + read.validate(&library).unwrap(); +} diff --git a/crates/trainer/src/repertoire/graph_tests.rs b/crates/trainer/src/repertoire/graph_tests.rs new file mode 100644 index 0000000..23f9102 --- /dev/null +++ b/crates/trainer/src/repertoire/graph_tests.rs @@ -0,0 +1,703 @@ +use std::collections::BTreeSet; + +use chess_core::shakmaty::{CastlingMode, Position}; +use chess_core::{Game, NodeId}; + +use super::*; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 24 * 60 * 60; + +fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { + library + .create(name, &chess_core::parse_str(pgn).game) + .unwrap() +} + +fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { + let mut library = Library::default(); + let id = add_repertoire(&mut library, "One", pgn); + (library, id) +} + +fn scope(id: RepertoireId, side: LearningSide) -> StatsScope { + StatsScope::for_repertoire(id, side, NOW) +} + +fn strings(moves: &[&str]) -> Vec { + moves.iter().map(|mv| (*mv).to_owned()).collect() +} + +fn key_at_path(repertoire: &Repertoire, path: &[String], expected_uci: &str) -> LearningItemKey { + let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); + let parent = tree.node_at_path(path).unwrap(); + LearningItemKey::local(tree.position_key(parent).unwrap(), expected_uci) +} + +fn learnt(item: &mut LearningItem, next_review_at: i64) { + item.introduced = true; + item.correct_streak = 3; + item.correct_count = 3; + item.last_review_at = Some(NOW - DAY); + item.last_correct_at = Some(NOW - DAY); + item.next_review_at = Some(next_review_at); + item.previous_interval_seconds = Some(DAY); +} + +fn pgn_with_white_moves(count: usize) -> String { + let mut game = Game::new(); + let mut position = game.start().position().clone(); + let mut node = NodeId::ROOT; + let mut visited = BTreeSet::from([fen4(&position)]); + for _ in 0..count * 2 - 1 { + let mut moves = position.legal_moves(); + moves.sort_by_key(|mv| mv.to_uci(CastlingMode::Standard).to_string()); + let mv = moves + .into_iter() + .find(|mv| { + let mut next = position.clone(); + next.play_unchecked(*mv); + !visited.contains(&fen4(&next)) + }) + .expect("fixture must have a non-repeating legal continuation"); + node = game.add_line(node, &[mv]).unwrap(); + position.play_unchecked(mv); + visited.insert(fen4(&position)); + } + game.to_pgn() +} + +fn transposition_pgn() -> &'static str { + "1. e4 d5 (1... Nf6 2. d4 d5 3. c4) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 e6 6. g3 *" +} + +#[test] +fn at_01_one_hundred_real_pgn_moves_are_unique_unseen_and_not_due() { + let (library, id) = single_repertoire(&pgn_with_white_moves(100)); + let learning = LearningData::default(); + let scoped = aggregate_scope( + &library, + &learning, + &scope(id, LearningSide::White), + &SrsSettings::default(), + ) + .unwrap(); + + assert_eq!(scoped.summary.total, 100); + assert_eq!(scoped.summary.unseen, 100); + assert_eq!(scoped.summary.learning, 0); + assert_eq!(scoped.summary.learnt, 0); + assert_eq!(scoped.summary.due, 0); + assert_eq!(scoped.items.len(), 100); + assert_eq!(scoped.scope.as_of, NOW); + assert!(learning.items.is_empty()); +} + +#[test] +fn at_07_zero_due_with_unseen_is_not_confirmed_current() { + let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 *"); + let scope = scope(id, LearningSide::White); + let mut learning = LearningData::default(); + let first = active_learning_keys(&library, &scope) + .unwrap() + .into_iter() + .find(|key| key.expected_uci == "e2e4") + .unwrap(); + let item = learning.ensure_item(first); + item.introduced = true; + item.correct_streak = 1; + item.next_review_at = Some(NOW + DAY); + + let scoped = aggregate_scope(&library, &learning, &scope, &SrsSettings::default()).unwrap(); + assert_eq!(scoped.summary.due, 0); + assert_eq!(scoped.summary.unseen, 1); + assert_eq!(scoped.summary.learning, 1); + assert_ne!( + scoped.summary.repertoire_status, + RepertoireStatus::ConfirmedCurrent + ); + assert_eq!( + scoped.summary.repertoire_status, + RepertoireStatus::InProgress + ); +} + +#[test] +fn at_14_two_repertoires_use_one_global_learning_item() { + let mut library = Library::default(); + let first = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); + let second = add_repertoire(&mut library, "Petrov", "1. e4 e5 2. Nf3 Nf6 *"); + let root = fen4(Game::new().start().position()); + let shared_key = LearningItemKey::local(root, "e2e4"); + let mut learning = LearningData::default(); + let shared_item = learning.ensure_item(shared_key.clone()); + shared_item.introduced = true; + shared_item.correct_streak = 2; + + let first_scope = scope(first.clone(), LearningSide::White); + let second_scope = scope(second.clone(), LearningSide::White); + let both_scope = StatsScope::new([first, second], LearningSide::White, NOW); + for selected in [&first_scope, &second_scope, &both_scope] { + let scoped = + aggregate_scope(&library, &learning, selected, &SrsSettings::default()).unwrap(); + assert_eq!(scoped.summary.total, 2); + assert_eq!(scoped.summary.learning, 1); + assert_eq!(scoped.summary.unseen, 1); + assert_eq!( + scoped + .items + .iter() + .filter(|item| item.key == shared_key) + .count(), + 1 + ); + } + assert_eq!(learning.items.len(), 1); + assert_eq!(learning.items[0].correct_streak, 2); +} + +#[test] +fn at_15_global_aggregate_is_union_not_sum_of_repertoire_rows() { + let mut library = Library::default(); + let first = add_repertoire(&mut library, "Two knights", "1. e4 e5 2. Nf3 Nc6 *"); + let second = add_repertoire(&mut library, "Petrov", "1. e4 e5 2. Nf3 Nf6 *"); + let learning = LearningData::default(); + let first_total = aggregate_scope( + &library, + &learning, + &scope(first.clone(), LearningSide::Black), + &SrsSettings::default(), + ) + .unwrap() + .summary + .total; + let second_total = aggregate_scope( + &library, + &learning, + &scope(second.clone(), LearningSide::Black), + &SrsSettings::default(), + ) + .unwrap() + .summary + .total; + let global = aggregate_scope( + &library, + &learning, + &StatsScope::new([first, second], LearningSide::Black, NOW), + &SrsSettings::default(), + ) + .unwrap(); + + assert_eq!((first_total, second_total), (2, 2)); + assert_eq!(global.summary.total, 3); + assert!(global.summary.total < first_total + second_total); +} + +#[test] +fn at_16_no_active_own_moves_is_empty_without_percentages() { + let (library, id) = single_repertoire("1. e4 *"); + let scoped = aggregate_scope( + &library, + &LearningData::default(), + &scope(id, LearningSide::Black), + &SrsSettings::default(), + ) + .unwrap(); + + assert_eq!(scoped.summary.total, 0); + assert_eq!(scoped.summary.repertoire_status, RepertoireStatus::Empty); + for percentage in [ + scoped.summary.coverage_percent, + scoped.summary.learnt_percent, + scoped.summary.confident_percent, + scoped.summary.learning_percent, + scoped.summary.unseen_percent, + ] { + assert_eq!(percentage, None); + } +} + +#[test] +fn at_17_depth_limits_summary_but_not_full_scope() { + let (library, id) = + single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 *"); + let full_scope = scope(id.clone(), LearningSide::White); + let depth_scope = full_scope.clone().with_max_depth(Some(10)); + let learning = LearningData::default(); + let depth = + aggregate_scope(&library, &learning, &depth_scope, &SrsSettings::default()).unwrap(); + let full = aggregate_scope(&library, &learning, &full_scope, &SrsSettings::default()).unwrap(); + + assert_eq!(depth.summary.total, 5); + assert_eq!(full.summary.total, 6); + assert!( + full.items + .iter() + .any(|item| item.key.expected_uci == "f1e1") + ); + assert!( + !depth + .items + .iter() + .any(|item| item.key.expected_uci == "f1e1") + ); +} + +#[test] +fn at_18_19_disable_and_reenable_preserve_global_history() { + let (mut library, id) = single_repertoire("1. e4 e5 (1... c5) 2. Nf3 *"); + let mut learning = LearningData::default(); + let nf3 = key_at_path( + library.repertoire(&id).unwrap(), + &strings(&["e2e4", "e7e5"]), + "g1f3", + ); + learnt(learning.ensure_item(nf3.clone()), NOW + DAY); + let before = learning.item(&nf3).unwrap().clone(); + let selected = scope(id.clone(), LearningSide::White); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4", "e7e5"]), true) + .unwrap(); + let disabled = + aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(disabled.summary.total, 1); + assert!(!disabled.items.iter().any(|item| item.key == nf3)); + assert_eq!(learning.item(&nf3), Some(&before)); + + let mut include_inactive = selected.clone(); + include_inactive.only_active = false; + assert_eq!( + aggregate_scope( + &library, + &learning, + &include_inactive, + &SrsSettings::default(), + ) + .unwrap() + .summary + .learnt, + 1 + ); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4", "e7e5"]), false) + .unwrap(); + let enabled = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(enabled.summary.total, 2); + assert_eq!(enabled.summary.learnt, 1); + assert_eq!(learning.item(&nf3), Some(&before)); +} + +#[test] +fn disabled_transposition_keeps_shared_key_through_another_active_branch() { + let (mut library, id) = single_repertoire(transposition_pgn()); + let selected = scope(id.clone(), LearningSide::White); + let shared = key_at_path( + library.repertoire(&id).unwrap(), + &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), + "c2c4", + ); + let mut learning = LearningData::default(); + learnt(learning.ensure_item(shared.clone()), NOW + DAY); + let before = learning.item(&shared).unwrap().clone(); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4", "d7d5"]), true) + .unwrap(); + let disabled_keys = active_learning_keys(&library, &selected).unwrap(); + assert!(disabled_keys.contains(&shared)); + assert_eq!(disabled_keys.len(), 3); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4", "d7d5"]), false) + .unwrap(); + let enabled_keys = active_learning_keys(&library, &selected).unwrap(); + assert!(enabled_keys.contains(&shared)); + assert_eq!(enabled_keys.len(), 7); + assert_eq!(learning.item(&shared), Some(&before)); +} + +#[test] +fn at_24_transposition_paths_share_one_key_and_progress() { + let (library, id) = single_repertoire(transposition_pgn()); + let repertoire = library.repertoire(&id).unwrap(); + let first_scope = + scope(id.clone(), LearningSide::White).with_branch_root(strings(&["e2e4", "d7d5"])); + let second_scope = scope(id, LearningSide::White).with_branch_root(strings(&["e2e4", "g8f6"])); + let first_keys = active_learning_keys(&library, &first_scope).unwrap(); + let second_keys = active_learning_keys(&library, &second_scope).unwrap(); + let shared: Vec<_> = first_keys.intersection(&second_keys).cloned().collect(); + let expected = key_at_path( + repertoire, + &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), + "c2c4", + ); + assert_eq!(shared.as_slice(), std::slice::from_ref(&expected)); + + let mut learning = LearningData::default(); + learnt(learning.ensure_item(expected), NOW + DAY); + for selected in [first_scope, second_scope] { + let scoped = + aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(scoped.summary.learnt, 1); + } + assert_eq!(learning.items.len(), 1); +} + +#[test] +fn at_25_adding_twenty_moves_recalculates_scope_and_preserves_successes() { + let (mut library, id) = single_repertoire(&pgn_with_white_moves(80)); + let selected = scope(id.clone(), LearningSide::White); + let old_keys = active_learning_keys(&library, &selected).unwrap(); + assert_eq!(old_keys.len(), 80); + let mut learning = LearningData::default(); + for key in old_keys { + learnt(learning.ensure_item(key), NOW + DAY); + } + let before = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(before.summary.learnt_percent, Some(100.0)); + + library.repertoire_mut(&id).unwrap().pgn = pgn_with_white_moves(100); + let after = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(after.summary.total, 100); + assert_eq!(after.summary.learnt, 80); + assert_eq!(after.summary.unseen, 20); + assert_eq!(after.summary.learnt_percent, Some(80.0)); + assert!(learning.items.iter().all(|item| item.correct_streak == 3)); +} + +#[test] +fn at_28_one_hundred_learnt_with_three_due_is_all_learnt_not_confirmed() { + let (library, id) = single_repertoire(&pgn_with_white_moves(100)); + let selected = scope(id, LearningSide::White); + let mut learning = LearningData::default(); + for (index, key) in active_learning_keys(&library, &selected) + .unwrap() + .into_iter() + .enumerate() + { + learnt( + learning.ensure_item(key), + if index < 3 { NOW } else { NOW + DAY }, + ); + } + let scoped = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(scoped.summary.total, 100); + assert_eq!(scoped.summary.learnt, 100); + assert_eq!(scoped.summary.due, 3); + assert_eq!( + scoped.summary.repertoire_status, + RepertoireStatus::AllLearnt + ); +} + +#[test] +fn at_29_one_hundred_fresh_learnt_without_due_is_confirmed_current() { + let (library, id) = single_repertoire(&pgn_with_white_moves(100)); + let selected = scope(id, LearningSide::White); + let mut learning = LearningData::default(); + for key in active_learning_keys(&library, &selected).unwrap() { + learnt(learning.ensure_item(key), NOW + DAY); + } + let scoped = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(scoped.summary.total, 100); + assert_eq!(scoped.summary.learnt, 100); + assert_eq!(scoped.summary.due, 0); + assert_eq!(scoped.summary.uncertain, 0); + assert_eq!( + scoped.summary.repertoire_status, + RepertoireStatus::ConfirmedCurrent + ); +} + +#[test] +fn at_30_lines_overlap_but_repertoire_is_not_an_arithmetic_mean() { + let (library, id) = single_repertoire(transposition_pgn()); + let repertoire = library.repertoire(&id).unwrap(); + let first_scope = + scope(id.clone(), LearningSide::White).with_branch_root(strings(&["e2e4", "d7d5"])); + let second_scope = + scope(id.clone(), LearningSide::White).with_branch_root(strings(&["e2e4", "g8f6"])); + let shared = key_at_path( + repertoire, + &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), + "c2c4", + ); + let mut learning = LearningData::default(); + learnt(learning.ensure_item(shared), NOW + DAY); + let first = + aggregate_scope(&library, &learning, &first_scope, &SrsSettings::default()).unwrap(); + let second = + aggregate_scope(&library, &learning, &second_scope, &SrsSettings::default()).unwrap(); + let full = aggregate_scope( + &library, + &learning, + &scope(id, LearningSide::White), + &SrsSettings::default(), + ) + .unwrap(); + + assert_eq!((first.summary.total, second.summary.total), (5, 2)); + assert_eq!(first.summary.learnt, 1); + assert_eq!(second.summary.learnt, 1); + assert_eq!(full.summary.total, 7); + assert_eq!(full.summary.learnt, 1); + let mean = + (first.summary.learnt_percent.unwrap() + second.summary.learnt_percent.unwrap()) / 2.0; + assert!((full.summary.learnt_percent.unwrap() - mean).abs() > f64::EPSILON); + let first_keys = active_learning_keys(&library, &first_scope).unwrap(); + let second_keys = active_learning_keys(&library, &second_scope).unwrap(); + assert_eq!(first_keys.union(&second_keys).count(), 6); + assert!(first_keys.union(&second_keys).count() < first_keys.len() + second_keys.len()); +} + +#[test] +fn all_answers_keep_real_pgn_context_and_shortest_graph_depth() { + let (library, id) = single_repertoire( + "1. e4 d5 (1... Nf6 2. d4 d5 3. g3) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 *", + ); + let full_scope = scope(id.clone(), LearningSide::White); + let full = active_learning_memberships(&library, &full_scope).unwrap(); + let c4 = full + .iter() + .find(|membership| membership.key.expected_uci == "c2c4") + .unwrap(); + assert_eq!(c4.min_depth, 5); + assert_eq!(c4.path.len(), 9); + let tree = RepertoireTree::from_game( + library.repertoire(&id).unwrap().game(), + u32::MAX, + Vec::new(), + ); + assert!( + tree.node_at_path(&c4.path).is_some(), + "context must be an actual annotated PGN path" + ); + assert_eq!(c4.path.last().map(String::as_str), Some("c2c4")); + assert!( + full.iter() + .any(|membership| membership.key.expected_uci == "g2g3") + ); + + let depth = + active_learning_memberships(&library, &full_scope.clone().with_max_depth(Some(5))).unwrap(); + assert!(depth.iter().any(|membership| membership.key == c4.key)); + assert!( + !active_learning_keys(&library, &full_scope.with_max_depth(Some(4))) + .unwrap() + .contains(&c4.key) + ); + + let short_branch = scope(id, LearningSide::White).with_branch_root(strings(&["e2e4", "g8f6"])); + let short_keys = active_learning_keys(&library, &short_branch).unwrap(); + assert_eq!(short_keys.len(), 2); + assert!(short_keys.iter().any(|key| key.expected_uci == "g2g3")); + assert!(!short_keys.iter().any(|key| key.expected_uci == "c2c4")); +} + +#[test] +fn main_answer_override_validates_side_and_pgn_move_and_roundtrips() { + let (library, id) = single_repertoire("1. e4 (1. d4) e5 *"); + let start = fen4(Game::new().start().position()); + let repertoire = library.repertoire(&id).unwrap(); + let original_pgn = repertoire.pgn.clone(); + let e4 = LearningItemKey::local(start.clone(), "e2e4"); + let d4 = LearningItemKey::local(start.clone(), "d2d4"); + let selected = scope(id.clone(), LearningSide::White); + let default_keys = active_learning_keys(&library, &selected).unwrap(); + assert!(default_keys.contains(&e4)); + assert!(default_keys.contains(&d4)); + + let mut changed = repertoire.clone(); + changed + .set_main_answer_override(&start, "d2d4", LearningSide::White) + .unwrap(); + assert_eq!(changed.main_answer_override(&start), Some("d2d4")); + assert!(matches!( + changed.set_main_answer_override(&start, "e7e5", LearningSide::Black), + Err(RepertoireError::MainAnswerWrongSide { .. }) + )); + assert!(matches!( + changed.set_main_answer_override(&start, "c2c4", LearningSide::White), + Err(RepertoireError::MainAnswerMoveNotFound { .. }) + )); + assert!(matches!( + changed.set_main_answer_override("missing", "d2d4", LearningSide::White), + Err(RepertoireError::MainAnswerPositionNotFound(_)) + )); + assert_eq!(changed.main_answer_override(&start), Some("d2d4")); + assert_eq!(changed.pgn, original_pgn); + + let encoded = serde_json::to_string(&changed).unwrap(); + let restored: Repertoire = serde_json::from_str(&encoded).unwrap(); + assert_eq!(restored.main_answer_override(&start), Some("d2d4")); + let mut old_json = serde_json::to_value(&changed).unwrap(); + old_json + .as_object_mut() + .unwrap() + .remove("main_answer_overrides"); + let old: Repertoire = serde_json::from_value(old_json).unwrap(); + assert!(old.main_answer_overrides.is_empty()); + + let mut overridden_library = Library::default(); + overridden_library.repertoires.push(changed.clone()); + let overridden = active_learning_keys(&overridden_library, &selected).unwrap(); + assert!(overridden.contains(&d4)); + assert!(overridden.contains(&e4)); + assert_eq!(overridden, default_keys); + let ordered = active_learning_memberships(&overridden_library, &selected).unwrap(); + let preferred = ordered.iter().find(|item| item.key == d4).unwrap(); + let other = ordered.iter().find(|item| item.key == e4).unwrap(); + assert!(preferred.pgn_order < other.pgn_order); + assert_eq!( + changed.clear_main_answer_override(&start).as_deref(), + Some("d2d4") + ); + assert_eq!(changed.clear_main_answer_override(&start), None); + + overridden_library.repertoires[0].clear_main_answer_override(&start); + let second = add_repertoire(&mut overridden_library, "Queen pawn", "1. e4 (1. d4) e5 *"); + overridden_library + .repertoire_mut(&second) + .unwrap() + .set_main_answer_override(&start, "d2d4", LearningSide::White) + .unwrap(); + let global = active_learning_keys( + &overridden_library, + &StatsScope::new([id, second], LearningSide::White, NOW), + ) + .unwrap(); + assert!(global.contains(&e4)); + assert!(global.contains(&d4)); + assert_eq!(global.len(), 2); +} + +#[test] +fn both_training_mode_is_rejected_for_learning_statistics() { + assert_eq!( + LearningSide::try_from(TrainingMode::White), + Ok(LearningSide::White) + ); + assert_eq!( + LearningSide::try_from(TrainingMode::Black), + Ok(LearningSide::Black) + ); + assert_eq!( + LearningSide::try_from(TrainingMode::Both), + Err(LearningGraphError::BothSidesNotSupported) + ); +} + +#[test] +fn repeated_fen4_cycle_terminates_and_deduplicates_items() { + let (library, id) = single_repertoire("1. Nf3 Nf6 2. Ng1 Ng8 3. Nf3 Nf6 4. Ng1 Ng8 *"); + let memberships = + active_learning_memberships(&library, &scope(id, LearningSide::White)).unwrap(); + assert_eq!(memberships.len(), 2); + let mut depths: Vec<_> = memberships + .iter() + .map(|membership| membership.min_depth) + .collect(); + depths.sort_unstable(); + assert_eq!(depths, [1, 3]); +} + +#[test] +fn aggregate_scope_uses_one_explicit_as_of() { + let (library, id) = single_repertoire("1. e4 *"); + let mut selected = scope(id, LearningSide::White); + let key = active_learning_keys(&library, &selected) + .unwrap() + .into_iter() + .next() + .unwrap(); + let mut learning = LearningData::default(); + let item = learning.ensure_item(key); + item.introduced = true; + item.correct_streak = 1; + item.next_review_at = Some(NOW); + + selected.as_of = NOW - 1; + let before = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(before.summary.due, 0); + assert_eq!(before.summary.next_due_at, Some(NOW)); + assert_eq!(before.scope.as_of, NOW - 1); + + selected.as_of = NOW; + let due = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(due.summary.due, 1); + assert_eq!(due.summary.next_due_at, None); + assert_eq!(due.scope.as_of, NOW); +} + +#[test] +fn reset_impact_projects_n_m_and_names_without_resetting() { + let mut library = Library::default(); + let first = add_repertoire(&mut library, "First", "1. e4 e5 2. Nf3 *"); + let second = add_repertoire(&mut library, "Second", "1. e4 c5 2. c4 *"); + let selected = scope(first, LearningSide::White); + let mut learning = LearningData::default(); + for key in active_learning_keys(&library, &selected).unwrap() { + learnt(learning.ensure_item(key), NOW + DAY); + } + let before = learning.clone(); + + let impact = reset_impact(&library, &selected).unwrap(); + assert_eq!(impact.reset_count, 2); + assert_eq!(impact.shared_count, 1); + assert_eq!(impact.affected_repertoires.len(), 2); + let first_impact = impact + .affected_repertoires + .iter() + .find(|repertoire| repertoire.name == "First") + .unwrap(); + let second_impact = impact + .affected_repertoires + .iter() + .find(|repertoire| repertoire.name == "Second") + .unwrap(); + assert_eq!(first_impact.item_count, 2); + assert_eq!(second_impact.item_count, 1); + assert!( + impact + .affected_repertoires + .iter() + .any(|repertoire| repertoire.id == second) + ); + assert_eq!(learning, before); +} + +#[test] +fn disabling_one_answer_keeps_other_active_variations() { + let (mut library, id) = single_repertoire("1. e4 (1. d4) e5 *"); + let selected = scope(id.clone(), LearningSide::White); + let root = fen4(Game::new().start().position()); + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4"]), true) + .unwrap(); + assert_eq!( + active_learning_keys(&library, &selected).unwrap(), + BTreeSet::from([LearningItemKey::local(root.clone(), "d2d4")]) + ); + + library + .repertoire_mut(&id) + .unwrap() + .set_main_answer_override(&root, "d2d4", LearningSide::White) + .unwrap(); + assert_eq!( + active_learning_keys(&library, &selected).unwrap(), + BTreeSet::from([LearningItemKey::local(root, "d2d4")]) + ); +} diff --git a/crates/trainer/src/repertoire/learning.rs b/crates/trainer/src/repertoire/learning.rs new file mode 100644 index 0000000..1e63e6c --- /dev/null +++ b/crates/trainer/src/repertoire/learning.rs @@ -0,0 +1,298 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +pub const LOCAL_PROFILE_ID: &str = "local"; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct LearningItemKey { + pub user_id: String, + pub position_fen4: String, + pub expected_uci: String, +} + +impl LearningItemKey { + pub fn new( + user_id: impl Into, + position_fen4: impl Into, + expected_uci: impl Into, + ) -> Self { + Self { + user_id: user_id.into(), + position_fen4: position_fen4.into(), + expected_uci: expected_uci.into(), + } + } + + pub fn local(position_fen4: impl Into, expected_uci: impl Into) -> Self { + Self::new(LOCAL_PROFILE_ID, position_fen4, expected_uci) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WrongMoveStats { + pub count: u64, + pub last_at: i64, +} + +pub const RECENT_INDEPENDENT_OUTCOMES_LIMIT: usize = 10; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum IndependentResult { + Correct, + Wrong, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct IndependentOutcome { + pub result: IndependentResult, + pub happened_at: i64, +} + +/// Learning state for one user/FEN4/UCI key. Timestamps are UTC Unix seconds. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LearningItem { + pub key: LearningItemKey, + pub introduced: bool, + pub correct_streak: u32, + pub wrong_streak: u32, + /// Only CORRECT_INDEPENDENT events increment this counter. + pub correct_count: u64, + /// Only INCORRECT_INDEPENDENT events increment this counter. + pub wrong_count: u64, + pub last_review_at: Option, + /// SRS growth base; an independent wrong answer clears it as before. + pub last_correct_at: Option, + pub next_review_at: Option, + pub previous_interval_seconds: Option, + pub last_wrong_move_uci: Option, + pub last_wrong_at: Option, + pub wrong_move_histogram: BTreeMap, + /// Response times of independent attempts only; contextual events are excluded. + pub independent_response_times_ms: Vec, + #[serde(default)] + pub last_independent_at: Option, + #[serde(default)] + pub last_independent_correct_at: Option, + #[serde(default)] + pub last_independent_wrong_at: Option, + #[serde(default)] + pub last_independent_result: Option, + #[serde(default)] + pub recent_independent_outcomes: Vec, + #[serde(default)] + pub resistant: bool, +} + +impl LearningItem { + pub fn new(key: LearningItemKey) -> Self { + Self { + key, + introduced: false, + correct_streak: 0, + wrong_streak: 0, + correct_count: 0, + wrong_count: 0, + last_review_at: None, + last_correct_at: None, + next_review_at: None, + previous_interval_seconds: None, + last_wrong_move_uci: None, + last_wrong_at: None, + wrong_move_histogram: BTreeMap::new(), + independent_response_times_ms: Vec::new(), + last_independent_at: None, + last_independent_correct_at: None, + last_independent_wrong_at: None, + last_independent_result: None, + recent_independent_outcomes: Vec::new(), + resistant: false, + } + } + + pub fn is_unseen(&self) -> bool { + !self.introduced + } + + pub fn is_learning(&self) -> bool { + self.introduced && self.correct_streak < 3 + } + + pub fn is_learnt(&self) -> bool { + self.introduced && self.correct_streak >= 3 + } + + pub fn is_due(&self, now: i64) -> bool { + self.introduced && self.next_review_at.is_some_and(|next| next <= now) + } + + pub fn is_resistant(&self) -> bool { + self.resistant + } + + pub fn independent_attempt_count(&self) -> u64 { + self.correct_count.saturating_add(self.wrong_count) + } + + pub fn accuracy_percent(&self) -> Option { + let attempts = self.independent_attempt_count(); + (attempts > 0).then(|| 100.0 * self.correct_count as f64 / attempts as f64) + } + + pub fn response_time_median_ms(&self) -> Option { + median(&self.independent_response_times_ms) + } + + pub(crate) fn record_independent_outcome(&mut self, result: IndependentResult, now: i64) { + self.last_independent_at = Some(now); + self.last_independent_result = Some(result); + match result { + IndependentResult::Correct => self.last_independent_correct_at = Some(now), + IndependentResult::Wrong => self.last_independent_wrong_at = Some(now), + } + self.recent_independent_outcomes.push(IndependentOutcome { + result, + happened_at: now, + }); + if self.recent_independent_outcomes.len() > RECENT_INDEPENDENT_OUTCOMES_LIMIT { + let excess = self + .recent_independent_outcomes + .len() + .saturating_sub(RECENT_INDEPENDENT_OUTCOMES_LIMIT); + self.recent_independent_outcomes.drain(..excess); + } + + let wrong_count = self + .recent_independent_outcomes + .iter() + .filter(|outcome| outcome.result == IndependentResult::Wrong) + .count(); + let correct_since_error = self + .recent_independent_outcomes + .iter() + .rev() + .take_while(|outcome| outcome.result == IndependentResult::Correct) + .count(); + if correct_since_error >= 3 { + self.resistant = false; + } else if self.recent_independent_outcomes.len() >= 5 && wrong_count >= 3 { + self.resistant = true; + } + } +} + +pub fn is_resistant(item: &LearningItem) -> bool { + item.is_resistant() +} + +fn median(values: &[u64]) -> Option { + if values.is_empty() { + return None; + } + let mut sorted = values.to_vec(); + sorted.sort_unstable(); + let middle = sorted.len() / 2; + if sorted.len().is_multiple_of(2) { + Some((sorted[middle - 1] as f64 + sorted[middle] as f64) / 2.0) + } else { + Some(sorted[middle] as f64) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum TrainingEventType { + CorrectIndependent, + IncorrectIndependent, + Previewed, + ReplayAfterError, + AutoContext, + IllegalMove, +} + +impl TrainingEventType { + pub fn is_independent(self) -> bool { + matches!(self, Self::CorrectIndependent | Self::IncorrectIndependent) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TrainingAttempt { + pub user_id: String, + pub position_fen4: String, + pub client_attempt_id: String, + pub session_id: String, + pub event_type: TrainingEventType, + pub expected_uci: String, + pub actual_uci: Option, + pub response_time_ms: Option, + /// UTC Unix seconds assigned by the event-recording boundary. + pub happened_at: i64, +} + +impl TrainingAttempt { + pub fn item_key(&self) -> LearningItemKey { + LearningItemKey::new( + self.user_id.clone(), + self.position_fen4.clone(), + self.expected_uci.clone(), + ) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AttemptApplication { + Applied, + Duplicate, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LearningError { + EmptyClientAttemptId, + WrongLearningItem, + MissingActualMove, +} + +impl std::fmt::Display for LearningError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::EmptyClientAttemptId => f.write_str("client attempt id must not be empty"), + Self::WrongLearningItem => { + f.write_str("training attempt belongs to a different learning item") + } + Self::MissingActualMove => { + f.write_str("an independent wrong attempt must contain the actual UCI move") + } + } + } +} + +impl std::error::Error for LearningError {} + +/// In-memory learning state and its idempotency journal; persistence is a separate layer. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct LearningData { + pub items: Vec, + pub attempts: Vec, + #[serde(flatten)] + pub extensions: BTreeMap, +} + +impl LearningData { + pub fn item(&self, key: &LearningItemKey) -> Option<&LearningItem> { + self.items.iter().find(|item| &item.key == key) + } + + pub fn ensure_item(&mut self, key: LearningItemKey) -> &mut LearningItem { + let index = match self.items.iter().position(|item| item.key == key) { + Some(index) => index, + None => { + self.items.push(LearningItem::new(key)); + self.items.len() - 1 + } + }; + &mut self.items[index] + } +} diff --git a/crates/trainer/src/repertoire/learning_analytics.rs b/crates/trainer/src/repertoire/learning_analytics.rs new file mode 100644 index 0000000..b919792 --- /dev/null +++ b/crates/trainer/src/repertoire/learning_analytics.rs @@ -0,0 +1,348 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::aggregate::is_uncertain; +use super::learning::{ + IndependentResult, LearningData, LearningItem, LearningItemKey, WrongMoveStats, +}; +use super::learning_graph::{ + LearningGraphError, LearningItemMembership, StatsScope, active_learning_memberships, + aggregate_scope, +}; +use super::model::Library; +use super::srs::SrsSettings; + +pub const SECONDS_PER_DAY: i64 = 24 * 60 * 60; +pub const SCHEDULED_WEEK_SECONDS: i64 = 7 * SECONDS_PER_DAY; +pub const SCHEDULED_MONTH_SECONDS: i64 = 30 * SECONDS_PER_DAY; +pub const SCHEDULED_YEAR_SECONDS: i64 = 365 * SECONDS_PER_DAY; + +/// Fixed UTC offset used for local calendar dates. The caller resolves named zones and DST. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct LocalDatePolicy { + pub utc_offset_seconds: i32, +} + +impl LocalDatePolicy { + pub const UTC: Self = Self { + utc_offset_seconds: 0, + }; + + pub const fn fixed(utc_offset_seconds: i32) -> Self { + Self { utc_offset_seconds } + } + + pub fn date(self, as_of: i64) -> String { + let local = i128::from(as_of) + i128::from(self.utc_offset_seconds); + civil_date(local.div_euclid(i128::from(SECONDS_PER_DAY))) + } + + /// Exclusive UTC boundary of the current local day: the next local midnight. + pub fn end_of_local_day_exclusive(self, as_of: i64) -> i64 { + let offset = i128::from(self.utc_offset_seconds); + let local = i128::from(as_of) + offset; + let next_midnight = + (local.div_euclid(i128::from(SECONDS_PER_DAY)) + 1) * i128::from(SECONDS_PER_DAY); + clamp_i64(next_midnight - offset) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ScheduledBuckets { + pub overdue: usize, + pub today: usize, + pub week: usize, + pub month: usize, + pub year: usize, + pub later: usize, +} + +impl ScheduledBuckets { + pub fn introduced(self) -> usize { + self.overdue + .saturating_add(self.today) + .saturating_add(self.week) + .saturating_add(self.month) + .saturating_add(self.year) + .saturating_add(self.later) + } +} + +/// Today ends at the explicit local midnight; all other ranges use fixed durations. +/// An introduced item without a schedule is overdue so the buckets remain a partition. +pub fn scheduled_buckets<'a>( + items: impl IntoIterator, + now: i64, + local_date: LocalDatePolicy, +) -> ScheduledBuckets { + let end_today = local_date.end_of_local_day_exclusive(now); + let end_week = now.saturating_add(SCHEDULED_WEEK_SECONDS); + let end_month = now.saturating_add(SCHEDULED_MONTH_SECONDS); + let end_year = now.saturating_add(SCHEDULED_YEAR_SECONDS); + let mut buckets = ScheduledBuckets::default(); + for item in unique_items(items).into_values() { + if item.is_unseen() { + continue; + } + let bucket = match item.next_review_at { + None => &mut buckets.overdue, + Some(next) if next <= now => &mut buckets.overdue, + Some(next) if next < end_today => &mut buckets.today, + Some(next) if next < end_week => &mut buckets.week, + Some(next) if next < end_month => &mut buckets.month, + Some(next) if next < end_year => &mut buckets.year, + Some(_) => &mut buckets.later, + }; + *bucket = bucket.saturating_add(1); + } + buckets +} + +pub type CorrectStreakHistogram = BTreeMap; +pub type WrongStreakHistogram = BTreeMap; +pub type AttemptsHistogram = BTreeMap; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SequenceHistograms { + pub correct_streak: CorrectStreakHistogram, + pub wrong_streak: WrongStreakHistogram, + pub attempts: AttemptsHistogram, +} + +pub fn sequence_histograms<'a>( + items: impl IntoIterator, +) -> SequenceHistograms { + let mut histograms = SequenceHistograms::default(); + for item in unique_items(items).into_values() { + increment(&mut histograms.correct_streak, item.correct_streak); + increment(&mut histograms.wrong_streak, item.wrong_streak); + increment(&mut histograms.attempts, item.independent_attempt_count()); + } + histograms +} + +pub fn correct_streak_histogram<'a>( + items: impl IntoIterator, +) -> CorrectStreakHistogram { + sequence_histograms(items).correct_streak +} + +pub fn wrong_streak_histogram<'a>( + items: impl IntoIterator, +) -> WrongStreakHistogram { + sequence_histograms(items).wrong_streak +} + +pub fn attempts_histogram<'a>( + items: impl IntoIterator, +) -> AttemptsHistogram { + sequence_histograms(items).attempts +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum MoveLearningStatus { + Unseen, + Learning, + LearntFresh, + Uncertain, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MoveLearningAnalytics { + pub key: LearningItemKey, + pub status: MoveLearningStatus, + pub resistant: bool, + pub accuracy_percent: Option, + pub correct_count: u64, + pub wrong_count: u64, + pub independent_attempts: u64, + pub correct_streak: u32, + pub wrong_streak: u32, + pub last_review_at: Option, + pub last_independent_at: Option, + pub last_independent_result: Option, + pub last_independent_correct_at: Option, + pub last_independent_wrong_at: Option, + pub next_review_at: Option, + pub review_in_seconds: Option, + pub overdue_seconds: Option, + pub uncertain_grace_seconds: Option, + pub wrong_move_histogram: BTreeMap, + pub response_time_median_ms: Option, + pub memberships: Vec, +} + +pub fn move_learning_analytics( + item: &LearningItem, + now: i64, + settings: &SrsSettings, +) -> MoveLearningAnalytics { + let uncertain = is_uncertain(item, now, settings); + let status = if item.is_unseen() { + MoveLearningStatus::Unseen + } else if !item.is_learnt() { + MoveLearningStatus::Learning + } else if uncertain { + MoveLearningStatus::Uncertain + } else { + MoveLearningStatus::LearntFresh + }; + let uncertain_grace_seconds = (item.is_learnt() && item.next_review_at.is_some()) + .then(|| { + item.previous_interval_seconds.unwrap_or(0).max(0) + / i64::from(settings.uncertain_interval_divisor.max(1)) + }) + .map(|interval_grace| { + settings + .uncertain_min_grace_seconds + .max(0) + .max(interval_grace) + }); + MoveLearningAnalytics { + key: item.key.clone(), + status, + resistant: item.is_resistant(), + accuracy_percent: item.accuracy_percent(), + correct_count: item.correct_count, + wrong_count: item.wrong_count, + independent_attempts: item.independent_attempt_count(), + correct_streak: item.correct_streak, + wrong_streak: item.wrong_streak, + last_review_at: item.last_review_at, + last_independent_at: item.last_independent_at, + last_independent_result: item.last_independent_result, + last_independent_correct_at: item.last_independent_correct_at, + last_independent_wrong_at: item.last_independent_wrong_at, + next_review_at: item.next_review_at, + review_in_seconds: item + .next_review_at + .filter(|next| *next > now) + .map(|next| next.saturating_sub(now)), + overdue_seconds: item + .next_review_at + .map(|next| now.saturating_sub(next).max(0)), + uncertain_grace_seconds, + wrong_move_histogram: item.wrong_move_histogram.clone(), + response_time_median_ms: item.response_time_median_ms(), + memberships: Vec::new(), + } +} + +pub fn scoped_move_learning_analytics( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + settings: &SrsSettings, +) -> Result, LearningGraphError> { + let scoped = aggregate_scope(library, learning, scope, settings)?; + let mut memberships_by_key: BTreeMap> = + BTreeMap::new(); + for membership in active_learning_memberships(library, scope)? { + memberships_by_key + .entry(membership.key.clone()) + .or_default() + .push(membership); + } + Ok(scoped + .items + .iter() + .map(|item| { + let mut analytics = move_learning_analytics(item, scope.as_of, settings); + analytics.memberships = memberships_by_key.remove(&item.key).unwrap_or_default(); + analytics + }) + .collect()) +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LearningSnapshot { + pub date: String, + pub scope: StatsScope, + pub as_of: i64, + pub timezone: LocalDatePolicy, + pub total: usize, + pub unseen: usize, + pub learning: usize, + pub learnt: usize, + pub uncertain: usize, + pub due: usize, +} + +impl LearningSnapshot { + pub fn capture( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + settings: &SrsSettings, + timezone: LocalDatePolicy, + ) -> Result { + let scoped = aggregate_scope(library, learning, scope, settings)?; + Ok(Self { + date: timezone.date(scope.as_of), + scope: scope.clone(), + as_of: scope.as_of, + timezone, + total: scoped.summary.total, + unseen: scoped.summary.unseen, + learning: scoped.summary.learning, + learnt: scoped.summary.learnt, + uncertain: scoped.summary.uncertain, + due: scoped.summary.due, + }) + } +} + +pub(crate) fn same_snapshot_slot(left: &LearningSnapshot, right: &LearningSnapshot) -> bool { + if left.date != right.date { + return false; + } + let mut left_scope = left.scope.clone(); + let mut right_scope = right.scope.clone(); + left_scope.as_of = 0; + right_scope.as_of = 0; + left_scope == right_scope +} + +fn unique_items<'a>( + items: impl IntoIterator, +) -> BTreeMap<&'a LearningItemKey, &'a LearningItem> { + let mut unique = BTreeMap::new(); + for item in items { + unique.entry(&item.key).or_insert(item); + } + unique +} + +fn increment(histogram: &mut BTreeMap, key: K) { + let count = histogram.entry(key).or_default(); + *count = count.saturating_add(1); +} + +fn clamp_i64(value: i128) -> i64 { + if value < i128::from(i64::MIN) { + i64::MIN + } else if value > i128::from(i64::MAX) { + i64::MAX + } else { + value as i64 + } +} + +fn civil_date(days_since_unix_epoch: i128) -> String { + let shifted = days_since_unix_epoch + 719_468; + let era = shifted.div_euclid(146_097); + let day_of_era = shifted - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let mut year = year_of_era + era * 400; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_prime = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_prime + 2) / 5 + 1; + let month = month_prime + if month_prime < 10 { 3 } else { -9 }; + if month <= 2 { + year += 1; + } + format!("{year:04}-{month:02}-{day:02}") +} diff --git a/crates/trainer/src/repertoire/learning_context.rs b/crates/trainer/src/repertoire/learning_context.rs new file mode 100644 index 0000000..a82fc9d --- /dev/null +++ b/crates/trainer/src/repertoire/learning_context.rs @@ -0,0 +1,131 @@ +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +use crate::repertoire::learning::{LearningData, LearningItem, LearningItemKey}; + +const SECONDS_PER_DAY: i64 = 24 * 60 * 60; +const MIN_SPEED_FACTOR: f64 = 0.25; +const MAX_SPEED_FACTOR: f64 = 4.0; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct LearningContextPolicy { + pub reinforce_minimum_correct: u32, + pub reinforce_minimum_days: Option, + pub dont_show_start_moves_threshold: u32, + pub use_fixed_piece_speed: bool, + pub move_speed_adjustment: f64, + pub consider_leadup_moves: bool, +} + +impl Default for LearningContextPolicy { + fn default() -> Self { + Self { + reinforce_minimum_correct: 3, + reinforce_minimum_days: None, + dont_show_start_moves_threshold: 100, + use_fixed_piece_speed: true, + move_speed_adjustment: 1.0, + consider_leadup_moves: false, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LearningContextAction { + Automatic, + Independent, +} + +pub(crate) struct LearningContextMove { + pub key: LearningItemKey, + pub own_move: bool, + pub least_recent_target: bool, +} + +pub(crate) struct LearningContextPlan { + pub actions: Vec, + pub skip_prefix: usize, +} + +pub(crate) fn plan_context( + moves: &[LearningContextMove], + learning: &LearningData, + policy: &LearningContextPolicy, + completed_keys: &BTreeSet, + least_recent: bool, + now: i64, +) -> LearningContextPlan { + let actions = moves + .iter() + .map(|context| { + if !context.own_move || completed_keys.contains(&context.key) { + return LearningContextAction::Automatic; + } + let item = learning.item(&context.key); + let reinforce = + policy.consider_leadup_moves && requires_reinforcement(item, policy, now); + if (least_recent && context.least_recent_target) || reinforce { + LearningContextAction::Independent + } else { + LearningContextAction::Automatic + } + }) + .collect::>(); + let mut skip_prefix = 0; + let mut known_own_move = false; + let mut stopped = false; + for (index, (context, action)) in moves.iter().zip(&actions).enumerate() { + if *action == LearningContextAction::Independent + || (context.own_move && !very_well_known(learning.item(&context.key), policy)) + { + skip_prefix = if known_own_move { index } else { 0 }; + stopped = true; + break; + } + known_own_move |= context.own_move; + } + if known_own_move && !stopped { + skip_prefix = moves.len(); + } + LearningContextPlan { + actions, + skip_prefix, + } +} + +pub(crate) fn speed_factor(policy: &LearningContextPolicy, item: Option<&LearningItem>) -> f64 { + if policy.use_fixed_piece_speed { + return 1.0; + } + let adjustment = if policy.move_speed_adjustment.is_finite() { + policy.move_speed_adjustment + } else { + 1.0 + }; + let scale = u32::max(policy.reinforce_minimum_correct, 1); + let knowledge = + f64::from(item.map_or(0, |item| item.correct_streak).min(scale)) / f64::from(scale); + (adjustment * (1.0 + knowledge)).clamp(MIN_SPEED_FACTOR, MAX_SPEED_FACTOR) +} + +fn requires_reinforcement( + item: Option<&LearningItem>, + policy: &LearningContextPolicy, + now: i64, +) -> bool { + let weak = item.map_or(0, |item| item.correct_streak) < policy.reinforce_minimum_correct; + let due_soon = policy.reinforce_minimum_days.is_some_and(|days| { + let horizon = now.saturating_add(i64::from(days).saturating_mul(SECONDS_PER_DAY)); + item.is_some_and(|item| { + item.introduced && item.next_review_at.is_some_and(|next| next <= horizon) + }) + }); + weak || due_soon +} + +fn very_well_known(item: Option<&LearningItem>, policy: &LearningContextPolicy) -> bool { + policy.dont_show_start_moves_threshold > 0 + && item.is_some_and(|item| item.correct_streak >= policy.dont_show_start_moves_threshold) +} diff --git a/crates/trainer/src/repertoire/learning_graph.rs b/crates/trainer/src/repertoire/learning_graph.rs new file mode 100644 index 0000000..ed22ad2 --- /dev/null +++ b/crates/trainer/src/repertoire/learning_graph.rs @@ -0,0 +1,629 @@ +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::fmt; + +use chess_core::MoveKind; +use chess_core::shakmaty::{CastlingMode, Position}; +use serde::{Deserialize, Serialize}; + +use super::aggregate::{LearningAggregate, aggregate}; +use super::learning::{LearningData, LearningItem, LearningItemKey}; +use super::learning_modes::LearningPriority; +use super::model::{LearningSide, Library, Repertoire, RepertoireId}; +use super::srs::SrsSettings; +use super::stats::TrainingMode; +use super::tree::RepertoireTree; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct StatsScope { + pub repertoire_ids: BTreeSet, + pub side: LearningSide, + pub max_depth: Option, + #[serde(default = "default_only_active")] + pub only_active: bool, + pub branch_root: Option>, + pub as_of: i64, + #[serde(default)] + pub learning_priority: LearningPriority, +} + +impl StatsScope { + pub fn new( + repertoire_ids: impl IntoIterator, + side: LearningSide, + as_of: i64, + ) -> Self { + Self { + repertoire_ids: repertoire_ids.into_iter().collect(), + side, + max_depth: None, + only_active: true, + branch_root: None, + as_of, + learning_priority: LearningPriority::default(), + } + } + + pub fn for_repertoire(id: RepertoireId, side: LearningSide, as_of: i64) -> Self { + Self::new([id], side, as_of) + } + + pub fn with_max_depth(mut self, max_depth: Option) -> Self { + self.max_depth = max_depth; + self + } + + pub fn with_branch_root(mut self, branch_root: Vec) -> Self { + self.branch_root = Some(branch_root); + self + } + + pub fn with_learning_priority(mut self, learning_priority: LearningPriority) -> Self { + self.learning_priority = learning_priority; + self + } +} + +fn default_only_active() -> bool { + true +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct LearningItemMembership { + pub repertoire_id: RepertoireId, + pub key: LearningItemKey, + pub min_depth: u32, + pub path: Vec, + #[serde(default)] + pub pgn_order: usize, + #[serde(default)] + pub variation_depth: u32, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ScopedLearningAggregate { + pub scope: StatsScope, + pub items: Vec, + pub summary: LearningAggregate, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResetRepertoireImpact { + pub id: RepertoireId, + pub name: String, + pub item_count: usize, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResetImpactProjection { + pub reset_count: usize, + pub shared_count: usize, + pub affected_repertoires: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LearningGraphError { + BothSidesNotSupported, + RepertoireNotFound(RepertoireId), + BranchRootNotFound { + repertoire_id: RepertoireId, + branch_root: Vec, + }, + DepthOverflow(RepertoireId), + TrainingPathGeneration { + repertoire_id: RepertoireId, + message: String, + }, +} + +impl fmt::Display for LearningGraphError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BothSidesNotSupported => { + f.write_str("learning statistics require exactly one side, not Both") + } + Self::RepertoireNotFound(id) => write!(f, "repertoire not found: {id}"), + Self::BranchRootNotFound { + repertoire_id, + branch_root, + } => write!( + f, + "branch root {} is not present in repertoire {repertoire_id}", + branch_root.join(" ") + ), + Self::DepthOverflow(id) => { + write!( + f, + "learning depth exceeds the supported limit in repertoire {id}" + ) + } + Self::TrainingPathGeneration { + repertoire_id, + message, + } => write!( + f, + "could not generate training paths in repertoire {repertoire_id}: {message}" + ), + } + } +} + +impl std::error::Error for LearningGraphError {} + +impl TryFrom for LearningSide { + type Error = LearningGraphError; + + fn try_from(mode: TrainingMode) -> Result { + match mode { + TrainingMode::White => Ok(Self::White), + TrainingMode::Black => Ok(Self::Black), + TrainingMode::Both => Err(LearningGraphError::BothSidesNotSupported), + } + } +} + +#[derive(Clone, Debug)] +struct GraphEdge { + /// Actual PGN occurrence; graph shortcuts must not invent a context path. + source_path: Vec, + uci: String, + to: String, + parent_order: usize, + child_order: usize, + pgn_order: usize, +} + +#[derive(Clone, Debug)] +struct PositionEntry { + side: LearningSide, + edges: Vec, +} + +pub fn active_learning_memberships( + library: &Library, + scope: &StatsScope, +) -> Result, LearningGraphError> { + let mut memberships = Vec::new(); + for id in &scope.repertoire_ids { + let repertoire = library + .repertoire(id) + .ok_or_else(|| LearningGraphError::RepertoireNotFound(id.clone()))?; + memberships.extend(repertoire_memberships(repertoire, scope)?); + } + memberships.sort_by(|left, right| { + (&left.repertoire_id, &left.key).cmp(&(&right.repertoire_id, &right.key)) + }); + Ok(memberships) +} + +pub fn active_learning_keys( + library: &Library, + scope: &StatsScope, +) -> Result, LearningGraphError> { + Ok(active_learning_memberships(library, scope)? + .into_iter() + .map(|membership| membership.key) + .collect()) +} + +pub fn aggregate_scope( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + settings: &SrsSettings, +) -> Result { + let keys = active_learning_keys(library, scope)?; + let items: Vec<_> = keys + .into_iter() + .map(|key| { + learning + .item(&key) + .cloned() + .unwrap_or_else(|| LearningItem::new(key)) + }) + .collect(); + let summary = aggregate(items.iter(), scope.as_of, settings); + Ok(ScopedLearningAggregate { + scope: scope.clone(), + items, + summary, + }) +} + +pub fn reset_impact( + library: &Library, + scope: &StatsScope, +) -> Result { + let selected_memberships = active_learning_memberships(library, scope)?; + let selected_keys: BTreeSet<_> = selected_memberships + .iter() + .map(|membership| membership.key.clone()) + .collect(); + let mut selected_by_repertoire: BTreeMap> = + BTreeMap::new(); + for membership in selected_memberships { + selected_by_repertoire + .entry(membership.repertoire_id) + .or_default() + .insert(membership.key); + } + + let mut shared_keys = BTreeSet::new(); + let mut affected_repertoires = Vec::new(); + for repertoire in &library.repertoires { + let selected = scope.repertoire_ids.contains(&repertoire.id); + let impacted_keys = if selected { + selected_by_repertoire + .remove(&repertoire.id) + .unwrap_or_default() + } else { + let other_scope = + StatsScope::for_repertoire(repertoire.id.clone(), scope.side, scope.as_of); + let other_keys = active_learning_keys(library, &other_scope)?; + shared_keys.extend( + other_keys + .intersection(&selected_keys) + .cloned() + .collect::>(), + ); + other_keys + .intersection(&selected_keys) + .cloned() + .collect::>() + }; + if !impacted_keys.is_empty() { + affected_repertoires.push(ResetRepertoireImpact { + id: repertoire.id.clone(), + name: repertoire.name.clone(), + item_count: impacted_keys.len(), + }); + } + } + + Ok(ResetImpactProjection { + reset_count: selected_keys.len(), + shared_count: shared_keys.len(), + affected_repertoires, + }) +} + +// Preferred answers order the traversal, but never remove another PGN answer. +fn preferred_children( + repertoire: &Repertoire, + tree: &RepertoireTree, + node: chess_core::NodeId, +) -> Vec { + let mut children = tree.game().children(node).to_vec(); + if let Some(preferred) = tree + .position_key(node) + .and_then(|position| repertoire.main_answer_override(position)) + { + children.sort_by_key(|child| { + tree.game() + .game_move(*child) + .and_then(|mv| mv.uci()) + .as_deref() + != Some(preferred) + }); + } + children +} + +fn preferred_node_order(repertoire: &Repertoire, tree: &RepertoireTree) -> Vec { + let mut nodes = Vec::new(); + let mut stack = vec![tree.root()]; + while let Some(node) = stack.pop() { + nodes.push(node); + stack.extend(preferred_children(repertoire, tree, node).into_iter().rev()); + } + nodes +} + +fn repertoire_memberships( + repertoire: &Repertoire, + scope: &StatsScope, +) -> Result, LearningGraphError> { + let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); + let game = tree.game(); + let branch_root = scope.branch_root.as_deref(); + let path_allowed = |path: &[String]| { + branch_root.is_none_or(|root| path.starts_with(root)) + && (!scope.only_active || !repertoire.is_prefix_disabled(path)) + }; + + let attached_nodes = preferred_node_order(repertoire, &tree); + let pgn_orders: BTreeMap<_, _> = attached_nodes + .iter() + .enumerate() + .map(|(order, node)| (*node, order)) + .collect(); + let mut positions: BTreeMap = BTreeMap::new(); + let mut branch_root_found = branch_root.is_none(); + let mut start = None; + for (parent_order, node) in attached_nodes.into_iter().enumerate() { + let Some(path) = tree.path(node) else { + continue; + }; + if branch_root.is_some_and(|root| path == root) { + branch_root_found = true; + if path_allowed(path) { + start = tree.position_key(node).map(str::to_owned); + } + } + if !path_allowed(path) { + continue; + } + let Some(position_fen4) = tree.position_key(node).map(str::to_owned) else { + continue; + }; + let Some(position) = tree.position(node) else { + continue; + }; + let entry = positions + .entry(position_fen4.clone()) + .or_insert_with(|| PositionEntry { + side: LearningSide::from(position.turn()), + edges: Vec::new(), + }); + for (child_order, child) in preferred_children(repertoire, &tree, node) + .iter() + .enumerate() + { + if !tree.path(*child).is_some_and(path_allowed) { + continue; + } + let Some(game_move) = game.game_move(*child) else { + continue; + }; + let MoveKind::Normal(mv) = game_move.kind else { + continue; + }; + let Some(to) = tree.position_key(*child).map(str::to_owned) else { + continue; + }; + entry.edges.push(GraphEdge { + source_path: tree.path(*child).expect("checked PGN path").to_vec(), + uci: mv.to_uci(CastlingMode::Standard).to_string(), + to, + parent_order, + child_order, + pgn_order: pgn_orders.get(child).copied().unwrap_or(usize::MAX), + }); + } + } + + if !branch_root_found { + return Err(LearningGraphError::BranchRootNotFound { + repertoire_id: repertoire.id.clone(), + branch_root: branch_root.unwrap_or_default().to_vec(), + }); + } + if branch_root.is_none() { + start = tree.position_key(tree.root()).map(str::to_owned); + } + let Some(start) = start else { + return Ok(Vec::new()); + }; + + for entry in positions.values_mut() { + entry.edges.sort_by(|left, right| { + (left.source_path.len(), left.parent_order, left.child_order) + .cmp(&( + right.source_path.len(), + right.parent_order, + right.child_order, + )) + .then_with(|| left.uci.cmp(&right.uci)) + .then_with(|| left.to.cmp(&right.to)) + }); + let mut seen = BTreeSet::new(); + entry.edges.retain(|edge| seen.insert(edge.uci.clone())); + } + + let base_depth = u32::try_from(branch_root.unwrap_or_default().len()) + .map_err(|_| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; + let mut queue = VecDeque::from([( + start.clone(), + base_depth, + branch_root.unwrap_or_default().to_vec(), + 0_u32, + )]); + let mut visited = BTreeSet::from([start]); + let mut result: BTreeMap = BTreeMap::new(); + + while let Some((position_fen4, depth, path, variation_depth)) = queue.pop_front() { + if scope.max_depth.is_some_and(|maximum| depth >= maximum) { + continue; + } + let Some(entry) = positions.get(&position_fen4) else { + continue; + }; + let own_position = entry.side == scope.side; + let edges = &entry.edges; + + for edge in edges { + let next_depth = depth + .checked_add(1) + .ok_or_else(|| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; + let next_variation_depth = variation_depth + .checked_add(u32::from(edge.child_order > 0)) + .ok_or_else(|| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; + let mut next_path = path.clone(); + next_path.push(edge.uci.clone()); + if own_position { + let key = LearningItemKey::local(position_fen4.clone(), edge.uci.clone()); + result + .entry(key.clone()) + .or_insert_with(|| LearningItemMembership { + repertoire_id: repertoire.id.clone(), + key, + min_depth: next_depth, + path: edge.source_path.clone(), + pgn_order: edge.pgn_order, + variation_depth: next_variation_depth, + }); + } + if visited.insert(edge.to.clone()) { + queue.push_back((edge.to.clone(), next_depth, next_path, next_variation_depth)); + } + } + } + + Ok(result.into_values().collect()) +} + +pub(crate) fn all_path_learning_memberships( + library: &Library, + scope: &StatsScope, +) -> Result, LearningGraphError> { + let mut memberships = Vec::new(); + for id in &scope.repertoire_ids { + let repertoire = library + .repertoire(id) + .ok_or_else(|| LearningGraphError::RepertoireNotFound(id.clone()))?; + memberships.extend(all_path_repertoire_memberships(repertoire, scope)?); + } + memberships.sort_by(|left, right| { + (&left.repertoire_id, &left.path, &left.key).cmp(&( + &right.repertoire_id, + &right.path, + &right.key, + )) + }); + Ok(memberships) +} + +struct AllPathContext<'a> { + repertoire: &'a Repertoire, + scope: &'a StatsScope, + tree: &'a RepertoireTree, + pgn_orders: &'a BTreeMap, +} + +fn all_path_repertoire_memberships( + repertoire: &Repertoire, + scope: &StatsScope, +) -> Result, LearningGraphError> { + let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); + let game = tree.game(); + let branch_root = scope.branch_root.as_deref(); + let path_allowed = |path: &[String]| { + branch_root.is_none_or(|root| path.starts_with(root)) + && (!scope.only_active || !repertoire.is_prefix_disabled(path)) + }; + let start = if let Some(root) = branch_root { + let Some(node) = game + .attached_nodes() + .into_iter() + .find(|node| tree.path(*node).is_some_and(|path| path == root)) + else { + return Err(LearningGraphError::BranchRootNotFound { + repertoire_id: repertoire.id.clone(), + branch_root: root.to_vec(), + }); + }; + if !tree.path(node).is_some_and(path_allowed) { + return Ok(Vec::new()); + } + node + } else { + tree.root() + }; + let base_depth = u32::try_from(branch_root.unwrap_or_default().len()) + .map_err(|_| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; + let attached_nodes = preferred_node_order(repertoire, &tree); + let pgn_orders: BTreeMap<_, _> = attached_nodes + .iter() + .enumerate() + .map(|(order, node)| (*node, order)) + .collect(); + let context = AllPathContext { + repertoire, + scope, + tree: &tree, + pgn_orders: &pgn_orders, + }; + let mut memberships = Vec::new(); + let mut path = branch_root.unwrap_or_default().to_vec(); + visit_all_path_memberships(&context, start, base_depth, 0, &mut path, &mut memberships)?; + Ok(memberships) +} + +fn visit_all_path_memberships( + context: &AllPathContext<'_>, + node: chess_core::NodeId, + depth: u32, + variation_depth: u32, + path: &mut Vec, + memberships: &mut Vec, +) -> Result<(), LearningGraphError> { + if context + .scope + .max_depth + .is_some_and(|maximum| depth >= maximum) + { + return Ok(()); + } + let Some(position_fen4) = context.tree.position_key(node) else { + return Ok(()); + }; + let Some(position) = context.tree.position(node) else { + return Ok(()); + }; + let own_position = LearningSide::from(position.turn()) == context.scope.side; + let game = context.tree.game(); + let mut seen_uci = BTreeSet::new(); + for (child_order, child) in preferred_children(context.repertoire, context.tree, node) + .iter() + .enumerate() + { + if !context.tree.path(*child).is_some_and(|child_path| { + context + .scope + .branch_root + .as_deref() + .is_none_or(|root| child_path.starts_with(root)) + && (!context.scope.only_active + || !context.repertoire.is_prefix_disabled(child_path)) + }) { + continue; + } + let Some(game_move) = game.game_move(*child) else { + continue; + }; + let MoveKind::Normal(mv) = game_move.kind else { + continue; + }; + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + if !seen_uci.insert(uci.clone()) { + continue; + } + let next_depth = depth + .checked_add(1) + .ok_or_else(|| LearningGraphError::DepthOverflow(context.repertoire.id.clone()))?; + let next_variation_depth = variation_depth + .checked_add(u32::from(child_order > 0)) + .ok_or_else(|| LearningGraphError::DepthOverflow(context.repertoire.id.clone()))?; + path.push(uci.clone()); + if own_position { + memberships.push(LearningItemMembership { + repertoire_id: context.repertoire.id.clone(), + key: LearningItemKey::local(position_fen4, uci), + min_depth: next_depth, + path: path.clone(), + pgn_order: context.pgn_orders.get(child).copied().unwrap_or(usize::MAX), + variation_depth: next_variation_depth, + }); + } + let result = visit_all_path_memberships( + context, + *child, + next_depth, + next_variation_depth, + path, + memberships, + ); + path.pop(); + result?; + } + Ok(()) +} diff --git a/crates/trainer/src/repertoire/learning_modes.rs b/crates/trainer/src/repertoire/learning_modes.rs new file mode 100644 index 0000000..a0c5d83 --- /dev/null +++ b/crates/trainer/src/repertoire/learning_modes.rs @@ -0,0 +1,87 @@ +use std::cmp::Ordering; +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::learning::{LearningData, LearningItemKey}; +use super::learning_graph::LearningItemMembership; + +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, +)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum LearningPriority { + #[default] + DepthFirst, + BreadthOverDepth, + MainLinesFirst, + CommonPositionsFirst, +} + +pub(crate) fn sort_by_priority( + memberships: &mut [LearningItemMembership], + priority: LearningPriority, +) { + memberships.sort_by(|left, right| compare_priority(left, right, priority)); +} + +pub(crate) fn sort_least_recent( + memberships: &mut [LearningItemMembership], + learning: &LearningData, + priority: LearningPriority, +) { + let states: BTreeMap)> = memberships + .iter() + .map(|membership| { + let key = membership.key.clone(); + let item = learning.item(&key); + let introduced = item.is_some_and(|item| item.introduced); + let last_attempt = learning + .attempts + .iter() + .filter(|attempt| attempt.item_key() == key) + .map(|attempt| attempt.happened_at) + .max(); + let last_seen = item + .and_then(|item| item.last_review_at) + .max(last_attempt) + .or(last_attempt); + (key, (introduced, last_seen)) + }) + .collect(); + + memberships.sort_by(|left, right| { + let (left_introduced, left_last_seen) = + states.get(&left.key).copied().unwrap_or((false, None)); + let (right_introduced, right_last_seen) = + states.get(&right.key).copied().unwrap_or((false, None)); + left_introduced + .cmp(&right_introduced) + .then_with(|| left_last_seen.cmp(&right_last_seen)) + .then_with(|| compare_priority(left, right, priority)) + }); +} + +fn compare_priority( + left: &LearningItemMembership, + right: &LearningItemMembership, + priority: LearningPriority, +) -> Ordering { + left.repertoire_id + .cmp(&right.repertoire_id) + .then_with(|| match priority { + LearningPriority::DepthFirst => left.pgn_order.cmp(&right.pgn_order), + // No popularity or engine data is stored: common-position priority is + // explicitly the deterministic breadth-first fallback. + LearningPriority::BreadthOverDepth | LearningPriority::CommonPositionsFirst => left + .min_depth + .cmp(&right.min_depth) + .then_with(|| left.pgn_order.cmp(&right.pgn_order)), + LearningPriority::MainLinesFirst => left + .variation_depth + .cmp(&right.variation_depth) + .then_with(|| left.pgn_order.cmp(&right.pgn_order)), + }) + .then_with(|| left.path.cmp(&right.path)) + .then_with(|| left.key.cmp(&right.key)) +} diff --git a/crates/trainer/src/repertoire/learning_session.rs b/crates/trainer/src/repertoire/learning_session.rs new file mode 100644 index 0000000..c93ac8a --- /dev/null +++ b/crates/trainer/src/repertoire/learning_session.rs @@ -0,0 +1,1533 @@ +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::{Arc, Mutex}, +}; + +use chess_core::shakmaty::fen::Fen; +use chess_core::shakmaty::uci::UciMove; +use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position}; +use serde::{Deserialize, Serialize}; + +use super::learning::{LearningData, LearningItemKey, TrainingAttempt, TrainingEventType}; +use super::learning_graph::{ + LearningGraphError, LearningItemMembership, StatsScope, active_learning_memberships, +}; +use super::learning_modes::{LearningPriority, sort_by_priority, sort_least_recent}; +use super::model::{LearningSide, Library, RepertoireId}; +use super::scope::TrainingScopeKey; +use super::srs::SrsSettings; +use super::stats::{QueueMode, TrainingMode}; +use super::store::LearningSession; +use super::tree::fen4; + +#[path = "learning_context.rs"] +mod learning_context; +pub use learning_context::LearningContextPolicy; +use learning_context::{ + LearningContextAction, LearningContextMove, LearningContextPlan, plan_context, speed_factor, +}; + +#[cfg(test)] +#[path = "context_tests.rs"] +mod context_tests; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum LearningSessionPhase { + AwaitingIndependent, + AwaitingContextIndependent, + AwaitingReplayAfterError, + PreviewedReplay, + AdvancingContext, + Finished, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LearningSessionTarget { + pub key: LearningItemKey, + pub repertoire_id: RepertoireId, + pub min_depth: u32, + /// Includes the expected target move as its last element. + pub path: Vec, + #[serde(default)] + pub pgn_order: usize, + #[serde(default)] + pub variation_depth: u32, +} + +impl From for LearningSessionTarget { + fn from(membership: LearningItemMembership) -> Self { + Self { + key: membership.key, + repertoire_id: membership.repertoire_id, + min_depth: membership.min_depth, + path: membership.path, + pgn_order: membership.pgn_order, + variation_depth: membership.variation_depth, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LearningSessionSnapshot { + pub session: LearningSession, + #[serde(default)] + pub context_policy: LearningContextPolicy, + pub stats_scope: StatsScope, + pub queue: Vec, + pub current_index: usize, + pub phase: LearningSessionPhase, + /// Number of already presented or deliberately omitted moves in the current target path. + pub context_index: usize, + pub completed_keys: BTreeSet, + #[serde(default)] + pub cycle: u64, + /// Per-session optimistic revision, independent from the store revision. + #[serde(default)] + pub revision: u64, + /// A move answered after a mistake or a hint goes to the end of this session's + /// queue instead of being completed (daily sessions). + #[serde(default, skip_serializing_if = "is_false")] + pub return_mistakes: bool, + /// Review in order ends after one pass instead of starting the next cycle. + #[serde(default, skip_serializing_if = "is_false")] + pub single_pass: bool, + /// The pending preview is the first showing of a new move, not a hint. + #[serde(default, skip_serializing_if = "is_false")] + pub showing_new: bool, + #[serde(skip)] + runtime: SessionRuntime, +} + +fn is_false(value: &bool) -> bool { + !*value +} + +// Derived data only: clones share it, persistence and snapshot equality do not. +#[derive(Clone, Default, Debug)] +struct SessionRuntime(Arc>); + +impl PartialEq for SessionRuntime { + fn eq(&self, _other: &Self) -> bool { + true + } +} + +#[derive(Default, Debug)] +struct RuntimeData { + source: Option, + #[cfg(test)] + parses: usize, + #[cfg(test)] + replays: usize, + #[cfg(test)] + plans: usize, +} + +#[derive(Debug)] +struct ReplaySource { + repertoire_id: RepertoireId, + pgn: String, + start: Chess, + target: Option, +} + +#[derive(Debug)] +struct ReplayedTarget { + target: LearningSessionTarget, + side: LearningSide, + positions: Arc>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LearningPosition { + pub fen: String, + pub fen4: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct LearningContextStep { + pub uci: String, + pub from: LearningPosition, + pub to: LearningPosition, + pub speed_factor: f64, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct LearningPresentation { + pub phase: LearningSessionPhase, + pub target: Option, + pub target_path: Vec, + pub current_position: Option, + /// Automatic steps that still need presentation before the independent answer. + pub automatic_context: Vec, + pub revealed_move: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LearningSessionError { + EmptySessionId, + EmptyClientAttemptId, + UnsupportedMode(QueueMode), + SessionSideMismatch, + InvalidPhase { + operation: &'static str, + phase: LearningSessionPhase, + }, + IntroductionRequiresFinished, + InvalidSnapshot(&'static str), + RepertoireNotFound(RepertoireId), + InvalidTargetPath { + repertoire_id: RepertoireId, + path: Vec, + }, + TargetPositionMismatch, + TargetSideMismatch, + /// A known repertoire answer that is not the pending question. This is neutral + /// input: callers must not record an attempt, play an error sound or reset SRS. + RepertoireAlternative { + already_completed: bool, + }, + Graph(LearningGraphError), +} + +impl std::fmt::Display for LearningSessionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::EmptySessionId => f.write_str("learning session id must not be empty"), + Self::EmptyClientAttemptId => f.write_str("client attempt id must not be empty"), + Self::UnsupportedMode(mode) => { + write!(f, "learning session operation does not support {mode:?}") + } + Self::SessionSideMismatch => { + f.write_str("learning session side does not match its statistics scope") + } + Self::InvalidPhase { operation, phase } => { + write!( + f, + "cannot {operation} while learning session is in {phase:?}" + ) + } + Self::IntroductionRequiresFinished => { + f.write_str("new learning items can be introduced only after the due queue") + } + Self::InvalidSnapshot(message) => { + write!(f, "invalid learning session snapshot: {message}") + } + Self::RepertoireNotFound(id) => write!(f, "repertoire not found: {id}"), + Self::InvalidTargetPath { + repertoire_id, + path, + } => write!( + f, + "learning target path is no longer legal in repertoire {repertoire_id}: {}", + path.join(" ") + ), + Self::TargetPositionMismatch => { + f.write_str("learning target path does not reach its saved position") + } + Self::TargetSideMismatch => { + f.write_str("learning target position belongs to the other side") + } + Self::RepertoireAlternative { already_completed } => { + if *already_completed { + f.write_str("this repertoire answer has already been reviewed in this pass") + } else { + f.write_str("this repertoire answer is not the current scheduled question") + } + } + Self::Graph(error) => error.fmt(f), + } + } +} + +impl std::error::Error for LearningSessionError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Graph(error) => Some(error), + _ => None, + } + } +} + +impl From for LearningSessionError { + fn from(error: LearningGraphError) -> Self { + Self::Graph(error) + } +} + +impl LearningSessionSnapshot { + pub fn new( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + ) -> Result { + Self::new_with_mode( + id, + library, + learning, + stats_scope, + settings, + QueueMode::SpacedRepetition, + ) + } + + pub fn new_with_mode( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + mode: QueueMode, + ) -> Result { + let id = id.into(); + if id.is_empty() { + return Err(LearningSessionError::EmptySessionId); + } + let queue = select_queue(library, learning, &stats_scope, mode)?; + let side = training_mode(stats_scope.side); + let session = LearningSession { + id, + mode, + side, + scope: TrainingScopeKey { + prefix: stats_scope.branch_root.clone().unwrap_or_default(), + end_prefix: None, + }, + settings, + }; + let mut snapshot = Self { + session, + context_policy: LearningContextPolicy::default(), + stats_scope, + queue, + current_index: 0, + phase: LearningSessionPhase::Finished, + context_index: 0, + completed_keys: BTreeSet::new(), + cycle: 0, + revision: 0, + return_mistakes: false, + single_pass: false, + showing_new: false, + runtime: SessionRuntime::default(), + }; + snapshot.reset_current_target_with_library(library)?; + Ok(snapshot) + } + + /// A daily session: every move due at `stats_scope.as_of` and at most `max_new` + /// moves never shown before, in the scope's priority order. A move answered after a + /// mistake or a hint comes back later in the same session. + pub fn new_daily( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + max_new: usize, + ) -> Result { + let mut snapshot = Self::new_with_mode( + id, + library, + learning, + stats_scope, + settings, + QueueMode::SpacedRepetition, + )?; + snapshot.queue = daily_targets(library, learning, &snapshot.stats_scope, true, max_new)?; + snapshot.return_mistakes = true; + snapshot.reset_current_target_with_library(library)?; + Ok(snapshot) + } + + /// One pass over every active move in the scope's order, then `Finished`. + pub fn new_single_pass_review( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + ) -> Result { + let mut snapshot = Self::new_with_mode( + id, + library, + learning, + stats_scope, + settings, + QueueMode::ReviewInOrder, + )?; + snapshot.single_pass = true; + Ok(snapshot) + } + + /// One pass over the lines through the move at `through` (a PGN path; empty: every + /// line). The move itself is asked when it is the trained side's. + pub fn new_branch_review( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + through: &[String], + ) -> Result { + let stats_scope = match through.split_last() { + Some((_, root)) => stats_scope.with_branch_root(root.to_vec()), + None => stats_scope, + }; + let mut snapshot = + Self::new_single_pass_review(id, library, learning, stats_scope, settings)?; + snapshot + .queue + .retain(|target| target.path.starts_with(through)); + snapshot.reset_current_target_with_library(library)?; + Ok(snapshot) + } + + /// After a finished daily session: the next `max_new` unseen moves only. + pub fn introduce_more( + &mut self, + library: &Library, + learning: &LearningData, + max_new: usize, + ) -> Result { + self.validate_configuration()?; + if self.session.mode != QueueMode::SpacedRepetition { + return Err(LearningSessionError::UnsupportedMode(self.session.mode)); + } + if self.phase != LearningSessionPhase::Finished { + return Err(LearningSessionError::IntroductionRequiresFinished); + } + self.queue = daily_targets(library, learning, &self.stats_scope, false, max_new)?; + self.current_index = 0; + self.completed_keys.clear(); + self.reset_current_target_with_library(library)?; + Ok(self.queue.len()) + } + + /// The current move has never been shown: true when it has no learning state or was + /// never introduced. + pub fn current_is_new(&self, learning: &LearningData) -> bool { + self.current_target().is_some_and(|target| { + learning + .item(&target.key) + .is_none_or(|item| !item.introduced) + }) + } + + /// Explicitly replaces a finished queue with the currently unseen items. No item is + /// introduced into SRS until an independent answer or preview is recorded. + pub fn introduce_new( + &mut self, + library: &Library, + learning: &LearningData, + ) -> Result { + self.validate_configuration()?; + if self.session.mode != QueueMode::SpacedRepetition { + return Err(LearningSessionError::UnsupportedMode(self.session.mode)); + } + if self.phase != LearningSessionPhase::Finished { + return Err(LearningSessionError::IntroductionRequiresFinished); + } + self.queue = select_targets( + library, + learning, + &self.stats_scope, + |item| item.is_none_or(|item| !item.introduced), + self.stats_scope.learning_priority, + )?; + self.current_index = 0; + self.completed_keys.clear(); + self.reset_current_target_with_library(library)?; + Ok(self.queue.len()) + } + + pub fn start_next_pass( + &mut self, + library: &Library, + learning: &LearningData, + ) -> Result { + self.validate_configuration()?; + if self.phase != LearningSessionPhase::Finished { + return Err(LearningSessionError::InvalidPhase { + operation: "start the next pass", + phase: self.phase, + }); + } + self.queue = select_queue(library, learning, &self.stats_scope, self.session.mode)?; + self.current_index = 0; + self.completed_keys.clear(); + if !self.queue.is_empty() { + self.cycle = self.cycle.saturating_add(1); + } + self.reset_current_target_with_library(library)?; + Ok(self.queue.len()) + } + + pub fn reset_review_order(&mut self) -> Result<(), LearningSessionError> { + self.validate_configuration()?; + if self.session.mode != QueueMode::ReviewInOrder { + return Err(LearningSessionError::UnsupportedMode(self.session.mode)); + } + self.current_index = 0; + self.context_index = 0; + self.completed_keys.clear(); + self.cycle = 0; + self.reset_current_target(); + Ok(()) + } + + pub fn resume(self, library: &Library) -> Result { + self.validate(library)?; + Ok(self) + } + + pub fn id(&self) -> &str { + &self.session.id + } + + pub fn current_target(&self) -> Option<&LearningSessionTarget> { + self.queue.get(self.current_index) + } + + pub fn current_expected_uci(&self) -> Option<&str> { + let target = self.current_target()?; + if self.is_context_challenge(target) { + target.path.get(self.context_index).map(String::as_str) + } else { + Some(&target.key.expected_uci) + } + } + + pub fn remaining(&self) -> usize { + self.queue + .iter() + .skip(self.current_index) + .filter(|target| !self.completed_keys.contains(&target.key)) + .count() + } + + /// Choices still due in this fixed pass; statistics stay separate for each UCI. + pub fn pending_answers_for_position(&self, position_fen4: &str) -> Vec { + self.queue + .iter() + .skip(self.current_index) + .filter(|target| { + target.key.position_fen4 == position_fen4 + && !self.completed_keys.contains(&target.key) + }) + .map(|target| target.key.expected_uci.clone()) + .collect() + } + + /// Only active answers in this session's scope qualify, never arbitrary legal + /// moves or a disabled/out-of-scope PGN branch. + pub fn is_active_repertoire_answer( + &self, + library: &Library, + position_fen4: &str, + uci: &str, + ) -> Result { + Ok(active_learning_memberships(library, &self.stats_scope)? + .iter() + .any(|item| item.key.position_fen4 == position_fen4 && item.key.expected_uci == uci)) + } + + pub fn presentation( + &self, + library: &Library, + ) -> Result { + self.presentation_impl(library, None) + } + + pub fn presentation_with_learning( + &mut self, + library: &Library, + learning: &LearningData, + ) -> Result { + self.sync_context_phase(library, Some(learning))?; + self.presentation_impl(library, Some(learning)) + } + + fn presentation_impl( + &self, + library: &Library, + learning: Option<&LearningData>, + ) -> Result { + self.validate_configuration()?; + let Some(target) = self.current_target() else { + return Ok(LearningPresentation { + phase: self.phase, + target: None, + target_path: Vec::new(), + current_position: None, + automatic_context: Vec::new(), + revealed_move: None, + }); + }; + let positions = self.replay_target(library, target)?; + if self.context_index >= positions.len() { + return Err(LearningSessionError::InvalidSnapshot( + "context index is outside the target path", + )); + } + let prefix_len = target.path.len().saturating_sub(1); + let plan = learning.map(|learning| self.context_plan(target, &positions, learning)); + let automatic_context = (self.context_index..prefix_len) + .take_while(|index| { + if *index == self.context_index && self.is_context_challenge(target) { + false + } else { + !self.context_needs_check(target, &positions, *index, plan.as_ref()) + } + }) + .map(|index| { + let factor = learning.map_or(1.0, |learning| { + let own_move = + LearningSide::from(positions[index].turn()) == self.stats_scope.side; + let key = LearningItemKey::new( + target.key.user_id.clone(), + fen4(&positions[index]), + target.path[index].clone(), + ); + let item = own_move.then(|| learning.item(&key)).flatten(); + speed_factor(&self.context_policy, item) + }); + LearningContextStep { + uci: target.path[index].clone(), + from: learning_position(&positions[index]), + to: learning_position(&positions[index + 1]), + speed_factor: factor, + } + }) + .collect(); + let revealed_move = match self.phase { + LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay => { + self.current_expected_uci().map(str::to_owned) + } + _ => None, + }; + Ok(LearningPresentation { + phase: self.phase, + target: Some(target.key.clone()), + target_path: target.path.clone(), + current_position: Some(learning_position(&positions[self.context_index])), + automatic_context, + revealed_move, + }) + } + + pub fn advance_context( + &mut self, + library: &Library, + client_attempt_id: impl Into, + happened_at: i64, + ) -> Result { + self.advance_context_impl(library, client_attempt_id, happened_at, None) + } + + pub fn advance_context_with_learning( + &mut self, + library: &Library, + learning: &LearningData, + client_attempt_id: impl Into, + happened_at: i64, + ) -> Result { + self.sync_context_phase(library, Some(learning))?; + self.advance_context_impl(library, client_attempt_id, happened_at, Some(learning)) + } + + fn advance_context_impl( + &mut self, + library: &Library, + client_attempt_id: impl Into, + happened_at: i64, + learning: Option<&LearningData>, + ) -> Result { + let client_attempt_id = checked_attempt_id(client_attempt_id.into())?; + self.require_phase( + "advance automatic context", + LearningSessionPhase::AdvancingContext, + )?; + let target = + self.current_target() + .cloned() + .ok_or(LearningSessionError::InvalidSnapshot( + "context has no current target", + ))?; + let positions = self.replay_target(library, &target)?; + let prefix_len = target.path.len() - 1; + if self.context_index >= prefix_len { + return Err(LearningSessionError::InvalidSnapshot( + "automatic context is already complete", + )); + } + let index = self.context_index; + let plan = learning.map(|learning| self.context_plan(&target, &positions, learning)); + if self.context_needs_check(&target, &positions, index, plan.as_ref()) { + return Err(LearningSessionError::InvalidSnapshot( + "automatic context requires an independent answer", + )); + } + let uci = target.path[index].clone(); + let attempt = TrainingAttempt { + user_id: target.key.user_id, + position_fen4: fen4(&positions[index]), + client_attempt_id, + session_id: self.session.id.clone(), + event_type: TrainingEventType::AutoContext, + expected_uci: uci.clone(), + actual_uci: Some(uci), + response_time_ms: None, + happened_at, + }; + self.context_index += 1; + self.sync_context_phase(library, learning)?; + Ok(attempt) + } + + pub fn preview( + &mut self, + client_attempt_id: impl Into, + happened_at: i64, + ) -> Result, LearningSessionError> { + self.preview_impl(client_attempt_id, happened_at, false) + } + + /// Shows a new move before asking it. The move is recorded as `PREVIEWED`, but in a + /// daily session it does not come back as a mistake would. + pub fn preview_new( + &mut self, + client_attempt_id: impl Into, + happened_at: i64, + ) -> Result, LearningSessionError> { + self.preview_impl(client_attempt_id, happened_at, true) + } + + fn preview_impl( + &mut self, + client_attempt_id: impl Into, + happened_at: i64, + new: bool, + ) -> Result, LearningSessionError> { + let client_attempt_id = checked_attempt_id(client_attempt_id.into())?; + self.validate_configuration()?; + match self.phase { + LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay => return Ok(None), + LearningSessionPhase::AwaitingIndependent => {} + phase => { + return Err(LearningSessionError::InvalidPhase { + operation: "preview the expected move", + phase, + }); + } + } + let target = + self.current_target() + .cloned() + .ok_or(LearningSessionError::InvalidSnapshot( + "preview has no current target", + ))?; + self.phase = LearningSessionPhase::PreviewedReplay; + self.showing_new = new; + Ok(Some(self.attempt( + &target.key, + TrainingEventType::Previewed, + Some(target.key.expected_uci.clone()), + None, + client_attempt_id, + happened_at, + ))) + } + + pub fn play_uci( + &mut self, + library: &Library, + uci: &str, + client_attempt_id: impl Into, + happened_at: i64, + response_time_ms: Option, + ) -> Result { + self.play_uci_impl( + library, + uci, + client_attempt_id, + happened_at, + response_time_ms, + None, + None, + ) + } + + pub fn play_uci_with_learning( + &mut self, + library: &Library, + learning: &LearningData, + uci: &str, + client_attempt_id: impl Into, + happened_at: i64, + response_time_ms: Option, + ) -> Result { + self.sync_context_phase(library, Some(learning))?; + self.play_uci_impl( + library, + uci, + client_attempt_id, + happened_at, + response_time_ms, + Some(learning), + None, + ) + } + + /// The UI prepares this scope's answers with the immutable library in its + /// startup worker, so a wrong move never rebuilds all repertoire graphs. + #[allow(clippy::too_many_arguments)] + pub fn play_uci_with_learning_answers( + &mut self, + library: &Library, + learning: &LearningData, + answers: &BTreeSet, + uci: &str, + client_attempt_id: impl Into, + happened_at: i64, + response_time_ms: Option, + ) -> Result { + self.sync_context_phase(library, Some(learning))?; + self.play_uci_impl( + library, + uci, + client_attempt_id, + happened_at, + response_time_ms, + Some(learning), + Some(answers), + ) + } + + #[allow(clippy::too_many_arguments)] + fn play_uci_impl( + &mut self, + library: &Library, + uci: &str, + client_attempt_id: impl Into, + happened_at: i64, + response_time_ms: Option, + learning: Option<&LearningData>, + answers: Option<&BTreeSet>, + ) -> Result { + let client_attempt_id = checked_attempt_id(client_attempt_id.into())?; + self.validate_configuration()?; + if !matches!( + self.phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + | LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay + ) { + return Err(LearningSessionError::InvalidPhase { + operation: "play a move", + phase: self.phase, + }); + } + let target = + self.current_target() + .cloned() + .ok_or(LearningSessionError::InvalidSnapshot( + "move input has no current target", + ))?; + let positions = self.replay_target(library, &target)?; + let context = self.is_context_challenge(&target); + let challenge_index = if context { + self.context_index + } else { + target.path.len() - 1 + }; + let position = &positions[challenge_index]; + let challenge_key = if context { + LearningItemKey::new( + target.key.user_id.clone(), + fen4(position), + target.path[challenge_index].clone(), + ) + } else { + target.key.clone() + }; + let legal = uci + .parse::() + .ok() + .and_then(|parsed| parsed.to_move(position).ok()); + let Some(mv) = legal else { + return Ok(self.attempt( + &challenge_key, + TrainingEventType::IllegalMove, + Some(uci.to_owned()), + None, + client_attempt_id, + happened_at, + )); + }; + let actual_uci = mv.to_uci(CastlingMode::Standard).to_string(); + let correct = actual_uci == challenge_key.expected_uci; + if !correct { + let actual_key = LearningItemKey::new( + challenge_key.user_id.clone(), + challenge_key.position_fen4.clone(), + actual_uci.clone(), + ); + if matches!( + self.phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + ) && let Some(index) = self + .queue + .iter() + .enumerate() + .skip(self.current_index) + .find_map(|(index, candidate)| { + (candidate.key == actual_key && !self.completed_keys.contains(&actual_key)) + .then_some(index) + }) + { + // Consume exactly the answer played. The original target remains + // pending, even when this question was part of its context. Never + // advance the old path after taking a different branch. + let attempt = self.attempt( + &actual_key, + TrainingEventType::CorrectIndependent, + Some(actual_uci), + response_time_ms, + client_attempt_id, + happened_at, + ); + self.queue.swap(self.current_index, index); + self.complete_current(library)?; + return Ok(attempt); + } + let known = match answers { + Some(answers) => answers.contains(&actual_key), + None => self.is_active_repertoire_answer( + library, + &actual_key.position_fen4, + &actual_uci, + )?, + }; + if known { + return Err(LearningSessionError::RepertoireAlternative { + already_completed: self.completed_keys.contains(&actual_key), + }); + } + } + let event_type = match self.phase { + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => { + if correct { + TrainingEventType::CorrectIndependent + } else { + TrainingEventType::IncorrectIndependent + } + } + LearningSessionPhase::AwaitingReplayAfterError => TrainingEventType::ReplayAfterError, + LearningSessionPhase::PreviewedReplay => TrainingEventType::AutoContext, + phase => { + return Err(LearningSessionError::InvalidPhase { + operation: "play a move", + phase, + }); + } + }; + let independent_time = if event_type.is_independent() { + response_time_ms + } else { + None + }; + let attempt = self.attempt( + &challenge_key, + event_type, + Some(actual_uci), + independent_time, + client_attempt_id, + happened_at, + ); + match self.phase { + LearningSessionPhase::AwaitingIndependent if correct => { + self.complete_current(library)?; + } + LearningSessionPhase::AwaitingContextIndependent if correct => { + self.complete_context(challenge_key, library, learning)?; + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => { + self.phase = LearningSessionPhase::AwaitingReplayAfterError; + } + LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay + if correct => + { + if context { + self.complete_context(challenge_key, library, learning)?; + } else if self.return_mistakes && !self.showing_new { + self.return_current(library)?; + } else { + self.complete_current(library)?; + } + } + _ => {} + } + Ok(attempt) + } + + pub fn validate(&self, library: &Library) -> Result<(), LearningSessionError> { + self.validate_configuration()?; + if self.current_index > self.queue.len() { + return Err(LearningSessionError::InvalidSnapshot( + "current index is outside the fixed queue", + )); + } + let mut keys = BTreeSet::new(); + if self.queue.iter().any(|target| !keys.insert(&target.key)) { + return Err(LearningSessionError::InvalidSnapshot( + "fixed queue contains a duplicate learning item", + )); + } + let Some(target) = self.current_target() else { + if self.phase != LearningSessionPhase::Finished { + return Err(LearningSessionError::InvalidSnapshot( + "a session without a current target must be finished", + )); + } + return Ok(()); + }; + if self.phase == LearningSessionPhase::Finished { + return Err(LearningSessionError::InvalidSnapshot( + "a session with a current target cannot be finished", + )); + } + if self.completed_keys.contains(&target.key) { + return Err(LearningSessionError::InvalidSnapshot( + "the current learning item is already completed in this pass", + )); + } + let positions = self.replay_target(library, target)?; + let prefix_len = target.path.len() - 1; + let own_context = self.context_index < prefix_len + && LearningSide::from(positions[self.context_index].turn()) == self.stats_scope.side; + let legacy_context_needs_check = self.context_index < prefix_len + && self.context_needs_check(target, &positions, self.context_index, None); + match self.phase { + LearningSessionPhase::AdvancingContext + if self.context_index < prefix_len && !legacy_context_needs_check => {} + LearningSessionPhase::AwaitingContextIndependent if own_context => {} + LearningSessionPhase::AwaitingIndependent if self.context_index == prefix_len => {} + LearningSessionPhase::AwaitingReplayAfterError + if self.context_index == prefix_len || own_context => {} + LearningSessionPhase::PreviewedReplay if self.context_index == prefix_len => {} + _ => { + return Err(LearningSessionError::InvalidSnapshot( + "phase and automatic context index disagree", + )); + } + } + if positions.len() != target.path.len() + 1 { + return Err(LearningSessionError::InvalidSnapshot( + "target path replay is incomplete", + )); + } + Ok(()) + } + + pub(crate) fn validate_configuration(&self) -> Result<(), LearningSessionError> { + if self.session.id.is_empty() { + return Err(LearningSessionError::EmptySessionId); + } + if !matches!( + self.session.mode, + QueueMode::SpacedRepetition | QueueMode::ReviewInOrder | QueueMode::LeastRecent + ) { + return Err(LearningSessionError::UnsupportedMode(self.session.mode)); + } + if self.session.side != training_mode(self.stats_scope.side) { + return Err(LearningSessionError::SessionSideMismatch); + } + Ok(()) + } + + fn require_phase( + &self, + operation: &'static str, + expected: LearningSessionPhase, + ) -> Result<(), LearningSessionError> { + self.validate_configuration()?; + if self.phase == expected { + Ok(()) + } else { + Err(LearningSessionError::InvalidPhase { + operation, + phase: self.phase, + }) + } + } + + fn attempt( + &self, + key: &LearningItemKey, + event_type: TrainingEventType, + actual_uci: Option, + response_time_ms: Option, + client_attempt_id: String, + happened_at: i64, + ) -> TrainingAttempt { + TrainingAttempt { + user_id: key.user_id.clone(), + position_fen4: key.position_fen4.clone(), + client_attempt_id, + session_id: self.session.id.clone(), + event_type, + expected_uci: key.expected_uci.clone(), + actual_uci, + response_time_ms, + happened_at, + } + } + + fn complete_current(&mut self, library: &Library) -> Result<(), LearningSessionError> { + if let Some(target) = self.current_target() { + self.completed_keys.insert(target.key.clone()); + } + self.current_index += 1; + while self + .current_target() + .is_some_and(|target| self.completed_keys.contains(&target.key)) + { + self.current_index += 1; + } + if self.session.mode == QueueMode::ReviewInOrder + && !self.single_pass + && self.current_index >= self.queue.len() + && !self.queue.is_empty() + { + self.current_index = 0; + self.completed_keys.clear(); + self.cycle = self.cycle.saturating_add(1); + } + self.reset_current_target_with_library(library) + } + + /// Moves the current target behind the rest of the queue: it is asked again later + /// in this session, from the start of its line. + fn return_current(&mut self, library: &Library) -> Result<(), LearningSessionError> { + if self.current_index < self.queue.len() { + let target = self.queue.remove(self.current_index); + self.queue.push(target); + } + while self + .current_target() + .is_some_and(|target| self.completed_keys.contains(&target.key)) + { + self.current_index += 1; + } + self.reset_current_target_with_library(library) + } + + fn complete_context( + &mut self, + key: LearningItemKey, + library: &Library, + learning: Option<&LearningData>, + ) -> Result<(), LearningSessionError> { + self.completed_keys.insert(key); + self.context_index += 1; + self.phase = LearningSessionPhase::AdvancingContext; + self.sync_context_phase(library, learning) + } + + fn reset_current_target_with_library( + &mut self, + library: &Library, + ) -> Result<(), LearningSessionError> { + self.reset_current_target(); + self.sync_context_phase(library, None) + } + + fn sync_context_phase( + &mut self, + library: &Library, + learning: Option<&LearningData>, + ) -> Result<(), LearningSessionError> { + self.validate_configuration()?; + let Some(target) = self.current_target().cloned() else { + self.phase = LearningSessionPhase::Finished; + return Ok(()); + }; + let positions = self.replay_target(library, &target)?; + let prefix_len = target.path.len() - 1; + if self.context_index > prefix_len { + return Err(LearningSessionError::InvalidSnapshot( + "context index is outside the target path", + )); + } + if self.context_index == prefix_len { + if !matches!( + self.phase, + LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay + ) { + self.phase = LearningSessionPhase::AwaitingIndependent; + } + return Ok(()); + } + if self.is_context_challenge(&target) { + if LearningSide::from(positions[self.context_index].turn()) == self.stats_scope.side { + return Ok(()); + } + return Err(LearningSessionError::InvalidSnapshot( + "opponent context cannot require an independent answer", + )); + } + let plan = learning.map(|learning| self.context_plan(&target, &positions, learning)); + if let Some(plan) = &plan + && self.phase == LearningSessionPhase::AdvancingContext + && self.context_index < plan.skip_prefix + { + self.context_index = plan.skip_prefix; + if self.context_index == prefix_len { + self.phase = LearningSessionPhase::AwaitingIndependent; + return Ok(()); + } + } + self.phase = + if self.context_needs_check(&target, &positions, self.context_index, plan.as_ref()) { + LearningSessionPhase::AwaitingContextIndependent + } else { + LearningSessionPhase::AdvancingContext + }; + Ok(()) + } + + fn context_plan( + &self, + target: &LearningSessionTarget, + positions: &[Chess], + learning: &LearningData, + ) -> LearningContextPlan { + #[cfg(test)] + { + self.runtime + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .plans += 1; + } + let queue_keys = (self.session.mode == QueueMode::LeastRecent).then(|| { + self.queue + .iter() + .map(|target| &target.key) + .collect::>() + }); + let moves = (0..target.path.len().saturating_sub(1)) + .map(|index| { + let key = LearningItemKey::new( + target.key.user_id.clone(), + fen4(&positions[index]), + target.path[index].clone(), + ); + LearningContextMove { + own_move: LearningSide::from(positions[index].turn()) == self.stats_scope.side, + least_recent_target: queue_keys + .as_ref() + .is_some_and(|keys| keys.contains(&key)), + key, + } + }) + .collect::>(); + plan_context( + &moves, + learning, + &self.context_policy, + &self.completed_keys, + self.session.mode == QueueMode::LeastRecent, + self.stats_scope.as_of, + ) + } + + fn context_needs_check( + &self, + target: &LearningSessionTarget, + positions: &[Chess], + index: usize, + plan: Option<&LearningContextPlan>, + ) -> bool { + if index >= target.path.len().saturating_sub(1) + || LearningSide::from(positions[index].turn()) != self.stats_scope.side + { + return false; + } + if let Some(plan) = plan { + return plan.actions[index] == LearningContextAction::Independent; + } + if self.session.mode != QueueMode::LeastRecent { + return false; + } + let key = LearningItemKey::new( + target.key.user_id.clone(), + fen4(&positions[index]), + target.path[index].clone(), + ); + !self.completed_keys.contains(&key) && self.queue.iter().any(|target| target.key == key) + } + + fn is_context_challenge(&self, target: &LearningSessionTarget) -> bool { + self.context_index < target.path.len().saturating_sub(1) + && matches!( + self.phase, + LearningSessionPhase::AwaitingContextIndependent + | LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay + ) + } + + fn reset_current_target(&mut self) { + self.context_index = 0; + self.showing_new = false; + self.phase = match self.current_target() { + None => LearningSessionPhase::Finished, + Some(target) if target.path.len() > 1 => LearningSessionPhase::AdvancingContext, + Some(_) => LearningSessionPhase::AwaitingIndependent, + }; + } +} + +fn checked_attempt_id(id: String) -> Result { + if id.is_empty() { + Err(LearningSessionError::EmptyClientAttemptId) + } else { + Ok(id) + } +} + +fn training_mode(side: LearningSide) -> TrainingMode { + match side { + LearningSide::White => TrainingMode::White, + LearningSide::Black => TrainingMode::Black, + } +} + +fn select_queue( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + mode: QueueMode, +) -> Result, LearningSessionError> { + match mode { + QueueMode::SpacedRepetition => select_targets( + library, + learning, + scope, + |item| item.is_some_and(|item| item.is_due(scope.as_of)), + LearningPriority::BreadthOverDepth, + ), + QueueMode::ReviewInOrder => { + select_targets(library, learning, scope, |_| true, scope.learning_priority) + } + QueueMode::LeastRecent => { + let mut memberships = + select_memberships(library, learning, scope, |_| true, scope.learning_priority)?; + sort_least_recent(&mut memberships, learning, scope.learning_priority); + Ok(memberships + .into_iter() + .map(LearningSessionTarget::from) + .collect()) + } + QueueMode::Practice => Err(LearningSessionError::UnsupportedMode(mode)), + } +} + +fn daily_targets( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + include_due: bool, + max_new: usize, +) -> Result, LearningSessionError> { + let mut new = 0usize; + Ok(select_memberships( + library, + learning, + scope, + |item| { + item.is_none_or(|item| !item.introduced) + || item.is_some_and(|item| item.is_due(scope.as_of)) + }, + scope.learning_priority, + )? + .into_iter() + .filter(|membership| { + let item = learning.item(&membership.key); + if item.is_none_or(|item| !item.introduced) { + new += 1; + new <= max_new + } else { + include_due + } + }) + .map(LearningSessionTarget::from) + .collect()) +} + +fn select_targets( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + include: impl Fn(Option<&super::learning::LearningItem>) -> bool, + priority: LearningPriority, +) -> Result, LearningSessionError> { + Ok( + select_memberships(library, learning, scope, include, priority)? + .into_iter() + .map(LearningSessionTarget::from) + .collect(), + ) +} + +fn select_memberships( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + include: impl Fn(Option<&super::learning::LearningItem>) -> bool, + priority: LearningPriority, +) -> Result, LearningSessionError> { + let memberships = active_learning_memberships(library, scope)?; + let mut by_key = BTreeMap::new(); + for membership in memberships { + by_key + .entry(membership.key.clone()) + .and_modify(|existing: &mut LearningItemMembership| { + if membership_order(&membership) < membership_order(existing) { + *existing = membership.clone(); + } + }) + .or_insert(membership); + } + let mut memberships: Vec<_> = by_key + .into_values() + .filter(|membership| include(learning.item(&membership.key))) + .collect(); + sort_by_priority(&mut memberships, priority); + Ok(memberships) +} + +fn membership_order( + membership: &LearningItemMembership, +) -> (&RepertoireId, u32, &[String], &LearningItemKey) { + ( + &membership.repertoire_id, + membership.min_depth, + &membership.path, + &membership.key, + ) +} + +impl LearningSessionSnapshot { + fn replay_target( + &self, + library: &Library, + target: &LearningSessionTarget, + ) -> Result>, LearningSessionError> { + let side = self.stats_scope.side; + if target.path.is_empty() || target.path.last() != Some(&target.key.expected_uci) { + return Err(LearningSessionError::InvalidTargetPath { + repertoire_id: target.repertoire_id.clone(), + path: target.path.clone(), + }); + } + let repertoire = library.repertoire(&target.repertoire_id).ok_or_else(|| { + LearningSessionError::RepertoireNotFound(target.repertoire_id.clone()) + })?; + let mut runtime = self + .runtime + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + if runtime.source.as_ref().is_none_or(|source| { + source.repertoire_id != target.repertoire_id || source.pgn != repertoire.pgn + }) { + runtime.source = Some(ReplaySource { + repertoire_id: target.repertoire_id.clone(), + pgn: repertoire.pgn.clone(), + start: repertoire.game().start().position().clone(), + target: None, + }); + #[cfg(test)] + { + runtime.parses += 1; + } + } + // The source was installed above. Avoid an assumption on user data at this boundary. + let Some(source) = runtime.source.as_ref() else { + return Err(LearningSessionError::InvalidSnapshot( + "replay source unavailable", + )); + }; + if let Some(cached) = &source.target + && cached.target == *target + && cached.side == side + { + return Ok(Arc::clone(&cached.positions)); + } + let mut position = source.start.clone(); + let mut positions = vec![position.clone()]; + for uci in &target.path { + let mv = uci + .parse::() + .ok() + .and_then(|parsed| parsed.to_move(&position).ok()) + .ok_or_else(|| LearningSessionError::InvalidTargetPath { + repertoire_id: target.repertoire_id.clone(), + path: target.path.clone(), + })?; + position.play_unchecked(mv); + positions.push(position.clone()); + } + let parent = &positions[target.path.len() - 1]; + if fen4(parent) != target.key.position_fen4 { + return Err(LearningSessionError::TargetPositionMismatch); + } + if LearningSide::from(parent.turn()) != side { + return Err(LearningSessionError::TargetSideMismatch); + } + let positions = Arc::new(positions); + if let Some(source) = runtime.source.as_mut() { + source.target = Some(ReplayedTarget { + target: target.clone(), + side, + positions: Arc::clone(&positions), + }); + } + #[cfg(test)] + { + runtime.replays += 1; + } + Ok(positions) + } + + #[cfg(test)] + pub(super) fn runtime_work_counts(&self) -> (usize, usize, usize) { + let runtime = self + .runtime + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + (runtime.parses, runtime.replays, runtime.plans) + } +} + +fn learning_position(position: &Chess) -> LearningPosition { + LearningPosition { + fen: Fen::from_position(position, EnPassantMode::Legal).to_string(), + fen4: fen4(position), + } +} diff --git a/crates/trainer/src/repertoire/line_analytics.rs b/crates/trainer/src/repertoire/line_analytics.rs new file mode 100644 index 0000000..f45d629 --- /dev/null +++ b/crates/trainer/src/repertoire/line_analytics.rs @@ -0,0 +1,107 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::aggregate::{LearningAggregate, aggregate}; +use super::learning::{LearningData, LearningItem, LearningItemKey}; +use super::learning_graph::{ + LearningGraphError, StatsScope, aggregate_scope, all_path_learning_memberships, +}; +use super::model::{Library, RepertoireId}; +use super::scope::TrainingScope; +use super::srs::SrsSettings; +use super::tree::RepertoireTree; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LineLearningAnalytics { + pub repertoire_id: RepertoireId, + pub line: Vec, + pub summary: LearningAggregate, + pub line_learnt: bool, + pub line_fresh: bool, +} + +pub fn line_learning_analytics( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + settings: &SrsSettings, +) -> Result, LearningGraphError> { + let memberships = all_path_learning_memberships(library, scope)?; + let scoped = aggregate_scope(library, learning, scope, settings)?; + let items_by_key: BTreeMap<&LearningItemKey, &LearningItem> = + scoped.items.iter().map(|item| (&item.key, item)).collect(); + let mut terminal_lines: BTreeMap>> = BTreeMap::new(); + for id in &scope.repertoire_ids { + let repertoire = library + .repertoire(id) + .ok_or_else(|| LearningGraphError::RepertoireNotFound(id.clone()))?; + let disabled_prefixes = if scope.only_active { + repertoire.disabled_prefixes.clone() + } else { + Vec::new() + }; + let tree = RepertoireTree::from_game( + repertoire.game(), + scope.max_depth.unwrap_or(u32::MAX), + disabled_prefixes, + ); + let lines = terminal_lines.entry(id.clone()).or_default(); + tree.visit_source_paths(&TrainingScope::whole(), |line| { + if scope + .branch_root + .as_deref() + .is_none_or(|root| line.starts_with(root)) + { + lines.push(line.to_vec()); + } + std::ops::ControlFlow::Continue(()) + }) + .map_err(|message| LearningGraphError::TrainingPathGeneration { + repertoire_id: id.clone(), + message, + })?; + lines.sort(); + lines.dedup(); + } + + let mut lines: BTreeMap< + (RepertoireId, Vec), + BTreeMap<&LearningItemKey, &LearningItem>, + > = BTreeMap::new(); + for membership in memberships { + let Some((key, item)) = items_by_key.get_key_value(&membership.key) else { + continue; + }; + let Some(candidates) = terminal_lines.get(&membership.repertoire_id) else { + continue; + }; + let first = candidates.partition_point(|line| line.as_slice() < membership.path.as_slice()); + for line in &candidates[first..] { + if !line.starts_with(&membership.path) { + break; + } + lines + .entry((membership.repertoire_id.clone(), line.clone())) + .or_default() + .insert(*key, *item); + } + } + + Ok(lines + .into_iter() + .map(|((repertoire_id, line), items)| { + let summary = aggregate(items.values().copied(), scope.as_of, settings); + let line_learnt = + summary.total > 0 && items.values().all(|item| item.correct_streak >= 3); + let line_fresh = line_learnt && summary.uncertain == 0 && summary.due == 0; + LineLearningAnalytics { + repertoire_id, + line, + summary, + line_learnt, + line_fresh, + } + }) + .collect()) +} diff --git a/crates/trainer/src/repertoire/line_tests.rs b/crates/trainer/src/repertoire/line_tests.rs new file mode 100644 index 0000000..b7f6961 --- /dev/null +++ b/crates/trainer/src/repertoire/line_tests.rs @@ -0,0 +1,299 @@ +use super::*; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 24 * 60 * 60; + +fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { + library + .create(name, &chess_core::parse_str(pgn).game) + .unwrap() +} + +fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { + let mut library = Library::default(); + let id = add_repertoire(&mut library, "One", pgn); + (library, id) +} + +fn scope(id: RepertoireId) -> StatsScope { + StatsScope::for_repertoire(id, LearningSide::White, NOW) +} + +fn strings(moves: &[&str]) -> Vec { + moves.iter().map(|mv| (*mv).to_owned()).collect() +} + +fn key_at_path(repertoire: &Repertoire, path: &[String], expected_uci: &str) -> LearningItemKey { + let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); + let parent = tree.node_at_path(path).unwrap(); + LearningItemKey::local(tree.position_key(parent).unwrap(), expected_uci) +} + +fn line<'a>( + rows: &'a [LineLearningAnalytics], + repertoire_id: &RepertoireId, + path: &[&str], +) -> Option<&'a LineLearningAnalytics> { + rows.iter().find(|row| { + &row.repertoire_id == repertoire_id + && row.line.iter().map(String::as_str).eq(path.iter().copied()) + }) +} + +fn learnt(item: &mut LearningItem, next_review_at: i64) { + item.introduced = true; + item.correct_streak = 3; + item.correct_count = 3; + item.last_review_at = Some(NOW - DAY); + item.last_correct_at = Some(NOW - DAY); + item.last_independent_at = Some(NOW - DAY); + item.next_review_at = Some(next_review_at); + item.previous_interval_seconds = Some(DAY); +} + +fn transposition_pgn() -> &'static str { + "1. e4 d5 (1... Nf6 2. d4 d5 3. c4) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 e6 6. g3 *" +} + +fn branching_pgn() -> &'static str { + "1. e4 e5 (1... c5 2. Nf3) 2. Nf3 Nc6 3. Bb5 *" +} + +#[test] +fn at_30_overlapping_lines_share_items_but_global_scope_deduplicates() { + let mut library = Library::default(); + let first = add_repertoire(&mut library, "First", transposition_pgn()); + let second = add_repertoire(&mut library, "Second", transposition_pgn()); + let shared = key_at_path( + library.repertoire(&first).unwrap(), + &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), + "c2c4", + ); + let mut learning = LearningData::default(); + learnt(learning.ensure_item(shared), NOW + DAY); + let rows = line_learning_analytics( + &library, + &learning, + &scope(first.clone()), + &SrsSettings::default(), + ) + .unwrap(); + assert_eq!(rows.len(), 2); + let main_line = line( + &rows, + &first, + &[ + "e2e4", "d7d5", "d2d4", "g8h6", "g1f3", "h6g8", "f3g1", "g8f6", "c2c4", "e7e6", "g2g3", + ], + ) + .unwrap(); + let transposing_line = line(&rows, &first, &["e2e4", "g8f6", "d2d4", "d7d5", "c2c4"]).unwrap(); + assert_eq!(main_line.summary.total, 6); + assert_eq!(transposing_line.summary.total, 3); + for row in [main_line, transposing_line] { + assert_eq!(row.summary.learnt, 1); + assert_eq!(row.summary.accuracy_correct, 3); + assert_eq!(row.summary.accuracy_attempts, 3); + assert!(!row.line_learnt); + assert!(!row.line_fresh); + } + + let global_scope = StatsScope::new([first, second], LearningSide::White, NOW); + let global = + aggregate_scope(&library, &learning, &global_scope, &SrsSettings::default()).unwrap(); + assert_eq!(global.summary.total, 7); + assert_eq!(global.summary.learnt, 1); + assert_eq!(global.summary.accuracy_correct, 3); + assert!(global.summary.total < main_line.summary.total + transposing_line.summary.total); + let mean = (main_line.summary.learnt_percent.unwrap() + + transposing_line.summary.learnt_percent.unwrap()) + / 2.0; + assert!((global.summary.learnt_percent.unwrap() - mean).abs() > f64::EPSILON); +} + +#[test] +fn line_learnt_and_fresh_follow_success_due_uncertain_and_wrong() { + let (library, id) = single_repertoire("1. e4 e5 2. Nf3 *"); + let selected = scope(id.clone()); + let keys = active_learning_keys(&library, &selected).unwrap(); + let mut learning = LearningData::default(); + let initial = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(initial.len(), 1); + assert_eq!(initial[0].summary.total, 2); + assert_eq!(initial[0].summary.unseen, 2); + assert!(!initial[0].line_learnt); + assert!(!initial[0].line_fresh); + + for key in &keys { + let item = learning.ensure_item(key.clone()); + for happened_at in [NOW - 3, NOW - 2, NOW - 1] { + apply_independent_correct(item, happened_at, &SrsSettings::default()); + } + item.next_review_at = Some(NOW + DAY); + item.previous_interval_seconds = Some(DAY); + } + let fresh = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(fresh[0].summary.learnt, 2); + assert_eq!(fresh[0].summary.due, 0); + assert_eq!(fresh[0].summary.uncertain, 0); + assert!(fresh[0].line_learnt); + assert!(fresh[0].line_fresh); + + let first = keys.iter().next().unwrap(); + learning.ensure_item((*first).clone()).next_review_at = Some(NOW); + let due = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(due[0].summary.due, 1); + assert_eq!(due[0].summary.uncertain, 0); + assert!(due[0].line_learnt); + assert!(!due[0].line_fresh); + + learning.ensure_item((*first).clone()).next_review_at = Some(NOW - 8 * DAY); + let uncertain = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(uncertain[0].summary.due, 1); + assert_eq!(uncertain[0].summary.uncertain, 1); + assert!(uncertain[0].line_learnt); + assert!(!uncertain[0].line_fresh); + + apply_independent_wrong( + learning.ensure_item((*first).clone()), + "d2d4", + NOW, + &SrsSettings::default(), + ); + let wrong = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(wrong[0].summary.learning, 1); + assert_eq!(wrong[0].summary.accuracy_wrong, 1); + assert!(!wrong[0].line_learnt); + assert!(!wrong[0].line_fresh); + + for happened_at in [NOW + 1, NOW + 2, NOW + 3] { + apply_independent_correct( + learning.ensure_item((*first).clone()), + happened_at, + &SrsSettings::default(), + ); + } + let mut restored_scope = selected; + restored_scope.as_of = NOW + 3; + let restored = line_learning_analytics( + &library, + &learning, + &restored_scope, + &SrsSettings::default(), + ) + .unwrap(); + assert_eq!(restored[0].summary.learnt, 2); + assert_eq!(restored[0].summary.due, 0); + assert_eq!(restored[0].summary.uncertain, 0); + assert!(restored[0].line_learnt); + assert!(restored[0].line_fresh); +} + +#[test] +fn empty_lines_are_omitted_and_never_reported_learnt() { + let (library, id) = single_repertoire("1. e4 *"); + let empty_scope = StatsScope::new([], LearningSide::White, NOW); + assert!( + line_learning_analytics( + &library, + &LearningData::default(), + &empty_scope, + &SrsSettings::default(), + ) + .unwrap() + .is_empty() + ); + + let no_black_items = StatsScope::for_repertoire(id, LearningSide::Black, NOW); + let rows = line_learning_analytics( + &library, + &LearningData::default(), + &no_black_items, + &SrsSettings::default(), + ) + .unwrap(); + assert!(rows.is_empty()); + assert!(rows.iter().all(|row| !row.line_learnt && !row.line_fresh)); +} + +#[test] +fn line_scope_honours_max_depth_disable_and_branch_root() { + let (mut library, id) = single_repertoire(branching_pgn()); + let learning = LearningData::default(); + let depth_scope = scope(id.clone()).with_max_depth(Some(2)); + let depth = line_learning_analytics(&library, &learning, &depth_scope, &SrsSettings::default()) + .unwrap(); + assert_eq!(depth.len(), 2); + assert!( + depth + .iter() + .all(|row| row.line.len() == 2 && row.summary.total == 1) + ); + + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&strings(&["e2e4", "c7c5"]), true) + .unwrap(); + let selected = scope(id.clone()); + let disabled = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(disabled.len(), 1); + assert!(!disabled[0].line.starts_with(&strings(&["e2e4", "c7c5"]))); + + let mut include_inactive = selected.clone(); + include_inactive.only_active = false; + let inactive = line_learning_analytics( + &library, + &learning, + &include_inactive, + &SrsSettings::default(), + ) + .unwrap(); + assert_eq!(inactive.len(), 2); + + let root = strings(&["e2e4", "e7e5"]); + let rooted = line_learning_analytics( + &library, + &learning, + &selected.with_branch_root(root.clone()), + &SrsSettings::default(), + ) + .unwrap(); + assert_eq!(rooted.len(), 1); + assert!(rooted[0].line.starts_with(&root)); + assert_eq!( + rooted[0].line, + strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5"]) + ); + assert_eq!(rooted[0].summary.total, 2); +} + +#[test] +fn line_projection_is_deterministic_and_sorted() { + let mut library = Library::default(); + let first = add_repertoire(&mut library, "First", branching_pgn()); + let second = add_repertoire(&mut library, "Second", branching_pgn()); + let selected = StatsScope::new([first, second], LearningSide::White, NOW); + let mut learning = LearningData::default(); + for key in active_learning_keys(&library, &selected).unwrap() { + learning.ensure_item(key); + } + let before = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + let mut sorted = before.clone(); + sorted.sort_by(|left, right| { + (&left.repertoire_id, &left.line).cmp(&(&right.repertoire_id, &right.line)) + }); + assert_eq!(before, sorted); + + learning.items.reverse(); + let after = + line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); + assert_eq!(before, after); +} diff --git a/crates/trainer/src/repertoire/migration.rs b/crates/trainer/src/repertoire/migration.rs new file mode 100644 index 0000000..2348973 --- /dev/null +++ b/crates/trainer/src/repertoire/migration.rs @@ -0,0 +1,104 @@ +#![allow(dead_code)] + +use std::cmp::Ordering; +use std::collections::BTreeMap; + +use crate::repertoire::learning::{LearningData, LearningItem, LearningItemKey}; +use crate::repertoire::stats::{MoveStats, StatsData, TrainingMode}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MigrationReport { + /// Legacy records coalesced into an existing shared learning item. + pub merged: usize, + /// Shared keys whose source records disagreed about streak or schedule. + pub conflicts: usize, + pub skipped_both: usize, +} + +pub(super) fn migrate_v2(stats: &StatsData) -> (LearningData, MigrationReport) { + let mut report = MigrationReport::default(); + let mut groups: BTreeMap> = BTreeMap::new(); + for entry in &stats.move_stats { + if entry.key.mode == TrainingMode::Both && entry.key.expected_uci.is_empty() { + report.skipped_both = report.skipped_both.saturating_add(1); + continue; + } + groups + .entry(LearningItemKey::local( + entry.key.position_fen4.clone(), + entry.key.expected_uci.clone(), + )) + .or_default() + .push(entry); + } + + let items = groups + .into_iter() + .filter_map(|(key, entries)| { + let mut iter = entries.iter().copied(); + let mut latest = iter.next()?; + for entry in iter { + if compare_recency(entry, latest) == Ordering::Greater { + latest = entry; + } + } + + report.merged = report + .merged + .saturating_add(entries.len().saturating_sub(1)); + if entries.iter().any(|entry| { + entry.streak != latest.streak + || entry.due != latest.due + || entry.interval_seconds != latest.interval_seconds + }) { + report.conflicts = report.conflicts.saturating_add(1); + } + + let mut item = LearningItem::new(key); + item.introduced = entries + .iter() + .any(|entry| entry.attempts > 0 || entry.due.is_some()); + if latest.streak < 0 { + item.wrong_streak = latest.streak.unsigned_abs(); + } else { + item.correct_streak = latest.streak as u32; + } + item.last_review_at = latest.last_seen; + item.next_review_at = entries.iter().filter_map(|entry| entry.due).min(); + item.previous_interval_seconds = + latest + .interval_seconds + .or_else(|| match (latest.due, latest.last_seen) { + (Some(due), Some(last_seen)) if due > last_seen => { + Some(due.saturating_sub(last_seen)) + } + _ => None, + }); + Some(item) + }) + .collect(); + + ( + LearningData { + items, + attempts: Vec::new(), + extensions: BTreeMap::new(), + }, + report, + ) +} + +fn compare_recency(left: &MoveStats, right: &MoveStats) -> Ordering { + left.last_seen + .cmp(&right.last_seen) + .then_with(|| left.key.repertoire_id.cmp(&right.key.repertoire_id)) + .then_with(|| mode_rank(left.key.mode).cmp(&mode_rank(right.key.mode))) +} + +fn mode_rank(mode: TrainingMode) -> u8 { + match mode { + TrainingMode::White => 0, + TrainingMode::Black => 1, + TrainingMode::Both => 2, + } +} diff --git a/crates/trainer/src/repertoire/mod.rs b/crates/trainer/src/repertoire/mod.rs new file mode 100644 index 0000000..183f091 --- /dev/null +++ b/crates/trainer/src/repertoire/mod.rs @@ -0,0 +1,89 @@ +//! Versioned opening repertoires, tree training and their persistent stores. +//! +//! This module is independent from the legacy line trainer in the crate root. + +mod aggregate; +mod branch_analytics; +mod learning; +mod learning_analytics; +mod learning_graph; +mod learning_modes; +mod learning_session; +mod line_analytics; +mod model; +mod scope; +mod srs; +mod stats; +mod store; +mod tree; + +pub use aggregate::{ + LearningAggregate, RepertoireStatus, aggregate, global_total_invariant_violation, is_uncertain, + log_global_total_invariant, +}; +pub use branch_analytics::{BranchLearningAnalytics, branch_learning_analytics}; +pub use learning::{ + AttemptApplication, IndependentOutcome, IndependentResult, LOCAL_PROFILE_ID, LearningData, + LearningError, LearningItem, LearningItemKey, RECENT_INDEPENDENT_OUTCOMES_LIMIT, + TrainingAttempt, TrainingEventType, WrongMoveStats, is_resistant, +}; +pub use learning_analytics::{ + AttemptsHistogram, CorrectStreakHistogram, LearningSnapshot, LocalDatePolicy, + MoveLearningAnalytics, MoveLearningStatus, SCHEDULED_MONTH_SECONDS, SCHEDULED_WEEK_SECONDS, + SCHEDULED_YEAR_SECONDS, ScheduledBuckets, SequenceHistograms, WrongStreakHistogram, + attempts_histogram, correct_streak_histogram, move_learning_analytics, scheduled_buckets, + scoped_move_learning_analytics, sequence_histograms, wrong_streak_histogram, +}; +pub use learning_graph::{ + LearningGraphError, LearningItemMembership, ResetImpactProjection, ResetRepertoireImpact, + ScopedLearningAggregate, StatsScope, active_learning_keys, active_learning_memberships, + aggregate_scope, reset_impact, +}; +pub use learning_modes::LearningPriority; +pub use learning_session::{ + LearningContextPolicy, LearningContextStep, LearningPosition, LearningPresentation, + LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, LearningSessionTarget, +}; +pub use line_analytics::{LineLearningAnalytics, line_learning_analytics}; +pub use model::{ + DEFAULT_MAX_PLIES, LIBRARY_VERSION, LearningSide, LegacyMigrationReport, Library, MergeReport, + Repertoire, RepertoireError, RepertoireId, +}; +pub use scope::{TrainingScope, TrainingScopeKey}; +pub use srs::{ + DEFAULT_GROWTH_FACTOR, FIRST_CORRECT_DELAY_SECONDS, MIN_PRACTICAL_INTERVAL_SECONDS, + MISTAKE_DELAY_SECONDS, PREVIEW_DELAY_SECONDS, SRS_MAX_INTERVAL_SECONDS, SrsSettings, + UNCERTAIN_INTERVAL_DIVISOR, UNCERTAIN_MIN_GRACE_SECONDS, apply_attempt, + apply_independent_correct, apply_independent_wrong, apply_preview, +}; +pub use stats::{ + AttemptRecord, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord, RunStats, + STATS_VERSION, StatsData, TrainingMode, +}; +pub use store::{ + LEARNING_STORE_VERSION, LearningSession, LearningStore, LearningStoreData, LibraryStore, + MigrationReport, PersistedAttempt, PersistedLearningReset, PersistedLearningSnapshot, + PersistedSessionAttempt, StatsStore, StoreError, +}; +pub use tree::{Candidate, RepertoireTree, fen4}; + +#[cfg(test)] +mod acceptance_tests; +#[cfg(test)] +mod advanced_tests; +#[cfg(test)] +mod analytics_tests; +#[cfg(test)] +mod branch_tests; +#[cfg(test)] +mod daily_tests; +#[cfg(test)] +mod graph_tests; +#[cfg(test)] +mod line_tests; +#[cfg(test)] +mod mode_tests; +#[cfg(test)] +mod session_tests; +#[cfg(test)] +mod tests; diff --git a/crates/trainer/src/repertoire/mode_tests.rs b/crates/trainer/src/repertoire/mode_tests.rs new file mode 100644 index 0000000..b51b7b1 --- /dev/null +++ b/crates/trainer/src/repertoire/mode_tests.rs @@ -0,0 +1,695 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::*; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 24 * 60 * 60; +static NEXT_DIR: AtomicU64 = AtomicU64::new(1); + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let sequence = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "cp-learning-modes-{}-{}-{name}", + std::process::id(), + sequence + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn path(&self) -> PathBuf { + self.0.join("learning.json") + } + + fn store(&self) -> LearningStore { + LearningStore::new(self.path()) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { + library + .create(name, &chess_core::parse_str(pgn).game) + .unwrap() +} + +fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { + let mut library = Library::default(); + let id = add_repertoire(&mut library, "Test", pgn); + (library, id) +} + +fn scope(id: RepertoireId, side: LearningSide) -> StatsScope { + StatsScope::for_repertoire(id, side, NOW) +} + +fn key_for(library: &Library, scope: &StatsScope, expected_uci: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected_uci) + .unwrap() + .key +} + +fn mode_session( + id: &str, + library: &Library, + learning: &LearningData, + scope: StatsScope, + mode: QueueMode, +) -> LearningSessionSnapshot { + LearningSessionSnapshot::new_with_mode( + id, + library, + learning, + scope, + SrsSettings::default(), + mode, + ) + .unwrap() +} + +fn queue_labels(session: &LearningSessionSnapshot) -> Vec { + session + .queue + .iter() + .map(|target| format!("{}@{}", target.key.expected_uci, target.min_depth)) + .collect() +} + +fn apply(learning: &mut LearningData, attempt: TrainingAttempt) { + assert_eq!( + learning.apply_attempt(attempt, &SrsSettings::default()), + Ok(AttemptApplication::Applied) + ); +} + +fn complete_target( + session: &mut LearningSessionSnapshot, + learning: &mut LearningData, + library: &Library, + id_prefix: &str, + happened_at: i64, +) { + let original_index = session.current_index; + let original_cycle = session.cycle; + let original_key = session.current_target().unwrap().key.clone(); + for step in 0..32 { + match session.phase { + LearningSessionPhase::AdvancingContext => { + let attempt = session + .advance_context( + library, + format!("{id_prefix}-{original_cycle}-{original_index}-context-{step}"), + happened_at, + ) + .unwrap(); + apply(learning, attempt); + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => { + let expected = session.current_expected_uci().unwrap().to_owned(); + let attempt = session + .play_uci( + library, + &expected, + format!("{id_prefix}-{original_cycle}-{original_index}-answer-{step}"), + happened_at, + Some(100 + step), + ) + .unwrap(); + apply(learning, attempt); + } + phase => panic!("unexpected phase while completing target: {phase:?}"), + } + if session.phase == LearningSessionPhase::Finished + || session.current_index != original_index + || session.cycle != original_cycle + || session + .current_target() + .is_none_or(|target| target.key != original_key) + { + return; + } + } + panic!("target did not complete"); +} + +fn commit( + store: &LearningStore, + session: &mut LearningSessionSnapshot, + attempt: TrainingAttempt, +) -> PersistedSessionAttempt { + let persisted = store.apply_attempt_and_session(attempt, session).unwrap(); + *session = persisted.session.clone(); + persisted +} + +fn introduced_at(learning: &mut LearningData, key: LearningItemKey, last_review_at: i64) { + let item = learning.ensure_item(key); + item.introduced = true; + item.correct_streak = 1; + item.correct_count = 1; + item.last_review_at = Some(last_review_at); + item.last_correct_at = Some(last_review_at); + item.next_review_at = Some(NOW + 10 * DAY); + item.previous_interval_seconds = Some(DAY); +} + +fn journal_attempt(key: &LearningItemKey, id: &str, happened_at: i64) -> TrainingAttempt { + TrainingAttempt { + user_id: key.user_id.clone(), + position_fen4: key.position_fen4.clone(), + client_attempt_id: id.into(), + session_id: "at22".into(), + event_type: TrainingEventType::CorrectIndependent, + expected_uci: key.expected_uci.clone(), + actual_uci: Some(key.expected_uci.clone()), + response_time_ms: Some(200), + happened_at, + } +} + +#[test] +fn learning_priorities_use_pgn_order_depth_rav_and_deterministic_bfs_fallback() { + let (library, id) = single_repertoire( + "1. e4 e5 (1... c5 2. c4 Nc6 (2... e6 3. g3)) (1... Nf6 2. d4) 2. Nf3 Nc6 *", + ); + let selected = scope(id, LearningSide::White); + let learning = LearningData::default(); + let order = |priority| { + queue_labels(&mode_session( + "priority", + &library, + &learning, + selected.clone().with_learning_priority(priority), + QueueMode::ReviewInOrder, + )) + }; + + assert_eq!( + order(LearningPriority::DepthFirst), + ["e2e4@1", "g1f3@3", "c2c4@3", "g2g3@5", "d2d4@3"] + ); + assert_eq!( + order(LearningPriority::BreadthOverDepth), + ["e2e4@1", "g1f3@3", "c2c4@3", "d2d4@3", "g2g3@5"] + ); + assert_eq!( + order(LearningPriority::MainLinesFirst), + ["e2e4@1", "g1f3@3", "c2c4@3", "d2d4@3", "g2g3@5"] + ); + assert_eq!( + order(LearningPriority::CommonPositionsFirst), + order(LearningPriority::BreadthOverDepth) + ); + + let memberships = active_learning_memberships(&library, &selected).unwrap(); + let nested = memberships + .iter() + .find(|membership| membership.key.expected_uci == "g2g3") + .unwrap(); + assert_eq!(nested.min_depth, 5); + assert_eq!(nested.variation_depth, 2); + assert!( + memberships + .iter() + .all(|membership| { membership.pgn_order > 0 }) + ); + assert!(matches!( + LearningSessionSnapshot::new_with_mode( + "practice", + &library, + &learning, + selected, + SrsSettings::default(), + QueueMode::Practice, + ), + Err(LearningSessionError::UnsupportedMode(QueueMode::Practice)) + )); +} + +#[test] +fn at_20_review_in_order_covers_each_key_once_updates_srs_and_wraps() { + let (library, id) = single_repertoire("1. e4 e5 (1... c5 2. c4) 2. Nf3 Nc6 *"); + let selected = scope(id, LearningSide::White); + let mut learning = LearningData::default(); + let mut session = mode_session( + "at20", + &library, + &learning, + selected, + QueueMode::ReviewInOrder, + ); + let expected = ["e2e4", "g1f3", "c2c4"]; + assert_eq!( + session + .queue + .iter() + .map(|target| target.key.expected_uci.as_str()) + .collect::>(), + expected + ); + + let mut first_cycle = Vec::new(); + for expected_uci in expected { + let current = session.current_target().unwrap().key.clone(); + assert_eq!(current.expected_uci, expected_uci); + assert!(!session.completed_keys.contains(¤t)); + first_cycle.push(current.clone()); + complete_target(&mut session, &mut learning, &library, "at20-first", NOW); + assert_eq!(learning.item(¤t).unwrap().correct_count, 1); + assert_eq!(learning.item(¤t).unwrap().correct_streak, 1); + assert_eq!( + learning.item(¤t).unwrap().next_review_at, + Some(NOW + DAY) + ); + } + assert_eq!( + first_cycle.len(), + first_cycle.iter().collect::>().len() + ); + assert_eq!(session.cycle, 1); + assert!(session.completed_keys.is_empty()); + assert_eq!(session.current_target().unwrap().key.expected_uci, "e2e4"); + + let e4 = session.current_target().unwrap().key.clone(); + complete_target( + &mut session, + &mut learning, + &library, + "at20-second", + NOW + DAY, + ); + assert_eq!(learning.item(&e4).unwrap().correct_count, 2); + assert_eq!(learning.item(&e4).unwrap().correct_streak, 2); + assert_eq!(session.cycle, 1); + assert!(session.completed_keys.contains(&e4)); + assert!( + !session + .completed_keys + .contains(&session.current_target().unwrap().key) + ); +} + +#[test] +fn review_cursor_resumes_mid_cycle_and_duplicate_event_does_not_advance_twice() { + let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 *"); + let selected = scope(id, LearningSide::White); + let learning = LearningData::default(); + let dir = TestDir::new("review-resume"); + let store = dir.store(); + let mut session = mode_session( + "review-resume", + &library, + &learning, + selected, + QueueMode::ReviewInOrder, + ); + let attempt = session + .play_uci(&library, "e2e4", "review-first", NOW, Some(100)) + .unwrap(); + commit(&store, &mut session, attempt.clone()); + let bytes = std::fs::read(dir.path()).unwrap(); + + let restored = store + .load() + .unwrap() + .session_snapshot("review-resume") + .cloned() + .unwrap() + .resume(&library) + .unwrap(); + assert_eq!(restored.current_index, 1); + assert_eq!(restored.cycle, 0); + assert_eq!(restored.completed_keys, session.completed_keys); + assert_eq!(restored.current_target().unwrap().key.expected_uci, "g1f3"); + + let mut duplicate_next = restored.clone(); + duplicate_next.current_index = 0; + duplicate_next.completed_keys.clear(); + duplicate_next.cycle = 9; + let duplicate = store + .apply_attempt_and_session(attempt, &mut duplicate_next) + .unwrap(); + assert_eq!(duplicate.application, AttemptApplication::Duplicate); + assert_eq!(duplicate.session, restored); + assert_eq!(duplicate.learning.attempts.len(), 1); + assert_eq!(std::fs::read(dir.path()).unwrap(), bytes); +} + +#[test] +fn at_21_variation_wrong_waits_for_the_next_due_pass_not_less_than_thirty_seconds() { + let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); + let selected = scope(id, LearningSide::White); + let mut learning = LearningData::default(); + for expected in ["e2e4", "g1f3", "f1b5"] { + let key = key_for(&library, &selected, expected); + introduced_at(&mut learning, key.clone(), NOW - DAY); + learning.ensure_item(key).next_review_at = Some(NOW); + } + let e4 = key_for(&library, &selected, "e2e4"); + let mut session = LearningSessionSnapshot::new( + "at21", + &library, + &learning, + selected.clone(), + SrsSettings::default(), + ) + .unwrap(); + let original_queue = session.queue.clone(); + + let wrong = session + .play_uci(&library, "d2d4", "at21-wrong", NOW, Some(400)) + .unwrap(); + apply(&mut learning, wrong); + assert_eq!(learning.item(&e4).unwrap().next_review_at, Some(NOW + 30)); + assert_eq!(session.queue, original_queue); + assert_eq!(session.current_target().unwrap().key, e4); + let replay = session + .play_uci(&library, "e2e4", "at21-replay", NOW + 1, Some(900)) + .unwrap(); + apply(&mut learning, replay); + assert_eq!(session.queue, original_queue); + assert_eq!(session.current_target().unwrap().key.expected_uci, "g1f3"); + assert_eq!( + session + .queue + .iter() + .filter(|target| target.key == e4) + .count(), + 1 + ); + + complete_target(&mut session, &mut learning, &library, "at21-nf3", NOW + 2); + complete_target(&mut session, &mut learning, &library, "at21-bb5", NOW + 3); + assert_eq!(session.phase, LearningSessionPhase::Finished); + + session.stats_scope.as_of = NOW + 29; + assert_eq!(session.start_next_pass(&library, &learning).unwrap(), 0); + session.stats_scope.as_of = NOW + 30; + assert_eq!(session.start_next_pass(&library, &learning).unwrap(), 1); + assert_eq!(session.current_target().unwrap().key, e4); +} + +#[test] +fn least_recent_prioritizes_unseen_then_oldest_and_skips_early_checked_context() { + let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); + let selected = scope(id, LearningSide::White); + let e4 = key_for(&library, &selected, "e2e4"); + let nf3 = key_for(&library, &selected, "g1f3"); + let bb5 = key_for(&library, &selected, "f1b5"); + let mut learning = LearningData::default(); + introduced_at(&mut learning, e4.clone(), NOW - 10); + introduced_at(&mut learning, nf3.clone(), NOW - 100); + + let unseen_first = mode_session( + "least-unseen", + &library, + &learning, + selected.clone(), + QueueMode::LeastRecent, + ); + assert_eq!( + unseen_first + .queue + .iter() + .map(|target| target.key.expected_uci.as_str()) + .collect::>(), + ["f1b5", "g1f3", "e2e4"] + ); + + introduced_at(&mut learning, bb5.clone(), NOW - 50); + let mut session = mode_session( + "least-context", + &library, + &learning, + selected, + QueueMode::LeastRecent, + ); + assert_eq!( + session + .queue + .iter() + .map(|target| target.key.expected_uci.as_str()) + .collect::>(), + ["g1f3", "f1b5", "e2e4"] + ); + assert_eq!( + session.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert_eq!(session.current_expected_uci(), Some("e2e4")); + + complete_target(&mut session, &mut learning, &library, "least-nf3", NOW); + assert!(session.completed_keys.contains(&e4)); + assert!(session.completed_keys.contains(&nf3)); + complete_target(&mut session, &mut learning, &library, "least-bb5", NOW + 1); + assert_eq!(session.phase, LearningSessionPhase::Finished); + assert_eq!(session.completed_keys.len(), 3); + for key in [e4, nf3, bb5] { + let independent = learning + .attempts + .iter() + .filter(|attempt| attempt.item_key() == key && attempt.event_type.is_independent()) + .count(); + assert_eq!(independent, 1, "duplicate review for {key:?}"); + } +} + +#[test] +fn at_22_shared_reset_preserves_cursor_journal_extensions_and_review_reset_preserves_srs() { + let mut library = Library::default(); + let first = add_repertoire(&mut library, "First", "1. e4 e5 2. Nf3 *"); + let second = add_repertoire(&mut library, "Second", "1. e4 c5 2. c4 *"); + let first_scope = scope(first, LearningSide::White); + let second_scope = scope(second, LearningSide::White); + let shared = key_for(&library, &first_scope, "e2e4"); + let nf3 = key_for(&library, &first_scope, "g1f3"); + let second_only = key_for(&library, &second_scope, "c2c4"); + let mut learning = LearningData::default(); + introduced_at(&mut learning, shared.clone(), NOW - 3 * DAY); + introduced_at(&mut learning, nf3.clone(), NOW - 2 * DAY); + introduced_at(&mut learning, second_only.clone(), NOW - DAY); + learning + .ensure_item(shared.clone()) + .independent_response_times_ms + .push(500); + learning + .attempts + .push(journal_attempt(&shared, "at22-old", NOW - DAY)); + let second_before = learning.item(&second_only).unwrap().clone(); + let pgn_before: Vec<_> = library + .repertoires + .iter() + .map(|repertoire| repertoire.pgn.clone()) + .collect(); + + let impact = reset_impact(&library, &first_scope).unwrap(); + assert_eq!((impact.reset_count, impact.shared_count), (2, 1)); + assert_eq!( + impact + .affected_repertoires + .iter() + .map(|repertoire| repertoire.name.as_str()) + .collect::>(), + BTreeSet::from(["First", "Second"]) + ); + + let dir = TestDir::new("shared-reset"); + let store = dir.store(); + std::fs::write( + dir.path(), + serde_json::to_vec_pretty(&LearningStoreData { + learning, + ..LearningStoreData::default() + }) + .unwrap(), + ) + .unwrap(); + let mut review = mode_session( + "at22", + &library, + &store.load().unwrap().learning, + first_scope.clone(), + QueueMode::ReviewInOrder, + ); + let review_attempt = review + .play_uci(&library, "e2e4", "at22-review", NOW, Some(250)) + .unwrap(); + commit(&store, &mut review, review_attempt); + let cursor_before = store + .load() + .unwrap() + .session_snapshot("at22") + .cloned() + .unwrap(); + assert_eq!(cursor_before.current_index, 1); + assert_eq!(cursor_before.completed_keys.len(), 1); + + let marker = serde_json::json!({"preserved": [1, {"nested": true}]}); + let mut raw: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.path()).unwrap()).unwrap(); + raw["future_root"] = marker.clone(); + raw["learning"]["future_learning"] = marker.clone(); + raw["learning"]["attempts"][0]["future_attempt"] = marker.clone(); + raw["session_snapshots"][0]["future_snapshot"] = marker.clone(); + raw["session_snapshots"][0]["queue"][0]["future_target"] = marker.clone(); + raw["legacy_practice"] = serde_json::json!({"raw_legacy": marker.clone()}); + let shared_index = raw["learning"]["items"] + .as_array() + .unwrap() + .iter() + .position(|item| { + item["key"]["position_fen4"] == serde_json::json!(shared.position_fen4.clone()) + && item["key"]["expected_uci"] == serde_json::json!("e2e4") + }) + .unwrap(); + raw["learning"]["items"][shared_index]["future_item"] = marker.clone(); + std::fs::write(dir.path(), serde_json::to_vec_pretty(&raw).unwrap()).unwrap(); + + #[cfg(unix)] + let old_path = dir.0.join("before-reset.json"); + #[cfg(unix)] + std::fs::hard_link(dir.path(), &old_path).unwrap(); + + let reset = store + .reset_learning(active_learning_keys(&library, &first_scope).unwrap()) + .unwrap(); + assert_eq!(reset.reset_count, 2); + assert_eq!( + reset.learning.item(&shared), + Some(&LearningItem::new(shared.clone())) + ); + assert_eq!( + reset.learning.item(&nf3), + Some(&LearningItem::new(nf3.clone())) + ); + assert_eq!(reset.learning.item(&second_only), Some(&second_before)); + assert!(reset.learning.item(&shared).unwrap().is_unseen()); + assert!(reset.learning.item(&nf3).unwrap().is_unseen()); + assert_eq!(reset.learning.attempts.len(), 2); + assert_eq!( + store.load().unwrap().session_snapshot("at22").unwrap(), + &cursor_before + ); + let second_summary = aggregate_scope( + &library, + &reset.learning, + &second_scope, + &SrsSettings::default(), + ) + .unwrap(); + assert!( + second_summary + .items + .iter() + .find(|item| item.key == shared) + .unwrap() + .is_unseen() + ); + assert_eq!( + library + .repertoires + .iter() + .map(|repertoire| repertoire.pgn.clone()) + .collect::>(), + pgn_before + ); + + let persisted_raw: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.path()).unwrap()).unwrap(); + for pointer in [ + "/future_root", + "/learning/future_learning", + "/learning/attempts/0/future_attempt", + "/session_snapshots/0/future_snapshot", + "/session_snapshots/0/queue/0/future_target", + "/legacy_practice/raw_legacy", + ] { + assert_eq!(persisted_raw.pointer(pointer), Some(&marker), "{pointer}"); + } + assert_eq!( + persisted_raw["learning"]["items"][shared_index]["future_item"], + marker + ); + #[cfg(unix)] + { + let old = LearningStore::new(old_path).load().unwrap(); + assert!(old.learning.item(&shared).unwrap().introduced); + assert_eq!(old.session_snapshot("at22"), Some(&cursor_before)); + } + + let duplicate = store + .apply_attempt( + journal_attempt(&shared, "at22-review", NOW), + &SrsSettings::default(), + ) + .unwrap(); + assert_eq!(duplicate.application, AttemptApplication::Duplicate); + assert!(duplicate.learning.item(&shared).unwrap().is_unseen()); + let fresh = store + .apply_attempt( + journal_attempt(&shared, "at22-fresh", NOW + DAY), + &SrsSettings::default(), + ) + .unwrap(); + let fresh_shared = fresh.learning.item(&shared).unwrap(); + assert_eq!(fresh_shared.correct_streak, 1); + assert_eq!(fresh_shared.correct_count, 1); + assert_eq!(fresh_shared.wrong_count, 0); + assert_eq!(fresh_shared.accuracy_percent(), Some(100.0)); + assert_eq!(fresh_shared.independent_response_times_ms, [200]); + assert_eq!(fresh.learning.attempts.len(), 3); + + let before_review_reset = store.load().unwrap().learning; + store.reset_review_order(&mut review).unwrap(); + assert_eq!(review.current_index, 0); + assert_eq!(review.cycle, 0); + assert!(review.completed_keys.is_empty()); + assert_eq!(store.load().unwrap().learning, before_review_reset); +} + +#[test] +fn old_scope_and_mode_snapshot_defaults_remain_deserializable() { + let (library, id) = single_repertoire("1. e4 *"); + let selected = scope(id, LearningSide::White); + let session = mode_session( + "defaults", + &library, + &LearningData::default(), + selected, + QueueMode::ReviewInOrder, + ); + let mut raw = serde_json::to_value(session).unwrap(); + raw.as_object_mut().unwrap().remove("cycle"); + raw["stats_scope"] + .as_object_mut() + .unwrap() + .remove("learning_priority"); + for field in ["pgn_order", "variation_depth"] { + raw["queue"][0].as_object_mut().unwrap().remove(field); + } + + let restored: LearningSessionSnapshot = serde_json::from_value(raw).unwrap(); + assert_eq!(restored.cycle, 0); + assert_eq!( + restored.stats_scope.learning_priority, + LearningPriority::DepthFirst + ); + assert_eq!(restored.queue[0].pgn_order, 0); + assert_eq!(restored.queue[0].variation_depth, 0); + restored.resume(&library).unwrap(); +} diff --git a/crates/trainer/src/repertoire/model.rs b/crates/trainer/src/repertoire/model.rs new file mode 100644 index 0000000..04aeebf --- /dev/null +++ b/crates/trainer/src/repertoire/model.rs @@ -0,0 +1,789 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use chess_core::shakmaty::uci::UciMove; +use chess_core::shakmaty::{CastlingMode, Color, Position}; +use chess_core::{EditError, Game, MoveKind, NodeId, StartPosition, paste}; +use serde::{Deserialize, Serialize}; +use web_time::{SystemTime, UNIX_EPOCH}; + +use super::tree::{RepertoireTree, fen4}; + +pub const LIBRARY_VERSION: u32 = 1; +pub const DEFAULT_MAX_PLIES: u32 = 20; + +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct RepertoireId(String); + +impl RepertoireId { + pub fn as_str(&self) -> &str { + &self.0 + } + + fn new() -> Self { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed); + Self(format!("r-{nanos:x}-{}-{sequence:x}", std::process::id())) + } + + pub(crate) fn legacy(start: &str) -> Self { + Self(format!("legacy-{:016x}", stable_hash(start.as_bytes()))) + } +} + +impl fmt::Display for RepertoireId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum LearningSide { + White, + Black, +} + +impl LearningSide { + pub fn color(self) -> Color { + match self { + Self::White => Color::White, + Self::Black => Color::Black, + } + } +} + +impl From for LearningSide { + fn from(color: Color) -> Self { + match color { + Color::White => Self::White, + Color::Black => Self::Black, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Repertoire { + pub id: RepertoireId, + pub name: String, + pub pgn: String, + pub max_plies: u32, + pub disabled_prefixes: Vec>, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub main_answer_overrides: BTreeMap, + pub path: Option, + pub detached: bool, +} + +impl Default for Repertoire { + fn default() -> Self { + Self { + id: RepertoireId::new(), + name: String::new(), + pgn: Game::new().to_pgn(), + max_plies: DEFAULT_MAX_PLIES, + disabled_prefixes: Vec::new(), + main_answer_overrides: BTreeMap::new(), + path: None, + detached: false, + } + } +} + +impl Repertoire { + pub fn game(&self) -> Game { + chess_core::parse_str(&self.pgn).game + } + + pub fn set_max_plies(&mut self, max_plies: u32) { + self.max_plies = max_plies; + } + + pub fn set_prefix_disabled( + &mut self, + prefix: &[String], + disabled: bool, + ) -> Result<(), RepertoireError> { + if prefix.is_empty() || prefix.iter().any(|m| m.is_empty()) { + return Err(RepertoireError::EmptyDisabledPrefix); + } + self.disabled_prefixes + .retain(|existing| existing.as_slice() != prefix); + if disabled { + self.disabled_prefixes.push(prefix.to_vec()); + } + self.disabled_prefixes.sort(); + self.disabled_prefixes.dedup(); + Ok(()) + } + + pub fn is_prefix_disabled(&self, path: &[String]) -> bool { + self.disabled_prefixes + .iter() + .any(|prefix| path.starts_with(prefix)) + } + + pub fn main_answer_override(&self, position_fen4: &str) -> Option<&str> { + self.main_answer_overrides + .get(position_fen4) + .map(String::as_str) + } + + pub fn set_main_answer_override( + &mut self, + position_fen4: &str, + expected_uci: &str, + side: LearningSide, + ) -> Result<(), RepertoireError> { + let tree = RepertoireTree::new(self); + let game = tree.game(); + let mut position_found = false; + for node in game.attached_nodes() { + if tree.position_key(node) != Some(position_fen4) || tree.path(node).is_none() { + continue; + } + position_found = true; + let actual_side = game + .position(node) + .map(|position| LearningSide::from(position.turn())); + if actual_side != Some(side) { + return Err(RepertoireError::MainAnswerWrongSide { + position_fen4: position_fen4.to_owned(), + expected: side, + actual: actual_side, + }); + } + let exists = game.children(node).iter().any(|child| { + let Some(game_move) = game.game_move(*child) else { + return false; + }; + match game_move.kind { + MoveKind::Normal(mv) => { + mv.to_uci(CastlingMode::Standard).to_string() == expected_uci + } + MoveKind::Null => false, + } + }); + if exists { + self.main_answer_overrides + .insert(position_fen4.to_owned(), expected_uci.to_owned()); + return Ok(()); + } + } + if position_found { + Err(RepertoireError::MainAnswerMoveNotFound { + position_fen4: position_fen4.to_owned(), + expected_uci: expected_uci.to_owned(), + }) + } else { + Err(RepertoireError::MainAnswerPositionNotFound( + position_fen4.to_owned(), + )) + } + } + + pub fn clear_main_answer_override(&mut self, position_fen4: &str) -> Option { + self.main_answer_overrides.remove(position_fen4) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct Library { + pub version: u32, + pub revision: u64, + pub repertoires: Vec, +} + +impl Default for Library { + fn default() -> Self { + Self { + version: LIBRARY_VERSION, + revision: 0, + repertoires: Vec::new(), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MergeReport { + pub added_nodes: usize, + pub merged_nodes: usize, + pub annotation_changes: usize, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LegacyMigrationReport { + pub repertoires: usize, + pub lines: usize, + pub skipped: Vec, +} + +#[derive(Debug)] +pub enum RepertoireError { + EmptyName, + NotFound(RepertoireId), + DuplicateId(RepertoireId), + EmptyDisabledPrefix, + MainAnswerPositionNotFound(String), + MainAnswerMoveNotFound { + position_fen4: String, + expected_uci: String, + }, + MainAnswerWrongSide { + position_fen4: String, + expected: LearningSide, + actual: Option, + }, + DifferentStart { + expected: String, + actual: String, + }, + UnparsedMerge, + Merge(String), + Edit(EditError), +} + +impl fmt::Display for RepertoireError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyName => f.write_str("repertoire name must not be empty"), + Self::NotFound(id) => write!(f, "repertoire not found: {id}"), + Self::DuplicateId(id) => write!(f, "repertoire id is already present: {id}"), + Self::EmptyDisabledPrefix => f.write_str("disabled UCI prefix must not be empty"), + Self::MainAnswerPositionNotFound(position) => { + write!( + f, + "main-answer position is not present in the PGN: {position}" + ) + } + Self::MainAnswerMoveNotFound { + position_fen4, + expected_uci, + } => write!( + f, + "main answer {expected_uci} is not a PGN move at {position_fen4}" + ), + Self::MainAnswerWrongSide { + position_fen4, + expected, + actual, + } => write!( + f, + "main answer side mismatch at {position_fen4}: requested {expected:?}, position has {actual:?}" + ), + Self::DifferentStart { expected, actual } => write!( + f, + "different starting positions: repertoire has {expected}, imported game has {actual}" + ), + Self::UnparsedMerge => { + f.write_str("cannot merge an unparsed PGN tail into an existing move") + } + Self::Merge(message) => write!(f, "PGN merge failed: {message}"), + Self::Edit(error) => error.fmt(f), + } + } +} + +impl std::error::Error for RepertoireError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Edit(error) => Some(error), + _ => None, + } + } +} + +impl From for RepertoireError { + fn from(error: EditError) -> Self { + Self::Edit(error) + } +} + +impl Library { + pub fn validate(&self) -> Result<(), RepertoireError> { + let mut ids = BTreeSet::new(); + for repertoire in &self.repertoires { + if !ids.insert(repertoire.id.clone()) { + return Err(RepertoireError::DuplicateId(repertoire.id.clone())); + } + } + Ok(()) + } + + pub fn repertoire(&self, id: &RepertoireId) -> Option<&Repertoire> { + self.repertoires.iter().find(|r| &r.id == id) + } + + pub fn repertoire_mut(&mut self, id: &RepertoireId) -> Option<&mut Repertoire> { + self.repertoires.iter_mut().find(|r| &r.id == id) + } + + pub fn create_empty( + &mut self, + name: impl Into, + ) -> Result { + self.create(name, &Game::new()) + } + + pub fn create( + &mut self, + name: impl Into, + game: &Game, + ) -> Result { + let name = checked_name(name.into())?; + let id = RepertoireId::new(); + self.repertoires.push(Repertoire { + id: id.clone(), + name, + pgn: game.to_pgn(), + max_plies: DEFAULT_MAX_PLIES, + disabled_prefixes: Vec::new(), + main_answer_overrides: BTreeMap::new(), + path: None, + detached: false, + }); + Ok(id) + } + + pub fn rename( + &mut self, + id: &RepertoireId, + name: impl Into, + ) -> Result<(), RepertoireError> { + let name = checked_name(name.into())?; + self.repertoire_mut(id) + .ok_or_else(|| RepertoireError::NotFound(id.clone()))? + .name = name; + Ok(()) + } + + pub fn delete(&mut self, id: &RepertoireId) -> Result { + let index = self + .repertoires + .iter() + .position(|r| &r.id == id) + .ok_or_else(|| RepertoireError::NotFound(id.clone()))?; + Ok(self.repertoires.remove(index)) + } + + /// Merges the complete source tree. The source game is never modified; an error + /// leaves the repertoire at its previous PGN snapshot. + pub fn add_game( + &mut self, + id: &RepertoireId, + source: &Game, + ) -> Result { + let repertoire = self + .repertoire_mut(id) + .ok_or_else(|| RepertoireError::NotFound(id.clone()))?; + let mut target = repertoire.game(); + check_start(&target, source)?; + let target_is_empty = target.children(NodeId::ROOT).is_empty() + && target.node(NodeId::ROOT).is_some_and(|root| { + root.nags().is_empty() + && root.comments_before().is_empty() + && root.comments_after().is_empty() + && root.unparsed().is_empty() + }); + if target_is_empty { + repertoire.pgn = source.to_pgn(); + return Ok(MergeReport { + added_nodes: source.attached_nodes().len().saturating_sub(1), + merged_nodes: 1, + annotation_changes: 0, + }); + } + let mut report = MergeReport::default(); + merge_annotations(&mut target, NodeId::ROOT, source, NodeId::ROOT, &mut report)?; + report.merged_nodes += 1; + merge_children( + &mut target, + NodeId::ROOT, + source, + NodeId::ROOT, + true, + &mut report, + )?; + repertoire.pgn = target.to_pgn(); + Ok(report) + } + + /// Adds exactly the path from the source root through `at`, without siblings or + /// descendants of `at`. Node comments and NAGs on the selected path are merged. + pub fn add_prefix( + &mut self, + id: &RepertoireId, + source: &Game, + at: NodeId, + ) -> Result { + if !source.is_attached(at) { + return Err(RepertoireError::Merge( + "selected source node is not attached".into(), + )); + } + let repertoire = self + .repertoire_mut(id) + .ok_or_else(|| RepertoireError::NotFound(id.clone()))?; + let mut target = repertoire.game(); + check_start(&target, source)?; + let mut report = MergeReport::default(); + merge_annotations(&mut target, NodeId::ROOT, source, NodeId::ROOT, &mut report)?; + report.merged_nodes += 1; + let mut target_parent = NodeId::ROOT; + for source_node in source.path(at).into_iter().skip(1) { + target_parent = merge_node( + &mut target, + target_parent, + source, + source_node, + false, + &mut report, + )?; + } + repertoire.pgn = target.to_pgn(); + Ok(report) + } + + /// Deterministically reconstructs playable lines stored in legacy line keys. The + /// legacy aggregates remain in `StatsData::legacy_lines`; no per-move history is + /// inferred from them. + pub fn migrate_legacy_lines( + &mut self, + legacy: &serde_json::Map, + ) -> LegacyMigrationReport { + let mut groups: BTreeMap>> = BTreeMap::new(); + let mut report = LegacyMigrationReport::default(); + for key in legacy.keys() { + let Some((start, moves)) = key.split_once(" | ") else { + report.skipped.push(key.clone()); + continue; + }; + let line: Vec = moves + .split_whitespace() + .filter(|m| !m.is_empty()) + .map(str::to_owned) + .collect(); + if line.is_empty() || line.iter().any(|m| m.parse::().is_err()) { + report.skipped.push(key.clone()); + continue; + } + groups.entry(start.to_owned()).or_default().push(line); + } + for (start, mut lines) in groups { + lines.sort(); + lines.dedup(); + let id = RepertoireId::legacy(&start); + if self.repertoire(&id).is_none() { + let Ok(position) = StartPosition::from_fen(&format!("{start} 0 1")) else { + report + .skipped + .extend(lines.into_iter().map(|line| line.join(" "))); + continue; + }; + let number = self + .repertoires + .iter() + .filter(|r| r.id.as_str().starts_with("legacy-")) + .count() + + 1; + self.repertoires.push(Repertoire { + id: id.clone(), + name: format!("ПеренеÑ�ённые линии {number}"), + pgn: Game::from_start(position).to_pgn(), + max_plies: DEFAULT_MAX_PLIES, + disabled_prefixes: Vec::new(), + main_answer_overrides: BTreeMap::new(), + path: None, + detached: false, + }); + report.repertoires += 1; + } + let Some(mut game) = self.repertoire(&id).map(Repertoire::game) else { + continue; + }; + for line in lines { + match game.add_uci_line(NodeId::ROOT, &line) { + Ok(_) => report.lines += 1, + Err(_) => report.skipped.push(line.join(" ")), + } + } + if let Some(repertoire) = self.repertoire_mut(&id) { + repertoire.pgn = game.to_pgn(); + } + } + report + } +} + +fn checked_name(name: String) -> Result { + let name = name.trim(); + if name.is_empty() { + Err(RepertoireError::EmptyName) + } else { + Ok(name.to_owned()) + } +} + +fn check_start(target: &Game, source: &Game) -> Result<(), RepertoireError> { + let expected = fen4(target.start().position()); + let actual = fen4(source.start().position()); + if expected == actual { + Ok(()) + } else { + Err(RepertoireError::DifferentStart { expected, actual }) + } +} + +fn merge_children( + target: &mut Game, + target_parent: NodeId, + source: &Game, + source_parent: NodeId, + recursive: bool, + report: &mut MergeReport, +) -> Result<(), RepertoireError> { + for source_child in source.children(source_parent) { + merge_node( + target, + target_parent, + source, + *source_child, + recursive, + report, + )?; + } + Ok(()) +} + +fn merge_node( + target: &mut Game, + target_parent: NodeId, + source: &Game, + source_node: NodeId, + recursive: bool, + report: &mut MergeReport, +) -> Result { + let kind = source + .game_move(source_node) + .map(|m| m.kind) + .ok_or_else(|| RepertoireError::Merge("source node has no move".into()))?; + if let Some(existing) = target + .children(target_parent) + .iter() + .copied() + .find(|child| target.game_move(*child).is_some_and(|m| m.kind == kind)) + { + report.merged_nodes += 1; + merge_annotations(target, existing, source, source_node, report)?; + if recursive { + merge_unparsed(target, existing, source, source_node)?; + } + if recursive { + merge_children(target, existing, source, source_node, true, report)?; + } + return Ok(existing); + } + + let plain = matches!(kind, MoveKind::Normal(_)) + && source + .node(source_node) + .is_some_and(|n| n.unparsed().is_empty()); + let target_node = if plain { + let MoveKind::Normal(mv) = kind else { + return Err(RepertoireError::Merge("invalid normal move".into())); + }; + let id = target.add_line(target_parent, &[mv])?; + merge_annotations(target, id, source, source_node, report)?; + report.added_nodes += 1; + id + } else { + let text = subtree_pgn(source, source_node, recursive, recursive); + // Clipboard matching searches the entire target for a matching position and + // may choose another occurrence. An empty local target makes the graft exact: + // no matched prefix, transposition or extra branch can redirect the insertion. + let fen = target + .fen(target_parent) + .ok_or_else(|| RepertoireError::Merge("missing target parent position".into()))?; + let start = StartPosition::from_fen(&fen) + .map_err(|error| RepertoireError::Merge(error.to_string()))?; + let local = Game::from_start(start); + let mut plan = paste::plan(&local, NodeId::ROOT, &text) + .map_err(|e| RepertoireError::Merge(format!("{e:?}")))?; + if plan.at != NodeId::ROOT { + return Err(RepertoireError::Merge( + "PGN graft did not start at its root".into(), + )); + } + plan.at = target_parent; + plan.continuation = target.children(target_parent).is_empty(); + let id = target.apply_paste(&plan)?; + let count = if recursive { + subtree_len(source, source_node) + } else { + 1 + }; + report.added_nodes += count; + id + }; + if plain && recursive { + merge_children(target, target_node, source, source_node, true, report)?; + } + Ok(target_node) +} + +fn merge_unparsed( + target: &Game, + target_node: NodeId, + source: &Game, + source_node: NodeId, +) -> Result<(), RepertoireError> { + let Some(source_node) = source.node(source_node) else { + return Ok(()); + }; + if source_node.unparsed().is_empty() { + return Ok(()); + } + if target + .node(target_node) + .is_some_and(|node| node.unparsed() == source_node.unparsed()) + { + Ok(()) + } else { + Err(RepertoireError::UnparsedMerge) + } +} + +fn subtree_len(game: &Game, root: NodeId) -> usize { + let mut stack = vec![root]; + let mut count = 0; + while let Some(node) = stack.pop() { + count += 1; + stack.extend(game.children(node)); + } + count +} + +fn merge_annotations( + target: &mut Game, + target_node: NodeId, + source: &Game, + source_node: NodeId, + report: &mut MergeReport, +) -> Result<(), RepertoireError> { + let (Some(source_node), Some(current)) = (source.node(source_node), target.node(target_node)) + else { + return Err(RepertoireError::Merge("missing annotation node".into())); + }; + let nags = union(current.nags().to_vec(), source_node.nags().to_vec()); + let before = union( + current.comments_before().to_vec(), + source_node.comments_before().to_vec(), + ); + let after = union( + current.comments_after().to_vec(), + source_node.comments_after().to_vec(), + ); + let changed = nags.len() != current.nags().len() + || before.len() != current.comments_before().len() + || after.len() != current.comments_after().len(); + target.annotate(target_node, nags, after)?; + target.set_comments_before(target_node, before)?; + report.annotation_changes += usize::from(changed); + Ok(()) +} + +fn union(mut target: Vec, source: Vec) -> Vec { + for value in source { + if !target.contains(&value) { + target.push(value); + } + } + target +} + +fn subtree_pgn(source: &Game, node: NodeId, recursive: bool, raw: bool) -> String { + let fen = source + .position_before(node) + .map(|p| { + chess_core::shakmaty::fen::Fen::from_position( + p, + chess_core::shakmaty::EnPassantMode::Legal, + ) + }) + .map(|f| f.to_string()) + .unwrap_or_else(|| source.start().fen()); + let mut out = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n"); + write_move(source, node, &mut out, raw); + if recursive { + write_line(source, node, &mut out); + } + out.push_str(" *\n"); + out +} + +fn write_line(game: &Game, parent: NodeId, out: &mut String) { + let mut current = parent; + while let Some(main) = game.children(current).first().copied() { + write_move(game, main, out, true); + for alternative in game.children(current).iter().skip(1) { + out.push_str(" ("); + write_move(game, *alternative, out, true); + write_line(game, *alternative, out); + out.push(')'); + } + current = main; + } +} + +fn write_move(game: &Game, node: NodeId, out: &mut String, raw: bool) { + let Some(data) = game.node(node) else { + return; + }; + for comment in data.comments_before() { + write_comment(comment, out); + } + if let Some(mv) = data.game_move() { + out.push(' '); + out.push_str(&mv.san); + } + for nag in data.nags() { + out.push_str(&format!(" ${}", nag.0)); + } + for comment in data.comments_after() { + write_comment(comment, out); + } + if raw { + for text in data.unparsed() { + out.push(' '); + out.push_str(text); + } + } +} + +fn write_comment(comment: &str, out: &mut String) { + if comment.contains('}') { + for line in comment.lines() { + out.push_str(&format!("\n;{}\n", line.trim())); + } + } else { + out.push_str(&format!(" {{{comment}}}")); + } +} + +pub(crate) fn stable_hash(bytes: &[u8]) -> u64 { + let mut hash = 0xcbf29ce484222325_u64; + for byte in bytes { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x100000001b3); + } + hash +} diff --git a/crates/trainer/src/repertoire/scope.rs b/crates/trainer/src/repertoire/scope.rs new file mode 100644 index 0000000..38e788d --- /dev/null +++ b/crates/trainer/src/repertoire/scope.rs @@ -0,0 +1,43 @@ +use serde::{Deserialize, Serialize}; + +/// A durable training area. The selected move is included; `end_prefix`, when present, +/// is also included and forms an early boundary. Node IDs never participate. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(default)] +pub struct TrainingScope { + pub prefix: Vec, + pub end_prefix: Option>, + /// Replay the path before the selected move/target as automatic context. + pub include_context: bool, +} + +impl TrainingScope { + pub fn whole() -> Self { + Self::default() + } + + pub(crate) fn parent_prefix(&self) -> &[String] { + self.prefix + .get(..self.prefix.len().saturating_sub(1)) + .unwrap_or(&[]) + } +} + +impl Default for TrainingScope { + fn default() -> Self { + Self { + prefix: Vec::new(), + end_prefix: None, + include_context: true, + } + } +} + +/// Identity of a training area for queues and history. Context presentation deliberately +/// does not split learning data. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(default)] +pub struct TrainingScopeKey { + pub prefix: Vec, + pub end_prefix: Option>, +} diff --git a/crates/trainer/src/repertoire/session_tests.rs b/crates/trainer/src/repertoire/session_tests.rs new file mode 100644 index 0000000..5a42576 --- /dev/null +++ b/crates/trainer/src/repertoire/session_tests.rs @@ -0,0 +1,1178 @@ +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::*; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 24 * 60 * 60; +static NEXT_DIR: AtomicU64 = AtomicU64::new(1); + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let sequence = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "cp-learning-session-{}-{}-{name}", + std::process::id(), + sequence + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn store(&self) -> LearningStore { + LearningStore::new(self.0.join("learning.json")) + } + + fn path(&self) -> PathBuf { + self.0.join("learning.json") + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn library(pgn: &str) -> (Library, RepertoireId) { + let mut library = Library::default(); + let id = library + .create("Test", &chess_core::parse_str(pgn).game) + .unwrap(); + (library, id) +} + +fn scope(id: RepertoireId, side: LearningSide) -> StatsScope { + StatsScope::for_repertoire(id, side, NOW) +} + +fn key_for(library: &Library, scope: &StatsScope, expected_uci: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected_uci) + .unwrap() + .key +} + +fn introduce_at(learning: &mut LearningData, key: LearningItemKey, next_review_at: i64) { + let item = learning.ensure_item(key); + item.introduced = true; + item.next_review_at = Some(next_review_at); +} + +fn due_session( + id: &str, + library: &Library, + learning: &LearningData, + scope: StatsScope, +) -> LearningSessionSnapshot { + LearningSessionSnapshot::new(id, library, learning, scope, SrsSettings::default()).unwrap() +} + +fn seed_store(dir: &TestDir, learning: &LearningData) { + let data = LearningStoreData { + learning: learning.clone(), + ..LearningStoreData::default() + }; + let bytes = serde_json::to_vec_pretty(&data).unwrap(); + std::fs::write(dir.path(), bytes).unwrap(); +} + +fn commit( + store: &LearningStore, + session: &mut LearningSessionSnapshot, + attempt: TrainingAttempt, +) -> PersistedSessionAttempt { + let persisted = store.apply_attempt_and_session(attempt, session).unwrap(); + *session = persisted.session.clone(); + persisted +} + +fn play( + store: &LearningStore, + library: &Library, + session: &mut LearningSessionSnapshot, + uci: &str, + id: &str, + at: i64, + response_time_ms: Option, +) -> PersistedSessionAttempt { + let attempt = session + .play_uci(library, uci, id, at, response_time_ms) + .unwrap(); + commit(store, session, attempt) +} + +fn advance( + store: &LearningStore, + library: &Library, + session: &mut LearningSessionSnapshot, + id: &str, + at: i64, +) -> PersistedSessionAttempt { + let attempt = session.advance_context(library, id, at).unwrap(); + commit(store, session, attempt) +} + +fn restore(store: &LearningStore, library: &Library, id: &str) -> LearningSessionSnapshot { + store + .load() + .unwrap() + .session_snapshot(id) + .cloned() + .unwrap() + .resume(library) + .unwrap() +} + +#[cfg(unix)] +fn file_inode(path: &std::path::Path) -> u64 { + use std::os::unix::fs::MetadataExt as _; + std::fs::metadata(path).unwrap().ino() +} + +#[test] +fn initial_queue_is_due_only_and_zero_due_finishes_without_unseen() { + let (library, id) = library("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let nf3 = key_for(&library, &scope, "g1f3"); + let bb5 = key_for(&library, &scope, "f1b5"); + let mut learning = LearningData::default(); + introduce_at(&mut learning, e4.clone(), NOW); + introduce_at(&mut learning, nf3, NOW + DAY); + + let session = due_session("due", &library, &learning, scope.clone()); + assert_eq!(session.queue.len(), 1); + assert_eq!(session.current_target().unwrap().key, e4); + assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); + assert!(!session.queue.iter().any(|target| target.key == bb5)); + + let empty = due_session("empty", &library, &LearningData::default(), scope); + assert_eq!(empty.phase, LearningSessionPhase::Finished); + assert!(empty.queue.is_empty()); + assert_eq!(empty.remaining(), 0); +} + +#[test] +fn introduction_is_explicit_and_does_not_introduce_until_an_answer() { + let (library, id) = library("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); + let scope = scope(id, LearningSide::White); + let learning = LearningData::default(); + let mut session = due_session("introduce", &library, &learning, scope.clone()); + assert_eq!(session.phase, LearningSessionPhase::Finished); + + assert_eq!(session.introduce_new(&library, &learning).unwrap(), 3); + assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); + assert!(learning.items.is_empty()); + assert!(session.completed_keys.is_empty()); + + let store = TestDir::new("introduce"); + let store = store.store(); + let persisted = play( + &store, + &library, + &mut session, + "e2e4", + "first-new", + NOW, + Some(100), + ); + let first = persisted + .learning + .item(&key_for(&library, &scope, "e2e4")) + .unwrap(); + assert!(first.introduced); + assert_eq!(first.correct_streak, 1); + assert_eq!(session.completed_keys.len(), 1); +} + +#[test] +fn illegal_input_and_unscheduled_repertoire_answer_do_not_change_learning() { + let (library, id) = library("1. e4 (1. d4) e5 *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let mut learning = LearningData::default(); + introduce_at(&mut learning, e4.clone(), NOW); + let before = learning.item(&e4).unwrap().clone(); + let dir = TestDir::new("illegal"); + let store = dir.store(); + seed_store(&dir, &learning); + let mut session = due_session("strict", &library, &learning, scope); + + let illegal = play( + &store, + &library, + &mut session, + "e2e5", + "illegal", + NOW, + Some(9_999), + ); + assert_eq!( + illegal.learning.attempts[0].event_type, + TrainingEventType::IllegalMove + ); + assert_eq!(illegal.learning.attempts[0].response_time_ms, None); + assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); + assert_eq!(illegal.learning.item(&e4), Some(&before)); + + let before_session = session.clone(); + assert!(matches!( + session.play_uci(&library, "d2d4", "legal-alternative", NOW + 1, Some(250)), + Err(LearningSessionError::RepertoireAlternative { + already_completed: false + }) + )); + assert_eq!(session, before_session); + let unchanged = store.load().unwrap().learning; + assert_eq!(unchanged.attempts.len(), 1); + assert_eq!(unchanged.item(&e4), Some(&before)); +} + +#[test] +fn at_05_wrong_then_repeated_replay_records_one_independent_wrong() { + let (library, id) = library("1. e4 e5 *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let mut learning = LearningData::default(); + introduce_at(&mut learning, e4.clone(), NOW); + let dir = TestDir::new("wrong-replay"); + let store = dir.store(); + seed_store(&dir, &learning); + let mut session = due_session("wrong-replay", &library, &learning, scope); + + let wrong = play( + &store, + &library, + &mut session, + "d2d4", + "wrong", + NOW, + Some(500), + ); + let after_wrong = wrong.learning.item(&e4).unwrap().clone(); + assert_eq!(after_wrong.correct_streak, 0); + assert_eq!(after_wrong.wrong_count, 1); + assert_eq!(after_wrong.next_review_at, Some(NOW + 30)); + assert_eq!(after_wrong.independent_response_times_ms, [500]); + assert_eq!( + session + .presentation(&library) + .unwrap() + .revealed_move + .as_deref(), + Some("e2e4") + ); + + let repeated_wrong = play( + &store, + &library, + &mut session, + "c2c4", + "replay-wrong", + NOW + 1, + Some(800), + ); + assert_eq!( + repeated_wrong.learning.attempts[1].event_type, + TrainingEventType::ReplayAfterError + ); + assert_eq!(repeated_wrong.learning.attempts[1].response_time_ms, None); + assert_eq!(repeated_wrong.learning.item(&e4), Some(&after_wrong)); + assert_eq!( + session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + + let replayed = play( + &store, + &library, + &mut session, + "e2e4", + "replay-expected", + NOW + 2, + Some(900), + ); + assert_eq!( + replayed.learning.attempts[2].event_type, + TrainingEventType::ReplayAfterError + ); + assert_eq!(replayed.learning.attempts[2].response_time_ms, None); + assert_eq!(replayed.learning.item(&e4), Some(&after_wrong)); + assert_eq!( + replayed + .learning + .item(&e4) + .unwrap() + .independent_attempt_count(), + 1 + ); + assert_eq!(session.phase, LearningSessionPhase::Finished); + assert!(session.completed_keys.contains(&e4)); +} + +#[test] +fn pending_alternative_credits_only_the_played_answer_and_keeps_original_pending() { + let (library, id) = library("1. e4 (1. d4) *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let d4 = key_for(&library, &scope, "d2d4"); + let mut session = due_session("alternatives", &library, &LearningData::default(), scope); + assert_eq!( + session + .introduce_new(&library, &LearningData::default()) + .unwrap(), + 2 + ); + assert_eq!(session.current_target().unwrap().key, e4); + let dir = TestDir::new("alternatives"); + let store = dir.store(); + let first = play( + &store, + &library, + &mut session, + "d2d4", + "d4-first", + NOW, + Some(123), + ); + assert_eq!(first.learning.attempts[0].item_key(), d4); + assert_eq!(first.learning.item(&d4).unwrap().correct_count, 1); + assert!(first.learning.item(&e4).is_none()); + assert_eq!(session.current_target().unwrap().key, e4); + assert_eq!(session.remaining(), 1); + session = restore(&store, &library, "alternatives"); + let before = session.clone(); + assert!(matches!( + session.play_uci(&library, "d2d4", "d4-again", NOW + 1, Some(12)), + Err(LearningSessionError::RepertoireAlternative { + already_completed: true + }) + )); + assert_eq!(session, before); + assert_eq!(store.load().unwrap().learning.attempts.len(), 1); + let second = play( + &store, + &library, + &mut session, + "e2e4", + "e4-next", + NOW + 2, + Some(124), + ); + assert_eq!(second.learning.item(&e4).unwrap().correct_count, 1); + assert_eq!(second.learning.item(&d4).unwrap().correct_count, 1); + assert_eq!(session.phase, LearningSessionPhase::Finished); + assert_eq!(session.completed_keys.len(), 2); +} + +#[test] +fn prepared_answer_cache_preserves_live_classification_and_credit() { + let (library, id) = library("1. e4 (1. d4) (1. c4) *"); + let selected = scope(id, LearningSide::White); + let answers = active_learning_keys(&library, &selected).unwrap(); + let mut learning = LearningData::default(); + for uci in ["e2e4", "d2d4"] { + introduce_at(&mut learning, key_for(&library, &selected, uci), NOW); + } + let original = due_session("answer-cache", &library, &learning, selected); + for uci in ["e2e4", "d2d4", "c2c4", "a2a3", "e2e5"] { + let mut direct = original.clone(); + let mut cached = original.clone(); + let first = + direct.play_uci_with_learning(&library, &learning, uci, "answer", NOW, Some(123)); + let second = cached.play_uci_with_learning_answers( + &library, + &learning, + &answers, + uci, + "answer", + NOW, + Some(123), + ); + assert_eq!(first, second, "different event for {uci}"); + assert_eq!(direct, cached, "different session transition for {uci}"); + } +} + +#[test] +fn alternative_during_context_does_not_continue_the_unplayed_branch() { + let (library, id) = library("1. e4 (1. d4 d5 2. c4) e5 2. Nf3 (2. Bc4) Nc6 *"); + let scope = scope(id, LearningSide::White); + let mut session = LearningSessionSnapshot::new_with_mode( + "context-alternative", + &library, + &LearningData::default(), + scope, + SrsSettings::default(), + QueueMode::LeastRecent, + ) + .unwrap(); + let deep = session + .queue + .iter() + .position(|target| target.key.expected_uci == "g1f3") + .unwrap(); + session.queue.swap(0, deep); + session.phase = LearningSessionPhase::AwaitingContextIndependent; + session.context_index = 0; + let original = session.current_target().unwrap().key.clone(); + session.validate(&library).unwrap(); + let dir = TestDir::new("context-alternative"); + let first = play( + &dir.store(), + &library, + &mut session, + "d2d4", + "d4-context", + NOW, + Some(300), + ); + assert_eq!(first.learning.attempts[0].expected_uci, "d2d4"); + assert_eq!( + first.learning.attempts[0].event_type, + TrainingEventType::CorrectIndependent + ); + assert!(!session.completed_keys.contains(&original)); + assert!( + session + .queue + .iter() + .skip(session.current_index) + .any(|target| target.key == original) + ); + assert_eq!( + session.context_index, 0, + "do not increment the e4 path after playing d4" + ); + session.validate(&library).unwrap(); + let restored = restore(&dir.store(), &library, "context-alternative"); + assert_eq!(restored, session); +} + +#[test] +fn replay_stays_on_revealed_answer_and_disabled_alternative_is_not_accepted() { + let (mut library, id) = library("1. e4 (1. d4) *"); + let selected = scope(id.clone(), LearningSide::White); + let mut session = due_session( + "replay-choices", + &library, + &LearningData::default(), + selected.clone(), + ); + session + .introduce_new(&library, &LearningData::default()) + .unwrap(); + session.preview("preview", NOW).unwrap(); + let before = session.clone(); + assert!(matches!( + session.play_uci(&library, "d2d4", "other-preview", NOW, None), + Err(LearningSessionError::RepertoireAlternative { + already_completed: false + }) + )); + assert_eq!(session, before); + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&["d2d4".to_owned()], true) + .unwrap(); + let mut session = due_session( + "disabled-choice", + &library, + &LearningData::default(), + selected, + ); + session + .introduce_new(&library, &LearningData::default()) + .unwrap(); + let attempt = session + .play_uci(&library, "d2d4", "disabled", NOW, Some(123)) + .unwrap(); + assert_eq!(attempt.expected_uci, "e2e4"); + assert_eq!(attempt.event_type, TrainingEventType::IncorrectIndependent); +} + +#[test] +fn at_06_preview_then_played_move_has_no_streak_accuracy_or_extra_preview() { + let (library, id) = library("1. e4 e5 *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let mut learning = LearningData::default(); + let item = learning.ensure_item(e4.clone()); + item.introduced = true; + item.correct_streak = 2; + item.wrong_streak = 1; + item.correct_count = 4; + item.wrong_count = 1; + item.last_correct_at = Some(NOW - DAY); + item.last_review_at = Some(NOW - DAY); + item.next_review_at = Some(NOW); + item.previous_interval_seconds = Some(DAY); + let dir = TestDir::new("preview"); + let store = dir.store(); + seed_store(&dir, &learning); + let mut session = due_session("preview", &library, &learning, scope); + + let preview = session.preview("preview", NOW).unwrap().unwrap(); + assert_eq!(preview.event_type, TrainingEventType::Previewed); + assert_eq!(preview.response_time_ms, None); + let previewed = commit(&store, &mut session, preview); + let after_preview = previewed.learning.item(&e4).unwrap().clone(); + assert_eq!(after_preview.next_review_at, Some(NOW + 60)); + assert_eq!(after_preview.correct_streak, 2); + assert_eq!(after_preview.wrong_streak, 1); + assert_eq!(after_preview.correct_count, 4); + assert_eq!(after_preview.wrong_count, 1); + assert_eq!(after_preview.last_correct_at, Some(NOW - DAY)); + assert!(after_preview.independent_response_times_ms.is_empty()); + assert!( + session + .preview("duplicate-hint", NOW + 1) + .unwrap() + .is_none() + ); + assert_eq!(store.load().unwrap().learning.attempts.len(), 1); + + let played = play( + &store, + &library, + &mut session, + "e2e4", + "preview-played", + NOW + 2, + Some(1_000), + ); + assert_eq!( + played.learning.attempts[1].event_type, + TrainingEventType::AutoContext + ); + assert_eq!(played.learning.attempts[1].response_time_ms, None); + assert_eq!(played.learning.item(&e4), Some(&after_preview)); + assert_eq!( + played.learning.item(&e4).unwrap().accuracy_percent(), + Some(80.0) + ); + assert_eq!(session.phase, LearningSessionPhase::Finished); +} + +#[test] +fn at_23_duplicate_does_not_move_session_or_rewrite_file() { + let (library, id) = library("1. e4 e5 *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let mut learning = LearningData::default(); + introduce_at(&mut learning, e4.clone(), NOW); + let dir = TestDir::new("duplicate"); + let store = dir.store(); + seed_store(&dir, &learning); + let mut session = due_session("duplicate", &library, &learning, scope); + store.save_session(&mut session).unwrap(); + let attempt = session + .play_uci(&library, "e2e4", "same-response", NOW, Some(100)) + .unwrap(); + let first = commit(&store, &mut session, attempt.clone()); + assert_eq!(first.application, AttemptApplication::Applied); + let bytes = std::fs::read(dir.path()).unwrap(); + #[cfg(unix)] + let inode = file_inode(&dir.path()); + + let mut duplicate_next = session.clone(); + duplicate_next.completed_keys.clear(); + duplicate_next.current_index = 99; + let duplicate = store + .apply_attempt_and_session(attempt, &mut duplicate_next) + .unwrap(); + assert_eq!(duplicate.application, AttemptApplication::Duplicate); + assert_eq!(duplicate.revision, first.revision); + assert_eq!(duplicate.session, session); + assert_eq!(duplicate.learning.attempts.len(), 1); + assert_eq!(duplicate.learning.item(&e4).unwrap().correct_count, 1); + assert_eq!(std::fs::read(dir.path()).unwrap(), bytes); + #[cfg(unix)] + assert_eq!(file_inode(&dir.path()), inode); +} + +#[cfg(unix)] +#[test] +fn attempt_and_session_replace_the_old_inode_once_with_both_changes() { + let (library, id) = library("1. e4 e5 *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let mut learning = LearningData::default(); + introduce_at(&mut learning, e4, NOW); + let dir = TestDir::new("atomic"); + let store = dir.store(); + seed_store(&dir, &learning); + let mut session = due_session("atomic", &library, &learning, scope); + store.save_session(&mut session).unwrap(); + let old_link = dir.0.join("old-inode.json"); + std::fs::hard_link(dir.path(), &old_link).unwrap(); + let old_inode = file_inode(&dir.path()); + let old_revision = store.load().unwrap().revision; + + let attempt = session + .play_uci(&library, "d2d4", "atomic-wrong", NOW, Some(100)) + .unwrap(); + let persisted = commit(&store, &mut session, attempt); + assert_eq!(persisted.revision, old_revision + 1); + assert_ne!(file_inode(&dir.path()), old_inode); + assert_eq!(file_inode(&old_link), old_inode); + + let old = LearningStore::new(&old_link).load().unwrap(); + assert!(old.learning.attempts.is_empty()); + assert_eq!( + old.session_snapshot("atomic").unwrap().phase, + LearningSessionPhase::AwaitingIndependent + ); + let new = store.load().unwrap(); + assert_eq!(new.learning.attempts.len(), 1); + assert_eq!( + new.session_snapshot("atomic").unwrap().phase, + LearningSessionPhase::AwaitingReplayAfterError + ); +} + +#[test] +fn same_session_conflict_is_explicit_and_different_sessions_keep_both_events() { + let (library, id) = library("1. e4 e5 *"); + let scope = scope(id, LearningSide::White); + let e4 = key_for(&library, &scope, "e2e4"); + let mut learning = LearningData::default(); + introduce_at(&mut learning, e4.clone(), NOW); + let dir = TestDir::new("conflict"); + let first_store = dir.store(); + let second_store = LearningStore::new(dir.path()); + seed_store(&dir, &learning); + let original = due_session("shared-session", &library, &learning, scope.clone()); + let mut left = original.clone(); + let mut right = original; + let left_attempt = left + .play_uci(&library, "d2d4", "left", NOW, Some(100)) + .unwrap(); + let right_attempt = right + .play_uci(&library, "e2e4", "right", NOW, Some(100)) + .unwrap(); + commit(&first_store, &mut left, left_attempt); + let before_conflict = std::fs::read(dir.path()).unwrap(); + + let conflict = second_store.apply_attempt_and_session(right_attempt, &mut right); + assert!(matches!( + conflict, + Err(StoreError::SessionConflict { + expected: 0, + actual: 1, + .. + }) + )); + assert_eq!(std::fs::read(dir.path()).unwrap(), before_conflict); + assert_eq!(first_store.load().unwrap().learning.attempts.len(), 1); + + let mut restored = restore(&first_store, &library, "shared-session"); + play( + &first_store, + &library, + &mut restored, + "e2e4", + "after-reload", + NOW + 1, + None, + ); + assert_eq!(first_store.load().unwrap().learning.attempts.len(), 2); + + let mut other_a = due_session("session-a", &library, &learning, scope.clone()); + let mut other_b = due_session("session-b", &library, &learning, scope); + let a = other_a + .play_uci(&library, "e2e4", "session-a-answer", NOW, Some(100)) + .unwrap(); + let b = other_b + .play_uci(&library, "d2d4", "session-b-answer", NOW, Some(200)) + .unwrap(); + commit(&first_store, &mut other_a, a); + commit(&second_store, &mut other_b, b); + let persisted = first_store.load().unwrap(); + let shared = persisted.learning.item(&e4).unwrap(); + assert_eq!(shared.correct_count, 1); + assert_eq!(shared.wrong_count, 2); + assert!(persisted.session_snapshot("session-a").is_some()); + assert!(persisted.session_snapshot("session-b").is_some()); + assert!( + persisted + .learning + .attempts + .iter() + .any(|attempt| attempt.client_attempt_id == "session-a-answer") + ); + assert!( + persisted + .learning + .attempts + .iter() + .any(|attempt| attempt.client_attempt_id == "session-b-answer") + ); +} + +#[test] +fn snapshot_resumes_every_phase_with_deterministic_context_and_positions() { + let (library, id) = library("1. e4 e5 2. Nf3 Nc6 *"); + let scope = scope(id, LearningSide::Black); + let mut learning = LearningData::default(); + for uci in ["e7e5", "b8c6"] { + introduce_at(&mut learning, key_for(&library, &scope, uci), NOW); + } + let dir = TestDir::new("resume"); + let store = dir.store(); + seed_store(&dir, &learning); + let mut session = due_session("resume", &library, &learning, scope.clone()); + + assert_eq!(session.phase, LearningSessionPhase::AdvancingContext); + store.save_session(&mut session).unwrap(); + session = restore(&store, &library, "resume"); + let presentation = session.presentation(&library).unwrap(); + assert_eq!(presentation.target_path, ["e2e4", "e7e5"]); + assert_eq!(presentation.automatic_context.len(), 1); + assert_eq!(presentation.automatic_context[0].uci, "e2e4"); + assert_eq!( + presentation.current_position.unwrap().fen4, + presentation.automatic_context[0].from.fen4 + ); + + advance(&store, &library, &mut session, "context-e4", NOW); + session = restore(&store, &library, "resume"); + assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); + assert_eq!( + session + .presentation(&library) + .unwrap() + .current_position + .unwrap() + .fen4, + key_for(&library, &scope, "e7e5").position_fen4 + ); + + play( + &store, + &library, + &mut session, + "e7e6", + "wrong-e6", + NOW, + Some(450), + ); + session = restore(&store, &library, "resume"); + assert_eq!( + session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + assert_eq!( + session + .presentation(&library) + .unwrap() + .revealed_move + .as_deref(), + Some("e7e5") + ); + + play( + &store, + &library, + &mut session, + "e7e5", + "replay-e5", + NOW + 1, + Some(999), + ); + session = restore(&store, &library, "resume"); + assert_eq!(session.phase, LearningSessionPhase::AdvancingContext); + assert_eq!(session.current_target().unwrap().key.expected_uci, "b8c6"); + assert_eq!( + session + .presentation(&library) + .unwrap() + .automatic_context + .len(), + 3 + ); + + for (index, uci) in ["e2e4", "e7e5", "g1f3"].into_iter().enumerate() { + advance( + &store, + &library, + &mut session, + &format!("next-context-{index}"), + NOW + 2, + ); + session = restore(&store, &library, "resume"); + if index < 2 { + assert_eq!(session.phase, LearningSessionPhase::AdvancingContext); + } + assert_eq!(session.current_target().unwrap().path[index], uci); + } + assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); + + let preview = session.preview("preview-nc6", NOW + 3).unwrap().unwrap(); + commit(&store, &mut session, preview); + session = restore(&store, &library, "resume"); + assert_eq!(session.phase, LearningSessionPhase::PreviewedReplay); + assert_eq!( + session + .presentation(&library) + .unwrap() + .revealed_move + .as_deref(), + Some("b8c6") + ); + + play( + &store, + &library, + &mut session, + "b8c6", + "played-preview-nc6", + NOW + 4, + Some(888), + ); + session = restore(&store, &library, "resume"); + assert_eq!(session.phase, LearningSessionPhase::Finished); + assert_eq!(session.completed_keys.len(), 2); + assert!( + session + .presentation(&library) + .unwrap() + .current_position + .is_none() + ); + + let data = store.load().unwrap(); + let e5 = data + .learning + .item(&key_for(&library, &scope, "e7e5")) + .unwrap(); + assert_eq!(e5.independent_response_times_ms, [450]); + let nc6 = data + .learning + .item(&key_for(&library, &scope, "b8c6")) + .unwrap(); + assert!(nc6.independent_response_times_ms.is_empty()); + assert!(data.learning.attempts.iter().all(|attempt| { + attempt.event_type.is_independent() || attempt.response_time_ms.is_none() + })); +} + +#[test] +fn both_and_legacy_queue_modes_are_rejected_on_resume() { + let (library, id) = library("1. e4 *"); + let selected = scope(id, LearningSide::White); + let mut session = due_session("invalid", &library, &LearningData::default(), selected); + session.session.side = TrainingMode::Both; + assert!(matches!( + session.clone().resume(&library), + Err(LearningSessionError::SessionSideMismatch) + )); + session.session.side = TrainingMode::White; + session.session.mode = QueueMode::Practice; + assert!(matches!( + session.resume(&library), + Err(LearningSessionError::UnsupportedMode(QueueMode::Practice)) + )); +} + +#[test] +fn transposition_target_replays_its_saved_membership_path_after_reload() { + let (library, id) = + library("1. e4 d5 (1... Nf6 2. d4 d5) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 *"); + let scope = scope(id, LearningSide::White); + let c4 = key_for(&library, &scope, "c2c4"); + let mut learning = LearningData::default(); + introduce_at(&mut learning, c4.clone(), NOW); + let dir = TestDir::new("transposition"); + let store = dir.store(); + seed_store(&dir, &learning); + let mut session = due_session("transposition", &library, &learning, scope); + assert_eq!( + session.current_target().unwrap().path, + [ + "e2e4", "d7d5", "d2d4", "g8h6", "g1f3", "h6g8", "f3g1", "g8f6", "c2c4" + ] + ); + store.save_session(&mut session).unwrap(); + session = restore(&store, &library, "transposition"); + assert_eq!( + session + .presentation(&library) + .unwrap() + .automatic_context + .len(), + 8 + ); + + for index in 0..8 { + advance( + &store, + &library, + &mut session, + &format!("transposition-context-{index}"), + NOW, + ); + } + session = restore(&store, &library, "transposition"); + assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); + assert_eq!( + session + .presentation(&library) + .unwrap() + .current_position + .unwrap() + .fen4, + c4.position_fen4 + ); + play( + &store, + &library, + &mut session, + "c2c4", + "transposition-answer", + NOW, + Some(100), + ); + assert_eq!(session.phase, LearningSessionPhase::Finished); +} + +#[test] +fn learnt_counter_tracks_persisted_independent_answers_for_both_sides_and_shared_scopes() { + for side in [LearningSide::White, LearningSide::Black] { + let (mut library, first) = library("1. e4 e5 *"); + let second = library + .create( + "Shared continuation", + &chess_core::parse_str("1. e4 e5 2. Nf3 *").game, + ) + .unwrap(); + let expected = if side == LearningSide::White { + "e2e4" + } else { + "e7e5" + }; + let wrong = if side == LearningSide::White { + "d2d4" + } else { + "c7c5" + }; + let key = key_for(&library, &scope(first.clone(), side), expected); + let dir = TestDir::new("learnt-counter-lifecycle"); + let store = dir.store(); + let mut at = NOW; + for (cycle, action) in ["correct", "correct", "preview", "correct", "wrong"] + .into_iter() + .enumerate() + { + let learning = store.load().unwrap().learning; + let mut selected = scope(first.clone(), side); + selected.as_of = at; + let mut session = due_session( + &format!("counter-{cycle}"), + &library, + &learning, + selected.clone(), + ); + if cycle == 0 { + assert_eq!(session.introduce_new(&library, &learning).unwrap(), 1); + } + while session.phase == LearningSessionPhase::AdvancingContext { + let event_id = format!("counter-{cycle}-auto-{}", session.context_index); + advance(&store, &library, &mut session, &event_id, at); + } + assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); + if action == "preview" { + let preview = session + .preview(format!("counter-{cycle}-preview"), at) + .unwrap() + .unwrap(); + commit(&store, &mut session, preview); + } + let played = if action == "wrong" { wrong } else { expected }; + let attempt = session + .play_uci( + &library, + played, + format!("counter-{cycle}-answer"), + at, + Some(100), + ) + .unwrap(); + let result = commit(&store, &mut session, attempt.clone()); + let duplicate = commit(&store, &mut session, attempt); + assert_eq!(duplicate.application, AttemptApplication::Duplicate); + assert_eq!(duplicate.learning, result.learning); + if action == "wrong" { + play( + &store, + &library, + &mut session, + expected, + "counter-replay", + at, + None, + ); + } + // Reload exactly what the UI uses after leaving a training session. + let learning = store.load().unwrap().learning; + let expected_streak = [1, 2, 2, 3, 0][cycle]; + let learnt = usize::from(expected_streak >= 3); + assert_eq!(learning.item(&key).unwrap().correct_streak, expected_streak); + let first_summary = + aggregate_scope(&library, &learning, &selected, &SrsSettings::default()) + .unwrap() + .summary; + assert_eq!((first_summary.learnt, first_summary.total), (learnt, 1)); + let shared_scope = StatsScope::new([first.clone(), second.clone()], side, at); + let shared = + aggregate_scope(&library, &learning, &shared_scope, &SrsSettings::default()) + .unwrap() + .summary; + let expected_total = if side == LearningSide::White { 2 } else { 1 }; + assert_eq!((shared.learnt, shared.total), (learnt, expected_total)); + let second_summary = aggregate_scope( + &library, + &learning, + &scope(second.clone(), side), + &SrsSettings::default(), + ) + .unwrap() + .summary; + assert_eq!(second_summary.learnt, learnt); + assert_eq!( + first_summary.total, + first_summary.unseen + first_summary.learning + first_summary.learnt + ); + assert_eq!(first_summary.accuracy_correct, [1, 2, 2, 3, 3][cycle]); + assert_eq!(first_summary.accuracy_wrong, u64::from(action == "wrong")); + at = learning.item(&key).unwrap().next_review_at.unwrap(); + } + } +} + +#[test] +fn runtime_replay_cache_is_shared_but_never_persisted_or_stale_after_source_changes() { + let (mut library, id) = library("1. e4 e5 2. Nf3 Nc6 3. Bb5 *"); + let selected = scope(id.clone(), LearningSide::White); + let mut learning = LearningData::default(); + introduce_at(&mut learning, key_for(&library, &selected, "f1b5"), NOW); + let mut session = due_session("runtime-cache", &library, &learning, selected); + let initial = session + .presentation_with_learning(&library, &learning) + .unwrap(); + let (parses, replays, _) = session.runtime_work_counts(); + assert_eq!((parses, replays), (1, 1)); + let mut clone = session.clone(); + for _ in 0..8 { + assert_eq!( + clone + .presentation_with_learning(&library, &learning) + .unwrap(), + initial + ); + } + assert_eq!(clone.runtime_work_counts().0, 1); + assert_eq!(clone.runtime_work_counts().1, 1); + let json = serde_json::to_value(&session).unwrap(); + assert!(json.get("runtime").is_none()); + let mut restored: LearningSessionSnapshot = serde_json::from_value(json).unwrap(); + assert_eq!(restored, session); + assert_eq!(restored.runtime_work_counts(), (0, 0, 0)); + assert_eq!( + restored + .presentation_with_learning(&library, &learning) + .unwrap(), + initial + ); + assert_eq!(restored.runtime_work_counts().0, 1); + + // Public PGN can change without a revision API. Compare exact source bytes; + // a shared clone must not retain old positions after a source edit. + let old_library = library.clone(); + library + .repertoire_mut(&id) + .unwrap() + .pgn + .push_str(" {edited}"); + assert_eq!( + clone + .presentation_with_learning(&library, &learning) + .unwrap(), + initial + ); + assert_eq!(session.runtime_work_counts().0, 2); + assert_eq!( + session + .presentation_with_learning(&old_library, &learning) + .unwrap(), + initial + ); + assert_eq!(session.runtime_work_counts().0, 3); + library.repertoire_mut(&id).unwrap().pgn = + "[SetUp \"1\"]\n[FEN \"rnbqkbnr/pppppppp/8/8/8/8/PPPP1PPP/RNBQKBNR w KQkq - 0 1\"]\n\n*" + .into(); + assert!(matches!( + clone.presentation_with_learning(&library, &learning), + Err(LearningSessionError::InvalidTargetPath { .. }) + )); + assert_eq!(clone.runtime_work_counts().0, 4); + assert_eq!( + session + .presentation_with_learning(&old_library, &learning) + .unwrap(), + initial + ); +} + +#[test] +fn context_presentation_plans_once_per_call_instead_of_once_per_prefix_move() { + // A long legal path with repeated positions; the saved PGN occurrence must + // retain its full history, while planning work stays constant per call. + let pgn = format!("{} e4 *", "Nf3 Nf6 Ng1 Ng8 ".repeat(64)); + let (library, id) = library(&pgn); + let selected = scope(id, LearningSide::White); + let mut learning = LearningData::default(); + introduce_at(&mut learning, key_for(&library, &selected, "e2e4"), NOW); + let mut session = due_session("linear-context-plan", &library, &learning, selected); + assert_eq!(session.current_target().unwrap().path.len(), 257); + let before = session.runtime_work_counts(); + let presentation = session + .presentation_with_learning(&library, &learning) + .unwrap(); + assert_eq!(presentation.automatic_context.len(), 256); + let after = session.runtime_work_counts(); + assert_eq!((after.0, after.1), (before.0, before.1)); + // One phase synchronisation plus one presentation, independent of path length. + assert_eq!(after.2 - before.2, 2); + let mut clone = session.clone(); + for index in 0..8 { + let attempt = clone + .advance_context_with_learning( + &library, + &learning, + format!("cached-context-{index}"), + NOW, + ) + .unwrap(); + assert_eq!(attempt.event_type, TrainingEventType::AutoContext); + } + assert_eq!(clone.context_index, 8); + assert_eq!(clone.runtime_work_counts().0, 1); + assert_eq!(clone.runtime_work_counts().1, 1); + // Policy remains live; no cached plan may hide a newly required question. + clone.context_policy.consider_leadup_moves = true; + assert_eq!( + clone + .presentation_with_learning(&library, &learning) + .unwrap() + .phase, + LearningSessionPhase::AwaitingContextIndependent + ); +} diff --git a/crates/trainer/src/repertoire/srs.rs b/crates/trainer/src/repertoire/srs.rs new file mode 100644 index 0000000..71c7668 --- /dev/null +++ b/crates/trainer/src/repertoire/srs.rs @@ -0,0 +1,199 @@ +use serde::{Deserialize, Serialize}; + +use super::learning::{ + AttemptApplication, IndependentResult, LearningData, LearningError, LearningItem, + LearningItemKey, TrainingAttempt, TrainingEventType, WrongMoveStats, +}; + +pub const DEFAULT_GROWTH_FACTOR: f64 = 2.0; +pub const FIRST_CORRECT_DELAY_SECONDS: i64 = 24 * 60 * 60; +pub const MISTAKE_DELAY_SECONDS: i64 = 30; +pub const PREVIEW_DELAY_SECONDS: i64 = 60; +pub const SRS_MAX_INTERVAL_SECONDS: i64 = 1095 * 24 * 60 * 60; +pub const MIN_PRACTICAL_INTERVAL_SECONDS: i64 = 1; +pub const UNCERTAIN_MIN_GRACE_SECONDS: i64 = 7 * 24 * 60 * 60; +pub const UNCERTAIN_INTERVAL_DIVISOR: u32 = 4; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SrsSettings { + pub growth_factor: f64, + pub first_correct_delay_seconds: i64, + pub mistake_delay_seconds: i64, + pub preview_delay_seconds: i64, + pub max_interval_seconds: i64, + /// Project-specific lower bound for elapsed-time growth, not a ChessTempo default. + pub min_practical_interval_seconds: i64, + pub uncertain_min_grace_seconds: i64, + pub uncertain_interval_divisor: u32, +} + +impl Default for SrsSettings { + fn default() -> Self { + Self { + growth_factor: DEFAULT_GROWTH_FACTOR, + first_correct_delay_seconds: FIRST_CORRECT_DELAY_SECONDS, + mistake_delay_seconds: MISTAKE_DELAY_SECONDS, + preview_delay_seconds: PREVIEW_DELAY_SECONDS, + max_interval_seconds: SRS_MAX_INTERVAL_SECONDS, + min_practical_interval_seconds: MIN_PRACTICAL_INTERVAL_SECONDS, + uncertain_min_grace_seconds: UNCERTAIN_MIN_GRACE_SECONDS, + uncertain_interval_divisor: UNCERTAIN_INTERVAL_DIVISOR, + } + } +} + +pub fn apply_independent_correct(item: &mut LearningItem, now: i64, settings: &SrsSettings) { + let delay = match (item.correct_streak, item.last_correct_at) { + (0, _) | (_, None) => settings.first_correct_delay_seconds.max(0), + (_, Some(last_correct_at)) => growth_delay(now.saturating_sub(last_correct_at), settings), + }; + + item.introduced = true; + item.correct_streak = item.correct_streak.saturating_add(1); + item.wrong_streak = 0; + item.correct_count = item.correct_count.saturating_add(1); + item.last_correct_at = Some(now); + item.last_review_at = Some(now); + item.previous_interval_seconds = Some(delay); + item.next_review_at = Some(now.saturating_add(delay)); + item.record_independent_outcome(IndependentResult::Correct, now); +} + +pub fn apply_independent_wrong( + item: &mut LearningItem, + played_move: &str, + now: i64, + settings: &SrsSettings, +) { + item.introduced = true; + item.correct_streak = 0; + item.wrong_streak = item.wrong_streak.saturating_add(1); + item.wrong_count = item.wrong_count.saturating_add(1); + item.last_correct_at = None; + item.last_review_at = Some(now); + item.next_review_at = Some(now.saturating_add(settings.mistake_delay_seconds.max(0))); + item.last_wrong_move_uci = Some(played_move.to_owned()); + item.last_wrong_at = Some(now); + let wrong = item + .wrong_move_histogram + .entry(played_move.to_owned()) + .or_insert(WrongMoveStats { + count: 0, + last_at: now, + }); + wrong.count = wrong.count.saturating_add(1); + wrong.last_at = now; + item.record_independent_outcome(IndependentResult::Wrong, now); +} + +/// Preview preserves streaks, independent counters and the last correct answer. +pub fn apply_preview(item: &mut LearningItem, now: i64, settings: &SrsSettings) { + item.introduced = true; + item.last_review_at = Some(now); + item.next_review_at = Some(now.saturating_add(settings.preview_delay_seconds.max(0))); +} + +pub fn apply_attempt( + item: &mut LearningItem, + attempt: &TrainingAttempt, + settings: &SrsSettings, +) -> Result<(), LearningError> { + validate_attempt(&item.key, attempt)?; + apply_validated_attempt(item, attempt, settings); + Ok(()) +} + +impl LearningData { + /// Applies and journals an event once per `(user_id, client_attempt_id)`. + pub fn apply_attempt( + &mut self, + attempt: TrainingAttempt, + settings: &SrsSettings, + ) -> Result { + if attempt.client_attempt_id.is_empty() { + return Err(LearningError::EmptyClientAttemptId); + } + if self.attempts.iter().any(|existing| { + existing.user_id == attempt.user_id + && existing.client_attempt_id == attempt.client_attempt_id + }) { + return Ok(AttemptApplication::Duplicate); + } + + let key = attempt.item_key(); + validate_attempt(&key, &attempt)?; + let item = self.ensure_item(key); + apply_validated_attempt(item, &attempt, settings); + self.attempts.push(attempt); + Ok(AttemptApplication::Applied) + } +} + +fn growth_delay(elapsed_seconds: i64, settings: &SrsSettings) -> i64 { + let min = settings.min_practical_interval_seconds.max(0); + let max = settings.max_interval_seconds.max(min); + let growth = if settings.growth_factor.is_finite() { + settings.growth_factor.max(0.0) + } else { + 0.0 + }; + let scaled = elapsed_seconds.max(0) as f64 * growth; + if scaled >= max as f64 { + max + } else if scaled <= min as f64 { + min + } else { + scaled as i64 + } +} + +fn validate_attempt(key: &LearningItemKey, attempt: &TrainingAttempt) -> Result<(), LearningError> { + if attempt.client_attempt_id.is_empty() { + return Err(LearningError::EmptyClientAttemptId); + } + if key != &attempt.item_key() { + return Err(LearningError::WrongLearningItem); + } + if attempt.event_type == TrainingEventType::IncorrectIndependent + && attempt + .actual_uci + .as_deref() + .is_none_or(|actual| actual.is_empty()) + { + return Err(LearningError::MissingActualMove); + } + Ok(()) +} + +fn apply_validated_attempt( + item: &mut LearningItem, + attempt: &TrainingAttempt, + settings: &SrsSettings, +) { + match attempt.event_type { + TrainingEventType::CorrectIndependent => { + apply_independent_correct(item, attempt.happened_at, settings); + } + TrainingEventType::IncorrectIndependent => { + apply_independent_wrong( + item, + attempt.actual_uci.as_deref().unwrap_or_default(), + attempt.happened_at, + settings, + ); + } + TrainingEventType::Previewed => { + apply_preview(item, attempt.happened_at, settings); + } + TrainingEventType::ReplayAfterError + | TrainingEventType::AutoContext + | TrainingEventType::IllegalMove => return, + } + + if attempt.event_type.is_independent() + && let Some(response_time_ms) = attempt.response_time_ms + { + item.independent_response_times_ms.push(response_time_ms); + } +} diff --git a/crates/trainer/src/repertoire/stats.rs b/crates/trainer/src/repertoire/stats.rs new file mode 100644 index 0000000..68ca588 --- /dev/null +++ b/crates/trainer/src/repertoire/stats.rs @@ -0,0 +1,275 @@ +use chess_core::shakmaty::Color; +use serde::{Deserialize, Serialize}; + +use super::model::RepertoireId; +use super::scope::TrainingScopeKey; + +pub const STATS_VERSION: u32 = 2; +/// Recent attempts kept per move in a v2 file. +const RECENT: usize = 10; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum TrainingMode { + White, + Black, + Both, +} + +impl TrainingMode { + pub fn user_color(self) -> Option { + match self { + Self::White => Some(Color::White), + Self::Black => Some(Color::Black), + Self::Both => None, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum QueueMode { + Practice, + SpacedRepetition, + ReviewInOrder, + LeastRecent, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct MoveKey { + pub repertoire_id: RepertoireId, + pub mode: TrainingMode, + pub position_fen4: String, + pub expected_uci: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AttemptRecord { + pub at: i64, + pub correct: bool, + pub hinted: bool, + /// The actual legal input, including a wrong move outside the repertoire. + pub actual_uci: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct MoveStats { + pub key: MoveKey, + pub attempts: u32, + pub correct: u32, + pub wrong: u32, + pub hints: u32, + /// Positive: clean correct answers in a row. Negative: wrong answers in a row. + pub streak: i32, + pub recent: Vec, + pub last_attempt: Option, + pub last_seen: Option, + pub due: Option, + /// Scheduled interval, independent of observations during non-scheduling reviews. + pub interval_seconds: Option, +} + +impl Default for MoveStats { + fn default() -> Self { + Self { + key: MoveKey { + repertoire_id: RepertoireId::legacy(""), + mode: TrainingMode::Both, + position_fen4: String::new(), + expected_uci: String::new(), + }, + attempts: 0, + correct: 0, + wrong: 0, + hints: 0, + streak: 0, + recent: Vec::new(), + last_attempt: None, + last_seen: None, + due: None, + interval_seconds: None, + } + } +} + +#[cfg(test)] +impl MoveStats { + pub fn new(key: MoveKey) -> Self { + Self { + key, + ..Self::default() + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunRecord { + pub at: i64, + pub mistakes: u32, + pub hints: u32, + pub hinted: bool, + pub path: Vec, + pub user_attempts: u32, + pub automatic_moves: u32, + #[serde(default)] + pub scope: TrainingScopeKey, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RunStats { + pub repertoire_id: RepertoireId, + pub mode: TrainingMode, + pub completions: u32, + pub last: Option, + pub recent: Vec, +} + +impl Default for RunStats { + fn default() -> Self { + Self { + repertoire_id: RepertoireId::legacy(""), + mode: TrainingMode::Both, + completions: 0, + last: None, + recent: Vec::new(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct PathKey { + pub repertoire_id: RepertoireId, + pub scope: TrainingScopeKey, + pub path: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PathStats { + pub key: PathKey, + pub completions: u32, + pub mistakes: u32, + pub hints: u32, + pub last_seen: Option, + pub last_completion: Option, + pub recent: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct ReviewCursor { + repertoire_id: RepertoireId, + mode: TrainingMode, + #[serde(default)] + scope: TrainingScopeKey, + next: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct PathReviewCursor { + repertoire_id: RepertoireId, + scope: TrainingScopeKey, + next: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct RandomPracticeCursor { + repertoire_id: RepertoireId, + mode: TrainingMode, + scope: TrainingScopeKey, + seed: u64, + position: usize, + count: usize, + #[serde(default)] + fingerprint: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct StatsData { + pub version: u32, + pub revision: u64, + /// Original legacy values, retained verbatim. They are not per-move attempts. + pub legacy_lines: serde_json::Map, + pub move_stats: Vec, + pub runs: Vec, + pub path_stats: Vec, + review_cursors: Vec, + path_review_cursors: Vec, + practice_path_cursors: Vec, + random_practice_cursors: Vec, +} + +impl Default for StatsData { + fn default() -> Self { + Self { + version: STATS_VERSION, + revision: 0, + legacy_lines: serde_json::Map::new(), + move_stats: Vec::new(), + runs: Vec::new(), + path_stats: Vec::new(), + review_cursors: Vec::new(), + path_review_cursors: Vec::new(), + practice_path_cursors: Vec::new(), + random_practice_cursors: Vec::new(), + } + } +} + +impl StatsData { + pub(crate) fn migrate_position_stats(&mut self) { + let mut merged: Vec = Vec::new(); + for mut entry in self.move_stats.drain(..) { + if entry.key.mode != TrainingMode::Both { + if entry.interval_seconds.is_none() { + entry.interval_seconds = match (entry.due, entry.last_seen) { + (Some(due), Some(last)) if due > last => Some(due.saturating_sub(last)), + _ => None, + }; + } + merged.push(entry); + continue; + } + entry.key.expected_uci.clear(); + entry.due = None; + entry.interval_seconds = None; + if let Some(old) = merged.iter_mut().find(|old| old.key == entry.key) { + old.attempts = old.attempts.saturating_add(entry.attempts); + old.correct = old.correct.saturating_add(entry.correct); + old.wrong = old.wrong.saturating_add(entry.wrong); + old.hints = old.hints.saturating_add(entry.hints); + if entry.last_attempt > old.last_attempt { + old.streak = entry.streak; + } + old.last_attempt = old.last_attempt.max(entry.last_attempt); + old.last_seen = old.last_seen.max(entry.last_seen); + old.recent.extend(entry.recent); + old.recent.sort_by_key(|attempt| attempt.at); + if old.recent.len() > RECENT { + old.recent.drain(..old.recent.len() - RECENT); + } + } else { + merged.push(entry); + } + } + self.move_stats = merged; + } + + pub(crate) fn normalize(&mut self) { + self.move_stats.sort_by(|a, b| a.key.cmp(&b.key)); + self.move_stats.dedup_by(|a, b| a.key == b.key); + self.runs + .sort_by(|a, b| (&a.repertoire_id, &a.mode).cmp(&(&b.repertoire_id, &b.mode))); + self.path_stats.sort_by(|a, b| a.key.cmp(&b.key)); + self.review_cursors.sort_by(|a, b| { + (&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope)) + }); + self.practice_path_cursors.sort_by(|a, b| { + (&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope)) + }); + self.random_practice_cursors.sort_by(|a, b| { + (&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope)) + }); + self.path_review_cursors + .sort_by(|a, b| (&a.repertoire_id, &a.scope).cmp(&(&b.repertoire_id, &b.scope))); + } +} diff --git a/crates/trainer/src/repertoire/store.rs b/crates/trainer/src/repertoire/store.rs new file mode 100644 index 0000000..35028b6 --- /dev/null +++ b/crates/trainer/src/repertoire/store.rs @@ -0,0 +1,1136 @@ +use std::collections::{BTreeSet, HashMap}; +use std::io; +use std::path::{Path, PathBuf}; + +use chess_core::pgn::store::write_atomic; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use super::learning::{ + AttemptApplication, LearningData, LearningError, LearningItem, LearningItemKey, TrainingAttempt, +}; +use super::learning_analytics::{LearningSnapshot, LocalDatePolicy, same_snapshot_slot}; +use super::learning_graph::{LearningGraphError, StatsScope}; +use super::learning_session::{LearningSessionError, LearningSessionSnapshot}; +use super::model::{LIBRARY_VERSION, Library, RepertoireError}; +use super::scope::TrainingScopeKey; +use super::srs::SrsSettings; +use super::stats::{QueueMode, STATS_VERSION, StatsData, TrainingMode}; + +#[path = "migration.rs"] +mod migration; +pub use migration::MigrationReport; + +#[derive(Debug)] +pub enum StoreError { + Io { + path: PathBuf, + source: io::Error, + }, + Json { + path: PathBuf, + source: serde_json::Error, + }, + UnsupportedVersion { + kind: &'static str, + version: u32, + path: PathBuf, + }, + MissingVersion { + kind: &'static str, + path: PathBuf, + }, + DuplicateStats(PathBuf), + Conflict { + path: PathBuf, + expected: u64, + actual: u64, + }, + LegacyPath(PathBuf), + SessionConflict { + session_id: String, + expected: u64, + actual: u64, + }, + SessionMismatch { + attempt_session_id: String, + session_id: String, + }, + Repertoire(RepertoireError), + Learning(LearningError), + LearningGraph(LearningGraphError), + Session(LearningSessionError), +} + +impl std::fmt::Display for StoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io { path, source } => write!(f, "I/O error at {}: {source}", path.display()), + Self::Json { path, source } => { + write!(f, "invalid JSON at {}: {source}", path.display()) + } + Self::UnsupportedVersion { + kind, + version, + path, + } => write!( + f, + "unsupported {kind} schema version {version} at {}", + path.display() + ), + Self::MissingVersion { kind, path } => { + write!(f, "{kind} at {} has no schema version", path.display()) + } + Self::DuplicateStats(path) => { + write!(f, "duplicate training keys in {}", path.display()) + } + Self::Conflict { + path, + expected, + actual, + } => write!( + f, + "concurrent modification of {}: loaded revision {expected}, disk revision {actual}; reload and retry", + path.display() + ), + Self::LegacyPath(path) => write!( + f, + "legacy training file must be different from the new statistics file: {}", + path.display() + ), + Self::SessionConflict { + session_id, + expected, + actual, + } => write!( + f, + "concurrent modification of learning session {session_id}: loaded revision {expected}, disk revision {actual}; reload and retry" + ), + Self::SessionMismatch { + attempt_session_id, + session_id, + } => write!( + f, + "training attempt belongs to session {attempt_session_id}, not {session_id}" + ), + Self::Repertoire(error) => error.fmt(f), + Self::Learning(error) => write!(f, "cannot apply training attempt: {error}"), + Self::LearningGraph(error) => write!(f, "cannot capture learning statistics: {error}"), + Self::Session(error) => write!(f, "invalid learning session: {error}"), + } + } +} + +impl std::error::Error for StoreError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io { source, .. } => Some(source), + Self::Json { source, .. } => Some(source), + Self::Repertoire(error) => Some(error), + Self::Learning(error) => Some(error), + Self::LearningGraph(error) => Some(error), + Self::Session(error) => Some(error), + _ => None, + } + } +} + +impl From for StoreError { + fn from(error: RepertoireError) -> Self { + Self::Repertoire(error) + } +} + +impl From for StoreError { + fn from(error: LearningError) -> Self { + Self::Learning(error) + } +} + +impl From for StoreError { + fn from(error: LearningGraphError) -> Self { + Self::LearningGraph(error) + } +} + +impl From for StoreError { + fn from(error: LearningSessionError) -> Self { + Self::Session(error) + } +} + +fn io(path: &Path, source: io::Error) -> StoreError { + StoreError::Io { + path: path.to_owned(), + source, + } +} + +fn json(path: &Path, source: serde_json::Error) -> StoreError { + StoreError::Json { + path: path.to_owned(), + source, + } +} + +// Lock a stable sidecar: the data file itself is replaced by atomic rename. Keeping +// the lock file avoids unlink/open races and the OS releases its lock after a crash. +fn lock_store(path: &Path) -> Result { + let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned()); + if let Some(parent) = target.parent().filter(|p| !p.as_os_str().is_empty()) { + std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?; + } + let mut lock_name = target.file_name().unwrap_or_default().to_os_string(); + lock_name.push(".lock"); + let lock_path = target.with_file_name(lock_name); + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .read(true) + .open(&lock_path) + .map_err(|e| io(&lock_path, e))?; + lock.lock().map_err(|e| io(&lock_path, e))?; + Ok(lock) +} + +fn read_optional(path: &Path) -> Result>, StoreError> { + match std::fs::read(path) { + Ok(bytes) => Ok(Some(bytes)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(io(path, error)), + } +} + +fn decode_versioned( + path: &Path, + bytes: &[u8], + kind: &'static str, + supported: u32, +) -> Result { + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| json(path, e))?; + let version = value + .get("version") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| StoreError::MissingVersion { + kind, + path: path.to_owned(), + })?; + let version = u32::try_from(version).unwrap_or(u32::MAX); + if version != supported { + return Err(StoreError::UnsupportedVersion { + kind, + version, + path: path.to_owned(), + }); + } + serde_json::from_value(value).map_err(|e| json(path, e)) +} + +#[derive(Clone, Debug)] +pub struct LibraryStore { + path: PathBuf, +} + +impl LibraryStore { + pub fn new(path: impl Into) -> Self { + Self { path: path.into() } + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// A missing new library is empty. Existing unreadable or unsupported data is an + /// error, never silently replaced by an empty library. + pub fn load(&self) -> Result { + let Some(bytes) = read_optional(&self.path)? else { + return Ok(Library::default()); + }; + let library: Library = + decode_versioned(&self.path, &bytes, "repertoire library", LIBRARY_VERSION)?; + library.validate()?; + Ok(library) + } + + /// Optimistic concurrency: a stale in-memory snapshot is rejected rather than + /// overwriting another process's additions. The caller reloads and reapplies its edit. + pub fn save(&self, library: &mut Library) -> Result<(), StoreError> { + library.validate()?; + let _lock = lock_store(&self.path)?; + let current = self.load()?; + if current.revision != library.revision { + return Err(StoreError::Conflict { + path: self.path.clone(), + expected: library.revision, + actual: current.revision, + }); + } + let previous = library.revision; + library.version = LIBRARY_VERSION; + library.revision = current.revision.saturating_add(1); + let bytes = serde_json::to_vec_pretty(library).map_err(|e| json(&self.path, e))?; + if let Err(error) = write_atomic(&self.path, &bytes) { + library.revision = previous; + return Err(io(&self.path, error)); + } + Ok(()) + } +} + +#[allow(dead_code)] +pub const LEARNING_STORE_VERSION: u32 = 3; + +#[allow(dead_code)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LearningSession { + pub id: String, + pub mode: QueueMode, + pub side: TrainingMode, + pub scope: TrainingScopeKey, + pub settings: SrsSettings, +} + +#[allow(dead_code)] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct LearningStoreData { + pub version: u32, + #[serde(default)] + pub revision: u64, + pub learning: LearningData, + #[serde(default)] + pub sessions: Vec, + #[serde(default)] + pub session_snapshots: Vec, + #[serde(default)] + pub snapshots: Vec, + /// Original v2 JSON, including unknown root and nested extension fields. + #[serde(default)] + pub legacy_practice: Option, + #[serde(flatten)] + pub extensions: std::collections::BTreeMap, +} + +impl Default for LearningStoreData { + fn default() -> Self { + Self { + version: LEARNING_STORE_VERSION, + revision: 0, + learning: LearningData::default(), + sessions: Vec::new(), + session_snapshots: Vec::new(), + snapshots: Vec::new(), + legacy_practice: None, + extensions: std::collections::BTreeMap::new(), + } + } +} + +impl LearningStoreData { + pub fn session_snapshot(&self, id: &str) -> Option<&LearningSessionSnapshot> { + self.session_snapshots + .iter() + .find(|snapshot| snapshot.id() == id) + } +} + +#[allow(dead_code)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PersistedAttempt { + pub application: AttemptApplication, + pub revision: u64, + pub learning: LearningData, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PersistedLearningReset { + pub revision: u64, + pub learning: LearningData, + pub reset_count: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PersistedLearningSnapshot { + pub snapshot: LearningSnapshot, + pub revision: u64, + pub recorded: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PersistedSessionAttempt { + pub application: AttemptApplication, + pub revision: u64, + pub learning: LearningData, + pub session: LearningSessionSnapshot, +} + +#[allow(dead_code)] +#[derive(Clone, Debug)] +pub struct LearningStore { + path: PathBuf, + legacy_path: Option, +} + +#[allow(dead_code)] +#[derive(Clone, Debug)] +enum LearningSource { + Missing, + V2(Vec), + V3(serde_json::Value), + LegacyLines, +} + +#[allow(dead_code)] +#[derive(Clone, Debug)] +struct LoadedLearning { + data: LearningStoreData, + report: MigrationReport, + source: LearningSource, +} + +#[allow(dead_code)] +impl LearningStore { + pub fn new(path: impl Into) -> Self { + Self { + path: path.into(), + legacy_path: None, + } + } + + /// The legacy line file is read only. All v3 writes target `path`. + pub fn with_legacy(path: impl Into, legacy_path: impl Into) -> Self { + Self { + path: path.into(), + legacy_path: Some(legacy_path.into()), + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn legacy_path(&self) -> Option<&Path> { + self.legacy_path.as_deref() + } + + pub fn load(&self) -> Result { + self.load_with_report().map(|(data, _)| data) + } + + pub fn load_with_report(&self) -> Result<(LearningStoreData, MigrationReport), StoreError> { + let loaded = self.load_latest()?; + Ok((loaded.data, loaded.report)) + } + + /// Writes an existing v2 or legacy-line source as v3. An already current or missing + /// store is left untouched, which makes repeated migration idempotent. + pub fn migrate(&self) -> Result { + self.check_legacy_path()?; + let _lock = lock_store(&self.path)?; + let mut loaded = self.load_latest()?; + if matches!( + loaded.source, + LearningSource::Missing | LearningSource::V3(_) + ) { + return Ok(loaded.report); + } + let report = loaded.report; + self.write_latest(&mut loaded)?; + Ok(report) + } + + /// Reloads under the cross-process lock, then persists the event and its learning + /// effect in one atomic replacement. Duplicate delivery never rewrites the file. + pub fn apply_attempt( + &self, + attempt: TrainingAttempt, + settings: &SrsSettings, + ) -> Result { + self.check_legacy_path()?; + let _lock = lock_store(&self.path)?; + let mut loaded = self.load_latest()?; + let application = loaded.data.learning.apply_attempt(attempt, settings)?; + if application == AttemptApplication::Duplicate { + return Ok(PersistedAttempt { + application, + revision: loaded.data.revision, + learning: loaded.data.learning, + }); + } + self.write_latest(&mut loaded)?; + Ok(PersistedAttempt { + application, + revision: loaded.data.revision, + learning: loaded.data.learning, + }) + } + + pub fn record_snapshot( + &self, + library: &Library, + scope: &StatsScope, + settings: &SrsSettings, + timezone: LocalDatePolicy, + ) -> Result { + self.check_legacy_path()?; + let _lock = lock_store(&self.path)?; + let mut loaded = self.load_latest()?; + let snapshot = + LearningSnapshot::capture(library, &loaded.data.learning, scope, settings, timezone)?; + if let Some(existing) = loaded + .data + .snapshots + .iter() + .find(|existing| same_snapshot_slot(existing, &snapshot)) + { + return Ok(PersistedLearningSnapshot { + snapshot: existing.clone(), + revision: loaded.data.revision, + recorded: false, + }); + } + loaded.data.snapshots.push(snapshot.clone()); + self.write_latest(&mut loaded)?; + Ok(PersistedLearningSnapshot { + snapshot, + revision: loaded.data.revision, + recorded: true, + }) + } + + pub fn reset_learning( + &self, + keys: impl IntoIterator, + ) -> Result + where + K: std::borrow::Borrow, + { + self.check_legacy_path()?; + let keys: BTreeSet = + keys.into_iter().map(|key| key.borrow().clone()).collect(); + let _lock = lock_store(&self.path)?; + let mut loaded = self.load_latest()?; + let mut reset_count = 0; + for item in &mut loaded.data.learning.items { + if keys.contains(&item.key) { + *item = LearningItem::new(item.key.clone()); + reset_count += 1; + } + } + if reset_count > 0 { + self.write_latest(&mut loaded)?; + } + Ok(PersistedLearningReset { + revision: loaded.data.revision, + learning: loaded.data.learning, + reset_count, + }) + } + + /// Persists a queue-only lifecycle change without replacing learning history. + pub fn save_session(&self, session: &mut LearningSessionSnapshot) -> Result { + self.check_legacy_path()?; + session.validate_configuration()?; + let _lock = lock_store(&self.path)?; + let mut loaded = self.load_latest()?; + check_session_revision(&loaded.data, session)?; + let previous = session.revision; + session.revision = session.revision.saturating_add(1); + upsert_session(&mut loaded.data, session); + if let Err(error) = self.write_latest(&mut loaded) { + session.revision = previous; + return Err(error); + } + Ok(loaded.data.revision) + } + + pub fn reset_review_order( + &self, + session: &mut LearningSessionSnapshot, + ) -> Result { + let mut reset = session.clone(); + reset.reset_review_order()?; + let revision = self.save_session(&mut reset)?; + *session = reset; + Ok(revision) + } + + /// Applies one event and its session transition in the same atomic replacement. Both + /// are based on the latest store contents loaded under the cross-process lock. + pub fn apply_attempt_and_session( + &self, + attempt: TrainingAttempt, + session: &mut LearningSessionSnapshot, + ) -> Result { + self.apply_attempts_and_session(vec![attempt], session) + } + + /// Persists an already displayed context prefix in one atomic transaction. + /// Every event is retained, but the store is read and replaced only once. + /// A retry must contain the whole batch: partial duplicates are rejected. + pub fn apply_attempts_and_session( + &self, + attempts: Vec, + session: &mut LearningSessionSnapshot, + ) -> Result { + self.check_legacy_path()?; + let invalid = |message| StoreError::Session(LearningSessionError::InvalidSnapshot(message)); + if attempts.is_empty() { + return Err(invalid("an attempt batch must not be empty")); + } + let mut identities = BTreeSet::new(); + for attempt in &attempts { + if attempt.session_id != session.session.id { + return Err(StoreError::SessionMismatch { + attempt_session_id: attempt.session_id.clone(), + session_id: session.session.id.clone(), + }); + } + if !identities.insert((&attempt.user_id, &attempt.client_attempt_id)) { + return Err(invalid("an attempt batch contains duplicate event IDs")); + } + } + let _lock = lock_store(&self.path)?; + let mut loaded = self.load_latest()?; + let mut unseen = identities; + for existing in &loaded.data.learning.attempts { + unseen.remove(&(&existing.user_id, &existing.client_attempt_id)); + if unseen.is_empty() { + break; + } + } + let duplicate_count = attempts.len() - unseen.len(); + if duplicate_count == attempts.len() { + let persisted_session = loaded + .data + .session_snapshot(&session.session.id) + .cloned() + .unwrap_or_else(|| session.clone()); + return Ok(PersistedSessionAttempt { + application: AttemptApplication::Duplicate, + revision: loaded.data.revision, + learning: loaded.data.learning, + session: persisted_session, + }); + } + if duplicate_count != 0 { + return Err(invalid("an attempt batch is only partially persisted")); + } + + session.validate_configuration()?; + check_session_revision(&loaded.data, session)?; + for attempt in attempts { + loaded + .data + .learning + .apply_attempt(attempt, &session.session.settings)?; + } + let previous = session.revision; + session.revision = session.revision.saturating_add(1); + upsert_session(&mut loaded.data, session); + if let Err(error) = self.write_latest(&mut loaded) { + session.revision = previous; + return Err(error); + } + Ok(PersistedSessionAttempt { + application: AttemptApplication::Applied, + revision: loaded.data.revision, + learning: loaded.data.learning, + session: session.clone(), + }) + } + + fn check_legacy_path(&self) -> Result<(), StoreError> { + if self.legacy_path.as_ref() == Some(&self.path) { + Err(StoreError::LegacyPath(self.path.clone())) + } else { + Ok(()) + } + } + + fn load_latest(&self) -> Result { + if let Some(bytes) = read_optional(&self.path)? { + let value: serde_json::Value = + serde_json::from_slice(&bytes).map_err(|e| json(&self.path, e))?; + let version = value + .get("version") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| StoreError::MissingVersion { + kind: "repertoire learning", + path: self.path.clone(), + })?; + let version = u32::try_from(version).unwrap_or(u32::MAX); + return match version { + STATS_VERSION => { + let legacy_practice = value.clone(); + let stats: StatsData = + serde_json::from_value(value).map_err(|e| json(&self.path, e))?; + validate_stats(&self.path, &stats)?; + let (learning, report) = migration::migrate_v2(&stats); + Ok(LoadedLearning { + data: LearningStoreData { + revision: stats.revision, + learning, + legacy_practice: Some(legacy_practice), + ..LearningStoreData::default() + }, + report, + source: LearningSource::V2(bytes), + }) + } + LEARNING_STORE_VERSION => { + let schema_error = |message| { + json( + &self.path, + ::custom(message), + ) + }; + let learning = value + .get("learning") + .and_then(serde_json::Value::as_object) + .ok_or_else(|| schema_error("v3 learning must be an object"))?; + for field in ["items", "attempts"] { + if learning.get(field).is_some_and(|value| !value.is_array()) { + return Err(schema_error("v3 learning items/attempts must be arrays")); + } + } + if value + .get("legacy_practice") + .is_some_and(|value| !value.is_null() && !value.is_object()) + { + return Err(schema_error("v3 legacy_practice must be an object or null")); + } + let data: LearningStoreData = + serde_json::from_value(value.clone()).map_err(|e| json(&self.path, e))?; + Ok(LoadedLearning { + data, + report: MigrationReport::default(), + source: LearningSource::V3(value), + }) + } + _ => Err(StoreError::UnsupportedVersion { + kind: "repertoire learning", + version, + path: self.path.clone(), + }), + }; + } + + let Some(legacy_path) = self.legacy_path.as_deref() else { + return Ok(LoadedLearning { + data: LearningStoreData::default(), + report: MigrationReport::default(), + source: LearningSource::Missing, + }); + }; + let Some(bytes) = read_optional(legacy_path)? else { + return Ok(LoadedLearning { + data: LearningStoreData::default(), + report: MigrationReport::default(), + source: LearningSource::Missing, + }); + }; + let legacy_lines: serde_json::Map = + serde_json::from_slice(&bytes).map_err(|e| json(legacy_path, e))?; + let mut legacy = StatsData::default(); + legacy.legacy_lines = legacy_lines; + let legacy_practice = serde_json::to_value(legacy).map_err(|e| json(legacy_path, e))?; + Ok(LoadedLearning { + data: LearningStoreData { + legacy_practice: Some(legacy_practice), + ..LearningStoreData::default() + }, + report: MigrationReport::default(), + source: LearningSource::LegacyLines, + }) + } + + fn write_latest(&self, loaded: &mut LoadedLearning) -> Result<(), StoreError> { + if let LearningSource::V2(bytes) = &loaded.source { + self.backup_v2_once(bytes)?; + } + loaded.data.version = LEARNING_STORE_VERSION; + loaded.data.revision = loaded.data.revision.saturating_add(1); + let current = serde_json::to_value(&loaded.data).map_err(|e| json(&self.path, e))?; + let value = match &loaded.source { + LearningSource::V3(raw) => preserve_extensions(raw, current), + _ => current, + }; + let bytes = serde_json::to_vec_pretty(&value).map_err(|e| json(&self.path, e))?; + write_atomic(&self.path, &bytes).map_err(|e| io(&self.path, e)) + } + + fn backup_v2_once(&self, bytes: &[u8]) -> Result<(), StoreError> { + let backup = learning_backup_path(&self.path); + match std::fs::metadata(&backup) { + Ok(metadata) if metadata.is_file() => return Ok(()), + Ok(_) => { + return Err(io( + &backup, + io::Error::new(io::ErrorKind::AlreadyExists, "backup path is not a file"), + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(io(&backup, error)), + } + write_atomic(&backup, bytes).map_err(|e| io(&backup, e)) + } +} + +/// Known values come from current state; unmodelled object fields remain from raw JSON. +fn preserve_extensions(raw: &serde_json::Value, current: serde_json::Value) -> serde_json::Value { + if current.as_object().is_some_and(|object| object.len() == 3) + && learning_item_key_fields(¤t).is_some() + { + return current; + } + match (raw, current) { + (serde_json::Value::Object(raw), serde_json::Value::Object(current)) => { + let mut merged = raw.clone(); + for (field, value) in current { + let value = match raw.get(&field) { + Some(raw) => preserve_extensions(raw, value), + None => value, + }; + merged.insert(field, value); + } + serde_json::Value::Object(merged) + } + (serde_json::Value::Array(raw), serde_json::Value::Array(current)) => { + let current_len = current.len(); + // Match persisted records by identity once, rather than scanning the entire + // history for every event on every save. First match preserves legacy semantics. + let mut by_identity = HashMap::with_capacity(raw.len()); + for previous in raw { + if let Some(identity) = stable_json_identity(previous) { + by_identity.entry(identity).or_insert(previous); + } + } + let merged = current + .into_iter() + .enumerate() + .map(|(index, value)| { + let previous = match stable_json_identity(&value) { + Some(identity) => by_identity.get(&identity).copied(), + None if raw.len() == current_len => raw.get(index), + None => None, + }; + match previous { + Some(raw) => preserve_extensions(raw, value), + None => value, + } + }) + .collect(); + serde_json::Value::Array(merged) + } + (_, current) => current, + } +} + +fn stable_json_identity(value: &serde_json::Value) -> Option { + let object = value.as_object()?; + if let (Some(user_id), Some(client_attempt_id)) = ( + object.get("user_id").and_then(serde_json::Value::as_str), + object + .get("client_attempt_id") + .and_then(serde_json::Value::as_str), + ) { + return Some(json_identity(&["attempt", user_id, client_attempt_id])); + } + if let Some((user_id, position_fen4, expected_uci)) = learning_item_key_fields(value) { + return Some(json_identity(&[ + "key", + user_id, + position_fen4, + expected_uci, + ])); + } + if let Some(key) = object.get("key") + && let Some((user_id, position_fen4, expected_uci)) = learning_item_key_fields(key) + { + let repertoire_id = object + .get("repertoire_id") + .and_then(serde_json::Value::as_str) + .unwrap_or_default(); + return Some(json_identity(&[ + "nested-key", + user_id, + position_fen4, + expected_uci, + repertoire_id, + ])); + } + if let (Some(date), Some(scope)) = ( + object.get("date").and_then(serde_json::Value::as_str), + object.get("scope"), + ) { + let mut scope = scope.clone(); + if let Some(object) = scope.as_object_mut() { + object.retain(|field, _| { + matches!( + field.as_str(), + "repertoire_ids" + | "side" + | "max_depth" + | "only_active" + | "branch_root" + | "as_of" + | "learning_priority" + ) + }); + } + let scope = scope.to_string(); + return Some(json_identity(&["learning-snapshot", date, &scope])); + } + if let Some(id) = object + .get("session") + .and_then(|session| session.get("id")) + .and_then(serde_json::Value::as_str) + { + return Some(json_identity(&["snapshot", id])); + } + object + .get("id") + .and_then(serde_json::Value::as_str) + .map(|id| json_identity(&["id", id])) +} + +fn learning_item_key_fields(value: &serde_json::Value) -> Option<(&str, &str, &str)> { + let object = value.as_object()?; + if object.contains_key("client_attempt_id") { + return None; + } + Some(( + object.get("user_id")?.as_str()?, + object.get("position_fen4")?.as_str()?, + object.get("expected_uci")?.as_str()?, + )) +} + +fn json_identity(parts: &[&str]) -> String { + serde_json::Value::Array( + parts + .iter() + .map(|part| serde_json::Value::String((*part).to_owned())) + .collect(), + ) + .to_string() +} + +fn check_session_revision( + data: &LearningStoreData, + session: &LearningSessionSnapshot, +) -> Result<(), StoreError> { + let actual = data + .session_snapshot(&session.session.id) + .map_or(0, |persisted| persisted.revision); + if session.revision == actual { + Ok(()) + } else { + Err(StoreError::SessionConflict { + session_id: session.session.id.clone(), + expected: session.revision, + actual, + }) + } +} + +fn upsert_session(data: &mut LearningStoreData, session: &LearningSessionSnapshot) { + if let Some(existing) = data + .sessions + .iter_mut() + .find(|existing| existing.id == session.session.id) + { + *existing = session.session.clone(); + } else { + data.sessions.push(session.session.clone()); + } + if let Some(existing) = data + .session_snapshots + .iter_mut() + .find(|existing| existing.session.id == session.session.id) + { + *existing = session.clone(); + } else { + data.session_snapshots.push(session.clone()); + } +} + +fn learning_backup_path(path: &Path) -> PathBuf { + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(".before-learning-v3"); + path.with_file_name(name) +} + +#[derive(Clone, Debug)] +pub struct StatsStore { + path: PathBuf, + legacy_path: Option, +} + +impl StatsStore { + /// A store for the new versioned format. It does not implicitly read or replace the + /// legacy global `training.json`. + pub fn new(path: impl Into) -> Self { + Self { + path: path.into(), + legacy_path: None, + } + } + + /// A new file plus an optional legacy source. Saving always writes `path`; the legacy + /// source is copied once to `.before-repertoire-v2` and is never renamed or overwritten. + pub fn with_legacy(path: impl Into, legacy_path: impl Into) -> Self { + Self { + path: path.into(), + legacy_path: Some(legacy_path.into()), + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn legacy_path(&self) -> Option<&Path> { + self.legacy_path.as_deref() + } + + pub fn load(&self) -> Result { + if let Some(bytes) = read_optional(&self.path)? { + let mut stats: StatsData = + decode_versioned(&self.path, &bytes, "repertoire statistics", STATS_VERSION)?; + validate_stats(&self.path, &stats)?; + stats.migrate_position_stats(); + return Ok(stats); + } + let Some(legacy_path) = self.legacy_path.as_deref() else { + return Ok(StatsData::default()); + }; + let Some(bytes) = read_optional(legacy_path)? else { + return Ok(StatsData::default()); + }; + let legacy_lines: serde_json::Map = + serde_json::from_slice(&bytes).map_err(|e| json(legacy_path, e))?; + let mut stats = StatsData::default(); + stats.legacy_lines = legacy_lines; + Ok(stats) + } + + pub fn save(&self, stats: &mut StatsData) -> Result<(), StoreError> { + if self.legacy_path.as_ref() == Some(&self.path) { + return Err(StoreError::LegacyPath(self.path.clone())); + } + validate_stats(&self.path, stats)?; + let _lock = lock_store(&self.path)?; + let current = self.load()?; + if current.revision != stats.revision { + return Err(StoreError::Conflict { + path: self.path.clone(), + expected: stats.revision, + actual: current.revision, + }); + } + self.backup_legacy_once()?; + let previous = stats.revision; + stats.version = STATS_VERSION; + stats.revision = current.revision.saturating_add(1); + stats.normalize(); + let bytes = serde_json::to_vec_pretty(stats).map_err(|e| json(&self.path, e))?; + if let Err(error) = write_atomic(&self.path, &bytes) { + stats.revision = previous; + return Err(io(&self.path, error)); + } + Ok(()) + } + + fn backup_legacy_once(&self) -> Result<(), StoreError> { + let Some(legacy) = self.legacy_path.as_deref() else { + return Ok(()); + }; + let Some(bytes) = read_optional(legacy)? else { + return Ok(()); + }; + let backup = legacy_backup_path(legacy); + if backup.exists() { + return Ok(()); + } + write_atomic(&backup, &bytes).map_err(|e| io(&backup, e)) + } +} + +fn legacy_backup_path(legacy: &Path) -> PathBuf { + let mut name = legacy.file_name().unwrap_or_default().to_os_string(); + name.push(".before-repertoire-v2"); + legacy.with_file_name(name) +} + +fn validate_stats(path: &Path, stats: &StatsData) -> Result<(), StoreError> { + let mut moves = BTreeSet::new(); + let mut runs = BTreeSet::new(); + let mut paths = BTreeSet::new(); + let valid = stats + .move_stats + .iter() + .all(|entry| moves.insert(&entry.key)) + && stats + .runs + .iter() + .all(|entry| runs.insert((&entry.repertoire_id, &entry.mode))) + && stats + .path_stats + .iter() + .all(|entry| paths.insert(&entry.key)); + if valid { + Ok(()) + } else { + Err(StoreError::DuplicateStats(path.to_owned())) + } +} + +#[cfg(test)] +mod lock_tests { + use super::*; + + #[test] + fn child_exits_while_holding_store_lock() { + let Some(path) = std::env::var_os("CP_TRAINER_LOCK_EXIT_TEST") else { + return; + }; + let _lock = lock_store(Path::new(&path)).unwrap(); + // process::exit skips Rust destructors, as does abrupt process termination. + std::process::exit(0); + } + + #[test] + fn store_lock_is_released_on_drop_and_process_exit() { + let path = + std::env::temp_dir().join(format!("cp-store-lock-exit-{}.json", std::process::id())); + let lock_path = path.with_file_name(format!( + "{}.lock", + path.file_name().unwrap().to_string_lossy() + )); + drop(lock_store(&path).unwrap()); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(&lock_path) + .unwrap(); + file.try_lock().unwrap(); + file.unlock().unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .arg("--exact") + .arg("repertoire::store::lock_tests::child_exits_while_holding_store_lock") + .env("CP_TRAINER_LOCK_EXIT_TEST", &path) + .status() + .unwrap(); + assert!(status.success()); + assert!(lock_path.exists()); + file.try_lock().unwrap(); + file.unlock().unwrap(); + std::fs::remove_file(lock_path).unwrap(); + } +} + +#[cfg(test)] +#[path = "store_tests.rs"] +mod store_tests; diff --git a/crates/trainer/src/repertoire/store_tests.rs b/crates/trainer/src/repertoire/store_tests.rs new file mode 100644 index 0000000..a3db3ba --- /dev/null +++ b/crates/trainer/src/repertoire/store_tests.rs @@ -0,0 +1,921 @@ +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Barrier}; + +use super::*; +use crate::repertoire::learning::{LearningItemKey, TrainingEventType}; +use crate::repertoire::learning_graph::StatsScope; +use crate::repertoire::model::{LearningSide, RepertoireId}; +use crate::repertoire::stats::{MoveKey, MoveStats}; + +static NEXT_DIR: AtomicU64 = AtomicU64::new(1); + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let sequence = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "cp-learning-store-{}-{}-{name}", + std::process::id(), + sequence + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn join(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn legacy_move(repertoire: &str, mode: TrainingMode, expected_uci: &str) -> MoveStats { + MoveStats::new(MoveKey { + repertoire_id: RepertoireId::legacy(repertoire), + mode, + position_fen4: "fen-shared".into(), + expected_uci: expected_uci.into(), + }) +} + +fn attempt(id: &str, happened_at: i64) -> TrainingAttempt { + TrainingAttempt { + user_id: "local".into(), + position_fen4: "fen-shared".into(), + client_attempt_id: id.into(), + session_id: "session-1".into(), + event_type: TrainingEventType::CorrectIndependent, + expected_uci: "e2e4".into(), + actual_uci: Some("e2e4".into()), + response_time_ms: Some(250), + happened_at, + } +} + +fn write_json(path: &Path, value: &impl Serialize) -> Vec { + let bytes = serde_json::to_vec_pretty(value).unwrap(); + std::fs::write(path, &bytes).unwrap(); + bytes +} + +fn read_json(path: &Path) -> serde_json::Value { + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() +} + +fn extension_marker() -> serde_json::Value { + serde_json::json!({"preserved": [1, {"nested": true}]}) +} + +const V3_EXTENSION_POINTERS: &[&str] = &[ + "/future_top_level_field", + "/learning/future_learning_field", + "/learning/items/0/future_item_field", + "/learning/attempts/0/future_attempt_field", + "/sessions/0/future_session_field", + "/session_snapshots/0/future_snapshot_field", + "/session_snapshots/0/session/future_nested_session_field", + "/session_snapshots/0/session/settings/future_settings_field", + "/session_snapshots/0/stats_scope/future_scope_field", + "/session_snapshots/0/queue/0/future_target_field", +]; + +fn assert_v3_extensions(value: &serde_json::Value) { + for pointer in V3_EXTENSION_POINTERS { + assert_eq!( + value.pointer(pointer), + Some(&extension_marker()), + "{pointer}" + ); + } +} + +fn extension_fixture() -> (LearningStoreData, Library) { + let mut library = Library::default(); + let repertoire_id = library + .create("Test", &chess_core::parse_str("1. e4 *").game) + .unwrap(); + let scope = StatsScope::for_repertoire(repertoire_id, LearningSide::White, 0); + let key = crate::repertoire::learning_graph::active_learning_memberships(&library, &scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == "e2e4") + .unwrap() + .key; + let mut learning = LearningData::default(); + let item = learning.ensure_item(key); + item.introduced = true; + item.next_review_at = Some(0); + learning.attempts.push(attempt("existing", 0)); + let snapshot = LearningSessionSnapshot::new( + "session-1", + &library, + &learning, + scope, + SrsSettings::default(), + ) + .unwrap(); + assert_eq!(snapshot.queue.len(), 1); + let data = LearningStoreData { + learning, + sessions: vec![snapshot.session.clone()], + session_snapshots: vec![snapshot], + ..LearningStoreData::default() + }; + (data, library) +} + +fn inject_v3_extensions(value: &mut serde_json::Value) { + value["future_top_level_field"] = extension_marker(); + value["learning"]["future_learning_field"] = extension_marker(); + value["learning"]["items"][0]["future_item_field"] = extension_marker(); + value["learning"]["items"][0]["key"]["future_key_extension"] = serde_json::json!(true); + value["learning"]["attempts"][0]["future_attempt_field"] = extension_marker(); + value["sessions"][0]["future_session_field"] = extension_marker(); + value["session_snapshots"][0]["future_snapshot_field"] = extension_marker(); + value["session_snapshots"][0]["session"]["future_nested_session_field"] = extension_marker(); + value["session_snapshots"][0]["session"]["settings"]["future_settings_field"] = + extension_marker(); + value["session_snapshots"][0]["stats_scope"]["future_scope_field"] = extension_marker(); + value["session_snapshots"][0]["queue"][0]["future_target_field"] = extension_marker(); +} + +#[cfg(unix)] +fn file_inode(path: &Path) -> u64 { + use std::os::unix::fs::MetadataExt as _; + std::fs::metadata(path).unwrap().ino() +} + +#[test] +fn at_23_duplicate_attempt_has_one_effect_and_one_file_replacement() { + let dir = TestDir::new("duplicate"); + let path = dir.join("repertoire-training.json"); + let store = LearningStore::new(&path); + let first_attempt = attempt("attempt-1", 1_000); + + let first = store + .apply_attempt(first_attempt.clone(), &SrsSettings::default()) + .unwrap(); + assert_eq!(first.application, AttemptApplication::Applied); + assert_eq!(first.revision, 1); + assert_eq!(first.learning.attempts.len(), 1); + let key = LearningItemKey::local("fen-shared", "e2e4"); + assert_eq!(first.learning.item(&key).unwrap().correct_streak, 1); + assert_eq!(first.learning.item(&key).unwrap().correct_count, 1); + let bytes_after_first = std::fs::read(&path).unwrap(); + #[cfg(unix)] + let inode_after_first = file_inode(&path); + + let duplicate = store + .apply_attempt(first_attempt, &SrsSettings::default()) + .unwrap(); + assert_eq!(duplicate.application, AttemptApplication::Duplicate); + assert_eq!(duplicate.revision, first.revision); + assert_eq!(duplicate.learning, first.learning); + assert_eq!(std::fs::read(&path).unwrap(), bytes_after_first); + #[cfg(unix)] + assert_eq!(file_inode(&path), inode_after_first); + + let different = store + .apply_attempt(attempt("attempt-2", 2_000), &SrsSettings::default()) + .unwrap(); + assert_eq!(different.application, AttemptApplication::Applied); + assert_eq!(different.revision, 2); + assert_eq!(different.learning.attempts.len(), 2); + assert_eq!(different.learning.item(&key).unwrap().correct_streak, 2); + assert_eq!(different.learning.item(&key).unwrap().correct_count, 2); +} + +#[test] +fn attempt_ids_are_scoped_to_user_and_different_ids_are_not_suppressed() { + let dir = TestDir::new("attempt-scope"); + let store = LearningStore::new(dir.join("repertoire-training.json")); + let mut other_user = attempt("shared-client-id", 10); + other_user.user_id = "other-profile".into(); + assert_eq!( + store + .apply_attempt(other_user, &SrsSettings::default()) + .unwrap() + .application, + AttemptApplication::Applied + ); + let local = store + .apply_attempt(attempt("shared-client-id", 11), &SrsSettings::default()) + .unwrap(); + assert_eq!(local.application, AttemptApplication::Applied); + assert_eq!(local.learning.attempts.len(), 2); + assert_eq!(local.learning.items.len(), 2); +} + +#[test] +fn two_stores_reload_latest_revision_instead_of_overwriting_stale_state() { + let dir = TestDir::new("two-stores"); + let path = dir.join("repertoire-training.json"); + let first = LearningStore::new(&path); + let second = LearningStore::new(&path); + let stale_first = first.load().unwrap(); + let stale_second = second.load().unwrap(); + assert_eq!(stale_first.revision, stale_second.revision); + + let barrier = Arc::new(Barrier::new(3)); + let writers = [ + (first.clone(), "from-first"), + (second.clone(), "from-second"), + ] + .map(|(store, id)| { + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + store.apply_attempt(attempt(id, 100), &SrsSettings::default()) + }) + }); + barrier.wait(); + let mut revisions = writers + .into_iter() + .map(|writer| writer.join().unwrap().unwrap().revision) + .collect::>(); + revisions.sort_unstable(); + assert_eq!(revisions, [1, 2]); + + let third = first + .apply_attempt(attempt("after-both", 200), &SrsSettings::default()) + .unwrap(); + assert_eq!(third.revision, 3); + assert_eq!(third.learning.attempts.len(), 3); + let persisted = second.load().unwrap(); + assert_eq!(persisted.revision, 3); + assert_eq!(persisted.learning.attempts.len(), 3); + assert!(stale_first.learning.attempts.is_empty()); + assert!(stale_second.learning.attempts.is_empty()); +} + +#[test] +fn process_attempt_writer_helper() { + let (Some(path), Some(id)) = ( + std::env::var_os("CP_LEARNING_STORE_CHILD_PATH"), + std::env::var_os("CP_LEARNING_STORE_CHILD_ID"), + ) else { + return; + }; + let id = id.to_string_lossy().into_owned(); + let result = LearningStore::new(PathBuf::from(path)) + .apply_attempt(attempt(&id, 100), &SrsSettings::default()) + .unwrap(); + assert_eq!(result.application, AttemptApplication::Applied); + std::process::exit(0); +} + +#[test] +fn two_processes_and_stale_parent_snapshot_keep_every_attempt() { + let dir = TestDir::new("two-processes"); + let path = dir.join("repertoire-training.json"); + let parent = LearningStore::new(&path); + assert_eq!(parent.load().unwrap().revision, 0); + let executable = std::env::current_exe().unwrap(); + let mut children = ["process-a", "process-b"] + .into_iter() + .map(|id| { + std::process::Command::new(&executable) + .arg("--exact") + .arg("repertoire::store::store_tests::process_attempt_writer_helper") + .env("CP_LEARNING_STORE_CHILD_PATH", &path) + .env("CP_LEARNING_STORE_CHILD_ID", id) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + }) + .collect::>(); + for child in &mut children { + assert!(child.wait().unwrap().success()); + } + + let after_children = parent.load().unwrap(); + assert_eq!(after_children.revision, 2); + assert_eq!(after_children.learning.attempts.len(), 2); + let after_stale_parent = parent + .apply_attempt(attempt("stale-parent", 200), &SrsSettings::default()) + .unwrap(); + assert_eq!(after_stale_parent.revision, 3); + assert_eq!(after_stale_parent.learning.attempts.len(), 3); +} + +#[test] +fn v2_to_v3_is_idempotent_and_backup_is_created_only_once() { + let dir = TestDir::new("migration-idempotent"); + let path = dir.join("repertoire-training.json"); + let mut stats = StatsData::default(); + stats.revision = 4; + stats.legacy_lines.insert( + "old-line".into(), + serde_json::json!({"runs": 3, "unknown": 7}), + ); + let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); + entry.attempts = 5; + entry.correct = 4; + entry.wrong = 1; + entry.streak = 2; + entry.last_seen = Some(100); + entry.due = Some(500); + entry.interval_seconds = Some(400); + stats.move_stats.push(entry); + let original = write_json(&path, &stats); + let store = LearningStore::new(&path); + + let (loaded, report) = store.load_with_report().unwrap(); + assert_eq!(loaded.version, LEARNING_STORE_VERSION); + assert_eq!(loaded.revision, 4); + assert_eq!(loaded.learning.items.len(), 1); + assert_eq!( + serde_json::to_value(&loaded.legacy_practice).unwrap(), + serde_json::to_value(&stats).unwrap() + ); + assert_eq!(report, MigrationReport::default()); + assert_eq!(std::fs::read(&path).unwrap(), original); + + let first_report = store.migrate().unwrap(); + assert_eq!(first_report, MigrationReport::default()); + let backup_path = dir.join("repertoire-training.json.before-learning-v3"); + assert_eq!(std::fs::read(&backup_path).unwrap(), original); + let migrated = store.load().unwrap(); + assert_eq!(migrated.version, 3); + assert_eq!(migrated.revision, 5); + assert_eq!( + serde_json::to_value(&migrated.legacy_practice).unwrap(), + serde_json::to_value(&stats).unwrap() + ); + let first_v3 = std::fs::read(&path).unwrap(); + + assert_eq!(store.migrate().unwrap(), MigrationReport::default()); + assert_eq!(std::fs::read(&path).unwrap(), first_v3); + assert_eq!(std::fs::read(&backup_path).unwrap(), original); + + store + .apply_attempt(attempt("new-after-migration", 600), &SrsSettings::default()) + .unwrap(); + assert_eq!(store.load().unwrap().revision, 6); + assert_eq!(std::fs::read(&backup_path).unwrap(), original); + assert_eq!( + store.load_with_report().unwrap().1, + MigrationReport::default() + ); +} + +#[test] +fn missing_legacy_interval_is_reconstructed_from_due_and_last_seen() { + let dir = TestDir::new("legacy-interval-reconstruction"); + let path = dir.join("repertoire-training.json"); + let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); + entry.attempts = 1; + entry.last_seen = Some(100); + entry.due = Some(500); + entry.interval_seconds = None; + let mut stats = StatsData::default(); + stats.move_stats.push(entry); + write_json(&path, &stats); + + let (loaded, _) = LearningStore::new(path).load_with_report().unwrap(); + let item = loaded + .learning + .item(&LearningItemKey::local("fen-shared", "e2e4")) + .unwrap(); + assert_eq!(item.next_review_at, Some(500)); + assert_eq!(item.previous_interval_seconds, Some(400)); +} + +#[test] +fn overdue_legacy_interval_is_not_reconstructed_as_a_duration() { + let dir = TestDir::new("legacy-overdue-interval"); + let path = dir.join("repertoire-training.json"); + for (due, last_seen) in [(100, 500), (100, 100)] { + let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); + entry.attempts = 1; + entry.last_seen = Some(last_seen); + entry.due = Some(due); + entry.interval_seconds = None; + let mut stats = StatsData::default(); + stats.move_stats.push(entry); + write_json(&path, &stats); + + let (loaded, _) = LearningStore::new(&path).load_with_report().unwrap(); + let item = loaded + .learning + .item(&LearningItemKey::local("fen-shared", "e2e4")) + .unwrap(); + assert_eq!(item.previous_interval_seconds, None); + } +} + +#[test] +fn unusable_backup_path_blocks_migration_without_replacing_v2() { + let dir = TestDir::new("backup-error"); + let path = dir.join("repertoire-training.json"); + let original = write_json(&path, &StatsData::default()); + let backup = dir.join("repertoire-training.json.before-learning-v3"); + std::fs::create_dir(&backup).unwrap(); + let store = LearningStore::new(&path); + + assert!(matches!(store.migrate(), Err(StoreError::Io { .. }))); + assert_eq!(std::fs::read(&path).unwrap(), original); + assert!(matches!( + store.apply_attempt(attempt("not-persisted", 100), &SrsSettings::default()), + Err(StoreError::Io { .. }) + )); + assert_eq!(std::fs::read(&path).unwrap(), original); +} + +#[test] +fn collision_merge_uses_latest_streak_earliest_due_and_is_deterministic() { + let dir = TestDir::new("collision"); + let mut older = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); + older.attempts = 7; + older.correct = 6; + older.wrong = 1; + older.streak = 2; + older.last_seen = Some(100); + older.due = Some(500); + older.interval_seconds = Some(50); + let mut latest = legacy_move("repertoire-b", TrainingMode::Black, "e2e4"); + latest.attempts = 3; + latest.correct = 1; + latest.wrong = 2; + latest.streak = -3; + latest.last_seen = Some(200); + latest.due = Some(300); + latest.interval_seconds = Some(40); + + let mut stats = StatsData::default(); + stats.move_stats = vec![older.clone(), latest.clone()]; + let mut reversed = StatsData::default(); + reversed.move_stats = vec![latest, older]; + let first_path = dir.join("first.json"); + let second_path = dir.join("second.json"); + write_json(&first_path, &stats); + write_json(&second_path, &reversed); + + let (data, report) = LearningStore::new(first_path).load_with_report().unwrap(); + let (reversed_data, reversed_report) = + LearningStore::new(second_path).load_with_report().unwrap(); + assert_eq!(data.learning, reversed_data.learning); + assert_eq!(report, reversed_report); + assert_eq!(report.merged, 1); + assert_eq!(report.conflicts, 1); + assert_eq!(report.skipped_both, 0); + assert_eq!( + serde_json::to_value(&data.legacy_practice).unwrap(), + serde_json::to_value(&stats).unwrap() + ); + + assert_eq!(data.learning.items.len(), 1); + let item = &data.learning.items[0]; + assert_eq!(item.key, LearningItemKey::local("fen-shared", "e2e4")); + assert_eq!(item.correct_streak, 0); + assert_eq!(item.wrong_streak, 3); + assert_eq!(item.last_review_at, Some(200)); + assert_eq!(item.next_review_at, Some(300)); + assert_eq!(item.previous_interval_seconds, Some(40)); + assert!(item.introduced); + assert_eq!(item.correct_count, 0); + assert_eq!(item.wrong_count, 0); + assert_eq!(item.last_correct_at, None); + assert_eq!(item.accuracy_percent(), None); +} + +#[test] +fn both_without_uci_is_skipped_and_old_attempts_do_not_create_accuracy() { + let dir = TestDir::new("conservative-migration"); + let mut skipped = legacy_move("repertoire-a", TrainingMode::Both, ""); + skipped.attempts = 20; + skipped.correct = 15; + skipped.wrong = 5; + skipped.streak = 4; + skipped.due = Some(100); + let mut scheduled_only = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); + scheduled_only.due = Some(200); + scheduled_only.interval_seconds = Some(100); + let mut attempted = legacy_move("repertoire-b", TrainingMode::Black, "d2d4"); + attempted.attempts = 8; + attempted.correct = 7; + attempted.wrong = 1; + attempted.streak = 2; + let mut stats = StatsData::default(); + stats.move_stats = vec![skipped, scheduled_only, attempted]; + let path = dir.join("stats.json"); + write_json(&path, &stats); + + let (data, report) = LearningStore::new(path).load_with_report().unwrap(); + assert_eq!(report.skipped_both, 1); + assert_eq!(report.merged, 0); + assert_eq!(report.conflicts, 0); + assert_eq!(data.learning.items.len(), 2); + assert_eq!( + data.legacy_practice.unwrap()["move_stats"] + .as_array() + .unwrap() + .len(), + 3 + ); + let scheduled = data + .learning + .item(&LearningItemKey::local("fen-shared", "e2e4")) + .unwrap(); + assert!(scheduled.introduced); + assert_eq!(scheduled.next_review_at, Some(200)); + assert_eq!(scheduled.previous_interval_seconds, Some(100)); + let attempted = data + .learning + .item(&LearningItemKey::local("fen-shared", "d2d4")) + .unwrap(); + assert!(attempted.introduced); + assert_eq!(attempted.correct_streak, 2); + assert_eq!(attempted.independent_attempt_count(), 0); + assert_eq!(attempted.accuracy_percent(), None); + assert_eq!(attempted.last_correct_at, None); +} + +#[test] +fn legacy_lines_are_retained_and_training_json_is_never_changed() { + let dir = TestDir::new("legacy-lines"); + let legacy_path = dir.join("training.json"); + let legacy_bytes = serde_json::to_vec_pretty(&serde_json::json!({ + "line-a": {"runs": 4, "unknown": [1, 2, 3]}, + "line-b": {"runs": 2, "best": 1} + })) + .unwrap(); + std::fs::write(&legacy_path, &legacy_bytes).unwrap(); + let path = dir.join("repertoire-training.json"); + let store = LearningStore::with_legacy(&path, &legacy_path); + + let loaded = store.load().unwrap(); + let legacy = loaded.legacy_practice.as_ref().unwrap(); + assert_eq!(legacy["legacy_lines"].as_object().unwrap().len(), 2); + assert_eq!( + legacy["legacy_lines"]["line-a"]["unknown"], + serde_json::json!([1, 2, 3]) + ); + store.migrate().unwrap(); + assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); + store + .apply_attempt(attempt("new-event", 1_000), &SrsSettings::default()) + .unwrap(); + assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); + let persisted = store.load().unwrap(); + assert_eq!( + persisted.legacy_practice.unwrap()["legacy_lines"], + legacy["legacy_lines"] + ); + + let old_reader = StatsStore::with_legacy(dir.join("old-reader.json"), &legacy_path); + assert_eq!(old_reader.load().unwrap().legacy_lines.len(), 2); + assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); +} + +#[test] +fn v3_session_snapshot_survives_attempt_persistence() { + let dir = TestDir::new("sessions"); + let path = dir.join("repertoire-training.json"); + let mut data = LearningStoreData { + revision: 7, + ..LearningStoreData::default() + }; + let session = LearningSession { + id: "session-1".into(), + mode: QueueMode::SpacedRepetition, + side: TrainingMode::White, + scope: TrainingScopeKey::default(), + settings: SrsSettings { + growth_factor: 2.25, + ..SrsSettings::default() + }, + }; + data.sessions.push(session.clone()); + write_json(&path, &data); + + let store = LearningStore::new(&path); + let loaded = store.load().unwrap(); + assert_eq!(loaded.sessions.len(), 1); + assert_eq!(loaded.sessions.first(), Some(&session)); + let applied = store + .apply_attempt(attempt("session-event", 100), &SrsSettings::default()) + .unwrap(); + assert_eq!(applied.revision, 8); + assert_eq!(store.load().unwrap().sessions, [session]); +} + +#[test] +fn v3_unknown_fields_survive_plain_and_session_attempt_roundtrips() { + let dir = TestDir::new("v3-extensions"); + let path = dir.join("repertoire-training.json"); + let (data, library) = extension_fixture(); + let mut raw = serde_json::to_value(data).unwrap(); + inject_v3_extensions(&mut raw); + let key_shaped = |object: &mut serde_json::Value| { + object["user_id"] = serde_json::json!("local"); + object["position_fen4"] = serde_json::json!("fen-shared"); + object["expected_uci"] = serde_json::json!("e2e4"); + }; + key_shaped(&mut raw); + key_shaped(&mut raw["learning"]); + let original = write_json(&path, &raw); + let store = LearningStore::new(&path); + assert_eq!(store.load().unwrap().revision, 0); + assert_eq!(std::fs::read(&path).unwrap(), original); + + store + .apply_attempt(attempt("plain-event", 100), &SrsSettings::default()) + .unwrap(); + let saved = read_json(&path); + assert_eq!(saved["revision"], serde_json::json!(1)); + assert_eq!(saved["learning"]["attempts"].as_array().unwrap().len(), 2); + assert_v3_extensions(&saved); + assert!( + saved["learning"]["items"][0]["key"] + .get("future_key_extension") + .is_none() + ); + + let loaded = store.load().unwrap(); + assert_eq!(loaded.revision, 1); + assert_eq!( + loaded.extensions["future_top_level_field"], + extension_marker() + ); + assert_eq!( + loaded.learning.extensions["future_learning_field"], + extension_marker() + ); + let mut session = loaded.session_snapshot("session-1").cloned().unwrap(); + let session_attempt = session + .play_uci(&library, "e2e4", "session-event", 200, Some(250)) + .unwrap(); + let persisted = store + .apply_attempt_and_session(session_attempt, &mut session) + .unwrap(); + assert_eq!(persisted.application, AttemptApplication::Applied); + assert_eq!(persisted.revision, 2); + assert_eq!(persisted.session.revision, 1); + + let saved = read_json(&path); + assert_eq!(saved["revision"], serde_json::json!(2)); + assert_eq!(saved["learning"]["attempts"].as_array().unwrap().len(), 3); + assert_eq!( + saved["session_snapshots"][0]["revision"], + serde_json::json!(1) + ); + assert_v3_extensions(&saved); +} + +#[test] +fn v2_unknown_root_and_nested_fields_survive_migration_and_later_writes() { + let dir = TestDir::new("v2-raw-extensions"); + let path = dir.join("repertoire-training.json"); + let mut stats = StatsData::default(); + stats.revision = 2; + stats + .legacy_lines + .insert("old-line".into(), serde_json::json!({"runs": 3})); + let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); + entry.attempts = 1; + entry.correct = 1; + entry.last_seen = Some(100); + entry.due = Some(500); + entry.interval_seconds = Some(400); + stats.move_stats.push(entry); + let mut raw = serde_json::to_value(&stats).unwrap(); + raw["future_v2_root"] = extension_marker(); + raw["move_stats"][0]["future_move_stats_field"] = extension_marker(); + raw["move_stats"][0]["key"]["future_move_key_field"] = extension_marker(); + raw["move_stats"][0]["recent"] = serde_json::json!([{ + "at": 100, + "correct": true, + "hinted": false, + "actual_uci": "e2e4", + "future_recent_field": extension_marker() + }]); + raw["legacy_lines"]["old-line"]["future_line_field"] = extension_marker(); + let original = write_json(&path, &raw); + let store = LearningStore::new(&path); + let extension_pointers = [ + "/legacy_practice/future_v2_root", + "/legacy_practice/move_stats/0/future_move_stats_field", + "/legacy_practice/move_stats/0/key/future_move_key_field", + "/legacy_practice/move_stats/0/recent/0/future_recent_field", + "/legacy_practice/legacy_lines/old-line/future_line_field", + ]; + + let (loaded, _) = store.load_with_report().unwrap(); + assert_eq!(loaded.learning.items.len(), 1); + assert_eq!( + loaded.legacy_practice.as_ref().unwrap()["future_v2_root"], + extension_marker() + ); + store.migrate().unwrap(); + let backup = dir.join("repertoire-training.json.before-learning-v3"); + assert_eq!(std::fs::read(backup).unwrap(), original); + let saved = read_json(&path); + assert_eq!(saved["revision"], serde_json::json!(3)); + for pointer in extension_pointers { + assert_eq!( + saved.pointer(pointer), + Some(&extension_marker()), + "{pointer}" + ); + } + + store + .apply_attempt(attempt("after-raw-migration", 600), &SrsSettings::default()) + .unwrap(); + let saved = read_json(&path); + assert_eq!(saved["revision"], serde_json::json!(4)); + for pointer in extension_pointers { + assert_eq!( + saved.pointer(pointer), + Some(&extension_marker()), + "{pointer}" + ); + } +} + +#[test] +fn unreadable_missing_and_unsupported_versions_are_errors_not_empty_data() { + let dir = TestDir::new("read-errors"); + let path = dir.join("repertoire-training.json"); + let store = LearningStore::new(&path); + + std::fs::write(&path, b"{broken").unwrap(); + assert!(matches!(store.load(), Err(StoreError::Json { .. }))); + assert!(matches!(store.migrate(), Err(StoreError::Json { .. }))); + assert_eq!(std::fs::read(&path).unwrap(), b"{broken"); + + std::fs::write(&path, br#"{"learning":{"items":[],"attempts":[]}}"#).unwrap(); + assert!(matches!( + store.load(), + Err(StoreError::MissingVersion { .. }) + )); + + std::fs::write( + &path, + br#"{"version":4,"learning":{"items":[],"attempts":[]}}"#, + ) + .unwrap(); + assert!(matches!( + store.load(), + Err(StoreError::UnsupportedVersion { version: 4, .. }) + )); + assert!(matches!( + store.apply_attempt(attempt("must-not-write", 1), &SrsSettings::default()), + Err(StoreError::UnsupportedVersion { version: 4, .. }) + )); + + std::fs::write(&path, br#"{"version":3,"learning":[]}"#).unwrap(); + let result = store.load(); + assert!( + matches!(&result, Err(StoreError::Json { .. })), + "unexpected result: {result:?}" + ); +} + +#[test] +fn extension_merge_tracks_reordered_identities_and_keeps_first_duplicate() { + let raw = serde_json::json!([ + {"user_id":"u", "client_attempt_id":"a", "known":0, "plugin":{"first":true}}, + {"user_id":"u", "client_attempt_id":"b", "known":0, "plugin":{"second":true}}, + {"user_id":"u", "client_attempt_id":"a", "known":0, "plugin":{"wrong":true}} + ]); + let current = serde_json::json!([ + {"user_id":"u", "client_attempt_id":"b", "known":2}, + {"user_id":"u", "client_attempt_id":"a", "known":1}, + {"user_id":"u", "client_attempt_id":"c", "known":3} + ]); + let merged = preserve_extensions(&raw, current); + assert_eq!( + merged, + serde_json::json!([ + {"user_id":"u", "client_attempt_id":"b", "known":2, "plugin":{"second":true}}, + {"user_id":"u", "client_attempt_id":"a", "known":1, "plugin":{"first":true}}, + {"user_id":"u", "client_attempt_id":"c", "known":3} + ]) + ); +} + +#[test] +fn context_batch_is_atomic_retryable_and_preserves_every_event() { + let dir = TestDir::new("context-batch"); + let store = LearningStore::new(dir.join("learning.json")); + let mut library = Library::default(); + let id = library + .create( + "Context", + &chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 *").game, + ) + .unwrap(); + let scope = StatsScope::for_repertoire(id, LearningSide::White, 100); + let mut learning = LearningData::default(); + let key = crate::repertoire::active_learning_memberships(&library, &scope) + .unwrap() + .into_iter() + .find(|m| m.key.expected_uci == "f1b5") + .unwrap() + .key; + let item = learning.ensure_item(key); + item.introduced = true; + item.next_review_at = Some(0); + let mut session = LearningSessionSnapshot::new( + "context-batch", + &library, + &learning, + scope, + SrsSettings::default(), + ) + .unwrap(); + store.save_session(&mut session).unwrap(); + let start = store.load().unwrap(); + let original = std::fs::read(store.path()).unwrap(); + let mut events = Vec::new(); + for i in 0..4 { + events.push( + session + .advance_context_with_learning(&library, &learning, format!("context-{i}"), 100) + .unwrap(), + ); + } + assert_eq!(session.context_index, 4); + let retry = session.clone(); + assert!( + store + .apply_attempts_and_session(vec![], &mut session) + .is_err() + ); + let mut invalid = events.clone(); + invalid[3].client_attempt_id.clear(); + assert!( + store + .apply_attempts_and_session(invalid, &mut session) + .is_err() + ); + assert_eq!(std::fs::read(store.path()).unwrap(), original); + assert_eq!(session, retry); + assert!( + store + .apply_attempts_and_session(vec![events[0].clone(), events[0].clone()], &mut session) + .is_err() + ); + assert_eq!(std::fs::read(store.path()).unwrap(), original); + + let saved = store + .apply_attempts_and_session(events.clone(), &mut session) + .unwrap(); + assert_eq!(saved.application, AttemptApplication::Applied); + assert_eq!( + saved.revision, + start.revision + 1, + "one transaction for the whole prefix" + ); + assert_eq!(saved.session.revision, retry.revision + 1); + assert_eq!(saved.learning.attempts, events); + assert!( + saved + .learning + .items + .iter() + .all(|item| item.correct_streak == 0) + ); + let bytes = std::fs::read(store.path()).unwrap(); + let mut stale = retry.clone(); + let duplicate = store + .apply_attempts_and_session(events.clone(), &mut stale) + .unwrap(); + assert_eq!(duplicate.application, AttemptApplication::Duplicate); + assert_eq!(duplicate.session, saved.session); + assert_eq!(std::fs::read(store.path()).unwrap(), bytes); + + let mut partial = events.clone(); + partial[3].client_attempt_id = "new-id".into(); + assert!( + store + .apply_attempts_and_session(partial, &mut session) + .is_err() + ); + assert_eq!(std::fs::read(store.path()).unwrap(), bytes); + let mut concurrent = events.clone(); + for event in &mut concurrent { + event.client_attempt_id.push_str("-concurrent"); + } + assert!(matches!( + store.apply_attempts_and_session(concurrent, &mut stale), + Err(StoreError::SessionConflict { .. }) + )); + assert_eq!(std::fs::read(store.path()).unwrap(), bytes); + let loaded = store.load().unwrap(); + loaded + .session_snapshot("context-batch") + .unwrap() + .validate(&library) + .unwrap(); + assert_eq!(loaded.learning.attempts, events); +} diff --git a/crates/trainer/src/repertoire/tests.rs b/crates/trainer/src/repertoire/tests.rs new file mode 100644 index 0000000..2e2516e --- /dev/null +++ b/crates/trainer/src/repertoire/tests.rs @@ -0,0 +1,408 @@ +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use chess_core::shakmaty::{Chess, Move, Position}; +use chess_core::{Game, MoveKind, NodeId, StartPosition}; +use serde_json::json; + +use super::*; + +static TEST_DIR: AtomicU64 = AtomicU64::new(1); + +fn game(pgn: &str) -> Game { + chess_core::parse_str(pgn).game +} + +fn play(game: &Game, line: &[&str]) -> Vec { + let mut position = game.start().position().clone(); + line.iter() + .map(|text| { + let mv = text + .parse::() + .unwrap() + .to_move(&position) + .unwrap(); + position.play_unchecked(mv); + mv + }) + .collect() +} + +fn temp_dir(name: &str) -> PathBuf { + let sequence = TEST_DIR.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "cp-repertoire-{}-{sequence}-{name}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + path +} + +#[test] +fn prefix_branch_dedup_and_annotations_merge_without_touching_source() { + let source = game("1. e4 {old} $1 c5 2. Nf3 d6 3. Bb5+ (3. d4 cxd4 4. Nxd4 (4. Qxd4)) *"); + let original = source.to_pgn(); + let canonical = source.canonical_tree(); + let mut library = Library::default(); + let id = library.create_empty("Sicilian").unwrap(); + + let prefix_end = source.mainline()[3]; + let report = library.add_prefix(&id, &source, prefix_end).unwrap(); + assert_eq!(report.added_nodes, 4); + let snapshot = library.repertoire(&id).unwrap().game(); + assert_eq!(snapshot.mainline().len(), 4); + assert_eq!( + snapshot.game_move(snapshot.mainline()[2]).unwrap().san, + "Nf3" + ); + assert!(!snapshot.to_pgn().contains("Bb5")); + assert!(!snapshot.to_pgn().contains("cxd4")); + + let annotated = game("1. e4 {new} $2 c5 2. Nf3 Nc6 3. d4 *"); + library.add_game(&id, &annotated).unwrap(); + library.add_game(&id, &annotated).unwrap(); + library.add_game(&id, &source).unwrap(); + let merged = library.repertoire(&id).unwrap().game(); + let e4 = merged.main_child(NodeId::ROOT).unwrap(); + assert_eq!(merged.node(e4).unwrap().comments_after(), ["old", "new"]); + assert_eq!( + merged + .node(e4) + .unwrap() + .nags() + .iter() + .map(|n| n.0) + .collect::>(), + [1, 2] + ); + let moves = play(&merged, &["e2e4", "c7c5", "g1f3"]); + let c5 = merged.find_child(e4, moves[1]).unwrap(); + let nf3 = merged.find_child(c5, moves[2]).unwrap(); + assert_eq!(merged.children(nf3).len(), 2); + assert_eq!( + library + .repertoire(&id) + .unwrap() + .game() + .attached_nodes() + .len(), + 12 + ); + + let before = library.repertoire(&id).unwrap().pgn.clone(); + let repeat = library.add_game(&id, &source).unwrap(); + assert_eq!(repeat.added_nodes, 0); + assert_eq!(library.repertoire(&id).unwrap().pgn, before); + assert_eq!(source.to_pgn(), original); + assert_eq!(source.canonical_tree(), canonical); +} + +#[test] +fn different_starts_are_rejected_and_fullmove_zero_is_preserved() { + let fen_game = + game("[SetUp \"1\"]\n[FEN \"4k3/8/8/8/8/8/4P3/4K2R b - - 0 0\"]\n\n1... Ke7 2. e4 *"); + let mut library = Library::default(); + let id = library.create("Black to move", &fen_game).unwrap(); + assert_eq!( + library + .repertoire(&id) + .unwrap() + .game() + .start() + .original_fen(), + Some("4k3/8/8/8/8/8/4P3/4K2R b - - 0 0") + ); + let before = library.repertoire(&id).unwrap().pgn.clone(); + assert!(matches!( + library.add_game(&id, &game("1. e4 *")), + Err(RepertoireError::DifferentStart { .. }) + )); + assert_eq!(library.repertoire(&id).unwrap().pgn, before); +} + +#[test] +fn null_and_unparsed_segments_survive_but_are_not_candidates() { + let source = game("1. e4 -- (1... e5) 2. d4 *"); + let mut library = Library::default(); + let id = library.create("Teaching", &game("1. e4 e5 *")).unwrap(); + library.add_game(&id, &source).unwrap(); + let stored = library.repertoire(&id).unwrap(); + assert!(stored.pgn.contains("--")); + let tree = RepertoireTree::new(stored); + let stored_game = tree.game(); + let e4 = stored_game.main_child(NodeId::ROOT).unwrap(); + let null = stored_game + .children(e4) + .iter() + .copied() + .find(|node| { + stored_game + .game_move(*node) + .is_some_and(|mv| mv.kind == MoveKind::Null) + }) + .unwrap(); + assert!(tree.candidates(null).is_empty()); + assert!(tree.candidates(e4).iter().any(|c| c.uci == "e7e5")); + assert!(tree.candidates(e4).iter().all(|c| c.uci != "0000")); + + let illegal = game("1. e4 e5 2. e5 *"); + assert!(illegal.canonical_tree().contains("U[")); + let mut illegal_library = Library::default(); + let illegal_id = illegal_library.create("Raw", &illegal).unwrap(); + let roundtrip = illegal_library.repertoire(&illegal_id).unwrap().game(); + assert_eq!(roundtrip.canonical_tree(), illegal.canonical_tree()); + assert!( + illegal_library + .add_game(&illegal_id, &game("1. e4 e5 2. Nf3 *")) + .is_ok() + ); + let mut target = Library::default(); + let target_id = target.create("Target", &game("1. e4 e5 *")).unwrap(); + let target_before = target.repertoire(&target_id).unwrap().pgn.clone(); + assert!(target.add_game(&target_id, &illegal).is_err()); + assert_eq!(target.repertoire(&target_id).unwrap().pgn, target_before); + + let mut empty = Library::default(); + let empty_id = empty.create_empty("Empty").unwrap(); + empty.add_game(&empty_id, &illegal).unwrap(); + assert_eq!( + empty.repertoire(&empty_id).unwrap().game().canonical_tree(), + illegal.canonical_tree() + ); + + let mut prefixes = Library::default(); + let prefix_id = prefixes.create("Prefix", &game("1. e4 *")).unwrap(); + let null_node = source.mainline()[1]; + prefixes.add_prefix(&prefix_id, &source, null_node).unwrap(); + let prefix_pgn = &prefixes.repertoire(&prefix_id).unwrap().pgn; + assert!(prefix_pgn.contains("--")); + assert!(!prefix_pgn.contains("d4")); +} + +#[test] +fn transpositions_share_candidates_but_keep_both_pgn_paths() { + let mut library = Library::default(); + let id = library.create_empty("Transpositions").unwrap(); + library + .add_game(&id, &game("1. d4 d5 2. Nf3 Nf6 3. g3 *")) + .unwrap(); + library + .add_game(&id, &game("1. Nf3 d5 2. d4 Nf6 *")) + .unwrap(); + let stored = library.repertoire(&id).unwrap(); + let tree = RepertoireTree::new(stored); + let game = tree.game(); + let first_path = ["d2d4", "d7d5", "g1f3", "g8f6"]; + let second_path = ["g1f3", "d7d5", "d2d4", "g8f6"]; + let first = tree.node_at_path(&first_path.map(str::to_owned)).unwrap(); + let second = tree.node_at_path(&second_path.map(str::to_owned)).unwrap(); + assert_ne!(first, second); + assert_eq!(tree.position_key(first), tree.position_key(second)); + assert!(tree.transpositions(first).contains(&second)); + assert!(tree.candidates(second).iter().any(|c| c.uci == "g2g3")); + let pgn = stored.pgn.clone(); + assert!(pgn.contains("d4")); + assert!(pgn.contains("Nf3")); + assert_eq!(game.attached_nodes().len(), 10); +} + +#[test] +fn fen4_ignores_counters_but_distinguishes_side_castling_and_legal_ep() { + let position = |fen: &str| StartPosition::from_fen(fen).unwrap().position().clone(); + let a = position("4k3/8/8/8/8/8/4P3/4K2R w K - 0 1"); + let counters = position("4k3/8/8/8/8/8/4P3/4K2R w K - 37 91"); + let black = position("4k3/8/8/8/8/8/4P3/4K2R b K - 0 1"); + let no_rights = position("4k3/8/8/8/8/8/4P3/4K2R w - - 0 1"); + assert_eq!(fen4(&a), fen4(&counters)); + assert_ne!(fen4(&a), fen4(&black)); + assert_ne!(fen4(&a), fen4(&no_rights)); + + let legal_ep = position("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 2"); + let no_ep = position("4k3/8/8/3pP3/8/8/8/4K3 w - - 0 2"); + let illegal_ep = position("4k3/8/8/3p4/8/8/8/4K3 w - d6 0 2"); + let illegal_no_ep = position("4k3/8/8/3p4/8/8/8/4K3 w - - 0 2"); + assert_ne!(fen4(&legal_ep), fen4(&no_ep)); + assert_eq!(fen4(&illegal_ep), fen4(&illegal_no_ep)); +} + +#[test] +fn library_crud_depth_and_disable_are_persistent_data() { + let mut library = Library::default(); + let id = library.create(" Name ", &game("1. e4 e5 *")).unwrap(); + assert_eq!(library.repertoire(&id).unwrap().name, "Name"); + assert_eq!(library.repertoire(&id).unwrap().max_plies, 20); + library.rename(&id, "Renamed").unwrap(); + assert!(library.rename(&id, " ").is_err()); + let repertoire = library.repertoire_mut(&id).unwrap(); + repertoire.set_max_plies(1); + repertoire + .set_prefix_disabled(&["e2e4".into()], true) + .unwrap(); + repertoire + .set_prefix_disabled(&["e2e4".into()], true) + .unwrap(); + assert_eq!(repertoire.disabled_prefixes.len(), 1); + assert!( + RepertoireTree::new(repertoire) + .candidates(NodeId::ROOT) + .is_empty() + ); + assert_eq!(library.delete(&id).unwrap().name, "Renamed"); + assert!(library.repertoire(&id).is_none()); +} + +#[test] +fn prefix_ignores_unparsed_tail_after_the_selected_node() { + let source = game("1. e4 e4 2. d4 *"); + assert_eq!(source.mainline().len(), 1); + assert!(!source.mainline().is_empty()); + let mut library = Library::default(); + let id = library.create("Target", &game("1. e4 c5 *")).unwrap(); + let before = library.repertoire(&id).unwrap().pgn.clone(); + + let report = library + .add_prefix(&id, &source, source.mainline()[0]) + .unwrap(); + + assert_eq!(report.added_nodes, 0); + assert_eq!(library.repertoire(&id).unwrap().pgn, before); +} + +#[test] +fn library_store_roundtrip_errors_and_conflicts_are_visible() { + let dir = temp_dir("library-store"); + let path = dir.join("repertoires.json"); + let store = LibraryStore::new(&path); + let mut first = store.load().unwrap(); + let id = first.create("One", &game("1. e4 *")).unwrap(); + store.save(&mut first).unwrap(); + assert_eq!(first.revision, 1); + assert_eq!(store.load().unwrap().repertoire(&id).unwrap().name, "One"); + + let mut stale = Library::default(); + stale.create("Stale", &game("1. d4 *")).unwrap(); + assert!(matches!( + store.save(&mut stale), + Err(StoreError::Conflict { .. }) + )); + let disk = store.load().unwrap(); + assert_eq!(disk.repertoires.len(), 1); + assert_eq!(disk.repertoires[0].name, "One"); + + std::fs::write(&path, b"{broken").unwrap(); + assert!(store.load().is_err()); + std::fs::write( + &path, + serde_json::to_vec(&json!({"version": 99, "repertoires": []})).unwrap(), + ) + .unwrap(); + assert!(matches!( + store.load(), + Err(StoreError::UnsupportedVersion { .. }) + )); + + let blocker = dir.join("not-a-directory"); + std::fs::write(&blocker, b"file").unwrap(); + let blocked = LibraryStore::new(blocker.join("library.json")); + let mut library = Library::default(); + assert!(blocked.save(&mut library).is_err()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn legacy_roundtrip_backup_migration_and_stats_conflict_preserve_data() { + let dir = temp_dir("legacy-store"); + let legacy_path = dir.join("training.json"); + let new_path = dir.join("repertoire-training.json"); + let start = crate::line_key(&Chess::default(), &play(&Game::new(), &["e2e4", "c7c5"])); + let other = crate::line_key(&Chess::default(), &play(&Game::new(), &["e2e4", "e7e5"])); + let legacy_bytes = serde_json::to_vec_pretty(&json!({ + (start.clone()): {"runs": 4, "last": 2, "best": 0, "clean_streak": 0, "recent": [[2, false]], "last_date": "2026-10-01", "unknown": 7}, + (other): {"runs": 2, "last": 0, "best": 0, "clean_streak": 2, "recent": [], "last_date": "2026-10-02"}, + "future-key": {"arbitrary": [1, 2, 3]} + })) + .unwrap(); + std::fs::write(&legacy_path, &legacy_bytes).unwrap(); + let store = StatsStore::with_legacy(&new_path, &legacy_path); + let mut stats = store.load().unwrap(); + assert_eq!(stats.legacy_lines.len(), 3); + assert!(stats.move_stats.is_empty()); + assert_eq!(stats.legacy_lines[&start]["runs"], 4); + assert_eq!(stats.legacy_lines[&start]["unknown"], 7); + + let mut library = Library::default(); + let report = library.migrate_legacy_lines(&stats.legacy_lines); + assert_eq!(report.repertoires, 1); + assert_eq!(report.lines, 2); + assert_eq!(report.skipped, ["future-key"]); + let after_first = library.repertoires[0].pgn.clone(); + let id = library.repertoires[0].id.clone(); + library.migrate_legacy_lines(&stats.legacy_lines); + assert_eq!(library.repertoires.len(), 1); + assert_eq!(library.repertoires[0].id, id); + assert_eq!(library.repertoires[0].pgn, after_first); + + let mut stale = stats.clone(); + store.save(&mut stats).unwrap(); + assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); + let backup = dir.join("training.json.before-repertoire-v2"); + assert_eq!(std::fs::read(backup).unwrap(), legacy_bytes); + assert!(matches!( + store.save(&mut stale), + Err(StoreError::Conflict { .. }) + )); + let reopened = store.load().unwrap(); + assert_eq!(reopened.legacy_lines, stats.legacy_lines); + assert!(reopened.move_stats.is_empty()); + + std::fs::write(&legacy_path, b"{bad").unwrap(); + let missing_new = StatsStore::with_legacy(dir.join("other.json"), &legacy_path); + assert!(missing_new.load().is_err()); + assert_eq!(std::fs::read(&legacy_path).unwrap(), b"{bad"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn stats_store_write_failure_does_not_replace_legacy_or_report_success() { + let dir = temp_dir("write-error"); + let legacy = dir.join("training.json"); + std::fs::write(&legacy, b"{}").unwrap(); + let blocker = dir.join("blocked"); + std::fs::write(&blocker, b"file").unwrap(); + let store = StatsStore::with_legacy(blocker.join("stats.json"), &legacy); + let mut stats = StatsData::default(); + assert!(store.save(&mut stats).is_err()); + assert_eq!(std::fs::read(&legacy).unwrap(), b"{}"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn adding_and_deleting_never_touches_the_source_file() { + let dir = temp_dir("source-file"); + let source_path = dir.join("legacy.pgn"); + let bytes = b"[Event \"Legacy\"]\n\n1. e4 c5 2. Nf3 d6 *\n\xff"; + std::fs::write(&source_path, bytes).unwrap(); + let source = game("1. e4 c5 2. Nf3 d6 3. Bb5+ *"); + let mut library = Library::default(); + let id = library.create_empty("Snapshot").unwrap(); + let at = source.mainline()[3]; + library.add_prefix(&id, &source, at).unwrap(); + library.delete(&id).unwrap(); + assert_eq!(std::fs::read(&source_path).unwrap(), bytes); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn v2_stats_without_the_random_cursor_field_still_read_and_save() { + let mut old = serde_json::to_value(StatsData::default()).unwrap(); + assert!( + old.as_object_mut() + .unwrap() + .remove("random_practice_cursors") + .is_some() + ); + let stats: StatsData = serde_json::from_value(old).unwrap(); + let saved = serde_json::to_value(&stats).unwrap(); + assert!(saved["random_practice_cursors"].is_array()); +} diff --git a/crates/trainer/src/repertoire/tree.rs b/crates/trainer/src/repertoire/tree.rs new file mode 100644 index 0000000..ffeab12 --- /dev/null +++ b/crates/trainer/src/repertoire/tree.rs @@ -0,0 +1,306 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use chess_core::shakmaty::fen::Fen; +use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position}; +use chess_core::{Game, MoveKind, NodeId}; + +use super::model::Repertoire; +use super::scope::TrainingScope; + +/// The position identity used by opening training: board, side, castling rights and +/// legal en passant. Halfmove and fullmove counters deliberately do not participate. +pub fn fen4(position: &Chess) -> String { + Fen::from_position(position, EnPassantMode::Legal) + .to_string() + .split(' ') + .take(4) + .collect::>() + .join(" ") +} + +#[derive(Clone, Debug)] +pub struct Candidate { + pub uci: String, +} + +#[derive(Clone, Debug)] +struct IndexedNode { + fen4: String, + path: Option>, +} + +/// A PGN tree plus derived position/transposition information. Node IDs are used only +/// while this value is alive and are never persisted in statistics or settings. +#[derive(Clone, Debug)] +pub struct RepertoireTree { + game: Game, + max_plies: u32, + disabled_prefixes: Vec>, + indexed: BTreeMap, + positions: BTreeMap>, +} + +impl RepertoireTree { + pub fn new(repertoire: &Repertoire) -> Self { + Self::from_game( + repertoire.game(), + repertoire.max_plies, + repertoire.disabled_prefixes.clone(), + ) + } + + pub fn from_game(game: Game, max_plies: u32, disabled_prefixes: Vec>) -> Self { + let mut indexed = BTreeMap::new(); + let mut positions: BTreeMap> = BTreeMap::new(); + for id in game.attached_nodes() { + let Some(position) = game.position(id) else { + continue; + }; + let key = fen4(position); + let path = normal_path(&game, id); + positions.entry(key.clone()).or_default().push(id); + indexed.insert(id, IndexedNode { fen4: key, path }); + } + Self { + game, + max_plies, + disabled_prefixes, + indexed, + positions, + } + } + + pub fn game(&self) -> &Game { + &self.game + } + + pub fn root(&self) -> NodeId { + self.game.root() + } + + pub fn position(&self, at: NodeId) -> Option<&Chess> { + self.game.position(at) + } + + pub fn position_key(&self, at: NodeId) -> Option<&str> { + self.indexed.get(&at).map(|n| n.fen4.as_str()) + } + + pub fn path(&self, at: NodeId) -> Option<&[String]> { + self.indexed.get(&at)?.path.as_deref() + } + + pub fn transpositions(&self, at: NodeId) -> &[NodeId] { + self.position_key(at) + .and_then(|key| self.positions.get(key)) + .map(Vec::as_slice) + .unwrap_or(&[]) + } + + pub fn is_trainable_path(&self, at: NodeId) -> bool { + let Some(node) = self.game.node(at) else { + return false; + }; + let Some(path) = self.path(at) else { + return false; + }; + node.ply() <= self.max_plies && !self.disabled(path) + } + + /// Enabled children of the current path and all its FEN4 transpositions. A direct + /// child is preferred so ordinary paths stay on their own PGN branch; otherwise the + /// first PGN path is the canonical continuation. Null and unparsed-after-null paths + /// never contribute candidates. + pub fn candidates(&self, at: NodeId) -> Vec { + self.candidates_impl(at, None) + } + + fn candidates_impl(&self, at: NodeId, scope: Option<&TrainingScope>) -> Vec { + if !self.is_trainable_path(at) + || self + .game + .node(at) + .is_none_or(|node| node.ply() >= self.max_plies) + { + return Vec::new(); + } + let mut nodes = Vec::new(); + nodes.push(at); + nodes.extend( + self.transpositions(at) + .iter() + .copied() + .filter(|node| *node != at), + ); + let mut seen = BTreeSet::new(); + let mut out = Vec::new(); + for parent in nodes { + let Some(parent_node) = self.game.node(parent) else { + continue; + }; + if !self.is_trainable_path(parent) + || parent_node.ply() >= self.max_plies + || !self.scope_allows_parent(parent, scope) + { + continue; + } + for child in self.game.children(parent) { + let Some(game_move) = self.game.game_move(*child) else { + continue; + }; + let MoveKind::Normal(mv) = game_move.kind else { + continue; + }; + if !self.is_trainable_path(*child) || !self.scope_allows_child(*child, scope) { + continue; + } + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + if seen.insert(uci.clone()) { + out.push(Candidate { uci }); + } + } + } + out + } + + pub fn candidate(&self, at: NodeId, uci: &str) -> Option { + self.candidates(at) + .into_iter() + .find(|candidate| candidate.uci == uci) + } + + /// Follows a normal UCI path on the actual PGN tree. No transposition jump is made + /// while replaying context, so the selected target path remains exact. + pub fn node_at_path(&self, path: &[String]) -> Option { + let mut current = self.root(); + let mut position = self.game.position(current)?.clone(); + for uci in path { + let mv = uci + .parse::() + .ok()? + .to_move(&position) + .ok()?; + current = self.game.find_child(current, mv)?; + position.play_unchecked(mv); + } + self.is_trainable_path(current).then_some(current) + } + + pub fn scope_anchor(&self, scope: &TrainingScope) -> Result { + if let Some(end) = &scope.end_prefix + && (end.len() < scope.prefix.len() || !end.starts_with(&scope.prefix)) + { + return Err("scope end must extend the selected prefix".into()); + } + let anchor = if scope.prefix.is_empty() { + self.root() + } else { + self.node_at_path(scope.parent_prefix()) + .ok_or_else(|| "scope parent is missing, disabled, or beyond depth".to_owned())? + }; + if let Some(selected) = scope.prefix.last() + && self.candidate(anchor, selected).is_none() + { + return Err("scope move is missing, disabled, or beyond depth".into()); + } + if let Some(end) = &scope.end_prefix + && self.node_at_path(end).is_none() + { + return Err("scope end is missing, disabled, or beyond depth".into()); + } + Ok(anchor) + } + + /// Streams the routes explicitly present in PGN, without importing continuations + /// from other paths that reach the same position. + pub fn visit_source_paths( + &self, + scope: &TrainingScope, + mut visit: impl FnMut(&[String]) -> std::ops::ControlFlow<()>, + ) -> Result<(), String> { + let anchor = self.scope_anchor(scope)?; + let _ = self.visit_source(anchor, scope, &mut Vec::new(), &mut visit); + Ok(()) + } + + fn visit_source( + &self, + at: NodeId, + scope: &TrainingScope, + current: &mut Vec, + visit: &mut impl FnMut(&[String]) -> std::ops::ControlFlow<()>, + ) -> std::ops::ControlFlow<()> { + let mut continued = false; + if scope.parent_prefix().len() + current.len() < self.max_plies as usize { + for child in self.game.children(at) { + let Some(game_move) = self.game.game_move(*child) else { + continue; + }; + let MoveKind::Normal(mv) = game_move.kind else { + continue; + }; + if !self.is_trainable_path(*child) || !self.scope_allows_child(*child, Some(scope)) + { + continue; + } + continued = true; + current.push(mv.to_uci(CastlingMode::Standard).to_string()); + let result = self.visit_source(*child, scope, current, visit); + current.pop(); + result?; + } + } + if current.is_empty() || continued { + std::ops::ControlFlow::Continue(()) + } else { + visit(current) + } + } + + fn scope_allows_parent(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool { + let Some(scope) = scope else { + return true; + }; + let Some(path) = self.path(at) else { + return false; + }; + path == scope.parent_prefix() || self.path_in_scope(path, scope) + } + + fn scope_allows_child(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool { + let Some(scope) = scope else { + return true; + }; + self.path(at) + .is_some_and(|path| self.path_in_scope(path, scope)) + } + + fn path_in_scope(&self, path: &[String], scope: &TrainingScope) -> bool { + if !path.starts_with(&scope.prefix) { + return false; + } + scope + .end_prefix + .as_ref() + .is_none_or(|end| path.len() <= end.len()) + } + + fn disabled(&self, path: &[String]) -> bool { + self.disabled_prefixes + .iter() + .any(|prefix| path.starts_with(prefix)) + } +} + +fn normal_path(game: &Game, at: NodeId) -> Option> { + let mut path = Vec::new(); + for node in game.path(at).into_iter().skip(1) { + match game.game_move(node).map(|m| m.kind) { + Some(MoveKind::Normal(mv)) => { + path.push(mv.to_uci(CastlingMode::Standard).to_string()); + } + Some(MoveKind::Null) | None => return None, + } + } + Some(path) +} diff --git a/crates/uci/Cargo.toml b/crates/uci/Cargo.toml new file mode 100644 index 0000000..edf7801 --- /dev/null +++ b/crates/uci/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "uci" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "UCI chess engine supervisor: a process, or a Web Worker in a browser (no UI dependencies)" + +[dependencies] +thiserror.workspace = true +web-time.workspace = true + +# The engine as a Web Worker in a browser. +[target.'cfg(target_family = "wasm")'.dependencies] +wasm-bindgen = "0.2.129" +js-sys = "0.3" +web-sys = { version = "0.3", features = ["Worker", "MessageEvent", "ErrorEvent"] } + +[target.'cfg(unix)'.dependencies] +# nice(2) for EngineConfig::nice, prctl(2) for kill_with_parent (std has neither). +libc = "0.2" + +# Test helper: deterministic fake UCI engine used by tests/ via CARGO_BIN_EXE_fake_uci. +[[bin]] +name = "fake_uci" +path = "src/bin/fake_uci.rs" +test = false +doc = false + +# tests/worker.rs: the worker transport in a browser (docs/dev/web.md). +[target.'cfg(target_family = "wasm")'.dev-dependencies] +wasm-bindgen-test = "0.3" +wasm-bindgen-futures = "0.4" +web-sys = { version = "0.3", features = ["Window", "Blob", "BlobPropertyBag", "Url"] } diff --git a/crates/uci/src/bin/fake_uci.rs b/crates/uci/src/bin/fake_uci.rs new file mode 100644 index 0000000..9eed3e5 --- /dev/null +++ b/crates/uci/src/bin/fake_uci.rs @@ -0,0 +1,378 @@ +//! Deterministic fake UCI engine used by the `uci` crate tests. +//! Not a real engine: it echoes a marker of the analysed position as the +//! first PV move, so tests can check that output is attributed to the right +//! search. +//! +//! Marker: first FEN field for `position fen`, otherwise the last move, or +//! `startpos`. +//! +//! Flags (all optional): +//! --name NAME id name (default "Fake UCI") +//! --banner print a banner line before anything +//! --exit-on-start print to stderr and exit(3) immediately +//! --stderr-flood-kb N write N KiB to stderr at start +//! --not-uci answer `uci` with non-UCI chatter only +//! --uciok-delay MS sleep before answering `uci` +//! --no-uciok never send uciok +//! --no-readyok never send readyok +//! --garbage emit malformed lines during handshake and search +//! --info-interval MS period of info output while searching (default 5) +//! --stale-after-stop N after `stop`, N more info lines of the old search +//! --info-after-bestmove N N info lines of the old search after bestmove +//! --bestmove-delay MS delay between `stop` and `bestmove` +//! --never-bestmove ignore `stop` and go silent (hung engine) +//! --exit-after-go N on the N-th `go`, print one info and exit(1) +//! --mate multipv 1 = mate 3, multipv 2 = mate -2 +//! --ignore-quit ignore `quit` (must be killed) +//! --hash-memory scores depend on the position and on the searches made +//! since the last `ucinewgame` (as a hash kept between them) +//! --searchmoves honour `go ... searchmoves M...`: M's first move is the +//! best move, scored 30 cp lower (a worse move) +//! --shallow N MOVE `go nodes n` with n < N (no `searchmoves`): MOVE is the +//! best move (a shallow search choosing another move) +//! --ignore-nodes `go nodes N` searches until `stop` (as Rodent does) +//! --answer MARKER TAIL `go` in the position of MARKER answers at once with +//! `info depth 10 multipv 1 score TAIL` and the bestmove of +//! the first move after `pv` in TAIL (repeatable) +//! +//! Protocol violations by the GUI (`position`/`go`/`setoption`/`ucinewgame` +//! during a search) are reported as `info string ERROR ...`. + +use std::io::{BufRead, Write}; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::time::Duration; + +#[derive(Default)] +struct Cfg { + name: Option, + banner: bool, + exit_on_start: bool, + stderr_flood_kb: usize, + not_uci: bool, + uciok_delay: u64, + no_uciok: bool, + no_readyok: bool, + garbage: bool, + info_interval: u64, + stale_after_stop: u32, + info_after_bestmove: u32, + bestmove_delay: u64, + never_bestmove: bool, + exit_after_go: Option, + mate: bool, + ignore_quit: bool, + hash_memory: bool, + searchmoves: bool, + shallow: Option<(u64, String)>, + answers: Vec<(String, String)>, + ignore_nodes: bool, +} + +fn parse_args() -> Cfg { + let mut c = Cfg { + info_interval: 5, + ..Cfg::default() + }; + let mut args = std::env::args().skip(1); + let num = |v: Option| -> u64 { v.and_then(|s| s.parse().ok()).unwrap_or(0) }; + while let Some(a) = args.next() { + match a.as_str() { + "--name" => c.name = args.next(), + "--banner" => c.banner = true, + "--exit-on-start" => c.exit_on_start = true, + "--stderr-flood-kb" => c.stderr_flood_kb = num(args.next()) as usize, + "--not-uci" => c.not_uci = true, + "--uciok-delay" => c.uciok_delay = num(args.next()), + "--no-uciok" => c.no_uciok = true, + "--no-readyok" => c.no_readyok = true, + "--garbage" => c.garbage = true, + "--info-interval" => c.info_interval = num(args.next()), + "--stale-after-stop" => c.stale_after_stop = num(args.next()) as u32, + "--info-after-bestmove" => c.info_after_bestmove = num(args.next()) as u32, + "--bestmove-delay" => c.bestmove_delay = num(args.next()), + "--never-bestmove" => c.never_bestmove = true, + "--exit-after-go" => c.exit_after_go = Some(num(args.next()) as u32), + "--mate" => c.mate = true, + "--ignore-quit" => c.ignore_quit = true, + "--hash-memory" => c.hash_memory = true, + "--searchmoves" => c.searchmoves = true, + "--shallow" => { + let n = num(args.next()); + c.shallow = args.next().map(|m| (n, m)); + } + "--ignore-nodes" => c.ignore_nodes = true, + "--answer" => { + if let (Some(m), Some(t)) = (args.next(), args.next()) { + c.answers.push((m, t)); + } + } + other => { + eprintln!("fake_uci: unknown flag {other}"); + std::process::exit(2); + } + } + } + c +} + +struct Search { + marker: String, + depth: u32, + max_depth: Option, + /// Added to every score (`--hash-memory`). + bias: i32, +} + +fn out(line: &str) { + let mut o = std::io::stdout().lock(); + let _ = writeln!(o, "{line}"); + let _ = o.flush(); +} + +fn info_lines(cfg: &Cfg, marker: &str, depth: u32, multipv: u32, bias: i32) { + for k in 1..=multipv { + let score = if cfg.mate && k == 1 { + "mate 3".to_string() + } else if cfg.mate && k == 2 { + "mate -2".to_string() + } else { + format!("cp {}", 50 - 10 * k as i32 + bias) + }; + out(&format!( + "info depth {depth} seldepth {} multipv {k} score {score} nodes {} nps 100000 \ + hashfull 3 time {depth} pv {marker} e7e5 g1f3", + depth + 2, + depth as u64 * 1000 + )); + } + if cfg.garbage { + out("info depth notanumber pv x"); + out("#### garbage ####"); + out("info score banana 7"); + } +} + +fn main() { + let cfg = parse_args(); + if cfg.exit_on_start { + eprintln!("fake_uci: exiting on start"); + std::process::exit(3); + } + if cfg.stderr_flood_kb > 0 { + let line = "x".repeat(1023); + let mut e = std::io::stderr().lock(); + for i in 0..cfg.stderr_flood_kb { + let _ = writeln!(e, "{i} {line}"); + } + } + if cfg.banner { + out("Fake UCI engine by nobody"); + } + + let (tx, rx) = mpsc::channel::(); + std::thread::spawn(move || { + let stdin = std::io::stdin(); + for line in stdin.lock().lines() { + match line { + Ok(l) => { + if tx.send(l).is_err() { + break; + } + } + Err(_) => break, + } + } + }); + + let mut multipv = 1u32; + let mut marker = "startpos".to_string(); + let mut search: Option = None; + let mut gos = 0u32; + // Searches since the last `ucinewgame` (`--hash-memory`). + let mut since_new_game = 0i32; + let mut hung = false; + let interval = Duration::from_millis(cfg.info_interval.max(1)); + + loop { + let line = if search.is_some() { + match rx.recv_timeout(interval) { + Ok(l) => Some(l), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => return, + } + } else { + match rx.recv() { + Ok(l) => Some(l), + Err(_) => return, + } + }; + let Some(line) = line else { + // Search tick. + if let Some(s) = search.as_mut() { + s.depth += 1; + info_lines(&cfg, &s.marker, s.depth, multipv, s.bias); + if s.max_depth.is_some_and(|m| s.depth >= m) { + out(&format!("bestmove {} ponder e7e5", bm(&s.marker))); + search = None; + } + } + continue; + }; + if hung { + continue; + } + let toks: Vec<&str> = line.split_whitespace().collect(); + match toks.first().copied() { + Some("uci") => { + if cfg.not_uci { + out("Hello! I am definitely not a chess engine."); + continue; + } + std::thread::sleep(Duration::from_millis(cfg.uciok_delay)); + out(&format!( + "id name {}", + cfg.name.as_deref().unwrap_or("Fake UCI") + )); + out("id author Test Suite"); + out("option name Threads type spin default 1 min 1 max 64"); + out("option name Hash type spin default 16 min 1 max 1024"); + out("option name MultiPV type spin default 1 min 1 max 10"); + out("option name Ponder type check default false"); + out( + "option name Play Style type combo default Normal var Solid var Normal var Very Risky", + ); + out("option name Clear Hash type button"); + out("option name Debug Log File type string default "); + if cfg.garbage { + out("option name Broken type spin default lots"); + out("~~~ random noise ~~~"); + } + if !cfg.no_uciok { + out("uciok"); + } + } + Some("isready") => { + if !cfg.no_readyok { + out("readyok"); + } + } + Some("setoption") => { + if search.is_some() { + out("info string ERROR setoption during search"); + } + // setoption name value + let vpos = toks.iter().position(|&t| t == "value"); + let name = toks[2..vpos.unwrap_or(toks.len())].join(" "); + if name.eq_ignore_ascii_case("MultiPV") + && let Some(v) = vpos.and_then(|p| toks.get(p + 1)) + { + multipv = v.parse().unwrap_or(1); + } + } + Some("ucinewgame") => { + if search.is_some() { + out("info string ERROR ucinewgame during search"); + } + since_new_game = 0; + } + Some("position") => { + if search.is_some() { + out("info string ERROR position during search"); + } + marker = match toks.get(1) { + Some(&"fen") => toks.get(2).unwrap_or(&"?").to_string(), + _ => match toks.iter().position(|&t| t == "moves") { + Some(p) if p + 1 < toks.len() => toks[toks.len() - 1].to_string(), + _ => "startpos".to_string(), + }, + }; + } + Some("go") => { + if search.is_some() { + out("info string ERROR go during search"); + } + gos += 1; + if let Some((_, tail)) = cfg.answers.iter().find(|(m, _)| *m == marker) { + out(&format!("info depth 10 multipv 1 score {tail}")); + let best = tail + .split_whitespace() + .skip_while(|&t| t != "pv") + .nth(1) + .unwrap_or("0000"); + out(&format!("bestmove {best}")); + continue; + } + if cfg.exit_after_go == Some(gos) { + info_lines(&cfg, &marker, 1, multipv, 0); + std::process::exit(1); + } + let max_depth = toks + .iter() + .position(|&t| t == "depth") + .and_then(|p| toks.get(p + 1)) + .and_then(|v| v.parse().ok()) + // `go nodes N`: a short search that ends by itself, like a real one. + .or_else(|| (toks.contains(&"nodes") && !cfg.ignore_nodes).then_some(3)); + since_new_game += 1; + let mut bias = if cfg.hash_memory { + let of_position = marker.bytes().map(i32::from).sum::() % 97; + of_position + 1000 * since_new_game + } else { + 0 + }; + let among = toks + .iter() + .position(|&t| t == "searchmoves") + .and_then(|p| toks.get(p + 1)); + let nodes: Option = toks + .iter() + .position(|&t| t == "nodes") + .and_then(|p| toks.get(p + 1)) + .and_then(|v| v.parse().ok()); + let mut shown = marker.clone(); + match (among, &cfg.shallow) { + (Some(m), _) if cfg.searchmoves => { + shown = (*m).to_owned(); + bias -= 30; + } + (None, Some((below, best))) if nodes.is_some_and(|n| n < *below) => { + shown = best.clone(); + } + _ => {} + } + search = Some(Search { + marker: shown, + depth: 0, + max_depth, + bias, + }); + } + Some("stop") => { + let Some(s) = search.take() else { continue }; + if cfg.never_bestmove { + hung = true; + continue; + } + for i in 0..cfg.stale_after_stop { + info_lines(&cfg, &s.marker, s.depth + 1 + i, multipv, s.bias); + } + std::thread::sleep(Duration::from_millis(cfg.bestmove_delay)); + out(&format!("bestmove {} ponder e7e5", bm(&s.marker))); + for i in 0..cfg.info_after_bestmove { + info_lines(&cfg, &s.marker, s.depth + 100 + i, multipv, s.bias); + } + } + Some("quit") if !cfg.ignore_quit => return, + _ => {} + } + } +} + +/// Best move token: the marker itself when it looks like a move, else e2e4. +fn bm(marker: &str) -> &str { + if marker.len() == 4 && marker.is_ascii() { + marker + } else { + "e2e4" + } +} diff --git a/crates/uci/src/error.rs b/crates/uci/src/error.rs new file mode 100644 index 0000000..a191406 --- /dev/null +++ b/crates/uci/src/error.rs @@ -0,0 +1,37 @@ +use std::path::PathBuf; +use std::process::ExitStatus; + +/// Errors returned by [`crate::Engine::spawn`] and the handle methods. +#[derive(Debug, thiserror::Error)] +pub enum EngineError { + #[error("engine executable not found: {0}")] + NotFound(PathBuf), + #[error("not an executable file: {path}: {reason}")] + NotExecutable { path: PathBuf, reason: String }, + #[error("failed to start engine: {0}")] + Spawn(#[source] std::io::Error), + /// The program answered but did not speak UCI before the `uciok` timeout. + #[error("program does not look like a UCI engine")] + NotUci { + /// First lines of stdout, for diagnostics. + output: Vec, + }, + #[error("engine did not answer `{waiting_for}` in time")] + HandshakeTimeout { waiting_for: &'static str }, + #[error("engine process exited during handshake ({status:?})")] + ProcessExited { + status: Option, + stderr: Vec, + }, + #[error("I/O error talking to engine: {0}")] + Io(#[source] std::io::Error), + #[error("invalid input: {0}")] + InvalidInput(String), + #[error("engine does not declare option {0:?}")] + UnknownOption(String), + #[error("invalid value for option {name:?}: {reason}")] + InvalidOptionValue { name: String, reason: String }, + /// The engine process is no longer running (quit, crashed, killed as hung). + #[error("engine is not running")] + NotRunning, +} diff --git a/crates/uci/src/events.rs b/crates/uci/src/events.rs new file mode 100644 index 0000000..16a1460 --- /dev/null +++ b/crates/uci/src/events.rs @@ -0,0 +1,52 @@ +//! What a running engine tells the UI, whatever carries it. + +use crate::types::{SearchId, SearchInfo}; + +/// Callback invoked after every new event (from the transport's thread on a +/// computer); the UI passes `ctx.request_repaint()` here. +pub type Waker = Box; + +/// Event delivered to the UI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EngineEvent { + /// `position` + `go` for this id were sent to the engine. + SearchStarted { search_id: SearchId }, + /// The request was replaced by a newer one (or cancelled by `stop`) + /// before it was sent to the engine; no events will follow for this id. + Superseded { search_id: SearchId }, + /// Search output. Only lines with a score or a PV are forwarded. + Info { + search_id: SearchId, + info: SearchInfo, + }, + /// Final `bestmove` of a started search. Exactly one per `SearchStarted` + /// unless the engine terminates first. + BestMove { + search_id: SearchId, + best: Option, + ponder: Option, + }, + /// `info string`, attributed to the running search if any. + InfoString { + search_id: Option, + text: String, + }, + /// Malformed or unexpected engine output; the line was skipped. + Warning(String), + /// The supervisor has stopped; the handle is no longer usable. + Terminated(TerminationReason), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TerminationReason { + /// `quit()` or drop of the handle. + Quit { + status: Option, + }, + /// The engine exited on its own (crash, end of its output, write failure). + Exited { + status: Option, + }, + /// The engine did not answer `stop` or `isready` in time and was killed. + Hung { waiting_for: &'static str }, +} diff --git a/crates/uci/src/lib.rs b/crates/uci/src/lib.rs new file mode 100644 index 0000000..db125eb --- /dev/null +++ b/crates/uci/src/lib.rs @@ -0,0 +1,39 @@ +//! UCI engine supervisor. +//! +//! The protocol is a state machine without I/O ([`protocol`]); a transport drives +//! it. On a computer the engine is a child process started without a shell: +//! stdout and stderr are read by two dedicated threads, a supervisor thread +//! feeds the machine. The UI talks to it through the non-blocking +//! [`EngineHandle`] and polls [`EngineEvent`]s every frame; the [`Waker`] +//! callback is invoked after each new event. WebAssembly in a browser has no +//! processes: there the engine is a Web Worker, its handle the same, its start +//! not blocking ([`Engine::start_worker`]). +//! +//! Search boundary: UCI has no request ids. A new `position`/`go` is written +//! only after the previous search ended with `bestmove` and a subsequent +//! `isready`/`readyok` round trip, so output of an old search can never be +//! attributed to a newer [`SearchId`]. Rapid requests are coalesced: only the +//! latest pending request is started, the others are reported as +//! [`EngineEvent::Superseded`]. No dependency on egui or chess-core: +//! positions are strings (FEN / UCI moves). + +mod error; +mod events; +pub mod parse; +#[cfg(not(target_family = "wasm"))] +mod process; +mod protocol; +mod types; +#[cfg(target_family = "wasm")] +mod worker; + +pub use error::EngineError; +pub use events::{EngineEvent, TerminationReason, Waker}; +#[cfg(not(target_family = "wasm"))] +pub use process::{Engine, EngineConfig, EngineHandle}; +pub use types::{ + EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score, + ScoreBound, SearchId, SearchInfo, SearchLimits, Side, Timeouts, WhiteEval, WhiteScore, +}; +#[cfg(target_family = "wasm")] +pub use worker::{Engine, EngineHandle, Starting, WorkerConfig}; diff --git a/crates/uci/src/parse.rs b/crates/uci/src/parse.rs new file mode 100644 index 0000000..cd9441a --- /dev/null +++ b/crates/uci/src/parse.rs @@ -0,0 +1,485 @@ +//! Hand-written parser for the engine → GUI subset of UCI that the supervisor +//! needs. Malformed lines produce `Err`, never a panic. + +use crate::types::{EngineOption, EngineScore, OptionKind, Score, ScoreBound, SearchInfo}; + +/// One parsed line of engine output. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EngineLine { + IdName(String), + IdAuthor(String), + Option(EngineOption), + UciOk, + ReadyOk, + BestMove { + /// `None` for `bestmove (none)` / `bestmove 0000` (no legal moves). + best: Option, + ponder: Option, + }, + Info(SearchInfo), + /// `info string ...` without other search data. + InfoString(String), + /// Empty line. + Empty, + /// Anything else (banners, `copyprotection`, `registration`, vendor + /// extensions). The supervisor ignores these during the handshake. + Unknown(String), +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{reason}: {line:?}")] +pub struct ParseError { + pub line: String, + pub reason: String, +} + +/// Tokens with their byte offsets so that "rest of line" values keep their +/// original spacing. +fn tokens(line: &str) -> Vec<(usize, &str)> { + let base = line.as_ptr() as usize; + line.split_ascii_whitespace() + .map(|t| (t.as_ptr() as usize - base, t)) + .collect() +} + +pub fn parse_line(line: &str) -> Result { + let toks = tokens(line); + let err = |reason: &str| ParseError { + line: line.to_string(), + reason: reason.to_string(), + }; + let Some(&(_, first)) = toks.first() else { + return Ok(EngineLine::Empty); + }; + match first { + "uciok" => Ok(EngineLine::UciOk), + "readyok" => Ok(EngineLine::ReadyOk), + "id" => match toks.get(1) { + Some(&(_, "name")) | Some(&(_, "author")) => { + let value = toks + .get(2) + .map(|&(off, _)| line[off..].trim_end().to_string()) + .unwrap_or_default(); + if toks[1].1 == "name" { + Ok(EngineLine::IdName(value)) + } else { + Ok(EngineLine::IdAuthor(value)) + } + } + _ => Ok(EngineLine::Unknown(line.to_string())), + }, + "bestmove" => { + let best = toks.get(1).ok_or_else(|| err("bestmove without a move"))?.1; + let best = match best { + "(none)" | "0000" | "none" => None, + m => Some(m.to_string()), + }; + let ponder = match (toks.get(2), toks.get(3)) { + (Some(&(_, "ponder")), Some(&(_, p))) if p != "(none)" && p != "0000" => { + Some(p.to_string()) + } + _ => None, + }; + Ok(EngineLine::BestMove { best, ponder }) + } + "option" => parse_option(line, &toks) + .map(EngineLine::Option) + .map_err(|r| err(&r)), + "info" => parse_info(line, &toks).map_err(|r| err(&r)), + _ => Ok(EngineLine::Unknown(line.to_string())), + } +} + +const INFO_KEYS: &[&str] = &[ + "depth", + "seldepth", + "time", + "nodes", + "pv", + "multipv", + "score", + "currmove", + "currmovenumber", + "hashfull", + "nps", + "tbhits", + "sbhits", + "cpuload", + "string", + "refutation", + "currline", + "wdl", +]; + +fn parse_info(line: &str, toks: &[(usize, &str)]) -> Result { + fn num(toks: &[(usize, &str)], i: usize, key: &str) -> Result { + let t = toks + .get(i) + .ok_or_else(|| format!("missing value for `{key}`"))? + .1; + t.parse::() + .map_err(|_| format!("bad value {t:?} for `{key}`")) + } + let mut info = SearchInfo::default(); + let mut string: Option = None; + let mut has_data = false; + let mut i = 1; + while i < toks.len() { + let key = toks[i].1; + i += 1; + match key { + "depth" => { + info.depth = Some(num(toks, i, key)?); + i += 1; + } + "seldepth" => { + info.seldepth = Some(num(toks, i, key)?); + i += 1; + } + "multipv" => { + let v: u32 = num(toks, i, key)?; + if v == 0 { + return Err("multipv must be >= 1".into()); + } + info.multipv = Some(v); + i += 1; + } + "nodes" => { + info.nodes = Some(num(toks, i, key)?); + i += 1; + } + "nps" => { + info.nps = Some(num(toks, i, key)?); + i += 1; + } + "time" => { + info.time_ms = Some(num(toks, i, key)?); + i += 1; + } + "hashfull" => { + info.hashfull = Some(num(toks, i, key)?); + i += 1; + } + "tbhits" => { + info.tbhits = Some(num(toks, i, key)?); + i += 1; + } + "wdl" => { + let w = num(toks, i, key)?; + let d = num(toks, i + 1, key)?; + let l = num(toks, i + 2, key)?; + info.wdl = Some((w, d, l)); + i += 3; + } + "score" => { + let kind = toks.get(i).ok_or("score without type")?.1; + let value: i32 = num(toks, i + 1, kind)?; + let score = match kind { + "cp" => Score::Cp(value), + "mate" => Score::Mate(value), + other => return Err(format!("unknown score type {other:?}")), + }; + i += 2; + let mut bound = ScoreBound::Exact; + while let Some(&(_, t)) = toks.get(i) { + match t { + "lowerbound" => bound = ScoreBound::Lower, + "upperbound" => bound = ScoreBound::Upper, + _ => break, + } + i += 1; + } + info.score = Some(EngineScore { score, bound }); + } + "pv" => { + while let Some(&(_, t)) = toks.get(i) { + if INFO_KEYS.contains(&t) { + break; + } + info.pv.push(t.to_string()); + i += 1; + } + } + "string" => { + string = Some( + toks.get(i) + .map(|&(off, _)| line[off..].trim_end().to_string()) + .unwrap_or_default(), + ); + break; + } + // Fields we do not expose: skip their arguments. + "currmove" | "currmovenumber" | "sbhits" | "cpuload" => { + i += 1; + continue; + } + "refutation" | "currline" => { + while let Some(&(_, t)) = toks.get(i) { + if INFO_KEYS.contains(&t) { + break; + } + i += 1; + } + continue; + } + // Unknown vendor keys are ignored for forward compatibility. + _ => continue, + } + has_data = true; + } + match (has_data, string) { + (false, Some(s)) => Ok(EngineLine::InfoString(s)), + _ => Ok(EngineLine::Info(info)), + } +} + +const OPTION_KEYS: &[&str] = &["default", "min", "max", "var"]; + +fn parse_option(line: &str, toks: &[(usize, &str)]) -> Result { + if toks.get(1).map(|t| t.1) != Some("name") { + return Err("option without name".into()); + } + let type_pos = toks + .iter() + .position(|&(_, t)| t == "type") + .ok_or("option without type")?; + if type_pos < 3 { + return Err("empty option name".into()); + } + let name = line[toks[2].0..toks[type_pos].0].trim().to_string(); + let kind_tok = toks.get(type_pos + 1).ok_or("option without type value")?.1; + + // Collect keyword → raw value slices after the type token. + let mut default: Option = None; + let mut min: Option<&str> = None; + let mut max: Option<&str> = None; + let mut vars: Vec = Vec::new(); + let mut i = type_pos + 2; + while i < toks.len() { + let key = toks[i].1; + if !OPTION_KEYS.contains(&key) { + return Err(format!("unexpected token {key:?} in option")); + } + let start = i + 1; + let mut end = start; + while end < toks.len() && !OPTION_KEYS.contains(&toks[end].1) { + end += 1; + } + let value = if start < end { + let from = toks[start].0; + let to = toks[end - 1].0 + toks[end - 1].1.len(); + line[from..to].to_string() + } else { + String::new() + }; + match key { + "default" => default = Some(value), + "min" => min = Some(toks.get(start).map(|t| t.1).unwrap_or("")), + "max" => max = Some(toks.get(start).map(|t| t.1).unwrap_or("")), + _ => vars.push(value), + } + i = end; + } + let int = |v: &str, what: &str| { + v.parse::() + .map_err(|_| format!("bad {what} {v:?} for option {name:?}")) + }; + let kind = match kind_tok { + "check" => OptionKind::Check { + default: match default.as_deref() { + Some("true") => true, + Some("false") => false, + other => return Err(format!("bad check default {other:?}")), + }, + }, + "spin" => OptionKind::Spin { + default: int(default.as_deref().ok_or("spin without default")?, "default")?, + min: min.map(|v| int(v, "min")).transpose()?, + max: max.map(|v| int(v, "max")).transpose()?, + }, + "combo" => OptionKind::Combo { + default: default.unwrap_or_default(), + vars, + }, + "button" => OptionKind::Button, + "string" => OptionKind::String { + default: default.unwrap_or_default(), + }, + other => return Err(format!("unknown option type {other:?}")), + }; + Ok(EngineOption { name, kind }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn info(line: &str) -> SearchInfo { + match parse_line(line).unwrap() { + EngineLine::Info(i) => i, + other => panic!("not info: {other:?}"), + } + } + + #[test] + fn stockfish_info_line() { + let i = info( + "info depth 10 seldepth 14 multipv 2 score cp -23 upperbound nodes 12345 nps 678900 \ + hashfull 12 tbhits 0 time 18 pv e7e5 g1f3 b8c6", + ); + assert_eq!(i.depth, Some(10)); + assert_eq!(i.seldepth, Some(14)); + assert_eq!(i.multipv, Some(2)); + assert_eq!( + i.score, + Some(EngineScore { + score: Score::Cp(-23), + bound: ScoreBound::Upper + }) + ); + assert_eq!(i.nodes, Some(12345)); + assert_eq!(i.nps, Some(678900)); + assert_eq!(i.hashfull, Some(12)); + assert_eq!(i.time_ms, Some(18)); + assert_eq!(i.pv, vec!["e7e5", "g1f3", "b8c6"]); + } + + #[test] + fn mate_and_wdl() { + let i = info("info depth 5 score mate -3 wdl 0 0 1000 pv a1a2"); + assert_eq!(i.score.unwrap().score, Score::Mate(-3)); + assert_eq!(i.wdl, Some((0, 0, 1000))); + assert_eq!(i.multipv_index(), 1); + let z = info("info depth 0 score mate 0"); + assert_eq!(z.score.unwrap().score, Score::Mate(0)); + assert!(z.pv.is_empty()); + } + + #[test] + fn pv_stops_at_known_key_and_lowerbound() { + let i = info("info score cp 15 lowerbound pv e2e4 e7e5 depth 3"); + assert_eq!(i.pv, vec!["e2e4", "e7e5"]); + assert_eq!(i.depth, Some(3)); + assert_eq!(i.score.unwrap().bound, ScoreBound::Lower); + } + + #[test] + fn info_string_and_currmove() { + assert_eq!( + parse_line("info string NNUE evaluation using nn.nnue").unwrap(), + EngineLine::InfoString("NNUE evaluation using nn.nnue".into()) + ); + let i = info("info depth 3 currmove e2e4 currmovenumber 1"); + assert_eq!(i.depth, Some(3)); + assert!(i.pv.is_empty()); + } + + #[test] + fn malformed_info_is_error() { + for l in [ + "info depth x", + "info depth", + "info score banana 3", + "info score cp", + "info multipv 0", + "info nodes -5", + "info wdl 1 2", + ] { + assert!(parse_line(l).is_err(), "{l}"); + } + } + + #[test] + fn bestmove_variants() { + assert_eq!( + parse_line("bestmove e2e4 ponder c7c6").unwrap(), + EngineLine::BestMove { + best: Some("e2e4".into()), + ponder: Some("c7c6".into()) + } + ); + assert_eq!( + parse_line("bestmove (none)").unwrap(), + EngineLine::BestMove { + best: None, + ponder: None + } + ); + assert!(parse_line("bestmove").is_err()); + } + + #[test] + fn id_lines_keep_spacing() { + assert_eq!( + parse_line("id name Stockfish 19").unwrap(), + EngineLine::IdName("Stockfish 19".into()) + ); + assert_eq!( + parse_line("id author the Stockfish developers (see AUTHORS file)").unwrap(), + EngineLine::IdAuthor("the Stockfish developers (see AUTHORS file)".into()) + ); + assert_eq!(parse_line(" ").unwrap(), EngineLine::Empty); + assert!(matches!( + parse_line("Stockfish 19 by the Stockfish developers").unwrap(), + EngineLine::Unknown(_) + )); + } + + fn opt(line: &str) -> EngineOption { + match parse_line(line).unwrap() { + EngineLine::Option(o) => o, + other => panic!("{other:?}"), + } + } + + #[test] + fn options() { + assert_eq!( + opt("option name Threads type spin default 1 min 1 max 1024"), + EngineOption { + name: "Threads".into(), + kind: OptionKind::Spin { + default: 1, + min: Some(1), + max: Some(1024) + } + } + ); + assert_eq!( + opt("option name Debug Log File type string default ").kind, + OptionKind::String { + default: "".into() + } + ); + assert_eq!( + opt("option name Book File type string default").kind, + OptionKind::String { default: "".into() } + ); + assert_eq!( + opt("option name Ponder type check default false"), + EngineOption { + name: "Ponder".into(), + kind: OptionKind::Check { default: false } + } + ); + assert_eq!(opt("option name Clear Hash type button").name, "Clear Hash"); + assert_eq!( + opt("option name Play Style type combo default Normal var Solid var Normal var Very Risky") + .kind, + OptionKind::Combo { + default: "Normal".into(), + vars: vec!["Solid".into(), "Normal".into(), "Very Risky".into()] + } + ); + for bad in [ + "option name X type spin default x", + "option name X type check default maybe", + "option name X type", + "option name type spin default 1", + "option X type button", + "option name X type weird", + ] { + assert!(parse_line(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/uci/src/process.rs b/crates/uci/src/process.rs new file mode 100644 index 0000000..76912a6 --- /dev/null +++ b/crates/uci/src/process.rs @@ -0,0 +1,634 @@ +//! The engine as a child process: started without a shell, its stdout and stderr +//! read by two threads, the protocol ([`crate::protocol`]) driven by a supervisor +//! thread that waits for input with the session's deadline. + +use std::collections::VecDeque; +use std::ffi::{OsStr, OsString}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use crate::error::EngineError; +use crate::events::{EngineEvent, TerminationReason, Waker}; +use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line}; +use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts}; + +/// Maximum stored length of one output line; longer lines are truncated. +const MAX_LINE_BYTES: usize = 64 * 1024; +/// Number of stderr lines kept for diagnostics. +const STDERR_TAIL_LINES: usize = 256; + +/// Spawn configuration. +#[derive(Debug, Clone)] +pub struct EngineConfig { + pub path: PathBuf, + pub args: Vec, + /// Working directory of the engine. `None` = directory of the executable + /// (engines often look for weights/books next to themselves). + pub working_dir: Option, + pub timeouts: Timeouts, + /// Added to the engine's nice value on Unix (0 = as the app): a phone keeps its + /// interface smooth while the engine thinks. Every thread of the engine has it. + pub nice: i32, + /// Variables added to the engine's environment (Rodent IV on Android finds its + /// personalities and books by `RODENT4HOME`). + pub env: Vec<(OsString, OsString)>, + /// Linux and Android: the engine is killed when the thread that started it ends + /// (`PR_SET_PDEATHSIG`), and so when the program ends, even in the middle of the + /// handshake. For engines whose starting thread lives as long as they should. + pub kill_with_parent: bool, +} + +impl EngineConfig { + pub fn new(path: impl Into) -> Self { + EngineConfig { + path: path.into(), + args: Vec::new(), + working_dir: None, + timeouts: Timeouts::default(), + nice: 0, + env: Vec::new(), + kill_with_parent: false, + } + } +} + +/// Namespace for spawning engines. +pub struct Engine; + +impl Engine { + /// Starts the engine and performs `uci`/`uciok` and `isready`/`readyok`. + /// + /// **Blocks** for up to `uciok + readyok` timeouts (defaults: 10 s each); + /// call it from a worker thread, not from the UI frame. + pub fn spawn( + path: impl AsRef, + args: I, + waker: Waker, + ) -> Result + where + I: IntoIterator, + S: AsRef, + { + let mut cfg = EngineConfig::new(path.as_ref()); + cfg.args = args.into_iter().map(|a| a.as_ref().to_owned()).collect(); + Self::spawn_with(cfg, waker) + } + + pub fn spawn_with(cfg: EngineConfig, waker: Waker) -> Result { + spawn_impl(cfg, waker) + } +} + +enum Input { + Cmd(Cmd), + Quit, + Stdout(String), + StdoutClosed, +} + +/// Handle owned by the UI. Dropping it quits (and if needed kills) the engine. +pub struct EngineHandle { + info: EngineInfo, + pid: u32, + tx: Sender, + events: Receiver, + alive: Arc, + child: Arc>, + stderr: Arc>>, + supervisor: Option>, + done: Receiver<()>, + timeouts: Timeouts, +} + +impl std::fmt::Debug for EngineHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EngineHandle") + .field("name", &self.info.name) + .field("pid", &self.pid) + .field("alive", &self.is_running()) + .finish() + } +} + +impl EngineHandle { + /// `id name/author` and declared options from the handshake. + pub fn info(&self) -> &EngineInfo { + &self.info + } + + pub fn pid(&self) -> u32 { + self.pid + } + + /// `false` after the engine terminated (quit, crash, hung-kill). + pub fn is_running(&self) -> bool { + self.alive.load(Ordering::Acquire) + } + + /// Non-blocking poll for the next event (call every frame). + pub fn try_recv(&self) -> Option { + self.events.try_recv().ok() + } + + /// Drains all currently queued events without blocking. + pub fn drain_events(&self) -> impl Iterator + '_ { + self.events.try_iter() + } + + /// Blocking receive with a timeout (tests, non-UI callers). + pub fn recv_timeout(&self, timeout: Duration) -> Option { + self.events.recv_timeout(timeout).ok() + } + + /// Last lines the engine wrote to stderr. + pub fn stderr_tail(&self) -> Vec { + lock(&self.stderr).iter().cloned().collect() + } + + /// Infinite analysis (`go infinite`) of `position` under `search_id`. + pub fn analyze( + &self, + position: EnginePosition, + search_id: SearchId, + ) -> Result<(), EngineError> { + self.search(position, search_id, SearchLimits::Infinite) + } + + /// Requests a search. Never blocks: the request is queued; a running + /// search is stopped first and only the latest request is started. + pub fn search( + &self, + position: EnginePosition, + search_id: SearchId, + limits: SearchLimits, + ) -> Result<(), EngineError> { + self.search_among(position, search_id, limits, Vec::new()) + } + + /// A search among these moves only (`go … searchmoves`, UCI moves of `position`); + /// empty: all of them. A move that is not a UCI move is refused. + pub fn search_among( + &self, + position: EnginePosition, + search_id: SearchId, + limits: SearchLimits, + among: Vec, + ) -> Result<(), EngineError> { + self.send(Cmd::search(position, search_id, limits, among)?) + } + + /// Stops the running search (its `BestMove` still arrives) and cancels a + /// queued one. + pub fn stop(&self) -> Result<(), EngineError> { + self.send(Cmd::Stop) + } + + /// `setoption`. `value` is `None` for buttons. Validated against the + /// declared options. Applied immediately when idle, otherwise at the next + /// search boundary (UCI forbids `setoption` during a search) — to see the + /// effect on the current analysis, call [`Self::analyze`] again. + pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> { + self.send(Cmd::Setup(option_line(&self.info, name, value)?)) + } + + pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { + self.set_option("MultiPV", Some(&lines.to_string())) + } + + pub fn set_threads(&self, threads: u32) -> Result<(), EngineError> { + self.set_option("Threads", Some(&threads.to_string())) + } + + pub fn set_hash_mb(&self, mb: u32) -> Result<(), EngineError> { + self.set_option("Hash", Some(&mb.to_string())) + } + + /// `ucinewgame` (applied at the next idle point, followed by `isready`). + pub fn new_game(&self) -> Result<(), EngineError> { + self.send(Cmd::Setup("ucinewgame".into())) + } + + /// Sends `stop`/`quit`, waits up to the quit timeout, then kills. Returns + /// the exit status if the process was reaped. + pub fn quit(mut self) -> Option { + self.shutdown() + } + + fn send(&self, cmd: Cmd) -> Result<(), EngineError> { + if !self.is_running() { + return Err(EngineError::NotRunning); + } + self.tx + .send(Input::Cmd(cmd)) + .map_err(|_| EngineError::NotRunning) + } + + fn shutdown(&mut self) -> Option { + if let Some(join) = self.supervisor.take() { + let _ = self.tx.send(Input::Quit); + // The supervisor bounds its own shutdown by stop+quit timeouts; + // the margin covers scheduling. If it is still stuck (e.g. a + // blocked write), kill the process from here. + let limit = self.timeouts.quit + self.timeouts.stop + Duration::from_millis(500); + match self.done.recv_timeout(limit) { + Err(RecvTimeoutError::Timeout) => { + let mut child = lock(&self.child); + let _ = child.kill(); + let _ = child.wait(); + drop(child); + // Killing closes the pipes, so the supervisor will finish. + let _ = self.done.recv_timeout(Duration::from_secs(1)); + if join.is_finished() { + let _ = join.join(); + } + } + _ => { + let _ = join.join(); + } + } + self.alive.store(false, Ordering::Release); + } + let mut child = lock(&self.child); + match child.try_wait() { + Ok(Some(status)) => Some(status), + _ => { + // Should not happen; make sure no zombie is left behind. + let _ = child.kill(); + child.wait().ok() + } + } + } +} + +impl Drop for EngineHandle { + fn drop(&mut self) { + self.shutdown(); + } +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result { + let path = cfg.path.clone(); + match std::fs::metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Err(EngineError::NotFound(path)); + } + Err(e) => { + return Err(EngineError::NotExecutable { + path, + reason: e.to_string(), + }); + } + Ok(m) if m.is_dir() => { + return Err(EngineError::NotExecutable { + path, + reason: "is a directory".into(), + }); + } + Ok(_) => {} + } + let workdir = cfg.working_dir.clone().or_else(|| { + path.parent() + .filter(|p| !p.as_os_str().is_empty()) + .map(Path::to_path_buf) + }); + let mut command = Command::new(&path); + command + .args(&cfg.args) + .envs(cfg.env.iter().map(|(k, v)| (k, v))) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if let Some(dir) = workdir { + command.current_dir(dir); + } + #[cfg(unix)] + if cfg.nice != 0 || cfg.kill_with_parent { + use std::os::unix::process::CommandExt; + let (nice, kill) = (cfg.nice, cfg.kill_with_parent); + // SAFETY: nice(2) and prctl(2) are async-signal-safe system calls and touch no + // memory of the parent. The results are not checked: an engine at the app's + // priority, or one outliving it, still works. + unsafe { + command.pre_exec(move || { + if nice != 0 { + libc::nice(nice); + } + #[cfg(any(target_os = "linux", target_os = "android"))] + if kill { + libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL); + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + let _ = kill; + Ok(()) + }); + } + } + #[cfg(windows)] + { + // Console engines would otherwise open a terminal window per process. + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + let mut child = command.spawn().map_err(|e| { + use std::io::ErrorKind as K; + match e.kind() { + K::NotFound => EngineError::NotFound(path.clone()), + K::PermissionDenied => EngineError::NotExecutable { + path: path.clone(), + reason: e.to_string(), + }, + // ENOEXEC: exec format error (wrong architecture, text file). + _ if e.raw_os_error() == Some(8) => EngineError::NotExecutable { + path: path.clone(), + reason: e.to_string(), + }, + _ => EngineError::Spawn(e), + } + })?; + let pid = child.id(); + // Unwraps are safe: all three were configured as piped. + let stdin = child.stdin.take().expect("piped stdin"); + let stdout = child.stdout.take().expect("piped stdout"); + let stderr = child.stderr.take().expect("piped stderr"); + + let (tx, rx) = mpsc::channel::(); + let stderr_tail = Arc::new(Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES))); + + { + let tx = tx.clone(); + thread::Builder::new() + .name(format!("uci-stdout-{pid}")) + .spawn(move || { + read_lines(BufReader::new(stdout), |line| { + tx.send(Input::Stdout(line)).is_ok() + }); + let _ = tx.send(Input::StdoutClosed); + }) + .map_err(EngineError::Spawn)?; + } + { + let tail = Arc::clone(&stderr_tail); + thread::Builder::new() + .name(format!("uci-stderr-{pid}")) + .spawn(move || { + read_lines(BufReader::new(stderr), |line| { + let mut t = lock(&tail); + if t.len() == STDERR_TAIL_LINES { + t.pop_front(); + } + t.push_back(line); + true + }); + }) + .map_err(EngineError::Spawn)?; + } + + let mut stdin = stdin; + let (info, warnings) = match handshake(&mut stdin, &rx, &cfg.timeouts) { + Ok(done) => done, + Err(mut e) => { + let _ = child.kill(); + let status = child.wait().ok(); + if let EngineError::ProcessExited { + status: s, + stderr: err, + } = &mut e + { + *s = status; + // Give the stderr thread a moment to collect the last words. + thread::sleep(Duration::from_millis(20)); + *err = lock(&stderr_tail).iter().cloned().collect(); + } + return Err(e); + } + }; + + let (ev_tx, ev_rx) = mpsc::channel(); + let alive = Arc::new(AtomicBool::new(true)); + let child = Arc::new(Mutex::new(child)); + let (done_tx, done_rx) = mpsc::channel::<()>(); + let mut sup = Supervisor { + pipes: Pipes { + stdin, + events: ev_tx, + waker, + }, + session: Session::new(cfg.timeouts), + child: Arc::clone(&child), + alive: Arc::clone(&alive), + timeouts: cfg.timeouts, + }; + for w in warnings { + sup.session.warn(w, &mut sup.pipes); + } + let supervisor = thread::Builder::new() + .name(format!("uci-supervisor-{pid}")) + .spawn(move || { + let _done = done_tx; + sup.run(rx); + }) + .map_err(EngineError::Spawn)?; + + Ok(EngineHandle { + info, + pid, + tx, + events: ev_rx, + alive, + child, + stderr: stderr_tail, + supervisor: Some(supervisor), + done: done_rx, + timeouts: cfg.timeouts, + }) +} + +fn write_line(stdin: &mut ChildStdin, line: &str) -> std::io::Result<()> { + let mut buf = Vec::with_capacity(line.len() + 1); + buf.extend_from_slice(line.as_bytes()); + buf.push(b'\n'); + stdin.write_all(&buf)?; + stdin.flush() +} + +/// The handshake over the pipes: every line read goes to [`Handshake`], until it is +/// complete or its deadline passes. +fn handshake( + stdin: &mut ChildStdin, + rx: &Receiver, + t: &Timeouts, +) -> Result<(EngineInfo, Vec), EngineError> { + let exited = || EngineError::ProcessExited { + status: None, + stderr: Vec::new(), + }; + let io = |e: std::io::Error| { + if e.kind() == std::io::ErrorKind::BrokenPipe { + exited() + } else { + EngineError::Io(e) + } + }; + let mut hs = Handshake::new(t, Instant::now()); + write_line(stdin, Handshake::FIRST_LINE).map_err(io)?; + loop { + let wait = hs.deadline().saturating_duration_since(Instant::now()); + let line = match rx.recv_timeout(wait) { + Ok(Input::Stdout(l)) => l, + Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), + Ok(Input::Cmd(_) | Input::Quit) => continue, + Err(RecvTimeoutError::Timeout) => return Err(hs.timed_out()), + }; + match hs.on_line(line, Instant::now()) { + HandshakeStep::Continue => {} + HandshakeStep::Write(l) => write_line(stdin, l).map_err(io)?, + HandshakeStep::Done(info, warnings) => return Ok((info, warnings)), + } + } +} + +/// Reads `\n`-terminated lines with a length cap; stops at EOF/error or when +/// `f` returns false. +fn read_lines(mut r: BufReader, mut f: impl FnMut(String) -> bool) { + let mut buf: Vec = Vec::new(); + loop { + buf.clear(); + let mut eof = false; + loop { + let avail = match r.fill_buf() { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => { + eof = true; + break; + } + }; + if avail.is_empty() { + eof = true; + break; + } + let (chunk, used, done) = match avail.iter().position(|&b| b == b'\n') { + Some(i) => (&avail[..i], i + 1, true), + None => (avail, avail.len(), false), + }; + let room = MAX_LINE_BYTES.saturating_sub(buf.len()); + buf.extend_from_slice(&chunk[..chunk.len().min(room)]); + r.consume(used); + if done { + break; + } + } + if eof && buf.is_empty() { + return; + } + if buf.last() == Some(&b'\r') { + buf.pop(); + } + if !f(String::from_utf8_lossy(&buf).into_owned()) || eof { + return; + } + } +} + +/// The process side of the session: the engine's stdin and the events' channel. +struct Pipes { + stdin: ChildStdin, + events: Sender, + waker: Waker, +} + +impl Link for Pipes { + fn write(&mut self, line: &str) -> Result<(), Gone> { + write_line(&mut self.stdin, line).map_err(|_| Gone) + } + + fn emit(&mut self, ev: EngineEvent) { + if self.events.send(ev).is_ok() { + (self.waker)(); + } + } +} + +struct Supervisor { + pipes: Pipes, + session: Session, + child: Arc>, + alive: Arc, + timeouts: Timeouts, +} + +impl Supervisor { + fn run(mut self, rx: Receiver) { + let result = loop { + let msg = match self.session.deadline() { + Some(d) => rx.recv_timeout(d.saturating_duration_since(Instant::now())), + None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected), + }; + let now = Instant::now(); + let step = match msg { + Ok(Input::Quit) | Err(RecvTimeoutError::Disconnected) => { + self.quit(); + return; + } + Ok(Input::Cmd(cmd)) => self.session.on_cmd(cmd, now, &mut self.pipes), + Ok(Input::Stdout(line)) => self.session.on_line(&line, now, &mut self.pipes), + Ok(Input::StdoutClosed) => Err(Exit::Gone), + Err(RecvTimeoutError::Timeout) => self.session.on_time(now), + }; + if let Err(e) = step { + break e; + } + }; + self.alive.store(false, Ordering::Release); + let reason = match result { + Exit::Hung(waiting_for) => { + let mut child = lock(&self.child); + let _ = child.kill(); + let _ = child.wait(); + TerminationReason::Hung { waiting_for } + } + Exit::Gone => TerminationReason::Exited { + status: self.reap(Duration::from_millis(500)), + }, + }; + self.pipes.emit(EngineEvent::Terminated(reason)); + } + + /// Waits up to `grace` for the process to exit, then kills it. Always reaps. + fn reap(&self, grace: Duration) -> Option { + let deadline = Instant::now() + grace; + loop { + { + let mut child = lock(&self.child); + match child.try_wait() { + Ok(Some(s)) => return Some(s), + Ok(None) if Instant::now() < deadline => {} + _ => { + let _ = child.kill(); + return child.wait().ok(); + } + } + } + thread::sleep(Duration::from_millis(5)); + } + } + + fn quit(&mut self) { + self.alive.store(false, Ordering::Release); + self.session.quit(&mut self.pipes); + let status = self.reap(self.timeouts.quit); + self.pipes + .emit(EngineEvent::Terminated(TerminationReason::Quit { status })); + } +} diff --git a/crates/uci/src/protocol.rs b/crates/uci/src/protocol.rs new file mode 100644 index 0000000..a48af09 --- /dev/null +++ b/crates/uci/src/protocol.rs @@ -0,0 +1,619 @@ +//! The UCI protocol as a state machine without I/O: the handshake and the session +//! after it. A transport (a child process on a computer, a Web Worker in a browser) +//! feeds it the engine's lines, the user's commands and the time, and carries out +//! what it asks: lines to write, events to deliver. Waiting is the transport's +//! business — the machine never blocks, it only names its next deadline. + +use web_time::Instant; + +use crate::error::EngineError; +use crate::events::EngineEvent; +use crate::parse::{EngineLine, parse_line}; +use crate::types::{EngineInfo, EnginePosition, OptionKind, SearchId, SearchLimits, Timeouts}; + +/// Maximum number of `Warning` events emitted per engine (flood protection). +const MAX_WARNINGS: usize = 100; + +/// A command from the handle to the session. +pub(crate) enum Cmd { + Search { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, + }, + Stop, + /// A complete `setoption ...` / `ucinewgame` line, applied while idle. + Setup(String), +} + +impl Cmd { + /// A search request, checked: a valid position, UCI moves to search among. + pub(crate) fn search( + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, + ) -> Result { + position.validate()?; + if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) { + return Err(EngineError::InvalidInput(format!("not a move: {bad:?}"))); + } + Ok(Cmd::Search { + position, + id, + limits, + among, + }) + } +} + +/// The `setoption` line for `name` = `value` (`None` for buttons), checked against +/// the options the engine declared. +pub(crate) fn option_line( + info: &EngineInfo, + name: &str, + value: Option<&str>, +) -> Result { + let opt = info + .option(name) + .ok_or_else(|| EngineError::UnknownOption(name.to_string()))?; + let bad = |reason: String| EngineError::InvalidOptionValue { + name: opt.name.clone(), + reason, + }; + if let Some(v) = value + && v.chars().any(char::is_control) + { + return Err(bad("control characters in value".into())); + } + let value = match (&opt.kind, value) { + (OptionKind::Button, None) => None, + (OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())), + (_, None) => return Err(bad("value required".into())), + (OptionKind::Check { .. }, Some(v)) => match v { + "true" | "false" => Some(v.to_string()), + _ => return Err(bad(format!("expected true/false, got {v:?}"))), + }, + (OptionKind::Spin { min, max, .. }, Some(v)) => { + let n: i64 = v + .trim() + .parse() + .map_err(|_| bad(format!("not an integer: {v:?}")))?; + if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) { + return Err(bad(format!("{n} outside {min:?}..={max:?}"))); + } + Some(n.to_string()) + } + (OptionKind::Combo { vars, .. }, Some(v)) => { + let var = vars + .iter() + .find(|x| x.eq_ignore_ascii_case(v)) + .ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?; + Some(var.clone()) + } + (OptionKind::String { .. }, Some(v)) => Some(v.to_string()), + }; + let line = match value { + Some(v) => format!("setoption name {} value {}", opt.name, v), + None => format!("setoption name {}", opt.name), + }; + Ok(line) +} + +/// The engine could not be written to: it is gone. +#[derive(Debug)] +pub(crate) struct Gone; + +/// What the session does to the outside world. +pub(crate) trait Link { + /// Writes one line (without its `\n`) to the engine. + fn write(&mut self, line: &str) -> Result<(), Gone>; + /// Delivers an event to the handle (and wakes the UI). + fn emit(&mut self, ev: EngineEvent); +} + +/// The step of the handshake: `uci` → `uciok`, then `isready` → `readyok`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Phase { + Uci, + Ready, +} + +/// `uci`/`uciok` and `isready`/`readyok`: the engine's name, author and options. +pub(crate) struct Handshake { + phase: Phase, + deadline: Instant, + readyok: std::time::Duration, + info: EngineInfo, + seen_uci: bool, + /// First lines of output, for [`EngineError::NotUci`]. + output: Vec, + /// Malformed lines, reported once the session runs. + warnings: Vec, +} + +/// How a line moved the handshake on. +pub(crate) enum HandshakeStep { + /// Keep feeding lines. + Continue, + /// Write this line, then keep feeding lines. + Write(&'static str), + /// Complete: the engine is ready for the session. + Done(EngineInfo, Vec), +} + +impl Handshake { + /// Starts the handshake at `now`; the caller writes [`Self::FIRST_LINE`]. + pub(crate) fn new(t: &Timeouts, now: Instant) -> Self { + Handshake { + phase: Phase::Uci, + deadline: now + t.uciok, + readyok: t.readyok, + info: EngineInfo::default(), + seen_uci: false, + output: Vec::new(), + warnings: Vec::new(), + } + } + + pub(crate) const FIRST_LINE: &'static str = "uci"; + + pub(crate) fn deadline(&self) -> Instant { + self.deadline + } + + /// One line of the engine's output, read at `now`. + pub(crate) fn on_line(&mut self, line: String, now: Instant) -> HandshakeStep { + match self.phase { + Phase::Uci => { + if self.output.len() < 20 { + self.output.push(line.clone()); + } + match parse_line(&line) { + Ok(EngineLine::IdName(n)) => { + self.seen_uci = true; + self.info.name = Some(n); + } + Ok(EngineLine::IdAuthor(a)) => { + self.seen_uci = true; + self.info.author = Some(a); + } + Ok(EngineLine::Option(o)) => { + self.seen_uci = true; + self.info.options.push(o); + } + Ok(EngineLine::UciOk) => { + self.phase = Phase::Ready; + self.deadline = now + self.readyok; + return HandshakeStep::Write("isready"); + } + Ok(_) => {} + Err(e) => { + if line.starts_with("option") { + self.seen_uci = true; + } + self.warnings.push(format!("handshake: {e}")); + } + } + HandshakeStep::Continue + } + Phase::Ready => { + if matches!(parse_line(&line), Ok(EngineLine::ReadyOk)) { + HandshakeStep::Done( + std::mem::take(&mut self.info), + std::mem::take(&mut self.warnings), + ) + } else { + HandshakeStep::Continue + } + } + } + } + + /// The error once [`Self::deadline`] has passed. + pub(crate) fn timed_out(self) -> EngineError { + match self.phase { + Phase::Uci if self.seen_uci => EngineError::HandshakeTimeout { + waiting_for: "uciok", + }, + Phase::Uci => EngineError::NotUci { + output: self.output, + }, + Phase::Ready => EngineError::HandshakeTimeout { + waiting_for: "readyok", + }, + } + } +} + +/// Session state. Invariant: `position`/`go` is only written in +/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a +/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` +/// belongs to the current search, and `info` read while `Idle`/`Syncing` is +/// stale and dropped. +#[derive(Debug, Clone, Copy)] +enum State { + /// No search running, nothing pending. + Idle, + /// `isready` sent before starting the pending search; waiting `readyok`. + Syncing { + deadline: Instant, + }, + Searching { + id: SearchId, + }, + /// `stop` sent; waiting for the final `bestmove` of `id`. + Stopping { + id: SearchId, + deadline: Instant, + }, +} + +struct PendingSearch { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, +} + +/// Why the session must end. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Exit { + /// The engine stopped reading or writing. + Gone, + /// The engine did not answer this in time; the transport kills it. + Hung(&'static str), +} + +impl From for Exit { + fn from(_: Gone) -> Self { + Exit::Gone + } +} + +/// The session after the handshake: searches, their boundaries, setup lines. +pub(crate) struct Session { + timeouts: Timeouts, + state: State, + pending: Option, + pending_setup: Vec, + warnings: usize, +} + +impl Session { + pub(crate) fn new(timeouts: Timeouts) -> Self { + Session { + timeouts, + state: State::Idle, + pending: None, + pending_setup: Vec::new(), + warnings: 0, + } + } + + /// When [`Self::on_time`] must be called next (`None`: nothing to wait for). + pub(crate) fn deadline(&self) -> Option { + match self.state { + State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), + _ => None, + } + } + + /// The time is `now`: an engine past its deadline is hung. + pub(crate) fn on_time(&mut self, now: Instant) -> Result<(), Exit> { + match self.state { + State::Syncing { deadline } if now >= deadline => Err(Exit::Hung("readyok")), + State::Stopping { deadline, .. } if now >= deadline => Err(Exit::Hung("bestmove")), + _ => Ok(()), + } + } + + pub(crate) fn warn(&mut self, msg: String, link: &mut impl Link) { + self.warnings += 1; + if self.warnings < MAX_WARNINGS { + link.emit(EngineEvent::Warning(msg)); + } else if self.warnings == MAX_WARNINGS { + link.emit(EngineEvent::Warning( + "too many warnings; further warnings suppressed".into(), + )); + } + } + + /// The last words before `quit`: a running search is stopped. + pub(crate) fn quit(&mut self, link: &mut impl Link) { + if matches!(self.state, State::Searching { .. }) { + let _ = link.write("stop"); + } + let _ = link.write("quit"); + } + + pub(crate) fn on_cmd( + &mut self, + cmd: Cmd, + now: Instant, + link: &mut impl Link, + ) -> Result<(), Exit> { + match cmd { + Cmd::Search { + position, + id, + limits, + among, + } => { + if let Some(old) = self.pending.replace(PendingSearch { + position, + id, + limits, + among, + }) { + link.emit(EngineEvent::Superseded { search_id: old.id }); + } + match self.state { + State::Idle => self.begin_sync(now, link)?, + State::Searching { id } => self.send_stop(id, now, link)?, + State::Syncing { .. } | State::Stopping { .. } => {} + } + } + Cmd::Stop => { + if let Some(old) = self.pending.take() { + link.emit(EngineEvent::Superseded { search_id: old.id }); + } + if let State::Searching { id } = self.state { + self.send_stop(id, now, link)?; + } + } + Cmd::Setup(line) => match self.state { + // The engine is not searching: safe to send right away; the + // `isready` before the next `go` fences it. + State::Idle | State::Syncing { .. } => link.write(&line)?, + State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), + }, + } + Ok(()) + } + + fn send_stop(&mut self, id: SearchId, now: Instant, link: &mut impl Link) -> Result<(), Exit> { + link.write("stop")?; + self.state = State::Stopping { + id, + deadline: now + self.timeouts.stop, + }; + Ok(()) + } + + /// Engine is idle: flush queued setup, then `isready` if a search waits. + fn begin_sync(&mut self, now: Instant, link: &mut impl Link) -> Result<(), Exit> { + for line in std::mem::take(&mut self.pending_setup) { + link.write(&line)?; + } + if self.pending.is_some() { + link.write("isready")?; + self.state = State::Syncing { + deadline: now + self.timeouts.readyok, + }; + } else { + self.state = State::Idle; + } + Ok(()) + } + + fn current_search(&self) -> Option { + match self.state { + State::Searching { id } | State::Stopping { id, .. } => Some(id), + _ => None, + } + } + + /// One line of the engine's output, read at `now`. + pub(crate) fn on_line( + &mut self, + line: &str, + now: Instant, + link: &mut impl Link, + ) -> Result<(), Exit> { + let parsed = match parse_line(line) { + Ok(p) => p, + Err(e) => { + self.warn(e.to_string(), link); + return Ok(()); + } + }; + match parsed { + EngineLine::Info(info) => { + if let Some(id) = self.current_search() + && (info.score.is_some() || !info.pv.is_empty()) + { + link.emit(EngineEvent::Info { + search_id: id, + info, + }); + } + // Otherwise: stale output of a finished search, dropped. + } + EngineLine::InfoString(text) => { + let search_id = self.current_search(); + link.emit(EngineEvent::InfoString { search_id, text }); + } + EngineLine::BestMove { best, ponder } => match self.current_search() { + Some(id) => { + link.emit(EngineEvent::BestMove { + search_id: id, + best, + ponder, + }); + self.state = State::Idle; + self.begin_sync(now, link)?; + } + None => self.warn(format!("unexpected bestmove ignored: {line:?}"), link), + }, + EngineLine::ReadyOk => { + if let State::Syncing { .. } = self.state { + match self.pending.take() { + Some(p) => { + link.write(&p.position.to_command())?; + let mut go = p.limits.to_command(); + if !p.among.is_empty() { + go += " searchmoves "; + go += &p.among.join(" "); + } + link.write(&go)?; + self.state = State::Searching { id: p.id }; + link.emit(EngineEvent::SearchStarted { search_id: p.id }); + } + None => self.state = State::Idle, + } + } + } + EngineLine::Empty => {} + EngineLine::UciOk + | EngineLine::IdName(_) + | EngineLine::IdAuthor(_) + | EngineLine::Option(_) + | EngineLine::Unknown(_) => { + self.warn(format!("unexpected engine output: {line:?}"), link); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + /// A link that records what the session did. + #[derive(Default)] + struct Record { + written: Vec, + events: Vec, + broken: bool, + } + + impl Link for Record { + fn write(&mut self, line: &str) -> Result<(), Gone> { + if self.broken { + return Err(Gone); + } + self.written.push(line.to_owned()); + Ok(()) + } + fn emit(&mut self, ev: EngineEvent) { + self.events.push(ev); + } + } + + fn search(id: u64) -> Cmd { + Cmd::Search { + position: EnginePosition::startpos(Vec::::new()), + id: SearchId(id), + limits: SearchLimits::Infinite, + among: Vec::new(), + } + } + + #[test] + fn handshake_collects_info_and_asks_ready() { + let t0 = Instant::now(); + let mut h = Handshake::new(&Timeouts::default(), t0); + assert!(matches!( + h.on_line("id name Fake".into(), t0), + HandshakeStep::Continue + )); + assert!(matches!( + h.on_line( + "option name Hash type spin default 16 min 1 max 1024".into(), + t0 + ), + HandshakeStep::Continue + )); + let later = t0 + Duration::from_secs(1); + assert!(matches!( + h.on_line("uciok".into(), later), + HandshakeStep::Write("isready") + )); + assert_eq!(h.deadline(), later + Timeouts::default().readyok); + // Output before `readyok` is not taken for the engine's description. + assert!(matches!( + h.on_line("id name Other".into(), later), + HandshakeStep::Continue + )); + match h.on_line("readyok".into(), later) { + HandshakeStep::Done(info, warnings) => { + assert_eq!(info.name.as_deref(), Some("Fake")); + assert_eq!(info.options.len(), 1); + assert!(warnings.is_empty()); + } + _ => panic!("handshake not done"), + } + } + + #[test] + fn handshake_timeouts_name_what_was_missing() { + let t0 = Instant::now(); + let silent = Handshake::new(&Timeouts::default(), t0); + assert!(matches!(silent.timed_out(), EngineError::NotUci { .. })); + let mut uci = Handshake::new(&Timeouts::default(), t0); + let _ = uci.on_line("id name Fake".into(), t0); + assert!(matches!( + uci.timed_out(), + EngineError::HandshakeTimeout { + waiting_for: "uciok" + } + )); + let mut ready = Handshake::new(&Timeouts::default(), t0); + let _ = ready.on_line("uciok".into(), t0); + assert!(matches!( + ready.timed_out(), + EngineError::HandshakeTimeout { + waiting_for: "readyok" + } + )); + } + + #[test] + fn a_search_waits_for_readyok_and_stale_info_is_dropped() { + let now = Instant::now(); + let mut s = Session::new(Timeouts::default()); + let mut link = Record::default(); + s.on_cmd(search(1), now, &mut link).unwrap(); + assert_eq!(link.written, ["isready"]); + // Info before the search starts belongs to nobody. + s.on_line("info depth 1 score cp 5 pv e2e4", now, &mut link) + .unwrap(); + assert!(link.events.is_empty()); + s.on_line("readyok", now, &mut link).unwrap(); + assert_eq!(link.written[1], "position startpos"); + assert_eq!(link.written[2], "go infinite"); + assert_eq!( + link.events, + [EngineEvent::SearchStarted { + search_id: SearchId(1) + }] + ); + // A newer request stops the running search; the old `bestmove` ends it. + s.on_cmd(search(2), now, &mut link).unwrap(); + assert_eq!(link.written[3], "stop"); + s.on_line("bestmove e2e4", now, &mut link).unwrap(); + assert_eq!(link.written[4], "isready"); + s.on_line("readyok", now, &mut link).unwrap(); + assert!(link.events.contains(&EngineEvent::SearchStarted { + search_id: SearchId(2) + })); + } + + #[test] + fn deadlines_and_a_broken_link_end_the_session() { + let now = Instant::now(); + let mut s = Session::new(Timeouts::default()); + let mut link = Record::default(); + assert_eq!(s.deadline(), None); + s.on_cmd(search(1), now, &mut link).unwrap(); + let d = s.deadline().expect("waiting for readyok"); + assert_eq!(s.on_time(now), Ok(())); + assert_eq!(s.on_time(d), Err(Exit::Hung("readyok"))); + link.broken = true; + assert_eq!(s.on_line("readyok", now, &mut link), Err(Exit::Gone)); + } +} diff --git a/crates/uci/src/types.rs b/crates/uci/src/types.rs new file mode 100644 index 0000000..7b57cca --- /dev/null +++ b/crates/uci/src/types.rs @@ -0,0 +1,418 @@ +//! Public data types shared by the parser and the supervisor. + +use std::time::Duration; + +use crate::error::EngineError; + +/// Caller-assigned identifier of a search request. +/// +/// UCI itself has no request identifiers; the supervisor attaches this local +/// id to every [`crate::EngineEvent`] that belongs to the search and +/// guarantees that output of a previous search is never reported under a newer +/// id (see the crate documentation for the boundary rules). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct SearchId(pub u64); + +/// Side to move. Kept local so that the crate does not depend on chess-core. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Side { + White, + Black, +} + +impl Side { + pub fn opposite(self) -> Side { + match self { + Side::White => Side::Black, + Side::Black => Side::White, + } + } +} + +/// Score exactly as the engine reported it: relative to the side to move in +/// the analysed (root) position. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Score { + /// Centipawns, positive = good for the side to move. + Cp(i32), + /// Mate in N moves (not plies). Positive: side to move mates; + /// negative: side to move gets mated; `0`: side to move is already mated. + Mate(i32), +} + +/// `lowerbound` / `upperbound` qualifier of a score. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ScoreBound { + #[default] + Exact, + /// The true score is at least the reported value. + Lower, + /// The true score is at most the reported value. + Upper, +} + +impl ScoreBound { + fn flipped(self) -> ScoreBound { + match self { + ScoreBound::Exact => ScoreBound::Exact, + ScoreBound::Lower => ScoreBound::Upper, + ScoreBound::Upper => ScoreBound::Lower, + } + } +} + +/// Engine score with its bound, relative to the side to move. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EngineScore { + pub score: Score, + pub bound: ScoreBound, +} + +/// Evaluation from White's point of view. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WhiteEval { + /// Centipawns, positive = White is better. + Cp(i32), + /// Forced mate. `moves == 0` means the side to move is already mated. + Mate { winner: Side, moves: u32 }, +} + +/// Score converted to White's point of view; the bound is flipped when the +/// sign of the score is flipped. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WhiteScore { + pub eval: WhiteEval, + pub bound: ScoreBound, +} + +impl EngineScore { + /// Converts the engine score (relative to `side_to_move` of the analysed + /// root position) into a White-relative score. Mate stays mate; it is + /// never folded into centipawns. + pub fn to_white(self, side_to_move: Side) -> WhiteScore { + let flip = side_to_move == Side::Black; + let eval = match self.score { + Score::Cp(cp) => WhiteEval::Cp(if flip { cp.saturating_neg() } else { cp }), + Score::Mate(n) if n > 0 => WhiteEval::Mate { + winner: side_to_move, + moves: n.unsigned_abs(), + }, + Score::Mate(n) => WhiteEval::Mate { + winner: side_to_move.opposite(), + moves: n.unsigned_abs(), + }, + }; + let bound = if flip { + self.bound.flipped() + } else { + self.bound + }; + WhiteScore { eval, bound } + } +} + +/// Parsed `info` line. Fields the engine did not send are `None` / empty. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct SearchInfo { + pub depth: Option, + pub seldepth: Option, + /// MultiPV index (1-based). `None` when the engine omitted it, which means + /// line 1. + pub multipv: Option, + pub score: Option, + pub nodes: Option, + pub nps: Option, + pub time_ms: Option, + /// Hash usage in permille. + pub hashfull: Option, + pub tbhits: Option, + /// Win/draw/loss in permille (Stockfish `UCI_ShowWDL`), side to move. + pub wdl: Option<(u32, u32, u32)>, + /// Principal variation in UCI move notation, as sent by the engine. + pub pv: Vec, +} + +impl SearchInfo { + /// MultiPV index, defaulting to 1. + pub fn multipv_index(&self) -> u32 { + self.multipv.unwrap_or(1) + } +} + +/// Typed `option` declaration. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EngineOption { + /// Name as declared by the engine (UCI names are case-insensitive). + pub name: String, + pub kind: OptionKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OptionKind { + Check { + default: bool, + }, + Spin { + default: i64, + min: Option, + max: Option, + }, + Combo { + default: String, + vars: Vec, + }, + Button, + /// Free text. The default is kept verbatim (Stockfish uses ``). + String { + default: String, + }, +} + +/// Result of the `uci` handshake. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct EngineInfo { + pub name: Option, + pub author: Option, + pub options: Vec, +} + +impl EngineInfo { + /// Case-insensitive option lookup (UCI option names are case-insensitive). + pub fn option(&self, name: &str) -> Option<&EngineOption> { + self.options + .iter() + .find(|o| o.name.eq_ignore_ascii_case(name)) + } +} + +/// Root of a position sent with `position`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PositionBase { + StartPos, + Fen(String), +} + +/// Position to analyse: a base position plus the move history in UCI +/// notation. Prefer sending the real history instead of only the final FEN, +/// so the engine can detect repetitions. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EnginePosition { + pub base: PositionBase, + pub moves: Vec, +} + +impl EnginePosition { + pub fn startpos(moves: I) -> Self + where + I: IntoIterator, + S: Into, + { + EnginePosition { + base: PositionBase::StartPos, + moves: moves.into_iter().map(Into::into).collect(), + } + } + + pub fn fen(fen: impl Into, moves: I) -> Self + where + I: IntoIterator, + S: Into, + { + EnginePosition { + base: PositionBase::Fen(fen.into()), + moves: moves.into_iter().map(Into::into).collect(), + } + } + + /// Checks that the position can be sent safely: no line breaks or control + /// characters, no `moves` token inside the FEN, and every move is plain + /// UCI coordinate notation. The null move `0000` is rejected: training + /// `--` must be converted by the caller (e.g. by sending the resulting + /// FEN), not passed as an ordinary move. + pub fn validate(&self) -> Result<(), EngineError> { + if let PositionBase::Fen(fen) = &self.base { + if fen.trim().is_empty() { + return Err(EngineError::InvalidInput("empty FEN".into())); + } + if fen.chars().any(char::is_control) { + return Err(EngineError::InvalidInput( + "FEN contains control characters".into(), + )); + } + if fen.split_ascii_whitespace().any(|t| t == "moves") { + return Err(EngineError::InvalidInput( + "FEN contains the token `moves`".into(), + )); + } + } + for mv in &self.moves { + if !is_uci_move(mv) { + return Err(EngineError::InvalidInput(format!("not a UCI move: {mv:?}"))); + } + } + Ok(()) + } + + /// The `position …` line for this position. + pub fn to_command(&self) -> String { + let mut s = match &self.base { + PositionBase::StartPos => "position startpos".to_string(), + PositionBase::Fen(fen) => format!("position fen {}", fen.trim()), + }; + if !self.moves.is_empty() { + s.push_str(" moves"); + for m in &self.moves { + s.push(' '); + s.push_str(m); + } + } + s + } +} + +pub(crate) fn is_uci_move(m: &str) -> bool { + let b = m.as_bytes(); + let sq = |f: u8, r: u8| (b'a'..=b'h').contains(&f) && (b'1'..=b'8').contains(&r); + match b.len() { + 4 => sq(b[0], b[1]) && sq(b[2], b[3]), + 5 => sq(b[0], b[1]) && sq(b[2], b[3]) && matches!(b[4], b'q' | b'r' | b'b' | b'n'), + _ => false, + } +} + +/// Limits for `go`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SearchLimits { + /// `go infinite`: runs until stopped or until the position changes. + Infinite, + Depth(u32), + MoveTime(Duration), + Nodes(u64), +} + +impl SearchLimits { + /// The `go …` line for these limits. + pub fn to_command(self) -> String { + match self { + SearchLimits::Infinite => "go infinite".into(), + SearchLimits::Depth(d) => format!("go depth {d}"), + SearchLimits::MoveTime(t) => format!("go movetime {}", t.as_millis().max(1)), + SearchLimits::Nodes(n) => format!("go nodes {n}"), + } + } +} + +/// Timeouts used by the supervisor. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Timeouts { + /// `uci` → `uciok`. + pub uciok: Duration, + /// `isready` → `readyok` (handshake and every sync before `go`). + /// Large `Hash` values may need a long time to allocate. + pub readyok: Duration, + /// `stop` → `bestmove`. On expiry the engine is considered hung and killed. + pub stop: Duration, + /// `quit` → process exit. On expiry the process is killed. + pub quit: Duration, +} + +impl Default for Timeouts { + fn default() -> Self { + Timeouts { + uciok: Duration::from_secs(10), + readyok: Duration::from_secs(10), + stop: Duration::from_secs(3), + quit: Duration::from_secs(1), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(score: Score, bound: ScoreBound) -> EngineScore { + EngineScore { score, bound } + } + + #[test] + fn white_perspective_cp() { + let w = s(Score::Cp(35), ScoreBound::Lower).to_white(Side::White); + assert_eq!(w.eval, WhiteEval::Cp(35)); + assert_eq!(w.bound, ScoreBound::Lower); + let b = s(Score::Cp(35), ScoreBound::Lower).to_white(Side::Black); + assert_eq!(b.eval, WhiteEval::Cp(-35)); + assert_eq!(b.bound, ScoreBound::Upper); + let n = s(Score::Cp(-120), ScoreBound::Exact).to_white(Side::Black); + assert_eq!(n.eval, WhiteEval::Cp(120)); + } + + #[test] + fn white_perspective_mate() { + let m = |n, side| s(Score::Mate(n), ScoreBound::Exact).to_white(side).eval; + assert_eq!( + m(3, Side::Black), + WhiteEval::Mate { + winner: Side::Black, + moves: 3 + } + ); + assert_eq!( + m(-2, Side::Black), + WhiteEval::Mate { + winner: Side::White, + moves: 2 + } + ); + assert_eq!( + m(-2, Side::White), + WhiteEval::Mate { + winner: Side::Black, + moves: 2 + } + ); + // mate 0: side to move is mated. + assert_eq!( + m(0, Side::White), + WhiteEval::Mate { + winner: Side::Black, + moves: 0 + } + ); + assert_eq!( + m(0, Side::Black), + WhiteEval::Mate { + winner: Side::White, + moves: 0 + } + ); + } + + #[test] + fn position_validation_and_command() { + let p = EnginePosition::startpos(["e2e4", "e7e5", "e7e8q"]); + p.validate().unwrap(); + assert_eq!(p.to_command(), "position startpos moves e2e4 e7e5 e7e8q"); + assert!(EnginePosition::startpos(["0000"]).validate().is_err()); + assert!(EnginePosition::startpos(["e2e4\nquit"]).validate().is_err()); + assert!(EnginePosition::startpos(["E2E4"]).validate().is_err()); + let f = EnginePosition::fen("8/8/8/8/8/8/8/K6k w - - 0 1", Vec::::new()); + f.validate().unwrap(); + assert_eq!(f.to_command(), "position fen 8/8/8/8/8/8/8/K6k w - - 0 1"); + assert!( + EnginePosition::fen("x\ny", Vec::::new()) + .validate() + .is_err() + ); + assert!( + EnginePosition::fen("a moves b", Vec::::new()) + .validate() + .is_err() + ); + assert!( + EnginePosition::fen(" ", Vec::::new()) + .validate() + .is_err() + ); + } +} diff --git a/crates/uci/src/worker.rs b/crates/uci/src/worker.rs new file mode 100644 index 0000000..3ce9cc7 --- /dev/null +++ b/crates/uci/src/worker.rs @@ -0,0 +1,434 @@ +//! The engine as a Web Worker (WebAssembly in a browser, which has no processes): +//! the engine's script runs in the worker, a line of UCI is one message each way, +//! and the protocol ([`crate::protocol`]) is driven by the worker's messages and by +//! timers set for its deadlines. Everything happens on the page's thread, so nothing +//! here blocks: the handshake is finished by the worker's messages and its outcome +//! taken by [`Starting::poll`]. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::{Rc, Weak}; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; +use web_time::Instant; + +use crate::error::EngineError; +use crate::events::{EngineEvent, TerminationReason, Waker}; +use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line}; +use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts}; + +#[wasm_bindgen] +extern "C" { + // The global timer functions: a page's and a worker's alike. + #[wasm_bindgen(js_name = setTimeout)] + fn set_timeout(f: &js_sys::Function, ms: f64) -> JsValue; + #[wasm_bindgen(js_name = clearTimeout)] + fn clear_timeout(id: &JsValue); +} + +/// How to start an engine in a worker. +#[derive(Debug, Clone)] +pub struct WorkerConfig { + /// The URL of the engine's worker script. + pub script: String, + pub timeouts: Timeouts, +} + +impl WorkerConfig { + pub fn new(script: impl Into) -> Self { + WorkerConfig { + script: script.into(), + timeouts: Timeouts::default(), + } + } +} + +/// The worker side of the session: the worker itself and the events' queue. +struct Port { + worker: web_sys::Worker, + events: VecDeque, + waker: Waker, +} + +impl Link for Port { + fn write(&mut self, line: &str) -> Result<(), Gone> { + self.worker + .post_message(&JsValue::from_str(line)) + .map_err(|_| Gone) + } + + fn emit(&mut self, ev: EngineEvent) { + self.events.push_back(ev); + (self.waker)(); + } +} + +enum Phase { + Handshake(Handshake), + Running(Session), + Ended, +} + +struct Inner { + port: Port, + phase: Phase, + timeouts: Timeouts, + /// The outcome of the handshake until [`Starting::poll`] takes it. + started: Option>, + /// The timer of the protocol's next deadline. + timer: Option, + /// The worker's handlers and the timer's callback, alive as long as the engine. + callbacks: Vec>, + on_timer: Option>, +} + +impl Inner { + fn deadline(&self) -> Option { + match &self.phase { + Phase::Handshake(h) => Some(h.deadline()), + Phase::Running(s) => s.deadline(), + Phase::Ended => None, + } + } + + /// Sets the timer for the protocol's next deadline (clearing the old one). + fn arm(&mut self) { + if let Some(id) = self.timer.take() { + clear_timeout(&id); + } + let (Some(at), Some(f)) = (self.deadline(), &self.on_timer) else { + return; + }; + let ms = at.saturating_duration_since(Instant::now()).as_secs_f64() * 1000.0; + // A millisecond late rather than early: the deadline must have passed. + self.timer = Some(set_timeout(f.as_ref().unchecked_ref(), ms.ceil() + 1.0)); + } + + fn on_line(&mut self, line: String) { + let now = Instant::now(); + match &mut self.phase { + Phase::Handshake(h) => match h.on_line(line, now) { + HandshakeStep::Continue => {} + HandshakeStep::Write(l) => { + if self.port.write(l).is_err() { + self.fail_start(gone(Vec::new())); + } + } + HandshakeStep::Done(info, warnings) => { + let mut session = Session::new(self.timeouts); + for w in warnings { + session.warn(w, &mut self.port); + } + self.phase = Phase::Running(session); + self.started = Some(Ok(info)); + (self.port.waker)(); + } + }, + Phase::Running(s) => { + if let Err(e) = s.on_line(&line, now, &mut self.port) { + self.end(e); + } + } + Phase::Ended => {} + } + self.arm(); + } + + fn on_cmd(&mut self, cmd: Cmd) -> Result<(), EngineError> { + let Phase::Running(s) = &mut self.phase else { + return Err(EngineError::NotRunning); + }; + if let Err(e) = s.on_cmd(cmd, Instant::now(), &mut self.port) { + self.end(e); + } + self.arm(); + Ok(()) + } + + fn on_timer(&mut self) { + self.timer = None; + let now = Instant::now(); + match &mut self.phase { + Phase::Handshake(h) if now >= h.deadline() => { + let Phase::Handshake(h) = std::mem::replace(&mut self.phase, Phase::Ended) else { + unreachable!("matched above"); + }; + self.port.worker.terminate(); + self.started = Some(Err(h.timed_out())); + (self.port.waker)(); + } + Phase::Running(s) => { + if let Err(e) = s.on_time(now) { + self.end(e); + } + } + Phase::Handshake(_) | Phase::Ended => {} + } + self.arm(); + } + + /// The worker reported an error: its script did not load or the engine failed. + fn on_error(&mut self, message: String) { + match self.phase { + Phase::Handshake(_) => self.fail_start(gone(vec![message])), + Phase::Running(_) => self.end(Exit::Gone), + Phase::Ended => {} + } + self.arm(); + } + + fn fail_start(&mut self, e: EngineError) { + self.port.worker.terminate(); + self.phase = Phase::Ended; + self.started = Some(Err(e)); + (self.port.waker)(); + } + + /// The session ended on its own; the worker is stopped. + fn end(&mut self, exit: Exit) { + self.port.worker.terminate(); + self.phase = Phase::Ended; + let reason = match exit { + Exit::Hung(waiting_for) => TerminationReason::Hung { waiting_for }, + Exit::Gone => TerminationReason::Exited { status: None }, + }; + self.port.emit(EngineEvent::Terminated(reason)); + } + + fn quit(&mut self) { + if let Phase::Running(s) = &mut self.phase { + s.quit(&mut self.port); + self.port.worker.terminate(); + self.phase = Phase::Ended; + self.port + .emit(EngineEvent::Terminated(TerminationReason::Quit { + status: None, + })); + } else { + self.port.worker.terminate(); + self.phase = Phase::Ended; + } + self.arm(); + self.port.worker.set_onmessage(None); + self.port.worker.set_onerror(None); + } +} + +fn gone(stderr: Vec) -> EngineError { + EngineError::ProcessExited { + status: None, + stderr, + } +} + +/// An engine whose handshake is under way. +pub struct Starting { + inner: Option>>, +} + +impl Starting { + /// The engine once its handshake is over (`None`: not yet). After a result it + /// keeps returning `None`. + pub fn poll(&mut self) -> Option> { + let started = self.inner.as_ref()?.borrow_mut().started.take()?; + let inner = self.inner.take()?; + Some(started.map(|info| EngineHandle { info, inner })) + } +} + +impl Drop for Starting { + fn drop(&mut self) { + if let Some(inner) = self.inner.take() { + inner.borrow_mut().quit(); + } + } +} + +/// Namespace for starting engines. +pub struct Engine; + +impl Engine { + /// Starts the engine of `cfg.script` in a new worker, and its handshake. The + /// worker's events wake the UI through `waker`; [`Starting::poll`] gives the + /// engine once it answered `readyok`. + pub fn start_worker(cfg: WorkerConfig, waker: Waker) -> Result { + start(cfg, waker) + } +} + +fn start(cfg: WorkerConfig, waker: Waker) -> Result { + let script_error = |e: JsValue| { + EngineError::Spawn(std::io::Error::other( + e.as_string() + .unwrap_or_else(|| format!("cannot start the worker {}", cfg.script)), + )) + }; + let worker = web_sys::Worker::new(&cfg.script).map_err(script_error)?; + let inner = Rc::new(RefCell::new(Inner { + port: Port { + worker: worker.clone(), + events: VecDeque::new(), + waker, + }, + phase: Phase::Handshake(Handshake::new(&cfg.timeouts, Instant::now())), + timeouts: cfg.timeouts, + started: None, + timer: None, + callbacks: Vec::new(), + on_timer: None, + })); + let weak = Rc::downgrade(&inner); + let with = move |f: &dyn Fn(&mut Inner)| { + if let Some(inner) = Weak::upgrade(&weak) { + f(&mut inner.borrow_mut()); + } + }; + let on_message = { + let with = with.clone(); + Closure::::new(move |ev: JsValue| { + let data = ev.unchecked_into::().data(); + // A message is a line; some builds join several with `\n`. + let text = data.as_string().unwrap_or_default(); + with(&|inner| { + for line in text.lines() { + inner.on_line(line.to_owned()); + } + }); + }) + }; + let on_error = { + let with = with.clone(); + Closure::::new(move |ev: JsValue| { + let message = ev + .dyn_ref::() + .map(web_sys::ErrorEvent::message) + .unwrap_or_else(|| "the engine's worker failed".into()); + with(&|inner| inner.on_error(message.clone())); + }) + }; + let on_timer = Closure::::new(move || with(&|inner| inner.on_timer())); + worker.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + worker.set_onerror(Some(on_error.as_ref().unchecked_ref())); + { + let mut i = inner.borrow_mut(); + i.callbacks = vec![on_message, on_error]; + i.on_timer = Some(on_timer); + if i.port.write(Handshake::FIRST_LINE).is_err() { + i.fail_start(gone(Vec::new())); + } + i.arm(); + } + Ok(Starting { inner: Some(inner) }) +} + +/// Handle owned by the UI. Dropping it quits the engine (its worker is stopped). +pub struct EngineHandle { + info: EngineInfo, + inner: Rc>, +} + +impl std::fmt::Debug for EngineHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EngineHandle") + .field("name", &self.info.name) + .field("alive", &self.is_running()) + .finish() + } +} + +impl EngineHandle { + /// `id name/author` and declared options from the handshake. + pub fn info(&self) -> &EngineInfo { + &self.info + } + + /// `false` after the engine terminated (quit, crash, hung). + pub fn is_running(&self) -> bool { + matches!(self.inner.borrow().phase, Phase::Running(_)) + } + + /// Non-blocking poll for the next event (call every frame). + pub fn try_recv(&self) -> Option { + self.inner.borrow_mut().port.events.pop_front() + } + + /// Drains all currently queued events. + pub fn drain_events(&self) -> impl Iterator + '_ { + std::iter::from_fn(|| self.try_recv()) + } + + /// Infinite analysis (`go infinite`) of `position` under `search_id`. + pub fn analyze( + &self, + position: EnginePosition, + search_id: SearchId, + ) -> Result<(), EngineError> { + self.search(position, search_id, SearchLimits::Infinite) + } + + /// Requests a search: a running search is stopped first and only the latest + /// request is started. + pub fn search( + &self, + position: EnginePosition, + search_id: SearchId, + limits: SearchLimits, + ) -> Result<(), EngineError> { + self.search_among(position, search_id, limits, Vec::new()) + } + + /// A search among these moves only (UCI moves of `position`); empty: all. + pub fn search_among( + &self, + position: EnginePosition, + search_id: SearchId, + limits: SearchLimits, + among: Vec, + ) -> Result<(), EngineError> { + let cmd = Cmd::search(position, search_id, limits, among)?; + self.inner.borrow_mut().on_cmd(cmd) + } + + /// Stops the running search (its `BestMove` still arrives) and cancels a + /// queued one. + pub fn stop(&self) -> Result<(), EngineError> { + self.inner.borrow_mut().on_cmd(Cmd::Stop) + } + + /// `setoption`, checked against the declared options; applied at the next + /// search boundary when a search runs. + pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> { + let line = option_line(&self.info, name, value)?; + self.inner.borrow_mut().on_cmd(Cmd::Setup(line)) + } + + pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { + self.set_option("MultiPV", Some(&lines.to_string())) + } + + pub fn set_threads(&self, threads: u32) -> Result<(), EngineError> { + self.set_option("Threads", Some(&threads.to_string())) + } + + pub fn set_hash_mb(&self, mb: u32) -> Result<(), EngineError> { + self.set_option("Hash", Some(&mb.to_string())) + } + + /// `ucinewgame` (applied at the next idle point, followed by `isready`). + pub fn new_game(&self) -> Result<(), EngineError> { + self.inner + .borrow_mut() + .on_cmd(Cmd::Setup("ucinewgame".into())) + } + + /// Sends `stop`/`quit` and stops the worker at once (a worker needs no grace + /// time: nothing of it outlives `terminate`). + pub fn quit(self) {} +} + +impl Drop for EngineHandle { + fn drop(&mut self) { + self.inner.borrow_mut().quit(); + } +} diff --git a/crates/uci/tests/fake_engine.rs b/crates/uci/tests/fake_engine.rs new file mode 100644 index 0000000..fd39dd8 --- /dev/null +++ b/crates/uci/tests/fake_engine.rs @@ -0,0 +1,751 @@ +//! Supervisor tests against the deterministic fake engine (src/bin/fake_uci.rs). +// The process transport. +#![cfg(not(target_family = "wasm"))] + +use std::collections::{HashMap, HashSet}; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use uci::{ + Engine, EngineConfig, EngineError, EngineEvent, EngineHandle, EnginePosition, OptionKind, + Score, ScoreBound, SearchId, SearchLimits, Side, TerminationReason, Timeouts, WhiteEval, +}; + +const FAKE: &str = env!("CARGO_BIN_EXE_fake_uci"); + +fn timeouts() -> Timeouts { + Timeouts { + uciok: Duration::from_millis(1500), + readyok: Duration::from_millis(1500), + stop: Duration::from_millis(1500), + quit: Duration::from_millis(500), + } +} + +fn config(args: &[&str]) -> EngineConfig { + let mut c = EngineConfig::new(FAKE); + c.args = args.iter().map(Into::into).collect(); + c.timeouts = timeouts(); + c +} + +fn spawn(args: &[&str]) -> EngineHandle { + Engine::spawn_with(config(args), Box::new(|| {})).expect("spawn fake engine") +} + +fn fen(marker: &str) -> EnginePosition { + EnginePosition::fen(format!("{marker} w - - 0 1"), Vec::::new()) +} + +/// Collects events until `pred` matches one (inclusive) or the timeout hits. +fn collect_until( + h: &EngineHandle, + timeout: Duration, + mut pred: impl FnMut(&EngineEvent) -> bool, +) -> (Vec, bool) { + let deadline = Instant::now() + timeout; + let mut out = Vec::new(); + while let Some(ev) = h.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + let hit = pred(&ev); + out.push(ev); + if hit { + return (out, true); + } + } + (out, false) +} + +fn proc_exists(pid: u32) -> bool { + Path::new(&format!("/proc/{pid}")).exists() +} + +fn no_protocol_errors(events: &[EngineEvent]) { + for e in events { + if let EngineEvent::InfoString { text, .. } = e { + assert!(!text.starts_with("ERROR"), "fake engine reported: {text}"); + } + } +} + +#[test] +fn handshake_collects_id_and_typed_options() { + let woke = Arc::new(AtomicUsize::new(0)); + let w = Arc::clone(&woke); + let h = Engine::spawn_with( + config(&["--banner", "--name", "Fake Engine 1.0"]), + Box::new(move || { + w.fetch_add(1, Ordering::SeqCst); + }), + ) + .unwrap(); + let info = h.info(); + assert_eq!(info.name.as_deref(), Some("Fake Engine 1.0")); + assert_eq!(info.author.as_deref(), Some("Test Suite")); + assert_eq!(info.options.len(), 7); + assert_eq!( + info.option("multipv").unwrap().kind, + OptionKind::Spin { + default: 1, + min: Some(1), + max: Some(10) + } + ); + assert_eq!( + info.option("Play Style").unwrap().kind, + OptionKind::Combo { + default: "Normal".into(), + vars: vec!["Solid".into(), "Normal".into(), "Very Risky".into()] + } + ); + assert_eq!(info.option("Clear Hash").unwrap().kind, OptionKind::Button); + assert_eq!( + info.option("Ponder").unwrap().kind, + OptionKind::Check { default: false } + ); + assert!(matches!( + info.option("Debug Log File").unwrap().kind, + OptionKind::String { .. } + )); + h.analyze(fen("m1"), SearchId(1)).unwrap(); + let (_, ok) = collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + assert!(ok); + assert!(woke.load(Ordering::SeqCst) > 0, "waker was not called"); + let pid = h.pid(); + let status = h.quit().expect("reaped"); + assert!(status.success(), "{status:?}"); + assert!(!proc_exists(pid)); +} + +#[test] +fn option_validation() { + let h = spawn(&[]); + assert!(matches!( + h.set_option("NoSuchOption", Some("1")), + Err(EngineError::UnknownOption(_)) + )); + assert!(matches!( + h.set_multipv(11), + Err(EngineError::InvalidOptionValue { .. }) + )); + assert!(h.set_option("Ponder", Some("yes")).is_err()); + assert!(h.set_option("Play Style", Some("Wild")).is_err()); + assert!(h.set_option("Clear Hash", Some("x")).is_err()); + assert!(h.set_option("Debug Log File", Some("a\nquit")).is_err()); + h.set_option("play style", Some("very risky")).unwrap(); + h.set_option("Clear Hash", None).unwrap(); + h.set_threads(2).unwrap(); + h.set_hash_mb(32).unwrap(); + h.set_multipv(3).unwrap(); + h.new_game().unwrap(); +} + +#[test] +fn spawn_errors() { + let tmp = Path::new(env!("CARGO_TARGET_TMPDIR")).join("uci-spawn-errors"); + std::fs::create_dir_all(&tmp).unwrap(); + + let e = Engine::spawn(tmp.join("missing"), Vec::::new(), Box::new(|| {})).unwrap_err(); + assert!(matches!(e, EngineError::NotFound(_)), "{e:?}"); + + let e = Engine::spawn(&tmp, Vec::::new(), Box::new(|| {})).unwrap_err(); + assert!(matches!(e, EngineError::NotExecutable { .. }), "{e:?}"); + + use std::os::unix::fs::PermissionsExt; + let plain = tmp.join("plain.txt"); + std::fs::write(&plain, "not a program\n").unwrap(); + std::fs::set_permissions(&plain, std::fs::Permissions::from_mode(0o644)).unwrap(); + let e = Engine::spawn(&plain, Vec::::new(), Box::new(|| {})).unwrap_err(); + assert!(matches!(e, EngineError::NotExecutable { .. }), "{e:?}"); + + let noexec = tmp.join("garbage.bin"); + std::fs::write(&noexec, [0u8, 1, 2, 3, 4, 5, 6, 7]).unwrap(); + std::fs::set_permissions(&noexec, std::fs::Permissions::from_mode(0o755)).unwrap(); + let e = Engine::spawn(&noexec, Vec::::new(), Box::new(|| {})).unwrap_err(); + assert!(matches!(e, EngineError::NotExecutable { .. }), "{e:?}"); +} + +#[test] +fn not_uci_program() { + let t = Instant::now(); + let e = Engine::spawn_with(config(&["--not-uci"]), Box::new(|| {})).unwrap_err(); + match e { + EngineError::NotUci { output } => { + assert!(output.iter().any(|l| l.contains("not a chess engine"))) + } + other => panic!("{other:?}"), + } + assert!(t.elapsed() < Duration::from_secs(4)); +} + +#[test] +fn missing_uciok_and_readyok_time_out() { + let e = Engine::spawn_with(config(&["--no-uciok"]), Box::new(|| {})).unwrap_err(); + assert!( + matches!( + e, + EngineError::HandshakeTimeout { + waiting_for: "uciok" + } + ), + "{e:?}" + ); + let t = Instant::now(); + let e = Engine::spawn_with(config(&["--no-readyok"]), Box::new(|| {})).unwrap_err(); + assert!( + matches!( + e, + EngineError::HandshakeTimeout { + waiting_for: "readyok" + } + ), + "{e:?}" + ); + assert!(t.elapsed() < Duration::from_secs(4)); +} + +#[test] +fn exit_during_handshake() { + let e = Engine::spawn_with(config(&["--exit-on-start"]), Box::new(|| {})).unwrap_err(); + match e { + EngineError::ProcessExited { status, stderr } => { + assert_eq!(status.and_then(|s| s.code()), Some(3)); + assert!( + stderr.iter().any(|l| l.contains("exiting on start")), + "{stderr:?}" + ); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn stderr_flood_does_not_block() { + let h = spawn(&["--stderr-flood-kb", "2048"]); + h.analyze(fen("m1"), SearchId(1)).unwrap(); + let (_, ok) = collect_until(&h, Duration::from_secs(3), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + assert!(ok); + let tail = h.stderr_tail(); + assert!(!tail.is_empty() && tail.len() <= 256); +} + +#[test] +fn multipv_and_mate_scores() { + let h = spawn(&["--mate"]); + h.set_multipv(3).unwrap(); + h.analyze(EnginePosition::startpos(["e2e4"]), SearchId(7)) + .unwrap(); + let mut seen = HashMap::new(); + let (events, ok) = collect_until(&h, Duration::from_secs(3), |e| { + if let EngineEvent::Info { search_id, info } = e { + assert_eq!(*search_id, SearchId(7)); + seen.insert(info.multipv_index(), info.score.unwrap()); + } + seen.len() == 3 + }); + assert!(ok, "{events:?}"); + assert_eq!(seen[&1].score, Score::Mate(3)); + assert_eq!(seen[&2].score, Score::Mate(-2)); + assert_eq!(seen[&3].score, Score::Cp(20)); + assert_eq!(seen[&1].bound, ScoreBound::Exact); + // After 1.e4 Black is to move: mate 3 for Black. + assert_eq!( + seen[&1].to_white(Side::Black).eval, + WhiteEval::Mate { + winner: Side::Black, + moves: 3 + } + ); + let pv_ok = events.iter().any(|e| match e { + EngineEvent::Info { info, .. } => info.pv.first().map(String::as_str) == Some("e2e4"), + _ => false, + }); + assert!(pv_ok); + no_protocol_errors(&events); +} + +#[test] +fn garbage_lines_become_warnings() { + let h = spawn(&["--garbage"]); + h.analyze(fen("g1"), SearchId(1)).unwrap(); + let mut infos = 0; + let mut warnings = 0; + let (events, _) = collect_until(&h, Duration::from_millis(400), |e| { + match e { + EngineEvent::Info { .. } => infos += 1, + EngineEvent::Warning(_) => warnings += 1, + _ => {} + } + false + }); + assert!(infos > 3, "{events:?}"); + assert!(warnings > 3); + // Warnings are capped. + assert!(warnings <= 100); + assert!(h.is_running()); + no_protocol_errors(&events); +} + +#[test] +fn depth_limited_search_finishes_with_bestmove() { + let h = spawn(&[]); + h.search( + EnginePosition::startpos(["d2d4"]), + SearchId(3), + SearchLimits::Depth(5), + ) + .unwrap(); + let (events, ok) = collect_until(&h, Duration::from_secs(3), |e| { + matches!(e, EngineEvent::BestMove { .. }) + }); + assert!(ok); + match events.last().unwrap() { + EngineEvent::BestMove { + search_id, + best, + ponder, + } => { + assert_eq!(*search_id, SearchId(3)); + assert_eq!(best.as_deref(), Some("d2d4")); + assert_eq!(ponder.as_deref(), Some("e7e5")); + } + _ => unreachable!(), + } + let max_depth = events + .iter() + .filter_map(|e| match e { + EngineEvent::Info { info, .. } => info.depth, + _ => None, + }) + .max(); + assert_eq!(max_depth, Some(5)); +} + +/// Core race: many rapid position changes against an engine that keeps +/// talking after `stop` and even after `bestmove`. Every Info must carry the +/// id of the position it was computed for. +fn rapid_changes(extra: &[&str], n: u64, pause_every: u64) { + let mut args = vec![ + "--stale-after-stop", + "3", + "--info-after-bestmove", + "3", + "--info-interval", + "1", + ]; + args.extend_from_slice(extra); + let h = spawn(&args); + h.set_multipv(2).unwrap(); + for i in 0..n { + let t = Instant::now(); + h.analyze(fen(&format!("m{i}")), SearchId(i)).unwrap(); + assert!(t.elapsed() < Duration::from_millis(50), "analyze blocked"); + if pause_every > 0 && i % pause_every == 0 { + std::thread::sleep(Duration::from_millis(i % 4)); + } + } + let last = SearchId(n - 1); + let (mut events, ok) = collect_until( + &h, + Duration::from_secs(5), + |e| matches!(e, EngineEvent::Info { search_id, .. } if *search_id == last), + ); + assert!(ok, "no info for the last request"); + h.stop().unwrap(); + let (more, ok) = collect_until( + &h, + Duration::from_secs(3), + |e| matches!(e, EngineEvent::BestMove { search_id, .. } if *search_id == last), + ); + assert!(ok); + events.extend(more); + // Let trailing stale output arrive; it must be dropped. + events.extend(collect_until(&h, Duration::from_millis(100), |_| false).0); + + let mut started = Vec::new(); + let mut bestmoves = HashSet::new(); + let mut superseded = HashSet::new(); + let mut infos = 0; + let mut current: Option = None; + for e in &events { + match e { + EngineEvent::SearchStarted { search_id } => { + assert!(current.is_none(), "start before bestmove of {current:?}"); + current = Some(*search_id); + started.push(*search_id); + } + EngineEvent::Info { search_id, info } => { + infos += 1; + assert_eq!(Some(*search_id), current, "info outside its search"); + assert_eq!( + info.pv[0], + format!("m{}", search_id.0), + "info of another position under {search_id:?}" + ); + } + EngineEvent::BestMove { search_id, .. } => { + assert_eq!(Some(*search_id), current); + assert!(bestmoves.insert(*search_id)); + current = None; + } + EngineEvent::Superseded { search_id } => { + assert!(superseded.insert(*search_id)); + } + EngineEvent::Terminated(r) => panic!("terminated: {r:?}"), + EngineEvent::Warning(w) => panic!("warning: {w}"), + EngineEvent::InfoString { .. } => {} + } + } + no_protocol_errors(&events); + assert!(infos > 0); + // Ids are started in increasing order, every started id got its bestmove, + // every id is either started or superseded, never both. + assert!(started.windows(2).all(|w| w[0] < w[1])); + assert_eq!(started.iter().copied().collect::>(), bestmoves); + for i in 0..n { + let id = SearchId(i); + assert!( + bestmoves.contains(&id) ^ superseded.contains(&id), + "{id:?} started={} superseded={}", + bestmoves.contains(&id), + superseded.contains(&id) + ); + } + assert!( + started.len() < n as usize, + "requests were not coalesced ({} started)", + started.len() + ); +} + +#[test] +fn rapid_position_changes_never_mix_search_ids() { + rapid_changes(&[], 200, 0); +} + +#[test] +fn rapid_position_changes_with_pauses_and_slow_bestmove() { + rapid_changes(&["--bestmove-delay", "3"], 60, 5); +} + +#[test] +fn slow_bestmove_within_timeout() { + let h = spawn(&["--bestmove-delay", "300", "--stale-after-stop", "2"]); + h.analyze(fen("a"), SearchId(1)).unwrap(); + collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + let t = Instant::now(); + h.analyze(fen("b"), SearchId(2)).unwrap(); + assert!(t.elapsed() < Duration::from_millis(50)); + let (events, ok) = collect_until(&h, Duration::from_secs(3), |e| { + matches!( + e, + EngineEvent::Info { + search_id: SearchId(2), + .. + } + ) + }); + assert!(ok); + let bm_pos = events + .iter() + .position(|e| { + matches!( + e, + EngineEvent::BestMove { + search_id: SearchId(1), + .. + } + ) + }) + .expect("bestmove of search 1"); + for (i, e) in events.iter().enumerate() { + if let EngineEvent::Info { search_id, info } = e { + let expect = if i < bm_pos { "a" } else { "b" }; + assert_eq!(info.pv[0], expect); + assert_eq!( + *search_id, + if i < bm_pos { SearchId(1) } else { SearchId(2) } + ); + } + } +} + +#[test] +fn options_are_deferred_until_search_ends() { + let h = spawn(&[]); + h.analyze(fen("a"), SearchId(1)).unwrap(); + collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + h.set_multipv(3).unwrap(); + h.new_game().unwrap(); + std::thread::sleep(Duration::from_millis(50)); + h.analyze(fen("b"), SearchId(2)).unwrap(); + let mut max_pv = 0; + let (events, ok) = collect_until(&h, Duration::from_secs(3), |e| { + if let EngineEvent::Info { + search_id: SearchId(2), + info, + } = e + { + max_pv = max_pv.max(info.multipv_index()); + } + max_pv == 3 + }); + assert!(ok, "{events:?}"); + no_protocol_errors(&events); +} + +#[test] +fn hung_engine_is_killed_and_does_not_block_caller() { + let mut cfg = config(&["--never-bestmove"]); + cfg.timeouts.stop = Duration::from_millis(300); + let h = Engine::spawn_with(cfg, Box::new(|| {})).unwrap(); + let pid = h.pid(); + h.analyze(fen("a"), SearchId(1)).unwrap(); + collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + let t = Instant::now(); + for i in 2..50 { + h.analyze(fen("b"), SearchId(i)).unwrap(); + } + assert!(t.elapsed() < Duration::from_millis(50), "caller blocked"); + let (events, ok) = collect_until(&h, Duration::from_secs(3), |e| { + matches!(e, EngineEvent::Terminated(_)) + }); + assert!(ok, "{events:?}"); + assert_eq!( + events.last().unwrap(), + &EngineEvent::Terminated(TerminationReason::Hung { + waiting_for: "bestmove" + }) + ); + assert!(t.elapsed() < Duration::from_secs(2)); + assert!( + !events + .iter() + .any(|e| matches!(e, EngineEvent::SearchStarted { .. })) + ); + assert!(!h.is_running()); + assert!(matches!( + h.analyze(fen("c"), SearchId(99)), + Err(EngineError::NotRunning) + )); + assert!(!proc_exists(pid), "hung process not reaped"); + let t = Instant::now(); + drop(h); + assert!(t.elapsed() < Duration::from_millis(500)); +} + +#[test] +fn crash_during_search_reports_terminated() { + let h = spawn(&["--exit-after-go", "2"]); + let pid = h.pid(); + h.analyze(fen("a"), SearchId(1)).unwrap(); + collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + h.analyze(fen("b"), SearchId(2)).unwrap(); + let (events, ok) = collect_until(&h, Duration::from_secs(3), |e| { + matches!(e, EngineEvent::Terminated(_)) + }); + assert!(ok, "{events:?}"); + match events.last().unwrap() { + EngineEvent::Terminated(TerminationReason::Exited { status }) => { + assert_eq!(status.and_then(|s| s.code()), Some(1)); + } + other => panic!("{other:?}"), + } + assert!(!proc_exists(pid)); + assert!(matches!(h.stop(), Err(EngineError::NotRunning))); +} + +#[test] +fn quit_kills_engine_that_ignores_quit() { + let h = spawn(&["--ignore-quit"]); + let pid = h.pid(); + h.analyze(fen("a"), SearchId(1)).unwrap(); + collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + let t = Instant::now(); + let status = h.quit().expect("reaped"); + assert!(t.elapsed() < Duration::from_secs(2)); + use std::os::unix::process::ExitStatusExt; + assert_eq!(status.signal(), Some(9), "{status:?}"); + assert!(!proc_exists(pid)); +} + +#[test] +fn drop_during_search_terminates_process() { + let h = spawn(&[]); + let pid = h.pid(); + h.analyze(fen("a"), SearchId(1)).unwrap(); + collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + assert!(proc_exists(pid)); + drop(h); + assert!(!proc_exists(pid), "process left behind after drop"); +} + +#[test] +fn stop_cancels_pending_and_idle_stop_is_harmless() { + let h = spawn(&["--bestmove-delay", "100"]); + h.stop().unwrap(); // idle: nothing happens + h.analyze(fen("a"), SearchId(1)).unwrap(); + collect_until(&h, Duration::from_secs(2), |e| { + matches!(e, EngineEvent::Info { .. }) + }); + h.analyze(fen("b"), SearchId(2)).unwrap(); // pending behind stop of #1 + h.stop().unwrap(); // cancels #2 + let (events, _) = collect_until(&h, Duration::from_millis(500), |_| false); + assert!(events.contains(&EngineEvent::Superseded { + search_id: SearchId(2) + })); + assert!(events.iter().any(|e| matches!( + e, + EngineEvent::BestMove { + search_id: SearchId(1), + .. + } + ))); + assert!(!events.iter().any(|e| matches!( + e, + EngineEvent::SearchStarted { + search_id: SearchId(2) + } + ))); + assert!(!events.iter().any(|e| matches!( + e, + EngineEvent::Info { + search_id: SearchId(2), + .. + } + ))); +} + +#[test] +fn invalid_positions_are_rejected_before_sending() { + let h = spawn(&[]); + assert!(matches!( + h.analyze(EnginePosition::startpos(["e2e4", "--"]), SearchId(1)), + Err(EngineError::InvalidInput(_)) + )); + assert!(matches!( + h.analyze(EnginePosition::startpos(["0000"]), SearchId(1)), + Err(EngineError::InvalidInput(_)) + )); + assert!(h.recv_timeout(Duration::from_millis(100)).is_none()); +} + +/// The nice value of a process (field 19 of /proc//stat, after the name). +#[cfg(target_os = "linux")] +fn nice_of(pid: u32) -> i32 { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).expect("stat"); + let after_name = &stat[stat.rfind(')').expect("name") + 2..]; + after_name + .split(' ') + .nth(16) + .expect("nice") + .parse() + .expect("number") +} + +#[cfg(target_os = "linux")] +#[test] +fn an_engine_can_run_below_the_app() { + let ours = nice_of(std::process::id()); + let calm = Engine::spawn_with( + EngineConfig { + nice: 10, + ..config(&[]) + }, + Box::new(|| {}), + ) + .expect("spawn"); + let plain = spawn(&[]); + assert_eq!(nice_of(calm.pid()), (ours + 10).min(19)); + assert_eq!(nice_of(plain.pid()), ours); + calm.quit(); + plain.quit(); +} + +#[cfg(target_os = "linux")] +#[test] +fn an_engine_gets_the_variables_given() { + let engine = Engine::spawn_with( + EngineConfig { + env: vec![("CP_TEST_HOME".into(), "/some/where".into())], + ..config(&[]) + }, + Box::new(|| {}), + ) + .expect("spawn"); + let environ = std::fs::read(format!("/proc/{}/environ", engine.pid())).expect("environ"); + assert!( + environ + .split(|&b| b == 0) + .any(|v| v == b"CP_TEST_HOME=/some/where") + ); + // The app's own environment goes on as well. + assert!(environ.split(|&b| b == 0).any(|v| v.starts_with(b"PATH="))); + engine.quit(); +} + +/// The state letter of process `pid` (`/proc//stat`), `None` when it is gone. +#[cfg(target_os = "linux")] +fn proc_state(pid: u32) -> Option { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + stat.rsplit_once(") ")?.1.chars().next() +} + +/// `kill_with_parent`: the engine dies with the thread that started it (the program +/// quitting while a handshake hangs); without it, it lives on. +#[cfg(target_os = "linux")] +#[test] +fn an_engine_can_die_with_its_starting_thread() { + let start = |kill: bool| { + std::thread::spawn(move || { + let mut c = config(&[]); + c.kill_with_parent = kill; + let handle = Engine::spawn_with(c, Box::new(|| {})).expect("spawn fake engine"); + let pid = handle.pid(); + // Never quit: as if the program ended under it. + std::mem::forget(handle); + pid + }) + .join() + .expect("the thread") + }; + let gone = |pid: u32| { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + match proc_state(pid) { + None | Some('Z') | Some('X') => return true, + _ if Instant::now() > deadline => return false, + _ => std::thread::sleep(Duration::from_millis(20)), + } + } + }; + let killed = start(true); + assert!(gone(killed), "the engine outlived its thread"); + let kept = start(false); + std::thread::sleep(Duration::from_millis(300)); + assert!( + matches!(proc_state(kept), Some('S' | 'R')), + "{:?}", + proc_state(kept) + ); + unsafe { + libc::kill(kept as i32, libc::SIGKILL); + } +} diff --git a/crates/uci/tests/stockfish.rs b/crates/uci/tests/stockfish.rs new file mode 100644 index 0000000..6c334a1 --- /dev/null +++ b/crates/uci/tests/stockfish.rs @@ -0,0 +1,180 @@ +//! Integration test with a real Stockfish binary. Ignored by default. +//! +//! Run: UCI_STOCKFISH=/path/to/stockfish cargo test -p uci --test stockfish -- --ignored +// The process transport. +#![cfg(not(target_family = "wasm"))] + +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +use uci::{ + Engine, EngineEvent, EngineHandle, EnginePosition, Score, SearchId, SearchInfo, SearchLimits, + Side, WhiteEval, +}; + +fn engine() -> EngineHandle { + let path = std::env::var_os("UCI_STOCKFISH").expect("set UCI_STOCKFISH to the binary path"); + Engine::spawn(path, Vec::::new(), Box::new(|| {})).expect("spawn stockfish") +} + +/// Runs a finite search and returns (infos, bestmove). +fn run( + h: &EngineHandle, + pos: EnginePosition, + id: SearchId, + limits: SearchLimits, +) -> (Vec, Option) { + h.search(pos, id, limits).unwrap(); + let deadline = Instant::now() + Duration::from_secs(60); + let mut infos = Vec::new(); + while let Some(ev) = h.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + match ev { + EngineEvent::Info { search_id, info } => { + assert_eq!(search_id, id); + infos.push(info); + } + EngineEvent::BestMove { + search_id, best, .. + } => { + assert_eq!(search_id, id); + return (infos, best); + } + EngineEvent::Terminated(r) => panic!("terminated: {r:?}"), + EngineEvent::Warning(w) => panic!("warning: {w}"), + _ => {} + } + } + panic!("no bestmove"); +} + +#[test] +#[ignore = "needs a real Stockfish binary in UCI_STOCKFISH"] +fn stockfish_multipv_depth_mate_and_position_switch() { + let h = engine(); + let name = h.info().name.clone().unwrap_or_default(); + println!("engine: {name}; options: {}", h.info().options.len()); + assert!(name.starts_with("Stockfish"), "{name}"); + h.set_threads(1).unwrap(); + h.set_hash_mb(16).unwrap(); + h.set_multipv(3).unwrap(); + + // Depth 10, MultiPV 3, Black to move after 1.e4. + let t = Instant::now(); + let (infos, best) = run( + &h, + EnginePosition::startpos(["e2e4"]), + SearchId(1), + SearchLimits::Depth(10), + ); + let mut last: BTreeMap = BTreeMap::new(); + for i in infos.iter().filter(|i| i.depth == Some(10)) { + last.insert(i.multipv_index(), i); + } + assert_eq!(last.keys().copied().collect::>(), vec![1, 2, 3]); + for (k, i) in &last { + let s = i.score.unwrap(); + println!( + "multipv {k}: depth {:?} score {:?} white {:?} nodes {:?} pv {}", + i.depth, + s.score, + s.to_white(Side::Black).eval, + i.nodes, + i.pv.join(" ") + ); + assert!(!i.pv.is_empty()); + assert!(matches!(s.score, Score::Cp(_))); + } + assert!(best.is_some()); + assert_eq!(best.as_deref(), Some(last[&1].pv[0].as_str())); + println!("depth 10 in {:?}, bestmove {best:?}", t.elapsed()); + + // Mate in 1 for White (Rd8#). + h.set_multipv(1).unwrap(); + let (infos, best) = run( + &h, + EnginePosition::fen( + "6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1", + Vec::::new(), + ), + SearchId(2), + SearchLimits::Depth(5), + ); + let s = infos.last().unwrap().score.unwrap(); + assert_eq!(s.score, Score::Mate(1)); + assert_eq!( + s.to_white(Side::White).eval, + WhiteEval::Mate { + winner: Side::White, + moves: 1 + } + ); + assert_eq!(best.as_deref(), Some("d1d8")); + + // Checkmated side to move: no legal moves. + let (infos, best) = run( + &h, + EnginePosition::fen( + "3R2k1/5ppp/8/8/8/8/5PPP/6K1 b - - 1 1", + Vec::::new(), + ), + SearchId(3), + SearchLimits::Depth(5), + ); + println!("mated position infos: {infos:?}, best {best:?}"); + assert_eq!(best, None); + if let Some(s) = infos.last().and_then(|i| i.score) { + assert_eq!(s.score, Score::Mate(0)); + } + + // Infinite analysis with rapid position switches. + h.set_multipv(2).unwrap(); + let positions = [ + vec!["e2e4"], + vec!["e2e4", "e7e5"], + vec!["d2d4"], + vec!["d2d4", "g8f6"], + vec!["c2c4"], + ]; + for (i, moves) in positions.iter().enumerate() { + h.analyze( + EnginePosition::startpos(moves.clone()), + SearchId(10 + i as u64), + ) + .unwrap(); + std::thread::sleep(Duration::from_millis(30)); + } + let last_id = SearchId(10 + positions.len() as u64 - 1); + let deadline = Instant::now() + Duration::from_secs(10); + let mut current = None; + let mut last_infos = 0; + while let Some(ev) = h.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + match ev { + EngineEvent::SearchStarted { search_id } => current = Some(search_id), + EngineEvent::Info { search_id, info } => { + assert_eq!(Some(search_id), current); + // After 1.c4 Black is to move; PV must start with a Black move + // (rank 7/8 origin) - a crude cross-position check. + if search_id == last_id { + let from_rank = info.pv[0].as_bytes()[1]; + assert!(from_rank == b'7' || from_rank == b'8', "{:?}", info.pv); + last_infos += 1; + if last_infos >= 20 { + break; + } + } + } + EngineEvent::BestMove { search_id, .. } => { + assert_eq!(Some(search_id), current); + current = None; + } + EngineEvent::Terminated(r) => panic!("{r:?}"), + _ => {} + } + } + assert!(last_infos >= 20, "too little output for the last position"); + let pid = h.pid(); + let status = h.quit().expect("reaped"); + println!("quit status: {status:?}"); + assert!(status.success()); + assert!(!std::path::Path::new(&format!("/proc/{pid}")).exists()); +} diff --git a/crates/uci/tests/worker.rs b/crates/uci/tests/worker.rs new file mode 100644 index 0000000..078acff --- /dev/null +++ b/crates/uci/tests/worker.rs @@ -0,0 +1,287 @@ +//! The worker transport against a fake engine written in JavaScript, in a browser +//! (`docs/dev/web.md`, «Проверки»: wasm-bindgen-test-runner with headless Firefox). +//! +//! The fake engine answers like `src/bin/fake_uci.rs` in the points that matter +//! here: the first PV move of a search is the marker of its position (the first +//! FEN field), info lines come every few milliseconds until `stop`, and flags make +//! it hang, crash or stay silent. +#![cfg(target_family = "wasm")] + +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::Duration; + +use uci::{ + Engine, EngineError, EngineEvent, EngineHandle, EnginePosition, SearchId, SearchLimits, + Starting, TerminationReason, Timeouts, WorkerConfig, +}; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +wasm_bindgen_test_configure!(run_in_browser); + +const FAKE: &str = r#" +let searching = null, timer = null, marker = 'startpos', n = 0; +const send = (l) => postMessage(l); +function stopSearch() { + if (searching === null) return; + clearInterval(timer); timer = null; + const m = searching; searching = null; + if (FLAGS.hangOnStop) return; + send('info depth 9 score cp 1 pv ' + m); + send('bestmove ' + m); +} +onmessage = (e) => { + const line = String(e.data), w = line.split(' '); + switch (w[0]) { + case 'uci': + if (FLAGS.silent) return; + send('id name Fake Worker'); send('id author Test Suite'); + send('option name MultiPV type spin default 1 min 1 max 10'); + send('option name Hash type spin default 16 min 1 max 1024'); + if (!FLAGS.noUciok) send('uciok'); + break; + case 'isready': if (!FLAGS.noReadyok) send('readyok'); break; + case 'position': + if (w[1] === 'fen') marker = w[2]; + else { const i = w.indexOf('moves'); marker = i > 0 && w.length > i + 1 ? w[w.length - 1] : 'startpos'; } + break; + case 'go': + if (FLAGS.crashOnGo) throw new Error('fake engine crashed'); + searching = marker; n = 0; + if (w[1] === 'nodes') { send('info depth 1 score cp 3 nodes ' + w[2] + ' pv ' + marker); stopSearch(); break; } + timer = setInterval(() => { n++; send('info depth ' + n + ' score cp ' + n + ' pv ' + searching); }, 5); + break; + case 'stop': stopSearch(); break; + case 'quit': close(); break; + } +}; +"#; + +/// A worker script of the fake engine with these flags (a `blob:` URL). +fn fake(flags: &str) -> String { + let source = format!("const FLAGS = {{{flags}}};\n{FAKE}"); + let parts = js_sys::Array::of1(&JsValue::from_str(&source)); + let opts = web_sys::BlobPropertyBag::new(); + opts.set_type("text/javascript"); + let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &opts).unwrap(); + web_sys::Url::create_object_url_with_blob(&blob).unwrap() +} + +fn timeouts() -> Timeouts { + Timeouts { + uciok: Duration::from_millis(1500), + readyok: Duration::from_millis(1500), + stop: Duration::from_millis(500), + quit: Duration::from_millis(500), + } +} + +async fn sleep(ms: i32) { + let promise = js_sys::Promise::new(&mut |resolve, _| { + web_sys::window() + .unwrap() + .set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms) + .unwrap(); + }); + wasm_bindgen_futures::JsFuture::from(promise).await.unwrap(); +} + +/// Starts the fake engine and waits for its handshake; also counts the waker's calls. +async fn start(flags: &str) -> (Result, u32) { + let woke = Arc::new(AtomicU32::new(0)); + let w = Arc::clone(&woke); + let mut config = WorkerConfig::new(fake(flags)); + config.timeouts = timeouts(); + let mut starting: Starting = Engine::start_worker( + config, + Box::new(move || { + w.fetch_add(1, Ordering::Relaxed); + }), + ) + .expect("worker created"); + for _ in 0..400 { + if let Some(r) = starting.poll() { + return (r, woke.load(Ordering::Relaxed)); + } + sleep(10).await; + } + panic!("the handshake neither ended nor timed out"); +} + +/// Events until `pred` holds for one (inclusive), or `ms` pass. +async fn until(h: &EngineHandle, ms: u32, pred: impl Fn(&EngineEvent) -> bool) -> Vec { + let mut out = Vec::new(); + for _ in 0..ms / 5 { + while let Some(ev) = h.try_recv() { + let hit = pred(&ev); + out.push(ev); + if hit { + return out; + } + } + sleep(5).await; + } + panic!("no expected event in {ms} ms: {out:?}"); +} + +fn fen(marker: &str) -> EnginePosition { + EnginePosition::fen(format!("{marker} w - - 0 1"), Vec::::new()) +} + +#[wasm_bindgen_test] +async fn handshake_then_analysis_and_stop() { + let (h, woke) = start("").await; + let h = h.expect("started"); + assert_eq!(h.info().name.as_deref(), Some("Fake Worker")); + assert_eq!(h.info().options.len(), 2); + assert!(woke > 0, "the waker was not called"); + h.set_multipv(2).unwrap(); + assert!(matches!( + h.set_multipv(11), + Err(EngineError::InvalidOptionValue { .. }) + )); + h.analyze(fen("m1"), SearchId(1)).unwrap(); + let evs = until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; + assert!(evs.contains(&EngineEvent::SearchStarted { + search_id: SearchId(1) + })); + h.stop().unwrap(); + let evs = until(&h, 2000, |e| matches!(e, EngineEvent::BestMove { .. })).await; + match evs.last() { + Some(EngineEvent::BestMove { + search_id, best, .. + }) => { + assert_eq!(*search_id, SearchId(1)); + assert_eq!(best.as_deref(), Some("m1")); + } + other => panic!("{other:?}"), + } + assert!(h.is_running()); +} + +#[wasm_bindgen_test] +async fn rapid_requests_start_only_the_latest_and_never_mix_output() { + let (h, _) = start("").await; + let h = h.expect("started"); + h.analyze(fen("a"), SearchId(1)).unwrap(); + until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; + for (id, m) in [(2, "b"), (3, "c"), (4, "d")] { + h.analyze(fen(m), SearchId(id)).unwrap(); + } + let evs = until(&h, 3000, |e| { + matches!( + e, + EngineEvent::Info { + search_id: SearchId(4), + .. + } + ) + }) + .await; + for id in [2, 3] { + assert!(evs.contains(&EngineEvent::Superseded { + search_id: SearchId(id) + })); + assert!(!evs.contains(&EngineEvent::SearchStarted { + search_id: SearchId(id) + })); + } + for e in &evs { + if let EngineEvent::Info { search_id, info } = e { + let want = if *search_id == SearchId(1) { "a" } else { "d" }; + assert_eq!(info.pv.first().map(String::as_str), Some(want), "{e:?}"); + } + } + // A node-limited search ends by itself. + h.search(fen("n"), SearchId(5), SearchLimits::Nodes(1000)) + .unwrap(); + let evs = until(&h, 2000, |e| { + matches!( + e, + EngineEvent::BestMove { + search_id: SearchId(5), + .. + } + ) + }) + .await; + assert!(matches!(evs.last(), Some(EngineEvent::BestMove { best: Some(b), .. }) if b == "n")); +} + +#[wasm_bindgen_test] +async fn an_engine_hung_on_stop_is_terminated() { + let (h, _) = start("hangOnStop: true").await; + let h = h.expect("started"); + h.analyze(fen("h"), SearchId(1)).unwrap(); + until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; + h.stop().unwrap(); + let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await; + assert_eq!( + evs.last(), + Some(&EngineEvent::Terminated(TerminationReason::Hung { + waiting_for: "bestmove" + })) + ); + assert!(!h.is_running()); + assert!(matches!(h.stop(), Err(EngineError::NotRunning))); +} + +#[wasm_bindgen_test] +async fn a_crash_ends_the_session() { + let (h, _) = start("crashOnGo: true").await; + let h = h.expect("started"); + h.analyze(fen("x"), SearchId(1)).unwrap(); + let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await; + assert_eq!( + evs.last(), + Some(&EngineEvent::Terminated(TerminationReason::Exited { + status: None + })) + ); +} + +#[wasm_bindgen_test] +async fn handshake_failures_are_named() { + let (silent, _) = start("silent: true").await; + assert!( + matches!(silent, Err(EngineError::NotUci { .. })), + "{silent:?}" + ); + let (no_uciok, _) = start("noUciok: true").await; + assert!( + matches!( + no_uciok, + Err(EngineError::HandshakeTimeout { + waiting_for: "uciok" + }) + ), + "{no_uciok:?}" + ); + let (no_readyok, _) = start("noReadyok: true").await; + assert!( + matches!( + no_readyok, + Err(EngineError::HandshakeTimeout { + waiting_for: "readyok" + }) + ), + "{no_readyok:?}" + ); + // A script that does not load. + let mut config = WorkerConfig::new("/no-such-engine.js"); + config.timeouts = timeouts(); + let mut starting = Engine::start_worker(config, Box::new(|| {})).expect("worker created"); + let mut result = None; + for _ in 0..400 { + result = starting.poll(); + if result.is_some() { + break; + } + sleep(10).await; + } + assert!( + matches!(result, Some(Err(EngineError::ProcessExited { .. }))), + "{result:?}" + ); +} diff --git a/docs/agent-team.md b/docs/agent-team.md new file mode 100644 index 0000000..27bc065 --- /dev/null +++ b/docs/agent-team.md @@ -0,0 +1,52 @@ +# Команда OpenCode + +Создано 2026-10-17. Формат проверен по документации OpenCode V2, уÑ�тановленнаÑ� верÑ�иÑ� — `v2.0.32`. + +## ПоÑ�тоÑ�нные профили + +| ID | Режим | ОтветÑ�твенноÑ�ть | +| --- | --- | --- | +| `orchestrator` | primary | План, делегирование, Ñ�оглаÑ�ование, интеграциÑ� и актуальнаÑ� Ñ�водка | +| `analyst` | subagent | ТребованиÑ�, иÑ�Ñ�ледование реальных PGN, критерии приёмки | +| `designer` | subagent | UX, визуальнаÑ� Ñ�иÑ�тема, нотациÑ�, варианты, клавиатура и Ñ�оÑ�тоÑ�ниÑ� | +| `developer` | subagent | Rust, модель документа, PGN, хранение, UCI, desktop UI | +| `tester` | subagent | Ð�езавиÑ�имаÑ� проверка данных, движков, интерфейÑ�а и регреÑ�Ñ�ий | + +ОпределениÑ� находÑ�Ñ‚Ñ�Ñ� в `.opencode/agents/*.md`. Модели не закреплены: дочерние агенты наÑ�ледуют модель оÑ�новной Ñ�еÑ�Ñ�ии. ДлÑ� дизайнера и разработчика подготовлены Ñ�пециализированные инÑ�трукции в Ñ�амих профилÑ�Ñ…; Ñ�торонние skills не уÑ�танавливалиÑ�ÑŒ. + +`opencode.jsonc` задаёт `orchestrator` как агента по умолчанию длÑ� новых Ñ�еÑ�Ñ�ий. Это не переключает уже Ñ�ущеÑ�твующую Ñ�еÑ�Ñ�ию автоматичеÑ�ки. + +## ФактичеÑ�каÑ� проверка региÑ�трации + +Команда: + +```sh +opencode api get '/api/agent?location[directory]=/home/vrubel/services/chessBaseLinux' +``` + +Вернула вÑ�е пÑ�ть профилей Ñ� ожидаемыми режимами. ДлÑ� их обнаружениÑ� перезапуÑ�к Ñ�ервиÑ�а не потребовалÑ�Ñ�. ТекущаÑ� рабочаÑ� Ñ�еÑ�Ñ�иÑ� продолжает координацию иÑ�Ñ�ледований; первоначальные четыре параллельных иÑ�Ñ�ледованиÑ� запущены через `general` Ñ� отдельными заданиÑ�ми аналитика, дизайнера, разработчика и теÑ�тировщика. + +## Рабочий цикл + +1. ОркеÑ�тратор читает `docs/decisions.md`, определÑ�ет ближайший проверÑ�емый результат и назначает облаÑ�ти файлов. +2. Ð�налитик уточнÑ�ет критерии; дизайнер опиÑ�ывает затрагиваемый Ñ�ценарий. +3. Разработчик реализует небольшой Ñ�квозной шаг поÑ�ле Ñ�оглаÑ�ованиÑ�. +4. ТеÑ�тировщик проверÑ�ет незавиÑ�имо, Ñ�ообщает воÑ�произведение дефектов и непроверенные облаÑ�ти. +5. ОркеÑ�тратор интегрирует результаты, фикÑ�ирует решениÑ� и Ñ�ообщает пользователю фактичеÑ�кое Ñ�оÑ�тоÑ�ние. + +Параллельно выполнÑ�ть только задачи, которые не перезапиÑ�ывают одни и те же файлы. ИÑ�Ñ�ледованиÑ� — аргументы длÑ� решениÑ�, а не автоматичеÑ�кое утверждение вÑ�его перечиÑ�ленного объёма. + +ИÑ�точники: +- https://opencode.ai/v2/docs/agents +- https://opencode.ai/v2/docs/config +- https://opencode.ai/v2/docs/api + +## Добавлено 2026-11-01 — запуÑ�к в Kimi Code CLI + +Разработка продолжаетÑ�Ñ� в Kimi Code CLI. OpenCode в окружении Ñ�ейчаÑ� не уÑ�тановлен (`opencode` отÑ�утÑ�твует в PATH), поÑ�тому повторнаÑ� проверка региÑ�трации профилей через API не выполнÑ�лаÑ�ÑŒ; файлы оÑ�таютÑ�Ñ� на меÑ�те и пригодны длÑ� возврата в OpenCode. + +Профили `.opencode/agents/*.md` оÑ�таютÑ�Ñ� каноничеÑ�кими определениÑ�ми ролей длÑ� обеих Ñ�ред; их Ñ�одержимое нейтрально к Ñ�реде иÑ�полнениÑ� (упоминаниÑ� OpenCode в профиле оркеÑ�тратора отноÑ�Ñ�Ñ‚Ñ�Ñ� только к запуÑ�ку внутри OpenCode). Ð’ Kimi Code профили не региÑ�трируютÑ�Ñ�: оркеÑ�тратор (оÑ�новнаÑ� Ñ�еÑ�Ñ�иÑ�) передаёт роль Ñ�убагенту через задание Ñ�о Ñ�Ñ�ылкой на файл профилÑ�. СоответÑ�твие ролей типам Ñ�убагентов (`coder`, `plan`, `explore`) и правила делегированиÑ� зафикÑ�ированы в `AGENTS.md`, раздел «Команда». + +Следы Claude Code: каталог `.claude/` профилей агентов не Ñ�одержит — там только `settings.local.json` (разрешениÑ�) и ворктри `.claude/worktrees/agent-a635674bcaa3af196` Ñ� Ñ�еÑ�Ñ�ии агента. Командные профили хранÑ�Ñ‚Ñ�Ñ� иÑ�ключительно в `.opencode/agents/`; дублировать их под `.claude/` или `.kimi/` не нужно. + +2026-11-01 профили ролей уÑ�илены по требованию владельца: единые правила доказательноÑ�ти (факт/гипотеза/предложение), обÑ�зательный формат отчёта, жёÑ�ткие предметные инварианты и ворота качеÑ�тва в профилÑ�Ñ… разработчика и теÑ�тировщика. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..7c47908 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,118 @@ +# Ð�рхитектура ChessPenguin + +СтатуÑ�: опиÑ�ание реализованной Ñ�иÑ�темы длÑ� выпуÑ�ка **2.5.2**, обновлено 2026-11-30. Тренажёр дебютов включён в наÑ�тольное приложение Ñ� пометкой α. +Первоначальный документ Ñ� Ñ�тим именем — архитектурное предложение Ñ�тапа иÑ�Ñ�ледованиÑ� +(2026-10-17) — Ñ�охранён в `docs/research/architecture-proposal-2026-10-17.md`. + +ChessPenguin — локальнаÑ� шахматнаÑ� база и анализ: PGN и ChessBase (`.cbh`/`.cbv`, архивы +zip/7z), проÑ�мотр и ввод партий Ñ� вариантами и комментариÑ�ми, анализ UCI-движками, +обзор партии, подготовка к Ñ�опернику, игра Ñ� компьютером (Maia, Rodent), онлайн-партии +Lichess/Chess.com. Платформы: Linux (оÑ�новнаÑ�), Windows, macOS, Android; веб-верÑ�иÑ� — +Ñ�тап 2 на ветке `web-app` (`docs/dev/web.md`, задача 22). + +## СоÑ�тав workspace + +Cargo workspace, edition 2024, rust-version 1.97, GPL-3.0-or-later. +Ключевые завиÑ�имоÑ�ти: shakmaty 0.30 (правила, SAN/FEN), egui/eframe 0.36 (wgpu, +Wayland/X11, AccessKit), encoding_rs, serde. Полный Ñ�пиÑ�ок — `Cargo.toml` + `Cargo.lock`. + +| ЧаÑ�ть | Ð�азначение | ПодробноÑ�ти | +| --- | --- | --- | +| `crates/chess-core` | Документ партии: арена узлов Ñ�о Ñ�табильными `NodeId`, Ñ�обÑ�твенный байтовый PGN-лекÑ�ер и writer, кодировки, диагноÑ�тика, терпимоÑ�ть к повреждённым данным | `docs/dev/chess-core.md` | +| `crates/chess-import` | Ð’Ñ�Ñ‘, что не проÑ�той PGN: ChessBase `.cbh`/`.cbv`, архивы; большие базы читаютÑ�Ñ� на меÑ�те; фильтры/Ñ�ортировка каталога; поиÑ�к по позиции (уÑ�коритель `.cbb`, Ñ�вой буÑ�тер, дебютный индекÑ�, таблица позиций PGN) | `docs/dev/import.md` | +| `crates/uci` | Протокол UCI как чиÑ�тый автомат без ввода-вывода; транÑ�порты: процеÑ�Ñ� (деÑ�ктоп) и Web Worker (браузер) | `docs/dev/uci.md` | +| `crates/game-review` | Обзор партии целиком в фоне: задание, отчёт, график, кÑ�ш; детерминированные оценки (`go nodes`, Ñ�верка Ñ�о Stockfish 19), метки !/!!, калиброванные на разметке chess.com | — | +| `crates/prep` | Подготовка к Ñ�опернику: дерево его дебютов, периоды (по давноÑ�ти/чиÑ�лу партий), Ñ�охранённые подготовки, поиÑ�к ошибок движком | — | +| `crates/openings` | Ð�азваниÑ� дебютов (ECO) | — | +| `crates/online-games` | API Lichess и Chess.com: проба, поиÑ�к ника, Ñ�качивание в PGN-базу Ñ� возобновлением | — | +| `crates/play` | Игра Ñ� компьютером: Rodent IV/V, личноÑ�ти, книги, чаÑ�Ñ‹, предложение ничьей | — | +| `crates/maia` | Ð�ейроÑ�етевой Ñ�оперник Maia: веÑ�а, checkpoint, шкала Ñ�илы | — | +| `crates/trainer` | Дебютные репертуары: PGN-дерево, граф транÑ�позиций, общий LearningItem, незавиÑ�имые попытки, SRS, Ñ�еÑ�Ñ�ии, аналитика и versioned JSON; Android Ñ�охранÑ�ет legacy API | `docs/design/repertoire-training.md` | +| `crates/releases` | Данные выпуÑ�ков длÑ� обновлениÑ� | — | +| `crates/mobile-api` | Общий API Android: Ñ�еÑ�Ñ�иÑ� партии, движок, обзор, игра, тренировка, обновлениÑ� | — | +| `apps/desktop` | Приложение: библиотека `chesspenguin_app` (веÑ�ÑŒ интерфейÑ�, ~модули в `src/`) + тонкий `main.rs`; i18n на 6 Ñ�зыков | `docs/dev/desktop.md` | +| `apps/web` | Та же библиотека в WebAssembly: `start(canvas)` → `start_web`; платформенный Ñ�лой браузера | `docs/dev/web.md` | +| `androidApp` | Kotlin-оболочка (Gradle, Rust через `mobile-api`) | `androidApp/` | +| `website` | Сайт продукта, отдельный деплой | `website/README.md` | + +## Слои и потоки данных + +```text +desktop (egui, apps/desktop) │ web (wasm, apps/web) │ android (Kotlin + mobile-api) + │ одна библиотека chesspenguin_app │ │ общие крейты через mobile-api + â–¼ â–¼ + platform (native │ web) — каталоги, файлы, фон, диалоги, clipboard + â–¼ + приложение: LibraryState, GameView (документ + Undo/Redo), AnalysisPreview, + UCI-контроллер, обзор, подготовка, игра, онлайн, обновление + â–¼ + crates: chess-core │ chess-import │ uci │ game-review │ prep │ play │ maia │ … +``` + +- **UI не блокируетÑ�Ñ�**: открытие/Ñ�канирование баз, импорт, поиÑ�к по позиции, обзор + партии и перевод работают в фоне Ñ� прогреÑ�Ñ�ом и отменой; результаты возвращаютÑ�Ñ� + Ñ�обытиÑ�ми, UI опрашивает их каждый кадр (`Waker` → `request_repaint`). +- **Документ**: арена узлов, Ñ�табильные идентификаторы, один шаг Undo на операцию. + ИÑ�ходные байты PGN неизменны; запиÑ�ÑŒ только Ñ�внаÑ� («Сохранить как…», Ñ�вои базы). +- **Ð�нализ привÑ�зан к иÑ�тории позиции** (`EngineHistory`: Ñ�тартоваÑ� позициÑ� + ходы UCI), + не к FEN и не к курÑ�ору; Ñ�обытиÑ� Ñ� чужым `SearchId` отбраÑ�ываютÑ�Ñ�. ПредпроÑ�мотр PV — + Ñ�нимок линии, документ менÑ�ет только «Добавить как вариант» (один шаг Undo). +- **UCI**: граница поиÑ�ков — `bestmove`, затем обÑ�зательный `isready`/`readyok`, и + только потом новый `position`/`go`; опции во времÑ� поиÑ�ка откладываютÑ�Ñ�. ПроцеÑ�Ñ� — + дочерний, без shell, Ñ� таймаутами, kill при `Drop`, stderr ограничен. +- **Импорт**: вÑ�Ñ‘ не-PGN приводитÑ�Ñ� к `PgnDatabase` (малые базы — конвертациÑ� в памÑ�ти) + или читаетÑ�Ñ� на меÑ�те (`Base` длÑ� больших ChessBase); дальше единый путь: библиотека, + нотациÑ�, анализ, Ñ�кÑ�порт в PGN. +- **ИндекÑ�Ñ‹**: уÑ�корители позиции и дебютный индекÑ� — в кÑ�ше приложениÑ� (`boosters/`, + `.cpo` от каноничеÑ�кого пути/размера/даты `.cbg`); атомарнаÑ� запиÑ�ÑŒ, + непригодный файл переÑ�траиваетÑ�Ñ�. Таблица позиций PGN Ñ�троитÑ�Ñ� в памÑ�ти. +- **Обучение дебютов**: PGN-дерево отделено от знаниÑ� хода. Ключ LearningItem — + `(profile, FEN4, expected UCI)`, поÑ�тому транÑ�позиции и одинаковые ходы из разных + репертуаров иÑ�пользуют общую иÑ�торию. Попытка, SRS-раÑ�пиÑ�ание и snapshot Ñ�еÑ�Ñ�ии + Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ� атомарно в фоновом worker; UI получает результат через канал и не принимает + повторный ответ до завершениÑ� запиÑ�и. `client_attempt_id` иÑ�ключает дубли, revision обнаруживает + конфликт одновременных Ñ�еÑ�Ñ�ий. ИÑ�торичеÑ�кие Ñ�нимки не переÑ�читываютÑ�Ñ� задним чиÑ�лом. + Ð�грегаты и подготовка Ñ�еÑ�Ñ�ии выполнÑ�ÑŽÑ‚Ñ�Ñ� вне UI-потока. + +## Ключевые решениÑ� + +Живой журнал — `docs/decisions.md`. Опоры архитектуры: + +1. egui/eframe 0.36 + wgpu; одна кодоваÑ� база интерфейÑ�а длÑ� деÑ�ктопа и веба + (библиотека + platform-Ñ�лой), Android — общие крейты через `mobile-api`. +2. СобÑ�твенный байтовый PGN-лекÑ�ер: pgn-reader молча пропуÑ�кает токены и не даёт + Ñ�мещений (запиÑ�ÑŒ â„–335), поÑ�тому он — лишь незавиÑ�имый Ñ�талон в теÑ�тах. +3. ТерпимоÑ�ть к реальным данным: legacy-кодировки, FEN fullmove=0, `--`, повреждённые + комментарии — вÑ�Ñ‘ Ñ�охранÑ�етÑ�Ñ� и диагноÑ�тируетÑ�Ñ�, оригинал доÑ�тупен (`raw_text`). +4. UCI — Ñ�вный автомат без ввода-вывода; транÑ�порт подменÑ�ем (процеÑ�Ñ�/воркер). +5. Обзор партии детерминирован: тот же движок-Ñ�талон (`go nodes` + Ñ�верка Stockfish 19), + одинаковые метки на вÑ�ех машинах; запиÑ�ÑŒ результата в партию — один шаг Undo. +6. Файл не перезапиÑ�ываетÑ�Ñ� неÑ�вно: запиÑ�ÑŒ в Ñ�вои базы — append/replace/remove Ñ� + проверкой, что файл Ñ� диÑ�ка не изменилÑ�Ñ�. + +## Проверка качеÑ�тва + +- `cargo test -p `: unit + fixtures; корпуÑ�ные теÑ�ты на `pgnFilesforExample/` + пропуÑ�каютÑ�Ñ� без файлов; теÑ�ты на Mega помечены `#[ignore]`. +- UCI-гонки — Ñ� детерминированным `fake_uci`; реальный Stockfish — только + интеграционный `#[ignore]`. +- РучнаÑ� проверка UI — dev-хуками `CP_*` (Ñ�нимки в `docs/screenshots/`), + `chesspenguin --bench <база>` — замеры на чужих машинах. +- Ð�езавиÑ�имые QA-проходы — `docs/qa/`; продуктовые проверки теÑ�тировщиком — + по ролевому профилю `.opencode/agents/tester.md`. + +## Ð�ктуальноÑ�ть и границы + +- Реализовано и выпущено: библиотека PGN/ChessBase, нотациÑ� Ñ� редактированием, + анализ и обзор партии, подготовка к Ñ�опернику, игра (Maia/Rodent), онлайн-партии, + Ñ�вои базы, перевод комментариев, автоматичеÑ�кое обновление. ИÑ�ториÑ� — `CHANGELOG.md`. +- Desktop-тренажёр дебютов (α): Ñ� 2.4.0 — упрощённый UI (`repertoire_ui.rs`, `opening_session.rs`, + `opening_lines.rs`, `opening_layout.rs`) поверх Ñ�дра `crates/trainer/src/repertoire`: общаÑ� SRS-модель + по `(профиль, FEN4, UCI)`, дневное занÑ�тие (к повторению + до 10 новых), «Повторить вÑ�Ñ‘ подрÑ�д», + тренировка ветки; режимы, параметры контекÑ�та и дашборд из UI удалены, формат хранениÑ� не менÑ�лÑ�Ñ�. + Android продолжает иÑ�пользовать прежний линейный + тренер и Ñ�овмеÑ�тимые legacy-данные; web-верÑ�иÑ� Ñ�тот Ñ�кран не получает. +- Очередь и идеи — `docs/dev/tasks.md`; переноÑ� на другую машину — `docs/dev/handoff.md`. +- Ð�е реализовано: веб-верÑ�иÑ� в проде (Ñ�тап 2), тренировочные файлы (задача 23), + автоматичеÑ�кий Ñ�бор дебютного репертуара из большой базы (задача 36), Ñ�инхронизациÑ�, + движковаÑ� оценка запоминаниÑ� и Ñ�оревнованиÑ� из V2 тренажёра. diff --git a/docs/chesstempo_opening_trainer_TZ.md b/docs/chesstempo_opening_trainer_TZ.md new file mode 100644 index 0000000..618252e --- /dev/null +++ b/docs/chesstempo_opening_trainer_TZ.md @@ -0,0 +1,945 @@ +# ТехничеÑ�кое задание: тренажёр изучениÑ� шахматных дебютов по принципам ChessTempo + +**ВерÑ�иÑ�:** 2.0 +**Дата иÑ�Ñ�ледованиÑ�:** 04.11.2026 +**РеференÑ�:** ChessTempo Opening Training +**Тип документа:** функциональное ТЗ + Ñ�пецификациÑ� алгоритма обучениÑ� + Ñ�пецификациÑ� Ñ�татиÑ�тики +**Язык интерфейÑ�а:** руÑ�Ñ�кий (внутренние идентификаторы могут быть английÑ�кими) + +> **Граница доÑ�товерноÑ�ти.** ИÑ�Ñ�ледованы публичный Ñ�айт ChessTempo, [официальное руководÑ�тво](https://www.chesstempo.com/manual/en/manual.html), [FAQ](https://www.chesstempo.com/faq/) и ответы разработчика Richard на форуме. Ð�вторизованнаÑ� тренировка Ñ� реальными пользовательÑ�кими данными не проходилаÑ�ÑŒ; иÑ�ходный код Ñ�ерверного алгоритма не доÑ�тупен. ПоÑ�тому документ **не утверждает**, что предложенные внутренние Ñ�хемы, формулы длÑ� неопубликованных деталей и SQL-реализациÑ� точно Ñ�овпадают Ñ� ChessTempo. +> +> ОбозначениÑ�: **[ПОДТВЕРЖДЕÐ�О]** — Ñ�вно опиÑ�ано в официальном руководÑ�тве; **[РÐ�ЗРÐ�БОТЧИК]** — подтверждено ответом разработчика на форуме; **[ПРОЕКТ]** — предлагаемый длÑ� реализации точный алгоритм; **[Ð�ЕИЗВЕСТÐ�О]** — публичного определениÑ� не найдено. Ð�аличие [ПРОЕКТ] не означает, что функциÑ� Ñ�ущеÑ�твует в оригинале. + +--- + +## 1. Цель и границы продукта + +Ð�еобходимо реализовать модуль, который помогает пользователю Ñ�оздавать дебютные репертуары, изучать **Ñ�вои ходы в конкретных шахматных позициÑ�Ñ…**, Ñ�иÑ�тематичеÑ�ки повторÑ�ть забываемые ответы и видеть доÑ�товерную Ñ�татиÑ�тику изученноÑ�ти репертуара, отдельных веток и ходов. + +Главный принцип: **изучаетÑ�Ñ� не файл PGN и не дебютное название, а запоминание правильного хода в определённой позиции**. Полные варианты нужны как контекÑ�Ñ‚. ЕÑ�ли разными порÑ�дками ходов получена та же позициÑ�, иÑ�ториÑ� знаниÑ� иÑ�пользуетÑ�Ñ� Ñ�овмеÑ�тно. + +ОбÑ�зательные модули: + +1. Репертуары за белых и чёрных; дерево вариантов; импорт/Ñ�кÑ�порт PGN. +2. ПредÑ�тавление шахматного материала графом позиций Ñ� транÑ�позициÑ�ми. +3. Тренировка за выбранную Ñ�торону, автоматичеÑ�кие ходы Ñ�оперника. +4. ПерÑ�ональнаÑ� иÑ�ториÑ� проверок и интервальное повторение (SRS). +5. КонтекÑ�тные ходы, подÑ�казки, работа Ñ� ошибками. +6. Три режима тренировки и четыре алгоритма введениÑ� новых ходов. +7. ПодробнаÑ� Ñ�татиÑ�тика: Ñ�татуÑ�, изученноÑ�ть, проÑ�роченные повторениÑ�, точноÑ�ть, иÑ�ториÑ�, динамика, проблемные ходы. +8. Прозрачные формулы процента изучениÑ� и Ñ�татуÑ�а *«репертуар изучен»* (предложеннаÑ� продуктоваÑ� надÑ�тройка над механикой ChessTempo). + +Вне базового MVP: Ñ�обÑ�твеннаÑ� база гроÑ�Ñ�мейÑ�терÑ�ких партий, клаÑ�терное обучение, рейтинг игрока по дебютам, оценка движком качеÑ�тва запоминаниÑ�, рекомендательнаÑ� Ñ�иÑ�тема на базе ИИ. + +## 2. Что дейÑ�твительно означает «дебют изучен» в ChessTempo + +### 2.1. Ð’ оригинале изучаетÑ�Ñ� отдельный ход, а не дебют целиком + +**[РÐ�ЗРÐ�БОТЧИК]** Ход получает Ñ�татуÑ� **Learnt** поÑ�ле **трёх или более правильных Ñ�амоÑ�тоÑ�тельных ответов подрÑ�д**. ЕÑ�ли пользователь ошибÑ�Ñ�, ход Ñ�нова Ñ�читаетÑ�Ñ� **Learning**. ИÑ�точник: [форум, ответ Richard в теме «Opening training no more positions to schedule yet?»](https://chesstempo.com/forum/topic/opening-training-no-more-positions-to-schedule-yet/9962/). + +**[РÐ�ЗРÐ�БОТЧИК]** С точки зрениÑ� планировщика еÑ�ть две оÑ�новополагающие группы: **Unseen** (ещё не введён в обучение) и **Learning** в широком Ñ�мыÑ�ле (уже находитÑ�Ñ� в Ñ�иÑ�теме повторений). Метки *Learnt* и *Uncertain* — Ñ�то **производные категории длÑ� показа Ñ�татиÑ�тики**. Они не Ñ�влÑ�ÑŽÑ‚Ñ�Ñ� отдельными алгоритмами планированиÑ�. + +**[ПОДТВЕРЖДЕÐ�О]** Сайт показывает чиÑ�ло изучаемых ходов, чиÑ�ло изученных ходов, общее чиÑ�ло ходов и чиÑ�ло `Uncertain`; в интерфейÑ�е вÑ�тречаетÑ�Ñ� вид `Learnt: 2/47` и `Learning: 4`. ИÑ�точники: [руководÑ�тво, раздел 10.5](https://www.chesstempo.com/manual/en/manual.html#repertoirestats), [форум Ñ� разбором Ñ�татиÑ�тики](https://chesstempo.com/forum/topic/trying-to-understand-how-opening-training-works-with-the-scheduling-option/10924/). + +**Вывод:** у ChessTempo нет подтверждённого отдельного глобального флага `whole_opening_mastered=true`, который можно припиÑ�ать вÑ�ему дебюту. ВмеÑ�то Ñ�того отображаютÑ�Ñ� результаты изучениÑ� Ñ�оÑ�тавлÑ�ющих его ходов. Требование «дебют изучен / не изучен» нужно формализовать Ñ�амоÑ�тоÑ�тельно (§ 5). + +### 2.2. Четыре отображаемых Ñ�татуÑ�а + +| СтатуÑ� | Значение | Как поÑ�влÑ�етÑ�Ñ� | +|---|---|---| +| **Unseen** | ЕÑ�ть в репертуаре, ещё не введён в Ñ�иÑ�тему повторениÑ� | При импорте/добавлении нового обучаемого хода | +| **Learning** | Введён в обучение, но не доÑ�тиг порога закреплениÑ� | ПоÑ�ле первой проверки или поÑ�ле ошибки | +| **Learnt** | ПоÑ�ледние 3 и более Ñ�амоÑ�тоÑ�тельных ответа правильны | При доÑ�тижении `correct_streak >= 3` | +| **Uncertain** | Ранее был Learnt, но его проверка Ñ�лишком давно проÑ�рочена | СтановитÑ�Ñ� «Ñ�омнительно закреплённым» Ñ�о временем без новой попытки | + +УточнениÑ�: + +- `Uncertain` — **подмножеÑ�тво ранее изученных (`Learnt`)**, а не дополнительное количеÑ�тво незавиÑ�имых ходов. Ð’ публичном объÑ�Ñ�нении Ñ�то категориÑ� ходов, которые удовлетворÑ�ÑŽÑ‚ критерию Learnt, но давно не перепроверÑ�лиÑ�ÑŒ. ОбÑ�зательно **не Ñ�читать Uncertain дважды** при вычиÑ�лении общего количеÑ�тва. +- Ход может быть **Learnt и одновременно Due**: Ñ�рок повторениÑ� пришёл, но трёх уÑ�пешных ответов подрÑ�д никто не отменÑ�л. +- `Due = 0` **не означает** `Learnt = Total`: вÑ�е назначенные на Ñ�ейчаÑ� проверки выполнены, однако оÑ�талиÑ�ÑŒ ходы `Unseen` или `Learning`. +- `Uncertain` — не то же Ñ�амое, что любой Due. **[Ð�ЕИЗВЕСТÐ�О]** Конкретный Ñ�рок, поÑ�ле которого обычное Due Ñ�тановитÑ�Ñ� Uncertain, в найденной документации не раÑ�крыт. Ð�иже определён конфигурируемый проектный вариант. +- СтатуÑ�Ñ‹ Learnt и Uncertain не дают права отменÑ�ть будущие повторениÑ�: знаниÑ� нужно регулÑ�рно подтверждать. + +### 2.3. Как правильно отображать Ñ�татуÑ�Ñ‹ без переÑ�ечений — [ПРОЕКТ] + +Ð’ хранилище задаём два незавиÑ�имых Ñ�войÑ�тва: + +- `introduced` — добавлен ли ход в раÑ�пиÑ�ание SRS; +- `correct_streak` — длина поÑ�ледовательноÑ�ти правильных Ñ�амоÑ�тоÑ�тельных ответов; + +и вычиÑ�лÑ�ем флаг `uncertain` длÑ� закреплённых ходов, которые Ñ�ущеÑ�твенно проÑ�рочены. + +Ð’ UI удобно показывать **взаимоиÑ�ключающие группы**: + +```text +UNSEEN: introduced = false +LEARNING: introduced = true AND correct_streak < 3 +LEARNT_FRESH: introduced = true AND correct_streak >= 3 AND NOT uncertain +UNCERTAIN: introduced = true AND correct_streak >= 3 AND uncertain +``` + +**Ð�е Ñ�оздавать отдельного физичеÑ�кого Ñ�оÑ�тоÑ�ниÑ� Resistant вмеÑ�то Learning:** уÑ�тойчиво проблемный ход — Ñ�то **дополнительный признак**, переÑ�екающийÑ�Ñ� Ñ� Learning/другими Ñ�оÑ�тоÑ�ниÑ�ми, но не менÑ�ющий их арифметику. + +ДлÑ� Ñ�крана, похожего на ChessTempo, Ñ�чётчик `Learnt` рекомендуетÑ�Ñ� определÑ�ть как `LEARNT_FRESH + UNCERTAIN`, а `Uncertain` выводить отдельно как уточнение. Ð’ интерфейÑ�е подпиÑ�ÑŒ должна прÑ�мо объÑ�Ñ�нÑ�ть вложенноÑ�ть. Можно также показывать отдельный Ñ�чётчик «Ð�адёжно изучено» = `LEARNT_FRESH`. + +### 2.4. Формула Uncertain — [ПРОЕКТ], а не опубликованный алгоритм ChessTempo + +```text +is_uncertain = + correct_streak >= 3 + AND now_utc > next_review_at + max(7 дней, 0.25 * previous_interval) +``` + +ЗначениÑ� `7 дней` и `0.25` — **предлагаемые наÑ�траиваемые коÑ�ффициенты**, Ð�Е подтверждённые значениÑ� ChessTempo. РеализациÑ� обÑ�зана выделить вычиÑ�ление в отдельную функцию `is_uncertain(item, now, settings)`. При изменении наÑ�троек Ñ�татуÑ�Ñ‹ должны переÑ�читыватьÑ�Ñ� без перепиÑ�ываниÑ� иÑ�тории ответов. + +ПоÑ�ле новой Ñ�амоÑ�тоÑ�тельной проверки: + +- правильный ответ: Ñ�оÑ�тоÑ�ние оÑ�таётÑ�Ñ�/Ñ�тановитÑ�Ñ� Learnt, дата Ñ�ледующей проверки переноÑ�итÑ�Ñ�; Uncertain Ñ�нимаетÑ�Ñ�; +- ошибка: `correct_streak=0`, Ñ�оÑ�тоÑ�ние Ñ�тановитÑ�Ñ� Learning; Uncertain Ñ�нимаетÑ�Ñ�; +- отÑ�утÑ�твие ответа: никаких иÑ�куÑ�Ñ�твенных уÑ�пехов или ошибок, Ñ�татуÑ� изменÑ�етÑ�Ñ� только за Ñ�чёт времени. + +## 3. ПредметнаÑ� модель и единица учёта + +### 3.1. СущноÑ�ти + +| СущноÑ�ть | Ключевые данные | +|---|---| +| `User` | `id`, наÑ�тройки, чаÑ�овой поÑ�Ñ� | +| `Repertoire` | `id`, `owner_id`, `name`, `color`, начальнаÑ� позициÑ� | +| `Position` | нормализованное Ñ�оÑ�тоÑ�ние, уникальный `position_key` | +| `MoveEdge` | `from_position_key`, `move_uci`, `to_position_key`, SAN, аннотации | +| `RepertoireEdge` | `repertoire_id`, Ñ�Ñ�ылка на ребро, включён/выключен, главный/побочный, порÑ�док | +| `LearningItem` | `user_id`, `position_key`, `move_uci`, интервалы, Ñ�ерии, Ñ�уммарные показатели | +| `TrainingAttempt` | Ñ�обытие проверки: ожидалоÑ�ÑŒ/Ñ�ыграно, результат, времÑ�, подÑ�казка | +| `TrainingSession` | режим, охват, порÑ�док, завершённые Ñ�лементы, наÑ�тройки на момент Ñ�тарта | +| `RepertoireSnapshot` | Ñ�нимок агрегатов на дату/момент | + +### 3.2. Ключ учебного Ñ�лемента + +```text +LearningItemKey = (user_id, position_key, expected_move_uci) +``` + +**[ПРОЕКТ]** Данные запоминаниÑ� принадлежат **пользователю**, а не одной ветке репертуара. ЕÑ�ли два репертуара Ñ�Ñ�ылаютÑ�Ñ� на один и тот же учебный Ñ�лемент, он имеет одну иÑ�торию и одно раÑ�пиÑ�ание. ПоÑ�вление общего хода во втором репертуаре не Ñ�оздаёт второй учебный Ñ�лемент. + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo иÑ�пользует единое предÑ�тавление шахматной позиции длÑ� транÑ�позиций, общий прогреÑ�Ñ� и графичеÑ�кие переходы между ветвÑ�ми. ИÑ�точник: [руководÑ�тво, § 17.4.6](https://www.chesstempo.com/manual/en/manual.html#transpositions). + +### 3.3. Почему позициÑ� не равна Ñ�троке PGN + +Пример одной позиции из двух поÑ�ледовательноÑ�тей: + +```text +Путь A: 1.d4 Nf6 2.c4 e6 3.Nf3 d5 +Путь B: 1.d4 d5 2.c4 e6 3.Nf3 Nf6 +``` + +Ð’ обоих Ñ�лучаÑ�Ñ… поÑ�ледующие ходы пользователÑ� нужно проверÑ�ть на оÑ�нове одной и той же позиции. ТребуетÑ�Ñ� нормализованный ключ Ñ� доÑ�кой, очередью хода, рокировочными правами и легально релевантным взÑ�тием на проходе. Счётчики FEN длÑ� 50 ходов и номера хода не должны разноÑ�ить одинаковые дебютные позиции на разные учебные запиÑ�и. ПолнаÑ� проверка легальноÑ�ти ходов обÑ�зательна. + +### 3.4. Варианты Ñ� неÑ�колькими Ñ�обÑ�твенными ответами — [ПРОЕКТ] + +ЕÑ�ли в одной позиции активны два Ñ�обÑ�твенных хода, Ñ�иÑ�теме нужно **Ñ�вно определить, чему именно она обучает**: + +- рекомендуемый режим `one_answer_per_position`: один выбранный главный ответ, альтернативы хранÑ�Ñ‚Ñ�Ñ� длÑ� Ñ�правки; +- раÑ�ширенный режим `multiple_accepted_moves`: еÑ�ли целью Ñ�влÑ�етÑ�Ñ� конкретный ответ, допуÑ�каетÑ�Ñ� заранее наÑ�троить, какие ответы зачтутÑ�Ñ�; при показе альтернативы не Ñ�ледует одновременно заÑ�читывать два разных `LearningItem`. + +ТочнаÑ� трактовка альтернативных Ñ�обÑ�твенных ходов иÑ�ходной Ñ�иÑ�темой в открытых иÑ�точниках не уÑ�тановлена. Это обÑ�зательно Ñ�оглаÑ�уемаÑ� чаÑ�ть реализации, но длÑ� MVP принÑ�Ñ‚ `one_answer_per_position`. + +## 4. Объём Ñ�татиÑ�тики и правило подÑ�чёта множеÑ�тва ходов + +### 4.1. Базовое множеÑ�тво + +ДлÑ� репертуара `R`, пользователÑ� `U`, глубины `D` и фильтра `F` определим: + +```text +S(U,R,D,F) = множеÑ�тво уникальных активных (позициÑ�, Ñ�обÑ�твенный ход), + доÑ�тижимых от корневой позиции R, + Ñ� глубиной <= D, + удовлетворÑ�ющих фильтру F. +``` + +Тренировка за белых проверÑ�ет **только белые ходы**, за чёрных — **только чёрные**. Ходы Ñ�оперника Ñ�лужат уÑ�ловиÑ�ми ветвлениÑ� и автоматичеÑ�ки проигрываютÑ�Ñ�. **[ПРОЕКТ]** ДлÑ� процентов прогреÑ�Ñ�а и требований теÑ�тированиÑ� в знаменатель входÑ�Ñ‚ именно проверÑ�емые Ñ�обÑ�твенные ходы. Ð’ публичном интерфейÑ�е ChessTempo употреблÑ�етÑ�Ñ� термин *positions/moves*, но правила знаменателÑ� длÑ� вÑ�ех Ñ�лучаев (например, отключённые ходы) не полноÑ�тью формализованы — при необходимоÑ�ти буквального Ñ�овпадениÑ� требуетÑ�Ñ� дополнительнаÑ� Ñ�кÑ�периментальнаÑ� проверка. + +ТранÑ�позиции в `S` **не дублируютÑ�Ñ�**. При выборе неÑ�кольких репертуаров иÑ�пользуем объединение множеÑ�тв, а не Ñ�умму: `S_all = S_A ∪ S_B`. + +### 4.2. Фильтры и облаÑ�ть охвата + +Каждый Ñ�татиÑ�тичеÑ�кий ответ обÑ�зан Ñ�одержать `scope`, например: + +```json +{ + "repertoire_ids": [12, 13], + "side": "WHITE", + "max_depth": null, + "only_active": true, + "branch_root": null, + "as_of": "2026-11-04T12:00:00Z" +} +``` + +Без `scope` невозможно понÑ�ть, отноÑ�итÑ�Ñ� «70% изучено» ко вÑ�ему репертуару или только к выбранной ветке. + +**[ПОДТВЕРЖДЕÐ�О]** Ð’ ChessTempo ограничение `Maximum learning depth` влиÑ�ет на **Ñ�водные цифры под доÑ�кой**, но **не влиÑ�ет на графики прогреÑ�Ñ�а**, которые Ñ�читают полную глубину. ДлÑ� нового продукта рекомендуетÑ�Ñ� отображать переключатель «текущий тренировочный охват / полный репертуар», чтобы Ñ�то отличие не воÑ�принималоÑ�ÑŒ как ошибка. ИÑ�точник: [руководÑ�тво § 17.4.2](https://www.chesstempo.com/manual/en/manual.html#trainingdepth). + +## 5. Точные формулы прогреÑ�Ñ�а репертуара — [ПРОЕКТ] + +### 5.1. Счётчики + +ДлÑ� набора `S` Ñ� чиÑ�лом Ñ�лементов `T = |S|`: + +```text +Unseen = count(item in S: not item.introduced) +Learning = count(item in S: item.introduced and item.correct_streak < 3) +Learnt = count(item in S: item.introduced and item.correct_streak >= 3) +Uncertain = count(item in S: item.correct_streak >= 3 and is_uncertain(item,now)) +LearntConfident = Learnt - Uncertain +Due = count(item in S: item.introduced and item.next_review_at <= now) +NextDueAt = min(next_review_at) длÑ� введённых Ñ�лементов Ñ� future next_review_at +``` + +**Инварианты:** + +```text +T = Unseen + Learning + Learnt +0 <= Uncertain <= Learnt +0 <= LearntConfident <= Learnt +0 <= Due <= Learning + Learnt +``` + +Ð�е Ñ�уммировать `Uncertain` второй раз: `T != Unseen + Learning + Learnt + Uncertain`. + +### 5.2. Проценты + +ДлÑ� `T > 0`: + +```text +CoveragePercent = 100 * (T - Unseen) / T +LearntPercent = 100 * Learnt / T +ConfidentPercent = 100 * (Learnt - Uncertain) / T +LearningPercent = 100 * Learning / T +UnseenPercent = 100 * Unseen / T +UncertainOfLearntPct = 100 * Uncertain / Learnt (еÑ�ли Learnt > 0) +DueOfIntroducedPct = 100 * Due / (T - Unseen) (еÑ�ли введённые > 0) +``` + +ДлÑ� `T = 0` не показывать `100%`: результат **«нет активных обучаемых ходов»**, процент = `null` (в UI отображаетÑ�Ñ� `—`). Это защищает от ложного заÑ�влениÑ� о полном изучении пуÑ�того репертуара. + +### 5.3. Как объÑ�влÑ�ть «репертуар изучен» + +Ð’ оригинале нет подтверждённого бинарного критериÑ� длÑ� вÑ�его дебюта. ПредлагаютÑ�Ñ� **разные Ñ�татуÑ�Ñ‹**, чтобы не Ñ�мешивать их: + +| Индикатор | Формальное уÑ�ловие | Значение | +|---|---|---| +| `NOT_STARTED` | `T>0, Unseen=T` | Ещё не начинали | +| `IN_PROGRESS` | `T>0, Learnt0, Learnt=T` | Ð’Ñ�е ходы хотÑ� бы доÑ�тигли формального порога | +| `CONFIRMED_CURRENT` | `T>0, Learnt=T, Uncertain=0, Due=0` | Ð’Ñ�Ñ‘ доÑ�тигло порога, критичеÑ�ки проÑ�роченных и назначенных на Ñ�ейчаÑ� проверок нет | +| `EMPTY` | `T=0` | Учить нечего | + +Переход `ALL_LEARNT → IN_PROGRESS` возможен поÑ�ле единÑ�твенной ошибки; `CONFIRMED_CURRENT → ALL_LEARNT` возможен автоматичеÑ�ки, когда наÑ�тупает времÑ� Ñ�ледующей проверки. ПоÑ�тому Ñ�то **не вечное доÑ�тижение**, а Ñ�оÑ�тоÑ�ние знаний **на момент `as_of`**. + +**Дополнительно:** разрешаетÑ�Ñ� Ñ�охранÑ�ть награду/доÑ�тижение «Впервые изучены вÑ�е ходы» как иÑ�торичеÑ�кий факт (`first_all_learnt_at`), не подменÑ�Ñ� им текущую оценку. + +**Рекомендуемые подпиÑ�и UI:** + +- `Изучено: 80 / 100 (80%)` +- `Ð’ процеÑ�Ñ�е: 15` +- `Ð�е начато: 5` +- `Из изученных требуют подтверждениÑ�: 12` +- `Проверить Ñ�ейчаÑ�: 9` +- `Ð�ктуально подтверждено: 68 / 100 (68%)` + +### 5.4. ЧиÑ�ловой пример + +ДопуÑ�тим, активный репертуар Ñ�одержит `T=100` уникальных обучаемых Ñ�обÑ�твенных ходов: + +```text +Unseen = 10 +Learning = 20 +Learnt = 70 (из них Uncertain = 15) +Due = 25 (любаÑ� Ñ�меÑ�ÑŒ Learning и Learnt) +``` + +Тогда: + +```text +CoveragePercent = (100-10)/100*100 = 90% +LearntPercent = 70/100*100 = 70% +ConfidentPercent = (70-15)/100*100 = 55% +UncertainOfLearntPct = 15/70*100 ≈ 21.43% +``` + +Вывод: **репертуар Ð�Е Ñ�читаетÑ�Ñ� полноÑ�тью изученным**, неÑ�мотрÑ� на 90% охвата. `Due=25` — Ñ�то чиÑ�ло заданий на Ñ�ейчаÑ�, а не процент невыученного материала. + +### 5.5. Разница «Learnt» и «Uncertain» на данных руководÑ�тва + +Ð’ [Ñ�криншоте таблицы Repertoire Summary из руководÑ�тва](https://www.chesstempo.com/manual/en/manual.html#repertoiresummary) приведён пример: **Catalan: Learning 421; Learnt 687; Moves 1643; Uncertain 461**. + +ЕÑ�ли трактовать `Uncertain` как **подмножеÑ�тво** `Learnt`, пример непротиворечив: + +```text +Unseen = 1643 - 421 - 687 = 535 +Learnt, не uncertain = 687 - 461 = 226 +``` + +Ð’ других Ñ�троках Ñ�криншота `Learning + Learnt + Uncertain` даже превышает `Moves`, что дополнительно показывает недопуÑ�тимоÑ�ть Ñ�кладываниÑ� вÑ�ех четырёх Ñ�толбцов как взаимоиÑ�ключающих групп. При Ñ�том точные правила формированиÑ� иÑ�ходного Ñ�толбца Moves на уровне внутренних Ñ�труктур Ñ�айта по Ñ�криншоту неизвеÑ�тны. + +### 5.6. Отдельные показатели длÑ� ветки и полного варианта + +ДлÑ� выбранного узла/ветки повторно вычиÑ�лÑ�етÑ�Ñ� `S` по **вÑ�ем доÑ�тижимым обучаемым ходам внутри ветки**, включаÑ� её подварианты. + +ДлÑ� одной конкретной линии `L`: + +```text +LineLearnt = T_line > 0 AND all(item.correct_streak >= 3 for item in unique(line.items)) +LineFresh = LineLearnt AND no uncertain items AND no due items in line +``` + +ЕÑ�ли позициÑ� предÑ�тавлена в двух линиÑ�Ñ…, в Ñ�татиÑ�тике **каждой отдельной линии** она может приÑ�утÑ�твовать; при агрегировании вÑ�его репертуара она учитываетÑ�Ñ� **один раз**. ВеÑ�ÑŒ репертуар нельзÑ� оценивать как Ñ�реднее арифметичеÑ�кое процентов линий, потому что линии разной длины и переÑ�екаютÑ�Ñ�. + +## 6. СтатиÑ�тика точноÑ�ти, ошибок и Ñ�короÑ�ти — [ПРОЕКТ] + +### 6.1. Что извеÑ�тно про ChessTempo + +**[ПОДТВЕРЖДЕÐ�О]** Ð’ деталÑ�Ñ… хода ChessTempo отображаютÑ�Ñ�: *Accuracy*, поÑ�леднее предъÑ�вление, правильные/ошибочные ответы подрÑ�д, дата Ñ�ледующего повторениÑ� и иÑ�ториÑ� неверных ходов Ñ� чаÑ�тотой и поÑ�ледним временем ошибочного ввода. Ð’ Sunburst и дереве можно окрашивать ходы по Accuracy, Correct sequence, Last seen, Next scheduled. ИÑ�точники: [руководÑ�тво § 17.11](https://www.chesstempo.com/manual/en/manual.html#movedetails), [§ 17.8](https://www.chesstempo.com/manual/en/manual.html#openingsunburstrepertoirevisualisation). + +**[Ð�ЕИЗВЕСТÐ�О]** ТочнаÑ� опубликованнаÑ� формула *Accuracy* в разделе **дебютного тренажёра** не обнаружена. Формула ниже — проектнаÑ�, Ñ�тандартнаÑ� и воÑ�производимаÑ�; не Ñ�ледует утверждать, что она идентична внутренней формуле ChessTempo. + +### 6.2. СобытиÑ� и знаменатель точноÑ�ти + +КаждаÑ� попытка имеет тип: + +- `CORRECT_INDEPENDENT` — правильный ход без заранее раÑ�крытого решениÑ�; +- `INCORRECT_INDEPENDENT` — Ñ�амоÑ�тоÑ�тельный неправильный ход; +- `PREVIEWED` — решение показано до ответа (Ñ�трелка/Ñ�внаÑ� подÑ�казка); +- `REPLAY_AFTER_ERROR` — пользователь повторил уже показанный ответ длÑ� продолжениÑ�; +- `AUTO_CONTEXT` — ход автоматичеÑ�ки проигран Ñ�иÑ�темой; +- `ILLEGAL_MOVE` — нелегальный ход, не Ñ�влÑ�ющийÑ�Ñ� Ñ�одержательной проверкой. + +**ДлÑ� проверки знаниÑ� учитываютÑ�Ñ� только `CORRECT_INDEPENDENT` и `INCORRECT_INDEPENDENT`.** ОÑ�тальные типы могут учитыватьÑ�Ñ� в аналитике иÑ�пользованиÑ�, но не должны иÑ�куÑ�Ñ�твенно улучшать Accuracy и correct streak. + +Ð’ `PREVIEWED` Ñ�иÑ�тема может назначить быÑ�трое повторение длÑ� Ñ�амоÑ�тоÑ�тельного контролÑ�; Ñ�м. § 7. + +### 6.3. Формула точноÑ�ти + +ДлÑ� учебного Ñ�лемента `i`: + +```text +correct_i = count(CORRECT_INDEPENDENT) +wrong_i = count(INCORRECT_INDEPENDENT) +attempts_i = correct_i + wrong_i +accuracy_i = attempts_i == 0 ? null : 100 * correct_i / attempts_i +``` + +Пример: 7 Ñ�амоÑ�тоÑ�тельных верных ответов и 3 ошибки → `70%`. + +ДлÑ� группы `S`: + +```text +GroupAccuracy = + 100 * SUM(correct_i) / SUM(correct_i + wrong_i), еÑ�ли SUM(attempts_i)>0 +``` + +**Ð�е иÑ�пользовать проÑ�тое Ñ�реднее `accuracy_i`** длÑ� оÑ�новного показателÑ�: ход, проверенный 100 раз, и ход, проверенный 1 раз, иначе получили бы одинаковый веÑ�. При необходимоÑ�ти дополнительно показывать `MeanPerItemAccuracy` как отдельную метрику Ñ� Ñ�вным названием. + +**ОÑ�обенноÑ�ть:** выÑ�окий Accuracy не доказывает `Learnt`: Ñ�ериÑ� `2 подрÑ�д` оÑ�таётÑ�Ñ� Learning даже при 98% общей точноÑ�ти. И наоборот, три правильных ответа поÑ�ле многочиÑ�ленных прошлых ошибок дают Learnt при низком иÑ�торичеÑ�ком Accuracy. + +### 6.4. Ошибки + +ДлÑ� каждого учебного Ñ�лемента хранить: + +```text +correct_streak +wrong_streak +last_wrong_move_uci +last_wrong_at +wrong_move_histogram[played_move_uci] = {count, last_at} +``` + +При ошибке: + +- `correct_streak = 0`, `wrong_streak += 1`; +- Ñ�охранить фактичеÑ�ки Ñ�деланный неправильный **легальный** ход; +- показать правильный репертуарный ход; +- уÑ�тановить новую дату повторениÑ� по правилам SRS; +- попытка пользователÑ� иÑ�править ход **не** превращает ошибку в уÑ�пех. + +При Ñ�амоÑ�тоÑ�тельном уÑ�пехе: `correct_streak += 1`, `wrong_streak = 0`. + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo Ñ�охранÑ�ет иÑ�торию неверных ходов Ñ� чаÑ�тотой и поÑ�ледним временем. Ð’ руководÑ�тве вÑ�тречаетÑ�Ñ� иÑ�торичеÑ�кое замечание о неполном учёте ошибок в мобильных клиентах; Ñ�то не должно влиÑ�ть на проектируемую Ñ�иÑ�тему: вÑ�е платформы отправлÑ�ÑŽÑ‚ Ñ�обытиÑ� в единое хранилище. + +### 6.5. ВремÑ� ответа + +Хранить `response_time_ms` от момента готовноÑ�ти доÑ�ки к Ñ�амоÑ�тоÑ�тельному ответу до первого завершённого легального хода. Отдельно учитывать времÑ� анимации контекÑ�та и пользовательÑ�ких пауз — **их не включать** в времÑ� размышлениÑ�. Медиану/перцентили Ñ�короÑ�ти показывать дополнительно, но не иÑ�пользовать длÑ� Learnt в базовом алгоритме. + +## 7. РаÑ�пиÑ�ание интервального повторениÑ� (SRS) + +### 7.1. Подтверждённые правила и значениÑ� по умолчанию + +| Ð�аÑ�тройка | Default ChessTempo | ИÑ�точник | +|---|---:|---| +| `growth_factor` | `2.0` | РуководÑ�тво § 17.15.2 | +| `first_correct_delay` | `1440 минут` (1 день) | Там же | +| `mistake_delay` | `0.5 минуты` (30 Ñ�екунд) | Там же | +| `preview_delay` | `1 минута` | Там же | +| `max_interval` | `1095 дней` (3 года) | Там же | +| `sort_due_items_by` | `Variation` | Там же | +| `undue_variation_window` | `0 чаÑ�ов` | Там же | + +СÑ�ылка: [официальные наÑ�тройки SRS](https://www.chesstempo.com/manual/en/manual.html#spacedrepetitionsettings). + +**[ПОДТВЕРЖДЕÐ�О]** Ð’ руководÑ�тве приведён пример: еÑ�ли ход был правильно воÑ�произведён **4 днÑ� назад**, а Ñ�егоднÑ� Ñ�нова решён правильно, при коÑ�ффициенте `2.0` Ñ�ледующее повторение будет через **8 дней**. Это значит, что правильнее ориентироватьÑ�Ñ� на **фактичеÑ�ки прошедший Ñ�рок**, а не безоговорочно удваивать Ñ�тарый плановый интервал. + +### 7.2. ПроектнаÑ� реализациÑ� планировщика + +Данные: + +```text +introduced boolean +correct_streak integer +last_correct_at timestamp|null +last_review_at timestamp|null +next_review_at timestamp|null +previous_interval_seconds integer|null +``` + +```pseudo +on_independent_correct(item, now): + item.introduced = true + if item.correct_streak == 0 or item.last_correct_at is null: + delay = settings.first_correct_delay + else: + elapsed = now - item.last_correct_at + delay = min(max(elapsed * settings.growth_factor, + settings.min_practical_interval), + settings.max_interval) + item.correct_streak += 1 + item.wrong_streak = 0 + item.last_correct_at = now + item.last_review_at = now + item.previous_interval_seconds = delay + item.next_review_at = now + delay + +on_independent_wrong(item, played_move, now): + item.introduced = true + item.correct_streak = 0 + item.wrong_streak += 1 + item.last_correct_at = null # проектное решение: Ñ�броÑ� базы роÑ�та + item.last_review_at = now + item.next_review_at = now + settings.mistake_delay + save_wrong_move(item, played_move) + +on_preview(item, now): + item.introduced = true + # Без зачёта уÑ�пеха и без увеличениÑ� Ñ�ерии + item.last_review_at = now + item.next_review_at = now + settings.preview_delay +``` + +`min_practical_interval` — внутренний защитный параметр, **не значение ChessTempo**. Должна быть чёткаÑ� политика длÑ� ответа, Ñ�деланного преждевременно: можно иÑ�пользовать фактичеÑ�кое времÑ�, но не допуÑ�кать интервал менее заданного нижнего предела. + +**[Ð�ЕИЗВЕСТÐ�О]** Ð�екоторые граничные детали SRS — например, точнаÑ� база роÑ�та поÑ�ле ошибки, доÑ�рочного ответа или показа подÑ�казки — по открытой документации не уÑ�тановлены. ДлÑ� них предпиÑ�ан приведённый выше воÑ�производимый алгоритм, покрытый теÑ�тами, а не домыÑ�ел о реализации ChessTempo. + +### 7.3. Due и очередь тренировок + +```text +Due(item, now) = item.introduced AND item.next_review_at <= now +``` + +`Due=0` означает, что на данный момент не оÑ�талоÑ�ÑŒ введённых ходов, Ñ�рок которых наÑ�тупил. **Unseen Ñ�юда не входÑ�Ñ‚.** + +**[РÐ�ЗРÐ�БОТЧИК]** При `Due=0` обычно разумно оÑ�тановитьÑ�Ñ�: еÑ�ли продолжить, тренажёр может ввеÑ�ти новые ходы из Unseen, а когда Unseen уже нет — начать проверÑ�ть ранее запланированные ходы доÑ�рочно. ИÑ�точники: [разбор «Trying to understand…»](https://chesstempo.com/forum/topic/trying-to-understand-how-opening-training-works-with-the-scheduling-option/10924/), [«Opening Training Best Practice»](https://chesstempo.com/forum/topic/opening-training-best-practice/12249/). + +Сортировки: + +- `Variation`: группировать готовые к проверке Ñ�лементы по веткам. По руководÑ�тву ошибки текущей Ñ�еÑ�Ñ�ии обычно попадают на повторную проверку **поÑ�ле первичной очереди**, а не Ñ�разу же Ñ�пуÑ�Ñ‚Ñ� 30 Ñ�екунд. +- `Due date`: Ñ�начала макÑ�имально проÑ�роченные; подходит при накопившемÑ�Ñ� долге. + +ВнутреннÑ�Ñ� очередь на Ñ�тарте Ñ�еÑ�Ñ�ии должна фикÑ�ировать Ñ�пиÑ�ок доÑ�тупных Ñ�лементов, но динамичеÑ�ки добавлÑ�ть пропущенные/ошибочные при Ñ�ледующем проходе. Одна и та же проверка не должна Ñ�читатьÑ�Ñ� дважды. + +### 7.4. Как вводить новые ходы + +Пока еÑ�ть `Due`, оÑ�новной режим предлагает их. ЕÑ�ли `Due=0` и еÑ�ть `Unseen`, пользователь может **Ñ�вно выбрать** продолжение обучениÑ�. Ð�овые Ñ�лементы выбираютÑ�Ñ� по наÑ�тройке `Learning priority`: + +1. `Depth first` — главнаÑ� линиÑ� полноÑ�тью, затем боковые. +2. `Breadth over depth` — ранние позиции вÑ�ех веток, затем более глубокие. +3. `Main lines first` — главные линии раньше подвариантов. +4. `Common positions first` — популÑ�рные позиции раньше редких; при отÑ�утÑ�твии данных иÑ�пользуетÑ�Ñ� fallback на движковые оценки, затем обход в ширину. + +**[ПОДТВЕРЖДЕÐ�О]** Приоритет новых ходов применÑ�етÑ�Ñ� **при переходе Unseen → введён в SRS**, а не перепиÑ�ывает даты повторениÑ� уже изучаемых. СÑ�ылка: [руководÑ�тво § 17.4.3](https://www.chesstempo.com/manual/en/manual.html#availabletrainingmodes). + +## 8. Режимы тренировки + +### 8.1. Spaced Repetition — Ñ�тандартный + +Выбор по `next_review_at`; периодичеÑ�кое добавление новых ходов; фикÑ�ациÑ� ошибок и уÑ�пешных ответов; обновление раÑ�пиÑ�аниÑ�. Ð�ужна возможноÑ�ть закончить работу при `Due=0`. + +### 8.2. Review in Order + +Проход вÑ�его активного репертуара или ветки по `Learning priority` **по одному разу за цикл**. СиÑ�тема хранит позицию цикла и автоматичеÑ�ки воÑ�производит уже проверенные ранее контекÑ�тные ходы. По окончании цикл начинаетÑ�Ñ� заново. ЕÑ�ть отдельный `Reset Review Order`, **не Ñ�браÑ�ывающий** Ñ�татиÑ�тику SRS. + +**[ПОДТВЕРЖДЕÐ�О]** Ответы в Ñ�том режиме вÑ�Ñ‘ равно менÑ�ÑŽÑ‚ SRS-раÑ�пиÑ�ание. Ð�овые ходы при первом предъÑ�влении выходÑ�Ñ‚ из Unseen. ИÑ�точник: [§ 17.4.3, Review in order](https://www.chesstempo.com/manual/en/manual.html#reviewinorder). + +### 8.3. Least Recent / Unseen First + +Сначала Unseen, затем ходы Ñ� Ñ�амой давней поÑ�ледней попыткой. Ð’Ñ�е реальные Ñ�амоÑ�тоÑ�тельные ответы также обновлÑ�ÑŽÑ‚ SRS. КонтекÑ�тные ходы, проверенные доÑ�рочно, помечаютÑ�Ñ� как уже пройденные в текущем цикле, чтобы не повторÑ�ть их без нужды. + +## 9. КонтекÑ�Ñ‚: не заÑ�тавлÑ�ть каждый раз играть от первого хода + +**[ПОДТВЕРЖДЕÐ�О]** При выборе целевой позиции ChessTempo может автоматичеÑ�ки показать ведущую к ней линию, уÑ�корить хорошо знакомые чаÑ�ти, пропуÑ�тить чрезвычайно хорошо извеÑ�тное начало и включить проверку неÑ�кольких контекÑ�тных ходов, еÑ�ли они Ñ�ами нуждаютÑ�Ñ� в закреплении. + +Ð�лгоритм: + +```pseudo +train(target_item): + line = choose_repertoire_path(root, target_item.position) + for each earlier move in line: + if move made by opponent: autoplay + else if should_test_as_context(move): ask_user_and_grade + else if can_skip_known_prefix(move): omit prefix presentation + else: autoplay at knowledge_adaptive_speed + ask_user_and_grade(target_item) +``` + +Ð�аÑ�тройки: + +- `Reinforce minimum correct` — дополнительно Ñ�прашивать контекÑ�тные ходы Ñ� Ñ�ерией короче порога; +- `Reinforce minimum days` — Ñ�прашивать контекÑ�тный ход, еÑ�ли его ближайшаÑ� проверка доÑ�таточно Ñ�коро; +- `Don't show start moves threshold` — пропуÑ�кать хорошо выученный **начальный префикÑ�**; +- `Move speed adjustment` — коÑ�ффициент Ñ�короÑ�ти анимации; +- `Use fixed piece movement speed` — фикÑ�ированнаÑ� Ñ�короÑ�ть вмеÑ�то адаптивной; +- `Consider leadup moves when training branch` — проверÑ�ть контекÑ�Ñ‚ выше точки начала ветки (по умолчанию в ChessTempo выключено). + +ИÑ�точники: [руководÑ�тво § 17.4.3 Context](https://www.chesstempo.com/manual/en/manual.html#contextfortrainingmoves), [§ 17.15.3](https://www.chesstempo.com/manual/en/manual.html#advancedsettings), [FAQ](https://www.chesstempo.com/faq/). + +**Правило Ñ�татиÑ�тики:** автоматичеÑ�кое проигрывание не изменÑ�ет `correct_streak`, `accuracy`, `last_correct_at` и не образует Ñ�амоÑ�тоÑ�тельную попытку; еÑ�ли контекÑ�тный ход реально проверен пользователем, результат учитываетÑ�Ñ� как обычнаÑ� проверка один раз. + +## 10. Проверка ответа и подÑ�казки + +### 10.1. Ð�еверный ход + +ПоÑ�ле первого легального неверного хода: + +1. ЗафикÑ�ировать ошибку ровно один раз. +2. Показать ожидаемый ход. +3. Позволить Ñ�ыграть ожидаемый ход длÑ� продолжениÑ� линии. +4. Повторное проигрывание Ñ�того показанного хода не заÑ�читывать как правильный ответ. +5. ПомеÑ�тить Ñ�лемент в очередь на Ñ�корое повторение по SRS. + +Ð�елегальное перемещение не Ñ�читаетÑ�Ñ� ответом; интерфейÑ� проÑ�то возвращает фигуру на меÑ�то. + +### 10.2. Предварительный показ ответа + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo может подÑ�вечивать ход Ñ�трелкой длÑ� новых позиций, ранее ошибочно решённых ходов или вообще вÑ�ех ходов — в завиÑ�имоÑ�ти от наÑ�троек. ЕÑ�ли решение предварительно показано, повторение назначаетÑ�Ñ� быÑ�трее, по умолчанию через одну минуту. ИÑ�точники: [§ 17.4.1](https://www.chesstempo.com/manual/en/manual.html#movehints), [§ 17.15.2](https://www.chesstempo.com/manual/en/manual.html#spacedrepetitionsettings). + +**[ПРОЕКТ]** Ð’ проекте при любой подÑ�казке, котораÑ� раÑ�крыла ожидаемый ход ДО Ñ�амоÑ�тоÑ�тельного ответа, Ñ�обытие помечаетÑ�Ñ� `PREVIEWED`; оно не увеличивает `correct_streak` и не ухудшает accuracy как неправильное. Движок должен позже проверить знание без подÑ�казки. + +### 10.3. Пауза/завершение линии + +Кнопки `Pause`, `Continue`, `Stop`. ОпциональнаÑ� оÑ�тановка в конце линии. Отображение комментариев и анализа вне фазы `AWAITING_MOVE`, чтобы Ñ�лучайно не выдавать ответ заранее. + +## 11. Панель Ñ�татиÑ�тики отдельного хода + +При выборе хода в дереве (и в паузе тренировки) показывать: + +| Поле | Формула / иÑ�точник | +|---|---| +| СтатуÑ� | Из § 2.3 | +| ТочноÑ�ть | `correct / (correct + wrong) * 100` | +| Правильно / ошибки | Счётчики Ñ�амоÑ�тоÑ�тельных попыток | +| Ð’Ñ�его Ñ�амоÑ�тоÑ�тельных проверок | `correct + wrong` | +| Правильных подрÑ�д | `correct_streak` | +| Ошибок подрÑ�д | `wrong_streak` | +| ПоÑ�ледний показ | `last_review_at` | +| ПоÑ�леднÑ�Ñ� Ñ�амоÑ�тоÑ�тельнаÑ� проверка | `max(timestamp незавиÑ�имых попыток)` | +| Следующий повтор | `next_review_at` или `—`, еÑ�ли Unseen | +| ВремÑ� до повтора | `next_review_at - now`, еÑ�ли будущее | +| ПроÑ�рочка | `max(0, now - next_review_at)` | +| Причина Ñ�татуÑ�а Uncertain | При наличии — проÑ�рочка и порог | +| Ошибочные ответы | UCI/SAN, чиÑ�ло ошибок, поÑ�ледний раз | +| Медиана времени ответа | По Ñ�амоÑ�тоÑ�тельным проверкам | +| Где вÑ�тречаетÑ�Ñ� | Репертуары и ветки, Ñ�одержащие тот же учебный Ñ�лемент | + +ЕÑ�ли `attempts=0`, точноÑ�ть выводитÑ�Ñ� как `—`, а не `0%` или `100%`. У каждой метрики должна быть информационнаÑ� подÑ�казка Ñ� определением. + +## 12. СводнаÑ� Ñ�татиÑ�тика репертуара + +### 12.1. ГлавнаÑ� Ñ�трока (как в ChessTempo) + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo имеет таблицу `Repertoire Summary` Ñ�о Ñ�толбцами **Name, Learning, Learnt, Moves, Uncertain, Due**. ЕÑ�ли еÑ�ть назначенные повторениÑ�, в `Due` видно их чиÑ�ло; еÑ�ли вÑ�Ñ‘ актуально — времÑ� до Ñ�ледующей проверки. ИÑ�точник: [руководÑ�тво § 10.5](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). + +ДлÑ� Ñ�воего продукта рекомендуемые колонки: + +| Ð�азвание | Ходов (`T`) | Ð�е начато | ИзучаетÑ�Ñ� | Изучено | Uncertain | Due | Изучено % | Ð�ктуально % | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| СицилианÑ�каÑ� защита | 100 | 10 | 20 | 70 | 15 | 25 | 70% | 55% | + +Под таблицей добавить `Next due at` и кнопку «Продолжить изучение» (когда Due=0, но Unseen>0). + +### 12.2. Блок «Что мне делать Ñ�егоднÑ�» + +Приоритет отображениÑ�: + +1. `Due > 0`: «Повторить N ходов». +2. `Due = 0` и `Unseen > 0`: «Ð�а Ñ�егоднÑ� повторений нет; можно изучить новые ходы». +3. `Due = 0`, `Unseen = 0`, `Learning > 0`: «Плановые повторы выполнены; чаÑ�ть материала ещё на Ñ�тапе закреплениÑ�». +4. `Due = 0`, `Unseen = 0`, `Learning = 0`: «ВÑ�е ходы изучены; Ñ�ледующее повторение …». + +**Ð�е пиÑ�ать «дебют полноÑ�тью оÑ�воен», еÑ�ли `Due=0`, но еÑ�ть Unseen или Learning.** + +### 12.3. Ð�еÑ�колько репертуаров и глобальнаÑ� Ñ�татиÑ�тика + +Общий Ñ�чётчик Ñ�троить по `UNION DISTINCT LearningItemKey` внутри выбранных репертуаров: + +```text +GlobalTotal != SUM(RepertoireTotal) при общих позициÑ�Ñ… +``` + +При Ñ�том таблица каждого репертуара иÑ�пользует Ñ�обÑ�твенное множеÑ�тво, поÑ�тому **Ñ�умма чиÑ�ел Ñ�трок таблицы может не равнÑ�тьÑ�Ñ� глобальному уникальному итогу**. Ð�а Ñ�кране пометить Ñ�ту оÑ�обенноÑ�ть. + +### 12.4. Сравнение веток + +По каждой ветке показывать T, Unseen, Learning, Learnt, Uncertain, Due, Accuracy, прогреÑ�Ñ� %, дату поÑ�ледней тренировки. Дочерние ветки могут Ñ�одержать общие транÑ�позиции; при Ñ�вёртке верхнего уровнÑ� требуетÑ�Ñ� объединÑ�ть по уникальным ключам, а не Ñ�кладывать дочерние Ñ�уммы. + +## 13. Графики и их алгоритмы + +### 13.1. History — динамика изучениÑ� + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo показывает изменение чиÑ�ла Learning, Learnt и Uncertain по времени; Uncertain может поÑ�влÑ�тьÑ�Ñ� проÑ�то из-за проÑ�рочки, без новой ошибки. ИÑ�точник: [руководÑ�тво § 17.25.1](https://www.chesstempo.com/manual/en/manual.html#globalstats). + +**[ПРОЕКТ]** Ежедневно (в указанном чаÑ�овом поÑ�Ñ�е пользователÑ�) вычиÑ�лÑ�ть Ñ�рез Ñ�татуÑ�ов вÑ�ех активных учебных Ñ�лементов: + +```text +(date, scope, total, unseen, learning, learnt, uncertain, due) +``` + +ДлÑ� каждого иÑ�торичеÑ�кого днÑ� нужно иÑ�пользовать **Ñ�оÑ�тав репертуара на Ñ�тот день**, либо Ñ�вно подпиÑ�ывать график как **ретроÑ�пективный переÑ�чёт текущего Ñ�оÑ�тава**. Эти подходы дают разные линии поÑ�ле добавлениÑ�/удалениÑ� ходов; нельзÑ� незаметно Ñ�мешивать их. + +Рекомендуемый режим по умолчанию: иÑ�торичеÑ�кий Ñ�нимок фактичеÑ�кого Ñ�оÑ�тава на конец днÑ�. Ð�е реконÑ�труировать прошлый `Uncertain` только из текущего Ñ�татуÑ�а — он завиÑ�ел от того времени и тогдашних наÑ�троек. + +График 1: `Learning`, `Learnt` и `Uncertain` (можно показывать Uncertain как подмножеÑ�тво Learnt). График 2 (проект): `% изучено`, `% актуально`, `Unseen`. + +### 13.2. Scheduled — раÑ�пределение предÑ�тоÑ�щих повторений + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo отображает количеÑ�тво уже проÑ�роченных, ожидающих повторениÑ� Ñ�егоднÑ�, на Ñ�ледующей неделе, меÑ�Ñ�це, году и дальше года. ИÑ�точник: [руководÑ�тво § 17.25.2](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). + +**[ПРОЕКТ]** ПредпиÑ�ать **непереÑ�екающиеÑ�Ñ� временные корзины** длÑ� введённых Ñ�лементов, иÑ�ключаÑ� Unseen: + +```text +OVERDUE: next_review_at <= now +TODAY: now < next_review_at < end_of_current_local_day +WEEK: end_today <= next_review_at < now + 7d +MONTH: now+7d <= next_review_at < now + 30d +YEAR: now+30d <= next_review_at < now + 365d +LATER: next_review_at >= now + 365d +``` + +ТочнаÑ� граница календарных «неделÑ�/меÑ�Ñ�ц/год» должна быть определена в единой функции Ñ� Ñ�вным чаÑ�овым поÑ�Ñ�ом. Более однозначный вариант длÑ� API — корзины по фикÑ�ированным `7/30/365` Ñ�уткам, а длÑ� UI — локальный календарь. Ð’ одной модели Ñ�мешивать нельзÑ�. + +**Проверка:** Ñ�умма корзин = `T - Unseen` (у каждого введённого Ñ�лемента еÑ�ть `next_review_at`). График можно Ñ�троить по любому репертуару и ветке. + +### 13.3. Sequences — длины Ñ�ерий + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo имеет две гиÑ�тограммы длины поÑ�ледовательных правильных и неправильных ответов (1, 2, 3, …) и третью — Ñ�колько ходов было Ñ�ыграно 1, 2, 3… раз. ИÑ�точник: [§ 17.25.2](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). + +**[ПРОЕКТ]** + +```text +CorrectStreakHistogram[k] = count(item in S: item.correct_streak = k) +WrongStreakHistogram[k] = count(item in S: item.wrong_streak = k) +AttemptsHistogram[k] = count(item in S: item.correct_i + item.wrong_i = k) +``` + +Добавить категорию `0` в раÑ�чётах, но при отображении можно Ñ�крывать её или выводить отдельной колонкой «Без проверок». ЕÑ�ли чиÑ�ло Ñ�ерий больше 20, поÑ�ледний Ñ�толбец может быть `20+`; Ñ�умма по отображаемым Ñ�толбцам должна Ñ�охранÑ�тьÑ�Ñ�. + +### 13.4. Дополнительные графики — [ПРОЕКТ] + +- Accuracy по днÑ�м — Ñ�амоÑ�тоÑ�тельные попытки в выбранный день, без подÑ�казок. +- ЧаÑ�тота ошибок по веткам — `wrong / (correct + wrong)`, при наличии попыток. +- Самые проблемные позиции — ранжирование по ошибкам и уÑ�тойчивоÑ�ти ошибки. +- УчебнаÑ� нагрузка — количеÑ�тво проверок по днÑ�м и ожидаемые Due на будущее. +- ВремÑ� решениÑ� — медиана по веткам. + +Ð�е Ñ�мешивать Ñ�татиÑ�тику изучениÑ� дебютов Ñ� engine accuracy, win rate в партиÑ�Ñ… или качеÑ�твом позиционной оценки: Ñ�то **разные метрики**. + +## 14. Resistant — уÑ�тойчиво проблемные ходы + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo выделÑ�ет повторÑ�ющиеÑ�Ñ� проблемные ходы как `Resistant`, имеет виртуальные общие репертуары таких ходов отдельно за белых и чёрных, а длÑ� выхода из Resistant требует более одного правильного ответа подрÑ�д. **[Ð�ЕИЗВЕСТÐ�О]** КонкретнаÑ� формула вÑ�туплениÑ�/выхода в категорию публично не раÑ�крыта. ИÑ�точник: [руководÑ�тво § 17.4.5](https://www.chesstempo.com/manual/en/manual.html#resistantrepertoires). + +**[ПРОЕКТ]** Формула, пригоднаÑ� длÑ� первой реализации: + +```text +becomes_resistant = attempts_in_last_10 >= 5 AND wrong_in_last_10 >= 3 +exits_resistant = 3 independent correct answers in a row since last error +``` + +Это **отдельный флаг**, а не пÑ�тый взаимоиÑ�ключающий Ñ�татуÑ�. `Resistant = true` Ñ�овмеÑ�тим Ñ� `Learning`; поÑ�ле воÑ�Ñ�тановленной Ñ�ерии теоретичеÑ�ки может кратковременно Ñ�овмещатьÑ�Ñ� Ñ� Learnt, еÑ�ли наÑ�тройки выхода отличаютÑ�Ñ�. СтатиÑ�тика Resistant выводитÑ�Ñ� отдельной Ñ�трокой и **не прибавлÑ�етÑ�Ñ�** к Total. + +## 15. СброÑ� и изменение Ñ�труктуры репертуара + +### 15.1. Reset training + +**[ПОДТВЕРЖДЕÐ�О]** ChessTempo Ñ�браÑ�ывает Ñ�татиÑ�тику и раÑ�пиÑ�ание SRS до Unseen. ПоÑ�кольку общие позиции разделÑ�ÑŽÑ‚Ñ�Ñ� между репертуарами, Ñ�броÑ� одного репертуара может затронуть Ñ�татиÑ�тику того же Ñ�лемента в другом. ИÑ�точник: [руководÑ�тво § 17.24.3](https://www.chesstempo.com/manual/en/manual.html#resettraining). + +**[ПРОЕКТ]** Перед Ñ�броÑ�ом показывать предупреждение: «Из N Ñ�браÑ�ываемых учебных Ñ�лементов M иÑ�пользуютÑ�Ñ� также другими репертуарами». Варианты безопаÑ�ной операции: + +- `Reset shared learning data` — очиÑ�тить общую иÑ�торию и длÑ� переÑ�екающихÑ�Ñ� репертуаров (аналог Ñ�емантики ChessTempo). +- `Reset selected view only` — **не поддерживать**, еÑ�ли нет незавиÑ�имой Ñ�татиÑ�тики по конкретному репертуару: нельзÑ� обещать изолированный Ñ�броÑ� одного и того же учебного Ñ�лемента при глобальном ключе. + +`Reset Review Order` менÑ�ет только прогреÑ�Ñ� порÑ�дка обхода, оÑ�тавлÑ�Ñ� SRS без изменений. + +### 15.2. Добавление/удаление/отключение ходов + +- Добавленный активный обучаемый ход увеличивает `T` и `Unseen`; прогреÑ�Ñ� % может уменьшитьÑ�Ñ� **без ухудшениÑ� памÑ�ти**. +- Отключённый ход иÑ�чезает из активного набора `S`, но его иÑ�ториÑ� Ñ�охранÑ�етÑ�Ñ� длÑ� обратного включениÑ�. +- Удаление ветки не должно Ñ�тирать общую позицию, еÑ�ли на неё еÑ�ть Ñ�Ñ�ылки из других веток/репертуаров. +- Переименование/изменение комментариÑ� не менÑ�ет иÑ�торию обучениÑ�. +- При изменении корневой позиции необходимо переÑ�читать доÑ�тижимоÑ�ть и предупреждать о маÑ�штабных изменениÑ�Ñ… T. + +### 15.3. Импорт/Ñ�кÑ�порт PGN + +Поддержать вложенные вариации, комментарии, NAG и транÑ�позиции, объединение Ñ� Ñ�ущеÑ�твующим репертуаром, включение/отключение ходов. ЭкÑ�портировать репертуары отдельно по именам и цветам. **Ð�е раÑ�Ñ�читывать**, что обычный PGN Ñ�одержит иÑ�торию SRS: длÑ� неё нужен отдельный резервный формат (например, JSON backup Ñ� верÑ�иÑ�ми Ñ�хемы). + +## 16. ПользовательÑ�кие Ñ�ценарии + +### Сценарий A. Создание и первый урок + +Пользователь импортирует PGN за белых, видит `T=120`, `Unseen=120`, `Learnt=0`, `Due=0`. Ð�ажимает «Изучить новые ходы». СиÑ�тема показывает нужный контекÑ�Ñ‚, обучает выбранный ответ, Ñ�тавит ближайшую проверку. `CoveragePercent` раÑ�тёт, а `LearntPercent` ещё равен нулю. + +### Сценарий B. ПоÑ�ле трёх правильных ответов + +Один и тот же учебный ход правильно воÑ�произведён три раза подрÑ�д **Ñ�амоÑ�тоÑ�тельно**, Ñ� Ñ�облюдением интервалов SRS. Его `correct_streak = 3`, Ñ�татуÑ� `Learnt`. Сводный Ñ�чётчик Learnt увеличиваетÑ�Ñ� на 1, Learning уменьшаетÑ�Ñ� на 1. СледующаÑ� проверка **вÑ�Ñ‘ равно запланирована**. + +### Сценарий C. Ошибка поÑ�ле изучениÑ� + +Ход был Learnt (`correct_streak=5`). Пользователь ошибÑ�Ñ�: `correct_streak=0`, Ñ�татуÑ� `Learning`, правильный ход показан, назначено Ñ�корое повторение. ПодÑ�казанное иÑ�правление не возвращает Learnt. + +### Сценарий D. СтатиÑ�тика Ñ�тановитÑ�Ñ� Uncertain без новой ошибки + +Ход был Learnt, но Ñ� даты `next_review_at` прошло больше уÑ�тановленного grace-периода. Без дейÑ�твиÑ� пользователÑ� он попадает в `Uncertain`. `Learnt` как чиÑ�ло иÑ�торичеÑ�ки доÑ�тигших порога **не увеличиваетÑ�Ñ�**, но «актуально подтверждено» уменьшаетÑ�Ñ�. Правильный Ñ�амоÑ�тоÑ�тельный ответ Ñ�нимает Uncertain. + +### Сценарий E. ОбщаÑ� позициÑ� двух дебютов + +Один учебный ход приÑ�утÑ�твует в двух репертуарах. Пользователь правильно ответил в первом — во втором одновременно отображаютÑ�Ñ� новаÑ� Ñ�ериÑ� и новое времÑ� проверки. Ð’ глобальном `T` Ñ�тот ход учитываетÑ�Ñ� только один раз. + +### Сценарий F. За Ñ�егоднÑ� вÑ�Ñ‘ повторено + +`Due=0`, `Learning=20`, `Unseen=10`. UI не пишет «репертуар выучен», а Ñ�ообщает, что текущие плановые проверки закончилиÑ�ÑŒ, и предлагает либо завершить занÑ�тие, либо вручную добавить новый материал. + +### Сценарий G. Глубина тренировки + +Ð’ репертуаре 100 ходов, но до уÑ�тановленной глубины доÑ�тупно только 40. Сводка тренировочной облаÑ�ти показывает 40, полнаÑ� Ñ�татиÑ�тика — 100, обе подпиÑ�аны Ñ�воими охватами. Ð�и один ход не терÑ�етÑ�Ñ�. + +## 17. Структура данных длÑ� разработчика + +Пример рекомендуемой релÑ�ционной Ñ�хемы (имена иллюÑ�тративные): + +```sql +CREATE TABLE learning_item ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + position_key TEXT NOT NULL, + expected_move_uci VARCHAR(8) NOT NULL, + introduced BOOLEAN NOT NULL DEFAULT FALSE, + correct_count INT NOT NULL DEFAULT 0, + wrong_count INT NOT NULL DEFAULT 0, + correct_streak INT NOT NULL DEFAULT 0, + wrong_streak INT NOT NULL DEFAULT 0, + last_review_at TIMESTAMPTZ, + last_correct_at TIMESTAMPTZ, + next_review_at TIMESTAMPTZ, + previous_interval_seconds BIGINT, + resistant BOOLEAN NOT NULL DEFAULT FALSE, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (user_id, position_key, expected_move_uci) +); + +CREATE TABLE training_attempt ( + id UUID PRIMARY KEY, + user_id BIGINT NOT NULL, + learning_item_id BIGINT NOT NULL REFERENCES learning_item(id), + session_id UUID NOT NULL, + event_type VARCHAR(32) NOT NULL, + expected_move_uci VARCHAR(8) NOT NULL, + played_move_uci VARCHAR(8), + response_time_ms BIGINT, + happened_at TIMESTAMPTZ NOT NULL, + settings_version TEXT NOT NULL, + UNIQUE (session_id, id) +); + +CREATE INDEX idx_learning_due ON learning_item (user_id, next_review_at) + WHERE introduced = TRUE; +CREATE INDEX idx_attempt_item_time ON training_attempt (learning_item_id, happened_at); +``` + +Отдельные таблицы нужны длÑ� `Repertoire`, `Position`, `MoveEdge`, `RepertoireEdge`, членÑ�тва репертуара, Ñ�еÑ�Ñ�ий и ежедневных Ñ�нимков. Ð’ `TrainingAttempt` желательно добавить ID идемпотентноÑ�ти **от клиента**, чтобы повторный Ñ�етевой запроÑ� не Ñ�оздавал вторую попытку: `UNIQUE(user_id, client_attempt_id)`. + +Сложные агрегаты Ñ�читать как `COUNT(DISTINCT learning_item.id)` по выбранному `scope`. **Ð�е группировать по SQL-Ñ�троке полного FEN**, еÑ�ли ключ позиции нормализован другим алгоритмом. + +## 18. API: контракт Ñ�татиÑ�тики — [ПРОЕКТ] + +### 18.1. ОбÑ�зательные конечные точки + +```text +GET /api/repertoires/{id}/stats?scope=full|training&depth=... +GET /api/repertoires/{id}/stats/history?from=...&to=... +GET /api/repertoires/{id}/stats/scheduled +GET /api/repertoires/{id}/stats/sequences +GET /api/repertoires/{id}/stats/branches +GET /api/learning-items/{id}/stats +POST /api/training-sessions +POST /api/training-sessions/{id}/attempts +POST /api/repertoires/{id}/reset-training +POST /api/repertoires/{id}/reset-review-order +``` + +### 18.2. Пример Ñ�водного ответа + +```json +{ + "repertoire_id": 12, + "as_of": "2026-11-04T12:00:00Z", + "scope": {"max_depth": null, "only_active": true, "distinct_transpositions": true}, + "total": 100, + "unseen": 10, + "learning": 20, + "learnt": 70, + "uncertain": 15, + "learnt_confident": 55, + "due": 25, + "next_due_at": null, + "coverage_percent": 90.0, + "learnt_percent": 70.0, + "confident_percent": 55.0, + "repertoire_status": "IN_PROGRESS", + "accuracy_percent": 74.6, + "accuracy_attempts": 280, + "resistant": 7 +} +``` + +`next_due_at` здеÑ�ÑŒ `null`, поÑ�кольку уже еÑ�ть Due; при Due=0 должна быть минимальнаÑ� будущаÑ� дата (или null, еÑ�ли ни одного введённого Ñ�лемента нет). + +API должен возвращать **вÑ�е** чиÑ�ла, из которых раÑ�Ñ�читаны проценты. Frontend не должен Ñ�амоÑ�тоÑ�тельно Ñ�уммировать переÑ�екающиеÑ�Ñ� категории и менÑ�ть знаменатель. + +## 19. Обновление Ñ�татиÑ�тики и техничеÑ�каÑ� конÑ�иÑ�тентноÑ�ть + +- Ð’Ñ�е Ñ�обытиÑ� запиÑ�ываютÑ�Ñ� Ñ�ервером. Клиент не уÑ�танавливает Ñ�ам `Learnt` или `Due`. +- ВремÑ� `happened_at` и раÑ�чёт интервала — Ñ�ерверное UTC; календарные графики конвертируютÑ�Ñ� в чаÑ�овой поÑ�Ñ� пользователÑ�. +- Обновление Ñ�ерии, агрегатов, Ñ�ледующего Ñ�рока и запиÑ�ÑŒ попытки атомарны. +- ПовторнаÑ� доÑ�тавка одного `client_attempt_id` возвращает прежний результат, не изменÑ�Ñ� Ñ�чётчики. +- ИÑ�торичеÑ�кие Ñ�нимки в конце днÑ� Ñ�троÑ�Ñ‚Ñ�Ñ� в одном и том же чаÑ�овом поÑ�Ñ�е; при изменении зоны отображение должно иметь Ñ�вную политику. +- ИÑ�торичеÑ�кие изменениÑ� поÑ�ле удалениÑ�/отключениÑ� хода не должны перепиÑ�ывать прежние Ñ�нимки без отдельной команды переÑ�чёта. +- РаÑ�пиÑ�ание не должно ломатьÑ�Ñ� при одновременных Ñ�еÑ�Ñ�иÑ�Ñ… одного пользователÑ�. ДлÑ� учебного Ñ�лемента требуетÑ�Ñ� блокировка Ñ�троки/optimistic version. +- При маÑ�Ñ�овом переÑ�чёте нужно поддерживать `as_of`, чтобы вÑ�е Ñ�чётчики одного ответа Ñ�троилиÑ�ÑŒ на одном моменте времени. +- Проектировать агрегаты так, чтобы `T = Unseen + Learning + Learnt` вÑ�егда проходил проверку. + +## 20. Проверки/критерии приёмки (обÑ�зательные) + +| ID | Проверка | ОжидаетÑ�Ñ� | +|---|---|---| +| AT-01 | 100 новых ходов | `T=100, Unseen=100, Learning=0, Learnt=0, Due=0` | +| AT-02 | Первый Ñ�амоÑ�тоÑ�тельный правильный ответ | `correct_streak=1`, Learning, next due +1 день | +| AT-03 | Третий ответ подрÑ�д без подÑ�казок | `correct_streak=3`, Learnt | +| AT-04 | Ошибка поÑ�ле Learnt | `correct_streak=0`, Learning, ближайший повтор через 30 Ñ�екунд | +| AT-05 | Повтор показанного правильного хода поÑ�ле ошибки | Ð�ет дополнительного Ñ�амоÑ�тоÑ�тельного уÑ�пеха | +| AT-06 | Превью перед ответом | Результат `PREVIEWED`, next due +1 минута, streak не раÑ�тёт | +| AT-07 | Ð�ет Due, но еÑ�ть Unseen | UI не выводит «вÑ�Ñ‘ изучено», предлагает новые ходы | +| AT-08 | Learnt и Due одновременно | Должен входить и в Learnt, и в Due | +| AT-09 | Learnt проÑ�рочен за grace-период | Входит в Uncertain, но не Ñ�уммируетÑ�Ñ� к T | +| AT-10 | Uncertain правильно повторён | СнимаетÑ�Ñ� Uncertain, оÑ�таётÑ�Ñ� Learnt | +| AT-11 | Uncertain решён ошибочно | Learning, Ñ�ледующий повтор по ошибке | +| AT-12 | 7 уÑ�пехов + 3 ошибки | Accuracy = 70%, отдельно от Ñ�татуÑ�а изученноÑ�ти | +| AT-13 | Ð�ет попыток | Accuracy = null, UI: `—` | +| AT-14 | Общий ход двух репертуаров | Одна запиÑ�ÑŒ LearningItem, Ñ�татиÑ�тика общаÑ� | +| AT-15 | ГлобальнаÑ� агрегациÑ� двух переÑ�екающихÑ�Ñ� репертуаров | Общий T Ñ�читаетÑ�Ñ� через объединение, без дублированиÑ� | +| AT-16 | У репертуара 0 активных ходов | Status EMPTY, проценты не равны 100% | +| AT-17 | МакÑ�имальнаÑ� глубина = 10 полуходов | Сводка менÑ�ет охват; полный график оÑ�таётÑ�Ñ� полным по Ñ�оответÑ�твующей наÑ�тройке | +| AT-18 | Отключить ветку | Она иÑ�чезает из активной Ñ�татиÑ�тики, иÑ�ториÑ� не удалÑ�етÑ�Ñ� | +| AT-19 | Включить ветку обратно | ИÑ�ториÑ� и предыдущий correct_streak воÑ�Ñ�тановлены | +| AT-20 | Review in Order | Каждый целевой Ñ�лемент один раз за цикл, SRS также обновлÑ�етÑ�Ñ� | +| AT-21 | Wrong в Variation mode | Ð�е вытеÑ�нÑ�ет иÑ�ходную очередь Ñ�разу; повтор возможен в Ñ�ледующем проходе | +| AT-22 | СброÑ� одного репертуара Ñ� общими позициÑ�ми | Явное предупреждение и корректное поÑ�ледÑ�твие длÑ� второго | +| AT-23 | Два одинаковых Ñ�етевых ответа | Один учтённый TrainingAttempt | +| AT-24 | Два разных порÑ�дка ходов, одна позициÑ� | Одна учебнаÑ� запиÑ�ÑŒ, одинаковый прогреÑ�Ñ� | +| AT-25 | Изменение Ñ�оÑ�тава репертуара на +20 ходов | T и проценты переÑ�читываютÑ�Ñ�, Ñ�тарые уÑ�пехи оÑ�таютÑ�Ñ� | +| AT-26 | Сумма корзин Scheduled | Ровно равна количеÑ�тву введённых Ñ�лементов | +| AT-27 | Снимки иÑ�тории без новых попыток | Uncertain может увеличитьÑ�Ñ� Ñ� течением времени | +| AT-28 | Сводка 100/100 Learnt, Due=3 | СтатуÑ� ALL_LEARNT, не CONFIRMED_CURRENT | +| AT-29 | Сводка 100/100 Learnt, Due=0, Uncertain=0 | CONFIRMED_CURRENT | +| AT-30 | СтатиÑ�тика линии и репертуара | ЛиниÑ� может учитывать переÑ�ечениÑ�; общий итог дедуплицируетÑ�Ñ� | + +### ОÑ�обые математичеÑ�кие инварианты + +```text +T == Unseen + Learning + Learnt +Uncertain <= Learnt +LearntConfident == Learnt - Uncertain +CoveragePercent >= LearntPercent >= ConfidentPercent +0 <= each percentage <= 100 +Due <= (Learning + Learnt) +GlobalTotal <= sum(T per repertoire) +AccuracyPercent is null OR 0 <= AccuracyPercent <= 100 +``` + +Любое нарушение должно региÑ�трироватьÑ�Ñ� в логах/метриках, а теÑ�ты обÑ�заны падать. + +## 21. ИнтерфейÑ�: минимальный набор Ñ�кранов + +### 21.1. Редактор репертуара + +ШахматнаÑ� доÑ�ка, дерево ходов, имÑ�/цвет, главное и побочные продолжениÑ�, комментарии, импорт/Ñ�кÑ�порт, переключатель активноÑ�ти ветки. ВыбраннаÑ� позициÑ� показывает её учебные показатели и Ñ�Ñ�ылку на вÑ�е репертуары, где она вÑ�тречаетÑ�Ñ�. + +### 21.2. Экран тренировки + +ДоÑ�ка, название репертуара/ветки, прогреÑ�Ñ� текущей Ñ�еÑ�Ñ�ии, «Повторить Ñ�ейчаÑ�: N», Ñ�ообщениÑ� об ошибке/подÑ�казке, кнопка паузы. Ð’ обычном режиме нельзÑ� заранее показывать решение. ЕÑ�ли при новом ходе включена автоподÑ�казка, UI и API должны отметить попытку как `PREVIEWED`. + +### 21.3. Дашборд репертуара + +Верх: главные KPI — `T`, `Unseen`, `Learning`, `Learnt`, `Uncertain`, `Due`, `% изучено`, `% актуально`, `NextDueAt`. + +Ð�иже: график иÑ�тории, раÑ�пределение раÑ�пиÑ�аниÑ�, Ñ�ерии ответов, раÑ�пределение чиÑ�ла попыток и Ñ�пиÑ�ок проблемных ходов. Ð’Ñ�е чиÑ�ла завиÑ�Ñ�Ñ‚ от Ñ�вно выбранного `scope`. + +### 21.4. Общий дашборд + +Сравнение репертуаров за белых/чёрных; глобальный прогреÑ�Ñ� **без повторного подÑ�чёта переÑ�екающихÑ�Ñ� Ñ�лементов**; учебнаÑ� нагрузка и Ñ�пиÑ�ок того, что требует дейÑ�твий Ñ�егоднÑ�. Разница между Ñ�уммой по Ñ�трокам и глобальным итогом объÑ�Ñ�нÑ�етÑ�Ñ� вÑ�плывающей подÑ�казкой. + +## 22. Этапы разработки + +**MVP:** граф позиций и PGN, редактор, `LearningItem`, `TrainingAttempt`, правильный/неправильный ответ, 3 подрÑ�д, SRS, Due, транÑ�позиции, базоваÑ� таблица показателей и математичеÑ�кие инварианты. + +**V1:** три режима тренировки, четыре приоритета нового материала, контекÑ�Ñ‚ и reinforcement, иÑ�тории/графики, ветки, Ñ�нимки, предупреждение при Ñ�броÑ�е, подробные ошибки, динамичеÑ�кие Uncertain и Resistant. + +**V2:** Ñ�инхронизациÑ� дебютной базы, движковые оценки, Sunburst, анализ Ñ�ыгранных партий, раÑ�ширеннаÑ� аналитика качеÑ�тва репертуара, режим Ñ�оревнований. + +## 23. Открытые вопроÑ�Ñ‹, которые нельзÑ� выдавать за факты ChessTempo + +1. **Порог Uncertain:** подтверждено только, что ход доÑ�таточно Ñ�ильно проÑ�рочен. ТочнаÑ� продолжительноÑ�ть не найдена. Ð’ Ñ�том ТЗ предложена формула Ñ� конфигурируемым grace-периодом. +2. **Формула Resistant:** не раÑ�крыта; предложено правило «≥3 ошибок Ñ�реди поÑ�ледних ≥5 проверок из окна 10» и выход поÑ�ле трёх правильных подрÑ�д. +3. **Формула дебютного Accuracy:** Ñ�ам показатель отображаетÑ�Ñ�, но точнаÑ� Ñ�ервернаÑ� формула длÑ� дебютного тренажёра не опубликована. Предложено `correct/(correct+wrong)` только по Ñ�амоÑ�тоÑ�тельным проверкам. +4. **Сложные Ñ�лучаи SRS:** извеÑ�тны дефолты, коÑ�ффициент роÑ�та и пример Ñ� фактичеÑ�ки прошедшими четырьмÑ� днÑ�ми, но не вÑ�е граничные Ñ�лучаи. ПÑ�евдокод выше — воÑ�производимый проектный вариант. +5. **Ð�льтернативные Ñ�обÑ�твенные ходы:** нужен продуктовый выбор Ñ�трогого или Ñ�вободного режима. Ð’ MVP выбран один обÑ�зательный ответ на позицию. +6. **Знаменатель Moves в абÑ�олютном Ñ�оответÑ�твии ChessTempo:** точнаÑ� внутреннÑ�Ñ� трактовка каждой категории Ñ�ложного графа не раÑ�крыта. Ð’ ТЗ принÑ�Ñ‚ однозначный набор уникальных активных Ñ�обÑ�твенных учебных Ñ�лементов. +7. **«ВеÑ�ÑŒ дебют изучен»:** бинарного подтверждённого глобального критериÑ� ChessTempo нет. ДлÑ� продукта введены Ñ�вные формулы `ALL_LEARNT` и `CONFIRMED_CURRENT`. +8. **ЭкÑ�порт Ñ�татиÑ�тики:** PGN не должен раÑ�Ñ�матриватьÑ�Ñ� как резервнаÑ� копиÑ� SRS, еÑ�ли иÑ�ториÑ� отдельно не Ñ�ериализуетÑ�Ñ�. + +## 24. ИÑ�точники длÑ� проверки реализации + +Официальные: + +1. [ChessTempo — Opening Training](https://www.chesstempo.com/opening-training/). +2. [ChessTempo User Guide, § 17 Opening Training](https://www.chesstempo.com/manual/en/manual.html#openingtraining). +3. [ChessTempo User Guide, § 17.4 Training Mode](https://www.chesstempo.com/manual/en/manual.html#trainingmode). +4. [ChessTempo User Guide, § 17.15 Settings](https://www.chesstempo.com/manual/en/manual.html#openingtrainingsettings). +5. [ChessTempo User Guide, § 17.25 Graphs and Statistics](https://www.chesstempo.com/manual/en/manual.html#graphsandstatistics). +6. [ChessTempo User Guide, § 10.5 Repertoire Stats](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). +7. [ChessTempo FAQ](https://www.chesstempo.com/faq/). + +Ответы разработчика: + +8. [«Opening training no more positions to schedule yet?» — прÑ�мое определение 3 правильных подрÑ�д, Unseen/Learning/Learnt/Uncertain](https://chesstempo.com/forum/topic/opening-training-no-more-positions-to-schedule-yet/9962/). +9. [«Trying to understand how opening training works with the scheduling option?» — Due, Learnt N/T, разбор Ñ�татиÑ�тики](https://chesstempo.com/forum/topic/trying-to-understand-how-opening-training-works-with-the-scheduling-option/10924/). +10. [«Opening Training Best Practice» — почему логично оÑ�танавливатьÑ�Ñ� при Due=0](https://chesstempo.com/forum/topic/opening-training-best-practice/12249/). +11. [«Moves stuck in learning» — Ñ�татуÑ� завиÑ�ит от Ñ�ерии правильных ходов](https://chesstempo.com/forum/topic/moves-stuck-in-learning/11361/). + +**РекомендациÑ� по реализации:** разработчик должен начать не Ñ� графиков, а Ñ� однозначной модели `LearningItem` и детерминированных unit-теÑ�тов из § 20. Тогда интерфейÑ� и проценты будут лишь разными проекциÑ�ми одних и тех же непротиворечивых данных. diff --git a/docs/decisions.md b/docs/decisions.md new file mode 100644 index 0000000..4ca09b8 --- /dev/null +++ b/docs/decisions.md @@ -0,0 +1,575 @@ +# РешениÑ� и открытые вопроÑ�Ñ‹ + +## Подтверждено пользователем — 2026-10-17 + +1. **Открытый иÑ�ходный код.** Можно выбирать GPL-Ñ�овмеÑ�тимый Ñ�тек. КонкретнаÑ� лицензиÑ� проекта пока не утверждена. +2. **ПерваÑ� целеваÑ� нагрузка — книги и учебные базы:** Ñ�отни и тыÑ�Ñ�чи аннотированных партий, как в предоÑ�тавленных примерах. Работа Ñ� миллионами партий не Ñ�влÑ�етÑ�Ñ� критерием первой верÑ�ии. +3. **Редактирование первой верÑ�ии — ходы, варианты и Ñ�кÑ�порт:** проÑ�мотр Ñ�ущеÑ�твующих комментариев, ввод ходов и ветвей, копирование PGN и Ñ�охранение отдельным файлом. Полный редактор комментариев, заголовков и маÑ�Ñ�овое изменение иÑ�ходной базы не входÑ�Ñ‚ в Ñ�оглаÑ�ованный первый объём. + +4. **UI-Ñ�тек — Rust + egui/eframe 0.36** (линиÑ� PhotoCraft/craft-ui), правила и PGN — shakmaty 0.30 + pgn-reader 0.29. Подтверждено 2026-10-17. +5. **ЛицензиÑ� проекта — GPL-3.0-or-later.** Подтверждено 2026-10-17. + +6. **Разбор PGN — Ñ�обÑ�твенный лекÑ�ер по иÑ�ходным байтам + shakmaty длÑ� SAN/правил.** pgn-reader 0.29.1 молча пропуÑ�кает нераÑ�познанные токены и не даёт байтовых Ñ�мещений (запиÑ�ÑŒ â„–335 учебника терÑ�ла текÑ�Ñ‚), поÑ�тому он оÑ�тавлен только как незавиÑ�имый Ñ�талон в теÑ�тах. Решение оркеÑ�тратора Ñ� ведома пользователÑ�, 2026-10-17. + +7. **Ð�азвание — ChessPenguin** (2026-10-18). Бинарник и пакеты `chesspenguin`, app id `io.github.vrubelroman.chessPenguin`, наÑ�тройки в `~/.config/chesspenguin` (Ñ�тарые переноÑ�Ñ�Ñ‚Ñ�Ñ� автоматичеÑ�ки). +8. **ПубликациÑ�** — https://github.com/vrubelroman/chessPenguin, чиÑ�таÑ� иÑ�ториÑ� без `designExample/` (чужие Ñ�криншоты оÑ�таютÑ�Ñ� только локально). ВерÑ�ии по SemVer, перваÑ� — `0.1.0`, тег `v0.1.0`; релизы Ñ�обирает GitHub Actions по тегу `v*`: deb, rpm, AppImage, Flatpak, Windows zip. + +9. **Ð�нализ партии (верÑ�иÑ� 0.2)** — 2026-10-18, по Ñ�хеме, предложенной оркеÑ�тратором и принÑ�той пользователем: + - живой движок (оценка текущей позиции, `L`) и анализ партии целиком — разные процеÑ�Ñ�Ñ‹ и разные кнопки; на времÑ� анализа партии живой движок Ñ�тавитÑ�Ñ� на паузу и затем возобновлÑ�етÑ�Ñ�; + - кнопка 📈 «Ð�нализ партии» — в нижней панели инÑ�трументов, правее «Копировать PGN» (Ñ�начала была в шапке; перенеÑ�ена по проÑ�ьбе пользователÑ�), `Shift+A`; во времÑ� работы — прогреÑ�Ñ� и отмена, поÑ�ле — та же кнопка («Отчёт») Ñ�крывает/показывает результаты; + - график оценки — полоÑ�ой под доÑ�кой (шкала — шанÑ� на победу, как на Lichess), клик/протÑ�жка переходит к ходу, отмечены Ñ�тадии партии и ошибки; + - Ñ�татиÑ�тика — вкладкой «Отчёт» Ñ€Ñ�дом Ñ� нотацией: неточноÑ�ти/ошибки/зевки (клик — к Ñ�ледующей), Ñ�реднÑ�Ñ� потерÑ� Ñ�антипешек, точноÑ�ть и точноÑ�ть по Ñ�тадиÑ�м; кнопки «разобрать Ñ�вои ошибки» нет — Ñ�мотрим чужие партии; + - отметки движка в нотации — отдельным Ñ�лоем (цветной значок), партиÑ� не менÑ�етÑ�Ñ�; «ЗапиÑ�ать анализ в партию» — отдельное дейÑ�твие Ñ� одним шагом отмены (NAG, комментарий, лучший вариант, `[%eval]`); + - анализируетÑ�Ñ� только оÑ�новнаÑ� линиÑ�; результаты кÑ�шируютÑ�Ñ� в `~/.cache/chesspenguin/analysis/`; при правке оÑ�новной линии дооцениваютÑ�Ñ� только новые позиции; оценки `[%eval]` из PGN иÑ�пользуютÑ�Ñ� без движка; + - методика — опубликованные формулы Lichess (lichess.org/page/accuracy), реализованы заново. + +10. **Stockfish в комплекте** — 2026-10-18, решение пользователÑ�: вкладываем во вÑ�е пакеты (deb, rpm, Arch, AppImage, Flatpak, Windows, tar.gz), не полагаемÑ�Ñ� на Ñ�иÑ�темные пакеты. Официальный «universal»-бинарник Stockfish 19 без изменений (верÑ�иÑ� и SHA-256 закреплены в `packaging/stockfish.sh`), в пакетах — `/lib/chesspenguin/stockfish` или `stockfish/` Ñ€Ñ�дом Ñ� exe; в наÑ�тройках вÑ�троенный движок хранитÑ�Ñ� признаком `builtin`, путь вычиÑ�лÑ�етÑ�Ñ� при запуÑ�ке (точка монтированиÑ� AppImage менÑ�етÑ�Ñ�). При первом запуÑ�ке без движков добавлÑ�етÑ�Ñ� вÑ�троенный, иначе Ñ�иÑ�темный `stockfish`. ЛицензиÑ� GPL-3.0 выполнÑ�етÑ�Ñ�: текÑ�Ñ‚ лицензии и AUTHORS в пакете, архив иÑ�ходников прикладываетÑ�Ñ� к каждому релизу. Пакеты выроÑ�ли до ~95 МБ. + +11. **Чтение ChessBase и архивов** — 2026-10-18, план принÑ�Ñ‚ пользователем («прÑ�м вдумчиво, грамотно»): Ñ�обÑ�твенный крейт `chess-import` (контейнер `.cbv` по uncbv, формат базы по открытому опиÑ�анию Morphy; cbvault и uncbv — только Ñ�талоны при проверке), `.cbh` Ñ� файлами Ñ€Ñ�дом, `.cbv`, `.zip` и `.7z` Ñ� PGN/ChessBase внутри. Ð’Ñ�Ñ‘ переводитÑ�Ñ� в PGN в памÑ�ти и открываетÑ�Ñ� как обычнаÑ� база, только длÑ� чтениÑ�; проблемы видны в «ЗамечаниÑ�Ñ… импорта». `.cbz` (пароль) и 2CBH — понÑ�тное Ñ�ообщение. ПодробноÑ�ти — `docs/dev/import.md`. + +12. **Большие базы ChessBase** — 2026-10-19, решение пользователÑ� по предложению оркеÑ�тратора (повод — Mega Database 2026: 11,7 млн партий, 4,7 ГБ). УточнÑ�ет пункт 2: базы на миллионы партий теперь в объёме. + - ДобавлÑ�ÑŽÑ‚Ñ�Ñ� тем же «+ Добавить базу»; `.cbh` на диÑ�ке читаетÑ�Ñ� напрÑ�мую, без перевода вÑ�ей базы в PGN: Ñ�троки таблицы — из запиÑ�ей `.cbh` и Ñ�правочников `.cbp/.cbt/.cbc`, партиÑ� разбираетÑ�Ñ� при открытии и дальше идёт обычным путём (нотациÑ�, движок, «Сохранить как PGN»). Ð�рхивы и `.cbv` — по-Ñ�тарому, в памÑ�ти. + - У большой базы Ñ�права от таблицы — панель фильтров (игрок, турнир, годы, Эло, ECO, результат и Ñ‚. п.), фильтр применÑ�етÑ�Ñ� Ñ�разу; проход по запиÑ�Ñ�м — в фоне. ПодробноÑ�ти компоновки — `docs/design/large-databases.md`. + - ПоиÑ�к по позиции — позже, отдельной задачей. + - ИÑ�ходные файлы только читаютÑ�Ñ�. + +13. **ПоиÑ�к по позиции на доÑ�ке** — 2026-10-19, решение пользователÑ� («Ñ�о вÑ�ем Ñ�оглаÑ�ен») по итогам иÑ�Ñ�ледований `docs/research/position-search.md`, `docs/research/position-index.md` и проекта `docs/design/board-search.md`. + - Ð’ шапке Ñ�пиÑ�ка партий переключатель `[Фильтры | ДоÑ�ка]`; доÑ�ка — праваÑ� чаÑ�ть окна, таблица ужимаетÑ�Ñ�. Пользователь делает ходы — таблица и Ñ�пиÑ�ок продолжений (партий, полоÑ�а Б/Ð�/Ч, Ñ�редний Эло) обновлÑ�ÑŽÑ‚Ñ�Ñ� Ñ�ами, без кнопки «Ð�айти». ПозициÑ� и фильтры панели дейÑ�твуют вмеÑ�те; над таблицей вÑ�егда видна Ñ�трока уÑ�ловий (чипы Ñ� ×). + - ИщетÑ�Ñ� точнаÑ� позициÑ� Ñ� учётом переходов. ПорÑ�док ходов — не переключатель заранее, а контекÑ�тнаÑ� Ñ�трока «Ñ�тим порÑ�дком ходов — N из M · [только Ñ�тот порÑ�док]», только еÑ�ли еÑ�ть переходы. + - Ð�айденнаÑ� партиÑ� открываетÑ�Ñ� в обычном Ñ�кране партии Ñ�разу на ходе, где вÑ�третилаÑ�ÑŒ позициÑ�; возврат — к той же позиции, фильтрам и Ñ�троке. + - БольшаÑ� база — только оÑ�новнаÑ� линиÑ�, быÑ�трый проход по ходам Ñ� предфильтром `.cbb` (еÑ�ли файл прошёл проверку), без поÑ�тоÑ�нного индекÑ�а; малые базы — разбор в памÑ�ть, поиÑ�к и в вариантах; в книгах продолжениÑ� показывают «N глав» вмеÑ�то результатов. + - С Ñ�крана партии «Ð�айти позицию в базе» — в поÑ�ледней выбранной базе, Ñ� выбором другой. Ð’ режиме доÑ�ки при Ñ�ортировке по умолчанию — Ñ�ильнейшие партии Ñ�верху. Полка Ñ�ворачиваетÑ�Ñ� в Ñ�троку при выÑ�оте окна < 760. «Только Ñ�тот порÑ�док» — в первой верÑ�ии; оценка движка на доÑ�ке поиÑ�ка — Ñ�разу поÑ�ле. + +14. **Stockfish по запроÑ�у вмеÑ�то вÑ�троенного** — 2026-10-19, решение пользователÑ� по предложению оркеÑ�тратора. ПереÑ�матривает п. 10. + - deb, rpm, AppImage, tar.gz, Windows zip, macOS — без движка (пакет ≈ 14 МБ вмеÑ�то ≈ 95); программа предлагает Ñ�качать официальный Stockfish 19 «universal» Ñ� GitHub `official-stockfish/Stockfish` (верÑ�иÑ� и SHA-256 закреплены, файл проверÑ�етÑ�Ñ� до запуÑ�ка) в каталог данных пользователÑ�. Предложение — при первой попытке анализа без движка и кнопкой в «Ð�аÑ�тройки → Движки»; молча при запуÑ�ке ничего не качаетÑ�Ñ�. Без Ñ�ети — Ñ�иÑ�темный `stockfish` или «Указать файл». + - Arch (AUR) — как оÑ�тальные пакеты: без движка, Ñ�о Ñ�качиванием по запроÑ�у; `stockfish` — необÑ�зательнаÑ� завиÑ�имоÑ�ть (`optdepends`). Уточнение 2026-10-19: в официальных репозиториÑ�Ñ… Arch Stockfish нет, только AUR-пакет `stockfish` (Ñ�обираетÑ�Ñ� из иÑ�ходников), поÑ�тому жёÑ�ткой завиÑ�имоÑ�тью он быть не может (первоначальное предложение оркеÑ�тратора было ошибочным). Flatpak — движок оÑ�таётÑ�Ñ� вÑ�троенным (Flathub против Ñ�качиваниÑ� иÑ�полнÑ�емых файлов), поÑ�тому архив иÑ�ходников Stockfish по-прежнему прикладываетÑ�Ñ� к релизу. + - ИнтерфейÑ� — `docs/design/engine-download.md`; «проÑ�то, понÑ�тно, интуитивно» — требование пользователÑ�. + +15. **Сборки длÑ� macOS на Apple Silicon** — 2026-10-19, запроÑ� пользователÑ�: `.app` в `.dmg` Ñ�обирает GitHub Actions (arm64). Пока без подпиÑ�и Apple: при первом запуÑ�ке — «Открыть» через контекÑ�тное меню; подпиÑ�ÑŒ и нотаризациÑ� — когда поÑ�витÑ�Ñ� аккаунт разработчика Apple. + +16. **Приложение длÑ� Android** — 2026-10-22, решениÑ� пользователÑ� по иÑ�Ñ�ледованию `docs/research/android-stack.md` и проекту `docs/design/android-ui.md`. + - Только Android, iOS пока не делаем. Стек: Kotlin + Jetpack Compose, Ñ�дро — наши крейты Rust (`chess-core`, `chess-import`, `uci`) через UniFFI, Ñ�борка `cargo-ndk`. Код — в `androidApp/`. + - Задача — Ñ�мотреть партии: базы тех же форматов, что читает наÑ�тольнаÑ� программа, Ñ�пиÑ�ок партий, партиÑ� Ñ� нотацией под доÑ�кой, лиÑ�тание партий. Ходы не вводÑ�Ñ‚Ñ�Ñ� и не Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�; уход в Ñ�вои ветки без Ñ�охранениÑ� — позже, еÑ�ли понадобитÑ�Ñ�. + - Mega на телефоне не нужна: цель — базы до ~1 млн партий. + - Две APK: Ñ� движком (Stockfish и Ñ�еть внутри) и без (движок Ñ�качиваетÑ�Ñ� по запроÑ�у), обе на GitHub и Ñ�айте Ñ� понÑ�тной подпиÑ�ью. + - Сначала APK на GitHub и Ñ�айте, магазины (F-Droid, Google Play) — потом. APK подпиÑ�ываетÑ�Ñ� Ñ�воим ключом: копиÑ� у пользователÑ� и у наÑ�, терÑ�ть нельзÑ� (без него не выйдут обновлениÑ�). + - Android 12 и новее (minSdk 31). + - ИнтерфейÑ� — «проÑ�то, понÑ�тно, Ñ�импатично»: проект `docs/design/android-ui.md` (§16 — решениÑ� владельца). Тема «Как в Ñ�иÑ�теме»; зелёнаÑ� доÑ�ка и Merida длÑ� вÑ�ех; выбор доÑ�ок, фигур и тем — в Ñ�ледующих верÑ�иÑ�Ñ…. ПодпиÑ�и Ñ�борок: «Stockfish уже внутри» / «Stockfish Ñ�качиваетÑ�Ñ� в приложении». + +## Следует из иÑ�ходного ТЗ + +- Linux desktop; предпочтение Ñ�тека Artcraft, подлежащего проверке по иÑ�ходникам. +- PGN-библиотека Ñ� ранее открытыми файлами, добавлением новых и таблицей партий. +- ДоÑ�ка Ñ� навигацией мышью/клавиатурой, комментариÑ�ми и вариантами. +- Ð�оваÑ� партиÑ� из начальной позиции. +- Выбор UCI-движков из файловой Ñ�иÑ�темы, анализ, проÑ�мотр линий на доÑ�ке и Ñ�трелка лучшего хода. +- Возвращение из партии в библиотеку. +- Ð�аÑ�тройки фигур, доÑ�ки, движков и звуков. + +20. **Свои комментарии в партии** — 2026-10-25, решение пользователÑ� по `docs/research/user-comments.md` и `docs/design/user-comments.md` (уточнÑ�ет пункт 3: редактор комментариев входит в объём): + - редактор — поле прÑ�мо в нотации, на меÑ�те комментариÑ� (в варианте поток режетÑ�Ñ� у хода); комментарий поÑ�ле любого хода, в начале партии; Ñ�ущеÑ�твующие «перед ходом» правÑ�Ñ‚Ñ�Ñ� и удалÑ�ÑŽÑ‚Ñ�Ñ�; + - Enter на ходе открывает, Enter — готово, Esc — отмена (черновик выбраÑ�ываетÑ�Ñ�); переход к другому ходу запиÑ�ывает; Shift+Enter — абзац; + - значки: мышью в меню хода и в редакторе (обе группы — ход и позициÑ�), дополнительно Ctrl+1…6 длÑ� `! ? !! ?? !? ?!`; + - Ñ�трелки и цветные полÑ� правой кнопкой на доÑ�ке — в первой верÑ�ии (цвет: без модификатора зелёный, Shift краÑ�ный, Alt Ñ�иний, Shift+Alt жёлтый; повтор Ñ�нимает); + - 2026-11-26: в игре и тренировках можно держать неÑ�колько временных Ñ�трелок и кругов до Ñ�мены позиции; они не запиÑ�ываютÑ�Ñ� в PGN. Ð’ обычном анализе фигуры оÑ�таютÑ�Ñ� комментариÑ�ми `[%cal]`/`[%csl]` и Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ� только вмеÑ�те Ñ� партией обычным дейÑ�твием Ñ�охранениÑ�. Модификаторы цвета и отказ от риÑ�ованиÑ� пальцем на Android не менÑ�ÑŽÑ‚Ñ�Ñ�; + - книжные комментарии: нетронутые байты не менÑ�ÑŽÑ‚Ñ�Ñ�, команды `[%cal]`, `[%clk]`, `[%eval]` Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�. + +## Игра Ñ� компьютером (Maia), 2026-10-25 + +- Соперник — Maia-3 (CSSLab), играет как человек выбранного рейтинга 600–2600; во времÑ� партии движок и анализ недоÑ�тупны, поÑ�ле — обычнаÑ� партиÑ�. +- Контроль по умолчанию 10+5; Ñ�амый быÑ�трый — 3+0 (пули нет); еÑ�ть Ñ�вой контроль и «Без ограничениÑ�» (без чаÑ�ов). +- ВеÑ�а Maia не раÑ�проÑ�транÑ�ем: лицензиÑ� не указана, файл Ñ�качиваетÑ�Ñ� по кнопке Ñ� Ñ�айта авторов (huggingface.co, закреплённаÑ� ревизиÑ�, SHA-256) — владелец Ñ�оглаÑ�ен. +- ГорÑ�чаÑ� клавиша «Играть» — Ctrl+G. +- Рейтинг Maia — по шкале Lichess; в диалоге поÑ�Ñ�нение, что Maia 1500 Ñ�лабее клубного игрока 1500. + +## Ð’Ñ�тавка варианта, игра Ñ� хода, изучение дебюта (2026-10-25) + +- **Ð’Ñ�тавка варианта из буфера:** Ñ�прашивать, только еÑ�ли вариант вÑ�таёт не на выбранном ходу; Ñ�Ñ�ылка на иÑ�точник в конце варианта — только имена игроков («Белые – Чёрные»), без турнира, года и рейтинга; неÑ�колько партий в буфере — вÑ�тавлÑ�етÑ�Ñ� перваÑ�, Ñ� Ñ�ообщением. +- **Игра Ñ� хода:** новаÑ� партиÑ� = ходы иÑ�ходной партии до выбранного хода + игра. Пункт меню «Играть отÑ�юда…». Цвет по умолчанию — Ñ�торона, чьÑ� очередь ходить. Реванш — тем же цветом. Кнопки «добавить вариантом в иÑ�ходную партию» нет: Ñ�ыгранную партию Ñ�охранÑ�ÑŽÑ‚ в базу как обычную. +- **Изучение дебюта:** ходы за обе Ñ�тороны вÑ�егда делает пользователь; режима «один цвет против программы» не будет. ПоÑ�ле третьей неверной попытки на одном ходе — Ñ�Ñ�ылка «Показать ход» (Ñ�трелка по запроÑ�у), прохождение помечаетÑ�Ñ� «Ñ� подÑ�казкой» (понÑ�то из ответа «5. ок»; уточнить, еÑ�ли иначе). КаждаÑ� невернаÑ� попытка Ñ�читаетÑ�Ñ�. + +## Строка заголовка библиотеки (2026-10-25) + +- Три группы, разделённые вертикальной чертой: базы («+ Добавить базу · ✚ Ð�оваÑ� база · ðŸŒ� Онлайн-партии») | ввод партии («♟ Ð�оваÑ� партиÑ� · 📋 Ð’Ñ�тавить PGN») | «♞ Играть»; «⚙ Ð�аÑ�тройки» — Ñ�права. ЗаменÑ�ет прежний порÑ�док, где ввод партии Ñ�тоÑ�л первым. + +## Android: ввод ходов, Ñ�вои базы, Maia, тренировка (2026-10-26) + +Решение владельца по иÑ�Ñ�ледованию `docs/research/android-port.md`. **ПереÑ�матривает п. 16 («только Ñ�мотреть») и `android-ui.md` §15.3.** + +- Ð�а Android поÑ�влÑ�етÑ�Ñ� ввод ходов на доÑ�ке — длÑ� Ñ�воих баз, новой партии Ñ� нулÑ� (длÑ� анализа), Ñ�охранениÑ� партий в базы пользователÑ�. +- **Свои базы — неÑ�колько**, Ñ�оздаютÑ�Ñ� в приложении (PGN во внутренней папке приложениÑ�; выгрузка и «ПоделитьÑ�Ñ�»). Чужие файлы, открытые через выбор файлов Android, не правÑ�Ñ‚Ñ�Ñ�. +- **Игра Ñ� Maia — только малаÑ� модель (5M, 21 МБ, до ≈1800)**, Ñ�ыграннаÑ� партиÑ� запиÑ�ываетÑ�Ñ� в Ñ�вою базу. +- **Без чаÑ�ов:** партиÑ� Ñ� Maia на телефоне вÑ�егда беÑ�Ñ�рочнаÑ�, контролей времени нет. +- **Тренировка дебюта и «Играть отÑ�юда»** — переноÑ�им. +- Ð�е переноÑ�им (Ñ�оглаÑ�ен Ñ�о вÑ�ем Ñ�пиÑ�ком §6 иÑ�Ñ�ледованиÑ�): большие базы ChessBase на меÑ�те, Ñ�вои UCI-движки из файла, запиÑ�ÑŒ в файлы пользователÑ� через выбор файлов, вход в ChatGPT по подпиÑ�ке, Ñ�трелки пальцем, «ЗапиÑ�ать анализ в партию», наÑ�тольные Ñ�очетаниÑ� клавиш и узкие окна. +- Логика — в общих крейтах Rust (обе программы на одном коде); в `mobile-api` не копируетÑ�Ñ� код из `apps/desktop`. +- По проекту `docs/design/android-play.md` (2026-10-26): «назад» во времÑ� партии Ñ� Maia откладывает её (карточка «Продолжить» на «Базах»); ходы в чужой партии не Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ� и не Ñ�прашиваютÑ�Ñ� (подÑ�казка «Ваши ходы не Ñ�охранены · Вернуть»); Ñ€Ñ�д «Играть Ñ� Maia · Ð�оваÑ� партиÑ�» вверху «Баз» — как в проекте, не во вÑ�ÑŽ ширину. + +## Предложение ничьей (2026-10-26) + +Владелец: человек может предложить ничью движку (компьютер и телефон). Движок Ñ�оглашаетÑ�Ñ�, еÑ�ли ему хуже или он лучше не больше чем на 0,2 и оценка неÑ�колько ходов почти не менÑ�етÑ�Ñ� (как у ботов Lichess). Сделано правилом крейта `play` (`accepts_draw`): Ñ�вно хуже (−0,5 и ниже) или его матуют — Ñ�разу; около равенÑ�тва (≤ +0,2) — еÑ�ли три поÑ�ледних оценки в пределах 0,3; иначе отказ; поÑ�ле отказа Ñ�нова — через два его хода. Оценивает тот же Ñ�крытый Stockfish, что и Ñ�дачу; без него кнопка объÑ�Ñ�нÑ�ет, что нужен Stockfish. + +## Соперник Ñ� характером: Rodent V (2026-10-26) + +Решение владельца по `docs/research/rodent.md`: +- Ð’ игре Ñ� компьютером — два Ñ�оперника: **Maia** (человечные ошибки, примерно до 2200) и **Rodent V** (Ñ�ильнее, Ñ�о Ñ�тилем). Выше ~2200 играет Rodent; но Rodent можно выбрать и на любой Ñ�иле. +- У Rodent наÑ�траиваютÑ�Ñ� **Ñ�ила** (откалиброваннаÑ� нами, по шкале Lichess, как у Maia), **Ñ�тиль** и **«Ñ�оперник»** (личноÑ�ть игрока, например Таль). +- Берём **Rodent V** (не IV). +- **Только на компьютере**; на телефоне оÑ�таётÑ�Ñ� Maia. +- Перед реализацией — замер Ñ�илы Rodent V по шкале Lichess (как у Maia) и проверка Ñ�борки на Linux, Windows, macOS. + +## Rodent IV: его перÑ�онажи — в Ñ�пиÑ�ке Ñ�тилей Rodent (2026-10-26) + +Владелец: «заюзаем rodent 4 Ñ�о вÑ�еми его Ñ�тилÑ�ми… людÑ�м хочетÑ�Ñ� больше перÑ�онажей». СоглаÑ�овано: +- **Один Ñ�оперник «Rodent»** в диалоге игры: его Ñ�пиÑ�ок раÑ�ширÑ�етÑ�Ñ� перÑ�онажами Rodent IV — характеры (Ð�манда, Защитник, Удав… — названиÑ� переведены на вÑ�е Ñ�зыки, в запиÑ�и партии английÑ�кое имÑ� движка) к Ñ�тилÑ�м, 22 великих шахматиÑ�та (Ð�лехин… Таль) к «Как игрок». Какой движок играет (V или IV), программа выбирает по перÑ�онажу; Ñ�ила — по шкале движка (IV 800–2800, V 800–3000). +- **Движок IV Ñ�обираем Ñ�ами** из иÑ�ходников авторов (GPL-3, зафикÑ�ированнаÑ� верÑ�иÑ�) в нашем CI длÑ� Linux, Windows и macOS и выкладываем отдельным выпуÑ�ком на GitHub; программа Ñ�качивает его по кнопке Ñ� проверкой Ñ�уммы. ПерÑ�онажи и книги Ñ�качиваютÑ�Ñ� из репозиториÑ� авторов на той же верÑ�ии, каждый файл Ñ� проверкой Ñ�уммы. Ð�а macOS Rodent поÑ�влÑ�етÑ�Ñ� впервые (V там нет). +- **Ð�а телефоне** — только Maia (игра) и Stockfish (анализ), других движков нет. *Изменено 2026-10-27, Ñ�м. ниже.* + +## Rodent IV на телефоне (2026-10-27) + +Владелец: «хочу чтобы в мобилке мы вÑ�е же внедрили 4 верÑ�ию движка… при Ñ�тарте игры показывали какой движок мы хотим выбрать». СоглаÑ�овано (проект `docs/design/android-rodent.md`): +- Соперник в игре на телефоне — Maia или Rodent IV (13 характеров и 22 великих шахматиÑ�та); Stockfish оÑ�таётÑ�Ñ� длÑ� анализа. Rodent V на телефоне нет. +- Движок Ñ�обираетÑ�Ñ� нашим Ñ�криптом (`androidApp/scripts/rodent4.sh`) из иÑ�ходников авторов на той же верÑ�ии и лежит в APK обеих Ñ�борок; характеры — в APK. +- Дебютные книги — **одним пакетом** (≈ 59 МБ: только иÑ�пользуемые характерами), Ñ�качиваютÑ�Ñ� один раз по кнопке Ñ� проверкой Ñ�умм; удалÑ�ÑŽÑ‚Ñ�Ñ� в «Ð�аÑ�тройки → Движок». Кнопка «Без книги» позволÑ�ет играть без них. +- Первый раз выбрана Maia; при первом выборе Rodent Ñ�ам открываетÑ�Ñ� Ñ�пиÑ�ок Ñ� предложенным Талем. С позиции книги не нужны. Сила запоминаетÑ�Ñ� отдельно длÑ� Maia и Rodent. Кнопка «Играть Ñ� Maia» на «Базах» Ñ�тановитÑ�Ñ� «Играть». + +## Сила Ñ�оперника — по шкале Ñ�амого движка (2026-10-26) + +Владелец: «запарилÑ�Ñ� Ñ� калибровкой движков» — в диалоге игры два движка, Maia и Rodent V, у каждого **Ñ�воÑ� шкала, как её заÑ�влÑ�ÑŽÑ‚ авторы**: Maia 600–2600 (рейтинг, на котором обучена Ñ�еть; ходы — выбором по её вероÑ�тноÑ�Ñ‚Ñ�м, температура 1), Rodent V 800–3000 (UCI_Elo; у Rodent по-прежнему выбираетÑ�Ñ� Ñ�тиль). Под ползунком Ñ�казано, что Ñ�то рейтинги Ñ�амих движков и Эло человека они не Ñ�оответÑ�твуют. Ð�втопереключениÑ� Maia → Rodent за 2100 больше нет; при Ñ�мене движка Ñ�ила приводитÑ�Ñ� в его диапазон. ПереÑ�чёт по замерам (`research/maia-strength.md`, `research/rodent.md`) оÑ�таётÑ�Ñ� иÑ�Ñ�ледованием и в программе не иÑ�пользуетÑ�Ñ� Ð�а телефоне — так же, Maia 600–2600 (владелец, 2026-10-26). + +## Партии игрока запиÑ�ываютÑ�Ñ� Ñ�ами (2026-10-26) + +Владелец: игроку, впиÑ�авшему имÑ�, программа Ñ�ама заводит базу его партий, и вÑ�е партии Ñ� компьютером пишутÑ�Ñ� туда без отдельного дейÑ�твиÑ� — на компьютере и на телефоне (Ñ�начала компьютер). Это отменÑ�ет прежнее «автоÑ�охранениÑ� нет» (`own-databases.md` §1 п.4, `play-mode.md` §5.2, `android-play.md`) — только длÑ� Ñ�ыгранных партий. СоглаÑ�овано по `research/player-games-db.md` и `design/player-games.md`: +- Ð�азвание — **«ИмÑ� — партии Ñ� компьютером»** (имÑ� не Ñ�клонÑ�етÑ�Ñ�); база Ñ�оздаётÑ�Ñ� при первой запиÑ�и, на компьютере — в `Документы/ChessPenguin`, на телефоне — перваÑ� в «Моих базах». +- **Без имени** — общаÑ� база «Партии Ñ� компьютером»; Ñ�трока под полем предлагает впиÑ�ать имÑ�. +- Программа только **допиÑ�ывает** новые партии в Ñ�озданную ею базу; замена и удаление — Ñ�вные дейÑ�твиÑ� (инвариант о файлах пользователÑ� не нарушаетÑ�Ñ�). Где окажетÑ�Ñ� партиÑ�, видно до игры (Ñ�трока под именем), один раз — уведомление о новой базе, поÑ�ле — «✓ ЗапиÑ�ано в «…»» в полоÑ�е результата. +- ПартиÑ� пишетÑ�Ñ� одной запиÑ�ью в конце; во времÑ� игры — журнал поÑ�ле каждого хода, при Ñ�бое партиÑ� допиÑ�ываетÑ�Ñ� при Ñ�ледующем запуÑ�ке Ñ� результатом `*`, без дублей. Ð�едоигранные (отложеннаÑ� и брошеннаÑ� на телефоне) — тоже Ñ� `*`. +- Кнопки «Ð�е Ñ�охранÑ�ть Ñ�ту партию» нет (лишнюю удалÑ�ÑŽÑ‚ из базы, Ñ� отменой); выключатель в наÑ�тройках, по умолчанию включено. +- Ð�еÑ�колько игроков на одном компьютере — Ñ�пиÑ�ок прежних имён у полÑ�, у каждого Ñ�воÑ� база и рейтинг. «Играть отÑ�юда» пишетÑ�Ñ� в базу игрока; тренировка дебюта — нет; Ñ�тарые партии не переноÑ�Ñ�Ñ‚Ñ�Ñ�. + +## ПредложениÑ�, требующие Ñ�оглаÑ�ованиÑ� + +- РуÑ�Ñ�кий интерфейÑ� по умолчанию Ñ� архитектурой длÑ� поÑ�ледующего английÑ�кого перевода. +- Компоновка одного окна: библиотека и рабочее меÑ�то партии Ñ� Ñ�охранением контекÑ�та. +- Сначала небольшой проверочный прототип Ñ�ложных UI-компонентов, затем перваÑ� рабочаÑ� верÑ�иÑ�. + +Рекомендации и техничеÑ�кие аргументы находÑ�Ñ‚Ñ�Ñ� в `architecture.md` и `research/`. При изменении объёма обновлÑ�ть Ñ�тот файл, чтобы Ñ�тарые иÑ�Ñ�ледованиÑ� не трактовалиÑ�ÑŒ как актуальное решение пользователÑ�. + +## Ход назад — только в блице (2026-10-27) + +Владелец: «длÑ� вÑ�ех контролей игры Ñ� движком кроме блицов убрал кнопку отменить ход»; уточнено: кнопка «↶ Ход назад» (и Ctrl+Z) еÑ�ть только в блице (3+0, 3+2, 5+0, 5+3); в рапиде, клаÑ�Ñ�ике и игре без чаÑ�ов её нет (Ñ�крыта, не Ñ�ераÑ�). Только компьютер; телефон не менÑ�етÑ�Ñ�. + +## Сборка длÑ� RuStore (2026-10-27) + +Владелец: приложение выкладываетÑ�Ñ� в RuStore; в Ñ�борке длÑ� магазина не должно быть Ñ�амообновлениÑ� и учёта уÑ�тановок, а Ñ�борка длÑ� Ñ�айта оÑ�таётÑ�Ñ� как еÑ�ть. Решено: +- **Ð�е отдельнаÑ� ветка**, а тип Ñ�борки `rustore` в той же оÑ�новной ветке (`androidApp/app/build.gradle.kts`): копиÑ� `release` Ñ� флагом `SELF_UPDATE = false`. Ветку пришлоÑ�ÑŒ бы каждый раз догонÑ�ть до оÑ�новной; тип Ñ�борки вÑ�егда Ñ�обираетÑ�Ñ� из Ñ�вежего кода. Сборки длÑ� Ñ�айта (`assembleFullRelease`, `assembleLightRelease`) не менÑ�ÑŽÑ‚Ñ�Ñ�. +- Ð’ Ñ�борке RuStore приложение **не проверÑ�ет выпуÑ�ки и не обращаетÑ�Ñ� к Ñ�айту** (Ñ�та проверка и еÑ�ть учёт уÑ�тановок: `/api/update` Ñ� id уÑ�тановки), не Ñ�качивает и не Ñ�тавит обновлениÑ�; в «О программе» нет блока обновлений; Ñ�охранённое ранее найденное обновление (еÑ�ли её поÑ�тавили поверх Ñ�айтовой) забываетÑ�Ñ�. МанифеÑ�Ñ‚ `src/rustore/AndroidManifest.xml` убирает `REQUEST_INSTALL_PACKAGES`, `UPDATE_PACKAGES_WITHOUT_USER_ACTION` и приёмник ответа уÑ�тановщика. ОбновлÑ�ет приложение магазин. +- **Только полнаÑ� Ñ�борка** (Stockfish внутри): лёгкаÑ� длÑ� `rustore` отключена. +- **Тот же пакет и тот же ключ**, что у Ñ�айта: одно и то же приложение, Ñ�тавитÑ�Ñ� поверх Ñ� Ñ�охранением баз и наÑ�троек в обе Ñ�тороны. +- **СобираетÑ�Ñ� на GitHub при каждом выпуÑ�ке** (`androidApp/scripts/release.sh` → `androidApp/dist-rustore/ChessPenguin-<верÑ�иÑ�>-rustore.apk`): артефакт `rustore` прогона «Release», **не файл выпуÑ�ка** — на Ñ�айте и в Ñ�пиÑ�ке Ñ�качиваний его нет; в RuStore загружаетÑ�Ñ� вручную. Скрипт проверÑ�ет, что разрешениÑ� на уÑ�тановку в нём нет. + +## БлеÑ�Ñ‚Ñ�щий и отличный ход (2026-10-28) + +Владелец: «как на chess.com» отмечать в разборе блеÑ�Ñ‚Ñ�щий (!!) и отличный (!) ход, везде, где отмечаютÑ�Ñ� ошибки, включаÑ� значок на доÑ�ке — и на телефоне тоже (там значков на доÑ�ке раньше не было). Правила — по `research/brilliant-moves.md`; на открытые вопроÑ�Ñ‹ аналитика принÑ�ты его рекомендации (владелец может переÑ�мотреть): +- **!!** — корректнаÑ� жертва фигуры не дешевле лёгкой (по раÑ�чёту размена Ñ�оперник выигрывает ≥ 2 очков Ñ�верх взÑ�того), ход лучший или почти лучший, поÑ�ле него не хуже ≈ −0,5, без него партиÑ� не была выиграна и так (лучший другой ход < 90 %). Конь за две пешки — не !!. +- **!** — ход движка â„–1, вÑ�е оÑ�тальные хуже не меньше чем на 10 % шанÑ�а (наша «ошибка»), поÑ�ле него не хуже ≈ −0,2 и без него не было уже выиграно. ВзÑ�тие обратно, выгодное взÑ�тие и мат не отмечаютÑ�Ñ�. +- **Калибровка по chess.com (2026-10-28, владелец приÑ�лал разметку «Вечнозелёной»):** жертва — только фигура, отданнаÑ� Ñ�амим ходом (а не виÑ�евшаÑ� и раньше: 18…Rg8 — «!», не «!!»); правила «одна отметка на комбинацию», «уход атакованной фигуры» и «ход менÑ�ет иÑ�ход» убраны (22.Bf5+! 23.Bd7+!, 13.Qa4!, 8…Qf6!). Совпало 7 из 8 отметок chess.com; 10…Nge7 (разрыв 9 % при пороге 10) — нет. Дальше калибровать по приÑ�ылаемым партиÑ�м, а не подгонÑ�ть порог под одну. +- **Калибровка 2 (2026-10-28, партиÑ� владельца Ñ� Rodent IV):** 18.Bxa7 — не жертва: ход вÑ�крывает линию d на ферзÑ�, и взÑ�тие Ñ�лона Ñ�разу проигрывает больше (18…Rxa7 19.Rxd8). Правило ChessCom: фигура не Ñ�читаетÑ�Ñ� отданной, еÑ�ли поÑ�ле её взÑ�тиÑ� ходÑ�щий тут же выигрывает не меньше (`taking_loses` в `features.rs`); правило Strict не менÑ�лоÑ�ÑŒ. **Ð�абор Ñ�верки** — `crates/game-review/chesscom/` (партии Ñ� отметками chess.com в NAG, README); поÑ�ле каждой калибровки прогонÑ�ть вÑ�е: `cargo run --release -p game-review --example chesscom_check -- `. Ð�а 2026-10-28: 10 из 10 Ñ�овпадений («ВечнозелёнаÑ�» 8, партиÑ� Ñ� Rodent 2 !!). +- **Калибровка 3 (2026-10-28, «БеÑ�Ñ�мертнаÑ�» по chess.com):** (а) жертва, котораÑ� матует быÑ�трее любого другого хода, — не «и так выиграно»: 22.Qf6+!! (мат в 2), хотÑ� 22.Qf7 тоже матует (в 4) — win % Ñ�того не различает (`mates_sooner` в `report.rs`); (б) длÑ� «!» лучшего хода движка падение оценки к Ñ�ледующей позиции не учитываетÑ�Ñ� — Ñ�то шум двух поиÑ�ков (9.Nf5! и 12.h4! пропадали на оценках владельца: −0,51 → −0,82). Обе правки — только правило ChessCom. Ð�абор: 17 из 17 на наших оценках; на оценках из кÑ�ша владельца 16 из 17 — 10…Nge7 «Вечнозелёной» (разрыв 9 % при пороге 10, пограничный Ñ�лучай Ñ� первой калибровки; порог под одну партию не двигаем). +- **Калибровка 4 (2026-10-28, Стейниц — фон Барделебен по chess.com):** правило калибровки 2 оказалоÑ�ÑŒ Ñ�лишком широким — оно Ñ�нÑ�ло 22.Rxe7+!! и 24.Rg7+!!: поÑ�ле 22…Qxe7 белые отыгрываютÑ�Ñ� 23.Rxc8+, но Ñ�ту угрозу открыло Ñ�амо взÑ�тие (ферзь ушёл Ñ� d7). Уточнено: фигура не отдана, только еÑ�ли угроза, отыгрывающаÑ� её, Ñ�тоÑ�ла уже Ñ�разу поÑ�ле хода (18.Bxa7: ферзь d8 под ладьёй до взÑ�тиÑ�). Оба !! Ñ�овпали, 18.Bxa7 по-прежнему без !!. РаÑ�хождениÑ� по «!» в Ñ�той партии (у наÑ� лишние 6…Bb4+, 8.exd5, 13.Bxe7, 17.d5, 18.Nd4, 19.Ne6, 23.Rf7+, 25.Rxh7+; нет 18…Kf7) — открыты, Ñ�м. разбор владельцу. +- **Калибровка 5 (2026-10-28, по предложению, владелец Ñ�оглаÑ�илÑ�Ñ� «поÑ�мотрим»):** правило ChessCom — (а) книжный ход (позициÑ� поÑ�ле хода лежит на линии таблицы дебютов `chess-openings`, крейт `crates/openings`) не получает ни !, ни !!; (б) ! нет, еÑ�ли лучший другой ход оÑ�тавлÑ�ет ≥ 60 % (было 75; у вÑ�ех ! chess.com в наборе — не больше 59 %, запаÑ� мал). Убрало 6…Bb4+, 18.Nd4, 23.Rf7+, 25.Rxh7+. Ð�абор: 23 Ñ�овпадениÑ�, 5 раÑ�хождений (8.exd5, 13.Bxe7, 17.d5, 19.Ne6 у наÑ� лишние; 18…Kf7 нет — у чёрных 17 %, ! там не Ñ�тавим); на оценках владельца ещё 10…Nge7. +- **Калибровка 6 (2026-10-28, ещё три партии: ПиллÑ�бери — ЛаÑ�кер, Ротлеви — Рубинштейн, Рети — Тартаковер):** правило ChessCom — (а) атакованнаÑ� фигура, тихо переÑ�тавленнаÑ� под новый бой, — жертва (могла уйти): 18…Ra3!!, 20…Ng4!!; «вÑ�Ñ‘ равно потерÑ�нной» оÑ�таётÑ�Ñ� только фигура, котораÑ� напоÑ�ледок бьёт (деÑ�перадо); (б) взÑ�тие, лишь отыгрывающее только что взÑ�тое Ñ�оперником (не на том же поле), — не «выгодное взÑ�тие» и может быть «!»: 18.fxe6!; но не когда Ñ�оперник взÑ�л фигуру, которую мы только что отдали (24…Bxe4+ поÑ�ле 23…Rd2 24.Qxd2 — продолжение комбинации); (в) пешка, отданнаÑ� ради более быÑ�трого мата, — «!!»: 29…b5+ (мат в 4 против 6 у 29…Qc4+). Ð�абор: 7 партий, 38 Ñ�овпадений, 6 раÑ�хождений (23.Rd2 у ПиллÑ�бери: наш движок предпочитает 23.Qh3; оÑ�тальные 5 — прежние в партии Стейница); на оценках из кÑ�ша владельца 35/9 — разброÑ� движка (лучший ход другой, нет второго поиÑ�ка). +- **Калибровка 7 (2026-10-28, ещё три партии; Ñ�начала прогон без правок):** ЛаÑ�кер — ТомаÑ�, Капабланка — Маршалл (поход по ходам) и Левицкий — Маршалл (только итоговые чиÑ�ла chess.com). До правок на двух партиÑ�Ñ… Ñ� ходами: !! 2 из 2, ! 1 из 1, лишних ! 2 (15.d4, 23.Kd3). Правка, правило ChessCom: «и так выиграно» длÑ� !! — только форÑ�ированный мат у лучшего другого хода (было: ≥ 90 % шанÑ�ов); в наборе каждаÑ� жертва, где другой ход тоже выигрывал (до 93 %), — !! у chess.com (23…Qg3, 22…Rxc3, 20…Ng4). 22…Rxh3 (Левицкий — Маршалл) жертвой не Ñ�читаетÑ�Ñ�: ладьÑ� за Ñ�лона и пешку — чиÑ�таÑ� потерÑ� 1 пункт при пороге 2; порог не двигали. 19.Rxd5 у наÑ� !!, у chess.com у белых !! нет — ждём запиÑ�ÑŒ ходов. +- **Обмен партиÑ�ми (2026-10-28):** владелец отдаёт chess.com партии, которые выбирает оркеÑ�тратор; наш прогноз фикÑ�ируетÑ�Ñ� коммитом до ответа (`chesscom/pending/README.md`). Бирн — Фишер: до правок !! 2/3, ! 1/1 (лишних 4). Правила ChessCom: взÑ�тие — «!» только когда вÑ�е другие ходы проигрывают (≤ 33 %); отыгрыш поÑ�ле принÑ�той Ñ�обÑ�твенной жертвы — не отдельный «!». Отброшено: «оÑ�тавленнаÑ� под боем фигура — жертва» (17…Be6!!, но +4 ложных !!). КаÑ�паров — Топалов: до правок !! 3/5, ! 6/8 (лишних 6). Правило: жертву отменÑ�ет только угроза, Ñ�озданнаÑ� Ñ�амим ходом, а не Ñ�тоÑ�вшаÑ� до него (37.Rd7!!). Отброшено: «пешка, отданнаÑ� единÑ�твенным хорошим ходом, — !!» (33.c3+!!, но ложный !! на 17.d5). ФикÑ�ированный режим разбора (1 млн узлов, 1 поток) — набор: !! 91 % найдено, 95 % наших верны; ! 78 % / 72 %. +- **Строже «!» (2026-10-28, владелец: «!! почти 100 %, а ! можно и меньше, чем у chess.com — закрутить гайки»):** правило ChessCom — взÑ�тие никогда не «!»; «!» только еÑ�ли лучший другой ход хуже на ≥ 25 % (было 10). Перебор порогов на наборе: точноÑ�ть «!» упиралаÑ�ÑŒ в 72–76 % из-за взÑ�тий в форÑ�ированных вариантах; Ñ� Ñ�тими правилами наши «!» — chess.com в 87 % Ñ�лучаев (найдено 54 % их «!»). 2 млн узлов вмеÑ�то 1: «!!» без изменений, «!» +1 из 37 — оÑ�тавили 1 млн. +- **Тихое отÑ�тупление — не «!» (2026-10-29, владелец о 10.Be2 Ñ�воей онлайн-партии: «ну какой же Ñ�то !»):** правило ChessCom — атакованнаÑ� фигура, уходÑ�щаÑ� на Ñ�воё единÑ�твенное хорошее поле без шаха, «!» не получает; уход Ñ� шахом — может (19…Ne2+, 23.Bd7+ у chess.com «!»). ТерÑ�ем 13.Qa4! «Вечнозелёной» (chess.com) — оÑ�ознанно: владельцу важнее, чтобы «!» не было лишних. Ð�абор: «!» найдено 20 из 40, наших верных 80 %; «!!» без изменений. Ra7! из второй партии владельца был в 2.0.0, в 2.1.0 его уже нет. +- **Трудный ход — «!!» и без жертвы (2026-10-29, идеÑ� владельца «двумÑ� движками»):** длÑ� кандидатов в !!/! — ещё неглубокий поиÑ�к (5 000 узлов, тот же детерминированный режим). ЕÑ�ли ход — единÑ�твенный хороший (разрыв ≥ 10 %), а неглубокий поиÑ�к выбирает другой ход и Ñ�тавит Ñ�тот на ≥ 30 % ниже — «!!». Опора — Ñ�татьÑ� Zaidi & Guerzhoy 2024 (arXiv 2406.11895: блеÑ�Ñ‚Ñ�щим Ñ�читают ход, который Ñ�лабый движок оценивает ниже, а Ñ�ильный — лучшим). Ð�абор: !! найдено 35 из 39 (было 32), верных 95 %; ложных не прибавилоÑ�ÑŒ; одинаково на 2 000–5 000 узлов и порогах 20–40 %. ДлÑ� «!» трудноÑ�ть не включена: при «неглубокий выбрал тот же ход» «!» иÑ�чезает почти веÑ�ÑŒ (5 000 узлов уже находÑ�Ñ‚ 127 из 141), при «неглубокий оценил ниже» уходÑ�Ñ‚ и матовые шахи, которые chess.com отмечает. Разбор длиннее на 1–2 %. Прежние правила — ветка Forgejo `marks-before-shallow`. Ð’ набор добавлены партии владельца Ñ� его вердиктом «Ñ�то не !» (`owner-*.pgn`, тег `OwnerPlain`): 10.Be2 и Ra7 — Ñ�ейчаÑ� без отметок. +- **Уход королÑ� из-под шаха — не «!» (2026-10-29, владелец: «будем Ñ�читать очевидным»):** правило ChessCom. Убрало три наших лишних «!» (23.Kd3, 20…Ka7, 32.Kd2) и три Ñ�овпадениÑ� Ñ� chess.com (22.Ke3, 25…Kb6, 20.Ke2 — chess.com здеÑ�ÑŒ непоÑ�ледователен; к тому же на новой учётке он щедрее, Ñ�ам пиÑ�ал об Ñ�том в 2023). Ð�абор: наших «!» верны 27 из 28 (96 %), найдено 27 из 82 отметок chess.com; «!!» без изменений (35 из 39, 95 %). +- Второй поиÑ�к движка (лучший ход, кроме Ñ�ыгранного) — **вÑ�егда**, только длÑ� подходÑ�щих ходов: разбор примерно на треть дольше. Старые разборы дозаполнÑ�ÑŽÑ‚Ñ�Ñ� кнопкой «Обновить» без переÑ�чёта оценок. +- ДлÑ� оценок из PGN (`[%eval]`) !! и ! нет: в отчёте прочерк и поÑ�Ñ�нение. +- Ð’ PGN — `$3`/`$1` Ñ� комментарием, только еÑ�ли у хода нет оценки автора. РуÑ�Ñ�кое имÑ� `$3` — «БлеÑ�Ñ‚Ñ�щий ход» (было «Отличный ход»); «Отличный ход» Ñ�тал !, затем переименован в «Замечательный ход» (владелец, 2026-10-28). + + +## Разбор партии на фикÑ�ированных параметрах движка (2026-10-28) + +Владелец: разбор партии вÑ�егда идёт на одних и тех же параметрах движка, пользователь их не выбирает — чтобы отметки ?!/?/??/!/!! и точноÑ�ть были одинаковы у вÑ�ех людей и на вÑ�ех машинах, а на Ñ�лабых компьютерах и телефонах разбор шёл Ñ� разумной Ñ�короÑ�тью. ДлÑ� анализа позиции «живым» движком выбор движка, потоков и памÑ�ти оÑ�таётÑ�Ñ�. + +- **ПоиÑ�к** (`crates/game-review/src/job.rs`): каждаÑ� позициÑ� — `go nodes 1 000 000` (`SEARCH_NODES`; 0,85 Ñ� на i7-13700KF, глубина ≈ 24), Stockfish Ñ� `Threads=1`, `Hash=32` МБ (`SEARCH_HASH_MB`), `MultiPV=1`, `ucinewgame` перед **каждым** поиÑ�ком, включаÑ� второй (`searchmoves`, длÑ� !!/!). Результат завиÑ�ит только от позиции (Ñ� её иÑ�торией): не от машины, порÑ�дка позиций и чиÑ�ла процеÑ�Ñ�ов. Движок — Stockfish 19 из ChessPenguin (на компьютере — вÑ�троенный или Ñ�качанный программой, на Android — его Ñ�борка); пользовательÑ�кий движок длÑ� разбора не берётÑ�Ñ� (Ñ� 2026-10-31 на компьютере — берётÑ�Ñ� Stockfish 19 пользователÑ�, прошедший проверку, Ñ�м. ниже). +- **ПараллельноÑ�ть** — неÑ�колькими процеÑ�Ñ�ами движка, каждый берёт Ñ�ледующую позицию: по чиÑ�лу логичеÑ�ких ЦП, на компьютере не больше 8, на телефоне не больше 4, и не больше, чем помещаетÑ�Ñ� в Ñ�вободную памÑ�ть (`MemAvailable` в `/proc/meminfo` на Linux и Android: ≈ 200 МБ Ñ�ети NNUE — она у Stockfish 19 в общей памÑ�ти, одна на вÑ�е процеÑ�Ñ�Ñ‹, — плюÑ� ≈ 70 МБ на процеÑ�Ñ�; где памÑ�ть не узнать — только пределы). Итого ≈ 0,8 ГБ на 8 процеÑ�Ñ�ов, ≈ 0,5 ГБ на телефоне. ПроцеÑ�Ñ�Ñ‹ — Ñ� `nice 10` и на компьютере, и на Android. +- **Замер** (i7-13700KF, партиÑ� `rodent-roman-2026-10-27.pgn`: 113 позиций, 163 поиÑ�ка): 1 процеÑ�Ñ� — 106 Ñ�, 4 — 28 Ñ�, 8 — 16 Ñ�; оценки вÑ�ех трёх прогонов побайтно одинаковы (`examples/review_bench.rs`). ТеÑ�Ñ‚ на `fake_uci --hash-memory` проверÑ�ет то же длÑ� 1/3/8 процеÑ�Ñ�ов и обратного порÑ�дка позиций. +- **ВерÑ�иÑ� поиÑ�ка** `SEARCH_VERSION` (Ñ�ейчаÑ� 1) запиÑ�ываетÑ�Ñ� в кÑ�ш разбора (`ReviewMeta.search`). Разбор другой верÑ�ии (в том чиÑ�ле вÑ�е разборы до Ñ�того решениÑ�, на «БыÑ�тро/Обычно/Глубоко») — уÑ�таревший: отчёт показываетÑ�Ñ�, в панели отчёта «Этот анализ Ñ�делан Ñ� прежними наÑ�тройками движка» и «Обновить», которое переÑ�читывает вÑ�Ñ‘ заново (не дополнÑ�ет). Смена узлов, памÑ�ти, движка или его верÑ�ии — повышать `SEARCH_VERSION`. +- **Подготовка к Ñ�опернику** ищет ошибки в дебютах тем же поиÑ�ком (качеÑ�тво «БыÑ�тро» 250k узлов убрано — поиÑ�к в 4 раза дольше прежнего по умолчанию); кÑ�ш позиций и отчёты Ñ� оценками другой верÑ�ии их не иÑ�пользуют (ошибки ищутÑ�Ñ� заново). +- **ИнтерфейÑ�.** Компьютер: диалог «Ð�нализ партии» убран — кнопка 📈 Ñ�разу запуÑ�кает разбор, оценка времени («N позиций, около T») — в её подÑ�казке (выбирать в диалоге больше нечего, а прогреÑ�Ñ� виден на графике). «Проанализировать заново…» убрано (тот же поиÑ�к дал бы те же оценки); длÑ� оценок из PGN — «Проанализировать движком». Диалог подготовки к Ñ�опернику оÑ�талÑ�Ñ� только Ñ� выбором цвета и оценкой времени. Без Ñ�обÑ�твенного Stockfish предлагаетÑ�Ñ� Ñ�качать его (окно без «Выбрать файл движка…»; Ñ�качанный Ñ�тановитÑ�Ñ� активным движком, только еÑ�ли активного не было). Android: в лиÑ�те запуÑ�ка разбора — только опиÑ�ание, оценка времени и кнопка (на Ñ�енÑ�орном Ñ�кране нет подÑ�казки); «Заново» и выбор качеÑ�тва убраны. +- Ð�аÑ�тройки `review.{quality,threads,hash_mb,chosen}` и `prep.quality` удалены; Ñ�тарые файлы наÑ�троек читаютÑ�Ñ� (лишние полÑ� пропуÑ�каютÑ�Ñ�). +- Оценка времени — по Ñ�короÑ�ти одного процеÑ�Ñ�а из поÑ�леднего разбора (или живого движка на поток; до замера — 700k узл/Ñ� на компьютере, 250k на телефоне) × чиÑ�ло процеÑ�Ñ�ов. +- Сверка Ñ� chess.com (`chesscom_check`) идёт в том же режиме; `CP_REVIEW_NODES` — только длÑ� подбора узлов в Ñ�том примере, кÑ�ш в отдельной папке. Первый прогон на 1M (правила — на коммите 968ab22, 10 партий): !! — 17 из 18 chess.com (94 %), наших 18, из них 94 % Ñ�овпали; ! — 24 из 29 (83 %), наших 30, Ñ�овпали 80 %; Ñ�овпадений 41, раÑ�хождений 12. + +## Ð’Ñ�троенные базы-примеры обновлÑ�ÑŽÑ‚Ñ�Ñ� Ñ� программой (2026-10-28) + +Владелец: база клаÑ�Ñ�ики раÑ�тёт (до 120–150 партий) и должна быть Ñ�разу доÑ�тупна, в том чиÑ�ле у тех, у кого уже лежит Ñ�тараÑ� верÑ�иÑ�. + +- **Компьютер** (`apps/desktop/src/examples.rs`). ТекÑ�Ñ‚ примеров вшит в программу (`include_str!`). При первом запуÑ�ке файлы пишутÑ�Ñ� в `/examples/` под именем на Ñ�зыке интерфейÑ�а и Ñ�тавÑ�Ñ‚Ñ�Ñ� на полку (`settings.examples_added`). При **каждом** запуÑ�ке файл примера Ñ�равниваетÑ�Ñ� Ñ� вшитым текÑ�том побайтно; отличаетÑ�Ñ� (Ñ�тараÑ� верÑ�иÑ�, повреждён, изменён Ñ�наружи) — заменÑ�етÑ�Ñ� атомарно (`chess_core::pgn::store::write_atomic`). Отдельной верÑ�ии нет: верÑ�иÑ� — Ñ�ам текÑ�Ñ‚. Файл ищетÑ�Ñ� под именем примера на любом Ñ�зыке (имÑ� дал Ñ�зык первого запуÑ�ка). +- Пример, убранный Ñ� полки, **на полку не возвращаетÑ�Ñ�**; его файл, еÑ�ли он оÑ�талÑ�Ñ� на диÑ�ке, вÑ�Ñ‘ равно обновлÑ�етÑ�Ñ� (Ñ�то файл программы, только длÑ� чтениÑ�; открыть его Ñ�нова — получить новую верÑ�ию). Удалённый Ñ� диÑ�ка и не Ñ�тоÑ�щий на полке файл заново не Ñ�оздаётÑ�Ñ�; Ñ�тоÑ�щий на полке — Ñ�оздаётÑ�Ñ�. +- КÑ�ши не мешают: чиÑ�ло партий на карточке (`db_counts`) привÑ�зано к размеру и времени файла — переÑ�читываетÑ�Ñ�; отметки проÑ�мотренных партий (`viewed`) — к текÑ�ту партии, у неизменных партий Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�; поиÑ�к позиций по PGN и Ñ�правочник держат данные в памÑ�ти, а замена идёт при запуÑ�ке, до открытиÑ� баз. +- **Android** (`data/Library.kt`). Примеры не копируютÑ�Ñ�: читаютÑ�Ñ� прÑ�мо из assets приложениÑ�, поÑ�тому Ñ� обновлением приложениÑ� новаÑ� верÑ�иÑ� открываетÑ�Ñ� Ñ�ама. Запомненное чиÑ�ло партий в Ñ�троке Ñ�пиÑ�ка Ñ�верÑ�етÑ�Ñ� Ñ� SHA-256 текÑ�та, из которого оно взÑ�то (`DbEntry.sha256`); не Ñ�овпало — пример перечитываетÑ�Ñ� при показе Ñ�пиÑ�ка баз (`countSamples`). + +## Веб-верÑ�иÑ� (2026-10-30) + +ИÑ�Ñ�ледование — `docs/research/web-version.md`, `web-version-tech.md`; подпроект `web/`, задача 22. РешениÑ� владельца: +- Ð�ачинаем Ñ� **лёгкой верÑ�ии**: открыть PGN/ChessBase-архив, Ñ�мотреть и править партии, анализ движком, разбор Ñ� !!/!, Ñ�качать PGN. ПолнаÑ� (Ñ�вои базы, подготовка к Ñ�опернику, игра Ñ� компьютером, офлайн) — потом. +- Размещение — **наш Ñ�айт**, адреÑ� вида `chess.vrubel.xyz/app/` (заголовки COOP/COEP длÑ� многопоточного Stockfish). +- Браузеры: **Chrome, Edge, Firefox, Safari** — веб-приложение **только на компьютере**. **Телефоны и планшеты (в том чиÑ�ле iPad) — без веб-приложениÑ�** (владелец, 2026-10-30: «не будем на Ñ�то тратитьÑ�Ñ�»): Ñ�траница «на Android — Ñ�качайте приложение, на iPhone/iPad — приложение Ñ�коро будет»; определение уÑ�тройÑ�тва — по `docs/design/web-version.md` §3.6 (iPadOS выдаёт Ñ�ебÑ� за Mac; короткаÑ� Ñ�торона Ñ�крана, каÑ�ание), тихаÑ� Ñ�Ñ�ылка «вÑ�Ñ‘ равно открыть веб-верÑ�ию». +- По открытым вопроÑ�ам дизайна принÑ�ты рекомендации: только чтение и в Chrome (в иÑ�ходный файл не пишем никогда); Ñ�правочника в лёгкой верÑ�ии нет; предупреждение длÑ� файлов больше 1 ГБ; на Ñ�транице длÑ� iPhone/iPad — «напишите нам» Ñ�Ñ�ылками (почта/Telegram), без форм. +- **Базы — только чтение, прÑ�мо Ñ� диÑ�ка**, без копии: Chrome/Edge помнÑ�Ñ‚ выбранный файл (одно «разрешить»), Firefox/Safari — файл выбираетÑ�Ñ� заново поÑ�ле перезагрузки; по желанию — «оÑ�тавить копию в браузере» Ñ� показом занÑ�того и Ñ�вободного меÑ�та (квота браузера) и отказом Ñ� объÑ�Ñ�нением, еÑ�ли не помещаетÑ�Ñ�. +- **Свои партии** (игры Ñ� движком, Ñ�озданные длÑ� анализа), разборы и наÑ�тройки — в хранилище браузера (OPFS/IndexedDB) Ñ� запроÑ�ом поÑ�тоÑ�нного хранениÑ�, показом занÑ�того меÑ�та и кнопкой «Ñ�качать мои партии в PGN». +- **ИнтерфейÑ� адаптируетÑ�Ñ� под веб** (палец, узкие Ñ�краны, открытие файлов кнопкой/перетаÑ�киванием, замена Ctrl+W/Ctrl+N, уÑ�тановка на главный Ñ�кран) — Ñ�начала дизайн. + +## Разбор партии на Stockfish 19 пользователÑ�; перетаÑ�кивание файлов (2026-10-31) + +Владелец одобрил по жалобе пользователÑ� (Ñ�вой stockfish в наÑ�тройках, анализ позиции работает, а разбор проÑ�ил Ñ�качать). + +- **Движок разбора на компьютере** (`apps/desktop/src/review_engine.rs`): Ñ�вой Stockfish 19 программы → движок пользователÑ�, прошедший проверку → предложение Ñ�качать. Кандидаты — движки анализа из наÑ�троек (активный первым) и `stockfish` из `PATH`; движки игры (Rodent IV/V, Maia — их папки) не проверÑ�ÑŽÑ‚Ñ�Ñ� никогда, при любых наÑ�тройках. Android и веб не менÑ�ÑŽÑ‚Ñ�Ñ�. +- **Проверка** (`game_review::probe`): движок, назвавшийÑ�Ñ� (`id name`) не «Stockfish 19», отвергаетÑ�Ñ� Ñ�разу поÑ�ле `uci`, без поиÑ�ков (Rodent, Komodo — доли Ñ�екунды). «Stockfish 19» делает три поиÑ�ка в режиме разбора (`Threads=1`, `Hash=32`, `MultiPV=1`, `ucinewgame` перед каждым, `go nodes 100000`, Ñ�трока — как в разборе); лучший ход, оценка и чиÑ�ло узлов должны Ñ�овпаÑ�ть Ñ� Ñ�талоном `REFERENCE` (Ñ�нÑ�Ñ‚ 2026-10-31 нашим `stockfish-linux-x86-64-universal`; тот же ответ дали Ñ�борки SF19 из иÑ�ходников релиза под x86-64 (SSE2) и x86-64-bmi2; Stockfish и Ñ�ам требует одинакового `bench` от вÑ�ех Ñ�резов универÑ�альной Ñ�борки, `scripts/check_universal.sh` релиза). Сторож: 10 Ñ� на поиÑ�к, 30 Ñ� на вÑ�ÑŽ проверку; не уÑ�пел — «не уÑ�пел ответить на проверку», в памÑ�ти до Ñ�ледующего запроÑ�а, на диÑ�к не пишетÑ�Ñ�. Проверка — в фоне (`nice 10`), движок запуÑ�каетÑ�Ñ� по пути из наÑ�троек/`PATH` (snap и обёртки Ñ�мотрÑ�Ñ‚ на имÑ� запуÑ�ка), вердикт — длÑ� реального файла. При выходе программа ждёт проверки не дольше 2 Ñ�; движок, завиÑ�ший на рукопожатии, умирает вмеÑ�те Ñ� потоком проверки (`EngineConfig::kill_with_parent`, `PR_SET_PDEATHSIG` на Linux). +- **КÑ�ш**: вердикт по реальному файлу (Ñ�Ñ�ылки разрешены) + размер + времÑ�, вмеÑ�те Ñ� ключом Ñ�талона (`reference_key`, FNV позиций/узлов/Ñ…Ñ�ша/ответов) в `/review-engines.json`; другой ключ — вÑ�Ñ‘ проверÑ�етÑ�Ñ� заново. «Ð�е запуÑ�тилÑ�Ñ�» не запоминаетÑ�Ñ�: Ñ�казано один раз, при Ñ�ледующем запроÑ�е — новаÑ� попытка. При Ñ�тарте разбора `id name` движка пользователÑ� Ñ�верÑ�етÑ�Ñ� ещё раз (обёртка могла начать запуÑ�кать другое): не «Stockfish 19» — разбор оÑ�танавливаетÑ�Ñ� до первой оценки, вердикт забываетÑ�Ñ�. Оценки те же, поÑ�тому `SEARCH_VERSION` и кÑ�ш разборов не менÑ�ÑŽÑ‚Ñ�Ñ�. +- **Ожидание проверки** привÑ�зано к Ñ�воей партии/подготовке (номер Ñ�крана): закрыта или открыта другаÑ� — разбор не начнётÑ�Ñ� на чужой; разбор партии и ошибки в дебютах ждут отдельно; «Проанализировать движком» (заново) Ñ�охранÑ�етÑ�Ñ�. ТоÑ�Ñ‚ «ПроверÑ�ÑŽ, подойдёт ли ваш движок длÑ� разбора…» — только когда движок дейÑ�твительно проверÑ�етÑ�Ñ�. +- **Окно, еÑ�ли не подошёл** — пÑ�ть Ñ�лучаев: другой движок («В наÑ�тройках указан …» / «В Ñ�иÑ�теме найден …»), «Ваш Stockfish 19 Ñ�читает иначе, чем Ñ�борка ChessPenguin (другаÑ� Ñ�борка или Ñ�еть)…», «Ð�е удалоÑ�ÑŒ запуÑ�тить …», «… не уÑ�пел ответить на проверку — проверю Ñ�нова в Ñ�ледующий раз»; затем зачем нужна официальнаÑ� Ñ�борка, «Скачать?», «Ваш движок оÑ�таётÑ�Ñ� длÑ� анализа позиции» (кроме незапуÑ�тившегоÑ�Ñ�) и «…начнётÑ�Ñ� Ñ�ам поÑ�ле загрузки»; ниже — «N МБ · Ñ� официальной Ñ�траницы Stockfish». Без движка — как прежде. +- **ПеретаÑ�кивание на компьютере** (`platform::files::take_dropped`): брошенные файлы открываютÑ�Ñ� как «Добавить базу» (на полку, выбираетÑ�Ñ� перваÑ�; партиÑ� на Ñ�кране не закрываетÑ�Ñ�, тогда тоÑ�Ñ‚ «Добавлено на полку: …»). `.pgn/.cbh/.cbv/.zip/.7z` — базы; другие файлы ChessBase-базы (`.cbg`, `.cba`, `.cbj`, … — извеÑ�тные раÑ�ширениÑ�) — её `.cbh` Ñ€Ñ�дом, база один раз (дубли по реальному файлу); папка — базы в ней (без вложенных), пуÑ�таÑ� — тоÑ�Ñ‚; неÑ�ущеÑ�твующий файл — «Ð�е найдено: …»; прочее — «Это не база: …». База, уже Ñ�тоÑ�щаÑ� на полке под другим путём к тому же файлу (Ñ�Ñ�ылка), второй раз не добавлÑ�етÑ�Ñ� (`touch_database` Ñ�равнивает реальные файлы). Брошенные файлы не заменÑ�ÑŽÑ‚ базу из «Выбрать Ñ�нова»; отмена Ñ�того диалога его завершает. Пока файл над окном — подÑ�ветка окна Ñ� рамкой и карточка «ОтпуÑ�тите, чтобы открыть». +- **Где работает перетаÑ�кивание**: Windows, macOS, Linux в X11 и XWayland. Ð’ Ñ�еанÑ�е Wayland окно перетаÑ�кивание не принимает (Ñ�иÑ�тема и не показывает «можно отпуÑ�тить»): в winit 0.30.13, на котором Ñ�тоит eframe 0.36, перетаÑ�кивание еÑ�ть только в X11 (`platform_impl/linux/x11/event_processor.rs`), в `wayland/` его нет. Принудительный запуÑ�к через X11 не делаем (без обходов). + +## Подготовка к Ñ�опернику: какие партии брать; Ñ�охранённые подготовки (2026-10-31) + +Владелец, задачи 20 и 21: +- **Период.** РÑ�дом Ñ� глубиной — выбор партий: вÑ�е / за 3 меÑ�Ñ�ца / полгода / год / 2 года / поÑ�ледние 50 / 100 / 200 (5 лет владелец убрал: «бред»). У каждого варианта Ñ�разу видно, Ñ�колько партий он берёт (длÑ� показанного цвета). ВремÑ� Ñ�читаетÑ�Ñ� **от поÑ�ледней партии Ñ�оперника в базе**, не от Ñ�егоднÑ� (владелец: «давай от поÑ�ледней») — так Ñ�тараÑ� база не оказываетÑ�Ñ� пуÑ�той. «ПоÑ�ледние N» — Ñ�амые Ñ�вежие N партий каждым цветом. +- **Партии без даты** берутÑ�Ñ� только во «ВÑ�ех партиÑ�х». При выборе периода под Ñ�пиÑ�ком напиÑ�ано, Ñ�колько их не учтено. ЕÑ�ли дат нет ни у одной партии, выбор по времени не показываетÑ�Ñ�, оÑ�таётÑ�Ñ� выбор по чиÑ�лу: поÑ�ледние запиÑ�и базы. +- **Сохранённые подготовки.** С 2026-11-01 (владелец) Ñ�охранение автоматичеÑ�кое, кнопки «Сохранить» больше нет: подготовка попадает в «Подготовки» Ñ�разу при запуÑ�ке, её отчёт Ñ� найденными ошибками запиÑ�ываетÑ�Ñ�, как только поÑ�троен, и дальше вÑ�е изменениÑ� (поиÑ�к ошибок, период, глубина) пишутÑ�Ñ� Ñ�ами. Подготовка лежит в данных программы (`~/.local/share/chesspenguin/preparations/`, не в кÑ�ше). Ð�а каждого игрока базы — одна подготовка: повторный запуÑ�к заменÑ�ет прежнюю. УдалённаÑ� из «Подготовок» не воÑ�крешаетÑ�Ñ� Ñ�ама: пока её Ñ�кран жив, обратно она не пишетÑ�Ñ�. +- **Где их открыть.** Кнопка «📑 Подготовки» в библиотеке: Ñ�пиÑ�ок (имÑ�, база, период, партии, цвет, ошибки, дата), там же «Открыть», «Переименовать», «Удалить» и «♟ Ð�оваÑ� подготовка…». ЕÑ�ли в базе поÑ�вилиÑ�ÑŒ новые партии, подготовка Ñ�обираетÑ�Ñ� заново Ñ� прежними оценками, и движок доÑ�читывает только новые позиции. + +## Подготовка: ручнаÑ� Ñ�верка Ñ� книгой и автозапуÑ�к движка (2026-11-01) + +Владелец: +- **Сверка Ñ� книгой — только вручную.** Ð�втоматичеÑ�кий поиÑ�к «выхода из книги» поÑ�ле поÑ�троениÑ� отчёта грузил вÑ�е Ñ�дра без ведома пользователÑ� (замерено ~2300 % CPU без stockfish). Теперь запуÑ�к — только кнопкой «▶ Сверить Ñ� книгой» Ñ€Ñ�дом Ñ� выбором книги, Ñ� прогреÑ�Ñ�ом «X из N партий» и отдельной оÑ�тановкой. ОÑ�тановка отбраÑ�ывает незавершённый проход (результат применÑ�етÑ�Ñ� только целиком), чаÑ�тичных чиÑ�ел нет; прежний завершённый результат Ñ�охранÑ�етÑ�Ñ�. +- **Движок — автозапуÑ�к.** ПоиÑ�к ошибок Ñ�тартует Ñ�ам поÑ�ле поÑ�троениÑ� отчёта, без диалога-объÑ�Ñ�нениÑ�; вкладка «Ошибки» открываетÑ�Ñ� один раз при фактичеÑ�ком Ñ�тарте. Полный кÑ�ш — без запуÑ�ка и без переключениÑ� вкладки. РучнаÑ� оÑ�тановка Ñ�охранÑ�ет оценённые позиции и запрещает автоперезапуÑ�к Ñ�той конфигурации, **включаÑ� повторный вход в Ñ�охранённую подготовку** (флаг в отчёте); Ñ�броÑ� — только Ñ�мена глубины/периода или Ñ�вное «Продолжить» (запуÑ�кает лишь недоÑ�тающие позиции). +- **Смена уÑ�ловий.** ДругаÑ� книга во времÑ� Ñ�верки отменÑ�ет проход и отбраÑ�ывает его результат; глубина/период отменÑ�ÑŽÑ‚ проход вмеÑ�те Ñ�о Ñ�тарым отчётом. ПоÑ�ле переÑ�троениÑ� книга Ñ�ама не Ñ�верÑ�етÑ�Ñ�, движок запуÑ�каетÑ�Ñ� автоматичеÑ�ки. Уход Ñ� Ñ�крана фон не оÑ�танавливает. +- **Движок не уÑ�тановлен** — автозапуÑ�к не открывает диалог и не качает Ñ�ам: на «Ошибках» предложение добавить движок; поÑ�ле уÑ�тановки — Ñ�ущеÑ�твующий `start_after_engine`. + +Дизайн движка — `docs/design/opponent-prep.md` (§4); прежние книжные требованиÑ� и 22 Ñ�ценариÑ� Ñ�охранены как иÑ�ториÑ� в `docs/research/prep-manual-book.md`. КнижнаÑ� чаÑ�ть отменена Ñ�ледующим решением. + +## Подготовка: Ñ�верка Ñ� книгой удалена (2026-11-02) + +Владелец отменил книжную чаÑ�ть решениÑ� от 2026-11-01: анализ выхода из книги убираетÑ�Ñ� из подготовки полноÑ�тью, а не только непонÑ�тнаÑ� Ñ�водка Ñ� медианой и процентом. Из диалога и отчёта удалÑ�ÑŽÑ‚Ñ�Ñ� выбор книги, ручной запуÑ�к, прогреÑ�Ñ�/оÑ�тановка, фоновый проход, колонки и вÑ�е Ñ�охранённые книжные результаты; алгоритм `find_book_exits`, example и dev-hook тоже удалÑ�ÑŽÑ‚Ñ�Ñ�. Обычный Справочник и книги движков игры не затрагиваютÑ�Ñ�. + +Старые полÑ� книги в JSON отчёта, Ñ�охранённой подготовки и наÑ�троек оÑ�таютÑ�Ñ� паÑ�Ñ�ивными legacy-данными: не вычиÑ�лÑ�ÑŽÑ‚Ñ�Ñ� и не показываютÑ�Ñ�, но не Ñ�тираютÑ�Ñ� при обычном автоÑ�охранении. Миграции и удалениÑ� пользовательÑ�ких файлов нет. Это оÑ�ознанно оÑ�тавлÑ�ет возможноÑ�ть вернуть функцию будущим откатом; в опиÑ�ании будущего коммита удаление книги отметить отдельно. Ð�втозапуÑ�к движка, ручнаÑ� оÑ�тановка и Ñ�охранение `engine_stopped` не менÑ�ÑŽÑ‚Ñ�Ñ�. + +## ПартиÑ� на Lichess / Chess.com (2026-10-31) + +Владелец: из Ñ�качанной партии перейти на её Ñ�траницу. СÑ�ылка берётÑ�Ñ� из тега Link (Chess.com), иначе из Site (Lichess), еÑ�ли там веб-адреÑ�. Кнопка «ðŸŒ�» в шапке партии поÑ�ле результата, пункт в ☰ и в контекÑ�тном меню Ñ�троки Ñ�пиÑ�ка партий. ПартиÑ� Lichess открываетÑ�Ñ� на показанном ходу (`#ply`) и Ñ�о Ñ�тороны, котораÑ� внизу доÑ�ки (`/black`); у Chess.com такой Ñ�Ñ�ылки нет — открываетÑ�Ñ� Ñ�траница партии. Ð�дреÑ� из подÑ�троки шапки убран: его открывает глобуÑ�. + +## Дебютные репертуары и тренировка по дереву (2026-11-02) + +ПоÑ�ле иÑ�Ñ�ледованиÑ� ChessTempo (`docs/research/chesstempo-opening-trainer.md`) владелец делегировал оÑ�тавшиеÑ�Ñ� решениÑ� оркеÑ�тратору и попроÑ�ил начать реализацию. ПринÑ�то: + +- **Два режима.** Одноцветный ChessTempo-режим: пользователь играет Ñ�вою Ñ�торону, программа отвечает только ходами включённого дерева; SRS-задание — конкретный ход. Режим за оба цвета: пользователь делает каждый полуход, любой включённый ход из текущей позиции принимаетÑ�Ñ� и ведёт по его ветке, ход вне разрешённых продолжений — ошибка. Прежний запрет одноцветного режима отменён. ПодÑ�казка по запроÑ�у поÑ�ле третьей ошибки и отметка «Ñ� подÑ�казкой» Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�. +- **Библиотека.** Ð�а Ñ�кране баз Ñ€Ñ�дом Ñ� «Подготовками» — «Тренировка дебюта». Полноценный Ñ�кран репертуаров, дерева и тренировки, не поÑ�ледовательноÑ�ть модальных окон. Прежнее «Учить дебют до Ñ�того хода» заменÑ�етÑ�Ñ� на **«Добавить в репертуар…»**: путь от начала партии до выбранного хода Ñ�ливаетÑ�Ñ� Ñ� деревом без немедленного запуÑ�ка и без изменениÑ� иÑ�ходной партии/PGN. +- **PGN и глубина.** Репертуар — Ñ�амодоÑ�таточный PGN-Ñ�нимок Ñ�о вÑ�еми ветками, комментариÑ�ми, NAG и иÑ�ходным FEN. Учебные хвоÑ�ты не удалÑ�ÑŽÑ‚Ñ�Ñ� и не угадываютÑ�Ñ� автоматичеÑ�ки. По умолчанию тренируютÑ�Ñ� первые **10 ходов (20 полуходов)**; глубину можно менÑ�ть, ветки можно отключать без удалениÑ� и ограничивать облаÑ�ть тренировки. Добавление «до Ñ�того хода» Ñ�охранÑ�ет точный выбранный префикÑ�, без Ñ�оÑ�едних веток и хвоÑ�та. +- **ТранÑ�позиции и Ñ�татиÑ�тика.** Одинаковые позиции объединÑ�ÑŽÑ‚Ñ�Ñ� по FEN4 внутри одного репертуара: одна learning-запиÑ�ÑŒ и каноничеÑ�кое продолжение, вÑ�е PGN-пути Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�. Между разными репертурами и режимами White/Black/Both Ñ�татиÑ�тика не Ñ�мешиваетÑ�Ñ�. Старые line-run агрегаты не превращаютÑ�Ñ� в выдуманную per-move Ñ�татиÑ�тику. +- **Фундаментальный объём.** Ð�еÑ�колько репертуаров, добавление/импорт дерева, depth/disable, одноцветнаÑ� SRS-очередь (due/unseen, уÑ�пех отодвигает, ошибка приближает), обзор подрÑ�д и Ñ�начала новые/давние, транÑ�позиции, Ñ�татиÑ�тика по ходам/веткам/репертурам. РаÑ�ширенные графики, resistant-наборы и маÑ�Ñ�овые операции — Ñ�ледующие Ñ�тапы. +- **Платформы.** Сначала полный desktop. Android продолжает иÑ�пользовать прежний линейный тренер, его UniFFI API и `training.json`; новаÑ� библиотека требует отдельных Kotlin-Ñ�кранов позже. Web не включаетÑ�Ñ� до отдельного хранилища VFS. Ð’Ñ�е запиÑ�и атомарны, ошибки видны пользователю, иÑ�ходные базы не изменÑ�ÑŽÑ‚Ñ�Ñ�. + +## Прохождение дебютов без Ñ�крытого целевого хода (2026-11-02) + +Владелец поÑ�ле живой тренировки отверг Ñ�ценарий «ход еÑ�ть в репертуаре, но Ñ�ейчаÑ� +повторÑ�етÑ�Ñ� другой»: непонÑ�тно, чего программа требует и как продолжить. Это +изменÑ�ет прежние решениÑ� о target/try again в одноцветном тренере. + +- ОÑ�новной Ñ�ценарий desktop — **«Пройти варианты»**: выбрать цвет и пройти ветку + целиком. Любой включённый ход принимаетÑ�Ñ�, за другой цвет отвечает программа + ходами из PGN. За обе Ñ�тороны вÑ�е ходы делает пользователь. +- Ð�втоответы Ñ�ледуют очередной предложенной ветке, пока пользователь не выбрал + другое включённое продолжение. Его выбор переключает фактичеÑ�кий путь. +- ПодÑ�казка доÑ�тупна Ñ�разу и предлагает ход текущей ветки. Ð�а развилке Ñ�вно + Ñ�казано, что допуÑ�тимо неÑ�колько продолжений. Ошибка — только ход вне + включённого репертуара; возвращение позиции Ñ�опровождаетÑ�Ñ� понÑ�тной подÑ�казкой. +- ПоÑ�ле конца облаÑ�ти/глубины/лиÑ�та/повторениÑ� — результат фактичеÑ�кого прохода, + оÑ�новное дейÑ�твие «СледующаÑ� ветка» (Enter), отдельно «Повторить путь». +- Повтор отдельных позиций — отдельный дополнительный режим. И здеÑ�ÑŒ включённаÑ� + альтернатива принимаетÑ�Ñ�: учитываетÑ�Ñ� только Ñ�ыгранный ход, а неÑ�деланнаÑ� + целеваÑ� позициÑ� оÑ�таётÑ�Ñ� due/unseen. Угадывать Ñ�крытый ответ не требуетÑ�Ñ�. +- Старые Ñ�охранённые наÑ�тройки очереди однократно переключаютÑ�Ñ� на оÑ�новной + Ñ�ценарий Ñ� Ñ�охранением выбранного цвета. Позднее Ñ�вно выбранный режим повторениÑ� + Ñ�охранÑ�етÑ�Ñ�; PGN и иÑ�ториÑ� попыток при миграции не менÑ�ÑŽÑ‚Ñ�Ñ�. +- Android оÑ�таётÑ�Ñ� на Ñ�таром линейном API; web новый вход не получает. + +## ПроÑ�таÑ� Ñ�лучайнаÑ� тренировка вариантов (2026-11-03) + +Владелец отменил ручные параметры и раÑ�ширенные режимы в desktop-интерфейÑ�е. Это решение имеет приоритет над пунктами про глубину, disabled, scope и SRS выше; внутренние Ñ�овмеÑ�тимые API и Ñ�тараÑ� Ñ�татиÑ�тика могут оÑ�татьÑ�Ñ�, но Ñ�крыто ограничивать тренировку не должны. + +- Ð’ репертуаре оÑ�таютÑ�Ñ� только выбор цвета `Белые / Чёрные / Оба`, чиÑ�ло доÑ�тупных вариантов и запуÑ�к. Ð�аÑ�троек глубины, облаÑ�ти, отключениÑ� веток и «Пройти варианты / ПовторÑ�ть отдельные позиции» нет. Видимое дерево ходов также удалено; PGN-дерево оÑ�таётÑ�Ñ� внутренней моделью. +- Ð’ Ñ�амой тренировке текÑ�товые ходы также не показываютÑ�Ñ�: ни SAN/номера, ни отметки ошибок у ходов, ни отдельнаÑ� панель нотации. Повторное уточнение владельца 2026-11-03 выбрало удаление, а не копирование нотации из Ñ�крана партии. ПроÑ�матривать уже показанные позиции можно только на доÑ�ке прежними кнопками/клавишами; внутренний путь длÑ� механики Ñ�охранÑ�етÑ�Ñ�. +- ТренируютÑ�Ñ� вÑ�е варианты целиком, без лимита 20 полуходов. Старые `max_plies` и `disabled_prefixes` при загрузке библиотеки Ñ�нимаютÑ�Ñ�; PGN и иÑ�ходные файлы не менÑ�ÑŽÑ‚Ñ�Ñ�. +- Очередь Ñ�лучайнаÑ�. Полный маршрут не повторÑ�етÑ�Ñ�, пока пользователь не прошёл оÑ�тальные маршруты текущего круга; затем начинаетÑ�Ñ� новый Ñ�лучайный круг. Общий префикÑ� разных веток не Ñ�читаетÑ�Ñ� переÑ�ечением: иначе невозможно пройти вÑ�е ветки. +- Проход может начинатьÑ�Ñ� не Ñ� первого хода. Программа автоматичеÑ�ки показывает предыдущий учаÑ�ток как контекÑ�Ñ‚ и предлагает продолжить вариант; длÑ� White/Black перваÑ� пользовательÑ�каÑ� позициÑ� Ñ�оответÑ�твует выбранному цвету, длÑ� Both пользователь продолжает за обе Ñ�тороны. +- Ð�а развилке по-прежнему принимаетÑ�Ñ� любой ход из PGN. ПоÑ�ле завершениÑ� две отдельные операции: «Повторить путь» — тот же фактичеÑ�кий маршрут Ñ� тем же началом, без продвижениÑ� очереди; «СледующаÑ� ветка» — новый непройденный маршрут текущего круга. +- Ð’ библиотеке оÑ�таютÑ�Ñ� `Ð�азвание | Варианты | меню`. ЧиÑ�ло вариантов — доÑ�тупные полные маршруты, а не завершённые тренировки. Колонки due удалены вмеÑ�те Ñ� SRS UI; Ñ�охранённые попытки и иÑ�ториÑ� не Ñ�тираютÑ�Ñ�. +- СлучайнаÑ� очередь не блокирует окно и не требует материализации вÑ�ех маршрутов большого дерева. Это отноÑ�итÑ�Ñ� и к «Следующей ветке», не только к первому запуÑ�ку. КурÑ�ор и Ñ�овмеÑ�тимоÑ�ть Ñ�охранённой Ñ�татиÑ�тики проверÑ�ÑŽÑ‚Ñ�Ñ� теÑ�тами; изменение PGN начинает новый круг по fingerprint Ñ�одержимого, даже еÑ�ли чиÑ�ло маршрутов оÑ�талоÑ�ÑŒ прежним. +- Уточнение владельца 2026-11-03: Ñ�оздание пуÑ�того репертуара оÑ�тавлÑ�ет пользователÑ� в Ñ�пиÑ�ке; импорт/Ñ�кÑ�порт убраны Ñ� Ñ�крана доÑ�ки и доÑ�тупны в меню Ñ�троки; наÑ�тройки — в правом углу шапки. СпиÑ�ок оформлен как оÑ�новнаÑ� таблица партий: один клик выделÑ�ет, двойной открывает. + +## Единый Ñ�кран репертуаров и ECO в таблице (2026-11-03) + +Владелец отменил раздельные Ñ�краны Ñ�пиÑ�ка и опиÑ�аниÑ� репертуара. Это решение заменÑ�ет прежние требованиÑ� к переходу по двойному клику и кнопкам навигации по позициÑ�м. + +- «Тренировка дебюта» Ñ�разу открывает одну рабочую облаÑ�ть Ñ� доÑ�кой. Карточка выбранного репертуара, таблица и вÑ�е операции библиотеки находÑ�Ñ‚Ñ�Ñ� Ñ€Ñ�дом; таблица доÑ�тупна и во времÑ� тренировки. Отдельного Ñ�крана Ñ�пиÑ�ка нет. +- Один клик выбирает Ñ�троку и менÑ�ет доÑ�ку без перехода. ЗапуÑ�к — отдельной кнопкой. Кнопки `â�® â—€ â–¶ â�­` удалены из панели тренировки. +- Таблица `Ð�азвание | ECO | Варианты | ⋯`: названиÑ� дебютов и вариантов перечиÑ�лены Ñ� новой Ñ�троки в Ñ�чейке названиÑ�, коды — в отдельной колонке. ИÑ�пользуетÑ�Ñ� вÑ�троенный Ñ�правочник `chess-openings`, наиболее точное название каждого полного маршрута; вычиÑ�ление выполнÑ�етÑ�Ñ� в фоне. БольшаÑ� база не требуетÑ�Ñ�. +- Создание, переименование, импорт, Ñ�кÑ�порт и удаление выполнÑ�ÑŽÑ‚Ñ�Ñ� в той же рабочей облаÑ�ти. Ð�еÑ�охранённаÑ� Ñ�татиÑ�тика активной тренировки по-прежнему защищена от молчаливой потери. +- Уточнение владельца 2026-11-03: «Пути» переименованы в «Варианты»; ECO выровнены поÑ�трочно Ñ� названиÑ�ми тем же мелким шрифтом; карточка и Ñ�татиÑ�тика иÑ�пользуют ровные Ñ�етки. Кнопка «Репертуары» удалена. СтатуÑ�Ñ‹ «Импорт PGN», «ИндекÑ�ациÑ� вариантов и ECO» и «Подготовка тренировки» заменÑ�ÑŽÑ‚ непонÑ�тное «Готовим дерево». +- Уточнение владельца 2026-11-03: Ñ�татиÑ�тика вÑ�егда занимает одну выÑ�оту, до попыток показаны нули и прочерк даты. Ð’Ñ�е Ñ�троки таблицы одинаковые, Ñ� меÑ�том под пÑ�ть ECO/названий. Добавлен Ñ�броÑ� Ñ�татиÑ�тики текущего репертуара и цвета Ñ� подтверждением; другие режимы не очищаютÑ�Ñ�. +- Уточнение владельца 2026-11-03: чиÑ�ло вариантов — Ñ�лева у подпиÑ�и, «Ð�ачать» и «СброÑ�ить» — одинаковой ширины. ДлÑ� UI обÑ�зательна приёмка отдельным дизайн-ревьюером Ñ� реальными Ñ�нимками и проверкой отÑ�утÑ�твиÑ� Ñ�качков; требование закреплено в `AGENTS.md` и `.opencode/agents/`. +- По результатам незавиÑ�имой визуальной приёмки: workspace и тренировка имеют общую шапку и одинаковую геометрию доÑ�ки; нижнÑ�Ñ� облаÑ�ть задаётÑ�Ñ� Ñ�вными прÑ�моугольниками, чтобы Ñ�одержимое не менÑ�ло её размер. ВыбраннаÑ� Ñ�трока прокручиваетÑ�Ñ� в видимую облаÑ�ть один раз, запуÑ�к иÑ�пользует primary-Ñ�тиль. +- Уточнение владельца 2026-11-03: Ñ�лучайный круг и Ñ�чётчик иÑ�пользуют только иÑ�ходные PGN-ветки; переключение между ними по транÑ�позициÑ�м не Ñ�оздаёт новые варианты. Старт не позже чем за Ñ�емь полуходов до конца ветки, короткие ветки проходÑ�Ñ‚Ñ�Ñ� Ñ� начала. +- Уточнение владельца 2026-11-03: на доÑ�ке тренировки показываютÑ�Ñ� NAG и графичеÑ�кие пометки PGN (`[%cal]`, `[%csl]`) теми же значками и цветами, что при проÑ�мотре партии. Пометки отноÑ�Ñ�Ñ‚Ñ�Ñ� только к текущему узлу. +- Уточнение владельца 2026-11-03: раздел «Прежние линии» удалён из библиотеки как непонÑ�тный и ненужный до первого выпуÑ�ка функции. ПереключателÑ� и таблицы архивной Ñ�татиÑ�тики больше нет. Старые файлы данных и Android-Ñ�овмеÑ�тимоÑ�ть не затрагиваютÑ�Ñ�. +- Уточнение владельца 2026-11-03: Ñ�чейка репертуара получила отÑ�туп 8 pt Ñ�верху и интервал 12 pt перед первым дебютом. Ð�азвание — 16 pt, дебюты/ECO — 14 pt вмеÑ�то заниженного `.small()`; выÑ�ота Ñ�троки 156 pt фикÑ�ирована длÑ� 0–5 названий (верх 8 pt, низ 4 pt), чтобы не было Ñ�качков и вертикального clipping. По результатам незавиÑ�имой визуальной проверки фоновый Ñ�татуÑ� получил поÑ�тоÑ�нную Ñ�троку 24 pt, чтобы таблица не подпрыгивала поÑ�ле индекÑ�ации. + +## Тренажёр по ТЗ ChessTempo: новаÑ� модель обучениÑ� (2026-11-04) + +Владелец подтвердил, что `docs/chesstempo_opening_trainer_TZ.md` имеет приоритет над его прежними импровизированными упрощениÑ�ми и над прежними решениÑ�ми здеÑ�ÑŒ, включаÑ� random path practice, per-repertoire иÑ�торию, any-enabled-answer и изолированный reset. СохранÑ�ÑŽÑ‚Ñ�Ñ� текущаÑ� рабочаÑ� облаÑ�ть, PGN-дерево, FEN4, доÑ�ка, таблица библиотеки, типографика и защита неÑ�охранённых данных. UI развиваетÑ�Ñ� внутри Ñ�той концепции, без переноÑ�а вÑ�ех графиков на один Ñ�кран. + +- **Единица знаниÑ�.** ОбщаÑ� `LearningItem(user/profile, FEN4, expected UCI)`, не запиÑ�ÑŒ по репертуару/режиму. Одинаковый ход в разных репертурах и транÑ�позициÑ�Ñ… имеет общую иÑ�торию и раÑ�пиÑ�ание. ЧленÑ�тво в репертурах/ветках отделено от знаниÑ�. Старые `MoveStats/RunStats/PathStats/random cursor` — legacy, а не второй иÑ�точник новых показателей. +- **Попытки.** Ð�езавиÑ�имые `CORRECT_INDEPENDENT` и `INCORRECT_INDEPENDENT` влиÑ�ÑŽÑ‚ на Ñ�ерии и Accuracy. `PREVIEWED`, `REPLAY_AFTER_ERROR`, `AUTO_CONTEXT`, `ILLEGAL_MOVE` не увеличивают уÑ�пех или ошибку. Learnt — три незавиÑ�имых уÑ�пеха подрÑ�д, но повторениÑ� продолжаютÑ�Ñ�. КаждаÑ� попытка имеет `client_attempt_id` длÑ� идемпотентноÑ�ти. +- **MVP.** Один оÑ�новной ответ на Ñ�обÑ�твенную позицию репертуара; альтернативы оÑ�таютÑ�Ñ� в PGN/редакторе. Это ограничение нашего MVP, не правило ChessTempo: ответ Richard подтверждает, что оригинал может обучать неÑ�колько Ñ�обÑ�твенных ответов одной позиции как отдельные Ñ�лементы. ПоÑ�тому модель ключа Ñ�разу Ñ�одержит UCI и не закрывает раÑ�ширение позже. +- **SRS.** РеализуетÑ�Ñ� проектный пÑ�евдокод ТЗ, не объÑ�влÑ�етÑ�Ñ� побитовым алгоритмом ChessTempo: first correct +1 день, mistake +30 Ñ�екунд, preview +60 Ñ�екунд, growth ×2 от фактичеÑ�ки прошедшего времени, max 1095 дней. Review in Order/Least Recent иÑ�пользуют общий обработчик попыток и тоже обновлÑ�ÑŽÑ‚ SRS. +- **СтатиÑ�тика.** `T = Unseen + Learning + Learnt`; `Uncertain ⊆ Learnt`, `Due ⊆ Learning+Learnt`, повторного Ñ�ложениÑ� нет. Проценты и Ñ�татуÑ�Ñ‹ вычиÑ�лÑ�ет core по активному множеÑ�тву и единому `as_of`, а не UI по Ñ�тарым запиÑ�Ñ�м. ОбщаÑ� Ñ�татиÑ�тика неÑ�кольких репертуаров — union по LearningItemKey. При T=0 проценты — `—`. +- **Reset/delete.** Общий LearningItem Ñ�браÑ�ываетÑ�Ñ� во вÑ�ех затронутых репертурах Ñ� предварительным показом N/M и имён. `Reset selected view only` не предлагать. Удаление репертуара не Ñ�тирает глобальные запиÑ�и; они лишь переÑ�тают входить в активное множеÑ�тво. +- **Хранение.** СледующаÑ� верÑ�иÑ� JSON читает Ñ�тарую, перед запиÑ�ью делает новый backup и Ñ�охранÑ�ет legacy без выдумываниÑ� незавиÑ�имой Accuracy. Старые streak/schedule можно мигрировать конÑ�ервативно; Ñ�мешанные hinted/replay Ñ�чётчики не превращаютÑ�Ñ� в незавиÑ�имые попытки. ЗапиÑ�ÑŒ Ñ�обытиÑ� и изменение Ñ�оÑ�тоÑ�ниÑ� атомарны. +- **Этапы.** Сначала LearningItem/events/SRS/aggregates и AT-Ñ�дро, затем graph/main answer/scope, хранилище v3 и Ñ�трогаÑ� session state machine, затем desktop MVP. ПоÑ�ле него: Review in Order/Least Recent, четыре Learning priority, reinforcement/adaptive context, Uncertain/Resistant, shared reset, иÑ�тории/графики и дашборды V1. V2 вне текущего Ñ�тапа. +- **UI.** Единый workspace Ñ�охранÑ�етÑ�Ñ�. ОÑ�новные CTA и KPI иÑ�пользуют один scope. Таблица оÑ�таётÑ�Ñ� библиотечной, полные summary/иÑ�тории открываютÑ�Ñ� отдельно по мере готовноÑ�ти. Automatic context анимируетÑ�Ñ� поÑ�ледовательно Ñ�о `settings.animation.seconds()` (Off/Fast/Normal/Slow = 0/0,12/0,25/0,5 Ñ�) при фикÑ�ированной Ñ�короÑ�ти; при адаптивной — Ñ� `base / speed_factor` текущего шага. ФактичеÑ�кий slide и scheduler обÑ�заны Ñ�овпадать, автоматичеÑ�кие Ñ�обытиÑ� не Ñ�влÑ�ÑŽÑ‚Ñ�Ñ� незавиÑ�имыми попытками. +- **Context policy.** ШеÑ�ть параметров контекÑ�та/Ñ�короÑ�ти Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ� отдельно длÑ� каждого репертуара в Settings. СеÑ�Ñ�иÑ� получает snapshot политики при Ñ�оздании; изменение наÑ�троек не перепиÑ�ывает уже начатую Ñ�еÑ�Ñ�ию. Дополнительные параметры находÑ�Ñ‚Ñ�Ñ� в collapsed-блоке, доÑ�ка не перегружаетÑ�Ñ�. +- **Dashboard.** Details открывает текущие репертуар и Ñ�торону, Global выбираетÑ�Ñ� Ñ�вно. ВмеÑ�то непонÑ�тного `T` иÑ�пользуетÑ�Ñ� Total; видно `Learnt = Confident + Uncertain`, знаменатель процентов — Total. Графики разделены по вкладкам History/Scheduled/Sequences, точные значениÑ� оÑ�таютÑ�Ñ� в таблицах. Снимок текущей Ñ�татиÑ�тики Ñ�охранÑ�етÑ�Ñ� автоматичеÑ�ки при первом проÑ�мотре scope в локальный день и доÑ�тупен вручную; дубли date/scope запрещены, PGN и знание ходов Ñ�нимок не менÑ�ет. +- **Depth и линии.** `max_plies` из редактора ограничивает тренировочный scope и его CTA/KPI; полнаÑ� иÑ�ториÑ� dashboard Ñ�охранÑ�ет полный scope. СтатиÑ�тика конкретной линии допуÑ�кает переÑ�ечениÑ� Ñ� другими линиÑ�ми; ветка объединÑ�ет Ñ�вои транÑ�позиции, а веÑ�ÑŒ репертуар/Global — только уникальные LearningItemKey. Среднее арифметичеÑ�кое процентов линий не иÑ�пользуетÑ�Ñ�. +- **ВизуальнаÑ� матрица.** По решению владельца 2026-11-04 минимальный размер визуальной приёмки — **960×600**, оÑ�новной — **1400×900**. Размер 640×480 и микро-контейнеры не определÑ�ÑŽÑ‚ дизайн и не иÑ�пользуютÑ�Ñ� длÑ� визуального вердикта; прежние кадры оÑ�таютÑ�Ñ� только иÑ�торичеÑ�кими QA-артефактами. +- **Проверка.** AT-01…30 Ñ�влÑ�ÑŽÑ‚Ñ�Ñ� обÑ�зательными поÑ�тапными критериÑ�ми, а не формальным Ñ�пиÑ�ком. До Ñ�оответÑ�твующей реализации не объÑ�влÑ�ть их выполненными. Production агрегаты проверÑ�ÑŽÑ‚ математичеÑ�кие инварианты и Ñ�ообщают нарушениÑ� в лог. ПоÑ�ле UI — отдельный design reviewer Ñ� реальными Ñ�нимками и переходами, Ñ�оглаÑ�но `AGENTS.md`. + +## Android: открытие PGN из буфера обмена (2026-11-04) + +Владелец уточнил Ñ�ценарий задачи 35. При холодном запуÑ�ке и возврате в приложение оно проверÑ�ет текÑ�Ñ‚ буфера на PGN, но импортирует только поÑ�ле подтверждениÑ� пользователÑ�. При неÑ�кольких партиÑ�Ñ… вÑ�егда открываетÑ�Ñ� перваÑ�; оÑ�тальные оÑ�таютÑ�Ñ� доÑ�тупны в локальной копии базы. Диалог иÑ�пользует Ñ�ущеÑ�твующий Material 3 Ñ�тиль, без нового отдельного Ñ�крана-маÑ�тера. + +- ТекÑ�Ñ‚ проверÑ�етÑ�Ñ� Ñ�ущеÑ�твующим PGN-reader на фоновом потоке; некорректный или пуÑ�той текÑ�Ñ‚ не вызывает предложение. Сетевых вызовов и передачи Ñ�одержимого наружу нет. +- Импорт иÑ�пользует `Library.addCopy`: локальнаÑ� копиÑ� Ñ�охранÑ�ет полное PGN-дерево, комментарии и анализ. Ð�авигациÑ� открывает `GameAt(id, 0)`, незавиÑ�имо от чиÑ�ла запиÑ�ей; поведение обычных файлов `Incoming.Opened` не менÑ�етÑ�Ñ�. +- Один и тот же SHA-256 текÑ�та не предлагаетÑ�Ñ� повторно поÑ�ле открытиÑ� или отказа, в том чиÑ�ле при повороте и холодном перезапуÑ�ке. Сам текÑ�Ñ‚ в наÑ�тройки не запиÑ�ываетÑ�Ñ�; обработанный hash Ñ�охранÑ�етÑ�Ñ� локально. СоÑ�тоÑ�ние нерешённого вопроÑ�а Ñ�охранÑ�етÑ�Ñ� в Application, аÑ�инхронный результат уÑ�таревшего текÑ�та отбраÑ�ываетÑ�Ñ�. +- Диалог не перекрывает `UpdateSheet`, `Incoming.Opening` или `Incoming.Failed`; поÑ�ле подтверждениÑ� иÑ�пользуетÑ�Ñ� Ñ�ущеÑ�твующий прогреÑ�Ñ� и обработка ошибок. ЕÑ�ли блокировщик поÑ�влÑ�етÑ�Ñ� поверх нерешённого предложениÑ�, оно Ñ�крываетÑ�Ñ� без отказа, а поÑ�ле закрытиÑ� выполнÑ�етÑ�Ñ� Ñ�вежаÑ� проверка. + + +## Переработка UI/UX тренажёра поÑ�ле проверки владельцем (2026-11-05) + +Владелец отклонил предыдущую компоновку: непонÑ�тные Total/Unseen, техничеÑ�каÑ� глубина, +разнородные и разнеÑ�ённые кнопки, нечитаемые ветки, ручное Ñ�охранение иÑ�тории. +По Ñ�тому запроÑ�у дизайн переÑ�мотрен (`docs/design/opening-cleanup-2026-11-05.md`). +Реализованы единаÑ� Ñ�трока трёх оÑ�новных дейÑ�твий, Ñ�водка Ñ� единицей «ходы», отÑ�утÑ�твие +чиÑ�ловой глубины на Ñ�тарте, обзор выбранного репертуара, дополнительный отчёт вариантов +Ñ� четырьмÑ� колонками и автоматичеÑ�каÑ� иÑ�ториÑ� без ручной кнопки. Прежние указаниÑ� о +раÑ�положении кнопок Ñ�броÑ�а/деталей и дублирующем Ñ�чётчике вариантов заменены Ñ�той компоновкой. +SRS, общий прогреÑ�Ñ�, Ñ�вное подтверждение Ñ�броÑ�а и точные Ñ�ущеÑ�твующие лимиты Ñ�охранены. +Это реализациÑ� по запроÑ�у владельца; незавиÑ�имаÑ� QA-проверка не заменÑ�ет его оценку дизайна. + + +## Тихие фоновые операции и общаÑ� дизайн-Ñ�иÑ�тема (2026-11-05) + +Владелец попроÑ�ил не показывать «Сохранение прогреÑ�Ñ�а» при каждом ходе и вращающийÑ�Ñ� +индикатор при запуÑ�ке на главном Ñ�кране. ОбычнаÑ� запиÑ�ÑŒ прогреÑ�Ñ�а выполнÑ�етÑ�Ñ� без +уведомлениÑ�; ошибки и безопаÑ�ный повтор оÑ�таютÑ�Ñ� видимыми. Ð�а главном Ñ�кране круговые +индикаторы убраны, информативные текÑ�товые Ñ�татуÑ�Ñ‹/проценты длительных операций Ñ�охранены. + +ОбщаÑ� дизайн-Ñ�иÑ�тема опиÑ�ана в `docs/design/design-system.md` по библиотеке, проÑ�мотру +партии и игре Ñ� движком. Тренировка дебюта не Ñ�влÑ�етÑ�Ñ� Ñ�тилевым Ñ�талоном. ФактичеÑ�кие +значениÑ� текущего UI отделены от рекомендуемых правил унификации новых Ñ�кранов. + +## Общие наÑ�тройки и ошибки при подготовке к Ñ�опернику (2026-11-05) + +По запроÑ�у владельца глобальные наÑ�тройки доÑ�тупны Ñ�права в шапке библиотеки +репертуаров, Ñ�татиÑ�тики, прохождениÑ� тренировки и редактора. ИÑ�пользуетÑ�Ñ� общаÑ� +кнопка библиотеки/партии: «⚙ Ð�аÑ�тройки», в узком окне — значок Ñ� подÑ�казкой Ctrl+,. +Параметры конкретной тренировки оÑ�таютÑ�Ñ� отдельным дейÑ�твием. Открытие общих +наÑ�троек не Ñ�браÑ�ывает текущую задачу, позицию, вкладку или черновик. + +Владелец иÑ�ключил из подготовки ошибки изучаемого игрока, которым предшеÑ�твовала +ошибка его Ñ�оперника. Отбор проходит по хронологии каждой партии: поÑ�ле первого +?!, ? или ?? другой Ñ�тороны поздние ошибки игрока не включаютÑ�Ñ�. Пороги оÑ�таютÑ�Ñ� +Ñ�ущеÑ�твующими; ранние ошибки игрока Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�. Пока предыдущие ходы другой +Ñ�тороны не проверены, позднÑ�Ñ� ошибка не публикуетÑ�Ñ�. При транÑ�позиции применимоÑ�ть +проверÑ�етÑ�Ñ� по иÑ�тории каждой партии, а не только по общей позиции. + +КÑ�ш и Ñ�охранённые отчёты переÑ�читывают производные ошибки/повторы/Ñ�чётчики из +Ñ�охранённых оценок; повторный запуÑ�к движка длÑ� Ñ�того не нужен. Старые Ñ�чётчики +в Ñ�пиÑ�ке подготовок Ñ�крываютÑ�Ñ� до открытиÑ� и переÑ�чёта Ñ�оответÑ�твующего отчёта. +PGN, дерево дебютов и оценки движка от Ñ�того фильтра не менÑ�ÑŽÑ‚Ñ�Ñ�. + +## Первый вход и понÑ�тные параметры тренировки (2026-11-05) + +При первом открытии автоматичеÑ�ки выделенный репертуар проходит тот же выбор, +что и при клике: Ñ�разу воÑ�Ñ�танавливаютÑ�Ñ� его Ñ�охранённые цвет, режим и порÑ�док. +Раньше до клика иÑ�пользовалиÑ�ÑŒ белые и SRS по умолчанию, поÑ�тому кнопка и Ñ�чётчики +могли отноÑ�итьÑ�Ñ� не к ожидаемым наÑ�тройкам. При доÑ�тупных заданиÑ�Ñ… запуÑ�к работает +без повторного выбора Ñ�троки. РаÑ�пиÑ�ание SRS не обходитÑ�Ñ�: еÑ�ли пока нет заданий, +подÑ�казка объÑ�Ñ�нÑ�ет возможноÑ�ть выбрать режим повторениÑ�. + +Параметры вынеÑ�ены из длинного меню в отдельное окно Ñ� прокручиваемым Ñ�одержимым +и видимой кнопкой закрытиÑ�. Группы: предыдущие ходы, пропуÑ�к знакомого начала, +Ñ�короÑ�ть показа; единицы и уÑ�ловиÑ� дейÑ�твиÑ� подпиÑ�аны. «Минимум дней длÑ� закреплениÑ�» +заменён на горизонт повторениÑ� до Ñ�рока: Ñ�то не возраÑ�Ñ‚ знаниÑ�. Порог пропуÑ�ка — +Ñ�ериÑ� верных ответов длÑ� каждого Ñ�воего хода, а не чиÑ�ло пропуÑ�каемых ходов. +Параметры отноÑ�Ñ�Ñ‚Ñ�Ñ� к новым Ñ�еÑ�Ñ�иÑ�м; продолжение Ñ�охранённой Ñ�еÑ�Ñ�ии оÑ�тавлÑ�ет её +прежнюю политику, как и до UI-правки. Хранение, диапазоны и алгоритмы не менÑ�лиÑ�ÑŒ. + +Ð�езавиÑ�имаÑ� Ñ�верка Ñ�чётчиков по пользовательÑ�кой копии, журналу Ñ�обытий и реальным +Ñ�еÑ�Ñ�иÑ�м не выÑ�вила арифметичеÑ�кого дефекта. «Изучено» по-прежнему требует трёх +Ñ�амоÑ�тоÑ�тельных верных ответов подрÑ�д; автоматичеÑ�кий показ и повтор решениÑ� +не увеличивают Ñ�ерию, ошибка Ñ�браÑ�ывает её. ПодÑ�казка не увеличивает и не Ñ�браÑ�ывает +Ñ�ерию. Параметры контекÑ�та не менÑ�ÑŽÑ‚ Ñ�тот критерий. ПодробноÑ�ти и границы проверки: +`docs/qa/learning-counts-and-parameters-2026-11-05.md`. + +## Обозначение альфы и управление доÑ�кой тренировки (2026-11-05) + +По запроÑ�у владельца название раздела в библиотеке и его шапке — +«Тренировка дебюта (α верÑ�иÑ�)», Ñ� гречеÑ�кой буквой α. Кнопка переворота доÑ�ки +отноÑ�итÑ�Ñ� к нижней панели управлениÑ�, как на Ñ�кране партии, а не к группе подÑ�казки. +ПодÑ�казка и управление показом ходов оÑ�таютÑ�Ñ� возле текущего заданиÑ�. + +Повтор первого хода оказалÑ�Ñ� повторным показом автоматичеÑ�кого контекÑ�та Ñ�ледующей +цели, а не двойным Ñ�амоÑ�тоÑ�тельным ответом. ЕÑ�ли новаÑ� цель продолжает уже показанный +путь того же репертуара, UI Ñ�охранÑ�ет текущую доÑ�ку и не озвучивает/анимирует Ñ�тот +префикÑ� повторно. ПроверÑ�ÑŽÑ‚Ñ�Ñ� полный путь и позициÑ�; Ñ�овпадение FEN при другом порÑ�дке +ходов недоÑ�таточно. СамоÑ�тоÑ�тельные вопроÑ�Ñ‹ контекÑ�та не пропуÑ�каютÑ�Ñ�. СобытиÑ� +AUTO_CONTEXT Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ� прежним Ñ�поÑ�обом, включаÑ� обработку ошибки запиÑ�и и retry. + +## ПеретаÑ�кивание во времÑ� Ñ�охранениÑ� ответа (2026-11-05) + +Отдельно воÑ�произведён возврат перенеÑ�ённой фигуры на иÑ�ходную клетку во времÑ� +фоновой запиÑ�и. Ð�а отпуÑ�кании мыши и в кадрах ожиданиÑ� ещё риÑ�овалаÑ�ÑŒ Ñ�тараÑ� доÑ�ка. +Виджет теперь риÑ�ует результат легального переноÑ�а уже в кадре отпуÑ�каниÑ�; +тренировочный UI Ñ�разу показывает Ñ�ту позицию, Ñ�охранÑ�Ñ� блокировку повторного ввода +до подтверждениÑ� запиÑ�и. Подтверждение и retry не запуÑ�кают движение заново. +СамоÑ�тоÑ�тельный уÑ�пех не запиÑ�ываетÑ�Ñ� до уÑ�пешного Ñ�охранениÑ�. ДлÑ� хода двумÑ� +кликами оÑ�таётÑ�Ñ� обычнаÑ� анимациÑ�; длÑ� неверного ответа — возврат, длÑ� рокировки +и взÑ�тиÑ� — движение ладьи и иÑ�чезновение взÑ�той фигуры. PGN-модель виджет не менÑ�ет. + +## СтабильнаÑ� панель библиотеки при запуÑ�ке (2026-11-06) + +По Ñ�ообщению владельца воÑ�произведены Ñ�двиг кнопок поÑ�ле проверки Ñ�ети и ложный +неактивный Ñ�тиль отдельных дейÑ�твий на переходном кадре. Кнопка «Онлайн-партии» +теперь приÑ�утÑ�твует Ñ� первого кадра на поддерживающей Ñ�ту функцию платформе; +загрузка базы и завершение Ñ�етевой проверки не менÑ�ÑŽÑ‚ Ñ�оÑ�тав панели. ДейÑ�твиÑ�м +назначены Ñ�табильные идентификаторы, чтобы предыдущий ответ Ñ�оÑ�еднего разделителÑ� +не определÑ�л оформление кнопки. Счётчик Ñ�качиваниÑ� оÑ�таётÑ�Ñ� в подÑ�казке и диалоге, +не раÑ�ширÑ�Ñ� панель по мере роÑ�та чиÑ�ла. + +При раннем открытии окна онлайн-партий текÑ�Ñ‚ объÑ�Ñ�нÑ�ет проверку Ñ�оединениÑ�; +при недоÑ�тупноÑ�ти обеих платформ предлагаетÑ�Ñ� повторить её. СпиÑ�ок платформ +по-прежнему Ñ�одержит только ответившие Ñ�ервиÑ�Ñ‹. ДоÑ�тупноÑ�ть обновлениÑ� уже +открытой онлайн-базы Ñ�охранÑ�ет прежнюю завиÑ�имоÑ�ть от результата проверки. +Ð�а главный Ñ�кран индикатор ожиданиÑ� не возвращаетÑ�Ñ�. + +## ВыпуÑ�к 2.2.0 (2026-11-06) + +Владелец разрешил закоммитить изменениÑ�, Ñ�лить ветку тренировки в `main`, отправить +в Forgejo и GitHub и выпуÑ�тить Ñ�борки Ñ� обновлением Ñ�айта. ВерÑ�иÑ� «2.2» оформлÑ�етÑ�Ñ� +по принÑ�тому SemVer как `2.2.0`, тег `v2.2.0`. Тренировка дебюта в desktop Ñ�охранÑ�ет +пометку α; Android получает уже включённое открытие PGN из буфера Ñ� подтверждением. +GitHub публикуетÑ�Ñ� Ñ�ущеÑ�твующим фильтром внутренних материалов; ТЗ тренажёра +также иÑ�ключено. Отправка главной ветки и тегов атомарнаÑ�, без перезапиÑ�и чужой +иÑ�тории. Сайт получает номер и файлы выпуÑ�ка из GitHub; новый текÑ�Ñ‚ на девÑ�ти +Ñ�зыках публикуетÑ�Ñ� поÑ�ле готовноÑ�ти Ñ�борок. + +## Разметка PGN и Ñ�обÑ�твенные альтернативы поÑ�ле 2.2.0 (2026-11-06) + +Владелец подтвердил выпуÑ�к 2.2.0 в подготовленном виде и поручил Ñ�ледующую +доработку: значки ходов, авторÑ�кие Ñ�трелки и отмеченные полÑ� показываютÑ�Ñ� в +тренировке как поÑ�ле ответа пользователÑ�, так и при автоматичеÑ�кой прокрутке. +ИÑ�пользуетÑ�Ñ� Ñ�ущеÑ�твующее оформление проÑ�мотра партии; обычный проÑ�мотр, +Ñ�оздание партий и анализ не изменÑ�ÑŽÑ‚Ñ�Ñ�. Пометки отноÑ�Ñ�Ñ‚Ñ�Ñ� к конкретному +показанному узлу PGN, а не к Ñ�овпавшему FEN и не к уже выбранной Ñ�ледующей задаче. + +По новому указанию изучаютÑ�Ñ� разные Ñ�обÑ�твенные варианты, поÑ�тому прежнее +ограничение одним main-answer отменÑ�етÑ�Ñ�. Ключ знаниÑ� оÑ�таётÑ�Ñ� `(профиль, FEN4, +UCI)`: разные ответы различаютÑ�Ñ�, транÑ�позиции одного ответа разделÑ�ÑŽÑ‚ иÑ�торию. +Другой ожидающий ответ из той же позиции получает Ñ�обÑ�твенный зачёт, иÑ�ходнаÑ� +цель оÑ�таётÑ�Ñ� в очереди. Уже повторённый или не запланированный активный ответ +репертуара не запиÑ�ываетÑ�Ñ� как ошибка. Предпочтительный ход влиÑ�ет только на +порÑ�док; выключение ветки — отдельное дейÑ�твие. КонтекÑ�Ñ‚ хранит реальный путь +PGN длÑ� точного выбора пометок, минимальнаÑ� глубина графа оÑ�таётÑ�Ñ� отдельной метрикой. + +Отдельно запрошены уточнениÑ�: иÑ�ключать ли Ñ�обÑ�твенные ветки Ñ� `?`/`??`/`?!` и +Ñ�читать ли авторÑ�кую Ñ�трелку, раÑ�крывающую ответ, подÑ�казкой длÑ� SRS. До ответа +Ñ�ти дополнительные политики не включены: оценки NAG Ñ�ами не фильтруют ветки, +риÑ�унки PGN Ñ�ами не Ñ�оздают Ñ�обытий PREVIEWED. + +## ВыпуÑ�к 2.3.0 (2026-11-06) + +Владелец поручил коммит, push, новый тег Ñ� минорным увеличением верÑ�ии и выпуÑ�к +Ñ�борок. ПоÑ�ле 2.2.0 Ñ�то верÑ�иÑ� 2.3.0, тег v2.3.0. Ð’ выпуÑ�к входÑ�Ñ‚ аннотации PGN, +обучение вÑ�ем включённым вариантам и уÑ�транение задержек автоматичеÑ�кого контекÑ�та. +ПубликациÑ� через main и штатный фильтр GitHub; Ñ�ущеÑ�твующие теги не менÑ�ÑŽÑ‚Ñ�Ñ�. +Ð�езавершённых изменений продуктовых правил NAG и авторÑ�ких Ñ�трелок в выпуÑ�ке нет: +вÑ�е включённые ветки изучаютÑ�Ñ�, риÑ�унки PGN Ñ�ами не менÑ�ÑŽÑ‚ тип зачёта. + +## Тренировка дебюта v2 (2026-11-26) + +Владелец поручил оркеÑ�тратору Ñ�амоÑ�тоÑ�тельно переработать раздел: «проще, понÑ�тнее, функционально», оÑ�тальные разделы не трогать. ПринÑ�то (концепциÑ� `docs/design/opening-trainer-concept-2026-11-26.md`, Ñ�пецификациÑ� `docs/design/opening-trainer-v2-spec.md`): + +- Ядро Ñ�охранÑ�етÑ�Ñ�: LearningItem `(профиль, FEN4, UCI)`, SRS, неÑ�колько Ñ�обÑ�твенных ответов (2.3.0), формат файлов и типы Settings без изменений. +- ЗанÑ�тие = вÑ�е ходы к повторению + до 10 новых, «Ещё 10 новых». Подача линией от начала; Ñ�прашиваютÑ�Ñ� только ходы к повторению и новые; новый ход Ñ�начала показываетÑ�Ñ� Ñ�трелкой; ошибка показывает правильный ход и возвращаетÑ�Ñ� в том же занÑ�тии. Только что показанные ходы по раÑ�пиÑ�анию возвращаютÑ�Ñ� через минуту, поÑ�тому Ñ�ледующее занÑ�тие в тот же день включает их. +- ПрогреÑ�Ñ� — в ходах: «Выучено X из Y · учитÑ�Ñ� Z». «Выучено» по Ñ�дру — три верных Ñ�амоÑ�тоÑ�тельных ответа подрÑ�д, обычно за неÑ�колько дней; поÑ�тому таблица показывает и «учитÑ�Ñ�» (двухÑ�егментнаÑ� полоÑ�а, подÑ�казка), а итог занÑ�тиÑ� — «УчитÑ�Ñ�: +N» (2026-11-27). +- Из UI удалены выбор режима и порÑ�дка, шеÑ�ть параметров контекÑ�та, дашборд Ñ� вкладками и графиками, отчёт Branches/Lines, режим «за оба цвета». Сохранённые значениÑ� оÑ�таютÑ�Ñ� на диÑ�ке, но не дейÑ�твуют; лимит `max_plies` Ñ�нимаетÑ�Ñ� при загрузке; незавершённые Ñ�еÑ�Ñ�ии 2.x не возобновлÑ�ÑŽÑ‚Ñ�Ñ�. Это заменÑ�ет UI-чаÑ�ти решений 2026-11-04/05. +- Вторичные дейÑ�твиÑ�: «Повторить вÑ�Ñ‘ подрÑ�д», «Тренировать Ñ�ту ветку», Ñ�кран «Варианты». РедактированиÑ� ходов на доÑ�ке в Ñ�том Ñ�тапе нет. Строка ходов линии в занÑ�тии показываетÑ�Ñ� по решению владельца 2026-11-27 (заменÑ�ет решение 03.11): одна бледнаÑ� Ñ�трока SAN Ñ� номерами до позиции на доÑ�ке, без Ñ�прашиваемого хода и без отметок ошибок, обрезка Ñ�лева, поÑ�тоÑ�ннаÑ� выÑ�ота; меÑ�то — между Ñ�трокой дебюта и комментарием (блок C Ñ�пецификации). +- Цвет задаётÑ�Ñ� при импорте/Ñ�оздании. При первом открытии раздела (файла библиотеки ещё нет) Ñ�оздаютÑ�Ñ� два примера: ИÑ�панÑ�каÑ� партиÑ� (белые) и Ð�айдорф (чёрные); удалённые примеры не возвращаютÑ�Ñ�. +- Ð�еверный ход на только что показанном новом ходе ошибкой не Ñ�читаетÑ�Ñ�: «Ð�е тот ход» ~0,4 Ñ�, затем Ñ�нова показ. + +## ВыпуÑ�к 2.4.0 (2026-11-27) + +Владелец поручил Ñ�лить ветку `feature/opening-trainer-v2` в `main`, отправить в Forgejo и GitHub, +Ñ�обрать Ñ�борки и обновить Ñ�айт по обычному процеÑ�Ñ�у. ПоÑ�ле 2.3.0 Ñ�то 2.4.0, тег v2.4.0. +Таблица репертуаров по замечаниÑ�м владельца: «СегоднÑ�» — фраза («повторить N», «новые: N», «завтра»), +«Пройдено A/Y» Ñ� полоÑ�ой «пройдено/закреплено»; Ñ�лова «учитÑ�Ñ�/выучено» заменены на «пройдено/закреплено». + +## Стартовые репертуары и теÑ�товые окна (2026-11-27) + +- Владелец: примеры дебютов должны поÑ�влÑ�тьÑ�Ñ� и у обновившихÑ�Ñ�. Выбран вариант «выдавать недоÑ�тающие один раз»: ключ каждого примера запоминаетÑ�Ñ� в `repertoire-starters.json`, удалённые не возвращаютÑ�Ñ�. ЗаменÑ�ет правило 2.4.0 «только при первом открытии раздела». Пользователь 2.4.0, удаливший пример до обновлениÑ�, получит его один раз — подтверждено владельцем 2026-11-27. +- Ð�абор: ИÑ�панÑ�каÑ� партиÑ� и Ферзевый гамбит за белых, Ð�айдорф и Треугольник (полуÑ�лавÑ�нÑ�каÑ�) за чёрных. +- ВизуальнаÑ� приёмка Ñ�того раздела — на Full HD 1920×1080 (владелец). +- ТеÑ�товые окна приложениÑ� — только на невидимом мониторе Hyprland через `scripts/dev/headless-run.sh`, не на мониторах владельца (владелец выбрал вариант 2). +- Комментарии примеров — на руÑ�Ñ�ком длÑ� руÑ�Ñ�кого интерфейÑ�а и на английÑ�ком длÑ� оÑ�тальных (владелец, 2026-11-27). Следующий выпуÑ�к — 2.4.1; не выпуÑ�кать, пока владелец не добавит задачи из бÑ�клога (42, 43 и др.) и не Ñ�командует выпуÑ�к. +- Задача 42, пакетнаÑ� копиÑ� в новую базу (владелец, 2026-11-27): дублем Ñ�читаетÑ�Ñ� только запиÑ�ÑŒ Ñ� тем же текÑ�том PGN (пробелы и переноÑ�Ñ‹ не в Ñ�чёт); верÑ�иÑ� партии Ñ� другими комментариÑ�ми копируетÑ�Ñ�; номера пропущенных — в итоге. Минимум: только desktop и только новаÑ� база; новаÑ� база вÑ�таёт в конец полки, вперёд — только по «Открыть». + +## ВыпуÑ�к 2.5.0 (2026-11-27) + +Владелец поручил коммит, push в Forgejo и GitHub, тег v2.5 и новую Ñ�борку, обновить Ñ�айт. Ранее названный номер 2.4.1 заменён: в выпуÑ�ке новые функции (задачи 27, 42, 43), поÑ�тому минорное увеличение — 2.5.0, тег v2.5.0. Ð’ выпуÑ�к входÑ�Ñ‚ задачи 26, 27, 42, 43, 44, 45. + +## Пакетный анализ вручную выделенных партий (2026-11-27) + +Владелец раÑ�ширил задачу 27 поÑ�ле выпуÑ�ка 2.5.0: маÑ�Ñ�ив длÑ� общего анализа можно получить не только фильтром, но и Ñ�ущеÑ�твующим ручным выделением партий из задачи 42. Это отменÑ�ет прежнее Ñ�оглаÑ�ованное ограничение «кнопка только по фильтру, без пункта длÑ� выделенных»; оÑ�тальные правила задачи 27 Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�. + +- **Приоритет иÑ�точника.** ЕÑ�ли выделена хотÑ� бы одна партиÑ�, Ñ�ущеÑ�твующаÑ� кнопка анализирует выделение; еÑ�ли выделениÑ� нет — отфильтрованный маÑ�Ñ�ив, как раньше. Отдельную вторую кнопку не добавлÑ�ем. +- **Скрытые фильтром.** Ð’ анализ входÑ�Ñ‚ вÑ�е выделенные партии, включаÑ� Ñ�крытые текущим фильтром: выделение по-прежнему переживает Ñ�мену фильтра. Перед запуÑ�ком Ñ�вно показываетÑ�Ñ� чиÑ�ло выбранных партий и, еÑ�ли они еÑ�ть, чиÑ�ло Ñ�крытых текущим фильтром. +- **Лимит.** ДлÑ� выделениÑ� дейÑ�твует тот же предел: 1–100 партий включительно. При большем чиÑ�ле кнопка неактивна и подÑ�казка проÑ�ит выбрать не больше 100; очиÑ�тка выделениÑ� возвращает прежнее поведение по фильтру. +- **Без нового механизма.** Диалог, предупреждение о времени, кÑ�ш, проход Stockfish, прогреÑ�Ñ�, оÑ�тановка/продолжение, итоговое окно и отметки `!!` иÑ�пользуютÑ�Ñ� общие. Создание новой базы из выбранных и иÑ�ходные PGN не менÑ�ÑŽÑ‚Ñ�Ñ�. + +## ВыпуÑ�к 2.5.1 (2026-11-28) + +Владелец Ñ�вно выбрал увеличение поÑ�леднего чиÑ�ла поÑ�ле 2.5.0: верÑ�иÑ� **2.5.1**, тег `v2.5.1`. Ð’ выпуÑ�к входит задача 46. Поручены отправка в Forgejo и GitHub и публикациÑ� Ñ�борок. + +## Android: проÑ�таÑ� подготовка к Ñ�опернику (2026-11-28) + +Владелец поручил мобильный Ñ�ценарий задачи 48: выбрать Ñ�оперника из базы или открытой партии и его цвет, показать доÑ�ку цветом пользователÑ� вниз (противоположным цвету Ñ�оперника), продолжениÑ� Ñ�трелками и Ñ�пиÑ�ком по чаÑ�тоте, чиÑ�ло партий и победы/ничьи/поражениÑ� выбранного игрока. Ход разрешён и на доÑ�ке, и каÑ�анием продолжениÑ�. Это разрешает **проÑ�тую** подготовку на Android и не переноÑ�ит наÑ�тольный отчёт целиком; прежнее «на Android не делаем» задачи 19 оÑ�таётÑ�Ñ� в Ñ�иле длÑ� его Ñ�ложных разделов. + +ТехничеÑ�кие границы реализации, выбранные оркеÑ�тратором в рамках Ñ�того проÑ�того Ñ�ценариÑ�: точный вариант имени без Ñ�клейки, одна выбраннаÑ� Ñ�торона, транÑ�позиции, только первое вхождение позиции в оÑ�новную линию каждой партии, RAV не Ñ�читаютÑ�Ñ� Ñ�ыгранными ходами, неизвеÑ�тный `Result` отдельно от поражений. Ð�икаких оценок движка, поиÑ�ка ошибок, SRS и изменениÑ� иÑ�ходных баз. + +## Android: ориентациÑ� доÑ�ки подготовки — Ñ�тороной пользователÑ� (2026-11-29) + +Владелец уточнил: подготовка Ñ�троитÑ�Ñ� от его Ñ�тороны против выбранного Ñ�оперника. ПоÑ�тому Ñ�оперник белыми означает чёрные внизу (`flipped = true`), Ñ�оперник чёрными — белые внизу (`flipped = false`). ПрежнÑ�Ñ� реализациÑ� Ñ� цветом Ñ�оперника вниз была неверной интерпретацией и иÑ�правлена. Ручной переворот доÑ�ки оÑ�таётÑ�Ñ� доÑ�тупным; обе Ñ�тартовые ориентации и ручной flip проверены на Ñ�мулÑ�торе и принÑ�ты незавиÑ�имым ревью (`docs/qa/android-prep-orientation.md`). + +## Android: Ñ�пиÑ�ок игроков Ñ� плоÑ�кими Ñ�троками (2026-11-29) + +Владелец выбрал улучшенный Ñ�кран Players по варианту B+: плоÑ�кие Ñ�троки 72 dp вмеÑ�то двух плашек White/Black у каждого игрока. ЕÑ�ли ненулевой цвет один, каÑ�ание Ñ�троки Ñ�разу открывает подготовку Ñ�тим цветом; еÑ�ли доÑ�тупны оба, открываетÑ�Ñ� короткий лиÑ�Ñ‚ Ñ� двумÑ� дейÑ�твиÑ�ми по 64 dp и без дополнительного подтверждениÑ�. Ð�улевой цвет оÑ�таётÑ�Ñ� видимым текÑ�том, но не отдельной disabled-кнопкой. ПоиÑ�к, точные имена, Ñ�чётчики и возврат в подготовку Ñ�охранÑ�ÑŽÑ‚Ñ�Ñ�. Проект — `docs/design/android-players-improvement.md`. По ремарке владельца 2026-11-29 лиÑ�Ñ‚ озаглавлен «ПодготовитьÑ�Ñ� к %1$s» (без двоеточиÑ�), дейÑ�твиÑ� названы «Против белых» и «Против чёрных», чтобы цвет не читалÑ�Ñ� как цвет Ñ�амого пользователÑ� (`docs/qa/android-color-sheet-wording.md`). + +## ВыпуÑ�к 2.5.2 (2026-11-30) + +Владелец Ñ�вно выбрал увеличение поÑ�леднего чиÑ�ла поÑ�ле 2.5.1: верÑ�иÑ� **2.5.2**, тег `v2.5.2`. Ð’ выпуÑ�к входÑ�Ñ‚ задачи 29 и 48: кнопка анализа и навигациÑ� на Ñ�кране Android-партии, проÑ�таÑ� подготовка к Ñ�опернику. Поручены commit и push в Forgejo и GitHub, Android-Ñ�борка длÑ� Ñ�айта, обновление Ñ�айта и RuStore. diff --git a/docs/design/android-lists.md b/docs/design/android-lists.md new file mode 100644 index 0000000..512bf86 --- /dev/null +++ b/docs/design/android-lists.md @@ -0,0 +1,260 @@ +# ChessPenguin длÑ� Android: Ñ�пиÑ�ки нарÑ�дней + +СтатуÑ�: утверждено владельцем 2026-10-26 (Ñ�пиÑ�ок партий — направление Ð�, «Базы» — Б, наÑ�тройки и лиÑ�Ñ‚ «Добавить базу» в том же Ñ�тиле), реализовано в тот же день; что Ñ�делано и что отложено — §10. ДополнÑ�ет `android-ui.md` (§3.2 Ñ�пиÑ�ок баз, §6.2 Ñ�трока партии, §9 наÑ�тройки, §10 внешний вид) и `android-play.md` (§30.2 «Базы», §31.7 отложеннаÑ� партиÑ�). ПоÑ�ле утверждениÑ� разделы `android-ui.md` правÑ�Ñ‚Ñ�Ñ� Ñ�Ñ�ылкой Ñ�юда. + +Макет длÑ� владельца: `index.html` (кадры 360×800, «Ñ�ейчаÑ�» и направлениÑ�, тёмнаÑ� и Ñ�ветлаÑ� темы). Генератор макета хранитÑ�Ñ� в рабочей папке Ñ�еÑ�Ñ�ии, в репозиторий не входит. + +ЗапроÑ� владельца: «Ñ�кран партии можно не трогать… а вот где Ñ�пиÑ�ки как-то уныло. СпиÑ�ок партий бы разделителÑ�ми разделить… Ñ� одной Ñ�тороны очень хорошо что проÑ�то, но визуально чуть бы разнообразнее. По пользовательÑ�ким путÑ�м в целом ок. Оформление Ñ�кудное». + +Значит: пути, кнопки, порÑ�док Ñ�кранов и текÑ�ты не менÑ�ем. МенÑ�ем только то, как нариÑ�ованы Ñ�троки и группы. Экран «ПартиÑ�» не трогаем. + +## 1. Что Ñ�ейчаÑ� не так + +Снимки 1080×2400, тёмнаÑ� тема: «Базы» и «Партии» (база «КлаÑ�Ñ�ичеÑ�кие партии»). + +**СпиÑ�ок партий.** + +1. Строки ничем не отделены друг от друга. Между партиÑ�ми только чуть больший интервал. Три Ñ�троки текÑ�та одного цвета, и глаз не видит, где кончаетÑ�Ñ� партиÑ�. +2. Результат — голые цифры `1` и `0` у правого краÑ�, полужирноÑ�ть почти не заметна. Кто выиграл, приходитÑ�Ñ� вычитывать. +3. Белые и чёрные различаютÑ�Ñ� только порÑ�дком Ñ�трок. Плашки у доÑ�ки (§7.11) различают их Ñ�вно, а Ñ�пиÑ�ок нет. +4. «Турнир · год · ECO» — одна Ñ�ераÑ� Ñ�трока. ECO терÑ�етÑ�Ñ� в конце, хотÑ� Ñ�то Ñ�амаÑ� короткаÑ� и Ñ�амаÑ� «шахматнаÑ�» метка. +5. Ð�ет никакого акцента. Ð�ет Ñ�леда партии, из которой человек только что вернулÑ�Ñ�. + +**Экран «Базы».** + +1. Ð’Ñ�е плашки одного цвета (`primaryContainer`). PGN, ChessBase, архив, Ñ�качаннаÑ� Ñ� Lichess база и Ñ�воÑ� база выглÑ�дÑ�Ñ‚ одинаково; разница только в двух-трёх буквах. +2. ЧиÑ�ло партий набрано так же, как формат («267 партий · PGN»). Большую базу не отличить от маленькой Ñ� первого взглÑ�да. +3. Группы «Мои базы» и «Файлы» — только Ñ�иний заголовок над плоÑ�ким Ñ�пиÑ�ком. +4. Карточка отложенной партии — Ñ�трока текÑ�та на Ñ�инем фоне. О Ñ�амой партии в ней ничего не видно. +5. Кнопки «Играть Ñ� Maia» и «Ð�оваÑ� партиÑ�» шириной по текÑ�ту. Справа оÑ�таётÑ�Ñ� пуÑ�тое меÑ�то, Ñ€Ñ�д выглÑ�дит недоделанным. + +**Другие Ñ�пиÑ�ки.** Ð’ наÑ�тройках, на Ñ�кране «Партии Ñ� Lichess и Chess.com» и в лиÑ�те «Добавить базу» те же плоÑ�кие Ñ�троки без значков, без групп и без цвета. + +**Правило, которое мешает.** `android-ui.md` §10.4: «Разделителей нет нигде». Это правило пиÑ�алоÑ�ÑŒ ради чиÑ�тоты, но на трёхÑ�трочных Ñ�троках оно и даёт «колонку текÑ�та». ПредлагаетÑ�Ñ� его заменить (§5). + +## 2. СпиÑ�ок партий: три направлениÑ� + +Во вÑ�ех трёх текÑ�ты, порÑ�док, нажатие, долгое нажатие и TalkBack те же. ОтличаютÑ�Ñ� только оформление и плотноÑ�ть. + +| | Ð�. Строки Ñ� разделителÑ�ми (рекомендую) | Б. Карточки | Ð’. Одна Ñ�трока «белые – чёрные» | +|---|---|---|---| +| Что Ñ�то | ТекущаÑ� трёхÑ�трочнаÑ� Ñ�трока. Добавлены тонкий разделитель, кружки цвета Ñ�торон, плашка у результата победителÑ� и ECO в рамке | КаждаÑ� партиÑ� — карточка `surfaceContainerLow` Ñ�о Ñ�круглением 12 dp. Ð�омер и турнир наверху, имена под ними | Белые и чёрные на одной Ñ�троке, между ними плашка «1–0». Под ними турнир | +| Ð’Ñ‹Ñ�ота | 80 dp, как Ñ�ейчаÑ� | ≈ 94 dp вмеÑ�те Ñ� промежутком 8 | 64 dp | +| Строк на 360×800 | 8,5 (как Ñ�ейчаÑ�) | 7,3 | 10,7 | +| ПлюÑ�Ñ‹ | ПлотноÑ�ть прежнÑ�Ñ�. ПобедителÑ� видно Ñ� первого взглÑ�да. Тот же Ñ�зык, что у плашек у доÑ�ки | Ð�арÑ�дней вÑ�ех. КаждаÑ� партиÑ� — отдельный предмет | Плотнее вÑ�ех, похоже на таблицу на компьютере | +| МинуÑ�Ñ‹ | Строки вÑ�Ñ‘ ещё текÑ�товые. Это и хорошо: не шумно | Ð’ базе на 5 000 и 870 тыÑ�. партий — Ñ�тена плиток. ТерÑ�етÑ�Ñ� 15 % плотноÑ�ти, при прокрутке Ñ€Ñ�бит | Имена приходитÑ�Ñ� Ñ�окращать («Zukertort J. H.»), чёрные обрезаютÑ�Ñ�. От Ñ�того ушли 2026-10-24 (§6.2) | + +Миниатюра позиции в Ñ�троке (поÑ�леднÑ�Ñ� позициÑ� или позициÑ� поÑ�ле дебюта) раÑ�Ñ�матривалаÑ�ÑŒ и отложена. Ð’ `GameRow` нет ни FEN, ни ходов, поÑ�тому длÑ� каждой Ñ�троки пришлоÑ�ÑŒ бы разбирать партию. Ð’ базе на миллион запиÑ�ей Ñ�то противоречит «тÑ�жёлое не блокирует». К тому же 48 dp доÑ�ки на Ñ�троку Ñ�ъедают имена. ВернутьÑ�Ñ� к ней можно длÑ� Ñ�крана «Партии игрока» или длÑ� Ñ�воих баз, где партий деÑ�Ñ�тки. + +**РекомендациÑ� — Ð�.** Владелец проÑ�ит «разделителÑ�ми разделить» и «чуть разнообразнее», но «хорошо что проÑ�то». Ð� делает ровно Ñ�то: Ñ�троки разделены, у каждой партии поÑ�влÑ�ÑŽÑ‚Ñ�Ñ� три цветовых акцента (кружки Ñ�торон, плашка победителÑ�, метка ECO), а плотноÑ�ть и вÑ�е пути оÑ�таютÑ�Ñ� прежними. + +## 3. СпецификациÑ� Ð�: Ñ�трока партии + +Схема на 360 dp (чиÑ�ла — dp): + +``` +16 │ â„– │12│â—�│8│ имÑ� белых ……………………………… Эло │8│[1]│16 24 bodyLarge + │ │ │○│ │ имÑ� чёрных ………………………………… Эло │ │ 0 │ 24 bodyLarge + │ │ │ Paris Opera · 1858 ………………… ✓ │8│C41│ 20 bodyMedium + └──────── разделитель 1 dp от кружков до 16 dp от правого краÑ� ───┘ + отÑ�тупы Ñ�верху и Ñ�низу по 6 → 80 +``` + +### 3.1. ГеометриÑ� + +- Ð’Ñ‹Ñ�ота и Ñ�етка — как в §6.2: 6 + 24 + 24 + 20 + 6 = 80 dp, при крупном шрифте Ñ�троки раÑ�тут так же, как Ñ�ейчаÑ� (`lineHeight`). Колонка номера — прежнÑ�Ñ� (ширина по Ñ�амому большому номеру, `bodySmall`, `tnum`, `onSurfaceVariant`, по линии белых), поÑ�ле неё 12 dp. +- **Кружок Ñ�тороны** — новый Ñ�толбец перед именем: круг 8 dp, поÑ�ле него 8 dp до имени. Стоит по центру Ñ�воей Ñ�троки 24 dp. ИмÑ� Ñ�тановитÑ�Ñ� на 16 dp уже. Правило Ñ�окращениÑ� `PlayerName` (полное → «ФамилиÑ� И. О.» → многоточие) не менÑ�етÑ�Ñ�. Ð�а 360 dp у имени около 230 dp, «Zukertort, Johannes Hermann» помещаетÑ�Ñ� целиком. +- Строка подробноÑ�тей начинаетÑ�Ñ� под именем, а не под кружком: отÑ�туп 16 dp Ñ�лева. +- **Колонка результата** — 24 dp, перед ней 8 dp, как Ñ�ейчаÑ�. + +### 3.2. Кружки Ñ�торон + +| | СветлаÑ� | ТёмнаÑ� | +|---|---|---| +| белые: заливка | `#FFFFFF` | `#FFFFFF` | +| чёрные: заливка | `#1C1D1F` | `#0E0F10` | +| кольцо 1 dp у обоих | `onSurfaceVariant` `#5D636B` | `onSurfaceVariant` `#A3A7AD` | + +Цвета добавить в `ChessColors` (`sideWhite`, `sideBlack`), кольцо — роль темы. Сделано пока прежним `SideDisc` (`#F5F5F0` / `#26282B`, кольцо `outline`), Ñ�м. §10. Кружки декоративные, TalkBack их не читает: Ñ�тороны и так названы Ñ�ловами («Белые: …»). Когда у Ñ�тюда нет чёрных (две Ñ�троки названиÑ�, §6.2), кружков нет вовÑ�е: Ñ�то не игроки. + +### 3.3. Результат + +Плашка 24×20 dp, Ñ�кругление 6 dp, текÑ�Ñ‚ 14sp `tnum` по центру. Стоит на линии Ñ�воей Ñ�троки. + +| Результат в PGN | Строка белых | Строка чёрных | ИмÑ� победителÑ� | +|---|---|---|---| +| `1-0` | плашка `1`: фон `primaryContainer`, текÑ�Ñ‚ `onPrimaryContainer`, 700 | `0` без плашки, `onSurfaceVariant`, 400 | у белых 500 | +| `0-1` | `0` без плашки | плашка `1` | у чёрных 500 | +| `1/2-1/2` | плашка `½`: фон `surfaceContainerHigh`, текÑ�Ñ‚ `onSurface`, 400 | такаÑ� же плашка `½` | оба 400 | +| `*` и прочее | пуÑ�то, колонка 24 dp оÑ�таётÑ�Ñ� | пуÑ�то | оба 400 | + +- Выигрыш намеренно не зелёный, а проигрыш не краÑ�ный. Выигрыш белых — Ñ�то проигрыш чёрных, у Ñ�пиÑ�ка нет «Ñ�воей» Ñ�тороны. Ð�кцент — цвет приложениÑ�. +- СмыÑ�л не передаётÑ�Ñ� одним цветом: цифра оÑ�таётÑ�Ñ� (§12.3). +- КонтраÑ�Ñ‚: `onPrimaryContainer` на `primaryContainer` — 5,4:1 в Ñ�ветлой и 8,0:1 в тёмной; `onSurface` на `surfaceContainerHigh` — выше 10:1. +- ИмÑ� победителÑ� 500 и имÑ� проигравшего 400 — в одной Ñ�троке разница заметна, но не кричит. ЕÑ�ли при 500 имÑ� переÑ�таёт помещатьÑ�Ñ�, работает то же правило Ñ�окращениÑ�: ширину мерÑ�ем уже Ñ� наÑ�ыщенноÑ�тью. + +### 3.4. Строка подробноÑ�тей + +- «Турнир · год» — как Ñ�ейчаÑ� (`bodyMedium`, `onSurfaceVariant`, многоточие). +- **ECO — отдельнаÑ� метка Ñ�права** (решение владельца: метка нужна, и поиÑ�к находит партию по ECO; найденнаÑ� метка заливаетÑ�Ñ� `primaryContainer` / `onPrimaryContainer`, как Ñ�овпадение в текÑ�те), выровненнаÑ� по правому краю колонки результата. ТекÑ�Ñ‚ `labelSmall` (12sp/16, 500, `tnum`) цветом `onSurfaceVariant`. Рамка 1 dp `outline`, Ñ�кругление 4 dp, полÑ� 4 dp, ширина не меньше 32 dp, выÑ�ота 16 dp. Метка не обрезаетÑ�Ñ�: обрезаетÑ�Ñ� турнир. Ð�ет ECO — нет метки. +- **«✓ проÑ�мотрена»** (§6.2, когда будет Ñ�делано) — значок `check` 16 dp цветом `primary` между турниром и меткой ECO, Ñ� отÑ�тупом 8 dp. + +### 3.5. Разделитель + +- 1 dp цветом `outlineVariant` (`#E1E3E6` / `#2E3033`) по низу Ñ�троки, внутри её 80 dp: выÑ�ота Ñ�троки не менÑ�етÑ�Ñ�, бегунок и прыжки не дёргаютÑ�Ñ� (§6.6). +- Слева начинаетÑ�Ñ� от Ñ�толбца кружков (16 + ширина номера + 12), Ñ�права кончаетÑ�Ñ� за 16 dp до краÑ�. Ð�омер оÑ�таётÑ�Ñ� на «поле», как номера Ñ�траниц. +- У поÑ�ледней Ñ�троки Ñ�пиÑ�ка разделителÑ� нет. У Ñ�троки-заглушки (§6.6) он еÑ�ть: заглушки той же формы. +- РеализациÑ�: `drawBehind` в Ñ�троке или `HorizontalDivider` внутри `Box` Ñ� `align(BottomStart)`. Ð�е отдельный Ñ�лемент `LazyColumn`, иначе ломаетÑ�Ñ� Ñ�чёт меÑ�Ñ‚. + +### 3.6. ПартиÑ�, открытаÑ� поÑ�ледней + +ПоÑ�ле возврата Ñ� Ñ�крана «ПартиÑ�» Ñ�трока Ñ�той партии отмечена, пока человек не откроет другую или не уйдёт Ñ� Ñ�крана: + +- фон Ñ�троки `surfaceContainer` (`#EEF0F2` / `#232427`); +- у левого краÑ� полоÑ�а 3 dp цветом `primary` Ñ�о Ñ�круглёнными правыми углами (2 dp); +- Ñ�пиÑ�ок прокручен так, чтобы Ñ�трока была видна. ЕÑ�ли она уже на Ñ�кране, прокрутки нет. + +Это то же меÑ�то в текущем порÑ�дке, что «12 из 340» (§7.6): еÑ�ли в партии лиÑ�тали ‹ ›, отмечена та, на которой оÑ�тановилиÑ�ÑŒ. TalkBack добавлÑ�ет в конец опиÑ�аниÑ�: «Открыта поÑ�ледней» / “Last openedâ€�. + +### 3.7. ПодÑ�ветка поиÑ�ка + +- Совпадение запроÑ�а в имени белых, имени чёрных и турнире: фон `primaryContainer`, текÑ�Ñ‚ `onPrimaryContainer` (`SpanStyle(background = …, color = …)`; в Compose фон без Ñ�круглениÑ�, Ñ�то допуÑ�тимо). Без учёта региÑ�тра, первое вхождение в каждом поле. +- ЕÑ�ли показано Ñ�окращённое имÑ�, подÑ�вечиваетÑ�Ñ� Ñ�овпадение в нём. ЕÑ�ли Ñ�овпадение попало в Ñ�окращённую чаÑ�ть («Johannes» → «J.»), подÑ�ветки нет; Ñ�трока вÑ�Ñ‘ равно найдена. +- Заголовок — как Ñ�ейчаÑ�: «Ð�айдено 2 из 38». + +### 3.8. СоÑ�тоÑ�ниÑ� + +- Ð�ажатие — Ñ�тандартнаÑ� Ñ€Ñ�бь M3 поверх фона, включаÑ� отмеченную Ñ�троку. +- Заглушка, пока Ñ�трока читаетÑ�Ñ�: Ñ�ерые полоÑ�Ñ‹ `surfaceContainerHigh` на меÑ�те имён и турнира, кружки и плашки той же формы и того же цвета, разделитель еÑ�ть. +- БольшаÑ� база (от 20 000): Ñ�трока та же. Чипы фильтров над Ñ�пиÑ�ком (§6.5) — без изменений. + +### 3.9. TalkBack + +ТекÑ�Ñ‚ Ñ�троки тот же, что в §12.3: «№ 12. Белые: КарлÑ�ен, МагнуÑ�, Эло 2830. Чёрные: Каруана, Фабиано, Эло 2795. 1-0, победили белые. Ð�орвегиÑ�, 2025, C42. ПроÑ�мотрена». ДобавлÑ�етÑ�Ñ� только «Открыта поÑ�ледней» (§3.6). Кружки, плашки и рамка ECO Ñ�мыÑ�ла не добавлÑ�ÑŽÑ‚ и не озвучиваютÑ�Ñ�. + +## 4. Экран «Базы»: три направлениÑ� + +| | Ð�. Цветные плашки, плоÑ�кий Ñ�пиÑ�ок | Б. Группы-карточки (рекомендую) | Ð’. Плитки в две колонки | +|---|---|---|---| +| Что Ñ�то | Строки как Ñ�ейчаÑ�, у плашек цвет по виду базы, тонкие разделители, чиÑ�ло партий выделено | То же, плюÑ� каждаÑ� группа — набор карточек Ñ� зазором 2 dp, как в наÑ�тройках Android 16 (M3 Expressive). Карточка отложенной партии Ñ� маленькой доÑ�кой. Кнопки поровну | Квадратные плитки 2×N: плашка, имÑ� в две Ñ�троки, чиÑ�ло партий | +| Строк на Ñ�кран | 8–9 | 8 (72 + 2 dp) | 4 Ñ€Ñ�да по 2 | +| ПлюÑ�Ñ‹ | Минимум работы | Группы читаютÑ�Ñ� как предметы, Ñ�кран «Ñ�обран». Тот же Ñ�зык, что в наÑ�тройках Ñ�иÑ�темы | ВыглÑ�дит как «полка» | +| МинуÑ�Ñ‹ | ОÑ�таётÑ�Ñ� плоÑ�ким | ИмÑ� базы уже на 12 dp | Меню â‹® не помещаетÑ�Ñ�, только долгое нажатие. При 20 базах — длиннаÑ� лента. Имена режутÑ�Ñ� по-другому, чем везде | + +**РекомендациÑ� — Б.** Цвет говорит о виде базы, группы Ñ�тановÑ�Ñ‚Ñ�Ñ� видимыми, а отложеннаÑ� партиÑ� показывает Ñ�ебÑ�, а не только подпиÑ�ÑŒ. Путей и кнопок не прибавилоÑ�ÑŒ. + +## 5. СпецификациÑ� Б: Ñ�кран «Базы» + +### 5.1. Плашки видов + +Плашка — 40×40 dp, Ñ�кругление 10 dp (было 8). ТекÑ�Ñ‚ `labelSmall` (12sp, 500) или значок 22 dp. Цвет выбираетÑ�Ñ� по виду, а не по раÑ�ширению. + +**Решение владельца (2026-10-26): цвета видов — из палитры Catppuccin**: в тёмной теме Mocha, в Ñ�ветлой Latte. ТекÑ�Ñ‚ или значок — цвет палитры, фон — подкраÑ�ка того же оттенка, подобраннаÑ� так, чтобы контраÑ�Ñ‚ был не ниже 5:1. Код: `theme/Color.kt`, `kindColor(kind, dark)`, виды — `DbKind`. + +| Вид | Содержимое | Оттенок Catppuccin | СветлаÑ� (Latte): фон / текÑ�Ñ‚ | ТёмнаÑ� (Mocha): фон / текÑ�Ñ‚ | +|---|---|---|---|---| +| PGN: файл, папка, копиÑ�, пример | `PGN` | blue | `#DFEAFE` / `#1957D0` | `#343E4D` / `#89B4FA` | +| ChessBase | `CB` | peach | `#FFE9DD` / `#A54107` | `#4B3D36` / `#FAB387` | +| архив 7z, ZIP | `7Z`, `ZIP` | mauve | `#EEE3FD` / `#7A33D7` | `#413B4D` / `#CBA6F7` | +| Ñ�качаннаÑ� Ñ� Lichess или Chess.com | значок `cloud_download` | teal | `#DFF0F1` / `#116D73` | `#364746` / `#94E2D5` | +| Ñ�воÑ� база | значок `edit_note` | green | `#E4F2E1` / `#2D701E` | `#3A473B` / `#A6E3A1` | +| база игрока (партии Ñ� Maia) | `♞` | green, как Ñ�воÑ� | как Ñ�воÑ� | как Ñ�воÑ� | +| ошибка | `!` | — | `errorContainer` / `error` | так же | + +- Тона ровно пÑ�ть. ЕÑ�ли видов Ñ�танет больше, новые получают blue (PGN), а не шеÑ�той цвет. +- ТекÑ�ты Latte в Ñ�ветлой теме затемнены отноÑ�ительно иÑ�ходной палитры: чиÑ�тые Latte-тона на Ñ�ветлой подкраÑ�ке дают меньше 4,5:1. +- Те же цвета у круглых плашек лиÑ�та «Добавить базу» и у плашек выбора файла. +- СмыÑ�л не только в цвете: на плашке еÑ�ть текÑ�Ñ‚ или значок, во второй Ñ�троке формат Ñ�ловами. +- ЕÑ�ли поÑ�вÑ�Ñ‚Ñ�Ñ� «Цвета обоев» (`android-ui.md` §10.3; в коде пока нет), цвета видов не менÑ�ÑŽÑ‚Ñ�Ñ�, включаÑ� PGN: Ñ�то метки, как NAG. +- Онлайн-база больше не показывает `PGN`: её отличие — откуда она, а не формат. + +### 5.2. Строка базы + +- 72 dp, как Ñ�ейчаÑ�. Плашка, 12 dp, имÑ� `bodyLarge` в одну Ñ�троку Ñ� многоточием, â‹® 48 dp. +- **ВтораÑ� Ñ�трока:** чиÑ�ло партий — `onSurface`, 500, `tnum`; оÑ�тальное — `onSurfaceVariant`, 400: «**267** партий · PGN», «**5 340** партий · PGN», «**1 204** партии · обновлено 2 ч назад». ТекÑ�Ñ‚ тот же, что Ñ�ейчаÑ�, выделено только чиÑ�ло. СоÑ�тоÑ�ниÑ� «ещё не открывалаÑ�ь», «читаю…», ошибки, полоÑ�а Ñ�качиваниÑ� 2 dp по низу — без изменений. + +### 5.3. Группы + +- Заголовок группы — как Ñ�ейчаÑ�: 48 dp, `titleSmall` (14sp, 500), `primary`, Ñ�лева 16 dp; у «Мои базы» Ñ�права «+ Ð�оваÑ� база». +- **Строки группы — отдельные карточки** `surfaceContainerLow` (`#F5F6F7` / `#1F2022`): + - полÑ� Ñ�крана 12 dp Ñ�лева и Ñ�права, внутри карточки 12 dp до плашки; + - между карточками зазор 2 dp цветом фона: он и еÑ�ть разделитель; + - Ñ�круглениÑ�: у первой карточки верхние углы 16 dp и нижние 4 dp, у поÑ�ледней наоборот, у Ñ�редних вÑ�е 4 dp, у единÑ�твенной вÑ�е 16 dp; + - Ñ€Ñ�бь нажатиÑ� обрезаетÑ�Ñ� по форме карточки. +- ИмÑ� базы при Ñ�том на 12 dp уже, чем Ñ�ейчаÑ� (≈ 224 dp вмеÑ�то 236 на 360 dp). Это цена карточек. +- ПуÑ�таÑ� группа «Мои базы» — Ñ�трока-подÑ�казка (§30.2) без карточки, как Ñ�ейчаÑ�. +- ПорÑ�док групп и Ñ�трок, правило «группа „Файлы“ без заголовка, еÑ�ли Ñ�воих баз не было» — без изменений. +- Ð�нимации поÑ�влениÑ� и удалениÑ� Ñ�трок (`animateItem`) оÑ�таютÑ�Ñ�. При удалении Ñ�редней Ñ�троки Ñ�оÑ�еди менÑ�ÑŽÑ‚ форму углов (перваÑ� или поÑ�леднÑ�Ñ�). Форму Ñ�читать по меÑ�ту в группе при риÑ�овании, а не хранить. + +### 5.4. ОтложеннаÑ� партиÑ� + +``` +┌────────────────────────────────────────â”� 16 dp Ñ�кругление, primaryContainer +│ ┌──────â”� ПартиÑ� Ñ� Maia 1550 ✕ │ bodyLarge 500, onPrimaryContainer +│ │доÑ�ка │ вы белыми · 6-й ход │ bodyMedium +│ │72 dp │ [ Продолжить ] │ Button 32 dp, primary / onPrimary +│ └──────┘ │ +└────────────────────────────────────────┘ полÑ� 12, выÑ�ота ≈ 96 +``` + +- **ДоÑ�ка 72 dp** — текущаÑ� позициÑ� отложенной партии. Те же доÑ�ка и фигуры, что выбраны в наÑ�тройках, Ñ�торона игрока внизу, без координат, Ñ�трелок и поÑ�леднего хода, Ñ�кругление 6 dp. РиÑ�уетÑ�Ñ� уже Ñ�ущеÑ�твующим `Board` в режиме «только показать», без нажатий, один раз при поÑ�влении карточки. PGN уже лежит в `filesDir/play/current.pgn`. +- ТекÑ�Ñ‚: перваÑ� Ñ�трока «ПартиÑ� Ñ� Maia {Ñ�ила}», втораÑ� «вы белыми · {n}-й ход». Ход — тот, что Ñ�ейчаÑ� на доÑ�ке. ЕÑ�ли ход неизвеÑ�тен, только «вы белыми». Строки — Ñ�ущеÑ�твующие `play_adjourned` / `play_adjourned_sub`, текÑ�Ñ‚ разбит на две. +- «Продолжить» — заполненнаÑ� кнопка (`primary`), а не текÑ�товаÑ�: Ñ�то главное дейÑ�твие на Ñ�кране, пока партиÑ� отложена. × — `IconButton` 48 dp в правом верхнем углу, поведение прежнее («ПартиÑ� удалена · Вернуть»). +- Ð’Ñ�Ñ� карточка нажимаетÑ�Ñ� как «Продолжить». TalkBack: «ОтложеннаÑ� партиÑ� Ñ� Maia 1550, вы белыми, 6-й ход. Продолжить, кнопка». + +### 5.5. РÑ�д дейÑ�твий + +- Две кнопки поровну, на вÑ�ÑŽ ширину: `Modifier.weight(1f)`, между ними 12 dp, полÑ� 16 dp. +- `FilledTonalButton` выÑ�отой 56 dp, Ñ�кругление 16 dp (как у FAB и карточек, а не таблетка). Значки и текÑ�ты прежние. Ð�а 360 dp у кнопки 158 dp, «Играть Ñ� Maia» Ñ�о значком помещаетÑ�Ñ� (Ñ�ейчаÑ� кнопка 148 dp). + +### 5.6. Что оÑ�таётÑ�Ñ� + +ВерхнÑ�Ñ� панель «ChessPenguin ⚙», FAB «Добавить базу» (Ñ�жимаетÑ�Ñ� при прокрутке), меню â‹® и долгое нажатие, Ñ�некбары «Вернуть», карточка обновлениÑ� (§25.8) первой в Ñ�пиÑ�ке, нижний отÑ�туп Ñ�пиÑ�ка 88 dp. + +## 6. Другие Ñ�пиÑ�ки — тот же Ñ�зык + +- **Ð�аÑ�тройки (§9).** Группы — те же карточки, что в §5.3: полÑ� 12, зазор 2, углы 16/4. Заголовки групп прежние (`labelLarge`, `primary`). У каждого пункта Ñ�лева значок Material Symbols 24 dp цветом `onSurfaceVariant`, поÑ�ле него 16 dp. Пункт по-прежнему не ниже 56 dp, длинные названиÑ� переноÑ�Ñ�Ñ‚Ñ�Ñ�. Значки: «ЗапиÑ�ÑŒ ходов» `notes`, «Ð�нимациÑ� фигур» `animation`, «Стрелка лучшего хода» `arrow_right_alt`, «Звук» `volume_up`, «ВибрациÑ�» `vibration`, «ЗапиÑ�ывать партии…» `save`, «ДоÑ�ка и фигуры» `grid_on`, «Тема» `palette`, «Язык» `translate`, движок `memory`, линии `format_list_numbered`, времÑ� `timer`, потоки `developer_board`, памÑ�ть `sd_card`, «О программе» `info`. Переключатели и Ñ�троки Ñ�оÑ�тоÑ�ниÑ� не менÑ�ÑŽÑ‚Ñ�Ñ�. +- **ЛиÑ�Ñ‚ «Добавить базу» (§4.1).** Значок пункта — в круглой плашке 40 dp цвета той базы, котораÑ� получитÑ�Ñ�: «ВÑ�тавить PGN», «Файл», «Папка» — Ñ�инÑ�Ñ� PGN, «Партии Ñ� Lichess и Chess.com» — бирюзоваÑ� онлайн-база. ТекÑ�ты и порÑ�док прежние. +- **«Партии Ñ� Lichess и Chess.com» (§23).** Ð�айденные аккаунты и карточки Ñ�качиваниÑ� — карточками §5.3 (одна группа на Ñ�кран), плашка у Ñ�троки аккаунта — бирюзоваÑ� Ñ� `cloud_download`. ПолÑ� ника и переключатель «вмеÑ�те» не менÑ�ÑŽÑ‚Ñ�Ñ�. При реализации Ñ�веритьÑ�Ñ� Ñ� `OnlineScreen.kt` (`FoundRow`, `DownloadCard`). +- **Сортировка, фильтры, меню, диалоги** — без изменений. + +## 7. Что менÑ�етÑ�Ñ� в правилах `android-ui.md` + +- §10.4 «Разделителей нет нигде…» заменить на: «Разделители — только в длинных Ñ�пиÑ�ках: 1 dp `outlineVariant` между Ñ�троками партий (§6.2, `android-lists.md` §3.5) и линиÑ� между нотацией и нижней панелью. Короткие Ñ�пиÑ�ки (базы, наÑ�тройки) группируютÑ�Ñ� карточками Ñ� зазором 2 dp». +- §10.4 Ñ�круглениÑ�: добавить «карточки групп — 16 dp Ñ�наружи и 4 dp внутри; плашки видов баз — 10 dp; плашка результата — 6 dp; метка ECO — 4 dp». +- §10.3: добавить таблицу цветов видов баз (§5.1) и цвета кружков Ñ�торон (§3.2). +- §10.6 «Плашка формата базы»: цвет по виду (§5.1). +- §3.2, §6.2, §30.2, §31.7 — Ñ�Ñ�ылки на разделы Ñ�того документа. + +## 8. Что не менÑ�етÑ�Ñ� + +Экран «ПартиÑ�» и вÑ�Ñ‘, что на нём. Цепочка Базы → Партии → ПартиÑ�. Ð�абор кнопок и пунктов меню. Ð’Ñ�е текÑ�ты, кроме разбивки карточки отложенной партии на две Ñ�троки и «Открыта поÑ�ледней» в TalkBack. Шрифт, Ñ�етка 4 dp, полÑ� 16 dp у Ñ�пиÑ�ка партий. Ð’Ñ‹Ñ�ота Ñ�троки партии 80 dp и плотноÑ�ть 8,5 Ñ�троки на Ñ�кран. + +## 9. Проверить при реализации + +- Обе темы, шрифт 100 % и 200 %. При 200 % Ñ�трока партии раÑ�тёт, плашка результата оÑ�таётÑ�Ñ� на линии Ñ�воей Ñ�троки, метка ECO не налезает на турнир. +- КонтраÑ�Ñ‚ по таблицам §3.3 и §5.1 — на уÑ�тройÑ�тве, а не только раÑ�чётом. +- БольшаÑ� база (870 тыÑ�.): прокрутка бегунком без рывков. Разделитель не добавлÑ�ет выÑ�оты, у заглушек он тоже еÑ�ть. +- Возврат из «Партии» поÑ�ле ‹ › отмечает ту партию, на которой оÑ�тановилиÑ�ÑŒ. +- Удаление Ñ�редней, первой и единÑ�твенной базы в группе: углы Ñ�оÑ�едей переÑ�читываютÑ�Ñ�, анимациÑ� не дёргаетÑ�Ñ�. +- TalkBack: Ñ�трока партии читаетÑ�Ñ� как раньше плюÑ� «Открыта поÑ�ледней»; карточка отложенной партии — одним узлом. +- «Цвета обоев» (когда поÑ�вÑ�Ñ‚Ñ�Ñ�): цвета видов баз оÑ�таютÑ�Ñ� Ñ�воими. + +## 10. Что Ñ�делано и что отложено (2026-10-26) + +Сделано (`ui/GamesScreen.kt` — `GameRowView`, `ListPlayer`, `EcoTag`; `ui/Common.kt` — `KindBadge`, `groupCard`, `ResultTile`, `highlighted`; `ui/DatabasesScreen.kt`; `ui/SettingsScreen.kt`; `ui/AddDatabase.kt`; `theme/Color.kt`): + +- Строка партии Ð�: кружки Ñ�торон 8 dp, плашка результата 24×20, имÑ� победителÑ� 500, метка ECO 16 dp Ñ� рамкой `outline`, разделитель 1 dp от кружков, у поÑ�ледней Ñ�троки нет. +- Отметка партии, открытой поÑ�ледней (фон `surfaceContainer`, полоÑ�а 3 dp `primary`, TalkBack «Открыта поÑ�ледней»); при возврате Ñ�пиÑ�ок прокручиваетÑ�Ñ� к ней. +- ПодÑ�ветка поиÑ�ка в именах и турнире; поиÑ�к по ECO, найденнаÑ� метка ECO залита. +- «Базы» Б: плашки по видам в цветах Catppuccin (§5.1), карточки групп 12/2/16/4, чиÑ�ло партий 500 `onSurface`, отложеннаÑ� партиÑ� Ñ� доÑ�кой 72 dp и кнопкой «Продолжить», две кнопки поровну 56 dp. +- Ð�аÑ�тройки — карточки групп и значки 24 dp; лиÑ�Ñ‚ «Добавить базу» — круглые плашки 40 dp цвета будущей базы. + +Отложено или Ñ�делано иначе: + +- «✓ проÑ�мотрена» (§3.4) — не Ñ�делано, как и раньше. +- Заглушка Ñ�троки (§3.8) — пуÑ�таÑ� Ñ�трока Ñ� разделителем, без Ñ�ерых полоÑ�. +- Экран «Партии Ñ� Lichess и Chess.com» (§6) — в Ñ�таром виде. +- Кружки Ñ�торон — прежние цвета `SideDisc`, а не `sideWhite`/`sideBlack` из §3.2. +- Прокрутка к отмеченной партии проиÑ�ходит вÑ�егда (Ñ�трока Ñ�тавитÑ�Ñ� третьей Ñ�верху), а не только когда её не видно. +- СветлаÑ� тема и шрифт 200 % на уÑ�тройÑ�тве ещё не проверены (§9). diff --git a/docs/design/android-opponent-prep.md b/docs/design/android-opponent-prep.md new file mode 100644 index 0000000..e617f17 --- /dev/null +++ b/docs/design/android-opponent-prep.md @@ -0,0 +1,332 @@ +# Задача 48. Android: проÑ�таÑ� подготовка к Ñ�опернику по базе + +Дизайнер, 2026-11-28, ветка `feature/android-opponent-prep`. Документ опиÑ�ывает **MVP длÑ� Android**, а не переноÑ� наÑ�тольного отчёта. Код не изменÑ�лÑ�Ñ�. + +## 1. Задача и границы + +**Задача Ñ�крана — за один взглÑ�д понÑ�ть, как выбранный человек играет из текущей позиции: доÑ�ка и ход важнее вÑ�его, затем чаÑ�тые продолжениÑ�, чиÑ�ло партий и результаты именно Ñ�того человека.** + +Ð’ MVP еÑ�ть два входа в один Ñ�кран иÑ�Ñ�ледованиÑ�: + +1. **Из открытой партии** — Ñ�оперник и позициÑ� уже извеÑ�тны; оÑ�таётÑ�Ñ� выбрать, чей репертуар Ñ�мотреть: белых или чёрных. +2. **Из базы** — через Ñ�кран игроков, где видны общее чиÑ�ло партий и отдельные входы «белыми» / «чёрными» Ñ� чиÑ�лом партий. + +Ð�а Ñ�кране иÑ�Ñ�ледованиÑ�: + +- доÑ�ка изначально повёрнута **цветом пользователÑ� вниз — противоположным цвету Ñ�оперника**; +- ход можно Ñ�делать на доÑ�ке, каÑ�анием Ñ�трелки чаÑ�того продолжениÑ� или каÑ�анием Ñ�троки продолжениÑ�; +- продолжениÑ� отÑ�ортированы по чиÑ�лу партий; у каждого видны чиÑ�ло, долÑ� и W/D/L выбранного игрока; +- â—€/â–¶, удержание длÑ� перехода к границам и ручной переворот работают как в текущей партии; +- вÑ�Ñ‘ проиÑ�ходит локально и только длÑ� чтениÑ�: партиÑ�, PGN и база не менÑ�ÑŽÑ‚Ñ�Ñ�. + +**Ð�е входит:** Stockfish и оценки, поиÑ�к ошибок, вкладки «Дебюты/Ошибки», ECO и названиÑ� вариантов, фильтры периода/Ñ�илы, Ñ�пиÑ�ок партий узла, Ñ�кÑ�порт доÑ�ье, Ñ�охранённые подготовки, онлайн-explorer, desktop-отчёт и новаÑ� Ñ�иÑ�тема повторений. СвÑ�зь Ñ� задачей 38 — только техничеÑ�каÑ�, через чтение базы и позиции; отдельного позиционного поиÑ�ка и его фильтров здеÑ�ÑŒ нет. + +## 2. Что проверено в реальных материалах + +ПроÑ�мотрены Ñ�ами изображениÑ�: + +- приложенный владельцем монтаж `docs/screenshots/android.jpg`, **1920×1080**: Ñ�пиÑ�ок партий, партиÑ�, лиÑ�Ñ‚ игры и Ñ�пиÑ�ок людей; +- `website/shots/raw/phone/01-home.png`, `02-games.png`, `03-game.png`, `04-engine.png`, каждый **1080×2400**; +- реальный кадр текущей панели поÑ�ле `a005185` — `/tmp/opencode/29-final.png`, **1080×2400**; +- `designExample/reference.png` — доÑ�ка и таблица продолжений ChessBase; +- `designExample/доÑ�ка.png` и `designExample/панель ходов Ñ� ответвлениÑ�ми.png` — ориентациÑ�, координаты и чтение ходов; +- наÑ�тольный `docs/screenshots/prep-openings.jpg` иÑ�пользован только как подтверждение Ñ�мыÑ�ла цвета и Ñ�татиÑ�тики, не как макет длÑ� телефона. + +Снимки телефона отноÑ�Ñ�Ñ‚Ñ�Ñ� к AVD **420 dpi**, то еÑ�ть density **2,625**, а не ×3: 1080×2400 px Ñ�оответÑ�твует примерно **411×914 dp**. ПоÑ�тому проектные размеры ниже даны в dp/sp; отдельно проверÑ�етÑ�Ñ� Ñ�талон **360×800 dp**. + +По Ñ�нимкам и коду текущего `a005185` подтверждено: + +- доÑ�ка в портрете занимает вÑ�ÑŽ ширину, без полей и Ñ�круглениÑ�; плашки игроков — 36 dp; +- Ñ�трока партии — 80 dp, полÑ� Ñ�пиÑ�ка — 16 dp, разделитель — 1 dp `outlineVariant`; +- нижнÑ�Ñ� панель партии — **72 dp**, поверхноÑ�ть `surfaceContainer`; поÑ�ле `a005185` â—€/â–¶ делают один шаг, удержание идёт в начало/конец без автоповтора; +- `Board` уже умеет ориентацию, поÑ�ледний ход, Ñ�трелки, tap-tap и drag через `BoardInput`; Ñ�ами Ñ�трелки Ñ�ейчаÑ� только риÑ�уютÑ�Ñ� и отдельного hit testing не имеют; +- `GamesScreen` имеет поиÑ�к и поÑ�транично читаемый `LazyColumn`; `Navigation.kt` Ñ�охранÑ�ет Ñ�оÑ�тоÑ�ние Ñ�кранов в Ñ�теке; +- в `mobile-api` пока нет Android-Ñ�крана игроков и готового API подготовки: его нужно Ñ�проектировать, а не выдавать наÑ�тольный `prep` за уже доÑ�тупный на телефоне. + +## 3. ПользовательÑ�кие пути и Ñ�охранение контекÑ�та + +### 3.1. Из партии: «Кого изучить — белых или чёрных?» + +Путь: **ПартиÑ� → â‹® → «ПодготовитьÑ�Ñ� к Ñ�опернику…» → Ñ�трока игрока/цвета → иÑ�Ñ�ледование**. + +Меню открывает небольшой `ModalBottomSheet`, а не добавлÑ�ет два почти одинаковых пункта в оÑ�новное меню: + +```text +┌────────────────────────────────────â”� +│ ─── │ +│ Подготовка к Ñ�опернику │ +│ â—‹ Morphy, Paul │ +│ Белые │ 64 dp, вÑ�Ñ� Ñ�трока — кнопка +│ â—� Duke Karl / Count Isouard │ +│ Чёрные │ 64 dp +└────────────────────────────────────┘ +``` + +- ИмÑ� — `bodyLarge`, цвет — `bodyMedium` `onSurfaceVariant`; Ñ�лева Ñ�ущеÑ�твующий `SideDisc` 12 dp. Полное имÑ� доÑ�тупно TalkBack, визуально — по правилу `PlayerName`. +- Одно каÑ�ание Ñ�разу открывает иÑ�Ñ�ледование. ДополнительнаÑ� кнопка «Открыть» не нужна: выбор Ñ�троки уже однозначен. +- ЕÑ�ли имÑ� одной Ñ�тороны пуÑ�то или `?`, показываетÑ�Ñ� только Ñ�трока другой Ñ�тороны. ЕÑ�ли имена Ñ�овпадают, оÑ�таютÑ�Ñ� обе Ñ�троки — репертуары за разные цвета различаютÑ�Ñ�. +- Пункт доÑ�тупен только у партии, открытой из Ñ�ущеÑ�твующей базы. У новой партии нет иÑ�точника Ñ�татиÑ�тики, поÑ�тому пункта нет; у активной игры Ñ� компьютером меню и так отдельное. +- Во времÑ� предпроÑ�мотра PV пункт неактивен; втораÑ� Ñ�трока пункта — «Сначала закройте линию движка». Ð�ельзÑ� молча подменить позицию партии позицией PV. ЕÑ�ли на пути текущего узла еÑ�ть учебный null move `--`, втораÑ� Ñ�трока — «ПоиÑ�к поÑ�ле учебного -- недоÑ�тупен»: поÑ�ле него нельзÑ� чеÑ�тно Ñ�опоÑ�тавить линию Ñ� реально Ñ�ыгранными партиÑ�ми. + +**СтартоваÑ� позициÑ� — текущий реальный узел партии**, включаÑ� вариант и иÑ�ходный FEN, но не PV. Ð’ иÑ�Ñ�ледование передаётÑ�Ñ� путь от начала Ñ�той партии до текущего узла, поÑ�тому â—€ позволÑ�ет пройти назад по уже виденной линии. Сама партиÑ� не продолжаетÑ�Ñ� и не редактируетÑ�Ñ�. + +Возврат Ñ�иÑ�темной «Ð�азад» или â†� воÑ�Ñ�танавливает партию на том же узле, Ñ� прежними нотацией, прокруткой, ориентацией и неÑ�охранёнными правками. Диалога «Ñ�охранить?» у иÑ�Ñ�ледованиÑ� нет — оно ничего не изменило. + +Почему Ñ�тот вход нужен нарÑ�ду Ñ�о Ñ�пиÑ�ком игроков: человек уже нашёл партию Ñ�оперника и конкретную позицию; повторный поиÑ�к имени и переход в начальную позицию потерÑ�ли бы главный контекÑ�Ñ‚. + +### 3.2. Из базы: «Ð�айти человека и Ñ�разу выбрать его цвет» + +Путь: **Партии базы → значок «Игроки» → кнопка цвета в Ñ�троке игрока → иÑ�Ñ�ледование Ñ� начальной позиции**. + +Ð’ `TopAppBar` Ñ�крана «Партии» добавлÑ�етÑ�Ñ� `IconButton` Ñ� `Icons.Rounded.Groups` и опиÑ�анием **«Игроки»**. Значок Ñ�тавитÑ�Ñ� перед поиÑ�ком; поиÑ�к оÑ�таётÑ�Ñ� на привычном меÑ�те. У онлайн-базы поÑ�ле них оÑ�таётÑ�Ñ� Ñ�ущеÑ�твующее Ñ�качивание/обновление. КаждаÑ� цель — 48×48 dp, длинное имÑ� базы уÑ�тупает меÑ�то и обрезаетÑ�Ñ� многоточием. + +Отдельный видимый значок выбран вмеÑ�то пункта меню, которого Ñ�ейчаÑ� у «Партий» нет: Ñ�то второй равноправный вход в задачу, а не Ñ�крытаÑ� команда. Ð�а полку баз новаÑ� кнопка не добавлÑ�етÑ�Ñ� — Ñ�начала нужен иÑ�точник, то еÑ�ть конкретнаÑ� база. + +Стек: + +```text +Базы → Партии → Игроки → Подготовка + └───── ПартиÑ� ────→ Подготовка +``` + +«Ð�азад» из игроков возвращает в ту же выдачу партий Ñ� поиÑ�ком и прокруткой. Возврат из подготовки — в игроков Ñ� прежними запроÑ�ом и прокруткой. СтартоваÑ� позициÑ� из Ñ�того входа — обычнаÑ� начальнаÑ�; никакие поиÑ�к/фильтры Ñ�пиÑ�ка партий не переноÑ�Ñ�Ñ‚Ñ�Ñ� Ñ�крыто в Ñ�татиÑ�тику. + +## 4. Экран «Игроки» + +### 4.1. Задача и компоновка + +**Задача Ñ�крана — выбрать точное напиÑ�ание игрока и цвет одним дейÑ�твием, видÑ� объём данных по каждому цвету.** + +```text +┌────────────────────────────────────â”� +│ â†� Игроки ⌕ │ +│ Alekhine │ +│ Alekhine, Alexander 266 партий│ +│ [â—‹ Белыми · 153] [â—� Чёрными · 113] │ 48 +│────────────────────────────────────│ +│ Anderssen, Adolf 2 партии│ +│ [â—‹ Белыми · 2] [â—� Чёрными · 0] │ +└────────────────────────────────────┘ +``` + +- Заголовок — «Игроки», втораÑ� Ñ�трока — имÑ� текущей базы. Справа поиÑ�к Ñ� Ñ�ущеÑ�твующим поведением `GamesScreen`: поле вмеÑ�то заголовка, клавиатура, ✕, задержка 250 мÑ�. ПодÑ�казка — **«ИмÑ� игрока»**. +- СпиÑ�ок по умолчанию — по алфавиту через `Collator`, без отдельной кнопки Ñ�ортировки. ПоиÑ�к фильтрует по подÑ�троке без учёта региÑ�тра. Это не поиÑ�к похожих имён и не объединение людей. +- Строки — плоÑ�кие, как Ñ�пиÑ�ок партий, **без карточек**. Разделитель 1 dp `outlineVariant` находитÑ�Ñ� внутри Ñ�троки и не добавлÑ�ет выÑ�оту. +- ОбычнаÑ� выÑ�ота Ñ�троки — **88 dp**: 8 Ñ�верху + имÑ�/Ñ�чёт 24 + 4 + кнопки 48 + 4 Ñ�низу. При крупном шрифте иÑ�пользуетÑ�Ñ� `heightIn(min = 88.dp)` и Ñ�трока раÑ�тёт. ЕÑ�ли две подпиÑ�и цвета больше не помещаютÑ�Ñ� Ñ€Ñ�дом, кнопки Ñ�тановÑ�Ñ‚Ñ�Ñ� одна над другой на вÑ�ÑŽ ширину, каждаÑ� оÑ�таётÑ�Ñ� не ниже 48 dp; название цвета не обрезаетÑ�Ñ�. +- ПолÑ� — 16 dp. ИмÑ� — `bodyLarge`, общее чиÑ�ло партий Ñ�права — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`; имÑ� Ñ�окращаетÑ�Ñ� первым. Полное имÑ� и полное чиÑ�ло озвучиваютÑ�Ñ�. +- Между цветовыми кнопками — 8 dp. Ð�а ширине 360 dp каждаÑ� занимает **160 dp**: `(360 − 32 − 8) / 2`. Ð�а 320 dp — 140 dp, на 280 dp — 120 dp. ПодпиÑ�ÑŒ одной Ñ�трокой, Ñ�начала Ñ�окращаетÑ�Ñ� чиÑ�ло по `short_count`, полное оÑ�таётÑ�Ñ� в опиÑ�ании. +- Кнопка — нейтральнаÑ� `surfaceContainerLow`, Ñ�кругление 8 dp, `SideDisc` 12 + 8 + текÑ�Ñ‚ `labelLarge`. Ð�икаких двух Ñ�рких цветовых плашек: круг и Ñ�лова уже различают Ñ�тороны. +- **Ð’Ñ�Ñ� кнопка 48 dp — дейÑ�твие.** Ð�ажатие на имÑ� ничего не открывает, поÑ�тому нет конкурирующего третьего Ñ�ценариÑ�. +- Ð�улевой цвет оÑ�таётÑ�Ñ� видимым, но кнопка неактивна. Это чеÑ�тнаÑ� информациÑ� «партий Ñ�тим цветом нет», а не причина переÑ�тавлÑ�ть кнопки. + +Ключ игрока — точное имÑ� из тега поÑ�ле `trim`, без нечёткого Ñ�лиÑ�ниÑ�. `Alekhine`, `Alekhine, Alexander` и другое напиÑ�ание оÑ�таютÑ�Ñ� разными Ñ�троками. ПуÑ�тые и `?` в Ñ�пиÑ�ок не попадают. Ð�втоматичеÑ�ких догадок, кто из тегов Ñ�влÑ�етÑ�Ñ� учебным названием, MVP не делает. Общее чиÑ�ло — чиÑ�ло различных запиÑ�ей; Ñ�чётчики цветов Ñ�читаютÑ�Ñ� отдельно. ЕÑ�ли имÑ� Ñ�тоит на обеих Ñ�торонах одной партии, общее чиÑ�ло не Ñ�кладывает её дважды, а результат в иÑ�Ñ�ледовании завиÑ�ит от выбранной Ñ�тороны. + +### 4.2. СоÑ�тоÑ�ниÑ� Ñ�пиÑ�ка + +| СоÑ�тоÑ�ние | Поведение | +|---|---| +| Первое чтение | ВерхнÑ�Ñ� панель уже видна; в облаÑ�ти Ñ�пиÑ�ка — индикатор и «Читаю игроков…». Ð�ули вмеÑ�то неизвеÑ�тных Ñ�чётчиков не показываютÑ�Ñ� | +| Подгрузка Ñ�траниц | Заглушки тех же 88 dp, разделители оÑ�таютÑ�Ñ�; Ñ�пиÑ�ок не Ñ�качет | +| ПоиÑ�к | Старый результат другой Ñ�троки запроÑ�а не выдаётÑ�Ñ� за новый; показаны заглушки/индикатор, затем результат | +| Ð�ет именованных игроков | «В Ñ�той базе нет именованных игроков» и кнопка «К партиÑ�м» | +| Ð�ичего не найдено | «Игрок не найден» + «СброÑ�ить поиÑ�к» | +| Ошибка базы/индекÑ�а | «Ð�е удалоÑ�ÑŒ прочитать игроков» + Ñ�ущеÑ�твующее `openProblem`, кнопка «Повторить»; техничеÑ�кий текÑ�Ñ‚ не подменÑ�ет причину | +| БольшаÑ� база | ИндекÑ� и поиÑ�к в фоне, `LazyColumn`, чтение Ñ�траницами; уход отменÑ�ет незавершённый запроÑ� | +| Возврат | ЗапроÑ�, выдача и прокрутка Ñ�охранены; выбранный ранее игрок не подÑ�вечиваетÑ�Ñ� как «текущаÑ� позициÑ�» — Ñ�то другое Ñ�оÑ�тоÑ�ние | + +## 5. Экран иÑ�Ñ�ледованиÑ� + +### 5.1. Портрет 360×800 dp + +Плашки двух игроков из Ñ�крана партии здеÑ�ÑŒ не повторÑ�ÑŽÑ‚Ñ�Ñ�: выбранный человек и цвет уже находÑ�Ñ‚Ñ�Ñ� в заголовке. Это оÑ�вобождает 72 dp под продолжениÑ�, не уменьшаÑ� доÑ�ку. + +```text +┌────────────────────────────────────â”� 24, Ñ�иÑ�темнаÑ� Ñ�трока +│ â†� Alekhine, Alexander │ 64 +│ Чёрными · Alekhine │ выбранный цвет · база +├────────────────────────────────────┤ +│ │ +│ ДОСКÐ� 360 × 360 │ чёрные внизу +│ до 3 Ñ�трелок продолжений │ +│ │ +├────────────────────────────────────┤ +│ Соперник играет · 1.e4 113 партий │ 32 +│ 1…c5 79/113 · 70 % │ 56 +│ +55 =14 −10 · W/D/L 70/18/13 % │ +│────────────────────────────────────│ +│ 1…e5 20/113 · 18 % │ 56 +│ +13 =4 −3 · W/D/L 65/20/15 % │ +│────────────────────────────────────│ +│ 1…Nf6 8/113 · 7 % │ +│ +4 =3 −1 · W/D/L 50/38/13 % │ +│ … прокручиваетÑ�Ñ� только Ñ�пиÑ�ок … │ +├────────────────────────────────────┤ +│ ⇅ â—€ â–¶ │ 72 +└────────────────────────────────────┘ 24, Ñ�иÑ�темнаÑ� навигациÑ� +``` + +ВерхнÑ�Ñ� панель: + +- â†� Ñ� опиÑ�анием «К партии» или «К игрокам» по иÑ�точнику; +- имÑ� игрока — `titleMedium`, одна Ñ�трока, полное имÑ� в TalkBack; +- втораÑ� Ñ�трока — **цвет Ñ�ловом + имÑ� базы**, `bodyMedium` `onSurfaceVariant`; +- новых â‹®, движка, разбора и наÑ�троек в Ñ�той панели нет. + +Строка контекÑ�та 32 dp Ñ�вно называет, чьи продолжениÑ� показаны: + +- на ходе выбранного человека — **«Соперник играет»**; +- на ходе другой Ñ�тороны — **«Его оппоненты играют»**. + +Затем идёт «начало» либо «поÑ�ле {SAN Ñ� номером}», Ñ�права — чиÑ�ло партий текущей позиции M. ЛеваÑ� чаÑ�ть обрезаетÑ�Ñ�, M оÑ�таётÑ�Ñ�. При неизвеÑ�тном Ñ�чётчике Ñ�тоит `…`, не `0`. ДлÑ� TalkBack добавлÑ�етÑ�Ñ� точнаÑ� Ñ�торона «ход белых/чёрных»: по FEN её нельзÑ� выводить из чётноÑ�ти хода. ПодпиÑ�ÑŒ «Его оппоненты играют» не даёт принÑ�ть первый ход белых за выбор Ñ�оперника чёрными. + +### 5.2. Строка продолжениÑ� и Ñ�мыÑ�л чиÑ�ел + +ОбычнаÑ� выÑ�ота — **56 dp**, полÑ� 16 dp, две Ñ�троки: + +1. SAN по наÑ�тройке запиÑ�и ходов, 17 sp, Ñ�лева; Ñ�права **`N/M · P %`** `bodyMedium.merge(Tabular)`, где M — партии текущей позиции, N — партии Ñ� Ñ�тим продолжением. +2. **`+W =D −L · W/D/L wp/dp/lp %`**, `labelSmall.merge(Tabular)`, `onSurfaceVariant`: Ñ�лева иÑ�ходные Ñ�чётчики, Ñ�права их доли в том же порÑ�дке. ЕÑ�ли у продолжениÑ� еÑ�ть партии Ñ� неизвеÑ�тным итогом, перед W/D/L добавлÑ�етÑ�Ñ� `ещё U`. + +Ð’Ñ�Ñ� Ñ�трока — `Role.Button` Ñ� обычным ripple. Разделитель 1 dp входит в её выÑ�оту. Ð�икаких карточек, графиков, рейтинговых цветов и Ñ�ортировки по Ñ�толбцам. + +- ПорÑ�док: **N по убыванию**, при равенÑ�тве — по SAN. Ð’Ñ�е продолжениÑ� оÑ�таютÑ�Ñ� в `LazyColumn`; редкие не Ñ�крываютÑ�Ñ�. +- `P = N / M × 100 %`, а не долÑ� от начального репертуара. СущеÑ�твующий ход Ñ� долей меньше 1 % показываетÑ�Ñ� как `<1 %`, не `0 %`. Одновременные `N/M` не дают принÑ�ть процент на одной партии за уÑ�тойчивую закономерноÑ�ть. +- Ð’ Ñ�татиÑ�тику входÑ�Ñ‚ **только реально Ñ�ыгранные оÑ�новные линии**. RAV в базе не Ñ�читаетÑ�Ñ� ходом Ñ�оперника; позициÑ�, взÑ�таÑ� из RAV открытой партии, при Ñ�том разрешена как отправнаÑ�. +- ТранÑ�позиции объединÑ�ÑŽÑ‚Ñ�Ñ� по позиции. ПартиÑ� учитываетÑ�Ñ� один раз, по **первому вхождению позиции в её оÑ�новную линию**; другой ход поÑ�ле повторного вхождениÑ� не добавлÑ�етÑ�Ñ�. +- ЕÑ�ли Ñ�умма долей меньше 100 %, поÑ�ле продолжений обычными недоÑ�тупными Ñ�троками показываютÑ�Ñ� **«ЗдеÑ�ÑŒ закончилиÑ�ÑŒ: N»** и, при учебном/неподдерживаемом Ñ�ледующем ходе, **«Ð�ет обычного продолжениÑ�: N»**. Должно выполнÑ�тьÑ�Ñ� `ΣN(move) + ended + noNormalContinuation = M`. +- Ð�еизвеÑ�тный результат `*` не Ñ�тановитÑ�Ñ� поражением. Он входит в N, M и чаÑ�тоту, но не в знаменатель W/D/L: `known = W + D + L`, каждаÑ� долÑ� делитÑ�Ñ� на `known`. ЕÑ�ли извеÑ�тных результатов нет, вмеÑ�то вÑ�ех трёх долей — `—`. Доли округлÑ�ÑŽÑ‚Ñ�Ñ� незавиÑ�имо и не подгонÑ�ÑŽÑ‚Ñ�Ñ� до Ñ�уммы ровно 100 %. +- ЕÑ�ли нечитаемые запиÑ�и повлиÑ�ли на выборку, отдельнаÑ� Ñ�лужебнаÑ� Ñ�трока — **«Пропущено нечитаемых: N»**. Ошибка чтениÑ� не маÑ�кируетÑ�Ñ� под ноль Ñ�овпадений. +- При нехватке меÑ�та втораÑ� Ñ�трока переноÑ�итÑ�Ñ�, а выÑ�ота раÑ�тёт через `heightIn(min = 56.dp)`. При крупном шрифте перваÑ� Ñ�трока иÑ�пользует компактное `N/M · P %`. Горизонтальной прокрутки нет. + +**W/D/L вÑ�егда отноÑ�итÑ�Ñ� к выбранному человеку, а не к Ñ�тороне, котораÑ� Ñ�ейчаÑ� ходит.** Ð�а ходе его Ñ�оперников Ñ�пиÑ�ок показывает их продолжениÑ�, но победы/ничьи/поражениÑ� по-прежнему Ñ�читаютÑ�Ñ� длÑ� выбранного человека. Ð�апример, длÑ� выбранных чёрных `0-1` — W, `1-0` — L. Это результат поÑ�ле фактичеÑ�ки Ñ�ыгранного продолжениÑ�, а не вероÑ�тноÑ�ть победы или оценка качеÑ�тва хода. Правило должно быть общим длÑ� API, отображениÑ� и TalkBack. + +### 5.3. ДоÑ�ка и Ñ�трелки + +- Ð�ачальнаÑ� ориентациÑ�: Ñ�оперник белыми — чёрные внизу (`flipped = true`), Ñ�оперник чёрными — белые внизу (`flipped = false`). Она **не завиÑ�ит от того, чей Ñ�ейчаÑ� ход**. Уточнение владельца 2026-11-29 заменÑ�ет прежнюю неверную ориентацию цветом Ñ�оперника вниз. +- ⇅ позволÑ�ет вручную перевернуть доÑ�ку; выбор Ñ�охранÑ�етÑ�Ñ� при навигации по позициÑ�м и повороте телефона, но новый вход Ñ�нова начинает Ñ� выбранного цвета. +- ПоÑ�ле готовых данных риÑ�уютÑ�Ñ� **до трёх Ñ�амых чаÑ�тых различных направлений** из Ñ�пиÑ�ка. Ð�е вÑ�е Ñ�разу: деÑ�Ñ�ток переÑ�екающихÑ�Ñ� Ñ�трелок закрыл бы фигуры и Ñ�делал hit testing Ñ�лучайным; полный выбор оÑ�таётÑ�Ñ� в Ñ�пиÑ�ке. Цвет и геометриÑ� — Ñ�ущеÑ�твующие `BoardArrow`/`EngineArrow`: первый веÑ� 1,0 и alpha 0,63, Ñ�ледующие — 0,85/0,45 и 0,70/0,35. Ð�овых цветовых легенд нет; порÑ�док дополнительно виден в Ñ�пиÑ�ке. +- ЕÑ�ли разные UCI имеют одинаковые from/to (например, превращениÑ�), риÑ�уетÑ�Ñ� одна Ñ�трелка, а не неÑ�колько одинаковых поверх. +- КаÑ�ание Ñ�трелки делает Ñ�оответÑ�твующий ход **один раз**. ОблаÑ�ть — не только тонкий видимый штрих: иÑ�пользуетÑ�Ñ� невидимый коридор вокруг shaft/head и зона не менее 48 dp у наконечника, ограниченнаÑ� доÑ�кой. +- КаÑ�ание наконечника и каÑ�ание Ñ�троки передают **точный UCI продолжениÑ�**, включаÑ� недопревращение. Обычный ручной ввод пешки Ñ�охранÑ�ет текущее правило приложениÑ� — по умолчанию ферзь. +- ЕÑ�ли коридоры/наконечники неÑ�кольких ходов переÑ�екаютÑ�Ñ� в точке каÑ�аниÑ�, нельзÑ� молча выбирать верхнюю Ñ�трелку: открываетÑ�Ñ� короткий лиÑ�Ñ‚ **«Выберите ход»** только Ñ� конфликтующими SAN. ЕÑ�ли from/to Ñ�овпадают, лиÑ�Ñ‚ обÑ�зателен. ПоÑ�ле выбора делаетÑ�Ñ� один ход. +- При уже выбранной фигуре обычный `BoardInput` имеет приоритет над shortcut Ñ�трелки. Drag не Ñ�читаетÑ�Ñ� каÑ�анием Ñ�трелки. РеализациÑ� должна иÑ�пользовать **один раÑ�познаватель жеÑ�тов** длÑ� доÑ�ки и Ñ�трелок, а не два конкурирующих `pointerInput`. +- Стрелки иÑ�чезают Ñ�разу при Ñ�мене позиции, загрузке, ошибке и пуÑ�том результате. СтатиÑ�тика прежней позиции не оÑ�таётÑ�Ñ� ни на доÑ�ке, ни в Ñ�пиÑ�ке. +- Ð�а доÑ�ке также работают Ñ�ущеÑ�твующие tap-tap и drag любого легального хода, даже еÑ�ли его нет в базе. Тогда Ñ�ледующаÑ� позициÑ� может чеÑ�тно показать «0 партий»; Ñ�то не ошибка и не запрет продолжать. + +До реализации нужен небольшой UI-прототип именно hit testing: повёрнутаÑ� доÑ�ка, переÑ�екающиеÑ�Ñ� Ñ�трелки, ширина 280 dp и drag. СущеÑ�твующий `Board` доказывает отриÑ�овку и ввод фигур, но не каÑ�аемоÑ�ть Ñ�трелок. + +### 5.4. ЛиниÑ�, â—€/â–¶ и нижнÑ�Ñ� панель + +Ð�ижнÑ�Ñ� панель оÑ�таётÑ�Ñ� **72 dp** и иÑ�пользует текущий `BarButton` из `a005185`: + +| ⇅ | â—€ | â–¶ | +|---|---|---| +| 72 dp | оÑ�тавшаÑ�Ñ�Ñ� ширина поровну | оÑ�тавшаÑ�Ñ�Ñ� ширина поровну | + +Ð�а 360 dp Ñ�то 72 / 144 / 144, на 320 dp — 72 / 124 / 124, на 280 dp — 72 / 104 / 104. Кнопки не уже 48 dp и занимают вÑ�ÑŽ выÑ�оту панели; значки â—€/â–¶ — 32 dp. + +- Короткое â—€/â–¶ — один полуход по иÑ�Ñ�ледуемой линии. Удержание â—€ — в её начало, â–¶ — в конец, один раз и без предварительного шага/автоповтора. +- ПоÑ�ле â—€ кнопка â–¶ возвращаетÑ�Ñ� **тем же продолжением**, а не Ñ�амым чаÑ�тым. +- Ð�овый ход поÑ�ле возврата назад отбраÑ�ывает только будущий хвоÑ�Ñ‚ временной линии. Это не удаление варианта PGN и не требует подтверждениÑ�. +- Длинное нажатие имеет те же accessibility custom actions «В начало/конец линии». Звук и вибрациÑ� — только поÑ�ле Ñ�овершённого хода и по общим наÑ�тройкам. +- Ð�едоÑ�тупные â—€/â–¶ оÑ�таютÑ�Ñ� на меÑ�те и не менÑ�ÑŽÑ‚ геометрию. + +## 6. Загрузка, пуÑ�то, ошибка и гонки + +ОблаÑ�ть под доÑ�кой имеет поÑ�тоÑ�нную геометрию: доÑ�ка, верхнÑ�Ñ� и нижнÑ�Ñ� панели не двигаютÑ�Ñ� при Ñ�мене данных. МенÑ�етÑ�Ñ� только Ñ�одержимое прокручиваемой облаÑ�ти. + +| СоÑ�тоÑ�ние | Что видно | +|---|---| +| Первый вход | Сразу доÑ�ка правильной ориентации и текущий путь; в облаÑ�ти продолжений — меÑ�то тех же Ñ�трок и индикатор | +| ЗапроÑ� короче 300 мÑ� | Результат поÑ�влÑ�етÑ�Ñ� без промежуточного миганиÑ� | +| ЗапроÑ� дольше 300 мÑ� | «Считаю продолжениÑ�…» в облаÑ�ти Ñ�пиÑ�ка; фикÑ�ированнаÑ� полоÑ�а 2 dp над ним. Прежние SAN, Ñ�трелки и W/D/L уже удалены | +| Ход во времÑ� запроÑ�а | ДоÑ�ка и путь менÑ�ÑŽÑ‚Ñ�Ñ� Ñ�разу; запроÑ� прежней позиции отменÑ�етÑ�Ñ�/игнорируетÑ�Ñ� по поколению, новый начинаетÑ�Ñ� незавиÑ�имо | +| ПозициÑ� не вÑ�тречалаÑ�ÑŒ | «В партиÑ�Ñ… {name} Ñ�той позиции нет» и подÑ�казка «Можно продолжить на доÑ�ке или вернутьÑ�Ñ� ◀»; Ñ�трелок нет | +| Продолжений нет, партии закончилиÑ�ÑŒ | «ВÑ�е партии здеÑ�ÑŒ закончилиÑ�ь»; W/D/L не выдумываетÑ�Ñ� | +| Ошибка текущего запроÑ�а | ДоÑ�ка и путь оÑ�таютÑ�Ñ�; в облаÑ�ти Ñ�пиÑ�ка «Ð�е удалоÑ�ÑŒ поÑ�читать продолжениÑ�» + причина + «Повторить». Повтор отноÑ�итÑ�Ñ� к видимой позиции | +| Ð�е хватает памÑ�ти длÑ� индекÑ�а | Отдельный текÑ�Ñ‚ «Ð�едоÑ�таточно памÑ�ти длÑ� поиÑ�ка по Ñ�той базе», не «позициÑ� не найдена»; доÑ�тупны «Повторить» и возврат | +| База иÑ�чезла/изменилаÑ�ÑŒ | Ð�е показывать кÑ�ш как актуальные данные; та же ошибка Ñ� `openProblem`, возврат по â†� доÑ�тупен | +| Много продолжений | ПрокручиваетÑ�Ñ� только Ñ�пиÑ�ок; доÑ�ка, контекÑ�Ñ‚ и кнопки закреплены | +| Выход из иÑ�Ñ�ледованиÑ� | ВременнаÑ� линиÑ� иÑ�чезает без вопроÑ�а; иÑ�ходный Ñ�кран Ñ�охранÑ�етÑ�Ñ� | +| Поворот/возврат из фона | Игрок, цвет, путь, курÑ�ор, ориентациÑ� и прокрутка Ñ�пиÑ�ка воÑ�Ñ�танавливаютÑ�Ñ�; ответ Ñ�тарого поколениÑ� не применÑ�етÑ�Ñ� | + +ДлÑ� каждого запроÑ�а ключ должен включать базу и её верÑ�ию, точное имÑ�, цвет и текущую позицию/иÑ�торию, необходимую Ñ�дру. Ответ применÑ�етÑ�Ñ� только еÑ�ли ключ вÑ�Ñ‘ ещё видим на Ñ�кране. + +## 7. Ð�льбомнаÑ� ориентациÑ�, узкие Ñ�краны и HiDPI + +- **Портрет:** доÑ�ка `fillMaxWidth().aspectRatio(1f)`, как в партии. Ð�а очень низком Ñ�кране она не уменьшаетÑ�Ñ�; Ñ�пиÑ�ок получает оÑ�таток и прокручиваетÑ�Ñ�. +- **Ð�льбомнаÑ� ориентациÑ�/широкое окно:** верхнÑ�Ñ� панель общаÑ�; Ñ�лева квадратнаÑ� доÑ�ка на вÑ�ÑŽ доÑ�тупную выÑ�оту, Ñ�права — Ñ�трока контекÑ�та, `LazyColumn` Ñ� веÑ�ом 1 и нижнÑ�Ñ� панель 72 dp. СиÑ�темные insets учитываютÑ�Ñ� отдельно, доÑ�ка не переÑ�екаетÑ�Ñ� Ñ� навигацией. +- **Планшетный портрет:** доÑ�ка ограничена 480 dp и центрируетÑ�Ñ�; Ñ�трока контекÑ�та и Ñ�пиÑ�ок имеют ту же ширину, а не раÑ�Ñ‚Ñ�гиваютÑ�Ñ� на веÑ�ÑŒ Ñ�кран. ПуÑ�тые полÑ� не заполнÑ�ÑŽÑ‚Ñ�Ñ� декоративными карточками. +- **280/320 dp:** те же три кнопки внизу, две цветовые кнопки у игрока и двухÑ�трочные продолжениÑ�; ни одна цель не уже 48 dp, горизонтальной прокрутки нет. +- **Крупный шрифт:** Ñ�трока контекÑ�та имеет `heightIn(min = 32.dp)` и может выраÑ�ти, не обрезаÑ� «Соперник играет» / «Его оппоненты играют». Строки продолжений раÑ�тут, `N/M` и чаÑ�тота оÑ�таютÑ�Ñ� в первой Ñ�троке, иÑ�ходные +/=/− и W/D/L переноÑ�Ñ�Ñ‚Ñ�Ñ� на Ñ�ледующие. ЧиÑ�ла не иÑ�чезают и не обрезаютÑ�Ñ�. У игрока кнопки цвета при необходимоÑ�ти Ñ�тановÑ�Ñ‚Ñ�Ñ� вертикальными по §4.1. +- **HiDPI:** иÑ�пользовать Ñ�ущеÑ�твующие векторные Material icons, dp/sp, `Pieces` Ñ� раÑ�тровым кÑ�шем фактичеÑ�кого размера. Ð�овых раÑ�тровых реÑ�урÑ�ов не требуетÑ�Ñ�. ОбÑ�зательнаÑ� проверка — реальный 420 dpi, без вывода «×3» из размеров PNG. + +## 8. ДоÑ�тупноÑ�ть, клавиатура и подÑ�казки + +### 8.1. TalkBack + +- **Игрок:** имÑ� и общее чиÑ�ло — один информационный узел. КаждаÑ� цветоваÑ� кнопка отдельно: «{name}, белыми, 153 партии. ПодготовитьÑ�Ñ�» / «… чёрными, нет партий, неактивно». Круг не озвучиваетÑ�Ñ� отдельно. +- **ДоÑ�ка:** один узел Ñ� позицией и ориентацией: «ДоÑ�ка, позициÑ� поÑ�ле 1.e4. Чёрные выбранного игрока внизу». Ð�е Ñ�оздавать 64 отдельных фокуÑ�а клеток. +- У доÑ�ки еÑ�ть custom actions длÑ� видимых Ñ�трелок: «Сыграть 1…c5, 79 партий, 70 процентов». Полный Ñ�пиÑ�ок продолжений вÑ�егда доÑ�тупен ниже, поÑ�тому Ñ�ценарий не завиÑ�ит от жеÑ�та по Canvas. +- **Продолжение:** одна кнопка: «1…c5. 79 из 113 партий, 70 процентов. Результаты Alekhine, Alexander: 55 побед, 14 ничьих, 10 поражений; 70, 18 и 13 процентов. Сыграть». При неизвеÑ�тных иÑ�ходах добавлÑ�етÑ�Ñ� их чиÑ�ло и поÑ�Ñ�нение, что они не входÑ�Ñ‚ в знаменатель процентов. +- **КонтекÑ�Ñ‚:** «Соперник играет, ход чёрных, поÑ�ле 1.e4, 113 партий» либо «Его оппоненты играют, ход белых…» объÑ�влÑ�етÑ�Ñ� politely поÑ�ле готовноÑ�ти, один раз на позицию. ПрогреÑ�Ñ� не озвучиваетÑ�Ñ� на каждое обновление; ошибка и пуÑ�той результат объÑ�влÑ�ÑŽÑ‚Ñ�Ñ� один раз. +- ПоÑ�ле активации Ñ�троки фокуÑ� не оÑ�таётÑ�Ñ� на удалённом Ñ�лементе: он переводитÑ�Ñ� на Ñ�троку контекÑ�та новой позиции. При быÑ�тром лиÑ�тании не накапливаетÑ�Ñ� очередь объÑ�влений. +- â—€/â–¶ Ñ�охранÑ�ÑŽÑ‚ текущие полные опиÑ�аниÑ� и custom actions границ. Ð�еактивноÑ�ть передаётÑ�Ñ� Ñ�емантичеÑ�ки, не только Ñ�ерым. + +### 8.2. Ð�ппаратнаÑ� клавиатура и D-pad + +| Клавиша | ДейÑ�твие | +|---|---| +| Tab / Shift+Tab, D-pad | Стандартный порÑ�док фокуÑ�а: â†� → доÑ�тупные custom actions доÑ�ки → Ñ�троки продолжений → ⇅ → â—€ → â–¶ | +| Enter / Space / DPAD_CENTER | Ð�ктивировать Ñ�фокуÑ�ированную Ñ�троку или кнопку, один раз | +| Android Back / Esc | Сначала закрыть лиÑ�Ñ‚/меню, затем покинуть текущий Ñ�кран | +| Длительное дейÑ�твие TalkBack | Границы линии через custom actions, как на Ñ�енÑ�орном Ñ�кране | + +Глобальных буквенных Ñ�окращений и перехвата â†�/→ в Ñ�пиÑ�ке нет: они нужны длÑ� перемещениÑ� фокуÑ�а. Произвольный ход по 64 клеткам Ñ� аппаратной клавиатуры в MVP не добавлÑ�етÑ�Ñ�; вÑ�е продолжениÑ� базы и навигациÑ� доÑ�тупны Ñ�пиÑ�ком. Это ограничение не должно маÑ�кироватьÑ�Ñ� под полную клавиатурную поддержку доÑ�ки. + +Видимый фокуÑ� — рамка 2 dp `primary` вокруг кнопки/Ñ�троки, а не только Ñ�мена tint. Hover-tooltip: «Игроки», «Перевернуть доÑ�ку», «Предыдущий ход. Удержание — в начало», «Следующий ход. Удержание — в конец». Ð�а â—€/â–¶ Ñ�енÑ�орное удержание выполнÑ�ет переход, а не показывает tooltip. + +## 9. ТребованиÑ� разработчику + +1. Добавить в Ñ�ущеÑ�твующий Nav3 два Ñ�охранÑ�емых назначениÑ�: «Игроки базы» и «Подготовка». Ð�е делать подготовку новым разделом верхнего уровнÑ�. Ð�е передавать вÑ�Ñ‘ PGN-дерево в `NavKey`; иÑ�пользовать Ñ�табильные идентификаторы и Ñ�охранÑ�емую Ñ�еÑ�Ñ�ию иÑ�Ñ�ледованиÑ�. +2. Ð’ `GamesScreen` вынеÑ�ти `onPlayers`; в `GameScreen` — `onPrepare(player, white)`. ЛиÑ�Ñ‚ выбора цвета оÑ�таётÑ�Ñ� локальным Ñ�оÑ�тоÑ�нием партии. ИÑ�пользовать Ñ�ущеÑ�твующий Ñ�тек, не переÑ�оздавать иÑ�ходный Ñ�кран при возврате. +3. Компоненты: `PlayersScreen`, плоÑ�каÑ� `PlayerPrepRow`, `PrepScreen`, `ContinuationRow`, общий блок `PrepControls`. ПереиÑ�пользовать `Board`, `BoardInput`, `Pieces`, `SideDisc`, `PlayerName`, `groupDigits`, `displaySan`, `openProblem` и текущий `BarButton`; не копировать жеÑ�Ñ‚ long press второй реализацией. +4. Ð�ужен новый локальный API, например модели `PlayerSummary(name,total,whiteGames,blackGames)`, `PrepPosition(games,continuations,endedHere,noNormalContinuation,skipped,unknownResults)`, `PrepContinuation(uci,san,games,wins,draws,losses,unknown)`. Ð�азваниÑ� — ориентир длÑ� разработчика, не утверждение о Ñ�ущеÑ�твующем UniFFI. +5. Счётчики Ñ�троить только по выбранной базе и точному `(name,color)`. Ð�грегациÑ� в Rust — **main line, first occurrence**, Ñ� транÑ�позициÑ�ми и без RAV в Ñ�татиÑ�тике; Ñ�ущеÑ�твующий Ñ�мешанный `MoveStat.tally` длÑ� Ñ�того не подходит. ЧаÑ�тота — от партий текущей позиции; W/D/L — от финального результата выбранного игрока на ходе любой Ñ�тороны. Ð�е запуÑ�кать Stockfish и не читать наÑ�тольный отчёт об ошибках. +6. Чтение игроков и позиций — вне UI-потока, Ñ�о Ñ�траницами, отменой и защитой от поздних ответов. БольшаÑ� база не Ñ�обираетÑ�Ñ� в памÑ�ть целиком ради Ñ�пиÑ�ка. ИÑ�ходные файлы открываютÑ�Ñ� только на чтение; теÑ�Ñ‚ — SHA-256/mtime до и поÑ�ле. +7. Путь иÑ�Ñ�ледованиÑ� отделён от `GameSession` партии. КаÑ�ание Ñ�троки/Ñ�трелки и обычный ввод дают один UCI и один переход. ДлÑ� недопревращений не заменÑ�ть UCI продолжениÑ� ходом по умолчанию. +8. Доработать `Board` одним gesture resolver: координаты hit regions Ñ�трелок вычиÑ�лÑ�ÑŽÑ‚Ñ�Ñ� тем же преобразованием `flipped`, что их отриÑ�овка. Проверить конфликты Ñ� выбором фигуры, drag, краÑ�ми доÑ�ки и Ñ�иÑ�темным «назад». +9. При каждом новом запроÑ�е Ñ�разу очищать Ñ�тарые Ñ�трелки/Ñ�татиÑ�тику. Ð�икакого «пока новое Ñ�читаетÑ�Ñ�, покажем прежнее». +10. Ð’Ñ�е видимые Ñ�троки и опиÑ�аниÑ� — реÑ�урÑ�Ñ‹ на вÑ�ех девÑ�ти уже поддерживаемых Ñ�зыках; чиÑ�ла партий — через plurals. W/D/L можно оÑ�тавить международным Ñ�окращением, но TalkBack обÑ�зан произноÑ�ить локализованные «победы/ничьи/поражениÑ�». +11. Compose-теÑ�ты: две цветовые цели игрока, disabled при нуле, одна активациÑ� продолжениÑ�, конфликт одинаковых from/to, flip-hit mapping, â—€/â–¶ и custom actions, отÑ�утÑ�твие фокуÑ�а на иÑ�чезнувшей Ñ�троке, Ñ�табильные минимальные размеры. +12. Ð�е добавлÑ�ть Ñ�охранение, undo, пункты анализа, Ñ�пиÑ�ок партий или фильтры «на будущее» в Ñ�том MVP. + +## 10. Ð�езавиÑ�имой проверке и теÑ�тировщику + +Визуальную приёмку выполнÑ�ет **отдельный ревьюер, не автор макета и не автор реализации**. Он запуÑ�кает реальное приложение в изолированных наÑ�тройках и прикладывает Ñ�нимки; чтениÑ� Kotlin и Compose preview недоÑ�таточно. + +### 10.1. ОбÑ�зательные Ñ�ценарии и доказательÑ�тва + +1. **Сравнение Ñ�ущеÑ�твующего и нового:** текущие «Партии» и «ПартиÑ�» из той же Ñ�борки, затем «Игроки» и «Подготовка». Сверить фон, `TopAppBar`, полÑ� 16 dp, доÑ�ку, нижние 72 dp, иконки и типографику. Ð�а реальном AVD 1080×2400/420 dpi указать фактичеÑ�кие dp, а не называть его 360×800. +2. **Оба входа:** партиÑ� → лиÑ�Ñ‚ White/Black → текущаÑ� позициÑ�; база → игроки → цвет → начальнаÑ� позициÑ�. Показать белые внизу в одном Ñ�лучае и чёрные внизу в другом. Возврат — к прежнему узлу/прокрутке. +3. **ЗаполненнаÑ� подготовка:** минимум четыре продолжениÑ�, разные N и W/D/L, до трёх Ñ�трелок. Проверить выравнивание SAN, `N/M · %`, второй Ñ�троки +/=/− и W/D/L и отÑ�утÑ�твие карточек. +4. **ПоÑ�ледовательноÑ�ть без Ñ�качков:** загрузка → заполнено → ход Ñ�трелкой → ход Ñ�трокой → â—€ → â–¶ → позициÑ� без партий → ошибка → «Повторить». Ð�а каждом кадре зафикÑ�ировать координаты доÑ�ки, Ñ�троки контекÑ�та и нижней панели. Изменение выÑ�оты допуÑ�тимо только при переноÑ�е текÑ�та/Ñ�мене ориентации по Ñ�вному уÑ�ловию. +5. **ПуÑ�тые Ñ�оÑ�тоÑ�ниÑ�:** нет игроков, поиÑ�к игрока без результата, нулевой цвет, ноль партий в позиции, вÑ�е партии закончилиÑ�ÑŒ. Ð�ули не должны мелькать во времÑ� загрузки. +6. **Узкое и крупное:** 320 и 280 dp, font scale 1,3 и 2,0: обе цветовые кнопки, три нижние кнопки и W/D/L не обрезаны; Ñ�троки раÑ�тут без горизонтальной прокрутки. +7. **Ð�льбомнаÑ� ориентациÑ�:** доÑ�ка Ñ�лева, продолжениÑ� Ñ�права, панель 72 dp; Ñ�иÑ�темные панели ничего не перекрывают. Светлую тему проверÑ�ть отдельно только еÑ�ли добавÑ�Ñ‚Ñ�Ñ� новые цвета — по текущему макету новых ролей нет. +8. **HiDPI:** чёткие SVG-фигуры, Material icons, круги Ñ�торон, Ñ�трелки и текÑ�Ñ‚ на 420 dpi. Снимки подпиÑ�ать файлом, размером px, density, ориентацией и Ñ�оÑ�тоÑ�нием данных. + +Вердикт «ровно» без Ñ�нимков не принимаетÑ�Ñ�. Дефект запиÑ�ывать как: Ñ�кран/Ñ�оÑ�тоÑ�ние, ожидаемаÑ� и фактичеÑ�каÑ� координата или выравнивание, шаги воÑ�произведениÑ�, файл Ñ�нимка. + +### 10.2. ФункциональнаÑ� матрица + +- Точные имена и цвета: одинаковое имÑ� за оба цвета, разные напиÑ�аниÑ�, пуÑ�то/`?`, нулевой цвет, длинное имÑ�. +- Текущий узел и FEN из партии; начальнаÑ� позициÑ� из базы; вариант партии; PV и путь поÑ�ле учебного `--` не иÑ�пользуютÑ�Ñ�. Старт чёрными и `fullmove=0` определÑ�ÑŽÑ‚ Ñ�торону по FEN, не по чётноÑ�ти ply. +- Стрелка, Ñ�трока, tap-tap и drag дают один и тот же ход; рокировка, взÑ�тие, превращение и недопревращение; flip не менÑ�ет UCI. +- ПереÑ�екающиеÑ�Ñ� Ñ�трелки и одинаковые from/to не делают произвольный ход. Двойное каÑ�ание не Ñ�оздаёт два хода. +- â—€/â–¶ по одному полуходу, удержание без предварительного шага и автоповтора; возврат тем же child; новый ход отÑ�екает только временный хвоÑ�Ñ‚. +- ЧаÑ�тота `N/M` от текущего узла, Ñ�ортировка по N, `<1 %`, «закончилиÑ�ÑŒ здеÑ�ь», `noNormalContinuation`, неизвеÑ�тный результат, иÑ�ходные +/=/− и W/D/L выбранного игрока на ходе обеих Ñ�торон. Отдельно проверить белых и чёрных. Контрольный fixture: у Ñ�оперника чёрными `0-1, 0-1, 1-0, *` → `+2 =0 −1 · ещё 1 · W/D/L 67/0/33 %`; зеркальный пример белыми даёт те же доли. +- Две транÑ�позиции дают одинаковую выборку; повтор позиции учитываетÑ�Ñ� один раз; RAV-only запиÑ�ÑŒ не входит, оÑ�новнаÑ� линиÑ� Ñ� RAV добавлÑ�ет только реальный Ñ�ледующий ход. Проверить равенÑ�тво `ΣN + ended + noNormalContinuation = M`. +- Гонка A → B → A: ответ первого A не применÑ�етÑ�Ñ� к поÑ�леднему A без Ñ�овпадениÑ� полного ключа/поколениÑ�; ответ B никогда не поÑ�влÑ�етÑ�Ñ� на A. +- ИÑ�ходнаÑ� партиÑ� Ñ� неÑ�охранёнными правками возвращаетÑ�Ñ� как была; PGN и база не изменилиÑ�ÑŒ. Ð�овых запиÑ�ей в «Мои базы» не поÑ�влÑ�етÑ�Ñ�. +- TalkBack: полные опиÑ�аниÑ�, disabled, custom actions Ñ�трелок и границ, отÑ�утÑ�твие прогреÑ�Ñ�-Ñ�пама, фокуÑ� поÑ�ле иÑ�чезновениÑ� Ñ�троки. Ð�ппаратнаÑ� клавиатура — по §8.2, без заÑ�влениÑ� произвольного хода по клеткам. +- БольшаÑ� база: прокрутка игроков и продолжений, Ñ�мена запроÑ�а во времÑ� чтениÑ�, уход Ñ� Ñ�крана, повтор поÑ�ле ошибки, отÑ�утÑ�твие блокировки UI. diff --git a/docs/design/android-play.md b/docs/design/android-play.md new file mode 100644 index 0000000..06fd94d --- /dev/null +++ b/docs/design/android-play.md @@ -0,0 +1,443 @@ +# ChessPenguin длÑ� Android: ввод ходов, Ñ�вои базы, игра Ñ� Maia, тренировка + +СтатуÑ�: Ñ�пецификациÑ� дизайнера, 2026-10-26, **длÑ� Ñ�оглаÑ�ованиÑ�**. Продолжает `android-ui.md` (нумерациÑ� разделов идёт дальше его §28; Ñ�Ñ�ылки «§7.4» без имени файла — на `android-ui.md`). ОÑ�нова — решение владельца `docs/decisions.md` «Android: ввод ходов, Ñ�вои базы, Maia, тренировка» и иÑ�Ñ�ледование `docs/research/android-port.md`. Ð�аÑ�тольные проекты, которые здеÑ�ÑŒ переложены на телефон: `play-mode.md`, `play-from-position.md`, `opening-trainer.md`, `own-databases.md`, `maia-models.md`; поведение доÑ�ки — `apps/desktop/src/board.rs`. + +Размеры — dp, текÑ�Ñ‚ — sp, Ñ�талон 360×800 dp (§0 `android-ui.md`). Логика (правила, SAN, дерево, правка Ñ� отменой, ход Maia, Ñ�татиÑ�тика тренера) — только в общих крейтах Rust; Kotlin риÑ�ует и передаёт каÑ�аниÑ�. + +**Что менÑ�етÑ�Ñ� в `android-ui.md`:** §0 п. 2 («только показывает») и §7.2 «КаÑ�ание доÑ�ки» заменÑ�ÑŽÑ‚Ñ�Ñ� §29; §12.1 Ñ�трока «доÑ�ка» — §29.7; §15.2 п. 1–2 Ñ�деланы здеÑ�ÑŒ; §15.3 «не делаем игры и тренировок» отменён решением владельца. + +## 29. Ввод ходов на доÑ�ке + +### 29.1. Главное + +1. **Ход — двумÑ� Ñ�поÑ�обами, оба вÑ�егда включены:** «тап-тап» (фигура, затем поле) и перетаÑ�кивание. Как на Lichess и на компьютере (`board.rs`). +2. **Ход никогда не Ñ�тирает Ñ�ущеÑ�твующий.** Ð’ конце линии — продолжает её; еÑ�ли такой ход уже еÑ�ть — проÑ�то переходит к нему; иначе — новый вариант. Как на компьютере. +3. **Файлы пользователÑ� не менÑ�ÑŽÑ‚Ñ�Ñ�.** Ходы в партии из чужого файла — разбор в памÑ�ти; Ñ�охранить можно только копию в Ñ�вою базу (§30). +4. Комментарии, значки и Ñ�трелки пальцем не вводÑ�Ñ‚Ñ�Ñ� (решение владельца, §6 иÑ�Ñ�ледованиÑ�). + +### 29.2. Тап-тап + +| КаÑ�ание | Результат | +|---|---| +| Ñ�воÑ� фигура (Ñ�тороны, чей ход) | выделена: клетка заливкой `selected` (тот же цвет, что выделение на компьютере, 0,5 прозрачноÑ�ти); на законных полÑ�Ñ… — точки | +| законное поле при выделенной фигуре | ход (анимациÑ� §10.8) | +| другаÑ� Ñ�воÑ� фигура | выделение переходит на неё | +| та же фигура, пуÑ�тое незаконное поле, фигура Ñ�оперника вне взÑ�тиÑ� | выделение Ñ�нимаетÑ�Ñ�, без звука и вибрации | +| фигура Ñ�тороны, которой не ход | ничего (выделениÑ� нет) | + +- **Точка законного хода** — круг диаметром 14 dp (≈ 0,3 клетки), цвет `#000000` 0,25 (на тёмной доÑ�ке тот же: так на Lichess). **ВзÑ�тие** — кольцо по краю клетки толщиной 4 dp того же цвета. Законные полÑ� даёт Ñ�дро (`GameSession.targets(from)`). +- ПоÑ�ледний ход подÑ�вечен, как Ñ�ейчаÑ� (§7.2); выделение риÑ�уетÑ�Ñ� поверх. + +### 29.3. ПеретаÑ�кивание + +- Ð�ачинаетÑ�Ñ�, когда палец на Ñ�воей фигуре Ñ�двинулÑ�Ñ� больше `touchSlop` (≈ 8 dp); до Ñ�того каÑ�ание Ñ�читаетÑ�Ñ� тапом. ОтпуÑ�кание без Ñ�двига = тап (§29.2). +- Фигура под пальцем **увеличена в 1,5 раза и поднÑ�та на полклетки** (22 dp) над точкой каÑ�аниÑ� — иначе её не видно под пальцем. ИÑ�ходнаÑ� клетка — заливка `selected`, фигура на ней полупрозрачнаÑ� 0,3. +- Клетка под пальцем — круг диаметром 2 клетки (90 dp), `#000000` 0,12, по центру клетки: видно, куда вÑ�танет фигура, даже под пальцем. +- Отпущена на законном поле — ход без анимации (фигура уже там). Ð�а незаконном или за доÑ�кой — фигура возвращаетÑ�Ñ� на меÑ�то за 150 мÑ� (без анимации — Ñ�разу), короткаÑ� вибрациÑ� `REJECT` (еÑ�ли вибрациÑ� включена), без звука. Выделение оÑ�таётÑ�Ñ� — можно доделать ход тапом. +- **СиÑ�темный «назад» у краÑ�.** ДоÑ�ка во вÑ�ÑŽ ширину, поÑ�тому перетаÑ�кивание от вертикали a или h Ñ�порит Ñ� жеÑ�том «назад». Ð�а доÑ�ке включаетÑ�Ñ� иÑ�ключение жеÑ�тов (`Modifier.systemGestureExclusion`) длÑ� полоÑ�Ñ‹ 200 dp по выÑ�оте (предел Android на край) по центру доÑ�ки — вертикали a и h в Ñ€Ñ�дах 3–6. Тап-тап у краÑ� работает вÑ�егда. Проверить на уÑ�тройÑ�тве Ñ� жеÑ�товой навигацией. +- Ð�отациÑ� под доÑ�кой прокручиваетÑ�Ñ� как раньше: доÑ�ка не внутри прокрутки, жеÑ�ты не Ñ�порÑ�Ñ‚. ЛиÑ�Ñ‚, меню и предпроÑ�мотр линии движка доÑ�ку перекрывают — пока они открыты, доÑ�ка каÑ�аний не принимает. + +### 29.4. Превращение + +**Решение владельца (2026-10-26): пешка вÑ�егда превращаетÑ�Ñ� в ферзÑ�, без выбора фигуры** («не нужно мудрить в Ñ�том меÑ�те»). Столбика выбора и наÑ�тройки «Сразу ферзь» нет. Ð’ тренировке, еÑ�ли в линии превращение не в ферзÑ�, ход заÑ�читываетÑ�Ñ� по полÑ�м «откуда–куда» (фигура берётÑ�Ñ� из линии). + +### 29.5. Куда вÑ�таёт ход + +- **Ð’ конце текущей линии** — продолжает её. +- **Такой ход уже еÑ�ть** (главный или вариант) — переход к нему, дерево не менÑ�етÑ�Ñ�. +- **Иначе** — новый вариант поÑ�ле текущего хода; в нотации он поÑ�влÑ�етÑ�Ñ� блоком варианта (§7.3), курÑ�ор на нём, Ñ�трока «Дальше» (§7.5) на развилке показывает и его. Замены «перезапиÑ�ать продолжение» нет — ни молча, ни вопроÑ�ом. +- Движок, еÑ�ли включён, Ñ�разу Ñ�читает новую позицию (правило §8.3 «новаÑ� позициÑ� — пуÑ�таÑ� Ñ�трока»). +- КаÑ�ание доÑ�ки во времÑ� предпроÑ�мотра линии движка (§8.3) Ñ�начала закрывает предпроÑ�мотр; ход Ñ�тим каÑ�анием не делаетÑ�Ñ�. +- **«+ Вариантом»** — в полоÑ�е предпроÑ�мотра линии движка Ñ�права от ✕ кнопка `TextButton` «+ Вариантом»: вÑ�тавлÑ�ет линию до показанного хода вариантом (`GameSession.add_line`), Ñ�некбар «Вариант добавлен · Вернуть». Решение «вÑ�тавка — отдельное дейÑ�твие Ñ� отменой» (`decisions.md`). +- ПодÑ�казка §7.2 «Это проÑ�мотр партии…» удалÑ�етÑ�Ñ�: каÑ�ание доÑ�ки теперь делает ход. + +### 29.6. Отмена, меню хода + +- **Отмена (Ctrl+Z компьютера)** — пункт «Отменить» в меню â‹® (первым, виден только когда еÑ�ть что отменÑ�ть; втораÑ� Ñ�трока — что именно: «ход 14.Кd5», «удаление варианта»). ОтменÑ�ет любую правку партии: ход, вариант, удаление, «Ñ�делать оÑ�новным», данные партии. Повтора (Ctrl+Y) нет: на телефоне путь назад — повторить ход на доÑ�ке. Каждое удаление и переÑ�тановка дополнительно дают Ñ�некбар 4 Ñ� Ñ� «Вернуть» — Ñ�то та же отмена. +- **Долгое нажатие на ход в нотации** (та же зона, что каÑ�ание, §7.3; вибрациÑ� `LONG_PRESS`) — переход к ходу и лиÑ�Ñ‚ «Ход 14…Ке7»: + +``` +┌────────────────────────────────────â”� +│ ─── │ +│ 14…Ке7 │ 22sp +│ [⤒] Сделать оÑ�новным │ 56 только в варианте +│ [✕] Удалить ход и продолжение │ 56 +│ ────────────────────────────────── │ +│ [♞] Играть отÑ�юда Ñ� Maia… │ 56 §31.6 +│ [â—Ž] Учить дебют до Ñ�того хода │ 56 Ñ�права: «прохождений: 4» +└────────────────────────────────────┘ +``` + +- «Удалить ход и продолжение» — без диалога, Ñ�некбар «Ходы удалены · Вернуть». КурÑ�ор — на ход перед удалённым. +- «Учить дебют…» неактивен, еÑ�ли на пути еÑ�ть `--` (втораÑ� Ñ�трока — `train_null`); «Играть отÑ�юда» неактивен в оконченной позиции (втораÑ� Ñ�трока «ЗдеÑ�ÑŒ партиÑ� окончена: мат»), как на компьютере. +- Ð’ режиме игры и тренировки долгое нажатие ничего не делает. +- Ð�ачальнаÑ� позициÑ� партии хода не имеет: «Играть Ñ� Ñ�той позиции…» еÑ�ть ещё в меню â‹® (длÑ� текущей позиции). + +### 29.7. ЖеÑ�ты — дополнение к §12.1 + +| Где | ЖеÑ�Ñ‚ | ДейÑ�твие | +|---|---|---| +| доÑ�ка | каÑ�ание Ñ�воей фигуры, затем полÑ�; перетаÑ�кивание | ход (§29.2–29.3) | +| ход в нотации | долгое нажатие | лиÑ�Ñ‚ хода (§29.6) | +| Ñ�трока партии Ñ�воей базы | долгое нажатие | меню: «Данные партии», «Удалить партию» (§30.5) | + +## 30. Свои базы + +### 30.1. Принцип + +- СвоÑ� база — PGN в папке приложениÑ� (`filesDir/own/{id}.pgn`); путь еÑ�ть, поÑ�тому работает общаÑ� запиÑ�ÑŒ `chess-core::pgn::store` (допиÑ�ать, заменить, удалить запиÑ�ÑŒ) как на компьютере. ИмÑ� базы — в Ñ�пиÑ�ке, имÑ� файла внутреннее. +- ПишетÑ�Ñ� только Ñ�воÑ� база и только по Ñ�вному дейÑ�твию («Сохранить»). Открытые файлы, папки, копии из других приложений и онлайн-базы не менÑ�ÑŽÑ‚Ñ�Ñ� никогда; из них Ñ�охранÑ�етÑ�Ñ� копиÑ� партии в Ñ�вою базу. + +### 30.2. Экран «Базы» + +``` +┌────────────────────────────────────â”� +│ ChessPenguin âš™ │ 64 +├────────────────────────────────────┤ +│ [ ♞ Играть Ñ� Maia ][ + Ð�оваÑ� партиÑ�]│ 48+16, две FilledTonalButton по 160 +│ Мои базы + Ð�оваÑ� база │ 48 заголовок группы и TextButton +│ [✎] Игры Ñ� Maia â‹® │ 72 +│ 14 партий · на телефоне │ +│ [✎] Партии Миши â‹® │ 72 +│ 3 партии · на телефоне │ +│ Файлы │ 48 заголовок группы +│ [PGN] КлаÑ�Ñ�ичеÑ�кие партии â‹® │ как §3.2 +│ ┌───────────────â”� │ +│ │+ Добавить базу│ │ FAB как Ñ�ейчаÑ� +└────────────────────────────────────┘ +``` + +- **РÑ�д дейÑ�твий** вверху Ñ�пиÑ�ка прокручиваетÑ�Ñ� вмеÑ�те Ñ� ним. «Играть Ñ� Maia» — §31.1; «Ð�оваÑ� партиÑ�» — пуÑ�таÑ� доÑ�ка (§30.4). Две кнопки, а не второй FAB: FAB один, и Ñ�то «Добавить базу». +- **Группа «Мои базы»** — вÑ�егда первой. Плашка 40 dp `primaryContainer` Ñ�о значком `edit_note`. ВтораÑ� Ñ�трока: «{n} партий · на телефоне». ПуÑ�таÑ� группа — одна Ñ�трока 14sp `onSurfaceVariant` «ЗдеÑ�ÑŒ будут партии, которые вы введёте или Ñ�ыграете Ñ� Maia» под заголовком. +- **Группа «Файлы»** — вÑ�е прежние базы (файлы, папки, копии, онлайн-базы), как §3.2. Заголовки групп `titleSmall`, `primary`, отÑ�туп 16 dp; группа «Файлы» без заголовка, еÑ�ли Ñ�воих баз нет и не было (первый запуÑ�к выглÑ�дит как раньше, но Ñ� Ñ€Ñ�дом дейÑ�твий). +- Карточка отложенной партии (§31.7) — над Ñ€Ñ�дом дейÑ�твий. + +### 30.3. Создать, переименовать, удалить, выгрузить + +- **«+ Ð�оваÑ� база»** — диалог «Ð�оваÑ� база»: поле «Ð�азвание» (по умолчанию «Мои партии», при Ñ�овпадении — «Мои партии 2»), подпиÑ�ÑŒ «ХранитÑ�Ñ� на телефоне, в ChessPenguin. Выгрузить файл можно в меню базы.» Кнопки «Отмена» / «Создать». ПуÑ�тое имÑ� — «Создать» неактивна. ПоÑ�ле Ñ�озданиÑ� база в Ñ�пиÑ�ке, Ñ�некбар нет. +- **Меню â‹® / долгое нажатие:** «Переименовать», «Выгрузить файл…», «ПоделитьÑ�Ñ�», «СведениÑ�», «Удалить базу». + - «Переименовать» — диалог §3.3, без подпиÑ�и «Файл не менÑ�етÑ�Ñ�». + - «Выгрузить файл…» — `ACTION_CREATE_DOCUMENT`, тип `application/x-chess-pgn`, имÑ� `{Ð�азвание}.pgn`; копиÑ� вÑ�его файла как еÑ�ть; Ñ�некбар «Файл Ñ�охранён». Это одноразоваÑ� копиÑ�: приложение её не отÑ�леживает и в неё не пишет. + - «ПоделитьÑ�Ñ�» — Ñ�иÑ�темное окно Ñ� тем же файлом через `FileProvider` (как «ПоделитьÑ�Ñ� партией», §7.8). + - «СведениÑ�» — лиÑ�Ñ‚ §3.3, «Формат: PGN, Ñ�воÑ� база», «Где: на телефоне, в ChessPenguin»; Ñ�трока `info_readonly` не показываетÑ�Ñ�. + - «Удалить базу» — пуÑ�таÑ� база удалÑ�етÑ�Ñ� Ñ�разу, Ñ�о Ñ�некбаром «База удалена · Вернуть». Ð�епуÑ�таÑ� — диалог «Удалить «Игры Ñ� Maia»?» / «14 партий будут удалены Ñ� телефона. ЕÑ�ли они нужны, Ñ�начала выгрузите файл.» — «Отмена» / «Удалить» (цвет `error`). Это единÑ�твеннаÑ� копиÑ� партий пользователÑ�, поÑ�тому диалог, а не только Ñ�некбар (в отличие от копий файлов, §3.3). + +### 30.4. Ð�оваÑ� партиÑ� и Ñ�охранение + +- **«Ð�оваÑ� партиÑ�»** (Ñ€Ñ�д дейÑ�твий §30.2 или FAB «+ ПартиÑ�» в «ПартиÑ�х» Ñ�воей базы) — Ñ�кран «ПартиÑ�» Ñ� начальной позицией. Заголовок «Ð�оваÑ� партиÑ�», втораÑ� Ñ�трока — база, еÑ�ли начата из Ñ�воей базы («в «Партии Миши»»), иначе пуÑ�то. ‹ › нет. Плашки «Белые» / «Чёрные» Ñ�ерым (§7.11). +- **Признак изменений и «Сохранить».** Когда в партии еÑ�ть неÑ�охранённые правки, в верхней панели вмеÑ�то ‹ › — кнопка `save` 48 dp (подÑ�казка и TalkBack — «Сохранить в «Партии Миши»» или «Сохранить в мою базу…»). ПоÑ�ле Ñ�охранениÑ� ‹ › возвращаютÑ�Ñ�. Пока правки не Ñ�охранены, переход к Ñ�оÑ�едней партии вÑ�Ñ‘ равно потребовал бы решениÑ�, поÑ�тому ‹ › на Ñ�то времÑ� не нужны. + +| Откуда партиÑ� | «Сохранить» | Уход Ñ� правками («назад») | +|---|---|---| +| Ñ�воÑ� база | заменить запиÑ�ÑŒ; Ñ�некбар «Сохранено в «X»» | диалог «Сохранить изменениÑ� в «X»?» — «Сохранить» / «Ð�е Ñ�охранÑ�ть» / «Отмена» | +| новаÑ� партиÑ�, партиÑ� Ñ� Maia | лиÑ�Ñ‚ «Сохранить в базу» (§30.6) | диалог «Сохранить партию?» — «Сохранить в базу…» / «Ð�е Ñ�охранÑ�ть» / «Отмена» (без ходов — без диалога) | +| чужой файл, копиÑ�, онлайн-база | лиÑ�Ñ‚ «Сохранить в базу» — копиÑ� | **без диалога**; на «ПартиÑ�х» Ñ�некбар 6 Ñ� «Ваши ходы не Ñ�охранены · Вернуть» — «Вернуть» Ñ�нова открывает партию Ñ� ходами (Ñ�еÑ�Ñ�иÑ� живёт до конца Ñ�некбара) | + +- Почему чужаÑ� партиÑ� не Ñ�прашивает: на телефоне ход в учебной партии — Ñ�то «попробовать», как доÑ�ка анализа Lichess; вопроÑ� при каждом выходе из учебника мешал бы читать. Снекбар Ñ�трахует от Ñ�лучайной потери. +- Один раз, при первом ходе в чужой партии, Ñ�некбар «Ходы в Ñ�ту партию в файл не запиÑ�ываютÑ�Ñ�. КопиÑ� — кнопка «Сохранить»» (флажок в наÑ�тройках, больше не показываетÑ�Ñ�). +- СиÑ�темный «назад» и â†� в верхней панели — одно поведение; предиктивный «назад» при открытом диалоге не анимирует Ñ�кран. + +### 30.5. Данные партии + +- КаÑ�ание заголовка открывает «СведениÑ� о партии» (§7.8). У партии Ñ�воей базы и новой партии в лиÑ�те кнопка «Изменить» (Ñ€Ñ�дом Ñ� «Копировать PGN»). ЧужаÑ� партиÑ� — без неё. +- «Изменить» — полноÑ�кранный диалог (`Dialog` на веÑ�ÑŒ Ñ�кран, Material 3 длÑ� форм на телефоне): верхнÑ�Ñ� панель «✕ Данные партии [Готово]», полÑ� Ñ�толбиком по 56 dp, `OutlinedTextField`: + - «Белые» + Ñ�права «Эло» 88 dp; «Чёрные» + «Эло»; «Турнир»; «МеÑ�то»; «Дата» (клавиатура цифр, подÑ�казка «ГГГГ.ММ.ДД», правила разбора `own-databases.md` §3.5) + «Тур» 88 dp; «Результат» — `SingleChoiceSegmentedButtonRow` «1-0 · ½-½ · 0-1 · *». + - ОбÑ�зательных полей нет. Ð�еразобраннаÑ� дата — текÑ�Ñ‚ ошибки под полем, «Готово» неактивна. ПуÑ�тое поле пишетÑ�Ñ� заполнителем PGN, как на компьютере. + - «Готово» — правка в партию (её можно отменить, §29.6), поÑ�влÑ�етÑ�Ñ� кнопка «Сохранить». «✕» и «назад» Ñ� правками — «Отменить изменениÑ�?» «Отменить» / «Продолжить правку». + - Ð�оваÑ� партиÑ�: дата — Ñ�егоднÑ�; имена — пуÑ�то; длÑ� партии Ñ� Maia полÑ� уже заполнены (§31.5). +- Первое Ñ�охранение новой партии Ñ�начала открывает Ñ�ту форму Ñ� кнопкой «Сохранить в «X»» вмеÑ�то «Готово» (как режим добавлениÑ� на компьютере). +- Ð’ «ПартиÑ�х» Ñ�воей базы долгое нажатие Ñ�троки — «Данные партии» (открыть партию и форму) и «Удалить партию» (Ñ�некбар 6 Ñ� «ПартиÑ� удалена · Вернуть», запиÑ�ÑŒ возвращаетÑ�Ñ� на меÑ�то побайтно). + +### 30.6. ЛиÑ�Ñ‚ «Сохранить в базу» + +``` +┌────────────────────────────────────â”� +│ ─── │ +│ Сохранить в базу │ 22sp +│ Ð’Ñ‹ — Maia 1500 · 26.10.2026 │ 14sp onSurfaceVariant +│ (â—�) Игры Ñ� Maia 14 партий │ 56 радио, поÑ�леднÑ�Ñ� иÑ�пользованнаÑ� +│ ( ) Партии Миши 3 партии │ 56 +│ [+] Ð�оваÑ� база… │ 56 +│ [Сохранить] │ 48 +└────────────────────────────────────┘ +``` + +- Выбрана база, куда Ñ�охранÑ�ли в прошлый раз; еÑ�ли её нет — перваÑ�. Своих баз нет — Ñ�троки «Ð�оваÑ� база…» нет, вмеÑ�то Ñ�пиÑ�ка поле «Ð�азвание» (по умолчанию «Мои партии») и кнопка «Создать и Ñ�охранить». +- «Ð�оваÑ� база…» — диалог §30.3; поÑ�ле него новаÑ� база выбрана. +- Дубль (те же игроки, дата, ходы) — диалог «ТакаÑ� партиÑ� уже еÑ�ть» Ñ� «Заменить â„– 7» / «Добавить как новую» / «Отмена» (`own-databases.md` §5.5). +- ПоÑ�ле запиÑ�и — Ñ�некбар «Сохранено в «Игры Ñ� Maia», â„– 15»; партиÑ� теперь из Ñ�той базы (заголовок, ‹ ›, «Сохранить» заменÑ�ет запиÑ�ÑŒ). +- Ошибка запиÑ�и (нет меÑ�та) — диалог «Ð�е удалоÑ�ÑŒ Ñ�охранить: на телефоне нет меÑ�та» «ПонÑ�тно»; партиÑ� оÑ�таётÑ�Ñ� на Ñ�кране Ñ� правками. + +## 31. Игра Ñ� Maia (без чаÑ�ов) + +### 31.1. ЛиÑ�Ñ‚ «Игра Ñ� Maia» + +``` +┌────────────────────────────────────â”� +│ ─── │ +│ Игра Ñ� Maia │ 22sp +│ ┌──────â”� С позиции поÑ�ле 14…Ке7 │ только «Играть отÑ�юда» (§31.6): +│ │доÑ�ка │ из партии КарлÑ�ен — Каруана│ мини-доÑ�ка 96 dp, текÑ�Ñ‚ 14sp +│ │ 96 │ Ход белых │ +│ └──────┘ │ +│ Соперник — Maia 1500 │ 16sp 500 +│ 1100 â”�â”�â”�â”�â”�â”�â”�â”�â”�â—�â”�â”�â”�â”�â”�â”�â”�â”�â”�â”�â”�â”�â”�â”� 1800 │ 48 Slider, шаг 50 +│ Её измереннаÑ� Ñ�ила, по шкале блица │ 12sp onSurfaceVariant +│ Lichess. │ +│ Цвет │ +│ [ Белыми ][▌Случайноâ–�][ Чёрными ] │ 48 SegmentedButton +│ ┌ Ваше имÑ� (длÑ� запиÑ�и партии) ──â”� │ 56 необÑ�зательно +│ └────────────────────────────────┘ │ +│ Maia · 21 МБ, Ñ�качиваетÑ�Ñ� один раз │ 20 Ñ�трока Ñ�оÑ�тоÑ�ниÑ�, вÑ�егда еÑ�ть +│ Ñ� huggingface.co (файл авторов) │ +│ ┌────────────────────────────────â”� │ +│ │ Скачать и играть │ │ 56 главнаÑ�, на вÑ�ÑŽ ширину +│ └────────────────────────────────┘ │ +└────────────────────────────────────┘ +``` + +- **Сила** — `Slider` 1100–1800, шаг 50 (`steps = 13`), заголовок «Соперник — Maia {elo}» менÑ�етÑ�Ñ� при движении. ПодпиÑ�ÑŒ под ползунком — Ñ�трока компьютера `maia_measured`. РиÑ�ки шагов не риÑ�уютÑ�Ñ� (их Ñ�лишком много на 296 dp). Впервые — 1500. Таблица «Ñ�ила → чиÑ�ло длÑ� модели» малой модели — общаÑ� Ñ� компьютером (`play.rs` → крейт `play`), поÑ�тому «Maia 1500» одинакова на обоих. +- **Цвет** — «Белыми · Случайно · Чёрными», впервые «Случайно». **Времени нет** (решение: на телефоне партиÑ� вÑ�егда без чаÑ�ов) — ни выбора, ни Ñ�троки «Без чаÑ�ов». +- **ИмÑ�** — общаÑ� наÑ�тройка «Ваше имÑ�» (поле в «Ð�аÑ�тройки → ПартиÑ�» тоже); пуÑ�то — в партии «Вы»/`?`. Рейтинга и «Слабее · Как Ñ� · Сильнее» нет: ползунок из 15 положений их заменÑ�ет. +- Сила, цвет и имÑ� запоминаютÑ�Ñ� при «Играть». Цвет «Играть отÑ�юда» не запоминаетÑ�Ñ� (`play-from-position.md` §2). +- **ЛиÑ�Ñ‚ — `ModalBottomSheet`**, при открытой клавиатуре прокручиваетÑ�Ñ�; кнопка вÑ�егда видна над клавиатурой. + +### 31.2. Скачивание Maia (21 МБ) + +Тот же механизм, что Ñ�еть Stockfish (§8.4): `DownloadManager` в `filesDir`, Ñ�Ñ�ылка, ревизиÑ� и SHA-256 — из общего крейта. Строка Ñ�оÑ�тоÑ�ниÑ� и кнопка — поÑ�тоÑ�нной выÑ�оты (`maia-models.md` §2.1, «диалог не прыгает»): + +| СоÑ�тоÑ�ние | Строка Ñ�оÑ�тоÑ�ниÑ� | ГлавнаÑ� кнопка | +|---|---|---| +| не Ñ�качана | «Maia · 21 МБ, Ñ�качиваетÑ�Ñ� один раз Ñ� huggingface.co (файл авторов)» | «Скачать и играть» | +| идёт загрузка | `LinearProgressIndicator` + «8 из 21 МБ» + ✕ (отмена) | неактивна «Играть» | +| проверка | «Проверка…» | неактивна | +| готова | «Maia Ñ�качана» | «Играть» | +| нет Ñ�ети | `error`: «Ð�е удалоÑ�ÑŒ Ñ�качать: нет Ñ�оединениÑ�» | «Повторить» | +| мало меÑ�та | `error`: «Мало меÑ�та: нужно 21 МБ, Ñ�вободно {n} МБ» | «Повторить» | +| файл не тот | `error`: «Файл не Ñ�овпал Ñ� опубликованным — Ñ�качайте Ñ�нова» | «Повторить» | + +- ПоÑ�ле «Скачать и играть» партиÑ� начинаетÑ�Ñ� Ñ�ама, когда файл проверен, еÑ�ли лиÑ�Ñ‚ ещё открыт. Закрытие лиÑ�та загрузку не отменÑ�ет (уведомление `DownloadManager`); отменÑ�ет только ✕. +- **Ð�аÑ�тройки → Движок** — Ñ�трока «Maia, Ñ�оперник в игре · 21 МБ» Ñ�о второй Ñ�трокой «Ñ�качана» / «не Ñ�качана» и дейÑ�твием «Удалить» / «Скачать» (во времÑ� партии «Удалить» неактивна). + +### 31.3. Экран игры + +``` +┌────────────────────────────────────â”� +│ â†� Игра Ñ� Maia 1500 │ 64 â‹® нет +│ вы белыми · без чаÑ�ов │ +├────────────────────────────────────┤ +│ â—� Maia 1500 â—Œ думает… │ 36 плашка Ñ�оперника +│ ДОСКÐ� 360 │ +│ â—‹ Роман │ 36 плашка «вы» +├────────────────────────────────────┤ +│ 1. e4 c5 │ нотациÑ�: только главнаÑ� линиÑ�, +│ 2. Кf3 d6 │ только чтение, 184 dp +├────────────────────────────────────┤ +│ ↶ Ход âš‘ СдатьÑ�Ñ� ⇅ â—€ â–¶ │ 72 нижнÑ�Ñ� панель игры +│ назад │ +└────────────────────────────────────┘ +``` + +- **Ð�ижнÑ�Ñ� панель игры:** «Ход назад» 72 · «СдатьÑ�Ñ�» 72 · ⇅ 52 · â—€ 82 · â–¶ 82 = 360. Значки `undo`, `flag`, подпиÑ�и 12sp (как «Движок»). Кнопки «Движок», â�®, â�­ нет: движок в партии выключен (`play-mode.md` §3.7), к концу ведёт â–¶ Ñ� удержанием. До первых ходов обеих Ñ�торон вмеÑ�то «СдатьÑ�Ñ�» — «Прервать» (`close`), без подтверждениÑ�: возврат туда, откуда пришли, партиÑ� не Ñ�охранÑ�етÑ�Ñ�. +- **Плашки** — §7.11 без результата, Ñ� именами «Maia 1500» и «Ваше имÑ�» (или «Вы»). Справа на плашке Ñ�оперника, пока Maia Ñ�читает дольше 300 мÑ�, — `CircularProgressIndicator` 16 dp и «думает…» 12sp. Чей ход — больше нигде не отмечаетÑ�Ñ�. +- **ДоÑ�ка** — ориентациÑ� по цвету пользователÑ�. Ходит только Ñ�торона пользователÑ� и только в Ñ�вой ход. Пока Maia думает, фигуры не берутÑ�Ñ� (предварительных ходов нет: без чаÑ�ов Ñ�пешить некуда); каÑ�ание Ñ�воей фигуры — ничего. +- **Ход Maia** — Ñ� анимацией и звуком; пауза «как человек» — общаÑ� функциÑ� `pause` длÑ� партии без чаÑ�ов (как на компьютере). +- **ПроÑ�мотр назад** (â—€, каÑ�ание хода): над нижней панелью Ñ�трока 48 dp `primaryContainer` «ПроÑ�мотр 12…Кf6 · к игре ›», вÑ�Ñ� Ñ�трока — кнопка. Ход в прошлой позиции не делаетÑ�Ñ�: фигура возвращаетÑ�Ñ�. Ход Maia возвращает к текущей позиции Ñ�ам. +- **Ход назад** — как на компьютере: Ñ�нимает ответ Maia и ваш поÑ�ледний ход; еÑ�ли Maia думает — Ñ�нимает ваш ход, её раÑ�чёт отбраÑ�ываетÑ�Ñ� (ответ Ñ�тарой позиции не применÑ�етÑ�Ñ�). Ходы удалÑ�ÑŽÑ‚Ñ�Ñ�, а не Ñ�тановÑ�Ñ‚Ñ�Ñ� вариантом. Ð�ктивна поÑ�ле вашего первого хода. +- **СдатьÑ�Ñ�** — `AlertDialog` «СдатьÑ�Ñ�?» / «СдатьÑ�Ñ�» (`error`) · «Отмена»: чаÑ�ов нет, модальное окно ничего не Ñ�тоит. +- **Maia Ñ�даётÑ�Ñ�** — еÑ�ли Stockfish еÑ�ть (в лёгкой Ñ�борке — Ñ�качаннаÑ� Ñ�еть) и позициÑ� Maia безнадёжна два хода подрÑ�д (`play::hopeless`), вмеÑ�то хода — карточка над нотацией: «Maia Ñ�даётÑ�Ñ�» / «Её позициÑ� проиграна. ПринÑ�ть победу или доиграть?» — «ПринÑ�ть победу» (заполненнаÑ�) · «Доиграть» (больше в Ñ�той партии не предлагает). Звук `Defeat`. Без Stockfish не предлагает. +- **Сбой Maia** — карточка «Maia переÑ�тала отвечать.» — «ПерезапуÑ�тить» · «Прервать» (`play-mode.md` §3.8). +- **Поворот Ñ�крана** — партиÑ� живёт в Ñ�дре (`PlaySession`), не в Composable; раÑ�чёт продолжаетÑ�Ñ�. + +### 31.4. Конец партии + +- Экран Ñ�тановитÑ�Ñ� **обычной партией** (§7): нижнÑ�Ñ� панель §7.4 Ñ� «Движком», â‹®, ‹ › нет. Ð�ад нотацией — карточка результата (`surfaceContainerHigh`, Ñ�кругление 12, полÑ� 16): + +``` +┌────────────────────────────────────â”� +│ [1-0] Ð’Ñ‹ выиграли · мат × │ 48 чип + titleMedium +│ [ Ð�нализ ] [ Реванш ] [Сохранить…] │ 48 три кнопки по 104 +└────────────────────────────────────┘ +``` + +- Заголовок и причина — таблица `play-mode.md` §5.2 без Ñ�трок про времÑ�: «Вы выиграли» / «Вы проиграли» / «Вы Ñ�далиÑ�ь» / «Ð�ичьÑ�» + «мат», «пат», «позициÑ� повторилаÑ�ÑŒ трижды», «50 ходов без взÑ�тий и ходов пешек», «ни у кого нет материала длÑ� мата», «Maia Ñ�далаÑ�ь». +- «Ð�нализ» (заполненнаÑ�) — отчёт по партии (§21, лиÑ�Ñ‚ запуÑ�ка Ñ� прошлыми наÑ�тройками). «Реванш» — та же Ñ�ила, цвета менÑ�ÑŽÑ‚Ñ�Ñ� (при «Случайно» — Ñ�нова жребий; Ñ� позиции — та же позициÑ� и тот же цвет). «Сохранить…» — лиÑ�Ñ‚ §30.6; поÑ�ле запиÑ�и кнопка — «✓ Сохранено». «Ð�оваÑ� игра» (лиÑ�Ñ‚ §31.1) — в â‹®. +- Реванш и новаÑ� игра при неÑ�охранённой партии — диалог «Сохранить партию?» (§30.4). Ð�втоÑ�охранениÑ� в базу нет. +- × убирает карточку; карточка уходит и при первой правке партии. Звук конца: `Success` при победе, `Defeat` при поражении, `Move` при ничьей (как на компьютере, где еÑ�ть). + +### 31.5. Теги Ñ�ыгранной партии + +Как на компьютере (крейт `play`): `Event` «ПартиÑ� Ñ� компьютером», `Site` «ChessPenguin», `Date` Ñ�егоднÑ�, `White`/`Black` — имÑ� и «Maia 1500», `Result`, `Termination`, `WhiteType`/`BlackType` `human`/`program`. `TimeControl "-"`, `[%clk]` нет. С позиции — ходы иÑ�ходной партии и комментарий проиÑ�хождениÑ� (`play-from-position.md` §3.2). + +### 31.6. «Играть отÑ�юда» + +- Вход — лиÑ�Ñ‚ хода (§29.6) или â‹® «Играть Ñ� Ñ�той позиции…». ЛиÑ�Ñ‚ §31.1 Ñ� блоком позиции, цвет по умолчанию — Ñ�торона, чей ход. +- Экран игры — §31.3; ходы иÑ�ходной партии в нотации `onSurfaceVariant`, поÑ�ле них блок проиÑ�хождениÑ�. «Ход назад» и «Прервать» — только по новым ходам. «Прервать», «назад» до первых ходов и «назад» поÑ�ле конца ведут к иÑ�ходной партии (её правки и курÑ�ор целы — Ñ�кран оÑ�таётÑ�Ñ� в Ñ�теке под игрой). + +### 31.7. Уход из идущей партии и фон + +ПартиÑ� без чаÑ�ов, поÑ�тому **ничего не терÑ�етÑ�Ñ� и ничего не Ñ�прашиваетÑ�Ñ�**: + +- **Фон, звонок, гашение Ñ�крана** — ничего оÑ�обенного: раÑ�чёт Maia может продолжитьÑ�Ñ� или замереть вмеÑ�те Ñ� процеÑ�Ñ�ом; при возврате ход применÑ�етÑ�Ñ�, еÑ�ли он про текущую позицию. +- **«Ð�азад» / â†�** — партиÑ� **откладываетÑ�Ñ�** (рекомендациÑ�, вопроÑ� 1): Ñ�дро пишет её PGN в `filesDir/play/current.pgn` поÑ�ле каждого хода. Ð�а «Базах» над Ñ€Ñ�дом дейÑ�твий — карточка «ПартиÑ� Ñ� Maia 1500 · 24-й ход · вы белыми» — «Продолжить» · ×. × — «ПартиÑ� удалена · Вернуть». ЕÑ�ли Android завершил процеÑ�Ñ�, карточка та же. +- Одна отложеннаÑ� партиÑ�. «Играть Ñ� Maia», пока она еÑ�ть, — диалог «ЕÑ�ть отложеннаÑ� партиÑ� Ñ� Maia 1500» — «Продолжить её» · «Ð�ачать новую» (отложеннаÑ� удалÑ�етÑ�Ñ�). + +## 32. Тренировка дебюта + +### 32.1. Вход и Ñ�кран + +- ЛиÑ�Ñ‚ хода (§29.6) «Учить дебют до Ñ�того хода»; Ñ�права «прохождений: 4», еÑ�ли линию учили. Без диалога: Ñ�кран открываетÑ�Ñ� в начальной позиции линии, поверх партии (партиÑ� в Ñ�теке не менÑ�етÑ�Ñ�). + +``` +┌────────────────────────────────────â”� +│ â†� Учим дебют │ 64 +│ КарлÑ�ен — Каруана · до 12…Лd8 │ +├────────────────────────────────────┤ +│ Ход 7 из 12 ход белых │ 48 карточка «задание» +│ â–“â–“â–“â–“â–“â–“â–“â–“â–“â–“â–“â–“â–“â–“â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘ │ 3 прогреÑ�Ñ� внутри полоÑ�Ñ‹ +│ ДОСКÐ� 360 │ +│ Ошибок: 2 Прохождение 3 │ 48 карточка «вы» +├────────────────────────────────────┤ +│ 1. e4 c5 │ 160 нотациÑ�: только Ñ�ыгранное +├────────────────────────────────────┤ +│ ⇅ ↻ Сначала â—€ â–¶ │ 72 +└────────────────────────────────────┘ +``` + +- ПолоÑ�Ñ‹ 48 dp вмеÑ�то плашек 36 (в полоÑ�е «вы» бывает кнопка, ей нужно 48 dp); текÑ�ты — `opening-trainer.md` §2.4–2.5. «ход белых» — `titleSmall` 500. Второй Ñ�троки длÑ� иÑ�тории в полоÑ�е 48 dp нет, поÑ�тому до первого хода полоÑ�а «вы» показывает иÑ�торию («Прошлое: 1 · лучшее: 0» / «Эту линию ещё не проходили») вмеÑ�то «Ошибок: 0», а поÑ�ле первого хода — Ñ�чёт ошибок. +- ОриентациÑ� — как на Ñ�кране партии при входе, за ходом не поворачиваетÑ�Ñ�. ХодÑ�Ñ‚ обе Ñ�тороны (пользователь за обе). Превращение — Ñ�м. §29.4. +- Ð�ижнÑ�Ñ� панель: ⇅ 72 · «Сначала» 144 (`replay`, неактивна до первого хода, без подтверждениÑ�) · â—€ 72 · â–¶ 72. ПроÑ�мотр назад — Ñ�трока «ПроÑ�мотр · к тренировке ›» (§31.3). +- Движка, меню â‹®, долгого нажатиÑ� нет. + +### 32.2. Ход + +- **Верный** — обычный звук, ход в нотации, «Ход … из …» и прогреÑ�Ñ� обновлÑ�ÑŽÑ‚Ñ�Ñ�. +- **Ð�еверный** (законный, не ход линии): фигура вÑ�таёт на поле; клетки «откуда» и «куда» — `error` 0,45; звук `Wrong`; вибрациÑ� `REJECT`; полоÑ�а «вы» — «✗ Ð’ партии другой ход» цветом `error`, «Ошибок» +1. Через 400 мÑ� фигура возвращаетÑ�Ñ� (150 мÑ� анимации), заливка Ñ�нимаетÑ�Ñ�, Ñ�ообщение оÑ�таётÑ�Ñ� до верного хода. Пока 400 мÑ� не прошли, доÑ�ка каÑ�аний не принимает. +- **Ð�езаконнаÑ�** попытка — не ошибка: как везде (§29.3). +- **ТретьÑ� ошибка на одном полуходе** — Ñ�права в полоÑ�е «вы» кнопка `TextButton` «Показать ход». КаÑ�ание — на доÑ�ке Ñ�трелка верного хода, Ñ�ообщение «Сделайте ход Ñ�о Ñ�трелки». Прохождение заÑ�читываетÑ�Ñ� «Ñ� подÑ�казкой» (`opening-trainer.md` §6, вариант Б, — так Ñ�делано на компьютере, `train.rs` `HINT_AFTER = 3`). + +### 32.3. Итог и Ñ�татиÑ�тика + +- ПоÑ�ледний ход Ñ�ыгран → звук `Success`, полоÑ�Ñ‹ «задание» и «вы» Ñ�крываютÑ�Ñ�, над нотацией карточка (вид §31.4): + +``` +┌────────────────────────────────────â”� +│ [✓] Пройдено · ошибок: 2 │ 48 +│ Прохождение 5 · лучшее: 0 │ 14sp +│ ПоÑ�ледние: 3 · 2 · 1 · 0 · 2 │ 14sp onSurfaceVariant +│ [ Ещё раз ] [ К партии ] │ 48 +└────────────────────────────────────┘ +``` + +- ТекÑ�ты — `opening-trainer.md` §4 («Пройдено без ошибок», «Пройдено Ñ� подÑ�казкой · ошибок: 5», «без ошибок подрÑ�д: 2», «5*»). У ходов Ñ� ошибками в нотации — «×2» 12sp цветом `error` (Ñ� подÑ�казкой — цветом предупреждениÑ�). +- «Ещё раз» — новое прохождение Ñ�разу; «К партии» и «назад» — к иÑ�ходной партии. Уход поÑ�реди прохождениÑ� — без вопроÑ�а, не заÑ�читываетÑ�Ñ�. +- СтатиÑ�тика — `filesDir/training.json`, формат и ключ линии общие Ñ� компьютером (крейт тренера); Ñ� компьютером не Ñ�инхронизируетÑ�Ñ�. + +## 33. Звуки + +- **Ð�абор один** — `sfx` компьютера (Lichess standard) плюÑ� `common/Wrong` (Kenney, CC0); лицензии уже в `THIRD_PARTY_NOTICES.md`. Выбора наборов и громкоÑ�ти нет (§15.4). +- **СобытиÑ�:** ход, взÑ�тие, шах (и мат — звук шаха, как в `sfx`), ошибка тренера, линиÑ� пройдена, конец игры (`Success`/`Defeat`), Maia Ñ�даётÑ�Ñ� (`Defeat`). +- **Где:** ходы на доÑ�ке, ход Maia, шаги â—€ â–¶ и каÑ�ание хода в нотации (§7.4 Ñ�то уже обещает). При удержании â—€ â–¶ (повтор) звук и вибрациÑ� — только у первого шага и у поÑ�леднего. +- **Проигрывание** — `SoundPool`, `AudioAttributes.USAGE_GAME` (громкоÑ�ть мультимедиа); звуки загружаютÑ�Ñ� при открытии Ñ�крана партии. +- **Ð�аÑ�тройка** «ПартиÑ� → Звук» Ñ€Ñ�дом Ñ� «Вибрацией», включена по умолчанию. + +## 34. ДоÑ�тупноÑ�ть + +- **Цели каÑ�аниÑ�.** Клетка 45 dp — меньше 48: иÑ�ключение, как во вÑ�ех шахматных приложениÑ�Ñ…; TalkBack даёт обходной путь. Ð’Ñ�Ñ‘ оÑ�тальное новое — не меньше 48 dp (полоÑ�Ñ‹ тренировки, Ñ�троки лиÑ�тов, кнопки карточек, Ñ�егменты). +- **ДоÑ�ка в TalkBack** — каждаÑ� клетка узел Ñ� ролью кнопки, озвучивание §12.3 плюÑ� Ñ�оÑ�тоÑ�ниÑ�: «g1, белый конь, выбран»; на законном поле — «f3, пуÑ�то, можно пойти» / «d5, чёрнаÑ� пешка, можно взÑ�ть». Двойное каÑ�ание = тап (§29.2): ход делаетÑ�Ñ� без перетаÑ�киваниÑ�. ПоÑ�ле хода — объÑ�вление (`liveRegion` polite) запиÑ�и хода Ñ�ловами: «Конь f3», «Maia: конь f6, шах». +- **Ход в нотации** — пользовательÑ�кие дейÑ�твиÑ� TalkBack (`customActions`) вмеÑ�то долгого нажатиÑ�: «Сделать оÑ�новным», «Удалить ход и продолжение», «Играть отÑ�юда Ñ� Maia», «Учить дебют до Ñ�того хода». +- **Тренер** — неверный ход объÑ�влÑ�етÑ�Ñ� «Ð�е тот ход. Ошибок: 2»; «Показать ход» — кнопка, поÑ�ле неё объÑ�вление «Ð�ужный ход: конь f3» (Ñ�трелку TalkBack не видит). +- **Думает Maia** — плашка «Maia 1500, думает»; без анимаций при «удалить анимации» в Ñ�иÑ�теме: подÑ�казки поÑ�влÑ�ÑŽÑ‚Ñ�Ñ� Ñ�разу, вÑ�пышка ошибки держитÑ�Ñ� 400 мÑ� без перехода. +- СмыÑ�л не только цветом: ошибка — ещё и текÑ�Ñ‚, выделение — ещё и озвучивание. + +## 35. ТекÑ�ты RU / EN + +Ключи новые; где Ñ�трока Ñ�овпадает Ñ� компьютерной (`i18n.rs`), берётÑ�Ñ� её перевод на вÑ�е 9 Ñ�зыков. Plurals — как в §14. + +| Ключ | RU | EN | +|---|---|---| +| `play_maia` | Играть Ñ� Maia | Play Maia | +| `new_game` | Ð�оваÑ� партиÑ� | New game | +| `own_dbs` / `files_group` | Мои базы / Файлы | My databases / Files | +| `own_empty` | ЗдеÑ�ÑŒ будут партии, которые вы введёте или Ñ�ыграете Ñ� Maia | Games you enter or play against Maia will appear here | +| `own_new` / `own_new_title` | Ð�оваÑ� база / Ð�оваÑ� база | New database / New database | +| `own_name` / `own_default` | Ð�азвание / Мои партии | Name / My games | +| `own_where_hint` | ХранитÑ�Ñ� на телефоне, в ChessPenguin. Выгрузить файл можно в меню базы. | Kept on the phone, in ChessPenguin. You can export the file from the database menu. | +| `own_create` / `own_create_save` | Создать / Создать и Ñ�охранить | Create / Create and save | +| `own_games` | {n} партий · на телефоне | {n} games · on the phone | +| `own_export` / `own_exported` | Выгрузить файл… / Файл Ñ�охранён | Export file… / File saved | +| `own_delete` / `own_delete_q` | Удалить базу / Удалить «{name}»? | Delete database / Delete “{name}â€�? | +| `own_delete_body` | {n} партий будут удалены Ñ� телефона. ЕÑ�ли они нужны, Ñ�начала выгрузите файл. | {n} games will be deleted from the phone. If you need them, export the file first. | +| `own_deleted` / `delete` | База удалена / Удалить | Database deleted / Delete | +| `own_info_format` / `own_info_where` | PGN, Ñ�воÑ� база / Ð�а телефоне, в ChessPenguin | PGN, your own database / On the phone, in ChessPenguin | +| `save_to` / `save_to_my` | Сохранить в «{name}» / Сохранить в мою базу… | Save to “{name}â€� / Save to my database… | +| `save_sheet` / `saved_to` | Сохранить в базу / Сохранено в «{name}», â„– {n} | Save to a database / Saved to “{name}â€�, no. {n} | +| `save_failed_space` | Ð�е удалоÑ�ÑŒ Ñ�охранить: на телефоне нет меÑ�та | Could not save: the phone is out of space | +| `dup_title` / `dup_body` | ТакаÑ� партиÑ� уже еÑ�ть / Ð’ базе «{name}» â„– {n}: те же игроки, дата и ходы. | This game is already there / In “{name}â€�, no. {n}: same players, date and moves. | +| `dup_replace` / `dup_add` | Заменить â„– {n} / Добавить как новую | Replace no. {n} / Add as a new game | +| `leave_own_q` | Сохранить изменениÑ� в «{name}»? | Save the changes to “{name}â€�? | +| `leave_new_q` | Сохранить партию? | Save the game? | +| `dont_save` | Ð�е Ñ�охранÑ�ть | Don't save | +| `moves_not_saved` | Ваши ходы не Ñ�охранены | Your moves were not saved | +| `foreign_hint` | Ходы в Ñ�ту партию в файл не запиÑ�ываютÑ�Ñ�. КопиÑ� — кнопка «Сохранить» | Moves are not written to this file. To keep a copy, tap Save | +| `edit_undo` / `edit_undo_move` / `edit_undo_delete` | Отменить / ход {move} / удаление ходов | Undo / move {move} / deleting moves | +| `make_main` / `delete_from_here` | Сделать оÑ�новным / Удалить ход и продолжение | Make main line / Delete move and continuation | +| `moves_deleted` / `line_added` | Ходы удалены / Вариант добавлен | Moves deleted / Line added | +| `add_as_line` | + Вариантом | + As a line | +| `play_from_here` / `play_from_pos` | Играть отÑ�юда Ñ� Maia… / Играть Ñ� Ñ�той позиции… | Play on from here against Maia… / Play from this position… | +| `train_here` / `train_runs` | Учить дебют до Ñ�того хода / прохождений: {n} | Learn the opening up to this move / runs: {n} | +| `train_null` | Ð’ линии еÑ�ть пропуÑ�к хода (--) | The line has a null move (--) | +| `pos_over` | ЗдеÑ�ÑŒ партиÑ� окончена: {reason} | The game is over here: {reason} | +| `game_data` / `edit` / `done` | Данные партии / Изменить / Готово | Game data / Edit / Done | +| `tag_white` … `tag_round` | Белые, Чёрные, Эло, Турнир, МеÑ�то, Дата, Тур, Результат | White, Black, Elo, Event, Site, Date, Round, Result | +| `date_hint` / `date_bad` | ГГГГ.ММ.ДД / Дата в виде 2026.10.18, 2026.10 или 2026 | YYYY.MM.DD / A date like 2026.10.18, 2026.10 or 2026 | +| `discard_q` / `discard` / `keep_editing` | Отменить изменениÑ�? / Отменить / Продолжить правку | Discard changes? / Discard / Keep editing | +| `sound` / `your_name` | Звук / Ваше имÑ� | Sound / Your name | +| `play_title` / `play_opponent` | Игра Ñ� Maia / Соперник — Maia {elo} | Play Maia / Opponent — Maia {elo} | +| `maia_measured` | Её измереннаÑ� Ñ�ила, по шкале блица Lichess. | Her measured strength, on the Lichess blitz scale. | +| `colour` / `as_white` / `random` / `as_black` | Цвет / Белыми / Случайно / Чёрными | Colour / White / Random / Black | +| `name_for_game` | Ваше имÑ� (длÑ� запиÑ�и партии) | Your name (for the game record) | +| `maia_offer` | Maia · 21 МБ, Ñ�качиваетÑ�Ñ� один раз Ñ� huggingface.co (файл авторов) | Maia · 21 MB, downloaded once from huggingface.co (the authors' file) | +| `maia_progress` / `checking` / `maia_ready` | {a} из {b} МБ / Проверка… / Maia Ñ�качана | {a} of {b} MB / Checking… / Maia downloaded | +| `dl_no_net` / `dl_no_space` / `dl_bad` | Ð�е удалоÑ�ÑŒ Ñ�качать: нет Ñ�оединениÑ� / Мало меÑ�та: нужно {need} МБ, Ñ�вободно {free} МБ / Файл не Ñ�овпал Ñ� опубликованным — Ñ�качайте Ñ�нова | Download failed: no connection / Not enough space: {need} MB needed, {free} MB free / The file is not the published one — download it again | +| `download_play` / `play` / `retry` | Скачать и играть / Играть / Повторить | Download and play / Play / Retry | +| `maia_settings` | Maia, Ñ�оперник в игре · 21 МБ | Maia, the opponent in games · 21 MB | +| `play_sub` | вы белыми · без чаÑ�ов / вы чёрными · без чаÑ�ов | you play White · no clock / you play Black · no clock | +| `thinking` | думает… | thinking… | +| `take_back` / `resign` / `abort` | Ход назад / СдатьÑ�Ñ� / Прервать | Take back / Resign / Abort | +| `resign_q` | СдатьÑ�Ñ�? | Resign? | +| `viewing` / `to_game` / `to_training` | ПроÑ�мотр {move} / к игре / к тренировке | Viewing {move} / back to the game / back to training | +| `maia_resigns` / `maia_resigns_body` | Maia Ñ�даётÑ�Ñ� / Её позициÑ� проиграна. ПринÑ�ть победу или доиграть? | Maia resigns / Her position is lost. Accept the win, or play to the end? | +| `accept_win` / `play_on` | ПринÑ�ть победу / Доиграть | Accept the win / Play to the end | +| `maia_stopped` / `restart` | Maia переÑ�тала отвечать. / ПерезапуÑ�тить | Maia stopped responding. / Restart | +| `won` / `lost` / `you_resigned` / `draw` | Ð’Ñ‹ выиграли / Ð’Ñ‹ проиграли / Ð’Ñ‹ Ñ�далиÑ�ÑŒ / Ð�ичьÑ� | You won / You lost / You resigned / Draw | +| `end_*` | мат; пат; позициÑ� повторилаÑ�ÑŒ трижды; 50 ходов без взÑ�тий и ходов пешек; ни у кого нет материала длÑ� мата; Maia Ñ�далаÑ�ÑŒ | checkmate; stalemate; the position occurred three times; 50 moves without a capture or a pawn move; neither side can checkmate; Maia resigned | +| `analyse` / `rematch` / `save_dots` / `saved_check` | Ð�нализ / Реванш / Сохранить… / ✓ Сохранено | Analyse / Rematch / Save… / ✓ Saved | +| `deferred` / `continue` | ПартиÑ� Ñ� Maia {elo} · {n}-й ход / Продолжить | Game against Maia {elo} · move {n} / Continue | +| `deferred_q` / `deferred_resume` / `deferred_new` | ЕÑ�ть отложеннаÑ� партиÑ� Ñ� Maia {elo} / Продолжить её / Ð�ачать новую | There is an unfinished game against Maia {elo} / Continue it / Start a new one | +| `game_deleted` | ПартиÑ� удалена | Game deleted | +| `train_title` / `train_upto` | Учим дебют / до {move} | Learning the opening / up to {move} | +| `train_move_of` / `w_to_move` / `b_to_move` | Ход {n} из {m} / ход белых / ход чёрных | Move {n} of {m} / White to move / Black to move | +| `train_mistakes` / `train_run` | Ошибок: {n} / Прохождение {n} | Mistakes: {n} / Run {n} | +| `train_last` / `train_new` | Прошлое: {n} · лучшее: {m} / Эту линию ещё не проходили | Last time: {n} · best: {m} / Not done before | +| `train_wrong` / `train_show` / `train_play_arrow` | ✗ Ð’ партии другой ход / Показать ход / Сделайте ход Ñ�о Ñ�трелки | ✗ The game has another move here / Show the move / Play the move on the arrow | +| `train_restart` / `train_again` / `back_to_game` | Сначала / Ещё раз / К партии | Restart / Again / Back to the game | +| `train_done*` | Пройдено без ошибок / Пройдено · ошибок: {n} / Пройдено Ñ� подÑ�казкой · ошибок: {n} | Done without mistakes / Done · mistakes: {n} / Done with a hint · mistakes: {n} | +| `train_recent` / `train_clean` | ПоÑ�ледние: {list} / без ошибок подрÑ�д: {n} | Recent: {list} / clean in a row: {n} | +| `cd_square_*` | можно пойти / можно взÑ�ть / выбран | can move here / can capture / selected | +| `cd_promote` | Превратить в: {piece} | Promote to: {piece} | +| `cd_wrong` / `cd_hint` | Ð�е тот ход. Ошибок: {n} / Ð�ужный ход: {move} | Not the move. Mistakes: {n} / The move: {move} | +| `cd_save` / `cd_thinking` | Сохранить в «{name}» / {name}, думает | Save to “{name}â€� / {name}, thinking | + +## 36. Что Ñ�троит разработчик (порÑ�док) + +1. Ядро: `GameSession` (§4.1 иÑ�Ñ�ледованиÑ�), каÑ�аниÑ� доÑ�ки, превращение, точки, вÑ�тавка хода по §29.5, отмена, лиÑ�Ñ‚ хода, звуки (§33), доÑ�тупноÑ�ть доÑ�ки (§34). +2. Свои базы (§30): папка, Ñ�пиÑ�ок Ñ� группами, Ñ�оздание/удаление/выгрузка, Ñ�охранение, форма данных, лиÑ�Ñ‚ «Сохранить в базу», дубль. +3. Тренировка (§32) — поÑ�ле выноÑ�а тренера из `apps/desktop` в крейт. +4. Игра Ñ� Maia (§31) — поÑ�ле крейта `play` и Ñ�качиваниÑ� 5M; отложеннаÑ� партиÑ� (§31.7). + +## 37. ВопроÑ�Ñ‹ владельцу + +1. **Уход из партии Ñ� Maia** — откладывать её (карточка «Продолжить» на «Базах», переживает закрытие приложениÑ�, §31.7) вмеÑ�то вопроÑ�а «СдатьÑ�Ñ� и выйти», как на компьютере? +2. **Ходы в чужой партии** (учебник, онлайн-база) — не Ñ�прашивать при выходе, только Ñ�некбар «Ваши ходы не Ñ�охранены · Вернуть» (§30.4)? Или Ñ�прашивать, как на компьютере? +3. **РÑ�д «Играть Ñ� Maia · Ð�оваÑ� партиÑ�»** вверху «Баз» (§30.2) — уÑ�траивает, или «Играть» вынеÑ�ти крупнее (например, длÑ� детей — первой Ñ�трокой на вÑ�ÑŽ ширину)? diff --git a/docs/design/android-players-improvement.md b/docs/design/android-players-improvement.md new file mode 100644 index 0000000..d5b6510 --- /dev/null +++ b/docs/design/android-players-improvement.md @@ -0,0 +1,211 @@ +# Задача 48. Android: улучшение Ñ�крана «Игроки» + +Дизайнер, 2026-11-29. Документ предлагает Ñ�ледующий MVP-шаг поÑ�ле уже реализованного Ñ�крана. **Production-код, реÑ�урÑ�Ñ‹ и другие документы не изменÑ�лиÑ�ÑŒ.** Это не отчёт о визуальной приёмке и не иÑ�правление падениÑ� поиÑ�ка. + +## 1. Задача и приоритет + +**Задача Ñ�крана — быÑ�тро найти точное имÑ� и начать подготовку за нужный цвет, не заÑ�тавлÑ�Ñ� человека читать по две одинаковые кнопки у каждого игрока.** + +Приоритеты: + +1. точное имÑ� и понÑ�тное Ñ�ледующее дейÑ�твие; +2. чиÑ�ло партий по каждому цвету, включа� че�тный ноль; +3. одно ка�ание там, где �уще�твует только один возможный цвет, и от�ут�твие отдельного подтверждени� «Открыть»; +4. пло�кий мобильный �пи�ок, пои�к и прокрутка �отен имён — не таблица и не до�ье. + +Общее чи�ло партий о�таёт�� полезным контек�том, но не должно отнимать ме�то у имени и цветов. Пои�к похожих имён, объединение напи�аний, аватары, рейтинги, �пи�ок партий игрока и до�ье не добавл�ют��. + +## 2. Что проверено в материалах + +### 2.1. Текуща� реализаци� + +Прочитаны `docs/design/android-opponent-prep.md` §4 и актуальный `PlayersScreen.kt`. + +Сейча� `PlayerPrepRow` дей�твительно �о�тоит из: + +- имени и общего �чётчика; +- двух отдельных кнопок вы�отой не менее 48 dp; +- нейтральных плашек `surfaceContainerLow` �о �круглением 8 dp; +- disabled-кнопки при нулевом цвете; +- обычной вы�оты 88 dp и трёх accessibility-узлов на человека: информаци�, White, Black. + +Это пон�тна� и бы�тра� �хема: цвет выбирает�� �разу, одним ка�анием. Её цена — повторение двух плашек и подпи�ей в каждой �троке, а также визуальное при�ут�твие неактивных дей�твий там, где у человека е�ть партии только одним цветом. + +`/tmp/opencode/qa48-search-crash/players.xml` �уще�твует и прочитан как **UI Automator XML, а не PNG**. �а AVD 1080×2400, 420 dpi он подтверждает: + +- шаг обычных �трок 231 px = 88 dp; +- цветовые цели 126 px = 48 dp; +- пол� 42 px = 16 dp; +- у Alekhine две до�тупные кнопки, у Anderssen — White до�тупна, Black � нулём disabled; +- им�/�чёт и обе цветовые кнопки �вл�ют�� отдельными semantic nodes. + +Также прочитаны `games.xml` и `logcat.txt`. Падение — отдельный `NullPointerException` из-за чтени� `players!!` �тарым `LazyColumn` при �мене запро�а. �ова� компоновка �ама по �ебе �тот дефект не и�правл�ет и не должна подмен�ть его regression-фик�. + +**Ограничение evidence:** актуального PNG Players в `/tmp/opencode/qa48-search-crash/` нет; прежний каталог `/tmp/opencode/prep48` от�ут�твует. По�тому утверждени� о текущей геометрии опирают�� на XML и Kotlin, а не на не�уще�твующий новый �нимок. �иже — проектное �равнение, не повторна� визуальна� приёмка �тарого �крана. + +### 2.2. Визуальна� �и�тема продукта + +Ин�трументом про�мотра изображений по�мотрены �ами изображени�: + +- `docs/screenshots/android.jpg`, 1920×1080 — монтаж Android-�пи�ков, партии и ли�тов; +- `website/shots/raw/phone/01-home.png`, `02-games.png`, `03-game.png`, каждый 1080×2400; +- `designExample/reference.png`, `designExample/до�ка.png`, `designExample/панель ходов � ответвлени�ми.png` — референ�ы �мы�ла до�ки и нотации, не макет мобильного �пи�ка. + +Дл� Players нужно �охранить уже �уще�твующий �зык Android-приложени�: тёмную `surface`, обычную `TopAppBar`, `bodyLarge`/`bodyMedium`, `SideDisc`, пло�кие разделители `outlineVariant`, пол� 16 dp и �тандартный ripple. �овых цветовых ролей, карточек, градиентов, аватаров и dashboard-плиток не требует��. + +## 3. Сравнение вариантов + +| Вариант | Дей�тви� | Плотно�ть и шум | Цена | +|---|---|---|---| +| **A. О�тавить две кнопки 48 dp у каждого** | В�егда 1 ка�ание | 88 dp; полные �лова White/Black �амые �вные, но две плашки и до двух дей�твий повтор�ют�� в каждой �троке. �улевой цвет занимает disabled-плашку | Минимум разработки и уже знакома� модель. �е решает запро� на более �покойный и компактный �кран; при линейном TalkBack-обходе много лишних о�тановок | +| **B. Одна �трока игрока → выбор цвета** | Обычно 2 ка�ани�: игрок, затем цвет | Строка может быть 72 dp; им� и в�е �чётчики видны без кнопочных плашек. �а ли�те помещают�� полное им�, полные подпи�и и точные чи�ла | Дополнительный ли�т и второй тап даже тогда, когда ненулевой цвет только один. Е�ли об�зательно открывать ли�т в�ем, �то неоправданна� плата за единообразие | +| **C. Компактные segmented controls в �троке** | 1 ка�ание, е�ли �егмент �разу запу�кает подготовку; 2, е�ли �то на�то�щий single-choice � по�ледующим «Открыть» | Возможна �трока 72 dp, но на 360 dp группа шириной 144 dp о�тавл�ет имени примерно 172 dp по�ле полей и промежутка. Полные локализованные «Белыми»/«Чёрными» и большие чи�ла уже не помещают��; приходит�� о�тавл�ть круги и короткие чи�ла | Маленькие �о�едние цели повышают цену промаха и �нова �окращают имена. При 280 dp/font scale 2.0 блок придёт�� перено�ить, возвраща��ь к вы�оте текущего варианта. `SingleChoiceSegmentedButtonRow` �о `selected` также ложно обещает �охран�емый выбор, хот� зде�ь нужен переход, а не фильтр | + +### Рекомендаци� — **B+: одна �покойна� �трока, ли�т только при реальном выборе** + +- **Оба цвета ненулевые:** ка�ание �троки открывает короткий `ModalBottomSheet` � двум� большими дей�тви�ми. Второй тап — �ам выбор цвета, отдельной кнопки подтверждени� нет. +- **�енулевой только один цвет:** ка�ание �троки �разу открывает подготовку �тим цветом. Спрашивать един�твенный возможный вариант не нужно. +- **�оль:** о�таёт�� видимым тек�том в �троке, но пере�таёт быть отдельной disabled-кнопкой. +- �икогда не выбирать автоматиче�ки цвет � большим чи�лом партий, по�ледний и�пользованный цвет или White по умолчанию. + +Так �охран�ет�� один тап у ча�того �луча� «е�ть только White или только Black», а при двух репертуарах по�вл�ет�� более �вный и безопа�ный выбор. Это не �крыта� �мена �мы�ла �троки: до�тупные цвета и ноль видны до ка�ани�, а TalkBack заранее произно�ит либо «Выбрать цвет», либо «Подготовить�� белыми/чёрными». + +Почему не C: �кономи� одного ка�ани� только у игроков � двум� цветами не оправдывает по�то�нное �окращение в�ех имён, ри�к попа�ть не в тот �егмент и неоднозначную �емантику selected/action. При необходимо�ти A можно о�тавить как временную реализацию, но не как целевой MVP-�кран. + +## 4. Пользователь�кий путь и контек�т + +```text +Партии → Игроки → игрок � двум� цветами → ли�т цвета → Подготовка + └ игрок � одним цветом ───────────────→ Подготовка +``` + +- Пои�к о�таёт�� в текущей `TopAppBar`: под�трока без учёта реги�тра, задержка 250 м�, ✕ и �и�темное закрытие пои�ка. Пор�док — алфавитный через `Collator`; точные напи�ани� не объедин�ют��. +- При переходе в подготовку клавиатура �крывает��. Возврат во��танавливает запро�, режим пои�ка и прокрутку, но �ам не открывает клавиатуру поверх �пи�ка. +- Возврат из подготовки идёт в Players, а не заново в ли�т цвета. Прежний игрок не получает по�то�нную под�ветку «выбран» или «текуща� позици�». +- Android Back при открытом ли�те �начала закрывает только ли�т и возвращает фоку� на и�ходную �троку. Следующий Back возвращает�� в партии. +- Players и ли�т только читают уже полученный `PlayerSummary`; никаких не�охранённых изменений и диалога �охранени� нет. + +## 5. Макет �пи�ка + +### 5.1. Обычна� �трока, 360 dp + +```text +┌────────────────────────────────────� +│ � Игроки ⌕ │ +│ Classic games │ +│────────────────────────────────────│ +│ Alekhine, Alexander 5 партий ›│ 24 +│ ○ Белыми · 2 � Чёрными · 3 │ 20 +│────────────────────────────────────│ обычна� вы�ота �троки 72 +│ Anderssen, Adolf 2 партии ›│ +│ ○ Белыми · 2 � Чёрными · 0 │ +│────────────────────────────────────│ +│ Aronian, Levon 1 парти� ›│ +│ ○ Белыми · 1 � Чёрными · 0 │ +└────────────────────────────────────┘ +``` + +`›` показан �права у�ловно по центру �троки, а не как треть� колонка таблицы. В�� �трока, включа� им�, �чётчики и �вободное ме�то, — одна кнопка. + +### 5.2. Геометри� и типографика + +- Минимальна� вы�ота — **72 dp**: 12 �верху + им�/общий �чёт 24 + 4 + цвета 20 + 12 �низу. Разделитель 1 dp находит�� внутри нижней границы и вы�оту не добавл�ет. +- По �равнению �о 88 dp �то на 18 % меньше вы�оты и примерно на 22 % больше видимых �трок в той же обла�ти. �апример, в подтверждённой текущим XML обла�ти около 750 dp помещает�� ориентировочно 10,4 �троки вме�то 8,5. +- Горизонтальные пол� — 16 dp. Справа декоративный `ChevronRight` 24 dp `onSurfaceVariant`, перед ним промежуток 8 dp; отдельной зоны нажати� у него нет. +- Им� — �уще�твующий `PlayerName`, `bodyLarge`: полное им�, затем `shortName`, затем многоточие. Полное точное им� о�таёт�� в content description. Общий �чёт — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`, одной �трокой; перед ним 8 dp, �окращает�� �начала им�. +- Цвета — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`, в неизменном пор�дке **Белыми, затем Чёрными**. Суще�твующий `SideDisc` 12 dp, промежуток до тек�та 8 dp; круг не озвучивает�� отдельно. +- Группа «круг + название цвета + чи�ло» неделима. Между группами 16 dp. Е�ли обе не помещают��, они перено��т�� на две �троки, а вы�ота ра�тёт через `heightIn(min = 72.dp)`; горизонтальной прокрутки и обрезани� нулей нет. +- Общее чи�ло — прежнее чи�ло различных запи�ей, а не об�зательно `whiteGames + blackGames`. Оно не должно «и�правл�ть��» �уммированием на UI. +- Строка пло�ка�, без фона-карточки. Е�ть �тандартный ripple и разделитель `outlineVariant`; по�то�нного selected-фона по�ле возврата нет. + +### 5.3. Ли�т выбора цвета + +Открывает�� только когда `whiteGames > 0 && blackGames > 0`: + +```text +┌────────────────────────────────────� +│ ─── │ +│ Alekhine, Alexander │ titleLarge, полное им� +│ 5 партий · выберите цвет │ bodyMedium, secondary +│ ○ Белыми 2 ›│ 64, в�� �трока — дей�твие +│ � Чёрными 3 ›│ 64 +└────────────────────────────────────┘ +``` + +- И�пользовать �уще�твующий паттерн `ModalBottomSheet`, горизонтальные пол� 24 dp и нижний от�туп 24 dp, как у текущего ли�та подготовки из партии. +- Полное им� перено�ит��, а не замен�ет�� инициалами. При аномально длинном теге �одержимое ли�та прокручивает��; цветовые подпи�и и чи�ла не обрезают��. +- Кажда� �трока — `heightIn(min = 64.dp)`, `SideDisc` 12 + 12 dp, цвет `bodyLarge`, точный �чёт �права `bodyMedium.merge(Tabular)`. Это `Role.Button`, не RadioButton и не `selected` segment. +- �икакой загрузки �тати�тики внутри ли�та: им� и �чётчики уже е�ть в `PlayerSummary`, по�тому его вы�ота не мен�ет�� по�ле по�влени�. +- Ка�ание цвета �разу вызывает �уще�твующий `onPrepare(player, white)` и закрывает ли�т. Кнопки «Открыть»/«Продолжить» нет. + +## 6. Со�то�ни� и крайние �лучаи + +| Со�то�ние | Требуемое поведение | +|---|---| +| Первое чтение | Верхн�� панель видна; в обла�ти �пи�ка текущий индикатор/«Читаю игроков…». �ули вме�то неизве�тных значений не показывают�� | +| Подгрузка �траниц | Заглушки � той же минимальной вы�отой 72 dp и теми же двум� тек�товыми лини�ми; разделители не и�чезают. Переход заглушка → обычна� одно�трочна� запи�ь не мен�ет шаг �пи�ка | +| Пои�к | Прежнее поведение и debounce �охран�ют��; ответ �тарого запро�а не показывает�� как новый. Одновременно � redesign об�зателен отдельный regression-фик� �нимка �пи�ка, а не новый `players!!` в �троке | +| �ет именованных игроков | Прежние «В �той базе нет именованных игроков» и «К парти�м» | +| �ичего не найдено | Прежние «Игрок не найден» и «Сбро�ить пои�к» | +| Ошибка | Прежние причина через `openProblem` и «Повторить»; ошибка не ма�кирует�� под пу�той �пи�ок или нулевые цвета | +| Оба цвета е�ть | Одна �трока «Выбрать цвет», затем ли�т � двум� дей�тви�ми | +| Только White или только Black | Оба �чётчика видны, включа� `0`; ка�ание �разу запу�кает един�твенный ненулевой цвет | +| �улевой цвет | Тек�т `… · 0` обычной secondary-кра�кой, без disabled-плашки и отдельного фоку�а. Цвет не �крывает�� и ме�та White/Black не мен�ют�� | +| Длинное им� | Дей�твует �уще�твующее `PlayerName`; �чётчики не наезжают. Полное им� озвучивает��, а на ли�те двух цветов также перено�ит�� визуально | +| 280/320 dp и font scale 1.3/2.0 | Цветовые группы перено��т��, �трока и ли�т ра�тут; названи� цветов и нули не обрезают��. �ет горизонтального �кролла и �егментов уже 48 dp | +| Сотни игроков | Сохранить `LazyColumn`, �траницы по 100, �табильный ключ `id` и фоновое чтение. Один semantic node на человека �окращает линейный TalkBack-обход. �е добавл�ть ради �того полную загрузку базы в пам�ть | +| Широкое окно/ландшафт | Та же одноколоночна� лента и тот же ли�т, не �етка и не на�тольные �толбцы | +| HiDPI | Только dp/sp, �уще�твующие векторные icons и `SideDisc`; новых ра�тровых ре�ур�ов нет | +| Возврат | Запро� и прокрутка прежние; ли�т закрыт, клавиатура �ама не по�вл�ет��, �трока не под�вечена как выбранна� | + +�лфавитный бы�трый бегунок, буквенные section headers и виртуальные �толбцы в �тот MVP не вход�т: пои�к уже решает о�новной �ценарий �отен имён без у�ложнени� же�тов. + +## 7. До�тупно�ть, клавиатура и фоку� + +### 7.1. TalkBack + +В�� �трока игрока — один `Role.Button`; дочерние тек�ты не �оздают �амо�то�тельные о�тановки. + +- Два цвета: **«Alekhine, Alexander, в�его 5 партий. Белыми 2, чёрными 3. Выбрать цвет»**. +- Один цвет: **«Anderssen, Adolf, в�его 2 партии. Белыми 2, чёрными 0. Подготовить�� белыми»**. +- Только Black формулирует�� �имметрично. �оль произно�ит�� �ловами/чи�лом, а не только затемнением. +- �а ли�те дей�тви�: **«Alekhine, Alexander, белыми, 2 партии. Подготовить��»** и аналогично дл� чёрных. + +При открытии ли�та фоку� переходит в него и один раз объ�вл�ет�� контек�т «выберите цвет». При закрытии без выбора фоку� возвращает�� на и�ходного игрока. По�ле возврата из подготовки фоку�/прокрутка по возможно�ти во��танавливают�� на том же `id`, без объ�влени� его «текущей позицией». Ошибка и пу�той результат объ�вл�ют�� один раз; подгрузка каждой �траницы не читает�� в�лух. + +### 7.2. �ппаратна� клавиатура и D-pad + +| Ввод | Дей�твие | +|---|---| +| Tab / Shift+Tab, D-pad | � → Search/поле пои�ка → �троки игроков → до�тупное дей�твие пу�того/ошибочного �о�то�ни�. �а ли�те: White → Black | +| Enter / Space / DPAD_CENTER | �ктивировать игрока или цвет один раз | +| IME Search | Скрыть клавиатуру, не запу�кать первого найденного игрока | +| Android Back / Esc | Закрыть ли�т; затем закрыть пои�к; затем покинуть Players | +| Буквы и �/→ вне тек�тового пол� | �е перехватывают�� глобально; и�пользуют�� �и�темной навигацией фоку�а | + +Видимый фоку� — рамка 2 dp `primary` вокруг в�ей �троки или дей�тви� ли�та. Hover-tooltip у �троки �оответ�твует будущему дей�твию: «Выбрать цвет» либо «Подготовить�� белыми/чёрными». Дополнительного �ен�орного long press не требует��. + +## 8. Требовани� разработчику + +1. Заменить в �пи�ке `PlayerPrepRow` � двум� `PlayerColorButton` на одну пло�кую actionable-�троку по §5. `PlayerSummary`, API �тати�тики и `onPrepare(player, white)` не мен�ют��; новых запро�ов ради ли�та нет. +2. Локальное �о�то�ние ли�та — только выбранный `PlayerSummary?`. У�ловие ли�та �трого `whiteGames > 0 && blackGames > 0`; при ровно одном ненулевом �чётчике вызывать `onPrepare` �разу. �е добавл�ть remembered color, �ортировку по ча�тоте или автоматиче�кий выбор большего репертуара. +3. �е и�пользовать `SingleChoiceSegmentedButtonRow` и `checked/selected` дл� навигационных дей�твий ли�та. �ужны две обычные �троки `Role.Button`, визуально близкие к �уще�твующему ли�ту подготовки из партии. +4. Переи�пользовать `ModalBottomSheet`, `SideDisc`, `PlayerName`, `Tabular`, `groupDigits`, plurals и текущие цвета темы. �овые цвета не вводить; в�е новые �троки/action labels переве�ти на дев�ть поддерживаемых �зыков. +5. Placeholder и обычна� запи�ь имеют одинаковую минимальную геометрию 72 dp. Разделитель ри�овать внутри �троки, не отдельным �лементом `LazyColumn`. +6. И�правление NPE при пои�ке о�таёт�� об�зательной отдельной ча�тью изменени�: LazyColumn должен работать � неизменным snapshot �траницы, без чтени� обнулённого `players!!`. �е �читать �мену UI-те�та доказатель�твом от�ут�тви� гонки. +7. Сохранить точную �тати�тику и по�транично�ть. Общий total не вычи�л�ть �уммой цветов; пу�тые/`?` имена и разные напи�ани� обрабатывать как раньше. +8. Compose-те�ты: два цвета → ли�т; только White/Black → пр�мой переход; нули видимы без disabled-дей�тви�; от�ут�твие выбора по большему count; одна активаци� при double tap; Back из ли�та/подготовки; �охранение query+scroll; полное semantics-опи�ание; перено� на 280 dp/font scale 2.0; placeholder → данные без �качка 72 dp. + +## 9. �езави�имой проверке по�ле реализации + +Реализацию принимает отдельный ревьюер, не автор макета и не автор кода. �ужны реальные запу�к и �нимки, а не только Compose Preview или чтение Kotlin. Сравнить главную/«Партии» и «Партию» той же �борки по фону, TopAppBar, типографике, пол�м и `SideDisc`. + +Минимальные доказатель�тва � учётом �кономии владельца: + +1. **Players, заполненный:** 1080×2400, 420 dpi, тёмна� тема; один человек � двум� ненулевыми цветами и минимум один � нулём. Проверить шаг 72 dp, пол� 16 dp, перено�ы, от�ут�твие карточек и disabled-плашек. +2. **Ли�т двух цветов:** тот же игрок и те же �чётчики; полное им�, White/Black, �троки ≥64 dp. Back возвращает к той же �троке без выбора. +3. **Един�твенный цвет:** ка�ание �разу открывает подготовку �тороной пользовател� вниз (противоположной �опернику); возврат �охран�ет query/scroll и не открывает ли�т. +4. **Переполнение:** длинное им� и font scale 2.0 либо 280/320 dp — отдельный целевой кадр, потому что зде�ь мен�ет�� wrapping. Чи�ла и �лова цветов не обрезаны, вы�ота ра�тёт только от перено�а тек�та. +5. **Пагинаци�/пои�к:** заглушка 72 dp → данные, ввод и очи�тка запро�а без crash и без выдачи �тарого результата за новый. Дл� �качков зафик�ировать координаты �о�едних �трок; не �оздавать лишнюю �ерию одинаковых кадров. + +Каждый �нимок подпи�ать файлом, px, density, ориентацией и �о�то�нием. Дефект запи�ывать как �кран/�о�то�ние, ожидаема� и фактиче�ка� геометри� или дей�твие, шаги во�произведени� и файл evidence. От�ут�твие прежнего `/tmp/opencode/prep48` не разрешает выдавать �тот документ за визуально доказанное «�тало лучше»: �то решение к реализации и по�ледующей приёмке. diff --git a/docs/design/android-review-button.md b/docs/design/android-review-button.md new file mode 100644 index 0000000..90f260d --- /dev/null +++ b/docs/design/android-review-button.md @@ -0,0 +1,215 @@ +# Задача 29. Android: «📈 �нализ» в нижней панели партии + +Дизайнер, 2026-11-28, ветка `feature/android-review-button`. Я мен�л только �тот документ; код не редактировал. + +**Стату� решени�:** �ценарий ниже — подтверждённое требование владельца, не вариант дл� выбора. Отдельные **� и � убрать**. **Ка�ание ◀/▶ — один ход, удержание ◀ — в начало, удержание ▶ — в конец.** «📈 �нализ» добавить �права в ту же нижнюю панель, цветом `!!`. Второй панели не будет, до�ка не уменьшает��. + +## 1. Задача �крана и пользователь�кий путь + +Главное на �кране — читать партию и переходить по ходам; разбор должен быть заметен �разу, но не отнимать ме�то у до�ки и не �мешивать�� � живым движком. + +Путь �тановит�� короче: + +- раньше: «Парти�» → `⋮` → «�нализ партии» → ли�т запу�ка; +- теперь: «Парти�» → **📈 �нализ** → тот же ли�т запу�ка → «�нализировать». + +По�ле разбора та же кнопка — **📈 Отчёт**: открывает �уще�твующий `ReviewSheet` и возвращает �крытую панель анализа. �лгоритм, к�ш, ли�т запу�ка, график, отчёт, о�тановка кре�тиком и пауза живого движка не мен�ют��. Пункт «�нализ партии / Отчёт по партии» убрать из `⋮`, чтобы не было двух одинаковых входов. О�тальные пункты меню и кнопка «Отчёт» внутри панели анализа о�тают��. + +Закрытие ли�та запу�ка или отчёта возвращает к той же позиции и прокрутке нотации. Си�темна� «�азад» по-прежнему �начала закрывает верхний ли�т, затем предпро�мотр PV, и только потом покидает партию. + +## 2. Что проверено в реальных материалах + +Про�мотрены изображени�, а не только имена файлов: + +- `docs/screenshots/android.jpg` — 1920×1080; +- `website/shots/raw/06-android.png` — 3840×2160; +- `website/shots/raw/phone/03-game.png`, `04-engine.png`, `08-review.png` — каждый 1080×2400, то е�ть �талонные 360×800 dp при density ×3; +- о�тальные телефонные �нимки `01-home.png`, `02-games.png`, `05-play.png`, `06-who.png`, `07-rodent.png`; +- �оответ�твующие материалы `designExample/`, включа� до�ку � анализом и панель вариантов. + +�а `03-game.png` панель вы�отой 72 dp �одержит ше�ть �лементов: движок, переворот, �, ◀, ▶, �. �а `04-engine.png` включённый движок обозначен �иним и подчёркиванием; �то �о�то�ние нельз� дублировать у разбора. �а `08-review.png` цвет `!!` уже и�пользует�� в �троке «!! Brilliant move» и в кружке на до�ке, а «Report» находит�� в �троке над графиком. + +Проверен код: + +- нижн�� панель — `GameScreen.kt:852–879`, вы�ота `72.dp`; до�ка в портрете — `fillMaxWidth()` (`1284–1290`), в альбомной ориентации — `fillMaxHeight()` (`1272–1282`); +- повтор ходов �ейча� в�троен в `BarButton` (`1642–1693`): шаг на нажатии, повтор через 400 м� каждые 120 м�. **Этот автоповтор дл� ◀/▶ отмен�ет�� новым требованием владельца**; +- �тарый вход в разбор и его у�лови� — `GameScreen.kt:1179–1200`; +- панель разбора и ли�ты — `ReviewViews.kt`; о�танавливать разбор новой нижней кнопкой не требует��: дл� �того уже е�ть ✕ в `ReviewPanel`; +- во врем� активной партии � компьютером и�пользует�� отдельный `PlayControls`; его �о�тав �той задачей не мен�ем. + +## 3. Об�зательна� компоновка + +### 3.1. Портрет, �талон 360 dp + +```text +┌────────────────────────────────────� +│ � Турнир · год ‹ › ⋮ │ +│ � Чёрные │ +│ │ +│ ДОСК� 360 × 360 │ без изменени� размера +│ │ +│ ○ Белые │ +│ [движок/разбор — только по state] │ +│ нотаци�, комментарии, варианты │ +├────────────────────────────────────┤ +│ ▣ ⇅ ◀ ▶ [📈]│ 72 dp, одна панель +│ Движок �нализ│ +└────────────────────────────────────┘ +``` + +Пор�док �лева направо фик�ирован: **Движок → Перевернуть → ◀ → ▶ → 📈 �нализ/Отчёт**. � и � не о�тают�� ни визуально, ни как невидимые кнопки. + +Размеры �лотов на 360 dp: + +| Движок | Перевернуть | ◀ | ▶ | �нализ | +|---:|---:|---:|---:|---:| +| 60 dp | 48 dp | 78 dp | 78 dp | 96 dp | + +Сумма — ровно 360 dp. В�е п�ть целей ка�ани� занимают полную вы�оту 72 dp; минимальна� ширина — 48 dp. ◀/▶ о�тают�� шире о�тальных навигационных кнопок, их значки — прежние 32 dp. + +�а 320 dp: **56 / 48 / 64 / 64 / 88 = 320 dp**. �иже 320 dp подпи�ь «�нализ/Отчёт» �крывает��, �лот разбора �ужает�� до 52 dp, иконка и полное опи�ание дл� TalkBack о�тают��; панель не прокручивает�� горизонтально и не перено�ит�� на вторую �троку. При ширине 280 dp ра�кладка: **52 / 48 / 64 / 64 / 52 = 280 dp**. + +В альбомной ориентации и�пользует�� та же �трока в правой колонке, вы�ота по-прежнему 72 dp. До�ка продолжает занимать полную до�тупную вы�оту. �икаких дополнительных карточек, отдельной плавающей кнопки или FAB над нотацией нет. + +### 3.2. Сам контрол разбора + +Он повтор�ет геометрию подпи�анной кнопки «Движок», чтобы базовые линии �овпадали: + +- зона нажати� — ве�ь закреплённый �лот × 72 dp; +- визуальный контейнер иконки — **36×36 dp**, значок **24 dp**; +- под иконкой — одна �трока `labelSmall` 12 sp/16 dp: «�нализ», «Отчёт» либо табличный �чётчик `N/M`; +- контейнер 36 dp и ширина �лота не мен�ют�� между �о�то�ни�ми; +- у разбора нет �инего подчёркивани� движка: �то дей�твие/переход к отчёту, не переключатель. + +Иконка — `Icons.Rounded.QueryStats`: график � лупой, близкий к на�тольному 📈 и отличный от `Memory` живого движка. �аличие `rounded/QueryStatsKt` проверено в уже подключённом `material-icons-extended-android:1.7.8`; новую графику и �торонние ре�ур�ы добавл�ть не нужно. + +## 4. �авигаци�: ка�ание и удержание + +| Контрол | Короткое ка�ание | Удержание | +|---|---|---| +| ◀ | Ровно один шаг назад, как текущий `back()` | Один переход в начало отображаемой линии | +| ▶ | Ровно один шаг вперёд, как текущий `forward()` | Один переход в конец отображаемой линии | + +Об�зательные детали: + +1. **Удержание не должно �начала делать один ход.** Короткий шаг выполн�ет�� при отпу�кании до �и�темного `longPressTimeout`; по до�тижении таймаута выполн�ет�� только переход к границе. Отпу�кание по�ле него не добавл�ет ещё один шаг. +2. �втоповтора 400/120 м� больше нет. Удержание �рабатывает один раз; движение/отмена ка�ани� — без дей�тви�. +3. Обычна� парти�: начало — узел `0`; конец — конец текущей ветки, как у �уще�твующего `end()`. +4. Предпро�мотр PV о�таёт�� отдельным контек�том: ка�ани� ли�тают шаги PV, удержани� идут к первому/по�леднему шагу PV. Выход из PV — прежние ✕, �и�темна� «�азад» или ка�ание до�ки; ка�ание ◀ до первого шага также выходит, как �ейча�. Партию предпро�мотр не измен�ет. +5. `canBack`/`canForward` одновременно управл�ют ка�анием и удержанием. �едо�тупные дей�тви� не и�чезают и не пере�тавл�ют �о�едние кнопки. +6. Дл� �тих двух кнопок нужен отдельный `combinedClickable`-контрол (или �квивалент � такой же �емантикой), а не прежний `BarButton(repeat = true)`. Переворот до�ки о�таёт�� на прежнем `BarButton`. + +## 5. Со�то�ни� кнопки разбора + +Дей�твие кнопки переи�пользует логику удал�емого пункта меню `1179–1200`; повторный разбор, �качивание движка и открытие �е��ии дл� новой/завершённой компьютерной партии не перепи�ывают��. + +| Со�то�ние | Вид в по�то�нном �лоте | Дей�твие и до�тупно�ть | +|---|---|---| +| Парти� загружает�� | �ейтральна� иконка, «�нализ» | �едо�тупна; �лот уже зан�т, по�ледующего �двига нет | +| �ет ходов | �ейтральна� иконка, «�нализ» | �едо�тупна; под�казка «В партии нет ходов дл� анализа» | +| Разбора нет, ходы е�ть | **Бирюзовый контейнер 36 dp**, тёмна�/бела� иконка по теме, подпи�ь «�нализ» | Открывает �уще�твующий ли�т запу�ка; разбор не начинает�� молча | +| Движок ещё не �качан | То же приглашающее �о�то�ние | Тот же ли�т запу�ка, затем �уще�твующий ли�т �качивани� | +| Движок готовит�� | Индетерминированное кольцо вокруг 📈, «�нализ» | �е даёт открыть дубликат потока; тек�т «Готовлю движок…» о�таёт�� в панели | +| Идёт первый разбор, данных дл� отчёта ещё нет | Детерминированное кольцо 📈, подпи�ь `N/M`, без �плошной заливки | �едо�тупна как дей�твие; прогре�� и ✕ «О�тановить» — в `ReviewPanel` | +| Идёт разбор, ча�тичный/прежний отчёт уже е�ть | Кольцо 📈, подпи�ь «Отчёт» | До�тупна: открывает отчёт, проце�� продолжает��; о�тановка только �уще�твующим ✕ | +| Разбор готов или загружен из к�ша/PGN | 📈 бирюзовым **без заливки**, подпи�ь «Отчёт» обычным `onSurface` | Открывает `ReviewSheet`, возвращает панель, е�ли она была �крыта | +| �нализ �крыт через «Скрыть анализ» | То же �о�то�ние «Отчёт» | `reviewHidden = false` и открытие отчёта; анализ не удал�ет�� | +| `stale`, `missing`, `secondsMissing`, ошибка | �ижн�� кнопка о�таёт�� «Отчёт», е�ли `hasData`; иначе обычна� «�нализ» | «Обновить», «Дополнить», «Продолжить» о�тают�� в панели; новых параллельных дей�твий нет | +| Идёт парти� � компьютером | Эта панель не показывает��, дей�твует `PlayControls` | �ичего не добавл�ть; по�ле завершени� до�тупен обычный �кран разбора | + +Прогре�� не должен озвучивать�� автоматиче�ки на каждое обновление: TalkBack читает `N/M` при фоку�е, иначе не�колько �отен объ�влений подр�д помешают навигации. + +## 6. Цвет и �уще�твующие �електоры + +### 6.1. И�точник цвета + +В Android уже е�ть единый �електор шахматных цветов `nagColor(nag, dark)` в `theme/Color.kt:57–79`; `judgementColor(BRILLIANT, dark)` вызывает его через NAG `$3` (`ReviewViews.kt:81–92`). И�пользовать его, **не дублировать новую кон�танту разбора в `GameScreen.kt`**. + +| Со�то�ние | Тёмна� тема | Светла� тема | +|---|---|---| +| Контейнер «�нализ» | `#26C2A3` — `nagColor(3, true)` | `#1A846F` — `nagColor(3, false)` | +| Иконка на контейнере | `#1B1B1B`, контра�т 7,65:1 | `#FFFFFF`, контра�т 4,59:1 | +| Hover при мыши | `#3FD3B4` / иконка `#1B1B1B` | `#157461` / бела� иконка | +| Pressed | `#1FA88D` / иконка `#1B1B1B` | `#10614F` / бела� иконка | +| «Отчёт» | Без заливки; 📈 `#26C2A3`, подпи�ь `onSurface` | Без заливки; 📈 `#1A846F`, подпи�ь `onSurface` | +| �едо�тупна | Без бирюзового: `onSurface` � alpha 0,38 | То же | + +Оттенки hover/pressed �овпадают � уже прин�тым на�тольным решением `docs/design/task-26-review-button-2026-11-27.md`. �а панели Android `surfaceContainer` контра�т �амой бирюзовой иконки — 6,89:1 в тёмной и 4,02:1 в �ветлой теме; дл� графики до�таточно 3:1. Подпи�ь в�егда `onSurface`, по�тому читаемо�ть 12 sp не зави�ит от бирюзового. + +В проекте нет XML `res/color*` или `selector`-ре�ур�ов дл� �тих кнопок: �о�то�ни� задают�� в Compose. �е �оздавать параллельный `ColorStateList`. Базовый цвет берёт�� из `nagColor`; производные оттенки, е�ли понадоб�т�� �вно, размещают�� одной функцией р�дом � ним. Обычный ripple нажати� �охран�ет�� поверх указанных цветов. + +Сплошна� заливка нужна только до первого разбора. По�ле него �ркое приглашение и�чезает, чтобы не �порить � до�кой, �иним текущим ходом (`#005C80`) и включённым движком. Со�то�ни� различают�� также тек�том, кольцом прогре��а и до�тупно�тью, не одним цветом. + +## 7. TalkBack, клавиатура и под�казки + +### 7.1. Семантика разбора + +- В�� обла�ть �лота — один `Role.Button`, без отдельно фоку�ируемых иконки и подпи�и. +- `contentDescription`: полное �уще�твующее `review_menu` («�нализ партии») или `review_report_menu` («Отчёт по партии»), а не короткое видимое «�нализ». +- Во врем� подготовки/разбора `stateDescription`: «Готовлю движок…» или �уще�твующий `review_progress` («�нализ партии · N из M»). +- �едо�тупное �о�то�ние вы�тавл�ет�� через `disabled()`/`enabled = false`; TalkBack должен �казать «неактивно», ка�ание ничего не запу�кает. +- Кнопка не `Switch` и не `toggleable`: открытый ли�т — не включённый режим. + +### 7.2. Семантика ◀/▶ и альтернатива удержанию + +Дл� ◀: + +- `contentDescription` — «Предыдущий ход»; +- `onClick` — один шаг; +- `onLongClick(label = "В начало линии")` — переход к началу; +- в `customActions` добавить **«В начало линии»**. + +Дл� ▶ — �имметрично: «Следующий ход», `onLongClick(label = "В конец линии")`, custom action **«В конец линии»**. + +Так переходы к границам до�тупны не только же�том: в TalkBack они е�ть в меню дей�твий �лемента. Двойное ка�ание выполн�ет один шаг; двойное ка�ание � удержанием — long click. �е полагать�� только на по�ледний же�т. + +Пор�док обхода TalkBack и D-pad: **Движок → Перевернуть → Предыдущий ход → Следующий ход → �нализ партии**. Enter/Space/DPAD_CENTER активирует короткое дей�твие. При фоку�е на ◀ клавиша Home повтор�ет «В начало линии», при фоку�е на ▶ End — «В конец линии»; глобальных буквенных �окращений не добавл�ть. Фоку� — видима� рамка 2 dp `primary` вокруг контейнера иконки, не только изменение tint. + +### 7.3. Видимые под�казки + +1. **📈:** `PlainTooltip` по hover и удержанию (у �той кнопки удержание не зан�то навигацией). Тек�т: «�нализ партии», «Отчёт по партии», «�нализ партии · N из M. О�тановка — кре�тиком над графиком» либо причина недо�тупно�ти. Tooltip обёртывает ве�ь �лот, по�тому работает и у визуально неактивной кнопки. +2. **◀/▶:** hover-tooltip «Предыдущий ход. Удержание — в начало линии» / «Следующий ход. Удержание — в конец линии». �а �ен�орном �кране долгое нажатие выполн�ет дей�твие, а не показывает tooltip. +3. Чтобы же�т был открываем без мыши и TalkBack, один раз на у�трой�тво показать �уще�твующий `SnackbarHost`: **«Ка�ание ◀ ▶ — один ход. Удержание — начало или конец линии.»** Показ — по�ле загрузки обычной партии, не во врем� активной игры � компьютером и не поверх открытого ли�та. Snackbar перекрывает панель временно, но не мен�ет размеры layout; повтор�ть при каждом открытии не нужно. Признак показа �охран�ет�� в на�тройках. +4. Дл� локализации добавить короткие `review_short` («�нализ» / «Analysis»), под�казки удержани� и одноразового Snackbar на в�е уже поддерживаемые �зыки. Полные названи� берут�� из �уще�твующих `review_menu`, `review_report_menu`, `review_progress`, `review_stop`. + +## 8. Матрица размеров и о�тальных �о�то�ний + +| Ситуаци� | Требуемое поведение | +|---|---| +| Пу�та�/нова� парти� | Кнопка видна, но неактивна; до�ка и о�тальные четыре контрола не двигают�� | +| Ошибка загрузки партии | �ейтральна� неактивна� «�нализ»; ошибка о�таёт�� �уще�твующим тек�том в обла�ти нотации | +| Больша� база | Разбор отно�ит�� к уже открытой партии; новых �пи�ков и работы на UI-потоке нет | +| �е�охранённые правки | Поведение �охранени� и ухода не мен�ет��; нижн�� кнопка и�пользует тот же путь, что прежний пункт меню | +| Запу�к → прогре�� → готово | Панель о�таёт�� 72 dp, �лот и контейнер 36 dp неизменны; мен�ют�� только иконка/кольцо и подпи�ь | +| По�вление к�ша при открытии | «�нализ» мен�ет�� на «Отчёт» внутри того же �лота без изменени� ширины и вы�оты | +| Живой движок включён | Кнопка движка о�таёт��; во врем� разбора его �трока показывает прежнюю паузу, затем �чёт продолжает�� | +| Крупный шрифт | В узком �лоте о�таёт�� только 📈; полное им� е�ть в TalkBack и tooltip. Тек�т не обрезает�� и не перено�ит панель | +| 320/280 dp | Ра�кладки из §3.1; п�ть целей не уже 48 dp, нет горизонтального �кролла | +| HiDPI | Vector-иконка и кольцо задают�� в dp; �талонные �нимки ×3 не должны показать обрезку или размытие | +| Смена темы | Мен�ет�� только палитра; размеры и позиции идентичны | + +По�вление �уще�твующей панели разбора 88 dp уменьшает только нотацию и прои�ходит по �вному запу�ку/открытию �охранённого анализа, как раньше. **Само �то изменение новой кнопки не добавл�ет ни одного dp по вертикали; до�ка в портрете о�таёт�� 360×360 dp, а в альбомной ориентации — на в�ю до�тупную вы�оту.** Завершение, о�тановка, возврат из фона и по�вление �тати�тики не должны вызывать �качков нижней панели. + +## 9. Требовани� разработчику + +1. В `GameScreen.kt` удалить два �лота `FirstPage`/`LastPage`, добавить `ReviewButton` �права и о�тавить вы�оту `Surface`/�троки без изменений. +2. Дл� ◀/▶ заменить repeat-контрол на tap/long-click � �емантикой §4 и §7. �е вызывать шаг на `down`, иначе удержание да�т лишний ход. +3. Выне�ти текущий обработчик пункта меню в один `onReview()` и вызывать его из новой кнопки; пункт меню удалить. �е заводить вторую реализацию открыти� �е��ии. +4. Базовый цвет получать через `judgementColor(MoveJudgement.BRILLIANT, dark)` или `nagColor(3, dark)`. �е и�пользовать `MaterialTheme.colorScheme.primary`: �иний зарезервирован за движком и текущей позицией. +5. Ширину �лота не вычи�л�ть от тек�та «�нализ»/`N/M`/«Отчёт». Счётчик — `labelSmall.merge(Tabular)`, одна �трока. +6. Со�то�ни� и нажати� не должны мен�ть `review`, кроме �уще�твующего пути запу�ка/открыти� отчёта. О�тановка о�таёт�� только в `ReviewPanel`. +7. Добавить/обновить Compose-те�ты �емантики: один click, long click без предварительного click, custom actions, disabled, content/state descriptions и по�то�нные размеры �лотов. + +## 10. Что передать незави�имому ревьюеру и те�тировщику + +Ревьюер — не автор реализации; провер�ть реальное приложение на �мул�торе/у�трой�тве и �нимки, не только Kotlin-код. + +1. **Сравнение 360×800 dp, density ×3:** `03-game`, `04-engine`, `08-review` до/по�ле. До�ка и верх панели �овпадают по координатам; нижн�� панель о�таёт�� 72 dp. Со�то�ни�: нет разбора, идёт первый разбор, готово/«Отчёт», включён живой движок. +2. **Сери� без �качков:** «�нализ» → ли�т запу�ка → `N/M` → «Отчёт» → �крыть анализ → вернуть через нижнюю кнопку. Зафик�ировать координаты до�ки, верха нотации и в�ех п�ти �лотов на каждом �нимке. +3. **Же�ты:** 20 коротких ка�аний дают ровно 20 ходов; удержание ◀/▶ — один переход к границе без предварительного шага и без автоповтора. Проверить вариант и PV, выход из PV прежними �по�обами. +4. **До�тупно�ть:** TalkBack озвучивает полные названи�, прогре�� только по запро�у фоку�а, disabled; custom actions «В начало/конец линии» работают без удержани�. Проверить одноразовый Snackbar и tooltip разбора. +5. **Узкое и крупное:** 320 dp и 280 dp, крупный шрифт: п�ть кнопок видны, цели ≥48 dp, тек�т не обрезан, второй �троки нет. +6. **Цвет:** пик�ельна� �верка контейнера � `nagColor(3, dark)` и �трокой «!! Brilliant move» на `08-review`-�о�то�нии. В �ветлой теме — `#1A846F`, бела� иконка. «Отчёт» не �охран�ет �плошную заливку. +7. **Регре��ии:** живой движок �тавит�� на паузу и возобновл�ет��; о�тановка разбора �уще�твующим ✕; поворот и возврат из фона продолжают разбор; активна� игра � компьютером и�пользует прежний `PlayControls`. + +Вердикт визуальной приёмки должен ��ылать�� на файлы �нимков, размер/плотно�ть и �о�то�ние каждого. Общего «панель выгл�дит так же» без доказатель�тв недо�таточно. diff --git a/docs/design/android-rodent.md b/docs/design/android-rodent.md new file mode 100644 index 0000000..6d9485a --- /dev/null +++ b/docs/design/android-rodent.md @@ -0,0 +1,474 @@ +# Rodent IV на телефоне: выбор �оперника и его характера + +Стату�: проект дизайнера, 2026-10-27, **дл� �огла�овани�**. Продолжает `android-play.md` §31 (игра � Maia) и `android-lists.md` §5.4–5.5; �талон 360×800 dp, размеры — dp, тек�т — sp (`android-ui.md` §0). �а�тольный образец — `rodent-opponent.md` и нынешний `Dialog::show` в `apps/desktop/src/play.rs` (�пи�ок `STYLES`, переводы в `apps/desktop/src/i18n.rs`). И��ледование — `docs/research/rodent.md`. + +**Что мен�ет�� в решени�х.** `docs/decisions.md`, «Rodent IV: его пер�онажи…», п. 3: «�а телефоне — только Maia (игра) и Stockfish (анализ)». Владелец 2026-10-27 �то мен�ет: «хочу чтобы в мобилке мы в�е же внедрили 4 вер�ию движка где у на� куча режимов, и при �тарте игры показывали какой движок мы хотим выбрать (май� 5м или же �тот движок 4 вер�ии) и е�ли его, то чтобы был выбор его режимов». �а телефоне �оперников в игре два — **Maia** и **Rodent IV**; анализ по-прежнему только Stockfish. Rodent V на телефон не идёт: у него нет �борки под ARM (`research/rodent.md` §5). Запи�ь в `decisions.md` делает орке�тратор. + +Техниче�кие у�лови� (у�тановил орке�тратор): и�полн�емый Rodent IV �обирает�� NDK и лежит в APK, как `libstockfish.so`, в обеих �борках (полной и лёгкой), около 1 МБ на ABI. Скачанный файл Android запу�кать не даёт, по�тому �ам движок не �качивает��. Файлы характеров (`personalities/*.txt`, 109 КБ) тоже лежат в APK. Скачивают�� только дебютные книги. + +## 0. Коротко + +1. Кнопка «Играть» на «Базах» открывает тот же ли�т «Игра � компьютером». **�овое — вверху ли�та:** две карточки �оперника, «Maia» и «Rodent IV», а под ними �трока характера. Дл� Rodent в �троке выбранный характер («Таль»), ка�ание открывает �кран выбора «С кем играть». Дл� Maia �трока неактивна: «Как человек». +2. **Характер выбирает�� на полно�кранном �пи�ке.** Там 35 �трок в двух группах: «Великие шахмати�ты» (22) и «Характеры» (13). У каждой �троки буквица, им� и опи�ание � компьютера. Выбор одним ка�анием �разу возвращает к ли�ту. +3. **Сила у каждого движка �во� и запоминает�� отдельно.** У Maia шкала 600–2600, у Rodent IV — 800–2800. При �мене �оперника ползунок в�таёт на по�леднее значение �того движка, подпи�и концов и по��нение мен�ют��. +4. **Дебютные книги Rodent IV �качивают�� одним пакетом, один раз** (решение владельца 2026-10-27, §5). Кнопка та же, что у Maia: «Скачать и играть». Движок в APK играет и без книг, по�тому без �ети или при отказе от загрузки можно «Без книги». +5. **Ли�т не прыгает.** Карточки, �трока характера, по��нение под ползунком и �трока �о�то�ни� — фик�ированной вы�оты. Строка �о�то�ни� и кнопка «Играть» закреплены внизу ли�та, о�тальное прокручивает��. +6. В партии на плашке и в заголовке: «Rodent IV 1800 · Таль». В PGN, как на компьютере: `Rodent IV 1800 (Tal)`. Отложенную партию � Rodent можно продолжить, как партию � Maia. + +## 1. Пути пользовател� + +### 1.1. Первый раз (ничего не �качано, Rodent ни разу не выбирали) + +1. «Базы» → «Играть». Ли�т: выбрана карточка **Maia** (как �ейча�, вопро� 1). Строка характера неактивна: «Как человек · Maia не выбирает �тиль…». Ползунок показывает «Сила: 1500» (600–2600). Внизу: «Maia �качивает�� один раз (21 МБ…)» и «Скачать и играть». +2. Пользователь ка�ает�� карточки **Rodent IV**. Карточка выбрана, ползунок переходит на шкалу Rodent (800–2800, «Сила: 1500»). Так как характер ещё ни разу не выбирали, **�разу открывает�� «С кем играть»** (только �тот раз, §3.4). Спи�ок прокручен к предложенному «Талю», он отмечен. +3. Ка�ание «Карпов» возвращает на ли�т. В �троке характера «Карпов — Позиционное давление, профилактика и техника.» Внизу: «Дебютные книги Rodent IV · 59 МБ, �качивают�� один раз � github.com (файлы авторов)», «Скачать и играть», �права в �троке — «Без книги». +4. «Скачать и играть»: поло�а «12 из 59 МБ» � ✕, затем «Проверка…». Когда в�ё проверено, парти� начинает�� �ама, е�ли ли�т ещё открыт и выбран Rodent (характер можно было �менить — книги общие). По�ле �того книги е�ть у в�ех 35 характеров; больше Rodent ничего не качает. +5. Е�ли пользователь закрыл «С кем играть» «назад» без выбора, о�таёт�� предложенный Таль. Выбор не об�зателен, но �пи�ок он увидел. + +### 1.2. Возвращает�� + +- Ли�т открывает�� � по�ледним выбором: �оперник, характер, �ила �того �оперника, цвет, им�. Книги уже е�ть: «Играть» — одно ка�ание, как �ейча� � Maia. +- Отложенна� парти� е�ть — �начала прежний вопро� `AdjournedQuestion` («Е�ть отложенна� парти� � Rodent IV 1800»), §6.5. + +### 1.3. Сменить �оперника или характер + +- Ка�ание другой карточки мен�ет �оперника, �илу (�во� у каждого, §4) и �троку �о�то�ни�. Характер Rodent при переходе на Maia не тер�ет��, при возврате он �нова в �троке. Повторно �кран выбора �ам не открывает��. +- Сменить характер: ка�ание �троки характера → «С кем играть» → ка�ание имени. Сила при �мене характера не мен�ет��: шкала у в�ех характеров одна (UCI_Elo). +- Сменить характер, пока Maia выбрана, нельз�: �трока неактивна. Сначала карточка Rodent IV. Так же у�троено на компьютере, где комбо �тил� выключено у Maia. + +### 1.4. Скачивани� + +| Ситуаци� | Что видит пользователь | +|---|---| +| Выбрана Maia, её нет | как �ейча� (§31.2): «Maia �качивает�� один раз…», «Скачать и играть» | +| Выбран Rodent, книг нет | «Дебютные книги Rodent IV · 59 МБ…» + «Без книги»; кнопка «Скачать и играть» | +| Выбран Rodent, книги е�ть, а Maia не �качана | «Играть»; о Maia ни �лова: �трока �о�то�ни� отно�ит�� только к выбранному �опернику (как на компьютере, `rodent-opponent.md` §6) | +| �ет ни Maia, ни книг | показано то, что нужно выбранному �опернику; другой не упоминает�� | +| Идёт загрузка, пользователь переключил �оперника на готового | «Играть» активна; загрузка продолжает�� в фоне (уведомление `DownloadManager`, как у Maia); парти� по окончании �ама не начнёт�� | +| Идёт загрузка книг, пользователь мен�ет характер | ничего не мен�ет��: книги общие, загрузка идёт, по окончании парти� начнёт�� � новым характером | +| ✕ во врем� загрузки | загрузка о�танавливает��. Скачанные и проверенные файлы пакета о�тают��, при �ледующем «Скачать и играть» докачивает�� о�таток; размер в �троке — о�таток | +| �ет �ети / обрыв / нет ме�та / файл не тот | кра�на� �трока, прежние тек�ты `no_internet`, `interrupted`, `no_space` (нужно 59 МБ), `corrupt`; кнопка «Повторить», �права «Без книги» (§5.5) | +| Закрыли ли�т во врем� загрузки | загрузка продолжает�� в фоне � уведомлением; парти� не начинает�� (как у Maia) | + +### 1.5. Играть � позиции (§31.6) + +Ли�т тот же, � блоком позиции вверху; �оперник и характер — по�ледние. **Книги � позиции не требуют��.** Е�ли книг нет, �трока �о�то�ни�: «С позиции дебютна� книга не нужна — Rodent IV играет �разу», кнопка «Играть» (вопро� 4). Е�ли книги е�ть, движок ими пользует��. За�тавл�ть качать 59 МБ ради позиции из �ередины партии, где книга почти никогда не �рабатывает, не �тоит. + +### 1.6. Реванш + +Тот же �оперник, характер и �ила; цвета мен�ют�� (§31.4). Книги уже �качаны, так что начинает�� �разу. Е�ли книги удалили в на�тройках между парти�ми, реванш открывает ли�т (как «�ова� игра»), а не �тартует молча � загрузкой. + +### 1.7. Отложенна� парти� � Rodent + +«�азад» откладывает партию � Rodent так же, как � Maia (§31.7). Карточка на «Базах»: «Парти� � Rodent IV 1800», втора� �трока — «Таль · вы белыми · 6-й ход». «Продолжить» поднимает Rodent IV � тем же характером и �илой. **Книги дл� продолжени� не требуют��**: е�ли их удалили, парти� продолжает�� без книги, без вопро�ов (к �ередине партии книга обычно уже не нужна). + +### 1.8. В партии + +Плашка �оперника: «Rodent IV 1800 · Таль». Заголовок: «Парти� � Rodent IV 1800», под ним «Таль · вы белыми · без ча�ов». �ичь�, �дача, «Ход назад», про�мотр и конец партии — как � Maia (§31.3–31.4), � тек�тами дл� Rodent (§9). + +## 2. Ли�т «Игра � компьютером» + +### 2.1. Компоновка (360×800, портрет) + +``` +┌────────────────────────────────────� +│ ─── │ ручка 22 +│ Игра � компьютером │ 22sp titleLarge +│ ┌──────� По�ле 14…Ке7 │ только «Играть от�юда», +│ │до�ка │ из партии Карл�ен — Каруана│ мини-до�ка 96 dp (как �ейча�) +│ └──────┘ │ +│ ┌───────────────�┌───────────────� │ +│ │✓ Maia ││ Rodent IV │ │ 64 две карточки по 152, зазор 8 +│ │играет как ││�ильный, �о │ │ им� titleSmall 500, +│ │человек ││�тилем │ │ подпи�ь bodySmall, 2 �троки +│ └───────────────┘└───────────────┘ │ +│ ┌────────────────────────────────� │ +│ │(Т) Таль › │ │ 80 �трока характера (§2.3) +│ │ Риж�кий волшебник: жертвы │ │ опи�ание bodyMedium, ≤ 2 �трок +│ │ и атака. │ │ +│ └────────────────────────────────┘ │ +│ Сила: 1800 │ 24 titleMedium 500, Tabular +│ 800 ������������������������ 2800 │ 48 Slider, шаг 50 +│ Соб�твенный рейтинг Rodent │ 32 12sp onSurfaceVariant, +│ (UCI_Elo): он не равен Эло человека│ в�егда 2 �троки (minLines 2) +│ Цвет │ 20 +│ [ Белыми ][▌Случайно�][ Чёрными ] │ 48 +│ ┌ Ваше им� ────────────────── ▾ � │ 56 как �ейча� (player-games.md §6) +│ └───────────────────────────────┘ │ +│ В «Роман — партии � компьютером» … │ 20 +╞������������������������������������╡ � граница прокрутки (тень при прокрутке) +│ Дебютные книги Rodent IV · 59 МБ, │ 40 �трока �о�то�ни�, 2 �троки 12sp; +│ один раз � github.com [Без книги]│ �права TextButton 48 + +│ ┌────────────────────────────────� │ +│ │ Скачать и играть │ │ 56 Button на в�ю ширину +│ └────────────────────────────────┘ │ +└────────────────────────────────────┘ +``` + +- **Вы�ота без позиции** ≈ 22 + 44 + 64 + 8 + 80 + 8 + 24 + 48 + 32 + 16 + 76 + 12 + 76 = 510 dp прокручиваемой ча�ти и 128 dp подвала (�трока 40, зазор 8, кнопка 56, поле 24). Итого ≈ 640 dp плю� �и�темна� панель — помещает�� в 800 без прокрутки. С блоком позиции (+108) — ≈ 750, на маленьких �кранах прокручивает��. +- **Подвал закреплён** (новое по �равнению � §31.1): �трока �о�то�ни� и кнопка вне `verticalScroll`, под ними `navigationBarsPadding`, над ними `imePadding`. Когда клавиатура открыта (поле имени), подвал �тоит над ней. Пока ча�ть �одержимого �крыта под подвалом, над ним тень `Elevation 2`/лини� `outlineVariant` 1 dp. Без �того при новых 150 dp кнопка «Играть» уходила бы под край на маленьком телефоне � позицией. +- **Пор�док блоков:** �оперник → характер → �ила → цвет → им�. Сначала *кто*, потом *на�колько �ильный*: шкала �илы зави�ит от �оперника. +- Заголовок ли�та — нынешн�� �трока `play_title` («Игра � компьютером»). Прежний заголовок �екции «Соперник — Maia 1500» убирает��: �оперник виден на карточках, �ила — в «Сила: 1800». Это возвращает �троку, которую берёт �трока характера. + +### 2.2. Карточки �оперника + +- Две `OutlinedCard`, кажда� � `Modifier.selectable(role = RadioButton)` в общей `selectableGroup`. Размер 152×64 (ве� 1, зазор 8), �кругление 12, пол� 12. +- **Выбранна�:** заливка `secondaryContainer`, рамка 2 dp `primary`, �лева от имени значок `check` 18 dp. **�евыбранна�:** заливка `surface`, рамка 1 dp `outlineVariant`. Значок � галочкой нужен, чтобы выбор был виден не только цветом. +- Строки — переводы � компьютера: им� (`Maia`, `Rodent IV` — не перевод�т��) и подпи�ь «играет как человек» / «�ильный, �о �тилем» (`plays like a human` / `strong, with a style`), не больше 2 �трок, затем «…». +- Ка�ание мен�ет �оперника; �ила, концы ползунка, �трока характера и �трока �о�то�ни� обновл�ют�� �разу, без анимации вы�оты. Вы�ота ли�та не мен�ет��. +- Rodent IV в APK в�егда е�ть, по�тому неактивного �о�то�ни� карточки нет. Е�ли движок не запу�тил�� на �том у�трой�тве, �м. §6.6. + +### 2.3. Строка характера + +Одна и та же �трока 80 dp при обоих �оперниках, мен�ет�� только �одержимое: + +| | Rodent IV | Maia | +|---|---|---| +| �лева | буквица 40 dp (§3.2) | значок `person` 24 dp в круге 40 dp `surfaceContainerHighest` | +| перва� �трока | им� характера («Таль», «Удав»), bodyLarge 500 | «Как человек» (`Like a human`) | +| втора� | опи�ание (`about` � компьютера), bodyMedium `onSurfaceVariant`, ≤ 2 �трок | «Maia не выбирает �тиль: она играет, как люди её рейтинга.» | +| �права | `chevron_right` | ничего | +| ка�ание | открывает «С кем играть» (§3) | нет; в�� �трока цвета `onSurface` 0,38 | +| фон | `surfaceContainerHigh`, �кругление 12 | тот же, неактивный | + +- Почему �трока е�ть и у Maia: вы�ота ли�та не мен�ет�� при �мене �оперника. Кроме того, неактивна� �трока под�казывает, что �тиль — �вой�тво Rodent (на компьютере так же). +- Почему не выпадающий �пи�ок, как на компьютере: 35 пунктов � опи�ани�ми в `ExposedDropdownMenu` — �то узкое меню на 4 �крана вы�оты без заголовков групп и без размеров книг. Полно�кранный �пи�ок читает�� лучше и даёт ме�то под опи�ание. + +### 2.4. Строка �о�то�ни� и кнопка (подвал) + +Вы�ота �троки в�егда 40 dp (2 �троки 12sp), кнопка в�егда 56 dp. Содержимое — только о выбранном �опернике. Дл� Maia в�ё по `android-play.md` §31.2 без изменений. Дл� Rodent: + +| Со�то�ние | Строка (`bodySmall`) | Кнопка | +|---|---|---| +| книги е�ть | «Rodent IV и его дебютные книги на телефоне» `onSurfaceVariant` | «Играть» | +| книг нет | «Дебютные книги Rodent IV · {n} МБ, �качивают�� один раз � github.com (файлы авторов)»; �права `TextButton` «Без книги» | «Скачать и играть» | +| книг нет, игра � позиции | «С позиции дебютна� книга не нужна — Rodent IV играет �разу» | «Играть» | +| загрузка | `LinearProgressIndicator` + «{a} из {b} МБ» + ✕ 48 dp (`cancel_download`) | «Играть», неактивна | +| проверка | «Проверка…» | неактивна | +| ошибка | `error`: `no_internet` / `interrupted` / `no_space` / `corrupt`; �права «Без книги» | «Повторить» | + +- `{n}` — �колько **о�тало�ь** �качать (по�ле ✕ или обрыва — о�таток), целым � округлением вверх, как �ейча� `megabytes()`. +- Тек�т �троки при «книг нет» обрезает�� �права кнопкой «Без книги» (≈ 96 dp): �трока 2 �троки по ≈ 230 dp — укладывает�� на ру��ком и англий�ком; на длинных �зыках — «…», полный тек�т в TalkBack. +- «Скачать и играть»: парти� начнёт�� �ама по�ле проверки, е�ли ли�т открыт и выбран Rodent (иначе флаг `playAfter` �бра�ывает�� — правило компьютера, `rodent-opponent.md` §6). Смена характера флаг не �бра�ывает: книги общие. + +## 3. Экран «С кем играть» + +### 3.1. Компоновка + +Полно�кранный `Dialog` (`usePlatformDefaultWidth = false`) поверх ли�та, как форма «Данные партии» (§30.5). Ли�т под ним о�таёт�� открытым. + +``` +┌────────────────────────────────────� +│ � С кем играть │ 64 TopAppBar +├────────────────────────────────────┤ +│ Характер — �то �тиль и дебюты, │ 14sp onSurfaceVariant, пол� 16 +│ �илу задаёт ползунок. │ +│ Великие шахмати�ты │ 48 заголовок группы, прилипает +│ (�) �лехин │ 72+ ListItem +│ Динамичные атаки и глубокие │ +│ комбинации. │ +│ (�) �нанд │ +│ Бы�тра�, универ�альна� игра… │ +│ … │ +│▌(Т) Таль ✓ �│ выбранный: фон secondaryContainer +│ Риж�кий волшебник: жертвы… │ +│ … │ +│ Характеры │ 48 +│ (�) �манда │ +│ Сначала атакует, потом… │ +│ … │ +└────────────────────────────────────┘ +``` + +- **Группы и пор�док.** Первыми «Великие шахмати�ты» (22), затем «Характеры» (13). Имена шахмати�тов — главное, ради чего �тавит�� Rodent IV («Таль», «Карпов»). Внутри группы — по алфавиту переведённых имён (на компьютере игроки упор�дочены так же). Заголовки групп — `titleSmall` `primary`, `stickyHeader`. +- **Строка** — `ListItem` не ниже 72 dp: буквица �лева (§3.2), им� (`bodyLarge`), опи�ание (`bodyMedium` `onSurfaceVariant`, без ограничени� �трок — зде�ь как раз ме�то прочитать его целиком). Выбранна� �трока: фон `secondaryContainer`, �права `check`. Размеров и отметок «�качано» в �троках нет: книги одним пакетом, их �о�то�ние — в подвале ли�та. +- **Ка�ание �троки** выбирает и �разу закрывает �кран (�пи�ок одиночного выбора, M3 «simple dialog»). � и �и�темный «назад» закрывают без изменений. Кнопок «Готово» и «Отмена» нет. +- **Открывает�� прокрученным** так, чтобы выбранна� �трока была видна (третьей �верху, как отмеченна� парти� в �пи�ке, `android-lists.md` §10). +- **Пои�ка нет.** 35 �трок в двух группах, около 4 �кранов. �лфавит и заголовки наход�т «Карпова» бы�трее, чем клавиатура. Е�ли �пи�ок выра�тет за 60, вернуть�� к пои�ку. +- Без �ети и без книг �кран не мен�ет��: выбор характера к �ети не отно�ит��. + +### 3.2. Буквица + +Круг 40 dp � первой буквой переведённого имени (`titleMedium` 500). Цвет по группе: шахмати�ты — `tertiaryContainer` / `onTertiaryContainer`, характеры — `secondaryContainer` / `onSecondaryContainer`. Портретов нет: у портретов чемпионов разные и ча�то не��ные лицензии, а ри�овать «похожих» — хуже, чем букву. TalkBack буквицу не читает (декораци�). + +### 3.3. Спи�ок характеров + +Ровно 35 характеров компьютерного �пи�ка `STYLES` � `rodent: Gen::IV` (id `iv_*`, им� дл� PGN, название и опи�ание � переводами на 9 �зыков). Ampere и Swapper из `basic.ini` на компьютере не показаны (Ampere е�ть у V), на телефоне их тоже нет. �азвани� и опи�ани� берут�� � компьютера, новых не придумывает��. Един�твенное отличие: «Таль (кла��ика)» на телефоне — про�то «Таль» (ключ `Tal` в `i18n.rs` уже переведён), потому что второго Тал� (V) зде�ь нет. Размеры — в приложении A. + +### 3.4. Первое открытие + +Первое ка�ание карточки Rodent IV, пока `rodentPersonality` в на�тройках не запи�ан, �амо открывает «С кем играть». Предложен и отмечен «Таль»: �амое изве�тное им� (вопро� 2). Больше �кран �ам не открывает�� никогда, даже е�ли пользователь закрыл его без выбора (тогда запи�ывает�� Таль). + +## 4. Сила: две шкалы + +- **У каждого движка �во� пам�ть �илы:** `maiaStrength` (е�ть) и `rodentStrength` (новое, впервые 1500). При переключении карточки ползунок в�таёт на �охранённое значение �того движка. Так переход Maia ↔ Rodent ничего не портит: 2600 у Maia не обрезает�� до 2800 → 2600 при возврате и т. п. �а компьютере �ила одна, �о �двигом в диапазон (вопро� 5). +- **Диапазоны** — за�вленные авторами (`decisions.md` «Сила �оперника — по шкале �амого движка»): Maia 600–2600 (`maia_range()`), Rodent IV 800–2800 (`RODENT_MIN`, `RODENT_IV_MAX` в `play.rs`, их нужно выне�ти в общий крейт `play`). Шаг 50, ри�ок нет. Концы подпи�аны чи�лами �лева и �права (как �ейча�). +- **Заголовок** «Сила: {elo}» (`Strength:` � компьютера + чи�ло), `Tabular`, мен�ет�� при движении. +- **По��нение под ползунком** — в�егда 2 �троки, �троки компьютера: Maia — «Соб�твенный рейтинг Maia: он не равен Эло человека.» (уже е�ть, `play_measured`); Rodent — «Соб�твенный рейтинг Rodent (UCI_Elo): он не равен Эло человека.». Именно оно объ��н�ет, почему у �о�едних карточек разные чи�ла и почему Rodent 1500 ≠ Maia 1500. +- 2800 у Rodent IV — полна� �ила (без `UCI_LimitStrength`), как на компьютере. Подпи�ь конца — «2800», не «мак�.». +- Сила не зави�ит от характера (`UCI_Elo` и `Personality` разведены). Таль 1200 — �то �лабый игрок в �тиле Тал�; �то �казано вводной фразой �крана «С кем играть». + +## 5. Книги Rodent: один пакет + +### 5.1. Решение владельца (2026-10-27) + +Дебютные книги Rodent IV �качивают�� **одним пакетом, один раз** (как на компьютере, где Rodent IV качает�� целиком), а не по характеру. По�ле загрузки в�е 35 характеров играют �о �воими дебютами без �ети. Вариант «книги каждого характера при первой партии � ним» ра��мотрен и отклонён. + +### 5.2. Факты дл� пакета + +- Каталог `books/` авторов на зафик�ированном коммите — **69,3 МБ**, но **35 характеров и�пользуют 59,0 МБ**. 10,3 МБ не нужны никому (`guide/ph-exoticbook.bin` 9,4 МБ, `main/*`, `flank`, `tricky`…). Ра�чёт — `apps/desktop/src/rodent4_files.rs` и `GuideBookFile`/`MainBookFile` из `personalities/*.txt` на коммите `e8d84c8`; по характерам — приложение A. **Рекомендаци� разработчику:** в пакет брать только и�пользуемые книги (59 МБ). Е�ли проще вз�ть общий � компьютером манифе�т целиком — 69 МБ; тек�ты берут размер из манифе�та, по�тому от выбора не зави��т. +- Три характера ��ылают�� на им� книги, которого в репозитории нет: Удав — `guide/strangler.bin` (в репозитории `Strangler.bin`; на Android файлова� �и�тема различает реги�тр), Спа��кий — `ph_spassky2.bin` (в репозитории через дефи�), Дебора — `guide/guide.bin` (в репозитории `books/guide.bin`). �а компьютере �то решено копией под нужным именем (`BOOK_NAMES` в `apps/desktop/src/rodent4_download.rs`). Телефону нужно то же �амое, из общего кода. +- И�точник — `raw.githubusercontent.com/nescitus/rodent-iv/<коммит>/books/…`, каждый файл � проверкой SHA-256 из общего � компьютером манифе�та. Подпи�ь «� github.com (файлы авторов)», как у Maia «� huggingface.co (файл авторов)». +- Лицензии ча�ти книг (Hase `ph-*`, Robinson `rj-*`) не уточнены (`research/rodent.md` §5, его вопро� 5). Программа �качивает их по кнопке из репозитори� авторов, как на компьютере, а не раздаёт �ама. По�тому книги — не в APK (кроме того, APK выро� бы на 59 МБ, и лёгка� �борка потер�ла бы �мы�л). + +### 5.3. Где предлагает�� загрузка + +1. **�а ли�те**, когда выбран Rodent и книг нет: �трока «Дебютные книги Rodent IV · 59 МБ…», кнопка «Скачать и играть», �права «Без книги» (§2.4). Путь тот же, что у Maia: по�ле проверки парти� начинает�� �ама. +2. **В «�а�тройки → Движок»**: �трока «Rodent IV — дебютные книги» � «Скачать» / «Удалить» (§7.2). + +Подтверждени� перед загрузкой на мобильной �ети нет (у Maia его тоже нет): размер напи�ан в �троке, а кнопка — �вное дей�твие. + +### 5.4. Как идёт загрузка + +- Тот же механизм, что у Maia (`CheckedDownload`/`DownloadManager` в `filesDir`): одна поло�а на ве�ь пакет (�умма байт), «{a} из {b} МБ», затем «Проверка…». Закрытие ли�та загрузку не отмен�ет — она идёт в фоне � уведомлением (заголовок «Дебютные книги Rodent IV»). Отмен�ет только ✕. +- **Докачка.** Пакет — около 50 файлов, каждый провер�ет�� отдельно. По�ле ✕, обрыва или нехватки ме�та проверенные файлы о�тают��, «Повторить» докачивает о�таток, а �трока показывает о�таток. Пакет �читает�� готовым, только когда на ме�те в�е файлы: ча�тично �качанный пакет дл� игры — как «книг нет». +- **�ет ме�та:** «Мало ме�та: нужно {n} МБ, �вободно {m} МБ» (�уще�твующа� `no_space`). + +### 5.5. «Без книги» + +`TextButton` «Без книги» �права в �троке �о�то�ни�: при «книг нет» и при любой ошибке загрузки. Парти� начинает�� без дебютной книги: движок, характер и �ила те же. �ад нотацией ничего не пишет��. В PGN им� то же (`Rodent IV 1800 (Tal)`): книга — дебютный репертуар �оперника, а не он �ам. Без книги шахмати�ты тер�ют �вои дебюты (`research/rodent.md` §4), по�тому кнопка второ�тепенна� (тек�това�), а главна� — «Скачать и играть». Это �вный выбор пользовател�, а не молчалива� подмена, по�тому правило «без обходных путей» не нарушает�� (вопро� 3). �ужна она затем, чтобы в �амолёте и на дорогом трафике Rodent IV — един�твенный �оперник, который не требует �ети, — в�ё же играл. У Maia такой кнопки нет: без файла Maia не играет вов�е. + +Сделанный выбор «Без книги» не запоминает��: в �ледующий раз ли�т �нова предлагает �качать. + +## 6. В партии + +### 6.1. Экран игры + +Как §31.3. Мен�ют�� только имена: + +``` +│ � Парти� � Rodent IV 1800 │ 64 titleLarge +│ Таль · вы белыми · без ча�ов │ bodyMedium +├────────────────────────────────────┤ +│ � Rodent IV 1800 · Таль ◌ думает… │ 36 плашка �оперника +``` + +- **Заголовок:** «Парти� � {�оперник}», где {�оперник} = «Maia 1500» / «Rodent IV 1800» (�трока `play_adjourned_title`, котора� уже е�ть, — один и тот же шаблон дл� карточки, вопро�а и заголовка). Втора� �трока — «{характер} · вы белыми · без ча�ов»; у Maia, как �ейча�, без характера. + - Сейча� заголовок у Maia — «Играть � Maia 1500» (`play_with_maia` + �ила). Предлагаю у обоих «Парти� � …»: �то название, а не команда. +- **Плашка:** «Rodent IV 1800 · Таль». Е�ли не помещает�� р�дом � «думает…», обрезает�� им� характера («Rodent IV 1800 · Рубинш…»), чи�ло �илы не обрезает�� никогда. TalkBack: «Rodent IV 1800, Таль, думает». +- **Темп.** Rodent на ограничении �илы отвечает почти мгновенно, по�тому пауза «как человек» обща� � Maia (`pause`), как на компьютере. �а 2800 (полна� �ила) — лимит времени на ход из общего крейта (на компьютере 0,5 �). «думает…» по�вл�ет�� по�ле 300 м�, как у Maia. +- Ход назад, про�мотр, поворот �крана, фон — без изменений. Rodent — дочерний проце�� UCI (`crates/uci`) � о�тановкой и таймаутами; ответ на �тарую позицию не примен�ет�� (инварианты AGENTS.md). + +### 6.2. �ичь�, �дача, конец + +Те же правила и Stockfish (`play::hopeless`, `accepts_draw`). В лёгкой �борке без �качанной �ети Rodent, как Maia, не �даёт�� и отвечает на ничью �трокой «…� помощью Stockfish». Тек�ты — пары к �трокам Maia (§9): «Rodent �даёт��» / «Его позици� проиграна…», «Rodent отказывает�� от ничьей», «Rodent �дал��» (причина конца). Род �огла�ует��, по�тому �троки отдельные, а не `{name}` (`rodent-opponent.md` §7). + +### 6.3. Запи�ь партии + +Как на компьютере (крейт `play`): `White`/`Black` — `Rodent IV 1800 (Tal)` (англий�кое им� характера, PGN — формат обмена, не переводит��), `…Type "program"`, `Event` «Парти� � компьютером». В базу игрока пишет�� так же, как парти� � Maia (`player-games.md`). + +### 6.4. Реванш, «�ова� игра», «Играть от�юда» + +- «Реванш» — §1.6. «�ова� игра» (⋮) открывает ли�т � �тим же �оперником. +- Пункт ли�та хода «Играть от�юда � Maia…» (`play_from_maia`) �тановит�� «Играть от�юда…» (`play_from_here`, �трока уже е�ть): �оперник выбирает�� на ли�те. TalkBack-дей�твие — так же. + +### 6.5. Отложенна� парти� + +- Карточка (`android-lists.md` §5.4): «Парти� � Rodent IV 1800» / «Таль · вы белыми · 6-й ход». У Maia втора� �трока прежн��. TalkBack: «Отложенна� парти� � Rodent IV 1800, Таль, вы белыми, 6-й ход. Продолжить, кнопка». +- Вопро� при новой игре: «Е�ть отложенна� парти� � Rodent IV 1800» — «Продолжить её» · «�ачать новую», как �ейча�. +- Разработчику: в `PlayMeta` (`data/MaiaGames.kt`) добавить �оперника (`maia` | `rodent4`) и id характера (`iv_tal`). Парти�, отложенна� до обновлени�, без �тих полей — парти� � Maia. �азвание кла��а (`MaiaGames`) можно о�тавить, но �мы�л теперь «парти� � компьютером». + +### 6.6. Сбои + +- **Rodent не запу�тил��** (не та ABI, повреждён APK): карточка в партии «Rodent не запу�тил��.» — «Перезапу�тить» · «Прервать» (`play-mode.md` §3.8). Скачать его заново нельз� (он в APK), по�тому кнопки «Скачать заново», как у Maia, нет. +- **Книга не читает��** (файл повреждён по�ле проверки): движок играет без неё. Это не ошибка дл� пользовател�; в журнал приложени� пишет�� предупреждение. + +## 7. Что запоминает�� + +### 7.1. �а�тройки (`app.settings.prefs`) + +| Ключ | Значение | Впервые | Когда пишет�� | +|---|---|---|---| +| `opponent` | `maia` \| `rodent4` | `maia` | при «Играть» (и «Без книги») | +| `maiaStrength` | 600–2600 (е�ть) | 1500 | при «Играть» � Maia | +| `rodentStrength` | 800–2800 | 1500 | при «Играть» � Rodent | +| `rodentPersonality` | id компьютера (`iv_tal`…) | нет → при первом выборе Rodent предлагает�� `iv_tal` и открывает�� �пи�ок (§3.4) | при выборе в �пи�ке или закрытии �пи�ка, открытого в первый раз | +| `maiaColor` → лучше переименовать в `playColor` | 1 / 0 / −1 | 0 | при «Играть», кроме «Играть от�юда» (как �ейча�) | +| `yourName` | е�ть | — | как �ейча� | + +- Ползунок и карточки при закрытии ли�та без «Играть» **не** запоминают�� (как �ейча�: �ила пишет�� при «Играть»). Характер запоминает�� �разу при выборе: выбор в отдельном �кране — уже о�ознанное дей�твие, и тер�ть его было бы обидно. +- �еизве�тный id характера (из будущей вер�ии) — `iv_tal`. + +### 7.2. «�а�тройки → Движок» + +Под �трокой Maia (§31.2) — �трока «Rodent IV — дебютные книги»: +- втора� �трока: «�качаны · 59 МБ» / «не �качаны · 59 МБ»; �права дей�твие «Скачать» или «Удалить»; во врем� загрузки — поло�а «{a} из {b} МБ» и ✕; +- «Удалить» без диалога, �некбар «Книги удалены» (без «Вернуть»: во��тановление — та же загрузка). Пока идёт парти� � Rodent, «Удалить» неактивна (как у Maia); +- о �амом движке �троки нет: он в приложении, удалить его нельз�. + +## 8. Ориентаци�, планшет, до�тупно�ть + +### 8.1. �льбомна� ориентаци� и планшет + +- **Телефон в альбомной ориентации** (800×360): ли�т на в�ю вы�оту, подвал закреплён (≈ 128 dp), прокручиваемой ча�ти ≈ 200 dp. Карточки и �трока характера те же. Ли�т `ModalBottomSheet` шириной не больше 640 dp (так в M3 по умолчанию). +- **Планшет** (�редний и ра�ширенный кла��, `android-ui.md` §13): ли�т тот же, по центру, до 640 dp. «С кем играть» на ширине от 600 dp — не полно�кранный, а обычный `Dialog` 560 × до 90 % вы�оты, � той же верхней панелью (M3: полно�кранные диалоги только на компактной ширине). + +### 8.2. До�тупно�ть и TalkBack + +- **Карточки �оперника** — `selectableGroup`, роль `RadioButton`: «Maia, играет как человек, выбрано» / «Rodent IV, �ильный, �о �тилем, не выбрано». +- **Строка характера** (Rodent) — одна кнопка: «Характер: Таль. Риж�кий волшебник: жертвы и атака. Изменить, кнопка» (`onClickLabel` «Изменить»). Дл� Maia �трока читает�� как тек�т, без роли кнопки: «Как человек. Maia не выбирает �тиль…». +- **Ползунок:** `contentDescription` «Сила», значение «1800, от 800 до 2800». Смена �оперника объ�вл�ет�� (`liveRegion` polite у заголовка «Сила»): «Сила: 1800». +- **«С кем играть»:** �троки — `selectable` � ролью `RadioButton`: «Таль, великий шахмати�т. Риж�кий волшебник: жертвы и атака. Выбрано». Заголовки групп — `heading()`. � — «�азад». +- **Строка �о�то�ни�** — `liveRegion` polite, но объ�вл�ют�� только �мены �о�то�ни� («Скачивание», «Проверка», «Скачано», ошибка), а не каждый процент. ✕ — «Отменить �качивание». «Без книги» — «Играть без дебютной книги». +- **Цели ка�ани�:** карточки 64, �троки 72–80, ✕ и «Без книги» 48 — в�ё не меньше 48 dp. +- **Шрифт 200 %:** вы�оты �трок ра�тут (min, а не фик�ированные значени�). Ли�т прокручивает��, подвал о�таёт�� видимым. Опи�ани� в �троке характера — мак�имум 2 �троки � «…», полный тек�т в �пи�ке и TalkBack. +- Выбор отмечает�� не только цветом: ✓ на карточке и в �пи�ке. +- Клавиатура (аппаратна�): пор�док фоку�а — карточки → �трока характера → ползунок (�трелки ±50) → цвет → им� → «Играть». Enter на �троке открывает �пи�ок; в �пи�ке �трелки и Enter, Esc = назад. Специально под клавиатуру ничего не делает��. + +## 9. Тек�ты RU / EN + +Где �трока �овпадает � компьютерной (`i18n.rs`), она и её переводы на в�е 9 �зыков берут�� оттуда — в таблице отмечено «комп.». О�тальные новые, их перевод�т на 7 �зыков. + +**Имена и опи�ани� характеров** (35 пар) — без изменений � компьютера: `title` и `about` запи�ей `iv_*` в `STYLES` (например, «Удав» / «Удав: медленно душит, очень по-человече�ки.», «Strangler» / «A boa constrictor: squeezes slowly, very human-like.»). И�ключение: `iv_tal` на телефоне называет�� ключом `Tal` («Таль»), а не `Tal (classic)`. + +| Ключ (предложение) | RU | EN | И�точник | +|---|---|---|---| +| `play_title` | Игра � компьютером | (как �ейча�) | е�ть | +| `play_button` (кнопка на «Базах», вме�то `play_with_maia`) | Играть | Play | новое; TalkBack: `play_button_cd` «Играть � компьютером» / «Play the computer» | +| `opp_maia_sub` | играет как человек | plays like a human | комп. | +| `opp_rodent_sub` | �ильный, �о �тилем | strong, with a style | комп. | +| `like_human` | Как человек | Like a human | комп. | +| `maia_no_style` | Maia не выбирает �тиль: она играет, как люди её рейтинга. | Maia does not pick a style: she plays like people of her rating. | комп. | +| `strength_n` | Сила: {elo} | Strength: {elo} | комп. `Strength:` + чи�ло | +| `rodent_measured` | Соб�твенный рейтинг Rodent (UCI_Elo): он не равен Эло человека. | Rodent's own rating (UCI_Elo): it does not match a person's Elo. | комп. | +| `pick_title` | С кем играть | Who to play | новое | +| `pick_intro` | Характер — �то �тиль и дебюты, �илу задаёт ползунок. Книги дебютов �качивают�� при первой партии; их размер — �права. | A character is a style and openings; the slider sets the strength. Opening books are downloaded for the first game; their size is on the right. | новое | +| `pick_players` | Великие шахмати�ты | Great players | новое | +| `pick_characters` | Характеры | Characters | новое (комп. `Character` — ед. чи�ло) | +| `pick_change` | Изменить | Change | новое (TalkBack) | +| `pick_row_cd` | {name}, великий шахмати�т / {name}, характер | {name}, great player / {name}, character | новое (TalkBack) | +| `books_ready` | Rodent IV и его дебютные книги на телефоне | Rodent IV and its opening books are on the phone | новое | +| `books_offer` | Дебютные книги Rodent IV: {mb} МБ, �качивают�� один раз � github.com | Rodent IV opening books: {mb} MB, downloaded once from github.com | новое (короче: �трока делит ме�то � «Без книги») | +| `books_not_needed` | С позиции дебютна� книга не нужна — Rodent IV играет �разу | From a position no opening book is needed: Rodent IV plays at once | новое | +| `books_without` | Без книги | No book | новое; TalkBack `books_without_cd` «Без книги: играть без дебютной книги» / «No book: play without the opening book» | +| `books_notification` | Дебютные книги Rodent IV | Rodent IV opening books | новое (заголовок уведомлени� загрузки) | +| `books_settings` | Rodent IV — дебютные книги | Rodent IV — opening books | новое | +| `books_settings_sub` | �качаны · {mb} МБ / не �качаны · {mb} МБ | downloaded · {mb} MB / not downloaded · {mb} MB | новое | +| `books_deleted` | Дебютные книги удалены | Opening books deleted | новое; TalkBack «Удалить» — `books_delete_cd` «Удалить дебютные книги» / «Delete the opening books» | +| `play_adjourned_title` | Парти� � {opponent} | Game against {opponent} | мен�ет��: было «…� Maia %1$s»; {opponent} = «Maia 1500» / «Rodent IV 1800» | +| `play_adjourned_q` | Е�ть отложенна� парти� � {opponent} | There is a game put aside against {opponent} | мен�ет�� так же | +| `play_sub_style` | {style} · вы {colour} · без ча�ов | {style} · you play {colour} · no clock | новое (заголовок игры, Rodent) | +| `play_card_sub_style` | {style} · вы {colour} · {n}-й ход | {style} · you play {colour} · move {n} | новое (карточка, Rodent) | +| `rodent_resigns` | Rodent �даёт�� | Rodent resigns | комп. | +| `rodent_position_lost` | Его позици� проиграна. Прин�ть победу или доиграть? | Its position is lost. Accept the win, or play to the end? | EN — комп.; RU как у Maia на телефоне (`play_her_position_lost`), на компьютере «…играть до конца?» | +| `end_rodent_resigned` | Rodent �дал�� | Rodent resigned | комп. | +| `rodent_draw_declined` | Rodent отказывает�� от ничьей | Rodent declines the draw | комп. | +| `rodent_draw_later` | Rodent отказал��; �нова можно предложить через два его хода | Rodent declined; offer again after two of its moves | комп. | +| `rodent_draw_no_engine` | Rodent отвечает на ничью � помощью Stockfish: �качайте его кнопкой «Движок» | Rodent answers a draw offer with Stockfish: download it in the game screen («Engine») | новое (пара к `play_draw_no_engine`) | +| `rodent_stopped_playing` | Rodent о�тановил�� во врем� игры. | Rodent stopped during the game. | комп. «it stopped while playing» (проце�� оборвал�� по�реди партии) | +| `rodent_stopped` | Rodent не запу�тил��. | Rodent did not start. | новое (пара к `play_maia_stopped`); комп. `Rodent did not start: {e}` — дл� журнала | +| `play_note_from_rodent` | Дальше — игра � Rodent IV {elo} · {style}. | From here on, a game against Rodent IV {elo} · {style}. | новое (пара к `play_note_from`, комментарий в PGN «Играть от�юда») | +| `record_games` | Запи�ывать партии � компьютером в базу игрока | Write games against the computer to the player's database | мен�ет�� (было «� Maia»), тек�т из `player-games.md` §8 | +| `own_empty` | Зде�ь будут партии, которые вы введёте или �ыграете � компьютером | Games you enter or play against the computer will be here | мен�ет�� | + +Суще�твующие �троки без изменений: `play_download_and_play`, `play_play`, `play_retry`, `play_checking`, `downloaded_of`, `cancel_download`, `no_internet`, `interrupted`, `no_space`, `corrupt`, `play_from_here`, `play_continue_it`, `play_start_new`. + +## 10. Критерии приёмки (дл� те�тировщика) + +**Ли�т** +1. Первый запу�к: ли�т открыт � выбранной Maia, «Сила: 1500», концы 600 / 2600, �трока характера неактивна и читает «Как человек». +2. Ка�ание «Rodent IV» в первый раз �амо открывает «С кем играть»; Таль отмечен и виден без прокрутки. «�азад» → на ли�те «Таль». Второе ка�ание Maia → Rodent �кран больше не открывает. +3. Переключение Maia ↔ Rodent: �нимки ли�та �овпадают по вы�оте и положению кнопки «Играть» до пик�ел� (�нимки до/по�ле, оба �оперника, в�е �о�то�ни� �троки �о�то�ни�). +4. Maia 2400 → Rodent 1200 → обратно: у Maia �нова 2400, у Rodent 1200. Концы и по��нение под ползунком мен�ют�� вме�те � �оперником. +5. Выбор «Карпов» в �пи�ке �разу закрывает �кран; �трока характера показывает им� и опи�ание � компьютера; по�ле перезапу�ка приложени� выбран Карпов. +6. В�е 35 характеров е�ть, 22 в «Великих шахмати�тах» и 13 в «Характерах», по алфавиту в �зыке интерфей�а; опи�ани� �овпадают � компьютерными на в�ех 9 �зыках. +7. С открытой клавиатурой (поле имени) кнопка «Играть» видна над клавиатурой. + +**Книги** +8. Чи�та� у�тановка, выбран Rodent: �трока «Дебютные книги Rodent IV · 59 МБ…» и «Без книги»; «Скачать и играть» → поло�а → «Проверка…» → парти� начинает�� �ама. Скачаны в�е книги, которые называют 35 характеров (и только они, е�ли прин�т пакет 59 МБ), �уммы SHA-256 �овпадают � манифе�том. +9. По�ле загрузки �мена характера (любой из 35) не предлагает ничего �качивать; «Играть» �разу, в том чи�ле в режиме полёта. +10. Удав, Спа��кий, Дебора дей�твительно открывают �вою книгу (первый ход из книги-гида, проверка журналом UCI движка), не�мотр� на имена в их файлах. +11. ✕ на �ередине: проверенные файлы о�тали�ь, «Скачать и играть» показывает о�таток и докачивает только его; ча�тичный пакет не �читает�� готовым. +12. Режим полёта, книг нет: «Скачать и играть» → «�е удало�ь �качать: нет �оединени�», «Повторить» и «Без книги». «Без книги» начинает партию; в PGN `Rodent IV {�ила} ({Name})`. В �ледующий раз ли�т �нова предлагает �качать. +13. Смена характера во врем� загрузки: загрузка продолжает��, по окончании парти� начинает�� � новым характером. Переход на Maia во врем� загрузки: загрузка идёт в фоне, парти� �ама не начинает��. +14. «Играть от�юда» � Rodent без книг: «Играть» �разу, без загрузки. +15. «�а�тройки → Движок»: «Скачать» качает тот же пакет (общий � ли�том, втора� загрузка не начинает�� параллельно); «Удалить» удал�ет в�е книги, ли�т �нова предлагает �качать; во врем� партии � Rodent «Удалить» неактивна. +16. �и один файл книг не лежит в APK; движок лежит в обеих �борках и запу�кает�� без �ети. + +**Парти�** +17. Плашка «Rodent IV 1800 · Таль», заголовок «Парти� � Rodent IV 1800» / «Таль · вы белыми · без ча�ов»; на 360 dp при «думает…» обрезает�� им� характера, не �ила. +18. Сила реально передаёт��: `UCI_LimitStrength true`, `UCI_Elo 1800`; на 2800 ограничени� нет. Характер — опцией движка; книга — из папки на телефоне. +19. Ход назад во врем� ра�чёта Rodent: ответ �тарой позиции не примен�ет�� (гонка UCI). «Прервать», «Сдать��», конец партии и реванш (тот же характер и �ила, цвета мен�ют��) работают как у Maia. +20. «�азад» в �ередине партии → карточка «Парти� � Rodent IV 1800» / «Таль · вы белыми · {n}-й ход»; убить проце�� приложени� → карточка та же; «Продолжить» → тот же характер и �ила, позици� та же. Удалить книги, затем «Продолжить» — парти� продолжает�� без вопро�ов. +21. Парти�, отложенна� вер�ией без Rodent, по�ле обновлени� продолжает�� как парти� � Maia. +22. Тек�ты �дачи и ничьей у Rodent — �вои («Rodent �даёт��», «Его позици�…»), не «Maia». +23. Запи�ь в базу игрока: `White`/`Black` `Rodent IV 1800 (Tal)`, `…Type "program"`. + +**До�тупно�ть и вид** +24. TalkBack: карточки — переключатели � «выбрано»; �трока характера — одна кнопка � именем и опи�анием; �троки �пи�ка читают им�, группу и опи�ание; ползунок — «Сила, 1800, от 800 до 2800». +25. Шрифт 200 %, обе темы, альбомна� ориентаци� телефона, планшет (�пи�ок — диалог 560 dp): ничего не обрезает�� без «…», подвал виден. + +## 11. Вопро�ы владельцу + +1. **Кто выбран при первом открытии ли�та — Maia, как �ейча�?** Рекомендую Maia: прежние пользователи ничего не тер�ют, а карточка Rodent IV �тоит р�дом на виду. Другой вариант — ничего не выбирать и попро�ить выбрать; �то лишнее ка�ание каждому новичку. +2. **Первый характер Rodent — Таль, и при первом выборе Rodent �пи�ок открывает�� �ам?** Рекомендую да: Таль — �амое узнаваемое им�, а �пи�ок �разу показывает, �колько в�его характеров. +3. **Кнопка «Без книги» р�дом � «Скачать и играть»?** Рекомендую да: 59 МБ на мобильной �ети или в �амолёте — �ерьёзный барьер, а движок в приложении играть может; пользователь �ам видит, что дебютов не будет. +4. **С позиции играть без загрузки книг?** Рекомендую да: книга почти не нужна в �ередине партии, а ждать загрузку ради неё �транно. +5. **Сила у Maia и Rodent запоминает�� отдельно (на компьютере одна обща�)?** Рекомендую отдельно: шкалы разные, обща� �ила при переключени�х обрезает�� и тер�ет��. Е�ли нравит��, позже так же �делать на компьютере. +6. **Кнопка на «Базах»: «Играть» (�о значком робота) вме�то «Играть � Maia»?** Рекомендую «Играть»: «Играть � компьютером» в кнопку шириной 158 dp не помещает�� в одну �троку. + +## Приложение A. Книги характеров (коммит `e8d84c8`) + +Какие книги нужны каждому характеру (книга-гид + о�новна�) и �колько �то � нул� — �правочно, дл� �о�тава пакета и проверки (критерии 8, 10). Пакет — их объединение. + +**Великие шахмати�ты** (о�новна� книга — �поха): + +| id | RU | Гид | О�новна� | МБ | +|---|---|---|---|---| +| iv_alekhine | �лехин | players/rj-alekhine 0,87 | hist/_pre30 0,17 | 1,0 | +| iv_anand | �нанд | players/ph-anand2 2,00 | hist/_post06 1,47 | 3,5 | +| iv_anderssen | �ндер�ен | players/ph-anderssen2 8,54 | hist/_pre30 | 8,7 | +| iv_bosboom | Бо�бум | players/bn-bosboom 0,54 | hist/_post06 | 2,0 | +| iv_botvinnik | Ботвинник | players/ph-botvinnik2 1,76 | hist/_31to80 0,59 | 2,4 | +| iv_kasparov | Ка�паров | players/rj-kasparov 1,62 | hist/_81to06 1,39 | 3,0 | +| iv_karpov | Карпов | players/ph-karpov2 2,29 | hist/_81to06 | 3,7 | +| iv_kortchnoi | Корчной | players/rj-kortchnoi 0,14 | hist/_31to80 | 0,7 | +| iv_larsen | Лар�ен | players/ph-larsen2 2,09 | hist/_31to80 | 2,7 | +| iv_lasker | Ла�кер | players/ph-lasker2 1,75 | hist/_pre30 | 1,9 | +| iv_marshall | Маршалл | players/rj-marshall 0,30 | hist/_pre30 | 0,5 | +| iv_morphy | Морфи | players/morphy 0,001 | hist/_pre30 | 0,2 | +| iv_nimzowitsch | �имцович | players/nimzowitsch 0,26 | hist/_pre30 | 0,4 | +| iv_petrosian | Петро��н | players/petrosian 0,85 | hist/_31to80 | 1,4 | +| iv_reti | Рети | players/ph-reti2 1,64 | hist/_pre30 | 1,8 | +| iv_rubinstein | Рубинштейн | players/ph-rubinstein2 1,71 | hist/_pre30 | 1,9 | +| iv_spassky | Спа��кий | players/ph-spassky2 2,02 (в файле `ph_spassky2`) | hist/_31to80 | 2,6 | +| iv_steinitz | Стейниц | players/steinitz 0,08 | hist/_pre30 | 0,3 | +| iv_tal | Таль | players/ph-tal2 2,06 | hist/_31to80 | 2,7 | +| iv_tarrasch | Тарраш | players/ph-tarrasch2 1,68 | hist/_pre30 | 1,8 | +| iv_topalov | Топалов | players/ph-topalov2 1,83 | hist/_post06 | 3,3 | +| iv_fischer | Фишер | players/ph-fischer2 1,73 | hist/_31to80 | 2,3 | + +В�е 22 вме�те — 39,4 МБ. + +**Характеры** (о�новна� книга у в�ех — `rodent.bin` 10,18 МБ): + +| id | RU | Гид | МБ � нул� | +|---|---|---|---| +| iv_amanda | �манда | guide/ph-gambitbook 8,41 | 18,6 | +| iv_cloe | Клои | guide/closed 0,001 | 10,2 | +| iv_deborah | Дебора | books/guide.bin 0,003 (в файле `guide/guide.bin`) | 10,2 | +| iv_defender | Защитник | guide/solid 0,70 | 10,9 | +| iv_dynamic | Динамик | guide/active 0,30 | 10,5 | +| iv_grumpy | Ворчун | guide/grandpa 0,01 | 10,2 | +| iv_partisan | Партизан | guide/low 0,002 | 10,2 | +| iv_pawnsacker | Гамбити�т | rodent.bin (гид = о�новна�) | 10,2 | +| iv_pedrita | Педрита | guide/solid | 10,9 | +| iv_preston | Пре�тон | guide/cs 0,004 | 10,2 | +| iv_simple | Про�так | guide/simple 0,001 | 10,2 | +| iv_spitfire | Задира | guide/active | 10,5 | +| iv_strangler | Удав | guide/Strangler 0,01 (в файле `strangler`) | 10,2 | + +В�е 13 вме�те — 19,6 МБ. По�ле первого характера (кроме �манды) о�тальные обычно добавл�ют от 0,01 до 0,7 МБ. + +**Итого:** нужно 35 характерам — 59,0 МБ; ве�ь каталог `books/` — 69,3 МБ. diff --git a/docs/design/android-ui.md b/docs/design/android-ui.md new file mode 100644 index 0000000..3b014f4 --- /dev/null +++ b/docs/design/android-ui.md @@ -0,0 +1,2174 @@ +# ChessPenguin дл� Android: интерфей� + +Стату�: �пецификаци� дизайнера дл� реализации, редакци� 2 от 2026-10-22, � правками по�ле ревью первой реализации (§17). Она учитывает решени� владельца из `docs/decisions.md` §16: только про�мотр, Android 12 и новее, две APK, базы до ~1 млн партий. О�тавшие�� вопро�ы — в §16. Где �пецификаци� ра�ходит�� � ранними набро�ками и � `docs/research/android-stack.md` по интерфей�у, дей�твует она. Стек — Kotlin + Jetpack Compose (Material 3). + +Опирает�� на на�тольную вер�ию: + +- `library.rs` — полка баз, «+ Добавить базу», пои�к «игрок, турнир, ECO, год», «Убрать из �пи�ка», ошибки архивов; +- `large_db.rs` — режим большой базы от 20 000 запи�ей, фильтры, �чётчик «найдено из»; +- `game_view.rs` и `notation.rs` — до�ка, нотаци� в две колонки, комментарии и варианты блоками; лини� движка в предпро�мотре не мен�ет партию; +- `board.rs` — �трелки, под�ветка, анимаци�; +- `settings.rs` — темы до�ки, наборы фигур, запи�ь ходов, звук, �зык, движок; +- `san.rs` и `move-notation.md` — три режима запи�и ходов; +- `viewed.rs` — отметка «про�мотрена»; +- `examples.rs` — примеры баз; +- `engine_offer.rs` и `engine-download.md` — предложение �качать движок; +- `docs/dev/import.md` — что открывает��. + +Тон тек�тов такой же, как в `translation-ui.md` и `large-databases.md`: коротко, про�тыми �ловами, у каждой ошибки е�ть �ледующий шаг. + +Размеры даны в dp, размеры тек�та — в sp. Эталонный телефон — 360×800 dp � же�товой навигацией: нижний от�туп 24 dp, �трока �о�то�ни� 24 dp. + +## 0. Главное + +1. **Три �крана в одну цепочку: Базы → Партии → Парти�.** �а�тройки открывают�� � �крана «Базы». �ижней панели навигации нет: разделов верхнего уровн� в�его два, а ребёнку не нужно выбирать вкладку. +2. **Приложение только показывает.** Ходы не ввод�т��, комментарии не прав�т��, в файлы ничего не запи�ывает��. �и одно дей�твие не мен�ет файл пользовател�. Ка�ание до�ки в первой вер�ии ничего не делает, только один раз под�казывает, где кнопки (§7.2). +3. **До�ка на в�ю ширину �верху, под ней нотаци� как на компьютере.** О�новна� лини� идёт в две колонки, комментарии и варианты — блоками во в�ю ширину. Ленты ходов в одну �троку нет (обо�нование в §7.3). +4. **Ходы ли�тают�� кнопками внизу, под большим пальцем.** Свайпов по до�ке и по нотации нет. Един�твенный же�т «вбок» — �и�темный «назад». +5. **Со�едн�� парти� открывает�� �трелками ‹ › в верхней панели.** Перейти к ходу и перейти к партии невозможно перепутать: у кнопок разные ме�та, формы и размеры значков. +6. **Движок включает�� одной кнопкой — в каждой партии заново.** Открыта� парти� в�егда начинает�� � выключенным движком. Он �ам выключает��, когда человек выходит из партии, приложение уходит в фон или га�нет �кран. Стара� оценка не показывает�� дл� новой позиции ни на миг. В �борке без движка �та же кнопка предлагает его �качать (§8.4). +7. **Приложение работает без интернета.** Сеть нужна только дл� облачного файла, дл� �качивани� движка в �борке без него и дл� партий � Lichess и Chess.com (§23) — и только по�ле нажати� человека. Един�твенный запро� без нажати� — проверка обновлений при запу�ке (§25); её выключают в «О программе». +8. **Вид — �покойный и аккуратный:** цвета и до�ка те же, что на компьютере и �айте, Material 3 без украшений (§10). + +## 1. И�точники: что заим�твуем + +| Откуда | Что видно | Что берём | +|---|---|---| +| Lichess mobile, `analysis_layout.dart` — | В портрете: линии движка, до�ка, под до�кой вкладки � деревом ходов, внизу в�егда нижн�� панель. В альбомной ориентации и на планшете до�ка �боку, �права линии движка и дерево. | Портрет: до�ка �верху, ходы под ней, кнопки внизу. �льбомна� ориентаци� и планшет: до�ка �лева, �права движок и нотаци�. | +| Lichess mobile, `analysis_screen.dart` — | �ижн�� панель: меню, перевернуть до�ку, движок, назад, вперёд. При удержании «назад» и «вперёд» повтор�ют�� (`RepeatButton`). Свайпов по до�ке нет. | Со�тав нижней панели и повтор при удержании; без �вайпов. | +| Lichess mobile, `tree_view.dart` — | Под до�кой полное дерево ходов в двух видах (`twoColumn` и `inlineNotation`), в дереве видны комментарии PGN. | Полный �пи�ок ходов в две колонки, а не лента. | +| Lichess mobile, `move_list.dart` — | Лента вы�отой 40 dp или �толбик. Текущий ход центрирует��: `ensureVisible(alignment: 0.5)`, анимаци� 200 м�. | �втопрокрутка к текущему ходу, 200 м�. Ленту не берём. | +| Lichess mobile, `variations_bar.dart` — | Е�ли у позиции не�колько продолжений, показывает�� поло�а � ними; главное выделено. | Строка «Дальше:» на развилке (§7.5). | +| Lichess mobile, `pgn_games_list_screen.dart` — | Строка партии: «белые vs чёрные, результат», ниже «турнир • ме�то • дата». Перехода к �о�едней партии нет. | Двух�трочна� �трока партии. Переход к �о�едней партии добавл�ем �ами. | +| Lichess mobile, `android_gesture_exclusion.dart` — | Выключает �и�темный же�т «назад» в заданной зоне у кра�. | Так же защищаем бегунок бы�трой прокрутки (§6.6). | +| ChessBase Online дл� Android — | Пои�к по игроку, году и турниру; про�мотр партий � тек�том и цветными пометками. | Пои�к по игроку как главный �по�об; �трелки и цветные пол� из комментариев. Сведени� вз�ты из опи�ани�, на у�трой�тве не провер�ли�ь. | +| Android SAF — | `ACTION_OPEN_DOCUMENT`, `ACTION_OPEN_DOCUMENT_TREE`, по�то�нный до�туп к файлам. С Android 11 нельз� выбрать папку «Download» или корень пам�ти целиком. | Выбор файла и папки (§4). | +| Android: же�ты, предиктивный «назад» — , | Си�темные же�ты у краёв �крана; и�ключить из них можно не больше 200 dp вы�оты на каждый край. | Своих же�тов у краёв нет; предиктивный «назад» поддерживаем (§2). | +| Android 12: за�тавка — | Си�темна� за�тавка �о значком приложени�, `setKeepOnScreenCondition`. | §2.2. | +| Android 12: динамиче�кие цвета — | `dynamicLightColorScheme` и `dynamicDarkColorScheme` �тро�т палитру из обоев. | Это на�тройка, по умолчанию выключена (§10.3). | +| Android 13: �зык приложени� — | Язык приложени� задаёт�� отдельно от �и�темы; `AppCompatDelegate.setApplicationLocales` работает и на 12. | §9. | +| Отри�овка до краёв (edge-to-edge) — | С targetSdk 35 приложение об�зано ри�овать под �и�темными панел�ми. | §2.2. | +| Material Symbols — , лицензи� Apache 2.0 | �абор значков Material. | Значки §10.6. | +| �даптивный значок — | Хол�т 108 dp, безопа�ный круг 66 dp; �лой дл� монохромного значка (Android 13). | §10.7. | + +Приложение chess.com мы не изучали, по�тому утверждений о нём зде�ь нет. + +## 2. Экраны и �и�темное поведение + +### 2.1. Карта �кранов + +``` + ┌──────────────� + запу�к ──────▶│ Базы │──⚙──▶ �а�тройки ──▶ О программе + └──────┬───────┘ + «Добавить базу» │ нажатие на базу + (ли�т → �и�темный ▼ + выбор файла/папки) ┌──────────────� ⌕ пои�к, ⇅ �ортировка, фильтры + │ Партии │ + └──────┬───────┘ + │ нажатие на партию + ▼ + ┌──────────────� ‹ › �о�едн�� парти� (тот же �кран) + │ Парти� │ ли�ты: «Сведени�», меню ⋮, «Скачать движок» + └──────────────┘ + +«Открыть � помощью» / «Поделить��» из Telegram, почты, файлового менеджера, +«В�тавить PGN из буфера» в ли�те «Добавить базу» + ──▶ копи� в приложении в�таёт в �пи�ок баз; поверх «Баз» �разу + «Партии» �той копии, а е�ли парти� одна — «Парти�» (§4.5, §4.6). + +Обновление (§25): карточка над �пи�ком «Баз» или «О программе» + ──▶ ли�т «Обновление» ──▶ (один раз) �и�темна� на�тройка разрешени� + ──▶ окно Android «Обновить приложение?» ──▶ приложение закрывает��. +``` + +- Приложение — одна активно�ть; �краны лежат в �теке. «�азад» (же�т или � в верхней панели) в�егда возвращает на шаг: Парти� → Партии → Базы → выход. +- «�азад» �начала закрывает �амое верхнее: клавиатуру → ли�т или меню → предпро�мотр линии движка → поле пои�ка (вме�те � запро�ом) → �кран. +- По�ле возврата в «Партии» пои�к, фильтры, �ортировка и прокрутка о�тают�� прежними. Строка по�ледней про�мотренной партии (в том чи�ле открытой через ‹ ›) прокручивает�� в видимую ча�ть и на 1 � под�вечивает��. +- Приложение в�егда открывает�� на �кране «Базы»: так ребёнок каждый раз начинает � пон�тного ме�та. + +### 2.2. Android 12+ (minSdk 31) + +- **За�тавка.** И�пользуем �и�темную за�тавку Android 12 (`installSplashScreen`): значок §10.7 на фоне `background` текущей темы. За�тавка держит�� только пока читают�� на�тройки и �пи�ок баз (`setKeepOnScreenCondition`), обычно меньше 300 м�. И�ку��твенной задержки нет, отдельного �крана-за�тавки тоже. +- **Отри�овка до краёв.** Включает�� `enableEdgeToEdge()`, �и�темные панели прозрачные. Верхн�� панель приложени� ри�ует�� под �трокой �о�то�ни�, её фон — `surface`. �ижн�� панель кнопок занимает и поло�у же�тов: кнопки �то�т выше неё (`WindowInsets.navigationBars`), а фон продолжает�� до кра�. Значки �троки �о�то�ни� �ветлые или тёмные в зави�имо�ти от темы. До�ка �о �трокой �о�то�ни� не пере�екает�� никогда. +- **Предиктивный «назад».** Включён (`enableOnBackInvokedCallback`). При же�те назад видно �кран, на который вернём��; ли�ты закрывают�� в�лед за пальцем. +- **Язык.** Язык приложени� выбирает�� в �амом приложении. �а Android 13 и новее тот же выбор виден в �и�темных на�тройках приложени� (§9). +- **Уведомлени�.** Разрешение на уведомлени� не запрашиваем. Скачивание движка и обновлени� работает и без него: уведомление о ходе показывает �ам `DownloadManager` (§8.4, §25.6). + +## 3. Экран «Базы» + +### 3.1. Пу�той �кран (первый запу�к) + +``` +┌────────────────────────────────────� 360 +│ ChessPenguin ⚙ │ 64 +├────────────────────────────────────┤ +│ │ +│ [пингвин] │ 96 значок приложени� +│ │ +│ Зде�ь будут ваши базы │ 22sp +│ │ +│ Добавьте файл PGN, базу ChessBase│ 16sp, по центру, +│ или архив .zip/.7z — � телефона │ ширина ≤ 296 +│ или из облака. │ +│ │ +│ ┌──────────────────────� │ +│ │ + Добавить базу │ │ 48 заполненна� кнопка +│ └──────────────────────┘ │ +│ Открыть примеры партий │ 48 тек�това� кнопка +└────────────────────────────────────┘ +``` + +- **Примеры уже в �пи�ке при первом запу�ке** — две базы из `examples/` («Кла��иче�кие партии» и «�лехин»), � именами на �зыке интерфей�а, пока их не переименовали. Так приложение � первой �екунды показывает, что умеет, а «+ Добавить» в заголовке «Файлы» видна �разу (правка по�ле ревью: раньше примеры добавл�ли�ь кнопкой). +- Пу�той �кран по�вл�ет��, только е�ли человек убрал из �пи�ка в�ё. Тогда «Открыть примеры партий» возвращает примеры и открывает первый. +- �а пу�том �кране главное дей�твие в центре. + +### 3.2. Спи�ок баз + +Оформление �трок, групп, плашек видов и карточки отложенной партии — `android-lists.md` §5 (утверждено 2026-10-26); пути и тек�ты ниже не мен�ют��. + +``` +┌────────────────────────────────────� +│ ChessPenguin ⚙ │ +├────────────────────────────────────┤ +│ Файлы + Добавить │ 48 заголовок группы � кнопкой +│ [PGN] Мои партии ⋮ │ 72 +│ 1 248 партий · PGN │ +│ [CB] Турниры 2000–2025 ⋮ │ +│ 870 ты�. партий · ChessBase │ +│ [ZIP] Дворецкий. Учебник ⋮ │ +│ ▬▬▬▬▬▬▭▭▭ читаю… 3 400 │ поло�а и �чётчик +│ [!] Турнир Петрова ⋮ │ +│ �ет до�тупа к файлу �айти │ цвет ошибки и кнопка-��ылка +└────────────────────────────────────┘ +``` + +- **Строка базы.** + - Слева плашка формата 40 dp � тек�том `PGN`, `CB`, `ZIP` или `7Z` (§10.6). У базы � ошибкой вме�то неё `!` на фоне `errorContainer`. + - Им� базы 16sp. Под ним 14sp цветом `onSurfaceVariant`: «N партий · формат». + - Чи�ла �окращают�� как на компьютере (`short_count`): «870 ты�. партий», «1,6 млн партий»; меньше 100 000 — полно�тью, � пробелом между разр�дами. + - Пока базу ни разу не открывали, втора� �трока — «ещё не открывала�ь · PGN». Формат �ловом, как по�ле открыти�: `PGN`, `ChessBase`, `архив 7z`, `архив ZIP`; не код плашки `CB`. Размера нет: у баз из папки его нет без лишнего запро�а. +- Разделителей между �троками нет: �троки группы — карточки � зазором 2 dp (`android-lists.md` §5.3). +- Базы идут в пор�дке добавлени�, новые внизу. +- �ажатие открывает «Партии». Долгое нажатие и ⋮ открывают одно и то же меню: «Переименовать», «Сведени�», «Убрать из �пи�ка». +- «+ Добавить» — тек�това� кнопка в заголовке «Файлы», как «+ �ова� база» в заголовке «Моих баз» (решение владельца 2026-10-27: плавающа� кнопка ви�ела поверх �пи�ка). Кажда� группа �о �воим дей�твием �права, над �пи�ком ничего не ви�ит. Без файлов под заголовком �трока-под�казка, что �юда попадут добавленные файлы, папки и партии из интернета. + +### 3.3. Меню базы + +- **Переименовать** — диалог � полем, текущее им� в нём выделено. Под полем подпи�ь: «�азвание в �пи�ке. Файл не мен�ет��.» Кнопки «Отмена» и «Сохранить»; � пу�тым именем «Сохранить» неактивна. +- **Сведени�** — ли�т �низу: + +``` +┌────────────────────────────────────� +│ ─── │ +│ Турниры 2000–2025 │ 22sp +│ │ +│ Формат ChessBase, только чтение│ +│ Партий 871 204 │ +│ Размер 310 МБ │ +│ Где Внутренн�� пам�ть › │ +│ Шахматы/Турниры │ +│ Добавлена 12 окт. 2026 │ +│ │ +│ ChessPenguin только читает �тот │ +│ файл и никогда его не мен�ет. │ +│ Замечани� (2) ▾ │ +└────────────────────────────────────┘ +``` + + - У PGN не в UTF-8 �трока «Формат» — «PGN, кодировка windows-1251». + - У копии (§4.4) �трока «Где» — «Копи� в ChessPenguin (из Google Ди�ка)». + - «Тек�тов» показывает��, только е�ли в базе е�ть тек�товые главы. + - «Замечани�» — заметки импорта (например, что повтор в архиве пропущен). Е�ли заметок нет, пункта нет. +- **Убрать из �пи�ка** — без диалога. Строка и�чезает, на 4 � по�вл�ет�� �некбар «База убрана из �пи�ка · Вернуть». Сам файл не удал�ет��. + - Копи� в приложении (§4.4) при �том удал�ет��; �некбар — «База удалена из ChessPenguin · Вернуть». ~~Диалог «Убрать базу?»~~ — заменён �некбаром 2026-10-23 (§20). + +## 4. Добавление базы + +### 4.1. Ли�т «Добавить базу» + +«+ Добавить» открывает ли�т, а не �разу �и�темный выбор: базе ChessBase из не�кольких файлов нужна папка, и �то надо показать заранее. Ли�т — `ModalBottomSheet` как у движка (§8.4), �троки — `ListItem` на прозрачном фоне, без �воей заливки. + +``` +┌────────────────────────────────────� +│ ─── │ +│ Добавить базу │ 22sp +│ [⎘] В�тавить PGN из буфера │ 72 только е�ли в буфере тек�т +│ Партии, �копированные в другом│ +│ приложении │ +│ [▤] Файл │ 72 +│ PGN, .cbv, .zip или .7z │ +│ [▣] Папка │ 72 +│ В�е базы в папке, в том чи�ле │ +│ ChessBase (.cbh) │ +│ Корень пам�ти и �аму «Загрузки» │ 12sp, onSurfaceVariant +│ выбрать нельз� — только папку │ +│ внутри них. │ +└────────────────────────────────────┘ +``` + +- Сно�ка внизу — един�твенное ме�то, где объ��н�ет�� запрет Android. Си�темный выбор папки �ам пишет «Can't use this folder» по-англий�ки и предлагает �оздать папку; наша �трока заранее говорит, что делать. +- **«В�тавить PGN из буфера»** (§4.5) — перва� �трока, значок `content_paste`. Она е�ть, только е�ли в буфере тек�т. Провер�ет�� лишь опи�ание буфера (`primaryClipDescription`, тип `text/*`): чтение �амого тек�та Android объ�вл�ет в�плывающим �ообщением, по�тому тек�т читает�� только по нажатию. + - Отдельный автоматиче�кий �ценарий из уточнени� владельца (§4.5) провер�ет тек�т при запу�ке/возврате в foreground один раз до решени� пользовател�; он не мен�ет �тот ручной путь и не �оздаёт по�то�нного �лушател� буфера. + - Строка первой, потому что она контек�тна�: человек только что �копировал партию в другом приложении и пришёл её в�тавить. «Файл» и «Папка» �двигают�� на 72 dp, но на них не нажимают в�лепую — ли�т читают глазами. + - Под�казка до двух �трок — допу�тимо; на 360 dp по-ру��ки она помещает�� в одну-две �троки, по-немецки «In einer anderen App kopierte Partien» — в одну. + +### 4.2. «Файл» + +- И�пользует�� `ACTION_OPEN_DOCUMENT` � MIME `*/*`, один файл. Формат определ�ет�� по �одержимому, как в `chess_import::open`. Сразу по�ле выбора приложение берёт по�то�нный до�туп (`takePersistableUriPermission`). +- Строка базы по�вл�ет�� в �пи�ке и открывают�� её «Партии». +- **Выбран `.cbh`** (или `.cbg`, `.cba` и т. п.) — диалог: + + > **�ужна в�� папка** + > База ChessBase — �то не�колько файлов р�дом: .cbh, .cbg, .cba и другие. Выберите папку, в которой они лежат. + > [Отмена] [Выбрать папку] + + Выбор папки открывает�� там, где лежал файл (`EXTRA_INITIAL_URI`), е�ли �и�тема �то позвол�ет. +- **Файл уже в �пи�ке** — второй �троки не по�вл�ет��. Снекбар «Эта база уже в �пи�ке», �пи�ок прокручивает�� к ней. + +### 4.3. «Папка» + +- `ACTION_OPEN_DOCUMENT_TREE`, по�то�нный до�туп на чтение берёт�� �разу и возвращает�� �и�теме, е�ли из папки ничего не добавили (отмена, пу�та� папка). +- Ищут�� `.pgn`, `.zip`, `.7z`, `.cbv` и `.cbh` в �амой папке и во вложенных на два уровн�. Пор�док — по алфавиту внутри каждой папки, �начала файлы, потом вложенные папки. +- **Пара `.cbh` + `.cbv` � одним именем в одной папке** — �то одна база (`.cbv` — её архив). Показывает�� одна �трока, `.cbh`; `.cbv` не предлагает��. +- Ли�т открывает�� �разу во в�ю вы�оту (`skipPartiallyExpanded`), кнопки в�егда видны под �пи�ком. + +**Пои�к** (обычно доли �екунды, на облачной папке дольше): + +``` +│ ◌ Ищу базы… │ 96, индикатор 24 dp +``` + +Ли�т можно закрыть и во врем� пои�ка. + +**�айдено** — �пи�ок � флажками, отмечено в�ё, что можно добавить: + +``` +┌────────────────────────────────────� +│ В папке «Шахматы» найдено 7 баз │ 22sp, может в две �троки +│ ☑ [CB] Endgame Manual │ 64, в�� �трока — флажок +│ Endgame Manual.cbh │ 14sp onSurfaceVariant +│ ☑ [PGN] Кла��ика │ +│ Книги/Ещё · Кла��ика.pgn │ путь · файл +│ ☑ [PGN] Alekhin │ флажок отмечен и неактивен +│ уже в �пи�ке │ +│ � [CB] �еполна� │ плашка errorContainer, +│ Книги · нет файла .cbg — │ подпи�ь цветом error, +│ партии не открыть │ до двух �трок +│ Отмена [Добавить 6]│ +└────────────────────────────────────┘ +``` + +- Перва� �трока — им� без ра�ширени�; втора� — где лежит внутри выбранной папки и им� файла (у файла в �амой папке — только им� файла). Так две разные базы � одинаковым именем различают�� путём. +- **Уже в �пи�ке** — та же база (тот же файл; у файла, добавленного через «Файл», — по имени и размеру). Флажок отмечен и неактивен. +- **�еполна�** — `.cbh` без `.cbg`: флажок �н�т и неактивен, плашка `CB` на `errorContainer`. +- Кнопка — «Добавить N», N — чи�ло отмеченных; при N = 0 неактивна. Е�ли добавить нечего (в�ё уже в �пи�ке или неполное) — одна кнопка «Готово». +- По�ле добавлени� ли�т закрывает��, базы в�тают в конец �пи�ка, �некбар «Добавлено 6 баз». Сразу ничего не открывает��: базы читают�� при первом открытии, до �того �трока — «ещё не открывала�ь · ChessBase» (§3.2). +- **�и одной базы:** + + > **В папке нет баз** + > Подход�т файлы PGN, базы ChessBase (.cbh, .cbv) и архивы .zip и .7z — в �амой папке и во вложенных папках на два уровн�. + > [Отмена] [Выбрать другую] + + «Выбрать другую» �нова открывает �и�темный выбор папки. +- Одна найденна� база тоже показывает�� �пи�ком из одной �троки: человек видит, что именно добавит��. + +### 4.4. Файл на ме�те или копи� + +- **Файл в пам�ти телефона или на SD-карте** читает�� на ме�те, без копии. +- **Облачный файл** (Google Ди�к и т. п., е�ли его нельз� читать � произвольного ме�та), **файл из «Открыть � помощью» и «Поделить��»** (§4.6) и **тек�т из буфера** (§4.5) копируют�� в пам�ть приложени� (`files/copies/`). + - Копи� — обычна� база в �пи�ке. Во второй �троке у неё �лово «копи�»: «1 парти� · PGN · копи�» (en «1 game · PGN · copy»), чтобы человек знал, что файл лежит в ChessPenguin, а не там, откуда пришёл. + - «Убрать из �пи�ка» у копии удал�ет её. Снекбар другой: «База удалена из ChessPenguin · Вернуть» (en «Database deleted from ChessPenguin · Undo»); пока он виден, «Вернуть» возвращает базу, по�ле него файл копии �тирает��. Диалог §3.3 заменён �тим �некбаром: дей�твие обратимо, лишний вопро� не нужен. + - Тот же файл или тот же тек�т второй раз не копирует��: по SHA-256 находит�� уже �охранённа� копи�, и открывает�� она (� её текущим, возможно, новым именем). + - Е�ли файл больше 50 МБ, �начала диалог: «Файл в облаке. ChessPenguin �охранит копию у �еб�: 120 МБ.» � кнопками «Отмена» и «Сохранить копию». + - Пока идёт копирование, в �троке базы напи�ано «копирую… 40 %». +- Как отличить один �лучай от другого, решает разработчик: по флагам документа и по тому, поддерживает ли де�криптор `seek`. Пользователь видит итог в «Сведени�х». + +### 4.5. «В�тавить PGN из буфера» + +- По нажатию ли�т закрывает��, тек�т буфера �охран�ет�� копией (§4.4) и �тавит�� в конец �пи�ка баз. Поверх «Баз» открывают��: + - одна парти� — �разу «Парти�» («1 из 1», ‹ › неактивны); «назад» ведёт в «Партии» �той копии, потом в «Базы»; + - не�колько — «Партии». +- **Им� копии.** + - Одна парти� — игроки, как в �троке партии (§6.2): «Alekhine A. – Rozanov V.». Е�ли обоих игроков нет («?»), — как у не�кольких партий. + - �е�колько партий � одним и тем же непу�тым тегом `Event` — �то �обытие: «Wijk aan Zee 2024». + - Иначе — «Из буфера, {дата и врем�}»: «Из буфера, 23 окт., 14:05» (en «Pasted 23 Oct, 14:05»). Дата и врем� — `DateUtils.formatDateTime` � `FORMAT_SHOW_DATE | FORMAT_SHOW_TIME | FORMAT_ABBREV_MONTH`, без года. Так две разные в�тавки в �пи�ке различают��; переименовать можно как любую базу. +- �ет партий (пу�той тек�т, обычный тек�т, тек�т без тегов и ходов) — ли�т закрыт, �некбар «В буфере нет партий в формате PGN». В �пи�ок ничего не добавл�ет��. +- Тот же тек�т второй раз открывает уже �охранённую копию (§4.4). + +#### �втоматиче�кое предложение при запу�ке и возврате + +Уточнение владельца: приложение �амо провер�ет буфер при холодном запу�ке и возврате в `RESUMED`, но только предлагает открыть его. Это не замен�ет ручную �троку «В�тавить PGN из буфера»: ручной путь о�таёт�� до�тупен дл� уже отклонённого тек�та. + +- Тек�т разбирает�� локально на фоновом потоке тем же PGN-reader. Предложение по�вл�ет�� только е�ли перва� запи�ь �одержит теги или ходы; пу�той, обычный и повреждённый тек�т не вызывает диалог или �некбар. Снимок больше 8 MiB игнорирует��, чтобы не блокировать интерфей� и не ра�ходовать пам�ть. +- Обычный Material 3 `AlertDialog`: заголовок `Парти�/Партии в буфере обмена`, короткое по��нение и тек�товые кнопки «Открыть»/«Отмена». При не�кольких и�пользует�� локализованное чи�ло и �вно �казано, что откроет�� перва�. «�азад» и нажатие мимо означают отказ. Залитых кнопок, иконки и нового отдельного �крана нет. +- До выбора копии и запи�и в библиотеку нет. По�ле «Открыть» вызывает�� `Library.addCopy`, затем �тек `Databases → Games(id) → GameAt(id, 0)`: в�егда открывает�� перва� запи�ь. `shown` и `lastOpened` �той копии �бра�ывают��, чтобы �тарый пои�к не изменил выбор. О�тальные запи�и до�тупны обычными �трелками и в �пи�ке по�ле Back. +- По�ле у�пешного открыти� или отказа SHA-256 �охран�ет�� в приватных на�тройках и по�ле холодного перезапу�ка; �ам PGN в на�тройки не пишет��. �ажатие «Открыть» �амо по �ебе решённым не �читает��: digest по�вл�ет�� в на�тройках только по�ле фактиче�ки �охранённой запи�и, по�тому ошибка запи�и допу�кает повторную попытку. Открытый или отклонённый тек�т повторно не предлагает��, новый тек�т получает новое предложение. �ерешённый offer живёт в Application и переживает поворот без повторного разбора и дублировани�. +- Пу�той или новый буфер инвалидирует предыдущее поколение. У�таревший accept и у�таревший импорт не публикуют��. Проверка по�леднего запро�а и публикаци� атомарны; URI и clipboard и�пользуют общий пор�док по�леднего запро�а и `compareAndSet` при потреблении �обыти�, чтобы �тарый collector не �тёр новое. +- `UpdateSheet`, `Incoming.Opening` и `Incoming.Failed` имеют приоритет: clipboard-диалог их не перекрывает. �ерешённый вопро� �крывает�� без отказа, по�ле закрыти� блокировщика выполн�ет�� �вежа� проверка. +- Чтение только в foreground, без по�то�нного listener и �етевых вызовов. �еобработанный тек�т не пишет�� в логи, Bundle и на�тройки; по�ле отказа о�таёт�� только SHA-256. + +### 4.6. «Открыть � помощью» и «Поделить��» + +- Приложение принимает `ACTION_VIEW` (�хема `content`) и `ACTION_SEND` � MIME `application/x-chess-pgn`, `application/vnd.chess-pgn`, `application/zip`, `application/x-7z-compressed` и `application/octet-stream` — по�ледний дл� `.cbv` и дл� `.pgn` из приложений, которые не знают �тот тип (Telegram). `text/plain` не принимаем: иначе ChessPenguin предлагал�� бы дл� любого тек�та; тек�т партии в�тавл�ет�� из буфера (§4.5). +- �ктивно�ть одна (`singleTask`): файл приходит в уже открытое приложение, а не во вторую копию поверх Telegram. +- Файл �разу копирует�� в приложение (§4.4): чужое приложение даёт до�туп только на врем�. Им� базы — им� файла без ра�ширени�. Им� без изве�тного ра�ширени� (`file_123`) читает�� как PGN. +- **Пока копирует��** — модальный диалог без кнопок, его не закрыть ни «назад», ни нажатием мимо: + +``` +┌──────────────────────────────� +│ (◌) Открываю файл… │ 24 dp индикатор, 16 dp, bodyLarge +└──────────────────────────────┘ от�тупы 24 dp, extraLarge, surfaceContainerHigh +``` + +- **Готово** — диалог закрывает��, база в�таёт в конец �пи�ка. Стек �бра�ывает�� до «Баз», поверх — «Партии» �той базы, а е�ли парти� одна — «Парти�». То, что было открыто до �того, закрывает��: пришедший файл важнее. +- **Ошибка** — диалог: + + > **Файл не открыл��** + > {причина} + > [Пон�тно] + + Причина — та же, что при открытии базы из �пи�ка (§11): «В �том файле нет шахматных партий.», «Файл повреждён или �то не шахматна� база.», пароль, `.2cbh` и т. п. Е�ли файл не удало�ь прочитать (до�туп отозван, файла уже нет) — «Файл не прочитал��: его уже нет или приложение, из которого он открыт, не дало к нему до�тупа. Попробуйте открыть его ещё раз.» В �пи�ок ничего не добавл�ет��, �кран под диалогом не мен�ет��. +- TalkBack: при по�влении диалога «Открываю файл…» фоку� на нём, тек�т читает�� �разу; индикатор без �воего опи�ани�. Диалог ошибки — обычный `AlertDialog`: заголовок, причина, кнопка. + +## 5. Открытие и чтение + +- **Чтение идёт в фоне и не мешает �крану.** + - В �троке базы — поло�а прогре��а и «читаю… 3 400». + - «Партии» уже открыты: �верху линейный индикатор, партии по�вл�ют�� по мере чтени�, в заголовке ра�тёт чи�ло («3 400 партий…»). +- **Больша� база ChessBase** (от 20 000 запи�ей, порог `LARGE_CHESSBASE`) открывает�� по индек�у, без перевода в PGN. Это занимает не�колько �екунд; индикатор без процентов � подпи�ью «Открываю базу…». +- **Очень больша� база** (больше 1 млн запи�ей; приложение ра��читано на базы до ~1 млн) — перед первым открытием диалог: «Очень больша� база: 11,7 млн партий. ChessPenguin ра��читан на базы до миллиона партий; �та может открывать�� долго и работать медленно.» Кнопки «Отмена» и «В�ё равно открыть». +- **PGN больше 200 МБ** не открывает��. Сообщение: «Файл �лишком большой дл� телефона (1,2 ГБ). ChessPenguin открывает PGN до 200 МБ. Откройте его на компьютере или разделите на ча�ти.» Кнопка «Пон�тно». Порог 200 МБ — одна кон�танта, разработчик уточнит её замером. +- **Отмена чтени�** — ✕ �права от индикатора и пункт «О�тановить чтение» в меню �троки базы. + - По�ле отмены: «Чтение о�тановлено» и кнопка «Прочитать �нова». + - Прочитанную ча�ть не выдаём за в�ю базу. +- Уход � �крана чтение не о�танавливает, пока приложение открыто. Е�ли �и�тема выгрузила приложение, чтение начнёт�� заново при �ледующем открытии базы. +- Повторно открыть неизменённый файл нужно бы�тро, без полного перечитывани�. К�ш индек�а — решение разработчика; е�ли его не будет, разработчик отмечает �то как изве�тное ограничение. + +## 6. Экран «Партии» + +### 6.1. Мала� база + +``` +┌────────────────────────────────────� +│ � Мои партии ⌕ ⇅ │ 64 +│ 1 248 партий │ +├────────────────────────────────────┤ +│ 1 Карл�ен, Магну� 2830 1 │ 80 белые +│ Каруана, Фабиано 2795 0 │ чёрные +│ �орвеги� · 2025 · C42 ✓ │ подробно�ти +│ 2 Иванов Пётр ½ │ 80 +│ Сидоров �лек�ей ½ │ +│ Первен�тво школы · 2024 · B90│ +│ 17 Ретти, 1921. Белые начинают │ 80 �тюд: у чёрных «?», +│ и делают ничью │ им� белых в две �троки +│ Этюды · 1921 │ +│ 1248 Alekhine, Alexander 0 │ 80 +│ Capablanca, José Raúl 1 │ +│ World Championship · 1927 ✓ │ +│ … � │ бегунок бы�трой прокрутки +└────────────────────────────────────┘ +``` + +(Обновлено 2026-10-24: каждый игрок на �воей �троке, §6.2.) + +В малой базе, как на компьютере, е�ть только пои�к и �ортировка. + +### 6.2. Строка партии (80 dp, три �троки) + +Оформление � 2026-10-26 — `android-lists.md` §3: кружки �торон, плашка результата, метка ECO, разделитель, отметка партии, открытой по�ледней, под�ветка пои�ка. Сетка и вы�ота ниже не мен�ют��. + +Обновлено 2026-10-24. Раньше «Белые – Чёрные» �то�ли в одной �троке, и на 360 dp фамили� чёрных ча�то обрезала�ь. Теперь у каждого игрока �во� �трока: белые �верху, чёрные под ними, как плашки на до�ке (§7.11), только в обратном пор�дке — �верху вниз читает�� «кто играл белыми, кто чёрными». + +``` + 16 ┌ номер � 16 ┌──────────── тек�т, о�таток ширины ────────────� 8 24 16 + │ 12 │ │ Карл�ен, Магну� 2830 │ 1 │ 24 bodyLarge, белые + │ │ │ Каруана, Фабиано 2795 │ 0 │ 24 bodyLarge, чёрные + │ │ │ �орвеги� · 2025 · C42 │ ✓ │ 20 bodyMedium + от�тупы �верху и �низу по 6 → 80 +``` + +- **Вы�ота �троки — 80 dp:** от�туп 6 + �трока белых 24 (`bodyLarge`, 16sp/24) + �трока чёрных 24 + �трока подробно�тей 20 (`bodyMedium`, 14sp/20) + от�туп 6. + - Вы�ота одинакова у в�ех �трок, в том чи�ле у �тюда без чёрных и у заглушки, пока �трока читает�� (§6.6). Заглушка ри�ует те же три �троки �ерыми поло�ками, по�тому при крупном шрифте она ра�тёт вме�те � на�то�щими �троками. Иначе бегунок и прыжки по большой базе дёргают��. + - �а �кран 360×800 помещает�� 8,5 �троки (было 10,7). Это цена за то, что видны обе фамилии. +- **�омер партии в базе** — �лева, отдельной колонкой (� 2026-10-23). + - Это номер запи�и в файле (перва� парти� — 1), а не ме�то в �пи�ке: при �ортировке, пои�ке и фильтрах номер о�таёт�� тем же, по�тому по нему партию можно найти �нова и назвать другому человеку («открой 154-ю»). + - Цифры моноширинные (`tnum`), цвет `onSurfaceVariant`, выравнивание вправо. Ты��чи раздел�ют�� узким пробелом, как в �чётчиках (`1 248`). Кегль — как �ейча� в коде (`bodySmall`). + - **По вертикали номер �тоит на базовой линии �троки белых**, а не по центру �троки 80 dp: в трёх�трочной �троке номер по центру оказал�� бы напротив чёрных, и казало�ь бы, что он отно�ит�� к ним. + - Ширина колонки — по �амому большому номеру в базе, одна на ве�ь �пи�ок, чтобы имена не прыгали при прокрутке. По�ле колонки — от�туп до тек�та, как �ейча� (12 dp). + - �омер виден и при пои�ке: он показывает, где найденна� парти� �тоит в базе. «12 из 340» в заголовке �крана «Парти�» — другое чи�ло, ме�то в текущем пор�дке (§7.6). +- **Строка белых и �трока чёрных**, 16sp (`bodyLarge`), цвет `onSurface`. + - **Им� — полно�тью, как в файле** («Карл�ен, Магну�»). �а �воей �троке у имени около 210–250 dp, �то 25–30 знаков, по�тому почти в�е имена помещают�� целиком. + - **Е�ли полное им� не помещает��**, вме�то него показывает�� короткое: «Фамили�, Им� Отче�тво» → «Фамили� И. О.» (`shortName()`). Е�ли не помещает�� и оно, или им� без зап�той («Вафин Радель Ильдарович Длинный»), оно обрезает�� многоточием в конце. Многоточие — только по�леднее �ред�тво. Это одно правило дл� �пи�ка и плашек на до�ке (§7.11): общий �лемент `PlayerName`. + - **Эло** — �разу по�ле имени, через 8 dp, 14sp (`bodyMedium`), `onSurfaceVariant`, `tnum`. Показывает��, только е�ли в теге чи�ло больше нул�. Эло не обрезает��: при нехватке ме�та �окращает�� и обрезает�� им�. + - **Результат — в колонке 24 dp �права, у каждого игрока �вой**: `1` у победител�, `0` у проигравшего, `½` у обоих при ничьей. Как на плашках у до�ки (§7.11), только в �пи�ке он выровнен по базовой линии �воей �троки. 16sp, `tnum`, выравнивание вправо. Цифра победител� — `onSurface` и полужирна� (500); `0` и `½` — `onSurfaceVariant`, обычные. Смы�л не передаёт�� одним цветом: �ама цифра его и не�ёт. + - Результат `*` (парти� без итога, учебна� позици�) не показывает��: в учебниках �то �толбик звёздочек без �мы�ла. Колонка 24 dp о�таёт�� пу�той, чтобы имена в разных �троках кончали�ь на одной линии. +- **�е хватает имён.** + - У чёрных пу�то или `?` (позици� из учебника, �тюд, где в теге White запи�ано название): �троки чёрных нет, тек�т белых занимает обе �троки (`maxLines = 2`, затем многоточие). Сокращение `shortName()` в �том �лучае не примен�ет�� — �то не им�, а название. Результат, е�ли он е�ть, �тоит на линии первой �троки. + - У белых пу�то или `?`, а чёрные е�ть: в �троке белых `?` цветом `onSurfaceVariant`, �троки не мен�ют�� ме�тами. + - �ет обоих: одна �трока `?` цветом `onSurfaceVariant`, втора� пу�та�. +- **Строка подробно�тей**, 14sp (`bodyMedium`), `onSurfaceVariant`: турнир · год · ECO. Пу�тые значени� и `?` пропу�кают�� вме�те � точкой. Справа, в колонке результата, «✓», е�ли парти� уже про�мотрена. Обрезает�� многоточием. +- Тур и чи�ло ходов на телефоне не показывают��: они е�ть в «Сведени�х». +- **Тек�това� глава книги** (ChessBase): вме�то результата значок «¶» на линии первой �троки, название главы занимает две �троки имён (как �тюд), �трока подробно�тей — «Тек�т». �ажатие открывает режим чтени� (§7.9). +- **TalkBack** читает �троку одним узлом (номер больше не отдельный узел): «№ 12. Белые: Карл�ен, Магну�, Эло 2830. Чёрные: Каруана, Фабиано, Эло 2795. 1-0, победили белые. �орвеги�, 2025, C42. Про�мотрена». В опи�ании в�егда полное им� из файла, даже е�ли на �кране короткое. Без результата фраза о нём опу�кает��; у �тюда — «№ 17. Ретти, 1921. Белые начинают и делают ничью. Этюды, 1921». +- �ажатие открывает «Партию». Долгое нажатие — меню: «Поделить�� партией», «Копировать PGN», «Отметить как непро�мотренную» (или «Отметить как про�мотренную»). + +### 6.3. Пои�к + +- ⌕ ра�крывает в верхней панели поле пои�ка (M3 search bar), клавиатура открывает�� �разу. Под�казка в поле: «Игрок, турнир, ECO, год». Пои�к идёт по мере ввода, � задержкой 150 м�. +- Втора� �трока заголовка — «�айдено 34 из 1 248». Е�ли ничего нет: «�ичего не найдено» и кнопка «Сбро�ить пои�к». +- «�азад» и ✕ закрывают поле и �бра�ывают запро� (упрощение по�ле ревью: �о�то�ние «запро� е�ть, пол� нет» ребёнку непон�тно). При возврате из «Партии» пои�к о�таёт�� открытым � тем же запро�ом. + +### 6.4. Сортировка + +⇅ открывает ли�т � радиокнопками. Выбор �разу примен�ет��, и ли�т закрывает��. Варианты: + +- «Как в файле» (по умолчанию); +- «Дата: �начала новые»; +- «Дата: �начала �тарые»; +- «Белые (�–Я)»; +- «Чёрные (�–Я)»; +- «Турнир»; +- «ECO». + +В большой базе �ортировка работает, е�ли найдено не больше 50 000 партий. Иначе пункты неактивны, а над ними �трока «Сначала �узьте пои�к: �ортировка работает, когда найдено не больше 50 000 партий». + +### 6.5. Больша� база (от 20 000 запи�ей) + +``` +┌────────────────────────────────────� +│ � Турниры 2000–2025 ⌕ ⇅ │ +│ �айдено 1 204 из 870 ты�. │ +├────────────────────────────────────┤ +│ [Карл�ен ✕] [2020–2025 ✕] [Фильтры 3]│ 48 чипы; «Фильтры» закреплён �права +├────────────────────────────────────┤ +│ �троки партий… │ +``` + +- **Пои�к ищет игрока** (под�казка «Игрок»). Под полем — до 8 под�казок из �правочника игроков: «Carlsen, Magnus · 3 412 партий». Выбранна� под�казка �тановит�� фильтром «Игрок», поле закрывает��. +- **Ли�т фильтров** открывает�� на в�ю вы�оту. Пол� те же, что в панели фильтров на компьютере: + +``` +┌────────────────────────────────────� +│ ✕ Фильтры Сбро�ить │ 64 +├────────────────────────────────────┤ +│ Игрок │ +│ [Carlsen, Magnus ✕] │ 56 +│ (любым) (белыми) (чёрными) │ �егменты +│ Соперник [ ] │ +│ Турнир или ме�то [ ] │ +│ Годы [ � 2020 ] – [ по 2025 ]│ +│ Эло от [ 2500 ] │ +│ Результат (Выигрыш)(�ичь�)(Проигрыш)│ без игрока: 1-0 ½-½ 0-1 +│ ECO [ B90, B9 или C60-C99 ] │ +│ � � комментари�ми � � вариантами │ +├────────────────────────────────────┤ +│ [ Показать 1 204 ] │ 56 закреплена над клавиатурой +└────────────────────────────────────┘ +``` + + - Чи�ло в кнопке пере�читывает�� в фоне по мере ввода; пока �читает�� — «Показать…» � индикатором. + - �а компьютере фильтр �разу мен�ет таблицу. �а телефоне ли�т закрывает таблицу, по�тому результат примен�ет�� кнопкой. + - «✕» и «назад» закрывают ли�т без применени� изменений. «Сбро�ить» очищает пол�. + - Е�ли найдено 0, кнопка называет�� «�ичего не найдено» и неактивна. +- **Чипы** показывают активные у�лови�. �ажатие на чип открывает ли�т � �тим полем; ✕ на чипе �нимает у�ловие. + +### 6.6. Бы�тра� прокрутка + +- При прокрутке у правого кра� по�вл�ет�� бегунок 6×48 dp � зоной нажати� 48×48. Через 1,5 � без движени� он и�чезает. +- Пока бегунок т�нут, у пальца виден пузырь: при �ортировке по дате — год, в о�тальных �луча�х — «12 340 / 870 ты�.». +- Зона бегунка и�ключена из �и�темного же�та «назад» (`systemGestureExclusion`, только вы�ота бегунка). +- Строки читают�� �траницами. По�ле прыжка на их ме�те �начала видны �ерые заглушки той же вы�оты, потом заполн�ют��; вы�ота �пи�ка не �качет. + +### 6.7. Со�то�ни� �крана + +| Со�то�ние | Что видно | +|---|---| +| База читает�� | линейный индикатор, �троки по�вл�ют�� по мере чтени�, «3 400 партий…», ✕ | +| В базе нет партий | «В �той базе нет партий» | +| �ичего не найдено | «�ичего не найдено» и кнопка «Сбро�ить пои�к» или «Сбро�ить фильтры» | +| База не читает�� | �кран ошибки (§11) | +| Парти� разбирает�� ча�тично | парти� открывает�� �о в�ем, что удало�ь прочитать, и замечани�ми (§7.10) | + +## 7. Экран «Парти�» + +### 7.1. Компоновка, телефон 360×800 + +``` +┌────────────────────────────────────� 24 �трока �о�то�ни� +│ � Norway Chess · 2025 ‹ › ⋮ │ 64 +│ 12 из 340 · тур 5 │ +├────────────────────────────────────┤ +│ � Каруана, Фабиано 2795 0 │ 36 плашка чёрных (§7.11) +├────────────────────────────────────┤ +│ │ +│ ДОСК� │ 360 (клетка 45) +│ 360 × 360 │ +│ │ +├────────────────────────────────────┤ +│ ○ Карл�ен, Магну� 2830 1 │ 36 плашка белых +├────────────────────────────────────┤ +│ �+0.4▌ гл.22 14.Кd5 Сxd5 15.exd5 ▾│ 48 только е�ли движок включён +├────────────────────────────────────┤ +│ 1. e4 e5 │ 48 �троки нотации +│ 2. Кf3 Кc6 │ +│ 3. Сb5 a6 │ +│ ┌ И�пан�ка� парти�. Ход 3…a6 — �│ блок комментари� +│ └ �амый попул�рный ответ. ┘│ +│ 4. ▓Сa4▓ Кf6 │ текущий ход +├────────────────────────────────────┤ +│ Дальше: [5.O-O] (5.Фe2) (5.d3) │ 48 только на развилке +├────────────────────────────────────┤ +│ ▣ ⇅ � ◀ ▶ � │ 72 нижн�� панель +│Движок │ +└────────────────────────────────────┘ 24 поло�а же�тов +``` + +Бюджет вы�оты (� 2026-10-24, � плашками игроков): 800 − 24 − 64 − 36 − 360 − 36 − 72 − 24 = **184 dp** на нотацию, �то 3,8 �троки по 48 dp (без плашек было 256 dp, 5 �трок). Е�ли движок включён (поло�а оценки 3 + �трока 48), о�таёт�� 133 dp; на развилке — ещё на 48 dp меньше. При трёхкнопочной навигации — на 24 dp меньше. Худший �лучай (движок, развилка, три кнопки) — 61 dp, чуть больше одной �троки; до�ка при �том не уменьшает�� — так решил владелец, имена игроков важнее. Длинные тек�ты читают�� в отдельном режиме (§7.9). + +### 7.2. До�ка + +- **Размер и вид.** До�ка во в�ю ширину �крана, без полей и �круглений. По умолчанию тема «Зелёна�» и фигуры Merida (§10.5). +- **Координаты** �то�т внутри крайних клеток, цветом противоположной клетки, как на Lichess. При перевороте они мен�ют�� вме�те � до�кой. +- **Под�ветка.** + - По�ледний ход под�вечен. + - При шахе под королём кра�ное �вечение. + - Стрелки и цветные пол� из комментариев (`[%cal]`, `[%csl]`) показывают�� дл� текущего хода. + - Стрелка лучшего хода движка ри�ует�� �воим цветом. +- **�нимаци�** — §10.8. +- **Ка�ание до�ки.** + - В первой вер�ии до�ка не реагирует на ка�ани�: фигура не выдел�ет��, точек возможных ходов нет, волны ка�ани� (ripple) нет. + - Только при �амом первом ка�ании до�ки по�ле у�тановки показывает�� �некбар «Это про�мотр партии. Ходы ли�тают�� кнопками ◀ ▶ внизу.», и кнопки ◀ ▶ один раз м�гко под�вечивают�� (заливка `primaryContainer` 600 м�). По�ле �того ка�ание до�ки ничего не делает. + - Так мы не обещаем ввода ходов, которого нет, и не путаем человека выделением фигуры. Когда по�в�т�� �вои ветки (§15.2), ка�ание до�ки будет означать «�делать ход», и прежний �мы�л ка�ани� не придёт�� переучивать. +- Свайпов по до�ке нет: у краёв �крана горизонтальный �вайп �порит � �и�темным «назад», а дет�м проще одно правило. +- ~~Плашек � именами игроков над до�кой и под ней нет: имена уже в верхней панели, а ме�то нужнее нотации.~~ **Заменено 2026-10-24:** над до�кой плашка чёрных, под до�кой — белых, как на Lichess; при перевороте они мен�ют�� ме�тами (§7.11). В одной �троке верхней панели р�дом � трем� значками фамили� чёрных ча�то не помещала�ь. + +### 7.3. �отаци�: решение + +**�отаци� вертикальна�, как на компьютере. Ленты ходов нет.** + +- **Почему не лента** (как `MoveList` в режиме `inline` у Lichess): + - в ленту помещает�� 5–6 полуходов, а комментари�м и вариантам ме�та нет; + - наши базы — учебники, �борники � автор�кими тек�тами, партии учеников � пометками тренера, и в них комментарий важнее, чем чи�ло ходов на �кране; + - �ам Lichess на �кране анализа тоже показывает под до�кой полное дерево, а ленту — только в живой партии; + - одна и та же нотаци� на телефоне, планшете и компьютере: тренер объ��н�ет ученику одно и то же. +- **О�новна� лини�** — три колонки: номер хода 40 dp (`onSurfaceVariant`), затем ходы белых и чёрных поровну на о�таток ширины. + - Вы�ота �троки 48 dp; в�� �чейка хода — зона нажати�. + - Ходы 17sp. +- **Комментарий** — блок во в�ю ширину между �троками (§10.4). Е�ли комментарий �тоит по�ле хода белых, ход чёрных перено�ит�� на новую �троку: `4. … Кf6`. Многоточие �тавит�� только в пу�той �чейке белых; пу�та� �чейка чёрных в �троке перед комментарием о�таёт�� пу�той. +- **Левый край.** Блок комментари� и лини� варианта начинают�� в 16 dp от кра� �крана, как �троки �пи�ков; тек�т в них — ещё через 12 dp. +- **Вариант** — блок во в�ю ширину �плошным тек�том: `4.d4 exd4 5.O-O Сe7 (5…Кxe4 6.Лe1)`. + - От�туп 16 dp на каждый уровень вложенно�ти, не больше трёх уровней. Слева вертикальна� лини� 2 dp цвета `outlineVariant`. + - Комментарии внутри варианта набирают�� кур�ивом в той же �троке. + - Меж�трочный интервал 28 dp. Ка�ание выбирает ближайший ход в радиу�е 24 dp от пальца. +- **NAG** �тоит �разу по�ле хода, в цветах Lichess (`assessment_color`). Оценки позиции (`+=`, `∓`) �ерые. Значки ри�уют�� шрифтом `NotoSansMath-nag.ttf` � компьютера, чтобы не было пу�тых квадратов. +- **Запи�ь ходов** берёт�� из на�троек (`display_san`); в режиме «Фигурки» и�пользует�� шрифт `figurines.ttf` � компьютера. +- **Текущий ход** выделен заливкой (§10.3) �о �круглением 6 dp — одинаково в таблице и в тек�те варианта. Выделение переезжает к новому ходу, а не прыгает (§10.9). +- **�втопрокрутка.** Текущий ход держит�� по�ередине видимой нотации, прокрутка 200 м�. Е�ли человек прокрутил нотацию �ам, автопрокрутка возобновл�ет�� �о �ледующего шага. +- **�ачало партии.** Парти� открывает�� в позиции до первого хода: первым виден в�тупительный комментарий, ни одна �чейка не выделена. +- **Конец партии.** По�ле по�леднего хода — �трока результата: «1-0 · Победили белые», «Мат · 1-0» или «Пат · ½-½». +- **Крупный шрифт.** Е�ли при текущем ма�штабе шрифта два хода не помещают�� в �вои колонки, о�новна� лини� тоже набирает�� �плошным тек�том. +- Варианты не �ворачивают��: на компьютере их тоже не �ворачивают, а �пр�танный вариант ученик не найдёт. + +### 7.4. �ижн�� панель + +``` +┌──────┬──────┬──────┬──────────┬──────────┬──────� +│ ▣ │ ⇅ │ � │ ◀ │ ▶ │ � │ 72 dp +│Движок│ │ │ │ │ │ +└──────┴──────┴──────┴──────────┴──────────┴──────┘ + 52 52 52 76 76 52 = 360 +``` + +- **◀ ▶** — �амые широкие кнопки (76 dp, значки 32 dp), они �то�т в правой половине �крана, под большим пальцем. + - Удержание повтор�ет шаг: первый повтор через 400 м�, дальше каждые 120 м�. + - ▶ идёт по текущей линии. ◀ возвращает на предыдущий ход; � первого хода варианта — на ход перед развилкой. +- **�** ведёт к началу партии, **�** — к концу текущей линии. +- **⇅** переворачивает до�ку. +- **Движок** — переключатель � подпи�ью; когда он включён, значок залит, а под ним поло�а `primary` (§8.2). +- �еактивные кнопки (◀ � в начале, ▶ � в конце) �ерые, но о�тают�� на ме�те. +- Ка�ание хода в нотации переводит к �тому ходу. Каждый шаг �опровождает�� лёгкой вибрацией и звуком хода, е�ли они включены в на�тройках. + +### 7.5. Развилки: �трока «Дальше» + +- Е�ли у позиции больше одного продолжени�, над нижней панелью по�вл�ет�� �трока 48 dp: подпи�ь «Дальше:» и чипы ходов � номерами. + - Первый чип — продолжение текущей линии, залитый. О�тальные — варианты, � контуром. + - Е�ли чипы не помещают��, �трока прокручивает�� вбок. +- Ка�ание чипа делает �тот ход. ▶ в�егда равен первому чипу. +- Ме�то под �троку берёт�� у нотации, до�ка не двигает��. + +### 7.6. Со�едн�� парти� + +- **‹ ›** в верхней панели открывают предыдущую и �ледующую партию в том пор�дке, в каком они �то�ли в «Парти�х» при открытии, — � учётом пои�ка, фильтров и �ортировки. «12 из 340» — номер партии в �том пор�дке. +- �ова� парти� открывает�� � начала и �разу отмечает�� про�мотренной. Это тот же �кран, по�тому включённый движок о�таёт�� включённым и �читает её начальную позицию. Е�ли до�ка была перевёрнута, она такой и о�таёт��. +- �а первой партии ‹ неактивна, на по�ледней неактивна ›. +- Парти� �мен�ет�� плавно (§10.8). Стек �кранов не ра�тёт: «назад» ведёт в «Партии». +- Свайпа между парти�ми нет: �лучайно потер�ть ме�то в разобранной партии хуже, чем лишний раз нажать �трелку. +- Парти� из буфера или из файла � одной партией — тоже база в �пи�ке (§4.5, §4.6): «1 из 1», обе �трелки неактивны. + +### 7.7. Верхн�� панель и меню ⋮ + +- � ведёт к «Парти�м». +- ~~Заголовок в две �троки: «Белые – Чёрные» (фамилии, 16sp, 500) и «12 из 340 · 1-0» (14sp, `onSurfaceVariant`).~~ **Заменено 2026-10-24:** имена игроков и результат теперь на плашках у до�ки (§7.11), а заголовок говорит, *что �то за парти� и где она в �пи�ке*: + - **перва� �трока** (16sp, 500, `titleMedium`) — турнир и год: `Norway Chess · 2025`. Е�ли тега `Event` нет (пу�то, `?`), вме�то него `Site`; е�ли нет и его — им� базы (`displayName`), чтобы �трока никогда не была пу�той. Год — из `Date` (`year()`), е�ли он изве�тен. Длинное название турнира обрезает�� многоточием в конце: оно целиком е�ть в «Сведени�х», а в�ё важное дл� чтени� партии — на плашках; + - **втора� �трока** (14sp, `onSurfaceVariant`, `tnum`) — ме�то в �пи�ке и тур: `12 из 340 · тур 5`. Тур показывает��, е�ли в `Round` е�ть что-то кроме пу�то, `?` и `-`. Результата зде�ь больше нет — он на плашках. Эта �трока коротка� и не обрезает��; + - парти� из буфера или файла � одной партией: втора� �трока `1 из 1` (§7.6) — без изменений; + - **ка�ание заголовка** (обе �троки, в�� обла�ть между � и ‹) открывает «Сведени� о партии» (§7.8). Роль — кнопка, опи�ание дл� TalkBack: «Norway Chess, 2025, парти� 12 из 340, тур 5. Сведени� о партии». +- Справа в панели ровно три значка: ‹ › и ⋮. �а�тройки — пункт меню ⋮, отдельной ше�терёнки на �том �кране нет. +- Меню ⋮: + - «Сведени� о партии»; + - «Копировать PGN»; + - «Копировать FEN» — позици� текущего хода; + - «Поделить�� партией»; + - «Замечани� по �овме�тимо�ти PGN» — только е�ли они е�ть; + - «�а�тройки». + +### 7.8. Ли�т «Сведени� о партии» + +``` +┌────────────────────────────────────� +│ ─── │ +│ Карл�ен, Магну� 2830 │ +│ Каруана, Фабиано 2795 │ +│ 1-0 · Победили белые │ +│ │ +│ Турнир Norway Chess │ +│ Ме�то Ставангер │ +│ Дата 03.06.2025 │ +│ Тур 5 │ +│ ECO C42 │ +│ Комментатор Дворецкий │ +│ База Мои партии · 12 из 340│ +│ В�е теги ▾ │ +│ [Копировать PGN] [Поделить��] │ +└────────────────────────────────────┘ +``` + +- Пу�тые пол� и пол� �о значением `?` не показывают��. +- **«Копировать PGN»** копирует PGN партии � комментари�ми в оригинале. Снекбар «PGN �копирован». У «Копировать FEN» — �некбар «FEN �копирован». +- **«Поделить��»** открывает �и�темное окно «Поделить��» � файлом `Karlsen-Caruana-2025.pgn`: имена из тегов латиницей, а е�ли их нет — `game.pgn`. У получател� � ChessPenguin такой файл откроет�� по §4.6. + +### 7.9. Режим чтени� + +- Комментарий длиннее 8 �трок (в�тупление, глава книги) обрезает��: внизу затухание и ��ылка «Читать дальше». +- С�ылка открывает тек�т на ве�ь �кран. Верхн�� панель — «� Комментарий к 14.Кd5» или «� В�тупление». Шрифт 17sp, на планшете �трока не шире 600 dp. Ходы в �том тек�те не нажимают��. +- Тек�това� глава книги из «Партий» �разу открывает�� в �том режиме. + +### 7.10. Замечани� �овме�тимо�ти + +- Е�ли в партии е�ть нулевой ход `--`, FEN � номером хода 0 или нера�познанный фрагмент, в нотации у �того ме�та �тоит значок ⓘ, а в меню ⋮ по�вл�ет�� пункт «Замечани� по �овме�тимо�ти PGN». +- �ера�познанный фрагмент показывает�� как е�ть, моноширинным шрифтом, � подпи�ью «Фрагмент PGN не разобран; о�тавлен как е�ть». +- По�ле `--` в �троке движка напи�ано: «По�ле нулевого хода (--) �то учебна� �хема, а не позици� партии: движок её не �читает». + +### 7.11. Плашки игроков (2026-10-24) + +Решение владельца: как на Lichess — плашка чёрных над до�кой, плашка белых под до�кой. Когда до�ка перевёрнута (⇅), плашки мен�ют�� ме�тами: у каждого кра� до�ки в�егда тот, чьи фигуры �то�т � �того кра�. + +``` + 16 12 8 8 24 16 +┌────────────────────────────────────────────────────────────� +│ � Каруана, Фабиано 2795 0 │ 36 +└────────────────────────────────────────────────────────────┘ + │ │ │ └ результат, titleSmall tnum, вправо + │ │ └ Эло, bodyMedium, onSurfaceVariant, через 8 dp + │ └ им�, titleSmall (14sp/20, 500), onSurface, PlayerName (§6.2) + └ кружок цвета 12 dp +``` + +- **Вы�ота 36 dp**, во в�ю ширину до�ки, от�тупы �лева и �права 16 dp, �одержимое по центру по вертикали. Фон — `surface`, как у �крана: без заливки, рамок и разделителей; край до�ки и так отдел�ет плашку. + - 36, а не 48: в портрете каждые 12 dp — четверть �троки нотации (§7.1). Плашка не нажимает�� (�м. ниже), по�тому правило 48 dp дл� зоны нажати� к ней не отно�ит��. +- **Кружок цвета** 12 dp (`CircleShape`), ри�ует��, а не �имволом ○/� (�имволы в разных шрифтах разного размера и в тёмной теме «белый» кружок выгл�дит дырой). Белые — заливка `#F5F5F0`, чёрные — `#26282B`, те же цвета, что у поло�ы оценки (`EngineViews.kt`). У обоих рамка 1 dp `outline`, чтобы белый был виден на �ветлом фоне, а чёрный — на тёмном. Дл� TalkBack кружок не озвучивает�� отдельно (цвет говорит�� �ловом, �м. ниже). +- **Им�** — `titleSmall` (14sp/20, 500), `onSurface`, правило `PlayerName` из §6.2: полное им� как в файле → е�ли не помещает��, `shortName()` («Фамили� И. О.») → е�ли не помещает�� и так, многоточие в конце. �а 360 dp у имени около 230 dp (≈ 30 знаков), то е�ть почти в�егда видно полное им� — �то един�твенное ме�то на �кране партии, где им� напи�ано целиком. +- **Эло** — �разу по�ле имени через 8 dp, `bodyMedium` (14sp), `onSurfaceVariant`, `tnum`. Только е�ли в `WhiteElo` / `BlackElo` чи�ло больше нул�. Эло не обрезает��, у�тупает им�. +- **Результат** — �права, колонка 24 dp, выравнивание вправо, `titleSmall` + `tnum`: `1` у победител�, `0` у проигравшего, `½` у обоих. Цифра победител� `onSurface`, у `0` и `½` — `onSurfaceVariant`. + - Результат показывает�� **в�егда, когда он изве�тен**, а не только в конце партии: он и так �тоит в �пи�ке партий (§6.2) и раньше �то�л в заголовке; пр�тать его до по�леднего хода — новое �о�то�ние �крана без пользы дл� разбора учебной партии. + - `*` (нет итога, учебна� позици�) — колонка пу�та�. + - Строка результата в конце нотации («1-0 · Победили белые», §7.3) о�таёт�� как е�ть. +- **Ча�ов нет.** В PGN Lichess и Chess.com врем� запи�ано в комментари�х (`[%clk]`), но �дро дл� Android его пока не отдаёт (`GameRow`/`Game` в `crates/mobile-api`), а комментарии показывают�� без �тих меток. Когда ча�ы по�в�т�� (§15.2), они в�танут между Эло и результатом: врем� на ча�ах по�ле текущего хода, `tnum`, без от�чёта. +- **Чей ход** на плашке не отмечает��: �то видно по до�ке и по выделенному ходу в нотации, а лишний под�веченный �лемент �порит � выделением текущего хода. +- **Ка�ание плашки ничего не делает** — как и ка�ание до�ки (§7.2). «Сведени� о партии» открывают�� ка�анием заголовка и из ⋮ (§7.7). Отдельна� зона нажати� 36 dp р�дом � до�кой ловила бы промахи по до�ке и кнопкам, а нажимать её незачем: в�ё, что на ней напи�ано, уже видно. Под�казка о кнопках ◀ ▶ (§7.2) ка�анием плашки не вызывает��. +- **�е хватает тега.** Плашки е�ть в�егда, даже е�ли имён нет: иначе при переходе ‹ › между парти�ми до�ка прыгала бы вверх-вниз. + - Пу�то или `?` у игрока — на ме�те имени �лово «Белые» / «Чёрные» цветом `onSurfaceVariant` (обычное начертание, не 500). Кружок, Эло и результат — как обычно. + - Этюд или позици� из учебника, где в `White` запи�ано название, а в `Black` — `?`: на нижней плашке �то название (одна �трока; `shortName()` не примен�ет��, е�ли у чёрных `?` — �то название, а не им�; иначе многоточие), на верхней — «Чёрные» �ерым. �азвание обычно повтор�ет в�тупительный комментарий, по�тому обрезанный конец не тер�ет��. +- **Предпро�мотр линии движка** (§8.2) плашки не мен�ет: �то те же игроки той же партии. +- **Пор�док под до�кой в портрете**: плашка белых (или чёрных при перевороте) �тоит вплотную под до�кой, под ней — �трока движка � поло�ой оценки 3 dp, панель анализа партии, нотаци�. Поло�а оценки о�таёт�� над �трокой движка, как �ейча�: она ча�ть �троки движка, а не кра� до�ки. +- **�льбомна� ориентаци� и планшеты** (§13): е�ли плашки по�тавить над до�кой и под ней, до�ка в альбомной ориентации �тала бы на 72 dp меньше. По�тому там, где до�ка �тоит �лева, плашки уход�т в правую колонку, как на Lichess в широком окне: верхн�� плашка — первой �трокой колонки (над �трокой движка), нижн�� — по�ледней �трокой над панелью кнопок. Их пор�док тот же: �верху тот, чьи фигуры у верхнего кра� до�ки. В портрете на планшете (§13.2) плашки над до�кой и под ней, шириной � до�ку (вме�те � вертикальной шкалой оценки), по центру. +- **TalkBack.** Плашка — один узел (`clearAndSetSemantics`): «Чёрные: Каруана, Фабиано, Эло 2795, проигрыш» / «Белые: Карл�ен, Магну�, Эло 2830, выигрыш»; при ничьей «ничь�»; без результата — без по�леднего �лова; без имени — про�то «Чёрные». В�егда полное им� из файла. Пор�док обхода — по �крану: верхн�� плашка, до�ка, нижн�� плашка. +- **Крупный шрифт.** Вы�ота плашки — `heightIn(min = 36.dp)`: при ма�штабе шрифта больше 1,3 она ра�тёт вме�те � тек�том, им� о�таёт�� в одну �троку и �окращает�� по тому же правилу. + +## 8. Движок + +### 8.1. Две �борки + +| Сборка | Что внутри | Кнопка «Движок» | +|---|---|---| +| **С движком** | Stockfish 19 и его нейро�еть | работает �разу, без �ети | +| **Без движка** | без нейро�ети Stockfish, она �качивает�� по запро�у (~80 МБ) | при первом ка�ании предлагает �качать (§8.4) | + +- У обеих �борок один идентификатор пакета и один ключ подпи�и. По�тому одну можно по�тавить поверх другой, базы и на�тройки �охран�т��. + - Сборка � движком поверх �борки без движка: при первом запу�ке �качанна� нейро�еть удал�ет��, ме�то о�вобождает��. + - Сборка без движка поверх �борки � движком: движок �нова предлагает�� �качать. +- Техниче�ки в �борке «без движка» программа Stockfish (1–2 МБ) в�ё равно внутри, а �качивает�� его нейро�еть (данные, не код; �м. `android-stack.md` §5). Пользователь �того не видит: дл� него �качивает�� «движок». +- В «О программе» по�ле вер�ии указана �борка теми же �ловами, что на �айте (§16): «0.9.0 · Stockfish уже внутри» или «0.9.0 · Stockfish �качивает�� в приложении». +- **Подпи�и на �айте и в релизе на GitHub:** + + | Файл | RU | EN | + |---|---|---| + | `ChessPenguin-<вер�и�>-android.apk` | **Stockfish уже внутри** · ≈ 95 МБ — оценка и лучшие ходы �разу, без интернета. | **Stockfish built in** · ≈ 95 MB — evaluation and best moves right away, no internet needed. | + | `ChessPenguin-<вер�и�>-android-noengine.apk` | **Stockfish �качивает�� в приложении** · ≈ 15 МБ — движок (80 МБ) можно �качать, когда понадобит��. | **Stockfish downloaded in the app** · ≈ 15 MB — the engine (80 MB) can be downloaded when you need it. | + + Размеры — оценка из `android-stack.md`, в релизе пишут�� на�то�щие. �а �айте главна� кнопка — «Stockfish уже внутри», втора� — ��ылкой под ней. + +### 8.2. Что видно в партии + +- **Движок выключен** — �троки движка нет, значок на кнопке контурный. +- **Движок включён** — между до�кой и нотацией �трока 48 dp: + +``` +│ �+0.4▌ гл.22 14.Кd5 Сxd5 15.exd5 … ▾│ +``` + - Плашка оценки 56×28 dp, рамка 1 dp цвета `outline`, чтобы �ветла� плашка не �ливала�ь �о �трокой. При переве�е белых она �ветла� (`#F5F5F0`, тек�т `#1C1D1F`), при переве�е чёрных — тёмна� (`#26282B`, тек�т `#E8E8E8`). Значени�: «+0.4», «−1.2», «#3», «#−2», цифры моноширинные. + - По верхнему краю �троки поло�а 3 dp: дол� белых �лева, а при перевёрнутой до�ке �права. + - Глубина «гл. 22» цветом `onSurfaceVariant`. + - Лучша� лини� — в запи�и ходов из на�троек, хво�т обрезает�� многоточием. + - ▾ ра�крывает �троку: до 3 линий по 40 dp, �колько задано в «Линий» (по умолчанию 2). �отаци� при �том �тановит�� короче. ▴ �ворачивает обратно. ▾ о�таёт�� и на паузе, р�дом � «Глубже». + - Стрелка второй линии ри�ует�� тем же цветом, но бледнее (прозрачно�ть 35 % против 63 % у лучшей) — находка реализации. + - В �борке � движком при первом включении, пока движок ра�паковывает��, на ме�те �троки — «Готовлю движок…» � маленьким индикатором. +- �а телефоне в портрете вертикальной шкалы оценки нет: она отн�ла бы ширину у до�ки. В альбомной ориентации и на планшете шкала 12 dp �тоит �лева от до�ки, как на компьютере. + +### 8.3. Правила + +- **�ова� позици� — пу�та� �трока.** При любом переходе �трока показывает «Считаю…» и пу�тую плашку, пока движок не ответит про новую позицию. Стара� оценка не показывает�� ни на миг. +- **Предпро�мотр линии.** + - Ка�ание линии показывает на до�ке её первый ход. �ад нотацией по�вл�ет�� поло�а 48 dp «Лини� движка · ход 1 из 12 [✕]» (фон `primaryContainer`, тек�т `onPrimaryContainer`). Показанный ход под�вечивает�� в тек�те линии заливкой текущего хода. + - Пока поло�а видна, ◀ ▶ ли�тают �ту линию, а � возвращает к позиции партии. + - Из предпро�мотра вывод�т ✕, «назад» и ка�ание хода в нотации. + - Парти� при �том не мен�ет��. В�тавить линию как вариант в первой вер�ии нельз�. +- **Врем�.** По умолчанию движок �читает позицию 20 �, потом о�танавливает��: в �троке «гл. 26 · пауза» и кнопка «Глубже» (ещё 20 �). Другие значени� на�тройки «Врем� на позицию»: 10 �, 1 мин, без ограничени�. +- **Батаре�.** + - Е�ли �кран пога� или приложение ушло в фон, движок о�танавливает��, проце�� завершает��, а кнопка выключает��: по�ле возврата движок ждёт нажати�. + - Е�ли поверх партии открыты �а�тройки (меню ⋮) или телефон повернули, проце�� тоже о�танавливает��, но кнопка о�таёт�� включённой: по�ле возврата �чёт начинает�� заново �ам. + - При включённой �кономии зар�да движок работает в один поток; один раз показывает�� �некбар «Экономи� зар�да: движок работает медленнее». +- **Сбои.** Запу�к и о�тановка идут � таймаутами (`docs/dev/uci.md`). + - Движок не отвечает — «Движок не отвечает» и кнопка «Перезапу�тить». + - Движок не запу�кает�� на �том проце��оре — «Движок не запу�кает�� на �том телефоне». +- **Кнопка не запоминает�� между парти�ми** (� 2026-10-23; раньше �о�то�ние хранило�ь в на�тройках). Каждый раз, когда парти� открывает�� из �пи�ка, движок выключен; включает�� он только кнопкой. Выход из партии («назад») выключает его. ‹ › внутри партии его не выключают (§7.6). + - Причина: движок, включённый вчера, не должен �ам �адить батарею при каждом открытии партии, а ребёнок �начала �мотрит партию и только потом �прашивает оценку. +- Лицензи� Stockfish (GPL-3) и его авторы указаны в «О программе». + +### 8.4. Скачивание движка (�борка без движка) + +**Где предлагает��** — только в двух ме�тах, и только когда человек �ам �того захотел: + +1. Ка�ание кнопки «Движок» в партии. До �качивани� значок на кнопке контурный, �о �трелкой загрузки в углу (`download`). +2. �а�тройки → «Движок» → «Скачать (80 МБ)». + +При запу�ке приложени�, в �пи�ках и в под�казках �качать движок не предлагает��. + +**Ли�т «Движок Stockfish»:** + +``` +┌────────────────────────────────────� +│ ─── │ +│ Движок Stockfish │ 22sp +│ │ +│ Оценивает позицию и показывает │ +│ лучшие ходы. Работает без интернета│ +│ — нужно один раз �качать. │ +│ │ +│ Размер: 80 МБ │ +│ ⚠ Сейча� нет Wi-Fi: загрузка пойдёт│ только е�ли �еть платна� +│ через мобильный интернет. │ +│ │ +│ [�е �ейча�] [Скачать] │ +└────────────────────────────────────┘ +``` + +**Ход �качивани�:** + +| Шаг | Что видно | +|---|---| +| Идёт загрузка | Ли�т: поло�а прогре��а и «Скачано 23 из 80 МБ», кнопка «Отменить». Ли�т можно закрыть — загрузка продолжит��; на кнопке «Движок» вокруг значка кольцо прогре��а. Повторное ка�ание кнопки �нова открывает ли�т � прогре��ом. | +| Приложение �вёрнуто | Загрузка продолжает�� (WorkManager, длительна� задача � уведомлением о ходе). Разрешение на уведомлени� не �прашиваем: без него загрузка идёт, про�то уведомление не видно. | +| Отменено | Ли�т закрывает��, �некбар «Загрузка отменена». Скачанна� ча�ть �охран�ет��, �ледующа� загрузка продолжит�� � того же ме�та. | +| Готово | Файл провер�ет�� по SHA-256. Снекбар «Движок готов». Е�ли загрузку начали кнопкой в партии, движок �разу включает��. | +| �ет �ети | «�ет интернета. Подключите�ь к �ети и попробуйте ещё раз.» [Повторить] | +| Сеть оборвала�ь | «Загрузка прервала�ь. Скачанное �охранено.» [Продолжить] | +| �ет ме�та | «�е хватает ме�та: нужно 80 МБ.» [Пон�тно] | +| Файл повреждён (не �овпала �умма) | «Файл движка повреждён при загрузке. Скачайте его ещё раз.» [Скачать �нова] | + +- Е�ли загрузка не закончена, кнопка «Движок» открывает ли�т � её �о�то�нием. Строка движка в партии не по�вл�ет��, пока движок не готов. +- В �а�тройках у �качанного движка �трока «Stockfish 19 · �качан» и пункт «Удалить движок (о�вободит 80 МБ)», � подтверждением: «Удалить движок? Его можно �качать �нова.» — «Отмена» / «Удалить». +- В�е размеры в ли�те, в на�тройках и в ошибках берут�� из �борки (`{size}`, �ейча� 98 МБ), а не пишут�� чи�лом 80. +- И�точник файла и его �умма закреплены в приложении. Это решение разработчика, как в `engine-download.md`; в интерфей�е адре� не показывает��. + +## 9. �а�тройки + +�а�тройки — один �кран �о �пи�ком групп, без вкладок. Изменени� примен�ют�� �разу. + +**Как �делано �ейча�** (звука пока нет; выбор до�ки и фигур — � 2026-10-23, §9.1): + +``` +┌────────────────────────────────────� +│ � �а�тройки │ +├────────────────────────────────────┤ +│ П�РТИЯ │ +│ Запи�ь ходов │ +│ Латин�кие буквы (K Q R B N) │ +│ �нимаци� фигур [�] │ +│ Стрелка лучшего хода [�] │ +│ Вибраци� [�] │ +├────────────────────────────────────┤ +│ В�ЕШ�ИЙ ВИД │ +│ До�ка и фигуры │ отдельный �кран, §9.1 +│ Зелёна� · merida │ +│ Тема │ +│ Как в �и�теме │ +│ Язык │ +│ Как в �и�теме │ +├────────────────────────────────────┤ +│ ДВИЖОК │ +│ Stockfish 19 · в�троен │ 14sp, onSurfaceVariant, без нажати� +│ Линий 2 │ +│ Врем� на позицию 20 � │ +│ Дополнительно │ Потоки, Пам�ть — диалог или под�кран +│ Движок ра�ходует зар�д. Он �ам │ +│ о�танавливает��, когда га�нет �кран.│ +├────────────────────────────────────┤ +│ О программе │ +└────────────────────────────────────┘ +``` + +- Группа называет�� «Парти�» (`s_game_group`, en «Game»): запи�ь ходов, анимаци�, �трелка и вибраци� отно��т�� к про�мотру партии, а не к до�ке. +- Строка «Stockfish 19 · в�троен» — �о�то�ние, а не пункт: набирает�� 14sp цветом `onSurfaceVariant`, чтобы не выгл�деть нажимаемой. +- У пункта «О программе», когда вышла нова� вер�и�, втора� �трока цветом `primary`: «Вышла вер�и� 0.15.0» (§25.5). Она е�ть и при выключенных предложени�х: �то не предложение, а �ведени� там, где их ищут. Блок «Обновлени�» — на �кране «О программе». + +Полна� �хема на будущее (звук, координаты, цвета обоев). До�ка и фигуры в ней теперь — одна �трока «До�ка и фигуры» из §9.1, а не две: + +``` +┌────────────────────────────────────� +│ � �а�тройки │ +├────────────────────────────────────┤ +│ ДОСК� │ +│ [▦] До�ка Зелёна� ›│ �кран � �еткой превью +│ [♞] Фигуры Merida ›│ �кран � �еткой превью +│ Запи�ь ходов Латин�кие ›│ диалог � образцами +│ Координаты [�] │ +│ �нимаци� фигур [�] │ +│ Стрелка лучшего хода [�] │ +├────────────────────────────────────┤ +│ ЗВУК И ОТКЛИК │ +│ Звук ходов [�] │ +│ Вибраци� [�] │ +├────────────────────────────────────┤ +│ В�ЕШ�ИЙ ВИД │ +│ Тема Как в �и�теме ›│ +│ Цвета обоев [ ] │ Material You, по умолчанию выкл. +│ Язык Как в �и�теме ›│ +├────────────────────────────────────┤ +│ ДВИЖОК │ +│ Stockfish 19 · в�троен │ или «�е �качан · Скачать (80 МБ)» +│ Линий 2 ›│ 1 / 2 / 3 +│ Врем� на позицию 20 � ›│ +│ Дополнительно ›│ Потоки, Пам�ть +│ Движок ра�ходует зар�д. Он �ам │ 14sp, onSurfaceVariant +│ о�танавливает��, когда га�нет �кран.│ +├────────────────────────────────────┤ +│ О программе ›│ вер�и� и �борка, лицензии, авторы +└────────────────────────────────────┘ +``` + +- **До�ка и фигуры** — §9.1. +- **Запи�ь ходов** — диалог � трем� вариантами и образцами, как в `move-notation.md` §2.1: «Латин�кие буквы (K Q R B N)», «Фигурки», «Ру��кие буквы (Кр Ф Л С К)». Под ними: «Только вид на �кране. В PGN и при копировании в�егда K Q R B N.» По умолчанию — латин�кие буквы. В англий�ком интерфей�е третьего варианта нет. +- **�нимаци� фигур** только включает�� и выключает��. Четыре �коро�ти, как на компьютере, телефону не нужны. +- **�абора звуков** нет: и�пользует�� набор по умолчанию � компьютера (`sfx`). В беззвучном режиме звука нет. +- **Тема:** «Как в �и�теме» (по умолчанию), «Светла�» или «Тёмна�». +- **Цвета обоев** — §10.3. +- **Язык:** «Как в �и�теме» и ше�ть �зыков компьютера (English, Ру��кий, Français, Deutsch, Español, Italiano). Язык задаёт�� через `AppCompatDelegate.setApplicationLocales`: на Android 13+ тот же выбор виден в �и�темных на�тройках приложени�, на Android 12 работает внутри приложени�. Е�ли �зык �и�темы не из �тих ше�ти, интерфей� на англий�ком. +- **Движок → Дополнительно:** «Потоки» — от 1 до чи�ла �дер, по умолчанию половина, но не больше 2 (� 0.11.2; раньше 4): интерфей�у телефона о�таёт�� ме�то. У тех, кто не мен�л �тарое значение по умолчанию, оно замен�ет�� новым. «Пам�ть» — 16, 32, 64, 128 или 256 МБ, по умолчанию 64. +- «Скачать» в на�тройках открывает тот же ли�т «Движок Stockfish» (§8.4), а не начинает загрузку молча: в ли�те е�ть предупреждение о мобильном интернете и отмена. +- Строка �о�то�ни� движка зави�ит от �борки и §8.4: «Stockfish 19 · в�троен», «�е �качан · Скачать (80 МБ)», «Скачивает��… 23 из 80 МБ» или «Stockfish 19 · �качан» � пунктом «Удалить движок». + +### 9.1. Экран «До�ка и фигуры» + +Пункт «До�ка и фигуры» в группе «Внешний вид», первым. Под названием — текущий выбор: «Зелёна� · merida» (им� до�ки, точка, им� набора). Открывает отдельный �кран; «назад» возвращает в �а�тройки. + +``` +┌────────────────────────────────────� +│ � До�ка и фигуры │ +├────────────────────────────────────┤ +│ ┌──────────� │ превью: и�пан�ка� парти� по�ле 3.Сb5, +│ │ ♜ �♛♚�♞♜ │ │ под�вечен ход f1–b5; не нажимает�� +│ │ …… │ │ +│ └──────────┘ │ +│ До�ка │ Фигуры │ вкладки (SecondaryTabRow) +├────────────────────────────────────┤ +│ [▚] [▚] [▚] [▚] │ «До�ка»: 2×2 клетки или угол картинки +│ Коричн. Син�� Зелёна� Турнирна� │ +│ … │ 37 до�ок +│ │ «Фигуры»: белый конь на �ветлой клетке, +│ │ чёрный ферзь на тёмной; 17 наборов +└────────────────────────────────────┘ +``` + +- **Превью �тоит на ме�те**, �етка прокручивает�� под ним. В портрете — по центру, 60 % ширины �крана, но не больше 240 dp, � пол�ми 12 dp �верху и �низу. В альбомной ориентации превью занимает левую ча�ть (пол� 16 dp), �етка — правую. +- Превью — на�то�ща� до�ка приложени� (`Board`) � выбранными до�кой и фигурами, без анимации и без ка�аний. Дл� TalkBack — «До�ка: Зелёна� · merida». +- **Сетка** — `LazyVerticalGrid`, �чейки от 88 dp (на телефоне 360–412 dp — четыре в р�д), пол� 12 dp по бокам. �ад �еткой две вкладки, «До�ка» и «Фигуры» (en Board / Pieces): наборы не пр�чут�� под 37 до�ками. Пор�док — как на компьютере (§10.5). + - **До�ка** — квадрат: 2×2 клетки её цветов (a1 тёмна�, �лева внизу) или, у тек�турных, левый нижний угол картинки 2×2 клетки. Скругление 6 dp. Под ним название до�ки, `bodySmall`, не больше двух �трок. Одинаковые названи� различают�� номером: «Дерево», «Дерево 2», «Дерево 3». + - **�абор фигур** (вкладка «Фигуры») — пр�моугольник 2:1: белый конь на �ветлой и чёрный ферзь на тёмной клетке **выбранной до�ки** (так тёмные наборы о�тают�� видны, и человек �разу видит итог). Под ним им� набора как на компьютере и на Lichess — латиницей, �трочными (`cburnett`, `kiwen-suwi`); имена наборов не перевод�т��. +- **Выбор примен�ет�� �разу** и �охран�ет��, кнопок «Готово» и «Отмена» нет. Превью, а за ним и до�ка в партии мен�ют�� мгновенно. +- **Выбранный �лемент** — кольцо 3 dp цветом `primary` вокруг образца (образец внутри уменьшает�� на 5 dp, чтобы кольцо не налезало на клетки) и подпи�ь цветом `primary`. О�тальные подпи�и — `onSurfaceVariant`. +- Каждый �лемент — `selectable` � ролью «переключатель» (`Role.RadioButton`): TalkBack читает «Зелёна�, выбрано, переключатель». Вкладки TalkBack читает как вкладки. +- По умолчанию — «Зелёна�» и merida (§10.5). + +## 10. Внешний вид + +Цель — «про�то, пон�тно, �импатично». Сред�тва: те же цвета, до�ки и фигуры, что на компьютере и �айте, Material 3 � тональными поверхно�т�ми вме�то теней, крупна� до�ка как главный предмет �крана и немного аккуратного движени�. �икаких фоновых картинок, градиентов, �модзи и тем «под дерево» в интерфей�е: фактура бывает только у до�ки. + +### 10.1. От�тупы + +Сетка 4 dp. И�пользуют�� только значени� 4, 8, 12, 16, 24 и 32. + +- Пол� �крана �лева и �права 16 dp. У �трок �пи�ков 16 dp по горизонтали, у значка и тек�та — 16 dp между ними. +- Между группами на�троек 24 dp, над заголовком группы 16 dp. +- В ли�тах: пол� 24 dp, между ручкой и заголовком 16 dp. +- У блоков нотации внутренние пол� 12 по горизонтали и 8 по вертикали; между блоками 8 dp. + +### 10.2. Шрифт + +- Интерфей� набирает�� �и�темным шрифтом (`FontFamily.Default`, на большин�тве телефонов �то Roboto). Свой шрифт не в�траиваем: �и�темный е�ть в любом �зыке, знаком человеку и бе�платен по размеру. +- В�траиваем два шрифта � компьютера: `figurines.ttf` дл� режима «Фигурки» и `NotoSansMath-nag.ttf` дл� значков NAG (`⩲ ∓ ⨀`). Лицензи� OFL, `apps/desktop/assets/fonts/OFL.txt`. +- Шкала шрифтов (M3; размер / меж�трочный интервал / на�ыщенно�ть): + +| Роль | Где | sp | +|---|---|---| +| `titleLarge` | заголовки �кранов, ли�тов, пу�тых �о�то�ний | 22 / 28 / 400 | +| заголовок партии, 1-� �трока | верхн�� панель «Парти�» (`titleMedium`) | 16 / 24 / 500 | +| `bodyLarge` | им� базы, �трока партии, пункты на�троек | 16 / 24 / 400 | +| `bodyMedium` | вторые �троки, подпи�и | 14 / 20 / 400 | +| `labelLarge` | кнопки, чипы | 14 / 20 / 500 | +| `labelSmall` | подпи�и нижней панели, «гл. 22» | 12 / 16 / 500 | +| ход в нотации | о�новна� лини� | 17 / 24 / 500 | +| номер хода | о�новна� лини� | 15 / 24 / 400 | +| комментарий, вариант | нотаци� | 15 / 22 (у варианта 28) / 400 | +| оценка | плашка движка | 15 / 20 / 700 | + +- В�е чи�ла, которые мен�ют�� на ме�те (оценка, глубина, �чётчики, результат), набирают�� моноширинными цифрами (`fontFeatureSettings = "tnum"`), чтобы тек�т не дёргал��. + +### 10.3. Цвета + +**Решение: по умолчанию �вои цвета, как на компьютере и �айте. «Цвета обоев» (Material You) — на�тройка, по умолчанию выключена.** + +- Почему �вои цвета: телефон, компьютер и �айт выгл�д�т как одна программа, и тренер, показыва� ученику, видит те же цвета. Кроме того, цвета NAG и выделени� хода подобраны под нашу палитру, а �лучайные обои могут �делать их невидимыми. +- Е�ли включить «Цвета обоев», палитру из обоев (`dynamicLight/DarkColorScheme`) получают только панели, кнопки, чипы и переключатели. До�ка, фигуры, NAG, цвет комментариев, выделение текущего хода и плашка оценки в�егда �вои. + +Свои цвета, роли M3. Цвета вз�ты из токенов �айта (`website/`) и цветов комментариев и выделени� в `notation.rs`: + +| Роль | Светла� | Тёмна� | +|---|---|---| +| `background` | `#FFFFFF` | `#161718` | +| `surface` | `#FFFFFF` | `#161718` | +| `surfaceContainerLow` (блоки комментариев, ли�ты) | `#F5F6F7` | `#1F2022` | +| `surfaceContainer` (верхн�� панель при прокрутке, нижн�� панель) | `#EEF0F2` | `#232427` | +| `surfaceContainerHigh` (меню, диалоги) | `#E8EAED` | `#2A2C2F` | +| `onSurface` | `#1C1D1F` | `#E8E8E8` | +| `onSurfaceVariant` | `#5D636B` | `#A3A7AD` | +| `outline` | `#C4C8CD` | `#4A4D52` | +| `outlineVariant` | `#E1E3E6` | `#2E3033` | +| `primary` | `#1F6FA8` | `#62AEE6` | +| `onPrimary` | `#FFFFFF` | `#0B2A40` | +| `primaryContainer` | `#D6E8F6` | `#1A4566` | +| `onPrimaryContainer` | `#1A5F91` | `#D6E8F6` | +| `error` | `#C42B1C` | `#F28B82` | +| `errorContainer` | `#FCE4E1` | `#5C1A14` | +| текущий ход (заливка) | `#90D1FF` | `#005C80` | +| тек�т комментари� | `#2A5B8A` | `#9EC4E0` | +| NAG `!` `?` `!!` `??` `!?` `?!` | `#4E7F22` `#A35F00` `#12806F` `#C23B3B` `#B0259F` `#1F72A8` | цвета `assessment_color` (Lichess): `#629C2E` `#E68F00` `#22AC9A` `#DF5353` `#EA45D8` `#56B4E9` | + +Цвета Lichess на белом фоне дают контра�т 2,3–3,8:1, по�тому в �ветлой теме те же оттенки затемнены до 4,8–5,8:1. �а заливке текущего хода значок NAG набирает�� цветом тек�та хода (`onSurface`): цветной значок на голубой заливке не читает�� ни в одной теме (1,4–3,2:1). + +Контра�т тек�та и фона не ниже 4,5:1, включа� `onSurfaceVariant` и цвет комментари�. Разработчик провер�ет �то на обеих темах. + +**Цвета видов баз** (плашки на «Базах», в ли�те «Добавить базу» и при выборе файла) — из Catppuccin: Mocha в тёмной теме, Latte в �ветлой (решение владельца 2026-10-26). PGN — blue, ChessBase — peach, архивы — mauve, �качанные � Lichess и Chess.com — teal, �вои базы и база игрока — green; фон — подкра�ка того же оттенка, контра�т не ниже 5:1. Таблица — `android-lists.md` §5.1, код — `kindColor` в `theme/Color.kt`. Это метки, как NAG: «Цвета обоев» их не мен�ют. Цвета кружков �торон в �пи�ке партий — `android-lists.md` §3.2. + +### 10.4. Поверхно�ти, вы�оты, �круглени� + +- **Теней нет**, кроме ли�тов � затемнением фона. Вме�то теней — тональные поверхно�ти. Верхн�� панель при прокрутке мен�ет `surface` на `surfaceContainer` (M3 `pinnedScrollBehavior`). +- **Скруглени�:** + - текущий ход — 6 dp; + - плашка оценки, чипы, пол� ввода — 8 dp; + - блок комментари� — 12 dp; + - кнопки — полно�тью �круглённые (M3 по умолчанию); + - диалоги и верх ли�тов — 28 dp; + - карточки групп (базы, на�тройки) — 16 dp �наружи и 4 dp там, где карточки �о�ед�твуют; кнопки «Играть � Maia» и «�ова� парти�» — 16 dp; + - плашки видов баз — 10 dp; плашка результата в �пи�ке партий — 6 dp; метка ECO — 4 dp; + - до�ка на телефоне — 0 (во в�ю ширину), на планшете — 8 dp. +- **Блок комментари�** — фон `surfaceContainerLow`, без рамки. **Блок варианта** — без фона, только лини� �лева. +- Разделители — только в длинных �пи�ках: 1 dp `outlineVariant` между �троками партий (§6.2, `android-lists.md` §3.5) и лини� между нотацией и нижней панелью. Короткие �пи�ки (базы, на�тройки) группируют�� карточками `surfaceContainerLow` � зазором 2 dp (`android-lists.md` §5.3). Правило изменено 2026-10-26: раньше разделителей не было нигде. + +### 10.5. До�ки и фигуры + +- Те же файлы и цвета, что на компьютере: темы до�ок из `assets.rs` (`BoardThemeId`: цветные и тек�турные из `apps/desktop/assets/boards`) и 17 наборов фигур из `apps/desktop/assets/pieces`. Пор�док и названи� — как в на�тройках компьютера; названи� до�ок переведены на ше�ть �зыков интерфей�а, имена наборов — нет. Выбор — §9.1. +- **По умолчанию на телефоне — до�ка «Зелёна�» (`Green`: `#FFFFDD` / `#86A666`) и фигуры Merida.** Так играет �ам владелец. Пло�ка� зелёна� до�ка �покойна, хорошо читает�� на �олнце и не �порит � цветными �трелками, а Merida привычна по книгам. �а компьютере значени� по умолчанию о�тают�� прежними. +- Тек�турные до�ки на телефоне ма�штабируют�� под размер до�ки один раз и к�шируют�� как картинка. +- Цвета �трелок и полей из комментариев (зелёный, кра�ный, жёлтый, �иний) и �трелка движка — как в `board.rs`. + +### 10.6. Значки + +- Material Symbols Rounded, толщина 400, размер 24 dp; у ◀ ▶ значки 32 dp. Обычное �о�то�ние — контурный значок (fill 0), включённое — залитый (fill 1). + +| Дей�твие | Symbol | +|---|---| +| назад по �крану | `arrow_back` | +| ход назад / вперёд | `play_arrow`, дл� «назад» отражённый (залитые треугольники 32 dp). `arrow_left`/`arrow_right` �лишком узкие: даже в 44 dp треугольник около 9×14 dp и выгл�дит �лабее � � | +| в начало / в конец линии | `first_page` / `last_page` | +| предыдуща� / �ледующа� парти� | `chevron_left` / `chevron_right` (тонкие уголки, только в верхней панели) | +| перевернуть до�ку | `swap_vert` | +| движок | `memory`; в �борке без движка до �качивани� — �о значком `download` в углу | +| меню | `more_vert` | +| пои�к / �ортировка / фильтры | `search` / `sort` / `filter_list` | +| добавить базу | `add` | +| файл / папка / в�тавить | `description` / `folder_open` / `content_paste` | +| поделить�� / копировать | `share` / `content_copy` | +| на�тройки | `settings` | +| про�мотрена | `check` | +| замечание �овме�тимо�ти | `info` | +| ошибка | `error` | + +- Ход и парти� различают�� формой значков: у хода — залитые треугольники крупно внизу, у партии — тонкие уголки мелко вверху. +- Плашка формата базы — не значок, а тек�т `PGN`, `CB`, `ZIP` или `7Z` (`labelSmall`, 500) в �круглённом квадрате 40 dp (10 dp) цвета вида базы (§10.3, `android-lists.md` §5.1). Это пон�тнее любого ри�унка файла. У �качанной базы вме�то тек�та значок `cloud_download`, у �воей — `edit_note`, у базы игрока — `♞`. + +### 10.7. Значок приложени� и за�тавка + +- **И�точник** — пингвин � королём � компьютера (`apps/desktop/assets/icon-256.png`). И�ходник вы�окого разрешени� — `icons/icon1.png` (1254 px); разработчик �вер�ет его � `icon-256.png`. Ри�унок не мен�ем. +- **�даптивный значок** (`mipmap-anydpi-v26/ic_launcher.xml`): + - передний �лой — пингвин, впи�анный в безопа�ный круг 66 dp на хол�те 108 dp (вы�ота фигуры около 62 dp), без �воего фона; + - фоновый �лой — ровный цвет `#EAF2F9`, �ветло-голубой. Чёрный пингвин и оранжевый клюв на нём читают�� и в �ветлом, и в тёмном лаунчере; + - монохромный �лой дл� тематиче�ких значков Android 13+ — �илу�т пингвина � вырезанным королём, один цвет, вектор. Его ри�уют по �илу�ту `icon1.png`; �то задача на отри�овку, а не на программирование. +- **За�тавка Android 12:** передний �лой значка на фоне `background` темы (`#FFFFFF` или `#161718`), под значком круг `#EAF2F9` (`windowSplashScreenIconBackgroundColor`). Значок не анимирует��. + +### 10.8. Движение + +| Что | Как | Длительно�ть | +|---|---|---| +| ход фигуры на до�ке | перемещение, `FastOutSlowIn`, как «Обычно» на компьютере (длительно�ти Lichess) | 250 м� | +| прыжок больше чем на один ход (ка�ание хода, � �) | без анимации, �разу нова� позици� | 0 | +| вз�тие | вз�та� фигура га�нет, пока подходит друга� | 250 м� | +| переход на �кран глубже / назад | M3 shared axis X: �двиг на 30 dp и про�вление | 300 м� | +| �мена партии через ‹ › | перекрё�тное ра�творение до�ки и нотации | 150 м� | +| �трока движка по�вл�ет�� и уходит | выезжает из-под до�ки, нотаци� �двигает�� | 200 м� | +| оценка мен�ет�� | плашка и поло�а плавно мен�ют значение | 300 м� | +| ли�ты, меню, �некбары | �тандартные M3 | — | + +Е�ли в �и�теме выключены анимации (ма�штаб длительно�ти 0), выключают�� и наши; ходы показывают�� �разу. + +### 10.9. �емного тепла + +�е�колько деталей, из-за которых приложение при�тно в руке. �ичего из �того не добавл�ет кнопок. + +1. **Выделение хода переезжает.** Заливка текущего хода плавно перемещает�� от �чейки к �чейке (150 м�), а не мигает. Глаз �ам ведёт по партии. +2. **Вибраци� �о �мы�лом.** �а каждом шаге лёгкий тик (`CLOCK_TICK`), в начале и в конце партии — чуть �ильнее (`CONFIRM`): пон�тно, что дальше ходов нет, даже не гл�д�. +3. **Результат как печать.** По�ле по�леднего хода — �трока результата в �круглённой плашке `surfaceContainerHigh` по центру: «1-0 · Победили белые». +4. **Пингвин на пу�тых �кранах.** Тот же значок в�тречает на пу�том �кране «Базы» и в «�ичего не найдено» (там в половинном размере, 48 dp). �икакой другой графики нет. +5. **Превью — на на�то�щей до�ке.** �ад выбором �тоит до�ка � позицией и выбранными до�кой и фигурами, а образцы фигур нари�ованы на клетках выбранной до�ки: человек видит итог, а не образец (§9.1). +6. **Тиха� вежливо�ть.** Под�казка про кнопки показывает�� один раз. «Убрать из �пи�ка» отмен�ет��. Движок �ам �еб� выключает. �ичего не в�плывает без причины. + +## 11. Со�то�ни� и ошибки + +| Ситуаци� | Где | Тек�т | Дей�твие | +|---|---|---|---| +| �ет баз | Базы | «Зде�ь будут ваши базы» | «Добавить базу», «Открыть примеры партий» | +| База читает�� | �трока базы, Партии | «читаю… 3 400» | ✕ «О�тановить чтение» | +| Очень больша� база | диалог | «Очень больша� база: {n} партий…» | «В�ё равно открыть» / «Отмена» | +| PGN больше 200 МБ | диалог | «Файл �лишком большой дл� телефона…» | «Пон�тно» | +| �е база партий | �кран ошибки | «Это не база партий» / «В файле не нашло�ь ни одной партии PGN или базы ChessBase.» | «К базам» | +| �рхив без баз | �кран ошибки | «В архиве нет баз PGN или ChessBase» | «К базам» | +| �рхив � паролем | �кран ошибки | «�рхивы � паролем (.cbz, зашифрованные zip/7z) не поддерживают��» | «К базам» | +| �овый формат ChessBase `.2cbh` | �кран ошибки | «Этот формат ChessBase пока не читает��…» | «К базам» | +| �ет файла `.cbg` | �кран ошибки | «�е хватает файла .cbg р�дом � .cbh…» | «Выбрать папку» | +| �ет до�тупа (файл перемещён или удалён, SD-карта вынута, облачное приложение удалено) | �трока базы | «�ет до�тупа к файлу» | «�айти» — �и�темный выбор; е�ли выбран тот же файл, им� базы и отметки �охран�ют�� | +| Файл изменил�� | Партии | �некбар «Файл изменил�� — читаю заново» | — | +| Облачный файл без �ети | �кран ошибки | «Файл в облаке, а интернета нет…» | «Повторить» | +| Файл повреждён по�ередине | Партии, поло�а �верху | «Прочитано {n} партий; дальше файл повреждён.» | «Подробно�ти» | +| �ичего не найдено | Партии | «�ичего не найдено» | «Сбро�ить пои�к» / «Сбро�ить фильтры» | +| В буфере нет PGN | Базы, �некбар | «В буфере нет партий в формате PGN» | — | +| Файл из другого приложени� копирует�� | диалог | «Открываю файл…» | — | +| Файл из другого приложени� не открыл�� | диалог | «Файл не открыл��» / причина | «Пон�тно» | +| Ошибки �качивани� движка | ли�т движка | §8.4 | §8.4 | +| Движок не отвечает | �трока движка | «Движок не отвечает» | «Перезапу�тить» | +| Движок не запу�кает�� | �трока движка | «Движок не запу�кает�� на �том телефоне» | — | +| Ошибки обновлени� | карточка на «Базах» (коротко), ли�т «Обновление» (полно�тью) | §25.3, F | §25.3, F | +| Проверка обновлений не удала�ь | «О программе» (только по�ле «Проверить �ейча�») | «�ет интернета — проверить обновлени� нельз�» / «�е удало�ь проверить обновлени�: �айт не ответил…» | — | + +- По�то�нный до�туп переживает перезагрузку. «�ет до�тупа» означает, что файл переехал или и�чез, а не что телефон перезагрузили. При запу�ке до�туп ко в�ем базам провер�ет�� в фоне. +- Экран ошибки �о�тоит из пингвина 48 dp, заголовка 22sp, одной-двух �трок объ��нени� и одной кнопки. Техниче�кие подробно�ти (тек�т `ImportError`) открывают�� ��ылкой «Подробно�ти» в ли�те, там же кнопка «Копировать». +- Без интернета приложение работает полно�тью. Сообщение «нет интернета» бывает только у облачного файла, у �качивани� движка, партий � �айтов и обновлени� — и только по�ле нажати� человека. �втоматиче�ка� проверка обновлений без �ети молчит. + +## 12. Же�ты и до�тупно�ть + +### 12.1. В�е же�ты + +| Где | Же�т | Дей�твие | +|---|---|---| +| везде | �и�темный «назад» | шаг назад (§2.1) | +| �пи�ки | прокрутка; бегунок у правого кра� | прокрутка; бы�трый прыжок | +| �трока базы или партии | ка�ание; удержание | открыть; меню | +| нотаци� | ка�ание хода; прокрутка | перейти к ходу; читать | +| ◀ ▶ | ка�ание; удержание | шаг; повтор | +| ли�ты | т�нуть вниз | закрыть | +| до�ка | — | ничего, кроме первой под�казки (§7.2) | + +Других горизонтальных же�тов, кроме прокрутки р�да чипов и �троки «Дальше», нет. + +### 12.2. Одной рукой + +- В�ё ча�тое — в нижних 200 dp �крана: ◀ ▶, движок, переворот до�ки, «Показать» в фильтрах. +- Редкое — наверху: ‹ ›, меню, пои�к. Пои�к открывают до про�мотра, а не во врем� ли�тани� ходов. +- В�е цели ка�ани� не меньше 48×48 dp. И�ключение одно — ходы внутри тек�та вариантов. Дл� них ка�ание выбирает ближайший ход, а продублированы они чипами 48 dp в �троке «Дальше». + +### 12.3. TalkBack + +| Элемент | RU | EN | +|---|---|---| +| клетка � фигурой | «e4, белый конь» | “e4, white knight� | +| пу�та� клетка | «e4, пу�то» | “e4, empty� | +| до�ка, дей�твие «Опи�ать позицию» | «Белые: король g1, ферзь d1, … Чёрные: …» | “White: king g1, queen d1, … Black: …� | +| ход в нотации | «4, белые, �лон a4, хороший ход, е�ть комментарий» | “4, White, bishop a4, good move, has comment� | +| новый ход по�ле ◀ ▶ (объ�вление) | «4… конь f6» | “4… knight f6� | +| вз�тие, шах, мат, рокировка | «�лон берёт f7, шах»; «мат»; «коротка� рокировка» | “bishop takes f7, check�; “checkmate�; “short castling� | +| плашка оценки | «Оценка плю� 0,4, глубина 22» / «Мат в 3 хода» | “Evaluation plus 0.4, depth 22� / “Mate in 3� | +| �трока партии (§6.2, � 2026-10-24) | «№ 12. Белые: Карл�ен, Магну�, Эло 2830. Чёрные: Каруана, Фабиано, Эло 2795. 1-0, победили белые. �орвеги�, 2025, C42. Про�мотрена» | “No. 12. White: Carlsen, Magnus, Elo 2830. Black: Caruana, Fabiano, Elo 2795. 1-0, White won. Norway, 2025, C42. Viewed� | +| плашка игрока (§7.11) | «Чёрные: Каруана, Фабиано, Эло 2795, проигрыш» | “Black: Caruana, Fabiano, Elo 2795, lost� | +| заголовок партии (§7.7) | «Norway Chess, 2025, парти� 12 из 340, тур 5. Сведени� о партии, кнопка» | “Norway Chess, 2025, game 12 of 340, round 5. Game details, button� | +| образец до�ки или набора (§9.1) | «Зелёна�, выбрано, переключатель» / «merida, не выбрано, переключатель» | “Green, selected, radio button� / “merida, not selected, radio button� | +| кнопка «Движок» | «Движок, выключен» / «Движок, не �качан» | “Engine, off� / “Engine, not downloaded� | +| ‹ › | «Предыдуща� парти�» / «Следующа� парти�» | “Previous game� / “Next game� | +| ход � отметкой движка (§21.4) | «6, чёрные, конь f6, ошибка» | “6, Black, knight f6, mistake� | +| график оценки (§21.3) | «График оценки, ход 23, оценка плю� 1,2» | “Evaluation graph, move 23, evaluation plus 1.2� | +| �чейка отчёта (§21.5) | «�еточно�ти, чёрные, 3, кнопка» | “Inaccuracies, Black, 3, button� | +| карточка обновлени� (§25.8) | «Вышла вер�и� 0.15.0, заголовок» / «Обновление до 0.15.0, �качано 3 из 9 мегабайт, кнопка» | “Version 0.15.0 is out, heading� / “Update to 0.15.0, 3 of 9 megabytes downloaded, button� | +| × на карточке обновлени� (§25.8) | «�е предлагать обновлени�, кнопка» | “Don't offer updates, button� | + +- Фигуры озвучивают�� �ловами («конь»), а не буквами запи�и. Клетки читают�� от a8 к h1, при перевёрнутой до�ке — от h1 к a8. +- Смы�л никогда не передаёт�� одним цветом: у NAG е�ть значок, у результата тек�т, у текущего хода — озвучивание «текущий». +- Под�казка о кнопках §7.2 в TalkBack не показывает��: до�ка там озвучивает�� �ама. + +### 12.4. Шрифт и контра�т + +- В�е размеры тек�та в sp. Ма�штаб шрифта до 200 % не обрезает кнопки; при ма�штабе больше 1,3 подпи�и нижней панели �крывают��, о�тают�� значки � опи�ани�ми дл� TalkBack. +- При крупном шрифте нотаци� переходит в �плошной тек�т (§7.3). Размер до�ки от шрифта не зави�ит. + +## 13. �льбомна� ориентаци� и планшеты + +Кла��ы размеров окна M3: компактный — уже 600 dp, �редний — 600–839, ра�ширенный — от 840; низкий — вы�ота меньше 480. + +### 13.1. Телефон в альбомной ориентации (800×360) + +``` +┌──────────────────────────────────────────────────────────────────� +│ � Norway Chess · 2025 · 12 из 340 · тур 5 ‹ › ⋮ │ 48 +├─────────────────────────┬─┬──────────────────────────────────────┤ +│ │▌│ � Каруана, Фабиано 2795 0 │ 36 верхн�� плашка +│ │▌├──────────────────────────────────────┤ +│ │▌│ �+0.4▌ гл.22 14.Кd5 Сxd5 … ▾ │ 40 +│ ДОСК� │▌├──────────────────────────────────────┤ +│ ~ 288 │▌│ 1. e4 e5 2. Кf3 Кc6 … │ +│ │▌├──────────────────────────────────────┤ +│ │▌│ ○ Карл�ен, Магну� 2830 1 │ 36 нижн�� плашка +│ │▌├──────────────────────────────────────┤ +│ │▌│ ▣ ⇅ � ◀ ▶ � │ 56 +└─────────────────────────┴─┴──────────────────────────────────────┘ +``` + +До�ка в�егда �лева, шкала оценки �права от неё, нижн�� панель под нотацией. Верхн�� панель низка� (48 dp), заголовок в одну �троку: «турнир · год · 12 из 340 · тур» (§7.7), обрезает�� многоточием � конца названи� турнира, а не � номера: номер и тур — отдельный `Text` без �жати� �права от названи�. Плашки игроков (§7.11) — первой и по�ледней �трокой правой колонки, до�ка их не тер�ет; при перевороте они мен�ют�� ме�тами. �отации в колонке о�таёт�� 288 − 36 − 36 − 56 = 160 dp, � движком — около 120. + +### 13.2. Планшет в портрете (�редний, 800×1280) + +Компоновка как у телефона. До�ка — меньшее из ширины и 60 % вы�оты, по центру, �лева от неё вертикальна� шкала оценки 12 dp. Плашки игроков (§7.11) над до�кой и под ней, шириной � до�ку вме�те �о шкалой, по центру. Спи�ки в одну колонку; в �троке подробно�тей партии добавл�ет�� тур (Эло � 2026-10-24 �тоит у имени и на телефоне, §6.2). + +### 13.3. Планшет в альбомной ориентации (ра�ширенный, 1280×800) + +``` +┌───────────────┬────────────────────────────────────────────────────────� +│ � Мои партии ⌕│ ☰ Norway Chess · 2025 · 12 из 340 · тур 5 ‹ › ⋮ │ +│ 1 248 партий ├─┬──────────────────────────────┬───────────────────────┤ +│───────────────│▌│ │ � Каруана, Фабиано 0 │ 36 +│ 1 Карл�ен, М 1▌│ ├───────────────────────┤ +│ Каруана, Ф 0▌│ │ �+0.4▌ гл.22 14.Кd5 …▾│ +│ �орвеги� · 2025 ├───────────────────────┤ +│ ▓2 Иванов Пётр ½▓│ ДОСК� │ 1. e4 e5 │ +│ ▓ Сидоров �. ½▓│ ~ 640×640 │ 2. Кf3 Кc6 │ +│ … │▌│ │ … │ +│ │ │ ├───────────────────────┤ +│ │ │ │ ○ Карл�ен, Магну� 1 │ 36 +│ │ │ ├───────────────────────┤ +│ │ │ │ ▣ ⇅ � ◀ ▶ � │ +└───────────────┴─┴──────────────────────────────┴───────────────────────┘ + 320 ≥ 320 +``` + +- Две панели: �лева «Партии» (320 dp), �права «Парти�». Выбранна� �трока под�вечена; ‹ › передвигают и под�ветку. +- ☰ пр�чет �пи�ок: до�ка �тановит�� больше, нотаци� о�таёт�� не уже 320 dp. Приложение помнит, �пр�тан ли �пи�ок. +- Размер до�ки — меньшее из до�тупной вы�оты и «ширина − �пи�ок − 320». +- Строки �пи�ка �лева — те же трёх�трочные 80 dp (§6.2); в 320 dp у имени около 230 dp, правило �окращени� то же. Плашки игроков — в правой колонке, как в §13.1. +- «Базы» и «�а�тройки» по-прежнему занимают в�ё окно. +- Средний размер в альбомной ориентации (600–839 dp) — без �пи�ка, как в §13.1, но � обычной верхней панелью. + +## 14. Тек�ты RU / EN + +Тон как на компьютере: коротко, без во�клицаний и без «пожалуй�та». Чи�ла �клон�ют�� через �и�темные plurals: `1 парти� / 2 партии / 5 партий`, `1 game / 2 games`. Где �трока �овпадает � компьютерной, вз�т перевод из `i18n.rs`. + +### 14.1. Базы и добавление + +| Ключ | RU | EN | +|---|---|---| +| `app_name` | ChessPenguin | ChessPenguin | +| `db_empty_title` | Зде�ь будут ваши базы | Your databases will appear here | +| `db_empty_body` | Добавьте файл PGN, базу ChessBase или архив .zip/.7z — � телефона или из облака. | Add a PGN file, a ChessBase database or a .zip/.7z archive — from your phone or the cloud. | +| `db_add` | Добавить базу | Add database | +| `db_examples` | Открыть примеры партий | Open sample games | +| `db_games` | {n} партий · {format} | {n} games · {format} | +| `db_not_opened` | ещё не открывала�ь · {format} | not opened yet · {format} | +| `db_reading` | читаю… {n} | reading… {n} | +| `db_copying` | копирую… {p} % | copying… {p}% | +| `db_no_access` | �ет до�тупа к файлу | No access to the file | +| `db_find` | �айти | Find | +| `db_rename` | Переименовать | Rename | +| `db_rename_hint` | �азвание в �пи�ке. Файл не мен�ет��. | The name in the list. The file is not changed. | +| `db_info` | Сведени� | Details | +| `db_remove` | Убрать из �пи�ка | Remove from list | +| `db_removed` | База убрана из �пи�ка | Database removed from the list | +| `undo` | Вернуть | Undo | +| `remove` | Убрать | Remove | +| `cancel` / `save` | Отмена / Сохранить | Cancel / Save | +| `db_stop_reading` | О�тановить чтение | Stop reading | +| `db_already` | Эта база уже в �пи�ке | This database is already in the list | +| `info_format` / `info_games` / `info_texts` / `info_size` / `info_where` / `info_added` | Формат / Партий / Тек�тов / Размер / Где / Добавлена | Format / Games / Texts / Size / Location / Added | +| `info_readonly` | ChessPenguin только читает �тот файл и никогда его не мен�ет. | ChessPenguin only reads this file and never changes it. | +| `info_cb` | ChessBase, только чтение | ChessBase, read-only | +| `info_encoding` | PGN, кодировка {enc} | PGN, encoding {enc} | +| `info_copy` | Копи� в ChessPenguin (из {source}) | Copy in ChessPenguin (from {source}) | +| `info_notes` | Замечани� ({n}) | Notes ({n}) | +| `add_title` | Добавить базу | Add database | +| `add_file` / `add_file_hint` | Файл / PGN, .cbv, .zip или .7z | File / PGN, .cbv, .zip or .7z | +| `add_folder` / `add_folder_hint` | Папка / В�е базы в папке, в том чи�ле ChessBase (.cbh) | Folder / Every database in a folder, ChessBase (.cbh) too | +| `add_paste` / `add_paste_hint` | В�тавить PGN из буфера / Партии, �копированные в другом приложении | Paste PGN from the clipboard / Games copied in another app | +| `add_tree_hint` | Корень пам�ти и �аму «Загрузки» выбрать нельз� — только папку внутри них. | Android won't let apps pick the storage root or Downloads itself — only a folder inside them. | +| `cbh_title` | �ужна в�� папка | The whole folder is needed | +| `cbh_body` | База ChessBase — �то не�колько файлов р�дом: .cbh, .cbg, .cba и другие. Выберите папку, в которой они лежат. | A ChessBase database is several files side by side: .cbh, .cbg, .cba and others. Pick the folder they are in. | +| `cbh_pick` | Выбрать папку | Pick folder | +| `folder_scanning` | Ищу базы… | Looking for databases… | +| `folder_found` | В папке «{name}» найдено {n} баз | {n} databases in “{name}� | +| `add_chosen` | Добавить {n} | Add {n} | +| `added_count` | Добавлено {n} баз | {n} databases added | +| `folder_added` | уже в �пи�ке | already on the list | +| `folder_incomplete` | нет файла .cbg — партии не открыть | no .cbg file — the games can't be opened | +| `folder_empty_title` | В папке нет баз | No databases in this folder | +| `folder_empty_text` | Подход�т файлы PGN, базы ChessBase (.cbh, .cbv) и архивы .zip и .7z — в �амой папке и во вложенных папках на два уровн�. | Looks for PGN files, ChessBase databases (.cbh, .cbv) and .zip or .7z archives in the folder and two levels of folders inside it. | +| `folder_other` | Выбрать другую | Pick another | +| `done` | Готово | Done | +| `cloud_copy` | Файл в облаке. ChessPenguin �охранит копию у �еб�: {size}. | The file is in the cloud. ChessPenguin will keep a copy: {size}. | +| `cloud_copy_ok` | Сохранить копию | Save a copy | +| `paste_none` | В буфере нет партий в формате PGN | No PGN games in the clipboard | +| `paste_db` | Из буфера, {when} | Pasted {when} | +| `db_copy` | {n} партий · {format} · копи� | {n} games · {format} · copy | +| `removed_copy` | База удалена из ChessPenguin | Database deleted from ChessPenguin | +| `examples_classics` / `examples_alekhine` | Кла��иче�кие партии / �лехин | Classic games / Alekhine | + +### 14.2. Открытие и ошибки + +| Ключ | RU | EN | +|---|---|---| +| `open_cb` | Открываю базу… | Opening the database… | +| `huge_db` | Очень больша� база: {n} партий. ChessPenguin ра��читан на базы до миллиона партий; �та может открывать�� долго и работать медленно. | A very large database: {n} games. ChessPenguin is made for databases of up to a million games; this one may open slowly and run slowly. | +| `huge_db_open` | В�ё равно открыть | Open anyway | +| `pgn_too_big` | Файл �лишком большой дл� телефона ({size}). ChessPenguin открывает PGN до 200 МБ. Откройте его на компьютере или разделите на ча�ти. | The file is too large for a phone ({size}). ChessPenguin opens PGN files of up to 200 MB. Open it on a computer or split it into parts. | +| `ok` | Пон�тно | OK | +| `stopped` / `read_again` | Чтение о�тановлено / Прочитать �нова | Reading stopped / Read again | +| `err_not_db_title` | Это не база партий | This is not a games database | +| `err_not_db_body` | В файле не нашло�ь ни одной партии PGN или базы ChessBase. | No PGN games or ChessBase database found in the file. | +| `err_archive_empty` | В архиве нет баз PGN или ChessBase | No PGN or ChessBase database in the archive | +| `err_encrypted` | �рхивы � паролем (.cbz, зашифрованные zip/7z) не поддерживают�� | Password-protected archives (.cbz, encrypted zip/7z) are not supported | +| `err_cb2` | Этот формат ChessBase пока не читает��. Сохраните базу в ChessBase как .cbh или PGN. | This ChessBase format cannot be read yet. Save the database in ChessBase as .cbh or PGN. | +| `err_cbg_missing` | �е хватает файла .cbg р�дом � .cbh. Скопируйте папку базы целиком. | The .cbg file next to the .cbh is missing. Copy the whole database folder. | +| `err_offline` | Файл в облаке, а интернета нет. Подключите�ь к �ети или �охраните копию на телефоне. | The file is in the cloud and there is no internet. Connect or keep a copy on the phone. | +| `err_broken` | Прочитано {n} партий; дальше файл повреждён. | {n} games read; the rest of the file is damaged. | +| `file_changed` | Файл изменил�� — читаю заново | The file has changed — reading it again | +| `to_databases` | К базам | To databases | +| `opening_file` | Открываю файл… | Opening the file… | +| `file_failed` | Файл не открыл�� | Couldn't open the file | +| `file_no_games` | В �том файле нет шахматных партий. | There are no chess games in this file. | +| `file_unreadable` | Файл не прочитал��: его уже нет или приложение, из которого он открыт, не дало к нему до�тупа. Попробуйте открыть его ещё раз. | The file could not be read: it may be gone, or the app it came from did not give access to it. Try opening it again. | +| `retry` | Повторить | Retry | +| `details` / `copy` | Подробно�ти / Копировать | Details / Copy | + +### 14.3. Партии + +| Ключ | RU | EN | +|---|---|---| +| `list_count` / `list_count_reading` | {n} партий / {n} партий… | {n} games / {n} games… | +| `list_found` | �айдено {n} из {total} | Found {n} of {total} | +| `search_hint_small` / `search_hint_large` | Игрок, турнир, ECO, год / Игрок | Player, event, ECO, year / Player | +| `player_suggest` | {name} · {n} партий | {name} · {n} games | +| `nothing_found` | �ичего не найдено | Nothing found | +| `reset_search` / `reset_filters` | Сбро�ить пои�к / Сбро�ить фильтры | Clear search / Reset filters | +| `db_empty` | В �той базе нет партий | There are no games in this database | +| `sort` | Сортировка | Sort | +| `sort_file` / `sort_new` / `sort_old` / `sort_white` / `sort_black` / `sort_event` / `sort_eco` | Как в файле / Дата: �начала новые / Дата: �начала �тарые / Белые (�–Я) / Чёрные (�–Я) / Турнир / ECO | As in the file / Date: newest first / Date: oldest first / White (A–Z) / Black (A–Z) / Event / ECO | +| `sort_narrow` | Сначала �узьте пои�к: �ортировка работает, когда найдено не больше 50 000 партий | Narrow the search first: sorting works for up to 50,000 games | +| `filters` / `filters_n` | Фильтры / Фильтры {n} | Filters / Filters {n} | +| `f_player` / `f_opponent` / `f_event` / `f_years` / `f_elo` / `f_result` / `f_eco` | Игрок / Соперник / Турнир или ме�то / Годы / Эло от / Результат / ECO | Player / Opponent / Tournament or place / Years / Elo from / Result / ECO | +| `f_any` / `f_white` / `f_black` | любым / белыми / чёрными | either colour / as White / as Black | +| `f_win` / `f_draw` / `f_loss` | Выигрыш / �ичь� / Проигрыш | Win / Draw / Loss | +| `f_from` / `f_to` | � / по | from / to | +| `f_eco_hint` | B90, B9 или C60-C99 | B90, B9 or C60-C99 | +| `f_comments` / `f_variations` | � комментари�ми / � вариантами | with comments / with variations | +| `f_reset` | Сбро�ить | Reset | +| `f_show` | Показать {n} | Show {n} | +| `text_row` | Тек�т | Text | +| `row_desc_white` / `row_desc_black` (2026-10-24, TalkBack, §6.2) | Белые: {name} / Чёрные: {name} | White: {name} / Black: {name} | +| `elo_n` | Эло {n} | Elo {n} | +| `row_share` / `row_copy` | Поделить�� партией / Копировать PGN | Share game / Copy PGN | +| `row_unviewed` / `row_viewed` | Отметить как непро�мотренную / Отметить как про�мотренную | Mark as not viewed / Mark as viewed | + +### 14.4. Парти� + +| Ключ | RU | EN | +|---|---|---| +| `game_pos` (� 2026-10-24 без результата, §7.7) | {i} из {n} | {i} of {n} | +| `round_n` | тур {r} | round {r} | +| `player_white_missing` / `player_black_missing` (плашка без имени, §7.11) | Белые / Чёрные | White / Black | +| `player_won` / `player_lost` / `player_drew` (TalkBack плашки) | выигрыш / проигрыш / ничь� | won / lost / draw | +| `title_info_hint` (TalkBack заголовка) | Сведени� о партии | Game details | +| `prev_game` / `next_game` | Предыдуща� парти� / Следующа� парти� | Previous game / Next game | +| `nav_start` / `nav_back` / `nav_fwd` / `nav_end` | В начало / �азад / Вперёд / В конец линии | To start / Back / Forward / To the end of the line | +| `flip` | Перевернуть до�ку | Flip board | +| `eng_state_on` / `eng_state_off` / `eng_state_missing` | включён / выключен / не �качан | on / off / not downloaded | +| `next_moves` | Дальше: | Next: | +| `board_hint` | Это про�мотр партии. Ходы ли�тают�� кнопками ◀ ▶ внизу. | This is a game viewer. Step through the moves with ◀ ▶ below. | +| `menu_info` | Сведени� о партии | Game details | +| `copy_pgn` / `copy_fen` | Копировать PGN / Копировать FEN | Copy PGN / Copy FEN | +| `pgn_copied` / `fen_copied` | PGN �копирован / FEN �копирован | PGN copied / FEN copied | +| `share_game` / `share_short` | Поделить�� партией / Поделить�� | Share game / Share | +| `compat` | Замечани� по �овме�тимо�ти PGN | PGN compatibility notes | +| `settings` | �а�тройки | Settings | +| `i_white` / `i_black` / `i_event` / `i_site` / `i_date` / `i_round` / `i_eco` / `i_annotator` / `i_db` / `i_all_tags` | Белые / Чёрные / Турнир / Ме�то / Дата / Тур / ECO / Комментатор / База / В�е теги | White / Black / Event / Site / Date / Round / ECO / Annotator / Database / All tags | +| `res_white` / `res_black` / `res_draw` | Победили белые / Победили чёрные / �ичь� | White won / Black won / Draw | +| `res_mate_w` / `res_mate_b` / `res_stalemate` | Мат · 1-0 / Мат · 0-1 / Пат · ½-½ | Checkmate · 1-0 / Checkmate · 0-1 / Stalemate · ½-½ | +| `read_more` | Читать дальше | Read more | +| `comment_to` / `intro` | Комментарий к {move} / В�тупление | Comment on {move} / Introduction | +| `unparsed` | Фрагмент PGN не разобран; о�тавлен как е�ть | PGN fragment that could not be parsed; kept as is | +| `null_move` | По�ле нулевого хода (--) �то учебна� �хема, а не позици� партии: движок её не �читает | After a null move (--) this is a teaching scheme, not a game position: the engine does not analyse it | + +### 14.5. Движок и его �качивание + +| Ключ | RU | EN | +|---|---|---| +| `engine` | Движок | Engine | +| `eng_thinking` | Считаю… | Thinking… | +| `eng_depth` / `eng_paused` | гл. {d} / гл. {d} · пауза | depth {d} / depth {d} · paused | +| `eng_preparing` | Готовлю движок… | Preparing the engine… | +| `eng_deeper` | Глубже | Deeper | +| `eng_preview` | Лини� движка · ход {i} из {n} | Engine line · move {i} of {n} | +| `eng_saver` | Экономи� зар�да: движок работает медленнее | Battery saver: the engine runs slower | +| `eng_stuck` / `eng_restart` | Движок не отвечает / Перезапу�тить | The engine is not responding / Restart | +| `eng_unsupported` | Движок не запу�кает�� на �том телефоне | The engine cannot run on this phone | +| `dl_title` | Движок Stockfish | Stockfish engine | +| `dl_body` | Оценивает позицию и показывает лучшие ходы. Работает без интернета — нужно один раз �качать. | Evaluates the position and shows the best moves. Works offline — it only needs to be downloaded once. | +| `dl_size` | Размер: {size} | Size: {size} | +| `dl_metered` | Сейча� нет Wi-Fi: загрузка пойдёт через мобильный интернет. | No Wi-Fi now: the download will use mobile data. | +| `dl_later` / `dl_start` | �е �ейча� / Скачать | Not now / Download | +| `dl_progress` | Скачано {done} из {total} | Downloaded {done} of {total} | +| `dl_cancel` | Отменить | Cancel | +| `dl_cancelled` | Загрузка отменена | Download cancelled | +| `dl_done` | Движок готов | The engine is ready | +| `dl_notification` | Скачиваю движок · {done} из {total} | Downloading the engine · {done} of {total} | +| `dl_offline` | �ет интернета. Подключите�ь к �ети и попробуйте ещё раз. | No internet. Connect and try again. | +| `dl_interrupted` / `dl_resume` | Загрузка прервала�ь. Скачанное �охранено. / Продолжить | The download was interrupted. What was downloaded is kept. / Resume | +| `dl_no_space` | �е хватает ме�та: нужно {size}. | Not enough space: {size} needed. | +| `dl_corrupt` / `dl_again` | Файл движка повреждён при загрузке. Скачайте его ещё раз. / Скачать �нова | The engine file was damaged in download. Download it again. / Download again | +| `dl_delete` | Удалить движок (о�вободит {size}) | Delete the engine (frees {size}) | +| `dl_delete_q` / `delete` | Удалить движок? Его можно �качать �нова. / Удалить | Delete the engine? You can download it again. / Delete | + +### 14.6. �а�тройки и «О программе» + +| Ключ | RU | EN | +|---|---|---| +| `s_board_group` / `s_sound_group` / `s_look_group` / `s_engine_group` / `s_game_group` | До�ка / Звук и отклик / Внешний вид / Движок / Парти� | Board / Sound and feedback / Appearance / Engine / Game | +| `board_and_pieces` / `board` / `pieces_tab` | До�ка и фигуры / До�ка / Фигуры | Board and pieces / Board / Pieces | +| `board_*` (названи� до�ок) | Коричнева�, Син��, Зелёна�, Турнирна�, … Дерево, Клён, … �абро�ок; IC и NCF не перевод�т�� | Brown, Blue, Green, Tournament, … Wood, Maple, … Sketch | +| `s_notation` | Запи�ь ходов | Move notation | +| `s_latin` / `s_figurine` / `s_local` | Латин�кие буквы (K Q R B N) / Фигурки / Ру��кие буквы (Кр Ф Л С К) | Letters (K Q R B N) / Figurines / — (не показывает�� в англий�ком) | +| `s_notation_note` | Только вид на �кране. В PGN и при копировании в�егда K Q R B N. | Display only. PGN and copied text always use K Q R B N. | +| `s_coords` / `s_anim` / `s_best_arrow` | Координаты / �нимаци� фигур / Стрелка лучшего хода | Coordinates / Piece animation / Best move arrow | +| `s_sound` / `s_haptic` | Звук ходов / Вибраци� | Move sounds / Vibration | +| `s_theme` / `s_theme_system` / `s_theme_light` / `s_theme_dark` | Тема / Как в �и�теме / Светла� / Тёмна� | Theme / System default / Light / Dark | +| `s_dynamic` / `s_dynamic_sub` | Цвета обоев / Панели и кнопки в цветах обоев. До�ка не мен�ет��. | Wallpaper colours / Bars and buttons in your wallpaper colours. The board stays the same. | +| `s_lang` / `s_lang_system` | Язык / Как в �и�теме | Language / System default | +| `s_eng_builtin` / `s_eng_downloaded` / `s_eng_missing` / `s_eng_downloading` | Stockfish 19 · в�троен / Stockfish 19 · �качан / �е �качан · Скачать ({size}) / Скачивает��… {done} из {total} | Stockfish 19 · built in / Stockfish 19 · downloaded / Not downloaded · Download ({size}) / Downloading… {done} of {total} | +| `s_lines` / `s_time` / `s_more` / `s_threads` / `s_memory` | Линий / Врем� на позицию / Дополнительно / Потоки / Пам�ть | Lines / Time per position / More / Threads / Memory | +| `s_time_inf` | Без ограничени� | No limit | +| `s_battery` | Движок ра�ходует зар�д. Он �ам выключает��, когда вы выходите из партии или га�нет �кран. | The engine uses battery. It turns off by itself when you leave the game or the screen turns off. | +| `s_about` | О программе | About | +| `about_version_full` / `about_version_light` | {v} · Stockfish уже внутри / {v} · Stockfish �качивает�� в приложении | {v} · Stockfish built in / {v} · Stockfish downloaded in the app | +| `about_licenses` | Лицензии и авторы | Licenses and authors | + +### 14.7. Отчёт по партии (§21) + +Слова те же, что на компьютере (`apps/desktop/src/i18n.rs`, «Whole-game analysis»), кроме отмеченных *. �емецкий, и�пан�кий, француз�кий и италь�н�кий — тоже как на компьютере («Grober Fehler», «Error grave», «Gaffe», «Svarione», «Resoconto»). + +| Ключ | RU | EN | +|---|---|---| +| `review_menu` / `review_report_menu` | �нализ партии / Отчёт по партии | Game analysis / Game report | +| `review_text` | Движок оценит каждую позицию о�новной линии. Сама парти� не изменит��. | The engine evaluates every position of the main line. The game itself is not changed. | +| `review_stale` / `review_update` / `review_engine` | �нализ �делан � прежними на�тройками движка / Обновить / Проанализировать движком | This analysis was made with other engine settings / Update / Analyse with the engine | +| `review_estimate` | Позиций: {n}, примерно {time} | {n} positions, about {time} | +| `review_seconds` / `review_minutes` | {n} � / {n} мин | {n} s / {n} min | +| `review_partial` | Уже оценено позиций: {done} из {total}. | {done} of {total} positions are evaluated already. | +| `review_start` / `review_fill` | �нализировать / Дополнить | Analyse / Fill in | +| `review_progress` / `review_stop` | �нализ партии · {done} из {total} / О�тановить анализ | Game analysis · {done} of {total} / Stop the analysis | +| `review_accuracy` / `review_accuracy_of` | Точно�ть / Точно�ть: белые {w}, чёрные {b} | Accuracy / Accuracy: White {w}, Black {b} | +| `review_report` | Отчёт | Report | +| `review_better` | лучше было {move} | {move} was better | +| `review_inaccuracy` / `review_mistake` / `review_blunder` | �еточно�ть / Ошибка / Зевок | Inaccuracy / Mistake / Blunder | +| `review_inaccuracies` / `review_mistakes` / `review_blunders` | �еточно�ти / Ошибки / Зевки | Inaccuracies / Mistakes / Blunders | +| `review_missing` | Без оценки: {n} | Not evaluated: {n} | +| `review_failed` / `review_resume` | �нализ прервал�� / Продолжить | The analysis stopped / Continue | +| `review_acpl` | Средн�� потер� �антипешек | Average centipawn loss | +| `review_opening` / `review_middlegame` / `review_endgame` | Дебют / Миттельшпиль / Эндшпиль | Opening / Middlegame / Endgame | +| `review_source` / `review_source_pgn` | {engine} · {nodes} узлов на ход / Оценки из PGN ([%eval]) | {engine} · {nodes} nodes per move / Evaluations from the PGN ([%eval]) | +| `review_hide` * | Скрыть анализ | Hide analysis | +| `review_graph` * (TalkBack) | График оценки | Evaluation graph | +| `review_engine_paused` * | Пауза: идёт анализ партии | Paused: the game is being analysed | +| `review_best_preview` * | Лучша� лини� · ход {i} из {n} | Better line · move {i} of {n} | +| `review_next` * (TalkBack) | Перейти к �ледующему такому ходу | Go to the next such move | +| `review_show_best` (TalkBack) | Показать лучшую линию на до�ке | Show the better line on the board | + +- `review_no_line` («Оценки вз�ты из PGN: лучшей линии в них нет.») не и�пользует��: без лучшей линии �трока про�то не нажимает�� (§21.3). Строку удалить. +- `review_next` на компьютере «Перейти к �ледующей» �огла�ует�� только � «неточно�тью» и «ошибкой», а не � «зевком»; на телефоне — нейтрально «к �ледующему такому ходу». Компьютеру — по желанию то же. +- О�тальные п�ть �зыков дл� �трок � *: «Erneut» / «Von vorn» (de), «Empezar de nuevo» (es), «Recommencer» (fr), «Ricomincia» (it) дл� `review_restart`; «Analyse ausblenden», «Ocultar el análisis», «Masquer l'analyse», «Nascondi l'analisi» дл� `review_hide`; `review_next` — «Zum nächsten solchen Zug», «Ir a la siguiente jugada así», «Aller au coup suivant de ce type», «Vai alla prossima mossa di questo tipo»; `review_engine_paused` — � заглавной: «Pausiert: …», «En pausa: …», «En pause : …», «In pausa: …». + +### 14.8. Партии � Lichess и Chess.com (§23) + +Слова — как на компьютере (`apps/desktop/src/i18n.rs`, блок онлайн-партий), где �трока там е�ть. ✎ — изменить, + — добавить. `{games}` — `games_count` («473 партии»), `{n}` — чи�ло � пробелами между разр�дами (`groupDigits`), никогда не голый `%d` дл� чи�ла партий. + +| Ключ | RU | EN | +|---|---|---| +| `online_title` | Партии � Lichess и Chess.com | Games from Lichess and Chess.com | +| `online_title_short` + (только е�ли длинный заголовок обрезает��, §23.2) | Lichess и Chess.com | Lichess and Chess.com | +| `add_online_hint` | Партии любого игрока по нику: �вои, ученика, �оперника | Any player's games by nickname: yours, a pupil's, an opponent's | +| `online_intro` ✎ (не повтор�ть подпи�ь ли�та) | Партии игрока �танут базой на телефоне — и�кать, �мотреть, анализировать. �ужен только ник, входить на �айт не нужно. | The player's games become a database on your phone, to search, view and analyse. Only the nickname is needed, no login. | +| `online_nick` / `online_nick_lichess` + (когда открыто второе поле) | �ик игрока / �ик на Lichess | Player's nickname / Nickname on Lichess | +| `online_nick_hint` | как на �айте | as on the site | +| `online_other` / `online_other_nick` / `online_same_nick` | �а Chess.com другой ник / �ик на Chess.com / Тот же ник | A different nickname on Chess.com / Nickname on Chess.com / The same nickname | +| `online_nick_rule` | Латиница, цифры, _ и -, от 2 до 30 �имволов | Latin letters, digits, _ and -, 2 to 30 characters | +| `online_find` / `online_searching` | �айти / Ищу на �айтах… | Find / Looking on the sites… | +| `games_up_to` + (plurals) | до {n} партии (one) / до {n} партий (few, many) / до {n} партии (other) | up to {n} game / up to {n} games | +| `online_lichess_found` ✎ | {up_to} · первый раз около {m} мин | {up_to} · about {m} min the first time | +| `online_lichess_quick` + | {up_to} · первый раз меньше минуты | {up_to} · under a minute the first time | +| `online_chesscom_found` | ме��цев � парти�ми: {m} | months with games: {m} | +| `online_not_found` ✎ (как на компьютере) | {site}: игрока � таким ником нет — проверьте напи�ание | {site}: no player with this nickname — check the spelling | +| `online_merge` / `online_merge_hint` | Объединить оба �айта в одну базу / Иначе у каждого �айта будет �во� база | Merge both sites into one database / Otherwise each site gets a database of its own | +| `online_into_new` / `online_into_existing` | В новую базу «{name}» / В базу «{name}» (там уже {games}; добав�т�� только новые) | Into the new database “{name}� / Into “{name}� ({games} there already; only new games are added) | +| `online_download` / `online_stop` / `online_open` | Скачать / О�тановить / Открыть базу | Download / Stop / Open the database | +| `online_progress_lichess` ✎ (`{t}` — чи�ло, без �лова) | Lichess: {n} из примерно {t} · о�тало�ь около {m} мин | Lichess: {n} of about {t} · about {m} min left | +| `online_progress_chesscom` | Chess.com: ме��ц {i} из {k} · {games} | Chess.com: month {i} of {k} · {games} | +| `online_leave` + | Можно уйти � �того �крана: база уже в �пи�ке, �качивание продолжит��. | You can leave this screen: the database is on the list and the download goes on. | +| `online_done` + (первое �качивание) | Готово: {games} | Done: {games} | +| `online_added` ✎ (`{n}` � разр�дами) | +{n}, в�его {games} | +{n}, {games} in all | +| `online_no_new` / `online_stopped` | �овых партий нет, в базе {games} / О�тановлено, в базе {games} | No new games, {games} in the database / Stopped, {games} in the database | +| `online_no_games` | Партий в обычные шахматы там нет. | No games of standard chess there. | +| `online_try_again` | Попробовать ещё раз | Try again | +| `online_err_*` | §23.4, как на компьютере; `online_err_disk` — «на телефоне не хватает ме�та» | as on the desktop; `online_err_disk` — “the phone is out of space� | +| `online_short_network` / `online_short_rate` / `online_short_failed` | {site} не отвечает / {site} про�ит паузу / Скачивание прервало�ь | {site} does not answer / {site} asks for a pause / The download stopped | +| `online_update` / `online_stop_download` | Скачать новые партии / О�тановить �качивание | Download new games / Stop the download | +| `online_downloading` | Скачивает�� · {n} | Downloading · {n} | +| `online_updated` / `online_updated_now` + / `online_unfinished` | обновлено {when} / обновлено только что / не докачана | updated {when} / updated just now / not finished | +| `online_snack_added` + / `online_snack_none` + / `online_snack_failed` + | «{name}»: +{n}, в�его {games} / «{name}»: новых партий нет / «{name}»: {short} | “{name}�: +{n}, {games} in all / “{name}�: no new games / “{name}�: {short} | +| `online_removed` | Скачанна� база удалена | Downloaded database deleted | +| `db_empty_body` ✎ | Добавьте файл PGN, базу ChessBase или архив .zip/.7z — � телефона или из облака — или �качайте партии � Lichess и Chess.com. | Add a PGN file, a ChessBase database or a .zip/.7z archive — from your phone or the cloud — or download games from Lichess and Chess.com. | + +- **Почему `games_up_to`.** «до» и «из примерно» требуют родительного падежа: «до 24 партий», а `games_count` даёт «24 партии». В `online_progress_lichess` проще в�его, как на компьютере, под�тавить голое чи�ло. В de/es/fr/it падеж не мен�ет�� — там `games_up_to` повтор�ет `games_count` � предлогом: «bis zu {n} Partien», «hasta {n} partidas», «jusqu'à {n} parties», «fino a {n} partite». +- **`online_added`:** �ейча� `+%1$d` — «+6541» без пробела, а р�дом «6 541 парти�». Под�тавл�ть `groupDigits`. +- **�овые �троки, другие �зыки.** `online_leave`: «Sie können diesen Bildschirm verlassen: die Datenbank ist in der Liste, der Download läuft weiter.» / «Puedes salir de esta pantalla: la base ya está en la lista y la descarga continúa.» / «Vous pouvez quitter cet écran : la base est dans la liste et le téléchargement continue.» / «Puoi uscire da questa schermata: la base è già nell'elenco e il download continua.» `online_done`: «Fertig: {games}» / «Listo: {games}» / «Terminé : {games}» / «Fatto: {games}». `online_updated_now`: «gerade aktualisiert» / «actualizada ahora mismo» / «mise à jour à l'instant» / «aggiornata adesso». `online_nick_lichess`: «Nickname auf Lichess» / «Apodo en Lichess» / «Pseudo sur Lichess» / «Nickname su Lichess». `online_not_found`, `online_snack_*` — � компьютера (`✖` не �тавить). +- **Мелочи о�тальных �зыков.** it `online_downloading` «Download · {n}» читает�� как кнопка — лучше «Download in corso · {n}». fr `online_title` как на компьютере («de Lichess et Chess.com») — о�тавить ради един�тва. + +### 14.9. Обновление приложени� (§25) + +Слова, где можно, вз�ты � компьютера (`apps/desktop/src/i18n.rs`, блок обновлени�): «Вышла вер�и� {v}», «Провер�ть обновлени� при запу�ке», «Проверить �ейча�», «ChessPenguin обновлён: {from} → {to}», «Файл повредил�� при �качивании…». Строки, которые уже е�ть в приложении, не дублируют��: `not_now`, `retry`, `ok`, `download_again`, `cancel_download`, `downloaded_of`, `no_internet`, `no_space`. `{size}` и `{done}`/`{total}` — в МБ, как у движка. + +| Ключ | RU | EN | +|---|---|---| +| `upd_title` | Вышла вер�и� {v} | Version {v} is out | +| `upd_you_have` | У ва� {v} | You have {v} | +| `upd_update` / `upd_install` | Обновить / У�тановить | Update / Install | +| `upd_offers_off_snack` (вме�то `upd_hidden_snack`) | Больше не предлагаем. Включить — в �а�тройках, «О программе» | We won't offer it again. Turn it on in Settings, About | +| `upd_dismiss_cd` (TalkBack, ×) | �е предлагать обновлени� | Don't offer updates | +| `upd_offer` | Предлагать новые вер�ии | Offer new versions | +| `upd_offer_sub` | Карточка на �кране «Базы», когда выходит нова� вер�и�. | A card on the Databases screen when a new version is out. | +| `upd_offer_needs_check` (подпи�ь выключенной �троки) | Работает, когда включена проверка обновлений. | Works when the update check is on. | +| `upd_keeps` / `upd_keeps_no_engine` | Базы, на�тройки и движок о�танут��. / Базы и на�тройки о�танут��. | Databases, settings and the engine stay. / Databases and settings stay. | +| `upd_closes` | �а врем� у�тановки ChessPenguin закроет�� — потом откройте его �нова. | ChessPenguin closes while it installs — then open it again. | +| `upd_online_note` | Идёт �качивание партий: у�тановка его о�тановит, потом его можно продолжить. | Games are downloading: installing stops it; you can continue it later. | +| `upd_perm_title` | �ужно одно разрешение | One permission is needed | +| `upd_perm_body` | Android �тавит приложени� не из магазина только � вашего разрешени�. Откроют�� на�тройки: включите переключатель дл� ChessPenguin и верните�ь назад. | Android installs apps from outside a store only with your permission. Settings will open: turn the switch on for ChessPenguin and come back. | +| `upd_perm_open` | Открыть на�тройки | Open settings | +| `upd_perm_denied` | Разрешение не включено — без него Android не у�тановит новую вер�ию. | The permission is off — without it Android won't install the new version. | +| `upd_perm_granted` (TalkBack) | Разрешение е�ть, �качиваю | Permission granted, downloading | +| `upd_on_site` / `upd_open_site` | Скачать на �айте / Открыть �айт | Download from the website / Open the website | +| `upd_leave` | Ли�т можно закрыть: загрузка продолжит��. | You can close this: the download goes on. | +| `upd_waiting_net` | �ет �ети. Загрузка продолжит�� �ама, когда �еть по�вит��. | No network. The download goes on by itself when the network is back. | +| `upd_waiting_net_short` | Ждёт �еть | Waiting for network | +| `upd_checking_file` / `upd_keeping_engine` / `upd_installing` | Провер�ю файл… / Сохран�ю движок… / У�танавливаю… | Checking the file… / Keeping the engine… / Installing… | +| `upd_ready` / `upd_ready_short` | �ова� вер�и� �качана и проверена. / Скачана и проверена | The new version is downloaded and checked. / Downloaded and checked | +| `upd_ready_snack` | �ова� вер�и� �качана | The new version is downloaded | +| `upd_aborted` | У�тановка отменена. �ова� вер�и� �качана — у�тановите её, когда будет удобно. | Installation cancelled. The new version is downloaded — install it whenever you like. | +| `download_cancelled` (уже е�ть у движка, новой �троки нет) | Загрузка отменена | Download cancelled | +| `upd_notification` (заголовок загрузки в `DownloadManager`) | Обновление ChessPenguin | ChessPenguin update | +| `upd_done_snack` | ChessPenguin обновлён: {from} → {to} | ChessPenguin is updated: {from} → {to} | +| `upd_err_failed` | Загрузка не удала�ь. Попробуйте ещё раз. | The download failed. Try again. | +| `upd_err_corrupt` | Файл повредил�� при �качивании, по�тому не у�тановлен. Попробуйте ещё раз. | The file got damaged while downloading, so it was not installed. Try again. | +| `upd_err_release` | С �тим выпу�ком что-то не так: файл дл� Android нельз� проверить. Скачайте новую вер�ию на �айте. | Something is wrong with this release: the Android file cannot be checked. Download the new version from the website. | +| `upd_err_storage` | Android не у�тановил новую вер�ию: не хватает ме�та. О�вободите {size} и попробуйте ещё раз. | Android did not install the new version: not enough space. Free {size} and try again. | +| `upd_err_conflict` | Android не у�тановил новую вер�ию: �тот ChessPenguin подпи�ан другим ключом. По�тавить новую вер�ию можно только по�ле удалени� �той, а при удалении пропадут �пи�ок баз и �качанные базы. | Android did not install the new version: this ChessPenguin is signed with a different key. The new version can only be installed after removing this one, and removing it loses the list of databases and the downloaded databases. | +| `upd_err_blocked` | У�тановку о�тановил Android или защита телефона. Скачайте новую вер�ию на �айте. | Android or the phone's protection stopped the installation. Download the new version from the website. | +| `upd_err_install` | Android не у�тановил новую вер�ию. Попробуйте ещё раз или �качайте её на �айте. | Android did not install the new version. Try again or download it from the website. | +| `upd_short_offline` / `upd_short_space` / `upd_short_corrupt` / `upd_short_install` / `upd_short_failed` | �ет интернета / �е хватает ме�та / Файл повредил�� / Android не у�тановил / Загрузка не удала�ь | No internet / Not enough space / The file got damaged / Android did not install it / The download failed | +| `upd_more` / `upd_details` / `upd_copy` | Подробнее / Подробно�ти / Копировать | More / Details / Copy | +| `upd_group` | Обновлени� | Updates | +| `upd_auto` | Провер�ть обновлени� при запу�ке | Check for updates at start | +| `upd_auto_sub` | Раз в день ChessPenguin �прашивает у �воего �айта, кака� вер�и� по�ледн��; �айт �читает работающие у�тановки. Передают�� только �лучайный номер �той у�тановки, вер�и� и �и�тема. Проверка идёт и при выключенных предложени�х. | Once a day ChessPenguin asks its site which version is the latest; the site counts installations that run. Only a random number of this installation, the version and the system are sent. The check runs even with offers off. | +| `upd_check_now` / `upd_checking` | Проверить �ейча� / Провер�ю… | Check now / Checking… | +| `upd_latest` | У ва� по�ледн�� вер�и� | You have the latest version | +| `upd_checked` | Проверено {when} | Checked {when} | +| `upd_check_offline` | �ет интернета — проверить обновлени� нельз� | No internet — cannot check for updates | +| `upd_check_failed` | �е удало�ь проверить обновлени�: �айт не ответил. Попробуйте позже. | Could not check for updates: the site did not answer. Try later. | +| `s_about_available` / `s_about_downloading` / `s_about_ready` | Вышла вер�и� {v} / Скачивает�� вер�и� {v}… / Вер�и� {v} �качана | Version {v} is out / Downloading version {v}… / Version {v} is downloaded | +| `upd_card_downloading` (TalkBack) | Обновление до {v}, �качано {done} из {total} мегабайт | Update to {v}, {done} of {total} megabytes downloaded | + +- `upd_closes` не обещает, что приложение откроет�� �амо: Android по�ле �амообновлени� проце�� завершает и не запу�кает (§25.6). +- О�тальные п�ть �зыков переводит разработчик � �тих двух. Где �трока е�ть на компьютере (`Version {v} is out`, `Check for updates at start`, `Check now`, `ChessPenguin is updated: {from} → {to}`, `The file got damaged…`), берёт�� перевод компьютера. Строки `upd_whats_new`, `upd_whats_new_cd`, `upd_notes_english`, `upd_hidden_snack` удалены 2026-10-24 (§28). + +## 15. Перва� вер�и� и дальше + +### 15.1. Перва� вер�и� + +- **Базы:** �пи�ок, пу�той �кран � примерами, добавление файла и папки (в�е базы в ней), «Открыть � помощью» и «Поделить��», переименование, �ведени�, «Убрать из �пи�ка», «�ет до�тупа» → «�айти». +- **Форматы** — в�ё, что читает компьютер (`docs/dev/import.md`). Ра�чёт на базы до ~1 млн партий и PGN до 200 МБ. +- **Партии:** �троки, пои�к, �ортировка, фильтры и чипы дл� больших баз, бы�тра� прокрутка, отметка «про�мотрена», тек�товые главы. +- **Парти�:** до�ка, �трелки и пол� из комментариев, нотаци� � вариантами и комментари�ми, �трока «Дальше», ◀ ▶ � �, переворот до�ки, ‹ › �о�едн�� парти�, �ведени�, копирование PGN и FEN, «Поделить��» файлом, режим чтени�, замечани� �овме�тимо�ти, под�казка при ка�ании до�ки. +- **Движок:** две �борки, �качивание в �борке без движка, оценка, 1–3 линии, предпро�мотр линии, лимит времени, о�тановка в фоне. +- **О�тальное:** на�тройки §9, внешний вид §10 (включа� адаптивный значок и за�тавку), альбомна� ориентаци�, планшеты §13, TalkBack §12.3. + +### 15.2. Позже + +1. **Свои ветки:** �делать ход на до�ке и по�мотреть, что будет, без �охранени�. Зде�ь пригодит�� заложенный �мы�л ка�ани� до�ки (§7.2). +2. В�тавка линии движка как варианта, � отменой. +3. Справочник позиции (как вкладка «Справочник» на компьютере) и пои�к по позиции. +4. Перевод комментариев (`translation-ui.md`). +5. Отчёт по партии. +6. ~~Скачивание партий � Lichess и Chess.com по нику.~~ Сделано (§23). +7. «Поделить��» картинкой позиции. +8. Пор�док баз перета�киванием, фильтры дл� малых баз. +9. Магазины приложений: F-Droid, Google Play. +10. Ча�ы на плашках игроков из `[%clk]` (§7.11): �дру нужно отдавать врем� у хода. + +### 15.3. Сознательно не делаем + +- �е мен�ем и не перезапи�ываем файлы пользовател�. +- �е делаем игры � движком, задач и тренировок: �то другое приложение. +- �е делаем учётных запи�ей, �воего облака, рекламы и аналитики. +- �е делаем �вайпов дл� ходов и партий (§7.2, §7.6) и ленты ходов в одну �троку (§7.3). +- �е на�траиваем мелочи, которые е�ть на компьютере: �коро�ть анимации, набор звуков, �торону до�ки в альбомной ориентации. + +### 15.4. Что упрощено по �равнению � первой редакцией + +- Убраны выбор набора звуков и четыре �коро�ти анимации: о�тали�ь переключатели. +- Потоки и пам�ть движка убраны в «Дополнительно». +- PGN больше 200 МБ не открывает�� � пон�тным �ообщением, вме�то диалога «Открыть в�ё равно». +- Mega больше не �талон. Дл� баз больше 1 млн партий — одно предупреждение. + +## 16. Решени� владельца (2026-10-22) + +1. Тема по умолчанию — «Как в �и�теме». +2. Зелёна� до�ка и Merida — дл� в�ех по умолчанию. ~~В первой вер�ии выбора до�ок, фигур и тем нет~~ — **заменено 2026-10-23:** до�ки и наборы фигур компьютера выбирают�� на �кране «До�ка и фигуры» (§9.1). +3. Подпи�и �борок: «Stockfish уже внутри · ≈ 95 МБ» и «Stockfish �качивает�� в приложении · ≈ 15 МБ» (en «Stockfish built in» / «Stockfish downloaded in the app»). + +## 17. Ревью первой реализации (2026-10-22) + +Что изменено в �той �пецификации по итогам ревью `androidApp/` (�тап 1) и �нимков � �мул�тора: + +- §3.1 — примеры в �пи�ке � первого запу�ка (как �делано в реализации), пу�той �кран — только когда �пи�ок очищен. +- §2.1, §6.3 — «назад» закрывает пои�к вме�те � запро�ом. +- §6.2 — результат `*` не показывает��; результат на линии первой �троки; без « – ?» у пу�тых чёрных. +- §7.3 — многоточие только в пу�той �чейке белых; левый край блоков 16 dp. +- §7.7, §10.2 — заголовок партии 16sp/500 и 14sp; в верхней панели ‹ › ⋮, на�тройки — в меню. +- §8.1, §14.6 — подпи�ь �борки в «О программе» �ловами владельца. +- §8.2, §8.3 — плашка 56×28 � рамкой `outline`; ▾ о�таёт�� на паузе; бледна� �трелка второй линии; «Готовлю движок…»; поло�а предпро�мотра 48 dp и под�ветка хода в линии. +- §8.4, §9 — размер из �борки; «Скачать» в на�тройках открывает ли�т; �хема на�троек первой вер�ии � группой «Парти�». +- §10.3 — тёмные варианты цветов NAG дл� �ветлой темы; NAG на заливке текущего хода цветом тек�та. +- §10.6 — ◀ ▶ значком `play_arrow` 32 dp. +- §14.4, §14.5 — �о�то�ни� кнопки «Движок» дл� TalkBack, «depth» вме�то «d» в англий�ком. + +## 18. Ревью «Добавить папку» (2026-10-22) + +- §4.1 — �троки «Файл» и «Папка» на прозрачном фоне; �но�ка про корень пам�ти и «Загрузки»; в�тавка из буфера отложена. +- §4.3 — пои�к на два уровн� вглубь, пара `.cbh` + `.cbv` — одна �трока; «уже в �пи�ке» и «неполна�»; «Добавить N» и «Готово»; пу�та� папка � «Выбрать другую»; одна база — тоже �пи�ком. +- §3.2, §14.1 — «ещё не открывала�ь · формат �ловом», без размера. + +## 19. До�ка и фигуры, номера партий, движок (2026-10-23) + +- §9, §9.1, §10.5, §10.9, §16 — выбор до�ки и набора фигур на отдельном �кране � превью; решение §16.2 о «первой вер�ии без выбора» заменено. +- §6.1, §6.2, §12.3 — номер партии в базе �лева в �троке �пи�ка, виден и при пои�ке. +- §0, §7.6, §8.3, §14.6 — кнопка «Движок» больше не запоминает��: кажда� парти� открывает�� � выключенным движком; выход из партии, фон и пога�ший �кран его выключают; поворот, �а�тройки поверх партии и ‹ › — нет. + +## 20. В�тавка из буфера и файлы из других приложений (2026-10-23) + +- §2.1, §4.4, §4.5, §4.6 — временные базы � поло�ой «Этой базы нет в �пи�ке [Добавить]» отменены: в�тавленный тек�т и файл из «Открыть � помощью» / «Поделить��» �разу �танов�т�� копией в �пи�ке. Одна парти� открывает «Партию», не�колько — «Партии». +- §4.1 — «В�тавить PGN из буфера» первой �трокой ли�та, только когда в буфере тек�т; �ам буфер читает�� по нажатию. +- §4.4, §3.3 — у копии в �троке «· копи�»; «Убрать из �пи�ка» удал�ет копию �о �некбаром «База удалена из ChessPenguin · Вернуть» вме�то диалога; повтор того же файла или тек�та открывает прежнюю копию. +- §4.5 — им� в�тавки: игроки дл� одной партии, общий `Event` дл� не�кольких, иначе «Из буфера, 23 окт., 14:05». +- §4.6, §11 — диалоги «Открываю файл…» и «Файл не открыл��»; `text/plain` не принимает��; `singleTask`. +- §7.6 — парти� из буфера или из файла � одной партией — «1 из 1» � неактивными ‹ ›. +- §9 — потоков движка по умолчанию не больше 2. Кнопка «Движок» включает и выключает анализ, движок запу�кает�� только ею (§19); �кран партии при анализе перери�овывает только �троку движка и �трелки. +- §14.1, §14.2 — новые и и�правленные �троки. + +## 21. Отчёт по партии (2026-10-23) + +Тот же анализ, что на компьютере (`docs/decisions.md` п. 9): движок оценивает каждую позицию о�новной линии, из оценок получают�� неточно�ти, ошибки и зевки, �редн�� потер� и точно�ть по формулам Lichess. Ра�чёт, к�ш и задание движка — общий крейт `game-review`, по�тому цифры на телефоне и на компьютере �овпадают. Парти� не мен�ет��; «Запи�ать анализ в партию» на телефоне нет (про�мотр, §15.3). + +### 21.1. Пути пользовател� + +1. **«Где он ошиб��?»** Парти� открыта → ⋮ → «�нализ партии» → ли�т запу�ка → «�нализировать». Пока движок �читает, можно ли�тать партию: график ра�тёт, отметки по�вл�ют�� в нотации. Когда готово — �трока над графиком показывает точно�ть, «Отчёт» открывает цифры. +2. **«Почему �то зевок?»** Человек �тоит на ходе � отметкой (или нажал «Зевки 1 ›» в отчёте) → �трока «?? Зевок · лучше было 23…Кf6». Ка�ание �троки показывает лучшую линию на до�ке (предпро�мотр §8.3: ◀ ▶ ли�тают, ✕ и «назад» вывод�т). �а до�ке �трелка цвета отметки — как �оперник наказывает ход. +3. **«Пройти в�е ошибки»** — в отчёте �чётчики «�еточно�ти / Ошибки / Зевки» у каждого игрока: ка�ание закрывает ли�т и ведёт к �ледующему такому ходу �того игрока, по кругу. +4. **Парти� уже оценена.** Е�ли �та о�новна� лини� анализировала�ь раньше (к�ш) или у каждого хода е�ть `[%eval]` (выгрузки Lichess), график и отметки видны �разу при открытии, движок не нужен. +5. **Сборка без движка.** «�нализировать» без �качанного движка открывает ли�т �качивани� (§8.4); когда движок готов, анализ начинает�� �ам. +6. **Вход один — первый пункт меню ⋮** (ревью 2026-10-23). �ижн�� панель полна (§7.4), отдельной кнопки нет. Пункт называет�� «�нализ партии», пока оценок нет, и «Отчёт по партии», когда они е�ть (тогда он открывает отчёт и возвращает �крытую панель). Пока идёт первый анализ и оценок ещё нет, пункт неактивен: панель � ходом анализа уже на �кране. �овый анализ при готовом отчёте — кнопкой «�нализировать заново» в отчёте. +7. **Убрать � �крана.** «Скрыть анализ» в отчёте убирает панель и отметки в нотации до �ледующего открыти� партии. �нализ при �том не удал�ет��. + +### 21.2. Ли�т запу�ка «�нализ партии» + +``` +┌────────────────────────────────────� +│ �нализ партии │ 22sp +│ Движок оценит каждую позицию │ +│ о�новной линии. Сама парти� не │ +│ изменит��. │ +│ │ +│ Позиций: 80, примерно 2 мин │ +│ │ +│ [Отмена] [�нализировать] │ +└────────────────────────────────────┘ +``` + +- Параметров нет (решение владельца 2026-10-28, `docs/decisions.md` «Разбор партии на фик�ированных параметрах движка»): пои�к один и тот же на в�ех телефонах и компьютерах — 1 млн узлов, один поток, Hash 32 МБ, проце��ов движка по чи�лу �дер (до 4, по �вободной пам�ти), `nice 10`. �а�тройки движка (§9) отно��т�� только к живому анализу. +- Оценка времени — по �коро�ти одного проце��а, измеренной в прошлый раз на �том телефоне (�начала — о�торожна� прикидка), × чи�ло проце��ов, �ловами «примерно 2 мин». +- Е�ли ча�ть позиций уже оценена �тим же пои�ком, под оценкой времени �трока «Уже оценено позиций: 60 из 80.», а кнопка — «Дополнить» (только недо�тающие). «Заново» нет: тот же пои�к дал бы те же оценки. �ад оценками из PGN кнопка «�нализировать» �читает в�ё движком. +- Разбор, �деланный до �того решени� (на выбранном каче�тве), — у�таревший: панель (§21.3) пишет «�нализ �делан � прежними на�тройками движка» и «Обновить» — пере�читать в�ё. +- Оценка времени �читает только те позиции, которые будут �читать��: при «Дополнить» — недо�тающие. + +### 21.3. Панель анализа + +Между до�кой (и �трокой движка, е�ли он включён) и нотацией, 88 dp: �трока 48 dp и график 40 dp (крива� 32 dp и 8 dp �низу). Фон `surfaceContainerLow`, как у �троки движка. + +``` +│ ?? Зевок · лучше было 23…Кf6 Отчёт │ 48 �трока +│ �▂▃▅▆▇▇▆▅▃▂��▂▃▅ · · │ │ 40 график +``` + +- **Строка 48 dp**, а не 40: в ней нажимают�� «Отчёт», «Дополнить», ✕ и �ама �трока � ошибкой, а цели ка�ани� не меньше 48 dp (§12.2). Кнопка «Отчёт» не должна принимать ка�ани� на графике. +- **Строка** зави�ит от �о�то�ни� (по пор�дку важно�ти): + - идёт анализ — «�нализ партии · 23 из 80» и ✕ (о�тановить; по�читанное �охран�ет��); «Отчёта» нет; + - движок готовит�� (�борка � движком, первый запу�к) — «Готовлю движок…»; + - текущий ход � отметкой — значок и название («?? Зевок») цветом отметки и «лучше было 23…Кf6». Ход «23…Кf6» набирает�� цветом `primary`, как ��ылка: так видно, что �троку можно нажать. Ка�ание в�ей �троки (кроме «Отчёта») — предпро�мотр лучшей линии. Е�ли лучшей линии нет (оценки из `[%eval]`), ход и «лучше было» не показывают��, �трока не нажимает��; + - движок о�тановил�� — «�нализ прервал��» цветом `error` и «Продолжить»; + - не в�е позиции оценены — «Без оценки: 12» и «Дополнить»; + - иначе — «Точно�ть ○ 91% � 84%» (кружки — цвета �торон, белый � рамкой `outline`); TalkBack: «Точно�ть: белые 91%, чёрные 84%». + - Справа «Отчёт» во в�ех �о�то�ни�х, кроме хода анализа и подготовки движка. +- **График** — шан� на победу, как на компьютере и Lichess: �ветла� обла�ть — переве� белых, тёмна� — чёрных, оранжева� крива�, точки ошибок цветами отметок (поверх в�его, кроме линии текущего хода), тонкие линии начала миттельшпил� и �ндшпил�, вертикальна� лини� текущего хода (в варианте — хода, от которого он ответвил��). Ка�ание и прот�жка по графику перевод�т к ходу. + - **Подпи�ей �тадий на графике нет** (ревью 2026-10-23). В 48 dp подпи�и 10sp занимали треть вы�оты, закрывали кривую там, где она обычно идёт — у верхнего кра� при переве�е белых, были мельче �амого мелкого шрифта приложени� (12sp, §10.2) и при крупном шрифте выро�ли бы до 20sp. Линии �тадий о�тают��; точно�ть по �тади�м — в отчёте, названи� — в опи�ании дл� TalkBack. + - В TalkBack график — одно опи�ание: «График оценки» и �о�то�ние «ход 23, оценка +1,2». Под�казку «ко�ните�ь или проведите» не произно�ить: в TalkBack двойное ка�ание не выбирает ход на графике, а переходы по партии делают�� нотацией и ◀ ▶. +- Панель видна, пока е�ть оценки или идёт анализ. «Скрыть анализ» в отчёте убирает её до �ледующего открыти� партии; ⋮ → «Отчёт по партии» возвращает. +- **Вы�ота нотации.** Панель отнимает у нотации 88 dp из 256 (§7.1): о�таёт�� 168 dp, около трёх �трок; � включённым движком — 120, на развилке — 72. По�тому панель — только по про�ьбе (к�ш или `[%eval]` показывают её �разу, но «Скрыть анализ» убирает), а �трока движка во врем� анализа не ра�крывает�� (▾ �крыт). +- **В альбомной ориентации** панель �тоит в правой колонке над нотацией. Колонка низка� (около 220 dp над кнопками), по�тому при включённом движке график �крывает�� и о�таёт�� только �трока 48 dp; без движка панель полна�. + +### 21.4. Отметки в нотации + +- По�ле хода о�новной линии — плашка «?!», «?» или «??» 13sp на подложке цвета отметки (16 %), �кругление 4 dp, отдельно от автор�ких NAG: �то �лой движка, а не тек�т партии. Плашка �тоит вне заливки текущего хода, по�тому �охран�ет �вой цвет и на текущем ходе. +- Е�ли у хода уже е�ть автор�кий знак � тем же �имволом (автор по�тавил «?», движок — тоже ошибка), плашка не ри�ует��: «Кf6? ?» читает�� как опечатка. Е�ли знаки разные («Кf6!?» и зевок движка) — видны оба. +- Цвета — цвета NAG Lichess (§10.3): неточно�ть — как `?!`, ошибка — как `?`, зевок — как `??`. +- Отметки только в таблице о�новной линии; в тек�те вариантов их нет (варианты не оценивают��). +- TalkBack читает «4, белые, Кf3, зевок». + +### 21.5. Ли�т «Отчёт по партии» + +Две колонки — белые и чёрные р�дом, как на Lichess (ревью 2026-10-23). В первой реализации игроки шли друг под другом: ли�т вы�отой около 1000 dp открывал�� наполовину, и �чётчики чёрных — обычно �амое интере�ное — оказывали�ь за краем �крана; �равнить игроков можно было только прокруткой. + +``` +│ Отчёт по партии │ 22sp +│ ○ Морфи � Герцог │ имена 14sp/500, до 2 �трок +│ Точно�ть 98 % 79 % │ 24sp/500 +│ ?! �еточно�ти 0 3 › │ �троки 48 dp; �чейка +│ ? Ошибки 0 2 › │ �о �чётом > 0 нажимает�� +│ ?? Зевки 0 0 │ +│ Средн�� потер� │ +│ �антипешек 8 64 │ 14sp, onSurfaceVariant +│ Дебют 96 % 80 % │ +│ Миттельшпиль 100 % 78 % │ �трока �тадии — е�ли е�ть +│ Эндшпиль — — │ хоть у одного игрока +│ │ +│ Stockfish 19 · 250k узлов на ход │ или «Оценки из PGN ([%eval])» +│ [Скрыть анализ] (�нализировать заново) │ +``` + +- Колонка подпи�ей занимает о�таток ширины, колонки игроков — по 96 dp, чи�ла по правому краю, моноширинные цифры. Им� игрока — фамили� до зап�той («Morphy, Paul» → «Morphy»), до двух �трок, дальше многоточие; полное им� — в TalkBack. +- Ячейка «3 ›» �о �чётом больше нул� — цель ка�ани� 96×48 dp: ли�т закрывает��, парти� переходит к �ледующему такому ходу �того игрока, по кругу. Счёт набирает�� цветом отметки, нуль — `onSurfaceVariant` без ›. +- TalkBack читает �троку �чейками: «�еточно�ти, чёрные, 3, кнопка, перейти к �ледующему такому ходу». +- Ли�т открывает�� �разу целиком (`skipPartiallyExpanded`), как ли�т «Добавить базу»: в нём нечего пр�тать за краем. �а маленьком �кране и при крупном шрифте он прокручивает��. +- Точно�ть по �тадии показывает��, только е�ли в �тадии не меньше трёх ходов игрока (как на компьютере); иначе «—». +- Пока оценены не в�е позиции, точно�ти нет («—»), �чётчики — по оценённому. +- Кнопки: «Скрыть анализ» (тек�това�) и «�нализировать заново» (контурна�, открывает ли�т запу�ка; пока идёт анализ, неактивна). + +### 21.6. Правила + +- �нализ — отдельный проце�� движка (nice 10, потоки и пам�ть из на�троек). Пока он идёт, живой движок �тоит на паузе: �трока движка «Пауза: идёт анализ партии» (� заглавной: �то отдельна� �трока, а не хво�т «гл. 26 · пауза»), без ▾; по�ле анализа �чёт продолжает�� �ам. +- Экран пога� или приложение ушло в фон — анализ о�танавливает�� (батаре�, §8.3), по�читанное �охран�ет��; при возврате он продолжает�� �ам � недо�тающих позиций. +- Выход из партии и ‹ › о�танавливают анализ; по�читанное хранит�� в к�ше приложени� и показывает�� при �ледующем открытии �той партии. +- Оценивает�� только о�новна� лини�; варианты не трогают��. + +## 22. Ревью отчёта по партии (2026-10-23) + +Что изменено в §21 по итогам ревью реализации (`ReviewViews.kt`, `GameScreen.kt`, `Notation.kt`) и �нимков � �мул�тора: + +- §21.1 — вход один: первый пункт ⋮; пункт неактивен, пока идёт первый анализ без оценок; «Скрыть анализ» убирает и панель, и отметки. +- §21.2 — при ча�тичной оценке «Заново» (отдельна� �трока `review_restart`) и «Дополнить», без «Отмены»; врем� — только дл� �читаемых позиций. +- §21.3 — �трока 48 dp и график 40 dp (обща� вы�ота та же, 88 dp): цели ка�ани� по §12.2. Подпи�ей �тадий на графике нет. Ход «лучше было …» цветом `primary` как признак нажати�. Пор�док �о�то�ний. TalkBack у графика без под�казки про же�ты. Бюджет нотации и альбомна� ориентаци�: при движке график �крыт. +- §21.4 — плашка не дублирует такой же автор�кий знак. +- §21.5 — отчёт в две колонки (белые | чёрные), ли�т открывает�� целиком. +- §21.6 — «Пауза: идёт анализ партии» � заглавной, без ▾. +- §12.3, §14.7 — озвучивание и таблица �трок; правки «Скрыть анализ», «Лучша� лини� · ход …», «к �ледующему такому ходу»; `review_no_line` удалить. +- По итогам те�тировани� (2026-10-23): поворот телефона во врем� анализа не о�танавливает его на�ов�ем — анализ продолжает�� �ам, как по�ле возврата из фона; по�читанное пишет�� в к�ш и по ходу работы (раз в 10 �), чтобы падение приложени� не тер�ло минуты работы; «Дополнить» �читает � тем же каче�твом, что и первый прогон (один отчёт — одно каче�тво), по�тому оценка времени при «Дополнить» берёт прежнее каче�тво, а выбор каче�тва отно�ит�� к «Заново»; у партии без ходов пункт ⋮ неактивен; пат в конце, как и мат, движку не отдаёт��; в альбомной ориентации права� колонка не заходит под �и�темные кнопки. + +## 23. Партии � Lichess и Chess.com (2026-10-23) + +То же, что на компьютере (0.8.0, `CHANGELOG.md`): партии любого игрока по нику — �вои, ученика, �оперника — без входа на �айт, в базу PGN; позже «Скачать новые партии» добавл�ет только новые. Скачивание, файл �о�то�ни�, продолжение по�ле обрыва без повторов — общий крейт `online-games`, тот же, что на компьютере. + +Сеть: обе �борки получают разрешение INTERNET (раньше �борка � движком в �еть не ходила). В �еть ничего не уходит, пока человек �ам не нажал «�айти» или «Скачать»; при запу�ке �айты не опрашивают�� (на компьютере опрашивают�� — на телефоне �то лишний трафик и батаре�). + +### 23.1. Пути пользовател� + +1. **Первый раз.** Базы → «Добавить базу» → «Партии � Lichess и Chess.com» (перва� �трока ли�та, по�ле «В�тавить из буфера», е�ли она е�ть) → �кран: ник → «�айти» → что нашло�ь на каждом �айте → «Скачать». Ход �качивани� виден на �том же �кране; � �крана можно уйти — база уже в �пи�ке, её �трока показывает «Скачивает�� · 1 234». Когда готово — «Открыть базу». +2. **�овые партии.** Механизм — докачка (решение владельца): «Скачать новые партии» берёт только партии, �ыгранные по�ле прошлого �качивани�. Два входа: �трока базы → ⋮ и значок ⤓ в верхней панели «Партий» �той базы (§23.3). Итог — �некбар «Magnus: +12, в�его 1 246» или «Magnus: новых партий нет», как на компьютере. Без �некбара человек не узнаёт, что докачка прошла впу�тую: подпи�ь «обновлено 1 мин назад» �того не говорит. +3. **Разные ники.** С�ылка «�а Chess.com другой ник» открывает второе поле; первое тогда называет�� «�ик на Lichess». +4. **Оба �айта.** �айдены оба — по умолчанию одна база «�ик (Lichess + Chess.com)»; выключенный переключатель «Объединить оба �айта в одну базу» делает две. +5. **Обрыв.** �ет �ети, �айт про�ит паузу, приложение закрыли — �качанное о�таёт�� в базе, подпи�ь «не докачана» или тек�т ошибки, «Скачать новые партии» продолжает � того же ме�та без повторов. +6. **Удаление.** «Убрать из �пи�ка» удал�ет �качанную базу � телефона, как копию (§20), �о �некбаром «Скачанна� база удалена · Вернуть»; идущее �качивание при �том о�танавливает��. +7. **�ичего не �качало�ь** (на �айте только варианты шахмат или ошибка � первого запро�а) — базы � нулём партий не бывает: �трока и�чезает из �пи�ка, а на �кране �качивани� о�таёт�� причина. + +Отдельной кнопки «Lichess» на �кране «Базы» нет: вход в ли�те «Добавить базу» до�таточно заметен (�то перва� по�то�нна� �трока), а лишн�� кнопка �порила бы � «+ Добавить». Пу�той �кран (§3.1) упоминает �айты в тек�те `db_empty_body` — так новичок узнаёт о возможно�ти до того, как откроет ли�т. + +### 23.2. Экран «Партии � Lichess и Chess.com» + +``` +┌────────────────────────────────────� +│ � Партии � Lichess и Chess.com │ +│ │ +│ Скачать партии любого игрока по │ +│ нику: �вои, ученика, �оперника. │ +│ ┌ �ик игрока ──────────────────� │ поле, «как на �айте» +│ └──────────────────────────────┘ │ +│ �а Chess.com другой ник │ ��ылка → второе поле +│ [�айти] │ +│ ─────────────────────────────── │ +│ ☑ Lichess · Magnus │ по�ле пои�ка +│ до 6 541 партии · ≈ 6 мин │ +│ ☑ Chess.com · magnus │ +│ ме��цев � парти�ми: 84 │ +│ Объединить оба �айта в одну (�) │ только е�ли отмечены оба +│ базу │ +│ Иначе у каждого �айта �во� база │ +│ В новую базу «Magnus (Lichess + │ +│ Chess.com)» │ +│ [Скачать] │ +└────────────────────────────────────┘ +``` + +Уточнени� по�ле ревью (2026-10-23): + +- **Пол� �крана 16 dp** (§10.1), не 24: 24 — дл� ли�тов. С�ылка «�а Chess.com другой ник» выровнена по левому краю пол� (у `TextButton` �вой от�туп 12 dp — его убрать `contentPadding`, иначе ��ылка «�ъезжает» вправо, как на �нимке). +- **Заголовок в верхней панели** — `online_title`. Он перено�ит�� на две �троки и при шрифте 200 % занимает три; е�ли те�тировщик увидит обрезку, в панели показывать короткое `online_title_short` «Lichess и Chess.com», а полное им� о�тавить в ли�те «Добавить базу». +- **Вводный тек�т** `bodyMedium` (14sp), не `bodyLarge`: �то по��нение, а не �одержание; так поле ника поднимает�� выше клавиатуры. +- **Правило ника** — кра�ным, только е�ли в нике е�ть недопу�тимый знак или в нём больше 30 знаков. �ик из одной буквы, пока его печатают, не ошибка: «�айти» про�то неактивна. Ребёнок не должен видеть кра�ное по�ле первой же буквы. +- **«�айти»** �крывает клавиатуру (результаты иначе о�тают�� под ней) и прокручивает к ним. По�ле пои�ка, пока ник не изменён, «�айти» �тановит�� контурной: главна� кнопка на �кране одна — «Скачать». +- **Строка Lichess:** «до 6 541 партии · первый раз около 6 мин». «До» — потому что в �чёт �айта вход�т и варианты шахмат, которые не �качивают��. Чи�ло � предлогом �клон�ет�� отдельным plurals `games_up_to` (RU: «до 1 партии», «до 24 партий», «до 6 541 партии»), а не через `games_count` — «до 24 партии» неграмотно. Е�ли на �качивание нужно меньше минуты — «первый раз меньше минуты». +- **�е найден** — как на компьютере: «Lichess: игрока � таким ником нет — проверьте напи�ание», без галочки. Сайт не ответил — тек�т ошибки (§23.4) цветом `error` и «Попробовать ещё раз». +- **Переключатель** «Объединить оба �айта в одну базу» — �трока 64 dp целиком переключает (`toggleable`, роль Switch); по умолчанию включён. +- **Куда:** «В новую базу «…»» или «В базу «…» (там уже 1 234; добав�т�� только новые)». Им� — как в �пи�ке баз (� учётом переименовани�), а не им� файла. +- **По�ле «Скачать»** кнопка «Скачать» и галочки �крывают��, пока человек не нажмёт «�айти» �нова (новый ник или те же). Иначе в конце на �кране две заполненные кнопки — «Скачать» и «Открыть базу», и повторное «Скачать» неочевидно, что делает. +- **Карточка �качивани�:** им� базы (`titleMedium`), �трока хода («Lichess: 1 200 из примерно 6 541 · о�тало�ь около 5 мин», «Chess.com: ме��ц 12 из 84 · 340 партий»; общее чи�ло — цифрами, без �лова «партий»), поло�а, под ней `online_leave` «Можно уйти � �того �крана: база уже в �пи�ке, �качивание продолжит��» и «О�тановить» (контурна�). + - Поло�а при двух �айтах в одной базе — обща�: дол� = (номер �айта + дол� �айта) / чи�ло �айтов. Сейча� она доходит до конца на Lichess и �нова начинает�� � нул� на Chess.com. +- **Итог:** первое �качивание — «Готово: 6 541 парти�»; докачка — «+12, в�его 1 246»; без новых — «�овых партий нет, в базе 1 234»; о�тановлено — «О�тановлено, в базе 1 200». Затем «Открыть базу» (заполненна�). Ошибка — тек�т §23.4 цветом `error`, и при �том, е�ли в базе что-то е�ть, тоже «Открыть базу». +- **Поворот �крана** �охран�ет найденное (`found`, отметки) — человек не должен и�кать заново. + +### 23.3. Строка такой базы в �пи�ке + +- Значок формата «PGN», подпи�ь: «1 234 партии · обновлено 3 ч назад»; пока не закончено ни одно �качивание — «1 234 партии · не докачана». Меньше минуты назад — «обновлено только что» (не «1 минуту назад»). +- Во врем� �качивани�: «Скачивает�� · 1 234» и поло�а 2 dp по низу �троки; ⋮ → «О�тановить �качивание» (первым пунктом, на ме�те «Скачать новые партии»). +- Ошибка по�леднего �качивани� — подпи�ь цветом `error`, чи�ло партий о�таёт��: «1 234 партии · Lichess не отвечает». Сейча� �чёт пропадает, и база выгл�дит пу�той. ⋮ → «Скачать новые партии» пробует �нова. +- Конец любого �качивани�, пока виден �кран «Базы» (в том чи�ле начатого на �кране §23.2, е�ли человек ушёл � него), — �некбар 4 �: «Magnus: +12, в�его 1 246» / «Magnus: новых партий нет» / «Magnus: Lichess не отвечает» (коротка� форма). Дей�твие �некбара — «Открыть», е�ли в базе е�ть партии. Это един�твенна� обратна� �в�зь докачки из �пи�ка (§23.1 п. 2). +- **Верхн�� панель «Партий» такой базы:** р�дом � пои�ком значок `download` (Material Symbols), опи�ание «Скачать новые партии». Пока идёт �качивание — на его ме�те ✕ «О�тановить �качивание», под панелью поло�а 2 dp; по концу — тот же �некбар, и �пи�ок перечитывает�� �ам, о�тава��ь на ме�те прокрутки. Зачем: базу �воих партий открывают каждый день, и «новые партии» ищут там, где партии, а не в ⋮ �пи�ка баз. Свайп «пот�нуть, чтобы обновить» не делаем: же�т �крытый, а ребёнок его не найдёт (§0 п. 4). + +### 23.4. Тек�ты ошибок + +Как на компьютере: «{site} не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.»; «{site} про�ит �делать паузу…»; «{site} ответил непон�тно…»; «�е удало�ь запи�ать базу: на телефоне не хватает ме�та.»; «Эта база уже �качивает��.» Короткие формы дл� �троки базы и �некбара: «{site} не отвечает», «{site} про�ит паузу», «Скачивание прервало�ь». + +### 23.5. Пор�док партий (решение владельца, 2026-10-23) + +- В �качанной базе партии идут **от по�ледней �ыгранной к первой**: по `UTCDate` + `UTCTime`, е�ли их нет — по `Date`; партии двух �айтов перемешаны по времени. О�тальные базы — в пор�дке файла, как раньше. +- ‹ › в партии и пои�к идут в том же пор�дке; номер в �троке партии — ме�то в �том �пи�ке (№ 1 — �ама� �вежа�). +- По�ле докачки новые партии оказывают�� наверху — по�тому �пи�ок по�ле «Скачать новые партии» возвращает�� к началу только е�ли человек и так был в начале; иначе о�таёт�� на ме�те. +- Втора� �трока партии такой базы (предложение, nice): полна� дата вме�то года — «блиц · 12 мар. 2026 · C42». Год у в�ех партий за по�ледний ме��ц одинаков и не помогает найти «вчерашнюю». + +### 23.6. TalkBack + +- Строка хода �качивани� **не** жива� обла�ть: она мен�ет�� 2–3 раза в �екунду, и TalkBack читал бы её без о�тановки. Жива� обла�ть (`Polite`) — только итог и ошибки; ход читает�� по фоку�у. +- «Ищу на �айтах…» и найденные �троки — жива� обла�ть `Polite` один раз, по�ле пои�ка. +- �айденна� �трока: «Lichess, Magnus, до 6 541 партии, первый раз около 6 минут, флажок, отмечен». +- Строка базы во врем� �качивани�: «Magnus (Lichess + Chess.com), �качивает��, 1 234». +- Значок в «Парти�х»: «Скачать новые партии, кнопка» / «О�тановить �качивание, кнопка». + +## 24. Ревью «Партий � Lichess и Chess.com» (2026-10-23) + +Ревью реализации (`OnlineScreen.kt`, `DatabasesScreen.kt`, `AddDatabase.kt`, `OnlineDownloads.kt`, �троки `online_*` на ше�ти �зыках) и �нимков � �мул�тора. Что изменено в �пецификации: + +- §0 п. 7 — �еть нужна и дл� партий � �айтов, только по нажатию; §15.2 п. 6 — �делано. +- §23.1 — докачка как механизм обновлени� (решение владельца); второй вход «Скачать новые партии» — значок в «Парти�х» �той базы; итог докачки — �некбар; база без партий и�чезает; отдельной кнопки на «Базах» нет, о �айтах говорит пу�той �кран. +- §23.2 — пол� 16 dp; вводный тек�т 14sp и без повтора подпи�и ли�та; правило ника не кра�неет от первой буквы; «�айти» пр�чет клавиатуру; «Скачать» �крывает�� по�ле запу�ка (две заполненные кнопки в конце); обща� поло�а дл� двух �айтов; под�казка «можно уйти � �крана»; «Готово: N партий» вме�то «+N, в�его N» при первом �качивании; им� базы — как в �пи�ке; найденное переживает поворот. +- §23.3 — ошибка не пр�чет чи�ло партий; «обновлено только что»; �некбар по концу �качивани�; значок в верхней панели «Партий». +- §23.5 — пор�док партий от по�ледней (решение владельца), ‹ › и пои�к в том же пор�дке. +- §23.6 — TalkBack: ход �качивани� не жива� обла�ть. +- §14.8 — таблица �трок; падеж по�ле «до» и «из примерно» (`games_up_to`, голое чи�ло), разр�ды в `online_added`. +- По итогам те�тировани� (2026-10-23): найденное на �кране §23.2 живёт вме�те � �краном (у каждого �крана навигации �воё хранилище �о�то�ни� и ViewModel) — повторный вход начинает�� � чи�того �крана, поворот найденное �охран�ет; чи�ло партий и врем� обновлени� �качанной базы при запу�ке и по�ле «Вернуть» берут�� из файла �о�то�ни� �качивани� (докачка, оборванна� закрытием приложени�, �разу видна в �троке); �некбар «База удалена · Вернуть» держит�� 10 �, а не бе�конечно. Изве�тно: при шрифте 130 % подпи�ь �троки базы обрезает�� многоточием. + +## 25. Обновление приложени� (2026-10-23) + +> Сборка дл� RuStore (`decisions.md` «Сборка дл� RuStore», 2026-10-27) — без в�его �того раздела: проверки, карточки, ли�та, блока в «О программе» и разрешений на у�тановку; обновл�ет магазин. + +Приложение �тавит�� не из магазина, а файлом APK � �айта или �о �траницы выпу�ка на GitHub. Чтобы человек не ходил за новой вер�ией �ам, приложение узнаёт о ней, �качивает лёгкую �борку, провер�ет и передаёт Android на у�тановку. Базы, на�тройки и движок при �том о�тают��. Проверка — запро� к �айту, который отвечает �ведени�ми о по�леднем выпу�ке и заодно �читает у�тановки (§25.6), и �верка � `SHA256SUMS.txt`, как на компьютере (`apps/desktop/src/update.rs`). Слова тоже вз�ты � компьютера, где они там е�ть. + +Решени�: + +- **Проверка** — при каждом запу�ке приложени� и при возвращении в него, е�ли � прошлой проверки прошло 6 ч (изменено 2026-10-27: раз в �утки владелец не узнавал о выпу�ке, вышедшем через день по�ле прошлого). Её можно выключить в «О программе»; кнопка «Проверить �ейча�» работает и при выключенной проверке. Проверка же �читает у�тановки дл� �тати�тики �айта (§25.6), по�тому от предложений она не зави�ит. +- **Предложение** (� 2026-10-24, §28) — карточка над �пи�ком баз. Она отдельна от проверки: переключатель «Предлагать новые вер�ии» в «О программе». × на карточке выключает предложени� на�ов�ем, пока человек �ам не включит их �нова. Проверка при �том продолжает��, а нова� вер�и� видна в «О программе». +- **Где видно** — карточка над �пи�ком баз (е�ли предложени� включены) и втора� �трока пункта «О программе» в �а�тройках (в�егда, когда вер�и� изве�тна). Больше нигде: ни уведомлений, ни диалогов поверх партии. +- **Без GitHub.** В интерфей�е обновлени� нет ни ��ылок на GitHub, ни «Что нового»: �пи�ок изменений е�ть только по-англий�ки, а человеку дл� обновлени� он не нужен (§25.4). Един�твенна� внешн�� ��ылка — «Скачать на �айте» / «Открыть �айт» в ошибках (chess.vrubel.xyz, �айт переведён). +- **Скачивает�� в�егда лёгка� �борка.** Сборка � движком перед у�тановкой �охран�ет нейро�еть у �еб� в пам�ти (§25.6), по�тому движок у человека о�таёт�� без �качивани� 98 МБ. +- **Мобильный интернет.** �и вопро�а, ни предупреждени� нет: файл ве�ит около 9 МБ, размер виден в ходе �качивани�. Предупреждение о мобильном интернете е�ть только у движка (98 МБ, §8.4). +- **У�тановка** — через `PackageInstaller`. Е�ли Android показывает �вой вопро� «Обновить приложение?», на него отвечает человек. Перед �тим приложение один раз ведёт в �и�темную на�тройку «У�тановка неизве�тных приложений». + +### 25.1. Пути пользовател� + +1. **Обычный путь.** Человек открывает приложение, и над �пи�ком баз по�вл�ет�� карточка «Вышла вер�и� 0.15.0». Он нажимает «Обновить», открывает�� ли�т «Обновление»: загрузка 9 МБ, проверка, затем «У�танавливаю…». Android �прашивает «Обновить приложение?», человек отвечает «Обновить», и ChessPenguin закрывает��. Человек открывает его �нова и видит �кран «Базы» �о �некбаром «ChessPenguin обновлён: 0.14.0 → 0.15.0» (без дей�тви�). +2. **Первый раз: разрешение.** Е�ли у ChessPenguin ещё нет разрешени� �тавить приложени� (`canRequestPackageInstalls() == false`), то по�ле «Обновить» ли�т �начала объ��н�ет, что нужно �делать, и показывает «Открыть на�тройки». Открывает�� �и�темна� �траница именно �того приложени� (`Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES`, `package:io.github.vrubelroman.chesspenguin`). Человек включает переключатель и возвращает�� назад. + - Разрешение е�ть — загрузка начинает�� �ама, второй раз нажимать «Обновить» не нужно. + - Разрешени� нет — ли�т говорит, что без него Android не у�тановит обновление, и предлагает либо ещё раз «Открыть на�тройки», либо «Скачать на �айте». + - Е�ли Android перезапу�тил приложение, пока человек был в на�тройках (на некоторых телефонах так бывает при �мене �того разрешени�), ли�т по�ле запу�ка открывает�� поверх «Баз» в том же ме�те пути (§25.7, `awaitingPermission`). +3. **Без вопро�а Android.** Е�ли прошлое обновление по�тавил �ам ChessPenguin, Android 12+ может у�тановить �ледующее без �воего вопро�а (`SessionParams.setRequireUserAction(USER_ACTION_NOT_REQUIRED)` и разрешение `UPDATE_PACKAGES_WITHOUT_USER_ACTION`; у�лови� �тавит Android, а не мы). Путь такой же, только без �и�темного окна: по�ле «У�танавливаю…» приложение закрывает�� �амо. Тек�т ли�та одинаков в обоих �луча�х, вопро� Android в нём не обещает��. +4. **Сборка � движком.** Перед у�тановкой по�вл�ет�� шаг «Сохран�ю движок…»: не�колько �екунд нейро�еть копирует�� из APK в пам�ть приложени� (§25.6). По�ле обновлени� приложение �тановит�� лёгкой �боркой, а в «О программе» напи�ано «Stockfish �качивает�� в приложении». Движок при �том работает, и в �а�тройках он значит�� «Stockfish 19 · �качан». +5. **Сборка без движка.** Шага � движком нет. Скачанна� нейро�еть лежит в пам�ти приложени� и переживает обновление. +6. **Ушёл из приложени� во врем� загрузки.** Загрузку ведёт �и�темный `DownloadManager`: она идёт �о �вёрнутым и даже � закрытым приложением, ход виден в уведомлении �и�темы «Обновление ChessPenguin». Отдельное разрешение на уведомлени� не �прашивает�� (§2.2). Когда человек возвращает��: + - загрузка ещё идёт — карточка и ли�т показывают её ход; + - загрузка закончила�ь, пока его не было, — файл провер�ет��, и карточка говорит «Вер�и� 0.15.0 �качана · У�тановить». Сама у�тановка не начинает��: �и�темное окно не должно вы�кочить по�реди партии. + - ли�т был открыт, когда человек ушёл, — он так и о�таёт�� открытым, в �о�то�нии E «�ова� вер�и� �качана и проверена» � «У�тановить»: одно ка�ание, без неожиданного окна Android. +7. **Загрузка закончила�ь в приложении.** Ли�т открыт — проверка и у�тановка идут �разу, без нового ка�ани�, ведь человек ждёт именно �того. Ли�т закрыт и человек �мотрит партию — один �некбар 10 � «�ова� вер�и� �качана · У�тановить», а карточка на «Базах» переходит в �о�то�ние «�качана». +8. **Отменил вопро� Android** («Отмена» или «назад» в окне «Обновить приложение?»). Ли�т пишет «У�тановка отменена. �ова� вер�и� �качана — у�тановите её, когда будет удобно» и показывает «�е �ейча�» и «У�тановить». Файл о�таёт�� на телефоне, �качивать его заново не нужно. +9. **�ет интернета.** + - �втоматиче�ка� проверка молчит: карточки нет, �ообщений нет. Следующа� попытка — при �ледующем запу�ке, но не раньше чем через ча�. + - «Проверить �ейча�» пишет «�ет интернета — проверить обновлени� нельз�». + - «Обновить» без �ети пишет «�ет интернета. Подключите�ь к �ети и попробуйте ещё раз.» и показывает «Повторить». + - Е�ли �еть пропала во врем� загрузки, `DownloadManager` ждёт её �ам. В ли�те вме�то хода видно «�ет �ети. Загрузка продолжит�� �ама, когда �еть по�вит��.», а поло�а �тоит на ме�те. Ошибкой �то не �читает��. +10. **Пока лежит �качанна� 0.15.0, вышла 0.16.0.** Проверка находит 0.16.0, файл 0.15.0 удал�ет��, карточка показывает 0.16.0. Е�ли предложени� выключены, карточки нет и дл� 0.16.0: выключение отно�ит�� ко в�ем вер�и�м. Пока идёт загрузка или у�тановка, проверка не запу�кает��: начатое доводит�� до конца, а �ледующа� проверка предложит 0.16.0. +11. **По�тавил новую вер�ию вручную � �айта.** При запу�ке приложение видит, что �качанный файл не новее у�тановленной вер�ии, и молча его удал�ет. +12. **Выключил проверку.** Карточка и втора� �трока в �а�тройках пропадают, �трока «Предлагать новые вер�ии» �тановит�� неактивной. �ачата� загрузка доводит�� до конца: её начал �ам человек. «О программе» → «Проверить �ейча�» по-прежнему работает. +13. **Отказал�� от предложени� (×).** Карточка уходит, �некбар 10 � «Больше не предлагаем. Включить — в �а�тройках, «О программе»» � дей�твием «Вернуть» (на �лучай промаха). Проверка идёт дальше: карточки нет ни дл� �той, ни дл� �ледующих вер�ий. Втора� �трока у пункта «О программе» в �а�тройках о�таёт��, и обновить�� можно оттуда: «О программе» → «Обновить» (§25.5). +14. **Включил предложени� �нова.** Переключатель «Предлагать новые вер�ии» в «О программе». Е�ли нова� вер�и� уже изве�тна, карточка по�вит�� на «Базах» �разу; е�ли проверка давно не шла, она запу�кает�� (`checkIfDue`). +15. **Первый запу�к.** Предложени� включены, проверка включена (в отладочной �борке выключена). Перва� проверка — по�ле показа �пи�ка баз, как обычно. Е�ли человек по�тавил не по�леднюю вер�ию, карточка по�вит�� �разу; �то и е�ть нужный �лучай. �и вводного окна, ни вопро�а «предлагать ли обновлени�» нет. + +### 25.2. Карточка на �кране «Базы» + +Карточка — первый �лемент �пи�ка баз (и пу�того �крана §3.1, над пингвином). Она прокручивает�� вме�те �о �пи�ком и не закрепл�ет��. Показывает��, когда включены и предложени�, и проверка (или вер�ию нашла «Проверить �ейча�»): `offer && (auto || asked)`. + +``` +┌────────────────────────────────────� +│ ChessPenguin ⚙ │ +├────────────────────────────────────┤ +│ ┌────────────────────────────────� │ пол� 16, �верху 8 +│ │ [↑] Вышла вер�и� 0.15.0 [×]│ │ значок 24 + bodyLarge/500; × 48×48 +│ │ У ва� 0.14.0 │ │ bodyMedium, onSurfaceVariant +│ │ [Обновить] │ │ 48: FilledTonalButton +│ └────────────────────────────────┘ │ ≈ 116 dp +│ [PGN] Мои партии ⋮ │ +│ 1 248 партий · PGN │ +``` + +- **Вид.** `Surface` � фоном `surfaceContainerHigh` и �круглением 12 dp, без тени и рамки (§10.4). Внутренние пол�: 16 dp �лева, 12 �верху, 8 �низу (кнопка). Значок `system_update_alt` 24 dp цветом `primary` �тоит в 16 dp от тек�та. Карточка �покойна�, `primaryContainer` не и�пользует��: обновление — ново�ть, а не тревога. +- **×** — `IconButton` 48×48 в правом верхнем углу карточки (вплотную к краю, без �воего пол�), значок `close` 20 dp цветом `onSurfaceVariant`. Справа у заголовка поле 40 dp, чтобы длинный заголовок (de «Version 0.15.0 ist erschienen») перено�ил��, а не заезжал под ×. × — един�твенный �по�об убрать карточку: «�е �ейча�» на карточке больше нет, одна кнопка не путает�� � другой. +- **Одна �трока тек�та** — «У ва� 0.14.0». Спи�ка изменений, ��ылок и размера нет: размер виден в ходе загрузки, а что �охранит�� — в ли�те. +- **Со�то�ни� карточки:** + +| Со�то�ние | Справа вверху | Строка 2 | Кнопка | +|---|---|---|---| +| вышла вер�и� (`Available`) | × | «У ва� 0.14.0» | «Обновить» — открывает ли�т и начинает (`start`) | +| нужно разрешение / разрешени� нет (`NeedsPermission`) | × | «У ва� 0.14.0» | «Обновить» — открывает ли�т в шаге A/B | +| �качивает�� (`Downloading`) | `chevron_right` 24 dp, `onSurfaceVariant` (не кнопка) | поло�а 4 dp и «Скачано 3 из 9 МБ» (моноширинные цифры); без �ети — поло�а �тоит, «Ждёт �еть» | нет; ка�ание карточки открывает ли�т; вы�ота ≈ 88 dp | +| проверка, �охранение движка, у�тановка (`Busy`) | `chevron_right` | поло�а без хода и «Провер�ю файл…» / «Сохран�ю движок…» / «У�танавливаю…» | нет; как выше | +| �качана (`Ready`) | × | «Скачана и проверена» | «У�тановить» | +| ошибка (`Failed`) | × | коротка� причина цветом `error`: «�ет интернета», «�е хватает ме�та», «Файл повредил��», «Файл нельз� проверить», «Android не у�тановил», «Загрузка не удала�ь» | «Подробнее» — открывает ли�т � полным тек�том | + +- **Заголовок** во в�ех �о�то�ни�х один: «Вышла вер�и� {v}». +- **Почему во врем� загрузки нет ×.** Загрузку начал �ам человек, �то уже не предложение, а ход дела; отменить её можно в ли�те («Отменить»). Шеврон показывает, что карточка нажимает��. +- **× делает одно:** выключает предложени� (`setOffer(false)`), карточка уходит за 200 м� (`animateItem`), и по�вл�ет�� �некбар `SnackbarDuration.Long` «Больше не предлагаем. Включить — в �а�тройках, «О программе»» � дей�твием «Вернуть». «Вернуть» включает предложени� обратно, и карточка возвращает�� в том же �о�то�нии. �ичего другого × не трогает: �качанный файл о�таёт�� (в «О программе» — «У�тановить»), ошибка видна в «О программе», проверка идёт по-прежнему. +- **При выключенных предложени�х** карточки нет ни в каком �о�то�нии, даже когда человек начал обновление из «О программе»: ход виден в ли�те, в уведомлении `DownloadManager` и в «О программе»; когда файл �качан, приходит обычный �некбар «�ова� вер�и� �качана · У�тановить» (ответ на его �об�твенное дей�твие). +- **По�вление.** Ответ �айта обычно приходит меньше чем за �екунду по�ле запу�ка. Карточка выезжает �верху за 200 м� (`animateItem`), и �пи�ок �двигает��. Е�ли �пи�ок уже прокручен, перва� видима� �трока о�таёт�� на ме�те: так ведёт �еб� `LazyColumn` � ключами �трок. +- **Пу�той �кран** (§3.1). Карточка �тоит над пингвином � пол�ми 16 dp, о�тальна� компоновка не мен�ет��. + +### 25.3. Ли�т «Обновление» + +Это `ModalBottomSheet` � пол�ми 24 dp, как ли�т движка (`EngineSheet`, §8.4). Верх ли�та во в�ех �о�то�ни�х одинаков, мен�ет�� только нижн�� ча�ть. Ли�т открывает�� целиком (`skipPartiallyExpanded`). Закрыть его можно �вайпом, «назад» или кнопкой; закрытие не отмен�ет загрузку. + +``` +┌────────────────────────────────────� +│ ─── │ +│ Вышла вер�и� 0.15.0 │ titleLarge 22sp +│ У ва� 0.14.0 │ bodyMedium, onSurfaceVariant +│ │ 16 +│ Базы, на�тройки и движок о�танут��.│ bodyLarge +│ �а врем� у�тановки ChessPenguin │ +│ закроет�� — потом откройте его │ +│ �нова. │ +│ │ 16 +│ ……… нижн�� ча�ть по �о�то�нию ……… │ +└────────────────────────────────────┘ +``` + +- В лёгкой �борке без �качанного движка перва� �трока — «Базы и на�тройки о�танут��.» (`upd_keeps_no_engine`): обещать движок, которого нет, нельз�. +- Что изменило�ь в вер�ии, ли�т не ра��казывает: переведённого �пи�ка изменений нет, а пере�каз «и�правлени� и улучшени�» ничего не �ообщает. Человеку дл� решени� до�таточно знать, что вер�и� новее и что базы о�танут��. +- Е�ли в �тот момент �качивают�� партии (§23), над нижней ча�тью по�вл�ет�� �трока «Идёт �качивание партий: у�тановка его о�тановит, потом его можно продолжить.» Скачивание партий продолжает�� без повторов (§23.1 п. 5), по�тому вопро�а нет, е�ть только предупреждение. + +**�ижн�� ча�ть по �о�то�ни�м:** + +**A. �ужно разрешение** (до загрузки): + +``` +│ �ужно одно разрешение │ titleMedium 16sp/500 +│ Android �тавит приложени� не из │ bodyMedium +│ магазина только � вашего │ +│ разрешени�. Откроют�� на�тройки: │ +│ включите переключатель дл� │ +│ ChessPenguin и верните�ь назад. │ +│ │ 24 +│ [Отмена] [Открыть на�тройки] │ +``` + +**B. Разрешени� нет** — человек вернул��, не включив переключатель: + +``` +│ Разрешение не включено — без него │ bodyMedium, error +│ Android не у�тановит новую вер�ию. │ +│ Скачать на �айте ↗ │ ��ылка, 48 dp +│ │ +│ [Отмена] [Открыть на�тройки] │ +``` + +«Скачать на �айте» открывает `https://chess.vrubel.xyz` в браузере. Это че�тный обходной путь: тот же APK, по�тавленный руками, как в первый раз. + +**C. Скачивает��:** + +``` +│ ▬▬▬▬▬▬▬▬▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭ │ LinearProgressIndicator +│ Скачано 3 из 9 МБ │ bodyMedium, tnum +│ Ли�т можно закрыть: загрузка │ bodyMedium, onSurfaceVariant +│ продолжит��. │ +│ [Отменить] │ TextButton +``` + +- Без �ети (`STATUS_PAUSED` � причиной `PAUSED_WAITING_FOR_NETWORK` или `PAUSED_WAITING_TO_RETRY`) поло�а �тоит, а вме�то «Скачано…» напи�ано «�ет �ети. Загрузка продолжит�� �ама, когда �еть по�вит��.» +- «Отменить» удал�ет загрузку и файл, ли�т закрывает��, по�вл�ет�� �некбар «Загрузка отменена». Карточка возвращает�� в �о�то�ние «вышла вер�и�». + +**D. Проверка, �охранение движка, у�тановка** — поло�а без хода (`LinearProgressIndicator` без `progress`) и одна �трока: «Провер�ю файл…», затем в �борке � движком «Сохран�ю движок…», затем «У�танавливаю…». Кнопок нет: прерывать �ти шаги не нужно, каждый длит�� �екунды. Е�ли на шаге «У�танавливаю…» Android показывает �воё окно, оно в�таёт поверх ли�та. + +**E. Скачана** (вернул�� по�ле загрузки, отменил вопро� Android, нажал «У�тановить» на карточке): + +``` +│ �ова� вер�и� �качана и проверена. │ bodyMedium +│ │ +│ [�е �ейча�] [У�тановить] │ +``` + +По�ле отмены вопро�а Android перва� �трока — «У�тановка отменена. �ова� вер�и� �качана — у�тановите её, когда будет удобно.» + +«�е �ейча�» в ли�те (зде�ь, в �о�то�нии «вышла вер�и�» и в ошибках) только закрывает ли�т: карточка о�таёт��, предложени� не выключают��. Выключает их только × на карточке. + +**F. Ошибки** — тек�т цветом `error` (bodyMedium) и кнопки: + +| Ситуаци� | Тек�т | Кнопки | +|---|---|---| +| нет �ети при «Обновить» | �ет интернета. Подключите�ь к �ети и попробуйте ещё раз. | «�е �ейча�», «Повторить» | +| загрузка не удала�ь (`STATUS_FAILED`, кроме ме�та) | Загрузка не удала�ь. Попробуйте ещё раз. | «�е �ейча�», «Повторить» | +| нет ме�та дл� загрузки (`ERROR_INSUFFICIENT_SPACE` или проверка до начала: нужно в 2 раза больше файла, в �борке � движком ещё + размер нейро�ети) | �е хватает ме�та: нужно {size}. | «Пон�тно» | +| не �овпала �умма | Файл повредил�� при �качивании, по�тому не у�тановлен. Попробуйте ещё раз. | «�е �ейча�», «Скачать �нова» | +| в выпу�ке нет �уммы дл� файла, или `SHA256SUMS.txt` не �качал�� | С �тим выпу�ком что-то не так: файл дл� Android нельз� проверить. Скачайте новую вер�ию на �айте. | «Пон�тно», «Открыть �айт» | +| нет ме�та дл� у�тановки (`STATUS_FAILURE_STORAGE`) | Android не у�тановил новую вер�ию: не хватает ме�та. О�вободите {size} и попробуйте ещё раз. | «�е �ейча�», «Повторить» | +| друга� подпи�ь (`STATUS_FAILURE_CONFLICT`) | Android не у�тановил новую вер�ию: �тот ChessPenguin подпи�ан другим ключом. По�тавить новую вер�ию можно только по�ле удалени� �той, а при удалении пропадут �пи�ок баз и �качанные базы. | «Пон�тно», «Открыть �айт» | +| заблокировано (`STATUS_FAILURE_BLOCKED`) | У�тановку о�тановил Android или защита телефона. Скачайте новую вер�ию на �айте. | «Пон�тно», «Открыть �айт» | +| другое (`STATUS_FAILURE`, `_INVALID`, `_INCOMPATIBLE`) | Android не у�тановил новую вер�ию. Попробуйте ещё раз или �качайте её на �айте. | «Открыть �айт», «Повторить» | + +- У ошибок у�тановки под тек�том е�ть ��ылка «Подробно�ти». Она ра�крывает тек�т Android (`EXTRA_STATUS_MESSAGE`) моноширинным шрифтом 12sp � кнопкой «Копировать», как �кран ошибки §11. +- �и одна ошибка не удал�ет базы и на�тройки. Ошибки у�тановки не удал�ют и �качанный файл: «Повторить» не �качивает его заново. Повреждённый файл удал�ет�� �разу. +- В ли�т попадают только �ообщени� от `DownloadManager` и `PackageInstaller`. Сырые коды в о�новной тек�т не вывод�т��. + +### 25.4. «Что нового» — убрано (2026-10-24) + +- С�ылки «Что нового ↗» нет нигде: ни на карточке, ни в ли�те, ни в «О программе», ни в �некбаре по�ле обновлени�. Строки «Спи�ок изменений — на GitHub, по-англий�ки» тоже нет. +- Причина (решение владельца): ��ылка вела на англий�кую �траницу GitHub, а пользователи — в о�новном ру��ко�зычные и не техниче�кие — туда не ход�т, и дл� обновлени� им �то не нужно. Переведённого �пи�ка изменений у выпу�ков нет. +- Е�ли позже по�в�т�� короткие переведённые заметки к выпу�ку (например, на �айте или в ответе проверки по �зыку), их ме�то — одна-две �троки в ли�те под «У ва� 0.14.0», без внешних ��ылок. Пока �того нет, ничего не показываем. + +### 25.5. �а�тройки и «О программе» + +**Пункт «О программе» в �а�тройках** (§9). Когда изве�тна нова� вер�и� и проверка включена (или вер�ию нашла «Проверить �ейча�»), у пункта по�вл�ет�� втора� �трока цветом `primary`: «Вышла вер�и� 0.15.0», «Скачивает�� вер�и� 0.15.0…» или «Вер�и� 0.15.0 �качана». Она не зави�ит от предложений: при выключенных предложени�х �то и е�ть путь к обновлению. Точек-значков на ше�терёнке «Баз» нет. + +**Экран «О программе».** Блок «Обновлени�» �тоит �разу под �трокой вер�ии, выше тек�та о программе и лицензий. + +Когда нова� вер�и� изве�тна: + +``` +┌────────────────────────────────────� +│ � О программе │ +├────────────────────────────────────┤ +│ [пингвин 72] │ +│ ChessPenguin │ titleLarge +│ 0.14.0 · Stockfish уже внутри │ onSurfaceVariant +│ │ 24 +│ ОБ�ОВЛЕ�ИЯ │ labelLarge, primary +│ Вышла вер�и� 0.15.0 │ bodyLarge/500 +│ У ва� 0.14.0 │ bodyMedium, onSurfaceVariant +│ [Обновить] │ Button; по �о�то�нию — ход, +│ │ «У�тановить», ошибка + «Подробнее» +│ Предлагать новые вер�ии [�] │ �трока ≥ 72 dp, toggleable +│ Карточка на �кране «Базы», когда │ bodyMedium, onSurfaceVariant +│ выходит нова� вер�и�. │ +│ Провер�ть обновлени� [�] │ �трока ≥ 72 dp, toggleable +│ при запу�ке │ +│ Раз в день ChessPenguin �прашивает │ bodyMedium, onSurfaceVariant +│ у �воего �айта, кака� вер�и� │ +│ по�ледн��; �айт �читает работающие │ +│ у�тановки. Передают�� только │ +│ �лучайный номер �той у�тановки, │ +│ вер�и� и �и�тема. Проверка идёт и │ +│ при выключенных предложени�х. │ +│ Проверить �ейча� │ TextButton, левый край по тек�ту +│ Проверено �егодн� в 14:05 │ bodySmall, onSurfaceVariant +│ │ +│ Шахматна� база дл� про�мотра… │ about_text, �айт, лицензии +``` + +Когда новой вер�ии нет — вме�то первых трёх �трок «У ва� по�ледн�� вер�и�» (bodyLarge), о�тальное то же. + +- **Два переключател�, а не один.** «Предлагать новые вер�ии» — о том, что видно на главном �кране; «Провер�ть обновлени� при запу�ке» — о том, ходит ли приложение в �еть без нажати�. Человек, которому мешает карточка, выключает первый и о�таёт�� в �чёте у�тановок; человек, который не хочет никаких запро�ов, выключает второй, и тек�т под ним че�тно говорит, что именно уходит на �айт. Один переключатель � �тими двум� �мы�лами пришло�ь бы либо называть неправдой («Предлагать…», а он ещё и отключает запро�), либо лишать карточку �об�твенного выключател�. +- **Пор�док.** «Предлагать» �тоит первым: именно его ищет человек, пришедший по �некбару. «Провер�ть» — второй, � тек�том о том, что передаёт��. +- **Зави�имо�ть.** Когда проверка выключена, �трока «Предлагать новые вер�ии» неактивна (`enabled = false`, 38 %), её значение �охран�ет��, а подпи�ь мен�ет�� на «Работает, когда включена проверка обновлений.» Включение проверки возвращает �троку в прежнее значение. +- **По умолчанию** оба включены (в отладочной �борке проверка выключена, §25.6). Включение «Предлагать» запу�кает `checkIfDue()`; е�ли вер�и� уже изве�тна, карточка по�вл�ет�� �разу. +- **«Обновить» при выключенных предложени�х** работает как обычно: открывает ли�т и начинает. Карточка на «Базах» при �том не по�вл�ет�� (§25.2). +- **«Проверить �ейча�»** на врем� запро�а �тановит�� �трокой «Провер�ю…» � маленьким индикатором 16 dp. Результат по�вл�ет�� в том же блоке: + - нова� вер�и� — блок «Вышла вер�и�» выше; карточка на «Базах» тоже по�вл�ет��, е�ли предложени� включены (даже при выключенной проверке: человек �ам �про�ил, `asked`); + - новой нет — «У ва� по�ледн�� вер�и�» и �некбар � тем же тек�том, чтобы нажатие не прошло незаметно; + - ошибка — �трокой цветом `error` под кнопкой: «�ет интернета — проверить обновлени� нельз�» или «�е удало�ь проверить обновлени�: �айт не ответил. Попробуйте позже.» +- **«Проверено …»** — врем� по�ледней удачной проверки: «�егодн� в 14:05», «вчера в 09:12», «12 окт.» (`DateUtils`). Е�ли удачной проверки ещё не было, �троки нет. +- **Переключатель проверки** выключенный пр�чет карточку и вторую �троку в �а�тройках. �ачатую загрузку он не отмен�ет (§25.1 п. 12). +- Пока изве�тна� вер�и� пришла из прошлой проверки, а не из только что �деланной, блок в�ё равно её показывает: �ведени� хран�т�� (§25.7). + +### 25.6. Правила + +- **Когда провер�ть.** Проверка идёт при каждом запу�ке приложени� (первый `ON_START` проце��а), как на компьютере, и при возвращении из фона (`ON_START`), е�ли � по�ледней удачной проверки прошло не меньше 6 ч (до 2026-10-27 — 24 ч и при запу�ке тоже). По�ле неудачной попытки �ледующа� — не раньше чем через 1 ч. Запро� идёт в фоне по�ле того, как показан �пи�ок баз, и не держит за�тавку. Таймауты как на компьютере: �оединение 10 �, ответ 30 �. Пока идёт загрузка или у�тановка обновлени�, проверка не запу�кает��. +- **Что �читает�� обновлением.** Выпу�к `releases/latest` (без предварительных), у которого вер�и� выше `BuildConfig.VERSION_NAME` при �равнении чи�ел `major.minor.patch`, а �реди файлов е�ть `ChessPenguin-<вер�и�>-android-noengine.apk` и `SHA256SUMS.txt`. Выпу�к без файла дл� Android (например, только дл� компьютера) обновлением не �читает��, и карточка не по�вл�ет��. +- **Счёт у�тановок.** Тот же запро� передаёт �айту �лучайный номер у�тановки (`installId`, делает�� один раз), вер�ию и �и�тему (`android` / `android-noengine`); �айт по ним �читает работающие у�тановки. По�тому запро� зави�ит только от «Провер�ть обновлени� при запу�ке», а не от «Предлагать новые вер�ии» (§25.5). �ичего другого не передаёт��, и тек�т под переключателем говорит �то пр�мо (`upd_auto_sub`). +- **Отладочна� �борка** при запу�ке не провер�ет (переключатель выключен по умолчанию): у неё другой ключ, и у�тановка в�ё равно закончила�ь бы ошибкой подпи�и. +- **Магазины** (§15.2 п. 9). Сборка дл� F-Droid или Google Play выходит без �той функции и без разрешени� `REQUEST_INSTALL_PACKAGES`: там обновл�ет магазин. +- **Загрузка.** Файл �качивает `DownloadManager` в папку приложени� (`getExternalFilesDir("updates")`, разрешени� не нужны), видимо�ть `VISIBILITY_VISIBLE`. Уведомление о завершении не показывает��: нажатие на такое уведомление открыло бы APK в обход проверки. Разрешена загрузка через мобильный интернет и роуминг. Идентификатор загрузки хранит��, по�тому по�ле перезапу�ка приложение подхватывает её так же, как загрузку движка (`EngineFiles`). +- **Проверка файла.** SHA-256 файла �вер�ет�� �о �трокой дл� �того имени в `SHA256SUMS.txt` того же выпу�ка. `SHA256SUMS.txt` (не�колько �отен байт) �качивает�� при проверке выпу�ка, и �умма хранит�� вме�те � найденной вер�ией (`latest`). Выпу�к без �уммы дл� лёгкой APK �разу показывает�� ошибкой «С �тим выпу�ком что-то не так» (коротка� �трока на карточке — «Файл нельз� проверить»), а выпу�к без файла дл� Android обновлением не �читает��. Файл, не прошедший проверку, удал�ет��. +- **Сохранение движка (�борка � движком).** Перед у�тановкой, е�ли нейро�ети ещё нет в пам�ти приложени�, она копирует�� из APK тем же кодом, что при первом включении движка (`EngineFiles.prepare()`, � проверкой �уммы). Е�ли ме�та не хватает, шаг молча пропу�кает��: по�ле обновлени� движок предложит �качать �еб� (§8.4), как в любой лёгкой �борке. Е�ли нова� вер�и� и�пользует другую нейро�еть, �копированна� не подойдёт. Тогда нова� вер�и� при первом запу�ке удал�ет из `files/engine` нейро�ети, которые ей не нужны, и движок тоже предлагает�� �качать. +- **У�тановка.** Се��и� `PackageInstaller` (`MODE_FULL_INSTALL`, `setRequireUserAction(USER_ACTION_NOT_REQUIRED)`; на Android 13+ — ещё и `setPackageSource(PACKAGE_SOURCE_DOWNLOADED_FILE)`). Итог приходит в `PendingIntent`. `STATUS_PENDING_USER_ACTION` открывает окно Android, но только когда приложение на �кране. Е�ли приложение в фоне, окно откроет�� при возвращении. Е�ли окно Android закрыто и приложение �нова на �кране, а итога нет, �е��и� отмен�ет�� (`abandon`) и ли�т переходит в �о�то�ние E. +- **По�ле у�тановки** Android завершает проце�� приложени�. Сам �еб� ChessPenguin не перезапу�кает, по�тому в ли�те че�тно напи�ано «откройте его �нова». При первом запу�ке новой вер�ии приложение �равнивает `installingFrom` и текущую вер�ию, показывает �некбар «ChessPenguin обновлён: {from} → {to}» (10 �, без дей�тви�) и удал�ет APK и �о�то�ние обновлени�. +- **Партии и анализ** во врем� у�тановки ведут �еб� как при закрытии приложени�: �качивание партий потом продолжает�� без повторов (§23), анализ партии уже запи�ан в к�ш (§22). Загрузка движка идёт в `DownloadManager` и переживает у�тановку. + +### 25.7. Что хранит�� + +В�ё хранит�� в `SharedPreferences("update")`, которые переживают обновление. Файл — в `getExternalFilesDir("updates")`. + +| Ключ | Что | Когда �тирает�� | +|---|---|---| +| `autoCheck` | переключатель «Провер�ть обновлени� при запу�ке», по умолчанию `true` (`false` в отладочной �борке) | никогда | +| `lastCheckOk` / `lastAttempt` | врем� по�ледней удачной проверки и по�ледней попытки | — | +| `latest` | вер�и�, `html_url` �траницы, им�, адре�, размер и SHA-256 лёгкой APK по�леднего найденного выпу�ка | когда вер�и� у�тановлена или найдена новее | +| `offerUpdates` | переключатель «Предлагать новые вер�ии», по умолчанию `true`; × на карточке �тавит `false` | никогда | +| `hiddenVersion` (до 2026-10-24) | вер�и�, �пр�танна� прежним «�е �ейча�» | удал�ет�� при первом запу�ке новой вер�ии; в `offerUpdates` не переводит��: прежнее «�е �ейча�» значило «не �ту вер�ию», а не «никогда» | +| `downloadId` / `downloadVersion` | загрузка `DownloadManager` | по окончании или отмене | +| `readyVersion` | проверенный файл, готовый к у�тановке | по�ле у�тановки, при отмене, при более новой вер�ии | +| `awaitingPermission` | вер�и�, ради которой человек ушёл в на�тройки разрешени� | при возвращении и проверке разрешени� | +| `installingFrom` | вер�и� до у�тановки | при первом запу�ке новой вер�ии: переходит в `updatedFrom` | +| `updatedFrom` | �некбар «обновлён: {from} → {to}» ждёт показа (`updatedPage` больше не нужен и удал�ет��) (Android может �начала запу�тить новую вер�ию в фоне, только чтобы передать ей ответ у�тановщика) | когда �некбар показан | + +�е хранит��: открыт ли ли�т, тек�ты ошибок. По�ле перезапу�ка ошибка загрузки показывает�� заново только дл� �о�то�ний, которые видны по `DownloadManager`. + +### 25.8. TalkBack + +- Карточка — одна группа (`semantics(mergeDescendants = false)`, заголовок `heading()`): «Вышла вер�и� 0.15.0, заголовок», «У ва� 0.14.0». Дальше по пор�дку �крана: «�е предлагать обновлени�, кнопка» (×, `contentDescription = upd_dismiss_cd`; �лово «Закрыть» не годит�� — оно не говорит, что предложений больше не будет), «Обновить, кнопка». Пор�док обхода е�те�твенный, `traversalIndex` не нужен. +- Снекбар по�ле × объ�вл�ет�� как обычный, его дей�твие — «Вернуть». +- Карточка во врем� загрузки — одна кнопка: «Обновление до 0.15.0, �качано 3 из 9 мегабайт, кнопка, открыть». Ход — `progressBarRangeInfo` поло�ы, не жива� обла�ть. +- В ли�те жива� обла�ть `Polite` объ�вл�ет только �мену шага: «�ужно разрешение», «Скачиваю», «Провер�ю файл», «У�танавливаю», «�ова� вер�и� �качана», «У�тановка отменена» и тек�т ошибки. Ход загрузки не объ�вл�ет��: он мен�ет�� дважды в �екунду (так же �делано в §23.6). +- По�ле возвращени� из �и�темных на�троек � выданным разрешением TalkBack объ�вл�ет «Разрешение е�ть, �качиваю». +- Переключатели в «О программе» — �троки целиком (`toggleable`, `Role.Switch`): «Предлагать новые вер�ии, включено, переключатель» (выключенна� проверка: «…, недо�тупно»), «Провер�ть обновлени� при запу�ке, включено, переключатель». +- Снекбар «ChessPenguin обновлён…» объ�вл�ет�� как обычный �некбар, дей�тви� у него нет. + +## 26. Изменени� ради обновлени� приложени� (2026-10-23) + +- §25 — новый раздел: проверка при запу�ке, карточка на «Базах», ли�т «Обновление» � шагами A–F, блок «Обновлени�» в «О программе», правила, хранение, TalkBack. +- §0 п. 7 — проверка обновлений как един�твенный запро� без нажати�, выключает��. +- §2.1 — путь обновлени� на карте �кранов; §2.2 — уведомление загрузки показывает `DownloadManager`, разрешение на уведомлени� по-прежнему не нужно. +- §9 — втора� �трока у пункта «О программе». +- §11 — �троки про ошибки обновлени� и проверки. +- §12.3 — озвучивание карточки и «Что нового». +- §14.9 — таблица �трок `upd_*`. +- Манифе�т: разрешени� `REQUEST_INSTALL_PACKAGES` и `UPDATE_PACKAGES_WITHOUT_USER_ACTION` — только в �борках � �айта и GitHub, не в будущих �борках дл� магазинов (§25.6). +- Открыто дл� владельца: (1) �охран�ть ли нейро�еть перед у�тановкой в �борке � движком (§25.6; предложение дизайнера — да, �то 0 МБ �ети вме�то 98); (2) приложение по�ле у�тановки не открывает�� �амо — Android �того не делает, по�тому тек�т че�тно про�ит открыть его �нова (`upd_closes`). + +## 27. Обновление 2026-10-24: плашки игроков и имена в �пи�ке + +Повод: на �кране партии верхн�� панель ча�то пр�тала фамилию чёрных («Белые – Чёрные» в одной �троке р�дом � ‹ › ⋮; имена без зап�той, вроде «Вафин Радель», шли целиком), в �пи�ке партий обрезал�� �оперник. Решени� владельца: плашки игроков как на Lichess; в �пи�ке каждый игрок на �воей �троке. + +- §7.2, §7.11 — новые плашки 36 dp: чёрные над до�кой, белые под ней, при перевороте мен�ют�� ме�тами; кружок цвета, полное им� (при нехватке ме�та — `shortName()`, потом многоточие), Эло, результат `1` / `0` / `½` �права в�егда, когда он изве�тен. Плашки не нажимают��; без имени — «Белые» / «Чёрные» �ерым, плашка о�таёт��. Ча�ов нет (§15.2 п. 10). +- §7.1 — �хема и бюджет вы�оты: нотации 184 dp вме�то 256 (3,8 �троки), � движком 133. +- §7.7, §13.1, §13.3 — заголовок: «турнир · год» и «12 из 340 · тур 5»; результата в заголовке больше нет; ка�ание заголовка открывает «Сведени�». +- §13.1, §13.2, §13.3 — в альбомной ориентации плашки в правой колонке (первой и по�ледней �трокой), до�ка не уменьшает��; на планшете в портрете — над до�кой и под ней шириной � до�ку. +- §6.1, §6.2 — �трока �пи�ка 80 dp в три �троки: белые, чёрные, подробно�ти; номер на базовой линии белых; результат у каждого игрока в колонке 24 dp; Эло у имени; �тюд без чёрных — название в две �троки; одно правило имени `PlayerName` �о �пи�ком и плашками. +- §12.3, §14.3, §14.4 — озвучивание �троки, плашки и заголовка; �троки `row_desc_*`, `elo_n`, `round_n`, `player_*`, `title_info_hint`; `game_pos` без результата. + +## 28. Обновление 2026-10-24: предложение обновлени� без GitHub + +Повод (владелец): карточка на «Базах» показывала «Что нового ↗» и вела на англий�кую �траницу GitHub; было непон�тно, как убрать карточку; предложение должно быть ненав�зчивым, отказ — окончательным до включени� в �а�тройках. Ограничение разработчика: фонова� проверка �читает у�тановки дл� �тати�тики �айта, по�тому отказ от предложений не должен выключать проверку. + +- §25 (решени�), §25.4 — «Что нового», ��ылки на GitHub и �трока «Спи�ок изменений — на GitHub, по-англий�ки» убраны отов�юду: карточка, ли�т, «О программе», �некбар «обновлён». Заметок к выпу�ку в приложении нет. +- §25.2 — карточка: заголовок, одна �трока «У ва� {v}», одна кнопка; × в правом верхнем углу вме�то «�е �ейча�»; во врем� загрузки и у�тановки вме�то × — шеврон, в�� карточка открывает ли�т; таблица �о�то�ний. +- §25.1 п. 13–15, §25.2 — × выключает предложени� (`offerUpdates = false`) дл� в�ех �ледующих вер�ий; �некбар «Больше не предлагаем. Включить — в �а�тройках, «О программе»» · «Вернуть»; проверка и �чёт у�тановок продолжают��. +- §25.5 — новый переключатель «Предлагать новые вер�ии» над «Провер�ть обновлени� при запу�ке»; неактивен при выключенной проверке; че�тный тек�т о том, что проверка идёт и без предложений; «Обновить» в «О программе» работает при выключенных предложени�х; втора� �трока пункта «О программе» в �а�тройках от предложений не зави�ит. +- §25.3 — ли�т без «Что нового»: «Вышла вер�и� {v}» / «У ва� {v}»; «�е �ейча�» в ли�те только закрывает ли�т. +- §25.7 — ключ `offerUpdates`; `hiddenVersion` и `updatedPage` удал�ют�� при первом запу�ке; прежнее «�е �ейча�» в отказ не переводит��. +- §25.8, §12.3 — × озвучивает�� «�е предлагать обновлени�»; «Что нового» убрано. +- §9, §11, §14.9 — «�айт не ответил» вме�то «GitHub не ответил»; �троки `upd_offer`, `upd_offer_sub`, `upd_offer_needs_check`, `upd_offers_off_snack`, `upd_dismiss_cd`; удалены `upd_whats_new`, `upd_whats_new_cd`, `upd_notes_english`, `upd_hidden_snack`; `upd_auto_sub` дополнена. + +## 29. Ввод ходов, �вои базы, игра � Maia, тренировка (2026-10-26) + +Решение владельца `decisions.md` «Android: ввод ходов, �вои базы, Maia, тренировка» отмен�ет принцип «только про�мотр». Спецификаци� выне�ена в отдельный файл **`android-play.md`** (�тот документ �лишком длинный); его разделы продолжают нумерацию: §29 ввод ходов на до�ке, §30 �вои базы, §31 игра � Maia без ча�ов, §32 тренировка дебюта, §33 звуки, §34 до�тупно�ть, §35 тек�ты, §36 пор�док работ, §37 вопро�ы владельцу. + +Зде�ь замен�ют��: §0 п. 2 и §7.2 «Ка�ание до�ки» (под�казка при первом ка�ании удал�ет��), §12.1 �трока «до�ка», §15.2 п. 1–2 (�деланы), §15.3 «не делаем игры и тренировок» (отменено); §3.2 — �пи�ок баз делит�� на группы «Мои базы» и «Файлы» � р�дом дей�твий вверху (`android-play.md` §30.2). diff --git a/docs/design/board-search.md b/docs/design/board-search.md new file mode 100644 index 0000000..fbab71d --- /dev/null +++ b/docs/design/board-search.md @@ -0,0 +1,508 @@ +# Библиотека: пои�к партий по позиции на до�ке + +Стату�: проект дизайнера, 2026-10-19; **утверждён** владельцем (решение 13 в `../decisions.md`), перва� вер�и� реализована (`apps/desktop/src/board_search.rs`, `large_db.rs`, `library.rs`). О�нова — запро� владельца продукта (переключатель «Фильтры | До�ка» в шапке, до�ка на правой половине, таблица �лева ужимает��, ходы на до�ке �разу фильтруют таблицу, режимы �очетают�� в любом пор�дке) и позици� орке�тратора. Опирает�� на и��ледование `../research/position-search.md` (далее — «и��ледование») и на реализованную панель фильтров `large-databases.md` (далее — «LD»). По�ле утверждени� замен�ет LD §2.4 (мини-до�ка 240×240 в панели фильтров). + +Размеры — логиче�кие точки egui. Эталонный �кран владельца — 3840×2160 при ма�штабе 2 = **1920×1080 логиче�ки** (`target/mega-probe/shots/lib3.png`); ноутбук — 1280×800; минимум — 900×600. + +## 0. Главна� задача �крана + +**«Какие партии прошли через �ту позицию и что в ней играли» — за один взгл�д, без кнопки «И�кать».** + +Приоритет информации в режиме «До�ка»: + +1. До�ка � текущей позицией и чь� очередь хода — что именно ищем. +2. Сколько партий нашло�ь (�чётчик в шапке) и идёт ли пои�к. +3. Продолжени� �о �тати�тикой — куда можно пойти дальше, не уйд� в пу�тоту. +4. Таблица партий — �ильнейшие �верху, � ходом, где в�третила�ь позици�. +5. Строка у�ловий — что ещё ограничивает выборку (игрок, Эло…), чтобы цифры не обманывали. + +Принцип про�тоты: у пользовател� **одно дей�твие — делать ходы**. �и режимов �овпадени�, ни ма�ок, ни кнопки «�айти». В�ё о�тальное (переходы, фильтры, пор�док ходов) объ��н�ет�� контек�тно и только когда �то мен�ет картину. + +## 1. Сценарии + +Обозначени�: `[До�ка]` — �егмент переключател� в шапке; «продолжени�» — �пи�ок под до�кой. + +### 1.1. Изучить дебют (Mega, без фильтров) + +1. Выбрать Mega на полке → `[До�ка]` (или `Ctrl+B`). Справа до�ка в начальной позиции, под ней продолжени� первого хода: `1.e4 · 5 012 340 · 43 %`, `1.d4 …` — �читают�� в фоне, таблица пока показывает в�ю базу (у�лови� «позици�» ещё нет). +2. Сделать ход e2–e4 мышью (клик-клик или перета�кивание, как на �кране партии) **или** щёлкнуть �троку `1.e4` в продолжени�х **или** нажать `1` (номер �троки). +3. В �троке у�ловий по�вл�ет�� чип «Позици�: 1.e4 ×», �чётчик — «⟳ 18 %», таблица затемн�ет�� через 150 м�; продолжени� �разу очищают�� и заполн�ют�� по мере под�чёта (§4.3). +4. По завершении: «найдено 5 012 340 из 11 741 260», таблица от�ортирована «�ильнейшие �верху», продолжени� 1…c5 / 1…e5 / … � поло�ами Б/�/Ч. +5. Дальше c5, Nf3, d6 — каждый ход отмен�ет прошлый проход. `�` — шаг назад (хво�т линии о�таёт�� �ерым, `→` возвращает), `Backspace` — забрать по�ледний ход. +6. Двойной щелчок / `Enter` по партии → �кран партии **на ходе, где в�третила�ь позици�**. `Ctrl+W` → обратно: тот же режим, та же до�ка, та же выделенна� �трока. + +### 1.2. Репертуар игрока (�начала игрок, потом до�ка) + +1. `[Фильтры]` → «Игрок: carlsen», выбрать под�казку «Carlsen, Magnus», цвет «белыми». Чип «Игрок: Carlsen, Magnus · белыми ×». +2. `[До�ка]`. До�ка **не переворачивает�� �ама** (§4.9), продолжени� из начальной позиции — только по его парти�м белыми: «1.e4 · 1 210», «1.d4 · 980», «1.Nf3 · 640». +3. Щёлкать по продолжени�м — видно, что он играет в каждой позиции и � каким результатом. Таблица — его партии � �той позицией. +4. Обратный пор�док (�начала ходы, потом `[Фильтры]` → игрок) даёт ту же выборку: позици� — про�то ещё одно у�ловие, �очетание по И. + +### 1.3. Как играют �ильные + +1. В режиме «До�ка» � позицией 1.e4 c5 2.Nf3 d6 3.d4 cxd4 4.Nxd4 Nf6 5.Nc3 a6. +2. `[Фильтры]` → «Эло от 2600 дл� обоих», «Годы 2018 – 2026». Чипы добавл�ют��. +3. `[До�ка]` — продолжени� и таблица уже пере�читаны по отобранному: 6.Be3 / 6.Bg5 / 6.h3 � иными дол�ми, чем без фильтра. Колонка «Год» в продолжени�х показывает, жив ли ход. + +### 1.4. �айти позицию из партии + +1. �а �кране партии (14-й ход, хоть в варианте) — кнопка � «�айти позицию в базе» в нижней панели ин�трументов или `Ctrl+Shift+F`. +2. Открывает�� библиотека: выбранна� база-цель (§6.3), режим «До�ка», на до�ке позици� **� и�торией** — лини� под до�кой показывает путь от начала партии до текущего хода. Ориентаци� до�ки — как в партии. +3. Таблица — партии � �той позицией; е�ли они пришли другим пор�дком ходов — метка ⤳ и �трока про пор�док (§3). +4. В панели до�ки �лева вверху — «� К партии» (возврат к той же партии и ходу, пока она открыта). + +### 1.5. �айти разбор позиции в книге (мала� база) + +1. Книга «Ruy Lopez — Move by Move» (49 глав). В шапке р�дом � полем пои�ка — кнопка `[До�ка]`. +2. Вве�ти 1.e4 e5 2.Nf3 Nc6 3.Bb5 a6 4.Ba4 Nf6 5.O-O Be7. Таблица — главы, где �та позици� в�тречает�� **в о�новной линии или в вариантах**; в колонке «Ход» — «5… ⑂» дл� найденных в варианте. +3. Продолжени� — «что книга об�уждает зде�ь»: 6.Re1 · 31 глава, 6.d3 · 4, 6.Qe2 · 2 (без поло�ы результатов и Эло — в книге они бе��мы�ленны, §4.10). +4. `Enter` → глава открывает�� � кур�ором на �том узле, в том чи�ле внутри варианта. + +### 1.6. Вернуть�� к фильтрам и обратно + +1. В режиме «До�ка» � позицией и фильтром «Игрок» нажать `[Фильтры]` (или `Ctrl+F`, который �разу �тавит фоку� в «Игрок»). Права� ча�ть — панель фильтров (280), таблица шире, колонка «Ход» о�таёт��, чип «Позици�: …» о�таёт�� — позици� продолжает дей�твовать. +2. Помен�ть фильтр — таблица пере�читывает�� � учётом позиции. +3. `[До�ка]` / `Ctrl+B` / щелчок по чипу «Позици�» — обратно; до�ка, лини� и положение в линии те же. +4. Щелчок по чипу «Игрок: …» в режиме «До�ка» — переключает на `[Фильтры]` � фоку�ом в поле «Игрок». + +### 1.7. Сбро�ить позицию + +- «Сбро�ить» в шапке панели до�ки, `Ctrl+Backspace` или `×` на чипе «Позици�» → начальна� позици�, у�ловие «позици�» �н�то, таблица — �нова только по фильтрам. +- Без подтверждени�. Вме�то него на ме�те линии 8 �екунд показывает�� «Позици� �брошена · [Вернуть]» — во��танавливает линию и позицию (результат берёт�� из к�ша, без прохода). +- `Ctrl+Shift+Backspace` (как в LD) — �бро�ить **в�е** у�лови�, включа� позицию; тоже � «Вернуть». + +### 1.8. Позици� не в�тречает�� + +1. Ввёл 1.e4 c5 2.Nf3 d6 3.d4 cxd4 4.Qxd4 Nc6 5.Qa4?! — при фильтре «Эло ≥ 2600» 0 партий. +2. Таблица: «Позици� не в�третила�ь в 3 412 парти�х по у�лови�м» + чипы у�ловий + `[И�кать во в�ей базе]` (�нимает фильтры, позици� о�таёт��) и `[� До по�ледней позиции � парти�ми (4…Nc6)]`. +3. В линии под до�кой по�ле 4…Nc6 — тонка� вертикальна� черта � под�казкой «дальше партий нет»: видно, где лини� ушла из базы. + +## 2. Компоновка + +### 2.1. Обща� �хема и переключатель + +Шапка над таблицей (28) — как в LD: им� базы · «ChessBase, только чтение» · �чётчик · индикатор · `⚠ N` · �права **�егментный переключатель** `[Фильтры | До�ка]` вме�то кнопки «Фильтры ⟩». + +- Две `selectable_label` в одной рамке, вы�ота 22, ширина по тек�ту (~70 + ~60). +- Щелчок по неактивному �егменту — переключить правую ча�ть. Щелчок по активному — �вернуть правую ча�ть (оба �егмента без выделени�; таблица на в�ю ширину). Tooltip активного �егмента: «Скрыть панель». Это замен�ет кнопку «Фильтры ⟩» из LD, третьего �лемента не нужно. +- �а �егменте «Фильтры» — чи�ло активных фильтров, е�ли права� ча�ть не показывает фильтры: «Фильтры (2)». �а �егменте «До�ка» — точка «•», е�ли позици� задана, а показаны фильтры. +- Права� ча�ть — `SidePanel::right`, `resizable(true)`. Ширины запоминают�� **отдельно**: фильтры 280 (260–380, как �ейча�), до�ка — **дол� окна, по умолчанию 0,5**, диапазон: от 340 до (ширина окна − 420). Разделитель — штатный край `SidePanel`. **Обновление 2026-10-24:** верхн�� граница — `ширина − TABLE_MIN` (≈ 540), а при ширине < ≈ 880 до�ка показывает�� вме�то таблицы, по очереди — `narrow-windows.md` §2.3. + +### 2.2. Строка у�ловий (чипы) + +Сразу под шапкой, вы�ота **26** (чип 22 + от�тупы). + +``` +│ Позици�: 1.e4 c5 2.Nf3 d6 × · Игрок: Carlsen, Magnus · белыми × · Эло ≥ 2600 × [�бро�ить в�е] │ +│ �тим пор�дком ходов 312 из 3 412 · [только �тот пор�док] │ � �права, �лабым, только е�ли е�ть переходы +``` + +- **Больша� база — �трока е�ть в�егда**, даже без у�ловий (тогда �лабым тек�том «У�ловий нет — показаны в�е партии»). Ме�то зарезервировано, по�тому первый ход или первый фильтр не �двигает таблицу вниз. +- ~~**Мала� база — �трока е�ть только при открытой до�ке**~~ — � 2026-10-23 у в�ех баз один �кран (LD §9), �трока у�ловий е�ть в�егда. +- Пор�док чипов **фик�ированный**, а не по времени добавлени� (чипы не прыгают): Позици� → Пои�к → Игрок → Соперник → Турнир → Комментатор → Годы → Эло → Результат → ECO → Ходов → �ннотации (� 2026-10-23 «Пои�к» — у в�ех баз, �разу по�ле позиции, LD §9.2). +- Чип: `Frame` �о �круглением 4, фон — �лаба� заливка, тек�т 13, `×` — маленька� кнопка 16×16 �права внутри. Щелчок по `×` — �н�ть у�ловие �разу. Щелчок по тек�ту чипа — перейти к у�ловию: «Позици�» → `[До�ка]`; о�тальные → `[Фильтры]` � фоку�ом в �оответ�твующем поле. +- Тек�т чипа «Позици�»: до 8 полуходов — �ама лини� («Позици�: 1.e4 c5 2.Nf3 d6»); длиннее — «Позици� по�ле 14…Nf6». Tooltip — в�� лини� и **мини-до�ка 160×160** (неинтерактивна� отри�овка `board.rs`), чтобы у�ловие было видно в режиме «Фильтры». +- Е�ли включено «только �тот пор�док» — «Ходы: 1.e4 c5 2.Nf3 d6 (точно �тот пор�док) ×». +- �е помещает�� в ширину — по�ледний видимый чип замен�ет�� на «+3 ещё» (tooltip �о �пи�ком; щелчок → `[Фильтры]`). Перено� на вторую �троку не делаю: �трока фик�ированной вы�оты. +- «�бро�ить в�е» — ��ылка �права, только при ≥ 2 у�лови�х. +- Справа в той же �троке — **�ообщение о пор�дке ходов** (§3), �лабым тек�том. Е�ли ме�та нет, оно уходит в tooltip �чётчика, а не на отдельную �троку. + +### 2.3. Режим «До�ка», 1920×1080 (логиче�ки). Широкий вариант: продолжени� �права от до�ки + +Права� ча�ть 960. Под �одержимое: 1080 − полка 112 − шапка 28 − чипы 26 = **914**. + +``` +┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────� +│ Базы [♟ �ова� парти�][📋 В�тавить PGN][⚙] │ +│ [🗄 Ruy Lopez – Move by Move · 49] [🗄 Mega Database 2026 · 11,7 млн 🔒] [+ Добавить базу] │ полка 112 +├────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ Mega Database 2026 · ChessBase, только чтение · найдено 3 412 из 11 741 260 [⚠ 1] [ Фильтры (2) │�До�ка▌] │ шапка 28 +│ Позици�: 1.e4 c5 2.Nf3 d6 × · Игрок: Carlsen, Magnus · белыми × · Эло ≥ 2600 × �тим пор�дком 3 100 из 3 412 · [только �тот] │ чипы 26 +├──────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────────┤ +│ Ход Белые Elo Чёрные Elo Рез. Год Турнир│ � К партии ○ Ход белых · по�ле 2…d6 [⇅][Сбро�ить][⋯] │ 28 +│ 3. Carlsen, M. 2864 Caruana, F. 2835 1-0 2023 Norway│ ┌──────────────────────────────────────� Продолжени� │ +│ 3. Carlsen, M. 2859 Nepomniacht.. 2795 ½-½ 2022 Tata │ │ │ 3 412 партий │ +│⤳4. Carlsen, M. 2847 So, W. 2780 1-0 2021 Champ │ │ │1 3.d4 2 880 84%│ +│ 3. … │ │ до�ка 576×576 │ ████▒▒▒░░░ 2768 2026│ +│ (виртуализированна� таблица; �ортировка «�ильнейшие │ │ │2 3.Bb5+ 401 12%│ +│ �верху» — � �лабо на обоих Elo) │ │ │ ███▒▒▒▒░░░ 2790 2026│ +│ │ │ │3 3.c3 98 3%│ +│ │ │ │ ... │ +│ │ └──────────────────────────────────────┘ │ +│ │ ◀ ▶ 1.e4 c5 2.Nf3 d6 │3.d4 cxd4 4.Nxd4 │ Закончили�ь│ +│ │ (текущий — выделен; хво�т по�ле � — �ерый)│ зде�ь: 33 │ +└──────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────────┘ +``` + +Широкий вариант включает��, когда ширина правой ча�ти **≥ 820**: + +- шапка панели до�ки — 28; +- до�ка — `min(вы�ота − 28 − 64 − 16, ширина − 360 − 24)`, ограничено 280…640. При 960 × 914: **576**; +- �права от до�ки — продолжени� шириной **360** во в�ю вы�оту (~38 �трок по 22); +- под до�кой — лини� ходов, шириной до�ки, до 3 �трок (вы�ота 64 включает кнопки ◀ ▶). + +Почему продолжени� �права, а не под до�кой: на 1920 под до�кой 640 о�тавало�ь бы ме�то лишь на 6 �трок, а 360 точек по ширине пропадали бы. Р�дом � до�кой видны в�е продолжени�. И �то та же �хема, что на �кране партии: до�ка �лева, тек�т �права. + +### 2.4. Режим «До�ка», 1280×800. Узкий вариант: продолжени� под до�кой + +Права� ча�ть 640 (0,5), под �одержимое 800 − 112 − 28 − 26 = **634**. + +``` +┌──────────────────────────────────────────────────────────────────────────────────────────� +│ Mega Database 2026 · только чтение · найдено 3 412 из 11 741 260 ⟳ 43 % [Фильтры(2)│До�ка] │ +│ Позици�: 1.e4 c5 2.Nf3 d6 × · Игрок: Carlsen… × · Эло ≥ 2600 × +1 ещё │ +├───────────────────────────────────────────┬──────────────────────────────────────────────┤ +│ Ход Белые Elo Чёрные Elo Рез. Год│ ○ Ход белых · по�ле 2…d6 [⇅][Сбро�ить][⋯] │ +│ 3. Carlsen, M. 2864 Caruana, F. 2835 1-0 2023│ ┌──────────────────────� │ +│ 3. Carlsen, M. 2859 Nepomniac.. 2795 ½-½ 2022│ │ │ │ +│⤳4. Carlsen, M. 2847 So, W. 2780 1-0 2021│ │ до�ка 370×370 │ │ +│ … │ │ │ │ +│ │ └──────────────────────┘ │ +│ │ ◀ ▶ 1.e4 c5 2.Nf3 d6 │3.d4 │ +│ │ Продолжени� · 3 412 партий │ +│ │ 1 3.d4 2 880 84% ████▒▒▒░░ 2768 2026 │ +│ │ 2 3.Bb5+ 401 12% ███▒▒▒▒░░ 2790 2026 │ +│ │ 3 3.c3 98 3% ██▒▒▒░░░░ 2741 2025 │ +│ │ Закончили�ь зде�ь: 33 │ +└────────────────────────────────────────────┴──────────────────────────────────────────────┘ +``` + +Узкий вариант (ширина правой ча�ти < 820): + +- до�ка — `min(ширина − 16, вы�ота − 28 − 64 − 156 − 16)`, ограничено 240…640, по центру по горизонтали. 1280×800: **370**; +- продолжени� — под линией, на в�ю ширину панели, �во� прокрутка; минимум под них — 6 �трок (156); +- таблица 640: колонки «Ход 44 · Белые 150 · Elo 44 · Чёрные 150 · Elo 44 · Рез. 44 · Год 44» = 520, о�таток — «Турнир» (показывает�� при ≥ 100, иначе пр�чет��). + +### 2.5. Минимум 900×600 + +Под �одержимое 600 − 112 − 28 − 26 = 434 — дл� до�ки � продолжени�ми мало. **Рекомендаци�:** в режиме «До�ка» при вы�оте окна < 760 полка �ворачивает�� в одну �троку 28 (выпадающий выбор базы «🗄 Mega Database 2026 ▾» + «+ Добавить базу»; полка разворачивает�� �ама, когда выходишь из режима «До�ка» или окно �тановит�� выше). Тогда под �одержимое **518**. + +``` +┌────────────────────────────────────────────────────────────────────────────────� +│ 🗄 Mega Database 2026 ▾ [+] [♟][📋][⚙] │ 28 (�вёрнута� полка) +│ Mega Database 2026 · найдено 3 412 из 11 741 260 ⟳ [Фильтры(2)│До�ка] │ 28 +│ Позици�: 1.e4 c5 2.Nf3 d6 × · Игрок: Carlsen… × +1 ещё │ 26 +├────────────────────────────────────┬───────────────────────────────────────────┤ +│ Ход Белые Чёрные Рез. Год│ ○ Ход белых · по�ле 2…d6 [⇅][↺][⋯] │ +│ 3. Carlsen 2864 Caruana 2835 1-0 2023│ ┌──────────────────� │ +│ 3. Carlsen 2859 Nepomn… 2795 ½-½ 2022│ │ до�ка 300×300 │ │ +│⤳4. Carlsen 2847 So 2780 1-0 2021│ └──────────────────┘ │ +│ … │ ◀ ▶ 1.e4 c5 2.Nf3 d6 │ +│ │ 1 3.d4 2 880 ████▒▒░░ 2768 │ +│ │ 2 3.Bb5+ 401 ███▒▒▒░░ 2790 │ +│ │ 3 3.c3 98 ██▒▒▒░░░ 2741 (прокрутка) │ +└────────────────────────────────────┴───────────────────────────────────────────┘ +``` + +- Таблица ≥ **420**, права� ча�ть ≤ 900 − 420 − от�туп = **460**. +- До�ка: `min(444, 518 − 28 − 48 − 110 − 12)` ≈ **300**. �ижн�� граница 240. +- Продолжени� — 4 �троки � прокруткой; колонки «Год» и «дол� %» �крыты. +- Таблица: **Ход · Белые · Чёрные · Рез. · Год**. Эло �крытых колонок допи�ывает�� �лабым тек�том в �чейку имени («Carlsen 2864»): �ортировка «�ильнейшие �верху» без видимого Эло выгл�дела бы �лучайной. +- «Сбро�ить» в шапке панели �тановит�� иконкой ↺ � tooltip. +- Без �ворачивани� полки (е�ли владелец против): до�ка 240, продолжени� — 3 �троки. Работает, но те�но; проверить на реальном окне по�ле реализации. +- HiDPI: в�ё в логиче�ких точках; 1920×1080 при ма�штабе 2 = 960×540 — ниже минимума. Шапка, чипы и до�ка 240 должны о�тать�� видимыми, продолжени� и таблица прокручивают��. + +### 2.6. Режим «Фильтры» � активной позицией + +Как в LD §2.1, � трем� отличи�ми: + +1. Под шапкой �трока чипов, в ней «Позици�: … ×» (tooltip � мини-до�кой). +2. В таблице е�ть колонка «Ход» (перва�, 44) и �ортировка «�ильнейшие �верху», пока задана позици� (§4.8). +3. Подвал панели «Сбро�ить фильтры (N)» �бра�ывает **только фильтры панели**, позици� о�таёт�� (она видна в чипе, у неё �вой `×`). Это нужно дл� �ценари� «позици� та же, помен�ю игрока». + +### 2.7. Колонки таблицы: что о�таёт�� при ужатии + +Пор�док �крыти� при нехватке ширины (первым уходит верхний): + +| Приоритет �крыти� | Колонка | Комментарий | +| --- | --- | --- | +| 1 | Тур (Round) | | +| 2 | № | в режиме «До�ка» номер запи�и почти не нужен | +| 3 | ✎ | | +| 4 | Длина (бывш. «Ходы») | �м. ниже | +| 5 | ECO | при заданной позиции почти у в�ех одинаковый | +| 6 | Турнир | в tooltip �троки | +| 7 | Дата → Год | «14.12.1902» (76) превращает�� в «1902» (40) | +| 8 | Elo ×2 | переезжают в �чейку имени �лабым тек�том | +| никогда | **Ход**, Белые, Чёрные, Рез., Год | | + +- �ова� колонка **«Ход»** (44, �лева): номер хода, по�ле которого возникла позици�, в запи�и � очерёдно�тью: «9.» — по�ле хода белых, «9…» — по�ле хода чёрных. Дл� партий, пришедших другим пор�дком, перед чи�лом �тоит «⤳» (§3), дл� найденных в варианте (мала� база) — «⑂» по�ле чи�ла. Колонка е�ть только при заданной позиции. +- Чтобы не путать � новой колонкой, �уще�твующую «Ходы» (длина партии) переименовать в **«Длина»** (EN «Length»), tooltip «Ходов в партии». Это решение дизайнера, не вопро� владельцу. +- Tooltip �троки при �крытых колонках — как в LD: «Турнир · раунд · длина · комментатор», плю� дл� ⤳ — пор�док ходов �той партии до позиции. + +## 3. «Ходы» или «позици�» + +### 3.1. Решение + +**В�егда ищем позицию (� переходами).** Отдельного переключател� «по ходам / по позиции» нет. Пор�док ходов показывает�� только там, где он что-то мен�ет. + +Почему так: + +1. Пользователь, ввод� ходы, �прашивает «что зде�ь играют», а не «кто �ыграл ровно �ту по�ледовательно�ть». Парти� 1.c4 e6 2.d4 Nf6 3.Nc3 d5 — такой же ферзевый гамбит, как 1.d4 d5 2.c4 e6 3.Nc3 Nf6. Скрывать её — тер�ть теорию. +2. Так работают в�е ра��мотренные программы (и��ледование §2, вывод 2). �и одна не держит режим «только пор�док» на главном �кране. +3. Переключатель режима перед вводом за�тавл�ет решать то, о чём пользователь ещё не думал. � контек�тна� под�казка по�вл�ет��, когда �то �тало важно, и уже � чи�лами. +4. Ввод из партии (§1.4) ча�то идёт редким пор�дком (1.Nf3 d5 2.d4…). При пои�ке по ходам така� парти� почти в�егда давала бы «0 партий» при богатой теории. + +### 3.2. Как показываю пор�док ходов (уточнение позиции орке�тратора) + +Согла�ен � идеей «⤳ + �трока только при наличии переходов». Мен�ю формулировку и ме�то: + +- **�ейтральна� формулировка**, без �лова «переход»: «**�тим пор�дком ходов — 312 из 3 412** · [только �тот пор�док]». Формулировка орке�тратора «1 240 — другим пор�дком ходов» делает пор�док пользовател� нормой. � при вводе из партии он обычно редкий, и фраза «3 100 из 3 412 — другим пор�дком» выгл�дит как ошибка. +- **Ме�то — правый край �троки чипов** (�лабый тек�т 12), а не отдельна� �трока над таблицей. Отдельна� �трока, котора� то по�вл�ет��, то и�чезает, �двигает таблицу на каждом ходу. +- Показывает��, только е�ли позици� задана и хот� бы одна парти� пришла иначе. В начальной позиции и при 0 партий — нет. +- Метка в таблице — «⤳» в колонке «Ход». Tooltip: «К позиции пришли другим пор�дком: 1.c4 e6 2.Nc3 d5 3.d4 Nf6». Сравнивать по полному �овпадению первых N полуходов � линией пользовател� (данные уже е�ть в проходе). +- «[только �тот пор�док]» — ��ылка-переключатель. Включённый режим виден в чипе: «Ходы: 1.e4 c5 2.Nf3 d6 (точно �тот пор�док) ×». С�ылка �тановит�� «[в�е пор�дки]». Продолжени� �читают�� по той же выборке. Смена хода режим не �бра�ывает, �бро� позиции — �бра�ывает. +- Е�ли позици� получена из FEN-партии (лини� начинает�� � ⌂), «�тот пор�док» — от той же �тартовой позиции. + +### 3.3. Как объ��нить без терминов + +- Tooltip ��ылки: «Показать только партии, где ходы шли в точно�ти как у ва� на до�ке. Сейча� показаны в�е партии, пришедшие к �той позиции любым путём». +- Tooltip �чётчика: «Партий, где на до�ке была �та позици� (� �той очередью хода), любым пор�дком ходов». +- В �правке/под�казке первого запу�ка не нужно ничего: по умолчанию пои�к даёт «больше правильных партий». + +## 4. Компоненты и �о�то�ни� + +### 4.1. Шапка панели до�ки (28) + +Слева направо: + +- «� К партии» — только е�ли пришли из партии и она ещё открыта. +- Индикатор очереди хода: круг 10 (белый � тёмной обводкой или чёрный �о �ветлой) + тек�т «Ход белых · по�ле 2…d6». В начальной позиции — «�ачальна� позици�». +- Справа кнопки: `⇅` (перевернуть, `F`); «Сбро�ить» (`Ctrl+Backspace`, неактивна в начальной позиции); `⋯` — меню. + +Меню `⋯`: + +- «Открыть как новую партию» — нова� парти� � введёнными ходами (или FEN + ходы). Мо�т к анализу и вводу. +- «Копировать FEN». +- «Копировать ходы (PGN)». + +### 4.2. До�ка + +- Тот же виджет `board.rs`: клик-клик, перета�кивание, превращение, рокировка кликом на корол�/ладью, под�ветка по�леднего хода, координаты, тема и фигуры из на�троек, звук хода по на�тройкам. +- Принимают�� только легальные ходы. Пу�той ход `--` вве�ти нельз�. +- Ход в �ередине линии (по�ле `�`) **обрезает хво�т** и продолжает новую линию. Дерева вариантов на до�ке пои�ка в первой вер�ии нет. Потер� хво�та допу�тима: �то не парти�, а запро�. +- До�ка пои�ка не �в�зана ни � какой партией и ничего в парти�х не мен�ет. +- Предпро�мотр: + - **наведение на продолжение** — �трелка �того хода. Цвет — �иний полупрозрачный: отличает�� от зелёных �трелок движка и не похож на �деланный ход; + - **наведение на �троку таблицы** — та же �трелка хода, �ыгранного в �той партии из найденной позиции (берёт�� из того же прохода). �ет хода (парти� закончила�ь) — без �трелки; + - �трелка и�чезает �разу, как уходит кур�ор. Позици� не мен�ет��, отмен�ть нечего. + +### 4.3. Идёт пои�к + +Проблема: нельз� показывать под новой позицией продолжени� �тарой. Это то же правило, что «не показывать анализ �тарой позиции как новой». Щелчок по �тарому продолжению �делал бы чужой, возможно нелегальный ход. По�тому таблица и продолжени� ведут �еб� по-разному. + +**Таблица** — как в LD §3.6: �тара� выборка, через 150 м� затемнение 0,6, �пиннер и процент в шапке. Строки — реальные партии, их можно открыть (откроют�� на ходе той позиции, дл� которой найдены). Ча�тичные результаты в таблицу не идут, чтобы не дёргали�ь �троки, выделение и �ортировка. + +**Продолжени�** — очищают�� в момент хода, затем показывают **ча�тичный под�чёт новой позиции**: + +- первые 300 м� — пу�то, по центру «Считаю…» �лабым тек�том (короткие пои�ки не мигают); +- дальше �троки � текущими чи�лами, �лабым цветом, обновление не чаще 4 раз в �екунду, над �пи�ком «Под�чёт… 43 %»; +- **пока кур�ор над �пи�ком, обновление �трок замораживает��** (иначе �трока уедет из-под мыши), процент идёт; +- щелчок по ча�тичной �троке разрешён: ходы вз�ты из новой позиции и легальны; +- по завершении — обычный цвет, окончательный пор�док. + +**До�ка и лини�** — в�егда интерактивны. �овый ход отмен�ет текущий проход (поколени�, как в LD). + +Возврат `�` к уже по�читанной позиции берёт�� из к�ша �е��ии: мгновенно, без затемнени�. + +### 4.4. �ачальна� позици� + +- У�лови� «позици�» **нет**: чипа нет, колонки «Ход» нет, таблица — по фильтрам (в�� база, е�ли фильтров нет). Ровно как до открыти� до�ки, по�тому открытие до�ки ничего не пере�читывает в таблице. +- Продолжени� — �тати�тика первого хода по текущей выборке. �а Mega без фильтров �то полный проход по первым ходам: в фоне, � «Под�чёт… %», к�ширует�� на �е��ию. Таблица при �том не затемн�ет�� — она не мен�ет��. +- Партии из FEN и тек�ты в �тати�тику первого хода не вход�т. Внизу �пи�ка: «�е из начальной позиции: 6 879» (�лабым). +- Под�казка в пу�том �пи�ке на врем� первого под�чёта: «Делайте ходы на до�ке — таблица покажет партии � �той позицией». + +### 4.5. �оль партий + +- До�ка работает дальше: позици� может в�третить�� через переход позже. +- Таблица — по центру: «Позици� не в�третила�ь в 3 412 парти�х по у�лови�м» (без фильтров — «…в базе»), ниже чипы у�ловий � `×`, кнопки `[И�кать во в�ей базе]` (только при фильтрах; �нимает фильтры, позици� о�таёт��) и `[� До по�ледней позиции � парти�ми (4…Nc6)]`. +- Второго пои�ка «без фильтров» автоматиче�ки не делаю: �то удвоение работы на 11,7 млн (как в и��ледовании §4.2). +- Продолжени�: «�ет продолжений в �той выборке». +- **Метка выхода из базы** в линии — вертикальна� черта 1 px перед первым ходом, по�ле которого партий 0. Tooltip: «Дальше партий нет». Чи�ло партий дл� каждой пройденной позиции уже е�ть в к�ше, так что почти бе�платно. �а �кране партии �то зародыш пои�ка новинок (§6). + +### 4.6. Позиции из FEN, пу�той ход, Chess960, тек�ты, ошибки + +- **Парти� базы � заданной �тартовой позицией (FEN)** ищет�� от �воей �тартовой позиции, как обычна�. +- **Позици� из FEN-партии на до�ке пои�ка** («�айти позицию» из партии � `[FEN]`): лини� начинает�� значком «⌂» (tooltip «Стартова� позици� партии» + FEN). Сбро� возвращает к обычной начальной позиции, а не к FEN партии; «Вернуть» — к ней. +- **Пу�той ход `--` в пути до текущего хода партии.** Кнопка «�айти позицию в базе» неактивна, tooltip: «По�ле пу�того хода (--) �то учебна� �хема, а не позици� партии — в базе не ищет��». Партии базы по�ле `--` в пои�ке не уча�твуют (и��ледование §4.3, инвариант AGENTS.md). +- **Chess960.** «�айти позицию» в такой партии неактивна, tooltip «Позиции Chess960 не ищут��». Партии Chess960 базы в пои�к не вход�т; в tooltip �чётчика: «�е уча�твуют в пои�ке: Chess960 — 4 481». +- **Тек�ты** при заданной позиции в выборку не вход�т (у них нет ходов) — то же правило, что дл� игрока/Эло в LD §3.5. +- **Партии, которые не удало�ь разобрать** — пропу�кают��. В tooltip �чётчика: «�е прочитаны: 12», в «Замечани�х импорта» — одна �водна� �трока. + +### 4.7. Лини� ходов под до�кой + +- Поток токенов «1.e4 c5 2.Nf3 d6» — как о�новна� лини� в нотации, шрифт 14. Каждый ход — отдельный hit-rect, щелчок переходит к нему. +- Текущий ход — заливка цветом выделени� (как в нотации). Ходы по�ле текущего (по�ле `�`) — �ерым. +- Слева кнопки ◀ ▶ (24×24). +- **Очень длинна� лини�** (из партии, 40+ ходов): вы�ота до 3 �трок, дальше вертикальна� прокрутка; текущий ход в�егда прокручен в видимую обла�ть (`scroll_to_rect`). Без многоточий: каждый ход до�тупен. +- Лини� из партии — путь от начала до текущего узла, включа� ходы вариантов (как они ведут к позиции). Скобок нет: на до�ке пои�ка лини� в�егда одна. +- Пу�та� лини� (начальна� позици�) — под�казка �лабым тек�том «Ходы на до�ке — зде�ь». + +### 4.8. Сортировка в режиме до�ки — «�ильнейшие �верху» + +- Как только задана позици� и пользователь **ещё не выбирал �ортировку �ам** в �той базе, таблица �ортирует�� по **�реднему Эло партии по убыванию**. При равен�тве — по дате, новые выше. Без Эло — в конце. Так «топ-партии» Lichess/SCID получают�� без отдельного окна. +- Видимо�ть: на обоих заголовках Elo — �лаба� �. Tooltip: «Сильнейшие партии �верху (�реднее Эло). Щёлкните другой заголовок, чтобы �ортировать иначе». +- Выбрал �ортировку �ам — она �охран�ет�� и при �мене позиции. Позицию �н�ли, а �ортировка была автоматиче�кой — возвращает�� прежн�� (по умолчанию «№»). +- Почему не «как �ейча� (№)»: в Mega пор�док «№» — �то пор�док ввода в базу, �верху партии 1902 года. Дл� позиции бе�полезно. + +### 4.9. Перевёрнута� до�ка + +- `F` / `⇅`. Ориентаци� хранит�� на �е��ию, обща� дл� в�ех баз. +- При «�айти позицию в базе» — ориентаци� как в партии. +- �втоматиче�кого переворота «при фильтре чёрными» в первой вер�ии нет (�крыта� �мена — повод дл� вопро�а «почему до�ка перевернула�ь?»). Иде� на потом — §7.2. +- Поло�ы Б/�/Ч и тек�ты от ориентации **не** зави��т: в�егда «белые �лева». + +### 4.10. Продолжени� + +Строка (вы�ота 22): + +``` +1 3.d4 2 880 84 % [████████▒▒▒▒▒▒░░░░░] 2768 2026 +^ ^ ^ ^ ^ поло�а Б/�/Ч, ≥120 ^ �р. ^ по�ледний +№ ход партий дол� Эло год +14 64 64 40 44 40 +``` + +- № �троки (�лабый, 1–9) — под�казка гор�чей клавиши. +- Ход — SAN � номером хода («3.d4», «3…Nc6»). +- Партий — � разделителем ты��ч. Дол� — от чи�ла партий позиции. +- **Поло�а Б/�/Ч — не только цвет**: + - три �егмента по �ветлоте: белые выиграли — �ветлый (`#E8E8E8`), ничьи — �ерый (`#8C8C8C`), чёрные выиграли — тёмный (`#2B2B2B` � обводкой 1 px �ветлее фона, чтобы не �ливал�� � тёмной темой); + - внутри �егмента шириной ≥ 26 — процент контра�тным цветом («38 · 34 · 28»); + - tooltip: «Белые выиграли 1 094 (38 %) · ничьих 979 (34 %) · чёрные выиграли 807 (28 %)». + - Цвета не кра�ные/зелёные. Шкала аб�олютна� (белые �лева), без «очков �тороны на ходу»: нет термина, который нужно объ��н�ть. +- Мало партий (< 10) — в�� �трока �лабее, tooltip «Мало партий — �тати�тика ненадёжна». +- Ср. Эло — �реднее по парти�м, где Эло изве�тно у обоих игроков; нет — «—». Tooltip заголовка: «Средний рейтинг игроков в парти�х � �тим ходом». +- Год — по�ледний раз �ыгран. Tooltip: «Когда ход играли по�ледний раз». +- Сортировка — по чи�лу партий. Пере�ортировка по заголовкам не нужна в первой вер�ии. +- Внизу — «Закончили�ь зде�ь: 33» (�лабым): �умма продолжений + закончившие�� = �чётчику (и��ледование §4.1, критерий 4). +- �аведение — �ин�� �трелка на до�ке, под�ветка �троки. Щелчок или цифра — �делать ход. +- При нехватке ширины �крывают�� по очереди: Год → Дол� → Ср. Эло. Поло�а не уже 80. +- **Мала� база (книга):** �трока — «№ · ход · N глав», без поло�ы, Эло и года. Результаты партий книги к теории не отно��т��, а �редний Эло авторов глав бе��мы�лен. Заголовок: «Продолжени� в книге». Ходы �читают�� по о�новным лини�м и вариантам; у хода, в�треченного только в вариантах, — «⑂». + +### 4.11. Мала� база (книга) + +> **Заменено 2026-10-23 разделом 9 `large-databases.md`:** PGN и переведённые базы получают тот же �кран, что ChessBase (`[Фильтры | До�ка]`, панель, �трока у�ловий в�егда). Отдельной кнопки `[До�ка]` у малых баз больше нет. Пои�к в вариантах (⑂/🔀), открытие на найденном узле и «N глав» в продолжени�х книг о�тают�� (LD §9.9). �иже — и�ходный тек�т дл� и�тории. + +- Справа в шапке, по�ле пол� пои�ка, — кнопка-переключатель `[До�ка]` (дл� малых баз панели фильтров нет, �егмента «Фильтры» тоже). +- Поле пои�ка и позици� �очетают�� по И. Тек�т пои�ка при открытой до�ке дублирует�� чипом «Пои�к: carlsen ×». +- Пои�к **и в вариантах**. Парти� �читает�� один раз; е�ли позици� е�ть и в о�новной линии, и в варианте — берёт�� о�новна� лини�, иначе первое вхождение в пор�дке тек�та. «⑂» в колонке «Ход». +- Открытие партии �тавит кур�ор на найденный узел, в том чи�ле внутри варианта (�уще�твующий механизм кур�ора по пути). +- Пои�к на ты��чах партий — мгновенный (разбор один раз за �е��ию, и��ледование §6). Затемнени� и процента почти никогда не будет; механизм тот же. + +### 4.12. Возврат из партии и �охранение �о�то�ни� + +- Открыли партию из режима «До�ка» → `Ctrl+W` → тот же режим, та же лини� и ход в ней, та же выборка и выделение (LD §4.8, §7). +- До�ка, лини�, ориентаци�, «только �тот пор�док» хран�т�� **на базу в пределах �е��ии**, как фильтры. Между запу�ками не �охран�ют��, кроме ширины панели до�ки и по�леднего выбранного режима правой ча�ти. + +## 5. Клавиатура, фоку�, tooltip-ы + +### 5.1. Правило фоку�а + +Про�тое правило без невидимых «зон»: **вертикаль — таблице, горизонталь — до�ке.** Таблица не и�пользует �/→, а до�ка не и�пользует ↑/↓, по�тому конфликтов нет и не надо помнить, где фоку�. + +В�е клавиши без модификаторов работают, только е�ли фоку� **не** в тек�товом поле. В поле �/→/Backspace/цифры/F — редактирование тек�та. `Esc` из пол� — как в LD: закрыть под�казки → очи�тить поле → выйти из пол�. + +Техниче�ки: щелчок по до�ке, линии или продолжени�м должен �нимать фоку� � тек�тового пол� (`surrender_focus` у пол� / `request_focus` на id панели до�ки). Иначе по�ле пои�ка в малой базе �трелки уйдут в поле. + +### 5.2. Таблица клавиш (режим «До�ка») + +| Клавиша | Дей�твие | +| --- | --- | +| `�` / `→` | назад / вперёд по линии (хво�т �охран�ет��) | +| `Home` / `End` | начало / конец линии (как на �кране партии; таблица Home/End �ейча� не и�пользует) | +| `Backspace` | забрать по�ледний ход (укоротить линию до текущего хода − 1) | +| `1`…`9` | �ыграть продолжение � �тим номером | +| `F` | перевернуть до�ку | +| `Ctrl+Backspace` | �бро�ить позицию (� «Вернуть») | +| `Ctrl+Shift+Backspace` | �бро�ить в�е у�лови� (как в LD) | +| `↑` / `↓`, `PgUp` / `PgDn` | �трока таблицы (как �ейча�) | +| `Ctrl+Home` / `Ctrl+End` | перва� / по�ледн�� �трока таблицы | +| `Enter` | открыть выделенную партию на найденном ходе; без выделени� — ничего | +| `Ctrl+F` | переключить�� на «Фильтры», фоку� в «Игрок» (как в LD) | +| `Ctrl+B` | переключить�� на «До�ка» (из любого режима библиотеки) | +| `Esc` | закрыть меню `⋯` / под�казки; позицию **не** �бра�ывает | +| `Ctrl+Z` | только внутри 8 � по�ле �бро�а = «Вернуть» (иначе ничего в библиотеке) | + +�а �кране партии: `Ctrl+Shift+F` — «�айти позицию в базе». + +`→` в конце линии **ничего не делает**, а не играет �амое ча�тое продолжение. Иначе зажатый `→`, чтобы дойти до конца, пролетал бы дальше по «главной линии базы». Дл� бы�трого хода е�ть `1`. + +### 5.3. Видимый фоку� и выделение + +- Выделенна� �трока таблицы — как в LD, � поло�ой `▌` �лева. +- Текущий ход линии — заливка выделени�. Строка продолжени� под кур�ором — под�ветка наведени�; «выбранного» продолжени� нет. Со�то�ний в�его два: позици� на до�ке и �трока таблицы. + +### 5.4. Tooltip-ы + +- Сегмент «До�ка»: «�айти партии по позиции: делайте ходы на до�ке (Ctrl+B)». +- `⇅`: «Перевернуть до�ку (F)». +- «Сбро�ить»: «�ачальна� позици� (Ctrl+Backspace)». +- «� К партии»: «Вернуть�� к партии Anderssen — Kieseritzky, ход 14». +- ◀ ▶: «Ход назад (�)» / «Ход вперёд (→)». +- «Ход» (заголовок колонки): «Ход, по�ле которого в партии возникла позици�. ⤳ — пришли другим пор�дком ходов, ⑂ — в варианте». +- Поло�а, Эло, Год, «только �тот пор�док», �чётчик — тек�ты в §3.3 и §4.10. +- � на �кране партии: «�айти �ту позицию в базе (Ctrl+Shift+F)». + +### 5.5. До�тупно�ть + +- Поло�а — по �ветлоте + чи�ла + tooltip (§4.10). +- Очередь хода — круг + тек�т. +- ⤳/⑂ — значки + tooltip, без опоры на цвет. +- В�е дей�тви� до�тупны � клавиатуры, кроме ввода хода на до�ке (как и на �кране партии; ввод ходов тек�том SAN — позже, §7.2). + +## 6. «Больше, чем ChessBase», но без �ложно�ти + +| Иде� | Ценно�ть | Стоимо�ть | Решение | +| --- | --- | --- | --- | +| **Позици� + фильтры в одном �кране, живо** (без ма�ки и OK) | главна� | заложено | перва� вер�и� — �то и е�ть продукт | +| **Сильнейшие �верху по умолчанию** («топ-партии» без отдельного окна) | вы�ока� | ноль (�ортировка) | перва� вер�и� | +| **Стрелка хода при наведении на партию** в таблице — видно, что в ней �ыграли дальше, не открыва� её | вы�ока�, такого нет у ChessBase | низка� (ход уже е�ть в проходе) | перва� вер�и� | +| **Метка «дальше партий нет»** в линии | �редн�� | низка� (к�ш) | перва� вер�и� | +| «Вернуть» по�ле �бро�а вме�то подтверждени� | �редн�� | низка� | перва� вер�и� | +| «Открыть как новую партию», «Копировать FEN» | �редн�� (мо�т к анализу) | низка� | перва� вер�и� | +| **Оценка движка текущей позиции** по `L` — �трока над продолжени�ми «+0.31 · 3.d4 · глубина 24» + зелёна� �трелка | вы�ока� дл� изучени� дебюта | �редн��: `analysis.rs` уже прив�зан к и�тории позиции, нужен второй потребитель и пауза при уходе � �крана | **�разу по�ле первой вер�ии** (вопро� 7.3.4) | +| Пои�к новинки: на �кране партии «парти� вышла из базы на 14-м ходу» | вы�ока� дл� комментатора | �редн�� (позиционный проход по в�ей линии партии) | позже | +| �азвани� дебютов над линией (таблица lichess chess-openings, CC0 — проверить лицензию) | �редн�� | низка�-�редн�� (данные + лицензи�) | позже | +| Оценка движка у каждого продолжени� | �редн�� | вы�ока� (MultiPV по в�ем ходам) | нет | +| Perf, «Hot», впервые �ыграно, тренд по годам | низка� дл� нашей аудитории | �редн�� | позже | +| Фрагмент/материал/�труктура/манёвры | �редн�� у �пециали�тов | вы�ока�, другой интерфей� | позже, отдельной ма�кой | +| Чипы-поповеры: правка фильтра пр�мо из чипа, не уход� � до�ки | вы�ока� дл� �очетани� режимов | �редн�� (дубль полей в `Popup`) | �ледующа� итераци�, е�ли переключение окажет�� ча�тым | + +## 7. Объём и вопро�ы + +### 7.1. Перва� вер�и� + +1. Сегментный переключатель `[Фильтры | До�ка]` (вме�то «Фильтры ⟩»), отдельна� ширина панели до�ки (0,5 окна), `Ctrl+B`. +2. Строка у�ловий: в�егда в большой базе, в малой — при открытой до�ке; фик�ированный пор�док, `×`, переход к у�ловию по щелчку, мини-до�ка в tooltip «Позиции». +3. До�ка пои�ка (виджет `board.rs`), шапка панели, лини� � ◀ ▶, `�/→/Home/End/Backspace/F/Ctrl+Backspace`, «Сбро�ить» + «Вернуть», меню `⋯`. +4. Совпадение по позиции � переходами, первое вхождение, о�новна� лини� (больша� база) / � вариантами (мала�). Пор�док ходов: ⤳, �ообщение в �троке чипов, «только �тот пор�док». +5. Продолжени�: две компоновки (�права от до�ки при ширине ≥ 820, иначе под ней), поло�а Б/�/Ч � чи�лами, �р. Эло, год, «Закончили�ь зде�ь», цифры 1–9, наведение — �трелка, ча�тичный под�чёт � заморозкой под кур�ором. Дл� книг — упрощённый вид. +6. Таблица: колонка «Ход», «Ходы» → «Длина», приоритеты �крыти�, Эло в �чейке имени на узкой таблице, «�ильнейшие �верху» автоматиче�ки, �трелка хода при наведении на �троку, открытие на найденном ходе. +7. Со�то�ни�: пои�к (таблица �тара� затемнённа�, продолжени� ча�тичные), 0 партий � двум� выходами и меткой «дальше партий нет», FEN/`--`/Chess960/тек�ты. +8. «�айти позицию в базе» на �кране партии (`Ctrl+Shift+F`), «� К партии». +9. Свёрнута� полка при вы�оте < 760 в режиме «До�ка» (е�ли владелец �огла�ен, вопро� 7.3.2). + +### 7.2. Потом + +Оценка движка по `L`; правка у�ловий из чипов; три колонки «таблица | до�ка | фильтры» на окнах ≥ 1700; дерево введённых вариантов на до�ке пои�ка; ввод хода тек�том (SAN); автоматиче�кий переворот при «Игрок … чёрными»; пои�к новинки; названи� дебютов; �ортировка продолжений по заголовкам; фрагменты/материал/�труктура; по�то�нный индек� позиций; �к�порт выборки в PGN (LD 8.5). + +### 7.3. Вопро�ы владельцу (� рекомендацией) + +1. **Куда ищет «�айти позицию в базе» из партии?** Рекомендую кнопку � выпадающей �трелкой «� �айти в: Mega Database 2026 ▾». По умолчанию — по�ледн�� выбранна� база-цель, а пока её не выбирали — �ама� больша� база на полке (типичный путь «читаю книгу → что играют ма�тера?»), иначе база �амой партии. Отдельного пон�ти� «�правочна� база» не вводить. +2. **Сворачивать полку до одной �троки в режиме «До�ка» при вы�оте окна < 760?** Рекомендую да: иначе на 900×600 до�ка 240 и 3 �троки продолжений. +3. **«Только �тот пор�док» — в первую вер�ию?** Рекомендую да: �то одна ��ылка и одно �равнение в уже идущем проходе. Е�ли по�вит�� только при наличии переходов — �ложно�ти не добавит. +4. **Оценка движка на до�ке пои�ка (`L`)** — перва� вер�и� или �разу по�ле? Рекомендую �разу по�ле: �начала у�то�ть �коро�т�м и �о�то�ни�м пои�ка. +5. **Сортировка по умолчанию — «�ильнейшие �верху» (�реднее Эло)?** Рекомендую да, � возвратом прежней �ортировки при �н�тии позиции (§4.8). +6. **Мала� база: продолжени� без результатов и Эло (только «N глав»)?** Рекомендую да (§4.10). + +## 8. Где не �огла�ен � и�ходной �хемой и почему (�водка) + +1. **Продолжени� во врем� пои�ка не могут показывать �тарую позицию** — очищают�� и показывают ча�тичный под�чёт новой (§4.3). Таблица — �тара�, затемнённа�, как у фильтров. +2. **Сообщение о пор�дке ходов** — нейтральна� формулировка «�тим пор�дком N из M» и ме�то в �троке чипов, без отдельной в�плывающей �троки над таблицей (§3.2). +3. **Строка у�ловий** — в�егда в большой базе (зарезервирована, чтобы не прыгала), в малой — только при открытой до�ке (§2.2). +4. **Продолжени� �права от до�ки на широком �кране** (≥ 820 ширины панели), под до�кой — на узком (§2.3–2.4). Одна вертикальна� �хема тер�ет половину �крана 1920. +5. **Клавиши: «вертикаль — таблице, горизонталь — до�ке»**, цифры 1–9 дл� продолжений, `→` в конце линии не играет ход (§5). +6. **Стати�тика в книгах** — без поло�ы результатов и Эло (§4.10). +7. **Сортировка «�ильнейшие �верху»** — автоматиче�ка�, только е�ли пользователь �ам не выбирал �ортировку, и откатывает�� при �н�тии позиции (§4.8). +8. **«�айти позицию» по�ле `--` и в Chess960** — неактивна � объ��нением, а не «пои�к по ра��тановке» (§4.6). diff --git a/docs/design/design-system.md b/docs/design/design-system.md new file mode 100644 index 0000000..be598b8 --- /dev/null +++ b/docs/design/design-system.md @@ -0,0 +1,175 @@ +# Дизайн-�и�тема ChessPenguin + +Дата фик�ации: 2026-11-05. О�нова документа — **библиотека баз и �пи�ок партий, про�мотр партии, на�тройка и игра � компьютером**. Раздел тренировки дебютов не �вл�ет�� визуальным �талоном дл� �того документа. + +Документ различает три �тату�а: + +- **Факт** — �уще�твующа� реализаци�, подтверждённа� и�ходниками и про�мотренными �нимками. +- **Правило пользовател�** — об�зательное требование, в том чи�ле новое, даже е�ли раньше интерфей� работал иначе. +- **Рекомендаци�** — предлагаемый �по�об унифицировать новые �краны; не утверждение, что в�е �тарые �краны уже ему �оответ�твуют. + +В�е размеры далее — логиче�кие единицы egui (pt), не физиче�кие пик�ели �нимка. Ма�штаб окна/HiDPI мен�ет физиче�кое изображение. Значени� цветов — и�ходные токены, а не замер �глаженных пик�елей тек�та. + +## 1. Характер интерфей�а и �талоны + +**Факт.** Это плотное на�тольное приложение дл� работы � шахматным материалом. О�нову �о�тавл�ют панели, таблицы, нотаци� и до�ка; заголовки и дей�тви� компактны. Выделение �инее, фон �покойный, разделители тонкие. Больша� ча�ть про�тран�тва отдана данным, а не декоративным контейнерам. + +Про�мотренные визуальные и�точники: + +| Экран | Что задаёт �талон | Снимок | +|---|---|---| +| Библиотека | Верхн�� полка баз, �трока дей�твий, плотна� таблица, фильтры �права | [library.png](../screenshots/library.png) | +| Парти� | До�ка �лева, нотаци�/анализ �права, компактна� шапка, toolbar внизу | [game.png](../screenshots/game.png) | +| �а�тройка игры | По�ледовательно�ть выбора, равные плитки внутри группы, о�новной Play и Cancel внизу | [play.jpg](../screenshots/play.jpg) | + +Это реальные �нимки приложени�, а не новые макеты. Их �зык, ма�штаб и �о�тав данных отличают��; точные размеры берут�� из кода. Дополнительно про�мотрены �вежие RU-�нимки текущей �борки, 1400×900, тёмна� тема: [главна�](../../target/qa-quiet-status/shots/main.png), [парти�](../../target/qa-quiet-status/shots/game.png), [на�тройка игры](../../target/qa-quiet-status/shots/play.png). По�ледний �нимок подтверждает диалог выбора, а не запущенную партию � движком. QA-файлы в `target/` локальные и могут от�ут�твовать по�ле очи�тки. + +**Рекомендаци�.** �овые разделы заим�твуют �ту �труктуру и общие widgets. �е вводить отдельную палитру, крупные декоративные KPI-карточки, по�то�нные пу�тые резервные блоки или новый комплект шрифтов. Суще�твование карточек базы и шахматных ча�ов не делает карточку универ�альным контейнером дл� любого тек�та. + +## 2. Типографика + +**Факт.** Приложение начинает � `egui::FontDefinitions::default()`: о�новной proportional — **Ubuntu Light**, monospace — **Hack**. Дополнительно подключены **Ubuntu Bold**, глифы фигур и NotoSansMath дл� шахматных оценок. Дл� фигур и�пользует�� tweak scale 0.85 и y-offset −1. И�точник: [assets.rs:156](../../apps/desktop/src/assets.rs#L156), [assets.rs:168](../../apps/desktop/src/assets.rs#L168). + +| �азначение | Реализованное значение | И�точник | +|---|---:|---| +| Обычный тек�т / �тандартна� кнопка | 13 | egui `TextStyle::Body` / `Button` | +| Обычный heading | 18 | egui `TextStyle::Heading` | +| Monospace по умолчанию | 13 | egui `TextStyle::Monospace` | +| `.small()` по умолчанию | 9 | egui `TextStyle::Small` — не универ�альна� рекомендаци� дл� важных данных | +| �азвание базы / �трока подробно�тей на полке | 14 / 12 | [library.rs:1200](../../apps/desktop/src/library.rs#L1200) | +| Ход о�новной нотации | Ubuntu Bold 16 | [notation.rs:606](../../apps/desktop/src/notation.rs#L606) | +| �омер хода / комментарий | 14 / 14.5 | [notation.rs:299](../../apps/desktop/src/notation.rs#L299), [notation.rs:862](../../apps/desktop/src/notation.rs#L862) | +| Заголовок группы / выбор в на�тройке игры | 15 strong / 14 | [play.rs:1278](../../apps/desktop/src/play.rs#L1278) | +| Им� игрока / �о�то�ние под именем | 15 / 13 weak | [game_view.rs:3515](../../apps/desktop/src/game_view.rs#L3515) | +| Шахматные ча�ы | monospace 18–28, адаптивно | [game_view.rs:3484](../../apps/desktop/src/game_view.rs#L3484) | + +`RichText::strong()` и �вный `assets::bold()` — разные механизмы: наличие `.strong()` не означает назначение Ubuntu Bold. Дл� шахматных ходов уже е�ть �вный �емей�твенный токен, его �ледует переи�пользовать. + +**Рекомендаци�.** Body/heading примен�ть по �мы�лу. Второ�тепенно�ть выражать `weak()`, а не произвольным уменьшением в�ех подпи�ей. Значимые чи�ла, названи� и кнопки не делать 9 pt. Имена обрезать � многоточием и давать полное название в tooltip; по��нени� перено�ить. Дл� ча�ов и техниче�ких по�ледовательно�тей допу�тим monospace, дл� обычных метрик он не об�зателен. + +## 3. Темы и цветовые токены + +**Факт.** И�пользуют�� `egui::Visuals::dark()` и `light()`, без �об�твенной глобальной палитры. Тёмна� тема — значение по умолчанию в Settings. И�точники: [app.rs:3782](../../apps/desktop/src/app.rs#L3782), [settings.rs:210](../../apps/desktop/src/settings.rs#L210). + +Значени� ниже �н�ты � локально у�тановленной зави�имо�ти **egui 0.36.2**, на которой по�троена текуща� реализаци�. Они опи�ывают snapshot, а не требование дублировать RGB в каждом модуле. Вызывать `ui.visuals()` предпочтительнее литералов. + +| Роль / токен | Тёмна� тема | Светла� тема | +|---|---|---| +| Фон панелей/окон `panel_fill`, `window_fill` | RGB(27,27,27), `#1B1B1B` | RGB(248,248,248), `#F8F8F8` | +| Обычный тек�т `noninteractive.fg_stroke` | RGB(140,140,140), `#8C8C8C` | RGB(80,80,80), `#505050` | +| Разделитель `noninteractive.bg_stroke` | RGB(60,60,60), `#3C3C3C`, 1 pt | RGB(190,190,190), `#BEBEBE`, 1 pt | +| Фон кнопки в обычном �о�то�нии (без наведени�) | RGB(60,60,60), `#3C3C3C` | RGB(230,230,230), `#E6E6E6` | +| Тек�т кнопки в обычном �о�то�нии (без наведени�) | RGB(180,180,180), `#B4B4B4` | RGB(60,60,60), `#3C3C3C` | +| Hover-фон обычной кнопки | RGB(70,70,70), `#464646` | RGB(220,220,220), `#DCDCDC` | +| �ажатый фон обычной кнопки | RGB(55,55,55), `#373737` | RGB(165,165,165), `#A5A5A5` | +| Выбранное / primary `selection.bg_fill` | RGB(0,92,128), `#005C80` | RGB(144,209,255), `#90D1FF` | +| `selection.stroke.color` | RGB(192,222,255), `#C0DEFF` | RGB(0,83,125), `#00537D` | +| Фон пол� ввода `extreme_bg_color` | RGB(10,10,10), `#0A0A0A` | RGB(255,255,255), `#FFFFFF` | +| С�ылка `hyperlink_color` | RGB(90,170,255), `#5AAAFF` | RGB(0,155,255), `#009BFF` | +| Предупреждение `warn_fg_color` | RGB(255,143,0), `#FF8F00` | RGB(255,100,0), `#FF6400` | +| Ошибка `error_fg_color` | RGB(255,0,0), `#FF0000` | RGB(255,0,0), `#FF0000` | + +`weak_text_alpha=0.6`, `disabled_alpha=0.5`. `faint_bg_color` — аддитивна� �рко�ть 5, **не �амо�то�тельный непрозрачный RGB-фон**. �е примен�ть её как един�твенную заливку полно�кранного workspace. Стандартные радиу�ы: окно 6, обычный widget 2, hover 3; локальные компоненты могут задавать �вои значени�. + +И�точники чи�ел: локальный [egui style.rs:1414](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1414), [темы:1498](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1498), [выделение:1618](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1618), [widget states:1681](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1681). Это ��ылки на локальный cache дл� во�производимо�ти, они не �вл�ют�� файлами репозитори�. + +### Шахматные �емантиче�кие цвета + +**Факт.** Комментарии: dark `#9EC4E0`, light `#2A5B8A` ([notation.rs:1141](../../apps/desktop/src/notation.rs#L1141)). NAG имеют отдельную �огла�ованную палитру, а тек�т в �ветлой теме затемнён дл� читаемо�ти: + +| NAG | О�новной цвет | Тек�т в �ветлой теме | +|---|---|---| +| `!` | `#81B64C` | `#5B8135` | +| `?` | `#FFA459` | `#C25700` | +| `!!` | `#26C2A3` | `#1A846F` | +| `??` | `#FA412D` | `#D2301C` | +| `!?` | `#EA45D8` | `#B0259F` | +| `?!` | `#56B4E9` | `#1F72A8` | + +И�точник: [notation.rs:695](../../apps/desktop/src/notation.rs#L695). Цвета до�ки/фигуры выбирает пользователь; зелёна� или коричнева� до�ка на �нимке не задаёт палитру интерфей�а. Стрелки PGN имеют �амо�то�тельную �емантику ([board.rs:767](../../apps/desktop/src/board.rs#L767)). + +## 4. Кнопки и �о�то�ни� + +**Факт.** Одного размера дл� в�ех кнопок �ейча� нет. Это важно учитывать, а не объ�вл�ть произвольные 30 pt уже �уще�твующим глобальным �тандартом. + +| Роль | Реализаци� | Размер/поведение | +|---|---|---| +| Плотна� кнопка toolbar | `ui.button`, обычный egui Button | Базовый `interact_size` 40×18, padding 4×1; фактиче�кий размер зави�ит от тек�та и widget | +| Главное дей�твие диалога | `widgets::primary[_wide]` | Минимальна� вы�ота 30; strong, заливка selection; `_wide` �охран�ет минимальную ширину | +| Подтвердить/отменить значком | `widgets::icon_button` | 30×30, радиу� 4, ри�ованные ✓/✕ | +| �ебольша� отмена фоновой задачи | `widgets::small_close_button` | 22×20, при hover кра�ный `#C42B1C`, белый кре�тик | +| Сортировка таблицы | `widgets::sort_header` | Без рамки, strong, направление �/� | +| Выбор цвета/времени игры | selectable button | 32 pt вы�ота, 14 pt тек�т; внутри �троки одинакова� ширина, gap 6 | +| Выбор Maia/Rodent | Специальна� плитка выбора | 48 pt вы�ота, два уровн� тек�та | +| Управление текущей игрой | `play_toolbar` | Обща� вы�ота 28; значки 18 pt, �лове�ные кнопки 14 pt | + +И�точники: [widgets.rs:35](../../apps/desktop/src/widgets.rs#L35), [widgets.rs:80](../../apps/desktop/src/widgets.rs#L80), [play.rs:1274](../../apps/desktop/src/play.rs#L1274), [play.rs:1406](../../apps/desktop/src/play.rs#L1406), [game_view.rs:3561](../../apps/desktop/src/game_view.rs#L3561). + +**Рекомендаци� дл� новых групп.** Св�занные дей�тви� должны иметь одну вы�оту и baseline. Дл� группы о�новных дей�твий и�пользовать 30 pt, дл� плотного toolbar — �уще�твующий размер �о�едних �лементов; не увеличивать в�ю верхнюю панель без причины. Равна� ширина нужна у альтернативных вариантов выбора и замен�ющих друг друга дей�твий; кнопка «Закрыть» не об�зана быть шириной �о в�ё окно. Primary — одно очевидное о�новное дей�твие, не каждый переход. Разрушительное дей�твие отдел�ет�� �мы�лом и подтверждением, а не только кра�ным цветом. + +**Факт.** Hover/pressed/open/disabled получают цвета из `ui.style().interact(...)` или �тандартного Button. Selected — отдельное �о�то�ние: �то не hover. Дл� �об�твеннори�ованных кнопок нужно во�произве�ти �о�то�ние и hit target; ри�овать только иконку недо�таточно. До�тупно�ть `add_enabled` не замен�ть визуально похожим тек�том. + +**Правило пользовател�, 2026-11-05.** Глобальные на�тройки — одна обща� кнопка �права +в шапке, включа� �тати�тику и прохождение тренировки. `widgets::settings_button` +переи�пользует�� библиотекой, партией и разделом дебютов: обычна� «⚙ �а�тройки», +без primary-заливки; в компактном режиме — значок � пон�тной под�казкой и Ctrl+,. +Ме�то под неё резервирует�� до длинного заголовка. Локальные параметры тренировки +не замен�ют общие на�тройки. Возврат из окна на�троек �охран�ет контек�т �крана. + +## 5. Таблицы, полка баз и нотаци� + +**Факт — �пи�ок партий.** `TableBuilder`: поло�атые �троки, измен�емые ширины колонок, кликабельна� �трока; header **26 pt**, обычна� �трока **24 pt**. Ячейки и�пользуют left-to-right / Align::Center: вертикально центрированы, тек�т по умолчанию �лева. Чи�ловые колонки зде�ь **не выровнены глобально вправо**. �азвани� обрезают��, �обытие выделено кур�ивом, неизве�тные значени� ча�то пу�тые. Один клик выдел�ет; открытие и клавиатура реализованы отдельно. И�точник: [large_db.rs:2109](../../apps/desktop/src/large_db.rs#L2109), [large_db.rs:2149](../../apps/desktop/src/large_db.rs#L2149), [large_db.rs:2212](../../apps/desktop/src/large_db.rs#L2212). + +Колонки адаптируют�� к ширине: второ�тепенные данные �крывают��, дата может �тать годом. �е требовать от узкого окна одновременно показывать полный набор колонок. Сортировочный заголовок показывает активное направление. Выбранна� �трока, hover и отметка про�мотренной партии — разные признаки. + +**Факт — полка баз.** Карточка базы **190×64**, промежутки 8×8; название 14 pt мак�имум две �троки, подробно�ти 12 pt, иконка 22 pt. Это �пецифиче�кий переключатель и�точника данных, а не образец вы�оты �троки таблицы. При более чем двух р�дах/низком окне полка �ворачивает�� в компактный вариант. И�точник: [library.rs:545](../../apps/desktop/src/library.rs#L545), [library.rs:947](../../apps/desktop/src/library.rs#L947), [library.rs:1172](../../apps/desktop/src/library.rs#L1172). + +**Факт — нотаци�.** Строка о�новной пары ходов **26 pt**, колонка номера **38 pt**, кажда� �чейка хода мак�имум **160 pt**. �омер выровнен вправо, white/black �то�т в отдельных �чейках. �ктивный ход выдел�ет��; комментарии и ветви занимают �об�твенные �троки/блоки. И�точник: [notation.rs:180](../../apps/desktop/src/notation.rs#L180), [notation.rs:290](../../apps/desktop/src/notation.rs#L290). + +**Рекомендаци�.** �ова� одноуровнева� таблица начинает � 24/26 pt и увеличивает вы�оту только по реальному �одержимому. Много�трочна� �трока должна иметь отдельное обо�нование. Значени� 156 pt и оформление �пи�ка тренировки дебютов **не вход�т в общую дизайн-�и�тему**. Чи�ла в новой аналитиче�кой таблице удобно выравнивать вправо, но �то предложение дл� неё, не опи�ание �уще�твующего �пи�ка партий. + +## 6. Компоновка и от�тупы + +**Факт.** Стандартный egui spacing: между widget 8 pt по горизонтали и 3 pt по вертикали; window/menu margin 6. Локально приложение мен�ет spacing по задаче: play-dialog — gap 6, form-grid 8×6, начало �екции +12 и по�ле заголовка +2. Ча�ы имеют inner margin 10×6 и радиу� 4. + +- Библиотека: полка �верху, таблица в центре, фильтры �права; фильтры по умолчанию 280 pt, верхний предел 380 ([library.rs:602](../../apps/desktop/src/library.rs#L602)). +- Парти�: `Panel::top` шапки; права� измен�ема� панель и `CentralPanel` до�ки. Бокова� панель нотации по умолчанию `(width*0.4).clamp(260,460)` � дополнительным ограничением ме�та дл� до�ки. Минимумы: side 240, reference 320, board 220; поло�а оценки 26 ([game_view.rs:749](../../apps/desktop/src/game_view.rs#L749), [game_view.rs:5004](../../apps/desktop/src/game_view.rs#L5004)). +- В узком/вы�оком окне панель партии может перейти под до�ку; выбор компоновки зави�ит от окна, а не по�влени� анализа или �мены вкладки. Подробное �уще�твующее правило: [narrow-windows.md](narrow-windows.md). +- Игра и�пользует тот же карка� до�ки. Им�/ча�ы верхней �тороны �верху, нижней — �низу, нотаци� между ними, toolbar закреплён внизу ([game_view.rs:3359](../../apps/desktop/src/game_view.rs#L3359)). +- Диалог игры имеет ширину 460; тело �кроллит�� при малой вы�оте, кнопки завершени� выбора о�тают�� видны. �е �кроллить главный CTA вме�те � длинным телом ([play.rs:1253](../../apps/desktop/src/play.rs#L1253)). + +**Рекомендаци�.** Св�занные �лементы группировать интервалами 6–8 pt, �мы�ловые группы отдел�ть 10–12 pt или �тандартным separator. �е примен�ть фик�ированную пу�тую вы�оту как универ�альную защиту от �качков. Закрепл�ть дей�тви� вне ра�тущего тек�та/�кролла, а данные давать е�те�твенной вы�оты. Ра�чёт минимальной ширины должен учитывать реальный перевод и ме�та под кнопки до размещени� длинного имени. + +## 7. Клавиатура, фоку�, названи� + +**Факт.** В �пи�ке партий е�ть ↑/↓, PageUp/PageDown, Enter; �об�твенные базы добавл�ют команды редактировани�. В партии е�ть �/→, Home/End, F (поворот), команды �охранени� и Undo/Redo. Команды отделены от ввода тек�та и контек�тных режимов; по�тому буквальные �очетани� �ледует провер�ть в обработчике конкретного �крана, а не копировать без guards. И�точники: [large_db.rs:2377](../../apps/desktop/src/large_db.rs#L2377), [game_view.rs:4779](../../apps/desktop/src/game_view.rs#L4779). Escape отмен�ет диалог на�тройки игры ([play.rs:1815](../../apps/desktop/src/play.rs#L1815)). + +**Рекомендаци�.** Tab/Shift+Tab — по�ледовательный обход, Enter активирует ожидаемое дей�твие �фоку�ированного �лемента, Escape закрывает �амый верхний popup/диалог прежде, чем уходить � �крана. �е перехватывать �очетание редактировани� тек�та дл� управлени� до�кой. Иконки без �лов требуют tooltip � пон�тным дей�твием; полные обрезанные имена до�тупны при наведении. �е �читать полную клавиатурную до�тупно�ть в�ех �тарых �кранов доказанной только наличием egui. + +## 8. Загрузка, �охранение, ошибки + +**Правила пользовател�, 2026-11-05.** + +1. **�е показывать spinner при обычном �тарте главного �крана.** Во��тановление библиотеки и её �лужебные фоновые проверки не должны превращать запу�к в демон�трацию внутренних операций. +2. **�е показывать «Сохранение прогре��а / Saving progress…» по�ле каждого хода.** Обычна� у�пешна� фонова� запи�ь проходит тихо; она не должна мен�ть тек�т, вы�оту или �о�то�ние о�новного блока на каждом ответе. + +Эти правила не означают запрет в�ей обратной �в�зи о длительной работе. **Рекомендаци�:** при �вно запущенном пользователем импорте, �качивании движка или длительном анализе показывать о�мы�ленное �о�то�ние, чи�ленный прогре��, е�ли он изве�тен, и отмену, е�ли она поддерживает��. Короткие внутренние операции не должны мигать индикаторами. + +**Факт.** В на�тройке игры �качивание ве�ов и�пользует ProgressBar ([play.rs:1978](../../apps/desktop/src/play.rs#L1978)); текущий �оперник показывает «thinking…» тек�том в �воей �троке �о�то�ни� ([game_view.rs:3518](../../apps/desktop/src/game_view.rs#L3518)). Это предметна� обратна� �в�зь, а не общий spinner на в�ё окно. + +**Рекомендаци�.** Ошибку показывать �ловами о результате дей�тви�, � конкретным до�тупным �ледующим шагом. Техниче�кую причину — ра�крываемыми подробно�т�ми, без обрезани� един�твенного полезного �ообщени�. При ошибке запи�и нельз� показывать у�пешное �охранение или молча тер�ть данные. Со�то�ние загрузки не должно подмен�ть �тарые данные новой позиции; а stale-анализ нельз� выдавать за текущий. Empty-�о�то�ние объ��н�ет от�ут�твие данных и до�тупное дей�твие, а не выводит набор нулей без контек�та. + +## 9. Граница применени� и приёмка + +Этот файл опи�ывает �уще�твующую о�нову и рекомендует единые правила дл� дальнейшей работы. Он не утверждает, что ве�ь UI уже унифицирован. Плотный toolbar 18 pt, игровые кнопки 28 pt, primary 30 pt и плитки выбора 32/48 pt — реальные разные роли; и�правл�ть их до одного чи�ла без анализа �ценари� не требует��. + +Дл� нового UI провер�ть не только попадание тек�та в пр�моугольник: + +- Пон�тны ли задача �крана, единицы чи�ел и �ледующее дей�твие без чтени� внутреннего ТЗ? +- Соответ�твуют ли фон, тек�т, выделение и плотно�ть о�новным �кранам? +- Совпадают ли размеры и baseline дей�твий одной группы? +- Сохран�ют�� ли контек�т, выбранна� �трока, фоку� и геометри� до�ки при данных/ошибке/возврате? +- Работают ли длинные имена, пу�тое �о�то�ние, �ветла�/тёмна� тема и выбранна� минимальна� ширина? +- �ет ли мигающей �лужебной активно�ти при �тарте и на каждом ходе? + +Визуальную приёмку проводит отдельный reviewer на реальных �нимках, � указанием �о�то�ни�, размера окна и конкретного �ценари�. Код и геометриче�кие те�ты полезны, но не замен�ют оценку пон�тно�ти и �оответ�тви� �талонам. diff --git a/docs/design/desktop-adjourned.md b/docs/design/desktop-adjourned.md new file mode 100644 index 0000000..8ce9498 --- /dev/null +++ b/docs/design/desktop-adjourned.md @@ -0,0 +1,297 @@ +# Отложенна� парти� на компьютере + +Стату�: проект дизайнера, 2026-10-26, **не утверждён** (вопро�ы — §10). Запро� владельца: «� карточкой мне очень понравило�ь как ты �делал на телефоне. нужно тут подумать как �то в де�ктопе правильно �делать. очень кра�иво и гармонично». Ча�ы продолжают � того ме�та, где партию о�тавили. + +Опирает�� на: телефон — `android-play.md` §31.7, `android-lists.md` §5.4, `DatabasesScreen.kt` (карточка), `PlayMode.kt` (`AdjournedQuestion`); компьютер — `play-mode.md` §3.5, §6, `player-games.md` §4, §6, `library-layout.md` §1.4–1.5, `narrow-windows.md` §2.5, §4a, `rodent-opponent.md` §7; код — `library.rs` (`shelf`, `compact_shelf`, `db_card` 190 × 64), `game_view.rs` (`play_toolbar`, `leave_question`, `guard_leaving`), `player_games.rs` (`Journal::put_aside`, `PutAside`, `recover` — уже в работе у разработчика), `play.rs` (`rival_name`, `Saved`). + +Снимки 1.7.0, по которым �делан проект (scratchpad `designer-adj/`): `lib1400.png`, `lib1400d.png` (тёмна�), `lib960.png`, `lib640.png` (640 × 480, компактна� полка), `play1400.png`, `play640.png` (�топка), `leave1400.png` (�егодн�шний вопро� «Парти� идёт»). + +Размеры — логиче�кие точки egui. Тек�ты — по-ру��ки, англий�кий ключ `tr(...)` в �кобках или в таблице §9. + +## 0. Главное + +1. **Отложить** можно трем� пут�ми: кнопка «� Отложить» в панели игры (без вопро�а), ответ «Отложить» в вопро�е «Парти� идёт» (теперь главна� кнопка) и закрытие окна программы (без вопро�а). Ча�ы о�танавливают��, �оперник выключает��, ничего не пишет�� в базу. +2. **Карточка** — на полке библиотеки, �права в первом р�ду, той же вы�оты 64, что карточки баз: �лева до�ка позиции во в�ю вы�оту (как обложка), три �троки тек�та, «Продолжить» (главна� кнопка) и ×. Рамка акцентным цветом, а не заливка: заливка на полке уже значит «выбранна� база». +3. **×** — «не доигрывать»: парти� запи�ывает�� в базу игрока неоконченной (`*`), как на телефоне. Под�казка × так и говорит. +4. **Сбой** — при �ледующем запу�ке парти� не запи�ывает��, а лежит отложенной: та же карточка и один то�т о том, что �лучило�ь. +5. **�ова� парти� при отложенной** — вопро� «Е�ть отложенна� парти�» � до�кой: «Продолжить её» (главна�, Enter) / «�ачать новую». Ctrl+G, Enter — продолжить � клавиатуры. +6. **Одна** отложенна� парти� — как на телефоне. + +## 1. Где живёт карточка + +### 1.1. Библиотека — полка + +�а �нимках `lib1400.png` / `lib960.png` �права от карточек баз пу�тое ме�то во в�ю вы�оту р�да. Это ме�то карточки. + +``` +1400 × 900, 3 базы +Базы + Добавить базу ✚ �ова� база � Онлайн-партии │ ♟ �ова� парти� 📋 В�тавить PGN │ ⚔ Играть ⚙ �а�тройки +┌──────────────────� ┌──────────────────� ┌──────────────────� ┌────────┬───────────────────────────────────────� +│♞ Роман — партии �│ │🗄 Кла��иче�кие │ │🗄 �лехин │ │ до�ка │ Парти� � Maia 1550 × │ +│ компьютером │ │ партии │ │ │ │ 64×64 │ вы белыми · 5-й ход [▌Продолжить�] │ +│ 3 партии │ │ не загружена │ │ не загружена │ │ │ 5+3 · вы 4:12 · Maia 3:58 │ +└──────────────────┘ └──────────────────┘ └──────────────────┘ └────────┴───────────────────────────────────────┘ +────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +Роман — партии � компьютером · PGN, UTF-8 · 3 партии + Парти� � Пои�к… Фильтры До�ка +``` + +- **Справа, а не первой �лева** (рекомендаци�, вопро� 1). Карточки баз не �двигают��, пока парти� отложена: человек находит базу там, где привык. Отложенна� парти� — не база, ей ме�то отдельно; у правого кра� она �тоит под «⚙ �а�тройки», в�егда в одной точке, �колько бы ни было баз. Заметно�ть дают рамка и един�твенна� на полке заполненна� кнопка. +- **�е�колько р�дов баз** — карточка о�таёт�� �права в первом р�ду, как колонка; базы во в�ех р�дах перено��т�� в ширине `W − карточка − 24`. Чи�ло р�дов `card_rows` и правило компактной полки (`narrow-windows.md` §2.5, «больше двух р�дов») �читают�� � �той шириной. +- **Пу�та� полка** (`library-layout.md` §1.5, «Баз пока нет») — так быть не может: у отложенной партии � запи�ью в�егда е�ть база игрока. Е�ли запи�ь выключена и баз нет — карточка �права в �троке, где были бы карточки, приглашение «Баз пока нет» — ниже, как обычно. + +### 1.2. Экран партии + +**�а �кране партии карточки нет** — ни во врем� игры, ни при про�мотре другой партии. Экран партии — про одну партию на до�ке; втора� до�ка р�дом �порила бы � ней. Об отложенной партии �кран партии говорит только тогда, когда начинает�� нова� игра (вопро� §5) или когда уход возвращает не в библиотеку (то�т §3.4). + +## 2. Карточка + +### 2.1. Вид + +``` +┌────────┬──────────────────────────────────────────� вы�ота 64, ширина по �одержимому 360…460 +│▓▓░░▓▓░░│ Парти� � Maia 1550 × │ 14, цвет тек�та; × — small_close_button +│░░▓▓░░▓▓│ вы белыми · 5-й ход [▌Продолжить�] │ 12, �лабым; кнопка primary, по центру вы�оты +│▓▓░░▓▓░░│ 5+3 · вы 4:12 · Maia 3:58 │ 12, �лабым, цифры моно +└────────┴──────────────────────────────────────────┘ + ↑ до�ка 64 × 64 вплотную к левому краю, �кругление 6 только �лева +``` + +| Ча�ть | Что | Как | +|---|---|---| +| рамка | `faint_bg_color` (как у карточки базы), обводка 1,5 `selection.bg_fill`, �кругление 6 | наведение — заливка `widgets.hovered.weak_bg_fill`, обводка та же | +| до�ка | позици� по�ле по�леднего �ыгранного хода, �торона игрока �низу; до�ка и фигуры — из на�троек; без координат, �трелок, под�ветки хода | ри�ует�� �уще�твующей отри�овкой до�ки «только показать»; 8 точек на поле — узор позиции, разгл�деть — в под�казке (§2.3) | +| �трока 1 | «Парти� � {�оперник}» | Maia — «Парти� � Maia 1550»; Rodent — «Парти� � Rodent IV 2200» (им� и �ила, `rival_label`); не помещает�� — «…», целиком в под�казке | +| �трока 2 | «вы белыми · {n}-й ход»; у Rodent �о �тилем �тиль первым: «�лехин · вы чёрными · 18-й ход» | �тиль — переведённое название (`rival_style`), как на поло�е �оперника; «Сбалан�ированный» не пишет��. `{n}` — номер хода текущей позиции (тот, что �ейча� делает��), как на телефоне; неизве�тен — только «вы белыми» | +| �трока 3 | ча�ы: «5+3 · вы 4:12 · Maia 3:58»; без ча�ов — «без ча�ов» | врем� — `clock_text`, моноширинные цифры; у �оперника — короткое им� без �илы («Maia», «Rodent IV»), �ила уже в �троке 1 | +| «Продолжить» | `widgets::primary`, �права, по центру вы�оты | един�твенна� заполненна� кнопка на полке | +| × | `widgets::small_close_button`, правый верхний угол, от�туп 4 | �мы�л — §2.4 | + +- **В�� карточка нажимает��** как «Продолжить» (как на телефоне): щелчок по до�ке или тек�ту. × и кнопка — �вои обла�ти. +- **Ширина**: `64 + 12 + max(�троки 1–3) + 12 + кнопка + 8 + 20 + 4`, не меньше 360 и не больше 460; �троки �окращают�� «…» внутри мак�имума. Дл� «Парти� � Maia 1550» ≈ 400, дл� Rodent IV �о �тилем — 460 � �окращением �троки 2. +- Между по�ледней базой р�да и карточкой — не меньше 24 (как между группами �троки заголовка). + +### 2.2. Цвета (�ветла� и тёмна�) + +В�ё из `ui.visuals()` — �воих цветов карточка не заводит: + +| | Светла� | Тёмна� | +|---|---|---| +| фон | `faint_bg_color` (как карточка базы, `lib1400.png`) | то же (`lib1400d.png`) | +| рамка | `selection.bg_fill` (голуба�, как у выбранной базы) | `selection.bg_fill` (тёмно-�ин��) — на тёмном фоне видна, проверить по �нимку | +| «Продолжить» | `primary`: заливка `selection.bg_fill`, тек�т `selection.stroke` | то же | +| тек�т | `text_color` / `weak_text_color` | то же | + +Почему рамка, а не заливка, как на телефоне: на полке компьютера заливкой `selection.bg_fill` уже отмечена выбранна� база (`lib1400.png`, «Роман — партии � компьютером»). Две голубые плашки р�дом читали�ь бы как «выбраны обе». Рамка того же цвета и голуба� кнопка дают то же «�то ждёт ва�», не �пор� � выбором. + +### 2.3. Под�казка (наведение) + +``` +┌──────────────────────────� +│ до�ка 192 × 192 │ по�ледний ход под�вечен, координат нет +│ │ +│ Парти� � Rodent IV 2200 │ +│ �лехин · вы чёрными │ +│ 18-й ход, ваш │ «ваш» / «ход Rodent IV» +│ Отложена 26.10, 21:40 │ дата — врем� запи�и журнала +│ Щелчок или Ctrl+G, Enter │ �лабым +└──────────────────────────┘ +``` + +�а до�ке 64 позицию не разгл�деть, а на компьютере е�ть наведение — под�казка и е�ть «по�мотреть позицию, прежде чем �е�ть за неё». + +### 2.4. × — «не доигрывать» + +- Под�казка ×: «�е доигрывать: парти� запишет�� в «{db}» неоконченной» (`Don't finish it: the game is written to “{db}� unfinished`). +- �ажатие — **без вопро�а** (ничего не тер�ет��): парти� допи�ывает�� в базу игрока � результатом `*` (как `PutAside::discard`), карточка и�чезает, то�т 6 �: «Парти� запи�ана в «{db}» неоконченной, № {n}» (`Game written to “{db}� unfinished, No. {n}`). «Вернуть» нет — как на телефоне: запи�ь удал�ет�� в таблице базы, � отменой (`own-databases.md` §4.3). +- **Запи�ь выключена** («Свои базы → Запи�ывать партии…» �н�т): × удал�ет партию; то�т «Отложенна� парти� удалена» (`The game put aside is deleted`) � кнопкой «Вернуть» и Ctrl+Z, как у удалённой партии �воей базы (`app.rs`, `Toast.undo`). Под�казка ×: «�е доигрывать: парти� будет удалена» (`Don't finish it: the game is deleted`). +- Ошибка запи�и — то�т кра�ным «�е удало�ь запи�ать в «{db}»: {причина}» (е�ть, `player-games.md` §4); карточка **о�таёт��** (парти� не потер�на). + +### 2.5. Клавиатура и до�тупно�ть + +- **Ctrl+G** (как «⚔ Играть») при отложенной партии открывает вопро� §5 � фоку�ом на «Продолжить её»: **Ctrl+G, Enter — продолжить**. Отдельного �очетани� нет: «играть» одно дей�твие, и оно �амо �прашивает, какую партию. +- Tab доходит до «Продолжить» и × карточки в пор�дке полки (по�ле карточек баз). +- AccessKit: «Отложенна� парти� � Maia 1550, вы белыми, 5-й ход, о�тало�ь 4:12. Продолжить» / `Game put aside against Maia 1550, you play white, move 5, 4:12 left. Continue`. + +### 2.6. «Продолжить» + +- Открывает�� �кран игры в позиции по�ле по�леднего хода, ча�ы — §6, �оперник запу�кает�� заново �о в�ей и�торией ходов (как «Перезапу�тить» при �бое, `play-mode.md` §3.8). Пока он грузит�� — «загружает��…» на его карточке ча�ов, ча�ы не идут (е�ть). +- Е�ли на �кране партии была открыта друга� парти� � правками — �начала обычный вопро� «Парти� изменена», как при открытии любой партии. +- **Соперник удалён** (Maia/Rodent нет на ди�ке) — то же предложение �качать, что и в диалоге «Игра � компьютером» (`engine-download.md`); по�ле загрузки парти� продолжает��. Карточка о�таёт��, пока не продолжили или не нажали ×. + +## 3. Уход из партии + +### 3.1. Кнопка «� Отложить» в панели игры + +``` +� ◀ ▶ � │ 🔃 │ ↶ Ход назад │ ⚑ Сдать�� │ ½ Предложить ничью │ � Отложить +``` + +- По�ледней, по�ле разделител�: и�ходы партии (�дать��, ничь�) отдельно от «уйти, не конча�». +- Под�казка: «Отложить партию: ча�ы о�танов�т��, продолжить можно � карточки в библиотеке» (`Put the game aside: the clocks stop; go on from its card in the library`). +- Дей�твие — **без вопро�а** (�вна� кнопка, ничего не тер�ет��): уход в библиотеку, там карточка (§3.4 — куда ведёт уход). +- Видна по�ле первых ходов обеих �торон — там же, где «⚑ Сдать��»; до них на �том ме�те «× Прервать» (откладывать нечего). +- **Узко** (`narrow-windows.md` §4a): группа «↶ ⚑ ½ �» при нехватке ширины �тановит�� значками � подпи��ми в под�казках, как «↶ �» в `play-mode.md` §3.5. �а `play640.png` р�д уже зан�т до кра� — при 640 «�» значком. +- Значок � (U+23F8) — проверить в шрифтах программы; нет — «‖». + +�ужна ли кнопка, е�ли е�ть вопро�: вопро� по�вл�ет�� от «⬅ Библиотека» и Esc, и человек, не нажавший их, не узнает, что партию можно отложить. Кнопка показывает возможно�ть и откладывает в одно нажатие. + +### 3.2. Вопро� «Парти� идёт» + +Сегодн� (`leave1400.png`): «Сдать�� и выйти» / «Продолжить игру» (главна�). �овый: + +``` +┌─ Парти� идёт ──────────────────────────────────────────────────� +│ Maia 1550 · вы белыми · 5+3 · 5-й ход │ �лабым +│ Отложите партию — ча�ы о�танов�т��, а продолжить её можно │ +│ � карточки в библиотеке. Е�ли �дать��, парти� закончит�� │ +│ и запишет�� в «Роман — партии � компьютером». │ +│ │ +│ [Сдать�� и выйти] [Продолжить игру] [▌Отложить�] │ +└─────────────────────────────────────────────────────────────────┘ +``` + +- **Главна� — «Отложить»** (рекомендаци�, вопро� 2): человек нажал «уйти», и безопа�ный уход — отложить; он ничего не �тоит. «Продолжить игру» — отмена вопро�а, Esc. «Сдать�� и выйти» — �лева, отдельно от двух других (разрушительное дей�твие не р�дом � главной). +- **Enter = «Отложить»**. Раньше Enter ничего не нажимал, потому что главна� была «Продолжить игру», а вопро� по�вл�ет�� от Esc (`play-mode.md` §6); теперь главна� безвредна, и Enter может её нажимать. +- Ча�ы �то�т, пока вопро� открыт (е�ть). +- Поводы: «⬅ Библиотека», Esc, Ctrl+W. Закрытие окна — §3.3. +- Без запи�и: втора� фраза «Е�ли �дать��, парти� закончит�� вашей �дачей.» (`If you resign, the game ends.` — �м. §9). + +### 3.3. Закрытие окна программы + +- Во врем� партии окно закрывает�� **без вопро�а**: парти� откладывает��, при �ледующем запу�ке — карточка. Это поведение телефона («назад» откладывает) и че�тное: ничего не тер�ет��. Вопро� «Парти� идёт» при закрытии больше не задаёт��. +- То же при перезапу�ке по�ле обновлени� (`update_ui.rs`, `request_close(QuitApp)`): обновление больше не отнимает у человека партию. +- Вме�те � партией закрывают�� и другие не�охранённые правки — их вопро� «Парти� изменена» прежний (игра — не правка, её вопро� не нужен). + +### 3.4. Куда ведёт уход + +- Обычно — в библиотеку; карточка уже на полке, то�та нет (карточка и е�ть ответ). +- Парти� начата «Играть от�юда» из другой партии (`ReturnToPrevious`, «⬅ К партии …») — уход возвращает к той партии, и полки не видно: то�т «Парти� отложена — продолжить можно в библиотеке» (`Game put aside: go on from the library`), 4 �. +- До первых ходов обеих �торон — как �ейча�: парти� прерывает�� без результата, ни карточки, ни вопро�а. + +## 4. Сбой + +- Журнал пишет�� по�ле каждого хода (е�ть). При �ледующем запу�ке парти�, которую не закончили, **не пишет�� в базу**, а �тановит�� отложенной: та же карточка. То�т «�еоконченна� парти� (программа закрыла�ь) запи�ана в «{db}», № {n}» дл� такой партии больше не показывает��; он о�таёт�� дл� уже законченных партий, которые �бой не дал допи�ать, и дл� журналов �тарых вер�ий. +- Один раз при запу�ке — то�т 6 �: «Программа закрыла�ь по�реди партии — парти� отложена, её можно продолжить» (`The program closed during a game: the game is put aside, you can go on with it`). �ужен, чтобы карточка не по�вила�ь «из ниоткуда»; по�ле обычного отложени� (кнопка, вопро�, закрытие окна) его нет. Разработчику: отличить по признаку в журнале «отложена» (�тавит�� при `put_aside`); у журнала без признака — �бой. +- Ча�ы по�ле �бо� — по по�ледним `[%clk]` (врем�, которое ушло на недоделанный ход, не изве�тно; §6). +- Сбой по�реди «�ачать новую» / × (запи�ь уже �делана) — защищено `before` в журнале (е�ть): парти� не запишет�� дважды. + +## 5. �ова� игра при отложенной партии + +Поводы: «⚔ Играть» и Ctrl+G в библиотеке, «Играть от�юда…» в партии, «↻ Реванш» и «⚔ �ова� игра» на поло�е результата, пу�та� полка «⚔ Играть � компьютером». Вопро� задаёт�� **до** диалога «Игра � компьютером», чтобы человек не на�траивал игру зр�. (Реванш и «�ова� игра» при отложенной партии почти не в�тречают�� — поло�а результата бывает по�ле законченной, а законченна� нова� парти� уже заменила отложенную; правило одно дл� в�ех входов.) + +``` +┌─ Е�ть отложенна� парти� ─────────────────────────────────� +│ ┌────────� Парти� � Maia 1550 │ 14 +│ │ до�ка │ вы белыми · 5-й ход │ 12 �лабым +│ │ 96×96 │ 5+3 · вы 4:12 · Maia 3:58 │ 12 �лабым +│ └────────┘ │ +│ �ова� парти� заменит её; отложенна� запишет�� в │ +│ «Роман — партии � компьютером» неоконченной. │ +│ [�ачать новую] [▌Продолжить её�] │ +└───────────────────────────────────────────────────────────┘ +``` + +- Modal 460, как «Парти� идёт». До�ка 96 — та же отри�овка, что на карточке, �о �тороной игрока �низу; �троки — те же три, что на карточке (§2.1): человек видит, что именно бро�ает. +- **Главна� — «Продолжить её»**, фоку� на ней, Enter. Esc — закрыть вопро�, ничего не делать. +- «�ачать новую» — отложенна� запи�ывает�� в базу неоконченной (`*`), то�т «Парти� запи�ана в «{db}» неоконченной, № {n}», затем то, что человек начинал: диалог «Игра � компьютером» (Играть, Играть от�юда) или �разу парти� (Реванш, �ова� игра). +- Без запи�и: тек�т «�ова� парти� заменит её: отложенна� будет удалена.» (`A new game replaces it: the one put aside is deleted.`). Человек �то подтвердил — «Вернуть» по�ле не нужен. + +## 6. Ча�ы + +- Пока парти� отложена, ча�ы �то�т. Соперник выключен (проце�� завершён), его недоделанный ра�чёт отбра�ывает��. +- При «Продолжить» у каждой �тороны — врем�, о�тавшее�� в момент отложени�. У �тороны, котора� не ходит, �то `[%clk]` её по�леднего хода. У �тороны, котора� ходит, — **врем� на момент отложени�** (рекомендаци�, вопро� 3): е�ли человек думал над ходом 2 минуты и отложил, �ти 2 минуты не возвращают��. Дл� �того журнал хранит одно чи�ло — о�таток ход�щей �тороны — р�дом � PGN. Сейча� разработчик берёт `[%clk]` по�леднего хода каждой �тороны (`resume_play`) — так думанное перед отложением врем� возвращает��. +- По�ле �бо� �того чи�ла нет — берёт�� `[%clk]` (§4). +- Ча�ы ход�щей �тороны идут �разу, как только �кран игры открыл�� и �оперник загружен: позици� человеку уже показана на карточке и в под�казке. +- Добавка за ход («+3») за отложение не начи�л�ет��. + +## 7. Одна отложенна� парти� + +Подтверждаю — как на телефоне: + +- Одна карточка — «одно дело ждёт», полка о�таёт�� полкой баз. �е�колько карточек потребовали бы �пи�ка, �ортировки и выбора — �то уже перепи�ка, а не «отложить партию». +- Во��тановление уже держит одну: �ама� нова� отложена, о�тальные допи�ывают�� неоконченными (`recover_in`). +- Втора� отложенна� может возникнуть только при двух окнах программы. Карточку показывает то окно, которое держит её журнал (замок `PutAside`); второе окно её не видит. Отдельного тек�та не нужно. + +## 8. Узкие окна + +Правила `narrow-windows.md` — без и�ключений; ниже только карточка. + +| Полка | Где карточка | +|---|---| +| полна�, �права в первом р�ду е�ть `карточка + 24` | �права в первом р�ду (§1.1) | +| полна�, ме�та нет (при 640: три базы 3 × 198 = 594 — р�д полон) | **�вой р�д над карточками баз**, прижат вправо; входит в �чёт р�дов правила компактной полки | +| компактна� (много баз, вы�ота `< 600`, до�ка пои�ка при вы�оте `< 760`; `lib640.png`) | **поло�а под �трокой полки**, вы�ота 40 (§8.1) | + +### 8.1. Поло�а в компактной полке + +``` +640 × 480 +[♞ Роман — партии � компьютером ▾] [+ ▾] │ ♟ 📋 │ ⚔ ⚙ +┌──────┬───────────────────────────────────────────────────────────────────────────────� +│до�ка │ Парти� � Maia 1550 · вы белыми · 5-й ход · вы 4:12 · Maia 3:58 [Продолжить] × │ 40 +└──────┴───────────────────────────────────────────────────────────────────────────────┘ +Роман — партии � к… · 3 партии + Парти� � Пои�к Фильтры До�ка +``` + +- Та же рамка, до�ка 40 × 40 вплотную �лева (узор позиции; под�казка §2.3 та же), одна �трока 13 через «·», �окращает�� �права «…», целиком — в под�казке. «Продолжить» и × — как в карточке. +- В компактной полке нет ме�та на 64 по вы�оте и нет пу�того ме�та в �троке: �трока полки при 640 зан�та до «⚙». Поло�а — временна� (пока парти� отложена) и �тоит 40 из 480. + +## 9. Тек�ты (RU → EN) + +| Где | RU | EN | +|---|---|---| +| карточка, �трока 1 | «Парти� � {rival}» | `Game against {rival}` | +| карточка, �трока 2 | «вы белыми» / «вы чёрными» · «{n}-й ход» | `you play white` / `you play black` · `move {n}` | +| карточка, �трока 3 | «{tc} · вы {t1} · {rival_short} {t2}» / «без ча�ов» | `{tc} · you {t1} · {rival_short} {t2}` / `no clock` | +| карточка | «Продолжить» | `Continue` | +| под�казка × | «�е доигрывать: парти� запишет�� в «{db}» неоконченной» | `Don't finish it: the game is written to “{db}� unfinished` | +| под�казка ×, без запи�и | «�е доигрывать: парти� будет удалена» | `Don't finish it: the game is deleted` | +| под�казка карточки | «{n}-й ход, ваш» / «{n}-й ход, ход {rival_short}» · «Отложена {дата}, {врем�}» · «Щелчок или Ctrl+G, Enter» | `move {n}, yours` / `move {n}, {rival_short} to move` · `Put aside {date}, {time}` · `Click, or Ctrl+G, Enter` | +| то�т по�ле × | «Парти� запи�ана в «{db}» неоконченной, № {n}» | `Game written to “{db}� unfinished, No. {n}` | +| то�т по�ле ×, без запи�и | «Отложенна� парти� удалена» · «Вернуть» | `The game put aside is deleted` · `Undo` | +| панель игры | «� Отложить» | `� Put aside` | +| под�казка | «Отложить партию: ча�ы о�танов�т��, продолжить можно � карточки в библиотеке» | `Put the game aside: the clocks stop; go on from its card in the library` | +| вопро� «Парти� идёт», тек�т | «Отложите партию — ча�ы о�танов�т��, а продолжить её можно � карточки в библиотеке. Е�ли �дать��, парти� закончит�� и запишет�� в «{db}».» | `Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends and is written to “{db}�.` | +| то же, без запи�и | «Отложите партию — ча�ы о�танов�т��, а продолжить её можно � карточки в библиотеке. Е�ли �дать��, парти� закончит�� вашей �дачей.» | `Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends.` | +| вопро�, кнопки | «Сдать�� и выйти» (е�ть) · «Продолжить игру» (е�ть) · «Отложить» | `Resign and leave` · `Keep playing` · `Put aside` | +| то�т, уход к прежней партии | «Парти� отложена — продолжить можно в библиотеке» | `Game put aside: go on from the library` | +| то�т по�ле �бо� | «Программа закрыла�ь по�реди партии — парти� отложена, её можно продолжить» | `The program closed during a game: the game is put aside, you can go on with it` | +| новый вопро�, заголовок | «Е�ть отложенна� парти�» | `There is a game put aside` | +| новый вопро�, тек�т | «�ова� парти� заменит её; отложенна� запишет�� в «{db}» неоконченной.» | `A new game replaces it; the one put aside is written to “{db}� unfinished.` | +| то же, без запи�и | «�ова� парти� заменит её: отложенна� будет удалена.» | `A new game replaces it: the one put aside is deleted.` | +| новый вопро�, кнопки | «Продолжить её» · «�ачать новую» | `Continue it` · `Start a new one` | +| AccessKit карточки | «Отложенна� парти� � {rival}, вы белыми, {n}-й ход, о�тало�ь {t1}. Продолжить» | `Game put aside against {rival}, you play white, move {n}, {t1} left. Continue` | + +- `{rival}` — `rival_label`: «Maia 1550», «Rodent IV 2200»; �тиль Rodent — отдельно, первым в �троке 2, переведённый. «Парти� � Maia» не �клон�ет им� («� Maia», «� Rodent IV») — не нужны отдельные �троки Maia/Rodent (`rodent-opponent.md` §7 требует их, только где глагол �огла�ует�� � родом; зде�ь глагола нет). +- `{n}-й ход` — `move_n`, е�ли уже е�ть (телефон: `play_move_n`). + +## 10. Вопро�ы владельцу + +1. **Ме�то карточки на полке.** � — �права в первом р�ду, базы не двигают�� (**рекомендую**); Б — первой �лева, как на телефоне (перва� в �пи�ке), базы �двигают�� вправо, пока парти� отложена. +2. **Уход «⬅ Библиотека» / Esc.** � — вопро� «Парти� идёт» � главной «Отложить» и Enter = «Отложить» (**рекомендую**: Esc нажимают по привычке, вопро� заодно напоминает о �даче); Б — откладывать без вопро�а, как «назад» на телефоне (�дать�� — только кнопкой). Закрытие окна в обоих вариантах — без вопро�а. +3. **Врем� ход�щей �тороны.** � — �колько было в момент отложени�: думанное перед отложением не возвращает�� (**рекомендую**: «ча�ы продолжают � того ме�та, где их о�тавили» буквально); Б — `[%clk]` её по�леднего хода (так �делано �ейча�): отложить — значит вернуть �ебе врем� на �тот ход. +4. **Размер до�ки на карточке.** � — карточка 64, как у баз, до�ка 64 и больша� до�ка в под�казке (**рекомендую**: полка ровна�); Б — карточка 96 � до�кой 96 (позици� видна �разу, но р�д полки выше о�тальных, пока парти� отложена). +5. **× при выключенной запи�и.** � — удалить � «Вернуть» (**рекомендую**, как удаление партии �воей базы); Б — �про�ить «Удалить отложенную партию?». + +## 11. Разработчику (не дизайн, замечено при чтении кода) + +- `begin_play` �оздаёт журнал только при запи�и (`record.map(...)`): при выключенной запи�и партию нельз� отложить. Журнал нужен в�егда; цель запи�и — необ�зательна. +- Признак «отложена» (не �бой) и о�таток времени ход�щей �тороны — в `Entry` (§4, §6). +- `recover_in`: нечитаемый журнал (`None`) удал�ет�� молча — парти� тер�ет�� без �лова. Редко (запи�ь атомарна�), но лучше о�тавить файл и �казать в логе. +- Карточка держит `PutAside` (замок) в�ё врем�, пока показана, — иначе второе окно программы возьмёт ту же партию. + +## 12. Проверки (план, не выполнено) + +Снимки 1400 × 900 �ветла�/тёмна�, 960 × 1040, 640 × 900 (�вой р�д), 640 × 480 (поло�а): карточка Maia без ча�ов, Maia 5+3, Rodent IV �о �тилем (�окращение); под�казка � до�кой; вопро� «Парти� идёт» � трем� кнопками при 640; вопро� «Е�ть отложенна� парти�». Поведение: отложить → закрыть программу → запу�тить → ча�ы те же (по рекомендации §6 — вплоть до �екунды хода); `kill -9` во врем� партии → то�т �бо� и карточка; × → запи�ь `*` один раз; «�ачать новую» → запи�ь `*` и диалог; два окна программы. + +## 13. Решени� и от�туплени� (ревью реализации, 2026-10-26) + +Решено (орке�тратор): §10 вопро�ы 1–4 — вариант � (карточка �права; «Отложить» главна�, Enter = «Отложить», Esc = «Продолжить игру»; ча�ы ход�щей �тороны — на момент отложени�, в журнале; карточка 64, под�казка 192). Закрытие окна — без вопро�а. + +От�туплени�, прин�тые дизайнером: +- **× без запи�и** — вопро� «Удалить отложенную партию?» (кра�на� «Удалить» / «Отмена», Esc — отмена) вме�то удалени� � «Вернуть» (вопро� 5 → Б). Желательно показать в вопро�е ту же �водку � до�кой, что в «Е�ть отложенна� парти�» (`Card::summary`). +- **Под�ветка по�леднего хода** на до�ке карточки (§2.1 говорил «без под�ветки») — о�тавить: на клетках 8 точек помогает узнать позицию. +- **Узка� полка**: карточка �тоит р�дом � базами, пока р�дом помещает�� хот� бы одна; базы перено��т�� в колонку, и при 640 × 900 � трем� базами полка �тановит�� компактной (поло�а §8.1) вме�то «�воего р�да» §8. Прин�то: поло�а дешевле по вы�оте. +- Цифры ча�ов на карточке — обычным шрифтом, не моно (�трока �татична). + +�е прин�то (нужно и�править): �оперник не у�тановлен → только то�т «�качайте его в «Играть»», а «Играть» при отложенной партии �начала задаёт вопро�, и диалог открывает�� лишь по�ле «�ачать новую», котора� отложенную запи�ывает/удал�ет — тупик. �ужен путь к загрузке без потери партии (§2.6). diff --git a/docs/design/engine-download.md b/docs/design/engine-download.md new file mode 100644 index 0000000..14303c1 --- /dev/null +++ b/docs/design/engine-download.md @@ -0,0 +1,444 @@ +# Получение движка: Stockfish по запро�у + +Стату�: проект дизайнера, 2026-10-19, **не утверждён**. О�нова — решение 14 в `../decisions.md` (Stockfish больше не в пакетах, кроме Flatpak и Arch) и требование владельца «про�то, пон�тно, интуитивно пон�тно». Пере�матривает поведение из решени� 10: «в�троенный» Stockfish о�таёт�� только во Flatpak. + +Опирает�� на текущий код: `apps/desktop/src/engines.rs` (`first_run_setup`, `suggestions`, `system_stockfish`), `settings_ui.rs` (вкладка «Движки»), `app.rs::toggle_engine` (�ейча� без движка — то�т и открытие на�троек), `review.rs::dialog` (окно «�нализ партии», `egui::Modal`, 440 pt, кнопки �права налево), `game_view.rs::engine_panel` (переключатель «�нализ: вкл/выкл»). Скриншоты: (�тарые �нимки удалены; актуальные — `docs/screenshots/`). + +Размеры — логиче�кие точки egui; �талон 1920×1080 логиче�ки, минимум 900×600. + +## 0. Главна� задача + +**Человек нажал «анализ» — через минуту анализ идёт. Одно решение («Скачать»), без �лов «UCI», «SHA-256», «бинарник».** + +Принципы: + +1. Предлагаем только в ответ на дей�твие человека (L, «�нализ: выкл», Shift+A / 📈, кнопка в на�тройках). При запу�ке программы — ничего. +2. Одно главное дей�твие в каждом �о�то�нии, одна главна� кнопка. Запа�ные пути видны, но вторичны. +3. По�ле загрузки �разу выполн�ет�� то, ради чего человек пришёл. Отдельного �крана «Готово» � кнопкой «ОК» нет. +4. Загрузку можно убрать � глаз и продолжать работать. Отмен�ет�� она только �вно. +5. Ошибка в�егда говорит, что �лучило�ь, про�тыми �ловами, и что делать: «Повторить» и «Указать файл движка…». Техниче�кие подробно�ти — в �ворачиваемом блоке. + +## 1. Сценарии + +Обозначени�: **О** — окно-предложение (§2), **И** — индикатор загрузки на �кране (§4), «запрошенное дей�твие» — живой анализ или анализ партии, которые запу�т�т�� по�ле у�тановки. + +Общее правило выбора, что показать при попытке анализа без активного движка: + +``` +активный движок е�ть и файл на ме�те → обычный анализ, ничего нового +загрузка уже идёт → �нова показать О в �о�то�нии «Скачивание» +�качанный Stockfish в �пи�ке, файл пропал → О, вариант «Файл удалён» (§2.4) +в �пи�ке пу�то, но найден �и�темный → О, вариант «�айден на компьютере» (§2.3) +�борка Flatpak → О без кнопки «Скачать» (§1.12) +иначе → О, о�новной вариант (§2.2) +``` + +### 1.1. �овичок нажал L (или «�нализ: выкл») + +1. Открывает�� **О** (модальное, §2.1). Фоку� на «Скачать Stockfish». +2. Enter → в том же окне �о�то�ние «Скачивание»: поло�а, «34 из 81 МБ · 42 %». +3. По�ле загрузки — «Проверка и у�тановка…» (обычно 1–2 �, �пиннер). +4. Окно закрывает�� �амо, Stockfish 19 добавлен в �пи�ок и �делан активным, **живой анализ включает��**, то�т «Stockfish у�тановлен — анализ включён». +5. Е�ли за �то врем� человек ушёл к другой партии — анализ включает�� на текущей позиции текущей партии (анализ в�егда прив�зан к кур�ору). Е�ли ушёл в библиотеку — анализ не включает�� (на �кране нечего анализировать), то�т «Stockfish у�тановлен». + +### 1.2. �ажал «�нализ партии» (Shift+A или 📈) + +�нализ партии уже начинает�� � окна запу�ка (каче�тво, потоки, пам�ть, оценка времени). Второе окно поверх него не нужно: **предложение в�траивает�� в окно «�нализ партии»**. + +1. Открывает�� обычное окно «�нализ партии». Вме�то выпадающего �пи�ка движка — �трока «Движок: нет. Stockfish будет �качан (81 МБ)». Ползунки каче�тва/потоков/пам�ти работают как обычно, оценка времени — по �коро�ти по умолчанию. +2. Главна� кнопка вме�то «�нализировать» — **«Скачать и анализировать»**. Слева от «Отмена» — ��ылка «Указать файл движка…». +3. �ажатие → то же окно переходит в �о�то�ние «Скачивание» (та же поло�а, что в §2.5) � подпи�ью «�нализ партии начнёт�� �ам по�ле загрузки». +4. По�ле у�тановки окно закрывает��, анализ партии �тартует � выбранными на�тройками (как по�ле «�нализировать»: живой анализ на паузе, открывает�� вкладка отчёта). +5. Е�ли загрузку �крыли и за �то врем� открыли другую партию — анализ партии **не** �тартует (он т�жёлый и мен�ет боковую вкладку), то�т «Stockfish у�тановлен. �нализ партии — Shift+A». + +### 1.3. Пришёл в «�а�тройки → Движки» �ам + +Кнопка «Скачать Stockfish 19 · 81 МБ» над кнопкой «Указать файл движка…» (§3). Прогре�� — пр�мо на ме�те кнопки. Запрошенного дей�тви� нет: по�ле у�тановки движок по�вл�ет�� в �пи�ке; активным он �тановит��, только е�ли активного не было. То�т не нужен — результат виден в �амом окне. + +### 1.4. �ет интернета + +Ошибка обнаруживает�� за �екунды (таймаут �оединени� 15 �). **О** в �о�то�нии «Ошибка: нет �оединени�» (§2.7). Кнопки: «Указать файл движка…» · «Закрыть» · **«Повторить»**. �а Linux под тек�том под�казка «Или у�тановите пакет stockfish из менеджера пакетов — программа найдёт его �ама». + +### 1.5. Загрузка оборвала�ь + +Данных нет дольше 30 � или �оединение разорвано. Со�то�ние «Ошибка: загрузка прервала�ь на 34 из 81 МБ». «Повторить» начинает заново (докачка — открытый вопро� В4). �едокачанный файл удал�ет�� �разу. + +### 1.6. Проверка не прошла + +Файл удал�ет�� до ра�паковки и до любого запу�ка. Тек�т без «SHA-256»: «Скачанный файл не прошёл проверку и удалён. Скорее в�его, он повредил�� при загрузке». «Повторить» — главна� кнопка. В «Подробно�т�х» — ожидаема� и полученна� �умма, адре�, кнопка «Копировать» (дл� �ообщени� об ошибке). Е�ли проверка не прошла дважды подр�д — дополнительна� �трока «Е�ли повторит�� — �ообщите нам: возможно, файл на �ервере изменил��». + +### 1.7. �ет ме�та / нет прав на запи�ь + +- **Ме�то** провер�ет�� до начала загрузки: нужно ≈ 185 МБ на врем� у�тановки (архив 81 + ра�пакованный 103), по�ле у�тановки о�таёт�� 103 МБ. Ошибка �разу, без загрузки: «�едо�таточно ме�та на ди�ке: нужно 185 МБ, �вободно 40 МБ». Кнопки: «Указать файл движка…» · «Закрыть» · «Повторить» (по�ле о�вобождени� ме�та). +- **Права**: «�ет до�тупа на запи�ь в папку». Путь — второй �трокой мелким шрифтом, � кнопкой «Копировать». Кнопки те же. Каталог �оздаёт�� заранее; ошибка прав возникает до загрузки, е�ли каталог не �оздаёт�� или в него нельз� запи�ать пробный файл. +- Ме�то кончило�ь во врем� ра�паковки — �то та же ошибка «�едо�таточно ме�та», недора�пакованное удал�ет��. + +### 1.8. Закрыл окно во врем� загрузки + +Кнопка «Скрыть», Esc и щелчок мимо модального окна **�крывают окно, загрузка продолжает��**. По�вл�ет�� **И** (§4). Щелчок по И �нова открывает окно. Запрошенное дей�твие �охран�ет�� (� оговоркой §1.2 п. 5). Отменить — только кнопкой «Отменить загрузку» (в окне, у И — ×, в на�тройках). + +Е�ли загрузку �крыли и она завершила�ь ошибкой: И �тановит�� «⚠ Stockfish не �качан», то�т � тем же тек�том; щелчок по И открывает окно в �о�то�нии ошибки. Само окно не выпрыгивает поверх работы. + +### 1.9. Программу закрыли во врем� загрузки + +- Подтверждени� при закрытии **нет** (потер� — только врем� загрузки; �м. открытый вопро� В5). Загрузка прерывает��, временные файлы (`*.part`, недора�пакованный каталог) удал�ют�� при выходе. +- Е�ли удалить не у�пели (аварийный выход) — при �ледующем запу�ке о�татки молча удал�ют��. Загрузка �ама **не** возобновл�ет��, окно не показывает��, запрошенное дей�твие забыто. Человек нажмёт L ещё раз и увидит обычное предложение. + +### 1.10. Движок был �качан, но файл удалён + +В на�тройках Stockfish 19 о�таёт�� в �пи�ке. При L / Shift+A — **О** в варианте «Stockfish не найден» (§2.4): «Файл Stockfish пропал � ди�ка. Скачать заново? 81 МБ». В на�тройках �трока движка помечена «⚠ Файл не найден» и кнопкой «Скачать заново» (§3.4). Загрузка во��танавливает ту же запи�ь (без дубл�), активно�ть �охран�ет��. + +### 1.11. Е�ть �и�темный stockfish + +- **Первый запу�к**: `first_run_setup` уже добавл�ет �и�темный Stockfish активным → анализ работает �разу, **никаких предложений**. Это о�новной путь дл� Arch. +- **Спи�ок пу�т, но �и�темный найден** (человек �ам удалил в�е движки): **О** в варианте §2.3, главна� кнопка — «И�пользовать у�тановленный», �качивание о�таёт�� второй кнопкой. Мгновенно и без �ети — правильный выбор по умолчанию. +- **В на�тройках**: блок «Скачать Stockfish 19» о�таёт�� (ди�трибутивна� вер�и� может быть �тарее), но в компактном виде — одна �трока-кнопка без по��нительного абзаца (§3.1). + +### 1.12. Flatpak и Arch + +- **Flatpak**: в�троенный Stockfish е�ть, `first_run_setup` его добавл�ет — ничего не показывает��. Кнопка «Скачать Stockfish» в на�тройках **�крыта** (Flathub против �качивани� и�полн�емых файлов). Е�ли человек удалил в�троенный из �пи�ка — он предлагает�� в «�айдено на �том компьютере», как �ейча�; **О** в �том �лучае — вариант без загрузки: «Вернуть в�троенный Stockfish» · «Указать файл движка…» · «Позже». +- **Arch**: `stockfish` — зави�имо�ть пакета, работает §1.11. + +### 1.13. Прочие �лучаи + +- **Сервер GitHub отказал** (404, 403, 5xx): «Сервер не отдал файл (ошибка 503). Попробуйте позже». Дей�тви� те же. +- **Скачан, но не запу�кает��** (по�ле у�тановки делает�� проверочный запу�к `uci` → `uciok`, как при добавлении движка из файла): «Stockfish �качан, но не запу�кает�� на �том компьютере». Кнопки: «Указать файл движка…» · **«Закрыть»**; «Повторить» нет — повтор да�т то же. Скачанное удал�ет��. Подробно�ти — вывод/код выхода. �а macOS без подпи�и — отдельный тек�т, е�ли �то причина (вопро� В7). +- **Два окна программы** одновременно: загрузка в одном; второе при L видит запи�ь-блокировку и показывает «Stockfish уже �качивает�� в другом окне ChessPenguin». (Деталь дл� разработчика: lock-файл в каталоге движков.) +- **Загрузка идёт, нажали Shift+A** (начинали � L): открывает�� окно «�нализ партии» в �о�то�нии «Скачивание» � подпи�ью «�нализ партии начнёт�� �ам по�ле загрузки». Запрошенное дей�твие одно — по�леднее. + +## 2. Окно-предложение + +### 2.1. Модальное или нет — рекомендаци�: модальное (`egui::Modal`) + +- Его вызывает �вное дей�твие, ответ нужен �разу; без движка �тот запро� в�ё равно не выполнить. +- Так уже �делано окно «�нализ партии» — одинаковое поведение, Esc/щелчок мимо закрывает. +- Модально�ть �нимает��, как только начинает�� долгое ожидание: «Скрыть» (и Esc) убирают окно, загрузка идёт в фоне, работа � партией не блокирует��. Модальным о�таёт�� только момент решени�. + +Размер: ширина 440 pt (как «�нализ партии»), вы�ота по �одержимому. Заголовок — `heading`, о�новной тек�т — обычный, второ�тепенный — `weak`/`small`. Кнопки �права налево: главна� — крайн�� права�, `strong`, 16 pt (как «�нализировать»). Запа�ной путь «Указать файл движка…» — �лева, обычна� кнопка. + +### 2.2. О�новной вариант (L, движков нет) + +``` +┌──────────────────────────────────────────────────� +│ Дл� анализа нужен движок │ +│ │ +│ Скачать Stockfish — �амый �ильный бе�платный │ +│ шахматный движок? �нализ включит�� �ам, как │ +│ только загрузка закончит��. │ +│ │ +│ 81 МБ · � официальной �траницы Stockfish │ weak +│ У�танавливает�� только дл� ва�, ⓘ │ weak, ⓘ = путь в под�казке +│ │ +│ [Указать файл движка…] [Позже] [Скачать Stockfish] │ +└──────────────────────────────────────────────────┘ +``` + +| | Ру��кий | English | +|---|---|---| +| Заголовок | Дл� анализа нужен движок | Analysis needs a chess engine | +| Тек�т | Скачать Stockfish — �амый �ильный бе�платный шахматный движок? �нализ включит�� �ам, как только загрузка закончит��. | Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes. | +| Строка 1 | 81 МБ · � официальной �траницы Stockfish | 81 MB · from the official Stockfish page | +| Строка 2 | У�танавливает�� только дл� ва� | Installed for your account only | +| Под�казка ⓘ | Папка: `~/.local/share/chesspenguin/engines/stockfish-19`. Её можно удалить в «�а�тройки → Движки». | Folder: `…`. You can remove it in Settings → Engines. | +| Кнопки | Указать файл движка… · Позже · **Скачать Stockfish** | Choose engine file… · Later · **Download Stockfish** | + +Размер в тек�те берёт�� из закреплённого опи�ани� �борки дл� текущей платформы (не кон�танта 81). Округление до целых МБ. + +«Позже» закрывает окно и ничего не запоминает: в �ледующий раз при L окно по�вит�� �нова (оно по�вл�ет�� только по дей�твию, по�тому не надоедает). «Указать файл движка…» открывает тот же выбор файла, что «+ Добавить движок…»; по�ле у�пешной проверки файла запрошенное дей�твие тоже запу�кает�� �амо. + +Под�казка о папке (ⓘ — `on_hover_text`) по платформам (каталог данных `directories::ProjectDirs`): +- Linux: `~/.local/share/chesspenguin/engines/stockfish-19/` +- Windows: `%LOCALAPPDATA%\vrubelroman\ChessPenguin\data\engines\stockfish-19\` (рекомендую local, не roaming: 100 МБ не должны �инхронизировать�� в профиле) +- macOS: `~/Library/Application Support/io.github.vrubelroman.ChessPenguin/engines/stockfish-19/` + +### 2.3. Вариант «�айден на компьютере» + +``` +┌──────────────────────────────────────────────────� +│ Дл� анализа нужен движок │ +│ │ +│ �а компьютере уже у�тановлен Stockfish. │ +│ /usr/bin/stockfish │ small weak +│ │ +│ Или �качайте официальную �борку Stockfish 19 │ weak +│ (81 МБ). │ +│ │ +│ [Указать файл…] [Скачать] [Позже] [И�пользовать его] │ +└──────────────────────────────────────────────────┘ +``` + +- ru: «�а компьютере уже у�тановлен Stockfish.» / «Или �качайте официальную �борку Stockfish 19 (81 МБ).» Кнопки: Указать файл движка… · Скачать · Позже · **И�пользовать его**. +- en: “Stockfish is already installed on this computer.� / “Or download the official Stockfish 19 build (81 MB).� Buttons: Choose engine file… · Download · Later · **Use it**. + +При нехватке ширины (длинные переводы) кнопки перено��т�� в две �троки: перва� — главна� и «Позже», втора� — запа�ные (`horizontal_wrapped` не подходит дл� пор�дка �права налево; делать две �вные �троки при `available_width < нужной`). + +### 2.4. Вариант «Файл удалён» + +``` +┌──────────────────────────────────────────────────� +│ Stockfish не найден │ +│ │ +│ Файл Stockfish пропал � ди�ка. Скачать его │ +│ заново? 81 МБ. │ +│ │ +│ [Указать файл движка…] [Позже] [Скачать заново] │ +└──────────────────────────────────────────────────┘ +``` + +- ru: заголовок «Stockfish не найден»; тек�т «Файл Stockfish пропал � ди�ка. Скачать его заново? 81 МБ.»; кнопки Указать файл движка… · Позже · **Скачать заново**. +- en: “Stockfish not found�; “The Stockfish file is missing from the disk. Download it again? 81 MB.�; Choose engine file… · Later · **Download again**. + +### 2.5. Скачивание + +``` +┌──────────────────────────────────────────────────� +│ Скачивание Stockfish │ +│ │ +│ [██████████████░░░░░░░░░░░░░░░░░░] 42 % │ ProgressBar, тек�т �права +│ 34 из 81 МБ · о�тало�ь около 20 � │ weak +│ │ +│ �нализ включит�� �ам по�ле загрузки. │ weak +│ │ +│ [Отменить загрузку] [Скрыть] │ +└──────────────────────────────────────────────────┘ +``` + +| | Ру��кий | English | +|---|---|---| +| Заголовок | Скачивание Stockfish | Downloading Stockfish | +| Прогре�� | 34 из 81 МБ · о�тало�ь около 20 � | 34 of 81 MB · about 20 s left | +| До первых данных | Подключение… (�пиннер, поло�а неопределённа�) | Connecting… | +| Подпи�ь (L) | �нализ включит�� �ам по�ле загрузки. | Analysis will start by itself when the download finishes. | +| Подпи�ь (Shift+A) | �нализ партии начнёт�� �ам по�ле загрузки. | Game analysis will start by itself when the download finishes. | +| Подпи�ь (на�тройки) | — | — | +| Кнопки | Отменить загрузку · **Скрыть** | Cancel download · **Hide** | + +- «О�тало�ь» показывать по�ле 3 � загрузки (�коро�ть �глажена), раньше — только МБ. +- Поло�а — `egui::ProgressBar` на в�ю ширину, процент в тек�те поло�ы; МБ — отдельной �трокой (цифры не только цветом). +- «Отменить загрузку» — �лева, обычна� кнопка, не главна�: отмена не должна �лучать�� от Enter. Отмена → окно закрывает��, файлы удалены, то�т «Загрузка отменена». Подтверждени� нет — повтор �тоит одной кнопки. +- Обновление: `ctx.request_repaint_after(100 ms)` из фоновой задачи, не каждый кадр. + +### 2.6. Проверка и у�тановка + +``` +┌──────────────────────────────────────────────────� +│ Скачивание Stockfish │ +│ │ +│ [████████████████████████████████] 100 % │ +│ ◌ Проверка и у�тановка… │ spinner +│ │ +│ [Скрыть] │ +└──────────────────────────────────────────────────┘ +``` + +ru «Проверка и у�тановка…» / en “Checking and installing…�. Отмены нет (�екунды, и прерывание о�тавило бы полуу�тановленный каталог). + +### 2.7. У�пех + +Отдельного �о�то�ни� в окне нет. Окно закрывает��, затем: + +| Контек�т | Что прои�ходит | То�т ru / en | +|---|---|---| +| L на �кране партии | живой анализ включён | Stockfish у�тановлен — анализ включён / Stockfish installed — analysis is on | +| Shift+A, та же парти� | анализ партии запущен, вкладка отчёта | Stockfish у�тановлен — анализ партии запущен / Stockfish installed — game analysis started | +| Shift+A, парти� �менила�ь | ничего | Stockfish у�тановлен. �нализ партии — Shift+A / Stockfish installed. Game analysis: Shift+A | +| Человек в библиотеке | ничего | Stockfish у�тановлен / Stockfish installed | +| Из на�троек | �трока в �пи�ке (§3.3) | — | + +### 2.8. Ошибки + +Общий вид: + +``` +┌──────────────────────────────────────────────────� +│ ⚠ Stockfish не �качан │ warn_fg_color + значок + тек�т +│ │ +│ �е удало�ь подключить��. Проверьте интернет │ +│ и попробуйте ещё раз. │ +│ Или у�тановите пакет stockfish из менеджера │ weak, только Linux и только «нет �ети» +│ пакетов — программа найдёт его �ама. │ +│ │ +│ ▸ Подробно�ти │ CollapsingHeader, �вёрнут +│ │ +│ [Указать файл движка…] [Закрыть] [Повторить] │ +└──────────────────────────────────────────────────┘ +``` + +Развёрнутые подробно�ти — моноширинный `small`, выдел�емый тек�т + «Копировать»: адре�, ошибка �и�темы/HTTP-код, дл� проверки — ожидаема� и полученна� SHA-256. + +| Ошибка | Ру��кий | English | Главна� кнопка | +|---|---|---|---| +| Заголовок (в�е) | ⚠ Stockfish не �качан | ⚠ Stockfish wasn't downloaded | — | +| �ет �ети | �е удало�ь подключить��. Проверьте интернет и попробуйте ещё раз. | Couldn't connect. Check your internet connection and try again. | Повторить / Retry | +| Обрыв | Загрузка прервала�ь на 34 из 81 МБ. Проверьте интернет и попробуйте ещё раз. | The download stopped at 34 of 81 MB. Check your connection and try again. | Повторить | +| Проверка | Скачанный файл не прошёл проверку и удалён. Скорее в�его, он повредил�� при загрузке. | The downloaded file failed the integrity check and was deleted. It was most likely damaged during the download. | Повторить | +| Проверка, 2-й раз (+�трока) | Е�ли �то повторит�� — �ообщите нам: возможно, файл на �ервере изменил��. | If this keeps happening, please let us know: the file on the server may have changed. | Повторить | +| Ме�то | �едо�таточно ме�та на ди�ке: нужно 185 МБ, �вободно 40 МБ. | Not enough disk space: 185 MB needed, 40 MB free. | Повторить | +| Права | �ет до�тупа на запи�ь в папку: (путь второй �трокой) | Can't write to the folder: (path below) | Повторить | +| Сервер | Сервер не отдал файл (ошибка 503). Попробуйте позже. | The server didn't provide the file (error 503). Please try again later. | Повторить | +| �е запу�кает�� | Stockfish �качан, но не запу�кает�� на �том компьютере. | Stockfish was downloaded but doesn't run on this computer. | Закрыть / Close (Повторить нет) | + +Кнопки ошибки: «Указать файл движка…» (�лева) · «Закрыть» · **«Повторить»**. Е�ли найден �и�темный Stockfish — добавл�ет�� «И�пользовать у�тановленный» перед «Закрыть». «Повторить» — �разу �нова «Скачивание», без возврата к предложению. + +### 2.9. Окно «�нализ партии» без движка (§1.2) + +``` +┌──────────────────────────────────────────────────� +│ �нализ партии │ +│ Движок оценит каждую позицию о�новной линии. │ weak (как �ейча�) +│ Сама парти� не изменит��. │ +│ │ +│ Движок нет — Stockfish будет �качан (81 МБ) ⓘ │ вме�то ComboBox +│ Каче�тво [────�────] Хорошее · 2 млн узлов │ +│ Потоки [──�──────] 4 / 24 │ +│ Пам�ть [───�─────] 256 МБ │ +│ 61 позици�, около 3 мин │ +│ │ +│ [Указать файл движка…] [Отмена] [Скачать и анализировать] │ +└──────────────────────────────────────────────────┘ +``` + +ru «нет — Stockfish будет �качан (81 МБ)», кнопка **«Скачать и анализировать»**; en “none — Stockfish will be downloaded (81 MB)�, **“Download and analyse�**. Вме�то текущего «Сначала добавьте движок» � недо�тупной кнопкой. + +По�ле нажати� �одержимое окна (заголовок «�нализ партии» �охран�ет��) замен�ет�� блоком §2.5 � подпи�ью «�нализ партии начнёт�� �ам по�ле загрузки»; ошибки — §2.8 в �том же окне, «Закрыть» возвращает к на�тройкам анализа (ползунки), а не закрывает окно. + +Е�ли е�ть �и�темный Stockfish (§1.11, �пи�ок пу�т) — �трока движка «нет» � кнопкой «И�пользовать у�тановленный Stockfish», главна� кнопка о�таёт�� «�нализировать» (недо�тупна до выбора) — �юда �качивание не нав�зываем. + +## 3. Вкладка «Движки» + +Текуща� �труктура �охран�ет��: по��нение → �пи�ок движков (рамки � радиокнопкой, именем, 🗑, путём) → «�айдено на �том компьютере» → кнопки. Добавл�ет�� блок Stockfish. + +### 3.1. Спи�ок пу�т (нова� у�тановка) + +Блок «пу�того �о�то�ни�» **над** ме�том �пи�ка — первое, что видно на вкладке: + +``` +Движки +UCI-движки. �ктивный и�пользует�� дл� анализа… weak (как �ейча�) + +┌ рамка group ───────────────────────────────────────� +│ Движок ещё не выбран strong │ +│ Дл� анализа нужен шахматный движок. Stockfish — │ +│ �амый �ильный бе�платный, загрузка 81 МБ. │ +│ │ +│ [⬇ Скачать Stockfish 19] [Указать файл движка…] │ +└────────────────────────────────────────────────────┘ +�айдено на �том компьютере: (е�ли е�ть) + Stockfish (�и�темный) [Добавить] +``` + +ru «Движок ещё не выбран» / «Дл� анализа нужен шахматный движок. Stockfish — �амый �ильный бе�платный, загрузка 81 МБ.»; en “No engine yet� / “Analysis needs a chess engine. Stockfish is the strongest free one, an 81 MB download.� Кнопки: **⬇ Скачать Stockfish 19** / **⬇ Download Stockfish 19**, Указать файл движка… / Choose engine file…. + +Когда �пи�ок не пу�т, а �качанного Stockfish нет — компактно, одной �трокой внизу р�дом � «Указать файл движка…»: + +``` +[⬇ Скачать Stockfish 19 · 81 МБ] [+ Указать файл движка…] +``` + +Предлагаю переименовать «+ Добавить движок…» в «+ Указать файл движка…» — одно название во в�ех окнах (вопро� В6). + +### 3.2. Загрузка в на�тройках + +�а ме�те кнопки «Скачать» (в рамке пу�того �о�то�ни� или в нижней �троке): + +``` +Скачивание Stockfish 19 [███████░░░░░░░░] 42 % 34 из 81 МБ [✕] +``` + +`ProgressBar` 160 pt, ✕ — «Отменить загрузку» в под�казке. Ошибка — на том же ме�те одной �трокой `⚠ �е удало�ь подключить�� [Повторить]`, полный тек�т и «Подробно�ти» — в под�казке и по «ⓘ». Е�ли загрузка начала�ь из L/Shift+A — в на�тройках отображает�� та же загрузка (одна задача на приложение). + +### 3.3. Скачанный движок в �пи�ке + +Обычна� рамка движка, отличие — втора� �трока: + +``` +┌───────────────────────────────────────────────────� +│ (�) [Stockfish 19 ] 🗑 │ +│ Скачан ChessPenguin · 103 МБ ⓘ │ small weak; ⓘ — полный путь +└───────────────────────────────────────────────────┘ +``` + +- Им� по умолчанию «Stockfish 19» (не «в�троенный»), редактирует�� как у о�тальных. +- ru «Скачан ChessPenguin · 103 МБ», en “Downloaded by ChessPenguin · 103 MB�. Путь в под�казке ⓘ (по щелчку — копировать, то�т «Путь �копирован»). Техниче�ки — признак `downloaded` в `EngineConfig`, по аналогии � `builtin`; путь вычи�л�ет�� от каталога данных при запу�ке. +- Блок «Скачать Stockfish 19» не показывает��, пока �качанна� копи� е�ть. + +### 3.4. Файл пропал + +``` +│ ( ) [Stockfish 19 ] 🗑 │ +│ ⚠ Файл не найден [Скачать заново] │ warn_fg_color + значок +``` + +ru «⚠ Файл не найден» · «Скачать заново»; en “⚠ File not found� · “Download again�. Радиокнопка о�таёт�� выбираемой (выбор �охран�ет��), анализ при L ведёт в §2.4. + +### 3.5. Удаление �качанного + +🗑 у �качанного движка удал�ет **и из �пи�ка, и � ди�ка** (иначе 103 МБ о�тают�� му�ором, которого человек не видит). Подтверждение — маленький popup под 🗑 (`egui::Popup`/`menu`), не модальное окно: + +``` + ┌──────────────────────────────────� + │ Удалить Stockfish 19? │ + │ О�вободит�� 103 МБ. Скачать │ + │ �нова можно в любой момент. │ + │ [Отмена] [Удалить] │ + └──────────────────────────────────┘ +``` + +ru «Удалить Stockfish 19?» / «О�вободит�� 103 МБ. Скачать �нова можно в любой момент.» / Отмена · **Удалить**; en “Remove Stockfish 19?� / “This frees 103 MB. You can download it again at any time.� / Cancel · **Remove**. Е�ли идёт анализ �тим движком — �начала о�тановить (как �ейча� при удалении активного). По�ле удалени� по�вл�ет�� кнопка «Скачать Stockfish 19». Дл� прочих движков 🗑 по-прежнему «Убрать из �пи�ка» без подтверждени� — файлы человека мы не трогаем. + +## 4. Экран во врем� �крытой загрузки + +Индикатор **И** — там, где человек ждёт анализ: в шапке панели анализа **вме�то** переключател� «�нализ: выкл». + +``` + ┌ панель анализа ──────────────────────────────────� + │ [⬇ Stockfish 42 % ▓▓▓▓░░░░] ✕ ⚙ │ + │ │ +``` + +- Кнопка-индикатор: `ProgressBar` 110×20 pt � тек�том «⬇ Stockfish 42 %»; щелчок открывает окно §2.5; под�казка «Скачивание Stockfish: 34 из 81 МБ. Щёлкните, чтобы открыть». ✕ — «Отменить загрузку». +- L в �то врем� открывает то же окно (не запу�кает вторую загрузку). +- Е�ли запрошен анализ партии — кнопка 📈 на панели ин�трументов показывает тот же прогре�� (у неё уже е�ть вид «прогре�� + ✕» дл� идущего анализа партии; переи�пользовать) � под�казкой «Скачивание Stockfish — анализ партии начнёт�� �ам». +- Ошибка в фоне: индикатор �тановит�� `⚠ Stockfish не �качан` (warn-цвет + значок), щелчок — окно � ошибкой; плю� то�т. Индикатор не и�чезает �ам, пока его не откроют или не нажмут ✕. +- В **библиотеке** панели анализа нет — тот же индикатор маленьким чипом в верхней �троке �лева от «⚙ �а�тройки». Решение «показывать ли в библиотеке» — вопро� В3. +- Окно «�а�тройки → Движки», е�ли открыто, показывает §3.2. + +## 5. Клавиатура, фоку�, до�тупно�ть + +| Со�то�ние | Enter | Esc / щелчок мимо | �ачальный фоку� | +|---|---|---|---| +| Предложение (§2.2–2.4) | главна� кнопка (Скачать / И�пользовать его / Скачать заново) | Позже | главна� кнопка | +| Скачивание, у�тановка | ничего | Скрыть (загрузка продолжает��) | «Скрыть» | +| Ошибка | Повторить (у «не запу�кает��» — Закрыть) | Закрыть | главна� кнопка | +| �нализ партии без движка | Скачать и анализировать | Отмена | главна� кнопка | +| Popup удалени� | Удалить | Отмена | «Отмена» (удаление — разрушающее) | + +- Enter — через `consume_key` в окне, только е�ли фоку� не в другом виджете ввода; Space нажимает кнопку в фоку�е (�тандарт egui). +- Пор�док Tab — **визуальный �лева направо**: при ра�кладке `right_to_left` egui �оздаёт виджеты (и Tab-пор�док) �права налево. Строку кнопок �обирать �лева направо � ра�поркой `ui.add_space(ui.available_width() - ширина_кнопок)`, или о�тавить right_to_left, но тогда Tab идёт «главна� → Позже → Указать файл», что тоже приемлемо. Решение за разработчиком, главное — главна� кнопка получает фоку� первой (`request_focus` в первом кадре). +- Гор�чие клавиши �крана партии (�трелки, L) во врем� модального окна не �рабатывают; по�ле «Скрыть» — �нова работают. +- До�тупно�ть: у egui е�ть AccessKit — у в�ех кнопок тек�товые подпи�и (у ✕ и ⓘ — `on_hover_text` и accessible label), прогре�� озвучивает�� тек�том «42 %, 34 из 81 МБ», а не только поло�ой. Ошибки — значок ⚠ + �лово «не �качан», не только цвет. Контра�т `warn_fg_color` проверить в �ветлой теме. +- Малое окно (900×600) и HiDPI: модальное окно 440 pt помещает��; длинный англий�кий тек�т перено�ит�� (`ui.label` � шириной окна), кнопки при нехватке ширины — в две �троки (§2.3). + +## 6. Открытые вопро�ы владельцу + +| # | Вопро� | Рекомендаци� | +|---|---|---| +| В1 | Модальное окно предложени� или плашка в панели анализа без окна? | Модальное в момент решени�, «Скрыть» на врем� загрузки (§2.1). Плашка проще пропу�тить, а человек �вно попро�ил анализ. | +| В2 | Shift+A без движка: в�троить загрузку в окно «�нализ партии» или �начала отдельное предложение, потом окно анализа? | В�троить (§2.9): одно окно, на�тройки выбирают�� заранее, анализ �тартует �ам. | +| В3 | Показывать индикатор �крытой загрузки в библиотеке? | Да, маленький чип у «⚙ �а�тройки» — иначе загрузка «тер�ет��» при переходе в библиотеку. | +| В4 | Докачивать по�ле обрыва (HTTP Range) или начинать заново? | В первой вер�ии заново: 81 МБ, проще и надёжнее; докачку — е�ли будут жалобы � медленных �етей. | +| В5 | Спрашивать подтверждение при закрытии программы во врем� загрузки? | �ет: потер� — только врем� загрузки; лишний вопро� мешает чаще, чем помогает. | +| В6 | Переименовать «+ Добавить движок…» в «+ Указать файл движка…»? | Да — одно название в на�тройках, предложении и ошибках. | +| В7 | macOS без подпи�и: �качанный Stockfish может блокировать�� Gatekeeper. �ужен отдельный тек�т ошибки? | Да, е�ли проверка покажет блокировку: «macOS не разрешила запу�к Stockfish» + ин�трукци�. Проверить на реальной �борке до выпу�ка. | +| В8 | Предлагать �качивание, когда в �и�теме уже е�ть Stockfish (Arch и др.)? | В окнах — нет, главна� кнопка «И�пользовать его»; в на�тройках — компактна� кнопка «Скачать Stockfish 19» о�таёт�� (вер�и� может быть новее ди�трибутивной). | +| В9 | Когда программа перейдёт на Stockfish 20 — предлагать обновление �качанной копии? | �е автоматиче�ки; в на�тройках �трока «До�тупна вер�и� 20 · [Обновить]». Вне первой вер�ии �той функции. | +| В10 | Прок�и/корпоративные �ети. | Учитывать �и�темные переменные `HTTPS_PROXY`; отдельной на�тройки прок�и не делать, при ошибке — «Указать файл движка…». | + +## 7. Проверки дл� те�тировщика (план, не выполнено) + +- L без движка → Скачать → живой анализ включил�� �ам; Shift+A → анализ партии �тартовал � выбранным каче�твом. +- Отключить �еть до и во врем� загрузки; ограничить �коро�ть; подменить файл (неверна� �умма) — файл удалён, не запу�кал��. +- Заполненный ди�к / каталог без прав; закрытие окна (Esc) и программы во врем� загрузки; о�татки `*.part` удалены при �ледующем запу�ке, окно не по�вл�ет��. +- Удалить файл �качанного движка → §2.4 и §3.4; удалить через 🗑 → каталог и�чез, кнопка «Скачать» вернула�ь. +- Си�темный stockfish в PATH при пу�том �пи�ке → §2.3; Flatpak → кнопки «Скачать» нет нигде. +- Клавиатура: Enter/Esc/Tab во в�ех �о�то�ни�х; ру��кий и англий�кий интерфей� при ширине окна 900. diff --git a/docs/design/large-databases.md b/docs/design/large-databases.md new file mode 100644 index 0000000..1298654 --- /dev/null +++ b/docs/design/large-databases.md @@ -0,0 +1,456 @@ +# Библиотека: большие базы ChessBase и панель фильтров + +Стату�: проект дизайнера, 2026-10-19. �е утверждено; решени� владельца продукта, на которые опирает�� документ: большие базы открывают�� через «+ Добавить базу», �права от таблицы — панель фильтров, фильтр мен�ет таблицу �разу. Пои�к по позиции — не в �той вер�ии, но ме�то под него заложено (раздел 2.4). + +Эталонна� нагрузка — Mega Database 2026: 11 741 260 запи�ей, 479 ты�. игроков, 109 ты�. турниров, 1 823 тек�товые главы. + +**Обновление 2026-10-24 (§2.2, §2.6, §3.1).** Сетка панели фильтров: колонка подпи�ей и полей группы «Парти�», по�то�нное ме�то под `×`, «=» в �троке подпи�и, пор�док «Годы → Эло → Ходы → ECO → Результат»; панель мен�ет ширину только перета�киванием. + +**Обновление 2026-10-23 (раздел 9).** Владелец решил: у PGN те же фильтры и пои�к по позиции, что у ChessBase, «идентично как � базами от chessbase», — один �кран дл� в�ех баз. Бы�трый тек�товый пои�к PGN о�таёт�� и �тановит�� ча�тью �того �крана у в�ех баз. Деление на «малый» и «большой» режим (раздел 0) больше не определ�ет �кран: оно о�таёт�� только техниче�ким (как база читает�� — по индек�у `.cbh` или в пам�ть). Где разделы 0–8 говор�т о «малом режиме», дей�твует раздел 9. + +## 0. Главна� задача �крана и критерий «большой базы» + +Дл� книги (�отни партий) задача �крана — «проли�тать и открыть». Дл� Mega — «�узить 11,7 млн до де��тков и открыть». По�тому в большой базе главный �лемент — не таблица, а �в�зка «фильтры → �чётчик → таблица». Приоритет информации в шапке: �колько найдено из �кольких → идёт ли пои�к → им� базы и «только чтение». + +**Критерий (рекомендаци�):** режим определ�ет�� по базе, а не по окну и не по пользователю. + +| Режим | Когда | Пои�к | +| --- | --- | --- | +| Малый (как �ейча�) | PGN любого размера; архивы; ChessBase � чи�лом запи�ей **< 20 000** (конвертирует�� в PGN в пам�ти, как �ейча�) | одно поле над таблицей, без изменений | +| Большой | ChessBase (`.cbh`, `.cbv`, ChessBase внутри архива) � чи�лом запи�ей **≥ 20 000** — открывает�� по индек�у `.cbh` без конвертации | поле над таблицей убирает��; панель фильтров �права | + +- Чи�ло запи�ей изве�тно �разу (размер `.cbh` / 46), до чтени� �правочников, по�тому режим выбирает�� до начала загрузки и �кран загрузки уже правильный. +- 20 000 — одна кон�танта; книги и учебные базы (≤ 5 000) гарантированно о�тают�� в малом режиме, а базы турниров/дебютов на 50–500 ты�. уже выигрывают от панели. Точное значение — по замеру разработчика: порог там, где конвертаци� в PGN начинает заметно тормозить открытие (> ~2 �). +- ~~Большие PGN (lichess-выгрузки) в �той вер�ии о�тают�� в малом режиме~~ — **заменено разделом 9:** �кран (панель фильтров, до�ка, таблица, �трока у�ловий) один дл� в�ех баз; таблица выше теперь говорит только о том, как база читает�� (порог `LARGE_CHESSBASE` = 20 000 в `crates/chess-import/src/lib.rs`). + +**Поле пои�ка.** ~~Одно «умное» поле на 11,7 млн неоднозначно… по�тому его нет.~~ **Заменено разделом 9.2:** бы�трый пои�к е�ть у в�ех баз, �права в шапке р�дом � переключателем; он — ещё одно у�ловие по И, видно чипом «Пои�к», по�тому выборка не бывает неожиданной. `Ctrl+F` ведёт в него (раздел 9.10). + +## 1. Сценарии + +В�е �ценарии — без единого нажати� «И�кать»: фильтр примен�ет�� �ам. + +1. **Партии игрока.** `Ctrl+F` `Ctrl+F` (второе нажатие ведёт из бы�трого пои�ка в «Игрок», раздел 9.10) → набрать «carlsen» → через 250 м� таблица показывает партии в�ех игроков, в имени которых е�ть «carlsen» (Carlsen, Magnus и Carlsen, Henrik), под полем — под�казки «Carlsen, Magnus — 6 812 партий». `↓` + `Enter` в под�казках закрепл�ет точного игрока. Счётчик: «найдено 6 812 из 11 741 260». `↓` (под�казки закрыты) — к первой �троке таблицы, `Enter` — открыть. +2. **Игрок против игрока.** Заполнить «Игрок» (Carlsen) и «Соперник» (Nakamura). Цвет «любым» — партии в обе �тороны; «белыми» — только где Carlsen белыми. Результат в �том �лучае переключает�� в отно�ительный: «выигрыш / ничь� / проигрыш» игрока. +3. **Турнир.** Поле «Турнир» (под�трока по названию и ме�ту): «wijk 2024» → под�казки «Tata Steel Masters · Wijk aan Zee · 2024 — 91 парти�». Выбор под�казки — точный турнир; без выбора — в�е турниры, �овпавшие по в�ем �ловам. +4. **Годы + минимальный Эло.** «Годы» 2015 – 2024, «Эло от» 2600, «дл�: обоих». Без имени — проход по в�ем 11,7 млн запи�ей (до ~1 �), таблица показывает прогре�� (раздел 3.6). +5. **Дебют по ECO.** «ECO»: `B90` (точно), `B9` (префик� = B90–B99) или `C60-C99` (диапазон). �еверна� �трока — поле � кра�ной рамкой и под�казкой формата, фильтр по ECO не примен�ет��, о�тальные работают. +6. **Только аннотированные.** Флажки «� комментари�ми», «� вариантами» (что именно до�тупно в запи�и `.cbh` — уточн�ет аналитик). Обычно в �очетании � игроком/дебютом. +7. **Вернуть�� из партии к той же �троке.** Двойной клик / `Enter` → �кран партии → `Ctrl+W` или «� Библиотека». Возвращает�� тот же �кран: те же фильтры, тот же пор�док �ортировки, та же �трока выделена и прокручена в центр (�уще�твующий `Library::reveal`), без повторного прохода — выборка хранит�� в пам�ти. Открыта� парти� получает ✓ «про�мотрено». + +## 2. Компоновка + +### 2.1. Wireframe (окно 1280×800, логиче�кие пик�ели) + +``` +┌──────────────────────────────────────────────────────────────────────────────────────────────────� +│ Базы [♟ �ова� парти�][📋 В�тавить PGN][⚙] │ +│ ┌────────────────�┌────────────────�┌────────────────�┌──────────────� │ полка +│ │🗄 Ruy Lopez – ││🗄 Mega Database ││🗄 classics ││+ Добавить │ │ (как +│ │ Move by Move ││ 2026 🔒 ││ │ │ базу │ │ �ейча�) +│ │ 49 партий ││ 11,7 млн ││ не загружена ││ │ │ +│ └────────────────┘└────────────────┘└────────────────┘└──────────────┘ │ +├──────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ Mega Database 2026 · ChessBase, только чтение · найдено 6 812 из 11 741 260 ⟳ 43 % [⚠ 3][Фильтры ⟩]│ шапка 28 +├────────────────────────────────────────────────────────────────────┬─────────────────────────────┤ +│ № Белые Elo Чёрные Elo Рез. Ход ECO ✎ ┆ Игроки ▾ │ +│ 10234567 Carlsen, M. 2830 Nakamura, H. 2789 1-0 41 C65 ✎⑂┆ Игрок │ +│ 10234568 Caruana, F. 2805 Carlsen, M. 2830 ½-½ 30 C42 ┆ [carlsen × ] │ +│▌10240012 Carlsen, M. 2832 Firouzja, A. 2785 0-1 57 B90 ✎ ┆ (•)любым ( )белыми ( )чёрными│ +│ 10240013 … ┆ Соперник │ +│ … (виртуализированна� таблица, ┆ [ ] │ +│ видимые �троки) ┆ │ +│ ┆ Турнир ▾ │ +│ Турнир Дата ┆ [ ] │ +│ (колонки «Турнир», «Дата» �права от ECO при ширине ≥ 1100) ┆ Комментатор │ +│ ┆ [ ] │ +│ ┆ Парти� ▾ │ +│ ┆ Годы [2015] – [2024] │ +│ ┆ Эло от [2600] [обоих▾] │ +│ ┆ Ходы [ ] – [ ] │ +│ ┆ ECO [B9 ] × │ +│ ┆ Результат │ +│ ┆ [1-0][½-½][0-1][ * ] │ +│ ┆ �ннотации ▾ │ +│ ┆ [ ] � комментари�ми │ +│ ┆ [ ] � вариантами │ +│ ┆ [x] показывать тек�ты │ +│ ┆─────────────────────────────│ +│ ┆ [ Сбро�ить фильтры (4) ] │ подвал +└───────────────────────────────────────────────────────────────────┴─────────────────────────────┘ +``` + +Полна� �трока таблицы при ширине центральной ча�ти ≥ 1100: `№ · Белые · Elo · Чёрные · Elo · Результат · Ходы · ECO · ✎ · Турнир · Раунд · Дата`. + +### 2.2. Панель фильтров + +- `egui::SidePanel::right("filters")`, `resizable(true)`, ширина по умолчанию **280**, диапазон **260–380**; ширина и �о�то�ние «�вёрнута» запоминают�� в на�тройках (общие дл� в�ех больших баз). +- Внутри: `ScrollArea::vertical` � группами (`CollapsingHeader`, по умолчанию ра�крыты в�е) и прижатый к низу подвал � кнопкой «Сбро�ить фильтры (N)» — N = чи�ло активных у�ловий, кнопка неактивна при N = 0. Подвал не прокручивает�� вме�те � пол�ми. +- Пор�док — по ча�тоте и�пользовани�: **Игроки → Турнир → Парти� → �ннотации**. Внутри группы подпи�ь над полем (не �лева): в 280 px подпи�и �лева �ъедают ширину полей и ломают�� в немецком/француз�ком переводах. И�ключени� — �троки группы «Парти�» «Годы», «Эло от», «Ходы», «ECO»: подпи�ь �лева в общей колонке подпи�ей (�етка — §2.6). +- У каждого непу�того тек�тового пол� — кнопка `×` �права в �троке (очи�тить �то поле). Ме�то под `×` е�ть у пол� **в�егда**, и у пу�того: поле не мен�ет ширину при наборе (§2.6). +- **Ширину панели мен�ет только пользователь** перета�киванием кра�. Содержимое никогда не шире панели: ни набор тек�та, ни выбор под�казки, ни длинный перевод её не ра�шир�ют (§2.6). У группы � активным у�ловием в заголовке — �чётчик: «Парти� (2)», чтобы �вёрнута� группа не пр�тала фильтр. +- Плотно�ть как у о�тального приложени�: вы�ота пол� 24, интервал между пол�ми 6, между группами 10, внутренний от�туп панели 8. +- **Свернуть панель:** кнопка «Фильтры ⟩» в правом конце шапки (при �вёрнутой — «⟨ Фильтры (3)»). Свёрнута� панель полно�тью и�чезает, таблица занимает в�ю ширину; чи�ло активных у�ловий о�таёт�� видно в кнопке, а �чётчик «найдено N из M» — в шапке. Так фильтр нельз� «забыть»: он в�егда виден либо в панели, либо в кнопке и �чётчике. + +### 2.3. Шапка над таблицей + +Слева направо: им� базы (жирным) · «ChessBase, только чтение» (�лабым, tooltip как �ейча�) · **«найдено 6 812 из 11 741 260»** · индикатор фоновой работы · �права `⚠ N` (замечани� импорта, как �ейча�) и «Фильтры ⟩». + +- Без фильтров: «11 741 260 партий · 1 823 тек�та». +- Чи�ла — полно�тью, � разделением ты��ч узким пробелом (U+202F) по правилам локали; «млн» — только на карточке полки. +- Счётчик обновл�ет�� только по�ле завершени� прохода; пока проход идёт, �тарое чи�ло показано �лабым цветом, �права — �пиннер и процент («⟳ 43 %»). Процент — дол� про�мотренных запи�ей, а не найденных партий. + +### 2.4. Ме�то под пои�к по позиции (позже) + +Будуща� группа «Позици�» �тавит�� **первой** в той же панели: мини-до�ка 240×240 (впи�ывает�� в 260–380 без изменени� ширины), под ней «точна� позици� / тот же материал» и кнопка «Вз�ть � �крана партии». �ичего больше в компоновке не мен�ет��: те же �чётчик, индикатор, отмена прохода. Сейча� в интерфей�е её **нет �ов�ем** — без неактивных заглушек «�коро». Техниче�ки �то означает, что фильтр — набор незави�имых у�ловий, к которым позже добавит�� ещё одно, а прогре��/отмена общие. + +### 2.5. Узкое окно (минимум 900×600) и HiDPI + +**Обновление 2026-10-24:** минимум окна — 640×480; пороги «панель р�дом / поверх таблицы» и минимальна� ширина таблицы — `narrow-windows.md` §1–2 (имеет приоритет над �тим разделом). + +- 900 px − 280 (панель) = 620 px на таблицу. Колонки �крывают�� по приоритету, пока ширина центральной ча�ти меньше �уммы минимальных: �начала **Раунд**, затем **Турнир**, **Ходы**, **✎**, затем **№**. Белые, Чёрные, Эло, Результат, ECO, Дата не �крывают��. Скрытое значение до�тупно в tooltip �троки (наведение на �троку показывает «Турнир · раунд · ходов · комментатор»). +- Колонка «№» в большой базе — 76 px (8 цифр), в малой о�таёт�� 52. +- «Результат» в большой базе — 48 px (`1-0`, `½-½`, `0-1`, `*`). +- По вы�оте 600: полка 112, шапка 28, о�таёт�� ~460 под панель и таблицу. Содержимое панели (~520 при в�ех ра�крытых группах) прокручивает��; подвал «Сбро�ить» в�егда виден. Предложение (не об�зательно в первой итерации): в большой базе полку можно �вернуть до одной �троки чипов — открытый вопро� 8.6. +- В�е размеры — логиче�кие точки egui; при ма�штабе 1,5/2 геометри� та же, физиче�ки крупнее. Проверить при 2× на 1920×1080 (= 960×540 логиче�ки — ниже минимума; шапка и подвал должны о�тать�� видимыми, панель прокручивает��). +- Пол� «Годы», «Эло», «Ходы» т�нут�� вме�те � панелью по �етке §2.6 (при 260–380 — от 77 до 137 точек, 4 цифры помещают�� в�егда); длинные тек�товые пол� — на в�ю ширину панели без колонки `×`. + +### 2.6. Сетка панели фильтров (2026-10-24) + +Причина раздела — два дефекта, найденных владельцем: панель ра�шир�ла�ь при наборе игрока, а �троки «Годы / Эло / ECO / Ходы» не выровнены (пол� начинали�ь � разных x по длине подпи�и, ECO т�нуло�ь до кра�, «до» и выпадающий �пи�ок �то�ли где попало). + +**Правило ширины.** `egui::Panel` � `resizable(true)` запоминает ширину по фактиче�кому пр�моугольнику �одержимого: �трока, вылезша� за край хот� бы на 1 точку, ра�шир�ет панель, в �ледующем кадре поле �нова ра�тёт на �ту ширину — и так до 380. По�тому кажда� �трока панели �троит�� от `ui.available_width()` и никогда его не превышает; ширины, получающие�� вычитанием, округл�ют�� вниз (`floor`), чтобы дробные точки не накапливали�ь. Строки из кнопок � подпи��ми (цвет игрока, результат) — `horizontal_wrapped`. + +**Колонки** (в�е размеры — логиче�кие точки; W — `available_width` внутри прокрутки, ≈ ширина панели − 16): + +| Обозначение | Значение | Смы�л | +|---|---|---| +| `s` | 4 | промежуток между �лементами внутри �троки | +| `X` | 22 + `s` = 26 | колонка `×` �права: `small_close_button` 22×20 и промежуток перед ним | +| `L` | max ширины подпи�ей «Годы», «Эло от», «Ходы», «ECO» в текущем �зыке, вверх до целого | колонка подпи�ей группы «Парти�» (ru ≈ 32, es «Elo desde» ≈ 55) | +| `g` | 8 | от подпи�и до пол� | +| `C` | floor(W − L − g − X) | колонка полей группы «Парти�» | +| `D` | 16 | �чейка «–» между «от» и «до», тире по центру | +| `N` | floor((C − D − 2·s) / 2) | поле чи�ла и выпадающий �пи�ок Эло | + +В�е пол� панели заканчивают�� на одной вертикали W − X; �права от неё — только `×` непу�того тек�тового пол�. Пу�тое тек�товое поле держит ме�то `×` пу�тым, по�тому ширина пол� от набора не зави�ит. + +``` + Панель 280 (W = 264), ру��кий: L = 32, C = 198, N = 87 + ├ 8 ┤ + Игроки (1) + Игрок = � «=» — в �троке подпи�и + [вафин ] × поле W−X = 238, × 22 + [любым][белыми][чёрными] � horizontal_wrapped + Соперник + [ ] � ме�то × пу�тое, поле той же ширины + … + Парти� (2) + Годы [2020 ] – [2026 ] + Эло от [1500 ] [обоих ▾] � �пи�ок под полем «до», ширина N + Ходы [ ] – [ ] + ECO [B90, B9 или C60-C99 ] × + Результат + [Выигрыш][�ичь�][Проигрыш][*] � horizontal_wrapped, от левого кра� + ├ L ┤g├──── N ────┤ D ├──── N ────┤ X ┤ +``` + +- Пор�док �трок группы «Парти�» мен�ет��: **Годы → Эло от → Ходы → ECO → Результат**. Строки � подпи�ью �лева идут подр�д и образуют одну �етку; «Результат» (подпи�ь над кнопками — четыре кнопки не помещают�� в C) завершает группу и не разрывает �етку. +- Подпи�и колонки L — по левому краю, по центру �троки по вертикали. Тире — по центру �чейки D. +- «Эло от»: поле N в колонке «от», �чейка D пу�та�, �пи�ок правила Эло — ширина N ровно под полем «до». Слово «дл�» не пишет��: подпи�ь �троки и пункты �пи�ка («обоих / любого / �реднего / �оперника») его подразумевают. +- ECO и «Комментатор» — `text_field` � колонкой `×`, как имена. +- Вы�ота �трок — `interact_size.y` (как у полей), интервал �трок — 6, как во в�ей панели. +- В�плывающий �пи�ок под�казок — отдельный �лой (`Area`) и на ширину панели не вли�ет; прив�зан к пр�моугольнику пол�, который теперь не двигает��. +- Кра�на� рамка неверного значени� ри�ует�� �наружи пол� и ме�та не занимает. + +## 3. Элементы управлени� + +### 3.1. Игрок / Соперник / Турнир / Комментатор — тек�т � под�казками + +`TextEdit::singleline` на в�ю ширину + в�плывающий �пи�ок под полем (`egui::Popup`/`Area`, прив�занный к rect пол�, шириной пол�, до 8 �трок). + +- **Что фильтрует �вободный тек�т:** под�трока без учёта реги�тра и диакритики («hubner» находит «Hübner»); не�колько �лов — в�е должны в�тречать�� в любом пор�дке («magnus carlsen» находит «Carlsen, Magnus»). Это �разу работает «вживую». +- **Под�казки �то�т того** — в Mega у одного игрока не�колько напи�аний и де��тки однофамильцев, а у турниров одинаковые названи� по годам; без под�казок пользователь не видит, что именно �овпало. Строка под�казки: «Carlsen, Magnus — 6 812» (чи�ло партий, е�ли оно е�ть в `.cbp`; иначе без чи�ла), дл� турнира — «Tata Steel Masters · Wijk aan Zee · 2024 — 91». Пор�док: �овпадение � начала фамилии, затем по чи�лу партий, затем по алфавиту. По�ледн�� �трока — «ещё 312 �овпадений…» (неактивна). +- **Выбор под�казки** (клик или `↓`/`↑` + `Enter`) закрепл�ет точную �ущно�ть: поле показывает им�, а в �троке подпи�и над полем, �разу по�ле неё, — жирный значок `=` («Игрок =», tooltip «Точно �тот игрок; изменить тек�т — �нова пои�к по под�троке»). Значок не �тоит в �троке пол�: поле не �двигает�� и не �ужает�� при выборе под�казки. Любое редактирование тек�та �нимает закрепление. +- Под�казки �читают�� в фоне на том же debounce, что и фильтр; е�ли не у�пели — �пи�ок не показывает�� (никаких «загрузка…» в выпадашке). +- Спи�ок открывает�� только при наборе тек�та и закрывает�� `Esc`, выбором, потерей фоку�а. + +Цвет игрока — три `selectable_value` в �троке � перено�ом (`horizontal_wrapped`): «любым / белыми / чёрными»; во француз�ком «toute couleur / avec les Blancs / avec les Noirs» шире 260 и перено�ит��, а не ра�шир�ет панель. Примен�ет�� к «Игроку»; без игрока неактивен (�ерый, tooltip «Сначала укажите игрока»). + +### 3.2. Годы, Эло, Ходов — диапазоны + +- Два коротких `TextEdit` � фильтром цифр (не `DragValue`: перета�кивание года мышью неудобно, а ввод «2015» � клавиатуры — о�новной путь). Пу�тое = без границы. Под�казки в пу�тых пол�х: «1850» / «2026», «2600», «20» / «60». +- �еполный ввод («20» в поле года) не примен�ет��, пока не �танет корректным чи�лом из 4 цифр; поле � неверным значением — кра�на� рамка, tooltip «Год от 1 до 2100». Е�ли «от» > «до» — обе рамки кра�ные, фильтр по годам не примен�ет��. +- Партии без года (дата ????) при любом заданном годе и�ключают��; при пу�тых пол�х — показывают��. +- **Эло от** + выпадающий �пи�ок «дл�: обоих / любого / �реднего»; когда задан игрок — добавл�ет�� «�оперника» (ча�тый �ценарий «партии Карл�ена против 2700+»). «Эло до» не делаю в первой вер�ии (редкий �ценарий; открытый вопро� не нужен — добавл�ет�� без перекомпоновки). +- Партии без Эло (0) при заданном «Эло от» и�ключают��. + +### 3.3. Результат + +Четыре переключател�-кнопки `[1-0] [½-½] [0-1] [*]`, множе�твенный выбор; ни одна не нажата = любой результат. �ажатое �о�то�ние — заливка цветом выделени� **и** жирный тек�т (не только цвет). + +Е�ли задан игрок, надпи�и мен�ют�� на `[Выигрыш] [�ичь�] [Проигрыш] [*]` — результат отно�ительно игрока (дл� «Carlsen любым цветом» «1-0» бе��мы�ленно). Со�то�ние кнопок при �том �бра�ывает��, чтобы не было �крытого перевода �мы�лов. + +### 3.4. ECO + +Одно тек�товое поле, под�казка «B90, B9 или C60-C99». Принимает: точный код, префик� из буквы или буквы � цифрой, диапазон `X00-Y99` (дефи� или тире), не�колько через зап�тую. Реги�тр не важен. Подкоды ChessBase не и�пользуют�� в фильтре (отображение — как �ейча�, без подкода). �еверный ввод — кра�на� рамка, tooltip � примерами, у�ловие не примен�ет��. + +### 3.5. Флажки + +- «� комментари�ми», «� вариантами» — по признакам запи�и `.cbh` (что точно до�тупно — у аналитика; е�ли признака нет, флажок не показывает��, а не делает�� неактивным). +- «показывать тек�ты» — тек�товые главы. Флажок е�ть только у базы, в которой тек�ты е�ть (ChessBase � тек�тами; книга из `.cbv`/малого `.cbh`, переведённа� в PGN, — раздел 9.4); у базы без тек�тов, в том чи�ле у любого обычного PGN, его нет. По умолчанию включено; тек�ты автоматиче�ки не вход�т в выборку, когда задан любой фильтр, который к ним неприменим (игрок, �оперник, результат, Эло, ECO, ходы, аннотации) — у тек�тов нет игроков и результата. Турнир и комментатор к тек�там применимы; даты у тек�тов нет, по�тому у�ловие на годы их тоже и�ключает (уточнено при реализации, QA-отчёт №2, D6). + +### 3.6. Жива� фильтраци� + +- **Когда запу�кает�� проход:** тек�товые пол� — через 250 м� по�ле по�леднего нажати�; чи�ловые — через 250 м� и только при корректном значении; кнопки, флажки, выбор под�казки, «Сбро�ить» — �разу. +- **Отмена:** каждый запу�к получает номер поколени�; новый запу�к отмен�ет предыдущий (флаг отмены, проверка раз в ~64 ты�. запи�ей); результат � у�таревшим номером отбра�ывает��. Тот же механизм у �ортировки. +- **Пока идёт проход:** таблица показывает **�тарую** выборку и о�таёт�� рабочей (прокрутка, открытие партии из �тарой выборки допу�тимо — �то реальные партии). Е�ли проход длит�� дольше 150 м� — таблица затемн�ет�� (`ui.set_opacity(0.6)`), в шапке �пиннер и процент. Короткие проходы (под�казка закрепила игрока � 300 парти�ми) не мигают. +- **Ча�тичные результаты не показывают��** (никакого «найдено ≥ 3 412…» � прыгающими �троками): � �ортировкой и выделением �то дёргает таблицу. При ≤ 1 � ожидани� процента до�таточно. +- По завершении: нова� выборка, �чётчик, прокрутка в начало; выделение — по правилам раздела 4.8. +- По�ледовательно�ть «фильтр → �ортировка» одна: �менили фильтр при �ортировке по имени — нова� выборка �разу приходит от�ортированной. + +## 4. Со�то�ни� + +### 4.1. Открытие большой базы + +Справочники читают�� до показа таблицы; �то �екунды, а не милли�екунды. Таблица замен�ет�� блоком по центру (как �ейча� у загрузки PGN), но � �тапами: + +``` +Открываю Mega Database 2026 — 11 741 260 запи�ей + ✓ Игроки 479 012 + ⟳ Турниры 63 400 / 109 118 ███████████░░░░░░ + Запи�и партий + [ Отменить ] +``` + +- Панель фильтров уже видна, но неактивна (`add_enabled(false, …)`) — пользователь видит, что его ждёт, и может начать печатать �разу по�ле готовно�ти. +- Карточка на полке: «загрузка… 58 %». +- «Отменить» — база о�таёт�� на полке как «не загружена». + +### 4.2. Пу�то (ничего не найдено) + +Вме�то �трок — по центру таблицы: «�ичего не найдено» и ниже �лабым тек�том �пи�ок активных у�ловий кнопками-��ылками: «Игрок: carlsen × · Годы: 1950–1960 × · [Сбро�ить в�е]». Клик по `×` �нимает одно у�ловие. Счётчик: «найдено 0 из 11 741 260». + +### 4.3. Ошибка + +- База не открыла�ь (повреждённый `.cbh`, нет `.cbp`, нехватка пам�ти) — как �ейча�: кра�ный тек�т � причиной и «Повторить»; панель �крыта. +- Ошибка во врем� фильтрации (не должна быть, но) — в шапке вме�то �чётчика «⚠ Пои�к прерван: <причина>» и «Повторить»; таблица показывает предыдущую выборку. +- Парти� не читает�� при открытии (`.cbg` повреждён) — о�таём�� в библиотеке, �трока помечает�� оранжевым номером (как �ейча� `has_decode_errors`), �ообщение во в�плывающем уведомлении/�троке шапки: «Партию № 10234567 не удало�ь прочитать: …». + +### 4.4. База удалена или перемещена + +- �а полке (база не загружена): карточка «файл не найден» + `⚠`; при выборе — по центру «Файл не найден: /путь/Mega Database 2026.cbh» и кнопки «Указать новое ра�положение…» (диалог выбора файла; база о�таёт�� той же карточкой, фильтры �охран�ют��) и «Убрать из �пи�ка». +- Во врем� работы (база открыта, файлы удалены/ди�к отключён): �пи�ок и фильтры продолжают работать из пам�ти; ошибка про�вит�� только при открытии партии — «Файлы базы недо�тупны (удалены или ди�к отключён)» � кнопкой «Перечитать базу». Е�ли разработчик и�пользует mmap: на Linux удалённый файл о�таёт�� читаемым, но отключённый ди�к даёт SIGBUS — �то нужно обработать на �тороне разработчика (не дизайн, но ри�к). + +### 4.5. Тек�товые главы + +Строка тек�та: в колонке «Белые» — «📄 » + заголовок (кур�ивом), «Чёрные», Эло, результат, ходы, ECO пу�ты; турнир и дата — е�ли е�ть. �омер — общий дл� в�ех запи�ей (как в ChessBase). Открытие — �уще�твующий �кран партии без ходов, тек�т как комментарий (как �ейча� у книг). + +### 4.6. Партии Chess960 и прочие нечитаемые варианты + +Признак виден из запи�и без разбора (ECO ≥ 64576 → в колонке ECO «960»). В �троке: ECO «960», tooltip «Chess960: ходы не читают��, показывают�� заголовок и результат». Открытие — �кран партии � заголовком и �ообщением о причине вме�то пу�той нотации. В «Замечани�х импорта» дл� большой базы не перечи�л�ть каждую такую партию (их могут быть ты��чи) — одна �водна� �трока «Chess960 и др.: 4 120 партий без ходов». + +### 4.7. Сортировка + +- Клик по заголовку — как �ейча� (�/�). Сортировка запу�кает�� тем же фоновым механизмом � индикатором; по чи�ловым пол�м обычно мгновенно. +- По умолчанию — «№» по возра�танию (пор�док базы, без затрат). И�ключение — базы, �качанные � Lichess и Chess.com: «Дата �», новые �верху (раздел 9.6). +- Строки � пу�тым значением (без Эло, без даты) — в�егда в конце, в обоих направлени�х. +- Сортировка не �бра�ывает�� при �мене фильтра; при �мене �ортировки выделенна� �трока о�таёт�� выделенной и прокручивает�� в центр. + +### 4.8. Выделенна� �трока выпала из выборки + +- Выделение хранит�� как номер партии, а не позици� в таблице. +- По�ле �мены фильтра: е�ли парти� е�ть в новой выборке — о�таёт�� выделенной; прокрутка — в начало (пользователь �мотрит на результат нового фильтра); е�ли нет — выделение �нимает��, `Enter` ничего не делает, `↓` выдел�ет первую �троку. Так `Enter` по�ле набора имени не откроет �лучайную партию из �тарой выборки. +- Возврат из партии — в�егда к открытой партии (прокрутка в центр), даже е�ли дл� �того нужно дождать�� прохода, запущенного до открыти�. + +### 4.9. «Про�мотрено» ✓ + +Текущий ключ — хеш �одержимого партии; дл� 11,7 млн его нельз� по�читать заранее. Дл� большой базы ключ — (идентично�ть базы, номер запи�и). Отметка �тавит�� при открытии, как �ейча�; контек�тное меню �троки — без изменений. + +## 5. Клавиатура, фоку�, tooltip-ы + +| Клавиша | Где | Дей�твие | +| --- | --- | --- | +| `Ctrl+F` | библиотека, люба� база | **заменено разделом 9.10:** фоку� в бы�трый пои�к в шапке; повторное `Ctrl+F` из пои�ка — панель «Фильтры» и фоку� в «Игрок» | +| `Tab` / `Shift+Tab` | панель | по пол�м �верху вниз, затем в таблицу | +| `Esc` | поле � открытыми под�казками | закрыть под�казки | +| `Esc` | непу�тое поле | очи�тить поле (у�ловие �нимает�� �разу) | +| `Esc` | пу�тое поле | фоку� в таблицу | +| `↓` / `↑` | поле � открытыми под�казками | по под�казкам | +| `↓` / `↑` | поле без под�казок, таблица | выделение в таблице (как �ейча� в малом режиме) | +| `Enter` | под�казка под�вечена | закрепить игрока/турнир | +| `Enter` | иначе | открыть выделенную партию (е�ли выделени� нет — ничего) | +| `PgUp` / `PgDn` | таблица и пол� | выделение на �траницу (новое дл� обоих режимов: на 11,7 млн колё�ико бе�полезно) | +| `Home` / `End` | только таблица в фоку�е | перва� / по�ледн�� �трока (в поле — кур�ор тек�та) | +| `Ctrl+Shift+Backspace` | библиотека, больша� база | �бро�ить в�е фильтры (в tooltip кнопки «Сбро�ить») | + +Видимый фоку�: у полей — штатна� рамка egui; у таблицы — выделенна� �трока � поло�ой �лева (`▌`) в фоку�е и без неё, когда фоку� в панели, чтобы было пон�тно, куда пойдут �трелки при открытых под�казках. + +Tooltip-ы (коротко, по делу): +- «Игрок»: «Под�трока имени, без учёта реги�тра. Выберите под�казку, чтобы и�кать точно �того игрока. Ctrl+F». +- «Соперник»: «Партии игрока против �того �оперника». +- «Турнир»: «�азвание или ме�то, можно не�колько �лов: wijk 2024». +- «ECO»: «B90 — код, B9 — B90–B99, C60-C99 — диапазон». +- «Эло дл�»: «обоих — оба не ниже; любого — хот� бы один; �реднего — �реднее Эло партии». +- «Показывать тек�ты»: «Главы-тек�ты базы. Скрывают��, е�ли задан игрок, результат, Эло или ECO». +- Счётчик в шапке: «Запи�ей в базе: 11 741 260, из них тек�тов 1 823». +- Строка таблицы (при �крытых колонках): «Турнир · раунд · ходов · комментатор». + +## 6. Карточка базы на полке + +Тот же размер 190×64 и та же �труктура, что у о�тальных карточек. + +- Втора� �трока: чи�ло запи�ей в коротком виде и признак «только чтение»: «11,7 млн партий · 🔒». Правило: < 10 000 — точно («4 512 партий»), 10 000–999 999 — «479 ты�.», от 1 млн — «11,7 млн» (одна цифра по�ле зап�той). В англий�ком «11.7M games», «479K games». +- 🔒 — у в�ех баз только дл� чтени� (ChessBase, архивы), не только у больших; у PGN нет. Проверить, что глиф е�ть в шрифтах egui; е�ли нет — �лабым тек�том «чтение». +- Tooltip карточки: путь + «11 741 260 партий, 1 823 тек�та · ChessBase · только чтение: �охран�йте партию в отдельный PGN». +- Отдельного «большого» значка не нужно: разница видна по чи�лу, а режим — по панели по�ле выбора. +- Контек�тное меню: «Убрать из �пи�ка», «Перечитать базу», дл� от�ут�твующего файла — «Указать новое ра�положение…». + +## 7. Сохранение фильтров + +Рекомендаци�: + +- **Фильтры и �ортировка — на базу, в пределах �е��ии.** Переключили�ь на книгу и обратно, открыли партию и вернули�ь — в�ё на ме�те, включа� прокрутку и выделение. +- **Между запу�ками фильтры не �охран�ют��;** �охран�ют�� только ширина панели, �вёрнуто�ть панели и групп, �ортировка по умолчанию. Причина: во��тановленный фильтр по�ле перезапу�ка выгл�дит как «база показывает не в�ё», а проход по 11,7 млн при открытии — лишн�� �екунда без запро�а пользовател�. Счётчик �нижает �тот ри�к, но не убирает. +- Позже, е�ли понадобит��: именованные «�охранённые запро�ы» — �вное дей�твие, а не не�вное во��тановление. + +## 8. Открытые вопро�ы к владельцу продукта + +1. ~~**Порог большой базы — 20 000 запи�ей ChessBase?**~~ Решено (20 000, `LARGE_CHESSBASE`); � 2026-10-23 порог вли�ет только на �по�об чтени�, не на �кран (раздел 9). +2. ~~**Общее поле пои�ка в большом режиме убрать?**~~ Пере�мотрено 2026-10-23: бы�трый пои�к е�ть у в�ех баз (раздел 9.2); вопро� 9.13.1. +3. **Фильтры между запу�ками:** рекомендую только в пределах �е��ии (раздел 7). +4. ~~**Панель дл� больших PGN** и кнопка «Фильтры» дл� малых баз~~ — решено владельцем 2026-10-23: у в�ех PGN тот же �кран (раздел 9). +5. **Эк�порт выборки в PGN** («�охранить 6 812 найденных партий») — очень полезно и е�те�твенно по�ле фильтра, но �то новый т�жёлый фоновый проце�� � прогре��ом. Рекомендую �ледующей итерацией, не �ейча�. +6. **Сворачивание полки в большой базе** до одной �троки при вы�оте окна < 700 — рекомендую не делать в первой итерации, проверить на 900×600 по�ле реализации. +7. **Переход к партии по номеру** (`Ctrl+G` → «№ 10234567») — дёшево, полезно дл� ��ылок из книг и комментариев. Рекомендую добавить, е�ли не мешает �рокам. +8. **Колонка «✎» (е�ть комментарии/варианты)** — зави�ит от того, что подтвердит аналитик в запи�и `.cbh`; е�ли признаков нет, колонка и флажки не показывают��. + +## 9. Один �кран дл� в�ех баз: PGN как ChessBase + +Стату�: проект дизайнера, 2026-10-23, по решению владельца: «идентично как � базами от chessbase». Пол�, которых в PGN может не быть (ECO, комментатор), о�тают�� видны, а фильтр по ним про�то ничего не находит. Бы�трый тек�товый пои�к PGN о�таёт��. Пример реальной нагрузки — `Гран-при_РШШ_архив_в�е_партии.pgn`: 81 МБ, 33 640 партий. Теги `Event`, `Date` (вида `2026-10-18`), `Round`, `Board`, `White`/`Black`, Эло, `WebSite`, `GameId`, `Result`. У каждого хода `[%clk]`, ECO нет. + +### 9.1. Какой �кран у какой базы + +- **В�е базы полки открывают�� в одном �кране** — �кран раздела 2 и `board-search.md`: шапка, �трока у�ловий (чипы), таблица, �права `[Фильтры | До�ка]`. Это PGN любого размера, от одной партии до миллиона, �качанные � Lichess и Chess.com, архивы, малые ChessBase и `.cbv`, переведённые в PGN, и большие ChessBase. Порога «маленька� база — без панели» нет: учебный файл на 38 партий получает тот же �кран. Два �крана означали бы два набора клавиш и поведений, а владелец про�ит один. +- Панель по умолчанию у новой базы — «Фильтры», как у ChessBase �ейча�. Кому панель в книге на 49 глав мешает, тот �крывает её щелчком по активному �егменту, и таблица займёт в�ю ширину (§2.1 `board-search.md`). +- Различи� между базами идут только от данных, а не от �крана (§9.11): у �лемента, которому нечего показать, нет ме�та на �кране; неактивных заглушек нет. +- Техниче�ки `LargeView` работает над и�точником запи�ей � двум� реализаци�ми: `Base` (ChessBase, как �ейча�) и таблица запи�ей PGN в пам�ти (§9.7). Им нужны одни операции: `query`, `sort_records`, `suggest_players`/`suggest_events`, �трока таблицы, чи�ло запи�ей и тек�тов. `SmallBoard` и отдельна� таблица PGN в `library.rs::table_area` уход�т. `Filter`, `NameFilter`, `fold`, `words`, `parse_eco` выно��т�� из `chessbase::base` в общий модуль `chess-import`, чтобы оба и�точника понимали у�лови� одинаково. + +### 9.2. Бы�трый пои�к + +``` +│ Гран-при_РШШ_архив_в�е_партии · PGN, кодировка UTF-8 · найдено 412 из 33 640 ⟳ 40 % [⚠ 2] [� вафин] × [Фильтры | До�ка] │ шапка 28 +│ Пои�к: вафин × · Годы: 2025–2026 × · Результат: 1-0 × �бро�ить в�е │ чипы 26 +``` + +- **Ме�то** — шапка, �права, �лева от переключател� `[Фильтры | До�ка]`. Поле на ме�те у в�ех баз, включа� ChessBase (вопро� 9.13.1). Ширина 220; в узкой шапке (до�тупно < 700) — 140. Раньше него укорачивает�� лева� ча�ть шапки, и в ней первым — **им� базы**: �чётчик «найдено N из M» важнее имени (им� видно на карточке полки), по�тому им� получает ширину, о�тавшую�� по�ле подпи�и формата, �чётчика и «⟳ �овые партии», но не меньше 80. Подпи�ь формата пр�чет�� по нынешнему правилу (< 520). +- **`×` пол�** �тоит �права от пол�, между ним и переключателем (у одно�трочного пол� egui нет ме�та под кнопку внутри). Ме�то под `×` зан�то и у пу�того пол�, чтобы поле не �двигало�ь при первой букве. Под�казка в пу�том поле — �уще�твующа� �трока «� Пои�к: игрок, турнир, ECO, год». +- **Что ищет.** Слова без учёта реги�тра и диакритики (`fold`, как в §3.1). Каждое �лово должно найти�ь хот� бы в одном поле; пол� дл� разных �лов могут быть разные. У PGN пол� те же, что �ейча�: `White`, `Black`, `Event`, `Site`, `ECO`, `Date`, `Annotator`. У ChessBase — имена белых и чёрных, турнир (название, ме�то, год), комментатор, код ECO, год. Это �ознательное изменение: �ейча� в�� �трока должна была �то�ть в одном теге, и «carlsen 2024» не находил ничего. +- **Живой пои�к** — тот же механизм, что у полей панели (§3.6): 250 м� по�ле по�ледней клавиши, фоновый проход, отмена �тарого прохода, затемнение по�ле 150 м�. �а PGN в ты��чи партий проход мгновенный, мигани� нет. +- **Сочетание** — по И � панелью и позицией. Пои�к по позиции ищет �реди партий, прошедших панель и бы�трый пои�к (�ейча� `SmallBoard` делает то же дл� тек�та). +- **Чип «Пои�к: вафин ×»** е�ть в �троке у�ловий, пока поле не пу�то. Пор�док чипов: Позици� → **Пои�к** → Игрок → … (`board-search.md` §2.2: там «Пои�к» �то�л по�ледним и только у малой базы). Щелчок по тек�ту чипа �тавит фоку� в поле пои�ка. +- **Очи�тка:** `×` у пол�, `×` на чипе, `Esc` в непу�том поле, `Ctrl+Shift+Backspace` (�нимает в�ё, включа� позицию). «Сбро�ить фильтры (N)» в подвале панели �нимает только у�лови� панели. Пои�к, как и позици�, о�таёт��: у них �вои `×`, и в N пои�к не входит. В «Фильтры (N)» на переключателе тоже не входит. +- **Счётчик** «найдено N из M» показывает�� при любом у�ловии, пои�к тоже �читает��. + +### 9.3. Пол� фильтра дл� PGN + +| Поле | ChessBase | PGN | +| --- | --- | --- | +| Игрок, Соперник, цвет | игроки `.cbp` | теги `White`, `Black`. Игрок — �трока имени как в файле, крайние пробелы убраны, двойные �жаты. `?`, `-` и пу�тое им� — «нет игрока»: в под�казки не попадает и не �овпадает ни � чем | +| Турнир или ме�то | турнир `.cbt`: «�азвание (ме�то) год» | тот же вид имени: `Event`, ме�то из `Site`, год из `Date`; по �тому имени ищет �вободный тек�т. `Site` берёт�� ме�том, только е�ли �то не `?`, не ��ылка (нет `://`: Lichess и Chess.com пишут туда адре� партии) и его ещё нет в названии. «Блиц 5, до 15 лет 2026» и «… 2025» — разные турниры, как в ChessBase. Работают «wijk 2024», «блиц 5 2026»; у Lichess `Event` вида «Rated Blitz game», по�тому �лово «blitz» отбирает блиц | +| Комментатор | `.cbc`, �лова | тег `Annotator`, �лова, без под�казок (как у ChessBase) | +| Годы | дата запи�и | год из `Date`; е�ли в `Date` года нет — из `UTCDate`. Разделители `.`, `-`, `/`: `2026-10-18`, `2026.10.18`, `2010.??.??` → 2010. `????.??.??` или нет тега — года нет: при заданных годах парти� и�ключает��, без них показывает�� (§3.2) | +| Эло от + «дл�» | Эло запи�и, 0 — нет | `WhiteElo`/`BlackElo`, целое > 0. `?`, `-`, пу�то, 0 — «нет Эло». Правила «обоих / любого / �реднего / �оперника» те же | +| Результат | байт результата | `Result`: `1-0`, `0-1`, `1/2-1/2` (и `½-½`). В�ё прочее или нет тега — `*`. Отно�ительно игрока — как в §3.3 | +| ECO | код запи�и | первые три знака тега `ECO`, `A00`–`E99`, без учёта реги�тра: `B90a` и `B90 Sicilian` → B90. Иначе ECO нет, и при заданном ECO парти� и�ключает��. Поле о�таёт�� и тогда, когда ECO нет ни у одной партии (решение владельца), а пу�той результат объ��н�ет причину (§9.8) | +| Ходов | ходы о�новной линии | `GameEntry::moves()`: тег `PlyCount`, е�ли он е�ть, иначе полуходы о�новной линии вне �кобок, пополам � округлением вверх. Разработчик уже добавл�ет `main_plies` в `scan.rs` | +| � комментари�ми | признак запи�и | `has_text_comments`: в комментарии е�ть тек�т помимо команд `[%…]`. `[%clk]`, `[%eval]`, `[%emt]`, `[%cal]`, `[%csl]` не �читают��, комментарий `;` �читает��, одни NAG (`!?`, `$14`) — нет. В примере РШШ таких партий 0, и �то правильно: ча�ы — не комментарий | +| � вариантами | признак запи�и | `has_variations`: �кобки в нотации | +| показывать тек�ты | тек�ты базы | §9.4 | + +### 9.4. Тек�ты + +- **У обычного PGN тек�тов нет, и флажка «показывать тек�ты» нет**: он �крыт, а не неактивен. Это не фильтр по полю, которое может быть пу�тым, а вид запи�ей, которых в базе нет. Правило одно дл� в�ех баз: флажок е�ть, только е�ли в базе е�ть тек�ты; у ChessBase без тек�тов его тоже нет (§3.5). +- **PGN, переведённый из ChessBase** (`.cbv`, малый `.cbh`, архивы � ними): конвертер точно знает, какие запи�и были тек�тами (`writer::text_game`). Он помечает их (�пи�ок номеров в `Opened`/`PgnDb`), и дальше они ведут �еб� как тек�ты ChessBase: �трока «📄 заголовок» кур�ивом и правила §3.5 и §4.5. Угадывать тек�т по признаку «нет ходов» нельз�: запи�ь � заголовком и без ходов — законна� парти� (так в Mega запи�аны ты��чи партий). + +### 9.5. Совпадение имён и под�казки + +- **Правило то же, что у ChessBase** (`Names::matching`). Им� и запро� привод�т�� к `fold`, запро� делит�� на �лова по пробелам и зап�тым, каждое �лово должно быть под�трокой имени, пор�док любой. По�тому «Карл�ен, М» находит «Магну� Карл�ен», а «magnus carlsen» — «Carlsen, Magnus»: пор�док «фамили� первой» не важен ни в одну �торону. «вафин» находит «Вафин Радель». Тран�литерации нет (`Carlsen` ≠ `Карл�ен`): разные алфавиты — разные имена, как и в ChessBase. +- **Решение дизайнера дл� обоих форматов:** в `fold` добавить `ё → е`. В ру��ких PGN одно им� пишут и «�ртём», и «�ртем» (в примере РШШ е�ть «Макаров �ртём»), а набирают почти в�егда через «е». Это одна �трока в `fold` и те�т. +- **Под�казки PGN** берут�� из таблиц имён, которые �тро�т�� при открытии (§9.7): разные игроки и разные турниры (§9.3) � чи�лом партий. Вид, пор�док (�овпадение � начала имени → чи�ло партий → алфавит), 8 �трок, «ещё N �овпадений…», закрепление `=` — как в §3.1. Выбор под�казки закрепл�ет одну �троку имени. Разные напи�ани� одного человека о�тают�� разными игроками, как в ChessBase. + +### 9.6. Таблица + +Колонки те же, что у ChessBase в коде: `[Ход] · № · Белые · Elo · Чёрные · Elo · Рез. · Длина · ECO · 💬 · Турнир · Тур · Дата`. Заголовок результата — короткий ключ `Res.` («Рез.»), а не «Результат»: в колонку 56 «Результат» не входит. Пор�док �крыти� при узком окне тот же (`board-search.md` §2.7). + +- **№** — пор�дковый номер партии в файле (� 1). Ширина колонки — по чи�лу знаков номера � разделител�ми разр�дов (8 на знак + 24 под ✓, от 52 до 84). +- **Турнир** — `Event` (`?` → пу�то), кур�ивом, как �ейча�. Отдельной колонки «Ме�то» нет, потому что её нет и у ChessBase. Ме�то видно в под�казке «Турнир или ме�то» и в tooltip �троки: «Рапид 42, до 11 лет · Казань · тур 1.1 · ходов: 42 · комментатор» — только то, что е�ть. Длина пишет�� «ходов: N», чтобы не �клон�ть чи�ло; тур — �о �ловом, голое «1.1» непон�тно. С�ылку из `Site` ме�то не показывает. +- **Тур** — `Round` как в файле (`1.1`), `?` → пу�то. Тег `Board` не показывает��. Заголовок «Тур» (ключ `Round`), как у ChessBase и в ру��кой шахматной практике. +- **Дата** — `Date` (е�ли нет, то `UTCDate`), «18.10.2026», «05.1997», «1997». �айденный дефект: `library::display_date` понимает только точки, и у файла РШШ дата `2026-10-18` �ейча� показывает�� пу�той. �ужно понимать `.`, `-` и `/`. +- **Длина** — `moves()` (§9.3). Сейча� она пу�та у файлов без `PlyCount`, в том чи�ле у РШШ. +- **💬** — отметки «е�ть комментарии / варианты» по признакам §9.3. У партий, где е�ть только ча�ы, отметки нет. +- ✓ «про�мотрено» (ключ — �одержимое партии, как �ейча� у PGN) и оранжевый номер при ошибках �труктуры или кодировки — без изменений. + +**Сортировка** — по тем же колонкам, что у ChessBase. Пу�тые значени� (нет Эло, даты, ECO) — в конце в обоих направлени�х (§4.7); �ейча� PGN �тавит партии без Эло первыми при �ортировке по возра�танию. Ключ даты — `played_at()`: `UTCDate` + `UTCTime`, когда е�ть оба, иначе `Date`. Так партии одного дн� из онлайн-выгрузки идут по времени. + +**Пор�док по умолчанию:** «№ �» — пор�док файла (книга читает�� главами по пор�дку). У баз, �качанных � Lichess и Chess.com (`online::is_online`), — «Дата �», новые �верху. Сейча� «новые �верху» �пр�тано в колонке «№» под �трелкой �, а будет видно че�тной �трелкой на «Дата». Это �ортировка по умолчанию, а не выбор пользовател� (`sort_chosen = false`): � позицией включают�� «�ильнейшие �верху», а по�ле �н�ти� позиции возвращает�� «Дата �». + +### 9.7. Открытие, подготовка, перечитывание + +- **Загрузка** — как �ейча�: «Читаю … — найдено партий: N», поло�а, «Отменить». Один раз за �еан� �троит�� **таблица запи�ей дл� фильтров** (в коде — `pgn_catalog::Catalog`). Её �троит поток загрузки �разу по�ле разбора или первый фоновый проход фильтра, но не поток интерфей�а: на выгрузке в миллион партий �то заметное врем�. �а партию в ней номера белых, чёрных, турнира и комментатора, год, два Эло, результат, ECO, длина и признаки; к ней добавл�ют�� таблицы имён � чи�лом партий. Это де��тки байт на партию: 33 640 партий — мгновенно, миллион партий выгрузки — меньше �екунды. Е�ли подготовка дольше 150 м�, поло�а �тоит на 100 % � подпи�ью «Готовлю �пи�ок…». Таблица и панель по�вл�ют�� вме�те, как у ChessBase. +- **Перечитывание** («⟳ �овые партии», файл ра�тёт во врем� �качивани�, «Перечитать базу»): фильтры, пои�к, позици�, �ортировка и выделение �охран�ют�� (�о�то�ние прив�зано к пути). Выборка пере�читывает�� тем же проходом. Выделение о�таёт��, е�ли номер партии ещё е�ть в выборке: �качанные партии допи�ывают�� в конец файла, номера �тарых не мен�ют��. Прокрутка не прыгает. Таблица позиций (§9.9) по�ле перечитывани� �троит�� заново при �ледующем и�пользовании до�ки. + +### 9.8. Со�то�ни� + +- **Пу�то** — как в §4.2: «�ичего не найдено», чипы � `×` и кнопка по тому, что задано: «Сбро�ить фильтры» (только панель), «Сбро�ить пои�к» (только пои�к), «Сбро�ить фильтры и пои�к» (оба). Она �нимает у�лови� панели и пои�к, а позици� о�таёт��; при заданной позиции та же кнопка называет�� «И�кать во в�ей базе» и тоже �нимает пои�к (`board-search.md` §4.5). +- **Поле, которого в базе нет.** Е�ли у�ловие задано по полю, которое не заполнено ни у одной партии базы, под «�ичего не найдено» �тоит �трока-объ��нение: «�и у одной партии �той базы нет кода ECO» (а также комментатора, Эло, года; дл� Эло — «нет Эло», как подпи�ано поле, а не «рейтинга»). Чи�ло заполненных полей �читает�� при подготовке (§9.7). Поле в панели при �том о�таёт�� как е�ть, без �ерого и без предупреждений до пои�ка — так решил владелец. +- **Ошибка открыти�** — как �ейча�: причина и «Повторить». Ошибок фильтрации у PGN не бывает: фильтр не читает ди�к. +- **Парти� не разбирает�� при открытии** — как �ейча�: открывает�� � диагно�тикой. + +### 9.9. Пои�к по позиции + +- Та же панель до�ки, те же чипы, колонка «Ход», продолжени�, «�ильнейшие �верху», ↪ и «только �тот пор�док». PGN ищет и в вариантах (🔀 в колонке «Ход»; `board-search.md` пи�ал ⑂, в коде 🔀 и ↪ вме�то ⤳ — верны значки кода), ChessBase — только о�новную линию. Это различие данных, и tooltip колонки «Ход» уже его объ��н�ет. +- **Книги:** продолжени� «N глав» без результатов и Эло, е�ли у большин�тва партий нет результата (правило `SmallBoard::books`: решённых < половины). Считает�� при подготовке таблицы запи�ей PGN (`Catalog::books`). У ChessBase — в�егда партии: учебники ChessBase приход�т как `.cbv` и перевод�т�� в PGN, а у большой `.cbh` неполных результатов меньшин�тво. +- **Подготовка таблицы позиций.** Таблица �троит�� при первом и�пользовании до�ки — первый пои�к или продолжени� начальной позиции — один раз за �еан� (0,12 � на 33 640 парти�х). Отдельной �троки, как у у�корител� ChessBase, нет: подготовка — ча�ть первого пои�ка. В обла�ти продолжений вме�то «Считаю… N %» �тоит «Готовлю пои�к по позици�м (один раз)… N %». Правило 300 м� то же, по�тому на 0,12 � надпи�ь не мелькнёт; таблица затемн�ет�� через 150 м�, как в�егда. Та же таблица �лужит вкладке «Справочник». +- **�е хватает пам�ти** (`positions_blocked`). Проверка — перед запу�ком пои�ка, не каждый кадр. + - Панель до�ки: �трока предупреждени� (�уще�твующий тек�т «�е хватает пам�ти… нужно ещё около N МБ», цвет предупреждени�) и кнопка «Повторить» (реализаци�: короче, тек�т выше уже говорит «попробуйте ещё раз»). Строка �тоит над до�кой, во в�ю ширину панели. + - До�ка о�таёт�� рабочей: ходы делают��, лини� ра�тёт. Продолжени�: «—». + - Чип: «Позици�: 1.e4 c5 ⚠», tooltip «�е применена: не хватает пам�ти дл� пои�ка по позици�м». + - Таблица показывает выборку по фильтрам без позиции, без колонки «Ход»; �чётчик — по фильтрам (без других у�ловий — «33 640 партий», не «найдено 33 640 из 33 640»). Пор�док — выбранный пользователем или пор�док базы по умолчанию (№ � / Дата �), **не** «�ильнейшие �верху»: позици� не применена, и молчалива� �ортировка по Эло без �трелки выгл�дит �лучайной. Результат прежней позиции не показывает�� никогда. + - Повторна� проверка — по кнопке и при �ледующем ходе на до�ке (одна проверка на ход). + - Фильтры панели и бы�трый пои�к работают полно�тью: таблица позиций им не нужна. + +### 9.10. Клавиатура + +| Клавиша | Где | Дей�твие | +| --- | --- | --- | +| `Ctrl+F` | библиотека, люба� база | фоку� в бы�трый пои�к, тек�т выдел�ет�� целиком | +| `Ctrl+F` | в бы�тром пои�ке | панель «Фильтры» (ра�крыть, е�ли �крыта или показана до�ка) и фоку� в «Игрок». Tooltip пои�ка: «Ctrl+F; ещё раз — фильтры» | +| `Esc` | бы�трый пои�к | непу�той — очи�тить (у�ловие �нимает�� �разу), пу�той — фоку� в таблицу | +| `↓` / `↑`, `PgUp` / `PgDn` | бы�трый пои�к | выделение в таблице (как �ейча� у PGN) | +| `Enter` | бы�трый пои�к | открыть выделенную партию; без выделени� — ничего (§4.8) | +| `Tab` | шапка | бы�трый пои�к → пол� панели �верху вниз → таблица | + +О�тальные клавиши — §5 и `board-search.md` §5, одинаково дл� в�ех баз: `Ctrl+B`, `Ctrl+Shift+Backspace` (в�ё, включа� пои�к и позицию), `Ctrl+Backspace` (позици�) и прочие. + +### 9.11. Чего у PGN нет и как �то �крыто + +| Элемент | ChessBase | PGN | +| --- | --- | --- | +| Подпи�ь формата в шапке | «ChessBase, только чтение» | «PGN, кодировка UTF-8» / «PGN, кодировка windows-1251» (реализаци�: одна форма дл� любой кодировки); у переведённых — «ChessBase CBV, только чтение» (как �ейча�) | +| «⟳ �овые партии» | — | только у �качанных баз, в шапке, как �ейча� | +| Строка у�корител� «У�кор�ю пои�к по �той базе (один раз)…» | е�ть, когда нужна | нет; вме�то неё подготовка внутри первого пои�ка (§9.9) | +| «показывать тек�ты» | е�ли е�ть тек�ты | только у переведённых из ChessBase � тек�тами (§9.4) | +| ECO «960», �водка Chess960 | е�ть | нет (колонка ECO показывает тег как е�ть; пои�к по позиции дл� таких партий — без изменений против нынешнего) | +| Варианты в пои�ке по позиции | только о�новна� лини� | и варианты (🔀) | +| Замечани� импорта `⚠ N`, ✓ про�мотрено, 🔒 на карточке | — | без изменений | + +Элемент, которого у базы нет, не ри�ует��. �еактивных �лементов � объ��нением «у PGN �того нет» нет. Пол� фильтра, которых у конкретных партий нет (ECO, комментатор), к �тому не отно��т��: они видны в�егда (§9.3). + +### 9.12. Сохранение + +Как в §7 и `board-search.md` §4.12. Фильтры, **бы�трый пои�к**, позици�, �ортировка, права� панель и выделение хран�т�� дл� каждой базы в пределах �е��ии. Сейча� тек�т пои�ка PGN общий (`Library::search`) и переходит в другую базу — �то и�правл�ет��. Между запу�ками фильтры и пои�к не �охран�ют��; ширина панелей запоминает��, как �ейча�. + +### 9.13. Вопро�ы владельцу + +1. **Бы�трый пои�к и у баз ChessBase (Mega)?** Рекомендую да: один �кран без и�ключений. Ранний довод против (§0) �н�т: пои�к — обычное у�ловие � чипом и �чётчиком, неожиданных выборок нет. Проход по Mega — около �екунды, � тем же прогре��ом. �льтернатива — поле только у PGN; тогда �краны различают�� одним �лементом. +2. **`Ctrl+F` ведёт в бы�трый пои�к, а повторное `Ctrl+F` — в «Игрок»?** Рекомендую да. Сейча� у ChessBase `Ctrl+F` ведёт в «Игрок», у PGN — в пои�к, а одна клавиша должна делать одно. �льтернатива — `Ctrl+F` в�егда в «Игрок», в пои�к — мышью. diff --git a/docs/design/library-layout.md b/docs/design/library-layout.md new file mode 100644 index 0000000..0aa7414 --- /dev/null +++ b/docs/design/library-layout.md @@ -0,0 +1,395 @@ +# Библиотека: дей�тви� полки, бы�трый пои�к, «+ Парти�» + +Стату�: проект дизайнера, 2026-10-25, **не утверждён**. Три �в�занных вопро�а владельца об �кране «Библиотека» (полка карточек �верху, таблица выбранной базы, панель фильтров �права): + +1. Убрать «+ Добавить базу», «✚ �ова� база», «� Онлайн-партии» из общего р�да � карточками баз в отдельную зону. +2. �ужна ли �трока бы�трого пои�ка над таблицей, когда е�ть панель фильтров (задача № 8 в `docs/dev/tasks.md`, `large-databases.md` §9.2). +3. Кнопка «добавить партию в �ту базу» р�дом � таблицей: нова� парти�, прив�занна� к выбранной базе, Ctrl+S пишет пр�мо в неё. + +Опирает�� на код: `apps/desktop/src/library.rs` (`show` — под�чёт `card_rows`, `shelf`, `side_card_widths`, `db_card`, `compact_shelf`, `shelf_buttons`), `large_db.rs` (`table` — шапка и пу�та� база, `search_field`, `pane_switch`), `app.rs` (`new_game`, `open_chooser`, `add_current_to`). Об�зательные правила узких окон — `narrow-windows.md` (§0, §2.4, §2.5); �вои базы — `own-databases.md`. Снимки 0.17-dev: `own_shelf.png`, `own_empty.png`, `own_shelf640.png`, `r_new.png`, `l_1400x1000.png`, `l_640x1000.png` (scratchpad разработчика `dev2/`). + +Размеры — логиче�кие точки egui. Тек�ты — по-ру��ки, в �кобках ключ `tr(...)`; �уще�твующие ключи помечены «(е�ть)». + +**Макеты.** Ширина 1400 нари�ована из ра�чёта 14 точек на знак (100 знаков), ширина 640 — 10 точек на знак (64 знака). Значки в ASCII опущены там, где ломают выравнивание; в �пецификации они названы �вно. «2 базы» — Петров, Мои партии; «12 баз» — Петров, Мои партии, Сицилиан�ка�, Гран-при РШШ, Alekhin, Anand 01-14, Дворецкий, Тренировки, Турнир 2025, Ученики, Каро-Канн, Эндшпиль. + +## 0. Что уже решено и что из �того �ледует + +- **Решение владельца: �пи�ок «Добавить в базу» показывает только пополн�емые базы.** Серые �троки `own-databases.md` §3.3 и колонка «В �пи�ке баз» таблицы §5 уход�т. След�тви�, которые нужно уче�ть разработчику: + - �трока базы в другой кодировке вела в «Сделать копию в UTF-8…»; �тот вход о�таёт�� только в меню карточки (§5.3 там уже преду�матривал его) — пункт «Сделать копию в UTF-8…» в меню карточки PGN в другой кодировке об�зателен; + - когда пополн�емых баз нет, работает пу�тое �о�то�ние �пи�ка §3.3 («Своих баз пока нет…» и «✚ �ова� база…» главной кнопкой) — даже е�ли на полке е�ть Mega и онлайн-базы; + - предложение (не об�зательно): под �пи�ком, е�ли на полке е�ть непополн�емые базы, одна �трока �лабым тек�том «Базы ChessBase, � Lichess и Chess.com и в �тарой кодировке �юда не добавл�ют��» (`ChessBase, Lichess / Chess.com and legacy-encoding databases cannot take games`). Отвечает на вопро� «куда дела�ь мо� база» без �ерых �трок. +- Этот же принцип «чего нет — не ри�уем» (`own-databases.md` §1.5) определ�ет поведение кнопки «+ Парти�» у непополн�емой базы (§3.4 ниже): её нет. + +## 1. Дей�тви� полки в отдельной зоне + +### 1.1. Что �ейча� и в чём проблема + +``` +1400, 2 базы — �ейча� +Базы [�ова� парти�] [В�тавить PGN] [�а�тройки] +┌───────────� ┌───────────� ┌──────────� ┌──────────� ┌───────────� +│Петров │ │Мои партии │ │ + Добавить│ │ ✚ �ова� │ │ Онлайн- │ +│12 партий │ │48 партий │ │ базу │ │ база │ │ партии │ +└───────────┘ └───────────┘ └──────────┘ └──────────┘ └───────────┘ +``` + +- Три контурные карточки �то�т в одном потоке � базами и перено��т�� вме�те � ними (`own_shelf640.png`: втора� �трока «Anand 01-14 · + Добавить базу · ✚ �ова� база»). Ме�то дей�тви� зави�ит от чи�ла баз и ширины окна — глазу не за что зацепить��. +- Кажда� из них занимает ме�то карточки (150–166 точек). При 1400 полна� полка вмещает 14 �лементов в два р�да, но 3 из них — кнопки: компактна� полка включает�� уже на **12-й** базе. При 640 компактна� полка включает�� на **4-й** базе (без кнопки онлайн — на 5-й). +- Контурна� карточка в р�ду закрашенных выгл�дит «пу�той базой», а не командой; при �том три команды визуально ве�омее �амих баз. + +### 1.2. Варианты + +**Вариант �. Колонка дей�твий �лева от карточек.** Три �троки-кнопки по 20 точек одна под другой (вме�те 64 = вы�ота карточки), ширина 150, тонка� вертикальна� черта, �права — поток карточек. + +``` +1400, 2 базы +Базы [�ова� парти�] [В�тавить PGN] [�а�тройки] + + Добавить базу │ ┌───────────� ┌───────────� + ✚ �ова� база │ │Петров │ │Мои партии │ + Онлайн-партии │ │12 партий │ │48 партий │ + │ └───────────┘ └───────────┘ + +1400, 12 баз (6 в р�ду — 2 р�да) + + Добавить базу │ ┌───────────� ┌───────────� ┌───────────� ┌───────────� ┌───────────� ┌──────────� + ✚ �ова� база │ │Петров │ │Мои партии │ │Сицилиан�ка│ │Гран-при │ │Alekhin │ │Anand 01-1│ + Онлайн-партии │ └───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘ └──────────┘ + │ ┌───────────� … ещё 5 +``` + +``` +640, 2 базы 640, 12 баз → компактна� полка (как �ейча�) +Базы [�ова� парти�] [В�тавить PGN] [�а�тр.] [Петров ▾] [+ ▾] [�] [�ова� парти�] [В�тавить] [⚙] + + Добавить базу │ ┌─────────────────� ┌───── + ✚ �ова� база │ │Петров │ │Мои п � втора� карточка уже не входит в р�д: + Онлайн-партии │ │12 партий │ │ 624 − 150 − 17 = 457 → 2 карточки (396) + │ └─────────────────┘ └───── +``` + +**Вариант Б. Колонка дей�твий �права.** То же, но колонка прижата к правому краю, под кнопками «�ова� парти� · В�тавить PGN · �а�тройки». В�е команды �крана �обирают�� в правом верхнем углу, базы — �лева. + +``` +1400, 2 базы +Базы [�ова� парти�] [В�тавить PGN] [�а�тройки] +┌───────────� ┌───────────� │ + Добавить базу +│Петров │ │Мои партии │ │ ✚ �ова� база +│12 партий │ │48 партий │ │ Онлайн-партии +└───────────┘ └───────────┘ │ + +640, 2 базы +Базы [�ова� парти�] [В�тавить PGN] [�а�тр.] +┌─────────────────� ┌─────────────────�│ + Добавить +│Петров │ │Мои партии ││ ✚ �ова� база � колонка 150 + 2 карточки = 571 из 624: +│12 партий │ │48 партий ││ Онлайн-парт третьей карточке ме�та нет +└─────────────────┘ └─────────────────┘│ +``` + +**Вариант В. Дей�тви� в �троке заголовка, �разу по�ле «Базы».** Строка «Базы … �ова� парти� · В�тавить PGN · �а�тройки» уже е�ть и в �ередине пу�та. Слева в ней — то, что делают � базами, �права — то, что делают � парти�ми и программой. Р�д карточек — только базы. + +``` +1400, 2 базы +Базы [+ Добавить базу] [✚ �ова� база] [Онлайн-партии] [�ова� парти�] [В�тавить PGN] [�а�тройки] +┌───────────� ┌───────────� +│Петров │ │Мои партии │ +│12 партий │ │48 партий │ +└───────────┘ └───────────┘ + +1400, 12 баз (7 в р�ду — 2 р�да, полна� полка о�таёт��) +Базы [+ Добавить базу] [✚ �ова� база] [Онлайн-партии] [�ова� парти�] [В�тавить PGN] [�а�тройки] +┌───────────� ┌───────────� ┌───────────� ┌───────────� ┌───────────� ┌───────────� ┌───────────� +│Петров │ │Мои партии │ │Сицилиан�ка│ │Гран-при РШ│ │Alekhin │ │Anand 01-14│ │Дворецкий │ +│12 партий │ │48 партий │ │31 парти� │ │33 640 парт│ │267 партий │ │не загружен│ │не загружен│ +└───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘ +┌───────────� ┌───────────� ┌───────────� ┌───────────� ┌───────────� +│Тренировки │ │Турнир 2025│ │Ученики │ │Каро-Канн │ │Эндшпиль │ +└───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘ +``` + +``` +640, 2 базы (дей�тви� баз �вёрнуты в «+ ▾», как в компактной полке) +Базы [+ ▾] [�] [�ова� парти�] [В�тавить PGN] [⚙] +┌─────────────────� ┌─────────────────� +│Петров │ │Мои партии │ +│12 партий │ │48 партий │ +└─────────────────┘ └─────────────────┘ + +640, 12 баз (4 р�да > 2 → компактна� полка, без изменений) +[Петров ▾] [+ ▾] [�] [�ова� парти�] [В�тавить PGN] [⚙] +``` + +### 1.3. Оценка + +| Критерий | �. Колонка �лева | Б. Колонка �права | В. Строка заголовка | +|---|---|---|---| +| �аходимо�ть | хороша�: первое, что видит глаз при чтении �лева | �редн��: угол �крана, р�дом � другими командами; в широком окне далеко от карточек | хороша� дл� привыкшего; дл� новичка кнопки мельче карточек — компен�ирует�� пу�той полкой � крупными карточками (§1.5) | +| Узкие окна (`narrow-windows.md` §2.5) | хуже �егодн�шнего: колонка 167 точек отнимает карточку в каждом р�ду; при 640 — 2 карточки в р�д, компактна� полка уже � 5-й базы | так же, как � | лучше �егодн�шнего: р�д целиком под базы; при 640 — 3 в р�д, компактна� � 7-й базы; при 1400 — � 15-й | +| Вы�ота | при 2 базах — один р�д везде | так же | при 640 и 2–3 базах — один р�д (�егодн� два: −72 точки, +3 �троки таблицы) | +| Клавиатура | Tab: дей�тви� → карточки | Tab: карточки → дей�тви� (колонка ри�ует�� по�ледней) или наоборот при правой ра�кладке — пор�док не �овпадает � видом | Tab: «Базы»-дей�тви� → правые кнопки → карточки; �овпадает � пор�дком чтени� | +| Визуальный шум | нова� колонка � вертикальной чертой — новый тип �лемента | три команды + три команды в одном углу, две колонки кнопок разного вида | +3 кнопки в �уще�твующей �троке; новых типов �лементов нет | +| Согла�ованно�ть | колонки нет больше нигде | то же | **та же �труктура, что у компактной полки**: «база(ы) · + · � · … · правые кнопки». Полна� и компактна� полки различают�� только тем, как показаны базы | +| Сложно�ть | р�д карточек � правой зоной фик�ированной ширины | то же + выравнивание под шапкой �права | проще �егодн�шнего: из потока уход�т три о�обые карточки, `card_rows` �читает только базы | + +**Рекомендаци� — вариант В.** Это и е�ть «отдельна� зона �лева, отдельно от баз»: она в �троке заголовка, а не р�дом � р�дом карточек, по�тому ни одной карточке не мешает. Главные доводы — узкое окно (� и Б отбирают по карточке в каждом р�ду, а ча�тое ме�то владельца — половина 4K ≈ 960) и одинакова� �труктура полной и компактной полки. Един�твенный мину� В — кнопки меньше карточек — закрыт там, где он важен: у новичка � пу�той полкой (§1.5). + +### 1.4. Спецификаци� варианта В + +**Строка заголовка полной полки** (�лева направо): + +| Элемент | Подпи�ь | Под�казка | Клавиша | Дей�твие | +|---|---|---|---|---| +| заголовок | «Базы» (`Databases`, е�ть) | — | — | — | +| от�туп | 16 | | | | +| кнопка | «+ Добавить базу» (`+ Add database`, е�ть) | «Открыть PGN, ChessBase (.cbh, .cbv) или архив (.zip, .7z) (Ctrl+O)» (е�ть) | Ctrl+O | `AddDatabases` | +| кнопка | «✚ �ова� база» (`✚ New database`, е�ть) | «Пу�той PGN-файл дл� �воих партий (Ctrl+Shift+N)» (е�ть) | Ctrl+Shift+N | `NewDatabase` | +| кнопка, только при `self.online` | «� Онлайн-партии» (`� ` + `Online games`, е�ть) | «Скачать партии любого игрока по нику в базу: �вои, ученика, �оперника» (е�ть) | нет | `OnlineGames` | +| гибкий промежуток | | | | | +| права� группа | «♟ �ова� парти� · 📋 В�тавить PGN · ⚙ �а�тройки» и кнопка обновлени� — **без изменений** | | | | + +- Вид кнопок — обычный `ui.button`, как у правой группы (тот же размер, фон, вы�ота `interact_size.y`). Контурные карточки 150 × 64 из р�да удал�ют��; `side_card_widths` больше не нужен дл� полной полки. +- Промежуток между кнопками — `item_spacing.x`, как в правой группе. Между левой и правой группой — не меньше 24 (иначе группы читают�� как одна). +- **Загрузка онлайн-партий** (�егодн� — втора� �трока карточки «загрузка… N»): �права от кнопки «� Онлайн-партии» �пиннер 14 и �лабым тек�том чи�ло �качанных партий («1 240»), в под�казке кнопки — «Скачано {n}…» (`downloading… {n}`, е�ть). Ширина �пиннера и чи�ла входит в ра�чёт ра�кладки, пока загрузка идёт (переключение ра�кладки возможно один раз в начале и один раз в конце загрузки — допу�тимо, �то изменение �одержимого, а не размера окна). +- **Р�д карточек** — только базы (`databases`), карточки 190 × 64, промежуток 8, без изменений. `card_rows` в `Library::show` �читает�� по `databases.len()` карточкам ширины 190. Правило компактной полки (`narrow-windows.md` §2.5) прежнее: «больше двух р�дов», вы�ота `< 600`, до�ка пои�ка при вы�оте `< 760`. + +**Сужение �троки заголовка** (ширины — из тек�тов, как `shelf_buttons_w`; решение — функци� ширины, без ги�терези�а): + +1. В�ё помещает�� — в�ё подпи�ано. +2. �е помещает�� — **лева� группа �ворачивает��** в «+ ▾» и «�» точно как в компактной полке: меню «Добавить базу… Ctrl+O» (`Add database…`, е�ть) и «�ова� база… Ctrl+Shift+N» (`New database…`, е�ть), кнопка «�» � прежней под�казкой. Сначала лева�, потому что базы добавл�ют редко, а «�ова� парти�» нужна каждый день. +3. В�ё ещё не помещает�� — права� группа �тановит�� значками «♟ 📋 ⚙» (�уще�твующее правило §2.5). +4. �е помещает�� и так (уже 640 — только в тайлинговом менеджере) — заголовок «Базы» �крывает��. + +Ориентиры (проверить по измерению): при 960 в�ё подпи�ано; при 640 — шаг 2 (лева� группа «+ ▾ �», права� � подпи��ми: ≈ 50 + 16 + 36 + 30 + 24 + 310 ≈ 470 из 624). + +**Компактна� полка** — без изменений (`[🗄 база ▾] [+ ▾] [�] … права� группа`). Теперь она �овпадает �о �трокой заголовка шага 2 во в�ём, кроме �пи�ка баз вме�то заголовка. + +### 1.5. Со�то�ни� + +- **Пу�та� полка** (ни одной базы): р�да карточек нет, �трока заголовка как обычно. Центральна� обла�ть вме�то �егодн�шней фразы «Выберите базу выше, добавьте PGN или начните новую партию» показывает приглашение � крупными контурными карточками — **�то и е�ть �егодн�шние карточки 150 × 64, перене�ённые туда, где они нужны новичку**: + + ``` + Баз пока нет + ┌────────────────� ┌────────────────� ┌──────────────────� + │ + Добавить базу│ │ ✚ �ова� база │ │ � Онлайн-партии │ + │ │ │ │ │Lichess·Chess.com │ + └────────────────┘ └────────────────┘ └──────────────────┘ + или ♟ �ова� парти� — без базы + ``` + + «Баз пока нет» (`No databases yet`), 16, по центру; карточки по центру, промежуток 8, отри�овка — �егодн�шн�� (контур, наведение, под�казки, «Lichess · Chess.com» второй �трокой у онлайн-карточки, только при `self.online`); ниже �лабым «или» (`or`) и кнопка «♟ �ова� парти�» (`NewGame`). При 640 три карточки (≈ 480) помещают�� в р�д; е�ли окно уже — перено��т�� (`horizontal_wrapped`, по центру). +- **�ет выбранной базы, но базы е�ть** — �егодн�шн�� фраза, заменить тек�т на «Выберите базу выше» (`Choose a database above`): добавление и нова� парти� уже видны в �троке заголовка. +- **Много баз** — компактна� полка, как �ейча�, но порог �двигает��: при 1400 — � 15-й базы (было 12), при 960 — � 9-й (было 7), при 640 — � 7-й (было � 4-й, без кнопки онлайн — � 5-й). Чи�ла — дл� �луча�, когда кнопка «Онлайн-партии» е�ть. Проверить под�чётом `card_rows` на �нимках. +- **�ет �в�зи � Lichess/Chess.com при �тарте** (`self.online == false`) — кнопки «� Онлайн-партии» нет, как �ейча�; позици� о�тальных не мен�ет�� (она по�ледн�� в группе). +- **Идёт загрузка онлайн-партий** — �пиннер и чи�ло у кнопки (§1.4). + +## 2. Бы�трый пои�к при панели фильтров + +### 2.1. Чем они на �амом деле отличают�� + +| | Бы�трый пои�к (шапка) | Панель фильтров | +|---|---|---| +| Ввод | одно поле, любые �лова, без выбора пол� | отдельное поле на каждый признак | +| Что находит | каждое �лово — в любом из полей: игроки, турнир, ме�то, комментатор, ECO, дата; «вафин 2025», «carlsen wijk» | точно: игрок и цвет, �оперник, диапазон лет, Эло � правилом, длина, результат, аннотации | +| Где виден | в�егда: при панели фильтров, при **до�ке пои�ка** (она занимает ме�то панели), в узком окне (панель там выдвижна� и закрыта) | только при открытой панели; при до�ке пои�ка — не виден вов�е | +| Ctrl+F | первое нажатие — �юда | второе нажатие — «Игрок» | + +Дублирование ча�тичное: «Игрок» в панели и �лово в пои�ке могут дать один результат. О�тальное не пере�екает��: в панели нет «любое �лово в любом поле», в пои�ке нет диапазонов, цвета, результата. + +### 2.2. Варианты + +**�. О�тавить как е�ть** (пои�к в шапке, фильтры в панели, у�лови� �кладывают��). + +``` +1400 +Гран-при_РШШ_архив_в�е_партии · PGN, UTF-8 · 33 640 партий × [Пои�к: игрок, турнир, ECO, год] [Фильтры│До�ка] +640 +Гран-при_РШ… · 33 640 партий × [Пои�к: игрок…] [Фильтры│До�ка] +``` + +**Б. Перене�ти поле в панель фильтров** — первой �трокой «Везде: [____]» над группой «Игроки»; шапка о�вобождает��. + +``` +1400 │ Везде [вафин 2025 ] +Гран-при_РШШ_архив_в�е_партии · PGN, UTF-8 · найдено 412 из 33 640 [Фильтры│До�ка]│ Игроки + │ Игрок [ ] +640 — поле внутри выдвижной панели: чтобы набрать �лово, панель надо открыть; + при включённой до�ке пои�ка пол� нет на �кране �ов�ем +``` + +**В. Убрать пои�к.** Ctrl+F �разу �тавит фоку� в «Игрок» (открыва� панель или выдвижную панель). + +``` +1400 / 640 +Гран-при_РШШ_архив_в�е_партии · PGN, UTF-8 · 33 640 партий [Фильтры│До�ка] +``` + +### 2.3. Оценка + +| Критерий | �. О�тавить | Б. В панель | В. Убрать | +|---|---|---|---| +| �аходимо�ть | поле на виду; �амый очевидный путь «найти партию» | �пр�тано в панель | «найти Вафина» — только через панель | +| Узкие окна | поле 220 → 140, уже учтено в ра�кладке шапки §2.4 | в узком окне — лишний щелчок перед каждым пои�ком | шапка �вободнее | +| До�ка пои�ка | пои�к и позици� работают вме�те («вафин» + позици�) — �ценарий тренера «как мой ученик играл �ту позицию» | при до�ке пол� нет | при до�ке нужен переход на «Фильтры» и обратно | +| Клавиатура | Ctrl+F → печатать; ещё раз — точные пол� | Ctrl+F → открыть панель → поле | Ctrl+F → «Игрок» | +| Визуальный шум | одно поле в шапке | ниже в шапке, больше в панели | меньше в�его | +| Возможно�ти | пои�к по не�кольким пол�м одной �трокой | те же | **тер�ет��**: «carlsen 2024», турнир+год, пои�к по комментатору одной �трокой | + +**Рекомендаци� — �: о�тавить оба**, задачу № 8 закрыть � ответом «пои�к — бы�трый ввод, который виден в�егда и работает вме�те � до�кой; фильтры — точна� на�тройка». Две мелкие правки, без изменени� �мы�ла: + +1. **Под�казка в узком поле.** При ширине пол� 140 тек�т «� Пои�к: игрок, турнир, ECO, год» обрезает�� на полу�лове. При 140 показывать «� Пои�к» (`� Search`), полный тек�т — в под�казке пол� перед «Ctrl+F; ещё раз — фильтры»: «Игрок, турнир, ECO, год — любые �лова. Ctrl+F; ещё раз — фильтры» (`Player, event, ECO, year — any words. Ctrl+F; again — the filters`). +2. **Пу�та� база** (0 партий): поле и переключатель по-прежнему не нужны — и�кать нечего; �м. §3.5. + +О�тальное — `large-databases.md` §9.2 без изменений. + +## 3. Кнопка «+ Парти�» у таблицы + +### 3.1. Что нужно + +Тренер выбрал базу «Петров», хочет запи�ать в неё партию. Сегодн�: «♟ �ова� парти�» → ходы → Ctrl+S → �пи�ок баз, где «Петров» выделен, только е�ли он — по�леднее назначение (`last_target`); иначе выбрать. �ужна команда, у которой назначение изве�тно � �амого начала и видно в�ё врем�. + +### 3.2. Варианты + +**�. Кнопка «+ Парти�» в шапке таблицы**, �лева от пол� пои�ка. + +``` +1400 +Петров · PGN, UTF-8 · 12 партий [+ Парти�] × [Пои�к: игрок, турнир, ECO, год] [Фильтры│До�ка] +640 +Петров · 12 партий [+ Парти�] × [Пои�к: игрок…] [Фильтры│До�ка] +640, больша� база — кнопка �жимает�� до «+» +Гран-при_РШ… · найдено 812 из 33 640 [+] × [Пои�к] [Фильтры (2)│До�ка] +``` + +**Б. Без новой кнопки: «♟ �ова� парти�» прив�зывает�� к выбранной базе �ама**, е�ли она пополн�ема�. + +``` +Базы [+ Добавить базу] [✚ �ова� база] [Онлайн-партии] [�ова� парти�] [В�тавить PGN] [�а�тройки] + ↑ при выбранной «Петров» — парти� дл� «Петров» +``` + +**В. Строка «+ �ова� парти�» в конце таблицы** (как «добавить �троку» в таблицах). + +``` +│ 12 Иванов 1650 Петров 1580 1-0 2026 │ +│ + �ова� парти� │ +``` + +### 3.3. Оценка + +| Критерий | �. В шапке | Б. �е�вна� прив�зка | В. Строка в конце | +|---|---|---|---| +| �аходимо�ть | р�дом � таблицей, у имени базы | не видна вов�е: поведение мен�ет�� от того, кака� карточка выделена | в большой базе — по�ле 33 640 �трок, не видна | +| Пон�тно�ть назначени� | под�казка и шапка партии называют базу | человек мог выбрать базу про�то по�мотреть — парти� неожиданно «принадлежит» ей; нарушает «парти� в�егда знает, где живёт» только �вно | пон�тно, но только в конце �пи�ка | +| Узкие окна | +80 точек в шапке; �жимает�� до «+» (28) по правилу §3.4 | ничего | ничего | +| Клавиатура | Tab-до�тупна | Ctrl+N мен�ет �мы�л в зави�имо�ти от выделени� | недо�тупна без прокрутки | +| Шум | одна кнопка | нет | �трока в таблице, мешает �ортировке («где конец») | +| Согла�ованно�ть | шапка — ме�то команд над таблицей (пои�к, переключатель, «⟳ �овые партии») | — | в таблице нет других �трок-команд | + +**Рекомендаци� — �.** Глобальна� «♟ �ова� парти�» о�таёт�� как е�ть (парти� без базы, Ctrl+S открывает выбор базы); «+ Парти�» — то же, но � назначением. + +### 3.4. Спецификаци� + +**Кнопка** + +- Подпи�ь «+ Парти�» (`+ Game`). �е «�ова� парти�»: в одной поло�е �крана не должно быть двух кнопок � одной подпи�ью и разным дей�твием. +- Под�казка: «�ова� парти� дл� «{name}»: Ctrl+S добавит её в �ту базу» (`A new game for “{name}�: Ctrl+S adds it to this database`). +- Вид: обычна� кнопка `ui.button`, вы�ота как у пол� пои�ка. Ме�то: шапка таблицы, права� группа �права налево — переключатель `[Фильтры│До�ка]`, поле пои�ка � `×`, от�туп 8, **«+ Парти�»**. Справа она прив�зана к полю, по�тому поле и переключатель не �двигают��, е�ть кнопка или нет. +- Клавиша: �об�твенной нет в первой вер�ии (Ctrl+N — глобальна� нова� парти�, Ctrl+Shift+N — нова� база). До�тупна по Tab. Е�ли владелец захочет клавишу — вопро� §5.3. +- Пор�док важно�ти в шапке (`narrow-windows.md` §2.4, в�тавка между пунктами 2 и 3): 1) переключатель; 2) поле пои�ка 220 → 140; **2а) «+ Парти�» → «+»** (ширина `button_w("+")`, под�казка та же); 3) �чётчик; … �лгоритм одной �троки: убрать формат → поле 220 → 140 → кнопка «+ Парти�» → «+» → им� 80 → убрать им� → две �троки. В две �троки перва� — им� (гибкое) · кнопка (� подпи�ью, е�ли помещает��, иначе «+») · поле · переключатель. Ширина кнопки входит в `right()` в `table()`; у непополн�емой базы — не входит. + +**Что делает** + +1. Как `new_game()` (пу�та� до�ка, `Date` = �егодн�, `mark_saved`) плю� **назначение** — новое поле партии `target: Option` (путь выбранной базы). И�точника (`source`) нет: парти� ещё не в базе. +2. Шапка партии, подзаголовок: первым �лементом «🗄 Петров · нова� парти�» (`{name} · new game`), � тем же приоритетом �окращени�, что «🗄 {name} · № {n}» (`own-databases.md` §3.1). �азначение видно в�ё врем�. +3. **Ctrl+S / 💾** при `source == None` и `target == Some(Петров)`, е�ли «Петров» на полке и пополн�ема�: �разу `add_current_to(Петров)` — �пи�ок баз не показывает��. Так как данные ещё не �прашивали�ь, открывает�� редактор «Данные партии» � кнопкой «Добавить в «Петров»» (`own-databases.md` §3.5); Enter — добавлено, то�т «Добавлено в «Петров» (№ 13)», `source = (Петров, 13)`, `target` очищает��, `last_target = Петров`. Дальше — обычна� парти� �воей базы: Ctrl+S замен�ет запи�ь. +4. Под�казка 💾: «Добавить в «Петров» (Ctrl+S)»; меню ☰: «Добавить в «Петров» Ctrl+S» над «Добавить в базу… Ctrl+Shift+S». +5. **Ctrl+Shift+S** — �пи�ок баз, выделена база назначени� (а не `last_target`). Выбрал другую — парти� уходит туда, `target` очищает��. +6. **Уход из изменённой партии** (`own-databases.md` §3.4): главна� кнопка «Добавить в «Петров»», о�тальные как обычно. +7. **�азначение �тало недо�тупно** до первого Ctrl+S (база убрана � полки, файл удалён или �тал непополн�емым): �лемент «🗄 Петров · нова� парти�» и�чезает, `target` очищает�� при проверке, Ctrl+S ведёт �еб� как у партии без базы (�пи�ок). Без отдельного �ообщени�: �пи�ок баз и так объ��н�ет, куда можно. +8. Парти�, в�тавленна� из буфера (📋), и парти� из «♟ �ова� парти�» назначени� не получают — как �ейча�. + +**Со�то�ни� кнопки** + +| База в таблице | Кнопка | +|---|---| +| пополн�емый PGN | видна | +| пу�та� пополн�ема� база | видна в шапке, и та же команда — главной кнопкой пу�того �о�то�ни� (§3.5) | +| ChessBase, архив, Lichess/Chess.com, PGN в другой кодировке, нет прав на запи�ь | **нет** (�огла�но решению «в �пи�ок попадают только пополн�емые» и `own-databases.md` §1.5). Поле и переключатель не �двигают�� | +| база загружает�� / ошибка / файл не найден | шапки нет — кнопки нет | +| до�ка пои�ка на ме�те таблицы (узкое окно) | видна (шапка та же) | + +Почему не �ера� � объ��нением: у непополн�емой базы «+ Парти�» нечего обещать, а един�твенный о�мы�ленный путь (�во� база) объ��н�ет�� там, где человек пытает�� пи�ать (то�т на Delete, вопро� при уходе). Е�ли владелец предпочтёт �ерую кнопку � причиной в под�казке (тек�ты §5 `own-databases.md`, колонка «�а полке и при попытке») — �то вопро� §5.2. + +### 3.5. Пу�та� база + +Сегодн� у пу�той базы шапка не ри�ует�� (`table()` возвращает�� раньше), а кнопка пу�того �о�то�ни� — обща� «♟ �ова� парти�». Приве�ти к `own-databases.md` §2.3 и к §3.4: + +``` +1400 +Мои партии · PGN, UTF-8 · 0 партий [+ Парти�] + + В базе «Мои партии» пока нет партий + [+ Парти�] Ctrl+S �охранит её �юда. Или откройте любую партию + и выберите «Добавить в базу…» (Ctrl+Shift+S) + Файл: /home/roman/Документы/ChessPenguin/Мои партии.pgn +``` + +- Шапка: им� · формат · «0 партий» · «+ Парти�». Поле пои�ка и переключатель у пу�той базы не показывают�� (и�кать нечего), панель фильтров и до�ка пои�ка тоже — на �нимке `own_empty.png` �права пу�та� панель фильтров занимает 280 точек и ничего не делает. Это от�тупление от `own-databases.md` §2.3 («ничего не пр�чет��»). Кнопка «+ Парти�» �тоит на том же ме�те от правого кра�, где у непу�той базы �тоит поле пои�ка, — �то допу�тимое �мещение: у пу�той базы других кнопок нет. При первой добавленной партии по�вл�ют�� поле, переключатель и (е�ли `pane == Filters`) панель. +- Главна� кнопка по центру — та же команда «+ Парти�». Тек�т �права: «Ctrl+S �охранит её �юда. Или откройте любую партию и выберите «Добавить в базу…» (Ctrl+Shift+S)» (`Ctrl+S will save it here. Or open any game and choose “Add to database…� (Ctrl+Shift+S)`). Замен�ет нынешнее «Добавьте: ♟ �ова� парти� или…». +- Строка «Файл: …» — �лабым, как �ейча�. + +## 4. В�ё вме�те + +``` +1400 × 1000, 2 базы +Базы [+ Добавить базу] [✚ �ова� база] [Онлайн-партии] [�ова� парти�] [В�тавить PGN] [�а�тройки] +┌───────────� ┌───────────� +│Петров │ │Мои партии │ +│12 партий │ │48 партий │ +└───────────┘ └───────────┘ +──────────────────────────────────────────────────────────────────────────┬───────────────────────── +Петров · PGN, UTF-8 · 12 партий [+ Парти�] × [Пои�к: игрок, турнир…] [Фильтры│До�ка]│ Игроки +У�ловий нет — показаны в�е партии │ Игрок [ ] +№ Белые Elo Чёрные Elo Рез. Длина ECO Турнир │ … +1 Иванов Иван 1650 Петров Пётр 1580 1-0 42 C45 Первен�тво │ +``` + +``` +1400 × 1000, 12 баз — полка в два р�да (§1.2 В), шапка таблицы та же + +640 × 1000, 2 базы +Базы [+ ▾] [�] [�ова� парти�] [В�тавить PGN] [⚙] +┌─────────────────� ┌─────────────────� +│Петров │ │Мои партии │ +│12 партий │ │48 партий │ +└─────────────────┘ └─────────────────┘ +────────────────────────────────────────────────────────────── +Петров · 12 партий [+ Парти�] × [Пои�к: игрок…] [Фильтры│До�ка] +№ Белые Elo Чёрные Elo Рез. Год +1 Иванов Иван 1650 Петров Пётр 1580 1-0 2026 + +640 × 1000, 12 баз +[Петров ▾] [+ ▾] [�] [�ова� парти�] [В�тавить PGN] [⚙] +────────────────────────────────────────────────────────────── +Петров · 12 партий [+ Парти�] × [Пои�к: игрок…] [Фильтры│До�ка] +``` + +## 5. Вопро�ы владельцу + +1. **Вариант В дл� дей�твий полки** (�трока заголовка, �ворачивание в «+ ▾» в узком окне, крупные карточки только на пу�той полке). Е�ли владелец хочет именно колонку р�дом � карточками — из � и Б лучше � (пор�док чтени� и Tab �овпадают), но в узком окне она �тоит по карточке в р�ду. +2. **«+ Парти�» у непополн�емой базы** — нет кнопки (рекомендаци�) или �ера� � причиной в под�казке. +3. **Клавиша дл� «+ Парти�».** Предлагаю без клавиши. Е�ли нужна — Ctrl+N при фоку�е в таблице? �е рекомендую: одна клавиша � двум� �мы�лами в зави�имо�ти от фоку�а. Свободной и пон�тной пары нет; лучше пу�ть под�кажет практика. +4. **Строка-по��нение под �пи�ком «Добавить в базу»** о непоказанных базах (§0) — добавить или нет. + +## 6. Что мен�ет разработчик + +1. `library.rs` `shelf()`: лева� группа кнопок в �троке заголовка (§1.4) � пор�дком �ворачивани�; удалить контурные карточки из р�да; `card_rows` — только базы; �пиннер загрузки онлайн у кнопки. +2. `library.rs` `table_area()`: пу�та� полка — приглашение � трем� карточками (§1.5), перено� их отри�овки из `shelf()`; тек�т «Выберите базу выше». +3. `large_db.rs` `table()`: кнопка «+ Парти�» (§3.4) в правой группе шапки и в ра�чёте ширины; новое дей�твие `LibraryAction::NewGameIn(PathBuf)`; пу�та� база — шапка без пол� и переключател�, без панели (§3.5); под�казка узкого пол� пои�ка (§2.3). +4. `app.rs`: `GameView.target`; Ctrl+S / 💾 / ☰ / вопро� при уходе � назначением; `open_chooser` выдел�ет `target` раньше `last_target`; проверка до�тупно�ти назначени�. +5. `game_view.rs`: �лемент подзаголовка «🗄 {name} · нова� парти�». +6. Меню карточки: «Сделать копию в UTF-8…» у PGN в другой кодировке (вход вме�то �троки �пи�ка — §0). +7. Снимки дл� проверки: 1400×1000, 960×1050, 640×1000, 640×480 — � 0, 2, 7, 12 базами; пу�та� база; непополн�ема� база (нет «+ Парти�»); идёт загрузка онлайн-партий. + +## Изменени� + +- 2026-10-25: перва� вер�и�. +- 2026-10-25: по решению владельца «♟ �ова� парти�» и «📋 В�тавить PGN» �то�т �лева, по�ле дей�твий � базами (через промежуток 16): �лева в�ё, чем наполн�ют библиотеку; �права — только программа: «⚙ �а�тройки» и кнопка обновлени�. В пу�той базе «+ Парти�» одна — главна� кнопка по�ередине (в шапке её нет). В «�овой базе» «Изменить папку…» — отдельной �трокой под «Файл:». +- 2026-10-25: по решению владельца пор�док �лева: «♟ �ова� парти�», «📋 В�тавить PGN», промежуток, затем дей�тви� � базами. Поле «�айти базу» в «Добавить в базу» — только когда предлагаемых баз больше во�ьми. diff --git a/docs/design/maia-models.md b/docs/design/maia-models.md new file mode 100644 index 0000000..47a3403 --- /dev/null +++ b/docs/design/maia-models.md @@ -0,0 +1,194 @@ +# Две модели Maia: мала� и больша� — пути пользовател� + +Стату�: проект дизайнера, 2026-10-25. **Сделано по упрощённому пути** (владелец: «задей�твуй половину �дер… чего ты паришь��», «�мотри �ам»): + +- **Сделано:** ползунок — на�то�ща� �ила 1100–2000, шаг 50; таблицы «�ила → чи�ло дл� модели» (`play.rs`, `rating_input`); правило `model_for`: больша�, е�ли е�ть, иначе мала� до 1800, иначе «Скачать и играть» (качает большую); �трока под временем, пока большой нет, видна в�егда (диалог не прыгает); реванш и игра � хода при нехватке модели открывают диалог � теми же выбором и позицией (`Dialog::for_start`); ход �читает�� на половине �дер. +- **�е делаем пока:** автоопределение �лабого компьютера, флажок «до 1800 — мала�», блок Maia в «�а�тройках», загрузка вне диалога � докачкой, пере�чёт �тарой �охранённой �илы (�бра�ывает�� на 1500). +- �иже — и�ходный проект целиком, дл� будущих шагов. О�нова — решени� владельца от 2026-10-25 (в �борке больша� Maia 79M, �качивание 315 МБ приемлемо; ползунок показывает на�то�щую �илу; мала� модель допу�тима, е�ли её «отыграть» на уровне путей) и замеры `../research/maia-strength.md` («Замер, 2026-10-25»). + +Опирает�� на код: `apps/desktop/src/play.rs` (`Dialog`, `STRENGTH_MIN/MAX`, `pause`), `maia_download.rs` (�ейча� один файл `maia3-5m.pt`, загрузка принадлежит диалогу и отмен�ет�� при его закрытии), `app.rs::start_play` / `play_next_now` (реванш, игра � хода), `settings_ui.rs` (вкладка «Движки», кнопка «⬇ Download Stockfish 19 · {mb} MB»). Дизайн диалога — `play-mode.md` §2, игра � хода — `play-from-position.md`, загрузка Stockfish — `engine-download.md`. + +**Проверено в коде:** в «�а�тройках» Maia �ейча� нет вообще — ни в �пи�ке движков, ни отдельно; �качать её можно только из диалога. Раздел 5 — новое. + +## 0. Главное + +1. **Человек выбирает �илу, а не модель.** Ползунок — на�то�ща� �ила (блиц Lichess). Кака� модель �ыграет на �том уровне — решает программа по одному правилу (§3). Слово «модель» по�вл�ет�� только там, где надо �качать или удалить файл. +2. **У каждой модели �во� таблица «на�то�ща� �ила → чи�ло, которое подаёт�� в Maia».** По�тому «Maia 1600» одинаково �ильна на малой и на большой модели; замена модели не мен�ет �илу, только «человечно�ть» и �коро�ть. +3. **Больша� модель — о�новна�.** Мала� — дл� тех, у кого она уже е�ть, у кого медленный компьютер или кто не хочет качать 315 МБ, и только до её потолка. +4. **Диалог не прыгает.** Строка �о�то�ни� над кнопками е�ть в�егда и в�егда в одну �троку; главна� кнопка по�то�нной ширины. + +## 1. Ползунок и правило выбора + +**Шкала.** Ползунок от `MIN` до `MAX` на�то�щей �илы, шаг 50 (�ейча� 100 при �жатой шкале 600–2600; в на�то�щих единицах ве�ь диапазон уже ~800, шаг 100 да�т лишь 9 положений). Черновик: **1200–2000**, верх 2100, е�ли ночной замер «только лучший ход» дл� 79M �то подтвердит (вопро� 1). �ижн�� граница — по замеру обеих моделей на низких уровн�х (�ейча� измерено только от 1100 номинала = 1310 реальных у 5M и от 1500 у 79M): **�то нужно измерить до выпу�ка**, иначе таблицы внизу �к�траполированы. + +**Потолок малой модели — 1800** (номинал 2500 → 1813, 2600 → 1786: выше она не ра�тёт). Кон�танта `SMALL_CEILING = 1800`. + +**Правило (одна функци� `choose_model(level)`, ею пользуют�� диалог, реванш и игра � хода):** + +``` +больша� е�ть и (не «�лабый компьютер» или level > 1800) → больша� +мала� е�ть и level ≤ 1800 → мала� +иначе → нужна загрузка: + level > 1800 или малой нет и компьютер не �лабый → больша� (315 МБ) + иначе → мала� (21 МБ) +``` + +Модель фик�ирует�� в начале партии и до её конца не мен�ет�� (даже е�ли во врем� партии докачала�ь друга�). + +**Переход дл� тех, кто обновил��.** Сохранённое `settings.play.strength` было номиналом 5M; при первом чтении оно переводит�� в на�то�щую �илу по таблице 5M (1500 → 1500 по�ле округлени� до 50, 1900 → 1650, 2600 → 1800) — �оперник человека о�таёт�� таким же. Признак новой шкалы хранит�� в на�тройках, чтобы перевод был один раз. + +## 2. Диалог «Игра � компьютером» + +### 2.1. Вид (ширина 460, как �ейча�) + +``` +│ Соперник — Maia 1650 │ +│ 1200 ���������������������������������┊░░░░░░░░░░░ 2000 │ +│ Рейтинг блица Lichess, который Maia набирает на �том │ � �лабым, 11.5 +│ уровне. │ +│ …Цвет, Врем� — без изменений… │ +│ │ +│ Больша� Maia · 315 МБ, �качивает�� один раз � huggingf… │ � �трока �о�то�ни� +│ [▌ Скачать и играть �] [ Отмена ] │ +``` + +- Заголовок «Соперник — Maia {elo}» — уже на�то�ща� �ила. Подпи�ь под ползунком мен�ет��: прежн�� «Шкала Lichess: Maia 1500 �лабее клубного игрока 1500» больше не верна. �ова�: «Рейтинг блица Lichess, который Maia набирает на �том уровне.» (`The Lichess blitz rating Maia scores at this level.`). +- **Метка 1800** (`┊`): тонка� вертикальна� ри�ка на дорожке ползунка — **только когда большой модели нет**. Отрезок 1800–MAX тогда затенён (цвет `weak`, полупрозрачна� заливка дорожки), но ползунок туда ходит �вободно. Под�казка при наведении на затенённый отрезок: «Сильнее 1800 играет больша� Maia» (`Above 1800 the large Maia plays`). Когда больша� е�ть — ни ри�ки, ни затенени�. +- **Строка �о�то�ни�** — одна �трока вы�отой 20 над кнопками, е�ть во в�ех �о�то�ни�х (�ейча� при у�тановленной Maia её нет — диалог на одну �троку ниже, чем без неё; �то и е�ть «прыжок»). Тек�т обрезает�� многоточием по ширине, полный — в под�казке. Прогре��-поло�а занимает ту же �троку той же вы�оты. +- **Главна� кнопка по�то�нной ширины:** `min_width` = ширина �амой длинной из её подпи�ей на текущем �зыке («Играть», «Скачать и играть», «Повторить»). «Отмена» не �двигает��. + +### 2.2. Со�то�ни� �троки и кнопки + +| Ситуаци� | Строка �о�то�ни� | Главна� кнопка | +|---|---|---| +| Модель дл� уровн� е�ть, больша� | «Больша� Maia» �лабым (`Large Maia`) | «Играть» | +| Е�ть только мала�, уровень ≤ 1800 | «Мала� Maia. Больша� играет человечнее: [�качать · 315 МБ]» | «Играть» | +| Е�ть только мала�, уровень > 1800 | «Сильнее 1800 играет больша� Maia: 315 МБ, один раз.» | «Скачать и играть» | +| �ет ничего (§2.3) | «Больша� Maia · 315 МБ, один раз, � huggingface.co (файл авторов). [Мала� · 21 МБ, до 1800]» | «Скачать и играть» | +| Идёт загрузка | поло�а «120 из 315 МБ · 38 %» и �права кнопка «×» (отменить) | «Играть», е�ли дл� уровн� модель уже е�ть; иначе неактивна | +| Проверка | �пиннер, «Проверка…» | неактивна (или «Играть», как выше) | +| Ошибка | кра�ным, коротко (§6) | «Повторить» | +| Слабый компьютер, малой нет (§4) | «Зде�ь больша� Maia ходит ≈ {s} �. [Мала� бы�трее · 21 МБ]» | «Играть» | + +`[…]` — ��ылка (`egui::Link`), не кнопка: второ�тепенное дей�твие, без �мены главной кнопки. С�ылка на загрузку малой видна только при уровне ≤ 1800; выше — её ме�то занимает тек�т �троки (вы�ота та же). + +### 2.3. Путь 1 — перва� игра, ничего не �качано + +**Рекомендаци�: главна� кнопка в�егда �качивает большую (315 МБ); мала� — ��ылкой в �троке �о�то�ни�, только при уровне ≤ 1800.** Модель не выбирает�� �вно переключателем: по умолчанию (1500) человек видит одну главную кнопку и одно чи�ло. + +Почему так: владелец решил, что о�новна� — больша�; она человечнее на в�ех уровн�х, и � ней ползунок работает целиком, без затенени�. С�ылка на 21 МБ — выход дл� медленного интернета или �тарого ноутбука, не нав�занный выбор. Почему не «≤ 1800 → мала� автоматиче�ки»: тогда большин�тво (ученики играют ниже 1800) никогда не получит лучшую модель, а затенённый отрезок �танет по�то�нной ча�тью диалога. + +По�ле нажати� «Скачать и играть» парти� начинает�� �ама, когда файл проверен (как �ейча�: «запрошенное дей�твие»). Пока качают�� 315 МБ, человек может закрыть диалог — загрузка **не отмен�ет��** (§2.4). + +### 2.4. Путь 2 — е�ть только мала� (в�е, кто обновил��) + +- Уровень ≤ 1800: «Играть» �разу, мала� модель. В �троке — ненав�зчивое предложение большой (таблица §2.2). Больше ничего не мен�ет��: по�ле обновлени� у человека тот же �оперник (перевод шкалы, §1). +- Ползунок за 1800: отрезок затенён, �трока «Сильнее 1800 играет больша� Maia…», кнопка «Скачать и играть». Вернул ползунок ≤ 1800 — �нова «Играть». +- **Во врем� загрузки большой можно играть до 1800 на малой.** Дл� �того загрузка принадлежит приложению, а не диалогу (�ейча� `Dialog.download` отмен�ет�� в `Drop` при закрытии): закрытие диалога и начало партии её не прерывают; прогре�� виден в �троке �о�то�ни� при �ледующем открытии диалога и в «�а�тройках» (§5). Отмен�ет только «×». +- Загрузка закончила�ь, пока диалог закрыт: то�т «Больша� Maia �качана» (`Large Maia downloaded`). Идуща� парти� продолжает�� на �воей модели. Е�ли диалог открыт и был нажат «Скачать и играть» — парти� начинает�� �ама; е�ли человек за �то врем� закрыл диалог — нет. + +### 2.5. Путь 3 — е�ть только больша� (или обе) + +**Рекомендаци�: больша� играет на в�ех уровн�х; мала� и�пользует�� только при «�лабом компьютере» (§4) или е�ли большой нет.** Мала� �ама на низких уровн�х не подключает��. + +Почему: (1) больша� человечнее везде (57,1 % против 55,4 % �овпадений � ходом человека) — а �мы�л Maia именно в человечно�ти; (2) один �оперник дл� в�ех уровней: ученик, переход�щий � 1700 на 1850, не замечает «�мены характера»; (3) �коро�ть на обычном компьютере (0,2–0,4 �) пр�чет�� внутри паузы, которую Maia и так «думает» (`pause`: не меньше 0,4 �, обычно �екунды), — у�корение малой модели человек не увидит. Удал�ть малую при наличии большой не предлагаем: 21 МБ ничего не �то�т, и она нужна как запа�на�. + +## 3. Где дей�твует правило + +Диалог, реванш и игра � хода вызывают одну `choose_model(level)` (§1); ни одно ме�то не выбирает модель �амо. + +## 4. Слабый компьютер + +**Рекомендаци�: определ�ть автоматиче�ки замером, � ручным выключателем в «�а�тройках».** + +- **Замер:** при первой загрузке большой модели (�тади� «Проверка» по�ле �качивани�, и при первом запу�ке партии на �той вер�ии программы) — три прогона на начальной позиции � тем чи�лом потоков, � каким играет парти�; медиана �охран�ет�� в на�тройки (`maia_large_ms`). Порог «�лабый» — **1,0 � на ход** (больше — паузы Maia в дебюте, где они ×0,3, заметно зат�гивают��). Повторный замер — по�ле �мены вер�ии программы (могла �менить�� параллельно�ть). +- **Что мен�ет��:** флажок «До 1800 — мала� модель» (§5) включает�� �ам. По правилу §1 до 1800 играет мала�, выше — больша� (медленно, но иначе нужной �илы нет). Е�ли малой нет — �трока �о�то�ни� предлагает её ��ылкой (таблица §2.2), «Играть» о�таёт�� активной: �ыграть на большой можно, про�то дольше. +- Дл� уровн� выше 1800 на �лабом компьютере �трока: «Зде�ь больша� Maia ходит ≈ {s} �.» — че�тное ожидание; ча�ы Maia �тим не штрафуют�� (`Clock::moved` берёт её паузу, а не врем� �чёта), так что �то вопро� терпени�, а не че�тно�ти партии. +- Без переключени� «на лету»: модель выбрана на в�ю партию. + +Почему не только ручна� на�тройка: человек не знает, «�лабый» ли у него компьютер; почему не только автомат: замер может ошибить�� (фонова� нагрузка во врем� проверки), выключатель �то и�правл�ет. + +## 5. �а�тройки → Движки: блок «Maia» + +Maia — не UCI-движок и не может анализировать, по�тому **не в �пи�ке движков**, а отдельным блоком под ним (по�ле «+ Выбрать файл движка…»), � заголовком как у групп вкладки: + +``` +Maia — �оперник в игре + Больша� (79M) · 315 МБ у�тановлена [ Удалить ] + Мала� (5M) · 21 МБ не �качана [ ⬇ Скачать ] + [x] До 1800 — мала� модель (бы�трее на �лабом компьютере) + Больша� на �том компьютере: ≈ 0,3 � на ход. � �лабым +``` + +- Три колонки �еткой (`egui::Grid`): название � размером, �о�то�ние, кнопка. Ширина кнопки — по �амой длинной подпи�и («Удалить» / «⬇ Скачать»), чтобы �троки не прыгали. +- Со�то�ни�: «у�тановлена» (`installed`), «не �качана» (`not downloaded`), при загрузке — поло�а � «×» на ме�те �о�то�ни� и кнопки (тот же вид, что у Stockfish, `download_progress`), «повреждена — �качайте �нова» кра�ным (е�ли файл е�ть, но не загрузил��: �ейча� `forget_broken` молча его удал�ет; удал�ть можно, но �казать). +- Флажок активен, только когда у�тановлены обе модели; иначе неактивен � под�казкой «�ужны обе модели» (`Both models are needed`). Строка �о �коро�тью — только по�ле замера. +- Удалить нельз� модель, на которой идёт парти�: кнопка неактивна, под�казка «Идёт парти� � �той моделью» (`A game with this model is in progress`). +- Удаление большой — � подтверждением (малой — без, 21 МБ): «Удалить большую Maia? Дл� игры �ильнее 1800 её придёт�� �качать �нова (315 МБ).» Кнопки «Удалить» · «Отмена». + +## 6. Ошибки, отмена, ме�то на ди�ке + +- **Перед загрузкой** проверить �вободное ме�то (размер + 10 %). �е хватает — загрузка не начинает��, �трока кра�ным: «Мало ме�та: нужно 315 МБ, �вободно {n} МБ» (`Not enough space: {need} MB needed, {free} MB free`). Главна� кнопка «Повторить». +- **Ошибка �ети / обрыв:** «�е удало�ь �качать: нет �оединени�» (`Download failed: no connection`), подробно�ти — в под�казке �троки. Дл� 315 МБ обрыв веро�тен: рекомендую при «Повторить» докачивать `.part` запро�ом `Range` (huggingface.co его поддерживает — проверить), а удал�ть `.part` только при отмене или не�овпадении SHA-256. +- **Файл не тот** (SHA-256): «Файл не �овпал � опубликованным — �качайте �нова» (�трока уже е�ть: `The file is not the published one`), `.part` удал�ет��. +- **Отмена:** «×» у поло�ы; `.part` удал�ет��, �трока возвращает�� к предложению. Закрытие диалога и Esc загрузку не отмен�ют (§2.4). +- **Две загрузки �разу** (больша� и мала�) — можно, �то разные файлы; кажда� �о �воей поло�ой в «�а�тройках». В �троке диалога — загрузка той модели, что нужна дл� текущего уровн�. + +## 7. Игра � хода и реванш + +- Обе идут через `choose_model(level)` � тем же уровнем. Модель е�ть — парти� начинает�� �разу, как �ейча�. +- �ужной модели нет (удалили между парти�ми; либо уровень > 1800, а большой нет): **открывает�� диалог � тем же уровнем, цветом и, дл� игры � хода, той же позицией** (`Dialog::new_from`), в �о�то�нии «Скачать и играть». �икогда не подмен�ть уровень молча на до�тупный. +- **�айдено в коде:** `app.rs::start_play` при от�ут�твии ве�ов открывает `Dialog::new` — позици� игры � хода тер�ет��, а реванш открывает диалог � �охранёнными, а не текущими на�тройками. �ужно передавать `start.from` (и уровень реванша) в диалог. + +## 8. У�тойчиво�ть ра�кладки — �водка + +- Строка �о�то�ни� в�егда е�ть, в�егда одна �трока (обрезка + под�казка); поло�а загрузки — той же вы�оты. +- Главна� кнопка — по�то�нной ширины; «Отмена» на ме�те. +- Ри�ка 1800 и затенение — внутри дорожки ползунка, не добавл�ют �трок. +- С�ылки «�качать большую / малую» — внутри �троки �о�то�ни�, не отдельной �трокой. +- Снимки дл� проверки: 1400×900 и 640×480 (`play-mode.md` §7) в �о�то�ни�х: ничего нет; только мала� ≤ 1800; только мала� > 1800; загрузка; ошибка; обе модели. Блок «Maia» в на�тройках — у�тановлена/не �качана/загрузка. + +## 9. Строки дл� перевода (9 �зыков) + +Глифы: ✓ ✕ ✗ + � в шрифте нет — «у�тановлена» �ловом, отмена «×», «⬇» уже и�пользует�� у Stockfish. + +| English (ключ) | Ру��кий | +|---|---| +| `The Lichess blitz rating Maia scores at this level.` | Рейтинг блица Lichess, который Maia набирает на �том уровне. | +| `Above 1800 the large Maia plays` | Сильнее 1800 играет больша� Maia | +| `Large Maia` / `Small Maia` | Больша� Maia / Мала� Maia | +| `Small Maia. The large one plays more like a human:` | Мала� Maia. Больша� играет человечнее: | +| `download · {mb} MB` | �качать · {mb} МБ | +| `Above {elo} the large Maia plays: {mb} MB, downloaded once.` | Сильнее {elo} играет больша� Maia: {mb} МБ, один раз. | +| `Large Maia · {mb} MB, downloaded once from huggingface.co (the authors' file).` | Больша� Maia · {mb} МБ, �качивает�� один раз � huggingface.co (файл авторов). | +| `Small · {mb} MB, up to {elo}` | Мала� · {mb} МБ, до {elo} | +| `{done} of {total} MB · {pct} %` | {done} из {total} МБ · {pct} % | +| `Retry` | Повторить | +| `Here the large Maia takes ≈ {s} s a move.` | Зде�ь больша� Maia ходит ≈ {s} �. | +| `The small one is faster · {mb} MB` | Мала� бы�трее · {mb} МБ | +| `Large Maia downloaded` | Больша� Maia �качана | +| `Maia — the opponent in a game` | Maia — �оперник в игре | +| `Large (79M) · {mb} MB` / `Small (5M) · {mb} MB` | Больша� (79M) · {mb} МБ / Мала� (5M) · {mb} МБ | +| `installed` / `not downloaded` | у�тановлена / не �качана | +| `damaged — download it again` | повреждена — �качайте �нова | +| `Up to {elo} — the small model (faster on a slow computer)` | До {elo} — мала� модель (бы�трее на �лабом компьютере) | +| `The large one on this computer: ≈ {s} s a move.` | Больша� на �том компьютере: ≈ {s} � на ход. | +| `Both models are needed` | �ужны обе модели | +| `A game with this model is in progress` | Идёт парти� � �той моделью | +| `Delete the large Maia? To play above {elo} it will have to be downloaded again ({mb} MB).` | Удалить большую Maia? Дл� игры �ильнее {elo} её придёт�� �качать �нова ({mb} МБ). | +| `Not enough space: {need} MB needed, {free} MB free` | Мало ме�та: нужно {need} МБ, �вободно {free} МБ | +| `Download failed: {reason}` | �е удало�ь �качать: {reason} | + +Чи�ло 1800 — параметром `{elo}`, не в тек�те: потолок может �двинуть�� по�ле замеров. У�таревшие �троки: `The Lichess scale: Maia 1500 is weaker than a club player rated 1500.`, `Maia is downloaded once ({mb} MB, …)` — убрать. + +## 10. Что нужно разработчику (не владельцу) + +- Таблицы калибровки обеих моделей на в�ём диапазоне, включа� низ (�ейча� 79M измерена от 1500) — аналитик/замер. +- Загрузчик на две модели (ревизи�, файл, SHA-256, размер у каждой), владелец загрузки — приложение; докачка `Range`. +- `choose_model`, перевод �охранённой �илы на новую шкалу, замер �коро�ти, блок «Maia» в на�тройках, и�правление `start_play` (§7). + +## 11. Вопро�ы владельцу + +1. **Верх ползунка: 2000 или 2100?** Зави�ит от ночного замера «только лучший ход» дл� 79M. Е�ли наверху играть «лучшим ходом» (температура 0), Maia там менее человечна — �огла�ны ли на �то ради �илы на �амых вы�оких делени�х? +2. **Перва� загрузка:** главна� кнопка в�егда качает большую (315 МБ), мала� — ��ылкой «Мала� · 21 МБ, до 1800» (мо� рекомендаци�, §2.3). Или наоборот: до 1800 по умолчанию мала�, больша� — только когда ползунок выше? +3. **Слабый компьютер:** у�траивает ли автоматиче�кий замер � порогом 1 � на ход и флажок «До 1800 — мала� модель» в на�тройках (§4), или до�таточно одного флажка без автоматики? diff --git a/docs/design/move-notation.md b/docs/design/move-notation.md new file mode 100644 index 0000000..07661ed --- /dev/null +++ b/docs/design/move-notation.md @@ -0,0 +1,243 @@ +# Запи�ь ходов: латиница, фигурки, буквы �зыка интерфей�а + +Стату�: �пецификаци� дизайнера дл� реализации, 2026-10-21. О�нова: `docs/research/figurine-notation.md` (аналитик). Там, где документы ра�ход�т��, дей�твует �тот. Решени� ниже прин�ты дизайнером, а три вопро�а в конце о�тают�� за владельцем. + +Опирает�� на код: `settings_ui.rs` (`board_tab`: «�абор фигур», «До�ка», «�нимаци� фигур», флажки), `settings.rs` (`Settings`, `first_start()`, `#[serde(default)]`), `i18n.rs` (en ru fr de es it, англий�кий тек�т �лужит ключом, `set_lang`), `notation.rs`, `game_view.rs`, `reference.rs`, `board_search.rs`, `review.rs`. + +Размеры даны в логиче�ких точках egui. + +## 0. Главное + +1. **Это только вид на �кране.** Данные партии, PGN, буфер обмена, FEN, UCI и `[%eval]` в�егда запи�ывают�� латиницей (`Nf3`). SAN замен�ет�� в одном ме�те, при форматировании подпи�и. В данные замена не попадает никогда. +2. **Три режима, одна на�тройка:** «Латин�кие буквы», «Фигурки», «Буквы �зыка интерфей�а». +3. **Комментарии авторов не трогаем.** Е�ли в комментарии напи�ано «лучше 12.Nf3» или «12.Кf3», так и о�таёт��. +4. **Переключение дей�твует �разу,** без перезапу�ка и без повторного открыти� партии, во в�ех открытых окнах и вкладках. + +## 1. Режимы + +### 1.1. Что показывает�� + +| Режим (`MoveNotation`) | Король | Ферзь | Ладь� | Слон | Конь | Пример | +|---|---|---|---|---|---|---| +| `Latin` | K | Q | R | B | N | `Nf3 Qxd8+ e8=Q O-O` | +| `Figurine` | ♔ U+2654 | ♕ U+2655 | ♖ U+2656 | ♗ U+2657 | ♘ U+2658 | `♘f3 ♕xd8+ e8=♕ O-O` | +| `Local`, ru | Кр | Ф | Л | С | К | `Кf3 Фxd8+ e8=Ф O-O` | +| `Local`, de | K | D | T | L | S | `Sf3 Dxd8+ e8=D O-O` | +| `Local`, fr | R | D | T | F | C | `Cf3 Dxd8+ e8=D O-O` | +| `Local`, es | R | D | T | A | C | `Cf3 Dxd8+ e8=D O-O` | +| `Local`, it | R | D | T | A | C | `Cf3 Dxd8+ e8=D O-O` | +| `Local`, en | = `Latin` | | | | | | + +�еизменно во в�ех режимах: + +- пол� и вертикали �трочными латин�кими буквами: `e4`, `exd5`, `Nbd7` → `♘bd7` / `Кbd7`; +- пешка без значка и без буквы, как на Lichess и в книгах; +- рокировка `O-O` и `O-O-O` (не `0-0`); +- вз�тие `x`. Двоеточие из �тарых ру��ких книг не и�пользуем: `x` привычен в�ем, кто читает PGN, движки и Lichess, и не путает�� �о временем `[%clk 0:05:00]` в �о�едних комментари�х; +- шах `+` и мат `#`; +- нулевой ход `--`, номера ходов `12.` и `12…`, NAG и их цвета (`!`, `?!`, `+=`, `$146`). + +Фигурки ри�уют�� одним контурным �тилем дл� белых и чёрных (U+2654–2658), как на Lichess. Сплошные U+265A–265F не и�пользуем: в тёмной теме �плошна� фигурка в �ветлом цвете тек�та выгл�дит как бела�. + +### 1.2. Правило замены + +Замен�ет�� только буква фигуры: первый �имвол хода, е�ли �то `K Q R B N`, и �имвол �разу по�ле `=` при превращении. Ходы `O-O`, `O-O-O` и `--` не трогают��. Замен�ть «в�е заглавные буквы» нельз�: так проще ошибить�� в будущем, например на `Z0` или на дропах. + +``` +fn display_san(san: &str, mode: MoveNotation, lang: Lang) -> Cow<'_, str> +``` + +Режим `Latin` и англий�кий �зык в режиме `Local` возвращают `Cow::Borrowed`, то е�ть ничего не �то�т. + +### 1.3. «Буквы �зыка интерфей�а»: одна опци�, а не �пи�ок �зыков + +Решение: **одна опци�, котора� �ледует за �зыком интерфей�а.** В подпи�и �разу видны буквы, например «Ру��кие буквы (Кр Ф Л С К)». Отдельный �пи�ок �зыков нотации не нужен. Человек, который хочет немецкие буквы при ру��ком интерфей�е, �уще�твует, но �то редкий �лучай, а лишний выпадающий �пи�ок у�ложн�ет про�тую на�тройку. + +- В на�тройках хранит�� `Local`, а не «ру��кий». Е�ли �менить �зык интерфей�а на немецкий, нотаци� �разу �танет `Sf3`, а при возврате на ру��кий �нова `Кf3`. +- **Интерфей� на англий�ком:** опцию «буквы �зыка» не показываем, потому что она �овпала бы � латиницей. Сохранённое значение `Local` не мен�ет��. Пока интерфей� англий�кий, нотаци� показывает�� латиницей и в группе выбрана радиокнопка «Letters (K Q R B N)». Е�ли человек �ам нажмёт её, значение �танет `Latin`, и �то нормально. + +## 2. Где в на�тройках + +**Вкладка «До�ка и фигуры»**, новый раздел между «До�ка» и «�нимаци� фигур». + +Почему зде�ь, а не в «Интерфей�е»: + +- на�тройка отвечает на вопро� «как выгл�д�т фигуры», а �о�едние наборы фигур отвечают на тот же вопро�. Владелец назвал �то ме�то первым; +- на вкладке уже е�ть живые превью. Строка-превью нотации �мотрит�� там е�те�твенно, а во вкладке «Интерфей�» (�зык и тема в две �троки) она выгл�дела бы чужой; +- зави�имо�ть от �зыка объ��н�ет�� подпи�ью �амой опции («Ру��кие буквы…»), по�тому держать её р�дом � выбором �зыка не об�зательно. + +### 2.1. Макет (интерфей� на ру��ком, выбраны фигурки) + +``` +┌ �а�тройки ──────────────────────────────────────────────────────────� +│ [Движки] [До�ка и фигуры] [Звук] [Интерфей�] [Перевод] [О программе] │ +│ │ +│ �абор фигур │ +│ [♞♛ cburnett] [♞♛ merida] [♞♛ alpha] … │ +│ │ +│ До�ка │ +│ [▦] [▦] [▦] [▦] … │ +│ │ +│ Запи�ь ходов │ +│ ○ Латин�кие буквы (K Q R B N) Nf3 Qxd8+ e8=Q │ +│ � Фигурки ♘f3 ♕xd8+ e8=♕ │ +│ ○ Ру��кие буквы (Кр Ф Л С К) Кf3 Фxd8+ e8=Ф │ +│ ┌──────────────────────────────────────────────────────────────� │ +│ │ 1.e4 e5 2.♘f3 ♘c6 3.▓♗b5▓ a6 4.♗a4 ♘f6 5.O-O ♗e7 6.♖e1 b5 │ │ +│ └──────────────────────────────────────────────────────────────┘ │ +│ Только вид на �кране. В PGN и при копировании в�егда K Q R B N. │ +│ │ +│ �нимаци� фигур [Выкл] [Бы�тро] [Обычно] [Медленно] │ +│ ☑ Показывать координаты │ +│ ☑ Показывать �трелки лучшего хода движка │ +└──────────────────────────────────────────────────────────────────────┘ +``` + +Детали: + +- Заголовок раздела `RichText::strong()`, как у «�абор фигур» и «До�ка». Перед ним `add_space(8.0)`, как между �уще�твующими разделами. +- Три `radio_value` в �толбик, а не `selectable_value` в �троку, как у анимации: у каждой опции е�ть подпи�ь и образец, в �троку они не помещают��. Образцы �права выровнены по одной вертикали: подпи�и кладут�� в `Grid` из двух �толбцов. Образец ри�ует�� �емей�твом `san` (§5) размером 15 pt, цвет обычного тек�та. Щелчок по образцу тоже выбирает опцию (в�� �трока грида — одна зона нажати�), иначе он будет казать�� кнопкой, котора� не работает. +- Превью — рамка `Frame::group`, внутри одна �трока нотации 16 pt �емей�твом `san`, ширина по �одержимому вкладки, `truncate` в конце. Ход `3.Bb5` под�вечен как текущий: `selection.bg_fill` и `selection.stroke.color`, ровно как в `paint_move_cell`. По превью �разу видно, как выгл�дит выделение. Строка превью �татична�: `1.e4 e5 2.Nf3 Nc6 3.Bb5 a6 4.Ba4 Nf6 5.O-O Be7 6.Re1 b5`, прогнанна� через `display_san`. +- Под превью одна �трока `.weak()`, 12 pt. Это не под�казка при наведении: о том, что PGN не мен�ет��, должен знать каждый. +- В англий�ком интерфей�е третьей �троки нет, а группа �жимает�� до двух. + +### 2.2. Тек�ты (англий�кий — ключ i18n) + +| Ключ (en) | ru | fr | de | es | it | +|---|---|---|---|---|---| +| `Move notation` | Запи�ь ходов | Notation des coups | Zugnotation | Notación de jugadas | Notazione delle mosse | +| `Letters (K Q R B N)` | Латин�кие буквы (K Q R B N) | Lettres anglaises (K Q R B N) | Englische Buchstaben (K Q R B N) | Letras inglesas (K Q R B N) | Lettere inglesi (K Q R B N) | +| `Figurines` | Фигурки | Figurines | Figurinen | Figurines | Figurine | +| `Interface language letters` (en не показывает��) | Ру��кие буквы | Lettres françaises | Deutsche Buchstaben | Letras españolas | Lettere italiane | +| `Only how moves look on screen. PGN files and copied games always use K Q R B N.` | Только вид на �кране. В PGN и при копировании в�егда K Q R B N. | Seulement l'affichage. Les fichiers PGN et les parties copiées utilisent toujours K Q R B N. | Nur die Anzeige. PGN-Dateien und kopierte Partien verwenden immer K Q R B N. | Solo cambia la vista. Los archivos PGN y las partidas copiadas siempre usan K Q R B N. | Cambia solo la visualizzazione. I file PGN e le partite copiate usano sempre K Q R B N. | + +К подпи�и третьей опции буквы допи�ывают�� кодом: `"{label} ({letters})"`, где `letters` берут�� из той же таблицы, что и дл� замены. Так подпи�ь не разойдёт�� � реальной нотацией. + +Под�казки при наведении (`on_hover_text` на �троке опции): + +| Ключ (en) | ru | +|---|---| +| `International notation, as in PGN files and engine output` | Международна� запи�ь, как в PGN-файлах и у движков | +| `Piece symbols, as on Lichess. They look the same in every language.` | Значки фигур, как на Lichess. Одинаковы на любом �зыке. | +| `Follows the interface language` | Мен�ет�� вме�те � �зыком интерфей�а | + +fr/de/es/it перевод�т�� в том же �тиле, что и о�тальные �троки `i18n.rs`. + +## 3. Значение по умолчанию + +Решение: **«Латин�кие буквы» дл� в�ех**, и дл� новых пользователей, и дл� тех, кто обновил��. + +- У тех, кто обновил��, нотаци� не должна мен�ть�� без их ведома. Это ход в данных, который человек читает каждую минуту. В файле на�троек пол� нет, по�тому `#[serde(default)]` даёт `Latin`. +- Дл� новых пользователей тоже `Latin`, и в `first_start()` по �зыку �и�темы её не мен�ем. Владелец говорит, что многие предпочитают латиницу. Латиницу и�пользуют PGN, движки, базы, ChessBase и пои�к в интернете, по�тому человек видит то же, что потом �копирует. Ру��кие буквы нужны меньшин�тву, в о�новном тем, кто учит�� по �овет�ким книгам. Это о�ознанный выбор, а не значение по умолчанию. +- Lichess по умолчанию показывает фигурки, но он не база партий: там PGN почти не читают глазами. Чтобы фигурки было легко найти, в CHANGELOG и на �айте нужна �трока «�овое: запи�ь ходов фигурками или ру��кими буквами (�а�тройки → До�ка и фигуры)». + +Хранение: `Settings::move_notation: MoveNotation`, в JSON `"latin" | "figurine" | "local"`. �еизве�тное значение из будущей вер�ии превращает�� в `Latin` и не должно ломать загрузку о�тальных на�троек. + +## 4. Где дей�твует на�тройка + +### 4.1. Примен�ет�� (только подпи�ь) + +| Ме�то | Код | +|---|---| +| �отаци�, табличный режим, �чейки ходов | `notation.rs` `paint_move_cell` | +| �отаци�, тек�товый режим � вариантами: ходы о�новной линии и вариантов, кнопка текущего хода | `notation.rs` около �троки 450 | +| Отметки разбора в нотации, «Лучше: …» | `notation.rs` около �троки 282 | +| Линии движка (в�е MultiPV, до 14 ходов) | `game_view.rs` около �троки 1007 | +| Справка: таблица ходов, `node_label`, `move_label`, короткое продолжение партии | `reference.rs` | +| Пои�к по позиции: дерево, �троки продолжений, лини� на до�ке пои�ка | `board_search.rs` `move_label`, `continuation_row` | +| Отчёт разбора: лучший ход и любые подпи�и ходов | `review.rs`, `best_label` | +| В�плывающие �ообщени� и под�казки, где показан ход (например «В�тавлен вариант 12.Nf3 …»), е�ли они е�ть | в�е ме�та, где SAN попадает в �троку дл� показа | + +`review.rs` хранит готовую �троку `best_label`, �обранную при ра�чёте. Её нужно �обирать при показе из `best_san` и номера хода, иначе по�ле переключени� отчёт о�танет�� в �таром виде. Это отно�ит�� ко в�ем к�шированным подпи��м � ходами. + +### 4.2. �е примен�ет�� + +- Запи�ь и �к�порт PGN, «Сохранить», «Сохранить как…», копирование PGN и FEN, любой `copy_text`. +- Тек�т комментариев: оригинал, перевод (`translate.rs`, `translate_ui.rs`) и варианты, напи�анные внутри комментари� тек�том. +- �азвани� дебютов и ECO, заголовки партии, имена. +- UCI, логи, `[%eval]`, к�ш разбора, пои�к и �ортировка (§6). +- Сырой тек�т PGN, е�ли он где-то показан (импорт из буфера, диагно�тика �овме�тимо�ти): �то тек�т файла. + +### 4.3. Ввод ходов тек�том + +Сейча� пользователь�кого ввода ходов тек�том нет: ходы делают�� на до�ке, а `CP_BOARD` и те�ты и�пользуют латиницу. Правило дл� будущего ввода: **латиница принимает�� в�егда, фигурки (U+2654–2658, а также U+265A–265E) тоже,** они однозначны. Буквы �зыка принимают�� только дл� ru и de, где они не пере�екают�� � латиницей по �мы�лу. Во fr, es и it `R` означает корол�, а в латинице ладью, по�тому там принимает�� только латиница. Перед разбором `San` �трока нормализует�� в латиницу. + +## 5. Как выгл�д�т фигурки + +### 5.1. Шрифт + +- Отдельное �емей�тво `FontFamily::Name("san")` = `["Ubuntu-Light", "figurine"]`. Им ри�уют�� в�е подпи�и из §4.1 во **в�ех трёх режимах**. Тогда у режимов одинакова� метрика �троки, и при переключении вы�ота �трок не прыгает. Кириллица е�ть в Ubuntu-Light. +- Решение на первую вер�ию: `figurine` — �то байты уже в�троенного `emoji-icon-font`, зареги�трированные под вторым именем �о �воим `FontTweak`. �овых файлов и лицензий не нужно. При ма�штабе интерфей�а 1×, а у ноутбука 1280 px именно 1×, у �того шрифта �амый контра�тный контур: тонкий Noto Sans Symbols 2 р�дом � тек�том выгл�дит бледным. Е�ли потом выберем Noto, помен�ет�� только одно им� (�м. вопро� 3). +- �ачальный твик: `scale 0.85`, `y_offset_factor` подобрать так, чтобы о�нование фигурки �то�ло на базовой линии. Критерии, которые провер�ет дизайнер на �криншотах: + - вы�ота фигурки от 1,05 до 1,15 вы�оты заглавной `N` (как у Lichess: 1,06–1,15); + - о�нование на базовой линии, ±1 px при 16 pt и 1×; ничего не уходит ниже базовой линии; + - верх кон� и корол� не обрезает�� в `Button` и в �троках `painter.text`; + - между фигуркой и полем нет «дыры»: `♘f3` читает�� одним �ловом, а не как `♘ f3`. Е�ли правый от�туп глифа �лишком велик, ма�штаб уменьшить до 0,80, но не ниже; + - толщина обводки на глаз не т�желее жирного тек�та. + +### 5.2. Цвет и �о�то�ни� + +- Фигурка — �то глиф, по�тому она кра�ит�� цветом тек�та. Текущий ход: `selection.stroke.color` на `selection.bg_fill`. Ход � NAG-оценкой окрашивает�� целиком, вме�те � фигуркой, как �ейча� окрашивает�� буква. `.weak()` в вариантах тоже дей�твует на фигурку. +- Тёмна� тема: контур �ветлый на тёмном, читает�� так же, как буквы. Отдельной на�тройки нет. +- Кнопка текущего хода в тек�товом режиме: вы�ота кнопки и �троки в режиме `Figurine` равна вы�оте в `Latin` (провер�ет те�тировщик, §7). + +### 5.3. Узкие ме�та по ширине + +С фигуркой ход шире примерно на 0,2–0,3 em. В ру��ком режиме `Кр` добавл�ет целую букву: `Крxe2+` длиннее `Kxe2+`. + +- `board_search.rs`, `x += 70.0` при 13 pt: заменить на `max(70, ширина �амой длинной подпи�и �реди видимых �трок + 10)`. Ширину измерить галлеем в том же шрифте. Строк немного, по�тому �то дёшево. �омера �права не должны налезать на ход. +- `reference.rs`, �толбец ходов `Column::exact(86.0)`: в худшем �лучае (`23…Крxe8+` или `23…♕xd8+` при 13 pt) подпи�ь должна поме�тить��. Е�ли не помещает��, увеличить �толбец до 96 и уче�ть �то в `used` при ра�чёте, какие �толбцы пр�тать в узкой панели. Подпи�ь в любом �лучае обрезает�� внутри �чейки (`clip`) и не залезает в �толбец «Партии». +- Табличный режим нотации: �чейка — половина панели, `Крxe8=Ф+!?` при 16 pt должен поме�тить�� в �чейку при �амой узкой панели. Е�ли не помещает��, обрезать � `…` �права, NAG не тер�ть: NAG ри�овать отдельно, �права. +- Линии движка (`horizontal_wrapped`): �трок при перено�е может �тать больше, �то допу�тимо. Вы�ота панели движка не должна дёргать�� при каждом новом `info`. + +## 6. О�обые �лучаи + +- **Варианты в комментари�х.** Комментарий «12.Nf3 �ильнее» р�дом � ходом `12.♘f3` — ожидаемое поведение, его не и�правл�ем. То же дл� перевода комментариев. +- **Узка� бокова� панель** (ноутбук 1280 px логиче�ких, минимальна� ширина панели): ничего не обрезает�� по�реди хода, кроме �лучаев из §5.3 � `…`. Горизонтальной прокрутки нет. Справка пр�чет �толбцы по �воей логике, а �толбец ходов не пр�чет�� никогда. +- **Сортировка и пои�к.** Данные о�тают�� латиницей: �ортировка ходов (е�ли по�вит�� �ортировка по ходу) идёт по латин�кому SAN, по�тому пор�док от режима не зави�ит. Пои�к по позиции работает по позиции, а не по �троке. Сравнени� `san == best_san` и `p.san == line.san` работают � данными, а не � подпи��ми. +- **Смена �зыка в режиме `Local`:** нотаци�, превью и подпи�ь опции мен�ют�� в том же кадре. +- **�нглий�кий интерфей� в режиме `Local`:** показывает�� латиница, выбрана радиокнопка «Letters» (§1.3). +- **Превращение:** `e8=Q+` → `e8=♕+` / `e8=Ф+`. Подпревращение `e8=N` → `e8=♘` / `e8=К`. +- **Ру��ка� С и латин�ка� c:** `Сxc3` (�лон) похож на `cxc3`, но � заглавной. Так прин�то в ру��ких книгах, о�тавл�ем. +- **Chess960:** рокировка `O-O`, как в данных. +- **�улевой ход `--` и непон�тный ход `?`:** без изменений. +- **Скриншоты �айта и магазина:** �нимать в режиме `Latin`, как у большин�тва. Фигурки показать отдельным кадром � на�тройками. + +## 7. Чек-ли�т те�тировщика + +Провер�ть на �борке, в �ветлой и тёмной теме, при ма�штабе 1× и 2×, е�ли не �казано иное. + +Замена: + +1. `display_san` (юнит-те�ты), дл� в�ех трёх режимов и в�ех ше�ти �зыков: `Nf3`, `Nbd7`, `N1f3`, `Qh4xe1`, `Kxe2+`, `exd8=Q#`, `e8=N`, `bxc3`, `Bxc3`, `O-O`, `O-O-O+`, `--`, `b4`, `Rfe1`. Пешечные ходы и рокировка не мен�ют��, `b` в `bxc3` о�таёт�� буквой. +2. `ru`: `Kxe2+` → `Крxe2+`, `Nbd7` → `Кbd7`, `Bxc3` → `Сxc3`. Буквы кирилличе�кие, проверить по коду �имвола. +3. `de`: `Nf3` → `Sf3`, `Bb5` → `Lb5`. `fr`: `Bb5` → `Fb5`, `Kg1` → `Rg1`, `Rf1` → `Tf1`. + +Сохранно�ть: + +4. Открыть PGN � вариантами, комментари�ми и NAG, включить «Фигурки», затем «Буквы �зыка». По�ле «Сохранить как…» файл побайтно �овпадает � файлом, �охранённым в режиме `Latin`. +5. «Копировать PGN» и «Копировать FEN» в каждом режиме дают одинаковый тек�т, без `♘` и кириллицы. +6. Комментарий, в котором напи�ано `12.Nf3` или `12.Кf3`, в любом режиме показывает�� так, как напи�ан, в оригинале и в переводе. +7. В�тавка линии движка как варианта в режиме `Figurine` �оздаёт обычный вариант. В PGN он запи�ан латиницей, а отмена работает. + +Где дей�твует: + +8. Каждое ме�то из §4.1 по очереди: нотаци� (таблица и тек�т), варианты, линии движка, �правка (таблица и продолжени�), пои�к по позиции, отчёт разбора («Лучше: …»). В�ё в выбранном режиме, нигде латиница не «про�ачивает��». +9. Переключение режима при открытой партии, работающем движке и открытом отчёте разбора: в�ё мен�ет�� в �ледующем кадре, включа� уже по�читанный отчёт. Движок не перезапу�кает��, анализ не �бра�ывает��. +10. Режим `Local` и �мена �зыка интерфей�а ru → de → en → ru: нотаци� `Кf3` → `Sf3` → `Nf3` → `Кf3`. В англий�ком третьей опции нет, выбрана «Letters». +11. �а�тройки по�ле перезапу�ка �охран�ют��. Старый файл на�троек без пол� даёт `Latin`. Файл � `"move_notation": "nonsense"` не �бра�ывает о�тальные на�тройки. + +Вид: + +12. Скриншоты при 16 pt и 1×: текущий ход � фигуркой, ход � `?` (цвет) и `!!`, ход в варианте (`.weak()`), р�дом тот же ход латиницей. О�нование фигурки на базовой линии, верх не обрезан. +13. Вы�ота �трок нотации и кнопки текущего хода одинакова в трёх режимах. Перед переключением и по�ле него �равнить �криншоты � одной позицией прокрутки: �троки не должны прыгать. +14. Пои�к по позиции: �троки � `12…♕xd8+` и `12…Крxe8+` не налезают на �толбец «Партии». +15. Справка: �амый длинный ход в таблице в режимах `Figurine` и `Local` (ru) при узкой панели помещает�� или обрезает�� внутри �чейки. +16. Окно 1280×800 логиче�ких, �ама� узка� бокова� панель: нет горизонтальной прокрутки и наложений, у линий движка аккуратный перено�. +17. Превью в на�тройках под�вечивает `3.Bb5` цветом выделени�. Подпи�ь третьей опции �овпадает � буквами в превью дл� каждого �зыка. Щелчок по образцу �права выбирает опцию. + +## 8. Вопро�ы владельцу + +1. **По умолчанию дл� новых пользователей:** � выбрал латиницу дл� в�ех. �ужно ли новым пользовател�м �разу показывать фигурки, как на Lichess? Тех, кто уже пользует�� программой, �то в любом �лучае не затронет. +2. **Ру��кий режим:** о�тавл�ем `O-O` и `x`, как в PGN, или делаем по-книжному: `0-0` и `:` (`Л:e1`)? Я за `O-O` и `x`. +3. **Шрифт фигурок:** в первой вер�ии берём уже в�троенный жирный `emoji-icon-font`, он контра�тнее при 1×. Тонкий контур как на Lichess (Noto Sans Symbols 2) потребует один раз �делать �аб�ет шрифта (pyftsubset в отдельном venv) и добавить файл на 5 КБ � лицензией OFL. Сделать �ейча� или по�ле �криншотов? diff --git a/docs/design/narrow-windows.md b/docs/design/narrow-windows.md new file mode 100644 index 0000000..84a50dc --- /dev/null +++ b/docs/design/narrow-windows.md @@ -0,0 +1,251 @@ +# Узкие и низкие окна + +Стату�: проект дизайнера, 2026-10-24, по жалобе владельца: в узком окне (�жатое по горизонтали, половина 4K-монитора при ма�штабе 2 в Hyprland ≈ 940–960 × 1040 логиче�ких точек) �лементы налезают друг на друга. Тайлинговый менеджер не �облюдает минимальный размер окна, по�тому кажда� компоновка должна о�тавать�� правильной при любой ширине; владелец �огла�ил�� �низить минимум окна � 900×600 до **640×480** (`apps/desktop/src/main.rs`, `with_min_inner_size`) и �делать в�ё правильным до него. + +Замен�ет: `large-databases.md` §2.5 (минимум 900×600), диапазон ширины панели до�ки из `board-search.md` §2.1 («от 340 до ширина − 420»), фразу «до�ка не уменьшает��» из `reference.md` («Где»). + +В�е размеры — логиче�кие точки egui. Снимки, на которые опирает�� документ: `n_*` (0.16.1) и `o_*` (0.15.0) при 1400/1200/960/800/640, а также `des_lib_640x480`, `des_game_640x480`, `des_board_640x700` в каталоге �нимков разработчика (scratchpad `narrow/`). + +## 0. Принцип + +**Компоновку выбирает размер окна, а не текуща� ширина панелей.** Кажда� панель имеет минимум �воего �одержимого (§1). Е�ли на �кране не помещают�� в�е панели � их минимумами, одна из них пере�таёт занимать ширину: уходит в выдвижную панель (фильтры), замен�ет �о�еда по очереди (до�ка пои�ка) или переезжает вниз (нотаци�). �ичего не �двигает�� под �о�еда и не обрезает�� �лева. + +- Решение «р�дом / поверх / по очереди / �топкой» — чи�та� функци� ширины и вы�оты окна (точнее, `available_rect` �крана). Оно не зави�ит от ширины, до которой пользователь перетащил панель, от включённого анализа, от открытой вкладки, от графика оценки. По�тому нет обратной �в�зи и не нужен ги�терези�: при плавном изменении окна компоновка переключает�� ровно один раз на границе. +- Ширины, полученные вычитанием, округл�ют�� вниз (`floor`), как в `large-databases.md` §2.6. +- Пользователь�ка� ширина панели (перета�кивание) — предпочтение. Е�ли окно её не вмещает, панель показывает�� уже (до �воего минимума), а при ра�ширении окна возвращает�� к �охранённой. Е�ли в egui `Panel` при �ужении `size_range` перезапи�ывает запомненную ширину, �то допу�тимо (пользователь перетащит �нова); обходных путей не делать. + +## 1. Минимальные ширины �одержимого + +| Кон�танта | Значение | Что в неё входит | Где примен�ть | +|---|---|---|---| +| `TABLE_MIN` (таблица партий библиотеки) | формула ниже; ≈ **560** (PGN на 33 640 партий — 558, Mega — 570); � колонкой «Ход» вме�то «№» ≈ **540** | колонки узкого набора (`year_only`, без Турнира/ECO/✎/Длины/Раунда): «№» (52–84 по чи�лу цифр) или «Ход» 52, Elo 44 ×2, Рез. 56, Год 48, имена **2 × 110**, промежутки 6 × 8, поло�а прокрутки 10, пол� центральной панели 16 | `large_db.rs`: нова� `pub fn table_min_width(&self, db) -> f32`, �читает�� из тех же чи�ел, что `table()` (выне�ти ширины колонок в кон�танты, чтобы не разошли�ь) | +| `FILTERS_MIN` | **260** (е�ть) | �етка `large-databases.md` §2.6 | `library.rs`, панель `filters` | +| `SEARCH_BOARD_MIN` | **340** (е�ть) | до�ка 240 + пол� + �трока �о�то�ни� | `library.rs`, панель `search_board` | +| `SIDE_MIN` (права� панель партии: «�отаци�», «Отчёт») | **240** | �трока «�нализ: выкл · Stockfish 19 · ⚙» (~220), нотаци� в две колонки (№ 36 + 2 × 80 + пол�), панель ин�трументов в две �троки | `game_view.rs`, `show()` | +| `REF_MIN` (вкладка «Справочник») | **по �одержимому**, ≈ 370 (об�зательные колонки таблицы ходов + поло�а результата; измер�ет разработчик) | `reference.md`, пор�док �крыти� колонок | `game_view.rs` / `reference.rs` (делает разработчик) | +| `BOARD_MIN` (до�ка партии) | **220** | 27,5 точки на поле: ещё попадает�� мышью; при 640 и «Справочнике» � анализом: 640 − 370 − 16 − 26 = 228 | `game_view.rs`, `board_area()` (�ейча� `.max(120.0)`) | +| `STACK_BOTTOM_MIN` (нижн�� ча�ть в �топке) | **300** | �трока движка ~44 + вкладки 30 + 6 �трок нотации 174 + панель ин�трументов в одну �троку ~44 | `game_view.rs` | +| `NAME_MIN` (им� в таблице) | **110** | «Конюшенко С…», «Пузырев�кий…» — фамили� узнаёт�� | внутри `TABLE_MIN` | + +Формула таблицы: `TABLE_MIN = num + 44 + 44 + 56 + 48 + 2 × NAME_MIN + 6 × spacing + scrollbar + 16`, где `num` — ширина колонки «№» (`(цифры × 8 + 24).clamp(52, 84)`) или 52 дл� «Ход». + +Проверка минимума окна 640×480: таблица в выдвижном режиме получает 624 ≥ 570; до�ка партии ≥ 228 при любой вкладке; нотаци� 240. В�ё �одержимое помещает�� — дальше колонки пр�тать не нужно. + +## 2. Библиотека + +### 2.1. Пороги + +`W` — ширина �крана библиотеки (`ui.available_width()` в `Library::show` до панелей). + +| Ширина | Фильтры | До�ка пои�ка | +|---|---|---| +| `W ≥ TABLE_MIN + 260` (≈ **820**) | �права, р�дом � таблицей; ширина = �охранённа� (260–380), но не больше `W − TABLE_MIN` | — | +| `W < 820` | **выдвижна� панель поверх таблицы** (§2.2) | — | +| `W ≥ TABLE_MIN_pos + 340` (≈ **880**) | — | �права, р�дом; диапазон `340 ..= W − TABLE_MIN_pos`, по умолчанию `0,5 · W`, но не больше верхней границы | +| `W < 880` | — | **по очереди � таблицей** (§2.3) | + +При 960 (половина 4K): фильтры р�дом (таблица 680), до�ка р�дом шириной до 420 (таблица 540). Раньше до�ка брала 480 и о�тавл�ла таблице 480 � обрезанными именами (`n_board_960`); теперь имена читают��, до�ка — 400 вме�то 460. Это �ознательный выбор: таблица — результат пои�ка. + +### 2.2. Фильтры как выдвижна� панель (W < 820) + +``` +640 × 1000 +┌──────────────────────────────────────────────────────────────� +│ Базы ♟ �ова� парти� 📋 В�тавить ⚙ │ +│ [🗄 Гран-при…] [+ Добавить базу] [� Онлайн-партии] │ +├──────────────────────────────────────────────────────────────┤ +│ Гран-при_Р… · найдено 812 из 33 640 [× Пои�к…] [Фильтры (2)│До�ка] +│ Игрок: Вафин × Годы: 2025–2026 × │ +├──────────────────────────────┬───────────────────────────────┤ +│ № Белые Elo Чёрные ┃ Игроки │ +│ 1 Вафин Рад… 1887 Ширшов С ┃ Игрок │ +│ 2 Кузнецов … 1484 Гади�ов ┃ [Вафин ] × │ +│ … (таблица жива�, ┃ … │ +│ видна и обновл�ет��) ┃ Парти� │ +│ ┃ Годы [2025 ]–[2026 ] │ +│ ┃ … │ +│ ┃ [Сбро�ить фильтры] │ +└──────────────────────────────┴───────────────────────────────┘ + ↑ тень �лева, без затемнени� таблицы +``` + +- **Ме�то:** правый край �крана библиотеки, �верху — от нижней границы шапки таблицы (�троки � пои�ком и переключателем) и �троки у�ловий, �низу — до низа окна. Шапка, пои�к и переключатель о�тают�� видимыми и работают. +- **Ширина:** �охранённа� ширина фильтров (260–380), но не больше `W − 48`: �лева в�егда видна поло�а таблицы, по которой можно щёлкнуть, чтобы закрыть. Край не перета�кивает�� (ширину мен�ют в широком окне). +- **Вид:** то же �одержимое `LargeView::panel` (тот же `id` прокрутки — положение прокрутки �охран�ет�� при переходе «р�дом ↔ поверх»), фон панели, тень �лева (`window_shadow`), без затемнени� и без блокировки таблицы. Без анимации. +- **Таблица жива�:** фильтр примен�ет�� по мере ввода, как �ейча�; видима� ча�ть таблицы и �чётчик в шапке обновл�ют��, пока панель открыта. +- **Открыть:** щелчок по �егменту «Фильтры»; `Ctrl+F` дважды (второе нажатие открывает панель и �тавит фоку� в «Игрок», как �ейча�); щелчок по чипу у�лови�. +- **Закрыть** (у�лови� �охран�ют��, �егмент показывает «Фильтры (N)»): + - щелчок по активному �егменту «Фильтры»; + - `Esc`, когда фоку� не в поле панели. Пор�док `Esc`: �пи�ок под�казок → поле (egui �нимает фоку�) → панель. Т. е. из пол� — дважды; + - щелчок вне панели (таблица, шапка, полка). Щелчок **не поглощает��**: �трока выдел�ет��, поле пои�ка получает фоку� и т. д. Коле�о мыши над таблицей прокручивает таблицу и панель не закрывает. +- **Клавиатура таблицы** (↑ ↓ Enter) работает, когда фоку� не в тек�товом поле — как �ейча�; открыта� панель её не перехватывает. +- **Сужение окна:** е�ли фильтры были р�дом и окно �тало `< 820`, панель **закрывает��** (не превращает�� в открытую выдвижную): изменение размера окна не должно накрывать таблицу. +- **Ра�ширение окна:** при `≥ 820` фильтры �нова р�дом, е�ли `pane == Filters`. Открыта� выдвижна� панель �тановит�� панелью р�дом без мигани�. +- **Со�то�ние:** `pane: Pane` о�таёт�� предпочтением широкого окна (как �ейча�). Добавл�ет�� переходное `drawer_open: bool` (не �охран�ет��). В узком режиме открытие �тавит `pane = Filters` и `drawer_open = true`; закрытие — только `drawer_open = false`. Переход широкий → узкий �бра�ывает `drawer_open`. +- Подпи�ь �егмента: «Фильтры (N)» показывает�� в�егда, когда панель не открыта (в узком режиме — и при `pane == Filters`), т. к. у�ловий не видно. + +### 2.3. До�ка пои�ка по очереди � таблицей (W < 880) + +``` +640 × 1000, режим «До�ка» +┌──────────────────────────────────────────────────────────────� +│ (полка) │ +├──────────────────────────────────────────────────────────────┤ +│ Гран-при · 19 230 партий › [× Пои�к…] [Фильтры │ До�ка] │ +│ Позици�: 1.e4 × │ +├──────────────────────────────────────────────────────────────┤ +│ ○ Ход чёрных · по�ле 1.e4 ⟳ Сбро�ить ☰ │ +│ ┌──────────────────────� │ +│ │ до�ка (узкий │ │ +│ │ вариант board- │ │ +│ │ search §2.4) │ │ +│ └──────────────────────┘ │ +│ ◀ ▶ 1.e4 │ +│ Продолжени� · 19 230 партий │ +│ 1 1…c5 8 113 [▮▮▮▯▯] 1630 2026 │ +└──────────────────────────────────────────────────────────────┘ +``` + +- До�ка занимает **в�ю ширину** вме�то таблицы (`CentralPanel` показывает `board_panel`, а не таблицу). Внутри работает �во� компоновка из `board-search.md` §2.3–2.4 (по ширине панели: ≥ 820 — продолжени� �права, иначе под до�кой). +- **Вернуть�� к таблице:** щелчок по активному �егменту «До�ка» (�то уже дей�твие «�крыть панель» — новых �лементов переключател� нет); `Esc` (в библиотеке он �ейча� ни за что не отвечает); щелчок по �чётчику в шапке — в �том режиме он �тановит�� ��ылкой «19 230 партий ›» � под�казкой «Показать �пи�ок партий (Esc)». +- Позици� при �том о�таёт�� у�ловием (чип «Позици�: 1.e4 ×», на �егменте «До�ка •»), таблица показывает найденные партии. +- **Открыть до�ку:** �егмент «До�ка», `Ctrl+B`, «�айти в базе» из партии. +- Клавиши до�ки (� → Home End Backspace) дей�твуют, пока до�ка на �кране; клавиши таблицы — пока на �кране таблица. Конфликта нет. +- **Сужение окна** при до�ке р�дом: до�ка о�таёт�� на �кране (на в�ю ширину) — � ней работали. **Ра�ширение** до ≥ 880: до�ка в�таёт �права, таблица возвращает�� �лева. +- Фильтры в �том режиме открывают�� выдвижной панелью поверх до�ки, правила те же (§2.2). + +### 2.4. Шапка таблицы + +Элементы по убыванию важно�ти: + +1. переключатель `[Фильтры (N) │ До�ка •]` — в�егда целиком; +2. поле пои�ка � ме�том под `×` — 220, при нехватке 140 (не меньше); +3. �чётчик «· найдено N из M» � индикатором и процентом — не �окращает�� (�то результат); +4. «⟳ �овые партии» / «обновление…»; +5. `⚠ N` (заметки импорта); +6. им� базы — �окращает�� � «…» (полное — в под�казке), не уже 80, иначе �крыто: оно же на карточке полки или в �пи�ке компактной полки; +7. «· формат» — пр�чет�� первым. + +�лгоритм (ширины �читают�� из размеров тек�та — `layout_no_wrap` галактик, а не из пр�моугольников прошлого кадра): + +1. В�ё помещает�� в одну �троку � полем 220 → одна �трока. +2. Убрать формат; затем поле 220 → 140; затем им� (�начала �ократить до 80, потом убрать). +3. Е�ли и так не помещает�� — **две �троки**: перва� — им� (гибкое) · поле · переключатель; втора� — �чётчик · индикатор · `⚠ N` · «⟳ �овые партии», �лева. Строка у�ловий (чипы) — третьей, как �ейча�. + +``` +одна �трока: Гран-при_Р… · найдено 812 из 33 640 [× Пои�к…] [Фильтры (2)│До�ка] +две �троки: Гран-при_РШШ_архив… [× Пои�к…] [Фильтры (2)│До�ка] + · найдено 812 из 33 640 ◌ 42 % ⚠ 3 [⟳ �овые партии] +``` + +Сейча� при 640 и 800 �чётчик залезает под поле (`n_lib_640`, `des_lib_640x480`): `Label::truncate` в `left_to_right` внутри `right_to_left` получает отрицательную ширину. Правка — заранее вычи�ленна� ра�кладка выше. + +### 2.5. Полка + +- Карточки 190 × 64 и 150 × 64 без изменений; при 640 в р�д помещают�� три (`190 + 150 + 150 + 16`). +- **Компактна� полка** (одна �трока �о �пи�ком баз), когда выполн�ет�� любое: + - полной полке нужно **больше двух р�дов** карточек (чи�ло карточек и ширина изве�тны до ра�кладки); + - вы�ота �крана библиотеки `< 600` (при 640×480 полна� полка забирает 115 из 480; таблице о�таёт�� 10 �трок); + - на �кране до�ка пои�ка и вы�ота `< 760` (е�ть). +- **Компактна� полка в узком окне** �ейча� вылезает влево (`des_board_640x700`: «🗄» обрезан). Правило: права� группа «♟ �ова� парти� · 📋 В�тавить PGN · ⚙ �а�тройки» (~330) при нехватке �тановит�� **значками** «♟ 📋 ⚙» (под�казки � названием и �очетанием клавиш); �пи�ок баз — `clamp(до�тупно − «+» − «�» − права� группа − 16, 140, 260)`, им� в нём �окращает��. Пор�док: �начала �жать �пи�ок до 180, затем значки, затем �пи�ок до 140. +- Заголовок полной полки «Базы» + три кнопки при 640 помещает��; правило значков то же. + +## 3. Экран партии + +### 3.1. Р�дом или �топкой + +`W`, `H` — ширина и вы�ота под шапкой партии. Решение принимает�� **только** по `W` и `H`, � по�то�нными допущени�ми (вкладка «�отаци�», поло�а оценки зарезервирована, без графика), чтобы переключение вкладки, `L` или `Shift+A` не пере�траивали �кран: + +``` +board_side = min(H − 16, W − SIDE_MIN − 26 − 24) +board_stack = min(W − 16 − 26, H − STACK_BOTTOM_MIN − 16) +�топка ⇔ board_stack ≥ 1,25 · board_side +``` + +Порог 1,25: �топка отнимает у нотации вы�оту окна, по�тому выигрыш до�ки должен быть заметным. Примеры: + +| Окно | р�дом | �топкой | Компоновка | +|---|---|---|---| +| 640 × 480 | 350 | 114 | р�дом | +| 640 × 700 | 350 | 334 | р�дом | +| 640 × 800 | 350 | 434 | р�дом (1,24; � вы�оты окна ≈ 805 — �топка) | +| 640 × 1000 | 350 | 598 | **�топка** | +| 720 × 1000 | 430 | 634 | **�топка** | +| 800 × 1000 | 510 | 634 | р�дом (1,24) | +| 960 × 1050 | 670 | 684 | р�дом (�лучай владельца) | +| 1400 × 900 | 834 | 534 | р�дом | + +### 3.2. Р�дом (как �ейча�, � минимумами) + +- Права� панель: `size_range(min ..= W − BOARD_MIN − 26 − 24)`, где `min` — `SIDE_MIN` или `REF_MIN` по вкладке; ширина по умолчанию — как �ейча�. +- До�ка: `max(BOARD_MIN)` вме�то `max(120.0)` в `board_area`. При 640 × 480 � «Справочником» и анализом — 228. +- Короткие окна (вы�ота ниже, чем нужно дл� �топки) **никогда** не �кладывают��: до�ка ограничена вы�отой, нотаци� �права во в�ю вы�оту. + +### 3.3. Стопка + +``` +640 × 1000 +┌──────────────────────────────────────────────────────────────� +│ � Библиотека │ Вафин Р. — Ширшов С. 1-0 �▾ ⚙ │ +├──────────────────────────────────────────────────────────────┤ +│ ▌┌────────────────────────────────────────────────────────� │ +│ ▌│ │ │ +│ ▌│ до�ка 598 (по ширине окна) │ │ +│ ▌│ │ │ +│ ▌└────────────────────────────────────────────────────────┘ │ +│ [график оценки, е�ли открыт отчёт] │ +├��������������������� разделитель (т�нуть) �������������������┤ +│ �нализ: выкл · Stockfish 19 ⚙ │ +│ [�отаци�] Справочник Отчёт │ +│ 1 │ e4 c5 │ │ +│ … │ +│ � ◀ ▶ � │ 🔃 ↩ ↪ │ ☰ 📋 │ 📈 │ +└──────────────────────────────────────────────────────────────┘ +``` + +- Вме�то `Panel::right(side_id)` — `Panel::bottom("game_side_stacked")` � **тем же** �одержимым `side_panel()` (�трока движка, вкладки, �одержимое, панель ин�трументов). Пор�док блоков не мен�ет��; панель ин�трументов при ширине ≥ 600 — в одну �троку. +- �отаци� в �топке — та же таблица «№ · белые · чёрные» (комментарии и варианты в�тавлены между �троками, по�тому не�колько пар в �троку невозможны). Ширина клетки хода ограничена `CELL_MAX = 160` (`notation.rs`, `Row::flush`): таблица прижата влево, выделенный ход не ра�т�гивает�� на пол�крана; блоки комментариев и вариантов занимают в�ю ширину. +- Вы�ота нижней ча�ти учитывает движок: нижн�� граница диапазона — `STACK_BOTTOM_MIN` плю� вы�ота линий движка (когда анализ включён) и панели на�троек движка (когда открыта), но не больше верхней границы (до�ка ≥ `BOARD_MIN`). До�ка при �том уменьшает�� — компоновка (�топка) не мен�ет��. Иначе при включённом анализе нотации о�таёт�� одна �трока. +- Вы�ота нижней ча�ти: по умолчанию — в�ё, что о�тало�ь под до�кой `board_stack` и графиком; `resizable(true)`, диапазон `STACK_BOTTOM_MIN ..= H − BOARD_MIN − график − 16`. Т�нут вверх — до�ка уменьшает��, нотаци� ра�тёт. egui запоминает вы�оту отдельно от ширины правой панели (�вой `id`). +- До�ка и поло�а оценки — по центру по горизонтали, график оценки — под до�кой, как �ейча�. +- «Справочник» в �топке получает в�ю ширину окна — его колонки помещают��; вы�оты меньше, таблицы прокручивают��. +- Клавиатура не мен�ет��. Фоку� и прокрутка нотации к кур�ору работают так же. +- Переход «р�дом ↔ �топка» прои�ходит при изменении размера окна; вкладка, прокрутка, кур�ор, анализ �охран�ют�� (�о�то�ние в `GameView`, а не в панели). + +### 3.4. Шапка партии (делает разработчик) + +Приоритет: «� Библиотека» и результат `1-0` видны в�егда (результат — �разу по�ле названи�, внутри группы, котора� �окращает��); название и подзаголовок �окращают�� � «…» (полные — в под�казке); правые кнопки при нехватке �танов�т�� значками «� ▾» и «⚙» (под�казки � названи�ми), когда названию о�таёт�� < 160. + +## 4. Что мен�ть в коде + +1. `apps/desktop/src/main.rs`: `with_min_inner_size([640.0, 480.0])`. +2. `apps/desktop/src/large_db.rs`: + - выне�ти ширины колонок узкого набора в кон�танты, добавить `table_min_width(&self, db, use_position) -> f32` по формуле §1; + - шапка `table()`: ра�кладка §2.4 вме�то `room = (available − 300).max(80)` и `width > 700 ? 220 : 140` — измерить тек�ты, выбрать одну или две �троки; + - `pane_switch`: подпи�ь «Фильтры (N)», когда панель не показана (в узком режиме � `drawer_open == false` тоже); в режиме до�ки на в�ю ширину — �чётчик-��ылка «N партий ›»; + - `Esc` в режиме до�ки на в�ю ширину → таблица; `Esc` при открытой выдвижной панели (фоку� не в поле) → закрыть; `Ctrl+F` дважды в узком режиме → открыть выдвижную панель и фоку� в «Игрок». +3. `apps/desktop/src/library.rs` `show()`: + - вычи�лить `W`, `narrow_filters = W < table_min + 260`, `narrow_board = W < table_min_pos + 340`; + - `filters`: р�дом — `size_range(260 ..= (W − table_min).max(260))`; в узком — не `Panel::right`, а `egui::Area` (`Order::Middle`, прив�зка к правому краю под шапкой таблицы, `Frame::side_top_panel` + тень) при `drawer_open`; закрытие по щелчку вне (`clicked_elsewhere`, не поглоща� щелчок) и по `Esc`; + - `search_board`: р�дом — `size_range(340 ..= (W − table_min_pos).max(340))`, по умолчанию `min(0,5·W, верх)`; в узком — `CentralPanel` показывает `board_panel` вме�то `table_area`; + - переход широкий → узкий �бра�ывает `drawer_open`; + - полка: у�ловие компактной полки §2.5; `compact_shelf()` и заголовок `shelf()` — значки и ширина �пи�ка §2.5. +4. `apps/desktop/src/game_view.rs` `show()`: + - решение «�топка» по §3.1 (функци� от `W`, `H`), `Panel::bottom("game_side_stacked")` вме�то правой панели при �топке; + - `board_area()`: нижн�� граница до�ки `BOARD_MIN = 220`; + - права� панель: верхн�� граница `W − BOARD_MIN − 26 − 24`, нижн�� — минимум вкладки (§1). + +## 4a. Общие �лементы узкой правой панели + +- **Панель ин�трументов** перено�ит�� только между группами (`� ◀ ▶ �` · `🔃 ↩ ↪` · `☰ 📋` · `📈`): группа не разрывает��. Ширина группы измер�ет�� до ра�кладки; е�ли группа не помещает�� в о�таток �троки — нова� �трока; разделитель в конце �троки не ри�ует��. +- **Строка движка** при ширине панели меньше нужной дл� «переключатель · оценка · им�/глубина · ⚙» (измерить): перва� �трока — «�нализ: вкл +0.19 … ⚙», втора� — «Stockfish 19 · глубина 22 · 2.6 Музл/�» мелким приглушённым тек�том, �окращает�� � «…». ⚙ никогда не ри�ует�� поверх тек�та. Им� движка без �троки �о�то�ни� (анализ выключен) выравнивает�� по центру �троки, а не по её верху. +- **Выдвижна� панель фильтров:** тень видна �лева: `Shadow { offset: [-6, 0], blur: 16, spread: 0, color: black α 110 }` вме�то `window_shadow` (у него �мещение вправо-вниз, за край окна, и на тёмной теме тени не видно). +- **Шапка таблицы в две �троки:** втора� �трока начинает�� �о �чётчика без ведущего «· ». + +## 5. Проверка + +Снимки при 640×480, 640×800, 640×1000, 720×1000, 800×600, 800×1000, 820/819 × 900, 880/879 × 900, 960×1050, 1400×900: библиотека (фильтры закрыты и открыты поверх, до�ка), парти� («�отаци�», «Справочник», анализ включён, отчёт � графиком). Признаки правильно�ти: ничего не обрезано �лева, тек�ты не налезают друг на друга, таблица не уже `TABLE_MIN`, до�ка не меньше 220, на границах порогов компоновка мен�ет�� один раз и не мигает при медленном перета�кивании кра� окна. + +## Изменени� + +- 2026-10-24 (ревью реализации f65668c, 0a2c924, 4ebb1bb): §3.3 — нотаци� в �топке таблицей � `CELL_MAX` вме�то не�кольких пар в �троку; вы�ота нижней ча�ти учитывает движок; добавлен §4a (перено� панели ин�трументов по группам, �трока движка в узкой панели, тень выдвижной панели, втора� �трока шапки без «· »). Порог до�ки пои�ка «≈ 880» — по формуле `TABLE_MIN_pos + 340`, фактиче�ки ≈ 870 (879 — ещё р�дом). diff --git a/docs/design/opening-cleanup-2026-11-05.md b/docs/design/opening-cleanup-2026-11-05.md new file mode 100644 index 0000000..1a7f38d --- /dev/null +++ b/docs/design/opening-cleanup-2026-11-05.md @@ -0,0 +1,146 @@ +# Тренировка дебюта: переработка интерфей�а по�ле пользователь�кой проверки + +Дата: 2026-11-05. Стату�: �пецификаци� дл� реализации, не визуальна� приёмка. + +## Задача и причина переработки + +�а �тартовом �кране человек должен выбрать репертуар, пон�ть, что уже знает и что пора повторить, и начать зан�тие. Стати�тика должна отвечать на �ти вопро�ы �ловами пользовател�, а не во�производить �труктуру LearningAggregate. + +Скриншот пользовател� `/tmp/codex-clipboard-edzt9U.png` показывает реальные проблемы, пропущенные прежней приёмкой: `4294967295 полуходов`, �чётчики «Итого / �овый» без единицы измерени�, кнопки разных размеров в п�ти ме�тах, дублирование названи� и чи�ла вариантов. Прежний PASS означал геометриче�кую и�правно�ть и был недо�таточным критерием каче�тва продукта. Данна� работа мен�ет информационную иерархию, а не только от�тупы. + +О�нова визуального �зыка: библиотека партий и �кран партии — обычные панели, таблицы и нотаци�, �покойный фон, �иний цвет только дл� выбранного/о�новного дей�тви�. Без KPI-карточек, декоративных контейнеров и крупных процентов ради процентов. + +## 1. Стартовый �кран + +Сохран�ет�� едина� рабоча� обла�ть: до�ка �лева; �права выбранный репертуар и библиотека. Смена �троки не запу�кает тренировку. Возврат из редактора/�тати�тики/зан�ти� �охран�ет выбранную �троку, размер панели и прокрутку библиотеки. + +Права� панель �верху вниз: + +```text +sicilian + +За кого [Белыми] [Чёрными] +Пор�док [По ра�пи�анию ▾] + +Изучено 0 из 23 ходов +Пора повторить: 0 · Ещё не изучали: 23 + +[ Тренировать�� ] [ Параметры ] [ Стати�тика ] +───────────────────────────────────────────── +[ Создать ] [ Импорт PGN… ] +�азвание ECO Варианты +…библиотека… +``` + +При наличии ограничени� выбранного репертуара р�дом �о �водкой допу�кает�� короткое «Ча�ть репертуара» � tooltip о на�троенном ограничении. �е печатать техниче�кий depth/plies, sentinel, вычи�ленную дату или формулу scope. Чи�ла на �том �кране отно��т�� к реальной очереди зан�ти�; чи�ло изученных нельз� делить на общий полный репертуар при ограниченной тренировке. + +### Ра�положение дей�твий + +- О�новные дей�тви� зан�ти� — одна �трока, ровно три равных по ширине кнопки. Вы�ота 30 pt, промежутки 8 pt; ширина `(до�тупна� ширина − 16)/3`. �адпи�и по центру, без перено�а. Primary только «Тренировать��» / «Продолжить»; две другие нейтральные. +- Тек�т primary не �одержит чи�ла и не мен�ет�� на длинное «Добавить новые ходы». Е�ли �роков повторени� нет и е�ть новые ходы, дей�твие по-прежнему начинает зан�тие � новым материалом. Это объ��н�ет�� �водкой, tooltip и �о�то�нием зан�ти�. +- �е выно�ить Edit �права от заголовка, Details �права от �тати�тики и маленькое ⋯ в третий угол. «Редактировать» до�тупно в меню �троки репертуара р�дом � Rename/Import/Export/Delete; �то операции над материалом, не дей�тви� зан�ти�. +- Параметры зан�ти� открывают единый popup/диалог: пор�док нового материала, контек�т и �коро�ть, затем отделённа� группа «Сбро�ить прогре��…» и при необходимо�ти «�ачать обход заново…». Сбро� подтверждает�� � опи�анием общих ходов; core-�емантика не мен�ет��. �е о�тавл�ть отдельный Reset Review Order под о�новной �трокой. +- «Создать» и «Импорт PGN…» принадлежат библиотеке: отдельна� �трока под разделителем, одинакова� вы�ота 28 pt и �огла�ованна� ширина не менее 120 pt. �е повтор�ть их у до�ки. +- Чи�ло вариантов о�таёт�� в �толбце таблицы. Дубликат крошечным �ерым тек�том возле CTA удалить. + +### Тек�ты и �мы�л + +| Сейча� | �а �кране | По��нение при наведении | +|---|---|---| +| Total / Итого | В �водке: «Изучено X из Y ходов»; в ра�ширенных таблицах: «Ходов дл� изучени�» | Уникальные ответы выбранной �тороны. Общие позиции �читают�� один раз. | +| Unseen / �овый | «Ещё не изучали» | Эти ходы ещё не в�тречали�ь в тренировке. | +| Learning / Изучает�� | «Закрепл�ем» | Дл� закреплени� нужны три �амо�то�тельных правильных ответа подр�д. | +| Learnt / Изучено | «Изучено» | �е менее трёх �амо�то�тельных правильных ответов подр�д. Знание требует по�ледующих повторений. | +| Due / К повторению | «Пора повторить» | Срок очередной проверки уже на�тупил. | +| Uncertain | «Давно не повтор�ли» | Ча�ть ранее изученных ходов, проверка которых �ильно про�рочена. �е добавл�ет�� к общему чи�лу второй раз. | +| Confident % | «�ктуальные знани�» только в подробной �тати�тике | Изученные ходы без �ильно про�роченной проверки. | +| Review individual moves | «По ра�пи�анию» | Повтор�ем ходы, �рок проверки которых на�тупил, затем вводим новые. | +| Review in order | «По пор�дку» | По�ледовательный обход материала. | +| Least recent and unseen first | «Сначала новые и давно не повторённые» | Длинное по��нение допу�тимо в popup, выбранный тек�т может �окращать��. | + +�е мен�ть глобальный перевод общего `Total`, который и�пользует�� в других разделах: в тренажёре нужны �об�твенные ключи. + +Со�то�ни� �водки занимают одинаковые две �троки. При загрузке — прочерки и краткое «Обновл�ем прогре��…» без ра�ширени� панели. При нулевом материале — «�ет ходов дл� тренировки» и «Добавьте варианты через редактор или импорт PGN»; primary выключен. При Due=0 не пи�ать «В�ё изучено». При Unseen>0 нейтральное по��нение — «Следующее зан�тие начнёт�� � новых ходов», е�ли требует��, в tooltip primary. + +## 2. Длина материала + +�и «полуходы», ни чи�ловой sentinel не должны по�вл�ть�� на обычном �тартовом �кране или в �водке. `u32::MAX` отображает�� только как «Без ограничени�». + +В редакторе ограничение — второ�тепенна� на�тройка «Длина вариантов», изначально �вернута�. Переключатель «Без ограничени�» должен быть отдельным checkbox; чи�ловой ввод не активен, когда он включён. Сн�тие ограничени� — �вное дей�твие, не побочное �лед�твие открыти� редактора. + +�ельз� молча округлить �тарый нечётный `max_plies` до чи�ла полных ходов: �то мен�ет материал зан�ти�. В рамках текущей переработки предпочтительнее убрать чи�ловой лимит из о�новного редактора, �охранив �уще�твующий конечный лимит и возможно�ть �вного �н�ти� ограничени�; его точна� дальнейша� форма редактировани� требует отдельного решени�. Е�ли команда �охран�ет чи�ловой legacy-контрол на данном �тапе, он должен быть �крыт в дополнительных параметрах и че�тно именовать единицу. �е выдавать `20 plies` за `20 ходов`. Это и�ключение не оправдывает возврат техниче�кой �троки в prep. + +## 3. Экран �тати�тики + +Задача: показать прогре�� выбранного материала и помочь пон�ть, что повтор�ть. �азвание �крана «Стати�тика тренировки», а не «Панель обучени�». + +Шапка: �лева «� К репертуару», далее название. Под ней одна �трока фильтров «Репертуар [sicilian ▾] За кого [Чёрными ▾]». Значение глобального scope — «В�е репертуары», без �лова «объединение». Дедупликаци� объ��н�ет�� в tooltip общего итога. �е дублировать ту же пару фильтров �ледующей тек�товой �трокой и не выводить «Ра��читано в…» как по�то�нную пользователь�кую информацию. + +О�новные вкладки: **Обзор · Динамика · Ра�пи�ание · Ходы**. Дополнительные отчёты «Варианты» и «Серии ответов» открывают�� через компактное меню «Дополнительно» на той же �троке, е�ли их �охран�ют в UI. При их открытии текущий отчёт имеет видимый заголовок; нельз� о�тавл�ть активной неверную о�новную вкладку. + +### Обзор выбранного репертуара + +Выбран конкретный репертуар — показываем только его �водку: + +```text +Изучено 8 из 23 ходов 35 % +[поло�а прогре��а] + +Пора повторить 4 +Ещё не изучали 10 +Закрепл�ем 5 +Давно не повтор�ли 2 +Следующее повторение завтра / — +``` + +Прогре�� компактный и в�троенный, без декоративной карточки. «Давно не повтор�ли» �опровождает�� «из чи�ла изученных» в tooltip. �ет попыток — точно�ть «—», не ноль. Когда е�ть Due, вме�то пу�той даты пи�ать «Е�ть ходы дл� повторени�» либо показывать только Due. Дополнительные метрики — под ра�крывающим�� «Как �читает�� прогре��», где объ��нение короткое и без идентификаторов API. + +Выбраны в�е репертуары — �равнительна� таблица из **п�ти** �толбцов: «Репертуар», «Изучено» (X/Y), «Прогре��» (%), «Пора повторить», «Ещё не изучали». �ижн�� �трока «В�его без повторов». �азвание получает не менее 40% ширины. �е показывать таблицу в�ех репертуаров под фильтром одного — �то противоречит выбранному контек�ту. + +### Динамика и �охранение + +Удалить кнопку «Сохранить �тати�тику в и�торию» и по�то�нные у�пешные �ообщени� о snapshot. �втоматиче�кий механизм �нимков о�таёт��. Во вкладке «Динамика» короткое по��нение: «Прогре�� �охран�ет�� автоматиче�ки при первом про�мотре за день». �е обещать ежедневные фоновые �нимки, которых нет. Пу�та� и�тори�: «Зде�ь по�вит�� изменение вашего прогре��а». Ошибка �охранени� — в �той вкладке � дей�твием «Повторить», без �лужебных деталей на каждом �кране. + +### Варианты: зачем и как + +�ынешн�� таблица из де��ти колонок �лишком рано включает wide-режим; дл� пути о�таёт�� 120–150 pt. Это превращает �мы�ловой �толбец в обрезанную �троку и не помогает решить, что повтор�ть. Сохранить core-агрегаты, убрать отчёт � о�новного пути. + +Е�ли отчёт до�тупен через «Дополнительно → Варианты», его задача пр�мо напи�ана: «Какие продолжени� �тоит повторить. Общие ходы могут в�тречать�� в не�кольких вариантах». �а в�ех ширинах одна модель из четырёх колонок: + +1. «�ачало варианта» — не менее половины ширины, SAN, полный тек�т до�тупен при выборе. +2. «Изучено» — X/Y, не два голых �чётчика. +3. «Пора повторить» — N. +4. «Точно�ть» — % / —. + +Под таблицей по�то�нна� по размеру обла�ть выбранного варианта: полный SAN � перено�ом, три-четыре пон�тные метрики. �е пытать�� поме�тить дату, дев�ть чи�ел и длинный SAN в одну �троку. Выбор �троки должен давать видимое полезное �лед�твие; е�ли отчёт не предлагает о�мы�ленного дей�тви�/деталей, лучше временно убрать его из пользователь�кого UI целиком, �охранив ра�чёты. �азвание «Ветки» заменить на «Варианты» — �лово �огла�овано � библиотекой. + +## 4. Библиотека, плотно�ть, редактор + +Библиотека о�таёт�� таблицей, а не лентой карточек. Сейча� фик�ированные 156 pt были ранее �вно �огла�ованы дл� п�ти ECO; нова� задача позвол�ет пере�мотр, но �то не об�зательное у�ловие и�правлени� верхнего блока. Рекомендуемый �ледующий шаг, е�ли нужен компактный �пи�ок: вы�ота по готовому �одержимому, им� + 1–5 �трок дебютов, 6 pt �верху/�низу, без пу�того резерва под от�ут�твующие �троки. Показывать готовый набор �трок атомарно по�ле индек�ации; при обновлении �охран�ть anchor выбранной �троки. �е допу�кать по�тепенного ра�т�гивани� каждой �троки по мере фоновых ответов. Е�ли �то не реализовано надёжно, текущие 156 pt временно �охран�ют��; не ма�кировать нехватку ме�та уменьшением шрифта. + +Редактор: дерево — о�новна� обла�ть, детали выбранного хода �низу. Сохранить фик�ацию дерева, левое выравнивание, отдельную прокрутку аналитики и одинаковую � prep геометрию до�ки. Команды редактировани� одной группы одинаковой вы�оты. �е �оздавать вторую копию полной �тати�тики в редакторе. + +## 5. Размеры и поведение + +- Базовый тек�т — �уще�твующий body приложени�; заголовок репертуара — existing heading, без нового размера. +- Между пол�ми 6 pt, между �мы�ловыми группами 10–12 pt. Граница библиотеки одна, без декоративных заливок. +- Пол� параметров выровнены �еткой. �е ра�т�гивать подпи�и и чи�ла по разным кра�м широкой панели без причины. +- Длинные имена truncate + tooltip; ширина кнопок и ме�то под них ра��читывают�� до тек�та имени. +- Стандартные выбранные �о�то�ни� темы и primary приложени�. Со�то�ни� «ошибка/под�казка/завершено» различают�� тек�том, не только цветом. +- Tab/Shift+Tab обход�т им�/меню, параметры, CTA, вторичные дей�тви� и библиотеку по�ледовательно. Enter активирует �фоку�ированную кнопку; Escape �начала закрывает popup, затем возвращает на предыдущий �кран. �е запу�кать зан�тие про�то от Enter во врем� редактировани� имени. +- Пу�тое/загрузка/ошибка занимают те же �мы�ловые обла�ти. Ошибки �охранени� нельз� �крывать ради кра�оты; длинные детали ра�крывают�� отдельно. + +## 6. Приёмка по задаче пользовател� + +�ужен другой reviewer, не автор �того документа и не автор реализации. Реальные �нимки RU 960×600 и 1400×900 в обеих темах, �равнение � библиотекой и партией. Помимо bbox он должен ответить: + +1. Пон�тно ли без tooltip, �колько ходов изучено и что делать �ейча�? +2. Видны ли в�е три главные кнопки одной группой, одинаковых размеров и на одном baseline? +3. От�ут�твуют ли u32MAX, «полуходы», «Итого / �овый», ручное �охранение и�тории и техниче�кие snapshot-�ообщени� на обычном пути? +4. При фильтре одного репертуара �водка дей�твительно отно�ит�� к нему? +5. Можно ли проче�ть идентифицирующий SAN в отчёте вариантов и пон�ть пользу его выбора? +6. Empty/new/learning/due/all-learnt, длинное им�, загрузка данных и возврат не ломают иерархию? +7. Сохранены ли главные дей�тви� при 960×600 без �кролла, а библиотека получила заметную долю вы�оты? +8. Изменение layout не изменило PGN, SRS и �уще�твующие конечные ограничени� молча? + +«В�е надпи�и поме�тили�ь» — необходимое, но недо�таточное у�ловие. Вердикт должен опи�ывать �ценарий, который �тал пон�тнее, и конкретные о�тавшие�� трудно�ти. diff --git a/docs/design/opening-trainer-concept-2026-11-26.md b/docs/design/opening-trainer-concept-2026-11-26.md new file mode 100644 index 0000000..dcfd6ab --- /dev/null +++ b/docs/design/opening-trainer-concept-2026-11-26.md @@ -0,0 +1,67 @@ +# Тренировка дебюта: нова� концепци� (2026-11-26) + +Стату�: решение орке�тратора по поручению владельца («проработай �ам: проще, пон�тнее, +функционально; другие разделы не трогать»). О�новани�: `docs/research/opening-trainer-rethink-2026-11-26.md` +(аналитик), `docs/research/opening-trainer-code-audit-2026-11-26.md` (разработчик), +`docs/design/opening-trainer-ui-audit-2026-11-26.md` (дизайнер), руковод�тво и форум ChessTempo +(корпу�: `target/qa-opening-rethink/chesstempo-corpus/`). + +## Иде� в одной фразе + +Репертуар — �то PGN-дерево за один цвет; кнопка «Тренировать��» проводит по лини�м от начала, +�прашивает только те �вои ходы, которые пора повторить или которые новые, и заканчивает зан�тие +пон�тным итогом. В�ё о�тальное — во втором плане или удалено. + +## Сценарий + +1. «Тренировка дебюта» → один �кран: �лева до�ка (геометри� �крана партии), �права таблица + репертуаров (�тиль таблицы библиотеки) и карточка выбранного. +2. Пу�то → тек�т и две кнопки: «Импорт PGN…», «�овый репертуар». Ещё путь — «Добавить в репертуар…» + из �крана партии (уже е�ть, не мен�ет��). +3. Карточка: название · «Играю белыми/чёрными» · «Сегодн�: N повторить · M новых» · + «Выучено X из Y ходов» � поло�ой · о�новна� кнопка **Тренировать��**. +4. Зан�тие: программа проигрывает ходы �оперника и уже уверенно изве�тные �вои ходы � анимацией, + о�танавливает�� на �прашиваемом ходе. Одна �трока �о�то�ни� �верху: что делать �ейча� и «О�тало�ь N». + - **�овый ход:** показан �трелкой и подпи�ью «�овый ход — �ыграйте его»; комментарий PGN виден. + - **Повторение:** «Ваш ход» без �трелки. + - **Верно:** короткое «Верно», комментарий к ходу, дальше. + - **�еверно:** фигура возвращает��, «Правильно: Сb5» + �трелка, пользователь играет его; ход + вернёт�� в �том же зан�тии. + - «Под�казка» (H) — показать ход; за�читывает�� как показанный, а не как верный. +5. Конец: «Готово. Верно 14, ошибок 2. Следующее повторение — завтра» и кнопки «К репертуару» / + «Ещё 10 новых» (е�ли е�ть). +6. Меню �троки `⋯`: «Повторить в�ё подр�д» (обзор перед турниром, лини� за линией), «Про�мотр + вариантов» (дерево ходов: выбрать ход → «Тренировать �ту ветку», «�е тренировать»/«Тренировать»), + переименовать, �менить цвет, �к�порт PGN, �бро� прогре��а (� подтверждением), удалить. + +## Уточнени� по UI-аудиту дизайнера (прин�ты) + +- Со�то�ние зан�ти� («�овый ход», «Ваш ход», «�еверно…», «О�тало�ь N») живёт в карточке правой + панели, как �тату� партии в игре � компьютером, а не �трокой над до�кой. +- Цвет репертуара �прашивает�� при импорте/�оздании (�ейча� чёрный PGN открывает�� как «Белые», `op-04`). +- Меню `⋯` дей�твует только на �вою �троку; вёр�тка таблицы в узкой панели провер�ет�� на 960×600. + +## Решени� по открытым вопро�ам + +| Вопро� | Решение | Почему | +| --- | --- | --- | +| Единица тренировки | Ход (SRS по `(FEN4, UCI)`), подача — линией от начала | �дро ChessTempo; лини� даёт контек�т, который владелец про�ил 02–03.11 | +| Единица прогре��а | Ходы | че�тно отражает модель; варианты пере�екают�� | +| Порци� новых | 10 за зан�тие, кнопка «Ещё 10 новых» | ��ный конец зан�ти�; без на�тройки | +| Режимы, пор�дки, 6 параметров контек�та, окно параметров | Удалить из UI | главный и�точник прошлых отказов; типы в Settings о�тают��, чтобы не �бро�ить на�тройки | +| Дашборд, графики, вкладки, отчёт Branches/Lines, Uncertain/Resistant | Удалить из UI | замен�ют�� трем� чи�лами карточки; данные на ди�ке не трогают�� | +| Режим «за оба цвета» | Удалить из UI | у репертуара один цвет; �тарые «Both» открывают�� как белые/выбор цвета при первом запу�ке | +| Лимит глубины `max_plies` | Снимать при загрузке (как 03.11 �н�ли �тарые лимиты) | пользователь его не выбирал; PGN не мен�ет�� | +| �езавершённые �е��ии 2.x | �е возобновл�ть, начинать новое зан�тие | в�е ответы уже запи�аны; прогре�� не тер�ет�� | +| Редактирование ходов на до�ке | �е в �том �тапе | нова� функци�; добавление идёт через PGN и «Добавить в репертуар…» | +| �е�колько �воих ответов (2.3.0) | Сохранить | уже выпущено | +| Пометки PGN и временные �трелки | Сохранить | выпущено/в работе, полезно | + +## Границы + +- База — `main` (2.3.0), отдельный worktree. Рабочее дерево ветки `feature/opening-repertoire-training` + � незакоммиченными временными �трелками не трогает��; при интеграции �трелки перено��т��. +- Мен�ют�� только файлы раздела в `apps/desktop/src` и минимальные дополнени� �дра + `crates/trainer/src/repertoire` (�мешанна� очередь «к повторению + N новых», возврат ошибки в том же + зан�тии). Формат файлов, Settings-типы, `app.rs`, библиотека, �кран партии, до�ка, Android — без изменений. +- Мёртвый код �дра (`session.rs`, `stats.rs`, `StatsStore`) удал�ет�� отдельной задачей по�ле приёмки. diff --git a/docs/design/opening-trainer-ui-audit-2026-11-26.md b/docs/design/opening-trainer-ui-audit-2026-11-26.md new file mode 100644 index 0000000..fafba24 --- /dev/null +++ b/docs/design/opening-trainer-ui-audit-2026-11-26.md @@ -0,0 +1,140 @@ +# Тренировка дебюта: аудит интерфей�а по реальным �нимкам (2026-11-26) + +Стату�: аудит дизайнера, **не макет**. И�ходный код и другие документы не мен�ли�ь. +Отчёты аналитика и разработчика (`docs/research/opening-trainer-*-2026-11-26.md`) не пере�казывают��. + +## 0. Как �нимало�ь и что не �н�то + +- Снимки: `target/qa-opening-rethink/shots/`, в�е 1400×900, тёмна� тема, ру��кий, ма�штаб 1. +- Вер�ии: **[2.2.0+]** — рабочее дерево (`f425e3a` + незакоммиченные правки); **[2.3.0]** — `main` @ `ddc8361`, + worktree `/tmp/opencode/cp-main`, цель �борки `/tmp/opencode/cp-main-target`. + - [2.2.0+]: `ref-01…06`, `op-01…10`, `op-12`. + - [2.3.0]: `op-11`, `op-13`, `op-20…28`, `op-30…43`, `op-50`. +- Изол�ци�: отдельные `HOME`/`XDG_*` в `/tmp/opencode/qa/prof-*`; на�то�щие данные пользовател� не измен�ли�ь. + Окно — вложенный Xwayland `:7`, ввод XTEST, �тарт �о�то�ний dev-хуками `CP_*`. Данные — два �воих PGN � + вариантами, импортированные через интерфей�. +- **�е �н�то** (обрыв бюджета и ограничени� �тенда): 960×600; конец зан�ти�; �бро� прогре��а; модальное + «Добавить в репертуар» из партии; автопоказ подвод�щих ходов; кадр «верно» �разу по�ле ответа (�тенд + задерживает �обыти� ввода — длительно�ти пауз тоже не измер�ли�ь); HiDPI; �ветла� тема. + `op-28` (вкладка «Серии») �н�т, но не про�мотрен. По �тим �о�то�ни�м выводов ниже нет. + +## 1. Под�чёты (по �нимкам) + +| Что | Сколько | Снимки | +| --- | --- | --- | +| Экраны раздела | 4: рабоча� обла�ть, задание, �тати�тика, «редактор» | `op-06`, `op-30`, `op-22`, `op-50` | +| Вкладки �тати�тики | 6 (4 видимых + 2 в меню «Дополнительно») + 2 �електора | `op-22…27` | +| Окна и в�тавные формы | модальное «Параметры» (8 �лементов управлени�, 9 абзацев по��нений); в�тавные формы импорта, имени, удалени�; меню �троки (5 пунктов); �пи�ок режимов (3) | `op-09`, `op-02`, `op-11`, `op-10`, `op-08`, `op-07` | +| Элементы управлени� на �тартовом �кране (2 репертуара) | 14: назад, на�тройки, цвет ×2, режим, 3 кнопки, 2 �троки, 2 меню `…`, «Создать», «Импорт» + 3 �троки �чётчиков | `op-06` | +| Элементы управлени� в задании | 4: назад, на�тройки, «Под�казка», переворот | `op-30` | +| Шагов до первого хода | 2 клика, только е�ли нужный репертуар первый по алфавиту и цвет угадан; иначе 4 (�трока, цвет). С нул�: импорт → файл → «Добавить» → ожидание → цвет → «Тренировать��» = 5–6 | `op-01…06`, `op-30` | + +## 2. Главные проблемы + +1. **Задание не говорит, какой ход нужен.** Первый же вопро� по ни разу не виденному ходу: «Ваш ход: �ыграйте + ход из репертуара» — без показа (`op-30`, 2.3.0). Подтверждает вывод разработчика «новый ход �прашивает�� + без предварительного показа». �аказание �ледует �разу: «Ошибка» (`op-31`). +2. **Тек�ты обратной �в�зи — �зык модели, не человека.** «Повторите показанный ход; �то не будет + �амо�то�тельным у�пехом» (`op-31`, причём ход в �тот момент ещё не показан — �трелка по�вл�ет�� позже, + `op-33`), «Ход повторён по�ле ошибки. Само�то�тельный ответ не за�читан» (`op-34`), «Ответ � под�казкой + не �читает�� �амо�то�тельным» (`op-36`). �азвание правильного хода тек�том не пишет�� нигде. +3. **Блок �о�то�ни� мен�ет вы�оту и вид**: одна �трока (`op-30`) → две �троки � кра�ной рамкой (`op-31`) → + две �троки без рамки (`op-33`). Права� панель при �том на 85 % пу�та�: 700 px ниже блока не и�пользуют��. +4. **�ет прогре��а зан�ти�.** «Заданий: 2 из 51» (`op-38`) — �то �чёт от в�его репертуара; �колько о�тало�ь + �егодн� и где конец, не видно. Под заголовком — �лужебное «По ра�пи�анию · Белые». +5. **Цвет не �вой�тво репертуара.** Репертуар за чёрных по�ле импорта открыт � «Цвет: Белые» и предлагает + учить ходы белых (`op-04`: 8 ходов; на 2.3.0 — 17, `op-11`). Пользователь об�зан помнить и переключать. +6. **Скрытый лимит глубины подтверждён.** Оба импортированных репертуара получили `max_plies = 20` + (проверено в `repertoires.json` изолированного профил�); на �кране �то только бледна� �трока + «Тренировка: ча�ть репертуара» (`op-06`), а �амо чи�ло видно лишь в «редакторе»: «Глубина 20 полуходов» + (`op-50`). +7. **«Редактор» («Изменить») не редактирует ходы** — подтверждено: пло�кий �пи�ок одной главной линии без + вариантов, чекбок� глубины и «�налитика хода» (`op-50`). Варианты, которые видны в библиотеке (4), зде�ь + не найти. +8. **В�тавные формы вме�то диалогов, �пи�ок прыгает.** Импорт (`op-02`, `op-05`), им� (`op-11`, `op-13`), + удаление (`op-10`) в�тавл�ют�� над таблицей и �двигают её на 22–88 px; положение формы зави�ит от того, + выбран ли репертуар (y=145 в `op-02`, y=323 в `op-05`). Эталоны дл� того же и�пользуют модальные окна. +9. **Дей�твие �троки не прив�зано к объекту.** Меню `…` �троки white открывает�� при выбранном black + (`op-08`); вопро� «Удалить репертуар?» не называет им� (`op-10`); поле переименовани� white �тоит над + �пи�ком при под�веченном black (`op-11`). Ри�к удалить не то. +10. **Мигание при выборе и возврате.** �а �екунду и более �чётчики превращают�� в «Изучено … из … ходов», + три кнопки га�нут (`op-12`, `op-42`), затем кнопка мен�ет подпи�ь на «Продолжить» (`op-43`). По�ле + импорта форма о�таёт�� на �кране, пока �трока крутит индикатор (`op-03`) — владелец про�ил без �пиннеров. +11. **Строка таблицы — 158 px.** П�ть �трок ECO-названий на англий�ком на репертуар; на �кран входит 3–4 + репертуара (`op-06`). В библиотеке �трока 27 px (`ref-01`). Им� берёт�� из имени файла («white»), а не + из `Event` PGN. +12. **Три режима и окно параметров на пути к запу�ку** (`op-07`, `op-09`): «По ра�пи�анию / Подр�д / Сначала + новые и давние», «Верных ответов подр�д», «Дней до �рока повторени�», «Пропу�к знакомого начала … 100». + Окно при открытии дора�тает на �троку «Сбро�ить прогре��…» (наблюдало�ь на двух кадрах подр�д; �охранён + только итоговый `op-09`). +13. **Стати�тика — отдельное приложение.** Пу�тые полно�кранные ли�ты (`op-20`, `op-22`), повторный выбор + репертуара и �тороны, термины «Элементы», «Введено в обучение», «От�рочка до потери подтверждени�», + «�адёжно изучено %», «Изучено = надёжно изучено + неподтверждено» (`op-22`, `op-24`, `op-25`). + «Ходы» — �пи�ок SAN без номера и линии, � повторами «Bb3» (`op-25`); «Варианты» — �пи�ок префик�ов + «1. d4», «1. d4 1… d5», а не вариантов (`op-27`); «Динамика» показывает 0/51/0, когда в обзоре уже 2 к + повторению, о�ь «0–0», дата ISO (`op-23`). Две вкладки �пр�таны в кнопку, похожую на вкладку (`op-26`). +14. **Счётчики ра�ход�т�� по �ловам и �мы�лу.** «�е изучали�ь: 47 · Пора повторить: 2» (`op-43`) против + «Ещё не изучали 47 / В проце��е изучени� 4 / Пора повторить 2» (`op-22`) по�ле трёх �ыгранных ходов; + в задании тот же объект назван «Заданий». +15. **�е�огла�ованно�ть � �талонами.** До�ка прижата к левому краю (x=8…832, `op-06`), на �кране партии она + по центру �воей обла�ти (x=54…886, `ref-02`); шапка одно�трочна� 30 px � «� Базы» против двух�трочной + 52 px � «⬅ Библиотека» (`ref-02`, `ref-04`); права� панель 560 px против 460 px; главна� и второ�тепенные + кнопки одной вы�оты и ширины в р�д (`op-06`), в �талонах главна� одна и �права внизу (`ref-03`, `ref-05`). + До�ка �тартового �крана ничего не показывает — выбор репертуара её не мен�ет (`op-04`, `op-06`). + +## 3. Паттерны �талонов дл� переи�пользовани� + +�омера �трок — по рабочему дереву [2.2.0+]; на `main` �верить. + +| Паттерн | Где видно | Код | +| --- | --- | --- | +| Шапка раздела: кнопка назад, разделитель, заголовок, «�а�тройки» �права | `ref-06`, `op-06` | `widgets.rs:14` `section_header`, `widgets.rs:6` `settings_button` | +| Шапка партии: две �троки (заголовок + бледна� подпи�ь), бейдж �права от заголовка | `ref-02`, `ref-04` | `game_view.rs:952` `header` | +| Геометри� «до�ка + права� панель 460 px», до�ка по центру обла�ти | `ref-02`, `ref-04` | `game_view.rs:1217` `board_area`, `game_view.rs:1467` `side_panel` | +| Карточка �о�то�ни� в правой панели (им�, подпи�ь «ваш ход/ждёт», активна� — � заливкой) | `ref-04` | `game_view.rs:3432` `clock_card` | +| �ижн�� поло�а значков 30×30 под панелью, дей�твие («Прервать») отдельной �трокой | `ref-02`, `ref-04` | `widgets.rs:127` `icon_button` | +| Главна� кнопка: заливка цвета выделени�, жирный тек�т, вы�ота 30; одна на �кран/диалог | `ref-03`, `ref-06` | `widgets.rs:112` `primary`, `widgets.rs:117` `primary_wide` (ширина не �качет при �мене подпи�и) | +| Диалог: `egui::Modal`, заголовок, �екции � жирным подзаголовком, бледные по��нени�, «Отмена» + главна� �права внизу | `ref-03`, `ref-05` | `play.rs:1256`, `prep_ui.rs:534`, `own_db.rs:143` | +| Подтверждение опа�ного дей�тви� — модальное, � именем объекта | — (по коду) | `own_db.rs:806`, `app.rs:2196` | +| Сегментный выбор из 2–3 значений плашками (Белые / Случайно / Чёрные) | `ref-03` | `play.rs:1256` и ниже (там же �етка контролей) | +| Таблица: �трока 27 px, чередование фона, �ортируемые заголовки, выделение заливкой | `ref-01`, `ref-06` | `large_db.rs:2106`, `prep_ui.rs:4052` (`TableBuilder`), `widgets.rs:64` `sort_header` | +| Пу�тое �о�то�ние: бледный тек�т по центру + одна главна� кнопка | `ref-06` | `prep_ui.rs:4761` | +| Вкладки-плашки над �одержимым панели | `ref-02`, `ref-06` | `game_view.rs:221` (`side_tab`), `prep_ui.rs:1703` | +| Строка-�водка бледным под заголовком («PGN, кодировка UTF-8 · 100 партий») | `ref-01` | `library.rs:1466` `header` | +| Типографика: заголовок `heading`, о�новной тек�т 14, по��нени� `weak()`, предупреждение оранжевым | `ref-03`, `ref-06` | `docs/design/design-system.md` | + +## 4. Предварительные принципы нового раздела + +1. Два �крана: «репертуары» и «зан�тие». Стати�тика и «редактор» как отдельные �краны и�чезают. +2. Зан�тие повтор�ет �кран игры � компьютером: та же шапка, до�ка по центру, панель 460 px, карточка + �о�то�ни� фик�ированной вы�оты, поло�а значков �низу. �ичего нового не изобретать. +3. Блок «что делать �ейча�» — одного размера во в�ех �о�то�ни�х; тек�т называет ход («Правильно: Сb5»), + цвет рамки не един�твенный признак ошибки. +4. �овый ход �начала показан (�трелка + подпи�ь), потом �прашивает��. +5. В зан�тии виден о�таток («О�тало�ь N»), а не дол� в�его репертуара. +6. Цвет задаёт�� один раз при �оздании или импорте и хранит�� в репертуаре; на пути к запу�ку — одна кнопка. +7. В�е вопро�ы и формы (импорт, им�, удаление, �бро�) — `egui::Modal` � именем объекта. Спи�ок никогда не + �двигает��. +8. Строка репертуара — одна, 27 px: им�, цвет, «повторить �егодн�», «выучено X из Y». ECO-названи� — в + карточке выбранного или в под�казке. +9. Одни и те же �лова дл� одних и тех же чи�ел на в�ех �кранах; ни одного из терминов п. 2.2 и 2.13. +10. �икаких переходных «…» и га�нущих кнопок: до готовно�ти данных показывает�� прежнее значение. + +## 5. Замечани� к концепции (`opening-trainer-concept-2026-11-26.md`) + +- **«Одна �трока �о�то�ни� �верху»** — на �талоне игры �о�то�ние живёт в карточке правой панели + (`ref-04`), а не над до�кой. Предлагаю карточку в панели; иначе до�ка зан�ти� �ме�тит�� отно�ительно + �крана партии. +- **«Таблица в �тиле библиотеки» + карточка выбранного** — в панели 460 px таблица библиотеки � 4 колонками + не поме�тит�� без обрезани�; нужна проверка прототипом на 960×600 (панель там уже). Чи�ло колонок — не + больше трёх. +- **Меню `⋯` из �еми пунктов** пр�чет две функции («Повторить в�ё подр�д», «Про�мотр вариантов»), а + о�тальные — �лужебные. Меню должно дей�твовать на выбранную �троку и только на неё (�ейча� �то нарушено, + `op-08`); «Про�мотр вариантов» лучше дать видимой второ�тепенной кнопкой карточки. +- **«Сменить цвет» в меню** — нужен и момент первого выбора: импорт �ейча� молча �тавит «Белые» (`op-04`). + Определ�ть по PGN или �прашивать в диалоге импорта. +- **Конец зан�ти�: две кнопки** — главна� одна («К репертуару» или «Ещё 10 новых» — решить), втора� обычна�. +- **До�ка на �кране репертуаров** �ейча� декоративна (`op-06`). Либо она показывает позицию выбранного + варианта, либо её �тоит обо�новать заново. +- **Сн�тие `max_plies` при загрузке** увеличит «Y» у �уще�твующих репертуаров — в карточке �то не должно + выгл�деть как потер� прогре��а. diff --git a/docs/design/opening-trainer-v2-spec.md b/docs/design/opening-trainer-v2-spec.md new file mode 100644 index 0000000..c41177b --- /dev/null +++ b/docs/design/opening-trainer-v2-spec.md @@ -0,0 +1,470 @@ +# Тренировка дебюта v2: �пецификаци� интерфей�а (2026-11-26) + +О�нование: `opening-trainer-concept-2026-11-26.md` (продуктовые решени� не пере�матривают��), +`opening-trainer-ui-audit-2026-11-26.md` (�нимки `ref-*`, `op-*`). �омера �трок — по �тому worktree +(`feature/opening-trainer-v2`, 2.3.0). Тек�ты: EN — ключ `tr("…")`, RU — �трока `i18n.rs`; о�тальные +четыре �зыка — по образцу. Размеры в pt при ма�штабе 1. + +Задача раздела одной фразой: **выбрать репертуар и одной кнопкой начать зан�тие, в котором в каждый момент +напи�ано, что делать, и виден конец**. + +Три �крана: **Репертуары** (§2–3), **Зан�тие** (§4–6), **Варианты** (§6.3). Диалоги — §7. Других �кранов, +окон и вкладок нет. + +## 1. Компоновка (обща� дл� трёх �кранов) + +В�е три �крана и�пользуют один карка�. Переход между ними не мен�ет ни пр�моугольник до�ки, ни ширину панели. + +| Обла�ть | 1400×900 | 960×600 | Как �делать | +| --- | --- | --- | --- | +| Шапка | вы�ота 52 (y 0…52) | 52 | Две �троки, как у партии (`ref-02`, `ref-04`): �трока 1 — кнопка «назад», разделитель, заголовок `heading` � обрезкой, �права `settings_button`; �трока 2 — бледна� подпи�ь � обрезкой. `GameView::header` (`game_view.rs:952`) закрыт и �в�зан � партией, по�тому: **нова�** функци� `widgets::section_header_sub(ui, back, title, subtitle) -> (bool, bool)` р�дом � `section_header` (`widgets.rs:14`), повтор�юща� от�тупы `game_view.rs:958` (`add_space(4)`) и �троку подпи�и `game_view.rs:1151`. Суще�твующие функции не мен�ть. | +| Права� панель | ширина 460 (x 940…1400) | 384 | `egui::Panel::right("opening_side")`, один id на в�е три �крана. Формула партии, `game_view.rs:788–800`: `default_size((width*0.4).clamp(260.0, 460.0).min(room))`, `room = (width - board - 24).clamp(least, most)`, `resizable(true)`, `size_range(least..=most)`, `least = 320` (как `REF_MIN`, `game_view.rs:5001`), `most = (width - 220 - 24).max(least)`. По�ле — `widgets::check_panel` (`widgets.rs:36`). | +| До�ка | квадрат 832, x 54…886, y 60…892 | квадрат 532, x 22…554, y 60…592 | `CentralPanel`; квадрат по центру обла�ти, формула `game_view.rs:1250–1253`. Виджет `BoardView::show` (`board.rs:169`, `:194`) � на�тройками до�ки пользовател�. Поло�ы оценки нет. | +| Узкое/вы�окое окно | — | — | Правило партии `game_view.rs:761–763`: е�ли `board_stack >= 1.25 * board_side` — до�ка �верху, панель �низу вы�отой ≥ 300 (`STACK_BOTTOM_MIN`). Текущее �об�твенное правило `learning_training.rs:1530` (`width < 900 && height > width`) удалить. | + +Внутренние пол� панели: �тандартные egui (как у партии), между блоками 6. �икаких новых цветов, рамок и +шрифтов: заливка выделени� — `visuals.selection.bg_fill`, рамки — `widgets.noninteractive.bg_stroke`, +ошибка — `visuals.error_fg_color`, предупреждение — `visuals.warn_fg_color`. + +Общие компоненты: + +| �ужно | Брать | +| --- | --- | +| Главна� кнопка (одна на �кран/диалог) | `widgets::primary_wide` (`widgets.rs:117`), вы�ота 30, фик�ированна� ширина | +| Обычна� кнопка | `ui.button`, в р�ду � главной — `min_size(vec2(0, 30))` | +| Значки нижней поло�ы 28 pt | замыкание `icon` из `play_toolbar` (`game_view.rs:3563–3564`), переворот — `game_view.rs:3582` | +| Карточка �о�то�ни� | рамка `clock_card` (`game_view.rs:3451–3463`): `inner_margin(10, 6)`, радиу� 4, обводка 1; активна� — заливка `sel.bg_fill.gamma_multiply(0.35)`; ошибка — обводка 1.5 `error_fg_color` | +| Плашки выбора из двух значений | замыкание `choice` (`play.rs:1283–1289`): `Button::selectable(..).frame_when_inactive(true)` | +| Заголовок �екции диалога | `play.rs:1280` (`strong().size(15.0)`) | +| Диалог | `egui::Modal`, `ui.set_width(460.0)`, `ui.heading`, как `game_view.rs:3261–3263`; вопро� � опа�ным дей�твием — как `app.rs:2196`, `own_db.rs:806` | +| Таблица | `TableBuilder`, на�тройки `large_db.rs:2106–2111`, заголовок 26 (`:2146`), �трока 24 (`:2160`) | +| Пу�тое �о�то�ние | `prep_ui.rs:4760` (бледный тек�т по центру + одна `primary`) | +| Дерево ходов | `Notation` (`notation.rs:13`, `show` — `:189`) � `read_only: true` | + +## 2. Экран «Репертуары»: таблица + +Шапка: назад «⬅ Library / ⬅ Библиотека»; заголовок «Opening training / Тренировка дебюта» (пометку +«(α version)» �охранить до решени� владельца — одна �трока `repertoire_ui.rs:1035`); подпи�ь +«{n} repertoires / Репертуаров: {n}», при пу�том �пи�ке подпи�и нет. + +Панель �верху вниз: карточка выбранного (§3, фик�ированна� вы�ота 166) · поле пои�ка (только е�ли +репертуаров > 8, вы�ота 24, под�казка «Search / Пои�к») · таблица (в�ё о�тавшее��, прокрутка) · поло�а +�ообщени� (вы�ота 20, в�егда зарезервирована, §7.6) · нижний р�д (вы�ота 30): «Import PGN… / Импорт PGN…», +«New repertoire / �овый репертуар» — обычные кнопки одинаковой ширины 150. + +Колонки (ширина панели 384 → на название о�таёт�� ≥ 150): + +| Колонка | Ширина | Содержимое | +| --- | --- | --- | +| «Name / �азвание» | о�таток, обрезка «…», полный тек�т в под�казке | им� репертуара | +| (без заголовка) | 22 | король цвета: ♔ / ♚; под�казка «You play White / Вы играете белыми» (… Black / чёрными) | +| «Today / Сегодн�» | 58, вправо | `повторить + новые` одним чи�лом; 0 → «—» бледно. Под�казка: «{n} to review, {m} new / Повторить: {n}, новых: {m}» | +| «Learned / Выучено» | 70, вправо | «34/120»; пу�той репертуар → «—» | +| (без заголовка) | 26 | кнопка `⋯` | + +- Строка 24, чередование фона, выделение — заливка выделени� на в�ю �троку (как библиотека, `ref-01`). + Пор�док — по имени, без �ортировки по клику. +- Клик — выбрать (карточка и до�ка обновл�ют��). Двойной клик или Enter — то же, что главна� кнопка карточки. + ↑/↓ — �о�едн�� �трока, выбранна� �трока прокручивает�� в видимую обла�ть. +- Пока �трока �читает�� в фоне, в «Сегодн�» и «Выучено» — прежние значени�; е�ли их ещё не было — «…». + Индикаторов вращени� нет. +- До�ка �крана: позици� **по�ле общего начала репертуара** (по�ледний ход до первого разветвлени�), � + под�веткой по�леднего хода, перевёрнута дл� чёрных; ввода нет. Пу�той репертуар и пу�той �пи�ок — + начальна� позици�. + +Меню `⋯` (также правый клик по �троке). Открытие меню **выбирает �ту �троку**; в�е пункты дей�твуют на неё. + +| № | EN | RU | Примечание | +| --- | --- | --- | --- | +| 1 | Train | Тренировать�� | = главна� кнопка; недо�тупно, е�ли ходов нет | +| 2 | Review all lines | Повторить в�ё подр�д | §6.1 | +| 3 | Lines… | Варианты… | §6.3 | +| — | | | разделитель | +| 4 | Rename… | Переименовать… | §7.3 | +| 5 | Play as Black / Play as White | Играть чёрными / Играть белыми | показан противоположный текущему; §7.4 | +| 6 | Add PGN to this repertoire… | Добавить PGN в �тот репертуар… | §7.1 | +| 7 | Export PGN… | Эк�порт PGN… | �и�темный диалог, как �ейча� (`repertoire_ui.rs:799`) | +| — | | | разделитель | +| 8 | Reset progress… | Сбро�ить прогре��… | §7.5 | +| 9 | Delete… | Удалить… | §7.5 | + +Пу�той �пи�ок: карточки и таблицы нет; по центру панели (вертикально тоже) — +заголовок «No repertoires yet / Репертуаров пока нет», бледный тек�т «A repertoire is your opening moves as a +PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…�. / +Репертуар — �то ваши дебютные ходы в PGN � вариантами. Импортируйте файл или откройте любую партию, +выберите ход и нажмите «Добавить в репертуар…».», под ним `primary` «Import PGN… / Импорт PGN…» и обычна� +«New repertoire / �овый репертуар». �ижний р�д в �том �о�то�нии �крыт (кнопки не дублируют��). + +## 3. Карточка выбранного репертуара + +Рамка как у `clock_card` без заливки, вы�ота 166 во в�ех �о�то�ни�х (�троки не по�вл�ют�� и не и�чезают — +пу�та� �трока о�таёт�� пу�той). + +| Строка | Вы�ота | Содержимое | +| --- | --- | --- | +| 1 | 26 | им� (`heading`, обрезка) · �права бледно «♔ You play White / ♔ Вы играете белыми» (♚ … Black / чёрными) | +| 2 | 22 | **�егодн�** (strong 15), тек�ты ниже | +| 3 | 8 + 20 | поло�а прогре��а вы�отой 8 во в�ю ширину: �егмент «выучено» — цвет выделени�, �егмент «учит��» — тот же цвет � `gamma_multiply(0.45)`, о�таток — фон пол�; под ней «Learned {x} of {y} moves / Выучено {x} из {y} ходов», �права бледно «{k} in progress / учит��: {k}» (�крыто при k = 0) | +| 4 | 20 | бледна� �трока по��нени� (тек�ты ниже) | +| 5 | 30 | главна� кнопка (ширина 170) · «Lines / Варианты» (ширина 110) · ме�то третьей кнопки (ширина 150) | + +Определени� чи�ел (из �дра, без новых пон�тий): `y` — �вои ходы репертуара за его цвет; `x` — ходы �о +�тату�ом �дра «изучено»; `k` — ходы, которые уже �прашивали, но ещё не «изучено»; «повторить» — ходы �о +�роком �егодн� или раньше; «новых» — `min(10, ещё не показанные)`. + +Со�то�ни� (�трока 2 · �трока 4 · кнопки): + +| Со�то�ние | Строка 2 (EN / RU) | Строка 4 (EN / RU) | Главна� | Треть� кнопка | +| --- | --- | --- | --- | --- | +| Е�ть повторени� (и, возможно, новые) | «Today: {n} to review · {m} new» / «Сегодн�: {n} повторить · {m} новых» (ча�ть � нулём опу�кает��) | «About {t} min» / «Примерно {t} мин» (20 � на ход, округление вверх; < 1 мин не показывать) | **Train / Тренировать��** | — | +| Повтор�ть нечего, е�ть новые | «Today: {m} new moves» / «Сегодн�: {m} новых ходов» | «Nothing to review today» / «Повтор�ть �егодн� нечего» | **Learn {m} new / Учить {m} новых** | «Review all lines / Повторить в�ё подр�д» | +| В�ё показано, до повторени� е�ть врем� | «Done for today» / «�а �егодн� в�ё» | «Next review: {when} · {n} moves» / «Следующее повторение: {when} · ходов: {n}» | **Review all lines / Повторить в�ё подр�д** | — | +| В�ё выучено и повторений в ра�пи�ании нет (теоретиче�ки) | «Done for today» / «�а �егодн� в�ё» | пу�то | **Review all lines / Повторить в�ё подр�д** | — | +| Репертуар пу�той | «No moves yet» / «Ходов пока нет» | «Add a PGN, or use “Add to repertoire…� in any game» / «Добавьте PGN или нажмите «Добавить в репертуар…» в любой партии» | **Add PGN… / Добавить PGN…** | — | +| В репертуаре нет ходов за выбранный цвет | «No moves for White here» / «Зде�ь нет ходов за белых» (… Black / чёрных) | «This PGN may be a repertoire for the other colour» / «Возможно, �то репертуар за другой цвет» | **Play as Black / Играть чёрными** (или белыми) | — | +| Индек�аци� в фоне, прежние чи�ла е�ть | прежние значени� | прежн�� �трока | прежн��, до�тупна | прежн�� | +| Индек�аци� в фоне, чи�ел ещё не было | «Counting moves…» / «Считаем ходы…» | пу�то | **Train / Тренировать��**, недо�тупна, под�казка «Counting moves… / Считаем ходы…» | — | +| Ошибка чтени� репертуара | «Cannot read this repertoire» / «�е удало�ь прочитать репертуар» (цвет предупреждени�) | тек�т ошибки � обрезкой, полный в под�казке | **Try again / Повторить** | — | + +`{when}`: «today at 18:40 / �егодн� в 18:40», «tomorrow / завтра», «in {d} days / через {d} дн.», далее дата +в формате библиотеки (`ДД.ММ.ГГГГ`). + +Тупиков нет: в любом �о�то�нии главна� кнопка что-то делает; «Повторить в�ё подр�д» в�егда е�ть в меню `⋯`. +Кнопка «Варианты» недо�тупна только у пу�того репертуара. Подпи�ь главной кнопки мен�ет�� только при �мене +�о�то�ни� данных; ширина фик�ирована. + +## 4. Экран «Зан�тие» + +### 4.1. Шапка и панель + +Шапка: назад «⬅ Repertoires / ⬅ Репертуары» (при ширине < 600 — «⬅»); заголовок — им� репертуара; подпи�ь — +вид зан�ти�: «Training · you play White / Тренировка · вы играете белыми» (�м. §6 дл� других видов). + +Панель �верху вниз, **в�е вы�оты по�то�нны**: + +| Блок | Вы�ота | Содержимое | +| --- | --- | --- | +| A. Карточка �о�то�ни� | 64 | �лева две �троки: заголовок (strong 15) и указание (обычный 13, обрезка; полный тек�т в под�казке); �права �чётчик: чи�ло моноширинным 24 и под ним бледна� подпи�ь 11. Рамка и заливка по §1 | +| B. Дебют | 20 | бледно, обрезка: «C84 · Ruy Lopez: Closed» — код и название текущей позиции из той же базы названий, что �ейча� в библиотеке (`repertoire_ui.rs:1297`); е�ли позици� вне базы — по�леднее изве�тное название; до первого хода пу�то | +| C. Путь | 20 | бледно, одна �трока, обрезка **�лева** («… 4. Ba4 Nf6 5. O-O Be7»): ходы до текущей позиции в нотации приложени� (`san::show`). Спрашиваемый ход в �троку не входит, пока не �ыгран. Клики не обрабатывают�� | +| D. Комментарий | о�таток, прокрутка внутри | заголовок-ход (strong): номер, ход, значок NAG цветом `notation::assessment_text_color` (`notation.rs:709`); ниже тек�т комментари� PGN (`notation::comment_text`, `notation.rs:748`). Правила — §4.4. Пу�то — пу�та� обла�ть, без «нет комментари�» | +| E. Дей�тви� | 30 | �лева обычна� «Hint (H) / Под�казка (H)» шириной 150; �права ме�то главной кнопки шириной 170 (обычно пу�то) | +| F. Поло�а | 28 + разделитель | значок переворота � под�казкой «Flip board (F) / Перевернуть до�ку (F)»; �права «× Finish / × Закончить» (как «× Прервать», `ref-04`) | + +До�ка: �трелки и кружки PGN, значок-бейдж хода — как в 2.3.0 (`learning_training.rs:1206–1265`), временные +�трелки пользовател� �охран�ют��. Стрелка-под�казка — �уще�твующа� зелёна� (`op-33`, `op-36`). + +### 4.2. Машина �о�то�ний + +Счётчик в обычном зан�тии: чи�ло = �колько вопро�ов о�тало�ь в �том зан�тии (включа� возвращённые ошибки), +подпи�ь «left / о�тало�ь». Чи�ло уменьшает�� только по�ле верного �амо�то�тельного ответа или �ыгранного +нового хода; при ошибке не мен�ет�� (ход вернёт��). + +| Со�то�ние | Когда | Заголовок EN / RU | Указание EN / RU | Рамка | До�ка, кнопки | +| --- | --- | --- | --- | --- | --- | +| S0 Подготовка | до первого кадра зан�ти�, только е�ли дольше 300 м� | Preparing… / Готовим зан�тие… | — | обычна� | ввод закрыт; �чётчик «—» | +| S1 Подвод | программа проигрывает ходы до вопро�а (ходы �оперника и уверенно изве�тные �вои) | Watch / Смотрите | Moves up to your next question / Ходы до вашего �ледующего вопро�а | обычна� | ввод закрыт; «Под�казка» недо�тупна; главна� �права: «Skip (Enter) / Пропу�тить (Enter)» — обычна� кнопка, �разу �тавит позицию вопро�а | +| S2 �овый ход | ход ни разу не показывали | New move / �овый ход | Play {san} — it is shown by the arrow / Сыграйте {san} — он показан �трелкой | активна� заливка | �трелка �разу; комментарий хода виден (§4.4); «Под�казка» недо�тупна | +| S3 Ваш ход | повторение | Your move / Ваш ход | Play the move from your repertoire / Сыграйте ход из репертуара | активна� заливка | �трелки нет; «Под�казка» до�тупна | +| S3a Ваш ход, ответов не�колько | в позиции не�колько �воих ходов (2.3.0) | Your move / Ваш ход | Play {san}'s alternative: one more move here / Зде�ь е�ть ещё один ваш ход, не {san} | активна� заливка | показывает��, когда �прашивает�� не первый из ответов; уже �ыгранные перечи�л�ют�� через зап�тую | +| S4 Верно | верный �амо�то�тельный ответ | Correct / Верно | {n}. {san} | обычна�, заголовок цветом оценки «хороший ход» (`notation::assessment_text_color` дл� `!`) | 600 м� по�ле анимации, затем S1/S2/S3 �ледующего вопро�а или S8; ввод закрыт | +| S5 �еверно | �ыгран не тот ход | Not this move / �е тот ход | Correct: {san}. Play it / Правильно: {san}. Сыграйте его | обводка 1.5 `error_fg_color` | фигура возвращает�� (�уще�твующа� анимаци�), �разу �трелка верного хода; ждём ход пользовател�; «Под�казка» недо�тупна. Другой неверный ход — �о�то�ние о�таёт��, фигура возвращает�� | +| S5a Ход е�ть в репертуаре, но �прашивает�� другой | �ыгран другой �вой ход �той позиции | This one is in your repertoire too / Этот ход тоже е�ть в репертуаре | Now the other one: play {san} / Сейча� нужен другой: �ыграйте {san} | обычна� | ошибкой **не �читает��**; �трелка на нужный ход | +| S6 По�ле показа | �ыгран ход, показанный в S5 или S7 | Got it / Запомним | {n}. {san} will come back in this session / {n}. {san} вернёт�� в �том зан�тии | обычна� | 600 м�, далее �ледующий вопро� | +| S7 Под�казка | нажата «Под�казка» в S3 | Hint / Под�казка | Play {san}. It will come back in this session / Сыграйте {san}. Ход вернёт�� в �том зан�тии | обычна� | �трелка; по�ле хода — S6 | +| S9 Ошибка запи�и | ответ не �охранил�� | Could not save your answer / �е удало�ь �охранить ответ | тек�т ошибки, обрезка, полный в под�казке | обводка 1.5 `error_fg_color` | ввод закрыт; в E: главна� «Try again / Повторить», �лева вме�то «Под�казки» — «Finish / Закончить» | +| S8 Итог | вопро�ы кончили�ь | §5 | | | | + +Обычное �охранение ответа не показывает�� никак (решение 05.11). До�ка по�ле отпу�кани� фигуры �разу +показывает �ыгранный ход (поведение 2.2.0 �охран�ет��). + +В�е `{san}` — в нотации приложени� (буквы фигур по на�тройке �зыка), � номером хода там, где указано `{n}.`. + +### 4.3. Клавиши и выход + +| Клавиша | Дей�твие | Сверка | +| --- | --- | --- | +| H | под�казка (S3) | как �ейча�, `learning_training.rs:1136` | +| F | перевернуть до�ку | как в партии и игре, `game_view.rs:3583` | +| Enter, Space | S1 — пропу�тить подвод; S8 — «К репертуару»; S9 — «Повторить» | Enter на итоге уже е�ть, `learning_training.rs:1142` | +| N | S8 — «Ещё 10 новых» | нова�, только на итоге | +| Esc, Ctrl+W | закончить зан�тие и вернуть�� к репертуарам | как �ейча�, `:1130–1131`; Ctrl+W — «в библиотеку» у партии | +| Ctrl+, | общие на�тройки, зан�тие не �бра�ывает�� | решение 05.11 | + +Клавиши не дей�твуют, пока открыт модальный диалог или поле ввода (правило `game_view.rs:4776–4783`). +Удал�ют��: Space/P — пауза автопоказа, Esc — отмена автопоказа (`:1124–1128`), L и Shift+A (`:1138–1139`). + +Выход по�реди зан�ти� (Esc, Ctrl+W, «⬅ Репертуары», «× Закончить»): **без вопро�а**, �разу на �кран +«Репертуары» — каждый ответ уже запи�ан, тер�ть нечего; текущий неотвеченный вопро� не за�читывает��. +Е�ли запи�ь в проце��е — выход по�ле её завершени� (как �ейча�, Esc ждёт `!board.is_busy()`). Е�ли +отвечен хот� бы один вопро�, вме�то мгновенного выхода показывает�� итог §5 � заголовком «Session stopped / +Зан�тие прервано» — человек видит, что �деланное �охранено. �езаконченное зан�тие не возобновл�ет�� +(концепци�): кнопка карточки начинает новое. + +### 4.4. Комментарии и значки PGN + +- Значок NAG хода (`!`, `?`, `!?` …) пишет�� р�дом � ходом в блоке D и в указании S4/S6; бейдж на до�ке — как + в 2.3.0. +- В блоке D в�егда комментарий **по�леднего хода на до�ке**; у хода �оперника — его комментарий (он + объ��н�ет позицию вопро�а). +- Комментарий **�прашиваемого** хода в S3 не показывает�� (он под�казывает ответ). Он по�вл�ет�� в S2 + (�разу), в S5 и S7 (вме�те �о �трелкой), в S4/S6 (по�ле хода) и о�таёт�� до �ледующего комментари�, � + заголовком-ходом, чтобы было видно, к чему он отно�ит��. +- Комментарий перед первым ходом партии PGN показывает�� в начале подвода. +- Перевод комментариев и их редактирование — нет (не �тот �тап). + +## 5. Итог зан�ти� (S8) + +До�ка о�таёт�� на по�ледней позиции, ввода нет. Панель: блоки A–C и F на ме�тах и тех же вы�от; блок D +зан�т итогом; блок E — кнопки. + +- A: заголовок «Session complete / Зан�тие окончено» (при до�рочном выходе — «Session stopped / Зан�тие + прервано»), указание «Everything is saved / В�ё �охранено»; �чётчик «0», при до�рочном — о�таток. +- D, �троки по 22, подпи�ь �лева, чи�ло �права (колонка 60): + - «Correct first time / Верно � первого раза» — {a} + - «Mistakes / Ошибок» — {b} + - «Hints / Под�казок» — {h} (�трока �крыта при 0) + - «New moves learned / �овых ходов» — {m} (�крыта при 0) + - разделитель + - «Next review / Следующее повторение» — {when} (§3); е�ли что-то о�тало�ь на �егодн� — «today, {n} more / + �егодн�, ещё {n}» + - е�ли были ошибки — подзаголовок «Moves to remember / Что запомнить» и до 8 �трок «{n}. {san}» � путём + бледно («по�ле 2… Nc6»: «after {path} / по�ле {path}»); больше 8 — «and {k} more / и ещё {k}». +- E: главна� �права — **«To repertoires (Enter) / К репертуарам (Enter)»**; �лева обычна� «10 more new (N) / + Ещё 10 новых (N)» (чи�ло — �колько реально о�тало�ь, мак�имум 10; �крыта, е�ли новых нет или вид зан�ти� — + §6). + +## 6. Другие виды зан�ти� и �кран «Варианты» + +### 6.1. «Повторить в�ё подр�д» + +Тот же �кран и те же �о�то�ни�. Отличи�: + +- подпи�ь шапки: «Review all lines · you play White / Повторение подр�д · вы играете белыми»; +- �чётчик карточки A: чи�ло «{k}/{n}», подпи�ь «line / вариант»; `n` — чи�ло вариантов (ли�тьев дерева � + учётом выключенных веток), `k` — текущий; +- �прашивает�� **каждый** �вой ход варианта, уверенно изве�тные не пропу�кают��; ход, которого ещё не + показывали, идёт как S2; +- между вариантами S1 � заголовком «Next line / Следующий вариант» и указанием «{k} of {n} / {k} из {n}»; + общее начало � предыдущим вариантом не проигрывает�� заново (поведение 05.11 �охран�ет��); +- ошибочный ход повтор�ет�� �разу (S5→S6) и в �том зан�тии не возвращает��; +- ответы запи�ывают�� в ра�пи�ание, как в обычном зан�тии; +- итог: перва� �трока «Lines reviewed / Пройдено вариантов» — {k} из {n}; кнопки «Ещё 10 новых» нет. + +### 6.2. «Тренировать �ту ветку» + +Как §6.1, но только варианты, проход�щие через выбранный ход. Подпи�ь шапки: +«Branch: {path} / Ветка: {path}» (путь � обрезкой �лева). �азад и «× Закончить» возвращают на �кран +«Варианты» � тем же выбранным ходом; Enter на итоге — туда же («To lines / К вариантам»). + +### 6.3. Экран «Варианты» + +Задача: по�мотреть, что в репертуаре, и выбрать, что тренировать. Ходы не редактируют��. + +Шапка: назад «⬅ Repertoires / ⬅ Репертуары»; заголовок — им�; подпи�ь «Lines · {n} lines · {y} your moves / +Варианты · вариантов: {n} · ваших ходов: {y}». + +Панель: + +| Блок | Вы�ота | Содержимое | +| --- | --- | --- | +| Дебют | 20 | как блок B зан�ти�, дл� выбранной позиции | +| Дерево | о�таток, прокрутка | `Notation { game: &дерево репертуара, cursor: выбранный ход, scroll_to_cursor: true при �мене хода � клавиатуры, read_only: true, marks/preview/translations/editor/dim_until/mistakes: None }` (`notation.rs:13–33`). Клик — `NotationResponse::clicked` (`:37`). Комментарии и NAG ри�ует �ам компонент | +| Выбранный ход | 92 | рамка как у карточки; �трока 1 — путь до хода (strong, обрезка �лева); �трока 2 бледно — «Below: {n} lines · {y} your moves · learned {x} / Дальше: вариантов {n} · ваших ходов {y} · выучено {x}»; у выключенной ветки �трока 2 — «Not trained / �е тренирует��» цветом предупреждени�; �трока 3 — кнопки: главна� «Train this branch / Тренировать �ту ветку» (170), обычна� «Don't train / �е тренировать» ↔ «Train again / Снова тренировать» (170) | +| Поло�а | 28 | `� ◀ ▶ �` и переворот — как `play_toolbar` (`game_view.rs:3567–3583`) | + +- До�ка: позици� выбранного хода, под�ветка по�леднего хода, �трелки/кружки PGN; перевёрнута дл� чёрных; + ввода нет. +- �ичего не выбрано (начало): �трока 1 — «Start position / �ачальна� позици�», главна� — + «Review all lines / Повторить в�ё подр�д», втора� кнопка �крыта. +- «�е тренировать» выключает ветку от выбранного хода (�уще�твующие `disabled_prefixes`), дей�твует �разу, + отмен�ет�� той же кнопкой; чи�ла карточки пере�читывают�� в фоне. У хода �оперника и у �воего хода + дей�твует одинаково. +- Клавиши как у партии: �/→ ход, ↑/↓ �о�едний вариант, Home/End, F — переворот, Enter — главна� кнопка, + Esc/Ctrl+W — назад. +- **Отметка выключенных веток в дереве.** `Notation` не умеет приглушать поддерево (`dim_until` — только + главна� лини� по номеру полухода). �ужна аддитивна� правка `notation.rs`: поле + `muted: Option<&HashSet>` по образцу `mistakes` (`:32`) — ходы из множе�тва ри�уют�� `weak` и + зачёркнутыми. Это выход за границу «только файлы раздела»; до �огла�овани� орке�тратора — без отметки в + дереве, �о�то�ние видно только в блоке выбранного хода. + +## 7. Диалоги + +В�е — `egui::Modal`, ширина 460, `heading`, кнопки �права внизу: «Cancel / Отмена», затем главна�. Enter — +главна� (кроме опа�ных, где Enter = «Отмена»), Esc — отмена. Таблица под диалогом не �двигает��. + +### 7.1. Импорт PGN + +Сначала �и�темный выбор файла (`rfd`, как `repertoire_ui.rs:753`), затем диалог «Import PGN / Импорт PGN»: + +- «Name / �азвание» — поле (до 120 знаков); по умолчанию — тег `Event` первой партии, е�ли он не пу�той и не + «?», иначе им� файла без ра�ширени�. +- «You play / Вы играете» — две плашки `choice` шириной 222, вы�отой 34: «♔ White / ♔ Белыми», «♚ Black / + ♚ Чёрными». Предвыбор: цвет, у которого в дереве меньше позиций � не�колькими ходами (�вои ходы обычно + един�твенные); при равен�тве — белые. Под плашками бледно: «Chosen from the PGN — check it / Выбрано по + PGN — проверьте». +- Сводка бледно: «{g} games · {v} lines · {y} your moves / Партий: {g} · вариантов: {v} · ваших ходов: {y}» + — `y` пере�читывает�� при �мене цвета. +- Предупреждени� (цвет предупреждени�, до 3 �трок, о�тальное — «and {k} more / и ещё {k}»): нера�познанные + ходы, партии без ходов. +- Кнопки: «Cancel / Отмена», главна� «Import / Импортировать» (недо�тупна при пу�том имени или `y = 0`; + под�казка «No moves for this colour / �ет ходов за �тот цвет»). +- Пока файл читает��: вме�то �водки «Reading the file… / Читаем файл…», главна� недо�тупна. +- По�ле импорта диалог закрывает��, новый репертуар выбран. + +«Добавить PGN в �тот репертуар…»: заголовок «Add PGN to “{name}� / Добавить PGN в «{name}»», без полей имени +и цвета; �водка «{m} new moves · {v} new lines / �овых ходов: {m} · новых вариантов: {v}»; при `m = 0` — +«Nothing new in this file / В файле нет новых ходов», главна� недо�тупна. Главна� — «Add / Добавить». + +Окно «Добавить в репертуар…» из партии (`repertoire_ui.rs:1987`) о�таёт�� как е�ть; при �оздании нового +репертуара в нём добавл�ют�� те же плашки цвета (предвыбор — �торона, чей ход выбран в партии). + +### 7.2. �овый репертуар + +«New repertoire / �овый репертуар»: поле названи�, плашки цвета (предвыбор — белые), бледно: «Moves are added +from a PGN file or with “Add to repertoire…� in any game. / Ходы добавл�ют�� из PGN-файла или кнопкой +«Добавить в репертуар…» в любой партии.» Главна� — «Create / Создать». Ошибка имени (пу�тое, зан�то) — +�трока цветом предупреждени� под полем, ме�то под неё зарезервировано. + +### 7.3. Переименование + +«Rename repertoire / Переименовать репертуар»: поле � текущим именем, выделенным целиком; главна� — +«Save / Сохранить»; та же �трока ошибки. + +### 7.4. Смена цвета + +«Play “{name}� as Black? / Играть «{name}» чёрными?» (или белыми). Тек�т: «You will be asked Black's moves: +{y}. Progress for White is kept and comes back if you switch again. / Спрашивать�� будут ходы чёрных: {y}. +Прогре�� за белых �охранит�� и вернёт��, е�ли переключить обратно.» Главна� — «Switch / Переключить». + +### 7.5. Сбро� прогре��а и удаление + +Опа�ные: главной (залитой) кнопки нет, обе кнопки обычные, фоку� и Enter — на «Отмена» (образец +`app.rs:2196`). + +**Сбро�.** Заголовок: «Reset progress of “{name}�? / Сбро�ить прогре�� «{name}»?» + +- «All {y} moves of this repertoire become new again: answers and review dates are erased. / В�е ходы �того + репертуара ({y}) �нова �танут новыми: ответы и �роки повторений будут �тёрты.» +- «The moves themselves and PGN files do not change. / Сами ходы и PGN-файлы не мен�ют��.» +- Е�ли е�ть общие позиции (�уще�твующий ра�чёт `impact`, `repertoire_ui.rs:1906–1940`), цветом + предупреждени�: «{s} of these moves are also in: {names}. They become new there too. / Из них {s} + в�тречают�� также в: {names}. Там они тоже �танут новыми.» +- Кнопки: «Cancel / Отмена», «Reset / Сбро�ить». Флажок «I understand…» (`:1950`) убрать — его замен�ет + точный тек�т. + +**Удаление.** Заголовок: «Delete “{name}�? / Удалить «{name}»?» + +- «The repertoire leaves this list. PGN files on disk do not change. / Репертуар и�чезнет из �пи�ка. + PGN-файлы на ди�ке не мен�ют��.» +- «Your answers are kept: import the same PGN again and the progress returns. / Ответы �охран�т��: е�ли + импортировать тот же PGN �нова, прогре�� вернёт��.» (�верить � �дром; е�ли прогре�� не возвращает�� — + разработчик �ообщает, тек�т мен�ет�� на «Progress of its moves is erased / Прогре�� по его ходам будет + �тёрт».) +- Кнопки: «Cancel / Отмена», «Delete / Удалить». По�ле удалени� выбирает�� �о�едн�� �трока. + +### 7.6. Сообщени� и ошибки + +Поло�а �ообщени� над нижним р�дом �крана «Репертуары» (20, в�егда зарезервирована): одна �трока � обрезкой, +полный тек�т в под�казке, �права `small_close_button` (`widgets.rs:74`). Ошибка — цвет предупреждени� +(«Could not save: {e} / �е удало�ь �охранить: {e}»), у�пех �к�порта — обычный бледный («Saved to {path} / +Сохранено: {path}»), и�чезает через 6 �. Сообщение никогда не �двигает таблицу. + +## 8. Что удал�ет�� из интерфей�а + +| Что | Где �ейча� | +| --- | --- | +| Экран «Стати�тика обучени�» целиком: вкладки Обзор, Динамика, Ра�пи�ание, Ходы, меню «Дополнительно» (Варианты, Серии), �електоры репертуара и �тороны, «Показатели обучени�» | `learning_dashboard.rs`, `learning_charts.rs`, `learning_branches.rs`; вход `repertoire_ui.rs:1007`; хук `CP_LEARNING_DASHBOARD_TAB` | +| Окно «Параметры тренировки» и кнопка «Параметры» | `repertoire_ui.rs:1669`, `learning_context_controls.rs` | +| Экран «Изменить» («редактор»): �пи�ок главной линии, «Без ограничени� глубины», «Глубина … полуходов», «�налитика хода», «Отмена/Сохранить» в шапке | `repertoire_editor.rs`; вход `repertoire_ui.rs:992`. Заменён �краном «Варианты» | +| Переключатель «Цвет» и �пи�ок «Режим» (По ра�пи�анию / Подр�д / Сначала новые и давние) в карточке | `repertoire_ui.rs:1515` (`workspace_panel`) | +| Строки «�е изучали�ь… · Пора повторить…», «Тренировка: ча�ть репертуара» | `repertoire_ui.rs:1591` и р�дом | +| Кнопки «Стати�тика», «Продолжить» (возобновление) | `workspace_panel` | +| В�тавные формы: им� (`name_editor`), импорт (`import_preview`), удаление, �бро� (`shared_reset_panel`) | `repertoire_ui.rs:1403`, `:1448`, `:1172–1195`, `:1906` | +| Строка таблицы вы�отой 156 � п�тью названи�ми ECO, колонки «ECO» и «Варианты», индикатор вращени� в �троке | `repertoire_ui.rs:1136` (`show_library`), `:1297–1331` | +| Пункт меню «Изменить» | `repertoire_ui.rs:1350` | +| В зан�тии: «Заданий: k из n», �трока «По ра�пи�анию · Белые», блок �ообщений переменной вы�оты, тек�ты «…не будет �амо�то�тельным у�пехом», «Само�то�тельный ответ не за�читан», «…не �читает�� �амо�то�тельным» | `learning_training.rs` (`side`, тек�ты �о�то�ни�) | +| В зан�тии: пауза/отмена автопоказа (Space, P, Esc), L, Shift+A; кнопки управлени� показом | `learning_training.rs:1124–1139` | +| Соб�твенна� ра�кладка «до�ка �верху» по правилу `width < 900 && height > width`; id панели `repertoire_workspace_side`; ширина панели 420–560 | `learning_training.rs:1530–1554`, `repertoire_ui.rs:1507`, `repertoire_editor.rs:100` | +| Режим «за оба цвета», лимит глубины в любом виде | по концепции | + +Строки `i18n.rs`, которые по�ле �того нигде не и�пользуют��, удалить (те�т `all_used_keys_are_translated` +ловит обратное, не �то — проверить пои�ком). + +## 9. Визуальна� приёмка + +Ревьюер — не автор кода; изолированный профиль; �нимки 1400×900 и 960×600, тёмна� тема, ру��кий �зык; +дополнительно три ключевых кадра (репертуары, S3, итог) в �ветлой теме, на англий�ком и при ма�штабе 2. + +**Сравнение � �талонами** (�нимки в одном размере окна, наложением): + +1. Пр�моугольник до�ки в «Репертуарах», «Зан�тии», «Вариантах» �овпадает � до�кой игры � компьютером + (`ref-04`): 1400×900 — x 54…886, y 60…892; 960×600 — x 22…554, y 60…592; допу�к 1 px. +2. Вы�ота шапки, положение кнопки «назад», заголовка, подпи�и и «�а�троек» — как у партии (`ref-02`). +3. Левый край правой панели — как у игры (940 при 1400; 576 при 960). +4. Карточка �о�то�ни� р�дом � карточкой игрока (`ref-04`): те же пол�, радиу�, обводка, заливка активной. +5. Строка и заголовок таблицы р�дом � таблицей библиотеки (`ref-01`): вы�оты 24 и 26, чередование, выделение. +6. Диалоги р�дом � «Игра � компьютером» и «Подготовка к �опернику» (`ref-03`, `ref-05`): заголовок, пол�, + кнопки �права внизу, одна главна�. +7. Вы�ота в�ех кнопок в р�дах — 30, значков поло�ы — 28; ширины главных кнопок 170. + +**Со�то�ни� дл� �нимков** (каждое в двух размерах): пу�той �пи�ок; один репертуар; 12 репертуаров (пои�к, +прокрутка); длинное им� (120 знаков); каждое �о�то�ние карточки из §3 (дев�ть); меню `⋯`; в�е диалоги §7, +включа� импорт � предупреждени�ми, �бро� � общими позици�ми и ошибку имени; S0–S9 зан�ти�, включа� S3a и +S5a; длинный комментарий (прокрутка в D); позици� без названи� дебюта; итог без ошибок, � ошибками (> 8), +до�рочный; «Повторить в�ё подр�д» (S1 между вариантами, итог); «Тренировать �ту ветку»; «Варианты» — начало, +выбран глубокий ход, выключенна� ветка; поло�а �ообщени� � ошибкой; панель, �уженна� до 320. + +**От�ут�твие �качков** — �ерии кадров � наложением, различи� допу�кают�� только внутри названных блоков: + +- A. Выбор �трок 1→2→3 и возврат: мен�ют�� только тек�ты карточки и позици� до�ки; рамка карточки, таблица, + нижний р�д неподвижны. +- B. Импорт: до диалога → диалог → по�ле: таблица �двигает�� только на добавленную �троку; во врем� �чёта + нет «…» поверх прежних чи�ел и нет индикатора вращени�. +- C. «Тренировать��» → S1 → S3 → S4 → S3 → S5 → S6 → S7 → S6 → S8 → «К репертуарам»: до�ка и границы + блоков A–F �овпадают на в�ех кадрах; мен�ют�� только тек�ты, рамка A и �одержимое D. +- D. Ошибка запи�и (S9) и повтор: те же границы. +- E. «Варианты»: выбор де��ти разных ходов, включение/выключение ветки — блок выбранного хода и поло�а не + мен�ют вы�оту. +- F. Открытие общих на�троек из каждого �крана и возврат: �о�то�ние не �брошено. + +**Пон�тно�ть без цвета**: в S4, S5, S9 �о�то�ние названо �ловом в заголовке; выключенна� ветка — �ловом «�е +тренирует��»; цвет репертуара — фигурой корол� и под�казкой. + +Дефект запи�ывает�� так: �нимок, размер, �о�то�ние, блок, ожидаемое и фактиче�кое значение в pt. + +## 10. Передать те�тировщику + +- Чи�ла карточки, таблицы, �чётчика зан�ти� и итога �ход�т�� между �обой на одном �ценарии (10 новых, + 3 ошибки, 1 под�казка). +- Ошибочный ход возвращает�� в том же зан�тии; S5a не �читает�� ошибкой. +- Выход на каждом �о�то�нии (Esc, Ctrl+W, кнопки) не тер�ет запи�анные ответы; PGN-файлы не мен�ют�� + (контрольные �уммы до и по�ле). +- Репертуары 2.2.0/2.3.0 � режимом «оба цвета», � `max_plies = 20`, � незаконченной �е��ией открывают�� без + ошибок и без потери прогре��а. +- Сбро� � общими позици�ми мен�ет ровно названные репертуары. +- Клавиши §4.3 и §6.3 не �рабатывают под диалогом и в поле ввода. + +## Возражени� и ри�ки + +1. **Строка «Путь» (блок C).** 03.11 владелец убрал нотацию из тренировки. Зде�ь �то одна бледна� + нередактируема� �трока «где �», без дерева. Считаю её полезной дл� запоминани� номеров ходов; е�ли + владелец против — блок удал�ет�� без по�лед�твий дл� вёр�тки (D займёт его ме�то один раз, при �борке). +2. **Поло�а прогре��а � �егментом «учит��».** Концепци� даёт одно чи�ло «Выучено X из Y». Критерий �дра + «изучено» — три верных ответа подр�д, по�тому первые дни X = 0 и работа не видна. Сегмент «учит��» не + вводит на�троек и �нимает �то; чи�ло `k` можно убрать, о�тавив только цвет. +3. **«�овый репертуар» без редактировани� ходов** �оздаёт пу�той объект, который нечем наполнить на �том + �кране. Диалог �то объ��н�ет, но путь о�таёт�� �лабым до �тапа «ходы на до�ке». +4. **Отметка выключенных веток** требует правки общего `notation.rs` (§6.3) — нужно решение орке�тратора. +5. **Тек�т удалени� про возврат прогре��а** (§7.5) не проверен по �дру. +6. **Предвыбор цвета при импорте** — �ври�тика; на PGN из целых партий она ненадёжна, по�тому выбор в�егда + показан и подпи�ан «проверьте». +7. Пометка «(α вер�и�)» в названии о�тавлена: её ввёл владелец, �н�ть её может только он. + +## Решени� орке�тратора по вопро�ам дизайнера (2026-11-26) + +1. `widgets::section_header_sub` — **прин�то**: нова� функци� в `widgets.rs`, �уще�твующие функции и их вызовы не мен�ют��. +2. Поле в общем `notation.rs` дл� выключенных веток — **отклонено**: �кран партии не трогаем. Со�то�ние ветки показывает�� в блоке выбранного хода; е�ли нужна отметка в дереве — только �ред�твами раздела (например, �во� обёртка/по�тобработка), без изменени� поведени� и вида нотации в других �кранах. +3. Строка «Путь» в зан�тии — **не делать**: владелец дважды (03.11) �вно убирал нотацию из тренировки. Ме�то �троки не резервировать. +4. Сегмент «учит��» в поло�е прогре��а — **прин�то**. +5. Тек�т диалога удалени� — разработчик �вер�ет � �дром (удаление репертуара не �тирает LearningItem; при повторном импорте того же дерева прогре�� подхватывает�� по `(FEN4, UCI)`); е�ли не так — и�править тек�т, а не �дро. diff --git a/docs/design/opening-trainer.md b/docs/design/opening-trainer.md new file mode 100644 index 0000000..344698d --- /dev/null +++ b/docs/design/opening-trainer.md @@ -0,0 +1,296 @@ +# Учить дебют: повторить по пам�ти ходы обеих �торон + +Стату�: проект дизайнера, 2026-10-25, **не утверждён**. Требовани� — `docs/research/opening-trainer.md` (аналитик: что такое лини� и ошибка §3, ход тренировки §4, �тати�тика §5, звук §7, объём §9, критерии §10). Уточнение владельца: **ходы за обе �тороны делает пользователь**, программа за �оперника не отвечает. Экран — род�твенник режима игры (`docs/design/play-mode.md`, `game_view.rs` `play_side`, `clock_card`, `play_toolbar`, `result_strip`): та же компоновка, другие карточки. Где проект ра�ходит�� � и��ледованием — §11. + +Снимки нынешнего вида (scratchpad разработчика `dev2/`): `pl_white.png` (�кран игры 1400: карточки у краёв панели, панель ин�трументов), `pl_640.png` (640), `m_end.png` (поло�а результата), `rs_final.png` (карточка поверх нотации). + +Размеры — логиче�кие точки egui. Тек�ты — по-ру��ки, в �кобках англий�кий ключ; �уще�твующие помечены «(е�ть)». + +## 0. Главное + +1. **Вход** — пункт меню хода «Учить дебют до �того хода» (�права — «прохождений: 4», е�ли линию уже учили). Без диалога: �кран открывает�� �разу на начальной позиции. +2. **Экран тренировки** — отдельный �кран поверх партии (как парти� из «Справочника», кнопка «⬅ К партии …»), � компоновкой игры: до�ка, �права две карточки и нотаци� между ними. Верхн�� карточка — **задание**: «Ход 7 из 12 · ♔ ход белых», «до 12…Rd8», поло�ка прогре��а. �ижн�� — **вы**: «Ошибок: 2 · Прохождение 3», «Прошлое: 1 · лучшее: 0». +3. **�отаци� показывает только �ыгранное.** Комментарии, значки, �трелки и варианты и�ходной партии не видны. Движка, �правочника, вкладок нет. +4. **�еверный ход:** фигура в�таёт на поле, обе клетки хода в�пыхивают кра�ным, короткий звук «не тот ход», через 0,4 � фигура возвращает��; в карточке «✗ В партии — другой ход», «Ошибок» +1. +5. **Конец:** звук у�пеха, верхн�� карточка �тановит�� итогом «Пройдено · ошибок: 2» � кнопками «↻ Повторить» (Enter) и «⬅ К партии» (Esc); в нотации у ходов � ошибками — кра�ные «×2». +6. **Уход по�реди прохождени�** — без вопро�а, прохождение не за�читывает��. +7. **Е�ли не помнит ход** — два варианта на выбор владельцу (§6): � — под�казок нет �ов�ем; Б — по�ле третьей ошибки на одном ходу по�вл�ет�� ��ылка «Показать ход». + +## 1. Вход + +| Где | Подпи�ь | Справа | �еактивно | +|---|---|---|---| +| меню хода | «Учить дебют до �того хода» (`Learn the opening up to this move`) | �лабым: «прохождений: 4» (`runs: 4`), е�ли линию проходили; иначе пу�то | на пути е�ть `--` | +| меню ☰ | «Учить дебют до �того хода» — по�ле «Играть от�юда � Maia… (Ctrl+G)» | — | то же; в начале партии — «Выберите ход, до которого учить» (`Select the move to learn up to`) | + +- Под�казка пункта: «Повторите по пам�ти ходы обеих �торон от начала партии до {move}» (`Replay from memory the moves of both sides from the start of the game up to {move}`). +- �еактивный пункт при `--` на пути, под�казка: «В линии е�ть пропу�к хода (--) — его нельз� �ыграть на до�ке» (`The line has a null move (--): it cannot be played on the board`). +- «прохождений: 4» �тоит в колонке `shortcut_text` — той же, где `Enter`, `Ctrl+V`, `Ctrl+G` (`paste-variation.md` §1.1). Это и е�ть «и�тори�» в точке входа: видно, что лини� уже учена. +- **Клавиши нет.** Свободные �очетани� е�ть (Ctrl+T), но функци� начинает�� � выбора хода мышью, а клавиша без хода (в начале партии) ничего бы не делала. Можно добавить позже, е�ли попро��т. +- Значка в подпи�и нет (меню хода без значков; глиф 🎓 в шрифтах программы не проверен). +- **Лини�** — путь от начала до выбранного хода включительно, в том чи�ле через вариант (и��ледование §3). Учить линию варианта — щёлкнуть правой на его по�леднем ходе. +- Без диалога: выбирать нечего (обе �тороны — пользователь). Экран открывает�� в тот же кадр. + +## 2. Экран тренировки + +### 2.1. Где он живёт + +Это **нова� `GameView` поверх и�ходной партии** — тем же механизмом, что парти� из «Справочника» (`previous_games`, кнопка «⬅ К партии {game}», е�ть). И�ходна� парти� прио�танавливает�� и ждёт как была, � не�охранёнными правками, кур�ором и вкладкой. Её игра-тренировка не мен�ет (критерий 12). + +Парти� на �кране тренировки — **временна�**: начальна� позици� линии и �ыгранные ходы. Она не помечает�� изменённой и при уходе не �прашивает «Парти� изменена»; �охранить её нельз� (Ctrl+S молчит). + +### 2.2. 1400 × 900, р�дом + +``` +┌──────────────────────────────────────────────────────────────────────────────────────────────────� +│ ⬅ Библиотека │ ⬅ К партии Карл�ен — Каруана │ Учим дебют: Карл�ен — Каруана ⚙ �а�тройки │ +│ │ │ Вейк-ан-Зее 2024 · до 12…Rd8 │ +├──────────────────────────────────────────────────────────────────┬───────────────────────────────┤ +│ ┌───────────────────────────────────────────────────────────� │┌─────────────────────────────�│ +│ │8 │ ││ Ход 7 из 12 ♔ ход белых││ � карточка «задание» +│ │ │ ││ до 12…Rd8 ││ +│ │ │ ││▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░││ � прогре�� 3 по нижнему краю +│ │ │ │└─────────────────────────────┘│ +│ │ │ │ 1 e4 c5 │ +│ │ до�ка; ориентаци� — как на �кране партии │ │ 2 Nf3 d6 │ +│ │ в момент входа, не переворачивает�� за ходом │ │ … │ +│ │ │ │ 6 Be2 ▌e5� │ +│ │ │ │ │ +│ │ │ │┌─────────────────────────────�│ +│ │ │ ││ Ошибок: 2 Прохождение 3││ � карточка «вы» +│ │1 a h │ ││ Прошлое: 1 · лучшее: 0 ││ +│ └───────────────────────────────────────────────────────────┘ │└─────────────────────────────┘│ +│ ↑ ме�то поло�ы оценки (пу�то, как в игре) │ � ◀ ▶ � │ 🔃 │ ↻ Сначала │ ✕ Выйти│ +└──────────────────────────────────────────────────────────────────┴───────────────────────────────┘ +``` + +Бокова� панель �верху вниз — **как в игре** (`play_side`): карточка, нотаци� (в�� о�тавша��� вы�ота), �трока про�мотра (когда ли�тают назад), карточка, панель ин�трументов. До�ка �тоит там же, где в игре и в обычной партии (ме�то поло�ы оценки держит��): вход и выход не двигают до�ку. + +### 2.3. Шапка + +- Слева «⬅ Библиотека» (е�ть) и «⬅ К партии {game}» (е�ть) — Esc. +- �азвание: «Учим дебют: {game}» (`Learning the opening: {game}`), `{game}` — «Белые — Чёрные» и�ходной партии (как её название в шапке); нет имён — «Учим дебют» (`Learning the opening`). +- Подзаголовок: «{турнир год} · до {move}» (`{event} · up to {move}`); нет турнира — «до 12…Rd8». +- Справа — только «⚙ �а�тройки». Скрыты: «�айти в базе», «�», заметки �овме�тимо�ти, «•», чип результата. �азвание не кликает�� (нет «Данных партии»). + +### 2.4. Карточка «задание» (�верху) + +Рамка — как у карточки ча�ов (`clock_card`: пол� 10 × 6, �кругление 4, обводка 1 `noninteractive.bg_stroke`), без заливки. Вы�ота — те же две �троки (≈ 56). + +- Строка 1, 15: �лева «Ход 7 из 12» (`Move {n} of {last}`); �права «♔ ход белых» / «♚ ход чёрных» (`♔ White to move` / `♚ Black to move`), 15 жирным — кто ходит �ейча�. Пользователь ходит за обоих, по�тому �то главное, что надо видеть на каждом полуходе. + - `{n}` — номер хода, который �ейча� делает��, `{last}` — номер по�леднего хода линии, оба — в нумерации партии (как в нотации и в «до 12…Rd8»). У FEN-партии � 20-го хода — «Ход 23 из 31». +- Строка 2, 13 �лабым: «до 12…Rd8» (`up to {move}`). +- **Прогре��** — поло�ка 3 по нижнему краю **внутри** рамки (не мен�ет вы�оту карточки), во в�ю ширину между пол�ми: заполнено `�ыграно полуходов / в�его`, цвет `selection.bg_fill`, о�таток — `noninteractive.bg_stroke`. Поло�ка точна в полуходах, подпи�ь — в ходах партии: две шкалы не �пор�т, а дополн�ют. + +### 2.5. Карточка «вы» (�низу) + +Та же рамка, на ме�те карточки пользовател� в игре. + +- Строка 1, 15: �лева «Ошибок: 2» (`Mistakes: {n}`) — при 0 �лабым, иначе обычным; �права 13 �лабым «Прохождение 3» (`Run {n}`) — номер �того прохождени� (прошлых + 1). +- Строка 2, 13 �лабым — и�тори� линии: + - «Прошлое: 1 · лучшее: 0» (`Last time: {n} · best: {m}`) — ошибок в прошлом и в лучшем прохождении; + - е�ли подр�д без ошибок ≥ 2: «Прошлое: 0 · без ошибок подр�д: 3» (`Last time: 0 · clean in a row: {n}`) — «лучшее: 0» тогда очевидно; + - впервые: «Эту линию ещё не проходили» (`Not done before`). +- **По�ле неверного хода** �трока 2 �тановит�� �ообщением цветом ошибки (`error_fg_color`): «✗ В партии — другой ход» (`✗ The game has another move here`) — и держит��, пока не �делан верный ход (тогда возвращает�� и�тори�). Повторна� ошибка на том же ходу — то же �ообщение, �чётчик ра�тёт, в�пышка повтор�ет��. +- Подпи�и по�троены как «�азвание: чи�ло» — без �клонени� «ошибка/ошибки/ошибок». + +### 2.6. �отаци� + +- Таблица «№ · белые · чёрные» (е�ть), **только чтение** (`read_only`, как в игре): щелчок — позици�, меню хода нет. +- Только �ыгранные ходы �того прохождени�; по�ледний выделен, нотаци� прокручена к нему. Комментариев, значков, вариантов, �трелок `[%cal]` нет — их нет в �той временной партии. +- В начале прохождени� нотаци� пу�та; в пу�той обла�ти — ничего (под�казка не нужна: карточка �верху говорит «Ход 1 из 12 · ♔ ход белых»). + +### 2.7. Панель ин�трументов + +``` +� ◀ ▶ � │ 🔃 │ ↻ Сначала │ ✕ Выйти +``` + +| Кнопка | Подпи�ь / под�казка | Клавиша | +|---|---|---| +| � ◀ ▶ � | как �ейча� (е�ть) | Home � → End, ↓ ↑ | +| 🔃 | «Перевернуть до�ку (F)» (е�ть) | F | +| ↻ Сначала | «↻ Сначала» (`↻ Restart`), под�казка «�ачать прохождение заново — �то не за�читывает��» (`Start the run again; this one is not counted`) | нет | +| ✕ Выйти | «✕ Выйти» (`✕ Leave`), под�казка «К партии — прохождение не за�читывает�� (Esc)» (`Back to the game; the run is not counted (Esc)`) | Esc | + +- Вид — как `play_toolbar` (значки 18, �лова 14 вы�отой 28). �еактивна «↻ Сначала» до первого хода. +- «↻ Сначала» и «✕ Выйти» — без подтверждени�: тер�ет�� только незаконченное прохождение, которое и так не за�читывает��. +- Перено� групп в узкой панели — `narrow-windows.md` §4a. + +### 2.8. До�ка + +- **Ориентаци� — как на �кране партии в момент входа**, и по�ле ходов **не переворачивает��** (и��ледование §4.2): рука и глаз не переучивают�� на каждом полуходе. 🔃 / F — переворот. +- Ходить можно фигурами **�тороны, чей ход** (обе �тороны — пользователь). Предварительных ходов нет. Превращение — **в�егда � выбором фигуры**, даже при «автоферзе» (критерий 11). +- Стрелки и круги правой кнопкой — временные, �тирают�� ходом (как в игре). +- **Ли�тание назад** (� / � / щелчок по ходу): �трока про�мотра под нотацией «Про�мотр прошлой позиции · к игре — End» (е�ть; в тренировке — «…· к тренировке — End», `Viewing an earlier position · back to training — End`). Попытка хода в прошлой позиции — до�ка возвращает�� к текущей, ошибкой не �читает��. + +## 3. Ход + +### 3.1. Верный + +Обычный звук (ход, вз�тие, шах — как в�егда), ход по�вл�ет�� в нотации, «Ход … из …», «ход белых/чёрных» и поло�ка обновл�ют��. Е�ли �трока 2 карточки «вы» показывала «✗ …» — возвращает�� и�тори�. + +### 3.2. �еверный (законный, но не ход линии) + +Покадрово: + +| Врем� | До�ка | Карточка «вы» | Звук | +|---|---|---|---| +| 0 | фигура �тоит на поле, куда её по�тавили (вз�та� фигура пропала); клетки «откуда» и «куда» залиты `error_fg_color` � прозрачно�тью 0,45 поверх под�ветки по�леднего хода | «Ошибок» +1; �трока 2 — «✗ В партии — другой ход»; обводка карточки 1,5 цветом ошибки | `Sound::Wrong` | +| 0–400 м� | так и �тоит; новые ходы � до�ки не принимают�� | — | — | +| 400 м� | позици� возвращает��: фигура уезжает назад � анимацией на�троек (не дольше 150 м�; при «без анимации» — �разу), вз�та� фигура возвращает��, кра�на� заливка �нимает�� | обводка — обычна�; �ообщение о�таёт�� | — | + +- Сообщение одно дл� в�ех �лучаев, в том чи�ле дл� хода из варианта партии (и��ледование §3): «✗ В партии — другой ход». �ичего не под�казывает. +- **�езаконна�** попытка (фигура туда не ходит) — не ошибка: до�ка не даёт её �делать, как везде; звука нет. +- 400 м� — �ередина рекомендованных 0,3–0,5 �: ошибку у�певают увидеть, но не ждут. +- Считает�� **кажда�** неверна� попытка; отдельно запоминает��, на каком полуходе и �колько (дл� отметок §4). + +### 3.3. Звуки + +| Событие | Звук | И�точник | +|---|---|---| +| верный ход | Move / Capture / Check (е�ть) | текущий набор | +| неверный ход | **`Sound::Wrong`** (новый) — короткий негромкий �игнал | Kenney Interface Sounds `error_00x` (CC0) дл� в�ех наборов — и��ледование §7 | +| лини� пройдена | **`Sound::Success`** (новый) | Lichess `Victory.ogg` дл� sfx/piano/futuristic/nes, Kenney `confirmation_00x` дл� wood/glass/clicks — и��ледование §7 | + +Звуки подчин�ют�� общей громко�ти и выключателю звука в на�тройках. Запи�и в `THIRD_PARTY_NOTICES.md`. + +## 4. Конец прохождени� + +По�ледний ход линии �ыгран верно → в тот же кадр: + +1. звук `Success`; запи�ь �тати�тики (§7); +2. **карточка «задание» �мен�ет�� карточкой итога** (вид поло�ы результата `result_strip`: заливка `extreme_bg_color`, обводка 1, пол� 10 × 8); **карточка «вы» �крывает��** (её чи�ла — в итоге), нотаци� занимает о�вободившее�� ме�то; +3. нотаци� показывает в�ю линию **� отметками ошибок**; кур�ор на по�леднем ходе; +4. панель ин�трументов: «� ◀ ▶ � │ 🔃» (дей�тви� — в карточке итога). + +``` +┌─────────────────────────────────� +│ [✓] Пройдено без ошибок │ � чип 15 + заголовок 17 жирным (как «0-1 Вы проиграли») +│ Прохождение 5 · лучшее: 0 · │ � 13 +│ без ошибок подр�д: 2 │ +│ По�ледние: 3 · 2 · 1 · 0 · 0 │ � 13 �лабым; по�леднее — �то, жирным +│ [▌ ↻ Повторить �] [⬅ К партии]│ � вы�ота 30, 14; главна� — заливка выделени� +└─────────────────────────────────┘ + 1 e4 c5 + 2 Nf3 d6 ×2 � отметка ошибок + 3 d4 cxd4 + 4 Nxd4 ×1 Nf6 +``` + +- **Заголовок:** «Пройдено без ошибок» (`Done without mistakes`) / «Пройдено · ошибок: 2» (`Done · mistakes: {n}`) / при под�казке (вариант Б) — «Пройдено � под�казкой · ошибок: 5» (`Done with a hint · mistakes: {n}`). +- **Чип** — «✓» в рамке чипа результата; без ошибок — фон чипа зелёный (`assessment_color($1)`, Lichess «хороший ход»), иначе — обычный фон чипа. +- **Строка итога:** «Прохождение {n} · лучшее: {m} · без ошибок подр�д: {k}» (`Run {n} · best: {m} · clean in a row: {k}`); `{k}` = 0 — �та ча�ть не пишет��. +- **По�ледние** — до 10 по�ледних за�читанных прохождений �той линии, �тарые �лева: «По�ледние: 3 · 2 · 1 · 0 · 0» (`Recent: …`). Это «и�тори�» пр�мо на �кране: видно, что ошибок �тановит�� меньше. Первое прохождение — �троки нет. +- **Кнопки:** «↻ Повторить» (`↻ Again`), под�казка «Enter» — главна�, �разу новое прохождение � начальной позиции, без вопро�ов; «⬅ К партии» (`⬅ Back to the game`), под�казка «Esc». Ширина: обе в �троку, е�ли помещают��, иначе кажда� во в�ю ширину, главна� �верху (правило `result_strip`). Кре�тика нет: итог — �то и е�ть �о�то�ние �крана. +- **Отметки ошибок** в нотации: по�ле SAN (и значка NAG, е�ли бы он был) — от�туп 3 и «×2» 11 точек цветом ошибки; под�казка при наведении — «Ошибок на �том ходу: 2» (`Mistakes on this move: {n}`). Ход, показанный под�казкой (вариант Б), — отметка цветом предупреждени� (`warn_fg_color`) � под�казкой «Ошибок: 3, ход показан» (`Mistakes: {n}; the move was shown`). Теперь �то разбор, а не под�казка — лини� уже пройдена. Парти� не мен�ет��: отметки — �лой поверх нотации, как отметки анализа. +- Щелчок по ходу показывает позицию — можно по�мотреть, где ошиб��. До�ка в итоге не принимает ходов. +- **«↻ Повторить» / Enter:** итог и�чезает, карточки возвращают��, нотаци� пу�та, до�ка — в начальной позиции, ориентаци� — кака� была. + +## 5. Уход + +| Повод | По�реди прохождени� | По�ле итога | +|---|---|---| +| Esc, «✕ Выйти», «⬅ К партии …» | �разу к и�ходной партии, **без вопро�а**; прохождение не за�читывает�� (ни чи�ло, ни ошибки) | к и�ходной партии | +| «⬅ Библиотека», Ctrl+W | в библиотеку (не�охранённые партии �тека �прашивают��, как �ейча�) | так же | +| закрытие программы | без вопро�а о тренировке | так же | + +И�ходна� парти� возвращает�� как была: кур�ор на ходе, � которого начали учить, вкладка, прокрутка. + +## 6. Е�ли не помнит ход — два варианта + +Владелец �казал «под�казывать нельз�». Без выхода из «не помню» за�тр�вший ученик может только уйти. �иже оба варианта; от выбора зави��т только �трока 2 карточки «вы», заголовок итога и цвет отметки. + +### Вариант �. Под�казок нет + +- По�ле любой ошибки — «✗ В партии — другой ход». Больше ничего. +- �е помнит — «✕ Выйти» (Esc), по�мотреть партию, начать �нова. Прохождение не за�читано. +- Плю�: �трого, как про�или; каждое за�читанное прохождение — че�тно «по пам�ти». Мину�: на длинной линии одна забыта� позици� обнул�ет в�ё пройденное. + +### Вариант Б. «Показать ход» по�ле третьей ошибки на одном ходу (рекомендую) + +- Ошибки 1 и 2 на �том полуходе — как в �. +- С **третьей** �трока 2 карточки «вы»: «✗ В партии — другой ход · Показать ход» — втора� ча�ть ��ылка (`Show the move`), тем же цветом ошибки, подчёркнута при наведении. �ичего не по�вл�ет�� �амо: под�казку надо попро�ить. +- Щелчок: на до�ке — �трелка верного хода (зелёна�, как �трелки пользовател�), �трока 2 — «Сделайте ход �о �трелки» (`Play the move on the arrow`), обычным �лабым цветом. Ход нужно �ыграть �амому; �трелка и�чезает � ходом. Другой ход по-прежнему ошибка. +- Прохождение **за�читывает��** как пройденное (`runs` +1), но � пометкой «� под�казкой»: в «лучшее» и «без ошибок подр�д» не идёт (�ери� обнул�ет��); в «По�ледние» — чи�ло �о звёздочкой «5*», под�казка «� под�казкой». +- Три — порог: одна ошибка — �лучайно�ть, две — «почти помню», треть� — уже перебор вариантов наугад. +- Плю�: ученик доходит до конца и видит, где забыл; �тати�тика че�тна�. Мину�: под�казка в�ё же �уще�твует. + +## 7. Стати�тика: где видна и�тори� + +Хранение и ключ — по и��ледованию §5 (`$XDG_DATA_HOME/chesspenguin/training.json`, ключ — начальна� позици� + ходы линии, атомарна� запи�ь по�ле каждого за�читанного прохождени�). Дополнение дизайна: `recent: Vec` — ошибки по�ледних 10 прохождений (и признак под�казки) дл� �троки «По�ледние». + +Где видно: + +| Ме�то | Что | +|---|---| +| меню хода | «прохождений: 4» �права от пункта (§1) | +| карточка «вы» во врем� прохождени� | номер прохождени�, прошлое, лучшее, �ери� (§2.5) | +| итог | прохождение, лучшее, �ери�, по�ледние 10 (§4) | +| библиотека | **ничего в v1.** Спи�ок «Мои дебюты» � повторением по ра�пи�анию — позже, вме�те � интервалами (и��ледование §5); метка в таблице партий была бы неточной: лини� — не парти� (та же лини� бывает в разных парти�х и вариантах) | + +## 8. Клавиатура — �водка + +| Клавиша | Где | Дей�твие | Сегодн� (�кран партии) | +|---|---|---|---| +| � → Home End ↑ ↓ | тренировка | ли�тание �ыгранного | как в партии | +| F | тренировка | перевернуть до�ку | как в партии | +| Esc | тренировка | к и�ходной партии (без вопро�а) | в партии — в библиотеку / к предыдущей | +| Ctrl+W | тренировка | в библиотеку | как в партии | +| Enter | итог | «↻ Повторить» | в партии — комментарий | +| L, Shift+A | тренировка | то�т «Во врем� тренировки движок выключен» (`The engine is off while training`) | движок / анализ | +| Ctrl+Z, Ctrl+Y, Ctrl+S, Ctrl+V, Ctrl+G, F2, Enter (во врем� прохождени�), Ctrl+1…6 | тренировка | ничего | правки, �охранение | + +То�т только дл� L и Shift+A — их жмут по привычке (как в игре, `play-mode.md` §3.7). + +## 9. Узкие окна + +- **Р�дом (640 × 480):** панель не уже `SIDE_MIN` 240. Карточки 2 × ≈ 56, панель ин�трументов в две �троки «� ◀ ▶ � │ 🔃» / «↻ Сначала │ ✕ Выйти» (при нехватке — «↻ ✕» � подпи��ми в под�казках); нотации ≈ 220. Строка 1 карточки «задание»: «Ход 7 из 12» и «♔ ход белых» не помещают�� в 240 − 20 — «ход белых» уходит, о�таёт�� «♔» (король и е�ть «кто ходит»), полна� подпи�ь — в под�казке. Строка 2 карточки «вы» �окращает�� � «…», полна� — в под�казке; �ообщение об ошибке не �окращает�� (перено�ит�� на вторую �троку, карточка на �то врем� выше — допу�тимо, �то ответ на дей�твие). +- **Стопка (640 × 1000):** как игра при 640 (`pl_640.png`): до�ка �верху, карточки и нотаци� — в нижней панели в том же пор�дке. +- **Итог** при 240: кнопки кажда� во в�ю ширину, главна� �верху. +- Шапка: «⬅ ⬅» значками, название �окращает�� � «…» (`narrow-windows.md` §3.4). + +## 10. Что �троит разработчик + +1. Режим �крана партии: вме�то пары `play`/`play_end` — перечень `Mode::Normal | Play(Session) | Train(Training)` (и��ледование §8); общее «ограниченный �кран»: что �крыто, `read_only` нотации, маршрут хода � до�ки, ли�тание без хода в прошлом, Esc, то�ты L/Shift+A. +2. `Training`: начальна� позици�, лини� `Vec`, индек� полухода, ошибки прохождени� по полуходам, под�казка (вариант Б), ключ �тати�тики, врем� в�пышки ошибки. +3. Вход: `NotationCommand::Train`, пункт ☰; `GameAction::Train(line)` → `app.rs`: текущую партию в `previous_games` (`suspend`), нова� временна� `GameView` (не �прашивает о �охранении) � `previous = title`, ориентаци� — и�ходной. +4. `train_side`: карточки §2.4–2.5 (обща� рамка � `clock_card`), итог §4 (общий вид � `result_strip`), панель §2.7. +5. `board.rs`: заливка клеток ошибки (две клетки, цвет, до момента) и возврат фигуры; «превращение в�егда � выбором» дл� тренировки. +6. `notation.rs`: �лой отметок ошибок (`×n`, цвет, под�казка) — как `marks`, но отдельной картой. +7. `assets.rs`: `Sound::Wrong`, `Sound::Success` во в�ех �еми наборах, `THIRD_PARTY_NOTICES.md`. +8. `training.rs`: чтение/атомарна� запи�ь `training.json`, `recent`. +9. Хук: `CP_TRAIN=1` вме�те � `CP_OPEN`/`CP_PLY` — тренировка до хода кур�ора; `CP_KEYS` / `CP_TYPE` дл� ходов; дл� �нимка итога — `CP_TRAIN=done` (пройти линию верно). Опи�ать в `docs/dev/desktop.md`. + +## 11. Ра�хождени� � и��ледованием + +- Тренировка — отдельный �кран поверх и�ходной партии (готовый механизм «⬅ К партии …»), а не режим той же `GameView`: и�ходна� парти� гарантированно не мен�ет��, а возврат к ней — привычна� кнопка и Esc. +- Карточки — как в игре (верх/низ панели), а не один блок над нотацией: до�ка и нотаци� �то�т там же, где в игре. +- Прогре�� — «Ход 7 из 12» в номерах партии + точна� поло�ка по полуходам, а не «Пройдено 12 из 24 ходов» (номера �овпадают � нотацией и � «до 12…Rd8»). +- Добавлены «↻ Сначала» и �трока «По�ледние» (`recent` в �тати�тике). +- Подпи�и без �клонений («Ошибок: 2», «прохождений: 4»). +- В варианте Б под�казку надо попро�ить (��ылка по�ле третьей ошибки), �трелка не по�вл�ет�� �ама. + +## 12. Открытые вопро�ы владельцу + +1. **Что делать, е�ли не помнит ход: вариант � (под�казок нет) или Б («Показать ход» по�ле третьей ошибки, по запро�у, прохождение помечает�� «� под�казкой»)?** Рекомендую Б: под�казка не нав�зывает��, но ученик не бро�ает тренировку на �ередине. +2. **Считать каждую неверную попытку?** Рекомендую да (как вы �казали) и отдельно помнить ходы � ошибками — дл� отметок «×2» в конце. +3. **Одна �торона против программы** (программа отвечает за �оперника) — �ледующей вер�ией, переключателем на карточке? Рекомендую да, по�ле v1. +4. **И�тори� в библиотеке** — �пи�ок «Мои дебюты» � повторением по ра�пи�анию — по�ле v1? Рекомендую да; в v1 и�тори� видна в меню хода, на карточке и в итоге. + +## 13. Чек-ли�т реализации + +- [ ] Пункт меню хода и ☰; «прохождений: N» в колонке `shortcut_text`; неактивен при `--` � причиной. +- [ ] Вход без диалога, в тот же кадр; и�ходна� парти� в �теке, «⬅ К партии …» в шапке; временна� парти� не �прашивает о �охранении. +- [ ] До�ка на том же ме�те, что в игре; ориентаци� — и�ходна�, по�ле ходов не переворачивает��; F переворачивает. +- [ ] Карточка «задание»: «Ход n из m», «♔/♚ ход …», «до …», поло�ка 3 внутри рамки; карточка «вы»: «Ошибок», «Прохождение», и�тори� / «ещё не проходили». +- [ ] �отаци� только �ыгранного, без комментариев/значков/�трелок/вариантов и�ходной партии; движка, �правочника, вкладок нет (критерий 5). +- [ ] �еверный ход: фигура на поле, две клетки кра�ным, `Wrong`, «Ошибок» +1, 400 м� без ввода, возврат � анимацией ≤ 150 м�, �ообщение до верного хода (критерий 2); ход из варианта — то же (критерий 3); незаконный — ничего (критерий 4). +- [ ] Превращение в�егда � выбором; ферзь вме�то кон� — ошибка (критерий 11). +- [ ] Ли�тание назад: �трока про�мотра, ход в прошлой позиции не делает�� и не �читает��. +- [ ] Итог: `Success`, карточка итога, отметки «×n», «↻ Повторить» (Enter) — новое прохождение (критерий 7), «⬅ К партии» (Esc). +- [ ] Уход по�реди — без вопро�а, `runs` не ра�тёт (критерий 8); «↻ Сначала» — тоже не за�читывает��. +- [ ] Стати�тика переживает перезапу�к; та же лини� из другой партии — та же �тати�тика (критерий 9); `recent` до 10. +- [ ] FEN-парти� (fullmove 0) — � её позиции; нумераци� «Ход n из m» по партии (критерий 10). +- [ ] Вариант � или Б — по решению владельца (§6). +- [ ] Снимки 1400 × 900, 640 × 480, 640 × 1000: прохождение, в�пышка ошибки, итог. diff --git a/docs/design/opponent-prep.md b/docs/design/opponent-prep.md new file mode 100644 index 0000000..08164e2 --- /dev/null +++ b/docs/design/opponent-prep.md @@ -0,0 +1,532 @@ +# Подготовка к �опернику: �кран отчёта по дебютам + +Стату�: проект дизайнера, 2026-10-28, актуализирован 2026-11-02; ветка `opponent-prep`. **Решени� владельца 2026-11-02 (фик�ированные): �верка � книгой полно�тью удалена из подготовки; автоматиче�кий пои�к ошибок движком по�ле по�троени� отчёта �охран�ет�� без изменений.** О�тальные проектные предложени� не утверждены. Объём — по решени�м владельца (`../research/opponent-prep.md` §9): **только дебюты** — что �оперник играет (репертуар по цветам � названи�ми и первыми ходами) и где в дебютах ошибает�� (какие ошибки, в каких дебютах, в каких парти�х). Без ча�ов, фаз, трендов, �тил�, онлайн-партий, до�ье и Android. �азвани� дебютов — по таблице `lichess-org/chess-openings`, по-англий�ки при любом �зыке интерфей�а, в�егда � первыми ходами; ошибки — движком. + +Опирает�� на: концепцию аналитика (`../research/opponent-prep.md` §3.1–3.4, §5), техниче�кую ча�ть разработчика (`../research/opponent-prep-tech.md` §2–5, §7: крейт `crates/prep`, дерево на N = 20 полуходов, дедупликаци� позиций, к�ш по позиции, формула времени), `reference.md` (таблица ходов и таблица партий, выбор базы, «�овинка», �тек партий «⬅ К партии»), `board-search.md` (поло�а Б/�/Ч, чипы, мини-до�ка в под�казке, меню ⋯ до�ки), `large-databases.md` / `library-layout.md` (панель фильтров, шапка таблицы), `narrow-windows.md` (минимум окна 640×480, �топка на �кране партии), `player-games.md` (�пи�ок имён, тек�ты RU/EN), код `apps/desktop/src/review.rs` (диалог анализа: движок · каче�тво · потоки · пам�ть · оценка времени; по�ле первого запу�ка кнопка �тартует �разу — флаг `chosen`), `notation.rs` (`assessment_color`, `assessment_text_color`), `large_db.rs` (группа «Игроки», контек�тное меню �троки партии), `library.rs` (контек�тное меню карточки), `game_view.rs` (шапка партии, `previous` → «⬅ К партии»). + +Размеры — логиче�кие точки egui. Макеты: ширина 1400 — 14 точек на знак (100 знаков), 640 — 10 точек на знак (64 знака); значки в ASCII опущены там, где ломают выравнивание. Тек�ты — по-ру��ки, в §9 — пары «ключ EN → RU» (ключ — англий�кий тек�т, как везде в `i18n.rs`). Пример данных — Вафин Радель из базы «Гран-при РШШ» (271 парти�: 138 белыми, 133 чёрными). + +## 0. Коротко + +1. **Вход — три двери, один диалог.** «Подготовить�� к {им�}…» е�ть в панели фильтров (когда игрок выбран), в контек�тном меню �троки партии (по одному пункту на каждого игрока) и в меню ☰ / по правой кнопке на названии партии. В�е три ведут в один диалог «Подготовка к �опернику» � базой, �пи�ком кандидатов � чи�лом партий (похожие имена отдельной группой, объединение напи�аний — флажками) и цветом. Е�ли им� уже точное (из фильтра � под�казкой или из �троки партии), диалог открывает�� � готовым выбором — о�таёт�� нажать Enter. +2. **Отчёт — отдельный �кран на ве�ь размер окна, как �кран партии**, �о �теком возврата «⬅ К подготовке» из открытой партии. Слева до�ка выбранной позиции, �права вкладки «Репертуар | Дебюты | Ошибки» и под ними �пи�ок партий выбранного узла. В правую панель библиотеки (260–380) дерево � ше�тью колонками не входит; отдельное окно ОС противоречит однооконной компоновке проекта. +3. **Цвет — переключатель в шапке отчёта «Белые | Чёрные | Оба»**, не вопро� при входе. Дерево в�егда имеет корни «Белыми · 138» и «Чёрными · 133»; переключатель показывает один корень или оба. По умолчанию — цвет из фильтра библиотеки, е�ли он задан, иначе «Оба». Обла�ть работы движка �ледует переключателю (в диалоге можно помен�ть). +4. **Движок — автоматиче�ки по�ле по�троени� отчёта** (решение владельца, 2026-11-01), без диалога-объ��нени�. При фактиче�ком �тарте один раз открывает�� вкладка «Ошибки»; там поло�а «Проверено X из Y позиций» и «О�тановить». Отметки по�вл�ют�� по мере оценки; о�тановка �охран�ет �деланное и запрещает автоматиче�кий перезапу�к, «Продолжить» запу�кает вручную. Смена глубины или периода �нова разрешает автозапу�к по�ле пере�троени�. Параметры — только по «▾». +5. **Ошибка прив�зана к узлу дерева** (позици� + его ход): отметка `?!`/`?`/`??` �тоит у хода в дереве, цветами нотации; «повтор�юща��� ошибка» — �то узел � отметкой и ≥ 2 парти�ми. Одна модель данных дл� дерева, таблицы дебютов и вкладки «Ошибки». +6. **Сводка — �етка без перено�ов.** �азвание цвета и правовыравненное чи�ло партий — отдельные колонки; �чёт �охран�ет�� хот� бы в компактном виде. Счётчики ошибок и процент партий — две �о�едние колонки � незави�имо измер�емой шириной; при нехватке ме�та �крывают�� только «по�ледн��», затем «�оперники». Подробно�ти и нулевые �о�то�ни� — §3.5. + +## 1. Сценарии + +### 1.1. Тренер готовит ученика к завтрашней партии белыми против Вафина + +1. Библиотека, база «Гран-при РШШ» → «Фильтры» → «Игрок: вафин» → под�казка «Вафин Радель · 271». Под �трокой цвета по�вила�ь кнопка «♟ Подготовить�� к Вафин Радель…». +2. �ажал → диалог: база «Гран-при РШШ», кандидат «Вафин Радель · 271» отмечен, ниже «Похожие имена: Вафина Ра�на · 10» (не отмечена), цвет «Чёрные» (ученик играет белыми — �оперник чёрными). Enter. +3. Экран отчёта �разу показывает «Репертуар» во врем� �бора. Когда отчёт готов, движок �тартует �ам, без диалога, и один раз открывает «Ошибки»: «Проверено 412 из 1 306 позиций · ≈ 20 � [О�тановить]». Пока идёт анализ, тренер возвращает�� в «Репертуар» — повторного автопереключени� нет. +4. Корень «Чёрными · 133»: «1.e4 — 79 партий», под ним «1…c5 — 79 · 100 %», дальше «2.Nf3 d6 — 39», «2.c3 Nf6 — 17»… Щелчок по «2.c3 Nf6» — до�ка показывает позицию, �низу 17 партий; в дереве у «6…Nb6» уже видны «?» и «×3» от параллельно работавшего движка. +5. Вкладка «Ошибки»: «Повтор�ющие��» — «по�ле 6.Bc4 · 6…Nb6 ? · лучше 6…e6 · ×3 · +1 −2 · Sicilian Defense: Grand Prix Attack». Щелчок — до�ка показывает позицию до хода � двум� �трелками (�ыгранный — оранжевый, лучший — зелёный). Enter — парти� на �том ходу; «⬅ К подготовке» возвращает. +6. �а до�ке «⋯ → Играть от�юда…» — ученик разыгрывает позицию по�ле 6…Nb6 против Maia; «Открыть как партию» — тренер запи�ывает линию � комментари�ми и �охран�ет в базу ученика. + +### 1.2. Бы�трый взгл�д перед туром, не дожида��ь движка + +Турнирна� база открыта, таблица партий. Права� кнопка на �троке «Кузнецов — Вафин» → «Подготовить�� к Вафин Радель…» → Enter в диалоге → отчёт за �екунду. Движок �ам начал проверку на вкладке «Ошибки», но тренер �разу открывает «Дебюты»: «Белыми: Sicilian Defense 37 % · French Defense 15 % · Caro-Kann 13 %…», ра�крывает �ицилиан�кую — варианты � первыми ходами и �чётом. Ждать движок дл� вывода «он в�егда 1.e4, на 1…c5 чаще 2.Nf3, но бывает Гран-при» не нужно. + +### 1.3. Повторный отчёт по�ле обновлени� базы + +База онлайн-партий допи�ала�ь новыми парти�ми. Вход тот же; �бор дерева — мгновенно; оценки прежних позиций — из к�ша. По�ле пере�троени� движок автоматиче�ки провер�ет 84 новые позиции: вкладка «Ошибки» показывает «Проверено 12 из 84 позиций · ≈ 4 � [О�тановить]». + +## 2. Точка входа + +### 2.1. Три двери + +| Где | Элемент | Что передаёт в диалог | +|---|---|---| +| **Панель фильтров**, группа «Игроки», под �трокой цвета («любым цветом · белыми · чёрными») | кнопка «♟ Подготовить�� к {name}…» (`♟ Prepare against {name}…`); видна, когда игрок выбран из под�казки (`NameFilter.exact`); при �вободном тек�те без под�казки — кнопка «♟ Подготовить�� к �опернику…» без имени (диалог покажет кандидатов по �тому тек�ту). В узком окне панель — выдвижна�, кнопка та же | база — текуща�; игрок — `exact`; цвет — из фильтра («белыми» → Белые, «чёрными» → Чёрные, иначе Оба); о�тальные активные фильтры (годы, Эло, турнир) — как у�лови� отчёта (§2.4) | +| **Контек�тное меню �троки таблицы партий** (`large_db.rs:2214`), по�ле «Открыть» | два пункта: «Подготовить�� к {white}…», «Подготовить�� к {black}…» (им� в тек�те пункта, без �клонени�). Один пункт, е�ли имена �овпадают или одно пу�тое | база — текуща�; игрок — точное им� из запи�и; цвет — Оба | +| **Экран партии**: меню ☰ нижней панели и права� кнопка по названию партии в шапке | подменю «Подготовить�� к �опернику ▸» � двум� пунктами-именами; по правой кнопке на названии — те же два пункта �разу | база — база партии (`source`); у партии без базы (в�тавлена, нова�) — база не выбрана, диалог про�ит выбрать; игрок — точное им�; цвет — Оба | + +Клавиша в библиотеке: `Ctrl+Shift+P` — то же, что кнопка панели (� игроком из фильтра, е�ли выбран; иначе пу�той диалог). �а �кране партии клавиши нет. + +Почему не кнопка в шапке таблицы и не карточка на полке: вход в�егда начинает�� � человека — им� либо уже в фильтре, либо в �троке партии, либо в шапке партии. Отдельна� кнопка «без имени» за�тавила бы и�кать игрока второй раз. + +### 2.2. Диалог «Подготовка к �опернику» + +Модальное окно 520 × по �одержимому (как диалог анализа, `egui::Modal`). + +``` +┌ Подготовка к �опернику ────────────────────────────────────────� +│ База [Гран-при РШШ · 33 640 ▾] │ +│ Игрок [вафин ] × │ +│ ☑ Вафин Радель 271 парти� │ +│ � Vafin, Radel 6 партий │ +│ Похожие имена — �корее в�его, другие люди │ +│ � Вафина Ра�на 10 партий │ +│ Отмечено: Вафин Радель, Vafin, Radel · 277 партий │ +│ │ +│ Цвет (•) Оба ( ) Белые — 138 ( ) Чёрные — 133 + 6 │ +│ [Отмена] [▌Открыть отчёт�]│ +└────────────────────────────────────────────────────────────────┘ +``` + +- **База** — �пи�ок баз полки (им� · чи�ло партий), как «База» в Справочнике; по умолчанию та, откуда пришли. Смена базы перезапрашивает кандидатов. База, котора� ещё не открыта, открывает�� тут же �о �пиннером в �троке («Открываю базу…»). +- **Игрок** — поле � тем же механизмом, что «Игрок» панели фильтров (`suggest_players`, �лова без учёта реги�тра и пор�дка; точки в инициалах убирают�� — правка `words()`, `opponent-prep-tech.md` §2.2). �о �пи�ок кандидатов **не выпадающий, а по�то�нный** под полем, � флажками: до 8 �трок, дальше прокрутка. Перва� �трока отмечена �ама, е�ли �овпадение по в�ем �ловам ровно одно; иначе ничего не отмечено, кнопка «Открыть отчёт» неактивна � под�казкой «Отметьте игрока». +- **Похожие имена** — отдельна� группа под �лабым заголовком «Похожие имена — �корее в�его, другие люди»: имена, которые �овпадают по началу �лова, но не по �лову целиком («Вафин» ⊂ «Вафина»), или отличают�� одной буквой. �икогда не отмечают�� �ами. �втоматиче�кой �клейки нет (решение и��ледовани� §5.7). +- **Объединение напи�аний** — про�то не�колько флажков. Строка «Отмечено: … · N партий» показывает �умму. Выбор запоминает�� на базу и им� (в данных программы, как про�мотренные партии): в �ледующий раз те же флажки �то�т �ами. +- **Цвет** — радио «Оба / Белые — N / Чёрные — N» � чи�лом партий; по умолчанию из входа (§2.1). Это начальное положение переключател� отчёта, его мен�ют в отчёте в любой момент. +- Enter — «Открыть отчёт», Esc — отмена. Фоку� при открытии: в поле «Игрок», е�ли игрок не задан; иначе на «Открыть отчёт». + +Диалог показывает�� в�егда, даже когда в�ё изве�тно: в нём видно чи�ло партий по цветам и похожие имена — то, из-за чего отчёты врут. Это один Enter. + +### 2.3. Что прои�ходит по�ле «Открыть отчёт» + +Экран отчёта открывает�� �разу. Сбор линий, дерева и имён — в фоне (`Background::spawn`): дл� �отен партий �бор заканчивает�� до первого кадра; дл� фильтра по Mega — �екунды � прогре��ом «Собираю партии… 37 %» на ме�те дерева. По�ле готовно�ти отчёта автоматиче�ки �тартует пои�к ошибок движком (§4), е�ли в�е нужные позиции ещё не оценены. + +### 2.4. У�лови� из библиотеки + +Е�ли при входе из панели фильтров были активны другие фильтры (годы, Эло �оперников, турнир), отчёт �троит�� **по отфильтрованной выборке**, и �то видно в шапке отчёта чипами без `×`: «Годы: 2025–2026 · Эло ≥ 1700». Так тренер получает «по�ледний год» и «против �ильных» без новых �лементов управлени� в отчёте. Убрать у�ловие — вернуть�� в библиотеку и �н�ть фильтр. Вход из �троки партии и из шапки партии — в�егда в�е партии игрока. (Вопро� 11.1.) + +## 3. Экран отчёта + +### 3.1. Где живёт + +| Вариант | За | Против | +|---|---|---| +| **�. Отдельный �кран на в�ё окно, как �кран партии** (шапка «⬅ Библиотека», �тек возврата) | ме�то дл� до�ки + дерева в 6 колонок + �пи�ка партий; парти� из отчёта открывает�� поверх �о �теком «⬅ К подготовке» — механизм уже е�ть (`previous`, `reference.md`); �о�то�ние библиотеки не трогает�� | ещё один тип �крана (третий по�ле библиотеки и партии) | +| Б. Третий �егмент в библиотеке `[Фильтры │ До�ка │ Подготовка]` | р�дом � фильтром игрока, нулевой переход | права� ча�ть — 260–480 точек: дерево � колонками не помещает��; таблица партий библиотеки показывает в�е партии базы, а отчёту нужен �вой �пи�ок по узлу; в узком окне (< 880) панель и так идёт по очереди � таблицей | +| В. Вкладка в правой панели �крана партии, как «Справочник» | та же механика «таблица ходов + партии» | отчёт — не про текущую партию, а про игрока; открывать пу�тую партию, чтобы по�мотреть отчёт, �транно; панель 370–700 те�на дл� дерева + дебютов + ошибок | +| Г. Отдельное окно ОС | можно держать р�дом � партией | в проекте одно окно; viewport-ы egui т�нут за �обой отдельные на�тройки, фоку�, тайлинг; на ноутбуке второе окно некуда �тавить | + +**Рекомендаци� — �.** Шапка — как у партии: «⬅ Библиотека», название, �права «⚙ �а�тройки». `Ctrl+W` — назад в библиотеку, к той же базе и фильтрам. Отчёт живёт, пока его не закрыли; повторный вход дл� того же игрока (та же база, те же напи�ани�) возвращает его как был (вкладка, узел, прокрутка, результаты движка). + +### 3.2. Компоновка, 1400 × 1000 + +``` +⬅ Библиотека │ Подготовка к �опернику: Вафин Радель · 271 парти� · 01.2026 – 10.2026 · Гран-при РШШ ⚙ �а�тройки +[Белые │ Чёрные │� Оба ▌] Период [В�е партии ▾] Дебют [10 ходов ▾] [Ошибки найдены ▾] +Белыми │ 138 │ 77 % (+103 =8 −27) │ �оперники ≈ 1612 │ по�ледн�� 18.10.2026 │ 14 ?! · 11 ? · 5 ?? │ в 17 % партий +Чёрными │ 133 │ 58 % (+70 =14 −49) │ �оперники ≈ 1655 │ по�ледн�� 18.10.2026 │ 30 ?! · 10 ? · 13 ?? │ в 71 % партий +──────────────────────────────────┬───────────────────────────────────────────────────────────────────── + ○ Ход чёрных · по�ле 3.Bb5 │ [�Репертуар▌] Дебюты Ошибки Ветви от [3 ▾] партий · Ра�крыть в�ё +┌────────────────────────────� │ Ход Дебют Партий % Счёт По�ледн�� +│ │ │ ▾ Белыми 138 77 % ▕███▒░� 18.10.2026 +│ │ │ ▾ 1.e4 136 99 77 % 18.10.2026 +│ │ │ ▾ 1…c5 Sicilian Defense · B20 50 37 70 % 18.10.2026 +│ до�ка 380 │ │ ▾ 2.Nf3 33 66 73 % 12.10.2026 +│ │ │ ▾ 2…Nc6 16 48 69 % 12.10.2026 +│ │ │ ▌3.Bb5 Sicilian Defense: Nyezhmetdinov-Ros… · B30 14 88 71 % 12.10.2026 +│ │ │ ▸ 3…g6 9 64 67 % 12.10.2026 +│ │ │ ▸ 3…e6 4 29 75 % 03.09.2026 +└────────────────────────────┘ │ ▸ другие ходы (1) 1 + 1.e4 c5 2.Nf3 Nc6 3.Bb5 │ ▸ 2…d6 12 36 75 % 05.10.2026 + Sicilian Defense: Nyezhmetdinov- │ ▸ 2.Nc3 17 34 65 % 18.10.2026 + Rossolimo Attack · B30 │ ▸ 1…e6 French Defense · C00 21 15 81 % 18.10.2026 + [Открыть как партию] [⋯] │ ▸ 1…c6 Caro-Kann Defense · B10 18 13 83 % 27.09.2026 + ├───────────────────────────────────────────────────────────────────── + │ Партии · по�ле 3.Bb5 · 14 ✕ + │ Белые Эло Чёрные Эло Рез. Дата Дальше Турнир + │ Вафин Радель 1887 Ширшов С. 1802 1-0 12.10.2026 3…g6 4.O-O Bg7 Блиц 12, до 13 + │ Вафин Радель 1860 Гади�ов М. 1744 ½-½ 03.09.2026 3…e6 4.O-O Nge7 Рапид 9, до 13 +``` + +Вы�оты: шапка 36; �трока переключателей 32; �водка 2 �троки по 20 (при «Белые» или «Чёрные» — одна �трока выбранного цвета, втора� �лабым); разделитель. Лева� колонка — до�ка `min(H_панели − 120, 420)`, не меньше `BOARD_MIN` 220, ширина колонки = до�ка + 24; права� — о�тальное, не уже 560. Права� колонка делит�� по вертикали: вкладки �верху, �пи�ок партий �низу, граница перета�кивает�� (по умолчанию �пи�ок — 35 %, не меньше 4 �трок). + +### 3.3. Шапка + +- �азвание: «Подготовка к �опернику: {name}» (`Preparing against {name}`); при не�кольких напи�ани�х — первое отмеченное и «+1 напи�ание» (`+1 spelling`) � под�казкой-�пи�ком. Дальше �лабым: чи�ло партий, период «MM.YYYY – MM.YYYY» (по датам партий; без дат — пу�то), им� базы; чипы у�ловий из библиотеки (§2.4). Сокращение в узком окне — как у шапки партии (`narrow-windows.md` §3.4): «⬅ Библиотека» и им� видны в�егда, о�тальное � «…». +- «⚙ �а�тройки» — общие на�тройки программы, как везде. + +### 3.4. Строка переключателей + +Пор�док �лева направо: **цвет | период | глубина | кнопка до�ки в низком окне | движок**. + +- **Цвет** — �егментный переключатель `[Белые │ Чёрные │ Оба]` (`White · Black · Both`), как `[Фильтры │ До�ка]`. Дей�твует на дерево (какие корни показаны), таблицу дебютов, вкладку «Ошибки», �пи�ок партий и на обла�ть движка. Сводка показывает оба цвета в�егда (�трока другого цвета �лабым). +- **Период** — �уще�твующий �пи�ок выбора партий. Смена пере�траивает отчёт, по�ле чего движок автоматиче�ки провер�ет недо�тающие позиции новой конфигурации. +- **Дебют: 10 ходов ▾** — глубина дерева и анализа: 6 / 10 / 15 ходов (12 / 20 / 30 полуходов, по умолчанию 20 — `opponent-prep-tech.md` §3.1). Смена пере�траивает дерево и мен�ет чи�ло позиций дл� движка; по�ле пере�троени� движок запу�кает�� автоматиче�ки. +- **«♙ До�ка»** — только в �топке при `H < 720`, между глубиной и контролом движка; открывает выдвижную до�ку по §6. В о�тальных компоновках кнопки нет. +- **Контрол движка** — §4. Во врем� работы на его ме�те компактна� поло�а прогре��а и «О�тановить»; по�ле — �трока �о�то�ни�. + +### 3.5. Сводка + +Две �троки `egui::Grid`, по одной на цвет; при выбранном одном цвете втора� �трока о�таёт�� �лабой. Пор�док колонок: **название цвета | партии | �чёт | �оперники | по�ледн�� | �чётчики ошибок | процент партий � ошибками**. + +- **�азвание и чи�ло партий — отдельные колонки.** Чи�ло выравнивает�� по правому краю, по�тому разна� длина названий не �двигает �ледующие показатели. +- **Счёт** — очки игрока в процентах; +/=/− — � его точки зрени�. Полный вид: `77 % (+103 =8 −27)`; компактный: `77 %`. При �окращении процент �чёта �охран�ет��. +- **Ошибки — две �о�едние колонки.** В первой цветные �чётчики в пор�дке `30 ?! · 10 ? · 13 ??`, во второй — `в 71 % партий`. Процент �тоит на одной X в обеих �троках незави�имо от разр�дно�ти и чи�ла �чётчиков. Ширины counts и percent ра��читывают�� незави�имо по реальному `Label`, � фактиче�ким `gap = 4`; нельз� измер�ть их как одну приблизительную �троку в общем `horizontal`. +- **�ули.** Типы � нулевым �чётчиком пропу�кают��: например, `10 ? · 13 ??`. Е�ли у одного цвета в�е три �чётчика равны нулю, в его �троке только «нет ошибок», а �чейка процента пу�та�. Е�ли ошибок нет у в�ех показанных цветов, отдельна� колонка процента не �оздаёт��. +- **Скрытие при нехватке ширины:** �начала «по�ледн��», затем «�оперники». �азвание, чи�ло партий, �чёт и ошибки не �крывают��; �чёт переходит в компактный вид. +- **Стопка (stacked):** ошибки в �водке не дублируют�� — они показывают�� только на вкладке «Ошибки». О�тальные колонки �ледуют тем же правилам �окращени�. + +### 3.6. Вкладка «Репертуар» — дерево + +Та же таблица, что таблица ходов Справочника (поло�атые �троки, обычный шрифт), но � от�тупами дерева. + +| Колонка | Что | Ширина | +|---|---|---| +| Ход | `▾`/`▸` + от�туп 14 на уровень + SAN � номером («3.Bb5», «2…Nc6»); ход игрока — обычным, ход �оперника — �лабым; ⤳ по�ле хода — к позиции приходили и другим пор�дком (под�казка — пор�дки) | гибка�, ≥ 180 | +| Дебют | им� по таблице у **первого** узла, где оно по�вило�ь (глубже — пу�то, чтобы не повтор�ть); «Family: Variation» + �лабым ECO; �окращает�� � «…», полное — в под�казке | гибка�, ≥ 160, пр�чет�� второй | +| Партий | чи�ло партий игрока через �ту позицию | 56 | +| % | дол� от родител� | 40 | +| Счёт | очки игрока в процентах + поло�а Б/�/Ч 60 (как на до�ке пои�ка; под�казка «+10 =1 −3») | 110 | +| По�ледн�� | дата по�ледней партии (дд.мм.гггг; без дат — год или «—») | 84 | +| (по�ле движка) | у хода игрока — значок отметки `?!`/`?`/`??` (пилюл� как в нотации) �разу по�ле SAN в колонке «Ход» и в под�казке «Ошибка: лучше 6…e6 (оценка 0,0 → −1,2) · в 3 парти�х» | — | + +- **Корни** — «Белыми · 138» и «Чёрными · 133» (`As White`, `As Black`); при переключателе «Белые» виден один корень, ра�крытый. Чередование уровней: под корнем «Белыми» первый уровень — его ходы, второй — ответы �оперников, и так далее. +- **Ра�крытие по умолчанию**: до узлов � ≥ 5 парти�ми включительно, но не глубже 6 полуходов; о�тальное �вёрнуто. «Ра�крыть в�ё» / «Свернуть» — ��ылки в �троке над таблицей (дей�твуют на выбранный узел, без выбора — на корни). +- **Ветви от N партий** — выпадающий 2 / 3 / 5 (по умолчанию 3; «груба� → тонка�» детализаци� ChessBase). Дети � меньшим чи�лом партий �ворачивают�� в одну �троку «другие ходы (N)» (`other moves (N)`) в конце �пи�ка детей; ра�крывает�� как узел и показывает их. +- **Выделение** — одна �трока (поло�а ▌ �лева, как в таблицах библиотеки). Выбранный узел = позици� на до�ке + заголовок �пи�ка партий «Партии · по�ле 3.Bb5 · 14». Щелчок по уже выбранному — ничего (не �нимает). Щелчок по `▾/▸` — ра�крыть/�вернуть без �мены выделени�. Двойной щелчок — ра�крыть/�вернуть. +- **Мало партий**: в узлах � < 5 парти�ми «%», «Счёт» и поло�а — �лабым цветом, под�казка «Мало партий — проценты ненадёжны» (`Few games: percentages are unreliable`). +- **Переходы**: узел — по пор�дку ходов, �тати�тика — по позиции (как рекомендует разработчик, §3.1 техча�ти): два узла � одной позицией показывают одинаковые чи�ла и ⤳; под�казка перечи�л�ет пор�дки. +- Вы�ота — в�� вкладка, прокрутка; выбранный узел прокручивает�� в видимую обла�ть при навигации � клавиатуры. + +### 3.7. Вкладка «Дебюты» — таблица + +``` + Дебют Первые ходы Партий % Счёт По�ледн�� Ошибок + ▾ Sicilian Defense B20–B99 1.e4 c5 50 37 70 % ▕██▒░� 18.10.2026 3 ? · 1 ?? + Nyezhmetdinov-Rossolimo Attack B30 1.e4 c5 2.Nf3 Nc6 3.Bb5 14 28 71 % 12.10.2026 1 ? + Grand Prix Attack B23 1.e4 c5 2.Nc3 Nc6 3.f4 11 22 64 % 18.10.2026 2 ? · 1 ?? + Open Sicilian B32–B99 1.e4 c5 2.Nf3 … 3.d4 19 38 74 % 05.10.2026 + без названи� глубже 6 12 67 % 21.08.2026 + ▸ French Defense C00–C19 1.e4 e6 21 15 81 % 18.10.2026 2 ?! + ▸ Caro-Kann Defense B10–B19 1.e4 c6 18 13 83 % 27.09.2026 +``` + +- Две �тупени: **�емей�тво** (ча�ть имени до двоеточи�) → **варианты** (�амое глубокое им� линии). Парти� �читает�� в одном варианте. Варианты без имени глубже �емей�тва — �трока «без названи� глубже» (`no deeper name`). +- Колонки: Дебют (им�, у варианта — без повторени� �емей�тва), ECO �лабым (у �емей�тва — диапазон), Первые ходы (лини� до именованной позиции, �лабым, �окращает�� � «…» по�ередине — первые и по�ледние ходы важнее �ередины), Партий, % (�емей�тво — от цвета, вариант — от �емей�тва), Счёт � поло�ой, По�ледн��, Ошибок (по�ле движка: �чётчики цветом отметок; пу�то = ошибок нет; «…» пока �читает��). +- При переключателе «Оба» — колонка «Цвет» первой (`♙`/`♟` + «белыми / чёрными»), и �емей�тва одного имени за разные цвета — разные �троки. Сортировка по умолчанию — по чи�лу партий; заголовки �ортируют (Счёт, По�ледн��, Ошибок). +- Щелчок по �троке — до�ка показывает именованную позицию, �пи�ок партий — партии дебюта/варианта («Партии · French Defense · 21»). Двойной щелчок по �емей�тву — ра�крыть. С�ылка в под�казке �троки «показать в дереве» — вопро� 11.6; в первой вер�ии нет. + +### 3.8. Вкладка «Ошибки» + +При автозапу�ке �та вкладка открывает�� �ама (§4). Во врем� работы её перва� �трока — полный `egui::ProgressBar` «Ищу ошибки: {done} из {total} позиций · ≈ {time}» � кнопкой «О�тановить»; �пи�ок результатов ра�тёт ниже. По�ле ручной о�тановки зде�ь же — «Проверено {done} из {total}» и «Продолжить». Пример завершённого �о�то�ни� в �топке, где �водка по цвету находит�� на �той вкладке: + +``` + Ошибки найдены · Stockfish 19 · 1 306 позиций [▾] + Чёрными: неточно�тей 14 · ошибок 11 · зевков 5 — в 24 парти�х из 133 (18 %) + + Повтор�ющие�� ошибки — одна и та же позици�, тот же ход + Позици� Сыграл Лучше × Счёт Дебют + ▸ по�ле 6.Bc4, ход чёрных 6…Nb6 ? 6…e6 3 +1 −2 Sicilian Defense: Grand Prix Attack · B23 + ▸ по�ле 4…Nf6, ход белых 5.e5 ?? 5.Nc3 2 +0 −2 Caro-Kann Defense: Advance Variation · B12 + ▸ по�ле 7.Qd2, ход чёрных 7…O-O ?! 7…Nxd4 2 +1 −1 Sicilian Defense: Open · B56 + + По дебютам + ▾ Sicilian Defense: Grand Prix Attack · B23 11 партий · 2 ? · 1 ?? + 6…Nb6 ? лучше 6…e6 Кузнецов — Вафин 0-1 18.10.2026 + 6…Nb6 ? лучше 6…e6 Ширшов — Вафин 1-0 12.10.2026 + 9…f5 ?? лучше 9…Be7 Гади�ов — Вафин 1-0 03.09.2026 + ▸ Sicilian Defense: Nyezhmetdinov-Rossolimo Attack · B30 14 партий · 1 ? + ▸ French Defense · C00 21 партий · 2 ?! +``` + +- **Повтор�ющие��** — узлы дерева � отметкой и ≥ 2 парти�ми; пор�док: по чи�лу партий, затем по т�же�ти. Ра�крытие �троки показывает партии (как в «По дебютам»). «Счёт» — результат игрока в �тих парти�х. +- **По дебютам** — по вариантам (�амое глубокое им�), внутри — ошибки по парти�м: ход � отметкой, «лучше …» (первый ход лучшей линии, под�казка — лини� и оценки), парти� «Белые — Чёрные», результат, дата. Сортировка �емей�тв — по чи�лу ошибок � ве�ом (?? = 3, ? = 2, ?! = 1), чтобы наверху было �амое больное. �еточно�ти показывают��, но �читают�� �лабее; выключатель «показывать неточно�ти» — вопро� 11.4. +- **Щелчок** по �троке ошибки — до�ка показывает позицию **до** хода, �трелки: �ыгранный ход цветом отметки, лучший — зелёный (как �трелка лучшего хода на �кране партии); под до�кой лини� до позиции и �трока «6…Nb6 ? — лучше 6…e6 · 0,0 → −1,2». **Enter / двойной щелчок** — парти� на �том ходу (у повтор�ющей�� — перва� по дате, ра�крытие даёт выбрать). +- Ошибки, попавшие за пределы глубины дебюта (�трока «Дебют: 10 ходов»), не ищут�� — под�казка �троки прогре��а и �тату�а указывает �ту глубину. +- В �топке �водка ошибок по цветам показывает�� зде�ь, а не в §3.5; при «Оба» — два блока. В �пи�ках при «Оба» — колонка «Цвет». + +### 3.9. До�ка + +- Виджет `board.rs`, без ввода ходов (щелчок по фигуре ничего не делает; ввод — через «Открыть как партию»). Ориентаци� — **по цвету игрока** (его фигуры �низу: �мотрим его глазами; «Оба» — по цвету выбранного корн�); `F` переворачивает, выбор держит�� до закрыти� отчёта. +- �ад до�кой — индикатор очереди хода и «по�ле 3.Bb5» (как в панели до�ки пои�ка). Под до�кой — лини� ходов до узла (поток токенов, щелчок по ходу — до�ка на �тот ход, выделение в дереве не мен�ет��), под ней им� дебюта + ECO дл� �той позиции (�лабым), затем кнопки «Открыть как партию» (`Open as a game`) и `⋯`. +- Меню `⋯`: «Играть от�юда…» (`Play on from here…`, тот же диалог, что на �кране партии; цвет по умолчанию — �торона на ходу), «�айти позицию в базе» (`Ctrl+Shift+F`, до�ка пои�ка библиотеки � �той линией), «Копировать FEN», «Копировать ходы (PGN)». +- �аведение на �троку дерева (не выбранную) — �ин�� �трелка **�ледующего хода** на текущей до�ке, е�ли наведённый узел — ребёнок выбранного; иначе ничего (чужа� позици� — чужие �трелки). �аведение на �троку �пи�ка партий — �трелка хода �той партии из позиции (как в Справочнике). +- Мини-до�ка 160×160 в под�казке — только в �троках «Повтор�ющие�� ошибки» (позици� до хода � двум� �трелками): бы�тро пробежать �пи�ок, не щёлка�. В дереве мини-до�ок нет — р�дом больша�. + +### 3.10. Спи�ок партий + +Таблица как в Справочнике: Белые · Эло · Чёрные · Эло · Рез. · Дата · Дальше · Турнир; плю� по�ле движка колонка **Ошибки** (`Errors`): отметки его ходов в дебюте �той партии «7.? 12.??» (номер хода + значок цветом; пу�то — без ошибок; «…» — ещё �читает��). Игрок — полужирным в �воей колонке. + +- Заголовок: «Партии · 271» без выбора; � узлом — «Партии · по�ле 3.Bb5 · 14 ✕»; � дебютом — «Партии · French Defense · 21 ✕»; � ошибкой — «Партии · 6…Nb6 ? · 3 ✕». `✕` �нимает выбор (в�е партии цвета). При переключателе «Оба» — в�е партии игрока. +- Сортировка по умолчанию — новые �верху; заголовки �ортируют. +- **Двойной щелчок / Enter** — парти� в обычном �кране **на ходе выбранного узла** (у ошибки — на ходе � ошибкой; без узла — на первом ходе). В шапке партии «⬅ К подготовке» (`⬅ Back to preparation`), `Ctrl+W` возвращает к отчёту как был. Отчёт о�таёт�� в �теке так же, как парти� из Справочника (`reference.md`, «Открыта� из �пи�ка парти� не закрывает текущую»). +- Открыта� парти� — обычна�: анализ партии `Shift+A`, живой движок, комментарии. Отметки отчёта в нотацию не перено��т�� (разные к�ши; вопро� 11.5). +- В узкой таблице колонки пр�чут�� по очереди: Турнир, Дальше, Дата → Год, Эло (в �чейку имени �лабым) — как в `board-search.md` §2.7. + +## 4. Движок: автоматиче�кий пои�к ошибок в дебютах + +### 4.1. �втозапу�к — решение владельца, 2026-11-01 + +Задача �о�то�ни� — �разу начать оценку дебютных позиций текущими параметрами, о�тавив пользователю видимый прогре�� и возможно�ть о�тановить работу. + +- По�ле по�троени� отчёта пои�к ошибок �тартует **автоматиче�ки**, без диалога-объ��нени� и без требовани� �начала нажать «�айти ошибки». И�пользуют�� текущие �охранённые параметры движка; флаг «параметры однажды выбраны» не �вл�ет�� у�ловием запу�ка. +- Во врем� �бора пользователь видит «Репертуар». При фактиче�ком �тарте движка �кран **один раз** переключает�� на «Ошибки» — �то уже прин�тое поведение реализации (§12). Дальше пользователь может уйти на «Репертуар» или «Дебюты»; работа продолжает��, а вкладка �ама больше не переключает��. +- Е�ли в�е позиции уже е�ть в к�ше, проце�� не запу�кает�� и автопереключени� вкладки нет: повторный вход �охран�ет вкладку по §3.1, а «Ошибки» �одержат готовый �тату� и результаты. �улевое чи�ло партий — �о�то�ние §5, фиктивный прогре�� и запу�к проце��а не нужны. +- Смена глубины или периода �нова разрешает автозапу�к: �начала завершает�� �тарый job и �охран�ют�� его оценки, затем отчёт пере�траивает��, по�ле чего движок автоматиче�ки провер�ет недо�тающие позиции новой конфигурации. Это дей�твует и по�ле предыдущей ручной о�тановки. +- Уход/возврат на �кран и открытие параметров автозапу�к не вызывают. Ручна� о�тановка запрещает автоматиче�кий перезапу�к �той конфигурации, в том чи�ле при повторном входе в ту же �охранённую подготовку; �бро� запрета — только �мена глубины/периода либо �вное «Продолжить». + +### 4.1.1. Допу�тимые ошибки игрока (решение владельца, 2026-11-05) + +В результат вход�т только ошибки изучаемого игрока **до первой ошибки его �оперника** +в каждой партии. Учитывают�� �уще�твующие категории ?!, ? и ??; новые пороги не ввод�т��. +Более ранние ошибки �амого игрока о�тают��. Сыгранный лучший ход движка, как и раньше, +ошибкой не �читает��. До проверки предше�твующих ходов �оперника поздн�� ошибка игрока +не показывает��. Это фильтр �пи�ка ошибок, повторов и их агрегатов, а не дерева репертуара. +При одинаковой позиции из разных партий у�ловие провер�ет�� отдельно по каждой и�тории. +Старые отчёты пере�читывают�� из �охранённых оценок при загрузке. + +### 4.2. Контролы и параметры + +- �а вкладке «Ошибки» во врем� работы перва� �трока — `egui::ProgressBar`: `Ищу ошибки: 812 из 1 306 позиций · ≈ 20 �` и р�дом тек�това� **«О�тановить»**. Это о�новной, �амый полный индикатор. Компактный дубль � теми же чи�лами и Stop о�таёт�� в �троке переключателей, чтобы �о�то�ние было видно � других вкладок. +- Кнопка **«▾»** открывает �уще�твующий `engine_dialog` только по �вному запро�у — дл� про�мотра/�мены параметров и оценки времени. Он не по�вл�ет�� перед первым автозапу�ком, по�ле �мены глубины/периода или перед «Продолжить». Со�тав �амого диалога �та правка не ра�шир�ет. +- Оценка времени по-прежнему �читает�� по дедуплицированным позици�м без к�ша: `позиции_без_к�ша × узлы / (nps_на_поток × потоки)`; одинаковые позиции �читают�� один раз. Оценка нужна в прогре��е и в диалоге параметров, но не задерживает �тарт. +- Е�ли движок не у�тановлен, автозапу�к не открывает об�зательный диалог и не начинает загрузку �ам. �а «Ошибках» видно «Сначала добавьте движок» и �уще�твующее дей�твие �качивани� Stockfish (`engine-download.md`). По�ле �вной у�тановки �уще�твующий `start_after_engine` запу�кает пои�к без дополнительного диалога-объ��нени�. + +### 4.3. Работа, о�тановка и ручное продолжение + +- Отметки по�вл�ют�� **по мере оценки** в дереве, таблице дебютов, �пи�ке партий и на вкладке «Ошибки» (�трока «Повтор�ющие��» пере�ортировывает�� не чаще раза в �екунду; пока кур�ор над �пи�ком — не пере�ортировывает��). Пор�док оценки — по дереву в ширину: ча�тые позиции и повтор�ющие�� ошибки видны первыми. +- **«О�тановить»** �охран�ет в�е уже полученные оценки. Вкладка показывает `Проверено 812 из 1 306 позиций · [Продолжить ≈ 12 �]`; ча�тичные �чётчики имеют под�казку «из проверенных позиций». Под�казка Stop: «О�тановить пои�к ошибок; уже оценённые позиции �охран�т��». +- **«Продолжить»** — ручной запу�к только недо�тающих позиций, без диалога и без потери к�ша. Оно до�тупно и на «Ошибках», и в �троке переключателей. По�ле о�тановки никакой таймер, возврат на �кран или �мена вкладки не запу�кают движок �ами. +- Один engine job на в�ю программу: пока идёт пои�к ошибок, «�нализ партии» в открытой из отчёта партии неактивен � под�казкой «Идёт пои�к ошибок в дебютах — дождите�ь или о�тановите его в отчёте»; живой анализ (`L`) �тавит�� на паузу. И наоборот: автозапу�к подготовки ждёт до�тупно�ти движка, а не �оздаёт конкурирующий проце��. Е�ли ожидание требует�� реализацией, на «Ошибках» показывает�� «Ожидаю о�вобождени� движка…», без повтор�ющих�� попыток запу�ка каждый кадр. +- Уход � �крана отчёта работу **не прерывает**: при возврате — актуальный прогре��, ча�тичный результат по�ле Stop либо готовый результат. Выход из программы во врем� работы — вопро� «Идёт пои�к ошибок в дебютах. Выйти и о�тановить?»; �деланное �охранено в к�ше. +- В узком окне полный прогре�� и тек�това� «О�тановить» о�тают�� на «Ошибках»; в �троке переключателей допу�тимо только �окращение тек�та до `{done}/{total}` � полной под�казкой. �втозапу�к не мен�ет �уще�твующие правила компоновки. + +### 4.4. Завершение, �бой и �мена у�ловий + +- По�ле завершени� прогре�� замен�ет�� на `Ошибки найдены · Stockfish 19 · 1 306 позиций`; ниже — полные �пи�ки ошибок и �водка. Проце�� завершён, кнопки Stop нет, автоматиче�кого повторного прохода нет. «▾» о�таёт�� до�тупна дл� параметров. +- Сбой движка — �трока � предупреждением, «Подробно�ти» и **«Повторить»**, как у анализа партии. Повтор только ручной; уже полученные оценки �охран�ют��. Ошибка не ма�кирует�� под «ошибок нет». +- Смена глубины/периода о�танавливает job �тарой конфигурации, �охран�ет �деланное и запу�кает �ценарий §4.1 дл� новой. Результаты �тарого job не примен�ют�� к новому отчёту. +- К�ш по позиции — `~/.cache/chesspenguin/prep/` (техча�ть §7.3). При повторном входе � полным к�шем показывает�� готовый результат без нагрузки; � ча�тичным к�шем по�ле ручной о�тановки — �о�то�ние «Проверено X из Y» и ручное «Продолжить», а не автозапу�к. + +## 5. Со�то�ни� + +| Со�то�ние | Что видно | +|---|---| +| **Партий мало** (< 10 выбранным цветом) | под �водкой �трока предупреждени�: «Партий мало (7) — проценты и �чёт ненадёжны» (`Few games (7): percentages and scores are unreliable`); проценты в узлах � < 5 парти�ми �лабым (§3.6) | +| **�ет партий выбранным цветом** | дерево/таблица: по центру «Чёрными партий нет. Белыми — 138 · [Показать белые]» (`No games as Black. As White — 138 · Show White`); корень «Чёрными · 0» в режиме «Оба» показывает�� �лабым без ра�крыти�; движок дл� пу�того выбранного цвета не запу�кает��, при «Оба» провер�ет�� имеющий�� цвет | +| **�ет партий вов�е** (у�лови� библиотеки от�екли в�ё) | «Партий по у�лови�м нет: {чипы}. [Открыть без у�ловий]»; движок не запу�кает��, прогре��а `0/0` нет | +| **Сбор идёт** (Mega-фильтр) | на ме�те дерева «Собираю партии… 37 %» � поло�ой и «Отмена» (возвращает в библиотеку); шапка уже показывает им�; движок ещё не запущен | +| **Движок ещё не запущен** | штатно �то только ожидание готовно�ти отчёта или о�вобождени� движка: на «Ошибках» �оответ�твующий �тату�, без диалога. При невозможно�ти автозапу�ка — причина и ручное дей�твие; приглашение � об�зательным первым диалогом больше не и�пользует�� | +| **Движок �читает** | на «Ошибках» полна� поло�а «Ищу ошибки: 812 из 1 306 позиций · ≈ 20 � [О�тановить]», в �троке переключателей компактный дубль; отметки и �пи�ки ра�тут по мере оценки | +| **Движок о�тановлен** | «Проверено 812 из 1 306 позиций · [Продолжить]»; ча�тичные �чётчики � под�казкой «из проверенных позиций»; �ам не перезапу�кает�� | +| **Готово** | �трока �о�то�ни� §4.4, Stop нет, повторного автозапу�ка нет | +| **Готово, ошибок нет** | вкладка «Ошибки»: «В первых 10 ходах ошибок не нашло�ь (неточно�тей 3). [Глубже: 15 ходов]» | +| **�ет движка** | на «Ошибках» «Сначала добавьте движок» и �вное дей�твие �качать Stockfish (`engine-download.md`); об�зательный диалог и автоматиче�ка� загрузка не открывают�� | +| **База изменила�ь** (допи�ана, файл заменён) | отчёт пере�обирает�� при возврате, оценки берут�� из к�ша; е�ли ручна� о�тановка не запретила автозапу�к, новые позиции провер�ют�� автоматиче�ки, иначе показывает�� «Продолжить» | +| **Игрок — не�колько напи�аний** | «+1 напи�ание» в шапке � под�казкой; в �пи�ке партий им� — как в запи�и | +| **Партии без дат** | «По�ледн��» — «—», период в шапке пропущен | +| **Парти� � FEN или Chess960** | не входит в дерево; в под�казке �чётчика шапки «не учтены: � заданной позиции — 2» | + +## 6. Узкие и низкие окна + +Правило `narrow-windows.md` §0: компоновку выбирает размер окна. `W`, `H` — под шапкой отчёта. + +- **Р�дом** (как в §3.2), когда `W ≥ BOARD_MIN(220) + 24 + 560` = **804** и `H ≥ 600`: до�ка `min(H − 120, 420, W − 584)`, но не меньше 220; права� колонка — о�тальное. +- **Стопка** (`W < 804` или `H < 600`): верхний блок — до�ка 240 �лева, �права от неё лини� ходов, им� дебюта и кнопки (вертикально); под ним вкладки и �пи�ок партий. При `H < 720` до�ка в �топке �крыта по умолчанию: в �троке переключателей кнопка «♙ До�ка» (`Board`) открывает её поверх правой нижней ча�ти как выдвижную панель 264 × 300 (� тенью, как фильтры в узком окне), закрытие — та же кнопка, `Esc` или щелчок вне. Так при 640 × 480 дереву о�таёт�� ≈ 300 точек вы�оты — 12 �трок. + +``` +640 × 1000 (�топка) 640 × 480 (до�ка �крыта) +⬅ Библиотека │ Вафин Радель · 271 · … ⚙ ⬅ Библиотека │ Вафин Радель… ⚙ +[Белые│Чёрные│Оба] [В�е ▾] [10 х. ▾] [▶ Ошибки] [Белые│Чёрные│Оба] [В�е ▾] [10 х.] [♙] [▶] +Чёрными 133 · 58 % Чёрными 133 · 58 % +┌──────────� ○ Ход белых · по�ле 2…Nf6 [Репертуар] Дебюты Ошибки +│ │ 1.e4 c5 2.c3 Nf6 Ход Партий % Счёт +│ до�ка 240│ Sicilian Defense: Alapin · B22 ▾ Чёрными 133 58 % +│ │ [Открыть как партию] [⋯] ▾ 1.e4 79 59 60 % +└──────────┘ ▾ 1…c5 79 100 60 % +[Репертуар] Дебюты Ошибки ▸ 2.Nf3 39 49 63 % +Ход Дебют Партий % Счёт ▌2.c3 17 22 53 % +▾ Чёрными 133 58 % ────────────────────────────── + ▾ 1.e4 79 59 60 % Партии · по�ле 2.c3 · 17 ✕ + ▾ 1…c5 Sicilian · B20 79 100 60 % Белые Чёрные Рез. Год +``` + +- **Строка переключателей** — пор�док и наличие кнопки до�ки определ�ют�� §3.4; подпи�и глубины и периода �окращают�� по измеренной ширине, компактный движок — по §4.3. Полные прогре�� движка и Stop в�егда до�тупны на «Ошибках». Отдельна� задача 30 о пере�ечении контролов �тим обновлением не закрывает��. +- **Сводка** — при `W < 804` одна �трока выбранного цвета (у «Оба» — две). Сначала �крывает�� «по�ледн��», затем «�оперники» (полные значени� — в под�казке); �чёт �охран�ет�� в компактном виде. В �топке ошибки показывают�� только на вкладке «Ошибки». +- **Колонки дерева** пр�чут�� по очереди: По�ледн�� → поло�а �чёта (о�таёт�� %) → Дебют (им� переезжает в под�казку хода). �икогда: Ход, Партий, %, Счёт-процент. Таблица дебютов: Первые ходы → По�ледн�� → ECO → поло�а. Вкладка «Ошибки»: Дебют → Счёт. +- **Диалоги** (§2.2, §4.2) при 640 × 480 — тело прокручивает��, кнопки вне прокрутки (как `play-mode.md` §2.5). + +## 7. Клавиатура + +Правило как на до�ке пои�ка: клавиши без модификаторов дей�твуют, когда фоку� не в тек�товом поле. Фоку� один из двух: дерево/таблица вкладки или �пи�ок партий; `Tab` переключает между ними, видимый фоку� — поло�а ▌ у выделенной �троки �рче. + +| Клавиша | Дей�твие | +|---|---| +| `↑` / `↓`, `PgUp` / `PgDn`, `Home` / `End` | �трока в текущей таблице | +| `→` | дерево: ра�крыть узел; ра�крыт — к первому ребёнку. Таблица дебютов: ра�крыть �емей�тво | +| `�` | дерево: �вернуть; �вёрнут — к родителю | +| `Space` | ра�крыть/�вернуть без перемещени� | +| `Enter` | в дереве/дебютах — фоку� в �пи�ок партий (перва� �трока); в �пи�ке партий и во вкладке «Ошибки» — открыть партию на ходе | +| `Ctrl+1` / `Ctrl+2` / `Ctrl+3` | вкладки Репертуар / Дебюты / Ошибки | +| `Ctrl+W` / `Ctrl+B` | цвет Белые / Чёрные (`Ctrl+W` зде�ь не «закрыть»: закрытие отчёта — «⬅ Библиотека» или `Esc` без выделени�) — **вопро� 11.7**; запа�ной вариант: `Alt+1/2/3` дл� Белые/Чёрные/Оба | +| `F` | перевернуть до�ку | +| `Shift+A` | «�айти ошибки в дебютах» (та же клавиша, что «�нализ партии» — то же дей�твие «позвать движок»); во врем� работы — «О�тановить» | +| `Ctrl+Shift+F` | найти позицию до�ки в базе (до�ка пои�ка библиотеки) | +| `Esc` | закрыть меню/под�казку → �н�ть выбор узла (�пи�ок — в�е партии) → назад в библиотеку | +| `Ctrl+Shift+P` (библиотека) | «Подготовить�� к…» � игроком из фильтра | + +В�е дей�тви�, кроме �трелок наведени�, до�тупны � клавиатуры; чтение �крана — у отметок тек�товые под�казки � названием («Ошибка», «Зевок»). + +## 8. Цвета и значки + +Отметки — как в нотации и в отчёте анализа (`notation::assessment_color` / `assessment_text_color`, `review::judgement_color`): + +| Отметка | NAG | Заливка значка | Тек�т на �ветлом | Где | +|---|---|---|---|---| +| `?!` неточно�ть | 6 | `#56b4e9` | `#1f72a8` | значок-пилюл� по�ле SAN (дерево, «Сыграл», колонка «Ошибки» �пи�ка партий); �чётчики тек�том | +| `?` ошибка | 2 | `#ffa459` | `#c25700` | то же | +| `??` зевок | 4 | `#fa412d` | `#d2301c` | то же | + +- Значок — пилюл� � белым �имволом, как `move_glyph` в нотации; в �чётчиках («3 ? · 1 ??») — тек�т цветом `assessment_text_color` по теме; `!!`/`!` зде�ь не ищут�� и не показывают��. +- Стрелки на до�ке: �ыгранный ход — цвет его отметки (полупрозрачный), лучший — зелёный �трелки движка; наведение — �иний полупрозрачный, как на до�ке пои�ка. +- Поло�а �чёта — �ветлотой (Б �ветлый, ничьи �ерый, Ч тёмный) � процентами внутри и под�казкой, без кра�ного/зелёного (`board-search.md` §4.10). Счёт — в�егда очки **игрока**, незави�имо от цвета; подпи�ь колонки «Счёт», под�казка «Очки �оперника в �тих парти�х». +- «Мало партий» — �лабый тек�т. �и одно �о�то�ние не передаёт�� только цветом: у в�ех е�ть чи�ло, �имвол или под�казка. + +## 9. Тек�ты (ключ EN → RU) + +| EN (ключ) | RU | +|---|---| +| `♟ Prepare against {name}…` | ♟ Подготовить�� к {name}… | +| `♟ Prepare against an opponent…` | ♟ Подготовить�� к �опернику… | +| `Prepare against ▸` | Подготовить�� к �опернику ▸ | +| `Preparing against an opponent` (диалог) | Подготовка к �опернику | +| `Preparing against {name}` (шапка) | Подготовка к �опернику: {name} | +| `Database` (е�ть) | База | +| `Player` (е�ть) | Игрок | +| `Similar names — most likely other people` | Похожие имена — �корее в�его, другие люди | +| `Selected: {names} · {n}` | Отмечено: {names} · {n} | +| `Tick a player` | Отметьте игрока | +| `+{n} spelling` / `+{n} spellings` | +{n} напи�ание / +{n} напи�ани� (`i18n` �клонение) | +| `Colour` | Цвет | +| `Both` · `White` · `Black` | Оба · Белые · Чёрные | +| `White — {n}` · `Black — {n}` | Белые — {n} · Чёрные — {n} | +| `As White` · `As Black` (корни дерева) | Белыми · Чёрными | +| `Retry` | Повторить | +| `Open report` | Открыть отчёт | +| `Opening: {n} moves` | Дебют: {n} ходов | +| `Collecting games… {p} %` | Собираю партии… {p} % | +| `{n} games · {score} % ({w}+ {d}= {l}−) · opponents ≈ {elo} · last {date}` | {n} · {score} % (+{w} ={d} −{l}) · �оперники ≈ {elo} · по�ледн�� {date} | +| `{i} ?! · {m} ? · {b} ??` | {i} ?! · {m} ? · {b} ?? | +| `in {p} % of games` | в {p} % партий | +| `no errors` | нет ошибок | +| `Opening errors: {i} inaccuracies · {m} mistakes · {b} blunders — in {g} games ({p} %)` | Ошибок в дебюте: неточно�тей {i} · ошибок {m} · зевков {b} — в {g} парти�х ({p} %) | +| `Few games ({n}): percentages and scores are unreliable` | Партий мало ({n}) — проценты и �чёт ненадёжны | +| `Few games: percentages are unreliable` | Мало партий — проценты ненадёжны | +| `Repertoire` · `Openings` · `Errors` | Репертуар · Дебюты · Ошибки | +| `Branches from {n} games` | Ветви от {n} партий | +| `Expand all` · `Collapse` | Ра�крыть в�ё · Свернуть | +| `Move` · `Opening` · `Games` · `%` · `Score` · `Last` | Ход · Дебют · Партий · % · Счёт · По�ледн�� | +| `First moves` · `Errors` · `Played` · `Better` · `Position` · `Colour` | Первые ходы · Ошибок · Сыграл · Лучше · Позици� · Цвет | +| `other moves ({n})` | другие ходы ({n}) | +| `no deeper name` | без названи� глубже | +| `Reached by another move order too: {orders}` | К позиции приходили и другим пор�дком: {orders} | +| `The opponent's points in these games` | Очки �оперника в �тих парти�х | +| `Games · {n}` · `Games · after {move} · {n}` · `Games · {opening} · {n}` · `Games · {move} · {n}` | Партии · {n} · Партии · по�ле {move} · {n} · Партии · {opening} · {n} · Партии · {move} · {n} | +| `Then` (е�ть) · `Event` (е�ть) | Дальше · Турнир | +| `Open as a game` | Открыть как партию | +| `Play on from here…` (е�ть) · `Find this position in a database (Ctrl+Shift+F)` (е�ть) · `Copy FEN` · `Copy moves (PGN)` | Играть от�юда… · �айти позицию в базе (Ctrl+Shift+F) · Копировать FEN · Копировать ходы (PGN) | +| `⬅ Back to preparation` | ⬅ К подготовке | +| `▶ Find opening errors` · `▶ Find opening errors ≈ {time}` | ▶ �айти ошибки в дебютах · ▶ �айти ошибки в дебютах ≈ {time} | +| `Options…` | Параметры… | +| `Opening errors` (диалог) | Ошибки в дебютах | +| `The engine evaluates the first {n} moves of every game of the opponent. The games are not changed.` | Движок оценит первые {n} ходов каждой партии �оперника. Партии не мен�ют��. | +| `Engine` · `Quality` · `Threads` · `Memory` (е�ть) | Движок · Каче�тво · Потоки · Пам�ть | +| `For opening errors “Fast� is usually enough. “Normal� is for adult databases and takes 4 times longer.` | Дл� пои�ка ошибок в дебюте обычно до�таточно «Бы�тро». «Обычно» — дл� взро�лых баз, в 4 раза дольше. | +| `{n} positions, about {time}` (е�ть) | {n} позиций, около {time} | +| `identical positions are counted once; {n} already evaluated earlier` | одинаковые позиции �читают�� один раз; {n} уже оценены раньше | +| `Find errors` | �айти ошибки | +| `Finding errors: {done} of {total} positions · ≈ {time}` | Ищу ошибки: {done} из {total} позиций · ≈ {time} | +| `The engine evaluates positions to find inaccuracies, mistakes and blunders. It starts automatically after the report is built; evaluated positions are kept after Stop.` (hover контрола движка) | Движок оценивает позиции и находит неточно�ти, ошибки и зевки. Запу�кает�� �ам по�ле по�троени� отчёта; по�ле Stop оценённые позиции �охран�ют��. | +| `Stop` · `Continue ≈ {time}` | О�тановить · Продолжить ≈ {time} | +| `Stop the error search. Evaluated positions are kept.` | О�тановить пои�к ошибок. Уже оценённые позиции �охран�т��. | +| `Waiting for the engine to become available…` | Ожидаю о�вобождени� движка… | +| `No games to analyse` | �ет партий дл� анализа | +| `Checked {done} of {total} positions` | Проверено {done} из {total} позиций | +| `of the checked positions` | из проверенных позиций | +| `Errors found · {engine} · {quality} · {n} positions · {date}` | Ошибки найдены · {engine} · {quality} · {n} позиций · {date} | +| `More precisely…` · `Analyse {n} more positions ≈ {time}` | Точнее… · Доразобрать {n} позиций ≈ {time} | +| `Opening errors are being searched — wait or stop it in the report` | Идёт пои�к ошибок в дебютах — дождите�ь или о�тановите его в отчёте | +| `A game analysis is running — wait for it to finish` | Идёт анализ партии — дождите�ь его конца | +| `Opening errors are being searched. Quit and stop?` | Идёт пои�к ошибок в дебютах. Выйти и о�тановить? | +| `Add an engine first` | Сначала добавьте движок | +| `No errors in the first {n} moves ({i} inaccuracies).` | В первых {n} ходах ошибок не нашло�ь (неточно�тей {i}). | +| `Deeper: {n} moves` | Глубже: {n} ходов | +| `Repeated errors — the same position, the same move` | Повтор�ющие�� ошибки — одна и та же позици�, тот же ход | +| `By opening` | По дебютам | +| `after {move}, {side} to move` | по�ле {move}, ход {side} (белых/чёрных) | +| `{played} — better {best} · {before} → {after}` | {played} — лучше {best} · {before} → {after} | +| `Mistake: better {best} ({before} → {after}) · in {n} games` | Ошибка: лучше {best} (оценка {before} → {after}) · в {n} парти�х | +| `Inaccuracy` · `Mistake` · `Blunder` (е�ть) | �еточно�ть · Ошибка · Зевок | +| `No games as {colour}. As {other} — {n} · Show {other}` | {colour} партий нет. {other} — {n} · Показать {other} | +| `No games match the conditions: {chips} · Open without conditions` | Партий по у�лови�м нет: {chips} · Открыть без у�ловий | +| `not counted: from a set position — {n}` | не учтены: � заданной позиции — {n} | +| `Board` (кнопка в �топке) | До�ка | + +Имена игроков нигде не �клон�ют�� («Подготовить�� к Вафин Радель…»); чи�ла партий — через `i18n::games`. + +## 10. Что мен�ет разработчик (�водка дл� `apps/desktop`) + +1. `large_db.rs` `players_group`: кнопка «♟ Подготовить�� к…» под �трокой цвета; контек�тное меню �троки — два пункта; `LibraryAction::PrepareAgainst { path, names, side, filter }`. +2. `game_view.rs`: пункт ☰ «Подготовить�� к �опернику ▸» и контек�тное меню названи�; `GameAction::PrepareAgainst`; «⬅ К подготовке» по тому же `previous`-механизму, что «⬅ К партии». +3. `prep_ui.rs`: книжные контролы, фоновый проход, колонки и результаты удалены из подготовки. Старые пол� в JSON отчёта, �охранённой подготовки и на�троек о�тают�� па��ивными legacy-данными: не вычи�л�ют�� и не показывают��, но не �тирают�� обычным авто�охранением. Обычный Справочник не мен�ет��. +4. `prep_ui.rs`: по�ле готовно�ти отчёта автоматиче�ки вызывать `start_engine` без `engine_asked`/`prep.chosen`; автопереход на «Ошибки» только при �тарте. �а «Ошибках» добавить полный прогре�� и Stop. По�ле ручной о�тановки хранить запрет автозапу�ка дл� �той конфигурации; «Продолжить» вызывает запу�к напр�мую. Смена глубины/периода �бра�ывает запрет и запу�кает движок по�ле пере�троени�. `engine_dialog` о�таёт�� только по «▾». +5. `settings.rs` / �охранённа� подготовка: `prep.chosen` больше не �вл�ет�� разрешением запу�ка; �о�то�ние ручной о�тановки должно переживать уход и повторный вход, чтобы ча�тичный к�ш не запу�кал движок �ам. �а�тройки глубины и периода �охран�ют�� как прежде. +6. `app.rs`: уход � �крана не отмен�ет engine job; поздние ответы примен�ют�� только к �воей конфигурации. Сохран�ет�� один engine job на программу и вопро� при выходе во врем� анализа. +7. Сводка — по §3.5: отдельные title/games, games � выравниванием вправо, компактный score, �о�едние counts/percent. Ширины counts и percent измер�ть незави�имо через реальный `Label` � `gap = 4`; нулевые типы пропу�кать, при в�ех нул�х не �оздавать колонку процента. Пор�док �крыти� — last → opponents; score/errors не �крывать, в �топке ошибки о�тавить только на вкладке «Ошибки». +8. Снимки дл� проверки: �чётчики разной разр�дно�ти и �табильна� X процента, пропущенные нулевые типы, в�е нули без процента, компактный score; автозапу�к движка на «Ошибках», ручна� о�тановка и «Продолжить» без диалога; �мена глубины/периода; уход и повторный вход; нулевые партии и 640×480. Пере�ечение контролов провер�ет�� отдельно по задаче 30 и зде�ь не �читает�� и�правленным. + +## 11. Открытые вопро�ы + +1. **У�лови� библиотеки в отчёте** (§2.4): брать активные фильтры (годы, Эло, турнир) как у�лови� отчёта при входе из панели — да (рекомендаци�) или в�егда в�е партии игрока? +2. **Цвет по умолчанию** — «Оба» при входе из партии/�троки и цвет фильтра при входе из панели (рекомендаци�), или в�егда �прашивать? Диалог показывает радио в любом �лучае. +3. **Каче�тво «Бы�тро» по умолчанию** отдельной на�тройкой от анализа партии — утвердить (техча�ть, вопро� 4). +4. **�еточно�ти `?!`** во вкладке «Ошибки»: показывать в�егда (рекомендаци�, �лабее и ниже) или за выключателем «показывать неточно�ти»? +5. **Отметки отчёта в открытой партии**: показывать оценки дебюта из к�ша отчёта как �лой в нотации (без анализа партии)? Требует общего к�ша по позиции � `game-review` (техча�ть, вопро� 5). Рекомендую позже. +6. **«Показать в дереве»** из таблицы дебютов и из «Ошибок» — ��ылка, переключающа� вкладку и выдел�юща� узел. Дёшево; добавить в первую вер�ию? +7. **Клавиши цвета**: `Ctrl+W`/`Ctrl+B` занимают «закрыть» — предпочитаю `Alt+1/2/3` или вов�е без клавиш (переключатель в�егда на виду). Решить. +8. **Мини-до�ка в под�казке** �трок «Повтор�ющие�� ошибки» — о�тавить (рекомендаци�) или до�таточно большой до�ки по щелчку? +9. **«Играть от�юда…» и «Открыть как партию»** � до�ки отчёта — в первую вер�ию (рекомендаци�: �то �уще�твующие дей�тви�) или по�ле? + +## 12. Ревью реализации (f02f140, 2026-10-28) + +Проверено по �нимкам разработчика (1400×1000 тёмна�, 640×1000, 640×480) и �воим: �ветла� тема (репертуар, ошибки), «Дебюты» при «Чёрные», диалог движка, ход движка, 804/803×900, 960×1050, диалог при 640×480, «Ошибки» и «Дебюты» при 640×1000, вход из панели фильтров. Снимки — `scratchpad/prep-design/*.png`. �е �н�то: выбранна� ошибка �о �трелками на до�ке (выбрать её можно только мышью — �м. �6). + +Общее: архитектура �крана, диалог, три вкладки, �пи�ок партий, движок, �топка и низкое окно — по дизайну; палитра отметок и пилюли — как в нотации, в обеих темах читают��. Замечани� ниже — по приоритету: **�** мешает читать и понимать данные, **Б** ра�ходит�� � визуальной �и�темой, **В** узкие окна. У каждого — правка. + +### �. Данные и понимание + +1. **Сводка — одно длинное предложение.** По�ле движка �трока цвета �тановила�ь �лишком длинной; при 960 и 804 она перено�ила�ь по�реди фразы («Ошибок в / дебюте: …», `w960.png`, `w804.png`), и втора� �трока читала�ь как нова� запи�ь. �ктуальна� правка — §3.5: `egui::Grid`, отдельные title/games � правовыравненным чи�лом, компактный score, �о�едние counts/percent � незави�имым измерением через реальный `Label` и `gap = 4`. Счётчики ошибок — цветные, в пор�дке `?! · ? · ??`; нулевые типы пропу�кают��, при в�ех нул�х о�таёт�� только «нет ошибок». Скрытие — last → opponents; score/errors не �крывают��, в �топке ошибки только на вкладке «Ошибки». +2. **Чи�ла в поло�е �чёта �пор�т � «Счётом».** В �троке «Белыми · 138» р�дом �то�т «78 %» (очки) и «75» внутри поло�ы (дол� побед белых); у чёрных внутри �ветлого �егмента �тоит дол� побед **�оперника** («Queen's Pawn Game · 56 % · [56]», `openings_black.png`). Два разных чи�ла в одной �чейке без подпи�и — главный и�точник непонимани� колонки «Счёт». Правка: в поло�е 56 точек чи�ел не ри�овать (`results_bar` � флагом без тек�та либо �во� узка� вер�и�); проценты — только в под�казке «+10 =1 −3». Поло�а о�таёт�� аб�олютной (Б �ветлый �лева, Ч тёмный �права), как на до�ке пои�ка. Заодно: при «мало партий» поло�а не приглушает�� (`painter_alpha` вычи�лен и выброшен) — ри�овать её � `gamma_multiply(0.5)` или не ри�овать вов�е. +3. **Лини� под до�кой нумерует чёрные ходы:** «1.e4 1…c5 2.Nf3 2…d6». �игде в программе так не пишут. Правка: `short_label` только дл� первого хода и дл� белых ходов; чёрные — голым SAN («1.e4 c5 2.Nf3 d6»). Та же лини� нужна в «Первые ходы» таблицы дебютов, где �ейча� формат таблицы lichess «1. e4 c5» (� пробелом по�ле номера) — приве�ти к `line_text`. +4. **«Первые ходы» нет на 1400×1000 при «Оба»** (`openings.png`): колонка «Цвет» 90 + «Дебют» ≥ 200 не о�тавл�ют 160 дл� ходов, и между «Дебют» и «ECO» пу�тота. Это именно те данные, ради которых владелец про�ил «в�егда � первыми ходами». Правка: «Цвет» — только значок `♙`/`♟` шириной 24 � под�казкой (�лово «Белыми» 11 раз подр�д — шум); минимум «Дебют» 180, «Первые ходы» 140; пор�док �крыти� как в §6. �льтернатива лучше, но дороже: вме�то колонки — �троки-заголовки «Белыми · 138» / «Чёрными · 133», как корни дерева. Также �окращение линии режет ход пополам и даёт двойное многоточие («…5 4. Bg2 Be7 5. …», `openings_black.png`): `shorten_middle` — по границам ходов и по измеренной ширине, без второго `truncate`. +5. **Им� дебюта в дереве «откатывает��»:** под «2…d6 Sicilian Defense: Modern Variations» �тоит «3.d4 Sicilian Defense» — таблица даёт менее точное им� глубже, и правило «показывать, когда мен�ет��» печатает его как новое. Правка: не показывать им�, е�ли оно — префик� имени родител� (�емей�тво без варианта); лучше — в `prep` �делать им� узла «липким» (�амое глубокое им� по пути), тогда и под�казка, и таблица дебютов �огла�уют��. +6. **Вкладка «Ошибки» без клавиатуры и без �трок.** Стрелки там ничего не выбирают (`keyboard` → только Enter), а щелчок ловит лишь подпи�ь «Позици�» / им� дебюта, не �трока (`egui::Grid` без ответа �троки). В «По дебютам» �чётчики ошибок �то�т на разной вы�оте — не �равнить. Правка: обе ча�ти — `TableBuilder` �о `striped`, `sense(click)` и выделением �троки, как дерево; клавиши ↑/↓/→/� по общему �пи�ку �трок (повтор�ющие�� + дебюты + ра�крытые партии), Enter — открыть партию. Это же да�т хук дл� �нимка выбранной ошибки (`CP_KEYS`). +7. **Четыре �троки одних и тех же чи�ел** на 1400 (`errors.png`): �водка (2 �троки) и �разу под ней в «Ошибках» «Белыми: … / Чёрными: …». Правка: во вкладке �троки цветов показывать только в �топке (там �водка их не не�ёт, §6); р�дом — только �трока �о�то�ни� «Ошибки найдены · Stockfish 19 · Бы�тро · 2 947 позиций · Точнее…». +8. **Колонка «Дебют» в дереве тер�ет ECO:** длинное им� забирает в�ю ширину, ECO обрезает�� до «··» («Nyezhmetdinov-Rossolimo Attack ··», `repertoire.png`). Правка: ECO кла�ть первым в `right_to_left`, им� — в о�таток � `truncate`. +9. Мелкое: «2947 позиций» без разделител� ты��ч (�тату�, диалог, прогре��) — `large_db::grouped`; «%» в таблице дебютов без под�казки (в дереве е�ть) — «Дол� от партий цветом; у варианта — от �емей�тва». + +### Б. Визуальна� �и�тема + +1. **«▾» �лева от «Ошибки найдены»** (в�е �нимки): в `right_to_left` кнопка параметров добавлена второй и в�тала левее подпи�и — выгл�дит как �ворачивалка. Правка: добавл�ть «▾» первой (окажет�� �права), чтобы �тату� о�тавал�� �лева от неё, как в §4.4. +2. **Три пор�дка цветов:** диалог «Оба · Белые · Чёрные», диалог движка «Белые · Чёрные · Оба», переключатель «Белые · Чёрные · Оба». Правка: везде «Белые · Чёрные · Оба». +3. **«🗙» у заголовка �пи�ка партий** — крупна� рамочна� кнопка т�желее заголовка. Правка: `widgets::small_close_button`, как в диалоге у пол� «Игрок» и у чипов. +4. **Поло�а �чёта в �ветлой теме** почти �ливает�� � фоном �троки (`light_rep.png`) — общее �вой�тво `results_bar`, не �того �крана; е�ли править п. �2 �воей вер�ией поло�ы — дать �ветлому �егменту обводку 1 px `weak_text_color` в �ветлой теме. +5. Глубина «Дебют: 10 ходов» при W < 760 превращает�� в голое «10» (`narrow640.png`), хот� в �троке о�таёт�� ~150 точек. Правка: выбирать подпи�ь по измеренной ширине («Дебют: 10 ходов» → «10 ходов» → «10 х.»), а не по порогу окна. + +### В. Узкие и низкие окна + +1. **Имена в �пи�ке партий уже `NAME_MIN` 110** при 640–804 («Вафин Рад…», «Конюшенко С…», `narrow640.png`, `w804.png`): Elo и «Дальше» о�тают��, имена ужимают�� до 82–95. Правка (как §3.10 и `board-search.md` §2.7): �начала �читать `player_w`; е�ли < 110 — пр�тать «Дальше», затем Elo (в �чейку имени �лабым), и только потом резать имена. +2. **640×480: дереву о�таёт�� 6 �трок** (`low640.png`) — минимум �пи�ка партий 4 �троки + 60 и дол� 35 %. Правка: при H < 600 минимум �пи�ка — 2 �троки, дол� 25 %; дерево получает ≈ 10 �трок. +3. В �топке над до�кой нет подпи�и «Ход белых · по�ле 2.Nf3» (`board_caption` не вызывает��, `w803.png`): добавить первой �трокой в колонку �права от до�ки. +4. «другие ходы (1)» на глубине обрезает�� в «другие ход…» при минимуме колонки 180 (`w804.png`): короче — «другие (1)». +5. Пороги 804/803 и 720 работают как задумано (`w804.png` — р�дом, `w803.png` — �топка; `low640.png` — до�ка по кнопке); диалоги при 640×480 помещают��. + +### Что принимаю из отклонений разработчика + +- «⤳» → «⇄» — да, ��нее. +- Им� дебюта в дереве только когда мен�ет�� отно�ительно родител� — да, � поправкой �5 (не показывать менее точное им�). +- «Первые ходы» �емей�тва — его позици� по таблице — да. +- Строки ошибок в �водке нет в �топке — да (§6 так и задумано). +- Строка ошибок в �водке про�тым тек�том — **нет**, �м. �1: `counts_text` уже е�ть, �то три �троки правки. +- Отложены: вход � �крана партии, мини-до�ка в под�казке, «показать в дереве», �ортировка таблицы дебютов — да; «Точнее…» только во вкладке «Ошибки», а не в �троке переключателей — да, �трока и так те�на�. +- �втопереход на вкладку «Ошибки» при запу�ке движка (в дизайне не было) — да, полезно. + +### �е проверено + +Выбранна� ошибка (�трелки �ыгранного/лучшего хода, �трока «… — лучше … · 0,0 → −1,2» под до�кой), «О�тановлено → Продолжить», «нет партий цветом», парти�, открыта� из отчёта («⬅ К подготовке»). Дл� �нимков нужна клавиатура во вкладке «Ошибки» (�6) или хук `CP_PREP_SELECT`. + +## Изменени� + +- 2026-10-28: перва� вер�и�. +- 2026-10-28: §12 — ревью реализации f02f140 (замечани� �/Б/В, прин�тые отклонени�, что не проверено). +- 2026-11-01: по тогдашним решени�м владельца книга переведена на ручной запу�к � прогре��ом/Stop и без ча�тичных результатов; движок — на автозапу�к по�ле по�троени� отчёта и по�ле �мены глубины/периода, без первого диалога и без �амоперезапу�ка по�ле Stop. Обновлены §0–6, §9–11; обща� вёр�тка не пере�матривала�ь. +- 2026-11-02: книжна� �верка полно�тью удалена из актуального проекта; предыдущий пункт о�тавлен как и�тори�. Диалог, �ценарии, контролы, дерево, �о�то�ни�, i18n и примечани� реализации приведены к �крану без неё. §3.5 дополнен �огла�ованной �еткой summary: отдельные title/games и counts/percent, незави�имое измерение через реальный `Label` � `gap = 4`, нулевые �о�то�ни�, last → opponents и ошибки только на вкладке «Ошибки» в �топке. Правила движка не изменены; задача 30 не закрывает��. diff --git a/docs/design/own-databases.md b/docs/design/own-databases.md new file mode 100644 index 0000000..5616e56 --- /dev/null +++ b/docs/design/own-databases.md @@ -0,0 +1,454 @@ +# Свои базы: �оздание, добавление, �охранение и удаление партий + +Стату�: проект дизайнера, 2026-10-24, **не утверждён**. О�нова — и��ледование аналитика `../research/own-databases.md` (ChessBase, наш код, критерии приёмки) и решени� владельца, перечи�ленные в §0. Пользователи — тренеры и ученики шахматной школы, не техниче�кие; требование владельца — «мак�имально пон�тно и коротко, без лишнего». + +Опирает�� на код: `apps/desktop/src/app.rs` (`confirm_dialog`, `pick_save`, `save_game`, `toast`), `game_view.rs` (`header`, меню ☰, `keyboard`, `GameSource`), `library.rs` (`shelf`, `db_card`, `compact_shelf`, `RemoveDatabase`), `large_db.rs` (таблица: `selected: Option` — выделение одной �троки, контек�тное меню �троки), `settings.rs` (`write_atomic`, `Settings.databases`), `settings_ui.rs` (вкладка «Интерфей�»). Св�занные проекты: `large-databases.md` (полка, таблица, §9.7 перечитывание), `narrow-windows.md` (компактна� полка, узка� шапка). + +Размеры — логиче�кие точки egui. Тек�ты даны по-ру��ки, в �кобках — англий�кий ключ `tr(...)`; где ключ очевиден из ру��кого, он опущен. + +## 0. Решени� владельца, на которые опирает�� проект + +1. **Каждый PGN на полке — «�вой»**, без переключател�. �ельз� пополн�ть только: базы, �качанные � Lichess/Chess.com (обновл�ют�� �ами и потер�ли бы добавленное), базы и архивы ChessBase (только чтение), PGN в у�таревшей кодировке (предлагает�� копи� в UTF-8). +2. **Запи�ь только по �вной команде.** «Сохранить» (Ctrl+S) замен�ет запи�ь партии в том PGN, откуда она открыта (атомарно, о�тальные запи�и побайтно те же). «Добавить в базу…» допи�ывает копию в выбранный PGN. «Удалить из базы» — из таблицы �воей базы, � подтверждением и отменой на не�колько �екунд. +3. **Уход из изменённой партии** �прашивает: главна� кнопка «Сохранить в «X»» (парти� из �воего PGN) или «Добавить в базу…»; «�е �охран�ть»; «Отмена». Esc — как �егодн�. +4. Править партию из любой базы и добавл�ть копию в другую — нормально (= «Save game as» ChessBase). +5. **Редактор данных партии** (Белые, Чёрные, Эло, Турнир, Ме�то, Дата, Тур, Результат, Комментатор; комментатор — из на�тройки «Ваше им�»): �ам при первом добавлении новой или в�тавленной партии; потом — ☰, щелчок по названию в шапке партии, клавиша. +6. **Проверка дублей** при добавлении (те же игроки, дата и ходы) → вопро�. +7. **Папка новых баз** — `Документы/ChessPenguin/`; при �оздании виден полный путь, папку можно �менить; карточка и её меню показывают, где файл («Показать в папке»). +8. Замена и удаление перепи�ывают файл целиком: дл� очень больших PGN — прогре�� и �овет ве�ти небольшую �вою базу (порог — §6.4). +9. Android о�таёт�� только дл� чтени�. + +## 1. Принципы + +1. **Парти� в�егда знает, где живёт.** Им� базы напи�ано в шапке партии, в то�те по�ле запи�и, на главной кнопке вопро�а при уходе. Слово «Сохранить» без имени базы в интерфей�е не в�тречает��. +2. **Два дей�тви�, два �лова.** «Сохранить в «Петров»» — замена �воей запи�и. «Добавить в базу…» — копи� в другую базу. Одна клавиша Ctrl+S делает то из двух, что возможно; Ctrl+Shift+S — в�егда выбор базы. +3. **Файл — вещь пользовател�.** Он лежит в «Документах», виден путь, е�ть «Показать в папке». Программа файлы не удал�ет — только запи�и в них. +4. **�ичего молча.** �ет авто�охранени�, нет запи�и без имени базы на кнопке, нет тихой перезапи�и при изменении файла другой программой. +5. **Чего нет — не ри�уем.** �епополн�емые базы не получают �ерых кнопок на полке; объ��нение по�вл�ет�� там, где человек пытает�� в них пи�ать (§5). + +## 2. Библиотека + +### 2.1. Точка входа «�ова� база…» + +Отдельна� карточка на полке р�дом � «+ Добавить базу», тем же контуром (190 × 64 → дл� коротких подпи�ей — ширина по тек�ту + 32, не меньше 150, как у `side_card_widths`): + +``` +│ Базы [♟ �ова� парти�][📋 В�тавить PGN][⚙] │ +│ ┌──────────────�┌──────────────�┌────────────�┌────────────�┌─────────────────────� │ +│ │🗄 Петров ││🗄 Мои партии ││+ Добавить ││✚ �ова� ││� Онлайн-партии │ │ +│ │ 12 партий ││ 48 партий ││ базу ││ база ││ Lichess · Chess.com│ │ +│ └──────────────┘└──────────────┘└────────────┘└────────────┘└─────────────────────┘ │ +``` + +- Подпи�ь `✚ New database` («✚ �ова� база»), tooltip: «Создать пу�тую базу — файл .pgn в папке Документы/ChessPenguin (Ctrl+Shift+N)». Контурна� карточка (`rect_stroke`), как у «+ Добавить базу». Глиф `✚` (U+271A) проверить в шрифтах egui (�то не �модзи); е�ли его нет — «🗄 �ова� база» (значок базы отличает карточку от «+ Добавить»). +- Разница «Добавить» и «�ова�» объ��н�ет�� под�казками, не тек�том на полке: «Добавить» — «Открыть PGN, ChessBase или архив»; «�ова�» — «Создать пу�тую базу». +- **Компактна� полка** (`narrow-windows.md` §2.5): ме�та под вторую контурную кнопку нет, по�тому «+» �тановит�� кнопкой-меню «+ ▾» � двум� пунктами: «Добавить базу… Ctrl+O» и «�ова� база… Ctrl+Shift+N». В полной полке — две карточки, в компактной — одно меню; других различий нет. +- Ещё две точки входа: пункт «�ова� база…» внутри диалога «Добавить в базу» (§3.3) и Ctrl+Shift+N в библиотеке. + +### 2.2. Диалог «�ова� база» + +`egui::Modal`, ширина 440. Един�твенное об�зательное поле — им�. + +``` +┌─ �ова� база ───────────────────────────────────────────────� +│ │ +│ �азвание [Петров ] │ +│ │ +│ Папка Документы/ChessPenguin [Изменить…] │ +│ Файл /home/roman/Документы/ChessPenguin/Петров.pgn │ � �лабым, truncate �лева +│ │ +│ [Создать] [Отмена] │ +└────────────────────────────────────────────────────────────┘ +``` + +- **�азвание** (`Name`): `TextEdit` � фоку�ом при открытии; под�казка в пу�том поле — «Петров, Мои партии, Сицилиан�ка�» (`Petrov, My games, Sicilian`). Ра�ширение `.pgn` добавл�ет�� �амо; е�ли человек напечатал «Петров.pgn», второй раз не добавл�ет��. Пробелы по кра�м убирают��. +- **Папка** (`Folder`): запомненна� папка новых баз (`Settings.new_database_dir`, по умолчанию `UserDirs::document_dir()/ChessPenguin`, без «Документов» — `home/ChessPenguin`). Показывает�� коротко: путь отно�ительно домашней папки («Документы/ChessPenguin»), полный — в �троке «Файл» и в tooltip. «Изменить…» — `rfd::FileDialog::pick_folder`; выбранна� папка �тановит�� запомненной. Папка �оздаёт�� при нажатии «Создать», не при открытии диалога. +- **Файл** (`File`): полный путь результата, обновл�ет�� при наборе. Это главна� гаранти� п. 7 решений: человек видит, что именно по�вит�� на ди�ке, до нажати� кнопки. +- **Проверка** (пока им� не годит�� — «Создать» неактивна, под полем �лабым тек�том причина): + - пу�то — без тек�та, про�то неактивна� кнопка; + - запрещённые знаки `/ \ : * ? " < > |` или им� из точек — «В названии нельз� и�пользовать / \ : * ? " < > |» (`A name cannot contain / \ : * ? " < > |`), кра�на� рамка пол�; + - файл уже �уще�твует — «Такой файл уже е�ть в �той папке» (`A file with this name is already in this folder`) и ��ылка-кнопка «Добавить его на полку» (`Add it to the shelf`): �уще�твующий PGN никогда не перезапи�ывает�� и не очищает��; + - така� же база уже на полке (тот же путь) — «Эта база уже на полке» и «Открыть». +- **Клавиши:** Enter — «Создать» (е�ли им� годит��), Esc — «Отмена». +- **По�ле �оздани�:** пу�той файл `Петров.pgn` (0 байт), карточка первой на полке (`touch_database`) и выбрана; �та база �тановит�� запомненным назначением дл� «Добавить в базу…» (`Settings.last_target`). То�т не нужен — карточка и пу�тое �о�то�ние таблицы говор�т в�ё. +- **Ошибки:** нет прав на папку / ди�к недо�тупен — тек�т под полем «�е удало�ь �оздать файл: <причина>» (`Could not create the file: {e}`), диалог о�таёт�� открытым, можно �менить папку. + +### 2.3. Пу�та� база + +В таблице вме�то �трок — по центру, как у «�ичего не найдено»: + +``` + В базе «Петров» пока нет партий. + + [♟ �ова� парти�] или откройте любую партию и выберите + «Добавить в базу…» (Ctrl+Shift+S) + + Файл: /home/roman/Документы/ChessPenguin/Петров.pgn +``` + +- `No games in “{name}� yet.` / `or open any game and choose “Add to database…� (Ctrl+Shift+S)` / `File: {path}`. +- «♟ �ова� парти�» зде�ь — то же `LibraryAction::NewGame`; нова� парти� без и�точника, и при первом Ctrl+S в диалоге «Добавить в базу» �та база уже выделена (она — `last_target`). Специального �о�то�ни� «нова� парти� в �той базе» не нужно. +- Шапка таблицы: «Петров · PGN, кодировка UTF-8 · 0 партий». Панель фильтров и переключатель — как у любой базы (§9 `large-databases.md`), ничего не пр�чет��. + +### 2.4. Карточка и её меню + +Карточка не мен�ет�� (190 × 64, 🗄, «12 партий»). Признака «�во�» нет — �во� кажда� PGN; у непополн�емых и так е�ть «🔒» (ChessBase) и «�» (онлайн). Tooltip карточки — путь, как �ейча�. + +Контек�тное меню (права� кнопка): + +``` +Показать в папке +Переименовать… � только пополн�емый PGN +Перечитать файл +────────────── +Убрать � полки +``` + +- **«Показать в папке»** (`Show in folder`) — открыть папку в файловом менеджере � выделенным файлом: Linux — D-Bus `org.freedesktop.FileManager1.ShowItems`, при неудаче `xdg-open <папка>`; Windows — `explorer /select,<путь>`; macOS — `open -R <путь>`. Е�ть у в�ех карточек, у которых файл на ме�те (и у ChessBase — там показывает�� `.cbh`). +- **«Переименовать…»** (`Rename…`) — маленький Modal � одним полем (им� без ра�ширени�), те же проверки, что в §2.2; переименовывает файл на ди�ке и путь на полке; открытые партии из �той базы получают новый путь и�точника. �едо�тупно дл� ChessBase, онлайн-баз, файла в другой кодировке, файла без прав. Можно отложить на �ледующую итерацию без ущерба — тогда переименовывать через «Показать в папке». +- **«Убрать � полки»** (`Remove from shelf`; �егодн� «Remove from list» — переименовать ключ) — файл о�таёт��. То�т: «База «Петров» убрана � полки. Файл о�тал��: Документы/ChessPenguin/Петров.pgn» (`“{name}� removed from the shelf. The file stays: {path}`), 6 �. Так человек, который хотел �тереть базу, узнаёт, что файл цел и где он. +- **Удалени� файла в программе нет.** Довод: безвозвратно, легко перепутать � «Убрать � полки», а файловый менеджер уже в одном щелчке («Показать в папке»). Е�ли владелец захочет — отдельна� команда «Удалить файл � ди�ка…» � подтверждением, где напечатан путь; не рекомендую в первой вер�ии. + +## 3. Экран партии + +### 3.1. Где парти� живёт + +Подзаголовок шапки (`subtitle`) начинает�� � базы, когда у партии е�ть и�точник: + +``` +│ ⬅ Библиотека │ Иванов — Петров • 1-0 � �айти в базе ▾ ⚙ │ +│ 🗄 Петров · № 13 · Первен�тво школы · Казань · 2026.10.18 │ +``` + +- Элемент `🗄 {name} · № {n}` �тавит�� первым и при нехватке ме�та �окращает�� по�ледним (им� базы важнее ме�та турнира: по нему пон�тно, куда уйдёт Ctrl+S). О�тальной подзаголовок — как �ейча�. Дл� непополн�емого и�точника тот же вид � его значком: «🔒 Mega Database 2026 · № 10234567», «� petrov (Lichess) · № 412». +- Парти� без и�точника (нова�, в�тавленна�) — �лемента базы нет; «•» в названии уже говорит, что е�ть не�охранённое. Пи�ать «не в базе» на каждом новом ходе — лишний шум. +- **�азвание кликабельно**: наведение — подчёркивание и tooltip «Данные партии (F2)» (`Game data (F2)`), щелчок — редактор §3.5. Это един�твенное ме�то шапки, где щелчок что-то открывает; других �крытых дей�твий у заголовка нет. +- По�ле добавлени� в базу подзаголовок мен�ет�� на новую базу и номер, то�т подтверждает: «Добавлено в «Петров» (№ 13)» (`Added to “{name}� (no. {n})`). Два и�точника правды о ме�тоположении, оба �вные. + +### 3.2. Сохранить и добавить: кнопки и клавиши + +�ижн�� панель ин�трументов: `� ◀ ▶ � · 🔃 ↩ ↪ · ☰ 💾 📋 · 📈`. Кнопка 💾 — одно дей�твие по контек�ту, подпи�ь в tooltip в�егда называет базу: + +| И�точник партии | Ctrl+S / 💾 | Ctrl+Shift+S | +| --- | --- | --- | +| пополн�емый PGN, парти� изменена | заменить запи�ь; то�т «Сохранено в «Петров»» (`Saved to “{name}�`) | «Добавить в базу…» (копи� в другую базу) | +| пополн�емый PGN, изменений нет | ничего не пи�ать; то�т «Изменений нет» (`No changes to save`) | то же | +| нет и�точника (нова�, в�тавленна�) или непополн�емый и�точник (ChessBase, онлайн, друга� кодировка, нет прав) | открыть «Добавить в базу…» (§3.3) | то же | + +- Tooltip 💾: «Сохранить в «Петров» (Ctrl+S)» / «Добавить в базу… (Ctrl+S)». Кнопка в�егда активна: человек нажал — получил либо запи�ь, либо ответ «изменений нет». +- Меню ☰ (�верху вниз): «Данные партии… F2» · «Сохранить в «Петров» Ctrl+S» (только когда и�точник пополн�емый) · «Добавить в базу… Ctrl+Shift+S» · разделитель · «Копировать PGN», «Копировать FEN», «Заметки о �овме�тимо�ти», перевод — как �ейча�. Пункт «Сохранить партию как…» из ☰ уходит: он живёт внутри «Добавить в базу» �трокой «Сохранить как файл…». В «Что нового»: «Ctrl+S теперь �охран�ет в базу; отдельный файл — Ctrl+Shift+S → «Сохранить как файл…»». +- Парти� из Mega/онлайн/книги: Ctrl+S �разу открывает выбор базы — без промежуточного «нельз�». Причина, почему и�ходна� база не в �пи�ке, видна в �амом диалоге (§5). + +### 3.3. Диалог «Добавить в базу» + +`egui::Modal`, ширина 440. Спи�ок — пополн�емые PGN в пор�дке полки; непополн�емые — в конце, �ерым, � причиной (§5): человек ищет «petrov (Lichess)», находит и �разу читает, почему туда нельз�. + +``` +┌─ Добавить в базу ──────────────────────────────────────────� +│ Иванов — Петров · 2026.10.18 │ � �лабым +│ │ +│ ▌Петров 12 партий Документы/… �│ � выделена (по�ледн�� и�пользованна�) +│ Мои партии 48 партий Документы/… │ +│ Сицилиан�ка� 6.Bg5 31 парти� Документы/… │ +│ petrov (Lichess) пополн�ет�� � Lichess �ама │ � �ерым +│ Mega Database 2026 ChessBase — только чтение │ � �ерым +│ Учебник кодировка windows-1251 · Сделать копию в UTF-8… │ +│ │ +│ ✚ �ова� база… │ +│ Сохранить как файл… │ +│ │ +│ [Добавить] [Отмена] │ +└────────────────────────────────────────────────────────────┘ +``` + +- Строка: им� (жирным), чи�ло партий (`{n} games`, �лабым), папка (�лабым, отно�ительно домашней, �окращает�� � «…» �лева). Вы�ота �троки 26. Выделение — `selectable_label` на в�ю ширину. +- **Выделена по умолчанию** по�ледн�� база, в которую добавл�ли (`Settings.last_target`); е�ли её нет на полке — перва� пополн�ема�. Enter = «Добавить» в выделенную. Двойной щелчок по �троке — то же. +- **Больше 8 �трок** — �пи�ок в `ScrollArea` вы�отой 8 × 26, над ним поле «�айти базу» (`Find a database`) � фоку�ом; набор фильтрует по под�троке имени; ↓/↑ ход�т по �трокам, Enter добавл�ет. При ≤ 8 �трок пол� нет и фоку� �разу на �пи�ке. +- **Серые �троки** — `add_enabled(false)`, вме�то �чётчика и папки — причина в одну �троку (§5, колонка «в �пи�ке баз»). Строка базы в другой кодировке — активна и ведёт в поток копии (§5.3); её тек�т: «кодировка windows-1251 · Сделать копию в UTF-8…». +- **«✚ �ова� база…»** открывает §2.2 поверх; по�ле �оздани� нова� база выделена в �пи�ке, и «Добавить» �нова под Enter — одного Enter до�таточно (`Create` → возврат в �пи�ок → Enter). Е�ли человек нажимает Enter в диалоге новой базы, а потом ещё раз — парти� уже в новой базе: «�ова� база, Enter, Enter». +- **«Сохранить как файл…»** (`Save as a file…`) — �егодн�шний `pick_save` → `save_game`: �к�порт одиночного PGN, и�точник партии не мен�ет��, файл на полку не в�таёт. Внизу �пи�ка, обычным тек�том, без выделени� жирным: �то запа�ной путь. +- **Пу�то** (нет ни одного пополн�емого PGN): вме�то �пи�ка — «Своих баз пока нет. База — �то файл .pgn в папке Документы/ChessPenguin; �оздайте первую.» (`No databases of your own yet. A database is a .pgn file in Documents/ChessPenguin — create the first one.`), под ним «✚ �ова� база…» как главна� кнопка и «Сохранить как файл…». +- Esc — «Отмена». Е�ли диалог открыт из вопро�а «Парти� изменена» (§3.4), отмена возвращает к вопро�у. + +**Что прои�ходит по�ле выбора** (в �том пор�дке): + +1. Е�ли парти� без и�точника и редактор данных дл� неё ещё не показывал�� — редактор §3.5 в режиме добавлени� (кнопка «Добавить в «Петров»»). Копии из других баз редактор не показывают: данные уже е�ть. +2. Проверка дубл� (§5.5) — вопро�, е�ли нашёл��. +3. Допи�ывание (`append`) → `mark_saved`, и�точник = (Петров, N) → то�т «Добавлено в «Петров» (№ 13)» → подзаголовок обновлён → `Library::reload(Петров)` � �охранением фильтров и выделени� (`large-databases.md` §9.7); е�ли Петров — выбранна� база, нова� �трока выделена и прокручена в центр (§4.1). +4. Е�ли добавление было ответом на вопро� при уходе — уход продолжает�� (`close_after_save`). + +### 3.4. Вопро� «Парти� изменена» + +Тот же `confirm_dialog` (Modal 380), три кнопки, Esc — как �егодн� (при уходе = «�е �охран�ть», при закрытии программы = «Отмена»). Мен�ют�� тек�ты и перва� кнопка: + +``` +И�точник — пополн�емый PGN И�точник — нет или непополн�емый +┌─ Парти� изменена ────────────────� ┌─ Парти� изменена ────────────────� +│ Иванов — Петров │ │ Иванов — Петров │ +│ Сохранить изменени� в базу │ │ База «petrov (Lichess)» не │ +│ «Петров»? │ │ мен�ет��. Добавить партию � │ +│ │ │ изменени�ми в �вою базу? │ +│ [Сохранить в «Петров»] [�е �охран�ть] [Отмена] [Добавить в базу…] [�е �охран�ть] [Отмена] +``` + +Тек�ты второго �луча� по и�точнику: + +| И�точник | Тек�т (`key`) | +| --- | --- | +| нова� / в�тавленна� парти� | «Добавить партию в �вою базу?» (`Add the game to one of your databases?`) | +| ChessBase / архив | «База «{name}» в формате ChessBase не мен�ет��. Добавить партию � изменени�ми в �вою базу?» (`“{name}� is a ChessBase database and is not changed. Add the game with your changes to one of your databases?`) | +| онлайн-база | «База «{name}» пополн�ет�� � Lichess �ама и не мен�ет��. Добавить партию � изменени�ми в �вою базу?» (`“{name}� fills itself from Lichess and is not changed. …`; дл� Chess.com — его им�) | +| друга� кодировка / нет прав | «Файл «{name}» нельз� дополнить (кодировка windows-1251). Добавить партию � изменени�ми в �вою базу?» (`The file “{name}� cannot be added to ({reason}). …`) | + +- «Сохранить в «Петров»» выполн�ет замену и уходит. Ошибка запи�и (§6) — о�таём�� в партии, вопро� закрыт, показан диалог ошибки. +- «Добавить в базу…» открывает §3.3; «Отмена» там — возврат к �тому вопро�у, не уход. +- Главна� кнопка — перва� �лева, как �егодн�; Enter её **не** нажимает (как �ейча�; запи�ь по Enter в вопро�е, который по�вил�� от Esc, — лишний ри�к). Это �ознательное отличие от о�тальных диалогов документа. + +### 3.5. Редактор «Данные партии» + +`egui::Modal`, ширина 460. Колонка подпи�ей `L` = ширина �амой длинной подпи�и в текущем �зыке (ru ≈ 96: «Комментатор»), пол� — о�таток. Об�зательных полей нет: «Готово» в�егда активна. + +``` +┌─ Данные партии ────────────────────────────────────────────� +│ Белые [Иванов Сергей ] Эло [1650] │ +│ Чёрные [Петров Иван ] Эло [1580] │ +│ Турнир [Первен�тво школы ] │ +│ Ме�то [Казань ] │ +│ Дата [2026.10.18 ] Тур [3 ] │ +│ Результат [1-0][½-½][0-1][ * ] │ +│ Комментатор [Роман Врубель ] │ +│ Ещё 3 тега: ECO, PlyCount, TimeControl │ � �лабым, не прав�т�� +│ │ +│ [Готово] [Отмена] │ +└────────────────────────────────────────────────────────────┘ +``` + +- Подпи�и: `White`, `Black`, `Elo`, `Event` («Турнир»), `Site` («Ме�то»), `Date`, `Round` («Тур»), `Result`, `Annotator` («Комментатор»). Пол� Эло — 56, Тур — 72, Дата — 112; о�тальные на в�ю ширину. +- **Фоку�** при открытии — «Белые», тек�т выделен. Tab — по пор�дку �верху вниз, �лева направо; Enter в любом поле = «Готово»; Esc = «Отмена». +- **Заполнители PGN** `?` и `????.??.??` показывают�� пу�тыми пол�ми; пу�тое поле запи�ывает�� обратно �тандартным заполнителем (`?`, `????.??.??`); Эло пу�тое — тег не пишет��, е�ли его не было; `Annotator` пу�той — тег не пишет��. +- **Дата**: принимает `2026.10.18`, `18.10.2026`, `2026-10-18`, `2026.10`, `2026`, `2026.??.18`, пу�то. �еполна� → `2026.10.??` / `2026.??.??`. При потере фоку�а показывает�� в виде PGN. Что не разобрало�ь — кра�на� рамка �наружи пол� и tooltip «Дата в виде 2026.10.18, 2026.10 или 2026; неизве�тное — ?» (`A date like 2026.10.18, 2026.10 or 2026; ? for unknown`); «Готово» при кра�ной рамке неактивна. Под�казка в пу�том поле: «ГГГГ.ММ.ДД» (`YYYY.MM.DD`). +- **Эло**: только цифры, до 4 знаков; пу�то — нет Эло. +- **Результат**: четыре кнопки-переключател�, одна нажата (как §3.3 `large-databases.md`: заливка и жирный). Мен�ет `Result` и результат документа вме�те (`set_result`) — тег и терминатор ходов не ра�ход�т��. +- **Комментатор**: предзаполнен из «Ваше им�» (§7), когда тег пу�т; иначе — как в партии. +- **�ова� парти�** (без и�точника, в�е теги — заполнители): «Дата» предзаполнена �егодн�шней. В�тавленна� парти� — как е�ть. +- **«Ещё N тегов: …»** (`{n} more tags: {list}`) — одной �лабой �трокой, без правки; �крыта, когда других тегов нет. Так видно, что ECO/ча�ы не потер�ют��, и нет �облазна �делать редактор «на в�е теги». +- **Режимы кнопки**: открыт по F2 / из ☰ / щелчком по названию — «Готово» (`Done`): правки ложат�� в документ (`set_tag`, `unsaved_meta`), в шапке по�вл�ет�� «•», �охран�ет Ctrl+S. Открыт в потоке добавлени� (§3.3, шаг 1) — кнопка «Добавить в «Петров»» (`Add to “{name}�`), «Отмена» прерывает добавление, парти� о�таёт�� изменённой и на �кране. Заголовок диалога в �том режиме — «Данные партии → «Петров»». +- ECO автоматиче�ки не �тавит�� (вопро� 6 аналитика — не в первой вер�ии). + +## 4. Таблица партий + +### 4.1. Добавленна� парти� + +- По�ле добавлени� выбранна� база перечитывает�� (§9.7). Е�ли �то база-назначение — нова� �трока выделена и прокручена в центр (`reveal`), фильтры не �бра�ывают��; е�ли из-за фильтра �трока не видна — �чётчик «N партий» выро�, а то�т уже назвал номер. Е�ли выбрана друга� база — ничего не прыгает, карточка назначени� показывает новое чи�ло. +- Возврат «⬅ Библиотека» из партии, добавленной в другую базу, ведёт туда, откуда парти� открыта (�трока и�точника о�таёт�� выделенной, как �егодн�). База-назначение — на карточке � новым чи�лом партий; то�т �казал, куда ушла копи�. + +### 4.2. Дей�тви� над �трокой + +Контек�тное меню �троки (�ейча� — только «Отметить про�мотренной»): + +``` +Открыть Enter +Данные партии… F2 +Добавить в базу… Ctrl+Shift+S +────────────── +Отметить про�мотренной +────────────── +Удалить из базы… Delete � только пополн�емый PGN +``` + +- **«Данные партии…»** из таблицы = открыть партию и �разу редактор §3.5 («Готово» → «•» → Ctrl+S). Одно поведение редактора во в�ём приложении; правка «на ме�те в таблице» без открыти� партии — не нужна. +- **«Добавить в базу…»** дл� �троки — тот же диалог §3.3; дл� неизменённой партии из PGN в файл пишет�� и�ходный тек�т запи�и (`raw_text`), не нормализованный (аналитик §3.3). +- **Множе�твенное выделение** в таблице �ейча� нет (`selected: Option`). Перва� вер�и� — одна парти� за раз. «Добавить выбранные (12) в базу…» и удаление не�кольких — �ледующа� итераци� вме�те � Shift-щелчком/Ctrl-щелчком; к диалогу §3.3 добавит�� только подзаголовок «12 партий» и прогре��. Тематиче�ка� база (путь 3 в §9) в первой вер�ии �обирает�� по одной партии из таблицы пои�ка по позиции — �то терпимо дл� де��тков партий, не дл� �отен; �казать владельцу пр�мо. + +### 4.3. Удаление партии + +До�тупно у �троки пополн�емого PGN: клавиша Delete (фоку� в таблице, не в поле) и пункт меню. У непополн�емой базы Delete даёт то�т � причиной из §5 («База «Mega…» — ChessBase, только чтение»), пункта в меню нет. + +``` +┌─ Удалить партию из базы? ──────────────────────────────� +│ Иванов — Петров · 2026.10.18 · № 13 │ +│ Из файла «Петров.pgn» будет удалена одна запи�ь. │ +│ Другие базы не затрагивают��. │ +│ │ +│ [Удалить] [Отмена] │ +└─────────────────────────────────────────────────────────┘ +``` + +- `Delete the game from the database?` / `One record will be removed from the file “{file}�. Other databases are not affected.` Enter — «Удалить», Esc — «Отмена». Enter допу�тим, потому что е�ть отмена. +- По�ле удалени�: �трока и�чезает, выделение — на �ледующую (по�ледн�� удалена — на предыдущую), файл перепи�ан, карточка «11 партий». �омера по�ле удалённой �двигают�� на один — как в любом PGN. +- **То�т � отменой**, 6 � (пауза при наведении): «Парти� удалена из «Петров» [Отменить]» (`Game deleted from “{name}�` / `Undo`). Ctrl+Z в библиотеке, пока то�т виден, — то же, что кнопка. Отмена в�тавл�ет �охранённые байты запи�и на прежнее ме�то — файл побайтно прежний, �трока �нова выделена. Это един�твенный �лучай, когда у то�та е�ть кнопка; штатный то�т о�таёт�� без кнопок. +- **Открытые партии из �той базы** («за» �правочником, `previous_games`): индек�ы по�ле удалённой уменьшают�� на один; удалённа� парти�, е�ли она открыта, тер�ет и�точник (�тановит�� «без базы»; Ctrl+S дл� неё → «Добавить в базу…»). Решает разработчик, дизайн фик�ирует только видимое: така� парти� в шапке без «🗄 …». +- Удаление, когда файл изменил�� на ди�ке — §6.2. + +## 5. �епополн�емые и�точники + +Три �луча�, одни и те же �лова во в�ех ме�тах. «В �пи�ке баз» — �ера� �трока §3.3; «на полке» — tooltip карточки и перва� �трока её меню (неактивна�, �лабым); «при попытке» — то�т на Delete в таблице и тек�т вопро�а §3.4. + +| Случай | В �пи�ке баз (одна �трока) | �а полке и при попытке | +| --- | --- | --- | +| Lichess / Chess.com (`online::is_online`) | «пополн�ет�� � Lichess �ама» (`fills itself from Lichess`) | «База пополн�ет�� � Lichess �ама: добавленные вручную партии пропали бы при обновлении. Добавл�йте партии в �вою базу.» (`This database fills itself from Lichess: games added by hand would be lost at the next update. Add games to a database of your own.`) | +| ChessBase (`.cbh`, `.cbv`), архивы | «ChessBase — только чтение» (`ChessBase — read only`); дл� архива «архив — только чтение» (`archive — read only`) | «База в формате ChessBase: ChessPenguin её читает, но не мен�ет. Добавл�йте партии в �вою базу (PGN).» (`A ChessBase database: ChessPenguin reads it but does not change it. Add games to a database of your own (PGN).`) | +| PGN в другой кодировке (`detected_encoding` ≠ UTF-8/ASCII или включён ремонт букв) | «кодировка windows-1251 · Сделать копию в UTF-8…» (`{encoding} encoding · Make a UTF-8 copy…`) | «Файл в кодировке windows-1251. Чтобы дополн�ть его, нужна копи� в UTF-8 — программа �делает её р�дом, и�ходный файл не изменит��.» (`The file is in {encoding}. To add games it needs a UTF-8 copy — made next to it, the original is not changed.`) | +| нет прав на запи�ь / файл только дл� чтени� | «нет прав на запи�ь» (`no permission to write`) | «�ет прав на запи�ь в файл {path}.» | + +### 5.3. Копи� в UTF-8 + +�ажатие «Сделать копию в UTF-8…» (в �пи�ке баз или в меню карточки): + +``` +┌─ Копи� в UTF-8 ─────────────────────────────────────────────� +│ Файл «Учебник.pgn» в кодировке windows-1251. │ +│ Будет �оздана копи� «Учебник (UTF-8).pgn» в той же папке │ +│ �о в�еми 312 парти�ми. И�ходный файл не изменит��. │ +│ │ +│ [Создать копию] [Отмена] │ +└─────────────────────────────────────────────────────────────┘ +``` + +- `“{file}� is in {encoding}.` / `A copy “{copy}� with all {n} games will be made in the same folder. The original file is not changed.` Е�ли «Учебник (UTF-8).pgn» уже е�ть — «(UTF-8 2)». Е�ли папка и�ходного файла не пишет�� — копи� идёт в папку новых баз, и �трока «в той же папке» замен�ет�� полным путём. +- Копи� �оздаёт�� из `raw_text` в�ех запи�ей (аналитик §3.7), в�таёт на полку **�разу по�ле** и�ходной карточки и �тановит�� выбранной; и�ходна� о�таёт��. Е�ли копию запро�или из диалога «Добавить в базу» — по�ле �оздани� копи� выделена в �пи�ке, Enter добавл�ет. Прогре�� — по правилу §6.4 (дольше 300 м�). + +## 5.5. Дубль + +Провер�ет�� перед допи�ыванием: �реди запи�ей базы-назначени� � теми же `White`, `Black`, `Date` (по�ле `fold`, `?` �читает�� равным `?`) ищет�� запи�ь � той же по�ледовательно�тью ходов о�новной линии (SAN по�ле разбора; комментарии, варианты и NAG не �равнивают�� — �то одна и та же парти� � разными пометками). + +``` +┌─ Така� парти� уже е�ть ────────────────────────────────────� +│ В базе «Петров» № 7: Иванов — Петров · 2026.10.18 │ +│ Те же игроки, дата и ходы. │ +│ │ +│ [Заменить № 7] [Добавить как новую] [Отмена] │ +└────────────────────────────────────────────────────────────┘ +``` + +- `This game is already there` / `In “{name}�, no. {n}: {title}` / `Same players, date and moves.` / `Replace no. {n}` / `Add as a new game` / `Cancel`. +- **Предложение дизайнера — «Заменить № 7» вме�то «Открыть �уще�твующую».** Типичный �лучай дубл� у тренера: парти� ученика уже лежит в «Петрове», он открыл её копию из онлайн-базы, прокомментировал и добавл�ет �нова. Ему нужна одна запи�ь � комментари�ми, а не втора� и не переход к �тарой (при котором ещё и �про�или бы про не�охранённую текущую). Замена — та же атомарна� перезапи�ь §6; по�ле неё и�точник партии = (Петров, 7). Esc — «Отмена». Главной кнопки нет: Enter зде�ь ничего не делает — выбор о�мы�ленный, пу�ть будет щелчком или Tab. +- Е�ли дублей не�колько — показывает�� первый по номеру, в тек�те «и ещё 1 така� же». +- При проверке на больших базах-назначени�х (де��тки ты��ч партий) �равнение идёт по каталогу имён и разбирает только кандидатов; на обычных �воих базах — мгновенно. + +## 6. Ошибки, изменение файла, большие файлы + +В�е ошибки запи�и — `egui::Modal` 420, не то�т: путь и причину надо у�петь прочитать. Документ по�ле любой ошибки о�таёт�� изменённым («•» на ме�те), ничто не тер�ет��. + +### 6.1. Запи�ь не удала�ь + +``` +┌─ �е удало�ь �охранить ─────────────────────────────────────� +│ База «Петров»: Документы/ChessPenguin/Петров.pgn │ +│ �ет прав на запи�ь в файл. � причина про�тыми �ловами │ +│ Парти� о�тала�ь на �кране, изменени� не потер�ны. │ +│ │ +│ [Повторить] [Добавить в другую базу…] [Закрыть] │ +└────────────────────────────────────────────────────────────┘ +``` + +- `Could not save` / `The game stays on screen, your changes are kept.` / `Retry` / `Add to another database…` / `Close`. Причины: «�ет прав на запи�ь в файл» (`No permission to write to the file`), «Файл базы не найден — его переме�тили или удалили» (`The database file was not found — it was moved or deleted`), «�а ди�ке не хватает ме�та» (`Not enough space on the disk`; файл не повреждён — запи�ь шла во временный файл), иное — тек�т ошибки ОС под �ворачиваемым «Подробно�ти». +- Е�ли �то было ответом на вопро� при уходе — уход отменён, о�таём�� в партии. + +### 6.2. Файл изменил�� на ди�ке + +Перед заменой и удалением провер�ет�� `fingerprint` (размер и врем�). Ра�хождение: + +``` +┌─ База «Петров» изменила�ь ─────────────────────────────────� +│ Файл изменила друга� программа или ещё одна копи� │ +│ ChessPenguin. Чтобы ничего не потер�ть, парти� будет │ +│ добавлена в конец базы как нова�, а �пи�ок перечитан. │ +│ │ +│ [Добавить как новую] [Отмена] │ +└────────────────────────────────────────────────────────────┘ +``` + +`“{name}� has changed on disk` / `Another program, or another ChessPenguin window, changed the file. To lose nothing, the game will be added to the end of the database as a new one and the list reread.` Дл� удалени�: «…Спи�ок будет перечитан; проверьте и удалите �нова.» � одной кнопкой «Перечитать» (`Reread`). Запи�ь «в�лепую» в изменённый файл не предлагает�� никогда. + +### 6.3. Карточка «файл не найден» + +Парти� открыта, файл базы удалён/перемещён → Ctrl+S даёт §6.1 � причиной «не найден»; на полке — �уще�твующа� карточка «файл не найден» и «Указать новое ра�положение…» (`large-databases.md` §4.4). По�ле указани� новой папки Ctrl+S �нова работает (путь и�точника обновл�ет�� вме�те � карточкой). + +### 6.4. Большие файлы: прогре�� и �овет + +- **Порог** — `BIG_REWRITE_BYTES = 50 МБ` (одна кон�танта; архив РШШ на 81 МБ попадает, учебники и �вои базы — нет). Отно�ит�� к замене и удалению (перепи�ывают ве�ь файл); допи�ывание в конец не перепи�ывает файл и под порог не попадает. +- **Совет** — один раз на базу за �еан�, при первой замене/удалении в файле больше порога: + +``` +┌─ База больша� ─────────────────────────────────────────────� +│ «Гран-при РШШ» — 81 МБ, 33 640 партий. Сохран�ть в неё │ +│ можно, но каждое �охранение перепи�ывает ве�ь файл. │ +│ Удобнее держать �вои партии в небольшой базе. │ +│ │ +│ [Сохранить в «Гран-при РШШ»] [Добавить в другую базу…] [Отмена] +└────────────────────────────────────────────────────────────┘ +``` + +`A large database` / `“{name}� is {size}, {n} games. Saving into it works, but every save rewrites the whole file. A small database of your own is handier.` Главна� — в�ё же «Сохранить»: человек �вно открыл партию от�юда и нажал Ctrl+S; �овет не должен выгл�деть запретом. + +- **Прогре��** — по общему правилу приложени�: е�ли запи�ь длит�� дольше 300 м�, поверх окна Modal «Сохран�ю в «Гран-при РШШ»… ▓▓▓▓▓░░░ 62 %» (`Saving to “{name}�…`) без кнопки отмены (запи�ь атомарна и коротка; отмена по�реди `rename` бе��мы�ленна). Запи�ь идёт в фоновом потоке, интерфей� не замирает. Дл� копии в UTF-8 — то же окно «Создаю копию…». + +## 7. �а�тройки + +Вкладка «Интерфей�», новый блок под �зыком и темой — «Свои базы» (`Your databases`): + +``` +Свои базы +Ваше им� [Роман Врубель ] � Комментатор в ваших парти�х +Папка новых баз Документы/ChessPenguin [Изменить…] +``` + +- `Your name` — tooltip/подпи�ь �лабым «Запи�ывает�� комментатором (Annotator) в партии, которые вы добавл�ете» (`Written as the annotator of the games you add`). Пу�то — тег не пишет��. +- `Folder for new databases` — та же папка, что в §2.2; «Изменить…» — `pick_folder`. Полный путь — в tooltip. +- Хранение: `Settings.your_name: String`, `Settings.new_database_dir: Option` (None = по умолчанию), `Settings.last_target: Option`. + +## 8. Клавиатура + +| Клавиша | Где | Дей�твие | Сегодн� | +| --- | --- | --- | --- | +| Ctrl+S | парти� | «Сохранить в «X»» (замена) или, когда замена невозможна, «Добавить в базу…» | «Сохранить как…» — **�мы�л мен�ет��**, �казать в «Что нового» | +| Ctrl+Shift+S | парти�, таблица (выделенна� �трока) | «Добавить в базу…» в�егда (в нём же «Сохранить как файл…») | �вободна | +| F2 | парти�; таблица (выделенна� �трока) | «Данные партии…» (из таблицы — открыть партию и редактор) | �вободна. Как в ChessBase и в проводниках; на macOS без fn F2 — �рко�ть, по�тому там же работает ⌘I (`Modifiers::COMMAND`+I, только macOS); в меню показывать клавишу текущей платформы | +| Ctrl+Shift+N | библиотека | «�ова� база…» | �вободна (Ctrl+N — нова� парти�, Ctrl+O — добавить базу) | +| Delete | таблица, фоку� не в поле | «Удалить из базы…» (у непополн�емой — то�т � причиной) | �вободна; в пол�х Delete о�таёт�� редактированием (`egui_wants_keyboard_input`) | +| Ctrl+Z | библиотека, пока виден то�т удалени� | отменить удаление | �вободна в библиотеке (в партии — undo хода, без изменений) | +| Enter | диалоги §2.2, §3.3, §3.5, §4.3 | главна� кнопка | — | +| Enter | вопро� «Парти� изменена» | ничего (как �егодн�) | — | +| Esc | в�е новые диалоги | «Отмена»; из «Добавить в базу», открытого вопро�ом при уходе, — назад к вопро�у | �емантика Esc в вопро�е при уходе не мен�ет�� | + +Проверено по `game_view.rs::keyboard()`: зан�ты Ctrl+Z/Y/Shift+Z, Ctrl+Shift+C, Ctrl+S, Ctrl+W, Ctrl+Shift+F, Ctrl+Shift+T, Shift+A, Shift+↑/↓, �трелки, Home/End, F, L, Esc; в библиотеке — Ctrl+O, Ctrl+N, Ctrl+,, Ctrl+F, Ctrl+B, Ctrl+Shift+Backspace, Ctrl+Backspace, Esc, �трелки, PgUp/PgDn, Enter. Конфликтов у новых �очетаний нет. Таблицу клавиш в README дополнить �троками «Ctrl+S �охранить в базу · Ctrl+Shift+S добавить в базу · F2 данные партии · Ctrl+Shift+N нова� база · Delete удалить партию». + +## 9. Пути пользовател� + +1. **Тренер запи�ывает партию ученика по�ле тура.** Полка → «♟ �ова� парти�» → ходы → Ctrl+S → «Добавить в базу» � выделенным «Петров» (по�леднее назначение) → Enter → «Данные партии → «Петров»» (дата �егодн�, комментатор — тренер) → имена, тур, результат → Enter → то�т «Добавлено в «Петров» (№ 13)», подзаголовок «🗄 Петров · № 13». Поправил ход → Ctrl+S → «Сохранено в «Петров»». В�его два диалога, оба закрывают�� Enter. +2. **Комментирует партию ученика � Lichess в «Петров».** Открыл партию из «petrov (Lichess)» → варианты, пометки → Ctrl+S → �пи�ок баз («petrov (Lichess)» �ерым: «пополн�ет�� � Lichess �ама») → «Петров» → Enter → редактора нет (данные е�ть) → то�т → парти� теперь «🗄 Петров · № 14»; онлайн-база побайтно прежн��. Е�ли �ту же партию уже добавл�ли — вопро� §5.5, «Заменить № 7». +3. **Тематиче�ка� база по дебюту.** «✚ �ова� база» → «Сицилиан�ка� 6.Bg5» → Enter → карточка пу�та�. В большой базе — пои�к по позиции → в таблице на �троке Ctrl+Shift+S → Enter (нова� база уже выделена) — по одной партии; де��тки партий за минуту, �отни — ждут множе�твенного выделени� (§4.2). +4. **И�править опечатку в фамилии.** Открыл партию из «Петров» → щёлкнул название (или F2) → поправил → Enter («Готово», в шапке «•») → Ctrl+S → «Сохранено в «Петров»». Из таблицы: �трока → F2 → то же. +5. **Удалить лишнюю партию.** В таблице «Петров» �трока → Delete → «Удалить партию из базы?» → Enter → �трока и�чезла, то�т «Парти� удалена из «Петров» [Отменить]». Передумал — «Отменить» или Ctrl+Z в течение 6 �: файл и �трока на ме�те. +6. **Отдать базу ученику.** Карточка → права� кнопка → «Показать в папке» → файл `Петров.pgn` в «Документах» → отправить ме��енджером; на телефоне открывает�� в ChessPenguin дл� Android только дл� чтени�. + +## 10. Android + +Сво� база — обычный PGN; в Android-приложении открывает�� как любой файл, без признака «�во�», без запи�и (решение 16). В �том документе больше ничего дл� Android нет. + +## 11. Что �троит разработчик (компоненты) + +Ядро (`chess-core` / `chess-import`; критерии приёмки — у аналитика §4): + +1. `PgnDatabase::append(record)`, `replace(index, record)`, `delete(index)` → `remove`/`insert_raw(index, bytes)` дл� отмены — атомарно через tmp + `sync_all` + `rename`; `write_atomic` дополнить `sync_all`; окончани� �трок и `\n\n` по §3.7 аналитика. +2. `fingerprint`/`source_changed()` перед заменой и удалением; `Writable` — перечи�ление причин непополн�емо�ти (`Online`, `ChessBase`, `Archive`, `Encoding(name)`, `NoPermission`) � тек�тами §5. +3. Копи� в UTF-8 из `raw_text` в�ех запи�ей; пои�к дубл� (кандидаты по White/Black/Date, �равнение SAN о�новной линии). +4. `Game::set_tag`/`set_result` — уже е�ть; разбор дат из §3.5; `your_name` → `Annotator`. + +Приложение (`apps/desktop`): + +5. Полка: карточка «✚ �ова� база» и меню «+ ▾» в компактной полке; `LibraryAction::NewDatabase`; меню карточки: «Показать в папке» (D-Bus/`xdg-open`, `explorer /select,`, `open -R`), «Переименовать…», «Убрать � полки» � то�том-путём; пу�тое �о�то�ние базы §2.3. +6. Диалоги (`egui::Modal`): «�ова� база» §2.2, «Добавить в базу» §3.3 (�пи�ок, пои�к при > 8, �ерые �троки), «Данные партии» §3.5 (два режима кнопки), «Удалить партию» §4.3, «Така� парти� уже е�ть» §5.5, «Копи� в UTF-8» §5.3, ошибки §6.1–6.2, «База больша�» §6.4, прогре�� запи�и; `confirm_dialog` — тек�ты и кнопки §3.4 � возвратом из отменённого выбора базы. +7. Экран партии: кнопка 💾 и пункты ☰ §3.2; �лемент `🗄 {name} · № {n}` в `subtitle` � приоритетом �окращени�; кликабельное название → редактор; `GameAction::Save`, `AddToDatabase`, `EditGameData`; по�ле добавлени� — `source = (target, n)`, `mark_saved`, `Library::reload(target)` � `reveal`. +8. Таблица (`large_db.rs`): контек�тное меню �троки §4.2; Delete/F2/Ctrl+Shift+S при фоку�е в таблице; выделение по�ле удалени�; то�т � кнопкой «Отменить» (новый вид то�та, 6 �, пауза при наведении) и Ctrl+Z; �двиг индек�ов открытых партий и потер� и�точника у удалённой. +9. �а�тройки: `your_name`, `new_database_dir`, `last_target`; блок «Свои базы» во вкладке «Интерфей�» §7. +10. README: таблица клавиш §8; «Что нового»: �мена �мы�ла Ctrl+S. + +## 12. Открытые вопро�ы владельцу + +1. **Дубль: «Заменить № 7» вме�то «Открыть �уще�твующую»** (§5.5) — от�тупление от перечи�ленных владельцем вариантов; довод — реальный �лучай тренера и от�ут�твие второго шага � вопро�ом про не�охранённую партию. +2. **Удаление файла базы в программе** — предлагаю не делать (§2.4): е�ть «Показать в папке». +3. **Множе�твенное выделение** — не в первой вер�ии (его нет в таблице); тематиче�кие базы на �отни партий ждут �ледующей итерации (§4.2). +4. **«Переименовать…»** на карточке — дёшево, но можно отложить (§2.4). +5. **Порог 50 МБ** дл� �овета о большой базе (§6.4) — подобран по архиву РШШ; разработчик может �корректировать по замеру времени перезапи�и (ориентир — �овет там, где перезапи�ь дольше ~1 �). diff --git a/docs/design/paste-variation.md b/docs/design/paste-variation.md new file mode 100644 index 0000000..13b5b19 --- /dev/null +++ b/docs/design/paste-variation.md @@ -0,0 +1,206 @@ +# В�тавка варианта из буфера обмена + +Стату�: проект дизайнера, 2026-10-25, **не утверждён**. Требовани� — `docs/research/paste-variation.md` (аналитик; правила разбора §4.2, ме�то в�тавки §4.3, что в�тавл�ет�� §4.4, критерии приёмки §6). Этот документ отвечает на вопро� «как �то выгл�дит и что видит пользователь»; правила разбора и пои�ка ме�та не повтор�ют��, на них даны ��ылки. Где проект ра�ходит�� � и��ледованием — §9. + +Опирает�� на код: `notation.rs` (меню хода `resp.context_menu`, блок варианта, `read_only`), `game_view.rs` (`keyboard`, `insert_preview` — образец «+ Добавить как вариант», `toolbar` → меню ☰, `GameAction::Toast`), `app.rs` (`paste_pgn`, `open_pgn_text`, то�т `TOAST`). Документы: `user-comments.md` §5.1 (меню хода), `own-databases.md` §3.4 (вопро�ы), `narrow-windows.md`. Снимок `dev2/ef_var.png` — вариант из книжной партии �о ��ылкой на и�точник в конце («1/2-1/2, Radjabov Teimour (AZE) 2752 - Dominguez…»): так в нашей нотации уже выгл�дит то, что получит�� по�ле в�тавки. + +Размеры — логиче�кие точки egui. Тек�ты — по-ру��ки, в �кобках англий�кий ключ `tr(...)`; �уще�твующие помечены «(е�ть)». + +## 0. Главное + +1. **Ctrl+V на �кране партии** и пункт меню хода «В�тавить вариант из буфера». Кнопки на панели нет. +2. **Без окна в обычном �лучае.** Вариант в�таёт �разу, кур�ор — на его первый ход, нотаци� прокручена к нему, то�т называет, что и куда в�тавлено, и напоминает Ctrl+Z. Один шаг отмены. +3. **Один вопро�** — только когда вариант в�таёт **не там, где пользователь �тоит** (раньше выбранного хода или в другой ветке): «В�тавить вариант раньше?». +4. **Отказы — то�том**, парти� не мен�ет��: нет ходов, ход невозможен, «парти� �юда не подходит», «�ти ходы уже е�ть». +5. **И�точник** — комментарий в конце варианта, как в образце ChessBase у владельца: «0-1 Mellado Trivino,J (2430) – Garcia Albarracin,F (2305), ESP-ch Torrevieja 1997 (3)». + +## 1. Точки входа + +| Где | Подпи�ь | Клавиша | Когда нет | +|---|---|---|---| +| �кран партии | — | **Ctrl+V** | фоку� в поле ввода (редактор комментари�, «Данные партии») — там �то обычна� в�тавка тек�та; режим игры и тренировки | +| меню хода (правый щелчок) | «В�тавить вариант из буфера» (`Paste a line from the clipboard`), �права �лабым `Ctrl+V` (`shortcut_text`) | — | меню в игре и тренировке нет вов�е (`read_only`) | +| меню ☰ | «В�тавить вариант из буфера (Ctrl+V)» (`Paste a line from the clipboard (Ctrl+V)`) — �разу по�ле «Копировать FEN» (е�ть) | — | — | + +- Под�казка пункта меню хода (при наведении): «Ходы или парти� PGN из буфера — вариантом � того ме�та, где они ра�ход�т�� � �той партией» (`Moves or a PGN game from the clipboard, as a variation from where they part from this game`). +- **Ctrl+V �вободна** на �кране партии (`game_view.rs` `keyboard`: зан�ты Ctrl+Z/Y, Ctrl+Shift+Z/C/S/F/T, Ctrl+S, Ctrl+W, Ctrl+1…6, F2). Разработчику: egui превращает Ctrl+V в �обытие `Event::Paste(text)`, а не в нажатие клавиши, — ловить его в `keyboard`, когда `!egui_wants_keyboard_input()`; тек�т буфера брать из �обыти� (а при вызове из меню — `arboard`, как `paste_pgn`). +- Пункт в меню хода **в�егда активен**: читать буфер при каждом открытии меню нельз� (на Wayland �то медленно и может �про�ить разрешение); пу�той буфер — ответ то�том §4. + +### 1.1. Меню хода целиком + +Пункты без значков, как �ейча� в меню хода: значок у одного-двух пунктов �двигает их тек�т отно�ительно о�тальных. Пор�док — от правок �того хода к дей�тви�м над линией и к новым �кранам: + +``` +┌───────────────────────────────────────────────� +│ Комментарий… Enter │ (е�ть) +│ Удалить комментарий │ (е�ть, е�ли е�ть комментарий) +│ ! ? !! ?? !? ?! │ (е�ть) +│ = ∞ ⩲ ⩱ ± ∓ +− −+ │ (е�ть) +│ ───────────────────────────────────────────── │ +│ Комментарий в начале партии… │ (е�ть, у первого хода) +│ ───────────────────────────────────────────── │ +│ В�тавить вариант из буфера Ctrl+V │ �ОВОЕ +│ Сделать главным продолжением │ (е�ть, у варианта) +│ Удалить ход и продолжение │ (е�ть) +│ ───────────────────────────────────────────── │ +│ Играть от�юда � Maia… Ctrl+G │ play-from-position.md +│ Учить дебют до �того хода прохождений: 4│ opening-trainer.md +└───────────────────────────────────────────────┘ +``` + +Правые подпи�и (`Enter`, `Ctrl+V`, `Ctrl+G`, «прохождений: 4») — одним �лабым �тилем `shortcut_text`, прижаты вправо одной колонкой. + +## 2. Что видит пользователь: обычный �лучай + +Правый щелчок делает ход текущим (е�ть). Дальше — без окон: + +**До** (кур�ор на 5…Bf5, в буфере парти� Mellado – Garcia): + +``` + 4 Nxe4 Nf6 + 5 f3 ▌Bf5� � кур�ор + 6 Ng3 … +``` + +**По�ле** (в�тавлено в тот же кадр): + +``` + 4 Nxe4 Nf6 + 5 f3 Bf5 +┌──────────────────────────────────────────────────────────� +│ 5…▌Nxe4� 6.fxe4 e5 7.d5 Bc5 8.Nf3 … 51.Kc4 Rb3 │ � блок варианта (е�ть) +│ 0-1 Mellado Trivino,J (2430) – Garcia Albarracin,F │ � ��ылка: обычный комментарий +│ (2305), ESP-ch Torrevieja 1997 (3) │ +└──────────────────────────────────────────────────────────┘ + 6 Ng3 … +``` + +- **Кур�ор — на первом в�тавленном ходе** (5…Nxe4), до�ка показывает позицию по�ле него, нотаци� прокручена так, чтобы ход был по центру (`scroll_to_cursor`). Так же по�тупает «+ Добавить как вариант» (`insert_preview`). +- **Отдельной под�ветки в�тавленного нет.** Выделенный ход и �ам новый блок варианта и так показывают, где он; ещё одна под�ветка — лишнее �о�то�ние, которое надо га�ить по таймеру или по дей�твию. Длинный вариант (93 полухода) читает�� от кур�ора вниз. +- �овый вариант — **по�ледним** �реди вариантов �того хода; о�новна� лини� не мен�ет��. +- В шапке по�вл�ет�� «•» (парти� изменена) — как у любой правки. +- **То�т** (3,5 �, внизу по центру, компонент `TOAST`): + - «Вариант 5…Nxe4 … 51…Rb3 в�тавлен по�ле 5.f3 (Ctrl+Z — отменить)» (`Line {first} … {last} inserted after {move} (Ctrl+Z to undo)`); + - короткий вариант (до 3 полуходов) — в�е ходы: «Вариант 2…Nc6 3.d4 в�тавлен по�ле 2.Nf3 (Ctrl+Z — отменить)» (`Line {moves} inserted after {move} (Ctrl+Z to undo)`); + - вариант к первому ходу партии: «…в�тавлен в начале партии» (`…inserted at the start of the game`); + - у хода не было продолжени� — лини� продолжена (`add_line` делает её о�новной): «Парти� продолжена: 6.Qd3 e6 (Ctrl+Z — отменить)» (`The game is continued: {moves} (Ctrl+Z to undo)`). + - Диапазон ходов вме�то чи�ла («93 хода») — однозначно (ход ≠ полуход) и �разу говорит, *что* в�тавлено; �клон�ть чи�лительное не нужно. + - Ходы в то�тах — в текущей запи�и ходов (`san::show`: фигурки / буквы �зыка), многоточие `…` как в нотации. +- **Звука нет** (правка, а не ход на до�ке; «+ Добавить как вариант» тоже без звука). +- **Отмена.** Ctrl+Z (и ↩ на панели) убирает в�тавку целиком одним шагом, кур�ор возвращает�� туда, где �то�л до в�тавки. Ctrl+Y возвращает. + +### 2.1. С�ылка на и�точник и пометка о переходе + +- **С�ылка** — комментарий по�ле по�леднего хода варианта (обычный, правит�� и удал�ет�� как любой, `user-comments.md`). Формат — как в образце владельца (ChessBase): результат, затем парти�: + `{Result} {White} ({WhiteElo}) – {Black} ({BlackElo}), {Event} {год} ({Round})` + Пу�тые ча�ти пропу�кают�� вме�те �о �кобками и зап�тыми; `Result` = `*` — не пишет��; год — из `Date` (`1997.??.??` → 1997). Тире между игроками — «–» (U+2013, как в образце). С�ылка �тавит��, только е�ли у в�тавл�емой партии е�ть `White` или `Black` (у обрывка ходов её нет). +- **Пере�тановка** (и��ледование §4.3 п. 2): перед первым ходом варианта — комментарий «Другим пор�дком ходов: 1.Nf3 c5 2.e4» (`By another move order: {moves}`), «перед ходом» (`Slot::Before`). Он читает�� там, где у пользовател� возникает вопро� «откуда �тот вариант без первых ходов», а не через 90 ходов в конце. +- Тек�ты, которые пишут�� **в партию** (пометка о переходе), — на �зыке интерфей�а в момент в�тавки, ходы в них — латиницей SAN (данные, `move-notation.md` §0 п. 1). С�ылка на и�точник — без �лов, только данные тегов. +- Комментарии, NAG и вложенные варианты в�тавл�емой партии по�ле точки ра�хождени� перено��т�� (и��ледование §4.4) и выгл�д�т как обычные: в блоке варианта, вложенные — в �кобках. + +## 3. Вопро� «В�тавить вариант раньше?» + +**Когда.** Ме�то в�тавки найдено (и��ледование §4.2–4.3), но �то **не** выбранный ход, **не** ход по�ле него по любой ветке и **не** вариант к �амому выбранному ходу (его родитель). Проще: вариант окажет�� не там, куда пользователь �мотрит. Типичный �лучай — �то�т на 20.Rd1, а парти� из буфера ра�ходит�� по�ле 2.Nf3. Кур�ор в начале партии — вопро�а нет никогда (�мотрит на в�ю партию). + +`egui::Modal`, ширина `min(460, W − 32)`, вид — как вопро�ы `own-databases.md` §3.4: + +``` +┌─ В�тавить вариант раньше? ─────────────────────────────� +│ Парти� из буфера ра�ходит�� � �той раньше выбранного │ +│ хода: по�ле 2.Nf3, а не по�ле 20.Rd1. │ +│ │ +│ ┌────────────────────────────────────────────────────� │ � рамка 1 (bg_stroke), �кругление 4, +│ │ 2…Nc6 3.d4 cxd4 4.Nxd4 Nf6 5.Nc3 e5 6.Ndb5 … 51…Rb3│ │ пол� 8; ходы 14, в одну �троку, +│ │ 0-1 Mellado Trivino,J – Garcia Albarracin,F, 1997 │ │ лишнее — «…» перед по�ледним ходом; +│ └────────────────────────────────────────────────────┘ │ втора� �трока 13 �лабым — и�точник +│ │ +│ [ Отмена ] [▌В�тавить по�ле 2.Nf3�] │ � вы�ота 30, прижаты вправо, +└────────────────────────────────────────────────────────┘ главна� — крайн�� права� (как «Играть») +``` + +- Заголовок «В�тавить вариант раньше?» (`Insert the line earlier?`). +- Тек�т: «Парти� из буфера ра�ходит�� � �той раньше выбранного хода: по�ле {from}, а не по�ле {cursor}.» (`The game in the clipboard parts from this one before the selected move: after {from}, not after {cursor}.`). Е�ли ме�то в другой ветке, а не раньше: «Парти� из буфера ра�ходит�� � �той в другом варианте: по�ле {from}.» (`The game in the clipboard parts from this one in another line: after {from}.`). Ме�то — начало партии: «…в начале партии» (`…at the start of the game`). +- Рамка � линией — чтобы было видно, *что* в�тавит��, без чтени� PGN. Втора� �трока — та же ��ылка, что запишет�� в партию, но без Эло и тура (коротко); нет имён — �троки нет. +- Кнопки: «В�тавить по�ле 2.Nf3» (`Insert after {move}`; в начале партии — «В�тавить в начале» / `Insert at the start`) — главна�, **Enter**; «Отмена» (`Cancel`, е�ть) — **Esc**. Щелчок вне окна — ничего (как у других вопро�ов). +- «Отмена» ничего не мен�ет (критерий 9). «В�тавить» — как §2, кур�ор на первом в�тавленном ходе (нотаци� прокручивает�� к нему вверх). +- Узкое окно: при 640 — ширина 460, помещает��; е�ли две кнопки не вход�т в �троку (длинный ход в подпи�и) — кажда� на �воей �троке во в�ю ширину, главна� �верху. + +## 4. Отказы и о�обые ответы (то�ты, парти� не мен�ет��) + +| Случай (и��ледование) | То�т | Кур�ор | +|---|---|---| +| буфер пу�т, недо�тупен или в нём нет ни одного хода (§4.2 п. 1) | «В буфере нет ходов» (`The clipboard holds no moves`) | на ме�те | +| обрывок не в�таёт ни по�ле выбранного хода, ни вме�то него, ни по номеру (§4.2 п. 4) | «Эти ходы нельз� �делать ни по�ле {move}, ни вме�то него» (`These moves fit neither after {move} nor instead of it`) | на ме�те | +| ход по�реди линии невозможен (§4.2) | «Ход {n}.{san} невозможен — ничего не в�тавлено» (`The move {n}.{san} is impossible — nothing inserted`); у чёрных `{n}…{san}` | на ме�те | +| нет ни общих ходов, ни общих позиций — «�ицилианка и d4» (§4.3 п. 3) | «Парти� из буфера �юда не подходит: в �той партии нет её позиций» (`The game in the clipboard does not fit: none of its positions occur in this game`) | на ме�те | +| в�ё уже е�ть (§4.4) | «Эти ходы уже е�ть в партии» (`These moves are already in the game`); е�ли у в�тавл�емой были комментарии — «Эти ходы уже е�ть в партии — комментарии из буфера не перене�ены» (`These moves are already in the game — the comments from the clipboard were not carried over`) | **на конец �овпавшей линии**, нотаци� прокручена — «вот где они» | +| в буфере не�колько партий (§4.2 п. 5) | к то�ту у�пеха — вторым предложением «В буфере {count} партий — в�тавлена перва�.» (`The clipboard has {count} games — the first one is inserted.`) — один то�т, не два (то�т один на �кране); чи�ло — через �уще�твующий `games_count` | как §2 | + +- То�т об отказе — тот же компонент `TOAST`: коротка� причина, читает�� за 3,5 �, ничего не загораживает. Окно � «ОК» на отказ — лишний щелчок. +- **Ширина то�та.** Сейча� то�т — одна �трока (`ui.horizontal`); тек�ты �той функции длиннее, а окно бывает 640. То�ту — ширина не больше `min(560, W − 32)` � перено�ом �трок (правка общего компонента, о�тальным то�там не вредит). + +## 5. Со�то�ни� �крана партии + +| Со�то�ние | Что делает Ctrl+V / пункт | +|---|---| +| обычна� парти� из �воей базы | §2 | +| парти� из базы **только дл� чтени�** (ChessBase, архив, онлайн-партии), нова� парти�, парти� из буфера | так же: правка в пам�ти, «•» в шапке; запи�ь — Ctrl+S → «Добавить в базу…», как у любой правки (`own-databases.md` §3.2). И�ходный файл не трогает�� | +| открыт редактор комментари� | Ctrl+V — в�тавка тек�та в редактор (фоку� в поле); пункт меню — �начала «Готово» редактора (`commit_editor`), потом в�тавка варианта | +| на до�ке показана лини� движка (`preview`) | показ линии закрывает��, в�тавка — отно�ительно на�то�щего кур�ора (ход, выделенный в нотации) | +| идёт «�нализ партии» | в�тавка разрешена; отметки анализа новых ходов не получают (как у любой правки �ейча�) | +| режим игры � Maia, тренировка дебюта | ничего (Ctrl+V молчит, меню хода нет) | +| кур�ор в начале партии | в�тавка по правилам и��ледовани�; вопро�а §3 нет | + +## 6. Узкие окна + +- Меню хода — �и�темное контек�тное меню egui, ширина по �амой длинной �троке (≈ 300 � «прохождений: 4»); при 640 помещает��. +- Вопро� §3 — §3, по�ледний пункт. То�т — §4. +- Компоновка «р�дом/�топка» не мен�ет��; в �топке нотаци� — нижн�� панель, прокрутка к кур�ору работает так же. + +## 7. Клавиатура — �водка + +| Клавиша | Где | Дей�твие | Сегодн� | +|---|---|---|---| +| Ctrl+V | �кран партии, фоку� не в поле | в�тавить вариант из буфера | �вободна | +| Enter / Esc | вопро� §3 | «В�тавить по�ле …» / «Отмена» | — | +| Ctrl+Z / Ctrl+Y | �кран партии | отменить / вернуть в�тавку целиком | как �ейча� | + +## 8. Что �троит разработчик + +1. `chess-core`: разбор буфера и пои�к ме�та — по и��ледованию §4.2–4.4; результат — «план в�тавки»: узел-ме�то, поддерево, лини� дл� показа, ��ылка, пометка о переходе, признак «продолжение»; одно изменение дл� отмены (�борка поддерева + `Attach`). +2. `game_view.rs`: `Event::Paste` в `keyboard`; новые `NotationCommand::Paste` (меню хода) и пункт ☰; решение «вопро� или �разу» (§3); по�ле в�тавки — `goto(first)`, `scroll_to_cursor`, то�т. +3. Вопро� §3 — модальное окно `GameView` (как `leave_question`), �о�то�ние `paste_pending: Option`. +4. `notation.rs`: пункт меню и `shortcut_text` у пунктов §1.1. +5. То�т: перено� �трок и ширина `min(560, W − 32)` (`app.rs`, `TOAST`). +6. Ключи `i18n.rs` — в�е тек�ты §1–§4 на ше�ть �зыков. +7. Хук дл� �нимков и проверок: `CP_PASTE_LINE="<тек�т>"` — по�ле открыти� партии (`CP_OPEN`, `CP_PLY`) в�тавить тек�т как вариант (как будто нажат Ctrl+V). Опи�ать в `docs/dev/desktop.md`. + +## 9. Ра�хождени� � и��ледованием + +- В меню без значка «📋»: в меню хода значков нет ни у одного пункта, а значок у одного �двинул бы его тек�т. +- Вопро� задаёт�� по правилу «вариант в�таёт не там, куда �мотрит пользователь» (раньше выбранного хода **или в другой ветке**), а не только «раньше»; вариант к �амому выбранному ходу («вме�то него») — без вопро�а, �то обычный книжный �лучай. +- В то�те — диапазон ходов вме�то чи�ла «93 хода». +- Пометка о переходе — комментарием **перед** первым ходом варианта, а не внутри ��ылки в конце. +- С�ылка начинает�� � результата (как в образце владельца), а не заканчивает�� им. + +## 10. Открытые вопро�ы владельцу + +1. **Спрашивать, е�ли вариант в�таёт не там, где вы �тоите?** Рекомендую да (одно окно, Enter — в�тавить): защищает от «в�тавил не ту партию», обычный �лучай проходит молча. +2. **С�ылка на и�точник — в�егда, когда у партии е�ть имена игроков?** Рекомендую да, в формате вашего образца («0-1 Белые (Эло) – Чёрные (Эло), Турнир год (тур)»); не нужна — удал�ет�� как комментарий. +3. **�е�колько партий в буфере — в�тавл�ть первую � �ообщением?** Рекомендую да в первой вер�ии; «влить в�е» — потом, е�ли понадобит��. + +## 11. Чек-ли�т реализации + +- [ ] Ctrl+V через `Event::Paste` только при `!egui_wants_keyboard_input()`; в редакторе комментари� — обычна� в�тавка тек�та. +- [ ] Пункт меню хода и пункт ☰ на �воих ме�тах (§1, §1.1), правые подпи�и одной колонкой, без значков. +- [ ] Обычна� в�тавка: один кадр, кур�ор на первом в�тавленном ходе, прокрутка, «•», то�т � диапазоном ходов; Ctrl+Z убирает в�ё одним шагом и возвращает кур�ор. +- [ ] «Продолжение» (у хода нет продолжени�) — то�т «Парти� продолжена…». +- [ ] С�ылка на и�точник — формат §2.1, пу�тые пол� без лишних �кобок и зап�тых; `*` не пишет��; без имён — нет ��ылки. +- [ ] Пометка о переходе — комментарий перед первым ходом варианта. +- [ ] Вопро� §3: у�ловие (не кур�ор / не потомок / не родитель кур�ора), Enter/Esc, рамка � линией, кнопки при 640. +- [ ] Отказы §4 — парти� не мен�ет�� (`revision()`), кур�ор на ме�те; «уже е�ть» — кур�ор на конце �овпавшей линии. +- [ ] �е�колько партий — один то�т, не два. +- [ ] То�т перено�ит�� и не шире `min(560, W − 32)`; проверить при 640 × 480. +- [ ] Игра и тренировка: Ctrl+V ничего не делает, меню хода нет. +- [ ] Парти� из базы только дл� чтени�: в�тавка работает, файл базы не мен�ет��, Ctrl+S → «Добавить в базу…». +- [ ] Критерии приёмки и��ледовани� §6 (1–11) — те�тами `chess-core` и �нимками � `CP_PASTE_LINE`. diff --git a/docs/design/play-from-position.md b/docs/design/play-from-position.md new file mode 100644 index 0000000..c926023 --- /dev/null +++ b/docs/design/play-from-position.md @@ -0,0 +1,212 @@ +# Играть от�юда � Maia: парти� из базы продолжает�� игрой + +Стату�: проект дизайнера, 2026-10-25, **не утверждён**. Требовани� — `docs/research/play-from-position.md` (аналитик: §4 — вход, диалог, кака� парти� получает��, граница дл� хода назад, реванш; §7 — критерии приёмки). О�нова �крана — режим игры `docs/design/play-mode.md` и его реализаци� (`play.rs` `Dialog::show`, `game_view.rs` `play_side`, `clock_card`, `play_toolbar`, `result_strip`, `leave_question`). Зде�ь — только то, что **отличает��** от обычной игры. Где проект ра�ходит�� � и��ледованием — §9. + +Снимки нынешнего вида (scratchpad разработчика `dev2/`): `rs_custom.png` / `s_dialog.png` — диалог «Игра � компьютером»; `pl_white.png`, `pl_640.png` — �кран игры 1400 и 640; `rs_final.png` — карточка «Maia �даёт��»; `m_end.png` — поло�а результата. + +Размеры — логиче�кие точки egui. Тек�ты — по-ру��ки, в �кобках англий�кий ключ; �уще�твующие помечены «(е�ть)». + +## 0. Главное + +1. **Вход** — пункт меню хода «Играть от�юда � Maia…» и **Ctrl+G** на �кране партии (позици� под кур�ором). +2. **Диалог — тот же**, � одним новым блоком �верху: мини-до�ка позиции и «С позиции по�ле 14…Ке7 · из партии Карл�ен — Каруана, Вейк-ан-Зее 2024 · Ход белых». Цвет по умолчанию — �торона, чей ход. +3. **�ова� парти� = ходы и�ходной до �той позиции + игра.** Во врем� игры ходы и�ходной партии в нотации приглушены, по�ле них — блок-комментарий «Продолжение партии … Дальше — игра � Maia 1600». �азад они не берут��, «Прервать/Сдать��» и ча�ы �читают�� только по новым ходам. +4. **И�ходна� парти� о�таёт�� открытой «под» игрой** — тем же механизмом, что парти� из «Справочника»: в шапке игры кнопка «⬅ К партии Карл�ен — Каруана» (е�ть), Esc по�ле игры возвращает к ней, кур�ор на ходе, � которого играли. �е�охранённые правки и�ходной партии не тер�ют�� и не требуют вопро�а при входе. +5. **Реванш — � той же позиции**, «�ова� игра» — тот же диалог � той же позицией. + +## 1. Точки входа + +| Где | Подпи�ь | Клавиша | �еактивно, когда | +|---|---|---|---| +| меню хода (правый щелчок) | «Играть от�юда � Maia…» (`Play on from here against Maia…`), �права �лабым `Ctrl+G` | — | позици� окончена (§1.1) | +| �кран партии | — | **Ctrl+G** — позици� под кур�ором, в том чи�ле начальна� позици� партии (у неё нет хода дл� меню) | позици� окончена — то�т §1.1 | +| меню ☰ | «Играть от�юда � Maia… (Ctrl+G)» (`Play on from here against Maia… (Ctrl+G)`), по�ле «В�тавить вариант из буфера (Ctrl+V)», отделён чертой | — | как у меню хода | + +- Под�казка пункта: «Парти� � компьютером � позиции по�ле {move}» (`A game against the computer from the position after {move}`). +- Ме�то в меню хода — по�ледн�� группа «новые �краны» (`paste-variation.md` §1.1): «Играть от�юда � Maia…», «Учить дебют до �того хода». +- **Ctrl+G �вободна** на �кране партии: в `app.rs` она открывает обычную игру только при `self.game.is_none()` (библиотека). Смы�л один — «играть»: в библиотеке � начала, в партии — от�юда. +- Многоточие в подпи�и — потому что дальше диалог. +- В режиме игры и тренировки меню хода нет, Ctrl+G молчит. По�ле конца игры парти� обычна� — пункт �нова е�ть (�ценарий П4 — переиграть �вою партию � 25-го хода). +- Ctrl+G при открытом редакторе комментари� не дей�твует (фоку� в поле); при показе линии движка — позици� на�то�щего кур�ора, показ линии закрывает��. + +### 1.1. Позици� окончена + +Мат, пат, нет материала у обеих �торон (`play::ending` дл� позиции кур�ора). Пункт меню �ерый, под�казка неактивного пункта: «Зде�ь парти� окончена: мат» (`The game is over here: checkmate`) / «…: пат» (`stalemate`) / «…: ни у кого нет материала дл� мата» (`neither side can checkmate`). Ctrl+G в такой позиции — тот же тек�т то�том. + +Троекратное повторение и 50 ходов игру **не** запрещают: в партии �то право требовать ничью, а не конец. (Е�ли позици� на границе уже повторила�ь дважды, третье повторение в игре закончит её — критерий 3 и��ледовани�.) + +## 2. Диалог + +Тот же `play::Dialog` «Игра � компьютером» (е�ть), ширина 460, � двум� отличи�ми: блок позиции вверху и цвет по умолчанию. + +``` +┌─ Игра � компьютером ─────────────────────────────────────� +│ ┌──────────────────────────────────────────────────────� │ � блок позиции: рамка 1 (bg_stroke), +│ │ ┌────────────� С позиции по�ле 14…Ке7 │ │ �кругление 4, пол� 8, ширина 460; +│ │ │ │ из партии Карл�ен — Каруана, │ │ мини-до�ка 112 × 112 (клетка 14), +│ │ │ мини- │ Вейк-ан-Зее 2024 │ │ тек�т в колонке �права, +│ │ │ до�ка │ │ │ от�туп от до�ки 12 +│ │ │ 112 │ Ход белых │ │ +│ │ └────────────┘ │ │ +│ └──────────────────────────────────────────────────────┘ │ +│ Вы │ � дальше как �ейча� (е�ть) +│ Им�: [Роман Врубель ] │ +│ Рейтинг: [2600] не об�зательно │ +│ Соперник — Maia 1500 │ +│ 600 ��������������������������������������������� 2600 │ +│ [ Слабее ] [ Как � ] [ Сильнее ] │ +│ Цвет │ +│ [▌ ♔ Белые �] [ Случайно ] [ ♚ Чёрные ] │ � выбрана �торона, чей ход +│ Врем� │ +│ [3+0] [3+2] [5+0] [5+3] │ +│ … │ +│ [Отмена] [▌Играть�]│ +└──────────────────────────────────────────────────────────┘ +``` + +**Блок позиции.** +- Мини-до�ка — `BoardView` без взаимодей�тви�, без координат, 112 × 112, тот же набор фигур и цвета до�ки, под�ветка по�леднего хода (14…Ке7). **Ориентаци� �ледует плитке «Цвет»**: «Белые» — белые �низу, «Чёрные» — чёрные �низу, «Случайно» — �низу �торона, чей ход. Щелчок по плитке цвета �разу переворачивает мини-до�ку — видно, за кого будете играть. +- Строка 1, 15 жирным: «С позиции по�ле 14…Ке7» (`From the position after {move}`); ход — в текущей запи�и ходов (`san::show`), `…` у чёрных. �ачальна� позици� FEN-партии — «С начальной позиции партии» (`From the game's starting position`). +- Строка 2, 13 �лабым: «из партии Карл�ен — Каруана, Вейк-ан-Зее 2024» (`from the game {game}`): `White — Black, Event год`, пу�тые ча�ти пропу�кают��; не больше двух �трок, дальше «…», полный тек�т — в под�казке. �ет ни игроков, ни турнира — �троки нет. +- Строка 3, 13 обычным: «Ход белых» / «Ход чёрных» (`White to move` / `Black to move`) — прижата к низу колонки (на уровне нижнего кра� до�ки), чтобы блок не выгл�дел пу�тым �низу. +- Путь � учебным пропу�ком хода `--` (и��ледование §4.3): �трока 4, 13 �лабым — «Ходы до пропу�ка хода (--) в игру не войдут» (`The moves before the null move (--) are not carried over`). +- Блок замен�ет в�тупительную �троку про Maia («Maia играет как человек выбранного рейтинга…», е�ть): диалог не ра�тёт на вы�оту в�его блока (+112 − 36), а объ��нение Maia о�таёт�� в подпи�и под ползунком. +- **�изкое окно** (то же у�ловие, по которому �ейча� пр�чет�� в�тупление, `body_h < 420`): мини-до�ка не ри�ует��, блок — три �троки тек�та в той же рамке (≈ 64). + +**Цвет.** Плитки «♔ Белые · Случайно · ♚ Чёрные» (е�ть). При открытии выбрана **�торона, чей ход** в позиции (и��ледование §4.2). Этот выбор **не пишет��** в `Settings.play.color`: �ледующа� обычна� игра (Ctrl+G в библиотеке) откроет�� � прежним цветом. О�тальное (им�, рейтинг, �ила, врем�) запоминает�� как обычно — при «Играть». + +**В�ё о�тальное** — без изменений: «Скачать и играть», когда Maia не у�тановлена; Enter — «Играть»; Esc — «Отмена». Заголовок окна тот же: �то та же игра. + +## 3. Экран игры + +Экран — режим игры `play-mode.md` §3 без изменений компоновки (карточки ча�ов, нотаци�, панель «� ◀ ▶ � │ 🔃 │ ↶ Ход назад │ ✕ Прервать / ⚑ Сдать��»). Отличи�: + +### 3.1. Шапка + +``` +⬅ Библиотека │ ⬅ К партии Карл�ен — Каруана │ Роман Врубель — Maia 1600 ⚙ �а�тройки + │ │ Парти� � компьютером, рапид · ChessPenguin · 2026.10.25 +``` + +- «⬅ К партии {game}» (е�ть, `previous`) — та же кнопка, что у партии, открытой из «Справочника»; под�казка (е�ть) «Парти�, из которой открыта �та, — как вы её о�тавили (Esc)». Во врем� игры она, как «⬅ Библиотека», ведёт к вопро�у «Парти� идёт» (`guard_leaving` уже понимает `ReturnToPrevious`). +- �азвание и подзаголовок — как у обычной игры (теги `start_play`). Откуда игра — видно по кнопке «⬅ К партии …» и по блоку в нотации, отдельной �троки в шапке не нужно. +- При 640 кнопки �танов�т�� значками «⬅ ⬅» � под�казками (е�ть, `narrow-windows.md` §3.4). + +### 3.2. �отаци� + +``` + 1 e4 c5 + 2 Nf3 d6 � ходы и�ходной партии: �лабым цветом (weak_text_color) + … + 14 Bd3 Ke7 +┌─────────────────────────────� +│ Продолжение партии Карл�ен — │ � комментарий по�ле 14…Ke7: обычный блок комментари� (е�ть) +│ Каруана, Вейк-ан-Зее 2024, │ +│ по�ле 14...Ke7. Дальше — │ +│ игра � Maia 1600. │ +└─────────────────────────────┘ + 15 ▌Rd1� … � новые ходы: обычным цветом +``` + +- **Ходы и�ходной партии — приглушены** (`weak_text_color`) **только во врем� игры**: видно, что �то не ваши ходы и их не вз�ть назад. Щелчок по ним показывает позицию (ли�тание е�ть, `play-mode.md` §3.6). По�ле конца игры парти� — обычна�, приглушени� нет. +- **Блок прои�хождени�** — комментарий *по�ле по�леднего хода и�ходной партии* (`Slot::After(граница)`); у FEN-партии � начальной позиции — комментарий в начале партии. Это на�то�щий комментарий, он запи�ывает�� в PGN и виден в любой программе; в нотации он �ам �лужит чертой между «было» и «играем». + - Тек�т: «Продолжение партии {game}, по�ле {move}. Дальше — игра � Maia {elo}.» (`Continued from {game}, after {move}. From here on, a game against Maia {elo}.`). `{game}` — как �трока 2 диалога; нет имён — «Продолжение партии по�ле {move}…» (`Continued after {move}…`). + - Пишет�� на �зыке интерфей�а, ход — латиницей SAN � `...` (данные, `move-notation.md` §0 п. 1); в нотации показывает�� как е�ть. +- Комментарии, значки и варианты и�ходной партии **не перено��т��** (и��ледование §4.3) — в нотации только ходы. +- При �тарте нотаци� прокручена к концу (к границе), как �ейча� к по�леднему ходу. + +### 3.3. Граница: ход назад, прервать, �дать��, ча�ы + +| Что | Обычна� игра (е�ть) | Игра � позиции | +|---|---|---| +| «↶ Ход назад» активна | по�ле первого хода пользовател� | по�ле первого хода пользовател� **по�ле границы**; ходы и�ходной партии не �нимают�� никогда | +| «✕ Прервать» вме�то «⚑ Сдать��» | до первых ходов обеих �торон | до первых ходов обеих �торон **по�ле границы** | +| уход без вопро�а | то же | то же | +| ча�ы пошли | по�ле первых ходов обеих �торон | по�ле первых ходов обеих �торон по�ле границы; у обоих полное врем� � момента ответвлени� | +| Maia ходит первой | когда пользователь за чёрных | когда ход �тороны Maia в позиции границы — �разу по�ле открыти� �крана | + +- **«✕ Прервать» и Esc до первых ходов** ведут **обратно к и�ходной партии** (как «⬅ К партии»), а не в библиотеку: пользователь пришёл оттуда и, �корее в�его, передумал о �иле или цвете. +- Вопро� «Парти� идёт» (е�ть) — тот же; «Сдать�� и выйти» уходит туда, куда вёл повод: «⬅ К партии»/Esc — к и�ходной партии, «⬅ Библиотека» — в библиотеку. +- Звуки, премув, предложение Maia �дать��, �бой Maia — как в обычной игре. + +### 3.4. Карточки ча�ов + +Без изменений. До первых ходов по�ле границы — �о�то�ние «до первых ходов» (е�ть). + +## 4. По�ле игры + +- Экран �тановит�� обычной партией � поло�ой результата (е�ть, `m_end.png`): «📈 �нализировать», «↻ Реванш», «♞ �ова� игра», «💾 Сохранить в базу…». Приглушение префик�а �нимает��, блок прои�хождени� о�таёт��. +- **«↻ Реванш» — � той же позиции**, те же �ила и врем�. Цвет — �м. вопро� 2: рекомендую **тот же**, под�казка «Та же позици�, вы �нова за белых» (`The same position, you play White again`) вме�то «Те же на�тройки, цвета мен�ют��» (е�ть). В обычной игре цвет — жребий, в игре � позиции цвет — ча�ть задачи («�ыграть �ту позицию белыми»). +- **«♞ �ова� игра»** — диалог §2 � тем же блоком позиции (цвет — �нова �торона, чей ход). +- Реванш и �ова� игра замен�ют �ыгранную партию: перед �тим — вопро� «Парти� изменена» (е�ть, `own-databases.md` §3.4). И�ходна� парти� о�таёт�� «под» новой игрой, кнопка «⬅ К партии …» в шапке та же. +- **«⬅ К партии …» / Esc** по�ле игры: �ыгранна� парти� не �охранена → вопро� «Парти� изменена · Добавить в базу?» (е�ть) → и�ходна� парти�, кур�ор там, где был (на ходе, � которого играли). +- Сохранить — «💾 Сохранить в базу…» / Ctrl+S (е�ть): запи�ывает�� нова� парти� (теги игры, префик�, блок прои�хождени�, ходы игры). И�ходна� база не трогает��. +- **Вернуть �ыгранное в и�ходную партию вариантом** — отдельной кнопки в v1 нет: «Копировать PGN» (Ctrl+Shift+C), «⬅ К партии», Ctrl+V — в�тавка в�танет ровно в точку ответвлени� (`paste-variation.md`). См. вопро� 3. + +## 5. И�ходна� парти� «под» игрой + +Механизм уже е�ть (`app.rs` `previous_games`, `GameView.previous`, кнопка «⬅ К партии {game}»): парти� из «Справочника» открывает�� поверх текущей, текуща� ждёт в �теке, как её о�тавили. + +- При входе в игру и�ходна� парти� **прио�танавливает��** (`suspend`, движок о�танавливает��) и уходит в �тек; вопро� «Парти� изменена» **не задаёт��** — ничего не тер�ет�� (и��ледование §4.5 предлагало вопро� — зде�ь он не нужен). +- «⬅ Библиотека» из игры или по�ле неё — обычный уход: не�охранённые партии �тека �прашивают�� по одной (е�ть, `finish_close`). +- �ачать «играть от�юда» из партии, котора� �ама открыта поверх другой, можно: �тек про�то ра�тёт. + +## 6. Узкие окна + +- Диалог при 640: ширина 460 помещает��; блок позиции — мини-до�ка 112 + колонка тек�та 460 − 16 − 112 − 12 = 320. Строка 2 перено�ит�� (две �троки мак�имум). +- 640 × 480: тело диалога прокручивает�� (е�ть), мини-до�ки нет (§2, низкое окно), �трока кнопок в�егда видна. +- Экран игры — как `play-mode.md` §7 (р�дом при 640 × 480, карточки в нижней панели в �топке — `pl_640.png`); блок прои�хождени� в нотации — обычный блок комментари� на в�ю ширину. +- Шапка — §3.1. + +## 7. Клавиатура — �водка + +| Клавиша | Где | Дей�твие | Сегодн� | +|---|---|---|---| +| Ctrl+G | �кран партии (обычный режим) | диалог «Игра � компьютером» � позиции кур�ора | �вободна (в библиотеке — обычна� игра) | +| Enter / Esc | диалог | «Играть» / «Отмена» | е�ть | +| Esc | игра до первых ходов по�ле границы | назад к и�ходной партии | в игре — уход | +| Esc | игра по�ле первых ходов | вопро� «Парти� идёт» | е�ть | +| Esc | по�ле игры | «⬅ К партии …» (� вопро�ом о �охранении) | е�ть дл� `previous` | +| Ctrl+Z | игра | ход назад, не дальше границы | е�ть | + +## 8. Что �троит разработчик + +1. `play::Start.from: Option` — начальна� позици� (�тандартна� / FEN, по�ле по�леднего `--`), ходы префик�а, опи�ание партии-и�точника (дл� блока и комментари�), ход границы дл� подпи�и. `Dialog::new_from(settings, from)` — блок позиции, цвет по умолчанию из очереди хода, без запи�и цвета в на�тройки. +2. `NotationCommand::PlayFrom` (меню хода), Ctrl+G в `keyboard`, пункт ☰; проверка §1.1 через `play::ending`. +3. `GameAction::PlayFrom(StartFrom)` → `app.rs`: открыть диалог; при «Играть» — текуща� парти� в `previous_games` (`suspend`), нова� `GameView` � `previous = title`, `start_play` �троит префик� (`Game::from_start` + `add_line`), комментарий прои�хождени�, запоминает `play_floor: NodeId`. +4. `play_started`, `take_back`, «ходил ли пользователь» в `play_toolbar` и `take_back`, ча�ы — �читать по ходам по�ле `play_floor` (и��ледование §1). +5. `notation.rs`: признак «приглушить ходы до узла» (`dim_until: Option`) дл� режима игры. +6. «✕ Прервать» и Esc до первых ходов: `ReturnToPrevious`, когда е�ть `previous`. +7. Реванш: `Start.from` �охран�ет��; цвет — по решению владельца (вопро� 2); под�казка кнопки — §4. +8. Хук: `CP_PLAY_FROM=white|black|dialog` вме�те � `CP_OPEN`/`CP_PLY` — игра (или диалог) � позиции кур�ора. Опи�ать в `docs/dev/desktop.md`. + +## 9. Ра�хождени� � и��ледованием + +- И�ходна� парти� о�таёт�� в �теке � кнопкой «⬅ К партии …» уже в v1 (вопро� 2 аналитика): �то готовый механизм, а не нова� функци�; по�тому при входе не нужен вопро� «Парти� изменена», а «Прервать»/Esc до первых ходов возвращают к и�ходной партии. +- Мини-до�ка позиции в диалоге: подпи�ь «по�ле 14…Ке7» без до�ки за�тавл�ет помнить позицию; до�ка 112 �нимает �омнение «та ли позици�» и показывает, за кого играешь. +- Комментарий прои�хождени� — по�ле по�леднего хода и�ходной партии (ме�то то же, но он �уще�твует � первого кадра игры). +- Ходы и�ходной партии приглушены во врем� игры. +- Реванш � позиции — тем же цветом (вопро� 2). +- �азвание пункта без значка «⚔»: в меню хода значков нет (`paste-variation.md` §9). + +## 10. Открытые вопро�ы владельцу + +1. **Цвет по умолчанию — �торона, чей ход?** Рекомендую да (�менить можно одним щелчком; угадывать по имени игрока — нет: имена пишут�� по-разному). +2. **«↻ Реванш» � позиции — тем же цветом или � обменом цветов, как в обычной игре?** Рекомендую тем же: вы играете *�ту позицию* за �вою �торону; помен�ть�� — «�ова� игра» и щелчок по цвету. +3. **Кнопка «Добавить в и�ходную партию вариантом» в поло�е результата?** Рекомендую не в v1: путь «Копировать PGN → ⬅ К партии → Ctrl+V» уже работает и в�тавл�ет ровно в точку ответвлени�; е�ли будете делать �то ча�то — добавим кнопку, она �танет одной �трокой поверх готовой в�тавки. + +## 11. Чек-ли�т реализации + +- [ ] Пункт меню хода, Ctrl+G и пункт ☰; �ерый пункт � причиной в окончённой позиции; Ctrl+G там — то�т. +- [ ] Ctrl+G в библиотеке по-прежнему — обычна� игра; на �кране партии — � позиции. +- [ ] Диалог: блок позиции 460, мини-до�ка 112 �ледует плитке цвета, �троки §2; в низком окне — без до�ки; FEN-начало и путь � `--` — �вои подпи�и. +- [ ] Цвет по умолчанию — чей ход; `Settings.play.color` не мен�ет�� (критерий 9). +- [ ] �ова� парти�: префик� — только ходы (путь через вариант — тоже), теги игры, комментарий прои�хождени� по�ле границы; и�ходна� парти� не изменена (`revision()`). +- [ ] Maia получает в�ю и�торию (критерий 2); троекратное повторение � учётом префик�а (критерий 3). +- [ ] Граница: ход назад, «Прервать/Сдать��», ча�ы, «ходил ли пользователь» — по ходам по�ле границы (критерии 4–5). +- [ ] Префик� приглушён во врем� игры, по�ле конца — обычный. +- [ ] Шапка: «⬅ К партии …» во врем� игры ведёт к вопро�у «Парти� идёт»; до первых ходов «✕ Прервать»/Esc — к и�ходной партии без вопро�а. +- [ ] По�ле игры: Реванш � той же позиции (цвет по решению), «�ова� игра» — диалог � блоком; Esc — вопро� о �охранении, затем и�ходна� парти� � кур�ором на ходе ответвлени�. +- [ ] И�ходна� парти� � не�охранёнными правками не тер�ет��: «⬅ Библиотека» �прашивает о ней (е�ть). +- [ ] Запи�анный PGN переоткрывает�� без замечаний (критерий 8). +- [ ] Снимки 1400 × 900, 640 × 480, 640 × 1000: диалог � блоком, игра � префик�ом, поло�а результата. diff --git a/docs/design/play-mode.md b/docs/design/play-mode.md new file mode 100644 index 0000000..9e70261 --- /dev/null +++ b/docs/design/play-mode.md @@ -0,0 +1,494 @@ +# Игра � компьютером (Maia): кнопка, диалог, �кран игры, конец партии + +Стату�: проект дизайнера, 2026-10-25, **не утверждён**. О�нова — запро� владельца («Играть»: им� и рейтинг по желанию, �ила Maia 600–2600 или от �воего рейтинга, цвет, контроль времени как на Lichess, во врем� игры — только до�ка и нотаци�, по�ле — обычна� парти�) и и��ледование аналитика `docs/research/play-mode.md` (требовани� R1–R21, пре�еты Lichess, теги PGN, объём v1). Где проект ра�ходит�� � и��ледованием, �то �казано �вно (§10). + +Опирает�� на код и документы: `apps/desktop/src/library.rs` (`shelf`, `compact_shelf`, `game_buttons`, `shelf_buttons_w`), `game_view.rs` (`show` — решение «р�дом/�топка», `header`, `side_panel`, `engine_panel`, `toolbar`, `keyboard`, `game_over`), `library-layout.md` §1.4 (�трока заголовка и её �ужение), `own-databases.md` §3.2–3.5 (Ctrl+S, «Добавить в базу», вопро� «Парти� изменена», «Данные партии»), `narrow-windows.md` (об�зательные правила узких окон), `user-comments.md` (�трелки и комментарии), `engine-download.md` (получение движка по запро�у). Снимки 0.17-dev: `ef_main.png`, `ef_640.png` (�кран партии 1400 и 640), `x_1400.png`, `x_640.png` (библиотека) в scratchpad разработчика `dev2/`. + +Размеры — логиче�кие точки egui. Тек�ты — по-ру��ки, в �кобках англий�кий ключ `tr(...)`; �уще�твующие помечены «(е�ть)». Макеты: 1400 — 14 точек на знак (100 знаков), 640 — 10 точек на знак (64 знака), диалог — 10 точек на знак. Значки, которые ломают выравнивание ASCII, названы в тек�те. + +## 0. Главное + +1. **Вход** — «⚔ Играть» в �троке заголовка библиотеки, между «♟ �ова� парти�» и «📋 В�тавить PGN», клавиша **Ctrl+G** (предложение аналитика; �вободна). +2. **Один диалог** «Игра � компьютером»: Вы (им�, рейтинг) → Соперник (Maia 600–2600 и «Слабее · Как � · Сильнее») → Цвет → Врем� (плитки по категори�м, «Свой», «Без ча�ов») → «Играть». В�ё запоминает��; повторна� игра — Ctrl+G, Enter. +3. **Экран игры** — тот же �кран партии в режиме игры. Вме�то �троки движка и вкладок — две карточки ча�ов: �оперник вверху, вы внизу, нотаци� между ними (как на Lichess). Поло�а оценки — пу�тое ме�то (чтобы до�ка не прыгнула по�ле игры). Панель ин�трументов: ли�тание, переворот, «↶ Ход назад», «� Сдать��». В�ё о�тальное �крыто, а не �ерое. +4. **Конец** — �кран �разу �тановит�� обычной партией (движок, �правочник, комментарии, Ctrl+S), а �верху боковой панели — поло�а результата: «Вы выиграли · мат» и кнопки «📈 �нализировать», «↻ Реванш», «⚔ �ова� игра», «💾 Сохранить в базу…». +5. **Уход во врем� игры** — один вопро� «Парти� идёт» � трем� ответами: «Сдать�� и добавить в базу…», «Сдать�� и выйти», «Продолжить игру». Пока вопро� открыт, ча�ы �то�т. До первых ходов обеих �торон — уход без вопро�а. + +## 1. Кнопка «Играть» в библиотеке + +### 1.1. Ме�то + +Группа партий — «что положить на �кран»: нова� пу�та� до�ка, игра, парти� из буфера. «Играть» в�таёт **второй**: р�дом � «�овой партией» (владелец так и опи�ал), но перед «В�тавить PGN», которым пользуют�� реже. + +``` +1400, в�е подпи�аны (шаг 1 library-layout.md §1.4) +Базы ♟ �ова� парти� ⚔ Играть 📋 В�тавить PGN + Добавить базу ✚ �ова� база � Онлайн-партии ⚙ �а�тройки +┌───────────� ┌───────────� ┌───────────� ┌───────────� +│Mine │ │Alekhin │ │Anand 01-14│ │Дворецкий │ +└───────────┘ └───────────┘ └───────────┘ └───────────┘ +``` + +``` +640 (шаг 2: дей�тви� баз �вёрнуты) +Базы ♟ �ова� парти� ⚔ Играть 📋 В�тавить PGN + ▾ � ⚙ �а�тр. +``` + +| Элемент | Подпи�ь | Под�казка | Клавиша | Дей�твие | +|---|---|---|---|---| +| кнопка | «⚔ Играть» (`⚔ Play`) | «Парти� � компьютером Maia: он играет как человек выбранного рейтинга (Ctrl+G)» (`A game against Maia, a computer that plays like a human of the chosen rating (Ctrl+G)`) | Ctrl+G (только в библиотеке, как Ctrl+N) | `LibraryAction::Play` → диалог §2 | + +- Вид — обычный `ui.button`, как �о�еди; не главна� кнопка (акцентной заливки в �троке нет ни у кого). +- Значок `⚔` (U+2694) — проверить, что он е�ть в шрифтах программы; е�ли нет — `▶` (U+25B6). Подпи�ь не мен�ет��. + +### 1.2. Сужение + +Пор�док шагов `library-layout.md` §1.4 не мен�ет��, «Играть» входит в группу партий: + +1. в�ё подпи�ано; +2. дей�тви� баз → «+ ▾ �»; +3. группа партий и «�а�тройки» → значки «♟ ⚔ 📋 · ⚙»; под�казка значка начинает�� � названи� («Играть\nПарти� � компьютером Maia… (Ctrl+G)», правило `shelf_hint`); +4. �крывает�� заголовок «Базы». + +- Ширину добавить в `shelf_buttons_w`: тек�ты `[⚙ Settings, 📋 Paste PGN, ⚔ Play, ♟ New game]` / значки `["⚙", "📋", "⚔", "♟"]`. +- Проверка по `x_640.png`: на шаге 2 �права от «�» до «�а�тройки» �вободно ≈ 188 точек, «⚔ Играть» ≈ 75 — при 640 �трока о�таёт�� на шаге 2, подпи�и видны. Измерить на �нимке. +- **Компактна� полка** — то же: «♟ ⚔ 📋» в той же группе, пор�док тот же. +- **Пу�та� полка** (`library-layout.md` §1.5): �трока под карточками — «или ♟ �ова� парти� — без базы · ⚔ Играть � компьютером» (`or ♟ New game — without a database · ⚔ Play the computer`), две кнопки-��ылки. +- �а �кране партии кнопки нет: начать игру из открытой партии — через библиотеку или кнопками поло�ы результата (§5). «Играть от�юда» (� позиции) — не v1. + +## 2. Диалог «Игра � компьютером» + +### 2.1. Вид + +`egui::Modal`, ширина **520** (в узком окне — `min(520, W − 32)`), заголовок «Игра � компьютером» (`Play the computer`). Блоки �верху вниз — в пор�дке, в котором один вли�ет на другой: рейтинг задаёт �илу �оперника. + +``` +┌─ Игра � компьютером ─────────────────────────────────� +│ Вы │ +│ Им� [Иванов Сергей ] Рейтинг [1350] │ +│ �е об�зательно. По рейтингу подбирает�� �оперник. │ � �лабым +│ │ +│ Соперник — Maia 1400 · как вы │ +│ 600 ������������������������������������������ 2600 │ +│ [ Слабее ] [▌Как ��] [ Сильнее ] │ +│ Maia — нейро�еть: ходит как человек �того рейтинга │ � �лабым +│ на Lichess и ошибает�� так же. │ +│ │ +│ Цвет │ +│ [ ♔ Белые ] [▌� Случайно�] [ ♚ Чёрные ] │ +│ │ +│ Врем� │ +│ Пул� [ 1+0 ] [ 2+1 ] │ +│ Блиц [ 3+0 ] [ 3+2 ] [ 5+0 ] [▌5+3�] │ +│ Рапид [10+0 ] [10+5 ] [15+10] │ +│ Кла��ика [30+0 ] [30+20] │ +│ [ Свой… ] [ Без ча�ов ] │ +│ │ +│ [▌Играть�] [Отмена] │ +└──────────────────────────────────────────────────────┘ +``` + +**Вы** (`You`, заголовок блока — как группы в панели фильтров). +- «Им�» (`Name`) — поле, общее � «Ваше им�» в на�тройках (`Settings.your_name`, `own-databases.md` §7): одно им� дл� комментатора и дл� игры. Под�казка в пу�том поле — «как запи�ать в партию» (`as written in the game`). +- «Рейтинг» (`Rating`) — поле 64, только цифры, до 4 знаков; пу�то — рейтинга нет. Допу�тимо 100–3000; вне — кра�на� рамка, под�казка «Рейтинг от 100 до 3000» (`A rating from 100 to 3000`), «Играть» неактивна. Под�казка пол�: «Примерно как на Lichess: Maia �читает в его рейтингах» (`Roughly your Lichess rating: Maia counts in those`) — до ответа владельца на вопро� аналитика № 1. +- Слаба� �трока: «�е об�зательно. По рейтингу подбирает�� �оперник.» (`Optional. The opponent is matched to your rating.`). +- Хранение: им� и рейтинг пишут�� в на�тройки **при нажатии «Играть»** (не на каждую букву; «Отмена» ничего не мен�ет). �овое поле `Settings.your_rating: Option`; в «�а�тройки → Интерфей� → Свои базы» р�дом � «Ваше им�» — поле «Ваш рейтинг» (`Your rating`), та же проверка. + +**Соперник** (`Opponent`). +- Заголовок � текущей �илой: «Соперник — Maia 1400» (`Opponent — Maia {elo}`); при выбранной отно�ительной �иле — «· как вы» / «· на 200 �лабее» / «· на 200 �ильнее» (`· like you`, `· 200 weaker`, `· 200 stronger`). +- Ползунок 600–2600, шаг 100, подпи�и концов �лабым. Клавиатура: �/→ — ±100, Home/End — концы. +- Три переключател� «Слабее» (`Weaker`), «Как �» (`Like me`), «Сильнее» (`Stronger`): �ила = рейтинг −200 / ±0 / +200, округление до 100, обрезка в 600–2600. **Это режим, а не разова� кнопка:** выбранный переключатель запоминает�� (`Strength::Relative(−200 | 0 | +200)`), и при изменении рейтинга — �ейча� или в �ледующий раз — �ила пере�читывает��; ползунок ходит �ам. Сдвиг ползунка рукой �нимает выбор (`Strength::Fixed(elo)`). +- Без рейтинга переключатели неактивны, под�казка «Укажите �вой рейтинг выше» (`Enter your rating above`); �ила — по ползунку (впервые 1500). Е�ли рейтинг �тёрт при выбранном «Как �» — о�таёт�� по�леднее значение как фик�ированное. +- Слаба� �трока про Maia — одна на ве�ь диалог; она объ��н�ет, почему «1400» — �то «человек», а не уровень 1–8. + +**Цвет** (`Colour`): три переключател� «Белые» (`White`), «Случайно» (`Random`), «Чёрные» (`Black`), 140 × 40. Значок — король из **текущего набора фигур** 20 точек (белый, чёрный, дл� «Случайно» — разрезанный по диагонали), а не �имвол шрифта: �овпадает � до�кой и не зави�ит от глифов. Впервые — «Случайно» (как Lichess). + +**Врем�** (`Time`): +- Строки по категори�м Lichess, подпи�ь категории �лева (колонка = ширина �амой длинной подпи�и текущего �зыка): «Пул�» (`Bullet`) 1+0, 2+1 · «Блиц» (`Blitz`) 3+0, 3+2, 5+0, 5+3 · «Рапид» (`Rapid`) 10+0, 10+5, 15+10 · «Кла��ика» (`Classical`) 30+0, 30+20. Пре�еты и категории — и��ледование §2.1 (`PoolList.scala`, формула `база + 40 × прибавка`). +- Плитка 64 × 36, тек�т «5+3» 16 точек; выбранна� — заливка выделени� и жирный (как переключатели «Результат» в фильтрах). Под�казка плитки — «5 минут + 3 �екунды за ход» (`5 minutes + 3 seconds a move`). +- По�ледн�� �трока: «Свой…» (`Custom…`) и «Без ча�ов» (`No clock`) — шире, по тек�ту. +- **«Свой»** ра�крывает под �еткой два ползунка �о шагами Lichess (и��ледование §2.1) и �троку-итог; при выборе другой плитки они и�чезают (диалог мен�ет вы�оту — допу�тимо, �то ответ на щелчок): + +``` +│ [▌Свой�] [ Без ча�ов ] │ +│ Минуты ��������������������������������� 7 │ +│ Прибавка ��������������������������������� 2 � │ +│ 7+2 · около 8 мин у каждого · рапид │ � �лабым +``` + + - Подпи�и: «Минуты» (`Minutes`), «Прибавка» (`Increment`), значение �права: «¼», «½», «1½», «7»; «2 �» (`2 s`). Итог: «{tc} · около {n} мин у каждого · {категори�}» (`{tc} · about {n} min each · {category}`). + - Значени� — по�ледние �вои; впервые 7+2. **0+0 нельз�** (как у Lichess): итог «�ужны минуты или прибавка» (`Set minutes or an increment`) кра�ным, «Играть» неактивна. База 0 � прибавкой — можно (начальное врем� = прибавка, не меньше 3 �, R5). +- **«Без ча�ов»** — ча�ов нет ни у кого; категории в шапке нет. +- Впервые выбрано **10+0**: обычный рапид, �покойный дл� ученика и не «вечный». Владелец может предпоче�ть «Без ча�ов» (как у компьютера Lichess) — вопро� §11. +- Пули (1+0, 2+1) в v1 о�тают��, хот� предварительных ходов нет: в под�казке плиток пули — «Без предварительных ходов �то очень бы�тро» (`Without premoves this is very fast`). Решение владельца — вопро� аналитика № 4. + +**Кнопки**: «Играть» (`Play`) — главна�, «Отмена» (`Cancel`, е�ть); пор�док как в `own-databases.md` (главна� левее, прижаты вправо). + +### 2.2. Клавиатура и фоку� + +- Фоку� при открытии — **на «Играть»**: прошлые на�тройки уже �то�т, Enter �разу начинает (�ценарий С2). Tab — по блокам �верху вниз; внутри групп переключателей �/→ мен�ют выбор. +- Enter в любом ме�те, включа� пол� имени и рейтинга, — «Играть» (как «Готово» в «Данных партии»). Esc — «Отмена». +- Щелчок вне окна диалог не закрывает (там пол� ввода). + +### 2.3. Запоминание + +`Settings.play` (новое): `strength: Fixed(u16) | Relative(i16)`, `colour: White | Random | Black`, `time: Preset(index) | Custom { minutes_step, increment_step } | NoClock`, `custom` (по�ледние значени� ползунков, даже когда выбран пре�ет). Пишет�� при «Играть». Первое открытие: 1500, «Случайно», 10+0. + +### 2.4. Со�то�ни� + +- **Maia не у�тановлена.** Блоки диалога те же; над кнопками — �трока «Дл� игры нужна Maia (≈ 21 МБ). Скачать один раз.» (`Maia is needed to play (≈ 21 MB). Downloaded once.`), главна� кнопка — «Скачать и играть» (`Download and play`). Дальше — �о�то�ни� окна из `engine-download.md` §2.5–2.8 **в �том же диалоге** (поло�а «8 из 21 МБ · 38 %», проверка, ошибки � «Повторить»); по�ле у�тановки парти� начинает�� �ама — «запрошенное дей�твие». Без интернета — ошибка §2.8 там же. Как по�тавл�ет�� Maia и в каком виде (вопро� аналитика № 8) — до �того решени� макет �о�то�ни� у�ловный. +- **Maia загружает��** (первый запу�к в �еан�е может зан�ть �екунды): диалог закрывает�� �разу, �кран игры открыт, в карточке �оперника — «загружает��…» (§3.3). Ча�ы ещё не идут (они пойдут по�ле первых ходов), по�тому ожидание ничего не �тоит. +- **�е удало�ь запу�тить Maia** — �кран игры не открывает��: диалог о�таёт��, над кнопками кра�ным «Maia не запу�тила�ь: {причина}» (`Maia did not start: {reason}`) и «Подробнее» (�ворачиваемый тек�т ошибки). + +### 2.5. Узкое окно + +- Ширина `min(520, W − 32)`: при 640 — 520, помещает��. Сетка времени: колонка подпи�ей ≈ 72 + 4 × (64 + 6) = 352, им� + рейтинг — поле имени гибкое (не уже 160). +- Вы�ота: �одержимое ≈ 560 (≈ 620 � ра�крытым «Свой»). Е�ли `H − 32` меньше — блоки в `ScrollArea`, **�трока кнопок вне прокрутки**, в�егда видна. При 640 × 480 прокручивает��; при 640 × 900 — нет. + +## 3. Экран игры + +### 3.1. Принцип + +Это **тот же `GameView`** � признаком игры (R6, `play: Option`). Решение «р�дом / �топка» — та же функци� ширины и вы�оты окна (`narrow-windows.md` §3.1), **� теми же допущени�ми** (поло�а оценки зарезервирована). По�тому по�ле конца партии �кран не пере�траивает��: и�чезают ча�ы и по�вл�ют�� �трока движка и вкладки, до�ка о�таёт�� на ме�те (един�твенное и�ключение — �топка, §7.2). + +До�ка повёрнута �тороной пользовател� вниз. Ме�то поло�ы оценки �лева от до�ки — **пу�тое** (поло�ы нет, ме�то держит��). + +### 3.2. 1400 × 900, р�дом + +``` +┌──────────────────────────────────────────────────────────────────────────────────────────────────� +│ ⬅ Библиотека │ Вы — Maia 1500 [5+3] ⚙ �а�тройки │ +│ │ Парти� � компьютером · блиц │ +├──────────────────────────────────────────────────────────────────┬───────────────────────────────┤ +│ ┌───────────────────────────────────────────────────────────� │┌─────────────────────────────�│ +│ │8 │ ││ ♚ Maia 1500 4:52 ││ � не её ход: приглушено +│ │ │ ││ ждёт ││ +│ │ │ │└─────────────────────────────┘│ +│ │ │ │ 1 e4 e5 │ +│ │ │ │ 2 Nf3 Nc6 │ +│ │ до�ка ≈ 832, белые �низу │ │ 3 Bb5 a6 │ +│ │ │ │ 4 Ba4 ▌Nf6� │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │┌─────────────────────────────�│ +│ │ │ ││▌♔ Вы · 1350 3:07 �││ � ваш ход: заливка +│ │1 a h │ ││▌ ваш ход �││ +│ └───────────────────────────────────────────────────────────┘ │└─────────────────────────────┘│ +│ ↑ ме�то поло�ы оценки (пу�то) │ � ◀ ▶ � │ 🔃 │ ↶ Ход назад │ � Сдать�� +└──────────────────────────────────────────────────────────────────┴───────────────────────────────┘ +``` + +Бокова� панель (та же `Panel::right("game_side")`, та же ширина, что у обычной партии) �верху вниз: + +1. карточка �оперника; +2. нотаци� (в�� о�тавша��� вы�ота); +3. �трока про�мотра (только когда ли�тают назад, §3.6); +4. карточка пользовател�; +5. панель ин�трументов §3.5. + +Карточки у верхнего и нижнего кра� панели, т. е. примерно на уровне верхнего и нижнего кра� до�ки — «�оперник напротив, вы у �еб�», как на Lichess. При перевороте до�ки (F) карточки мен�ют�� ме�тами: �верху в�егда тот, чьи фигуры �верху (R9). + +### 3.3. Карточка ча�ов + +Вы�ота 56, на в�ю ширину панели, �кругление и фон как у блока комментари� (`ef_main.png`), от�тупы 8. + +``` +┌─────────────────────────────� +│ ♔ Вы · 1350 3:07 │ � король 18 (набор фигур), им� 15, рейтинг �лабым; врем� моно 30 +│ ваш ход │ � �о�то�ние, 13, �лабым +└─────────────────────────────┘ +``` + +- **Им�:** «Вы» (`You`) — в игре �то пон�тнее, чем �воё им�; рейтинг �лабым по�ле «·», е�ли задан. Соперник — «Maia 1500». +- **Врем�:** моноширинный шрифт 30 (цифры не прыгают), прижато вправо. Формат `м:��`; от ча�а — `ч:мм:��`; меньше 10 � — де��тые: `0:08.4`. Считает�� по монотонным ча�ам (R10). +- **Со�то�ни�** (�трока под именем и вид карточки): + +| Со�то�ние | Строка | Вид | +|---|---|---| +| не его ход | «ждёт» (`waiting`) у Maia; у пользовател� — пу�то | фон панели, врем� обычным цветом | +| ход пользовател�, ча�ы идут | «ваш ход» (`your move`) | заливка выделени� (`selection.bg_fill` �лабо), врем� �рким | +| ход Maia | «думает…» (`thinking…`), три точки анимированы | то же выделение | +| до первых ходов | у того, кто ходит: «ваш ход · ча�ы пойдут по�ле первого хода каждой �тороны» (`your move · the clocks start after each side's first move`), �окращает�� � «…»; у Maia — «думает…» | выделение, врем� полное, не убывает | +| мало времени (`≤ emergSeconds`: 1+0 → 10 �, 3+0 → 22 �, 5+0 → 37 �, ≥ 10+0 → 60 �) | без изменений | врем� **кра�ным** (`error_fg_color`), рамка карточки кра�на� 1,5 | +| врем� вышло | «врем� вышло» (`time is up`) | `0:00` кра�ным; через кадр — конец партии §5 | +| Maia загружает�� | «загружает��…» (`loading…`) | выделение, ча�ы не идут | +| без ча�ов | как выше, но без времени | врем� не ри�ует��, им� на в�ю ширину | + +- Звук при входе в «мало времени» (� 2026-10-27): один раз за партию, когда **ча�ы пользовател�** �танов�т�� кра�ными, — двойной тик `Sound::LowTime` (`assets/sounds/common/LowTime.ogg`, из Kenney «Interface Sounds», CC0; один дл� в�ех наборов, как `Wrong`). Ча�ы �оперника не звучат. Выключенный звук в на�тройках выключает и его. Звуки ходов, вз�тий, шаха — как в обычной партии; конец партии — `Checkmate`, е�ли он е�ть в наборе. +- Maia **не проигрывает по времени** (R15), по�тому кра�ной её карточка практиче�ки не бывает; правило одно дл� обеих. + +### 3.4. Шапка + +``` +⬅ Библиотека │ Вы — Maia 1500 [5+3] ⚙ �а�тройки + │ Парти� � компьютером · блиц +``` + +- �азвание — белые — чёрные, как в�егда, но пользователь назван «Вы»: «Вы — Maia 1500» белыми, «Maia 1500 — Вы» чёрными (`You`). �е кликает�� (нет «Данных партии» в игре). +- **Чип контрол�** «5+3» — на ме�те чипа результата, тем же видом; «Без ча�ов» — чип «∞» � под�казкой «Бе��рочно» (`Unlimited`, как в окне «Играть»); у чипа контрол� под�казка «Контроль времени» (`Time control`). По�ле конца на �том ме�те — результат «1-0»: чип не прыгает. +- Подзаголовок: «Парти� � компьютером · {категори�}» (`Game vs computer · {category}`), без ча�ов — «Парти� � компьютером». +- Слева — «⬅ Библиотека» (ведёт к вопро�у §6). Справа — только «⚙ �а�тройки» (вид до�ки и звук можно мен�ть, ча�ы при �том идут). **Скрыты:** «� �айти в базе», «�», «⚠/ℹ заметки», «•» не�охранённой партии, «⬅ К партии …». + +### 3.5. Панель ин�трументов + +``` +� ◀ ▶ � │ 🔃 │ ↶ Ход назад │ � Сдать�� +``` + +| Кнопка | Подпи�ь / под�казка | Клавиша | Когда активна | +|---|---|---|---| +| � ◀ ▶ � | как �ейча� (е�ть) | Home � → End, ↓ ↑ | в�егда; только про�мотр (§3.6) | +| 🔃 | «Перевернуть до�ку (F)» (е�ть) | F | в�егда | +| ↶ Ход назад | «Вз�ть ход назад (Ctrl+Z)» (`Take back a move (Ctrl+Z)`) | Ctrl+Z | по�ле первого хода пользовател� | +| � Сдать�� | «Сдать��» (`Resign`) | нет (чтобы не �дать�� �лучайно) | по�ле первых ходов обеих �торон; до них на �том ме�те «✕ Прервать» (`✕ Abort`, под�казка «Выйти без результата: ходы ещё не �деланы» — `Leave without a result: no moves made yet`) | + +- **Ход назад** (R21; � 2026-10-27 — только в блице, в о�тальных контрол�х и без ча�ов кнопки и Ctrl+Z нет, `decisions.md` «Ход назад — только в блице»): е�ли ход пользовател� — �нимают�� ответ Maia и предыдущий ход пользовател�; е�ли Maia думает — �нимает�� ход пользовател�, её ра�чёт отбра�ывает�� (R14). Ча�ы не возвращают��. Ходы удал�ют��, а не �танов�т�� вариантом. Е�ли пользователь чёрными и е�ть только первый ход Maia — неактивна. +- **Сдать��** — подтверждение на ме�те, без окна (ча�ы идут, модальное окно зде�ь лишнее): кнопка превращает�� в «Сдать��? [Да] [�ет]» (`Resign? [Yes] [No]`), «Да» — кра�ной заливкой. Отмена — «�ет», Esc, ход любой �тороны или 4 � без дей�тви�. «Да» → конец §5. +- **Прервать** — без подтверждени� (тер�ть нечего): �кран закрывает��, возврат в библиотеку, парти� не �охран�ет�� (R20). +- Скрыты (не �ерые): ↩ ↪, ☰, 💾, 📋, 📈. Группы перено��т�� по `narrow-windows.md` §4a; группа «↶ Ход назад · � Сдать��» — одна, при ширине панели меньше её подпи�анной ширины кнопки �танов�т�� значками «↶ �» � подпи��ми в под�казках. + +### 3.6. �отаци� и про�мотр + +- �отаци� — та же таблица «№ · белые · чёрные», только главна� лини�, **только чтение**: щелчок по ходу показывает позицию; правый щелчок по ходу меню не открывает; Enter, 1–6, двойной щелчок ничего не делают. По�ледний ход выделен, нотаци� прокручена к нему. +- **Ли�тание назад** не мешает игре: ча�ы идут. Под нотацией по�вл�ет�� �трока «Про�мотр: 12…Nf6 · к игре — End» (`Viewing 12…Nf6 · back to the game — End`), �лабым, в�� �трока — ��ылка. Попытка хода в прошлой позиции не делает хода: до�ка возвращает�� к текущей позиции (фигура на ме�то). Ход Maia возвращает к текущей позиции �ам — его нужно увидеть. +- Во врем� хода Maia фигуры пользовател� не перета�кивают�� (предварительных ходов в v1 нет); кур�ор обычный. +- **Стрелки и выделени� правой кнопкой** работают, но **в партию не пишут��**: они временные и �тирают�� �ледующим ходом (как на Lichess). Иначе кажда� �трелка �тановила�ь бы комментарием `[%cal]` в �ыгранной партии. + +### 3.7. Что �крыто и что делают клавиши + +| Во врем� игры нет | Клавиша | Что при нажатии | +|---|---|---| +| �трока движка, линии, �трелки движка, поло�а оценки | L | то�т «Во врем� партии движок выключен — анализ по�ле конца» (`The engine is off during the game — analyse after it ends`) | +| «�нализ партии», график, вкладка «Отчёт» | Shift+A | тот же то�т | +| вкладка «Справочник» (вкладок нет вов�е) | — | — | +| «�айти в базе» | Ctrl+Shift+F | ничего | +| редактор комментариев и значков, варианты | Enter, 1–6, Shift+↑/↓ | ничего | +| «Данные партии», �охранение, копирование | F2, Ctrl+S, Ctrl+Shift+S, Ctrl+Shift+C | ничего | +| отмена правок | Ctrl+Z / Ctrl+Y | Ctrl+Z = «Ход назад»; Ctrl+Y — ничего | +| перевод комментариев | Ctrl+Shift+T | ничего | +| — | Esc, Ctrl+W | вопро� «Парти� идёт» (§6); е�ли открыт «Сдать��? Да/�ет» — Esc �начала закрывает его | + +То�т только дл� L и Shift+A: �ти клавиши жмут по привычке и должны получить ответ; о�тальные про�то молчат. + +### 3.8. Сбой Maia + +Е�ли проце�� Maia завершил�� или не ответил за таймаут: ча�ы обеих �торон **о�танавливают��** (вина программы, не игрока), над карточкой �оперника — блок: + +``` +┌─────────────────────────────� +│ Maia пере�тала отвечать. │ +│ [Перезапу�тить] [Прервать] │ +└─────────────────────────────┘ +``` + +`Maia stopped responding.` · `Restart` (новый проце��, позици� передаёт�� в�ей и�торией ходов, R12; ча�ы продолжают � того же ме�та) · `Abort` (парти� заканчивает�� без результата `*`, �кран �тановит�� обычной партией; её можно �охранить, `Termination "Unterminated"`). + +## 4. Окно и �и�тема во врем� игры + +- Свёрнутое окно, другое окно в фоку�е — ча�ы идут (как на Lichess); Maia ходит, звук хода е�ть. +- Сон компьютера — по и��ледованию, критерий 9: фактиче�кое поведение зафик�ировать при проверке. +- Окно «�а�тройки» поверх игры — ча�ы идут. + +## 5. Конец партии + +### 5.1. Что прои�ходит + +В один кадр: +1. результат пишет�� в документ и теги (и��ледование §5: `Result`, `Termination`, `TimeControl`, `WhiteElo/BlackElo`, `WhiteType/BlackType`, `[%clk]`), признак игры �нимает��; +2. �кран �тановит�� **обычной новой партией**: в боковой панели — �трока «�нализ: выкл», вкладки «�отаци� · Справочник · Отчёт», полна� панель ин�трументов; шапка — на�то�щие имена «Иванов Сергей — Maia 1500», чип результата «0-1», «•» не�охранённой партии, название �нова открывает «Данные партии»; подзаголовок — «Парти� � компьютером, блиц · 2026.10.25» (из тегов `Event`, `Date`); +3. �верху боковой панели — **поло�а результата**; +4. звук конца (е�ли е�ть в наборе); кур�ор — на по�леднем ходе. + +Движок �ам не включает�� (L, как в�егда). Ме�то поло�ы оценки уже было, до�ка не двигает��. + +### 5.2. Поло�а результата + +``` +1400 × 900, по�ле конца +├──────────────────────────────────────────────────────────────────┬───────────────────────────────┤ +│ ┌───────────────────────────────────────────────────────────� │┌─────────────────────────────�│ +│ │ │ ││ [0-1] Вы проиграли ││ � 17, жирным +│ │ │ ││ врем� вышло ││ +│ │ │ ││ О�тало�ь: вы 0:00 · Maia 2:41│ � �лабым +│ │ │ ││ [▌📈 �нализировать�] [↻ Реванш]│ +│ │ до�ка (не �двинула�ь) │ ││ [⚔ �ова� игра] [💾 Сохранить в базу…] ×│ +│ │ │ │└─────────────────────────────┘│ +│ │ │ │ �нализ: выкл · Stockfish 19 ⚙│ +│ │ │ │ [�отаци�] Справочник Отчёт │ +│ │ │ │ 1 e4 e5 │ +│ │ │ │ … │ +│ └───────────────────────────────────────────────────────────┘ │ � ◀ ▶ � │ 🔃 ↩ ↪ │ ☰ 💾 📋 │ 📈 │ +└──────────────────────────────────────────────────────────────────┴───────────────────────────────┘ +``` + +Тек�ты: чип результата + заголовок + причина. Заголовок — � точки зрени� пользовател�: + +| И�ход | Чип | Заголовок | Причина | +|---|---|---|---| +| мат Maia | 1-0 / 0-1 | «Вы выиграли» (`You won`) | «мат» (`checkmate`) | +| мат пользователю | | «Вы проиграли» (`You lost`) | «мат» | +| врем� пользовател� вышло | | «Вы проиграли» | «врем� вышло» (`time is up`) | +| врем� вышло, у Maia нечем матовать | ½-½ | «�ичь�» (`Draw`) | «врем� вышло, но у Maia нечем по�тавить мат» (`time is up, but Maia cannot checkmate`) | +| �дача | | «Вы �дали�ь» (`You resigned`) | — | +| пат | ½-½ | «�ичь�» | «пат» (`stalemate`) | +| повторение | ½-½ | «�ичь�» | «позици� повторила�ь трижды» (`the position occurred three times`) | +| 50 ходов | ½-½ | «�ичь�» | «50 ходов без вз�тий и ходов пешек» (`50 moves without a capture or a pawn move`) | +| мало материала | ½-½ | «�ичь�» | «ни у кого нет материала дл� мата» (`neither side can checkmate`) | +| прервано из-за �бо� (§3.8) | * | «Парти� прервана» (`Game aborted`) | — | + +- «О�тало�ь: вы {t} · Maia {t}» (`Left: you {t} · Maia {t}`) — итог ча�ов; без ча�ов �троки нет. +- Кнопки (перено��т�� по ширине, главна� — перва�): + - **«📈 �нализировать»** (`📈 Analyse`) — главна�. То же, что 📈 / Shift+A: окно «�нализ партии» � прошлыми на�тройками, Enter запу�кает; без Stockfish — предложение �качать (`engine-download.md` §1.2). Отдельного пути анализа нет. + - **«↻ Реванш»** (`↻ Rematch`), под�казка «Те же на�тройки, цвета мен�ют��» (`Same settings, colours swapped`). При «Случайно» — �нова �лучайно. + - **«⚔ �ова� игра»** (`⚔ New game`) — диалог §2 � прошлыми на�тройками. �азвание отличает�� от «�овой партии» (пу�та� до�ка), значок тот же, что у «Играть». + - **«💾 Сохранить в базу…»** (`💾 Save to a database…`), под�казка «Ctrl+S». Поток `own-databases.md` §3.3: �пи�ок баз → «Данные партии» в режиме добавлени�, предзаполнены (имена, Эло, дата, результат, турнир «Парти� � компьютером, блиц») → дубль → запи�ь. По�ле запи�и кнопка �тановит�� тек�том «✓ В «Мои партии», № 13» (`✓ In “{name}�, No. {n}`). + - **×** — убрать поло�у. +- Поло�а держит��, пока её не закрыли, пока пользователь не начал править партию (ход, комментарий, данные) или не ушёл. �нализ поло�у не убирает. +- **Реванш и �ова� игра замен�ют не�охранённую партию**, по�тому перед заменой — обычный вопро� `own-databases.md` §3.4 «Парти� изменена · Добавить партию в �вою базу?» («Добавить в базу…» / «�е �охран�ть» / «Отмена»). Дл� «�овой игры» вопро� задаёт�� **при нажатии «Играть»** в диалоге (отмена диалога ничего не тер�ет); «Отмена» в вопро�е возвращает к диалогу. +- �вто�охранени� нет: как у «�овой партии», запи�ь — �вное дей�твие (и��ледование, вопро� № 9). + +## 6. Уход во врем� игры + +Поводы: «⬅ Библиотека», Esc, Ctrl+W, закрытие окна программы. + +- **До первых ходов обеих �торон** — ухода не �прашиваем: парти� прерывает�� без результата и не �охран�ет�� (R20). +- **Иначе** — вопро�; пока он открыт, **ча�ы обеих �торон �то�т и Maia не ходит** (ответ, пришедший за �то врем�, держит�� до закрыти� вопро�а и примен�ет�� только при «Продолжить игру»): + +``` +┌─ Парти� идёт ──────────────────────────────────────────────� +│ Maia 1500 · вы белыми · 5+3 · 24-й ход │ � �лабым +│ Е�ли выйти, парти� закончит�� вашей �дачей. │ +│ │ +│ [Сдать�� и добавить в базу…] [Сдать�� и выйти] [Продолжить игру] │ +└────────────────────────────────────────────────────────────┘ +``` + +- Под заголовком �лабым — кака� �то парти� (� 2026-10-27): �оперник (у Rodent — и �тиль), цвет пользовател�, контроль («без ча�ов»), номер хода — те же �лова, что на карточке отложенной партии. +- Заголовок «Парти� идёт» (`The game is on`); тек�т «Е�ли выйти, парти� закончит�� вашей �дачей.» (`If you leave, the game ends with your resignation.`). Modal 460, `confirm_dialog` по образцу §3.4. +- «Сдать�� и добавить в базу…» (`Resign and add to a database…`) — результат «�дача», затем поток «Добавить в базу» (§5.2); по�ле запи�и уход продолжает�� (`close_after_save`); «Отмена» в нём — парти� уже закончена, �кран о�таёт�� на �ыгранной партии � поло�ой результата (уход не продолжает��, ничего не потер�но). +- «Сдать�� и выйти» (`Resign and leave`) — результат пишет��, парти� не �охран�ет��, уход (или закрытие программы). +- «Продолжить игру» (`Keep playing`) — Esc; ча�ы продолжают. +- Enter **ничего не нажимает** (вопро� по�вл�ет�� от Esc — как в `own-databases.md` §3.4). +- При закрытии программы — тот же вопро�; второй вопро� «Парти� изменена» не задаёт��: �тот уже �про�ил про базу. + +## 7. Узкие окна + +Об�зательные правила `narrow-windows.md` дей�твуют без и�ключений; ниже — только то, что добавл�ет игра. + +### 7.1. Р�дом (640 × 480, 800 × 1000, 960 × 1050) + +- Бокова� панель не уже `SIDE_MIN` = 240: карточка (им� �окращает�� � «…», врем� 30 моно не �окращает��) + нотаци� + карточка + панель ин�трументов в две �троки по группам: «� ◀ ▶ � │ 🔃» / «↶ Ход назад │ � Сдать��» (при нехватке — «↶ �»). +- 640 × 480: вы�ота под шапкой ≈ 430 → карточки 2 × 56, панель 2 × 44, нотации ≈ 220 (7 �трок). Со�то�ние «до первых ходов» �окращает�� � «…», полное — в под�казке. +- Шапка: правило `narrow-windows.md` §3.4 — «⬅» и «⚙» значками, название «Вы — Maia 1500» �окращает��, чип «5+3» виден в�егда. +- Поло�а результата в панели 240: «📈 �нализировать» — отдельна� �трока, затем «↻ Реванш · ⚔ �ова� игра», затем «💾 Сохранить в базу…»; × — в �троке заголовка поло�ы. + +### 7.2. Стопка (640 × 900, 640 × 1000, 720 × 1000) + +При 640 × 900 решение §3.1: `board_side` = 350, `board_stack` = 584 ≥ 1,25 × 350 → �топка. Карточки зде�ь — **поло�ы над и под до�кой** (в центральной панели, ширина до�ки � ме�том поло�ы оценки), а не в нижней панели: «�оперник напротив» должен быть у до�ки. + +``` +640 × 900, игра +┌──────────────────────────────────────────────────────────────� +│ ⬅ │ Вы — Maia 1500 [5+3] ⚙ │ +│ │ Парти� � компьютером · блиц │ +├──────────────────────────────────────────────────────────────┤ +│ ┌──────────────────────────────────────────────────────� │ +│ │ ♚ Maia 1500 · думает… 4:52 │ │ � поло�а 36, выделение (её ход) +│ └──────────────────────────────────────────────────────┘ │ +│ ┌──────────────────────────────────────────────────────� │ +│ │ │ │ +│ │ до�ка ≈ 504 │ │ +│ │ │ │ +│ └──────────────────────────────────────────────────────┘ │ +│ ┌──────────────────────────────────────────────────────� │ +│ │ ♔ Вы · 1350 3:07 │ │ � поло�а 36 +│ └──────────────────────────────────────────────────────┘ │ +├��������������������� разделитель (т�нуть) �������������������┤ +│ 1 │ e4 e5 │ +│ 2 │ Nf3 Nc6 │ +│ 3 │ Bb5 ▌a6� │ +│ … │ +│ � ◀ ▶ � │ 🔃 │ ↶ Ход назад │ � Сдать�� │ +└──────────────────────────────────────────────────────────────┘ +``` + +- Поло�а-карточка — одна �трока 36: король, им�, «· �о�то�ние» �лабым, врем� моно 24 �права. Со�то�ни� и цвета — как §3.3. +- �ижн�� панель — нотаци� + панель ин�трументов; вы�ота по умолчанию — как у обычной �топки (`STACK_BOTTOM_MIN` и далее по §3.3 `narrow-windows.md`), т. е. нотации до�таёт�� больше �трок, чем в обычной партии (нет �троки движка и вкладок). +- До�ка = `min(W − 16 − EVAL_BAR, вы�ота центральной ча�ти − 2 × 40)`, не меньше `BOARD_MIN`. +- **По�ле конца** поло�ы ча�ов и�чезают, до�ка выра�тает на ≈ 80 — один раз, по �обытию «парти� окончена», а не от размера окна; �то допу�тимо (правило «без мигани�» ка�ает�� изменени� размеров окна). Поло�а результата — первой �трокой нижней панели, кнопки в одну-две �троки. + +``` +640 × 900, по�ле конца +├──────────────────────────────────────────────────────────────┤ +│ ▌┌────────────────────────────────────────────────────� │ +│ ▌│ до�ка ≈ 584 │ │ +│ ▌└────────────────────────────────────────────────────┘ │ +├�������������������������������������������������������������─┤ +│ [0-1] Вы проиграли · врем� вышло · вы 0:00 · Maia 2:41 × │ +│ [▌📈 �нализировать�] [↻ Реванш] [⚔ �ова� игра] [💾 Сохранить…]│ +│ �нализ: выкл · Stockfish 19 ⚙ │ +│ [�отаци�] Справочник Отчёт │ +│ 1 │ e4 e5 │ +└──────────────────────────────────────────────────────────────┘ +``` + +### 7.3. Диалоги + +- «Игра � компьютером» — §2.5. +- «Парти� идёт» — ширина `min(460, W − 32)`; три кнопки при нехватке перено��т�� (кажда� на �вою �троку, по ширине окна, главна� �верху). + +## 8. Клавиатура — �водка + +| Клавиша | Где | Дей�твие | Сегодн� | +|---|---|---|---| +| Ctrl+G | библиотека | диалог «Игра � компьютером» | �вободна | +| Enter / Esc | диалог | «Играть» / «Отмена» | — | +| � → Home End ↑ ↓ | игра | про�мотр ходов | как в партии | +| F | игра | перевернуть до�ку (карточки мен�ют�� ме�тами) | как в партии | +| Ctrl+Z | игра | вз�ть ход назад | в партии — отмена правки | +| Esc, Ctrl+W | игра | закрыть «Сдать��? Да/�ет», иначе вопро� «Парти� идёт» | в партии — в библиотеку | +| L, Shift+A | игра | то�т «Во врем� партии движок выключен…» | движок / анализ | +| Ctrl+S | по�ле конца | «Добавить в базу…» | как в партии | + +## 9. Что �троит разработчик (компоненты) + +1. `library.rs`: кнопка в `game_buttons`, ширина в `shelf_buttons_w`, `LibraryAction::Play`, Ctrl+G; �трока пу�той полки. +2. �овый модуль диалога (`play_dialog.rs`): §2, `Settings.play`, `Settings.your_rating`, поле «Ваш рейтинг» в на�тройках; �о�то�ние «Maia не у�тановлена» — переи�пользовать окно загрузки `engine-download.md`. +3. `GameView`: `play: Option` (на�тройки, ча�ы, �о�то�ние Maia, подтверждение �дачи); в `show()` — та же функци� «р�дом/�топка»; `side_panel` в игре — карточки + нотаци� только дл� чтени� + �трока про�мотра; в �топке — поло�ы в `board_area`; `header`, `toolbar`, `keyboard` — ветки игры по таблицам §3.4–3.7; поло�а оценки — ме�то без поло�ы. +4. Ча�ы и Maia — по и��ледованию (R10, R12–R16); ответ на у�таревшую позицию отбра�ывает��. +5. Конец: определение повторени� и 50 ходов (�ейча� `game_over` их нет), теги и `[%clk]`, поло�а результата §5.2, переход в обычный режим. +6. Вопро� §6 в `app.rs` р�дом � `confirm_dialog`, пауза ча�ов на врем� вопро�а. + +## 10. Ра�хождени� � и��ледованием + +- Пор�док блоков диалога: аналитик — Вы, Цвет, Врем�, Соперник; зде�ь — Вы, **Соперник**, Цвет, Врем�: �ила зави�ит от рейтинга и должна быть р�дом � ним; �амый большой блок (врем�) — по�ледним, у кнопки. +- Сетка пре�етов — **�троками по категори�м** (запро� владельца «по группам»), а не 4 × 3 � подпи�ью под плиткой. +- «Слабее · Как � · Сильнее» — запоминаемый режим, а не разовые кнопки (�мы�л «отно�ительно моего рейтинга»). +- Ча�ы — в боковой панели у краёв (р�дом) и поло�ами у до�ки (�топка), а не только «у до�ки». +- Уход: одна форма � «Сдать�� и добавить в базу…» вме�то цепочки «Сдать�� и выйти» → «Парти� изменена»; «Прервать» — кнопкой на панели до первых ходов, а не в вопро�е (до первых ходов вопро�а нет). +- Пока открыт вопро� ухода — ча�ы �то�т (в и��ледовании не оговорено). +- Стрелки в игре временные, в партию не пишут�� (R7 �того не уточн�л). +- «Без ча�ов» вме�то «Без времени» (�лово владельца). + +## 11. Вопро�ы владельцу + +1. Контроль по умолчанию при первом открытии: **10+0** (предлагаю) или «Без ча�ов», как у компьютера Lichess? +2. �азвани� «Ещё раз» (аналитик) или «Реванш» (предлагаю, �лово владельца и Lichess)? +3. Ctrl+G дл� «Играть» — подходит? +4. О�тальные вопро�ы — и��ледование §8 (шкала рейтинга, пули без premove, �зык `Event`, по�тавка и лицензи� Maia); от них зави��т подпи�и пол� «Рейтинг», под�казка пуль и �о�то�ние «Maia не у�тановлена». + +## 12. Проверки дл� те�тировщика (план, не выполнено) + +1. Библиотека 1400 / 960 / 640: «⚔ Играть» на �воём ме�те, подпи�ана; при �ужении — значок � под�казкой; Ctrl+G открывает диалог. +2. Диалог: Enter �разу играет � прошлыми на�тройками; рейтинг 99/3001 — кра�на� рамка и «Играть» неактивна; «Как �» при 1350 → 1400, по�ле �мены рейтинга на 1720 при �ледующем открытии — 1700; �двиг ползунка �нимает «Как �»; «Свой» 0+0 — нельз�; 7+2 → «рапид»; при 640 × 480 �трока кнопок видна, �одержимое прокручивает��. +3. Отмена диалога не мен�ет им� и рейтинг в на�тройках. +4. Экран игры: нет �троки движка, вкладок, поло�ы оценки (но ме�то е�ть), «�айти в базе», ☰, 💾; L и Shift+A — то�т; F2, Ctrl+S, Enter, 1–6 — ничего; Ctrl+Z — ход назад. +5. Чёрными: до�ка чёрными �низу, Maia ходит первой, карточка Maia �верху; F — карточки мен�ют�� ме�тами. +6. Ли�тание назад во врем� �воего хода: ча�ы идут, �трока «Про�мотр…», попытка хода возвращает к текущей позиции без хода; ход Maia возвращает к текущей позиции. +7. 3+0: при 0:22 ча�ы кра�неют; < 10 � — де��тые; 0:00 — конец «Вы проиграли · врем� вышло». +8. «Сдать��» → «Сдать��? Да/�ет»; Esc/4 �/ход отмен�ют; «Да» — конец. +9. Конец: в тот же кадр — обычна� парти�, до�ка (р�дом) не �двинула�ь; поло�а результата; Ctrl+S → «Добавить в базу», данные предзаполнены; «Реванш» � не�охранённой партией �прашивает. +10. Esc во врем� игры: вопро�, ча�ы �то�т, Maia не ходит; «Продолжить» — в�ё продолжает�� � того же времени; закрытие окна — тот же вопро�, без второго. +11. Esc до первых ходов — выход без вопро�а; «✕ Прервать» до первых ходов. +12. Стопка 640 × 900: поло�ы ча�ов над и под до�кой; по�ле конца поло�ы уход�т, до�ка ра�тёт один раз; при медленном изменении размера окна во врем� игры компоновка переключает�� там же, где у обычной партии. +13. Сбой Maia (убить проце��): ча�ы �то�т, блок «Maia пере�тала отвечать», «Перезапу�тить» продолжает партию. diff --git a/docs/design/player-games.md b/docs/design/player-games.md new file mode 100644 index 0000000..9007cad --- /dev/null +++ b/docs/design/player-games.md @@ -0,0 +1,221 @@ +# База партий игрока: �ыгранные партии запи�ывают�� �ами (компьютер и телефон) + +Стату�: �огла�овано владельцем 2026-10-26 (`docs/decisions.md`, «Партии игрока запи�ывают�� �ами»); компьютер �делан, телефон — позже. Выбор владельца: название «Им� — партии � компьютером»; без имени — обща� база «Партии � компьютером»; кнопки «�е �охран�ть» нет; флажок в на�тройках включён по умолчанию. �иже тек�ты и �хемы приведены к �тому выбору; что �делано и что отложено — §11. Требовани� и хранение — у аналитика (`docs/research/player-games-db.md`); зде�ь — путь пользовател� и �краны. Опирает�� на `play-mode.md`, `rodent-opponent.md`, `own-databases.md`, `android-play.md` §30–31, `narrow-windows.md`. + +Запро� владельца: игрок впи�ал им� и играет — дл� него �ама заводит�� база � его именем, в�е его партии пишут�� туда; игрока об �том уведомл�ют; на компьютере и на телефоне. + +## 0. Что мен�ет�� в прин�тых правилах + +- `own-databases.md` §1 п. 4 «�ичего молча. �ет авто�охранени�» и `play-mode.md` §5.2 / `android-play.md` §31.4 «�вто�охранени� нет» — **дл� �ыгранных партий отмен�ют��**. Инвариант AGENTS.md («и�ходные PGN пользовател� �охран�ть; запи�ь — �вное дей�твие») не задет: база игрока �оздаёт�� программой, в чужие файлы ничего не пишет��, а �вное дей�твие — им� в диалоге игры при видимой �троке «партии запи�ывают�� в «…»». +- �овый принцип вме�то «ничего молча»: **ничего тайно**. Куда пишет�� парти�, видно до игры (�трока под именем), в момент запи�и (поло�а результата) и в библиотеке (значок базы). +- Правило запи�и одно на обе платформы: **в базу попадает кажда� парти�, в которой оба �делали хот� бы по ходу** (как порог R20: раньше — парти� про�то прерывает��). Запи�ывает�� один раз, когда парти� кончила�ь — � результатом. + +## 1. �азвание базы + +Шаблон должен �одержать им� и не �клон�ть его (�клон�ть имена программно нельз�: «Партии Романа», но «Партии Ильи», «Партии Любови»). + +| Вариант | RU | EN | За | Против | +|---|---|---|---|---| +| � (рекомендаци� дизайнера) | «Роман — мои партии» | «Roman — my games» | читает�� от лица игрока; «мои» — как «Мои базы» и «Мои партии» на телефоне; годит�� и дл� партий, введённых вручную потом | �зык фик�ирует�� при �оздании | +| Б | «Роман (ChessPenguin)» | то же | в паре � онлайн-базами «Роман (Lichess)»; не зави�ит от �зыка | новичку не��но, что внутри; на телефоне «(ChessPenguin)» лишнее | +| **В (выбор владельца)** | «Роман — партии � компьютером» | «Roman — games against the computer» | точнее в�его �егодн� | длинно дл� карточки 190 (им� в две �троки, длинное им� обрезает��); закрывает дорогу парти�м не � компьютером | + +- **Без имени** (выбор владельца) — обща� база «Партии � компьютером» (`Games against the computer`), а не «не запи�ывать». + +- Им� берёт�� как введено (обрезка пробелов, внутренние пробелы �хлопнуты); �имволы, запрещённые в имени файла (`own_db::FORBIDDEN`), замен�ют�� на «_» только в имени файла, на полке — как введено. +- Язык названи� — �зык интерфей�а в момент �оздани�; потом база не переименовывает�� �ама. +- Е�ли файл � таким именем уже е�ть и �то не база игрока (пользователь �ам завёл) — «Роман — партии � компьютером 2»; в чужой файл не допи�ываем. +- Компьютер: `Документы/ChessPenguin/Роман — партии � компьютером.pgn` (папка новых баз, `own-databases.md` §7). Телефон: �во� база в `filesDir/own/`, название — в �пи�ке. + +## 2. Путь пользовател� + +``` +диалог «Игра � компьютером» парти� конец библиотека +Им� [Роман ▾] → (ничего нового) → поло�а результата: → ♞ Роман — партии +Партии будут запи�ывать�� в ✔ Запи�ано в базу, � компьютером +новую базу «Роман — партии № 1 · Открыть 15 партий +� компьютером». + + один раз то�т «Создана база…» +``` + +1. **До игры** — �трока под полем имени (§3). Это и е�ть уведомление: тихое, �лабым тек�том, в�егда правдивое. Отдельного окна-объ��нени� нет. +2. **�ачало партии** — база ещё не �оздаёт�� (парти� может прервать�� до ходов). +3. **Конец партии** (любой и�ход, включа� «Сдать�� и выйти») — парти� допи�ывает�� в базу; е�ли базы не было, она �оздаёт�� и попадает на полку первой. +4. **Один раз на базу** (при её �оздании) — то�т: «Создана база «Роман — партии � компьютером» — �юда будут запи�ывать�� ваши партии.» (`Database “Roman — games against the computer� created: your games will be written there.`). Потом — только �трока в поло�е результата, без то�тов. +5. **Библиотека** — база �о значком ♞, наверху полки (полка и так «по�ледние �верху»: запи�ь трогает базу, `touch_database`). + +�икакой разовой «�правки» �верх �того: �трока под именем объ��н�ет до, то�т — в момент по�влени� базы, �трока в поло�е — каждый раз, где лежит парти�. + +## 3. Диалог «Игра � компьютером» (компьютер) + +``` +│ Вы │ +│ Им� [Роман ▾] Рейтинг [1350] │ +│ Партии запи�ывают�� в «Роман — партии � │ � �лабым, перено�ит�� +│ компьютером» · 14 партий │ в ширину пол� +│ │ +│ Соперник — Maia 1400 · как вы │ +``` + +**Строка под именем** (вме�то «�е об�зательно. По рейтингу подбирает�� �оперник.»; �мы�л про рейтинг уходит в под�казку пол� «Рейтинг»): + +| Со�то�ние имени | RU | EN | +|---|---|---| +| е�ть база �того игрока | «Партии запи�ывают�� в «{db}» · {n}» | `Games are written to “{db}� · {n}` | +| новое им� | «Партии будут запи�ывать�� в новую базу «{db}».» | `Games will be written to a new database “{db}�.` | +| пу�то | «Без имени партии идут в «Партии � компьютером». Впишите им� — заведём вашу базу.» | `Without a name games go to “Games against the computer�. Enter a name to have a database of your own.` | +| запи�ь выключена в на�тройках (§8) | «Партии �ами не запи�ывают�� (�а�тройки → Свои базы).» | `Games aren't saved automatically (Settings → Your databases).` | + +- `{n}` — «14 партий» (`crate::i18n::games`). Строка обновл�ет�� на каждую букву; �равнение имён без учёта реги�тра и лишних пробелов («роман» = «Роман»). +- **Пу�тое им�** (выбор владельца) — игра разрешена, парти� пишет�� в общую базу «Партии � компьютером»; �трока зовёт впи�ать им�. Модального вопро�а нет. +- **Ширина �троки:** �трока не задаёт ширину диалога — перено�ит�� в ширину пол� имени (иначе диалог ра�тёт и прыгает на каждую букву, а при 640 × 480 �трока обрезает��). +- **�е�колько игроков (�емь�).** Поле имени — � выпадающим �пи�ком ▾ прошлых игроков (у кого е�ть база), по�ледние �верху. Выбор имени под�тавл�ет и **его рейтинг**: рейтинг хранит�� на игрока, не один на в�ех. Строка �пи�ка: «Роман · 1350 · 14 партий». �овое им� — про�то впи�ать. +- Опечатка («Ромн») даёт �троку «…в новую базу «Ромн — партии � компьютером»» — видно до «Играть»; �пи�ок ▾ делает выбор без набора. +- «Ваше им�» в на�тройках (комментатор) — по-прежнему по�леднее им� из диалога; отдельно не трогаем. +- **Клавиатура:** фоку�, как �ейча�, — на «Играть». В поле имени ↓ или Alt+↓ открывает �пи�ок, ↑/↓ — выбор, Enter — вз�ть им� (�пи�ок закрыт — Enter = «Играть»), Esc закрывает �пи�ок (второй Esc — «Отмена»). +- **Узкое окно:** �трока перено�ит�� на две; при 640 × 480 тело прокручивает��, кнопки вне прокрутки (`play-mode.md` §2.5). Спи�ок ▾ — шириной пол�, не выше 8 �трок. + +## 4. Во врем� и по�ле партии (компьютер) + +**Во врем�** — ничего нового на �кране (игре не мешаем). Вопро� «Парти� идёт» при уходе: + +``` +┌─ Парти� идёт ─────────────────────────────────────────� +│ Е�ли выйти, парти� закончит�� вашей �дачей │ +│ и запишет�� в «Роман — партии � компьютером». │ +│ [Сдать�� и выйти] [▌Продолжить игру�] │ +└────────────────────────────────────────────────────────┘ +``` + +- Кнопка «Сдать�� и добавить в базу…» убирает�� (парти� и так попадёт в базу); «Сдать�� и выйти» запи�ывает партию �о �дачей. Без имени (запи�ь выключена) — вопро� как �егодн�. +- Тек�т: «If you leave, the game ends with your resignation and is written to “{db}�.» + +**Поло�а результата** (`play-mode.md` §5.2): кнопка «💾 Сохранить в базу…» замен�ет�� �трокой: + +``` +│ [0-1] Вы проиграли × │ +│ врем� вышло │ +│ О�тало�ь: вы 0:00 · Maia 2:41 │ �лабым +│ ✓ Запи�ано в «Роман — партии � компьютером», № 15 · Открыть │ �лабым, «Открыть» — ��ылка +│ [▌📈 �нализировать�] [↻ Реванш] [♞ �ова� игра] │ +``` + +- RU «✓ Запи�ано в «{db}», № {n}» + ��ылка «Открыть»; EN `✓ Written to “{db}�, No. {n}` + `Open`. «Открыть» — библиотека, база выбрана, �трока �той партии выделена и видна. +- Три кнопки вме�то четырёх — в узкой поло�е помещают�� в один р�д чаще; правило перено�а то же (главна� во в�ю ширину, две пополам). +- **Ошибка запи�и** (нет ме�та, нет прав): �трока кра�ным «�е удало�ь запи�ать в «{db}»: {причина}» (`Could not write to “{db}�: {reason}`), возвращает�� кнопка «💾 Сохранить в базу…» — парти� не тер�ет��, дальше обычный поток. +- Ctrl+S по�ле конца — «Сохранить в «{db}»» (парти� теперь из базы); Ctrl+Shift+S — копи� в другую базу, как в�егда. + +**«Парти� изменена»** (`app.rs` ~2110). По�ле запи�и парти� — обычна� запи�ь �воей базы (`source` = база, № 15), по�тому: +- без правок — вопро�а нет (реванш, нова� игра, «⬅ Библиотека», выход); +- � правками (комментарии, в�тавленные варианты движка, «Данные партии») — обычный вопро� «Сохранить изменени� в «Роман — партии � компьютером»?». Сама парти� уже в базе, тер�ют�� только правки — так и должно быть. + +**«�е �охран�ть �ту партию»** — не нужна (рекомендаци�, вопро� 2): отдельна� кнопка на поло�е подталкивает «пр�тать проигрыши» и ломает «в�е партии». �енужна� запи�ь удал�ет��, как люба�, из таблицы базы (`own-databases.md` §4.3, � отменой). + +## 5. База в библиотеке (компьютер) + +``` +┌──────────────────────────� +│ ♞ Роман — партии � компьютером │ значок ♞ вме�то 🗄 (как � у онлайн-баз) +│ 15 партий │ +└──────────────────────────┘ +``` + +- **Значок ♞** (тот же, что у «♞ Играть») — признак «партии игрока». Под�казка карточки: путь файла и �трока «Сюда запи�ывают�� партии � компьютером игрока Роман» (`Roman's games against the computer are written here`). +- **Ме�то на полке** — без закреплени�: полка уже упор�дочена «по�ледние �верху», по�ле партии база перва�. Семь� — карточки идут в пор�дке, кто играл по�ледним. +- Меню карточки — как у �воей базы («Показать в папке», «Убрать из �пи�ка», …). «Убрать из �пи�ка» базу игрока **не отв�зывает**: при �ледующей партии она вернёт�� на полку (файл тот же). Файл удалён — при �ледующей партии база �оздаёт�� заново, � то�том §2 п. 4. +- **Таблица по умолчанию** — новые �верху (по номеру запи�и, по убыванию; по�ледн�� �ыгранна� — перва� �трока). Столбцы обычные; «Турнир» уже говорит «Парти� � компьютером, блиц», в «Белые/Чёрные» — «Роман» и «Maia 1500» / «Rodent V 2400 (Tal)». Отдельный вид «Соперник · Цвет · Итог дл� игрока · Контроль» — позже, не в первой вер�ии (вопро� 4). +- Сортировку пользователь мен�ет как обычно; выбор запоминает�� дл� базы как у других. + +## 6. Android + +**Ли�т «Игра � Maia»** (`android-play.md` §31.1): поле «Ваше им� (дл� запи�и партии)» → `ExposedDropdownMenuBox` «Ваше им�» �о �пи�ком прошлых игроков; под ним `supportingText` — те же четыре �троки §3 (12sp `onSurfaceVariant`). Рейтинга на телефоне нет — �пи�ок без рейтинга: «Роман · 14 партий». + +**«Базы»** (§30.2): база игрока — в группе «Мои базы», первой; плашка значка — `chess` (конь) вме�то `edit_note`; втора� �трока «15 партий · партии � компьютером» (`15 games · games vs the computer`). Пу�той группы больше почти не бывает — �трока `own_empty` о�таёт�� дл� �луча� без имени. + +**Экран игры** — без изменений. **Карточка результата** (§31.4): + +``` +┌────────────────────────────────────� +│ [1-0] Вы выиграли · мат × │ +│ ✓ В «Роман — партии � компьютером», № 15 › │ 40 bodyMedium, в�� �трока — кнопка +│ [ �нализ ] [ Реванш ] [ �ова� ] │ 48 три кнопки +└────────────────────────────────────┘ +``` + +- «›» открывает «Партии» �той базы � прокруткой к запи�и. «Сохранить…» уходит; «�ова� игра» выходит из ⋮ в карточку (ме�то о�вободило�ь). +- Создание базы — один раз �некбар 6 �: «Создана база «Роман — партии � компьютером»: �юда пишут�� ваши партии» · «Открыть». +- Реванш / нова� игра / «назад» по�ле конца — без диалога «Сохранить партию?» (парти� уже в базе); � правками — «Сохранить изменени� в «…»?» (§30.4, �трока «�во� база»). + +**Отложенна� парти�** (§31.7) — пишет�� в `current.pgn` как �ейча�; в базу попадает, **когда кончит��**. Е�ли её не доиграли: +- × на карточке отложенной и «�ачать новую» в вопро�е «Е�ть отложенна� парти�» — парти� (где оба �ходили) запи�ывает�� в базу **неоконченной** (результат `*`); �некбар «Парти� запи�ана в «{db}» неоконченной» (`Game written to “{db}� unfinished`), без «Вернуть». Тек�т вопро�а: «�ова� парти� заменит её; �та запишет�� в базу неоконченной.» Так «в�е партии» о�тают�� правдой и ничего не пропадает молча; лишнее удал�ет�� в базе. +- �а компьютере отложенных партий нет: уход — �дача, она и запи�ывает��. + +## 7. �а�тройки (обе платформы) + +«�а�тройки → Интерфей� → Свои базы» (компьютер), «�а�тройки → Парти�» (телефон): флажок «Запи�ывать партии � компьютером в базу игрока» (`Write games against the computer to the player's database`), включён по умолчанию. Выключен — в�ё как до �той функции (�трока под именем — четвёрта� �трока таблицы §3, поло�а � «Сохранить в базу…»). �ужен дл� тех, кто играет «на пробу» и не хочет базы (вопро� 3). + +## 8. Тек�ты (RU → EN), �водка + +| RU | EN | +|---|---| +| «{name} — партии � компьютером» | `{name} — games against the computer` | +| «Партии запи�ывают�� в «{db}» · {n}» | `Games are written to “{db}� · {n}` | +| «Партии будут запи�ывать�� в новую базу «{db}».» | `Games will be written to a new database “{db}�.` | +| «Без имени партии идут в «{db}». Впишите им� — заведём вашу базу.» | `Without a name games go to “{db}�. Enter a name to have a database of your own.` | +| «Партии �ами не запи�ывают�� (�а�тройки → Свои базы).» | `Games aren't saved automatically (Settings → Your databases).` | +| «Создана база «{db}» — �юда будут запи�ывать�� ваши партии.» | `Database “{db}� created: your games will be written there.` | +| «✓ Запи�ано в «{db}», № {n}» · «Открыть» | `✓ Written to “{db}�, No. {n}` · `Open` | +| «✓ В «{db}», № {n}» (телефон) | `✓ In “{db}�, No. {n}` | +| «�е удало�ь запи�ать в «{db}»: {reason}» | `Could not write to “{db}�: {reason}` | +| «Е�ли выйти, парти� закончит�� вашей �дачей и запишет�� в «{db}».» | `If you leave, the game ends with your resignation and is written to “{db}�.` | +| «Сюда запи�ывают�� партии � компьютером игрока {name}» (под�казка карточки) | `{name}'s games against the computer are written here` | +| «партии � компьютером» (втора� �трока, телефон) | `games vs the computer` | +| «Парти� запи�ана в «{db}» неоконченной» | `Game written to “{db}� unfinished` | +| «�ова� парти� заменит её; �та запишет�� в базу неоконченной.» | `A new game replaces it; this one is written to the database unfinished.` | +| «Запи�ывать партии � компьютером в базу игрока» | `Write games against the computer to the player's database` | + +Им� нигде не �клон�ет��: «игрока Роман», «ваши партии». + +## 9. Снимки дл� проверки (�деланы при проверке 2026-10-26, кроме ошибки запи�и и �пи�ка ▾ — §11) + +`CP_PLAY=dialog` � пу�тым именем, � новым именем, � именем �уще�твующей базы (три �троки §3); 640 × 480 и 1400 × 900. `CP_PLAY=white,none` + `CP_PLAY_AUTO=1` — поло�а результата �о �трокой «✓ Запи�ано…» (широка� и 640 ширины). Поло�а � ошибкой запи�и (папка только дл� чтени�). Полка � двум� базами игроков и онлайн-базой р�дом. + +## 10. Решени� владельца (2026-10-26) + +1. **Пу�тое им�** — обща� база «Партии � компьютером» (не «не запи�ывать», как рекомендовал дизайнер). +2. **«�е �охран�ть �ту партию»** — кнопки нет; лишнее удал�ет�� в таблице базы � отменой. +3. **Флажок в на�тройках** — е�ть, включён по умолчанию. +4. **�азвание** — «Им� — партии � компьютером» (вариант В). +5. **�едоигранна� отложенна� парти� на телефоне** — запи�ывает�� неоконченной (`*`); вме�те � о�тальным телефоном — позже. + +## 11. Что �делано на компьютере и что отложено (проверка дизайнера 2026-10-26) + +Сделано: �трока под именем (четыре �о�то�ни�, чи�ло партий), �пи�ок ▾ прежних игроков � рейтингом, запи�ь в конце партии и журнал на �лучай �бо� (то�т при �ледующем запу�ке), «✔ Запи�ано в «…», № n · Открыть» и три кнопки в поло�е, вопро� «Парти� идёт» без «Сдать�� и добавить в базу…», ♞ на карточке и в �вёрнутой полке, под�казка карточки, флажок в «Свои базы», то�т о �оздании базы. + +К и�правлению (по �нимкам проверки): +- �трока под именем не перено�ит�� и ра�шир�ет диалог (§3 «Ширина �троки»); +- �трока в поло�е � длинным названием занимает три �троки узкой поло�ы — показывать «✔ Запи�ано в базу, № {n} · Открыть», название базы — в под�казке (оно уже е�ть в �троке под заголовком партии); +- то�т о �оздании базы — 3,5 �, �овпадает � концом партии: держать дольше (6 �, как �некбар телефона). + +Отложено: +- клавиатура �пи�ка ▾ (↓/Alt+↓, Enter, Esc) и чи�ло партий в �троке �пи�ка («Роман · 1350 · 14 партий»); +- таблица базы игрока по умолчанию «новые �верху» (§5) — �ейча� по номеру по возра�танию; +- «Открыть» � выделенной �трокой партии (§4) — проверить: �ейча� �то переход в библиотеку; +- ~~телефон (§6) целиком~~ — �делан, �м. §11.1. + +### 11.1. Телефон (проверка дизайнера 2026-10-26, �нимки �мул�тора 1080 × 2400) + +Сделано: поле «Ваше им�» �о �пи�ком ▾ прежних игроков и �трокой под ним (четыре �о�то�ни�, чи�ло партий); запи�ь в конце партии; �трока «✓ В «…», № n ›» в карточке результата, открывает базу; �некбар о �оздании базы; ♞ и втора� �трока в «Мои базы»; × на карточке отложенной пишет её неоконченной �о �некбаром; флажок «�а�тройки → Парти�», включён. Шкала �оперника — 600–2600, �об�твенный рейтинг Maia, под ползунком «Соб�твенный рейтинг Maia: он не равен Эло человека.» + +К и�правлению: +1. Снекбар «Создана база…» на 6 � закрывает кнопки карточки результата (�нализ/Реванш/Сохранить) ровно в момент, когда они нужны. Решение: �некбар убрать, а при �оздании �трока карточки говорит �то �ама: «✓ Создана база «{db}», № 1 ›» (`✓ New database “{db}�, No. 1 ›`); дальше — «✓ В «{db}», № n ›». +2. Треть� кнопка карточки при запи�анной партии — неактивна� «✓ Сохранено»: дублирует �троку «✓ В…» и занимает ме�то. По §6 — «�ова�» (нова� парти� � теми же на�тройками); «Сохранить…» о�таёт�� только при выключенном флажке или ошибке запи�и. +3. Ошибка запи�и — общий «�е удало�ь �охранить партию», в карточке нет �троки, кнопка «Сохранить…» активна. �ужен тек�т §8: «�е удало�ь запи�ать в «{db}»: {reason}» (`Could not write to “{db}�: {reason}`). +4. Втора� �трока базы игрока «2 партии · партии � компьютером» повтор�ет название �лово в �лово. Вме�то — «2 партии · пишут�� �ами» (`2 games · recorded automatically`). +5. Строка «✓ В «…», № 1 ›» — цветом `onSurfaceVariant`, не похожа на нажимаемую. «›» (или в�ю �троку) — `primary`. +6. Тихие запи�и неоконченной: «�ачать новую» в вопро�е об отложенной и «Прервать» при �бое Maia пишут партию без �некбара (§6 требует �некбар «Парти� запи�ана в «{db}» неоконченной»). Тек�т вопро�а `play_adjourned_new_text` обещает запи�ь в�егда — и при выключенном флажке, и когда ходов меньше двух; показывать его только когда запи�ь дей�твительно будет, иначе прежний тек�т. +7. Строки под именем: «…в новую базу «…»» и «…в «…» · 2 партии» без точки, «Без имени…» — � точкой. Точки во в�ех или ни в одной (две фразы — значит во в�ех). +8. Подпи�ь пол� «Ваше им� (дл� запи�и партии)» — �кобка лишн��, �трока под полем объ��н�ет; «Ваше им�» (`Your name`). +9. Спи�ок ▾ открывает�� ка�анием редактируемого пол� и не фильтрует�� по набранному — при вводе нового имени закрывает �троку под полем. Фильтровать по началу имени, не показывать при пу�том �овпадении; �трока `players_menu` не и�пользует�� — убрать или �делать заголовком �пи�ка. + +Отложено: чи�ло партий в �троке �пи�ка («Роман · 14 партий»); таблица базы игрока «новые �верху» и прокрутка к запи�и по «›»; «Сохранить изменени� в «…»?» по�ле правок запи�анной партии — проверить. diff --git a/docs/design/reference.md b/docs/design/reference.md new file mode 100644 index 0000000..33095ab --- /dev/null +++ b/docs/design/reference.md @@ -0,0 +1,70 @@ +# Вкладка «Справочник» (reference) + +Стату�: проект, 2026-10-19. Образец — вкладка Reference в ChessBase (`designExample/reference.png`): �верху ходы из позиции �о �тати�тикой, �низу партии, дошедшие до позиции. �аша вкладка повтор�ет �ту �хему двум� таблицами того же вида, что таблица партий библиотеки (поло�атые �троки, заголовки, обычный размер шрифта, а не мелкий тек�т). + +## Где + +Вкладка в правой панели окна партии: `�отаци� | Справочник | Отчёт` (не «Справка»: её читают как «Помощь») («Отчёт» — только когда е�ть анализ партии). Справочнику нужна ширина: у панели � открытым «Справочником» �во� ширина — в�ё, что о�таёт�� р�дом � до�кой во в�ю вы�оту окна (у нотации — 40 %, не больше 460). Панель никогда не шире �того, до�ка не уменьшает��; уже — можно, перета�киванием (egui запоминает отдельно дл� каждой вкладки). **Обновление 2026-10-24:** панель не уже �одержимого вкладки (`REF_MIN`), до�ка уменьшает�� до 220; в узком вы�оком окне нотаци� и «Справочник» уход�т под до�ку — `narrow-windows.md` §3. + +## Сверху: база и теори� + +``` +База [ Mega Database 2026 · 11 743 083 ▾] +В базе до хода 12…Nd7 (дальше парти� �во�) � ��ылка: перейти к ходу +``` + +- «База» — �пи�ок баз полки (им� · чи�ло партий); по умолчанию �ама� больша� по размеру файла, выбор запоминает��. +- �овинка: «�овинка: 14.Nf3» (��ылка) — первый ход партии, которого нет ни в одной другой партии базы; е�ли такого хода нет (в�е ходы партии в�тречают�� в базе), �троки нет. Сама парти� и её копии не �читают��. Первые 12 полуходов провер�ют�� по одному, дальше граница ищет�� удвоением и делением пополам (позици� почти в�егда е�ть в базе, е�ли в ней е�ть более поздн�� позици� той же линии). Ответ �охран�ет��, пока парти� удлин�ет�� за его пределы; номера ходов у партий � FEN — от их начала. +- Пока больша� база �троит индек�: «У�кор�ю пои�к по �той базе (один раз)… N %». + +В �троке выбора базы, �права от него (по�вл�ют�� через мгновение и не занимают �воей �троки): «�овинка: 14.Bg5» и «Эта парти� е�ть в базе — открыть». Под ней: +- �трока позиции: «Ход белых · по�ле 4…Nc6 · в партии 5.Nb5»; +- «Эта парти� е�ть в базе — открыть», е�ли в базе нашла�ь копи�: парти� � теми же игроками (фамилии) и годом, доход�ща� до финальной позиции �той. Тренеру ценно открыть, например, комментированную вер�ию. У пу�той партии копий и теории нет. + +Копии партии и �ама парти� (е�ли она из �той базы) не вход�т в «теорию» и в таблицу партий; в �чётчиках ходов о�тают��, как в ChessBase. + +Между блоками — горизонтальные разделители. + +## Таблица ходов + +| Ход | Партий | % | Результат | Белые | Ср. Эло | Год | Лучшие игроки | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 5.Nc3 | 70 608 | 74 % | ▕██▒▒░░� | 55 % | 2236 | 2025 | Carlsen, Caruana | + +- **Ход** — SAN � номером; **Партий** и **%** — �колько партий �ыграли ход; **Результат** — поло�а белые/ничьи/чёрные (как на до�ке пои�ка), **Белые** — очки белых в процентах; **Ср. Эло** — �редний рейтинг партий, где изве�тны оба; **Год** — по�ледний; **Лучшие игроки** — две фамилии �ильнейших (по рейтингу в партии) игроков, �ыгравших �тот ход. +- По�ледн�� �трока — «Конец партии»: �только партий закончило�ь в �той позиции (�дача, ничь�, мат, врем�). В начальной позиции �то партии, запи�анные без ходов (только игроки и результат), �трока называет�� «Без ходов». +- Ход, �ыгранный в партии, отмечен «�» и полужирным. +- Дл� книги (большин�тво партий без результата) — «Главы» вме�то «Партий», без колонок результата, очков и Эло. +- **Один клик** выдел�ет ход: �ин�� �трелка на до�ке, таблица партий ниже показывает только партии � �тим ходом. Повторный клик �нимает выделение. **Двойной клик** играет ход в партии: переход, е�ли такой ход в партии е�ть, иначе новый вариант (Ctrl+Z отмен�ет). +- �аведение — �ин�� �трелка �того хода. Строки кликают�� целиком, и по тек�ту тоже (тек�т в �чейках не выдел�ет��). +- Вы�ота — до 40 % панели, дальше прокрутка. + +## Таблица партий + +`Партии · 95 949` (или `Партии � ходом 5.Nc3 · 70 608 ✕`), под заголовком — «показаны 100 �ильнейших» когда партий больше. + +| Белые | Эло | Чёрные | Эло | Рез. | Год | Дальше | Турнир | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Carlsen, Magnus | 2863 | Caruana, Fabiano | 2835 | ½-½ | 2020 | 5.Nc3 a6 6.Be2 | Chessable Masters | + +- Сильнейшие �верху (�редний рейтинг, затем новее) или новые �верху — заголовки «Эло» и «Год»; �то разные выборки (100 партий, у хода — 40), а не пере�тановка одной. Спи�ки е�ть у каждого хода; «Дальше» читает�� дл� 12 �амых ча�тых. Лучшие игроки хода — по �об�твенному рейтингу игрока, �делавшего ход. +- В PGN (до 5000 �овпадений) парти� учитывает�� во в�ех �воих ветках: в �пи�ке каждого хода, �ыгранного из позиции в любом варианте, и «Дальше» идёт от той ветки. +- **Дальше** — три полухода партии по�ле позиции (откуда она отличает�� от текущей). +- �аведение — �ин�� �трелка �ледующего хода �той партии. **Двойной клик** открывает партию на �той позиции; текуща� не закрывает��, а о�таёт�� в �теке (�м. ниже). +- В узкой панели колонки пр�чут�� по очереди: Турнир, Дальше, Год; у таблицы ходов — Лучшие игроки, Год, Белые, Ср. Эло. +- С�ылка «в�е в библиотеке ➡» открывает позицию на до�ке пои�ка �той базы. +- Открыта� из �пи�ка парти� не закрывает текущую: в шапке «⬅ К партии …» возвращает её как была (� не�охранёнными правками). «⬅ Библиотека» и выход из программы по очереди �прашивают «�охранить?» про каждую о�тавленную партию � не�охранёнными изменени�ми (показыва� её), затем идут, куда про�или. Вкладка «Справочник» о�таёт�� открытой и в �ледующей партии, открытой из библиотеки или из �правочника. + +## Со�то�ни� + +- �ет баз на полке: «Добавьте базу в библиотеку, чтобы видеть, что зде�ь играли». +- База открывает��: �пиннер «Открываю базу…». +- База не открыла�ь: причина, без повторов. +- Идёт под�чёт: первые 0,3 � пу�то (без мигани� при ли�тании), потом «Считаю… N %»; прежний результат другой позиции не показывает��. +- Пои�к не удал�� (PGN, дл� таблицы позиций которого нет пам�ти): «�е хватает пам�ти…: нужно ещё около N МБ», кнопка «Попробовать ещё раз», без повторов каждый кадр. +- Позици� в базе не в�тречала�ь: «В �той базе такой позиции нет» и �трока теории. +- Парти� � заданной позиции (FEN): пои�к по позиции работает, «тем же пор�дком» и теори� �читают�� от её начала. + +## Ру��кие чи�лительные + +Счётчики �о �ловом «парти�» �клон�ют��: 1 парти�, 2 партии, 5 партий (`i18n::games`). diff --git a/docs/design/repertoire-panel-layout-2026-11-27.md b/docs/design/repertoire-panel-layout-2026-11-27.md new file mode 100644 index 0000000..c7b75e1 --- /dev/null +++ b/docs/design/repertoire-panel-layout-2026-11-27.md @@ -0,0 +1,60 @@ +# Права� панель «Тренировка дебюта»: ширина, таблица, карточка (2026-11-27) + +Задача �крана: выбрать репертуар и �разу начать зан�тие; приоритет — название, «что �егодн�», главна� кнопка; до�ка не должна �традать. + +## Снимки текущего �о�то�ни� (изолированный профиль, �борка debug 2026-11-27 12:08) + +`XDG_CONFIG_HOME/XDG_DATA_HOME/CP_REPERTOIRE_DIR=/tmp/opencode/rp/*`, `CP_REPERTOIRE=library CP_REPERTOIRE_SELECT=И�пан CP_SCREENSHOT_SIZE=WxH`. +Снимки: `/tmp/opencode/rp/s/lib-1280.png` (1280×800), `lib-1600.png` (1600×1000), `lib-1920.png` (1920×1000). Окружение Wayland, ма�штаб >1 (1280 логич. �н�то в 2000 px). + +�аблюдени�: +- 1600 и 1920: панель упирает�� в потолок 460 логич. px; при 1920 �лева/�права от до�ки ~270 px пу�тоты, а таблица те�на�: «Полу�лав�н�ка� защита…», «Сицилиан�ка� защита: …» обрезаны. +- Колонка «Сегодн�» (90) + отдельна� колонка поло�ы (44) без заголовка: поло�а визуально прижата к «новые: 10», т.е. читает�� как ча�ть «Сегодн�» — дефект 5 у владельца. +- «Пройдено» — колонка 64 px; жирный заголовок «Пройдено» ≈ 68–72 px → при меньшей ширине/другом шрифте режет�� до «Прой» (дефект 3). +- �а �тартовых коротких названи�х обрезка заголовка карточки и «Повторить в�ё» на моих �нимках не во�произвела�ь; у владельца (панель ~620 физ. px ≈ 400 логич.) — да. Причины в коде ниже. + +## Откуда ширины (код) + +- `apps/desktop/src/opening_layout.rs:53` — `default_size((width * 0.4).clamp(260.0, 460.0).min(room))`: потолок 460 при любом окне. +- `opening_layout.rs:15` `SIDE_LEAST = 320`, `:54` `size_range(SIDE_LEAST..=most)`, `most = width - BOARD_MIN - 24`. Перета�кивание е�ть (`resizable(true)`), но ширина не �охран�ет�� между запу�ками/�кранами раздела (проверить: id `opening_side` хранит egui memory только в �е��ии). +- `apps/desktop/src/repertoire_ui.rs:56-58` — `TODAY_W 90`, `MINI_BAR_W 44`, `PASSED_W 64`; `:1682-1687` колонки: `remainder().at_least(80)`, 22, 90, 44, 64, 26. Фик�ированна� ча�ть = 246 + 5 межколоночных промежутков (≈40) ≈ 286 px; на название при панели 400 о�таёт�� ~95 px. +- `:1699-1706` заголовки: «Сегодн�» над колонкой 3, колонка 4 (поло�а) — пу�та�, «Пройдено» над колонкой 5. +- `:1557-1569` заголовок карточки: ширина «Вы играете белыми» �читает�� `text_width(ui, &you, 14.0)+8`, а ри�ует�� `RichText::weak()` шрифтом Body темы; при ра�хождении размера и без учёта `item_spacing.x` им� получает меньше/больше ме�та, а `layout::line` (`opening_layout.rs:106`) режет «…». +- `:1589-1615` кнопки карточки: в�егда один р�д; `grow` раздаёт только �вободное, но е�ли `room < main_need+lines_need+third_need+2·gap`, кнопки не �жимают�� ниже `need`, и треть� выходит за правый край карточки (обрезает�� клипом). `text_width(…,14.0)` также может не �овпадать �о шрифтом кнопки. + +## Решени� + +### 1. Ширина панели +- По умолчанию: `clamp(width × 0.36, 380, 560)`, но не больше `room` (до�ка ≥ `BOARD_MIN`). Итог: 1280 → 461, 1600 → 560, 1920 → 560 логич. px. При 1920 до�ка о�таёт�� ≥ вы�оты окна − 16, т.е. не уменьшает�� (�ейча� там пу�тота). +- Минимум: `SIDE_LEAST` подн�ть до 360 (меньше таблица не помещает�� без обрезки двух чи�ел). Мак�имум без изменений: `width − BOARD_MIN − 24`. +- Перета�кивание: о�тавить; ширину, вы�тавленную пользователем, �охран�ть в `Settings` (ключ, напр. `opening_side_width`) и примен�ть как default на в�ех �кранах раздела (тот же id → до�ка не прыгает). Двойной клик по разделителю — �бро� к умолчанию (е�ли egui позвол�ет; иначе пункт не об�зателен). + +### 2. Таблица репертуаров (`repertoire_ui.rs:1682`) +Колонки (5 вме�то 6): +1. �азвание — `remainder().at_least(120).clip(true)`, у�ечение «…» только при реальной нехватке, полное им� в tooltip. +2. Цвет (♔/♚) — `exact(22)`. +3. «Сегодн�» — `exact(today_w)`, где `today_w = max(ширина заголовка, ширина «повторить 99», «новые: 10», «завтра»)` измеренна� фактиче�ким шрифтом �троки (`ui.fonts(|f| layout_no_wrap(...))`) + 4; ожидаемо ≈ 76–84 вме�то 90. Выравнивание вправо. +4. «Пройдено» — одна колонка: поло�а 44 + промежуток 6 + чи�ло «0/22» вправо. `passed_w = max(ширина жирного заголовка, 44 + 6 + ширина «000/000»)` ≈ 100. Заголовок «Пройдено» выравнивает�� вправо над чи�лом, поло�а — �лева в той же колонке (решает дефект 5: поло�а под «Пройдено»). +5. `⋯` — `exact(26)`. +Фик�. ча�ть ≈ 22+82+100+26 + 4 промежутка·8 ≈ 262; название при 460 ≥ ~180, при 560 ≥ ~280 — �тартовые названи� влезают целиком. +Правило: чи�ловые колонки никогда не режут��; при минимальной панели 360 режет�� только название. Ширины �читать один раз на кадр до `TableBuilder` (не по �одержимому видимых �трок — чтобы не было �качков при прокрутке/под�чёте). «…» (под�чёт) и «нет ходов» впи�ывают�� в те же ширины; е�ли «нет ходов» шире — включить его в max дл� `passed_w`. + +### 3. Заголовок карточки (`:1557-1569`) +- Мерить «Вы играете белыми» тем же `FontId`, которым ри�ует�� (Body), + `item_spacing.x`. +- Е�ли `name_w + you_w > width`: �начала заменить метку на короткую (только король ♔/♚ � tooltip «Вы играете белыми»), и лишь затем у�екать им� «…». Перено� имени на 2 �троки не делать (фик�ированна� `CARD_H`, без �качков). + +### 4. Кнопки карточки (`:1589-1640`) +- Измер�ть потребно�ть шрифтом кнопки (`TextStyle::Button`) + `2·button_padding.x`. +- Е�ли три кнопки влезают — один р�д, как �ейча� (главна� ра�тёт первой). +- Иначе — две �троки: 1-� — главна� на в�ю ширину; 2-� — «Варианты…» и «Повторить в�ё» поровну. Решение «одна/две �троки» зави�ит только от ширины панели, не от �о�то�ни� карточки; вы�оту карточки (`CARD_H`) дл� двух�трочного режима увеличить на 30+6 и держать её одинаковой во в�ех �о�то�ни�х при �той ширине (в т.ч. когда третьей кнопки нет — пу�тое ме�то), чтобы таблица не прыгала при выборе другой �троки. +- `.truncate()` у кнопок о�тавить как �траховку, но в норме обрезки быть не должно. + +## Критерии приёмки (ревьюер — не автор, по реальным �нимкам) +Сери�: окна 1280×800, 1600×1000, 1920×1000, а также панель перет�нута до минимума 360 и до мак�имума; ма�штаб 1.0 и HiDPI; �зык ru и en (de — �амые длинные �троки). +1. Ширина панели по умолчанию 461/560/560 логич. px (±2) на трёх окнах; до�ка на 1920 не меньше, чем до изменени�. +2. По�ле перета�кивани� и перезапу�ка ширина та же; переход «Репертуары ⇄ Варианты ⇄ зан�тие» не �двигает до�ку (�нимки до/по�ле, x левого кра� до�ки �овпадает). +3. Таблица: «Сегодн�», «Пройдено», чи�ла «0/22», поло�а никогда не обрезаны ни при одной ширине ≥360; поло�а и чи�ло под заголовком «Пройдено», правый край заголовка = правый край чи�ла (±1 px); заголовок «Сегодн�» выровнен по правому краю значений. +4. При 560 �тартовые названи� («Полу�лав�н�ка� защита», «Сицилиан�ка� защита: …» полно�тью) без «…»; при 360 режет�� только название, tooltip даёт полное. +5. Заголовок карточки не у�ечён, е�ли �вободного ме�та хватает; при нехватке �начала и�чезает тек�т «Вы играете…», о�таёт�� король. +6. �и одна кнопка карточки не выходит за рамку; при узкой панели — две �троки; вы�ота карточки одинакова при переключении �трок � разными �о�то�ни�ми (�нимки 3 выбранных �трок подр�д, y шапки таблицы �овпадает). +7. Под�чёт �тати�тики («…» → чи�ла) не мен�ет ширину колонок (�ери� �нимков �разу по�ле запу�ка и через 4 �). diff --git a/docs/design/repertoire-training.md b/docs/design/repertoire-training.md new file mode 100644 index 0000000..fe93a3e --- /dev/null +++ b/docs/design/repertoire-training.md @@ -0,0 +1,998 @@ +# Дебютные репертуары и тренировка по дереву + +**Дополнение по�ле выпу�ка 2.2.0 (06.11.2026):** владелец поручил показывать +PGN-значки и ри�унки в новом �кране обучени� по�ле �об�твенных и автоматиче�ких +ходов, и�пользу� вид обычного про�мотра партии. Он также отменил ограничение +одним �об�твенным ответом: изучают�� в�е включённые варианты. Предпочтительный +ход мен�ет пор�док, а не �о�тав заданий. Другой ожидающий ответ из той же позиции +за�читывает�� именно �ыгранному `(FEN4, UCI)`; повторённый/не запланированный +ответ репертуара обрабатывает�� нейтрально. И�ходные PGN и �кран обычного про�мотра +партии от �той доработки не мен�ют��. Это дополнение имеет приоритет над правилом +един�твенного main-answer в и�ториче�ких разделах ниже. + +Стату�: **финальный рабочий дизайн дл� desktop-реализации**, 2026-11-02. О�нование — подтверждённое решение `docs/decisions.md` «Дебютные репертуары и тренировка по дереву (2026-11-02)». Этот документ замен�ет �ценарий немедленного «Учить дебют до �того хода» на desktop; �тарый Android-тренер не мен�ет��. + +**�ктуализаци� 2026-11-02:** �крыта� целева� модель и `try again` из прежних разделов отменены по�ле живого замечани� владельца; пользователь�кий путь уточнён в §20. + +**Дей�твующа� редакци� 2026-11-04:** §23 и `docs/chesstempo_opening_trainer_TZ.md`. Владелец подтвердил приоритет полного ТЗ над прежними упрощени�ми из §21. Единый workspace из §22 �охран�ет��; разделы до §23 о�тавлены как и�тори� проектировани� и не опи�ывают текущую модель там, где противоречат ТЗ и §23. + +Размеры ниже — логиче�кие точки egui. Подпи�и даны на ру��ком; об�зательные RU/EN/DE-�троки — в §13. Открытых продуктовых вопро�ов и альтернатив дл� реализации нет. + +## 0. Задача и границы + +Пользователь �обирает не�колько �амодо�таточных PGN-репертуаров, ограничивает их обла�ть и глубину, а затем либо повтор�ет отдельные ходы одного цвета по очереди, либо во�производит ветки целиком за обе �тороны. + +Об�зательные инварианты: + +1. Репертуар — **PGN-дерево**: о�новна� лини�, в�е RAV, комментарии, NAG и и�ходный FEN �охран�ют��. Это �емантиче�кий PGN-�нимок, а не набор UCI и не ��ылка на `NodeId` и�ходной партии. +2. И�ходна� парти�, её база и импортированный файл никогда не измен�ют��. Добавление, импорт и тренировка пишут только данные библиотеки репертуаров и `training.json`. +3. Глубина по умолчанию — **20 полуходов от начала репертуара**. Глубина и `disabled` ограничивают тренировку, но не удал�ют �одержимое и не мен�ют PGN-�к�порт. +4. `White`, `Black` и `Both` — три раздельных про�тран�тва �тати�тики внутри каждого репертуара. Стати�тика разных репертуаров также не �мешивает��. +5. Тран�позиции объедин�ют�� по FEN4 **только внутри одного репертуара**. В�е и�ходные пути о�тают�� в PGN и в про�мотре. +6. Движок в тренировке не уча�твует. В�е автоматиче�кие ходы и допу�тимые продолжени� берут�� из включённого дерева. +7. Desktop-first. �а Android о�тают�� прежний линейный тренер, его UniFFI API и legacy-запи�и `training.json`; web не получает кнопку до отдельного VFS-хранилища. +8. В�е запи�и атомарны. Ошибка запи�и видна и не ма�кирует�� у�пешным результатом. + +Термины: + +- **Ход/цель** в одноцветном режиме — конкретный `(position FEN4, expected UCI)` выбранного цвета. +- **Путь** в `Both` — фактиче�ки �ыгранна� по�ледовательно�ть полуходов от начала обла�ти до ли�та, глубины или повторени� позиции. +- **Обла�ть** — ве�ь репертуар либо поддерево от выбранного хода. Выбранный ход входит в обла�ть. +- **Контек�т** — путь от начала репертуара до начала обла�ти или текущей цели. Контек�тные ходы не �вл�ют�� попытками пользовател�. + +## 1. Информационна� архитектура + +�а �кране баз непо�ред�твенно р�дом � «📑 Подготовки» находит�� обычна� кнопка «Тренировка дебюта». Без нового непроверенного значка. Она открывает библиотеку репертуаров, а не до�ку �лучайной тренировки. + +Три рабочих �крана, без по�ледовательно�ти ма�теров и модальных окон: + +1. **Репертуары** — таблица библиотеки, �оздание, переименование, удаление, импорт, прежние line-run. +2. **Репертуар** — до�ка и полное дерево, обла�ть, глубина, режим, очередь, �тати�тика, запу�к. +3. **Тренировка** — ограниченный �кран до�ки и �ыгранного пути, по�троенный на визуальной о�нове текущего тренера. + +Допу�тимы только �и�темный выбор PGN-файла, компактный выбор назначени� из партии и контек�тные меню. Создание, переименование, удаление и предпро�мотр импорта выполн�ют�� inline. Един�твенное разрушительное подтверждение — удаление репертуара — тоже ра�крывает�� �трокой в таблице, а не отдельным окном. + +Возврат: + +- `Репертуары → Базы` возвращает прежний �кран баз без изменени� фильтров и выбранной базы. +- `Репертуар → Репертуары` �охран�ет �троку, прокрутку и ра�крытую вкладку библиотеки. +- `Тренировка → Репертуар` возвращает ту же обла�ть, активный ход дерева, глубину, режим и очередь. +- Е�ли репертуар открыли по ��ылке из то�та добавлени� в партии, в его шапке е�ть «� К партии {название}». Возврат во��танавливает кур�ор, вкладку, прокрутку и не�охранённые правки партии. Из тренировки возвращают�� �начала в репертуар, затем по �той кнопке в партию. + +## 2. Экран библиотеки репертуаров + +### 2.1. Задача и приоритет + +Главное — выбрать репертуар и увидеть, что именно требует внимани� в каждом режиме. Это рабоча� таблица, а не набор карточек и не �водка � графиками. + +### 2.2. Макет 1400 × 900 + +```text +┌──────────────────────────────────────────────────────────────────────────────────────────────� +│ � Базы │ Тренировка дебюта [+ Создать] [Импорт PGN…] ⚙ �а�тройки │ +├──────────────────────────────────────────────────────────────────────────────────────────────┤ +│ [Репертуары] [Прежние линии · 8] [�айти…] (е�ли >8) │ +│ │ +│ �азвание Включено ходов Белые: к повт. Чёрные: к повт. Обе �тороны ⋯ │ +│ ──────────────────────────────────────────────────────────────────────────────────────────── │ +│ Сицилиан�ка�, �айдорф 126 12 — 3 новых пути ⋯ │ +│ Каро-Канн, за чёрных 84 — 7 давно: 4 ⋯ │ +│ И�пан�ка�, рабоча� 238 4 4 не было ⋯ │ +│ │ +│ Показаны в�е репертуары · 3 │ +└──────────────────────────────────────────────────────────────────────────────────────────────┘ +``` + +Правила таблицы: + +- Строка открывает�� одиночным щелчком по названию или Enter. Выделенна� �трока, hover и фоку� — �уще�твующие �о�то�ни� таблиц библиотеки. +- «Включено ходов» — чи�ло уникальных тренируемых рёбер в полном PGN без учёта текущей глубины; disabled и недо�тижимые из-за disabled не вход�т. Тран�позиционные повторы `(FEN4, UCI)` �читают�� один раз. +- Прочерк в `White`/`Black` означает, что в режиме нет целей либо режим ещё не и�пользовал��; tooltip ра�крывает причину. �оль выводит�� именно как `0`, когда цели е�ть, но ни одна не due. +- «Обе �тороны» не показывает due: у режима нет SRS. Зде�ь выводит�� полезный факт — `N новых путей`, `давно не было: N`, `не было` или `по�ледний проход: {дата}`. Он не �кладывает�� � одноцветной �тати�тикой. +- Меню `⋯`: «Открыть», «Переименовать», «Импортировать PGN в �тот репертуар…», «Эк�портировать PGN…», «Удалить…». +- Пор�док по умолчанию — �начала �троки � незавершённой �е��ией, затем по названию. Сортировка по колонкам до�тупна незави�имо дл� due White и due Black; общего рейтинга или �уммы режимов нет. +- Длинные �пи�ки виртуализируют��. Пои�к по�вл�ет�� только при более чем во�ьми репертуарах и фильтрует по названию без изменени� пор�дка PGN внутри них. + +### 2.3. Создание и переименование + +**Создать** в�тавл�ет первую �троку � полем названи� и кнопками «Создать» / «Отмена»: + +- пу�тое название по�ле trim не принимает��; +- названи� уникальны без учёта реги�тра и повтор�ющих�� пробелов, по�кольку они и�пользуют�� в компактном выборе назначени�; +- длина — до 120 Unicode-�имволов, полный тек�т в�егда до�тупен в tooltip и на �кране репертуара; +- Enter �оздаёт, Esc отмен�ет; фоку� о�таёт�� в поле при ошибке; +- новый пу�той репертуар из библиотеки получает �тандартную начальную позицию. Пу�той репертуар, �озданный из FEN-партии, на�ледует её и�ходный FEN; +- по�ле у�пешной атомарной запи�и открывает�� �кран пу�того репертуара, не тренировка. + +**Переименовать** превращает название в той же �троке в поле. ID, PGN, disabled, очередь и в�� �тати�тика не мен�ют��. Enter �охран�ет, Esc отмен�ет, клик вне пол� не тер�ет молча введённый тек�т, а о�тавл�ет режим редактировани� до �вного выбора. + +### 2.4. Удаление + +«Удалить…» ра�крывает под �трокой поло�у: + +```text +Удалить «И�пан�ка�, рабоча�» и в�ю её новую �тати�тику? И�ходные PGN и прежние линии не измен�т��. +[Отмена] [Удалить репертуар] +``` + +- Удал�ют�� только �амодо�таточный PGN репертуара, его и�точники-��ылки, на�тройки и нова� �тати�тика в�ех трёх режимов. +- И�ходные базы, импортированные файлы и legacy line-run не затрагивают��. +- До у�пешной запи�и �трока не и�чезает. При ошибке о�таёт�� поло�а ошибки � «Повторить». +- Е�ли е�ть незавершённа� тренировка �того репертуара, она �начала закрывает�� без запи�и завершени�; уже за�читанные попытки о�тают�� в удал�емой �тати�тике и и�чезают только вме�те � �вным удалением. + +### 2.5. Пу�та� библиотека и прежние линии + +Пу�тое �о�то�ние занимает центральную обла�ть, без декоративных карточек: + +```text +Репертуаров пока нет +Создайте пу�той или импортируйте PGN. Можно также выбрать ход в любой партии +и нажать «Добавить в репертуар…» — добавит�� путь только до �того хода. +[+ Создать] [Импорт PGN…] +``` + +Вкладка «Прежние линии · N» показывает�� только при наличии legacy `LineStats`. Это отдельна� таблица: + +`Лини� · Прохождени� · Ошибки по�леднего · Лучшее · Чи�та� �ери� · По�ледние · Дата`. + +- Под�казанные прохождени� обозначают�� `*`, как раньше. +- �икаких колонок «точно�ть хода», «�ледующий ход» или per-move ошибок зде�ь нет: �тарый формат �того не знает. +- Legacy-запи�и не превращают�� автоматиче�ки в новые репертуары, не получают `due_at` и не �уммируют�� � новыми попытками. +- Android продолжает читать и запи�ывать �ти данные прежним �по�обом. + +### 2.6. Ошибки библиотеки + +- �ечитаемый `training.json`: библиотека PGN открывает�� дл� про�мотра и �к�порта, но �оздание/изменение �тати�тики и запу�к тренировки о�танавливают��. Сверху по�то�нна� поло�а «�е удало�ь прочитать �тати�тику: {путь}. Файл не заменён» и «Повторить». Пу�тое хранилище молча не �оздаёт�� поверх повреждённого. +- Ошибка запи�и: операци� о�таёт�� видимой как не�охранённа�, по�вл�ет�� поло�а «�е удало�ь �охранить изменени� · Повторить». У�пешный то�т запрещён. +- Один повреждённый репертуар не �крывает о�тальные: его �трока о�таёт�� � тек�том «Ошибка PGN», открывает�� диагно�тика и �к�порт �охранённого и�ходного тек�та, е�ли он до�тупен. +- Импорт и по�троение индек�а — фоновые операции � прогре��ом и отменой. Отмена не о�тавл�ет новый репертуар или ча�ть �ли�ни�. + +## 3. Добавление из партии + +### 3.1. Точка входа + +�а desktop пункт меню хода и общего меню «Учить дебют до �того хода» замен�ет�� на **«Добавить в репертуар…»**. + +- До�тупен только на выбранном ходе. В начальной позиции — неактивен � причиной «Выберите ход, до которого добавить». +- Е�ли на пути е�ть учебный null move `--`, пункт неактивен: «В пути е�ть пропу�к хода (--)». Такой путь не превращает�� в обычные легальные ходы. +- Справа можно показывать название по�леднего �овме�тимого репертуара, но не чи�ло прохождений: нова� �тати�тика не line-run. + +### 3.2. Один компактный выбор назначени� + +Пункт открывает прив�занную к ходу панель шириной 360, не отдельный ма�тер: + +```text +Добавить в репертуар +1.e4 c5 2.Nf3 d6 3.d4 cxd4 4.Nxd4 — 7 полуходов +(•) Сицилиан�ка�, �айдорф +( ) И�пан�ка�, рабоча� +( ) �овый репертуар: [Сицилиан�ка� за белых____________] +[Отмена] [Добавить] +``` + +- Показывают�� только репертуары � �овме�тимой начальной позицией. При более чем во�ьми — поле пои�ка внутри той же панели. +- По умолчанию выбран по�ледний репертуар, е�ли он �овме�тим, иначе первый; «�овый репертуар» в�егда до�тупен и на�ледует и�ходный FEN. +- Видна точна� лини� в компактной форме и чи�ло полуходов. Полный SAN — tooltip; прокрутка длинной �троки не ра�т�гивает окно. +- Enter — «Добавить», Esc/клик вне — отмена. По�ле закрыти� фоку� возвращает�� и�ходному ходу. + +### 3.3. Что именно добавл�ет�� + +1. Путь от и�ходной позиции до выбранного хода **включительно**, даже е�ли ча�ть пути находит�� внутри RAV. +2. Комментарии и NAG корн� и узлов �того пути, включа� комментарии непо�ред�твенно до/по�ле выбранного хода. +3. И�ходный FEN и пор�док ходов пути. +4. **�е добавл�ют��**: продолжение по�ле выбранного хода, �о�едние ветки любого уровн�, другие партии базы и �лужебные �трелки/оценки временной партии. +5. Добавление не запу�кает тренировку, не мен�ет и�ходную `revision`, не �оздаёт Undo в и�ходной партии и не мен�ет её файл. + +По�ле у�пешной запи�и и�ходна� парти� о�таёт�� на том же ходу. То�т: + +`Добавлено в «Сицилиан�ка�, �айдорф»: новых ходов: 4 · �овпало: 3 · [Открыть]`. + +Е�ли изменили�ь только аннотации: `Путь уже был в репертуаре; добавлены аннотации: N`. При полном дубле: `Уже в репертуаре — изменений нет`. Эти �ообщени� не означают запу�к или �бро� �тати�тики. + +### 3.4. И�точник и возврат + +С репертуаром �охран�ют�� навигационные �ведени� об и�точнике: файл, индек� запи�и, контрольное значение �одержимого и UCI-путь. Они не �вл�ют�� хранилищем репертуара. + +- «Открыть и�точник» �начала провер�ет файл и линию. При изменении/удалении базы выводит�� «И�точник изменил�� или недо�тупен; репертуар �охранён» — �лучайна� парти� по прежнему индек�у не открывает��. +- Переименование или удаление и�точника не вли�ет на дерево, очередь и �тати�тику. +- У одной ветки может быть не�колько и�точников; про�мотр показывает их �пи�ком, без копировани� дерева. + +## 4. Импорт PGN и �ли�ние + +### 4.1. �азначение + +- «Импорт PGN…» в библиотеке �оздаёт **один новый репертуар** из в�его выбранного файла. +- «Импортировать PGN в �тот репертуар…» на �кране/�троке добавл�ет ве�ь файл в �уще�твующий. +- Multi-game PGN **не разбивает�� на репертуары по чи�лу партий**: в�е запи�и �ливают�� в одно дерево, как линии одного репертуара. +- Им� нового репертуара по умолчанию — им� файла без ра�ширени�; при конфликте добавл�ет�� чи�ловой �уффик�, который можно �разу изменить inline. + +### 4.2. Предпро�мотр без модального окна + +По�ле �и�темного выбора файла в библиотеке или над деревом ра�крывает�� панель: + +```text +Импорт: repertoire.pgn +Запи�ей PGN: 24 · новых ходов: 386 · �овпадающих путей: 51 · ветвей: 73 +Комментарии и NAG: �охранить · мак�имальна� глубина: 48 полуходов +При текущей глубине 20 в тренировку войдёт 214 целей из 386 +⚠ 2 ветки �одержат «--»: �охран�т�� дл� чтени�, в тренировку не попадут +[Отмена] [Импортировать в один репертуар] +``` + +Предпро�мотр об�зан показывать ма�штаб **до запи�и**: запи�и, новые/�овпадающие ходы, чи�ло ветвей, мак�имальную глубину и объём при текущей глубине. Дл� нового репертуара в ра�чёте уже �тоит 20 полуходов. Полные партии не объ�вл�ют�� автоматиче�ки «примерными» и не обрезают��. + +### 4.3. Правила �ли�ни� + +1. Сначала разбирает�� и провер�ет�� ве�ь файл; запи�ь выполн�ет�� один раз по�ле подтверждени�. Ча�тичный �крытый импорт запрещён. +2. Общий префик� �овпадает по �тартовой позиции и по�ледовательно�ти шахматных ходов, не по �троке SAN. Пор�док �уще�твующих детей не мен�ет��; новые дети добавл�ют�� в пор�дке запи�ей PGN и RAV. +3. Е�ли дерево пу�тое, перва� о�новна� лини� первой запи�и �тановит�� о�новной. Multi-game запи�и добавл�ют �вои ответвлени� от общего корн�; заголовки `White`, `Black`, `Event` не �оздают �амо�то�тельные репертуары. +4. Точный повтор пути � теми же аннотаци�ми — no-op: нет новых узлов, дублей комментариев или �бро�а и�тории. +5. Совпавшие узлы � новыми аннотаци�ми не тер�ют ни �тарые, ни новые данные: + - отличающий�� комментарий добавл�ет�� отдельным блоком в пор�дке импорта; + - одинаковый комментарий повторно не добавл�ет��; + - NAG объедин�ют�� как набор без чи�ловых дублей; разные оценочные NAG �охран�ют�� и показывают�� оба; + - disabled/enable и ручна� глубина �уще�твующего репертуара не �бра�ывают��. +6. �овые ветки по умолчанию enabled. Повторный импорт ранее отключённой �уще�твующей ветки **не включает её �ам**. +7. Изменени� PGN не удал�ют learning-запи�и неизменных `(FEN4, UCI)`. Удалённа� из нового импорта ветка не удал�ет�� из �уще�твующего репертуара: импорт только добавл�ет и дополн�ет аннотации. +8. В�е запи�и должны иметь �овме�тимую и�ходную позицию. Разные FEN в одном файле не �мешивают�� молча: импорт о�танавливает�� � номерами запи�ей и тек�том «В одном репертуаре должна быть одна и�ходна� позици�». Дл� пу�того репертуара первый FEN задаёт корень. +9. `fullmove=0` нормализует�� �уще�твующим правилом � диагно�тикой; �тарт чёрных и нумераци� �охран�ют��. Счётчики halfmove/fullmove не уча�твуют в FEN4-тран�позици�х, но и�ходный FEN о�таёт�� в PGN. +10. Учебный `--`, неподдерживаемые токены и неиграбельные уча�тки �охран�ют�� дл� чтени�/�к�порта и получают диагно�тику. Узлы по�ле нево��тановимого нелегального хода не угадывают��; такой файл отклон�ет�� целиком, а не обрезает�� молча. Играбельные ветки, изолированные корректно ра�познанным `--`, не попадают в очередь. +11. Legacy-кодировки проход�т �уще�твующий импорт � замечани�ми. И�ходный файл не перекодирует�� и не перезапи�ывает��; внутренний �нимок может быть нормализованным UTF-8 PGN, но об�зан �охранить дерево и �одержимое аннотаций. + +По�ле у�пеха новый репертуар открывает�� на дереве; при добавл�ющем импорте о�таёт�� текущий �кран и активный ход. Показывает�� �водка фактиче�ки запи�анных изменений, не тренировка. + +## 5. Экран одного репертуара + +### 5.1. Задача и приоритет + +Зде�ь пользователь читает аннотированное дерево, �вно ограничивает объём и запу�кает выбранный вид повторени�. До�ка и дерево важнее �тати�тики; �тати�тика не превращает �кран в dashboard. + +### 5.2. Макет 1400 × 900 + +```text +┌──────────────────────────────────────────────────────────────────────────────────────────────� +│ � Репертуары │ Сицилиан�ка�, �айдорф [Импорт PGN…] [Эк�порт PGN] [⋯] ⚙ �а�тройки │ +├───────────────────────────────────────────────────────────────────┬──────────────────────────┤ +│ │ Режим: [Белые|Чёрные|Оба] │ +│ │ Очередь: [По ра�пи�анию ▾] │ +│ ДОСК� │ Глубина: [20] полуходов │ +│ (активна� позици�) │ Обла�ть: Ве�ь репертуар ⌄ │ +│ │ В обла�ти: 86 целей │ +│ │ К повторению: 12 · новых: 34│ +│ │ [▶ �ачать: 12 к повторению] │ +│ ├──────────────────────────┤ +│ │ [Дерево] [Стати�тика] │ +│ │ 1 e4 c5 │ +│ │ 2 Nf3 d6 │ +│ │ ├ 2…Nc6 ⌀ не учить │ +│ │ └ 2…e6 ⇄ 2 пути │ +│ │ 3 d4 cxd4 │ +│ │ … комментарии и NAG … │ +│ │ ────────────────────────── │ +│ │ Выбран 2…d6 · запланирован │ +│ │ Верных: 8/10 · �ледующий:… │ +│ ├──────────────────────────┤ +│ │ � ◀ ▶ � │ 🔃 │ ☰ │ +└───────────────────────────────────────────────────────────────────┴──────────────────────────┘ +``` + +Права� панель — �уще�твующа� бокова� панель партии, не набор �амо�то�тельных карточек. �а�тройки тренировки закреплены �верху; дерево прокручивает�� незави�имо. Рамка только отдел�ет функциональные обла�ти. + +### 5.3. Выбор режима, обла�ти, глубины и очереди + +**Режим** — три �егмента: + +- `Белые` — target-ходы только белых, ответы программы только за чёрных; +- `Чёрные` — target-ходы только чёрных, ответы программы только за белых; +- `Обе �тороны` — пользователь делает каждый полуход, автоматиче�ких ответов нет. + +По�ледний выбранный режим и очередь запоминают�� отдельно дл� репертуара. Смена режима не перено�ит очередь, кур�ор обзора, due или �тати�тику другого режима. + +**Обла�ть** — компактный selector над деревом: + +- `Ве�ь репертуар`; +- `От хода {SAN}` по�ле команды контек�тного меню «Тренировать �ту ветку» или кнопки «Сделать обла�тью» у выбранного хода. + +Дл� ветки показывает�� путь и отдельна� `×` дл� �бро�а к в�ему репертуару. Подвод�щий путь до родител� выбранного хода — автоматиче�кий контек�т; �ам выбранный ход провер�ет��. �ктивна� позици� на до�ке, выделенный ход в дереве и назначенна� обла�ть — разные �о�то�ни�: обла�ть обозначена значком `▶` и тек�товой �трокой, не только цветом. + +**Глубина**: + +- чи�ловое поле от 1 до 999 полуходов � кнопками `−` / `+` и отдельным пунктом меню «Без ограничени�»; +- по умолчанию 20; значение �охран�ет�� на репертуар; +- глубина 20 разрешает рёбра � номерами 1…20 от корн�, а не 20 ходов от начала выбранной ветки; +- изменение глубины �разу пере�читывает цели и знаменатели, не удал�ет �тати�тику вне лимита; +- при FEN-�тарте глубина в�ё равно �читает�� от корн� репертуара, а не от номера полного хода в и�ходном FEN. + +**Очередь** зави�ит от режима: + +| Режим | Варианты | +|---|---| +| White / Black | `По ра�пи�анию`, `Подр�д`, `Сначала новые и давние` | +| Both | `По дереву`, `Сначала новые и давние` | + +В `Both` нет SRS, due и до�рочного повторени�. Под выбором в�егда е�ть короткое по��нение: дл� обзоров — `Сроки повторений не мен�ют��`, дл� SRS — `Сначала ходы � на�тупившим �роком`. + +**Главна� кнопка** формулирует фактиче�кий запу�к: + +- `�ачать: 12 к повторению`; +- е�ли due=0 и е�ть непред�тавленные в SRS — `�ачать: 10 новых` (или меньше, е�ли о�тало�ь меньше); +- дл� обзора — `�ачать обзор: 86 ходов` / `�ачать проход веток`; +- е�ли до�тупных ходов нет — неактивна, а причина находит�� на её ме�те, не только в tooltip. + +### 5.4. Дерево и дей�тви� над ветками + +И�пользует�� �уще�твующа� нотаци� � вложенными вариантами, комментари�ми и NAG, только чтение ходов. В про�мотре до�тупны в�е узлы, включа� disabled и глубже лимита. + +Обозначени�: + +- disabled: `⌀` + тек�т `не учить` у корн� ветки; в�� отключённа� обла�ть дополнительно получает приглушённый тек�т, но о�таёт�� контра�тной и читаемой; +- глубже лимита: небольшой тек�т `>20` у первого и�ключённого хода; �то не disabled; +- тран�позици�: `⇄ N путей`, ра�крытие показывает SAN-пути и позвол�ет перейти к каждому; +- активный ход — �уще�твующа� заливка кур�ора; выбранна� обла�ть — `▶` �лева; ра�крыта� ветка — disclosure-�трелка. Эти �о�то�ни� не �ливают��. + +Контек�тное меню хода: + +- «Показать позицию»; +- «Тренировать �ту ветку»; +- «�е учить ветку» / «Вернуть в тренировку»; +- «Показать �тати�тику хода»; +- «Открыть и�точник», е�ли и�точник �уще�твует. + +**�е учить ветку** отключает выбранное ребро и недо�тижимое через него поддерево дл� будущих очередей и ответов программы. PGN, комментарии, NAG, �к�порт и прежн�� и�тори� �охран�ют��. Повторное включение возвращает прежние запи�и без дублей. + +Е�ли та же позици� или ход до�тижимы другой enabled-тран�позицией, логиче�ка� цель о�таёт�� в очереди по �тому альтернативному пути. По�тому disabled — �вой�тво PGN-ветки, а не молчалива� глобальна� блокировка FEN во в�ём репертуаре. + +Редактирование ходов, promote/delete и ма��овые операции не вход�т в �тот объём. «Эк�порт PGN» выпи�ывает в�ё дерево, включа� disabled и хво�ты глубже лимита. + +### 5.5. Пу�той репертуар и подготовка дерева + +Пу�той репертуар показывает и�ходную до�ку и вме�то нотации: + +```text +В репертуаре пока нет ходов +[Импорт PGN…] +Или откройте партию, выберите по�ледний ход нужной линии +и нажмите «Добавить в репертуар…». +``` + +Кнопки режима и глубины видны, запу�к неактивен. По�ле большого импорта дерево до�тупно дл� чтени�, а пока �троит�� FEN4-индек�, вме�то запу�ка — `Готовим дерево… {прогре��}` и «Отмена». Тренировка не �тартует на ча�тично по�троенном индек�е. + +## 6. Единые правила тренировки + +### 6.1. Ввод и позици� + +- �а до�ке можно ходить только фигурами �тороны, чей ход на�тупил. В `White`/`Black` ввод противоположной �тороны недо�тупен; в `Both` до�тупны обе по очереди. +- �елегальна� попытка не �оздаёт шахматный ход, не �читает�� ошибкой и не мен�ет �тати�тику. +- Превращение в�егда открывает �уще�твующий выбор фигуры, незави�имо от на�тройки автоферз�. Ферзь вме�то кон� — другой UCI и ход вне цели/вариантов. +- Ориентаци�: `White` — белыми вниз, `Black` — чёрными вниз, `Both` — как на �кране репертуара. `F` переворачивает; автоматиче�кого переворота по�ле полухода нет. +- Про�мотр уже �ыгранных ходов разрешён. Попытка хода из прошлого возвращает к текущему концу без ошибки. +- Движок, Справочник, редактирование, �охранение как парти� и в�тавка PGN выключены. `L` и `Shift+A` дают прежний то�т «Во врем� тренировки движок выключен». + +### 6.2. Ошибка и flash + +Легальный ход вне разрешённого набора: + +1. фигура на 400 м� в�таёт на выбранное поле, клетки from/to получают �уще�твующую кра�ную заливку ошибки; +2. звучит `Wrong`, �чётчик неверных попыток увеличивает�� ровно на 1; +3. новый ввод на �ти 400 м� блокирует��; +4. позици� возвращает��, кра�на� заливка �нимает��, �ообщение о�таёт�� до правильного хода; +5. кажда� повторна� попытка �нова �читает��. + +Сообщени� различают модели: + +- одноцветный режим: `✗ Сейча� в репертуаре ожидает�� другой ход`; +- `Both`: `✗ Этот ход вне включённых вариантов`. + +Disabled-ход и ход глубже текущего лимита в активной тренировке �читают�� вне разрешённого набора. �е и�пользует�� оценка «объективно хороший/плохой» — движка нет. + +### 6.3. Под�казка и �пойлеры + +- По�ле **третьей неверной попытки на текущем задании/позиции** по�вл�ет�� ��ылка «Показать ход». До �того правильный ход не ра�крывает��. +- Стрелка по�вл�ет�� только по �вному запро�у. В одноцветном режиме она показывает target-UCI; в `Both` — первый enabled-ребёнок в канониче�ком PGN-пор�дке. +- По�ле под�казки в `Both` любой enabled-ребёнок по-прежнему принимает��, а не только показанный. +- Пользователь �ам делает ход. Под�казка помечает задание и ве�ь проход `� под�казкой`, �бра�ывает чи�тую �ерию и не даёт чи�того результата. +- До попытки �крыты будущие ветки, комментарии, NAG, автор�кие �трелки, �ледующие SAN и �тати�тика, �по�обна� назвать ответ. В нотации — только контек�т и фактиче�ки �ыгранный текущий путь. +- Во врем� тренировки нельз� переключить�� на полное дерево. По�ле завершени� открывают�� аннотации только пройденного пути; полное дерево до�тупно через «К репертуару». + +## 7. Одноцветный режим: White / Black + +### 7.1. Задание + +Единица — конкретный target-ход выбранного цвета. Очередь никогда не превращает�� в общий проход за обе �тороны. + +�ачало задани�: + +1. Программа во��танавливает канониче�кий путь к позиции **перед target-ходом**. Подвод�щие ходы обеих �торон, включа� ходы цвета пользовател�, показывают�� как контек�т и не �оздают попыток. +2. В�е автоматиче�кие ходы �оответ�твуют enabled-дереву, обла�ти и глубине. При не�кольких пут�х к FEN4 и�пользует�� �амый короткий enabled-путь; при равен�тве — первый в PGN-пор�дке. +3. Верхн�� панель �ообщает `Белые · по ра�пи�анию`, номер задани� в текущей �е��ии и `♔ ход белых` / `♚ ход чёрных`. SAN цели не показывает��. +4. Е�ли �ледующее задание продолжает текущий путь, программа доходит до него только ходами противоположной �тороны и нужным контек�том. Е�ли задание в другой ветке, переход к нему выполн�ет�� без имитации неправильного ответа на до�ке. + +### 7.2. Ответ пользовател� + +- **Target-UCI:** правильный ответ. Ход за�читывает��, �тати�тика запи�ывает��. Е�ли �ледующий ход принадлежит программе и е�ть enabled-ребёнок внутри глубины, программа делает один ответ из канониче�кого продолжени�; �тот ответ не �вл�ет�� попыткой и не мен�ет очередь. Е�ли ответа нет, задание нормально завершает�� на раннем ли�те. +- **Другой enabled-ребёнок того же пользователь�кого цвета, но не текуща� цель:** отдельный `try again`, не ошибка. Фигура возвращает�� по�ле 250 м�, нейтральна� рамка вме�то кра�ной, звука `Wrong` нет: + + `Этот ход е�ть в репертуаре, но �ейча� повтор�ет�� другой · Попробуйте ещё раз`. + + Он не увеличивает mistakes, не мен�ет accuracy, streak, hint counter или due. Позже альтернатива о�таёт�� �амо�то�тельной целью очереди. +- **Легальный ход вне enabled-дерева, disabled-ребёнок или ход за глубиной:** обычна� неверна� попытка по §6.2. + +�икакой enabled-альтернативы, автоматиче�ки за�читанной как target, зде�ь нет: �тим одноцветный режим принципиально отличает�� от `Both`. + +### 7.3. Завершение задани� и �е��ии + +По�ле target-хода показывает�� короткое `✓ Верно`; при ошибках/под�казке — `✓ Прин�то · будет повторено раньше`. Следующее задание не начинает��, пока результат текущего не �охранён. + +Се��и� заканчивает��, когда и�черпана выбранна� очередь/пакет новых либо пользователь вышел. Ли�т раньше глубины — нормальное завершение пути, не ошибка и не повод добавить ход извне дерева. + +Итог SRS/обзора показывает: + +`Заданий: N · правильных: N · неверных попыток: N · � под�казкой: N`. + +Дл� SRS дополнительно — `К повторению �ейча�: 0` и дей�тви� из §9.3. �ет процента «дебют выучен». + +## 8. Режим Both: проход за обе �тороны + +### 8.1. �езави�има� модель + +`Both` не и�пользует target-SRS и не требует заранее выбранный ход. Пользователь делает **каждый полуход** от начала обла�ти до границы. Программа не отвечает ни за белых, ни за чёрных. + +�а каждой позиции: + +- разрешённый набор — в�е enabled-дети канониче�кой FEN4-группы внутри обла�ти и глубины; +- **любой** из них принимает��, запи�ывает�� как фактиче�ки �ыгранный ход и ведёт по его ветке; +- от�ут�твие `try again`: не бывает «верный ход, но не тот путь»; +- любой легальный ход вне набора — ошибка по §6.2; +- disabled-ребёнок и продолжение за глубиной — вне набора. + +Верхн�� панель показывает `Обе �тороны · проход ветки`, `Полуход 7 из не более 20` и текущую �торону. Е�ли ли�т на�тупит раньше, заранее обещать точное чи�ло полуходов нельз�. �отаци� пополн�ет�� фактиче�ким путём, а не заранее выбранной mainline. + +### 8.2. Ли�т, глубина и повторение позиции + +Проход у�пешно заканчивает�� в одном из �лучаев: + +1. нет enabled-детей — `Ветка завершена`; +2. �ыгран по�ледний разрешённый полуход глубины — `До�тигнута глубина: 20 полуходов`; +3. канониче�кое продолжение привело к FEN4, уже в�тречавшему�� в �том проходе, — `Позици� повторила�ь · проход завершён`. Это защита от цикла при FEN4 без �чётчиков, не ошибка. + +Пу�та� обла�ть или от�ут�твие enabled-детей **до первого пользователь�кого хода** не �читает�� у�пешным проходом: показывает�� �о�то�ние на�тройки «�ет включённых ходов в �той обла�ти». + +### 8.3. Повтор пути и новый проход + +Итог �одержит две разные команды: + +- **«Повторить путь»** — начать ту же обла�ть � тем же предложенным маршрутом. Это не превращает прошлый путь в фик�ированную линию: на развилке любой enabled-ребёнок �нова принимает��. +- **«�овый проход»** — получить �ледующий предложенный маршрут по выбранной очереди веток. + +Итог: `Пройдено полуходов: N · ошибок: N · � под�казкой: да/нет`. В нотации фактиче�кого пути ошибки отмечают�� `×N` у позиции, а не при�ваивают�� произвольному «ожидаемому» SAN. + +Е�ли предложенный маршрут A пользователь �менил на enabled-маршрут B, �тати�тику получает B; A не отмечает�� пройденным. Это правило об�зательно и дл� «По дереву», и дл� «Сначала новые и давние». + +## 9. Очереди и ра�пи�ание + +### 9.1. Общие �тату�ы + +Стату�ы видимы тек�том и не опирают�� только на цвет: + +| Стату� | Значение | +|---|---| +| `�овый` | Дл� �того режима ещё не было ни одной оценённой попытки � �тим ходом/путём | +| `К повторению` | Только White/Black SRS: `due_at <= now` | +| `Запланирован` | Е�ть будущий `due_at`; р�дом видна дата | +| `Вне ра�пи�ани�` | Ход уже в�тречал�� в обзоре, но SRS-�рок ему не назначал�� | +| `Обзор` | Маркер текущей до�рочной/по�ледовательной �е��ии; не уровень mastery | +| `Давно не было` | Пор�док по `last_seen`, без выдуманного порога в дн�х | +| `�е учить` | И�ключено из текущих очередей; и�тори� �охранена | + +�ет �тату�ов `Learnt`, `Mastered` или процента «выучено». Чи�та� �ери� — только факт �ерии, не доказатель�тво долговременного знани�. + +### 9.2. White/Black: три очереди + +**По ра�пи�анию (SRS)** + +1. Сначала в�е due выбранной обла�ти и глубины, по `due_at`, затем по канониче�кому PGN-пор�дку. Одна FEN4+UCI-цель по�вл�ет�� один раз. +2. Unseen не затапливают due. �овые ввод�т�� отдельными �вными пакетами **до 10 целей** в пор�дку depth-first PGN mainline-first. +3. В пакет введени� вход�т `�овый` и `Вне ра�пи�ани�`; �начала новые, затем виденные без �рока. +4. У�пех отодвигает �рок, ошибка приближает. До�рочные/по�ледовательные обзоры �роки не мен�ют. + +Фик�ированные правила v1, без �крана ко�ффициентов: + +- чи�тый правильный ответ на новой цели или по�ле lapse — `due = now + 1 день`; +- �ледующий чи�тый правильный ответ — прежний интервал ×2, минимум 1 день, мак�имум 365 дней; +- кажда� неверна� попытка — `due = now + 10 минут`, чи�та� �ери� �бра�ывает��, цель помечает�� lapse; +- правильный ответ по�ле ошибки в том же показе или по�ле под�казки за�читывает�� как ответ, но о�тавл�ет `due = now + 10 минут`; �ледующий чи�тый у�пех по�ле �того �нова даёт 1 день; +- `try again` ничего в ра�пи�ании не мен�ет; +- короткий �рок не означает немедленный показ раньше других due. + +**Подр�д (Review in order)** + +- Depth-first обход enabled-целей, mainline-first, без повторов тран�позиций. +- Сроки SRS не мен�ют��. Попытки, ошибки, под�казки и `last_seen` запи�ывают��. +- Ме�то обзора запоминает�� отдельно дл� `(репертуар, режим, обла�ть)`. По�ле по�ледней цели итог предлагает «�овый проход» — кур�ор возвращает�� к первой. +- При изменении дерева/глубины кур�ор перено�ит�� на ближайшую �ледующую �уще�твующую цель; удалённа�/disabled не показывает��, дублей нет. + +**Сначала новые и давние (Least recent/unseen)** + +- Сначала в�е `�овый` в PGN-пор�дке, затем о�тальные по возра�танию `last_seen`; при равен�тве — PGN-пор�док. +- Сроки SRS не мен�ют��. Это обзор, а не �крытое введение в�его дерева в ра�пи�ание. +- По�ле цикла до�тупен новый проход по обновлённым `last_seen`. + +### 9.3. Когда due = 0 + +�икакого автоматиче�кого перехода ко в�ем unseen или будущим цел�м нет. + +Итог `К повторению �ейча�: 0` �одержит незави�имые дей�тви�: + +1. **«Добавить новые: 10 из N»** — �вно вве�ти �ледующий пакет. Е�ли N=0, кнопки нет. +2. **«Повторить будущие раньше»** — только запланированные цели, ближайший `due_at` первым. �а в�ём таком проходе видна поло�а `До�рочный обзор · �роки не мен�ют��`; попытки и last_seen пишут��, `due_at` и интервалы о�тают�� прежними. +3. **«Обзор подр�д»** — переключить�� на по�ледовательный обзор обла�ти. +4. **«К репертуару»**. + +Е�ли нет ни новых, ни будущих, о�тают�� только обзор и возврат. Первый запу�к нового репертуара и�пользует ту же �вную формулировку на главной кнопке `�ачать: 10 новых`, по�тому отдельного пу�того SRS-�крана в �той �итуации нет. + +### 9.4. Both: очередь путей, не целей + +- **По дереву:** depth-first предложение root-to-boundary маршрутов в PGN-пор�дке. Кур�ор цикла хранит�� отдельно дл� обла�ти. +- **Сначала новые и давние:** �начала пути, ни разу не завершённые в `Both`, затем пути по �амому давнему фактиче�кому завершению; при равен�тве — PGN-пор�док. +- Любое enabled-отклонение мен�ет фактиче�кий путь. Запи�ывает�� он; предложенный, но не пройденный путь �охран�ет прежний �тату�. +- Даты due, интервалы и пакеты новых одноцветного режима зде�ь не �оздают�� и не измен�ют��. +- Спи�ок путей генерирует�� по мере необходимо�ти; большое дерево не разворачивает�� целиком ради по�троени� очереди. + +## 10. Тран�позиции FEN4 + +1. Ключ позиции — нормализованные первые четыре пол� FEN: фигуры, �торона хода, права рокировки и **легальное** en passant. Halfmove/fullmove не вход�т. +2. В PGN в�е узлы и пути о�тают�� отдельными. FEN4-индек� — производный �лой, не перепи�ывание дерева в DAG. +3. Внутри репертуара и одного режима `(FEN4, UCI)` имеет одну learning-запи�ь и одно ме�то в очереди. +4. Кандидаты продолжени� — объединение enabled-детей в�ех до�тижимых узлов FEN4-группы. Пор�док: �начала дети первого узла в PGN depth-first, затем новые ходы из о�тальных узлов в том же пор�дке. +5. Дл� конкретного UCI выбирает�� одно канониче�кое продолжение: первое enabled-ребро в указанном пор�дке, по�ле чего работа продолжает�� � FEN4-группой результата. По�тому продолжение не дублирует��, а проход не заканчивает�� про�то из-за тран�позиции. +6. Путь и путевые комментарии не тер�ют��: в про�мотре `⇄ N путей` ра�крывает их. В тренировке контек�т к цели — кратчайший enabled-путь, tie-break по PGN. +7. Disabled-ветка и�ключает �вои рёбра, но не блокирует тот же логиче�кий ход, е�ли он до�тижим через другой enabled-путь. +8. Стати�тика одинаковых позиций разных репертуаров не объедин�ет��. `White`, `Black`, `Both` тоже имеют незави�имые запи�и. +9. Цикл по FEN4 в `Both` завершает�� по правилу §8.2; в одноцветном target-режиме бе�конечного автоматиче�кого прохода нет. + +## 11. Стати�тика без ложного mastery + +### 11.1. Что видно на каждом уровне + +| Уровень | White / Black | Both | +|---|---|---| +| Текущее задание/позици� | �омер задани�, ошибки �ейча�, под�казка, режим очереди | Полуходы текущего пути, ошибки �ейча�, под�казка | +| Ход | Попытки, correct, wrong, hints, `correct/(correct+wrong)`, чи�та� �ери�, last seen, last attempt, next due, по�ледние неверные SAN | Сколько раз ход фактиче�ки �ыгран, last played; ошибки и под�казки отно��т�� к позиции перед ходом, а не к выдуманной един�твенной цели | +| Ветка | Включено целей, новых, due, запланировано, виденных; по�ледние ошибки; disabled и�ключены из знаменател� | Завершени�, чи�тые/� под�казкой, ошибки, по�ледний проход, фактиче�кие пути, новые/давние | +| Репертуар | Отдельные чи�ла White и Black: enabled в обла�ти, seen/total, due, unseen, unscheduled | Завершённые пути/в�его до�тупных, новые, last completion; без due | +| И�тори� | Дата, режим, обла�ть, тип очереди, задани�, correct/wrong/hints, завершена/прервана | Дата, обла�ть, фактиче�кий путь, полуходы, ошибки, под�казка, завершён/прерван | + +Правила пред�тавлени�: + +- Точно�ть в�егда подпи�ана как `Верных: 8 из 10`, р�дом может быть процент; голый процент без знаменател� запрещён. +- Под�казки показывают�� отдельно и не вход�т в чи�тые �ерии. +- Одноцветный `try again` не увеличивает ни правильные, ни ошибочные попытки; при желании показывает�� только в текущем �ообщении, не в и�ториче�кой accuracy. +- В `Both` неверный ход вне дерева запи�ывает�� на текущую позицию � фактиче�ким wrong UCI. Его нельз� при�ваивать первому enabled-ребёнку как ошибку �того ребра. +- Disabled и глубина мен�ют только текущий знаменатель. И�тори� не перепи�ывает�� задним чи�лом; в ней видна обла�ть/глубина на момент �обыти�. +- «Показано X из Y» не называет�� «Выучено X %». +- Ра�ширенные графики, resistant-наборы и ма��овые операции от�ут�твуют. + +### 11.2. Вкладка «Стати�тика» на �кране репертуара + +Без графиче�кого dashboard. Сверху — переключатель `Белые | Чёрные | Обе �тороны`, затем обычные таблицы: + +1. `Сводка` — чи�ла из таблицы §11.1 только выбранного режима. +2. `Ходы` — виртуализированна� таблица � фильтрами `В�е / К повторению / �овые / Давно не было / С ошибками / �е учить`; �ортировка по �року, last_seen и чи�лу ошибок. +3. `И�тори�` — по�ледние �обыти� выбранного режима, новые �верху, ограниченна� �траницами/виртуализацией. + +Выбор �троки «Ходы» показывает позицию на до�ке и �оответ�твующий узел/в�е тран�позиционные пути в дереве. Это про�мотр, не запу�к и не ра�крытие ответа в активной тренировке, по�кольку �кран �тати�тики из тренировки недо�тупен. + +### 11.3. �езавершённое + +- Выход или «Сначала» не �оздаёт завершение пути/�е��ии. +- Уже оценённые новые per-move �обыти� �охран�ют��: они реально произошли. �езавершённый `Both` не увеличивает чи�ло завершений пути; незавершённа� SRS-�е��и� не обнул�ет уже запи�анные ответы. +- При возврате в пределах одного запу�ка приложени� на �кране репертуара видна поло�а `�езавершённа� тренировка: {режим} · {прогре��}` � «Продолжить» и «�ачать заново». «�ачать заново» отбра�ывает только черновик текущего пути/показа, не и�торию. +- По�ле перезапу�ка приложени� черновик не во��танавливает��; и�тори� �одержит �обытие `прервана`, е�ли уже были оценённые дей�тви�, и никогда не показывает его как завершённое. +- Старый line-run ведёт �еб� по-прежнему: незавершённое �тарое прохождение не добавл�ет `runs`. + +## 12. Экран тренировки и адаптивные макеты + +### 12.1. 1400 × 900 + +```text +┌──────────────────────────────────────────────────────────────────────────────────────────────� +│ � К репертуару │ Сицилиан�ка�, �айдорф · Белые · По ра�пи�анию ⚙ �а�тройки │ +├───────────────────────────────────────────────────────────────────┬──────────────────────────┤ +│ │ ┌──────────────────────� │ +│ │ │ Задание 4 · ♔ белые │ │ +│ ДОСК� │ │ К повторению: 12 │ │ +│ │ └──────────────────────┘ │ +│ │ 1 e4 c5 │ +│ │ 2 Nf3 d6 │ +│ │ … только текущий путь … │ +│ │ ┌──────────────────────� │ +│ │ │ Ошибок: 2 │ │ +│ │ │ Показать ход (по�ле 3)│ │ +│ │ └──────────────────────┘ │ +│ │ � ◀ ▶ � │ 🔃 │ ↻ │ ✕ │ +└───────────────────────────────────────────────────────────────────┴──────────────────────────┘ +``` + +И�пользуют�� две функциональные рамки текущего тренера — задание �верху и �о�то�ние пользовател� �низу. �е добавл�ют�� графики, KPI-карточки, цветные плитки или второй р�д панелей. + +В `Both` верхн�� рамка: `Полуход 7 · ♚ чёрные` / `до глубины 20 или конца ветки`. �ижн��: `Ошибок: N` / �ообщение или «Показать ход». + +Итог занимает ме�то верхней/нижней функциональной обла�ти по образцу �уще�твующего `result_strip`; нотаци� о�таёт�� видимой. Дл� due=0 итог ра�крывает�� на вы�оту �вных дей�твий из §9.3, но не открывает модальное окно. + +### 12.2. Библиотека при 640 + +При 640 × 480 и 640 × 900 таблица о�таёт�� о�новным �одержимым; вы�окое окно добавл�ет �троки, а не новые панели. + +```text +┌────────────────────────────────────────────────────────────� +│ � Базы │ Тренировка дебюта [+ Создать] [Импорт] [⚙] │ +│ [Репертуары] [Прежние линии] │ +│ �азвание Б: к повт. Ч: к повт. ⋯ │ +│ Сицилиан�ка�, �айдорф 12 — ⋯ │ +│ Каро-Канн, за чёрных — 7 ⋯ │ +└────────────────────────────────────────────────────────────┘ +``` + +- Скрывают�� «Включено ходов», «Обе �тороны» и итогова� �трока; они до�тупны на �кране репертуара. �азвание �окращает�� � многоточием, полное — tooltip. +- Создание/переименование и подтверждение удалени� перено��т тек�т на две �троки, кнопки о�тают�� видимыми без горизонтальной прокрутки. +- Длинные EN/DE-подпи�и дей�твий могут перено�ить шапку на две �троки; `+ Создать` и `Импорт` не обрезают�� до непон�тных значков. + +### 12.3. Репертуар при 640 × 480 + +И�пользует�� правило «р�дом» из `narrow-windows.md`: до�ка �лева не меньше `BOARD_MIN`, права� панель не уже 240. + +```text +┌───────────────────────────────┬────────────────────────────� +│ � Репертуары │ Сицилиан�ка�… │ Режим: [Белые ▾] │ +│ │ Очередь: [По ра�пи�анию ▾] │ +│ ДОСК� │ Глубина: [20] · В�� ветка │ +│ │ 12 к повт. · 34 новых │ +│ │ [▶ �ачать] │ +│ │ [Дерево] [Стати�тика] │ +│ │ 1 e4 c5 │ +│ │ 2 Nf3 d6 │ +│ │ � ◀ ▶ � │ 🔃 │ ☰ │ +└───────────────────────────────┴────────────────────────────┘ +``` + +Вме�то трёх �егментов при недо�татке ширины — dropdown режима; механика не мен�ет��. Обла�ть выводит�� второй �трокой � `×`, полный путь — tooltip. Чи�ла не перено��т�� на кнопку запу�ка. Дерево и �тати�тика прокручивают��, на�тройки о�тают�� закреплены. + +### 12.4. Репертуар и тренировка при 640 × 900 + +По формуле `narrow-windows.md` и�пользует�� �топка: до�ка �верху, нижн�� панель � тем же �одержимым. �ижн�� панель получает не меньше 300 точек, е�ли �то возможно при `BOARD_MIN`; разделитель можно т�нуть. + +- �а�тройки запу�ка занимают две �троки: `Режим · Очередь` и `Глубина · Обла�ть`, затем �водка и главна� кнопка. Дерево о�таёт�� минимум � трем� видимыми �троками и �об�твенной прокруткой. +- В тренировке �верху до�ка, �низу задание, �ыгранна� нотаци� и �о�то�ние пользовател�. Функциональные рамки не �крывают нотацию целиком; �ообщение об ошибке может временно увеличить нижнюю рамку. +- При 640 × 480 о�таёт�� компоновка «р�дом», а не �топка: низкое окно не �кладывает��. + +### 12.5. Переполнение и HiDPI + +- Ра�кладка выбирает�� по до�тупным `W/H`, а не по фактиче�кой ширине тек�та прошлого кадра. Медленное изменение окна не вызывает мигани�. +- Длинные названи� и пути �окращают�� только там, где е�ть tooltip; ошибки, причины недо�тупно�ти и кнопки дей�твий перено��т�� полно�тью. +- В�е критичные �о�то�ни� провер�ют�� при 100/125/150/200 % ма�штаба. Под�ветка, фоку�, disabled, ошибка и тран�позици� различимы не только цветом. + +## 13. Подпи�и RU / EN / DE + +В�е �троки идут через �уще�твующую �и�тему перевода; чи�ла и формы множе�твенного чи�ла не �клеивают�� из отдельных �лов. Как минимум добавл�ют�� �ледующие ключи и �мы�ловые варианты: + +| RU | EN | DE | +|---|---|---| +| Тренировка дебюта | Opening training | Eröffnungstraining | +| Репертуары | Repertoires | Repertoires | +| Добавить в репертуар… | Add to repertoire… | Zum Repertoire hinzufügen… | +| Импорт PGN… | Import PGN… | PGN importieren… | +| Импортировать в один репертуар | Import into one repertoire | In ein Repertoire importieren | +| Белые / Чёрные / Обе �тороны | White / Black / Both sides | Weiß / Schwarz / Beide Seiten | +| По ра�пи�анию | Spaced schedule | Nach Zeitplan | +| Подр�д | Review in order | Der Reihe nach | +| Сначала новые и давние | Least recent and unseen first | Neue und älteste zuerst | +| К повторению | Due | Fällig | +| �овый | Unseen | Neu | +| Вне ра�пи�ани� | Unscheduled | Nicht eingeplant | +| До�рочный обзор · �роки не мен�ют�� | Early review · schedule unchanged | Vorzeitige Wiederholung · Zeitplan unverändert | +| Добавить новые: 10 из N | Introduce new: 10 of N | Neue hinzufügen: 10 von N | +| Повторить будущие раньше | Review future moves early | Künftige Züge früher wiederholen | +| �е учить ветку | Disable branch | Variante nicht lernen | +| Вернуть в тренировку | Enable for training | Wieder trainieren | +| Показать ход | Show move | Zug zeigen | +| Попробуйте ещё раз | Try again | Noch einmal versuchen | +| С под�казкой | With hint | Mit Hinweis | +| Повторить путь / �овый проход | Repeat path / New run | Pfad wiederholen / Neuer Durchgang | +| �езавершённа� тренировка | Unfinished training | Nicht abgeschlossenes Training | +| �е удало�ь �охранить изменени� | Could not save changes | Änderungen konnten nicht gespeichert werden | + +�азвани� режимов данных о�тают�� `White`, `Black`, `Both`; переводит�� только UI. Стату� не переводит�� как «выучено». Длинные немецкие �троки �вл�ют�� об�зательным fixture дл� проверки компоновки. + +## 14. Клавиатура, фоку� и до�тупно�ть + +### 14.1. Обща� карта + +| Клавиша | Библиотека/репертуар | Тренировка | +|---|---|---| +| Tab / Shift+Tab | По в�ем дей�тви�м, пол�м, таблице/дереву | По до�тупным дей�тви�м; до�ка �охран�ет ввод мышью | +| Enter | Открыть �троку; подтвердить inline-редактирование; запу�тить, е�ли фоку� на кнопке | Только на итоге: о�новное «Далее»/«�овый проход»/«Повторить»; во врем� хода ничего | +| Space | �ктивировать �фоку�ированную кнопку/переключатель | То же | +| Esc | Закрыть popup/отменить inline; затем вернуть�� на предыдущий �кран | К репертуару; незавершённое не за�читывает�� завершённым | +| � → Home End | �авигаци� по позици�м активного дерева | Про�мотр уже �ыгранного | +| ↑ ↓ | Строки таблицы; навигаци� нотации по �уще�твующим правилам | Как в текущем тренере | +| F | Перевернуть до�ку | Перевернуть до�ку | +| Ctrl+W | К �крану баз � �облюдением не�охранённых данных | К �крану баз через подтверждение только реальных не�охранённых данных | +| Shift+F10 / Menu | Контек�тное меню выбранной �троки/хода | �ет меню будущих ходов | +| L, Shift+A | В репертуаре движок не запу�кает�� | Прежний то�т об отключённом движке | +| Ctrl+Z/Y/S/V/G, Ctrl+1…6 | Только обычные дей�тви� �оответ�твующего �крана; в дереве репертуара редактировани� нет | �ичего | + +Отдельной клавиши под�казки нет: она до�тупна по Tab только по�ле по�влени�. Delete не удал�ет репертуар. + +### 14.2. Фоку� + +- Видимый focus ring минимум 2 точки, контра�тный в dark/light; selection и focus не �овпадают только цветом. +- При открытии выбора назначени� фоку� — на �пи�ке репертуаров; по�ле добавлени�/отмены — на и�ходном ходе. +- По�ле �оздани�/переименовани� фоку� возвращает�� �троке; по�ле удалени� — �ледующей �троке или кнопке «Создать» в пу�той библиотеке. +- Ошибка ввода не крадёт фоку� у до�ки. Ошибка запи�и переводит фоку� на «Повторить» только е�ли пользователь уже взаимодей�твовал � кнопками, а не делал ход; иначе поло�а получает до�тупное объ�вление без �мены фоку�а. +- Переход «р�дом ↔ �топка» �охран�ет фоку�, активный ход, прокрутку и выбранную вкладку. + +### 14.3. �е только цвет + +- Ошибка — `✗` и тек�т, try again — отдельный тек�т без кра�ного кре�та. +- Disabled — `⌀` и `не учить`, due/new — �вные �лова, тран�позици� — `⇄ N путей`. +- Под�казанный результат — тек�т `� под�казкой`, а не только звёздочка/жёлтый цвет. +- О�новной тек�т и важные значки — контра�т не ниже 4,5:1; крупные �лементы фоку�а/рамки — не ниже 3:1 в обеих темах. + +## 15. Что визуально переи�пользовать из �тарого тренера + +Об�зательно �охранить: + +1. Ра�положение до�ки, правой/нижней панели и поло�ы под до�кой — вход в тренировку не «прыгает» отно�ительно партии. +2. До�ку, легально�ть, под�ветку по�леднего хода, выбор превращени�, �трелку под�казки и поведение ориентации. +3. Две рамки по образцу `clock_card`, панель ин�трументов `play_toolbar`, итог `result_strip` и �троку про�мотра прошлой позиции. +4. Read-only таблицу нотации только �ыгранного, автоматиче�кую прокрутку к по�леднему ходу и �лой `×N` ошибок в итоге. +5. Кра�ный flash двух полей на 400 м�, блокировку ввода, возврат фигуры � �уще�твующей анимацией не более 150 м�, звуки `Wrong` и `Success`. +6. Клавиши навигации, `F`, `Esc`, `Ctrl+W`, Enter только в итоге и то�ты `L`/`Shift+A`. + +�е переи�пользовать без изменени� �мы�ла: + +- линейный `Ход k из N` дл� SRS и заранее неизве�тного пути `Both`; +- один `wanted(k)` дл� в�ех режимов; +- кра�ную ошибку дл� другого enabled-хода в одноцветном `try again`; +- �тарое «Прохождение N · лучшее» как будто �то per-move �тати�тика; +- �тарый line-key дл� тран�позиций или общий �чётчик дл� White/Black/Both; +- немедленный запу�к из контек�тного меню партии. + +## 16. Пр�мые требовани� к UI-реализации + +1. Со�то�ни� маршрута разделены: `RepertoireLibrary`, `RepertoireDetail`, `RepertoireTraining`. �ктивна� тренировка — ограниченна� временна� �е��и�, не редактируемый PGN-документ. +2. PGN о�таёт�� и�точником дерева. FEN4-индек�, кандидаты и очереди — производные; в JSON нельз� ��ылать�� на временный `NodeId`. +3. Общий Rust-автомат различает `target exact`, `try again`, `outside enabled`, `illegal input`, `boundary`; UI не дублирует шахматные правила. +4. В�е автоматиче�кие ответы изолированы выбором канониче�кого enabled-ребёнка. �и UI, ни движок не выбирают �лучайный или «лучший» ход. +5. Глубина, disabled, scope примен�ют�� одновременно к очереди, пользователь�ким кандидатам, ответам программы и знаменател�м �тати�тики. +6. Стати�тика имеет ключи режима и репертуара. Legacy line-run хранит�� и отображает�� отдельно; per-move данные из него не рекон�труируют��. +7. Запи�ь PGN/на�троек/�тати�тики атомарна. Перед запи�ью и�ключает�� потер� изменений другого проце��а; ошибка возвращает�� в UI. +8. При ошибке запи�и тренировка о�таёт�� на текущем результате, �ледующее задание не начинает��. Е�ть «Повторить»; выход � не�охранёнными новыми �обыти�ми и�пользует �уще�твующую защиту не�охранённых данных. Молчаливого «продолжить как будто �охранено» нет. +9. Разбор импорта, �ли�ние, FEN4-индек�ирование и большие очереди не блокируют UI. Отмена до commit не о�тавл�ет ча�тичного результата. +10. Таблица библиотеки, дерево, таблицы ходов и и�тори� виртуализируют��. �ельз� каждый кадр заново разбирать PGN или ра�кладывать в�е ветки целиком. +11. Дерево не разворачивает�� автоматиче�ки целиком по�ле импорта: ра�крывают�� о�новна� лини� и активный путь, о�тальные RAV �охран�ют �о�то�ние ра�крыти�. +12. Кнопка и новые �краны включены только на desktop � `CAPS.training`. Android API/�краны и web-поведение не мен�ют��; от�ут�твие новой кнопки там — ожидаемое поведение. +13. В�е тек�ты локализованы RU/EN/DE, включа� причины disabled, диагно�тику PGN, множе�твенные чи�ла и и�торию. +14. Цвета берут�� из �уще�твующих `selection`, `error_fg_color`, `warn_fg_color`, `noninteractive.bg_stroke`; новой декоративной палитры нет. + +## 17. Приёмка дл� developer и tester + +### 17.1. Библиотека и контек�т + +- [ ] «Тренировка дебюта» �тоит р�дом � «Подготовками» и открывает библиотеку; Android/web не получают �ломанного нового входа. +- [ ] Создание, переименование, удаление, импорт и ошибки запи�и работают inline; нет цепочки модальных окон. +- [ ] �е�колько репертуаров имеют незави�имые деревь�, глубину, disabled, очереди и �тати�тику. +- [ ] «Добавить в репертуар…» добавл�ет точный префик�, включа� путь внутри RAV, комментарии/NAG/FEN; �о�едних веток и хво�та нет. +- [ ] По�ле добавлени� тренировка не начинает��; и�ходна� парти�, её кур�ор, revision, не�охранённые комментарии и файл не мен�ют��. +- [ ] Возврат по «Открыть» из то�та и затем «К партии» во��танавливает и�ходный контек�т. Изменённый/удалённый и�точник не открывает �лучайную запи�ь. + +### 17.2. PGN и объём + +- [ ] Multi-game PGN �оздаёт один репертуар; вложенные RAV, комментарии, NAG и FEN переживают �охранение и перечитывание. +- [ ] Повторный импорт полного дубл� не �оздаёт узлов/аннотаций; новый комментарий/NAG на �уще�твующем пути не тер�ет�� и не затирает прежний. +- [ ] Добавл�ющий импорт �охран�ет �тати�тику и disabled �уще�твующих ходов; новые ходы enabled. +- [ ] Разные �тартовые FEN, нелегальный ход, legacy-кодировка, fullmove=0, �тарт чёрных, `--`, у�ечённа� запи�ь дают либо корректное дерево � диагно�тикой, либо �вный отказ без �крытого ча�тичного импорта. +- [ ] Глубина по умолчанию 20 полуходов; изменение глубины мен�ет очередь/ответы/знаменатели, но не PGN и �к�порт. +- [ ] Disabled о�таёт�� читаемым и �к�портируемым, не попадает в кандидаты и очередь; enable возвращает прежнюю �тати�тику. +- [ ] В�е disabled, пу�той репертуар, глубина ниже начала выбранной ветки и от�ут�твие ходов выбранного цвета имеют отдельные пон�тные �о�то�ни� и не запу�кают пу�тую до�ку как у�пех. + +### 17.3. Одноцветный режим + +- [ ] White и Black провер�ют только �вой target-ход; контек�тные ходы не �оздают попыток; программа отвечает только enabled-ходами дерева. +- [ ] Другой enabled-ребёнок вне цели даёт отдельный `try again` без mistakes/due/accuracy; disabled и ход вне дерева — обычна� ошибка. +- [ ] �елегальный ввод не �читает��; превращени� различают��; кажда� повторна� ошибка увеличивает �чётчик. +- [ ] По�ле третьей ошибки под�казка до�тупна по запро�у, �трелка не по�вл�ет�� �ама; hinted �бра�ывает чи�тую �ерию. +- [ ] Ли�т раньше глубины завершает задание/путь нормально; нет ответа движком или хода за пределами лимита. +- [ ] SRS �начала берёт due; unseen ввод�т�� пакетами до 10 только �вно. При due=0 е�ть раздельные «Добавить новые» и «Повторить будущие раньше». +- [ ] У�пех/ошибка/hint мен�ют �роки по §9.2; до�рочный и по�ледовательный обзоры пишут попытки, но не мен�ют due. +- [ ] «Подр�д» помнит ме�то и начинает новый цикл; «Сначала новые и давние» �начала unseen, затем ascending last_seen. + +### 17.4. Both + +- [ ] Пользователь делает каждый полуход; автоматиче�ких ответов нет. +- [ ] �а развилке каждый enabled-ребёнок принимает��; нет `try again` и заранее об�зательной ветки. +- [ ] Ход вне дерева, disabled и за глубиной возвращает�� � ошибкой; по�ле третьей можно запро�ить �трелку, но другой enabled-ход в�ё равно принимает��. +- [ ] Ли�т, depth и FEN4-цикл завершают проход ровно один раз; «Повторить путь» не делает его фик�ированной линией. +- [ ] Enabled-отклонение от предложенного маршрута запи�ывает фактиче�кий путь, а незавершённый предложенный не отмечает пройденным. +- [ ] В `Both` нет due/SRS-�тату�ов; его �тати�тика не мен�ет White/Black. + +### 17.5. Тран�позиции и �тати�тика + +- [ ] `1.d4 d5 2.Nf3` и `1.Nf3 d5 2.d4` дают одну FEN4-запи�ь внутри репертуара, одну цель в очереди и канониче�кое продолжение; оба PGN-пути видны. +- [ ] Очередь хода, права рокировки и легальное en passant различают позиции; �чётчики не �оздают дубли. +- [ ] Disabled одного пути не �крывает логиче�кую цель, до�тупную по другому enabled-пути. +- [ ] По ходу видны реальные attempts/correct/wrong/hints/last/due; в Both ошибки отно��т�� к позиции, а не выдуманному expected SAN. +- [ ] Disabled не входит в текущий знаменатель; нет «% mastered». И�тори� режимов и репертуаров раздельна. +- [ ] Старые line-run видны на отдельной вкладке � и�ходными чи�лами и без новых per-move колонок; незавершённое не �тановит�� завершением. + +### 17.6. Визуальна� и �и�темна� матрица + +Каждый пункт провер�ет�� в **RU, EN, DE**, **dark и light**, при **1400×900, 640×900 и 640×480**: + +- [ ] Библиотека: пу�то, 3 и 50+ репертуаров, длинное название, legacy-вкладка, ошибка чтени�/запи�и. +- [ ] Импорт: предпро�мотр большого multi-game PGN, предупреждени�, отмена, не�овме�тимый FEN. +- [ ] Репертуар: пу�то, большое ветви�тое дерево, в�е disabled, нет ходов цвета, в�� обла�ть глубже лимита, активна� FEN4-группа. +- [ ] Тренировка: White, Black, Both; правильный ход, try again, ошибка flash, треть� ошибка/под�казка, ли�т, depth, повторение позиции, due=0, итог, незавершённое, ошибка запи�и. +- [ ] �ичего не обрезано �лева, тек�ты не накладывают��, до�ка не меньше 220, панель не уже 240 в режиме «р�дом», в �топке о�таёт�� читаема� нотаци�. +- [ ] Клавиатура и focus ring проход�т ве�ь �ценарий без мыши, кроме �амого шахматного хода; Esc не тер�ет реальные не�охранённые данные. +- [ ] Комментарии/NAG/будущие SAN/автор�кие �трелки не ра�крывают ответ до положенного момента. +- [ ] Большой ветви�тый PGN: разбор и индек�ирование не блокируют окно, отмена не о�тавл�ет ча�тичную запи�ь, прокрутка виртуализированного дерева и таблиц не разворачивает в�е пути. +- [ ] По�ле перезапу�ка во��танавливают�� PGN, disabled, глубина, на�тройки, отдельные очереди и в�� нова�/legacy �тати�тика. И�ходные PGN-файлы побайтово не изменили�ь. + +## 18. Итог дл� реализации + +Разработчик �троит не ра�ширенный линейный «repeat game», а три �в�занных рабочих �крана вокруг �амодо�таточного PGN-дерева. Одноцветный режим провер�ет конкретную цель и имеет SRS/обзоры; `Both` провер�ет принадлежно�ть каждого фактиче�кого полухода enabled-дереву и и�пользует очередь путей. Общими �вл�ют�� до�ка, flash, под�казка по запро�у, глубина, disabled, FEN4 и �охранно�ть данных — но не модель задани� и не �тати�тика. + +Те�тировщик получает однозначные контра�тные �ценарии: `try again` против ошибки, любой enabled-ход в `Both`, due=0 без автоматиче�кого потока новых, тран�позици� без дубл�, ранний ли�т, незавершённое, отдельные legacy line-run и полна� матрица RU/EN/DE × dark/light × 1400×900/640×900/640×480. + +## 19. Уточнение компоновки по�ле живой проверки (2026-11-02) + +По замечанию владельца о неровной вёр�тке на�тройки репертуара объединены � деревом +в одной прокручиваемой панели. �а широком и коротком окне она �права от до�ки; +на узком вы�оком — �низу � до�таточной минимальной вы�отой дл� дерева. До�ка +центрирует�� в о�тавшей�� обла�ти. Глубина, режим и очередь образуют двухколоночную +�етку, о�тальные дей�тви� перено��т�� внутри �воей �троки. Библиотека и�пользует +виртуализированную таблицу � по�то�нными колонками и обрезкой длинных названий +(полное название — tooltip). Подтверждение удалени� ра�полагает�� перед таблицей. + +Панель тренировки прокручивает�� целиком; заголовок репертуара, задание и очередь +хода не конкурируют за одну �троку. Кнопки навигации имеют одинаковые размеры. +О�новна� лини� дерева видна �разу, боковые продолжени� ра�крывают�� у родитель�кого +хода. Выбор позиции через тран�позицию ра�крывает её путь. + +Индек�аци�, под�чёт заданий и подготовка �е��ии имеют �о�то�ние загрузки и работают +в фоне. Во врем� подготовки параметры блокируют��; возврат отмен�ет прин�тие её +позднего результата. Ожидающий под�чёт не дублирует�� при �мене минуты. + +## 20. Дей�твующий �ценарий: пройти варианты + +1. Импорт PGN открывает репертуар. По умолчанию выбран режим «Пройти варианты», + цвет — белые (или �охранённый пользователем). Под выбором объ��н�ет��: + ветка проходит�� целиком, любой включённый ход принимает��, �оперник отвечает + автоматиче�ки. «Повтор�ть отдельные позиции» — �вный отдельный режим. +2. «�ачать» открывает и�ходную позицию обла�ти. За чёрных программа �начала + делает ход белых. Заголовок «Продолжайте вариант», очередь хода и тек�т «Ваш ход: + �ыграйте любой ход из репертуара. Затем ответит программа» объ��н�ют дей�твие. +3. �а развилке можно выбрать любое продолжение. Программа принимает его и отвечает + из �той ветки; перено�а к незави�имой цели в обычном прохождении нет. +4. «�е помню — показать ход» до�тупно �разу. Под�казка �оответ�твует очередной + предложенной ветке, но не запрещает альтернативу. Ход вне включённых вариантов + отклон�ет�� � объ��нением и предложением во�пользовать�� под�казкой. +5. �а завершении — �чёт фактиче�ких пользователь�ких ходов/ошибок/под�казок. + О�новна� кнопка «Следующа� ветка» и Enter начинают �ледующий проход. «Повторить + путь» во�производит фактиче�ки �ыгранный маршрут автоответов. +6. В режиме отдельных позиций включённа� альтернатива также принимает��. Она не + получает ложную оценку за �крытую цель; не�деланный целевой ход о�таёт�� дл� + будущего повторени�. Старое �ообщение «�ейча� повтор�ет�� другой» не выдаёт��. + +�а�тройки очереди прежнего интерфей�а однократно мигрируют в «Пройти варианты». +Стати�тика ходов отражает фактиче�ки �ыгранные ответы; автоматиче�кие ходы не +�читают�� попытками. Практика не мен�ет �уще�твующие �роки SRS. Прохождени� и +�тати�тика веток за обе �тороны обновл�ют�� и в новом о�новном режиме. + +## 21. Дей�твующее упрощение: �лучайный круг вариантов (2026-11-03) + +Этот раздел замен�ет прежние требовани� к видимому дереву, глубине, disabled, обла�ти, due-колонкам и выбору очереди. О�тальные правила �охранно�ти PGN, до�ки, ввода, ошибок, под�казок и �тати�тики дей�твуют. + +### 21.1. Библиотека и репертуар + +Библиотека — таблица `�азвание | Варианты | ⋯` в �тиле о�новной таблицы партий: обычные тек�товые �чейки, один клик выдел�ет �троку, двойной открывает репертуар. Создание пу�того репертуара выдел�ет его �троку и о�тавл�ет пользовател� в �пи�ке, не открыва� до�ку. Кнопка на�троек находит�� в правом углу шапки. Чи�ловые заголовки и значени� выровнены по правому краю. «Варианты» — количе�тво маршрутов, до�тупных тренировке, а не чи�ло завершений: у нового репертуара � двум� маршрутами �разу показано `2`. Под�чёт выполн�ет�� в фоне; во врем� него виден индикатор, а не прочерк, похожий на ноль. + +�а �кране репертуара нет дерева ходов, ручных ограничений и кнопок импорта/�к�порта. Пор�док �лементов: название; цвет `Белые | Чёрные | Оба`; чи�ло вариантов и о�новна� кнопка «�ачать тренировку»; компактна� �тати�тика. Импорт в �уще�твующий репертуар и �к�порт до�тупны в меню `⋯` его �троки в библиотеке. Глубина, обла�ть и выбор «проход / отдельные позиции» удалены, а не �крыты под дополнительным меню. Старые ограничени� из JSON �нимают�� при загрузке, чтобы невидимо не мен�ть �одержимое тренировки. + +### 21.2. Случайный круг и начало не � первого хода + +- Дл� круга формирует�� �лучайна� пере�тановка полных маршрутов. Каждый предлагает�� один раз; по�ле по�леднего начинает�� новый круг � новой пере�тановкой. Повтор по желанию пользовател� не �читает�� �ледующим �лементом очереди. +- Два маршрута могут иметь общий префик�: �то разные варианты, а не ошибочное пере�ечение. �е повтор�ет�� именно полный маршрут. +- Круг �троит�� только из и�ходных PGN-веток, без увеличени� их чи�ла через тран�позиции. �ачало выбирает�� �лучайно �реди позиций и�ходной ветки, где е�ть продолжение дл� выбранной �тороны. До неё проигрывает�� automatic context. До конца о�таёт�� не меньше �еми полуходов; е�ли ветка короче, она начинает�� � и�ходной позиции. Пользователь не на�траивает prefix/scope и не видит �ырые UCI. +- White/Black получают первую задачу �воего цвета; программа отвечает из выбранной ветки. Both получает любую позицию � продолжением и ходит за обе �тороны. Пу�той suffix и �тарт за пределами PGN недопу�тимы. +- Очередь �троит�� в фоне и при первом запу�ке, и при Next. Дл� большого дерева и�пользуют�� по�ледовательный под�чёт и выбор маршрута, а не �пи�ок в�ех путей в пам�ти; �о�то�ние круга �ериализует�� �овме�тимо �о �тарой �тати�тикой. Fingerprint PGN входит в ключ круга: изменение �одержимого при неизменном чи�ле маршрутов также начинает новый круг. + +### 21.3. Проход и результат + +Экран прохода �охран�ет до�ку, ошибку, под�казку и чи�ло ошибок. �а текущей позиции показывают�� �уще�твующие значки NAG (`!`, `?`, `!!`, `??`, `!?`, `?!`) и автор�кие �трелки/круги из `[%cal]`/`[%csl]` � теми же цветами, что при про�мотре партии. При про�мотре более ранней позиции пометки текущего узла �крывают��, чтобы не отно�ить их к другому ходу. Под�казка отображает�� вме�те � автор�кими �трелками. �втоматиче�кий префик� не �читает�� пользователь�кими попытками. Видимого «Дерева» будущих ходов нет. Тек�това� нотаци� также полно�тью удалена: SAN, номера ходов, `×N`/`*` и отдельна� scroll area не показывают�� и не резервируют ме�то. Про�мотр уже показанных позиций выполн�ет�� на до�ке прежним toolbar и клавишами; внутренний путь дл� �того и дл� механики �охран�ет��. + +По�ле по�леднего реального полухода показывают�� результат и два равноправно до�тупных дей�тви� � разным приоритетом: + +1. О�новна� **«Следующа� ветка»** (и Enter) выбирает �ледующий непройденный маршрут круга, � новым �лучайным началом. +2. **«Повторить путь»** повтор�ет фактиче�ки �ыгранный маршрут, включа� выбранные пользователем отклонени�, автоответы и и�ходную �тартовую позицию. Кур�ор очереди не двигает��. + +«�азад к репертуару» о�таёт�� отдельным дей�твием. Ошибка �охранени� не позвол�ет молча продолжить как будто данные запи�аны. + +### 21.4. Об�зательна� приёмка �того уточнени� + +- �овый Spanish � двум� маршрутами и нулём завершений показывает `Варианты: 2`; по�ле тренировок �мы�л чи�ла не мен�ет��. +- Старые `max_plies=20`, disabled и SRS-на�тройки не ограничивают новый запу�к; PGN и и�тори� попыток �охран�ют��. +- �а fixture минимум из трёх веток ве�ь круг �одержит каждый полный маршрут один раз; �ледующий круг �нова �одержит в�е. Изменение PGN корректно начинает новый круг. +- White, Black и Both получают легальный automatic context и ход нужной �тороны; до�ка �овпадает � фактиче�кой позицией session, тек�товой нотации и её пу�того контейнера нет. Repeat �охран�ет точный путь и �тарт, Next не на�ледует �тарую �лучайную обла�ть. +- В RU/EN/DE, dark/light, 1400×900 и 640×480 нет удалённых контролов, обрезанных заголовков, наложений и недо�тижимых кнопок. Во в�ех режимах провер�ют�� правильный ход, ошибка/под�казка, итог, Repeat, Next и Back. + +## 22. Единый �кран репертуаров и тренировки (2026-11-03) + +Этот раздел замен�ет раздельные �краны библиотеки и репертуара из §21.1, а также панель кнопок навигации по позици�м. + +### 22.1. Одна рабоча� обла�ть + +- «Тренировка дебюта» на �кране баз �разу открывает рабочую обла�ть � до�кой, даже е�ли библиотека пу�та. Отдельных �кранов �пи�ка репертуаров и опи�ани� репертуара больше нет. +- �а широком окне до�ка �лева, панель �права; на узком вы�оком панель перено�ит�� под до�ку. Выбранный репертуар показан компактной карточкой: название, цвет, чи�ло вариантов, «�ачать тренировку» и �тати�тика. Верхн�� шапка и геометри� до�ки одинаковы в workspace и активной тренировке; при узком окне обла�ти вычи�л�ют�� �вными `board_rect`/`side_rect`, чтобы �одержимое не мен�ло размер и центр до�ки. +- Таблица репертуаров находит�� в той же панели под карточкой. Во врем� тренировки она о�таёт�� до�тупна под карточками задани�/результата. Кнопки `� ◀ ▶ �` удалены; внутренн�� и�тори� позиций и клавиатурный про�мотр �охран�ют��. +- Один клик по �троке выбирает репертуар и обновл�ет до�ку, не открыва� другой �кран. Запу�к выполн�ет�� отдельной о�новной кнопкой. Создание, переименование, импорт, �к�порт, удаление и пои�к до�тупны в �той же панели и во врем� тренировки. Раздела «Прежние линии» нет: владелец удалил архивную таблицу из текущего интерфей�а, �тарые файлы данных при �том не �тирают��. +- При первом входе, выборе и возврате из тренировки выбранна� �трока однократно прокручивает�� в видимую обла�ть. По�ледующа� ручна� прокрутка не �бра�ывает��. +- Смена репертуара или редактирование библиотеки завершает текущий показ тренировки и возвращает в рабочую обла�ть. При ошибке �охранени� управление блокирует��: не�охранённые �обыти� нельз� потер�ть молча. + +### 22.2. Таблица и дебютные названи� + +- Колонки: `�азвание | ECO | Варианты | ⋯`. Под названием репертуара в его �чейке показывают�� названи� дебютов/вариантов, каждое � новой �троки; �оответ�твующие ECO-коды также перечи�л�ют�� по�трочно. В�е �троки имеют одинаковую вы�оту **156 pt** � ме�том под п�ть названий: �верху 8 pt, �лот названи� 24 pt, интервал 12 pt, п�ть �лотов по 20 pt � шагом 2 pt между ними, �низу 4 pt. Лишние названи� �крывают�� за `…` в п�той �троке, полный �пи�ок до�тупен в её под�казке. �азвание репертуара — �уще�твующий strong 16 pt, названи� дебютов и ECO — обычный proportional 14 pt, без `.small()`. Вы�ота не зави�ит от чи�ла загруженных названий и от DPI. +- И�точник — в�троенный `chess-openings` (таблица Lichess), а не об�зательна� больша� база. Дл� каждого полного маршрута выбирает�� наиболее точна� названна� позици� `deepest`; повторы одинаковых пар ECO/название удал�ют��. Тран�позиции ра�познают�� по позиции. +- Чи�ло «Варианты» — полные ветки, �вно запи�анные в и�ходном PGN. Тран�позиции позвол�ют переключать�� между ветками во врем� прохождени�, но не увеличивают их количе�тво и не добавл�ют новые �лементы в �лучайный круг. +- Коды и названи� вычи�л�ют�� вме�те � деревом в фоновой индек�ации. До готовно�ти индек�а и при от�ут�твии названи� показывает�� нейтральный прочерк, интерфей� не блокирует��. +- Пу�та� библиотека показывает обычную до�ку и �лементы �оздани�/импорта, а не отдельный пу�той �кран. + +### 22.3. Выравнивание и �о�то�ни� фоновой работы + +- Везде в рабочей обла�ти и�пользует�� подпи�ь «Варианты», не «Пути». Карточка репертуара по�троена �етками: подпи�и и контролы «Цвет»/«Варианты» выровнены по колонкам; «Попытки», «Ошибки» и «Завершени�» показывают�� отдельной �еткой �тати�тики. Блок �тати�тики в�егда занимает одну вы�оту: до первой попытки показаны нули и прочерк вме�то даты, �трока завершений не по�вл�ет�� позже. Кнопка «Сбро�ить» по�ле подтверждени� очищает �тати�тику и очередь только текущего репертуара и цвета; другие режимы и legacy-линии �охран�ют��. +- Чи�ло �тоит �лева непо�ред�твенно р�дом �о �ловом «Варианты». «�ачать» и «Сбро�ить» имеют одинаковую ширину 120 логиче�ких точек и выравнивают�� по правому краю �воих �трок. Запу�к и�пользует общий акцентный `primary_wide`, «Сбро�ить» о�таёт�� второ�тепенной кнопкой. +- ECO-код �тоит точно напротив названи� �воей ветки, а не напротив названи� репертуара. Коды и названи� и�пользуют одинаковый размер 14 pt и �лоты 20 pt � шагом 2 pt; пу�той �лот названи� в колонке ECO повтор�ет от�тупы и вы�оту названи� репертуара. +- Отдельной кнопки «Репертуары» нет. Переключени� на «Прежние линии» и архивной таблицы также нет. +- Стату�ы различают дей�тви�: чтение файла — «Импорт PGN…» � отменой; по�троение индек�а — «Индек�аци� вариантов и названий ECO…»; запу�к — «Подготовка тренировки…». �епон�тное «Готовим дерево…» из интерфей�а удалено. Дл� фонового �тату�а в�егда зарезервирована одна �трока 24 pt: по�ле завершени� работы она пу�та, но кнопки и таблица не �двигают��; длинный тек�т у�ечает�� � tooltip. + +## 23. Переход к модели ТЗ ChessTempo (2026-11-04) + +Этот раздел фик�ирует по�тапный UX дл� новой модели из `docs/decisions.md`. ТЗ имеет приоритет над прежними упрощени�ми. Текущий workspace, до�ка, таблица библиотеки и визуальна� �и�тема �охран�ют��; �лучайна� Practice не �тановит�� четвёртым режимом SRS. + +### 23.1. Рабоча� обла�ть по �тапам + +- **MVP:** �тандартный SRS дл� White/Black, один о�новной ответ, незави�имые попытки, базовые `T/Unseen/Learning/Learnt/Uncertain/Due`, проценты и `NextDueAt`. Primary CTA и KPI и�пользуют один scope. Редактор дерева и назначение main-ответа по�вл�ют�� внутри рабочей обла�ти, без ма�тера модальных окон. +- **Три режима:** один компактный dropdown `Повторени� (SRS) / По пор�дку / Сначала новые и давние`. Review in Order и Least Recent и�пользуют тот же pipeline незави�имых ответов. Continue отно�ит�� к во��тановленной �е��ии, а не про�то к наличию �тарой �тати�тики. +- **Ра�ширенна� аналитика:** полна� summary-таблица, ветвевые и глобальные проекции, и�тории и графики открывают�� отдельно. Библиотечна� таблица не превращает�� в dashboard и не получает во�емь KPI-колонок. +- **Reset:** общий LearningItem �бра�ывает�� через preview N/M � именами затронутых репертуаров. `Reset Review Order` — отдельное дей�твие, не мен�ющее SRS. Де�труктивный фоку� по умолчанию не получает Enter. + +Со�то�ни� CTA: Due>0 — `Повторить �ейча� · N`; Due=0 и Unseen>0 — `Изучить новые`; Due=0 и Unseen=0 — завершить либо �вно повторить до�рочно � `NextDueAt`. �овый репертуар не получает ложное «в�ё повторено». При T=0 проценты `—`, Start недо�тупен. `ALL_LEARNT` допу�кает Due; `CONFIRMED_CURRENT` требует Due=0 и Uncertain=0. + +KPI — один �покойный блок в выбранной карточке, � полной подпи�ью обла�ти и времени ра�чёта. `Uncertain` �вно подмноже�тво Learnt, Due — пере�ечение � Learning+Learnt. И�тори� �тарых Attempts/Completions не �мешивает�� � �о�то�нием знани�. + +### 23.2. Тренировка и контек�т + +- До�ка о�таёт�� центральной; библиотека под активным заданием не показывает��. Тек�това� нотаци� не возвращает��. �азвание, scope, прогре�� �е��ии и фик�ированна� панель �о�то�ни� о�тают�� на ме�те. +- �еверный легальный ход запи�ывает�� один раз. По�ле возврата позиции ожидаемый ход показывает�� �трелкой; повтор продолжает линию как `REPLAY_AFTER_ERROR` и не называет�� �амо�то�тельным у�пехом. Повторные ошибки в �той фазе не �оздают новых незави�имых попыток. +- `PREVIEWED` виден до во�произведени�: �ери� и Accuracy не ра�тут, требует�� поздн�� проверка без под�казки. �втоматиче�кий context запи�ывает только �лужебное �обытие `AUTO_CONTEXT`, не �оздаёт незави�имых попыток и не мен�ет SRS. Е�ли контек�тный ход �ам провер�ет�� как reinforcement, он имеет �вное �о�то�ние и запи�ывает�� один раз. +- �втоматиче�кие ходы показывают�� по�ледовательно `position_before → position_after`. Кажда� нова� автоматиче�ка� �ери� начинает�� �о �татичного prime-кадра из `from` первого шага: он не анимирует предыдущую позицию и не �оздаёт обратный slide; только �ледующий кадр запу�кает scheduler. При фик�ированной �коро�ти каждый шаг занимает `settings.animation.seconds()`: Off=0, Fast=0,12, Normal=0,25, Slow=0,5 �. При адаптивной �коро�ти фактиче�кий slide и scheduler и�пользуют одну длительно�ть `base / speed_factor` текущего шага, включа� по�ледний; переход before→after начинает�� в начале �того интервала. Два–три ответа/контек�тных хода не телепортируют�� за один кадр. Во врем� autoplay ввод заблокирован, Pause/Stop до�тупны; Off разрешает мгновенный переход. +- До готовно�ти board ввод невозможен. Результат по�вл�ет�� по�ле завершени� по�леднего визуального шага, а не только по�ле изменени� session. Сохранение ошибок блокирует переход как раньше. + +### 23.3. Компоновка и приёмка + +- Wide: до�ка �лева, �права название/scope, �торона/режим, CTA, единый KPI, библиотека. Узкое окно не пр�чет primary action и не �оздаёт горизонтальную прокрутку. +- Вы�оты карточек и �трок не зави��т от по�влени� индек�а, �тати�тики, ошибки или длины �ообщени�. Переходы Wrong→Reveal→Replay→Opponent→Next не двигают до�ку. +- Об�зательные �нимки 1400×900 (о�новной размер) и 960×600 (минимальный дл� визуальной приёмки): empty/new/mixed KPI, Due=0, в�е Learnt, три режима, wrong/replay, preview, autoplay 1/3→3/3, Pause/Continue, shared reset, save error, Continue/New session. Дополнительно �ери� кадров доказывает длительно�ть анимации, один �татиче�кий �нимок её не доказывает. Размер 640×480 о�таёт�� только в и�ториче�ких техниче�ких те�тах и не определ�ет дизайн. +- �езави�имый design reviewer �равнивает main/game и рабочую обла�ть, а орке�тратор провер�ет core AT-01…30 отдельно от визуальной приёмки. + +### 23.4. Details, �равнение веток и на�тройки контек�та + +- `Details` находит�� в �троке `Statistics` �лева от `Reset`, обе кнопки вторичные вы�отой 26 pt. Открывает�� отдельна� рабоча� обла�ть вме�то до�ки и боковой панели, не popover и не нова� карточка в библиотеке. �ачальные Scope/Side на�ледуют текущий выбор; Global до�тупен только �вным переключением. Close/Escape возвращает к той же �троке и фактиче�кой прокрутке без принудительного центрировани�. +- `Context and move speed` — один default-collapsed р�д по�ле о�новных на�троек и `Reset Review Order`, но до `Statistics`. Перед ним 8 pt, по�ле 6 pt; expanded body и�пользует �покойную двухколоночную �етку 12×6 pt � перено�ами длинных подпи�ей. В узкой панели выбранный блок ограничен примерно половиной вы�оты и получает �об�твенную вертикальную прокрутку: CTA о�таёт�� в начале, toolbar/header и �трока библиотеки не и�чезают. Вложенных карточек и горизонтальной прокрутки нет. +- В compact KPI не и�пользует�� непон�тное `T`: показывает�� `Total moves`/`Total`. Слаба� �трока `Learnt = Confident + Uncertain · percentages use Total` объ��н�ет �о�тав и знаменатель. �оль попыток и пу�той scope дают `—`, а не 0% или 100%. +- Dashboard разделён на Summary, Branches, History, Scheduled, Sequences и Moves. Summary �одержит точную таблицу репертуаров и дедуплицированный Global total; Branches — T/Unseen/Learning/Learnt/Uncertain/Due/Accuracy/Learnt %/Last trained. �а узком �кране Branches показывает о�новные колонки и в�е детали выбранной ветки ниже, без уменьшени� шрифта и горизонтальной прокрутки. +- History �одержит линии Learning/Learnt/Uncertain по фактиче�ким ежедневным �нимкам; Uncertain — незави�има� лини�-подмноже�тво, не stack. Scheduled — ше�ть непере�екающих�� корзин; Sequences — три ги�тограммы, включа� ноль. Точные таблицы о�тают�� под графиками. Один snapshot — видима� точка; от�ут�твующие данные не �интезируют��. +- Дей�твие называет�� `Save statistics to History`, а не «�нимок» без контек�та. Первый про�мотр scope в локальный день �охран�ет �нимок автоматиче�ки, повторное ручное �охранение того же date/scope идемпотентно. PGN и LearningItem не мен�ют��. Фоновое обновление по�ле запи�и не замен�ет уже видимую таблицу коротким loading-body. +- Тренировочный KPI и CTA учитывают `max_plies`; полна� History о�таёт�� полной по на�тройке scope. Сравнение веток и линий и�пользует в�е PGN-пути: общий LearningItem при�ут�твует в каждой подход�щей линии, дедуплицирует�� внутри ветки и не �уммирует�� повторно в Global. +- �езави�имый reviewer провер�ет collapsed/expanded, первый вход→loading→loaded→Details→Close, 1400×900 и 960×600, RU/EN/DE и dark/light. Отдельно фик�ирует читаемо�ть в�ех заголовков, от�ут�твие �качков по�ле Save statistics to History и до�тупно�ть выбранной �троки библиотеки. Микро-окна не и�пользуют�� дл� визуального вердикта. diff --git a/docs/design/rodent-opponent.md b/docs/design/rodent-opponent.md new file mode 100644 index 0000000..b4db2b9 --- /dev/null +++ b/docs/design/rodent-opponent.md @@ -0,0 +1,170 @@ +# Rodent V в диалоге «Играть � компьютером» (компьютер) + +Стату�: проект дизайнера, 2026-10-26. О�нование: `docs/decisions.md` («Соперник � характером: Rodent V», «Предложение ничьей»), `docs/research/rodent.md`, текущий `Dialog::show` в `apps/desktop/src/play.rs`, правила `docs/design/play-mode.md` и `docs/design/maia-models.md` (диалог не прыгает, р�ды фик�ированной вы�оты, плитки дел�т ширину р�да). Только компьютер; на телефоне о�таёт�� Maia. + +Чи�ла �илы Rodent ниже — **заглушки дл� компоновки** (`RODENT_MIN = 1100`, `RODENT_MAX = 2700`); разработчик под�тавл�ет измеренные. Граница Maia — `MAIA_MAX = 2100` (больша� модель), как �ейча� `STRENGTH_MAX`. + +## 1. Путь пользовател� + +1. Открывает «Играть � компьютером». Впервые выбрана Maia 1500 (как �ейча�); дальше — по�ледний выбор: �оперник, �ила, �тиль Rodent. +2. Хочет �ильнее: т�нет ползунок вправо. Перейд� 2100, �разу (во врем� перета�кивани�) �оперником �тановит�� Rodent V, р�д «Стиль» оживает, �трока под ползунком объ��н�ет почему. +3. Хочет «Тал�» на 1600: щёлкает плитку «Rodent V» (�ила о�таёт�� 1600), в «Стиль» выбирает «Таль». +4. Rodent не �качан: внизу �трока «�качивает�� один раз, 48 МБ», кнопка «Скачать и играть»; по�ле загрузки парти� начинает�� �ама (как у Maia). +5. Играет: в поло�е игрока «Rodent V 2400 · Таль»; ничь�, �дача, реванш — как � Maia. + +## 2. Компоновка тела диалога + +Пор�док блоков прежний: «Вы» → «Соперник» → «Ваш цвет» → «Врем�». Вводна� фраза про Maia (`body_h >= 420`) **убирает��**: её �мы�л переходит в подпи�и плиток �оперника. Это возвращает вы�оту, которую берёт новый р�д «Стиль». + +``` +Соперник — Rodent V 2400 (заголовок �екции, как �ейча�) +┌──────────────────────────�┌──────────────────────────� +│ Maia ││ Rodent V │ две плитки 227 × 48 +│ играет как человек ││ �ильный движок � характером│ +└──────────────────────────┘└──────────────────────────┘ +Сила: 1100 [��������������������������������] 2700 + ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ поло�а «зона Maia» 1100–2100 + Сильнее 2100 играет Rodent V: Maia так �ильно не играет. (1 �трока) +Стиль: [ Таль — гибрид ▾] ComboBox, вы�ота 32 + �такующий �тиль, на�троенный по парти�м Тал�. (1 �трока) +``` + +- Заголовок �екции: `Соперник — Maia {elo}` / `Соперник — Rodent V {elo}`. Стиль в заголовок не идёт (длинно); он виден в �воём р�ду. +- «Сила:» и «Стиль:» — �етка из двух колонок, как «Им�:/Рейтинг:» в «Вы» (подпи�и выровнены по левому краю одной колонки). +- **Р�д «Стиль» е�ть в�егда**, вы�ота по�то�нна� (комбо 32 + одна �трока опи�ани�). Диалог не прыгает ни при переключении �оперника, ни при автопереходе. +- Дл� Maia комбо **выключено** и показывает «Как человек»; опи�ание: «Maia не выбирает �тиль: она играет, как люди её рейтинга.» Выключенный р�д че�тно говорит, что �тиль — �вой�тво Rodent, и под�казывает, где его и�кать. Под�казка при наведении: «Стиль выбирает�� у Rodent V». +- В�е �троки-по��нени� — одна �трока на ширине 460 при 11,5 pt (тек�ты ниже подобраны короткими; переводчикам — то же ограничение, при переполнении обрезка � «…» и полный тек�т во в�плывающей под�казке). + +## 3. Выбор �оперника + +Две плитки `Button::selectable`, рамка в�егда (как цвет и врем�), 227 × 48, две �троки: им� 14 pt полужирное, подпи�ь 11,5 pt приглушённа�. + +| Плитка | Подпи�ь RU | Подпи�ь EN | +|---|---|---| +| Maia | играет как человек, � типичными ошибками | plays like a human, typical mistakes included | +| Rodent V | �ильный движок � характером: �ила и �тиль | a strong engine with character: strength and style | + +Щелчок по плитке: +- **Maia при �иле > 2100** → �ила �тановит�� 2100 (её предел); �трока под ползунком: «Maia играет до 2100 — �ила �нижена до 2100.» Выбор пользовател� �вный, по�тому мен�ть �илу можно, но молча — нельз�. +- **Rodent при �иле < `RODENT_MIN`** (е�ли замер покажет нижнюю границу выше 1100) → �ила поднимает�� до `RODENT_MIN`, �трока: «Rodent V играет от {min} — �ила подн�та до {min}.» +- Иначе �ила не мен�ет��. + +Клавиатура: плитки в пор�дке Tab; Enter/Space выбирает; Enter вне комбо — «Играть» (как �ейча�). + +## 4. Ползунок �илы — один на обоих + +- **Диапазон в�егда один**: `min(Maia_min, RODENT_MIN) … RODENT_MAX`, шаг 50. Шкала не мен�ет�� от �мены �оперника: точка ползунка в�егда значит одно и то же чи�ло. Концы подпи�аны (как �ейча�, 34 px). +- **Поло�а «зона Maia»**: 3 px под дорожкой ползунка от 1100 до 2100 (ри�ует�� painter'ом по пр�моугольнику ответа �лайдера, вы�ота зарезервирована в�егда). Цвет: акцент � прозрачно�тью ~35 %, когда выбрана Maia; цвет обводки неактивных виджетов, когда Rodent. Без подпи�и на ней — объ��н�ет �трока под ползунком. +- **�втопереход вверх** (об�зательное требование владельца): Maia выбрана и значение �тало > 2100 (мышь, �трелки, Home/End) → `opponent = Rodent` �разу, �тиль — по�ледний выбранный у Rodent (впервые «Сбалан�ированный»). Ставит�� флаг `auto_switched` (только на врем� диалога). +- **Обратно ниже 2100 — о�таёт�� Rodent**, без молчаливого возврата. Строка: «Зде�ь может играть и Maia — выберите её, е�ли хотите человечных ошибок.» +- **�втопереход вниз** (�имметрично, только е�ли `RODENT_MIN > 1100`): Rodent выбран, значение < `RODENT_MIN` → Maia, �трока «Слабее {min} играет Maia.» +- Е�ли у Rodent верхн�� точка — «без ограничени�» (полна� �ила), подпи�ь конца — измеренное чи�ло, а не «∞»: шкала везде че�тна�. + +**Строка под ползунком** — одна, фик�ированной вы�оты; �одержание по приоритету: + +1. по�леднее �обытие диалога (автопереход, �нижение/подъём �илы при выборе плитки) — держит�� до �ледующего изменени� �оперника или �илы через плитку; +2. Rodent выбран, �ила ≤ 2100 и был автопереход → «Зде�ь может играть и Maia…»; +3. иначе обычна�: Maia — «Её измеренна� �ила, по шкале блица Lichess. Сильнее 2100 — Rodent V.»; Rodent — «Измеренна� �ила, по шкале блица Lichess.» + +## 5. Выбор �тил� + +Элемент — **выпадающий �пи�ок** (`egui::ComboBox`, ширина р�да), а не плитки: �емь пунктов плитками — два р�да непон�тных имён и +80 px; �пи�ок ра�тёт без перекомпоновки (и��ледование предлагает добавл�ть лично�ти). В закрытом виде: «{�тиль} — {им� лично�ти}» приглушённым хво�том, например «�такующий — Ampere». В �пи�ке два раздела � некликабельными заголовками (11,5 pt, приглушённо) и разделителем; каждый пункт — две �троки: название и опи�ание. + +**Стиль** (по умолчанию «Сбалан�ированный»): + +| Файл | �азвание RU / EN | Опи�ание RU | Опи�ание EN | +|---|---|---|---| +| rodent | Сбалан�ированный / Balanced | Ровна� универ�альна� игра, без переко�ов. | Even, all-round play with no bias. | +| ampere | �такующий / Attacking | �ктивные фигуры и атака, крепка� пешечна� �труктура. | Active pieces and attack, sound pawn structure. | +| chaotic | Хаотичный / Chaotic | �гре��и� и хитрые дебюты, пешки не бережёт. | Aggressive, tricky openings, careless with pawns. | +| nimzoid | Сковывающий / Restricting | Закрытые позиции, �те�нение �оперника, �тарые дебюты. | Closed positions, cramping the opponent, old openings. | +| hector | Кла��иче�кий / Classical | Оценка, напи�анна� вручную, без нейро�ети. | Hand-written evaluation, no neural network. | + +**Как игрок:** + +| Файл | �азвание RU / EN | Опи�ание RU | Опи�ание EN | +|---|---|---|---| +| tal_hybrid | Таль / Tal | �такующий �тиль, на�троенный по парти�м Тал�. | Attacking style tuned on Tal's games. | +| tal_nnue | Таль (�еть) / Tal (network) | �ейро�еть, обученна� на парти�х Тал�. | A neural network trained on Tal's games. | + +- Опи�ание выбранного пункта — �трока под комбо (одна �трока). Имена лично�тей (Ampere, Hector…) не перевод�т��. +- Стиль не мен�ет шкалу �илы (�ила — UCI_Elo, �тиль — `PersonalityFile`, они разведены). См. открытый вопро� 1. +- Клавиатура: Tab до комбо, Space/Enter открывает, �трелки, Enter выбирает, Esc закрывает �пи�ок (не диалог). + +## 6. Загрузка Rodent + +Та же �трока �о�то�ни� над кнопками, что у Maia, и та же кнопка «Скачать и играть». + +- **Резерв �троки**: �трока е�ть, пока не у�тановлен хоть один из нужных файлов (Rodent или больша� Maia) — тогда переключение �оперника её не добавл�ет и не убирает. Е�ли активный �оперник готов, а не хватает другого — �трока пу�та� той же вы�оты. +- Содержание отно�ит�� **только к выбранному �опернику**: + - Rodent нет: «Rodent V �качивает�� один раз (48 МБ, � github.com, файл авторов).» + - идёт загрузка: поло�а � процентами; затем «Проверка…», затем «Ра�паковка…» (�пиннер); + - ошибка загрузки: кра�ным «�е удало�ь �качать Rodent V: {error}»; кнопка о�таёт�� «Скачать и играть» (повтор); + - ошибка ра�паковки/запи�и: кра�ным «�е удало�ь ра�паковать Rodent V: {error}». +- Во врем� загрузки «Играть» выключена (как �ейча�); плитки и ползунок до�тупны. Парти� �тартует �ама по окончании, **только е�ли** выбран в�ё ещё Rodent; иначе `play_after` �бра�ывает��, кнопка про�то показывает �о�то�ние нового выбора. Закрытие диалога отмен�ет загрузку (как у Maia). +- **macOS** (�борки авторов нет): плитка Rodent выключена, подпи�ь «пока нет дл� macOS»; под�казка: «У авторов Rodent V ещё нет �борки дл� macOS. Когда по�вит��, он будет зде�ь.» Диапазон ползунка — только Maia (1100–2100), поло�ы зоны нет, автоперехода нет; �трока под ползунком — обычна� Maia без хво�та «Сильнее 2100 — Rodent V». Р�д «Стиль» о�таёт�� выключенным, как дл� Maia. +- Rodent не запу�тил�� при �тарте партии: как � Maia (`Dialog::for_start` � тем же выбором), кра�ным в �троке �о�то�ни� «Rodent V не запу�тил��: {e}». + +## 7. В партии + +- Поло�а игрока (�ейча� `{king} Maia {strength}`): `{king} Rodent V {strength} · {�тиль}`; дл� «Сбалан�ированного» �тиль не пишет��: `Rodent V 2400`. +- PGN (имена не перевод�т��, �то обменный формат): `White/Black "Rodent V 2400 (Tal)"`; дл� `rodent` без �кобок; в �кобках — им� лично�ти: Ampere, Chaotic, Nimzoid, Hector, Tal, Tal NNUE. `WhiteElo/BlackElo` = измеренна� �ила, `…Type "program"` — как у Maia. +- �ичь� и �дача — тот же �крытый Stockfish и `accepts_draw`; кнопки и правила те же. +- Реванш и «Играть от�юда» открывают диалог � тем же �оперником, �илой и �тилем. +- Темп ответа: Rodent на лимите узлов отвечает мгновенно — темп как у Maia (е�ли у Maia е�ть минимальна� пауза, та же пауза). +- **Тек�ты � «Maia» внутри** не обобщать через `{name}`: в ру��ком и других �зыках род �огла�ует�� («Maia �дала�ь» / «Rodent V �дал��»). Дл� Rodent — отдельные �троки (�пи�ок ниже). + +## 8. Тек�ты дл� i18n (EN-ключ → RU) + +Диалог: +- `Opponent` → «Соперник» (е�ли заголовок без имени понадобит��), `Opponent — Rodent V {elo}` → «Соперник — Rodent V {elo}» +- `plays like a human, typical mistakes included` → «играет как человек, � типичными ошибками» +- `a strong engine with character: strength and style` → «�ильный движок � характером: �ила и �тиль» +- `Strength:` → «Сила:»; `Style:` → «Стиль:» +- `Like a human` → «Как человек» +- `Maia does not pick a style: she plays like people of her rating.` → «Maia не выбирает �тиль: она играет, как люди её рейтинга.» +- `The style is chosen for Rodent V` → «Стиль выбирает�� у Rodent V» +- `Style` → «Стиль»; `As a player` → «Как игрок» (заголовки разделов �пи�ка) +- 7 названий и 7 опи�аний — таблицы §5 +- `Her measured strength, on the Lichess blitz scale. Stronger than {elo}: Rodent V.` → «Её измеренна� �ила, по шкале блица Lichess. Сильнее {elo} — Rodent V.» (замен�ет нынешнюю �троку; на macOS — �тара� без хво�та) +- `Measured strength, on the Lichess blitz scale.` → «Измеренна� �ила, по шкале блица Lichess.» +- `Stronger than {elo} plays Rodent V: Maia does not play that strong.` → «Сильнее {elo} играет Rodent V: Maia так �ильно не играет.» +- `Maia can play here too — choose her if you want human mistakes.` → «Зде�ь может играть и Maia — выберите её, е�ли хотите человечных ошибок.» +- `Maia plays up to {elo}: the strength is lowered to {elo}.` → «Maia играет до {elo} — �ила �нижена до {elo}.» +- `Rodent V plays from {elo}: the strength is raised to {elo}.` → «Rodent V играет от {elo} — �ила подн�та до {elo}.» +- `Weaker than {elo} plays Maia.` → «Слабее {elo} играет Maia.» +- `Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).` → «Rodent V �качивает�� один раз ({mb} МБ, � github.com, файл авторов).» +- `Unpacking…` → «Ра�паковка…» +- `Could not download Rodent V: {error}` → «�е удало�ь �качать Rodent V: {error}» +- `Could not unpack Rodent V: {error}` → «�е удало�ь ра�паковать Rodent V: {error}» +- `not yet for macOS` → «пока нет дл� macOS» +- `The authors of Rodent V have no macOS build yet. When there is one, it will be here.` → «У авторов Rodent V ещё нет �борки дл� macOS. Когда по�вит��, он будет зде�ь.» + +Парти� (пары к �трокам Maia): +- `Rodent V did not start: {e}` → «Rodent V не запу�тил��: {e}» +- `Rodent V resigned` → «Rodent V �дал��»; `Rodent V resigns` → «Rodent V �даёт��» +- `Rodent V's time is up, but you cannot checkmate` → «У Rodent V кончило�ь врем�, но вам нечем по�тавить мат» +- `Rodent V plays on and will not offer again in this game` → «Rodent V играет дальше и в �той партии больше не предложит» +- `From here on, a game against Rodent V {elo}.` и три варианта «Continued…» — как у Maia +- ответы на предложение ничьей, е�ли в них е�ть «Maia», — пары дл� Rodent V + +## 9. Снимки дл� проверки (харне�� �криншотов) + +1. Maia 1500, в�ё �качано: зона Maia под�вечена, «Стиль» выключен. +2. Maia 2050 → перет�нуто на 2200: Rodent выбран, �трока автоперехода, «Стиль» включён. +3. По�ле (2) обратно на 1800: Rodent о�таёт��, �трока «Зде�ь может играть и Maia…». +4. Rodent 1600, «Таль», открытый �пи�ок (оба раздела). +5. Rodent не �качан: �трока 48 МБ, «Скачать и играть»; затем загрузка 40 %; «Ра�паковка…»; ошибка. +6. Rodent 2500 → щелчок Maia: �ила 2100, �трока «�нижена до 2100». +7. macOS-�о�то�ние (принудительно флагом): плитка Rodent выключена, ползунок 1100–2100. +8. Диалог «Играть от�юда» � Rodent и низкое окно (прокрутка тела, кнопки видны). +9. Поло�а игрока «Rodent V 2400 · Таль» и поло�а дл� «Сбалан�ированного» без �тил�. +10. �аложение �нимков 1–3 и 5: вы�ота диалога и положение кнопок �овпадают до пик�ел�. +11. Самый длинный �зык (de/ru): �троки под ползунком и под комбо в одну �троку или � «…». + +## 10. Открытые вопро�ы + +1. **Сила по �тил�м.** Шкала мерит��, веро�тно, на «Сбалан�ированном». Hector без �ети заметно �лабее на том же UCI_Elo; е�ли замер покажет разницу > ~100, нужно либо мерить каждую лично�ть (�вой `RODENT_MAX` у �тил�, ползунок ограничивает�� �о �трокой «Кла��иче�кий играет до {elo}»), либо пр�тать �лабые �тили выше их предела. До замера — одна шкала. +2. Какой из двух Талей �тавить первым и как подпи�ать — по впечатлению владельца от партий. +3. �ижн�� граница Rodent: е�ли замер да�т ≥ 1100, автопереход вниз не нужен (§4). +4. �а�тройки: `settings.play.opponent` (`Maia | Rodent`), `settings.play.rodent_style`; �ила обща�. Кнопка «Сбро�ить» не нужна. diff --git a/docs/design/task-26-review-button-2026-11-27.md b/docs/design/task-26-review-button-2026-11-27.md new file mode 100644 index 0000000..e0cc7a8 --- /dev/null +++ b/docs/design/task-26-review-button-2026-11-27.md @@ -0,0 +1,88 @@ +# Задача 26. Кнопка «�нализ партии» цветом бле�т�щего хода (!!) + +Дизайнер, 2026-11-27, ветка `feature/starter-repertoires`. Код не мен�л��. + +**Задача �крана.** �овичок должен заметить в панели под нотацией кнопку, котора� запу�кает разбор партии. По�ле разбора кнопка не должна �порить � активной позицией в нотации. + +## 0. Что �ейча� (реальные �нимки) + +Снимал через `scripts/dev/headless-run.sh`, 1920×1080, scale 1. Профиль изолирован: `/tmp/opencode/d26/{cfg,data,cache}`, Stockfish 19 подключён ��ылкой. Парти� — копи� `Alekhin.pgn`, № 1 (84 полухода) и № 2, `CP_PLY=20`. Сборка — `target/debug` текущего HEAD. Её копию из `target/design-26` � удалил. Полные �нимки лежат в `/tmp/opencode/d26/s/`, вырезки — в `docs/design/task-26/`. + +| Снимок | Со�то�ние | Что видно | +|---|---|---| +| `idle-d1.png`, `idle-d0.png` → `task-26/now-idle-d1-crop.png` | разбора нет | По�ледн�� кнопка панели, иконка `📈`. Обычна� заливка: тёмна� `#3c3c3c`, �ветла� `#e6e6e6`. Пр�моугольник 27×23 px, x 1818–1844, y 1046–1068. Кнопку легко не заметить | +| `run-d1.png`, `run-d0.png` → `task-26/now-running-d1-crop.png` | идёт разбор 29/84 | Кнопку замен�ют ProgressBar (70 px, �иний `#005c80`) и ×. **Дефект: они не помещают�� и уход�т на вторую �троку.** Панель выра�тает примерно на 24 px, нотаци� укорачивает��. Когда разбор кончает��, панель возвращает�� в одну �троку: два �качка без дей�тви� пользовател� | +| `task-26/graph-overlap.png` | идёт разбор | **Дефект:** �чётчик «29/84» в правом верхнем углу графика налезает на подпи�ь «Эндшпиль» (видно «Эндшпиль29/84») | +| `done-d1.png`, `cached-d*.png` | разбор готов, отчёт открыт | Кнопка �тала переключателем `toggle_value`, заливка выбранного: тёмна� `#005c80`, �ветла� `#90d1ff` | +| `hidden-d1.png`, `hidden-d0.png` | разбор готов, отчёт �крыт (Shift+A) | Переключатель ри�ует�� **без рамки и без заливки**, хот� �о�едние кнопки залиты. Это лишнее отличие от о�тальных кнопок | +| �водка `task-26/now-states-strip.png` | в�е �о�то�ни� подр�д | — | + +Где задано в коде: +- кнопка — `GameView::review_button` (`apps/desktop/src/game_view.rs:1048`); +- ме�то в панели — `next_group(ui, &["📈"], …)` (`game_view.rs:2296–2302`), резерв `70 + 22 + 10` во врем� разбора; +- �о�то�ние «неактивна» — `engine_busy`. Сейча� его �тавит только пои�к ошибок в дебютах (`app.rs:4081`), задача 27 добавит проход по парти�м; +- цвет !! — `notation::assessment_color(Nag(3))` = `#26c2a3` и `assessment_text_color(Nag(3), dark=false)` = `#1a846f` (`notation.rs:791–818`). Тот же цвет у �троки «Бле�т�щий» в отчёте, у кружка на до�ке и у префик�а «!!» из задачи 27 (§4.1 там). Решени� �огла�ованы: «!! = разбор» везде один бирюзовый. + +## 1. Решени� + +1. **Пока парти� не разобрана, кнопка залита бирюзовым, иконка `📈` тёмна� (�ветла� тема — бела�).** Это един�твенна� цветна� кнопка в панели. Площадь у неё маленька� (27×23), по�тому она привлекает внимание, но не �порит � главным акцентом — �иним выделением текущего хода и активной вкладкой. Цвет другой (бирюзовый, а не �иний), так что «выбрано» и «пригла�ить» не путают��. +2. **По�ле разбора бирюзова� заливка не нужна:** приглашение выполнено. О�таёт�� обычный переключатель: + - отчёт открыт — �тандартна� заливка выбранного (�ин��, как у вкладки «Отчёт»); + - отчёт �крыт — обычна� кнопка (`#3c3c3c` / `#e6e6e6`), а бирюзовой �тановит�� только иконка. Так видно, что отчёт е�ть, и и�чезает нынешн�� кнопка без рамки. +3. **Во врем� разбора прогре�� ри�ует�� внутри той же кнопки 27×23.** Отдельной поло�ы и × больше нет, ширина и вы�ота панели не мен�ют��. Бирюзова� заливка ра�тёт �лева направо по дорожке обычного цвета. Щелчок по кнопке о�танавливает разбор; Shift+A и Esc в фоку�е тоже о�танавливают, как прежний ×. Чи�ло «N/M» о�таёт�� в графике (он открывает�� вме�те � разбором) и в под�казке. Это заодно убирает перено� панели на вторую �троку. +4. **�еактивна� кнопка выгл�дит как штатна� неактивна� egui**, без бирюзового: недо�тупное дей�твие не должно звать к �ебе. Под�казка о�таёт�� прежней. Дл� задачи 27 нужна �во�: «Идёт пои�к замечательных ходов — дождите�ь или о�тановите его». + +Почему не �плошна� бирюзова� кнопка во в�ех �о�то�ни�х: по�ле разбора она �тала бы �амым �рким п�тном на �кране и забирала бы внимание у до�ки и нотации. Кроме того, «отчёт открыт» и «отчёт �крыт» тогда отличали�ь бы только оттенком. + +## 2. Со�то�ни� и точные значени� + +Макет: `docs/design/task-26/states-mock.png` — набро�ок по реальной вырезке панели; �круглени� упрощены. + +| Со�то�ние | Тёмна�: заливка / иконка | Светла�: заливка / иконка | Рамка | +|---|---|---|---| +| обычна� (не разобрана) | `#26c2a3` / `#1b1b1b` (7,65:1) | `#1a846f` / `#ffffff` (4,59:1) | нет | +| наведение | `#3fd3b4` / `#1b1b1b` (9,18:1) | `#157461` / `#ffffff` (5,67:1) | `widgets.hovered.bg_stroke` | +| нажата | `#1fa88d` / `#1b1b1b` (5,78:1) | `#10614f` / `#ffffff` (> 7:1) | `widgets.active.bg_stroke` | +| фоку� клавиатуры | как «обычна�» | как «обычна�» | `visuals.selection.stroke` (как у других кнопок) | +| идёт разбор, p % | �лева p·ширины `#26c2a3`, �права `#3c3c3c`; иконка на бирюзовом `#1b1b1b`, на дорожке — обычный цвет тек�та кнопки | �лева `#1a846f`, �права `#e6e6e6`; иконка бела� / обычный цвет | как у обычной | +| разобрана, отчёт �крыт | `#3c3c3c` / `#26c2a3` (4,9:1) | `#e6e6e6` / `#1a846f` (3,68:1, иконке до�таточно 3:1) | как у обычной кнопки | +| разобрана, отчёт открыт | `selection.bg_fill` `#005c80` / как �ейча� | `#90d1ff` / как �ейча� | как �ейча� | +| неактивна (`engine_busy`) | штатна� `add_enabled(false)` от обычной кнопки | то же | — | + +Контра�т заливки � фоном панели (`#1b1b1b` / `#f8f8f8`) — 7,65:1 и 4,32:1, то е�ть больше 3:1 дл� �лемента интерфей�а. Светлый оттенок `#26c2a3` � белой иконкой даёт 2,25:1, по�тому в �ветлой теме его брать **нельз�**. + +Без опоры на цвет: в каждом �о�то�нии кнопку выдаёт что-то кроме цвета. �е разобрана — под�казка «�нализ партии…». Идёт разбор — поло�а заполн�ет��. Отчёт открыт — нажата� кнопка-переключатель и открытый график. + +## 3. Требовани� к реализации + +- Размер об�зательно тот же, что у `ui.button(RichText::new("📈").size(18.0))`. Брать его тем же ра�чётом, что и у �о�едних кнопок: galley иконки плю� `button_padding` и `interact_size.y`, никаких кон�тант. Ширина и вы�ота одинаковы во в�ех �о�то�ни�х. `next_group` резервирует ширину одной кнопки: убрать ветку `70 + 22 + 2*5`. +- `egui::Button::fill()` в egui 0.36.2 отмен�ет �ффект наведени� (`widgets/button.rs:140`). По�тому кнопку ри�овать �амим: `allocate_exact_size(size, Sense::click())`, затем по `response.hovered()`, `is_pointer_button_down_on()` и `has_focus()` выбрать заливку из таблицы. Скругление и рамку брать из `ui.style().interact(&response)`, чтобы кнопка �овпадала � �о�ед�ми. Прогре�� — две заливки и иконка, нари�ованна� дважды через `painter.with_clip_rect`. +- Цвета не дублировать: заливку брать из `notation::assessment_text_color(Nag(3), dark)`. Три новых оттенка (наведение и нажатие дл� двух тем) — заве�ти р�дом � ней одной функцией, например `brilliant_button_fill(dark, state)`. +- Под�казки: при разборе — «�нализ партии: N из M. Щелчок или Shift+A — о�тановить». О�тальные — как �ейча�. �овые �троки вне�ти в `i18n.rs` на в�е �зыки. +- Shift+A ведёт �еб� как щелчок в любом �о�то�нии, включа� о�тановку разбора. Tab доходит до кнопки по пор�дку панели. +- Счётчик «N/M» в графике �двинуть так, чтобы он не налезал на подпи�ь «Эндшпиль» (отдельный мелкий дефект, `graph-overlap.png`). +- Задача 27: на врем� прохода вы�тавл�ть `engine_busy`; кнопка �тановит�� неактивной, нужна �во� под�казка. +- Android: аналог е�ть — пункт `review_menu` / `review_report_menu` в меню ⋮ �крана партии (`androidApp/.../ui/GameScreen.kt:1180`). Сейча� его **не делаем**. + +## 4. Критерии приёмки (ревьюер — не автор кода) + +Окна только через `scripts/dev/headless-run.sh`, профиль изолирован (`XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`), партии из копии `Alekhin.pgn`. �а каждом �нимке указывать файл, размер и �о�то�ние. + +1. Снимки 1920×1080, тёмна� и �ветла� темы: не разобрана, наведение (по возможно�ти), идёт разбор (`CP_REVIEW=1`, задержки 3 и 6 �), готово � открытым отчётом, отчёт �крыт (`CP_KEYS="Shift+A"`), неактивна (пои�к ошибок в дебютах на вкладке «Отчёт»). Цвета пик�елей заливки �верить � таблицей §2, допу�к ±2 на канал (�глаживание). +2. **�ет �качков.** Пр�моугольник кнопки (у нынешней �борки 27×23 при x 1818, y 1046) и верх панели �овпадают до пик�ел� на �ери�х «не разобрана → разбор 3 � → 6 � → готово → �крыт». Панель в�егда в одну �троку. Вы�ота нотации мен�ет�� только тогда, когда пользователь открывает или �крывает отчёт: график при открытии отчёта — уже �уще�твующее �вное дей�твие. +3. Кнопка по вы�оте и �круглению �овпадает � �о�едними `💾` и `�`. Промежуток до разделител� тот же, что в о�тальных группах. +4. Узкое окно 960×600, тёмна� тема: панель перено�ит�� так же, как раньше (`game-960-en` из задачи 42), а �ама кнопка во врем� разбора не мен�ет размер. +5. HiDPI ×2 (е�ли окружение позвол�ет): граница прогре��а и иконка чёткие, иконка не обрезана. +6. Бирюзовый р�дом � �иним выделенным ходом в нотации и активной вкладкой не �ливает�� � ними. �а �нимке «не разобрана» глаз �начала находит до�ку и выделенный ход, а кнопка — един�твенна� цветна� в панели. +7. О�тановка щелчком и Shift+A во врем� разбора работает. По�ле о�тановки кнопка возвращает�� в «не разобрана» или «отчёт» (е�ли данные ча�тично �охранены) без изменени� размера. + +## 5. Что передать те�тировщику + +- Shift+A во в�ех четырёх �о�то�ни�х, Tab-фоку� на кнопке, Esc и Enter при фоку�е. +- Гонка: щелчок в момент завершени� разбора не должен запу�кать разбор заново или тер�ть отчёт. +- `engine_busy` от пои�ка ошибок в дебютах (и от прохода задачи 27): кнопка неактивна, под�казка верна�, разбор не �тартует по Shift+A. +- Повторное открытие разобранной партии из к�ша �разу показывает �о�то�ние «отчёт». + +## �ерешённое + +- Чи�ло «N/M» уходит из панели в график и под�казку. Е�ли владелец хочет видеть чи�ло пр�мо на кнопке, придёт�� ра�ширить �лот по�то�нно (примерно 44 px) во в�ех �о�то�ни�х. Это нужно �про�ить у владельца. diff --git a/docs/design/task-26/graph-overlap.png b/docs/design/task-26/graph-overlap.png new file mode 100644 index 0000000..d725680 Binary files /dev/null and b/docs/design/task-26/graph-overlap.png differ diff --git a/docs/design/task-26/now-idle-d1-crop.png b/docs/design/task-26/now-idle-d1-crop.png new file mode 100644 index 0000000..17de690 Binary files /dev/null and b/docs/design/task-26/now-idle-d1-crop.png differ diff --git a/docs/design/task-26/now-running-d1-crop.png b/docs/design/task-26/now-running-d1-crop.png new file mode 100644 index 0000000..2bc9ad4 Binary files /dev/null and b/docs/design/task-26/now-running-d1-crop.png differ diff --git a/docs/design/task-26/now-states-strip.png b/docs/design/task-26/now-states-strip.png new file mode 100644 index 0000000..8e1a12e Binary files /dev/null and b/docs/design/task-26/now-states-strip.png differ diff --git a/docs/design/task-26/states-mock.png b/docs/design/task-26/states-mock.png new file mode 100644 index 0000000..c2dc37b Binary files /dev/null and b/docs/design/task-26/states-mock.png differ diff --git a/docs/design/task-27-brilliant-search-2026-11-27.md b/docs/design/task-27-brilliant-search-2026-11-27.md new file mode 100644 index 0000000..721546d --- /dev/null +++ b/docs/design/task-27-brilliant-search-2026-11-27.md @@ -0,0 +1,606 @@ +# Задача 27. Пои�к замечательных ходов (!!, !) по отфильтрованным парти�м базы + +Стату�: �пецификаци� дизайнера, 2026-11-27. Код не мен�л��. Учтены решени� владельца +от 2026-11-27 (`docs/dev/tasks.md`, задача 27): лимит ≤ 100 включительно; кнопка видна +в�егда; при > 100 она неактивна и показывает под�казку; разобранные партии берут�� из +�охранённого разбора; е�ть «О�тановить», и в�ё разобранное до о�тановки �охран�ет��; +найденное отмечает�� значком в �троке. Решение �очетает�� �о �пецификацией задачи 42 +(`docs/design/tasks-42-43-2026-11-27.md` §42.3, §42.9), котора� �ейча� реализует��. + +**Обновление 2026-11-27 (2).** Владелец прин�л вариант B и в�е п�ть рекомендаций §9, а также +добавил итоговое окно. Что изменило�ь в документе: + +| Решение владельца | Где отражено | +|---|---| +| Кнопка работает только по фильтру, пункта «в выбранных» нет | §4.7 (перепи�ан), §6 (�трока меню убрана) | +| Е�ли в фильтре задан игрок, �читают�� только его ходы | §4.3 (значок и под�казка), §4.9, §5 п. 3 (индек� хранит отметки по цвету) | +| Старый разбор за�читывает�� без пере�чёта | §4.3 (�трока «у�тарел» — только подпи�ь), §4.9 | +| Фильтра «только � !!» нет, е�ть �ортировка по колонке «!!» | §4.3 | +| Игра � движком во врем� прохода запрещена, е�ть под�казка | §4.5, §6 | +| **�овое:** итоговое окно по�ле прохода и по�ле «О�тановить» | **§4.9**; то�ты «готово / о�тановлен / в�ё было» из §4.6 и §6 заменены окном | +| Задача 26 �делана: 📈 цветом `#26c2a3` / `#1a846f` | «!!» на кнопке задачи 27 — тот же цвет (§4.1), �квозна� �в�зь «!! = разбор» | + +## 0. И�ходные �нимки (текущий код, `target/debug/chesspenguin` от 2026-11-27 13:27) + +Снимал через `scripts/dev/headless-run.sh` � изолированным профилем +`/tmp/opencode/t27/{cfg-*,data,cache}`. Базы: копии `ruy.pgn` (49 партий), `alekhin.pgn` +(267) и Mega Database 2026 (11,7 млн, только чтение). Снимки лежат в `/tmp/opencode/t27/s/`, +макеты — в `docs/design/task-27/` (нари�ованы поверх �тих �нимков). + +| Снимок | Размер | Со�то�ние | Что из него �ледует | +|---|---|---|---| +| `ruy-ru-1920.png` | 1920×1080 | 49 партий, фильтра нет | Строка у�ловий (22 px) е�ть в�егда: «У�ловий нет — показаны в�е партии». Справа в ней пу�то. Кнопка зде�ь была бы активна (49 ≤ 100) даже без фильтра | +| `alekhin-ru-1920.png` | 1920×1080 | 267, фильтра нет | Кнопка неактивна | +| `alekhin-f-ru-1920/960.png` | 1920 / 960×600 | «Годы: 1914–1914», найдено 7 из 267 | Шапка: «найдено 7 из 267». Один чип | +| `mega-f-ru-1920.png` | 1920×1080 | 3 у�лови�, найдено 4 221 | Кнопка неактивна, нужна под�казка. Колонка 💬 (40 px) заполнена 💬🔀 | +| `mega-f2-ru-1920.png` | 1920×1080 | 3 у�лови�, найдено 62 | Типичный рабочий �лучай: кнопка активна | +| `mega-f2-ru-960.png` | 960×600 | то же | Таблица 676 px. Колонки 💬, ECO, «Длина», «Турнир», «Тур» �крыты. **Колонка 💬 пропадает уже при ширине < 1000**, значит значок туда кла�ть нельз�. Три чипа занимают до x≈424, �права �вободно ~250 px | +| `ruy-en-960.png` | 960×600 | англ., без фильтра | «No conditions: all games are shown» до x≈211 | +| `docs/screenshots/review.png` | 2000×1125 | отчёт партии | Цвета: !! бирюзовый `#26c2a3`, ! зелёный `#81b64c` (`notation::assessment_color`). Значок на до�ке — бирюзовый кружок «!!» | + +Что видно на �нимках: +- шапка базы измер�ет�� по ширине и на узком окне уходит на вторую �троку + (`narrow-windows.md §2.4`, `large_db.rs:1714+`); +- �трока у�ловий по�то�нна по вы�оте (`chips()`, `set_min_height(22.0)`). Справа она уже + зан�та блоком «в �том пор�дке ходов…» (пои�к по позиции), а задача 42 �тавит туда �чётчик + выделени� и прогре�� запи�и; +- нижн�� поло�а панели фильтров («Сбро�ить фильтры (3)») видна только при открытой вкладке + «Фильтры». При вкладке «До�ка», при `Pane::Hidden` и в �щике узкого окна её нет. + +## 1. Задача (одной фразой) + +Пользователь �узил базу фильтром или пои�ком по позиции до небольшого набора и одной командой +узнаёт, в каких из �тих партий были бле�т�щие (!!) и замечательные (!) ходы. Важно�ть +информации: можно ли запу�кать (и почему нельз�) → идёт ли проход, �колько о�тало�ь и как +о�тановить → какие партии отмечены и чем. + +## 2. Путь пользовател� и �охранение контек�та + +1. База Mega → фильтры «Игрок: carlsen magnus», «Годы 2025–2026», «Elo ≥ 2780» → «найдено 62». + Справа в �троке у�ловий кнопка «!! �айти замечательные ходы» �тала активной. При 4 221 + найденных она была видна, но неактивна, и под�казка объ��н�ла почему. +2. Щелчок (или Shift+A) → диалог: «Движок разберёт 53 партии — примерно 14 минут. 9 уже + разобраны…» → «�ачать». +3. �а ме�те кнопки по�вл�ет�� �трока прогре��а «!! Проанализировано 12 из 62 · о�тало�ь ≈ 11 мин + ▕██░░� О�тановить». Таблица не �двигает��. Значки по�вл�ют�� в �троках по мере разбора. + Таблицу можно ли�тать, �ортировать, фильтровать. Партию можно открыть, а потом вернуть�� + (Ctrl+W / «� Библиотека»): фильтры, прокрутка и выделение о�тают�� прежними (как �ейча�). +4. Окончание (или «О�тановить»): прогре�� �мен�ет�� кнопкой и открывает�� итоговое окно + (§4.9) — �уммы !!, !, ?!, ?, ??, �редн�� точно�ть и �пи�ок партий � !!. +5. Позже — то же �амое при повторном открытии базы или по�ле перезапу�ка программы: значки + читают�� из �охранённых результатов. + +�абор партий фик�ирует�� в момент нажати� «�ачать». Е�ли потом изменить фильтр, проход идёт +по зафик�ированному �пи�ку, а значки по�вл�ют�� везде, где �ти партии видны. + +## 3. Варианты размещени� кнопки + +### Вариант A — в шапке базы, р�дом � «найдено 62 из …» (`docs/design/task-27/A-header-1920.png`) + +``` +│ Mega Database 2026 · ChessBase, только чтение · найдено 62 из 11 743 083 ⓘ1 [!! �айти замечательные ходы] [� Пои�к…] [Фильтры][До�ка] │ +│ [Игрок: carlsen magnus ×] [Годы: 2025–2026 ×] [Elo ≥ 2780 ×] │ +``` + +- \+ Св�зь � чи�лом очевидна: «найдено 62» �тоит пр�мо р�дом � кнопкой. +- − Шапку измер�ют по ширине (`narrow-windows.md §2.4`). �а 960×600 уже �ейча� им� базы + �окращено до «Mega Database 2…». �ова� кнопка шириной 210 px �двинет поле пои�ка и отправит + шапку на вторую �троку, **таблица уедет вниз**. Задача 42 отказала�ь от шапки по той же + причине. +- − Прогре��у (~380 px) ме�та в шапке нет �ов�ем. +- − Кнопка оказывает�� �реди «па�порта» базы (им�, формат, кодировка), а не �реди у�ловий. + +### Вариант B — �права в �троке у�ловий (рекомендует��) (`B1…B5`) + +``` +├ �трока у�ловий, 22 px ───────────────────────────────────────────────────────────────────────────────┤ +│ [Игрок: carlsen magnus ×] [Годы: 2025–2026 ×] [Elo ≥ 2780 ×] Выбрано: 3 · Сн�ть [!! �айти замечательные ходы] │ +``` + +- \+ Кнопка **буквально �тоит в конце �пи�ка у�ловий**: «вот у�лови� → по ним найти». Она + получает�� �лед�твием фильтра, как про�ил владелец. Без фильтра в той же �троке напи�ано + «У�ловий нет — показаны в�е партии», и кнопка в�ё так же видна. +- \+ Строка е�ть в�егда и вы�оту не мен�ет. �и кнопка, ни прогре��, ни неактивное �о�то�ние + таблицу не �двигают. +- \+ Механизм ухода чипов в «+N ещё» уже е�ть (меньше 140 px �вободно → о�таток в под�казке). + Ме�та на кнопку и прогре�� отдают у�лови�, а не таблица. +- \+ Работает при любой вкладке правой панели (Фильтры / До�ка / �крыта), в �щике узкого окна + и дл� пои�ка по позиции. Пои�к по позиции тоже фильтр, его 62 партии — тоже выборка. +- − Строку дел�т три владельца: пор�док ходов, выделение (42), пои�к (27). �а 960 px � трем� + чипами и выделением чипы �ворачивают�� до «Игрок: … +2 ещё». Это приемлемо, так + задумано в 42 (`B4`). +- − Кнопка 18 px в �троке 22 px. Это маленька� кнопка того же размера, что `small_button` + в шапках. + +### Вариант C — в нижней поло�е панели фильтров, над «Сбро�ить фильтры» (`C-filters-footer-1920.png`) + +``` +│ … �ннотации │ +│ ─────────────────────────── │ +│ [!! �айти замечательные ходы (62)] │ +│ [Сбро�ить фильтры (3)] │ +``` + +- \+ Кнопка физиче�ки �тоит у фильтров. +- − �е видна при вкладке «До�ка» (пои�к по позиции тоже фильтрует), при �крытой панели и в + закрытом �щике узкого окна. Правило «видна в�егда» нарушено. +- − Поло�а шириной 280 px: в одну �троку � «Сбро�ить» не помещает��, нужна втора� �трока. + Вы�ота поло�ы ра�тёт, панель фильтров тер�ет 30 px. +- − Прогре�� в панели шириной 280 px получает�� те�ным, а при закрытой панели его вообще + не видно. Пришло�ь бы дублировать его в таблице. +- − �еактивна� кнопка � под�казкой внизу панели незаметна: взгл�д туда не попадает. + +### Рекомендаци� — **B** + +Только �тот вариант выполн�ет в�е у�лови� �разу: кнопка видна в�егда, о�таёт�� �лед�твием +фильтра, прогре�� не �двигает таблицу, на 960 px в�ё �охран�ет��. Мину� варианта B — те�на� +�трока. Он решает�� правилами �окращени� из §4.2, их уже примен�ет задача 42. + +## 4. Вариант B подробно + +### 4.1. Пор�док в �троке у�ловий (�права налево) + +``` +[�лот 27: кнопка или прогре�� пои�ка] [в �том пор�дке ходов: n из m · только �тот пор�док] [�лот 42: Выбрано / прогре�� запи�и] [у�лови�…] +``` + +- **Слот 27 — крайний �права, в�егда.** Так кнопка не прыгает по горизонтали, когда + по�вл�ет�� �чётчик выделени� (Ctrl+щелчок) или блок пор�дка ходов (�мена позиции на до�ке). + Это уточнение к §42.3: блок «пор�док ходов» и �лот 42 �двигают�� на ширину �лота 27 влево. + Разработчику 42 нужно о�тавить в `chips()` ме�то дл� �лота �права. +- Промежуток между �лотами — 12 px (`item_spacing.x` + 4). +- Кнопка — **обычна�** маленька� кнопка (фон `widgets.inactive.weak_bg_fill`, как «Сбро�ить + фильтры»), а не о�новна� (primary). Префик� «!!» — Ubuntu-B 13 px цветом + `assessment_text_color($3)` (бирюзовый, в �ветлой теме `#1a846f`). Это тот же знак, что в + отчёте и на до�ке (задача 26 делает кнопку разбора в партии того же цвета: �в�зь + «!! = разбор» �квозна�). Тек�т — обычный цвет кнопки. О�новную �инюю заливку не берём: + в большой базе кнопка почти в�егда неактивна, а неактивна� о�новна� кнопка выгл�дит как + �ломанна�. +- �еактивное �о�то�ние — штатное `add_enabled(false, …)` (egui приглушает в�ю кнопку, + включа� «!!»), под�казка — `on_disabled_hover_text`. + +### 4.2. Сокращени� по ширине (измер�ть тек�том, как в шапке) + +| Свободно под �лот 27 | Кнопка | Прогре�� | +|---|---|---| +| ≥ 400 px | «!! �айти замечательные ходы» | «!! Проанализировано 12 из 62 · о�тало�ь ≈ 11 мин ▕90 px� О�тановить» | +| ≥ 220 px | «!! �айти замечательные ходы» | «!! 12 из 62 · ≈ 11 мин ▕60 px� О�тановить» | +| меньше | «!! �айти ходы» (`B5`) | «!! 12 из 62 ▕60 px� О�тановить» (`B4`) | + +Полный тек�т и, при �окращении, о�тавшее�� врем� — в под�казке при наведении на �лот. +Сначала �ворачивают�� чипы (до «+N ещё»), потом �окращает�� �лот 27. Ширину �лота прогре��а +резервировать **по �амому длинному значению** («100 из 100 · о�тало�ь ≈ 59 мин»), а тек�т +выравнивать по правому краю. Иначе поло�а и «О�тановить» будут дрожать при �мене цифр +(шрифт Ubuntu пропорциональный). + +### 4.3. Значок в �троке партии + +**Ме�то — нова� узка� колонка «!!» шириной 28 px �разу по�ле «Рез.»** (`B1`, `B3`, `B4`). + +- Колонка 💬 не подходит: при ширине < 1000 px она �крывает�� (`show_marks`), а результат + пои�ка должен быть виден и на 960 px. Ширина 40 px там уже зан�та «💬🔀». +- Колонка № не подходит: там уже �тоит ✓ «про�мотрено», а в узком окне при пои�ке по позиции + колонка № �крывает��. +- �ова� колонка **показывает�� в�егда**: в любой базе, на любой ширине, в том чи�ле пока + в ней пу�то. По�тому по�вление первого значка ничего не �двигает. �а 960 px её 28 px берут�� + из колонок имён (они `remainder`). �а �нимке `B4` имена при �том помещают��. +- Ячейки (по центру, Ubuntu-B 13 px): + +| Со�то�ние партии | Ячейка | Цвет | Под�казка | +|---|---|---|---| +| не разбирала�ь | пу�то | — | — | +| в очереди текущего прохода | пу�то | — | — | +| разбирает�� �ейча� | �пиннер 12 px | тек�т | «Разбирает��…» | +| е�ть !! (и, может быть, !) | `!!` | `assessment_text_color($3)` | «Бле�т�щих ходов: 1 — 21.Rxf7!! (белые) / Замечательных: 2 — 14.Nd5!, 26…Qe7! (чёрные)» | +| только ! | `!` | `assessment_text_color($1)` | «Замечательных: 2 — …» | +| разобрана, !! и ! нет | `·` | `weak_text_color` | «Разобрана: бле�т�щих и замечательных ходов нет» | +| не разбирает�� (Chess960, нет ходов, учебный `--`) | `—` | weak | «�е разбирает��: {причина}» | +| разбор прежними на�тройками (`ReviewMeta::is_stale`) | как выше | как выше | + �трока «Разбор прежними на�тройками движка» | + +- Читает�� без цвета: `!!`, `!`, `·`, `—` — разные знаки. �а выбранной �троке (заливка + `selection.bg_fill`) знаки ри�уют�� цветом `selection.stroke.color`, как о�тальной тек�т: + бирюзовый на �инем не читает��, а форма знака �охран�ет��. +- Ходы в под�казке — не больше трёх на вид, дальше «и ещё N», нотаци� — по на�тройке + (латиница/ру��ка�/фигурки). +- Заголовок колонки «!!» �ортирует: !! → ! → «·» → «—» → не разобранные. Внутри групп пор�док + по номеру запи�и. Так без нового фильтра можно �обрать найденное �верху (решение владельца: + отдельного фильтра нет). +- **Игрок в фильтре** (решение владельца): значок, �ортировка и под�казка учитывают только + ходы игрока из у�лови� «Игрок» � учётом «белыми / чёрными / любым». В под�казке перва� + �трока — weak: «Ходы игрока «carlsen magnus»». Сменил�� фильтр — значки пере�читывают�� + из индек�а без движка. Е�ли без фильтра у партии е�ть !! �оперника, а у игрока — только !, + то при фильтре в �троке �тоит «!». Так и задумано. +- Пометка «Разбор прежними на�тройками движка» в под�казке — только информаци�. Такой + разбор за�читывает�� как готовый и в проходе не пере�читывает�� (решение владельца). +- Контек�тное меню �троки � отметками (одна парти�) — новый пункт «Открыть на ходе 21.Rxf7!!» + (первый !!, иначе первый !). Он открывает партию на �том ходе �о вкладкой «Отчёт». Щелчок + по �чейке ничего о�обого не делает: щелчок по �троке — �то выделение (задача 42), двойной + щелчок — открыть. + +### 4.4. Диалог перед запу�ком (`D-dialog-1920.png`) + +Тот же вид окна, что «Добавить в базу» (`chooser-ru.png`): без затемнени�, ширина ≈ 520 px, +заголовок 17 px, weak-подзаголовок 12 px, кнопки �права внизу. + +``` +┌──────────────────────────────────────────────────────────────� +│ �айти замечательные ходы │ +│ Mega Database 2026 · 62 партии по у�лови�м: Игрок, Годы, Elo │ � weak +│ │ +│ Движок разберёт 53 партии — примерно 14 минут. │ +│ 9 уже разобраны: их отметки возьмут�� из �охранённого разбора.│ +│ │ +│ Компьютер будет загружен (до 8 проце��ов Stockfish 19). │ +│ Работать � программой можно; о�тановить — в любой момент, │ +│ разобранные партии �охран�т��. │ +│ [Отмена] [�ачать] │ +└──────────────────────────────────────────────────────────────┘ +``` + +- **Оценка времени:** `Σ (полуходы_i + 1) × 0,94 � / P` по неразобранным парти�м. 0,94 � — + �то пои�к на позицию в одном проце��е вме�те �о вторым пои�ком дл� !!/!: 106 � / 113 позиций, + `decisions.md`, «Разбор на фик�ированных параметрах». P — чи�ло проце��ов разбора, которое + `job.rs` выберет на �той машине. Длина берёт�� из индек�а (`r.moves`). Округл�ть: < 1 мин → + «меньше минуты», < 60 мин → «примерно N минут», иначе «примерно 1 ч 20 мин». Во врем� + прохода «о�тало�ь ≈» пере�читывает�� по фактиче�кой �коро�ти по�ле 3 партий, а до �того — по + той же формуле. +- Счёт «уже разобраны» идёт в фоне (≤ 100 партий: прочитать ход, проверить к�ш). Пока он не + готов, на ме�те первых двух �трок �тоит «Считаю, �колько партий уже разобрано…» �о + �пиннером, и «�ачать» неактивна. Вы�ота окна резервирует�� под две �троки, чтобы окно не + прыгало. +- **В�е 62 уже разобраны:** диалог не показывает��, а �разу открывает�� итоговое окно (§4.9). + Это и е�ть �по�об �нова по�мотреть итог. +- **Подзаголовок:** «по у�лови�м: …» — названи� активных у�ловий. Дл� пои�ка по позиции — + «по позиции на до�ке». Без у�ловий — «в�е партии базы». +- Enter — «�ачать», Esc — «Отмена». Фоку� по умолчанию — на «�ачать». +- �ет Stockfish 19 → �начала �уще�твующее предложение �качать + (`need_review_engine`, новый `Pending::BrilliantSearch`), затем �тот диалог. + +### 4.5. Один engine job на программу + +| Что зан�то | Кнопка 27 | Под�казка / поведение | +|---|---|---| +| Идёт пои�к ошибок дебюта в подготовке (`prep.running()`) | неактивна | «Движок зан�т: идёт пои�к ошибок дебюта в подготовке — дождите�ь или о�тановите его» | +| Идёт разбор одной партии («�нализ партии») | неактивна | «Движок зан�т: идёт разбор партии {белые — чёрные}» | +| Проход 27 идёт в **другой** базе | неактивна | «Идёт пои�к в «{база}»: 12 из 62 — о�тановите его там» | +| Живой анализ в открытой партии | — | При «�ачать» живой анализ выключает��, как `PrepAction::EngineStarted` | +| Во врем� прохода пользователь открыл партию | — | Кнопка «�нализ партии» и включение живого анализа неактивны. Под�казка: «Идёт пои�к замечательных ходов в «{база}»: 12 из 62. О�тановить — в библиотеке». Е�ли парти� уже разобрана, её отчёт открывает�� из к�ша | +| Во врем� прохода — подготовка / игра � движком | — | Запу�к пои�ка ошибок дебюта и «Играть» неактивны (решение владельца). Под�казка: «Идёт пои�к замечательных ходов в «{база}»: 12 из 62 — дождите�ь или о�тановите его в библиотеке». То же дл� «Играть � �той позиции» в партии | + +Во врем� прохода в **других** базах �лот 27 показывает не кнопку, а компактный прогре�� +«!! В «Mega»: 12 из 62» (��ылка ведёт в ту базу) и «О�тановить». Кнопку «�айти» в �той базе +и�кать не нужно, а о�тановить проход можно � любого ме�та. + +### 4.6. Матрица �о�то�ний + +| Со�то�ние | Слот 27 | Таблица / прочее | +|---|---|---| +| Пу�та� база | �троки у�ловий нет (�кран «�ет партий», как �ейча�) | — | +| Без у�ловий, ≤ 100 партий (ruy, 49) | кнопка активна | колонка «!!» пу�та� или �о значками | +| 0 найдено | кнопка неактивна: «�ет партий по �тим у�лови�м» | «�ет партий» | +| 1…100 найдено | кнопка активна; под�казка «Разобрать движком {n} и отметить найденные !! и ! (Shift+A)» | — | +| > 100 (4 221, 11,7 млн) | кнопка **видна, неактивна** (`B2`); под�казка «Отфильтруйте партии, чтобы их было не больше 100» и втора� �трока «Сейча�: 4 221» | — | +| Фильтр ещё �читает�� (больша� база, прогре�� в шапке) | кнопка неактивна: «Подождите — партии ещё отбирают��» | как �ейча�, `set_opacity(0.6)` | +| Движок зан�т | §4.5 | — | +| Диалог | §4.4 | — | +| Идёт проход | прогре�� (`B3`, `B4`) | �пиннер в разбираемой �троке, значки по�вл�ют�� по одному | +| �ажато «О�тановить» | «О�танавливаю…» и �пиннер на ме�те поло�ы, до о�тановки проце��ов (≤ 2 �) | — | +| О�тановлено | кнопка; **итоговое окно** по разобранным (§4.9, вид «о�тановлен») | недоразобранна� парти� о�таёт�� без значка | +| Готово | кнопка; **итоговое окно** (§4.9) | — | +| Готово, ничего не найдено | итоговое окно, нули приглушены, «Бле�т�щих ходов нет» (§4.9) | везде «·» | +| Ча�ть пропущена | в итоговом окне �трока «�е разобраны: 1 (Chess960)» (§4.9) | «—» в �троке | +| Ошибка движка (упал, таймаут) | кра�ный `error_fg_color` на ме�те прогре��а: «Движок о�тановил�� � ошибкой: {причина}. Разобрано 12 из 62» + `×` | разобранное �охранено | +| Файл базы изменил�� во врем� прохода | проход о�танавливает��, тот же кра�ный тек�т: «База «{им�}» изменила�ь — пои�к о�тановлен. Разобрано 12 из 62» | значки разобранных партий прив�заны к их ходам (§5) и о�тают�� верными | +| Закрытие окна во врем� прохода | без вопро�а: проце��ы га��т�� (как при выходе из разбора), разобранное уже �охранено | — | +| Одновременно запи�ь из задачи 42 | оба прогре��а в �воих �лотах, при нехватке ме�та — �окращённые формы | — | +| Узкое окно 960×600 | �окращени� §4.2 | колонка «!!» видна (28 px) | +| HiDPI ×2 | 1 логиче�кий px = 2 физиче�ких; �пиннер и поло�а — painter, чёткие | проверить, не обрезает�� ли «!!» в 28 px | +| Светла� тема | `assessment_text_color(.., dark=false)`: `#1a846f`, `#5b8135` (контра�т ≥ 4,5:1) | — | + +### 4.7. Св�зь � выделением задачи 42 (решено) + +Кнопка и Shift+A **в�егда** работают по отфильтрованной таблице. Выделение на них не вли�ет, +и в пакетном меню §42.7 пункта дл� пои�ка нет (решение владельца). Итоговое окно (§4.9) только +выбирает �троку обычным щелчком. Много�трочное выделение оно не �оздаёт. + +### 4.8. Клавиатура и фоку� + +| Клавиша | Где | Дей�твие | +|---|---|---| +| Shift+A | библиотека, фоку� не в поле ввода | то же, что кнопка (по аналогии � «�нализ партии» в партии, Shift+A). Е�ли кнопка неактивна — то�т � тек�том её под�казки | +| Tab | �трока у�ловий | кнопка и «О�тановить» — обычные фоку�ируемые виджеты � рамкой фоку�а egui | +| Enter / Esc | диалог | «�ачать» / «Отмена» | +| Esc | во врем� прохода | **не о�танавливает** (Esc �нимает выделение и закрывает �щик, §42.6). О�тановить — только �вно: «О�тановить» | + +Под�казки: у кнопки — §4.6; у «О�тановить» — «О�тановить пои�к; разобранные партии +�охран�т��»; у прогре��а — полный тек�т и текуща� парти� «Сейча�: Carlsen — Nakamura, 2025». + +### 4.9. Итоговое окно (дополнение владельца 2026-11-27) + +Задача окна: одним взгл�дом показать, что нашёл проход по выборке, — �начала бле�т�щие +и замечательные ходы, затем ошибки, затем общий уровень. Из окна можно �разу перейти к парти�м � !!. + +Макеты: `docs/design/task-27/E1-summary-1920.png` (готово, 1920×1080, игрок в фильтре), +`E2-summary-960-stopped.png` (о�тановлено, 960×600). + +#### Когда показывает�� + +| Событие | Окно | +|---|---| +| Проход закончил�� | открывает�� �амо, вид «готово» | +| �ажато «О�тановить», проце��ы о�тановлены | открывает�� �амо, вид «о�тановлен» по разобранным парти�м | +| Ошибка движка или база изменила�ь во врем� прохода | кра�ный тек�т на ме�те прогре��а (§4.6). Окно по разобранным открывает�� по щелчку на �том тек�те («Итог по разобранным»), �амо не открывает�� | +| Кнопка «�айти» нажата, а в�е партии выборки уже разобраны | открывает�� **�разу, без диалога**. Это и е�ть повторный показ (§4.4) | +| Кнопка нажата, разобраны не в�е | обычный диалог (§4.4). В диалоге по�вл�ет�� треть� кнопка «Итог по разобранным ({k})», е�ли k ≥ 1 | + +**Отдельной кнопки «Итог» в �троке у�ловий нет.** В �троке и так те�но (§4.2), а итог в�егда +�читает�� заново из индек�а дл� **текущей** выборки, по�тому его можно вызвать той же кнопкой. +Под�казка кнопки, когда в�ё разобрано: «В�е {games} уже разобраны — показать итог (Shift+A)». + +#### Со�тав и пор�док (�верху вниз) + +``` +┌───────────────────────────────────────────────────────────────────────────� +│ Итог · разобрано: 62 партии × │ � заголовок 17 px +│ Mega Database 2026 · Игрок: carlsen magnus · Годы: 2025–2026 · Elo ≥ 2780 │ � weak 12 px, у�лови� +│ Считают�� только ходы игрока «carlsen magnus»: белыми 31, чёрными 31 │ � weak, только при игроке +│ │ +│ 2 Бле�т�щий │ � #26c2a3 +│ 9 Замечательный │ � #81b64c +│ 71 �еточно�ти │ � #56b4e9 +│ 38 Ошибки │ � #ffa459 +│ 11 Зевки │ � #fa412d +│ 27 Средн�� потер� �антипешек │ +│ 86% Средн�� точно�ть │ +│ ───────────────────────────────────────────────────────────────────────── │ +│ Партии � !! (2) │ � strong 13 px +│ 21.Rxf7!! Carlsen, M. — Nakamura, H. · 1-0 · Chessable Masters · 19.02.2025 │ � выбранна� �трока �пи�ка +│ 34…Nf3+!! Erigaisi, A. — Carlsen, M. · ½-½ · Chessable Masters · 19.02.2025 │ +│ Щелчок — выбрать �троку в таблице, двойной щелчок — открыть на �том ходе │ � weak 12 px +│ [Открыть партию] [Закрыть] │ +└───────────────────────────────────────────────────────────────────────────┘ +``` + +1. **Заголовок:** «Итог · разобрано: {games}» (`i18n::games`: «62 партии», «1 парти�»); при + о�тановке — «Пои�к о�тановлен · разобрано: {i} из {n}». Справа `×`. +2. **Подзаголовок:** база и у�лови� выборки (как в диалоге §4.4) — чтобы позже, при повторном + показе, было пон�тно, к чему отно��т�� чи�ла. +3. **Строка про игрока** — только е�ли в фильтре е�ть «Игрок»: «Считают�� только ходы игрока + «{name}»: белыми {w}, чёрными {b}». Е�ли задано «белыми» или «чёрными» — «…игрока «{name}» + белыми ({w} партий)». Парти�, где игроку подход�т обе �тороны, учитывает�� за обе. Без игрока + �троки нет, а �читают�� ходы обеих �торон в�ех партий. +4. **Таблица категорий** — тот же grid и �тиль, что в отчёте партии (`review.rs:760+`): чи�ло + �права strong 15 px, название 15 px, цвет `judgement_text_color` (в �ветлой теме — + `assessment_text_color(.., false)`). При нуле �трока приглушена `weak_text_color`, как в + отчёте. Пор�док и названи� берут�� из отчёта, ключи `judgement_plural` те же: + !! → ! → ?! → ? → ??. Чи�ла — �уммы по разобранным парти�м (� учётом п. 3). +5. **Средн�� потер� �антипешек** и **�редн�� точно�ть**: �реднее по парти�м (по �торонам), + а не по ходам. Это та же величина, что в отчёте, у�реднённа� по {k} �торонам. При игроке — + только его �тороны. Фазовые �троки («Дебют / Миттельшпиль / Эндшпиль») не показывают��: + в �умме по разным парти�м они мало что говор�т, а окно �тало бы вдвое выше. Под�казка у + «Средн�� точно�ть»: «Среднее по {k} парти�м: от {min}% до {max}%». +6. **Разделитель** и **�пи�ок «Партии � !! ({n})»**: одна �трока на **ход** !! (у партии � двум� + !! — две �троки). Пор�док — как в таблице на момент прохода, внутри партии — по ходу. Слева + ход � номером (Ubuntu-B 13 px, бирюзовый, нотаци� по на�тройке, колонка шириной по + �амому длинному ходу). Справа «Белые — Чёрные · рез. · турнир · дата» обрезает�� многоточием. + Вы�ота �троки 24 px. Спи�ок — `ScrollArea` вы�отой не больше 6 �трок (144 px). Больше 6 — + прокрутка, окно не ра�тёт. +7. **Под�казка по �пи�ку** (weak 12 px) и **кнопки** �права внизу: «Открыть партию» + (активна, когда в �пи�ке выбрана �трока) и «Закрыть». О�новной (�иней) кнопки нет: окно + ничего не подтверждает. + +#### Спи�ок: щелчок и клавиатура + +| Дей�твие | Результат | +|---|---| +| Щелчок по �троке �пи�ка | �трока �пи�ка выбрана (заливка `selection.bg_fill`). **В таблице за окном выбирает�� та же парти�** (одна �трока, как обычный щелчок в таблице; выделение задачи 42 �водит�� к ней), таблица прокручивает�� к ней. Окно о�таёт�� открытым | +| Двойной щелчок / Enter / «Открыть партию» | открыть партию **на �том ходе** �о вкладкой «Отчёт» (как пункт меню «Открыть на ходе», §4.3). Окно закрывает��. Возврат (Ctrl+W) — в библиотеку � той же выборкой, парти� выбрана в таблице, окно �нова не открывает�� | +| ↑ / ↓ | по �трокам �пи�ка, фоку� в окне | +| Esc, `×`, «Закрыть» | закрыть окно; выборка, �ортировка и выделение не мен�ют�� | +| Парти� �пи�ка �крыта текущим фильтром (фильтр помен�ли при открытом окне) | �трока �пи�ка приглушена, под�казка «Скрыта фильтром»; щелчок только выбирает �троку �пи�ка, двойной щелчок открывает партию | + +Окно **немодальное** (`egui::Window`, как «Добавить в базу», без затемнени�), его можно +перета�кивать. Таблица за ним работает. Окно прив�зано к базе: при переключении базы на +полке оно закрывает��. + +#### Варианты �о�то�ни� + +| Со�то�ние | Что мен�ет�� | +|---|---| +| Готово, е�ть !! | как на макете E1 | +| Готово, !! нет, но е�ть ! | �пи�ок замен�ет�� �трокой weak «Бле�т�щих ходов нет. Партии � ! — �ортировка по колонке «!!»» и ��ылкой «От�ортировать» (�ортирует таблицу, окно о�таёт��) | +| Готово, нет ни !!, ни ! | �троки 1–2 таблицы приглушены (нули), под разделителем — «Бле�т�щих и замечательных ходов нет» | +| О�тановлено (E2) | заголовок «Пои�к о�тановлен · разобрано: 12 из 62»; под �трокой игрока weak «50 партий не разобраны — «Продолжить» разберёт только их»; �лева от «Открыть партию» кнопка «Продолжить», она открывает диалог §4.4 по о�тавшим�� | +| Разобрано 0 (о�тановили на первой партии) | окно не открывает��. То�т «Пои�к о�тановлен: ни одна парти� не разобрана» | +| Ча�ть пропущена | weak-�трока под подзаголовком: «�е разобраны: 1 (Chess960)». В чи�ле «разобранных» её нет | +| Среди партий е�ть �тарые разборы | weak-�трока «{k} из них разобраны прежними на�тройками движка». Чи�ла учитывают�� (решение владельца) | +| Игрок в фильтре, но в партии он не найден по имени (другое напи�ание) | парти� �читает�� без ходов игрока; �трока «В {k} парти�х игрок не найден по имени — их ходы не �читали�ь», под�казка — �пи�ок номеров | +| 960×600 (E2) | окно шириной `min(600, окно − 40)`, вы�ота не больше `окно − 80`. Спи�ок �жимает�� до 3 �трок, тек�т партии обрезает�� многоточием | +| HiDPI | без о�обенно�тей. Чи�ла и цвета — тек�т, проверить обрезку чи�ел из трёх цифр («100%», «128») | + +## 5. Требовани� к реализации (разработчику) + +1. **Слот 27 в `chips()`:** крайний �права, перед блоком пор�дка ходов и �лотом 42 (§4.1). + Ширина измер�ет�� тек�том, �окращени� по §4.2, резерв ширины прогре��а — по мак�имальному + значению. Вы�ота �троки о�таёт�� 22 px. +2. **Колонка «!!»:** `Column::exact(28.0)` по�ле «Рез.», вне правил `show_*`, е�ть во в�ех + ра�кладках (войдёт в ключ `layout` дл� `id_salt`). Сортировка `SortKey::Marks` по §4.3. + Ри�ование — `RichText` Ubuntu-B 13 px или painter (�пиннер — `egui::Spinner` 12 px). +3. **Индек� отметок на базу** (без него таблица на 11,7 млн �трок не �может показывать + значки: им� к�ша разбора — х�ш о�новной линии, `game-review::cache_name`, и вычи�л�ть его + дл� каждой видимой �троки �лишком дорого). Файл в к�ше программы р�дом � к�шем разбора: + `marks/.json`, где номер запи�и → {х�ш о�новной линии, чи�ло !!, + и **по каждому цвету**: чи�ло !!, !, ?!, ?, ??, точно�ть, �редн�� потер�, до 3 ходов !!/! � + номерами полуходов (дл� под�казки и �пи�ка итога — в�е ходы !!), `search` вер�и�, + пропу�к/причина}. По цвету — потому что при игроке в фильтре �читают�� только его ходы. + Сторона игрока в партии определ�ет�� тем же �равнением имени, что и фильтр «Игрок». При показе + и�пользует�� запи�ь, только е�ли х�ш �овпадает � к�шем разбора. Е�ли база + изменила�ь (fingerprint) — проверка х�ша при �ледующем разборе, без ма��ового пере�чёта. + **Индек� пополн�ет и разбор одной партии**, открытой из базы («�нализ партии»). Иначе + разобранна� вручную парти� не получит значок. +4. **Проход:** фонова� задача; �пи�ок номеров запи�ей �нимает�� в пор�дке таблицы на момент + «�ачать». Дл� каждой партии: к�ш разбора �вежий → вз�ть отметки; иначе — тот же + `game-review` job � фик�ированными параметрами (`SEARCH_NODES`, проце��ы по `job.rs`). + По�ле каждой партии к�ш разбора и индек� �охран�ют�� атомарно. Прогре�� отправл�ет�� + через канал не чаще 10 раз/�. «О�тановить» — `AtomicBool` + `stop` проце��ов, таймаут + 2 �, затем kill. Оценки `[%eval]` из PGN дл� прохода **не и�пользуют��** (по ним !!/! не + �тав�т��, `decisions.md`). Парти� разбирает�� движком, и в её PGN ничего не пишет��. +5. **Взаимои�ключение** � подготовкой и разбором одной партии (§4.5): общий флаг «engine job + зан�т» в `app.rs`, к нему подключить и `game.engine_busy`. +6. **Диалог** — по образцу `own_db::Chooser`, оценка по §4.4, фоновый под�чёт разобранных. +7. **Пункт меню �троки** «Открыть на ходе …» (§4.3). Пакетного пункта нет (§4.7). +8. **Итоговое окно** (§4.9): `egui::Window` без затемнени�. Считает�� из индек�а дл� текущей + выборки (≤ 100 запи�ей), в фоне не нужно. Пере�чёт идёт при открытии и при �мене фильтра, + пока окно открыто (чи�ла в окне не мен�ют��: окно держит выборку, по которой открыто; + мен�ют�� только пометки «Скрыта фильтром»). Открытие партии на ходе — тот же путь, что + «Открыть на ходе» в меню. Щелчок по �троке �пи�ка — то же, что щелчок по �троке таблицы, + плю� `scroll_to_selected`. +9. **Отладочные хуки дл� �нимков:** `CP_BRILLIANT_SUMMARY=1` (открыть итоговое окно по + индек�у �разу по�ле �тарта); `CP_MARKS_DEMO=1` (заполнить индек� фиктивными + отметками дл� первых �трок); `CP_BRILLIANT_RUN=1` (�разу запу�тить проход без диалога); + `CP_BRILLIANT_SLOW=1` (`fake_uci` � задержкой, чтобы �н�ть прогре��); `CP_KEYS=Shift+A` + уже работает. + +## 6. Тек�ты ru / en + +| Смы�л | ru | en | +|---|---|---| +| кнопка | !! �айти замечательные ходы | !! Find great moves | +| кнопка, коротко | !! �айти ходы | !! Find moves | +| под�казка, активна | Разобрать движком {games} и отметить найденные !! и ! (Shift+A) | Review {games} with the engine and mark the !! and ! moves found (Shift+A) | +| под�казка, > 100 | Отфильтруйте партии, чтобы их было не больше 100 | Filter the games down to 100 or fewer | +| под�казка, > 100, 2-� �трока | Сейча�: {n} | Now: {n} | +| 0 партий | �ет партий по �тим у�лови�м | No games match these conditions | +| фильтр �читает�� | Подождите — партии ещё отбирают�� | Wait: the games are still being filtered | +| зан�то, подготовка | Движок зан�т: идёт пои�к ошибок дебюта в подготовке — дождите�ь или о�тановите его | The engine is busy searching opening errors in a preparation: wait or stop it | +| зан�то, разбор | Движок зан�т: идёт разбор партии {game} | The engine is busy reviewing {game} | +| зан�то, друга� база | Идёт пои�к в «{db}»: {i} из {n} — о�тановите его там | Searching in «{db}»: {i} of {n}; stop it there | +| диалог, заголовок | �айти замечательные ходы | Find great moves | +| подзаголовок | {db} · {games} по у�лови�м: {list} / по позиции на до�ке / в�е партии базы | {db} · {games} matching: {list} / by the board position / all games | +| �трока 1 | Движок разберёт {games} — примерно {time}. | The engine will review {games}: about {time}. | +| �трока 2 | {k} уже разобраны: их отметки возьмут�� из �охранённого разбора. | {k} are already reviewed: their marks come from the saved review. | +| �трока 3 | Компьютер будет загружен (до {p} проце��ов Stockfish 19). Работать � программой можно; о�тановить — в любой момент, разобранные партии �охран�т��. | The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept. | +| �читаю | Считаю, �колько партий уже разобрано… | Counting the games already reviewed… | +| кнопки | Отмена / �ачать | Cancel / Start | +| прогре�� | Проанализировано {i} из {n} · о�тало�ь ≈ {time} | Analysed {i} of {n} · ≈ {time} left | +| прогре��, коротко | {i} из {n} | {i} of {n} | +| прогре��, друга� база | В «{db}»: {i} из {n} | In «{db}»: {i} of {n} | +| о�тановить | О�тановить | Stop | +| под�казка о�тановить | О�тановить пои�к; разобранные партии �охран�т�� | Stop the search; the reviewed games are kept | +| о�танавливаю | О�танавливаю… | Stopping… | +| пропущено | , пропущено {k} ({reason}) | , {k} skipped ({reason}) | +| под�казка кнопки, в�ё разобрано | В�е {games} уже разобраны — показать итог (Shift+A) | All {games} are already reviewed: show the summary (Shift+A) | +| диалог, 3-� кнопка | Итог по разобранным ({k}) | Summary of the reviewed ({k}) | +| итог, заголовок | Итог · разобрано: {games} | Summary · reviewed: {games} | +| итог, заголовок при о�тановке | Пои�к о�тановлен · разобрано: {i} из {n} | Search stopped · reviewed: {i} of {n} | +| итог, игрок | Считают�� только ходы игрока «{name}»: белыми {w}, чёрными {b} | Only the moves of «{name}» are counted: as White {w}, as Black {b} | +| итог, игрок одним цветом | Считают�� только ходы игрока «{name}» белыми ({games}) / чёрными ({games}) | Only the moves of «{name}» as White ({games}) / as Black ({games}) are counted | +| итог, им� не найдено | В {k} парти�х игрок не найден по имени — их ходы не �читали�ь | The player's name was not found in {k} games: their moves were not counted | +| итог, не разобраны | �е разобраны: {k} ({reason}) | Not reviewed: {k} ({reason}) | +| итог, о�тали�ь | {k} партий не разобраны — «Продолжить» разберёт только их | {k} games are not reviewed: «Continue» reviews only them | +| итог, �тарые разборы | {k} из них разобраны прежними на�тройками движка | {k} of them were reviewed with the previous engine settings | +| итог, категории | Бле�т�щий / Замечательный / �еточно�ти / Ошибки / Зевки — ключи отчёта (`judgement_plural`) | Brilliant moves / Great moves / Inaccuracies / Mistakes / Blunders — the report's keys | +| итог, потер� | Средн�� потер� �антипешек | Average centipawn loss | +| итог, точно�ть | Средн�� точно�ть | Average accuracy | +| итог, под�казка точно�ти | Среднее по {k} парти�м: от {min}% до {max}% | Average of {k} games: {min}% to {max}% | +| итог, �пи�ок | Партии � !! ({n}) | Games with !! ({n}) | +| итог, под�казка �пи�ка | Щелчок — выбрать �троку в таблице, двойной щелчок — открыть на �том ходе | Click selects the row in the table; double-click opens at this move | +| итог, �крыта | Скрыта фильтром | Hidden by the filter | +| итог, только ! | Бле�т�щих ходов нет. Партии � ! — �ортировка по колонке «!!» | No brilliant moves. Games with ! — sort by the «!!» column | +| итог, ��ылка | От�ортировать | Sort | +| итог, ничего | Бле�т�щих и замечательных ходов нет | No brilliant or great moves | +| итог, кнопки | Продолжить / Открыть партию / Закрыть | Continue / Open game / Close | +| о�тановлен, 0 разобрано (то�т) | Пои�к о�тановлен: ни одна парти� не разобрана | Search stopped: no game was reviewed | +| зан�то, пои�к (Играть, пои�к ошибок дебюта) | Идёт пои�к замечательных ходов в «{db}»: {i} из {n} — дождите�ь или о�тановите его в библиотеке | Searching for great moves in «{db}»: {i} of {n}; wait or stop it in the library | +| ошибка движка | Движок о�тановил�� � ошибкой: {reason}. Разобрано {i} из {n} | The engine failed: {reason}. {i} of {n} reviewed | +| база изменила�ь | База «{db}» изменила�ь — пои�к о�тановлен. Разобрано {i} из {n} | «{db}» changed; the search stopped. {i} of {n} reviewed | +| �чейка, !! | Бле�т�щих ходов: {n} — {moves} | Brilliant moves: {n}: {moves} | +| �чейка, ! | Замечательных: {n} — {moves} | Great moves: {n}: {moves} | +| �чейка, · | Разобрана: бле�т�щих и замечательных ходов нет | Reviewed: no brilliant or great moves | +| �чейка, — | �е разбирает��: {reason} | Cannot be reviewed: {reason} | +| �чейка, у�тарел | Разбор прежними на�тройками движка | Reviewed with the previous engine settings | +| �чейка, идёт | Разбирает��… | Being reviewed… | +| меню �троки | Открыть на ходе {move} | Open at {move} | +| в партии во врем� прохода | Идёт пои�к замечательных ходов в «{db}»: {i} из {n}. О�тановить — в библиотеке | Searching for great moves in «{db}»: {i} of {n}. Stop it in the library | + +Чи�ла — � группировкой (`grouped`), «{games}» — `i18n::games(n)`. �овые ключи нужно добавить во в�е �зыки `i18n.rs`, а не только ru/en. «Замечательный» = «!», +«бле�т�щий» = «!!» (`decisions.md`). �нглий�кое «great» — как в отчёте («Great moves»). + +## 7. Критерии приёмки (дизайн-ревьюер — не автор кода) + +Окна — только через `scripts/dev/headless-run.sh`, профиль изолирован. Каждый пункт +подтверждает�� �нимком � указанием размера и �о�то�ни�. + +1. 1920×1080: ruy (49, без у�ловий) — кнопка активна; alekhin (267) — неактивна, �нимок + под�казки; Mega «carlsen, 2015–2026, ≥2600» (4 221) — неактивна, под�казка � «Сейча�: 4 221»; + Mega «…2025–2026, ≥2780» (62) — активна. **Верх таблицы и �трока заголовков на в�ех + �нимках на одной y**, вы�ота �троки у�ловий 22 px. +2. 960×600 (ru и en): три чипа + кнопка; три чипа + «Выбрано: 3 · Сн�ть» + кнопка (чипы + �вернули�ь в «+N ещё», кнопка на ме�те). Шапка базы не перене�ла�ь из-за 27. +3. Сери� по горизонтали: Ctrl+щелчок по 2-й �троке (по�вил�� �чётчик 42), �мена позиции на + до�ке (по�вил�� пор�док ходов) — **x кнопки не мен�ет��** (крайн�� �права). +4. Колонка «!!» видна на 1920 и 960 и в базе без единого значка. По�вление первого значка + (�ери� во врем� прохода, ≥ 3 �нимка) не мен�ет ширины колонок и положени� тек�та. +5. Значки читают�� в тёмной и �ветлой теме и в оттенках �ерого (`!!`, `!`, `·`, `—` различимы + по форме). �а выбранной �троке знак виден. +6. Сери� прохода (`CP_BRILLIANT_SLOW`): диалог → «�ачать» → 0 из N → �ередина → «О�танавливаю…» + → о�тановлено (итоговое окно E2); и запу�к → готово → итоговое окно E1. �а в�ех + �нимках: таблица не �двинута, поло�а прогре��а и «О�тановить» не дрожат по x при �мене + цифр (�равнить x «О�тановить» на двух �нимках). +7. Диалог: ширина и кнопки как у `chooser-ru.png`. Со�то�ние «Считаю…» не мен�ет вы�оту окна + (�нимок до и по�ле под�чёта). +8. Зан�тый движок: подготовка ищет ошибки → кнопка неактивна, под�казка; во врем� прохода + открыть партию → «�нализ партии» неактивна � под�казкой; вернуть�� (Ctrl+W) — фильтры, + прокрутка, выделение и прогре�� на ме�те. +9. Ошибка движка (`fake_uci` � падением): кра�ный тек�т на ме�те прогре��а, `×`, таблица на ме�те. +11. Итоговое окно (1920 и 960, ru/en): пор�док и цвета категорий �овпадают � отчётом партии + (�равнить � `docs/screenshots/review.png`); нули приглушены; �трока игрока е�ть только при + фильтре «Игрок»; �пи�ок > 6 �трок прокручивает��, окно не ра�тёт. Сери�: щелчок по �троке + �пи�ка → в таблице выбрана та же парти� и прокручена к ней (�нимок), окно на ме�те; + двойной щелчок → парти� на ходе !!, вкладка «Отчёт»; Ctrl+W → библиотека, окно закрыто, + парти� выбрана. Повторно «�айти» при в�ех разобранных → �разу окно, без диалога. + Варианты «только !» и «ничего» — по �нимку. +10. HiDPI (е�ли окружение позвол�ет, иначе пометить «не проверено»): «!!» в 28 px не обрезан, + �пиннер чёткий. + +## 8. Что передать те�тировщику + +- Лимит: ровно 100 — активна, 101 — неактивна; при изменении фильтра во врем� прохода + проход идёт по зафик�ированному �пи�ку. +- К�ш: парти�, разобранна� вручную, в проходе не пере�читывает�� (врем� ≈ 0, запро�ов к + движку нет) и �разу получает значок. У�таревший разбор (`SEARCH_VERSION`) не пере�читывает�� + (решение владельца). +- Игрок в фильтре: �уммы итога и значки — только по его ходам. Сверка вручную на 3 парти�х: + �уммы итога = �уммы �трок игрока в отчётах �тих партий. «белыми» / «чёрными» / «любым»; + парти� игрока � �амим �обой; напи�ание имени, не �овпавшее � фильтром. +- Итог без игрока = �умма обеих �торон по отчётам; �редн�� точно�ть = �реднее по �торонам. +- Во врем� прохода «Играть» и пои�к ошибок дебюта неактивны; по�ле окончани� — �нова активны. +- О�тановка: по�ле «О�тановить» проце��ов `stockfish` нет через ≤ 2 �; разобранные партии + е�ть в к�ше и индек�е по�ле перезапу�ка; недоразобранна� — без значка, без битого файла. + То же при kill программы во врем� прохода. +- Сохранно�ть: и�ходный PGN, `.cbv`/`.cbh` не мен�ют�� (sha256/mtime до и по�ле). В PGN �воих баз + ничего не допи�ывает��. +- Индек�: удаление партии из �воей базы (номера �двигают��) — значки у других партий не + «переезжают» на чужие �троки (проверка х�ша); внешнее изменение файла. +- Взаимои�ключение: проход ↔ подготовка ↔ «�нализ партии» ↔ живой анализ; проход в базе A, + кнопка в базе B. +- Chess960, партии без ходов, FEN � fullmove=0, учебный `--` — «—» � причиной, проход не падает. +- `[%eval]` в PGN: проход в�ё равно запу�кает движок, отметки �тав�т��. +- Shift+A в поле пои�ка печатает «A», а не запу�кает проход. + +## 9. Решени� владельца (2026-11-27) + +В�е п�ть вопро�ов прин�ты по рекомендации: +1. Кнопка работает только по фильтру, пункта дл� выделенных нет (§4.7). +2. Е�ли в фильтре задан игрок, �читают�� только его ходы (§4.3, §4.9). +3. Старый разбор за�читывает�� без пере�чёта (§4.3). +4. Фильтра «только � !!» нет, е�ть �ортировка по колонке «!!» (§4.3). +5. Игра � движком во врем� прохода запрещена, е�ть под�казка (§4.5). + +Дополнение — итоговое окно (§4.9). + +Открытых вопро�ов по итоговому окну нет. Решени� дизайнера, которые владелец может +пере�мотреть: +- фазовые точно�ти в окне не показывают��; +- в �пи�ке только !!, без !; +- отдельной кнопки «Итог» нет — итог открывает та же кнопка «�айти», когда в�ё разобрано. diff --git a/docs/design/task-27-selected-games-analysis-2026-11-27.md b/docs/design/task-27-selected-games-analysis-2026-11-27.md new file mode 100644 index 0000000..5b4112a --- /dev/null +++ b/docs/design/task-27-selected-games-analysis-2026-11-27.md @@ -0,0 +1,414 @@ +# Пакетный анализ вручную выделенных партий — ра�ширение задачи 27 + +Стату�: �пецификаци� дизайнера, 2026-11-27. Отно�ит�� к задаче 46 в `docs/dev/tasks.md`. +Код не мен�л��; реализаци� и визуальна� приёмка �тим документом не за�вл�ют��. Учтены решение +владельца (`docs/decisions.md:546-553`) и требовани� аналитика +`docs/research/task-27-selected-games-analysis-2026-11-27.md`, о�обенно §3.1, §6 и §8–10. + +Документ замен�ет только прежнее правило «кнопка работает только по фильтру» из §4.7 и §9 +`task-27-brilliant-search-2026-11-27.md`. О�тальные правила задач 27 и 42 �охран�ют��. + +## 0. Что по�мотрено в реальном интерфей�е + +Перед проектированием про�мотрены изображени�, а не только их названи�: + +- `designExample/�пи�ок баз и партий выбранной базы.png` и + `designExample/до�ка � панелью ходов и анализом движка.png` — и�ходные референ�ы: таблица и + чтение партии о�тают�� центром продукта; новую «dashboard»-компоновку не перено�им. +- `docs/screenshots/library.png` — главный �кран � фильтром: компактна� шапка, по�то�нна� �трока + у�ловий, плотна� виртуальна� таблица и права� панель. +- `docs/screenshots/game.png` и `docs/screenshots/review.png` — �кран партии и отчёт: обычные + тёмные поверхно�ти, �инее выделение, тек�товые `!!`/`!`; новые цвета и контейнеры не нужны. +- Реальные �нимки реализации `docs/qa/task-27-design/c-idle-ruy.png`, `c-sel-run.png`, + `c-run-series.png`, `c-dlg-cond.png`, `car-done.png`, `full-done.png`, `stopped.png` — кнопка и + прогре�� уже занимают один крайний правый �лот; �чётчик выделени� �тоит левее и не двигает + таблицу; диалог имеет ширину 520 px; итог и�пользует �уще�твующие �троки отчёта. +- Реальные �нимки задачи 42 `/tmp/opencode/rev42/s2/many.png`, + `/tmp/opencode/rev42/s/filter.png`, `/tmp/opencode/rev42/s2/prog.png` и + `/tmp/opencode/rev42/s2/game43.png` — выделение, �крытые фильтром запи�и, прогре�� и возврат в + партию и�пользуют уже прин�тую визуальную �и�тему. Измерени� и ограничени� �тих �нимков + зафик�ированы в `docs/qa/task-42-design-review-2026-11-27.md`. + +След�твие: мен�ют�� только выбор и�точника и тек�товые подпи�и �уще�твующих �лементов. До�ка, +нотаци�, колонка `!!`, �чётчик задачи 42, ширина окон и визуальные токены не перепроектируют��. + +## 1. Задача изменени� — одной фразой + +Пользователь запу�кает **тот же** пои�к `!!`/`!` либо по ручному выделению, е�ли оно е�ть, либо +по текущему фильтру, е�ли выделени� нет, и до запу�ка �вно видит �о�тав и ограничени� разбора. + +Приоритет информации: и�точник и допу�тимо�ть запу�ка → чи�ло выбранных и �крытых → правило +«только ходы игрока», е�ли оно активно → врем�/нагрузка → неизменный прогре�� и итог. + +## 2. Термины и неизменные правила и�точника + +- **N** — чи�ло уникальных запи�ей ручного выделени� задачи 42 (`marked`), включа� одну запи�ь. + Сам по �ебе кур�ор на невыделенной �троке не �оздаёт N. +- **F** — чи�ло запи�ей по�леднего полно�тью ра��читанного текущего `view`: фильтр, бы�трый пои�к + и пои�к по позиции вход�т �юда по прежним правилам. +- **k** — чи�ло выделенных запи�ей вне �того `view`: `k = N − |selection ∩ view|`. Сортировка не + делает запи�ь �крытой. +- **И�точник** — `selection` при N>0, `filter` при N=0. Объединени� `selection ∪ view` нет. +- Лимит примен�ет�� **до** и�ключени� к�шированных и неподдерживаемых запи�ей: N=1…100 либо + F=1…100. N=101 не откатывает�� даже к подход�щему F=1. + +**Очи�тка и возврат к фильтру.** Esc и �уще�твующа� ��ылка «Сн�ть» при N≥2 лишь �ворачивают +выделение к �троке кур�ора: о�таёт�� N=1, по�тому �ледующий запу�к в�ё ещё идёт по одной +выделенной партии. Полное N=0 даёт �уще�твующее переключение по�ледней запи�и — Ctrl+щелчок по +ней или Ctrl+Space на ней. Только по�ле N=0 во��танавливает�� filter-only. �овых же�тов и обещаний +«Esc вернёт фильтр» не вводим; поведение �амой ��ылки задачи 42 не мен�ем. + +## 3. Пользователь�кий путь и �охранение контек�та + +1. Пользователь выдел�ет A, B и C, затем мен�ет фильтр так, что B и C �крыты. Суще�твующий + �чётчик показывает «Выбрано: 3 (2 �крыто фильтром) · Сн�ть»; кнопка `!!` о�таёт�� на ме�те. +2. Щелчок по кнопке или Shift+A открывает прежний диалог, но его и�точник �вно гла�ит + «Выбрано: 3 партии», отдельно «2 �крыто текущим фильтром». �евыделенна� видима� D не + добавл�ет��. При активном у�ловии «Игрок» зде�ь же видно правило только его ходов (§6). +3. «�ачать» запу�кает показанный набор. По�ле �того можно изменить выделение, фильтр и �ортировку, + открыть партию и вернуть�� Ctrl+W: текущее выделение и прокрутка ведут �еб� как прежде, а + �о�тав и пор�док идущего прохода не мен�ют�� (§7). +4. Завершение/о�тановка открывает �уще�твующий итог по �нимку запу�ка. «Продолжить» отно�ит�� к + о�тавшим�� запи��м того же �нимка, не к новому выделению. +5. Повторный вызов при том же �о�таве и�пользует к�ш; е�ли новой работы нет, �разу открывает�� + итог без пред�тартового диалога и без запу�ка Stockfish. + +Чтобы до «�ачать» заменить показанный в диалоге �о�тав, пользователь нажимает «Отмена» и вызывает +команду повторно по�ле изменени� выделени�. Диалог не подмен�ет �вой �о�тав молча (§7.1). + +## 4. Одна кнопка: �о�то�ни�, disabled и tooltip + +### 4.1. Общие правила + +- Вид, тек�т и ме�то кнопки не мен�ют��: `!! �айти замечательные ходы` либо �уще�твующа� коротка� + форма `!! �айти ходы`. Чи�ло и �лово «выделенных» **в �аму кнопку не добавл�ют��**: �то �охран�ет + ширину �лота. И�точник различён тек�том под�казки и диалога, не цветом. +- Сначала дей�твуют �уще�твующие блокировки engine job/прохода в другой базе. Во врем� �воего + прохода вме�то кнопки — �уще�твующий прогре��, при о�тановке — «О�танавливаю…». +- Е�ли новый фильтр ещё �читает��, до�товерного k ещё нет. При N=1…100 кнопка временно неактивна: + `Подождите — �читаю, �колько выделенных партий �крыто текущим фильтром`. + Это ожидание только ради че�тного k, а не зави�имо�ть �о�тава или лимита от F. При N>100 причина + переполнени� изве�тна �разу и имеет приоритет над ожиданием k. При N=0 о�таёт�� прежнее + `Подождите — партии ещё отбирают��`. +- �еактивна� кнопка и�пользует �уще�твующий `on_disabled_hover_text`. Shift+A вне пол� ввода при + той же блокировке показывает то�т � **тем же тек�том причины**. В поле ввода Shift+A печатает `A`. + +### 4.2. Матрица приоритета (фильтр уже ра��читан, движок �вободен) + +| N | F | Кнопка и и�точник | Что об�зано произойти | +|---:|---:|---|---| +| 0 | 0 | disabled, фильтр | Прежнее `�ет партий по �тим у�лови�м` | +| 0 | 1…100 | активна, фильтр | Прежний filter-only диалог по в�ем F | +| 0 | >100 | disabled, фильтр | Прежние две �троки `Отфильтруйте партии, чтобы их было не больше 100` / `Сейча�: {F}` | +| 1 | 0 | **активна, выделение** | Диалог N=1, k=1; анализирует�� �крыта� запи�ь. Пу�та� видима� выдача не �крывает команду | +| 1 | >100 | **активна, выделение** | Диалог N=1, k=0; большой F не блокирует допу�тимое выделение | +| 2…100 | 0 | **активна, выделение** | В�е N �крыты и в�е вход�т; k=N | +| 2…100 | 1…100 | **активна, выделение** | �нализируют�� только выделенные; видимые невыделенные запи�и F не добавл�ют�� | +| 100 | >100 | **активна, выделение** | Ровно 100 допу�тимо; большой F игнорирует�� как и�точник | +| 101 и больше | 0 | disabled, выделение | Причина по N, а не «нет партий по у�лови�м» | +| 101 и больше | 1…100 | disabled, выделение | Подход�щий F **не подмен�ет** �лишком большое выделение | +| 101 и больше | >100 | disabled, выделение | Одна причина по N; вторую ошибку про F не нагромождаем | +| �тало 0 | любой готовый F | �нова правила N=0 | Полное переключение по�ледней запи�и возвращает прежний filter-only | + +�епу�та� база � F=0 и N>0 �охран�ет �троку у�ловий и до�тупную кнопку. Полно�тью пу�та� база без +выделени� �охран�ет �уще�твующий �кран «�ет партий». + +### 4.3. Точные короткие под�казки дл� selection + +**�ктивна, N=1…100:** + +```text +Выбрано: {games}. Разобрать их движком и отметить !! и ! (Shift+A) +``` + +Втора� �трока при k>0: + +```text +Скрыто текущим фильтром: {k}; �ти партии тоже вход�т. +``` + +При k=0 вме�то неё: + +```text +Фильтр не мен�ет �о�тав �того запу�ка. +``` + +Зде�ь `{games}` — �уще�твующее `i18n::games(N)`, например «1 парти�», «3 партии», «100 партий». +Дл� filter-only активна� под�казка о�таёт�� прежней: +`Разобрать движком {games} и отметить найденные !! и ! (Shift+A)`. + +**Disabled, N>100 — дл� любого F:** + +```text +Выбрано: {games} — больше 100. +О�тавьте не больше 100 выделенных; фильтр не и�пользует��. +``` + +Эта под�казка намеренно не предлагает Esc как «полную очи�тку»: по�ле Esc о�танет�� N=1. При N=1 +под�казка о�обенно важна, потому что по�то�нного �чётчика «Выбрано: 1» по правилам задачи 42 нет. + +## 5. Макет �троки у�ловий — без нового �лемента + +```text +[у�лови�…] [Выбрано: N (k �крыто фильтром) · Сн�ть] [пор�док ходов] [!! �айти замечательные ходы] + ↑ прежний крайний �лот +``` + +- Суще�твующий `right_slot` не мен�ет ни ширины, ни положени� при �мене `filter → selection`, + по�влении k, переходе `кнопка → прогре�� → кнопка`, ошибке или итоге. +- Строка у�ловий о�таёт�� вы�отой **22 логиче�ких px**. Верх таблицы, вы�ота её заголовка и �троки + не �двигают��. Счётчик задачи 42 по-прежнему может отнимать ме�то у чипов у�ловий, но не мен�ет + вы�оту и не двигает крайний правый �лот. +- �овых кнопок, выпадающего меню и�точника, переключател� «фильтр/выделение», второй панели или + отдельного пункта контек�тного меню нет. + +## 6. Пред�тартовый диалог + +### 6.1. Selection-макет + +Тот же `egui::Window`, ширина �одержимого 520 px, заголовок, фон, кнопки и от�тупы �уще�твующего +диалога. Пример �огла�ованного �чёта: N=12, k=9, к�шировано 3, новых 8, пропущено 1. + +```text +┌──────────────────────────────────────────────────────────────� +│ �айти замечательные ходы │ +│ Mega Database 2026 · Выбрано: 12 партий │ � weak 12 px +│ 9 �крыто текущим фильтром │ � weak 12 px, только k>0 +│ Считают�� только ходы игрока «carlsen magnus». │ � 12 px обычным тек�том, е�ли задан игрок +│ │ +│ Движок разберёт 8 партий — примерно 4 минуты. │ +│ 3 уже разобраны: их отметки возьмут�� из �охранённого разбора.│ +│ 1 нельз� разобрать (пу�той ход в о�новной линии) │ � weak, е�ли е�ть пропу�ки +│ │ +│ Компьютер будет загружен (до 8 проце��ов Stockfish 19). │ +│ Работать � программой можно; о�тановить — в любой момент, │ +│ разобранные партии �охран�т��. │ +│ [Итог по разобранным (3)] [Отмена] [�ачать] │ � треть� кнопка по прежнему правилу +└──────────────────────────────────────────────────────────────┘ +``` + +Дл� N=1 перва� �трока — `… · Выбрано: 1 парти�`; при k=1 — `1 �крыто текущим фильтром`. �е пи�ать +в selection-варианте «{F} по у�лови�м» или «в�е партии базы»: �то �оздало бы впечатление разбора +в�его фильтра. �евыделенные запи�и фильтра нигде не прибавл�ют�� к N. + +### 6.2. Player-only должен быть заметен до запу�ка + +Суще�твующее решение владельца не мен�ет��: е�ли в **у�ловии «Игрок»** задан игрок, в отметках и +итоге учитывают�� только его ходы; бы�трый пои�к по имени �ам по �ебе �то правило не включает. +Дл� произвольного выделени� �то о�обенно важно: парти� о�таёт�� в проходе даже е�ли игрока в ней +нет, но её ходы тогда не за�читывают��. + +По�тому в selection-диалоге добавл�ет�� одна тек�това� �трока того же �мы�ла, что в итоге: + +- любой цвет: `Считают�� только ходы игрока «{name}».`; +- ограничение цветом: `Считают�� только ходы игрока «{name}» белыми.` / `… чёрными.`. + +Она и�пользует обычный `text_color`, 12 px, без значка и нового цвета; weak зде�ь недо�таточно дл� +един�твенного предупреждени� о неочевидном ограничении. Tooltip �троки: +`У�ловие игрока ограничивает �читаемые ходы, но не и�ключает выбранные партии из разбора.` +В итоге �охран�ет�� �уще�твующа� подробна� weak-�трока � чи�лом �торон; новой политики и отдельного +предупреждени�-то�та нет. + +### 6.3. Filter-only и по�то�нна� геометри� + +- Перва� �трока filter-only о�таёт�� прежней: `{db} · {games} по у�лови�м: {list}` / по позиции / + `… · в�е партии базы` � �уще�твующим и�правленным разделителем. +- Под и�точник резервирует�� **три одинаковые тек�товые �троки** дл� обоих и�точников: (1) база и + �о�тав, (2) ме�то дл� k, (3) ме�то дл� player-only. Пу�тые зарезервированные �троки ничего не + ри�уют. По�тому `filter ↔ selection`, k=0/k>0 и наличие игрока не мен�ют вы�оту �ледующего + открыти� диалога и не �двигают его �одержимое по�ле открыти�. +- �иже �охран�ет�� �уще�твующа� зарезервированна� зона под «Считаю…»/врем�/к�ш/пропу�ки. Спиннер и + готовые чи�ла по-прежнему не мен�ют вы�оту окна. Предупреждение о нагрузке и кнопки не двигают��. +- N, k и player-scope изве�тны �инхронно из �нимка при открытии; они не по�вл�ют�� позже в�лед за + фоновым под�чётом к�ша. «�ачать» неактивна только до готовно�ти �уще�твующего под�чёта разборов. +- Enter — «�ачать» по�ле готовно�ти, Esc — «Отмена». Предложение у�тановить Stockfish 19 и в�е + �уще�твующие у�лови� запу�ка �охран�ют��. + +## 7. Snapshot и по�ледующие изменени� выделени� + +### 7.1. От показанного диалога к запу�ку — без �крытой подмены + +1. По�ле готовно�ти `view` команда �оздаёт **черновой �нимок**: база/fingerprint, и�точник, + �об�твенна� копи� упор�доченных ID, N, k, �ортировка и фильтр/player-scope. Дл� selection + пор�док — текущий компаратор таблицы дл� в�ех выбранных, включа� �крытые, � tie-break по номеру + запи�и, как в задаче 42. Дл� filter — �уще�твующий пор�док `view`. +2. Пред�тартовый диалог показывает именно �тот черновой �нимок. Изменени� таблицы за открытым + окном не запу�кают фоновых пере�чётов и не мен�ют его молча. Дл� нового �о�тава нужны «Отмена» + и повторный вызов; так N/k/оценка никогда не опи�ывают один набор, а «�ачать» запу�кает другой. +3. «�ачать» фик�ирует **тот же** �нимок как snapshot прохода. Повторного чтени� живого `marked`, + `view`, �ортировки или фильтра в �тот момент нет. При немедленном полно�тью к�шированном итоге + snapshot команды �разу �тановит�� snapshot итога. + +### 7.2. Во врем� прохода + +По�ледующие Ctrl+щелчок, Ctrl+Space, Ctrl+A, Esc, �мена фильтра/позиции/�ортировки: + +- мен�ют только текущую таблицу, рамку кур�ора и �уще�твующий �чётчик задачи 42; +- **не** добавл�ют/удал�ют запи�и, не мен�ют их пор�док, знаменатель прогре��а, player-scope, + оценку о�тавшего�� времени по и�ходной очереди и будущий итог; +- не запу�кают второй проход и не отмен�ют и�ходную запи�ь, �н�тую из текущего выделени�. + +Видимый тек�т прогре��а не ра�шир�ет��: + +```text +!! Проанализировано {i} из {M} · о�тало�ь ≈ {time} [поло�а] О�тановить +``` + +Зде�ь M — �уще�твующее чи�ло анализируемых запи�ей snapshot, включа� вз�тые из к�ша и и�ключа� +заранее пропущенные как неподдерживаемые. По�тому M может быть меньше N/F; �уще�твующа� �трока +«{k} нельз� разобрать» объ��н�ет разницу. Лимит 100 при �том уже проверен по и�ходным N/F. + +Tooltip прогре��а дл� selection: + +```text +И�точник: выбранные {games}; �крыто фильтром при запу�ке: {k}. +Изменени� выделени� и фильтра не мен�ют �тот проход. +``` + +При k=0 первое предложение — `И�точник: выбранные {games}.` Далее �охран�ют�� �уще�твующие полный +прогре�� и текуща� парти�. «О�тановить» и кра�на� ошибка и�пользуют тот же зафик�ированный M. + +По�ле завершени� до�тупно�ть кнопки заново вычи�л�ет�� по **текущим** N/F. Это не мен�ет уже +открытый итог �тарого snapshot. + +## 8. Итог, о�тановка и повторный запу�к из к�ша + +- Компоновка �уще�твующего итогового окна не мен�ет��. В selection-варианте его weak-подзаголовок: + `{db} · Выбрано: {games}`. Он не �одержит F и не называет набор «парти�ми по у�лови�м». + Tooltip подзаголовка при k>0 добавл�ет `Скрыто фильтром при запу�ке: {k}`; отдельной новой + �троки и изменени� вы�оты итога нет. +- Следующа� �уще�твующа� �трока про игрока о�таёт�� видимой: `Считают�� только ходы игрока + «{name}»: белыми {w}, чёрными {b}` либо её вариант одного цвета. Она отно�ит�� к snapshot, + а не к новому фильтру, выбранному по�ле запу�ка. +- Заголовки «Итог · разобрано…» / «Пои�к о�тановлен · разобрано…», �уммы, �пи�ок `Партии � !!`, + навигаци� и кнопки �охран�ют��. Изменение текущего выделени� не перепи�ывает �тот итог. +- «Продолжить» получает только `rest` и�ходного snapshot, и�ходные пор�док/about/player-scope. + Оно допу�тимо, даже е�ли пользователь уже выделил другие запи�и или текущее N>100: �то �вное + продолжение показанного �тарого прохода, не новый анализ текущего выделени�. +- Уже разобранные запи�и, включа� разбор прежними на�тройками, не пере�читывают��. При �мешанном + к�ше диалог показывает прежние чи�ла «уже разобраны»/«движок разберёт», движок получает только + `left`. Е�ли `left` пу�т, пред�тартовый диалог пропу�кает�� и �разу открывает�� итог; новых + проце��ов Stockfish быть не должно. +- Повторный вызов по�ле изменени� выделени� �оздаёт **новый** snapshot и заново провер�ет к�ш дл� + него; он не должен незаметно показать �тарый итог как итог нового �о�тава. + +## 9. О�тальна� матрица �о�то�ний + +| Со�то�ние | Требование | +|---|---| +| Счётчик к�ша в диалоге | Прежний «Считаю, �колько партий уже разобрано…» �о �пиннером; N/k/player уже видимы, вы�ота не мен�ет�� | +| Ошибка движка | Прежний кра�ный тек�т и `×` в том же правом �лоте; разобранное и �о�тав snapshot �охран�ют�� | +| База изменила�ь | Прежн�� о�тановка и защита record ID; позднее �н�тие текущего выделени� не мен�ет тек�т/итог завершённой ча�ти | +| F=0, но е�ть �крытое N≤100 | Команда до�тупна и запу�кает N; ранний выход «нет видимых партий» запрещён | +| В�е запи�и пропущены | Суще�твующий итог � причинами; фиктивный запу�к движка не нужен | +| Больша� база | N и k и�пользуют �уще�твующие к�шированные �чётчики; N≤100 не требует анализа в�его F. Чи�ла группируют�� пробелами | +| �е�охранённые изменени� | �овых �о�то�ний нет: анализ не пишет и�ходные PGN/ChessBase и не мен�ет �уще�твующие вопро�ы редактора | +| Узкое окно | Суще�твующие коротка� кнопка, �ворачивание чипов и truncation tooltip; новых перено�ов �троки у�ловий нет. Отдельный �нимок по правилу �кономии не нужен | +| HiDPI | Только �уще�твующий тек�т/egui-виджеты; новых ра�тровых ре�ур�ов нет. Логиче�кие 22 px и размеры шрифтов неизменны | +| Светла� тема | Цвета не ввод�т�� и не мен�ют��; отдельна� визуальна� проверка не нужна | + +## 10. Клавиатура, фоку� и до�тупно�ть + +| Клавиша | Поведение | +|---|---| +| Shift+A вне пол� ввода и других окон | Тот же resolver и�точника, что у кнопки; при disabled — то�т � той же причиной | +| Tab / Shift+Tab | Суще�твующий пор�док: кнопка пои�ка, «О�тановить», затем �лементы диалога/итога. �овых focusable-�лементов нет | +| Enter в готовом диалоге | «�ачать» показанный snapshot | +| Esc в диалоге | «Отмена», без запу�ка | +| Esc при N≥2 в библиотеке | Как прежде, �ве�ти к N=1; **не** обещать filter-only и не о�танавливать проход | +| Ctrl+Space на по�ледней выделенной запи�и | Переключить её в N=0; �ледующий вызов �нова и�пользует F | +| Ctrl+A / Shift+диапазон во врем� прохода | Мен�ют только �ледующее текущее выделение, не snapshot идущего прохода | +| Enter / ↑ / ↓ / Esc в итоге | Без изменений | + +Рамка фоку�а egui, заливка выбранной �троки и отдельна� рамка кур�ора �охран�ют��. Selection-и�точник, +�крытые запи�и, переполнение и player-only объ��н�ют�� �ловами, а не только приглушением/цветом. +Тултипы не �вл�ют�� един�твенным ме�том критичной информации: N/k/player-only об�зательно видны в +пред�тартовом диалоге. + +## 11. Требовани� разработчику + +1. **Единый resolver** дл� кнопки и Shift+A: N>0 → selection, N=0 → filter. �е и�пользовать порог + N≥2 и не делать fallback N>100 → F. При N>0,F=0 не �рабатывает ранний return пу�той таблицы. +2. **До�товерный k.** Снимок �оздаёт�� только по завершённому актуальному `view`; ожидание показано + �о�то�нием §4.1. �ельз� под�тавл�ть k=0 по неизве�тному значению. k �читает�� по ID запи�ей, не + по видимым номерам �трок или �ортировке. +3. **Соб�твенный snapshot.** Передать в �уще�твующие `StartDialog` → `PassJob` → stopped/summary / + «Продолжить» �об�твенную копию ID, пор�дка, и�точника/N/k, fingerprint и player-scope. Живой + `marked`/`view` в фоновом проходе дл� изменени� �о�тава не читать. Черновой �нимок диалога и + запу�каемый �пи�ок об�заны �овпадать запи�ь в запи�ь. +4. **Player-only без потери �крытых запи�ей.** Дл� каждого ID selection-snapshot �тороны игрока + определ�ют�� тем же �опо�тавлением имени и `Side`, что в дей�твующем фильтре. �ельз� получать их + только пере�ечением � полным результатом `db.query(filter)`: �крыта� по году/Elo/другому у�ловию + выбранна� парти� в�ё равно должна получить �тороны P. От�ут�твие P в запи�и ведёт к �уще�твующему + `player_missing`, а не к и�ключению запи�и. Без у�лови� «Игрок» �читают�� обе �тороны. +5. **Переи�пользование.** �е дублировать алгоритм разбора, к�ш, очередь, окна и индек� отметок. + Суще�твующие `count`, к�ш (включа� stale), `PassJob`, о�тановка, atomic-save, ошибки и итог + работают над snapshot из другого и�точника без второго «ма��ива анализа». +6. **UI.** �е мен�ть ширину `right_slot`, �троку 22 px и �чётчик/копирование задачи 42. В диалоге + выделить фик�ированные три �троки и�точника (§6.3), �охранить �уще�твующую зону под�чёта и + предупреждение. В итоге мен�ет�� только тек�т �уще�твующего подзаголовка/tooltip. +7. **Тек�ты.** Добавить новые ключи во в�е �зыки �уще�твующего `i18n.rs`, не только ru/en; + и�пользовать `i18n::games` и `grouped`. �е мен�ть тек�т «Сн�ть»/Esc так, будто они дают N=0. +8. **Отладочна� провер�емо�ть.** И�пользовать �уще�твующие `CP_SELECT`, `CP_FILTER_PLAYER`, + `CP_SEARCH`, `CP_KEYS`, `CP_BRILLIANT_SLOW`, `CP_BRILLIANT_STOP_AFTER`. Е�ли ими нельз� �н�ть + disabled-tooltip или изменить selection **по�ле** �тарта, добавить минимальные debug-хуки дл� + �того и журнал ID/вызовов движка; пользователь�ких кнопок и �и�темной �мул�ции ввода не нужно. + +## 12. �езави�имому reviewer и tester + +### 12.1. Минимальна� визуальна� приёмка — только 1920×1080, тёмна� тема, ру��кий UI + +Reviewer — не автор �той �пецификации и не автор реализации. Запу�к только через +`scripts/dev/headless-run.sh`, изолированный профиль. Сравнение � главным �краном и партией — по +�уще�твующим реальным `docs/screenshots/library.png`, `game.png`, `review.png` и �нимкам QA27/42; +новые размеры, �ветла� тема и новый �нимок партии без найденного дефекта не нужны. + +До�таточно четырёх доказательных �о�то�ний; каждый вердикт �опровождает�� файлом, размером и +�о�то�нием, а не фразой «в�ё ровно»: + +1. **Библиотека, N=3, k=2, активный игрок P.** Видны выделенные �троки/рамка кур�ора, один �чётчик, + одна кнопка в прежнем правом �лоте. Зафик�ировать y �троки у�ловий/верха таблицы и x �лота. +2. **Пред�тартовый диалог того же �о�то�ни�.** Одновременно читаемы «Выбрано: 3 партии», + «2 �крыто текущим фильтром», player-only, оценка времени, нагрузка и «�ачать». По�ле закрыти� + ра�кладка за окном �овпадает � кадром 1, �двиг таблицы **0 px**; внутри диалога по�вление + готового под�чёта не мен�ет вы�оту. +3. **N=101 при F≤100.** Кнопка видна в том же �лоте и неактивна; tooltip �одержит именно причину + по выделению и не обрезан. Е�ли разрешённым хуком hover �н�ть нельз�, визуальный пункт + пометить «не проверено»; тек�т отдельно проверить через Shift+A, а не выдать PASS по коду. +4. **Идущий selected-проход по�ле изменени� selection/filter.** Видны �тарый знаменатель прогре��а + и уже другой текущий �чётчик. Против кадра 1 �трока у�ловий о�таёт�� 22 px, верх таблицы — + **0 px**, правый �лот — тот же; поло�а и «О�тановить» не дрожат по x при �мене цифр. + +Итог визуально не пере�матривать, е�ли изменил�� только тек�т �уще�твующего подзаголовка: его +�о�тав провер�ет�� функционально. �овый �нимок итога нужен только при изменении layout или дефекте. +Любой дефект запи�ывать � ме�том, ожидаемой/фактиче�кой координатой и шагами во�произведени�. + +### 12.2. Функциональный чек-ли�т tester + +Полный об�зательный набор — `docs/research/task-27-selected-games-analysis-2026-11-27.md` §5, +Ф1–Ф11. О�обо не потер�ть: + +- границы 0/1/100/101 дл� обоих и�точников и обе конфликтные пары `F>100,N≤100` / `N>100,F≤100`; +- N=1,k=1 при F=0; Esc→N=1 о�таёт�� selection, �ледующий Ctrl+Space→N=0 возвращает filter-only; +- точное �овпадение показанных N/k и журнала запущенных ID, включа� пор�док �крытых запи�ей; +- изменение selection/filter/sort по�ле «�ачать» и по�ле о�тановки: неизменные проход, итог и + «Продолжить» и�ходного `rest`; нова� выбранна� X не вызывает�� движком; +- к�ш: �мешанный запу�к �читает только `left`; повтор в�ех готовых — ноль новых проце��ов и + неизменные файлы к�ша; �тарый разбор за�читывает��; +- player-only дл� видимой и �крытой запи�и, цвета «белыми/чёрными/любым», P от�ут�твует в запи�и, + �мена P→Q по�ле �тарта не мен�ет итог; бы�трый пои�к имени не включает player-only; +- до�товерный k во врем� пере�чёта фильтра: никакого молчаливого k=0; disabled tooltip и то�т + Shift+A �овпадают; +- ошибка/о�тановка/закрытие: проце��ы завершают�� по �уще�твующему таймауту, готовый к�ш читает�� + по�ле перезапу�ка, и�ходные PGN/ChessBase �охран�ют sha256/mtime; +- анализ не мен�ет «�ова� база из выбранных»: N=101 запрещает только анализ, копирование задачи 42 + и полные PGN-деревь� не затронуты; +- legacy CP1251/CP1252, fullmove=0, �тарт чёрных, учебный `--`, RAV/комментарии/NAG, повтор + позиции, `[%eval]`, Chess960/нечитаема� запи�ь дают тот же результат, что filter-only. + +## 13. Явно вне объёма + +�ова� кнопка или меню выбора и�точника; объединение фильтра и выделени�; отдельна� очередь/окно +дл� selection; новый фильтр `только � !!`; изменение порогов разбора и правил `!!`/`!`; изменение +копировани� задачи 42, Esc/«Сн�ть», до�ки, нотации, колонки `!!`, цветов, и�ходных PGN и политики +player-only. diff --git a/docs/design/task-27/A-header-1920.png b/docs/design/task-27/A-header-1920.png new file mode 100644 index 0000000..f11bf5d Binary files /dev/null and b/docs/design/task-27/A-header-1920.png differ diff --git a/docs/design/task-27/B1-ruy-1920-idle-badges.png b/docs/design/task-27/B1-ruy-1920-idle-badges.png new file mode 100644 index 0000000..902763e Binary files /dev/null and b/docs/design/task-27/B1-ruy-1920-idle-badges.png differ diff --git a/docs/design/task-27/B2-mega4221-1920-disabled.png b/docs/design/task-27/B2-mega4221-1920-disabled.png new file mode 100644 index 0000000..7f3d3bc Binary files /dev/null and b/docs/design/task-27/B2-mega4221-1920-disabled.png differ diff --git a/docs/design/task-27/B3-mega62-1920-running.png b/docs/design/task-27/B3-mega62-1920-running.png new file mode 100644 index 0000000..f2cf008 Binary files /dev/null and b/docs/design/task-27/B3-mega62-1920-running.png differ diff --git a/docs/design/task-27/B4-mega62-960-running.png b/docs/design/task-27/B4-mega62-960-running.png new file mode 100644 index 0000000..7ec08f2 Binary files /dev/null and b/docs/design/task-27/B4-mega62-960-running.png differ diff --git a/docs/design/task-27/B5-mega62-960-idle.png b/docs/design/task-27/B5-mega62-960-idle.png new file mode 100644 index 0000000..ed0d300 Binary files /dev/null and b/docs/design/task-27/B5-mega62-960-idle.png differ diff --git a/docs/design/task-27/C-filters-footer-1920.png b/docs/design/task-27/C-filters-footer-1920.png new file mode 100644 index 0000000..89db388 Binary files /dev/null and b/docs/design/task-27/C-filters-footer-1920.png differ diff --git a/docs/design/task-27/D-dialog-1920.png b/docs/design/task-27/D-dialog-1920.png new file mode 100644 index 0000000..db45fc3 Binary files /dev/null and b/docs/design/task-27/D-dialog-1920.png differ diff --git a/docs/design/task-27/E1-summary-1920.png b/docs/design/task-27/E1-summary-1920.png new file mode 100644 index 0000000..1b14285 Binary files /dev/null and b/docs/design/task-27/E1-summary-1920.png differ diff --git a/docs/design/task-27/E2-summary-960-stopped.png b/docs/design/task-27/E2-summary-960-stopped.png new file mode 100644 index 0000000..92a1719 Binary files /dev/null and b/docs/design/task-27/E2-summary-960-stopped.png differ diff --git a/docs/design/tasks-42-43-2026-11-27.md b/docs/design/tasks-42-43-2026-11-27.md new file mode 100644 index 0000000..9e66779 --- /dev/null +++ b/docs/design/tasks-42-43-2026-11-27.md @@ -0,0 +1,503 @@ +# Задачи 42 и 43: выделение не�кольких партий → нова� база; обнаруживаемо�ть �трелок + +Стату�: �пецификаци� дизайнера, 2026-11-27, ветка `feature/starter-repertoires`. Код не мен�л��. +О�нова: аудит `docs/research/tasks-42-43-audit-2026-11-27.md`, решени� владельца от 2026-11-27, +переданные орке�тратором (ниже — «решение владельца»), и �нимки текущего HEAD (`3cad881`). + +## 0. И�ходные �нимки (текущий HEAD, 1920×1080 и 960×600, headless-run, изолированный профиль) + +Профиль `/tmp/opencode/d4243/{cfg,cfg2,data}`, базы — копии `The Ruy Lopez - Move by Move.pgn` +(49, windows-1252), `Alekhin.pgn` (267) и `shapes.pgn` (1 парти� �о �трелками и кругами). +Каталог �нимков: `/tmp/opencode/d4243/s/`. Файл `shapes.pgn` по�ле в�ех запу�ков не изменил�� +(sha256 `242c86e4…5239f`). + +| Снимок | Размер | Что видно и что из �того �ледует | +|---|---|---| +| `lib-ru.png` | 1920×1080 | Таблица базы без выделени�. Под шапкой е�ть **по�то�нна� �трока у�ловий** вы�отой 22 px: «У�ловий нет — показаны в�е партии». Строка е�ть и без фильтров, по�тому в неё можно по�тавить �чётчик выделени�, и таблица не �двинет��. | +| `lib-sel-ru.png` | 1920×1080 | Одна выбранна� �трока (№ 3) — �плошна� заливка `selection.bg_fill` по в�ей ширине; ✓ «про�мотрено» �тоит в колонке №. | +| `lib-960-en.png` | 960×600 | Узкое окно: таблица 680 px, �трока у�ловий на ме�те, колонки �окращены до «Year». | +| `chooser-ru.png` | 1920×1080 | Диалог «Добавить в базу»: подзаголовок «Berg, E. — Rudd, J.», �пи�ок �воих баз, «➕ �ова� база…», «Сохранить как файл…», «Отмена / Добавить». Пакетный режим �троит�� на �том же диалоге. | +| `newbase-ru.png` | 1920×1080 | Диалог «�ова� база»: «�азвание», «Файл: …/ChessPenguin/», «Изменить папку…», «Отмена / Создать». | +| `game-shapes-ru.png` | 1920×1080 | Парти� на ходе 1…e5 � `[%cal Gg1f3,Gf1c4]`: на до�ке две зелёные �трелки, а в нотации у `e5` **никакого признака** нет. | +| `game-shapes-en.png` | 1920×1080 | Ход 7.Qb3 � двум� кра�ными �трелками: в нотации признака тоже нет. Вариант `7…Qd7 8.Qxb7` � `[%csl Ga8]` тоже без признака. | +| `game-960-en.png` | 960×600 | Узкий �кран партии: до�ка вплотную к панели, �вободных полей у до�ки нет; панель кнопок перено�ит�� на вторую �троку (так было и раньше). | +| `settings-board-ru.png` | 1920×1080 | «�а�тройки › До�ка и фигуры» — разделы «�абор фигур», «Запи�ь ходов», «До�ка»; про �трелки ничего нет. | + +--- + +# Задача 42. �е�колько партий → нова� база + +## 42.1. Задача �крана (одной фразой) + +В таблице базы пользователь �обирает произвольный набор партий и одной командой получает из +них новую базу. Важно�ть информации: какие �троки выбраны → �колько их, в том чи�ле невидимых +при текущем фильтре → идёт ли запи�ь и чем она кончила�ь. + +## 42.2. Путь пользовател� и �охранение контек�та + +1. Библиотека → база «ruy» → щелчок по № 3, Ctrl+щелчок по № 7 и № 15. В �троке у�ловий + �права по�вл�ет�� «Выбрано: 3 · Сн�ть». +2. Права� кнопка по любой выбранной �троке → «�ова� база из выбранных…» (или Ctrl+Shift+S → + пакетный диалог «Добавить в базу: 3 партии» → «➕ �ова� база…»). +3. Диалог «�ова� база» � подзаголовком «Из выбранных: 3 партии из «ruy»» → название + «Подборка» → «Создать и �копировать». +4. Запи�ь идёт в фоне. В �троке у�ловий на ме�те �чётчика видна �трока прогре��а + «Запи�ь в «Подборка»: 1 из 3 ▕██░░� Отменить». Таблицу можно ли�тать, партии — открывать. +5. Итог — то�т «Подборка: �копировано 3, пропущено 0» � кнопкой «Открыть». �а полке по�вл�ет�� + карточка «Подборка». **Пользователь о�таёт�� в и�ходной базе**: фильтры, �ортировка, + прокрутка и выделение те же. «Открыть» переключает полку на новую базу. +6. Возврат из партии (Ctrl+W / «� Библиотека») приводит к той же таблице � тем же выделением. + +И�ходна� база только читает�� (решение владельца). Файл и�точника не открывает�� на запи�ь ни +на каком шаге. + +## 42.3. Компоновка и обо�нование + +�овых панелей нет. Добавл�ют�� три вещи в уже �уще�твующие ме�та. + +``` +┌ шапка базы ──────────────────────────────────────────────────────────────────────────────� +│ ruy · PGN, кодировка windows-1252 · 49 партий [� Пои�к…] [Фильтры][До�ка]│ +├ �трока у�ловий (22 px, е�ть в�егда) ─────────────────────────────────────────────────────┤ +│ У�ловий нет — показаны в�е партии Выбрано: 3 · Сн�ть │ � �чётчик �права +├──────────────────────────────────────────────────────────────────────────────────────────┤ +│ № ▲ Белые Elo Чёрные Elo Рез. Длина ECO 💬 Турнир Тур Дата │ +│ 1 Carlsen, M. Topalov, V. 1-0 32 C84 … Nanjing 2010 │ +│ 2 McDonald, N. Savage, B. 1-0 55 C84 … British League 2011 │ +│ ✓ 3 Berg, E. Rudd, J. 1-0 30 C78 … Liverpool 2007 │ � выбрано (заливка) +│ 4 … │ +│ 7 Gashimov, V. Kramnik, V. 1-0 39 C65 … Monaco (rapid) 2011 │ � выбрано (заливка) +│ … │ +│┌15 Topalov, V. Van der Sterren, P. 1-0 55 C95 … Antwerp 1997�│ � выбрано + кур�ор +│└─────────────────────────────────────────────────────────────────────────────────────────┘│ (заливка + рамка 1 px) +``` + +Во врем� запи�и на ме�те �чётчика (та же �трока и вы�ота, правый край): + +``` +│ У�ловий нет — показаны в�е партии Запи�ь в «Подборка»: 1 240 из 5 000 ▕████░░░░� Отменить │ +``` + +Обо�нование: + +- **Счётчик в �троке у�ловий, �права.** Строка по�то�нна (22 px, `chips()` в `large_db.rs`, + `set_min_height(22.0)`), значит по�вление и и�чезновение �чётчика не �двигает таблицу. Это + важно на деле, а не дл� вида: при �ерии Ctrl+щелчков �трока под кур�ором не должна уехать + на 22 px, иначе �ледующий щелчок попадёт в �о�еднюю партию. Шапка не подходит: её вёр�тка + измер�ет�� по ширине (`narrow-windows.md §2.4`), новый �лемент перенё� бы её на вторую �троку + в узком окне. Отдельна� нижн�� поло�а не подходит: она уменьшила бы таблицу �качком. +- Счётчик �тоит **правее у�ловий, но левее** «в �том пор�дке ходов: n из m · только �тот пор�док» + (он тоже �права, `right_to_left`). Пор�док �права налево: [пор�док ходов] [выделение] + [у�лови�…]. У�лови� уже умеют �ворачивать�� в под�казку, когда ме�та меньше 140 px, по�тому + ме�то под выделение отнимает�� у них, а не у таблицы. +- **Прогре�� запи�и — в том же ме�те, что и �чётчик.** Пользователь �мотрит туда, где только + что был �чётчик. Вы�ота �троки та же. �а врем� запи�и �чётчик выделени� не показывает��, + а выделение о�таёт�� и по�ле запи�и вернёт�� на ме�то. +- **Команды — только в контек�тном меню �троки и в пакетном режиме �уще�твующего диалога.** + Кнопок в шапке нет (решение владельца: «в �уще�твующем диалоге / контек�тном меню»). + Отдельной кнопки на поло�е выделени� тоже нет: «Сн�ть» — един�твенна� ��ылка. + +## 42.4. Три �о�то�ни� �троки: выбрана, кур�ор, наведение + +Это три разных �о�то�ни�, их нельз� �ливать (как в нотации: активна� позици�, выбранна� �трока +и ра�крыта� ветка). + +| Со�то�ние | Вид | Откуда | +|---|---|---| +| Выбрана | Сплошна� заливка `selection.bg_fill`, тек�т `selection.stroke.color` — **как �ейча� у един�твенной выбранной �троки** (`lib-sel-ru.png`) | `row.set_selected(..)` | +| Кур�ор (фоку� клавиатуры, его открывает Enter, F2, «До�ка» показывает его) | Рамка 1 px `selection.stroke.color` внутрь �троки (`StrokeKind::Inside`), радиу� 0. Рамка ри�ует�� **только при N ≥ 2 или когда кур�ор �тоит на невыбранной �троке**. При N = 1 вид точно как �ейча� | painter по `row.response().rect` | +| �аведение | Как �ейча� (`hovered.weak_bg_fill`) | без изменений | + +Кур�ор отличим без опоры на цвет: рамка — �то форма. Тот же приём, что у текущего хода +в вариантах (`move_chip`: заливка и 1 px `selection.stroke`). Ширина рамки не мен�ет геометрию +�троки. + +## 42.5. Мышь + +| Дей�твие | Выделение | Кур�ор | Якорь (anchor) | +|---|---|---|---| +| Щелчок | только �та �трока | �та �трока | �та �трока | +| Ctrl+щелчок | переключить �ту �троку (добавить или �н�ть) | �та �трока | �та �трока | +| Shift+щелчок | **заменить** диапазоном �корь…�трока в пор�дке текущей таблицы | �та �трока | не мен�ет�� | +| Ctrl+Shift+щелчок | **добавить** диапазон �корь…�трока к выделению | �та �трока | не мен�ет�� | +| Двойной щелчок | первый щелчок уже о�тавил одну �троку; парти� открывает�� (как �ейча�) | — | — | +| Права� кнопка по **выбранной** �троке при N ≥ 2 | выделение не мен�ет��, открывает�� **пакетное** меню | �та �трока | — | +| Права� кнопка по **невыбранной** �троке | только �та �трока, обычное меню одной партии | �та �трока | �та �трока | + +Якорь �крыт фильтром (Shift+щелчок по�ле �мены фильтра): �корем �тановит�� кур�ор, е�ли он +виден. Иначе Shift+щелчок работает как обычный щелчок. Выделение прот�жкой мыши в минимум +не входит. + +## 42.6. Клавиатура (когда фоку� не в поле ввода; `egui_wants_keyboard_input() == false`) + +| Клавиши | Дей�твие | +|---|---| +| ↑ ↓ PgUp PgDn | Кур�ор двигает�� (как �ейча�, шаг �траницы 20). Выделение �тановит�� одной �трокой кур�ора, �корь переходит на кур�ор | +| Home / End | Кур�ор на первую или по�леднюю �троку таблицы (нового нет, только �та пара клавиш) | +| Shift + ↑ ↓ PgUp PgDn Home End | Кур�ор двигает��; выделение = диапазон �корь…кур�ор (замен�ет) | +| Ctrl + ↑ ↓ | Кур�ор двигает��, выделение не мен�ет�� (рамка без заливки) | +| Ctrl+Space | Переключить �троку кур�ора (добавить или �н�ть) | +| Ctrl+A | Выбрать **в�е �троки текущей таблицы** (результат фильтра). В поле ввода Ctrl+A о�таёт�� «выделить тек�т» | +| Esc | Цепочка (первое подход�щее �рабатывает и поглощает клавишу): поле ввода (как �ейча�) → открытый на узком окне �щик фильтров → **при N ≥ 2 выделение �водит�� к �троке кур�ора** → «только до�ка» отдаёт ме�то таблице (`view.escape()`, как �ейча�) | +| Enter | Открыть партию кур�ора (как �ейча�) | +| F2 | Данные партии кур�ора (как �ейча�) | +| Ctrl+Shift+S | N ≤ 1 — как �ейча� (одна парти�); N ≥ 2 — пакетный диалог «Добавить в базу: N партий» | +| Delete | N ≤ 1 — как �ейча�; **N ≥ 2 — ничего не удал�ет��**, то�т «Удал�ть можно по одной партии: �нимите выделение (Esc)». Удалить одну �троку кур�ора, когда под�вечено не�колько, — опа�на� неожиданно�ть | + +Под�казки при наведении: у «Сн�ть» — «Сн�ть выделение (Esc)». У �чётчика �о �крытыми �троками — +«Скрытые фильтром партии тоже будут �копированы. Сн�ть выделение — Esc». + +## 42.7. Контек�тное меню + +**Одна �трока (N ≤ 1):** как �ейча�. В конец группы, перед «Отметить как про�мотренную», +добавл�ет�� «Выделить в�е (Ctrl+A)» — так пользователь узнаёт, что выдел�ть можно не�колько. + +**Пакетное (права� кнопка по выбранной �троке при N ≥ 2):** + +``` + Выбрано партий: 3 � weak, не кнопка + ───────────────────────────── + �ова� база из выбранных… + Добавить выбранные в базу… Ctrl+Shift+S + ───────────────────────────── + Выделить в�е Ctrl+A + Сн�ть выделение Esc +``` + +«Подготовить�� к …», «Данные партии», «Отметить», «Удалить» в пакетном меню не показывают��: +они отно��т�� к одной партии. Пока идёт запи�ь, оба пункта запи�и неактивны, под�казка: +«Идёт запи�ь в «Подборка» — дождите�ь окончани�». Две запи�и одновременно не запу�кают��. + +## 42.8. Диалоги + +**Пакетный режим диалога «Добавить в базу»** (тот же `own_db::Chooser`, вид как `chooser-ru.png`): + +- Заголовок «Добавить в базу: 3 партии» (`i18n::games(n)` — правильные формы чи�ла). +- Подзаголовок (weak, одна �трока, обрезает�� многоточием): «из «ruy» · пор�док как в таблице: + № ▲». Ключ и направление �ортировки — те же, что в заголовке колонки. +- Е�ли ча�ть выбранных �крыта фильтром — втора� weak-�трока: «из них 9 �ейча� �крыты фильтром». +- Спи�ок �воих баз: выбор базы и «Добавить» допи�ывают пакет в �ту базу (дубли пропу�кают��, + §42.10). Решение владельца про дубли («пропу�кают�� �о �водкой») имеет �мы�л именно зде�ь, + механика та же. **Е�ли орке�тратор �читает �то вне минимума**, �троки баз в пакетном режиме + �танов�т�� неактивными � под�казкой «Пока только в новую базу» — вёр�тка от �того не мен�ет��. +- «➕ �ова� база…» → диалог «�ова� база» (ниже). «Сохранить как файл…» → тот же фоновый путь + в выбранный пользователем файл. +- При N ≥ 50 000 — weak-�трока над кнопками: «Много партий: запи�ь может зан�ть не�колько + минут, её можно отменить». +- Кнопка по умолчанию — «Добавить» (е�ли выбрана база), Enter — она, Esc — «Отмена». + +**Диалог «�ова� база»** (`newbase-ru.png`), вызванный из пакета: + +- Под заголовком weak-�трока «Из выбранных: 3 партии из «ruy»». +- О�новна� кнопка «Создать и �копировать» вме�то «Создать». О�тальное без изменений: проверка + имени, «Изменить папку…», `create_new` — �уще�твующий файл не перезапи�ывает��, причина отказа + показывает�� в диалоге, как �ейча�. + +## 42.9. Матрица �о�то�ний + +| Со�то�ние | Строка у�ловий �права | Таблица | Меню / клавиши | +|---|---|---|---| +| �ет выделени� (база только что открыта) | пу�то | без заливки | как �ейча� | +| N = 1 | **пу�то** (�чётчик «Выбрано: 1» — шум, одна �трока видна и так) | одна заливка, вид как �ейча� | как �ейча� | +| N ≥ 2, в�е видны | «Выбрано: 3 · Сн�ть» | заливки, рамка у кур�ора | пакетное меню | +| N ≥ 2, ча�ть �крыта фильтром | «Выбрано: 12 (9 �крыто фильтром) · Сн�ть» | видимые выбранные залиты | пакетное меню; в диалоге — �трока про �крытые | +| Ctrl+A в Mega2026 (11,7 млн) | «Выбрано: 11 741 260 · Сн�ть» | в�е залиты | диалог � предупреждением «Много партий» | +| Идёт запи�ь | «Запи�ь в «Подборка»: 1 240 из 5 000 ▕██░░� Отменить» | работает, выделение можно мен�ть (пакет зафик�ирован в момент запу�ка) | пункты запи�и неактивны | +| Отмена нажата | «Отмена…» и �пиннер 14 px на ме�те поло�ы, до о�тановки потока | — | — | +| Отменено | �чётчик выделени� возвращает��; то�т «Копирование отменено: база «Подборка» не �оздана» (дл� �воей базы — «…«X» не изменена») | — | — | +| Готово | �чётчик выделени� возвращает��; то�т «Подборка: �копировано 3, пропущено 1 (дубли)» + «Открыть»; карточка на полке | — | — | +| Ча�ть запи�ей не прочитана | то�т «Подборка: �копировано 48, пропущено 2 — дубли 1, не прочитано 1 (№ 40)». Больше 5 номеров — «(№ 40, 41, 77 и ещё 12)» | — | — | +| Ошибка запи�и (нет ме�та, нет прав, им� зан�то к концу) | кра�ный тек�т `error_fg_color` на ме�те прогре��а: «�е удало�ь запи�ать «Подборка»: нет ме�та на ди�ке. �ичего не запи�ано» + `×`; то же то�том. Под�казка — полный путь и тек�т ОС | — | — | +| И�точник изменил�� во врем� запи�и (fingerprint) | то же, что ошибка: «База «ruy» изменила�ь во врем� копировани�. �ичего не запи�ано» | выделение �нимает�� (номера запи�ей больше не верны) | — | +| И�точник перечитан по�ле внешнего изменени� (без запи�и) | — | выделение �нимает��, то�т «Выделение �н�то: файл базы изменил��» | — | +| Удаление запи�и в �воей базе | — | выделение �водит�� к кур�ору (номера �двигают��) | — | +| Пу�та� база | �троки нет: �кран «�ет партий» (как �ейча�) | — | — | +| Узкое окно 960×600 | �чётчик �окращает�� до «3 · Сн�ть» (под�казка — полный тек�т), е�ли меньше 140 px ме�та у�лови�м | рамка кур�ора видна | — | +| HiDPI (ма�штаб 2) | рамка 1 логиче�кий px = 2 физиче�ких; тек�т не обрезает�� | — | — | + +Скрытые фильтром �троки при Ctrl+A не добавл�ют��: Ctrl+A берёт только текущую таблицу. + +## 42.10. Фильтр, �ортировка, пор�док, дубли + +- **Сортировка** не мен�ет набор выбранных; мен�ет�� только пор�док, в котором они видны. +- **Смена фильтра или позиции пои�ка не �нимает выделение** (решение дизайнера). Причина: + подборку �обирают из не�кольких пои�ков (партии Карл�ена, потом партии Каруаны). Сбра�ывать её + от �лучайного ка�ани� пол� дорого. Скрытые �троки в�егда видны в �чётчике («9 �крыто + фильтром») и в диалоге; под�казка �чётчика пр�мо говорит, что их тоже �копируют. Это + отличает�� от текущего правила дл� одной �троки (`large_db.rs:630-637`: �трока, ушедша� из + �пи�ка, пере�таёт быть выбранной). Дл� **кур�ора** текущее правило о�таёт��: ушедший кур�ор + �бра�ывает��, и Enter не открывает невидимую партию. +- Выделение хранит�� отдельно у каждой базы (как фильтры и �ортировка), переживает + переключение баз на полке и возврат из партии. Между запу�ками программы не �охран�ет��. +- **Пор�док в новой базе — как в таблице** (решение владельца): в�е выбранные запи�и, в том + чи�ле �крытые фильтром, �ортируют�� текущим ключом и направлением �ортировки таблицы. + Одинаковые значени� упор�дочивают�� по номеру запи�и. Е�ли в�е выбранные видны, �то в точно�ти + пор�док �трок на �кране. Пор�док фик�ирует�� в момент нажати� «Создать и �копировать». +- **Дубли** (решение владельца): пропу�кают�� без вопро�а на каждую партию. Это и повторы внутри + выбора, и (дл� �уще�твующей базы) партии, которые в ней уже е�ть. Признак дубл� — тот же, что + у текущей проверки (`store.rs`: игроки, дата, о�новна� лини�). В итоге — чи�ло пропущенных. + +## 42.11. Большие базы: требовани� к отзывчиво�ти + +- Выделение — **битовое множе�тво по номеру запи�и** (`Vec`, `total/64` �лов; дл� Mega + ≈ 1,4 МБ) или `HashSet` при малом N. Отри�овка �троки провер�ет принадлежно�ть за O(1); + на кадр — только видимые �троки (таблица уже виртуальна�, `TableBuilder`). +- Ctrl+A по 11,7 млн и Shift-диапазон по большой таблице — один проход по `view` без + перери�овки в�ех �трок. Цель — не дольше одного кадра на 4 221 �троке, ≤ 100 м� на 11,7 млн + (порог провер�ет разработчик замером). +- Счётчики «выбрано» и «�крыто фильтром» **к�шируют��** и пере�читывают�� только при изменении + выделени� или `view`, а не на каждом кадре. +- Запи�ь — отдельный поток: �нимок �пи�ка запи�ей → чтение (`raw_text` или `load_game().to_pgn()`, + как в `app.rs:1449-1455`) → временный файл р�дом � целью → в конце атомарна� публикаци� без + перезапи�и (дл� новой: `hard_link`/`RENAME_NOREPLACE`, отказ при по�вившем�� файле; дл� �воей + базы — `write_atomic` �тарого �одержимого � добавкой). Прогре�� — через канал не чаще + 10 раз/�; отмена — `AtomicBool`, провер�ет�� на каждой запи�и. Отмена или ошибка: временный + файл удал�ет��, нова� база **не �оздаёт��**. Пу�та� база на полке не о�таёт��. +- Закрытие окна во врем� запи�и: поток отмен�ет��, временный файл удал�ет��, и�точник не + тронут. Отдельного вопро�а нет: атомарна� публикаци� гарантирует, что половины файла не будет. + +## 42.12. Тек�ты ru / en + +| Ключ (�мы�л) | ru | en | +|---|---|---| +| �чётчик | Выбрано: {n} | Selected: {n} | +| �чётчик �о �крытыми | Выбрано: {n} ({k} �крыто фильтром) | Selected: {n} ({k} hidden by the filter) | +| ��ылка (�водит выделение к �троке кур�ора, как Esc; ключ `Deselect`, т. к. «Clear» уже переведено «Очи�тить») | Сн�ть | Deselect | +| под�казка ��ылки | Сн�ть выделение (Esc) | Clear the selection (Esc) | +| под�казка �чётчика �о �крытыми | Скрытые фильтром партии тоже будут �копированы. Сн�ть выделение — Esc | Games hidden by the filter will be copied too. Esc clears the selection | +| меню, заголовок | Выбрано партий: {n} | Games selected: {n} | +| меню | �ова� база из выбранных… | New database from selected… | +| меню | Выделить в�е (Ctrl+A) | Select all (Ctrl+A) | +| меню | Сн�ть выделение (Esc) | Clear selection (Esc) | +| пункт неактивен | Идёт запи�ь в «{name}» — дождите�ь окончани� | Writing to «{name}» — wait until it finishes | +| диалог «�ова� база», �крытые | из них {k} �ейча� �крыты фильтром | {k} of them are hidden by the filter now | +| диалог, много | Много партий: запи�ь может зан�ть не�колько минут, её можно отменить | Many games: writing may take a few minutes; you can cancel it | +| нова� база, подзаголовок | Из выбранных: {games} из «{src}» | From the selection: {games} from «{src}» | +| нова� база, кнопка | Создать и �копировать | Create and copy | +| прогре�� | Запи�ь в «{name}»: {i} из {n} | Writing to «{name}»: {i} of {n} | +| прогре��, ��ылка (общий ключ `Cancel`) | Отмена | Cancel | +| отмена идёт | Отмена… | Cancelling… | +| итог | {name}: �копировано {n}, пропущено {m} | {name}: copied {n}, skipped {m} | +| итог, причины | {name}: �копировано {n}, пропущено {m} — дубли {d}, не прочитано {u} (№ {list}) | {name}: copied {n}, skipped {m} — duplicates {d}, unreadable {u} (No. {list}) | +| итог, кнопка | Открыть | Open | +| отменено, нова� | Копирование отменено: база «{name}» не �оздана | Copying cancelled: «{name}» was not created | +| ошибка | �е удало�ь запи�ать «{name}»: {reason}. �ичего не запи�ано | Could not write «{name}»: {reason}. Nothing was written | +| и�точник изменил�� | База «{src}» изменила�ь во врем� копировани�. �ичего не запи�ано | «{src}» changed while copying. Nothing was written | +| выделение �н�то | Выделение �н�то: файл базы изменил�� | Selection cleared: the database file changed | +| Delete при N≥2 | Удал�ть можно по одной партии: �нимите выделение (Esc) | Games are deleted one at a time: clear the selection (Esc) | + +Прин�то при реализации (минимум владельца, 2026-11-27): пакет только в новую базу — пакетного режима +диалога «Добавить в базу», �трок «Добавить выбранные…» и «Пока только в новую базу» нет; Ctrl+Shift+S при +N ≥ 2 �разу открывает «�ова� база». Ошибка запи�и — кра�на� �трока � `×` на ме�те прогре��а и то�т. + +Чи�ла — � группировкой, как в «найдено 4 221 из 11 743 083» (`grouped`). «{games}» — +`i18n::games(n)`. + +--- + +# Задача 43. Как узнать о �трелках и кругах + +## 43.1. Задача (одной фразой) + +Пользователь, который читает или анализирует партию, узнаёт без документации, что правой +кнопкой на до�ке ри�уют�� �трелки и круги и что они �охран�ют��. Ходы � такими пометками видны +в нотации. Важно�ть: �ам ход → его оценка (NAG) → признак пометок. Признак не �порит � ходом +за внимание. + +## 43.2. Где показывать под�казку и почему не «под до�кой» + +Владелец про�ил под�казку «у до�ки». Снимки показывают, что отдельного ме�та р�дом � до�кой нет: +до�ка занимает в�ю вы�оту (`game-shapes-ru.png`: 60…1072 px), боковые пол� е�ть только в широком +окне, а на 960×600 до�ка �тоит вплотную к панели (`game-960-en.png`). �адпи�ь поверх до�ки +закрывала бы клетки и мешала бы ри�овать. + +**Решение:** информационна� поло�а **вверху панели нотации**, пр�мо у правого кра� до�ки. Это +тот же компонент, что поло�а «Комментарии на другом �зыке (англий�кий) [Переве�ти] ×» +(`chooser-ru.png`, `translate_ui.rs:1790-1840`): вы�ота �троки, перено� тек�та, `small_close_button`. +�овый вид не вводит��. Тек�т поло�ы — обычного цвета, как у поло�ы перевода, не weak +(ревью 2026-11-27, Д2: weak давал контра�т 2,6:1, а под�казку показывают в�его три раза). + +``` +┌ панель нотации ─────────────────────────────────────────────� +│ �нализ: выкл Движок не выбран ⚙ │ +│ [�отаци�] Справочник │ +│ Стрелки и круги: права� кнопка мыши на до�ке — прот�ните ×│ � поло�а, обычный тек�т, +│ или щёлкните. Сохран�ют�� в партии. │ перено�ит�� по ширине +│ ┌ Intro ──────────────────────────────────────────────────� │ +│ 1 e4 e5 ↗ │ � признак пометок +│ 2 Nf3 d6 │ +│ 3 d4 ◯ … │ +``` + +## 43.3. Когда показывать и как не надоедать + +| Правило | Значение | +|---|---| +| Где | Только обычный про�мотр и анализ партии, где до�ка интерактивна и фигуры пишут�� в партию (`game_view.rs:1441-1447`: нет про�мотра линии, Maia, тренировки). В игре, тренировке, подготовке, на до�ках без ввода — не показывать | +| Когда по�вл�ет�� | При открытии партии, до первой отри�овки нотации (поло�а не «въезжает» во врем� чтени�) | +| Про�мотр линии движка | Поло�а, уже показанна� в партии, о�таёт�� на ме�те приглушённой (вы�ота та же, `×` активен), чтобы нотаци� не прыгала; впервые в про�мотре не по�вл�ет�� (ревью Д1) | +| Одна поло�а за раз | Е�ли видна поло�а перевода, под�казка в �той партии не показывает�� (и не за�читывает��) | +| И�чезает нав�егда | (а) пользователь нари�овал мышью любую �трелку или круг (б) нажал `×`. Признак `settings.hints.board_shapes = done` | +| И�чезает �ама | По�ле показа в **3** разных открыти�х партии без реакции. Счётчик в на�тройках; одна парти�, открыта� повторно в той же �е��ии, не �читает�� и под�казку �охран�ет — в том чи�ле треть� за�читанна� | +| Закрытие внутри партии | Поло�а не и�чезает �ама во врем� работы � партией (никаких таймеров): вы�ота панели мен�ет�� только от дей�тви� пользовател� (`×` или ри�овани�). При ри�овании поло�а пропадает **по�ле отпу�кани� кнопки**, а не во врем� прот�жки | +| Под�казка тек�та | Цвета и �н�тие — в под�казке при наведении на тек�т поло�ы, не в �амом тек�те | + +По�то�нное ме�то �правки (под�казка и�чезает, знание должно где-то о�тать��): в «�а�тройках › +До�ка и фигуры», в разделе «До�ка», �разу под его заголовком, перед образцами до�ок (иначе она ниже видимой ча�ти окна, ревью Д3) — одна weak-�трока +(`settings-board-ru.png`, по образцу «Только вид на �кране. В PGN…»): +«Стрелки и круги — права� кнопка мыши на до�ке; Shift — кра�ный, Alt — �иний, Shift+Alt — +жёлтый. Сохран�ют�� в комментарии хода ([%cal], [%csl])». + +## 43.4. Признак у хода � пометками + +- **Что:** маленький значок, **нари�ованный painter'ом**, а не �имволом шрифта. Причина: + �трелки е�ть только в моноширинном шрифте egui (`assets.rs:169`), а у глифа друга� вы�ота + �троки. Painter даёт чёткий значок при любом ма�штабе. Значок 10×10 логиче�ких px: �трелка + (отрезок 1,5 px и треугольный наконечник) — е�ли у хода е�ть хот� бы одна �трелка; иначе + кружок 1,5 px диаметром 9. Цвет — `weak_text_color()`, на текущем ходе — + `selection.stroke.color` (как тек�т хода). **Цвет �амих �трелок значок не повтор�ет**: + зелёный и кра�ный �порили бы � цветами NAG (`Qb3!` зелёный, `b5?` оранжевый на `game.png`). +- **Где в таблице о�новной линии:** �разу по�ле хода и NAG, `x = text_right + 4`, по + вертикальному центру �чейки. Е�ли е�ть таблетка ошибок `×N` (`notation.rs:319-337`), значок + �тоит по�ле неё. Ячейка фик�ированной ширины (≤ 160 px, `CELL_MAX`) и вы�оты (`ROW_H = 26`), + по�тому �трока не мен�ет�� ни по вы�оте, ни по положению хода. Сама� длинна� запи�ь + `Qxb8+!!` � таблеткой и значком помещает�� в 160 px; проверить на «Фигурках» и ру��ких буквах. +- **В вариантах** (`move_chip` в потоке): значок внутри чипа �права от тек�та, ширина чипа + +14 px. Поток может перене�ти�ь только при добавлении или �н�тии фигуры, то е�ть по дей�твию + пользовател�. При открытии и переходах по ходам ничего не мен�ет��. +- **Корень (до 1-го хода):** е�ли е�ть тек�т начального комментари� — значок у правого кра� + его блока. Е�ли комментарий �о�тоит только из команд — признака нет (ограничение минимума, + на начальной позиции фигуры видны на до�ке). +- **Под�казка при наведении на �чейку хода** (вме�те � �уще�твующими): «Стрелки: 2 · круги: 1 + — видны на до�ке на �том ходу». +- Признак �троит�� по `[%cal]`/`[%csl]` в `comments_after` узла. Разбор к�ширует�� на вер�ию + партии (по�ле каждого `annotate` — пере�чёт), а не повтор�ет�� на каждом кадре. +- Стрелки движка признака не дают (они не в PGN). + +## 43.5. Матрица �о�то�ний + +| Со�то�ние | Поло�а | Признак | +|---|---|---| +| Первое открытие партии | видна | у ходов � пометками | +| Ри�ование мышью (прот�жка) | видна до отпу�кани�, затем и�чезает нав�егда | по�вл�ет�� у текущего хода �разу по�ле отпу�кани� | +| Повтор фигуры (�н�тие по�ледней) | — | и�чезает | +| Ctrl+Z / Ctrl+Y | — | �ледует за партией | +| Про�мотр линии движка | о�таёт�� приглушённой, вы�ота та же | у ходов партии о�таёт��; у ходов PV признака нет | +| Игра � Maia, тренировка | нет | нет (фигуры временные) | +| Парти� из базы только дл� чтени� | видна (ри�овать можно, �охранение — в �вою базу по Ctrl+S, как �ейча�) | да | +| Видна поло�а перевода | нет | да | +| Узкое окно 960×600 | тек�т в 2–3 �троки, `×` в правом верхнем углу поло�ы | да | +| HiDPI | значок чёткий (painter), лини� 1,5 логиче�ких px | — | +| Тёмна� и �ветла� тема | weak-цвет темы; на текущем ходе — цвет тек�та выделени� | — | + +## 43.6. Клавиатура + +�овых клавиш нет. Ри�ование о�таёт�� мышью: права� кнопка, Shift — кра�ный, Alt — �иний, +Shift+Alt — жёлтый; Ctrl+Z отмен�ет. `×` поло�ы — обычна� кнопка (Tab, Enter/Space). +**Ри�к:** в ча�ти окружений Linux Alt+перета�кивание зан�то оконным менеджером. В +Hyprland и GNOME по умолчанию �то Super, но в некоторых �борках Xfce и KDE — Alt. Те�тировщик +провер�ет в до�тупных окружени�х. Е�ли Alt перехвачен, �то ограничение, а не дефект приложени�. + +## 43.7. Тек�ты ru / en + +| Смы�л | ru | en | +|---|---|---| +| поло�а | Стрелки и круги: права� кнопка мыши на до�ке — прот�ните или щёлкните. Сохран�ют�� в партии. | Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game. | +| под�казка поло�ы | Без клавиши — зелёный, Shift — кра�ный, Alt — �иний, Shift+Alt — жёлтый. Та же фигура ещё раз — убрать. Ctrl+Z — отменить. | No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes. | +| `×` | Больше не показывать | Don't show again | +| признак | Стрелки: {a} · круги: {c} — видны на до�ке на �том ходу | Arrows: {a} · circles: {c} — shown on the board at this move | +| на�тройки | Стрелки и круги — права� кнопка мыши на до�ке; Shift — кра�ный, Alt — �иний, Shift+Alt — жёлтый. Сохран�ют�� в комментарии хода ([%cal], [%csl]). | Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]). | + +Е�ли чи�ло равно нулю, его ча�ть в под�казке признака опу�кает�� («Стрелки: 2 — видны…»). + +--- + +# Требовани� к реализации (разработчику) + +**42** +1. `LargeView`: `selection` (битовое множе�тво/набор номеров запи�ей), `cursor: Option` + (бывший `selected`), `anchor`. К�ш `selected_count`, `hidden_count`, пере�чёт по изменению. + Отри�овка �троки: `set_selected(selection.contains(i))`, рамка кур�ора painter'ом (§42.4). +2. Модификаторы щелчка через `ui.input(|i| i.modifiers)` (`command` = Ctrl на Linux); таблица + и клавиатура по §42.5–42.6; Esc — в цепочку `library.rs:672-683` перед `view.escape()`. +3. Строка у�ловий (`chips()`): �права налево — пор�док ходов, затем блок выделени� или + прогре��а. У�лови� �ворачивают�� раньше, вы�ота 22 px не мен�ет��. +4. Меню и пакетный режим `Chooser`/`NewBaseDialog` (§42.7–42.8). �овый `LibraryAction` + � `Vec` в пор�дке §42.10 (пор�док вычи�л�ет�� при запу�ке). +5. Фоновое задание по §42.11; итог — то�т � кнопкой «Открыть» (по образцу `Toast.undo`); + карточка на полке — только по�ле публикации файла. +6. Delete при N ≥ 2 — то�т, не удаление. + +**43** +1. Поло�а под�казки — тот же компонент, что поло�а перевода; правила §43.3; пол� на�троек + `hints.board_shapes` (`done`, `shown`). +2. Признак — `paint_move_cell` (по�ле `text_right`, по�ле таблетки ошибок) и `move_chip`; + к�ш разбора на вер�ию партии; под�казка при наведении. +3. Строка в «�а�тройки › До�ка и фигуры». +4. Те�ты `apply_shape` и прот�жки мышью — из аудита (не дизайн, но у�ловие приёмки 43). + +Отладочные хуки дл� �нимков (предложение, чтобы ревьюер и те�тировщик �могли �н�ть �о�то�ни� +без мыши): `CP_SELECT=3,7,15` (выделить запи�и), `CP_BATCH=new:<им�>` (запу�тить пакет), +`CP_BATCH_SLOW=1` (и�ку��твенна� задержка на запи�ь, чтобы �н�ть прогре��), +`CP_HINT_RESET=1` (�бро�ить под�казку 43). `CP_KEYS` уже умеет Shift/Ctrl+клавиши. + +# Критерии приёмки дл� дизайн-ревьюера + +Ревьюер — не автор кода. Окна только через `scripts/dev/headless-run.sh`, изолированный профиль. +Каждый пункт подтверждает�� �нимком � размером и �о�то�нием. + +**42** +1. Сери� 1920×1080, `ruy`: нет выделени� → щелчок № 3 → Ctrl+щелчок № 7 → Ctrl+щелчок № 15 → + Shift+щелчок № 20. Измерить y-координату верха таблицы и �троки № 15 на каждом �нимке: + **�двиг 0 px**. Счётчик по�вл�ет�� только начина� � N = 2. +2. Вид при N = 1 �овпадает � и�ходным `lib-sel-ru.png` попик�ельно в �троке (кроме ✓). +3. Кур�ор отличим от выбранной �троки в тёмной и �ветлой теме и в оттенках �ерого (рамка видна). + Кур�ор на невыбранной �троке (Ctrl+↓) — рамка без заливки. +4. Строка у�ловий � фильтром (2–3 чипа) и выделением: чипы �ворачивают��, �чётчик целиком, + вы�ота �троки 22 px; 960×600 — �окращённый �чётчик, без перено�а шапки. +5. Пакетное меню и пакетный диалог: заголовок, подзаголовок � пор�дком, �трока «�крыто + фильтром»; ширина диалога и кнопки как у `chooser-ru.png`/`newbase-ru.png`. +6. Сери� запи�и (� `CP_BATCH_SLOW`): запу�к → 30 % → «Отмена…» → отменено; и запу�к → готово + → то�т → карточка на полке. �а в�ех �нимках вы�ота �троки у�ловий и верх таблицы + неизменны; полка мен�ет�� только по�влением карточки в конце. +7. Ошибка (цель в каталоге без прав): кра�ный тек�т на ме�те прогре��а, `×`, таблица не + �двинута. +8. Больша� база (Mega2026 или �интетика ≥ 1 млн): Ctrl+A, прокрутка, Shift+End — кадры идут + (`CP_LOG_FRAMES`), �чётчик � группировкой разр�дов не обрезан. +9. �нглий�кий интерфей�: в�е �троки §42.12 помещают��, без обрезки на 1920 и 960. + +**43** +10. Открытие `shapes.pgn` на ходе e5 (1920 и 960): поло�а вверху нотации тем же компонентом, + что и поло�а перевода (�равнить �нимок � поло�ой перевода: от�тупы, вы�ота �троки, `×`). +11. Признак у `e5`, `d4`, `Qb3`, у `8.Qxb7` в варианте; на текущем ходе (заливка) значок + читает��. Позици� SAN в �чейке � признаком и без него одинакова (x отличает�� на 0 px); + вы�ота �троки 26 px. +12. Сери�: нари�овать �трелку (прот�жка) → отпу�тить → поло�а и�чезла, признак по�вил��; �двиг + нотации ровно на вы�оту поло�ы, один раз, по�ле отпу�кани�. +13. Повторное открытие по�ле `×` — поло�ы нет; четвёртое открытие без реакции — поло�ы нет. +14. В про�мотре линии движка, в игре � Maia и в тренировке поло�ы нет. +15. HiDPI (е�ли окружение позвол�ет, иначе пометить «не проверено»): значок и рамка кур�ора + чёткие. + +# Что передать те�тировщику + +- 42: �охранно�ть — и�точник sha256/mtime до и по�ле (PGN UTF-8, legacy windows-1252, + `.cbv`, Mega2026); пор�док в новой базе = пор�док таблицы при �ортировке по «Белые ▼» и при + �крытых фильтром выбранных; дубли внутри выбора и � �уще�твующей базой; отмена на �ередине — + файла нет, временного файла нет; kill проце��а во врем� запи�и — ча�тичного файла нет; им� + зан�то к моменту публикации — �уще�твующий файл не тронут; Delete при N ≥ 2 ничего не + удал�ет; выделение по�ле внешнего изменени� файла �нимает��; Ctrl+A в поле пои�ка выдел�ет + тек�т, а не партии. +- 43: прот�жка правой кнопкой в анализе � работающим движком; Alt-цвет в до�тупных оконных + менеджерах; поло�а не по�вл�ет�� в Maia, тренировке и подготовке; �чётчик «3 показа» не ра�тёт + при повторном открытии той же партии в �е��ии; признак по�ле Ctrl+Z/Ctrl+Y и по�ле + �охранени� и повторного открыти�. + +# �ерешённое (орке�тратору) + +1. Пакет в **�уще�твующую** базу — в минимуме или нет (§42.8). Вёр�тка готова дл� обоих + вариантов. +2. Порог «Много партий» (50 000) и порог отзывчиво�ти Ctrl+A — по�ле замера разработчика. +3. Значок дл� корн� без тек�та — вне минимума. +4. «Убрать в�е �трелки и круги хода» в меню хода — полезно, но владелец про�ил только + обнаруживаемо�ть; не включено. diff --git a/docs/design/translation-ui.md b/docs/design/translation-ui.md new file mode 100644 index 0000000..3b5b293 --- /dev/null +++ b/docs/design/translation-ui.md @@ -0,0 +1,740 @@ +# Перевод комментариев: интерфей� и пути пользовател� + +Стату�: �пецификаци� дизайнера дл� реализации, 2026-10-21. О�нова — `translation.md` (утверждён � правками владельца; правки главнее). Этот документ замен�ет разделы «Интерфей�» и «Ошибки» из `translation.md` там, где они ра�ход�т��; там, где он молчит, дей�твует `translation.md`. + +Опирает�� на код: `game_view.rs` (бокова� панель: вкладки «�отаци� / Справка / Отчёт» над нотацией, панель движка �верху, панель кнопок �низу � меню ☰; `keyboard()`), `notation.rs` (`comment_block` — блок во в�ю ширину, `inline_line` — комментарии в вариантах тек�том в �троке), `settings_ui.rs` (окно «�а�тройки», вкладки), `engine_offer.rs` (окно, открытое в ответ на дей�твие), `online_ui.rs` / `update_ui.rs` (окно можно закрыть, работа идёт; ошибки про�тыми �ловами + «Подробно�ти»; `widgets::primary`), `i18n.rs` (en ru fr de es it; англий�кий тек�т — ключ), `translate.rs` (`Connection`, `Preset`, `TranslationSettings`, `plan()`, `Failure`, `Event::{Done, Bad, Failed, Finished}`, `cache_size` / `clear_cache`, `WAITING`). + +Размеры — логиче�кие точки egui. + +## 0. Главное + +1. **Перевод — �то про�то чтение.** �и в PGN, ни в буфер обмена, ни в «Сохранить как…» перевод не попадает. Ходы не перевод�т�� нигде. Перевод не редактирует��; правка комментари� мен�ет оригинал (�м. `user-comments.md` §9). +2. **Одно �огла�ие — и дальше �амо.** Пока человек ни разу не �огла�ил��, над нотацией видно предложение. По�ле первого �огла�и� люба� открыта� парти� � комментари�ми на другом �зыке переводит�� �ама; переключатель [Оригинал | Перевод] в�егда под рукой. +3. **Вход через ChatGPT прои�ходит в браузере, а ChessPenguin в�ё врем� говорит, чего ждёт** и что делать, е�ли браузер не открыл��. +4. **Кажда� ошибка — одна �трока про�тыми �ловами и кнопка �ледующего шага.** Техниче�кие подробно�ти — по ��ылке «Подробно�ти». +5. **�ичего не блокирует интерфей�.** Перевод идёт в фоне, комментарии замен�ют�� по мере готовно�ти, готовое �разу в к�ше. + +## 1. Режим и когда показывает�� �трока + +### 1.1. �а�тройка «Когда комментарии на другом �зыке» + +Три положени� (одна радиогруппа в �а�тройки → Перевод, §3.5); в `TranslationSettings` �то `auto` и `never_offer`: + +| Положение | `auto` | `never_offer` | Поведение | +|---|---|---|---| +| «Переводить �разу» | true | false | парти� открыла�ь → перевод начинает�� �ам | +| «Спрашивать» (по умолчанию до первого �огла�и�) | false | false | �трока-предложение � кнопкой «Переве�ти» | +| «�ичего не делать» | — | true | �троки нет; переве�ти можно из меню ☰ | + +Первое у�пешное �огла�ие (окно �огла�и� или на�тройка модели на компьютере) �тавит «Переводить �разу». Больше программа �ама �то не мен�ет. + +### 1.2. Что решает�� при открытии партии + +При каждом открытии партии в `GameView` (из библиотеки, большой базы, пои�ка позиции, вкладки «Справка», буфера обмена) вызывает�� `plan(comments(game), target)`. Дл� партии, где тек�та комментариев больше 50 000 �имволов, `plan()` выполн�ет�� в фоновом потоке; до ответа �троки нет. + +``` +plan() = None → �троки нет (в т. ч. партии Lichess/Chess.com: там только [%clk]) +в�е тек�ты плана уже в к�ше → «Готово», без �ети и без проверки �огла�и� +«�ичего не делать» → �троки нет (к�ш тоже не показывает��, пока не выбрано ☰ → Переве�ти) +пользователь нажал ✕ в �той партии → �троки нет до �ледующего открыти� партии +«Спрашивать» → «Предложение» +«Переводить �разу», но подключение не готово + или �ерви� не разрешён → «Предложение» (кнопка ведёт в на�тройку / �огла�ие) +«Переводить �разу», чужого тек�та > 60 000 �имв. → «Больша� парти�» (предложение � объёмом) +«Переводить �разу» → перевод начинает��, �трока «Идёт» +``` + +Ча�тично в к�ше: показывает�� �разу то, что е�ть; в очередь уходит только о�тальное. + +### 1.3. Переключатель [Оригинал | Перевод] + +- Режим отно�ит�� к открытой партии и **не запоминает��**: кажда� вновь открыта� парти� начинает�� � «Перевод» (раз человек �огла�ил�� на автоперевод, он хочет читать перевод). Возврат к партии через «� назад к…» — тоже «Перевод». +- Переключатель виден, как только переведён хот� бы один комментарий, во в�ех �о�то�ни�х �троки, кроме «Предложени�». +- В режиме «Оригинал» перевод продолжает�� в фоне; �трока показывает прогре��, комментарии о�тают�� оригинальными, пометок нет. + +## 2. Пути пользовател� + +Обозначени�: **С** — �трока над нотацией (§3.1), **К** — окно «Как переводить?» (§3.2), **Сг** — окно �огла�и� (§3.4), **�** — �а�тройки → Перевод (§3.5), **Б** — вкладка браузера. + +### (а) Перва� парти� на чужом �зыке, ничего не на�троено, е�ть ChatGPT Plus + +1. Человек открывает партию � англий�кими комментари�ми (интерфей� ру��кий). �ад нотацией **С**: «Комментарии на другом �зыке (англий�кий) · [Переве�ти] · ✕». +2. «Переве�ти» → открывает�� **К**. Выбран вариант «У мен� е�ть ChatGPT Plus или Pro». Главна� кнопка — «Войти через ChatGPT». +3. �ажатие: программа открывает �лушатель на `127.0.0.1:<�вободный порт>`, затем �и�темный браузер �о �траницей входа OpenAI. **К** переходит в �о�то�ние «Ждём вход в браузере» (§3.3): �пиннер, «Браузер не открыл��? Скопировать ��ылку», «Отмена». Окно можно закрыть — ожидание продолжает��, в **С** видно «Ждём вход в браузере… · Отмена». +4. В **Б** человек входит в аккаунт OpenAI и на �кране разрешений нажимает «Разрешить» дл� ChessPenguin. +5. Браузер возвращает�� на `127.0.0.1`; программа обменивает код на токены, провер�ет выданные права и отвечает �траницей «Готово» (§3.7). Окно ChessPenguin про�ит фоку� (`ViewportCommand::Focus`, при неудаче — `RequestUserAttention`). +6. Программа �разу делает пробный запро� (одна фик�ированна� фраза, не тек�ты пользовател�), чтобы узнать, работает ли подпи�ка. **К**: «Провер�ю…» → дальше шаг 7, или ветка (i). +7. **К** �мен�ет �одержимое на �огла�ие (тот же тек�т, что **Сг**, §3.4): что уйдёт в ChatGPT, что ходы партии не уйдут, что дальше переводит�� �амо. Кнопка «Переводить». +8. «Переводить» → окно закрывает��, `allowed += "chatgpt"`, режим «Переводить �разу». **С**: «Перевод… 0 из 40 · О�тановить»; комментарии в нотации замен�ют�� по мере ответов, у каждого — значок «⇄». +9. Конец: **С** «Машинный перевод (ChatGPT) · [Оригинал | Перевод]». + +�ажатий в программе: 3 («Переве�ти», «Войти через ChatGPT», «Переводить») плю� вход в браузере. + +### (б) Подпи�ки нет → ключ DeepSeek + +1–2. Как в (а). В **К** человек выбирает «Подпи�ки нет — ключ API». Под ним ра�крывает��: «Серви�: [DeepSeek ▾]» и шаги получени� ключа дл� выбранного �ерви�а (§3.2). +3. «Открыть �айт DeepSeek ↗» открывает `platform.deepseek.com/api_keys` в браузере. �а �айте: вход или реги�траци� → пополнение балан�а (DeepSeek работает по предоплате) → «Create new API key» → �копировать ключ (показывает�� один раз). �азвани� кнопок �айта в шагах — как на �айте, по-англий�ки; перед выпу�ком �верить � �айтом. +4. Человек в�тавл�ет ключ в поле «Ключ» (Ctrl+V; пробелы и переводы �трок по кра�м обрезают��). Кнопка «Проверить и продолжить» �тановит�� активной. +5. �ажатие → «Провер�ю…» → пробна� фраза. У�пех: «✓ Работает: «The knight is strong» → «Конь �илён»», и **К** переходит к �огла�ию «Отправл�ть комментарии в DeepSeek?». Ошибка — �трока под полем (тек�ты §4), окно о�таёт�� на �том шаге. +6. «Переводить» → как (а) 8–9, в **С** — «(DeepSeek)». + +Е�ли человек выбрал Google Gemini — под �пи�ком �трока-предупреждение (§5, «Gemini»), о�тальное так же. Е�ли OpenAI — в шагах отдельна� �трока: «Ключ API оплачивает�� отдельно от подпи�ки ChatGPT». + +### (в) Ollama на �том компьютере + +1–2. Как в (а). В **К** — «Подпи�ки нет — ключ API», �ерви� «Ollama — на �том компьютере». +3. Поле ключа �крыто. Шаги: «1. У�тановите Ollama � �айта ollama.com ↗ и запу�тите её. 2. Скачайте модель: `ollama pull {model}` [Копировать]. 3. �ажмите «Проверить и продолжить».» `{model}` — рекомендуема� модель, кон�танта в коде (выбирает разработчик по проверке каче�тва). +4. «Проверить и продолжить» → `GET /models`. Ollama не запущена → «Ollama не отвечает. Запу�тите Ollama и нажмите «Проверить и продолжить».» Моделей нет → «В Ollama нет моделей. Скачайте модель командой ниже.» Модели е�ть → по�вл�ет�� «Модель: [▾]» (рекомендуема�, е�ли е�ть, иначе перва�) и пробна� фраза. +5. У�пех → �огла�и� нет (адре� локальный). Под кнопкой уже была �трока «Дальше комментарии на других �зыках будут переводить�� �ами…». Окно закрывает��, режим «Переводить �разу», перевод идёт. +6. Первый запро� к локальной модели может идти долго: е�ли ответа нет 8 � — **С** «Модель загружает�� в пам�ть — �то бывает до минуты…». Таймаут ответа дл� локального адре�а — 180 �. + +LM Studio — так же, шаги: «1. У�тановите LM Studio � �айта lmstudio.ai ↗. 2. Загрузите в LM Studio модель. 3. Включите �ервер: вкладка Developer → Start Server. 4. �ажмите «Проверить и продолжить».» + +### (г) Следующие партии: автоперевод и к�ш + +1. Человек открывает другую партию � комментари�ми на немецком. **С** �разу «Перевод… 0 из 25 · О�тановить» — без вопро�ов. +2. Пока идёт перевод, можно ходить по партии, �мотреть «Справку», анализировать: перевод в фоне. +3. Открыта друга� парти� до окончани� — задача прежней о�танавливает�� (`Job` уничтожает��); готовое уже в к�ше. При возврате к прежней партии готовое показывает�� �разу, о�тальное переводит�� дальше. +4. Парти�, переведённа� раньше (тот же комментарий в любой базе): в�ё из к�ша → **С** �разу «Машинный перевод (DeepSeek) · [Оригинал | Перевод]», под�казка «Показан �охранённый перевод — ничего не отправл�ло�ь». Работает без �ети и даже по�ле выхода из ChatGPT. +5. Парти� на �зыке интерфей�а — �троки нет. +6. Целевой �зык �менили в �а�тройках — открыта� парти� �разу переводит�� на новый �зык (тот же автоперевод; переводы на прежний �зык о�тают�� в к�ше). + +### (д) Оригинал / перевод + +1. Щелчок по «Оригинал» в **С**, или Ctrl+Shift+T, или ☰ → «Показать оригинал». Комментарии �разу оригинальные, значки «⇄» и�чезают. +2. Ещё раз — обратно к переводу. +3. Один комментарий можно �верить без переключени�: наведите на «⇄» — под�казка � оригиналом. +4. «Копировать PGN» (📋, Ctrl+Shift+C, ☰) копирует оригинал; е�ли включён режим «Перевод», то�т: «PGN �копирован (комментарии — в оригинале)». + +### (е) Ошибки по�реди перевода + +Общее: готовое о�таёт�� на �кране и в к�ше; непереведённые комментарии показывают�� в оригинале; переключатель о�таёт��, е�ли переведено хоть что-то. + +1. **Лимит ChatGPT.** Перевод о�танавливает��. **С**: «⚠ Лимит подпи�ки ChatGPT дл� ChessPenguin и�черпан. Когда он во��тановит��, видно в на�тройках ChatGPT.» · [�а�тройки ChatGPT ↗] · [Другой �по�об] · Подробно�ти. «Другой �по�об» открывает **К** � выбранным «ключ API». Врем� во��тановлени� не угадываем. При �ледующем открытии партии (автоперевод) — одна попытка; �нова лимит — та же �трока. +2. **�ет интернета.** Строка �покойна�, без ⚠ и цвета предупреждени�: «�ет �в�зи � DeepSeek. Переведём, когда �в�зь по�вит��.» · [Повторить]. Сами не повтор�ем; �ледующее открытие партии — нова� попытка. +3. **Серви� про�ит подождать (429).** Пока идёт от�чёт из `WAITING` — «Серви� про�ит подождать… 20 � · О�тановить». По�ле трёх ожиданий — «⚠ Серви� перегружен. Уже переведённое �охранено.» · [Повторить]. +4. **Ключ не подошёл (401).** «⚠ Ключ не подошёл. Возможно, он �копирован не полно�тью или удалён на �айте.» · [�а�тройки перевода] — открывает **�**, фоку� в поле ключа. +5. **�ет денег (DeepSeek 402).** «⚠ �а �чёте DeepSeek закончили�ь деньги. Пополните балан� на �айте.» · [Открыть �айт ↗]. +6. **Ollama не отвечает.** «⚠ Ollama не отвечает. Запу�тите Ollama и нажмите «Повторить».» · [Повторить]. +7. **Ча�ть комментариев не перевела�ь** (`Event::Bad`: ответ потер�л или изменил ходы, пу�той). По�ле `Finished`: «Переведено: 37 из 40, не удало�ь: 3 ⚠» · [Повторить] · [Оригинал | Перевод]. В нотации у �тих трёх — значок «⚠» (§3.6). «Повторить» отправл�ет только их, по одному. В к�ш неудачные не пишут��, по�тому при �ледующем открытии партии в автоперевод они попадут �нова. +8. **Вход в ChatGPT больше не дей�твует** (отозван, обновл�ющий токен и�тёк — 30 дней без и�пользовани�). «⚠ Вход в ChatGPT больше не дей�твует. Войдите �нова.» · [Войти �нова] — �разу браузер (шаг (а) 3), окно **К** не открывает��; ожидание показывает�� в **С**. + +Полный перечень — §4. + +### (ж) Выход, �мена �ерви�а, отзыв разрешени� (�а�тройки → Перевод) + +1. **Выйти из ChatGPT.** «Выйти» р�дом � аккаунтом. Без подтверждени�. Токены удал�ют�� из хранилища паролей, `account` очищает��, `"chatgpt"` убирает�� из разрешённых. `client_id` и `host_id` о�тают�� (�то не �екреты, новый вход их переи�пользует). Под �трокой — ��ылка «Управл�ть до�тупом на �айте OpenAI ↗» (там можно отозвать до�туп �ов�ем). Открыта� парти�: е�ли шёл перевод — он о�танавливает��; к�ш виден как прежде. +2. **Сменить �по�об** (радио ChatGPT ↔ ключ API) или **�ерви�** в �пи�ке. Примен�ет�� �разу (на�тройки �охран�ют�� при изменении, как везде). Идущий перевод о�танавливает��. Е�ли новый �ерви� ещё не разрешён, �ледующий перевод начнёт�� � **Сг**: в открытой партии **С** покажет «Предложение», «Переве�ти» → **Сг**. Ключи у каждого �ерви�а �вои (`Credentials.keys` по `Preset::id`), �мена �ерви�а ключ не �тирает. +3. **Отозвать разрешение.** Строка «Разрешено отправл�ть комментарии: ChatGPT ✕ · DeepSeek ✕». ✕ у �ерви�а убирает его из `allowed`; режим «Переводить �разу» о�таёт��, но дл� �того �ерви�а �нова понадобит�� **Сг**. Под�казка у ✕: «Больше не отправл�ть комментарии в {service}». +4. **Очи�тить �охранённые переводы.** «Очи�тить» → на ме�те кнопки «Удалить в�е �охранённые переводы? [Отмена] [Удалить]» (как удаление движка). Открыта� парти� переключает�� на оригинал и, в автопереводе, переводит�� заново. + +### (з) Человек отказывает�� и не хочет предложений + +1. В **С** «Предложение» нажимает ✕ — �трока �крывает�� дл� �той партии (до её �ледующего открыти�). +2. Счётчик отказов `declined` (в на�тройках, не �бра�ывает��) ра�тёт на 1. +3. �ачина� �о второго отказа «Предложение» �одержит ещё ��ылку «�е предлагать». +4. «�е предлагать» → режим «�ичего не делать», то�т: «Перевод больше не предлагает��. Вернуть: �а�тройки → Перевод.» +5. Переве�ти в�ё же можно: ☰ → «Переве�ти комментарии» (пункт е�ть, е�ли у партии е�ть план). Выбор в ☰ режим не мен�ет — переводит�� только �та парти� (� �огла�ием, е�ли нужно). +6. Отказ в **К** или **Сг** («✕», «Отмена», Esc) — то же, что ✕ в �троке: �крыть дл� �той партии, `declined += 1`. + +### (и) Вход через ChatGPT: что прои�ходит на каждом шаге + +Где вход начинает�� — только в трёх ме�тах: **К** («Войти через ChatGPT»), **�** («Войти через ChatGPT» / «Войти �нова»), **С** в ошибке «Вход больше не дей�твует» («Войти �нова»). Везде один и тот же проце�� и одно �о�то�ние ожидани� (одновременно идёт не больше одного входа; повторное нажатие показывает уже идущее ожидание). + +1. **Подготовка.** Слушатель `TcpListener` на `127.0.0.1:0` (порт выбирает �и�тема) в отдельном потоке; PKCE (`code_verifier` / `S256`), `state`; при первом входе `client_id=dynamic_agent_client`, `agent_name_hint=ChessPenguin`. �е удало�ь открыть �лушатель → «⚠ �е удало�ь подготовить вход: ChessPenguin не может прин�ть ответ браузера.» · Подробно�ти · [Попробовать ещё раз]. +2. **Браузер.** `ctx.open_url` / �и�темный �по�об (во Flatpak — через портал). Программа не знает, открыл�� ли браузер, по�тому ��ылка «Браузер не открыл��? Скопировать ��ылку» видна в�егда в �о�то�нии ожидани�. Щелчок кладёт полный адре� входа в буфер, р�дом на 2 � «Скопировано», и �трока-под�казка «В�тавьте ��ылку в адре�ную �троку браузера». +3. **Ожидание.** Со�то�ние §3.3. Окно **К** можно закрыть — ожидание продолжает�� в **С** (е�ли открыта парти�) и в **�**. «Отмена» закрывает �лушатель; е�ли браузер потом в�ё же вернёт��, он покажет �вою ошибку �оединени� — �то допу�тимо. +4. **Таймаут — 10 минут.** Слушатель закрывает��; в **К** / **�** / **С**: «Вход не завершён за 10 минут.» · [Попробовать ещё раз]. +5. **Человек отказал на �айте** (`error=access_denied`). Страница в браузере «Вход отменён» (§3.7). В программе: «Вход отменён в браузере.» · [Попробовать ещё раз], **К** о�таёт�� на выборе �по�оба. +6. **�еверный `state` или ошибка обмена кода.** Страница «�е удало�ь завершить вход». В программе: «⚠ �е удало�ь завершить вход.» · Подробно�ти · [Попробовать ещё раз]. +7. **У�пех, но без права ра�ходовать лимит подпи�ки** (в выданных правах нет `chatgpt.tokens.use.direct`). Вход �охран�ет�� (аккаунт виден в **�**), но перевод через ChatGPT невозможен. Страница «Вход выполнен, но без разрешени�…». В программе: «⚠ Вы вошли, но не разрешили ChessPenguin ра�ходовать лимит подпи�ки. Без �того перевод через ChatGPT не работает.» · [Войти �нова] · [И�пользовать ключ API]. Под�казка у «Войти �нова»: «�а �айте OpenAI о�тавьте разрешение на и�пользование подпи�ки включённым». +8. **У�пех.** Страница «Готово». Затем пробный запро� (п. (а) 6). +9. **Бе�платный аккаунт или аккаунт, которому �то недо�тупно** (`subscription_sharing_user_not_eligible`, 403 — у пробного запро�а или позже): «⚠ Этот аккаунт ChatGPT не может переводить в ChessPenguin: нужна подпи�ка Plus или Pro.» · [И�пользовать ключ API] · [Войти другим аккаунтом]. Вход �охран�ет�� (подпи�ку могут купить позже); в **�** под аккаунтом — та же �трока. +10. **Токены.** До�тупа — около ча�а, обновл�ет�� молча перед запро�ом или по�ле 401; обновл�ющий ротирует�� (замен�ть оба �разу); 30 дней без и�пользовани� — п. (е) 8. +11. **Повторный заход браузера** на тот же адре� (обновили вкладку) до закрыти� �лушател� — �траница «Этот вход уже завершён. Вкладку можно закрыть.». + +## 3. Макеты и �о�то�ни� + +### 3.1. Строка над нотацией + +Ме�то: `side_panel`, внутри `CentralPanel`, �разу по�ле `ui.separator()` под вкладками, **только на вкладке «�отаци�»**, вне `ScrollArea` (не уезжает при прокрутке). `egui::Frame` � `faint_bg_color`, внутренний от�туп 8×4, вы�ота одной �троки 26. Слева тек�т �о�то�ни� (обычный цвет; ⚠-�о�то�ни� — `warn_fg_color` у значка и тек�та), �права налево: ✕ (`widgets::small_close_button`), переключатель, кнопки. Е�ли ширина панели < 360 — две �троки: тек�т �верху, кнопки и переключатель �низу (выравнивание вправо). + +Переключатель — два `selectable_label` в рамке, как «Тёмна� / Светла�» во вкладке «Интерфей�». + +``` +Предложение +┌──────────────────────────────────────────────────────────────� +│ Комментарии на другом �зыке (англий�кий) [Переве�ти] ✕ │ +└──────────────────────────────────────────────────────────────┘ +Предложение по�ле второго отказа +│ Комментарии на другом �зыке (англий�кий) [Переве�ти] �е предлагать ✕ │ + +Больша� парти� (автоперевод не начат �ам) +│ Много комментариев на другом �зыке (англий�кий), │ +│ ≈ 120 ты�. �имволов [Переве�ти] ✕ │ + +Ждём вход +│ ◌ Ждём вход в браузере… Отмена │ + +Идёт +│ ◌ Перевод… 12 из 40 О�тановить [Оригинал|▣Перевод] │ +│ ▂▂▂▂▂▂▂▂▂▂������������������������� (поло�а 3 pt, при total > 40) │ + +Локальна� модель загружает�� +│ ◌ Модель загружает�� в пам�ть — �то бывает до минуты… О�тановить │ + +Ждём по про�ьбе �ерви�а +│ ◌ Серви� про�ит подождать… 20 � О�тановить [Оригинал|Перевод] │ + +Готово +│ Машинный перевод (DeepSeek) [Оригинал|▣Перевод] │ + +Ча�тично +│ ⚠ Переведено: 37 из 40, не удало�ь: 3 Повторить [Оригинал|▣Перевод] │ + +О�тановлено (кнопкой) +│ Переведено: 12 из 40 Продолжить [Оригинал|▣Перевод] │ + +�ет �в�зи (�покойно, без ⚠) +│ �ет �в�зи � DeepSeek. Переведём, когда �в�зь по�вит��. Повторить [Оригинал|Перевод] ✕ │ + +Ошибка +│ ⚠ Ключ не подошёл. Возможно, он �копирован не полно�тью │ +│ или удалён на �айте. [�а�тройки перевода] Подробно�ти ✕ │ +│ ┌ (по�ле «Подробно�ти») ─────────────────────────────────� │ +│ │ HTTP 401: Authentication Fails … [Копировать] │ │ +│ └────────────────────────────────────────────────────────┘ │ + +Вход �охранён, перевод из к�ша ча�тичный, подключение не готово +│ Переведено: 30 из 40 [�а�троить перевод] [Оригинал|▣Перевод] │ +``` + +Правила: + +- «◌» — `egui::Spinner` размером � тек�т. +- Кнопка �ледующего шага в ошибке — обычна� кнопка � тек�том; «Подробно�ти» — ��ылка, ра�крывает моноширинный выдел�емый блок под �трокой � кнопкой «Копировать» (тек�т `Failure` + ответ �ерви�а). Блок закрывает�� повторным щелчком. +- ✕ е�ть в «Предложении», «Большой партии», ошибках и «�ет �в�зи». В рабочих и готовых �о�то�ни�х ✕ нет (там е�ть переключатель; убирать нечего). +- Под�казка на тек�те «Готово»: «Переведено: {n} из {total}. Отправлено �ейча�: ≈ {k} ты�. �имволов. В файл PGN перевод не запи�ывает��.»; е�ли в�ё из к�ша — «Показан �охранённый перевод — ничего не отправл�ло�ь. В файл PGN перевод не запи�ывает��.» +- Под�казка на «Переве�ти» в «Предложении», е�ли подключение готово и разрешено: «Переве�ти через {service}». Е�ли нет: «Выбрать, как переводить». +- Esc перевод не о�танавливает (Esc в партии уже зан�т), только «О�тановить». +- «Продолжить» и «Повторить» запу�кают задачу только по о�тавшим�� / неудачным тек�там. + +Что делает «Переве�ти»: подключение не готово (`!ready()`) → **К**; готово, но не разрешено (`!allowed()`) → **Сг**; иначе — перевод. Дл� «Большой партии» по�ле «Переве�ти» дополнительных вопро�ов нет. + +### 3.2. Окно «Как переводить?» (К) + +`egui::Window`, не модальное, ширина 460, по центру, `collapsible(false)`, закрывает�� ✕ и Esc (когда фоку� не в поле ввода). Открывает�� из **С** («Переве�ти» без готового подключени�), из ☰ → «Переве�ти комментарии» и из ошибок «Другой �по�об» / «И�пользовать ключ API». Одно окно на программу; е�ли оно открыто дл� одной партии, а человек открыл другую — окно о�таёт��, перевод по�ле на�тройки начнёт�� в той партии, котора� открыта в момент �огла�и�. + +Шаг 1 — выбор (по умолчанию выбран ChatGPT): + +``` +┌ Как переводить? ────────────────────────────────────────── ✕ � +│ Комментарии переводит �зыкова� модель. Выберите, какую: │ +│ │ +│ � У мен� е�ть ChatGPT Plus или Pro │ +│ Проще в�его: войдите, ключ не нужен. │ +│ Ра�ходует ча�ть лимита подпи�ки. │ +│ │ +│ ○ Подпи�ки нет — ключ API │ +│ Серви� � ключом или модель на �том компьютере. │ +│ │ +│ Дальше комментарии на других �зыках будут переводить�� �ами, │ +│ когда вы открываете партию. Изменить: �а�тройки → Перевод. │ +│ │ +│ [ Отмена ] [■ Войти через ChatGPT ] │ +└───────────────────────────────────────────────────────────────┘ +``` + +Шаг 1, выбран «ключ API» (вариант ра�крывает�� под радио; пример — DeepSeek): + +``` +│ ○ У мен� е�ть ChatGPT Plus или Pro │ +│ � Подпи�ки нет — ключ API │ +│ Серви�: [DeepSeek ▾] │ +│ 1. Откройте �айт DeepSeek ↗ и войдите. │ +│ 2. Пополните балан�: DeepSeek работает по предоплате. │ +│ 3. �ажмите «Create new API key» и �копируйте ключ — │ +│ его показывают один раз. │ +│ 4. В�тавьте ключ �юда: │ +│ Ключ: [sk-•••••••••••••••••••••• ] � │ +│ ✓ Работает: «The knight is strong» → «Конь �илён» │ +│ │ +│ Дальше комментарии … �а�тройки → Перевод. │ +│ [ Отмена ] [■ Проверить и продолжить ] │ +``` + +Спи�ок «Серви�» (пор�док фик�ирован): «DeepSeek», «OpenAI», «Google Gemini», «Ollama — на �том компьютере», «LM Studio — на �том компьютере», «Свой адре�». + +Шаги по �ерви�ам: + +| Серви� | Шаги | О�обое | +|---|---|---| +| DeepSeek | как в макете; ��ылка — `Preset::key_page` | — | +| OpenAI | 1. Откройте �айт OpenAI ↗ и войдите. 2. Пополните балан� в разделе Billing. 3. �ажмите «Create new secret key» и �копируйте ключ. 4. В�тавьте ключ �юда: | �трока приглушённо: «Ключ API оплачивает�� отдельно от подпи�ки ChatGPT.» | +| Google Gemini | 1. Откройте Google AI Studio ↗ и войдите � аккаунтом Google. 2. �ажмите «Create API key» и �копируйте ключ. 3. В�тавьте ключ �юда: | �трока `warn_fg_color`: «Бе�платно � аккаунтом Google, но Google может и�пользовать тек�ты дл� обучени� �воих моделей.» | +| Ollama | §2 (в) 3 | пол� ключа нет; по�ле проверки — «Модель: [▾]» | +| LM Studio | §2 (в), абзац LM Studio | пол� ключа нет; по�ле проверки — «Модель: [▾]» | +| Свой адре� | «�дре�: [https://…/v1]», «Ключ (е�ли нужен): [ ]», «Модель: [ ]» | под�казка у адре�а: «�дре� �ерви�а, �овме�тимого � OpenAI, вме�те � /v1». �дре� `127.0.0.1` / `localhost` / `::1` — без �огла�и�, о�тальные — � �огла�ием | + +Со�то�ни� кнопки и проверки: + +- «Проверить и продолжить» неактивна, пока ключ пу�т (дл� �ерви�ов � ключом) или адре� пу�т («Свой адре�»); под�казка неактивной: «Сначала в�тавьте ключ». +- Во врем� проверки — кнопка неактивна, под полем «◌ Провер�ю…». +- Ошибка — под полем �трокой `warn_fg_color`, тек�ты §4; поле не очищает��. +- У�пех — «✓ Работает: «{пример}» → «{перевод}»» и через 1 � (чтобы у�пели увидеть) — шаг 3 (�огла�ие) или, дл� локального адре�а, закрытие окна и начало перевода. +- Пример дл� проверки: англий�ка� фраза «The knight is strong on d5.»; е�ли целевой �зык англий�кий — немецка� «Der Springer ist auf d5 stark.». Это не тек�ты пользовател�, �огла�и� не требует. + +Шаг 2 — ожидание входа (§3.3), шаг 3 — �огла�ие (§3.4) в том же окне: заголовок окна мен�ет�� на «Отправл�ть комментарии в {service}?», кнопки — «�азад» и «Переводить». + +### 3.3. Ожидание входа в браузере + +В **К** (то же �одержимое в **�**, в блоке ChatGPT): + +``` +┌ Как переводить? ────────────────────────────────────────── ✕ � +│ ◌ Ждём вход в браузере… │ +│ │ +│ В браузере открыла�ь �траница OpenAI. Войдите в аккаунт │ +│ ChatGPT и разрешите до�туп дл� ChessPenguin. Потом верните�ь │ +│ �юда — в�ё продолжит�� �амо. │ +│ │ +│ Браузер не открыл��? Скопировать ��ылку │ +│ (по�ле щелчка:) Скопировано. В�тавьте ��ылку в адре�ную │ +│ �троку браузера. │ +│ │ +│ Это окно можно закрыть: вход продолжит��. │ +│ [ Отмена ] │ +└───────────────────────────────────────────────────────────────┘ +``` + +По�ле возврата из браузера: «◌ Провер�ю подпи�ку…» (пробный запро�), затем �огла�ие или ошибка (§2 (и) 5–9) на ме�те тек�та, � кнопками �ледующего шага �права внизу. + +### 3.4. Окно �огла�и� (Сг) + +Показывает�� один раз на �ерви� (`allowed`), перед первой отправкой. Как отдельное окно — `egui::Modal`, ширина 440, кнопки �права налево (как «�нализ партии»); как шаг 3 окна **К** — то же �одержимое. + +``` +┌ Отправл�ть комментарии в DeepSeek? ──────────────────────────� +│ Дл� перевода в DeepSeek (api.deepseek.com) будут отправлены: │ +│ • тек�ты комментариев — в �той партии 40, ≈ 12 ты�. �имволов;│ +│ • имена игроков, турнир и дебют — дл� точных терминов. │ +│ Ходы партии не отправл�ют��; ходы, запи�анные в комментари�х, │ +│ — отправл�ют��. │ +│ Как DeepSeek хранит данные: политика конфиденциально�ти ↗ │ +│ │ +│ Дальше комментарии на других �зыках будут переводить�� �ами, │ +│ когда вы открываете партию. Отключить или отозвать разрешение:│ +│ �а�тройки → Перевод. │ +│ [ Отмена ] [■ Переводить ]│ +└───────────────────────────────────────────────────────────────┘ +``` + +- Дл� ChatGPT: «Отправл�ть комментарии в ChatGPT?», «Дл� перевода в ChatGPT (OpenAI) будут отправлены: …», ��ылка — политика OpenAI; добавл�ет�� �трока «Перевод ра�ходует ча�ть лимита вашей подпи�ки.» +- Дл� «Свой адре�» — им� хо�та вме�то названи� �ерви�а, �троки о политике нет. +- С�ылки на политики — кон�танты в `Preset` (новое поле), перед выпу�ком проверить. +- Enter = «Переводить», Esc = «Отмена». Фоку� — на «Переводить». +- «Отмена» — §2 (з) 6. + +### 3.5. �а�тройки → «Перевод» + +**Решение:** нова� вкладка «Перевод» между «Интерфей�» и «О программе». Почему не «Интерфей�»: там два коротких выбора (�зык, тема), а зде�ь вход в аккаунт, ключи, разрешени� и к�ш — �то отдельна� тема � �об�твенными ошибками; во вкладке «Интерфей�» она бы занимала три четверти ме�та и пр�тала �зык интерфей�а. С�ылки «�а�тройки → Перевод» в тек�тах ведут �юда (`SettingsAction` / `Tab::Translation`, фоку� при необходимо�ти — в поле ключа). + +``` + Движки | До�ка и фигуры | Звук | Интерфей� | ▣Перевод | О программе +────────────────────────────────────────────────────────────────────── + Комментарии партий на других �зыках переводит �зыкова� модель. + Ходы не перевод�т��. В файлы PGN перевод не запи�ывает��. (приглушённо) + + Переводить на: [Ру��кий ▾] + + Когда комментарии на другом �зыке: + � Переводить �разу ○ Спрашивать ○ �ичего не делать + + Как переводить (жирный) + � Вход через ChatGPT + Дл� подпи�ки Plus или Pro. Ра�ходует ча�ть её лимита. (приглушённо) + ┌ �о�то�ние ChatGPT (�м. ниже) � + ○ Ключ API + Серви�: [DeepSeek ▾] + Ключ: [•••••••••••••••• ] � [Проверить] + Получить ключ на �айте DeepSeek ↗ + ▸ Дополнительно + �дре�: [https://api.deepseek.com ] + Модель: [deepseek-chat ▾] + ✓ Работает: «The knight is strong» → «Конь �илён» + + Разрешено отправл�ть комментарии: ChatGPT ✕ DeepSeek ✕ + (е�ли пу�то:) Пока никуда. (приглушённо) + + Сохранённые переводы: 1,2 МБ [Очи�тить] + Чтобы переведённые партии открывали�ь без �ети и без ра�хода. (приглушённо) + + ⚠ Ключ хранит�� в файле, а не в хранилище паролей �и�темы. (только без хранилища) +``` + +Блок ChatGPT по �о�то�ни�м (виден под радио, даже е�ли выбран «Ключ API», но тогда приглушён): + +``` +не вошли: [Войти через ChatGPT] +ждём браузер: ◌ Ждём вход в браузере… [Отмена] Браузер не открыл��? Скопировать ��ылку +провер�ем: ◌ Провер�ю подпи�ку… +вошли: Вы вошли: {account} · Выйти + Управл�ть до�тупом на �айте OpenAI ↗ + ✓ Работает, модель {model} (по�ле проверки) +без разрешени�: Вы вошли: {account} · Выйти + ⚠ Вы не разрешили ChessPenguin ра�ходовать лимит подпи�ки. [Войти �нова] +нет подпи�ки: Вы вошли: {account} · Выйти + ⚠ Этому аккаунту нужна подпи�ка Plus или Pro. +лимит: ⚠ Лимит подпи�ки дл� ChessPenguin и�черпан. �а�тройки ChatGPT ↗ +вход у�тарел: ⚠ Вход больше не дей�твует. [Войти �нова] +``` + +Правила: + +- Выбор радио «Вход через ChatGPT» без входа — допу�тим (�охран�ет��), блок показывает «Войти через ChatGPT». +- Дл� Ollama / LM Studio �троки «Ключ» и «Получить ключ» замен�ют�� на «Модель: [▾] [Проверить]»; �пи�ок моделей загружает�� при открытии вкладки и по «Проверить»; Ollama не отвечает — под �трокой «⚠ Ollama не отвечает. Запу�тите Ollama и нажмите «Проверить».». +- Дл� «Свой адре�» «�дре�» и «Модель» видны �разу (не в «Дополнительно»), ключ — «Ключ (е�ли нужен)». +- Дл� Gemini под �ерви�ом — та же �трока-предупреждение, что в **К**. +- Модель ChatGPT выбирает�� автоматиче�ки по `GET /v1/models`; выбора в интерфей�е нет (§6). +- «Переводить на» — 6 �зыков интерфей�а, по умолчанию — �зык интерфей�а (пункт «Как в интерфей�е ({�зык})» первым). +- Поле ключа: `password(true)`, � показывает ключ, пока нажат переключатель. Изменение ключа �бра�ывает �троку «✓ Работает». +- Строка «Ключ хранит�� в файле…» � под�казкой: «В �и�теме нет хранилища паролей (Secret Service). Ключ лежит в файле на�троек, до�тупном только вашей учётной запи�и.» + +### 3.6. Пометки в нотации + +**Переведённый комментарий-блок** (`comment_block`): �права внутри рамки — значок «⇄» 11 pt цветом `weak_text_color`, у верхнего кра�; правый внутренний от�туп блока дл� таких комментариев 22 вме�то 10, чтобы тек�т не заходил под значок. Значок — отдельный `Response` (`Sense::hover()`), под�казка только на нём, по�тому щелчки по �о�едним ходам не �традают. + +``` +┌────────────────────────────────────────────────────────────� +│ Белые могли �ыграть 23.Лd1, �охран�� давление по ⇄ │ +│ линии d. │ +└────────────────────────────────────────────────────────────┘ + под�казка на «⇄»: + ┌──────────────────────────────────────────� + │ Машинный перевод. Оригинал: │ + │ White could play 23.Rd1, keeping the │ + │ pressure on the d-file. │ + └──────────────────────────────────────────┘ +``` + +Ходы внутри комментариев возвращают�� ровно как в оригинале (`same_moves`); пример выше — лишь иллю�траци� ме�та значка. + +- Под�казка: перва� �трока «Машинный перевод. Оригинал:», далее оригинал по�ле `comment_text()` (� той же переформатировкой абзацев), шириной до 360, обрезка по�ле 1 000 �имволов � «…». +- **Комментарий в варианте** (`inline_line`, тек�т в �троке): по�ле тек�та — маленька� метка «⇄» (`small().weak()`), та же под�казка. +- **Ещё не переведён** (в очереди, пока идёт задача): оригинал и значок «⋯» `weak`, под�казка «Переводит��…». +- **�е удало�ь** (`Event::Bad`): оригинал, значок «⚠» цветом `warn_fg_color`, под�казка «Этот комментарий не удало�ь переве�ти — показан оригинал. �ажмите «Повторить» в �троке над нотацией.». +- Узел � не�колькими комментари�ми (`comments_after()` �клеивает�� в один блок): значок «⇄», е�ли переведён хот� бы один; «⚠», е�ли хоть один не удал�� (⚠ важнее ⇄). +- В режиме «Оригинал» значков нет. +- Комментарии только из команд `[%…]` не мен�ют�� и не помечают�� (их нет в плане). + +### 3.7. Страница во вкладке браузера + +Отдаёт �ам ChessPenguin �о `127.0.0.1` по�ле обмена кода. Один HTML без внешних ре�ур�ов (�тили в�троены, �ветла� и тёмна� тема по `prefers-color-scheme`), на �зыке интерфей�а (``), заголовок вкладки «ChessPenguin». Вкладку не закрываем �криптом (браузеры не дают). Содержимое: название «ChessPenguin», крупный заголовок, одна-две �троки тек�та. + +``` +┌──────────────────────────────────────────� +│ ChessPenguin │ +│ │ +│ ✓ Вы вошли в ChatGPT │ +│ Верните�ь в ChessPenguin — перевод │ +│ продолжит�� там. Эту вкладку можно │ +│ закрыть. │ +└──────────────────────────────────────────┘ +``` + +| Случай | Заголовок | Тек�т | +|---|---|---| +| у�пех | «✓ Вы вошли в ChatGPT» | «Верните�ь в ChessPenguin — перевод продолжит�� там. Эту вкладку можно закрыть.» | +| без права на лимит | «Вход выполнен, но без разрешени�» | «Вы не разрешили ChessPenguin ра�ходовать лимит подпи�ки, по�тому перевод через ChatGPT не заработает. Верните�ь в ChessPenguin: там можно войти �нова или выбрать ключ API.» | +| отказ на �айте | «Вход отменён» | «Верните�ь в ChessPenguin. Эту вкладку можно закрыть.» | +| ошибка | «�е удало�ь завершить вход» | «Верните�ь в ChessPenguin и попробуйте ещё раз.» | +| повторный заход | «Этот вход уже завершён» | «Эту вкладку можно закрыть.» | + +### 3.8. Меню ☰ + +�овые пункты в меню ☰ панели кнопок, по�ле «Сохранить партию как…»: + +- «Переве�ти комментарии» — е�ли у партии е�ть план, ничего не переведено и задача не идёт. Дей�твует как «Переве�ти» в **С** (и когда �трока �крыта ✕ или режим «�ичего не делать»). +- «Показать оригинал (Ctrl+Shift+T)» / «Показать перевод (Ctrl+Shift+T)» — е�ли переведено хоть что-то. +- «�а�тройки перевода…» — в�егда; открывает **�**. + +## 4. Ошибки: тек�т и �ледующий шаг + +`Failure` → �трока в **С** (а также под полем в **К** / **�**, е�ли ошибка �лучила�ь при проверке). + +| `Failure` | Тек�т (RU) | Кнопка | +|---|---|---| +| `Key` | ⚠ Ключ не подошёл. Возможно, он �копирован не полно�тью или удалён на �айте. | �а�тройки перевода | +| `Money` | ⚠ �а �чёте {service} закончили�ь деньги. Пополните балан� на �айте. | Открыть �айт ↗ (`key_page`) | +| ожидание (`WAITING` > 0) | Серви� про�ит подождать… {s} � | О�тановить | +| `RateLimited` | ⚠ Серви� перегружен. Уже переведённое �охранено. | Повторить | +| `PlanLimit` | ⚠ Лимит подпи�ки ChatGPT дл� ChessPenguin и�черпан. Когда он во��тановит��, видно в на�тройках ChatGPT. | �а�тройки ChatGPT ↗ · Другой �по�об | +| `NotEligible` | ⚠ Этот аккаунт ChatGPT не может переводить в ChessPenguin: нужна подпи�ка Plus или Pro. | И�пользовать ключ API | +| `SignedOut` | ⚠ Вход в ChatGPT больше не дей�твует. Войдите �нова. | Войти �нова | +| `Offline` | �ет �в�зи � {service}. Переведём, когда �в�зь по�вит��. (без ⚠) | Повторить | +| `LocalDown` | ⚠ {service} не отвечает. Запу�тите {service} и нажмите «Повторить». | Повторить | +| `NoModel` (Ollama) | ⚠ В Ollama нет модели {model}. Скачайте её командой: ollama pull {model} | Копировать команду | +| `NoModel` (другие) | ⚠ У {service} нет модели {model}. Выберите другую в на�тройках перевода. | �а�тройки перевода | +| `Service` | ⚠ Серви� ответил ошибкой ({code}). | Повторить | +| `Bad` (ча�ть) | ⚠ Переведено: {n} из {total}, не удало�ь: {bad} | Повторить | + +У в�ех ⚠-�трок — «Подробно�ти» (тек�т `Failure` через `Display`, у `Service` — тело ответа). «�а�тройки ChatGPT ↗» открывает `https://chatgpt.com/#settings` (адре� раздела � лимитом проверить перед выпу�ком; не угадывать дату во��тановлени�). + +## 5. Тек�ты (англий�кий — ключ i18n) + +Правила: без �клонени� названий �зыков — �зык в�егда в именительном падеже в �кобках; чи�ла через «{n} из {total}» и «≈ {k} ты�.», чтобы не нужны были формы множе�твенного чи�ла. �азвани� �зыков: ключи `tr(whatlang::Lang::eng_name())` — дл� �зыков из таблицы перевод�т��, дл� о�тальных `tr()` вернёт англий�кое название. В таблицу `i18n.rs` вне�ти названи� ≥ 20 �зыков (English, German, French, Spanish, Italian, Portuguese, Dutch, Russian, Ukrainian, Polish, Czech, Hungarian, Swedish, Danish, Bokmal, Finnish, Turkish, Romanian, Bulgarian, Serbian, Croatian, Greek, Chinese (Mandarin), Japanese) — �о �трочной буквы в ру��ком: «англий�кий». �овые и�ходные файлы добавить в �пи�ок те�та `all_used_keys_are_translated`. + +### Строка над нотацией и меню + +| EN (ключ) | RU | +|---|---| +| Comments in another language ({lang}) | Комментарии на другом �зыке ({lang}) | +| Many comments in another language ({lang}), about {k} thousand characters | Много комментариев на другом �зыке ({lang}), ≈ {k} ты�. �имволов | +| Translate | Переве�ти | +| Translate with {service} | Переве�ти через {service} | +| Choose how to translate | Выбрать, как переводить | +| Don't offer | �е предлагать | +| Never offer to translate comments. You can turn it back on in Settings → Translation. | Больше не предлагать перевод. Вернуть можно в �а�тройки → Перевод. | +| Hide for this game | Скрыть дл� �той партии | +| Translation will not be offered again. To turn it back on: Settings → Translation. | Перевод больше не предлагает��. Вернуть: �а�тройки → Перевод. | +| Waiting for sign-in in the browser… | Ждём вход в браузере… | +| Translating… {n} of {total} | Перевод… {n} из {total} | +| The model is loading into memory — this can take up to a minute… | Модель загружает�� в пам�ть — �то бывает до минуты… | +| The service asks to wait… {s} s | Серви� про�ит подождать… {s} � | +| Stop | О�тановить (е�ть) | +| Machine translation ({service}) | Машинный перевод ({service}) | +| Translated: {n} of {total}. Sent now: about {k} thousand characters. The translation is not written to the PGN file. | Переведено: {n} из {total}. Отправлено �ейча�: ≈ {k} ты�. �имволов. В файл PGN перевод не запи�ывает��. | +| Saved translation shown — nothing was sent. The translation is not written to the PGN file. | Показан �охранённый перевод — ничего не отправл�ло�ь. В файл PGN перевод не запи�ывает��. | +| Translated: {n} of {total}, failed: {bad} | Переведено: {n} из {total}, не удало�ь: {bad} | +| Translated: {n} of {total} | Переведено: {n} из {total} | +| Continue | Продолжить | +| Retry | Повторить (е�ть) | +| Set up translation | �а�троить перевод | +| Original | Оригинал | +| Translation | Перевод | +| Details | Подробно�ти (е�ть) | +| Copy | Копировать (е�ть) | +| Translate comments | Переве�ти комментарии | +| Show the original (Ctrl+Shift+T) | Показать оригинал (Ctrl+Shift+T) | +| Show the translation (Ctrl+Shift+T) | Показать перевод (Ctrl+Shift+T) | +| Translation settings… | �а�тройки перевода… | +| PGN copied (comments in the original) | PGN �копирован (комментарии — в оригинале) | + +### Пометки в нотации + +| EN | RU | +|---|---| +| Machine translation. Original: | Машинный перевод. Оригинал: | +| Translating… | Переводит��… | +| This comment could not be translated — the original is shown. Press "Retry" in the line above the notation. | Этот комментарий не удало�ь переве�ти — показан оригинал. �ажмите «Повторить» в �троке над нотацией. | +| Machine translation (им� дл� AccessKit у «⇄») | Машинный перевод | +| Not translated (им� дл� AccessKit у «⚠») | �е переведено | + +### Окно «Как переводить?» и ожидание входа + +| EN | RU | +|---|---| +| How to translate? | Как переводить? | +| Comments are translated by a language model. Choose which: | Комментарии переводит �зыкова� модель. Выберите, какую: | +| I have ChatGPT Plus or Pro | У мен� е�ть ChatGPT Plus или Pro | +| The easiest way: sign in, no key needed. | Проще в�его: войдите, ключ не нужен. | +| Uses part of your subscription's limit. | Ра�ходует ча�ть лимита подпи�ки. | +| No subscription — an API key | Подпи�ки нет — ключ API | +| A service with a key, or a model on this computer. | Серви� � ключом или модель на �том компьютере. | +| From now on, comments in other languages will be translated by themselves when you open a game. To change: Settings → Translation. | Дальше комментарии на других �зыках будут переводить�� �ами, когда вы открываете партию. Изменить: �а�тройки → Перевод. | +| Sign in with ChatGPT | Войти через ChatGPT | +| Check and continue | Проверить и продолжить | +| Paste the key first | Сначала в�тавьте ключ | +| Cancel | Отмена (е�ть) | +| Back | �азад | +| Service: | Серви�: | +| Key: | Ключ: | +| Key (if needed): | Ключ (е�ли нужен): | +| Address: | �дре�: | +| Model: | Модель: | +| The address of an OpenAI-compatible service, with /v1 | �дре� �ерви�а, �овме�тимого � OpenAI, вме�те � /v1 | +| Ollama — on this computer | Ollama — на �том компьютере | +| LM Studio — on this computer | LM Studio — на �том компьютере | +| Another address | Свой адре� | +| 1. Open the {service} website ↗ and sign in. | 1. Откройте �айт {service} ↗ и войдите. | +| 2. Top up the balance: DeepSeek works with prepayment. | 2. Пополните балан�: DeepSeek работает по предоплате. | +| 3. Press "Create new API key" and copy the key — it is shown only once. | 3. �ажмите «Create new API key» и �копируйте ключ — его показывают один раз. | +| 2. Top up the balance in the Billing section. | 2. Пополните балан� в разделе Billing. | +| 3. Press "Create new secret key" and copy the key. | 3. �ажмите «Create new secret key» и �копируйте ключ. | +| 1. Open Google AI Studio ↗ and sign in with your Google account. | 1. Откройте Google AI Studio ↗ и войдите � аккаунтом Google. | +| 2. Press "Create API key" and copy the key. | 2. �ажмите «Create API key» и �копируйте ключ. | +| Paste the key here: | В�тавьте ключ �юда: | +| The API key is paid separately from the ChatGPT subscription. | Ключ API оплачивает�� отдельно от подпи�ки ChatGPT. | +| Free with a Google account, but Google may use the texts to train its models. | Бе�платно � аккаунтом Google, но Google может и�пользовать тек�ты дл� обучени� �воих моделей. | +| 1. Install Ollama from ollama.com ↗ and start it. | 1. У�тановите Ollama � �айта ollama.com ↗ и запу�тите её. | +| 2. Download a model: | 2. Скачайте модель: | +| 3. Press "Check and continue". | 3. �ажмите «Проверить и продолжить». | +| 1. Install LM Studio from lmstudio.ai ↗. | 1. У�тановите LM Studio � �айта lmstudio.ai ↗. | +| 2. Download a model in LM Studio. | 2. Загрузите в LM Studio модель. | +| 3. Turn on the server: the Developer tab → Start Server. | 3. Включите �ервер: вкладка Developer → Start Server. | +| 4. Press "Check and continue". | 4. �ажмите «Проверить и продолжить». | +| There are no models in Ollama. Download one with the command below. | В Ollama нет моделей. Скачайте модель командой ниже. | +| Checking… | Провер�ю… | +| Checking the subscription… | Провер�ю подпи�ку… | +| ✓ Works: "{sample}" → "{result}" | ✓ Работает: «{sample}» → «{result}» | +| ✓ Works, model {model} | ✓ Работает, модель {model} | +| A page from OpenAI has opened in the browser. Sign in to your ChatGPT account and allow access for ChessPenguin. Then come back here — everything goes on by itself. | В браузере открыла�ь �траница OpenAI. Войдите в аккаунт ChatGPT и разрешите до�туп дл� ChessPenguin. Потом верните�ь �юда — в�ё продолжит�� �амо. | +| The browser did not open? Copy the link | Браузер не открыл��? Скопировать ��ылку | +| Copied. Paste the link into the browser's address bar. | Скопировано. В�тавьте ��ылку в адре�ную �троку браузера. | +| You can close this window: the sign-in goes on. | Это окно можно закрыть: вход продолжит��. | +| Sign-in was not finished in 10 minutes. | Вход не завершён за 10 минут. | +| Sign-in was cancelled in the browser. | Вход отменён в браузере. | +| ⚠ Sign-in could not be finished. | ⚠ �е удало�ь завершить вход. | +| ⚠ Sign-in could not be prepared: ChessPenguin cannot receive the browser's answer. | ⚠ �е удало�ь подготовить вход: ChessPenguin не может прин�ть ответ браузера. | +| ⚠ You signed in, but did not allow ChessPenguin to use the subscription's limit. Without it, translation with ChatGPT does not work. | ⚠ Вы вошли, но не разрешили ChessPenguin ра�ходовать лимит подпи�ки. Без �того перевод через ChatGPT не работает. | +| On the OpenAI site, leave the permission to use the subscription turned on | �а �айте OpenAI о�тавьте разрешение на и�пользование подпи�ки включённым | +| Sign in again | Войти �нова | +| Use an API key | И�пользовать ключ API | +| Sign in with another account | Войти другим аккаунтом | +| Try again | Попробовать ещё раз (е�ть) | + +### Окно �огла�и� + +| EN | RU | +|---|---| +| Send comments to {service}? | Отправл�ть комментарии в {service}? | +| To translate, these will be sent to {service} ({host}): | Дл� перевода в {service} ({host}) будут отправлены: | +| • comment texts — {n} in this game, about {k} thousand characters; | • тек�ты комментариев — в �той партии {n}, ≈ {k} ты�. �имволов; | +| • player names, the event and the opening — for accurate terms. | • имена игроков, турнир и дебют — дл� точных терминов. | +| The game's moves are not sent; moves written inside comments are. | Ходы партии не отправл�ют��; ходы, запи�анные в комментари�х, — отправл�ют��. | +| How {service} stores data: privacy policy ↗ | Как {service} хранит данные: политика конфиденциально�ти ↗ | +| Translation uses part of your subscription's limit. | Перевод ра�ходует ча�ть лимита вашей подпи�ки. | +| From now on, comments in other languages will be translated by themselves when you open a game. To turn it off or withdraw the permission: Settings → Translation. | Дальше комментарии на других �зыках будут переводить�� �ами, когда вы открываете партию. Отключить или отозвать разрешение: �а�тройки → Перевод. | +| Start translating | Переводить | + +Главна� кнопка �огла�и� — отдельный ключ "Start translating" → «Переводить», чтобы не путать � "Translate" → «Переве�ти» в �троке. + +### �а�тройки → Перевод + +| EN | RU | +|---|---| +| Translation | Перевод | +| Comments in other languages are translated by a language model. Moves are not translated. The translation is not written to PGN files. | Комментарии партий на других �зыках переводит �зыкова� модель. Ходы не перевод�т��. В файлы PGN перевод не запи�ывает��. | +| Translate into: | Переводить на: | +| As the interface ({lang}) | Как в интерфей�е ({lang}) | +| When comments are in another language: | Когда комментарии на другом �зыке: | +| Translate at once | Переводить �разу | +| Ask | Спрашивать | +| Do nothing | �ичего не делать | +| How to translate | Как переводить | +| Sign in with ChatGPT (радио) | Вход через ChatGPT | +| For a Plus or Pro subscription. Uses part of its limit. | Дл� подпи�ки Plus или Pro. Ра�ходует ча�ть её лимита. | +| API key (радио) | Ключ API | +| Get a key on the {service} website ↗ | Получить ключ на �айте {service} ↗ | +| Advanced | Дополнительно | +| Check | Проверить | +| You are signed in: {account} | Вы вошли: {account} | +| Sign out | Выйти | +| Manage access on the OpenAI site ↗ | Управл�ть до�тупом на �айте OpenAI ↗ | +| ⚠ You did not allow ChessPenguin to use the subscription's limit. | ⚠ Вы не разрешили ChessPenguin ра�ходовать лимит подпи�ки. | +| ⚠ This account needs a Plus or Pro subscription. | ⚠ Этому аккаунту нужна подпи�ка Plus или Pro. | +| ⚠ The subscription's limit for ChessPenguin is used up. | ⚠ Лимит подпи�ки дл� ChessPenguin и�черпан. | +| ChatGPT settings ↗ | �а�тройки ChatGPT ↗ | +| ⚠ The sign-in is no longer valid. | ⚠ Вход больше не дей�твует. | +| Comments may be sent to: | Разрешено отправл�ть комментарии: | +| Nowhere yet. | Пока никуда. | +| Stop sending comments to {service} | Больше не отправл�ть комментарии в {service} | +| Saved translations: {size} | Сохранённые переводы: {size} | +| Clear | Очи�тить | +| So that translated games open without the internet and without cost. | Чтобы переведённые партии открывали�ь без �ети и без ра�хода. | +| Delete all saved translations? | Удалить в�е �охранённые переводы? | +| Delete | Удалить | +| ⚠ The key is kept in a file, not in the system's password storage. | ⚠ Ключ хранит�� в файле, а не в хранилище паролей �и�темы. | +| The system has no password storage (Secret Service). The key is in the settings file, readable only by your account. | В �и�теме нет хранилища паролей (Secret Service). Ключ лежит в файле на�троек, до�тупном только вашей учётной запи�и. | + +### Ошибки + +| EN | RU | +|---|---| +| ⚠ The key was not accepted. Perhaps it was copied incompletely or deleted on the site. | ⚠ Ключ не подошёл. Возможно, он �копирован не полно�тью или удалён на �айте. | +| ⚠ The {service} account has run out of money. Top up the balance on the site. | ⚠ �а �чёте {service} закончили�ь деньги. Пополните балан� на �айте. | +| Open the site ↗ | Открыть �айт ↗ | +| ⚠ The service is overloaded. What is translated is saved. | ⚠ Серви� перегружен. Уже переведённое �охранено. | +| ⚠ The ChatGPT subscription's limit for ChessPenguin is used up. When it comes back is shown in the ChatGPT settings. | ⚠ Лимит подпи�ки ChatGPT дл� ChessPenguin и�черпан. Когда он во��тановит��, видно в на�тройках ChatGPT. | +| Another way | Другой �по�об | +| ⚠ This ChatGPT account cannot translate in ChessPenguin: a Plus or Pro subscription is needed. | ⚠ Этот аккаунт ChatGPT не может переводить в ChessPenguin: нужна подпи�ка Plus или Pro. | +| ⚠ The ChatGPT sign-in is no longer valid. Sign in again. | ⚠ Вход в ChatGPT больше не дей�твует. Войдите �нова. | +| No connection to {service}. We will translate when the connection is back. | �ет �в�зи � {service}. Переведём, когда �в�зь по�вит��. | +| ⚠ {service} does not answer. Start {service} and press "Retry". | ⚠ {service} не отвечает. Запу�тите {service} и нажмите «Повторить». | +| ⚠ Ollama has no model {model}. Download it with the command: ollama pull {model} | ⚠ В Ollama нет модели {model}. Скачайте её командой: ollama pull {model} | +| Copy the command | Копировать команду | +| ⚠ {service} has no model {model}. Choose another one in the translation settings. | ⚠ У {service} нет модели {model}. Выберите другую в на�тройках перевода. | +| ⚠ The service answered with an error ({code}). | ⚠ Серви� ответил ошибкой ({code}). | +| Translation settings | �а�тройки перевода | + +### Страница в браузере + +| EN | RU | +|---|---| +| ✓ You are signed in to ChatGPT | ✓ Вы вошли в ChatGPT | +| Go back to ChessPenguin — the translation goes on there. You can close this tab. | Верните�ь в ChessPenguin — перевод продолжит�� там. Эту вкладку можно закрыть. | +| Signed in, but without permission | Вход выполнен, но без разрешени� | +| You did not allow ChessPenguin to use the subscription's limit, so translation with ChatGPT will not work. Go back to ChessPenguin: you can sign in again there or choose an API key. | Вы не разрешили ChessPenguin ра�ходовать лимит подпи�ки, по�тому перевод через ChatGPT не заработает. Верните�ь в ChessPenguin: там можно войти �нова или выбрать ключ API. | +| Sign-in cancelled | Вход отменён | +| Go back to ChessPenguin. You can close this tab. | Верните�ь в ChessPenguin. Эту вкладку можно закрыть. | +| Sign-in could not be finished | �е удало�ь завершить вход | +| Go back to ChessPenguin and try again. | Верните�ь в ChessPenguin и попробуйте ещё раз. | +| This sign-in is already finished | Этот вход уже завершён | +| You can close this tab. | Эту вкладку можно закрыть. | + +## 6. Клавиатура, до�тупно�ть, о�обые �лучаи + +### Клавиатура + +- **Ctrl+Shift+T** (на macOS ⌘⇧T) — проверено: в `GameView::keyboard()` зан�ты Ctrl+Shift+Z, Ctrl+Y, Ctrl+Z, Ctrl+Shift+C, Ctrl+S, Ctrl+W, Ctrl+Shift+F, Shift+A и одиночные �→↑↓ Home End F L Esc; в `app.rs` — Ctrl+O, Ctrl+N, Ctrl+,; в библиотеке и большой базе — Ctrl+B, Ctrl+F, Ctrl+Shift+Backspace, �трелки, Enter, Esc. **Конфликта нет.** Добавить в `keyboard()` как `ctrl_shift(Key::T)` → `"translate"`; дей�твует только в окне партии и только е�ли фоку� не в поле ввода (обща� проверка `egui_wants_keyboard_input` уже е�ть). Поведение: е�ть перевод → переключить [Оригинал | Перевод]; «Предложение» / «Больша� парти�» → как «Переве�ти»; иначе ничего. +- Окна **К** и **Сг**: Enter — главна� кнопка (е�ли активна и фоку� не в много�трочном поле), Esc — «Отмена». Пор�док Tab: радио → пол� → ��ылки → кнопки. +- Строка **С**: её кнопки и переключатель до�тупны по Tab раньше нотации. + +### До�тупно�ть + +- В�е �о�то�ни� выражены тек�том, цвет — только дополнительно (⚠ в�егда �о �ловами). +- Значки «⇄», «⋯», «⚠» в нотации — `Response` � `widget_info` (имена «Машинный перевод», «Переводит��…», «�е переведено»), чтобы AccessKit их называл. +- Прогре�� — тек�том «{n} из {total}»; поло�а — только дополнение. +- Под�казки не перекрывают ходы: они прив�заны к значку, а не к блоку. +- Размеры значков отно�ительно шрифта (ма�штаб egui учитывает�� �ам). + +### Длинные партии (книжные главы) + +- Прогре�� — �чётчик и поло�а (при total > 40). +- Порог автозапу�ка — 60 000 �имволов чужого тек�та; выше — «Больша� парти�» � объёмом, перевод только по нажатию (защищает лимит и деньги). +- Пачки идут по пор�дку нотации; кажда� пачка �разу видна и �разу в к�ше. �ебольшие �двиги тек�та над видимой ча�тью при замене комментариев допу�тимы в первой вер�ии. +- О�тановка — «О�тановить»; открытие другой партии тоже о�танавливает. + +### Откуда открыта парти� + +| Откуда | Поведение | +|---|---| +| Библиотека (обычна� PGN-база) | как опи�ано | +| Больша� база (`large_db.rs`, .cbh / большой PGN) | так же: переводит�� только открыта� парти�; �пи�ок и значок 💬 в таблице не мен�ют��; базу целиком не переводим | +| Пои�к позиции (`board_search.rs`): открыта� из результатов парти� | так же | +| Предпро�мотр в пои�ке позиции и в �пи�ках (до�ка, ли�тание ходов без нотации) | ничего: комментарии не показывают��, ничего не отправл�ет�� | +| Вкладка «Справка» → парти�; «� назад к…» | так же; возврат к партии — из к�ша, режим «Перевод» | +| Базы Lichess / Chess.com | комментарии — только `[%clk]`, `plan()` = None → �троки нет. Специального правила не нужно; проверить те�том на на�то�щей выгрузке | +| Буфер обмена, «�ова� парти�» | так же (у новой партии комментариев нет) | + +### Что уходит в PGN и буфер + +�икогда не перевод: «Копировать PGN», Ctrl+Shift+C, Ctrl+S / «Сохранить партию как…», запи�ь анализа в партию (`write_to_game` добавл�ет `[%eval]` к оригинальным комментари�м). Перевод живёт только в `GameView` и к�ше. + +## 7. Что не делаем в первой вер�ии + +1. Выбор и�ходного �зыка («англий�ком ▾»): модели �казано определить �зык �амой; ошибки `whatlang` вли�ют только на название �зыка в �троке. +2. Выбор целевого �зыка в �троке — только в �а�тройках (без запи�и перевода �ценарий «тренер → ученику» не работает). +3. Перевод небольших баз целиком (�тап 3 из `translation.md`) и в�ё, что � ним �в�зано. +4. Меню у комментари�: «Переве�ти ещё раз», показать оригинал одного комментари� на ме�те. Е�ть «Повторить» в �троке и под�казка � оригиналом. +5. Выбор модели ChatGPT — автоматиче�ки по `/v1/models`. +6. Счётчик «отправлено за ме��ц», пои�к по переведённому тек�ту, редактирование �ловар� терминов. +7. Отзыв до�тупа на �тороне OpenAI из программы — только ��ылка «Управл�ть до�тупом на �айте OpenAI». +8. �втоматиче�ка� в�тавка ключа из буфера при открытии окна. +9. Удержание позиции прокрутки при замене комментариев над видимой ча�тью. + +## 8. Вопро�ы владельцу + +1. Порог «большой партии» — 60 000 �имволов чужого тек�та (≈ 15–20 �траниц книги): выше �того автоперевод ждёт нажати� «Переве�ти». Подходит? +2. «Выйти» из ChatGPT заодно �нимает разрешение отправл�ть в ChatGPT (по�ле нового входа �нова окно �огла�и�). Так или о�тавл�ть разрешение? +3. Режим [Оригинал | Перевод] не запоминает��: кажда� нова� парти� открывает�� в переводе. Или запоминать по�ледний выбор дл� в�ех партий? diff --git a/docs/design/translation.md b/docs/design/translation.md new file mode 100644 index 0000000..8dde384 --- /dev/null +++ b/docs/design/translation.md @@ -0,0 +1,239 @@ +# Перевод комментариев партий + +Стату�: утверждено владельцем � правками (2026-10-21); учтена рецензи� дизайнера. + +**Правки владельца (главнее тек�та ниже):** +1. В �а�тройках два �по�оба: «Вход через ChatGPT» и «Ключ API» (�ерви�ы: DeepSeek, OpenAI, Gemini, Ollama / LM Studio на компьютере — без ключа, «Свой адре�»). Модель на компьютере — пункт второго �по�оба, не третий. +2. Перевод живёт только на врем� про�мотра: в PGN не пишет�� никогда, «Сохранить � переводом» нет. О�таёт�� �лужебный к�ш (повторное открытие без �ети и без ра�хода), «Очи�тить» в �а�тройках. +3. Предложение переве�ти — только до первого �огла�и�. Дальше люба� открыта� парти� � комментари�ми на чужом �зыке переводит�� �ама (любой �зык); [Оригинал | Перевод] е�ть в�егда. Перевод�т�� только партии, открытые дл� про�мотра. +4. Ходы нигде не перевод�т�� и не мен�ют��. +5. Отчёт и печать — не ка�ают�� (в отчёте нет комментариев, печати нет). Проверенные факты — �о ��ылками; о�тальное — предлагаемые решени�. + +## Задача + +Комментарии в парти�х ча�то на чужом �зыке: англий�кие книги и базы, немецкие �борники, ру��кий разбор дл� ино�транного ученика. Пользователь хочет читать их на �воём �зыке, а тренер — отдать �вой разбор ученику на другом. + +Переводим **только тек�т комментариев** открытой партии или небольшой PGN-базы, по �вному дей�твию. Большие базы (Mega) не переводим целиком. + +�удитори� — шахмати�ты и тренеры, многие не знают, что такое API-ключ. Самый трудный момент — первое нажатие «Переве�ти»; он проектирует�� отдельно. + +## Инварианты + +- И�ходный PGN не мен�ет��. Перевод — �лой поверх партии (к�ш); «Сохранить � переводом» пишет **копию** и помечает перевод как машинный. +- Ходы, NAG, команды `[%cal]`, `[%csl]`, `[%clk]`, `[%eval]`, имена, ��ылки и чи�ла о�тают�� как в оригинале. +- Машинный перевод в�егда помечен там, где он виден. +- Без �огла�и� ничего не отправл�ет��: один раз на �ерви�, � че�тным перечнем того, что уйдёт. Локальна� модель на `127.0.0.1` / `localhost` / `::1` �огла�и� не требует; любой другой адре� �читает�� внешним �ерви�ом. +- Перевод не блокирует интерфей�: идёт в фоне, комментарии по�вл�ют�� по мере готовно�ти, его можно о�тановить; готовое �охран�ет�� �разу. +- Ключи и токены не лежат в `settings.json` открытым тек�том. +- Без �ети переводы из к�ша показывают�� как обычно. + +## Подключени� + +| Подключение | Кому | Протокол | Деньги | +|---|---|---|---| +| **Вход через ChatGPT** | е�ть подпи�ка Plus или Pro — �амый про�той путь | Responses API � токеном подпи�ки | из недельного лимита подпи�ки | +| **Ключ �ерви�а** | нет подпи�ки: DeepSeek, OpenAI, Google Gemini, «Другой (OpenAI-�овме�тимый)» | Chat Completions | по тарифу �ерви�а, обычно доли цента за партию | +| **Модель на компьютере** | без интернета и бе�платно: Ollama, LM Studio | Chat Completions на `127.0.0.1` | бе�платно; нужен мощный компьютер | + +### Вход через ChatGPT — по документации OpenAI + +С DevDay 2026 OpenAI даёт локальным программам � открытым кодом запу�кать запро�ы за �чёт подпи�ки ChatGPT пользовател� ([обзор](https://developers.openai.com/siwc/token-sharing-open-source)); ChessPenguin (GPL, локальный) подходит. + +- Реги�трировать приложение заранее не нужно: первый вход � `client_id=dynamic_agent_client` и `agent_name_hint=ChessPenguin`, в ответ — по�то�нный `client_id` (`oaiapp_…`), его �охран�ем ([вход](https://developers.openai.com/siwc/token-sharing-open-source/sign-in)). +- `ext_agent_host_id` — по�то�нный идентификатор у�тановки (`urn:uuid:…`), �оздаёт�� до первого входа, не �екрет. +- OAuth � PKCE через �и�темный браузер, обратный адре� `http://127.0.0.1:<порт>/auth/callback` (не `localhost`), �лушатель запу�кает�� до открыти� браузера (`TcpListener` из std). +- Обла�ти: `openid profile email offline_access resource.invoke chatgpt.tokens.use.direct`; по�ле обмена кода проверить, что `chatgpt.tokens.use.direct` выдана. +- Токен до�тупа живёт около ча�а; обновл�ющий ротирует�� — замен�ть оба �разу. +- Запро�ы: `POST https://api.openai.com/v1/responses`, `stream: true`, `store: false`, без `temperature`, `max_output_tokens` и других запрещённых полей ([ограничени�](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations)); модель — из `GET /v1/models` �тим токеном ([модели](https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference)). +- Лимит приходит по�реди потока: `subscription_sharing_usage_limit_exceeded` / `subscription_sharing_usage_unavailable`. +- Бе�платный аккаунт ChatGPT не подходит: «Вход через ChatGPT работает только � платной подпи�кой (Plus или Pro).» · [Выбрать другой �по�об]. + +Ри�ки: �то «preview», у�лови� могут помен�ть��. Подпи�ка Claude в �торонних программах не разрешена — не предлагаем. + +### Ключ �ерви�а + +DeepSeek, OpenAI, Gemini, Ollama и LM Studio понимают `POST {base}/chat/completions` и `GET {base}/models`. Пре�ет под�тавл�ет адре�, ��ылку «Получить ключ ↗» и модель; адре� и модель �пр�таны в «Дополнительно». + +**Gemini (Google AI Studio)** — бе�платный тариф � аккаунтом Google, но по у�лови�м Google дл� бе�платного тарифа запро�ы и ответы и�пользуют�� дл� улучшени� продуктов и могут читать�� людьми; в ЕЭЗ, Швейцарии и Великобритании бе�платный тариф дл� �торонних программ не разрешён ([у�лови� Gemini API](https://ai.google.dev/gemini-api/terms)). До�тупно�ть в Ро��ии не проверена. По�тому Gemini — в �пи�ке, но не рекомендуемый, � че�тной �трокой: «Бе�платно � аккаунтом Google; Google может и�пользовать тек�ты дл� обучени� �воих моделей». + +OpenRouter отдельным пре�етом не показываем: его покрывает «Другой». + +Цены мен�ют�� — в программе их не обещаем, показываем объём: «≈ 12 ты�. �имволов». + +## Определение �зыка + +Локально, крейт `whatlang` (MIT). + +- Команды `[%…]`, чи�ла, ходы и �имволы (`+-`, `!?`, `=`) вырезают�� перед определением. Комментарии только из них не уча�твуют ни в определении, ни в переводе (иначе кажда� парти� � Lichess предлагала бы перевод из-за `[%clk]`). +- Язык комментари� определ�ет�� по большин�тву букв. Короткие («Weak.», «Better was…») на�ледуют �зык партии. +- Предлагаем перевод, только е�ли на чужом �зыке хот� бы 3 комментари� или 150 букв. +- Смешанна� парти�: «15 из 40 комментариев на англий�ком» — отправл�ют�� только �ти 15. +- Смешанный комментарий: модели �казано о�тавить ча�ти, уже напи�анные на целевом �зыке, как е�ть. +- Комментарий, который пользователь напи�ал �ам в ChessPenguin, не �читает�� чужим и не переводит��. +- Ошибку определени� (whatlang путает и�пан�кий, италь�н�кий, португаль�кий на коротких тек�тах) пользователь и�правл�ет в �троке: «англий�ком ▾». + +## Интерфей� + +### Строка над нотацией — в�е �о�то�ни� + +``` +Предложение: Комментарии на англий�ком ▾ · [Переве�ти на ру��кий ▾] · ✕ +Идёт: Перевод � англий�кого… 12 из 40 · О�тановить +Готово: Машинный перевод � англий�кого (DeepSeek) · [Оригинал | Перевод] +Ча�тично: Переведено 37 из 40, 3 не удало�ь ⚠ · Повторить · [Оригинал | Перевод] +О�тановлено: Переведено 12 из 40 · Продолжить · [Оригинал | Перевод] +Ошибка: ⚠ {тек�т ошибки} · {кнопка �ледующего шага} · Подробно�ти · ✕ +У�тарел: 2 комментари� изменены · Переве�ти их · [Оригинал | Перевод] +``` + +- «на ру��кий ▾» — выбор целевого �зыка (по умолчанию — �зык интерфей�а). Это и �ценарий тренера: �вой ру��кий разбор — ученику на англий�кий. +- Переключатель — �егментный [Оригинал | Перевод]; режим запоминает�� дл� партии. Клавиша — Ctrl+Shift+T (проверить, что �вободна) и пункт в меню ☰. +- Перевод уже е�ть в к�ше — �разу «Готово», без �ети. +- «✕» �крывает �троку дл� �той партии. Отключить предложени� �ов�ем — флажок в �а�тройках. +- Esc перевод не о�танавливает (чтобы не �бить �лучайно), только кнопка. Кнопки �троки до�тупны по Tab, прогре�� — тек�том. +- Локальна� модель при первом запро�е грузит�� в пам�ть де��тки �екунд: «Модель загружает�� в пам�ть…», не таймаут. + +### Первое нажатие «Переве�ти» без подключени� — окно «Как переводить?» + +�е в �а�тройки, а окно � выбором (как предложение �качать Stockfish), по�ле подключени� перевод начинает�� �ам: + +``` +┌ Перевод комментариев ─────────────────────────────── ✕ � +│ Перевод делает �зыкова� модель. Выберите, кака�: │ +│ │ +│ � У мен� е�ть подпи�ка ChatGPT (Plus или Pro) │ +│ Проще в�его: войдите, ключи не нужны. │ +│ Ра�ходует ча�ть лимита подпи�ки. │ +│ [ Войти через ChatGPT ] │ +│ │ +│ ○ Подпи�ки нет — и�пользовать ключ �ерви�а │ +│ �ужно зареги�трировать�� на �айте и в�тавить ключ. │ +│ Обычно �то доли цента за партию. │ +│ [DeepSeek ▾] │ +│ 1. Откройте �айт ↗ 2. Создайте ключ │ +│ 3. В�тавьте его �юда [______________] [Проверить] │ +│ │ +│ ○ Модель на �том компьютере (Ollama, LM Studio) │ +│ Бе�платно и без интернета. �ужен мощный компьютер. │ +│ Рекомендуем {модель} (≈ 5 ГБ, нужно 8 ГБ пам�ти); │ +│ маленькие модели перевод�т заметно хуже. │ +└─────────────────────────────────────────────────────────┘ +``` + +«Проверить» показывает пример: «✓ Работает: «The knight is strong» → «Конь �илён»». + +### Согла�ие — один раз на �ерви� + +``` +┌ Отправить комментарии в DeepSeek? ──────────────────────� +│ Дл� перевода в DeepSeek (api.deepseek.com) будут │ +│ отправлены: │ +│ • тек�ты комментариев — 40 шт., ≈ 12 ты�. �имволов; │ +│ • имена игроков, турнир и дебют — дл� точных терминов. │ +│ Ходы партии отправлены не будут; ходы внутри │ +│ комментариев — будут. │ +│ Как DeepSeek хранит и и�пользует данные: │ +│ Политика конфиденциально�ти ↗ │ +│ │ +│ Разрешение можно отозвать в �а�тройки → Перевод. │ +│ [ Отмена ] [ Отправить и переве�ти ] │ +└─────────────────────────────────────────────────────────┘ +``` + +Дл� ChatGPT то же окно — по�ле входа (вход ещё не значит «отправл�й мои тек�ты»). + +### Пометка машинного перевода + +- В �троке в�егда «Машинный перевод … (подключение)». +- У каждого переведённого комментари� — мелкий приглушённый значок «⇄» � под�казкой «Машинный перевод. Оригинал: …» (виден и без мыши, и на �криншотах). Под�казка не должна мешать щелчку по ходу. +- «Сохранить � переводом…» добавл�ет в начало партии комментарий `{Комментарии переведены машинно � англий�кого (DeepSeek, 2026-10-21)}` (решение владельца: комментарий или тег `Annotator`). +- Пои�к по комментари�м ищет по оригиналу; отчёт и печать — то, что на �кране, � пометкой (решение владельца). + +### Правка в режиме перевода + +- Поле правки: �верху «Перевод (только дл� чтени�): …», ниже «Оригинал: [поле]». В меню комментари� — «Заменить оригинал переводом» (�вно, � отменой). +- По�ле правки перевод �того комментари� переделывает�� �ам, е�ли �огла�ие уже дано; е�ли новый тек�т уже на целевом �зыке — перевод про�то убирает��. +- Первый Ctrl+S в режиме перевода — однажды то�т: «Сохранён оригинал. Чтобы �охранить перевод, и�пользуйте «Сохранить � переводом…» в меню ☰.» + +### �ебольша� база (�тап 3) + +Пункт меню базы «Переве�ти комментарии…» виден в�егда; дл� большой базы неактивен � под�казкой: «База �лишком больша� дл� перевода целиком (12 000 партий, ≈ 30 млн �имволов). Переводите партии по одной — перевод �охранит��.» Граница — ~500 партий или ~2 млн �имволов. + +``` +Переве�ти комментарии базы «Dvoretsky.pgn» + Партий � комментари�ми: 214 из 300 + �а англий�ком: 198 партий · ≈ 1,4 млн �имволов + Переве�ти на: [Ру��кий ▾] Через: DeepSeek + [ Отмена ] [ Переве�ти ] +``` + +Идёт в фоне («Перевод… 57 из 198 партий» · О�тановить), окно можно закрыть, как загрузку онлайн-партий; по�ле перезапу�ка — «Продолжить» (готовое в к�ше). + +### �а�тройки → «Перевод» + +``` +Перевод комментариев + Переводить на: [Ру��кий ▾] + [✓] Предлагать перевод, е�ли комментарии на другом �зыке + + Как переводить + � Вход через ChatGPT vrubel@… · Выйти + Ра�ходует ча�ть недельного лимита подпи�ки + ○ Ключ �ерви�а [DeepSeek ▾] Ключ [••••••••] [Проверить] + Получить ключ ↗ + ▸ Дополнительно (адре�, модель) + ○ Модель на компьютере [Ollama ▾] Модель [qwen… ▾] [Проверить] + ▸ Дополнительно (адре�) + Со�то�ние: ✓ Работает — проверено 21.10, модель deepseek-chat + + Разрешено отправл�ть: DeepSeek · Отозвать + Сохранённые переводы: 1,2 МБ · [Очи�тить] + ⚠ Ключ хранит�� в файле, а не в хранилище паролей (только е�ли хранилища нет) +``` + +## Ошибки — у каждой �ледующий шаг кнопкой + +| Что | Тек�т | Кнопка | +|---|---|---| +| 401 | «Ключ не подошёл. Возможно, он �копирован не полно�тью или удалён на �айте.» | Открыть на�тройки перевода | +| 402 (DeepSeek `Insufficient Balance`) | «�а �чёте DeepSeek закончили�ь деньги. Пополните балан� на �айте DeepSeek.» | Открыть �айт ↗ | +| 429 | «Серви� про�ит подождать. Продолжим через 20 �…» (от�чёт) | О�тановить | +| лимит ChatGPT | «Лимит ChatGPT дл� ChessPenguin на �ту неделю и�черпан. Он во��тановит�� {дата}. Лимит можно изменить в на�тройках ChatGPT.» | Подробно�ти · Другой �по�об | +| вход у�тарел или отозван | «Вход в ChatGPT больше не дей�твует. Войдите �нова.» | Войти через ChatGPT | +| нет интернета | «�ет �в�зи � интернетом. Уже переведённое �охранено.» (без бе�конечных повторов) | Повторить | +| Ollama не отвечает | «Ollama не отвечает. Запу�тите программу Ollama и нажмите «Повторить».» | Повторить · Подробно�ти | +| нет модели | «В Ollama нет модели {model}. Скачайте её командой `ollama pull {model}`.» | Копировать команду | +| неизве�тна� | «Серви� ответил ошибкой.» | Подробно�ти (код, ответ) | +| и�порченный ответ | у ⚠: «Этот комментарий не удало�ь переве�ти — показан оригинал.» | в меню комментари�: «Переве�ти ещё раз» | + +## Как переводим + +1. Собираем комментарии к переводу (�м. «Определение �зыка»), у каждого `id` (узел + до/по�ле хода + номер). +2. Команды `[%…]` замен�ем метками `⟦1⟧`, `⟦2⟧`…; ходы о�тавл�ем. +3. Пачки по ~6 ты��ч �имволов; запро� — JSON-ма��ив `[{"id": …, "text": …}]`, ответ той же формы (`response_format: json_object`, где е�ть; иначе первый `[...]` в ответе). +4. Ин�трукци�: переве�ти шахматные комментарии � {�зыка} на {�зык}; ходы, метки `⟦n⟧`, имена и чи�ла не мен�ть; ча�ти на целевом �зыке о�тавить; прин�тые шахматные термины; ничего не добавл�ть. Плю� �ловарь ~30 терминов на �зык (размен каче�тва, проходна�, цугцванг, фианкетто, вилка, �в�зка…), хранит�� в программе. Контек�т: игроки, турнир, дебют из заголовков. +5. Проверка ответа: те же `id`, те же метки, тот же набор ходов (SAN по регул�рному выражению). �е �овпало — один повтор �того комментари� отдельно, потом ⚠ и оригинал. +6. Метки обратно, результат в к�ш; по�ле ответа в под�казке �троки — «Отправлено ≈ 12 ты�. �имволов». + +## Хранение + +- К�ш: `/translations/<�зык>.jsonl`, ключ — sha256(оригинальный тек�т, целевой �зык, вер�и� формата); значение — перевод, подключение, модель, дата. Один комментарий переводит�� один раз дл� в�ех партий и баз. +- Ключи и токены ChatGPT — в �и�темном хранилище паролей (крейт `keyring`: Secret Service, Ди�петчер учётных данных Windows, Св�зка ключей macOS). �ет хранилища — файл 0600 в папке на�троек и предупреждение в �а�тройках. +- В `settings.json`: целевой �зык, подключение, пре�ет, адре�, модель, `client_id`, `ext_agent_host_id`, разрешённые �ерви�ы, флажок предложений. + +## Этапы + +1. **Ядро** (внутренний, дл� проверки владельцем): определение �зыка, �трока �о в�еми �о�то�ни�ми, окно «Как переводить?», ключ �ерви�а и модель на компьютере, перевод открытой партии, к�ш, переключатель, пометки, �огла�ие, хранилище ключей, �а�тройки → «Перевод», «Сохранить � переводом». +2. **Вход через ChatGPT**: OAuth � PKCE, обновление токенов, Responses API � потоком. **Публичный выпу�к — �тапы 1 и 2 вме�те**: дл� нашей аудитории вход через ChatGPT — �амый лёгкий путь, без него первое впечатление «�ложно». +3. **�ебольшие базы**; позже — «Сохранить копию базы � переводом», «Переводить англий�кие партии �разу» (только дл� уже разрешённого �ерви�а), �чётчик «отправлено за ме��ц». + +�е делаем: перевод заголовков; меню на «✕»; отдельный пре�ет OpenRouter. + +�овые зави�имо�ти: `whatlang` (MIT), `keyring` (MIT/Apache-2.0). HTTP (`ureq`) и sha256 (`sha2`) уже е�ть. + +## Решени� владельца + +1. Выпу�кать перевод публично только вме�те �о входом через ChatGPT (�тапы 1+2)? +2. Пометка в �охранённом PGN: комментарий в начале партии или тег `Annotator`? +3. Отчёт и печать: перевод (� пометкой) или оригинал? +4. Ходы в комментари�х в ру��кой нотации (Кр/Ф/Л) — о�тавл�ем как в оригинале (предложение: да). diff --git a/docs/design/user-comments.md b/docs/design/user-comments.md new file mode 100644 index 0000000..dca1160 --- /dev/null +++ b/docs/design/user-comments.md @@ -0,0 +1,500 @@ +# Свои комментарии и оценки ходов в партии + +Стату�: проект дизайнера от 2026-10-25, **не утверждён**. Запро� владельца: «чтобы пользователь мог пи�ать �вои комментарии в партии; может, про�то между ходами, но е�ть варианты, разные линии… как лучше, не знаю; не у�ложн�ть; по�мотреть, как у других». И��ледование аналитика `../research/user-comments.md` идёт параллельно. Е�ли в нём найдут�� факты, которые противоречат �тому проекту, факты важнее. + +Проект опирает�� на код: +- `apps/desktop/src/notation.rs`: таблица главной линии `Row::flush`; блоки во в�ю ширину `comment_block`, `variation_block`, `mark_block`; поток варианта `inline_line`; контек�тное меню хода `handle_move_response`. +- `apps/desktop/src/game_view.rs`: `keyboard()`, панель ин�трументов `� ◀ ▶ � · 🔃 ↩ ↪ · ☰ 💾 📋 · 📈`, меню ☰, предпро�мотр линии движка `Preview`, `debug_comment`, `copy_pgn`. +- `crates/chess-core/src/edit.rs`: `annotate(id, nags, comments_after)` — один шаг отмены, без изменений не запи�ывает. +- `crates/chess-core/src/comment.rs`: `parse_comment`, `comment_display_text`. +- `crates/chess-core/src/pgn/write.rs`: `comment()`. +- `crates/chess-core/src/nag.rs`. + +Св�занные проекты: +- `own-databases.md` §3.2 и §3.4: Ctrl+S, «•», вопро� «Парти� изменена». +- `narrow-windows.md` §3 и §4a: окно 640 × 480, бокова� панель от 240, �топка. +- `translation-ui.md` §0.1. Фраза «комментарии в ChessPenguin не редактируют��» �тим проектом **отмен�ет��**, �м. §9. + +Размеры даны в логиче�ких точках egui. Тек�ты приведены по-ру��ки, в �кобках — англий�кий ключ `tr(...)`. + +## 0. Главное + +1. **Комментарий пишет�� там, где он будет �то�ть**: пр�мо в нотации, на ме�те блока комментари� по�ле хода. Отдельного окна нет, и до�ка не закрывает��. В варианте блок варианта на врем� правки «ра�крывает��» у �того хода: начало линии, поле ввода, продолжение линии (§3.3). +2. **Комментарий принадлежит ходу**: «по�ле хода X». В главной линии и в вариантах правило одно. Е�ть одно о�обое ме�то — «в начале партии» (комментарий корн�). +3. **Три входа на в�ё:** + - **Enter** — к текущему ходу; + - **правый щелчок по ходу** — пункт меню «Комментарий…» и р�д значков оценки; + - **двойной щелчок по комментарию** — правка �того комментари�. + + Оценки `! ? !! ?? !? ?!` �тав�т�� также �очетани�ми **Ctrl+1…Ctrl+6**, без открыти� пол�. +4. **Enter — готово, Esc — отмена.** Переход к другому ходу (щелчок, ход на до�ке, кнопки ◀ ▶) �охран�ет напи�анное. Одно «Готово» — один шаг Ctrl+Z. +5. **Сохран�ет�� только �вно**, как люба� правка: в шапке по�вл�ет�� «•», а Ctrl+S запи�ывает по `own-databases.md` §3.2. +6. **�ичего чужого не тер�ет��.** + - Команды внутри комментари� (`[%cal]`, `[%csl]`, `[%clk]`, `[%eval]` и любые другие) в поле не показывают�� и �охран�ют�� до�ловно. + - �епривычные NAG ($32, □, N…) о�тают��. + - Е�ли комментарий не трогали, его байты не мен�ют��. +7. **Стрелки и цветные пол� ри�овать в первой вер�ии нельз�.** Уже запи�анные в PGN показывают��, как и �ейча� (§10). + +## 1. Как �то �делано у других + +Сведени� �верены по документации там, где указана ��ылка; о�тальное — по пам�ти, помечено «не проверено». + +| Программа | Где пишет�� комментарий | Оценки (NAG) | Клавиши | Стрелки и пол� | +|---|---|---|---|---| +| ChessBase / Fritz | Отдельное окно-редактор «Text after move» / «Text before move». Вызов: правый щелчок по ходу или **Ctrl+A** / **Shift+Ctrl+A**. Enter в нём — новый абзац, выход — «OK» или Alt+0. У тек�та е�ть �зык, Tab переключает �зыки [1] | Палитра и клавиатура [1] | Ctrl+A по�ле хода, Shift+Ctrl+A перед ходом [1] | Е�ть, Alt и щелчок (не проверено) | +| Lichess, �тудии | Поле под нотацией дл� текущей позиции. Пишет��, пока позици� выбрана; уходишь — �охранено | Отдельна� панель значков, клавиша **g** [2] | **d** — комментарий к позиции [2] | Правый щелчок и прот�жка по до�ке, цвет от модификатора | +| En Croissant | Панель «Annotate» под до�кой, поле комментари� к текущему ходу, �охран�ет�� при уходе � хода [3] | Цифры **1, 2, 3…**, повторное нажатие �нимает знак [4] | **d** — панель «Annotate» [3] | Правый щелчок и прот�жка, Ctrl+L — �тереть [3] | +| Scid vs PC | Отдельное окно «Comment Editor»: тек�т, NAG и маленька� до�ка дл� �трелок. Сохран�ет при переходе к другому ходу; Ctrl+Enter — �охранить и закрыть; Ctrl+�/→ — ходить по партии из редактора [5] | Кнопки в редакторе, `!`, `?` и т. п. можно набрать в главном окне [5] | Ctrl+Enter [5] | В редакторе на мини-до�ке, на главной до�ке — Ctrl/Shift и щелчок [5] | +| ChessX | Пункты «комментарий по�ле/перед ходом» в контек�тном меню хода, окно-диалог; подменю оценок хода и позиции (не проверено) | Контек�тное меню | — | Е�ть (не проверено) | + +Что из �того �ледует дл� на�: +- **В�е комментируют ход (узел), а не «промежуток».** Комментарий «перед ходом» е�ть только у ChessBase и ChessX, и пользователи им почти не пользуют��. В Lichess его нет �ов�ем. Мы берём «по�ле хода» и «в начале партии». +- **Отдельное окно** (ChessBase, Scid) закрывает до�ку и требует подтверждени�. **Поле у нотации, �охран�емое при уходе** (Lichess, En Croissant), легче. Мы берём лёгкую модель, но �тавим поле не внизу панели, а на ме�то �амого комментари� (§2). +- **Оценки �тав�т�� одной клавишей.** В En Croissant �то цифры. �ам цифры без модификатора нежелательны: возможный будущий ввод ходов тек�том (`move-notation.md` §4.3) их займёт. По�тому Ctrl+цифра. +- **Стрелки везде ри�уют�� правой кнопкой на до�ке.** У на� правый щелчок по до�ке уже �нимает выбор фигуры, и �то не конфликтует � прот�жкой. Это �ледующий шаг (§10), не перва� вер�и�. + +И�точники: +[1] https://help.chessbase.com/CBase/18/Eng/000131.htm, https://help.chessbase.com/Fritz/18/Eng/text_commentary.htm +[2] https://lichess.org/@/jomega/blog/general-use-of-lichess-studies/2dIoggNY (таблица клавиш, по �ловам автора блога) +[3] https://www.mintlify.com/franciscoBSalgueiro/en-croissant/guides/analyzing-games +[4] https://www.mintlify.com/franciscoBSalgueiro/en-croissant/guides/keyboard-shortcuts +[5] https://scidvspc.sourceforge.net/doc/Comment.htm + +## 2. Варианты + +Обозначени� в макетах: +- `[Nf6]` — текущий ход (выделение кур�ора); +- `▌…�` — поле ввода, `|` — тек�товый кур�ор; +- 1400 — окно 1400 × 900, права� панель ≈ 460; +- 640 — окно 640 × 480, права� панель ≈ 240, видима� ча�ть нотации ≈ 270 по вы�оте. + +### Вариант A. Поле на ме�те комментари�, в нотации (выбран) + +``` +1400 640 × 480 (панель 240) +│ [�отаци�] Справочник │ │ [�отаци�] Справочник │ +│ 3 │ Bb5 a6 │ │ 3 │ Bb5 a6 │ +│ 4 │ Ba4 [Nf6] │ │ 4 │ Ba4 [Nf6] │ +│ ┌ Комментарий по�ле 4…Nf6 [Готово] [Отмена]�│ │┌ По�ле 4…Nf6 ✓ ✕ �│ +│ │ ! ? !! ?? !? ?! │ = ∞ ⩲ ⩱ ± ∓ +− −+ ││ ││ ! ? !! ?? !? ?! ±▾ ││ +│ │▌Главный ход. Возможно и 4…d6| �││ ││▌Главный ход. �││ +│ │▌ �││ ││▌Возможно и 4…d6| �││ +│ │ Enter — готово · Esc — отмена ││ │└────────────────────┘│ +│ └───────────────────────────────────────────┘│ │ 5 │ O-O Be7 │ +│ 5 │ O-O Be7 │ │ � ◀ ▶ � │ 🔃 ↩ ↪ │ +``` + +- Плю�ы: + - видно, где окажет�� тек�т, и ход, к которому он отно�ит��, р�дом; + - до�ка и движок не закрыты; + - нет новой панели, котора� мен�ла бы вы�оту нотации; + - точно отвечает «про�то между ходами». +- Мину�ы: + - в варианте поле нужно в�тавить внутрь тек�тового потока; �то требует переделки `inline_line` (§3.3, §11); + - в окне 640 × 480 поле занимает ≈ 110–150 из 270 по вы�оте нотации (на врем� правки �то приемлемо). + +### Вариант B. Поло�а комментари� внизу вкладки «�отаци�» + +``` +1400 640 × 480 +│ 4 │ Ba4 [Nf6] │ │ 4 │ Ba4 [Nf6] │ +│ ┌──────────────────────────────────────────�│ │ 5 │ O-O Be7 │ +│ │ Главный ход. Возможно и 4…d6 ││ │──────────────────────│ +│ └──────────────────────────────────────────┘│ │ По�ле 4…Nf6 ✓ ✕ │ +│ 5 │ O-O Be7 │ │ ! ? !! ?? !? ?! ±▾ │ +│ ──────────────────────────────────────────── │ │▌Главный ход. Возм…|� │ +│ Комментарий по�ле 4…Nf6 [Готово] [Отмена] │ │ � ◀ ▶ � │ 🔃 ↩ ↪ │ +│ ! ? !! ?? !? ?! │ = ∞ ⩲ ⩱ ± ∓ +− −+ │ +│▌Главный ход. Возможно и 4…d6| � │ +│ � ◀ ▶ � │ 🔃 ↩ ↪ │ ☰ 💾 📋 │ 📈 │ +``` + +Так �делано в Lichess и En Croissant: одна поло�а над панелью ин�трументов, нотаци� не пере�траивает��, а блок в нотации обновл�ет�� по мере набора. +- Плю�ы: �ама� про�та� реализаци�; ме�то пол� одно и то же дл� главной линии и вариантов. +- Мину�ы: + - тек�т отделён от ме�та, куда он в�танет; в длинном варианте глаз прыгает между поло�ой и нотацией; + - в 640 × 480 поло�а и нотаци� дел�т 270 точек, и нотации о�таёт�� 3–4 �троки; + - открытие и закрытие поло�ы мен�ет вы�оту нотации, так что текущий ход «прыгает». + +### Вариант C. Окно-диалог (как ChessBase, ChessX) + +``` +┌─ Комментарий по�ле 4…Nf6 ─────────────────────� +│ ! ? !! ?? !? ?! = ∞ ⩲ ⩱ ± ∓ +− −+ │ +│ ┌───────────────────────────────────────────� │ +│ │ Главный ход. Возможно и 4…d6| │ │ +│ │ │ │ +│ └───────────────────────────────────────────┘ │ +│ [Готово] [Отмена] │ +└───────────────────────────────────────────────┘ +``` + +`egui::Modal` шириной 440, при 640 — шириной окна мину� 32. +- Плю�ы: реализаци� �ама� про�та�; фоку� однозначен. +- Мину�ы: + - закрывает до�ку (при 640 почти в�ю); + - модально�ть: нельз� шагнуть к �о�еднему ходу, не закрыв окно; + - т�жело дл� ча�того «по�тавить ?» и короткой фразы; + - чужеродно р�дом � о�тальным �краном партии, где в�ё правит�� на ме�те (предпро�мотр линии движка, «Добавить как вариант»). + +### Оценка + +| Критерий | A | B | C | +|---|---|---|---| +| Видно, к чему отно�ит�� тек�т | ✔ на ме�те | ~ подпи�ь «по�ле 4…Nf6» | ~ подпи�ь | +| Варианты, вложенные линии | ✔ поток ра�крывает�� у хода | ✔ одинаково | ✔ одинаково | +| До�ка и движок видны | ✔ | ✔ | ✘ | +| 640 × 480 | ~ поле в прокрутке нотации | ~ нотаци� 3–4 �троки | ✘ закрывает до�ку | +| Пере�тройка �крана | только нотаци� у хода | вы�ота нотации мен�ет�� | нет | +| Цена реализации | �редн�� (токены варианта, §11) | низка� | низка� | +| Ри�к конфликтов клавиш | одинаковый: поле в фоку�е, `keyboard()` уже молчит | = | нет | + +**Выбор: A.** Это �амое пон�тное дл� школьника и тренера: пишешь там, где будет напи�ано. Един�твенна� �ложна� ча�ть — разрыв потока варианта. Она решает�� одной переделкой ри�овани� (§11) и полезна �ама по �ебе: на неё же потом л�жет показ �трелок у хода. Е�ли разработчик оценит переделку `inline_line` как непропорционально дорогую, запа�ной путь — B � теми же клавишами, тек�тами и правилами (§4–§9 от варианта не зави��т). + +## 3. Выбранный вариант: редактор в нотации + +### 3.1. Что правит�� + +Целью правки (`Slot`) бывает одно из трёх: + +| Цель | Где �тоит в нотации | Заголовок редактора | +|---|---|---| +| по�ле хода `id` (главна� лини� или вариант) | блок по�ле �троки хода / по�ле хода в потоке варианта | «Комментарий по�ле 4…Nf6» (`Comment after {move}`) | +| начало партии (корень, `comments_after` корн�) | первый блок над таблицей | «Комментарий в начале партии» (`Comment at the start of the game`) | +| перед ходом `id` (`comments_before`, **только уже �уще�твующий**) | блок перед ходом | «Комментарий перед 3…Nf6» (`Comment before {move}`) | + +- Ход в заголовке пишет�� � номером (`4.Ba4`, `4…Nf6`) и в выбранной нотации (`move-notation.md`: латиница, фигурки или буквы �зыка). При 640 заголовок �окращает�� до «По�ле 4…Nf6» (`After {move}`), «В начале партии» (`At the start`), «Перед 3…Nf6» (`Before {move}`). Правило то же, что у панели ин�трументов: е�ли полный заголовок � кнопками не помещает�� в �троку, берёт�� короткий. +- **�овый комментарий «перед ходом» в первой вер�ии не �оздаёт��.** Вме�то «{Другой путь} 3…Nf6» пишут «3…Nf6 {Другой путь…}». Суще�твующие «перед» из книг прав�т�� и удал�ют��, иначе их не убрать. + +### 3.2. Главна� лини� и начало партии + +Редактор — рамка во в�ю ширину на том ме�те, где �тоит или в�танет блок комментари�. Пор�док блоков по�ле хода �охран�ет��: оценка движка (`mark_block`), **комментарий или редактор**, непрочитанный PGN, варианты. + +- Комментарий по�ле хода белых разрывает �троку таблицы уже во врем� правки: `4 │ Ba4 │ …`, потом редактор, потом `4 │ … │ Nf6`. Так будет выгл�деть и результат. +- �ачало партии: редактор �тоит над �трокой 1. В партии без ходов он �тоит в пу�той нотации один. + +### 3.3. Ход в варианте + +Блок варианта на врем� правки делит�� у �того хода на три ча�ти: + +``` +1400 +│ ┌────────────────────────────────────────────� │ +│ │ 3.e4 Nc6 4.f4 d6 5.d3 Be7 6.Nf3 Bg4 │ │ � начало потока до хода включительно +│ │ 7.Be2 [Bxf3] │ │ +│ ├ Комментарий по�ле 7…Bxf3 [Готово] [Отмена]┤ │ +│ │ ! ? !! ?? !? ?! │ = ∞ ⩲ ⩱ ± ∓ +− −+ │ │ +│ │▌Размен в пользу белых| �│ │ +│ │ Enter — готово · Esc — отмена │ │ +│ ├────────────────────────────────────────────┤ │ +│ │ 8.Bxf3 Nd4 9.Be3 Nxf3+ 10.Qxf3 … │ │ � продолжение потока +│ └────────────────────────────────────────────┘ │ +``` + +- Поток до хода, редактор и продолжение наход�т�� в одной рамке варианта: в�ё ещё видно, что �то одна лини�. Скобки вложенных вариантов, открытые до хода, о�тают�� открытыми, а закрывают�� в продолжении. +- Продолжение начинает�� � номера хода, как по�ле любого комментари� в потоке (`need_number = true`). +- По�ле «Готово» вариант �нова ри�ует�� одним потоком, а тек�т �тоит в нём по�ле хода, как �ейча�. + +### 3.4. Редактор + +``` +┌ {заголовок} ─────────────────── [Готово] [Отмена] � рамка: обводка selection.stroke 1.5 +│ [!][?][!!][??][!?][?!] │ [=][∞][⩲][⩱][±][∓][+−][−+] │ или «… [?!] [±▾]», е�ли не помещает�� +│ ▌тек�т � │ TextEdit::multiline, 2…12 �трок +│ Enter — готово · Esc — отмена │ �лабым, мелким; �крыт при ширине < 360 +│ ⇄ Правит�� оригинал; перевод �того комментари� │ только е�ли был показан перевод (§9) +│ пропадёт │ +└────────────────────────────────────────────────────┘ +``` + +**Заголовок и кнопки.** +- Слева заголовок (§3.1), обычным тек�том. +- Справа «Готово» (`Done`) — главна� кнопка (`widgets::primary`), и «Отмена» (`Cancel`). +- При ширине рамки < 360 кнопки �танов�т�� значками «✓» и «✕» � под�казками «Готово (Enter)» и «Отмена (Esc)» (`Done (Enter)`, `Cancel (Esc)`). + +**Значки оценки.** Две группы переключателей, `selectable_label` размером 28 × 24 (�имвол 15): + +| Знак | NAG | Под�казка (ru / en) | Клавиша | +|---|---|---|---| +| ! | 1 | Хороший ход / Good move | Ctrl+1 | +| ? | 2 | Ошибка / Mistake | Ctrl+2 | +| !! | 3 | Бле�т�щий ход / Brilliant move | Ctrl+3 | +| ?? | 4 | Груба� ошибка / Blunder | Ctrl+4 | +| !? | 5 | Интере�ный ход / Interesting move | Ctrl+5 | +| ?! | 6 | Сомнительный ход / Dubious move | Ctrl+6 | +| = | 10 | Равен�тво / Equal position | — | +| ∞ | 13 | �е��но / Unclear position | — | +| ⩲ | 14 | У белых чуть лучше / White is slightly better | — | +| ⩱ | 15 | У чёрных чуть лучше / Black is slightly better | — | +| ± | 16 | У белых переве� / White is better | — | +| ∓ | 17 | У чёрных переве� / Black is better | — | +| +− | 18 | Белые выигрывают / White is winning | — | +| −+ | 19 | Чёрные выигрывают / Black is winning | — | + +- Под�казка выгл�дит как «Хороший ход (Ctrl+1)». +- Знаки хода окрашены цветами `assessment_color`, как в нотации; знаки позиции — обычным тек�том. Цвет не един�твенный но�итель �мы�ла: в�егда виден �ам �имвол. +- **Кажда� группа — один выбор или ничего.** Щелчок по нажатому знаку �нимает его. Щелчок по другому знаку замен�ет. +- Прочие NAG хода ($7 □, $22 ⨀, $32 ⟳, $36 ↑, $40 →, $132 ⇆, $140 ∆, $146 N, любые `$n`) в редакторе не показывают�� и при «Готово» �охран�ют�� на �воих ме�тах. +- **Ра�кладка групп.** Е�ли обе группы помещают�� в одну �троку (≈ 430), они �то�т в �троку через разделитель. Иначе втора� группа �ворачивает�� в кнопку «±▾». �а кнопке показан текущий знак позиции («⩲▾»), без знака — «±▾». Кнопка открывает в�плывающий р�д из во�ьми знаков (2 × 4 при ширине < 240). Под�казка кнопки: «Оценка позиции» (`Position assessment`). Ширина �читает�� так же, как в `toolbar()::next_group`. Знаки хода в�егда в одной �троке: 6 × 28 + промежутки ≈ 200 помещают�� в 240. +- **Значки — черновик.** Они мен�ют только черновик редактора и запи�ывают�� вме�те � тек�том по «Готово», одним шагом отмены. «Отмена» откатывает и их. В нотации знак у хода по�вл�ет�� по�ле «Готово». + +**Поле тек�та.** +- `TextEdit::multiline`, шрифт и цвет как у комментариев (14.5, `comment_color`), ширина — в�� рамка. +- Вы�ота ра�тёт по тек�ту от 2 до 12 �трок. Длиннее 12 �трок поле прокручивает�� внутри. Без �того длинный комментарий из книги (ты��чи знаков) вытолкнул бы кнопки за �кран. +- Под�казка в пу�том поле: «Ваш комментарий…» (`Your comment…`). +- Фоку� �тавит�� в поле при открытии. Кур�ор — в конец тек�та; тек�т не выделен, потому что чаще допи�ывают, чем замен�ют. +- В поле показывает�� **тек�т без команд**: `parse_comment` → только `CommentPart::Text`. �е�колько комментариев PGN у хода (`{a} {b}`) показывают�� через пробел, как в нотации. �бзацы (пу�та� �трока) показывают�� пу�той �трокой. + +**Прокрутка.** При открытии и при ро�те пол� нотаци� прокручивает�� так, чтобы рамка была видна целиком (`scroll_to_rect`, выравнивание `None`), а е�ли рамка выше видимой ча�ти — чтобы был виден её верх. + +### 3.5. Со�то�ни� + +| Со�то�ние | Вид | +|---|---| +| нет комментари�, редактор закрыт | как �ейча�: блока нет | +| редактор открыт, пу�то | рамка � под�казкой «Ваш комментарий…», «Готово» активна (пу�то + Готово = нет комментари�) | +| редактор открыт � тек�том | рамка, тек�т, кур�ор в конце | +| поле не в фоку�е (щёлкнули по до�ке мимо фигур, по пу�тому ме�ту панели) | рамка о�таёт��, обводка ту�кнеет до `weak` и кур�ор тек�та �крыт. Стрелки, F, L �нова работают как в партии (§4), а переход к другому ходу �охран�ет и закрывает редактор. Enter или щелчок в поле возвращает фоку� | +| предпро�мотр линии движка | редактор не открывает�� по Enter (§4). Е�ли предпро�мотр начинают при открытом редакторе (щелчок по ходу «Лучше: …»), �то �читает�� переходом: �охранить и закрыть | +| и�точник только дл� чтени� (ChessBase, онлайн, образцы, друга� кодировка) | правка разрешена, как ходы и варианты. Ctrl+S ведёт в «Добавить в базу…» (`own-databases.md` §3.2) | + +## 4. Клавиатура и фоку� + +`keyboard()` уже ничего не делает, пока поле ввода в фоку�е (`egui_wants_keyboard_input`). По�тому �трелки, Home/End, F, L внутри пол� — �то редактирование тек�та, а не ходы. Конфликта нет, и так и должно о�тать��. + +**В партии (фоку� не в поле):** + +| Клавиша | Дей�твие | +|---|---| +| **Enter** | открыть редактор «по�ле текущего хода», на корне — «в начале партии». Е�ли редактор открыт, но не в фоку�е, — вернуть фоку�. �е дей�твует при предпро�мотре линии движка и при открытом окне или меню (`overlay_open`). Клавиша поглощает�� (`consume_key`), чтобы Enter, закрывший диалог в �том кадре, не открыл редактор | +| **Ctrl+1 … Ctrl+6** | по�тавить или �н�ть `! ? !! ?? !? ?!` у текущего хода. Сразу, одним шагом отмены, без редактора; знак той же группы замен�ет��. �а корне и при предпро�мотре ничего не делают. Ctrl+0, Ctrl+= и Ctrl+− не трогаем: �то ма�штаб egui | + +**В редакторе (фоку� в поле):** + +| Клавиша | Дей�твие | +|---|---| +| **Enter**, **Ctrl+Enter** | Готово. Ctrl+Enter — дл� привыкших к Scid | +| **Shift+Enter** | новый абзац (пу�та� �трока). Только при у�ловии §8.3; иначе в первой вер�ии ничего не делает | +| **Esc** | Отмена: черновик выбра�ывает�� без вопро�а, ход о�таёт�� выбранным. Esc поглощает��: партию он не закрывает | +| **Ctrl+Z / Ctrl+Y** | отмена и повтор **набора** внутри пол� (в�троенные в `TextEdit`) | +| **Ctrl+1…6** | переключить знак хода в черновике | +| **Ctrl+S** | Готово, затем «Сохранить» (`own-databases.md` §3.2) | +| **Ctrl+W** | Готово, затем уход из партии (вопро� «Парти� изменена», е�ли нужно) | +| **Tab / Shift+Tab** | поле → значки → «±▾» → Готово → Отмена → поле. Табул�ци� в тек�т не в�тавл�ет�� | +| �трелки, Home/End, Ctrl+�/→ | обычное редактирование тек�та | + +**Сохран�ет и закрывает редактор** (как Готово, затем �амо дей�твие): +- щелчок по другому ходу в нотации; +- ход на до�ке; +- кнопки � ◀ ▶ �; +- щелчок по ходу «Лучше: …»; +- «⬅ Библиотека»; +- закрытие программы — перед вопро�ом о не�охранённом. + +**�а врем� открытого редактора кнопки ↩ ↪ панели неактивны.** Иначе «↩» откатил бы предыдущую правку под ещё не запи�анным тек�том. Под�казка у них прежн��. Ctrl+Z в поле — �то отмена набора. + +## 5. Как вызвать + +### 5.1. Контек�тное меню хода (правый щелчок, главна� лини� и варианты) + +``` +┌──────────────────────────────────────� +│ Комментарий… Enter │ или «Изменить комментарий…», е�ли он е�ть +│ Удалить комментарий │ только е�ли комментарий е�ть +│ ! ? !! ?? !? ?! │ р�д переключателей, текущий нажат +│ = ∞ ⩲ ⩱ ± ∓ +− −+ │ +│ ──────────────────────────────────── │ +│ Комментарий в начале партии… │ только у первого хода главной линии +│ ──────────────────────────────────── │ +│ Сделать главной линией │ как �ейча� (у варианта) +│ Удалить ход и продолжение │ как �ейча� +└──────────────────────────────────────┘ +``` + +- Тек�ты: «Комментарий…» (`Comment…`), «Изменить комментарий…» (`Edit comment…`), «Удалить комментарий» (`Delete comment`), «Комментарий в начале партии…» (`Comment at the start of the game…`). Клавиша Enter �тоит �права �лабым тек�том (`shortcut_text`). +- Правый щелчок �начала делает ход текущим, как �ейча� делает левый, чтобы было видно, к чему отно�ит�� меню. +- Значки в меню запи�ывают�� **�разу**, одним шагом отмены, и меню не закрывают: можно �н�ть «?» и по�тавить «?!». Под�казки — из таблицы §3.4. +- «Удалить комментарий» удал�ет �разу, без вопро�а, и показывает то�т «Комментарий удалён (Ctrl+Z — вернуть)» (`Comment deleted (Ctrl+Z to undo)`). То�т нужен, потому что удалить можно длинный книжный тек�т. + +### 5.2. Блок комментари� + +- **Двойной щелчок** по блоку комментари� (главна� лини�) или по тек�ту комментари� в потоке варианта открывает редактор �того комментари�: «по�ле», «перед» или «в начале партии». +- Блок при наведении �легка под�вечивает�� (`widgets.hovered.weak_bg_fill`), как ход. Под�казок при наведении нет: у длинных книжных тек�тов они мешали бы читать. +- **Правый щелчок** по блоку открывает меню из двух пунктов: «Изменить комментарий…» и «Удалить комментарий». +- Выделение тек�та мышью в блоке (чтобы �копировать) пропадает. Копирование о�таёт�� через «Копировать PGN» и через редактор: открыть его и выделить там. + +### 5.3. Меню ☰ + +�овый пункт �разу по�ле «Данные партии… (F2)»: «Комментарий к ходу… (Enter)» (`Comment on the move… (Enter)`). �а корне подпи�ь — «Комментарий в начале партии… (Enter)». Пункт нужен, чтобы функцию можно было найти без правого щелчка. �овой кнопки на панели ин�трументов нет: в узкой панели ме�та нет (`narrow-windows.md` §4a). + +## 6. Запи�ь в партию и отмена + +1. «Готово» вызывает **одну** правку, то е�ть один шаг Ctrl+Z, кур�ор по�ле отмены на �том ходе: + - дл� «по�ле хода» и «начала партии» — `annotate(id, nags, comments_after)`; + - дл� «перед ходом» — нова� правка � `comments_before` (§11). +2. **�ет изменений — нет запи�и.** Е�ли тек�т �овпадает � показанным при открытии (�равнение по�ле обрезки пробелов по кра�м) и знаки не мен�ли�ь, ничего не пишет��, «•» не по�вл�ет��, байты комментари� прежние. Это уже обе�печивает `annotate` (no-op при равен�тве), е�ли UI передаёт и�ходный `Vec`, когда тек�т не тронут. +3. **Сборка нового значени�** (функци� в `chess-core/src/comment.rs`, � те�тами): + - команды (`[%…]`) из в�ех комментариев узла �обирают�� по пор�дку; + - результат — **одна** �трока: `тек�т` + пробел + команды подр�д (`Размен [%cal Gf3d5][%clk 0:03:12]`); без тек�та — только команды; + - е�ли нет ни тек�та, ни команд — пу�той `Vec`, а не `[""]`: `write.rs` иначе запишет `{}`; + - тек�т: кра� обрезаны, пробелы и табы внутри �троки �охран�ют��, переводы �трок — по §8.3. +4. **Пу�той тек�т + Готово = комментарий удалён** (команды и ча�ы о�тают��). То�та нет: человек �ам �тёр тек�т. +5. **«•» и Ctrl+S.** Правка �тавит «•» в шапке (`touch()` → `is_modified()`). Запи�ь — только Ctrl+S / 💾 по `own-databases.md`. Возврат через Ctrl+Z к �охранённому �о�то�нию �нимает «•», как у ходов. �вто�охранени� нет. +6. �нализ партии (`review`) ничего не пере�читывает: комментарии на оценку не вли�ют. К�ш перевода — по §9. + +## 7. Суще�твующие и длинные комментарии (книги, legacy) + +- В редакторе �тоит ровно то, что видно в нотации в режиме «Оригинал»: тек�т без команд, �троки, разбитые перено�ом файла, �литы (`comment_display_text`), абзацы разделены пу�той �трокой. Так человек правит то, что видит, а не жё�ткие перено�ы ChessBase по 80 знаков. +- Длинный тек�т: поле до 12 �трок � внутренней прокруткой (§3.4), рамка � кнопками о�таёт�� на ме�те. +- Пока длинный комментарий не изменён, файл не мен�ет�� (§6.2). Е�ли в нём и�править одну букву, комментарий будет запи�ан заново в виде из §6.3: одна �трока вме�то не�кольких `{}` и без и�ходных жё�тких перено�ов. Смы�л и абзацы �охран�ют�� (при у�ловии §8.3). Это о�ознанна� цена правки, и именно по�тому �равнение «не тронут» об�зательно. +- Комментарий, который �ам �одержит запи�ь ходов («3.e4 Nc6 4.f4 … 1-0, Radjabov …», `r_f2.png`), — обычный тек�т, правит�� как тек�т. +- Варианты, запи�анные тек�том внутри комментари�, ходами не �танов�т��. + +## 8. Тек�т: �имволы, длина, перено�ы + +### 8.1. Символы + +- Разрешены любые Unicode-�имволы, включа� кириллицу и фигурки. +- Символ `}` в PGN-комментарии невозможен. `write.rs` в таком �лучае переходит на `;`-комментарии, и �то громоздко. Решение: при вводе `}` замен�ет�� на `)` (`{` о�таёт��). То�та нет: �лучай редкий. +- В�тавка из буфера (Ctrl+V): табул�ции �танов�т�� пробелами, переводы �трок обрабатывают�� по §8.3. + +### 8.2. Длина + +Без ограничени�: книжные главы бывают длинными. Предупреждений нет. + +### 8.3. �бзацы: зави�имо�ть от запи�и PGN + +Сейча� `write.rs::comment()` разбивает тек�т по пробельным �имволам и �обирает заново (`split_whitespace`). По�тому переводы �трок внутри `{…}` **при запи�и тер�ют��**, в том чи�ле абзацы книжных комментариев, которые �егодн� видны в нотации. Это ка�ает�� любого �охранени�, не только правки. + +- **Рекомендаци� разработчику (малое изменение, отдельна� проверка):** внутри комментари� �охран�ть пу�тую �троку (абзац) при запи�и. �апример, пи�ать `\n\n` как е�ть внутри фигурных �кобок. PGN �то допу�кает; разборщик и `comment_display_text` уже читают такой абзац. +- Когда �то �делано, Shift+Enter в редакторе в�тавл�ет абзац. �е�колько переводов �трок подр�д, в том чи�ле одиночный, запи�ывают�� как одна пу�та� �трока (`\n\n`): одиночный перевод в показе в�ё равно �ливает��. +- До �того Shift+Enter ничего не делает, переводы �трок при в�тавке �танов�т�� пробелами, а редактор работает в один абзац. �бзацы книжного комментари� в редакторе видны, но по�ле правки, как и по�ле любого �охранени�, �ольют��. + +## 9. Перевод комментариев + +- **Правит�� в�егда оригинал.** Перевод — только чтение (`translation-ui.md` §0.1). Е�ли на �кране был перевод �того комментари� (значок ⇄), редактор в�ё равно показывает оригинал. Под полем �тоит �лаба� �трока «⇄ Правит�� оригинал; перевод �того комментари� пропадёт» (`You are editing the original; its translation will be dropped`). +- Перевод хранит�� по тек�ту оригинала (`translations: HashMap`), по�тому изменённый тек�т про�то о�таёт�� без перевода. По�ле любой правки комментариев `GameTranslation` заново решает `plan()` по изменённой партии, лишь по изменённым тек�там: �об�твенный комментарий на �зыке интерфей�а переводить не нужно, а чужой в�танет в очередь по обычным правилам. +- «Копировать PGN» и запи�ь в�егда берут оригинал, как �ейча�. +- В `translation-ui.md` §0.1 фразу «Комментарии в ChessPenguin не редактируют��, по�тому режима правки нет» заменить на «Перевод не редактирует��; правка комментари� мен�ет оригинал (�м. `user-comments.md` §9)». + +## 10. Перва� вер�и� и что потом + +**Перва� вер�и�:** +- редактор в нотации (§3) дл� «по�ле хода» в главной линии и вариантах, «в начале партии» и правки или удалени� �уще�твующих «перед ходом»; +- знаки хода (6) и позиции (8) в редакторе и контек�тном меню; Ctrl+1…6; +- Enter, двойной щелчок, контек�тное меню, пункт ☰; +- �охранение команд, NAG и нетронутых байтов; один шаг отмены; «•» и Ctrl+S; +- перевод (§9), узкие окна (§12), до�тупно�ть (§13). + +**Потом (в пор�дке пользы):** +1. **Стрелки и цветные пол�.** Права� кнопка � прот�жкой по до�ке ри�ует �трелку, правый щелчок по полю — круг. Цвет — от модификатора, как в Lichess: без модификатора зелёный, Shift — кра�ный, Alt — �иний, Shift+Alt — жёлтый. Запи�ывают�� в комментарий текущего хода как `[%cal]` и `[%csl]`. Повтор той же �трелки �нимает её. Отдельный шаг отмены. Отдельный проект: конфликт � правым щелчком, который �нимает выбор фигуры, и � предпро�мотром движка. +2. �бзацы (§8.3), е�ли не войдут в первую вер�ию. +3. Создание комментари� «перед ходом» (Shift+Enter в партии или пункт меню у первого хода варианта). +4. Прочие NAG: □, N, ⟳, →, ↑, ⇆, ∆ — во в�плывающем «Ещё…». +5. Режим «редактор �ледует за ходом»: Alt+�/→ в поле — �охранить и перейти, редактор о�таёт�� открытым. Дл� подробного разбора партии подр�д. +6. Пои�к по тек�ту комментариев в библиотеке. + +**�е делаем:** +- �зыки комментариев, как в ChessBase; +- форматирование тек�та (жирный и т. п.); +- проверку орфографии; +- в�тавку диаграмм. + +�а Android парти� только дл� про�мотра (`android-app.md`), по�тому там правки нет. + +## 11. Что �троит разработчик + +1. **`chess-core`:** + - `comment.rs`: `pub fn editable_text(comments: &[String]) -> String` (то же, что `comment_display_text`, � абзацами) и `pub fn with_text(comments: &[String], text: &str) -> Vec` по §6.3. Те�ты: команды �охран�ют��, пу�той тек�т о�тавл�ет только команды, нет команд и тек�та — пу�той `Vec`, `}` → `)`. + - `edit.rs`: `Annotations` дополнить `comments_before`, а `annotate` разделить на `set_after(id, nags, comments_after)` (нынешнее поведение) и `set_before(id, comments_before)`. Обе — один шаг отмены и no-op без изменений. Те�т «перед»: отмена и повтор, кур�ор. + - `pgn/write.rs`: абзацы по §8.3 (отдельной правкой) � те�том «запи�ь → чтение → `comment_display_text` равен». +2. **`notation.rs`:** + - `Notation` получает `editing: Option<&mut CommentEditor>`: цель, черновик тек�та и NAG, флаг «перевод был показан». + - Главна� лини�: на ме�те `comment_block` нужной цели ри�ует�� редактор; дл� «по�ле хода» �трока таблицы �бра�ывает�� (`row.flush`) так же, как при �уще�твующем комментарии. + - **Вариант:** `inline_line` переделать на два шага. Сначала обход дерева в пло�кий �пи�ок токенов (`Move(id, label)`, `Comment(slot, text)`, `Open`, `Close`, `Unparsed`) — рекур�и� только тут. Затем ра�кладка токенов ку�ками в `horizontal_wrapped`. Е�ли редактор открыт внутри варианта, �пи�ок режет�� по�ле токена хода (или вме�то токена комментари�): ку�ок, редактор, ку�ок, внутри одной `block_frame`. + - `NotationResponse` получает `edit: Option` (двойной щелчок, пункт меню), `nag: Option<(NodeId, Nag)>` (значок в меню), `delete_comment: Option`. Блоки комментариев получают `Sense::click()` (двойной и правый щелчок). +3. **`game_view.rs`:** + - �о�то�ние `comment_editor: Option`; + - `keyboard()`: Enter и Ctrl+1…6 (§4); + - перехват Enter/Ctrl+Enter/Esc/Ctrl+S/Ctrl+W в редакторе до `TextEdit`, через `consume_key` в начале кадра, пока поле в фоку�е. Enter надо �н�ть до того, как `TextEdit` в�тавит перевод �троки; + - «�охранить и закрыть» в `goto`, `play_move`, `step_*` и при уходе; + - ↩ ↪ неактивны при открытом редакторе; + - пункт ☰ (§5.3); то�т удалени�. + - Хук дл� �нимков: `CP_COMMENT_EDIT=after|root|var` — открыть редактор на текущем ходе (по аналогии � `debug_comment`). +4. **`translate_ui.rs`:** перепланирование по�ле правки комментариев (§9). +5. **README / «Что нового»:** «Свои комментарии: Enter на ходу или правый щелчок → «Комментарий…»; оценки ! ? — Ctrl+1…6». + +## 12. Узкие окна + +По `narrow-windows.md`: компоновку определ�ет размер окна, редактор её не мен�ет. + +- **Р�дом, панель 240–300 (окно 640 × 480):** + - заголовок короткий, кнопки — значки ✓ ✕; + - знаки позиции �вёрнуты в «±▾», �троки-под�казки «Enter — готово…» нет; + - поле от 2 �трок, вы�ота рамки ≈ 24 + 28 + 2 × 20 + от�тупы ≈ 110; ниже рамки в�егда о�таёт�� ме�то хот� бы дл� одной �троки нотации, и нотаци� прокручивает�� к рамке (§3.4); + - ничего не налезает: рамка не шире панели, тек�т перено�ит��. +- **Стопка (640 × 1000, ширина 640):** в�ё в одну �троку, как при 1400. +- **Контек�тное меню** — в�плывающее, не зави�ит от ширины панели. Р�д знаков позиции (8 × 28 ≈ 240) помещает��. +- **�е превышать минимум панели** (`SIDE_MIN` 240): у рамки нет фик�ированной ширины, а значки хода (≈ 200) — �амое широкое неделимое. + +``` +640 × 480, панель 240 640 × 1000, �топка +│ 4 │ Ba4 [Nf6] │ │ 4 │ Ba4 [Nf6] │ +│┌ По�ле 4…Nf6 ✓ ✕ �│ │ ┌ Комментарий по�ле 4…Nf6 [Готово] [Отмена]�│ +││ ! ? !! ?? !? ?! ±▾ ││ │ │ ! ? !! ?? !? ?! │ = ∞ ⩲ ⩱ ± ∓ +− −+ ││ +││▌Главный ход. �││ │ │▌Главный ход. Возможно и 4…d6| �││ +││▌Возможно и 4…d6| �││ │ │ Enter — готово · Esc — отмена ││ +│└────────────────────┘│ │ └─────────────────────────────────────────────────┘│ +│ 5 │ O-O Be7 │ │ 5 │ O-O Be7 │ +``` + +## 13. До�тупно�ть + +- У пол� е�ть до�тупное им� — заголовок редактора: `labelled_by` или `widget_info` «Комментарий по�ле 4…Nf6». Под�казка «Ваш комментарий…» именем не �лужит. +- Значки — переключатели � именем из таблицы §3.4 и �о�то�нием «нажато» (`WidgetType::SelectableLabel`, `selected`). Пор�док Tab — по §4. +- В�ё до�тупно � клавиатуры: Enter открывает, Ctrl+1…6 �тав�т оценку, Tab ведёт по значкам, Enter или Esc закрывают. Мышь не об�зательна: оценка позиции �тавит�� через Tab → значок → пробел. +- Рамка редактора отличает�� обводкой цвета выделени� и заголовком, а не только цветом. Значки оценок различимы по �имволу, цвет лишь дублирует. +- Контра�т: тек�т в поле — `comment_color` на `extreme_bg_color`, как у �уще�твующих блоков (уже проверено в �ветлой и тёмной теме). +- По�ле «Готово» фоку� возвращает�� партии, так что �трелки �нова ход�т. Хорошо бы �ообщить �кранному чтению (accesskit) «Комментарий �охранён»; �то не об�зательно. + +## 14. Пути пользовател� + +1. **Тренер комментирует партию ученика.** + - Открыл партию → → → до 12…Nf6. + - Ctrl+2: у хода по�вило�ь «?». + - Enter → «�ужно было 12…Be7, конь уходит � защиты» → Enter. + - → → → Правый щелчок по 14.Ng5 → «!». + - Ctrl+S → «Сохранено в «Петров»». + - �и одного окна. +2. **В варианте.** Щелчок по 7…Bxf3 внутри блока варианта → Enter: блок ра�крыл�� у хода, поле под ним → тек�т → Enter: тек�т в�тал в поток по�ле хода. +3. **Книжный комментарий � опечаткой.** Двойной щелчок по блоку → поле � тек�том (8 �трок, прокрутка внутри) → и�правил �лово → Enter. Ошиб�� — Ctrl+Z вне пол� вернул прежний тек�т. +4. **Удалить чужой комментарий.** Правый щелчок по блоку → «Удалить комментарий» → то�т «Комментарий удалён (Ctrl+Z — вернуть)». +5. **Парти� � немецкими комментари�ми, показан перевод.** Двойной щелчок → в поле немецкий оригинал и �трока «⇄ Правит�� оригинал…» → человек допи�ал �воё по-ру��ки → Готово → комментарий показан как напи�ан (без ⇄). +6. **�ова� парти� без ходов.** Enter → «Комментарий в начале партии» → «Разбор � зан�ти� 25.10» → Enter → ходы на до�ке. + +## 15. Чек-ли�т те�тировщика + +1. Enter на ходе главной линии (белые, чёрные), в варианте, во вложенном варианте, на корне, в пу�той партии: правильный заголовок и ме�то рамки, �трока таблицы разорвана, вариант ра�крыт у хода. +2. Готово без изменений: «•» не по�вило�ь, Ctrl+Z не добавил шаг, PGN побайтно прежний. +3. Комментарий � `[%cal Ra1a8][%csl Gd4][%clk 0:03:00]` и тек�том: в поле нет команд. По�ле правки и по�ле очи�тки тек�та �трелка на до�ке и ча�ы �охранили�ь. +4. `{a} {b}` у одного хода: в поле «a b», по�ле правки один комментарий. +5. Esc отмен�ет и тек�т, и знаки, партию не закрывает. Второй Esc (вне пол�) закрывает партию как раньше. +6. Щелчок по другому ходу, ход на до�ке, ◀ ▶, «⬅ Библиотека», закрытие программы � открытым редактором: тек�т �охранён, затем дей�твие (вопро� «Парти� изменена» при уходе). +7. Ctrl+S в поле: запи�ано вме�те � тек�том. Ctrl+Z в поле — отмена набора; вне пол� — отмена в�его комментари� одним шагом, кур�ор на ходе; Ctrl+Y возвращает. +8. Ctrl+1…6 вне пол�: �тавит, повтор �нимает, другой знак замен�ет; $32 и N о�тают��. В меню знаки �тав�т�� �разу, меню не закрывает��. +9. Стрелки, F, L, Home в поле — редактирование тек�та, не ходы. Enter, закрывший «Добавить в базу», не открывает редактор. +10. `}` превращает�� в `)`. В�тавка много�трочного тек�та — по §8.3. Пу�той итог — нет `{}` в PGN. +11. Перевод показан → правка → �трока «⇄ Правит�� оригинал…», по�ле Готово — оригинал без ⇄, «Копировать PGN» �одержит новый тек�т. +12. 640 × 480, 640 × 1000, 960 × 1050, 1400 × 900: ничего не налезает, «±▾» при узкой панели, рамка видна по�ле открыти�, кнопки не уход�т за �кран при длинном тек�те. +13. И�точник ChessBase или онлайн: правка возможна, Ctrl+S → «Добавить в базу…». +14. Предпро�мотр линии движка: Enter не открывает редактор; щелчок по ходу «Лучше:» при открытом редакторе �охран�ет и закрывает его. + +## 16. Вопро�ы владельцу + +1. **Где пи�ать:** пр�мо в нотации на ме�те комментари� (A, рекомендую) или поло�ой внизу, как в Lichess (B)? +2. **Esc при длинном тек�те** выбра�ывает черновик без вопро�а. Это пред�казуемо, но можно потер�ть абзац. О�тавить так или �делать Esc равным «Готово», как в Lichess и En Croissant, где уход �охран�ет? +3. **Ctrl+1…6 дл� знаков** или цифры 1…6 без Ctrl, как в En Croissant? Цифры без Ctrl бы�трее, но займут клавиши будущего ввода ходов тек�том. +4. **�бзацы (§8.3):** делать правку запи�и PGN �ейча�? От неё зави��т Shift+Enter и �охранно�ть абзацев книжных комментариев при любом �охранении. +5. **Стрелки и пол�** — �ледующим шагом по�ле комментариев или позже? +- 2026-10-25: решени� владельца (`decisions.md` п. 20): вариант A, Esc — отмена, значки мышью в меню и редакторе плю� Ctrl+1…6, �трелки и пол� на до�ке — в первую вер�ию (�м. «Потом» п. 1 — перене�ено в первую вер�ию). +- 2026-10-25, по�ле проверки реализации (те�тировщик + дизайнер): кнопки — «Готово» у правого кра�, «Отмена» �лева от неё, обе 30 вы�отой (как во в�ех окнах); в узкой панели — нари�ованные ✓/✕ 30 × 30 (в шрифте нет таких глифов); значки 24 × 24, порог дл� двух групп в одну �троку — 154 + 4 + 12 + 4 + 206 = 380 (в панели 240 — 22 × 24 и «±▾»); нажатый значок — цветом тек�та выделени�, не цветом оценки; поле в �об�твенной рамке (фон панели / белый, обводка 1); под�казка под полем 11,5 � от�тупом 4; вы�ота пол� ограничена так, чтобы над и под редактором о�тавало�ь по �троке нотации, при открытии в вид прокручивает�� и �трока хода; у длинного комментари� конец (� кур�ором) виден �разу; продолжение варианта по�ле редактора начинает�� � номера хода; Shift+Enter — абзац (провер�ет�� раньше Enter); блок комментари� под�вечивает�� под мышью и целиком принимает двойной и правый щелчок; заметка на �зыке интерфей�а в чужой книге не идёт в перевод. diff --git a/docs/design/web-version.md b/docs/design/web-version.md new file mode 100644 index 0000000..de8838e --- /dev/null +++ b/docs/design/web-version.md @@ -0,0 +1,876 @@ +# Веб-вер�и� (лёгка�): интерфей� + +Стату�: проект дизайнера, 2026-10-30, **не утверждён**. Задача — `docs/dev/tasks.md` §22, подпроект `web/`. + +Об�зательные решени� владельца — `docs/decisions.md` «Веб-вер�и� (2026-10-30)» и уточнение того же дн� (через орке�тратора): **под телефон веб-приложение не делаем**; на телефоне вме�то приложени� — �траница-заглушка (§3.6). iPad и компьютер — веб-приложение. + +Опирает�� на: `docs/research/web-version.md` (аналитик: возможно�ти браузеров, квоты, PWA), `docs/research/web-version-tech.md` (разработчик: прототип в Firefox, Stockfish в wasm, файлы, воркеры), `narrow-windows.md` (компоновка по размеру окна), `android-ui.md` и `android-play.md` (ка�ание, нижн�� панель, отчёт, ввод ходов пальцем), `user-comments.md` (Ctrl+1…6), `move-notation.md`, `reference.md`. Снимки: программа в браузере — `target/webresearch/shot2.png`, `shot3.png`, `shot5.png`; компьютер — `website/static/screenshots/04-review-1280.jpg` и др.; телефон — `website/static/screenshots/phone/`. + +Обозначени�: **Факт** — проверено по и�точнику или коду (��ылка в и��ледовани�х). **Проверить** — утверждение по пам�ти или по вторичному и�точнику; разработчик провер�ет на прототипе до реализации. Размеры — логиче�кие точки egui; в браузере 1 точка = 1 CSS-пик�ель (eframe �тавит `pixels_per_point = devicePixelRatio`), �то то же, что dp на Android и pt на iPad. + +## 0. Главное + +1. **Это та же программа.** Веб-вер�и� — на�тольный интерфей� (egui в ``), а не новый �айт. Кто попробовал в браузере, узнает программу по�ле у�тановки, и наоборот. Отличи� — только там, где браузер не даёт иначе: файлы, клавиши, хранение, ка�ание. +2. **Лёгка� вер�и� = попробовать и поработать � партией:** открыть PGN/архив, �мотреть, вводить ходы и варианты, комментарии, живой анализ Stockfish 19, разбор � ?!/?/?? и !!/!, отчёт и график, �качать PGN. �ет: полки больших баз, �правочника, пои�ка по позиции, подготовки к �опернику, игры, тренировки, онлайн-партий, других движков, офлайна. +3. **Файлы пользовател� только читают��.** Правки партии из файла �охран�ют�� в «Мои партии» (в браузере) или �качивают��. �ичего не пишет�� в файл на ди�ке — ни в Chrome, ни где-либо ещё. +4. **В�ё, что лежит в браузере, че�тно подпи�ано:** где хранит��, �колько занимает, что пропадёт при очи�тке данных �айта, и в�егда р�дом «Скачать в�ё в PGN». +5. **Три �реды:** компьютер (мышь), iPad (палец; альбом и портрет), телефон — �траница-заглушка � приложением дл� Android и ответом дл� iPhone. +6. **Без в�плывающих уговоров.** У�тановку как приложени� предлагаем там, где она решает на�то�щую проблему (iPad: Safari �тирает данные), и только в момент, когда �то важно. + +## 1. Со�тав лёгкой вер�ии и как она выгл�дит + +### 1.1. Карта �кранов + +``` + ��ылка � �айта /app/ + │ + ▼ + ┌──────────────� телефон (§3.6) ─────────────▶ �траница «ChessPenguin на телефоне» + │ определение │ └ «В�ё равно открыть веб-вер�ию» ─� + │ у�трой�тва │ компьютер, iPad ──� │ + └──────────────┘ ▼ │ + ┌──────────────� ◀──────────────────────────────────────┘ + ⚙ �а�тройки ◀────── │ Библиотека │ ──── «Открыть файл», перета�кивание, «В�тавить PGN» + └──────┬───────┘ + │ парти� (двойной щелчок / ка�ание) + ▼ + ┌──────────────� движок, разбор, отчёт, «Скачать PGN», + │ Парти� │ «Сохранить в Мои партии» (Ctrl+S) + └──────────────┘ +``` + +- Экранов два, как на компьютере: **Библиотека** и **Парти�**. Переход в партию добавл�ет запи�ь в и�торию браузера (`history.pushState`), по�тому кнопка «�азад» браузера, Alt+�, бокова� кнопка мыши и же�т от левого кра� в Safari на iPad означают «� Библиотека» — � теми же вопро�ами о не�охранённом, что и кнопка в шапке (§2.6). Из Библиотеки «�азад» уводит �о �траницы — �то обычное поведение браузера, мы его не трогаем. +- �дре� не мен�ет�� по парти�м (`/app/` в�егда): ��ылка на партию из чужого файла бе��мы�ленна. И�ключение — ��ылки на в�троенные примеры (§1.3). + +### 1.2. Первый �кран: Библиотека при первом входе + +Человек пришёл � �айта по кнопке «Открыть в браузере». Он ещё ничего не открывал. Библиотека — та же, что на компьютере (полка карточек �верху, �права кнопки), только в центре вме�то таблицы — привет�твие � ме�том дл� файла. + +``` +1400 × 860, первый вход +┌──────────────────────────────────────────────────────────────────────────────────────────────────� +│ Базы ♟ �ова� парти� 📋 В�тавить PGN ⇩ У�тановить ⚙ │ +│ ┌──────────────────� ┌──────────────────� ┌──────────────────� ┌──────────────────� │ +│ │ ★ Кла��ика │ │ ★ �лехин │ │ ✎ Мои партии │ │ + Открыть файл… │ │ +│ │ 100 партий │ │ 267 партий │ │ пока пу�то │ │ PGN, CBV, ZIP, 7Z│ │ +│ └──────────────────┘ └──────────────────┘ └──────────────────┘ └──────────────────┘ │ +├──────────────────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ � │ +│ Перетащите �юда файл � парти�ми │ +│ │ │ │ +│ [ Открыть файл… ] PGN · ChessBase CBV · ZIP · 7Z │ +│ │ │ │ +│ Файл только читает�� и не уходит на �ервер: в�ё работает │ +│ │ в вашем браузере. │ │ +│ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │ +│ │ +│ Или начните � примера: 100 кла��иче�ких партий › Партии �лехина › �ова� парти� › │ +│ │ +│ �ужны большие базы, игра � компьютером, подготовка к �опернику? │ +│ Скачайте программу дл� компьютера ↗ │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ +``` + +- **Полка.** Карточки примеров (★ — в�троенный, только чтение), «Мои партии» (✎ — хранит�� в браузере, §2.3), открытые раньше файлы (§2.2), �права отдельно «+ Открыть файл…» — как зона дей�твий в `library-layout.md` §1. Карточки «+ �ова� база», «� Онлайн-партии» в лёгкой вер�ии не ри�уют�� (принцип «чего нет — не ри�уем»). +- **Привет�твие** показывает��, пока не выбрана ни одна база (первый вход или в�е карточки убраны). Дальше Библиотека открывает�� на по�ледней выбранной базе, как на компьютере. +- **Перета�кивание** работает над в�ем окном, не только над рамкой: при наведении файла поверх �крана — полупрозрачна� заливка `accent` 12 % и надпи�ь «Отпу�тите, чтобы открыть». �е�колько файлов — каждый �воей карточкой; первый выбирает��. +- **«📋 В�тавить PGN»** — как на компьютере: в Chrome/Edge читает буфер по кнопке (браузер �про�ит разрешение), в Firefox/Safari открывает поле, куда в�тавл�ют Ctrl+V / «В�тавить» из меню (�обытие `paste` работает везде без разрешений). В�тавленные партии — во временной карточке «Из буфера» до �охранени� в «Мои партии». +- **«⇩ У�тановить»** — только когда браузер может у�тановить приложение (§5); иначе кнопки нет. +- **«�ова� парти�»** — пу�та� парти�, при �охранении попадает в «Мои партии». +- **Язык** — по `?lang=` из ��ылки �айта, иначе выбранный раньше в на�тройках, иначе первый подход�щий из `navigator.languages` �реди 9 �зыков, иначе англий�кий. +- В шапке нет ше�терёнки «Обновить программу», «Онлайн-партии», «Подготовка» — их в веб-вер�ии нет. + +**Примеры по ��ылке.** Сайт может ве�ти �разу на пример: `/app/?open=classics` (база), `/app/?open=classics&game=3` (парти�). Только дл� в�троенных примеров. Это даёт кнопкам �айта «по�мотреть разбор Бе��мертной» пр�мой путь. + +**Открытый файл.** По�ле выбора файла — та же таблица партий, что на компьютере (пои�к, �ортировка, фильтры дл� небольших баз), `narrow-windows.md` §2. Ограничение лёгкой вер�ии — §2.5. + +### 1.3. Экран партии + +Тот же �кран, что на компьютере (`shot3.png`, `04-review-1280.jpg`): шапка, до�ка � поло�ой оценки, �права �трока движка, вкладки **�отаци� | Отчёт**, панель ин�трументов. Вкладки «Справочник» в лёгкой вер�ии нет (ему нужна полка баз; открытый вопро� 3). + +``` +1400 × 860, мышь +┌──────────────────────────────────────────────────────────────────────────────────────────────� +│ � Библиотека │ �ндер�ен, �дольф — Дюфрен, Жан 1-0 ⇩ Скачать PGN ▾ ⚙ │ +│ │ Кла��ика · № 3 · Берлин 1852 · C52 │ +├───────────────────────────────────────────────────────┬──────────────────────────────────────┤ +│ ▌┌────────────────────────────────────────────────� │ �нализ: вкл +1.9 гл.24 · Stockfish ⚙│ +│ ▌│ │ │ 19.Rad1 Qxf3 20.Rxe7+ … │ +│ ▌│ ДОСК� │ ├──────────────────────────────────────┤ +│ ▌│ │ │ �отаци� [Отчёт] │ +│ ▌│ │ │ ○ �ндер�ен !! 1 ! 4 ?? 1 85 %│ +│ ▌└────────────────────────────────────────────────┘ │ � Дюфрен !! 0 ! 2 ?? 3 73 %│ +│ �▂▃▅▆▇ график оценки (когда е�ть разбор) ▇▆▅▃▂� │ … │ +│ │ � ◀ ▶ � │ 🔃 ↩ ↪ │ ☰ 💾 │ 📈 │ +└───────────────────────────────────────────────────────┴──────────────────────────────────────┘ +``` + +Отличи� от на�тольной вер�ии: + +| Где | �а компьютере | В вебе | +|---|---|---| +| Шапка �права | «� �айти в базе ▾», «⚙» | **«⇩ Скачать PGN ▾»** (меню: «Эту партию (.pgn)», «В�ю базу � моими правками (.pgn)» — §2.4), «⚙». «�айти в базе» нет | +| 💾 / Ctrl+S | �охранить в базу партии или в выбранную | **«Сохранить в Мои партии»** (§2.4); дл� партии из «Моих партий» — �охранить в неё | +| Разбор 📈 | запу�к �разу, оценка времени в под�казке | мышь — так же; ка�ание — короткий ли�т � оценкой времени и «�нализировать» (под�казок у пальца нет), как Android §21.2 | +| Движок ⚙ | выбор движка, потоки, пам�ть | только «Линий» (1–5) и «Врем� на позицию»; потоки и пам�ть — автоматиче�ки (§1.5) | +| «Запи�ать анализ в партию» | мен�ет партию в базе | мен�ет партию в пам�ти → �то правка, её �охран�ют в «Мои партии» или �качивают | + +- **Разбор � !!/!** — те же правила и тот же пои�к (1 млн узлов, 1 поток, Hash 32): **Факт** — оценки Stockfish 19 wasm побитово �овпадают � нативными (`web-version-tech.md` §2.2), по�тому отметки и точно�ть те же, что в программе и на Android. Отчёт (вкладка «Отчёт»), график под до�кой, значки !!/! на до�ке, переход к ходам — как на компьютере. +- **Параллельно�ть разбора** — воркеры � отдельным движком в каждом: компьютер — по `navigator.hardwareConcurrency`, не больше 8; iPad — не больше 3 (пам�ть ≈ 130 МБ на воркер, **проверить** на iPad); оценка времени — по �коро�ти прошлого разбора на �том у�трой�тве. +- **Вкладка в фоне.** Живой анализ о�танавливает��, когда вкладка �крыта (`visibilitychange`), и �ам продолжает�� при возврате (кнопка о�таёт�� включённой) — �кономи� батареи и че�тно�ть: браузер в�ё равно тормозит фоновые вкладки. Разбор на компьютере продолжает�� в фоне; на iPad Safari его прио�танавливает — при возврате он продолжает�� � недо�тающих позиций (по�читанное в к�ше). Пока идёт разбор, заголовок вкладки браузера: «�нализ 23/80 · ChessPenguin». +- **Уход �о �траницы** (закрыть вкладку, F5, вве�ти адре�) при не�охранённых правках или идущем разборе — �тандартный вопро� браузера «Покинуть �айт?» (`beforeunload`; �вой тек�т браузеры не показывают — **факт** общеизве�тный). Внутри программы (� Библиотека, «�азад» браузера) — наш вопро�, §2.6. + +### 1.4. Движок: �качивание один раз + +Движок — 78 МБ (brotli; **факт**, `web-version-tech.md` §2.1) — не грузит�� вме�те � программой. Первое нажатие «�нализ» (L) или 📈 открывает окно: + +``` +┌ Движок Stockfish 19 ──────────────────────────────� +│ Оценивает позицию, показывает лучшие ходы и │ +│ разбирает партию. Скачивает�� один раз и хранит�� │ +│ в �том браузере. │ +│ │ +│ Размер: 78 МБ · �вободно дл� �айта: 9,6 ГБ │ +│ │ +│ [�е �ейча�] [Скачать] │ +└───────────────────────────────────────────────────┘ +``` + +- Ход загрузки — поло�а в том же окне «Скачано 23 из 78 МБ» и «Отменить»; окно можно закрыть — загрузка идёт, на кнопке «�нализ» кольцо прогре��а. Готово → движок �разу включает�� (или �тартует разбор, е�ли звали его). +- Ошибки — тек�ты Android §8.4 (нет �ети, оборвало�ь, не хватает ме�та, файл повреждён), � проверкой SHA-256. +- Сохран�ет�� в Cache API/OPFS, виден в «Данных в браузере» (§2.3) � кнопкой «Удалить». +- Пока движок не �качан, �трока движка: «�нализ: выкл · Stockfish не �качан». +- Облегчённа� �еть (1,1 МБ, другие оценки) в лёгкой вер�ии **не и�пользует��**: разбор на ней дал бы другие отметки, а два движка � разными оценками в одной программе путают (открытый вопро� 5). + +### 1.5. �а�тройки (минимум) + +Окно на�троек как на компьютере (`shot5.png`), вкладки: + +| Вкладка | Что е�ть | Чего нет (по �равнению � компьютером) | +|---|---|---| +| **До�ка и фигуры** | до�ка, набор фигур (ча�ть наборов: по 4–6 лучших, о�тальные — открытый вопро� 6), координаты, запи�ь ходов (`move-notation.md`) | — | +| **Движок** | Линий 1–5, Врем� на позицию (10 �, 20 �, 1 мин, без ограничени�), «Stockfish 19 · �качан · 78 МБ [Удалить]» | �пи�ок движков, «Выбрать файл движка…», потоки, пам�ть | +| **Интерфей�** | �зык (9), тема (как в �и�теме / �ветла� / тёмна�), звук вкл/выкл, **«Крупные кнопки дл� пальца: �вто / Вкл / Выкл»** (§3.1) | перевод комментариев (ChatGPT) | +| **Данные в браузере** | §2.3 | — | +| **О программе** | вер�и�, «У�тановить как приложение» (§5), лицензии (ChessPenguin GPL-3.0-or-later, Stockfish GPL-3.0, шрифты, фигуры), «И�ходный код �той вер�ии ↗», «Программа дл� компьютера ↗», «Сайт ↗» | проверка обновлений (веб-вер�и� обновл�ет�� �ама при �ледующем открытии) | + +Потоки живого анализа — автоматиче�ки: компьютер — половина `hardwareConcurrency`, не больше 8; iPad — 2. Многопоточный движок требует COOP/COEP (решение владельца: �тавим на `/app/`); е�ли �траница в�ё же не изолирована, работает однопоточный, без �ообщений пользователю. + +## 2. Файлы и хранение + +### 2.1. Две полки — два правила + +| Что | Где лежит | Можно ли потер�ть | +|---|---|---| +| **Ваши файлы** (PGN, CBV, ZIP, 7Z) | на ди�ке; программа только читает | нет: программа их не мен�ет | +| **Копи� файла в браузере** (по желанию, §2.2) | хранилище �айта (OPFS) | да, при очи�тке данных �айта; оригинал на ди�ке цел | +| **Мои партии** — новые партии, правленые копии, партии � запи�анным разбором | хранилище �айта | да — по�тому «Скачать в�ё в PGN» | +| Разборы партий (к�ш), отметки «про�мотрено», на�тройки, движок | хранилище �айта | да; разборы пере�читывают��, движок �качивает�� �нова | + +### 2.2. Открытые файлы: только чтение, � ди�ка + +**Chrome / Edge** (File System Access API, **факт**: `web-version.md` §3.1). «Открыть файл…» вызывает `showOpenFilePicker`; программа хранит ��ылку на файл (в IndexedDB). В �ледующий раз карточка на полке: + +``` +┌──────────────────────� ┌──────────────────────� +│ 🗄 Alekhin.pgn │ │ 🗄 Alekhin.pgn │ +│ 267 партий │ → │ 267 партий │ +│ 🔒 Разрешить чтение │ щелчок│ │ +└──────────────────────┘ └──────────────────────┘ +``` + +- Пока разрешени� нет, на карточке �трока «🔒 Разрешить чтение» (цвет `accent`). Щелчок по карточке → `requestPermission()` → браузер �ам �прашивает «Разрешить ChessPenguin про�матривать Alekhin.pgn?». В Chrome 122+ там е�ть «Разрешать в�егда» (**проверить**) — тогда �троки больше не будет. +- Отказ → карточка о�таёт�� � той же �трокой; �низу на 4 �: «Без разрешени� браузер не даёт прочитать файл». +- Файл изменил�� на ди�ке → читает�� заново (как на компьютере, по размеру и времени). +- Файл удалён или перемещён → «Файл не найден на ди�ке. [Выбрать �нова] [Убрать � полки]». + +**Firefox / Safari** (API нет — **факт**). Файл выбирает�� через ``; ��ылку �охранить нельз�. Программа помнит **им�, размер и отпечаток** (SHA-256 первых 1 МБ + размер), чтобы вернуть отметки «про�мотрено» и к�ш разборов. По�ле перезагрузки: + +``` +┌──────────────────────� +│ 🗄 Alekhin.pgn │ +│ 267 партий │ +│ ↻ Выбрать файл �нова │ +└──────────────────────┘ +``` + +- Щелчок → �и�темный выбор файла (под�казка в нём, где он был, браузеры не дают). Выбран тот же файл (отпечаток �овпал) — открывает�� как был. Другой файл � тем же именем — открывает�� как новый, �тара� карточка замен�ет��, без вопро�ов. +- Под полкой один раз за �еан�, �лабым тек�том: «Этот браузер не запоминает файлы: по�ле перезагрузки выберите файл �нова или о�тавьте копию в браузере.» + +**«О�тавить копию в браузере»** — пункт меню карточки файла (во в�ех браузерах; в Chrome/Edge полезен мало, но не пр�чем — одинаково везде). Окно: + +``` +┌ О�тавить копию в браузере ────────────────────────� +│ Alekhin.pgn · 2,7 МБ │ +│ │ +│ Копи� откроет�� �разу, без выбора файла. Она │ +│ хранит�� в �том браузере на �том у�трой�тве и │ +│ пропадёт, е�ли очи�тить данные �айта. Файл на │ +│ ди�ке не мен�ет��. │ +│ │ +│ Зан�то �айтом: 96 МБ · �вободно: 9,6 ГБ │ +│ │ +│ [Отмена] [О�тавить копию] │ +└───────────────────────────────────────────────────┘ +``` + +- Ме�то — из `navigator.storage.estimate()`: «�вободно» = `quota − usage` (�то квота �айта, а не �вободное ме�то ди�ка; так и называем — «�вободно дл� �айта» в на�тройках). +- **�е помещает��** (`размер × 1,1 > �вободно`): кнопка «О�тавить копию» неактивна, вме�то опи�ани� ме�та: «�е помещает��: копии нужно 1,2 ГБ, а браузер даёт �айту ещё 900 МБ. О�вободите ме�то в «Данных в браузере» или открывайте файл � ди�ка.» Е�ли квота неизве�тна — пробуем запи�ать; при ошибке запи�и — тот же тек�т без чи�ел и копи� удал�ет�� целиком (половины копии не бывает). +- Карточка � копией: значок ⧉ и �трока «копи� в браузере». Меню: «Удалить копию» (файл на ди�ке не трогает��). +- Копи� **не обновл�ет��** �ама, е�ли файл на ди�ке изменил�� (браузер не видит ди�к). Меню: «Обновить копию из файла…» (выбор файла). + +### 2.3. «Мои партии» и «Данные в браузере» + +**«Мои партии»** — одна �во� база в браузере (PGN в OPFS), карточка на полке в�егда (пу�та� — «пока пу�то»). Что туда попадает: + +- нова� парти� при �охранении (Ctrl+S / 💾); +- парти� из файла или примера, которую поправили и �охранили (копи�; тег `Source` � именем файла — **предложение**, чтобы видно было, откуда); +- парти� � запи�анным разбором («Запи�ать анализ в партию» + �охранить); +- в полной вер�ии — �ыгранные � движком (ме�то готово, в лёгкой их нет). + +Меню карточки и шапка таблицы «Моих партий»: **«Скачать в�ё в PGN»** (`ChessPenguin-my-games-2026-10-30.pgn`), удаление партии (Delete, � отменой Ctrl+Z, как на компьютере), «Очи�тить в�ё…» (подтверждение � чи�лом партий; перед �тим — кнопка «Сначала �качать»). �а карточке втора� �трока: «12 партий · �качано 3 дн� назад» или «12 партий · ещё не �качаны» (цвет `warn`, е�ли е�ть партии, не �качанные больше 14 дней, — без окон и уговоров). + +**По�то�нное хранение.** При **первом** �охранении в «Мои партии» или первой копии файла программа вызывает `navigator.storage.persist()` (�то дей�твие пользовател� — Firefox покажет �вой вопро�; Chromium и Safari решают �ами, **факт**: `web-version.md` §3.2). Перед вопро�ом Firefox — �трока в окне �охранени�: «Браузер �про�ит, можно ли хранить данные по�то�нно, — разрешите, чтобы партии не пропали при нехватке ме�та.» + +**�а�тройки → «Данные в браузере»:** + +``` +Данные в �том браузере +В�ё ниже хранит�� только зде�ь, на �том у�трой�тве. Файлы на ди�ке не мен�ют��. + +Зан�то 96 МБ · �вободно дл� �айта 9,6 ГБ +По�то�нное хранение: ✓ включено (или ⚠ не разрешено браузером) + + Мои партии · 12 партий 340 КБ [Скачать в�ё в PGN] + Копии файлов · 2 16 МБ [Удалить…] + Движок Stockfish 19 78 МБ [Удалить] + Разборы партий · 31 1,2 МБ [Очи�тить] + Запомненные файлы, отметки, на�тройки 40 КБ + +Е�ли очи�тить данные �айта в браузере, в�ё �то пропадёт. +Скачайте �вои партии в PGN, чтобы не потер�ть их. +``` + +- В Safari (не у�тановленном, §5) — ещё �трока `warn`: «Safari удал�ет данные �айта, е�ли не открывать его 7 дней. У�тановите ChessPenguin на �кран «Домой» или �качивайте партии.» (**факт** про 7 дней — WebKit 2020, на 2026 **проверить**). +- Чи�ла — из `estimate()` и размеров файлов в OPFS; «Удалить…» у копий открывает �пи�ок � размерами. + +### 2.4. Сохранение и �качивание + +| Дей�твие | Что делает | +|---|---| +| **Ctrl+S / 💾 «Сохранить в Мои партии»** | Парти� из «Моих партий» — �охран�ет�� в неё же. Люба� друга� (пример, файл, буфер, нова�) — копи� в «Мои партии»; по�ле �того открыта� парти� — уже �та копи� (шапка: «Мои партии · № 13»), дальнейшие Ctrl+S пишут в неё. Подтверждение внизу на 4 �: «Сохранено в «Мои партии» · Скачать PGN». | +| **⇩ «Скачать PGN» → «Эту партию»** | Скачивание `Anderssen-Dufresne-1852.pgn` (имена латиницей из тегов, иначе `game.pgn`; как Android §7.8). С правками, �охранёнными или нет. | +| **⇩ → «В�ю базу � моими правками»** | Только е�ли в �той базе е�ть правленые, но не �охранённые в «Мои партии» партии, или �то «Мои партии». Скачивает�� новый файл `Alekhin (ChessPenguin).pgn` — оригинал на ди�ке не трогает��. | +| Скачать «Мои партии» | §2.3 | + +Скачанный файл уходит туда, куда браузер кладёт загрузки (Chrome может �про�ить ме�то — �то его на�тройка). Запи�ь **в и�ходный файл** даже в Chrome не делаем — решение владельца «базы только дл� чтени�». + +### 2.5. Что открывает��, что нет + +| Файл | Лёгка� вер�и� | +|---|---| +| `.pgn` (люба� кодировка, FEN, `--`), `.cbv`, `.zip`/`.7z` � PGN или CBV | да; замечани� �овме�тимо�ти — как на компьютере | +| Папка ChessBase `.cbh` + `.cbg/.cba/…` | выбрать **в�е файлы базы �разу** (множе�твенный выбор) или перетащить папку; е�ли выбран один `.cbh`: «Это ча�ть базы ChessBase из не�кольких файлов. Выберите в�е её файлы �разу (Ctrl+A в папке) или откройте архив .cbv.» (**предложение**; разработчик подтверждает, что `open_chessbase_files` укладывает�� в лёгкую) | +| Большие базы | предел по размеру файла и чи�лу партий (�тавит разработчик по замеру пам�ти; ориентир — 200 МБ / 200 000 партий на компьютере, вдвое меньше на iPad). Сверх предела: «Эта база �лишком больша� дл� веб-вер�ии (1,9 ГБ). Откройте её в программе дл� компьютера — там нет такого предела. [Скачать программу ↗]» | + +### 2.6. �е�охранённые правки + +- «� Библиотека», «�азад» браузера, переход к другой партии: тот же вопро�, что на компьютере, но � веб-ответами: «Сохранить изменени� в партии? [Сохранить в Мои партии] [�е �охран�ть] [Отмена]». +- Esc дважды — уйти без �охранени� (как на компьютере). +- Закрытие вкладки / перезагрузка — только вопро� браузера (§1.3). **Черновик** не�охранённой партии пишет�� в хранилище раз в 5 � (одна запи�ь, по�ледн�� парти�); при �ледующем открытии вверху Библиотеки: «Е�ть не�охранённа� парти�: �ндер�ен — Дюфрен, 14 ходов. [Открыть] [Удалить]». Это защита от �лучайно закрытой вкладки, а не авто�охранение в «Мои партии». + +### 2.7. При очи�тке данных �айта + +Пропадает в�ё из таблицы §2.1, кроме файлов на ди�ке: «Мои партии», копии, разборы, движок, на�тройки, �пи�ок открытых файлов и разрешени�. Программа по�ле �того выгл�дит как при первом входе (§1.2) — отличить очи�тку от первого входа нельз�, и не нужно. Предупреждение заранее — в «Данных в браузере» (§2.3) и на карточке «Моих партий» (дата по�леднего �качивани�). + +## 3. Ра�кладки: компьютер, iPad, телефон + +### 3.1. Два незави�имых признака + +1. **Ввод: мышь или палец.** «Крупные кнопки дл� пальца» = �вто → включены, е�ли о�новной указатель грубый: `matchMedia('(pointer: coarse)')`. iPad � клавиатурой и трекпадом о�таёт�� «пальцем» (о�новной указатель у него — палец, **проверить** в Safari); ноутбук � �ен�орным �краном — «мышь». �а�тройка Вкл/Выкл перекрывает �вто. +2. **Компоновка: по размеру окна**, как `narrow-windows.md` §0: р�дом / �топкой — чи�та� функци� `W`, `H`, без ги�терези�а. Дл� «пальца» мен�ют�� только кон�танты. + +| Кон�танта | Мышь (как на компьютере) | Палец | +|---|---|---| +| Вы�ота кнопки, �троки �пи�ка | как �ейча� (≈ 24–28) | **44** (Apple HIG), о�новные ◀ ▶ — 48 × 72 | +| `SIDE_MIN` правой колонки | 240 | **320** | +| `STACK_BOTTOM_MIN` | 300 | **380** (�трока движка 48 + вкладки 44 + 4 �троки нотации по 44 + панель 64 + пол�) | +| Строка нотации | как �ейча� | 40 (ход — в�� �чейка; в тек�те вариантов — ближайший ход в радиу�е 22) | +| До�ка в �топке | `narrow-windows.md` §3.1 | не выше **60 % вы�оты** окна (как Android §13.2) | +| Панель ин�трументов | одна �трока мелких значков | нижн�� панель кнопок 64 (§3.3) | + +### 3.2. Компьютер + +Ровно на�тольна� программа � правилами `narrow-windows.md`: Библиотека (полка, таблица, фильтры р�дом или выдвижные), парти� р�дом или �топкой. Отличи� — только §1–2 и клавиши (§4). Ма�штаб — ма�штабом браузера (Ctrl + / Ctrl −): egui �ам �ледует `devicePixelRatio`; �об�твенный ма�штаб egui по Ctrl+=/− в вебе выключен, чтобы не было двух ма�штабов. + +**Узкое окно в вебе.** Окно браузера бывает уже 640 (минимум на�тольной программы). �иже 640 — �топка � до�кой во в�ю ширину, панели перено��т�� по группам (§4a там же). �иже **360** по ширине или 420 по вы�оте — вме�то �крана �покойна� надпи�ь по центру: «Окно �лишком маленькое. Ра�т�ните его, чтобы работать � партией.» (Парти� и анализ при �том живут, про�то не ри�уют��.) + +### 3.3. iPad: альбом + +Размеры iPad (CSS px): mini 744 × 1133, iPad/Air 820 × 1180, Pro 11" 834 × 1194, Pro 13" 1024 × 1366 (**проверить** по актуальным модел�м). В Safari во вкладке вы�оту �ъедают адре�на� �трока и вкладки (≈ 70–110), в у�тановленном приложении — только �трока �о�то�ни� (24). + +``` +iPad 1180 × 800 (у�тановленное приложение), палец +┌───────────────────────────────────────────────────────────────────────────────────────────� +│ ‹ Библиотека �ндер�ен — Дюфрен 1-0 · Берлин 1852 ⇩ ☰ ⚙ │ 52 +├─┬────────────────────────────────────────────────────┬────────────────────────────────────┤ +│▌│ │ � Дюфрен, Жан 0 │ 40 +│▌│ ├────────────────────────────────────┤ +│▌│ │ [�нализ �] +1.9 гл.24 19.Rad1 … ▾ │ 48 +│▌│ ├────────────────────────────────────┤ +│▌│ ДОСК� │ ?? Зевок · лучше было 19…Qxf3 Отчёт│ 44 +│▌│ ≈ 700 × 700 │ �▂▃▅▆▇▇▆▅▃▂� график │ 40 +│▌│ ├────────────────────────────────────┤ +│▌│ │ 17 Bxh7+ Kxh7 │ 40 +│▌│ │ 18 ▓Qh5+▓ Kg8 │ +│▌│ │ … │ +│▌│ ├────────────────────────────────────┤ +│▌│ │ ○ �ндер�ен, �дольф 1 │ 40 +│ │ ├────────────────────────────────────┤ +│ │ │ ↩ 🔃 � ◀ ▶ � │ 64 +└─┴────────────────────────────────────────────────────┴────────────────────────────────────┘ +``` + +- **Это компоновка «р�дом»** � кон�тантами «пальца»: до�ка = меньшее из вы�оты и `W − 320 − 26 − 24`; права� колонка ≥ 320. +- **Плашки игроков** (как Android §7.11, §13.1) — первой и по�ледней �трокой правой колонки, а не над и под до�кой: до�ка не тер�ет 80 точек вы�оты. В режиме «мышь» плашек нет — имена в шапке, как на компьютере. +- **Вкладки �отаци� | Отчёт** — �егментом 44 над нотацией, когда е�ть разбор; без разбора — про�то нотаци�. +- **�ижн�� панель** (64): ↩ отменить (неактивна, е�ли нечего), 🔃 перевернуть, � ◀ ▶ �; ◀ ▶ — по 72, удержание повтор�ет (400 м�, затем каждые 120 м� — Android §7.4). Панель — у правого нижнего кра�, под большим пальцем правой руки. ↪ повтор — в меню ☰ (на ка�ании редок). +- **☰ (меню партии)**: �нализ партии / Отчёт, Сохранить в Мои партии, Данные партии (F2), Копировать PGN, Копировать FEN, В�тавить вариант, Скачать PGN, Повторить (↪), Замечани� �овме�тимо�ти. +- **Строка «Дальше»** на развилке (Android §7.5) — над нижней панелью, чипы 44: на ка�ании Shift+↑/↓ нет, а ходы в тек�те вариантов мелкие. + +### 3.4. iPad: портрет и разделённый �кран + +``` +iPad 820 × 1180, палец +┌────────────────────────────────────────────────────� +│ ‹ Библиотека �ндер�ен — Дюфрен 1-0 ⇩ ☰ ⚙ │ 52 +├────────────────────────────────────────────────────┤ +│ � Дюфрен, Жан 0 │ 40 +│ ▌┌──────────────────────────────────────� │ +│ ▌│ │ │ +│ ▌│ ДОСК� ≈ 700 │ │ ≤ 60 % вы�оты +│ ▌│ │ │ +│ ▌└──────────────────────────────────────┘ │ +│ ○ �ндер�ен, �дольф 1 │ 40 +├�������������������� разделитель �������������������┤ +│ [�нализ �] +1.9 гл.24 19.Rad1 Qxf3 … ▾ │ 48 +│ ?? Зевок · лучше было 19…Qxf3 Отчёт │ 44 (+ график 40) +│ 17 Bxh7+ Kxh7 │ +│ 18 ▓Qh5+▓ Kg8 │ нотаци� +├────────────────────────────────────────────────────┤ +│ Дальше: [19.Rad1] (19.Qxf7+) │ 44 на развилке +│ ↩ 🔃 � ◀ ▶ � │ 64 +└────────────────────────────────────────────────────┘ +``` + +- **Стопка** � кон�тантами «пальца»: плашки над и под до�кой шириной � до�ку (Android §13.2), до�ка ≤ 60 % вы�оты, разделитель т�нет��. Бюджет 1180: 24 + 52 + 40 + 700 + 40 + 48 + 64 = 968, нотации ≈ 210 (5 �трок); � панелью разбора ≈ 125. +- **Поворот** iPad переключает альбом ↔ портрет без потери �о�то�ни� (`narrow-windows.md` §3.3: �о�то�ние в `GameView`). +- **Split View / Slide Over** (окно 320–700 шириной): та же �топка; плашки, ⇩ и ⚙ уход�т в ☰ при ширине < 500; ниже 360 — надпи�ь «Окно �лишком маленькое» (§3.2). Это не телефонна� ра�кладка — мы только не ломаем��. +- **Библиотека на iPad**: полка компактной �трокой (`narrow-windows.md` §2.5), �троки таблицы 44, фильтры — выдвижна� панель; двойного щелчка у пальца нет — парти� открывает�� **одним ка�анием** �троки (выделение и открытие �разу). Сортировка — ка�анием заголовка. + +### 3.5. Же�ты (палец) + +| Где | Же�т | Дей�твие | +|---|---|---| +| до�ка | ка�ание фигуры, затем пол�; перета�кивание | ход (Android `android-play.md` §29.2–29.3: точки ходов, фигура под пальцем подн�та на полклетки; превращение — как на компьютере, **проверить** окно выбора под палец) | +| до�ка | — | **ли�тани� ходов �вайпом нет**: �вайп по до�ке �порит � перета�киванием фигуры, а у левого кра� в Safari — � же�том «назад» (Android §7.2, то же правило) | +| ◀ ▶ | ка�ание; удержание | шаг; повтор | +| график оценки | ка�ание, прот�жка | перейти к ходу — �то и е�ть «ли�тание пальцем»: прот�жка по графику пробегает партию | +| нотаци� | ка�ание хода; прокрутка | перейти; читать | +| нотаци� | **долгое нажатие** на ход | контек�тное меню хода (то, что на компьютере правой кнопкой): комментарий, знаки ! ? !! ?? !? ?!, �делать о�новным, удалить ход и продолжение | +| лини� движка | ка�ание | предпро�мотр (◀ ▶ ли�тают линию, ✕ выходит; «+ Вариантом» — в�тавка � отменой) | +| левый край �крана (Safari) | �вайп вправо | «�азад» браузера = � Библиотека (§1.1) | +| везде | щипок | ничего: ма�штаб �траницы на хол�те выключен (`touch-action: none`); на компьютере ма�штаб — браузером | + +- **Стрелки и цветные пол� пальцем не ри�уют��** (как на Android — решение владельца по `android-play.md` §29.1); � трекпадом или мышью на iPad права� кнопка работает как на компьютере. +- **Комментарий** — поле ввода � �кранной клавиатурой iPad. egui в браузере принимает тек�т через �крытое поле ввода; **проверить** на iPad набор по-ру��ки, автозамену и диктовку до реализации — �то главный ри�к ка�ани� (открытый вопро� 7). + +### 3.6. Телефон: �траница-заглушка вме�то приложени� + +**Решение владельца:** веб-приложение под телефон не делаем. Телефон, открывший `/app/` (по ��ылке � �айта, из �ообщени�, по закладке), видит не программу, а �траницу «ChessPenguin на телефоне». Программа (5–7 МБ) при �том **не �качивает��**. + +#### 3.6.1. Как отличить телефон от планшета и компьютера + +Решение — в маленьком �крипте в �амой �транице `/app/` **до** загрузки wasm. �а �ервере по `User-Agent` �того не решить: iPad и iPhone в режиме «Полна� вер�и� �айта» выдают �еб� за Mac, размер �крана �ервер не видит. + +```js +// Обща� функци� дл� �айта и /app/ — один файл static/js/device.js (�ейча� detect() живёт в site.js). +function deviceClass() { + var ua = navigator.userAgent || ""; + var plat = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || ""; + var touch = navigator.maxTouchPoints > 0; + var short = Math.min(screen.width, screen.height); // CSS px, ве�ь �кран, не окно + var coarse = matchMedia("(pointer: coarse)").matches; + var finePresent = matchMedia("(any-pointer: fine)").matches; + + var ios = /iPhone|iPod|iPad/.test(ua) || (/Mac/.test(plat) && navigator.maxTouchPoints > 1); + if (ios) return short < 600 ? "iphone" : "ipad"; + if (/Android/i.test(ua)) return short < 600 ? "android-phone" : "android-tablet"; + if (navigator.userAgentData && navigator.userAgentData.mobile) return short < 600 ? "phone" : "tablet"; + if (/CrOS/.test(ua)) return "computer"; + if (touch && coarse && !finePresent && short < 600) return "phone"; // «вер�и� дл� ПК» на телефоне и прочее + return "computer"; +} +``` + +Почему так: + +- **iPadOS выдаёт �еб� за Mac** (UA `Macintosh`), а на�то�щий Mac не имеет `maxTouchPoints > 1` — признак `Mac + ка�ание` (**факт**: так уже работает `site.js`, `touchMac`). �о iPhone � включённой «Запро�ить на�тольный веб-�айт» тоже выгл�дит `Mac + ка�ание` — по�тому iPhone и iPad дальше различают�� **размером �крана**. +- **Порог 600 по короткой �тороне �крана.** Самый широкий iPhone — 440 (16 Pro Max), �амый маленький iPad — 744 (mini); телефоны Android — 360–480; Galaxy Fold в �ложенном виде — телефон, в разложенном (≈ 670+) — планшет, и �то верно: на развёрнутом �кране программа помещает��. 600 — граница «компактного» кла��а окна у Google (Material 3), её же и�пользует Android-дизайн (`android-ui.md` §13). (Размеры моделей — **проверить** по актуальным �пецификаци�м.) +- **`screen`, а не размер окна:** iPad в Split View/Slide Over (окно 320) — в�ё равно iPad, а узкое окно браузера на компьютере — в�ё равно компьютер. `min()` убирает зави�имо�ть от поворота (Android отдаёт `screen` в текущей ориентации, iOS — в портретной). +- **Android-планшет** (UA без `Mobile` или Chrome в режиме «вер�и� дл� ПК», который на больших планшетах включён по умолчанию — **проверить**) получает веб-программу: она дл� такого �крана �делана; в «О программе» и на первом �кране — �трока «Е�ть приложение дл� Android ↗». +- **Ошибки неизбежны** (необычные у�трой�тва, увеличенный ма�штаб �крана Android, будущие �кладные) — по�тому е�ть «В�ё равно открыть» (§3.6.4), а не тупик. +- Без JavaScript — `