feat(flatpak): report the download flatpak never announces

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 %.
This commit is contained in:
BlackAngelTV committed 2026-09-27 21:33:41 +02:00
1 parent 7c46023489
commit f1fbd3cd8a
11 files changed
+529 -63

No files matched your search

+193 -14
View File
@@ -3,6 +3,9 @@
#include "progress-tracker.h"
#include <array>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <sstream>
@@ -11,6 +14,8 @@
#include <cstdlib>
#include <filesystem>
#include <set>
#include <thread>
#include <utility>
#include <vector>
namespace fs = std::filesystem;
@@ -21,6 +26,181 @@ static fs::path userShareDir() {
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.
@@ -339,9 +519,9 @@ bool FlatpakManager::install(const std::string& packageName,
// 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 runWithProgress("flatpak install --noninteractive --assumeyes " + extra
+ " " + packageName + " 2>&1",
progressCallback);
return runFlatpak("flatpak install --noninteractive --assumeyes " + extra
+ " " + packageName + " 2>&1",
progressCallback);
};
// A fresh flatpak setup has no remote configured: add the default flathub
@@ -367,7 +547,7 @@ bool FlatpakManager::install(const std::string& packageName,
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);
runWithProgress("flatpak update --appstream 2>&1", progressCallback);
runFlatpak("flatpak update --appstream 2>&1", progressCallback);
output = tryInstall(ambiguous() ? "--user flathub" : "");
}
@@ -470,7 +650,7 @@ bool FlatpakManager::remove(const std::string& packageName,
m_lastError.clear();
if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1);
std::string output = runWithProgress(
std::string output = runFlatpak(
"flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1",
progressCallback);
@@ -490,7 +670,7 @@ bool FlatpakManager::update(const std::string& packageName,
auto tryUpdate = [&](const std::string& extra) {
std::string command = "flatpak update --noninteractive --assumeyes " + extra;
if (!packageName.empty()) command += " " + packageName;
return runWithProgress(command + " 2>&1", progressCallback);
return runFlatpak(command + " 2>&1", progressCallback);
};
if (packageName.empty()) {
@@ -519,13 +699,13 @@ bool FlatpakManager::refresh(ProgressCallback progressCallback) {
// Re-download the appstream metadata of every remote so search and
// update detection reflect the latest published versions.
std::string output = runWithProgress("flatpak update --appstream 2>&1", progressCallback);
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 = runWithProgress("flatpak update --appstream --user 2>&1", progressCallback);
output = runFlatpak("flatpak update --appstream --user 2>&1", progressCallback);
}
if (output.find("error:") != std::string::npos) {
@@ -573,7 +753,7 @@ bool FlatpakManager::installFile(const std::string& path,
progressCallback("Ajout du dépôt " + repoNamespace(path) + "...", -1);
}
const std::string output =
runWithProgress(installFileCommand(kind, path, /*userScope=*/true), progressCallback);
runFlatpak(installFileCommand(kind, path, /*userScope=*/true), progressCallback);
if (output.find("error:") != std::string::npos) {
m_lastError = lastOutputLines(output);
return false;
@@ -588,14 +768,13 @@ bool FlatpakManager::installFile(const std::string& path,
-1);
}
std::string output =
runWithProgress(installFileCommand(kind, path, /*userScope=*/false), progressCallback);
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 = runWithProgress(installFileCommand(kind, path, /*userScope=*/true),
progressCallback);
output = runFlatpak(installFileCommand(kind, path, /*userScope=*/true), progressCallback);
}
if (output.find("error:") != std::string::npos) {
@@ -625,7 +804,7 @@ bool FlatpakManager::cleanCache(ProgressCallback progressCallback) {
// Runtimes left behind by uninstalled applications weigh several hundred
// megabytes each; flatpak only removes those no installed app references.
std::string output = runWithProgress(
std::string output = runFlatpak(
"flatpak uninstall --unused --noninteractive --assumeyes 2>&1", progressCallback);
if (output.find("error:") != std::string::npos) {