From 632cdf1dea790af09b1c47f7c1f61c827fa3f167 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Sat, 12 Sep 2026 22:17:08 +0200 Subject: [PATCH] feat(cleanup): add a maintenance page for unused and legacy packages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Leftovers pile up on a machine: dependencies that no installed package requires any more, and installs coming from the AUR or manual builds that the sync databases know nothing about. The new Nettoyage page lists both (orphans first, since they are the ones that can be removed in bulk), shows which provider reported each row, and frees the space held by the caches: paccache (or pacman -Sc) and flatpak's unused runtimes. Cleanup is an optional capability of IPackageManager, so providers that only install packages keep working unchanged. Generated with Codebuff 🤖 Co-Authored-By: Codebuff --- include/main-window.h | 37 +- include/package-manager.h | 43 ++ include/pacman-manager.h | 28 ++ plugins/flatpak-provider/flatpak-manager.cpp | 19 + plugins/flatpak-provider/flatpak-manager.h | 5 + resources/icons/broom.svg | 5 + resources/resources.qrc | 1 + src/main-window.cpp | 420 ++++++++++++++++++- src/pacman-manager.cpp | 115 +++++ tests/pacman-manager.test.cpp | 83 ++++ 10 files changed, 750 insertions(+), 6 deletions(-) create mode 100644 resources/icons/broom.svg diff --git a/include/main-window.h b/include/main-window.h index 26564c8..1754de1 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -14,6 +14,7 @@ #include #include +#include #include #include "package-manager.h" @@ -54,7 +55,7 @@ private: class ListWorker : public QThread { Q_OBJECT public: - enum Mode { Installed, Updates }; + enum Mode { Installed, Updates, Cleanup }; ListWorker(const std::vector& providers, Mode mode); void run() override; signals: @@ -70,8 +71,11 @@ private: class InstallWorker : public QThread { Q_OBJECT public: - enum class Op { Install, Remove, Update, UpdateAll, Refresh }; + enum class Op { Install, Remove, Update, UpdateAll, Refresh, RemovePackages, CleanCache }; InstallWorker(IPackageManager* pm, Op op, const std::string& package); + // Bulk variant: removes several packages in one provider call (cleanup + // page) instead of one call per package. + InstallWorker(IPackageManager* pm, Op op, const std::vector& packages); InstallWorker(const std::vector& providers, Op op); void run() override; signals: @@ -84,6 +88,7 @@ private: std::vector m_providers; Op m_op; std::string m_package; + std::vector m_packages; }; class MainWindow : public QMainWindow { @@ -123,6 +128,12 @@ private slots: void onUpdateCheckFinished(bool hasUpdate, const QString& latestVersion, const QString& errorMessage); void onSelfUpdateFinished(bool success, const QString& message); + void onCleanupScan(); + void onCleanupListFinished(std::vector results); + void onCleanupSelectionChanged(int row); + void onRemoveCleanupOrphans(); + void onRemoveCleanupSelection(); + void onCleanCaches(); private: enum BrowseMode { ModeSearch, ModeInstalled, ModeUpdates }; @@ -135,6 +146,7 @@ private: NavSearch, NavInstalled, NavUpdates, + NavCleanup, NavHistory, NavLogs, NavPlugins, @@ -148,6 +160,7 @@ private: PageHistory, PageLogs, PagePlugins, + PageCleanup, }; // When the sudo password is requested: once per session (at launch) or @@ -183,6 +196,7 @@ private: void setupHistoryPage(); void setupLogsPage(); void setupPluginsPage(); + void setupCleanupPage(); void setupMenuBar(); void updatePageTitle(); void updateStatusBar(); @@ -206,6 +220,13 @@ private: void loadInstalled(); void loadUpdates(); void refreshHistoryTable(); + void loadCleanup(); + void populateCleanupTable(const std::vector& candidates); + // Runs a bulk removal of the given candidates, one provider at a time, and + // refreshes the cleanup list when the last group is done. + void removeCleanupPackages(const std::vector& packages, + const QString& description); + void startNextCleanupRemoval(); void loadLogs(); void applyLogsFilter(); void setupTray(); @@ -276,6 +297,18 @@ private: // dashboard refreshes do not spam the user. int m_lastNotifiedUpdates = -1; + // Cleanup page + QTableWidget* m_cleanupTable = nullptr; + QLabel* m_cleanupCount = nullptr; + QPushButton* m_cleanupRemoveOrphansButton = nullptr; + QPushButton* m_cleanupRemoveSelectionButton = nullptr; + QPushButton* m_cleanupCacheButton = nullptr; + std::vector m_cleanupCandidates; + // Providers left to process for the bulk removal in progress, with the + // packages each of them owns. They run one after another because pacman + // locks its database. + std::vector>> m_pendingRemovals; + // Plugins page QTableWidget* m_pluginTable = nullptr; QPushButton* m_pluginToggleButton = nullptr; diff --git a/include/package-manager.h b/include/package-manager.h index 1740a97..294a75b 100644 --- a/include/package-manager.h +++ b/include/package-manager.h @@ -24,6 +24,13 @@ struct PackageInfo { std::vector providers; bool installed = false; bool updateAvailable = false; + // Cleanup classification, filled by providers that report maintainable + // leftovers (see IPackageManager::listCleanupCandidates): true when no + // installed package requires this one, so it is safe to bulk-remove. + bool orphan = false; + // Short reason this row shows up as a cleanup candidate (e.g. "Orphelin", + // "Étranger"), empty for regular packages. + std::string cleanupReason; }; // Merge packages that share the same name (offered by several providers) into @@ -142,6 +149,42 @@ public: virtual std::vector listUpdates() = 0; virtual bool refresh(ProgressCallback progressCallback = nullptr) = 0; + // ---- Cleanup (optional) ---- + // Providers that can reclaim unused/legacy packages override these; the + // defaults leave providers that only install packages working unchanged. + + // Whether the provider can enumerate cleanup candidates at all. + virtual bool canListCleanup() const { return false; } + + // Packages a cleanup can reclaim: orphans (nothing installed requires + // them) and legacy leftovers (installed from outside the sync + // repositories, e.g. AUR or manual builds). Rows carry `orphan` and + // `cleanupReason`. + virtual std::vector listCleanupCandidates() { return {}; } + + // Remove several packages in one operation (a single privileged command + // instead of one per package). Defaults to a sequence of remove() calls. + virtual bool removePackages(const std::vector& packages, + ProgressCallback progressCallback = nullptr) { + bool success = true; + for (const auto& name : packages) { + success = remove(name, progressCallback) && success; + } + return success; + } + + // Whether cleanCache() actually has something to trim here, so the UI only + // offers the action for providers that own a cache. + virtual bool canCleanCache() const { return false; } + + // Free the disk space held by the provider's caches (package cache, + // unused runtimes...). Returns false when the cleanup failed; the reason is + // then in lastError(). + virtual bool cleanCache(ProgressCallback progressCallback = nullptr) { + (void)progressCallback; + return false; + } + // Check if the package manager is available on the system virtual bool isAvailable() const = 0; diff --git a/include/pacman-manager.h b/include/pacman-manager.h index 792e3b2..1a12f4d 100644 --- a/include/pacman-manager.h +++ b/include/pacman-manager.h @@ -43,6 +43,24 @@ public: // Exposed as static so the parsing can be unit-tested without invoking pacman. static std::map parseSyncRepos(const std::string& output); + // Merge `pacman -Qdt` (orphans) and `pacman -Qm` (foreign) output into + // cleanup candidates tagged with their reason: orphans are safe to + // bulk-remove, foreign packages are listed for review only since nothing + // proves they are unused. Exposed as static so it can be unit-tested + // without invoking pacman. + static std::vector parseCleanupOutput(const std::string& orphans, + const std::string& foreign); + + // `pacman -Rns` command removing every given package together with the + // dependencies it dragged in, or empty when the list is empty. Exposed as + // static so the command can be unit-tested without invoking pacman. + static std::string removePackagesCommand(const std::vector& packages); + + // Command that trims the package cache, given whether paccache + // (pacman-contrib) is installed on this system. Exposed as static so both + // branches can be unit-tested without invoking pacman. + static std::string cleanCacheCommand(bool paccacheAvailable); + // Detect a sudo authentication failure (wrong or missing password) in the // output of a privileged command. Exposed as static so it can be // unit-tested without invoking sudo. @@ -79,6 +97,16 @@ public: std::vector listUpdates() override; bool refresh(ProgressCallback progressCallback = nullptr) override; + // Cleanup: pacman is the one provider that knows about packages no longer + // required by anything (-Qdt) and about legacy installs coming from + // outside the sync databases (-Qm). + bool canListCleanup() const override { return true; } + bool canCleanCache() const override { return true; } + std::vector listCleanupCandidates() override; + bool removePackages(const std::vector& packages, + ProgressCallback progressCallback = nullptr) override; + bool cleanCache(ProgressCallback progressCallback = nullptr) override; + private: bool isPackageInstalled(const std::string& name); diff --git a/plugins/flatpak-provider/flatpak-manager.cpp b/plugins/flatpak-provider/flatpak-manager.cpp index 642b8f6..f27e355 100644 --- a/plugins/flatpak-provider/flatpak-manager.cpp +++ b/plugins/flatpak-provider/flatpak-manager.cpp @@ -461,3 +461,22 @@ bool FlatpakManager::refresh(ProgressCallback progressCallback) { integrateAllInstalled(); return true; } + +bool FlatpakManager::cleanCache(ProgressCallback progressCallback) { + m_lastError.clear(); + if (progressCallback) { + progressCallback("Suppression des runtimes Flatpak inutilisés...", -1); + } + + // Runtimes left behind by uninstalled applications weigh several hundred + // megabytes each; flatpak only removes those no installed app references. + std::string output = exec( + "flatpak uninstall --unused --noninteractive --assumeyes 2>&1"); + streamOutput(output, progressCallback); + + if (output.find("error:") != std::string::npos) { + m_lastError = lastOutputLines(output); + return false; + } + return true; +} diff --git a/plugins/flatpak-provider/flatpak-manager.h b/plugins/flatpak-provider/flatpak-manager.h index 2227b8b..62b7bd4 100644 --- a/plugins/flatpak-provider/flatpak-manager.h +++ b/plugins/flatpak-provider/flatpak-manager.h @@ -49,6 +49,11 @@ public: std::vector listUpdates() override; bool refresh(ProgressCallback progressCallback = nullptr) override; + // Cleanup: flatpak knows which runtimes no installed application uses any + // more, so it can reclaim them from the maintenance page. + bool canCleanCache() const override { return true; } + bool cleanCache(ProgressCallback progressCallback = nullptr) override; + // Make an app appear in the desktop's application launcher (wofi, GNOME, // KDE, ...) regardless of XDG_DATA_DIRS, like a pacman install would: link // its .desktop entries and icons from flatpak's exports into the user's diff --git a/resources/icons/broom.svg b/resources/icons/broom.svg new file mode 100644 index 0000000..6a51a34 --- /dev/null +++ b/resources/icons/broom.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/resources/resources.qrc b/resources/resources.qrc index e499842..821fb5a 100644 --- a/resources/resources.qrc +++ b/resources/resources.qrc @@ -15,5 +15,6 @@ icons/filter.svg icons/alert.svg icons/plugin.svg + icons/broom.svg \ No newline at end of file diff --git a/src/main-window.cpp b/src/main-window.cpp index 96df58b..731b04c 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -92,22 +92,34 @@ void ListWorker::run() { pkg.provider = pm->getName(); results.push_back(pkg); } - } else { + } else if (m_mode == Updates) { if (!pm->canUpdate()) continue; for (auto& pkg : pm->listUpdates()) { pkg.provider = pm->getName(); results.push_back(pkg); } + } else { + if (!pm->canListCleanup()) continue; + for (auto& pkg : pm->listCleanupCandidates()) { + pkg.provider = pm->getName(); + results.push_back(pkg); + } } } // One row per package name, whatever the number of providers offering it. - mergeProviderDuplicates(results); + // Cleanup candidates stay as reported: each row is tied to the provider + // that must remove it, and merging would hide which one reported it. + if (m_mode != Cleanup) mergeProviderDuplicates(results); emit finished(results); } InstallWorker::InstallWorker(IPackageManager* pm, Op op, const std::string& package) : m_providers{pm}, m_op(op), m_package(package) {} +InstallWorker::InstallWorker(IPackageManager* pm, Op op, + const std::vector& packages) + : m_providers{pm}, m_op(op), m_packages(packages) {} + InstallWorker::InstallWorker(const std::vector& providers, Op op) : m_providers(providers), m_op(op) {} @@ -134,6 +146,10 @@ void InstallWorker::run() { case Op::Update: success = pm->update(m_package, cb) && success; break; case Op::UpdateAll: success = pm->update("", cb) && success; break; case Op::Refresh: success = pm->refresh(cb) && success; break; + case Op::RemovePackages: + success = pm->removePackages(m_packages, cb) && success; + break; + case Op::CleanCache: success = pm->cleanCache(cb) && success; break; } } emit finished(success); @@ -304,6 +320,7 @@ void MainWindow::setupUI() { setupHistoryPage(); setupLogsPage(); setupPluginsPage(); + setupCleanupPage(); contentLayout->addWidget(m_pages, 1); rootLayout->addWidget(content, 1); @@ -539,6 +556,8 @@ void MainWindow::setupSidebar() { addNavButton(NavSearch, "search", "Recherche", "Rechercher des paquets"); addNavButton(NavInstalled, "package", "Installés", "Voir les paquets installés"); addNavButton(NavUpdates, "arrow-up", "Mises à jour", "Voir les mises à jour disponibles"); + addNavButton(NavCleanup, "broom", "Nettoyage", + "Purger les paquets inutilisés ou legacy et vider les caches"); layout->addSpacing(8); addNavButton(NavHistory, "history", "Historique", "Historique des actions"); addNavButton(NavLogs, "logs", "Logs", "Logs pacman"); @@ -633,6 +652,14 @@ void MainWindow::setupDashboardPage() { connect(btnUpdateAll, &QPushButton::clicked, this, &MainWindow::onUpdateAll); actionsRow->addWidget(btnUpdateAll); + QPushButton* btnCleanup = new QPushButton("Nettoyer le système"); + btnCleanup->setIcon(loadIcon("broom")); + btnCleanup->setToolTip("Purger les paquets inutilisés et vider les caches"); + connect(btnCleanup, &QPushButton::clicked, this, [this]() { + m_navGroup->button(NavCleanup)->click(); + }); + actionsRow->addWidget(btnCleanup); + QPushButton* btnRefresh = new QPushButton("Rafraîchir les sources"); btnRefresh->setProperty("variant", "info"); btnRefresh->setIcon(loadIcon("refresh")); @@ -886,7 +913,8 @@ void MainWindow::setupHistoryPage() { filterRow->addWidget(filterLabel); m_historyFilter = new QComboBox(); - m_historyFilter->addItems({"Toutes les actions", "Installations", "Suppressions", "Mises à jour"}); + m_historyFilter->addItems({"Toutes les actions", "Installations", "Suppressions", + "Mises à jour", "Nettoyages"}); connect(m_historyFilter, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::onHistoryFilterChanged); filterRow->addWidget(m_historyFilter); @@ -1058,6 +1086,103 @@ void MainWindow::setupPluginsPage() { m_pages->addWidget(page); } +// Maintenance page: lists what a cleanup can reclaim (orphans and legacy +// packages reported by every provider) and frees the disk space the providers +// hold in their caches. Nothing runs until the user asks for it: the candidate +// list is only built on demand, since both queries cost a pacman call. +void MainWindow::setupCleanupPage() { + QWidget* page = new QWidget(); + QVBoxLayout* layout = new QVBoxLayout(page); + layout->setContentsMargins(24, 20, 24, 20); + layout->setSpacing(12); + + QFrame* hintCard = makeCard(); + QVBoxLayout* hintLayout = new QVBoxLayout(hintCard); + hintLayout->setContentsMargins(18, 16, 18, 16); + hintLayout->setSpacing(4); + + QLabel* hintTitle = new QLabel("PAQUETS INUTILISÉS ET LEGACY"); + hintTitle->setObjectName("cardTitle"); + hintLayout->addWidget(hintTitle); + + QLabel* hint = new QLabel( + "Les orphelins ont été installés comme dépendances et ne sont " + "plus requis par aucun paquet : ils peuvent être supprimés sans risque. " + "Les paquets étrangers viennent de l'AUR ou d'une compilation " + "manuelle : vérifiez-les un par un avant de les supprimer."); + hint->setTextFormat(Qt::RichText); + hint->setWordWrap(true); + hint->setStyleSheet("font-size: 12px; color: #7a8299;"); + hintLayout->addWidget(hint); + + layout->addWidget(hintCard); + + m_cleanupTable = new QTableWidget(0, 4); + m_cleanupTable->setHorizontalHeaderLabels( + {"Paquet", "Version", "Type", "Fournisseur"}); + m_cleanupTable->verticalHeader()->setVisible(false); + m_cleanupTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_cleanupTable->setSelectionMode(QAbstractItemView::SingleSelection); + m_cleanupTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_cleanupTable->setShowGrid(false); + m_cleanupTable->setAlternatingRowColors(true); + m_cleanupTable->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + m_cleanupTable->verticalHeader()->setDefaultSectionSize(36); + m_cleanupTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); + m_cleanupTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + m_cleanupTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); + m_cleanupTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); + connect(m_cleanupTable, &QTableWidget::currentCellChanged, this, + [this](int currentRow, int, int, int) { onCleanupSelectionChanged(currentRow); }); + layout->addWidget(m_cleanupTable, 1); + + QHBoxLayout* buttonBar = new QHBoxLayout(); + buttonBar->setSpacing(8); + + QPushButton* scanButton = new QPushButton("Analyser"); + scanButton->setProperty("variant", "primary"); + scanButton->setIcon(loadIcon("search")); + scanButton->setToolTip("Rechercher les paquets inutilisés et legacy"); + connect(scanButton, &QPushButton::clicked, this, &MainWindow::onCleanupScan); + buttonBar->addWidget(scanButton); + + m_cleanupRemoveOrphansButton = new QPushButton("Supprimer les orphelins"); + m_cleanupRemoveOrphansButton->setProperty("variant", "danger"); + m_cleanupRemoveOrphansButton->setIcon(loadIcon("trash")); + m_cleanupRemoveOrphansButton->setEnabled(false); + m_cleanupRemoveOrphansButton->setToolTip( + "Supprimer tous les paquets que plus rien ne requiert"); + connect(m_cleanupRemoveOrphansButton, &QPushButton::clicked, + this, &MainWindow::onRemoveCleanupOrphans); + buttonBar->addWidget(m_cleanupRemoveOrphansButton); + + m_cleanupRemoveSelectionButton = new QPushButton("Supprimer la sélection"); + m_cleanupRemoveSelectionButton->setIcon(loadIcon("trash")); + m_cleanupRemoveSelectionButton->setEnabled(false); + connect(m_cleanupRemoveSelectionButton, &QPushButton::clicked, + this, &MainWindow::onRemoveCleanupSelection); + buttonBar->addWidget(m_cleanupRemoveSelectionButton); + + m_cleanupCacheButton = new QPushButton("Vider les caches"); + m_cleanupCacheButton->setProperty("variant", "warning"); + m_cleanupCacheButton->setIcon(loadIcon("broom")); + m_cleanupCacheButton->setToolTip( + "Purger le cache de paquets (paccache / pacman -Sc) et les runtimes " + "Flatpak inutilisés"); + connect(m_cleanupCacheButton, &QPushButton::clicked, this, &MainWindow::onCleanCaches); + buttonBar->addWidget(m_cleanupCacheButton); + + buttonBar->addStretch(); + + m_cleanupCount = new QLabel(""); + m_cleanupCount->setStyleSheet("font-size: 12px; color: #7a8299; font-weight: 600;"); + buttonBar->addWidget(m_cleanupCount); + + layout->addLayout(buttonBar); + + m_pages->addWidget(page); +} + void MainWindow::setupMenuBar() { QMenuBar* menuBar = this->menuBar(); menuBar->setStyleSheet( @@ -1094,6 +1219,8 @@ void MainWindow::setupMenuBar() { [this]() { m_navGroup->button(NavInstalled)->click(); }); toolsMenu->addAction("Mises à jour", this, [this]() { m_navGroup->button(NavUpdates)->click(); }); + toolsMenu->addAction("Nettoyage", this, + [this]() { m_navGroup->button(NavCleanup)->click(); }); toolsMenu->addAction("Historique", this, [this]() { m_navGroup->button(NavHistory)->click(); }); toolsMenu->addAction("Logs pacman", this, @@ -1312,6 +1439,11 @@ void MainWindow::updatePageTitle() { m_headerTitle->setText("Mises à jour disponibles"); m_headerSubtitle->setText("Maintenez votre système à jour"); break; + case NavCleanup: + m_headerTitle->setText("Nettoyage"); + m_headerSubtitle->setText( + "Purger les paquets inutilisés ou legacy et libérer de l'espace"); + break; case NavHistory: m_headerTitle->setText("Historique"); m_headerSubtitle->setText("Journal de toutes vos actions"); @@ -1350,6 +1482,10 @@ void MainWindow::onNavChanged(int id) { setBrowseMode(ModeUpdates); loadUpdates(); break; + case NavCleanup: + m_pages->setCurrentIndex(PageCleanup); + loadCleanup(); + break; case NavHistory: m_pages->setCurrentIndex(PageHistory); refreshHistoryTable(); @@ -1856,6 +1992,276 @@ void MainWindow::onRefresh() { worker->start(); } +void MainWindow::onCleanupScan() { + loadCleanup(); +} + +void MainWindow::loadCleanup() { + std::vector providers = m_pluginManager->availableManagers(); + if (providers.empty()) { + statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); + return; + } + + setBusy(true); + statusBar()->showMessage("Analyse des paquets inutilisés et legacy..."); + m_cleanupTable->setRowCount(0); + m_cleanupCandidates.clear(); + m_cleanupRemoveOrphansButton->setEnabled(false); + m_cleanupRemoveSelectionButton->setEnabled(false); + + auto* worker = new ListWorker(providers, ListWorker::Cleanup); + connect(worker, &ListWorker::finished, this, &MainWindow::onCleanupListFinished); + connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); + worker->start(); +} + +void MainWindow::onCleanupListFinished(std::vector results) { + setBusy(false); + populateCleanupTable(results); + + int orphans = 0; + for (const auto& pkg : results) { + if (pkg.orphan) ++orphans; + } + statusBar()->showMessage( + QString("%1 orphelin(s) et %2 paquet(s) legacy détecté(s)") + .arg(orphans).arg(static_cast(results.size()) - orphans)); +} + +void MainWindow::populateCleanupTable(const std::vector& candidates) { + m_cleanupCandidates = candidates; + m_cleanupTable->setRowCount(0); + m_cleanupTable->setRowCount(static_cast(candidates.size())); + + QFont nameFont; + nameFont.setWeight(QFont::DemiBold); + + int orphans = 0; + for (int i = 0; i < static_cast(candidates.size()); ++i) { + const PackageInfo& pkg = candidates[i]; + if (pkg.orphan) ++orphans; + + QTableWidgetItem* nameItem = new QTableWidgetItem(QString::fromStdString(pkg.name)); + nameItem->setFont(nameFont); + m_cleanupTable->setItem(i, 0, nameItem); + + m_cleanupTable->setItem(i, 1, + new QTableWidgetItem(QString::fromStdString(pkg.version))); + + QTableWidgetItem* typeItem = + new QTableWidgetItem(QString::fromStdString(pkg.cleanupReason)); + typeItem->setForeground(QColor(pkg.orphan ? "#e0af68" : "#7a8299")); + typeItem->setIcon(loadIcon(pkg.orphan ? "alert" : "package")); + m_cleanupTable->setItem(i, 2, typeItem); + + m_cleanupTable->setItem(i, 3, + new QTableWidgetItem(providersLabel(m_pluginManager, pkg))); + } + + m_cleanupCount->setText(QString("%1 orphelin(s) · %2 legacy") + .arg(orphans).arg(static_cast(candidates.size()) - orphans)); + m_cleanupRemoveOrphansButton->setEnabled(orphans > 0); + m_cleanupRemoveOrphansButton->setText(orphans > 0 + ? QString("Supprimer les orphelins (%1)").arg(orphans) + : QString("Supprimer les orphelins")); + + if (!candidates.empty()) m_cleanupTable->selectRow(0); + onCleanupSelectionChanged(m_cleanupTable->currentRow()); +} + +void MainWindow::onCleanupSelectionChanged(int row) { + if (row < 0 || row >= static_cast(m_cleanupCandidates.size())) { + m_cleanupRemoveSelectionButton->setEnabled(false); + m_cleanupRemoveSelectionButton->setToolTip(QString()); + return; + } + + const PackageInfo& pkg = m_cleanupCandidates[row]; + const QString name = QString::fromStdString(pkg.name); + m_cleanupRemoveSelectionButton->setEnabled(true); + // A legacy package is only ever removed one by one and with an explicit + // warning: nothing on the system proves it is unused. + m_cleanupRemoveSelectionButton->setToolTip( + pkg.orphan + ? QString("Supprimer « %1 » (orphelin)").arg(name) + : QString("Supprimer « %1 » (%2) — à vérifier : rien ne prouve " + "qu'il est inutilisé") + .arg(name, QString::fromStdString(pkg.cleanupReason))); +} + +void MainWindow::onRemoveCleanupOrphans() { + std::vector orphans; + for (const auto& pkg : m_cleanupCandidates) { + if (pkg.orphan) orphans.push_back(pkg); + } + if (orphans.empty()) { + statusBar()->showMessage("Aucun orphelin à supprimer."); + return; + } + removeCleanupPackages(orphans, QString("%1 orphelin(s)").arg(orphans.size())); +} + +void MainWindow::onRemoveCleanupSelection() { + const int row = m_cleanupTable->currentRow(); + if (row < 0 || row >= static_cast(m_cleanupCandidates.size())) return; + + // Copied: the candidate list is rebuilt once the removal completes. + const PackageInfo pkg = m_cleanupCandidates[row]; + removeCleanupPackages({pkg}, + QString("« %1 »").arg(QString::fromStdString(pkg.name))); +} + +// Groups the candidates per provider (each provider then gets a single removal +// command), confirms once, and hands over to the sequential runner below. +void MainWindow::removeCleanupPackages(const std::vector& packages, + const QString& description) { + m_pendingRemovals.clear(); + for (const auto& pkg : packages) { + IPackageManager* provider = providerFor(pkg.provider); + if (!provider || !provider->canRemove()) continue; + + auto group = std::find_if( + m_pendingRemovals.begin(), m_pendingRemovals.end(), + [provider](const auto& entry) { return entry.first == provider; }); + if (group == m_pendingRemovals.end()) { + m_pendingRemovals.push_back({provider, {pkg.name}}); + } else { + group->second.push_back(pkg.name); + } + } + + if (m_pendingRemovals.empty()) { + statusBar()->showMessage("Aucun paquet sélectionné n'est supprimable."); + return; + } + + if (QMessageBox::question(this, "Nettoyage", + QString("Supprimer %1 ?\n\nCette action est irréversible.") + .arg(description)) != QMessageBox::Yes) { + m_pendingRemovals.clear(); + return; + } + + std::vector providers; + for (const auto& entry : m_pendingRemovals) providers.push_back(entry.first); + + if (!tryAcquireOp()) { + m_pendingRemovals.clear(); + return; + } + if (!ensureCredentials(providers)) { + setBusy(false); + m_pendingRemovals.clear(); + return; + } + + startNextCleanupRemoval(); +} + +// Removes the next provider's group of packages, then chains into the +// following one. Two removals never run at once: pacman locks its database for +// the whole operation. +void MainWindow::startNextCleanupRemoval() { + if (m_pendingRemovals.empty()) { + setBusy(false); + clearCredentialsAfterUse(); + m_detailsCache.clear(); + loadCleanup(); + refreshDashboard(); + return; + } + + const auto job = m_pendingRemovals.front(); + m_pendingRemovals.erase(m_pendingRemovals.begin()); + IPackageManager* provider = job.first; + const std::vector packages = job.second; + + statusBar()->showMessage( + QString("Suppression de %1 paquet(s)...").arg(packages.size())); + + auto* worker = new InstallWorker(provider, InstallWorker::Op::RemovePackages, packages); + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { + statusBar()->showMessage(msg); + }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); + connect(worker, &InstallWorker::finished, this, + [this, provider, packages](bool success) { + if (success) { + statusBar()->showMessage( + QString("%1 paquet(s) supprimé(s)").arg(packages.size())); + } else { + statusBar()->showMessage("Échec du nettoyage"); + showProviderError("Échec du nettoyage", provider); + } + // One history row per removed package keeps the install/remove filters + // of the History page meaningful. + for (const auto& name : packages) { + m_historyManager->record({"", "remove", name, provider->getName(), success}); + } + startNextCleanupRemoval(); + }); + connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); + worker->start(); +} + +void MainWindow::onCleanCaches() { + std::vector providers; + QStringList names; + for (IPackageManager* pm : m_pluginManager->availableManagers()) { + if (!pm->canCleanCache()) continue; + providers.push_back(pm); + names << QString::fromStdString(pm->getName()); + } + if (providers.empty()) { + statusBar()->showMessage("Aucun cache à nettoyer sur ce système."); + return; + } + + if (QMessageBox::question(this, "Nettoyage", + QString("Vider les caches de %1 ?\n\npacman ne conserve que la " + "dernière version de chaque paquet téléchargé et Flatpak " + "supprime les runtimes qu'aucune application n'utilise " + "plus.").arg(names.join(", "))) != QMessageBox::Yes) { + return; + } + + if (!tryAcquireOp()) return; + if (!ensureCredentials(providers)) { + setBusy(false); + return; + } + + statusBar()->showMessage("Nettoyage des caches..."); + + auto* worker = new InstallWorker(providers, InstallWorker::Op::CleanCache); + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { + statusBar()->showMessage(msg); + }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); + connect(worker, &InstallWorker::finished, this, [this, providers](bool success) { + setBusy(false); + if (success) { + statusBar()->showMessage("Caches nettoyés"); + } else { + statusBar()->showMessage("Échec du nettoyage des caches"); + for (IPackageManager* pm : providers) { + if (!pm->lastError().empty()) { + showProviderError("Échec du nettoyage des caches", pm); + break; + } + } + } + for (IPackageManager* pm : providers) { + m_historyManager->record({"", "cleanup", "caches", pm->getName(), success}); + } + clearCredentialsAfterUse(); + refreshDashboard(); + }); + connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); + worker->start(); +} + void MainWindow::performInstall(const std::string& package) { IPackageManager* provider = providerFor(m_selectedPackage.provider); if (!provider || !provider->canInstall()) return; @@ -1999,7 +2405,8 @@ void MainWindow::refreshHistoryTable() { bool match = filter == 0 || (filter == 1 && entry.action == "install") || (filter == 2 && entry.action == "remove") - || (filter == 3 && entry.action == "update"); + || (filter == 3 && entry.action == "update") + || (filter == 4 && entry.action == "cleanup"); if (match) entries.push_back(entry); } @@ -2016,6 +2423,9 @@ void MainWindow::refreshHistoryTable() { } else if (entry.action == "remove") { actionText = "Suppression"; actionColor = "#f7768e"; + } else if (entry.action == "cleanup") { + actionText = "Nettoyage"; + actionColor = "#56b6c2"; } else { actionText = "Mise à jour"; actionColor = "#e0af68"; @@ -2175,6 +2585,8 @@ void MainWindow::refreshRecentActivity() { actionText = "Installation"; actionBg = "#12301f"; actionFg = "#3fb950"; } else if (entry.action == "remove") { actionText = "Suppression"; actionBg = "#3a1a1a"; actionFg = "#f7768e"; + } else if (entry.action == "cleanup") { + actionText = "Nettoyage"; actionBg = "#12333a"; actionFg = "#56b6c2"; } else { actionText = "Mise à jour"; actionBg = "#3d2f0f"; actionFg = "#e0af68"; } diff --git a/src/pacman-manager.cpp b/src/pacman-manager.cpp index 5d1f0ac..844445d 100644 --- a/src/pacman-manager.cpp +++ b/src/pacman-manager.cpp @@ -300,6 +300,76 @@ std::vector PacmanManager::listUpdates() { return parseUpdatesOutput(exec("pacman -Qu 2>&1")); } +// Orphans (-Qdt: no installed package requires them) and legacy packages (-Qm: +// installed from outside the sync databases, i.e. AUR or manual builds). +std::vector PacmanManager::listCleanupCandidates() { + // `pacman -Qdt` warns on stderr when the system has no orphan at all: only + // stdout is parsed, so the warning never reaches the candidate list. + return parseCleanupOutput(exec("pacman -Qdt 2>/dev/null"), + exec("pacman -Qm 2>/dev/null")); +} + +bool PacmanManager::removePackages(const std::vector& packages, + ProgressCallback progressCallback) { + const std::string command = removePackagesCommand(packages); + if (command.empty()) return true; + + if (progressCallback) { + progressCallback("Suppression de " + std::to_string(packages.size()) + + " paquet(s)...", -1); + } + + std::string output = execPrivileged(command, m_password, progressCallback); + + m_lastError.clear(); + if (authFailed(output)) { + clearPassword(); + m_lastError = "Échec d'authentification sudo."; + return false; + } + if (dbLocked(output)) { + m_lastError = dbLockHint(); + return false; + } + + // One missing target or one package still required by another fails the + // whole transaction, so report the real cause instead of a partial cleanup. + if (output.find("error:") != std::string::npos + || output.find("erreur") != std::string::npos) { + m_lastError = "Échec de la suppression des paquets.\nDétail :\n" + + lastOutputLines(output); + return false; + } + return true; +} + +bool PacmanManager::cleanCache(ProgressCallback progressCallback) { + const bool paccache = + system("command -v paccache > /dev/null 2>&1") == 0; + if (progressCallback) progressCallback("Nettoyage du cache pacman...", -1); + + std::string output = + execPrivileged(cleanCacheCommand(paccache), m_password, progressCallback); + + m_lastError.clear(); + if (authFailed(output)) { + clearPassword(); + m_lastError = "Échec d'authentification sudo."; + return false; + } + if (dbLocked(output)) { + m_lastError = dbLockHint(); + return false; + } + if (output.find("error:") != std::string::npos + || output.find("erreur") != std::string::npos) { + m_lastError = "Échec du nettoyage du cache pacman.\nDétail :\n" + + lastOutputLines(output); + return false; + } + return true; +} + bool PacmanManager::refresh(ProgressCallback progressCallback) { if (progressCallback) progressCallback("Rafraîchissement des bases de données...", -1); @@ -444,6 +514,51 @@ std::map PacmanManager::parseSyncRepos( return repos; } +// Orphans first: they are the rows the UI can bulk-remove, and the ones users +// look for. Foreign packages follow, marked so the UI never removes them +// without an explicit per-row confirmation. +std::vector PacmanManager::parseCleanupOutput(const std::string& orphans, + const std::string& foreign) { + std::vector results = parseInstalledOutput(orphans); + for (auto& pkg : results) { + pkg.orphan = true; + pkg.cleanupReason = "Orphelin"; + } + + // A foreign package can also be an orphan; the orphan classification is the + // meaningful one (it is the one that may be removed in bulk). + std::set seen; + for (const auto& pkg : results) seen.insert(pkg.name); + for (auto& pkg : parseInstalledOutput(foreign)) { + if (!seen.insert(pkg.name).second) continue; + pkg.cleanupReason = "Étranger (AUR / manuel)"; + results.push_back(pkg); + } + + return results; +} + +std::string PacmanManager::removePackagesCommand(const std::vector& packages) { + if (packages.empty()) return {}; + + // -s also drops the dependencies these packages dragged in, -n their + // pacman-managed config backups. --noconfirm keeps the removal unattended: + // the UI already asked the user before starting. + std::string command = "pacman -Rns --noconfirm"; + for (const auto& name : packages) { + command += " " + shellQuote(name); + } + return command; +} + +std::string PacmanManager::cleanCacheCommand(bool paccacheAvailable) { + // paccache (pacman-contrib) keeps the latest version of every package, + // which is far more conservative than `pacman -Sc`: the latter also drops + // the cached copies of packages that are still installed, so a later + // rollback or reinstall has to download them again. + return paccacheAvailable ? "paccache -rk1" : "pacman -Sc --noconfirm"; +} + bool PacmanManager::authFailed(const std::string& output) { return output.find("incorrect password") != std::string::npos || output.find("a password is required") != std::string::npos diff --git a/tests/pacman-manager.test.cpp b/tests/pacman-manager.test.cpp index 683dd4c..d145542 100644 --- a/tests/pacman-manager.test.cpp +++ b/tests/pacman-manager.test.cpp @@ -99,6 +99,76 @@ static void testParseSyncRepos_emptyInput() { assert(PacmanManager::parseSyncRepos("").empty()); } +static void testParseCleanupOutput_tagsOrphans() { + auto pkgs = PacmanManager::parseCleanupOutput("libedit 20240808-1\n", ""); + + assert(pkgs.size() == 1); + assert(pkgs[0].name == "libedit"); + assert(pkgs[0].cleanupReason == "Orphelin"); + assert(pkgs[0].orphan); +} + +static void testParseCleanupOutput_tagsForeignAsLegacy() { + auto pkgs = PacmanManager::parseCleanupOutput("", "yay-bin 12.4.2-1\n"); + + assert(pkgs.size() == 1); + assert(pkgs[0].name == "yay-bin"); + // Legacy installs are listed for review, never bulk-removed. + assert(!pkgs[0].orphan); + assert(pkgs[0].cleanupReason.find("tranger") != std::string::npos); +} + +static void testParseCleanupOutput_orphanWinsOverForeign() { + // A foreign package can also be orphaned: it stays bulk-removable, which is + // the classification the cleanup page acts on. + auto pkgs = PacmanManager::parseCleanupOutput("yay-bin 12.4.2-1\n", + "yay-bin 12.4.2-1\n"); + + assert(pkgs.size() == 1); + assert(pkgs[0].orphan); +} + +static void testParseCleanupOutput_keepsBothSources() { + auto pkgs = PacmanManager::parseCleanupOutput("libedit 20240808-1\n", + "yay-bin 12.4.2-1\n"); + + assert(pkgs.size() == 2); + assert(pkgs[0].name == "libedit" && pkgs[0].orphan); + assert(pkgs[1].name == "yay-bin" && !pkgs[1].orphan); +} + +static void testParseCleanupOutput_emptyInput() { + assert(PacmanManager::parseCleanupOutput("", "").empty()); +} + +static void testRemovePackagesCommand_listsEveryPackage() { + std::string cmd = PacmanManager::removePackagesCommand({"libedit", "python-pip"}); + + assert(cmd == "pacman -Rns --noconfirm 'libedit' 'python-pip'"); +} + +static void testRemovePackagesCommand_emptyIsNoOp() { + // Nothing to remove: the caller then has no command to run at all. + assert(PacmanManager::removePackagesCommand({}).empty()); +} + +static void testRemovePackagesCommand_quotesNames() { + // Package names are data: spaces and quotes must not reach the shell as + // syntax, whatever the cleanup page lists. + assert(PacmanManager::removePackagesCommand({"libedit; rm -rf /"}) + == "pacman -Rns --noconfirm 'libedit; rm -rf /'"); + assert(PacmanManager::removePackagesCommand({"a'b"}) + == "pacman -Rns --noconfirm 'a'\\''b'"); +} + +static void testCleanCacheCommand_prefersPaccache() { + assert(PacmanManager::cleanCacheCommand(true) == "paccache -rk1"); +} + +static void testCleanCacheCommand_fallsBackToPacman() { + assert(PacmanManager::cleanCacheCommand(false) == "pacman -Sc --noconfirm"); +} + static void testAuthFailed_detectsWrongPassword() { assert(PacmanManager::authFailed( "[sudo] password for alice: Sorry, try again.\nsudo: 1 incorrect password attempt")); @@ -151,6 +221,19 @@ int main() { testParseSyncRepos_skipsHeader(); testParseSyncRepos_emptyInput(); + testParseCleanupOutput_tagsOrphans(); + testParseCleanupOutput_tagsForeignAsLegacy(); + testParseCleanupOutput_orphanWinsOverForeign(); + testParseCleanupOutput_keepsBothSources(); + testParseCleanupOutput_emptyInput(); + + testRemovePackagesCommand_listsEveryPackage(); + testRemovePackagesCommand_emptyIsNoOp(); + testRemovePackagesCommand_quotesNames(); + + testCleanCacheCommand_prefersPaccache(); + testCleanCacheCommand_fallsBackToPacman(); + testAuthFailed_detectsWrongPassword(); testAuthFailed_detectsMissingPassword(); testAuthFailed_ignoresPacmanErrors();