From cd5bed0f4d591283f1b9dfd26b968a3d46d61771 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Sat, 29 Aug 2026 20:17:45 +0200 Subject: [PATCH] feat(ui): stream search results and show real download progress MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Search now publishes provider results in small batches as they arrive, so the first matches appear in the table while slower providers keep running. The bottom status-bar bar is now a determinate indicator: pacman output is streamed live and its (n/Total) package counter is parsed into a percentage that fills the bar during install/update, instead of an indeterminate spinner. Generated with Codebuff 🤖 Co-Authored-By: Codebuff --- include/flatpak-manager.h | 8 +- include/main-window.h | 13 ++ include/package-manager.h | 13 +- include/pacman-manager.h | 8 +- plugins/example-provider/example-provider.cpp | 14 +- src/flatpak-manager.cpp | 33 ++-- src/main-window.cpp | 171 +++++++++++++----- src/pacman-manager.cpp | 98 +++++++--- 8 files changed, 246 insertions(+), 112 deletions(-) diff --git a/include/flatpak-manager.h b/include/flatpak-manager.h index 22d8f7d..2227b8b 100644 --- a/include/flatpak-manager.h +++ b/include/flatpak-manager.h @@ -40,14 +40,14 @@ public: std::vector search(const std::string& query) override; bool install(const std::string& packageName, - std::function progressCallback) override; + ProgressCallback progressCallback) override; bool remove(const std::string& packageName, - std::function progressCallback) override; + ProgressCallback progressCallback) override; bool update(const std::string& packageName = "", - std::function progressCallback = nullptr) override; + ProgressCallback progressCallback = nullptr) override; std::vector listInstalled() override; std::vector listUpdates() override; - bool refresh(std::function progressCallback = nullptr) override; + bool refresh(ProgressCallback progressCallback = nullptr) override; // Make an app appear in the desktop's application launcher (wofi, GNOME, // KDE, ...) regardless of XDG_DATA_DIRS, like a pacman install would: link diff --git a/include/main-window.h b/include/main-window.h index 04e0400..76eddd8 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -38,6 +38,9 @@ public: void run() override; signals: void finished(std::vector results); + // Emitted as search results are accumulated, so a few packages can be + // shown immediately while the remaining searches keep running. + void chunk(std::vector results); private: std::vector m_providers; std::string m_query; @@ -70,6 +73,9 @@ public: void run() override; signals: void progress(const QString& message); + // Real download percentage (0-100) when the provider reports it, used to + // fill the determinate progress bar in the status bar. + void progressValue(int percent); void finished(bool success); private: std::vector m_providers; @@ -91,7 +97,9 @@ private slots: void onUpdateAll(); void onRefresh(); void onSearchFinished(std::vector results); + void onSearchChunk(std::vector results); void onListFinished(std::vector results); + void onInstallProgress(int percent); void onPackageSelected(int row); void onNavChanged(int id); void onClearHistory(); @@ -143,6 +151,8 @@ private: void performInstall(const std::string& package); void performRemove(const std::string& package); void populatePackageTable(const std::vector& results); + void appendPackageRows(const std::vector& results); + void addPackageRow(int row, const PackageInfo& pkg); void setBusy(bool busy); void reloadCurrentView(); void loadInstalled(); @@ -184,6 +194,9 @@ private: QPushButton* m_updateButton = nullptr; QPushButton* m_updateAllButton = nullptr; QProgressBar* m_progressBar = nullptr; + // Small indeterminate bar anchored in the status bar, shown at the bottom + // of the window while any install/search runs. + QProgressBar* m_installProgressBar = nullptr; QTableWidget* m_packageTable = nullptr; QLabel* m_packageName = nullptr; QLabel* m_packageVersion = nullptr; diff --git a/include/package-manager.h b/include/package-manager.h index 559508d..1740a97 100644 --- a/include/package-manager.h +++ b/include/package-manager.h @@ -108,6 +108,11 @@ inline void sortByProviderThenName(std::vector& packages, }); } +// Progress reported during an operation: a human-readable message plus an +// optional percentage (0-100) when the tool exposes real progress, or -1 when +// the exact position is unknown. -1 lets the UI keep an indeterminate bar. +using ProgressCallback = std::function; + // Abstract interface for the package manager class IPackageManager { public: @@ -128,14 +133,14 @@ public: // Operations virtual std::vector search(const std::string& query) = 0; virtual bool install(const std::string& packageName, - std::function progressCallback = nullptr) = 0; + ProgressCallback progressCallback = nullptr) = 0; virtual bool remove(const std::string& packageName, - std::function progressCallback = nullptr) = 0; + ProgressCallback progressCallback = nullptr) = 0; virtual bool update(const std::string& packageName = "", - std::function progressCallback = nullptr) = 0; + ProgressCallback progressCallback = nullptr) = 0; virtual std::vector listInstalled() = 0; virtual std::vector listUpdates() = 0; - virtual bool refresh(std::function progressCallback = nullptr) = 0; + virtual bool refresh(ProgressCallback progressCallback = nullptr) = 0; // Check if the package manager is available on the system virtual bool isAvailable() const = 0; diff --git a/include/pacman-manager.h b/include/pacman-manager.h index 0cd1203..8094c92 100644 --- a/include/pacman-manager.h +++ b/include/pacman-manager.h @@ -51,14 +51,14 @@ public: std::vector search(const std::string& query) override; bool install(const std::string& packageName, - std::function progressCallback) override; + ProgressCallback progressCallback) override; bool remove(const std::string& packageName, - std::function progressCallback) override; + ProgressCallback progressCallback) override; bool update(const std::string& packageName = "", - std::function progressCallback = nullptr) override; + ProgressCallback progressCallback = nullptr) override; std::vector listInstalled() override; std::vector listUpdates() override; - bool refresh(std::function progressCallback = nullptr) override; + bool refresh(ProgressCallback progressCallback = nullptr) override; private: bool isPackageInstalled(const std::string& name); diff --git a/plugins/example-provider/example-provider.cpp b/plugins/example-provider/example-provider.cpp index c7747f6..175647a 100644 --- a/plugins/example-provider/example-provider.cpp +++ b/plugins/example-provider/example-provider.cpp @@ -34,18 +34,12 @@ public: bool isAvailable() const override { return true; } std::vector search(const std::string&) override { return {}; } - bool install(const std::string&, std::function) override { - return false; - } - bool remove(const std::string&, std::function) override { - return false; - } - bool update(const std::string&, std::function) override { - return false; - } + bool install(const std::string&, ProgressCallback) override { return false; } + bool remove(const std::string&, ProgressCallback) override { return false; } + bool update(const std::string&, ProgressCallback) override { return false; } std::vector listInstalled() override { return {}; } std::vector listUpdates() override { return {}; } - bool refresh(std::function) override { return false; } + bool refresh(ProgressCallback) override { return false; } }; FWS_PROVIDER_PLUGIN(SampleProvider, "sample", "Sample Provider", "0.1.0", diff --git a/src/flatpak-manager.cpp b/src/flatpak-manager.cpp index 5f4dad2..642b8f6 100644 --- a/src/flatpak-manager.cpp +++ b/src/flatpak-manager.cpp @@ -42,13 +42,14 @@ static std::string exec(const char* cmd) { } // Stream the lines of a command's output to the progress callback, if any. -static void streamOutput(const std::string& output, - std::function progressCallback) { +// 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); + if (!line.empty()) progressCallback(line, -1); } } @@ -240,19 +241,19 @@ bool FlatpakManager::isInstalled(const std::string& appId) { } bool FlatpakManager::install(const std::string& packageName, - std::function progressCallback) { + ProgressCallback progressCallback) { m_lastError.clear(); // Idempotent: an app already deployed (in either installation) is reported // as installed without re-running the installer, then made sure it appears // in the desktop launcher (covers apps installed before this feature). if (isInstalled(packageName)) { - if (progressCallback) progressCallback(packageName + " est déjà installé."); + if (progressCallback) progressCallback(packageName + " est déjà installé.", -1); integrateDesktopEntries(packageName); return true; } - if (progressCallback) progressCallback("Installation de " + packageName + "..."); + if (progressCallback) progressCallback("Installation de " + packageName + "...", -1); auto tryInstall = [&](const std::string& extra) { return exec(("flatpak install --noninteractive --assumeyes " + extra + " " @@ -281,14 +282,14 @@ bool FlatpakManager::install(const std::string& packageName, // repeating a doomed attempt. if (output.find("error:") != std::string::npos && !isInstalled(packageName) && (noRefs() || ambiguous())) { - if (progressCallback) progressCallback("Mise à jour des métadonnées des dépôts..."); + if (progressCallback) progressCallback("Mise à jour des métadonnées des dépôts...", -1); exec("flatpak update --appstream 2>&1"); output = tryInstall(ambiguous() ? "--user flathub" : ""); } // Remaining failures get one per-user attempt (no polkit, no ambiguity). if (output.find("error:") != std::string::npos && !isInstalled(packageName)) { - if (progressCallback) progressCallback("Nouvel essai en mode utilisateur..."); + if (progressCallback) progressCallback("Nouvel essai en mode utilisateur...", -1); output = tryInstall("--user flathub"); } @@ -383,9 +384,9 @@ void FlatpakManager::integrateAllInstalled() { } bool FlatpakManager::remove(const std::string& packageName, - std::function progressCallback) { + ProgressCallback progressCallback) { m_lastError.clear(); - if (progressCallback) progressCallback("Suppression de " + packageName + "..."); + if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1); std::string output = exec( ("flatpak uninstall --noninteractive --assumeyes " + packageName + " 2>&1").c_str()); @@ -402,7 +403,7 @@ bool FlatpakManager::remove(const std::string& packageName, } bool FlatpakManager::update(const std::string& packageName, - std::function progressCallback) { + ProgressCallback progressCallback) { m_lastError.clear(); auto tryUpdate = [&](const std::string& extra) { if (packageName.empty()) { @@ -413,15 +414,15 @@ bool FlatpakManager::update(const std::string& packageName, }; if (packageName.empty()) { - if (progressCallback) progressCallback("Mise à jour de toutes les applications..."); + if (progressCallback) progressCallback("Mise à jour de toutes les applications...", -1); } else { - if (progressCallback) progressCallback("Mise à jour de " + packageName + "..."); + if (progressCallback) progressCallback("Mise à jour de " + packageName + "...", -1); } std::string output = tryUpdate(""); // System-wide updates need polkit: fall back to the per-user installation. if (output.find("error:") != std::string::npos) { - if (progressCallback) progressCallback("Nouvel essai en mode utilisateur..."); + if (progressCallback) progressCallback("Nouvel essai en mode utilisateur...", -1); output = tryUpdate("--user"); } streamOutput(output, progressCallback); @@ -433,9 +434,9 @@ bool FlatpakManager::update(const std::string& packageName, return true; } -bool FlatpakManager::refresh(std::function progressCallback) { +bool FlatpakManager::refresh(ProgressCallback progressCallback) { m_lastError.clear(); - if (progressCallback) progressCallback("Rafraîchissement des métadonnées Flatpak..."); + if (progressCallback) progressCallback("Rafraîchissement des métadonnées Flatpak...", -1); // Re-download the appstream metadata of every remote so search and // update detection reflect the latest published versions. diff --git a/src/main-window.cpp b/src/main-window.cpp index 793a172..af08ade 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -35,11 +35,26 @@ void SearchWorker::run() { std::vector results; for (IPackageManager* pm : m_providers) { if (!pm->canSearch()) continue; + + // Publish the freshly found packages right away, grouped in small + // batches so the table starts filling while the next provider is still + // running its (potentially slow) search in the background. + std::vector providerResults; for (auto& pkg : pm->search(m_query)) { pkg.provider = pm->getName(); - results.push_back(pkg); + providerResults.push_back(pkg); } + constexpr int kBatchSize = 10; + for (size_t i = 0; i < providerResults.size(); i += kBatchSize) { + std::vector batch( + providerResults.begin() + i, + providerResults.begin() + std::min(i + kBatchSize, providerResults.size())); + emit chunk(std::move(batch)); + } + + results.insert(results.end(), providerResults.begin(), providerResults.end()); } + // One row per package name, whatever the number of providers offering it. mergeProviderDuplicates(results); @@ -86,7 +101,8 @@ void InstallWorker::run() { bool success = true; for (IPackageManager* pm : m_providers) { // Prefix progress lines with the provider when several run at once. - auto cb = [this, pm](const std::string& msg) { + // 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) { emit progress(QString("[%1] %2") .arg(QString::fromStdString(pm->getName()), @@ -94,6 +110,7 @@ void InstallWorker::run() { } else { emit progress(QString::fromStdString(msg)); } + if (percent >= 0) emit progressValue(percent); }; // Keep running the remaining providers even if one fails. @@ -241,6 +258,17 @@ 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 content pages. + m_installProgressBar = new QProgressBar(); + m_installProgressBar->setRange(0, 0); + m_installProgressBar->setTextVisible(false); + m_installProgressBar->setFixedHeight(4); + m_installProgressBar->setFixedWidth(120); + m_installProgressBar->setVisible(false); + statusBar()->addPermanentWidget(m_installProgressBar); + setStyleSheet( // ---- Base ---- "QMainWindow, QWidget { background: #0d1017; color: #dbe2f0; }" @@ -1263,11 +1291,18 @@ void MainWindow::onSearch() { m_packageTable->setRowCount(0); SearchWorker* worker = new SearchWorker(providers, query); + connect(worker, &SearchWorker::chunk, this, &MainWindow::onSearchChunk); connect(worker, &SearchWorker::finished, this, &MainWindow::onSearchFinished); connect(worker, &SearchWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } +// Called as results stream in: append the incoming row instead of rebuilding +// the whole table, so the first matches appear while the search continues. +void MainWindow::onSearchChunk(std::vector results) { + appendPackageRows(results); +} + void MainWindow::loadInstalled() { setBusy(true); statusBar()->showMessage("Chargement des paquets installés..."); @@ -1294,6 +1329,8 @@ void MainWindow::loadUpdates() { void MainWindow::onSearchFinished(std::vector results) { setBusy(false); + // The table is already filled incrementally via onSearchChunk; rebuild it + // once at the end to guarantee a consistent final list. populatePackageTable(results); statusBar()->showMessage(QString("%1 paquet(s) trouvé(s)").arg(results.size())); } @@ -1349,53 +1386,8 @@ void MainWindow::populatePackageTable(const std::vector& results) { m_packageTable->setRowCount(0); m_packageTable->setRowCount(static_cast(results.size())); - QFont nameFont; - nameFont.setWeight(QFont::DemiBold); - for (int i = 0; i < static_cast(results.size()); ++i) { - const PackageInfo& pkg = results[i]; - - QTableWidgetItem* nameItem = new QTableWidgetItem(QString::fromStdString(pkg.name)); - nameItem->setFont(nameFont); - m_packageTable->setItem(i, 0, nameItem); - - m_packageTable->setItem(i, 1, - new QTableWidgetItem(QString::fromStdString(pkg.version))); - - m_packageTable->setItem(i, 2, new QTableWidgetItem( - pkg.repository.empty() ? "—" : QString::fromStdString(pkg.repository))); - - QTableWidgetItem* providerItem = new QTableWidgetItem( - providersLabel(m_pluginManager, pkg)); - providerItem->setForeground(QColor("#98a0b3")); - providerItem->setIcon(loadIcon("package")); - m_packageTable->setItem(i, 3, providerItem); - - QString statusText; - QString statusIcon; - QColor statusColor; - if (pkg.installed && pkg.updateAvailable) { - statusText = "MAJ dispo"; - statusIcon = "arrow-up"; - statusColor = QColor("#e0af68"); - } else if (pkg.installed) { - statusText = "Installé"; - statusIcon = "check"; - statusColor = QColor("#3fb950"); - } else if (!pkg.repository.empty()) { - statusText = "Disponible"; - statusIcon = "package"; - statusColor = QColor("#98a0b3"); - } else { - statusText = "—"; - statusIcon.clear(); - statusColor = QColor("#565f73"); - } - - QTableWidgetItem* statusItem = new QTableWidgetItem(statusText); - statusItem->setForeground(statusColor); - if (!statusIcon.isEmpty()) statusItem->setIcon(loadIcon(statusIcon)); - m_packageTable->setItem(i, 4, statusItem); + addPackageRow(i, results[i]); } m_resultCount->setText(QString("%1 paquet(s)").arg(results.size())); @@ -1421,6 +1413,66 @@ void MainWindow::populatePackageTable(const std::vector& results) { m_packageTable->selectRow(0); } +// Appends an incoming search chunk to the already-displayed rows, updating the +// stored result set so selection and the details panel stay consistent. +void MainWindow::appendPackageRows(const std::vector& results) { + const int startRow = static_cast(m_currentResults.size()); + m_currentResults.insert(m_currentResults.end(), results.begin(), results.end()); + m_packageTable->setRowCount(static_cast(m_currentResults.size())); + + for (size_t i = 0; i < results.size(); ++i) { + addPackageRow(startRow + static_cast(i), results[i]); + } + m_resultCount->setText(QString("%1 paquet(s)").arg(m_currentResults.size())); +} + +void MainWindow::addPackageRow(int i, const PackageInfo& pkg) { + QFont nameFont; + nameFont.setWeight(QFont::DemiBold); + + QTableWidgetItem* nameItem = new QTableWidgetItem(QString::fromStdString(pkg.name)); + nameItem->setFont(nameFont); + m_packageTable->setItem(i, 0, nameItem); + + m_packageTable->setItem(i, 1, + new QTableWidgetItem(QString::fromStdString(pkg.version))); + + m_packageTable->setItem(i, 2, new QTableWidgetItem( + pkg.repository.empty() ? "—" : QString::fromStdString(pkg.repository))); + + QTableWidgetItem* providerItem = new QTableWidgetItem( + providersLabel(m_pluginManager, pkg)); + providerItem->setForeground(QColor("#98a0b3")); + providerItem->setIcon(loadIcon("package")); + m_packageTable->setItem(i, 3, providerItem); + + QString statusText; + QString statusIcon; + QColor statusColor; + if (pkg.installed && pkg.updateAvailable) { + statusText = "MAJ dispo"; + statusIcon = "arrow-up"; + statusColor = QColor("#e0af68"); + } else if (pkg.installed) { + statusText = "Installé"; + statusIcon = "check"; + statusColor = QColor("#3fb950"); + } else if (!pkg.repository.empty()) { + statusText = "Disponible"; + statusIcon = "package"; + statusColor = QColor("#98a0b3"); + } else { + statusText = "—"; + statusIcon.clear(); + statusColor = QColor("#565f73"); + } + + QTableWidgetItem* statusItem = new QTableWidgetItem(statusText); + statusItem->setForeground(statusColor); + if (!statusIcon.isEmpty()) statusItem->setIcon(loadIcon(statusIcon)); + m_packageTable->setItem(i, 4, statusItem); +} + void MainWindow::onPackageSelected(int row) { if (row < 0 || row >= static_cast(m_currentResults.size())) { resetDetailsPanel(); @@ -1491,6 +1543,7 @@ void MainWindow::onUpdate() { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); connect(worker, &InstallWorker::finished, this, [this, provider](bool success) { setBusy(false); if (success) { @@ -1523,6 +1576,7 @@ void MainWindow::onUpdateAll() { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); connect(worker, &InstallWorker::finished, this, [this, providers](bool success) { setBusy(false); if (success) { @@ -1560,6 +1614,7 @@ void MainWindow::onRefresh() { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); connect(worker, &InstallWorker::finished, this, [this, providers](bool success) { setBusy(false); if (success) { @@ -1594,6 +1649,7 @@ void MainWindow::performInstall(const std::string& package) { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); connect(worker, &InstallWorker::finished, this, [this, provider](bool success) { setBusy(false); if (success) { @@ -1629,6 +1685,7 @@ void MainWindow::performRemove(const std::string& package) { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); connect(worker, &InstallWorker::finished, this, [this, provider](bool success) { setBusy(false); if (success) { @@ -1663,11 +1720,26 @@ void MainWindow::reloadCurrentView() { void MainWindow::setBusy(bool busy) { m_progressBar->setVisible(busy); + m_installProgressBar->setVisible(busy); if (busy) { - m_progressBar->setRange(0, 0); // Indeterminate + // Start indeterminate; a real percentage (onInstallProgress) switches + // the bottom bar to a determinate fill once the tool reports progress. + m_progressBar->setRange(0, 0); + m_progressBar->setValue(0); + m_installProgressBar->setRange(0, 0); + m_installProgressBar->setValue(0); } } +// A real download percentage reported by the provider fills the bottom bar as +// a determinate progress. -1 (unknown) leaves the bar in its previous state. +void MainWindow::onInstallProgress(int percent) { + if (percent < 0) return; + m_installProgressBar->setVisible(true); + m_installProgressBar->setRange(0, 100); + m_installProgressBar->setValue(percent); +} + void MainWindow::refreshHistoryTable() { const auto& all = m_historyManager->getHistory(); @@ -1917,6 +1989,7 @@ void MainWindow::onInstallProviderTool() { connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); + connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); connect(worker, &InstallWorker::finished, this, [this, id](bool success) { setBusy(false); clearCredentialsAfterUse(); diff --git a/src/pacman-manager.cpp b/src/pacman-manager.cpp index f3aa401..6f73386 100644 --- a/src/pacman-manager.cpp +++ b/src/pacman-manager.cpp @@ -31,23 +31,71 @@ static std::string shellQuote(const std::string& s) { 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 returning the combined stdout+stderr. +// 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. static std::string execPrivileged(const std::string& pacmanCmd, - const std::string& password) { + const std::string& password, + ProgressCallback progressCallback) { std::string full = "printf '%s\\n' " + shellQuote(password) + " | sudo -S " + pacmanCmd + " 2>&1"; - return exec(full.c_str()); + + 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; } -// Stream the lines of a command's output to the progress callback, if any. -static void streamOutput(const std::string& output, - std::function progressCallback) { +// 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; + } +} + +// 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); + if (!line.empty()) progressCallback(line, -1); } } @@ -98,11 +146,11 @@ std::vector PacmanManager::search(const std::string& query) { } bool PacmanManager::install(const std::string& packageName, - std::function progressCallback) { - if (progressCallback) progressCallback("Installation de " + packageName + "..."); + ProgressCallback progressCallback) { + if (progressCallback) progressCallback("Installation de " + packageName + "...", -1); - std::string output = execPrivileged("pacman -S --noconfirm " + packageName, m_password); - streamOutput(output, progressCallback); + std::string output = + execPrivileged("pacman -S --noconfirm " + packageName, m_password, progressCallback); // A wrong/expired password must not be silently reused: drop it so the // next attempt prompts again. @@ -115,11 +163,11 @@ bool PacmanManager::install(const std::string& packageName, } bool PacmanManager::remove(const std::string& packageName, - std::function progressCallback) { - if (progressCallback) progressCallback("Suppression de " + packageName + "..."); + ProgressCallback progressCallback) { + if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1); - std::string output = execPrivileged("pacman -R --noconfirm " + packageName, m_password); - streamOutput(output, progressCallback); + std::string output = + execPrivileged("pacman -R --noconfirm " + packageName, m_password, progressCallback); if (authFailed(output)) { clearPassword(); @@ -130,16 +178,16 @@ bool PacmanManager::remove(const std::string& packageName, } bool PacmanManager::update(const std::string& packageName, - std::function progressCallback) { + ProgressCallback progressCallback) { std::string output; if (packageName.empty()) { - if (progressCallback) progressCallback("Mise à jour de tous les paquets..."); - output = execPrivileged("pacman -Syu --noconfirm", m_password); + if (progressCallback) progressCallback("Mise à jour de tous les paquets...", -1); + output = execPrivileged("pacman -Syu --noconfirm", m_password, progressCallback); } else { - if (progressCallback) progressCallback("Mise à jour de " + packageName + "..."); - output = execPrivileged("pacman -S --noconfirm " + packageName, m_password); + if (progressCallback) progressCallback("Mise à jour de " + packageName + "...", -1); + output = execPrivileged("pacman -S --noconfirm " + packageName, + m_password, progressCallback); } - streamOutput(output, progressCallback); if (authFailed(output)) { clearPassword(); @@ -205,11 +253,11 @@ std::vector PacmanManager::listUpdates() { return parseUpdatesOutput(exec("pacman -Qu 2>&1")); } -bool PacmanManager::refresh(std::function progressCallback) { - if (progressCallback) progressCallback("Rafraîchissement des bases de données..."); +bool PacmanManager::refresh(ProgressCallback progressCallback) { + if (progressCallback) progressCallback("Rafraîchissement des bases de données...", -1); - std::string output = execPrivileged("pacman -Sy --noconfirm", m_password); - streamOutput(output, progressCallback); + std::string output = + execPrivileged("pacman -Sy --noconfirm", m_password, progressCallback); if (authFailed(output)) { clearPassword();