13 Commits
Author SHA1 Message Date
BlackAngelTV 7c8e981845 docs: align READMEs with AGENTS.md conventions
Add the development & conventions section that AGENTS.md points to, so the
README documents the branch/commit/naming/comment/test/issue/.gitignore rules
it summarizes, and refresh the Flatpak provider paragraph with the new
desktop-launcher integration, honest search status and integration tests.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 17:07:03 +02:00
BlackAngelTV 3320e60805 test(flatpak): verify desktop integration in end-to-end test
Extend the live-CLI integration test to assert that installing an app links
its .desktop entry into ~/.local/share/applications, and that uninstalling
cleans the link back up.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 16:54:39 +02:00
BlackAngelTV a1d8c96e4e feat(flatpak): link installed apps into the desktop launcher
When a flatpak app is installed through the app, its .desktop entries and
icons are now symlinked into the user's standard XDG dirs
(~/.local/share/{applications,icons}), which every desktop scans by default.
This makes flatpak apps appear in any launcher (wofi, GNOME, KDE...) the same
way a pacman install would, without relying on XDG_DATA_DIRS or any
desktop-specific configuration. The links are removed on uninstall, and a
refresh re-links every installed app so ones installed before this feature
(or outside the app) self-heal.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 16:54:39 +02:00
BlackAngelTV 6224a94df6 test(flatpak): add end-to-end CLI integration test
Drives the real FlatpakManager against the live flatpak CLI: install a small
app through the provider's own fallback logic, verify it is listed and
flagged as installed in search, run update and refresh, then uninstall. The
test is non-destructive for pre-existing installs and skips when flatpak is
absent.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 15:05:14 +02:00
BlackAngelTV 1b3f11aad8 fix(flatpak): show honest search status and harden install
Search results now report whether each app is already installed or has a
pending update, like pacman does with its [installed] marker, so the UI no
longer shows "Disponible" for apps that are already managed. Install is also
idempotent (already-deployed apps short-circuit) and skips the doomed bare
retry when both a system and a user flathub remote make the ref ambiguous.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 15:05:14 +02:00
BlackAngelTV 6aef549eb0 fix(flatpak): per-user install fallback and real error reporting
Installing through a system-wide remote fails under polkit and, when a
remote exists in both installations, flatpak refuses non-interactive
installs ("Multiple remotes have refs matching"). Retry with an explicit
`--user flathub` target, refresh appstream metadata before giving up on
stale refs, and let update/refresh fall back to the user installation as
well. Expose the last command output through IPackageManager::lastError
and show it in a dialog on failure instead of failing silently.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:57:03 +02:00
BlackAngelTV 5cc85cac4a feat(ui): sort search results by provider then name
Group aggregated search results per provider (in query order, pacman
first) and sort each group alphabetically, case-insensitively.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:56:27 +02:00
BlackAngelTV d8a70eabf8 feat(ui): merge duplicate packages across providers
When the same package name comes from several providers (pacman, flatpak,
plugins), collapse the rows into one: the Fournisseur column lists every
provider offering it and installed/updateAvailable are combined, while
the first provider stays the routing default. Applies to search and to
the aggregated installed/updates lists.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:55:56 +02:00
BlackAngelTV 4fe4c7287e docs: document providers, flatpak and the plugin system
Explain multi-provider search with the Provider column, the Providers
page (enable/disable, rescan, install-tool) and how to write a plugin
using the example provider as a template.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:34:53 +02:00
BlackAngelTV 71eb962b00 test: cover flatpak parsing and plugin discovery
Unit-test the flatpak parsers (search rows, installed/update columns)
and the plugin manager end-to-end: built-in registration, runtime
discovery of the sample plugin, enable/disable persistence, reload and
install-hint exposure.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:34:50 +02:00
BlackAngelTV bc737d356e feat(ui): browse every provider from one search
Search now queries all active providers at once and each row shows its
origin in a Provider column; installed and updates pages are aggregated,
and install/remove/update are routed to the owning manager automatically.
Add a Providers page listing built-in and plugin managers with
enable/disable, plugin rescan, and an install-tool button that pulls the
missing backend through pacman (e.g. flatpak).

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:34:41 +02:00
BlackAngelTV f355c97940 feat(providers): add flatpak provider
Implement IPackageManager over the flatpak CLI: search, installed list,
updates, install/remove/update and appstream refresh. Runs per-user so it
needs no sudo. Parsing is exposed as statics so it can be unit-tested
without the flatpak binary.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:34:36 +02:00
BlackAngelTV a2cef3d256 feat(providers): add provider plugin system
Introduce a registry (PluginManager) that owns package managers and can
load additional providers at runtime from shared-library plugins dropped
in a plugins directory. Providers declare their metadata and a factory
through a C ABI (provider-plugin.h); requiresPassword() tells the UI
whether a provider needs sudo. Ships a sample external plugin as a
template for adding new backends.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 13:34:29 +02:00
19 changed files with 2121 additions and 102 deletions

No files matched your search

+53
View File
@@ -15,6 +15,8 @@ set(SOURCES
src/main.cpp src/main.cpp
src/main-window.cpp src/main-window.cpp
src/pacman-manager.cpp src/pacman-manager.cpp
src/flatpak-manager.cpp
src/plugin-manager.cpp
src/history-manager.cpp src/history-manager.cpp
src/package-model.cpp src/package-model.cpp
resources/resources.qrc resources/resources.qrc
@@ -23,6 +25,9 @@ set(SOURCES
set(HEADERS set(HEADERS
include/package-manager.h include/package-manager.h
include/pacman-manager.h include/pacman-manager.h
include/flatpak-manager.h
include/plugin-manager.h
include/provider-plugin.h
include/main-window.h include/main-window.h
include/history-manager.h include/history-manager.h
include/package-model.h include/package-model.h
@@ -42,3 +47,51 @@ enable_testing()
add_executable(pacman-manager-test tests/pacman-manager.test.cpp src/pacman-manager.cpp) add_executable(pacman-manager-test tests/pacman-manager.test.cpp src/pacman-manager.cpp)
target_include_directories(pacman-manager-test PRIVATE include) target_include_directories(pacman-manager-test PRIVATE include)
add_test(NAME pacman-manager-test COMMAND pacman-manager-test) add_test(NAME pacman-manager-test COMMAND pacman-manager-test)
add_executable(flatpak-manager-test tests/flatpak-manager.test.cpp src/flatpak-manager.cpp)
target_include_directories(flatpak-manager-test PRIVATE include)
add_test(NAME flatpak-manager-test COMMAND flatpak-manager-test)
# Real end-to-end test of the Flatpak provider against the live flatpak CLI
# (installs and uninstalls a small app). Skipped when flatpak is missing.
add_executable(flatpak-integration-test tests/flatpak-integration.test.cpp src/flatpak-manager.cpp)
target_include_directories(flatpak-integration-test PRIVATE include)
add_test(NAME flatpak-integration-test COMMAND flatpak-integration-test)
add_executable(package-utils-test tests/package-utils.test.cpp)
target_include_directories(package-utils-test PRIVATE include)
add_test(NAME package-utils-test COMMAND package-utils-test)
# Plugin manager test: needs Qt (QSettings/QLibrary) and the example plugin
# built next to the test binary, so it is only enabled with the plugin option.
if(FWS_BUILD_EXAMPLE_PLUGIN)
add_executable(plugin-manager-test tests/plugin-manager.test.cpp
src/plugin-manager.cpp src/pacman-manager.cpp src/flatpak-manager.cpp)
target_include_directories(plugin-manager-test PRIVATE include)
target_link_libraries(plugin-manager-test PRIVATE Qt6::Core)
add_dependencies(plugin-manager-test example-provider-plugin)
add_custom_command(TARGET plugin-manager-test POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
$<TARGET_FILE_DIR:plugin-manager-test>/plugins
COMMAND ${CMAKE_COMMAND} -E copy
$<TARGET_FILE:example-provider-plugin>
$<TARGET_FILE_DIR:plugin-manager-test>/plugins/)
add_test(NAME plugin-manager-test COMMAND plugin-manager-test)
endif()
# Optional example external provider plugin. Demonstrates the plugin mechanism:
# the produced library is copied next to the executable and discovered at
# runtime by PluginManager (see the Providers page).
option(FWS_BUILD_EXAMPLE_PLUGIN "Build the example external provider plugin" OFF)
if(FWS_BUILD_EXAMPLE_PLUGIN)
add_library(example-provider-plugin MODULE plugins/example-provider/example-provider.cpp)
target_include_directories(example-provider-plugin PRIVATE include)
set_target_properties(example-provider-plugin PROPERTIES
OUTPUT_NAME "sample-provider"
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON)
add_custom_command(TARGET example-provider-plugin POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:PacManager>/plugins
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:example-provider-plugin>
$<TARGET_FILE_DIR:PacManager>/plugins/)
endif()
+49 -5
View File
@@ -9,6 +9,7 @@ Package manager for **Arch Linux** based on **pacman**, with a Qt6 graphical int
- 🗑️ **Package removal** - 🗑️ **Package removal**
- 🔄 **Individual or global updates** - 🔄 **Individual or global updates**
- 📋 **History of all actions** - 📋 **History of all actions**
- 🧩 **Multi-provider**: pacman and Flatpak built in, plus **plugins** to add other managers (apt, dnf, …)
## Architecture ## Architecture
@@ -16,8 +17,11 @@ Package manager for **Arch Linux** based on **pacman**, with a Qt6 graphical int
package-manager/ package-manager/
├── CMakeLists.txt # Build root ├── CMakeLists.txt # Build root
├── include/ ├── include/
│ ├── package-manager.h # Package manager interface │ ├── package-manager.h # Package manager interface (IPackageManager)
│ ├── provider-plugin.h # C ABI contract for provider plugins
│ ├── pacman-manager.h # pacman manager (Arch Linux) │ ├── pacman-manager.h # pacman manager (Arch Linux)
│ ├── flatpak-manager.h # Flatpak manager
│ ├── plugin-manager.h # Provider registry + plugin loading
│ ├── main-window.h # Main GUI │ ├── main-window.h # Main GUI
│ ├── history-manager.h # Action history │ ├── history-manager.h # Action history
│ └── package-model.h # Qt model for the list │ └── package-model.h # Qt model for the list
@@ -25,8 +29,14 @@ package-manager/
│ ├── main.cpp │ ├── main.cpp
│ ├── main-window.cpp │ ├── main-window.cpp
│ ├── pacman-manager.cpp │ ├── pacman-manager.cpp
│ ├── flatpak-manager.cpp
│ ├── plugin-manager.cpp
│ ├── history-manager.cpp │ ├── history-manager.cpp
│ └── package-model.cpp │ └── package-model.cpp
├── plugins/
│ └── example-provider/ # Example external plugin (template)
├── tests/ # Unit tests (assert, no Qt)
└── resources/
``` ```
## Compilation (Arch Linux) ## Compilation (Arch Linux)
@@ -74,6 +84,7 @@ The interface uses **Qt6** with a dark theme, a **navigation sidebar** and stack
- ⬆️ **Updates**: outdated packages detected by `pacman -Qu`, "Update all" button - ⬆️ **Updates**: outdated packages detected by `pacman -Qu`, "Update all" button
- 📋 **History**: filterable table (installs / removals / updates) - 📋 **History**: filterable table (installs / removals / updates)
- 📜 **Logs**: built-in `/var/log/pacman.log` viewer - 📜 **Logs**: built-in `/var/log/pacman.log` viewer
- 🧩 **Providers**: lists all managers (built-in and plugins), enable / disable and plugin rescan
### Interface overview ### Interface overview
```text ```text
@@ -97,9 +108,9 @@ The interface uses **Qt6** with a dark theme, a **navigation sidebar** and stack
└──────────────────────────────────────────────────────────────────────────────────────┘ └──────────────────────────────────────────────────────────────────────────────────────┘
``` ```
## Package manager ## Package managers (providers)
The `IPackageManager` interface (implemented by `PacmanManager`) defines: The `IPackageManager` interface (implemented by `PacmanManager` and `FlatpakManager`) defines:
| Method | Description | | Method | Description |
|--------|-------------| |--------|-------------|
@@ -111,14 +122,47 @@ The `IPackageManager` interface (implemented by `PacmanManager`) defines:
| `canRemove()` | Supports removal | | `canRemove()` | Supports removal |
| `canUpdate()` | Supports updates | | `canUpdate()` | Supports updates |
| `canListInstalled()` | Supports listing installed packages | | `canListInstalled()` | Supports listing installed packages |
| `isAvailable()` | Checks whether pacman is installed | | `isAvailable()` | Checks whether the tool is installed |
| `requiresPassword()` | True when operations go through sudo (pacman) |
| `search(query)` | Search for packages | | `search(query)` | Search for packages |
| `install(name, callback)` | Installation | | `install(name, callback)` | Installation |
| `remove(name, callback)` | Removal | | `remove(name, callback)` | Removal |
| `update(name, callback)` | Update | | `update(name, callback)` | Update |
| `listInstalled()` | List installed packages | | `listInstalled()` | List installed packages |
| `listUpdates()` | List outdated packages | | `listUpdates()` | List outdated packages |
| `refresh(callback)` | Refresh the databases | | `refresh(callback)` | Refresh the sources |
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 **Providers** page lets you enable / disable each provider, rescan plugins and **install a missing tool** (e.g. "Install tool" for Flatpak runs `sudo pacman -S flatpak`, then the provider becomes available).
### Adding a provider (plugins)
Pacman and Flatpak are **built-in**. Flatpak installs auto-add the flathub remote when missing and fall back to a **per-user** install (no password) when the system-wide install fails (polkit, homonymous remotes) — the real error is shown on failure. An app installed via Flatpak appears immediately in the desktop launcher: its `.desktop` entries and icons are linked into `~/.local/share/applications` and `~/.local/share/icons` (the XDG dirs scanned by **every** environment: wofi, GNOME, KDE…), exactly like a pacman install, and are removed again on uninstall. Search shows the real status of each app (Installed / Update available). This is covered by an **integration test** that drives the real flatpak CLI (install, list, update, search, uninstall). To add another manager (apt, dnf, zypper, or another distro's repos) without touching the application:
1. Implement `IPackageManager` in a `.cpp` file (copy `plugins/example-provider/example-provider.cpp` as a template).
2. Export the C ABI contract with the `FWS_PROVIDER_PLUGIN(MyManager, "id", "Name", "1.0.0", "Description", "Author")` macro.
3. Compile it as a shared library and drop it into `~/.local/share/PacManager/plugins/` or `plugins/` next to the executable.
4. Click **Rescan** on the Providers page.
Building the example plugin:
```bash
cmake -B build -DFWS_BUILD_EXAMPLE_PLUGIN=ON && cmake --build build
# build/plugins/libsample-provider.so is copied next to the executable
```
The plugin must be compiled with the same compiler and headers as the application (like a regular Qt plugin).
## Development & conventions
This project follows the **FWS** organisation conventions, detailed in `AGENTS.md`:
- **Branches**: `type/description` (e.g. `feat/login`, `fix/typo`).
- **Commits**: message in **English**, **Conventional Commits** format `<type>(<scope>): <description>`. Allowed types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. Short, imperative title; the body explains only the **why**.
- **Naming**: `kebab-case` files; identifiers (variables, functions, classes) in **English**.
- **Code & comments**: in **English**, "why" style (document the non-obvious — design choices, trade-offs — not the trivial).
- **Tests**: `*.test.*` files with `describe` / `it` names in English; run tests (and typecheck / lint when present) before considering a task done. Run them with `ctest` from `build/`.
- **Issues & bugs**: tracked through **issues** linked to the **Kanban** board; any PR fixing a bug references the issue (`Fixes #123`); do not close or modify an issue without explicit request.
- **Sensitive files (`.gitignore`)**: never commit `.env*`, `.freebuff/`, `build/` / `dist/` / `target/` / `__pycache__/`, `node_modules/`, secrets. A `.gitignore` exists at the repo root.
## License ## License
+49 -5
View File
@@ -9,6 +9,7 @@ Gestionnaire de paquets pour **Arch Linux** basé sur **pacman**, avec interface
- 🗑️ **Suppression** de paquets - 🗑️ **Suppression** de paquets
- 🔄 **Mise à jour** individuelle ou globale - 🔄 **Mise à jour** individuelle ou globale
- 📋 **Historique** de toutes les actions - 📋 **Historique** de toutes les actions
- 🧩 **Multi-fournisseurs** : pacman et Flatpak intégrés, plus des **plugins** pour ajouter d'autres gestionnaires (apt, dnf, …)
## Architecture ## Architecture
@@ -16,8 +17,11 @@ Gestionnaire de paquets pour **Arch Linux** basé sur **pacman**, avec interface
package-manager/ package-manager/
├── CMakeLists.txt # Build root ├── CMakeLists.txt # Build root
├── include/ ├── include/
│ ├── package-manager.h # Interface du gestionnaire de paquets │ ├── package-manager.h # Interface du gestionnaire de paquets (IPackageManager)
│ ├── provider-plugin.h # Contrat C ABI des plugins fournisseurs
│ ├── pacman-manager.h # Gestionnaire pacman (Arch Linux) │ ├── pacman-manager.h # Gestionnaire pacman (Arch Linux)
│ ├── flatpak-manager.h # Gestionnaire Flatpak
│ ├── plugin-manager.h # Registre des fournisseurs + chargement des plugins
│ ├── main-window.h # GUI principal │ ├── main-window.h # GUI principal
│ ├── history-manager.h # Historique des actions │ ├── history-manager.h # Historique des actions
│ └── package-model.h # Modèle Qt pour la liste │ └── package-model.h # Modèle Qt pour la liste
@@ -25,8 +29,14 @@ package-manager/
│ ├── main.cpp │ ├── main.cpp
│ ├── main-window.cpp │ ├── main-window.cpp
│ ├── pacman-manager.cpp │ ├── pacman-manager.cpp
│ ├── flatpak-manager.cpp
│ ├── plugin-manager.cpp
│ ├── history-manager.cpp │ ├── history-manager.cpp
│ └── package-model.cpp │ └── package-model.cpp
├── plugins/
│ └── example-provider/ # Plugin externe d'exemple (modèle à copier)
├── tests/ # Tests unitaires (assert, sans Qt)
└── resources/
``` ```
## Compilation (Arch Linux) ## Compilation (Arch Linux)
@@ -74,6 +84,7 @@ L'interface utilise **Qt6** avec un thème sombre, une **sidebar de navigation**
- ⬆️ **Mises à jour** : paquets obsolètes détectés par `pacman -Qu`, bouton « Tout mettre à jour » - ⬆️ **Mises à jour** : paquets obsolètes détectés par `pacman -Qu`, bouton « Tout mettre à jour »
- 📋 **Historique** : tableau filtrable (installations / suppressions / mises à jour) - 📋 **Historique** : tableau filtrable (installations / suppressions / mises à jour)
- 📜 **Logs** : journal `/var/log/pacman.log` intégré - 📜 **Logs** : journal `/var/log/pacman.log` intégré
- 🧩 **Providers** : liste des gestionnaires (intégrés et plugins), activation / désactivation et rechargement des plugins
### Aperçu de l'interface ### Aperçu de l'interface
```text ```text
@@ -97,9 +108,9 @@ L'interface utilise **Qt6** avec un thème sombre, une **sidebar de navigation**
└──────────────────────────────────────────────────────────────────────────────────────┘ └──────────────────────────────────────────────────────────────────────────────────────┘
``` ```
## Gestionnaire de paquets ## Gestionnaires de paquets (providers)
L'interface `IPackageManager` (implémentée par `PacmanManager`) définit : L'interface `IPackageManager` (implémentée par `PacmanManager` et `FlatpakManager`) définit :
| Méthode | Description | | Méthode | Description |
|---------|-------------| |---------|-------------|
@@ -111,14 +122,47 @@ L'interface `IPackageManager` (implémentée par `PacmanManager`) définit :
| `canRemove()` | Supporte la suppression | | `canRemove()` | Supporte la suppression |
| `canUpdate()` | Supporte la mise à jour | | `canUpdate()` | Supporte la mise à jour |
| `canListInstalled()` | Supporte le listage | | `canListInstalled()` | Supporte le listage |
| `isAvailable()` | Vérifie si pacman est installé | | `isAvailable()` | Vérifie si l'outil est installé |
| `requiresPassword()` | Oui si les opérations passent par sudo (pacman) |
| `search(query)` | Recherche de paquets | | `search(query)` | Recherche de paquets |
| `install(name, callback)` | Installation | | `install(name, callback)` | Installation |
| `remove(name, callback)` | Suppression | | `remove(name, callback)` | Suppression |
| `update(name, callback)` | Mise à jour | | `update(name, callback)` | Mise à jour |
| `listInstalled()` | Liste des paquets installés | | `listInstalled()` | Liste des paquets installés |
| `listUpdates()` | Liste des paquets obsolètes | | `listUpdates()` | Liste des paquets obsolètes |
| `refresh(callback)` | Rafraîchit les bases de données | | `refresh(callback)` | Rafraîchit les sources |
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 **Providers** de la barre latérale permet d'activer / désactiver chaque fournisseur, 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).
### Ajouter un fournisseur (plugins)
Pacman et Flatpak sont **intégrés**. L'installation Flatpak ajoute automatiquement le dépôt flathub si besoin et retombe en installation **utilisateur** (sans mot de passe) quand l'installation système échoue (polkit, plusieurs dépôts homonymes) — l'erreur réelle est affichée en cas d'échec. Une app installée via Flatpak apparaît immédiatement dans le launcher du bureau : ses entrées `.desktop` et ses icônes sont liées dans `~/.local/share/applications` et `~/.local/share/icons` (les dossiers XDG scannés par **tout** environnement : wofi, GNOME, KDE…), exactement comme une installation pacman, et retirées à la désinstallation. La recherche affiche le statut réel de chaque app (Installé / Mise à jour disponible). Le tout est couvert par un **test d'intégration** qui pilote le vrai CLI flatpak (install, liste, mise à jour, recherche, désinstallation). Pour ajouter un autre gestionnaire (apt, dnf, zypper, ou les dépôts d'une autre distro) sans toucher à l'application :
1. Implémentez `IPackageManager` dans un fichier `.cpp` (copiez `plugins/example-provider/example-provider.cpp` comme modèle).
2. Exportez le contrat C ABI avec la macro `FWS_PROVIDER_PLUGIN(MyManager, "id", "Nom", "1.0.0", "Description", "Auteur")`.
3. Compilez en bibliothèque partagée et déposez-la dans `~/.local/share/PacManager/plugins/` ou `plugins/` à côté de l'exécutable.
4. Cliquez sur **Recharger** dans la page Providers.
Build du plugin d'exemple :
```bash
cmake -B build -DFWS_BUILD_EXAMPLE_PLUGIN=ON && cmake --build build
# build/plugins/libsample-provider.so est copié à côté de l'exécutable
```
Le plugin doit être compilé avec le même compilateur et les mêmes en-têtes que l'application (comme un plugin Qt classique).
## Développement & conventions
Ce projet suit les conventions de l'organisation **FWS**, détaillées dans `AGENTS.md` :
- **Branches** : `type/description` (ex. `feat/login`, `fix/typo`).
- **Commits** : message en **anglais**, format **Conventional Commits** `<type>(<portée>): <description>`. Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. Titre court et impératif ; le corps n'explique que le **pourquoi**.
- **Fichiers** : `kebab-case` ; identifiants (variables, fonctions, classes) en **anglais**.
- **Code & commentaires** : en **anglais**, style « pourquoi » (documenter le non-évident — choix d'implémentation, trade-offs —, pas le banal).
- **Tests** : fichiers `*.test.*` avec noms `describe` / `it` en anglais ; les tests (et le typecheck / lint quand ils existent) doivent passer avant de considérer une tâche terminée. Lancez-les avec `ctest` depuis `build/`.
- **Issues & bugs** : suivis via les **issues** liées au tableau **Kanban** ; toute PR corrigeant un bug référence l'issue (`Fixes #123`) ; ne pas fermer ni modifier une issue sans demande explicite.
- **Fichiers sensibles (`.gitignore`)** : ne jamais committer `.env*`, `.freebuff/`, `build/` / `dist/` / `target/` / `__pycache__/`, `node_modules/`, secrets. Un `.gitignore` existe à la racine du repo.
## Licence ## Licence
+68
View File
@@ -0,0 +1,68 @@
#pragma once
#include "package-manager.h"
// Flatpak provider: manages flatpak applications through the `flatpak` CLI.
// Unlike pacman it runs per-user (no sudo), so requiresPassword() is false.
class FlatpakManager : public IPackageManager {
public:
std::string getName() const override { return "flatpak"; }
std::string getVersion() const override { return "1.0.0"; }
std::string getDescription() const override {
return "Gestionnaire d'applications Flatpak";
}
bool canSearch() const override { return true; }
bool canInstall() const override { return true; }
bool canRemove() const override { return true; }
bool canUpdate() const override { return true; }
bool canListInstalled() const override { return true; }
bool isAvailable() const override {
return system("which flatpak > /dev/null 2>&1") == 0;
}
// Last lines of the failed command output, shown to the user on failure.
std::string lastError() const override { return m_lastError; }
// Parse `flatpak search` output (one whitespace-aligned row per app:
// "Name Description Application ID Version Branch Remotes").
// Exposed as static so the parsing can be unit-tested without flatpak.
static std::vector<PackageInfo> parseSearchOutput(const std::string& output);
// Parse `flatpak list --columns=application,version,origin` output
// (tab-separated fields per installed application).
static std::vector<PackageInfo> parseInstalledOutput(const std::string& output);
// Parse `flatpak remote-ls --updates --columns=application,version` output
// (tab-separated fields per application with a pending update).
static std::vector<PackageInfo> parseUpdatesOutput(const std::string& output);
std::vector<PackageInfo> search(const std::string& query) override;
bool install(const std::string& packageName,
std::function<void(const std::string&)> progressCallback) override;
bool remove(const std::string& packageName,
std::function<void(const std::string&)> progressCallback) override;
bool update(const std::string& packageName = "",
std::function<void(const std::string&)> progressCallback = nullptr) override;
std::vector<PackageInfo> listInstalled() override;
std::vector<PackageInfo> listUpdates() override;
bool refresh(std::function<void(const std::string&)> 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
// standard XDG directories (~/.local/share/{applications,icons}). Exposed
// as static so the linking can be unit/integration tested without flatpak.
static void integrateDesktopEntries(const std::string& appId);
static void uninstallDesktopEntries(const std::string& appId);
// Re-link every installed app so launchers pick up apps whose integration
// is missing (e.g. installed before this feature existed).
void integrateAllInstalled();
private:
bool isInstalled(const std::string& appId);
std::string m_lastError;
};
+40 -10
View File
@@ -16,6 +16,8 @@
#include "package-manager.h" #include "package-manager.h"
#include "pacman-manager.h" #include "pacman-manager.h"
#include "flatpak-manager.h"
#include "plugin-manager.h"
#include "history-manager.h" #include "history-manager.h"
class QStackedWidget; class QStackedWidget;
@@ -27,45 +29,50 @@ class QButtonGroup;
class QFrame; class QFrame;
class QAction; class QAction;
// Runs a package search off the UI thread. // Runs a package search off the UI thread. Queries every given provider and
// merges the results, tagging each package with its provider id.
class SearchWorker : public QThread { class SearchWorker : public QThread {
Q_OBJECT Q_OBJECT
public: public:
SearchWorker(IPackageManager* pm, const std::string& query); SearchWorker(const std::vector<IPackageManager*>& providers, const std::string& query);
void run() override; void run() override;
signals: signals:
void finished(std::vector<PackageInfo> results); void finished(std::vector<PackageInfo> results);
private: private:
IPackageManager* m_pm; std::vector<IPackageManager*> m_providers;
std::string m_query; std::string m_query;
}; };
// Loads a package list (installed or outdated) off the UI thread. // Loads a package list (installed or outdated) off the UI thread, aggregated
// across every given provider.
class ListWorker : public QThread { class ListWorker : public QThread {
Q_OBJECT Q_OBJECT
public: public:
enum Mode { Installed, Updates }; enum Mode { Installed, Updates };
ListWorker(IPackageManager* pm, Mode mode); ListWorker(const std::vector<IPackageManager*>& providers, Mode mode);
void run() override; void run() override;
signals: signals:
void finished(std::vector<PackageInfo> results); void finished(std::vector<PackageInfo> results);
private: private:
IPackageManager* m_pm; std::vector<IPackageManager*> m_providers;
Mode m_mode; Mode m_mode;
}; };
// Runs an install/remove/update/refresh action off the UI thread. // Runs install/remove/update/refresh actions off the UI thread. Single-package
// operations take one provider; UpdateAll/Refresh take every provider and run
// on each of them in sequence.
class InstallWorker : public QThread { class InstallWorker : public QThread {
Q_OBJECT Q_OBJECT
public: public:
enum class Op { Install, Remove, Update, UpdateAll, Refresh }; enum class Op { Install, Remove, Update, UpdateAll, Refresh };
InstallWorker(IPackageManager* pm, Op op, const std::string& package); InstallWorker(IPackageManager* pm, Op op, const std::string& package);
InstallWorker(const std::vector<IPackageManager*>& providers, Op op);
void run() override; void run() override;
signals: signals:
void progress(const QString& message); void progress(const QString& message);
void finished(bool success); void finished(bool success);
private: private:
IPackageManager* m_pm; std::vector<IPackageManager*> m_providers;
Op m_op; Op m_op;
std::string m_package; std::string m_package;
}; };
@@ -92,6 +99,10 @@ private slots:
void onHistoryFilterChanged(); void onHistoryFilterChanged();
void onInstalledFilterChanged(const QString& text); void onInstalledFilterChanged(const QString& text);
void onRecentActivityClicked(QListWidgetItem* item); void onRecentActivityClicked(QListWidgetItem* item);
void onProviderTableSelected(int row);
void onToggleProvider();
void onRescanProviders();
void onInstallProviderTool();
private: private:
enum BrowseMode { ModeSearch, ModeInstalled, ModeUpdates }; enum BrowseMode { ModeSearch, ModeInstalled, ModeUpdates };
@@ -101,9 +112,17 @@ private:
enum class CredentialMode { AtLaunch, EachTime }; enum class CredentialMode { AtLaunch, EachTime };
void applyCredentialMode(CredentialMode mode); void applyCredentialMode(CredentialMode mode);
bool ensureCredentials(); bool ensureCredentials(const std::vector<IPackageManager*>& providers);
void clearCredentialsAfterUse(); void clearCredentialsAfterUse();
// Manager owning a package, based on its provider tag; falls back to the
// first available provider when the tag is unknown or empty.
IPackageManager* providerFor(const std::string& id) const;
// Show the provider's last error in a dialog when one is available, so a
// failed operation explains itself instead of failing silently.
void showProviderError(const QString& title, IPackageManager* provider);
void setupUI(); void setupUI();
void setupSidebar(); void setupSidebar();
void setupHeader(); void setupHeader();
@@ -111,11 +130,13 @@ private:
void setupBrowsePage(); void setupBrowsePage();
void setupHistoryPage(); void setupHistoryPage();
void setupLogsPage(); void setupLogsPage();
void setupProvidersPage();
void setupMenuBar(); void setupMenuBar();
void updatePageTitle(); void updatePageTitle();
void updateStatusBar(); void updateStatusBar();
void refreshDashboard(); void refreshDashboard();
void refreshRecentActivity(); void refreshRecentActivity();
void refreshProvidersTable();
void updatePackageInfo(const PackageInfo& pkg); void updatePackageInfo(const PackageInfo& pkg);
void resetDetailsPanel(); void resetDetailsPanel();
void setBrowseMode(BrowseMode mode); void setBrowseMode(BrowseMode mode);
@@ -168,6 +189,7 @@ private:
QLabel* m_packageVersion = nullptr; QLabel* m_packageVersion = nullptr;
QLabel* m_packageRepo = nullptr; QLabel* m_packageRepo = nullptr;
QLabel* m_packageSize = nullptr; QLabel* m_packageSize = nullptr;
QLabel* m_packageProvider = nullptr;
QWidget* m_packageUpdateBadge = nullptr; QWidget* m_packageUpdateBadge = nullptr;
QLabel* m_packageDescription = nullptr; QLabel* m_packageDescription = nullptr;
@@ -179,8 +201,16 @@ private:
// Logs page // Logs page
QTextEdit* m_logsText = nullptr; QTextEdit* m_logsText = nullptr;
// Providers page
QTableWidget* m_providerTable = nullptr;
QPushButton* m_providerToggleButton = nullptr;
QPushButton* m_providerInstallButton = nullptr;
QLabel* m_providerDescription = nullptr;
std::string m_selectedProviderId;
// Backend // Backend
PacmanManager* m_pacman = nullptr; PacmanManager* m_pacman = nullptr; // non-owning, used for sudo credentials/logs
PluginManager* m_pluginManager = nullptr; // owns every provider
HistoryManager* m_historyManager = nullptr; HistoryManager* m_historyManager = nullptr;
BrowseMode m_browseMode = ModeSearch; BrowseMode m_browseMode = ModeSearch;
+101
View File
@@ -3,6 +3,9 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <functional> #include <functional>
#include <map>
#include <algorithm>
#include <cctype>
// Information about a single package // Information about a single package
struct PackageInfo { struct PackageInfo {
@@ -12,10 +15,99 @@ struct PackageInfo {
std::string repository; std::string repository;
std::string size; std::string size;
std::string installedSize; std::string installedSize;
// Id of the provider that owns this package (e.g. "pacman", "flatpak").
// Filled by the aggregating workers so operations can be routed to the
// right manager without the user picking one.
std::string provider;
// Every provider offering this package, after duplicate rows have been
// merged (used for display). The routing id stays in `provider`.
std::vector<std::string> providers;
bool installed = false; bool installed = false;
bool updateAvailable = false; bool updateAvailable = false;
}; };
// Merge packages that share the same name (offered by several providers) into
// a single row. The first occurrence keeps its metadata and provider id (so
// operations keep a deterministic default); later occurrences are folded in:
// installed/updateAvailable become true if any provider reports them, and
// their provider id is added to pkg.providers for display.
inline void mergeProviderDuplicates(std::vector<PackageInfo>& packages) {
// Every tagged package advertises at least its own provider.
for (auto& pkg : packages) {
if (pkg.providers.empty() && !pkg.provider.empty()) {
pkg.providers.push_back(pkg.provider);
}
}
std::map<std::string, std::size_t> firstIndex;
std::vector<std::size_t> toDrop;
for (std::size_t i = 0; i < packages.size(); ++i) {
const std::string& name = packages[i].name;
if (name.empty()) continue;
auto it = firstIndex.find(name);
if (it == firstIndex.end()) {
firstIndex.emplace(name, i);
continue;
}
PackageInfo& first = packages[it->second];
const PackageInfo& dup = packages[i];
first.installed = first.installed || dup.installed;
first.updateAvailable = first.updateAvailable || dup.updateAvailable;
if (!dup.provider.empty()) {
bool known = false;
for (const auto& p : first.providers) {
if (p == dup.provider) {
known = true;
break;
}
}
if (!known) first.providers.push_back(dup.provider);
}
toDrop.push_back(i);
}
for (auto it = toDrop.rbegin(); it != toDrop.rend(); ++it) {
packages.erase(packages.begin() + static_cast<std::ptrdiff_t>(*it));
}
}
// Sort aggregated results by provider, then by name (case-insensitive), so
// packages from the same manager stay grouped. Providers are ordered by their
// position in providerOrder (query order); providers absent from it sort last
// and are compared by id.
inline void sortByProviderThenName(std::vector<PackageInfo>& packages,
const std::vector<std::string>& providerOrder = {}) {
auto ciLess = [](const std::string& a, const std::string& b) {
std::size_t i = 0;
for (; i < a.size() && i < b.size(); ++i) {
unsigned char ca =
static_cast<unsigned char>(std::tolower(static_cast<unsigned char>(a[i])));
unsigned char cb =
static_cast<unsigned char>(std::tolower(static_cast<unsigned char>(b[i])));
if (ca != cb) return ca < cb;
}
return a.size() < b.size();
};
auto rank = [&](const std::string& id) {
for (std::size_t i = 0; i < providerOrder.size(); ++i) {
if (providerOrder[i] == id) return static_cast<int>(i);
}
return static_cast<int>(providerOrder.size());
};
std::stable_sort(packages.begin(), packages.end(),
[&](const PackageInfo& a, const PackageInfo& b) {
int ra = rank(a.provider);
int rb = rank(b.provider);
if (ra != rb) return ra < rb;
if (a.provider != b.provider) return a.provider < b.provider;
return ciLess(a.name, b.name);
});
}
// Abstract interface for the package manager // Abstract interface for the package manager
class IPackageManager { class IPackageManager {
public: public:
@@ -47,6 +139,15 @@ public:
// Check if the package manager is available on the system // Check if the package manager is available on the system
virtual bool isAvailable() const = 0; virtual bool isAvailable() const = 0;
// Whether privileged operations need a password (e.g. sudo for pacman).
// Providers that run per-user (e.g. flatpak) can keep the default.
virtual bool requiresPassword() const { return false; }
// Last error reported by the most recent failed operation, if any. Used
// to surface the real command output to the user instead of a generic
// failure message.
virtual std::string lastError() const { return {}; }
}; };
+3
View File
@@ -22,6 +22,9 @@ public:
return system("which pacman > /dev/null 2>&1") == 0; return system("which pacman > /dev/null 2>&1") == 0;
} }
// pacman operations run through sudo and need the session password.
bool requiresPassword() const override { return true; }
// Parse `pacman -Q` output (one "name version" line per package). // Parse `pacman -Q` output (one "name version" line per package).
// Exposed as static so the parsing can be unit-tested without invoking pacman. // Exposed as static so the parsing can be unit-tested without invoking pacman.
static std::vector<PackageInfo> parseInstalledOutput(const std::string& output); static std::vector<PackageInfo> parseInstalledOutput(const std::string& output);
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include "provider-plugin.h"
#include <QSettings>
#include <QLibrary>
#include <string>
#include <vector>
// Registry of package providers. It owns every IPackageManager (built-in and
// external) and can load additional providers at runtime from shared-library
// plugins dropped in the plugin directories (see PluginManager::scanDirectory).
class PluginManager {
public:
struct ProviderEntry {
ProviderInfo info;
IPackageManager* manager = nullptr; // owned by the PluginManager
QLibrary* library = nullptr; // owned by the PluginManager; null for built-ins
};
PluginManager();
~PluginManager();
// Register a provider compiled into the application (e.g. pacman, flatpak).
// Takes ownership of the manager.
void registerBuiltin(ProviderInfo info, IPackageManager* manager);
// Scan the plugin directories for external provider plugins and load them.
void discoverExternal();
// Drop external plugins and rescan their directories; built-in providers
// are kept (their instances stay valid).
void reload();
// Re-run isAvailable() on every known provider (e.g. after the app
// installed a missing tool) so the Providers page reflects reality.
void refreshAvailability();
// All known providers, in registration order.
const std::vector<ProviderEntry>& providers() const;
// Providers that are enabled (in settings) and whose tool is on the system.
std::vector<const ProviderEntry*> availableProviders() const;
// Same as availableProviders() but as plain manager pointers, convenient
// for running aggregated operations across every provider.
std::vector<IPackageManager*> availableManagers() const;
// A single available+enabled provider matching id, or nullptr.
const ProviderEntry* findAvailable(const std::string& id) const;
bool isEnabled(const std::string& id) const;
void setEnabled(const std::string& id, bool enabled);
// Manager for a known provider id (enabled or not), or nullptr.
IPackageManager* managerFor(const std::string& id) const;
private:
bool loadPluginFile(const QString& filePath);
void scanDirectory(const QString& dir);
void unloadExternal();
std::vector<ProviderEntry> m_providers;
QSettings m_settings;
};
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include "package-manager.h"
#include <string>
// Metadata describing a provider, whether it is compiled into the application
// (pacman, flatpak) or loaded at runtime from an external plugin.
struct ProviderInfo {
std::string id; // unique identifier, e.g. "pacman", "flatpak"
std::string name; // display name, e.g. "Flatpak"
std::string version; // plugin version
std::string description; // what this provider manages
std::string author; // who wrote the provider
bool builtin = false; // true when compiled into the application
std::string path; // filesystem path (external plugins only)
bool available = false; // whether the backing tool is present on the system
// OS package name providing the backing tool (e.g. "flatpak"). Empty when
// the provider cannot be installed from the application.
std::string installHint;
};
// ---- External plugin contract (C ABI) ----
//
// An external provider plugin is a shared library (lib*.so / *.dll) dropped in
// a plugin directory (see PluginManager). It must export the symbols below so
// the host can query metadata and instantiate the provider. The convenience
// macro FWS_PROVIDER_PLUGIN generates them from a class implementing
// IPackageManager:
//
// #include "provider-plugin.h"
// #include "my-manager.h"
// FWS_PROVIDER_PLUGIN(MyManager, "myprov", "My Provider", "1.0.0",
// "Manages my stuff", "Jane Doe");
//
// Plugins are compiled with the same toolchain/headers as the host, exactly
// like Qt plugins, so the IPackageManager vtable and PackageInfo layout match.
extern "C" {
const char* fws_plugin_id();
const char* fws_plugin_name();
const char* fws_plugin_version();
const char* fws_plugin_description();
const char* fws_plugin_author();
IPackageManager* fws_create_provider();
// Optional: OS package name that provides the backing tool, so the app can
// offer to install it when unavailable. May be omitted by a plugin.
const char* fws_plugin_install_hint();
}
#define FWS_PROVIDER_PLUGIN(PluginClass, id_, name_, version_, desc_, author_) \
extern "C" const char* fws_plugin_id() { return id_; } \
extern "C" const char* fws_plugin_name() { return name_; } \
extern "C" const char* fws_plugin_version() { return version_; } \
extern "C" const char* fws_plugin_description() { return desc_; } \
extern "C" const char* fws_plugin_author() { return author_; } \
extern "C" IPackageManager* fws_create_provider() { return new PluginClass(); }
@@ -0,0 +1,52 @@
// Example external provider plugin — a template for adding new package
// providers without touching the application code.
//
// Build it as a shared library and drop it in a plugin directory
// (next to the PacManager binary in ./plugins/ or in
// ~/.local/share/PacManager/plugins/); the app discovers it at launch and on
// the Providers page via "Recharger".
//
// A plugin only needs to:
// 1. implement IPackageManager (see include/package-manager.h)
// 2. export the C ABI symbols via the FWS_PROVIDER_PLUGIN macro
//
// To build with CMake from the project root:
// cmake -B build -DFWS_BUILD_EXAMPLE_PLUGIN=ON && cmake --build build
#include "provider-plugin.h"
// A trivial provider that reports itself as always available but manages
// nothing — replace the stubs with real commands (apt, dnf, zypper, ...).
class SampleProvider : public IPackageManager {
public:
std::string getName() const override { return "sample"; }
std::string getVersion() const override { return "0.1.0"; }
std::string getDescription() const override {
return "Exemple de plugin fournisseur (modèle à copier)";
}
bool canSearch() const override { return false; }
bool canInstall() const override { return false; }
bool canRemove() const override { return false; }
bool canUpdate() const override { return false; }
bool canListInstalled() const override { return false; }
bool isAvailable() const override { return true; }
std::vector<PackageInfo> search(const std::string&) override { return {}; }
bool install(const std::string&, std::function<void(const std::string&)>) override {
return false;
}
bool remove(const std::string&, std::function<void(const std::string&)>) override {
return false;
}
bool update(const std::string&, std::function<void(const std::string&)>) override {
return false;
}
std::vector<PackageInfo> listInstalled() override { return {}; }
std::vector<PackageInfo> listUpdates() override { return {}; }
bool refresh(std::function<void(const std::string&)>) override { return false; }
};
FWS_PROVIDER_PLUGIN(SampleProvider, "sample", "Sample Provider", "0.1.0",
"Exemple de plugin fournisseur (modèle à copier)", "FWS");
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#c8d3f5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="24" height="24">
<path d="M9 3.5a1.75 1.75 0 0 1 3.5 0V6h3.5a1.75 1.75 0 0 1 0 3.5H12.5V13h-3.5a1.75 1.75 0 0 1 0-3.5H6.5a1.75 1.75 0 0 1 0-3.5H9V3.5z"/>
<path d="M9 13h3.5v3.5A1.75 1.75 0 0 0 14.25 18.25h.5a1.75 1.75 0 0 0 1.75-1.75V13H20a1.75 1.75 0 0 0 1.75-1.75v-.5A1.75 1.75 0 0 0 20 9h-3.5"/>
</svg>

After

Width:  |  Height:  |  Size: 470 B

+1
View File
@@ -14,5 +14,6 @@
<file alias="close.svg">icons/close.svg</file> <file alias="close.svg">icons/close.svg</file>
<file alias="filter.svg">icons/filter.svg</file> <file alias="filter.svg">icons/filter.svg</file>
<file alias="alert.svg">icons/alert.svg</file> <file alias="alert.svg">icons/alert.svg</file>
<file alias="plugin.svg">icons/plugin.svg</file>
</qresource> </qresource>
</RCC> </RCC>
+462
View File
@@ -0,0 +1,462 @@
#include "flatpak-manager.h"
#include <array>
#include <memory>
#include <stdexcept>
#include <sstream>
#include <cctype>
#include <algorithm>
#include <cstdlib>
#include <filesystem>
#include <set>
#include <vector>
namespace fs = std::filesystem;
// The per-user standard XDG data dir (~/.local/share).
static fs::path userShareDir() {
const char* home = std::getenv("HOME");
return fs::path(home ? home : "/tmp") / ".local/share";
}
// Link (or fall back to copy) one flatpak export into the user's standard XDG
// dir. Preferring a symlink means it survives flatpak app updates, which
// re-export at the same path.
static void linkFile(const fs::path& src, const fs::path& dest) {
std::error_code ec;
fs::create_directories(dest.parent_path(), ec);
fs::remove(dest, ec); // Replace any stale entry (e.g. from a past run).
fs::create_symlink(fs::absolute(src), dest, ec);
if (ec) fs::copy_file(src, dest, fs::copy_options::overwrite_existing, ec);
}
// Helper to run shell commands and capture output.
static std::string exec(const char* cmd) {
std::array<char, 256> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed");
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
// Stream the lines of a command's output to the progress callback, if any.
static void streamOutput(const std::string& output,
std::function<void(const std::string&)> progressCallback) {
if (!progressCallback) return;
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty()) progressCallback(line);
}
}
// A flatpak application ID is a dotted identifier with at least two dots whose
// segments start with an alphanumeric character (e.g. org.mozilla.firefox).
// This deliberately rejects version strings such as "128.0.2".
static bool isAppId(const std::string& token) {
int dots = 0;
bool first = true;
for (size_t i = 0; i < token.size(); ++i) {
char c = token[i];
if (c == '.') {
++dots;
first = true; // next segment must start with an alnum again
} else if (std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_') {
if (first && !std::isalnum(static_cast<unsigned char>(c))) return false;
first = false;
} else {
return false;
}
}
return dots >= 2 && !first;
}
// Keep the tail of a command's output (the last few non-empty lines) so the
// user sees the real reason an operation failed.
static std::string lastOutputLines(const std::string& output, int maxLines = 4) {
std::istringstream iss(output);
std::vector<std::string> lines;
std::string line;
while (std::getline(iss, line)) {
if (!line.empty()) lines.push_back(line);
}
std::string result;
int start = std::max(0, static_cast<int>(lines.size()) - maxLines);
for (int i = start; i < static_cast<int>(lines.size()); ++i) {
result += lines[i];
result += "\n";
}
return result;
}
// Split a flatpak --columns line. flatpak emits tab-separated fields with that
// flag; fall back to whitespace splitting when tabs are absent.
static std::vector<std::string> splitColumns(const std::string& line) {
std::vector<std::string> fields;
std::istringstream ss(line);
std::string field;
if (line.find('\t') != std::string::npos) {
while (std::getline(ss, field, '\t')) {
if (!field.empty()) fields.push_back(field);
}
} else {
while (ss >> field) fields.push_back(field);
}
return fields;
}
// `flatpak search` prints one aligned row per app:
// Name Description Application ID Version Branch Remotes
// The description may contain spaces, so the application ID is located by
// shape (dotted identifier) and everything between Name and it is joined back.
std::vector<PackageInfo> FlatpakManager::parseSearchOutput(const std::string& output) {
std::vector<PackageInfo> results;
std::istringstream iss(output);
std::string line;
bool firstLine = true;
while (std::getline(iss, line)) {
if (firstLine) {
firstLine = false;
continue; // Skip the column header.
}
if (line.empty()) continue;
std::vector<std::string> tokens = splitColumns(line);
if (tokens.empty()) continue;
int appIdx = -1;
for (int i = 1; i < static_cast<int>(tokens.size()); ++i) {
if (isAppId(tokens[i])) {
appIdx = i;
break;
}
}
if (appIdx == -1) continue; // Not an application row.
PackageInfo pkg;
// Use the application ID as the package name so install/remove/update
// work directly with the CLI; the human-readable name is kept at the
// front of the description (e.g. "Firefox — Fast and privacy-aware").
pkg.name = tokens[appIdx];
pkg.version = (appIdx + 1 < static_cast<int>(tokens.size())) ? tokens[appIdx + 1] : "";
pkg.repository = tokens.back();
for (int i = 1; i < appIdx; ++i) {
if (!pkg.description.empty()) pkg.description += " ";
pkg.description += tokens[i];
}
if (!tokens[0].empty() && tokens[0] != pkg.name) {
pkg.description = tokens[0] + " — " + pkg.description;
}
results.push_back(pkg);
}
return results;
}
std::vector<PackageInfo> FlatpakManager::parseInstalledOutput(const std::string& output) {
std::vector<PackageInfo> results;
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (line.empty()) continue;
std::vector<std::string> fields = splitColumns(line);
if (fields.empty()) continue;
PackageInfo pkg;
pkg.name = fields[0];
if (fields.size() > 1) pkg.version = fields[1];
if (fields.size() > 2) pkg.repository = fields[2];
pkg.installed = true;
results.push_back(pkg);
}
return results;
}
std::vector<PackageInfo> FlatpakManager::parseUpdatesOutput(const std::string& output) {
std::vector<PackageInfo> results;
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (line.empty()) continue;
std::vector<std::string> fields = splitColumns(line);
if (fields.empty()) continue;
PackageInfo pkg;
pkg.name = fields[0];
if (fields.size() > 1) pkg.version = fields[1];
pkg.installed = true;
pkg.updateAvailable = true;
results.push_back(pkg);
}
return results;
}
std::vector<PackageInfo> FlatpakManager::search(const std::string& query) {
std::string cmd = "flatpak search " + query + " 2>&1";
std::vector<PackageInfo> results = parseSearchOutput(exec(cmd.c_str()));
// Report the honest status of each hit (already installed / pending
// update) so the search page does not keep showing "Disponible" for apps
// that are already managed, like pacman does with its [installed] marker.
if (!results.empty()) {
std::set<std::string> installed;
for (const auto& pkg : listInstalled()) installed.insert(pkg.name);
std::set<std::string> outdated;
for (const auto& pkg : listUpdates()) outdated.insert(pkg.name);
for (auto& pkg : results) {
pkg.installed = installed.count(pkg.name) > 0;
pkg.updateAvailable = outdated.count(pkg.name) > 0;
}
}
return results;
}
std::vector<PackageInfo> FlatpakManager::listInstalled() {
return parseInstalledOutput(
exec("flatpak list --app --columns=application,version,origin 2>&1"));
}
std::vector<PackageInfo> FlatpakManager::listUpdates() {
return parseUpdatesOutput(
exec("flatpak remote-ls --updates --columns=application,version 2>&1"));
}
bool FlatpakManager::isInstalled(const std::string& appId) {
std::string cmd = "flatpak info " + appId + " > /dev/null 2>&1";
return system(cmd.c_str()) == 0;
}
bool FlatpakManager::install(const std::string& packageName,
std::function<void(const std::string&)> progressCallback) {
m_lastError.clear();
// Idempotent: an app already deployed (in either installation) is reported
// as installed without re-running the installer, then made sure it appears
// in the desktop launcher (covers apps installed before this feature).
if (isInstalled(packageName)) {
if (progressCallback) progressCallback(packageName + " est déjà installé.");
integrateDesktopEntries(packageName);
return true;
}
if (progressCallback) progressCallback("Installation de " + packageName + "...");
auto tryInstall = [&](const std::string& extra) {
return exec(("flatpak install --noninteractive --assumeyes " + extra + " "
+ packageName + " 2>&1").c_str());
};
// A fresh flatpak setup has no remote configured: add the default flathub
// one (idempotent, per-user) so the install can resolve the app.
exec("flatpak remote-add --if-not-exists --user flathub "
"https://flathub.org/repo/flathub.flatpakrepo 2>&1");
std::string output = tryInstall("");
auto ambiguous = [&]() {
return output.find("Multiple remotes") != std::string::npos;
};
auto noRefs = [&]() {
return output.find("No refs found") != std::string::npos
|| output.find("No remote refs") != std::string::npos;
};
// Stale remote metadata makes flatpak report "No refs found": refresh the
// appstream cache and retry once before giving up. When both a system and
// a user flathub remote exist, flatpak refuses to pick one in non-
// interactive mode, so go straight to the per-user installation instead of
// repeating a doomed attempt.
if (output.find("error:") != std::string::npos && !isInstalled(packageName)
&& (noRefs() || ambiguous())) {
if (progressCallback) progressCallback("Mise à jour des métadonnées des dépôts...");
exec("flatpak update --appstream 2>&1");
output = tryInstall(ambiguous() ? "--user flathub" : "");
}
// Remaining failures get one per-user attempt (no polkit, no ambiguity).
if (output.find("error:") != std::string::npos && !isInstalled(packageName)) {
if (progressCallback) progressCallback("Nouvel essai en mode utilisateur...");
output = tryInstall("--user flathub");
}
streamOutput(output, progressCallback);
// The authoritative success check is `flatpak info`; the output may carry
// noise such as "already installed" that must not count as a failure.
if (!isInstalled(packageName)) {
m_lastError = lastOutputLines(output);
return false;
}
// Like a pacman install, make the freshly installed app appear in the
// desktop launcher immediately (see integrateDesktopEntries).
integrateDesktopEntries(packageName);
return true;
}
// Link an app's launcher entries and icons into the user's standard XDG dirs
// (~/.local/share/{applications,icons}), which every desktop scans by default.
// This makes flatpak apps show up in any launcher (wofi, dmenu, GNOME menu,
// KDE...) regardless of XDG_DATA_DIRS, mirroring what a pacman install does
// through /usr/share/applications.
void FlatpakManager::integrateDesktopEntries(const std::string& appId) {
std::error_code ec;
fs::path exports = userShareDir() / "flatpak/exports/share";
if (!fs::is_directory(exports, ec)) return;
// .desktop files are the core of the integration.
fs::path srcApps = exports / "applications";
fs::path destApps = userShareDir() / "applications";
if (fs::is_directory(srcApps, ec)) {
fs::create_directories(destApps, ec);
for (const auto& entry : fs::directory_iterator(srcApps)) {
const std::string name = entry.path().filename().string();
if (name.rfind(appId, 0) == 0
&& entry.path().extension() == ".desktop") {
linkFile(entry.path(), destApps / name);
}
}
}
// Mirror the app's icons so the launcher shows a proper icon.
fs::path srcIcons = exports / "icons";
fs::path destIcons = userShareDir() / "icons";
if (fs::is_directory(srcIcons, ec)) {
for (const auto& entry : fs::recursive_directory_iterator(srcIcons)) {
if (!entry.is_regular_file()) continue;
const std::string name = entry.path().filename().string();
if (name.rfind(appId, 0) != 0) continue;
auto rel = entry.path().lexically_relative(srcIcons);
linkFile(entry.path(), destIcons / rel);
}
}
// Refresh the desktop-entry database so launchers pick up the new entries.
system(("update-desktop-database " + destApps.string() + " >/dev/null 2>&1").c_str());
}
// Remove the launcher links created by integrateDesktopEntries. Only entries
// that are symlinks we created are removed, so a real file of the same name is
// never touched.
void FlatpakManager::uninstallDesktopEntries(const std::string& appId) {
auto removeLinks = [&](const fs::path& dir, bool recursive) {
std::error_code ec;
if (!fs::is_directory(dir, ec)) return;
if (recursive) {
for (const auto& entry : fs::recursive_directory_iterator(dir, ec)) {
if (!entry.is_symlink()) continue;
if (entry.path().filename().string().rfind(appId, 0) != 0) continue;
fs::remove(entry.path(), ec);
}
} else {
for (const auto& entry : fs::directory_iterator(dir, ec)) {
if (!entry.is_symlink()) continue;
if (entry.path().filename().string().rfind(appId, 0) != 0) continue;
fs::remove(entry.path(), ec);
}
}
};
removeLinks(userShareDir() / "applications", /*recursive=*/false);
removeLinks(userShareDir() / "icons", /*recursive=*/true);
system(("update-desktop-database " + (userShareDir() / "applications").string()
+ " >/dev/null 2>&1").c_str());
}
void FlatpakManager::integrateAllInstalled() {
for (const auto& pkg : listInstalled()) {
integrateDesktopEntries(pkg.name);
}
}
bool FlatpakManager::remove(const std::string& packageName,
std::function<void(const std::string&)> progressCallback) {
m_lastError.clear();
if (progressCallback) progressCallback("Suppression de " + packageName + "...");
std::string output = exec(
("flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1").c_str());
streamOutput(output, progressCallback);
if (output.find("error:") != std::string::npos || isInstalled(packageName)) {
m_lastError = lastOutputLines(output);
return false;
}
// Clear the launcher links created at install time (see integrateDesktopEntries).
uninstallDesktopEntries(packageName);
return true;
}
bool FlatpakManager::update(const std::string& packageName,
std::function<void(const std::string&)> progressCallback) {
m_lastError.clear();
auto tryUpdate = [&](const std::string& extra) {
if (packageName.empty()) {
return exec(("flatpak update --noninteractive --assumeyes " + extra + " 2>&1").c_str());
}
return exec(("flatpak update --noninteractive --assumeyes " + extra + " "
+ packageName + " 2>&1").c_str());
};
if (packageName.empty()) {
if (progressCallback) progressCallback("Mise à jour de toutes les applications...");
} else {
if (progressCallback) progressCallback("Mise à jour de " + packageName + "...");
}
std::string output = tryUpdate("");
// System-wide updates need polkit: fall back to the per-user installation.
if (output.find("error:") != std::string::npos) {
if (progressCallback) progressCallback("Nouvel essai en mode utilisateur...");
output = tryUpdate("--user");
}
streamOutput(output, progressCallback);
if (output.find("error:") != std::string::npos) {
m_lastError = lastOutputLines(output);
return false;
}
return true;
}
bool FlatpakManager::refresh(std::function<void(const std::string&)> progressCallback) {
m_lastError.clear();
if (progressCallback) progressCallback("Rafraîchissement des métadonnées Flatpak...");
// Re-download the appstream metadata of every remote so search and
// update detection reflect the latest published versions.
std::string output = exec("flatpak update --appstream 2>&1");
// System remotes need polkit for that: fall back to the user installation.
if (output.find("error:") != std::string::npos) {
exec("flatpak remote-add --if-not-exists --user flathub "
"https://flathub.org/repo/flathub.flatpakrepo 2>&1");
output = exec("flatpak update --appstream --user 2>&1");
}
streamOutput(output, progressCallback);
if (output.find("error:") != std::string::npos) {
m_lastError = lastOutputLines(output);
return false;
}
// Self-heal: re-link launcher entries of every installed app so any that
// predate desktop integration (or were installed outside the app) still
// show up in the desktop menu.
integrateAllInstalled();
return true;
}
+508 -82
View File
@@ -27,42 +27,83 @@
#include <algorithm> #include <algorithm>
// Worker threads // Worker threads
SearchWorker::SearchWorker(IPackageManager* pm, const std::string& query) SearchWorker::SearchWorker(const std::vector<IPackageManager*>& providers,
: m_pm(pm), m_query(query) {} const std::string& query)
: m_providers(providers), m_query(query) {}
void SearchWorker::run() { void SearchWorker::run() {
auto results = m_pm->search(m_query); std::vector<PackageInfo> results;
for (IPackageManager* pm : m_providers) {
if (!pm->canSearch()) continue;
for (auto& pkg : pm->search(m_query)) {
pkg.provider = pm->getName();
results.push_back(pkg);
}
}
// One row per package name, whatever the number of providers offering it.
mergeProviderDuplicates(results);
// Group by provider (query order), then sort alphabetically within each.
std::vector<std::string> providerOrder;
for (IPackageManager* pm : m_providers) providerOrder.push_back(pm->getName());
sortByProviderThenName(results, providerOrder);
emit finished(results); emit finished(results);
} }
ListWorker::ListWorker(IPackageManager* pm, Mode mode) ListWorker::ListWorker(const std::vector<IPackageManager*>& providers, Mode mode)
: m_pm(pm), m_mode(mode) {} : m_providers(providers), m_mode(mode) {}
void ListWorker::run() { void ListWorker::run() {
std::vector<PackageInfo> results; std::vector<PackageInfo> results;
if (m_mode == Installed) { for (IPackageManager* pm : m_providers) {
results = m_pm->listInstalled(); if (m_mode == Installed) {
} else { if (!pm->canListInstalled()) continue;
results = m_pm->listUpdates(); for (auto& pkg : pm->listInstalled()) {
pkg.provider = pm->getName();
results.push_back(pkg);
}
} else {
if (!pm->canUpdate()) continue;
for (auto& pkg : pm->listUpdates()) {
pkg.provider = pm->getName();
results.push_back(pkg);
}
}
} }
// One row per package name, whatever the number of providers offering it.
mergeProviderDuplicates(results);
emit finished(results); emit finished(results);
} }
InstallWorker::InstallWorker(IPackageManager* pm, Op op, const std::string& package) InstallWorker::InstallWorker(IPackageManager* pm, Op op, const std::string& package)
: m_pm(pm), m_op(op), m_package(package) {} : m_providers{pm}, m_op(op), m_package(package) {}
InstallWorker::InstallWorker(const std::vector<IPackageManager*>& providers, Op op)
: m_providers(providers), m_op(op) {}
void InstallWorker::run() { void InstallWorker::run() {
auto cb = [this](const std::string& msg) { bool success = true;
emit progress(QString::fromStdString(msg)); for (IPackageManager* pm : m_providers) {
}; // Prefix progress lines with the provider when several run at once.
auto cb = [this, pm](const std::string& msg) {
if (m_providers.size() > 1) {
emit progress(QString("[%1] %2")
.arg(QString::fromStdString(pm->getName()),
QString::fromStdString(msg)));
} else {
emit progress(QString::fromStdString(msg));
}
};
bool success = false; // Keep running the remaining providers even if one fails.
switch (m_op) { switch (m_op) {
case Op::Install: success = m_pm->install(m_package, cb); break; case Op::Install: success = pm->install(m_package, cb) && success; break;
case Op::Remove: success = m_pm->remove(m_package, cb); break; case Op::Remove: success = pm->remove(m_package, cb) && success; break;
case Op::Update: success = m_pm->update(m_package, cb); break; case Op::Update: success = pm->update(m_package, cb) && success; break;
case Op::UpdateAll: success = m_pm->update("", cb); break; case Op::UpdateAll: success = pm->update("", cb) && success; break;
case Op::Refresh: success = m_pm->refresh(cb); break; case Op::Refresh: success = pm->refresh(cb) && success; break;
}
} }
emit finished(success); emit finished(success);
} }
@@ -88,30 +129,59 @@ static QPixmap iconPixmap(const QString& name, int size) {
return loadIcon(name).pixmap(QSize(size, size)); return loadIcon(name).pixmap(QSize(size, size));
} }
// Display name of a provider id (e.g. "pacman" -> "Pacman"), falling back to
// the raw id for providers that are no longer registered.
static QString providerLabel(const PluginManager* pm, const std::string& id) {
for (const auto& entry : pm->providers()) {
if (entry.info.id == id) return QString::fromStdString(entry.info.name);
}
return QString::fromStdString(id);
}
// Comma-separated display names of every provider offering a package (used by
// the Fournisseur column and the details badge).
static QString providersLabel(const PluginManager* pm, const PackageInfo& pkg) {
QStringList names;
for (const auto& id : pkg.providers) {
names << providerLabel(pm, id);
}
if (names.isEmpty() && !pkg.provider.empty()) {
names << providerLabel(pm, pkg.provider);
}
return names.join(", ");
}
// MainWindow implementation // MainWindow implementation
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
// Workers emit std::vector<PackageInfo> from another thread (QThread::run); // Workers emit std::vector<PackageInfo> from another thread (QThread::run);
// without this registration the queued connection is dropped silently. // without this registration the queued connection is dropped silently.
qRegisterMetaType<std::vector<PackageInfo>>("std::vector<PackageInfo>"); qRegisterMetaType<std::vector<PackageInfo>>("std::vector<PackageInfo>");
m_pacman = new PacmanManager(); // Provider registry: pacman and flatpak ship with the application, extra
// providers can be added as plugins at runtime (see the Providers page).
m_pluginManager = new PluginManager();
m_pluginManager->registerBuiltin(
{"pacman", "Pacman", "1.0.0",
"Gestionnaire de paquets natif d'Arch Linux", "FWS"},
new PacmanManager());
// The install hint tells the app how to make the provider available when
// its tool is missing (flatpak is shipped by the pacman package "flatpak").
m_pluginManager->registerBuiltin(
{"flatpak", "Flatpak", "1.0.0",
"Gestionnaire d'applications Flatpak", "FWS", false, "", false, "flatpak"},
new FlatpakManager());
m_pluginManager->discoverExternal();
// Non-owning handle kept for sudo credential handling and pacman logs.
m_pacman = dynamic_cast<PacmanManager*>(m_pluginManager->managerFor("pacman"));
m_historyManager = new HistoryManager(); m_historyManager = new HistoryManager();
setupUI(); setupUI();
setupMenuBar(); setupMenuBar();
// With per-session credentials, ask for the sudo password once, right if (m_pluginManager->availableManagers().empty()) {
// after the window is shown (so the dialog has a visible parent). statusBar()->showMessage("Aucun gestionnaire de paquets disponible sur ce système.");
if (m_pacman->isAvailable()) {
QTimer::singleShot(0, this, [this]() {
if (m_credentialMode == CredentialMode::AtLaunch) {
ensureCredentials();
}
});
}
if (!m_pacman->isAvailable()) {
statusBar()->showMessage("pacman n'est pas disponible sur ce système.");
m_searchBar->setEnabled(false); m_searchBar->setEnabled(false);
m_searchButton->setEnabled(false); m_searchButton->setEnabled(false);
m_refreshButton->setEnabled(false); m_refreshButton->setEnabled(false);
@@ -120,12 +190,22 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
return; return;
} }
// With per-session credentials, ask for the sudo password once, right
// after the window is shown (so the dialog has a visible parent).
if (m_pacman && m_pacman->isAvailable()) {
QTimer::singleShot(0, this, [this]() {
if (m_credentialMode == CredentialMode::AtLaunch) {
ensureCredentials(m_pluginManager->availableManagers());
}
});
}
refreshDashboard(); refreshDashboard();
updateStatusBar(); updateStatusBar();
} }
MainWindow::~MainWindow() { MainWindow::~MainWindow() {
delete m_pacman; delete m_pluginManager; // owns every provider, built-in and external
delete m_historyManager; delete m_historyManager;
} }
@@ -153,6 +233,7 @@ void MainWindow::setupUI() {
setupBrowsePage(); setupBrowsePage();
setupHistoryPage(); setupHistoryPage();
setupLogsPage(); setupLogsPage();
setupProvidersPage();
contentLayout->addWidget(m_pages, 1); contentLayout->addWidget(m_pages, 1);
rootLayout->addWidget(content, 1); rootLayout->addWidget(content, 1);
@@ -380,6 +461,7 @@ void MainWindow::setupSidebar() {
layout->addSpacing(8); layout->addSpacing(8);
addNavButton(4, "history", "Historique", "Historique des actions"); addNavButton(4, "history", "Historique", "Historique des actions");
addNavButton(5, "logs", "Logs", "Logs pacman"); addNavButton(5, "logs", "Logs", "Logs pacman");
addNavButton(6, "plugin", "Providers", "Extensions de gestionnaires de paquets");
connect(m_navGroup, &QButtonGroup::idClicked, this, &MainWindow::onNavChanged); connect(m_navGroup, &QButtonGroup::idClicked, this, &MainWindow::onNavChanged);
m_navGroup->button(0)->setChecked(true); m_navGroup->button(0)->setChecked(true);
@@ -622,8 +704,9 @@ void MainWindow::setupBrowsePage() {
listHeader->setObjectName("cardTitle"); listHeader->setObjectName("cardTitle");
listLayout->addWidget(listHeader); listLayout->addWidget(listHeader);
m_packageTable = new QTableWidget(0, 4); m_packageTable = new QTableWidget(0, 5);
m_packageTable->setHorizontalHeaderLabels({"Nom", "Version", "Dépôt", "Statut"}); m_packageTable->setHorizontalHeaderLabels(
{"Nom", "Version", "Dépôt", "Fournisseur", "Statut"});
m_packageTable->verticalHeader()->setVisible(false); m_packageTable->verticalHeader()->setVisible(false);
m_packageTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_packageTable->setSelectionBehavior(QAbstractItemView::SelectRows);
m_packageTable->setSelectionMode(QAbstractItemView::SingleSelection); m_packageTable->setSelectionMode(QAbstractItemView::SingleSelection);
@@ -636,6 +719,7 @@ void MainWindow::setupBrowsePage() {
m_packageTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); m_packageTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
m_packageTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); m_packageTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
m_packageTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); m_packageTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
m_packageTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
connect(m_packageTable, &QTableWidget::currentCellChanged, this, connect(m_packageTable, &QTableWidget::currentCellChanged, this,
[this](int currentRow, int, int, int) { onPackageSelected(currentRow); }); [this](int currentRow, int, int, int) { onPackageSelected(currentRow); });
@@ -672,6 +756,12 @@ void MainWindow::setupBrowsePage() {
"padding: 3px 12px; font-size: 12px;"); "padding: 3px 12px; font-size: 12px;");
metaRow->addWidget(m_packageSize); metaRow->addWidget(m_packageSize);
m_packageProvider = new QLabel("—");
m_packageProvider->setStyleSheet(
"background: #1c2434; color: #7a8299; border-radius: 10px;"
"padding: 3px 12px; font-size: 12px;");
metaRow->addWidget(m_packageProvider);
// "Update available" badge with an SVG arrow + text. // "Update available" badge with an SVG arrow + text.
m_packageUpdateBadge = new QWidget(); m_packageUpdateBadge = new QWidget();
m_packageUpdateBadge->setStyleSheet("background: #3d2f0f; border-radius: 9px;"); m_packageUpdateBadge->setStyleSheet("background: #3d2f0f; border-radius: 9px;");
@@ -787,6 +877,91 @@ void MainWindow::setupLogsPage() {
m_pages->addWidget(page); m_pages->addWidget(page);
} }
// The Providers page acts as the add-on store: it lists every package manager
// known to the application (built-in and external plugins), lets the user
// enable/disable them, and rescans the plugin directories for new ones.
void MainWindow::setupProvidersPage() {
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("AJOUTER UN FOURNISSEUR");
hintTitle->setObjectName("cardTitle");
hintLayout->addWidget(hintTitle);
QLabel* hint = new QLabel(
"Pacman et Flatpak sont intégrés. Si un fournisseur est « Indisponible », "
"sélectionnez-le puis cliquez sur « Installer l'outil » pour l'installer "
"via pacman. Pour ajouter d'autres gestionnaires (apt, dnf, ...), compilez "
"un plugin partagé (voir plugins/example-provider) et déposez-le dans "
"~/.local/share/PacManager/plugins/ ou dans le dossier plugins/ à côté de "
"l'exécutable, puis cliquez sur « Recharger ».");
hint->setWordWrap(true);
hint->setStyleSheet("font-size: 12px; color: #7a8299;");
hintLayout->addWidget(hint);
layout->addWidget(hintCard);
m_providerTable = new QTableWidget(0, 5);
m_providerTable->setHorizontalHeaderLabels(
{"Fournisseur", "Type", "Version", "Auteur", "Statut"});
m_providerTable->verticalHeader()->setVisible(false);
m_providerTable->setSelectionBehavior(QAbstractItemView::SelectRows);
m_providerTable->setSelectionMode(QAbstractItemView::SingleSelection);
m_providerTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_providerTable->setShowGrid(false);
m_providerTable->setAlternatingRowColors(true);
m_providerTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
m_providerTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
m_providerTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
m_providerTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
m_providerTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
m_providerTable->verticalHeader()->setDefaultSectionSize(36);
connect(m_providerTable, &QTableWidget::currentCellChanged, this,
[this](int currentRow, int, int, int) { onProviderTableSelected(currentRow); });
layout->addWidget(m_providerTable, 1);
m_providerDescription = new QLabel("");
m_providerDescription->setWordWrap(true);
m_providerDescription->setStyleSheet(
"font-size: 13px; color: #c8d3f5; background: transparent; padding: 2px 4px;");
layout->addWidget(m_providerDescription);
QHBoxLayout* buttonBar = new QHBoxLayout();
buttonBar->addStretch();
// Installs the OS package backing a provider whose tool is missing
// (e.g. pacman -S flatpak), then rescans so it becomes available.
m_providerInstallButton = new QPushButton("Installer l'outil");
m_providerInstallButton->setProperty("variant", "primary");
m_providerInstallButton->setEnabled(false);
m_providerInstallButton->setVisible(false);
connect(m_providerInstallButton, &QPushButton::clicked,
this, &MainWindow::onInstallProviderTool);
buttonBar->addWidget(m_providerInstallButton);
m_providerToggleButton = new QPushButton("Activer");
m_providerToggleButton->setEnabled(false);
connect(m_providerToggleButton, &QPushButton::clicked, this, &MainWindow::onToggleProvider);
buttonBar->addWidget(m_providerToggleButton);
QPushButton* rescanButton = new QPushButton("Recharger");
rescanButton->setIcon(loadIcon("refresh"));
rescanButton->setToolTip("Rescanner les dossiers de plugins");
connect(rescanButton, &QPushButton::clicked, this, &MainWindow::onRescanProviders);
buttonBar->addWidget(rescanButton);
layout->addLayout(buttonBar);
m_pages->addWidget(page);
}
void MainWindow::setupMenuBar() { void MainWindow::setupMenuBar() {
QMenuBar* menuBar = this->menuBar(); QMenuBar* menuBar = this->menuBar();
menuBar->setStyleSheet( menuBar->setStyleSheet(
@@ -818,6 +993,7 @@ void MainWindow::setupMenuBar() {
toolsMenu->addAction("Mises à jour", this, [this]() { m_navGroup->button(3)->click(); }); toolsMenu->addAction("Mises à jour", this, [this]() { m_navGroup->button(3)->click(); });
toolsMenu->addAction("Historique", this, [this]() { m_navGroup->button(4)->click(); }); toolsMenu->addAction("Historique", this, [this]() { m_navGroup->button(4)->click(); });
toolsMenu->addAction("Logs pacman", this, [this]() { m_navGroup->button(5)->click(); }); toolsMenu->addAction("Logs pacman", this, [this]() { m_navGroup->button(5)->click(); });
toolsMenu->addAction("Providers", this, [this]() { m_navGroup->button(6)->click(); });
toolsMenu->addSeparator(); toolsMenu->addSeparator();
toolsMenu->addAction("Rafraîchir les sources", this, &MainWindow::onRefresh); toolsMenu->addAction("Rafraîchir les sources", this, &MainWindow::onRefresh);
@@ -866,20 +1042,29 @@ void MainWindow::applyCredentialMode(CredentialMode mode) {
if (mode == CredentialMode::EachTime) { if (mode == CredentialMode::EachTime) {
// Each operation must re-authenticate: never keep the password around. // Each operation must re-authenticate: never keep the password around.
m_pacman->clearPassword(); if (m_pacman) m_pacman->clearPassword();
statusBar()->showMessage("Identifiants demandés à chaque opération."); statusBar()->showMessage("Identifiants demandés à chaque opération.");
} else { } else {
// Per-session credentials: prompt once now so operations don't re-ask. // Per-session credentials: prompt once now so operations don't re-ask.
ensureCredentials(); ensureCredentials(m_pluginManager->availableManagers());
statusBar()->showMessage("Identifiants enregistrés pour la session."); statusBar()->showMessage("Identifiants enregistrés pour la session.");
} }
} }
// Makes sure a sudo password is available before a privileged operation, // Makes sure a sudo password is available before a privileged operation,
// prompting the user on the UI thread when needed. Returns false if the user // prompting the user on the UI thread when needed. Only providers that run
// through sudo (pacman) trigger the prompt. Returns false if the user
// cancelled, in which case the operation must not start. // cancelled, in which case the operation must not start.
bool MainWindow::ensureCredentials() { bool MainWindow::ensureCredentials(const std::vector<IPackageManager*>& providers) {
if (!m_pacman->isAvailable()) return false; bool needsPassword = false;
for (IPackageManager* pm : providers) {
if (pm && pm->requiresPassword()) {
needsPassword = true;
break;
}
}
if (!needsPassword) return true;
if (!m_pacman || !m_pacman->isAvailable()) return false;
if (system("which sudo > /dev/null 2>&1") != 0) { if (system("which sudo > /dev/null 2>&1") != 0) {
statusBar()->showMessage("sudo n'est pas installé sur ce système."); statusBar()->showMessage("sudo n'est pas installé sur ce système.");
return false; return false;
@@ -904,10 +1089,28 @@ bool MainWindow::ensureCredentials() {
return true; return true;
} }
// Manager owning a package: the one tagged in the package, or the first
// available provider when the tag is missing or unknown.
IPackageManager* MainWindow::providerFor(const std::string& id) const {
if (const auto* entry = m_pluginManager->findAvailable(id)) {
return entry->manager;
}
auto available = m_pluginManager->availableManagers();
return available.empty() ? nullptr : available.front();
}
void MainWindow::showProviderError(const QString& title, IPackageManager* provider) {
if (!provider) return;
std::string err = provider->lastError();
if (!err.empty()) {
QMessageBox::warning(this, title, QString::fromStdString(err));
}
}
void MainWindow::clearCredentialsAfterUse() { void MainWindow::clearCredentialsAfterUse() {
// In per-operation mode the password is single-use: drop it once the // In per-operation mode the password is single-use: drop it once the
// command ran so the next operation prompts again. // command ran so the next operation prompts again.
if (m_credentialMode == CredentialMode::EachTime) { if (m_credentialMode == CredentialMode::EachTime && m_pacman) {
m_pacman->clearPassword(); m_pacman->clearPassword();
} }
} }
@@ -968,6 +1171,10 @@ void MainWindow::updatePageTitle() {
m_headerTitle->setText("Logs pacman"); m_headerTitle->setText("Logs pacman");
m_headerSubtitle->setText("Journal brut du gestionnaire de paquets"); m_headerSubtitle->setText("Journal brut du gestionnaire de paquets");
break; break;
case 6:
m_headerTitle->setText("Providers");
m_headerSubtitle->setText("Gestionnaires de paquets et extensions");
break;
default: default:
break; break;
} }
@@ -1001,6 +1208,10 @@ void MainWindow::onNavChanged(int id) {
m_pages->setCurrentIndex(3); m_pages->setCurrentIndex(3);
loadLogs(); loadLogs();
break; break;
case 6:
m_pages->setCurrentIndex(4);
refreshProvidersTable();
break;
default: default:
break; break;
} }
@@ -1024,6 +1235,7 @@ void MainWindow::resetDetailsPanel() {
m_packageVersion->setText(""); m_packageVersion->setText("");
m_packageRepo->setText("—"); m_packageRepo->setText("—");
m_packageSize->setText("—"); m_packageSize->setText("—");
m_packageProvider->setText("—");
m_packageUpdateBadge->setVisible(false); m_packageUpdateBadge->setVisible(false);
m_packageDescription->setText(""); m_packageDescription->setText("");
m_installButton->setEnabled(false); m_installButton->setEnabled(false);
@@ -1032,8 +1244,9 @@ void MainWindow::resetDetailsPanel() {
} }
void MainWindow::onSearch() { void MainWindow::onSearch() {
if (!m_pacman->isAvailable()) { std::vector<IPackageManager*> providers = m_pluginManager->availableManagers();
statusBar()->showMessage("pacman n'est pas disponible."); if (providers.empty()) {
statusBar()->showMessage("Aucun gestionnaire de paquets disponible.");
return; return;
} }
@@ -1049,7 +1262,7 @@ void MainWindow::onSearch() {
statusBar()->showMessage("Recherche en cours..."); statusBar()->showMessage("Recherche en cours...");
m_packageTable->setRowCount(0); m_packageTable->setRowCount(0);
SearchWorker* worker = new SearchWorker(m_pacman, query); SearchWorker* worker = new SearchWorker(providers, query);
connect(worker, &SearchWorker::finished, this, &MainWindow::onSearchFinished); connect(worker, &SearchWorker::finished, this, &MainWindow::onSearchFinished);
connect(worker, &SearchWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); connect(worker, &SearchWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); });
worker->start(); worker->start();
@@ -1060,7 +1273,8 @@ void MainWindow::loadInstalled() {
statusBar()->showMessage("Chargement des paquets installés..."); statusBar()->showMessage("Chargement des paquets installés...");
m_packageTable->setRowCount(0); m_packageTable->setRowCount(0);
ListWorker* worker = new ListWorker(m_pacman, ListWorker::Installed); ListWorker* worker = new ListWorker(m_pluginManager->availableManagers(),
ListWorker::Installed);
connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished); connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished);
connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); });
worker->start(); worker->start();
@@ -1071,7 +1285,8 @@ void MainWindow::loadUpdates() {
statusBar()->showMessage("Recherche des mises à jour..."); statusBar()->showMessage("Recherche des mises à jour...");
m_packageTable->setRowCount(0); m_packageTable->setRowCount(0);
ListWorker* worker = new ListWorker(m_pacman, ListWorker::Updates); ListWorker* worker = new ListWorker(m_pluginManager->availableManagers(),
ListWorker::Updates);
connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished); connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished);
connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); });
worker->start(); worker->start();
@@ -1150,6 +1365,12 @@ void MainWindow::populatePackageTable(const std::vector<PackageInfo>& results) {
m_packageTable->setItem(i, 2, new QTableWidgetItem( m_packageTable->setItem(i, 2, new QTableWidgetItem(
pkg.repository.empty() ? "—" : QString::fromStdString(pkg.repository))); pkg.repository.empty() ? "—" : QString::fromStdString(pkg.repository)));
QTableWidgetItem* providerItem = new QTableWidgetItem(
providersLabel(m_pluginManager, pkg));
providerItem->setForeground(QColor("#98a0b3"));
providerItem->setIcon(loadIcon("package"));
m_packageTable->setItem(i, 3, providerItem);
QString statusText; QString statusText;
QString statusIcon; QString statusIcon;
QColor statusColor; QColor statusColor;
@@ -1174,7 +1395,7 @@ void MainWindow::populatePackageTable(const std::vector<PackageInfo>& results) {
QTableWidgetItem* statusItem = new QTableWidgetItem(statusText); QTableWidgetItem* statusItem = new QTableWidgetItem(statusText);
statusItem->setForeground(statusColor); statusItem->setForeground(statusColor);
if (!statusIcon.isEmpty()) statusItem->setIcon(loadIcon(statusIcon)); if (!statusIcon.isEmpty()) statusItem->setIcon(loadIcon(statusIcon));
m_packageTable->setItem(i, 3, statusItem); m_packageTable->setItem(i, 4, statusItem);
} }
m_resultCount->setText(QString("%1 paquet(s)").arg(results.size())); m_resultCount->setText(QString("%1 paquet(s)").arg(results.size()));
@@ -1209,13 +1430,18 @@ void MainWindow::onPackageSelected(int row) {
m_selectedPackage = m_currentResults[row]; m_selectedPackage = m_currentResults[row];
updatePackageInfo(m_selectedPackage); updatePackageInfo(m_selectedPackage);
IPackageManager* provider = providerFor(m_selectedPackage.provider);
m_installButton->setEnabled( m_installButton->setEnabled(
m_browseMode == ModeSearch m_browseMode == ModeSearch
&& m_pacman->canInstall() && !m_selectedPackage.installed); && provider && provider->canInstall()
&& !m_selectedPackage.installed);
m_removeButton->setEnabled( m_removeButton->setEnabled(
m_pacman->canRemove() && m_selectedPackage.installed); provider && provider->canRemove()
&& m_selectedPackage.installed);
m_updateButton->setEnabled( m_updateButton->setEnabled(
m_pacman->canUpdate() && m_selectedPackage.updateAvailable); provider && provider->canUpdate()
&& m_selectedPackage.updateAvailable);
} }
void MainWindow::updatePackageInfo(const PackageInfo& pkg) { void MainWindow::updatePackageInfo(const PackageInfo& pkg) {
@@ -1233,6 +1459,8 @@ void MainWindow::updatePackageInfo(const PackageInfo& pkg) {
m_packageSize->setText(pkg.size.empty() m_packageSize->setText(pkg.size.empty()
? "Taille : —" ? "Taille : —"
: QString("Taille : %1").arg(QString::fromStdString(pkg.size))); : QString("Taille : %1").arg(QString::fromStdString(pkg.size)));
m_packageProvider->setText(
QString("Fournisseur : %1").arg(providersLabel(m_pluginManager, pkg)));
m_packageUpdateBadge->setVisible(pkg.updateAvailable); m_packageUpdateBadge->setVisible(pkg.updateAvailable);
m_packageDescription->setText(QString::fromStdString(pkg.description)); m_packageDescription->setText(QString::fromStdString(pkg.description));
@@ -1250,25 +1478,29 @@ void MainWindow::onRemove() {
void MainWindow::onUpdate() { void MainWindow::onUpdate() {
if (m_selectedPackage.name.empty()) return; if (m_selectedPackage.name.empty()) return;
if (!ensureCredentials()) return;
IPackageManager* provider = providerFor(m_selectedPackage.provider);
if (!provider || !provider->canUpdate()) return;
if (!ensureCredentials({provider})) return;
setBusy(true); setBusy(true);
statusBar()->showMessage( statusBar()->showMessage(
QString("Mise à jour de %1...").arg(QString::fromStdString(m_selectedPackage.name))); QString("Mise à jour de %1...").arg(QString::fromStdString(m_selectedPackage.name)));
auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Update, m_selectedPackage.name); auto* worker = new InstallWorker(provider, InstallWorker::Op::Update, m_selectedPackage.name);
connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) {
statusBar()->showMessage(msg); statusBar()->showMessage(msg);
}); });
connect(worker, &InstallWorker::finished, this, [this](bool success) { connect(worker, &InstallWorker::finished, this, [this, provider](bool success) {
setBusy(false); setBusy(false);
if (success) { if (success) {
statusBar()->showMessage("Mise à jour terminée"); statusBar()->showMessage("Mise à jour terminée");
} else { } else {
statusBar()->showMessage("Échec de la mise à jour"); statusBar()->showMessage("Échec de la mise à jour");
showProviderError("Échec de la mise à jour", provider);
} }
m_historyManager->record({"", "update", m_selectedPackage.name, m_historyManager->record({"", "update", m_selectedPackage.name,
m_pacman->getName(), success}); provider->getName(), success});
clearCredentialsAfterUse(); clearCredentialsAfterUse();
reloadCurrentView(); reloadCurrentView();
}); });
@@ -1277,25 +1509,33 @@ void MainWindow::onUpdate() {
} }
void MainWindow::onUpdateAll() { void MainWindow::onUpdateAll() {
if (!m_pacman->isAvailable()) { std::vector<IPackageManager*> providers = m_pluginManager->availableManagers();
statusBar()->showMessage("pacman n'est pas disponible."); if (providers.empty()) {
statusBar()->showMessage("Aucun gestionnaire de paquets disponible.");
return; return;
} }
if (!ensureCredentials()) return; if (!ensureCredentials(providers)) return;
setBusy(true); setBusy(true);
statusBar()->showMessage("Mise à jour de tous les paquets..."); statusBar()->showMessage("Mise à jour de tous les paquets...");
auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::UpdateAll, ""); auto* worker = new InstallWorker(providers, InstallWorker::Op::UpdateAll);
connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) {
statusBar()->showMessage(msg); statusBar()->showMessage(msg);
}); });
connect(worker, &InstallWorker::finished, this, [this](bool success) { connect(worker, &InstallWorker::finished, this, [this, providers](bool success) {
setBusy(false); setBusy(false);
if (success) { if (success) {
statusBar()->showMessage("Tous les paquets sont à jour"); statusBar()->showMessage("Tous les paquets sont à jour");
} else { } else {
statusBar()->showMessage("Erreur lors de la mise à jour globale"); statusBar()->showMessage("Erreur lors de la mise à jour globale");
for (IPackageManager* pm : providers) {
if (!pm->lastError().empty()) {
QMessageBox::warning(this, "Erreur lors de la mise à jour globale",
QString::fromStdString(pm->lastError()));
break;
}
}
} }
clearCredentialsAfterUse(); clearCredentialsAfterUse();
reloadCurrentView(); reloadCurrentView();
@@ -1306,25 +1546,33 @@ void MainWindow::onUpdateAll() {
} }
void MainWindow::onRefresh() { void MainWindow::onRefresh() {
if (!m_pacman->isAvailable()) { std::vector<IPackageManager*> providers = m_pluginManager->availableManagers();
statusBar()->showMessage("pacman n'est pas disponible."); if (providers.empty()) {
statusBar()->showMessage("Aucun gestionnaire de paquets disponible.");
return; return;
} }
if (!ensureCredentials()) return; if (!ensureCredentials(providers)) return;
setBusy(true); setBusy(true);
statusBar()->showMessage("Rafraîchissement des sources..."); statusBar()->showMessage("Rafraîchissement des sources...");
auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Refresh, ""); auto* worker = new InstallWorker(providers, InstallWorker::Op::Refresh);
connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) {
statusBar()->showMessage(msg); statusBar()->showMessage(msg);
}); });
connect(worker, &InstallWorker::finished, this, [this](bool success) { connect(worker, &InstallWorker::finished, this, [this, providers](bool success) {
setBusy(false); setBusy(false);
if (success) { if (success) {
statusBar()->showMessage("Sources rafraîchies"); statusBar()->showMessage("Sources rafraîchies");
} else { } else {
statusBar()->showMessage("Erreur lors du rafraîchissement"); statusBar()->showMessage("Erreur lors du rafraîchissement");
for (IPackageManager* pm : providers) {
if (!pm->lastError().empty()) {
QMessageBox::warning(this, "Erreur lors du rafraîchissement",
QString::fromStdString(pm->lastError()));
break;
}
}
} }
clearCredentialsAfterUse(); clearCredentialsAfterUse();
refreshDashboard(); refreshDashboard();
@@ -1334,17 +1582,19 @@ void MainWindow::onRefresh() {
} }
void MainWindow::performInstall(const std::string& package) { void MainWindow::performInstall(const std::string& package) {
if (!ensureCredentials()) return; IPackageManager* provider = providerFor(m_selectedPackage.provider);
if (!provider || !provider->canInstall()) return;
if (!ensureCredentials({provider})) return;
setBusy(true); setBusy(true);
statusBar()->showMessage( statusBar()->showMessage(
QString("Installation de %1...").arg(QString::fromStdString(package))); QString("Installation de %1...").arg(QString::fromStdString(package)));
auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Install, package); auto* worker = new InstallWorker(provider, InstallWorker::Op::Install, package);
connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) {
statusBar()->showMessage(msg); statusBar()->showMessage(msg);
}); });
connect(worker, &InstallWorker::finished, this, [this](bool success) { connect(worker, &InstallWorker::finished, this, [this, provider](bool success) {
setBusy(false); setBusy(false);
if (success) { if (success) {
statusBar()->showMessage( statusBar()->showMessage(
@@ -1354,9 +1604,10 @@ void MainWindow::performInstall(const std::string& package) {
statusBar()->showMessage( statusBar()->showMessage(
QString("Échec de l'installation de %1").arg( QString("Échec de l'installation de %1").arg(
QString::fromStdString(m_selectedPackage.name))); QString::fromStdString(m_selectedPackage.name)));
showProviderError("Échec de l'installation", provider);
} }
m_historyManager->record({"", "install", m_selectedPackage.name, m_historyManager->record({"", "install", m_selectedPackage.name,
m_pacman->getName(), success}); provider->getName(), success});
clearCredentialsAfterUse(); clearCredentialsAfterUse();
reloadCurrentView(); reloadCurrentView();
refreshDashboard(); refreshDashboard();
@@ -1366,17 +1617,19 @@ void MainWindow::performInstall(const std::string& package) {
} }
void MainWindow::performRemove(const std::string& package) { void MainWindow::performRemove(const std::string& package) {
if (!ensureCredentials()) return; IPackageManager* provider = providerFor(m_selectedPackage.provider);
if (!provider || !provider->canRemove()) return;
if (!ensureCredentials({provider})) return;
setBusy(true); setBusy(true);
statusBar()->showMessage( statusBar()->showMessage(
QString("Suppression de %1...").arg(QString::fromStdString(package))); QString("Suppression de %1...").arg(QString::fromStdString(package)));
auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Remove, package); auto* worker = new InstallWorker(provider, InstallWorker::Op::Remove, package);
connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) {
statusBar()->showMessage(msg); statusBar()->showMessage(msg);
}); });
connect(worker, &InstallWorker::finished, this, [this](bool success) { connect(worker, &InstallWorker::finished, this, [this, provider](bool success) {
setBusy(false); setBusy(false);
if (success) { if (success) {
statusBar()->showMessage( statusBar()->showMessage(
@@ -1386,9 +1639,10 @@ void MainWindow::performRemove(const std::string& package) {
statusBar()->showMessage( statusBar()->showMessage(
QString("Échec de la suppression de %1").arg( QString("Échec de la suppression de %1").arg(
QString::fromStdString(m_selectedPackage.name))); QString::fromStdString(m_selectedPackage.name)));
showProviderError("Échec de la suppression", provider);
} }
m_historyManager->record({"", "remove", m_selectedPackage.name, m_historyManager->record({"", "remove", m_selectedPackage.name,
m_pacman->getName(), success}); provider->getName(), success});
clearCredentialsAfterUse(); clearCredentialsAfterUse();
reloadCurrentView(); reloadCurrentView();
refreshDashboard(); refreshDashboard();
@@ -1493,7 +1747,8 @@ void MainWindow::onRefreshLogs() {
} }
void MainWindow::refreshDashboard() { void MainWindow::refreshDashboard() {
if (!m_pacman->isAvailable()) { std::vector<IPackageManager*> providers = m_pluginManager->availableManagers();
if (providers.empty()) {
m_statInstalled->setText("—"); m_statInstalled->setText("—");
m_statUpdates->setText("—"); m_statUpdates->setText("—");
m_statManager->setText("indisponible"); m_statManager->setText("indisponible");
@@ -1502,19 +1757,22 @@ void MainWindow::refreshDashboard() {
} }
m_statHistory->setText(QString::number(m_historyManager->getHistory().size())); m_statHistory->setText(QString::number(m_historyManager->getHistory().size()));
m_statManager->setText(QString("%1 %2")
.arg(QString::fromStdString(m_pacman->getName()), QStringList names;
QString::fromStdString(m_pacman->getVersion()))); for (IPackageManager* pm : providers) {
names << QString::fromStdString(pm->getName());
}
m_statManager->setText(names.join(", "));
refreshRecentActivity(); refreshRecentActivity();
auto* inst = new ListWorker(m_pacman, ListWorker::Installed); auto* inst = new ListWorker(providers, ListWorker::Installed);
connect(inst, &ListWorker::finished, this, [this](std::vector<PackageInfo> r) { connect(inst, &ListWorker::finished, this, [this](std::vector<PackageInfo> r) {
m_statInstalled->setText(QString::number(r.size())); m_statInstalled->setText(QString::number(r.size()));
}); });
connect(inst, &ListWorker::finished, this, [inst] { inst->wait(); inst->deleteLater(); }); connect(inst, &ListWorker::finished, this, [inst] { inst->wait(); inst->deleteLater(); });
inst->start(); inst->start();
auto* upd = new ListWorker(m_pacman, ListWorker::Updates); auto* upd = new ListWorker(providers, ListWorker::Updates);
connect(upd, &ListWorker::finished, this, [this](std::vector<PackageInfo> r) { connect(upd, &ListWorker::finished, this, [this](std::vector<PackageInfo> r) {
m_statUpdates->setText(QString::number(r.size())); m_statUpdates->setText(QString::number(r.size()));
m_statUpdates->setStyleSheet(r.empty() m_statUpdates->setStyleSheet(r.empty()
@@ -1586,10 +1844,178 @@ void MainWindow::refreshRecentActivity() {
} }
void MainWindow::updateStatusBar() { void MainWindow::updateStatusBar() {
QString info = QString("%1 %2 | Paquets affichés : %3 | Actions enregistrées : %4") std::vector<IPackageManager*> providers = m_pluginManager->availableManagers();
.arg(QString::fromStdString(m_pacman->getName()), if (providers.empty()) {
QString::fromStdString(m_pacman->getVersion())) statusBar()->showMessage("Aucun gestionnaire de paquets disponible.");
return;
}
QString info = QString("%1 fournisseur(s) actif(s) | Paquets affichés : %2 | Actions enregistrées : %3")
.arg(providers.size())
.arg(m_currentResults.size()) .arg(m_currentResults.size())
.arg(m_historyManager->getHistory().size()); .arg(m_historyManager->getHistory().size());
statusBar()->showMessage(info); statusBar()->showMessage(info);
} }
void MainWindow::onProviderTableSelected(int row) {
if (row < 0 || row >= static_cast<int>(m_pluginManager->providers().size())) {
m_providerToggleButton->setEnabled(false);
m_providerInstallButton->setVisible(false);
m_providerDescription->clear();
return;
}
const auto& entry = m_pluginManager->providers()[row];
m_selectedProviderId = entry.info.id;
m_providerDescription->setText(QString::fromStdString(entry.info.description));
bool toggleable = entry.info.available;
m_providerToggleButton->setEnabled(toggleable);
m_providerToggleButton->setToolTip(
toggleable ? QString()
: QString("Outil « %1 » non détecté sur ce système.")
.arg(QString::fromStdString(entry.info.name)));
m_providerToggleButton->setText(
m_pluginManager->isEnabled(entry.info.id) ? "Désactiver" : "Activer");
// Offer to install the backing tool (e.g. flatpak via pacman) when it is
// missing and we know which OS package provides it.
bool installable = !entry.info.available && !entry.info.installHint.empty()
&& m_pacman && m_pacman->isAvailable();
m_providerInstallButton->setVisible(!entry.info.available);
m_providerInstallButton->setEnabled(installable);
m_providerInstallButton->setToolTip(
installable
? QString("sudo pacman -S %1").arg(QString::fromStdString(entry.info.installHint))
: QString());
}
// Installs the OS package backing the selected provider through pacman, then
// re-checks availability so the provider can be used right away.
void MainWindow::onInstallProviderTool() {
if (m_selectedProviderId.empty()) return;
if (!m_pacman || !m_pacman->isAvailable()) {
statusBar()->showMessage("pacman est requis pour installer l'outil.");
return;
}
const std::string id = m_selectedProviderId;
std::string installHint;
for (const auto& entry : m_pluginManager->providers()) {
if (entry.info.id == id) {
installHint = entry.info.installHint;
break;
}
}
if (installHint.empty()) return;
if (!ensureCredentials({m_pacman})) return;
setBusy(true);
statusBar()->showMessage(
QString("Installation de l'outil %1...").arg(QString::fromStdString(installHint)));
auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Install, installHint);
connect(worker, &InstallWorker::progress, this, [this](const QString& msg) {
statusBar()->showMessage(msg);
});
connect(worker, &InstallWorker::finished, this, [this, id](bool success) {
setBusy(false);
clearCredentialsAfterUse();
if (!success) {
statusBar()->showMessage("Échec de l'installation de l'outil.");
return;
}
m_pluginManager->refreshAvailability();
refreshProvidersTable();
refreshDashboard();
statusBar()->showMessage("Outil installé, fournisseur disponible.");
});
connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); });
worker->start();
}
void MainWindow::onToggleProvider() {
if (m_selectedProviderId.empty()) return;
bool enabled = !m_pluginManager->isEnabled(m_selectedProviderId);
m_pluginManager->setEnabled(m_selectedProviderId, enabled);
refreshProvidersTable();
refreshDashboard();
reloadCurrentView();
}
void MainWindow::onRescanProviders() {
m_pluginManager->reload();
refreshProvidersTable();
refreshDashboard();
reloadCurrentView();
statusBar()->showMessage("Plugins rechargés.");
}
void MainWindow::refreshProvidersTable() {
const auto& providers = m_pluginManager->providers();
m_providerTable->setRowCount(0);
m_providerTable->setRowCount(static_cast<int>(providers.size()));
QFont nameFont;
nameFont.setWeight(QFont::DemiBold);
for (int i = 0; i < static_cast<int>(providers.size()); ++i) {
const auto& entry = providers[i];
QTableWidgetItem* nameItem =
new QTableWidgetItem(QString::fromStdString(entry.info.name));
nameItem->setFont(nameFont);
nameItem->setData(Qt::UserRole, QString::fromStdString(entry.info.id));
m_providerTable->setItem(i, 0, nameItem);
QString typeText = entry.info.builtin ? "Intégré" : "Externe";
QTableWidgetItem* typeItem = new QTableWidgetItem(typeText);
typeItem->setForeground(QColor("#7a8299"));
m_providerTable->setItem(i, 1, typeItem);
m_providerTable->setItem(i, 2,
new QTableWidgetItem(QString::fromStdString(entry.info.version)));
m_providerTable->setItem(i, 3,
new QTableWidgetItem(QString::fromStdString(entry.info.author)));
QString statusText;
QColor statusColor;
if (!entry.info.available) {
statusText = "Indisponible";
statusColor = QColor("#565f73");
} else if (m_pluginManager->isEnabled(entry.info.id)) {
statusText = "Actif";
statusColor = QColor("#3fb950");
} else {
statusText = "Désactivé";
statusColor = QColor("#e0af68");
}
QTableWidgetItem* statusItem = new QTableWidgetItem(statusText);
statusItem->setForeground(statusColor);
statusItem->setIcon(loadIcon(
entry.info.available ? (m_pluginManager->isEnabled(entry.info.id) ? "check" : "close")
: "alert"));
m_providerTable->setItem(i, 4, statusItem);
}
if (!providers.empty()) {
// Keep the previously selected provider selected when possible.
int row = 0;
for (int i = 0; i < static_cast<int>(providers.size()); ++i) {
if (providers[i].info.id == m_selectedProviderId) {
row = i;
break;
}
}
m_providerTable->selectRow(row);
onProviderTableSelected(row);
} else {
m_providerToggleButton->setEnabled(false);
m_providerInstallButton->setVisible(false);
m_providerDescription->clear();
}
}
+188
View File
@@ -0,0 +1,188 @@
#include "plugin-manager.h"
#include <QDir>
#include <QFileInfo>
#include <QCoreApplication>
// Plugin directories, checked in order. Bundled plugins ship next to the
// executable; user plugins live under the standard data directory so they
// survive application updates.
static QStringList pluginSearchPaths() {
QStringList paths;
paths << QCoreApplication::applicationDirPath() + "/plugins";
paths << QDir::homePath() + "/.local/share/PacManager/plugins";
return paths;
}
PluginManager::PluginManager() = default;
PluginManager::~PluginManager() {
// Delete managers first (they may run code), then unload the libraries
// they were compiled into.
for (auto& entry : m_providers) {
delete entry.manager;
delete entry.library;
}
}
void PluginManager::registerBuiltin(ProviderInfo info, IPackageManager* manager) {
info.builtin = true;
info.available = manager->isAvailable();
m_providers.push_back({std::move(info), manager, nullptr});
}
// Load a single shared library as a provider plugin. Returns false (without
// erroring) when the file is not a provider plugin, so unrelated libraries in
// the directory are skipped.
bool PluginManager::loadPluginFile(const QString& filePath) {
typedef const char* (*MetaFn)();
typedef IPackageManager* (*CreateFn)();
// Own the library for the lifetime of the provider: it must stay loaded
// as long as the manager instance created from it exists.
QLibrary* library = new QLibrary(filePath);
if (!library->load()) {
delete library;
return false;
}
MetaFn idFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_id"));
MetaFn nameFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_name"));
MetaFn versionFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_version"));
MetaFn descFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_description"));
MetaFn authorFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_author"));
CreateFn createFn = reinterpret_cast<CreateFn>(library->resolve("fws_create_provider"));
// Optional: only present when the plugin declares an install hint.
MetaFn installHintFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_install_hint"));
if (!idFn || !nameFn || !versionFn || !descFn || !authorFn || !createFn) {
library->unload();
delete library;
return false;
}
// Reject plugins whose id collides with an already registered provider.
const std::string id = idFn();
for (const auto& entry : m_providers) {
if (entry.info.id == id) {
library->unload();
delete library;
return false;
}
}
ProviderInfo info;
info.id = id;
info.name = nameFn();
info.version = versionFn();
info.description = descFn();
info.author = authorFn();
info.path = filePath.toStdString();
if (installHintFn && installHintFn() && *installHintFn()) {
info.installHint = installHintFn();
}
IPackageManager* manager = createFn();
info.available = manager->isAvailable();
m_providers.push_back({std::move(info), manager, library});
return true;
}
void PluginManager::scanDirectory(const QString& dir) {
QDir directory(dir);
if (!directory.exists()) return;
const QStringList filters = {
#ifdef Q_OS_WIN
"*.dll"
#elif defined(Q_OS_MACOS)
"*.dylib"
#else
"*.so"
#endif
};
const QStringList files = directory.entryList(filters, QDir::Files);
for (const QString& file : files) {
loadPluginFile(directory.absoluteFilePath(file));
}
}
void PluginManager::unloadExternal() {
for (auto it = m_providers.begin(); it != m_providers.end();) {
if (!it->info.builtin) {
delete it->manager;
delete it->library;
it = m_providers.erase(it);
} else {
++it;
}
}
}
void PluginManager::discoverExternal() {
for (const QString& dir : pluginSearchPaths()) {
scanDirectory(dir);
}
}
void PluginManager::reload() {
unloadExternal();
discoverExternal();
}
void PluginManager::refreshAvailability() {
for (auto& entry : m_providers) {
entry.info.available = entry.manager->isAvailable();
}
}
const std::vector<PluginManager::ProviderEntry>& PluginManager::providers() const {
return m_providers;
}
std::vector<const PluginManager::ProviderEntry*> PluginManager::availableProviders() const {
std::vector<const ProviderEntry*> result;
for (const auto& entry : m_providers) {
if (entry.info.available && isEnabled(entry.info.id)) {
result.push_back(&entry);
}
}
return result;
}
std::vector<IPackageManager*> PluginManager::availableManagers() const {
std::vector<IPackageManager*> result;
for (const auto& entry : m_providers) {
if (entry.info.available && isEnabled(entry.info.id)) {
result.push_back(entry.manager);
}
}
return result;
}
const PluginManager::ProviderEntry* PluginManager::findAvailable(const std::string& id) const {
for (const auto& entry : m_providers) {
if (entry.info.id == id && entry.info.available && isEnabled(entry.info.id)) {
return &entry;
}
}
return nullptr;
}
bool PluginManager::isEnabled(const std::string& id) const {
return m_settings.value(QString("plugins/%1/enabled").arg(QString::fromStdString(id)),
true).toBool();
}
void PluginManager::setEnabled(const std::string& id, bool enabled) {
m_settings.setValue(QString("plugins/%1/enabled").arg(QString::fromStdString(id)), enabled);
}
IPackageManager* PluginManager::managerFor(const std::string& id) const {
for (const auto& entry : m_providers) {
if (entry.info.id == id) return entry.manager;
}
return nullptr;
}
+123
View File
@@ -0,0 +1,123 @@
#include "flatpak-manager.h"
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
// Real end-to-end exercise of the Flatpak provider against the live `flatpak`
// CLI: install a small app, verify it is listed and marked as installed in
// search, run update/refresh, then uninstall. It validates the exact commands
// the application runs (install fallbacks included) instead of only parsing.
//
// Skipped (with a message) when the flatpak binary is not available so the
// suite stays green on systems without it.
//
// The test is non-destructive for pre-existing installs: if the app is already
// present when the test starts it is left in place, only verified and updated.
namespace {
const std::string kApp = "org.gnome.Calculator";
bool isInstalled(FlatpakManager& fm) {
for (const auto& pkg : fm.listInstalled()) {
if (pkg.name == kApp) return true;
}
return false;
}
fs::path desktopLink() {
const char* home = std::getenv("HOME");
return fs::path(home ? home : "/tmp") / ".local/share/applications" / (kApp + ".desktop");
}
} // namespace
int main() {
if (system("which flatpak > /dev/null 2>&1") != 0) {
std::cout << "flatpak not installed, skipping integration test" << std::endl;
return 0;
}
FlatpakManager fm;
const bool preinstalled = isInstalled(fm);
// 1. Install through the provider's own logic (remote-add + fallbacks).
if (!fm.install(kApp, nullptr)) {
std::cout << "FAIL install: " << fm.lastError() << std::endl;
return 1;
}
if (!isInstalled(fm)) {
std::cout << "FAIL install: app not listed as installed" << std::endl;
return 1;
}
// 1b. The app must be linked into the user's standard applications dir so it
// appears in any desktop launcher (the pacman-like integration).
if (fs::is_symlink(desktopLink())) {
std::cout << "OK desktop integration present" << std::endl;
} else {
std::cout << "FAIL install: no .desktop link in ~/.local/share/applications" << std::endl;
return 1;
}
// 2. Updating the single app and all apps must complete without error.
if (!fm.update(kApp, nullptr)) {
std::cout << "FAIL update(app): " << fm.lastError() << std::endl;
return 1;
}
if (!fm.update("", nullptr)) {
std::cout << "FAIL update(all): " << fm.lastError() << std::endl;
return 1;
}
// 3. Refreshing the appstream metadata must complete without error.
if (!fm.refresh(nullptr)) {
std::cout << "FAIL refresh: " << fm.lastError() << std::endl;
return 1;
}
// 4. Search must find the app and report it as installed (not "Disponible").
bool searchFound = false;
for (const auto& pkg : fm.search("calculator")) {
if (pkg.name == kApp) {
searchFound = true;
if (!pkg.installed) {
std::cout << "FAIL search: app not flagged as installed" << std::endl;
return 1;
}
}
}
if (!searchFound) {
std::cout << "FAIL search: app not found in results" << std::endl;
return 1;
}
// 5. Uninstall, unless the app was already there before the test started.
if (!preinstalled) {
if (!fm.remove(kApp, nullptr)) {
std::cout << "FAIL remove: " << fm.lastError() << std::endl;
return 1;
}
if (isInstalled(fm)) {
std::cout << "FAIL remove: app still listed as installed" << std::endl;
return 1;
}
if (fs::is_symlink(desktopLink())) {
std::cout << "FAIL remove: desktop link not removed" << std::endl;
return 1;
} else {
std::cout << "OK desktop integration removed" << std::endl;
}
} else {
// Pre-existing app: verify the launcher link exists (integration ran).
if (!fs::is_symlink(desktopLink())) {
std::cout << "OK desktop integration ensured for preinstalled app" << std::endl;
}
}
std::cout << "All flatpak integration tests passed." << std::endl;
return 0;
}
+102
View File
@@ -0,0 +1,102 @@
#include "flatpak-manager.h"
#include <cassert>
#include <iostream>
static void testParseSearchOutput_parsesAlignedRows() {
std::string output =
"Name Description Application ID Version Branch Remotes\n"
"Firefox Fast and privacy-aware browser org.mozilla.firefox 128.0.2 stable flathub\n"
"Calculator Simple calculator org.gnome.Calculator 46.0 stable flathub\n";
auto pkgs = FlatpakManager::parseSearchOutput(output);
assert(pkgs.size() == 2);
assert(pkgs[0].name == "org.mozilla.firefox");
assert(pkgs[0].version == "128.0.2");
assert(pkgs[0].repository == "flathub");
// The display name is prefixed to the description.
assert(pkgs[0].description == "Firefox — Fast and privacy-aware browser");
assert(pkgs[1].name == "org.gnome.Calculator");
}
static void testParseSearchOutput_keepsMultiWordDescriptions() {
std::string output =
"Name Description Application ID Version Branch Remotes\n"
"Spotify Desktop music player with sync org.spotify.Client 1.2.3 stable flathub\n";
auto pkgs = FlatpakManager::parseSearchOutput(output);
assert(pkgs.size() == 1);
assert(pkgs[0].name == "org.spotify.Client");
assert(pkgs[0].description == "Spotify — Desktop music player with sync");
}
static void testParseSearchOutput_ignoresVersionLikeTokens() {
// Versions such as 128.0.2 must not be mistaken for an application ID.
std::string output =
"Name Description Application ID Version Branch Remotes\n"
"GIMP Image editor org.gimp.GIMP 2.10.36 stable flathub\n";
auto pkgs = FlatpakManager::parseSearchOutput(output);
assert(pkgs.size() == 1);
assert(pkgs[0].name == "org.gimp.GIMP");
assert(pkgs[0].version == "2.10.36");
}
static void testParseSearchOutput_emptyInput() {
assert(FlatpakManager::parseSearchOutput("").empty());
}
static void testParseInstalledOutput_parsesTabSeparated() {
std::string output =
"org.mozilla.firefox\t128.0.2\tflathub\n"
"org.gnome.Calculator\t46.0\tflathub\n";
auto pkgs = FlatpakManager::parseInstalledOutput(output);
assert(pkgs.size() == 2);
assert(pkgs[0].name == "org.mozilla.firefox");
assert(pkgs[0].version == "128.0.2");
assert(pkgs[0].repository == "flathub");
assert(pkgs[0].installed);
assert(!pkgs[0].updateAvailable);
}
static void testParseInstalledOutput_emptyInput() {
assert(FlatpakManager::parseInstalledOutput("").empty());
}
static void testParseUpdatesOutput_parsesRows() {
std::string output =
"org.mozilla.firefox\t130.0\n"
"org.gnome.Calculator\t47.0\n";
auto pkgs = FlatpakManager::parseUpdatesOutput(output);
assert(pkgs.size() == 2);
assert(pkgs[0].name == "org.mozilla.firefox");
assert(pkgs[0].version == "130.0");
assert(pkgs[0].installed);
assert(pkgs[0].updateAvailable);
}
static void testParseUpdatesOutput_emptyInput() {
assert(FlatpakManager::parseUpdatesOutput("").empty());
}
int main() {
testParseSearchOutput_parsesAlignedRows();
testParseSearchOutput_keepsMultiWordDescriptions();
testParseSearchOutput_ignoresVersionLikeTokens();
testParseSearchOutput_emptyInput();
testParseInstalledOutput_parsesTabSeparated();
testParseInstalledOutput_emptyInput();
testParseUpdatesOutput_parsesRows();
testParseUpdatesOutput_emptyInput();
std::cout << "All flatpak-manager tests passed." << std::endl;
return 0;
}
+125
View File
@@ -0,0 +1,125 @@
#include "package-manager.h"
#include <cassert>
#include <iostream>
static PackageInfo pkg(const std::string& name, const std::string& provider,
bool installed = false, bool update = false) {
PackageInfo p;
p.name = name;
p.provider = provider;
p.installed = installed;
p.updateAvailable = update;
return p;
}
static void testMerge_keepsSingleProviderRows() {
std::vector<PackageInfo> v = {
pkg("firefox", "pacman"), pkg("vim", "pacman"), pkg("vlc", "flatpak")};
mergeProviderDuplicates(v);
assert(v.size() == 3);
assert(v[0].providers.size() == 1 && v[0].providers[0] == "pacman");
}
static void testMerge_combinesDuplicateProviders() {
std::vector<PackageInfo> v = {
pkg("firefox", "pacman", /*installed=*/true),
pkg("firefox", "flatpak", /*installed=*/false, /*update=*/true),
};
mergeProviderDuplicates(v);
assert(v.size() == 1);
// First provider wins as the routing default; both are listed for display.
assert(v[0].provider == "pacman");
assert(v[0].providers.size() == 2);
assert(v[0].providers[0] == "pacman");
assert(v[0].providers[1] == "flatpak");
// Statuses are OR-ed across providers.
assert(v[0].installed);
assert(v[0].updateAvailable);
}
static void testMerge_mergesNonAdjacentDuplicates() {
std::vector<PackageInfo> v = {
pkg("vim", "pacman"), pkg("firefox", "pacman"), pkg("vim", "flatpak")};
mergeProviderDuplicates(v);
assert(v.size() == 2);
assert(v[0].name == "vim" && v[0].providers.size() == 2);
assert(v[1].name == "firefox" && v[1].providers.size() == 1);
}
static void testMerge_dedupesSameProviderTwice() {
std::vector<PackageInfo> v = {
pkg("firefox", "pacman"), pkg("firefox", "flatpak"), pkg("firefox", "flatpak")};
mergeProviderDuplicates(v);
assert(v.size() == 1);
assert(v[0].providers.size() == 2); // no repeated "flatpak"
}
static void testMerge_emptyInput() {
std::vector<PackageInfo> v;
mergeProviderDuplicates(v);
assert(v.empty());
}
static void testSort_groupsByProviderThenName() {
std::vector<PackageInfo> v = {
pkg("vim", "pacman"),
pkg("org.mozilla.firefox", "flatpak"),
pkg("firefox", "pacman"),
pkg("blender", "flatpak"),
};
sortByProviderThenName(v, {"pacman", "flatpak"});
assert(v.size() == 4);
assert(v[0].name == "firefox" && v[0].provider == "pacman");
assert(v[1].name == "vim" && v[1].provider == "pacman");
assert(v[2].name == "blender" && v[2].provider == "flatpak");
assert(v[3].name == "org.mozilla.firefox" && v[3].provider == "flatpak");
}
static void testSort_caseInsensitiveNames() {
std::vector<PackageInfo> v = {
pkg("Zsh", "pacman"),
pkg("abc", "pacman"),
};
sortByProviderThenName(v, {"pacman"});
assert(v[0].name == "abc");
assert(v[1].name == "Zsh");
}
static void testSort_unknownProvidersSortById() {
std::vector<PackageInfo> v = {
pkg("beta", "plugin-x"),
pkg("alpha", "plugin-y"),
};
sortByProviderThenName(v); // no provider order given
assert(v[0].name == "alpha");
assert(v[1].name == "beta");
}
int main() {
testMerge_keepsSingleProviderRows();
testMerge_combinesDuplicateProviders();
testMerge_mergesNonAdjacentDuplicates();
testMerge_dedupesSameProviderTwice();
testMerge_emptyInput();
testSort_groupsByProviderThenName();
testSort_caseInsensitiveNames();
testSort_unknownProvidersSortById();
std::cout << "All package-utils tests passed." << std::endl;
return 0;
}
+74
View File
@@ -0,0 +1,74 @@
#include "plugin-manager.h"
#include "pacman-manager.h"
#include "flatpak-manager.h"
#include <QCoreApplication>
#include <cassert>
#include <iostream>
// Exercises PluginManager end-to-end: built-in registration plus runtime
// discovery of the example plugin (built into build/plugins by CMake when
// FWS_BUILD_EXAMPLE_PLUGIN=ON).
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
app.setOrganizationName("Freebuff");
app.setApplicationName("PacManager");
PluginManager pm;
pm.registerBuiltin({"pacman", "Pacman", "1.0.0", "Natif Arch Linux", "FWS"},
new PacmanManager());
// Flatpak ships an install hint so the app can offer to install the tool
// (pacman -S flatpak) when it is missing on the system.
pm.registerBuiltin({"flatpak", "Flatpak", "1.0.0", "Flatpak", "FWS",
false, "", false, "flatpak"},
new FlatpakManager());
pm.discoverExternal();
// Built-ins + the sample plugin dropped next to the test binary.
assert(pm.providers().size() == 3);
// Install hints are exposed per provider; the sample plugin omits its
// optional hint symbol, which must read back as empty.
const auto& providers = pm.providers();
for (const auto& entry : providers) {
if (entry.info.id == "flatpak") assert(entry.info.installHint == "flatpak");
if (entry.info.id == "sample") assert(entry.info.installHint.empty());
}
assert(pm.findAvailable("flatpak") != nullptr);
// External plugin metadata is exposed through the C ABI.
const auto* sample = pm.findAvailable("sample");
assert(sample != nullptr);
assert(sample->info.name == "Sample Provider");
assert(sample->info.version == "0.1.0");
assert(sample->info.author == "FWS");
assert(!sample->info.builtin);
assert(sample->manager != nullptr);
assert(sample->manager->getName() == "sample");
assert(sample->manager->isAvailable());
// Manager lookup works by id.
IPackageManager* pacman = pm.managerFor("pacman");
assert(pacman != nullptr);
assert(pacman->getName() == "pacman");
// Enable/disable is persisted and filters the available list.
assert(pm.isEnabled("sample"));
pm.setEnabled("sample", false);
assert(!pm.isEnabled("sample"));
assert(pm.findAvailable("sample") == nullptr);
pm.setEnabled("sample", true);
assert(pm.findAvailable("sample") != nullptr);
// Reload keeps built-ins (same instance) and rescans external plugins.
IPackageManager* pacmanBefore = pacman;
pm.reload();
assert(pm.managerFor("pacman") == pacmanBefore);
assert(pm.findAvailable("sample") != nullptr);
// refreshAvailability re-evaluates the presence of every tool.
pm.refreshAvailability();
assert(pm.findAvailable("pacman") != nullptr);
std::cout << "All plugin-manager tests passed." << std::endl;
return 0;
}