Stockfish on request instead of bundled; macOS (Apple Silicon) builds
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

Packages no longer carry Stockfish (about 14 MB instead of 95): the first
analysis without an engine offers to download the official Stockfish 19
"universal" build from GitHub (pinned per platform with its SHA-256, checked
before use, unpacked into the user's local data directory, test-started),
then starts the analysis the user asked for. Settings -> Engines: download
with progress and cancel, "file not found" with download again, removal with
confirmation; "Choose engine file…" for any other engine. A system stockfish
is offered first when there is one. ChessPenguin's Stockfish = bundled
(Flatpak) or downloaded.

macOS: release job and CI job on macos-14 build ChessPenguin.app (icon,
Info.plist, ad-hoc signature) in a .dmg; Homebrew paths for a system
stockfish. Not signed by Apple yet.

Decisions 14-15; design docs/design/engine-download.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-19 09:33:37 +03:00
parent 99264f3d24
commit 50eb5e6623
24 changed files with 2473 additions and 85 deletions

View file

@ -47,6 +47,9 @@ pub struct App {
confirm_close: Option<CloseIntent>,
/// Close the game once the pending "save as" succeeds.
close_after_save: Option<CloseIntent>,
/// The offer to download Stockfish when an action needs an engine.
engine_offer: crate::engine_offer::EngineOffer,
offer_hook_done: bool,
/// A position to find in a database once the game is closed.
find_after_close: Option<(PathBuf, shakmaty::Chess, Vec<shakmaty::Move>, bool)>,
allow_quit: bool,
@ -93,6 +96,7 @@ impl App {
pub fn new(ctx: &egui::Context) -> Self {
let mut settings = Settings::load();
crate::i18n::set_lang(settings.language);
crate::engine_download::clean_leftovers();
if crate::engines::first_run_setup(&mut settings) {
let _ = settings.save();
}
@ -129,6 +133,8 @@ impl App {
confirm_close: None,
close_after_save: None,
find_after_close: None,
engine_offer: crate::engine_offer::EngineOffer::new(),
offer_hook_done: false,
allow_quit: false,
applied_dark: None,
debug: DebugStartup::from_env(),
@ -459,11 +465,70 @@ impl App {
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)"));
Some(cfg) if crate::engine_offer::EngineOffer::engine_ready(&self.settings) => {
self.analysis.start(&cfg, ctx)
}
_ => self
.engine_offer
.ask(crate::engine_offer::Pending::LiveAnalysis, &self.settings),
}
}
/// Makes ChessPenguin's Stockfish (just downloaded) or a found engine the active
/// one, then runs what the user was doing.
fn engine_arrived(
&mut self,
ctx: &egui::Context,
cfg: crate::settings::EngineConfig,
pending: Option<crate::engine_offer::Pending>,
) {
let known = self.settings.engines.iter().position(|e| {
(cfg.builtin && e.builtin) || (!cfg.builtin && !e.builtin && e.path == cfg.path)
});
let index = known.unwrap_or_else(|| {
self.settings.engines.push(cfg);
self.settings.engines.len() - 1
});
self.settings.active_engine = Some(index);
self.settings_dirty = true;
match pending {
Some(crate::engine_offer::Pending::LiveAnalysis) => {
if !self.analysis.is_on() {
self.toggle_engine(ctx);
}
}
Some(crate::engine_offer::Pending::GameAnalysis) => {
let actions = match self.game.as_mut() {
Some(g) => g.start_review_now(&self.settings, ctx),
None => Vec::new(),
};
for a in actions {
match a {
GameAction::PauseLive if self.analysis.is_on() => {
self.analysis.stop();
self.live_paused = true;
}
GameAction::Toast(m) => self.toast(ctx, m),
_ => {}
}
}
}
None => {}
}
}
fn offer_events(&mut self, ctx: &egui::Context) {
for e in self.engine_offer.show(ctx) {
match e {
crate::engine_offer::OfferEvent::Installed(pending) => {
self.engine_arrived(ctx, crate::engines::builtin_config(), pending)
}
crate::engine_offer::OfferEvent::UseSystem(path, pending) => {
let cfg = crate::settings::EngineConfig::new("Stockfish".into(), path);
self.engine_arrived(ctx, cfg, pending)
}
crate::engine_offer::OfferEvent::ChooseFile => self.pick_engine(ctx),
crate::engine_offer::OfferEvent::Toast(m) => self.toast(ctx, m),
}
}
}
@ -575,6 +640,16 @@ impl eframe::App for App {
self.confirm_close = Some(CloseIntent::QuitApp);
}
self.handle_async(&ctx);
// Dev hook (screenshots): the engine offer as on pressing L without an engine.
if std::env::var("CP_ENGINE_OFFER").is_ok() && !self.offer_hook_done {
self.offer_hook_done = true;
self.engine_offer
.ask(crate::engine_offer::Pending::LiveAnalysis, &self.settings);
if std::env::var("CP_ENGINE_OFFER").as_deref() == Ok("download") {
self.engine_offer.start(&ctx);
}
}
self.offer_events(&ctx);
self.debug_step(&ctx);
self.debug_screenshot(&ctx);
self.analysis.poll();
@ -597,6 +672,9 @@ impl eframe::App for App {
match a {
GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary),
GameAction::FindPosition(db) => self.find_position(&ctx, db),
GameAction::NeedEngine => self
.engine_offer
.ask(crate::engine_offer::Pending::GameAnalysis, &self.settings),
GameAction::Sound(s) => self.play(s),
GameAction::CopyText(text, msg) => {
ctx.copy_text(text);
@ -669,11 +747,24 @@ impl eframe::App for App {
}
}
self.settings_ui.download = self.engine_offer.stage();
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::DownloadEngine => self.engine_offer.start(&ctx),
SettingsAction::CancelDownload => self.engine_offer.cancel(),
SettingsAction::RemoveDownloaded => {
if let Err(e) = crate::engine_download::remove() {
self.toast(&ctx, e.to_string());
}
if self.settings.active_engine().is_some_and(|e| e.builtin)
&& !crate::engine_offer::EngineOffer::engine_ready(&self.settings)
{
self.analysis.stop();
}
}
SettingsAction::TestSound => {
if self.settings.sound_enabled {
self.sound

View file

@ -0,0 +1,421 @@
//! Downloading the official Stockfish on request (decision 14): the "universal" build of
//! a pinned release from github.com/official-stockfish/Stockfish, checked against its
//! SHA-256 before use and unpacked into the user's data directory. Nothing is downloaded
//! without the user asking.
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use sha2::{Digest, Sha256};
/// The release offered; keep in step with `packaging/stockfish.sh` (Flatpak bundles it).
const TAG: &str = "sf_19";
/// An archive of the release for this platform.
struct Asset {
file: &'static str,
sha256: &'static str,
/// Bytes, for the size shown before the download.
size: u64,
zip: bool,
}
fn asset() -> Option<Asset> {
let (file, sha256, size, zip) = match (std::env::consts::OS, std::env::consts::ARCH) {
("linux", "x86_64") => (
"stockfish-linux-x86-64-universal.tar.gz",
"9defc0d4e55d49c65a6d042f3e571a39fcea499ade6dbe741b53b8c65e03611f",
81_388_977,
false,
),
("linux", "aarch64") => (
"stockfish-linux-arm64-universal.tar.gz",
"fe26cfd1d9db4c8af3d21e24d9ff34cacb31c1f940085a7583da11796f2bac01",
80_181_250,
false,
),
("macos", _) => (
"stockfish-macos-universal.tar.gz",
"a1f0e3bcc5a6927a11fe6fc8e54a779754645f3c2bae2cf13420fd1957adaa77",
82_323_876,
false,
),
("windows", "x86_64") => (
"stockfish-windows-x86-64-universal.zip",
"3c8bf1f9ea66a09350a40df4f632288285ac206d99f33ab5842c408fc30b48a7",
81_431_614,
true,
),
("windows", "aarch64") => (
"stockfish-windows-arm64-universal.zip",
"8372ad3f0d7276deb2c70f801f541ec7db463219fc6d9c7592864e542aa4f401",
80_190_536,
true,
),
_ => return None,
};
Some(Asset {
file,
sha256,
size,
zip,
})
}
/// Whether a download is offered on this platform at all.
pub fn available() -> bool {
asset().is_some()
}
/// Size of the download in megabytes (rounded), for the offer.
pub fn size_mb() -> u64 {
asset().map_or(0, |a| a.size.div_ceil(1_000_000))
}
#[cfg(windows)]
const EXE: &str = "stockfish.exe";
#[cfg(not(windows))]
const EXE: &str = "stockfish";
/// Where the downloaded engine lives: `<local data dir>/engines/sf_19/` (on Windows
/// the local, not the roaming, profile).
fn dir() -> Option<PathBuf> {
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
.map(|d| d.data_local_dir().join("engines").join(TAG))
}
/// Removes what an interrupted download left (the program was closed meanwhile).
pub fn clean_leftovers() {
let Some(entries) = dir().and_then(|d| std::fs::read_dir(d).ok()) else {
return;
};
for e in entries.flatten() {
if e.path().extension().is_some_and(|x| x == "part") {
let _ = std::fs::remove_file(e.path());
}
}
}
/// The downloaded engine, if it is there.
pub fn installed() -> Option<PathBuf> {
let p = dir()?.join(EXE);
p.is_file().then_some(p)
}
/// Removes the downloaded engine (frees its space).
pub fn remove() -> std::io::Result<()> {
match dir() {
Some(d) if d.exists() => std::fs::remove_dir_all(d),
_ => Ok(()),
}
}
/// What went wrong, in terms of what the user can do about it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Failure {
/// No connection, or the connection broke.
Network(String),
/// The server answered with an error status.
Server(u16),
/// The engine was installed but does not start on this computer.
Broken,
/// The file is not the published one (damaged on the way or replaced).
Checksum,
/// Writing to the disk failed (space, permissions).
Disk(String),
/// No download for this platform.
Unsupported,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Stage {
Downloading { done: u64, total: u64 },
Unpacking,
Done(PathBuf),
Failed(Failure),
Cancelled,
}
/// A download running in a background thread.
pub struct Download {
stage: Arc<Mutex<Stage>>,
cancel: Arc<AtomicBool>,
}
impl Download {
pub fn start(ctx: &egui::Context) -> Download {
let total = asset().map_or(0, |a| a.size);
let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0, total }));
let cancel = Arc::new(AtomicBool::new(false));
let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone());
let spawned = std::thread::Builder::new()
.name("engine-download".into())
.spawn(move || {
let report = |st: Stage| {
if let Ok(mut g) = s.lock() {
*g = st;
}
ctx.request_repaint();
};
let end = match run(&report, &c) {
Ok(path) => Stage::Done(path),
Err(_) if c.load(Ordering::Relaxed) => Stage::Cancelled,
Err(f) => Stage::Failed(f),
};
report(end);
});
if spawned.is_err()
&& let Ok(mut g) = stage.lock()
{
*g = Stage::Failed(Failure::Disk("cannot start a thread".into()));
}
Download { stage, cancel }
}
pub fn stage(&self) -> Stage {
self.stage
.lock()
.map(|g| g.clone())
.unwrap_or(Stage::Cancelled)
}
pub fn cancel(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
pub fn running(&self) -> bool {
matches!(self.stage(), Stage::Downloading { .. } | Stage::Unpacking)
}
}
impl Drop for Download {
fn drop(&mut self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result<PathBuf, Failure> {
let asset = asset().ok_or(Failure::Unsupported)?;
let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?;
std::fs::create_dir_all(&dir).map_err(disk)?;
let archive = dir.join(format!("{}.part", asset.file));
let url = format!(
"https://github.com/official-stockfish/Stockfish/releases/download/{TAG}/{}",
asset.file
);
let result = fetch(&url, &archive, &asset, report, cancel)
.and_then(|()| {
report(Stage::Unpacking);
unpack(&archive, &dir, asset.zip)
})
.and_then(|exe| check_runs(&exe).map(|()| exe));
let _ = std::fs::remove_file(&archive);
if result.is_err() {
// Nothing half-installed is left behind.
let _ = std::fs::remove_file(dir.join(EXE));
}
result
}
/// Downloads `url` into `to`, checking the size and the SHA-256 on the way.
fn fetch(
url: &str,
to: &Path,
asset: &Asset,
report: &dyn Fn(Stage),
cancel: &AtomicBool,
) -> Result<(), Failure> {
let mut response = ureq::get(url).call().map_err(|e| match e {
ureq::Error::StatusCode(code) => Failure::Server(code),
e => Failure::Network(e.to_string()),
})?;
let total = response
.headers()
.get("content-length")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(asset.size);
let mut body = response
.body_mut()
.with_config()
.limit(asset.size + 1)
.reader();
let mut file = std::fs::File::create(to).map_err(disk)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 256 * 1024];
let mut done = 0u64;
let mut reported = 0u64;
loop {
if cancel.load(Ordering::Relaxed) {
return Err(Failure::Network("cancelled".into()));
}
let n = body
.read(&mut buf)
.map_err(|e| Failure::Network(e.to_string()))?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
file.write_all(&buf[..n]).map_err(disk)?;
done += n as u64;
if done - reported >= 512 * 1024 {
reported = done;
report(Stage::Downloading { done, total });
}
}
file.sync_all().map_err(disk)?;
let digest: String = hasher
.finalize()
.iter()
.map(|b| format!("{b:02x}"))
.collect();
if done != asset.size || digest != asset.sha256 {
return Err(Failure::Checksum);
}
Ok(())
}
/// Takes the engine executable and its license files out of the archive.
fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result<PathBuf, Failure> {
let exe = dir.join(EXE);
let wanted = |name: &str| -> Option<PathBuf> {
let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
if base.starts_with("stockfish") && (base.ends_with(".exe") || !base.contains('.')) {
Some(exe.clone())
} else if base == "Copying.txt" || base == "AUTHORS" {
Some(dir.join(base))
} else {
None
}
};
let file = std::fs::File::open(archive).map_err(disk)?;
if zip {
let mut z = zip::ZipArchive::new(file).map_err(|e| Failure::Disk(e.to_string()))?;
for i in 0..z.len() {
let mut entry = z.by_index(i).map_err(|e| Failure::Disk(e.to_string()))?;
if !entry.is_file() {
continue;
}
let name = entry
.name()
.map_err(|e| Failure::Disk(e.to_string()))?
.into_owned();
if let Some(dest) = wanted(&name) {
let mut out = std::fs::File::create(&dest).map_err(disk)?;
std::io::copy(&mut entry, &mut out).map_err(disk)?;
}
}
} else {
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
for entry in tar.entries().map_err(disk)? {
let mut entry = entry.map_err(disk)?;
if !entry.header().entry_type().is_file() {
continue;
}
let name = entry.path().map_err(disk)?.to_string_lossy().into_owned();
if let Some(dest) = wanted(&name) {
let mut out = std::fs::File::create(&dest).map_err(disk)?;
std::io::copy(&mut entry, &mut out).map_err(disk)?;
}
}
}
if !exe.is_file() {
return Err(Failure::Disk("no engine in the archive".into()));
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).map_err(disk)?;
}
Ok(exe)
}
/// Starts the engine once and waits for its name: the binary runs on this computer.
fn check_runs(exe: &Path) -> Result<(), Failure> {
let mut cmd = std::process::Command::new(exe);
cmd.arg("quit");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// No console window.
cmd.creation_flags(0x0800_0000);
}
let out = cmd.output().map_err(|_| Failure::Broken)?;
if String::from_utf8_lossy(&out.stdout).contains("Stockfish") {
Ok(())
} else {
Err(Failure::Broken)
}
}
fn disk(e: std::io::Error) -> Failure {
Failure::Disk(e.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn this_platform_has_a_pinned_download() {
if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
let a = asset().expect("asset");
assert_eq!(a.sha256.len(), 64);
assert!(!a.zip);
assert_eq!(size_mb(), 82);
}
}
/// Downloads the real release (≈ 80 MB): `XDG_DATA_HOME=… cargo test -- --ignored`.
#[test]
#[ignore]
fn downloads_the_real_engine() {
let ctx = egui::Context::default();
let d = Download::start(&ctx);
while d.running() {
std::thread::sleep(std::time::Duration::from_millis(200));
}
let Stage::Done(exe) = d.stage() else {
panic!("{:?}", d.stage());
};
let out = std::process::Command::new(&exe)
.arg("quit")
.output()
.expect("runs");
assert!(String::from_utf8_lossy(&out.stdout).contains("Stockfish"));
assert_eq!(installed(), Some(exe));
}
#[test]
fn unpacks_the_engine_and_licenses_from_a_tarball() {
let dir = std::env::temp_dir().join(format!("cp-sf-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let archive = dir.join("a.tar.gz");
{
let gz = flate2::write::GzEncoder::new(
std::fs::File::create(&archive).unwrap(),
flate2::Compression::fast(),
);
let mut b = tar::Builder::new(gz);
for (name, data) in [
("stockfish/stockfish-linux-x86-64-universal", &b"engine"[..]),
("stockfish/Copying.txt", b"GPL"),
("stockfish/README.md", b"x"),
] {
let mut h = tar::Header::new_gnu();
h.set_size(data.len() as u64);
h.set_mode(0o644);
h.set_cksum();
b.append_data(&mut h, name, data).unwrap();
}
b.into_inner().unwrap().finish().unwrap();
}
let exe = unpack(&archive, &dir, false).expect("unpacked");
assert_eq!(std::fs::read(&exe).unwrap(), b"engine");
assert!(dir.join("Copying.txt").is_file());
assert!(!dir.join("README.md").exists());
std::fs::remove_dir_all(&dir).unwrap();
}
}

View file

@ -0,0 +1,467 @@
//! Getting an engine when there is none (decision 14, `docs/design/engine-download.md`):
//! an offer to download the official Stockfish, its progress (hidden into a small
//! indicator if the user wants), the errors with what to do next, and the action the
//! user came for (live analysis or game analysis) started once the engine is there.
use std::path::PathBuf;
use egui::{RichText, Ui, vec2};
use crate::engine_download::{self, Download, Failure, Stage};
use crate::i18n::{tr, trf};
use crate::settings::Settings;
/// What the user wanted to do when the engine turned out to be missing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pending {
LiveAnalysis,
GameAnalysis,
}
/// What the owner should do.
pub enum OfferEvent {
/// The downloaded Stockfish is ready: make it the active engine, then run `Pending`.
Installed(Option<Pending>),
/// Use the Stockfish found on this computer, then run `Pending`.
UseSystem(PathBuf, Option<Pending>),
/// Open the file dialog to choose an engine.
ChooseFile,
Toast(String),
}
#[derive(Clone, PartialEq)]
enum Mode {
Offer,
/// A `stockfish` is installed on the computer.
System(PathBuf),
/// The downloaded engine was deleted from the disk.
Missing,
}
pub struct EngineOffer {
open: bool,
mode: Mode,
pending: Option<Pending>,
download: Option<Download>,
failure: Option<Failure>,
/// Bytes per second, smoothed, for "about 20 s left".
speed: f64,
last: Option<(f64, u64)>,
}
impl EngineOffer {
pub fn new() -> EngineOffer {
EngineOffer {
open: false,
mode: Mode::Offer,
pending: None,
download: None,
failure: None,
speed: 0.0,
last: None,
}
}
/// Whether the active engine can be started.
pub fn engine_ready(settings: &Settings) -> bool {
settings
.active_engine()
.and_then(|e| e.executable())
.is_some_and(|p| p.is_file())
}
/// Opens the offer for an action that needs an engine.
pub fn ask(&mut self, pending: Pending, settings: &Settings) {
self.pending = Some(pending);
self.failure = None;
self.mode = if settings.active_engine().is_some_and(|e| e.builtin) {
Mode::Missing
} else if settings.engines.is_empty()
&& let Some(p) = crate::engines::system_stockfish()
{
Mode::System(p)
} else {
Mode::Offer
};
self.open = true;
}
/// Starts the download (from the offer or from the settings).
pub fn start(&mut self, ctx: &egui::Context) {
if self.download.as_ref().is_some_and(Download::running) {
return;
}
self.failure = None;
self.speed = 0.0;
self.last = None;
self.download = Some(Download::start(ctx));
}
/// The download's stage, for the settings window.
pub fn stage(&self) -> Option<Stage> {
self.download.as_ref().map(Download::stage)
}
pub fn cancel(&mut self) {
if let Some(d) = &self.download {
d.cancel();
}
}
/// The offer window, the indicator of a hidden download, and what follows a
/// finished one.
pub fn show(&mut self, ctx: &egui::Context) -> Vec<OfferEvent> {
let mut events = Vec::new();
let now = ctx.input(|i| i.time);
if let Some(d) = &self.download {
match d.stage() {
Stage::Done(_) => {
let pending = self.pending.take();
events.push(OfferEvent::Installed(pending));
events.push(OfferEvent::Toast(
match pending {
Some(Pending::GameAnalysis) => {
tr("Stockfish installed — game analysis started")
}
Some(Pending::LiveAnalysis) => {
tr("Stockfish installed — analysis is on")
}
None => tr("Stockfish installed"),
}
.to_string(),
));
self.download = None;
self.open = false;
}
Stage::Failed(f) => {
if !self.open {
events.push(OfferEvent::Toast(
tr("⚠ Stockfish wasn't downloaded").into(),
));
}
self.failure = Some(f);
self.download = None;
}
Stage::Cancelled => {
self.download = None;
self.pending = None;
self.open = false;
}
Stage::Downloading { done, .. } => {
if let Some((t, b)) = self.last
&& now - t >= 0.5
{
let rate = (done.saturating_sub(b)) as f64 / (now - t);
self.speed = if self.speed == 0.0 {
rate
} else {
0.7 * self.speed + 0.3 * rate
};
self.last = Some((now, done));
} else if self.last.is_none() {
self.last = Some((now, done));
}
ctx.request_repaint_after(std::time::Duration::from_millis(200));
}
Stage::Unpacking => {
ctx.request_repaint_after(std::time::Duration::from_millis(200));
}
}
}
if self.open {
self.window(ctx, &mut events);
} else if self.download.is_some() || self.failure.is_some() {
self.indicator(ctx);
}
events
}
fn window(&mut self, ctx: &egui::Context, events: &mut Vec<OfferEvent>) {
let modal = egui::Modal::new(egui::Id::new("engine_offer")).show(ctx, |ui| {
ui.set_width(440.0);
if let Some(d) = &self.download {
self.progress_body(ui, &d.stage());
} else if let Some(f) = self.failure.clone() {
self.failure_body(ui, &f, events);
} else {
self.offer_body(ui, events);
}
});
if modal.should_close() {
// Escape or a click outside: "Later", or "Hide" while downloading.
self.open = false;
if self.download.is_none() {
self.pending = None;
self.failure = None;
}
}
}
fn offer_body(&mut self, ui: &mut Ui, events: &mut Vec<OfferEvent>) {
let size = engine_download::size_mb();
let (title, text) = match &self.mode {
Mode::Offer => (
tr("Analysis needs a chess engine"),
tr(
"Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.",
),
),
Mode::System(_) => (
tr("Analysis needs a chess engine"),
tr("Stockfish is already installed on this computer."),
),
Mode::Missing => (
tr("Stockfish not found"),
tr("The Stockfish file is missing from the disk. Download it again?"),
),
};
ui.heading(title);
ui.add_space(6.0);
ui.label(text);
ui.add_space(4.0);
if matches!(self.mode, Mode::System(_)) {
ui.label(
RichText::new(trf(
"Or download the official Stockfish 19 build ({mb} MB).",
&[("mb", &size)],
))
.weak(),
);
} else {
ui.label(
RichText::new(trf(
"{mb} MB · from the official Stockfish page",
&[("mb", &size)],
))
.weak(),
)
.on_hover_text("https://github.com/official-stockfish/Stockfish/releases/tag/sf_19");
ui.label(RichText::new(tr("Installed for your account only")).weak());
}
ui.add_space(10.0);
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
match self.mode.clone() {
Mode::System(p) => {
let main = ui.add(egui::Button::new(RichText::new(tr("Use it")).strong()));
main.request_focus();
if main.clicked() || enter {
events.push(OfferEvent::UseSystem(p, self.pending.take()));
self.open = false;
}
if ui.button(tr("Later")).clicked() {
self.open = false;
self.pending = None;
}
if ui.button(tr("Download")).clicked() {
self.start(ui.ctx());
}
}
mode => {
let label = if mode == Mode::Missing {
tr("Download again")
} else {
tr("Download Stockfish")
};
let main = ui.add(egui::Button::new(RichText::new(label).strong()));
main.request_focus();
if main.clicked() || enter {
self.start(ui.ctx());
}
if ui.button(tr("Later")).clicked() {
self.open = false;
self.pending = None;
}
}
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
if ui.button(tr("Choose engine file…")).clicked() {
events.push(OfferEvent::ChooseFile);
self.open = false;
self.pending = None;
}
});
});
});
}
fn progress_body(&mut self, ui: &mut Ui, stage: &Stage) {
ui.heading(tr("Downloading Stockfish"));
ui.add_space(8.0);
match *stage {
Stage::Downloading { done, total } => {
let frac = if total > 0 {
done as f32 / total as f32
} else {
0.0
};
ui.add(
egui::ProgressBar::new(frac)
.show_percentage()
.desired_width(ui.available_width()),
);
let mb = |b: u64| b / 1_000_000;
let mut line = trf(
"{done} of {total} MB",
&[("done", &mb(done)), ("total", &mb(total))],
);
if self.speed > 0.0 {
let left = (total.saturating_sub(done)) as f64 / self.speed;
line.push_str(" · ");
line.push_str(&trf("about {s} s left", &[("s", &(left.ceil() as u64))]));
}
ui.label(line);
}
_ => {
ui.horizontal(|ui| {
ui.spinner();
ui.label(tr("Checking and installing…"));
});
}
}
ui.add_space(4.0);
let after = match self.pending {
Some(Pending::GameAnalysis) => {
tr("Game analysis will start by itself when the download finishes.")
}
_ => tr("Analysis will start by itself when the download finishes."),
};
ui.label(RichText::new(after).weak());
ui.add_space(10.0);
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let hide = ui.add(egui::Button::new(RichText::new(tr("Hide")).strong()));
hide.request_focus();
if hide.clicked() {
self.open = false;
}
if ui.button(tr("Cancel download")).clicked() {
self.cancel();
}
});
});
}
fn failure_body(&mut self, ui: &mut Ui, f: &Failure, events: &mut Vec<OfferEvent>) {
ui.heading(tr("⚠ Stockfish wasn't downloaded"));
ui.add_space(6.0);
let (text, details) = failure_text(f);
ui.label(text);
if let Some(d) = details {
egui::CollapsingHeader::new(tr("Details"))
.id_salt("download_details")
.show(ui, |ui| {
ui.label(RichText::new(d).small().weak());
});
}
if matches!(f, Failure::Network(_)) && cfg!(target_os = "linux") {
ui.label(
RichText::new(tr(
"A stockfish package of your distribution is found by ChessPenguin too.",
))
.weak(),
);
}
ui.add_space(10.0);
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let retry = ui.add(egui::Button::new(RichText::new(tr("Retry")).strong()));
retry.request_focus();
if retry.clicked() || enter {
self.start(ui.ctx());
}
if ui.button(tr("Close")).clicked() {
self.open = false;
self.failure = None;
self.pending = None;
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
if ui.button(tr("Choose engine file…")).clicked() {
events.push(OfferEvent::ChooseFile);
self.open = false;
self.failure = None;
self.pending = None;
}
});
});
});
}
/// "⬇ Stockfish 42 %" in the top right corner while a download runs hidden (or
/// "⚠ Stockfish wasn't downloaded" after it failed); a click opens the window.
fn indicator(&mut self, ctx: &egui::Context) {
let text = match self.download.as_ref().map(Download::stage) {
Some(Stage::Downloading { done, total }) if total > 0 => {
format!("⬇ Stockfish {} %", done * 100 / total)
}
Some(_) => "⬇ Stockfish…".to_string(),
None => tr("⚠ Stockfish wasn't downloaded").to_string(),
};
egui::Area::new(egui::Id::new("download_indicator"))
.anchor(egui::Align2::RIGHT_BOTTOM, vec2(-12.0, -12.0))
.order(egui::Order::Foreground)
.show(ctx, |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
if ui
.add(egui::Label::new(text).sense(egui::Sense::click()))
.on_hover_text(tr("Show the download"))
.clicked()
{
self.open = true;
}
let close = crate::widgets::small_close_button(ui);
let close = if self.download.is_some() {
close.on_hover_text(tr("Cancel download"))
} else {
close.on_hover_text(tr("Close"))
};
if close.clicked() {
if self.download.is_some() {
self.cancel();
} else {
self.failure = None;
self.pending = None;
}
}
});
});
});
}
}
/// What to tell the user about a failure, and the technical details (collapsed).
fn failure_text(f: &Failure) -> (String, Option<String>) {
match f {
Failure::Network(e) => (
tr("Couldn't connect. Check your internet connection and try again.").into(),
Some(e.clone()),
),
Failure::Server(code) => (
trf(
"The server didn't provide the file (error {code}). Please try again later.",
&[("code", code)],
),
None,
),
Failure::Checksum => (
tr("The downloaded file failed the integrity check and was deleted. It was most likely damaged during the download.").into(),
Some("SHA-256 mismatch".into()),
),
Failure::Disk(e) => (
tr("Couldn't save the engine on the disk (not enough space or no permission).").into(),
Some(e.clone()),
),
Failure::Broken => (
tr("Stockfish was downloaded but doesn't run on this computer.").into(),
None,
),
Failure::Unsupported => (
tr("There is no Stockfish download for this computer. Choose an engine file instead.")
.into(),
None,
),
}
}

View file

@ -1,5 +1,6 @@
//! Finding engines without a file dialog: the Stockfish shipped with the packages and a
//! `stockfish` installed by the system package manager.
//! Finding engines without a file dialog: ChessPenguin's Stockfish (bundled in the
//! Flatpak, otherwise downloaded on request, see `engine_download`) and a `stockfish`
//! installed by the system package manager.
use std::path::{Path, PathBuf};
@ -26,10 +27,23 @@ pub fn bundled_stockfish() -> Option<PathBuf> {
candidates.into_iter().flatten().find(|p| is_executable(p))
}
/// `stockfish` from `PATH` (for example, the distribution package).
/// ChessPenguin's Stockfish: the bundled one, or else the downloaded one.
pub fn own_stockfish() -> Option<PathBuf> {
bundled_stockfish().or_else(crate::engine_download::installed)
}
/// `stockfish` from `PATH` (for example, the distribution package). On macOS an app
/// started from the Finder does not get the shell's `PATH`: Homebrew's directories are
/// looked at too.
pub fn system_stockfish() -> Option<PathBuf> {
let path = std::env::var_os("PATH")?;
let path = std::env::var_os("PATH").unwrap_or_default();
let extra: &[&str] = if cfg!(target_os = "macos") {
&["/opt/homebrew/bin", "/usr/local/bin"]
} else {
&[]
};
std::env::split_paths(&path)
.chain(extra.iter().map(PathBuf::from))
.map(|dir| dir.join(STOCKFISH))
.find(|p| is_executable(p))
}
@ -50,7 +64,7 @@ fn is_executable(p: &Path) -> bool {
}
pub fn builtin_config() -> EngineConfig {
let mut cfg = EngineConfig::new(tr("Stockfish (built-in)").into(), PathBuf::new());
let mut cfg = EngineConfig::new("Stockfish 19".into(), PathBuf::new());
cfg.builtin = true;
cfg
}
@ -63,7 +77,7 @@ pub fn first_run_setup(settings: &mut Settings) -> bool {
}
settings.engines_discovered = true;
if settings.engines.is_empty() {
let found = if bundled_stockfish().is_some() {
let found = if own_stockfish().is_some() {
Some(builtin_config())
} else {
system_stockfish().map(|p| EngineConfig::new("Stockfish".into(), p))
@ -79,7 +93,7 @@ pub fn first_run_setup(settings: &mut Settings) -> bool {
/// Engines found on this system that are not in the list yet (offered in the settings).
pub fn suggestions(settings: &Settings) -> Vec<EngineConfig> {
let mut out = Vec::new();
if bundled_stockfish().is_some() && !settings.engines.iter().any(|e| e.builtin) {
if own_stockfish().is_some() && !settings.engines.iter().any(|e| e.builtin) {
out.push(builtin_config());
}
if let Some(p) = system_stockfish() {

View file

@ -83,6 +83,8 @@ pub enum GameAction {
ResumeLive,
/// Find the current position in a database (`None`: the last chosen one).
FindPosition(Option<std::path::PathBuf>),
/// Game analysis needs an engine that is not there yet (offer to download one).
NeedEngine,
}
impl GameView {
@ -275,6 +277,11 @@ impl GameView {
ctx: &egui::Context,
actions: &mut Vec<GameAction>,
) {
if !crate::engine_offer::EngineOffer::engine_ready(settings) {
self.review.dialog_open = false;
actions.push(GameAction::NeedEngine);
return;
}
let Some(engine) = settings.active_engine().cloned() else {
self.review.dialog_open = true;
return;
@ -1075,6 +1082,17 @@ impl GameView {
}
}
/// Starts the game analysis right away (after an engine was installed for it).
pub fn start_review_now(
&mut self,
settings: &Settings,
ctx: &egui::Context,
) -> Vec<GameAction> {
let mut actions = Vec::new();
self.start_review(settings, true, ctx, &mut actions);
actions
}
/// Moves the cursor to the end of the main line.
pub fn goto_main_line_end(&mut self) {
let end = self.game.line_end(self.game.root());

View file

@ -79,6 +79,399 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String {
// [English, Русский, Français, Deutsch, Español, Italiano]
const ROWS: &[[&str; 6]] = &[
// --- engine download ---
[
"Stockfish installed — game analysis started",
"Stockfish установлен — анализ партии запущен",
"Stockfish installé — analyse de la partie lancée",
"Stockfish installiert — Partieanalyse gestartet",
"Stockfish instalado — análisis de la partida iniciado",
"Stockfish installato — analisi della partita avviata",
],
[
"Stockfish installed — analysis is on",
"Stockfish установлен — анализ включён",
"Stockfish installé — l'analyse est active",
"Stockfish installiert — Analyse läuft",
"Stockfish instalado — análisis activado",
"Stockfish installato — analisi attiva",
],
[
"Stockfish installed",
"Stockfish установлен",
"Stockfish installé",
"Stockfish installiert",
"Stockfish instalado",
"Stockfish installato",
],
[
"⚠ Stockfish wasn't downloaded",
"⚠ Stockfish не скачан",
"⚠ Stockfish n'a pas été téléchargé",
"⚠ Stockfish wurde nicht heruntergeladen",
"⚠ Stockfish no se descargó",
"⚠ Stockfish non è stato scaricato",
],
[
"Analysis needs a chess engine",
"Для анализа нужен движок",
"L'analyse nécessite un moteur",
"Für die Analyse wird eine Engine benötigt",
"El análisis necesita un motor",
"L'analisi richiede un motore",
],
[
"Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.",
"Скачать Stockfish — самый сильный бесплатный шахматный движок? Анализ включится сам, как только загрузка закончится.",
"Télécharger Stockfish, le meilleur moteur d'échecs gratuit ? L'analyse démarrera dès la fin du téléchargement.",
"Stockfish herunterladen, die stärkste kostenlose Schach-Engine? Die Analyse startet, sobald der Download fertig ist.",
"¿Descargar Stockfish, el motor de ajedrez gratuito más fuerte? El análisis empezará en cuanto termine la descarga.",
"Scaricare Stockfish, il motore scacchistico gratuito più forte? L'analisi partirà appena finisce il download.",
],
[
"Stockfish is already installed on this computer.",
"На компьютере уже установлен Stockfish.",
"Stockfish est déjà installé sur cet ordinateur.",
"Stockfish ist auf diesem Computer bereits installiert.",
"Stockfish ya está instalado en este ordenador.",
"Stockfish è già installato su questo computer.",
],
[
"Stockfish not found",
"Stockfish не найден",
"Stockfish introuvable",
"Stockfish nicht gefunden",
"Stockfish no encontrado",
"Stockfish non trovato",
],
[
"The Stockfish file is missing from the disk. Download it again?",
"Файл Stockfish пропал с диска. Скачать его заново?",
"Le fichier Stockfish a disparu du disque. Le télécharger à nouveau ?",
"Die Stockfish-Datei fehlt auf der Festplatte. Erneut herunterladen?",
"El archivo de Stockfish ya no está en el disco. ¿Descargarlo de nuevo?",
"Il file di Stockfish non è più sul disco. Scaricarlo di nuovo?",
],
[
"Installed for your account only",
"Устанавливается только для вас",
"Installé pour votre compte uniquement",
"Nur für Ihr Konto installiert",
"Se instala solo para su cuenta",
"Installato solo per il tuo account",
],
[
"Use it",
"Использовать его",
"L'utiliser",
"Diese verwenden",
"Usarlo",
"Usalo",
],
[
"Later",
"Позже",
"Plus tard",
"Später",
"Más tarde",
"Più tardi",
],
[
"Download",
"Скачать",
"Télécharger",
"Herunterladen",
"Descargar",
"Scarica",
],
[
"Download again",
"Скачать заново",
"Télécharger à nouveau",
"Erneut herunterladen",
"Descargar de nuevo",
"Scarica di nuovo",
],
[
"Download Stockfish",
"Скачать Stockfish",
"Télécharger Stockfish",
"Stockfish herunterladen",
"Descargar Stockfish",
"Scarica Stockfish",
],
[
"Choose engine file…",
"Указать файл движка…",
"Choisir le fichier du moteur…",
"Engine-Datei wählen…",
"Elegir archivo del motor…",
"Scegli il file del motore…",
],
[
"+ Choose engine file…",
"+ Указать файл движка…",
"+ Choisir le fichier du moteur…",
"+ Engine-Datei wählen…",
"+ Elegir archivo del motor…",
"+ Scegli il file del motore…",
],
[
"Downloading Stockfish",
"Скачивание Stockfish",
"Téléchargement de Stockfish",
"Stockfish wird heruntergeladen",
"Descargando Stockfish",
"Download di Stockfish",
],
[
"Checking and installing…",
"Проверка и установка…",
"Vérification et installation…",
"Prüfen und installieren…",
"Comprobando e instalando…",
"Verifica e installazione…",
],
[
"Game analysis will start by itself when the download finishes.",
"Анализ партии начнётся сам после загрузки.",
"L'analyse de la partie démarrera seule à la fin du téléchargement.",
"Die Partieanalyse startet nach dem Download von selbst.",
"El análisis de la partida empezará solo al terminar la descarga.",
"L'analisi della partita partirà da sola a fine download.",
],
[
"Analysis will start by itself when the download finishes.",
"Анализ включится сам после загрузки.",
"L'analyse démarrera seule à la fin du téléchargement.",
"Die Analyse startet nach dem Download von selbst.",
"El análisis empezará solo al terminar la descarga.",
"L'analisi partirà da sola a fine download.",
],
[
"Hide",
"Скрыть",
"Masquer",
"Ausblenden",
"Ocultar",
"Nascondi",
],
[
"Cancel download",
"Отменить загрузку",
"Annuler le téléchargement",
"Download abbrechen",
"Cancelar la descarga",
"Annulla il download",
],
[
"Details",
"Подробности",
"Détails",
"Details",
"Detalles",
"Dettagli",
],
[
"A stockfish package of your distribution is found by ChessPenguin too.",
"Пакет stockfish вашего дистрибутива ChessPenguin тоже находит сам.",
"ChessPenguin trouve aussi le paquet stockfish de votre distribution.",
"ChessPenguin findet auch das stockfish-Paket Ihrer Distribution.",
"ChessPenguin también encuentra el paquete stockfish de su distribución.",
"ChessPenguin trova anche il pacchetto stockfish della tua distribuzione.",
],
[
"Close",
"Закрыть",
"Fermer",
"Schließen",
"Cerrar",
"Chiudi",
],
[
"Show the download",
"Показать загрузку",
"Afficher le téléchargement",
"Download anzeigen",
"Mostrar la descarga",
"Mostra il download",
],
[
"Couldn't connect. Check your internet connection and try again.",
"Не удалось подключиться. Проверьте интернет и попробуйте ещё раз.",
"Connexion impossible. Vérifiez votre connexion Internet et réessayez.",
"Keine Verbindung. Prüfen Sie die Internetverbindung und versuchen Sie es erneut.",
"No se pudo conectar. Compruebe su conexión a Internet e inténtelo de nuevo.",
"Impossibile connettersi. Controlla la connessione Internet e riprova.",
],
[
"The downloaded file failed the integrity check and was deleted. It was most likely damaged during the download.",
"Скачанный файл не прошёл проверку и удалён. Скорее всего, он повредился при загрузке.",
"Le fichier téléchargé n'a pas passé la vérification et a été supprimé. Il a probablement été endommagé pendant le téléchargement.",
"Die heruntergeladene Datei hat die Prüfung nicht bestanden und wurde gelöscht. Sie wurde wahrscheinlich beim Download beschädigt.",
"El archivo descargado no pasó la verificación y se eliminó. Probablemente se dañó durante la descarga.",
"Il file scaricato non ha superato la verifica ed è stato eliminato. Probabilmente si è danneggiato durante il download.",
],
[
"Couldn't save the engine on the disk (not enough space or no permission).",
"Не удалось сохранить движок на диск (не хватает места или нет прав).",
"Impossible d'enregistrer le moteur sur le disque (espace insuffisant ou pas de droits).",
"Die Engine konnte nicht gespeichert werden (kein Platz oder keine Berechtigung).",
"No se pudo guardar el motor en el disco (falta espacio o permisos).",
"Impossibile salvare il motore sul disco (spazio insufficiente o permessi mancanti).",
],
[
"Stockfish was downloaded but doesn't run on this computer.",
"Stockfish скачан, но не запускается на этом компьютере.",
"Stockfish a été téléchargé mais ne fonctionne pas sur cet ordinateur.",
"Stockfish wurde heruntergeladen, läuft aber auf diesem Computer nicht.",
"Stockfish se descargó pero no funciona en este ordenador.",
"Stockfish è stato scaricato ma non funziona su questo computer.",
],
[
"There is no Stockfish download for this computer. Choose an engine file instead.",
"Для этого компьютера нет сборки Stockfish. Укажите файл движка.",
"Aucune version de Stockfish pour cet ordinateur. Choisissez un fichier de moteur.",
"Für diesen Computer gibt es keinen Stockfish-Download. Wählen Sie eine Engine-Datei.",
"No hay descarga de Stockfish para este ordenador. Elija un archivo de motor.",
"Non c'è un download di Stockfish per questo computer. Scegli un file del motore.",
],
[
"Or download the official Stockfish 19 build ({mb} MB).",
"Или скачайте официальную сборку Stockfish 19 ({mb} МБ).",
"Ou téléchargez la version officielle de Stockfish 19 ({mb} Mo).",
"Oder laden Sie die offizielle Stockfish-19-Version herunter ({mb} MB).",
"O descargue la versión oficial de Stockfish 19 ({mb} MB).",
"Oppure scarica la versione ufficiale di Stockfish 19 ({mb} MB).",
],
[
"{mb} MB · from the official Stockfish page",
"{mb} МБ · с официальной страницы Stockfish",
"{mb} Mo · depuis la page officielle de Stockfish",
"{mb} MB · von der offiziellen Stockfish-Seite",
"{mb} MB · desde la página oficial de Stockfish",
"{mb} MB · dalla pagina ufficiale di Stockfish",
],
[
"{done} of {total} MB",
"{done} из {total} МБ",
"{done} sur {total} Mo",
"{done} von {total} MB",
"{done} de {total} MB",
"{done} di {total} MB",
],
[
"about {s} s left",
"осталось около {s} с",
"encore environ {s} s",
"noch etwa {s} s",
"quedan unos {s} s",
"ancora circa {s} s",
],
[
"The server didn't provide the file (error {code}). Please try again later.",
"Сервер не отдал файл (ошибка {code}). Попробуйте позже.",
"Le serveur n'a pas fourni le fichier (erreur {code}). Réessayez plus tard.",
"Der Server hat die Datei nicht geliefert (Fehler {code}). Bitte später erneut versuchen.",
"El servidor no entregó el archivo (error {code}). Inténtelo más tarde.",
"Il server non ha fornito il file (errore {code}). Riprova più tardi.",
],
[
"No engine yet",
"Движок ещё не выбран",
"Pas encore de moteur",
"Noch keine Engine",
"Aún no hay motor",
"Nessun motore per ora",
],
[
"An engine evaluates positions and suggests moves. Stockfish is the strongest free one.",
"Движок оценивает позиции и подсказывает ходы. Stockfish — самый сильный из бесплатных.",
"Un moteur évalue les positions et propose des coups. Stockfish est le meilleur gratuit.",
"Eine Engine bewertet Stellungen und schlägt Züge vor. Stockfish ist die stärkste kostenlose.",
"Un motor evalúa posiciones y sugiere jugadas. Stockfish es el más fuerte de los gratuitos.",
"Un motore valuta le posizioni e suggerisce mosse. Stockfish è il più forte tra quelli gratuiti.",
],
[
"⬇ Download Stockfish 19",
"⬇ Скачать Stockfish 19",
"⬇ Télécharger Stockfish 19",
"⬇ Stockfish 19 herunterladen",
"⬇ Descargar Stockfish 19",
"⬇ Scarica Stockfish 19",
],
[
"⬇ Download Stockfish 19 · {mb} MB",
"⬇ Скачать Stockfish 19 · {mb} МБ",
"⬇ Télécharger Stockfish 19 · {mb} Mo",
"⬇ Stockfish 19 herunterladen · {mb} MB",
"⬇ Descargar Stockfish 19 · {mb} MB",
"⬇ Scarica Stockfish 19 · {mb} MB",
],
[
"Remove (and delete the downloaded files)",
"Удалить (вместе со скачанными файлами)",
"Retirer (et supprimer les fichiers téléchargés)",
"Entfernen (mit den heruntergeladenen Dateien)",
"Quitar (y borrar los archivos descargados)",
"Rimuovi (ed elimina i file scaricati)",
],
[
"Included with ChessPenguin",
"Входит в ChessPenguin",
"Inclus avec ChessPenguin",
"In ChessPenguin enthalten",
"Incluido con ChessPenguin",
"Incluso in ChessPenguin",
],
[
"⚠ File not found",
"⚠ Файл не найден",
"⚠ Fichier introuvable",
"⚠ Datei nicht gefunden",
"⚠ Archivo no encontrado",
"⚠ File non trovato",
],
[
"Remove",
"Удалить",
"Supprimer",
"Entfernen",
"Quitar",
"Rimuovi",
],
[
"From the official Stockfish page; installed for your account only",
"С официальной страницы Stockfish; устанавливается только для вас",
"Depuis la page officielle de Stockfish ; installé pour votre compte uniquement",
"Von der offiziellen Stockfish-Seite; nur für Ihr Konto installiert",
"Desde la página oficial de Stockfish; solo para su cuenta",
"Dalla pagina ufficiale di Stockfish; installato solo per il tuo account",
],
[
"{mb} MB from the official Stockfish page; installed for your account only",
"{mb} МБ с официальной страницы Stockfish; устанавливается только для вас",
"{mb} Mo depuis la page officielle de Stockfish ; installé pour votre compte uniquement",
"{mb} MB von der offiziellen Stockfish-Seite; nur für Ihr Konto installiert",
"{mb} MB desde la página oficial de Stockfish; solo para su cuenta",
"{mb} MB dalla pagina ufficiale di Stockfish; installato solo per il tuo account",
],
[
"Downloaded by ChessPenguin · {mb} MB",
"Скачан ChessPenguin · {mb} МБ",
"Téléchargé par ChessPenguin · {mb} Mo",
"Von ChessPenguin heruntergeladen · {mb} MB",
"Descargado por ChessPenguin · {mb} MB",
"Scaricato da ChessPenguin · {mb} MB",
],
[
"Remove Stockfish 19? This frees {mb} MB. You can download it again at any time.",
"Удалить Stockfish 19? Освободится {mb} МБ. Скачать снова можно в любой момент.",
"Supprimer Stockfish 19 ? Cela libère {mb} Mo. Vous pourrez le retélécharger à tout moment.",
"Stockfish 19 entfernen? Das gibt {mb} MB frei. Sie können es jederzeit erneut herunterladen.",
"¿Quitar Stockfish 19? Se liberan {mb} MB. Puede volver a descargarlo cuando quiera.",
"Rimuovere Stockfish 19? Si liberano {mb} MB. Puoi scaricarlo di nuovo in qualsiasi momento.",
],
// --- position search ---
["Year", "Год", "Année", "Jahr", "Año", "Anno"],
[
@ -2269,6 +2662,7 @@ mod tests {
include_str!("library.rs"),
include_str!("large_db.rs"),
include_str!("board_search.rs"),
include_str!("engine_offer.rs"),
include_str!("notation.rs"),
include_str!("review.rs"),
include_str!("engines.rs"),

View file

@ -6,6 +6,8 @@ mod app;
mod assets;
mod board;
mod board_search;
mod engine_download;
mod engine_offer;
mod engines;
mod game_view;
mod i18n;

View file

@ -20,7 +20,8 @@ pub struct EngineConfig {
/// Search time per position in seconds; `None` = infinite.
#[serde(default)]
pub search_secs: Option<u32>,
/// The Stockfish shipped with ChessPenguin; `path` is unused and resolved at start.
/// ChessPenguin's Stockfish (bundled in the Flatpak, otherwise downloaded on
/// request); `path` is unused and resolved at start.
#[serde(default)]
pub builtin: bool,
}
@ -50,10 +51,11 @@ impl EngineConfig {
}
}
/// Executable to start; `None` if the built-in engine is missing (e.g. a source build).
/// Executable to start; `None` if ChessPenguin's Stockfish is neither bundled nor
/// downloaded yet (it is offered for download then).
pub fn executable(&self) -> Option<PathBuf> {
if self.builtin {
crate::engines::bundled_stockfish()
crate::engines::own_stockfish()
} else {
Some(self.path.clone())
}

View file

@ -18,6 +18,11 @@ pub enum Tab {
pub enum SettingsAction {
AddEngine,
/// Download the official Stockfish (decision 14).
DownloadEngine,
CancelDownload,
/// Delete the downloaded Stockfish from the disk (it was removed from the list).
RemoveDownloaded,
TestSound,
/// The active engine (or its options) changed; a running analysis should restart.
EngineChanged,
@ -27,6 +32,10 @@ pub struct SettingsWindow {
pub open: bool,
pub tab: Tab,
pub checking_engine: bool,
/// The running (or last) Stockfish download, set by the application every frame.
pub download: Option<crate::engine_download::Stage>,
/// Engine whose removal (with its downloaded files) waits for confirmation.
confirm_remove: Option<usize>,
}
impl SettingsWindow {
@ -35,6 +44,8 @@ impl SettingsWindow {
open: false,
tab: Tab::default(),
checking_engine: false,
download: None,
confirm_remove: None,
}
}
@ -106,6 +117,43 @@ impl SettingsWindow {
RichText::new(tr("UCI engines. The active one is used for game analysis. Time, lines, threads and memory are set with ⚙ in the analysis panel.")).weak(),
);
ui.add_space(6.0);
let downloading = self.download.as_ref().is_some_and(|d| {
matches!(
d,
crate::engine_download::Stage::Downloading { .. }
| crate::engine_download::Stage::Unpacking
)
});
// No engine yet: the two ways to get one, plainly.
if s.engines.is_empty() {
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.label(RichText::new(tr("No engine yet")).strong());
ui.label(
RichText::new(tr("An engine evaluates positions and suggests moves. Stockfish is the strongest free one."))
.weak(),
);
ui.add_space(4.0);
ui.horizontal(|ui| {
if downloading {
self.download_progress(ui, actions);
} else if crate::engine_download::available()
&& ui
.button(RichText::new(tr("⬇ Download Stockfish 19")).strong())
.on_hover_text(trf(
"{mb} MB from the official Stockfish page; installed for your account only",
&[("mb", &crate::engine_download::size_mb())],
))
.clicked()
{
actions.push(SettingsAction::DownloadEngine);
}
if ui.button(tr("Choose engine file…")).clicked() {
actions.push(SettingsAction::AddEngine);
}
});
});
}
let mut remove = None;
for i in 0..s.engines.len() {
let active = s.active_engine == Some(i);
@ -127,30 +175,101 @@ impl SettingsWindow {
.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);
let downloaded =
s.engines[i].builtin && crate::engines::bundled_stockfish().is_none();
let hint = if downloaded {
tr("Remove (and delete the downloaded files)")
} else {
tr("Remove from list")
};
if ui.button("🗑").on_hover_text(hint).clicked() {
if downloaded && crate::engine_download::installed().is_some() {
self.confirm_remove = Some(i);
} else {
remove = Some(i);
}
}
});
});
let e = &s.engines[i];
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(),
if e.builtin {
if let Some(p) = crate::engines::bundled_stockfish() {
ui.label(
RichText::new(tr("Included with ChessPenguin"))
.small()
.weak(),
)
.on_hover_text(p.display().to_string());
} else if let Some(p) = crate::engine_download::installed() {
let mb = std::fs::metadata(&p).map_or(0, |m| m.len() / 1_000_000);
ui.label(
RichText::new(trf(
"Downloaded by ChessPenguin · {mb} MB",
&[("mb", &mb)],
))
.small()
.weak(),
)
.on_hover_text(p.display().to_string());
} else {
ui.horizontal(|ui| {
ui.label(
RichText::new(tr("⚠ File not found"))
.small()
.color(ui.visuals().warn_fg_color),
);
if downloading {
self.download_progress(ui, actions);
} else if crate::engine_download::available()
&& ui.small_button(tr("Download again")).clicked()
{
actions.push(SettingsAction::DownloadEngine);
}
});
}
} else {
e.path.display().to_string()
};
ui.label(RichText::new(location).small().weak());
ui.label(RichText::new(e.path.display().to_string()).small().weak());
}
});
}
if let Some(i) = self.confirm_remove {
let mut answer = None;
let modal = egui::Modal::new(egui::Id::new("remove_engine")).show(ui.ctx(), |ui| {
ui.set_width(360.0);
let mb = crate::engine_download::installed()
.and_then(|p| std::fs::metadata(p).ok())
.map_or(0, |m| m.len() / 1_000_000);
ui.label(trf(
"Remove Stockfish 19? This frees {mb} MB. You can download it again at any time.",
&[("mb", &mb)],
));
ui.add_space(8.0);
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let cancel = ui.button(tr("Cancel"));
cancel.request_focus();
if cancel.clicked() {
answer = Some(false);
}
if ui.button(tr("Remove")).clicked() {
answer = Some(true);
}
});
});
});
if modal.should_close() {
answer = Some(false);
}
match answer {
Some(true) => {
remove = Some(i);
actions.push(SettingsAction::RemoveDownloaded);
self.confirm_remove = None;
}
Some(false) => self.confirm_remove = None,
None => {}
}
}
if let Some(i) = remove {
s.engines.remove(i);
s.active_engine = match s.active_engine {
@ -181,12 +300,33 @@ impl SettingsWindow {
});
}
}
// ChessPenguin's Stockfish can always be (re)downloaded from here.
let own = crate::engines::own_stockfish().is_some();
if !s.engines.is_empty() && !own && crate::engine_download::available() {
ui.add_space(6.0);
ui.horizontal(|ui| {
if downloading {
self.download_progress(ui, actions);
} else if ui
.button(trf(
"⬇ Download Stockfish 19 · {mb} MB",
&[("mb", &crate::engine_download::size_mb())],
))
.on_hover_text(tr(
"From the official Stockfish page; installed for your account only",
))
.clicked()
{
actions.push(SettingsAction::DownloadEngine);
}
});
}
ui.add_space(6.0);
ui.horizontal(|ui| {
if ui
.add_enabled(
!self.checking_engine,
egui::Button::new(tr("+ Add engine…")),
egui::Button::new(tr("+ Choose engine file…")),
)
.clicked()
{
@ -200,6 +340,38 @@ impl SettingsWindow {
}
}
impl SettingsWindow {
/// The download's progress in place of its button, with a cancel button.
fn download_progress(&self, ui: &mut Ui, actions: &mut Vec<SettingsAction>) {
match &self.download {
Some(crate::engine_download::Stage::Downloading { done, total }) => {
let frac = if *total > 0 {
*done as f32 / *total as f32
} else {
0.0
};
ui.add(egui::ProgressBar::new(frac).desired_width(200.0).text(trf(
"{done} of {total} MB",
&[
("done", &(done / 1_000_000)),
("total", &(total / 1_000_000)),
],
)));
}
_ => {
ui.spinner();
ui.label(tr("Checking and installing…"));
}
}
if crate::widgets::small_close_button(ui)
.on_hover_text(tr("Cancel download"))
.clicked()
{
actions.push(SettingsAction::CancelDownload);
}
}
}
fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) {
ui.label(RichText::new(tr("Piece set")).strong());
ui.horizontal_wrapped(|ui| {