feat(flatpak): let the user choose which installation to act on

The same application can be present twice — in the user installation
and system-wide, or from two remotes or two branches — and flatpak then
refuses to act on the application id alone: "Multiple installed refs
match 'com.hoptodesk.HopToDesk'". Removing either copy was impossible
from the app.

A row now stands for the application and carries the copies it is made
of, so the details panel lists them and Remove opens one checkbox per
copy; the provider gets back the exact target it listed, and naming a
ref plus its installation is what makes the call unambiguous. Update
gains the same resolution, since it hit the very same refusal, and
removing one copy of two no longer takes the other one's launcher entry
away with it.

The listing that feeds it now asks flatpak for the ref, the branch and
the installation, and reads those columns by position: a branch
installed from a subdirectory has no version, and dropping that empty
column shifted every field after it.
This commit is contained in:
BlackAngelTV committed 2026-09-27 21:33:41 +02:00
1 parent f1fbd3cd8a
commit eb39905bf5
14 files changed
+559 -20

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ Package manager for **Arch Linux** based on **pacman**, with a Qt6 graphical int
- 📋 **History of all actions**
- 🧩 **Plugins**: package managers (pacman built-in, **Flatpak shipped by default**) and **extensions** written in C++ (UI addons, helpers, …)
- 📥 **Flatpak files**: drop a `.flatpakref`, `.flatpakrepo` or `.flatpak` onto the window (or right-click → **Open with PacManager** in your file manager) to install it directly — with the bytes actually downloaded and the elapsed time shown live, since flatpak prints nothing while a runtime comes down
- 🔁 **Several installations**: an application installed per-user *and* system-wide, or from two remotes, stays a **single row**; the details panel lists the copies and **Remove** opens one checkbox per installation so the user picks the ones to get rid of
## Architecture
+1
View File
@@ -12,6 +12,7 @@ Gestionnaire de paquets pour **Arch Linux** basé sur **pacman**, avec interface
- 📋 **Historique** de toutes les actions
- 🧩 **Plugins** : gestionnaires de paquets (pacman intégré, **Flatpak livré par défaut**) et **extensions** écrites en C++ (addons graphiques, helpers, …)
- 📥 **Fichiers Flatpak** : glissez-déposez un `.flatpakref`, `.flatpakrepo` ou `.flatpak` sur la fenêtre (ou clic droit → **Ouvrir avec PacManager** dans le gestionnaire de fichiers) pour l'installer directement — avec les octets réellement téléchargés et le temps écoulé affichés en direct, flatpak n'imprimant rien pendant le téléchargement d'un runtime
- 🔁 **Installations multiples** : une application installée en utilisateur *et* en système, ou depuis deux dépôts, reste **une seule ligne** ; la fiche de détail énumère les copies et **Supprimer** ouvre une case par installation pour choisir celles à retirer
## Architecture
+19
View File
@@ -138,6 +138,25 @@ mémorisé ; pour forcer un nouveau contrôle, utilisez l'entrée **Vérifier le
mises à jour** du menu ou du menu de la barre d'état, ou supprimez la clé
correspondante dans `~/.config/Freebuff/PacManager.conf`.
### « Multiple installed refs match … » ou « Multiple branches available »
L'application est installée plusieurs fois — en utilisateur **et** en système, ou
depuis deux dépôts ou deux branches — et Flatpak refuse alors de la viser par son
seul identifiant. C'est ce que montre l'encadré d'erreur.
Depuis la version qui gère les installations multiples, ce cas se règle dans
l'interface : la ligne est unique, la fiche de détail énumère les copies
(« utilisateur », « système », le dépôt et la branche), et **Supprimer** propose
une case par copie. Si le paquet vient de la recherche ou du nettoyage plutôt que
de la liste Installés, la suppression retire toutes ses copies.
En ligne de commande, la copie se nomme par sa référence complète :
```bash
flatpak uninstall --user com.example.App/x86_64/master # la copie utilisateur
flatpak uninstall com.example.App/x86_64/stable # la copie système
```
### La barre de progression semble figée ou fait des allers-retours
Elle ne devrait plus reculer : la progression est monotone et pondérée par phase
+26 -1
View File
@@ -34,7 +34,6 @@ dupliquer la table et le panneau de détails.
direct aux mises à jour en attente.
### Fichiers Flatpak (glisser-déposer et « Ouvrir avec PacManager »)
Un `.flatpakref`, `.flatpakrepo` ou `.flatpak` installé depuis le bureau arrive
par deux chemins, tous deux traités comme **une seule demande** par le cadre :
@@ -49,6 +48,32 @@ affiche un message dans la barre de statut, un fichier refusé par le fournisseu
montre sa sortie. Plusieurs fichiers déposés d'un coup s'installent **un par
un** (le core n'accepte qu'une opération à la fois).
### Un paquet installé plusieurs fois
Une même application peut être là deux fois — Flatpak le fait quand elle est
installée en utilisateur **et** en système, ou depuis deux dépôts ou deux
branches — et l'outil refuse alors de viser l'application par son seul nom. Le
tableau garde **une ligne par application** ; c'est la fiche de détail qui
énumère ses copies :
```
2 installation(s) :
• utilisateur · hoptodesk-origin · master
• utilisateur
```
Cliquer **Supprimer** sur une telle ligne ouvre alors un choix, une case par
copie, et l'installation cochée est la seule visée :
- une seule installation, ou un fournisseur qui n'en a qu'une : pas de question,
la suppression est celle de la ligne ;
- plusieurs cases cochées : une opération, une commande par installation ;
- aucune case cochée : rien ne part, et la barre de statut le dit.
La cible que le fournisseur a donnée à chaque copie (« user:…/master ») ne va
jamais à l'écran : elle est conservée à côté du libellé et rendue telle quelle au
fournisseur, qui est le seul à savoir la lire.
## Raccourcis clavier
| Raccourci | Effet |
+28 -1
View File
@@ -93,12 +93,39 @@ Copiez `plugins/example-provider/example-provider.cpp` comme point de départ.
| `listInstalled()` / `listUpdates()` | oui | Listes agrégées par les écrans. |
| `refresh(callback)` | oui | Met à jour les métadonnées des dépôts. |
| `canListCleanup()`, `listCleanupCandidates()`, `canCleanCache()`, `cleanCache()` | non | Page Nettoyage. Un fournisseur qui ne les implémente pas est simplement ignoré. |
| `removePackages(names, callback)` | non | Suppression groupée en une commande. |
| `removePackages(names, callback)` | non | Suppression groupée en une commande. Le défaut (un `remove()` par entrée) convient aux `target` d'un paquet installé plusieurs fois (voir plus bas). |
| `canInstallFile(path)`, `installFile(path, callback)` | non | Installation depuis un fichier du bureau (glisser-déposer, « Ouvrir avec PacManager »). Le fournisseur ne revendique que **ses** formats : Flatpak accepte `.flatpakref`, `.flatpakrepo` et `.flatpak`, et ignore le reste. |
`update("")` signifie **tout mettre à jour** : c'est ce que le worker appelle pour
l'opération globale.
### Un paquet installé plusieurs fois
La plupart des fournisseurs n'ont qu'une installation par paquet, mais pas flatpak
: une même application peut être là deux fois — dans l'installation utilisateur et
en système, ou depuis deux dépôts ou deux branches — et l'outil refuse alors
d'agir sur le simple identifiant (« Multiple installed refs match… »).
Un fournisseur dans ce cas remplit `PackageInfo::instances` dans ses listes : une
entrée `PackageInstance` par copie, avec
- `label`, ce que l'utilisateur lit (« utilisateur · flathub · master ») ;
- `target`, ce que le fournisseur reconnaît pour n'agir que sur cette copie.
Le contrat est alors le suivant, et il ne demande **aucune méthode de plus** :
- `remove()` et `update()` acceptent aussi bien un identifiant qu'un `target`. Sur
un identifiant, le fournisseur tente la commande habituelle ; si l'outil signale
l'ambiguïté, il liste ses copies et agit sur chacune d'elles. Sur un `target`, il
vise exactement cette copie ;
- l'interface fusionne les lignes de même nom et garde les `instances` des lignes
absorbées (`mergeProviderDuplicates`), puis laisse l'utilisateur choisir ;
- `removePackages()` (défaut : un `remove()` par entrée) fait déjà le travail pour
plusieurs `target`.
Le `target` n'est jamais affiché ni reconstruit par l'interface : seul le
fournisseur sait ce qu'il signifie.
### Rapporter la progression
Le callback est `void(const std::string& message, int percent)` :
+1 -1
View File
@@ -16,7 +16,7 @@ lance qu'une partie (`ctest -R progress`).
| Cible | Ce qu'elle couvre | Dépendances |
| --- | --- | --- |
| `pacman-manager-test` | Parsing de la sortie pacman : listes, mises à jour, orphelins/étrangers, commandes construites (`removePackagesCommand`, `cleanCacheCommand`) et détection des échecs (mot de passe, verrou). | Aucune (pas de pacman). |
| `flatpak-manager-test` | Parsing de la sortie Flatpak : recherche, listes, colonnes ; reconnaissance des formats de fichier (`.flatpakref`, `.flatpakrepo`, `.flatpak`, casse et URL) et commandes construites pour l'installation depuis un fichier (chemins entre guillemets compris). | Aucune. |
| `flatpak-manager-test` | Parsing de la sortie Flatpak : recherche, listes, colonnes ; reconnaissance des formats de fichier (`.flatpakref`, `.flatpakrepo`, `.flatpak`, casse et URL) et commandes construites pour l'installation depuis un fichier (chemins entre guillemets compris) ; **installations multiples** : chaque copie nommée (`<installation>:<ref>`, version absente qui ne décale pas les colonnes), copies conservées après fusion des lignes, commandes de désinstallation et de mise à jour ciblant une copie. | Aucune. |
| `flatpak-integration-test` | **Le vrai CLI flatpak** : installation et désinstallation d'une petite application, liste, recherche, mise à jour — donc aussi le `DownloadWatcher` en conditions réelles. | `flatpak` (le test se saute s'il est absent). |
| `aur-manager-test` | Parsing du helper AUR (yay/paru) et nettoyage des séquences ANSI. | Aucune. |
| `package-utils-test` | Logique partagée de `package-manager.h` : fusion des doublons entre fournisseurs, tri par fournisseur puis par nom. | Aucune. |
+14
View File
@@ -92,6 +92,13 @@ public:
// ---- Actions ----
StartResult install(const PackageInfo& package);
StartResult remove(const PackageInfo& package);
// Removes only the installations the user picked, when the provider can
// have several copies of the same application (flatpak: one in the user
// installation and one system-wide, or two remotes or branches). The targets
// are the ones the provider listed in PackageInfo::instances, so the core
// never builds them; an empty list is the plain remove().
StartResult removeInstances(const PackageInfo& package,
const std::vector<std::string>& targets);
StartResult update(const PackageInfo& package);
StartResult updateAll();
StartResult refresh();
@@ -202,6 +209,13 @@ private:
// File a file-based request acts on (see installFile), kept apart from
// `package.name`, which only carries the label for the UI and history.
QString path;
// The exact installation a request acts on, when the provider named one
// (see removeInstances). Like `path`, it is what the provider is given
// instead of the display label, which the UI and the history keep.
QString target;
// Several installations of the same application, acted on in one
// operation (see removeInstances).
std::vector<std::string> targets;
std::string pluginId;
};
+30
View File
@@ -7,6 +7,22 @@
#include <algorithm>
#include <cctype>
// One *installation* of a package. The same application can be present several
// times over — flatpak installs one copy in the user installation and another
// system-wide, or two different remotes or branches of the same id — and acting
// on "the package" is then ambiguous: flatpak refuses ("Multiple installed refs
// match …"). A provider that can have several fills `instances` so the view can
// list them and the user can choose the ones to act on.
struct PackageInstance {
// What the user reads: "utilisateur · flathub · stable".
std::string label;
// What the provider needs to act on exactly that one, in its own syntax
// ("user:com.example.App/x86_64/stable" for flatpak). The provider is the
// only one that understands it, which is why it is never shown and never
// rebuilt by the view.
std::string target;
};
// Information about a single package
struct PackageInfo {
std::string name;
@@ -22,6 +38,10 @@ struct PackageInfo {
// 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;
// Every installation of this package, when the provider can have more than
// one (see PackageInstance). Empty means a single installation, which is
// what every provider but flatpak reports.
std::vector<PackageInstance> instances;
bool installed = false;
bool updateAvailable = false;
// Cleanup classification, filled by providers that report maintainable
@@ -62,6 +82,16 @@ inline void mergeProviderDuplicates(std::vector<PackageInfo>& packages) {
const PackageInfo& dup = packages[i];
first.installed = first.installed || dup.installed;
first.updateAvailable = first.updateAvailable || dup.updateAvailable;
// The installations of both rows belong to the merged one: that is how a
// package installed system-wide *and* per-user still shows the two
// copies the user can choose from.
for (const PackageInstance& instance : dup.instances) {
bool known = false;
for (const PackageInstance& existing : first.instances) {
if (existing.target == instance.target) { known = true; break; }
}
if (!known) first.instances.push_back(instance);
}
if (!dup.provider.empty()) {
bool known = false;
for (const auto& p : first.providers) {
+94 -1
View File
@@ -1,6 +1,8 @@
#include "browse-page.h"
#include <QColor>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QFile>
#include <QFileDialog>
@@ -9,6 +11,7 @@
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QMessageBox>
#include <QProgressBar>
#include <QPushButton>
@@ -101,7 +104,15 @@ BrowsePage::BrowsePage(AppCore* core, QWidget* parent) : Page(core, parent) {
connect(m_removeButton, &QPushButton::clicked, this, [this, core] {
if (m_selected.name.empty()) return;
m_pendingSelect = QString::fromStdString(m_selected.name);
start(core->remove(m_selected), tr("Suppression"));
// Several copies of the same application: the user says which ones go.
// A cancelled chooser aborts, an empty choice tells why in the status bar.
const auto targets = chooseInstancesToRemove();
if (!targets.has_value()) return;
if (targets->empty()) {
emit message(tr("Aucune installation sélectionnée."));
return;
}
start(core->removeInstances(m_selected, *targets), tr("Suppression"));
});
actionBar->addWidget(m_removeButton);
@@ -200,6 +211,14 @@ BrowsePage::BrowsePage(AppCore* core, QWidget* parent) : Page(core, parent) {
metaRow->addStretch();
detailsLayout->addLayout(metaRow);
// Only shown for a package the provider holds several times over.
m_pkgInstances = new QLabel();
m_pkgInstances->setWordWrap(true);
m_pkgInstances->setStyleSheet(
"font-size: 13px; color: #7dd3fc; background: transparent;");
m_pkgInstances->setVisible(false);
detailsLayout->addWidget(m_pkgInstances);
QFrame* separator = new QFrame();
separator->setFrameShape(QFrame::HLine);
separator->setStyleSheet(
@@ -522,6 +541,24 @@ void BrowsePage::updateDetails(const PackageInfo& pkg) {
m_pkgProvider->setText(
QString("Fournisseur : %1").arg(ui::providersLabel(core()->plugins(), pkg)));
// A provider can hold several copies of the same application (flatpak: one
// per installation, per remote or per branch). The row stands for the
// application, so the copies it is made of are listed here — and the remove
// button asks which of them to act on.
if (pkg.instances.size() > 1) {
QStringList copies;
for (const PackageInstance& instance : pkg.instances) {
copies << QString::fromStdString(instance.label);
}
m_pkgInstances->setText(
QString("%1 installation(s) :\n• %2")
.arg(copies.size())
.arg(copies.join(QStringLiteral("\n• "))));
m_pkgInstances->setVisible(true);
} else {
m_pkgInstances->setVisible(false);
}
// Rich details (dependencies, required-by, install date, update size): the
// core queries pacman on demand and caches the answer, so selecting a row
// stays instant even when pacman is slow.
@@ -534,6 +571,61 @@ void BrowsePage::updateDetails(const PackageInfo& pkg) {
m_pkgDescription->setText(details);
}
// Asks which copies of the selected application to remove, when the provider
// holds it more than once (flatpak: a user and a system-wide installation, or
// two remotes or branches of the same id). One line per copy, each with the
// provider's own target kept aside, so the core is handed exactly what it must
// act on. Returns nothing when the user cancels.
std::optional<std::vector<std::string>> BrowsePage::chooseInstancesToRemove() {
if (m_selected.instances.size() < 2) {
// A single installation, or a provider that only ever has one: the row
// is the thing to remove, no question to ask.
return std::vector<std::string>{};
}
QDialog dialog(this);
dialog.setWindowTitle(tr("Supprimer %1").arg(QString::fromStdString(m_selected.name)));
QVBoxLayout* layout = new QVBoxLayout(&dialog);
layout->setSpacing(10);
QLabel* prompt = new QLabel(
tr("%1 est installé plusieurs fois. Choisissez les installations à "
"supprimer.")
.arg(QString::fromStdString(m_selected.name)),
&dialog);
prompt->setWordWrap(true);
layout->addWidget(prompt);
QListWidget* copies = new QListWidget(&dialog);
for (const PackageInstance& instance : m_selected.instances) {
QListWidgetItem* item =
new QListWidgetItem(QString::fromStdString(instance.label), copies);
// The target never reaches the screen: it is the provider's own syntax,
// kept beside the label and handed straight back.
item->setData(Qt::UserRole, QString::fromStdString(instance.target));
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(Qt::Unchecked);
}
layout->addWidget(copies);
QDialogButtonBox* buttons =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
buttons->button(QDialogButtonBox::Ok)->setText(tr("Supprimer"));
buttons->button(QDialogButtonBox::Cancel)->setText(tr("Annuler"));
connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
layout->addWidget(buttons);
if (dialog.exec() != QDialog::Accepted) return std::nullopt;
std::vector<std::string> targets;
for (int row = 0; row < copies->count(); ++row) {
if (copies->item(row)->checkState() != Qt::Checked) continue;
targets.push_back(copies->item(row)->data(Qt::UserRole).toString().toStdString());
}
return targets;
}
void BrowsePage::resetDetails() {
m_selected = PackageInfo{};
m_pkgName->setText("Sélectionnez un paquet");
@@ -541,6 +633,7 @@ void BrowsePage::resetDetails() {
m_pkgRepo->setText("—");
m_pkgSize->setText("—");
m_pkgProvider->setText("—");
m_pkgInstances->setVisible(false);
m_pkgDescription->setText("");
m_installButton->setEnabled(false);
m_removeButton->setEnabled(false);
+9
View File
@@ -1,6 +1,8 @@
#pragma once
#include <optional>
#include <QString>
#include <vector>
#include "page.h"
@@ -49,6 +51,10 @@ private:
void populateTable(const std::vector<PackageInfo>& packages);
void appendRows(const std::vector<PackageInfo>& packages);
void addRow(int row, const PackageInfo& pkg);
// Which installations of the selected package to remove, when the provider
// holds it more than once. Empty when there is only one to remove, nothing
// (std::nullopt) when the user cancels the chooser.
std::optional<std::vector<std::string>> chooseInstancesToRemove();
void updateDetails(const PackageInfo& pkg);
void resetDetails();
@@ -84,5 +90,8 @@ private:
QLabel* m_pkgRepo = nullptr;
QLabel* m_pkgSize = nullptr;
QLabel* m_pkgProvider = nullptr;
// The copies a multi-installed package is made of, shown only when there is
// more than one.
QLabel* m_pkgInstances = nullptr;
QLabel* m_pkgDescription = nullptr;
};
+199 -14
View File
@@ -95,6 +95,75 @@ static unsigned long long stagedBytes() {
return total;
}
// ---------------------------------------------------------------------------
// Naming and targeting one installation
// ---------------------------------------------------------------------------
// flatpak installs the same application id several times over — once in the
// user installation, once system-wide, or from two remotes or branches — and
// then refuses to act on the id alone: "Multiple installed refs match
// 'com.example.App', unable to proceed in non-interactive mode". Naming one
// copy therefore takes both its installation and its full ref.
// The string that names exactly one installation, "<installation>:<ref>". The
// view never builds it and never reads it: it is what the provider put in
// PackageInfo::instances when it listed the app, handed back unchanged when the
// user picks the copies to act on.
static std::string installationTarget(const std::string& installation,
const std::string& ref) {
return installation + ":" + ref;
}
// "user:com.example.App/x86_64/stable" -> installation "user", ref the rest.
static bool splitInstallationTarget(const std::string& target, std::string* installation,
std::string* ref) {
const std::size_t colon = target.find(':');
if (colon == std::string::npos || colon == 0 || colon + 1 >= target.size()) return false;
const std::string head = target.substr(0, colon);
// A plain application id has no colon, and anything else is not a target.
if (head != "user" && head != "system") return false;
*installation = head;
*ref = target.substr(colon + 1);
return true;
}
// What the user reads for one copy: "utilisateur · flathub · stable". The
// remote and the branch are the two things that tell two copies of the same id
// apart, so they are what the label carries.
static std::string instanceLabel(const std::string& installation, const std::string& origin,
const std::string& branch) {
std::string label = installation == "user" ? "utilisateur" : "système";
if (!origin.empty() && origin != "-" && origin != "flathub") {
label += " · " + origin;
}
if (!branch.empty() && branch != "master" && branch != "stable") {
label += " · " + branch;
}
return label;
}
// flatpak refuses an application id that names several copies, and the wording
// depends on what makes it ambiguous: several installed refs, or several branches
// of one ref. Both are the same situation here — the copies have to be listed
// and named one by one.
static bool isAmbiguous(const std::string& output) {
return output.find("Multiple installed refs match") != std::string::npos
|| output.find("Multiple branches available") != std::string::npos;
}
// Every installation of `appId` in a listing, as targets the caller can hand
// straight back. Empty when the id is not installed at all.
static std::vector<std::string> targetsFor(const std::vector<PackageInfo>& installed,
const std::string& appId) {
std::vector<std::string> targets;
for (const PackageInfo& pkg : installed) {
if (pkg.name != appId) continue;
for (const PackageInstance& instance : pkg.instances) {
if (!instance.target.empty()) targets.push_back(instance.target);
}
}
return targets;
}
// "218 Mio", "1,4 Gio": the same units a French file manager would use.
static std::string humanBytes(unsigned long long bytes) {
static const char* units[] = {"o", "Kio", "Mio", "Gio", "To"};
@@ -298,7 +367,8 @@ static std::string shellQuote(const std::string& value) {
}
// Split a flatpak --columns line. flatpak emits tab-separated fields with that
// flag; fall back to whitespace splitting when tabs are absent.
// flag; fall back to whitespace splitting when tabs are absent. Empty fields are
// dropped, which is what an aligned search row needs.
static std::vector<std::string> splitColumns(const std::string& line) {
std::vector<std::string> fields;
std::istringstream ss(line);
@@ -313,6 +383,20 @@ static std::vector<std::string> splitColumns(const std::string& line) {
return fields;
}
// Same split, but an empty column stays a column: a listing read by position
// would otherwise shift every field after it. `flatpak list` prints an empty
// version for a branch installed from a subdirectory, which is exactly where a
// row carries the ref and the installation that tell its copies apart.
static std::vector<std::string> splitColumnsByPosition(const std::string& line) {
if (line.find('\t') == std::string::npos) return {line};
std::vector<std::string> fields;
std::istringstream ss(line);
std::string field;
while (std::getline(ss, field, '\t')) 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
@@ -371,7 +455,7 @@ std::vector<PackageInfo> FlatpakManager::parseInstalledOutput(const std::string&
while (std::getline(iss, line)) {
if (line.empty()) continue;
std::vector<std::string> fields = splitColumns(line);
std::vector<std::string> fields = splitColumnsByPosition(line);
if (fields.empty()) continue;
PackageInfo pkg;
@@ -379,6 +463,22 @@ std::vector<PackageInfo> FlatpakManager::parseInstalledOutput(const std::string&
if (fields.size() > 1) pkg.version = fields[1];
if (fields.size() > 2) pkg.repository = fields[2];
pkg.installed = true;
// The ref, branch and installation columns (the last three) say *which*
// copy this row is: the same application can be installed in the user
// installation and system-wide, or from two remotes or branches, and
// flatpak then refuses to act on the application id alone.
if (fields.size() >= 6) {
const std::string& ref = fields[3];
const std::string& branch = fields[4];
const std::string& installation = fields[5];
if (!ref.empty()) {
PackageInstance instance;
instance.target = installationTarget(installation, ref);
instance.label = instanceLabel(installation, pkg.repository, branch);
pkg.instances.push_back(instance);
}
}
results.push_back(pkg);
}
@@ -442,6 +542,30 @@ std::string FlatpakManager::installFileCommand(FileKind kind, const std::string&
+ " 2>&1";
}
std::string FlatpakManager::uninstallCommand(const std::string& packageName) {
std::string installation;
std::string ref;
if (splitInstallationTarget(packageName, &installation, &ref)) {
// Naming the ref is what makes it unambiguous; the scope is what picks
// the copy, since the same ref can sit in both installations.
const std::string scope = installation == "user" ? "--user " : "";
return "flatpak uninstall --noninteractive --assumeyes " + scope + shellQuote(ref)
+ " 2>&1";
}
return "flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1";
}
std::string FlatpakManager::updateCommand(const std::string& packageName) {
std::string installation;
std::string ref;
if (splitInstallationTarget(packageName, &installation, &ref)) {
const std::string scope = installation == "user" ? "--user " : "";
return "flatpak update --noninteractive --assumeyes " + scope + shellQuote(ref)
+ " 2>&1";
}
return "flatpak update --noninteractive --assumeyes " + packageName + " 2>&1";
}
// Application ids mentioned in a command's output, e.g.
// "Installing: org.gnome.Dictionary/x86_64/stable from flathub". A file install
// only reveals the app id once flatpak resolved the file, and the launcher
@@ -487,8 +611,12 @@ std::vector<PackageInfo> FlatpakManager::search(const std::string& query) {
}
std::vector<PackageInfo> FlatpakManager::listInstalled() {
return parseInstalledOutput(
exec("flatpak list --app --columns=application,version,origin 2>&1"));
// ref, branch and installation are what tell two installations of the same
// application id apart, so they are listed: without them the view could
// neither show the copies nor choose between them.
return parseInstalledOutput(exec("flatpak list --app "
"--columns=application,version,origin,ref,branch,installation "
"2>&1"));
}
std::vector<PackageInfo> FlatpakManager::listUpdates() {
@@ -648,20 +776,56 @@ void FlatpakManager::integrateAllInstalled() {
bool FlatpakManager::remove(const std::string& packageName,
ProgressCallback progressCallback) {
m_lastError.clear();
if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1);
std::string output = runFlatpak(
"flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1",
progressCallback);
std::string installation;
std::string ref;
const bool targeted = splitInstallationTarget(packageName, &installation, &ref);
const std::string appId = targeted ? ref.substr(0, ref.find('/')) : packageName;
if (output.find("error:") != std::string::npos || isInstalled(packageName)) {
m_lastError = lastOutputLines(output);
return false;
if (progressCallback) {
progressCallback(
targeted ? "Suppression de " + appId + " (" + installation + ")..."
: "Suppression de " + packageName + "...",
-1);
}
// Clear the launcher links created at install time (see integrateDesktopEntries).
uninstallDesktopEntries(packageName);
return true;
std::vector<std::string> targets;
if (targeted) {
targets.push_back(packageName);
} else {
// A row stands for the application, not for one of its copies, so the
// application id is tried as it is: flatpak only refuses it when the
// copies are several, and the copies are then the ones to remove.
const std::string output = runFlatpak(uninstallCommand(packageName), progressCallback);
if (!isAmbiguous(output)) {
if (output.find("error:") != std::string::npos || isInstalled(appId)) {
m_lastError = lastOutputLines(output);
return false;
}
uninstallDesktopEntries(appId);
return true;
}
targets = targetsFor(listInstalled(), appId);
if (targets.empty()) {
m_lastError = lastOutputLines(output);
return false;
}
}
bool success = true;
for (const std::string& target : targets) {
const std::string output = runFlatpak(uninstallCommand(target), progressCallback);
if (output.find("error:") != std::string::npos) {
m_lastError = lastOutputLines(output);
success = false;
}
}
// The launcher links belong to the application as a whole: they go only once
// no copy is left, or removing one of two copies would take the entry away
// from the other.
if (success && !isInstalled(appId)) uninstallDesktopEntries(appId);
return success;
}
bool FlatpakManager::update(const std::string& packageName,
@@ -680,6 +844,27 @@ bool FlatpakManager::update(const std::string& packageName,
}
std::string output = tryUpdate("");
// Several installations of the same application: the id alone is refused, so
// every copy is updated with its own scope. No polkit fallback here — it
// would quietly update a different copy than the one that failed.
if (isAmbiguous(output)) {
const std::vector<std::string> targets = targetsFor(listInstalled(), packageName);
if (targets.empty()) {
m_lastError = lastOutputLines(output);
return false;
}
bool success = true;
for (const std::string& target : targets) {
const std::string copy = runFlatpak(updateCommand(target), progressCallback);
if (copy.find("error:") != std::string::npos) {
m_lastError = lastOutputLines(copy);
success = false;
}
}
return success;
}
// 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...", -1);
@@ -53,6 +53,14 @@ public:
static std::string installFileCommand(FileKind kind, const std::string& path,
bool userScope = false);
// Commands that act on exactly one installation of an application. Both take
// either an application id — flatpak then refuses it when several copies
// exist — or a target ("user:com.example.App/x86_64/stable") naming one copy,
// as found in PackageInfo::instances. Exposed so the exact command line is
// testable without running flatpak.
static std::string uninstallCommand(const std::string& packageName);
static std::string updateCommand(const std::string& packageName);
// Name a `.flatpakrepo` is registered under: its base name without the
// extension (flathub.flatpakrepo -> flathub), which is what the user then
// types in `flatpak install <name> <app>`.
+34 -2
View File
@@ -460,6 +460,29 @@ AppCore::StartResult AppCore::remove(const PackageInfo& package) {
return startRequest(request);
}
AppCore::StartResult AppCore::removeInstances(const PackageInfo& package,
const std::vector<std::string>& targets) {
if (targets.empty()) return remove(package);
if (targets.size() == 1) {
// One installation picked: the plain removal of that copy. The label
// stays the application name, so the status bar, the journal header and
// the history keep naming the application rather than its ref.
Request request;
request.action = QStringLiteral("remove");
request.package = package;
request.target = QString::fromStdString(targets.front());
return startRequest(request);
}
// Several picked: one operation, one command per installation, the provider
// removing each copy in turn.
Request request;
request.action = QStringLiteral("remove");
request.package = package;
request.targets = targets;
return startRequest(request);
}
AppCore::StartResult AppCore::update(const PackageInfo& package) {
Request request;
request.action = QStringLiteral("update");
@@ -501,8 +524,7 @@ bool AppCore::canInstallFile(const QString& path) const {
}
AppCore::StartResult AppCore::removePackages(const std::vector<PackageInfo>& packages,
const QString& description) {
Request request;
const QString& description) { Request request;
request.action = QStringLiteral("cleanup");
request.packages = packages;
request.description = description;
@@ -713,10 +735,20 @@ AppCore::StartResult AppCore::startRequest(Request request) {
if (action == QLatin1String("update-all") || action == QLatin1String("refresh")
|| action == QLatin1String("clean-caches")) {
worker = new InstallWorker(providers, op);
} else if (!request.targets.empty()) {
// Several installations of one application were picked in the chooser:
// the provider removes one copy per target, and the row they share is
// what the journal and the history name.
worker = new InstallWorker(providers.front(), InstallWorker::Op::RemovePackages,
request.targets);
} else if (action == QLatin1String("install-file")) {
// A file install needs the path, not the display label the other
// single-provider operations pass.
worker = new InstallWorker(providers.front(), op, request.path.toStdString());
} else if (!request.target.isEmpty()) {
// A single installation was picked: the target names it, the label does
// not.
worker = new InstallWorker(providers.front(), op, request.target.toStdString());
} else {
worker = new InstallWorker(providers.front(), op, label.toStdString());
}
+95
View File
@@ -67,6 +67,62 @@ static void testParseInstalledOutput_emptyInput() {
assert(FlatpakManager::parseInstalledOutput("").empty());
}
// The same application installed more than once: one copy per installation,
// per remote or per branch. Each row must say which one it is, or the view
// cannot list the copies and the provider cannot act on any of them.
static void testParseInstalledOutput_namesEveryInstallation() {
std::string output =
"com.hoptodesk.HopToDesk\t\thoptodesk-origin\tcom.hoptodesk.HopToDesk/x86_64/master\tmaster\tuser\n"
"com.hoptodesk.HopToDesk\t1.46.38\tflathub\tcom.hoptodesk.HopToDesk/x86_64/stable\tstable\tuser\n"
"com.usebottles.bottles\t67.3\tflathub\tcom.usebottles.bottles/x86_64/stable\tstable\tsystem\n"
"com.usebottles.bottles\t67.3\tflathub\tcom.usebottles.bottles/x86_64/stable\tstable\tuser\n";
auto pkgs = FlatpakManager::parseInstalledOutput(output);
assert(pkgs.size() == 4);
// An empty version is a column, not a gap: dropping it shifted every field
// after it, and the row said nothing about which copy it was.
assert(pkgs[0].version.empty());
assert(pkgs[0].repository == "hoptodesk-origin");
// The target is "<installation>:<ref>": the two halves are what flatpak
// needs to refuse the application id and name this copy instead.
assert(pkgs[0].instances[0].target == "user:com.hoptodesk.HopToDesk/x86_64/master");
assert(pkgs[1].instances[0].target == "user:com.hoptodesk.HopToDesk/x86_64/stable");
assert(pkgs[2].instances[0].target == "system:com.usebottles.bottles/x86_64/stable");
assert(pkgs[3].instances[0].target == "user:com.usebottles.bottles/x86_64/stable");
// A label says the installation, and the remote or branch when it is what
// tells two copies of the same id apart.
assert(pkgs[0].instances[0].label == "utilisateur · hoptodesk-origin · master");
assert(pkgs[1].instances[0].label == "utilisateur");
assert(pkgs[2].instances[0].label == "système");
}
// A listing without the ref/branch/installation columns stays readable: the
// row is the application, with no copy to choose between.
static void testParseInstalledOutput_withoutInstallationColumns() {
auto pkgs = FlatpakManager::parseInstalledOutput("org.gnome.Calculator\t47.0\tflathub\n");
assert(pkgs.size() == 1);
assert(pkgs[0].name == "org.gnome.Calculator");
assert(pkgs[0].instances.empty());
}
// Once merged, a row must keep the copies of every row it absorbed: that is
// what the chooser lists.
static void testMergedRowKeepsEveryCopy() {
std::vector<PackageInfo> rows = FlatpakManager::parseInstalledOutput(
"com.usebottles.bottles\t67.3\tflathub\tcom.usebottles.bottles/x86_64/stable\tstable\tsystem\n"
"com.usebottles.bottles\t67.3\tflathub\tcom.usebottles.bottles/x86_64/stable\tstable\tuser\n");
mergeProviderDuplicates(rows);
assert(rows.size() == 1);
assert(rows[0].instances.size() == 2);
assert(rows[0].instances[0].target == "system:com.usebottles.bottles/x86_64/stable");
assert(rows[0].instances[1].target == "user:com.usebottles.bottles/x86_64/stable");
}
static void testParseUpdatesOutput_parsesRows() {
std::string output =
"org.mozilla.firefox\t130.0\n"
@@ -150,6 +206,40 @@ static void testInstallFileCommand_buildsTheFlatpakCalls() {
assert(quoted.find("'/tmp/mon paquet.flatpak'") != std::string::npos);
}
// Naming one copy is what makes the call unambiguous: the ref alone picks the
// remote and the branch, the scope picks the installation.
static void testUninstallAndUpdateCommands_targetOneCopy() {
const std::string userCopy =
FlatpakManager::uninstallCommand("user:com.example.App/x86_64/stable");
assert(userCopy.find("flatpak uninstall") == 0);
assert(userCopy.find("--user") != std::string::npos);
assert(userCopy.find("com.example.App/x86_64/stable") != std::string::npos);
// The application's own id must not be in there any more: that is exactly
// what flatpak refuses when several copies exist.
assert(userCopy.find("--assumeyes com.example.App ") == std::string::npos);
const std::string systemCopy =
FlatpakManager::uninstallCommand("system:com.example.App/x86_64/stable");
assert(systemCopy.find("flatpak uninstall") == 0);
assert(systemCopy.find("--user") == std::string::npos);
assert(systemCopy.find("com.example.App/x86_64/stable") != std::string::npos);
const std::string update = FlatpakManager::updateCommand("user:com.example.App/x86_64/stable");
assert(update.find("flatpak update") == 0);
assert(update.find("--user") != std::string::npos);
assert(update.find("com.example.App/x86_64/stable") != std::string::npos);
}
// A plain application id keeps working as it always did — the provider only
// needs the target when the id is ambiguous, and finds out by trying.
static void testUninstallCommand_stillAcceptsAnApplicationId() {
const std::string plain = FlatpakManager::uninstallCommand("com.example.App");
assert(plain.find("flatpak uninstall") == 0);
assert(plain.find("com.example.App") != std::string::npos);
assert(plain.find("--user") == std::string::npos);
}
int main() {
testParseSearchOutput_parsesAlignedRows();
testParseSearchOutput_keepsMultiWordDescriptions();
@@ -158,6 +248,9 @@ int main() {
testParseInstalledOutput_parsesTabSeparated();
testParseInstalledOutput_emptyInput();
testParseInstalledOutput_namesEveryInstallation();
testParseInstalledOutput_withoutInstallationColumns();
testMergedRowKeepsEveryCopy();
testParseUpdatesOutput_parsesRows();
testParseUpdatesOutput_emptyInput();
@@ -165,6 +258,8 @@ int main() {
testClassifyFile_recognisesTheThreeFlatpakFormats();
testRepoName_comesFromTheFileName();
testInstallFileCommand_buildsTheFlatpakCalls();
testUninstallAndUpdateCommands_targetOneCopy();
testUninstallCommand_stillAcceptsAnApplicationId();
std::cout << "All flatpak-manager tests passed." << std::endl;
return 0;