diff --git a/README.en.md b/README.en.md index 7f9510c..6dc3a89 100644 --- a/README.en.md +++ b/README.en.md @@ -11,7 +11,7 @@ Package manager for **Arch Linux** based on **pacman**, with a Qt6 graphical int - 🧹 **Cleanup**: orphan and legacy packages, cache trimming - 📋 **History of all actions** - 🧩 **Plugins**: package managers (pacman built-in, **Flatpak shipped by default**) and **extensions** written in C++ (UI addons, helpers, …) -- 📥 **Flatpak files**: drop a `.flatpakref`, `.flatpakrepo` or `.flatpak` onto the window (or right-click → **Open with PacManager** in your file manager) to install it directly +- 📥 **Flatpak files**: drop a `.flatpakref`, `.flatpakrepo` or `.flatpak` onto the window (or right-click → **Open with PacManager** in your file manager) to install it directly — with the bytes actually downloaded and the elapsed time shown live, since flatpak prints nothing while a runtime comes down ## Architecture diff --git a/README.md b/README.md index 398d933..486e5c1 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Gestionnaire de paquets pour **Arch Linux** basé sur **pacman**, avec interface - 🧹 **Nettoyage** : paquets orphelins et legacy, purge des caches - 📋 **Historique** de toutes les actions - 🧩 **Plugins** : gestionnaires de paquets (pacman intégré, **Flatpak livré par défaut**) et **extensions** écrites en C++ (addons graphiques, helpers, …) -- 📥 **Fichiers Flatpak** : glissez-déposez un `.flatpakref`, `.flatpakrepo` ou `.flatpak` sur la fenêtre (ou clic droit → **Ouvrir avec PacManager** dans le gestionnaire de fichiers) pour l'installer directement +- 📥 **Fichiers Flatpak** : glissez-déposez un `.flatpakref`, `.flatpakrepo` ou `.flatpak` sur la fenêtre (ou clic droit → **Ouvrir avec PacManager** dans le gestionnaire de fichiers) pour l'installer directement — avec les octets réellement téléchargés et le temps écoulé affichés en direct, flatpak n'imprimant rien pendant le téléchargement d'un runtime ## Architecture diff --git a/doc/depannage.md b/doc/depannage.md index 5a8a4c1..d59fb0c 100644 --- a/doc/depannage.md +++ b/doc/depannage.md @@ -124,6 +124,10 @@ depuis le réseau. CLI pour un échec côté flatpak. - Plusieurs fichiers déposés d'un coup s'installent **un par un** : attendez la fin du premier avant de conclure que les suivants ont été oubliés. +- L'installation démarre puis plus rien ne s'affiche pendant plusieurs minutes : + c'est **normal**, flatpak n'imprime rien pendant qu'il télécharge un runtime. + La barre de statut affiche les octets téléchargés et le temps écoulé, et le + journal enregistre la même chose ([operations.md](operations.md)). ### « Mise à jour disponible » alors qu'aucune ne l'est @@ -137,10 +141,23 @@ correspondante dans `~/.config/Freebuff/PacManager.conf`. ### La barre de progression semble figée ou fait des allers-retours Elle ne devrait plus reculer : la progression est monotone et pondérée par phase -(voir [mise-a-jour.md](mise-a-jour.md)). Si elle reste sur une phase, regardez la -sortie dans la console : l'outil sous-jacent (pacman, flatpak, yay) n'a peut-être -rien produit après son téléchargement. Une phase sans compteur avance par pas, -lentement : c'est volontaire, l'interface ne peut pas inventer un pourcentage. +(voir [operations.md](operations.md)). Si elle reste à sa valeur initiale, c'est +que l'outil sous-jacent n'a rien produit : regardez la sortie dans la console. +Une phase sans compteur avance par pas, lentement : c'est volontaire, l'interface +ne peut pas inventer un pourcentage. + +Pendant ce silence, deux choses disent que l'opération n'est pas figée : + +- la barre de statut rappelle l'étape et la durée écoulée + (`Installation de com.usebottles.bottles… — 2 min 30`) ; +- le journal note l'attente toutes les 30 s (`[opération] toujours en cours + après…`). + +Pour une installation Flatpak, le fournisseur mesure en plus les octets +réellement téléchargés (`⬇ 213,8 Mio téléchargés (4,2 Mio/s)`). S'il n'y a rien +dans `/var/lib/flatpak/repo/tmp` ni dans `~/.local/share/flatpak/repo/tmp`, c'est +que rien ne se télécharge : l'installation est en cours de déploiement, ce qui +prend du temps sans produire d'octets. ## Diagnostic à joindre à une issue diff --git a/doc/operations.md b/doc/operations.md index 8ef8b81..6c27140 100644 --- a/doc/operations.md +++ b/doc/operations.md @@ -117,8 +117,9 @@ enveloppent pacman. ### Sortie en temps réel -`runStreamed()` lit la sortie du processus **caractère par caractère** à travers -le tampon de stdio et découpe sur `\n` **et sur `\r`** : +`runStreamed()` lit la sortie du processus avec `read()` — aussitôt qu'un octet +arrive, sans attendre le remplissage d'un tampon — et découpe sur `\n` **et sur +`\r`** : - sur `\n` : une vraie ligne, transmise comme message ; - sur `\r` : une mise à jour « sur place » (le compteur de téléchargement de @@ -127,12 +128,57 @@ le tampon de stdio et découpe sur `\n` **et sur `\r`** : C'est ce découpage sur `\r` qui fait vivre la barre pendant un téléchargement : une lecture ligne à ligne attendrait un retour à la ligne que ces compteurs -n'émettent jamais. +n'émettent jamais. Les **séquences ANSI** (couleurs, déplacements de curseur) +sont retirées au passage : un outil qui colorie sa sortie n'enverrait sinon que +du bruit dans la barre de statut et dans le journal. + +Une mise à jour « sur place » n'a pas de phrase, seulement un chiffre : tous les +10 %, elle est aussi rendue comme une ligne (`⏳ 40 %`), ce qui la fait figurer +dans le journal. Avant cela, Flatpak et AUR **tamponnaient toute la sortie** (`exec` + relecture -à la fin) : la barre restait indéterminée pendant toute la mise à jour et les +à la fin) : la barre reste indéterminée pendant toute la mise à jour et les lignes arrivaient d'un coup à la fin. +### Quand l'outil n'imprime rien : les octets réels + +flatpak **n'a pas de compteur de téléchargement à afficher** : son outil ne le +dessine que sur les deltas que le CDN lui sert, et sur une installation partie +d'un `.flatpakref` il passe plusieurs minutes sans produire une seule ligne +entre deux « Installing runtime/… ». La fenêtre semblait alors figée, et le +journal vide. + +Le fournisseur flatpak mesure donc le téléchargement lui-même +(`DownloadWatcher`) : flatpak dépose ce qu'il télécharge dans un répertoire de +staging de l'installation visée (`/repo/tmp/staging-…`, ou +`flatpak-cache-…` pour le montage revokefs d'une installation système), et ces +octets croissent. Une ligne par tranche de 4 Mio, au plus une toutes les 2,5 s : + +``` + ⬇ 213,8 Mio téléchargés (4,2 Mio/s) +``` + +Ce sont les octets que flatpak a réellement écrits, pas une estimation. La +mesure est prise dans un thread à part, dont le seul rôle est d'appeler le +callback de progression ; il s'arrête quand la commande se termine, et le volume +de départ est relevé au lancement pour qu'un transfert interrompu laissé sur le +disque ne soit pas compté pour l'opération en cours. + +### Quand l'outil se tait complètement : le temps écoulé + +Le `DownloadWatcher` se tait quand aucun octet n'arrive (analyse d'un runtime, +déploiement) : c'est alors la **fenêtre** qui prend le relais. Un minuteur d'une +seconde (`MainWindow::onActivityTick`) réaffiche l'étape courante avec la durée +écoulée après cinq secondes de silence, et note l'attente dans le journal toutes +les 30 s : + +``` +[2026-09-27 19:53:08] [opération] toujours en cours après 2 min 30 — Installation de com.usebottles.bottles… +``` + +Aucune invention : l'interface ne fabrique pas de pourcentage, elle dit ce +qu'elle sait — l'étape en cours, et depuis combien de temps. + ### Plusieurs fournisseurs Une opération globale (tout mettre à jour, rafraîchir) enchaîne les providers diff --git a/doc/tests.md b/doc/tests.md index 92bdfcf..41481e0 100644 --- a/doc/tests.md +++ b/doc/tests.md @@ -17,10 +17,10 @@ lance qu'une partie (`ctest -R progress`). | --- | --- | --- | | `pacman-manager-test` | Parsing de la sortie pacman : listes, mises à jour, orphelins/étrangers, commandes construites (`removePackagesCommand`, `cleanCacheCommand`) et détection des échecs (mot de passe, verrou). | Aucune (pas de pacman). | | `flatpak-manager-test` | Parsing de la sortie Flatpak : recherche, listes, colonnes ; reconnaissance des formats de fichier (`.flatpakref`, `.flatpakrepo`, `.flatpak`, casse et URL) et commandes construites pour l'installation depuis un fichier (chemins entre guillemets compris). | Aucune. | -| `flatpak-integration-test` | **Le vrai CLI flatpak** : installation et désinstallation d'une petite application, liste, recherche, mise à jour. | `flatpak` (le test se saute s'il est absent). | +| `flatpak-integration-test` | **Le vrai CLI flatpak** : installation et désinstallation d'une petite application, liste, recherche, mise à jour — donc aussi le `DownloadWatcher` en conditions réelles. | `flatpak` (le test se saute s'il est absent). | | `aur-manager-test` | Parsing du helper AUR (yay/paru) et nettoyage des séquences ANSI. | Aucune. | | `package-utils-test` | Logique partagée de `package-manager.h` : fusion des doublons entre fournisseurs, tri par fournisseur puis par nom. | Aucune. | -| `progress-tracker-test` | `ProgressTracker` : compteurs pacman/Flatpak, pourcentages seuls, phases pondérées, étapes non identifiables, monotonie, faux positifs. | Aucune, **même pas Qt**. | +| `progress-tracker-test` | `ProgressTracker` : compteurs pacman/Flatpak, pourcentages seuls, phases pondérées, étapes non identifiables, monotonie, faux positifs ; exécution d'une commande (`/bin/sh` en une ligne) : suppression des séquences ANSI, remontage d'une sortie au fil de l'eau, dernière ligne sans retour à la ligne, jalons de progression d'une jauge « sur place ». | Aucune, **même pas Qt**. | | `plugin-shop-test` | Format du catalogue (valide, invalide, entrées incomplètes) et comptabilité d'installation/désinstallation dans un dossier temporaire. | Qt Core + Network, aucun accès réseau. | | `app-core-test` | La couche logique : portes d'entrée (opération en cours, mot de passe, providers), file d'attente des listes, historique, mode d'identification, refus d'un fichier qu'aucun fournisseur ne sait installer. | Qt Core seulement — **pas** QtWidgets. | | `update-manager-test` | Comparaison de versions, choix de la méthode de mise à jour, et le script d'installation, exécuté pour de vrai contre un binaire en cours d'exécution. | Qt Core + Network. | diff --git a/include/main-window.h b/include/main-window.h index 881e7db..a0ee3e2 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -67,6 +68,9 @@ private slots: void onUpdateAll(); void onTrayActivated(QSystemTrayIcon::ActivationReason reason); void onCheckForUpdates(); + // Ticks once a second while an operation runs: what it does when the + // provider has printed nothing for a while is described in onActivityTick(). + void onActivityTick(); // ---- What a page asks the frame to do ---- // A page hands over a request so the frame can walk the user through what @@ -134,6 +138,9 @@ private: // dialog, anything else is shown as-is. void showActionError(const QString& title, const QString& error, bool locked); void applyCredentialMode(AppCore::CredentialMode mode); + // Records that the running operation just said something: the step is kept + // for the heartbeat and the "nothing printed" clock restarts. + void noteOperationOutput(const QString& step); // The files a drag carries that the core can install; empty when the drop is // nothing the app handles (which is also how dragEnterEvent refuses it). @@ -180,6 +187,16 @@ private: int m_progressValue = 0; int m_progressGeneration = 0; + // What the window knows about the operation it is waiting on. A download + // that takes minutes can print nothing at all for minutes, and a window + // that only repeats the same sentence looks broken: the timer re-states the + // current step with the elapsed time, and the journal notes the wait. + QTimer* m_activityTimer = nullptr; + QElapsedTimer m_operationClock; + QString m_operationStep; + qint64 m_lastOutputAtMs = 0; + qint64 m_lastWaitNoteMs = 0; + // Files waiting to be installed (dropped or opened), and whether one is // being installed right now. QStringList m_pendingFileInstalls; diff --git a/include/progress-tracker.h b/include/progress-tracker.h index a283d4d..7104177 100644 --- a/include/progress-tracker.h +++ b/include/progress-tracker.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -10,6 +11,12 @@ #include "package-manager.h" +#ifdef _WIN32 +#include +#else +#include +#endif + // Reading a package manager's output: streaming it as it is produced, and // turning it into a progress bar. // @@ -39,6 +46,42 @@ struct OutputChunk { using OutputHandler = std::function; +// Drops the ANSI escape sequences a tool emits once it thinks it is on a +// terminal (colours, cursor moves, erase-line). They are noise in the status +// bar and garbage in the journal, which replays the output as a terminal would +// show it. +inline std::string stripAnsi(const std::string& text) { + std::string out; + out.reserve(text.size()); + + for (std::size_t i = 0; i < text.size(); ++i) { + if (text[i] != '\033') { + out += text[i]; + continue; + } + // CSI (ESC [ … final byte): colours, cursor moves, erase. + if (i + 1 < text.size() && text[i + 1] == '[') { + std::size_t j = i + 2; + while (j < text.size() && static_cast(text[j]) >= 0x20 + && static_cast(text[j]) <= 0x3f) { + ++j; + } + i = j; // the final byte, or the last one when the run was cut + continue; + } + // OSC (ESC ] … BEL or ESC \): window titles, hyperlinks. + if (i + 1 < text.size() && text[i + 1] == ']') { + std::size_t j = i + 2; + while (j < text.size() && text[j] != '\a' && text[j] != '\033') ++j; + i = (j < text.size() && text[j] == '\033') ? j + 1 : j; + continue; + } + // Anything else is a two-byte sequence (ESC ( B, ESC =, …). + if (i + 1 < text.size()) ++i; + } + return out; +} + // Closes a popen() stream. A named deleter avoids the GCC warning about the // function-pointer attributes carried by decltype(&pclose) being dropped. struct ProcessCloser { @@ -47,42 +90,66 @@ struct ProcessCloser { } }; +// Reads whatever the command has already written, without waiting for a buffer +// to fill: that is what hands a '\r' update over while the tool is still +// running. One name for both platforms, the Windows CRT calling read() _read(). +inline long readOutput(int fd, char* buffer, unsigned int size) { +#ifdef _WIN32 + return static_cast(::_read(fd, buffer, size)); +#else + return static_cast(::read(fd, buffer, size)); +#endif +} + // Runs `command` through a shell, reports its output as it is produced and // returns everything it printed (byte-for-byte, so callers keep inspecting the // full output for `error:` lines and the like). // -// Chunks are cut on '\n' (a real line) and on '\r' (an in-place update). Reads -// go through stdio's buffer one character at a time, which is what makes the -// '\r' updates arrive while the command is still running: a line-oriented read -// would sit on them until the next newline, and a download meter never emits -// one. +// Chunks are cut on '\n' (a real line) and on '\r' (an in-place update), and +// the escape sequences some tools colour their output with are removed. Reads +// go through read() rather than stdio, so a '\r' update is handed over as soon +// as the tool writes it: a line-oriented read would sit on it until the next +// newline, and a download meter never emits one. inline std::string runStreamed(const std::string& command, const OutputHandler& onChunk) { std::string output; std::string pending; - std::unique_ptr pipe(popen(command.c_str(), "r")); - if (!pipe) return output; - // Empty lines are noise for a progress bar, so only non-empty chunks are // handed over. auto deliver = [&](bool partial) { - if (!pending.empty() && onChunk) onChunk(OutputChunk{pending, partial}); + if (!pending.empty() && onChunk) onChunk(OutputChunk{stripAnsi(pending), partial}); pending.clear(); }; - int read = 0; - while ((read = std::fgetc(pipe.get())) != EOF) { - const char c = static_cast(read); - if (c == '\n' || c == '\r') { - output += pending; - output += c; - deliver(c == '\r'); - } else { - pending += c; + auto feed = [&](const char* data, std::size_t length) { + for (std::size_t i = 0; i < length; ++i) { + const char c = data[i]; + if (c == '\n' || c == '\r') { + output += pending; + output += c; + deliver(c == '\r'); + } else { + pending += c; + } } + }; + + std::unique_ptr pipe(popen(command.c_str(), "r")); + if (!pipe) return output; + + char buffer[512]; + for (;;) { + const auto count = readOutput(fileno(pipe.get()), buffer, sizeof(buffer)); + if (count > 0) { + feed(buffer, static_cast(count)); + continue; + } + if (count < 0 && errno == EINTR) continue; + break; } deliver(/*partial=*/false); // Last line when the command ends without one. + // pclose() is what waits for the shell. return output; } @@ -290,18 +357,30 @@ private: // in-place updates that have no text of their own — so the whole thing lives // here rather than being copied into each provider. The full output is still // returned for the `error:` checks the providers run afterwards. +// +// An in-place meter is the one update that carries a number but no sentence, so +// every 10 % step of it is also reported as a line ("⏳ 40 %"): it is what the +// status bar shows and what the journal records while a tool rewrites its +// progress bar without ever printing a newline. inline std::string runWithProgress(const std::string& command, ProgressCallback callback) { ProgressTracker tracker; + constexpr int kMilestoneStep = 10; + int milestone = 0; + return runStreamed(command, [&](const OutputChunk& chunk) { if (!callback) return; const int percent = tracker.feed(chunk.text); // A partial chunk is an in-place progress meter: it carries a real // percentage but nothing worth printing in the status bar. - if (chunk.partial) { - if (percent >= 0) callback(std::string(), percent); + if (!chunk.partial) { + callback(chunk.text, percent); return; } - callback(chunk.text, percent); + if (percent >= 0) callback(std::string(), percent); + if (percent < 0 || percent - milestone < kMilestoneStep) return; + + milestone = percent; + callback("⏳ " + std::to_string(percent) + " %", percent); }); } diff --git a/plugins/aur-provider/aur-manager.cpp b/plugins/aur-provider/aur-manager.cpp index 541a738..1bc3fe3 100644 --- a/plugins/aur-provider/aur-manager.cpp +++ b/plugins/aur-provider/aur-manager.cpp @@ -40,20 +40,6 @@ static std::string lastOutputLines(const std::string& output, int maxLines = 4) return out; } -// Strip ANSI color escapes (`yay -Ss` colors repo/name pairs). -static std::string stripAnsi(const std::string& s) { - std::string out; - for (size_t i = 0; i < s.size(); ++i) { - if (s[i] == '\033' && i + 1 < s.size() && s[i + 1] == '[') { - i += 2; - while (i < s.size() && s[i] != 'm') ++i; - continue; - } - out += s[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"; diff --git a/plugins/flatpak-provider/flatpak-manager.cpp b/plugins/flatpak-provider/flatpak-manager.cpp index ab72655..93f41d6 100644 --- a/plugins/flatpak-provider/flatpak-manager.cpp +++ b/plugins/flatpak-provider/flatpak-manager.cpp @@ -3,6 +3,9 @@ #include "progress-tracker.h" #include +#include +#include +#include #include #include #include @@ -11,6 +14,8 @@ #include #include #include +#include +#include #include 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 "/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 stagingRoots() { + std::vector 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 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(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(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(now - lastReport).count(); + const unsigned long long perSecond = + seconds > 0.0 + ? static_cast((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 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) { diff --git a/src/main-window.cpp b/src/main-window.cpp index a14a9bf..019e9e9 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -41,6 +41,21 @@ #include "page.h" #include "plugins-page.h" +// How long a wait reads best in the status bar: "45 s", "2 min 05", "1 h 03". +static QString formatElapsed(qint64 ms) { + const qint64 seconds = ms / 1000; + const qint64 minutes = seconds / 60; + if (minutes >= 60) { + return QStringLiteral("%1 h %2").arg(minutes / 60) + .arg(minutes % 60, 2, 10, QLatin1Char('0')); + } + if (minutes > 0) { + return QStringLiteral("%1 min %2").arg(minutes) + .arg(seconds % 60, 2, 10, QLatin1Char('0')); + } + return QStringLiteral("%1 s").arg(seconds); +} + // Load one of the embedded SVG icons (see resources/resources.qrc). static QIcon loadIcon(const QString& name) { return QIcon(QString(":/icons/%1.svg").arg(name)); @@ -440,6 +455,12 @@ void MainWindow::setupUI() { m_installProgressBar->setVisible(false); statusBar()->addPermanentWidget(m_installProgressBar); + // Watchdog of the running operation: it is what tells a two-minute download + // from a frozen app (see onActivityTick). + m_activityTimer = new QTimer(this); + m_activityTimer->setInterval(1000); + connect(m_activityTimer, &QTimer::timeout, this, &MainWindow::onActivityTick); + setStyleSheet(appStyleSheet()); } @@ -1204,6 +1225,7 @@ void MainWindow::onCoreListFinished(AppCore::ListMode mode, void MainWindow::onCoreActionProgress(const QString& message, int percent) { if (!message.isEmpty()) statusBar()->showMessage(message); + noteOperationOutput(message); if (percent < 0) return; // A provider running several commands (or a second provider after the @@ -1249,6 +1271,17 @@ void MainWindow::onCoreBusyChanged(bool busy) { // operation and must not touch the new one. ++m_progressGeneration; + if (busy) { + m_operationClock.start(); + m_operationStep.clear(); + m_lastOutputAtMs = 0; + m_lastWaitNoteMs = 0; + m_activityTimer->start(); + } else { + m_activityTimer->stop(); + m_operationClock.invalidate(); + } + if (!busy) { if (m_installProgressBar->isVisible() && m_installProgressBar->maximum() > 0) { // Real progress was shown: complete it and let it be seen. A bar @@ -1279,6 +1312,40 @@ void MainWindow::onCoreBusyChanged(bool busy) { void MainWindow::onCoreStatusMessage(const QString& message) { statusBar()->showMessage(message); + noteOperationOutput(message); +} + +void MainWindow::noteOperationOutput(const QString& step) { + if (!step.isEmpty()) m_operationStep = step; + if (m_operationClock.isValid()) m_lastOutputAtMs = m_operationClock.elapsed(); +} + +// A long operation is not always a talkative one: flatpak prints nothing while +// a 1 Go runtime downloads, which left the window repeating the same sentence +// over a frozen bar. After a few seconds of silence the elapsed time joins the +// status bar, and every half-minute of waiting the journal says so too — the +// Logs screen then shows the operation is alive instead of stopped. +void MainWindow::onActivityTick() { + if (!m_operationClock.isValid()) return; + + // Five seconds of silence is a download; anything shorter is just a tool + // thinking, and rewriting the message then would only make it flicker. + constexpr qint64 kSilenceBeforeNotice = 5000; + constexpr qint64 kWaitNoteInterval = 30000; + + const qint64 elapsed = m_operationClock.elapsed(); + if (elapsed - m_lastOutputAtMs < kSilenceBeforeNotice) return; + + const QString elapsedText = formatElapsed(elapsed); + const QString step = m_operationStep.isEmpty() ? QStringLiteral("en cours") + : m_operationStep; + statusBar()->showMessage(QStringLiteral("%1 — %2").arg(step, elapsedText)); + + if (elapsed - m_lastWaitNoteMs < kWaitNoteInterval) return; + m_lastWaitNoteMs = elapsed; + LogManager::instance().logEvent( + QStringLiteral("opération"), + QStringLiteral("toujours en cours après %1 — %2").arg(elapsedText, step)); } void MainWindow::onCoreHistoryChanged() { diff --git a/tests/progress-tracker.test.cpp b/tests/progress-tracker.test.cpp index e68dd91..dbdfa59 100644 --- a/tests/progress-tracker.test.cpp +++ b/tests/progress-tracker.test.cpp @@ -1,11 +1,15 @@ // Unit tests for ProgressTracker: the single monotonic percentage the UI bars // are fed, built out of the very different ways package managers report their -// progress. No package manager, no display and no network is involved: the -// tracker only reads output lines. +// progress, and for running a command: the escape sequences that come with it, +// and the progress milestones a rewritten meter line is turned into. No package +// manager, no display and no network is involved: the commands are /bin/sh +// one-liners. #include "progress-tracker.h" #include #include +#include +#include // pacman picks up the download counter of the packages it fetches; the bar must // stay inside the download half and finish it at the last package. @@ -113,6 +117,73 @@ static void testRepeatedLinesReportNoChange() { assert(tracker.feed("") == -1); } +// The escape sequences some tools colour their output with are noise: they +// would reach the status bar and the journal as garbage (yay does it, flatpak +// does it as soon as it is on a terminal). +static void testAnsiEscapesAreStripped() { + assert(stripAnsi("\033[32mDownloading\033[0m 50%") == "Downloading 50%"); + assert(stripAnsi("\033[2K\033[1GDownloading") == "Downloading"); + assert(stripAnsi("plain text") == "plain text"); + // An unfinished sequence (the run ended in the middle of one) drops the + // fragment rather than printing half an escape code. + assert(stripAnsi("done\033[3") == "done"); +} + +// A command whose last line has no newline still hands that line over: reading +// until the end of the stream must not drop it. +static void testLastUnterminatedLineIsDelivered() { + std::string text; + runStreamed("printf 'first\\n'; sleep 0.2; printf 'no trailing newline'", + [&](const OutputChunk& chunk) { text += chunk.text; }); + assert(text == "firstno trailing newline"); +} + +// An in-place meter carries a percentage but no sentence: every 10 % step of it +// becomes a line of its own, which is what makes a tool that only rewrites its +// progress bar visible in the status bar and recorded in the journal. +static void testProgressMeterReportsMilestones() { + std::vector messages; + std::vector percents; + + runWithProgress("printf 'Downloading 30%%\\rDownloading 60%%\\rDownloading 95%%\\rdone\\n'", + [&](const std::string& message, int percent) { + if (!message.empty()) messages.push_back(message); + if (percent >= 0) percents.push_back(percent); + }); + + // Three meter steps, one real line, and a milestone line per 10 % step. + assert(messages.size() == 4); + assert(messages[0] == "done"); + assert(messages[1] == "\xE2\x8F\xB3 13 %"); + assert(messages[2] == "\xE2\x8F\xB3 27 %"); + assert(messages[3] == "\xE2\x8F\xB3 42 %"); + + // The bar only ever moves forward, whatever the stream mixes. + for (std::size_t i = 1; i < percents.size(); ++i) { + assert(percents[i] >= percents[i - 1]); + } +} + +// A tool that only prints once in a while must not turn the milestone into a +// log flood: five updates under the step are one line, not five. +static void testMilestonesAreThrottled() { + std::vector milestones; + std::string command; + for (int percent = 1; percent <= 45; percent += 3) { + command += "printf 'Downloading " + std::to_string(percent) + "%%\\r'; "; + } + + runWithProgress(command, [&](const std::string& message, int) { + if (!message.empty() && message.rfind("\xE2\x8F\xB3", 0) == 0) { + milestones.push_back(message); + } + }); + + // The meter reaches 20 % of the download half over those updates, so the + // 10 % step is crossed twice at most. + assert(milestones.size() <= 2); +} + int main() { testDownloadPhaseStaysInsideItsHalf(); testApplyPhaseFollowsTheDownloadPhase(); @@ -124,6 +195,10 @@ int main() { testFinalisationClosesInOnTheEnd(); testRatiosThatAreNotCountersAreIgnored(); testRepeatedLinesReportNoChange(); + testAnsiEscapesAreStripped(); + testLastUnterminatedLineIsDelivered(); + testProgressMeterReportsMilestones(); + testMilestonesAreThrottled(); std::cout << "All progress-tracker tests passed." << std::endl; return 0;