ChessPenguin 0.7.1: updates
The newest release is checked at start; a button next to Settings offers it. The Windows zip, the AppImage and the Linux archive replace themselves (checksum-checked) and restart; macOS opens the disk image; packages are downloaded with the command that installs them. Reviewed by independent tester and designer agents; their findings fixed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b4621bc077
commit
8c3ed18b12
18 changed files with 2263 additions and 12 deletions
3
.github/workflows/ci.yml
vendored
3
.github/workflows/ci.yml
vendored
|
|
@ -30,6 +30,8 @@ jobs:
|
|||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo build --locked -p chesspenguin
|
||||
# Self-update: replacing the running executable (the Windows rename scheme).
|
||||
- run: cargo test --locked -p chesspenguin update::
|
||||
|
||||
# Apple Silicon: the build and the app bundle (decision 15).
|
||||
macos-build:
|
||||
|
|
@ -40,3 +42,4 @@ jobs:
|
|||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo build --release --locked -p chesspenguin
|
||||
- run: VERSION=0.0.0 packaging/macos/build-app.sh dist
|
||||
- run: cargo test --locked -p chesspenguin update::
|
||||
|
|
|
|||
11
CHANGELOG.md
11
CHANGELOG.md
|
|
@ -2,6 +2,17 @@
|
|||
|
||||
All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [0.7.1] — 2026-10-20
|
||||
|
||||
- Updates: at start ChessPenguin asks GitHub for the latest version (can be turned off in
|
||||
Settings → About) and offers a newer one with a button next to Settings. The Windows zip,
|
||||
the AppImage and the Linux archive update themselves (download, checksum check, replace,
|
||||
restart); macOS downloads and opens the disk image with step-by-step instructions; deb, rpm,
|
||||
Arch and Flatpak packages are downloaded into Downloads and the one command that installs
|
||||
them is shown with a Copy button; the AUR package shows the helper command. "Skip this
|
||||
version" hides the button until the next one.
|
||||
- The Flatpak may use the network (the update check).
|
||||
|
||||
## [0.7.0] — 2026-10-20
|
||||
|
||||
- «Справочник» (Reference) tab of a game: what was played in the current position in a
|
||||
|
|
|
|||
8
Cargo.lock
generated
8
Cargo.lock
generated
|
|
@ -661,7 +661,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chess-core"
|
||||
version = "0.7.0"
|
||||
version = "0.7.1"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"pgn-reader",
|
||||
|
|
@ -671,7 +671,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chess-import"
|
||||
version = "0.7.0"
|
||||
version = "0.7.1"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"encoding_rs",
|
||||
|
|
@ -684,7 +684,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chesspenguin"
|
||||
version = "0.7.0"
|
||||
version = "0.7.1"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"chess-core",
|
||||
|
|
@ -4284,7 +4284,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
|||
|
||||
[[package]]
|
||||
name = "uci"
|
||||
version = "0.7.0"
|
||||
version = "0.7.1"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ resolver = "3"
|
|||
members = ["crates/chess-core", "crates/chess-import", "crates/uci", "apps/desktop"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.0"
|
||||
version = "0.7.1"
|
||||
edition = "2024"
|
||||
rust-version = "1.97"
|
||||
license = "GPL-3.0-or-later"
|
||||
|
|
|
|||
|
|
@ -59,6 +59,12 @@ pub struct App {
|
|||
previous_games: Vec<GameView>,
|
||||
/// The last game showed the reference tab: the next one opens with it too.
|
||||
reference_tab: bool,
|
||||
/// Updates: the release check, how this copy is installed, the window, and the
|
||||
/// executable to start after quitting (a restart into the new version).
|
||||
update_check: crate::update::Check,
|
||||
update_kind: crate::update::Install,
|
||||
update_ui: crate::update_ui::UpdateDialog,
|
||||
restart_to: Option<PathBuf>,
|
||||
/// The reference tab of games (kept across games: its results stay cached).
|
||||
reference: crate::reference::Reference,
|
||||
allow_quit: bool,
|
||||
|
|
@ -107,6 +113,18 @@ impl App {
|
|||
// Before the samples, which are named in this language.
|
||||
crate::i18n::set_lang(settings.language);
|
||||
crate::engine_download::clean_leftovers();
|
||||
crate::update::clean_leftovers();
|
||||
let settings_check_updates = settings.check_updates;
|
||||
// "Updated to …" once, when this version runs for the first time after another.
|
||||
let current = env!("CARGO_PKG_VERSION");
|
||||
let updated_from = settings
|
||||
.last_version
|
||||
.clone()
|
||||
.filter(|v| crate::update::parse_version(v) < crate::update::parse_version(current));
|
||||
if settings.last_version.as_deref() != Some(current) {
|
||||
settings.last_version = Some(current.to_owned());
|
||||
let _ = settings.save();
|
||||
}
|
||||
let engines_found = crate::engines::first_run_setup(&mut settings);
|
||||
if crate::examples::first_run_setup(&mut settings) || engines_found {
|
||||
let _ = settings.save();
|
||||
|
|
@ -129,7 +147,7 @@ impl App {
|
|||
if let Some(first) = settings.databases.first().filter(|p| p.exists()) {
|
||||
library.select_db(first, ctx);
|
||||
}
|
||||
Self {
|
||||
let mut app = Self {
|
||||
settings,
|
||||
settings_dirty: false,
|
||||
sound: SoundPlayer::new(),
|
||||
|
|
@ -146,6 +164,14 @@ impl App {
|
|||
find_after_close: None,
|
||||
previous_games: Vec::new(),
|
||||
reference_tab: false,
|
||||
update_check: if settings_check_updates {
|
||||
crate::update::Check::start(ctx)
|
||||
} else {
|
||||
crate::update::Check::idle()
|
||||
},
|
||||
update_kind: crate::update::detect(),
|
||||
update_ui: crate::update_ui::UpdateDialog::from_env(),
|
||||
restart_to: None,
|
||||
reference: Default::default(),
|
||||
engine_offer: crate::engine_offer::EngineOffer::new(),
|
||||
offer_hook_done: false,
|
||||
|
|
@ -153,7 +179,15 @@ impl App {
|
|||
applied_dark: None,
|
||||
debug: DebugStartup::from_env(),
|
||||
}
|
||||
.with_debug_settings()
|
||||
.with_debug_settings();
|
||||
if let Some(from) = updated_from {
|
||||
let msg = trf(
|
||||
"ChessPenguin is updated: {from} → {to}",
|
||||
&[("from", &from), ("to", ¤t)],
|
||||
);
|
||||
app.toast(ctx, msg);
|
||||
}
|
||||
app
|
||||
}
|
||||
|
||||
fn with_debug_settings(mut self) -> Self {
|
||||
|
|
@ -341,7 +375,10 @@ impl App {
|
|||
self.settings_dirty = true;
|
||||
}
|
||||
Async::SavePicked(path) => self.save_game(ctx, path),
|
||||
Async::SaveCancelled => self.close_after_save = None,
|
||||
Async::SaveCancelled => {
|
||||
self.close_after_save = None;
|
||||
self.restart_to = None;
|
||||
}
|
||||
Async::EngineChecked(res) => {
|
||||
self.settings_ui.checking_engine = false;
|
||||
match res {
|
||||
|
|
@ -480,6 +517,19 @@ impl App {
|
|||
}
|
||||
|
||||
if intent == CloseIntent::QuitApp {
|
||||
// A restart into the new version: start it as this one goes.
|
||||
if let Some(exe) = self.restart_to.take() {
|
||||
// The settings first (the new process reads them), and none of the dev
|
||||
// hooks of this one (they would start the update again).
|
||||
let _ = self.settings.save();
|
||||
let mut cmd = std::process::Command::new(exe);
|
||||
for (k, _) in std::env::vars_os() {
|
||||
if k.to_string_lossy().starts_with("CP_") {
|
||||
cmd.env_remove(k);
|
||||
}
|
||||
}
|
||||
let _ = cmd.spawn();
|
||||
}
|
||||
self.allow_quit = true;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
|
|
@ -661,6 +711,8 @@ impl App {
|
|||
Some(2) => {
|
||||
self.confirm_close = None;
|
||||
self.find_after_close = None;
|
||||
// A restart asked for waits for no later quit.
|
||||
self.restart_to = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
|
@ -777,6 +829,7 @@ impl eframe::App for App {
|
|||
}
|
||||
}
|
||||
}
|
||||
GameAction::OpenUpdate => self.update_ui.open = true,
|
||||
GameAction::ReturnToPrevious => {
|
||||
if !self.previous_games.is_empty() {
|
||||
self.request_close(&ctx, CloseIntent::ReturnToPrevious);
|
||||
|
|
@ -847,6 +900,7 @@ impl eframe::App for App {
|
|||
}
|
||||
LibraryAction::PastePgn => self.paste_pgn(&ctx),
|
||||
LibraryAction::AddDatabases => self.pick_databases(&ctx),
|
||||
LibraryAction::OpenUpdate => self.update_ui.open = true,
|
||||
LibraryAction::RemoveDatabase(p) => {
|
||||
self.settings.databases.retain(|d| *d != p);
|
||||
self.library.forget(&p);
|
||||
|
|
@ -857,12 +911,63 @@ impl eframe::App for App {
|
|||
}
|
||||
}
|
||||
|
||||
// Updates: the badge next to Settings, the window, the status in Settings → About.
|
||||
self.update_check.poll();
|
||||
let skipped = self.settings.skipped_version.clone();
|
||||
let badge = self
|
||||
.update_check
|
||||
.newer()
|
||||
.filter(|r| self.update_ui.active() || skipped.as_deref() != Some(r.version.as_str()))
|
||||
.map(|r| self.update_ui.badge(r));
|
||||
self.library.update = badge.clone();
|
||||
if let Some(g) = &mut self.game {
|
||||
g.update = badge;
|
||||
}
|
||||
for e in self
|
||||
.update_ui
|
||||
.show(&ctx, self.update_check.newer(), &self.update_kind)
|
||||
{
|
||||
match e {
|
||||
crate::update_ui::UpdateEvent::Restart(exe) => {
|
||||
self.restart_to = Some(exe);
|
||||
self.request_close(&ctx, CloseIntent::QuitApp);
|
||||
}
|
||||
crate::update_ui::UpdateEvent::CopyText(t) => {
|
||||
ctx.copy_text(t);
|
||||
self.toast(&ctx, tr("Copied"));
|
||||
}
|
||||
crate::update_ui::UpdateEvent::Quit => {
|
||||
self.request_close(&ctx, CloseIntent::QuitApp);
|
||||
}
|
||||
crate::update_ui::UpdateEvent::Skip(v) => {
|
||||
self.settings.skipped_version = Some(v);
|
||||
self.settings_dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.settings_ui.update_available = self.update_check.newer().map(|r| r.version.clone());
|
||||
self.settings_ui.update_status = if self.update_check.running() {
|
||||
Some(tr("Checking…").to_owned())
|
||||
} else if let Some(r) = self.update_check.newer() {
|
||||
Some(trf("Version {v} is out", &[("v", &r.version)]))
|
||||
} else if self.update_check.release.is_some() {
|
||||
Some(tr("This is the latest version").to_owned())
|
||||
} else if self.update_check.error.is_some() {
|
||||
Some(tr("Could not check for updates").to_owned())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
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::CheckUpdates => {
|
||||
self.update_check = self.update_check.again(&ctx);
|
||||
}
|
||||
SettingsAction::OpenUpdate => self.update_ui.open = true,
|
||||
SettingsAction::DownloadEngine => self.engine_offer.start(&ctx),
|
||||
SettingsAction::CancelDownload => self.engine_offer.cancel(),
|
||||
SettingsAction::RemoveDownloaded => {
|
||||
|
|
|
|||
|
|
@ -890,6 +890,11 @@ impl<T: Send + 'static> Background<T> {
|
|||
pub fn progress(&self) -> usize {
|
||||
self.progress.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Asks the work to stop; its result still arrives.
|
||||
pub fn cancel(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Background<T> {
|
||||
|
|
|
|||
|
|
@ -59,6 +59,8 @@ pub struct GameView {
|
|||
side_tab: SideTab,
|
||||
/// The game this one was opened from (reference tab): the title for "← back to".
|
||||
pub previous: Option<String>,
|
||||
/// A newer version to offer (its number), next to Settings.
|
||||
pub update: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
|
|
@ -96,6 +98,8 @@ pub enum GameAction {
|
|||
OpenGame(std::path::PathBuf, usize, Chess),
|
||||
/// Back to the game this one was opened from.
|
||||
ReturnToPrevious,
|
||||
/// The window offering a newer version.
|
||||
OpenUpdate,
|
||||
}
|
||||
|
||||
impl GameView {
|
||||
|
|
@ -121,6 +125,7 @@ impl GameView {
|
|||
SideTab::Notation
|
||||
},
|
||||
previous: None,
|
||||
update: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -457,11 +462,16 @@ impl GameView {
|
|||
{
|
||||
actions.push(GameAction::OpenSettings);
|
||||
}
|
||||
if let Some(v) = &self.update
|
||||
&& crate::widgets::update_button(ui, v).clicked()
|
||||
{
|
||||
actions.push(GameAction::OpenUpdate);
|
||||
}
|
||||
// Find the position in a database: the last chosen one, or another.
|
||||
let searchable = self.search_line().is_some();
|
||||
let why = tr("After a null move (--) this is a teaching scheme, not a position of a game: it is not searched");
|
||||
ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| {
|
||||
ui.menu_button("▾", |ui| {
|
||||
ui.menu_button("⏷", |ui| {
|
||||
for db in databases {
|
||||
let name = db
|
||||
.file_stem()
|
||||
|
|
|
|||
|
|
@ -2079,6 +2079,662 @@ const ROWS: &[[&str; 6]] = &[
|
|||
"Partidas de la base solo con los jugadores y el resultado, sin jugadas",
|
||||
"Partite della base con solo giocatori e risultato, senza mosse",
|
||||
],
|
||||
[
|
||||
"Checking…",
|
||||
"Проверяю…",
|
||||
"Vérification…",
|
||||
"Wird geprüft…",
|
||||
"Comprobando…",
|
||||
"Controllo…",
|
||||
],
|
||||
[
|
||||
"This is the latest version",
|
||||
"Это последняя версия",
|
||||
"C'est la dernière version",
|
||||
"Das ist die neueste Version",
|
||||
"Es la última versión",
|
||||
"È l'ultima versione",
|
||||
],
|
||||
[
|
||||
"Could not check (no connection?)",
|
||||
"Не удалось проверить (нет связи?)",
|
||||
"Vérification impossible (pas de connexion ?)",
|
||||
"Prüfung nicht möglich (keine Verbindung?)",
|
||||
"No se pudo comprobar (¿sin conexión?)",
|
||||
"Impossibile controllare (nessuna connessione?)",
|
||||
],
|
||||
[
|
||||
"Version {v} is out",
|
||||
"Вышла версия {v}",
|
||||
"La version {v} est sortie",
|
||||
"Version {v} ist erschienen",
|
||||
"Ha salido la versión {v}",
|
||||
"È uscita la versione {v}",
|
||||
],
|
||||
[
|
||||
"Check for a new version at start",
|
||||
"Проверять новую версию при запуске",
|
||||
"Rechercher une nouvelle version au démarrage",
|
||||
"Beim Start nach einer neuen Version suchen",
|
||||
"Buscar una versión nueva al iniciar",
|
||||
"Cerca una nuova versione all'avvio",
|
||||
],
|
||||
[
|
||||
"ChessPenguin asks GitHub which version is the latest; nothing about you is sent",
|
||||
"ChessPenguin спрашивает у GitHub, какая версия последняя; ничего о вас не отправляется",
|
||||
"ChessPenguin demande à GitHub quelle est la dernière version ; rien sur vous n'est envoyé",
|
||||
"ChessPenguin fragt GitHub nach der neuesten Version; nichts über Sie wird gesendet",
|
||||
"ChessPenguin pregunta a GitHub cuál es la última versión; no se envía nada sobre ti",
|
||||
"ChessPenguin chiede a GitHub qual è l'ultima versione; nulla su di te viene inviato",
|
||||
],
|
||||
[
|
||||
"Check now",
|
||||
"Проверить сейчас",
|
||||
"Vérifier maintenant",
|
||||
"Jetzt prüfen",
|
||||
"Comprobar ahora",
|
||||
"Controlla ora",
|
||||
],
|
||||
[
|
||||
"A new version of ChessPenguin is out",
|
||||
"Вышла новая версия ChessPenguin",
|
||||
"Une nouvelle version de ChessPenguin est sortie",
|
||||
"Eine neue Version von ChessPenguin ist erschienen",
|
||||
"Ha salido una nueva versión de ChessPenguin",
|
||||
"È uscita una nuova versione di ChessPenguin",
|
||||
],
|
||||
[
|
||||
"⬆ Update {v}",
|
||||
"⬆ Обновить до {v}",
|
||||
"⬆ Mettre à jour vers {v}",
|
||||
"⬆ Auf {v} aktualisieren",
|
||||
"⬆ Actualizar a {v}",
|
||||
"⬆ Aggiorna a {v}",
|
||||
],
|
||||
[
|
||||
"the deb package",
|
||||
"пакет deb",
|
||||
"le paquet deb",
|
||||
"das deb-Paket",
|
||||
"el paquete deb",
|
||||
"il pacchetto deb",
|
||||
],
|
||||
[
|
||||
"the rpm package",
|
||||
"пакет rpm",
|
||||
"le paquet rpm",
|
||||
"das rpm-Paket",
|
||||
"el paquete rpm",
|
||||
"il pacchetto rpm",
|
||||
],
|
||||
[
|
||||
"the Arch Linux package",
|
||||
"пакет Arch Linux",
|
||||
"le paquet Arch Linux",
|
||||
"das Arch-Linux-Paket",
|
||||
"el paquete de Arch Linux",
|
||||
"il pacchetto Arch Linux",
|
||||
],
|
||||
[
|
||||
"The new version is installed.",
|
||||
"Новая версия установлена.",
|
||||
"La nouvelle version est installée.",
|
||||
"Die neue Version ist installiert.",
|
||||
"La nueva versión está instalada.",
|
||||
"La nuova versione è installata.",
|
||||
],
|
||||
[
|
||||
"It starts after a restart; unsaved games are asked about first.",
|
||||
"Она запустится после перезапуска; про несохранённые партии программа сначала спросит.",
|
||||
"Elle démarre après un redémarrage ; les parties non enregistrées sont d'abord proposées à l'enregistrement.",
|
||||
"Sie startet nach einem Neustart; nach ungespeicherten Partien wird vorher gefragt.",
|
||||
"Se inicia tras reiniciar; antes se pregunta por las partidas sin guardar.",
|
||||
"Parte dopo il riavvio; prima viene chiesto delle partite non salvate.",
|
||||
],
|
||||
[
|
||||
"Restart now",
|
||||
"Перезапустить сейчас",
|
||||
"Redémarrer maintenant",
|
||||
"Jetzt neu starten",
|
||||
"Reiniciar ahora",
|
||||
"Riavvia ora",
|
||||
],
|
||||
[
|
||||
"The disk image is open.",
|
||||
"Образ диска открыт.",
|
||||
"L'image disque est ouverte.",
|
||||
"Das Disk-Image ist geöffnet.",
|
||||
"La imagen de disco está abierta.",
|
||||
"L'immagine disco è aperta.",
|
||||
],
|
||||
[
|
||||
"Drag ChessPenguin onto Applications in its window and choose Replace. Then quit this window of ChessPenguin and start it again.",
|
||||
"В его окне перетащите ChessPenguin в «Программы» и выберите «Заменить». Затем закройте ChessPenguin и запустите снова.",
|
||||
"Dans sa fenêtre, faites glisser ChessPenguin sur Applications et choisissez Remplacer. Puis quittez ChessPenguin et relancez-le.",
|
||||
"Ziehen Sie ChessPenguin in seinem Fenster auf Programme und wählen Sie Ersetzen. Beenden Sie dann ChessPenguin und starten Sie es neu.",
|
||||
"En su ventana, arrastra ChessPenguin a Aplicaciones y elige Reemplazar. Luego cierra ChessPenguin y ábrelo de nuevo.",
|
||||
"Nella sua finestra trascina ChessPenguin su Applicazioni e scegli Sostituisci. Poi chiudi ChessPenguin e riavvialo.",
|
||||
],
|
||||
[
|
||||
"The package is downloaded and checked.",
|
||||
"Пакет скачан и проверен.",
|
||||
"Le paquet est téléchargé et vérifié.",
|
||||
"Das Paket ist heruntergeladen und geprüft.",
|
||||
"El paquete está descargado y comprobado.",
|
||||
"Il pacchetto è scaricato e verificato.",
|
||||
],
|
||||
[
|
||||
"To install it, run this command in a terminal (it may ask for your password):",
|
||||
"Чтобы установить его, выполните в терминале команду (может спросить пароль):",
|
||||
"Pour l'installer, lancez cette commande dans un terminal (le mot de passe peut être demandé) :",
|
||||
"Zum Installieren diesen Befehl im Terminal ausführen (eventuell wird das Passwort abgefragt):",
|
||||
"Para instalarlo, ejecuta este comando en una terminal (puede pedir tu contraseña):",
|
||||
"Per installarlo, esegui questo comando in un terminale (potrebbe chiedere la password):",
|
||||
],
|
||||
[
|
||||
"Run it in the terminal of your system, not inside the Flatpak.",
|
||||
"Выполните её в обычном терминале системы, не внутри Flatpak.",
|
||||
"Lancez-la dans le terminal du système, pas à l'intérieur du Flatpak.",
|
||||
"Führen Sie ihn im Terminal des Systems aus, nicht im Flatpak.",
|
||||
"Ejecútalo en la terminal del sistema, no dentro del Flatpak.",
|
||||
"Eseguilo nel terminale del sistema, non dentro il Flatpak.",
|
||||
],
|
||||
[
|
||||
"Then close ChessPenguin and start it again.",
|
||||
"Затем закройте ChessPenguin и запустите снова.",
|
||||
"Puis fermez ChessPenguin et relancez-le.",
|
||||
"Schließen Sie dann ChessPenguin und starten Sie es neu.",
|
||||
"Luego cierra ChessPenguin y ábrelo de nuevo.",
|
||||
"Poi chiudi ChessPenguin e riavvialo.",
|
||||
],
|
||||
[
|
||||
"The downloaded file is damaged (its checksum does not match). Try again.",
|
||||
"Скачанный файл повреждён (контрольная сумма не совпала). Попробуйте ещё раз.",
|
||||
"Le fichier téléchargé est endommagé (la somme de contrôle ne correspond pas). Réessayez.",
|
||||
"Die heruntergeladene Datei ist beschädigt (Prüfsumme passt nicht). Versuchen Sie es erneut.",
|
||||
"El archivo descargado está dañado (la suma de comprobación no coincide). Inténtalo de nuevo.",
|
||||
"Il file scaricato è danneggiato (il checksum non corrisponde). Riprova.",
|
||||
],
|
||||
[
|
||||
"Cancelled.",
|
||||
"Отменено.",
|
||||
"Annulé.",
|
||||
"Abgebrochen.",
|
||||
"Cancelado.",
|
||||
"Annullato.",
|
||||
],
|
||||
[
|
||||
"ChessPenguin is installed from the AUR. Update it with your AUR helper:",
|
||||
"ChessPenguin установлен из AUR. Обновите его через AUR-помощник:",
|
||||
"ChessPenguin est installé depuis l'AUR. Mettez-le à jour avec votre assistant AUR :",
|
||||
"ChessPenguin ist aus dem AUR installiert. Aktualisieren Sie es mit Ihrem AUR-Helfer:",
|
||||
"ChessPenguin está instalado desde AUR. Actualízalo con tu asistente de AUR:",
|
||||
"ChessPenguin è installato da AUR. Aggiornalo con il tuo helper AUR:",
|
||||
],
|
||||
[
|
||||
"⬆ Update",
|
||||
"⬆ Обновить",
|
||||
"⬆ Mettre à jour",
|
||||
"⬆ Aktualisieren",
|
||||
"⬆ Actualizar",
|
||||
"⬆ Aggiorna",
|
||||
],
|
||||
[
|
||||
"⬇ Download",
|
||||
"⬇ Скачать",
|
||||
"⬇ Télécharger",
|
||||
"⬇ Herunterladen",
|
||||
"⬇ Descargar",
|
||||
"⬇ Scarica",
|
||||
],
|
||||
[
|
||||
"⬇ Download the package",
|
||||
"⬇ Скачать пакет",
|
||||
"⬇ Télécharger le paquet",
|
||||
"⬇ Paket herunterladen",
|
||||
"⬇ Descargar el paquete",
|
||||
"⬇ Scarica il pacchetto",
|
||||
],
|
||||
[
|
||||
"Download the new version from the website:",
|
||||
"Скачайте новую версию на сайте:",
|
||||
"Téléchargez la nouvelle version sur le site :",
|
||||
"Laden Sie die neue Version von der Website:",
|
||||
"Descarga la nueva versión en el sitio web:",
|
||||
"Scarica la nuova versione dal sito:",
|
||||
],
|
||||
[
|
||||
"Copy",
|
||||
"Копировать",
|
||||
"Copier",
|
||||
"Kopieren",
|
||||
"Copiar",
|
||||
"Copia",
|
||||
],
|
||||
[
|
||||
"ChessPenguin {v}",
|
||||
"ChessPenguin {v}",
|
||||
"ChessPenguin {v}",
|
||||
"ChessPenguin {v}",
|
||||
"ChessPenguin {v}",
|
||||
"ChessPenguin {v}",
|
||||
],
|
||||
[
|
||||
"A new version is out: {new} (you have {old}).",
|
||||
"Вышла новая версия: {new} (у вас {old}).",
|
||||
"Une nouvelle version est sortie : {new} (vous avez {old}).",
|
||||
"Eine neue Version ist erschienen: {new} (Sie haben {old}).",
|
||||
"Ha salido una nueva versión: {new} (tienes la {old}).",
|
||||
"È uscita una nuova versione: {new} (hai la {old}).",
|
||||
],
|
||||
[
|
||||
"Downloading… {done} of {total} MB",
|
||||
"Скачиваю… {done} из {total} МБ",
|
||||
"Téléchargement… {done} sur {total} Mo",
|
||||
"Wird heruntergeladen… {done} von {total} MB",
|
||||
"Descargando… {done} de {total} MB",
|
||||
"Scaricamento… {done} di {total} MB",
|
||||
],
|
||||
[
|
||||
"It is in {path}.",
|
||||
"Он лежит здесь: {path}.",
|
||||
"Il se trouve ici : {path}.",
|
||||
"Es liegt hier: {path}.",
|
||||
"Está aquí: {path}.",
|
||||
"Si trova qui: {path}.",
|
||||
],
|
||||
[
|
||||
"The update failed: {e}",
|
||||
"Обновить не удалось: {e}",
|
||||
"La mise à jour a échoué : {e}",
|
||||
"Die Aktualisierung ist fehlgeschlagen: {e}",
|
||||
"La actualización falló: {e}",
|
||||
"L'aggiornamento non è riuscito: {e}",
|
||||
],
|
||||
[
|
||||
"ChessPenguin ({kind}) updates itself: the new version is downloaded ({mb} MB), checked and put in place of this one.",
|
||||
"ChessPenguin ({kind}) обновляется сам: новая версия скачивается ({mb} МБ), проверяется и встаёт на место этой.",
|
||||
"ChessPenguin ({kind}) se met à jour tout seul : la nouvelle version est téléchargée ({mb} Mo), vérifiée et mise à la place de celle-ci.",
|
||||
"ChessPenguin ({kind}) aktualisiert sich selbst: die neue Version wird heruntergeladen ({mb} MB), geprüft und ersetzt diese.",
|
||||
"ChessPenguin ({kind}) se actualiza solo: la nueva versión se descarga ({mb} MB), se comprueba y sustituye a esta.",
|
||||
"ChessPenguin ({kind}) si aggiorna da solo: la nuova versione viene scaricata ({mb} MB), verificata e messa al posto di questa.",
|
||||
],
|
||||
[
|
||||
"The disk image ({mb} MB) is downloaded, checked and opened; you drag the app over the old one, as when you installed it.",
|
||||
"Образ диска ({mb} МБ) скачивается, проверяется и открывается; вы перетаскиваете программу поверх старой, как при установке.",
|
||||
"L'image disque ({mb} Mo) est téléchargée, vérifiée et ouverte ; vous glissez l'app sur l'ancienne, comme à l'installation.",
|
||||
"Das Disk-Image ({mb} MB) wird heruntergeladen, geprüft und geöffnet; Sie ziehen die App über die alte, wie bei der Installation.",
|
||||
"La imagen de disco ({mb} MB) se descarga, se comprueba y se abre; arrastras la app sobre la antigua, como al instalarla.",
|
||||
"L'immagine disco ({mb} MB) viene scaricata, verificata e aperta; trascini l'app sopra la vecchia, come all'installazione.",
|
||||
],
|
||||
[
|
||||
"ChessPenguin is installed as {kind}: the system installs it. The new package ({mb} MB) is downloaded into Downloads and checked; then you run one command.",
|
||||
"ChessPenguin установлен как {kind}: его ставит система. Новый пакет ({mb} МБ) скачивается в «Загрузки» и проверяется, затем вы выполняете одну команду.",
|
||||
"ChessPenguin est installé comme {kind} : c'est le système qui l'installe. Le nouveau paquet ({mb} Mo) est téléchargé dans Téléchargements et vérifié ; puis vous lancez une commande.",
|
||||
"ChessPenguin ist als {kind} installiert: das System installiert es. Das neue Paket ({mb} MB) wird nach Downloads geladen und geprüft; dann führen Sie einen Befehl aus.",
|
||||
"ChessPenguin está instalado como {kind}: lo instala el sistema. El nuevo paquete ({mb} MB) se descarga en Descargas y se comprueba; luego ejecutas un comando.",
|
||||
"ChessPenguin è installato come {kind}: lo installa il sistema. Il nuovo pacchetto ({mb} MB) viene scaricato in Download e verificato; poi esegui un comando.",
|
||||
],
|
||||
[
|
||||
"Could not check for updates",
|
||||
"Не удалось проверить обновления",
|
||||
"Impossible de rechercher les mises à jour",
|
||||
"Suche nach Updates nicht möglich",
|
||||
"No se pudieron buscar actualizaciones",
|
||||
"Impossibile cercare aggiornamenti",
|
||||
],
|
||||
[
|
||||
"ChessPenguin is updated: {from} → {to}",
|
||||
"ChessPenguin обновлён: {from} → {to}",
|
||||
"ChessPenguin est mis à jour : {from} → {to}",
|
||||
"ChessPenguin wurde aktualisiert: {from} → {to}",
|
||||
"ChessPenguin se ha actualizado: {from} → {to}",
|
||||
"ChessPenguin è aggiornato: {from} → {to}",
|
||||
],
|
||||
[
|
||||
"Check for updates at start",
|
||||
"Проверять обновления при запуске",
|
||||
"Rechercher les mises à jour au démarrage",
|
||||
"Beim Start nach Updates suchen",
|
||||
"Buscar actualizaciones al iniciar",
|
||||
"Cerca aggiornamenti all'avvio",
|
||||
],
|
||||
[
|
||||
"⬆ Update to {v}…",
|
||||
"⬆ Обновить до {v}…",
|
||||
"⬆ Mettre à jour vers {v}…",
|
||||
"⬆ Auf {v} aktualisieren…",
|
||||
"⬆ Actualizar a {v}…",
|
||||
"⬆ Aggiorna a {v}…",
|
||||
],
|
||||
[
|
||||
"less than 1",
|
||||
"меньше 1",
|
||||
"moins de 1",
|
||||
"unter 1",
|
||||
"menos de 1",
|
||||
"meno di 1",
|
||||
],
|
||||
[
|
||||
"deb package",
|
||||
"пакет deb",
|
||||
"paquet deb",
|
||||
"deb-Paket",
|
||||
"paquete deb",
|
||||
"pacchetto deb",
|
||||
],
|
||||
[
|
||||
"rpm package",
|
||||
"пакет rpm",
|
||||
"paquet rpm",
|
||||
"rpm-Paket",
|
||||
"paquete rpm",
|
||||
"pacchetto rpm",
|
||||
],
|
||||
[
|
||||
"Arch Linux package",
|
||||
"пакет Arch Linux",
|
||||
"paquet Arch Linux",
|
||||
"Arch-Linux-Paket",
|
||||
"paquete de Arch Linux",
|
||||
"pacchetto Arch Linux",
|
||||
],
|
||||
[
|
||||
"archive (tar.gz)",
|
||||
"архив (tar.gz)",
|
||||
"archive (tar.gz)",
|
||||
"Archiv (tar.gz)",
|
||||
"archivo (tar.gz)",
|
||||
"archivio (tar.gz)",
|
||||
],
|
||||
[
|
||||
"The file got damaged while downloading, so it was not installed. Try again.",
|
||||
"Файл повредился при скачивании, поэтому не установлен. Попробуйте ещё раз.",
|
||||
"Le fichier a été endommagé pendant le téléchargement ; il n'a pas été installé. Réessayez.",
|
||||
"Die Datei wurde beim Herunterladen beschädigt und deshalb nicht installiert. Versuchen Sie es erneut.",
|
||||
"El archivo se dañó al descargarse, así que no se instaló. Inténtalo de nuevo.",
|
||||
"Il file si è danneggiato durante lo scaricamento, quindi non è stato installato. Riprova.",
|
||||
],
|
||||
[
|
||||
"The download was cancelled.",
|
||||
"Скачивание отменено.",
|
||||
"Le téléchargement a été annulé.",
|
||||
"Der Download wurde abgebrochen.",
|
||||
"La descarga se canceló.",
|
||||
"Lo scaricamento è stato annullato.",
|
||||
],
|
||||
[
|
||||
"This release has no file for your system yet. Download the new version from the website.",
|
||||
"В этом выпуске пока нет файла для вашей системы. Скачайте новую версию на сайте.",
|
||||
"Cette version n'a pas encore de fichier pour votre système. Téléchargez-la sur le site.",
|
||||
"Diese Version hat noch keine Datei für Ihr System. Laden Sie sie von der Website.",
|
||||
"Esta versión aún no tiene archivo para tu sistema. Descárgala en el sitio web.",
|
||||
"Questa versione non ha ancora un file per il tuo sistema. Scaricala dal sito.",
|
||||
],
|
||||
[
|
||||
"The file could not be saved: no permission to write there, or the disk is full.",
|
||||
"Не удалось сохранить файл: нет прав на запись в эту папку или диск заполнен.",
|
||||
"Impossible d'enregistrer le fichier : pas le droit d'écrire ici, ou le disque est plein.",
|
||||
"Die Datei konnte nicht gespeichert werden: keine Schreibrechte oder die Festplatte ist voll.",
|
||||
"No se pudo guardar el archivo: sin permiso de escritura o el disco está lleno.",
|
||||
"Impossibile salvare il file: nessun permesso di scrittura o disco pieno.",
|
||||
],
|
||||
[
|
||||
"The new version could not be downloaded: no connection to the server. Check the internet and try again.",
|
||||
"Не удалось скачать новую версию: нет связи с сервером. Проверьте интернет и попробуйте ещё раз.",
|
||||
"Impossible de télécharger la nouvelle version : pas de connexion au serveur. Vérifiez Internet et réessayez.",
|
||||
"Die neue Version konnte nicht geladen werden: keine Verbindung zum Server. Prüfen Sie das Internet und versuchen Sie es erneut.",
|
||||
"No se pudo descargar la nueva versión: sin conexión con el servidor. Comprueba internet e inténtalo de nuevo.",
|
||||
"Impossibile scaricare la nuova versione: nessuna connessione al server. Controlla internet e riprova.",
|
||||
],
|
||||
[
|
||||
"ChessPenguin update",
|
||||
"Обновление ChessPenguin",
|
||||
"Mise à jour de ChessPenguin",
|
||||
"ChessPenguin-Update",
|
||||
"Actualización de ChessPenguin",
|
||||
"Aggiornamento di ChessPenguin",
|
||||
],
|
||||
[
|
||||
"You can close this window: the download goes on.",
|
||||
"Окно можно закрыть: скачивание продолжится.",
|
||||
"Vous pouvez fermer cette fenêtre : le téléchargement continue.",
|
||||
"Sie können dieses Fenster schließen: der Download läuft weiter.",
|
||||
"Puedes cerrar esta ventana: la descarga continúa.",
|
||||
"Puoi chiudere questa finestra: lo scaricamento continua.",
|
||||
],
|
||||
[
|
||||
"It starts after a restart. Unsaved games are asked about first; databases and settings stay as they are.",
|
||||
"Она запустится после перезапуска. Про несохранённые партии программа сначала спросит; базы и настройки останутся как есть.",
|
||||
"Elle démarre après un redémarrage. Les parties non enregistrées sont d'abord proposées à l'enregistrement ; bases et réglages restent tels quels.",
|
||||
"Sie startet nach einem Neustart. Nach ungespeicherten Partien wird zuerst gefragt; Datenbanken und Einstellungen bleiben erhalten.",
|
||||
"Se inicia tras reiniciar. Antes se pregunta por las partidas sin guardar; las bases y los ajustes se conservan.",
|
||||
"Parte dopo il riavvio. Prima viene chiesto delle partite non salvate; basi e impostazioni restano come sono.",
|
||||
],
|
||||
[
|
||||
"⟳ Restart now",
|
||||
"⟳ Перезапустить сейчас",
|
||||
"⟳ Redémarrer maintenant",
|
||||
"⟳ Jetzt neu starten",
|
||||
"⟳ Reiniciar ahora",
|
||||
"⟳ Riavvia ora",
|
||||
],
|
||||
[
|
||||
"The disk image is open",
|
||||
"Образ диска открыт",
|
||||
"L'image disque est ouverte",
|
||||
"Das Disk-Image ist geöffnet",
|
||||
"La imagen de disco está abierta",
|
||||
"L'immagine disco è aperta",
|
||||
],
|
||||
[
|
||||
"1. Quit ChessPenguin (the button below): a running app cannot be replaced.",
|
||||
"1. Закройте ChessPenguin (кнопка ниже): запущенную программу заменить нельзя.",
|
||||
"1. Quittez ChessPenguin (bouton ci-dessous) : une app ouverte ne peut pas être remplacée.",
|
||||
"1. Beenden Sie ChessPenguin (Knopf unten): eine laufende App lässt sich nicht ersetzen.",
|
||||
"1. Cierra ChessPenguin (botón de abajo): una app abierta no se puede reemplazar.",
|
||||
"1. Chiudi ChessPenguin (pulsante sotto): un'app aperta non si può sostituire.",
|
||||
],
|
||||
[
|
||||
"2. In the window of the disk image, drag the ChessPenguin icon onto the Applications folder and choose Replace.",
|
||||
"2. В окне образа диска перетащите значок ChessPenguin на папку «Программы» и нажмите «Заменить».",
|
||||
"2. Dans la fenêtre de l'image disque, faites glisser l'icône de ChessPenguin sur le dossier Applications et choisissez Remplacer.",
|
||||
"2. Ziehen Sie im Fenster des Disk-Images das ChessPenguin-Symbol auf den Ordner Programme und wählen Sie Ersetzen.",
|
||||
"2. En la ventana de la imagen de disco, arrastra el icono de ChessPenguin a la carpeta Aplicaciones y elige Reemplazar.",
|
||||
"2. Nella finestra dell'immagine disco trascina l'icona di ChessPenguin sulla cartella Applicazioni e scegli Sostituisci.",
|
||||
],
|
||||
[
|
||||
"3. Start ChessPenguin from Applications.",
|
||||
"3. Запустите ChessPenguin из «Программ».",
|
||||
"3. Lancez ChessPenguin depuis Applications.",
|
||||
"3. Starten Sie ChessPenguin aus Programme.",
|
||||
"3. Abre ChessPenguin desde Aplicaciones.",
|
||||
"3. Avvia ChessPenguin da Applicazioni.",
|
||||
],
|
||||
[
|
||||
"Quit ChessPenguin",
|
||||
"Закрыть ChessPenguin",
|
||||
"Quitter ChessPenguin",
|
||||
"ChessPenguin beenden",
|
||||
"Cerrar ChessPenguin",
|
||||
"Chiudi ChessPenguin",
|
||||
],
|
||||
[
|
||||
"The new version is downloaded",
|
||||
"Новая версия скачана",
|
||||
"La nouvelle version est téléchargée",
|
||||
"Die neue Version ist heruntergeladen",
|
||||
"La nueva versión está descargada",
|
||||
"La nuova versione è scaricata",
|
||||
],
|
||||
[
|
||||
"Open the folder",
|
||||
"Открыть папку",
|
||||
"Ouvrir le dossier",
|
||||
"Ordner öffnen",
|
||||
"Abrir la carpeta",
|
||||
"Apri la cartella",
|
||||
],
|
||||
[
|
||||
"1. Copy the command.",
|
||||
"1. Скопируйте команду.",
|
||||
"1. Copiez la commande.",
|
||||
"1. Kopieren Sie den Befehl.",
|
||||
"1. Copia el comando.",
|
||||
"1. Copia il comando.",
|
||||
],
|
||||
[
|
||||
"2. Open the Terminal of your system (not inside the Flatpak), paste the command (Ctrl+Shift+V) and press Enter.",
|
||||
"2. Откройте «Терминал» системы (не внутри Flatpak), вставьте команду (Ctrl+Shift+V) и нажмите Enter.",
|
||||
"2. Ouvrez le Terminal du système (pas dans le Flatpak), collez la commande (Ctrl+Maj+V) et appuyez sur Entrée.",
|
||||
"2. Öffnen Sie das Terminal des Systems (nicht im Flatpak), fügen Sie den Befehl ein (Strg+Umschalt+V) und drücken Sie Enter.",
|
||||
"2. Abre la Terminal del sistema (no dentro del Flatpak), pega el comando (Ctrl+Mayús+V) y pulsa Intro.",
|
||||
"2. Apri il Terminale del sistema (non dentro il Flatpak), incolla il comando (Ctrl+Maiusc+V) e premi Invio.",
|
||||
],
|
||||
[
|
||||
"2. Open the Terminal, paste the command (Ctrl+Shift+V) and press Enter. It asks for your password: while you type it nothing is shown, that is normal.",
|
||||
"2. Откройте «Терминал», вставьте команду (Ctrl+Shift+V) и нажмите Enter. Система спросит пароль: при вводе он не отображается, это нормально.",
|
||||
"2. Ouvrez le Terminal, collez la commande (Ctrl+Maj+V) et appuyez sur Entrée. Votre mot de passe est demandé : rien ne s'affiche pendant la saisie, c'est normal.",
|
||||
"2. Öffnen Sie das Terminal, fügen Sie den Befehl ein (Strg+Umschalt+V) und drücken Sie Enter. Es fragt nach Ihrem Passwort: bei der Eingabe wird nichts angezeigt, das ist normal.",
|
||||
"2. Abre la Terminal, pega el comando (Ctrl+Mayús+V) y pulsa Intro. Pedirá tu contraseña: al escribirla no se ve nada, es normal.",
|
||||
"2. Apri il Terminale, incolla il comando (Ctrl+Maiusc+V) e premi Invio. Chiede la password: mentre la scrivi non si vede nulla, è normale.",
|
||||
],
|
||||
[
|
||||
"3. When the command has finished, start ChessPenguin again.",
|
||||
"3. Когда команда закончится, запустите ChessPenguin снова.",
|
||||
"3. Quand la commande est terminée, relancez ChessPenguin.",
|
||||
"3. Wenn der Befehl fertig ist, starten Sie ChessPenguin neu.",
|
||||
"3. Cuando el comando termine, abre ChessPenguin de nuevo.",
|
||||
"3. Quando il comando è finito, riavvia ChessPenguin.",
|
||||
],
|
||||
[
|
||||
"ChessPenguin is installed from the AUR. Update it as usual, for example:",
|
||||
"ChessPenguin установлен из AUR. Обновите его как обычно, например:",
|
||||
"ChessPenguin est installé depuis l'AUR. Mettez-le à jour comme d'habitude, par exemple :",
|
||||
"ChessPenguin ist aus dem AUR installiert. Aktualisieren Sie es wie gewohnt, zum Beispiel:",
|
||||
"ChessPenguin está instalado desde AUR. Actualízalo como siempre, por ejemplo:",
|
||||
"ChessPenguin è installato da AUR. Aggiornalo come al solito, per esempio:",
|
||||
],
|
||||
[
|
||||
"This release has no file for your system yet. Download the new version from the website:",
|
||||
"В этом выпуске пока нет файла для вашей системы. Скачайте новую версию на сайте:",
|
||||
"Cette version n'a pas encore de fichier pour votre système. Téléchargez-la sur le site :",
|
||||
"Diese Version hat noch keine Datei für Ihr System. Laden Sie sie von der Website:",
|
||||
"Esta versión aún no tiene archivo para tu sistema. Descárgala en el sitio web:",
|
||||
"Questa versione non ha ancora un file per il tuo sistema. Scaricala dal sito:",
|
||||
],
|
||||
[
|
||||
"Not now",
|
||||
"Не сейчас",
|
||||
"Pas maintenant",
|
||||
"Nicht jetzt",
|
||||
"Ahora no",
|
||||
"Non ora",
|
||||
],
|
||||
[
|
||||
"Skip this version",
|
||||
"Пропустить эту версию",
|
||||
"Ignorer cette version",
|
||||
"Diese Version überspringen",
|
||||
"Omitir esta versión",
|
||||
"Salta questa versione",
|
||||
],
|
||||
[
|
||||
"The button next to Settings is hidden until the next version; Settings → About still offers this one",
|
||||
"Кнопка рядом с «Настройками» спрячется до следующей версии; в «Настройки → О программе» эту можно будет поставить",
|
||||
"Le bouton près de Réglages est masqué jusqu'à la prochaine version ; Réglages → À propos propose toujours celle-ci",
|
||||
"Der Knopf neben Einstellungen wird bis zur nächsten Version ausgeblendet; Einstellungen → Über bietet diese weiterhin an",
|
||||
"El botón junto a Ajustes se oculta hasta la próxima versión; Ajustes → Acerca de sigue ofreciendo esta",
|
||||
"Il pulsante accanto a Impostazioni resta nascosto fino alla prossima versione; Impostazioni → Informazioni offre ancora questa",
|
||||
],
|
||||
[
|
||||
"⬇ {v}: {p} %",
|
||||
"⬇ {v}: {p} %",
|
||||
"⬇ {v} : {p} %",
|
||||
"⬇ {v}: {p} %",
|
||||
"⬇ {v}: {p} %",
|
||||
"⬇ {v}: {p} %",
|
||||
],
|
||||
[
|
||||
"⟳ Restart for {v}",
|
||||
"⟳ Перезапустить ({v})",
|
||||
"⟳ Redémarrer ({v})",
|
||||
"⟳ Neu starten ({v})",
|
||||
"⟳ Reiniciar ({v})",
|
||||
"⟳ Riavvia ({v})",
|
||||
],
|
||||
[
|
||||
"⬆ {v}: install",
|
||||
"⬆ {v}: установить",
|
||||
"⬆ {v} : installer",
|
||||
"⬆ {v}: installieren",
|
||||
"⬆ {v}: instalar",
|
||||
"⬆ {v}: installa",
|
||||
],
|
||||
[
|
||||
"Version {v} is installed",
|
||||
"Версия {v} установлена",
|
||||
"La version {v} est installée",
|
||||
"Version {v} ist installiert",
|
||||
"La versión {v} está instalada",
|
||||
"La versione {v} è installata",
|
||||
],
|
||||
[
|
||||
"The file is in the folder {dir}.",
|
||||
"Файл сохранён в папку {dir}.",
|
||||
"Le fichier est dans le dossier {dir}.",
|
||||
"Die Datei liegt im Ordner {dir}.",
|
||||
"El archivo está en la carpeta {dir}.",
|
||||
"Il file è nella cartella {dir}.",
|
||||
],
|
||||
[
|
||||
"or: {c}",
|
||||
"или: {c}",
|
||||
"ou : {c}",
|
||||
"oder: {c}",
|
||||
"o: {c}",
|
||||
"oppure: {c}",
|
||||
],
|
||||
[
|
||||
"ChessPenguin downloads the new version ({mb} MB), checks it and puts it in place of this one. Databases, games and settings are not touched.",
|
||||
"Программа скачает новую версию ({mb} МБ), проверит её и заменит текущую. Базы, партии и настройки не затрагиваются.",
|
||||
"ChessPenguin télécharge la nouvelle version ({mb} Mo), la vérifie et la met à la place de celle-ci. Bases, parties et réglages ne sont pas touchés.",
|
||||
"ChessPenguin lädt die neue Version ({mb} MB), prüft sie und ersetzt diese. Datenbanken, Partien und Einstellungen bleiben unberührt.",
|
||||
"ChessPenguin descarga la nueva versión ({mb} MB), la comprueba y sustituye a esta. Las bases, partidas y ajustes no se tocan.",
|
||||
"ChessPenguin scarica la nuova versione ({mb} MB), la verifica e la mette al posto di questa. Basi, partite e impostazioni non vengono toccate.",
|
||||
],
|
||||
[
|
||||
"ChessPenguin downloads the disk image ({mb} MB), checks it and opens it; then you drag the app over the old one, as when you installed it.",
|
||||
"Программа скачает образ диска ({mb} МБ), проверит и откроет его; затем вы перетащите программу поверх старой, как при установке.",
|
||||
"ChessPenguin télécharge l'image disque ({mb} Mo), la vérifie et l'ouvre ; vous glissez ensuite l'app sur l'ancienne, comme à l'installation.",
|
||||
"ChessPenguin lädt das Disk-Image ({mb} MB), prüft und öffnet es; dann ziehen Sie die App über die alte, wie bei der Installation.",
|
||||
"ChessPenguin descarga la imagen de disco ({mb} MB), la comprueba y la abre; luego arrastras la app sobre la antigua, como al instalarla.",
|
||||
"ChessPenguin scarica l'immagine disco ({mb} MB), la verifica e la apre; poi trascini l'app sopra la vecchia, come all'installazione.",
|
||||
],
|
||||
[
|
||||
"ChessPenguin was installed through the system (its package manager), so it cannot replace itself. It downloads the new version ({mb} MB) into Downloads; to install it you run one command in a terminal, which you can copy.",
|
||||
"ChessPenguin установлен через систему (менеджер пакетов), поэтому заменить себя сам не может. Программа скачает новую версию ({mb} МБ) в «Загрузки», а установить её нужно одной командой в терминале — её можно будет скопировать.",
|
||||
"ChessPenguin a été installé par le système (son gestionnaire de paquets) : il ne peut pas se remplacer lui-même. Il télécharge la nouvelle version ({mb} Mo) dans Téléchargements ; pour l'installer, lancez une commande dans un terminal, que vous pourrez copier.",
|
||||
"ChessPenguin wurde über das System (Paketverwaltung) installiert und kann sich nicht selbst ersetzen. Es lädt die neue Version ({mb} MB) nach Downloads; zum Installieren führen Sie einen Befehl im Terminal aus, den Sie kopieren können.",
|
||||
"ChessPenguin se instaló a través del sistema (su gestor de paquetes), así que no puede reemplazarse solo. Descarga la nueva versión ({mb} MB) en Descargas; para instalarla ejecutas un comando en una terminal, que podrás copiar.",
|
||||
"ChessPenguin è stato installato tramite il sistema (il gestore dei pacchetti), quindi non può sostituirsi da solo. Scarica la nuova versione ({mb} MB) in Download; per installarla esegui un comando in un terminale, che potrai copiare.",
|
||||
],
|
||||
[
|
||||
"Installation: {kind}",
|
||||
"Тип установки: {kind}",
|
||||
"Installation : {kind}",
|
||||
"Installation: {kind}",
|
||||
"Instalación: {kind}",
|
||||
"Installazione: {kind}",
|
||||
],
|
||||
[
|
||||
"You have {old}",
|
||||
"У вас {old}",
|
||||
"Vous avez {old}",
|
||||
"Sie haben {old}",
|
||||
"Tienes la {old}",
|
||||
"Hai la {old}",
|
||||
],
|
||||
[
|
||||
"Checking engine…",
|
||||
"Проверка движка…",
|
||||
|
|
@ -3343,6 +3999,8 @@ mod tests {
|
|||
include_str!("settings_ui.rs"),
|
||||
include_str!("widgets.rs"),
|
||||
include_str!("reference.rs"),
|
||||
include_str!("update.rs"),
|
||||
include_str!("update_ui.rs"),
|
||||
include_str!("report.rs"),
|
||||
include_str!("board.rs"),
|
||||
include_str!("engine_download.rs"),
|
||||
|
|
|
|||
|
|
@ -58,6 +58,8 @@ pub enum LibraryAction {
|
|||
NewGame,
|
||||
PastePgn,
|
||||
AddDatabases,
|
||||
/// The window offering a newer version.
|
||||
OpenUpdate,
|
||||
RemoveDatabase(PathBuf),
|
||||
OpenSettings,
|
||||
}
|
||||
|
|
@ -197,6 +199,8 @@ pub struct Library {
|
|||
view: Vec<usize>,
|
||||
view_key: Option<(PathBuf, String, SortKey, bool)>,
|
||||
scroll_to_selected: bool,
|
||||
/// A newer version to offer (its number), next to Settings.
|
||||
pub update: Option<String>,
|
||||
/// File sizes of databases (`file_size`).
|
||||
sizes: HashMap<PathBuf, u64>,
|
||||
}
|
||||
|
|
@ -219,6 +223,7 @@ impl Library {
|
|||
view_key: None,
|
||||
scroll_to_selected: false,
|
||||
sizes: HashMap::new(),
|
||||
update: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -592,6 +597,11 @@ impl Library {
|
|||
if ui.button(tr("⚙ Settings")).clicked() {
|
||||
actions.push(LibraryAction::OpenSettings);
|
||||
}
|
||||
if let Some(v) = &self.update
|
||||
&& crate::widgets::update_button(ui, v).clicked()
|
||||
{
|
||||
actions.push(LibraryAction::OpenUpdate);
|
||||
}
|
||||
if ui.button(tr("📋 Paste PGN")).clicked() {
|
||||
actions.push(LibraryAction::PastePgn);
|
||||
}
|
||||
|
|
@ -610,6 +620,11 @@ impl Library {
|
|||
if ui.button(tr("⚙ Settings")).clicked() {
|
||||
actions.push(LibraryAction::OpenSettings);
|
||||
}
|
||||
if let Some(v) = &self.update
|
||||
&& crate::widgets::update_button(ui, v).clicked()
|
||||
{
|
||||
actions.push(LibraryAction::OpenUpdate);
|
||||
}
|
||||
if ui
|
||||
.button(tr("📋 Paste PGN"))
|
||||
.on_hover_text(tr("Open a game from the clipboard"))
|
||||
|
|
|
|||
|
|
@ -21,6 +21,8 @@ mod review;
|
|||
mod settings;
|
||||
mod settings_ui;
|
||||
mod sound;
|
||||
mod update;
|
||||
mod update_ui;
|
||||
mod viewed;
|
||||
mod widgets;
|
||||
|
||||
|
|
|
|||
|
|
@ -84,6 +84,12 @@ pub struct Settings {
|
|||
pub engines_discovered: bool,
|
||||
/// The sample databases were put on the shelf (see `examples::first_run_setup`).
|
||||
pub examples_added: bool,
|
||||
/// Ask GitHub for a newer release at start (Settings → About).
|
||||
pub check_updates: bool,
|
||||
/// A version the user chose to skip (its button is not shown).
|
||||
pub skipped_version: Option<String>,
|
||||
/// The version that ran last (to say "updated to …" once).
|
||||
pub last_version: Option<String>,
|
||||
/// The database of the reference tab (`None`: the largest one on the shelf).
|
||||
pub reference_db: Option<PathBuf>,
|
||||
}
|
||||
|
|
@ -139,6 +145,9 @@ impl Default for Settings {
|
|||
review: ReviewSettings::default(),
|
||||
engines_discovered: false,
|
||||
examples_added: false,
|
||||
check_updates: true,
|
||||
skipped_version: None,
|
||||
last_version: None,
|
||||
reference_db: None,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,10 @@ pub enum SettingsAction {
|
|||
TestSound,
|
||||
/// The active engine (or its options) changed; a running analysis should restart.
|
||||
EngineChanged,
|
||||
/// Ask now whether a newer version is out.
|
||||
CheckUpdates,
|
||||
/// Open the update window.
|
||||
OpenUpdate,
|
||||
}
|
||||
|
||||
pub struct SettingsWindow {
|
||||
|
|
@ -37,6 +41,10 @@ pub struct SettingsWindow {
|
|||
pub download: Option<crate::engine_download::Stage>,
|
||||
/// Engine whose removal (with its downloaded files) waits for confirmation.
|
||||
confirm_remove: Option<usize>,
|
||||
/// What the update check found, set by the application every frame, and the newer
|
||||
/// version if there is one.
|
||||
pub update_status: Option<String>,
|
||||
pub update_available: Option<String>,
|
||||
}
|
||||
|
||||
impl SettingsWindow {
|
||||
|
|
@ -47,6 +55,8 @@ impl SettingsWindow {
|
|||
checking_engine: false,
|
||||
download: None,
|
||||
confirm_remove: None,
|
||||
update_status: None,
|
||||
update_available: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -75,7 +85,41 @@ impl SettingsWindow {
|
|||
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::About => about_tab(ui, s.language),
|
||||
Tab::About => {
|
||||
let (status, available) =
|
||||
(self.update_status.clone(), self.update_available.clone());
|
||||
about_tab(ui, s.language, |ui| {
|
||||
// Updates, right under the version.
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
match (&available, &status) {
|
||||
(Some(v), _) => {
|
||||
let label = RichText::new(trf(
|
||||
"⬆ Update to {v}…",
|
||||
&[("v", v)],
|
||||
))
|
||||
.color(ui.visuals().hyperlink_color);
|
||||
if ui.button(label).clicked() {
|
||||
actions.push(SettingsAction::OpenUpdate);
|
||||
}
|
||||
}
|
||||
(None, Some(st)) => {
|
||||
ui.label(RichText::new(st).weak());
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
if ui.button(tr("Check now")).clicked() {
|
||||
actions.push(SettingsAction::CheckUpdates);
|
||||
}
|
||||
});
|
||||
changed |= ui
|
||||
.checkbox(&mut s.check_updates, tr("Check for updates at start"))
|
||||
.on_hover_text(tr(
|
||||
"ChessPenguin asks GitHub which version is the latest; nothing about you is sent",
|
||||
))
|
||||
.changed();
|
||||
});
|
||||
}
|
||||
Tab::Interface => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Language:"));
|
||||
|
|
@ -478,7 +522,7 @@ const REPO: &str = "https://github.com/vrubelroman/chessPenguin";
|
|||
const EMAIL: &str = "vrubelroman@gmail.com";
|
||||
|
||||
/// Version, links to the website and the sources, support contacts.
|
||||
fn about_tab(ui: &mut Ui, lang: Lang) {
|
||||
fn about_tab(ui: &mut Ui, lang: Lang, updates: impl FnOnce(&mut Ui)) {
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
// The website page in the interface language.
|
||||
let site = match lang {
|
||||
|
|
@ -492,6 +536,7 @@ fn about_tab(ui: &mut Ui, lang: Lang) {
|
|||
ui.add_space(6.0);
|
||||
ui.label(RichText::new("ChessPenguin").size(22.0).strong());
|
||||
ui.label(format!("{} {version}", tr("Version")));
|
||||
updates(ui);
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"Free chess database software for Windows, macOS and Linux.",
|
||||
|
|
|
|||
947
apps/desktop/src/update.rs
Normal file
947
apps/desktop/src/update.rs
Normal file
|
|
@ -0,0 +1,947 @@
|
|||
//! Updates: at start the program asks GitHub for the latest release (once, in the
|
||||
//! background; can be turned off in Settings → About). When it is newer, a button next
|
||||
//! to Settings offers it. What "update" does depends on how ChessPenguin was installed:
|
||||
//!
|
||||
//! - the Windows zip, the AppImage and the Linux tarball: the new file is downloaded,
|
||||
//! checked against `SHA256SUMS.txt` and put in place of the running one; the program
|
||||
//! offers to restart (Windows can rename a running executable, Linux can replace it);
|
||||
//! - macOS: the disk image is downloaded, checked and opened; the user drags the app
|
||||
//! over the old one, as at the first installation;
|
||||
//! - deb, rpm, Arch and Flatpak packages: their files belong to the system's package
|
||||
//! manager, so the package is downloaded into Downloads, checked, and the one command
|
||||
//! that installs it is shown with a Copy button;
|
||||
//! - the AUR package: it is updated with the AUR helper (the command is shown);
|
||||
//! - anything else (a build from the sources): a link to the download page.
|
||||
//!
|
||||
//! `CP_UPDATE_SOURCE=<dir>` reads `latest.json` (the GitHub answer) and the assets from
|
||||
//! a directory instead (tests, manual checks); `CP_UPDATE_KIND=<kind>` pretends another
|
||||
//! kind of installation.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const API: &str = "https://api.github.com/repos/vrubelroman/chessPenguin/releases/latest";
|
||||
pub const DOWNLOAD_PAGE: &str = "https://chess.vrubel.xyz/";
|
||||
|
||||
/// How this copy of ChessPenguin was installed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Install {
|
||||
/// The Windows zip: the executable can be replaced.
|
||||
Windows(PathBuf),
|
||||
/// macOS: the app bundle (replaced by the user from the disk image).
|
||||
Mac,
|
||||
/// An AppImage at this path (replaced in place).
|
||||
AppImage(PathBuf),
|
||||
/// The Linux tarball unpacked here: its `chesspenguin` is replaced.
|
||||
Tarball(PathBuf),
|
||||
Deb,
|
||||
Rpm,
|
||||
Arch,
|
||||
/// The AUR package `chesspenguin-bin`.
|
||||
Aur,
|
||||
Flatpak,
|
||||
/// A build from the sources, or a place we cannot write to.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Install {
|
||||
/// The suffix of the release asset for this installation.
|
||||
fn asset_suffix(&self) -> Option<&'static str> {
|
||||
Some(match self {
|
||||
Install::Windows(_) => "-windows-x86_64.zip",
|
||||
Install::Mac => "-macos-arm64.dmg",
|
||||
Install::AppImage(_) => "-x86_64.AppImage",
|
||||
Install::Tarball(_) => "-linux-x86_64.tar.gz",
|
||||
Install::Deb => "_amd64.deb",
|
||||
Install::Rpm => ".x86_64.rpm",
|
||||
Install::Arch => "-x86_64.pkg.tar.zst",
|
||||
Install::Flatpak => "-x86_64.flatpak",
|
||||
Install::Aur | Install::Other => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The program replaces its own files.
|
||||
pub fn replaces_itself(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Install::Windows(_) | Install::AppImage(_) | Install::Tarball(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// Short name for the dialog ("deb package").
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Install::Windows(_) => "Windows",
|
||||
Install::Mac => "macOS",
|
||||
Install::AppImage(_) => "AppImage",
|
||||
Install::Tarball(_) => "tar.gz",
|
||||
Install::Deb => "deb",
|
||||
Install::Rpm => "rpm",
|
||||
Install::Arch => "Arch Linux",
|
||||
Install::Aur => "AUR",
|
||||
Install::Flatpak => "Flatpak",
|
||||
Install::Other => "—",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn writable_dir(dir: &Path) -> bool {
|
||||
let probe = dir.join(".chesspenguin-write-test");
|
||||
let ok = std::fs::File::create(&probe).is_ok();
|
||||
let _ = std::fs::remove_file(&probe);
|
||||
ok
|
||||
}
|
||||
|
||||
/// How this copy was installed (see [`Install`]).
|
||||
pub fn detect() -> Install {
|
||||
if let Ok(kind) = std::env::var("CP_UPDATE_KIND") {
|
||||
let exe = std::env::current_exe().unwrap_or_default();
|
||||
return match kind.as_str() {
|
||||
"windows" => Install::Windows(exe),
|
||||
"mac" => Install::Mac,
|
||||
"appimage" => {
|
||||
Install::AppImage(std::env::var_os("APPIMAGE").map_or(exe, PathBuf::from))
|
||||
}
|
||||
"tarball" => Install::Tarball(exe.parent().map(Path::to_owned).unwrap_or_default()),
|
||||
"deb" => Install::Deb,
|
||||
"rpm" => Install::Rpm,
|
||||
"arch" => Install::Arch,
|
||||
"aur" => Install::Aur,
|
||||
"flatpak" => Install::Flatpak,
|
||||
_ => Install::Other,
|
||||
};
|
||||
}
|
||||
let Ok(exe) = std::env::current_exe() else {
|
||||
return Install::Other;
|
||||
};
|
||||
if cfg!(windows) {
|
||||
return match exe.parent() {
|
||||
Some(d) if writable_dir(d) => Install::Windows(exe),
|
||||
_ => Install::Other,
|
||||
};
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
return if exe.to_string_lossy().contains(".app/Contents/MacOS/") {
|
||||
Install::Mac
|
||||
} else {
|
||||
Install::Other
|
||||
};
|
||||
}
|
||||
if std::env::var_os("FLATPAK_ID").is_some() {
|
||||
return Install::Flatpak;
|
||||
}
|
||||
// An AppImage of ours: the AppImage runtime sets APPIMAGE and APPDIR, and this
|
||||
// executable lies inside APPDIR (a variable inherited from another AppImage, such
|
||||
// as a terminal started from one, must not make us replace that one).
|
||||
if let (Some(p), Some(appdir)) = (
|
||||
std::env::var_os("APPIMAGE").map(PathBuf::from),
|
||||
std::env::var_os("APPDIR").map(PathBuf::from),
|
||||
) && exe.starts_with(&appdir)
|
||||
{
|
||||
let p = std::fs::canonicalize(&p).unwrap_or(p);
|
||||
return match p.parent() {
|
||||
Some(d) if p.is_file() && writable_dir(d) => Install::AppImage(p),
|
||||
_ => Install::Other,
|
||||
};
|
||||
}
|
||||
if exe == Path::new("/usr/bin/chesspenguin") {
|
||||
return package_kind();
|
||||
}
|
||||
// The tarball: the executable next to the files it was unpacked with.
|
||||
if let Some(dir) = exe.parent()
|
||||
&& dir.join("THIRD_PARTY_NOTICES.md").is_file()
|
||||
&& dir.join("examples").is_dir()
|
||||
&& !dir.join("Cargo.toml").exists()
|
||||
&& writable_dir(dir)
|
||||
{
|
||||
return Install::Tarball(dir.to_owned());
|
||||
}
|
||||
Install::Other
|
||||
}
|
||||
|
||||
/// Which package manager owns `/usr/bin/chesspenguin`.
|
||||
fn package_kind() -> Install {
|
||||
if let Ok(entries) = std::fs::read_dir("/var/lib/pacman/local") {
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if name.starts_with("chesspenguin-bin-") {
|
||||
return Install::Aur;
|
||||
}
|
||||
if name
|
||||
.strip_prefix("chesspenguin-")
|
||||
.is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()))
|
||||
{
|
||||
return Install::Arch;
|
||||
}
|
||||
}
|
||||
}
|
||||
if Path::new("/var/lib/dpkg/info/chesspenguin.list").is_file() {
|
||||
return Install::Deb;
|
||||
}
|
||||
let rpm = std::process::Command::new("rpm")
|
||||
.args(["-q", "chesspenguin"])
|
||||
.output();
|
||||
if rpm.is_ok_and(|o| o.status.success()) {
|
||||
return Install::Rpm;
|
||||
}
|
||||
Install::Other
|
||||
}
|
||||
|
||||
/// "0.7.1" / "v0.7.1" → (0, 7, 1).
|
||||
pub fn parse_version(v: &str) -> Option<(u32, u32, u32)> {
|
||||
let mut it = v.trim().trim_start_matches('v').split('.');
|
||||
let n = |s: Option<&str>| -> Option<u32> {
|
||||
s?.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect::<String>()
|
||||
.parse()
|
||||
.ok()
|
||||
};
|
||||
Some((n(it.next())?, n(it.next())?, n(it.next()).unwrap_or(0)))
|
||||
}
|
||||
|
||||
pub fn current_version() -> (u32, u32, u32) {
|
||||
parse_version(env!("CARGO_PKG_VERSION")).unwrap_or((0, 0, 0))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Asset {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// The latest release.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Release {
|
||||
pub version: String,
|
||||
pub page: String,
|
||||
pub assets: Vec<Asset>,
|
||||
}
|
||||
|
||||
impl Release {
|
||||
pub fn newer(&self) -> bool {
|
||||
parse_version(&self.version).is_some_and(|v| v > current_version())
|
||||
}
|
||||
|
||||
pub fn asset_for(&self, kind: &Install) -> Option<&Asset> {
|
||||
let suffix = kind.asset_suffix()?;
|
||||
self.assets.iter().find(|a| a.name.ends_with(suffix))
|
||||
}
|
||||
|
||||
fn sums(&self) -> Option<&Asset> {
|
||||
self.assets.iter().find(|a| a.name == "SHA256SUMS.txt")
|
||||
}
|
||||
}
|
||||
|
||||
/// A local directory standing in for GitHub (tests).
|
||||
fn source_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("CP_UPDATE_SOURCE").map(PathBuf::from)
|
||||
}
|
||||
|
||||
fn agent(body_timeout: Option<Duration>) -> ureq::Agent {
|
||||
let config = ureq::Agent::config_builder()
|
||||
.user_agent(format!(
|
||||
"ChessPenguin/{} (+https://chess.vrubel.xyz)",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
))
|
||||
.timeout_connect(Some(Duration::from_secs(10)))
|
||||
.timeout_recv_response(Some(Duration::from_secs(30)))
|
||||
.timeout_recv_body(body_timeout)
|
||||
.build();
|
||||
ureq::Agent::new_with_config(config)
|
||||
}
|
||||
|
||||
/// The GitHub answer for the latest release, as a [`Release`].
|
||||
pub fn parse_release(v: &Value) -> Option<Release> {
|
||||
let tag = v["tag_name"].as_str()?;
|
||||
let assets = v["assets"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|a| {
|
||||
Some(Asset {
|
||||
name: a["name"].as_str()?.to_owned(),
|
||||
url: a["browser_download_url"].as_str()?.to_owned(),
|
||||
size: a["size"].as_u64().unwrap_or(0),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(Release {
|
||||
version: tag.trim_start_matches('v').to_owned(),
|
||||
page: v["html_url"].as_str().unwrap_or(DOWNLOAD_PAGE).to_owned(),
|
||||
assets,
|
||||
})
|
||||
}
|
||||
|
||||
/// Asks for the latest release. `Err` with a short reason when there is no answer.
|
||||
pub fn latest() -> Result<Release, String> {
|
||||
let text = match source_dir() {
|
||||
Some(dir) => std::fs::read_to_string(dir.join("latest.json")).map_err(|e| e.to_string())?,
|
||||
None => agent(Some(Duration::from_secs(30)))
|
||||
.get(API)
|
||||
.header("Accept", "application/vnd.github+json")
|
||||
.call()
|
||||
.map_err(|e| e.to_string())?
|
||||
.body_mut()
|
||||
.with_config()
|
||||
.limit(4 << 20)
|
||||
.read_to_string()
|
||||
.map_err(|e| e.to_string())?,
|
||||
};
|
||||
let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
|
||||
parse_release(&v).ok_or_else(|| "unexpected answer".to_owned())
|
||||
}
|
||||
|
||||
/// Opens an asset for reading (from GitHub or from the test directory).
|
||||
fn open(asset: &Asset) -> Result<Box<dyn Read + Send>, String> {
|
||||
match source_dir() {
|
||||
Some(dir) => Ok(Box::new(
|
||||
std::fs::File::open(dir.join(&asset.name)).map_err(|e| e.to_string())?,
|
||||
)),
|
||||
None => {
|
||||
// A whole download within half an hour (a stalled connection ends then).
|
||||
let resp = agent(Some(Duration::from_secs(1800)))
|
||||
.get(&asset.url)
|
||||
.call()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Box::new(resp.into_body().into_reader()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The SHA-256 of `name` in the release's `SHA256SUMS.txt`.
|
||||
fn expected_sum(release: &Release, name: &str) -> Result<String, String> {
|
||||
let sums = release.sums().ok_or("the release has no SHA256SUMS.txt")?;
|
||||
let mut text = String::new();
|
||||
open(sums)?
|
||||
.take(1 << 20)
|
||||
.read_to_string(&mut text)
|
||||
.map_err(|e| e.to_string())?;
|
||||
text.lines()
|
||||
.find_map(|l| {
|
||||
let (hash, file) = l.split_once(char::is_whitespace)?;
|
||||
(file.trim().trim_start_matches('*') == name).then(|| hash.to_lowercase())
|
||||
})
|
||||
.ok_or_else(|| format!("{name} is not in SHA256SUMS.txt"))
|
||||
}
|
||||
|
||||
/// Downloads `asset` into `to` (a `.part` file first), checking its SHA-256;
|
||||
/// `progress` counts the bytes.
|
||||
fn download(
|
||||
release: &Release,
|
||||
asset: &Asset,
|
||||
to: &Path,
|
||||
progress: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<(), String> {
|
||||
let expected = expected_sum(release, &asset.name)?;
|
||||
if let Some(d) = to.parent() {
|
||||
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let part = to.with_extension("part");
|
||||
let result = (|| {
|
||||
let mut input = open(asset)?;
|
||||
let mut file = std::fs::File::create(&part).map_err(|e| e.to_string())?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buf = vec![0u8; 256 * 1024];
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err("cancelled".to_owned());
|
||||
}
|
||||
let n = input.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buf[..n]);
|
||||
file.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||
progress.fetch_add(n, Ordering::Relaxed);
|
||||
}
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
let got = hasher
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>();
|
||||
if got != expected {
|
||||
return Err("checksum".to_owned());
|
||||
}
|
||||
std::fs::rename(&part, to).map_err(|e| e.to_string())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// What an update ended with.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Applied {
|
||||
/// The program's files are replaced: restarting runs the new version.
|
||||
Restart(PathBuf),
|
||||
/// The package is in Downloads: this command installs it.
|
||||
Command { file: PathBuf, command: String },
|
||||
/// The macOS disk image is open: drag the app over the old one.
|
||||
DiskImageOpened(PathBuf),
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn make_executable(p: &Path) -> std::io::Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn make_executable(_: &Path) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Puts `new` in place of `target` (the running program): `new` is moved next to it
|
||||
/// first, so the switch is one rename on the same disk. On Windows the running
|
||||
/// executable cannot be overwritten but can be renamed: it becomes `<name>.old` (removed
|
||||
/// at the next start, see [`clean_leftovers`]).
|
||||
pub fn replace_file(new: &Path, target: &Path) -> std::io::Result<()> {
|
||||
let name = target
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let staged = target.with_file_name(format!(".{name}.new"));
|
||||
std::fs::copy(new, &staged)?;
|
||||
// The permissions of the file it replaces (an executable stays one).
|
||||
match std::fs::metadata(target) {
|
||||
Ok(m) => std::fs::set_permissions(&staged, m.permissions())?,
|
||||
Err(_) => make_executable(&staged)?,
|
||||
}
|
||||
if cfg!(windows) {
|
||||
let old = target.with_file_name(format!("{name}.old"));
|
||||
let _ = std::fs::remove_file(&old);
|
||||
if target.exists() {
|
||||
std::fs::rename(target, &old)?;
|
||||
}
|
||||
if let Err(e) = std::fs::rename(&staged, target) {
|
||||
// Put the old one back rather than leave nothing.
|
||||
let _ = std::fs::rename(&old, target);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
std::fs::rename(&staged, target)
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes what an update left: the previous Windows executable, a staged file.
|
||||
pub fn clean_leftovers() {
|
||||
let Ok(exe) = std::env::current_exe() else {
|
||||
return;
|
||||
};
|
||||
let name = exe
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let _ = std::fs::remove_file(exe.with_file_name(format!("{name}.old")));
|
||||
let _ = std::fs::remove_file(exe.with_file_name(format!(".{name}.new")));
|
||||
}
|
||||
|
||||
fn cache_dir() -> PathBuf {
|
||||
if let Some(d) = std::env::var_os("CP_UPDATE_CACHE") {
|
||||
return PathBuf::from(d);
|
||||
}
|
||||
crate::settings::Settings::cache_dir()
|
||||
.unwrap_or_else(std::env::temp_dir)
|
||||
.join("update")
|
||||
}
|
||||
|
||||
/// `XDG_DOWNLOAD_DIR` of the user's own `~/.config/user-dirs.dirs` (a Flatpak has its
|
||||
/// own config folder, where the file is not).
|
||||
fn host_download_dir(home: &Path) -> Option<PathBuf> {
|
||||
let text = std::fs::read_to_string(home.join(".config/user-dirs.dirs")).ok()?;
|
||||
let line = text
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("XDG_DOWNLOAD_DIR="))?;
|
||||
let v = line
|
||||
.trim()
|
||||
.trim_matches('"')
|
||||
.replace("$HOME", &home.to_string_lossy());
|
||||
let p = PathBuf::from(v);
|
||||
p.is_dir().then_some(p)
|
||||
}
|
||||
|
||||
/// Downloads (the system's, else `~/Downloads` when it exists, else the home folder).
|
||||
fn downloads_dir() -> PathBuf {
|
||||
let dirs = directories::UserDirs::new();
|
||||
dirs.as_ref()
|
||||
.and_then(|u| u.download_dir().map(Path::to_owned))
|
||||
.or_else(|| dirs.as_ref().and_then(|u| host_download_dir(u.home_dir())))
|
||||
.or_else(|| {
|
||||
dirs.as_ref()
|
||||
.map(|u| u.home_dir().join("Downloads"))
|
||||
.filter(|d| d.is_dir())
|
||||
})
|
||||
.or_else(|| dirs.as_ref().map(|u| u.home_dir().to_owned()))
|
||||
.unwrap_or_else(std::env::temp_dir)
|
||||
}
|
||||
|
||||
/// A word for a shell command: as it is when it has only safe characters, else in
|
||||
/// single quotes (nothing is expanded inside them in sh, bash, zsh and fish).
|
||||
fn shell_word(s: &str) -> String {
|
||||
let safe = |c: char| c.is_ascii_alphanumeric() || "/._-+:@%,".contains(c);
|
||||
if !s.is_empty() && s.chars().all(safe) {
|
||||
s.to_owned()
|
||||
} else {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The executable inside a downloaded Windows zip or Linux tarball.
|
||||
fn unpack_executable(archive: &Path, kind: &Install, into: &Path) -> Result<PathBuf, String> {
|
||||
std::fs::create_dir_all(into).map_err(|e| e.to_string())?;
|
||||
let out = into.join(if matches!(kind, Install::Windows(_)) {
|
||||
"ChessPenguin.exe"
|
||||
} else {
|
||||
"chesspenguin"
|
||||
});
|
||||
match kind {
|
||||
Install::Windows(_) => {
|
||||
let file = std::fs::File::open(archive).map_err(|e| e.to_string())?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||
let mut found = false;
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i).map_err(|e| e.to_string())?;
|
||||
let name = entry.name().map_err(|e| e.to_string())?.into_owned();
|
||||
if entry.is_file()
|
||||
&& (name.ends_with("/ChessPenguin.exe") || name == "ChessPenguin.exe")
|
||||
{
|
||||
let mut f = std::fs::File::create(&out).map_err(|e| e.to_string())?;
|
||||
std::io::copy(&mut entry, &mut f).map_err(|e| e.to_string())?;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err("ChessPenguin.exe is not in the archive".into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let file = std::fs::File::open(archive).map_err(|e| e.to_string())?;
|
||||
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
|
||||
let mut found = false;
|
||||
for entry in tar.entries().map_err(|e| e.to_string())? {
|
||||
let mut entry = entry.map_err(|e| e.to_string())?;
|
||||
let path = entry.path().map_err(|e| e.to_string())?.into_owned();
|
||||
if path.file_name().is_some_and(|n| n == "chesspenguin")
|
||||
&& entry.header().entry_type().is_file()
|
||||
{
|
||||
let mut f = std::fs::File::create(&out).map_err(|e| e.to_string())?;
|
||||
std::io::copy(&mut entry, &mut f).map_err(|e| e.to_string())?;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err("chesspenguin is not in the archive".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
make_executable(&out).map_err(|e| e.to_string())?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Downloads and applies the update for this installation (in a background thread).
|
||||
pub fn update(
|
||||
release: &Release,
|
||||
kind: &Install,
|
||||
progress: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<Applied, String> {
|
||||
let asset = release
|
||||
.asset_for(kind)
|
||||
.ok_or("the release has no file for this installation")?
|
||||
.clone();
|
||||
match kind {
|
||||
Install::Windows(_) | Install::AppImage(_) | Install::Tarball(_) => {
|
||||
let dir = cache_dir();
|
||||
let archive = dir.join(&asset.name);
|
||||
download(release, &asset, &archive, progress, cancel)?;
|
||||
let result = (|| {
|
||||
let (new, target) = match kind {
|
||||
Install::AppImage(path) => (archive.clone(), path.clone()),
|
||||
Install::Windows(exe) => (
|
||||
unpack_executable(&archive, kind, &dir.join("unpacked"))?,
|
||||
exe.clone(),
|
||||
),
|
||||
Install::Tarball(folder) => (
|
||||
unpack_executable(&archive, kind, &dir.join("unpacked"))?,
|
||||
folder.join("chesspenguin"),
|
||||
),
|
||||
_ => unreachable!("kinds that replace themselves"),
|
||||
};
|
||||
replace_file(&new, &target).map_err(|e| e.to_string())?;
|
||||
Ok(Applied::Restart(target))
|
||||
})();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
result
|
||||
}
|
||||
Install::Mac => {
|
||||
let file = downloads_dir().join(&asset.name);
|
||||
download(release, &asset, &file, progress, cancel)?;
|
||||
let _ = std::process::Command::new("open").arg(&file).spawn();
|
||||
Ok(Applied::DiskImageOpened(file))
|
||||
}
|
||||
Install::Deb | Install::Rpm | Install::Arch | Install::Flatpak => {
|
||||
let file = downloads_dir().join(&asset.name);
|
||||
download(release, &asset, &file, progress, cancel)?;
|
||||
Ok(Applied::Command {
|
||||
command: install_command(kind, &file).unwrap_or_default(),
|
||||
file,
|
||||
})
|
||||
}
|
||||
Install::Aur | Install::Other => Err("no automatic update for this installation".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// openSUSE installs rpm packages with zypper, the others with dnf.
|
||||
fn suse() -> bool {
|
||||
std::fs::read_to_string("/etc/os-release").is_ok_and(|t| {
|
||||
t.lines()
|
||||
.any(|l| (l.starts_with("ID=") || l.starts_with("ID_LIKE=")) && l.contains("suse"))
|
||||
})
|
||||
}
|
||||
|
||||
/// A Flatpak installed for the user (not system-wide): `/.flatpak-info` says where.
|
||||
fn flatpak_user() -> bool {
|
||||
std::fs::read_to_string("/.flatpak-info").map_or(true, |t| t.contains("/.local/share/flatpak"))
|
||||
}
|
||||
|
||||
/// The command that installs a downloaded package (`None`: nothing to download): it
|
||||
/// goes to the package's folder first, so the command stays short.
|
||||
pub fn install_command(kind: &Install, file: &Path) -> Option<String> {
|
||||
let dir = shell_word(&file.parent()?.to_string_lossy());
|
||||
let name = shell_word(&format!("./{}", file.file_name()?.to_string_lossy()));
|
||||
let install = match kind {
|
||||
Install::Deb => "sudo apt install",
|
||||
Install::Rpm if suse() => "sudo zypper install",
|
||||
Install::Rpm => "sudo dnf install",
|
||||
Install::Arch => "sudo pacman -U",
|
||||
Install::Flatpak if flatpak_user() => "flatpak install --user --reinstall -y",
|
||||
Install::Flatpak => "flatpak install --system --reinstall -y",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!("cd {dir} && {install} {name}"))
|
||||
}
|
||||
|
||||
/// The command for the AUR package (no download: the helper builds it).
|
||||
pub const AUR_COMMAND: &str = "yay -Syu chesspenguin-bin";
|
||||
/// The same with the other common AUR helper.
|
||||
pub const AUR_COMMAND_PARU: &str = "paru -Syu chesspenguin-bin";
|
||||
|
||||
/// The release check at start, in the background.
|
||||
pub struct Check {
|
||||
rx: Option<std::sync::mpsc::Receiver<Result<Release, String>>>,
|
||||
pub release: Option<Release>,
|
||||
pub error: Option<String>,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
impl Check {
|
||||
pub fn idle() -> Check {
|
||||
Check {
|
||||
rx: None,
|
||||
release: None,
|
||||
error: None,
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks again, keeping what the previous check found until the answer comes (a
|
||||
/// failed second check does not take an offer away).
|
||||
pub fn again(&self, ctx: &egui::Context) -> Check {
|
||||
let mut c = Check::start(ctx);
|
||||
c.release = self.release.clone();
|
||||
c
|
||||
}
|
||||
|
||||
pub fn start(ctx: &egui::Context) -> Check {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ctx = ctx.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("update-check".into())
|
||||
.spawn(move || {
|
||||
let _ = tx.send(latest());
|
||||
ctx.request_repaint();
|
||||
});
|
||||
Check {
|
||||
rx: spawned.ok().map(|_| rx),
|
||||
..Check::idle()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn poll(&mut self) {
|
||||
if let Some(rx) = &self.rx
|
||||
&& let Ok(r) = rx.try_recv()
|
||||
{
|
||||
match r {
|
||||
Ok(rel) => {
|
||||
self.release = Some(rel);
|
||||
self.error = None;
|
||||
}
|
||||
Err(e) => self.error = Some(e),
|
||||
}
|
||||
self.rx = None;
|
||||
self.done = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn running(&self) -> bool {
|
||||
self.rx.is_some()
|
||||
}
|
||||
|
||||
/// A newer release, if one was found.
|
||||
pub fn newer(&self) -> Option<&Release> {
|
||||
self.release.as_ref().filter(|r| r.newer())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn versions() {
|
||||
assert_eq!(parse_version("v0.7.1"), Some((0, 7, 1)));
|
||||
assert_eq!(parse_version("0.8"), Some((0, 8, 0)));
|
||||
assert_eq!(parse_version("1.2.3-beta"), Some((1, 2, 3)));
|
||||
assert_eq!(parse_version("x"), None);
|
||||
assert!((0, 10, 0) > (0, 9, 9));
|
||||
}
|
||||
|
||||
fn release() -> Release {
|
||||
let names = [
|
||||
"ChessPenguin-9.9.9-windows-x86_64.zip",
|
||||
"ChessPenguin-9.9.9-macos-arm64.dmg",
|
||||
"ChessPenguin-9.9.9-x86_64.AppImage",
|
||||
"ChessPenguin-9.9.9-linux-x86_64.tar.gz",
|
||||
"chesspenguin_9.9.9_amd64.deb",
|
||||
"chesspenguin-9.9.9-1.x86_64.rpm",
|
||||
"chesspenguin-9.9.9-1-x86_64.pkg.tar.zst",
|
||||
"ChessPenguin-9.9.9-x86_64.flatpak",
|
||||
"SHA256SUMS.txt",
|
||||
];
|
||||
Release {
|
||||
version: "9.9.9".into(),
|
||||
page: String::new(),
|
||||
assets: names
|
||||
.iter()
|
||||
.map(|n| Asset {
|
||||
name: (*n).into(),
|
||||
url: format!("https://example.org/{n}"),
|
||||
size: 1,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_asset_for_every_installation() {
|
||||
let r = release();
|
||||
assert!(r.newer());
|
||||
for (kind, name) in [
|
||||
(
|
||||
Install::Windows(PathBuf::new()),
|
||||
"ChessPenguin-9.9.9-windows-x86_64.zip",
|
||||
),
|
||||
(Install::Mac, "ChessPenguin-9.9.9-macos-arm64.dmg"),
|
||||
(
|
||||
Install::AppImage(PathBuf::new()),
|
||||
"ChessPenguin-9.9.9-x86_64.AppImage",
|
||||
),
|
||||
(
|
||||
Install::Tarball(PathBuf::new()),
|
||||
"ChessPenguin-9.9.9-linux-x86_64.tar.gz",
|
||||
),
|
||||
(Install::Deb, "chesspenguin_9.9.9_amd64.deb"),
|
||||
(Install::Rpm, "chesspenguin-9.9.9-1.x86_64.rpm"),
|
||||
(Install::Arch, "chesspenguin-9.9.9-1-x86_64.pkg.tar.zst"),
|
||||
(Install::Flatpak, "ChessPenguin-9.9.9-x86_64.flatpak"),
|
||||
] {
|
||||
assert_eq!(r.asset_for(&kind).map(|a| a.name.as_str()), Some(name));
|
||||
}
|
||||
assert!(r.asset_for(&Install::Aur).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_answer() {
|
||||
let v: Value = serde_json::from_str(
|
||||
r#"{"tag_name":"v0.7.1","html_url":"https://github.com/x/releases/tag/v0.7.1",
|
||||
"assets":[{"name":"SHA256SUMS.txt","browser_download_url":"https://x/s","size":10}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let r = parse_release(&v).unwrap();
|
||||
assert_eq!(r.version, "0.7.1");
|
||||
assert_eq!(r.assets.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands() {
|
||||
let f = Path::new("/home/u/Downloads/chesspenguin_9.9.9_amd64.deb");
|
||||
assert_eq!(
|
||||
install_command(&Install::Deb, f).unwrap(),
|
||||
"cd /home/u/Downloads && sudo apt install ./chesspenguin_9.9.9_amd64.deb"
|
||||
);
|
||||
let spaced = Path::new("/home/u/My Downloads/x.flatpak");
|
||||
assert!(
|
||||
install_command(&Install::Flatpak, spaced)
|
||||
.unwrap()
|
||||
.starts_with("cd '/home/u/My Downloads' && flatpak install")
|
||||
);
|
||||
// Nothing in a path is expanded by the shell.
|
||||
for nasty in [
|
||||
"/home/a`id`/x.deb",
|
||||
"/home/$USER/x.deb",
|
||||
"/home/O'Brien/x.deb",
|
||||
"/h/a b/!x.deb",
|
||||
] {
|
||||
let c = install_command(&Install::Deb, Path::new(nasty)).unwrap();
|
||||
let out = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(
|
||||
c.replace("cd ", "printf '%s\\n' ")
|
||||
.replace(" && sudo apt install ", " "),
|
||||
)
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = String::from_utf8(out.stdout).unwrap();
|
||||
let p = Path::new(nasty);
|
||||
assert_eq!(
|
||||
text,
|
||||
format!(
|
||||
"{}\n./{}\n",
|
||||
p.parent().unwrap().display(),
|
||||
p.file_name().unwrap().to_string_lossy()
|
||||
),
|
||||
"{nasty}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The running test executable can be put aside and back: what an update does to
|
||||
/// the running program (on Windows the rename is the point of the scheme).
|
||||
#[test]
|
||||
fn replacing_the_running_executable() {
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("cp-update-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// A copy of the running executable stands for the program in its folder.
|
||||
let target = dir.join(exe.file_name().unwrap());
|
||||
std::fs::copy(&exe, &target).unwrap();
|
||||
let new = dir.join("new-version");
|
||||
std::fs::write(&new, b"new version").unwrap();
|
||||
replace_file(&new, &target).unwrap();
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"new version");
|
||||
if cfg!(windows) {
|
||||
let name = target.file_name().unwrap().to_string_lossy().into_owned();
|
||||
assert!(target.with_file_name(format!("{name}.old")).exists());
|
||||
}
|
||||
assert!(
|
||||
!dir.join(format!(
|
||||
".{}.new",
|
||||
target.file_name().unwrap().to_string_lossy()
|
||||
))
|
||||
.exists()
|
||||
);
|
||||
// And the running executable itself can be renamed and put back.
|
||||
let aside = exe.with_extension("cp-test-aside");
|
||||
std::fs::rename(&exe, &aside).unwrap();
|
||||
std::fs::rename(&aside, &exe).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A whole update from a local "release": the tarball's executable replaced, the
|
||||
/// checksum checked, a wrong checksum refused.
|
||||
#[test]
|
||||
fn tarball_update_from_a_local_release() {
|
||||
let root = std::env::temp_dir().join(format!("cp-update-tar-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let src = root.join("release");
|
||||
let installed = root.join("installed");
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
std::fs::create_dir_all(&installed).unwrap();
|
||||
std::fs::write(installed.join("chesspenguin"), b"old").unwrap();
|
||||
// The release tarball: a folder with the new executable.
|
||||
let name = "ChessPenguin-9.9.9-linux-x86_64.tar.gz";
|
||||
{
|
||||
let f = std::fs::File::create(src.join(name)).unwrap();
|
||||
let gz = flate2::write::GzEncoder::new(f, flate2::Compression::fast());
|
||||
let mut tar = tar::Builder::new(gz);
|
||||
let mut h = tar::Header::new_gnu();
|
||||
h.set_size(3);
|
||||
h.set_mode(0o755);
|
||||
h.set_cksum();
|
||||
tar.append_data(
|
||||
&mut h,
|
||||
"ChessPenguin-9.9.9-linux-x86_64/chesspenguin",
|
||||
&b"new"[..],
|
||||
)
|
||||
.unwrap();
|
||||
tar.into_inner().unwrap().finish().unwrap();
|
||||
}
|
||||
let sum = |p: &Path| {
|
||||
Sha256::digest(std::fs::read(p).unwrap())
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>()
|
||||
};
|
||||
std::fs::write(
|
||||
src.join("SHA256SUMS.txt"),
|
||||
format!("{} {name}\n", sum(&src.join(name))),
|
||||
)
|
||||
.unwrap();
|
||||
let rel = Release {
|
||||
version: "9.9.9".into(),
|
||||
page: String::new(),
|
||||
assets: [name, "SHA256SUMS.txt"]
|
||||
.iter()
|
||||
.map(|n| Asset {
|
||||
name: (*n).into(),
|
||||
url: String::new(),
|
||||
size: 0,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
// SAFETY of the test: the variable is only read by this process's update code.
|
||||
unsafe {
|
||||
std::env::set_var("CP_UPDATE_SOURCE", &src);
|
||||
std::env::set_var("CP_UPDATE_CACHE", root.join("cache"));
|
||||
}
|
||||
let kind = Install::Tarball(installed.clone());
|
||||
let progress = AtomicUsize::new(0);
|
||||
let applied = update(&rel, &kind, &progress, &AtomicBool::new(false)).unwrap();
|
||||
assert_eq!(applied, Applied::Restart(installed.join("chesspenguin")));
|
||||
assert_eq!(
|
||||
std::fs::read(installed.join("chesspenguin")).unwrap(),
|
||||
b"new"
|
||||
);
|
||||
assert!(progress.load(Ordering::Relaxed) > 0);
|
||||
// A damaged download is refused and nothing is replaced.
|
||||
std::fs::write(installed.join("chesspenguin"), b"old").unwrap();
|
||||
std::fs::write(
|
||||
src.join("SHA256SUMS.txt"),
|
||||
format!("{} {name}\n", "0".repeat(64)),
|
||||
)
|
||||
.unwrap();
|
||||
let err = update(&rel, &kind, &AtomicUsize::new(0), &AtomicBool::new(false)).unwrap_err();
|
||||
assert_eq!(err, "checksum");
|
||||
assert_eq!(
|
||||
std::fs::read(installed.join("chesspenguin")).unwrap(),
|
||||
b"old"
|
||||
);
|
||||
unsafe {
|
||||
std::env::remove_var("CP_UPDATE_SOURCE");
|
||||
std::env::remove_var("CP_UPDATE_CACHE");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
425
apps/desktop/src/update_ui.rs
Normal file
425
apps/desktop/src/update_ui.rs
Normal file
|
|
@ -0,0 +1,425 @@
|
|||
//! The update window: the new version and the one step this installation needs (see
|
||||
//! `update.rs`): update and restart; download and open the disk image; or download the
|
||||
//! package and copy the command that installs it. Closing the window does not stop a
|
||||
//! download (the button next to Settings shows its progress).
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use crate::board_search::Background;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::update::{self, Applied, Install, Release};
|
||||
|
||||
/// What the window asks of the application.
|
||||
pub enum UpdateEvent {
|
||||
/// Quit (asking about unsaved games as usual) and start this executable.
|
||||
Restart(std::path::PathBuf),
|
||||
/// Quit (to replace the app from the disk image, or to start the installed package).
|
||||
Quit,
|
||||
CopyText(String),
|
||||
/// Hide the offer of this version.
|
||||
Skip(String),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UpdateDialog {
|
||||
pub open: bool,
|
||||
/// Dev hook (screenshots, manual checks): `CP_UPDATE_OPEN=1` opens the window once a
|
||||
/// newer release is known, `=start` also starts the update.
|
||||
auto: Option<bool>,
|
||||
job: Option<(u64, Background<Result<Applied, String>>)>,
|
||||
result: Option<Result<Applied, String>>,
|
||||
}
|
||||
|
||||
fn mb(bytes: u64) -> String {
|
||||
if bytes < 1_000_000 {
|
||||
tr("less than 1").to_owned()
|
||||
} else {
|
||||
format!("{:.0}", bytes as f64 / 1e6)
|
||||
}
|
||||
}
|
||||
|
||||
/// The installation for the footnote (for support, not for the decision).
|
||||
fn install_name(kind: &Install) -> String {
|
||||
match kind {
|
||||
Install::Deb => tr("deb package").to_owned(),
|
||||
Install::Rpm => tr("rpm package").to_owned(),
|
||||
Install::Arch => tr("Arch Linux package").to_owned(),
|
||||
Install::Tarball(_) => tr("archive (tar.gz)").to_owned(),
|
||||
Install::Flatpak => "Flatpak".to_owned(),
|
||||
Install::Aur => "AUR (chesspenguin-bin)".to_owned(),
|
||||
other => other.label().to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A failure in words a chess player can act on; the technical text goes under
|
||||
/// "Details".
|
||||
fn failure_text(e: &str) -> String {
|
||||
let lower = e.to_lowercase();
|
||||
if e == "checksum" {
|
||||
tr("The file got damaged while downloading, so it was not installed. Try again.").to_owned()
|
||||
} else if e == "cancelled" {
|
||||
tr("The download was cancelled.").to_owned()
|
||||
} else if lower.contains("no file for this installation")
|
||||
|| lower.contains("not in sha256sums")
|
||||
|| lower.contains("no sha256sums")
|
||||
{
|
||||
tr("This release has no file for your system yet. Download the new version from the website.").to_owned()
|
||||
} else if lower.contains("permission denied")
|
||||
|| lower.contains("no space")
|
||||
|| lower.contains("read-only")
|
||||
|| lower.contains("os error 13")
|
||||
|| lower.contains("os error 28")
|
||||
|| lower.contains("os error 30")
|
||||
{
|
||||
tr("The file could not be saved: no permission to write there, or the disk is full.")
|
||||
.to_owned()
|
||||
} else {
|
||||
tr("The new version could not be downloaded: no connection to the server. Check the internet and try again.").to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl UpdateDialog {
|
||||
pub fn from_env() -> UpdateDialog {
|
||||
let auto = std::env::var("CP_UPDATE_OPEN").ok().map(|v| v == "start");
|
||||
UpdateDialog {
|
||||
auto,
|
||||
..UpdateDialog::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The update is under way or done (its button stays even for a skipped version).
|
||||
pub fn active(&self) -> bool {
|
||||
self.job.is_some() || matches!(self.result, Some(Ok(_)))
|
||||
}
|
||||
|
||||
/// What the button next to Settings says: the offer, the download's progress, or
|
||||
/// that the new version waits for a restart / for its command.
|
||||
pub fn badge(&self, release: &Release) -> String {
|
||||
if let Some((size, job)) = &self.job {
|
||||
let pct = if *size > 0 {
|
||||
(100 * job.progress() as u64 / size).min(100)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
return trf("⬇ {v}: {p} %", &[("v", &release.version), ("p", &pct)]);
|
||||
}
|
||||
match &self.result {
|
||||
Some(Ok(Applied::Restart(_))) => trf("⟳ Restart for {v}", &[("v", &release.version)]),
|
||||
Some(Ok(Applied::Command { .. } | Applied::DiskImageOpened(_))) => {
|
||||
trf("⬆ {v}: install", &[("v", &release.version)])
|
||||
}
|
||||
_ => trf("⬆ Update {v}", &[("v", &release.version)]),
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&mut self, release: &Release, kind: &Install, ctx: &egui::Context) {
|
||||
let size = release.asset_for(kind).map_or(0, |a| a.size);
|
||||
let (r, k) = (release.clone(), kind.clone());
|
||||
let now = ctx.input(|i| i.time);
|
||||
self.result = None;
|
||||
self.job = Background::spawn(ctx, now, move |progress, cancel| {
|
||||
Some(update::update(&r, &k, progress, cancel))
|
||||
})
|
||||
.map(|j| (size, j));
|
||||
}
|
||||
|
||||
pub fn show(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
release: Option<&Release>,
|
||||
kind: &Install,
|
||||
) -> Vec<UpdateEvent> {
|
||||
let mut events = Vec::new();
|
||||
if let Some((_, job)) = &self.job
|
||||
&& let Some(r) = job.poll()
|
||||
{
|
||||
self.result = Some(r.unwrap_or_else(|| Err("cancelled".into())));
|
||||
self.job = None;
|
||||
}
|
||||
if self.job.is_some() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(250));
|
||||
}
|
||||
let Some(release) = release else {
|
||||
return events;
|
||||
};
|
||||
if let Some(start) = self.auto.take() {
|
||||
self.open = true;
|
||||
if start {
|
||||
self.start(release, kind, ctx);
|
||||
}
|
||||
}
|
||||
if !self.open {
|
||||
return events;
|
||||
}
|
||||
let mut open = true;
|
||||
egui::Window::new(tr("ChessPenguin update"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
.default_width(560.0)
|
||||
.max_width(620.0)
|
||||
.pivot(egui::Align2::CENTER_TOP)
|
||||
.default_pos(ctx.content_rect().center_top() + egui::vec2(0.0, 110.0))
|
||||
.show(ctx, |ui| self.body(ui, release, kind, &mut events));
|
||||
if !open {
|
||||
// A running download goes on; the button next to Settings shows it.
|
||||
self.open = false;
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn body(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
release: &Release,
|
||||
kind: &Install,
|
||||
events: &mut Vec<UpdateEvent>,
|
||||
) {
|
||||
let asset = release.asset_for(kind);
|
||||
// Running.
|
||||
if let Some((size, job)) = &self.job {
|
||||
heading(ui, release);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Spinner::new());
|
||||
ui.label(trf(
|
||||
"Downloading… {done} of {total} MB",
|
||||
&[
|
||||
("done", &format!("{:.0}", job.progress() as f64 / 1e6)),
|
||||
("total", &mb(*size)),
|
||||
],
|
||||
));
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
job.cancel();
|
||||
}
|
||||
});
|
||||
if *size > 0 {
|
||||
ui.add(egui::ProgressBar::new(
|
||||
(job.progress() as f32 / *size as f32).min(1.0),
|
||||
));
|
||||
}
|
||||
ui.label(RichText::new(tr("You can close this window: the download goes on.")).weak());
|
||||
return;
|
||||
}
|
||||
// Finished.
|
||||
match &self.result {
|
||||
Some(Ok(Applied::Restart(exe))) => {
|
||||
ui.label(
|
||||
RichText::new(trf("Version {v} is installed", &[("v", &release.version)]))
|
||||
.heading(),
|
||||
);
|
||||
ui.label(tr("It starts after a restart. Unsaved games are asked about first; databases and settings stay as they are."));
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
if primary(ui, tr("⟳ Restart now")).clicked() {
|
||||
events.push(UpdateEvent::Restart(exe.clone()));
|
||||
}
|
||||
if ui.button(tr("Later")).clicked() {
|
||||
self.open = false;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
Some(Ok(Applied::DiskImageOpened(_))) => {
|
||||
ui.label(RichText::new(tr("The disk image is open")).heading());
|
||||
ui.label(tr(
|
||||
"1. Quit ChessPenguin (the button below): a running app cannot be replaced.",
|
||||
));
|
||||
ui.label(tr("2. In the window of the disk image, drag the ChessPenguin icon onto the Applications folder and choose Replace."));
|
||||
ui.label(tr("3. Start ChessPenguin from Applications."));
|
||||
ui.add_space(6.0);
|
||||
if primary(ui, tr("Quit ChessPenguin")).clicked() {
|
||||
events.push(UpdateEvent::Quit);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Some(Ok(Applied::Command { file, command })) => {
|
||||
ui.label(RichText::new(tr("The new version is downloaded")).heading());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let dir = file
|
||||
.parent()
|
||||
.and_then(|d| d.file_name())
|
||||
.map(|n| format!("«{}»", n.to_string_lossy()))
|
||||
.unwrap_or_default();
|
||||
ui.label(trf("The file is in the folder {dir}.", &[("dir", &dir)]));
|
||||
if ui.link(tr("Open the folder")).clicked()
|
||||
&& let Some(d) = file.parent()
|
||||
{
|
||||
open_folder(d);
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.label(tr("1. Copy the command."));
|
||||
command_line(ui, command, events);
|
||||
if matches!(kind, Install::Flatpak) {
|
||||
ui.label(tr("2. Open the Terminal of your system (not inside the Flatpak), paste the command (Ctrl+Shift+V) and press Enter."));
|
||||
} else {
|
||||
ui.label(tr("2. Open the Terminal, paste the command (Ctrl+Shift+V) and press Enter. It asks for your password: while you type it nothing is shown, that is normal."));
|
||||
}
|
||||
ui.label(tr(
|
||||
"3. When the command has finished, start ChessPenguin again.",
|
||||
));
|
||||
ui.add_space(6.0);
|
||||
if ui.button(tr("Quit ChessPenguin")).clicked() {
|
||||
events.push(UpdateEvent::Quit);
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
heading(ui, release);
|
||||
let mut retry = false;
|
||||
if let Some(Err(e)) = &self.result {
|
||||
ui.label(RichText::new(failure_text(e)).color(ui.visuals().warn_fg_color));
|
||||
if e != "cancelled" && e != "checksum" {
|
||||
egui::CollapsingHeader::new(tr("Details"))
|
||||
.id_salt("update_details")
|
||||
.show(ui, |ui| {
|
||||
ui.label(RichText::new(e).monospace().weak());
|
||||
});
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
retry = true;
|
||||
}
|
||||
let action = |retry: bool, first: &'static str| if retry { tr("Try again") } else { first };
|
||||
// What to do.
|
||||
match (kind, asset) {
|
||||
(Install::Aur, _) => {
|
||||
ui.label(tr(
|
||||
"ChessPenguin is installed from the AUR. Update it as usual, for example:",
|
||||
));
|
||||
command_line(ui, update::AUR_COMMAND, events);
|
||||
ui.label(RichText::new(trf("or: {c}", &[("c", &update::AUR_COMMAND_PARU)])).weak());
|
||||
}
|
||||
(k, Some(a)) if k.replaces_itself() => {
|
||||
ui.label(trf(
|
||||
"ChessPenguin downloads the new version ({mb} MB), checks it and puts it in place of this one. Databases, games and settings are not touched.",
|
||||
&[("mb", &mb(a.size))],
|
||||
));
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
if primary(ui, action(retry, tr("⬆ Update"))).clicked() {
|
||||
self.start(release, k, ui.ctx());
|
||||
}
|
||||
self.not_now(ui, release, events);
|
||||
});
|
||||
}
|
||||
(Install::Mac, Some(a)) => {
|
||||
ui.label(trf(
|
||||
"ChessPenguin downloads the disk image ({mb} MB), checks it and opens it; then you drag the app over the old one, as when you installed it.",
|
||||
&[("mb", &mb(a.size))],
|
||||
));
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
if primary(ui, action(retry, tr("⬇ Download"))).clicked() {
|
||||
self.start(release, kind, ui.ctx());
|
||||
}
|
||||
self.not_now(ui, release, events);
|
||||
});
|
||||
}
|
||||
(k, Some(a)) => {
|
||||
ui.label(trf(
|
||||
"ChessPenguin was installed through the system (its package manager), so it cannot replace itself. It downloads the new version ({mb} MB) into Downloads; to install it you run one command in a terminal, which you can copy.",
|
||||
&[("mb", &mb(a.size))],
|
||||
));
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
if primary(ui, action(retry, tr("⬇ Download"))).clicked() {
|
||||
self.start(release, k, ui.ctx());
|
||||
}
|
||||
self.not_now(ui, release, events);
|
||||
});
|
||||
}
|
||||
(Install::Mac | Install::Windows(_), None) => {
|
||||
ui.label(tr("This release has no file for your system yet. Download the new version from the website:"));
|
||||
ui.hyperlink_to(update::DOWNLOAD_PAGE, update::DOWNLOAD_PAGE);
|
||||
}
|
||||
_ => {
|
||||
ui.label(tr("Download the new version from the website:"));
|
||||
ui.hyperlink_to(update::DOWNLOAD_PAGE, update::DOWNLOAD_PAGE);
|
||||
}
|
||||
}
|
||||
if !matches!(kind, Install::Other) {
|
||||
ui.add_space(4.0);
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"Installation: {kind}",
|
||||
&[("kind", &install_name(kind))],
|
||||
))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// "Not now" and "Skip this version".
|
||||
fn not_now(&mut self, ui: &mut Ui, release: &Release, events: &mut Vec<UpdateEvent>) {
|
||||
if ui.button(tr("Not now")).clicked() {
|
||||
self.open = false;
|
||||
}
|
||||
if ui
|
||||
.link(tr("Skip this version"))
|
||||
.on_hover_text(tr(
|
||||
"The button next to Settings is hidden until the next version; Settings → About still offers this one",
|
||||
))
|
||||
.clicked()
|
||||
{
|
||||
events.push(UpdateEvent::Skip(release.version.clone()));
|
||||
self.open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// "Version 0.8.0 is out" with the current version and the release notes under it.
|
||||
fn heading(ui: &mut Ui, release: &Release) {
|
||||
ui.label(RichText::new(trf("Version {v} is out", &[("v", &release.version)])).heading());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"You have {old}",
|
||||
&[("old", &env!("CARGO_PKG_VERSION"))],
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
ui.label(RichText::new("·").weak());
|
||||
ui.hyperlink_to(tr("What's new"), &release.page);
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
|
||||
/// The main button of the window: filled, a little taller.
|
||||
fn primary(ui: &mut Ui, label: &str) -> egui::Response {
|
||||
ui.add(
|
||||
egui::Button::new(RichText::new(label).strong())
|
||||
.fill(ui.visuals().selection.bg_fill)
|
||||
.min_size(egui::vec2(0.0, 30.0)),
|
||||
)
|
||||
}
|
||||
|
||||
/// A command in a monospace box with a Copy button beside it.
|
||||
fn command_line(ui: &mut Ui, command: &str, events: &mut Vec<UpdateEvent>) {
|
||||
ui.horizontal(|ui| {
|
||||
let width = (ui.available_width() - 110.0).max(200.0);
|
||||
egui::Frame::new()
|
||||
.fill(ui.visuals().extreme_bg_color)
|
||||
.inner_margin(egui::Margin::symmetric(8, 6))
|
||||
.corner_radius(4.0)
|
||||
.show(ui, |ui| {
|
||||
ui.set_max_width(width);
|
||||
ui.add(egui::Label::new(RichText::new(command).monospace()).wrap());
|
||||
});
|
||||
if primary(ui, tr("Copy")).clicked() {
|
||||
events.push(UpdateEvent::CopyText(command.to_owned()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Shows a folder in the file manager.
|
||||
fn open_folder(dir: &std::path::Path) {
|
||||
let program = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let _ = std::process::Command::new(program).arg(dir).spawn();
|
||||
}
|
||||
|
|
@ -32,3 +32,10 @@ pub fn notes_button(ui: &mut egui::Ui, notes: usize) -> egui::Response {
|
|||
ui.add(egui::Button::new(egui::RichText::new(format!("ℹ {notes}")).weak().small()).frame(false))
|
||||
.on_hover_text(crate::i18n::tr("Import notes"))
|
||||
}
|
||||
|
||||
/// "⬆ Update 0.8.0" (or the download's progress, "⟳ Restart for 0.8.0"): opens the
|
||||
/// update window.
|
||||
pub fn update_button(ui: &mut egui::Ui, label: &str) -> egui::Response {
|
||||
ui.button(egui::RichText::new(label).color(ui.visuals().hyperlink_color))
|
||||
.on_hover_text(crate::i18n::tr("A new version of ChessPenguin is out"))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i
|
|||
| `app.rs` | Состояние верхнего уровня: библиотека ⇄ партия, настройки, движок, фоновые диалоги (rfd в отдельных потоках), подтверждение закрытия изменённой партии |
|
||||
| `library.rs` | Полка баз, фоновое открытие через `chess_import::open` (PGN, ChessBase, архивы; прогресс, отмена), формат и «Замечания импорта» по каждой базе, таблица с поиском, сортировкой, клавиатурой |
|
||||
| `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху»; при открытой доске в фоне строится, чего не хватает для быстрого поиска (`Base::prepare`: свой ускоритель без пригодного `.cbb`, дебютный индекс при достаточной памяти; каталог кэша `boosters/`) со строкой прогресса над доской |
|
||||
| `update.rs` | Обновления: проверка последнего выпуска (GitHub API, при старте, отключается в «О программе»), вид установки (`detect`: zip на Windows, `.app` на macOS, AppImage — только если исполняемый файл внутри `$APPDIR`, архив tar.gz по соседним файлам, `/usr/bin` → pacman/dpkg/rpm, Flatpak по `FLATPAK_ID`, иначе «другое»), выбор файла выпуска по окончанию имени, загрузка с проверкой SHA-256 из `SHA256SUMS.txt`, замена исполняемого файла (`replace_file`: копия рядом и одно переименование; на Windows работающий `.exe` переименовывается в `.old`, удаляется при следующем запуске), команды для пакетов (`cd <папка> && sudo apt/dnf/zypper/pacman … ./файл`, все слова в одинарных кавычках, если в них есть что-то кроме безопасных символов), папка «Загрузки» (XDG, затем `~/.config/user-dirs.dirs` пользователя — у Flatpak своя папка настроек, затем `~/Downloads`, затем домашняя). Тесты: версии, файлы для каждого вида, команды и экранирование (через `sh`), замена работающего исполняемого файла (CI на Windows и macOS тоже), обновление архива из локального «выпуска» |
|
||||
| `update_ui.rs` | Окно «Обновление ChessPenguin»: «Вышла версия X · У вас Y · Что нового», один сценарий на вид установки с главной кнопкой, «Не сейчас», «Пропустить эту версию» (`skipped_version`); скачивание с прогрессом (окно можно закрыть, кнопка у «Настроек» показывает проценты); итог: «Перезапустить сейчас / Позже», шаги для macOS с «Закрыть ChessPenguin», команда с «Копировать», «Открыть папку» и шагами для пакетов; ошибки понятными словами, исходный текст — в «Подробностях». Перезапуск: `request_close(QuitApp)`, в `finish_close` настройки сохраняются, новый процесс запускается без переменных `CP_*`; отмена вопроса о партиях отменяет и перезапуск |
|
||||
| `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой |
|
||||
| `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура |
|
||||
| `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках |
|
||||
|
|
@ -42,7 +44,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe
|
|||
```
|
||||
|
||||
`CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии,
|
||||
`CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN).
|
||||
`CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN).
|
||||
|
||||
## Языки
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ finish-args:
|
|||
- --socket=pulseaudio
|
||||
# PGN files and UCI engine executables live in the user's home.
|
||||
- --filesystem=home
|
||||
# The update check (GitHub) and the user's games from Lichess and Chess.com.
|
||||
- --share=network
|
||||
build-options:
|
||||
append-path: /usr/lib/sdk/rust-stable/bin
|
||||
build-args:
|
||||
|
|
|
|||
|
|
@ -43,6 +43,11 @@
|
|||
<category>BoardGame</category>
|
||||
</categories>
|
||||
<releases>
|
||||
<release version="0.7.1" date="2026-10-20">
|
||||
<description>
|
||||
<p>Updates: ChessPenguin tells when a new version is out and updates itself where it can (Windows, AppImage, the Linux archive); for packages it downloads the new one and shows the command that installs it.</p>
|
||||
</description>
|
||||
</release>
|
||||
<release version="0.7.0" date="2026-10-20">
|
||||
<description>
|
||||
<p>The «Reference» tab of a game: what was played in the current position in a database of the shelf — the moves with their statistics and the strongest games, the novelty of the game, and its copy in the database. The board always keeps the full height of the window.</p>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue