diff --git a/README.en.md b/README.en.md index 6dc3a89..2423d97 100644 --- a/README.en.md +++ b/README.en.md @@ -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 diff --git a/README.md b/README.md index 486e5c1..dbd5c43 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/doc/depannage.md b/doc/depannage.md index d59fb0c..e052d8f 100644 --- a/doc/depannage.md +++ b/doc/depannage.md @@ -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 diff --git a/doc/interface.md b/doc/interface.md index fb14e5c..7167bf9 100644 --- a/doc/interface.md +++ b/doc/interface.md @@ -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 | diff --git a/doc/plugins.md b/doc/plugins.md index 5bd9c7a..17f5fd4 100644 --- a/doc/plugins.md +++ b/doc/plugins.md @@ -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)` : diff --git a/doc/tests.md b/doc/tests.md index 41481e0..0d266cf 100644 --- a/doc/tests.md +++ b/doc/tests.md @@ -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 (`:`, 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. | diff --git a/include/app-core.h b/include/app-core.h index 32b2004..3c1ed0b 100644 --- a/include/app-core.h +++ b/include/app-core.h @@ -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& 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 targets; std::string pluginId; }; diff --git a/include/package-manager.h b/include/package-manager.h index 5d3bf52..df0ca4f 100644 --- a/include/package-manager.h +++ b/include/package-manager.h @@ -7,6 +7,22 @@ #include #include +// 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 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 instances; bool installed = false; bool updateAvailable = false; // Cleanup classification, filled by providers that report maintainable @@ -62,6 +82,16 @@ inline void mergeProviderDuplicates(std::vector& 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) { diff --git a/pages/browse-page.cpp b/pages/browse-page.cpp index 0205213..655408a 100644 --- a/pages/browse-page.cpp +++ b/pages/browse-page.cpp @@ -1,6 +1,8 @@ #include "browse-page.h" #include +#include +#include #include #include #include @@ -9,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -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> 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{}; + } + + 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 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); diff --git a/pages/browse-page.h b/pages/browse-page.h index e0cce1b..9121283 100644 --- a/pages/browse-page.h +++ b/pages/browse-page.h @@ -1,6 +1,8 @@ #pragma once +#include #include +#include #include "page.h" @@ -49,6 +51,10 @@ private: void populateTable(const std::vector& packages); void appendRows(const std::vector& 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> 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; }; diff --git a/plugins/flatpak-provider/flatpak-manager.cpp b/plugins/flatpak-provider/flatpak-manager.cpp index 93f41d6..3e5106b 100644 --- a/plugins/flatpak-provider/flatpak-manager.cpp +++ b/plugins/flatpak-provider/flatpak-manager.cpp @@ -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, ":". 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 targetsFor(const std::vector& installed, + const std::string& appId) { + std::vector 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 splitColumns(const std::string& line) { std::vector fields; std::istringstream ss(line); @@ -313,6 +383,20 @@ static std::vector 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 splitColumnsByPosition(const std::string& line) { + if (line.find('\t') == std::string::npos) return {line}; + + std::vector 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 FlatpakManager::parseInstalledOutput(const std::string& while (std::getline(iss, line)) { if (line.empty()) continue; - std::vector fields = splitColumns(line); + std::vector fields = splitColumnsByPosition(line); if (fields.empty()) continue; PackageInfo pkg; @@ -379,6 +463,22 @@ std::vector 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 FlatpakManager::search(const std::string& query) { } std::vector 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 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 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 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); diff --git a/plugins/flatpak-provider/flatpak-manager.h b/plugins/flatpak-provider/flatpak-manager.h index 75d6c50..bc26be0 100644 --- a/plugins/flatpak-provider/flatpak-manager.h +++ b/plugins/flatpak-provider/flatpak-manager.h @@ -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 `. diff --git a/src/app-core.cpp b/src/app-core.cpp index ab8def1..7d83597 100644 --- a/src/app-core.cpp +++ b/src/app-core.cpp @@ -460,6 +460,29 @@ AppCore::StartResult AppCore::remove(const PackageInfo& package) { return startRequest(request); } +AppCore::StartResult AppCore::removeInstances(const PackageInfo& package, + const std::vector& 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& 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()); } diff --git a/tests/flatpak-manager.test.cpp b/tests/flatpak-manager.test.cpp index 546c168..f18612a 100644 --- a/tests/flatpak-manager.test.cpp +++ b/tests/flatpak-manager.test.cpp @@ -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 ":": 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 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;