feat(update): self-update from a cloned repo wherever the app is installed

Self-update assumed a conventional install prefix (silently reinstalling into
~/.local when the binary lived elsewhere) and needed a release tarball to do
anything. Pick the strategy from what the machine actually has -- a local
checkout, git+cmake+compiler for a clone, the prebuilt archive, or the release
sources -- and always write the fresh binary next to the running one, building
in a temp directory so sudo is only needed for the final copy.

Bundles the UI work that depends on it (tray, shortcuts, log filter, CSV
exports, cached package details), the structured log categories, and the new
test targets (update-manager, AUR, plugins) wired into CTest.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
BlackAngelTV committed 2026-09-11 20:15:41 +02:00
1 parent 6d5b4274c4
commit 54bff16369
9 files changed
+1123 -200

No files matched your search

+446 -63
View File
@@ -26,8 +26,17 @@
#include <QActionGroup>
#include <QInputDialog>
#include <QTimer>
#include <QSystemTrayIcon>
#include <QShortcut>
#include <QKeySequence>
#include <QFileDialog>
#include <QTextStream>
#include <QDir>
#include "app-logging.h"
#include <algorithm>
#include <functional>
// Worker threads
SearchWorker::SearchWorker(const std::vector<IPackageManager*>& providers,
@@ -138,6 +147,14 @@ static QLabel* makeBadge(const QString& text, const QString& bg, const QString&
return badge;
}
// Closes a popen() stream. A named deleter avoids the GCC warning about the
// function-pointer attributes carried by decltype(&pclose) being dropped.
struct PipeCloser {
void operator()(FILE* file) const {
if (file) pclose(file);
}
};
// Load one of the embedded SVG icons (see resources/resources.qrc).
static QIcon loadIcon(const QString& name) {
return QIcon(QString(":/icons/%1.svg").arg(name));
@@ -171,6 +188,25 @@ static QString providersLabel(const PluginManager* pm, const PackageInfo& pkg) {
return names.join(", ");
}
// Quote a CSV field when it contains the separator, a quote or a newline, so
// exported lists stay importable in a spreadsheet.
static QString csvField(const QString& value) {
if (!value.contains(';') && !value.contains('"') && !value.contains('\n')) {
return value;
}
QString escaped = value;
escaped.replace(QLatin1String("\""), QLatin1String("\"\""));
return QLatin1Char('"') + escaped + QLatin1Char('"');
}
// Human-readable status of a package row, shared by the table and the export.
static QString packageStatusText(const PackageInfo& pkg) {
if (pkg.installed && pkg.updateAvailable) return QStringLiteral("MAJ dispo");
if (pkg.installed) return QStringLiteral("Installé");
if (!pkg.repository.empty()) return QStringLiteral("Disponible");
return QStringLiteral("—");
}
// MainWindow implementation
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
// Workers emit std::vector<PackageInfo> from another thread (QThread::run);
@@ -195,6 +231,8 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
setupUI();
setupMenuBar();
setupTray();
setupShortcuts();
// Addon plugins get the main window so they can attach their own UI
// (status-bar widgets, toolbar buttons, ...). Only enabled+available
@@ -723,6 +761,11 @@ void MainWindow::setupBrowsePage() {
connect(m_updateAllButton, &QPushButton::clicked, this, &MainWindow::onUpdateAll);
actionBar->addWidget(m_updateAllButton);
QPushButton* exportBtn = new QPushButton("Exporter");
exportBtn->setToolTip("Exporter la liste affichée en CSV");
connect(exportBtn, &QPushButton::clicked, this, &MainWindow::onExportPackageList);
actionBar->addWidget(exportBtn);
actionBar->addStretch();
m_resultCount = new QLabel("");
@@ -803,21 +846,6 @@ void MainWindow::setupBrowsePage() {
"padding: 3px 12px; font-size: 12px;");
metaRow->addWidget(m_packageProvider);
// "Update available" badge with an SVG arrow + text.
m_packageUpdateBadge = new QWidget();
m_packageUpdateBadge->setStyleSheet("background: #3d2f0f; border-radius: 9px;");
QHBoxLayout* updLayout = new QHBoxLayout(m_packageUpdateBadge);
updLayout->setContentsMargins(9, 2, 9, 2);
updLayout->setSpacing(5);
QLabel* updIcon = new QLabel();
updIcon->setPixmap(iconPixmap("arrow-up", 12));
updLayout->addWidget(updIcon);
QLabel* updText = new QLabel("Mise à jour disponible");
updText->setStyleSheet("font-size: 11px; font-weight: 600; color: #e0af68; background: transparent;");
updLayout->addWidget(updText);
m_packageUpdateBadge->setVisible(false);
metaRow->addWidget(m_packageUpdateBadge);
metaRow->addStretch();
detailsLayout->addLayout(metaRow);
@@ -884,6 +912,11 @@ void MainWindow::setupHistoryPage() {
QHBoxLayout* buttonBar = new QHBoxLayout();
buttonBar->addStretch();
QPushButton* exportBtn = new QPushButton("Exporter (CSV)");
exportBtn->setToolTip("Enregistrer l'historique affiché dans un fichier CSV");
connect(exportBtn, &QPushButton::clicked, this, &MainWindow::onExportHistory);
buttonBar->addWidget(exportBtn);
QPushButton* clearBtn = new QPushButton("Effacer l'historique");
clearBtn->setProperty("variant", "danger");
clearBtn->setIcon(loadIcon("trash"));
@@ -901,6 +934,22 @@ void MainWindow::setupLogsPage() {
layout->setContentsMargins(24, 20, 24, 20);
layout->setSpacing(12);
// Filter row: /var/log/pacman.log can be huge, so the content is read once
// into m_logsRaw and filtered in memory (no re-read per keystroke).
QHBoxLayout* filterRow = new QHBoxLayout();
filterRow->setSpacing(10);
m_logsFilter = new QLineEdit();
m_logsFilter->setPlaceholderText("Filtrer les logs (paquet, action, date)...");
m_logsFilter->setMinimumHeight(36);
m_logsFilter->setClearButtonEnabled(true);
m_logsFilter->addAction(loadIcon("filter"), QLineEdit::LeadingPosition);
connect(m_logsFilter, &QLineEdit::textChanged,
this, &MainWindow::onLogsFilterChanged);
filterRow->addWidget(m_logsFilter, 1);
layout->addLayout(filterRow);
m_logsText = new QTextEdit();
m_logsText->setReadOnly(true);
layout->addWidget(m_logsText, 1);
@@ -1026,6 +1075,10 @@ void MainWindow::setupMenuBar() {
);
QMenu* fileMenu = menuBar->addMenu("Fichier");
fileMenu->addAction("Exporter la liste affichée...", this,
&MainWindow::onExportPackageList);
fileMenu->addAction("Exporter l'historique...", this, &MainWindow::onExportHistory);
fileMenu->addSeparator();
fileMenu->addAction("Quitter", this, &QWidget::close);
QMenu* toolsMenu = menuBar->addMenu("Outils");
@@ -1040,6 +1093,7 @@ void MainWindow::setupMenuBar() {
toolsMenu->addAction("Logs pacman", this, [this]() { m_navGroup->button(5)->click(); });
toolsMenu->addAction("Plugins", this, [this]() { m_navGroup->button(6)->click(); });
toolsMenu->addSeparator();
toolsMenu->addAction("Prévisualiser les mises à jour", this, &MainWindow::onPreviewUpdates);
toolsMenu->addAction("Rafraîchir les sources", this, &MainWindow::onRefresh);
QMenu* settingsMenu = menuBar->addMenu("Paramètres");
@@ -1146,11 +1200,51 @@ IPackageManager* MainWindow::providerFor(const std::string& id) const {
return available.empty() ? nullptr : available.front();
}
void MainWindow::showProviderError(const QString& title, IPackageManager* provider) {
if (!provider) return;
bool MainWindow::showProviderError(const QString& title, IPackageManager* provider) {
if (!provider) return false;
std::string err = provider->lastError();
if (!err.empty()) {
if (err.empty()) return false;
const bool dbLock = err.find("verrouillée") != std::string::npos
|| err.find("db.lck") != std::string::npos;
if (!dbLock) {
QMessageBox::warning(this, title, QString::fromStdString(err));
return false;
}
// Locked DB: explain + offer a retry, since the other manager (or stale
// lock) is often gone by the time the user clicks again.
QMessageBox box(this);
box.setWindowTitle(title);
box.setIcon(QMessageBox::Warning);
box.setText(QString::fromStdString(err));
box.setInformativeText("Fermez l'autre gestionnaire (ou supprimez le "
"fichier résiduel indiqué), puis réessayez.");
QPushButton* retryBtn = box.addButton("Réessayer", QMessageBox::AcceptRole);
box.addButton("Fermer", QMessageBox::RejectRole);
box.exec();
if (box.clickedButton() == retryBtn && !m_pendingRetryAction.isEmpty()) {
const QString action = m_pendingRetryAction;
m_pendingRetryAction.clear();
// Defer so the dialog closes before the worker touches the UI.
QTimer::singleShot(0, this, [this, action] { retryPrivilegedAction(action); });
} else {
m_pendingRetryAction.clear();
}
return true;
}
void MainWindow::retryPrivilegedAction(const QString& action) {
if (action == "install" && !m_selectedPackage.name.empty()) {
m_pendingSelect = m_selectedPackage.name;
performInstall(m_selectedPackage.name);
} else if (action == "remove" && !m_selectedPackage.name.empty()) {
m_pendingSelect = m_selectedPackage.name;
performRemove(m_selectedPackage.name);
} else if (action == "update-all") {
onUpdateAll();
} else if (action == "refresh") {
onRefresh();
} else if (action == "update" && !m_selectedPackage.name.empty()) {
onUpdate();
}
}
@@ -1228,6 +1322,7 @@ void MainWindow::updatePageTitle() {
}
void MainWindow::onNavChanged(int id) {
qCDebug(pacmgrUi) << "navigate to page" << id;
updatePageTitle();
switch (id) {
@@ -1283,7 +1378,6 @@ void MainWindow::resetDetailsPanel() {
m_packageRepo->setText("—");
m_packageSize->setText("—");
m_packageProvider->setText("—");
m_packageUpdateBadge->setVisible(false);
m_packageDescription->setText("");
m_installButton->setEnabled(false);
m_removeButton->setEnabled(false);
@@ -1532,9 +1626,94 @@ void MainWindow::updatePackageInfo(const PackageInfo& pkg) {
: QString("Taille : %1").arg(QString::fromStdString(pkg.size)));
m_packageProvider->setText(
QString("Fournisseur : %1").arg(providersLabel(m_pluginManager, pkg)));
m_packageUpdateBadge->setVisible(pkg.updateAvailable);
m_packageDescription->setText(QString::fromStdString(pkg.description));
// Rich details: dependencies, required-by, install date (pacman), update
// size estimate for pending updates. Loaded on demand so selecting a row
// stays instant even when pacman is slow.
QString details = QString::fromStdString(pkg.description);
const std::string rich = m_pacman ? richDetails(pkg) : std::string();
if (!rich.empty()) {
if (!details.isEmpty()) details += "\n\n";
details += QString::fromStdString(rich);
}
m_packageDescription->setText(details);
}
// Runs the read-only pacman queries backing the details panel. Kept
// synchronous: -Qi/-Si answer in milliseconds and the panel already updated
// the basics above, so no worker thread is worth the complexity.
std::string MainWindow::richDetails(const PackageInfo& pkg) {
if (!m_pacman || !m_pacman->isAvailable()) return {};
// Cache per name+provider+version+installed: selecting a row repeatedly (or
// arrowing through the table) must not re-spawn pacman every time.
const QString key = QStringLiteral("%1|%2|%3|%4")
.arg(QString::fromStdString(pkg.name),
QString::fromStdString(pkg.provider),
QString::fromStdString(pkg.version))
.arg(pkg.installed ? 1 : 0);
const auto cached = m_detailsCache.constFind(key);
if (cached != m_detailsCache.constEnd()) return cached.value();
auto run = [](const std::string& cmd) {
std::array<char, 4096> buf{};
std::string out;
std::unique_ptr<FILE, PipeCloser> pipe(popen(cmd.c_str(), "r"));
if (!pipe) return out;
while (fgets(buf.data(), buf.size(), pipe.get())) out += buf.data();
return out;
};
auto field = [&](const std::string& out, const std::string& name) {
std::istringstream iss(out);
std::string line;
while (std::getline(iss, line)) {
size_t colon = line.find(':');
if (colon == std::string::npos) continue;
std::string key = line.substr(0, colon);
while (!key.empty() && key.back() == ' ') key.pop_back();
if (key != name) continue;
std::string val = line.substr(colon + 1);
size_t start = val.find_first_not_of(" \t");
if (start != std::string::npos) val = val.substr(start);
while (!val.empty() && (val.back() == '\n' || val.back() == '\r' || val.back() == ' '))
val.pop_back();
return val;
}
return std::string();
};
const bool isPacmanPkg = pkg.provider == "pacman" || pkg.provider.empty();
const std::string q = pkg.provider == "aur" ? "yay -Qi " : "pacman -Qi ";
const std::string s = pkg.provider == "aur" ? "yay -Si " : "pacman -Si ";
std::string installed = run(q + pkg.name + " 2>/dev/null");
if (installed.empty() && isPacmanPkg) installed = run("pacman -Qi " + pkg.name + " 2>/dev/null");
std::string out;
auto addRow = [&](const char* label, const std::string& val) {
if (val.empty() || val == "None" || val == "--") return;
if (!out.empty()) out += "\n";
out += std::string(label) + " : " + val;
};
if (!installed.empty()) {
addRow("Taille installée", field(installed, "Installed Size"));
addRow("Date d'installation", field(installed, "Install Date"));
addRow("Dépend de", field(installed, "Depends On"));
addRow("Requis par", field(installed, "Required By"));
} else {
// Only query the sync database when the package is not installed here,
// halving the subprocess count on the Installed/Updates pages.
const std::string sync = run(s + pkg.name + " 2>/dev/null");
if (!sync.empty()) {
addRow("Taille du téléchargement", field(sync, "Download Size"));
addRow("Taille installée", field(sync, "Installed Size"));
addRow("Dépend de", field(sync, "Depends On"));
}
}
// Bound the cache so a long browsing session cannot grow it forever.
if (m_detailsCache.size() > 512) m_detailsCache.clear();
m_detailsCache.insert(key, out);
return out;
}
void MainWindow::onInstall() {
@@ -1552,9 +1731,14 @@ void MainWindow::onUpdate() {
IPackageManager* provider = providerFor(m_selectedPackage.provider);
if (!provider || !provider->canUpdate()) return;
if (!ensureCredentials({provider})) return;
if (!tryAcquireOp()) return;
m_pendingRetryAction = "update";
if (!ensureCredentials({provider})) {
setBusy(false);
m_pendingRetryAction.clear();
return;
}
setBusy(true);
statusBar()->showMessage(
QString("Mise à jour de %1...").arg(QString::fromStdString(m_selectedPackage.name)));
@@ -1586,9 +1770,14 @@ void MainWindow::onUpdateAll() {
statusBar()->showMessage("Aucun gestionnaire de paquets disponible.");
return;
}
if (!ensureCredentials(providers)) return;
if (!tryAcquireOp()) return;
m_pendingRetryAction = "update-all";
if (!ensureCredentials(providers)) {
setBusy(false);
m_pendingRetryAction.clear();
return;
}
setBusy(true);
statusBar()->showMessage("Mise à jour de tous les paquets...");
auto* worker = new InstallWorker(providers, InstallWorker::Op::UpdateAll);
@@ -1604,8 +1793,8 @@ void MainWindow::onUpdateAll() {
statusBar()->showMessage("Erreur lors de la mise à jour globale");
for (IPackageManager* pm : providers) {
if (!pm->lastError().empty()) {
QMessageBox::warning(this, "Erreur lors de la mise à jour globale",
QString::fromStdString(pm->lastError()));
// showProviderError offers a retry for db-lock errors.
showProviderError("Erreur lors de la mise à jour globale", pm);
break;
}
}
@@ -1624,9 +1813,14 @@ void MainWindow::onRefresh() {
statusBar()->showMessage("Aucun gestionnaire de paquets disponible.");
return;
}
if (!ensureCredentials(providers)) return;
if (!tryAcquireOp()) return;
m_pendingRetryAction = "refresh";
if (!ensureCredentials(providers)) {
setBusy(false);
m_pendingRetryAction.clear();
return;
}
setBusy(true);
statusBar()->showMessage("Rafraîchissement des sources...");
auto* worker = new InstallWorker(providers, InstallWorker::Op::Refresh);
@@ -1642,8 +1836,7 @@ void MainWindow::onRefresh() {
statusBar()->showMessage("Erreur lors du rafraîchissement");
for (IPackageManager* pm : providers) {
if (!pm->lastError().empty()) {
QMessageBox::warning(this, "Erreur lors du rafraîchissement",
QString::fromStdString(pm->lastError()));
showProviderError("Erreur lors du rafraîchissement", pm);
break;
}
}
@@ -1658,9 +1851,16 @@ void MainWindow::onRefresh() {
void MainWindow::performInstall(const std::string& package) {
IPackageManager* provider = providerFor(m_selectedPackage.provider);
if (!provider || !provider->canInstall()) return;
if (!ensureCredentials({provider})) return;
qCInfo(pacmgrOp) << "install" << QString::fromStdString(package)
<< "via" << QString::fromStdString(provider->getName());
if (!tryAcquireOp()) return;
m_pendingRetryAction = "install";
if (!ensureCredentials({provider})) {
setBusy(false);
m_pendingRetryAction.clear();
return;
}
setBusy(true);
statusBar()->showMessage(
QString("Installation de %1...").arg(QString::fromStdString(package)));
@@ -1694,9 +1894,16 @@ void MainWindow::performInstall(const std::string& package) {
void MainWindow::performRemove(const std::string& package) {
IPackageManager* provider = providerFor(m_selectedPackage.provider);
if (!provider || !provider->canRemove()) return;
if (!ensureCredentials({provider})) return;
qCInfo(pacmgrOp) << "remove" << QString::fromStdString(package)
<< "via" << QString::fromStdString(provider->getName());
if (!tryAcquireOp()) return;
m_pendingRetryAction = "remove";
if (!ensureCredentials({provider})) {
setBusy(false);
m_pendingRetryAction.clear();
return;
}
setBusy(true);
statusBar()->showMessage(
QString("Suppression de %1...").arg(QString::fromStdString(package)));
@@ -1728,6 +1935,9 @@ void MainWindow::performRemove(const std::string& package) {
}
void MainWindow::reloadCurrentView() {
// Installed state changed: drop the cached pacman details so the panel
// shows the fresh size/date after an install/remove/update.
m_detailsCache.clear();
if (m_browseMode == ModeInstalled) {
loadInstalled();
} else if (m_browseMode == ModeUpdates) {
@@ -1738,6 +1948,7 @@ void MainWindow::reloadCurrentView() {
}
void MainWindow::setBusy(bool busy) {
m_busy = busy;
m_progressBar->setVisible(busy);
m_installProgressBar->setVisible(busy);
if (busy) {
@@ -1750,6 +1961,18 @@ void MainWindow::setBusy(bool busy) {
}
}
// Single privileged pacman operation at a time: pacman locks its DB
// (/var/lib/pacman/db.lck), so a second concurrent op would fail with
// "verrouillage de la base de données impossible".
bool MainWindow::tryAcquireOp() {
if (m_busy) {
statusBar()->showMessage("Une opération est déjà en cours, patientez...");
return false;
}
setBusy(true);
return true;
}
// A real download percentage reported by the provider fills the bottom bar as
// a determinate progress. -1 (unknown) leaves the bar in its previous state.
void MainWindow::onInstallProgress(int percent) {
@@ -1821,6 +2044,7 @@ void MainWindow::loadLogs() {
QFile logFile(logPath);
if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_logsRaw.clear();
m_logsText->setPlainText(
QString("Impossible d'ouvrir %1.\n"
"Vérifiez que le fichier existe et que vous avez les droits de lecture.")
@@ -1828,7 +2052,32 @@ void MainWindow::loadLogs() {
return;
}
m_logsText->setPlainText(QString::fromUtf8(logFile.readAll()));
m_logsRaw = QString::fromUtf8(logFile.readAll());
applyLogsFilter();
}
void MainWindow::onLogsFilterChanged() {
applyLogsFilter();
}
// Renders m_logsRaw, keeping only the lines matching the filter box. Filtering
// in memory keeps typing instant even with a multi-megabyte pacman.log.
void MainWindow::applyLogsFilter() {
if (!m_logsText) return;
const QString needle = m_logsFilter ? m_logsFilter->text().trimmed() : QString();
if (needle.isEmpty()) {
m_logsText->setPlainText(m_logsRaw);
} else {
QString filtered;
const QStringList lines = m_logsRaw.split(QLatin1Char('\n'));
for (const QString& line : lines) {
if (line.contains(needle, Qt::CaseInsensitive)) {
filtered += line;
filtered += QLatin1Char('\n');
}
}
m_logsText->setPlainText(filtered);
}
m_logsText->moveCursor(QTextCursor::End);
}
@@ -1869,6 +2118,12 @@ void MainWindow::refreshDashboard() {
m_statUpdates->setStyleSheet(r.empty()
? QString()
: QString("color: #e0af68;"));
// Notify once per distinct count, so the periodic dashboard refresh
// does not re-pop the tray message.
if (static_cast<int>(r.size()) != m_lastNotifiedUpdates) {
m_lastNotifiedUpdates = static_cast<int>(r.size());
notifyUpdatesAvailable(static_cast<int>(r.size()));
}
});
connect(upd, &ListWorker::finished, this, [upd] { upd->wait(); upd->deleteLater(); });
upd->start();
@@ -2135,6 +2390,143 @@ void MainWindow::refreshPluginsTable() {
// Starts an update check against the Gitea releases API. Used both at launch
// (once per day) and from the Aide menu.
// ---------------------------------------------------------------------------
// System tray: optional, only created when the desktop actually provides one.
// Offers quick access to the pending updates from outside the window.
// ---------------------------------------------------------------------------
void MainWindow::setupTray() {
if (!QSystemTrayIcon::isSystemTrayAvailable()) return;
m_tray = new QSystemTrayIcon(loadIcon("package"), this);
m_tray->setToolTip("PacManager");
QMenu* menu = new QMenu(this);
menu->addAction("Afficher PacManager", this, [this]() {
showNormal();
raise();
activateWindow();
});
menu->addSeparator();
menu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates);
menu->addAction("Prévisualiser les mises à jour", this, &MainWindow::onPreviewUpdates);
menu->addAction("Tout mettre à jour", this, &MainWindow::onUpdateAll);
menu->addSeparator();
menu->addAction("Quitter", this, &QWidget::close);
m_tray->setContextMenu(menu);
connect(m_tray, &QSystemTrayIcon::activated, this, &MainWindow::onTrayActivated);
m_tray->show();
}
void MainWindow::onTrayActivated(QSystemTrayIcon::ActivationReason reason) {
// A click on the icon brings the window back from the background.
if (reason != QSystemTrayIcon::Trigger && reason != QSystemTrayIcon::DoubleClick) {
return;
}
showNormal();
raise();
activateWindow();
}
void MainWindow::notifyUpdatesAvailable(int count) {
if (!m_tray || count <= 0) return;
m_tray->showMessage("PacManager",
QString("%1 mise(s) à jour disponible(s)").arg(count),
QSystemTrayIcon::Information, 5000);
}
// Keyboard shortcuts for the actions used most often.
void MainWindow::setupShortcuts() {
auto bind = [this](const QKeySequence& key, const std::function<void()>& action) {
QShortcut* shortcut = new QShortcut(key, this);
shortcut->setContext(Qt::WindowShortcut);
connect(shortcut, &QShortcut::activated, this, action);
};
bind(QKeySequence::Find, [this]() {
m_navGroup->button(1)->click();
m_searchBar->setFocus();
m_searchBar->selectAll();
});
bind(QKeySequence::Refresh, [this]() { onRefresh(); });
bind(QKeySequence(Qt::Key_F5), [this]() { onRefresh(); });
bind(QKeySequence(QStringLiteral("Ctrl+U")), [this]() {
m_navGroup->button(3)->click();
});
bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() { onExportPackageList(); });
bind(QKeySequence::Quit, [this]() { close(); });
}
// Shows the pending updates without applying anything: jumps to the updates
// page, which lists every outdated package across the active providers.
void MainWindow::onPreviewUpdates() {
m_navGroup->button(3)->click();
statusBar()->showMessage("Prévisualisation des mises à jour disponibles");
}
// Exports the currently displayed package list (search / installed / updates)
// to a semicolon-separated CSV usable in a spreadsheet.
void MainWindow::onExportPackageList() {
if (m_currentResults.empty()) {
statusBar()->showMessage("Aucune liste à exporter.");
return;
}
const QString path = QFileDialog::getSaveFileName(
this, "Exporter la liste des paquets",
QDir::homePath() + "/pacmanager-paquets.csv", "CSV (*.csv)");
if (path.isEmpty()) return;
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "Export",
QString("Impossible d'écrire dans %1").arg(path));
return;
}
QTextStream out(&file);
out << "Nom;Version;Depot;Fournisseur;Statut\n";
for (const auto& pkg : m_currentResults) {
out << csvField(QString::fromStdString(pkg.name)) << ';'
<< csvField(QString::fromStdString(pkg.version)) << ';'
<< csvField(QString::fromStdString(pkg.repository)) << ';'
<< csvField(providersLabel(m_pluginManager, pkg)) << ';'
<< csvField(packageStatusText(pkg)) << '\n';
}
statusBar()->showMessage(
QString("%1 paquet(s) exporté(s) vers %2")
.arg(static_cast<int>(m_currentResults.size())).arg(path));
}
// Exports the recorded action history to CSV.
void MainWindow::onExportHistory() {
const auto& history = m_historyManager->getHistory();
if (history.empty()) {
statusBar()->showMessage("Historique vide.");
return;
}
const QString path = QFileDialog::getSaveFileName(
this, "Exporter l'historique",
QDir::homePath() + "/pacmanager-historique.csv", "CSV (*.csv)");
if (path.isEmpty()) return;
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "Export",
QString("Impossible d'écrire dans %1").arg(path));
return;
}
QTextStream out(&file);
out << "Date;Action;Paquet;Gestionnaire;Statut\n";
for (const auto& entry : history) {
out << csvField(QString::fromStdString(entry.timestamp)) << ';'
<< csvField(QString::fromStdString(entry.action)) << ';'
<< csvField(QString::fromStdString(entry.package)) << ';'
<< csvField(QString::fromStdString(entry.plugin)) << ';'
<< (entry.success ? "Succes" : "Echec") << '\n';
}
statusBar()->showMessage(
QString("Historique exporté vers %1").arg(path));
}
void MainWindow::onCheckForUpdates() {
statusBar()->showMessage("Vérification des mises à jour...");
connect(m_updateManager, &UpdateManager::checkFinished,
@@ -2162,9 +2554,12 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers
}
// Ask the user whether to update now or skip. The update runs in the
// background (git pull + rebuild from a checkout, or tarball download +
// rebuild + reinstall when installed); the running binary stays
// untouched until the next launch.
// background (git pull from a checkout, clone + rebuild, prebuilt unpack,
// or tarball rebuild); the running binary stays untouched until the next
// launch.
const UpdateManager::UpdateMethod method = m_updateManager->updateMethod();
const QString targetDir = m_updateManager->binDir();
QMessageBox box(this);
box.setWindowTitle("Mise à jour disponible");
box.setIcon(QMessageBox::Information);
@@ -2175,24 +2570,12 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers
QPushButton* updateBtn = box.addButton("Mettre à jour", QMessageBox::AcceptRole);
box.addButton("Plus tard", QMessageBox::RejectRole);
if (!m_updateManager->canSelfUpdate()) {
// No source checkout and no tarball URL: fall back to the releases
// page instead of a disabled button.
if (method == UpdateManager::UpdateMethod::None) {
// No local way to update: offer the releases page instead of a button
// that would immediately fail.
updateBtn->setText("Ouvrir la page des releases");
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.");
} else if (m_updateManager->repoPath().isEmpty()) {
// Installed mode: tarball download + local build + reinstall to the
// same prefix (sudo only for system prefixes).
box.setInformativeText(
QString("La mise à jour va télécharger les sources, les compiler "
"et réinstaller l'application dans %1.\n"
"Redémarrez PacManager ensuite pour utiliser la nouvelle version.")
.arg(m_updateManager->installPrefix()));
}
box.setInformativeText(UpdateManager::methodDescription(method, targetDir));
box.exec();
if (box.clickedButton() != updateBtn) {
@@ -2200,23 +2583,21 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers
return;
}
if (!m_updateManager->canSelfUpdate()) {
if (method == UpdateManager::UpdateMethod::None) {
QDesktopServices::openUrl(QUrl(m_updateManager->releasePageUrl()));
return;
}
// System prefixes (/usr, /usr/local) need sudo for `cmake --install`.
// Prompt once for the password; user prefixes install without sudo.
// Prompt for the sudo password only when the update must write into a
// root-owned directory (e.g. /usr/bin). Only the final copy is privileged:
// everything else builds in a temp directory owned by the user.
QString sudoPassword;
const QString prefix = m_updateManager->installPrefix();
const bool prefixWritable =
QFileInfo(prefix).isWritable() || QFileInfo(prefix + "/bin").isWritable();
if (m_updateManager->repoPath().isEmpty() && !prefixWritable
if (m_updateManager->repoPath().isEmpty() && !QFileInfo(targetDir).isWritable()
&& m_pacman && m_pacman->isAvailable()) {
bool ok = false;
sudoPassword = QInputDialog::getText(
this, "Mise à jour",
QString("Mot de passe sudo pour installer dans %1 :").arg(prefix),
QString("Mot de passe sudo pour installer dans %1 :").arg(targetDir),
QLineEdit::Password, QString(), &ok);
if (!ok) {
statusBar()->showMessage("Mise à jour annulée.");
@@ -2224,6 +2605,8 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers
}
}
qCInfo(pacmgrUpdate) << "applying update, method" << static_cast<int>(method)
<< "target" << targetDir;
statusBar()->showMessage("Mise à jour en cours en arrière-plan...");
connect(m_updateManager, &UpdateManager::selfUpdateFinished,
this, &MainWindow::onSelfUpdateFinished);