commit 8188b584aa677df3f58a7a08361bf937e2a41f28 Author: vrubel Date: Sun Oct 18 01:54:06 2026 +0300 ChessPenguin 0.1.0 Native chess database for Linux: PGN library, notation with variations and comments, UCI engine analysis, move entry and export. Co-Authored-By: Claude Opus 5.5 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ad495fa --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +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 --locked -p chesspenguin diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..d2896e4 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,127 @@ +# 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 + - 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 and rpm + 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/ + - 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/* + + publish: + needs: [version, linux, flatpak, windows] + if: github.ref_type == 'tag' + runs-on: ubuntu-24.04 + steps: + - uses: actions/download-artifact@v8 + with: + path: dist + merge-multiple: true + - name: Checksums + run: cd dist && sha256sum * > SHA256SUMS.txt + - uses: softprops/action-gh-release@v3 + with: + files: dist/* + generate_release_notes: true + # v1.0.0-beta.1 and similar tags become pre-releases. + prerelease: ${{ contains(github.ref_name, '-') }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1726b34 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/target +/engines/* +!/engines/README.md +/pgnFilesforExample/ + +# Third-party reference screenshots (kept locally, not published) +/designExample/ diff --git a/.opencode/agents/analyst.md b/.opencode/agents/analyst.md new file mode 100644 index 0000000..28849ef --- /dev/null +++ b/.opencode/agents/analyst.md @@ -0,0 +1,13 @@ +--- +description: Анализирует требования и реальные PGN, сохраняет актуальную аналитику и критерии приёмки +mode: subagent +color: "#33A68C" +--- + +Ты продуктовый и системный аналитик шахматного desktop-приложения. Читай AGENTS.md, техническое задание.txt и связанные исследования. Пиши по-русски. Сохраняй аналитику в назначенные файлы docs/; не изменяй код приложения и исходные материалы без прямого задания. + +Связывай требования со сценариями пользователя и проверяемыми критериями приёмки. Отмечай источник каждого требования: ТЗ, подтверждение пользователя, предложение команды. Разделяй первую версию и последующие этапы. Вопросы задавай только там, где ответ меняет решение. + +Исследуй реальные данные: кодировки, заголовки, неизвестные теги, начальные FEN, RAV, NAG, комментарии до и после ходов, расширения аннотаций, усечённые партии и неоднозначности PGN. Статистику снабжай методом подсчёта; подсчёт регулярными выражениями не называй полноценной проверкой легальности. + +Продумывай импорт, повторное открытие, изменение внешнего файла, отмену долгих операций, поиск, создание партии, экспорт и восстановление несохранённой работы. Поддерживай журнал решений и открытых вопросов в рамках назначенной области. В итогах сообщай факты, риски, изменённые файлы и рекомендации. diff --git a/.opencode/agents/designer.md b/.opencode/agents/designer.md new file mode 100644 index 0000000..ab6f417 --- /dev/null +++ b/.opencode/agents/designer.md @@ -0,0 +1,19 @@ +--- +description: Проектирует качественный Linux desktop UI для библиотеки PGN, доски, вариантов и анализа +mode: subagent +color: "#BD7AD8" +--- + +Ты senior product designer шахматного аналитического приложения. Прочитай AGENTS.md, ТЗ и релевантные изображения designExample через инструмент просмотра изображений. Изучай референсы визуально, а не только по именам файлов. Пиши и сохраняй результаты по-русски в назначенные файлы. + +Рабочая методика: +1. Определи основную задачу экрана и приоритет информации. +2. Опиши пользовательский путь, переходы и сохранение контекста между библиотекой и партией. +3. Сделай wireframe и объясни размещение доски, нотации, вариантов, комментариев и анализа. +4. Опиши конкретные компоненты, размеры, плотность, типографику, цвета и состояния. Избегай декоративного dashboard-дизайна, огромных карточек и градиентов без функции. +5. Проверь пустые, загрузочные, ошибочные, переполненные состояния и несохранённые изменения; протестируй компоновку мысленно на небольшом окне и HiDPI. +6. Задай клавиатурную навигацию, фокус, tooltip, видимую выбранную позицию и читаемость без опоры только на цвет. + +Доска и чтение аннотированной партии — центр продукта. Основная линия, побочные ветки, комментарии и NAG должны оставаться понятными при глубоком вложении. Предпросмотр PV движка должен визуально отличаться от партии и иметь очевидный возврат. Активная позиция, выбранная строка и раскрытая ветка — разные состояния. + +Учитывай нативные ограничения выбранного Rust UI: перенос rich text, hit testing ходов, виртуализация таблиц, clipboard, диалоги, звук, SVG, IME. Предлагай проверяемый UI-прототип для сомнительных возможностей. Код приложения меняй только по прямому назначению оркестратора. Не скачивай случайные skills и не копируй фирменные ресурсы без проверки происхождения. diff --git a/.opencode/agents/developer.md b/.opencode/agents/developer.md new file mode 100644 index 0000000..de12148 --- /dev/null +++ b/.opencode/agents/developer.md @@ -0,0 +1,15 @@ +--- +description: Проектирует и реализует Rust desktop приложение, PGN-дерево, индексы и управление UCI движками +mode: subagent +color: "#E5AC57" +--- + +Ты senior Rust desktop разработчик. Читай AGENTS.md, ТЗ, согласованные решения docs/architecture.md и связанные требования. Не выбирай другой UI-фреймворк без объяснения и согласования. Работай только в назначенной области. + +Держи шахматную модель и PGN независимо от UI. Используй проверенную библиотеку правил; самостоятельно проектируй дерево документа, привязку комментариев и сериализацию. Различай идентификатор узла, позицию, историю ходов, активную ветку и временный preview анализа. Проектируй семантический roundtrip PGN с сохранением исходного текста для неизменённых игр. + +UCI реализуй как явную машину состояний, с отдельным процессом, асинхронным чтением stdout/stderr, контролем stop/bestmove, таймаутами, MultiPV, типизированными опциями и привязкой результатов к поиску. Сначала завершай старый поиск, затем начинай новый: внутренний request ID не добавляет идентификатор в сам протокол UCI. Не вызывай движок через shell-строку. Завершай процессы при закрытии документа и приложения. + +Отделяй индекс библиотеки от исходного PGN; учитывай изменение файла, отмену импорта, пагинацию и атомарную запись. Не читай большую базу целиком в UI-потоке. Обрабатывай Result на границах; не применяй unwrap к пользовательским данным. Избегай абстракций ради гипотетических функций. + +Проверяй доступные API по документации и исходникам, фиксируй версии и лицензии зависимостей. Для изменений запускай подходящие cargo fmt/check/clippy/test или объясняй блокер. Добавляй значимые тесты на ошибки данных и конкурентность. Отчитывайся о точных командах и фактических результатах; не объявляй UI проверенным без запуска. diff --git a/.opencode/agents/orchestrator.md b/.opencode/agents/orchestrator.md new file mode 100644 index 0000000..1269bd5 --- /dev/null +++ b/.opencode/agents/orchestrator.md @@ -0,0 +1,13 @@ +--- +description: Ведёт разработку шахматного приложения, координирует аналитика, дизайнера, разработчика и тестировщика +mode: primary +color: "#5B8DEF" +--- + +Ты оркестратор Linux-приложения для шахматных баз и анализа. Общайся по-русски. Сначала прочитай AGENTS.md, исходное ТЗ и актуальную сводку docs/architecture.md, если она существует. + +Выясняй цель текущего этапа: исследование, согласование, реализация или проверка. Предлагай конкретное решение с аргументами, учитывая желание пользователя использовать стек Artcraft. Не выдавай собственную рекомендацию за решение пользователя. + +Делегируй независимые задачи агентам analyst, designer, developer и tester. Если инструменты текущей сессии ещё не показывают эти профили, используй general с полным контекстом роли и сообщи об этом. Назначай отдельные файлы и ожидаемый результат, не запускай дублирующее исследование. Сам интегрируй результаты, устраняй противоречия, поддерживай docs/architecture.md. Сохраняй существенные решения, открытые вопросы и следующий проверяемый шаг. + +Для реализации выбирай небольшой сквозной сценарий с работающим UI и реальными PGN. Перед расширением функций получай независимую проверку тестировщика. В конце различай выполненное, проверенное, рекомендованное и требующее ответа пользователя. Не перезапускай активный OpenCode самостоятельно. diff --git a/.opencode/agents/tester.md b/.opencode/agents/tester.md new file mode 100644 index 0000000..691d6b3 --- /dev/null +++ b/.opencode/agents/tester.md @@ -0,0 +1,15 @@ +--- +description: Независимо проверяет PGN, шахматную модель, UCI, Linux UI и регрессии сохранности данных +mode: subagent +color: "#E87575" +--- + +Ты инженер качества шахматного desktop-приложения. Читай AGENTS.md, требования и изменённые файлы. Пиши по-русски. Приоритет — реальные дефекты и воспроизводимость, а не число тестов. + +Проверяй на реальных примерах и малых синтетических fixtures: RAV с несколькими уровнями, FEN и ход чёрных, комментарии у корня/ходов/ветвей, NAG, нестандартные теги, кодировки, усечённые данные, рокировки, en passant, превращения, мат, пат, повторение. Roundtrip сравнивай семантически; отдельно проверяй сохранение неизменённых исходных данных. + +Для UCI используй детерминированный fake engine, который воспроизводит задержки, старый info, отсутствие readyok, некорректные строки, MultiPV, мат и завершение процесса. Реальный Stockfish — дополнительная интеграция, а не замена управляемым сценариям гонок. + +Проверяй переход библиотека—партия—библиотека, клавиатуру и фокус, preview PV без изменения документа, отмену операций, экспорт, восстановление и Linux Wayland/X11/HiDPI в доступном окружении. Для производительности фиксируй оборудование, размер входа, методику и измерение; цели не называй результатами. + +Не запускай неподтверждённые бинарники и не изменяй пользовательские PGN. Не исправляй production-код в ревью без задания. На дефект указывай серьёзность, шаги, ожидаемое/фактическое поведение, файл/строку и минимальный пример. Явно перечисляй непроверенное. Внешние тестовые библиотеки не публикуй без выяснения условий их распространения. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ce28f80 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,37 @@ +# Chess database for Linux + +## Контекст + +- Исходное ТЗ: `техническое задание.txt`. +- Пользовательские материалы: `designExample/`, `pgnFilesforExample/`, `engines/`. +- Рабочий язык обсуждений и проектных заметок — русский; идентификаторы кода — английский. +- Текущий этап: исследование и согласование архитектуры. Рекомендация не равна утверждённому решению. +- Сводка решений: `docs/architecture.md`; исследования: `docs/research/`. +- Подтверждённые пользователем границы первой версии: `docs/decisions.md`; они имеют приоритет над ранними предложениями исследований. + +## Команда + +Оркестратор распределяет независимые задачи между `analyst`, `designer`, `developer`, `tester`, согласует результаты и обсуждает продуктовые решения с пользователем. Делегирование разрешено. Дочерние агенты не создают дополнительные уровни команды без необходимости. + +- Аналитик поддерживает требования, реальные особенности PGN и критерии приёмки. +- Дизайнер отвечает за сценарии, компоновку, состояния, клавиатуру и визуальную систему. +- Разработчик отвечает за Rust, архитектуру, хранение, PGN и UCI. +- Тестировщик независимо проверяет поведение и сообщает конкретные воспроизводимые дефекты. + +Каждой параллельной задаче назначать собственные файлы. Не перезаписывать работу другого агента. В отчёте указывать изменения, проверки и нерешённые вопросы. + +## Инварианты продукта + +- Локальное приложение для просмотра, ввода и анализа шахматных партий, с PGN как форматом обмена. +- Варианты — дерево ходов, а не плоская последовательность. Поддерживать исходную позицию FEN, комментарии и NAG. +- Реальные учебные PGN содержат legacy-кодировки, FEN с fullmove=0 и `--`. Сохранять оригинал и диагностировать совместимость; учебный null move не считать обычным легальным ходом. +- Исходные пользовательские PGN сохранять; запись и замена файла должны быть явным действием. +- Просмотр линии движка не изменяет партию. Вставка варианта — отдельное действие с возможностью отмены. +- Не показывать анализ старой позиции как анализ новой. UCI — управляемый дочерний процесс с таймаутами, остановкой и завершением. +- Тяжёлый разбор, индексирование и взаимодействие с движком не блокируют UI. +- Сохранять историю позиции для корректного анализа повторений; одного FEN недостаточно для всех сценариев. +- Сторонний код и ресурсы брать из проверенных источников, фиксируя конкретные лицензии и авторство. + +## Работа + +Не изменять исходное ТЗ и референсы. Не запускать незавершённые загрузки движков. Не устанавливать инструменты и не начинать большой каркас приложения до выбора стека. Проверенные факты отделять от предложений; для внешних технических утверждений сохранять ссылки. Тестировать значимое поведение, особенно сохранность PGN и гонки UCI; не объявлять запланированные проверки выполненными. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7ba94f9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). + +## [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..f19beb3 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,4984 @@ +# 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 = "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 = "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 = "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 = "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 = "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 = "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 = "0.1.0" +dependencies = [ + "encoding_rs", + "pgn-reader", + "shakmaty", + "thiserror 2.0.21", +] + +[[package]] +name = "chesspenguin" +version = "0.1.0" +dependencies = [ + "arboard", + "chess-core", + "directories", + "eframe", + "egui", + "egui_extras", + "image", + "rfd", + "rodio", + "serde", + "serde_json", + "shakmaty", + "uci", + "winresource", +] + +[[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 = "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 = "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 = "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 = "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", + "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 = "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 = "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 = "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.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[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 = "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 = "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 = [ + "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 = "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 = "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", +] + +[[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 = "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 = "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 = "mach2" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1b95cd5421ec55b445b5ae102f5ea0e768de1f82bd3001e11f426c269c3aea" +dependencies = [ + "libc", +] + +[[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 = "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 = "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 = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[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-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 = "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 = "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 = "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 = "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 = "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 = "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 = "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" + +[[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 = "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 = "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 = "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 = "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 = "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 = "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 = "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 = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "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 = "uci" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + +[[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 = "usvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64", + "data-url", + "flate2", + "imagesize", + "kurbo 0.11.3", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "xmlwriter", +] + +[[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 = "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 = "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 = "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 = "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 = "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 = "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 = "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 = "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 = "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..b602062 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,33 @@ +[workspace] +resolver = "3" +members = ["crates/chess-core", "crates/uci", "apps/desktop"] + +[workspace.package] +version = "0.1.0" +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" +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"] } +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" } +uci = { path = "crates/uci" } + +[profile.dev.package."*"] +opt-level = 2 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 new file mode 100644 index 0000000..5f042f5 --- /dev/null +++ b/README.md @@ -0,0 +1,87 @@ +

+ ChessPenguin icon +

+ +

ChessPenguin

+ +

+ A native chess database for Linux: open PGN collections, read annotated games, + enter your own and analyse them with Stockfish or any UCI engine. +

+ +

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

+ +![Analysis](docs/screenshots/analysis.png) + +## Features + +- **PGN library** — keep several databases at hand, search and sort games, reopen where you left off. +- **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. +- **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. +- **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. +- **Looks** — 14 piece sets and 26 boards (flat colours and textures from Lichess), + sounds, dark and light themes. +- **Languages** — English, Русский, Français, Deutsch, Español, Italiano. + +| Library | Variations and engine settings | Boards and pieces | +| --- | --- | --- | +| ![Library](docs/screenshots/library.png) | ![Variations](docs/screenshots/variations.png) | ![Settings](docs/screenshots/settings.png) | + +## 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` | +| 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` | + +The engine is not bundled. Install Stockfish from your distribution +(`sudo apt install stockfish`) or download it from [stockfishchess.org](https://stockfishchess.org/download/), +then add it in **Settings → Engines**. + +### Build from source + +Rust 1.97 or newer. On Debian/Ubuntu: `sudo apt install pkg-config libasound2-dev libxkbcommon-dev libwayland-dev`. + +```sh +cargo run --release -p chesspenguin -- examples/classics.pgn +./scripts/install.sh # install for the current user (~/.local), --uninstall to remove +``` + +## Keyboard + +| Where | Keys | +| --- | --- | +| Library | ↑/↓ select · Enter open · Ctrl+O add PGN · Ctrl+N new game · Ctrl+F search | +| Game | ←/→ move · ↑/↓ switch variation · Home/End · F flip · L engine · Esc leave preview | +| Editing | Ctrl+Z / Ctrl+Y undo/redo · Ctrl+Shift+C copy PGN · Ctrl+S save as · Ctrl+W back to library | + +## Project layout + +- `crates/chess-core` — game tree, tolerant PGN import/export. +- `crates/uci` — UCI engine process supervisor. +- `apps/desktop` — the egui application. +- `packaging/` — desktop entry, AppStream metadata, icons, deb/rpm, AppImage and Flatpak recipes. + +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..cac95fd --- /dev/null +++ b/README.ru.md @@ -0,0 +1,39 @@ +# ChessPenguin + +Нативная шахматная база для Linux: открывайте PGN-сборники, читайте аннотированные партии, +вводите свои и анализируйте их со Stockfish или любым UCI-движком. + +[English](README.md) · [Скачать](https://github.com/vrubelroman/chessPenguin/releases/latest) + +![Анализ](docs/screenshots/analysis.png) + +## Возможности + +- **Библиотека PGN** — несколько баз под рукой, поиск и сортировка партий, возврат к той же строке. +- **Реальные PGN** — вложенные варианты, комментарии, NAG, партии из позиции FEN, старые кодировки + (windows-1251, windows-1252, KOI8-R, CP866) и учебные нулевые ходы `--`. Исходные файлы не изменяются. +- **Нотация** — основная линия таблицей в две колонки, комментарии и варианты блоками, + навигация мышью и клавиатурой. +- **Анализ движком** — любой UCI-движок, до 5 линий, стрелки лучших ходов, шкала оценки; + время, потоки и память настраиваются прямо в панели анализа. +- **Линии движка на доске** — просмотр линии без изменения партии и вставка её вариантом (с отменой). +- **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор, + копирование PGN/FEN, сохранение партии в новый файл. +- **Оформление** — 14 наборов фигур и 26 досок (цвета и текстуры Lichess), звуки, тёмная и светлая тема. +- **Языки** — English, Русский, Français, Deutsch, Español, Italiano. + +## Установка + +Пакеты каждого релиза — на странице [Releases](https://github.com/vrubelroman/chessPenguin/releases): +`.deb`, `.rpm`, AppImage, Flatpak и архив для Windows. Команды установки — в [README.md](README.md#install). + +Движок в комплект не входит: установите Stockfish (`sudo apt install stockfish` или +[stockfishchess.org](https://stockfishchess.org/download/)) и добавьте его в **Настройки → Движки**. + +Сборка из исходников: Rust 1.97+, затем `cargo run --release -p chesspenguin` +или `./scripts/install.sh` для установки в `~/.local`. + +## Лицензия + +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..c65bab9 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,39 @@ +# 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+ | + +Notes: +- 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. + +## 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). diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml new file mode 100644 index 0000000..3573ddd --- /dev/null +++ b/apps/desktop/Cargo.toml @@ -0,0 +1,28 @@ +[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 + +[dependencies] +chess-core.workspace = true +shakmaty.workspace = true +uci.workspace = true +egui.workspace = true +eframe.workspace = true +egui_extras.workspace = true +image.workspace = true +rfd.workspace = true +arboard.workspace = true +rodio.workspace = true +directories.workspace = true +serde.workspace = true +serde_json.workspace = true + +[build-dependencies] +winresource = "0.1" 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/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/icon-256.png b/apps/desktop/assets/icon-256.png new file mode 100644 index 0000000..f57a3c8 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/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/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/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/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/Checkmate.ogg b/apps/desktop/assets/sounds/piano/Checkmate.ogg new file mode 100644 index 0000000..80b2f6e --- /dev/null +++ b/apps/desktop/assets/sounds/piano/Checkmate.ogg @@ -0,0 +1 @@ +Check.ogg \ No newline at end of file diff --git a/apps/desktop/assets/sounds/piano/Error.ogg b/apps/desktop/assets/sounds/piano/Error.ogg new file mode 100644 index 0000000..ea77209 --- /dev/null +++ b/apps/desktop/assets/sounds/piano/Error.ogg @@ -0,0 +1 @@ +../standard/Error.ogg \ No newline at end of file diff --git a/apps/desktop/assets/sounds/piano/GenericNotify.ogg b/apps/desktop/assets/sounds/piano/GenericNotify.ogg new file mode 100644 index 0000000..4b66fd6 Binary files /dev/null and b/apps/desktop/assets/sounds/piano/GenericNotify.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/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/Checkmate.ogg b/apps/desktop/assets/sounds/sfx/Checkmate.ogg new file mode 100644 index 0000000..80b2f6e --- /dev/null +++ b/apps/desktop/assets/sounds/sfx/Checkmate.ogg @@ -0,0 +1 @@ +Check.ogg \ No newline at end of file diff --git a/apps/desktop/assets/sounds/sfx/Error.ogg b/apps/desktop/assets/sounds/sfx/Error.ogg new file mode 100644 index 0000000..ea77209 --- /dev/null +++ b/apps/desktop/assets/sounds/sfx/Error.ogg @@ -0,0 +1 @@ +../standard/Error.ogg \ No newline at end of file diff --git a/apps/desktop/assets/sounds/sfx/GenericNotify.ogg b/apps/desktop/assets/sounds/sfx/GenericNotify.ogg new file mode 100644 index 0000000..e789f67 Binary files /dev/null and b/apps/desktop/assets/sounds/sfx/GenericNotify.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/build.rs b/apps/desktop/build.rs new file mode 100644 index 0000000..5219d5b --- /dev/null +++ b/apps/desktop/build.rs @@ -0,0 +1,10 @@ +// Embeds the application icon into the Windows executable. +fn main() { + 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/analysis.rs b/apps/desktop/src/analysis.rs new file mode 100644 index 0000000..0f7fcf9 --- /dev/null +++ b/apps/desktop/src/analysis.rs @@ -0,0 +1,363 @@ +//! Engine analysis controller: owns the UCI process, binds results to the analysed position. + +use crate::i18n::{tr, trf}; +use std::sync::mpsc::{Receiver, channel}; + +use shakmaty::san::SanPlus; +use shakmaty::uci::UciMove; +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, +} + +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 { + 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 a background thread (handshake blocks for up to ~20 s). + pub fn start(&mut self, cfg: &EngineConfig, ctx: &egui::Context) { + self.stop(); + let (tx, rx) = channel(); + let ctx_w = ctx.clone(); + let ctx_done = ctx.clone(); + let cfg = cfg.clone(); + self.engine_name = cfg.name.clone(); + self.multipv = cfg.multipv.max(1); + self.limit = cfg.search_secs; + self.engine_path = Some(cfg.path.clone()); + let spawned = std::thread::Builder::new() + .name("engine-spawn".into()) + .spawn(move || { + let res = uci::Engine::spawn_with( + uci::EngineConfig::new(&cfg.path), + Box::new(move || ctx_w.request_repaint()), + ) + .inspect(|h| { + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = h.set_threads(cfg.threads); + let _ = h.set_hash_mb(cfg.hash_mb); + let _ = h.set_multipv(cfg.multipv.max(1)); + }); + let _ = tx.send(res); + ctx_done.request_repaint(); + }); + match spawned { + Ok(_) => { + self.spawning = Some(rx); + self.status = Status::Starting; + } + Err(e) => self.status = Status::Failed(e.to_string()), + } + } + + /// Stops analysis and terminates the engine process. + pub fn stop(&mut self) { + if let Some(e) = self.engine.take() { + // quit() may wait up to the quit timeout; do it off the UI thread. + let _ = std::thread::Builder::new() + .name("engine-quit".into()) + .spawn(move || { + 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.as_deref() != Some(cfg.path.as_path()) || 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(rx) = &self.spawning + && let Ok(res) = rx.try_recv() + { + 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(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(), + }, + }); + 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 + } + } +} + +impl Drop for Analysis { + fn drop(&mut self) { + self.stop(); + } +} + +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..127570d --- /dev/null +++ b/apps/desktop/src/app.rs @@ -0,0 +1,646 @@ +//! 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::settings::{EngineConfig, Settings, write_atomic}; +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 { + DatabasesPicked(Vec), + SavePicked(PathBuf), + SaveCancelled, + EngineChecked(Result<(PathBuf, String), String>), +} + +#[derive(Clone, Copy, PartialEq)] +enum CloseIntent { + BackToLibrary, + QuitApp, +} + +pub struct App { + settings: Settings, + settings_dirty: bool, + sound: SoundPlayer, + library: Library, + game: Option, + analysis: Analysis, + settings_ui: SettingsWindow, + toast: Option<(String, f64)>, + tx: Sender, + rx: Receiver, + confirm_close: Option, + /// Close the game once the pending "save as" succeeds. + close_after_save: Option, + allow_quit: bool, + applied_dark: Option, + debug: DebugStartup, +} + +/// 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. +#[derive(Default)] +struct DebugStartup { + open: 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, +} + +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"), + 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, + } + } +} + +impl App { + pub fn new(ctx: &egui::Context) -> Self { + let mut settings = Settings::load(); + crate::i18n::set_lang(settings.language); + // 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(); + } + let (tx, rx) = channel(); + let mut library = Library::new(); + if let Some(first) = settings.databases.first().filter(|p| p.exists()) { + library.select_db(first, ctx); + } + Self { + settings, + settings_dirty: false, + sound: SoundPlayer::new(), + library, + game: None, + analysis: Analysis::new(), + settings_ui: SettingsWindow::new(), + toast: None, + tx, + rx, + confirm_close: None, + close_after_save: None, + allow_quit: false, + applied_dark: None, + debug: DebugStartup::from_env(), + } + .with_debug_settings() + } + + 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; + if tab == "board" { + self.settings_ui.tab = Tab::Board; + } + } + self + } + + fn debug_screenshot(&mut self, ctx: &egui::Context) { + if self.debug.open_settings && ctx.input(|i| i.time) > 1.5 { + self.debug.open_settings = false; + self.settings_ui.open = true; + } + let Some(path) = self.debug.screenshot.clone() else { + return; + }; + let now = ctx.input(|i| i.time); + if !self.debug.screenshot_requested { + 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) { + 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); + if let Some(g) = &mut self.game { + g.debug_advance(self.debug.ply); + if std::env::var("CP_ENGINE_PANEL").is_ok() { + g.debug_open_engine_settings(); + } + } + if self.debug.analyze { + self.toggle_engine(ctx); + } + } + + fn toast(&mut self, ctx: &egui::Context, msg: impl Into) { + self.toast = Some((msg.into(), ctx.input(|i| i.time) + 3.5)); + } + + fn play(&self, s: Sound) { + if self.settings.sound_enabled { + self.sound + .play(self.settings.sound_set, s, self.settings.volume); + } + } + + 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) { + self.spawn_dialog(ctx, || { + rfd::FileDialog::new() + .set_title(tr("Open PGN")) + .add_filter("PGN", &["pgn", "PGN"]) + .add_filter(tr("All files"), &["*"]) + .pick_files() + .map(Async::DatabasesPicked) + }); + } + + 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))) + }); + } + + 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) { + while let Ok(msg) = self.rx.try_recv() { + match msg { + Async::DatabasesPicked(paths) => { + for p in paths.iter().rev() { + self.settings.touch_database(p); + } + if let Some(first) = paths.first() { + self.library.select_db(first, ctx); + } + self.settings_dirty = true; + } + Async::SavePicked(path) => self.save_game(ctx, path), + Async::SaveCancelled => self.close_after_save = 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(); + match write_atomic(&path, pgn.as_bytes()) { + Ok(()) => { + g.game.mark_saved(); + self.toast(ctx, trf("Saved: {path}", &[("path", &path.display())])); + 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) { + 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, + }), + parsed.diagnostics, + )); + 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) { + 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(); + if let Some(g) = self.game.take() + && let Some(src) = g.source + { + self.library.reveal(&src.path, src.index); + } + if intent == CloseIntent::QuitApp { + self.allow_quit = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + + fn toggle_engine(&mut self, ctx: &egui::Context) { + if self.analysis.is_on() { + self.analysis.stop(); + return; + } + match self.settings.active_engine().cloned() { + Some(cfg) => self.analysis.start(&cfg, ctx), + None => { + self.settings_ui.open = true; + self.settings_ui.tab = Tab::Engines; + self.toast(ctx, tr("Add a UCI engine (for example, Stockfish)")); + } + } + } + + fn paste_pgn(&mut self, ctx: &egui::Context) { + let text = arboard::Clipboard::new().and_then(|mut c| c.get_text()); + match text { + Ok(t) if !t.trim().is_empty() => { + // 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)])); + } + self.game = Some(GameView::new(parsed.game, None, parsed.diagnostics)); + } + _ => self.toast(ctx, tr("The clipboard is empty or unavailable")), + } + } + + fn confirm_dialog(&mut self, ctx: &egui::Context) { + let Some(intent) = self.confirm_close else { + return; + }; + let mut choice = None; + egui::Modal::new(egui::Id::new("confirm_close")).show(ctx, |ui| { + ui.set_width(380.0); + ui.heading(tr("Game modified")); + ui.label(tr( + "The source PGN is not changed. Save the changes to a separate file?", + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("Save as…")).clicked() { + choice = Some(0); + } + if ui.button(tr("Don't save")).clicked() { + choice = Some(1); + } + if ui.button(tr("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { + choice = Some(2); + } + }); + }); + match choice { + Some(0) => { + self.confirm_close = None; + self.close_after_save = Some(intent); + self.pick_save(ctx); + } + Some(1) => { + self.confirm_close = None; + self.finish_close(ctx, intent); + } + Some(2) => self.confirm_close = None, + _ => {} + } + } +} + +impl eframe::App for App { + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + 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); + } + if ctx.input(|i| i.viewport().close_requested()) + && !self.allow_quit + && self.game.as_ref().is_some_and(|g| g.game.is_modified()) + { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.confirm_close = Some(CloseIntent::QuitApp); + } + self.handle_async(&ctx); + self.debug_step(&ctx); + self.debug_screenshot(&ctx); + self.analysis.poll(); + + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) { + self.pick_databases(&ctx); + } + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() { + self.game = Some(GameView::new(Game::new(), None, Vec::new())); + } + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Comma))) { + self.settings_ui.open = !self.settings_ui.open; + } + + if let Some(game) = &mut self.game { + let input_enabled = self.confirm_close.is_none(); + let actions = game.show(ui, &mut self.settings, &mut self.analysis, input_enabled); + for a in actions { + match a { + GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary), + GameAction::Sound(s) => self.play(s), + GameAction::CopyText(text, msg) => { + ctx.copy_text(text); + self.toast(&ctx, msg); + } + GameAction::SaveAs => self.pick_save(&ctx), + 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::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + GameAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open, + GameAction::Toast(m) => self.toast(&ctx, m), + } + } + } else { + let dbs = self.settings.databases.clone(); + for a in self.library.show(ui, &dbs) { + match a { + LibraryAction::OpenGame { path, index } => self.open_game(&ctx, path, index), + LibraryAction::NewGame => { + self.game = Some(GameView::new(Game::new(), None, Vec::new())) + } + LibraryAction::PastePgn => self.paste_pgn(&ctx), + LibraryAction::AddDatabases => self.pick_databases(&ctx), + LibraryAction::RemoveDatabase(p) => { + self.settings.databases.retain(|d| *d != p); + self.library.forget(&p); + self.settings_dirty = true; + } + LibraryAction::OpenSettings => self.settings_ui.open = true, + LibraryAction::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + } + } + } + + let (actions, changed) = self.settings_ui.show(&ctx, &mut self.settings); + self.settings_dirty |= changed; + for a in actions { + match a { + SettingsAction::AddEngine => self.pick_engine(&ctx), + 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); + + if let Some((msg, until)) = &self.toast { + let now = ctx.input(|i| i.time); + if now > *until { + self.toast = None; + } else { + 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| { + ui.label(RichText::new(msg.as_str()).size(14.0)); + }); + }); + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } + } + + 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}"); + } + } + } + + fn on_exit(&mut self) { + self.analysis.stop(); + let _ = self.settings.save(); + } +} + +fn sanitize(s: &str) -> String { + s.chars() + .map(|c| match c { + '—' | '–' => '-', + c if c.is_alphanumeric() || " -.,".contains(c) => c, + _ => '_', + }) + .collect::() +} diff --git a/apps/desktop/src/assets.rs b/apps/desktop/src/assets.rs new file mode 100644 index 0000000..bd50b85 --- /dev/null +++ b/apps/desktop/src/assets.rs @@ -0,0 +1,442 @@ +//! 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, +} + +impl PieceSet { + pub const ALL: [PieceSet; 14] = [ + 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, + ]; + + 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", + } + } + + 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"), + } + } + + 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)) + } + + pub fn paint(self, ui: &egui::Ui, piece: Piece, rect: Rect) { + egui::Image::new(self.uri(piece)).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); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum BoardThemeId { + #[default] + Brown, + Blue, + Green, + Tournament, + Sand, + Coral, + Grey, + Purple, + Wood, + Wood2, + Wood3, + Wood4, + Maple, + Maple2, + Leather, + Marble, + BlueMarble, + Blue2, + Blue3, + Canvas, + Metal, + Olive, + Stone, + GreenPlastic, + PurpleDiag, + PinkPyramid, +} + +#[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"), + ), +]; + +impl BoardThemeId { + pub const ALL: [BoardThemeId; 26] = [ + BoardThemeId::Brown, + BoardThemeId::Blue, + BoardThemeId::Green, + BoardThemeId::Tournament, + BoardThemeId::Sand, + BoardThemeId::Coral, + BoardThemeId::Grey, + BoardThemeId::Purple, + 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, + ]; + + 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::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), + }; + 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), + 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"), + ), + }; + 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, +} + +impl SoundSet { + pub const ALL: [SoundSet; 2] = [SoundSet::Sfx, SoundSet::Piano]; + + pub fn label(self) -> &'static str { + match self { + SoundSet::Sfx => "SFX", + SoundSet::Piano => tr("Piano"), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Sound { + Move, + Capture, + Check, + Checkmate, +} + +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() + }; + } + match (set, sound) { + (SoundSet::Sfx, Sound::Move) => s!("sfx", "Move"), + (SoundSet::Sfx, Sound::Capture) => s!("sfx", "Capture"), + (SoundSet::Sfx, Sound::Check) => s!("sfx", "Check"), + (SoundSet::Sfx, Sound::Checkmate) => s!("sfx", "Checkmate"), + (SoundSet::Piano, Sound::Move) => s!("piano", "Move"), + (SoundSet::Piano, Sound::Capture) => s!("piano", "Capture"), + (SoundSet::Piano, Sound::Check) => s!("piano", "Check"), + (SoundSet::Piano, Sound::Checkmate) => s!("piano", "Checkmate"), + } +} diff --git a/apps/desktop/src/board.rs b/apps/desktop/src/board.rs new file mode 100644 index 0000000..b2b8bf3 --- /dev/null +++ b/apps/desktop/src/board.rs @@ -0,0 +1,370 @@ +//! Chessboard widget: drawing, click/drag move input, promotion picker, arrows. + +use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Shape, Stroke, Vec2, vec2}; +use shakmaty::{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, +} + +/// Interaction state that lives across frames (per board instance). +#[derive(Default)] +pub struct BoardState { + selected: Option, + drag: Option, + promotion: Option<(Square, Square)>, +} + +impl BoardState { + pub fn clear(&mut self) { + *self = Self::default(); + } +} + +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)], + pub interactive: bool, + pub show_coords: bool, + pub theme: BoardTheme, + pub pieces: PieceSet, +} + +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(); + let side = avail.x.min(avail.y).max(64.0).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; + + // --- input ----------------------------------------------------------------------- + if self.interactive && 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) + { + 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); + } + } + } 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), + } + } + if response.secondary_clicked() { + state.clear(); + } + } + + // --- 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(sel) = state.selected { + hl(&painter, sel, self.theme.selected); + } + if self.pos.is_check() + && let Some(k) = self.pos.board().king_of(self.pos.turn()) + { + let r = geo.square_rect(k); + painter.circle_filled( + r.center(), + sq_size * 0.48, + Color32::from_rgba_unmultiplied(230, 40, 40, 150), + ); + } + + if self.show_coords { + self.draw_coords(&painter, &geo); + } + + // --- pieces -------------------------------------------------------------------------- + for (sq, piece) in self.pos.board().clone() { + if state.drag == Some(sq) && response.dragged() { + continue; + } + self.pieces + .paint(ui, piece, geo.square_rect(sq).shrink(sq_size * 0.02)); + } + + // legal targets of the selected piece + if let Some(sel) = state.selected { + 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); + } + + // 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 own_piece(&self, sq: Square) -> bool { + self.pos + .board() + .piece_at(sq) + .is_some_and(|p| p.color == self.pos.turn()) + } + + fn try_move( + &self, + state: &mut BoardState, + legal: &shakmaty::MoveList, + from: Square, + to: Square, + ) -> Option { + 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 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), + ); + } + } +} + +/// 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))) + } +} + +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, + )); +} diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs new file mode 100644 index 0000000..5bd8821 --- /dev/null +++ b/apps/desktop/src/game_view.rs @@ -0,0 +1,1092 @@ +//! Game screen: board with eval bar, engine lines with PV preview, notation, toolbar. + +use crate::i18n::{tr, trf}; +use std::path::PathBuf; + +use chess_core::shakmaty::{Chess, Color, Move, Position, Square}; +use chess_core::{ + Annotation, CommentPart, Diagnostic, Game, MoveKind, 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::{Notation, NotationCommand}; +use crate::settings::Settings; + +/// Where an opened game came from (to return to the same library row). +#[derive(Clone, Debug)] +pub struct GameSource { + pub path: PathBuf, + pub index: usize, +} + +/// 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 { + pub game: Game, + pub source: Option, + pub diagnostics: Vec, + cursor: NodeId, + board: BoardState, + flipped: bool, + preview: Option, + scroll_to_cursor: bool, + show_diagnostics: bool, + engine_settings_open: bool, +} + +pub enum GameAction { + Back, + Sound(Sound), + CopyText(String, &'static str), + SaveAs, + ToggleEngine, + /// Threads/Hash/MultiPV/search time of the active engine changed (settings already updated). + EngineReconfigure, + /// Another engine was made active. + EngineSwitch, + OpenEngineSettings, + OpenSettings, + Quit, + Toast(String), +} + +impl GameView { + pub fn new(game: Game, source: Option, diagnostics: Vec) -> Self { + let flipped = false; + Self { + game, + source, + diagnostics, + cursor: NodeId::ROOT, + board: BoardState::default(), + flipped, + preview: None, + scroll_to_cursor: true, + show_diagnostics: false, + engine_settings_open: false, + } + } + + pub fn title(&self) -> String { + let g = &self.game; + let white = g.tag("White").filter(|s| *s != "?").unwrap_or(tr("White")); + let black = g.tag("Black").filter(|s| *s != "?").unwrap_or(tr("Black")); + format!("{white} — {black}") + } + + fn subtitle(&self) -> String { + let g = &self.game; + let mut parts = Vec::new(); + for t in ["Event", "Site", "Date", "ECO", "Annotator"] { + if let Some(v) = g + .tag(t) + .filter(|v| !v.is_empty() && !v.chars().all(|c| c == '?' || c == '.')) + { + parts.push(v.to_string()); + } + } + parts.join(" · ") + } + + fn goto(&mut self, id: NodeId) { + if id != self.cursor { + self.cursor = id; + self.board.clear(); + self.scroll_to_cursor = true; + } + self.preview = None; + } + + 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, + input_enabled: bool, + ) -> Vec { + let mut actions = Vec::new(); + if input_enabled { + 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); + egui::Panel::top("game_header").show(ui, |ui| self.header(ui, &mut actions)); + // Keep room for the board on narrow windows: the side panel never exceeds 60 %. + let width = ui.available_width(); + egui::Panel::right("game_side") + .resizable(true) + .default_size((width * 0.4).clamp(260.0, 460.0)) + .size_range(240.0_f32.min(width * 0.5)..=(width * 0.6).max(240.0)) + .show(ui, |ui| { + self.side_panel(ui, settings, analysis, &mut actions) + }); + self.sync_analysis(analysis); + egui::CentralPanel::default().show(ui, |ui| { + self.board_area(ui, &*settings, analysis, &mut actions) + }); + self.sync_analysis(analysis); + + 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 + } + + /// 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, actions: &mut Vec) { + ui.add_space(4.0); + ui.horizontal(|ui| { + if ui + .button(tr("⬅ Library")) + .on_hover_text(tr("Back to the game list (Ctrl+W)")) + .clicked() + { + actions.push(GameAction::Back); + } + ui.separator(); + ui.vertical(|ui| { + let modified = if self.game.is_modified() { " •" } else { "" }; + ui.label( + RichText::new(format!("{}{modified}", self.title())) + .strong() + .size(16.0), + ); + let sub = self.subtitle(); + if !sub.is_empty() { + ui.label(RichText::new(sub).weak()); + } + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::close_button(ui).clicked() { + actions.push(GameAction::Quit); + } + if ui + .button(tr("⚙ Settings")) + .on_hover_text("Ctrl+,") + .clicked() + { + actions.push(GameAction::OpenSettings); + } + let warnings = self + .diagnostics + .iter() + .filter(|d| d.severity >= Severity::Warning) + .count(); + if !self.diagnostics.is_empty() { + let text = if warnings > 0 { + RichText::new(format!("⚠ {warnings}")).color(ui.visuals().warn_fg_color) + } else { + RichText::new(format!("ℹ {}", self.diagnostics.len())).weak() + }; + if 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, + actions: &mut Vec, + ) { + 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)))); + } + _ => {} + } + } + } + } + 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 { 170 } else { 90 }; + arrows.push(Arrow { + from: sq.0, + to: sq.1, + color: Color32::from_rgba_unmultiplied(21, 120, 27, alpha), + weight: if i == 0 { 1.0 } else { 0.7 }, + }); + } + } + } + } + + // 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 side = (area.width() - bar_w - gap).min(area.height()).max(120.0); + 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, + interactive: self.preview.is_none(), + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + }; + if let Some(m) = view.show(ui, &mut self.board) { + 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 side_panel( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + analysis: &mut Analysis, + actions: &mut Vec, + ) { + 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)); + 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, + } + .show(ui); + if let Some(id) = resp.clicked { + self.goto(id); + } + if let Some((id, cmd)) = resp.context { + let result = match cmd { + 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); + 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), + ); + } + } + } + ui.vertical(|ui| { + 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()) + }; + ui.label(RichText::new(name).small()); + match &analysis.status { + Status::Starting => { + ui.label(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))], + ) + }; + ui.label( + RichText::new(format!("{}{tail}", trf("Depth {n}", &[("n", &depth)]))) + .small() + .weak(), + ); + } + Status::Failed(e) => { + ui.label(RichText::new(e).small().color(ui.visuals().error_fg_color)); + } + Status::Off => {} + } + }); + 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 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(); + for line in &lines { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 3.0; + ui.label( + RichText::new(analysis::format_eval(&line.score)) + .strong() + .monospace(), + ); + let start_num = root.as_ref().map(|p| (p.fullmoves().get(), p.turn())); + egui::ScrollArea::horizontal() + .id_salt(("pv", line.multipv)) + .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 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.preview = Some(Preview { + base, + root: root.clone(), + moves: line.moves.clone(), + san: line.san.clone(), + shown: i + 1, + }); + self.board.clear(); + } + } + }); + }); + }); + } + } + if let Some(p) = &self.preview { + let mut exit = false; + let mut insert = false; + egui::Frame::new() + .fill(ui.visuals().selection.bg_fill.gamma_multiply(0.35)) + .inner_margin(6) + .show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tr("Engine line preview")).strong()); + ui.label( + RichText::new(trf( + "move {a}/{b}", + &[("a", &p.shown), ("b", &p.moves.len())], + )) + .weak(), + ); + if ui.button(tr("Add as variation")).clicked() { + insert = true; + } + if ui.button(tr("Exit (Esc)")).clicked() { + exit = true; + } + }); + }); + if insert { + self.insert_preview(actions); + } else if exit { + self.preview = None; + } + } + 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); + ui.horizontal(|ui| { + let big = |s: &str| RichText::new(s).size(18.0); + 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); + } + ui.separator(); + if ui + .button(big("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.flipped = !self.flipped; + } + if ui + .add_enabled(self.game.can_undo(), egui::Button::new(big("↩"))) + .on_hover_text(tr("Undo move/edit (Ctrl+Z)")) + .clicked() + { + self.undo(); + } + if ui + .add_enabled(self.game.can_redo(), egui::Button::new(big("↪"))) + .on_hover_text(tr("Redo move/edit (Ctrl+Y)")) + .clicked() + { + self.redo(); + } + ui.separator(); + ui.menu_button(big("☰"), |ui| { + if ui.button(tr("Copy PGN")).clicked() { + actions.push(GameAction::CopyText(self.game.to_pgn(), tr("PGN copied"))); + 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 ui.button(tr("Save game as…")).clicked() { + actions.push(GameAction::SaveAs); + ui.close(); + } + if !self.diagnostics.is_empty() && ui.button(tr("Compatibility notes")).clicked() { + self.show_diagnostics = true; + ui.close(); + } + }); + if ui + .button(big("📋")) + .on_hover_text(tr("Copy PGN (Ctrl+Shift+C)")) + .clicked() + { + actions.push(GameAction::CopyText(self.game.to_pgn(), tr("PGN copied"))); + } + }); + 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; + } + + 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); + } + } + + fn step_back(&mut self) { + if let Some(p) = &mut self.preview { + 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() { + 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; + } + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let ctrl_shift = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k); + 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(Key::S)) { + cmds.push("save"); + } + if i.consume_shortcut(&ctrl(Key::W)) { + cmds.push("back"); + } + if i.modifiers.is_none() { + for (key, cmd) in [ + (Key::ArrowLeft, "back1"), + (Key::ArrowRight, "fwd1"), + (Key::ArrowUp, "prev_var"), + (Key::ArrowDown, "next_var"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::L, "engine"), + (Key::Escape, "esc"), + ] { + if i.key_pressed(key) { + cmds.push(cmd); + } + } + } + }); + for cmd in cmds { + match cmd { + "undo" => self.undo(), + "redo" => self.redo(), + "copy" => actions.push(GameAction::CopyText(self.game.to_pgn(), tr("PGN copied"))), + "save" => actions.push(GameAction::SaveAs), + "back" => actions.push(GameAction::Back), + "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, + "engine" => actions.push(GameAction::ToggleEngine), + "esc" => { + if self.preview.is_some() { + self.preview = None; + } else { + self.board.clear(); + } + } + _ => {} + } + } + } +} + +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; + ui.spacing_mut().slider_width = (ui.available_width() - 230.0).max(80.0); + egui::Grid::new("engine_settings_grid") + .num_columns(3) + .spacing(vec2(12.0, 8.0)) + .show(ui, |ui| { + // Search time + let mut t = SEARCH_TIMES + .iter() + .position(|s| *s == e.search_secs) + .unwrap_or(SEARCH_TIMES.len() - 1); + ui.label(tr("Search time")); + settled |= index_slider(ui, &mut t, SEARCH_TIMES.len()); + e.search_secs = SEARCH_TIMES[t]; + ui.label( + e.search_secs + .map(|s| trf("{n} s", &[("n", &s)])) + .unwrap_or_else(|| "∞".into()), + ); + ui.end_row(); + + // Lines + let mut k = e.multipv.clamp(1, 5) as usize - 1; + ui.label(tr("Lines")); + settled |= index_slider(ui, &mut k, 5); + e.multipv = k as u32 + 1; + ui.label(format!("{} / 5", e.multipv)); + ui.end_row(); + + // Threads + let mut th = e.threads.clamp(1, cores) as usize - 1; + ui.label(tr("Threads")); + settled |= index_slider(ui, &mut th, cores as usize); + e.threads = th as u32 + 1; + ui.label(format!("{} / {cores}", e.threads)); + ui.end_row(); + + // Memory + let mut h = hash_steps + .iter() + .position(|m| *m >= e.hash_mb) + .unwrap_or(hash_steps.len() - 1); + ui.label(tr("Memory")); + settled |= index_slider(ui, &mut h, hash_steps.len()); + e.hash_mb = hash_steps[h]; + ui.label(if e.hash_mb >= 1024 { + trf("{n} GB", &[("n", &(e.hash_mb / 1024))]) + } else { + trf("{n} MB", &[("n", &e.hash_mb)]) + }); + ui.end_row(); + }); + if settled { + actions.push(GameAction::EngineReconfigure); + } + }); +} + +/// Slider over `0..len`; returns true when the user finished changing it. +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()) +} + +/// Hash sizes from 16 MB up to half of physical memory (powers of two). +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 + } +} + +fn move_squares(m: &Move) -> Option<(Square, Square)> { + Some((m.from()?, board::ui_target(m))) +} + +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), + } +} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs new file mode 100644 index 0000000..5c97dab --- /dev/null +++ b/apps/desktop/src/i18n.rs @@ -0,0 +1,1101 @@ +//! 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, Serialize, Deserialize, Default)] +pub enum Lang { + #[default] + En, + Ru, + Fr, + De, + Es, + It, +} + +impl Lang { + pub const ALL: [Lang; 6] = [Lang::En, Lang::Ru, Lang::Fr, Lang::De, Lang::Es, Lang::It]; + + /// 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", + } + } + + fn column(self) -> usize { + self as usize + } +} + +static CURRENT: AtomicU8 = AtomicU8::new(0); + +pub fn set_lang(lang: Lang) { + CURRENT.store(lang as u8, Ordering::Relaxed); +} + +fn current() -> Lang { + Lang::ALL + .get(CURRENT.load(Ordering::Relaxed) as usize) + .copied() + .unwrap_or_default() +} + +fn table() -> &'static HashMap<&'static str, &'static [&'static str; 6]> { + 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) +} + +/// 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] +const ROWS: &[[&str; 6]] = &[ + // --- board themes --- + [ + "Tournament", + "Турнирная", + "Tournoi", + "Turnier", + "Torneo", + "Torneo", + ], + ["Sand", "Песочная", "Sable", "Sand", "Arena", "Sabbia"], + ["Coral", "Морская", "Corail", "Koralle", "Coral", "Corallo"], + ["Wood", "Дерево", "Bois", "Holz", "Madera", "Legno"], + ["Maple", "Клён", "Érable", "Ahorn", "Arce", "Acero"], + ["Leather", "Кожа", "Cuir", "Leder", "Cuero", "Pelle"], + ["Marble", "Мрамор", "Marbre", "Marmor", "Mármol", "Marmo"], + [ + "Blue marble", + "Синий мрамор", + "Marbre bleu", + "Blauer Marmor", + "Mármol azul", + "Marmo blu", + ], + ["Canvas", "Холст", "Toile", "Leinwand", "Lienzo", "Tela"], + ["Metal", "Металл", "Métal", "Metall", "Metal", "Metallo"], + ["Olive", "Олива", "Olive", "Olive", "Oliva", "Oliva"], + ["Stone", "Камень", "Pierre", "Stein", "Piedra", "Pietra"], + [ + "Green plastic", + "Зелёный пластик", + "Plastique vert", + "Grünes Plastik", + "Plástico verde", + "Plastica verde", + ], + [ + "Purple diagonal", + "Фиолетовые диагонали", + "Diagonales violettes", + "Lila Diagonalen", + "Diagonales moradas", + "Diagonali viola", + ], + [ + "Pink pyramid", + "Розовые пирамиды", + "Pyramides roses", + "Rosa Pyramiden", + "Pirámides rosas", + "Piramidi rosa", + ], + // --- common / window --- + [ + "Close the application", + "Закрыть программу", + "Fermer l'application", + "Programm schließen", + "Cerrar la aplicación", + "Chiudi l'applicazione", + ], + [ + "Cancel", + "Отмена", + "Annuler", + "Abbrechen", + "Cancelar", + "Annulla", + ], + [ + "Retry", + "Повторить", + "Réessayer", + "Erneut versuchen", + "Reintentar", + "Riprova", + ], + [ + "Remove from list", + "Убрать из списка", + "Retirer de la liste", + "Aus der Liste entfernen", + "Quitar de la lista", + "Rimuovi dall'elenco", + ], + ["White", "Белые", "Blancs", "Weiß", "Blancas", "Bianco"], + ["Black", "Чёрные", "Noirs", "Schwarz", "Negras", "Nero"], + // --- notation --- + [ + "Make main line", + "Сделать главным продолжением", + "Promouvoir en ligne principale", + "Zur Hauptvariante machen", + "Convertir en línea principal", + "Rendi linea principale", + ], + [ + "Delete move and continuation", + "Удалить ход и продолжение", + "Supprimer le coup et la suite", + "Zug und Fortsetzung löschen", + "Eliminar jugada y continuación", + "Elimina mossa e seguito", + ], + [ + "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'è", + ], + // --- assets --- + [ + "Brown", + "Коричневая", + "Marron", + "Braun", + "Marrón", + "Marrone", + ], + ["Blue", "Синяя", "Bleu", "Blau", "Azul", "Blu"], + ["Green", "Зелёная", "Vert", "Grün", "Verde", "Verde"], + ["Grey", "Серая", "Gris", "Grau", "Gris", "Grigio"], + ["Purple", "Фиолетовая", "Violet", "Lila", "Morado", "Viola"], + [ + "Piano", + "Фортепиано", + "Piano", + "Klavier", + "Piano", + "Pianoforte", + ], + // --- app --- + [ + "Open PGN", + "Открыть PGN", + "Ouvrir un PGN", + "PGN öffnen", + "Abrir PGN", + "Apri PGN", + ], + [ + "All files", + "Все файлы", + "Tous les fichiers", + "Alle Dateien", + "Todos los archivos", + "Tutti i file", + ], + [ + "Save game", + "Сохранить партию", + "Enregistrer la partie", + "Partie speichern", + "Guardar partida", + "Salva partita", + ], + [ + "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", + ], + [ + "Engine “{name}” added", + "Движок «{name}» добавлен", + "Moteur « {name} » ajouté", + "Engine „{name}“ hinzugefügt", + "Motor «{name}» añadido", + "Motore «{name}» aggiunto", + ], + [ + "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}", + ], + [ + "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", + ], + [ + "Saved: {path}", + "Сохранено: {path}", + "Enregistré : {path}", + "Gespeichert: {path}", + "Guardado: {path}", + "Salvato: {path}", + ], + [ + "Save failed: {e}", + "Ошибка сохранения: {e}", + "Échec de l'enregistrement : {e}", + "Speichern fehlgeschlagen: {e}", + "Error al guardar: {e}", + "Salvataggio non riuscito: {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", + ], + [ + "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)", + ], + [ + "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", + ], + [ + "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", + ], + [ + "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", + ], + [ + "Game modified", + "Партия изменена", + "Partie modifiée", + "Partie geändert", + "Partida modificada", + "Partita modificata", + ], + [ + "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?", + ], + [ + "Save as…", + "Сохранить как…", + "Enregistrer sous…", + "Speichern unter…", + "Guardar como…", + "Salva con nome…", + ], + [ + "Don't save", + "Не сохранять", + "Ne pas enregistrer", + "Nicht speichern", + "No guardar", + "Non salvare", + ], + // --- 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", + ], + [ + "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})", + ], + [ + "The engine exited", + "Движок завершился", + "Le moteur s'est arrêté", + "Die Engine wurde beendet", + "El motor terminó", + "Il motore è terminato", + ], + // --- settings --- + [ + "Settings", + "Настройки", + "Paramètres", + "Einstellungen", + "Ajustes", + "Impostazioni", + ], + [ + "Engines", + "Движки", + "Moteurs", + "Engines", + "Motores", + "Motori", + ], + [ + "Board & pieces", + "Доска и фигуры", + "Échiquier et pièces", + "Brett und Figuren", + "Tablero y piezas", + "Scacchiera e pezzi", + ], + ["Sound", "Звук", "Son", "Ton", "Sonido", "Audio"], + [ + "Interface", + "Интерфейс", + "Interface", + "Oberfläche", + "Interfaz", + "Interfaccia", + ], + [ + "Language:", + "Язык:", + "Langue :", + "Sprache:", + "Idioma:", + "Lingua:", + ], + ["Theme:", "Тема:", "Thème :", "Design:", "Tema:", "Tema:"], + ["Dark", "Тёмная", "Sombre", "Dunkel", "Oscuro", "Scuro"], + ["Light", "Светлая", "Clair", "Hell", "Claro", "Chiaro"], + [ + "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.", + ], + [ + "Make active", + "Сделать активным", + "Rendre actif", + "Aktivieren", + "Activar", + "Rendi attivo", + ], + ["Threads", "Потоки", "Threads", "Threads", "Hilos", "Thread"], + [ + "+ Add engine…", + "+ Добавить движок…", + "+ Ajouter un moteur…", + "+ Engine hinzufügen…", + "+ Añadir motor…", + "+ Aggiungi motore…", + ], + [ + "Checking engine…", + "Проверка движка…", + "Vérification du moteur…", + "Engine wird geprüft…", + "Comprobando el motor…", + "Verifica del motore…", + ], + [ + "Piece set", + "Набор фигур", + "Jeu de pièces", + "Figurensatz", + "Juego de piezas", + "Set di pezzi", + ], + [ + "Board", + "Доска", + "Échiquier", + "Brett", + "Tablero", + "Scacchiera", + ], + [ + "Show coordinates", + "Показывать координаты", + "Afficher les coordonnées", + "Koordinaten anzeigen", + "Mostrar coordenadas", + "Mostra coordinate", + ], + [ + "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", + ], + [ + "Move sounds", + "Звуки ходов", + "Sons des coups", + "Zuggeräusche", + "Sonidos de jugadas", + "Suoni delle mosse", + ], + ["Set:", "Набор:", "Jeu :", "Satz:", "Conjunto:", "Set:"], + [ + "Volume:", + "Громкость:", + "Volume :", + "Lautstärke:", + "Volumen:", + "Volume:", + ], + [ + "▶ Test", + "▶ Проверить", + "▶ Tester", + "▶ Testen", + "▶ Probar", + "▶ Prova", + ], + // --- library --- + [ + "Loading cancelled", + "Загрузка отменена", + "Chargement annulé", + "Laden abgebrochen", + "Carga cancelada", + "Caricamento annullato", + ], + [ + "Databases", + "Базы", + "Bases", + "Datenbanken", + "Bases", + "Database", + ], + [ + "⚙ Settings", + "⚙ Настройки", + "⚙ Paramètres", + "⚙ Einstellungen", + "⚙ Ajustes", + "⚙ Impostazioni", + ], + [ + "📋 Paste PGN", + "📋 Вставить PGN", + "📋 Coller un PGN", + "📋 PGN einfügen", + "📋 Pegar PGN", + "📋 Incolla 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", + ], + [ + "♟ New game", + "♟ Новая партия", + "♟ Nouvelle partie", + "♟ Neue Partie", + "♟ Nueva partida", + "♟ Nuova partita", + ], + [ + "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)", + ], + [ + "+ Add PGN", + "+ Добавить PGN", + "+ Ajouter un PGN", + "+ PGN hinzufügen", + "+ Añadir PGN", + "+ Aggiungi PGN", + ], + [ + "Open a PGN file (Ctrl+O)", + "Открыть PGN-файл (Ctrl+O)", + "Ouvrir un fichier PGN (Ctrl+O)", + "PGN-Datei öffnen (Ctrl+O)", + "Abrir un archivo PGN (Ctrl+O)", + "Apri un file PGN (Ctrl+O)", + ], + [ + "{n} games", + "{n} партий", + "{n} parties", + "{n} Partien", + "{n} partidas", + "{n} partite", + ], + [ + "loading… {n}", + "загрузка… {n}", + "chargement… {n}", + "lädt… {n}", + "cargando… {n}", + "caricamento… {n}", + ], + ["error", "ошибка", "erreur", "Fehler", "error", "errore"], + [ + "file not found", + "файл не найден", + "fichier introuvable", + "Datei nicht gefunden", + "archivo no encontrado", + "file non trovato", + ], + [ + "not loaded", + "не загружена", + "non chargée", + "nicht geladen", + "no cargada", + "non caricato", + ], + [ + "Reload file", + "Перечитать файл", + "Recharger le fichier", + "Datei neu laden", + "Volver a leer el archivo", + "Ricarica il file", + ], + [ + "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", + ], + [ + "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}", + ], + [ + "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} games · encoding {enc}", + "· {n} партий · кодировка {enc}", + "· {n} parties · encodage {enc}", + "· {n} Partien · Kodierung {enc}", + "· {n} partidas · codificación {enc}", + "· {n} partite · codifica {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", + ], + [ + "Result", + "Результат", + "Résultat", + "Ergebnis", + "Resultado", + "Risultato", + ], + ["Moves", "Ходы", "Coups", "Züge", "Jugadas", "Mosse"], + ["Event", "Турнир", "Tournoi", "Turnier", "Torneo", "Torneo"], + ["Date", "Дата", "Date", "Datum", "Fecha", "Data"], + // --- game view --- + [ + "PGN compatibility", + "Совместимость PGN", + "Compatibilité PGN", + "PGN-Kompatibilität", + "Compatibilidad PGN", + "Compatibilità PGN", + ], + [ + "line {n}: ", + "строка {n}: ", + "ligne {n} : ", + "Zeile {n}: ", + "línea {n}: ", + "riga {n}: ", + ], + [ + "⬅ Library", + "⬅ Библиотека", + "⬅ Bibliothèque", + "⬅ Bibliothek", + "⬅ Biblioteca", + "⬅ Libreria", + ], + [ + "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)", + ], + [ + "PGN compatibility notes", + "Замечания по совместимости PGN", + "Remarques de compatibilité PGN", + "Hinweise zur PGN-Kompatibilität", + "Avisos de compatibilidad PGN", + "Note di compatibilità PGN", + ], + [ + "Move not added: {e}", + "Ход не добавлен: {e}", + "Coup non ajouté : {e}", + "Zug nicht hinzugefügt: {e}", + "Jugada no añadida: {e}", + "Mossa non aggiunta: {e}", + ], + [ + "Analysis: on", + "Анализ: вкл", + "Analyse : activée", + "Analyse: an", + "Análisis: activado", + "Analisi: attiva", + ], + [ + "Analysis: off", + "Анализ: выкл", + "Analyse : désactivée", + "Analyse: aus", + "Análisis: desactivado", + "Analisi: disattiva", + ], + [ + "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)", + ], + [ + "No engine selected", + "Движок не выбран", + "Aucun moteur sélectionné", + "Keine Engine gewählt", + "Ningún motor seleccionado", + "Nessun motore selezionato", + ], + [ + "starting…", + "запуск…", + "démarrage…", + "startet…", + "iniciando…", + "avvio…", + ], + [ + " · done", + " · готово", + " · terminé", + " · fertig", + " · listo", + " · completato", + ], + [ + " · {n} Mn/s", + " · {n} Музл/с", + " · {n} Mn/s", + " · {n} MKn/s", + " · {n} Mn/s", + " · {n} Mn/s", + ], + [ + "Depth {n}", + "Глубина {n}", + "Profondeur {n}", + "Tiefe {n}", + "Profundidad {n}", + "Profondità {n}", + ], + [ + "Engine settings", + "Настройки движка", + "Réglages du moteur", + "Engine-Einstellungen", + "Ajustes del motor", + "Impostazioni del motore", + ], + [ + "Engine line preview", + "Предпросмотр линии движка", + "Aperçu de la ligne du moteur", + "Vorschau der Engine-Variante", + "Vista previa de la línea del motor", + "Anteprima della linea del motore", + ], + [ + "move {a}/{b}", + "ход {a}/{b}", + "coup {a}/{b}", + "Zug {a}/{b}", + "jugada {a}/{b}", + "mossa {a}/{b}", + ], + [ + "Add as variation", + "Добавить как вариант", + "Ajouter comme variante", + "Als Variante hinzufügen", + "Añadir como variante", + "Aggiungi come variante", + ], + [ + "Exit (Esc)", + "Выйти (Esc)", + "Quitter (Échap)", + "Beenden (Esc)", + "Salir (Esc)", + "Esci (Esc)", + ], + [ + "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)", + ], + [ + "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}", + ], + [ + "To start (Home)", + "В начало (Home)", + "Au début (Début)", + "Zum Anfang (Pos1)", + "Al inicio (Inicio)", + "All'inizio (Home)", + ], + [ + "Back (←)", + "Назад (←)", + "Reculer (←)", + "Zurück (←)", + "Atrás (←)", + "Indietro (←)", + ], + [ + "Forward (→)", + "Вперёд (→)", + "Avancer (→)", + "Vor (→)", + "Adelante (→)", + "Avanti (→)", + ], + [ + "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)", + ], + [ + "Flip board (F)", + "Перевернуть доску (F)", + "Retourner l'échiquier (F)", + "Brett drehen (F)", + "Girar el tablero (F)", + "Ruota la scacchiera (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)", + ], + [ + "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)", + ], + [ + "Copy PGN", + "Копировать PGN", + "Copier le PGN", + "PGN kopieren", + "Copiar PGN", + "Copia PGN", + ], + [ + "PGN copied", + "PGN скопирован", + "PGN copié", + "PGN kopiert", + "PGN copiado", + "PGN copiato", + ], + [ + "Copy FEN", + "Копировать FEN", + "Copier la FEN", + "FEN kopieren", + "Copiar FEN", + "Copia FEN", + ], + [ + "FEN copied", + "FEN скопирован", + "FEN copiée", + "FEN kopiert", + "FEN copiado", + "FEN copiato", + ], + [ + "Save game as…", + "Сохранить партию как…", + "Enregistrer la partie sous…", + "Partie speichern unter…", + "Guardar partida como…", + "Salva partita con nome…", + ], + [ + "Compatibility notes", + "Замечания по совместимости", + "Remarques de compatibilité", + "Kompatibilitätshinweise", + "Avisos de compatibilidad", + "Note di compatibilità", + ], + [ + "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)", + ], + ["Engine", "Движок", "Moteur", "Engine", "Motor", "Motore"], + [ + "not selected", + "не выбран", + "non sélectionné", + "nicht gewählt", + "no seleccionado", + "non selezionato", + ], + [ + "Add or edit engines…", + "Добавить или изменить движки…", + "Ajouter ou modifier des moteurs…", + "Engines hinzufügen oder bearbeiten…", + "Añadir o editar motores…", + "Aggiungi o modifica motori…", + ], + [ + "Add engine…", + "Добавить движок…", + "Ajouter un moteur…", + "Engine hinzufügen…", + "Añadir motor…", + "Aggiungi motore…", + ], + [ + "Search time", + "Время поиска", + "Temps de recherche", + "Suchzeit", + "Tiempo de búsqueda", + "Tempo di ricerca", + ], + ["{n} s", "{n} с", "{n} s", "{n} s", "{n} s", "{n} s"], + ["Lines", "Линий", "Lignes", "Varianten", "Líneas", "Linee"], + [ + "Memory", + "Память", + "Mémoire", + "Speicher", + "Memoria", + "Memoria", + ], + ["{n} GB", "{n} ГБ", "{n} Go", "{n} GB", "{n} GB", "{n} GB"], + ["{n} MB", "{n} МБ", "{n} Mo", "{n} MB", "{n} MB", "{n} MB"], + [ + "Checkmate · 0-1", + "Мат · 0-1", + "Mat · 0-1", + "Matt · 0-1", + "Jaque mate · 0-1", + "Scacco matto · 0-1", + ], + [ + "Checkmate · 1-0", + "Мат · 1-0", + "Mat · 1-0", + "Matt · 1-0", + "Jaque mate · 1-0", + "Scacco matto · 1-0", + ], + [ + "Stalemate · ½-½", + "Пат · ½-½", + "Pat · ½-½", + "Patt · ½-½", + "Ahogado · ½-½", + "Stallo · ½-½", + ], + [ + "Insufficient material", + "Недостаточно материала", + "Matériel insuffisant", + "Ungenügendes Material", + "Material insuficiente", + "Materiale insufficiente", + ], +]; + +#[cfg(test)] +mod tests { + use super::*; + + /// 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!("notation.rs"), + include_str!("settings_ui.rs"), + include_str!("widgets.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:?}"); + } + + #[test] + fn rows_are_unique_and_complete() { + let mut seen = std::collections::HashSet::new(); + for row in ROWS { + 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/library.rs b/apps/desktop/src/library.rs new file mode 100644 index 0000000..908bf7b --- /dev/null +++ b/apps/desktop/src/library.rs @@ -0,0 +1,628 @@ +//! Library screen: shelf of PGN databases + searchable, sortable game table. + +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::{GameEntry, OpenError, PgnDatabase, ScanProgress}; +use egui::{Color32, RichText, Sense, Ui, vec2}; +use egui_extras::{Column, TableBuilder}; + +enum Slot { + Loading { + progress: Arc>, + cancel: Arc, + rx: Receiver>, + }, + Ready(Arc), + Failed(String), +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum SortKey { + Index, + White, + WhiteElo, + Black, + BlackElo, + Result, + Date, + Event, + Eco, + Moves, +} + +pub enum LibraryAction { + OpenGame { path: PathBuf, index: usize }, + NewGame, + PastePgn, + AddDatabases, + RemoveDatabase(PathBuf), + OpenSettings, + Quit, +} + +pub struct Library { + slots: HashMap, + pub selected_db: Option, + search: String, + selected_row: Option, + sort: (SortKey, bool), + /// Cached filtered+sorted entry indices for (db, search, sort). + view: Vec, + view_key: Option<(PathBuf, String, SortKey, bool)>, + scroll_to_selected: bool, +} + +impl Library { + pub fn new() -> Self { + Self { + slots: HashMap::new(), + selected_db: None, + search: String::new(), + selected_row: None, + sort: (SortKey::Index, true), + view: Vec::new(), + view_key: None, + scroll_to_selected: false, + } + } + + /// 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, c, path_owned, ctx) = ( + progress.clone(), + cancel.clone(), + path.to_path_buf(), + ctx.clone(), + ); + let spawned = std::thread::Builder::new() + .name("pgn-scan".into()) + .spawn(move || { + let res = PgnDatabase::open( + &path_owned, + &mut |sp| { + if let Ok(mut g) = p.lock() { + *g = sp; + } + ctx.request_repaint(); + }, + &c, + ); + 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()); + self.selected_row = None; + self.search.clear(); + self.view_key = None; + } + } + + /// Selects (and scrolls to) a game row, e.g. when returning from a game. + pub fn reveal(&mut self, path: &Path, index: usize) { + if self.selected_db.as_deref() == Some(path) { + self.selected_row = Some(index); + self.scroll_to_selected = true; + } + } + + pub fn forget(&mut self, path: &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; + self.view_key = None; + } + } + + pub fn database(&self, path: &Path) -> Option> { + match self.slots.get(path) { + Some(Slot::Ready(db)) => Some(db.clone()), + _ => None, + } + } + + fn poll(&mut self) { + for slot in self.slots.values_mut() { + if let Slot::Loading { rx, .. } = slot + && let Ok(res) = rx.try_recv() + { + *slot = match res { + Ok(db) => Slot::Ready(Arc::new(db)), + Err(OpenError::Cancelled) => Slot::Failed(tr("Loading cancelled").into()), + Err(e) => Slot::Failed(e.to_string()), + }; + self.view_key = None; + } + } + } + + pub fn show(&mut self, ui: &mut Ui, databases: &[PathBuf]) -> Vec { + self.poll(); + let mut actions = Vec::new(); + egui::Panel::top("shelf").show(ui, |ui| self.shelf(ui, databases, &mut actions)); + egui::CentralPanel::default().show(ui, |ui| self.table_area(ui, &mut actions)); + actions + } + + fn shelf(&mut self, ui: &mut Ui, databases: &[PathBuf], actions: &mut Vec) { + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.heading(tr("Databases")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::close_button(ui).clicked() { + actions.push(LibraryAction::Quit); + } + if ui.button(tr("⚙ Settings")).clicked() { + actions.push(LibraryAction::OpenSettings); + } + if ui + .button(tr("📋 Paste PGN")) + .on_hover_text(tr("Open a game from the clipboard")) + .clicked() + { + actions.push(LibraryAction::PastePgn); + } + if ui + .button(tr("♟ New game")) + .on_hover_text(tr("Empty board in the starting position (Ctrl+N)")) + .clicked() + { + actions.push(LibraryAction::NewGame); + } + }); + }); + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 8.0); + for path in databases { + self.db_card(ui, path, actions); + } + let (rect, resp) = ui.allocate_exact_size(vec2(150.0, 64.0), Sense::click()); + let visuals = ui.style().interact(&resp); + ui.painter() + .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("+ Add PGN"), + egui::FontId::proportional(15.0), + visuals.text_color(), + ); + if resp.on_hover_text(tr("Open a PGN file (Ctrl+O)")).clicked() { + actions.push(LibraryAction::AddDatabases); + } + }); + ui.add_space(8.0); + } + + fn db_card(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec) { + 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 detail = match self.slots.get(path) { + Some(Slot::Ready(db)) => trf("{n} games", &[("n", &db.len())]), + 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(_)) => tr("error").into(), + None if !path.exists() => tr("file not found").into(), + None => tr("not loaded").into(), + }; + 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, + "🗄", + egui::FontId::proportional(22.0), + text_color, + ); + let galley = ui.painter().layout( + name, + egui::FontId::proportional(14.0), + text_color, + rect.width() - 52.0, + ); + 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 = resp.on_hover_text(path.display().to_string()); + if resp.clicked() { + self.select_db(path, ui.ctx()); + } + resp.context_menu(|ui| { + 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.view_key = None; + self.load(path, ui.ctx()); + ui.close(); + } + }); + } + + fn table_area(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(path) = self.selected_db.clone() else { + ui.centered_and_justified(|ui| { + ui.label( + RichText::new(tr( + "Choose a database above, add a PGN file or start a new game", + )) + .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", &path.display()), ("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; + } + 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", &path.display()), ("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 mut search_focused = false; + ui.horizontal(|ui| { + ui.label( + RichText::new( + path.file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(), + ) + .strong(), + ); + let enc = db.encoding(); + ui.label( + RichText::new(trf( + "· {n} games · encoding {enc}", + &[("n", &db.len()), ("enc", &enc.label())], + )) + .weak(), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let resp = ui.add( + egui::TextEdit::singleline(&mut self.search) + .hint_text(tr("🔍 Search: player, event, ECO, year")) + .desired_width(280.0), + ); + if ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::F)) { + resp.request_focus(); + } + search_focused = resp.has_focus(); + }); + }); + ui.add_space(4.0); + + let key = (path.clone(), self.search.clone(), self.sort.0, self.sort.1); + if self.view_key.as_ref() != Some(&key) { + self.view = filtered_sorted(db.entries(), &self.search, self.sort); + self.view_key = Some(key); + } + + // Keyboard: Up/Down move the selection, Enter opens. + if !ui.ctx().egui_wants_keyboard_input() || search_focused { + let pos = self + .selected_row + .and_then(|r| self.view.iter().position(|&i| i == r)); + let (up, down, enter) = ui.input(|i| { + ( + i.key_pressed(egui::Key::ArrowUp), + i.key_pressed(egui::Key::ArrowDown), + i.key_pressed(egui::Key::Enter), + ) + }); + if down || up { + let next = match (pos, down) { + (None, _) => 0, + (Some(p), true) => (p + 1).min(self.view.len().saturating_sub(1)), + (Some(p), false) => p.saturating_sub(1), + }; + if let Some(&i) = self.view.get(next) { + self.selected_row = Some(i); + self.scroll_to_selected = true; + } + } + if enter && let Some(index) = self.selected_row { + actions.push(LibraryAction::OpenGame { + path: path.clone(), + index, + }); + } + } + + let scroll_row = if std::mem::take(&mut self.scroll_to_selected) { + self.selected_row + .and_then(|r| self.view.iter().position(|&i| i == r)) + } else { + None + }; + let headers: [(&str, SortKey); 10] = [ + ("№", SortKey::Index), + (tr("White"), SortKey::White), + ("Elo", SortKey::WhiteElo), + (tr("Black"), SortKey::Black), + ("Elo", SortKey::BlackElo), + (tr("Result"), SortKey::Result), + (tr("Moves"), SortKey::Moves), + ("ECO", SortKey::Eco), + (tr("Event"), SortKey::Event), + (tr("Date"), SortKey::Date), + ]; + let mut table = TableBuilder::new(ui) + .striped(true) + .resizable(true) + .sense(Sense::click()) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::exact(52.0)) + .column(Column::initial(170.0).at_least(60.0).clip(true)) + .column(Column::exact(48.0)) + .column(Column::initial(170.0).at_least(60.0).clip(true)) + .column(Column::exact(48.0)) + .column(Column::exact(80.0)) + .column(Column::exact(52.0)) + .column(Column::exact(48.0)) + .column(Column::remainder().at_least(80.0).clip(true)) + .column(Column::exact(96.0)); + if let Some(r) = scroll_row { + table = table.scroll_to_row(r, Some(egui::Align::Center)); + } + let view = &self.view; + let entries = db.entries(); + let mut clicked = None; + let mut opened = None; + let mut sort_click = None; + table + .header(26.0, |mut header| { + for (label, key) in headers { + header.col(|ui| { + let arrow = if self.sort.0 == key { + if self.sort.1 { " ⏶" } else { " ⏷" } + } else { + "" + }; + if ui + .add( + egui::Button::new( + RichText::new(format!("{label}{arrow}")).strong(), + ) + .frame(false), + ) + .clicked() + { + sort_click = Some(key); + } + }); + } + }) + .body(|body| { + body.rows(24.0, view.len(), |mut row| { + let Some(e) = view.get(row.index()).and_then(|&i| entries.get(i)) else { + return; + }; + row.set_selected(self.selected_row == Some(e.index)); + let cells: [String; 10] = [ + (e.index + 1).to_string(), + e.white().unwrap_or("").to_string(), + e.white_elo().map(|x| x.to_string()).unwrap_or_default(), + e.black().unwrap_or("").to_string(), + e.black_elo().map(|x| x.to_string()).unwrap_or_default(), + e.result().unwrap_or("*").to_string(), + e.ply_count() + .map(|p| p.div_ceil(2).to_string()) + .unwrap_or_default(), + e.eco().unwrap_or("").to_string(), + e.event().filter(|s| *s != "?").unwrap_or("").to_string(), + display_date(e.date().unwrap_or("")), + ]; + for (i, text) in cells.into_iter().enumerate() { + row.col(|ui| { + let mut t = RichText::new(text); + if i == 0 { + t = t.weak(); + } + if i == 8 { + t = t.italics(); + } + if i == 0 && (e.flags.has_structure_issues || e.flags.has_decode_errors) + { + t = t.color(Color32::from_rgb(0xe6, 0x8f, 0x00)); + } + ui.add(egui::Label::new(t).selectable(false).truncate()); + }); + } + let resp = row.response(); + if resp.clicked() { + clicked = Some(e.index); + } + if resp.double_clicked() { + opened = Some(e.index); + } + }); + }); + if let Some(k) = sort_click { + self.sort = if self.sort.0 == k { + (k, !self.sort.1) + } else { + (k, true) + }; + } + if let Some(i) = clicked { + self.selected_row = Some(i); + } + if let Some(index) = opened { + self.selected_row = Some(index); + actions.push(LibraryAction::OpenGame { path, index }); + } + } +} + +/// "2010.??.??" → "2010", "1997.05.??" → "05.1997", full dates as "dd.mm.yyyy". +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(), + } +} + +fn filtered_sorted(entries: &[GameEntry], search: &str, (key, asc): (SortKey, bool)) -> Vec { + let needle = search.trim().to_lowercase(); + let mut v: Vec = entries + .iter() + .filter(|e| { + needle.is_empty() + || [ + "White", + "Black", + "Event", + "Site", + "ECO", + "Date", + "Annotator", + ] + .iter() + .any(|t| e.tag(t).is_some_and(|s| s.to_lowercase().contains(&needle))) + }) + .map(|e| e.index) + .collect(); + let text = |e: &GameEntry| -> String { + match key { + SortKey::White => e.white().unwrap_or("").to_lowercase(), + SortKey::Black => e.black().unwrap_or("").to_lowercase(), + SortKey::Result => e.result().unwrap_or("").to_string(), + SortKey::Date => e.date().unwrap_or("").to_string(), + SortKey::Event => e.event().unwrap_or("").to_lowercase(), + SortKey::Eco => e.eco().unwrap_or("").to_string(), + _ => String::new(), + } + }; + let num = |e: &GameEntry| -> i64 { + match key { + SortKey::Index => e.index as i64, + SortKey::WhiteElo => e.white_elo().map(i64::from).unwrap_or(-1), + SortKey::BlackElo => e.black_elo().map(i64::from).unwrap_or(-1), + SortKey::Moves => e.ply_count().map(i64::from).unwrap_or(-1), + _ => 0, + } + }; + v.sort_by(|&a, &b| { + let (ea, eb) = (&entries[a], &entries[b]); + let ord = text(ea) + .cmp(&text(eb)) + .then(num(ea).cmp(&num(eb))) + .then(a.cmp(&b)); + if asc { ord } else { ord.reverse() } + }); + v +} diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs new file mode 100644 index 0000000..8fab2be --- /dev/null +++ b/apps/desktop/src/main.rs @@ -0,0 +1,39 @@ +// No console window for release builds on Windows. +#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] + +mod analysis; +mod app; +mod assets; +mod board; +mod game_view; +mod i18n; +mod library; +mod notation; +mod settings; +mod settings_ui; +mod sound; +mod widgets; + +fn main() -> eframe::Result { + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_app_id("io.github.vrubelroman.chessPenguin") + .with_title("ChessPenguin") + .with_inner_size([1400.0, 900.0]) + .with_min_inner_size([900.0, 600.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(), + ), + ..Default::default() + }; + eframe::run_native( + "ChessPenguin", + options, + Box::new(|cc| { + assets::install(&cc.egui_ctx); + Ok(Box::new(app::App::new(&cc.egui_ctx))) + }), + ) +} diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs new file mode 100644 index 0000000..1a3932d --- /dev/null +++ b/apps/desktop/src/notation.rs @@ -0,0 +1,370 @@ +//! 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 crate::i18n::tr; +use chess_core::shakmaty::Color; +use chess_core::{CommentPart, Game, Nag, NodeId, parse_comment}; +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, +} + +/// Result of a frame of the notation panel. +#[derive(Default)] +pub struct NotationResponse { + pub clicked: Option, + pub context: Option<(NodeId, NotationCommand)>, +} + +#[derive(Clone, Copy, Debug)] +pub enum NotationCommand { + Promote, + Delete, +} + +const ROW_H: f32 = 26.0; +const NUM_W: f32 = 38.0; + +impl Notation<'_> { + pub fn show(self, ui: &mut Ui) -> NotationResponse { + let mut out = NotationResponse::default(); + let game = self.game; + let root_comments = comment_text( + game.node(NodeId::ROOT) + .map(|n| n.comments_after()) + .unwrap_or(&[]), + ); + if !root_comments.is_empty() { + comment_block(ui, &root_comments); + } + + 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 !before.is_empty() { + row.flush(ui, &self, &mut out); + comment_block(ui, &before); + } + 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); + let interrupted = !after.is_empty() || !vars.is_empty() || !n.unparsed().is_empty(); + if interrupted || color == Color::Black { + row.flush(ui, &self, &mut out); + if !after.is_empty() { + comment_block(ui, &after); + } + for u in n.unparsed() { + unparsed_block(ui, u); + } + for &v in vars { + variation_block(ui, &self, v, &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; + 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()); + paint_move_cell(ui, cell, n.game, id, id == n.cursor, resp.hovered()); + 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); + resp.context_menu(|ui| { + 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(); + } + }); + let _ = ui; +} + +fn paint_move_cell( + ui: &Ui, + cell: egui::Rect, + game: &Game, + id: NodeId, + current: bool, + hovered: bool, +) { + 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 (sym, color) = node + .map(|n| move_glyph(n.nags())) + .unwrap_or((String::new(), None)); + let text_color = if current { + visuals.selection.stroke.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}"), + FontId::proportional(16.0), + text_color, + ); +} + +/// Move-assessment glyph (`!`, `?`, …) with its color, plus position assessments. +fn move_glyph(nags: &[Nag]) -> (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() { + color = Some(match nag.0 { + 1 => Color32::from_rgb(0x62, 0x9c, 0x2e), + 2 => Color32::from_rgb(0xe6, 0x8f, 0x00), + 3 => Color32::from_rgb(0x22, 0xac, 0x9a), + 4 => Color32::from_rgb(0xdf, 0x53, 0x53), + 5 => Color32::from_rgb(0xea, 0x45, 0xd8), + 6 => Color32::from_rgb(0x56, 0xb4, 0xe9), + _ => continue, + }); + s.push_str(sym); + } else { + s.push(' '); + s.push_str(sym); + } + } + (s, color) +} + +fn comment_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 { + // Source line breaks are formatting, not content: reflow to the panel width. + for word in t.split_whitespace() { + if !out.is_empty() { + out.push(' '); + } + out.push_str(word); + } + } + } + } + out +} + +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, + )) +} + +fn comment_block(ui: &mut Ui, text: &str) { + block_frame(ui).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(RichText::new(text).color(comment_color(ui)).size(14.5)); + }); +} + +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) + } +} + +fn variation_block(ui: &mut Ui, n: &Notation, start: NodeId, out: &mut NotationResponse) { + block_frame(ui).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(3.0, 2.0); + inline_line(ui, n, start, out); + }); + }); +} + +/// Renders a line starting at `first` (a variation move) as flowing text. +fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationResponse) { + 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() { + ui.label(RichText::new(before).color(comment_color(ui))); + 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 (sym, sym_color) = move_glyph(nd.nags()); + 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 current = node == n.cursor; + let mut text = RichText::new(label).size(15.0); + if let Some(c) = sym_color + && !current + { + text = text.color(c); + } + // Same strong highlight as the main-line table, so the current move is visible inside text. + let button = if current { + let sel = ui.visuals().selection; + egui::Button::new(text.color(sel.stroke.color).strong()) + .fill(sel.bg_fill) + .stroke(egui::Stroke::new(1.0, sel.stroke.color)) + } else { + egui::Button::new(text).frame_when_inactive(false) + }; + let resp = ui.add(button); + handle_move_response(ui, &resp, n, node, out); + + let after = comment_text(nd.comments_after()); + if !after.is_empty() { + ui.label(RichText::new(after).color(comment_color(ui))); + need_number = true; + } + for u in nd.unparsed() { + ui.label( + RichText::new(u) + .monospace() + .color(ui.visuals().warn_fg_color), + ); + } + // 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) { + ui.label(RichText::new("(").weak()); + inline_line(ui, n, v, out); + ui.label(RichText::new(")").weak()); + need_number = true; + } + } + match game.main_child(node) { + Some(next) => node = next, + None => return, + } + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs new file mode 100644 index 0000000..6d54e81 --- /dev/null +++ b/apps/desktop/src/settings.rs @@ -0,0 +1,156 @@ +//! 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, +} + +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, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct Settings { + pub piece_set: PieceSet, + pub board_theme: BoardThemeId, + pub show_coords: bool, + pub sound_enabled: bool, + pub sound_set: SoundSet, + pub volume: f32, + pub dark_mode: bool, + 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, +} + +impl Default for Settings { + fn default() -> Self { + Self { + piece_set: PieceSet::default(), + board_theme: BoardThemeId::default(), + show_coords: true, + sound_enabled: true, + sound_set: SoundSet::default(), + volume: 0.7, + dark_mode: true, + language: Lang::default(), + engines: Vec::new(), + active_engine: None, + show_best_arrow: true, + databases: Vec::new(), + } + } +} + +impl Settings { + pub fn config_dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.config_dir().to_path_buf()) + } + + fn file() -> Option { + Self::config_dir().map(|d| d.join("settings.json")) + } + + pub fn load() -> Self { + let Some(path) = Self::file() else { + return Self::default(); + }; + migrate_legacy_config(&path); + match std::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(_) => 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)) + } + + pub fn touch_database(&mut self, path: &Path) { + self.databases.retain(|p| p != path); + self.databases.insert(0, path.to_path_buf()); + } +} + +/// Copies settings of the pre-rename build (`chessbase-linux`) once, if the new file is absent. +fn migrate_legacy_config(new_file: &Path) { + if new_file.exists() { + 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<()> { + 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); + }) +} diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs new file mode 100644 index 0000000..7693e94 --- /dev/null +++ b/apps/desktop/src/settings_ui.rs @@ -0,0 +1,296 @@ +//! Settings window: engines, board & pieces, sound, interface. + +use crate::i18n::{Lang, tr}; +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, +} + +pub enum SettingsAction { + AddEngine, + TestSound, + /// The active engine (or its options) changed; a running analysis should restart. + EngineChanged, +} + +pub struct SettingsWindow { + pub open: bool, + pub tab: Tab, + pub checking_engine: bool, +} + +impl SettingsWindow { + pub fn new() -> Self { + Self { + open: false, + tab: Tab::default(), + checking_engine: false, + } + } + + /// Returns actions and whether settings changed (to be saved). + pub fn show(&mut self, ctx: &egui::Context, s: &mut Settings) -> (Vec, bool) { + let mut actions = Vec::new(); + let mut changed = false; + let mut open = self.open; + 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")); + }); + 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::Sound => sound_tab(ui, s, &mut actions, &mut changed), + 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(); + }); + } + }); + }); + 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 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| { + if ui + .button("🗑") + .on_hover_text(tr("Remove from list")) + .clicked() + { + remove = Some(i); + } + }); + }); + ui.label( + RichText::new(s.engines[i].path.display().to_string()) + .small() + .weak(), + ); + }); + } + 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); + } + ui.add_space(6.0); + ui.horizontal(|ui| { + if ui + .add_enabled( + !self.checking_engine, + egui::Button::new(tr("+ Add engine…")), + ) + .clicked() + { + actions.push(SettingsAction::AddEngine); + } + if self.checking_engine { + ui.spinner(); + ui.label(tr("Checking engine…")); + } + }); + } +} + +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); + ui.label(RichText::new(tr("Board")).strong()); + 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); + *changed |= ui + .checkbox(&mut s.show_coords, tr("Show coordinates")) + .changed(); + *changed |= ui + .checkbox(&mut s.show_best_arrow, tr("Show engine best-move arrows")) + .changed(); +} + +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); + } + }); + }); +} diff --git a/apps/desktop/src/sound.rs b/apps/desktop/src/sound.rs new file mode 100644 index 0000000..cb10a76 --- /dev/null +++ b/apps/desktop/src/sound.rs @@ -0,0 +1,52 @@ +//! Sound playback on a dedicated thread; missing audio devices are tolerated silently. + +use std::io::Cursor; +use std::sync::mpsc::{Sender, channel}; + +use crate::assets::{Sound, SoundSet, sound_bytes}; + +pub struct SoundPlayer { + tx: Option>, +} + +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)); + } + } +} diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs new file mode 100644 index 0000000..1b84c91 --- /dev/null +++ b/apps/desktop/src/widgets.rs @@ -0,0 +1,26 @@ +//! Small shared widgets. + +use crate::i18n::tr; +use egui::{Color32, Sense, Stroke, Ui, vec2}; + +/// Window close button (the app runs undecorated under tiling compositors). +pub fn close_button(ui: &mut Ui) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(vec2(32.0, 28.0), 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 d = 6.0; + 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.on_hover_text(tr("Close the application")) +} diff --git a/crates/chess-core/Cargo.toml b/crates/chess-core/Cargo.toml new file mode 100644 index 0000000..2f0293e --- /dev/null +++ b/crates/chess-core/Cargo.toml @@ -0,0 +1,16 @@ +[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 + +[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..2d127fa --- /dev/null +++ b/crates/chess-core/src/comment.rs @@ -0,0 +1,172 @@ +//! 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 { + 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(), + } +} + +#[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()) + ] + ); + } +} diff --git a/crates/chess-core/src/database.rs b/crates/chess-core/src/database.rs new file mode 100644 index 0000000..984019c --- /dev/null +++ b/crates/chess-core/src/database.rs @@ -0,0 +1,337 @@ +//! A read-only PGN source: original bytes, encoding, index and lazy parsing. +//! +//! The source file is only read, never written. Saving is a separate explicit +//! operation of the application (write a new file from `Game::to_pgn`). + +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 + } +} + +/// 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, + }; + let bytes = std::fs::read(path).map_err(io_err)?; + let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok(); + 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, + }) + } + + pub fn path(&self) -> Option<&Path> { + self.path.as_deref() + } + + pub fn entries(&self) -> &[GameEntry] { + &self.entries + } + + 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::*; + + 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..786c68a --- /dev/null +++ b/crates/chess-core/src/diagnostic.rs @@ -0,0 +1,86 @@ +//! 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, +} + +/// 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..e3049a9 --- /dev/null +++ b/crates/chess-core/src/edit.rs @@ -0,0 +1,429 @@ +//! 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}; + +#[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, + }, +} + +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, + }, + } + } + + /// 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) + } + } + } +} + +#[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(()) + } + + 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). + fn record(&mut self, cmd: Command) { + if !matches!(cmd, Command::Attach { .. }) { + self.apply(&cmd); + } + 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::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); + } + } + } + } + + 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) + ); + } +} diff --git a/crates/chess-core/src/encoding.rs b/crates/chess-core/src/encoding.rs new file mode 100644 index 0000000..bc06a00 --- /dev/null +++ b/crates/chess-core/src/encoding.rs @@ -0,0 +1,220 @@ +//! 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. +#[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. +#[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`]. +#[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..98ca3f6 --- /dev/null +++ b/crates/chess-core/src/game.rs @@ -0,0 +1,630 @@ +//! 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, +} + +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, + } + } + + 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()) + } + + /// 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()); + } + + // ----- 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() + } + + /// 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()) + } + + 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..e7da93c --- /dev/null +++ b/crates/chess-core/src/lib.rs @@ -0,0 +1,32 @@ +//! 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 pgn; +pub mod repair; +pub mod start; + +pub use comment::{Annotation, CommentPart, ShapeColor, parse_comment}; +pub use database::{OpenError, PgnDatabase, SourceFingerprint}; +pub use diagnostic::{Diagnostic, DiagnosticCode, Severity, SourceLocation}; +pub use edit::{EditError, EditOutcome}; +pub use encoding::{Confidence, EncodingGuess, TextEncoding, detect_encoding}; +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/pgn/lexer.rs b/crates/chess-core/src/pgn/lexer.rs new file mode 100644 index 0000000..9cd166c --- /dev/null +++ b/crates/chess-core/src/pgn/lexer.rs @@ -0,0 +1,371 @@ +//! 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(); + } + } + + /// 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..8d9b59a --- /dev/null +++ b/crates/chess-core/src/pgn/mod.rs @@ -0,0 +1,28 @@ +//! PGN import (scan + lazy parse) and export. + +mod lexer; +pub mod parse; +pub mod scan; +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..d176b1e --- /dev/null +++ b/crates/chess-core/src/pgn/scan.rs @@ -0,0 +1,307 @@ +//! 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. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct EntryFlags { + pub has_fen: bool, + pub has_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. +#[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, +} + +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") + } + 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(), + }); + 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; + if !terminated { + entry.flags.has_structure_issues = true; + } + } + TokKind::LineComment => { + movetext_tokens += 1; + entry.flags.has_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; + } + } + } + } + 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) +} + +#[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 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/write.rs b/crates/chess-core/src/pgn/write.rs new file mode 100644 index 0000000..4faf152 --- /dev/null +++ b/crates/chess-core/src/pgn/write.rs @@ -0,0 +1,226 @@ +//! 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; + } + let words: Vec<&str> = text.split_whitespace().collect(); + match words.as_slice() { + [] => self.token("{}"), + [one] => self.token(&format!("{{{one}}}")), + [first, middle @ .., last] => { + self.token(&format!("{{{first}")); + for w in middle { + self.token(w); + } + self.token(&format!("{last}}}")); + } + } + } +} + +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..d095cb3 --- /dev/null +++ b/crates/chess-core/src/repair.rs @@ -0,0 +1,227 @@ +//! 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. +#[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(); + } + let (text, _) = encoding.decode(bytes); + let genuine_letters = text + .chars() + .filter(|c| matches!(c, 'ч' | 'Ч' | 'ю' | 'Ю')) + .count(); + let chars: Vec = text.chars().collect(); + let is_cyr = + |c: Option<&char>| c.is_some_and(|c| matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё')); + let mut sequences = 0usize; + let mut i = 0; + while i + 1 < chars.len() { + let pair = [chars[i], chars[i + 1]]; + if TABLE + .iter() + .any(|(s, _)| s.chars().eq(pair.iter().copied())) + { + let before = i.checked_sub(1).and_then(|p| chars.get(p)); + let after = chars.get(i + 2); + if is_cyr(before) || is_cyr(after) { + sequences += 1; + } + i += 2; + } else { + i += 1; + } + } + let markers = chars.iter().filter(|c| matches!(c, '~' | '^')).count(); + // Each `~~` has two markers, each `x^` one; `><` has none. + let detected = sequences >= MIN_SEQUENCES + && genuine_letters * 50 < sequences + && markers * 9 <= sequence_markers(&chars) * 10; + LetterRepairDetection { + detected, + sequences, + genuine_letters, + } +} + +fn sequence_markers(chars: &[char]) -> usize { + let mut n = 0; + let mut i = 0; + while i + 1 < chars.len() { + match (chars[i], chars[i + 1]) { + ('~', '~') => { + n += 2; + i += 2; + } + ('o' | 'о' | 'O' | 'О', '^') => { + n += 1; + i += 2; + } + _ => i += 1, + } + } + 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..9b8f8c2 --- /dev/null +++ b/crates/chess-core/tests/pgn_fixtures.rs @@ -0,0 +1,425 @@ +//! 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()] + ); +} diff --git a/crates/uci/Cargo.toml b/crates/uci/Cargo.toml new file mode 100644 index 0000000..d78642d --- /dev/null +++ b/crates/uci/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "uci" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "UCI chess engine process supervisor (no UI dependencies)" + +[dependencies] +thiserror.workspace = true + +# 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 diff --git a/crates/uci/src/bin/fake_uci.rs b/crates/uci/src/bin/fake_uci.rs new file mode 100644 index 0000000..9347e5d --- /dev/null +++ b/crates/uci/src/bin/fake_uci.rs @@ -0,0 +1,306 @@ +//! 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) +//! +//! 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, +} + +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, + other => { + eprintln!("fake_uci: unknown flag {other}"); + std::process::exit(2); + } + } + } + c +} + +struct Search { + marker: String, + depth: u32, + max_depth: Option, +} + +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) { + 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) + }; + 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; + 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); + 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"); + } + } + 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 cfg.exit_after_go == Some(gos) { + info_lines(&cfg, &marker, 1, multipv); + 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()); + search = Some(Search { + marker: marker.clone(), + depth: 0, + max_depth, + }); + } + 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); + } + 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); + } + } + 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/engine.rs b/crates/uci/src/engine.rs new file mode 100644 index 0000000..a9e5291 --- /dev/null +++ b/crates/uci/src/engine.rs @@ -0,0 +1,934 @@ +//! Engine process, handshake and the supervisor thread. + +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::parse::{EngineLine, parse_line}; +use crate::types::{ + EngineInfo, EnginePosition, OptionKind, SearchId, SearchInfo, SearchLimits, Timeouts, +}; + +/// Callback invoked (from the supervisor thread) after every new event; the +/// UI passes `ctx.request_repaint()` here. +pub type Waker = Box; + +/// Maximum stored length of one output line; longer lines are truncated. +const MAX_LINE_BYTES: usize = 64 * 1024; +/// Number of stderr lines kept for diagnostics. +const STDERR_TAIL_LINES: usize = 256; +/// Maximum number of `Warning` events emitted per engine (flood protection). +const MAX_WARNINGS: usize = 100; + +/// Event delivered to the UI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EngineEvent { + /// `position` + `go` for this id were sent to the engine. + SearchStarted { search_id: SearchId }, + /// The request was replaced by a newer one (or cancelled by `stop`) + /// before it was sent to the engine; no events will follow for this id. + Superseded { search_id: SearchId }, + /// Search output. Only lines with a score or a PV are forwarded. + Info { + search_id: SearchId, + info: SearchInfo, + }, + /// Final `bestmove` of a started search. Exactly one per `SearchStarted` + /// unless the engine terminates first. + BestMove { + search_id: SearchId, + best: Option, + ponder: Option, + }, + /// `info string`, attributed to the running search if any. + InfoString { + search_id: Option, + text: String, + }, + /// Malformed or unexpected engine output; the line was skipped. + Warning(String), + /// The supervisor has stopped; the handle is no longer usable. + Terminated(TerminationReason), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TerminationReason { + /// `quit()` or drop of the handle. + Quit { status: Option }, + /// The process exited on its own (crash, EOF on stdout, write failure). + Exited { status: Option }, + /// The engine did not answer `stop` or `isready` in time and was killed. + Hung { waiting_for: &'static str }, +} + +/// Spawn configuration. +#[derive(Debug, Clone)] +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, +} + +impl EngineConfig { + pub fn new(path: impl Into) -> Self { + EngineConfig { + path: path.into(), + args: Vec::new(), + working_dir: None, + timeouts: Timeouts::default(), + } + } +} + +/// 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), + Stdout(String), + StdoutClosed, +} + +enum Cmd { + Search { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + }, + Stop, + /// A complete `setoption ...` / `ucinewgame` line, applied while idle. + Setup(String), + Quit, +} + +/// Handle owned by the UI. Dropping it quits (and if needed kills) the engine. +pub struct EngineHandle { + info: EngineInfo, + 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> { + position.validate()?; + self.send(Cmd::Search { + position, + id: search_id, + limits, + }) + } + + /// 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> { + let opt = self + .info + .option(name) + .ok_or_else(|| EngineError::UnknownOption(name.to_string()))?; + let bad = |reason: String| EngineError::InvalidOptionValue { + name: opt.name.clone(), + reason, + }; + if let Some(v) = value + && v.chars().any(char::is_control) + { + return Err(bad("control characters in value".into())); + } + let value = match (&opt.kind, value) { + (OptionKind::Button, None) => None, + (OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())), + (_, None) => return Err(bad("value required".into())), + (OptionKind::Check { .. }, Some(v)) => match v { + "true" | "false" => Some(v.to_string()), + _ => return Err(bad(format!("expected true/false, got {v:?}"))), + }, + (OptionKind::Spin { min, max, .. }, Some(v)) => { + let n: i64 = v + .trim() + .parse() + .map_err(|_| bad(format!("not an integer: {v:?}")))?; + if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) { + return Err(bad(format!("{n} outside {min:?}..={max:?}"))); + } + Some(n.to_string()) + } + (OptionKind::Combo { vars, .. }, Some(v)) => { + let var = vars + .iter() + .find(|x| x.eq_ignore_ascii_case(v)) + .ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?; + Some(var.clone()) + } + (OptionKind::String { .. }, Some(v)) => Some(v.to_string()), + }; + let line = match value { + Some(v) => format!("setoption name {} value {}", opt.name, v), + None => format!("setoption name {}", opt.name), + }; + self.send(Cmd::Setup(line)) + } + + pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { + 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::Cmd(Cmd::Quit)); + // The supervisor bounds its own shutdown by stop+quit timeouts; + // the margin covers scheduling. If it is still stuck (e.g. a + // blocked write), kill the process from here. + 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) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if let Some(dir) = workdir { + command.current_dir(dir); + } + #[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 mut warnings = Vec::new(); + let handshake = handshake(&mut stdin, &rx, &cfg.timeouts, &mut warnings); + let info = match handshake { + Ok(info) => info, + Err(mut e) => { + let _ = child.kill(); + let status = child.wait().ok(); + 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 { + stdin, + child: Arc::clone(&child), + events: ev_tx, + waker, + alive: Arc::clone(&alive), + timeouts: cfg.timeouts, + state: State::Idle, + pending: None, + pending_setup: Vec::new(), + warnings: 0, + }; + for w in warnings { + sup.warn(w); + } + 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() +} + +fn handshake( + stdin: &mut ChildStdin, + rx: &Receiver, + t: &Timeouts, + warnings: &mut Vec, +) -> Result { + 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) + } + }; + write_line(stdin, "uci").map_err(io)?; + let mut info = EngineInfo::default(); + let mut seen_uci = false; + let mut output = Vec::new(); + let deadline = Instant::now() + t.uciok; + loop { + let line = match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + Ok(Input::Stdout(l)) => l, + Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), + Ok(Input::Cmd(_)) => continue, + Err(RecvTimeoutError::Timeout) => { + return Err(if seen_uci { + EngineError::HandshakeTimeout { + waiting_for: "uciok", + } + } else { + EngineError::NotUci { output } + }); + } + }; + if output.len() < 20 { + output.push(line.clone()); + } + match parse_line(&line) { + Ok(EngineLine::IdName(n)) => { + seen_uci = true; + info.name = Some(n); + } + Ok(EngineLine::IdAuthor(a)) => { + seen_uci = true; + info.author = Some(a); + } + Ok(EngineLine::Option(o)) => { + seen_uci = true; + info.options.push(o); + } + Ok(EngineLine::UciOk) => break, + Ok(_) => {} + Err(e) => { + if line.starts_with("option") { + seen_uci = true; + } + warnings.push(format!("handshake: {e}")); + } + } + } + write_line(stdin, "isready").map_err(io)?; + let deadline = Instant::now() + t.readyok; + loop { + match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + Ok(Input::Stdout(l)) => { + if matches!(parse_line(&l), Ok(EngineLine::ReadyOk)) { + return Ok(info); + } + } + Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), + Ok(Input::Cmd(_)) => {} + Err(RecvTimeoutError::Timeout) => { + return Err(EngineError::HandshakeTimeout { + waiting_for: "readyok", + }); + } + } + } +} + +/// 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; + } + } +} + +/// Supervisor state. Invariant: `position`/`go` is only written in +/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a +/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` +/// belongs to the current search, and `info` read while `Idle`/`Syncing` is +/// stale and dropped. +#[derive(Debug, Clone, Copy)] +enum State { + /// No search running, nothing pending. + Idle, + /// `isready` sent before starting the pending search; waiting `readyok`. + Syncing { + deadline: Instant, + }, + Searching { + id: SearchId, + }, + /// `stop` sent; waiting for the final `bestmove` of `id`. + Stopping { + id: SearchId, + deadline: Instant, + }, +} + +impl State { + fn deadline(self) -> Option { + match self { + State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), + _ => None, + } + } +} + +struct PendingSearch { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, +} + +struct Supervisor { + stdin: ChildStdin, + child: Arc>, + events: Sender, + waker: Waker, + alive: Arc, + timeouts: Timeouts, + state: State, + pending: Option, + pending_setup: Vec, + warnings: usize, +} + +/// Why the loop must end. +enum Exit { + ProcessGone, + Hung(&'static str), +} + +impl Supervisor { + fn emit(&self, ev: EngineEvent) { + if self.events.send(ev).is_ok() { + (self.waker)(); + } + } + + fn warn(&mut self, msg: String) { + self.warnings += 1; + if self.warnings < MAX_WARNINGS { + self.emit(EngineEvent::Warning(msg)); + } else if self.warnings == MAX_WARNINGS { + self.emit(EngineEvent::Warning( + "too many warnings; further warnings suppressed".into(), + )); + } + } + + fn write(&mut self, line: &str) -> Result<(), Exit> { + write_line(&mut self.stdin, line).map_err(|_| Exit::ProcessGone) + } + + fn run(mut self, rx: Receiver) { + let result = loop { + let msg = match self.state.deadline() { + Some(d) => rx.recv_timeout(d.saturating_duration_since(Instant::now())), + None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected), + }; + let step = match msg { + Ok(Input::Cmd(Cmd::Quit)) | Err(RecvTimeoutError::Disconnected) => { + self.quit(); + return; + } + Ok(Input::Cmd(cmd)) => self.on_cmd(cmd), + Ok(Input::Stdout(line)) => self.on_line(&line), + Ok(Input::StdoutClosed) => Err(Exit::ProcessGone), + Err(RecvTimeoutError::Timeout) => match self.state { + State::Syncing { deadline } if Instant::now() >= deadline => { + Err(Exit::Hung("readyok")) + } + State::Stopping { deadline, .. } if Instant::now() >= deadline => { + Err(Exit::Hung("bestmove")) + } + _ => Ok(()), + }, + }; + if let Err(e) = step { + break e; + } + }; + 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::ProcessGone => TerminationReason::Exited { + status: self.reap(Duration::from_millis(500)), + }, + }; + self.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); + if matches!(self.state, State::Searching { .. }) { + let _ = self.write("stop"); + } + let _ = self.write("quit"); + let status = self.reap(self.timeouts.quit); + self.emit(EngineEvent::Terminated(TerminationReason::Quit { status })); + } + + fn on_cmd(&mut self, cmd: Cmd) -> Result<(), Exit> { + match cmd { + Cmd::Search { + position, + id, + limits, + } => { + if let Some(old) = self.pending.replace(PendingSearch { + position, + id, + limits, + }) { + self.emit(EngineEvent::Superseded { search_id: old.id }); + } + match self.state { + State::Idle => self.begin_sync()?, + State::Searching { id } => self.send_stop(id)?, + State::Syncing { .. } | State::Stopping { .. } => {} + } + } + Cmd::Stop => { + if let Some(old) = self.pending.take() { + self.emit(EngineEvent::Superseded { search_id: old.id }); + } + if let State::Searching { id } = self.state { + self.send_stop(id)?; + } + } + Cmd::Setup(line) => match self.state { + // The engine is not searching: safe to send right away; the + // `isready` before the next `go` fences it. + State::Idle | State::Syncing { .. } => self.write(&line)?, + State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), + }, + Cmd::Quit => unreachable!("handled in run"), + } + Ok(()) + } + + fn send_stop(&mut self, id: SearchId) -> Result<(), Exit> { + self.write("stop")?; + self.state = State::Stopping { + id, + deadline: Instant::now() + self.timeouts.stop, + }; + Ok(()) + } + + /// Engine is idle: flush queued setup, then `isready` if a search waits. + fn begin_sync(&mut self) -> Result<(), Exit> { + for line in std::mem::take(&mut self.pending_setup) { + self.write(&line)?; + } + if self.pending.is_some() { + self.write("isready")?; + self.state = State::Syncing { + deadline: Instant::now() + self.timeouts.readyok, + }; + } else { + self.state = State::Idle; + } + Ok(()) + } + + fn current_search(&self) -> Option { + match self.state { + State::Searching { id } | State::Stopping { id, .. } => Some(id), + _ => None, + } + } + + fn on_line(&mut self, line: &str) -> Result<(), Exit> { + let parsed = match parse_line(line) { + Ok(p) => p, + Err(e) => { + self.warn(e.to_string()); + return Ok(()); + } + }; + match parsed { + EngineLine::Info(info) => { + if let Some(id) = self.current_search() + && (info.score.is_some() || !info.pv.is_empty()) + { + self.emit(EngineEvent::Info { + search_id: id, + info, + }); + } + // Otherwise: stale output of a finished search, dropped. + } + EngineLine::InfoString(text) => { + let search_id = self.current_search(); + self.emit(EngineEvent::InfoString { search_id, text }); + } + EngineLine::BestMove { best, ponder } => match self.current_search() { + Some(id) => { + self.emit(EngineEvent::BestMove { + search_id: id, + best, + ponder, + }); + self.state = State::Idle; + self.begin_sync()?; + } + None => self.warn(format!("unexpected bestmove ignored: {line:?}")), + }, + EngineLine::ReadyOk => { + if let State::Syncing { .. } = self.state { + match self.pending.take() { + Some(p) => { + self.write(&p.position.to_command())?; + self.write(&p.limits.to_command())?; + self.state = State::Searching { id: p.id }; + self.emit(EngineEvent::SearchStarted { search_id: p.id }); + } + None => self.state = State::Idle, + } + } + } + EngineLine::Empty => {} + EngineLine::UciOk + | EngineLine::IdName(_) + | EngineLine::IdAuthor(_) + | EngineLine::Option(_) + | EngineLine::Unknown(_) => { + self.warn(format!("unexpected engine output: {line:?}")); + } + } + Ok(()) + } +} diff --git a/crates/uci/src/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/lib.rs b/crates/uci/src/lib.rs new file mode 100644 index 0000000..b8c8a06 --- /dev/null +++ b/crates/uci/src/lib.rs @@ -0,0 +1,27 @@ +//! UCI engine process supervisor. +//! +//! The engine runs as a separate child process started without a shell. +//! stdout and stderr are read by two dedicated threads; a supervisor thread +//! owns the protocol state machine. The UI talks to it through the +//! non-blocking [`EngineHandle`] and polls [`EngineEvent`]s every frame; the +//! [`Waker`] callback is invoked after each new event. +//! +//! Search boundary: UCI has no request ids. A new `position`/`go` is written +//! only after the previous search ended with `bestmove` and a subsequent +//! `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 engine; +mod error; +pub mod parse; +mod types; + +pub use engine::{Engine, EngineConfig, EngineEvent, EngineHandle, TerminationReason, Waker}; +pub use error::EngineError; +pub use types::{ + EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score, + ScoreBound, SearchId, SearchInfo, SearchLimits, Side, Timeouts, WhiteEval, WhiteScore, +}; 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/types.rs b/crates/uci/src/types.rs new file mode 100644 index 0000000..72c4fc2 --- /dev/null +++ b/crates/uci/src/types.rs @@ -0,0 +1,416 @@ +//! 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(()) + } + + pub(crate) fn to_command(&self) -> String { + let mut s = match &self.base { + PositionBase::StartPos => "position startpos".to_string(), + PositionBase::Fen(fen) => format!("position fen {}", fen.trim()), + }; + if !self.moves.is_empty() { + s.push_str(" moves"); + for m in &self.moves { + s.push(' '); + s.push_str(m); + } + } + s + } +} + +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 { + pub(crate) 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/tests/fake_engine.rs b/crates/uci/tests/fake_engine.rs new file mode 100644 index 0000000..a8681b6 --- /dev/null +++ b/crates/uci/tests/fake_engine.rs @@ -0,0 +1,646 @@ +//! Supervisor tests against the deterministic fake engine (src/bin/fake_uci.rs). + +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()); +} diff --git a/crates/uci/tests/stockfish.rs b/crates/uci/tests/stockfish.rs new file mode 100644 index 0000000..ba5e068 --- /dev/null +++ b/crates/uci/tests/stockfish.rs @@ -0,0 +1,178 @@ +//! Integration test with a real Stockfish binary. Ignored by default. +//! +//! Run: UCI_STOCKFISH=/path/to/stockfish cargo test -p uci --test stockfish -- --ignored + +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/docs/agent-team.md b/docs/agent-team.md new file mode 100644 index 0000000..82872cf --- /dev/null +++ b/docs/agent-team.md @@ -0,0 +1,42 @@ +# Команда 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 diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..406528e --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,118 @@ +# Архитектурное предложение + +Дата: 2026-10-17. Статус: **рекомендация для согласования**, приложение ещё не реализовано. + +## Краткое решение + +Предлагаем **нативное Linux-приложение на Rust + egui/eframe + wgpu**, по стеку PhotoCraft, с независимым шахматным ядром, PGN-документом и управлением внешними UCI-движками. Для первой версии — одно окно, библиотека и рабочее пространство партии, один активный движок с несколькими линиями анализа. + +Пользователь уже подтвердил открытый исходный код, учебные базы на сотни/тысячи партий и ввод ходов/вариантов с экспортом. Точная фиксация решений — `decisions.md`. + +## Почему этот стек + +1. Соответствует прямому пожеланию использовать технологии PhotoCraft: в его desktop manifest явно включены eframe, egui, wgpu, Wayland/X11 и AccessKit. +2. Rust обслуживает и интерфейс, и PGN, и процессы движков; не нужен отдельный frontend-язык. +3. Рисование доски и стрелок, таблица и изменяемые панели укладываются в egui. Для нотации потребуется специализированный компонент. +4. `storytold/craft-libs` предлагает действительно общие компоненты: `craft-ui`, `craft-settings`, `craft-atomic`. Их можно подключать выборочно, на фиксированной ревизии, через тонкий адаптер. +5. В согласованную первую версию не входит полноценное редактирование rich text и миллионов записей, что уменьшает основные риски egui. + +Оговорка: PhotoCraft в каталоге отмечен early alpha; общие библиотеки не являются гарантированно стабильным SDK. Качество будущего приложения проверяется своим прототипом и тестами. + +| Вариант | Оценка | +| --- | --- | +| **Rust + egui/eframe** | Основная рекомендация; доску и нотацию делаем под наши сценарии | +| Tauri 2 + React/TypeScript | Резерв при существенных проблемах текстового UI/доступности; можно использовать Chessground, но появляются webview и второй стек | +| GTK4/Relm4 | Сильная Linux-интеграция; меньше соответствия выбранному PhotoCraft-стеку, шахматные компоненты также собственные | + +Важно: другие продукты организации ArtCraft используют и Tauri/React. Утверждение о egui относится конкретно к PhotoCraft/native Craft Apps, а не ко всем репозиториям организации. + +## Состав компонентов + +| Область | Рекомендуемый компонент | Наша работа | +| --- | --- | --- | +| UI и окно | egui + eframe + wgpu, egui_extras | Экраны, доска, нотация, варианты, клавиатура | +| Общие UI-примитивы | craft-ui выборочно | Визуальная система и компоненты шахматного продукта | +| Правила шахмат | shakmaty | Связь ходов, узлов документа, истории и интерфейса | +| Чтение PGN | pgn-reader | Visitor, дерево, совместимость старых файлов, диагностика | +| Экспорт PGN | Собственный writer | Сохранение тегов, комментариев, NAG и вариантов | +| Legacy-кодировки | encoding_rs как кандидат | Выбор кодировки, сохранение оригинала и диагностик; версию/API проверить на прототипе | +| UCI | Tokio process + vampirc-uci как кандидат | Управление процессом, поисками, таймаутами и MultiPV | +| Библиотека | Метаданные в памяти в прототипе; rusqlite для постоянного индекса | Каталог файлов, поиск, инвалидирование кэша, фоновый импорт | +| Настройки | craft-settings как кандидат | Собственная схема настроек и миграции | +| Файловые диалоги | rfd | Обработка отмены и ошибок | +| Clipboard | eframe API / arboard при необходимости | Копирование PGN и проверка на Wayland | +| Звук | rodio | Предзагрузка коротких звуков, mute/volume, устойчивость к отсутствию аудио | + +Версии согласовать как комплект. В проверенном PhotoCraft/craft-ui используется линия egui **0.36**; нельзя механически смешивать её с новой несовместимой версией egui_extras. Зафиксировать toolchain, git revisions и Cargo.lock после пробной сборки. Проверенный текущий workspace shakmaty требует более новый Rust, чем PhotoCraft; подробности и SHA — в `research/stack-options.md`. + +Предложение лицензии проекта — **GPL-3.0-or-later**, поскольку shakmaty и pgn-reader имеют эту лицензию. Конкретная лицензия ещё требует подтверждения. Для фигур и звука вести отдельный список происхождения и лицензий; подбор — `research/reuse-and-assets.md`. + +## Границы модулей + +```text +desktop UI + ├── LibraryState: выбранная база, поиск, строка, прокрутка + ├── DocumentView: активный узел, раскрытые ветки, ориентация + └── AnalysisPreview: снимок PV и точка возврата + │ команды / события + ▼ +application + ├── GameDocument + команды Undo/Redo + ├── PGN import/export + диагностика + ├── Library repository + настройки + └── UCI supervisor → отдельный engine process + │ + ▼ +shakmaty: правила, позиции, SAN/UCI/FEN +``` + +Это границы ответственности, а не требование сразу заводить множество crates. Для первого среза достаточно компактного workspace с библиотекой ядра и desktop-приложением; `pgn`, `library`, `uci`, `platform`, `ui` могут начинаться как модули. Выносить отдельно по фактическим границам зависимостей и тестирования. + +### Документ и PGN + +- Документ хранит упорядоченные теги, корневую позицию, дерево со стабильными ID, комментарии, NAG, неизвестные аннотации и результат. +- У узла один родитель и упорядоченные продолжения; первое — основное. Альтернативы начинаются от позиции до заменяемого хода. +- Активный узел и раскрытие вариантов — состояние представления, не изменение документа. +- Исходные байты/фрагменты и информация о кодировке сохраняются отдельно от нормализованной шахматной модели. Не обещать побайтовую идентичность после редактирования. +- PGN reader сам не строит дерево, не проверяет легальность и по умолчанию может пропускать варианты: visitor должен явно обрабатывать их. +- В текущих материалах найдены не-UTF-8 тексты, учебный `--` и FEN с fullmove=0. Нужен отдельный слой совместимости. Нормализацию не выдавать за оригинал; непонятные фрагменты не отбрасывать молча. +- Полный независимый аудит подтвердил 896 записей, 62 263 узла, вложенность RAV до 7, 846 FEN и 269 учебных null moves. В записи №335 учебника повреждены границы комментария: контрольный парсер теряет фрагмент текста без ошибки. Проверка покрытия исходного текста обязательна; успешный разбор сам по себе недостаточен. +- В первой версии сохраняем отдельную партию через «Сохранить как…». Исходная многопартийная база остаётся источником, а не объектом неявной перезаписи. + +### Анализ и предпросмотр + +- UCI работает в отдельном процессе; CPU/IO не блокируют UI. stdout и stderr читаются независимо. +- На смене позиции остановить старый поиск и дождаться его `bestmove`, затем запустить новый. `readyok` и локальный request ID сами по себе не отделяют поиски. +- Для обычной ветви отправлять начальную позицию и историю ходов; текущий FEN не заменяет историю повторений. +- Учебные null moves обрабатываются отдельно; синтетическую учебную историю не выдавать движку за обычную партию. +- Отображаемая оценка относительно белых, независимо от переворота доски. Мат хранить отдельно от centipawns. +- Клик по PV открывает зафиксированный снимок с явной меткой «Предпросмотр». Выход восстанавливает узел партии. Только команда «Добавить линию как вариант» изменяет документ и Undo-историю. + +## Интерфейс первой версии + +**Библиотека:** сверху компактная полка баз и «Добавить PGN», ниже поиск и таблица партий. **Партия:** слева крупная доска, справа анализ и нотация с комментариями; регулируемые панели. «Назад в библиотеку» восстанавливает выбранную базу и строку. + +Предлагаемые defaults для прототипа: русский UI, спокойная тёмная тема с возможностью светлой, один клик выбирает строку, двойной клик/Enter открывает партию. Эти детали не считаются уже утверждёнными пользователем. Макеты и состояния — `research/ux-direction.md`; расширенные редакторские команды из этого исследования отложены согласно `decisions.md`. + +## Следующий шаг и критерий выбора + +После согласования стека — технический прототип: окно на Hyprland/Wayland, SVG-доска, таблица реального PGN, кликабельные вложенные варианты, длинный русский комментарий, клавиатура и clipboard. Одновременно проверить парсер на учебных расширениях корпуса. Этот шаг проверяет самые дорогие предположения; остальная последовательность — `implementation-plan.md`. + +Если UI-прототип проходит, фиксируем стек и реализуем полный первый сценарий. Если проблема именно в нотации/доступности/платформенной интеграции и её устранение непропорционально, возвращаемся к сравнению с Tauri до наращивания UI. + +## Фактическое состояние окружения + +- После первоначального обследования пользователь установил Rust: подтверждены rustc/cargo **1.99.1**, rustup **1.29.1**. В PATH текущего процесса инструменты пока не появились; доступны по `~/.cargo/bin/`. Для будущих команд использовать полный путь или локально дополнить PATH. +- Пользователь завершил загрузку `engines/stockfish-linux-x86-64-universal.tar.gz`. SHA-256 и размер совпадают с официальным release asset **Stockfish 19**. Успешно проверены `uci`, `isready`, поиск глубины 4 и `quit` (exit 0). Бинарник временно извлечён для проверки и затем удалён; исходный архив сохранён. +- Linux: Omarchy / Hyprland / Wayland. GUI-прототип и продуктовые тесты пока не запускались. +- Пять профилей OpenCode созданы и обнаружены API без перезапуска; сведения — `agent-team.md`. + +## Материалы исследования + +- `research/requirements-and-pgn.md` — требования и фактическая структура обоих PGN. +- `research/ux-direction.md` — разбор семи скриншотов и UX-предложение. +- `research/stack-options.md` — первоисточники, версии, SHA, лицензии и сравнение стеков. +- `research/quality-plan.md` — обследование окружения и план проверок. +- `research/reuse-and-assets.md` — Lichess, фигуры и звук. + +Ключевые upstream: https://github.com/storytold/photocraft, https://github.com/storytold/craft-libs, https://github.com/niklasf/shakmaty. diff --git a/docs/decisions.md b/docs/decisions.md new file mode 100644 index 0000000..ed3f6a3 --- /dev/null +++ b/docs/decisions.md @@ -0,0 +1,33 @@ +# Решения и открытые вопросы + +## Подтверждено пользователем — 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. + +## Следует из исходного ТЗ + +- Linux desktop; предпочтение стека Artcraft, подлежащего проверке по исходникам. +- PGN-библиотека с ранее открытыми файлами, добавлением новых и таблицей партий. +- Доска с навигацией мышью/клавиатурой, комментариями и вариантами. +- Новая партия из начальной позиции. +- Выбор UCI-движков из файловой системы, анализ, просмотр линий на доске и стрелка лучшего хода. +- Возвращение из партии в библиотеку. +- Настройки фигур, доски, движков и звуков. + +## Предложения, требующие согласования + +- Русский интерфейс по умолчанию с архитектурой для последующего английского перевода. +- Компоновка одного окна: библиотека и рабочее место партии с сохранением контекста. +- Сначала небольшой проверочный прототип сложных UI-компонентов, затем первая рабочая версия. + +Рекомендации и технические аргументы находятся в `architecture.md` и `research/`. При изменении объёма обновлять этот файл, чтобы старые исследования не трактовались как актуальное решение пользователя. diff --git a/docs/dev/chess-core.md b/docs/dev/chess-core.md new file mode 100644 index 0000000..bf5b655 --- /dev/null +++ b/docs/dev/chess-core.md @@ -0,0 +1,165 @@ +# chess-core: API и политика совместимости PGN + +Статус: первая реализация ядра, 2026-10-17. Без зависимостей от UI. Зависимости: shakmaty 0.30.2 (правила, SAN/UCI/FEN), encoding_rs 0.8 (legacy-кодировки), thiserror 2. pgn-reader 0.29.1 подключён только как dev-dependency: это независимый эталон в корпусном тесте (сверка числа ходов основной линии). + +**Почему не pgn-reader в основном пути.** Проверено по исходникам 0.29.1 (`src/reader.rs`): нераспознанные токены пропускаются без вызова visitor (`skip_token`), байтовые смещения не передаются, `%`-строки игнорируются молча. С ним нельзя проверить покрытие исходного текста и диагностировать запись №335. Поэтому в ядре собственный байтовый лексер (`pgn/lexer.rs`): каждый непробельный байт относится ровно к одному токену, нераспознанное возвращается как диагностика и текст. + +## Модули и ключевые типы + +| Модуль | Назначение | +| --- | --- | +| `game` | `Game`, `Node`, `NodeId`, `GameMove`, `MoveKind`, `GameResult`, `EngineHistory`, `HistoryKind` | +| `edit` | добавление ходов и линий, удаление, повышение варианта, Undo/Redo (`EditError`, `EditOutcome`) | +| `start` | `StartPosition` (терпимый FEN), `FenRepair`, `FenError` | +| `pgn` | `scan_games` (индекс), `parse_game`/`parse_str`/`parse_game_range`, `write_game`/`Game::to_pgn` | +| `database` | `PgnDatabase`: исходные байты, кодировка, индекс, ленивый разбор, `SourceFingerprint` | +| `encoding` | `TextEncoding`, `detect_encoding`, `EncodingGuess`, `Confidence` | +| `diagnostic` | `Diagnostic { severity, code, message, location, node }` | +| `comment` | `parse_comment` → текст и команды `[%csl]`, `[%cal]`, прочие `[%…]` | +| `nag` | `Nag(u8)`, символы для отображения | +| `repair` | восстановление букв, заменённых в источнике (`detect_letter_substitution`, `repair_letters`, `LetterRepairDetection`, `LetterRepairCounts`) | + +### Дерево партии + +- Арена узлов, `NodeId::ROOT` — корень (стартовая позиция, без хода). Идентификаторы не переиспользуются. Удалённая ветка лишь отсоединяется (`is_attached() == false`), поэтому Undo/Redo сохраняет ID. +- `Node`: `parent()`, `children()` (первый — главное продолжение), `game_move()`, `position()` (позиция **после** хода, кэшируется в узле), `ply()`, `nags()`, `comments_before()`, `comments_after()`, `unparsed()`. +- Комментарий начала партии хранится в `comments_after()` корня. Комментарий начала варианта — `comments_before()` первого хода варианта. +- `MoveKind::Normal(shakmaty::Move)` | `MoveKind::Null` (учебный `--`). Null move создаётся только импортом и не входит в пользовательский ввод. + +### Запросы и навигация (`impl Game`) + +```rust +fn root(&self) -> NodeId +fn node(&self, id: NodeId) -> Option<&Node> +fn position(&self, id) -> Option<&Chess> // после хода +fn position_before(&self, id) -> Option<&Chess> +fn fen(&self, id) -> Option +fn parent(&self, id) -> Option // «назад» +fn main_child(&self, id) -> Option // «вперёд» +fn children(&self, id) -> &[NodeId]; fn variations(&self, id) -> &[NodeId] +fn next_sibling / prev_sibling(&self, id) -> Option // переключение варианта +fn line_end(&self, id) -> NodeId // «в конец» текущей линии +fn path(&self, id) -> Vec // [ROOT, …, id] +fn mainline(&self) -> Vec +fn is_mainline(&self, id) -> bool; fn variation_start(&self, id) -> Option +fn variation_depth(&self, id) -> usize // для отступов в нотации +fn move_number(&self, id) -> Option<(u32, Color)>; fn move_label(&self, id) -> Option +fn attached_nodes(&self) -> Vec // порядок обхода PGN +fn san_for(&self, id, m: Move) -> Option // SAN для отображения PV +fn engine_history(&self, id) -> Option +fn tags(&self) -> &[(String, String)]; fn tag(&self, name) -> Option<&str> +fn start(&self) -> &StartPosition; fn result(&self) -> GameResult +fn revision(&self) -> u64; fn is_modified(&self) -> bool; fn mark_saved(&mut self) +``` + +`EngineHistory { start_fen: Option, moves: Vec, current_fen, kind }`. `start_fen == None` означает `startpos`. FEN нормализован: fullmove не меньше 1. При `kind == HistoryKind::Complete` передаётся полная история ходов. Если на пути есть `--`, возвращается `HistoryKind::AfterNullMove { null_moves }`: `start_fen` — позиция сразу после последнего null move, `moves` — ходы после него. Более раннюю историю движку не выдаём за обычную партию. `current_fen` — запасной вариант. + +### Редактирование (каждая операция — один шаг Undo) + +```rust +fn add_move(&mut self, at: NodeId, m: Move) -> Result // существующий ход → его узел, без шага Undo +fn add_line(&mut self, at: NodeId, moves: &[Move]) -> Result // вставка PV; сначала проверяется вся линия +fn add_uci_line(&mut self, at: NodeId, moves: &[impl AsRef]) -> Result +fn delete_variation(&mut self, id) -> Result +fn promote_variation(&mut self, id) -> Result<(), EditError> // ветка, содержащая id, становится главной в точке ветвления +fn undo(&mut self) / redo(&mut self) -> Option +fn can_undo / can_redo +Game::new(); Game::from_start(StartPosition); fn set_tag; fn set_result +``` + +Новая ветка добавляется последней среди продолжений. Если продолжений ещё нет, она становится главной. + +### Импорт + +```rust +PgnDatabase::open(path, &mut |p: ScanProgress| …, &AtomicBool) -> Result +PgnDatabase::from_bytes(bytes, Option, progress, cancel) +db.entries() -> &[GameEntry] // index, byte_range, first_line, tags, flags +db.load_game(i) -> Option +db.raw_bytes(i) / db.raw_text(i) // исходная запись без изменений, для «копировать оригинал» +db.set_encoding(enc, progress, cancel); db.detected_encoding(); db.source_changed() +scan_games(bytes, enc, progress, cancel) -> Result, Cancelled> +parse_str(&str) -> ParsedGame // буфер обмена +``` + +`GameEntry` даёт `white()`, `black()`, `white_elo()`, `black_elo()`, `result()`, `date()`, `event()`, `eco()`, `ply_count()`, `tag(name)`. `EntryFlags` содержит признаки: FEN, комментарии, варианты, NAG, null move, структурные проблемы, ошибки декодирования, пустой movetext. `PgnDatabase`, `Game` и `ParsedGame` реализуют `Send + Sync` (проверено тестом). Открытие и сканирование рассчитаны на фоновый поток. Прогресс сообщается примерно каждые 64 KiB, отмена проверяется между токенами. + +Файл только читается. Запись выполняет приложение явным действием: `Game::to_pgn()` в новый файл. + +## Политика совместимости + +| Ситуация | Поведение | Диагностика | +| --- | --- | --- | +| Кодировка | BOM или строгий UTF-8 → UTF-8 (`Certain`). Иначе эвристика (`Likely`): изолированные старшие байты → windows-1252, серии → кириллица; среди cp1251/KOI8-R/IBM866 выбирается вариант с преобладанием строчной кириллицы. Структура разбирается по исходным байтам, смещения указывают на оригинал | `DecodeError` при заменах UTF-8 | +| CRLF | Внутри комментариев и тегов нормализуется в LF | — | +| FEN fullmove=0 | Игровая позиция получает 1, тег FEN сохраняется и экспортируется без изменений | Info `FenFullmoveZero` | +| FEN без SetUp / SetUp без FEN | FEN всё равно используется / берётся стандартная позиция | Info / Warning | +| Неверные права рокировки или поле en passant, невозможный шах, лишний материал | Принимаются с исправлением | Warning `FenRepaired` | +| Непригодный FEN (нет короля, синтаксис) | Movetext целиком сохраняется как raw в `root.unparsed()` и экспортируется дословно | Error `InvalidFen` | +| `--` | `MoveKind::Null`: ход переходит сопернику, en passant сбрасывается, счётчики идут дальше. Под шахом null move невозможен | при шахе Error `IllegalMove` | +| Нелегальный или неоднозначный SAN | Остаток текущей линии до её `)` или конца партии сохраняется дословно в `unparsed()` последнего легального узла. Разбор продолжается со следующей линии | Error `IllegalMove` со строкой | +| Текст вне `{}` (запись №335) | Последовательные нераспознанные слова сохраняются как отдельный комментарий на своём месте | Warning `UnrecognizedText` (строка и узел) | +| Лишняя `}` | Отбрасывается | Warning `StrayClosingBrace` | +| Незакрытый `{` | Комментарий длится до конца записи. Если внутри встречаются пустая строка и строка тега, комментарий обрывается там, чтобы не поглотить следующие партии | Warning `UnterminatedComment` | +| Незакрытые или лишние скобки, пустой вариант, `(` до первого хода | Терпимое закрытие или игнорирование. Вариант до хода сохраняется raw | Warning / Error | +| `;`-комментарий | Обычный комментарий. Экспортируется в `{}`; если текст содержит `}`, используется `;` | — | +| `%`-escape | Игнорируется по стандарту PGN | Info `EscapeLine` (с текстом) | +| `!`, `?!`, `+-`, `=+` и т. п. | Переводятся в NAG; NAG вне диапазона u8 сохраняются как текст | — | +| `0-0`, `1.e4`, `1...Ke7` | Принимаются | — | +| Результат | Сравнивается с тегом Result | Warning `ResultMismatch`, Info `MissingResult` | +| Буквы «ч/Ч/ю», заменённые в источнике на `~~`/`><`/`o^` (учебник Дворецкого) | Восстанавливаются только в тексте комментариев, включая восстановленный текст и payload `[%tqu]`. Теги, raw-фрагменты и исходные байты не меняются. Подробности ниже | Info `LettersRestored` с количеством по партии | +| Комментарий после последнего вложенного варианта без следующего хода | Привязывается к последнему ходу линии; при экспорте меняется место | Info `CommentMoved`; в двух реальных файлах ни одного случая | + +Нормализация при экспорте сделана намеренно: LF, перенос около 80 символов, схлопывание пробелов внутри комментариев, SAN заново строится из хода, NAG записываются как `$n`, номера ходов печатаются после комментариев и вариантов. Теги, их порядок и исходный текст FEN сохраняются. Побайтовую идентичность не обещаем; для оригинала есть `PgnDatabase::raw_text`. Семантический roundtrip проверяется `Game::canonical_tree()`: ходы, NAG, комментарии со схлопнутыми пробелами, raw-фрагменты и структура вариантов. + +## Восстановление заменённых букв + +**Факт по корпусу.** В декодированном учебнике (windows-1251) нет ни одной «ч», «Ч», «ю», «Ю». + +| Последовательность | Вхождений | Буква | +| --- | ---: | --- | +| `~~` | 5 702 | «ч» | +| `><` | 339 | «Ч» | +| `o^` (латинская o) | 2 974 | «ю» | + +Одиночных `~`, `^`, `<`, `>` нет. `О^`, `O^` и кириллическая `о^` в файле не встречаются, но поддержаны. Все вхождения находятся в комментариях; вне `{}` есть только текст повреждённой записи №335. В тегах вхождений нет. + +Прочие буквы с похожими кодами не повреждены: прописные Ъ, Ы, Ь и Ё не встречаются естественно, а у «Ю» в тексте нет даже кандидатов. + +**Правило детекции** (на уровне источника, `detect_letter_substitution`). Срабатывает, только если выполнены все условия: + +1. Кодировка windows-1251, KOI8-R или IBM866. +2. Не меньше 20 последовательностей из таблицы стоят рядом с кириллической буквой. +3. Настоящих «ч/Ч/ю/Ю» меньше 1 на 50 последовательностей. +4. Не меньше 90 % всех `~` и `^` входят в такие последовательности. Поэтому ASCII-графика и настоящие тильды отключают восстановление. + +UTF-8 и windows-1252 не затрагиваются никогда. + +**Замены.** + +| Последовательность | Буква | +| --- | --- | +| `><` | «Ч» | +| `~~` | «ч»; «Ч» в начале комментария или после `.`/`!`/`?` и пробела | +| `o^`, `о^` | «ю» | +| `O^`, `О^` | «Ю» | + +**API.** + +```rust +db.letter_repair() -> &LetterRepairDetection { detected, sequences, genuine_letters } +db.repair_letters_enabled() -> bool // по умолчанию равно detected +db.set_repair_letters(bool) // действует на последующие load_game +parse_game_range_with(bytes, range, line, enc, &ParseOptions { repair_letters }) +repair::repair_letters(&str) -> (String, LetterRepairCounts) +``` + +`set_encoding` повторяет детекцию. Оригинал доступен через `raw_bytes` и `raw_text`. Экспорт записывает восстановленный текст. + +**Результат на учебнике.** Восстановлено 9 015 букв в 819 записях: «ч» 5 614, «Ч» 427 (339 из `><` и 88 из `~~` в начале предложения), «ю» 2 974. В комментариях не осталось ни одной последовательности. Ruy Lopez не затронут: детекция false. + +## Проверка + +`cargo test -p chess-core`: модульные тесты, синтетические фикстуры (`tests/pgn_fixtures.rs`) и корпус (`tests/corpus.rs`; пропускается, если файлов нет). Статистика корпуса: `cargo test -p chess-core --test corpus -- --nocapture`. Разбор одной записи: `cargo run -p chess-core --example pgn_dump -- <номер с 1>`. + +Корпусный тест на двух файлах из `pgnFilesforExample/` получил 896 записей (49 + 847), столько же насчитал pgn-reader. Узлов ходов 62 263 (8 340 + 53 923), null moves 269, NAG 835 + 12 705, блоков комментариев 3 040 + 9 192, а в учебнике ещё один фрагмент, восстановленный из №335. FEN-записей 846, стартов чёрных 268, fullmove=0 72, максимальная глубина вариантов 7. Все эти числа совпали с независимым аудитом. Число ходов основной линии совпало с PlyCount и с pgn-reader во всех записях. Roundtrip без расхождений во всех 896 записях. Исходные файлы после теста побайтно и по mtime не изменились. diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md new file mode 100644 index 0000000..58bcc50 --- /dev/null +++ b/docs/dev/desktop.md @@ -0,0 +1,41 @@ +# Desktop-приложение (`apps/desktop`) + +egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `io.github.vrubelroman.chessPenguin`. + +## Модули + +| Файл | Ответственность | +| --- | --- | +| `app.rs` | Состояние верхнего уровня: библиотека ⇄ партия, настройки, движок, фоновые диалоги (rfd в отдельных потоках), подтверждение закрытия изменённой партии | +| `library.rs` | Полка баз, фоновое сканирование (прогресс, отмена), таблица с поиском, сортировкой, клавиатурой | +| `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура | +| `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках | +| `board.rs` | Виджет доски: клик/drag, превращение, рокировка кликом на поле короля или ладью, стрелки, круги | +| `analysis.rs` | Контроллер анализа поверх `uci`: запуск в фоне, привязка результатов к истории позиции, MultiPV | +| `assets.rs`, `sound.rs` | Встроенные SVG-фигуры, темы доски, звуки (rodio в отдельном потоке) | +| `settings.rs`, `settings_ui.rs` | JSON в `$XDG_CONFIG_HOME/chesspenguin/settings.json` (атомарная запись), окно настроек | + +## Инварианты + +- Анализ привязан к курсору партии, не к предпросмотру. Ключ — стартовая позиция + история ходов UCI; события с чужим `SearchId` отбрасываются. +- Предпросмотр PV — снимок линии; документ меняется только кнопкой «Добавить как вариант» (один шаг Undo). +- Исходный PGN не перезаписывается: только «Сохранить партию как…» в отдельный файл. + +## Клавиатура + +Библиотека: ↑/↓ — строка, Enter — открыть, Ctrl+O — добавить PGN, Ctrl+N — новая партия, Ctrl+F — поиск. +Партия: ←/→ — ход, ↑/↓ — соседний вариант, Home/End, F — перевернуть, L — движок, Esc — выйти из предпросмотра, +Ctrl+Z / Ctrl+Y — отмена/повтор, Ctrl+Shift+C — копировать PGN, Ctrl+S — сохранить как, Ctrl+W — в библиотеку, Ctrl+, — настройки. + +## Dev-хуки запуска (ручная проверка и скриншоты) + +```sh +XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspenguin +``` + +`CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, +`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки, `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. + +## Языки + +`i18n.rs`: английский текст — ключ, таблица на 6 языков (en по умолчанию, ru, fr, de, es, it). Новые строки оборачивать в `tr("…")` / `trf("… {n}", &[("n", &x)])` и добавлять строку в `ROWS`; тест `all_used_keys_are_translated` ловит пропуски. diff --git a/docs/dev/uci.md b/docs/dev/uci.md new file mode 100644 index 0000000..847a2b8 --- /dev/null +++ b/docs/dev/uci.md @@ -0,0 +1,63 @@ +# crate `uci` — супервизор UCI-движка + +Статус: реализовано 2026-10-17, `crates/uci`. Без зависимостей от egui и chess-core; единственная зависимость — `thiserror`. + +## Выбор реализации + +- **std, без tokio.** `std::process::Command` (без shell), два потока чтения (stdout, stderr), поток-супервизор с машиной состояний, `std::sync::mpsc`. UI опрашивает события `try_recv`/`drain_events` в каждом кадре, супервизор после каждого события вызывает `Waker` (`ctx.request_repaint`). Tokio не нужен остальному приложению; одному движку достаточно трёх потоков, а ожидания с таймаутом покрываются `recv_timeout`. crossbeam-channel не понадобился: все входы супервизора (команды UI и строки stdout) идут в один канал. +- **Собственный парсер**, а не `vampirc-uci 0.11.1`. Нужно небольшое подмножество engine→GUI (`id`, `option`, `uciok`, `readyok`, `bestmove`, `info`). Свой код даёт полный контроль над некорректными строками (ошибка → событие `Warning`, без паники), сохраняет пробелы в `id name`/значениях опций, не тянет pre-1.0 API. Покрыт unit-тестами на строках реального формата Stockfish. + +## Публичный API (кратко) + +```rust +Engine::spawn(path, args, waker: Waker) -> Result // блокирует до uciok+readyok +Engine::spawn_with(EngineConfig { path, args, working_dir, timeouts }, waker) +type Waker = Box; + +EngineHandle: + info() -> &EngineInfo // name, author, options: Vec + pid(), is_running(), stderr_tail() -> Vec + try_recv() -> Option, drain_events(), recv_timeout(d) + analyze(EnginePosition, SearchId) -> Result<(), EngineError> // go infinite + search(EnginePosition, SearchId, SearchLimits) -> Result<(), EngineError> + stop(), new_game(), set_option(name, Option<&str>), set_multipv/threads/hash_mb + quit(self) -> Option; Drop = quit +``` + +`spawn` блокирует вызывающий поток до таймаутов рукопожатия (по умолчанию до 10 + 10 с) — вызывать из рабочего потока. Все остальные методы неблокирующие: только проверка аргументов и отправка в канал. `quit`/`Drop` ограничены таймаутами stop + quit (+0,5 с), затем kill и `wait` (без зомби). + +`EngineEvent`: `SearchStarted{id}`, `Superseded{id}`, `Info{id, SearchInfo}`, `BestMove{id, best, ponder}`, `InfoString{Option, text}`, `Warning(String)` (не более 100 на движок), `Terminated(Quit|Exited|Hung)`. + +Оценка `EngineScore { score: Cp|Mate, bound }` хранится как прислал движок — относительно стороны на ходу корневой позиции. `to_white(side_to_move)` даёт `WhiteEval::Cp` или `WhiteEval::Mate { winner, moves }` и переворачивает lower/upper bound. `mate 0` = сторона на ходу уже получила мат. + +`EnginePosition::startpos(moves)` / `::fen(fen, moves)`; ходы проверяются как координатная UCI-нотация. `0000` (null move) и `--` отклоняются: учебную ветку UI передаёт итоговым FEN. + +## Машина состояний + +``` +Idle ──search──▶ Syncing (isready) ──readyok──▶ Searching(id) ──bestmove──▶ Idle/Syncing + ▲ │ new search/stop + └──────────bestmove──── Stopping(id) (stop отправлен) +``` + +- Новая позиция при `Searching` → `stop`, `Stopping`. Запросы, пришедшие в `Stopping`/`Syncing`, только заменяют единственный ожидающий запрос (`Superseded` для вытесненного). +- После `bestmove` всегда `isready` → `readyok` и только затем `position` + `go`. `bestmove` — граница поиска по протоколу. `isready` защищает от движков, печатающих `info` уже после `bestmove`: такие строки приходят до `readyok` и отбрасываются. Мутационная проверка: без этого барьера гоночные тесты падают. +- `info` в `Searching`/`Stopping` относится к текущему id. В `Idle`/`Syncing` это устаревший вывод, он отбрасывается. В UI передаются только `info` с score или pv. +- `setoption`/`ucinewgame` при простое отправляются сразу, во время поиска откладываются до его конца (UCI запрещает их во время поиска). Чтобы изменение MultiPV сразу повлияло на анализ, UI повторяет `analyze` с новым id. +- Таймауты (`Timeouts`, по умолчанию): uciok 10 с, readyok 10 с, stop→bestmove 3 с, quit 1 с. Если `bestmove` или `readyok` не пришёл вовремя, процесс убивается и отправляется событие `Terminated(Hung)`. EOF stdout или ошибка записи дают `Terminated(Exited{status})`. +- Строки длиннее 64 KiB обрезаются; хранятся последние 256 строк stderr. + +## Тесты + +`cargo test -p uci`: 11 unit-тестов (парсер, оценки, позиции) и 20 тестов с детерминированным `fake_uci` (`src/bin/fake_uci.rs`, флаги описаны в шапке файла). Реальный движок — `tests/stockfish.rs`, `#[ignore]`: + +``` +UCI_STOCKFISH=/path/to/stockfish cargo test -p uci --test stockfish -- --ignored +``` + +## Открытые вопросы + +- Обёртки движков (shell-скрипт, порождающий сам движок): kill завершает только прямого потомка. Убийство группы процессов требует `process_group` + `kill(-pgid)` (libc или nix) — пока не сделано. +- Запись в stdin синхронная. Если движок совсем не читает stdin, а GUI отправит >64 KiB, супервизор зависнет. Коалесценция делает это практически недостижимым, а `Drop` в таком случае убивает процесс из потока UI. +- Политику перезапуска после `Hung`/`Exited` решает приложение (handle после `Terminated` непригоден). +- Ponder, `go` с часами, `searchmoves`, Chess960 (`UCI_Chess960`) не реализованы (не нужны v1). diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md new file mode 100644 index 0000000..082dd76 --- /dev/null +++ b/docs/implementation-plan.md @@ -0,0 +1,59 @@ +# Путь к первой рабочей версии + +Статус: предложение команды, 2026-10-17. Границы продукта подтверждены в `decisions.md`; начало реализации и конкретный UI-стек ещё обсуждаются. + +## 0. Проверка выбранного UI-стека и PGN-совместимости + +Цель — проверить наиболее рискованные части до построения приложения вокруг них. + +- Проверить доступность Rust 1.99.1 и установить системные зависимости выбранного стека (если потребуются); инструменты уже доступны по `~/.cargo/bin/`. +- Запустить окно на текущем Hyprland/Wayland, проверить масштабирование, файловый диалог, кириллицу и clipboard. +- Показать таблицу, квадратную доску с SVG-фигурами и стрелкой, нотацию с длинными комментариями и вложенными кликабельными вариантами. +- Подтвердить корректность переноса и выбора ходов после изменения ширины панели, клавиатурного фокуса и автопрокрутки. +- Отдельно проверить оба PGN-корпуса выбранным парсером: кодировки, FEN, учебный `--`, неизвестные аннотации, восстановление после ошибок. Статистика текстовых маркеров не заменяет этот этап. + +Результат: запускаемый технический прототип и короткий протокол ограничений. Если сложная нотация или Linux-интеграция требуют чрезмерных обходов, пересмотреть UI-фреймворк на этом этапе. + +## 1. Вертикальный срез: открыть и читать + +Сценарий: открыть PGN → увидеть таблицу → выбрать партию → пройти основную линию и варианты → читать комментарии → вернуться к той же строке библиотеки. + +- Фоновое чтение с прогрессом и отменой, история баз, диагностика проблемных записей. +- Дерево документа, исходная позиция, активный узел и ветка, стабильные идентификаторы. +- Согласованная tolerant-политика для реальных учебных PGN, без молчаливой потери исходного содержания. +- Клавиатура и мышь; произвольная начальная позиция FEN обязательна уже здесь. + +Приёмка: оба локальных файла доступны с отчётом о совместимости; исходные байты не меняются; ветви и комментарии не теряются; доска совпадает с проверенными позициями. + +## 2. Ввод партии и переносимый результат + +Сценарий: новая партия → ввод ходов → ответвление → Undo/Redo → копировать PGN → сохранить отдельный файл → открыть результат. + +- Только легальные обычные ходы при вводе, все виды превращения, рокировка и en passant. +- Существующие комментарии, NAG и неизвестные теги сохраняются при экспорте. +- Dirty-состояние и обработка закрытия; ошибка сохранения оставляет документ доступным. +- Нормализованный UTF-8 экспорт с явно определённой политикой совместимости; сохранение неизменённого исходного фрагмента для точного восстановления/диагностики. + +Приёмка: семантический roundtrip, корректное ветвление, отмена и повтор, повторный импорт экспортированной партии. Учебные null moves сохраняются как особое расширение и не появляются в списке обычных легальных ходов. + +## 3. Движок и исследование вариантов + +Сценарий: добавить исполняемый UCI-файл → включить анализ → видеть оценку и MultiPV → просмотреть зафиксированную линию на доске → вернуться → отдельно добавить линию в партию. + +- Начать с детерминированного fake engine для гонок и отказов, затем проверить полноценный официальный Stockfish. +- Контролировать handshake, жизненный цикл и границу завершения предыдущего поиска; читать оба потока процесса. +- Привязать оценку и стрелки к конкретному поиску и позиции; быстрые переходы объединять до последней позиции. +- Предпросмотр хранит снимок линии, исходный узел и точку возврата; никогда не изменяет документ автоматически. +- Поддержать необходимые настройки движка, корректный знак оценки и мат, отсутствие MultiPV у стороннего движка. + +Приёмка: нет чужих оценок/стрелок после быстрой навигации; preview не меняет PGN; зависший или упавший движок не закрывает приложение и не уничтожает работу. + +## 4. Завершение первой версии + +- Настройки фигур, доски, звука и темы; сохранение размеров панелей и пользовательских настроек. +- Проверка Wayland, HiDPI, маленького окна, кириллических путей, отсутствия аудиоустройства. +- Публичные минимальные fixtures вместо копирования полных книжных PGN в репозиторий. +- Лицензия, список авторов сторонних ресурсов, воспроизводимая release-сборка и начальный способ установки для целевого Linux. +- Независимый сквозной прогон тестировщика по пользовательским сценариям. + +Выпуск определяется работающими сценариями и сохранностью данных. Конкретные сроки, поддержка дополнительных Linux-дистрибутивов и формат пакета уточняются после технического прототипа. diff --git a/docs/qa/report-1.md b/docs/qa/report-1.md new file mode 100644 index 0000000..214d4d3 --- /dev/null +++ b/docs/qa/report-1.md @@ -0,0 +1,36 @@ +# QA-отчёт №1 — первый вертикальный срез + +Дата: 2026-10-18. Проверка независимого тестировщика (профиль `tester`); исправления — оркестратор. +Окружение: Hyprland/Wayland, 2×4K, масштаб 2, debug-сборка, Stockfish 19. + +## Дефекты и статус + +| ID | Серьёзность | Суть | Статус | +| --- | --- | --- | --- | +| D1 | средняя | После падения движка оставалась оценка старой позиции; ошибка в Debug-формате | Исправлено (`analysis.rs`: очистка линий, `best()` только при Running, понятное сообщение). Проверено вживую: kill Stockfish → оценка исчезла | +| D2 | средняя | Вставка нескольких партий из буфера склеивала их в одну | Исправлено: буфер режется на записи, открывается первая с уведомлением | +| D3 | средняя | Отмена «Сохранить как…» из окна закрытия оставляла флаг закрытия | Исправлено: `SaveCancelled` сбрасывает флаг | +| D4 | средняя | Drag Потоки/Хеш/MultiPV перезапускал движок каждый кадр | Исправлено: перезапуск по завершении правки; запись настроек — после отпускания мыши | +| D5 | средняя | «Сохранить как» мог перезаписать исходную базу | Исправлено: запись поверх источника или любой базы из списка запрещена | +| D6 | низкая/средняя | NAG $8, $11 выводились как `$n` | Исправлено в `nag.rs` ($7/$8 → □, $10–$12 → =) | +| D7 | низкая | Рокировка кликом «король → ладья» не работала | Исправлено | +| D8 | низкая | Начало drag бралось после порога смещения | Исправлено (`press_origin`) | +| D9 | низкая | В мате/пате пустая панель, шкала 0.5 | Исправлено: «Мат · 1-0» / «Пат», шкала по исходу | +| D10 | низкая | Шорткаты под модальным окном; Enter в библиотеке из чужого поля | Исправлено | +| D11 | низкая | После отмены всех правок партия оставалась «изменённой» | Исправлено в ядре (глубина undo при сохранении), тест `modified_flag_follows_undo_to_saved_state` | +| D12 | мелочи | Имя файла `White _ Black.pgn`; сырой `????.??.??`; анализ прежней позиции на один кадр | Исправлено (имя, отображение даты, повторная привязка анализа перед каждой панелью) | + +Открытые продуктовые вопросы: +- «Добавить как вариант» вставляет весь PV, курсор ставится на просматриваемый ход. Альтернатива — вставлять только до просматриваемого хода. +- Колонка «Ходы» берётся из тега PlyCount; без тега пуста (полный разбор при сканировании не делается). + +## Проверено тестировщиком + +- `engine_history` для всех 63 159 узлов обоих корпусов переигран shakmaty: FEN совпадает в 100 %; 1073 узла после null move корректны. +- Синтетика: FEN с ходом чёрных и fullmove 0, альтернативы первому ходу, комментарий перед первым ходом варианта, вложенные варианты, `--` в главной линии и варианте. +- Правки (add_uci_line после null move, promote, delete с курсором внутри, undo/redo) + roundtrip; добавление линии в каждую партию корпуса и реимпорт — совпадение 889/889 (7 партий без легальных ходов пропущены). +- Скриншоты: библиотека, партии из FEN, глубокие варианты, MultiPV 3 со стрелками. + +## Не проверено + +Мышь/клавиатура вживую (клики, drag, превращение, предпросмотр PV, контекстное меню, поиск/сортировка), файловые диалоги и запись, буфер обмена, звук, изменение файла базы на диске, X11, другие масштабы, светлая тема, производительность. diff --git a/docs/research/quality-plan.md b/docs/research/quality-plan.md new file mode 100644 index 0000000..58e31d9 --- /dev/null +++ b/docs/research/quality-plan.md @@ -0,0 +1,196 @@ +# План качества и риски Linux PGN-приложения + +Дата обследования: 17.10.2026. Основание: `техническое задание.txt` и локальные данные проекта. + +Уточнение после ответа пользователя: первая целевая нагрузка — книги и учебные базы, сотни/тысячи партий (`../decisions.md`). Сценарии на 100 тысяч партий и соответствующие бюджеты ниже — возможная последующая нагрузочная проверка, не критерий выпуска первой версии. Редактирование первой версии ограничено ходами/вариантами и экспортом отдельного файла, при сохранении существующих комментариев и тегов. + +## Обновление после установки пользователем — 2026-10-17 + +Этот блок заменяет прежний статус отсутствия Rust/движка в первоначальном снимке ниже. Исторические наблюдения сохранены для воспроизводимости. + +- Через `~/.cargo/bin/` подтверждены **rustc 1.99.1**, **cargo 1.99.1**, **rustup 1.29.1**. В PATH уже работающего tool-процесса rustc/cargo ещё не видны; использовать полный путь либо добавить `$HOME/.cargo/bin` в окружение будущей команды. Изменение конфигурации shell не выполнялось. +- Теперь в `engines/` находится `stockfish-linux-x86-64-universal.tar.gz`, **81 388 977 байт**. Полное чтение gzip прошло проверку конца потока/CRC; tar содержит 111 записей. +- SHA-256: `9defc0d4e55d49c65a6d042f3e571a39fcea499ade6dbe741b53b8c65e03611f` — **совпадает** с `digest` официального GitHub release asset `sf_19`. Проверены также имя и размер через https://api.github.com/repos/official-stockfish/Stockfish/releases/latest; закреплённый релиз: https://github.com/official-stockfish/Stockfish/releases/tag/sf_19. +- Извлечён только бинарник `stockfish/stockfish-linux-x86-64-universal` во временный каталог `/tmp/opencode/stockfish-smoke-*`; после проверки временный каталог удалён. Пользовательский архив не изменён. +- **UCI smoke — PASS:** идентификация `Stockfish 19`; `uci → uciok`; параметры Threads=1, Hash=16 MiB; `isready → readyok`; `position startpos`, `go depth 4` → `info depth 4 ... score cp 23 ... pv e2e4 c7c6`, `bestmove e2e4 ponder c7c6`; `quit` → exit 0. Объявлены Threads, Hash, MultiPV. +- Этот запуск подтверждает базовую работоспособность движка, не интеграцию будущего приложения, гонки анализа, MultiPV runtime или UI. Приложение ещё не создано, его сборка и продуктовые тесты остаются **NOT RUN**. Прежние блокеры отсутствия toolchain и полного движка сняты; совместимость выбранного комплекта Rust-зависимостей ещё предстоит проверить сборкой. + +Полный PGN-аудит аналитика, завершённый после исходного обследования: `requirements-and-pgn.md`. Он подтвердил 896 записей и выявил повреждённый комментарий №335, который контрольный парсер частично теряет без диагностики. Это отдельный обязательный regression case для будущего импорта. + +## 1. Статус и границы фактической проверки + +Выполнено только read-only обследование входных файлов и окружения, прочитаны публичные спецификации PGN/UCI. Единственный создаваемый в проекте файл — этот план. ПО не устанавливалось, движки не скачивались; файл из `engines` не исполнялся; архив не извлекался на диск. Приложение, шахматный парсер и UCI-сеанс не запускались. Сборка, автоматические тесты, GUI, клавиатура и производительность приложения **ещё не проверены**. Все проверки ниже раздела 3 — будущая стратегия, а не результаты запусков. + +Прочитано ТЗ: нужны список PGN-баз и партий, доска и дерево нотации с комментариями, создание партии и копирование PGN, анализ выбранным внешним движком, просмотр его вариантов и лучших ходов, настройки фигур/доски и звуки, возврат к списку баз. Фреймворк и политика обработки нестандартного PGN пока не определены. + +На момент первого просмотра корень содержал `designExample`, `engines`, `pgnFilesforExample`, ТЗ; сборочный манифест в этом снимке не обнаружен. При первоначальном обследовании в корне и родительских каталогах `AGENTS.md` не найден; позднее harness передал созданные параллельно инструкции корневого `AGENTS.md`, учтённые в плане. Скриншоты UI в рамках этой проверки не изучались; визуальная приёмка ниже основана на сценариях ТЗ. + +## 2. Что установлено фактически + +### 2.1. Движок: загрузка неполная + +В `engines` найден только `Не подтвержден 263386.crdownload`: + +- размер 344 046 байт; права `0644`; +- SHA-256: `e31796c170781e7123409d2b26720c8df75b9566c3d480c7e096da629b861af2`; +- `file` определяет gzip; сигнатура начинается с `1f8b08`; +- в первом распакованном в памяти tar-заголовке имя `stockfish/`, формат `ustar`; +- ограниченное чтение gzip в памяти (лимит 16 MiB) завершилось `EOFError: Compressed file ended before the end-of-stream marker was reached`; до ошибки прочитано 1 048 576 распакованных байт; +- размер и mtime не менялись во время первоначального чтения и хеширования. + +**Вывод:** снимок файла — усечённый gzip/tar с корнем `stockfish/`, а не готовый к запуску движок. Это подтверждено ошибкой потока, не только расширением `.crdownload`. Нельзя утверждать, что браузер продолжает или уже прекратил загрузку: его состояние не проверялось. Версия Stockfish, происхождение, архитектура и требования CPU не установлены; локальный хеш не подтверждает подлинность. Поле «original size modulo 2^32» из `file` для усечённого gzip не считать размером исходного архива. + +Будущий UCI smoke-тест заблокирован до появления полного проверенного исполняемого файла. Перед ним нужны проверка источника/доступной контрольной суммы, архитектуры и CPU-варианта, прав запуска, затем ограниченный по времени `uci → uciok → isready → readyok`. Это **не выполнено**. + +### 2.2. Linux и build tooling + +| Проверка | Фактическое наблюдение | +|---|---| +| Дистрибутив | Omarchy 4.0.4, `ID_LIKE=arch` из `/etc/os-release` | +| Ядро/архитектура | `Linux 7.2.5-3-omarchy x86_64` | +| Сессия | `XDG_SESSION_TYPE=wayland`, `XDG_CURRENT_DESKTOP=Hyprland`, `DESKTOP_SESSION=omarchy` | +| Display env | `WAYLAND_DISPLAY=wayland-1`, `DISPLAY=:0` | +| Rust | `rustc`, `cargo`, `rustup` не найдены в PATH; стандартные `~/.cargo/bin/{rustc,cargo}` и `~/.rustup/toolchains` отсутствуют; версии неизвестны | +| C/tooling | `cc --version`: GCC 16.2.1 20260810; доступны gcc, clang, make, git, curl, wget, file, tar, unzip | +| Недоступно в PATH | cmake, ninja, pnpm, Xvfb, weston | +| JS/Python | Node v22.23.2, npm 12.0.2, Python 3.14.7 | +| pkg-config | 3.0.7 | +| GTK/WebKit | gtk+-3.0 3.24.52, gtk4 4.22.4, webkit2gtk-4.1 2.52.6, javascriptcoregtk-4.1 2.52.6, libsoup-3.0 3.6.6 | +| Другие `.pc` | openssl 3.6.4, x11 1.8.13, wayland-client 1.26.0, xcb 1.17.0, alsa 1.2.16.1, libudev 261, fontconfig 2.18.3, freetype2 26.6.20 | +| Ресурсы | Intel Core i7-13700KF, 24 логических CPU, MemTotal 32 676 332 kB (~31,2 GiB); доступная память изменяется | + +Проверялись только перечисленные display-переменные, не полный environment. Наличие библиотек в pkg-config не доказывает успешную компоновку или GUI-запуск. `DISPLAY=:0` не доказывает работоспособность X11/XWayland. Rust может существовать в нестандартном месте; установка отсутствующих зависимостей не выполнялась. Для Rust-сборки нужен отдельный подготовительный этап после выбора стека. + +### 2.3. Реальный PGN-корпус + +Чтение бинарных файлов, пробное декодирование и подсчёт текстовых маркеров дали: + +| Файл | Размер | Строки `[Event ...]` | FEN / SetUp | Особенности | +|---|---:|---:|---:|---| +| `The Ruy Lopez - Move by Move.pgn` | 374 129 B | 49 | 1 / 1 | Комментарии, RAV, NAG, дополнительные теги, не UTF-8 | +| `Дворецкий. Учебник жндшпиля.pgn` | 1 128 608 B | 847 | 845 / 845 | Массовые FEN, RAV, NAG, графические аннотации, учебные null moves, не UTF-8 | + +Хеши исходников для воспроизводимости: + +- Ruy Lopez: `19994af1c6bb2597e98e2e340014418726cf7b74a0ab136dad1089d4961a6bd5`. +- Дворецкий: `56a7711544c737a64255b60ac0479dca5fb59fb98fe730cf75eb62888ceca0f8`. + +UTF-8-декодирование завершилось ошибкой на байте 13 087 в Ruy Lopez и 477 в Дворецком. Проба cp1252 даёт `Grünfeld` в первом файле, cp1251 — читаемую кириллицу во втором. Это кандидаты кодировок, **не доказательство единой кодировки всего файла**. В русском примере встречается текст `клo^~~евыми` и похожие дефекты; автоматическое «исправление» может изменить исходное содержание. + +У Дворецкого 72 FEN заканчиваются счётчиком полного хода `0`; например, `8/3k4/8/3K4/3P4/8/8/8 w - - 0 0`. В первой партии уже есть вариант `1. -- Kc7 ...`. В файле 521 вхождение `[%cal`, 65 `[%csl`; это подсчёт маркеров, не проверка корректности аннотаций. В Ruy Lopez есть `[Source "Everyman Chess"]`, `[Annotator "Neil McDonald"]`, `[SourceDate "2011.10.24"]`. + +Количество Event-строк — ориентир числа записей, а не подтверждённое количество валидных партий. Подсчёт скобок без токенизации не доказывает повреждение RAV: скобки могут находиться в комментариях. Полная синтаксическая и шахматная валидация не проводилась. + +## 3. Приоритеты рисков и решения до реализации + +| Приоритет | Риск | Критерий контроля | +|---|---|---| +| P0 | Потеря комментариев, вариантов, тегов или текста при импорте/копировании | Семантический roundtrip без молчаливой потери; исходные байты не изменяются | +| P0 | Неверная позиция из FEN/RAV или принятие нелегального хода | Позиция каждого узла проверена независимым эталоном, ввод атомарен | +| P0 | Анализ старой позиции показан как текущий | Идентичность сессии/поиска/узла, контролируемая граница stop/go | +| P0 | Зависание UI или завершение приложения вместе с движком | Изоляция процесса, таймауты, ограниченные очереди, сценарии отказов | +| P1 | Реальные PGN отвергаются строгим парсером или искажаются нормализацией | Явная политика legacy-кодировок, FEN с `0`, `--`, неизвестных аннотаций | +| P1 | Ошибочный знак оценки, порядок MultiPV, отображение mate | Точные протокольные фикстуры, белая/чёрная сторона, неполные обновления | +| P1 | Клавиатура/clipboard/dialogs не работают в Linux | Ручная матрица Wayland/XWayland/X11 и автоматизация доступных слоёв | +| P1 | Большая база или verbose engine блокирует интерфейс | Измеримые бюджеты задержки, памяти и отмены | + +До кодирования согласовать: поддержку учебного `--` отдельно от легальных шахматных ходов; нормализацию fullmove `0` только во внутренней позиции с сохранением исходного FEN; выбор/подтверждение кодировки и формат экспорта; сохранение неизвестных полей; поведение частично повреждённой базы; точную систему знака оценки. Строгий режим не должен делать основной пользовательский корпус практически недоступным. Неподдержанные фрагменты сохранять с диагностикой либо явно блокировать потенциально неполный экспорт. + +## 4. PGN roundtrip и источники + +Проверять цепь `исходные байты → декодирование → AST → экспорт → повторный AST`. Основной oracle — семантическое равенство: порядок и структура ходов/RAV, начальная позиция, привязка комментариев до/после хода, NAG, результат, известные и неизвестные теги, текст аннотаций. Изменение пробелов/переносов допустимо только по заявленному контракту; побайтовое равенство нужно для отдельного режима lossless, если он реализован. Проверять устойчивость нормализованного экспорта при втором цикле. + +- Оба локальных файла: загрузка всех записей, навигация каждой ветки, экспорт каждой партии, повторный импорт; отдельно отчёт по неподдержанным фрагментам. Ожидаемые 49/847 записей подтвердить полноценным парсером, не регэкспом. +- Комментарии `{...}` и `;` до конца строки, CRLF/LF, BOM, UTF-8, cp1251/cp1252, кириллица, диакритика, длинные строки; экранированные кавычки/обратный слеш в тегах, неизвестные/повторные теги по выбранной политике. +- NAG `$1`, `$22`, символьные `!?`, пустые/вложенные варианты, пропущенные необязательные теги, `*`, ничья и решающий результат; конфликт Result-тега и завершающего маркера не скрывать. +- `%cal/%csl/%clk/%eval` и неизвестные директивы: не терять при копировании, даже если UI их не рисует. Проверить привязку цвета/стрелок к правильному узлу. +- Отсечённый файл, неверное экранирование, слишком глубокий RAV, гигантский комментарий, NUL и неверная кодировка: диагностируемая ошибка с местом/записью, лимиты ресурсов, отсутствие молчаливого пропуска хвоста базы. +- Копирование введённой и открытой партии: clipboard содержит именно выбранную партию и предусмотренные контрактом варианты; внешний импорт проверяет совместимость. Ошибка clipboard не уничтожает редактирование. +- Отмена открытия базы, недоступный/переименованный файл из истории, файл без прав чтения, изменение файла на диске во время чтения; повторное открытие не дублирует историю неконтролируемо. Импорт никогда не перезаписывает источник. + +Матрица будущих источников: текущие учебные базы, собственные минимальные фикстуры, экспорт Lichess, экспорт другого независимого PGN-редактора, турнирный PGN. Для каждой фикстуры записывать происхождение, хеш, кодировку и разрешение на распространение. Наличие локальных книг не означает право включать их целиком в публичный репозиторий/CI; публичные регрессии строить на собственных минимальных примерах. Удалённые экспорты в этом обследовании не скачивались. + +## 5. RAV, FEN и легальность + +1. RAV начинается от позиции **до** хода, которому альтернативен. Проверить вложенность минимум 3 уровня, соседние варианты, комментарии на входе/выходе, чёрный первый ход `17...`, переключение основной линии и ветки, возврат к родителю. Узел хранит устойчивый идентификатор, не только номер полухода. +2. FEN: все 6 полей, чёрная очередь, права рокировки, en passant, halfmove/fullmove, SetUp=1, отсутствие/конфликт SetUp, некорректные поля. Для 72 реальных FEN с fullmove=0 — отдельная регрессия согласованной tolerant-политики и сохранения оригинала. +3. Учебный `--`: отдельный тип узла/расширение; не разрешать обычному пользователю «пропустить ход» как легальный шахматный ход. Не передавать учебную ветку движку как обычную историю UCI без проверенного преобразования; допустима явно определённая отправка результирующего FEN. Не терять исходную нотацию. +4. Легальность ввода мышью/клавиатурой и PV: связки, вскрытый шах, короли рядом, двойной шах, рокировка из/через/под шах, утраченные права рокировки, взятие на проходе с вскрытием шаха, превращения во все 4 фигуры и взятия с превращением, неоднозначный SAN. Нелегальный ввод не меняет доску, AST и undo-историю. +5. Мат/пат, недостаточный материал, 50/75 ходов, троекратное/пятикратное повторение: различать заявление ничьей и автоматическое завершение. Для FEN без истории нельзя выдумывать повторения. +6. PGN SAN ↔ внутренний ход ↔ UCI ↔ новая позиция: эталонные FEN каждого узла, заранее проверенные perft-позиции (включая рокировку/en passant), сравнение с независимой шахматной библиотекой. Oracle не должен быть тем же кодом, что реализация. +7. Property-based тесты: последовательности легальных ходов, обратимость make/unmake, сериализация дерева, сохранение позиции при смене ветки; fuzz декодера/парсера и ограничение глубины. Это план, ни один perft/fuzz-прогон ещё не выполнен. + +## 6. UCI: stop/go и устаревшие ответы + +Основной тестовый инструмент — будущий детерминированный fake UCI subprocess: управляемые задержки, частичные строки, барьеры и произвольный порядок допустимых ответов. Реальный движок нужен для smoke/совместимости, но не заменяет воспроизводимые гонки. + +- Конечный автомат: запуск → `uci`/`uciok` → options → `isready`/`readyok` → `position` → `go` → `stop` → завершающий `bestmove`; выход через `quit`, затем ограниченное ожидание и принудительное завершение зависшего процесса по политике приложения. +- Сценарий A→B→C при быстром листании: старые `info`/`bestmove` после выбора B и C никогда не рисуют оценки/стрелки и не меняют дерево. То же после закрытия партии, переключения движка, возврата к той же FEN в другом узле и перезапуска процесса. +- У UCI нет request ID. Локальный generation ID сам по себе не отличает строки старого поиска, если новый поиск начат слишком рано. Сериализовать границу поисков: после `stop` дождаться завершающего `bestmove` предыдущего поиска, затем отправить актуальное `position/go`; при таймауте перезапустить процесс. `readyok` не заменяет эту границу и не означает окончания поиска. +- Локальную идентичность связывать с экземпляром процесса, поколением поиска, узлом и полным контекстом позиции/истории. Одинаковая расстановка фигур не гарантирует одинаковые права, очередь и условия повторения. +- Быстрая навигация объединяет ожидающие позиции до последней; не накапливает бесконечную очередь `go`. Отмена операции не блокирует UI. `bestmove` режима анализа не должен автоматически делать ход в пользовательской партии. +- При переходе к другой партии проверить `ucinewgame` и последующий `isready`; для обычной ветки передавать начальную позицию и историю `moves`, чтобы не терять повторения. Одного конечного FEN недостаточно для эквивалентного анализа истории. +- Инъекции: `info` после stop до bestmove, задержанный readyok, EOF посреди строки, разделённые UTF-8/байты, CRLF, неизвестные токены, длинные `info string`, отсутствие ответа, stdout/stderr flood. Чтение обоих потоков исключает deadlock; размеры строк/очередей ограничены. + +## 7. MultiPV, mate и просмотр линий + +- Из объявления `option name MultiPV ... min/max` получить возможности и диапазон; движок без MultiPV работает с одной линией. Изменение числа вариантов — через безопасную остановку/перенастройку поиска. +- Строки `multipv 1..N` приходят не по порядку и с разной depth. При обновлении не выдавать смесь глубин за завершённый единый снимок; пропуски/устаревшие строки обозначать или очищать. Смена позиции очищает предыдущий набор атомарно. +- Зафиксировать направление оценки (рекомендация UI: со стороны белых). UCI score интерпретировать относительно стороны корневой позиции; проверять инверсию при ходе чёрных, отрицательные cp, `mate ±N`, `mate 0` по состоянию терминальной позиции, `lowerbound/upperbound`. Mate не преобразовывать в cp или «точный процент». +- `bestmove (none)` и встречающееся `0000`, отсутствие `pv`, короткая PV, терминальная позиция: не создавать фиктивный ход. Счётчик mate не подписывать как полуходы без соответствующего преобразования. +- Каждую PV воспроизвести от FEN её поиска с проверкой легальности; при ошибке остановиться на валидном префиксе и отметить сбой. Обновление PV во время просмотра не должно менять позицию под пользователем: использовать закреплённый снимок или явно согласованное поведение. +- Выбор строки, движение по PV и возврат к партии не редактируют исходное дерево без отдельной команды. Стрелка лучшего хода соответствует активному поиску и правильно трансформируется при перевороте доски; превращение отображается без потери типа фигуры. + +## 8. Отказы движка и жизненный цикл + +Будущие случаи: отсутствующий файл, каталог вместо executable, права `0644`, неподходящая архитектура, отсутствующая shared library, неподдержанный CPU/illegal instruction, не-UCI программа, ненулевой exit, SIGSEGV, зависание handshake/stop/quit, авария во время PV, чрезмерный stderr, повторный запуск, закрытие приложения при активном анализе. + +Ожидание: партия и ввод сохраняются, UI остаётся доступным, статус объясняет причину/код выхода, строки умершего процесса не принимаются новым, дочерние процессы освобождаются, автоматические рестарты ограничены. Диагностический лог ограничен по объёму и не содержит полного environment. Путь с пробелами/кириллицей передаётся напрямую при spawn, без shell-интерполяции. Отдельно проверить два одинаково названных движка из разных каталогов. + +## 9. Клавиатура и Linux UI + +- Сквозной путь без мыши: открыть базу → выбрать партию → перейти к нотации → перемещаться по ходам/веткам → включить анализ → просмотреть PV → скопировать PGN → вернуться к списку. Зафиксировать раскладку горячих клавиш до приёмки. +- Tab/Shift+Tab, видимый фокус, Enter/Space, стрелки, Home/End, PageUp/PageDown, Escape; отсутствие фокус-ловушек. Стрелки редактирования текста не листают партию; глобальные shortcuts не ломают комментарии и поля пути. Проверить автоповтор клавиш и быстрые переключения. +- Русская/английская раскладки, Ctrl+C в тексте и отдельная команда копирования всей партии, IME/dead keys, кириллические имена файлов. После закрытия диалога фокус возвращается логично. +- Первичная ручная платформа: имеющаяся Hyprland/Wayland-сессия. Отдельные будущие прогоны: XWayland и настоящая X11-сессия, если они заявлены поддерживаемыми; наличие DISPLAY не считать выполненным прогоном. +- Нативный file picker/portal, cancel, clipboard между приложениями, отсутствие clipboard-provider/закрытие окна, drag-and-drop при поддержке; Wayland не требует глобального перехвата клавиш. +- Масштаб 100/125/150/200%, смешанный DPI и перенос между мониторами, resize/узкое окно, длинные комментарии, вложенные варианты, длинные имена игроков, темы/контраст и кириллический шрифт. Доска квадратная, координаты и hit-testing верны при flip и масштабировании. +- Звуки: включение/выключение, отсутствующее аудиоустройство/ассет, недоступный аудиосервер; ошибка звука не ломает ход или навигацию. Наборы фигур/фоны: корректность всех фигур, fallback при отсутствующем ресурсе, корректная лицензия ассетов. +- GUI-автотесты зависят от выбранного фреймворка; headless-тесты модели не заменяют реальный Wayland-прогон. Xvfb/Weston сейчас не найдены, их запуск не проводился. + +## 10. Производительность: предлагаемые бюджеты + +Ниже **целевые критерии для согласования**, не замеры. В протоколе будущего запуска фиксировать release/debug, commit, стек, файловую систему/накопитель, CPU/RAM, масштаб окна, движок и его Threads/Hash. CPU и память движка измерять отдельно от приложения. Cold/warm прогоны разделять, использовать median/p95 и максимумы; не делать вывод о p95 на одном запуске. + +| Сценарий | Предварительный бюджет | +|---|---| +| Локальный корпус ~1,5 MB / 896 Event-записей | Список готов ≤2 с на обследованной машине, без блокировки UI | +| Выбор хода, ветки, flip | p95 ≤50 мс до обновления доски | +| Прокрутка списка/нотации на 60 Hz | p95 кадра ≤16,7 мс, нет пауз >100 мс | +| Показ уже полученного актуального `info` | p95 ≤100 мс; время поиска движка не входит | +| Отмена импорта/анализа | UI подтверждает ≤100 мс; остановка процесса имеет отдельный конечный таймаут | +| Большая синтетическая база 100 тыс. партий / ~100 MB | Первые строки ≤2 с, полный индекс ориентир ≤30 с; прогресс и отмена доступны | +| Память приложения на такой базе | Предварительно ≤512 MiB RSS без движка, уточнить после выбора архитектуры | + +Нагрузки: крупная база с короткими партиями, одна партия с тысячами узлов RAV/комментариями, глубокое дерево, 1 000 переключений позиций, MultiPV=1/5/максимум поддерживаемого, высокочастотный stdout, 30 минут анализа и 100 циклов открытия/закрытия. Проверять ограниченность RSS/очередей/дескрипторов и отсутствие дочерних процессов после закрытия. Использовать виртуализацию списка и ленивую материализацию по результатам измерений, а не по предположению. Нельзя занимать все CPU движком по умолчанию и затем считать задержки UI неизбежными. + +## 11. Порядок проверки и критерии выпуска + +1. **Контракт и подготовка:** решить вопросы кодировок/FEN/`--`, определить стек и поддерживаемые Linux-бэкенды, подготовить Rust/build tooling отдельно; получить полноценный движок. Текущий `.crdownload` не годится для smoke-теста. +2. **Ядро P0:** AST/roundtrip, модель позиций/RAV/легальность, детерминированный fake-UCI с гонками и отказами. Фикстуры должны ловить реальную потерю данных/позиции, не повторять внутреннюю реализацию. +3. **Интеграция:** оба пользовательских PGN целиком с отчётом, проверенный реальный UCI-движок, импорт → навигация → анализ → clipboard → повторный импорт; реальные ошибки файловой системы и перезапуск движка. +4. **Linux/UI:** ручной smoke на Wayland, затем остальные заявленные бэкенды, клавиатура, масштабирование, clipboard, диалоги, ассеты/звук. +5. **Нагрузка и выпуск:** согласованные performance-бюджеты, ограниченный fuzz/soak, отсутствие потери данных, stale-анализов, нелегальных переходов и зависаний в сценариях P0. + +Будущий CI: после появления Rust-проекта — форматирование/статические проверки и тесты по правилам репозитория; headless core/parser/fake-UCI на каждом изменении, ресурсно ограниченные fuzz/нагрузочные задания отдельно, реальный движок и GUI по доступности соответствующего окружения. Не считать зелёный CI доказательством ручной Linux-приёмки. + +Для каждой проверки записывать: ID риска, фикстуру/хеш, команду или точные шаги, build/version, ожидаемое/фактическое, логи/скриншот, статус **PASS / FAIL / BLOCKED / NOT RUN**. Сейчас фактические результаты ограничены разделом 2; все продуктовые тесты имеют статус **NOT RUN**, Rust-сборка и реальный UCI smoke — **BLOCKED** выявленными предпосылками. Критерий релиза: нет открытых P0, P1 явно решены или согласованы, корпус обрабатывается без молчаливой потери, обязательные Linux-сценарии реально пройдены. + +## 12. Источники технических контрактов + +Прочитаны 17.10.2026: + +- [PGN Specification and Implementation Guide](https://www.saremba.de/chessgml/standards/pgn/pgn-complete.htm): разделы 3 (import/export), 5 (комментарии), 8.2.5 (RAV), 9.7 (SetUp/FEN), 16.1 (FEN). Legacy-кодировки и учебный `--` требуют расширения политики приложения, а не предположения об их стандартности. +- [UCI protocol, редакция апреля 2006](https://backscattering.de/chess/uci/): `isready`, `stop`, `bestmove`, `ucinewgame`, `info score`, `multipv`, `option`. В частности, readyok возможен во время поиска, а bestmove нужен для каждого завершённого go; mate измеряется ходами, не полуходами. + +Попытка открыть страницу Stockfish `https://official-stockfish.github.io/docs/stockfish-wiki/UCI-%26-Commands.html` вернула 404; её содержание не использовалось как подтверждение. diff --git a/docs/research/requirements-and-pgn.md b/docs/research/requirements-and-pgn.md new file mode 100644 index 0000000..4ddb3c2 --- /dev/null +++ b/docs/research/requirements-and-pgn.md @@ -0,0 +1,301 @@ +# Требования и исследование реальных PGN + +Дата: 2026-10-17. Роль: аналитик. Этап: исследование, до реализации приложения и утверждения стека. + +Актуальные подтверждённые границы из `docs/decisions.md` учтены: открытый исходный код; первая нагрузка — сотни/тысячи аннотированных партий; редактирование ходов и вариантов, копирование PGN и сохранение отдельным файлом. Полный редактор комментариев/тегов и массовое изменение базы отложены. При дальнейшем изменении объёма `docs/decisions.md` имеет приоритет над предложениями этой записки. + +## 1. Краткий вывод + +Нужен локальный Linux-просмотрщик и редактор отдельных шахматных партий с анализом движком и списком PGN-баз. На предоставленных материалах нельзя строить MVP вокруг плоского списка SAN и UTF-8: обязательны дерево вариантов, произвольная исходная позиция, наследуемые кодировки, комментарии до первого хода и перед вариантами, NAG и учебный нулевой ход `--`. + +**Проверено:** 896 записей в двух файлах, 62 263 узла ходов во всех ветках, 846 FEN; глубина вложения вариантов до 7. В учебнике есть повреждённый комментарий, который терпимый парсер частично теряет без сообщения об ошибке. Исходные байты и диагностические сведения должны храниться отдельно от разобранной модели. + +**Рекомендация:** выбирать Rust-парсер и шахматную библиотеку только после проверки этого корпуса. Успешное чтение заголовков или отсутствие ошибок парсера не являются доказательством сохранности PGN. Выбор конкретного GUI-фреймворка и соответствие стеку Artcraft здесь не проверялись; их нужно согласовать по отдельному исследованию архитектуры. + +## 2. Основания и методика + +Прочитано целиком `техническое задание.txt`, исследованы оба оригинальных файла `pgnFilesforExample/`. Скриншоты и лицензии внешних проектов не являются предметом этой записки. + +Выполнено: + +- Чтение исходных байтов, проверка строгого UTF-8, декодирование с альтернативными однобайтовыми кодировками; подсчёт размера, строк, BOM, переводов строк и NUL. +- Лексический обход всего movetext с отдельным учётом `{…}`, RAV `(...)`, NAG, ходов, результатов и встроенных `[%…]`. Скобки внутри комментариев не учитывались как RAV. +- Независимый полный разбор через Python-пакет `chess==1.11.2` (`chess.pgn`), как непрерывного потока, так и отдельных записей; обход **всех** веток с восстановлением позиции и проверкой обычных ходов на легальность. `--` учитывался отдельно и не объявлялся легальным турнирным ходом. +- Сопоставление числа ходов основной линии с `PlyCount`, результатов в заголовке и movetext, количества распознанных узлов и сырых токенов. Ручное исследование расхождений и образцов расширений. + +Оригинальные материалы не изменялись. Для аудита использовалось отдельное временное Python-окружение `/tmp/opencode/pgn-audit-venv`; промежуточная статистика записана в `/tmp/opencode/pgn-audit-results.json`. Это инструмент исследования, не зависимость предлагаемого приложения. Ни приложение, ни выбранный Rust-парсер на корпусе пока не тестировались. + +Номера записей ниже — порядковые номера с единицы. Номера строк относятся к исходным файлам. Под «партией» в статистике понимается PGN-запись: это может быть полная игра, фрагмент, упражнение или позиция без ходов. + +### Контрольные суммы исходников (SHA-256) + +```text +The Ruy Lopez - Move by Move.pgn +19994af1c6bb2597e98e2e340014418726cf7b74a0ab136dad1089d4961a6bd5 + +Дворецкий. Учебник жндшпиля.pgn +56a7711544c737a64255b60ac0479dca5fb59fb98fe730cf75eb62888ceca0f8 +``` + +## 3. Что действительно требует ТЗ + +| Требование пользователя | Основание в ТЗ | Следствие | +| --- | --- | --- | +| Linux и близость к стеку Artcraft, предположительно Rust | строки 1–2, 32 | Это пожелание и вопрос для исследования, а не установленный факт о чужом стеке | +| Работа с PGN | строка 3 | Поддержка проприетарных форматов ChessBase не нужна на первом этапе | +| Список ранее открытых баз и добавление новой из файловой системы | строки 6–8 | Сохранять историю путей, показывать таблицу записей выбранной базы | +| Открытие партии, доска и нотация рядом, навигация мышью и клавиатурой | строки 7, 10 | Активный узел дерева и позиция доски должны быть синхронизированы | +| Новая партия из начальной позиции и ручной ввод | строка 9 | Нужны проверка ходов, рокировка, взятие на проходе и выбор превращения | +| Выбор локального движка, включение анализа, просмотр его линий | строка 11 | Требуется менеджер движков и отдельное состояние предпросмотра PV | +| Чтение комментариев из базы | строка 12 | Текст нельзя терять при импорте, переключении веток и экспорте | +| Возврат из партии к списку баз и партий | строка 13 | Сохранять выбранную базу, строку, прокрутку и фильтр | +| Настройки движков, фигур, фона доски | строка 14 | Минимальные настройки должны быть частью первого согласованного релиза | +| Показ лучших ходов на доске | строка 16 | Стрелка анализа должна соответствовать именно текущей позиции | +| Копирование PGN введённой и открытой партии | строки 9, 19 | Экспорт текущего дерева в буфер обмена, включая исходный FEN и аннотации | +| Звуки | строка 21 | Звук хода/взятия и отключение звука; права на ресурсы проверить отдельно | +| Продумать дополнительные сценарии и организовать работу ролей | строки 15, 25–30 | Дополнительные функции ниже — предложения, не скрыто расширенное ТЗ | + +Облако, аккаунты, онлайн-игра, обучение по расписанию, автоматическая разметка всей базы и конвертация ChessBase в ТЗ не требуются. + +## 4. Размеры и кодировки + +| Показатель | Ruy Lopez | Дворецкий | +| --- | ---: | ---: | +| Размер, байт | 374 129 | 1 128 608 | +| Размер, MiB | 0,3568 | 1,0763 | +| Строки | 5 388 | 23 001 | +| PGN-записи | 49 | 847 | +| BOM / NUL | нет / нет | нет / нет | +| Переводы строк | CRLF во всех 5 388 строках | CRLF во всех 23 001 строках | +| Строгий UTF-8 | ошибка на байте с offset 13 087 | ошибка на байте с offset 477 | +| Рабочее декодирование | Windows-1252 либо ISO-8859-1 | Windows-1251 | + +**Точность определения кодировки.** В Ruy Lopez встречаются только два не-ASCII байта: `FC` и `F8`, по 6 раз каждый. Они дают `ü` и `ø` как в Windows-1252, так и в ISO-8859-1; различить эти кодировки по данному файлу нельзя. Примеры: `Grünfeld` (строка 180), `Tromsø` (546), `[White "Hübner, R."]` (3189). Для аудита применён `cp1252`. + +Windows-1251 даёт осмысленный русский текст учебника; это подтверждённое пригодное декодирование, но метки кодировки внутри файла нет. Одного критерия «декодирование завершилось без ошибки» недостаточно: оба файла формально декодируются и неподходящими однобайтовыми кодировками. + +**Предложение для продукта:** сначала строгий UTF-8, затем определение вероятной кодировки с предпросмотром и ручным переключением. Хранить выбор кодировки на источник, внутренний текст — Unicode. Экспорт в буфер обмена — Unicode/UTF-8. Смена кодировки не должна переписывать исходник. + +## 5. Полный movetext: измеренная структура + +| Показатель | Ruy Lopez | Дворецкий | +| --- | ---: | ---: | +| Ходы основной линии, полуходы | 3 308 | 14 834 | +| Все узлы ходов с вариантами, включая `--` | 8 340 | 53 923 | +| Максимум полуходов основной линии в одной записи | 109 | 97 | +| Максимум узлов во всех ветках одной записи | 426, №24 | 601, №578 | +| Число RAV, то есть открывающих `(` вне комментариев | 829 | 6 322 | +| Максимальная глубина RAV | 4 | 7 | +| Записи с RAV | 49 | 773 | +| Блоки комментариев `{…}` | 3 040 | 9 192 | +| Записи с комментариями | 49 | 841 | +| Записи с комментарием до первого хода в модели парсера | 12 | 625 | +| Комментарии перед началом варианта в модели парсера | 803 | 3 217 | +| Максимальная длина отдельного блока комментария, символы включая исходные CRLF | 1 951 | 1 444 | +| NAG, всего | 835 | 12 705 | +| Различных числовых NAG | 6 | 21 | +| Нулевые ходы `--` во всём дереве | 23 | 246 | +| Из них на основной линии | 2 | 20 | +| Записи с нулевыми ходами | 18 | 171 | +| Превращения во всём дереве | 5 | 602 | +| Из них превращения не в ферзя | 0 | 34 | +| Взятия на проходе во всём дереве | 11 | 27 | +| Рокировки во всём дереве | 164 | 2 | +| Записи без ходов основной линии | 0 | 4 | + +Комментарии подсчитаны как исходные блоки, а не как число полей `comment` в AST: соседние блоки парсер может объединять. Отдельные начальные комментарии вариантов нельзя потерять, сохраняя только комментарий после хода. + +Ни `;`-комментариев, ни escape-строк с `%` в начале строки не найдено. Отдельных символьных NAG `!`, `?!` вне комментариев не найдено: разметка выполнена числовыми `$n`. Отсутствие этих конструкций в двух примерах не означает, что их можно игнорировать в общем PGN-импорте. + +### NAG + +- Ruy Lopez: `$1` ×547, `$2` ×128, `$3` ×5, `$4` ×7, `$5` ×108, `$6` ×40. +- Дворецкий: `$1` ×4 929, `$2` ×1 819, `$3` ×264, `$4` ×250, `$5` ×359, `$6` ×193, `$8` ×38, `$11` ×1 780, `$13` ×1, `$14` ×5, `$15` ×12, `$16` ×20, `$17` ×18, `$18` ×1 484, `$19` ×839, `$22` ×577, `$40` ×1, `$44` ×1, `$132` ×3, `$140` ×100, `$142` ×12. + +Нужна поддержка не только `!?`, но и позиционных оценок и менее распространённых NAG. Неизвестный числовой код сохранять и показывать как `$n`, а не удалять. + +### Учебные нулевые ходы + +Уже первая запись учебника, строки 12–13: + +```pgn +{[%csl Rc6,Rd6,Re6]} 1. Ke5 (1. Kc5 Kc7 $22) (1. -- Kc7 (1... Ke7 2. Kc6) 2. +Ke6) 1... Ke7 $22 * +``` + +`--` здесь означает условную передачу хода для объяснения угрозы. Это реальный узел учебного дерева, а не отсутствие данных. Нельзя отбрасывать всю запись или сдвигать привязку последующих комментариев. Ввод обычных ходов пользователем и чтение таких учебных узлов требуют разных правил. Политику анализа позиций после `--` следует явно определить: не считать такую историю обычной сыгранной партией. + +## 6. FEN, SetUp и метаданные + +| Показатель | Ruy Lopez | Дворецкий | +| --- | ---: | ---: | +| FEN + `SetUp "1"` | 1 | 845 | +| FEN без согласованного SetUp / наоборот | 0 | 0 | +| Старт с ходом чёрных | 0 | 268 | +| FEN с номером полного хода `0` | 0 | 72 | +| Результат `1-0` | 41 | 325 | +| Результат `0-1` | 3 | 134 | +| Результат `1/2-1/2` | 2 | 266 | +| Результат `*` | 3 | 122 | + +- У Ruy Lopez единственная FEN-запись — №11, начало на строке 1464: `White = Chigorin Scenario Two:`, `Black = Puzzle`, один полуход. Дебютная книга тоже содержит упражнения с нестандартной позицией. +- В учебнике только №316 и №784 не содержат FEN; остальные начинаются с заданных позиций. Исходный номер полного хода встречается до 104 включительно: нельзя нумеровать любую запись с `1.`. +- Номер полного хода `0` не соответствует обычному требованию FEN о положительном номере. Контрольная библиотека принимает его и нормализует игровую доску к `1`, сохраняя исходный текст в заголовке. Такая терпимость не гарантирована выбранной Rust-библиотекой. +- Все стартовые доски и все восстановленные позиции приняты валидными контрольной библиотекой. Все обычные разобранные ходы легальны; ошибок парсера нет. Это проверка конкретной библиотекой с её терпимостью, а не сертификат строгого соответствия исходных файлов стандарту. +- `PlyCount` совпадает с разобранной основной линией во всех 896 записях. `Result` совпадает с завершающим токеном movetext. Дублированных ключей заголовков не обнаружено. +- Позиции без ходов учебника: №5 (`Coull, Alison — Stanciu, Gabriela`), №21 (`1.19`), №251 (`4.15`), №717 (`14.14`). Это содержательные диаграммы с комментариями, а не пустые/битые записи. + +Семь основных тегов присутствуют во всех записях, но данные часто условные: + +- В учебнике `Black = ?` у 399 записей, `Event = ?` у 225, `Site = ?` у 842, `Date = ????.??.??` у 140, `Round = ?` у 817. +- В Ruy Lopez `Site` и `Round` неизвестны во всех 49 записях; `Event = ?` у 5, `Black = ?` у одной. +- `White` может быть номером упражнения, не именем. Таблица должна иметь устойчивый порядковый номер записи и хорошо работать с частичными датами и неизвестными полями. + +Дополнительные теги: + +- Ruy Lopez: `ECO` — 48, `Annotator`, `EventDate`, `Source`, `SourceDate` — по 49, `EventType` — 2, `PlyCount` — 49. +- Дворецкий: `EventDate` — 411, `ECO`, `EventType`, `EventRounds`, `EventCountry` — по 1, `PlyCount` — 847. + +Нужна упорядоченная коллекция произвольных тегов, а не структура из только семи стандартных полей. Неизвестное поле сохранять при копировании PGN. + +## 7. Расширения в комментариях + +В Ruy Lopez директив `[%…]` не обнаружено. В учебнике они есть в 310 записях: + +| Расширение | Вхождений | Наблюдаемый пример | +| --- | ---: | --- | +| `csl` | 65 | `[%csl Rc6,Rd6,Re6]`, №1, строка 12 | +| `cal` | 521 | `[%cal Rc7b6]`, №19, строка 356 | +| `tqu` | 252 | `[%tqu "Каким должен быть первый ход белых?","","",Ka6,"",1,b6,"",0]`, №19, строка 353 | + +`csl` и `cal` содержат разметку полей и стрелок; примеры используют цветовые префиксы, включая `R` и `G`. Их графическое отображение существенно для смысла некоторых упражнений. Рекомендация — включить отображение и сохранение `csl`/`cal` в MVP и визуально различать авторскую разметку и текущую стрелку движка. + +**Наблюдение:** `tqu` содержит вопросы, SAN-ответы и числовые поля. **Гипотеза:** это формат интерактивных учебных вопросов экспортировавшего приложения. Семантика всех полей, баллов и происхождение формата не проверены. На первом этапе сохранять payload без изменения; можно показывать узнаваемый вопрос, но не объявлять интерактивную проверку ответов поддержанной. Полноценный режим упражнений — позже. + +`clk`, `eval`, `emt` в этих файлах не найдены. Неизвестные директивы будущих файлов также нельзя уничтожать при экспорте. + +## 8. Качество данных: реальные дефекты + +### 8.1. Повреждённый русский текст уже находится в исходнике + +В учебнике встречается `~~` 5 702 раза и `o^` 2 974 раза. Например, строки 26–29 после подходящего декодирования: + +```text +При пешке на 5-й горизонтали клo^~~евыми +являo^тся не только поля а7, b7 и с7 ... +Стоит отметить, ~~то нето~~но +``` + +Последовательности состоят из ASCII-байтов; выбор другой кодировки сам по себе их не восстановит. По контексту вероятны старые подстановки букв/дефект конвертации (`~~` часто стоит на месте «ч», `o^` — «ю»), но универсальное правило замены не доказано. Автоматическое исправление оригинала не предлагать. Отдельная опциональная очистка с предпросмотром может появиться позже. + +### 8.2. Повреждённые границы комментария: №335 + +Запись `Averbakh, Yuri L`, начало на строке 8253. Строки 8264–8266: + +```pgn +{Если слон не справляется в одино~~ку (а так бывает ~~аще всего}, то исход +борьбы зависит от положения короля слабейшей стороны: способен ли он +воспрепятствовать перекрытиo^ или вытеснениo^.} {При короле на a1 или b1 +``` + +Первый `}` преждевременно завершает комментарий, затем обычный русский текст находится вне `{…}`, а следующий `}` оказывается лишним. Лексический аудит обнаружил 17 посторонних токенов и одну лишнюю закрывающую фигурную скобку. Это единственное обнаруженное такое структурное расхождение в корпусе; дисбаланса RAV нет. + +Контрольный `chess.pgn` читает запись **без ошибок**, восстанавливает 31 узел дерева и 10 полуходов основной линии, но теряет фразу от `, то исход` до `вытеснениo^.`. Поэтому сырых токенов, первоначально похожих на movetext, здесь 48, но ходов только 31. Эти 17 токенов не входят в итоговую статистику ходов. + +**Вывод:** нельзя использовать `game.errors == []` как единственный критерий успешного импорта. Нужна проверка покрытия исходного текста токенами и диагностика неразобранных фрагментов с указанием записи/строки. Сохранять сырой PGN записи; нормализованный экспорт повреждённой записи не должен молча объявляться без потерь. Конкретный UX исправления или выбора сырого копирования требует согласования. + +### 8.3. Ограничения доказательств + +- Полностью идентичных текстовых записей в каждом файле не найдено; семантическая дедупликация одинаковых игр/позиций не выполнялась. +- Сохранность разобранных комментариев при будущей сериализации Rust-моделью ещё не проверена; данная работа выявляет требования к такой проверке. +- Примеры всего около 1,43 MiB суммарно. Они хорошо проверяют сложность аннотаций, но ничего не доказывают о скорости импорта многогигабайтных баз. +- Полнота формата `tqu`, иные шахматные варианты и повреждённые двоичные данные не исследовались. + +## 9. Предлагаемый MVP и последующие этапы + +Это предложение для согласования, не утверждённый новый объём ТЗ. + +### MVP — законченные пользовательские сценарии + +1. Открыть локальный PGN, показать прогресс/отмену и понятную диагностику кодировки/записи; сохранить историю баз. Пропавший файл в истории можно найти заново или убрать из списка. +2. Вывести таблицу записей с базовыми тегами, порядковым номером и признаком аннотаций/диаграммы. Предлагаются базовая сортировка и поиск по игрокам/событию, поскольку иначе список учебника из 847 записей неудобен. +3. Открыть запись и показывать доску, дерево нотации, корневые/межходовые/вариантные комментарии, NAG и исходную разметку `csl`/`cal`. Обрабатывать FEN, начальный ход чёрных и записи без ходов. +4. Навигация по основной линии и любому варианту мышью/клавиатурой, переход в начало/конец, возврат из ветки; активный узел всегда однозначен. Переворот доски — небольшое полезное дополнение. +5. Новая партия и редактирование ходов/вариантов открытой партии, легальный ввод ходов, выбор превращения, исправление последнего ввода. Ввод альтернативы из просмотренной позиции должен создавать ветку, а не незаметно стирать продолжение. Эти границы редактирования подтверждены в `docs/decisions.md`. +6. Менеджер локальных UCI-движков: добавить путь, выбрать активный, запуск/остановка анализа, как минимум оценка, глубина и PV. Выбранную PV можно просматривать на доске в отдельном состоянии и возвращаться к партии. Предлагается MultiPV, если пользователь ожидает одновременно несколько строк. +7. Стрелка лучшего хода по актуальной позиции. При быстрой навигации результаты старого поиска не присваиваются новой позиции. При смене движка старый процесс корректно завершается. +8. Копирование текущей партии в PGN и сохранение отдельным файлом с ветками, FEN, всеми тегами, комментариями и NAG; отдельное поведение для диагностированных повреждений. Исходный файл не меняется при просмотре и анализе. Сохранение отдельным файлом подтверждено в `docs/decisions.md`. +9. Выбор фигур/доски, базовые звуки с выключателем, сохранение настроек. Использовать только ресурсы с проверенной лицензией и атрибуцией. +10. Возврат к списку с сохранённым положением и обработка несохранённой введённой партии. Конкретный механизм черновика/подтверждения уточнить до реализации. + +### Позже + +- Интерактивные вопросы `tqu`, тренировка окончаний, скрытие ответов и учёт результатов. +- Полноценное редактирование тегов/комментариев/NAG и управление целыми базами: объединение, удаление, дедупликация, экспорт выборки. +- Индексация миллионов записей, поиск позиции/структуры, дебютное дерево и расширенные фильтры. +- Пакетный анализ партий, сохранение оценок движка, автоматическое обнаружение ошибок, график оценок. +- Редактор произвольной позиции и вставка FEN, если пользователь не включит их в первый релиз. +- Дополнительные протоколы движков, варианты шахмат, сетевые функции. +- Конвертация ChessBase и автоматическое восстановление испорченного текста — отдельные проекты, не предпосылки PGN-MVP. + +## 10. Следствия для архитектуры и выбора стека + +**Рекомендации, выведенные из корпуса:** + +- UI-фреймворк должен нормально поддерживать длинную интерактивную нотацию с вложенностью минимум 7 и крупные многострочные комментарии. Демонстрация одной доски недостаточна для оценки фреймворка. +- Модель партии: корень с исходной позицией/комментарием и дерево узлов с устойчивым ID, родителем, упорядоченными детьми, ходом, NAG, комментариями и сохранёнными директивами. PV движка — отдельная временная модель, не автоматически добавленная ветка партии. +- Источник: путь, исходная кодировка, идентификатор версии/отпечаток, байтовые диапазоны записей и сырые данные для диагностики и сохранности. Смещения нужно вычислять по байтам оригинала, а не по длинам строк после перекодировки. +- Парсер должен сохранять произвольные заголовки и расширения, возвращать диагностику с покрытием текста, не скрывать нераспознанные токены. FEN `fullmove=0` требует явной политики совместимости: исходное значение хранить, игровую позицию при необходимости нормализовать с диагностикой. +- Отдельно проверить поддержку null move библиотекой правил и парсером: это не гарантируется поддержкой стандартного SAN. Отказ импортировать 189 записей с такими ходами суммарно был бы заметной потерей пригодности продукта. +- Тяжёлая работа — вне UI-потока. Первая согласованная нагрузка — сотни/тысячи аннотированных партий. Для будущих больших баз можно иметь пересоздаваемый локальный индекс метаданных и ленивую загрузку дерева выбранной записи; необходимость конкретной СУБД на двух небольших примерах не доказана. +- UCI-обвязка должна передавать исходную позицию и известную историю ходов, а не только текущий FEN. Для импортированного фрагмента более ранняя история объективно неизвестна; для учебных null move нужна отдельная согласованная политика. +- Перед утверждением библиотек провести маленький совместимый с будущим стеком эксперимент: чтение этих 896 записей, диагностика №335, семь уровней RAV, null move, FEN с нулём, сохранение комментариев и обратный экспорт. Это следующий этап, а не выполненная здесь проверка Rust-стека. + +## 11. Пробелы требований и вопросы пользователю + +### Влияют на архитектуру или границы первого релиза + +Уже решено в `docs/decisions.md`: открытый исходный код с возможностью GPL-совместимого стека; сотни/тысячи аннотированных партий; редактирование ходов/вариантов и отдельный PGN-файл. Повторно спрашивать об этих границах не требуется. + +1. Каковы конкретные целевые время импорта и расход памяти для согласованной нагрузки в тысячи партий? Предоставленные книги малы по размеру, но богаты аннотациями. +2. «Тот же стек, что Artcraft» — обязательное условие или предпочтение? Допустима ли другая Rust-архитектура, если она лучше подходит для Linux и такого дерева нотации? +3. Какие целевые дистрибутивы/архитектуры, Wayland/X11 и способ установки нужны? Это не определяется только словом Linux. +4. Нужны ли автосохранение черновиков и восстановление после перезапуска? Как вести себя при закрытии изменённой партии? Ходы, варианты, копирование и сохранение отдельным PGN уже входят в первый объём. +5. Как должен вести себя экспорт повреждённой записи №335: копирование сырого исходника, исправление с предпросмотром или иной вариант? Нормализованное дерево здесь уже не содержит весь текст. +6. Анализ — интерактивный анализ текущей позиции или также автоматический проход по всей партии? В ТЗ явнее описан первый сценарий. Сколько одновременно PV и какие параметры движка доступны пользователю? + +### Можно согласовать при детализации интерфейса + +7. Партия открывается отдельным системным окном, вкладкой или экраном внутри приложения? Важен ли одновременный просмотр нескольких партий? +8. Нужны ли импорт PGN/FEN из буфера, редактор позиции, поиск партии и поиск позиции уже в MVP? +9. Должны ли стрелки/подсветки автора показываться по умолчанию вместе с анализом? Нужно ли интерактивно решать вопросы `tqu` или пока достаточно просмотра? +10. Какая перспектива оценки движка предпочтительна: всегда за белых или за сторону хода? Как отображать матовую оценку? +11. Нужны ли русский и английский интерфейсы, какие сочетания клавиш привычны пользователю, должен ли звук воспроизводиться при перемещении по нотации? +12. Каков предел ресурсов движка по умолчанию: Threads, Hash, MultiPV? Как обрабатывать перемещённый или недоступный исполняемый файл? + +## 12. Предлагаемые критерии приёмки + +Ниже — **будущие** приёмочные проверки, а не заявление о готовом приложении. + +| ID | Проверка | Наблюдаемый результат | +| --- | --- | --- | +| PGN-01 | Импорт обоих оригиналов | 49 и 847 записей; оригинальные SHA-256 не меняются; интерфейс продолжает отвечать | +| PGN-02 | Кодировки | `Hübner`, `Tromsø` и русский текст читаемы; доступна ручная смена кодировки; исходные `~~`/`o^` не исправляются самовольно | +| PGN-03 | Полное дерево | 8 340 и 53 923 узла, 829 и 6 322 RAV; все ветки доступны, в том числе глубина 7 в учебнике №568 | +| PGN-04 | Исходная позиция | Все 846 FEN открываются согласно политике совместимости; 72 случая полного хода `0` диагностируются без потери записи; 268 стартов чёрных показывают правильную сторону хода | +| PGN-05 | Позиции без ходов | №5, №21, №251, №717 учебника открывают диаграмму и начальный комментарий; навигация не падает | +| PGN-06 | Null move и специальные ходы | Сохраняются все 269 `--`; корректно отображаются рокировки, 38 взятий на проходе и 34 превращения не в ферзя во всех ветках | +| PGN-07 | Аннотации | Сохраняются 835 и 12 705 NAG, комментарии корня и перед вариантами; `csl`/`cal` отображаются, все 252 `tqu` сохраняются без потери payload | +| PGN-08 | Повреждённая запись | №335 получает адресную диагностику строк 8264–8266; непокрытый русский текст не исчезает бесследно; остальные записи доступны | +| PGN-09 | Экспорт и повторный импорт | Для корректных записей сохраняются порядок вариантов, ходы, позиция, теги, NAG и текст/директивы комментариев; допустима оговорённая нормализация пробелов, CRLF и синтаксического форматирования; для №335 выполняется отдельно согласованная политика | +| UX-01 | Клавиатура и мышь | Один и тот же узел выбран в нотации и на доске; переход из вложенной ветки к родителю восстанавливает ожидаемую позицию | +| UX-02 | Возврат и история | После закрытия партии восстановлены база, строка, фильтр и прокрутка; после перезапуска доступны недавние базы и настройки | +| EDIT-01 | Ввод и редактирование партии | Незаконный ход отвергается без порчи состояния; рокировка, en passant и выбор всех четырёх превращений работают; альтернативный ход создаёт вариант; PGN копируется, сохраняется отдельным файлом и перечитывается | +| UCI-01 | Интерактивный анализ | Выбранный локальный движок запускается, выдаёт оценку/глубину/PV, останавливается и освобождает процесс при завершении приложения | +| UCI-02 | Гонки анализа | При быстрой смене узлов устаревшие сообщения и стрелки не отображаются как анализ нового узла; ошибка/выход движка не закрывает приложение | +| UCI-03 | Просмотр PV | Перемещение по PV и возврат не изменяют дерево, комментарии и экспорт исходной партии | +| DATA-01 | Сохранность | Просмотр, анализ, смена темы и кодировки не записывают в исходные PGN; результаты диагностики доступны повторно | +| PERF-01 | Отзывчивость | Импорт и анализ выполняются вне UI-потока, есть прогресс/отмена; численные пределы времени/памяти утверждаются на целевом Linux и базе согласованного размера | +| PREF-01 | Настройки | Выбор движка, темы доски/фигур и отключение звука сохраняются после перезапуска | + +Перед выпуском дополнить корпус отдельными небольшими фикстурами, которых нет в книгах: UTF-8, `;`-комментарии, экранирование в тегах, неизвестная директива, повреждённый FEN, некорректный SAN, оборванный файл, результат без ходов, изменение файла на диске и сильно запаздывающий UCI-ответ. Эти проверки ещё не выполнены. diff --git a/docs/research/reuse-and-assets.md b/docs/research/reuse-and-assets.md new file mode 100644 index 0000000..93bb6fc --- /dev/null +++ b/docs/research/reuse-and-assets.md @@ -0,0 +1,32 @@ +# Повторное использование Lichess и ресурсов + +Проверено 2026-10-17 по первоисточникам. Это подбор кандидатов, ресурсы ещё не импортированы в приложение. + +## Что можно использовать + +- **Chessground** — готовая TypeScript-доска Lichess: drag-and-drop, стрелки, подсветка, анимация, темы и изменение размера. Шахматных правил внутри нет. Хорошо подходит к web UI/Tauri; для полностью нативного Rust UI прямого подключения без webview нет. Лицензия GPL-3.0-or-later. +- **Lila** — исходники самого Lichess; полезны как референс взаимодействия. Разворачивать весь сервер для локального PGN-приложения не требуется. Основная лицензия AGPL-3.0-or-later, но у многих ресурсов собственные условия. +- Для нативной доски можно использовать SVG-фигуры независимо от реализации web-доски, проверив лицензию конкретного набора. + +## Кандидаты для первой версии + +| Ресурс | Проверенная запись в COPYING.md Lila | Предложение | +| --- | --- | --- | +| `public/piece/chessnut` | Alexis Luengas, Apache 2.0 | Один из начальных наборов SVG | +| `public/piece/fantasy`, `spatial`, `celtic` | Maurizio Monge, MIT | Дополнительный визуально отличный набор | +| `public/piece/cburnett` | Colin M. L. Burnett, GPLv2+ | Знакомый пользователям набор, если выбран совместимый путь лицензирования | +| `public/piece/rhosgfx` | RhosGFX, CC0 1.0 | Ещё один кандидат после визуальной оценки | +| `public/sounds/sfx`, `piano`, `nes`, `futuristic` | Enigmahack, AGPLv3+ | Выбирать конкретный набор с сохранением авторства и условий | + +Для простой двухцветной доски достаточно собственных цветов и отрисовки; текстуры добавлять отдельными ресурсами. Короткие звуки можно создать самостоятельно, если это окажется удобнее выбранного стороннего набора. + +Нельзя приписывать всем ресурсам Lichess одну лицензию: в списке есть CC BY-NC-SA, неизвестные условия и отдельные ограничения на логотипы. Выбор модели распространения продукта нужен до окончательного выбора заимствуемого кода и наборов. Для каждого включённого ресурса сохранять исходный URL, ревизию, автора, лицензию и отметку об изменениях в будущем `THIRD_PARTY_NOTICES.md`. + +## Источники + +- https://github.com/lichess-org/chessground — README, возможности и лицензия. +- https://raw.githubusercontent.com/lichess-org/lila/master/COPYING.md — лицензии проекта и отдельных ресурсов. +- https://github.com/LexLuengas/chessnut-pieces — первоисточник набора Chessnut, ссылка из COPYING.md. +- https://github.com/maurimo/chess-art — первоисточник наборов Maurizio Monge, ссылка из COPYING.md. + +Лицензии последних двух репозиториев перед скачиванием фиксировать на выбранной ревизии; в этом исследовании условия для них проверены по реестру Lila. diff --git a/docs/research/stack-options.md b/docs/research/stack-options.md new file mode 100644 index 0000000..2294650 --- /dev/null +++ b/docs/research/stack-options.md @@ -0,0 +1,260 @@ +# Выбор стека Linux chess desktop: ArtCraft, Tauri, GTK4 + +Дата исследования: **2026-10-17**. Основание требований: `техническое задание.txt` в корне проекта. Авторская область: архитектура и первичные технические источники. + +Актуализация по `docs/decisions.md`: пользователь подтвердил открытый исходный код и допустимость GPL-совместимого стека; первая нагрузка — сотни/тысячи учебных партий; редактирование v1 — ходы, варианты, копирование PGN и сохранение отдельным файлом. Полное редактирование комментариев/заголовков и массовая перезапись исходной базы отложены. Сравнение богатых редакторов и миллионных таблиц ниже описывает запас развития, а не критерии v1. + +## 1. Вывод + +**Рекомендуется Rust + egui/eframe + wgpu, по образцу PhotoCraft, с выборочным использованием `storytold/craft-libs`.** Это непосредственно отвечает желанию пользователя использовать стек Craft Apps. Вариант технически подходит для доски, анализа UCI, таблиц партий и дерева вариантов. Главный риск — качество редактируемой нотации, работы с текстом и клавиатурной навигации: специализированного готового шахматного редактора в PhotoCraft нет. + +Рекомендация условна в двух конкретных местах: + +1. Проверить вертикальным прототипом нотацию с вложенными вариантами, отображением длинных русских комментариев, выбором/вводом ходов, а также Linux Wayland/HiDPI. Решение о UI принимать после этого, до масштабной реализации экранов. Полный редактор текста не блокирует v1. +2. Зафиксировать конкретную лицензию приложения: **`shakmaty` и `pgn-reader` — GPL-3.0-or-later**, а не MIT/Apache. Практичный вариант для продукта с этими связанными библиотеками — выпуск под GPL-3.0-or-later с выполнением условий распространения. Допустимость GPL-совместимого стека уже подтверждена пользователем; конкретная лицензия ещё не утверждена. + +**Tauri 2 + React/TypeScript — сильный резерв**, если прототип покажет неприемлемую стоимость текстового UI на egui. GTK4/Relm4 хорош для глубокой интеграции с Linux, но слабее соответствует прямому предпочтению пользователя и требует своей реализации шахматного представления. + +### Обозначения достоверности + +- **Подтверждено** — прочитаны первичный manifest, исходник либо документация разработчика. Заявление README о качестве/скорости остаётся заявлением автора, а не нашим измерением. +- **Оценка / предложение** — инженерный вывод для этого проекта; не обещание библиотеки. +- **Не проверено** — сборка, запуск или измерение здесь не выполнялись. В исследовании не проводились бенчмарки, runtime-проверка Linux и лицензионный аудит всех транзитивных зависимостей. +- Версии ниже — наблюдаемые значения в manifests на дату исследования, **не автоматически последние стабильные релизы** и не готовый согласованный `Cargo.lock`. + +## 2. Что фактически использует ArtCraft + +### 2.1. Нужно различать Craft Apps и основной ArtCraft + +**Подтверждено.** [Каталог Craft Apps](https://getartcraft.com/apps) перечисляет 13 приложений и заявляет native Rust без Electron/webview. PhotoCraft отмечен как early alpha. [Организация storytold](https://github.com/storytold) содержит несколько продуктов, а не один общий UI framework. + +Исследованные снимки репозиториев: + +| Репозиторий | SHA, полученный через GitHub API | Дата коммита UTC | +|---|---|---| +| `storytold/photocraft` | `06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3` | 2026-10-17 | +| `storytold/craft-libs` | `82a24b006eefa036b43c09a67fb9a3fbd17ffe63` | 2026-10-17 | +| `storytold/artcraft` | `d4e4ac69bbd93d237eaf5d0260bc6a5ff3a5e373` | 2026-10-11 | +| `niklasf/shakmaty` | `fd6296926137d89192c7810a0894346a03f749ef` | 2026-10-11 | +| `franciscoBSalgueiro/en-croissant` | `a91f32b1c57eb93acad92f9778205eac7b4345d9` | 2026-10-17 | + +В **основном `storytold/artcraft`** одновременно присутствуют: + +- `crates/desktop/artcraft`: Tauri 2, плагины dialog/log/upload/http, Rust backend. Корневой workspace указывает этот crate в `default-members`. +- `frontend/package.json`: React 18.3.1, TypeScript 5.8.3, Vite 6, Nx 21, Tailwind 3, React-компоненты. +- `artcraft-native`: egui/eframe 0.36, backend **glow**, `egui_extras`, `resvg`, `rfd`, `rodio`, Tokio. Несмотря на описание «no webview», manifest содержит `wry` с комментарием о браузерном окне авторизации Midjourney. Это не основание считать основной UI этого target вебовым, но исключает утверждение «ни одного webview нигде». + +Источники: [workspace ArtCraft](https://github.com/storytold/artcraft/blob/d4e4ac69bbd93d237eaf5d0260bc6a5ff3a5e373/Cargo.toml), [Tauri crate](https://github.com/storytold/artcraft/blob/d4e4ac69bbd93d237eaf5d0260bc6a5ff3a5e373/crates/desktop/artcraft/Cargo.toml), [frontend](https://github.com/storytold/artcraft/blob/d4e4ac69bbd93d237eaf5d0260bc6a5ff3a5e373/frontend/package.json), [native crate](https://github.com/storytold/artcraft/blob/d4e4ac69bbd93d237eaf5d0260bc6a5ff3a5e373/artcraft-native/Cargo.toml). + +**Вывод:** корректная формулировка нашего выбора — «стек PhotoCraft / native Craft Apps», а не «все проекты ArtCraft используют только egui» или «ArtCraft — это Tauri». + +### 2.2. PhotoCraft: workspace и UI + +**Подтверждено по manifests:** + +```toml +[workspace] +resolver = "3" +members = ["crates/*", "apps/*", "xtask"] +default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] + +[workspace.package] +version = "0.9.0" +edition = "2024" +license = "MIT OR Apache-2.0" +rust-version = "1.95" +``` + +Корневые зависимости: `egui = 0.36`, `eframe = 0.36`, `egui_kittest = 0.36`, `rfd = 0.17`, `serde`, `serde_json`, `rayon`; `craft-ui` подключён по git с `rev = 5c874d51eeb3de70e735c8ce87a59a7dedd47675` и feature `serde`. + +Desktop `apps/photocraft` включает у eframe `wgpu`, `accesskit`, `wayland`, `x11`, `persistence`. `crates/ui-egui` подключает `egui_extras 0.36` с `svg`. Есть `arboard` для clipboard, `rfd` для диалогов, platform-specific интеграция. Это нативный immediate-mode UI, не HTML/CSS и не GTK4/Relm4. `wgpu` обслуживает также отдельный графический compositor приложения; для шахмат такой compositor не требуется. + +В workspace разделены модель документа (`doc`), операции (`ops`), engine, I/O, CPU/GPU rendering, UI, CLI, web target, testkit. **Предлагается перенять границы слоёв и command-driven подход, а не фотообрабатывающий движок.** + +Источники: [Cargo.toml](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/Cargo.toml), [desktop Cargo.toml](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/apps/photocraft/Cargo.toml), [UI Cargo.toml](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/crates/ui-egui/Cargo.toml), [README](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/README.md). + +### 2.3. Реально переиспользуемое + +| Компонент | Подтверждённое назначение | Предлагаемое применение и границы | +|---|---|---| +| `craft-ui` | Небольшие egui-компоненты: SVG catalogs, доступные icon buttons, tabs, splits, resize handles, toolbar overflow, theme helpers, transactional docking | Панели «базы / партии / доска / нотация / анализ», кнопки и вкладки. Не предоставляет chessboard, PGN editor, готовый complete theme, локализацию или command engine | +| `craft-ui::docking` | Валидируемая модель layout и optional `DockArea`; floating groups внутри текущего viewport | Для изменяемого пользователем layout. Отдельные OS-окна не появляются автоматически. В MVP можно начать с фиксированных resizable splits | +| `craft-settings` | TOML, XDG-каталоги, backup, migration, восстановление повреждённых настроек, atomic save | Настройки движков, темы, фигур, звука. Своя схема и миграции. Контракт конкуренции — best effort, last writer wins, не межпроцессная блокировка | +| `craft-atomic` | Запись во временный соседний файл и замена, streaming writer, fault injection | Экспорт PGN. Проверять конкретную версию API; сохранение owner/ACL/xattrs/hardlinks не гарантируется, а durability имеет оговорки в README | +| PhotoCraft architecture / testkit patterns | Data model → commands → thin UI; headless tests и UI snapshots | Перенять организацию и сценарии тестирования. Графическое ядро и весь UI crate слишком связаны с фото-доменом для подключения в chess app | +| PhotoCraft fonts/icons | В `ATTRIBUTION.md` перечислены Inter/JetBrains Mono, Lucide и отдельные другие лицензии | Возможны точечные заимствования с attribution; обычно проще брать Lucide и шрифты непосредственно upstream | + +**Подтверждено:** `craft-libs` имеет `MIT OR Apache-2.0`, edition 2024, Rust 1.95; `craft-ui` использует egui 0.36. Подключение по pinned git revision — документированный upstream способ. Библиотека не содержит готовых иконок, шрифтов и application engines. + +**Оценка:** это настоящий повторно используемый слой, но не зрелый универсальный «ArtCraft SDK» с гарантией стабильности API. Нужны собственный адаптер и pin SHA. Нельзя механически заменить egui на latest: на дату исследования docs.rs уже показывает `egui_extras 0.37.0`, тогда как PhotoCraft/craft-ui остаются на 0.36. Две несовместимые линии egui создадут разные типы `Ui`/`Context`. + +Источники: [craft-libs workspace](https://github.com/storytold/craft-libs/blob/82a24b006eefa036b43c09a67fb9a3fbd17ffe63/Cargo.toml), [README](https://github.com/storytold/craft-libs/blob/82a24b006eefa036b43c09a67fb9a3fbd17ffe63/README.md), [craft-ui README](https://github.com/storytold/craft-libs/blob/82a24b006eefa036b43c09a67fb9a3fbd17ffe63/crates/ui/README.md), [settings](https://github.com/storytold/craft-libs/blob/82a24b006eefa036b43c09a67fb9a3fbd17ffe63/crates/settings/README.md), [atomic](https://github.com/storytold/craft-libs/blob/82a24b006eefa036b43c09a67fb9a3fbd17ffe63/crates/atomic/README.md). + +### 2.4. Лицензии PhotoCraft и материалов + +**Подтверждено:** код PhotoCraft dual-licensed MIT OR Apache-2.0. Есть `NOTICE`; third-party assets сохраняют свои лицензии. Например, Inter и JetBrains Mono — SIL OFL 1.1, большинство Lucide — ISC, часть Feather-derived иконок имеет дополнительные MIT notices, одна иконка — CC BY 3.0. Логотипы, wordmark и бренд в `docs/brand` не покрываются общей open-source лицензией; README требует удалить их из forks/modified versions. + +**Вывод:** заимствование generic-кода допустимо при соблюдении выбранной лицензии и notices. Не переносить весь asset-каталог под предположением «всё MIT» и не использовать ArtCraft branding для нашего продукта. + +Источники: [MIT](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/LICENSE-MIT), [Apache](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/LICENSE-APACHE), [NOTICE](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/NOTICE), [ATTRIBUTION](https://github.com/storytold/photocraft/blob/06ad0d5c9561d7499dc6f25ce8041b60db2ea1d3/ATTRIBUTION.md). + +## 3. Сравнение UI-стеков применительно к ТЗ + +Таблица ниже — **инженерная оценка**, опирающаяся на подтверждённые API. Все три варианта могут использовать одинаковые Rust crates для шахмат, PGN, SQLite и UCI. + +| Критерий | PhotoCraft-style: egui/eframe + wgpu | Tauri 2 + React/TypeScript | GTK4 + gtk4-rs/Relm4 | +|---|---|---|---| +| Желание «как Craft Apps» | Наиболее прямое соответствие выбранному PhotoCraft | Подтверждён в основном ArtCraft, но отличается от PhotoCraft и каталога native Craft Apps | В исследованных PhotoCraft manifests отсутствует | +| Доска, SVG, стрелки | Painter + SVG loaders/resvg, кэш по размеру/DPI; взаимодействия пишем сами | DOM/CSS/SVG; доступен Chessground с готовыми interactions | Custom DrawingArea/Snapshot, SVG через доступный loader/resvg; interactions свои | +| Нотация, комментарии, варианты | Clickable tokens + stable IDs, отдельные TextEdit для комментариев; сложный rich-text editor требует работы | DOM хорошо подходит flowing notation; редакторы текста и browser selection доступны, но связь текста с деревом ходов всё равно наша | TextView/TextBuffer tags, marks и отдельная модель дерева; сложный inline chess UX также проектируется | +| Таблица большого числа партий | `egui_extras::TableBody::rows` рисует видимые строки; SQL pagination отдельно | TanStack Virtual и аналогичные библиотеки; paged Rust API вместо передачи всей базы через IPC | ColumnView/ListView перерабатывают видимые widgets; GListModel с ленивой загрузкой | +| Дерево вариантов | Собственная domain-модель + виртуализированная/кэшируемая проекция | Собственная domain-модель + DOM tree/notation components | GtkTreeListModel/TreeExpander для древовидного вида; flowing notation отдельно | +| Звук | `rodio` в audio service, preload samples | Web Audio либо тот же Rust audio service | `rodio` либо системный audio backend | +| UCI child process | Tokio/std worker, каналы → UI repaint | Rust backend запускает engine; IPC доставляет сжатые результаты | Tokio/std worker → сообщения Relm4/GLib main loop | +| Linux desktop | Wayland/X11, portal dialogs; качество интеграции проверить | WebKitGTK runtime; web platform и Rust↔TS boundary | Сильная интеграция GTK/Pango/IME; другой визуальный характер | +| Стоимость сложности | Один основной язык; больше собственного board/notation UI | Два языка, IPC и два dependency graph; больше готового web UI | Rust + GObject/GLib concepts, системные GTK dependencies | +| Главный риск | Нотация, selection/focus/IME/accessibility, GPU и Wayland детали | WebKitGTK отличия, разрастание frontend, несогласованное состояние Rust/TS | Время на custom chess UI и GObject adapters, отклонение от ArtCraft-стиля | + +### Подтверждённые факты для сравнения + +- egui Extras `rows`/`heterogeneous_rows` рисуют только видимые строки. `heterogeneous_rows` всё равно перебирает высоты для определения общей геометрии; это не бесплатный доступ к произвольно длинной нотации. Источник: [table.rs для 0.36.0](https://github.com/emilk/egui/blob/0.36.0/crates/egui_extras/src/table.rs). +- Tauri использует Rust и HTML в OS webview, поддерживает произвольный frontend; MIT OR Apache-2.0. Linux prerequisites включают WebKitGTK 4.1. Источники: [архитектура Tauri](https://v2.tauri.app/concept/architecture/), [Linux prerequisites](https://v2.tauri.app/start/prerequisites/). +- GTK list widgets создают ограниченный набор list items и повторно привязывают их к моделям. Есть TreeListModel/TreeExpander. Виртуализация widgets не исключает память под загруженную модель. Источник: [GTK List Widget Overview](https://docs.gtk.org/gtk4/section-list-widget.html). +- Relm4 — Elm-inspired Rust layer над gtk4-rs; в просмотренном workspace 0.11.0, gtk4 0.11.2, Rust 1.93, MIT OR Apache-2.0. gtk4-rs — MIT; GTK — LGPL с отдельными исключениями для некоторых файлов. Источники: [Relm4 workspace](https://github.com/Relm4/Relm4/blob/main/Cargo.toml), [gtk4-rs workspace](https://github.com/gtk-rs/gtk4-rs/blob/main/Cargo.toml), [GTK README](https://github.com/GNOME/gtk/blob/main/README.md), [GTK COPYING](https://github.com/GNOME/gtk/blob/main/COPYING). +- Chessground — browser TypeScript chess UI, GPL-3.0-or-later; поддерживает drag/click, animation, arrows/circles, FEN и themes, **не содержит шахматных правил**. Это прямой кандидат только для web UI, не готовый egui widget. Источник: [Chessground README](https://github.com/lichess-org/chessground/blob/master/README.md). + +### Важная оговорка Linux + +**Подтверждено по PhotoCraft README:** на используемом winit 0.30 отсутствует Wayland file drag-and-drop; предлагается File → Open либо XWayland. XWayland с fractional scaling может давать размытие. Это конкретное ограничение наблюдаемого стека, не вечное свойство Rust или egui. Для нашего MVP открыть PGN через file dialog достаточно, но drag-and-drop нельзя обещать без проверки. + +**Предложение:** начать с desktop tarball/AppImage или обычного пакета. Flatpak отдельно проверить на запуске выбранного пользователем движка и доступе к его NNUE/конфигурационным файлам: наличие файлового портала само по себе не гарантирует запуск произвольного host executable внутри sandbox. Ни один UI framework не решает это автоматически. + +## 4. Шахматное ядро и PGN + +### 4.1. `shakmaty` + +**Подтверждено:** legal move generation, применение ходов, проверки mate/stalemate/insufficient material/outcome, FEN/SAN/UCI notation, стандартные шахматы и варианты, включая Chess960, Zobrist hashing. Syzygy — отдельный `shakmaty-syzygy`, PGN — отдельный `pgn-reader`. + +В текущем монорепозитории manifest `shakmaty` показывает 0.30.2; workspace задаёт **GPL-3.0-or-later**, edition 2024 и Rust 1.97. Для отдельных вариантов существует feature `variant`. Это библиотека правил, а не аналитический engine, не UI и не UCI process supervisor. `uci::UciMove` работает с нотацией ходов; не управляет обменом `uci/isready/go/info` с процессом. + +Источники: [workspace](https://github.com/niklasf/shakmaty/blob/fd6296926137d89192c7810a0894346a03f749ef/Cargo.toml), [crate manifest](https://github.com/niklasf/shakmaty/blob/fd6296926137d89192c7810a0894346a03f749ef/shakmaty/Cargo.toml), [README](https://github.com/niklasf/shakmaty/blob/fd6296926137d89192c7810a0894346a03f749ef/shakmaty/README.md). + +### 4.2. `pgn-reader` + +**Подтверждено:** streaming visitor parser; reader не строит дерево и не проверяет легальность ходов. События включают tags, SAN, NAG, comments, begin/end variation, outcome. Visitor выбирает, как хранить игру и что пропускать. В текущем workspace crate имеет версию 0.29.1, зависит от `shakmaty 0.30` и наследует **GPL-3.0-or-later**. + +Критические подробности из исходника: + +- `begin_variation` по умолчанию возвращает `Skip(true)` — если не переопределить, варианты будут пропущены! +- Очень длинные комментарии могут приходить через `partial_comment`, завершаясь `comment`; нужно собирать их в одну логическую запись. +- Парсер допускает вызов `end_variation` без соответствующего начала на некорректном PGN; наш visitor должен обрабатывать это без panic. +- README прямо требует собственное in-memory представление. Готовый редактируемый variation tree и PGN writer этот API не предоставляет. + +Источники: [README](https://github.com/niklasf/shakmaty/blob/fd6296926137d89192c7810a0894346a03f749ef/pgn-reader/README.md), [manifest](https://github.com/niklasf/shakmaty/blob/fd6296926137d89192c7810a0894346a03f749ef/pgn-reader/Cargo.toml), [Visitor](https://github.com/niklasf/shakmaty/blob/fd6296926137d89192c7810a0894346a03f749ef/pgn-reader/src/visitor.rs). Старый [rust-pgn-reader manifest](https://github.com/niklasf/rust-pgn-reader/blob/master/Cargo.toml) содержит 0.27.0, `shakmaty 0.28` и старую SPDX-запись `GPL-3.0+`; его нельзя смешивать с документацией нового API. + +### 4.3. Предлагаемая модель партии + +Это **проектное решение**, не возможность, уже реализованная ArtCraft: + +- `GameDocument`: ordered tags, root position/FEN, результат, arena узлов со стабильными `NodeId`, revision/dirty state. +- `MoveNode`: parent, ordered children (mainline — первый), move, NAGs, комментарии до/после хода, поддерживаемые annotations; текущий выбор узла хранится отдельно от документа. +- Стек контекстов при чтении RAV: вариант начинается от позиции **перед** заменяемым ходом. На закрытии варианта восстанавливаются родительская линия и её позиция. +- Команды `AddMove`, `PromoteVariation`, `DeleteVariation` формируют undo/redo. `SetComment` и `SetHeaders` — расширение после v1. Навигация и preview PV не меняют партию и не ставят dirty. +- Нотация — проекция дерева с token → NodeId mapping. На первом этапе редактирование ходов через доску/SAN input, вариантов через контекстное меню; исходные комментарии отображаются и сохраняются. Для дальнейшего редактирования комментариев можно использовать TextEdit. Полноценный произвольный rich-text PGN editor не входит в v1. +- PGN export реализовать отдельно; сохранять unknown tags и порядок вариантов, FEN/SetUp, NAG, Unicode и комментарии. Цель round-trip — семантическое сохранение; побайтовую идентичность без хранения исходных фрагментов обещать нельзя. +- `[%eval]`, `[%clk]`, `[%cal]`, `[%csl]` — текстовые расширения комментариев: разобрать нужные нам, неизвестные сохранить. Политика кодировок и восстановления ошибочных партий требует проверки на локальных примерах. +- По проектным инвариантам `AGENTS.md` реальные материалы содержат legacy-кодировки, FEN с fullmove=0 и учебный `--`. Это сведения команды о корпусе, а не результат повторной проверки в этом исследовании. Нужен compatibility layer: сохранять исходные bytes/токены, диагностировать нормализацию, представлять учебный null move отдельно от обычного легального хода. Поддержку этих случаев нельзя вывести только из списка функций shakmaty/pgn-reader. + +## 5. SQLite и большие базы + +### Кандидаты + +| Библиотека | Подтверждено | Оценка для проекта | +|---|---|---| +| `rusqlite` | MIT, SQLite wrapper, `bundled` собирает SQLite, prepared statements/transactions и optional backup/hooks | **Первый выбор**: один DB worker владеет connection, bounded requests/results, простой SQL и контроль импорта | +| `sqlx` | MIT OR Apache-2.0; async database layer, SQLite и migration features | Подходит при общей async-архитектуре; для одной локальной базы сложнее, чем rusqlite worker. Async API не превращает SQLite в многописательную БД | +| `diesel` | MIT OR Apache-2.0, typed query DSL и SQLite support | Подходит команде с опытом Diesel; для динамической таблицы/поиска не обязателен. Не копировать автоматически комбинацию Diesel+rusqlite из En Croissant | + +Источники: [rusqlite manifest](https://github.com/rusqlite/rusqlite/blob/master/Cargo.toml), [SQLx manifest](https://github.com/launchbadge/sqlx/blob/main/Cargo.toml), [Diesel manifest](https://github.com/diesel-rs/diesel/blob/master/diesel/Cargo.toml). + +**Предлагаемая стратегия:** PGN — поддерживаемый пользовательский формат; SQLite — внутренний индекс/кэш метаданных, поиска и состояния импорта. Это не вводит поддержку проприетарных форматов ChessBase. + +Для согласованных сотен/тысяч партий SQLite — удобный кандидат на persistence/index, а не обязательное условие MVP-производительности. Прототип может начать с фоновой загрузки метаданных в память за тем же repository API; вводить сложные keyset/rank индексы только по измерениям. Миллионы партий не являются приёмочным критерием v1. + +1. Background streaming import с прогрессом/отменой; batch transactions, один writer. Не парсить все партии в деревья при открытии списка. +2. Индексировать header fields, результат, идентификатор партии и источник. Для открытой партии загружать movetext/дерево по требованию. +3. Хранить source fingerprint и версию индекса. Вариант «byte offset + length» требует отдельно проверенного учёта буферизации и границ партий; произвольный `stream_position()` под buffered parser не гарантирует правильный offset. Для сжатого PGN offsets не являются прямым random access; можно сохранять извлечённый PGN каждой партии в SQLite. +4. UI получает только страницу метаданных и общее число результатов; не сериализовать миллионы строк через IPC и не выполнять SQL в draw callback. +5. Для последовательной навигации подходят keyset pages; для прыжка scroll thumb в произвольную позицию нужны отдельная стратегия range/rank и измерение. Виртуализация таблицы сама не решает стоимость сортировки и deep OFFSET. +6. В v1 экспортировать новую/изменённую партию отдельным файлом; исходную многопартийную базу сохранять. Массовая перезапись исходника — отложенный сценарий, для которого позднее потребуются собственные правила и atomic replace. + +Слово «pure Rust» описывает архитектурное предпочтение UI и кода приложения: `rusqlite`/SQLite используют C, ОС и графические/audio драйверы тоже не становятся Rust. Это осознанная практическая зависимость, а не нарушение функционального ТЗ. + +## 6. UCI: библиотеки и supervisor + +**Подтверждено:** `vampirc-uci 0.11.1` — Apache-2.0 parser/serializer UCI, с `parse_one`, `parse_with_unknown`, option/info/bestmove. Сам процесс библиотека не запускает. Автор README рекомендует реализовывать I/O современным async stack; до 1.0 не обещает окончательную стабильность API. Не включать optional `chess` feature, если уже используем `shakmaty`: это добавит вторую модель шахмат без необходимости. + +**Первый кандидат:** `tokio::process::Command` + `vampirc-uci` за нашим adapter. **Второй:** std::process + выделенные reader threads и тот же parser, если не требуется Tokio в остальном приложении. **Третий, запасной:** собственный узкий UCI codec, если тесты покажут проблемы с расширениями конкретных движков; это дополнительная стоимость корректности, а не готовое преимущество. + +Источники: [vampirc manifest](https://github.com/vampirc/vampirc-uci/blob/master/Cargo.toml), [README](https://github.com/vampirc/vampirc-uci/blob/master/README.md), [Tokio process](https://docs.rs/tokio/1.53.3/tokio/process/), [Stockfish UCI implementation](https://github.com/official-stockfish/Stockfish/blob/master/src/uci.cpp). + +**Предлагаемый supervisor, общий для всех UI:** + +- Executable path, args и рабочий каталог задаются отдельно; запуск через `Command`, без сборки shell-строки. +- Lifecycle: spawn → `uci`/`uciok` → сбор options → `setoption` → `isready`/`readyok` → `position` → `go`. Таймауты handshake и завершения; stdout и stderr читаются независимо, с ограниченными буферами/логами. +- Передавать `position startpos moves ...` либо `position fen moves ...` с историей выбранной ветви: один текущий FEN не содержит историю повторений. Для импортированного root FEN история до него неизвестна; для учебных null moves определить отдельную политику анализа и не выдавать синтетическую историю за реальную. +- При смене позиции: `stop`, дочитать завершающий `bestmove` старого поиска, затем новый `position/go`; при зависании перезапуск. UCI не передаёт request ID. Локальный generation ID помогает UI, но **не заменяет протокольное завершение старого поиска**. `readyok` не является подтверждением остановки анализа. +- Хранить snapshot по `(engine_session, search_generation, multipv)`, объединять частые `info`, не перерисовывать UI на каждую строку stdout. Различать score cp/mate, bound flags и сторону, относительно которой дана оценка. +- PV проверяется последовательно на легальность от анализируемой позиции, преобразуется в SAN. Preview PV — временное состояние; вставка PV в документ — отдельная undoable команда. Стрелка лучшего хода соответствует именно этому snapshot/позиции. +- Закрытие: `stop`, `quit`, timeout, kill и wait/reap. Tokio по умолчанию не убивает процесс при drop; `kill_on_drop` полезен как страховка, но явный shutdown/wait остаётся необходимым. +- Проверить Stockfish из `engines/`, пути с пробелами, ошибочные executable/permissions, stderr flood, отсутствие `uciok`, EOF/crash, MultiPV и быструю смену ходов. Runtime-проверка в рамках исследования не выполнялась. + +Stockfish — отдельная GPLv3 программа. При комплектовании бинарником нужно выполнять его условия распространения и предоставления соответствующего исходного кода. UCI-подключение отдельного установленного engine не тождественно линковке `shakmaty` в GUI. Источник: [Stockfish README, лицензирование](https://github.com/official-stockfish/Stockfish/blob/master/README.md). + +## 7. En Croissant как предметный референс + +**Подтверждено:** это существующий cross-platform chess GUI/database, с UCI multi-engine analysis, управлением движками/базами, поиском позиций и repertoire training. В снимке 0.15.1: + +- Backend: Tauri 2.10.2, Tokio, `shakmaty 0.27.1`, `pgn-reader 0.26.0`, `rusqlite 0.28` bundled + Diesel, fork `vampirc-uci` с pinned revision. +- Frontend: React 19, TypeScript, Vite, Mantine, Chessground, chessops, TanStack Virtual, Tiptap; state tree содержит navigation, promote/delete variation, comments, PGN copying. +- В `src-tauri/src/engine/process.rs` действительно используется `tokio::process::Command` с piped stdin/stdout/stderr, чтением stderr отдельной task, `uci/isready`, отправкой position/go/stop/quit. +- Rust manifest указывает **GPL-3.0-only**, README — GPL-3.0. Прямое копирование кода добавляет эти условия, а не «лицензию ArtCraft». + +**Что перенять как идеи:** разделение process transport и chess/UCI преобразований, дерево и команды нотации, сценарии управления базами и движками, поведение preview/variation navigation. При переносе конкретного кода — отдельное решение с attribution и совместимым лицензированием. + +**Почему не слепой fork:** он уже выбирает web frontend, содержит существенно больший scope (training, online integrations и другие функции), использует две chess-библиотеки в разных языках и свою схему базы. Эти решения не обязаны подходить нашему Rust-native продукту. Зависимости в manifest доказывают наличие стека, но не отсутствие багов; просмотренный process code не является доказательством полноты timeout/reaping всего приложения. Нужны собственные acceptance tests. + +Источники: [README](https://github.com/franciscoBSalgueiro/en-croissant/blob/a91f32b1c57eb93acad92f9778205eac7b4345d9/README.md), [frontend manifest](https://github.com/franciscoBSalgueiro/en-croissant/blob/a91f32b1c57eb93acad92f9778205eac7b4345d9/package.json), [backend manifest](https://github.com/franciscoBSalgueiro/en-croissant/blob/a91f32b1c57eb93acad92f9778205eac7b4345d9/src-tauri/Cargo.toml), [process.rs](https://github.com/franciscoBSalgueiro/en-croissant/blob/a91f32b1c57eb93acad92f9778205eac7b4345d9/src-tauri/src/engine/process.rs), [tree store](https://github.com/franciscoBSalgueiro/en-croissant/blob/a91f32b1c57eb93acad92f9778205eac7b4345d9/src/state/store/tree.ts). + +## 8. Предлагаемый стартовый состав и границы + +```text +apps/desktop eframe + egui + egui_extras(svg), wgpu, rfd +crates/chess-core shakmaty + GameDocument/variation tree + commands/undo +crates/pgn-io pgn-reader visitor + собственный PGN writer +crates/library rusqlite worker, import/index/query API +crates/uci Tokio process + vampirc-uci adapter + supervisor +crates/ui board, notation, table, panels; craft-ui adapter +crates/platform settings, clipboard, audio, filesystem integration +``` + +Это предложение структуры, не уже созданные crates. Core не зависит от egui/Tauri/GTK; движки и import общаются с UI typed messages. Так проверка UI-альтернатив не требует переписывать правила шахмат и хранение. + +- Начальный UI baseline — согласованная линия egui/eframe/egui_extras **0.36**, соответствующая проверенному craft-ui. Pin `craft-libs` на выбранный просмотренный SHA и зафиксировать Cargo.lock; обновления делать вместе с проверкой совместимости. +- Для shakmaty/pgn-reader выбрать согласованную пару версий и проверить MSRV. Если брать рассмотренный current workspace, Rust 1.97 выше требования PhotoCraft 1.95; не копировать toolchain PhotoCraft автоматически. +- Audio: `rodio` как отдельный service, предзагруженные короткие samples, volume/mute и отсутствие crash при недоступном audio device. Manifest upstream указывает MIT OR Apache-2.0: [rodio](https://github.com/RustAudio/rodio/blob/master/Cargo.toml). +- Chess piece SVG, board textures и sounds подбирать и лицензировать **пофайлово**. Наличие ресурса в Lichess/GitHub не делает его public domain; лицензия Chessground не заменяет лицензии сторонних наборов фигур/звуков. Конкретный asset pack в этом исследовании не утверждён. + +## 9. Условия принятия решения и открытые риски + +**Предлагаемый короткий proof-of-concept перед основной разработкой:** + +1. Открыть локальные PGN, сохранить comments/NAG/RAV/FEN и отобразить таблицу. Прочитать → экспортировать → прочитать и сравнить семантическое дерево. Особо вложенные варианты и комментарии до первого хода. +2. В одном экране совместить доску с SVG, flowing notation с русскими комментариями, ввод хода/варианта, undo/redo, клавиатуру, clipboard и звук. Rich-text/comment editing — необязательный будущий spike, не gate для v1. +3. Показать таблицу на сотнях/тысячах учебных партий; измерить latency/память отдельно для импорта, queries и UI. Миллионный стресс-корпус — дальнейшая проверка масштабирования, не gate для v1; цифры производительности здесь не заявляются. +4. Подключить локальный Stockfish: MultiPV, кликабельный PV preview, стрелка на доске, быстрое переключение позиций и корректный shutdown. Исключить отображение старой оценки на новой позиции. +5. Проверить Wayland и X11, дробный масштаб, русские шрифты/IME, keyboard focus, file dialog и доступность custom board/notation controls. Наличие AccessKit feature само не доказывает доступность наших widgets. + +**Сохраняем egui**, если эти сценарии реализуются с приемлемым качеством UX и объёмом собственного UI-кода. **Возвращаемся к Tauri**, если выявлен блокер именно согласованного UI (навигация, selection, accessibility), а не domain-model или UCI; отложенный богатый редактор сам по себе не причина менять стек v1. Это контролируемая проверка предпочтительного ArtCraft-стека, а не замена желания пользователя заранее. + +Главные риски: GPL-решение по связанным шахматным библиотекам; собственный PGN writer и сохранение вариантов; alpha-уровень/изменчивость craft-libs; совместимость egui версий; отзывчивость нотации и больших баз; UCI lifecycle и stale analysis; Linux packaging/Wayland/GPU; отдельные лицензии assets. На дату исследования подтверждена техническая применимость компонентов, но не работоспособность их будущей комбинации в нашем приложении. diff --git a/docs/research/ux-direction.md b/docs/research/ux-direction.md new file mode 100644 index 0000000..4c6dfea --- /dev/null +++ b/docs/research/ux-direction.md @@ -0,0 +1,407 @@ +# UX-направление: библиотека PGN и анализ партий для Linux + +Статус: проектное предложение для обсуждения и реализации. Дата: 17 октября 2026. + +Уточнение после ответа пользователя: актуальный объём первой версии зафиксирован в `../decisions.md` — ходы, варианты, просмотр комментариев и экспорт отдельной партии. Описанные ниже редактор комментариев/NAG/тегов, запись в исходную базу и расширенные фильтры — идеи дальнейшего развития, а не обязательства первой версии. Кнопка сохранения в стартовом макете должна называться «Сохранить как…»; неодобренные команды редактирования текста в первом интерфейсе не показывать. + +## 1. Идея продукта + +**Спокойная шахматная мастерская: найти партию, изучить её историю, проверить идею, сохранить результат.** + +От Lichess берём пространственную модель анализа: крупная доска слева, нотация справа, движок рядом с ходами, комментарии непосредственно в контексте партии. От ArtCraft — локальную работу с собственными файлами, знакомые профессиональные панели, предсказуемые команды и минимум декоративного шума. + +Основные принципы: + +1. Доска — главный визуальный объект; текст — полноценный рабочий материал, а не вспомогательная подпись. +2. Библиотека и анализ — два состояния одного окна. Возврат восстанавливает выбранную базу, запрос, сортировку, строку и прокрутку. +3. Партия, исследуемая позиция и временная линия движка различимы визуально и логически. +4. Просмотр ничего не записывает в PGN. Изменения партии имеют индикатор, отмену и явное сохранение. +5. Плотность профессионального инструмента достигается компактными строками и ясной иерархией, а не мелким шрифтом. +6. Русский интерфейс по умолчанию; оригинальные имена, комментарии и PGN-теги сохраняют язык источника. + +## 2. Источники и разбор референсов + +Прочитано `техническое задание.txt`. Все семь PNG из `designExample/` открыты инструментом `read` и рассмотрены непосредственно. + +| Референс | Наблюдение | Решение для продукта | +| --- | --- | --- | +| `список баз и партий выбранной базы.png` | Сверху коллекция баз, снизу таблица выбранной базы и маленькая доска. Хорошо видна связь «источник → партии», но множество разнотипных значков и сокращённых имён затрудняет поиск. | Сохранить верхнюю полку баз и явную кнопку добавления. Карточки одного типа: имя, число партий, путь/статус. Полка ограничена по высоте и сворачивается. Мини-доска — отключаемый инспектор выбранной строки. | +| `списко партий.png` | Таблица очень информативна: игроки, Elo, результат, число ходов, ECO, турнир, дата. Слишком плотные строки и постоянные многоточия ухудшают чтение. | Полноценная desktop-таблица: настройка ширины и видимости колонок, сортировка, поиск, закреплённый заголовок. Имена игроков и результат приоритетнее внутренних номеров. Полное содержимое доступно в инспекторе и подсказке. | +| `доска с панелью ходов и анализом движка.png` | Доска слева, оценка и линии движка над нотацией справа; видны выделенный ход, стрелки и транспорт навигации. Высокая насыщенность фактурой и фоном отвлекает. | Сохранить структуру, убрать фоновое изображение под текстом. Ограничить начальную высоту блока движка, закрепить транспорт. Отдельно обозначать ход партии и ход предпросмотра. | +| `доска.png` | Крупные различимые фигуры, координаты внутри клеток, перевёрнутая ориентация и подсветка последнего хода. Деревянная текстура активна визуально. | Два способа ввода: клик-клик и перетаскивание. Переворот доступен кнопкой. Спокойная плоская доска по умолчанию; дерево — выбираемая тема. Координаты корректно меняются при перевороте. | +| `лучший ход от движка.png` | Полупрозрачная направленная стрелка помогает сразу сопоставить рекомендацию и позицию. | По умолчанию показывать одну лучшую стрелку; дополнительные линии включать отдельно и маркировать номерами. Синхронизировать стрелки с точной позицией анализа. | +| `панель ходов с коментариями.png` | Вступительный текст и комментарии занимают всю ширину нотации, соседствуют с вариантами и оценочными символами. | Сохранять абзацы и порядок авторского текста. Комментарий связан с узлом, поддерживает раскрытие. Длинное вступление можно свернуть, но оно не исчезает. Редактирование отдельной явной командой. | +| `панель ходов с ответвлениями.png` | Основная линия двухколоночная, альтернативы встроены строками, вложенность выражена скобками и направляющими. | Основная линия — номер / белые / чёрные. Варианты — вложенные блоки с направляющей, раскрытием и кликабельными ходами. Для глубокой вложенности — путь текущего варианта и ограниченный отступ. | + +### ArtCraft: что подтверждено и что предложено + +Источник: , прочитан 17 октября 2026. Страница заявляет локальную работу с файлами, native-приложения на Rust, открытый код и знакомые профессионалам раскладки. Описания PhotoCraft, LightCraft и FigCraft показывают модель «рабочая область + контекстные панели» и различение библиотеки и редактирования. + +Страница прочитана как текст; её иллюстрации отдельно не рассматривались. Поэтому приведённые ниже цвета, размеры и оформление — самостоятельное предложение, а не измеренные токены ArtCraft. Выбор конкретного Rust UI-фреймворка и лицензии заимствуемых ресурсов требуют отдельного технического исследования. + +## 3. Информационная архитектура + +```text +Окно приложения ++-- Библиотека (стартовый экран) +| +-- Полка подключённых PGN-файлов / недавних баз +| +-- Поиск и фильтры выбранной базы +| +-- Таблица партий +| +-- Инспектор выбранной партии (по желанию) ++-- Партия / Новая партия +| +-- Заголовок и сведения +| +-- Доска, оценка, навигация +| +-- Движок: выбор, запуск, линии, предпросмотр +| +-- Нотация: основная линия, варианты, комментарии +| +-- Сведения PGN / копирование / сохранение ++-- Настройки + +-- Движки + +-- Доска и фигуры + +-- Внешний вид + +-- Звук и доступность + +-- Клавиатура +``` + +Начальная версия: одно активное рабочее пространство партии. Отдельное системное окно или вкладки для нескольких партий — последующее расширение после подтверждения пользователем. «Открыть партию» в ТЗ трактуется как переход в рабочее пространство внутри текущего окна. + +База в первой версии — ссылка на локальный PGN-файл, а не скрытое перемещение файла в приложение. «Убрать из библиотеки» удаляет ссылку из списка. Путь показывается в свойствах; одинаковые имена различаются папкой. Повторное открытие того же файла активирует существующую запись. + +## 4. Экран библиотеки + +### Компоновка + +```text ++------------------------------------------------------------------------------------+ +| Библиотека [Открыть PGN…] [Новая партия] [Настройки]| ++------------------------------------------------------------------------------------+ +| Базы [Поиск баз…] [Свернуть] [+ Добавить]| +| [Мои партии ] [Сицилианская ] [Учебные партии ] | +| [142 партии ] [2 340 партий ] [18 партий ] | ++------------------------------------------------------------------------------------+ +| Сицилианская 2 340 партий [Поиск игроков, турнира…] [Фильтры] | +| [Год: 2024 ×] [Сбросить] [Колонки] | ++---------------------------------------------------------------+--------------------+ +| Белые Elo | Чёрные Elo | Рез. | Дата | ECO | Выбранная партия | +| > Игрок A 2420 | Игрок B 2380 | 1-0 | 2024.05.12 | B20 | [мини-доска] | +| Игрок C 2290 | Игрок D 2310 | 1/2 | 2024.05.13 | B22 | Турнир, раунд | +| ... | Комментарии: есть | +| | [Открыть партию] | ++---------------------------------------------------------------+--------------------+ +| Найдено 86 из 2 340 · /home/…/sicilian.pgn | ++------------------------------------------------------------------------------------+ +``` + +### Поведение + +- Карточка базы выбирает файл и его список партий; добавление всегда доступно сверху, как запрошено в ТЗ. +- По умолчанию полка показывает одну-две строки. При большом числе баз доступно «Все базы» с поиском; бесконечная полка не вытесняет таблицу. +- Один клик по строке выбирает её и обновляет инспектор; двойной клик, Enter или кнопка «Открыть» открывают анализ. Это desktop-предложение требует подтверждения, поскольку ТЗ допускает открытие простым кликом. +- Начальные колонки: Белые, Elo белых, Чёрные, Elo чёрных, Результат, Дата, ECO, Турнир. Ходы, раунд, номер, наличие комментариев — дополнительные. Результаты выводятся полностью: `1-0`, `0-1`, `½-½`, `*`. +- Отсутствующее значение — `—`, неизвестные части даты сохраняются как неизвестные; не подставлять 1 января. +- Поиск сразу ограничивается выбранной базой. Расширенные фильтры: игрок и цвет, результат, диапазон дат, Elo, ECO, наличие комментариев/вариантов. Фильтры представлены удаляемыми чипами. +- При обновлении списка выделение привязано к идентификатору партии, а не номеру строки. Подгружаемые строки не вызывают скачков прокрутки. +- Длинные названия имеют многоточие только в таблице; инспектор и доступное имя содержат полный текст. Числа выравниваются по правому краю. +- Мини-доска показывает стартовую позицию партии, включая FEN при наличии. Полезнее сделать инспектор отключаемым, чем включать там ещё один полноценный анализ. + +## 5. Рабочее пространство партии + +```text ++------------------------------------------------------------------------------------+ +| [← Библиотека] Игрок A — Игрок B 1-0 • Изменено [Сохранить] [PGN ▾] [⋯] | +| Турнир · 2024.05.12 · B20 Партия 12 из 86 [Пред.] [След.] | ++-------------------------------------------+----------------------------------------+ +| Чёрные: Игрок B · 2380 | Stockfish ▾ [Запустить / Остановить] | +| +-----------------------------------+ | +0.34 · за белых · глубина 22 · 2 линии| +| | | | 1 +0.34 12.Nf3 Nc6 13.Bb5 ... | +| О | | | 2 +0.18 12.Bc4 Nf6 13.d3 ... | +| ц | ДОСКА | +----------------------------------------+ +| е | | | [Нотация] [Сведения] | +| н | | | 11 O-O Be7 | +| к | | | Комментарий к позиции… | +| а | | | 12 [Nf3] Nc6 | +| +-----------------------------------+ | + Вариант: 12.Bc4 Nf6 ... | +| Белые: Игрок A · 2420 | 13 Bb5 a6 | +| [Перевернуть] [В начало] [Назад] [Вперёд] | | +| [В конец] 12.Nf3 · ход чёрных | [Комментарий] [Оценка хода ▾] [⋯] | ++-------------------------------------------+----------------------------------------+ +| Партия · основная линия · позиция после 12.Nf3 [Звук: вкл.] | ++------------------------------------------------------------------------------------+ +``` + +- Краткая строка игроков над/под доской меняется местами при перевороте. Часы показывать только при наличии данных времени, не создавать впечатление онлайн-партии. +- Доска всегда квадратная. Последний ход, выбранная фигура, доступные поля и шах имеют разные обозначения. Выбор фигуры сбрасывается Escape. +- Перемещение — мышью и клик-клик; нелегальный ход оставляет позицию прежней и даёт короткое объяснение. Превращение вызывает выбор Q/R/B/N с клавиатурным управлением. +- Новый легальный ход из позиции внутри партии создаёт вариант. Если такой ход уже существует, переходить к существующему узлу. Основное продолжение автоматически не заменять. +- В конце текущей ветки новый ход продолжает её. Изменения дерева, комментариев, NAG и тегов делают документ изменённым. +- Полоса оценки опциональна. Рядом обязательно числовое значение: знак всегда относительно белых, независимо от ориентации. `+M3` — белые матуют за 3, `−M3` — чёрные; смысл доступен текстом. Нижнюю/верхнюю сторону полосы привязывать к цветам игроков на доске. +- Кнопка PGN: «Копировать всю партию», «Копировать текущий вариант как партию», «Сохранить как…». Копирование всей партии включает теги, комментарии и варианты. Исходный PGN использует стандартную SAN, даже если UI показывает фигурные символы. +- Просмотр позиции, запуск движка, поворот, сворачивание ветки и копирование не включают dirty. +- «Новая партия» сразу открывает начальную позицию и нейтральные имена «Белые — Чёрные». До первого изменения это пустой документ без запроса сохранения при закрытии. + +## 6. Нотация, дерево вариантов и комментарии + +### Представление дерева + +```text +Основная линия + 1 e4 e5 + 2 Nf3 Nc6 + 3 Bb5 a6 + Комментарий после 3…a6: «Основное продолжение». + 4 [Ba4] Nf6 + v Альтернатива белых на 4-м ходу + 4.Bxc6 dxc6 5.O-O + v Альтернатива чёрных после 4.Bxc6 + 4…bxc6 5.d4 + 5 O-O Be7 +``` + +Это иллюстративная нотация, не отдельная партия для импорта. Вариант `4.Bxc6` — другой ход из позиции после `3…a6`, а не потомок позиции после `4.Ba4`. Вложенный `4…bxc6` — альтернатива `4…dxc6`. В модели каждый узел хранит позицию после хода, а альтернативы разделяют одного родителя. В UI блок расположен рядом с заменяемым продолжением и явно подписан номером и стороной хода. + +- Основная линия полужирнее вариантов; активный ход выделяется фоном и рамкой, не только цветом текста. Номер и сторона хода доступны скринридеру. +- Направляющая и маркер раскрытия показывают структуру. У свёрнутой ветки остаются первые ходы и счётчик, например `4.Bxc6 dxc6… · 8 полуходов`. +- При навигации в скрытый узел раскрываются его предки. Активный ход аккуратно прокручивается в видимую область; ручная прокрутка для чтения комментария не перебивается поступлением анализа движка. +- Отступ растёт до трёх уровней, дальше сохраняется ширина текста и появляется путь `Основная → 4.Bxc6 → 4…bxc6`. Полный путь раскрывается по кнопке; не сжимать ход до одного символа. +- Контекстное меню: добавить/редактировать комментарий, поставить `!`, `?`, `!?`, `?!`, сделать основной линией, удалить ветку, копировать вариант. Удаление и повышение ветки отменяемы через Undo. +- Стрелка вправо идёт по выбранному продолжению, по умолчанию основному. В развилке кнопка «Варианты» открывает явный список; клавиатурное переключение описано ниже. + +### Работа с текстом + +- Вступительный комментарий относится к корню партии; комментарии перед ходом и после хода сохраняют исходную позицию относительно нотации. Повторное сохранение не должно переставлять авторский текст. +- Комментарии читаются inline на всю ширину панели; абзацы сохраняются. Более шести строк можно свернуть до первых трёх с кнопкой «Читать полностью». Сворачивание — настройка представления. +- Редактор комментария появляется в месте текста, имеет «Применить» и «Отмена». До применения это черновик; переход не должен молча его терять. `Ctrl+Enter` применяет, Escape закрывает без изменений после явного отказа от непустого черновика. +- Комментарии из PGN отображаются как текст. Ссылки можно открыть осознанным действием; HTML не исполняется. Авторские NAG и сохранённые оценки отличимы от текущей оценки движка. +- Для PGN-команд вроде `[%eval]`, `[%clk]`, `[%cal]`, `[%csl]` предусмотреть структурированное отображение при поддержке. Неизвестные аннотации сохранять без потерь; непонятный тег не должен уничтожаться редактором. + +## 7. Линия движка: отдельный предпросмотр + +**Инвариант: чтение любого числа ходов PV не изменяет дерево партии, исходный файл или Undo-историю.** + +PV — предполагаемое продолжение, которое движок может менять в процессе расчёта. + +### Сценарий + +1. Пользователь запускает выбранный локальный UCI-движок для текущего узла партии. Показываются имя, состояние, оценка, глубина и число линий; NPS и hash — во вторичных сведениях. +2. Наведение/фокус на строку подчёркивает строку и может выделить её первую стрелку, но не меняет позицию доски. +3. Клик по ходу PV или Enter на строке открывает предпросмотр. Фиксируются исходный узел партии, история ходов от начальной позиции, снимок линии, её оценка/глубина и исходный фокус. Одного FEN недостаточно для сохранения контекста повторений. Клик по конкретному ходу показывает позицию после него; Enter на строке — после первого хода. +4. Доска получает заметную рамку и надпись «Предпросмотр линии 2 · от 12-го хода · шаг 3/14». В нотации партии исходный узел остаётся отмеченным меткой «Точка возврата». +5. Расчёт исходной позиции останавливается, строки фиксируются. Глубина и оценка подписаны как данные исходной позиции, а не текущего шага PV. Смена ранга MultiPV не подменяет выбранную линию. +6. Стрелки и транспорт перемещаются только внутри снимка PV; шаг 0 возвращает исходную позицию внутри предпросмотра. Достижение конца не создаёт ходов. +7. Escape или «Вернуться к партии» восстанавливает исходный узел, фокус и прокрутку нотации. Если движок до входа работал, он снова запускается на этом узле. +8. «Добавить линию как вариант» — отдельная команда: добавляет всю зафиксированную PV в точку её начала с объединением общего префикса, без дублей и без замены основной линии. Одна операция Undo, dirty включается; пользователь переходит к добавленному варианту. Если вся линия уже существует, только переход, без dirty. + +```text ++------------------------------------+---------------------------------------------+ +| ПРЕДПРОСМОТР · линия 2 · шаг 3/14 | Зафиксировано от 12.Nf3 · глубина 22 | +| [доска временной позиции] | +0.18 12…Nf6 13.d3 [Be7] 14.O-O ... | +| | [Вернуться к партии · Esc] | +| [К началу PV] [Назад] [Вперёд] | [Добавить линию как вариант] [Копировать PV]| ++------------------------------------+---------------------------------------------+ +``` + +Дополнительные правила: + +- Выбор хода в нотации партии завершает предпросмотр и переходит в выбранный узел; не требуется подтверждение, поскольку документ не менялся. +- Ручной ввод хода в предпросмотре недоступен с понятной подписью: «Добавьте линию как вариант, чтобы продолжить её вручную». Не превращать временную позицию в скрытый редактор. +- В предпросмотре не показывать стрелки от исходной позиции на другой позиции. Допустима стрелка следующего хода зафиксированной PV с подписью «Следующий ход линии». +- Новые результаты движка принимаются только для соответствующих позиции и запроса анализа. После перехода по партии прежние стрелки сразу исчезают; вместо старой оценки — «Расчёт…» либо явно помеченный сохранённый результат. +- При остановке движка последняя оценка остаётся с подписью «Остановлен». Это отличается от индикатора активного расчёта. +- Выбор другого движка доступен после выхода из предпросмотра; кнопка объясняет необходимый переход. + +## 8. Настройки + +```text ++--------------------+--------------------------------------------------+ +| Настройки | Движки [+ Добавить…] | +| > Движки | ● Stockfish Готов | +| Доска и фигуры | Другой UCI Файл не найден [Выбрать файл…] | +| Внешний вид | | +| Звук | Активный: Stockfish | +| Доступность | Путь: /home/…/engines/stockfish | +| Клавиатура | [Проверить запуск] [Сделать активным] [Убрать] | +| | Потоки [ ] Hash, MiB [ ] Линий [ 2 ] | +| | [Дополнительные параметры UCI ▾] | ++--------------------+--------------------------------------------------+ +``` + +- Добавление движка: системный файловый диалог → проверка запуска/UCI → найденное имя → добавление в список. Состояния «Проверяем», «Готов», «Не исполняемый файл», «Нет ответа UCI», «Нужны дополнительные файлы». Сообщение содержит действие и раскрываемые технические подробности. +- Параметры потоков и памяти имеют единицы, границы и объяснение. Настройки работающего процесса применяются через явный перезапуск с сообщением о сбросе текущего расчёта. +- Доска и фигуры: живой пример позиции, переключение наборов, координат, анимации, подсветки, стрелок. Предпочтительны узнаваемые контрастные векторные фигуры; конкретные ассеты выбирать после проверки лицензии. +- Звук: общий выключатель, громкость, короткая кнопка проверки; отдельно звук ходов и уведомления. Быстрая клавиатурная прокрутка не должна создавать очередь звуков. Изменение оценки движка беззвучно. +- Внешний вид: «Как в системе / Светлая / Тёмная», плотность таблицы, размер текста. Изменения внешнего вида применяются сразу, есть сброс категории. + +## 9. Клавиатура и фокус + +Все сочетания отображаются в меню и справке. Таблица ниже — начальная схема, не обещание конфликтовать с глобальными сочетаниями оконного менеджера. + +| Область | Команда | Действие | +| --- | --- | --- | +| Глобально | Ctrl+O | Открыть PGN | +| Глобально | Ctrl+N | Новая партия | +| Документ | Ctrl+S / Ctrl+Shift+S | Сохранить / Сохранить как | +| Документ | Ctrl+Shift+C | Копировать всю партию как PGN; обычный Ctrl+C сохраняется для выделенного текста | +| Документ | Ctrl+Z / Ctrl+Shift+Z | Отменить / повторить изменение | +| Глобально | Ctrl+, | Настройки | +| Глобально | F1 | Справка по клавиатуре | +| Библиотека | Ctrl+F | Поиск в текущей базе | +| Таблица | ↑ / ↓, PageUp / PageDown, Home / End | Перемещение по строкам | +| Таблица | Enter | Открыть выбранную партию | +| Рабочее пространство | Ctrl+W | Закрыть партию и вернуться в библиотеку с обработкой dirty | +| Нотация / транспорт / preview | ← / → | Назад / вперёд на полуход в текущей линии | +| Нотация / транспорт / preview | Home / End | Начало / конец текущей линии; Ctrl+Home — корень партии вне preview | +| Нотация | Alt+↑ / Alt+↓ | Предыдущая / следующая альтернатива текущему ходу у общего родителя | +| Нотация | Enter на раскрытии / Space на кнопке | Раскрыть или свернуть ветку | +| Рабочая область вне ввода текста | F / E | Перевернуть доску / запустить или остановить движок | +| Предпросмотр | Escape | Вернуться в исходный узел партии | +| Комментарий | Ctrl+Enter | Применить текст | +| Глобально | Tab / Shift+Tab | Следующий / предыдущий интерактивный элемент | +| Глобально | F6 / Shift+F6 | Переход между крупными областями окна | + +Одиночные буквы и стрелки не перехватываются в текстовых полях. При фокусе внутри доски стрелки двигают курсор клетки, а не позицию партии; Enter/Space выбирает фигуру и поле назначения. Tab выходит из доски, а не заставляет пройти все 64 клетки. Порядок F6: заголовок → доска/транспорт → движок → нотация → строка состояния. Если Alt-сочетания заняты окружением, доступны переназначение и меню вариантов. + +Escape закрывает ближайший временный контекст: меню/выбор превращения/редактор → выделение фигуры → предпросмотр. Закрытие всей партии выполняется отдельной командой, чтобы повторный Escape не терял работу. + +## 10. Состояния и сохранение + +| Состояние | Что видит пользователь | Доступное действие | +| --- | --- | --- | +| Нет баз | Короткий текст «Откройте PGN или начните новую партию», две крупные кнопки | Открыть PGN, новая партия; обычный заголовок и настройки остаются | +| Пустой PGN | Имя файла, «В файле нет партий» | Новая партия, открыть другой файл | +| Нет результатов | «По этому запросу партии не найдены» и активные фильтры | Сбросить фильтры, изменить запрос | +| Загрузка/индексация | Имя файла, прочитанный объём/найденные партии, отмена; точный процент только при известном объёме | Отмена, работа с другими готовыми базами | +| Открытие партии | Спокойный индикатор в рабочей панели; предыдущая доска не выдаётся за новую | Вернуться в библиотеку | +| Ошибка PGN | Имя, номер партии/строка при наличии, понятная причина | Показать подробности, открыть другой файл; корректные партии доступны, если парсер умеет восстанавливаться | +| PGN частично прочитан | «Прочитано 120 партий, 3 с ошибками» и журнал | Просмотр исправных партий, экспорт выбранной; не перезаписывать исходник с молчаливой потерей ошибочных записей | +| Файл перемещён | Карточка с меткой «Файл не найден» | Указать новый путь, убрать ссылку | +| Движок не выбран | Компактный блок «Добавьте локальный UCI-движок» | Выбрать файл; партия полностью доступна | +| Движок запускается | «Запуск Stockfish…» без фиктивной оценки | Отменить запуск | +| Движок считает | Активный индикатор, глубина, линии; размер блока стабилен | Остановить, выбрать PV | +| Движок завершился с ошибкой | Встроенное сообщение, последняя оценка помечена устаревшей | Перезапустить, выбрать другой, раскрыть журнал | +| Dirty | Точка в заголовке и текст «Изменено»; активное сохранение | Сохранить, сохранить как, Undo | +| Сохранение | «Сохраняем…» до подтверждения записи | Просмотр остаётся доступным; повторное сохранение не дублируется | +| Ошибка записи | Изменения остаются в памяти, сообщение с причиной | Повторить, сохранить в другое место, копировать PGN | +| Файл изменён извне | Баннер «Файл изменился на диске» | При чистом документе — перечитать; при dirty — сохранить копию или явно отбросить локальные изменения и перечитать | + +### Контракт работы с документом + +- При закрытии изменённой партии: «Сохранить изменения в партии …?» → «Сохранить», «Не сохранять», «Отмена». Закрытие ждёт успешной записи; ошибка не закрывает документ. +- Пока стратегия безопасного обновления одной партии внутри многопартийного PGN не реализована, основное действие — «Сохранить как…» для отдельной партии. Подпись должна явно говорить, что записывается одна партия, а не вся база. +- Если редактирование базы поддерживается, обновляется только соответствующая партия; остальные партии, комментарии и неизвестные теги должны сохраниться. Перед применением проверяется внешнее изменение файла. Это обязательное условие включения команды «Сохранить в базу». +- Копирование PGN не снимает dirty. Undo до сохранённого состояния снимает dirty. Сохранение во время дальнейшего редактирования очищает dirty только для действительно записанной версии. +- Автовосстановление черновика желательно как отдельная функция: восстанавливает работу после сбоя, но не является незаметной записью поверх исходного PGN. +- Переход к следующей партии и открытие другой базы не обходят обработку несохранённых изменений. + +## 11. Resize и адаптация к Linux desktop + +Все размеры ниже — логические пиксели, стартовые ориентиры, которые проверяются на реальном шрифте, DPI и русских подписях. + +- Базовый макет: 1440×900; обязательные проверки: 1366×768, 1024×720, 800×600, масштабирование 125/150/200% и увеличенный системный шрифт. +- При ширине от 1100: доска слева, правая панель 380–520 px, исходное распределение примерно 58/42 с учётом доступной высоты. +- При 900–1099: правая панель от 320 px, сокращение вторичных сведений и перенос команд в меню; доска остаётся квадратной. +- При ширине менее 900 или невозможности сохранить доску хотя бы 320 px рядом с текстом: вертикальная компоновка «доска сверху, панель снизу». Движок и нотация доступны переключателем; индикатор предпросмотра и возврат всегда видимы. +- В узкой библиотеке инспектор скрывается, полка баз становится горизонтальным списком с поиском. Вторичные колонки доступны горизонтальной прокруткой; имена и результат сохраняют приоритет. +- Вертикальный разделитель регулирует доску/правую панель, горизонтальный — движок/нотацию. Видимая линия тонкая, область захвата 8–12 px. Двойной клик сбрасывает пропорции; фокусируемый разделитель меняется стрелками клавиатуры. +- Размер доски определяется меньшим из доступных ширины и высоты после заголовков и транспорта. Не растягивать клетки и не обрезать последнюю горизонталь. +- Движок по умолчанию занимает около 140–180 px. При увеличении MultiPV прокручивается его собственный блок, а не весь экран; нотации остаётся полезная высота. +- Панели имеют независимую прокрутку. Транспорт доски, заголовок движка и кнопка выхода из preview не уходят за пределы видимой области. +- Геометрия окна, ширины колонок и пропорции сохраняются между запусками; при смене монитора окно возвращается в доступную область. Предусмотреть «Сбросить расположение». +- В tiling-окружении приложение корректно принимает размер от оконного менеджера. Не навязывать полноэкранный режим и не полагаться на нестандартную рамку окна. + +## 12. Визуальный язык и начальные UI-токены + +Направление: графитовые или тёплые светлые панели, умеренный зелёно-бирюзовый акцент, ясные разделители, минимум теней. Фактура разрешена на доске по выбору пользователя; под таблицами и комментариями — сплошные поверхности. Цвет движка/preview не должен смешиваться с цветом сохранения и ошибок. + +### Цвета-кандидаты + +| Токен | Тёмная тема | Светлая тема | Назначение | +| --- | --- | --- | --- | +| `bg.app` | `#171B1E` | `#F3F4F2` | Фон окна | +| `bg.panel` | `#20262A` | `#FFFFFF` | Таблица, нотация | +| `bg.raised` | `#2B3338` | `#E8EDE9` | Поля, hover, карточки | +| `border.subtle` | `#465158` | `#CAD2CC` | Вторичные разделители | +| `border.control` | `#89969E` | `#65736C` | Граница интерактивных полей | +| `text.primary` | `#EEF2EF` | `#1D2822` | Основной текст | +| `text.secondary` | `#B1BCB5` | `#526158` | Метаданные | +| `accent.text` | `#8AD6B0` | `#146B46` | Ссылки и активные элементы | +| `accent.fill` | `#246B4B` | `#216C49` | Основная кнопка; текст `#FFFFFF` | +| `selection.bg` | `#294D42` | `#D7EDE0` | Выбранная строка / ход | +| `focus.ring` | `#8FC6FF` | `#145EB0` | Контур клавиатурного фокуса | +| `preview.text` | `#D2B5FF` | `#6A399B` | Временный режим плюс текстовая метка | +| `warning.text` | `#F1C878` | `#795000` | Dirty/предупреждение плюс значок | +| `error.text` | `#FFABA6` | `#A6242A` | Ошибка плюс сообщение | +| `board.light` | `#E5DEC9` | `#E5DEC9` | Светлое поле | +| `board.dark` | `#80947D` | `#80947D` | Тёмное поле | + +Тема доски независима от темы приложения, чтобы смена системной темы не меняла привычную шахматную палитру. Отдельный высококонтрастный набор доски и фигур обязателен. Подсветка последнего хода использует заливку и контур; шах — контур короля и текстовый статус. Лучшая стрелка движка — контрастная с обводкой и номером линии; пользовательские стрелки отличаются начертанием/маркером, а не только оттенком. + +### Размеры и типографика + +| Группа | Начальные значения | +| --- | --- | +| Шрифт UI | Системный sans с качественной кириллицей; Noto Sans как кандидат fallback | +| Текст | UI 14 px; комментарии 15 px / 1.5; нотация 17 px / 1.45; заголовки 18–22 px | +| Числа | Табличные цифры для Elo, глубины, оценок и дат | +| Сетка отступов | 4, 8, 12, 16, 24, 32 px | +| Высоты | Контрол 36 px; строка таблицы 36 px, компактная 30 px; заголовок таблицы 40 px | +| Радиусы | 4 px поле/кнопка, 8 px панель, 10 px диалог; без округления каждой клетки | +| Иконки | 16/20 px, единая толщина линий; подпись для главных действий | +| Фокус | Контур 2 px с внешним отступом 2 px; не обрезается контейнером | +| Движение | Hover 100–140 ms; фигура 120–180 ms; мгновенно при reduced motion | + +Цвета — кандидаты для прототипа, не заявление о пройденном аудите. Перед фиксацией проверить реальные пары foreground/background и альфа-композицию подсветок: текст ≥4.5:1, крупный текст ≥3:1, значимые контуры и состояния ≥3:1. `border.subtle` не использовать как единственную границу интерактивного элемента. + +## 13. Accessibility и особенности desktop + +- Полная работа без мыши: открыть PGN, выбрать партию, пройти варианты, прочитать комментарий, просмотреть PV, сохранить результат. +- Доступность должна проверяться через Linux AT-SPI/Orca на выбранном GUI-стеке; рисование текста на canvas без семантики недостаточно. +- Доска предоставляет доступное имя клетки: «e4, белая пешка, последний ход», состояние выбора и текущую сторону. Есть текстовый список фигур/позиции и доступная нотация как альтернативное представление. +- Озвучивание после навигации: номер, цвет, ход, шах/мат при наличии. Движок не озвучивает каждое изменение NPS/оценки; объявляет запуск, остановку и ошибку, а оценка читается по запросу. +- Иконки имеют имена, подсказки и видимый фокус. Подсказка не является единственным носителем важного состояния. +- Текст увеличивается до 200% без исчезновения действий; переполнение уходит в адаптивную компоновку, а не в наложение слоёв. +- Цвет дополняется текстом/формой: dirty — точка и «Изменено», preview — рамка и заголовок, ошибка — значок и сообщение, выбранный ход — контур. +- По умолчанию область нажатия не меньше 32×32 px, основные кнопки высотой 36 px; просторный режим увеличивает элементы управления и интервалы между ними. +- Анимации отключаются настройкой reduced motion. Звук отключаем независимо, все значимые звуковые события имеют визуальное представление. +- Внешний drag-and-drop PGN имеет видимую зону «Открыть файл»; всегда есть эквивалент через диалог. Для Wayland/X11 работа с буфером и системным файловым выбором должна проверяться отдельно. + +## 14. Приоритеты реализации и UX-проверки + +### Первая полноценная версия + +Библиотека локальных PGN → таблица → анализ партии; новая партия; фигуры и доска; чтение комментариев и вариантов; выбор UCI-движка; его линии и стрелка лучшего хода; изолированный preview; копирование полного PGN; явное сохранение как; обработка dirty; светлая/тёмная темы; базовая клавиатура и звук. + +### Следующие расширения + +Редактирование партии внутри многопартийного файла после решения вопроса сохранности; вкладки нескольких партий; расширенный поиск по позициям; массовый анализ; график оценок; репертуары. Эти функции не должны перегружать начальную навигацию. + +### Сценарии приёмки интерфейса + +1. Открыть базу, отфильтровать партии, войти в одну и вернуться: фильтры, строка и скролл восстановлены. +2. Открыть партию с длинным вступлением и тройной вложенностью: все комментарии доступны, текущий ход различим, путь ветки понятен. +3. Просмотреть десять ходов PV и выйти: исходный узел восстановлен, число узлов, PGN и dirty не изменились. +4. Добавить PV как вариант и сделать Undo: исходное дерево восстановлено одной операцией; основная линия не заменена. +5. Быстро менять позиции при работающем движке: старая стрелка не остаётся на новой доске, чужая оценка не представляется актуальной. +6. Ввести новую партию мышью и клавиатурой, включая превращение, скопировать PGN с вариантами и комментариями. +7. Смоделировать ошибку сохранения: документ остаётся открыт и изменён, доступно сохранение в другое место. +8. Уменьшить окно до 800×600 и увеличить текст: фигуры не искажены, возврат из preview и главные действия доступны. +9. Пройти базовый сценарий с Orca и без мыши; повторить в обеих темах и без цвета как единственного ориентира. + +## 15. Вопросы пользователю + +### Решения, влияющие на первую версию + +1. Открывать партию в том же окне с возвратом в библиотеку или нужен отдельный системный экземпляр окна? Для старта предложено то же окно. +2. Достаточно сохранять изменённую партию отдельным PGN или обязательно сразу редактировать партии внутри исходной большой базы? Предложено начать с явного «Сохранить как…». +3. Открывать строку одним кликом, как возможно подразумевает ТЗ, или привычным desktop-способом: выделение кликом, открытие двойным кликом/Enter? +4. Какие типичные и максимальные размеры баз, число партий и глубина вариантов? Это влияет на индексацию, фильтры и плотность интерфейса. +5. Нужен ли Chess960 уже в первой версии? В одном табличном референсе есть соответствующие турниры, но это не подтверждает требование; также важно определить поддержку нестандартной начальной позиции из FEN. + +### Предпочтения, которые можно уточнить на прототипе + +6. Нотация фигурными символами или буквенная SAN? Предложено сделать переключатель, экспортировать стандартную SAN. +7. Плоская спокойная доска или дерево по умолчанию? Предложена плоская, дерево доступно в настройках. +8. Нужна ли постоянно видимая мини-доска в библиотеке? Предложен отключаемый инспектор. +9. Какой Linux desktop/оконный менеджер, размеры экранов и масштабирование используются ежедневно? +10. Нужны ли сразу несколько открытых партий и одновременное сравнение движков? Начальное предложение — одна партия и один активный движок с несколькими линиями. +11. Комментарии только читать или также активно редактировать? Макет предусматривает оба сценария; это влияет на объём первого редактора. + +До ответов можно проектировать библиотеку, нотацию и безопасный preview по указанным исходным решениям. Открытыми остаются политика записи в базу, модель нескольких окон и поддержка шахматных вариантов. diff --git a/docs/screenshots/analysis.png b/docs/screenshots/analysis.png new file mode 100644 index 0000000..ce38fe5 Binary files /dev/null and b/docs/screenshots/analysis.png differ diff --git a/docs/screenshots/library.png b/docs/screenshots/library.png new file mode 100644 index 0000000..eb1f020 Binary files /dev/null and b/docs/screenshots/library.png differ diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png new file mode 100644 index 0000000..3ef59da Binary files /dev/null and b/docs/screenshots/settings.png differ diff --git a/docs/screenshots/variations.png b/docs/screenshots/variations.png new file mode 100644 index 0000000..17ac03c Binary files /dev/null and b/docs/screenshots/variations.png differ diff --git a/examples/classics.pgn b/examples/classics.pgn new file mode 100644 index 0000000..fba5f58 --- /dev/null +++ b/examples/classics.pgn @@ -0,0 +1,71 @@ +[Event "Paris Opera"] +[Site "Paris FRA"] +[Date "1858.??.??"] +[Round "?"] +[White "Morphy, Paul"] +[Black "Duke Karl / Count Isouard"] +[Result "1-0"] +[ECO "C41"] +[PlyCount "33"] +[Annotator "ChessPenguin sample"] + +{The "Opera Game": a model of rapid development and open lines.} 1. e4 e5 2. Nf3 +d6 3. d4 Bg4 $6 {Pinning the knight, but Black will have to give up the bishop +pair.} 4. dxe5 Bxf3 (4... dxe5 5. Qxd8+ Kxd8 6. Nxe5 {wins a pawn.}) 5. Qxf3 +dxe5 6. Bc4 {Threatening Qxf7#.} Nf6 7. Qb3 $1 {A double attack on f7 and b7.} +Qe7 8. Nc3 {Morphy prefers development to material.} (8. Qxb7 Qb4+ 9. Qxb4 Bxb4+ +{only trades queens.}) 8... c6 9. Bg5 b5 $2 10. Nxb5 $1 cxb5 11. Bxb5+ Nbd7 12. +O-O-O Rd8 13. Rxd7 $1 Rxd7 14. Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+ $3 Nxb8 17. Rd8# +1-0 + +[Event "London casual game"] +[Site "London ENG"] +[Date "1851.06.21"] +[Round "?"] +[White "Anderssen, Adolf"] +[Black "Kieseritzky, Lionel"] +[Result "1-0"] +[ECO "C33"] +[PlyCount "45"] +[Annotator "ChessPenguin sample"] + +{The "Immortal Game".} 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 c6 10. g4 Nf6 11. Rg1 $1 cxb5 12. h4 Qg6 +13. h5 Qg5 14. Qf3 Ng8 15. Bxf4 Qf6 16. Nc3 Bc5 17. Nd5 Qxb2 18. Bd6 $3 {White +gives up both rooks.} Bxg1 (18... Qxa1+ 19. Ke2 Bxg1 20. Nxg7+ Kd8 21. Qf6+ {is +similar.}) 19. e5 $1 Qxa1+ 20. Ke2 Na6 21. Nxg7+ Kd8 22. Qf6+ $3 Nxf6 23. Be7# +1-0 + +[Event "Berlin casual game"] +[Site "Berlin GER"] +[Date "1852.??.??"] +[Round "?"] +[White "Anderssen, Adolf"] +[Black "Dufresne, Jean"] +[Result "1-0"] +[ECO "C52"] +[PlyCount "47"] +[Annotator "ChessPenguin sample"] + +{The "Evergreen Game".} 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 {The Evans Gambit.} +Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d3 8. Qb3 Qf6 9. e5 Qg6 10. Re1 Nge7 11. Ba3 +b5 12. Qxb5 Rb8 13. Qa4 Bb6 14. Nbd2 Bb7 15. Ne4 Qf5 16. Bxd3 Qh5 17. Nf6+ $1 +gxf6 18. exf6 Rg8 19. Rad1 $3 Qxf3 20. Rxe7+ $1 Nxe7 (20... Kd8 21. Rxd7+ Kc8 +22. Rd8+ Kxd8 23. Bf5+ Qxd1 24. Qxd1+ {wins.}) 21. Qxd7+ $3 Kxd7 22. Bf5+ Ke8 +23. Bd7+ Kf8 24. Bxe7# 1-0 + +[Event "Endgame study"] +[Site "?"] +[Date "????.??.??"] +[Round "?"] +[White "White to move"] +[Black "Opposition"] +[Result "1-0"] +[SetUp "1"] +[FEN "4k3/8/4K3/4P3/8/8/8/8 w - - 0 1"] +[PlyCount "7"] +[Annotator "ChessPenguin sample"] + +{A starting position from FEN. With the king on the sixth rank in front of +its pawn, White wins whoever is to move.} 1. Kd6 (1. Kf6 Kf8 2. e6 Ke8 3. e7 Kd7 +4. Kf7 {also wins.}) 1... Kd8 2. e6 Ke8 3. e7 Kf7 4. Kd7 1-0 diff --git a/icons/icon1.png b/icons/icon1.png new file mode 100644 index 0000000..52cdb0f Binary files /dev/null and b/icons/icon1.png differ diff --git a/icons/icon2.png b/icons/icon2.png new file mode 100644 index 0000000..17341f3 Binary files /dev/null and b/icons/icon2.png differ diff --git a/icons/icon3.png b/icons/icon3.png new file mode 100644 index 0000000..943af36 Binary files /dev/null and b/icons/icon3.png differ diff --git a/opencode.jsonc b/opencode.jsonc new file mode 100644 index 0000000..942b3ad --- /dev/null +++ b/opencode.jsonc @@ -0,0 +1,4 @@ +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "orchestrator" +} diff --git a/packaging/build-appimage.sh b/packaging/build-appimage.sh new file mode 100755 index 0000000..9410f63 --- /dev/null +++ b/packaging/build-appimage.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Builds ChessPenguin--x86_64.AppImage from target/release/chesspenguin. +# Usage (repository root): VERSION=0.1.0 packaging/build-appimage.sh dist/ +set -euo pipefail + +app_id="io.github.vrubelroman.chessPenguin" +out_dir="${1:-dist}" +version="${VERSION:?set VERSION}" +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT + +curl -fsSL -o "${work}/linuxdeploy" \ + https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage +chmod +x "${work}/linuxdeploy" + +appdir="${work}/AppDir" +install -Dm755 target/release/chesspenguin "${appdir}/usr/bin/chesspenguin" +# AppStream metadata is left out: appimagetool validates its screenshot URLs over the network. +for size in 16 24 32 48 64 128 256 512; do + install -Dm644 "packaging/icons/hicolor/${size}x${size}/apps/${app_id}.png" \ + "${appdir}/usr/share/icons/hicolor/${size}x${size}/apps/${app_id}.png" +done + +mkdir -p "${out_dir}" +export LINUXDEPLOY_OUTPUT_VERSION="${version}" +export OUTPUT="${out_dir}/ChessPenguin-${version}-x86_64.AppImage" +APPIMAGE_EXTRACT_AND_RUN=1 "${work}/linuxdeploy" \ + --appdir "${appdir}" \ + --desktop-file "packaging/${app_id}.desktop" \ + --icon-file "packaging/icons/hicolor/256x256/apps/${app_id}.png" \ + --output appimage +echo "Built ${OUTPUT}" diff --git a/packaging/flatpak/io.github.vrubelroman.chessPenguin.yml b/packaging/flatpak/io.github.vrubelroman.chessPenguin.yml new file mode 100644 index 0000000..c11fdc2 --- /dev/null +++ b/packaging/flatpak/io.github.vrubelroman.chessPenguin.yml @@ -0,0 +1,40 @@ +# Flatpak manifest. CI builds a .flatpak bundle with network access during the build +# (cargo fetches crates). For Flathub, vendored sources (flatpak-cargo-generator) would be needed. +app-id: io.github.vrubelroman.chessPenguin +runtime: org.freedesktop.Platform +runtime-version: '25.08' +sdk: org.freedesktop.Sdk +sdk-extensions: + - org.freedesktop.Sdk.Extension.rust-stable +command: chesspenguin +finish-args: + - --socket=wayland + - --socket=fallback-x11 + - --share=ipc + - --device=dri + - --socket=pulseaudio + # PGN files and UCI engine executables live in the user's home. + - --filesystem=home +build-options: + append-path: /usr/lib/sdk/rust-stable/bin + build-args: + - --share=network + env: + CARGO_HOME: /run/build/chesspenguin/cargo +modules: + - name: chesspenguin + buildsystem: simple + build-commands: + - cargo build --release --locked -p chesspenguin + - install -Dm755 target/release/chesspenguin /app/bin/chesspenguin + - install -Dm644 packaging/io.github.vrubelroman.chessPenguin.desktop /app/share/applications/io.github.vrubelroman.chessPenguin.desktop + - install -Dm644 packaging/io.github.vrubelroman.chessPenguin.metainfo.xml /app/share/metainfo/io.github.vrubelroman.chessPenguin.metainfo.xml + - for s in 16 24 32 48 64 128 256 512; do install -Dm644 packaging/icons/hicolor/${s}x${s}/apps/io.github.vrubelroman.chessPenguin.png /app/share/icons/hicolor/${s}x${s}/apps/io.github.vrubelroman.chessPenguin.png; done + sources: + - type: dir + path: ../.. + skip: + - target + - .flatpak-builder + - pgnFilesforExample + - engines diff --git a/packaging/icons/hicolor/128x128/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/128x128/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..10e5626 Binary files /dev/null and b/packaging/icons/hicolor/128x128/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/icons/hicolor/16x16/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/16x16/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..03ed6d4 Binary files /dev/null and b/packaging/icons/hicolor/16x16/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/icons/hicolor/24x24/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/24x24/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..c78a0e9 Binary files /dev/null and b/packaging/icons/hicolor/24x24/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/icons/hicolor/256x256/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/256x256/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..f57a3c8 Binary files /dev/null and b/packaging/icons/hicolor/256x256/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/icons/hicolor/32x32/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/32x32/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..8ec2d3c Binary files /dev/null and b/packaging/icons/hicolor/32x32/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/icons/hicolor/48x48/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/48x48/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..7aa4ede Binary files /dev/null and b/packaging/icons/hicolor/48x48/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/icons/hicolor/512x512/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/512x512/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..8b5bb9a Binary files /dev/null and b/packaging/icons/hicolor/512x512/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/icons/hicolor/64x64/apps/io.github.vrubelroman.chessPenguin.png b/packaging/icons/hicolor/64x64/apps/io.github.vrubelroman.chessPenguin.png new file mode 100644 index 0000000..e710942 Binary files /dev/null and b/packaging/icons/hicolor/64x64/apps/io.github.vrubelroman.chessPenguin.png differ diff --git a/packaging/io.github.vrubelroman.chessPenguin.desktop b/packaging/io.github.vrubelroman.chessPenguin.desktop new file mode 100644 index 0000000..fa65f5d --- /dev/null +++ b/packaging/io.github.vrubelroman.chessPenguin.desktop @@ -0,0 +1,14 @@ +[Desktop Entry] +Type=Application +Name=ChessPenguin +GenericName=Chess Database +GenericName[ru]=Шахматная база +Comment=View, enter and analyse chess games in PGN +Comment[ru]=Просмотр, ввод и анализ шахматных партий в PGN +Exec=chesspenguin %F +Icon=io.github.vrubelroman.chessPenguin +Terminal=false +Categories=Game;BoardGame; +MimeType=application/x-chess-pgn;application/vnd.chess-pgn; +Keywords=chess;pgn;uci;stockfish;analysis;шахматы; +StartupWMClass=io.github.vrubelroman.chessPenguin diff --git a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml new file mode 100644 index 0000000..7e791f4 --- /dev/null +++ b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml @@ -0,0 +1,47 @@ + + + io.github.vrubelroman.chessPenguin + ChessPenguin + Chess database: view, enter and analyse PGN games + CC0-1.0 + GPL-3.0-or-later + + vrubelroman + + +

+ ChessPenguin is a native desktop chess database for PGN files. Open annotated books and + game collections, browse games with variations and comments, enter your own games and + analyse them with any UCI engine such as Stockfish. +

+
    +
  • Library of PGN databases with a searchable, sortable game list
  • +
  • Move tree with nested variations, comments and NAGs
  • +
  • Engine analysis with several lines, best-move arrows and an evaluation bar
  • +
  • Step through engine lines on the board without changing the game
  • +
  • Copy PGN/FEN, save games, undo and redo
  • +
  • Legacy encodings of real-world PGN files are detected
  • +
+
+ io.github.vrubelroman.chessPenguin.desktop + https://github.com/vrubelroman/chessPenguin + https://github.com/vrubelroman/chessPenguin/issues + + + https://raw.githubusercontent.com/vrubelroman/chessPenguin/main/docs/screenshots/analysis.png + + + https://raw.githubusercontent.com/vrubelroman/chessPenguin/main/docs/screenshots/library.png + + + + + Game + BoardGame + + + +

First public release.

+
+
+
diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml new file mode 100644 index 0000000..213276c --- /dev/null +++ b/packaging/nfpm.yaml @@ -0,0 +1,66 @@ +# deb and rpm packages (https://nfpm.goreleaser.com). Run from the repository root: +# VERSION=0.1.0 nfpm package -f packaging/nfpm.yaml -p deb -t dist/ +name: chesspenguin +arch: amd64 +platform: linux +version: ${VERSION} +section: games +priority: optional +maintainer: vrubelroman +vendor: vrubelroman +homepage: https://github.com/vrubelroman/chessPenguin +license: GPL-3.0-or-later +description: | + Chess database for Linux. + View, enter and analyse chess games in PGN with any UCI engine + (Stockfish and others): variations, comments, multi-line analysis. + +contents: + - src: target/release/chesspenguin + dst: /usr/bin/chesspenguin + file_info: + mode: 0755 + - src: packaging/io.github.vrubelroman.chessPenguin.desktop + dst: /usr/share/applications/io.github.vrubelroman.chessPenguin.desktop + - src: packaging/io.github.vrubelroman.chessPenguin.metainfo.xml + dst: /usr/share/metainfo/io.github.vrubelroman.chessPenguin.metainfo.xml + # Icons are listed one by one so the package does not own the shared hicolor directories. + - src: packaging/icons/hicolor/16x16/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/16x16/apps/io.github.vrubelroman.chessPenguin.png + - src: packaging/icons/hicolor/24x24/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/24x24/apps/io.github.vrubelroman.chessPenguin.png + - src: packaging/icons/hicolor/32x32/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/32x32/apps/io.github.vrubelroman.chessPenguin.png + - src: packaging/icons/hicolor/48x48/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/48x48/apps/io.github.vrubelroman.chessPenguin.png + - src: packaging/icons/hicolor/64x64/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/64x64/apps/io.github.vrubelroman.chessPenguin.png + - src: packaging/icons/hicolor/128x128/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/128x128/apps/io.github.vrubelroman.chessPenguin.png + - src: packaging/icons/hicolor/256x256/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/256x256/apps/io.github.vrubelroman.chessPenguin.png + - src: packaging/icons/hicolor/512x512/apps/io.github.vrubelroman.chessPenguin.png + dst: /usr/share/icons/hicolor/512x512/apps/io.github.vrubelroman.chessPenguin.png + - src: LICENSE + dst: /usr/share/licenses/chesspenguin/LICENSE + - src: THIRD_PARTY_NOTICES.md + dst: /usr/share/doc/chesspenguin/THIRD_PARTY_NOTICES.md + - src: examples/classics.pgn + dst: /usr/share/doc/chesspenguin/examples/classics.pgn + +overrides: + deb: + depends: + - libc6 + - libasound2 | libasound2t64 + - libxkbcommon0 + recommends: + - libvulkan1 + - libegl1 + rpm: + depends: + - alsa-lib + - libxkbcommon + recommends: + - vulkan-loader + - mesa-libEGL diff --git a/packaging/windows/chesspenguin.ico b/packaging/windows/chesspenguin.ico new file mode 100644 index 0000000..effb9b4 Binary files /dev/null and b/packaging/windows/chesspenguin.ico differ diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000..2d6e3d0 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Installs ChessPenguin for the current user (~/.local), or removes it with --uninstall. +set -euo pipefail + +app_id="io.github.vrubelroman.chessPenguin" +root="$(cd "$(dirname "$0")/.." && pwd)" +bin_dir="${HOME}/.local/bin" +data_dir="${XDG_DATA_HOME:-${HOME}/.local/share}" +apps_dir="${data_dir}/applications" +icons_dir="${data_dir}/icons/hicolor" +sizes=(16 24 32 48 64 128 256 512) + +refresh_caches() { + command -v update-desktop-database >/dev/null && update-desktop-database -q "${apps_dir}" || true + command -v gtk-update-icon-cache >/dev/null && gtk-update-icon-cache -q -t "${icons_dir}" || true +} + +remove_files() { + # Current names and the pre-rename development build (chessbase-linux). + for name in "${app_id}" chessbase-linux; do + rm -f "${apps_dir}/${name}.desktop" + for s in "${sizes[@]}"; do rm -f "${icons_dir}/${s}x${s}/apps/${name}.png"; done + done + rm -f "${bin_dir}/chesspenguin" "${bin_dir}/chessbase-linux" +} + +if [[ "${1:-}" == "--uninstall" ]]; then + remove_files + refresh_caches + echo "ChessPenguin removed (settings in ~/.config/chesspenguin are kept)." + exit 0 +fi + +cargo="${CARGO:-$(command -v cargo || echo "${HOME}/.cargo/bin/cargo")}" +"${cargo}" build --release -p chesspenguin --manifest-path "${root}/Cargo.toml" + +remove_files +install -Dm755 "${root}/target/release/chesspenguin" "${bin_dir}/chesspenguin" +install -Dm644 "${root}/packaging/${app_id}.desktop" "${apps_dir}/${app_id}.desktop" +for s in "${sizes[@]}"; do + install -Dm644 "${root}/packaging/icons/hicolor/${s}x${s}/apps/${app_id}.png" \ + "${icons_dir}/${s}x${s}/apps/${app_id}.png" +done +refresh_caches +echo "Installed: ${bin_dir}/chesspenguin (launcher entry «ChessPenguin»)." diff --git a/техническое задание.txt b/техническое задание.txt new file mode 100644 index 0000000..cefce4e --- /dev/null +++ b/техническое задание.txt @@ -0,0 +1,33 @@ +я буквально восхищен тем что делают ребята вот такие приложения https://getartcraft.com/apps +мне хотелось бы реальизовать под linux с тем же техстеком как и эти парни аналог chessbase. вроде они делают все это на rust, но не знаю какие фреймворки. вот вроде их github - https://github.com/storytold https://github.com/storytold/photocraft +при этом мне пика не нужно работать с форматами chessbase, с их по сути проприетарными фораматами. мне достаточно пока будет реализации с pgn файлами.в проекте есть папка pgnFilesforExample где лежат пару таких файлов, с которыми хочу работать. + +Теперь пользовательские кейсы, которые я хочу реализовать: +1. я открываю программу и сразу вижу разные возможности (скрин /home/vrubel/services/chessBaseLinux/designExample/список баз и партий выбранной базы.png, но нужна возможность добавлять базу в список вверху): + a) загрузить одну из баз что ранее открывали - если загрузил, то вижу список партий таблицой, где могу выбрать один из элементов и тогда уже откроется доска, спрва от нее панель с нотацией, по которой я клавиатурой или же мышкой могу выбирать ходы, которые будут отображаться на доска + b) могу открыть новую базу в файловой системе и тогда откроется такой же список партий (ну по интерфейсу имею ввиду) как в предыдущем пункте /home/vrubel/services/chessBaseLinux/designExample/список баз и партий выбранной базы.png только + c) могу открыть просто новую партию где фигуры будут сразу в исходной позиции - цель например вбить партию и посмотреть потом с помощью движка анализ партии, а еще если что скопировать pgn введенной партии +2. список партий что описаны в пунктах выше должны быть кликабельными и тогда откроется окно с доской и ходами /home/vrubel/services/chessBaseLinux/designExample/доска с панелью ходов и анализом движка.png. +3. должна быть возможность выбирать из файловой системы движок, включать его в режиме просмотра партии и видеть ходы что он пишет, а так же выбрать строку линии и перемещаться по ходам, видя как перемещаются фигуры на доске. +4. я так же должен видеть в нотации (скрины есть) комаентарии что есть в партиях в базе. скрины тоже есть в папке с примерами. +5. закрыв партию я должен буду видеть опять список партий и файлов баз. +6. должны быть настройки, где я могу загружать движки, выбирать активный, где могу менять наборы фигур и фон доски (скачай, думаю на github должны быть исходники от lichess или аналога) +7. всех кесов могу не продумать, продумай тоже ты. +8. в режиме анализа должен показываться на доске оптимальные ходы (скриншот /home/vrubel/services/chessBaseLinux/designExample/лучший ход от движка.png) +в папке engines я скачал stockfish движок. можешь закачать туда еще какие-нибудь. + +но основная миссия программы - смотреть, анализировать партии, базы, списки, иметь возможность выбирать движки и тд. мочь копировать введенный pgn или pgn открытой партии. + +да, должны быть звуки тоже, думаю так же можно взять из gihtub. + +в папке designExample есть еще и другие скрины, в целом они взяты (кроме списка партий) с lichess и есть вроде бы даже аналог lichess в github, который даже можно развернуть. так вот логику если что и как работает интерфейс можно взять будет оттуда. поищи, юзай для наших целей. + +я хочу чтобы ты создал агентов для этой нашей работы: +- оркестратор (мы в opencode) +- аналитик, который пишет и сохраняет текущую аналитику +- дизайнер, который грамотно продумывает интерфейс (заюзай какой-нибудь крутой скилл или агента md для проработки дизайна) +- разработчик (возможно заюзать тоже скил или описание уже грамотных агентов по rust) +- тестировщик. вроде после создания ну написания агентов нужно будет перезапустить opencode. если у тебя есть вопросы то задавай. + +если есть возможность условно из гитхаба по ссылкам выше юзать уже наработки что делали https://getartcraft.com/apps то гуд. +наша задача сделать качественный продукт.