diff --git a/CMakeLists.txt b/CMakeLists.txt index 3f8fe2c..301bd14 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,6 +58,7 @@ set(HEADERS include/update-manager.h include/app-logging.h include/workers.h + include/progress-tracker.h include/app-core.h pages/page.h pages/ui-kit.h @@ -149,6 +150,12 @@ add_executable(package-utils-test tests/package-utils.test.cpp) target_include_directories(package-utils-test PRIVATE include) add_test(NAME package-utils-test COMMAND package-utils-test) +# ProgressTracker is pure logic (it only reads output lines), so it is tested +# without a package manager, a display or even Qt. +add_executable(progress-tracker-test tests/progress-tracker.test.cpp) +target_include_directories(progress-tracker-test PRIVATE include) +add_test(NAME progress-tracker-test COMMAND progress-tracker-test) + add_executable(aur-manager-test tests/aur-manager.test.cpp plugins/aur-provider/aur-manager.cpp) target_include_directories(aur-manager-test PRIVATE include plugins/aur-provider) diff --git a/include/main-window.h b/include/main-window.h index a33f370..4147611 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -145,9 +145,15 @@ private: LogsPage* m_logs = nullptr; PluginsPage* m_plugins = nullptr; - // Small indeterminate bar anchored in the status bar, shown at the bottom - // of the window while any install/search runs. + // Progress of the running operation, anchored in the status bar: the bar + // itself (indeterminate until a provider reports a real percentage) and the + // value next to it. QProgressBar* m_installProgressBar = nullptr; + QLabel* m_progressLabel = nullptr; + // Highest percentage reported by the current operation, and a counter that + // invalidates the "hide the completed bar" timer when a new one starts. + int m_progressValue = 0; + int m_progressGeneration = 0; // Tray (optional: hidden when the desktop has no system tray) QSystemTrayIcon* m_tray = nullptr; diff --git a/include/pacman-manager.h b/include/pacman-manager.h index 99925fc..30ec59b 100644 --- a/include/pacman-manager.h +++ b/include/pacman-manager.h @@ -182,6 +182,7 @@ private: CachedQuery m_installedQuery; // pacman -Q CachedQuery m_installedDetailsQuery; // pacman -Qi CachedQuery m_syncReposQuery; // pacman -Sl + CachedQuery m_updatesQuery; // pacman -Qu std::string m_password; std::string m_lastError; diff --git a/include/progress-tracker.h b/include/progress-tracker.h new file mode 100644 index 0000000..a283d4d --- /dev/null +++ b/include/progress-tracker.h @@ -0,0 +1,307 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "package-manager.h" + +// Reading a package manager's output: streaming it as it is produced, and +// turning it into a progress bar. +// +// No tool reports progress in a form that can be forwarded as-is, which is why +// the bar used to jump around instead of filling up. pacman restarts its +// "(1/24)" counter at every phase of a transaction — "(1/24) téléchargement…", +// then "(1/24) installation…" — so a bar fed with those numbers goes +// 0→100→0→100 a few times per update; flatpak prints "Installing 2/3…" next to +// bare "42 %" updates of the file being unpacked, and the AUR helpers do both. +// ProgressTracker folds all of it into a single percentage that only ever moves +// forward, and runStreamed() hands the lines over as they arrive: a flatpak or +// AUR update used to buffer its whole output and report nothing until it was +// already over. + +// --------------------------------------------------------------------------- +// Streaming a command's output +// --------------------------------------------------------------------------- + +// One piece of a command's output. `partial` marks a chunk that ended with a +// carriage return: the tool is rewriting a progress meter in place (pacman and +// flatpak both do that), so the chunk carries progress but no message worth +// showing. +struct OutputChunk { + std::string text; + bool partial = false; +}; + +using OutputHandler = std::function; + +// Closes a popen() stream. A named deleter avoids the GCC warning about the +// function-pointer attributes carried by decltype(&pclose) being dropped. +struct ProcessCloser { + void operator()(FILE* file) const { + if (file) pclose(file); + } +}; + +// 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. +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}); + 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; + } + } + deliver(/*partial=*/false); // Last line when the command ends without one. + + return output; +} + +// --------------------------------------------------------------------------- +// Turning that output into a percentage +// --------------------------------------------------------------------------- + +// Builds a monotonic 0-99 percentage out of a package manager's chatter. +// +// The work is modelled as two halves — downloading, then applying (installing, +// upgrading or removing) — because that is the shape every tool has: it fetches +// what it needs, then writes it. A phase the tracker cannot place (pacman's key +// integrity checks, its file conflict analysis, its disk space check) holds the +// bar where it is rather than sending it backwards, and 100 % is left to the +// caller so the bar can be completed when the operation is known to have +// succeeded. +class ProgressTracker { +public: + // Feeds one line or chunk. Returns the new percentage when it moved, or -1 + // when the chunk said nothing new — which also keeps the UI free of + // duplicate updates on the hundreds of lines a long update produces. + int feed(const std::string& text) { + if (text.empty()) return -1; + + const std::string lowered = lower(text); + + int current = 0; + int total = 0; + const bool hasCounter = parseCounter(lowered, ¤t, &total); + const int filePercent = parsePercent(lowered); + + int candidate = -1; + if (containsAny(lowered, kApplyWords)) { + candidate = applyProgress(hasCounter, current, total); + } else if (containsAny(lowered, kDownloadWords) + || (!hasCounter && filePercent >= 0)) { + candidate = downloadProgress(hasCounter, current, total, filePercent); + } else if (containsAny(lowered, kFinalWords)) { + candidate = kFinalPercent; + } + + if (candidate < 0) return -1; + candidate = std::min(candidate, kMaxPercent); + if (candidate <= m_percent) return -1; + + m_percent = candidate; + return m_percent; + } + + int percent() const { return m_percent; } + +private: + // Where each half of the work sits on the bar. Downloading usually takes + // the smaller share; the last few percent are left for pacman's hooks. + static constexpr int kDownloadHigh = 45; + static constexpr int kApplyBase = 3; + static constexpr int kApplyHigh = 97; + static constexpr int kFinalPercent = 98; + static constexpr int kMaxPercent = 99; + + // Keywords are matched lowercased, in French and English: pacman output + // follows the system locale, and the AUR helpers wrap pacman. + static constexpr const char* kDownloadWords[] = { + "téléchargement", "telechargement", "récupération", "recuperation", + "downloading", "download", "fetching", "receiving", + }; + static constexpr const char* kApplyWords[] = { + "installation", "installing", "réinstallation", "reinstallation", + "reinstalling", "mise à niveau", "mise a niveau", "upgrading", + "suppression", "removing", "uninstalling", "désinstallation", + }; + static constexpr const char* kFinalWords[] = { + "finalisation", "finalizing", "hook", "traitement des", + }; + + static std::string lower(const std::string& text) { + std::string out = text; + for (char& c : out) { + // Bytes of UTF-8 accents are left alone: every keyword is written + // with the accents the tools themselves print. + if (c < 0) continue; + c = static_cast(std::tolower(static_cast(c))); + } + return out; + } + + template + static bool containsAny(const std::string& text, const char* const (&words)[N]) { + for (size_t i = 0; i < N; ++i) { + if (text.find(words[i]) != std::string::npos) return true; + } + return false; + } + + // Reads a "current/total" counter out of a line: pacman's "(3/24)" and the + // "Installing 2/3" of flatpak and the helpers. Anything that looks like a + // ratio without being a counter (a version, a path, a date) is rejected. + static bool parseCounter(const std::string& text, int* current, int* total) { + for (size_t slash = text.find('/'); slash != std::string::npos; + slash = text.find('/', slash + 1)) { + size_t begin = slash; + while (begin > 0 && std::isdigit(static_cast(text[begin - 1]))) { + --begin; + } + if (begin == slash) continue; + // A dot or a slash right before the number means this is not a + // counter but part of a longer token. + if (begin > 0 && (text[begin - 1] == '.' || text[begin - 1] == '/')) continue; + + size_t end = slash + 1; + while (end < text.size() && std::isdigit(static_cast(text[end]))) { + ++end; + } + if (end == slash + 1) continue; + if (end < text.size() && (text[end] == '.' || text[end] == '/')) continue; + + const std::string numerator = text.substr(begin, slash - begin); + const std::string denominator = text.substr(slash + 1, end - slash - 1); + if (numerator.size() > 6 || denominator.size() > 6) continue; + const int cur = std::atoi(numerator.c_str()); + const int den = std::atoi(denominator.c_str()); + if (den <= 0) continue; + + *current = cur; + *total = den; + return true; + } + return false; + } + + // Reads a bare percentage ("100 %", "42%", "42,5 %") — how download meters + // report the file they are fetching. + static int parsePercent(const std::string& text) { + for (size_t sign = text.find('%'); sign != std::string::npos; + sign = text.find('%', sign + 1)) { + size_t begin = sign; + while (begin > 0 && (std::isdigit(static_cast(text[begin - 1])) + || text[begin - 1] == '.' || text[begin - 1] == ',')) { + --begin; + } + if (begin == sign) continue; + + std::string number = text.substr(begin, sign - begin); + // "42,5 %" is what a French locale writes; atof() stops at the + // comma, so the decimal separator is normalised first. + std::replace(number.begin(), number.end(), ',', '.'); + const double value = std::atof(number.c_str()); + return static_cast(std::clamp(value, 0.0, 100.0)); + } + return -1; + } + + // Download half. The counter counts packages and the percentage counts the + // file being fetched, so combining them places the bar inside the package + // currently downloading instead of jumping to the end of the half as soon + // as the first one lands. + int downloadProgress(bool hasCounter, int current, int total, int filePercent) { + m_sawDownload = true; + if (hasCounter) { + m_downloadCurrent = std::max(m_downloadCurrent, current); + m_downloadTotal = std::max(m_downloadTotal, total); + } + + if (m_downloadTotal > 0) { + const int donePackages = std::max(1, m_downloadCurrent) - 1; + const int done = donePackages * 100 + std::max(0, filePercent); + return kDownloadHigh * done / (m_downloadTotal * 100); + } + if (filePercent >= 0) return kDownloadHigh * filePercent / 100; + return -1; + } + + // Apply half. A transaction with nothing to download (everything cached) + // starts near zero instead of pretending the download half happened. + int applyProgress(bool hasCounter, int current, int total) { + if (hasCounter) { + m_applied = std::max(m_applied, current); + m_applyTotal = std::max(m_applyTotal, total); + } else { + ++m_applied; // Tools that print one line per package without a counter. + } + + const int low = m_sawDownload ? kDownloadHigh : kApplyBase; + if (m_applyTotal <= 0) { + // Nothing to scale against: creep forward so the bar still shows + // the operation is alive. + return low + std::min(m_applied, kApplyHigh - low); + } + const int done = std::min(m_applied, m_applyTotal); + return low + (kApplyHigh - low) * done / m_applyTotal; + } + + int m_percent = 0; + int m_downloadCurrent = 0; + int m_downloadTotal = 0; + int m_applied = 0; + int m_applyTotal = 0; + bool m_sawDownload = false; +}; + +// Runs an action command and reports its progress as (message, percent). +// +// Every provider needs the same three things — the output streamed live, the +// percentages folded into one monotonic value, and an empty message for the +// 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. +inline std::string runWithProgress(const std::string& command, ProgressCallback callback) { + ProgressTracker tracker; + 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); + return; + } + callback(chunk.text, percent); + }); +} diff --git a/pages/browse-page.cpp b/pages/browse-page.cpp index ec7ba20..2afdfae 100644 --- a/pages/browse-page.cpp +++ b/pages/browse-page.cpp @@ -227,12 +227,27 @@ BrowsePage::BrowsePage(AppCore* core, QWidget* parent) : Page(core, parent) { }); connect(core, &AppCore::busyChanged, this, [this](bool busy) { m_progressBar->setVisible(busy); - if (!busy) return; - // Start indeterminate; only the status-bar bar turns determinate once - // the tool reports a real percentage. + if (!busy) { + // A band stopped just before the end reads as a cancellation: when + // real progress was shown, it is completed first. + if (m_progressBar->maximum() > 0) m_progressBar->setValue(100); + return; + } + m_progressValue = 0; + // Start indeterminate; the first real percentage reported by the tool + // turns the band into a determinate fill. m_progressBar->setRange(0, 0); m_progressBar->setValue(0); }); + connect(core, &AppCore::actionProgress, this, + [this](const QString&, int percent) { + if (percent < 0) return; + // Providers (and the commands inside one operation) each count + // from 0 again, so the band only ever moves forward. + if (percent > m_progressValue) m_progressValue = percent; + m_progressBar->setRange(0, 100); + m_progressBar->setValue(m_progressValue); + }); connect(core, &AppCore::actionFinished, this, [this](const QString& action, const QString&, bool success, const QString&, bool) { diff --git a/pages/browse-page.h b/pages/browse-page.h index 0870aae..e0cce1b 100644 --- a/pages/browse-page.h +++ b/pages/browse-page.h @@ -74,6 +74,9 @@ private: QPushButton* m_updateButton = nullptr; QPushButton* m_updateAllButton = nullptr; QProgressBar* m_progressBar = nullptr; + // Highest percentage reported by the running operation, so the bar never + // moves backwards when a provider restarts its own count. + int m_progressValue = 0; QTableWidget* m_table = nullptr; QStackedWidget* m_tableStack = nullptr; QLabel* m_pkgName = nullptr; diff --git a/plugins/aur-provider/aur-manager.cpp b/plugins/aur-provider/aur-manager.cpp index 2e04bfc..541a738 100644 --- a/plugins/aur-provider/aur-manager.cpp +++ b/plugins/aur-provider/aur-manager.cpp @@ -1,4 +1,7 @@ #include "aur-manager.h" + +#include "progress-tracker.h" + #include #include #include @@ -18,17 +21,6 @@ static std::string exec(const char* cmd) { return result; } -// Stream command output lines to the progress callback (text-only, -// percent = -1 keeps the UI bar indeterminate). -static void streamOutput(const std::string& output, ProgressCallback cb) { - if (!cb) return; - std::istringstream iss(output); - std::string line; - while (std::getline(iss, line)) { - if (!line.empty()) cb(line, -1); - } -} - // 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); @@ -166,9 +158,11 @@ bool AurManager::install(const std::string& packageName, return false; } if (progressCallback) progressCallback("Installation AUR de " + packageName + "...", -1); - // Helpers handle sudo themselves; run so the prompt reaches the user. - std::string output = exec((h + " -S --noconfirm " + packageName + " 2>&1").c_str()); - streamOutput(output, progressCallback); + // 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; @@ -185,8 +179,8 @@ bool AurManager::remove(const std::string& packageName, return false; } if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1); - std::string output = exec((h + " -R --noconfirm " + packageName + " 2>&1").c_str()); - streamOutput(output, progressCallback); + 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; @@ -204,8 +198,8 @@ bool AurManager::update(const std::string& packageName, } std::string target = packageName.empty() ? "--aur" : packageName; if (progressCallback) progressCallback("Mise a jour AUR...", -1); - std::string output = exec((h + " -Syu --noconfirm " + target + " 2>&1").c_str()); - streamOutput(output, progressCallback); + 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); @@ -222,8 +216,7 @@ bool AurManager::refresh(ProgressCallback progressCallback) { return false; } if (progressCallback) progressCallback("Rafraichissement AUR...", -1); - std::string output = exec((h + " -Sy 2>&1").c_str()); - streamOutput(output, progressCallback); + 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); diff --git a/plugins/flatpak-provider/flatpak-manager.cpp b/plugins/flatpak-provider/flatpak-manager.cpp index f27e355..d93a248 100644 --- a/plugins/flatpak-provider/flatpak-manager.cpp +++ b/plugins/flatpak-provider/flatpak-manager.cpp @@ -1,4 +1,7 @@ #include "flatpak-manager.h" + +#include "progress-tracker.h" + #include #include #include @@ -41,18 +44,6 @@ static std::string exec(const char* cmd) { return result; } -// Stream the lines of a command's output to the progress callback, if any. -// flatpak exposes no simple percentage, so progress is reported text-only -// (percent = -1 keeps the UI bar indeterminate). -static void streamOutput(const std::string& output, ProgressCallback progressCallback) { - if (!progressCallback) return; - std::istringstream iss(output); - std::string line; - while (std::getline(iss, line)) { - if (!line.empty()) progressCallback(line, -1); - } -} - // 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". @@ -255,9 +246,12 @@ bool FlatpakManager::install(const std::string& packageName, 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 exec(("flatpak install --noninteractive --assumeyes " + extra + " " - + packageName + " 2>&1").c_str()); + return runWithProgress("flatpak install --noninteractive --assumeyes " + extra + + " " + packageName + " 2>&1", + progressCallback); }; // A fresh flatpak setup has no remote configured: add the default flathub @@ -283,7 +277,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); - exec("flatpak update --appstream 2>&1"); + runWithProgress("flatpak update --appstream 2>&1", progressCallback); output = tryInstall(ambiguous() ? "--user flathub" : ""); } @@ -293,8 +287,6 @@ bool FlatpakManager::install(const std::string& packageName, output = tryInstall("--user flathub"); } - streamOutput(output, progressCallback); - // 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)) { @@ -388,9 +380,9 @@ bool FlatpakManager::remove(const std::string& packageName, m_lastError.clear(); if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1); - std::string output = exec( - ("flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1").c_str()); - streamOutput(output, progressCallback); + std::string output = runWithProgress( + "flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1", + progressCallback); if (output.find("error:") != std::string::npos || isInstalled(packageName)) { m_lastError = lastOutputLines(output); @@ -406,11 +398,9 @@ bool FlatpakManager::update(const std::string& packageName, ProgressCallback progressCallback) { m_lastError.clear(); auto tryUpdate = [&](const std::string& extra) { - if (packageName.empty()) { - return exec(("flatpak update --noninteractive --assumeyes " + extra + " 2>&1").c_str()); - } - return exec(("flatpak update --noninteractive --assumeyes " + extra + " " - + packageName + " 2>&1").c_str()); + std::string command = "flatpak update --noninteractive --assumeyes " + extra; + if (!packageName.empty()) command += " " + packageName; + return runWithProgress(command + " 2>&1", progressCallback); }; if (packageName.empty()) { @@ -425,7 +415,6 @@ bool FlatpakManager::update(const std::string& packageName, if (progressCallback) progressCallback("Nouvel essai en mode utilisateur...", -1); output = tryUpdate("--user"); } - streamOutput(output, progressCallback); if (output.find("error:") != std::string::npos) { m_lastError = lastOutputLines(output); @@ -440,15 +429,14 @@ 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 = exec("flatpak update --appstream 2>&1"); + std::string output = runWithProgress("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 = exec("flatpak update --appstream --user 2>&1"); + output = runWithProgress("flatpak update --appstream --user 2>&1", progressCallback); } - streamOutput(output, progressCallback); if (output.find("error:") != std::string::npos) { m_lastError = lastOutputLines(output); @@ -470,9 +458,8 @@ 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 = exec( - "flatpak uninstall --unused --noninteractive --assumeyes 2>&1"); - streamOutput(output, progressCallback); + std::string output = runWithProgress( + "flatpak uninstall --unused --noninteractive --assumeyes 2>&1", progressCallback); if (output.find("error:") != std::string::npos) { m_lastError = lastOutputLines(output); diff --git a/src/main-window.cpp b/src/main-window.cpp index b36f8b3..861f970 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -222,8 +222,12 @@ static QString appStyleSheet() { " color: #e2e8f0;" "}" // ---- Progress bar ---- - "QProgressBar { background: #273449; border: none; border-radius: 3px; }" - "QProgressBar::chunk { background: #38bdf8; border-radius: 3px; }" + // The value is spelled out beside the bar rather than inside it: the + // label Qt centres on the bar would sit half on the fill and half on + // the track, where no single colour stays readable. + "QLabel#progressLabel { color: #7dd3fc; font-size: 11px; font-weight: 700; padding-right: 8px; }" + "QProgressBar { background: #273449; border: none; border-radius: 4px; }" + "QProgressBar::chunk { background: #38bdf8; border-radius: 4px; }" // ---- Package table ---- // No outer frame: the table blends with the card it sits in, keeping // only the column header and alternating rows as visual separators. @@ -408,14 +412,20 @@ void MainWindow::setupUI() { statusBar()->showMessage("Prêt"); - // Tiny indeterminate bar anchored at the bottom of the window: it appears - // while install/update/remove/search operations run, without taking space - // on the screens. + // Progress of the running operation, anchored at the bottom of the window + // so it takes no space on the screens. It appears while install/update/ + // remove/search operations run: indeterminate at first, then filled to the + // real percentage reported by the provider (see onCoreActionProgress). + m_progressLabel = new QLabel(); + m_progressLabel->setObjectName("progressLabel"); + m_progressLabel->setVisible(false); + statusBar()->addPermanentWidget(m_progressLabel); + m_installProgressBar = new QProgressBar(); m_installProgressBar->setRange(0, 0); m_installProgressBar->setTextVisible(false); - m_installProgressBar->setFixedHeight(4); - m_installProgressBar->setFixedWidth(120); + m_installProgressBar->setFixedHeight(8); + m_installProgressBar->setFixedWidth(160); m_installProgressBar->setVisible(false); statusBar()->addPermanentWidget(m_installProgressBar); @@ -1011,11 +1021,17 @@ void MainWindow::onCoreActionProgress(const QString& message, int percent) { if (!message.isEmpty()) statusBar()->showMessage(message); if (percent < 0) return; - // A real download percentage reported by the provider fills the bottom bar - // as a determinate progress. + // A provider running several commands (or a second provider after the + // first) starts its own count at 0: within one operation the bar only ever + // moves forward, so a retry or a second command never sends it backwards. + if (percent > m_progressValue) m_progressValue = percent; + m_installProgressBar->setVisible(true); m_installProgressBar->setRange(0, 100); - m_installProgressBar->setValue(percent); + m_installProgressBar->setValue(m_progressValue); + + m_progressLabel->setText(QString("%1 %").arg(m_progressValue)); + m_progressLabel->setVisible(true); } void MainWindow::onCoreActionFinished(const QString& action, const QString& name, @@ -1036,13 +1052,36 @@ void MainWindow::onCoreActionFinished(const QString& action, const QString& name } void MainWindow::onCoreBusyChanged(bool busy) { - m_installProgressBar->setVisible(busy); - if (!busy) return; + // Any pending "hide the finished bar" timer belongs to the previous + // operation and must not touch the new one. + ++m_progressGeneration; - // Start indeterminate; a real percentage (onCoreActionProgress) switches the - // bar to a determinate fill once the tool reports progress. + if (!busy) { + if (m_installProgressBar->isVisible() && m_installProgressBar->maximum() > 0) { + // Real progress was shown: complete it and let it be seen. A bar + // that disappears at 97 % looks like a failure. + m_installProgressBar->setValue(100); + m_progressLabel->setText(QStringLiteral("100 %")); + const int generation = m_progressGeneration; + QTimer::singleShot(500, this, [this, generation] { + if (generation != m_progressGeneration) return; + m_installProgressBar->setVisible(false); + m_progressLabel->setVisible(false); + }); + return; + } + m_installProgressBar->setVisible(false); + m_progressLabel->setVisible(false); + return; + } + + // Start indeterminate; the first real percentage (onCoreActionProgress) + // switches the bar to a determinate fill. + m_progressValue = 0; m_installProgressBar->setRange(0, 0); m_installProgressBar->setValue(0); + m_installProgressBar->setVisible(true); + m_progressLabel->setVisible(false); } void MainWindow::onCoreStatusMessage(const QString& message) { diff --git a/src/pacman-manager.cpp b/src/pacman-manager.cpp index 8fb8797..d338457 100644 --- a/src/pacman-manager.cpp +++ b/src/pacman-manager.cpp @@ -1,4 +1,7 @@ #include "pacman-manager.h" + +#include "progress-tracker.h" + #include #include #include @@ -60,61 +63,21 @@ static std::string lastOutputLines(const std::string& output, int keep = 5) { return out; } -// Read a (current/Total) package counter out of a pacman line; see definition -// below. Declared first because execPrivileged uses it. -static int percentFromLine(const std::string& line); - // Run a privileged pacman command as root, piping the password to `sudo -S` -// on stdin and capturing combined stdout+stderr. Lines are delivered to the -// progress callback as soon as they are produced (pacman prints the download -// progress as it goes, so this keeps the UI bar live). The full output is -// still returned for auth/error checks. +// on stdin and capturing combined stdout+stderr. Output is delivered to the +// progress callback as pacman produces it — including its in-place download +// meters, which is what makes the bar move during a long download — and the +// full output is still returned for the auth/error checks. +// +// The percentage comes from ProgressTracker, not from the raw counters: pacman +// restarts "(1/24)" at every phase of the transaction, so forwarding those +// numbers made the bar go backwards several times per update. static std::string execPrivileged(const std::string& pacmanCmd, const std::string& password, ProgressCallback progressCallback) { - std::string full = "printf '%s\\n' " + shellQuote(password) - + " | sudo -S " + pacmanCmd + " 2>&1"; - - std::array buffer; - std::string result; - std::unique_ptr pipe(popen(full.c_str(), "r"), pclose); - if (!pipe) throw std::runtime_error("popen() failed"); - - // Force line-buffered on the read side; pacman flushes its progress lines - // with newlines so each is forwarded as soon as it is emitted. - while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { - std::string line(buffer.data()); - result += line; - // Trim the trailing newline for the callback. - while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) { - line.pop_back(); - } - if (progressCallback && !line.empty()) { - progressCallback(line, percentFromLine(line)); - } - } - return result; -} - -// Read a (current/Total) package counter out of a pacman line, e.g. -// "(3/5) téléchargement de ...". Returns a 0-100 percentage, or -1 when the -// line carries no counter (so the caller keeps the previous value / unknown). -static int percentFromLine(const std::string& line) { - size_t open = line.find('('); - size_t close = line.find(')'); - if (open == std::string::npos || close == std::string::npos || open > close) return -1; - std::string inner = line.substr(open + 1, close - open - 1); - size_t slash = inner.find('/'); - if (slash == std::string::npos) return -1; - try { - long cur = std::stol(inner.substr(0, slash)); - long total = std::stol(inner.substr(slash + 1)); - if (total <= 0) return -1; - int pct = static_cast(cur * 100 / total); - return std::max(0, std::min(100, pct)); - } catch (...) { - return -1; - } + const std::string full = "printf '%s\\n' " + shellQuote(password) + + " | sudo -S " + pacmanCmd + " 2>&1"; + return runWithProgress(full, progressCallback); } // pacman's database lock file. Every manager that goes through libalpm (pacman, @@ -140,17 +103,6 @@ static constexpr int kKillGraceMs = 3000; // cache outright. static constexpr std::chrono::seconds kQueryTtl{10}; -// Stream the lines of a command's output (already captured) to the callback — -// used by providers that buffer a whole command first. Percent stays unknown. -static void streamOutput(const std::string& output, ProgressCallback progressCallback) { - if (!progressCallback) return; - std::istringstream iss(output); - std::string line; - while (std::getline(iss, line)) { - if (!line.empty()) progressCallback(line, -1); - } -} - std::string PacmanManager::cachedQuery(PacmanManager::CachedQuery& slot, const char* command) { const auto now = std::chrono::steady_clock::now(); @@ -177,6 +129,7 @@ void PacmanManager::invalidateQueries() { m_installedQuery.valid = false; m_installedDetailsQuery.valid = false; m_syncReposQuery.valid = false; + m_updatesQuery.valid = false; } std::vector PacmanManager::search(const std::string& query) { @@ -366,7 +319,10 @@ static std::vector parseUpdatesOutput(const std::string& output) { } std::vector PacmanManager::listUpdates() { - return parseUpdatesOutput(exec("pacman -Qu 2>&1")); + // Cached like the other read-only queries: the dashboard badge, the updates + // screen and the "Tout mettre à jour" button all ask for it within the same + // second, and one pacman process answers for all of them. + return parseUpdatesOutput(cachedQuery(m_updatesQuery, "pacman -Qu 2>&1")); } // Orphans (-Qdt: no installed package requires them) and legacy packages (-Qm: diff --git a/src/workers.cpp b/src/workers.cpp index da5f686..9d9f0a9 100644 --- a/src/workers.cpp +++ b/src/workers.cpp @@ -98,19 +98,27 @@ void InstallWorker::run() { return; } + const int providerCount = static_cast(m_providers.size()); bool success = true; - for (IPackageManager* pm : m_providers) { + for (int index = 0; index < providerCount; ++index) { + IPackageManager* pm = m_providers[static_cast(index)]; // Prefix progress lines with the provider when several run at once. // A real percentage (>= 0) also drives the determinate status bar bar. - auto cb = [this, pm](const std::string& msg, int percent) { - if (m_providers.size() > 1) { + auto cb = [this, pm, index, providerCount](const std::string& msg, int percent) { + if (providerCount > 1) { emit progress(QString("[%1] %2") .arg(QString::fromStdString(pm->getName()), QString::fromStdString(msg))); } else { emit progress(QString::fromStdString(msg)); } - if (percent >= 0) emit progressValue(percent); + if (percent < 0) return; + + // Providers run one after the other, so each one owns an equal + // slice of the bar. Without this the bar dropped back to 0 when the + // second provider (flatpak, after pacman) started its own count. + const int scaled = (index * 100 + percent) / providerCount; + emit progressValue(std::min(scaled, 99)); }; // Keep running the remaining providers even if one fails. diff --git a/tests/progress-tracker.test.cpp b/tests/progress-tracker.test.cpp new file mode 100644 index 0000000..e68dd91 --- /dev/null +++ b/tests/progress-tracker.test.cpp @@ -0,0 +1,130 @@ +// 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. +#include "progress-tracker.h" + +#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. +static void testDownloadPhaseStaysInsideItsHalf() { + ProgressTracker tracker; + + tracker.feed(" (1/4) téléchargement de a-1.0-1-x86_64..."); + const int first = tracker.percent(); + assert(first >= 0 && first < 45); + + // The file being fetched drives the bar inside the package it belongs to. + assert(tracker.feed(" a-1.0-1-x86_64 1.2 MiB 640 KiB/s [####] 50%") == 5); + + tracker.feed(" (4/4) téléchargement de d-1.0-1-x86_64..."); + assert(tracker.feed(" d-1.0-1-x86_64 1.2 MiB 640 KiB/s [####] 100%") == 45); +} + +// The install phase starts where the download phase stopped (pacman restarts +// its counter at 1, so the raw numbers would send the bar back to zero). +static void testApplyPhaseFollowsTheDownloadPhase() { + ProgressTracker tracker; + tracker.feed(" (1/1) téléchargement de a-1.0-1-x86_64..."); + tracker.feed(" a-1.0-1-x86_64 1.2 MiB 640 KiB/s [####] 100%"); + assert(tracker.percent() == 45); + + assert(tracker.feed(" (1/4) installation de a-1.0-1-x86_64...") == 58); + assert(tracker.feed(" (2/4) installation de b-1.0-1-x86_64...") == 71); + assert(tracker.feed(" (4/4) installation de d-1.0-1-x86_64...") == 97); +} + +// A transaction with nothing to download (everything already cached) starts +// near zero instead of pretending the download half happened. +static void testApplyOnlyTransactionStartsLow() { + ProgressTracker tracker; + assert(tracker.feed(" (1/2) installation de a-1.0-1-x86_64...") == 50); + assert(tracker.feed(" (2/2) installation de b-1.0-1-x86_64...") == 97); +} + +// Steps whose share of the work is unknown — pacman's key and integrity +// checks, its file conflict analysis — hold the bar instead of moving it back. +static void testUnknownStepsHoldTheBar() { + ProgressTracker tracker; + tracker.feed(" (1/4) installation de a-1.0-1-x86_64..."); + const int held = tracker.percent(); + + assert(tracker.feed(" (1/4) vérification des clés du trousseau") == -1); + assert(tracker.feed(" (2/4) analyse des conflits entre fichiers") == -1); + assert(tracker.percent() == held); +} + +// A counter that goes backwards (a retry, a second command, a new phase) never +// lowers the value: this is what used to make the bar bounce left and right. +static void testValueNeverMovesBackwards() { + ProgressTracker tracker; + assert(tracker.feed(" (3/4) installation de c-1.0-1-x86_64...") == 84); + assert(tracker.feed(" (1/4) installation de a-1.0-1-x86_64...") == -1); + assert(tracker.percent() == 84); +} + +// flatpak and the AUR helpers print "Installing 1/3…" instead of a parenthesised +// counter; both must be understood. +static void testFlatpakAndHelperCountersAreRead() { + ProgressTracker tracker; + assert(tracker.feed("Installing 1/3…") == 34); + assert(tracker.feed("Installing 2/3…") == 65); + assert(tracker.feed("Installing 3/3…") == 97); + + ProgressTracker english; + assert(english.feed(" (1/2) downloading base-1.0-1-x86_64...") == 22); + assert(english.feed(" (2/2) upgrading base-1.0-1-x86_64...") == 71); +} + +// A bare "12 %" with no keyword is a download meter (that is the only place +// tools print one without naming the step). +static void testBarePercentIsDownloadProgress() { + ProgressTracker tracker; + assert(tracker.feed(" 12% ░░░░░░░░░░") == 5); + assert(tracker.feed(" 50% ░░░░░░░░░░") == 22); +} + +// Finalisation and hooks are the last step before completion, which the caller +// reports: the tracker itself never claims 100 %. +static void testFinalisationClosesInOnTheEnd() { + ProgressTracker tracker; + assert(tracker.feed(":: Finalisation de la transaction...") == 98); + assert(tracker.feed(" (1/1) hook: installation de a...") == 98); + assert(tracker.percent() < 100); +} + +// Nothing that only looks like a counter may be read as one. +static void testRatiosThatAreNotCountersAreIgnored() { + ProgressTracker tracker; + assert(tracker.feed(":: Synchronisation des bases de données du paquet…") == -1); + assert(tracker.feed(" https://mirror.example.org/arch/extra/os/x86_64/") == -1); + assert(tracker.feed("firefox 128.0.2/1.0 nothing to do") == -1); + assert(tracker.percent() == 0); +} + +// Repeating the same line (pacman reprints steps as it goes) costs nothing and +// produces no UI update. +static void testRepeatedLinesReportNoChange() { + ProgressTracker tracker; + assert(tracker.feed(" (1/2) installation de a-1.0-1-x86_64...") == 50); + assert(tracker.feed(" (1/2) installation de a-1.0-1-x86_64...") == -1); + assert(tracker.feed("") == -1); +} + +int main() { + testDownloadPhaseStaysInsideItsHalf(); + testApplyPhaseFollowsTheDownloadPhase(); + testApplyOnlyTransactionStartsLow(); + testUnknownStepsHoldTheBar(); + testValueNeverMovesBackwards(); + testFlatpakAndHelperCountersAreRead(); + testBarePercentIsDownloadProgress(); + testFinalisationClosesInOnTheEnd(); + testRatiosThatAreNotCountersAreIgnored(); + testRepeatedLinesReportNoChange(); + + std::cout << "All progress-tracker tests passed." << std::endl; + return 0; +}