Installing a .flatpakref looked frozen: flatpak prints two lines and then stays silent for the minutes a runtime takes to come down, so the window repeated the same sentence over a stalled bar and the journal recorded nothing at all. It has no meter to print — measured here, on a real 658 MB install, it draws nothing on a pipe nor on a full terminal, only on the deltas the CDN happens to serve — so the provider now measures the transfer itself: the bytes landing in flatpak's own staging directory, reported as they grow. When even those stop, the window takes over and says which step is running and for how long, in the status bar and in the journal. Along the way the runner reads with read() instead of stdio so in-place updates are not held back by a buffer, strips the ANSI escapes some tools colour their output with (the AUR plugin's own copy is gone), and turns a rewritten meter line into a journal entry every 10 %.
816 lines
32 KiB
C++
816 lines
32 KiB
C++
#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;
|
|
}
|
|
|
|
// "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.
|
|
static std::vector<std::string> splitColumns(const std::string& line) {
|
|
std::vector<std::string> fields;
|
|
std::istringstream ss(line);
|
|
std::string field;
|
|
if (line.find('\t') != std::string::npos) {
|
|
while (std::getline(ss, field, '\t')) {
|
|
if (!field.empty()) fields.push_back(field);
|
|
}
|
|
} else {
|
|
while (ss >> field) fields.push_back(field);
|
|
}
|
|
return fields;
|
|
}
|
|
|
|
// `flatpak search` prints one aligned row per app:
|
|
// Name Description Application ID Version Branch Remotes
|
|
// The description may contain spaces, so the application ID is located by
|
|
// shape (dotted identifier) and everything between Name and it is joined back.
|
|
std::vector<PackageInfo> FlatpakManager::parseSearchOutput(const std::string& output) {
|
|
std::vector<PackageInfo> results;
|
|
std::istringstream iss(output);
|
|
std::string line;
|
|
|
|
bool firstLine = true;
|
|
while (std::getline(iss, line)) {
|
|
if (firstLine) {
|
|
firstLine = false;
|
|
continue; // Skip the column header.
|
|
}
|
|
if (line.empty()) continue;
|
|
|
|
std::vector<std::string> tokens = splitColumns(line);
|
|
if (tokens.empty()) continue;
|
|
|
|
int appIdx = -1;
|
|
for (int i = 1; i < static_cast<int>(tokens.size()); ++i) {
|
|
if (isAppId(tokens[i])) {
|
|
appIdx = i;
|
|
break;
|
|
}
|
|
}
|
|
if (appIdx == -1) continue; // Not an application row.
|
|
|
|
PackageInfo pkg;
|
|
// Use the application ID as the package name so install/remove/update
|
|
// work directly with the CLI; the human-readable name is kept at the
|
|
// front of the description (e.g. "Firefox — Fast and privacy-aware").
|
|
pkg.name = tokens[appIdx];
|
|
pkg.version = (appIdx + 1 < static_cast<int>(tokens.size())) ? tokens[appIdx + 1] : "";
|
|
pkg.repository = tokens.back();
|
|
|
|
for (int i = 1; i < appIdx; ++i) {
|
|
if (!pkg.description.empty()) pkg.description += " ";
|
|
pkg.description += tokens[i];
|
|
}
|
|
if (!tokens[0].empty() && tokens[0] != pkg.name) {
|
|
pkg.description = tokens[0] + " — " + pkg.description;
|
|
}
|
|
results.push_back(pkg);
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
std::vector<PackageInfo> FlatpakManager::parseInstalledOutput(const std::string& output) {
|
|
std::vector<PackageInfo> results;
|
|
std::istringstream iss(output);
|
|
std::string line;
|
|
|
|
while (std::getline(iss, line)) {
|
|
if (line.empty()) continue;
|
|
|
|
std::vector<std::string> fields = splitColumns(line);
|
|
if (fields.empty()) continue;
|
|
|
|
PackageInfo pkg;
|
|
pkg.name = fields[0];
|
|
if (fields.size() > 1) pkg.version = fields[1];
|
|
if (fields.size() > 2) pkg.repository = fields[2];
|
|
pkg.installed = true;
|
|
results.push_back(pkg);
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
std::vector<PackageInfo> FlatpakManager::parseUpdatesOutput(const std::string& output) {
|
|
std::vector<PackageInfo> results;
|
|
std::istringstream iss(output);
|
|
std::string line;
|
|
|
|
while (std::getline(iss, line)) {
|
|
if (line.empty()) continue;
|
|
|
|
std::vector<std::string> fields = splitColumns(line);
|
|
if (fields.empty()) continue;
|
|
|
|
PackageInfo pkg;
|
|
pkg.name = fields[0];
|
|
if (fields.size() > 1) pkg.version = fields[1];
|
|
pkg.installed = true;
|
|
pkg.updateAvailable = true;
|
|
results.push_back(pkg);
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
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";
|
|
}
|
|
|
|
// 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() {
|
|
return parseInstalledOutput(
|
|
exec("flatpak list --app --columns=application,version,origin 2>&1"));
|
|
}
|
|
|
|
std::vector<PackageInfo> FlatpakManager::listUpdates() {
|
|
return parseUpdatesOutput(
|
|
exec("flatpak remote-ls --updates --columns=application,version 2>&1"));
|
|
}
|
|
|
|
bool FlatpakManager::isInstalled(const std::string& appId) {
|
|
std::string cmd = "flatpak info " + appId + " > /dev/null 2>&1";
|
|
return system(cmd.c_str()) == 0;
|
|
}
|
|
|
|
bool FlatpakManager::install(const std::string& packageName,
|
|
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();
|
|
if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1);
|
|
|
|
std::string output = runFlatpak(
|
|
"flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1",
|
|
progressCallback);
|
|
|
|
if (output.find("error:") != std::string::npos || isInstalled(packageName)) {
|
|
m_lastError = lastOutputLines(output);
|
|
return false;
|
|
}
|
|
|
|
// Clear the launcher links created at install time (see integrateDesktopEntries).
|
|
uninstallDesktopEntries(packageName);
|
|
return true;
|
|
}
|
|
|
|
bool FlatpakManager::update(const std::string& packageName,
|
|
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("");
|
|
// 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;
|
|
}
|