diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad495fa..c4d7307 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,3 +30,9 @@ jobs: - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - run: cargo build --locked -p chesspenguin + # The bundled engine: pinned download, checksum and a UCI handshake. + - name: Stockfish + shell: bash + run: | + packaging/stockfish.sh windows build/stockfish + printf 'uci\nquit\n' | build/stockfish/stockfish.exe | grep -m1 '^id name' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eb6cc1d..46f0885 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,12 +43,14 @@ jobs: - 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: Stockfish + run: packaging/stockfish.sh linux build/stockfish - 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}/" + cp -r packaging/icons packaging/*.desktop examples build/stockfish "dist/${name}/" tar -C dist -czf "dist/${name}.tar.gz" "${name}" rm -rf "dist/${name}" - name: deb, rpm and Arch Linux packages @@ -94,6 +96,9 @@ jobs: - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - run: cargo build --release --locked -p chesspenguin + - name: Stockfish + shell: bash + run: packaging/stockfish.sh windows build/stockfish - name: Zip shell: pwsh run: | @@ -101,7 +106,7 @@ jobs: 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/" + Copy-Item -Recurse examples, build/stockfish "dist/$name/" Compress-Archive -Path "dist/$name" -DestinationPath "dist/$name.zip" Remove-Item -Recurse "dist/$name" - uses: actions/upload-artifact@v7 @@ -114,10 +119,13 @@ jobs: if: github.ref_type == 'tag' runs-on: ubuntu-24.04 steps: + - uses: actions/checkout@v7 - uses: actions/download-artifact@v8 with: path: dist merge-multiple: true + - name: Stockfish source (GPL-3.0 source offer for the bundled engine) + run: packaging/stockfish.sh source dist - name: Checksums run: cd dist && sha256sum * > SHA256SUMS.txt - uses: softprops/action-gh-release@v3 diff --git a/.gitignore b/.gitignore index 1726b34..9942163 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ /target +# Downloaded Stockfish for packaging (packaging/stockfish.sh) +/build/ /engines/* !/engines/README.md /pgnFilesforExample/ diff --git a/CHANGELOG.md b/CHANGELOG.md index db49696..81c32c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Stockfish 19 is bundled with every package (unmodified official "universal" build, which picks + the right code path for the CPU) and set up on the first start; a system `stockfish` is detected + too. Settings → Engines offers engines found on the computer. Packages grow to about 95 MB. + - Game analysis (Shift+A): background evaluation of the whole main line with its own engine process, evaluation graph under the board, report tab with accuracy, inaccuracies, mistakes, blunders, average centipawn loss and accuracy per game phase; engine marks and better lines in the notation; diff --git a/README.md b/README.md index b60a631..70b70d1 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Source files are never modified. - **Notation** — main line as a two-column table, comments and variations as blocks, mouse and keyboard navigation. +- **Stockfish included** — analysis works right after installation; other UCI engines can be added. - **Engine analysis** — any UCI engine, up to 5 lines, best-move arrows, evaluation bar; search time, threads and memory are set right in the analysis panel. - **Game analysis** — evaluate the whole game in the background: evaluation graph under the board, @@ -54,9 +55,8 @@ Packages for every release are on the [Releases](https://github.com/vrubelroman/ | Flatpak | `flatpak install --user ChessPenguin--x86_64.flatpak` | | Windows | unzip `ChessPenguin--windows-x86_64.zip`, run `ChessPenguin.exe` | -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**. +**Stockfish 19 is included** and set up on the first start: install and analyse. A `stockfish` +from your distribution is found too, and any other UCI engine can be added in **Settings → Engines**. ### Build from source @@ -64,7 +64,7 @@ Rust 1.97 or newer. On Debian/Ubuntu: `sudo apt install pkg-config libasound2-de ```sh cargo run --release -p chesspenguin -- examples/classics.pgn -./scripts/install.sh # install for the current user (~/.local), --uninstall to remove +./scripts/install.sh # install for the current user (~/.local) with Stockfish; --no-stockfish, --uninstall ``` ## Keyboard diff --git a/README.ru.md b/README.ru.md index c0bdc5e..2e490e3 100644 --- a/README.ru.md +++ b/README.ru.md @@ -30,11 +30,11 @@ Пакеты каждого релиза — на странице [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/)) и добавьте его в **Настройки → Движки**. +**Stockfish 19 входит в комплект** и настраивается при первом запуске: установил и анализируешь. +Системный `stockfish` тоже находится автоматически, другие UCI-движки добавляются в **Настройки → Движки**. Сборка из исходников: Rust 1.97+, затем `cargo run --release -p chesspenguin` -или `./scripts/install.sh` для установки в `~/.local`. +или `./scripts/install.sh` для установки в `~/.local` вместе со Stockfish (`--no-stockfish` — без него). ## Лицензия diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c65bab9..ab9e45e 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -33,6 +33,23 @@ Notes: - 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. +## Stockfish (bundled engine) + +Release packages include **Stockfish 19** (tag `sf_19`), the unmodified official +`stockfish-*-x86-64-universal` binaries from +https://github.com/official-stockfish/Stockfish/releases/tag/sf_19 (SHA-256 pinned in +`packaging/stockfish.sh`). + +- License: GNU General Public License version 3 (`Copying.txt`, installed as + `stockfish-Copying.txt` next to this application's license); authors: the Stockfish + developers (`AUTHORS`, installed alongside). +- Source code: https://github.com/official-stockfish/Stockfish/tree/sf_19 ; every GitHub release of + ChessPenguin also carries `stockfish-sf_19-source.tar.gz`. The neural networks embedded in the + binary are published by the Stockfish project (see its `README.md` and `src/evaluate.h`). +- Stockfish's networks are trained on data provided by the Leela Chess Zero project under the + Open Database License (ODbL). +- ChessPenguin runs Stockfish as a separate process over the UCI protocol. + ## Rust crates Dependency licenses are recorded by `Cargo.lock`; key ones: shakmaty / pgn-reader (GPL-3.0-or-later), diff --git a/apps/desktop/src/analysis.rs b/apps/desktop/src/analysis.rs index a5a2dd3..f9cbbc9 100644 --- a/apps/desktop/src/analysis.rs +++ b/apps/desktop/src/analysis.rs @@ -86,6 +86,11 @@ impl Analysis { /// Starts the engine in a background thread (handshake blocks for up to ~20 s). pub fn start(&mut self, cfg: &EngineConfig, ctx: &egui::Context) { self.stop(); + let Some(path) = cfg.executable() else { + self.status = + Status::Failed(tr("The built-in engine is not part of this build").into()); + return; + }; let (tx, rx) = channel(); let ctx_w = ctx.clone(); let ctx_done = ctx.clone(); @@ -93,12 +98,12 @@ impl Analysis { self.engine_name = cfg.name.clone(); self.multipv = cfg.multipv.max(1); self.limit = cfg.search_secs; - self.engine_path = Some(cfg.path.clone()); + self.engine_path = Some(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), + uci::EngineConfig::new(&path), Box::new(move || ctx_w.request_repaint()), ) .inspect(|h| { @@ -139,7 +144,7 @@ impl Analysis { /// 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() { + if self.engine_path != cfg.executable() || self.spawning.is_some() { self.start(cfg, ctx); return; } diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index b380073..2662467 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -91,6 +91,9 @@ impl App { pub fn new(ctx: &egui::Context) -> Self { let mut settings = Settings::load(); crate::i18n::set_lang(settings.language); + if crate::engines::first_run_setup(&mut settings) { + let _ = settings.save(); + } // PGN files passed on the command line (e.g. "Open with…") join the library, first one selected. let args: Vec = std::env::args_os() .skip(1) diff --git a/apps/desktop/src/engines.rs b/apps/desktop/src/engines.rs new file mode 100644 index 0000000..1d2f7b1 --- /dev/null +++ b/apps/desktop/src/engines.rs @@ -0,0 +1,94 @@ +//! Finding engines without a file dialog: the Stockfish shipped with the packages and a +//! `stockfish` installed by the system package manager. + +use std::path::{Path, PathBuf}; + +use crate::i18n::tr; +use crate::settings::{EngineConfig, Settings}; + +#[cfg(windows)] +const STOCKFISH: &str = "stockfish.exe"; +#[cfg(not(windows))] +const STOCKFISH: &str = "stockfish"; + +/// The Stockfish shipped next to the application: +/// `/lib/chesspenguin/stockfish` for `/bin/chesspenguin` (deb, rpm, Arch, +/// AppImage, Flatpak) or `stockfish/stockfish[.exe]` beside the executable (Windows zip, +/// Linux tarball). Resolved at every start: the AppImage mount point changes between runs. +pub fn bundled_stockfish() -> Option { + let exe = std::env::current_exe().ok()?.canonicalize().ok()?; + let dir = exe.parent()?; + let candidates = [ + dir.parent() + .map(|prefix| prefix.join("lib").join("chesspenguin").join(STOCKFISH)), + Some(dir.join("stockfish").join(STOCKFISH)), + ]; + candidates.into_iter().flatten().find(|p| is_executable(p)) +} + +/// `stockfish` from `PATH` (for example, the distribution package). +pub fn system_stockfish() -> Option { + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path) + .map(|dir| dir.join(STOCKFISH)) + .find(|p| is_executable(p)) +} + +fn is_executable(p: &Path) -> bool { + let Ok(meta) = std::fs::metadata(p) else { + return false; + }; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + meta.is_file() && meta.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + { + meta.is_file() + } +} + +pub fn builtin_config() -> EngineConfig { + let mut cfg = EngineConfig::new(tr("Stockfish (built-in)").into(), PathBuf::new()); + cfg.builtin = true; + cfg +} + +/// First start: if no engine is configured, adds the bundled Stockfish (or else the system +/// one) and makes it active, so analysis works right after installation. Runs once. +pub fn first_run_setup(settings: &mut Settings) -> bool { + if settings.engines_discovered { + return false; + } + settings.engines_discovered = true; + if settings.engines.is_empty() { + let found = if bundled_stockfish().is_some() { + Some(builtin_config()) + } else { + system_stockfish().map(|p| EngineConfig::new("Stockfish".into(), p)) + }; + if let Some(cfg) = found { + settings.engines.push(cfg); + settings.active_engine = Some(0); + } + } + true +} + +/// Engines found on this system that are not in the list yet (offered in the settings). +pub fn suggestions(settings: &Settings) -> Vec { + let mut out = Vec::new(); + if bundled_stockfish().is_some() && !settings.engines.iter().any(|e| e.builtin) { + out.push(builtin_config()); + } + if let Some(p) = system_stockfish() { + let known = |e: &EngineConfig| { + !e.builtin && (e.path == p || e.path.canonicalize().ok() == p.canonicalize().ok()) + }; + if !settings.engines.iter().any(known) { + out.push(EngineConfig::new(tr("Stockfish (system)").into(), p)); + } + } + out +} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index e54cf46..7e88805 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -1355,6 +1355,63 @@ const ROWS: &[[&str; 6]] = &[ "Profundo", "Approfondito", ], + // Engines + [ + "The built-in engine is not part of this build", + "Встроенного движка нет в этой сборке", + "Le moteur intégré ne fait pas partie de cette version", + "Die eingebaute Engine ist in diesem Build nicht enthalten", + "El motor integrado no forma parte de esta compilación", + "Il motore integrato non fa parte di questa build", + ], + [ + "Shipped with ChessPenguin: {path}", + "Поставляется с ChessPenguin: {path}", + "Fourni avec ChessPenguin : {path}", + "Mit ChessPenguin geliefert: {path}", + "Incluido con ChessPenguin: {path}", + "Fornito con ChessPenguin: {path}", + ], + [ + "Shipped with ChessPenguin: not part of this build", + "Поставляется с ChessPenguin: в этой сборке отсутствует", + "Fourni avec ChessPenguin : absent de cette version", + "Mit ChessPenguin geliefert: in diesem Build nicht enthalten", + "Incluido con ChessPenguin: no está en esta compilación", + "Fornito con ChessPenguin: assente in questa build", + ], + [ + "Found on this computer:", + "Найдено на этом компьютере:", + "Trouvé sur cet ordinateur :", + "Auf diesem Computer gefunden:", + "Encontrado en este equipo:", + "Trovato su questo computer:", + ], + [ + "Add", + "Добавить", + "Ajouter", + "Hinzufügen", + "Añadir", + "Aggiungi", + ], + [ + "Stockfish (built-in)", + "Stockfish (встроенный)", + "Stockfish (intégré)", + "Stockfish (eingebaut)", + "Stockfish (integrado)", + "Stockfish (integrato)", + ], + [ + "Stockfish (system)", + "Stockfish (системный)", + "Stockfish (système)", + "Stockfish (System)", + "Stockfish (del sistema)", + "Stockfish (di sistema)", + ], ]; #[cfg(test)] @@ -1372,6 +1429,7 @@ mod tests { include_str!("library.rs"), include_str!("notation.rs"), include_str!("review.rs"), + include_str!("engines.rs"), include_str!("settings.rs"), include_str!("settings_ui.rs"), include_str!("widgets.rs"), diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index cd4fdcc..9045ce3 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -5,6 +5,7 @@ mod analysis; mod app; mod assets; mod board; +mod engines; mod game_view; mod i18n; mod library; diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index 89bea9c..c39298e 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -262,6 +262,10 @@ impl Review { ) -> bool { self.job = None; self.error = None; + let Some(path) = engine.executable() else { + self.error = Some(tr("The built-in engine is not part of this build").into()); + return false; + }; if full { self.evals.clear(); self.dirty = true; @@ -288,12 +292,7 @@ impl Review { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = targets.len(); - let (path, threads, hash, nodes) = ( - engine.path.clone(), - rs.threads.max(1), - rs.hash_mb, - rs.nodes(), - ); + let (path, threads, hash, nodes) = (path, rs.threads.max(1), rs.hash_mb, rs.nodes()); let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone()); let spawned = std::thread::Builder::new() .name("game-review".into()) diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index e9d5790..022d3b7 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -20,6 +20,9 @@ pub struct EngineConfig { /// Search time per position in seconds; `None` = infinite. #[serde(default)] pub search_secs: Option, + /// The Stockfish shipped with ChessPenguin; `path` is unused and resolved at start. + #[serde(default)] + pub builtin: bool, } fn default_threads() -> u32 { @@ -43,6 +46,16 @@ impl EngineConfig { hash_mb: default_hash(), multipv: default_multipv(), search_secs: None, + builtin: false, + } + } + + /// Executable to start; `None` if the built-in engine is missing (e.g. a source build). + pub fn executable(&self) -> Option { + if self.builtin { + crate::engines::bundled_stockfish() + } else { + Some(self.path.clone()) } } } @@ -65,6 +78,8 @@ pub struct Settings { pub databases: Vec, /// Whole-game analysis options. pub review: ReviewSettings, + /// The first-start engine discovery has run (see `engines::first_run_setup`). + pub engines_discovered: bool, } /// Options of the whole-game analysis (the engine is the active one). @@ -116,6 +131,7 @@ impl Default for Settings { show_best_arrow: true, databases: Vec::new(), review: ReviewSettings::default(), + engines_discovered: false, } } } diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index 7693e94..71b244d 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -1,6 +1,6 @@ //! Settings window: engines, board & pieces, sound, interface. -use crate::i18n::{Lang, tr}; +use crate::i18n::{Lang, tr, trf}; use egui::{RichText, Sense, Ui, vec2}; use shakmaty::{Color, Piece, Role}; @@ -136,11 +136,19 @@ impl SettingsWindow { } }); }); - ui.label( - RichText::new(s.engines[i].path.display().to_string()) - .small() - .weak(), - ); + let e = &s.engines[i]; + let location = if e.builtin { + match crate::engines::bundled_stockfish() { + Some(p) => trf( + "Shipped with ChessPenguin: {path}", + &[("path", &p.display())], + ), + None => tr("Shipped with ChessPenguin: not part of this build").into(), + } + } else { + e.path.display().to_string() + }; + ui.label(RichText::new(location).small().weak()); }); } if let Some(i) = remove { @@ -153,6 +161,26 @@ impl SettingsWindow { *changed = true; actions.push(SettingsAction::EngineChanged); } + let found = crate::engines::suggestions(s); + if !found.is_empty() { + ui.add_space(6.0); + ui.label(RichText::new(tr("Found on this computer:")).strong()); + for cfg in found { + ui.horizontal(|ui| { + let path = cfg.executable().unwrap_or_default(); + ui.label(&cfg.name) + .on_hover_text(path.display().to_string()); + if ui.button(tr("Add")).clicked() { + s.engines.push(cfg); + if s.active_engine.is_none() { + s.active_engine = Some(s.engines.len() - 1); + actions.push(SettingsAction::EngineChanged); + } + *changed = true; + } + }); + } + } ui.add_space(6.0); ui.horizontal(|ui| { if ui diff --git a/docs/decisions.md b/docs/decisions.md index d022796..5fea721 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -23,6 +23,8 @@ - анализируется только основная линия; результаты кэшируются в `~/.cache/chesspenguin/analysis/`; при правке основной линии дооцениваются только новые позиции; оценки `[%eval]` из PGN используются без движка; - методика — опубликованные формулы Lichess (lichess.org/page/accuracy), реализованы заново. +10. **Stockfish в комплекте** — 2026-10-18, решение пользователя: вкладываем во все пакеты (deb, rpm, Arch, AppImage, Flatpak, Windows, tar.gz), не полагаемся на системные пакеты. Официальный «universal»-бинарник Stockfish 19 без изменений (версия и SHA-256 закреплены в `packaging/stockfish.sh`), в пакетах — `/lib/chesspenguin/stockfish` или `stockfish/` рядом с exe; в настройках встроенный движок хранится признаком `builtin`, путь вычисляется при запуске (точка монтирования AppImage меняется). При первом запуске без движков добавляется встроенный, иначе системный `stockfish`. Лицензия GPL-3.0 выполняется: текст лицензии и AUTHORS в пакете, архив исходников прикладывается к каждому релизу. Пакеты выросли до ~95 МБ. + ## Следует из исходного ТЗ - Linux desktop; предпочтение стека Artcraft, подлежащего проверке по исходникам. diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index cc3c976..63108c7 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -12,6 +12,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках | | `board.rs` | Виджет доски: клик/drag, превращение, рокировка кликом на поле короля или ладью, стрелки, круги | | `analysis.rs` | Контроллер анализа поверх `uci`: запуск в фоне, привязка результатов к истории позиции, MultiPV | +| `engines.rs` | Поиск движков: встроенный Stockfish (`/lib/chesspenguin/stockfish` или `stockfish/` рядом с exe), системный `stockfish` в `PATH`; настройка при первом запуске, подсказки в настройках | | `report.rs` | Метрики анализа партии без UI: шанс на победу, точность хода и партии, неточность/ошибка/зевок, средняя потеря сантипешек, стадии партии (формулы Lichess) | | `review.rs` | Анализ партии целиком: фоновый поток с собственным процессом движка (`go nodes N`), кэш, `[%eval]` из PGN, график, вкладка «Отчёт», окно запуска, запись анализа в партию | | `assets.rs`, `sound.rs` | Встроенные SVG-фигуры, темы доски, звуки (rodio в отдельном потоке) | diff --git a/packaging/build-appimage.sh b/packaging/build-appimage.sh index 9410f63..e8a9ee9 100755 --- a/packaging/build-appimage.sh +++ b/packaging/build-appimage.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -# Builds ChessPenguin--x86_64.AppImage from target/release/chesspenguin. +# Builds ChessPenguin--x86_64.AppImage from target/release/chesspenguin and the +# Stockfish fetched by `packaging/stockfish.sh linux build/stockfish`. # Usage (repository root): VERSION=0.1.0 packaging/build-appimage.sh dist/ set -euo pipefail @@ -11,7 +12,9 @@ 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" +curl -fsSL -o "${work}/appimagetool" \ + https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage +chmod +x "${work}/linuxdeploy" "${work}/appimagetool" appdir="${work}/AppDir" install -Dm755 target/release/chesspenguin "${appdir}/usr/bin/chesspenguin" @@ -21,12 +24,20 @@ for size in 16 24 32 48 64 128 256 512; do "${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" +# 1. linuxdeploy fills the AppDir (dependencies, AppRun, desktop entry, icon). 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}" + --icon-file "packaging/icons/hicolor/256x256/apps/${app_id}.png" + +# 2. Stockfish is added afterwards: linuxdeploy would rewrite its RUNPATH, and the bundled +# engine must stay the unmodified official binary. +install -Dm755 build/stockfish/stockfish "${appdir}/usr/lib/chesspenguin/stockfish" +install -Dm644 build/stockfish/Copying.txt "${appdir}/usr/share/licenses/chesspenguin/stockfish-Copying.txt" + +# 3. appimagetool packs the AppDir as is. +mkdir -p "${out_dir}" +output="${out_dir}/ChessPenguin-${version}-x86_64.AppImage" +ARCH=x86_64 VERSION="${version}" APPIMAGE_EXTRACT_AND_RUN=1 \ + "${work}/appimagetool" --no-appstream "${appdir}" "${output}" +echo "Built ${output}" diff --git a/packaging/flatpak/io.github.vrubelroman.chessPenguin.yml b/packaging/flatpak/io.github.vrubelroman.chessPenguin.yml index c11fdc2..049ed89 100644 --- a/packaging/flatpak/io.github.vrubelroman.chessPenguin.yml +++ b/packaging/flatpak/io.github.vrubelroman.chessPenguin.yml @@ -22,6 +22,16 @@ build-options: env: CARGO_HOME: /run/build/chesspenguin/cargo modules: + # Bundled Stockfish (GPL-3.0). Keep in sync with packaging/stockfish.sh. + - name: stockfish + buildsystem: simple + build-commands: + - install -Dm755 stockfish-linux-x86-64-universal /app/lib/chesspenguin/stockfish + - install -Dm644 Copying.txt /app/share/licenses/chesspenguin/stockfish-Copying.txt + sources: + - type: archive + url: https://github.com/official-stockfish/Stockfish/releases/download/sf_19/stockfish-linux-x86-64-universal.tar.gz + sha256: 9defc0d4e55d49c65a6d042f3e571a39fcea499ade6dbe741b53b8c65e03611f - name: chesspenguin buildsystem: simple build-commands: @@ -38,3 +48,4 @@ modules: - .flatpak-builder - pgnFilesforExample - engines + - build diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml index 7c1433b..992fc06 100644 --- a/packaging/nfpm.yaml +++ b/packaging/nfpm.yaml @@ -1,4 +1,5 @@ -# deb and rpm packages (https://nfpm.goreleaser.com). Run from the repository root: +# deb, rpm and Arch packages (https://nfpm.goreleaser.com). Run from the repository root: +# packaging/stockfish.sh linux build/stockfish # VERSION=0.1.0 nfpm package -f packaging/nfpm.yaml -p deb -t dist/ (deb, rpm, archlinux) name: chesspenguin arch: amd64 @@ -12,8 +13,9 @@ 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. + View, enter and analyse chess games in PGN: variations, comments, + multi-line engine analysis and whole-game review. Stockfish is included; + any other UCI engine can be added. contents: - src: target/release/chesspenguin @@ -47,6 +49,15 @@ contents: dst: /usr/share/doc/chesspenguin/THIRD_PARTY_NOTICES.md - src: examples/classics.pgn dst: /usr/share/doc/chesspenguin/examples/classics.pgn + # Bundled Stockfish (GPL-3.0); the application looks for it in ../lib/chesspenguin. + - src: build/stockfish/stockfish + dst: /usr/lib/chesspenguin/stockfish + file_info: + mode: 0755 + - src: build/stockfish/Copying.txt + dst: /usr/share/licenses/chesspenguin/stockfish-Copying.txt + - src: build/stockfish/AUTHORS + dst: /usr/share/doc/chesspenguin/stockfish-AUTHORS overrides: deb: diff --git a/packaging/stockfish.sh b/packaging/stockfish.sh new file mode 100755 index 0000000..059a262 --- /dev/null +++ b/packaging/stockfish.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Fetches the official Stockfish release bundled with ChessPenguin and checks its SHA-256. +# +# packaging/stockfish.sh linux dist/stockfish -> stockfish, Copying.txt, AUTHORS +# packaging/stockfish.sh windows dist/stockfish -> stockfish.exe, Copying.txt, AUTHORS +# packaging/stockfish.sh source dist -> stockfish--source.tar.gz (GPL source offer) +# +# The "universal" builds pick the code path for the CPU at run time (x86-64 up to AVX-512), +# so one binary serves every machine. When updating, also update the archive URL and +# sha256 in packaging/flatpak/io.github.vrubelroman.chessPenguin.yml. +set -euo pipefail + +tag="sf_19" +base="https://github.com/official-stockfish/Stockfish/releases/download/${tag}" +linux_asset="stockfish-linux-x86-64-universal.tar.gz" +linux_sha256="9defc0d4e55d49c65a6d042f3e571a39fcea499ade6dbe741b53b8c65e03611f" +windows_asset="stockfish-windows-x86-64-universal.zip" +windows_sha256="3c8bf1f9ea66a09350a40df4f632288285ac206d99f33ab5842c408fc30b48a7" + +target="${1:?usage: $0 linux|windows|source OUT_DIR}" +out="${2:?usage: $0 linux|windows|source OUT_DIR}" +mkdir -p "${out}" +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT + +fetch() { # asset sha256 + curl -fsSL --retry 3 -o "${work}/$1" "${base}/$1" + echo "$2 ${work}/$1" | sha256sum -c --quiet - +} + +# Copies the engine executable matching a glob plus the license files from an unpacked release. +install_from() { # dir glob dest_name + local exe + exe="$(find "$1" -type f -name "$2" | head -n1)" + [[ -n "${exe}" ]] || { echo "stockfish.sh: no $2 in the archive" >&2; exit 1; } + install -m755 "${exe}" "${out}/$3" + for f in Copying.txt AUTHORS; do + local src + src="$(find "$1" -type f -name "${f}" | head -n1)" + [[ -n "${src}" ]] && install -m644 "${src}" "${out}/${f}" + done +} + +case "${target}" in + linux) + fetch "${linux_asset}" "${linux_sha256}" + tar -xzf "${work}/${linux_asset}" -C "${work}" + install_from "${work}" "stockfish-linux-x86-64*" stockfish + ;; + windows) + fetch "${windows_asset}" "${windows_sha256}" + python3 -m zipfile -e "${work}/${windows_asset}" "${work}/x" 2>/dev/null \ + || python -m zipfile -e "${work}/${windows_asset}" "${work}/x" + install_from "${work}/x" "stockfish-windows-x86-64*.exe" stockfish.exe + ;; + source) + curl -fsSL --retry 3 -o "${out}/stockfish-${tag}-source.tar.gz" \ + "https://github.com/official-stockfish/Stockfish/archive/refs/tags/${tag}.tar.gz" + ;; + *) + echo "usage: $0 linux|windows|source OUT_DIR" >&2 + exit 2 + ;; +esac +echo "Stockfish ${tag} (${target}) -> ${out}" diff --git a/scripts/install.sh b/scripts/install.sh index 2d6e3d0..9f69c4c 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1,10 +1,12 @@ #!/usr/bin/env bash # Installs ChessPenguin for the current user (~/.local), or removes it with --uninstall. +# Stockfish is downloaded into ~/.local/lib/chesspenguin once (skip with --no-stockfish). set -euo pipefail app_id="io.github.vrubelroman.chessPenguin" root="$(cd "$(dirname "$0")/.." && pwd)" bin_dir="${HOME}/.local/bin" +lib_dir="${HOME}/.local/lib/chesspenguin" data_dir="${XDG_DATA_HOME:-${HOME}/.local/share}" apps_dir="${data_dir}/applications" icons_dir="${data_dir}/icons/hicolor" @@ -26,6 +28,7 @@ remove_files() { if [[ "${1:-}" == "--uninstall" ]]; then remove_files + rm -rf "${lib_dir}" refresh_caches echo "ChessPenguin removed (settings in ~/.config/chesspenguin are kept)." exit 0 @@ -41,5 +44,8 @@ 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 +if [[ "${1:-}" != "--no-stockfish" && ! -x "${lib_dir}/stockfish" ]]; then + "${root}/packaging/stockfish.sh" linux "${lib_dir}" +fi refresh_caches echo "Installed: ${bin_dir}/chesspenguin (launcher entry «ChessPenguin»)."