#pragma once #include #include #include #include #include #include #include #include #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. // // 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; // 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 { void operator()(FILE* file) const { if (file) pclose(file); } }; // 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), 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; // 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{stripAnsi(pending), partial}); pending.clear(); }; 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; } // --------------------------------------------------------------------------- // 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. // // 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) { callback(chunk.text, percent); return; } if (percent >= 0) callback(std::string(), percent); if (percent < 0 || percent - milestone < kMilestoneStep) return; milestone = percent; callback("⏳ " + std::to_string(percent) + " %", percent); }); }