diff --git a/CMakeLists.txt b/CMakeLists.txt index 57b7f29..f223269 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) # Find Qt6 -find_package(Qt6 REQUIRED COMPONENTS Widgets) +find_package(Qt6 REQUIRED COMPONENTS Widgets Network) # Main executable set(SOURCES @@ -18,6 +18,7 @@ set(SOURCES src/plugin-manager.cpp src/history-manager.cpp src/package-model.cpp + src/update-manager.cpp resources/resources.qrc ) @@ -29,15 +30,24 @@ set(HEADERS include/main-window.h include/history-manager.h include/package-model.h + include/update-manager.h ) add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) target_include_directories(${PROJECT_NAME} PRIVATE include) -target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Widgets) +target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Widgets Qt6::Network) + +# Copy the version file next to the executable so UpdateManager can read the +# running build's version at runtime. +add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_CURRENT_SOURCE_DIR}/version + $/version) # Install install(TARGETS ${PROJECT_NAME} DESTINATION bin) +install(FILES version DESTINATION bin) install(DIRECTORY include/ DESTINATION include/${PROJECT_NAME}) # Tests diff --git a/include/main-window.h b/include/main-window.h index 20ec3a0..dac4748 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -18,6 +18,7 @@ #include "pacman-manager.h" #include "plugin-manager.h" #include "history-manager.h" +#include "update-manager.h" class QStackedWidget; class QTableWidget; @@ -110,6 +111,10 @@ private slots: void onToggleProvider(); void onRescanProviders(); void onInstallProviderTool(); + void onCheckForUpdates(); + void onUpdateCheckFinished(bool hasUpdate, const QString& latestVersion, + const QString& errorMessage); + void onSelfUpdateFinished(bool success, const QString& message); private: enum BrowseMode { ModeSearch, ModeInstalled, ModeUpdates }; @@ -224,6 +229,7 @@ private: PacmanManager* m_pacman = nullptr; // non-owning, used for sudo credentials/logs PluginManager* m_pluginManager = nullptr; // owns every provider HistoryManager* m_historyManager = nullptr; + UpdateManager* m_updateManager = nullptr; // checks Gitea releases (owned) BrowseMode m_browseMode = ModeSearch; // Settings diff --git a/include/update-manager.h b/include/update-manager.h new file mode 100644 index 0000000..912da0e --- /dev/null +++ b/include/update-manager.h @@ -0,0 +1,73 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +// Checks the Gitea repository for new releases and tracks the last check +// state in a JSON file so the app only queries the API once per day. +// When the user accepts, the app updates itself by pulling + rebuilding +// the source repository in the background; the running binary stays +// untouched until the next launch. +class UpdateManager : public QObject { + Q_OBJECT +public: + explicit UpdateManager(QObject* parent = nullptr); + + // Current app version, read from the version file at build time. + static QString currentVersion(); + + // Path of the state file storing the last check date and the latest + // known remote version (e.g. ~/.local/share/PacManager/update-state.json). + static QString stateFilePath(); + + // True when the last check happened less than 24h ago, so we can skip + // the network call at launch. + bool shouldCheck() const; + + // Latest remote version recorded in the state file (empty if never checked). + QString lastKnownRemoteVersion() const; + + // Fetches the latest release from the Gitea API. Emits checkFinished. + void checkForUpdates(); + + // True when the remote version is newer than the local one. + static bool isNewerVersion(const QString& remote, const QString& local); + + // Path of the source repository, or empty when the app is installed + // without the repo (e.g. ~/.local/bin). Used for self-update. + QString repoPath() const; + + // Whether the source repository is present so a self-update is possible. + bool canSelfUpdate() const; + + // Pulls the latest code from the remote and rebuilds the app in the + // background. The current running binary is left untouched; the new + // version takes effect at the next launch. Emits selfUpdateFinished. + void performSelfUpdate(); + +signals: + // Emitted after a check completes. hasUpdate is true when a newer + // release exists; errorMessage is non-empty when the request failed. + void checkFinished(bool hasUpdate, const QString& latestVersion, + const QString& errorMessage); + + // Emitted when the background self-update completes. success is true + // if the pull + build produced a fresh executable. + void selfUpdateFinished(bool success, const QString& message); + +private: + void saveState(const QString& remoteVersion); + void loadState(); + void runShell(const QString& script, const QString& workingDir); + + QNetworkAccessManager m_network; + QProcess m_process; // runs the git pull + build script + QString m_lastCheckDate; // ISO date of the last successful check + QString m_lastKnownRemoteVersion; // latest version seen on the server + QString m_latestVersion; // version of the pending update + QString m_repoPath; // source repo dir when found +}; \ No newline at end of file diff --git a/src/main-window.cpp b/src/main-window.cpp index 2536233..77a9069 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -188,6 +188,7 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { m_pacman = dynamic_cast(m_pluginManager->managerFor("pacman")); m_historyManager = new HistoryManager(); + m_updateManager = new UpdateManager(this); setupUI(); setupMenuBar(); @@ -214,11 +215,18 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { refreshDashboard(); updateStatusBar(); + + // Check for app updates once per day (or on first launch). The delay lets + // the window appear first so the status bar message is visible. + if (m_updateManager->shouldCheck()) { + QTimer::singleShot(1500, this, &MainWindow::onCheckForUpdates); + } } MainWindow::~MainWindow() { delete m_pluginManager; // owns every provider, built-in and external delete m_historyManager; + delete m_updateManager; } void MainWindow::setupUI() { @@ -1050,11 +1058,13 @@ void MainWindow::setupMenuBar() { [this]() { applyCredentialMode(CredentialMode::AtLaunch); }); QMenu* helpMenu = menuBar->addMenu("Aide"); + helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates); + helpMenu->addSeparator(); helpMenu->addAction("À propos", [this]() { QMessageBox::about(this, "PacManager", - "

PacManager v1.0.0

" - "

Gestionnaire de paquets pour Arch Linux (pacman).

" - ); + QString("

PacManager v%1

" + "

Gestionnaire de paquets pour Arch Linux (pacman).

") + .arg(UpdateManager::currentVersion())); }); } @@ -2087,3 +2097,83 @@ void MainWindow::refreshProvidersTable() { m_providerDescription->clear(); } } + +// Starts an update check against the Gitea releases API. Used both at launch +// (once per day) and from the Aide menu. +void MainWindow::onCheckForUpdates() { + statusBar()->showMessage("Vérification des mises à jour..."); + connect(m_updateManager, &UpdateManager::checkFinished, + this, &MainWindow::onUpdateCheckFinished); + m_updateManager->checkForUpdates(); +} + +// Handles the result of a release check: offers to self-update when a newer +// version exists, otherwise a status bar confirmation. Errors are reported +// silently in the status bar so a network failure never blocks the app. +void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVersion, + const QString& errorMessage) { + disconnect(m_updateManager, &UpdateManager::checkFinished, + this, &MainWindow::onUpdateCheckFinished); + + if (!errorMessage.isEmpty()) { + statusBar()->showMessage(errorMessage); + return; + } + + if (!hasUpdate) { + statusBar()->showMessage( + QString("PacManager est à jour (v%1)").arg(UpdateManager::currentVersion())); + return; + } + + // Ask the user whether to update now or skip. When the source repo is + // available the update runs in the background (git pull + build); the + // running binary stays untouched until the next launch. + QMessageBox box(this); + box.setWindowTitle("Mise à jour disponible"); + box.setIcon(QMessageBox::Information); + box.setTextFormat(Qt::RichText); + box.setText(QString("

PacManager v%1 est disponible

" + "

Vous utilisez actuellement la version %2.

") + .arg(latestVersion, UpdateManager::currentVersion())); + + QPushButton* updateBtn = box.addButton("Mettre à jour", QMessageBox::AcceptRole); + QPushButton* skipBtn = box.addButton("Plus tard", QMessageBox::RejectRole); + + if (!m_updateManager->canSelfUpdate()) { + // No source checkout: only point to the releases page. + box.setInformativeText( + "Le dépôt source n'est pas disponible sur ce système.\n" + "Téléchargez la nouvelle version depuis la page des releases."); + updateBtn->setEnabled(false); + } + + box.exec(); + + if (box.clickedButton() == updateBtn) { + statusBar()->showMessage("Mise à jour en cours en arrière-plan..."); + connect(m_updateManager, &UpdateManager::selfUpdateFinished, + this, &MainWindow::onSelfUpdateFinished); + m_updateManager->performSelfUpdate(); + } + // "Plus tard" (or closing the dialog) simply skips the update. +} + +// Called when the background git pull + build finishes. Reports the result in +// a dialog so the user knows whether to restart the app. +void MainWindow::onSelfUpdateFinished(bool success, const QString& message) { + disconnect(m_updateManager, &UpdateManager::selfUpdateFinished, + this, &MainWindow::onSelfUpdateFinished); + + if (success) { + QMessageBox::information(this, "Mise à jour terminée", + QString("

PacManager a été mis à jour

" + "

La nouvelle version sera active au prochain démarrage.

" + "
%1
") + .arg(message.toHtmlEscaped())); + } else { + QMessageBox::warning(this, "Échec de la mise à jour", + QString("

La mise à jour a échoué :

%1
") + .arg(message.toHtmlEscaped())); + } +} diff --git a/src/main.cpp b/src/main.cpp index 3a07e86..8faafda 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,10 +1,11 @@ #include #include "main-window.h" +#include "update-manager.h" int main(int argc, char* argv[]) { QApplication app(argc, argv); app.setApplicationName("PacManager"); - app.setApplicationVersion("1.0.0"); + app.setApplicationVersion(UpdateManager::currentVersion()); app.setOrganizationName("Freebuff"); MainWindow window; diff --git a/src/update-manager.cpp b/src/update-manager.cpp new file mode 100644 index 0000000..0743270 --- /dev/null +++ b/src/update-manager.cpp @@ -0,0 +1,238 @@ +#include "update-manager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Repository base URL used to query the Gitea API for releases. +// The app is hosted at https://gitea.nocode-var.tech/FWS/FWS-PacManage. +static const char* kApiUrl = + "https://gitea.nocode-var.tech/api/v1/repos/FWS/FWS-PacManage/releases/latest"; +static const char* kVersionToken = "FWSPACMANAGE_VERSION"; // replaced at build time +static const char* kRepoUrl = + "https://gitea.nocode-var.tech/FWS/FWS-PacManage.git"; + +UpdateManager::UpdateManager(QObject* parent) : QObject(parent) { + loadState(); + + // The running executable is expected to live in the build/ directory when + // launched from a source checkout. Walk up two levels to find the repo. + // When installed to ~/.local/bin there is no source tree, so update + // becomes impossible and the dialog simply points to the releases page. + QDir dir(QCoreApplication::applicationDirPath()); + if (dir.dirName() == QLatin1String("build")) { + dir.cdUp(); + if (dir.exists(QLatin1String("CMakeLists.txt"))) { + m_repoPath = dir.absolutePath(); + } + } + + connect(&m_process, &QProcess::finished, this, [this](int exitCode) { + const QString msg = QString::fromUtf8(m_process.readAllStandardOutput()) + + QString::fromUtf8(m_process.readAllStandardError()); + emit selfUpdateFinished(exitCode == 0, msg.trimmed()); + }); +} + +QString UpdateManager::currentVersion() { + // The `version` file at the repo root is the single source of truth. It is + // read from the executable's directory so a running build always reports + // the same version the developer bumped in the repo. + QString version; + const QString localFile = QCoreApplication::applicationDirPath() + "/version"; + QFile f(localFile); + if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { + version = QString::fromUtf8(f.readAll()).trimmed(); + } + if (version.isEmpty()) { + // CMake configure-time token; falls back to 1.0.0 when built without. + version = QString::fromLatin1(kVersionToken); + if (version == QLatin1String("FWSPACMANAGE_VERSION")) { + version = QStringLiteral("1.0.0"); + } + } + return version; +} + +QString UpdateManager::stateFilePath() { + QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); + if (dir.isEmpty()) { + dir = QDir::homePath() + "/.local/share/PacManager"; + } + return dir + "/update-state.json"; +} + +bool UpdateManager::shouldCheck() const { + if (m_lastCheckDate.isEmpty()) return true; + + QDateTime last = QDateTime::fromString(m_lastCheckDate, Qt::ISODate); + if (!last.isValid()) return true; + + // Only one network call per day keeps launch snappy and avoids hammering + // the Gitea API on every start. + return last.daysTo(QDateTime::currentDateTime()) >= 1; +} + +QString UpdateManager::lastKnownRemoteVersion() const { + return m_lastKnownRemoteVersion; +} + +QString UpdateManager::repoPath() const { + return m_repoPath; +} + +bool UpdateManager::canSelfUpdate() const { + if (m_repoPath.isEmpty()) return false; + + QDir repo(m_repoPath); + if (!repo.exists(QLatin1String(".git"))) return false; + + // The remote must point to the same FWS repo, otherwise we would build + // someone else's code on the user's machine. + QFile config(m_repoPath + "/.git/config"); + if (config.open(QIODevice::ReadOnly | QIODevice::Text)) { + const QString content = QString::fromUtf8(config.readAll()); + if (content.contains(QLatin1String("FWS/FWS-PacManage"))) { + return true; + } + } + return false; +} + +void UpdateManager::loadState() { + QFile file(stateFilePath()); + if (!file.open(QIODevice::ReadOnly)) return; + + QJsonParseError err; + QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &err); + if (err.error != QJsonParseError::NoError || !doc.isObject()) return; + + QJsonObject obj = doc.object(); + m_lastCheckDate = obj.value("lastCheckDate").toString(); + m_lastKnownRemoteVersion = obj.value("latestRemoteVersion").toString(); +} + +void UpdateManager::saveState(const QString& remoteVersion) { + QJsonObject obj; + obj["lastCheckDate"] = QDateTime::currentDateTime().toString(Qt::ISODate); + obj["latestRemoteVersion"] = remoteVersion; + + QString path = stateFilePath(); + QDir().mkpath(QFileInfo(path).absolutePath()); + + QFile file(path); + if (!file.open(QIODevice::WriteOnly)) return; + file.write(QJsonDocument(obj).toJson(QJsonDocument::Indented)); +} + +void UpdateManager::runShell(const QString& script, const QString& workingDir) { + m_process.setWorkingDirectory(workingDir); + m_process.setProcessChannelMode(QProcess::MergedChannels); +#if defined(Q_OS_WIN) + m_process.start("cmd.exe", QStringList{"/C", script}); +#else + m_process.start("/bin/sh", QStringList{"-c", script}); +#endif +} + +void UpdateManager::checkForUpdates() { + QNetworkRequest request{QUrl(QString::fromLatin1(kApiUrl))}; + request.setHeader(QNetworkRequest::UserAgentHeader, + QString("PacManager/%1").arg(currentVersion())); + + QNetworkReply* reply = m_network.get(request); + connect(reply, &QNetworkReply::finished, this, [this, reply]() { + reply->deleteLater(); + + if (reply->error() != QNetworkReply::NoError) { + emit checkFinished(false, QString(), + QStringLiteral("Impossible de contacter le serveur : %1") + .arg(reply->errorString())); + return; + } + + const QByteArray data = reply->readAll(); + QJsonParseError err; + QJsonDocument doc = QJsonDocument::fromJson(data, &err); + if (err.error != QJsonParseError::NoError || !doc.isObject()) { + emit checkFinished(false, QString(), + QStringLiteral("Réponse du serveur invalide.")); + return; + } + + // Gitea returns the release tag (e.g. "V1.2.1") as `tag_name`. + QString tag = doc.object().value("tag_name").toString().trimmed(); + if (tag.isEmpty()) { + emit checkFinished(false, QString(), + QStringLiteral("Aucune release trouvée sur le serveur.")); + return; + } + + // Normalise tags like "V1.2.1" or "v1.2.1" to "1.2.1" for comparison. + if (tag.startsWith('v') || tag.startsWith('V')) { + tag = tag.mid(1); + } + + saveState(tag); + + bool hasUpdate = isNewerVersion(tag, currentVersion()); + m_lastKnownRemoteVersion = tag; + m_latestVersion = tag; + emit checkFinished(hasUpdate, tag, QString()); + }); +} + +bool UpdateManager::isNewerVersion(const QString& remote, const QString& local) { + // Simple dotted numeric comparison ("1.10.2" > "1.9.1"). Non-numeric + // components are treated as 0 so pre-release tags stay comparable. + auto parts = [](const QString& v) { + QVector out; + for (const QString& chunk : v.split('.')) { + bool ok = false; + int n = chunk.toInt(&ok); + out.append(ok ? n : 0); + } + return out; + }; + + const QVector r = parts(remote); + const QVector l = parts(local); + const int n = qMax(r.size(), l.size()); + for (int i = 0; i < n; ++i) { + int ri = i < r.size() ? r[i] : 0; + int li = i < l.size() ? l[i] : 0; + if (ri != li) return ri > li; + } + return false; +} + +// Pulls the latest source and rebuilds the app in the background. The script +// exits with a non-zero code on failure so the caller can report it. The new +// binary replaces the old one only when the build completes — the currently +// running process is untouched and picks it up on its next launch. +void UpdateManager::performSelfUpdate() { + if (m_repoPath.isEmpty()) { + emit selfUpdateFinished(false, QStringLiteral("Dépôt source introuvable.")); + return; + } + + QString script = QStringLiteral( + "set -e\n" + "echo 'Mise à jour de PacManager...'\n" + "git pull --ff-only origin main 2>&1 || git pull --ff-only 2>&1\n" + "if [ -d build ]; then\n" + " cmake --build build -j$(nproc) 2>&1\n" + "else\n" + " cmake -B build -DCMAKE_BUILD_TYPE=Release . 2>&1\n" + " cmake --build build -j$(nproc) 2>&1\n" + "fi\n" + "echo 'Mise à jour terminée. Redémarrez PacManager pour utiliser la nouvelle version.'"); + + runShell(script, m_repoPath); +} \ No newline at end of file