From 384aaf78c6662dd15cf12e19c4f0d7c6e194d28f Mon Sep 17 00:00:00 2001 From: yann64 Date: Sat, 28 Nov 2026 19:54:04 +0100 Subject: [PATCH] =?UTF-8?q?gtk:=20interface=20GTK4,=20pr=C3=A9f=C3=A9rence?= =?UTF-8?q?s,=20versions,=20traductions,=20licence=20MIT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - interface gtkmm-4 : véhicules, ajout par VIN, mises à jour, dossier, téléchargement avec reprise et arrêt, choix de la clé, confirmation, écriture avec progression, fin avec guide d'installation ; travail dans un thread, résultats renvoyés via Glib::Dispatcher - préférences : dossier de téléchargement, langue (système par défaut), recherche automatique de nouvelle version d'OpenPU - recherche de nouvelle version (releases GitHub, format tags Gitea accepté) avec ouverture de la page dans le navigateur ; openpu-cli app-update - versions : project(VERSION) + git describe régénéré à chaque build, openpu-cli --version, À propos, User-Agent, CHANGELOG, tools/release.sh (étiquette annotée, push vers tous les remotes, release GitHub) - traductions gettext : textes anglais, fr.po complet (96 chaînes), extracteur de secours sans xgettext - core : module job (téléchargement licence/fw/carte), liens des guides PDF, ordre des véhicules conservé (ordered_json) - licence MIT (LICENSE, en-têtes SPDX) ; dépôt principal sur GitHub - validé dans WSLg : parcours complet jusqu'à l'écriture d'une clé loop (FAT32 propre, fichiers téléchargés supprimés) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar --- .clang-tidy | 3 + CHANGELOG.md | 42 + CMakeLists.txt | 5 + LICENSE | 21 + README.md | 52 +- cmake/GitVersion.cmake | 66 ++ po/CMakeLists.txt | 28 + po/LINGUAS | 1 + po/fr.po | 316 ++++++ po/openpu.pot | 401 +++++++ src/cli/main.cpp | 25 +- src/core/CMakeLists.txt | 18 +- src/core/api_client.cpp | 1 + src/core/app_update.cpp | 125 +++ src/core/archive.cpp | 1 + src/core/curl_transport.cpp | 8 +- src/core/download.cpp | 1 + src/core/http.cpp | 1 + src/core/include/openpu/api_client.hpp | 1 + src/core/include/openpu/app_update.hpp | 63 ++ src/core/include/openpu/archive.hpp | 1 + src/core/include/openpu/cancel.hpp | 1 + src/core/include/openpu/download.hpp | 1 + src/core/include/openpu/format.hpp | 38 + src/core/include/openpu/http.hpp | 1 + src/core/include/openpu/job.hpp | 59 + src/core/include/openpu/models.hpp | 1 + src/core/include/openpu/storage.hpp | 2 + src/core/include/openpu/usb.hpp | 1 + src/core/include/openpu/version.hpp | 12 + src/core/include/openpu/vin.hpp | 1 + src/core/job.cpp | 130 +++ src/core/models.cpp | 1 + src/core/storage.cpp | 6 +- src/core/usb.cpp | 1 + src/core/usb_none.cpp | 1 + src/core/usb_udisks.cpp | 1 + src/core/vin.cpp | 1 + src/ui-gtk/CMakeLists.txt | 17 + src/ui-gtk/io.github.openpu.OpenPU.desktop | 12 + src/ui-gtk/main.cpp | 30 + src/ui-gtk/main_window.cpp | 1135 ++++++++++++++++++++ src/ui-gtk/main_window.hpp | 141 +++ src/ui-gtk/ui_queue.hpp | 43 + tests/CMakeLists.txt | 1 + tests/main.cpp | 1 + tests/test_api_client.cpp | 1 + tests/test_app_update.cpp | 91 ++ tests/test_archive.cpp | 1 + tests/test_download.cpp | 1 + tests/test_http.cpp | 1 + tests/test_models.cpp | 1 + tests/test_storage.cpp | 6 + tests/test_usb.cpp | 29 + tests/test_util.hpp | 1 + tests/test_vin.cpp | 1 + tools/asar_extract.py | 1 + tools/check.sh | 15 +- tools/dev-polkit.sh | 1 + tools/e2e-usb.sh | 1 + tools/extract_strings.py | 36 + tools/release.sh | 44 + 62 files changed, 3029 insertions(+), 20 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 cmake/GitVersion.cmake create mode 100644 po/CMakeLists.txt create mode 100644 po/LINGUAS create mode 100644 po/fr.po create mode 100644 po/openpu.pot create mode 100644 src/core/app_update.cpp create mode 100644 src/core/include/openpu/app_update.hpp create mode 100644 src/core/include/openpu/format.hpp create mode 100644 src/core/include/openpu/job.hpp create mode 100644 src/core/include/openpu/version.hpp create mode 100644 src/core/job.cpp create mode 100644 src/ui-gtk/CMakeLists.txt create mode 100644 src/ui-gtk/io.github.openpu.OpenPU.desktop create mode 100644 src/ui-gtk/main.cpp create mode 100644 src/ui-gtk/main_window.cpp create mode 100644 src/ui-gtk/main_window.hpp create mode 100644 src/ui-gtk/ui_queue.hpp create mode 100644 tests/test_app_update.cpp create mode 100644 tools/extract_strings.py create mode 100644 tools/release.sh diff --git a/.clang-tidy b/.clang-tidy index 17e9979..46e7642 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -20,4 +20,7 @@ Checks: > WarningsAsErrors: '' HeaderFilterRegex: '.*/src/.*' FormatStyle: none +CheckOptions: + # A dialog dismissed by the user ends in an intentionally empty catch marked with this word. + bugprone-empty-catch.IgnoreCatchWithKeywords: '@TODO;@FIXME;dismissed' ... diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5a5a459 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +Format: [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/). Versions follow +[Semantic Versioning](https://semver.org/lang/fr/): `0.x` until the Linux and Haiku applications are +complete; every release is an annotated git tag `vX.Y.Z` (see `tools/release.sh`). + +## [Unreleased] + +### Ajouté +- Interface graphique GTK4 (gtkmm) : véhicules, ajout par VIN, mises à jour disponibles, choix du + dossier, téléchargement avec reprise, choix de la clé USB, écriture, guide d'installation. +- Versionnage : version CMake + `git describe` à chaque compilation, `openpu-cli --version`, + boîte « À propos », User-Agent `OpenPU/`, script `tools/release.sh`. +- Infrastructure de traduction gettext (textes sources en anglais, français fourni). +- Liens vers les guides d'installation officiels (PDF) en français et en anglais. +- Préférences : dossier de téléchargement, langue (langue du système par défaut), recherche + automatique d'une nouvelle version d'OpenPU au démarrage. +- Recherche d'une nouvelle version d'OpenPU (releases GitHub) : proposition d'ouvrir la page de + téléchargement dans le navigateur ; `openpu-cli app-update`. +- Licence MIT (`LICENSE`, en-têtes SPDX). + +### Prévu +- Paquets Linux `.deb`, Flatpak et AppImage ; paquet Haiku `.hpkg`. + +### Modifié +- Le dépôt principal est désormais https://github.com/yann64/openpu (Gitea reste un miroir). +- `vehicles.json` garde l'ordre d'ajout des véhicules. + +## [0.1.0] - 2026-11-28 + +### Ajouté +- Analyse de « Peugeot Update » 1.6.1 (`docs/analysis/`). +- `libopenpu` : client de l'API Majestic (VIN, calculateurs, mises à jour), téléchargement avec + reprise (Range), licence (placeholder vide de Majestic géré), archives tar (vérification, + extraction sécurisée sans `UpdateInfo.xml`), réglages et véhicules compatibles avec l'app + officielle, USB Linux via UDisks2 (MBR + FAT32, montage, éjection). +- `openpu-cli` : `check`, `download`, `verify`, `extract`, `usb-list`, `write-usb`, `write-dir`. +- Qualité : tests doctest, ASan/UBSan, valgrind, clang-tidy, cppcheck (`tools/check.sh`), test USB + de bout en bout sur image loop (`tools/e2e-usb.sh`). + +[Unreleased]: https://github.com/yann64/openpu/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/yann64/openpu/releases/tag/v0.1.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index 3651948..cb857b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,6 +40,11 @@ if(OPENPU_BUILD_CLI) add_subdirectory(src/cli) endif() +if(OPENPU_UI_GTK) + add_subdirectory(src/ui-gtk) + add_subdirectory(po) +endif() + if(OPENPU_BUILD_TESTS) enable_testing() add_subdirectory(tests) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..65601e4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 yann64 and the OpenPU contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index eb0a17b..98bc3be 100644 --- a/README.md +++ b/README.md @@ -8,15 +8,21 @@ C'est une alternative à l'application officielle « Peugeot Update » (Windows/ > Projet indépendant, sans lien avec Stellantis ni Peugeot. Les noms cités sont des marques > de leurs propriétaires respectifs. +- Dépôt : https://github.com/yann64/openpu (miroir : https://git.barbel.synology.me/yann64/opu) +- Licence : [MIT](LICENSE) +- Historique des versions : [CHANGELOG.md](CHANGELOG.md) + ## État - [x] Analyse de l'application existante : voir [`docs/analysis/`](docs/analysis/) -- [x] Cœur C++ : VIN, API Majestic, modèles, CLI `check` -- [x] Cœur C++ : téléchargement avec reprise, licence, tar (vérif + extraction), réglages et véhicules -- [x] USB Linux (UDisks2 : liste, MBR + FAT32, montage, éjection) + écriture de la mise à jour +- [x] Cœur C++ : VIN, API Majestic, téléchargement avec reprise, licence, tar, réglages, véhicules +- [x] USB Linux (UDisks2 : liste, MBR + FAT32, montage, éjection) et écriture de la mise à jour +- [x] CLI `openpu-cli` +- [x] UI GTK4 (Linux) : parcours complet, préférences, recherche de nouvelle version +- [x] Versions (`--version`, À propos, étiquettes `vX.Y.Z`, releases GitHub) +- [x] Traductions gettext (anglais, français) - [ ] USB Haiku (Storage Kit) -- [ ] UI GTK4 (Linux) - [ ] UI Haiku -- [ ] Paquets `.deb`, Flatpak et `.hpkg` +- [ ] Paquets Linux : `.deb`, Flatpak et AppImage ; Haiku : `.hpkg` ## Architecture ``` @@ -24,21 +30,43 @@ src/core libopenpu : API Majestic, téléchargement avec reprise, tar, USB src/cli openpu-cli src/ui-gtk interface gtkmm-4 src/ui-haiku interface BeAPI +po/ traductions (gettext) ``` -## Outils -- `tools/asar_extract.py` : extracteur asar minimal, en lecture seule, pour étudier l'app de référence. - Les sources extraites restent **hors du dépôt**. - ## Compiler (Linux / WSL) ```sh sudo apt install build-essential cmake ninja-build pkg-config libcurl4-openssl-dev \ - libarchive-dev nlohmann-json3-dev doctest-dev libglib2.0-dev valgrind clang-tidy cppcheck -cmake --preset debug && cmake --build --preset debug && ctest --preset debug -../build-openpu/debug/src/cli/openpu-cli check VF3XXXXXXXXXXXXXX + libarchive-dev nlohmann-json3-dev doctest-dev libglib2.0-dev libgtkmm-4.0-dev gettext \ + valgrind clang-tidy cppcheck +cmake --preset debug -DOPENPU_UI_GTK=ON && cmake --build --preset debug && ctest --preset debug +../build-openpu/debug/src/ui-gtk/openpu # interface graphique +../build-openpu/debug/src/cli/openpu-cli --version tools/check.sh # tests + ASan/UBSan + valgrind + clang-tidy + cppcheck # test USB de bout en bout sur une image loop (paquets udisks2 dosfstools mtools) sudo tools/dev-polkit.sh install # WSL/CI uniquement : polkit sans agent tools/e2e-usb.sh ../build-openpu/debug/src/cli/openpu-cli --license X.key update.tar ``` +Depuis l'arborescence de compilation, `OPENPU_LOCALEDIR=../build-openpu/debug/locale` permet à +l'interface de trouver ses traductions. + +## Versions +- La version de référence est `project(openpu VERSION x.y.z)` dans `CMakeLists.txt`. À chaque + compilation, `git describe` produit la description affichée (par exemple `0.2.0+3.g1a2b3c4.dirty`). +- Une version publiée est une étiquette annotée `vX.Y.Z` accompagnée d'une release GitHub, que + l'application consulte pour proposer les nouvelles versions. Le script + `tools/release.sh X.Y.Z` monte la version, date le CHANGELOG, commite, étiquette, pousse vers + tous les remotes et crée la release. + +## Traductions +Les textes sources sont en anglais et la traduction passe par gettext (`po/.po`). Pour +ajouter une langue : +1. mettre à jour le modèle avec `cmake --build --target pot`, ou + `python3 tools/extract_strings.py po/openpu.pot src/ui-gtk/main_window.cpp` si gettext n'est + pas installé ; +2. copier `po/openpu.pot` en `po/.po` et le traduire ; +3. ajouter la langue dans `po/LINGUAS` et dans la liste du dialogue Préférences. + +## Outils +- `tools/asar_extract.py` : extracteur asar minimal, en lecture seule, pour étudier l'app de référence. + Les sources extraites restent **hors du dépôt**. diff --git a/cmake/GitVersion.cmake b/cmake/GitVersion.cmake new file mode 100644 index 0000000..88cc094 --- /dev/null +++ b/cmake/GitVersion.cmake @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: MIT +# Run at build time (cmake -P): writes ${OUTPUT} with the release version (from project()) and the +# build description from `git describe`, rewriting the file only when it changes. +# +# Inputs: SOURCE_DIR, OUTPUT, VERSION (x.y.z), GIT_EXECUTABLE (may be empty) +# +# Description examples: +# 0.2.0 built exactly from tag v0.2.0, clean tree +# 0.2.0+3.g1a2b3c4 3 commits after v0.2.0 +# 0.2.0+3.g1a2b3c4.dirty ... with uncommitted changes +# 0.2.0 no git (release tarball, HaikuPorts recipe) + +set(description "${VERSION}") +if(GIT_EXECUTABLE AND EXISTS "${SOURCE_DIR}/.git") + execute_process( + COMMAND "${GIT_EXECUTABLE}" describe --tags --long --dirty --match "v[0-9]*" + WORKING_DIRECTORY "${SOURCE_DIR}" + OUTPUT_VARIABLE describe + RESULT_VARIABLE rc + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + # v0.2.0-3-g1a2b3c4[-dirty] + if(rc EQUAL 0 AND describe MATCHES "^v([0-9]+\\.[0-9]+\\.[0-9]+)-([0-9]+)-(g[0-9a-f]+)(-dirty)?$") + set(tag_version "${CMAKE_MATCH_1}") + set(distance "${CMAKE_MATCH_2}") + set(hash "${CMAKE_MATCH_3}") + set(dirty "${CMAKE_MATCH_4}") + if(NOT tag_version VERSION_EQUAL VERSION AND distance EQUAL 0) + message(WARNING "tag v${tag_version} does not match project(VERSION ${VERSION})") + endif() + if(NOT distance EQUAL 0) + string(APPEND description "+${distance}.${hash}") + endif() + if(dirty) + if(distance EQUAL 0) + string(APPEND description "+${hash}") + endif() + string(APPEND description ".dirty") + endif() + else() + # No tag yet: use the commit hash only. + execute_process( + COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD + WORKING_DIRECTORY "${SOURCE_DIR}" + OUTPUT_VARIABLE hash RESULT_VARIABLE rc + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + if(rc EQUAL 0) + string(APPEND description "+g${hash}") + endif() + endif() +endif() + +set(content "// Generated by cmake/GitVersion.cmake — do not edit. +#include \"openpu/version.hpp\" + +namespace openpu { +const char* version() noexcept { return \"${VERSION}\"; } +const char* versionDescription() noexcept { return \"${description}\"; } +} // namespace openpu +") + +if(EXISTS "${OUTPUT}") + file(READ "${OUTPUT}" previous) +endif() +if(NOT previous STREQUAL content) + file(WRITE "${OUTPUT}" "${content}") +endif() diff --git a/po/CMakeLists.txt b/po/CMakeLists.txt new file mode 100644 index 0000000..c440ee9 --- /dev/null +++ b/po/CMakeLists.txt @@ -0,0 +1,28 @@ +# Translations (gettext). Source strings are English; add a language by adding .po and +# listing it in LINGUAS. +find_package(Gettext) +if(NOT GETTEXT_FOUND) + message(WARNING "gettext (msgfmt) not found: translations are not built") + return() +endif() +file(STRINGS LINGUAS OPENPU_LINGUAS REGEX "^[^#]") +foreach(lang IN LISTS OPENPU_LINGUAS) + set(mo ${CMAKE_BINARY_DIR}/locale/${lang}/LC_MESSAGES/openpu.mo) + add_custom_command(OUTPUT ${mo} + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/locale/${lang}/LC_MESSAGES + COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} --check -o ${mo} ${CMAKE_CURRENT_SOURCE_DIR}/${lang}.po + DEPENDS ${lang}.po) + list(APPEND OPENPU_MO_FILES ${mo}) + install(FILES ${mo} DESTINATION ${CMAKE_INSTALL_LOCALEDIR}/${lang}/LC_MESSAGES) +endforeach() +add_custom_target(translations ALL DEPENDS ${OPENPU_MO_FILES}) + +# `cmake --build . --target pot` refreshes the template from the sources. +find_program(XGETTEXT xgettext) +if(XGETTEXT) + add_custom_target(pot + COMMAND ${XGETTEXT} --keyword=_ --keyword=N_ --from-code=UTF-8 --package-name=openpu + --add-comments=TRANSLATORS -o ${CMAKE_CURRENT_SOURCE_DIR}/openpu.pot + ${PROJECT_SOURCE_DIR}/src/ui-gtk/main_window.cpp + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) +endif() diff --git a/po/LINGUAS b/po/LINGUAS new file mode 100644 index 0000000..527e861 --- /dev/null +++ b/po/LINGUAS @@ -0,0 +1 @@ +fr diff --git a/po/fr.po b/po/fr.po new file mode 100644 index 0000000..5948fb4 --- /dev/null +++ b/po/fr.po @@ -0,0 +1,316 @@ +# French translation of OpenPU. +msgid "" +msgstr "" +"Project-Id-Version: openpu\n" +"Language: fr\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +msgid "Crony (navigation)" +msgstr "Crony (avec navigation)" + +msgid "Crony (no navigation)" +msgstr "Crony (sans navigation)" + +msgid "unknown head unit" +msgstr "autoradio inconnu" + +msgid "version %1, %2" +msgstr "version %1, %2" + +msgid "The update server cannot be reached. Check your Internet connection." +msgstr "Le serveur de mises à jour est injoignable. Vérifiez votre connexion Internet." + +msgid "The update server returned an error. Try again later." +msgstr "Le serveur de mises à jour a renvoyé une erreur. Réessayez plus tard." + +msgid "This VIN is not valid." +msgstr "Ce VIN n'est pas valide." + +msgid "Your saved data cannot be read" +msgstr "Vos données enregistrées sont illisibles" + +msgid "Back" +msgstr "Retour" + +msgid "About OpenPU" +msgstr "À propos d'OpenPU" + +msgid "" +"Download Peugeot head unit updates (system and navigation map) and prepare the USB stick, on " +"Linux and Haiku.\n" +"\n" +"Independent project, not affiliated with Stellantis or Peugeot." +msgstr "" +"Téléchargez les mises à jour de l'autoradio Peugeot (système et cartographie) et préparez la " +"clé USB, sous Linux et Haiku.\n" +"\n" +"Projet indépendant, sans lien avec Stellantis ni Peugeot." + +msgid "Source code" +msgstr "Code source" + +msgid "Cannot save the vehicle list" +msgstr "Impossible d'enregistrer la liste des véhicules" + +msgid "My vehicles" +msgstr "Mes véhicules" + +msgid "Add your vehicle with its VIN (17 characters, on the registration document, field E)." +msgstr "Ajoutez votre véhicule avec son VIN (17 caractères, sur le certificat d'immatriculation, champ E)." + +msgid "Add a vehicle" +msgstr "Ajouter un véhicule" + +msgid "Remove" +msgstr "Supprimer" + +msgid "Check for updates" +msgstr "Rechercher les mises à jour" + +msgid "download not finished" +msgstr "téléchargement inachevé" + +msgid "Remove %1?" +msgstr "Supprimer %1 ?" + +msgid "Downloaded files that were not written to a USB stick yet are deleted too." +msgstr "Les fichiers téléchargés qui n'ont pas encore été copiés sur une clé USB seront aussi supprimés." + +msgid "Cancel" +msgstr "Annuler" + +msgid "" +"The VIN (vehicle identification number) is written in field E of the registration document and " +"at the bottom of the windscreen." +msgstr "" +"Le VIN (numéro d'identification du véhicule) figure au champ E du certificat d'immatriculation " +"et en bas du pare-brise." + +msgid "VIN" +msgstr "VIN" + +msgid "Name" +msgstr "Nom" + +msgid "e.g. 208 or Family car" +msgstr "par ex. 208 ou Voiture familiale" + +msgid "Add" +msgstr "Ajouter" + +msgid "A VIN has 17 characters and starts with VF3 or VR3." +msgstr "Un VIN comporte 17 caractères et commence par VF3 ou VR3." + +msgid "Checking the vehicle…" +msgstr "Vérification du véhicule…" + +msgid "This vehicle is unknown to the update service." +msgstr "Ce véhicule est inconnu du service de mises à jour." + +msgid "This vehicle has no head unit that can be updated with a USB stick." +msgstr "Ce véhicule n'a pas d'autoradio pouvant être mis à jour par clé USB." + +msgid "Download folder:" +msgstr "Dossier de téléchargement :" + +msgid "Change…" +msgstr "Modifier…" + +msgid "Installation guide" +msgstr "Guide d'installation" + +msgid "Download" +msgstr "Télécharger" + +msgid "Looking for updates…" +msgstr "Recherche des mises à jour…" + +msgid "No update is available: your head unit is up to date." +msgstr "Aucune mise à jour disponible : votre autoradio est à jour." + +msgid "Select the updates to download:" +msgstr "Sélectionnez les mises à jour à télécharger :" + +msgid "System (firmware)" +msgstr "Système (firmware)" + +msgid "Navigation map" +msgstr "Cartographie" + +msgid "Download folder" +msgstr "Dossier de téléchargement" + +msgid "Cannot save the settings" +msgstr "Impossible d'enregistrer les réglages" + +msgid "Not enough free space" +msgstr "Espace libre insuffisant" + +msgid "" +"%1 are needed in %2 but only %3 are free. If a previous download of these files is already in " +"this folder, it will be resumed and may fit." +msgstr "" +"%1 sont nécessaires dans %2 mais seuls %3 sont libres. Si un téléchargement précédent de ces " +"fichiers se trouve déjà dans ce dossier, il sera repris et pourra tenir." + +msgid "Download anyway" +msgstr "Télécharger quand même" + +msgid "Downloading" +msgstr "Téléchargement" + +msgid "You can close the application: the download will resume where it stopped next time." +msgstr "Vous pouvez fermer l'application : le téléchargement reprendra là où il s'est arrêté." + +msgid "Stop" +msgstr "Arrêter" + +msgid "License" +msgstr "Licence" + +msgid "waiting" +msgstr "en attente" + +msgid "Connecting…" +msgstr "Connexion…" + +msgid "Cannot write the file: %1" +msgstr "Impossible d'écrire le fichier : %1" + +msgid "The download failed: %1" +msgstr "Le téléchargement a échoué : %1" + +msgid "Download interrupted" +msgstr "Téléchargement interrompu" + +msgid "The files already downloaded are kept; start again to resume." +msgstr "Les fichiers déjà téléchargés sont conservés ; relancez pour reprendre." + +msgid "done" +msgstr "terminé" + +msgid "Time left: %1" +msgstr "Temps restant : %1" + +msgid "(connection lost, attempt %1)" +msgstr "(connexion perdue, tentative %1)" + +msgid "Prepare the USB stick" +msgstr "Préparer la clé USB" + +msgid "This USB stick is too small." +msgstr "Cette clé USB est trop petite." + +msgid "Refresh" +msgstr "Actualiser" + +msgid "Erase and write" +msgstr "Effacer et écrire" + +msgid "Computing the required size…" +msgstr "Calcul de la taille nécessaire…" + +msgid "A downloaded file is damaged" +msgstr "Un fichier téléchargé est endommagé" + +msgid "Download the update again." +msgstr "Téléchargez à nouveau la mise à jour." + +msgid "Plug in a USB stick of at least %1. It will be completely erased and formatted (FAT32)." +msgstr "Branchez une clé USB d'au moins %1. Elle sera entièrement effacée et formatée (FAT32)." + +msgid "USB drives cannot be listed: " +msgstr "Impossible de lister les clés USB : " + +msgid "too small" +msgstr "trop petite" + +msgid "No USB stick found. Plug one in, then refresh." +msgstr "Aucune clé USB trouvée. Branchez-en une, puis actualisez." + +msgid "Erase %1?" +msgstr "Effacer %1 ?" + +msgid "Everything on this USB stick will be lost." +msgstr "Tout le contenu de cette clé USB sera perdu." + +msgid "Writing the USB stick" +msgstr "Écriture de la clé USB" + +msgid "Do not unplug the USB stick." +msgstr "Ne débranchez pas la clé USB." + +msgid "Checking the downloaded files…" +msgstr "Vérification des fichiers téléchargés…" + +msgid "Permission to format the USB stick was refused." +msgstr "L'autorisation de formater la clé USB a été refusée." + +msgid "The USB stick could not be prepared" +msgstr "La clé USB n'a pas pu être préparée" + +msgid "Formatting the USB stick…" +msgstr "Formatage de la clé USB…" + +msgid "Copying the license…" +msgstr "Copie de la licence…" + +msgid "Copying the update…" +msgstr "Copie de la mise à jour…" + +msgid "Ejecting the USB stick…" +msgstr "Éjection de la clé USB…" + +msgid "The USB stick is ready" +msgstr "La clé USB est prête" + +msgid "" +"You can unplug the USB stick. With the engine running, plug it into the vehicle and follow the " +"instructions on the screen. The installation can take a long time: do not stop the engine." +msgstr "" +"Vous pouvez débrancher la clé USB. Moteur tournant, branchez-la dans le véhicule et suivez les " +"instructions à l'écran. L'installation peut être longue : ne coupez pas le moteur." + +msgid "Finish" +msgstr "Terminer" + +msgid "Preferences" +msgstr "Préférences" + +msgid "Check for a new version of OpenPU" +msgstr "Rechercher une nouvelle version d'OpenPU" + +msgid "Menu" +msgstr "Menu" + +msgid "OpenPU is up to date" +msgstr "OpenPU est à jour" + +msgid "Version %1 is the latest version." +msgstr "La version %1 est la plus récente." + +msgid "Cannot check for a new version" +msgstr "Impossible de rechercher une nouvelle version" + +msgid "OpenPU %1 is available" +msgstr "OpenPU %1 est disponible" + +msgid "You are using version %1. Do you want to download the new version?" +msgstr "Vous utilisez la version %1. Voulez-vous télécharger la nouvelle version ?" + +msgid "Later" +msgstr "Plus tard" + +msgid "Language" +msgstr "Langue" + +msgid "System language" +msgstr "Langue du système" + +msgid "The new language is used the next time OpenPU starts." +msgstr "La nouvelle langue sera utilisée au prochain démarrage d'OpenPU." + +msgid "Check for a new version of OpenPU at startup" +msgstr "Rechercher une nouvelle version d'OpenPU au démarrage" diff --git a/po/openpu.pot b/po/openpu.pot new file mode 100644 index 0000000..ddae106 --- /dev/null +++ b/po/openpu.pot @@ -0,0 +1,401 @@ +msgid "" +msgstr "" +"Project-Id-Version: openpu\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: src\ui-gtk\main_window.cpp:54 +msgid "Crony (navigation)" +msgstr "" + +#: src\ui-gtk\main_window.cpp:55 +msgid "Crony (no navigation)" +msgstr "" + +#: src\ui-gtk\main_window.cpp:58 +msgid "unknown head unit" +msgstr "" + +#: src\ui-gtk\main_window.cpp:63 +#, qt-format +msgid "version %1, %2" +msgstr "" + +#: src\ui-gtk\main_window.cpp:70 +msgid "The update server cannot be reached. Check your Internet connection." +msgstr "" + +#: src\ui-gtk\main_window.cpp:73 +msgid "The update server returned an error. Try again later." +msgstr "" + +#: src\ui-gtk\main_window.cpp:75 +msgid "This VIN is not valid." +msgstr "" + +#: src\ui-gtk\main_window.cpp:104 +msgid "Your saved data cannot be read" +msgstr "" + +#: src\ui-gtk\main_window.cpp:109 +msgid "Back" +msgstr "" + +#: src\ui-gtk\main_window.cpp:113 src\ui-gtk\main_window.cpp:219 +msgid "Preferences" +msgstr "" + +#: src\ui-gtk\main_window.cpp:114 +msgid "Check for a new version of OpenPU" +msgstr "" + +#: src\ui-gtk\main_window.cpp:115 +msgid "About OpenPU" +msgstr "" + +#: src\ui-gtk\main_window.cpp:118 +msgid "Menu" +msgstr "" + +#: src\ui-gtk\main_window.cpp:181 +msgid "OpenPU is up to date" +msgstr "" + +#: src\ui-gtk\main_window.cpp:182 +#, qt-format +msgid "Version %1 is the latest version." +msgstr "" + +#: src\ui-gtk\main_window.cpp:185 +msgid "Cannot check for a new version" +msgstr "" + +#: src\ui-gtk\main_window.cpp:195 +#, qt-format +msgid "OpenPU %1 is available" +msgstr "" + +#: src\ui-gtk\main_window.cpp:197 +#, qt-format +msgid "You are using version %1. Do you want to download the new version?" +msgstr "" + +#: src\ui-gtk\main_window.cpp:201 +msgid "Later" +msgstr "" + +#: src\ui-gtk\main_window.cpp:201 src\ui-gtk\main_window.cpp:625 +msgid "Download" +msgstr "" + +#: src\ui-gtk\main_window.cpp:231 src\ui-gtk\main_window.cpp:705 +msgid "Download folder" +msgstr "" + +#: src\ui-gtk\main_window.cpp:238 src\ui-gtk\main_window.cpp:608 +msgid "Change…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:247 +msgid "Language" +msgstr "" + +#: src\ui-gtk\main_window.cpp:252 +msgid "System language" +msgstr "" + +#: src\ui-gtk\main_window.cpp:258 +msgid "The new language is used the next time OpenPU starts." +msgstr "" + +#: src\ui-gtk\main_window.cpp:271 src\ui-gtk\main_window.cpp:286 src\ui-gtk\main_window.cpp:718 +msgid "Cannot save the settings" +msgstr "" + +#: src\ui-gtk\main_window.cpp:279 +msgid "Check for a new version of OpenPU at startup" +msgstr "" + +#: src\ui-gtk\main_window.cpp:338 +msgid "Download Peugeot head unit updates (system and navigation map) and prepare the USB stick, on Linux and Haiku.\n\nIndependent project, not affiliated with Stellantis or Peugeot." +msgstr "" + +#: src\ui-gtk\main_window.cpp:344 +msgid "Source code" +msgstr "" + +#: src\ui-gtk\main_window.cpp:356 +msgid "Cannot save the vehicle list" +msgstr "" + +#: src\ui-gtk\main_window.cpp:370 +msgid "My vehicles" +msgstr "" + +#: src\ui-gtk\main_window.cpp:372 +msgid "Add your vehicle with its VIN (17 characters, on the registration document, field E)." +msgstr "" + +#: src\ui-gtk\main_window.cpp:392 src\ui-gtk\main_window.cpp:486 +msgid "Add a vehicle" +msgstr "" + +#: src\ui-gtk\main_window.cpp:393 src\ui-gtk\main_window.cpp:457 +msgid "Remove" +msgstr "" + +#: src\ui-gtk\main_window.cpp:394 +msgid "Check for updates" +msgstr "" + +#: src\ui-gtk\main_window.cpp:425 +msgid "download not finished" +msgstr "" + +#: src\ui-gtk\main_window.cpp:455 +#, qt-format +msgid "Remove %1?" +msgstr "" + +#: src\ui-gtk\main_window.cpp:456 +msgid "Downloaded files that were not written to a USB stick yet are deleted too." +msgstr "" + +#: src\ui-gtk\main_window.cpp:457 src\ui-gtk\main_window.cpp:741 src\ui-gtk\main_window.cpp:982 +msgid "Cancel" +msgstr "" + +#: src\ui-gtk\main_window.cpp:488 +msgid "The VIN (vehicle identification number) is written in field E of the registration document and at the bottom of the windscreen." +msgstr "" + +#: src\ui-gtk\main_window.cpp:496 +msgid "VIN" +msgstr "" + +#: src\ui-gtk\main_window.cpp:498 +msgid "Name" +msgstr "" + +#: src\ui-gtk\main_window.cpp:503 +msgid "e.g. 208 or Family car" +msgstr "" + +#: src\ui-gtk\main_window.cpp:517 +msgid "Add" +msgstr "" + +#: src\ui-gtk\main_window.cpp:535 +msgid "A VIN has 17 characters and starts with VF3 or VR3." +msgstr "" + +#: src\ui-gtk\main_window.cpp:541 +msgid "Checking the vehicle…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:558 +msgid "This vehicle is unknown to the update service." +msgstr "" + +#: src\ui-gtk\main_window.cpp:562 +msgid "This vehicle has no head unit that can be updated with a USB stick." +msgstr "" + +#: src\ui-gtk\main_window.cpp:604 +msgid "Download folder:" +msgstr "" + +#: src\ui-gtk\main_window.cpp:617 src\ui-gtk\main_window.cpp:1118 +msgid "Installation guide" +msgstr "" + +#: src\ui-gtk\main_window.cpp:651 +msgid "Looking for updates…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:685 +msgid "No update is available: your head unit is up to date." +msgstr "" + +#: src\ui-gtk\main_window.cpp:688 +msgid "Select the updates to download:" +msgstr "" + +#: src\ui-gtk\main_window.cpp:690 src\ui-gtk\main_window.cpp:803 +msgid "System (firmware)" +msgstr "" + +#: src\ui-gtk\main_window.cpp:695 src\ui-gtk\main_window.cpp:807 +msgid "Navigation map" +msgstr "" + +#: src\ui-gtk\main_window.cpp:736 +msgid "Not enough free space" +msgstr "" + +#: src\ui-gtk\main_window.cpp:738 +#, qt-format +msgid "%1 are needed in %2 but only %3 are free. If a previous download of these files is already in this folder, it will be resumed and may fit." +msgstr "" + +#: src\ui-gtk\main_window.cpp:741 +msgid "Download anyway" +msgstr "" + +#: src\ui-gtk\main_window.cpp:763 +msgid "Downloading" +msgstr "" + +#: src\ui-gtk\main_window.cpp:765 +msgid "You can close the application: the download will resume where it stopped next time." +msgstr "" + +#: src\ui-gtk\main_window.cpp:786 src\ui-gtk\main_window.cpp:1014 +msgid "Stop" +msgstr "" + +#: src\ui-gtk\main_window.cpp:799 src\ui-gtk\main_window.cpp:849 +msgid "License" +msgstr "" + +#: src\ui-gtk\main_window.cpp:799 +msgid "waiting" +msgstr "" + +#: src\ui-gtk\main_window.cpp:812 +msgid "Connecting…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:829 +#, qt-format +msgid "Cannot write the file: %1" +msgstr "" + +#: src\ui-gtk\main_window.cpp:830 +#, qt-format +msgid "The download failed: %1" +msgstr "" + +#: src\ui-gtk\main_window.cpp:839 +msgid "Download interrupted" +msgstr "" + +#: src\ui-gtk\main_window.cpp:840 +msgid "The files already downloaded are kept; start again to resume." +msgstr "" + +#: src\ui-gtk\main_window.cpp:849 +msgid "done" +msgstr "" + +#: src\ui-gtk\main_window.cpp:859 +#, qt-format +msgid "Time left: %1" +msgstr "" + +#: src\ui-gtk\main_window.cpp:861 +#, qt-format +msgid "(connection lost, attempt %1)" +msgstr "" + +#: src\ui-gtk\main_window.cpp:886 +msgid "Prepare the USB stick" +msgstr "" + +#: src\ui-gtk\main_window.cpp:897 src\ui-gtk\main_window.cpp:970 +msgid "This USB stick is too small." +msgstr "" + +#: src\ui-gtk\main_window.cpp:901 +msgid "Refresh" +msgstr "" + +#: src\ui-gtk\main_window.cpp:910 src\ui-gtk\main_window.cpp:982 +msgid "Erase and write" +msgstr "" + +#: src\ui-gtk\main_window.cpp:920 +msgid "Computing the required size…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:934 src\ui-gtk\main_window.cpp:1055 +msgid "A downloaded file is damaged" +msgstr "" + +#: src\ui-gtk\main_window.cpp:934 src\ui-gtk\main_window.cpp:1055 +msgid "Download the update again." +msgstr "" + +#: src\ui-gtk\main_window.cpp:941 +#, qt-format +msgid "Plug in a USB stick of at least %1. It will be completely erased and formatted (FAT32)." +msgstr "" + +#: src\ui-gtk\main_window.cpp:956 +msgid "USB drives cannot be listed: " +msgstr "" + +#: src\ui-gtk\main_window.cpp:961 +msgid "too small" +msgstr "" + +#: src\ui-gtk\main_window.cpp:964 +msgid "No USB stick found. Plug one in, then refresh." +msgstr "" + +#: src\ui-gtk\main_window.cpp:980 +#, qt-format +msgid "Erase %1?" +msgstr "" + +#: src\ui-gtk\main_window.cpp:981 +msgid "Everything on this USB stick will be lost." +msgstr "" + +#: src\ui-gtk\main_window.cpp:1000 +msgid "Writing the USB stick" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1001 +msgid "Do not unplug the USB stick." +msgstr "" + +#: src\ui-gtk\main_window.cpp:1026 src\ui-gtk\main_window.cpp:1072 +msgid "Checking the downloaded files…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1046 +msgid "Permission to format the USB stick was refused." +msgstr "" + +#: src\ui-gtk\main_window.cpp:1061 +msgid "The USB stick could not be prepared" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1074 +msgid "Formatting the USB stick…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1077 +msgid "Copying the license…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1078 +msgid "Copying the update…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1080 +msgid "Ejecting the USB stick…" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1111 +msgid "The USB stick is ready" +msgstr "" + +#: src\ui-gtk\main_window.cpp:1113 +msgid "You can unplug the USB stick. With the engine running, plug it into the vehicle and follow the instructions on the screen. The installation can take a long time: do not stop the engine." +msgstr "" + +#: src\ui-gtk\main_window.cpp:1126 +msgid "Finish" +msgstr "" diff --git a/src/cli/main.cpp b/src/cli/main.cpp index 0dd9c22..e2281f1 100644 --- a/src/cli/main.cpp +++ b/src/cli/main.cpp @@ -1,10 +1,13 @@ +// SPDX-License-Identifier: MIT // openpu-cli — command-line front-end of libopenpu. #include "openpu/api_client.hpp" +#include "openpu/app_update.hpp" #include "openpu/archive.hpp" #include "openpu/download.hpp" #include "openpu/storage.hpp" #include "openpu/usb.hpp" +#include "openpu/version.hpp" #include "openpu/vin.hpp" #include @@ -30,6 +33,7 @@ extern "C" void onSignal(int /*sig*/) void usage() { std::cerr << "usage: openpu-cli [--verbose] [args]\n" + " openpu-cli --version\n" "\n" "commands:\n" " check identify the head unit and list available updates\n" @@ -43,6 +47,7 @@ void usage() " ERASE , format FAT32 and write the update\n" " write-dir [--license F] ...\n" " write the update into an existing directory\n" + " app-update check for a newer OpenPU (exit status 10 if any)\n" " raw-devices print the raw devices/{VIN} response\n" " raw-updates print the raw getAvailableUpdate response\n" "\n" @@ -361,6 +366,22 @@ int run(std::vector args) curlOptions.verbose = true; args.erase(args.begin()); } + if (args.size() == 1 && (args[0] == "--version" || args[0] == "version")) { + std::cout << "openpu-cli " << openpu::versionDescription() << '\n'; + return 0; + } + if (args.size() == 1 && args[0] == "app-update") { + auto transport = openpu::makeCurlTransport(curlOptions); + const auto release = openpu::checkForNewerRelease(*transport, openpu::AppUpdateConfig::fromEnvironment(), + openpu::version()); + if (!release) { + std::cout << "OpenPU " << openpu::version() << " is up to date\n"; + return 0; + } + std::cout << "OpenPU " << release->version.toString() << " is available (this is " << openpu::version() + << "): " << release->pageUrl << '\n'; + return 10; + } if (args.size() == 1 && args[0] == "usb-list") return cmdUsbList(); if (args.size() < 2) { @@ -418,7 +439,9 @@ int main(int argc, char** argv) << "): " << e.what() << '\n'; } catch (const openpu::UsbError& e) { std::cerr << "\nUSB error: " << e.what() << '\n'; - } catch (const openpu::StorageError& e) { + } catch (const openpu::NetworkError& e) { + std::cerr << "network error: " << e.what() << '\n'; + } catch (const std::runtime_error& e) { // StorageError, ParseError, app-update errors... std::cerr << "error: " << e.what() << '\n'; } return 1; diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 35688d0..fcb64a3 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -13,12 +13,13 @@ add_library(openpu_core STATIC archive.cpp storage.cpp usb.cpp + job.cpp + app_update.cpp ) target_include_directories(openpu_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(openpu_core PUBLIC CURL::libcurl Threads::Threads PRIVATE nlohmann_json::nlohmann_json LibArchive::LibArchive openpu_warnings) -target_compile_definitions(openpu_core PRIVATE OPENPU_VERSION="${PROJECT_VERSION}") # USB backend if(HAIKU) @@ -32,3 +33,18 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") else() target_sources(openpu_core PRIVATE usb_none.cpp) endif() + +# Version (regenerated at every build from `git describe`, rewritten only when it changes) +find_package(Git QUIET) +set(OPENPU_VERSION_CPP ${CMAKE_CURRENT_BINARY_DIR}/generated/version.cpp) +add_custom_target(openpu_version + COMMAND ${CMAKE_COMMAND} + -DSOURCE_DIR=${PROJECT_SOURCE_DIR} + -DOUTPUT=${OPENPU_VERSION_CPP} + -DVERSION=${PROJECT_VERSION} + -DGIT_EXECUTABLE=${GIT_EXECUTABLE} + -P ${PROJECT_SOURCE_DIR}/cmake/GitVersion.cmake + BYPRODUCTS ${OPENPU_VERSION_CPP} + COMMENT "Computing the build version") +target_sources(openpu_core PRIVATE ${OPENPU_VERSION_CPP}) +add_dependencies(openpu_core openpu_version) diff --git a/src/core/api_client.cpp b/src/core/api_client.cpp index c964b07..a08303a 100644 --- a/src/core/api_client.cpp +++ b/src/core/api_client.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/api_client.hpp" #include "openpu/vin.hpp" diff --git a/src/core/app_update.cpp b/src/core/app_update.cpp new file mode 100644 index 0000000..50d9fe2 --- /dev/null +++ b/src/core/app_update.cpp @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: MIT +#include "openpu/app_update.hpp" + +#include "openpu/models.hpp" + +#include +#include + +namespace openpu { + +namespace { + +std::optional number(std::string_view s) +{ + if (s.empty() || s.size() > 6) + return std::nullopt; + unsigned v = 0; + for (char c : s) { + if (c < '0' || c > '9') + return std::nullopt; + v = v * 10 + static_cast(c - '0'); + } + return v; +} + +void overrideFromEnv(std::string& field, const char* name) +{ + const char* value = std::getenv(name); // NOLINT(concurrency-mt-unsafe): read once at startup + if (value != nullptr && *value != '\0') + field = value; +} + +} // namespace + +std::optional SemVer::parse(std::string_view text) +{ + if (!text.empty() && (text.front() == 'v' || text.front() == 'V')) + text.remove_prefix(1); + text = text.substr(0, text.find('+')); + const auto dot1 = text.find('.'); + const auto dot2 = dot1 == std::string_view::npos ? dot1 : text.find('.', dot1 + 1); + if (dot2 == std::string_view::npos) + return std::nullopt; + const auto major = number(text.substr(0, dot1)); + const auto minor = number(text.substr(dot1 + 1, dot2 - dot1 - 1)); + const auto patch = number(text.substr(dot2 + 1)); // "1.2.3-rc1" fails here: no pre-releases + if (!major || !minor || !patch) + return std::nullopt; + return SemVer{*major, *minor, *patch}; +} + +std::string SemVer::toString() const +{ + return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch); +} + +AppUpdateConfig AppUpdateConfig::fromEnvironment() +{ + AppUpdateConfig c; + overrideFromEnv(c.releasesUrl, "OPENPU_RELEASES_URL"); + overrideFromEnv(c.pageUrl, "OPENPU_RELEASE_PAGE_URL"); + return c; +} + +std::optional latestRelease(std::string_view json, const AppUpdateConfig& config) +{ + const auto doc = nlohmann::json::parse(json, nullptr, false); + if (doc.is_discarded() || !doc.is_array()) + throw ParseError("unexpected release list"); + const auto text = [](const nlohmann::json& o, const char* key) { + auto it = o.find(key); + return it != o.end() && it->is_string() ? it->get() : std::string(); + }; + const auto flag = [](const nlohmann::json& o, const char* key) { + auto it = o.find(key); + return it != o.end() && it->is_boolean() && it->get(); + }; + std::optional best; + for (const auto& item : doc) { + if (!item.is_object() || flag(item, "draft") || flag(item, "prerelease")) + continue; + // Releases carry "tag_name"; plain tags carry "name". + const bool isRelease = item.contains("tag_name"); + const std::string tag = text(item, isRelease ? "tag_name" : "name"); + if (tag.empty() || tag.front() != 'v') + continue; + const auto v = SemVer::parse(tag); + if (!v || (best && !(best->version < *v))) + continue; + AppRelease r; + r.version = *v; + r.tag = tag; + r.pageUrl = text(item, "html_url"); + if (r.pageUrl.empty()) { + r.pageUrl = config.pageUrl; + const auto pos = r.pageUrl.find("{tag}"); + if (pos != std::string::npos) + r.pageUrl.replace(pos, 5, tag); + } + r.notes = text(item, isRelease ? "body" : "message"); + best = std::move(r); + } + return best; +} + +std::optional checkForNewerRelease(Transport& transport, const AppUpdateConfig& config, + std::string_view currentVersion) +{ + const auto current = SemVer::parse(currentVersion); + if (!current) + throw std::runtime_error("invalid current version"); + HttpRequest req; + req.url = config.releasesUrl; + req.headers.emplace_back("Accept", "application/vnd.github+json, application/json"); + req.stallTimeout = std::chrono::seconds(20); + const HttpResponse r = transport.perform(req); + if (r.status != 200) + throw std::runtime_error("release server answered HTTP " + std::to_string(r.status)); + auto latest = latestRelease(r.body, config); + if (latest && *current < latest->version) + return latest; + return std::nullopt; +} + +} // namespace openpu diff --git a/src/core/archive.cpp b/src/core/archive.cpp index 5e24bb0..00df20c 100644 --- a/src/core/archive.cpp +++ b/src/core/archive.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/archive.hpp" #include diff --git a/src/core/curl_transport.cpp b/src/core/curl_transport.cpp index 023694f..123135c 100644 --- a/src/core/curl_transport.cpp +++ b/src/core/curl_transport.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/http.hpp" #include @@ -5,9 +6,8 @@ #include #include -#ifndef OPENPU_VERSION -#define OPENPU_VERSION "dev" -#endif +#include "openpu/version.hpp" + namespace openpu { @@ -123,7 +123,7 @@ public: { globalInit(); if (options_.userAgent.empty()) - options_.userAgent = std::string("OpenPU/") + OPENPU_VERSION; + options_.userAgent = std::string("OpenPU/") + version(); } HttpResponse perform(const HttpRequest& request) override diff --git a/src/core/download.cpp b/src/core/download.cpp index 583dde1..ee06cc9 100644 --- a/src/core/download.cpp +++ b/src/core/download.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/download.hpp" #include diff --git a/src/core/http.cpp b/src/core/http.cpp index 748fb2d..31f2f34 100644 --- a/src/core/http.cpp +++ b/src/core/http.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/http.hpp" #include diff --git a/src/core/include/openpu/api_client.hpp b/src/core/include/openpu/api_client.hpp index f7d66a6..d092057 100644 --- a/src/core/include/openpu/api_client.hpp +++ b/src/core/include/openpu/api_client.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include "openpu/http.hpp" diff --git a/src/core/include/openpu/app_update.hpp b/src/core/include/openpu/app_update.hpp new file mode 100644 index 0000000..90b7ac2 --- /dev/null +++ b/src/core/include/openpu/app_update.hpp @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MIT +#pragma once + +#include "openpu/http.hpp" + +#include +#include +#include + +namespace openpu { + +/// MAJOR.MINOR.PATCH, ordered numerically. +struct SemVer { + unsigned major = 0; + unsigned minor = 0; + unsigned patch = 0; + + /// Accepts "1.2.3" and "v1.2.3"; build metadata ("+3.gabc") is ignored. Pre-releases are rejected. + static std::optional parse(std::string_view text); + std::string toString() const; + + friend bool operator<(const SemVer& a, const SemVer& b) + { + if (a.major != b.major) + return a.major < b.major; + if (a.minor != b.minor) + return a.minor < b.minor; + return a.patch < b.patch; + } + friend bool operator==(const SemVer& a, const SemVer& b) + { + return a.major == b.major && a.minor == b.minor && a.patch == b.patch; + } +}; + +/// Where new OpenPU versions are published: the GitHub releases of the project. +/// A Gitea/GitHub `/tags` list is understood too (OPENPU_RELEASES_URL may point to one). +struct AppUpdateConfig { + std::string releasesUrl = "https://api.github.com/repos/yann64/openpu/releases"; + /// Page opened in the browser when the answer gives none; "{tag}" is replaced by the tag name. + std::string pageUrl = "https://github.com/yann64/openpu/releases/tag/{tag}"; + + /// Defaults overridden by OPENPU_RELEASES_URL and OPENPU_RELEASE_PAGE_URL when set. + static AppUpdateConfig fromEnvironment(); +}; + +struct AppRelease { + SemVer version; + std::string tag; + std::string pageUrl; + std::string notes; ///< release notes (or annotated tag message) +}; + +/// Highest vX.Y.Z release of a GitHub/Gitea `/releases` list (drafts and pre-releases skipped) or +/// of a `/tags` list (nullopt if none). Throws ParseError. +std::optional latestRelease(std::string_view json, const AppUpdateConfig& config); + +/// Newest published release if it is newer than `currentVersion`, nullopt when up to date. +/// Throws NetworkError, or std::runtime_error for an unexpected answer. +std::optional checkForNewerRelease(Transport& transport, const AppUpdateConfig& config, + std::string_view currentVersion); + +} // namespace openpu diff --git a/src/core/include/openpu/archive.hpp b/src/core/include/openpu/archive.hpp index 48e998d..cd1d0df 100644 --- a/src/core/include/openpu/archive.hpp +++ b/src/core/include/openpu/archive.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include "openpu/cancel.hpp" diff --git a/src/core/include/openpu/cancel.hpp b/src/core/include/openpu/cancel.hpp index 83634a4..3f7a9cc 100644 --- a/src/core/include/openpu/cancel.hpp +++ b/src/core/include/openpu/cancel.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include diff --git a/src/core/include/openpu/download.hpp b/src/core/include/openpu/download.hpp index 0e2b47a..df25b76 100644 --- a/src/core/include/openpu/download.hpp +++ b/src/core/include/openpu/download.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include "openpu/cancel.hpp" diff --git a/src/core/include/openpu/format.hpp b/src/core/include/openpu/format.hpp new file mode 100644 index 0000000..c7c731c --- /dev/null +++ b/src/core/include/openpu/format.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT +#pragma once + +#include +#include +#include +#include + +namespace openpu { + +/// "8.39 GB" (decimal units, as storage vendors and the official app use). +inline std::string formatSize(std::uint64_t bytes) +{ + const char* units[] = {"B", "KB", "MB", "GB", "TB"}; + auto value = static_cast(bytes); + std::size_t unit = 0; + while (value >= 1000.0 && unit + 1 < sizeof units / sizeof units[0]) { + value /= 1000.0; + ++unit; + } + char buf[32]; + (void)std::snprintf(buf, sizeof buf, unit == 0 ? "%.0f %s" : "%.2f %s", value, units[unit]); + return buf; +} + +/// "1:02:03" or "02:03". +inline std::string formatDuration(std::chrono::seconds s) +{ + const auto total = static_cast(s.count()); + char buf[32]; + if (total >= 3600) + (void)std::snprintf(buf, sizeof buf, "%lld:%02lld:%02lld", total / 3600, (total / 60) % 60, total % 60); + else + (void)std::snprintf(buf, sizeof buf, "%02lld:%02lld", total / 60, total % 60); + return buf; +} + +} // namespace openpu diff --git a/src/core/include/openpu/http.hpp b/src/core/include/openpu/http.hpp index 84ab9d8..c30c1c8 100644 --- a/src/core/include/openpu/http.hpp +++ b/src/core/include/openpu/http.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include diff --git a/src/core/include/openpu/job.hpp b/src/core/include/openpu/job.hpp new file mode 100644 index 0000000..6131223 --- /dev/null +++ b/src/core/include/openpu/job.hpp @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: MIT +#pragma once + +#include "openpu/download.hpp" +#include "openpu/models.hpp" +#include "openpu/usb.hpp" + +#include +#include +#include +#include +#include + +namespace openpu { + +/// URL of the installation guide (PDF) for a guide key such as "path_guide_rcc". +/// `language` is an ISO 639-1 code; French and English are known, anything else gives English. +std::string guideUrl(std::string_view guideKey, std::string_view language); + +/// Two-letter language of the user session (LANGUAGE / LC_ALL / LC_MESSAGES / LANG), "en" by default. +std::string systemLanguage(); + +/// What to download for one vehicle. +struct DownloadPlan { + std::optional firmware; + std::optional map; + std::filesystem::path dir; + + /// Bytes still to download (announced sizes minus partial files already in `dir`), +10 %. + /// Partial files are matched by name, so this needs the names (see resolveNames()). + std::uint64_t requiredSpace() const; + /// Total announced size. + std::uint64_t totalSize() const; +}; + +struct DownloadedFiles { + std::optional license; + std::optional firmware; + std::optional map; + + /// Write plan for the stick: license (with firmware only), firmware archive, then map archive. + UsbWritePlan writePlan() const; + /// Removes every file of the set (after a successful copy, or when the user gives up). + void remove() const; +}; + +enum class DownloadItem { License, Firmware, Map }; + +struct JobProgress { + DownloadItem item = DownloadItem::Firmware; + DownloadProgress progress; +}; +using JobProgressCallback = std::function; + +/// Official order: license (firmware only), firmware, map. Partial files are resumed. +DownloadedFiles downloadUpdates(Downloader& downloader, const DownloadPlan& plan, const JobProgressCallback& onProgress = {}, + const CancelToken* cancel = nullptr); + +} // namespace openpu diff --git a/src/core/include/openpu/models.hpp b/src/core/include/openpu/models.hpp index 5de8c4a..b8cd163 100644 --- a/src/core/include/openpu/models.hpp +++ b/src/core/include/openpu/models.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include diff --git a/src/core/include/openpu/storage.hpp b/src/core/include/openpu/storage.hpp index 87ea0a4..63c0ce8 100644 --- a/src/core/include/openpu/storage.hpp +++ b/src/core/include/openpu/storage.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include "openpu/models.hpp" @@ -74,6 +75,7 @@ struct PendingDownload { struct Settings { std::string language; ///< empty: follow the system locale std::filesystem::path downloadDir; ///< empty: paths::defaultDownloadDir() + bool checkAppUpdates = true; ///< look for a newer OpenPU at startup std::optional pending; std::filesystem::path effectiveDownloadDir() const; diff --git a/src/core/include/openpu/usb.hpp b/src/core/include/openpu/usb.hpp index 835493a..b247f56 100644 --- a/src/core/include/openpu/usb.hpp +++ b/src/core/include/openpu/usb.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include "openpu/cancel.hpp" diff --git a/src/core/include/openpu/version.hpp b/src/core/include/openpu/version.hpp new file mode 100644 index 0000000..9612b00 --- /dev/null +++ b/src/core/include/openpu/version.hpp @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +#pragma once + +namespace openpu { + +/// Release version, "MAJOR.MINOR.PATCH" (CMake project version, tagged vMAJOR.MINOR.PATCH in git). +const char* version() noexcept; + +/// Build description: the version, plus "+.g[.dirty]" when not built from the tag. +const char* versionDescription() noexcept; + +} // namespace openpu diff --git a/src/core/include/openpu/vin.hpp b/src/core/include/openpu/vin.hpp index 08d05b9..8df24a0 100644 --- a/src/core/include/openpu/vin.hpp +++ b/src/core/include/openpu/vin.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include diff --git a/src/core/job.cpp b/src/core/job.cpp new file mode 100644 index 0000000..2000814 --- /dev/null +++ b/src/core/job.cpp @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: MIT +#include "openpu/job.hpp" + +#include +#include +#include + +namespace openpu { + +namespace fs = std::filesystem; + +namespace { + +struct GuideLinks { + const char* nac; + const char* rcc; + const char* aio; +}; + +// From the official application's translations (dist/ovip-ui/assets/i18n/{fr,en}.json). +constexpr GuideLinks kFrench{ + "https://www.peugeot.fr/content/dam/peugeot/master/media/manual/1/fr/map-software-nac-fr.632350.pdf", + "https://www.peugeot.fr/content/dam/peugeot/master/media/manual/1/fr/map-software-rcc-fr.632352.pdf", + "https://www.peugeot.fr/content/dam/peugeot/master/media/manual/1/fr/map-software-iao-fr.793298.pdf", +}; +constexpr GuideLinks kEnglish{ + "https://www.peugeot.co.uk/content/dam/peugeot/master/media/manual/1/en/map-software-nac-en.632380.pdf", + "https://www.peugeot.co.uk/content/dam/peugeot/master/media/manual/1/en/map-software-rcc-en.632382.pdf", + "https://www.peugeot.co.uk/content/dam/peugeot/master/media/manual/1/en/map-software-iao-es.793301.pdf", +}; +constexpr const char* kCronyGuide = "https://www.stellantis.com/"; + +std::uint64_t sizeOf(const fs::path& p) +{ + std::error_code ec; + const auto s = fs::file_size(p, ec); + return ec ? 0 : static_cast(s); +} + +} // namespace + +std::string guideUrl(std::string_view key, std::string_view language) +{ + const GuideLinks& links = language == "fr" ? kFrench : kEnglish; + if (key == "path_guide_rcc") + return links.rcc; + if (key == "path_guide_aio") + return links.aio; + if (key.substr(0, 16) == "path_guide_wave_") + return links.nac; + if (key.substr(0, 17) == "path_guide_crony_") + return kCronyGuide; + return {}; +} + +std::string systemLanguage() +{ + for (const char* var : {"LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"}) { + const char* v = std::getenv(var); // NOLINT(concurrency-mt-unsafe) + if (v == nullptr || *v == '\0') + continue; + std::string s(v); + if (s == "C" || s == "POSIX" || s.size() < 2) + continue; + std::string lang; + for (char c : s.substr(0, 2)) + lang.push_back(static_cast(std::tolower(static_cast(c)))); + return lang; + } + return "en"; +} + +std::uint64_t DownloadPlan::totalSize() const +{ + return (firmware ? firmware->size : 0) + (map ? map->size : 0); +} + +std::uint64_t DownloadPlan::requiredSpace() const +{ + return withMargin(totalSize()); +} + +UsbWritePlan DownloadedFiles::writePlan() const +{ + UsbWritePlan plan; + if (firmware) { + plan.license = license; + plan.archives.push_back(*firmware); + } + if (map) + plan.archives.push_back(*map); + return plan; +} + +void DownloadedFiles::remove() const +{ + std::error_code ec; + for (const auto& f : {license, firmware, map}) + if (f) + fs::remove(*f, ec); +} + +DownloadedFiles downloadUpdates(Downloader& downloader, const DownloadPlan& plan, const JobProgressCallback& onProgress, + const CancelToken* cancel) +{ + DownloadedFiles files; + auto forward = [&](DownloadItem item) { + return [&onProgress, item](const DownloadProgress& p) { + if (onProgress) + onProgress(JobProgress{item, p}); + }; + }; + if (plan.firmware) { + if (!plan.firmware->licenseUrl.empty()) { + const auto lic = downloader.downloadSmall(plan.firmware->licenseUrl, plan.dir, std::nullopt, cancel); + files.license = lic.file; + if (onProgress) { + DownloadProgress p; + p.total = p.done = sizeOf(lic.file); + onProgress(JobProgress{DownloadItem::License, p}); + } + } + files.firmware = downloader.downloadResumable(plan.firmware->url, plan.dir, forward(DownloadItem::Firmware), cancel).file; + } + if (plan.map) + files.map = downloader.downloadResumable(plan.map->url, plan.dir, forward(DownloadItem::Map), cancel).file; + return files; +} + +} // namespace openpu diff --git a/src/core/models.cpp b/src/core/models.cpp index d50f52a..1af003a 100644 --- a/src/core/models.cpp +++ b/src/core/models.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/models.hpp" #include diff --git a/src/core/storage.cpp b/src/core/storage.cpp index 6c5a803..d3901e2 100644 --- a/src/core/storage.cpp +++ b/src/core/storage.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/storage.hpp" #include @@ -15,7 +16,7 @@ namespace openpu { namespace fs = std::filesystem; -using json = nlohmann::json; +using json = nlohmann::ordered_json; // keep the user's vehicle order namespace { @@ -244,6 +245,8 @@ Settings Settings::load(const fs::path& file) const json doc = parseJson(readFile(file), file.string()); s.language = str(doc, "language"); s.downloadDir = str(doc, "downloadPath"); + if (auto it = doc.find("checkAppUpdates"); it != doc.end() && it->is_boolean()) + s.checkAppUpdates = it->get(); auto p = doc.find("pendingDownload"); if (p != doc.end() && p->is_object() && !str(*p, "vin").empty()) { PendingDownload d; @@ -267,6 +270,7 @@ void Settings::save(const fs::path& file) const doc["language"] = language; if (!downloadDir.empty()) doc["downloadPath"] = downloadDir.string(); + doc["checkAppUpdates"] = checkAppUpdates; if (pending) { doc["pendingDownload"] = { {"vin", pending->vin}, diff --git a/src/core/usb.cpp b/src/core/usb.cpp index 8b4b3f2..979053e 100644 --- a/src/core/usb.cpp +++ b/src/core/usb.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/usb.hpp" #include "openpu/archive.hpp" diff --git a/src/core/usb_none.cpp b/src/core/usb_none.cpp index ad64841..396bd23 100644 --- a/src/core/usb_none.cpp +++ b/src/core/usb_none.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT // Fallback for platforms without a USB backend: listing and formatting are unavailable, // but writePayload() still works on an already prepared stick. diff --git a/src/core/usb_udisks.cpp b/src/core/usb_udisks.cpp index ea97517..ca45a4c 100644 --- a/src/core/usb_udisks.cpp +++ b/src/core/usb_udisks.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT // UDisks2 backend (Linux): enumeration, FAT32 formatting, mounting and ejecting over D-Bus. // Authorisation is delegated to polkit, so no root privileges are needed in a desktop session. diff --git a/src/core/vin.cpp b/src/core/vin.cpp index 2557f95..de76605 100644 --- a/src/core/vin.cpp +++ b/src/core/vin.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/vin.hpp" #include diff --git a/src/ui-gtk/CMakeLists.txt b/src/ui-gtk/CMakeLists.txt new file mode 100644 index 0000000..9307052 --- /dev/null +++ b/src/ui-gtk/CMakeLists.txt @@ -0,0 +1,17 @@ +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTKMM REQUIRED IMPORTED_TARGET gtkmm-4.0>=4.10) +include(GNUInstallDirs) + +add_executable(openpu + main.cpp + main_window.cpp +) +target_link_libraries(openpu PRIVATE openpu_core PkgConfig::GTKMM openpu_warnings) +target_compile_definitions(openpu PRIVATE + GETTEXT_PACKAGE="openpu" + OPENPU_LOCALEDIR="${CMAKE_INSTALL_FULL_LOCALEDIR}") +# gtkmm headers trigger -Wshadow/-Wconversion noise we cannot fix. +target_compile_options(openpu PRIVATE -Wno-shadow -Wno-conversion) + +install(TARGETS openpu RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +install(FILES io.github.openpu.OpenPU.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications) diff --git a/src/ui-gtk/io.github.openpu.OpenPU.desktop b/src/ui-gtk/io.github.openpu.OpenPU.desktop new file mode 100644 index 0000000..2ff8a30 --- /dev/null +++ b/src/ui-gtk/io.github.openpu.OpenPU.desktop @@ -0,0 +1,12 @@ +[Desktop Entry] +Type=Application +Name=OpenPU +GenericName=Head unit updates +GenericName[fr]=Mises à jour de l'autoradio +Comment=Download firmware and map updates for Peugeot head units and prepare the USB stick +Comment[fr]=Télécharger les mises à jour système et cartographie des autoradios Peugeot et préparer la clé USB +Exec=openpu +Icon=io.github.openpu.OpenPU +Terminal=false +Categories=Utility;GTK; +Keywords=Peugeot;NAC;RCC;GPS;map;firmware;USB; diff --git a/src/ui-gtk/main.cpp b/src/ui-gtk/main.cpp new file mode 100644 index 0000000..523992b --- /dev/null +++ b/src/ui-gtk/main.cpp @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT +#include "main_window.hpp" + +#include "openpu/storage.hpp" + +#include +#include +#include +#include + +int main(int argc, char* argv[]) +{ + // A language chosen in the settings overrides the session language (gettext reads LANGUAGE). + try { + const auto settings = openpu::Settings::load(openpu::paths::configDir() / "config.json"); + if (!settings.language.empty()) + (void)setenv("LANGUAGE", settings.language.c_str(), 1); // NOLINT(concurrency-mt-unsafe): no thread yet + } catch (const openpu::StorageError&) { + // dismissed: the window reports unreadable settings itself + } + (void)std::setlocale(LC_ALL, ""); // NOLINT(concurrency-mt-unsafe): no thread yet + // OPENPU_LOCALEDIR lets a build-tree binary find its translations. + const char* localeDir = std::getenv("OPENPU_LOCALEDIR"); // NOLINT(concurrency-mt-unsafe) + bindtextdomain(GETTEXT_PACKAGE, localeDir != nullptr ? localeDir : OPENPU_LOCALEDIR); + bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); + textdomain(GETTEXT_PACKAGE); + + auto app = Gtk::Application::create("io.github.openpu.OpenPU"); + return app->make_window_and_run(argc, argv); +} diff --git a/src/ui-gtk/main_window.cpp b/src/ui-gtk/main_window.cpp new file mode 100644 index 0000000..cf01756 --- /dev/null +++ b/src/ui-gtk/main_window.cpp @@ -0,0 +1,1135 @@ +// SPDX-License-Identifier: MIT +#include "main_window.hpp" + +#include "openpu/archive.hpp" +#include "openpu/format.hpp" +#include "openpu/version.hpp" +#include "openpu/vin.hpp" + +#include +#include + +namespace openpu::gtk { + +namespace fs = std::filesystem; + +namespace { + +Gtk::Label* heading(const Glib::ustring& text) +{ + auto* l = Gtk::make_managed(); + l->set_markup("" + Glib::Markup::escape_text(text) + ""); + l->set_xalign(0); + return l; +} + +void prose(Gtk::Label& l) +{ + l.set_wrap(true); + l.set_xalign(0); + l.set_max_width_chars(60); +} + +Gtk::Box* buttonRow() +{ + auto* row = Gtk::make_managed(Gtk::Orientation::HORIZONTAL, 6); + row->set_halign(Gtk::Align::END); + row->set_valign(Gtk::Align::END); + row->set_vexpand(true); + return row; +} + +void page(Gtk::Box& box) +{ + box.set_margin(24); +} + +/// "NAC (wave 4)" style description of a head unit. +Glib::ustring headUnitText(const Vehicle& v) +{ + switch (v.type) { + case HeadUnitType::Nac: return "NAC"; + case HeadUnitType::Rcc: return "RCC"; + case HeadUnitType::Aio: return "AIO"; + case HeadUnitType::CronyNav: return _("Crony (navigation)"); + case HeadUnitType::CronyNonav: return _("Crony (no navigation)"); + case HeadUnitType::Unknown: break; + } + return _("unknown head unit"); +} + +Glib::ustring updateText(const UpdateInfo& u) +{ + return Glib::ustring::compose(_("version %1, %2"), u.version, formatSize(u.size)); +} + +Glib::ustring apiErrorText(const ApiError& e) +{ + switch (e.kind()) { + case ApiError::Kind::Network: + return _("The update server cannot be reached. Check your Internet connection."); + case ApiError::Kind::Server: + case ApiError::Kind::BadResponse: + return _("The update server returned an error. Try again later."); + case ApiError::Kind::InvalidVin: + return _("This VIN is not valid."); + } + return e.what(); +} + +bool hasPendingFiles(const Vehicle& v) +{ + return !v.pendingFirmware.empty() || !v.pendingMap.empty(); +} + +} // namespace + +// --------------------------------------------------------------------------------------------- + +MainWindow::MainWindow() + : transport_(makeCurlTransport()), + api_(std::make_unique(*transport_, ApiConfig::fromEnvironment())), + store_(paths::configDir() / "vehicles.json"), + settingsFile_(paths::configDir() / "config.json") +{ + set_title("OpenPU"); + set_default_size(640, 520); + + try { + store_.load(); + settings_ = Settings::load(settingsFile_); + } catch (const StorageError& e) { + // Keep going with empty data, but never overwrite the unreadable file silently. + Glib::signal_idle().connect_once([this, msg = std::string(e.what())] { + showError(_("Your saved data cannot be read"), msg); + }); + } + + back_.set_icon_name("go-previous-symbolic"); + back_.set_tooltip_text(_("Back")); + back_.signal_clicked().connect([this] { show("vehicles"); }); + header_.pack_start(back_); + auto menu = Gio::Menu::create(); + menu->append(_("Preferences"), "win.preferences"); + menu->append(_("Check for a new version of OpenPU"), "win.check-app-update"); + menu->append(_("About OpenPU"), "win.about"); + menu_.set_menu_model(menu); + menu_.set_icon_name("open-menu-symbolic"); + menu_.set_tooltip_text(_("Menu")); + header_.pack_end(menu_); + add_action("preferences", [this] { showPreferences(); }); + add_action("check-app-update", [this] { checkAppUpdate(true); }); + add_action("about", [this] { showAbout(); }); + set_titlebar(header_); + + stack_.set_transition_type(Gtk::StackTransitionType::SLIDE_LEFT_RIGHT); + set_child(stack_); + + buildVehiclesPage(); + buildAddPage(); + buildUpdatesPage(); + buildDownloadPage(); + buildUsbPage(); + buildWritePage(); + buildDonePage(); + + refreshVehicles(); + show("vehicles"); + + if (settings_.checkAppUpdates) + checkAppUpdate(false); + + signal_close_request().connect( + [this] { + cancel_.cancel(); + joinWorker(); + return false; + }, + false); +} + +MainWindow::~MainWindow() +{ + cancel_.cancel(); + joinWorker(); + if (updateThread_.joinable()) + updateThread_.join(); +} + +// --- OpenPU's own updates ---------------------------------------------------------------------- + +void MainWindow::checkAppUpdate(bool manual) +{ + if (updateCheckRunning_) + return; + if (updateThread_.joinable()) + updateThread_.join(); + updateCheckRunning_ = true; + updateThread_ = std::thread([this, manual] { + std::optional release; + std::string error; + try { + release = checkForNewerRelease(*transport_, AppUpdateConfig::fromEnvironment(), version()); + } catch (const std::exception& e) { + error = e.what(); + } + ui_.post([this, manual, release, error] { + updateCheckRunning_ = false; + if (release) { + offerAppUpdate(*release); + } else if (manual && error.empty()) { + auto dialog = Gtk::AlertDialog::create(_("OpenPU is up to date")); + dialog->set_detail(Glib::ustring::compose(_("Version %1 is the latest version."), version())); + dialog->show(*this); + } else if (manual) { + showError(_("Cannot check for a new version"), error); + } + // An automatic check fails silently: being offline must not bother the user. + }); + }); +} + +void MainWindow::offerAppUpdate(const AppRelease& release) +{ + auto dialog = Gtk::AlertDialog::create( + Glib::ustring::compose(_("OpenPU %1 is available"), release.version.toString())); + Glib::ustring detail = + Glib::ustring::compose(_("You are using version %1. Do you want to download the new version?"), version()); + if (!release.notes.empty()) + detail += "\n\n" + release.notes; + dialog->set_detail(detail); + dialog->set_buttons({_("Later"), _("Download")}); + dialog->set_cancel_button(0); + dialog->set_default_button(1); + dialog->choose(*this, [this, dialog, url = release.pageUrl](Glib::RefPtr& result) { + try { + if (dialog->choose_finish(result) == 1) + Gtk::UriLauncher::create(url)->launch(*this, {}); + } catch (const Glib::Error&) { + // dismissed + } + }); +} + +// --- preferences ------------------------------------------------------------------------------- + +void MainWindow::showPreferences() +{ + auto* win = new Gtk::Window(); // NOLINT(cppcoreguidelines-owning-memory): deleted after it is hidden + win->set_title(_("Preferences")); + win->set_transient_for(*this); + win->set_modal(true); + win->set_hide_on_close(true); + win->set_default_size(520, -1); + + auto* grid = Gtk::make_managed(); + grid->set_margin(24); + grid->set_row_spacing(12); + grid->set_column_spacing(12); + + // Download folder + auto* dirCaption = Gtk::make_managed(_("Download folder")); + dirCaption->set_xalign(0); + auto* dirLabel = Gtk::make_managed(settings_.effectiveDownloadDir().string()); + dirLabel->set_ellipsize(Pango::EllipsizeMode::MIDDLE); + dirLabel->set_hexpand(true); + dirLabel->set_xalign(0); + prefsDirLabel_ = dirLabel; + auto* dirButton = Gtk::make_managed(_("Change…")); + dirButton->signal_clicked().connect([this] { onChooseFolder(); }); + grid->attach(*dirCaption, 0, 0); + grid->attach(*dirLabel, 1, 0); + grid->attach(*dirButton, 2, 0); + + // Language: language names are written in their own language, on purpose. + static const std::vector> languages{ + {"", ""}, {"en", "English"}, {"fr", "Français"}}; + auto* langCaption = Gtk::make_managed(_("Language")); + langCaption->set_xalign(0); + auto names = Gtk::StringList::create({}); + guint selected = 0; + for (guint i = 0; i < languages.size(); ++i) { + names->append(i == 0 ? Glib::ustring(_("System language")) : languages[i].second); + if (languages[i].first == settings_.language) + selected = i; + } + auto* langDrop = Gtk::make_managed(names); + langDrop->set_selected(selected); + auto* restartNote = Gtk::make_managed(_("The new language is used the next time OpenPU starts.")); + restartNote->set_xalign(0); + restartNote->add_css_class("dim-label"); + restartNote->set_visible(false); + langDrop->property_selected().signal_changed().connect([this, langDrop, restartNote] { + const auto i = langDrop->get_selected(); + if (i >= languages.size()) + return; + settings_.language = languages[i].first; + restartNote->set_visible(true); + try { + settings_.save(settingsFile_); + } catch (const StorageError& e) { + showError(_("Cannot save the settings"), e.what()); + } + }); + grid->attach(*langCaption, 0, 1); + grid->attach(*langDrop, 1, 1, 2, 1); + grid->attach(*restartNote, 1, 2, 2, 1); + + // OpenPU updates + auto* check = Gtk::make_managed(_("Check for a new version of OpenPU at startup")); + check->set_active(settings_.checkAppUpdates); + check->signal_toggled().connect([this, check] { + settings_.checkAppUpdates = check->get_active(); + try { + settings_.save(settingsFile_); + } catch (const StorageError& e) { + showError(_("Cannot save the settings"), e.what()); + } + }); + grid->attach(*check, 0, 3, 3, 1); + + win->set_child(*grid); + win->signal_hide().connect([this, win] { + prefsDirLabel_ = nullptr; + // Deleting a window from its own signal handler is unsafe: do it from the main loop. + Glib::signal_idle().connect_once([win] { delete win; }); // NOLINT(cppcoreguidelines-owning-memory) + }); + win->present(); +} + +void MainWindow::show(const char* name) +{ + stack_.set_visible_child(name); + // Going back is only possible from pages that do not run anything. + const std::string n = name; + back_.set_visible(n == "add" || n == "updates" || n == "usb"); +} + +template +void MainWindow::runAsync(F&& work) +{ + joinWorker(); + cancel_.reset(); + worker_ = std::thread(std::forward(work)); +} + +void MainWindow::joinWorker() +{ + if (worker_.joinable()) + worker_.join(); +} + +void MainWindow::showError(const Glib::ustring& title, const Glib::ustring& detail) +{ + auto dialog = Gtk::AlertDialog::create(title); + dialog->set_detail(detail); + dialog->show(*this); +} + +void MainWindow::showAbout() +{ + auto* about = new Gtk::AboutDialog(); // NOLINT(cppcoreguidelines-owning-memory): freed on hide + about->set_transient_for(*this); + about->set_modal(true); + about->set_hide_on_close(true); + about->set_program_name("OpenPU"); + about->set_version(versionDescription()); + about->set_logo_icon_name("io.github.openpu.OpenPU"); + about->set_comments(_("Download Peugeot head unit updates (system and navigation map) and prepare the USB " + "stick, on Linux and Haiku.\n\nIndependent project, not affiliated with Stellantis or " + "Peugeot.")); + about->set_website("https://github.com/yann64/openpu"); + about->set_license_type(Gtk::License::MIT_X11); + about->set_copyright("© 2026 yann64 and the OpenPU contributors"); + about->set_website_label(_("Source code")); + about->signal_hide().connect([about] { + Glib::signal_idle().connect_once([about] { delete about; }); // NOLINT(cppcoreguidelines-owning-memory) + }); + about->present(); +} + +void MainWindow::saveVehicles() +{ + try { + store_.save(); + } catch (const StorageError& e) { + showError(_("Cannot save the vehicle list"), e.what()); + } +} + +std::string MainWindow::language() const +{ + return settings_.language.empty() ? systemLanguage() : settings_.language; +} + +// --- vehicles ---------------------------------------------------------------------------------- + +void MainWindow::buildVehiclesPage() +{ + page(vehiclesPage_); + vehiclesPage_.append(*heading(_("My vehicles"))); + + vehiclesEmpty_.set_text(_("Add your vehicle with its VIN (17 characters, on the registration document, field E).")); + prose(vehiclesEmpty_); + vehiclesPage_.append(vehiclesEmpty_); + + vehicleList_.set_selection_mode(Gtk::SelectionMode::SINGLE); + vehicleList_.set_activate_on_single_click(false); // double-click or Enter opens the updates + vehicleList_.add_css_class("boxed-list"); + auto* scroll = Gtk::make_managed(); + scroll->set_child(vehicleList_); + scroll->set_vexpand(true); + scroll->set_policy(Gtk::PolicyType::NEVER, Gtk::PolicyType::AUTOMATIC); + vehiclesPage_.append(*scroll); + vehicleList_.signal_row_selected().connect([this](Gtk::ListBoxRow* row) { + removeButton_.set_sensitive(row != nullptr); + checkButton_.set_sensitive(row != nullptr); + }); + vehicleList_.signal_row_activated().connect([this](Gtk::ListBoxRow*) { onCheckUpdates(); }); + + auto* row = buttonRow(); + row->set_vexpand(false); + addButton_.set_label(_("Add a vehicle")); + removeButton_.set_label(_("Remove")); + checkButton_.set_label(_("Check for updates")); + checkButton_.add_css_class("suggested-action"); + addButton_.signal_clicked().connect([this] { + vinEntry_.set_text(""); + nameEntry_.set_text(""); + addStatus_.set_text(""); + show("add"); + vinEntry_.grab_focus(); + }); + removeButton_.signal_clicked().connect([this] { onRemoveVehicle(); }); + checkButton_.signal_clicked().connect([this] { onCheckUpdates(); }); + row->append(addButton_); + row->append(removeButton_); + row->append(checkButton_); + vehiclesPage_.append(*row); + stack_.add(vehiclesPage_, "vehicles"); +} + +void MainWindow::refreshVehicles() +{ + while (auto* r = vehicleList_.get_row_at_index(0)) + vehicleList_.remove(*r); + for (const auto& v : store_.all()) { + auto* box = Gtk::make_managed(Gtk::Orientation::VERTICAL, 2); + box->set_margin(10); + auto* name = Gtk::make_managed(); + name->set_markup("" + Glib::Markup::escape_text(v.name.empty() ? v.vin : v.name) + ""); + name->set_xalign(0); + auto* detail = Gtk::make_managed(); + Glib::ustring text = v.vin + " · " + headUnitText(v); + if (hasPendingFiles(v)) + text += " · " + Glib::ustring(_("download not finished")); + detail->set_text(text); + detail->set_xalign(0); + detail->add_css_class("dim-label"); + box->append(*name); + box->append(*detail); + vehicleList_.append(*box); + } + const bool empty = store_.all().empty(); + vehiclesEmpty_.set_visible(empty); + removeButton_.set_sensitive(false); + checkButton_.set_sensitive(false); +} + +std::optional MainWindow::selectedVehicle() const +{ + const auto* row = vehicleList_.get_selected_row(); + if (row == nullptr) + return std::nullopt; + const auto index = static_cast(row->get_index()); + if (index >= store_.all().size()) + return std::nullopt; + return store_.all()[index]; +} + +void MainWindow::onRemoveVehicle() +{ + const auto v = selectedVehicle(); + if (!v) + return; + auto dialog = Gtk::AlertDialog::create(Glib::ustring::compose(_("Remove %1?"), v->name.empty() ? v->vin : v->name)); + dialog->set_detail(_("Downloaded files that were not written to a USB stick yet are deleted too.")); + dialog->set_buttons({_("Cancel"), _("Remove")}); + dialog->set_cancel_button(0); + dialog->set_default_button(0); + dialog->choose(*this, [this, dialog, vin = v->vin](Glib::RefPtr& result) { + int button = 0; + try { + button = dialog->choose_finish(result); + } catch (const Glib::Error&) { + return; + } + if (button != 1) + return; + if (const Vehicle* veh = store_.find(vin)) { + std::error_code ec; + for (const auto& f : {veh->pendingFirmware, veh->pendingMap, veh->pendingLicense}) + if (!f.empty()) + fs::remove(f, ec); + } + store_.remove(vin); + saveVehicles(); + refreshVehicles(); + }); +} + +// --- add vehicle ------------------------------------------------------------------------------- + +void MainWindow::buildAddPage() +{ + page(addPage_); + addPage_.append(*heading(_("Add a vehicle"))); + auto* help = Gtk::make_managed( + _("The VIN (vehicle identification number) is written in field E of the registration document " + "and at the bottom of the windscreen.")); + prose(*help); + addPage_.append(*help); + + auto* grid = Gtk::make_managed(); + grid->set_row_spacing(8); + grid->set_column_spacing(12); + auto* vinLabel = Gtk::make_managed(_("VIN")); + vinLabel->set_xalign(0); + auto* nameLabel = Gtk::make_managed(_("Name")); + nameLabel->set_xalign(0); + vinEntry_.set_max_length(25); + vinEntry_.set_placeholder_text("VF3…"); + vinEntry_.set_hexpand(true); + nameEntry_.set_placeholder_text(_("e.g. 208 or Family car")); + grid->attach(*vinLabel, 0, 0); + grid->attach(vinEntry_, 1, 0); + grid->attach(*nameLabel, 0, 1); + grid->attach(nameEntry_, 1, 1); + addPage_.append(*grid); + + auto* status = Gtk::make_managed(Gtk::Orientation::HORIZONTAL, 8); + status->append(addSpinner_); + prose(addStatus_); + status->append(addStatus_); + addPage_.append(*status); + + auto* row = buttonRow(); + addConfirm_.set_label(_("Add")); + addConfirm_.add_css_class("suggested-action"); + addConfirm_.signal_clicked().connect([this] { onAddVehicle(); }); + vinEntry_.signal_activate().connect([this] { nameEntry_.grab_focus(); }); + nameEntry_.signal_activate().connect([this] { onAddVehicle(); }); + vinEntry_.signal_changed().connect([this] { + addConfirm_.set_sensitive(isValidVin(normalizeVin(vinEntry_.get_text().raw()))); + }); + addConfirm_.set_sensitive(false); + row->append(addConfirm_); + addPage_.append(*row); + stack_.add(addPage_, "add"); +} + +void MainWindow::onAddVehicle() +{ + const std::string vin = normalizeVin(vinEntry_.get_text().raw()); + if (!isValidVin(vin)) { + addStatus_.set_text(_("A VIN has 17 characters and starts with VF3 or VR3.")); + return; + } + const std::string name = nameEntry_.get_text().raw(); + addConfirm_.set_sensitive(false); + addSpinner_.start(); + addStatus_.set_text(_("Checking the vehicle…")); + runAsync([this, vin, name] { + std::optional check; + Glib::ustring error; + try { + check = api_->checkVehicle(vin); + } catch (const ApiError& e) { + error = apiErrorText(e); + } + ui_.post([this, vin, name, check, error] { + addSpinner_.stop(); + addConfirm_.set_sensitive(true); + if (!check) { + addStatus_.set_text(error); + return; + } + if (!check->exists) { + addStatus_.set_text(_("This vehicle is unknown to the update service.")); + return; + } + if (check->type == HeadUnitType::Unknown) { + addStatus_.set_text(_("This vehicle has no head unit that can be updated with a USB stick.")); + return; + } + Vehicle v; + if (const Vehicle* existing = store_.find(vin)) + v = *existing; + v.vin = vin; + v.name = name.empty() ? (v.name.empty() ? vin : v.name) : name; + v.type = check->type; + v.guideKey = check->guideKey; + store_.upsert(v); + saveVehicles(); + refreshVehicles(); + show("vehicles"); + }); + }); +} + +// --- updates ----------------------------------------------------------------------------------- + +void MainWindow::buildUpdatesPage() +{ + page(updatesPage_); + updatesTitle_.set_xalign(0); + updatesPage_.append(updatesTitle_); + + auto* status = Gtk::make_managed(Gtk::Orientation::HORIZONTAL, 8); + status->append(updatesSpinner_); + prose(updatesStatus_); + status->append(updatesStatus_); + updatesPage_.append(*status); + + updatesPage_.append(firmwareCheck_); + updatesPage_.append(mapCheck_); + auto toggled = [this] { + downloadButton_.set_sensitive((firmwareCheck_.get_visible() && firmwareCheck_.get_active()) || + (mapCheck_.get_visible() && mapCheck_.get_active())); + }; + firmwareCheck_.signal_toggled().connect(toggled); + mapCheck_.signal_toggled().connect(toggled); + + auto* dirRow = Gtk::make_managed(Gtk::Orientation::HORIZONTAL, 8); + auto* dirCaption = Gtk::make_managed(_("Download folder:")); + downloadDirLabel_.set_ellipsize(Pango::EllipsizeMode::MIDDLE); + downloadDirLabel_.set_hexpand(true); + downloadDirLabel_.set_xalign(0); + chooseDir_.set_label(_("Change…")); + chooseDir_.signal_clicked().connect([this] { onChooseFolder(); }); + dirRow->append(*dirCaption); + dirRow->append(downloadDirLabel_); + dirRow->append(chooseDir_); + dirRow->set_margin_top(12); + updatesPage_.append(*dirRow); + + auto* row = buttonRow(); + guideButton_.set_label(_("Installation guide")); + guideButton_.signal_clicked().connect([this] { + if (current_) { + const std::string url = guideUrl(current_->guideKey, language()); + if (!url.empty()) + Gtk::UriLauncher::create(url)->launch(*this, {}); + } + }); + downloadButton_.set_label(_("Download")); + downloadButton_.add_css_class("suggested-action"); + downloadButton_.signal_clicked().connect([this] { onStartDownload(); }); + row->append(guideButton_); + row->append(downloadButton_); + updatesPage_.append(*row); + stack_.add(updatesPage_, "updates"); +} + +void MainWindow::updateDownloadDirLabel() // also refreshes the open preferences window +{ + downloadDirLabel_.set_text(settings_.effectiveDownloadDir().string()); + if (prefsDirLabel_ != nullptr) + prefsDirLabel_->set_text(settings_.effectiveDownloadDir().string()); +} + +void MainWindow::onCheckUpdates() +{ + const auto selected = selectedVehicle(); + if (!selected) + return; + const Vehicle& vehicle = *selected; + current_ = vehicle; + updatesTitle_.set_markup("" + + Glib::Markup::escape_text(vehicle.name.empty() ? vehicle.vin : vehicle.name) + + " " + Glib::Markup::escape_text(headUnitText(vehicle))); + updatesStatus_.set_text(_("Looking for updates…")); + updatesSpinner_.start(); + firmwareCheck_.set_visible(false); + mapCheck_.set_visible(false); + downloadButton_.set_sensitive(false); + guideButton_.set_visible(!guideUrl(vehicle.guideKey, language()).empty()); + updateDownloadDirLabel(); + show("updates"); + + runAsync([this, vin = vehicle.vin, type = vehicle.type] { + std::optional updates; + Glib::ustring error; + try { + updates = api_->getUpdates(vin, type); + } catch (const ApiError& e) { + error = apiErrorText(e); + } + ui_.post([this, vin, updates, error] { + if (!current_ || current_->vin != vin) + return; // the user went back and picked another vehicle meanwhile + updatesSpinner_.stop(); + if (!updates) { + updatesStatus_.set_text(error); + return; + } + showUpdates(*updates); + }); + }); +} + +void MainWindow::showUpdates(const AvailableUpdates& updates) +{ + updates_ = updates; + if (!updates.firmware && !updates.map) { + updatesStatus_.set_text(_("No update is available: your head unit is up to date.")); + return; + } + updatesStatus_.set_text(_("Select the updates to download:")); + if (updates.firmware) { + firmwareCheck_.set_label(Glib::ustring(_("System (firmware)")) + " — " + updateText(*updates.firmware)); + firmwareCheck_.set_active(true); + firmwareCheck_.set_visible(true); + } + if (updates.map) { + mapCheck_.set_label(Glib::ustring(_("Navigation map")) + " — " + updateText(*updates.map)); + mapCheck_.set_active(true); + mapCheck_.set_visible(true); + } + downloadButton_.set_sensitive(true); +} + +void MainWindow::onChooseFolder() +{ + auto dialog = Gtk::FileDialog::create(); + dialog->set_title(_("Download folder")); + dialog->set_initial_folder(Gio::File::create_for_path(settings_.effectiveDownloadDir().parent_path().string())); + dialog->select_folder(*this, [this, dialog](Glib::RefPtr& result) { + try { + const auto folder = dialog->select_folder_finish(result); + if (!folder) + return; + settings_.downloadDir = folder->get_path(); + settings_.save(settingsFile_); + updateDownloadDirLabel(); + } catch (const Glib::Error&) { + // dismissed + } catch (const StorageError& e) { + showError(_("Cannot save the settings"), e.what()); + } + }); +} + +void MainWindow::onStartDownload() +{ + DownloadPlan plan; + if (firmwareCheck_.get_visible() && firmwareCheck_.get_active()) + plan.firmware = updates_.firmware; + if (mapCheck_.get_visible() && mapCheck_.get_active()) + plan.map = updates_.map; + plan.dir = settings_.effectiveDownloadDir(); + + std::error_code ec; + fs::create_directories(plan.dir, ec); + const auto space = fs::space(plan.dir, ec); + if (!ec && space.available < plan.requiredSpace()) { + auto dialog = Gtk::AlertDialog::create(_("Not enough free space")); + dialog->set_detail(Glib::ustring::compose( + _("%1 are needed in %2 but only %3 are free. If a previous download of these files is already in this " + "folder, it will be resumed and may fit."), + formatSize(plan.requiredSpace()), plan.dir.string(), formatSize(space.available))); + dialog->set_buttons({_("Cancel"), _("Download anyway")}); + dialog->set_cancel_button(0); + dialog->set_default_button(0); + dialog->choose(*this, [this, dialog, plan](Glib::RefPtr& result) { + try { + if (dialog->choose_finish(result) == 1) + startDownload(plan); + } catch (const Glib::Error&) { + // dismissed + } + }); + return; + } + startDownload(plan); +} + +// --- download ---------------------------------------------------------------------------------- + +void MainWindow::buildDownloadPage() +{ + page(downloadPage_); + downloadTitle_.set_xalign(0); + downloadPage_.append(*heading(_("Downloading"))); + auto* note = Gtk::make_managed( + _("You can close the application: the download will resume where it stopped next time.")); + prose(*note); + note->add_css_class("dim-label"); + downloadPage_.append(*note); + + for (auto* l : {&licenseLabel_, &firmwareLabel_, &mapLabel_}) { + l->set_xalign(0); + l->set_margin_top(8); + } + firmwareBar_.set_show_text(true); + mapBar_.set_show_text(true); + downloadPage_.append(licenseLabel_); + downloadPage_.append(firmwareLabel_); + downloadPage_.append(firmwareBar_); + downloadPage_.append(mapLabel_); + downloadPage_.append(mapBar_); + etaLabel_.set_xalign(0); + etaLabel_.set_margin_top(8); + downloadPage_.append(etaLabel_); + + auto* row = buttonRow(); + cancelDownload_.set_label(_("Stop")); + cancelDownload_.signal_clicked().connect([this] { + cancel_.cancel(); + cancelDownload_.set_sensitive(false); + }); + row->append(cancelDownload_); + downloadPage_.append(*row); + stack_.add(downloadPage_, "download"); +} + +void MainWindow::startDownload(const DownloadPlan& plan) +{ + licenseLabel_.set_visible(plan.firmware.has_value() && !plan.firmware->licenseUrl.empty()); + licenseLabel_.set_text(Glib::ustring(_("License")) + " — " + _("waiting")); + firmwareLabel_.set_visible(plan.firmware.has_value()); + firmwareBar_.set_visible(plan.firmware.has_value()); + if (plan.firmware) + firmwareLabel_.set_text(Glib::ustring(_("System (firmware)")) + " — " + updateText(*plan.firmware)); + mapLabel_.set_visible(plan.map.has_value()); + mapBar_.set_visible(plan.map.has_value()); + if (plan.map) + mapLabel_.set_text(Glib::ustring(_("Navigation map")) + " — " + updateText(*plan.map)); + firmwareBar_.set_fraction(0); + mapBar_.set_fraction(0); + firmwareBar_.set_text(""); + mapBar_.set_text(""); + etaLabel_.set_text(_("Connecting…")); + cancelDownload_.set_sensitive(true); + show("download"); + + runAsync([this, plan] { + Downloader downloader(*transport_); + std::optional files; + Glib::ustring error; + bool cancelled = false; + try { + files = downloadUpdates( + downloader, plan, [this](const JobProgress& p) { ui_.post([this, p] { onDownloadProgress(p); }); }, + &cancel_); + } catch (const Cancelled&) { + cancelled = true; + } catch (const DownloadError& e) { + error = e.kind() == DownloadError::Kind::Disk + ? Glib::ustring::compose(_("Cannot write the file: %1"), e.what()) + : Glib::ustring::compose(_("The download failed: %1"), e.what()); + } + ui_.post([this, files, error, cancelled] { + if (files) { + onDownloaded(*files); + return; + } + // Partial files stay in the download folder; the next download resumes them. + if (!cancelled) + showError(_("Download interrupted"), + error + "\n\n" + _("The files already downloaded are kept; start again to resume.")); + show("vehicles"); + }); + }); +} + +void MainWindow::onDownloadProgress(const JobProgress& p) +{ + if (p.item == DownloadItem::License) { + licenseLabel_.set_text(Glib::ustring(_("License")) + " — " + _("done")); + return; + } + Gtk::ProgressBar& bar = p.item == DownloadItem::Firmware ? firmwareBar_ : mapBar_; + const auto& d = p.progress; + const double fraction = d.total > 0 ? static_cast(d.done) / static_cast(d.total) : 0.0; + bar.set_fraction(fraction); + bar.set_text(formatSize(d.done) + " / " + formatSize(d.total)); + Glib::ustring eta; + if (const auto remaining = d.remaining()) + eta = Glib::ustring::compose(_("Time left: %1"), formatDuration(*remaining)); + if (d.attempt > 0) + eta += " " + Glib::ustring::compose(_("(connection lost, attempt %1)"), d.attempt); + etaLabel_.set_text(eta); +} + +void MainWindow::onDownloaded(const DownloadedFiles& files) +{ + files_ = files; + if (current_) { + Vehicle v = *current_; + v.pendingFirmware = files.firmware ? files.firmware->string() : ""; + v.pendingMap = files.map ? files.map->string() : ""; + v.pendingLicense = files.license ? files.license->string() : ""; + current_ = v; + store_.upsert(v); + saveVehicles(); + refreshVehicles(); + } + enterUsbPage(); +} + +// --- USB --------------------------------------------------------------------------------------- + +void MainWindow::buildUsbPage() +{ + page(usbPage_); + usbPage_.append(*heading(_("Prepare the USB stick"))); + prose(usbInfo_); + usbPage_.append(usbInfo_); + + driveModel_ = Gtk::StringList::create({}); + driveDrop_.set_model(driveModel_); + driveDrop_.set_hexpand(true); + driveDrop_.property_selected().signal_changed().connect([this] { + const auto i = driveDrop_.get_selected(); + const bool ok = i < drives_.size() && drives_[i].size >= withMargin(payload_); + prepareButton_.set_sensitive(ok); + usbStatus_.set_text(i < drives_.size() && !ok ? _("This USB stick is too small.") : ""); + }); + auto* driveRow = Gtk::make_managed(Gtk::Orientation::HORIZONTAL, 8); + refreshDrives_.set_icon_name("view-refresh-symbolic"); + refreshDrives_.set_tooltip_text(_("Refresh")); + refreshDrives_.signal_clicked().connect([this] { refreshDrives(); }); + driveRow->append(driveDrop_); + driveRow->append(refreshDrives_); + usbPage_.append(*driveRow); + prose(usbStatus_); + usbPage_.append(usbStatus_); + + auto* row = buttonRow(); + prepareButton_.set_label(_("Erase and write")); + prepareButton_.add_css_class("destructive-action"); + prepareButton_.signal_clicked().connect([this] { onPrepareUsb(); }); + row->append(prepareButton_); + usbPage_.append(*row); + stack_.add(usbPage_, "usb"); +} + +void MainWindow::enterUsbPage() +{ + usbInfo_.set_text(_("Computing the required size…")); + prepareButton_.set_sensitive(false); + show("usb"); + const UsbWritePlan plan = files_.writePlan(); + runAsync([this, plan] { + std::uint64_t size = 0; + Glib::ustring error; + try { + size = plan.payloadSize(); + } catch (const ArchiveError& e) { + error = e.what(); + } + ui_.post([this, size, error] { + if (!error.empty()) { + showError(_("A downloaded file is damaged"), error + "\n\n" + _("Download the update again.")); + files_.remove(); + show("vehicles"); + return; + } + payload_ = size; + usbInfo_.set_text(Glib::ustring::compose( + _("Plug in a USB stick of at least %1. It will be completely erased and formatted (FAT32)."), + std::to_string(minimumStickSize(size) / 1000000000ULL) + " GB")); + refreshDrives(); + }); + }); +} + +void MainWindow::refreshDrives() +{ + drives_.clear(); + try { + if (!usb_) + usb_ = makeUsbBackend(); + drives_ = usb_->list(); + } catch (const UsbError& e) { + usbStatus_.set_text(Glib::ustring(_("USB drives cannot be listed: ")) + e.what()); + } + std::vector names; + names.reserve(drives_.size()); + for (const auto& d : drives_) + names.emplace_back(d.description() + (d.size < withMargin(payload_) ? " — " + Glib::ustring(_("too small")) : "")); + driveModel_->splice(0, driveModel_->get_n_items(), names); + if (drives_.empty()) { + usbStatus_.set_text(_("No USB stick found. Plug one in, then refresh.")); + prepareButton_.set_sensitive(false); + } else { + driveDrop_.set_selected(0); + const bool ok = drives_[0].size >= withMargin(payload_); + prepareButton_.set_sensitive(ok); + usbStatus_.set_text(ok ? "" : _("This USB stick is too small.")); + } +} + +void MainWindow::onPrepareUsb() +{ + const auto i = driveDrop_.get_selected(); + if (i >= drives_.size()) + return; + const UsbDrive drive = drives_[i]; + auto dialog = Gtk::AlertDialog::create(Glib::ustring::compose(_("Erase %1?"), drive.description())); + dialog->set_detail(_("Everything on this USB stick will be lost.")); + dialog->set_buttons({_("Cancel"), _("Erase and write")}); + dialog->set_cancel_button(0); + dialog->set_default_button(0); + dialog->choose(*this, [this, dialog, drive](Glib::RefPtr& result) { + try { + if (dialog->choose_finish(result) == 1) + startWrite(drive); + } catch (const Glib::Error&) { + // dismissed + } + }); +} + +// --- writing ----------------------------------------------------------------------------------- + +void MainWindow::buildWritePage() +{ + page(writePage_); + writePage_.append(*heading(_("Writing the USB stick"))); + auto* note = Gtk::make_managed(_("Do not unplug the USB stick.")); + prose(*note); + writePage_.append(*note); + writeStep_.set_xalign(0); + writeStep_.set_margin_top(12); + writeBar_.set_show_text(true); + writeDetail_.set_xalign(0); + writeDetail_.set_ellipsize(Pango::EllipsizeMode::START); + writeDetail_.add_css_class("dim-label"); + writePage_.append(writeStep_); + writePage_.append(writeBar_); + writePage_.append(writeDetail_); + auto* row = buttonRow(); + cancelWrite_.set_label(_("Stop")); + cancelWrite_.signal_clicked().connect([this] { + cancel_.cancel(); + cancelWrite_.set_sensitive(false); + }); + row->append(cancelWrite_); + writePage_.append(*row); + stack_.add(writePage_, "write"); +} + +void MainWindow::startWrite(const UsbDrive& drive) +{ + writeStep_.set_text(_("Checking the downloaded files…")); + writeBar_.set_fraction(0); + writeBar_.set_text(""); + writeDetail_.set_text(""); + cancelWrite_.set_sensitive(true); + show("write"); + const UsbWritePlan plan = files_.writePlan(); + runAsync([this, drive, plan] { + Glib::ustring error; + bool cancelled = false; + bool corrupt = false; + try { + writeToUsb(*usb_, drive, drive.label, plan, + [this](const UsbProgress& p) { ui_.post([this, p] { onWriteProgress(p); }); }, &cancel_); + } catch (const Cancelled&) { + cancelled = true; + } catch (const ArchiveError& e) { + corrupt = e.kind() == ArchiveError::Kind::Corrupt; + error = e.what(); + } catch (const UsbError& e) { + error = e.kind() == UsbError::Kind::NotAuthorized ? Glib::ustring(_("Permission to format the USB stick was refused.")) + : Glib::ustring(e.what()); + } + ui_.post([this, error, cancelled, corrupt] { + if (error.empty() && !cancelled) { + onWritten(); + return; + } + if (corrupt) { + showError(_("A downloaded file is damaged"), error + "\n\n" + _("Download the update again.")); + files_.remove(); + show("vehicles"); + return; + } + if (!cancelled) + showError(_("The USB stick could not be prepared"), error); + enterUsbPage(); + }); + }); +} + +void MainWindow::onWriteProgress(const UsbProgress& p) +{ + const Glib::ustring count = + p.archiveCount > 1 ? Glib::ustring::compose(" (%1/%2)", p.archiveIndex + 1, p.archiveCount) : Glib::ustring(); + switch (p.step) { + case UsbStep::Verifying: writeStep_.set_text(_("Checking the downloaded files…") + count); break; + case UsbStep::Formatting: + writeStep_.set_text(_("Formatting the USB stick…")); + writeBar_.pulse(); + return; + case UsbStep::CopyingLicense: writeStep_.set_text(_("Copying the license…")); return; + case UsbStep::Extracting: writeStep_.set_text(_("Copying the update…") + count); break; + case UsbStep::Ejecting: + writeStep_.set_text(_("Ejecting the USB stick…")); + writeBar_.set_fraction(1); + return; + case UsbStep::Done: return; + } + if (p.total > 0) { + writeBar_.set_fraction(static_cast(p.done) / static_cast(p.total)); + writeBar_.set_text(formatSize(p.done) + " / " + formatSize(p.total)); + } + writeDetail_.set_text(p.detail); +} + +void MainWindow::onWritten() +{ + files_.remove(); // same as the official app: the files are on the stick now + files_ = {}; + if (current_) { + Vehicle v = *current_; + v.pendingFirmware.clear(); + v.pendingMap.clear(); + v.pendingLicense.clear(); + store_.upsert(v); + saveVehicles(); + refreshVehicles(); + } + show("done"); +} + +void MainWindow::buildDonePage() +{ + page(donePage_); + donePage_.append(*heading(_("The USB stick is ready"))); + doneText_.set_text( + _("You can unplug the USB stick. With the engine running, plug it into the vehicle and follow the " + "instructions on the screen. The installation can take a long time: do not stop the engine.")); + prose(doneText_); + donePage_.append(doneText_); + auto* row = buttonRow(); + doneGuide_.set_label(_("Installation guide")); + doneGuide_.signal_clicked().connect([this] { + if (current_) { + const std::string url = guideUrl(current_->guideKey, language()); + if (!url.empty()) + Gtk::UriLauncher::create(url)->launch(*this, {}); + } + }); + doneButton_.set_label(_("Finish")); + doneButton_.add_css_class("suggested-action"); + doneButton_.signal_clicked().connect([this] { show("vehicles"); }); + row->append(doneGuide_); + row->append(doneButton_); + donePage_.append(*row); + stack_.add(donePage_, "done"); +} + +} // namespace openpu::gtk diff --git a/src/ui-gtk/main_window.hpp b/src/ui-gtk/main_window.hpp new file mode 100644 index 0000000..78ccea6 --- /dev/null +++ b/src/ui-gtk/main_window.hpp @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT +#pragma once + +#include "ui_queue.hpp" + +#include "openpu/api_client.hpp" +#include "openpu/app_update.hpp" +#include "openpu/job.hpp" +#include "openpu/storage.hpp" +#include "openpu/usb.hpp" + +#include +#include +#include +#include + +namespace openpu::gtk { + +class MainWindow : public Gtk::ApplicationWindow { +public: + MainWindow(); + ~MainWindow() override; + MainWindow(const MainWindow&) = delete; + MainWindow& operator=(const MainWindow&) = delete; + +private: + // pages + void buildVehiclesPage(); + void buildAddPage(); + void buildUpdatesPage(); + void buildDownloadPage(); + void buildUsbPage(); + void buildWritePage(); + void buildDonePage(); + void show(const char* page); + + // vehicles + void refreshVehicles(); + std::optional selectedVehicle() const; + void onAddVehicle(); + void onRemoveVehicle(); + void onCheckUpdates(); + + // updates / download + void showUpdates(const AvailableUpdates& updates); + void onChooseFolder(); + void onStartDownload(); + void startDownload(const DownloadPlan& plan); + void onDownloadProgress(const JobProgress& p); + void onDownloaded(const DownloadedFiles& files); + + // usb + void enterUsbPage(); + void refreshDrives(); + void onPrepareUsb(); + void startWrite(const UsbDrive& drive); + void onWriteProgress(const UsbProgress& p); + void onWritten(); + + // helpers + template + void runAsync(F&& work); + void joinWorker(); + void showError(const Glib::ustring& title, const Glib::ustring& detail); + void showAbout(); + void showPreferences(); + void checkAppUpdate(bool manual); + void offerAppUpdate(const AppRelease& release); + void saveVehicles(); + void updateDownloadDirLabel(); + std::string language() const; + + UiQueue ui_; + std::unique_ptr transport_; + std::unique_ptr api_; + std::unique_ptr usb_; + VehicleStore store_; + Settings settings_; + std::filesystem::path settingsFile_; + std::thread worker_; + std::thread updateThread_; // OpenPU new-version check, independent of the main flow + bool updateCheckRunning_ = false; + CancelToken cancel_; + + // flow state + std::optional current_; + AvailableUpdates updates_; + DownloadedFiles files_; + std::vector drives_; + std::uint64_t payload_ = 0; + + // widgets + Gtk::HeaderBar header_; + Gtk::Button back_; + Gtk::MenuButton menu_; + Gtk::Label* prefsDirLabel_ = nullptr; // download folder shown in the open preferences window + Gtk::Stack stack_; + + Gtk::Box vehiclesPage_{Gtk::Orientation::VERTICAL, 12}; + Gtk::ListBox vehicleList_; + Gtk::Label vehiclesEmpty_; + Gtk::Button addButton_, removeButton_, checkButton_; + + Gtk::Box addPage_{Gtk::Orientation::VERTICAL, 12}; + Gtk::Entry vinEntry_, nameEntry_; + Gtk::Label addStatus_; + Gtk::Spinner addSpinner_; + Gtk::Button addConfirm_; + + Gtk::Box updatesPage_{Gtk::Orientation::VERTICAL, 12}; + Gtk::Label updatesTitle_, updatesStatus_; + Gtk::Spinner updatesSpinner_; + Gtk::CheckButton firmwareCheck_, mapCheck_; + Gtk::Label downloadDirLabel_; + Gtk::Button chooseDir_, downloadButton_, guideButton_; + + Gtk::Box downloadPage_{Gtk::Orientation::VERTICAL, 12}; + Gtk::Label downloadTitle_; + Gtk::Label licenseLabel_, firmwareLabel_, mapLabel_; + Gtk::ProgressBar firmwareBar_, mapBar_; + Gtk::Label etaLabel_; + Gtk::Button cancelDownload_; + + Gtk::Box usbPage_{Gtk::Orientation::VERTICAL, 12}; + Gtk::Label usbInfo_; + Gtk::DropDown driveDrop_; + Glib::RefPtr driveModel_; + Gtk::Button refreshDrives_, prepareButton_; + Gtk::Label usbStatus_; + + Gtk::Box writePage_{Gtk::Orientation::VERTICAL, 12}; + Gtk::Label writeStep_, writeDetail_; + Gtk::ProgressBar writeBar_; + Gtk::Button cancelWrite_; + + Gtk::Box donePage_{Gtk::Orientation::VERTICAL, 12}; + Gtk::Label doneText_; + Gtk::Button doneGuide_, doneButton_; +}; + +} // namespace openpu::gtk diff --git a/src/ui-gtk/ui_queue.hpp b/src/ui-gtk/ui_queue.hpp new file mode 100644 index 0000000..1cf6553 --- /dev/null +++ b/src/ui-gtk/ui_queue.hpp @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT +#pragma once + +#include +#include +#include +#include + +namespace openpu::gtk { + +/// Runs closures posted from worker threads on the GTK main loop. +/// Must be constructed on the main thread (Glib::Dispatcher requirement). +class UiQueue { +public: + UiQueue() { dispatcher_.connect([this] { drain(); }); } + + void post(std::function fn) + { + { + std::scoped_lock lock(mutex_); + queue_.push_back(std::move(fn)); + } + dispatcher_.emit(); + } + +private: + void drain() + { + std::deque> local; + { + std::scoped_lock lock(mutex_); + local.swap(queue_); + } + for (auto& fn : local) + fn(); + } + + Glib::Dispatcher dispatcher_; + std::mutex mutex_; + std::deque> queue_; +}; + +} // namespace openpu::gtk diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0f0c314..6f2b9c5 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,6 +10,7 @@ add_executable(openpu_tests test_archive.cpp test_storage.cpp test_usb.cpp + test_app_update.cpp ) find_package(LibArchive REQUIRED) target_link_libraries(openpu_tests PRIVATE openpu_core openpu_warnings LibArchive::LibArchive) diff --git a/tests/main.cpp b/tests/main.cpp index 0a3f254..5d46854 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -1,2 +1,3 @@ +// SPDX-License-Identifier: MIT #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include diff --git a/tests/test_api_client.cpp b/tests/test_api_client.cpp index 5754125..87d3462 100644 --- a/tests/test_api_client.cpp +++ b/tests/test_api_client.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/api_client.hpp" #include diff --git a/tests/test_app_update.cpp b/tests/test_app_update.cpp new file mode 100644 index 0000000..4f71eaf --- /dev/null +++ b/tests/test_app_update.cpp @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT +#include "openpu/app_update.hpp" +#include "openpu/models.hpp" +#include "openpu/version.hpp" + +#include + +using namespace openpu; + +namespace { + +class OneShot final : public Transport { +public: + HttpResponse response; + std::string url; + HttpResponse perform(const HttpRequest& req) override + { + url = req.url; + return response; + } +}; + +const char* const kTags = R"([ + {"name":"v0.1.0","message":"OpenPU 0.1.0\n\nfirst"}, + {"name":"v0.10.0","message":"OpenPU 0.10.0"}, + {"name":"v0.2.0","message":"OpenPU 0.2.0"}, + {"name":"v1.0.0-rc1","message":"pre-release, ignored"}, + {"name":"experiment","message":"not a version"} +])"; + +} // namespace + +TEST_CASE("semantic versions") +{ + CHECK(SemVer::parse("1.2.3").value() == SemVer{1, 2, 3}); + CHECK(SemVer::parse("v0.10.0").value() == SemVer{0, 10, 0}); + CHECK(SemVer::parse("0.2.0+3.g1a2b3c4.dirty").value() == SemVer{0, 2, 0}); + CHECK_FALSE(SemVer::parse("1.2").has_value()); + CHECK_FALSE(SemVer::parse("1.2.3-rc1").has_value()); + CHECK_FALSE(SemVer::parse("a.b.c").has_value()); + CHECK(SemVer{0, 9, 9} < SemVer{0, 10, 0}); // numeric, not lexical + CHECK(SemVer{1, 0, 0}.toString() == "1.0.0"); + // The build's own version must be valid, or the update check could never work. + CHECK(SemVer::parse(version()).has_value()); + CHECK(SemVer::parse(versionDescription()).has_value()); +} + +TEST_CASE("latest release is the highest vX.Y.Z tag") +{ + AppUpdateConfig cfg; + cfg.pageUrl = "https://example.test/releases/tag/{tag}"; + const auto r = latestRelease(kTags, cfg); + REQUIRE(r.has_value()); + CHECK(r->tag == "v0.10.0"); + CHECK(r->pageUrl == "https://example.test/releases/tag/v0.10.0"); + CHECK(r->notes == "OpenPU 0.10.0"); + CHECK_FALSE(latestRelease("[]", cfg).has_value()); + CHECK_THROWS_AS(latestRelease("{}", cfg), ParseError); +} + +TEST_CASE("GitHub releases: html_url and body, drafts and pre-releases skipped") +{ + const char* releases = R"([ + {"tag_name":"v0.3.0","draft":true,"prerelease":false,"html_url":"https://gh/d","body":"draft"}, + {"tag_name":"v0.2.1","draft":false,"prerelease":true,"html_url":"https://gh/p","body":"pre"}, + {"tag_name":"v0.2.0","draft":false,"prerelease":false,"html_url":"https://gh/r/v0.2.0","body":"notes"}, + {"tag_name":"v0.1.0","draft":false,"prerelease":false,"html_url":"https://gh/r/v0.1.0","body":"old"} + ])"; + const auto r = latestRelease(releases, AppUpdateConfig{}); + REQUIRE(r.has_value()); + CHECK(r->tag == "v0.2.0"); + CHECK(r->pageUrl == "https://gh/r/v0.2.0"); + CHECK(r->notes == "notes"); +} + +TEST_CASE("newer release detection") +{ + OneShot t; + t.response.status = 200; + t.response.body = kTags; + AppUpdateConfig cfg; + cfg.releasesUrl = "https://example.test/tags"; + const auto newer = checkForNewerRelease(t, cfg, "0.2.0"); + REQUIRE(newer.has_value()); + CHECK(newer->version == SemVer{0, 10, 0}); + CHECK(t.url == "https://example.test/tags"); + CHECK_FALSE(checkForNewerRelease(t, cfg, "0.10.0").has_value()); + CHECK_FALSE(checkForNewerRelease(t, cfg, "1.0.0").has_value()); + t.response.status = 404; + CHECK_THROWS(checkForNewerRelease(t, cfg, "0.1.0")); +} diff --git a/tests/test_archive.cpp b/tests/test_archive.cpp index 123d392..8881bf9 100644 --- a/tests/test_archive.cpp +++ b/tests/test_archive.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/archive.hpp" #include "test_util.hpp" diff --git a/tests/test_download.cpp b/tests/test_download.cpp index e098260..7aacbca 100644 --- a/tests/test_download.cpp +++ b/tests/test_download.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/download.hpp" #include "test_util.hpp" diff --git a/tests/test_http.cpp b/tests/test_http.cpp index 6f776a7..c1c1932 100644 --- a/tests/test_http.cpp +++ b/tests/test_http.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/http.hpp" #include diff --git a/tests/test_models.cpp b/tests/test_models.cpp index 9479ad0..8a2b4cb 100644 --- a/tests/test_models.cpp +++ b/tests/test_models.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/models.hpp" #include diff --git a/tests/test_storage.cpp b/tests/test_storage.cpp index 6ba2890..50977c2 100644 --- a/tests/test_storage.cpp +++ b/tests/test_storage.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/storage.hpp" #include "test_util.hpp" @@ -91,6 +92,11 @@ TEST_CASE("settings round trip") CHECK(r.pending->firmware); CHECK_FALSE(r.pending->map); CHECK(r.pending->licenseFile == "license_X.key"); + CHECK(r.checkAppUpdates); // default + + s.checkAppUpdates = false; + s.save(file); + CHECK_FALSE(Settings::load(file).checkAppUpdates); } TEST_CASE("XDG paths") diff --git a/tests/test_usb.cpp b/tests/test_usb.cpp index d48debb..6c8fae4 100644 --- a/tests/test_usb.cpp +++ b/tests/test_usb.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/archive.hpp" #include "openpu/usb.hpp" @@ -150,3 +151,31 @@ TEST_CASE("drive description") d.size = 32000000000ULL; CHECK(d.description() == "SanDisk Ultra (/dev/sdb, 32.0 GB)"); } + +#include "openpu/job.hpp" + +TEST_CASE("installation guide links") +{ + CHECK(guideUrl("path_guide_rcc", "fr").find("map-software-rcc-fr") != std::string::npos); + CHECK(guideUrl("path_guide_wave_4", "fr").find("map-software-nac-fr") != std::string::npos); + CHECK(guideUrl("path_guide_wave_default", "de").find("map-software-nac-en") != std::string::npos); + CHECK(guideUrl("path_guide_aio", "en").find("map-software-iao") != std::string::npos); + CHECK(guideUrl("path_guide_crony_2", "fr") == "https://www.stellantis.com/"); + CHECK(guideUrl("", "fr").empty()); +} + +TEST_CASE("downloaded files give the write plan in the official order") +{ + DownloadedFiles f; + f.license = fs::path("/dl/license_X.key"); + f.firmware = fs::path("/dl/fw.tar"); + f.map = fs::path("/dl/map.tar"); + auto plan = f.writePlan(); + REQUIRE(plan.license.has_value()); + CHECK(plan.archives == std::vector{"/dl/fw.tar", "/dl/map.tar"}); + + f.firmware.reset(); // map only: the license is not copied + plan = f.writePlan(); + CHECK_FALSE(plan.license.has_value()); + CHECK(plan.archives == std::vector{"/dl/map.tar"}); +} diff --git a/tests/test_util.hpp b/tests/test_util.hpp index dbb6885..6aa3c1b 100644 --- a/tests/test_util.hpp +++ b/tests/test_util.hpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #pragma once #include diff --git a/tests/test_vin.cpp b/tests/test_vin.cpp index ab0b823..6f2c859 100644 --- a/tests/test_vin.cpp +++ b/tests/test_vin.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: MIT #include "openpu/vin.hpp" #include diff --git a/tools/asar_extract.py b/tools/asar_extract.py index f4ac0fb..d231b0d 100644 --- a/tools/asar_extract.py +++ b/tools/asar_extract.py @@ -1,3 +1,4 @@ +# SPDX-License-Identifier: MIT """Minimal read-only asar extractor: copies selected files out of an asar archive. usage: python -I asar_extract.py [prefix ...] diff --git a/tools/check.sh b/tools/check.sh index 8160821..b635998 100644 --- a/tools/check.sh +++ b/tools/check.sh @@ -1,4 +1,5 @@ #!/bin/sh +# SPDX-License-Identifier: MIT # Full local quality gate: build + tests, ASan/UBSan tests, valgrind, clang-tidy, cppcheck. # usage: tools/check.sh [build-root] (default: ~/build/openpu-check) set -eu @@ -27,10 +28,22 @@ fi if command -v clang-tidy >/dev/null; then step "clang-tidy" # Only our sources; compile_commands.json comes from the debug build. - find "$SRC/src" -name '*.cpp' -print0 | + find "$SRC/src" -name '*.cpp' -not -path '*/ui-*' -print0 | xargs -0 clang-tidy -p "$OUT/debug" --quiet --warnings-as-errors='*' fi +if pkg-config --exists gtkmm-4.0; then + step "GTK user interface build" + cmake -S "$SRC" -B "$OUT/gtk" -G Ninja -DCMAKE_BUILD_TYPE=Debug -DOPENPU_WERROR=ON -DOPENPU_UI_GTK=ON \ + -DOPENPU_BUILD_TESTS=OFF >/dev/null + cmake --build "$OUT/gtk" + if command -v clang-tidy >/dev/null; then + step "clang-tidy (GTK user interface)" + find "$SRC/src/ui-gtk" -name '*.cpp' -print0 | + xargs -0 clang-tidy -p "$OUT/gtk" --quiet --warnings-as-errors='*' + fi +fi + if command -v cppcheck >/dev/null; then step "cppcheck" cppcheck --quiet --error-exitcode=1 --std=c++17 --enable=warning,performance,portability \ diff --git a/tools/dev-polkit.sh b/tools/dev-polkit.sh index f5a14fd..58f60d8 100644 --- a/tools/dev-polkit.sh +++ b/tools/dev-polkit.sh @@ -1,4 +1,5 @@ #!/bin/sh +# SPDX-License-Identifier: MIT # DEVELOPMENT ONLY (WSL / test VM): lets the invoking user run UDisks2 operations # (loop-setup, format, mount, power-off) without a polkit agent, so that the end-to-end # USB tests can run headless. Never install this on a real desktop machine. diff --git a/tools/e2e-usb.sh b/tools/e2e-usb.sh index 59f0063..0880be3 100644 --- a/tools/e2e-usb.sh +++ b/tools/e2e-usb.sh @@ -1,4 +1,5 @@ #!/bin/sh +# SPDX-License-Identifier: MIT # End-to-end USB test on Linux without a real stick: a sparse disk image is attached as a loop # device through UDisks2, `openpu-cli write-usb` formats and fills it, then the result is checked # with sfdisk / fsck.fat / mtools. Needs udisks2, dosfstools, mtools and, in a session without a diff --git a/tools/extract_strings.py b/tools/extract_strings.py new file mode 100644 index 0000000..230a687 --- /dev/null +++ b/tools/extract_strings.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: MIT +"""Fallback string extractor when xgettext is not available. + +Collects _("...") calls (with adjacent literal concatenation) from C++ sources and writes a +gettext template. Prefer `cmake --build --target pot` (xgettext) when gettext is installed. + +usage: python3 tools/extract_strings.py po/openpu.pot src/ui-gtk/main_window.cpp ... +""" +import re +import sys + +CALL = re.compile(r'\b_\(\s*((?:"(?:[^"\\]|\\.)*"\s*)+)\)', re.S) +LITERAL = re.compile(r'"((?:[^"\\]|\\.)*)"') + + +def main(): + out, *sources = sys.argv[1:] + seen = {} + for path in sources: + text = open(path, encoding="utf-8").read() + for m in CALL.finditer(text): + msgid = "".join(LITERAL.findall(m.group(1))) + line = text.count("\n", 0, m.start()) + 1 + seen.setdefault(msgid, []).append(f"{path}:{line}") + with open(out, "w", encoding="utf-8", newline="\n") as f: + f.write('msgid ""\nmsgstr ""\n"Project-Id-Version: openpu\\n"\n' + '"Content-Type: text/plain; charset=UTF-8\\n"\n"Content-Transfer-Encoding: 8bit\\n"\n') + for msgid, refs in seen.items(): + f.write("\n#: " + " ".join(refs) + "\n") + if "%1" in msgid: + f.write("#, qt-format\n") + f.write(f'msgid "{msgid}"\nmsgstr ""\n') + print(f"{len(seen)} strings -> {out}") + + +main() diff --git a/tools/release.sh b/tools/release.sh new file mode 100644 index 0000000..8c35177 --- /dev/null +++ b/tools/release.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT +# Cut a release: set project(VERSION) in CMakeLists.txt, date the "Unreleased" section of +# CHANGELOG.md, commit, create the annotated tag vX.Y.Z, push to every remote (GitHub origin and +# the Gitea mirror) and publish the GitHub release that the in-app update check reads. +# +# usage: tools/release.sh X.Y.Z [--no-push] +set -eu + +VERSION=${1:-} +PUSH=1 +[ "${2:-}" = "--no-push" ] && PUSH=0 +echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || { echo "usage: $0 X.Y.Z [--no-push]" >&2; exit 2; } + +cd "$(dirname "$0")/.." +[ -z "$(git status --porcelain)" ] || { echo "the working tree is not clean" >&2; exit 1; } +git rev-parse -q --verify "refs/tags/v$VERSION" >/dev/null && { echo "tag v$VERSION already exists" >&2; exit 1; } +grep -q '^## \[Unreleased\]' CHANGELOG.md || { echo "CHANGELOG.md has no [Unreleased] section" >&2; exit 1; } +PREVIOUS=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true) + +TODAY=$(date +%Y-%m-%d) +sed -i "s/^project(openpu VERSION [0-9.]* /project(openpu VERSION $VERSION /" CMakeLists.txt +grep -q "^project(openpu VERSION $VERSION " CMakeLists.txt || { echo "cannot update CMakeLists.txt" >&2; exit 1; } +# New release section under an empty Unreleased one, and comparison links at the bottom. +sed -i "s/^## \[Unreleased\]$/## [Unreleased]\n\n## [$VERSION] - $TODAY/" CHANGELOG.md +sed -i "s|^\[Unreleased\]: \(.*\)/compare/v[0-9.]*\.\.\.HEAD$|[Unreleased]: \1/compare/v$VERSION...HEAD\n[$VERSION]: \1/releases/tag/v$VERSION|" CHANGELOG.md + +git add CMakeLists.txt CHANGELOG.md +git commit -q -m "release: v$VERSION" +NOTES=$(awk -v v="$VERSION" '$0 ~ "^## \\[" v "\\]" {on=1; next} on && /^(## |\[)/ {exit} on {print}' CHANGELOG.md) +git tag -a "v$VERSION" -m "OpenPU $VERSION" -m "$NOTES" +echo "tagged v$VERSION (previous: ${PREVIOUS:-none})" + +[ "$PUSH" = 1 ] || exit 0 +for remote in $(git remote); do + git push --follow-tags "$remote" HEAD +done +GH=$(command -v gh || command -v gh.exe || true) +[ -z "$GH" ] && [ -x "/c/Program Files/GitHub CLI/gh.exe" ] && GH="/c/Program Files/GitHub CLI/gh.exe" +if [ -n "$GH" ]; then + printf '%s\n' "$NOTES" | "$GH" release create "v$VERSION" --verify-tag --title "OpenPU $VERSION" --notes-file - +else + echo "gh not found: create the GitHub release for v$VERSION by hand" >&2 +fi