refactor(tree): split the plugin host from the providers it loads
plugins/ held two unrelated things: the host that discovers and installs plugins, and the plugins themselves. The host moves to plugins/ with the built-in pacman provider beside it in providers/, where the external providers already live — so plugins/ is now one thing, and the name says which. The external plugin projects only change folder, not layout: providers/ holds aur-provider, flatpak-provider, example-provider and example-addon.
This commit is contained in:
15 files changed
+39
-39
No files matched your search
@@ -1,213 +0,0 @@
|
||||
#include "aur-manager.h"
|
||||
|
||||
#include "progress-tracker.h"
|
||||
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
|
||||
// Helper to run shell commands and capture output.
|
||||
static std::string exec(const char* cmd) {
|
||||
std::array<char, 8192> 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;
|
||||
}
|
||||
|
||||
// Keep the tail of a command's output so the user sees the real failure.
|
||||
static std::string lastOutputLines(const std::string& output, int maxLines = 4) {
|
||||
std::istringstream iss(output);
|
||||
std::string line;
|
||||
std::vector<std::string> lines;
|
||||
while (std::getline(iss, line)) {
|
||||
if (!line.empty()) lines.push_back(line);
|
||||
}
|
||||
std::string out;
|
||||
const size_t start = lines.size() > static_cast<size_t>(maxLines)
|
||||
? lines.size() - maxLines
|
||||
: 0;
|
||||
for (size_t i = start; i < lines.size(); ++i) {
|
||||
if (!out.empty()) out += "\n";
|
||||
out += lines[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string AurManager::helper() {
|
||||
// yay first (most common), paru as fallback.
|
||||
if (system("command -v yay > /dev/null 2>&1") == 0) return "yay";
|
||||
if (system("command -v paru > /dev/null 2>&1") == 0) return "paru";
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<PackageInfo> AurManager::parseSearchOutput(const std::string& output) {
|
||||
std::vector<PackageInfo> results;
|
||||
std::istringstream iss(stripAnsi(output));
|
||||
std::string header, desc;
|
||||
while (std::getline(iss, header)) {
|
||||
if (header.empty()) continue;
|
||||
if (!std::getline(iss, desc)) desc.clear();
|
||||
// Header looks like "aur/name version [installed]".
|
||||
size_t slash = header.find('/');
|
||||
if (slash == std::string::npos) continue;
|
||||
std::string rest = header.substr(slash + 1);
|
||||
std::istringstream ls(rest);
|
||||
std::string name, version;
|
||||
if (!(ls >> name >> version)) continue;
|
||||
PackageInfo pkg;
|
||||
pkg.name = name;
|
||||
pkg.version = version;
|
||||
pkg.description = desc;
|
||||
pkg.repository = "aur";
|
||||
pkg.installed = header.find("[installed") != std::string::npos
|
||||
|| header.find("(Installed") != std::string::npos;
|
||||
results.push_back(std::move(pkg));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
std::vector<PackageInfo> AurManager::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::istringstream ls(line);
|
||||
std::string name, version;
|
||||
if (!(ls >> name >> version)) continue;
|
||||
PackageInfo pkg;
|
||||
pkg.name = name;
|
||||
pkg.version = version;
|
||||
pkg.repository = "aur";
|
||||
pkg.installed = true;
|
||||
results.push_back(std::move(pkg));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
std::vector<PackageInfo> AurManager::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;
|
||||
// Format: "name old-version -> new-version".
|
||||
std::istringstream ls(line);
|
||||
std::string name, oldVer, arrow, newVer;
|
||||
if (!(ls >> name >> oldVer)) continue;
|
||||
ls >> arrow >> newVer;
|
||||
PackageInfo pkg;
|
||||
pkg.name = name;
|
||||
pkg.version = newVer.empty() ? oldVer : newVer;
|
||||
pkg.repository = "aur";
|
||||
pkg.installed = true;
|
||||
pkg.updateAvailable = true;
|
||||
results.push_back(std::move(pkg));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
std::vector<PackageInfo> AurManager::search(const std::string& query) {
|
||||
const std::string h = helper();
|
||||
if (h.empty()) return {};
|
||||
// --color=never keeps the output parseable.
|
||||
return parseSearchOutput(exec((h + " -Ss --color=never " + query + " 2>&1").c_str()));
|
||||
}
|
||||
|
||||
std::vector<PackageInfo> AurManager::listInstalled() {
|
||||
const std::string h = helper();
|
||||
if (h.empty()) return {};
|
||||
// -Qm lists foreign (AUR) packages only, so official repo packages stay
|
||||
// owned by the pacman provider and rows are not duplicated.
|
||||
return parseInstalledOutput(exec((h + " -Qm 2>&1").c_str()));
|
||||
}
|
||||
|
||||
std::vector<PackageInfo> AurManager::listUpdates() {
|
||||
const std::string h = helper();
|
||||
if (h.empty()) return {};
|
||||
return parseUpdatesOutput(exec((h + " -Qua 2>&1").c_str()));
|
||||
}
|
||||
|
||||
bool AurManager::install(const std::string& packageName,
|
||||
ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
const std::string h = helper();
|
||||
if (h.empty()) {
|
||||
m_lastError = "Aucun helper AUR (yay/paru) installe.";
|
||||
return false;
|
||||
}
|
||||
if (progressCallback) progressCallback("Installation AUR de " + packageName + "...", -1);
|
||||
// Helpers handle sudo themselves; run so the prompt reaches the user. The
|
||||
// output is streamed: the helpers build with makepkg and then hand over to
|
||||
// pacman, and both report progress as they go.
|
||||
std::string output = runWithProgress(
|
||||
h + " -S --noconfirm " + packageName + " 2>&1", progressCallback);
|
||||
if (system((h + " -Q " + packageName + " > /dev/null 2>&1").c_str()) != 0) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AurManager::remove(const std::string& packageName,
|
||||
ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
const std::string h = helper();
|
||||
if (h.empty()) {
|
||||
m_lastError = "Aucun helper AUR (yay/paru) installe.";
|
||||
return false;
|
||||
}
|
||||
if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1);
|
||||
std::string output = runWithProgress(
|
||||
h + " -R --noconfirm " + packageName + " 2>&1", progressCallback);
|
||||
if (system((h + " -Q " + packageName + " > /dev/null 2>&1").c_str()) == 0) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AurManager::update(const std::string& packageName,
|
||||
ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
const std::string h = helper();
|
||||
if (h.empty()) {
|
||||
m_lastError = "Aucun helper AUR (yay/paru) installe.";
|
||||
return false;
|
||||
}
|
||||
std::string target = packageName.empty() ? "--aur" : packageName;
|
||||
if (progressCallback) progressCallback("Mise a jour AUR...", -1);
|
||||
std::string output = runWithProgress(
|
||||
h + " -Syu --noconfirm " + target + " 2>&1", progressCallback);
|
||||
if (output.find("error:") != std::string::npos
|
||||
|| output.find("erreur") != std::string::npos) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AurManager::refresh(ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
const std::string h = helper();
|
||||
if (h.empty()) {
|
||||
m_lastError = "Aucun helper AUR (yay/paru) installe.";
|
||||
return false;
|
||||
}
|
||||
if (progressCallback) progressCallback("Rafraichissement AUR...", -1);
|
||||
std::string output = runWithProgress(h + " -Sy 2>&1", progressCallback);
|
||||
if (output.find("error:") != std::string::npos
|
||||
|| output.find("erreur") != std::string::npos) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "package-manager.h"
|
||||
|
||||
// AUR provider: manages Arch User Repository packages through an AUR helper
|
||||
// (`yay` preferred, `paru` fallback). Runs per-user like flatpak for search
|
||||
// and list (helpers handle sudo internally for install/remove/update), so
|
||||
// requiresPassword() is false — the helper prompts on its own terminal.
|
||||
class AurManager : public IPackageManager {
|
||||
public:
|
||||
std::string getName() const override { return "aur"; }
|
||||
std::string getVersion() const override { return "1.0.0"; }
|
||||
std::string getDescription() const override {
|
||||
return "Paquets communautaires Arch (AUR via yay/paru)";
|
||||
}
|
||||
|
||||
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 !helper().empty();
|
||||
}
|
||||
|
||||
// Last lines of the failed command output, shown to the user on failure.
|
||||
std::string lastError() const override { return m_lastError; }
|
||||
|
||||
// Name of the backing helper binary ("yay", "paru", or empty).
|
||||
// Exposed as static so availability can be unit-tested without helpers.
|
||||
static std::string helper();
|
||||
|
||||
// Parse `yay -Ss` output (pairs of "repo/name version" + description
|
||||
// line, with ANSI colors stripped) into packages.
|
||||
// Exposed as static so the parsing can be unit-tested without yay.
|
||||
static std::vector<PackageInfo> parseSearchOutput(const std::string& output);
|
||||
|
||||
// Parse `yay -Qm` output (one "name version" line per foreign package).
|
||||
// Exposed as static so the parsing can be unit-tested without yay.
|
||||
static std::vector<PackageInfo> parseInstalledOutput(const std::string& output);
|
||||
|
||||
// Parse `yay -Qu` output (one "name old -> new" line per outdated pkg).
|
||||
// Exposed as static so the parsing can be unit-tested without yay.
|
||||
static std::vector<PackageInfo> parseUpdatesOutput(const std::string& output);
|
||||
|
||||
std::vector<PackageInfo> search(const std::string& query) override;
|
||||
bool install(const std::string& packageName,
|
||||
ProgressCallback progressCallback) override;
|
||||
bool remove(const std::string& packageName,
|
||||
ProgressCallback progressCallback) override;
|
||||
bool update(const std::string& packageName = "",
|
||||
ProgressCallback progressCallback = nullptr) override;
|
||||
std::vector<PackageInfo> listInstalled() override;
|
||||
std::vector<PackageInfo> listUpdates() override;
|
||||
bool refresh(ProgressCallback progressCallback = nullptr) override;
|
||||
|
||||
private:
|
||||
std::string m_lastError;
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
// AUR provider plugin — an external provider loaded at runtime by
|
||||
// PluginManager from the plugins/ directory next to the executable (or in
|
||||
// ~/.local/share/PacManager/plugins/). Wraps the yay/paru helpers so AUR
|
||||
// packages show up in search/installed/updates like any other provider.
|
||||
//
|
||||
// Built by default (see the FWS_BUILD_AUR_PLUGIN CMake option).
|
||||
|
||||
#include "aur-manager.h"
|
||||
#include "provider-plugin.h"
|
||||
|
||||
extern "C" const char* fws_plugin_kind() { return "provider"; }
|
||||
extern "C" const char* fws_plugin_id() { return "aur"; }
|
||||
extern "C" const char* fws_plugin_name() { return "AUR"; }
|
||||
extern "C" const char* fws_plugin_version() { return "1.0.0"; }
|
||||
extern "C" const char* fws_plugin_description() {
|
||||
return "Paquets communautaires Arch (AUR via yay/paru)";
|
||||
}
|
||||
extern "C" const char* fws_plugin_author() { return "BlackAngelTV"; }
|
||||
extern "C" IPackageManager* fws_create_provider() { return new AurManager(); }
|
||||
// Helpers are installed from the AUR itself; the Plugins page can offer to
|
||||
// install yay when the provider is unavailable.
|
||||
extern "C" const char* fws_plugin_install_hint() { return "yay"; }
|
||||
@@ -1,55 +0,0 @@
|
||||
// Example addon plugin — a template for non-provider extensions (UI tweaks,
|
||||
// helpers, ...) written in C++.
|
||||
//
|
||||
// Unlike provider plugins (see plugins/example-provider), an addon does not
|
||||
// manage packages: it implements IPlugin (see include/plugin.h) and exports
|
||||
// the C ABI contract via the FWS_ADDON_PLUGIN macro. The host loads it, runs
|
||||
// onLoad()/onUnload() around its lifetime and hands it the main window via
|
||||
// onUiReady() so it can attach its own widgets — here a status-bar badge.
|
||||
//
|
||||
// Build with CMake from the project root:
|
||||
// cmake -B build -DFWS_BUILD_EXAMPLE_ADDON=ON && cmake --build build
|
||||
|
||||
#include "plugin.h"
|
||||
#include "provider-plugin.h"
|
||||
|
||||
#include <QLabel>
|
||||
#include <QMainWindow>
|
||||
#include <QStatusBar>
|
||||
|
||||
// A tiny UI addon: it shows a badge in the status bar while it is loaded and
|
||||
// removes it on unload. Copy this file as a starting point for real addons
|
||||
// (toolbar buttons, dashboard cards, helpers, ...).
|
||||
class ExampleAddon : public IPlugin {
|
||||
public:
|
||||
void onLoad() override { m_loaded = true; }
|
||||
void onUnload() override {
|
||||
m_loaded = false;
|
||||
if (m_badge) {
|
||||
if (m_window) m_window->statusBar()->removeWidget(m_badge);
|
||||
delete m_badge;
|
||||
m_badge = nullptr;
|
||||
m_window = nullptr;
|
||||
}
|
||||
}
|
||||
// Available only while onLoad() has run, so the host's availability check
|
||||
// also proves the lifecycle was applied.
|
||||
bool isAvailable() const override { return m_loaded; }
|
||||
|
||||
void onUiReady(QMainWindow* window) override {
|
||||
m_window = window;
|
||||
if (!m_loaded || !m_window) return;
|
||||
m_badge = new QLabel("⚡ Exemple d'addon actif");
|
||||
m_badge->setStyleSheet(
|
||||
"color: #38bdf8; font-size: 11px; font-weight: 600; padding-right: 8px;");
|
||||
m_window->statusBar()->addPermanentWidget(m_badge);
|
||||
}
|
||||
|
||||
private:
|
||||
bool m_loaded = false;
|
||||
QMainWindow* m_window = nullptr;
|
||||
QLabel* m_badge = nullptr;
|
||||
};
|
||||
|
||||
FWS_ADDON_PLUGIN(ExampleAddon, "example-addon", "Example Addon", "0.1.0",
|
||||
"Exemple d'addon : badge dans la barre de statut", "FWS");
|
||||
@@ -1,49 +0,0 @@
|
||||
// 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 Plugins page via "Recharger".
|
||||
//
|
||||
// This is a *provider* plugin: it adds a package manager. For non-provider
|
||||
// extensions (UI tweaks, helpers, ...), see plugins/example-addon instead.
|
||||
//
|
||||
// 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&, ProgressCallback) override { return false; }
|
||||
bool remove(const std::string&, ProgressCallback) override { return false; }
|
||||
bool update(const std::string&, ProgressCallback) override { return false; }
|
||||
std::vector<PackageInfo> listInstalled() override { return {}; }
|
||||
std::vector<PackageInfo> listUpdates() override { return {}; }
|
||||
bool refresh(ProgressCallback) override { return false; }
|
||||
};
|
||||
|
||||
FWS_PROVIDER_PLUGIN(SampleProvider, "sample", "Sample Provider", "0.1.0",
|
||||
"Exemple de plugin fournisseur (modèle à copier)", "FWS");
|
||||
@@ -1,1000 +0,0 @@
|
||||
#include "flatpak-manager.h"
|
||||
|
||||
#include "progress-tracker.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
#include <cctype>
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#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";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Watching a download that prints nothing
|
||||
// ---------------------------------------------------------------------------
|
||||
// flatpak has no progress meter to print while it fetches something: installing
|
||||
// a runtime is minutes of complete silence between two lines of output, on a
|
||||
// terminal as much as in a pipe (its meter is only drawn for the delta fetches
|
||||
// the CDN happens to serve). The transfer is visible though, because flatpak
|
||||
// stages it in a directory of its own and those bytes grow while it downloads.
|
||||
// Watching them is the only honest progress there is: the numbers are the ones
|
||||
// flatpak itself wrote, and they are what a user wants to see when an install
|
||||
// seems stuck — how far it has got, and how fast.
|
||||
|
||||
// Where flatpak stages a transfer: inside the repository of the installation it
|
||||
// writes to, under "<installation>/repo/tmp" — "staging-…" for the objects it is
|
||||
// fetching, "flatpak-cache-…" for the revokefs mount a system-wide install
|
||||
// streams through. The installation directories are the ones flatpak itself
|
||||
// resolves, so an override is honoured.
|
||||
static std::vector<fs::path> stagingRoots() {
|
||||
std::vector<fs::path> installations;
|
||||
|
||||
const char* userDir = std::getenv("FLATPAK_USER_DIR");
|
||||
if (userDir && *userDir) {
|
||||
installations.push_back(fs::path(userDir));
|
||||
} else {
|
||||
installations.push_back(userShareDir() / "flatpak");
|
||||
}
|
||||
|
||||
const char* systemDir = std::getenv("FLATPAK_SYSTEM_DIR");
|
||||
if (systemDir && *systemDir) {
|
||||
installations.push_back(fs::path(systemDir));
|
||||
} else {
|
||||
installations.push_back(fs::path("/var/lib/flatpak"));
|
||||
}
|
||||
|
||||
std::vector<fs::path> roots;
|
||||
for (const fs::path& dir : installations) roots.push_back(dir / "repo" / "tmp");
|
||||
return roots;
|
||||
}
|
||||
|
||||
// Bytes flatpak is currently staging, over every installation it may be writing
|
||||
// to. Zero when nothing is downloading, which is exactly what makes this usable
|
||||
// as an activity signal.
|
||||
static unsigned long long stagedBytes() {
|
||||
unsigned long long total = 0;
|
||||
for (const fs::path& root : stagingRoots()) {
|
||||
std::error_code ec;
|
||||
for (const auto& entry : fs::directory_iterator(
|
||||
root, fs::directory_options::skip_permission_denied, ec)) {
|
||||
// Only the two transient names flatpak gives a transfer; anything
|
||||
// else living there is not ours to measure.
|
||||
const std::string name = entry.path().filename().string();
|
||||
if (name.rfind("staging-", 0) != 0 && name.rfind("flatpak-cache-", 0) != 0) continue;
|
||||
|
||||
// A staging directory that is being written to, or mounted through
|
||||
// revokefs, can move under the walk: every step is error-tolerant so
|
||||
// a vanished entry is skipped instead of ending the measurement.
|
||||
std::error_code walkEc;
|
||||
for (const auto& file : fs::recursive_directory_iterator(
|
||||
entry.path(), fs::directory_options::skip_permission_denied, walkEc)) {
|
||||
std::error_code sizeEc;
|
||||
const auto size = file.is_regular_file(sizeEc) ? file.file_size(sizeEc) : 0;
|
||||
if (sizeEc) continue;
|
||||
total += static_cast<unsigned long long>(size);
|
||||
}
|
||||
}
|
||||
}
|
||||
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"};
|
||||
double value = static_cast<double>(bytes);
|
||||
std::size_t unit = 0;
|
||||
while (value >= 1024.0 && unit + 1 < sizeof(units) / sizeof(units[0])) {
|
||||
value /= 1024.0;
|
||||
++unit;
|
||||
}
|
||||
// One decimal, French separator — enough precision for a transfer, not so
|
||||
// much that the line jitters.
|
||||
char text[32];
|
||||
std::snprintf(text, sizeof(text), unit == 0 ? "%.0f %s" : "%.1f %s", value, units[unit]);
|
||||
std::string formatted(text);
|
||||
const std::size_t dot = formatted.find('.');
|
||||
if (dot != std::string::npos) formatted[dot] = ',';
|
||||
return formatted;
|
||||
}
|
||||
|
||||
// Samples the download caches while a command runs and turns what grows there
|
||||
// into progress lines. Started before the command and stopped when it returns;
|
||||
// the only thing the sampling thread does is call the provider's callback,
|
||||
// which the worker forwards to the UI.
|
||||
class DownloadWatcher {
|
||||
public:
|
||||
explicit DownloadWatcher(ProgressCallback callback) : m_callback(std::move(callback)) {
|
||||
// Nothing to report to: no thread, no walk of the staging directories.
|
||||
if (!m_callback) return;
|
||||
m_baseline = stagedBytes();
|
||||
m_thread = std::thread([this] { run(); });
|
||||
}
|
||||
|
||||
~DownloadWatcher() { stop(); }
|
||||
|
||||
DownloadWatcher(const DownloadWatcher&) = delete;
|
||||
DownloadWatcher& operator=(const DownloadWatcher&) = delete;
|
||||
|
||||
void stop() {
|
||||
m_stop = true;
|
||||
if (m_thread.joinable()) m_thread.join();
|
||||
}
|
||||
|
||||
private:
|
||||
void run() {
|
||||
// Sampling twice a second keeps the status bar alive; walking a staging
|
||||
// directory costs a couple of milliseconds (a runtime is a few hundred
|
||||
// objects, not a few hundred thousand files).
|
||||
constexpr auto kInterval = std::chrono::milliseconds(500);
|
||||
// One line every two and a half seconds, and only when at least a few
|
||||
// megabytes have landed since the last one: a line per sample would
|
||||
// repeat the same total and drown the journal. When nothing moves the
|
||||
// watcher stays quiet, and the window's heartbeat is what then says the
|
||||
// operation is alive.
|
||||
constexpr auto kReportEvery = std::chrono::milliseconds(2500);
|
||||
constexpr unsigned long long kMinStepBytes = 4ull << 20; // 4 Mio
|
||||
|
||||
auto lastReport = std::chrono::steady_clock::now();
|
||||
unsigned long long reported = 0;
|
||||
|
||||
while (!m_stop) {
|
||||
std::this_thread::sleep_for(kInterval);
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const unsigned long long total = stagedBytes();
|
||||
if (m_stop || !m_callback) return;
|
||||
|
||||
// flatpak empties its staging directory as it moves the objects into
|
||||
// the repository, so a total below the baseline means the transfer is
|
||||
// over rather than that bytes went missing.
|
||||
const unsigned long long done = total > m_baseline ? total - m_baseline : 0;
|
||||
if (done < reported + kMinStepBytes) continue;
|
||||
if (now - lastReport < kReportEvery) continue;
|
||||
|
||||
// The speed is measured over the whole window rather than the last
|
||||
// sample: half a second is short enough to make it jump around.
|
||||
const double seconds = std::chrono::duration<double>(now - lastReport).count();
|
||||
const unsigned long long perSecond =
|
||||
seconds > 0.0
|
||||
? static_cast<unsigned long long>((done - reported) / seconds)
|
||||
: 0;
|
||||
reported = done;
|
||||
lastReport = now;
|
||||
|
||||
m_callback("⬇ " + humanBytes(done) + " téléchargés"
|
||||
+ (perSecond > 0
|
||||
? " (" + humanBytes(perSecond) + "/s)"
|
||||
: ""),
|
||||
-1);
|
||||
}
|
||||
}
|
||||
|
||||
ProgressCallback m_callback;
|
||||
std::thread m_thread;
|
||||
std::atomic<bool> m_stop{false};
|
||||
// Whatever was already staged when the command started: a leftover from an
|
||||
// interrupted run must not be counted as this operation's progress.
|
||||
unsigned long long m_baseline = 0;
|
||||
};
|
||||
|
||||
// Every mutating flatpak command runs with the download watcher alongside: the
|
||||
// commands themselves stay silent for minutes at a time, and these are the only
|
||||
// lines the user gets while a runtime comes down.
|
||||
static std::string runFlatpak(const std::string& command, ProgressCallback callback) {
|
||||
DownloadWatcher watcher(callback);
|
||||
return runWithProgress(command, callback);
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
static std::string toLower(std::string text) {
|
||||
std::transform(text.begin(), text.end(), text.begin(),
|
||||
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
||||
return text;
|
||||
}
|
||||
|
||||
// Last component of a path or URL, without any query/fragment: the only part a
|
||||
// file is identified by, whatever the transport it came from.
|
||||
static std::string fileName(const std::string& path) {
|
||||
std::string cleaned = path;
|
||||
const std::size_t cut = cleaned.find_first_of("?#");
|
||||
if (cut != std::string::npos) cleaned.erase(cut);
|
||||
const std::size_t slash = cleaned.find_last_of('/');
|
||||
return slash == std::string::npos ? cleaned : cleaned.substr(slash + 1);
|
||||
}
|
||||
|
||||
static bool endsWith(const std::string& text, const std::string& suffix) {
|
||||
return text.size() >= suffix.size()
|
||||
&& text.compare(text.size() - suffix.size(), suffix.size(), suffix) == 0;
|
||||
}
|
||||
|
||||
// Quote one argument for the shell popen() runs, so a dropped file whose name
|
||||
// contains spaces or quotes still reaches flatpak as a single argument.
|
||||
static std::string shellQuote(const std::string& value) {
|
||||
std::string quoted = "'";
|
||||
for (char c : value) {
|
||||
if (c == '\'') quoted += "'\\''";
|
||||
else quoted += c;
|
||||
}
|
||||
quoted += "'";
|
||||
return quoted;
|
||||
}
|
||||
|
||||
// Split a flatpak --columns line. flatpak emits tab-separated fields with that
|
||||
// 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);
|
||||
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;
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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 = splitColumnsByPosition(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;
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
FlatpakManager::FileKind FlatpakManager::classifyFile(const std::string& path) {
|
||||
const std::string name = toLower(fileName(path));
|
||||
|
||||
// A bundle's extension is a prefix of the ref one's (.flatpak vs
|
||||
// .flatpakref), so the longer names are matched first.
|
||||
if (endsWith(name, ".flatpakref")) return FileKind::Ref;
|
||||
if (endsWith(name, ".flatpakrepo")) return FileKind::Repo;
|
||||
if (endsWith(name, ".flatpak")) return FileKind::Bundle;
|
||||
return FileKind::None;
|
||||
}
|
||||
|
||||
std::string FlatpakManager::repoNamespace(const std::string& path) {
|
||||
std::string name = toLower(fileName(path));
|
||||
const std::size_t dot = name.find_last_of('.');
|
||||
if (dot != std::string::npos) name = name.substr(0, dot);
|
||||
// flatpak requires a name, and a nameless path would otherwise register a
|
||||
// remote that cannot be typed back.
|
||||
return name.empty() ? "flatpak-repo" : name;
|
||||
}
|
||||
|
||||
std::string FlatpakManager::installFileCommand(FileKind kind, const std::string& path,
|
||||
bool userScope) {
|
||||
const std::string scope = userScope ? "--user " : "";
|
||||
if (kind == FileKind::Repo) {
|
||||
// A .flatpakrepo only defines a remote: --if-not-exists makes re-opening
|
||||
// the same file a no-op instead of an error.
|
||||
return "flatpak remote-add --if-not-exists " + scope + repoNamespace(path)
|
||||
+ " " + shellQuote(path) + " 2>&1";
|
||||
}
|
||||
// A ref file names the remote it needs and a bundle embeds its runtime, so
|
||||
// both are installed by handing the file itself to `flatpak install`.
|
||||
return "flatpak install --noninteractive --assumeyes " + scope + shellQuote(path)
|
||||
+ " 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
|
||||
// integration needs it (see integrateDesktopEntries).
|
||||
static std::set<std::string> appIdsInOutput(const std::string& output) {
|
||||
std::set<std::string> ids;
|
||||
std::istringstream iss(output);
|
||||
std::string line;
|
||||
while (std::getline(iss, line)) {
|
||||
std::istringstream fields(line);
|
||||
std::string token;
|
||||
while (fields >> token) {
|
||||
const std::size_t slash = token.find('/');
|
||||
if (slash != std::string::npos) token = token.substr(0, slash);
|
||||
const std::size_t colon = token.find(':');
|
||||
if (colon != std::string::npos) token = token.substr(colon + 1);
|
||||
if (isAppId(token)) ids.insert(token);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
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() {
|
||||
// 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() {
|
||||
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,
|
||||
ProgressCallback 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é.", -1);
|
||||
integrateDesktopEntries(packageName);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (progressCallback) progressCallback("Installation de " + packageName + "...", -1);
|
||||
|
||||
// Installs stream their output: flatpak reports "Installing 1/3…" and the
|
||||
// percentage of the file it is unpacking, which drives the UI progress bar.
|
||||
auto tryInstall = [&](const std::string& extra) {
|
||||
return runFlatpak("flatpak install --noninteractive --assumeyes " + extra
|
||||
+ " " + packageName + " 2>&1",
|
||||
progressCallback);
|
||||
};
|
||||
|
||||
// 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...", -1);
|
||||
runFlatpak("flatpak update --appstream 2>&1", progressCallback);
|
||||
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...", -1);
|
||||
output = tryInstall("--user flathub");
|
||||
}
|
||||
|
||||
// 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,
|
||||
ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
|
||||
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 (progressCallback) {
|
||||
progressCallback(
|
||||
targeted ? "Suppression de " + appId + " (" + installation + ")..."
|
||||
: "Suppression de " + packageName + "...",
|
||||
-1);
|
||||
}
|
||||
|
||||
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,
|
||||
ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
auto tryUpdate = [&](const std::string& extra) {
|
||||
std::string command = "flatpak update --noninteractive --assumeyes " + extra;
|
||||
if (!packageName.empty()) command += " " + packageName;
|
||||
return runFlatpak(command + " 2>&1", progressCallback);
|
||||
};
|
||||
|
||||
if (packageName.empty()) {
|
||||
if (progressCallback) progressCallback("Mise à jour de toutes les applications...", -1);
|
||||
} else {
|
||||
if (progressCallback) progressCallback("Mise à jour de " + packageName + "...", -1);
|
||||
}
|
||||
|
||||
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);
|
||||
output = tryUpdate("--user");
|
||||
}
|
||||
|
||||
if (output.find("error:") != std::string::npos) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FlatpakManager::refresh(ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
if (progressCallback) progressCallback("Rafraîchissement des métadonnées Flatpak...", -1);
|
||||
|
||||
// Re-download the appstream metadata of every remote so search and
|
||||
// update detection reflect the latest published versions.
|
||||
std::string output = runFlatpak("flatpak update --appstream 2>&1", progressCallback);
|
||||
|
||||
// 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 = runFlatpak("flatpak update --appstream --user 2>&1", 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;
|
||||
}
|
||||
|
||||
bool FlatpakManager::canInstallFile(const std::string& path) const {
|
||||
return classifyFile(path) != FileKind::None;
|
||||
}
|
||||
|
||||
bool FlatpakManager::installFile(const std::string& path,
|
||||
ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
|
||||
const FileKind kind = classifyFile(path);
|
||||
if (kind == FileKind::None) {
|
||||
m_lastError = "Format Flatpak non reconnu : " + path;
|
||||
return false;
|
||||
}
|
||||
|
||||
// A file install accepts a local path (what the user drops or opens) and an
|
||||
// URL (.flatpakref links served over https); only the local case can be
|
||||
// checked before flatpak runs.
|
||||
const bool isUrl = path.rfind("http://", 0) == 0 || path.rfind("https://", 0) == 0;
|
||||
if (!isUrl) {
|
||||
std::error_code ec;
|
||||
if (!fs::is_regular_file(path, ec)) {
|
||||
m_lastError = "Fichier introuvable : " + path;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Registering a repository is the whole job, and the per-user scope avoids
|
||||
// polkit on a machine where the user is not an administrator.
|
||||
if (kind == FileKind::Repo) {
|
||||
if (progressCallback) {
|
||||
progressCallback("Ajout du dépôt " + repoNamespace(path) + "...", -1);
|
||||
}
|
||||
const std::string output =
|
||||
runFlatpak(installFileCommand(kind, path, /*userScope=*/true), progressCallback);
|
||||
if (output.find("error:") != std::string::npos) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (progressCallback) {
|
||||
progressCallback(kind == FileKind::Ref
|
||||
? "Installation depuis " + path + "..."
|
||||
: "Installation du paquet " + path + "...",
|
||||
-1);
|
||||
}
|
||||
|
||||
std::string output = runFlatpak(installFileCommand(kind, path, /*userScope=*/false),
|
||||
progressCallback);
|
||||
// A system-wide install needs polkit: fall back to the per-user one, exactly
|
||||
// like a name-based install does.
|
||||
if (output.find("error:") != std::string::npos) {
|
||||
if (progressCallback) progressCallback("Nouvel essai en mode utilisateur...", -1);
|
||||
output = runFlatpak(installFileCommand(kind, path, /*userScope=*/true), progressCallback);
|
||||
}
|
||||
|
||||
if (output.find("error:") != std::string::npos) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Same launcher integration as a name-based install (see
|
||||
// integrateDesktopEntries), on the ids flatpak just reported. When the file
|
||||
// installed an app whose id cannot be read from the output, every installed
|
||||
// app is re-linked instead: missing the integration would leave the app
|
||||
// invisible in the desktop menu.
|
||||
const std::set<std::string> appIds = appIdsInOutput(output);
|
||||
if (appIds.empty()) {
|
||||
integrateAllInstalled();
|
||||
} else {
|
||||
for (const auto& appId : appIds) integrateDesktopEntries(appId);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FlatpakManager::cleanCache(ProgressCallback progressCallback) {
|
||||
m_lastError.clear();
|
||||
if (progressCallback) {
|
||||
progressCallback("Suppression des runtimes Flatpak inutilisés...", -1);
|
||||
}
|
||||
|
||||
// Runtimes left behind by uninstalled applications weigh several hundred
|
||||
// megabytes each; flatpak only removes those no installed app references.
|
||||
std::string output = runFlatpak(
|
||||
"flatpak uninstall --unused --noninteractive --assumeyes 2>&1", progressCallback);
|
||||
|
||||
if (output.find("error:") != std::string::npos) {
|
||||
m_lastError = lastOutputLines(output);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
#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);
|
||||
|
||||
// The Flatpak file formats the app accepts from the window (drag & drop) and
|
||||
// from the file manager ("Ouvrir avec PacManager").
|
||||
enum class FileKind { None, Ref, Repo, Bundle };
|
||||
|
||||
// Classify by extension, ignoring case and any URL query/fragment, so a
|
||||
// local path and a flathub URL are both recognised. Exposed as static so the
|
||||
// routing can be unit-tested without flatpak.
|
||||
static FileKind classifyFile(const std::string& path);
|
||||
|
||||
// Command that installs a ref or bundle file, or registers a repository
|
||||
// (.flatpakrepo). Exposed so the exact command line is testable without
|
||||
// running flatpak.
|
||||
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>`.
|
||||
static std::string repoNamespace(const std::string& path);
|
||||
|
||||
std::vector<PackageInfo> search(const std::string& query) override;
|
||||
bool install(const std::string& packageName,
|
||||
ProgressCallback progressCallback) override;
|
||||
bool remove(const std::string& packageName,
|
||||
ProgressCallback progressCallback) override;
|
||||
bool update(const std::string& packageName = "",
|
||||
ProgressCallback progressCallback = nullptr) override;
|
||||
std::vector<PackageInfo> listInstalled() override;
|
||||
std::vector<PackageInfo> listUpdates() override;
|
||||
bool refresh(ProgressCallback progressCallback = nullptr) override;
|
||||
|
||||
// Cleanup: flatpak knows which runtimes no installed application uses any
|
||||
// more, so it can reclaim them from the maintenance page.
|
||||
bool canCleanCache() const override { return true; }
|
||||
bool cleanCache(ProgressCallback progressCallback = nullptr) override;
|
||||
|
||||
// Install from a Flatpak file: a `.flatpakref` (an application reference
|
||||
// served by a remote), a `.flatpakrepo` (a remote definition) or a `.flatpak`
|
||||
// bundle. Unlike a name-based install these come from the user's disk or a
|
||||
// URL, so flatpak resolves the remote itself.
|
||||
bool canInstallFile(const std::string& path) const override;
|
||||
bool installFile(const std::string& path, ProgressCallback progressCallback) 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;
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
// Flatpak provider plugin — an external provider loaded at runtime by
|
||||
// PluginManager from the plugins/ directory next to the executable (or in
|
||||
// ~/.local/share/PacManager/plugins/). It exports the C ABI contract declared
|
||||
// in provider-plugin.h so the host can query metadata, check the backing tool,
|
||||
// and instantiate the manager without any compiled-in Flatpak support.
|
||||
//
|
||||
// Built by default (see the FWS_BUILD_FLATPAK_PLUGIN CMake option): the
|
||||
// flatpak-provider-plugin target compiles this file together with
|
||||
// flatpak-manager.cpp into libflatpak-provider.so and copies it next to the
|
||||
// PacManager binary, so a default build ships with Flatpak support enabled.
|
||||
|
||||
#include "flatpak-manager.h"
|
||||
#include "provider-plugin.h"
|
||||
|
||||
extern "C" const char* fws_plugin_kind() { return "provider"; }
|
||||
extern "C" const char* fws_plugin_id() { return "flatpak"; }
|
||||
extern "C" const char* fws_plugin_name() { return "Flatpak"; }
|
||||
extern "C" const char* fws_plugin_version() { return "1.0.0"; }
|
||||
extern "C" const char* fws_plugin_description() {
|
||||
return "Gestionnaire d'applications Flatpak";
|
||||
}
|
||||
extern "C" const char* fws_plugin_author() { return "BlackAngelTV"; }
|
||||
extern "C" IPackageManager* fws_create_provider() { return new FlatpakManager(); }
|
||||
// The backing tool is installed by the pacman package "flatpak"; exposing it
|
||||
// lets the Plugins page offer to install the missing tool.
|
||||
extern "C" const char* fws_plugin_install_hint() { return "flatpak"; }
|
||||
@@ -0,0 +1,253 @@
|
||||
#include "plugin-manager.h"
|
||||
#include "app-logging.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QCoreApplication>
|
||||
|
||||
// Plugin directories, checked in order. Bundled plugins ship next to the
|
||||
// executable (<prefix>/bin/plugins after install); 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";
|
||||
// System-wide plugins: <prefix>/lib/PacManager/plugins for installs to
|
||||
// /usr or /usr/local (covers both lib and lib64 layouts).
|
||||
const QString appDir = QCoreApplication::applicationDirPath();
|
||||
QDir prefix(appDir);
|
||||
if (prefix.dirName() == QLatin1String("bin") && prefix.cdUp()) {
|
||||
paths << prefix.absoluteFilePath("lib/PacManager/plugins");
|
||||
paths << prefix.absoluteFilePath("lib64/PacManager/plugins");
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
// Run a plugin's teardown and free what the host owns: the addon/provider
|
||||
// instance (after onUnload) and the library it was compiled into.
|
||||
static void unloadEntry(PluginManager::PluginEntry& entry) {
|
||||
if (entry.plugin) {
|
||||
entry.plugin->onUnload();
|
||||
delete entry.plugin;
|
||||
entry.plugin = nullptr;
|
||||
}
|
||||
if (entry.manager) {
|
||||
delete entry.manager;
|
||||
entry.manager = nullptr;
|
||||
}
|
||||
delete entry.library;
|
||||
entry.library = nullptr;
|
||||
}
|
||||
|
||||
PluginManager::PluginManager() = default;
|
||||
|
||||
PluginManager::~PluginManager() {
|
||||
// Unload plugins first (they may run code), then the libraries they were
|
||||
// compiled into.
|
||||
for (auto& entry : m_plugins) {
|
||||
unloadEntry(entry);
|
||||
}
|
||||
}
|
||||
|
||||
void PluginManager::registerBuiltin(PluginInfo info, IPackageManager* manager) {
|
||||
info.builtin = true;
|
||||
info.available = manager->isAvailable();
|
||||
m_plugins.push_back({std::move(info), nullptr, manager, nullptr});
|
||||
}
|
||||
|
||||
// Load a single shared library as a plugin. Returns false (without erroring)
|
||||
// when the file is not a plugin, so unrelated libraries in the directory are
|
||||
// skipped. The plugin's kind decides which create function is resolved:
|
||||
// "addon" -> IPlugin (see plugin.h), anything else -> IPackageManager.
|
||||
bool PluginManager::loadPluginFile(const QString& filePath) {
|
||||
typedef const char* (*MetaFn)();
|
||||
typedef IPackageManager* (*CreateProviderFn)();
|
||||
typedef IPlugin* (*CreatePluginFn)();
|
||||
|
||||
// Own the library for the lifetime of the plugin: it must stay loaded
|
||||
// as long as the addon/manager instance created from it exists.
|
||||
QLibrary* library = new QLibrary(filePath);
|
||||
if (!library->load()) {
|
||||
qCWarning(pacmgrPlugin) << "not a loadable plugin, skipping" << filePath
|
||||
<< library->errorString();
|
||||
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"));
|
||||
MetaFn kindFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_kind"));
|
||||
CreateProviderFn createProviderFn =
|
||||
reinterpret_cast<CreateProviderFn>(library->resolve("fws_create_provider"));
|
||||
CreatePluginFn createPluginFn =
|
||||
reinterpret_cast<CreatePluginFn>(library->resolve("fws_create_plugin"));
|
||||
// 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) {
|
||||
library->unload();
|
||||
delete library;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Reject plugins whose id collides with an already registered plugin.
|
||||
const std::string id = idFn();
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.info.id == id) {
|
||||
library->unload();
|
||||
delete library;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Kind defaults to "provider" so legacy plugins without the symbol keep
|
||||
// loading; "addon" requires the matching create function.
|
||||
const std::string kind = kindFn ? kindFn() : "provider";
|
||||
const bool isAddon = (kind == "addon");
|
||||
if ((isAddon && !createPluginFn) || (!isAddon && !createProviderFn)) {
|
||||
library->unload();
|
||||
delete library;
|
||||
return false;
|
||||
}
|
||||
|
||||
PluginInfo info;
|
||||
info.id = id;
|
||||
info.name = nameFn();
|
||||
info.version = versionFn();
|
||||
info.description = descFn();
|
||||
info.author = authorFn();
|
||||
info.kind = isAddon ? PluginKind::Addon : PluginKind::Provider;
|
||||
info.path = filePath.toStdString();
|
||||
if (installHintFn && installHintFn() && *installHintFn()) {
|
||||
info.installHint = installHintFn();
|
||||
}
|
||||
|
||||
if (isAddon) {
|
||||
IPlugin* plugin = createPluginFn();
|
||||
plugin->onLoad();
|
||||
info.available = plugin->isAvailable();
|
||||
m_plugins.push_back({std::move(info), plugin, nullptr, library});
|
||||
} else {
|
||||
IPackageManager* manager = createProviderFn();
|
||||
info.available = manager->isAvailable();
|
||||
m_plugins.push_back({std::move(info), nullptr, manager, library});
|
||||
}
|
||||
qCDebug(pacmgrPlugin) << "loaded" << (isAddon ? "addon" : "provider")
|
||||
<< filePath << "available" << m_plugins.back().info.available;
|
||||
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_plugins.begin(); it != m_plugins.end();) {
|
||||
if (!it->info.builtin) {
|
||||
unloadEntry(*it);
|
||||
it = m_plugins.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_plugins) {
|
||||
if (entry.plugin) {
|
||||
entry.info.available = entry.plugin->isAvailable();
|
||||
} else {
|
||||
entry.info.available = entry.manager->isAvailable();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<PluginManager::PluginEntry>& PluginManager::plugins() const {
|
||||
return m_plugins;
|
||||
}
|
||||
|
||||
std::vector<const PluginManager::PluginEntry*> PluginManager::availableProviders() const {
|
||||
std::vector<const PluginEntry*> result;
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.manager && 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_plugins) {
|
||||
if (entry.manager && entry.info.available && isEnabled(entry.info.id)) {
|
||||
result.push_back(entry.manager);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const PluginManager::PluginEntry* PluginManager::findAvailable(const std::string& id) const {
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.info.id == id && entry.manager && entry.info.available
|
||||
&& isEnabled(entry.info.id)) {
|
||||
return &entry;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<IPlugin*> PluginManager::availableAddons() const {
|
||||
std::vector<IPlugin*> result;
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.plugin && entry.info.available && isEnabled(entry.info.id)) {
|
||||
result.push_back(entry.plugin);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
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_plugins) {
|
||||
if (entry.info.id == id) return entry.manager;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include "provider-plugin.h"
|
||||
#include <QSettings>
|
||||
#include <QLibrary>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Registry of every plugin known to the application. It owns each plugin
|
||||
// (built-in and external), loads shared-library plugins dropped in the plugin
|
||||
// directories at runtime (see PluginManager::scanDirectory) and tracks which
|
||||
// are enabled in the settings. A plugin is either a package-manager provider
|
||||
// (implements IPackageManager) or a generic addon (implements IPlugin) — both
|
||||
// kinds share the same loading, lifecycle and enable/disable flow.
|
||||
class PluginManager {
|
||||
public:
|
||||
struct PluginEntry {
|
||||
PluginInfo info;
|
||||
IPlugin* plugin = nullptr; // non-null for addon plugins
|
||||
IPackageManager* manager = nullptr; // non-null for provider plugins
|
||||
QLibrary* library = nullptr; // owned by the PluginManager; null for built-ins
|
||||
};
|
||||
|
||||
PluginManager();
|
||||
~PluginManager();
|
||||
|
||||
// Register a provider compiled into the application (e.g. pacman).
|
||||
// Takes ownership of the manager.
|
||||
void registerBuiltin(PluginInfo info, IPackageManager* manager);
|
||||
|
||||
// Scan the plugin directories for external plugins and load them.
|
||||
void discoverExternal();
|
||||
|
||||
// Drop external plugins and rescan their directories; built-in plugins
|
||||
// are kept (their instances stay valid).
|
||||
void reload();
|
||||
|
||||
// Re-run isAvailable() on every plugin (e.g. after the app installed a
|
||||
// missing tool) so the Plugins page reflects reality.
|
||||
void refreshAvailability();
|
||||
|
||||
// All known plugins, in registration order.
|
||||
const std::vector<PluginEntry>& plugins() const;
|
||||
|
||||
// Provider plugins that are enabled (in settings) and whose tool is on the
|
||||
// system.
|
||||
std::vector<const PluginEntry*> 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 PluginEntry* findAvailable(const std::string& id) const;
|
||||
|
||||
// Addon plugins that are enabled and available (e.g. to hand the main
|
||||
// window to via IPlugin::onUiReady).
|
||||
std::vector<IPlugin*> availableAddons() 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<PluginEntry> m_plugins;
|
||||
QSettings m_settings;
|
||||
};
|
||||
@@ -0,0 +1,329 @@
|
||||
#include "plugin-package.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QSaveFile>
|
||||
#include <QSettings>
|
||||
|
||||
#include "app-logging.h"
|
||||
|
||||
// The per-user plugin directory, shared with PluginManager's search paths: what
|
||||
// a package installs lands exactly where a hand-copied library would, so the
|
||||
// registry needs nothing else to pick it up.
|
||||
static const char* kUserPluginDir = "/.local/share/PacManager/plugins";
|
||||
|
||||
// The manifest a package must carry, and the name the format is versioned
|
||||
// under. A package declaring another version is refused rather than guessed at.
|
||||
static const char* kManifestName = "plugin.json";
|
||||
|
||||
PluginPackage::PluginPackage(QObject* parent) : QObject(parent) {}
|
||||
|
||||
QString PluginPackage::suffix() {
|
||||
return QStringLiteral(".fwspacm");
|
||||
}
|
||||
|
||||
bool PluginPackage::isPackagePath(const QString& path) {
|
||||
return path.trimmed().endsWith(suffix(), Qt::CaseInsensitive);
|
||||
}
|
||||
|
||||
QString PluginPackage::librarySuffix() {
|
||||
#ifdef Q_OS_WIN
|
||||
return QStringLiteral(".dll");
|
||||
#elif defined(Q_OS_MACOS)
|
||||
return QStringLiteral(".dylib");
|
||||
#else
|
||||
return QStringLiteral(".so");
|
||||
#endif
|
||||
}
|
||||
|
||||
QString PluginPackage::installDirectory() const {
|
||||
if (!m_installDirectory.isEmpty()) return m_installDirectory;
|
||||
return QDir::homePath() + QLatin1String(kUserPluginDir);
|
||||
}
|
||||
|
||||
void PluginPackage::setInstallDirectory(const QString& path) {
|
||||
m_installDirectory = path;
|
||||
}
|
||||
|
||||
QString PluginPackage::installedKey(const QString& id) {
|
||||
return QStringLiteral("packages/installed/%1").arg(id);
|
||||
}
|
||||
|
||||
QString PluginPackage::installedKeyPrefix() {
|
||||
return QStringLiteral("packages/installed/");
|
||||
}
|
||||
|
||||
bool PluginPackage::isInstalled(const QString& id) const {
|
||||
return !installedPath(id).isEmpty();
|
||||
}
|
||||
|
||||
QString PluginPackage::installedPath(const QString& id) const {
|
||||
QSettings settings;
|
||||
const QString path = settings.value(installedKey(id)).toString();
|
||||
// A file deleted behind our back is not installed any more: the state
|
||||
// follows the disk, which is also what makes an uninstall of a missing
|
||||
// library a no-op rather than a failure.
|
||||
if (path.isEmpty() || !QFile::exists(path)) return QString();
|
||||
return path;
|
||||
}
|
||||
|
||||
QStringList PluginPackage::installedIds() const {
|
||||
QSettings settings;
|
||||
QStringList ids;
|
||||
const QString prefix = installedKeyPrefix();
|
||||
// allKeys(), not childKeys(): the ids sit one level below the prefix, and
|
||||
// childKeys() would only report the "installed" group itself.
|
||||
for (const QString& key : settings.allKeys()) {
|
||||
if (!key.startsWith(prefix)) continue;
|
||||
const QString id = key.mid(prefix.size());
|
||||
if (id.isEmpty() || !isInstalled(id)) continue;
|
||||
ids << id;
|
||||
}
|
||||
ids.sort();
|
||||
return ids;
|
||||
}
|
||||
|
||||
QString PluginPackage::targetFileName(const Manifest& manifest, const ZipArchive& archive,
|
||||
QString* error) {
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return QString();
|
||||
};
|
||||
|
||||
const QString suffix = librarySuffix();
|
||||
|
||||
// A manifest naming its library is trusted, but only as far as a name that
|
||||
// is safe to write: the entry is looked up in the archive, and what lands
|
||||
// in the plugin directory is a bare file name, never a path.
|
||||
if (!manifest.library.isEmpty()) {
|
||||
if (!ZipArchive::isSafeEntryName(manifest.library)
|
||||
|| manifest.library.contains(QLatin1Char('/'))
|
||||
|| manifest.library.contains(QLatin1Char('\\'))) {
|
||||
return fail(QStringLiteral("Nom de bibliothèque refusé : %1.")
|
||||
.arg(manifest.library));
|
||||
}
|
||||
if (!archive.contains(manifest.library)) {
|
||||
return fail(QStringLiteral("L'archive ne contient pas %1.")
|
||||
.arg(manifest.library));
|
||||
}
|
||||
// The directory is scanned for shared libraries, so an entry that is
|
||||
// not one would be written and then ignored.
|
||||
if (!manifest.library.endsWith(suffix, Qt::CaseInsensitive)) {
|
||||
return fail(QStringLiteral("%1 n'est pas une bibliothèque partagée (%2).")
|
||||
.arg(manifest.library, suffix));
|
||||
}
|
||||
return manifest.library;
|
||||
}
|
||||
|
||||
// Otherwise the library is the archive's single shared-library entry. More
|
||||
// than one would be ambiguous: picking one silently is how the wrong file
|
||||
// gets installed.
|
||||
QStringList candidates;
|
||||
for (const QString& name : archive.fileNames()) {
|
||||
if (name.endsWith(suffix, Qt::CaseInsensitive)) candidates << name;
|
||||
}
|
||||
if (candidates.isEmpty()) {
|
||||
return fail(QStringLiteral("L'archive ne contient aucune bibliothèque partagée (%1).")
|
||||
.arg(suffix));
|
||||
}
|
||||
if (candidates.size() > 1) {
|
||||
return fail(QStringLiteral("L'archive contient plusieurs bibliothèques : %1. "
|
||||
"Nommez celle à installer avec \"library\".")
|
||||
.arg(candidates.join(QStringLiteral(", "))));
|
||||
}
|
||||
return candidates.first();
|
||||
}
|
||||
|
||||
PluginPackage::Manifest PluginPackage::parseManifest(const QByteArray& json,
|
||||
const ZipArchive& archive, QString* error) {
|
||||
Manifest manifest;
|
||||
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return Manifest{};
|
||||
};
|
||||
|
||||
QJsonParseError parseError{};
|
||||
const QJsonDocument document = QJsonDocument::fromJson(json, &parseError);
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
return fail(QStringLiteral("Manifeste illisible : %1").arg(parseError.errorString()));
|
||||
}
|
||||
if (!document.isObject()) {
|
||||
return fail(QStringLiteral("Manifeste illisible : objet JSON attendu."));
|
||||
}
|
||||
|
||||
const QJsonObject root = document.object();
|
||||
manifest.format = root.value(QStringLiteral("format")).toInt(0);
|
||||
manifest.id = root.value(QStringLiteral("id")).toString().trimmed();
|
||||
manifest.name = root.value(QStringLiteral("name")).toString().trimmed();
|
||||
manifest.description = root.value(QStringLiteral("description")).toString().trimmed();
|
||||
manifest.version = root.value(QStringLiteral("version")).toString().trimmed();
|
||||
manifest.author = root.value(QStringLiteral("author")).toString().trimmed();
|
||||
manifest.kind = root.value(QStringLiteral("kind")).toString().trimmed().toLower();
|
||||
manifest.library = root.value(QStringLiteral("library")).toString().trimmed();
|
||||
manifest.sha256 = root.value(QStringLiteral("sha256")).toString().trimmed().toLower();
|
||||
|
||||
// The format is versioned so a future layout can be told apart from this
|
||||
// one; guessing would mean reading a package as something it is not.
|
||||
if (manifest.format != 1) {
|
||||
return fail(QStringLiteral("Format de paquet non pris en charge (%1).")
|
||||
.arg(manifest.format));
|
||||
}
|
||||
if (manifest.id.isEmpty()) {
|
||||
return fail(QStringLiteral("Manifeste sans \"id\"."));
|
||||
}
|
||||
// The id becomes a settings key, so the characters that would need quoting
|
||||
// there (a slash among them) are refused rather than sanitised into
|
||||
// something that would later mismatch.
|
||||
static const QString kForbidden = QStringLiteral("/\\\"");
|
||||
for (const QChar c : kForbidden) {
|
||||
if (manifest.id.contains(c)) {
|
||||
return fail(QStringLiteral("Identifiant refusé : %1").arg(manifest.id));
|
||||
}
|
||||
}
|
||||
// An unstated kind stays empty: the real kind is the one the library
|
||||
// declares once the registry loads it.
|
||||
if (manifest.kind != QLatin1String("provider") && manifest.kind != QLatin1String("addon")) {
|
||||
manifest.kind.clear();
|
||||
}
|
||||
|
||||
// Refused here rather than at write time, so an unusable package is
|
||||
// reported before anything is extracted.
|
||||
QString nameError;
|
||||
const QString target = targetFileName(manifest, archive, &nameError);
|
||||
if (target.isEmpty()) return fail(nameError);
|
||||
manifest.library = target;
|
||||
|
||||
if (error) error->clear();
|
||||
return manifest;
|
||||
}
|
||||
|
||||
PluginPackage::Contents PluginPackage::read(const QString& path, QString* error) {
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return Contents{};
|
||||
};
|
||||
|
||||
ZipArchive archive;
|
||||
if (!archive.open(path, error)) return fail(error ? *error : QString());
|
||||
|
||||
// The manifest is matched case-insensitively, so a package zipped on
|
||||
// Windows (where the name may have been uppercased) still installs.
|
||||
int manifestIndex = archive.indexOf(QLatin1String(kManifestName));
|
||||
if (manifestIndex < 0) {
|
||||
for (const QString& name : archive.fileNames()) {
|
||||
if (name.compare(QLatin1String(kManifestName), Qt::CaseInsensitive) == 0) {
|
||||
manifestIndex = archive.indexOf(name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (manifestIndex < 0) {
|
||||
return fail(QStringLiteral("Paquet invalide : %1 est introuvable.")
|
||||
.arg(QLatin1String(kManifestName)));
|
||||
}
|
||||
|
||||
const QByteArray manifestJson = archive.read(archive.entries()[static_cast<size_t>(manifestIndex)].name, error);
|
||||
if (error && !error->isEmpty()) return fail(*error);
|
||||
|
||||
Manifest manifest = parseManifest(manifestJson, archive, error);
|
||||
if (error && !error->isEmpty()) return fail(*error);
|
||||
|
||||
QByteArray library = archive.read(manifest.library, error);
|
||||
if (error && !error->isEmpty()) return fail(*error);
|
||||
if (library.isEmpty()) {
|
||||
return fail(QStringLiteral("La bibliothèque %1 est vide.").arg(manifest.library));
|
||||
}
|
||||
|
||||
// The checksum is the one guarantee about *which* bytes run: a package whose
|
||||
// library does not match what its manifest announces is never written.
|
||||
if (!manifest.sha256.isEmpty()) {
|
||||
const QString digest = QString::fromLatin1(
|
||||
QCryptographicHash::hash(library, QCryptographicHash::Sha256).toHex());
|
||||
if (digest.compare(manifest.sha256, Qt::CaseInsensitive) != 0) {
|
||||
return fail(QStringLiteral("Somme de contrôle invalide (attendu %1).")
|
||||
.arg(manifest.sha256));
|
||||
}
|
||||
}
|
||||
|
||||
Contents contents;
|
||||
contents.manifest = manifest;
|
||||
contents.library = library;
|
||||
contents.libraryName = manifest.library;
|
||||
if (error) error->clear();
|
||||
return contents;
|
||||
}
|
||||
|
||||
void PluginPackage::install(const QString& path) {
|
||||
const QString trimmed = path.trimmed();
|
||||
if (trimmed.isEmpty()) {
|
||||
emit installFinished(QString(), false, QStringLiteral("Aucun paquet à installer."));
|
||||
return;
|
||||
}
|
||||
if (!isPackagePath(trimmed)) {
|
||||
emit installFinished(QFileInfo(trimmed).completeBaseName(), false,
|
||||
QStringLiteral("Ce fichier n'est pas un paquet %1.")
|
||||
.arg(suffix()));
|
||||
return;
|
||||
}
|
||||
|
||||
QString error;
|
||||
const Contents contents = read(trimmed, &error);
|
||||
if (contents.library.isEmpty()) {
|
||||
const QString id = contents.manifest.id.isEmpty()
|
||||
? QFileInfo(trimmed).completeBaseName()
|
||||
: contents.manifest.id;
|
||||
emit installFinished(id, false, error);
|
||||
return;
|
||||
}
|
||||
|
||||
const QString directory = installDirectory();
|
||||
if (!QDir().mkpath(directory)) {
|
||||
emit installFinished(contents.manifest.id, false,
|
||||
QStringLiteral("Impossible de créer %1.").arg(directory));
|
||||
return;
|
||||
}
|
||||
|
||||
const QString target = QDir(directory).filePath(contents.libraryName);
|
||||
// Written through QSaveFile so the library only ever appears in the scanned
|
||||
// directory complete, under its final name. A rejected commit (a read-only
|
||||
// home, a full disk) leaves the previous version in place rather than a
|
||||
// truncated file.
|
||||
QSaveFile file(target);
|
||||
if (!file.open(QIODevice::WriteOnly) || file.write(contents.library) != contents.library.size()
|
||||
|| !file.commit()) {
|
||||
emit installFinished(contents.manifest.id, false,
|
||||
QStringLiteral("Impossible d'écrire %1.").arg(target));
|
||||
return;
|
||||
}
|
||||
|
||||
QSettings settings;
|
||||
settings.setValue(installedKey(contents.manifest.id), target);
|
||||
qCInfo(pacmgrPlugin) << "plugin package installed:" << contents.manifest.id << target;
|
||||
emit installFinished(contents.manifest.id, true, target);
|
||||
}
|
||||
|
||||
void PluginPackage::remove(const QString& id) {
|
||||
// Only a library this class wrote is removed: a plugin the user copied into
|
||||
// the directory by hand is not ours to delete.
|
||||
const QString path = installedPath(id);
|
||||
if (path.isEmpty()) {
|
||||
emit removeFinished(id, false,
|
||||
QStringLiteral("Ce plugin n'a pas été installé depuis un paquet."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (QFile::exists(path) && !QFile::remove(path)) {
|
||||
emit removeFinished(id, false, QStringLiteral("Impossible de supprimer %1.").arg(path));
|
||||
return;
|
||||
}
|
||||
|
||||
QSettings settings;
|
||||
settings.remove(installedKey(id));
|
||||
qCInfo(pacmgrPlugin) << "plugin package removed:" << id << path;
|
||||
emit removeFinished(id, true, path);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "zip-archive.h"
|
||||
|
||||
// A plugin package (.fwspacm): a ZIP archive holding a plugin and the manifest
|
||||
// describing it.
|
||||
//
|
||||
// The package is built by a plugin author with the script at the repo root
|
||||
// (make-plugin-package.py) and installed by dropping the file anywhere on the
|
||||
// window. There is no catalogue and no network: what the user installs is a
|
||||
// file they already have, which is the whole point of the format.
|
||||
//
|
||||
// Layout of the archive:
|
||||
//
|
||||
// plugin.json the manifest (required)
|
||||
// <library> the shared library (.so / .dll / .dylib)
|
||||
//
|
||||
// The manifest names what the plugin is, so the application can tell the user
|
||||
// what it is about to run before it is written anywhere:
|
||||
//
|
||||
// { "format": 1, "id": "flatpak", "name": "Flatpak", "kind": "provider",
|
||||
// "version": "1.0.0", "author": "FWS", "description": "…",
|
||||
// "library": "libflatpak-provider.so", "sha256": "…" }
|
||||
//
|
||||
// Installing a package runs third-party code inside this process, so the
|
||||
// reader stays deliberately strict: the archive has to be a ZIP, the manifest
|
||||
// has to be a well-formed object, the library has to be one of the entries, its
|
||||
// name has to be safe to write, and its checksum — when the manifest announces
|
||||
// one — has to match before anything lands in the plugin directory. The library
|
||||
// is written through QSaveFile, so it appears there complete, under its final
|
||||
// name, and never half-installed.
|
||||
class PluginPackage : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
// What the manifest declares about a plugin. Everything but the id is
|
||||
// there for the user: the plugin itself still reports its own identity
|
||||
// through the C ABI once loaded, and the registry stays the authority on
|
||||
// what is actually installed.
|
||||
struct Manifest {
|
||||
int format = 0;
|
||||
QString id;
|
||||
QString name;
|
||||
QString description;
|
||||
QString version;
|
||||
QString author;
|
||||
QString kind; // "provider" or "addon"; empty when unstated
|
||||
QString library; // file name to write in the plugin directory
|
||||
QString sha256; // optional checksum of that library
|
||||
};
|
||||
|
||||
// Outcome of reading a package, before anything is written: what the
|
||||
// manifest says and which library it points at.
|
||||
struct Contents {
|
||||
Manifest manifest;
|
||||
QByteArray library;
|
||||
QString libraryName; // name the library is written under
|
||||
};
|
||||
|
||||
explicit PluginPackage(QObject* parent = nullptr);
|
||||
|
||||
// ---- Format ----
|
||||
// The extension a package file carries.
|
||||
static QString suffix();
|
||||
// Whether a path looks like a package. Used by the window to accept a drop
|
||||
// without having to open the file first.
|
||||
static bool isPackagePath(const QString& path);
|
||||
|
||||
// ---- Installation ----
|
||||
// Directory packages are installed into (created on demand). Defaults to the
|
||||
// per-user plugin directory PluginManager already scans; overridable so the
|
||||
// tests never touch the user's real one.
|
||||
QString installDirectory() const;
|
||||
void setInstallDirectory(const QString& path);
|
||||
|
||||
// Installs a package, then emits installFinished(). The file is only
|
||||
// written once the manifest, the library and the checksum have all been
|
||||
// accepted, so a refused package leaves the plugin directory untouched.
|
||||
void install(const QString& path);
|
||||
// Removes a package this class installed, and emits removeFinished(). A
|
||||
// library the user copied in by hand is never touched.
|
||||
void remove(const QString& id);
|
||||
|
||||
// True when a package with that id was installed here and its file is
|
||||
// still on disk.
|
||||
bool isInstalled(const QString& id) const;
|
||||
// Absolute path of the library installed for that id (empty when none).
|
||||
QString installedPath(const QString& id) const;
|
||||
// Every id installed from a package, for the page that lists them.
|
||||
QStringList installedIds() const;
|
||||
|
||||
// Reads a package without writing anything: `error` is filled (and the
|
||||
// result empty) when the file is not a usable package. Pure logic, so it is
|
||||
// unit-tested without touching the disk.
|
||||
static Contents read(const QString& path, QString* error);
|
||||
|
||||
// Parses a manifest. `error` is filled when the document is not a manifest
|
||||
// or when it lacks what an install needs (an id, and a library the archive
|
||||
// actually contains).
|
||||
static Manifest parseManifest(const QByteArray& json, const ZipArchive& archive,
|
||||
QString* error);
|
||||
|
||||
// The name a library entry is written under in the plugin directory. An
|
||||
// entry the manifest does not name is found by its library suffix, so a
|
||||
// package does not have to agree with the script on the name.
|
||||
static QString targetFileName(const Manifest& manifest, const ZipArchive& archive,
|
||||
QString* error);
|
||||
|
||||
// The platform's shared-library suffix.
|
||||
static QString librarySuffix();
|
||||
|
||||
signals:
|
||||
void installFinished(const QString& id, bool success, const QString& message);
|
||||
void removeFinished(const QString& id, bool success, const QString& message);
|
||||
|
||||
private:
|
||||
// Settings key remembering the library installed for a package id.
|
||||
static QString installedKey(const QString& id);
|
||||
// Settings key prefix listing every installed package.
|
||||
static QString installedKeyPrefix();
|
||||
|
||||
QString m_installDirectory; // empty = the per-user plugin directory
|
||||
};
|
||||
Reference in new issue
Block a user