diff --git a/CMakeLists.txt b/CMakeLists.txt index eef050f..ef99ab4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,6 +7,13 @@ set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) +# The repo-root `version` file is the single source of truth for release +# versioning. It is compiled into the binaries as well as installed next to +# them, so a running app always reports the release it was built from instead +# of trusting a `version` file that an update may have left stale. +file(READ ${CMAKE_CURRENT_SOURCE_DIR}/version PACMANAGER_VERSION) +string(STRIP "${PACMANAGER_VERSION}" PACMANAGER_VERSION) + # Find Qt6 find_package(Qt6 REQUIRED COMPONENTS Widgets Network) @@ -39,6 +46,8 @@ add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) target_include_directories(${PROJECT_NAME} PRIVATE include) target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Widgets Qt6::Network) +target_compile_definitions(${PROJECT_NAME} PRIVATE + FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}") # Copy the version file next to the executable so UpdateManager can read the # running build's version at runtime. @@ -124,6 +133,8 @@ add_executable(update-manager-test tests/update-manager.test.cpp src/update-manager.cpp src/app-logging.cpp include/update-manager.h) target_include_directories(update-manager-test PRIVATE include) target_link_libraries(update-manager-test PRIVATE Qt6::Core Qt6::Network) +target_compile_definitions(update-manager-test PRIVATE + FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}") add_test(NAME update-manager-test COMMAND update-manager-test) # ---- Plugins ---- diff --git a/README.en.md b/README.en.md index ce2132c..4a02ff6 100644 --- a/README.en.md +++ b/README.en.md @@ -8,6 +8,7 @@ Package manager for **Arch Linux** based on **pacman**, with a Qt6 graphical int - 📦 **Package installation** - 🗑️ **Package removal** - 🔄 **Individual or global updates** +- 🧹 **Cleanup**: orphan and legacy packages, cache trimming - 📋 **History of all actions** - 🧩 **Plugins**: package managers (pacman built-in, **Flatpak shipped by default**) and **extensions** written in C++ (UI addons, helpers, …) @@ -128,7 +129,7 @@ The method is picked automatically (no configuration): | Method | When | What happens | | --- | --- | --- | -| **Checkout** | a source checkout surrounds the binary (dev) | `git pull` + rebuild in place | +| **Checkout** | a source checkout surrounds the binary (dev) | `git pull`, rebuild, install into the binary's directory | | **Clone** | installed app with no checkout, and `git` + `cmake` + a compiler | the repo is cloned/updated in `~/.local/share/PacManager/src`, rebuilt and installed in place | | **Prebuilt** | no build toolchain available | the release's prebuilt archive is downloaded and unpacked | | **Tarball** | no `git`, but `cmake` + a compiler | the release sources are built and installed | @@ -137,6 +138,11 @@ Everything builds in a temporary directory: only the final replacement of the binary (and plugins) needs `sudo`, and only when the target directory is owned by root. PacManager then restarts automatically on the new version. +All four methods install to the same place — the running binary's directory — +and rewrite the `version` file there. On top of that, the app reports the +version **compiled into the binary** (from the repo's `version` file) first, so +the same update is never offered again once it has been applied. + ## Graphical interface The interface uses **Qt6** with a dark theme, a **navigation sidebar** and stacked pages: @@ -144,10 +150,12 @@ The interface uses **Qt6** with a dark theme, a **navigation sidebar** and stack - 🔍 **Search**: search bar, package table on the left and details on the right - 📦 **Installed**: list with **instant name filter** (local, no pacman re-run) - ⬆️ **Updates**: outdated packages detected by `pacman -Qu`, "Update all" button -- 📋 **History**: filterable table (installs / removals / updates) + CSV export +- 🧹 **Cleanup**: **orphan** packages (`pacman -Qdt`, nothing requires them) and **legacy** ones (`pacman -Qm`, AUR / manual builds), bulk removal of the orphans, and cache trimming: `paccache` / `pacman -Sc` and unused Flatpak runtimes (`flatpak uninstall --unused`) +- 📋 **History**: filterable table (installs / removals / updates / cleanups) + CSV export - 📜 **Logs**: built-in `/var/log/pacman.log` viewer with an instant filter - 🧩 **Plugins**: lists every plugin (package providers and extensions), enable / disable and plugin rescan - ⌨️ **Convenience**: system tray icon and keyboard shortcuts (Ctrl+F search, Ctrl+R / F5 refresh, Ctrl+U updates, Ctrl+E export, Ctrl+Q quit) +- 🎨 **Legibility**: a sidebar split into sections, showing the installed version and the pending update count; quick actions (refresh, update all) in the header, reachable from any page; empty lists that say what to do next - 📤 **Export**: the displayed package list and the history can be exported as CSV ### Interface overview @@ -200,6 +208,14 @@ The `IPackageManager` interface (implemented by the built-in `PacmanManager` and | `listInstalled()` | List installed packages | | `listUpdates()` | List outdated packages | | `refresh(callback)` | Refresh the sources | +| `canListCleanup()` | Can list the packages a cleanup may reclaim | +| `listCleanupCandidates()` | Orphan (`orphan`) and legacy packages, with their reason | +| `removePackages(names, callback)` | Removes several packages in a single command | +| `canCleanCache()` / `cleanCache(callback)` | Trims the provider's cache (pacman cache, unused Flatpak runtimes) | + +The last four methods are **optional**: a provider that only installs packages +implements nothing, and the Cleanup page then simply reports that it has nothing +to offer. Search queries **all active providers at once**: every result shows its origin in the **Provider** column (Pacman, Flatpak, …), and the Installed / Updates pages are aggregated. Install, remove and update are routed automatically to the right manager. The sidebar **Plugins** page lists everything (providers **and** addons), lets you enable / disable each plugin, rescan plugins and **install a missing tool** (e.g. "Install tool" for Flatpak runs `sudo pacman -S flatpak`, then the provider becomes available). diff --git a/README.md b/README.md index 63cbf9e..2065441 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Gestionnaire de paquets pour **Arch Linux** basé sur **pacman**, avec interface - 📦 **Installation** de paquets - 🗑️ **Suppression** de paquets - 🔄 **Mise à jour** individuelle ou globale +- 🧹 **Nettoyage** : paquets orphelins et legacy, purge des caches - 📋 **Historique** de toutes les actions - 🧩 **Plugins** : gestionnaires de paquets (pacman intégré, **Flatpak livré par défaut**) et **extensions** écrites en C++ (addons graphiques, helpers, …) @@ -128,7 +129,7 @@ La méthode est choisie automatiquement (aucune configuration) : | Méthode | Quand | Ce qui se passe | | --- | --- | --- | -| **Checkout** | un dépôt source entoure le binaire (dev) | `git pull` + recompilation sur place | +| **Checkout** | un dépôt source entoure le binaire (dev) | `git pull`, recompilation puis installation dans le dossier du binaire | | **Clone** | app installée sans dépôt, avec `git` + `cmake` + compilateur | le dépôt est cloné puis mis à jour dans `~/.local/share/PacManager/src`, recompilé et installé en place | | **Prebuilt** | pas d'outillage de compilation | l'archive précompilée de la release est téléchargée et décompressée | | **Tarball** | `git` absent mais `cmake` + compilateur présents | les sources de la release sont compilées puis installées | @@ -138,6 +139,11 @@ binaire (et des plugins) demande `sudo`, et uniquement si le dossier cible appartient à root. PacManager redémarre ensuite automatiquement sur la nouvelle version. +Les quatre méthodes installent au même endroit — le dossier du binaire en cours +— et y réécrivent le fichier `version`. L'application lit de plus en priorité la +version **compilée dans le binaire** (à partir du fichier `version` du dépôt) : +une mise à jour déjà appliquée n'est donc jamais reproposée au lancement. + ## Interface graphique L'interface utilise **Qt6** avec un thème sombre, une **sidebar de navigation** et des pages empilées : @@ -145,10 +151,12 @@ L'interface utilise **Qt6** avec un thème sombre, une **sidebar de navigation** - 🔍 **Recherche** : barre de recherche, tableau de paquets à gauche et détails à droite - 📦 **Installés** : liste avec **filtre instantané** par nom (local, sans relancer pacman) - ⬆️ **Mises à jour** : paquets obsolètes détectés par `pacman -Qu`, bouton « Tout mettre à jour » -- 📋 **Historique** : tableau filtrable (installations / suppressions / mises à jour) + export CSV +- 🧹 **Nettoyage** : paquets **orphelins** (`pacman -Qdt`, rien ne les requiert) et **legacy** (`pacman -Qm`, AUR / compilation manuelle), suppression groupée des orphelins, et purge des caches : `paccache` / `pacman -Sc` et runtimes Flatpak inutilisés (`flatpak uninstall --unused`) +- 📋 **Historique** : tableau filtrable (installations / suppressions / mises à jour / nettoyages) + export CSV - 📜 **Logs** : journal `/var/log/pacman.log` intégré, avec filtre instantané - 🧩 **Plugins** : liste de tous les plugins (fournisseurs de paquets et extensions), activation / désactivation et rechargement - ⌨️ **Confort** : icône de notification (tray) et raccourcis clavier (Ctrl+F rechercher, Ctrl+R / F5 rafraîchir, Ctrl+U mises à jour, Ctrl+E exporter, Ctrl+Q quitter) +- 🎨 **Lisibilité** : barre latérale en sections, avec la version installée et le nombre de mises à jour en attente ; actions rapides (rafraîchir, tout mettre à jour) dans l'en-tête, disponibles depuis n'importe quelle page ; listes vides qui expliquent quoi faire - 📤 **Export** : liste de paquets affichée et historique exportables en CSV ### Aperçu de l'interface @@ -201,6 +209,14 @@ L'interface `IPackageManager` (implémentée par `PacmanManager` et `FlatpakMana | `listInstalled()` | Liste des paquets installés | | `listUpdates()` | Liste des paquets obsolètes | | `refresh(callback)` | Rafraîchit les sources | +| `canListCleanup()` | Peut lister les paquets à nettoyer | +| `listCleanupCandidates()` | Paquets orphelins (`orphan`) et legacy, avec leur raison | +| `removePackages(names, callback)` | Supprime plusieurs paquets en une seule commande | +| `canCleanCache()` / `cleanCache(callback)` | Purge le cache du fournisseur (cache pacman, runtimes Flatpak inutilisés) | + +Les quatre dernières méthodes sont **optionnelles** : un fournisseur qui ne fait +qu'installer des paquets n'a rien à implémenter et la page Nettoyage signale +alors simplement qu'il n'a rien à proposer. La recherche interroge **tous les fournisseurs actifs à la fois** : chaque résultat porte sa provenance dans la colonne **Fournisseur** (Pacman, Flatpak, …) et les pages Installés / Mises à jour sont agrégées. Installation, suppression et mise à jour sont routées automatiquement vers le bon gestionnaire. La page **Plugins** de la barre latérale liste tout (fournisseurs **et** addons), permet d'activer / désactiver chaque plugin, de recharger les plugins et d'**installer l'outil manquant** (ex. « Installer l'outil » pour Flatpak lance `sudo pacman -S flatpak` puis rend le fournisseur disponible). diff --git a/include/main-window.h b/include/main-window.h index a068139..93ac1f0 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,10 +128,41 @@ 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 }; + // Sidebar entries, in display order. Named so the sidebar, the dashboard + // shortcuts, the menu bar and the keyboard shortcuts cannot drift apart + // when a page is inserted. + enum NavPage { + NavDashboard = 0, + NavSearch, + NavInstalled, + NavUpdates, + NavCleanup, + NavHistory, + NavLogs, + NavPlugins, + }; + + // Indices in the stacked widget. Search / Installed / Updates share the + // browse page, so these deliberately differ from the nav ids. + enum StackedPage { + PageDashboard = 0, + PageBrowse, + PageHistory, + PageLogs, + PagePlugins, + PageCleanup, + }; + // When the sudo password is requested: once per session (at launch) or // before every privileged operation. enum class CredentialMode { AtLaunch, EachTime }; @@ -160,11 +196,15 @@ private: void setupHistoryPage(); void setupLogsPage(); void setupPluginsPage(); + void setupCleanupPage(); void setupMenuBar(); void updatePageTitle(); void updateStatusBar(); void refreshDashboard(); void refreshRecentActivity(); + // Mirrors the pending update count on the sidebar entry, so the page that + // needs attention is visible from wherever the user is. + void setUpdatesBadge(int count); void refreshPluginsTable(); void updatePackageInfo(const PackageInfo& pkg); std::string richDetails(const PackageInfo& pkg); @@ -183,18 +223,28 @@ 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(); void setupShortcuts(); void notifyUpdatesAvailable(int count); QFrame* makeCard(); - QFrame* makeStatCard(const QString& iconName, const QString& title, QLabel** valueOut); + QFrame* makeStatCard(const QString& iconName, const QString& title, + const QString& accent, QLabel** valueOut); // Sidebar QFrame* m_sidebar = nullptr; QButtonGroup* m_navGroup = nullptr; QPushButton* m_refreshButton = nullptr; + QPushButton* m_navUpdatesButton = nullptr; + QLabel* m_versionLabel = nullptr; // Header QWidget* m_headerWidget = nullptr; @@ -227,6 +277,8 @@ private: // of the window while any install/search runs. QProgressBar* m_installProgressBar = nullptr; QTableWidget* m_packageTable = nullptr; + // Listing + empty-state hint, swapped depending on the row count. + QStackedWidget* m_packageTableStack = nullptr; QLabel* m_packageName = nullptr; QLabel* m_packageVersion = nullptr; QLabel* m_packageRepo = nullptr; @@ -253,6 +305,19 @@ private: // dashboard refreshes do not spam the user. int m_lastNotifiedUpdates = -1; + // Cleanup page + QTableWidget* m_cleanupTable = nullptr; + QStackedWidget* m_cleanupTableStack = 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..5939095 100644 --- a/include/pacman-manager.h +++ b/include/pacman-manager.h @@ -1,7 +1,9 @@ #pragma once #include "package-manager.h" +#include #include +#include #include // Native Arch Linux package manager, integrated directly into the application @@ -43,6 +45,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,9 +99,39 @@ 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); + // Cache for the read-only queries several views ask for in a row: a search + // runs `pacman -Q`, the Installed page runs `-Q`, `-Qi` and `-Sl`, and the + // dashboard re-runs them on every visit. Without it that is a dozen + // subprocess spawns for a single click. The window is short enough that a + // package installed outside the app still shows up almost immediately, and + // every mutating operation drops the cache outright. + struct CachedQuery { + std::string output; + std::chrono::steady_clock::time_point fetched{}; + bool valid = false; + }; + + std::string cachedQuery(CachedQuery& slot, const char* command); + void invalidateQueries(); + + std::mutex m_queryMutex; + CachedQuery m_installedQuery; // pacman -Q + CachedQuery m_installedDetailsQuery; // pacman -Qi + CachedQuery m_syncReposQuery; // pacman -Sl + std::string m_password; std::string m_lastError; }; diff --git a/include/update-manager.h b/include/update-manager.h index f2c879a..e859c1b 100644 --- a/include/update-manager.h +++ b/include/update-manager.h @@ -13,7 +13,8 @@ // the directory that holds the running executable, wherever that is // (~/.local/bin, /usr/bin, an arbitrary extracted folder, a build tree...). // The strategy is picked by updateMethod(): -// - Checkout: a source checkout around the binary is pulled + rebuilt; +// - Checkout: a source checkout around the binary is pulled + rebuilt, then +// installed into the running binary's directory like the other methods; // - Clone: installed without a checkout, the repo is cloned (then pulled) // into ~/.local/share/PacManager/src, built, and installed in place; // - Prebuilt: the release's prebuilt archive is unpacked (no compiler); @@ -25,7 +26,9 @@ class UpdateManager : public QObject { public: explicit UpdateManager(QObject* parent = nullptr); - // Current app version, read from the version file at build time. + // Current app version, compiled in from the repo-root `version` file (see + // CMakeLists.txt), falling back to the `version` file installed next to the + // executable when the build bypassed CMake. static QString currentVersion(); // Path of the state file storing the last check date and the latest @@ -135,13 +138,14 @@ private: void saveState(const QString& remoteVersion); void loadState(); void runShell(const QString& script, const QString& workingDir); - void performCheckoutUpdate(); + void performCheckoutUpdate(const QString& sudoPassword); void performCloneUpdate(const QString& sudoPassword); void performPrebuiltUpdate(const QString& sudoPassword); void performTarballUpdate(const QString& sudoPassword); - // Shared script header for the installed (no checkout) paths: temp work - // dir, cleanup trap, and the export of the paths the install step needs. - QString installedScriptPrologue() const; + // Shared script header for every update path: temp work dir, cleanup trap, + // the release being installed, and the export of the paths the install step + // needs. + QString updateScriptPrologue() const; // Copy command that installs a staged tree ($STAGE/bin) into the running // binary's directory, wrapped in sudo when the target is not writable. QString installCommand(const QString& quotedPassword, 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 76ed3f9..905bd85 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -34,11 +34,13 @@ #include #include #include +#include #include "app-logging.h" #include #include +#include // Worker threads SearchWorker::SearchWorker(const std::vector& providers, @@ -92,22 +94,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 +148,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); @@ -190,6 +208,64 @@ static QString providersLabel(const PluginManager* pm, const PackageInfo& pkg) { return names.join(", "); } +// Inserts rows into a table in one repaint batch, with the table's signals +// muted for the duration. Without it every setItem() repaints the viewport, and +// on the browse page each selection change fires the pacman queries behind the +// details panel — a thousand rows meant a thousand repaints and a pacman call +// in the middle of the fill. +class TableFillBatch { +public: + explicit TableFillBatch(QTableWidget* table) : m_table(table) { + if (!m_table) return; + m_table->setUpdatesEnabled(false); + m_blocker = std::make_unique(m_table); + } + + // Called before the caller selects a row: that selection is what refreshes + // the details panel, so it has to be seen by the table's signals. Idempotent, + // which lets the destructor cover an early return too. + void release() { + if (!m_table || !m_blocker) return; + m_blocker.reset(); + m_table->setUpdatesEnabled(true); + } + + ~TableFillBatch() { release(); } + + TableFillBatch(const TableFillBatch&) = delete; + TableFillBatch& operator=(const TableFillBatch&) = delete; + +private: + QTableWidget* m_table = nullptr; + std::unique_ptr m_blocker; +}; + +// Wraps a listing in a stack that swaps in a centered hint while the listing is +// empty, so a page with no result explains itself instead of showing a bare +// table header. +static QStackedWidget* withEmptyState(QTableWidget* table, const QString& hint) { + QStackedWidget* stack = new QStackedWidget(); + stack->addWidget(table); + + QWidget* placeholder = new QWidget(); + QVBoxLayout* layout = new QVBoxLayout(placeholder); + layout->addStretch(); + QLabel* label = new QLabel(hint); + label->setAlignment(Qt::AlignCenter); + label->setWordWrap(true); + label->setStyleSheet( + "background: transparent; color: #565f73; font-size: 13px;"); + layout->addWidget(label); + layout->addStretch(); + stack->addWidget(placeholder); + return stack; +} + +// Swaps between the listing and its empty-state hint. +static void showEmptyState(QStackedWidget* stack, bool empty) { + if (stack) stack->setCurrentIndex(empty ? 1 : 0); +} + // 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) { @@ -263,6 +339,15 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { }); } + // "Tout mettre à jour" is only meaningful with a provider that can update; + // without this it stayed greyed out even when pacman was available. + for (IPackageManager* pm : m_pluginManager->availableManagers()) { + if (pm->canUpdate()) { + m_updateAllButton->setEnabled(true); + break; + } + } + refreshDashboard(); updateStatusBar(); @@ -304,6 +389,7 @@ void MainWindow::setupUI() { setupHistoryPage(); setupLogsPage(); setupPluginsPage(); + setupCleanupPage(); contentLayout->addWidget(m_pages, 1); rootLayout->addWidget(content, 1); @@ -349,12 +435,33 @@ void MainWindow::setupUI() { "QLabel#headerTitle { font-size: 19px; font-weight: 800; color: #e8edf9; }" "QLabel#headerSubtitle { font-size: 12px; color: #7a8299; }" // ---- Cards ---- - // Cards are intentionally frameless: the dashboard and detail panels - // use a flat look where content sits directly on the page background. - "QFrame#card { background: transparent; border: none; }" + // Cards read as raised surfaces: a slightly lighter background, a hair + // line border and a rounded corner separate them from the page without + // adding shadows Qt cannot render consistently across platforms. + "QFrame#card {" + " background: #121722;" + " border: 1px solid #1d2432;" + " border-radius: 12px;" + "}" + // Stat cards carry a coloured left edge so the four metrics are told + // apart at a glance. + "QFrame#card[accent=\"blue\"] { border-left: 3px solid #7aa2f7; }" + "QFrame#card[accent=\"amber\"] { border-left: 3px solid #e0af68; }" + "QFrame#card[accent=\"cyan\"] { border-left: 3px solid #56b6c2; }" + "QFrame#card[accent=\"green\"] { border-left: 3px solid #3fb950; }" "QLabel#cardTitle { font-size: 11px; font-weight: 700; color: #7a8299; letter-spacing: 1px; }" - "QLabel#statValue { font-size: 30px; font-weight: 800; color: #ffffff; }" + "QLabel#statValue { font-size: 32px; font-weight: 800; color: #ffffff; }" "QLabel#statTitle { font-size: 12px; color: #7a8299; font-weight: 600; }" + // ---- Sidebar extras ---- + "QLabel#sectionTitle {" + " font-size: 10px;" + " font-weight: 800;" + " color: #4d5566;" + " letter-spacing: 1.2px;" + " padding: 14px 10px 2px 10px;" + "}" + "QLabel#versionLabel { font-size: 11px; color: #565f73; padding: 8px 10px; }" + "QPushButton[nav=\"true\"][highlighted=\"true\"] { color: #e0af68; }" // ---- Buttons ---- "QPushButton {" " background: #232b3a;" @@ -521,6 +628,12 @@ void MainWindow::setupSidebar() { m_navGroup = new QButtonGroup(this); m_navGroup->setExclusive(true); + auto addSection = [&](const QString& title) { + QLabel* label = new QLabel(title); + label->setObjectName("sectionTitle"); + layout->addWidget(label); + }; + auto addNavButton = [&](int id, const QString& iconName, const QString& text, const QString& tip) { QPushButton* btn = new QPushButton(text); @@ -535,17 +648,22 @@ void MainWindow::setupSidebar() { return btn; }; - addNavButton(0, "home", "Tableau de bord", "Vue d'ensemble du système"); - addNavButton(1, "search", "Recherche", "Rechercher des paquets"); - addNavButton(2, "package", "Installés", "Voir les paquets installés"); - addNavButton(3, "arrow-up", "Mises à jour", "Voir les mises à jour disponibles"); - layout->addSpacing(8); - addNavButton(4, "history", "Historique", "Historique des actions"); - addNavButton(5, "logs", "Logs", "Logs pacman"); - addNavButton(6, "plugin", "Plugins", "Gestionnaires de paquets et extensions"); + addSection("GESTION"); + addNavButton(NavDashboard, "home", "Tableau de bord", "Vue d'ensemble du système"); + addNavButton(NavSearch, "search", "Recherche", "Rechercher des paquets"); + addNavButton(NavInstalled, "package", "Installés", "Voir les paquets installés"); + m_navUpdatesButton = addNavButton(NavUpdates, "arrow-up", "Mises à jour", + "Voir les mises à jour disponibles"); + + addSection("SYSTÈME"); + addNavButton(NavCleanup, "broom", "Nettoyage", + "Purger les paquets inutilisés ou legacy et vider les caches"); + addNavButton(NavHistory, "history", "Historique", "Historique des actions"); + addNavButton(NavLogs, "logs", "Logs", "Logs pacman"); + addNavButton(NavPlugins, "plugin", "Plugins", "Gestionnaires de paquets et extensions"); connect(m_navGroup, &QButtonGroup::idClicked, this, &MainWindow::onNavChanged); - m_navGroup->button(0)->setChecked(true); + m_navGroup->button(NavDashboard)->setChecked(true); layout->addStretch(); @@ -556,6 +674,13 @@ void MainWindow::setupSidebar() { m_refreshButton->setToolTip("Rafraîchir les bases de données (pacman -Sy)"); connect(m_refreshButton, &QPushButton::clicked, this, &MainWindow::onRefresh); layout->addWidget(m_refreshButton); + + // The version actually installed, right where the user looks for it. + m_versionLabel = new QLabel(QString("v%1").arg(UpdateManager::currentVersion())); + m_versionLabel->setObjectName("versionLabel"); + m_versionLabel->setAlignment(Qt::AlignCenter); + m_versionLabel->setToolTip("Version installée de PacManager"); + layout->addWidget(m_versionLabel); } void MainWindow::setupHeader() { @@ -580,6 +705,21 @@ void MainWindow::setupHeader() { layout->addLayout(textLayout); layout->addStretch(); + + // The two actions used most often stay reachable from every page instead of + // only from the dashboard. + QPushButton* refreshBtn = new QPushButton("Rafraîchir"); + refreshBtn->setIcon(loadIcon("refresh")); + refreshBtn->setToolTip("Rafraîchir les bases de données (Ctrl+R)"); + connect(refreshBtn, &QPushButton::clicked, this, &MainWindow::onRefresh); + layout->addWidget(refreshBtn); + + QPushButton* updateAllBtn = new QPushButton("Tout mettre à jour"); + updateAllBtn->setProperty("variant", "warning"); + updateAllBtn->setIcon(loadIcon("arrow-up")); + updateAllBtn->setToolTip("Mettre à jour tous les paquets (Ctrl+U affiche la liste)"); + connect(updateAllBtn, &QPushButton::clicked, this, &MainWindow::onUpdateAll); + layout->addWidget(updateAllBtn); } void MainWindow::setupDashboardPage() { @@ -592,10 +732,14 @@ void MainWindow::setupDashboardPage() { // Stat cards QHBoxLayout* statsRow = new QHBoxLayout(); statsRow->setSpacing(12); - statsRow->addWidget(makeStatCard("package", "Paquets installés", &m_statInstalled)); - statsRow->addWidget(makeStatCard("arrow-up", "Mises à jour dispo", &m_statUpdates)); - statsRow->addWidget(makeStatCard("history", "Actions enregistrées", &m_statHistory)); - statsRow->addWidget(makeStatCard("tools", "Gestionnaire", &m_statManager)); + statsRow->addWidget( + makeStatCard("package", "Paquets installés", "blue", &m_statInstalled)); + statsRow->addWidget( + makeStatCard("arrow-up", "Mises à jour dispo", "amber", &m_statUpdates)); + statsRow->addWidget( + makeStatCard("history", "Actions enregistrées", "cyan", &m_statHistory)); + statsRow->addWidget( + makeStatCard("tools", "Gestionnaire", "green", &m_statManager)); layout->addLayout(statsRow); // Quick actions @@ -615,7 +759,7 @@ void MainWindow::setupDashboardPage() { btnSearch->setProperty("variant", "primary"); btnSearch->setIcon(loadIcon("search")); connect(btnSearch, &QPushButton::clicked, this, [this]() { - m_navGroup->button(1)->click(); + m_navGroup->button(NavSearch)->click(); m_searchBar->setFocus(); }); actionsRow->addWidget(btnSearch); @@ -623,7 +767,7 @@ void MainWindow::setupDashboardPage() { QPushButton* btnInstalled = new QPushButton("Paquets installés"); btnInstalled->setIcon(loadIcon("package")); connect(btnInstalled, &QPushButton::clicked, this, [this]() { - m_navGroup->button(2)->click(); + m_navGroup->button(NavInstalled)->click(); }); actionsRow->addWidget(btnInstalled); @@ -633,6 +777,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")); @@ -642,7 +794,7 @@ void MainWindow::setupDashboardPage() { QPushButton* btnLogs = new QPushButton("Logs pacman"); btnLogs->setIcon(loadIcon("logs")); connect(btnLogs, &QPushButton::clicked, this, [this]() { - m_navGroup->button(5)->click(); + m_navGroup->button(NavLogs)->click(); }); actionsRow->addWidget(btnLogs); @@ -809,7 +961,11 @@ void MainWindow::setupBrowsePage() { connect(m_packageTable, &QTableWidget::currentCellChanged, this, [this](int currentRow, int, int, int) { onPackageSelected(currentRow); }); - listLayout->addWidget(m_packageTable); + m_packageTableStack = withEmptyState( + m_packageTable, + "Aucun paquet à afficher.\nLancez une recherche ou ouvrez la liste des " + "paquets installés."); + listLayout->addWidget(m_packageTableStack); splitter->addWidget(listCard); // Right card: package details @@ -886,7 +1042,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 +1215,106 @@ 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); }); + m_cleanupTableStack = withEmptyState( + m_cleanupTable, + "Rien à nettoyer pour le moment.\nLancez une analyse pour vérifier."); + layout->addWidget(m_cleanupTableStack, 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( @@ -1084,16 +1341,24 @@ void MainWindow::setupMenuBar() { fileMenu->addAction("Quitter", this, &QWidget::close); QMenu* toolsMenu = menuBar->addMenu("Outils"); - toolsMenu->addAction("Tableau de bord", this, [this]() { m_navGroup->button(0)->click(); }); + toolsMenu->addAction("Tableau de bord", this, + [this]() { m_navGroup->button(NavDashboard)->click(); }); toolsMenu->addAction("Rechercher", this, [this]() { - m_navGroup->button(1)->click(); + m_navGroup->button(NavSearch)->click(); m_searchBar->setFocus(); }); - toolsMenu->addAction("Paquets installés", this, [this]() { m_navGroup->button(2)->click(); }); - toolsMenu->addAction("Mises à jour", this, [this]() { m_navGroup->button(3)->click(); }); - toolsMenu->addAction("Historique", this, [this]() { m_navGroup->button(4)->click(); }); - toolsMenu->addAction("Logs pacman", this, [this]() { m_navGroup->button(5)->click(); }); - toolsMenu->addAction("Plugins", this, [this]() { m_navGroup->button(6)->click(); }); + toolsMenu->addAction("Paquets installés", this, + [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, + [this]() { m_navGroup->button(NavLogs)->click(); }); + toolsMenu->addAction("Plugins", this, + [this]() { m_navGroup->button(NavPlugins)->click(); }); toolsMenu->addSeparator(); toolsMenu->addAction("Prévisualiser les mises à jour", this, &MainWindow::onPreviewUpdates); toolsMenu->addAction("Rafraîchir les sources", this, &MainWindow::onRefresh); @@ -1265,8 +1530,10 @@ QFrame* MainWindow::makeCard() { } QFrame* MainWindow::makeStatCard(const QString& iconName, const QString& title, - QLabel** valueOut) { + const QString& accent, QLabel** valueOut) { QFrame* card = makeCard(); + // Read by the stylesheet rule that draws the coloured left edge. + card->setProperty("accent", accent); QVBoxLayout* layout = new QVBoxLayout(card); layout->setContentsMargins(18, 16, 18, 16); layout->setSpacing(6); @@ -1290,31 +1557,36 @@ QFrame* MainWindow::makeStatCard(const QString& iconName, const QString& title, void MainWindow::updatePageTitle() { switch (m_navGroup->checkedId()) { - case 0: + case NavDashboard: m_headerTitle->setText("Tableau de bord"); m_headerSubtitle->setText("Vue d'ensemble de votre système"); break; - case 1: + case NavSearch: m_headerTitle->setText("Recherche"); m_headerSubtitle->setText("Trouvez et installez des paquets"); break; - case 2: + case NavInstalled: m_headerTitle->setText("Paquets installés"); m_headerSubtitle->setText("Parcourez les paquets de votre système"); break; - case 3: + case NavUpdates: m_headerTitle->setText("Mises à jour disponibles"); m_headerSubtitle->setText("Maintenez votre système à jour"); break; - case 4: + 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"); break; - case 5: + case NavLogs: m_headerTitle->setText("Logs pacman"); m_headerSubtitle->setText("Journal brut du gestionnaire de paquets"); break; - case 6: + case NavPlugins: m_headerTitle->setText("Plugins"); m_headerSubtitle->setText("Gestionnaires de paquets et extensions"); break; @@ -1328,32 +1600,36 @@ void MainWindow::onNavChanged(int id) { updatePageTitle(); switch (id) { - case 0: - m_pages->setCurrentIndex(0); + case NavDashboard: + m_pages->setCurrentIndex(PageDashboard); refreshDashboard(); break; - case 1: + case NavSearch: setBrowseMode(ModeSearch); m_searchBar->setFocus(); break; - case 2: + case NavInstalled: setBrowseMode(ModeInstalled); loadInstalled(); break; - case 3: + case NavUpdates: setBrowseMode(ModeUpdates); loadUpdates(); break; - case 4: - m_pages->setCurrentIndex(2); + case NavCleanup: + m_pages->setCurrentIndex(PageCleanup); + loadCleanup(); + break; + case NavHistory: + m_pages->setCurrentIndex(PageHistory); refreshHistoryTable(); break; - case 5: - m_pages->setCurrentIndex(3); + case NavLogs: + m_pages->setCurrentIndex(PageLogs); loadLogs(); break; - case 6: - m_pages->setCurrentIndex(4); + case NavPlugins: + m_pages->setCurrentIndex(PagePlugins); refreshPluginsTable(); break; default: @@ -1363,7 +1639,7 @@ void MainWindow::onNavChanged(int id) { void MainWindow::setBrowseMode(BrowseMode mode) { m_browseMode = mode; - m_pages->setCurrentIndex(1); + m_pages->setCurrentIndex(PageBrowse); m_searchRowWidget->setVisible(mode == ModeSearch); m_filterRowWidget->setVisible(mode == ModeInstalled); @@ -1491,18 +1767,22 @@ void MainWindow::onRecentActivityClicked(QListWidgetItem* item) { if (name.isEmpty()) return; m_pendingSelect = name.toStdString(); - m_navGroup->button(2)->click(); // Installed page -> loadInstalled() runs + m_navGroup->button(NavInstalled)->click(); // Installed page -> loadInstalled() runs statusBar()->showMessage( QString("Ouverture des détails de %1...").arg(name)); } void MainWindow::populatePackageTable(const std::vector& results) { m_currentResults = results; - m_packageTable->setRowCount(0); - m_packageTable->setRowCount(static_cast(results.size())); + showEmptyState(m_packageTableStack, results.empty()); + { + TableFillBatch batch(m_packageTable); + m_packageTable->setRowCount(0); + m_packageTable->setRowCount(static_cast(results.size())); - for (int i = 0; i < static_cast(results.size()); ++i) { - addPackageRow(i, results[i]); + for (int i = 0; i < static_cast(results.size()); ++i) { + addPackageRow(i, results[i]); + } } m_resultCount->setText(QString("%1 paquet(s)").arg(results.size())); @@ -1533,10 +1813,13 @@ void MainWindow::populatePackageTable(const std::vector& results) { void MainWindow::appendPackageRows(const std::vector& results) { const int startRow = static_cast(m_currentResults.size()); m_currentResults.insert(m_currentResults.end(), results.begin(), results.end()); - m_packageTable->setRowCount(static_cast(m_currentResults.size())); + { + TableFillBatch batch(m_packageTable); + m_packageTable->setRowCount(static_cast(m_currentResults.size())); - for (size_t i = 0; i < results.size(); ++i) { - addPackageRow(startRow + static_cast(i), results[i]); + for (size_t i = 0; i < results.size(); ++i) { + addPackageRow(startRow + static_cast(i), results[i]); + } } m_resultCount->setText(QString("%1 paquet(s)").arg(m_currentResults.size())); } @@ -1850,6 +2133,280 @@ 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; + showEmptyState(m_cleanupTableStack, candidates.empty()); + + QFont nameFont; + nameFont.setWeight(QFont::DemiBold); + + TableFillBatch batch(m_cleanupTable); + m_cleanupTable->setRowCount(0); + m_cleanupTable->setRowCount(static_cast(candidates.size())); + + 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))); + } + batch.release(); + + 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; @@ -1993,11 +2550,13 @@ 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); } m_historyCount->setText(QString("%1 action(s)").arg(entries.size())); + TableFillBatch batch(m_historyTable); m_historyTable->setRowCount(static_cast(entries.size())); for (int i = 0; i < static_cast(entries.size()); ++i) { @@ -2010,6 +2569,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"; @@ -2126,11 +2688,28 @@ void MainWindow::refreshDashboard() { m_lastNotifiedUpdates = static_cast(r.size()); notifyUpdatesAvailable(static_cast(r.size())); } + setUpdatesBadge(static_cast(r.size())); }); connect(upd, &ListWorker::finished, this, [upd] { upd->wait(); upd->deleteLater(); }); upd->start(); } +void MainWindow::setUpdatesBadge(int count) { + if (!m_navUpdatesButton) return; + + m_navUpdatesButton->setText(count > 0 + ? QString("Mises à jour · %1").arg(count) + : QString("Mises à jour")); + + // A dynamic property only takes effect once the style is re-applied, so it + // is only touched when it actually changes. + const bool highlighted = count > 0; + if (m_navUpdatesButton->property("highlighted").toBool() == highlighted) return; + m_navUpdatesButton->setProperty("highlighted", highlighted); + m_navUpdatesButton->style()->unpolish(m_navUpdatesButton); + m_navUpdatesButton->style()->polish(m_navUpdatesButton); +} + void MainWindow::refreshRecentActivity() { m_recentList->clear(); @@ -2169,6 +2748,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"; } @@ -2322,12 +2903,14 @@ void MainWindow::onRescanPlugins() { void MainWindow::refreshPluginsTable() { const auto& plugins = m_pluginManager->plugins(); - m_pluginTable->setRowCount(0); - m_pluginTable->setRowCount(static_cast(plugins.size())); QFont nameFont; nameFont.setWeight(QFont::DemiBold); + TableFillBatch batch(m_pluginTable); + m_pluginTable->setRowCount(0); + m_pluginTable->setRowCount(static_cast(plugins.size())); + for (int i = 0; i < static_cast(plugins.size()); ++i) { const auto& entry = plugins[i]; @@ -2371,6 +2954,7 @@ void MainWindow::refreshPluginsTable() { : "alert")); m_pluginTable->setItem(i, 4, statusItem); } + batch.release(); if (!plugins.empty()) { // Keep the previously selected plugin selected when possible. @@ -2446,14 +3030,14 @@ void MainWindow::setupShortcuts() { }; bind(QKeySequence::Find, [this]() { - m_navGroup->button(1)->click(); + m_navGroup->button(NavSearch)->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(); + m_navGroup->button(NavUpdates)->click(); }); bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() { onExportPackageList(); }); bind(QKeySequence::Quit, [this]() { close(); }); @@ -2462,7 +3046,7 @@ void MainWindow::setupShortcuts() { // 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(); + m_navGroup->button(NavUpdates)->click(); statusBar()->showMessage("Prévisualisation des mises à jour disponibles"); } @@ -2591,10 +3175,11 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers } // 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: + // root-owned directory (e.g. /usr/bin). Every method installs into the + // running binary's directory, and only that final copy is privileged: // everything else builds in a temp directory owned by the user. QString sudoPassword; - if (m_updateManager->repoPath().isEmpty() && !QFileInfo(targetDir).isWritable() + if (!QFileInfo(targetDir).isWritable() && m_pacman && m_pacman->isAvailable()) { bool ok = false; sudoPassword = QInputDialog::getText( diff --git a/src/pacman-manager.cpp b/src/pacman-manager.cpp index 5d1f0ac..3ab41e5 100644 --- a/src/pacman-manager.cpp +++ b/src/pacman-manager.cpp @@ -112,6 +112,12 @@ static int percentFromLine(const std::string& line) { } } +// Read-only pacman output is reused by several views within a few seconds, so +// it is cached for this long. Short enough that a package installed outside the +// app still appears almost immediately, and every mutating operation drops the +// cache outright. +static constexpr std::chrono::seconds kQueryTtl{10}; + // Stream the lines of a command's output (already captured) to the callback — // used by providers that buffer a whole command first. Percent stays unknown. static void streamOutput(const std::string& output, ProgressCallback progressCallback) { @@ -123,6 +129,34 @@ static void streamOutput(const std::string& output, ProgressCallback progressCal } } +std::string PacmanManager::cachedQuery(PacmanManager::CachedQuery& slot, + const char* command) { + const auto now = std::chrono::steady_clock::now(); + { + std::lock_guard lock(m_queryMutex); + if (slot.valid && now - slot.fetched < kQueryTtl) return slot.output; + } + + // Queried outside the lock: a second thread asking for the same query then + // just runs it too, which is cheaper than serialising the whole app on + // pacman. + std::string fresh = exec(command); + { + std::lock_guard lock(m_queryMutex); + slot.output = fresh; + slot.fetched = now; + slot.valid = true; + } + return fresh; +} + +void PacmanManager::invalidateQueries() { + std::lock_guard lock(m_queryMutex); + m_installedQuery.valid = false; + m_installedDetailsQuery.valid = false; + m_syncReposQuery.valid = false; +} + std::vector PacmanManager::search(const std::string& query) { std::vector results; @@ -132,7 +166,8 @@ std::vector PacmanManager::search(const std::string& query) { // Load the installed packages once, so marking search results as // installed is an in-memory lookup instead of one `pacman -Qi` subprocess // per result (which made searches with many matches take minutes). - std::set installed = parseInstalledNames(exec("pacman -Q 2>&1")); + std::set installed = + parseInstalledNames(cachedQuery(m_installedQuery, "pacman -Q 2>&1")); std::istringstream iss(output); std::string line; @@ -176,6 +211,9 @@ std::vector PacmanManager::search(const std::string& query) { bool PacmanManager::install(const std::string& packageName, ProgressCallback progressCallback) { + // The transaction changes the installed set (and may fail halfway): drop + // the cached reads before it runs rather than after. + invalidateQueries(); if (progressCallback) progressCallback("Installation de " + packageName + "...", -1); std::string output = @@ -199,6 +237,7 @@ bool PacmanManager::install(const std::string& packageName, bool PacmanManager::remove(const std::string& packageName, ProgressCallback progressCallback) { + invalidateQueries(); if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1); std::string output = @@ -220,6 +259,7 @@ bool PacmanManager::remove(const std::string& packageName, bool PacmanManager::update(const std::string& packageName, ProgressCallback progressCallback) { + invalidateQueries(); std::string output; if (packageName.empty()) { if (progressCallback) progressCallback("Mise à jour de tous les paquets...", -1); @@ -245,13 +285,15 @@ bool PacmanManager::update(const std::string& packageName, } std::vector PacmanManager::listInstalled() { - auto packages = parseInstalledOutput(exec("pacman -Q 2>&1")); + auto packages = parseInstalledOutput(cachedQuery(m_installedQuery, "pacman -Q 2>&1")); // Enrich each installed package with its installed size (shown as "Taille") - // and the repository/origin it was installed from. Both come from a single - // subprocess each, which is fast enough to run on page load. - auto sizes = parseInstalledSizes(exec("pacman -Qi 2>&1")); - auto repos = parseSyncRepos(exec("pacman -Sl 2>&1")); + // and the repository/origin it was installed from. `pacman -Qi` answers for + // every package at once, and `-Sl` only changes on a sync, so both are + // cached across the views that need them. + auto sizes = parseInstalledSizes( + cachedQuery(m_installedDetailsQuery, "pacman -Qi 2>&1")); + auto repos = parseSyncRepos(cachedQuery(m_syncReposQuery, "pacman -Sl 2>&1")); for (auto& pkg : packages) { auto sizeIt = sizes.find(pkg.name); @@ -300,7 +342,80 @@ 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; + + invalidateQueries(); + 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) { + // A sync rewrites the sync databases the `-Sl` cache is built from. + invalidateQueries(); if (progressCallback) progressCallback("Rafraîchissement des bases de données...", -1); std::string output = @@ -444,6 +559,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/src/update-manager.cpp b/src/update-manager.cpp index 14ae819..a698e78 100644 --- a/src/update-manager.cpp +++ b/src/update-manager.cpp @@ -16,7 +16,14 @@ // 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 + +// Version compiled in from the repo-root `version` file (see CMakeLists.txt). +// Empty when the build bypasses CMake, in which case the `version` file next to +// the executable is used instead. +#ifndef FWSPACMANAGE_VERSION +#define FWSPACMANAGE_VERSION "" +#endif + static const char* kRepoUrl = "https://gitea.nocode-var.tech/FWS/FWS-PacManage.git"; @@ -45,23 +52,21 @@ UpdateManager::UpdateManager(QObject* parent) : QObject(parent) { } 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(); - } + // The compiled-in version wins: it describes the code that is actually + // running, so a `version` file left behind (or never refreshed) by an + // update cannot make the app re-offer a release it already installed. + QString version = QStringLiteral(FWSPACMANAGE_VERSION).trimmed(); + + // Fallback for builds that bypass CMake: the `version` file installed next + // to the executable. 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"); + QFile f(QCoreApplication::applicationDirPath() + "/version"); + if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { + version = QString::fromUtf8(f.readAll()).trimmed(); } } - return version; + + return version.isEmpty() ? QStringLiteral("1.0.0") : version; } QString UpdateManager::stateFilePath() { @@ -390,7 +395,7 @@ void UpdateManager::performSelfUpdate(const QString& sudoPassword) { << static_cast(method) << "into" << binDir(); switch (method) { case UpdateMethod::Checkout: - performCheckoutUpdate(); + performCheckoutUpdate(sudoPassword); return; case UpdateMethod::Clone: performCloneUpdate(sudoPassword); @@ -408,13 +413,14 @@ void UpdateManager::performSelfUpdate(const QString& sudoPassword) { } } -// Checkout path (dev): pull the sources and rebuild in place, then install -// with whatever prefix the build directory was configured with. -void UpdateManager::performCheckoutUpdate() { - QString script = QStringLiteral( - "set -e\n" - "echo 'Mise a jour de PacManager...'\n" - "export GIT_TERMINAL_PROMPT=0\n" +// Checkout path (dev, or any tree built from a clone): pull, rebuild, then +// install into the directory that holds the running binary — like every other +// method. The build's configured prefix is deliberately not used: it generally +// points at a system directory the app cannot write, and installing there would +// leave the copy in use (and its version marker) untouched. +void UpdateManager::performCheckoutUpdate(const QString& sudoPassword) { + QString script = updateScriptPrologue(); + script += QStringLiteral( "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" @@ -422,15 +428,17 @@ void UpdateManager::performCheckoutUpdate() { " cmake -B build -DCMAKE_BUILD_TYPE=Release . 2>&1\n" " cmake --build build -j$(nproc) 2>&1\n" "fi\n" - "cmake --install build 2>&1\n" - "echo 'Mise a jour terminee.'"); + "cmake --install build --prefix \"$STAGE\" 2>&1\n"); + script += installCommand(quotedPassword(sudoPassword), stagedInstallScript()); + script += QStringLiteral("echo 'Mise a jour terminee.'"); runShell(script, m_repoPath); } -// Shared prologue for the installed (no checkout) paths: temp work directory -// with a cleanup trap, plus the paths the install step needs, exported so the -// sudo-wrapped `sh -c` copy can expand them. -QString UpdateManager::installedScriptPrologue() const { +// Shared prologue for every update path: temp work directory with a cleanup +// trap, and the paths the install step needs, exported so the sudo-wrapped +// `sh -c` copy can expand them. APP_VERSION is the release being installed; the +// checkout path sets it too, so all four methods stamp the same marker. +QString UpdateManager::updateScriptPrologue() const { return QStringLiteral( "set -e\n" "echo 'Mise a jour de PacManager...'\n" @@ -438,9 +446,10 @@ QString UpdateManager::installedScriptPrologue() const { "trap 'rm -rf \"$WORK\"' EXIT\n" "BIN_DIR=%1\n" "STAGE=\"$WORK/stage\"\n" - "export WORK BIN_DIR STAGE\n" + "APP_VERSION=%2\n" + "export WORK BIN_DIR STAGE APP_VERSION\n" "export GIT_TERMINAL_PROMPT=0\n") - .arg(quotedBinDir()); + .arg(quotedBinDir(), quoteShell(m_lastKnownRemoteVersion)); } // Copies a staged install tree ($STAGE/bin, plugins under bin/plugins or @@ -465,6 +474,12 @@ QString UpdateManager::stagedInstallScript() { "}\n" "mkdir -p \"$BIN_DIR\"\n" "install_file \"$STAGE/bin/PacManager\" \"$BIN_DIR/PacManager\"\n" + // The version marker has to follow the installed release: it is what + // the app reports and what the next update check compares against, so + // a stale one would offer the same release again at every launch. + "if [ -n \"$APP_VERSION\" ]; then\n" + " printf '%s\\n' \"$APP_VERSION\" > \"$STAGE/bin/version\"\n" + "fi\n" "if [ -f \"$STAGE/bin/version\" ]; then\n" " install_file \"$STAGE/bin/version\" \"$BIN_DIR/version\"\n" "fi\n" @@ -519,7 +534,7 @@ QString UpdateManager::quotedPassword(const QString& sudoPassword) { // ones fast-forward it, then the app is rebuilt and installed where the // running binary lives. void UpdateManager::performCloneUpdate(const QString& sudoPassword) { - QString script = installedScriptPrologue(); + QString script = updateScriptPrologue(); script += QStringLiteral( "SRC=%1\n" "export SRC\n" @@ -548,7 +563,7 @@ void UpdateManager::performCloneUpdate(const QString& sudoPassword) { // Prebuilt path: download the release archive (bin/ + plugins/) and unpack it // straight into the running binary's directory. No compiler needed. void UpdateManager::performPrebuiltUpdate(const QString& sudoPassword) { - QString script = installedScriptPrologue(); + QString script = updateScriptPrologue(); script += QStringLiteral( "URL=%1\n" "ARCHIVE=\"$WORK/update.tar.gz\"\n" @@ -570,7 +585,7 @@ void UpdateManager::performPrebuiltUpdate(const QString& sudoPassword) { // Source fallback: fetch the release tarball, build it in /tmp and install the // result where the running binary lives. Used only when git is unavailable. void UpdateManager::performTarballUpdate(const QString& sudoPassword) { - QString script = installedScriptPrologue(); + QString script = updateScriptPrologue(); script += QStringLiteral( "command -v cmake >/dev/null 2>&1 || { echo 'cmake est requis pour la mise a jour'; exit 1; }\n" "URL=%1\n" 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(); diff --git a/tests/update-manager.test.cpp b/tests/update-manager.test.cpp index d760574..f61182c 100644 --- a/tests/update-manager.test.cpp +++ b/tests/update-manager.test.cpp @@ -15,6 +15,12 @@ #include "update-manager.h" +// Defined by CMake from the repo-root `version` file; empty when the test is +// built without it. +#ifndef FWSPACMANAGE_VERSION +#define FWSPACMANAGE_VERSION "" +#endif + static int failures = 0; static void check(bool cond, const char* name) { @@ -113,6 +119,14 @@ static void testChooseMethod_noneWhenNothingAvailable() { "method_none_without_anything"); } +// The version the app reports is the one compiled into it, so a stale `version` +// file next to the executable can never make it re-offer an installed update. +static void testCurrentVersion_isCompiledIn() { + check(UpdateManager::currentVersion() == QStringLiteral(FWSPACMANAGE_VERSION), + "current_version_compiled_in"); + check(!UpdateManager::currentVersion().isEmpty(), "current_version_not_empty"); +} + // The staged install must replace an executable that is currently running, // which is exactly the situation of the app updating itself: opening the busy // file for writing fails with ETXTBSY ("Text file busy"), so the script copies @@ -181,6 +195,47 @@ static void testStagedInstall_replacesRunningExecutable() { running.kill(); running.waitForFinished(2000); } + +// The version marker has to end up describing the release that was installed: +// it is what the app reports at launch and what the next update check compares +// against, so a stale marker makes the app offer the same update again. +static void testStagedInstall_writesReleaseVersionMarker() { + QTemporaryDir tmp; + check(tmp.isValid(), "version_marker_tmpdir"); + if (!tmp.isValid()) return; + + const QString binDir = tmp.path() + "/bin"; + const QString stage = tmp.path() + "/stage"; + QDir().mkpath(binDir); + QDir().mkpath(stage + "/bin"); + + // The target holds an outdated marker, and the staged tree has none at all + // (a prebuilt archive built without the file, or an install script that + // staged only the binary). + check(writeFile(binDir + "/version", "1.3.1"), "version_marker_seed"); + check(QFile::copy("/bin/echo", stage + "/bin/PacManager"), + "version_marker_stage_binary"); + + QProcess sh; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert("BIN_DIR", binDir); + env.insert("STAGE", stage); + env.insert("APP_VERSION", "9.9.9"); + sh.setProcessEnvironment(env); + sh.start("/bin/sh", {"-c", UpdateManager::stagedInstallScript()}); + const bool finished = sh.waitForFinished(15000); + check(finished && sh.exitCode() == 0, "version_marker_exit_zero"); + + QFile marker(binDir + "/version"); + const bool readable = marker.open(QIODevice::ReadOnly); + check(readable, "version_marker_readable"); + if (readable) { + check(QString::fromUtf8(marker.readAll()).trimmed() == "9.9.9", + "version_marker_updated"); + } + check(QDir(binDir).entryList(QStringList() << "*.new", QDir::Files).isEmpty(), + "version_marker_no_leftover_temp"); +} #endif // !Q_OS_WIN // The restart after a successful update must point at the binary the update @@ -240,6 +295,9 @@ int main() { // Empty remote never triggers an update prompt check(UpdateManager::isNewerVersion("", "1.3.1") == false, "empty_remote"); + // Reported version + testCurrentVersion_isCompiledIn(); + // Update-strategy choice testChooseMethod_checkoutWinsOverEverything(); testChooseMethod_cloneWhenToolchainPresent(); @@ -253,6 +311,7 @@ int main() { #if !defined(Q_OS_WIN) testStagedInstall_replacesRunningExecutable(); + testStagedInstall_writesReleaseVersionMarker(); #endif testRestartProgram_findsInstalledBinary();