5 Commits
Author SHA1 Message Date
BlackAngelTV d44dbc3ccf chore(release): bump the version file to 1.6.0
The journal is a user-facing feature, so the next release warrants a minor
bump rather than a patch.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-27 18:19:03 +02:00
BlackAngelTV f0b37bbb44 feat(ui): show the application journal in the Logs screen
The Logs screen only offered /var/log/pacman.log, which is unreadable
without root and says nothing about what the app itself did. Let the user
switch between that file and the new application journal, refresh it live
while an operation runs, and record navigation and dialog events so the
screen tells the whole story.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-27 18:18:59 +02:00
BlackAngelTV 8670c02eb3 feat(logs): record every operation and event in an application journal
The app kept no durable trace of what it ran: LogManager existed but was
never instantiated, so only a handful of console-only qCInfo calls survived
a session. Wire it up as a process-wide journal that captures each command's
raw output next to UI, search, plugin and update events, and funnel every Qt
log message into it, so a failure can still be diagnosed after the fact.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-27 18:18:55 +02:00
BlackAngelTV 656e365daf Merge pull request 'refactor(logs): optimisation' (#14) from refactor/logs-optimization into main
Reviewed-on: #14
2026-09-24 05:49:25 +00:00
BlackAngelTV a354a0f7fc refactor(logs): optimisation 2026-09-24 07:44:52 +02:00
10 changed files with 530 additions and 29 deletions

No files matched your search

+4 -2
View File
@@ -44,6 +44,7 @@ set(SOURCES
pages/browse-page.cpp
pages/cleanup-page.cpp
pages/history-page.cpp
src/log-manager.cpp
pages/logs-page.cpp
pages/plugins-page.cpp
resources/resources.qrc
@@ -63,6 +64,7 @@ set(HEADERS
include/progress-tracker.h
include/plugin-shop.h
include/app-core.h
include/log-manager.h
pages/page.h
pages/ui-kit.h
pages/dashboard-page.h
@@ -183,9 +185,9 @@ add_executable(app-core-test tests/app-core.test.cpp
src/app-core.cpp src/workers.cpp src/pacman-manager.cpp
src/plugin-manager.cpp src/history-manager.cpp src/update-manager.cpp
src/plugin-shop.cpp
src/app-logging.cpp
src/app-logging.cpp src/log-manager.cpp
include/app-core.h include/workers.h include/update-manager.h
include/plugin-shop.h)
include/plugin-shop.h include/log-manager.h)
target_include_directories(app-core-test PRIVATE include)
target_link_libraries(app-core-test PRIVATE Qt6::Core Qt6::Network)
target_compile_definitions(app-core-test PRIVATE
+3
View File
@@ -121,6 +121,9 @@ public:
// Full content of /var/log/pacman.log; `error` is filled when it cannot be
// read (file missing, no permission).
QString readPackageLog(QString* error = nullptr) const;
// Full content of the application's own journal (every operation and event,
// including the raw output of the commands that ran).
QString readAppLog(QString* error = nullptr) const;
// Extra pacman information for the details panel (-Qi / -Si), cached per
// package so selecting rows repeatedly does not re-spawn pacman.
QString packageDetails(const PackageInfo& package);
+89
View File
@@ -0,0 +1,89 @@
#pragma once
#include <QMutex>
#include <QObject>
#include <QString>
#include <cstdio>
// The application's single, always-on journal: everything the app does ends up
// in one plain-text file that the Logs screen displays and the user can grep
// like a terminal history.
//
// Two kinds of entry share the file:
//
// - a *command* records what a provider is about to run and then every raw
// line it prints, exactly what running the tool by hand would show:
//
// [2026-09-23 14:22:03] ── pacman · install ──────────────────────────
// [2026-09-23 14:22:03] $ install linux-headers
// [2026-09-23 14:22:04] :: Synchronizing package databases...
// [2026-09-23 14:22:05] :: Received timestamp for linux-headers ...
// ...
// [2026-09-23 14:22:10] ⟶ terminé
//
// - an *event* is a one-line note about something that is not a shelled
// command: navigation, a search, a plugin toggle, a network fetch, a refused
// request...
//
// [2026-09-23 14:22:02] [ui] navigation → recherche
// [2026-09-23 14:22:03] [recherche] "firefox" → 12 résultat(s)
//
// Every Qt log message (qCDebug/qCInfo/qCWarning/qCCritical) is funnelled into
// the same journal by installQtMessageHandler(), so the categories already used
// across the code base feed it without extra plumbing.
//
// The file lives in the user's own data tree (XDG_CONFIG_HOME / home) so it is
// never lost when a sandbox is rebuilt. All methods are safe to call from any
// thread.
class LogManager : public QObject {
Q_OBJECT
public:
// Process-wide journal, created on first use (thread-safe).
static LogManager& instance();
explicit LogManager(QObject* parent = nullptr);
// Records a one-line event. `category` is the short tag shown in brackets
// (e.g. "ui", "recherche", "plugin", "erreur").
void logEvent(const QString& category, const QString& message);
// Opens a command block: the provider(s) and action, plus a human-readable
// form of the command about to run (may be empty).
void beginCommand(const QString& provider, const QString& action,
const QString& command = QString());
// Appends one raw output line of the running command.
void appendOutput(const QString& line);
// Closes the current command block with its outcome. `error` carries the
// failure detail when the command failed.
void endCommand(bool success, const QString& error = QString());
// Full, plain text content of the journal (empty when nothing was written
// yet). `error` is filled when the file cannot be read at all.
QString readFile(QString* error = nullptr) const;
// True when the journal file already contains at least one entry.
bool hasEntries() const;
// Path of the journal as written on disk (useful for debugging).
QString filePath() const;
// Routes every Qt log message into the journal. Call once, after the
// QApplication exists. Safe to call more than once.
static void installQtMessageHandler();
signals:
// The journal changed on disk and a fresh copy of its content is available.
void fileUpdated();
private:
// Appends `text` verbatim, opening the file lazily. Caller does not hold the
// lock; this method takes it.
void write(const QString& text);
QString m_filePath;
FILE* m_file = nullptr;
mutable QMutex m_mutex;
};
+30 -1
View File
@@ -1,5 +1,6 @@
#include "logs-page.h"
#include <QComboBox>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
@@ -7,6 +8,7 @@
#include <QTextEdit>
#include <QVBoxLayout>
#include "log-manager.h"
#include "ui-kit.h"
LogsPage::LogsPage(AppCore* core, QWidget* parent) : Page(core, parent) {
@@ -17,6 +19,14 @@ LogsPage::LogsPage(AppCore* core, QWidget* parent) : Page(core, parent) {
QHBoxLayout* filterRow = new QHBoxLayout();
filterRow->setSpacing(10);
m_source = new QComboBox();
m_source->addItem(QStringLiteral("Journal de l'application"));
m_source->addItem(QStringLiteral("Journal pacman (/var/log/pacman.log)"));
m_source->setMinimumHeight(36);
m_source->setToolTip("Choisir la source du journal affiché");
connect(m_source, &QComboBox::currentIndexChanged, this, [this](int) { load(); });
filterRow->addWidget(m_source);
m_filter = new QLineEdit();
m_filter->setPlaceholderText("Filtrer les logs (paquet, action, date)...");
m_filter->setMinimumHeight(36);
@@ -45,6 +55,17 @@ LogsPage::LogsPage(AppCore* core, QWidget* parent) : Page(core, parent) {
buttonBar->addWidget(refreshButton);
layout->addLayout(buttonBar);
// The journal grows while the app runs: reload it whenever a new entry lands,
// but only while this page is actually showing it (so an install does not
// reload the text on a screen the user is not looking at).
connect(&LogManager::instance(), &LogManager::fileUpdated, this, [this] {
if (viewingAppLog() && isVisible()) load();
});
}
bool LogsPage::viewingAppLog() const {
return m_source->currentIndex() == 0;
}
void LogsPage::refresh() {
@@ -53,11 +74,19 @@ void LogsPage::refresh() {
void LogsPage::load() {
QString error;
m_raw = core()->readPackageLog(&error);
m_raw = viewingAppLog() ? LogManager::instance().readFile(&error)
: core()->readPackageLog(&error);
if (!error.isEmpty()) {
m_text->setPlainText(error);
return;
}
if (m_raw.isEmpty()) {
m_text->setPlainText(viewingAppLog()
? QStringLiteral("Journal vide : rien n'a encore été enregistré.")
: QStringLiteral("Journal pacman vide ou illisible."));
return;
}
applyFilter();
}
+11 -5
View File
@@ -4,20 +4,23 @@
#include "page.h"
class QComboBox;
class QLineEdit;
class QTextEdit;
// Logs pacman: the raw /var/log/pacman.log, filtered in memory so typing stays
// instant even with a multi-megabyte file (the core reads it, the page keeps a
// copy).
// Journal viewer. Two sources share the screen: the application's own journal —
// every operation and event, including the raw output of the commands that ran,
// so it reads like a hand-run terminal session — and the raw /var/log/pacman.log.
// Both are filtered in memory so typing stays instant even with a multi-megabyte
// file (the core/journal reads it, the page keeps a copy).
class LogsPage : public Page {
Q_OBJECT
public:
explicit LogsPage(AppCore* core, QWidget* parent = nullptr);
QString navTitle() const override { return QStringLiteral("Logs pacman"); }
QString navTitle() const override { return QStringLiteral("Logs"); }
QString navSubtitle() const override {
return QStringLiteral("Journal brut du gestionnaire de paquets");
return QStringLiteral("Journal de l'application et journal pacman");
}
void refresh() override;
@@ -25,7 +28,10 @@ public:
private:
void load();
void applyFilter();
// True when the selector points at the application's own journal.
bool viewingAppLog() const;
QComboBox* m_source = nullptr;
QLineEdit* m_filter = nullptr;
QTextEdit* m_text = nullptr;
QString m_raw;
+129 -18
View File
@@ -12,6 +12,7 @@
#include <sstream>
#include "app-logging.h"
#include "log-manager.h"
#include "plugin-shop.h"
#include "workers.h"
@@ -67,6 +68,10 @@ AppCore::StartResult accepted() {
AppCore::StartResult refused(const QString& error, bool needsPassword = false,
bool locked = false) {
// Every refusal is part of "what happened": the journal records it even when
// the reason is routine (missing password, locked database, busy core).
LogManager::instance().logEvent(QStringLiteral("refus"), error);
AppCore::StartResult result;
result.error = error;
result.needsPassword = needsPassword;
@@ -74,6 +79,16 @@ AppCore::StartResult refused(const QString& error, bool needsPassword = false,
return result;
}
// "pacman + flatpak", for the journal header of an operation.
QString providerLabel(const std::vector<IPackageManager*>& providers) {
QStringList names;
for (IPackageManager* pm : providers) {
if (pm) names << QString::fromStdString(pm->getName());
}
return names.isEmpty() ? QStringLiteral("aucun")
: names.join(QStringLiteral(" + "));
}
} // namespace
AppCore::AppCore(QObject* parent) : QObject(parent) {
@@ -126,6 +141,13 @@ AppCore::AppCore(QObject* parent) : QObject(parent) {
qCInfo(pacmgrOp) << "core ready,"
<< static_cast<int>(availableProviders().size())
<< "provider(s) available";
LogManager::instance().logEvent(
QStringLiteral("app"),
QStringLiteral("PacManager %1 démarré — %2 gestionnaire(s) : %3")
.arg(version())
.arg(static_cast<int>(availableProviders().size()))
.arg(providerLabel(availableProviders())));
}
AppCore::~AppCore() {
@@ -227,8 +249,14 @@ void AppCore::setCredentialMode(CredentialMode mode) {
if (mode == CredentialMode::EachTime) {
// Each operation must re-authenticate: never keep the password around.
clearSudoPassword();
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("identifiants sudo demandés à chaque opération"));
emit statusMessage(QStringLiteral("Identifiants demandés à chaque opération."));
} else {
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("identifiants sudo demandés une fois par session"));
emit statusMessage(QStringLiteral("Identifiants enregistrés pour la session."));
}
}
@@ -305,17 +333,20 @@ AppCore::StartResult AppCore::startList(ListMode mode) {
return accepted();
}
QString listLabel;
switch (mode) {
case ListMode::Installed:
emit statusMessage(QStringLiteral("Chargement des paquets installés..."));
listLabel = QStringLiteral("Chargement des paquets installés...");
break;
case ListMode::Updates:
emit statusMessage(QStringLiteral("Recherche des mises à jour..."));
listLabel = QStringLiteral("Recherche des mises à jour...");
break;
case ListMode::Cleanup:
emit statusMessage(QStringLiteral("Analyse des paquets inutilisés et legacy..."));
listLabel = QStringLiteral("Analyse des paquets inutilisés et legacy...");
break;
}
LogManager::instance().logEvent(QStringLiteral("liste"), listLabel);
emit statusMessage(listLabel);
auto* worker = new ListWorker(availableProviders(),
mode == ListMode::Installed ? ListWorker::Installed
@@ -327,26 +358,30 @@ AppCore::StartResult AppCore::startList(ListMode mode) {
[this, mode](std::vector<PackageInfo> results) {
m_list = nullptr;
QString done;
if (mode == ListMode::Installed) {
m_installedPackages = results;
emit statusMessage(QStringLiteral("%1 paquet(s) installé(s)")
.arg(results.size()));
done = QStringLiteral("%1 paquet(s) installé(s)")
.arg(results.size());
} else if (mode == ListMode::Updates) {
m_updatePackages = results;
emit statusMessage(QStringLiteral("%1 mise(s) à jour disponible(s)")
.arg(results.size()));
done = QStringLiteral("%1 mise(s) à jour disponible(s)")
.arg(results.size());
} else {
m_cleanupCandidates = results;
int orphans = 0;
for (const auto& pkg : results) {
if (pkg.orphan) ++orphans;
}
emit statusMessage(QStringLiteral("%1 orphelin(s) et %2 paquet(s) legacy "
"détecté(s)")
.arg(orphans)
.arg(static_cast<int>(results.size()) - orphans));
done = QStringLiteral("%1 orphelin(s) et %2 paquet(s) legacy "
"détecté(s)")
.arg(orphans)
.arg(static_cast<int>(results.size()) - orphans);
}
LogManager::instance().logEvent(QStringLiteral("liste"), done);
emit statusMessage(done);
emit listFinished(mode, results);
if (!m_queuedLists.isEmpty()) {
@@ -383,6 +418,9 @@ AppCore::StartResult AppCore::startSearch(const QString& query) {
return refused(QStringLiteral("Aucun gestionnaire de paquets disponible sur ce système."));
}
LogManager::instance().logEvent(
QStringLiteral("recherche"),
QStringLiteral("\"%1\" via %2").arg(query.trimmed(), providerLabel(providers)));
emit statusMessage(QStringLiteral("Recherche en cours..."));
auto* worker = new SearchWorker(providers, query.trimmed().toStdString());
@@ -392,7 +430,10 @@ AppCore::StartResult AppCore::startSearch(const QString& query) {
connect(worker, &SearchWorker::finished, this,
[this](std::vector<PackageInfo> results) {
m_search = nullptr;
emit statusMessage(QStringLiteral("%1 paquet(s) trouvé(s)").arg(results.size()));
const QString done = QStringLiteral("%1 paquet(s) trouvé(s)")
.arg(results.size());
LogManager::instance().logEvent(QStringLiteral("recherche"), done);
emit statusMessage(done);
emit searchFinished(results);
});
disposeWorker(worker);
@@ -471,12 +512,22 @@ AppCore::StartResult AppCore::releaseDatabaseLock() {
setBusy(true);
emit statusMessage(QStringLiteral("Libération de la base de données pacman..."));
LogManager::instance().beginCommand(
QStringLiteral("pacman"), QStringLiteral("release-lock"),
QString::fromStdString(PacmanManager::describeLockHolder(holder)));
auto* worker = new InstallWorker(m_pacman, holder);
connect(worker, &InstallWorker::progress, this,
[this](const QString& message) { emit statusMessage(message); });
[this](const QString& message) {
if (!message.isEmpty()) LogManager::instance().appendOutput(message);
emit statusMessage(message);
});
connect(worker, &InstallWorker::finished, this, [this](bool released) {
setBusy(false);
if (!m_pacman) return;
if (!m_pacman) {
LogManager::instance().endCommand(released);
return;
}
if (!released) {
emit statusMessage(QStringLiteral("Base pacman toujours verrouillée"));
// The core is only asked to free the lock when it is actually held:
@@ -484,11 +535,14 @@ AppCore::StartResult AppCore::releaseDatabaseLock() {
// Reported as a plain failure (not as another lock): the view
// already went through its lock dialog once, offering it again
// would loop.
LogManager::instance().endCommand(
false, QString::fromStdString(m_pacman->lastError()));
emit actionFinished(QStringLiteral("release-lock"), QString(),
false, QString::fromStdString(m_pacman->lastError()),
/*locked=*/false);
return;
}
LogManager::instance().endCommand(true);
emit statusMessage(QStringLiteral("Base libérée, reprise de l'opération..."));
// Deferred so the status message paints before the replayed action
// starts streaming its own progress.
@@ -610,6 +664,9 @@ AppCore::StartResult AppCore::startRequest(const Request& request) {
if (bulk) {
m_removalSuccess = true;
LogManager::instance().beginCommand(
providerLabel(providers), QStringLiteral("cleanup"),
request.description);
startNextRemovalGroup();
return accepted();
}
@@ -657,8 +714,21 @@ AppCore::StartResult AppCore::startAction(InstallWorker* worker, const Request&
qCInfo(pacmgrOp) << request.action << QString::fromStdString(request.package.name);
// Journal header: what is about to run, so the raw output that follows reads
// like a hand-run command.
const QString target = QString::fromStdString(request.package.name);
LogManager::instance().beginCommand(
providerLabel(providers), request.action,
target.isEmpty() ? QString()
: QStringLiteral("%1 %2").arg(request.action, target));
connect(worker, &InstallWorker::progress, this,
[this](const QString& message) { emit actionProgress(message, -1); });
[this](const QString& message) {
// Every non-empty line is the provider's own output: it is exactly
// what running the tool by hand would have printed.
if (!message.isEmpty()) LogManager::instance().appendOutput(message);
emit actionProgress(message, -1);
});
connect(worker, &InstallWorker::progressValue, this,
[this](int percent) { emit actionProgress(QString(), percent); });
connect(worker, &InstallWorker::finished, this,
@@ -723,6 +793,7 @@ void AppCore::finishAction(const Request& request,
emit pluginsChanged();
}
LogManager::instance().endCommand(success, error);
emit actionFinished(action, name, success, error, locked);
}
@@ -795,6 +866,7 @@ void AppCore::clearCredentialsAfterUse() {
void AppCore::startNextRemovalGroup() {
if (m_pendingRemovals.empty()) {
LogManager::instance().endCommand(m_removalSuccess);
m_removalSuccess = true;
setBusy(false);
clearCredentialsAfterUse();
@@ -812,14 +884,20 @@ void AppCore::startNextRemovalGroup() {
IPackageManager* provider = job.first;
const std::vector<std::string> packages = job.second;
emit actionProgress(QStringLiteral("Suppression de %1 paquet(s)...")
.arg(packages.size()), -1);
const QString groupLabel = QStringLiteral("Suppression de %1 paquet(s) via %2...")
.arg(packages.size())
.arg(QString::fromStdString(provider->getName()));
LogManager::instance().appendOutput(groupLabel);
emit actionProgress(groupLabel, -1);
auto* worker = new InstallWorker(provider, InstallWorker::Op::RemovePackages, packages);
m_action = worker;
connect(worker, &InstallWorker::progress, this,
[this](const QString& message) { emit actionProgress(message, -1); });
[this](const QString& message) {
if (!message.isEmpty()) LogManager::instance().appendOutput(message);
emit actionProgress(message, -1);
});
connect(worker, &InstallWorker::progressValue, this,
[this](int percent) { emit actionProgress(QString(), percent); });
connect(worker, &InstallWorker::finished, this,
@@ -856,6 +934,7 @@ void AppCore::startNextRemovalGroup() {
const QString error = QString::fromStdString(provider->lastError());
const bool locked = (m_pacman && m_pacman->lastErrorWasLock())
|| PacmanManager::dbLocked(provider->lastError());
LogManager::instance().endCommand(false, error);
emit statusMessage(QStringLiteral("Échec du nettoyage"));
emit actionFinished(QStringLiteral("cleanup"), m_cleanupRemovalDescription,
false, error, locked);
@@ -893,12 +972,19 @@ void AppCore::cancelPendingRequest() {
// ---------------------------------------------------------------------------
void AppCore::setPluginEnabled(const std::string& pluginId, bool enabled) {
LogManager::instance().logEvent(
QStringLiteral("plugin"),
QStringLiteral("%1 %2")
.arg(QString::fromStdString(pluginId),
enabled ? QStringLiteral("activé") : QStringLiteral("désactivé")));
m_plugins->setEnabled(pluginId, enabled);
refreshProviderCache();
emit pluginsChanged();
}
void AppCore::reloadPlugins() {
LogManager::instance().logEvent(QStringLiteral("plugin"),
QStringLiteral("registre rechargé"));
m_plugins->reload();
refreshProviderCache();
emit pluginsChanged();
@@ -906,20 +992,30 @@ void AppCore::reloadPlugins() {
}
void AppCore::loadPluginCatalog() {
LogManager::instance().logEvent(QStringLiteral("plugin"),
QStringLiteral("chargement du catalogue"));
emit statusMessage(QStringLiteral("Chargement du catalogue de plugins..."));
m_shop->refresh();
}
void AppCore::installShopPlugin(const QString& id) {
LogManager::instance().logEvent(
QStringLiteral("plugin"),
QStringLiteral("installation depuis la boutique : %1").arg(id));
emit statusMessage(QStringLiteral("Téléchargement du plugin %1...").arg(id));
m_shop->install(id);
}
void AppCore::removeShopPlugin(const QString& id) {
LogManager::instance().logEvent(
QStringLiteral("plugin"),
QStringLiteral("suppression depuis la boutique : %1").arg(id));
m_shop->remove(id);
}
void AppCore::clearHistory() {
LogManager::instance().logEvent(QStringLiteral("historique"),
QStringLiteral("effacé"));
m_history->clear();
emit historyChanged();
emit statusMessage(QStringLiteral("Historique effacé"));
@@ -933,6 +1029,7 @@ QString AppCore::readPackageLog(QString* error) const {
"Vérifiez que le fichier existe et que vous avez les "
"droits de lecture.")
.arg(QString::fromUtf8(kPacmanLogPath));
LogManager::instance().logEvent(QStringLiteral("erreur"), *error);
}
return QString();
}
@@ -940,6 +1037,10 @@ QString AppCore::readPackageLog(QString* error) const {
return QString::fromUtf8(logFile.readAll());
}
QString AppCore::readAppLog(QString* error) const {
return LogManager::instance().readFile(error);
}
QString AppCore::packageDetails(const PackageInfo& pkg) {
if (!m_pacman || !m_pacman->isAvailable()) return QString();
@@ -953,6 +1054,12 @@ QString AppCore::packageDetails(const PackageInfo& pkg) {
const auto cached = m_detailsCache.constFind(key);
if (cached != m_detailsCache.constEnd()) return cached.value();
LogManager::instance().logEvent(
QStringLiteral("détails"),
QStringLiteral("interrogation de %1 (%2)")
.arg(QString::fromStdString(pkg.name),
QString::fromStdString(pkg.provider)));
const bool isPacmanPkg = pkg.provider == "pacman" || pkg.provider.empty();
const std::string queryInstalled = pkg.provider == "aur" ? "yay -Qi " : "pacman -Qi ";
const std::string querySync = pkg.provider == "aur" ? "yay -Si " : "pacman -Si ";
@@ -999,6 +1106,8 @@ bool AppCore::shouldCheckForAppUpdate() const {
}
void AppCore::checkForAppUpdate() {
LogManager::instance().logEvent(QStringLiteral("maj-app"),
QStringLiteral("vérification de version"));
emit statusMessage(QStringLiteral("Vérification des mises à jour..."));
m_update->checkForUpdates();
}
@@ -1035,6 +1144,8 @@ bool AppCore::applySelfUpdate(const QString& sudoPassword, QString* error) {
return false;
}
if (error) error->clear();
LogManager::instance().logEvent(QStringLiteral("maj-app"),
QStringLiteral("mise à jour appliquée"));
m_update->performSelfUpdate(sudoPassword);
return true;
}
+188
View File
@@ -0,0 +1,188 @@
#include "log-manager.h"
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QLoggingCategory>
#include <QStandardPaths>
#include <QStringBuilder>
#include <QStringList>
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace {
// Where the plain text history of what the app did lives on any desktop
// session, inside the user's own data tree (so a Flatpak-sandboxed build still
// finds it in ~/.local/share).
QString logDirectory() {
const QString dir = QStandardPaths::writableLocation(
QStandardPaths::AppConfigLocation);
if (!dir.isEmpty()) {
QDir(dir).mkpath(".");
return dir;
}
return QDir::homePath() + QStringLiteral("/.config/PacManager");
}
QString currentTimestamp() {
return QDateTime::currentDateTime().toString(
QStringLiteral("yyyy-MM-dd hh:mm:ss"));
}
} // namespace
LogManager& LogManager::instance() {
// Function-local static: created once, thread-safe since C++11.
static LogManager manager;
return manager;
}
LogManager::LogManager(QObject* parent) : QObject(parent) {
m_filePath = logDirectory() + QStringLiteral("/") + QStringLiteral("operations.log");
}
QString LogManager::filePath() const {
return m_filePath;
}
void LogManager::write(const QString& text) {
QMutexLocker lock(&m_mutex);
// Append mode, opened lazily and kept open: a long session keeps growing and
// the file is never truncated while the app runs.
if (!m_file) {
m_file = std::fopen(QFile::encodeName(m_filePath).constData(), "a");
if (!m_file) return;
}
const QByteArray bytes = text.toUtf8();
std::fputs(bytes.constData(), m_file);
// Flushed line by line so the journal survives a crash: the last thing the
// app did is exactly what the user wants to read after one.
std::fflush(m_file);
}
void LogManager::logEvent(const QString& category, const QString& message) {
if (message.isEmpty()) return;
// A Qt log message may carry several lines; flatten them so every journal
// entry stays one physical line.
QString flat = message;
flat.replace(QLatin1Char('\n'), QStringLiteral(" "));
flat.replace(QLatin1Char('\r'), QString());
write(QStringLiteral("[%1] [%2] %3\n").arg(currentTimestamp(), category, flat));
emit fileUpdated();
}
void LogManager::beginCommand(const QString& provider, const QString& action,
const QString& command) {
const QString stamp = currentTimestamp();
QString text = QStringLiteral("[%1] ── %2 · %3 ")
.arg(stamp, provider, action);
// A rule long enough to separate two operations at a glance.
int rule = 46 - static_cast<int>(action.size()) - static_cast<int>(provider.size());
if (rule < 3) rule = 3;
text += QStringLiteral("─").repeated(rule);
text += QLatin1Char('\n');
if (!command.isEmpty()) {
text += QStringLiteral("[%1] $ %2\n").arg(stamp, command);
}
write(text);
emit fileUpdated();
}
void LogManager::appendOutput(const QString& line) {
if (line.trimmed().isEmpty()) return;
// No timestamp on output lines: this is the tool's own text, replayed as it
// would appear in a terminal, and timestamps on every line would drown it.
write(QStringLiteral(" %1\n").arg(line));
}
void LogManager::endCommand(bool success, const QString& error) {
QString text = QStringLiteral("[%1] %2\n")
.arg(currentTimestamp(),
success ? QStringLiteral("⟶ terminé")
: QStringLiteral("⟶ échec"));
if (!error.isEmpty()) {
const QStringList lines = error.split(QLatin1Char('\n'));
for (const QString& line : lines) {
if (line.trimmed().isEmpty()) continue;
text += QStringLiteral(" %1\n").arg(line);
}
}
write(text);
emit fileUpdated();
}
QString LogManager::readFile(QString* error) const {
QMutexLocker lock(&m_mutex);
if (!QFile::exists(m_filePath)) {
if (error) error->clear();
return QString();
}
QFile file(m_filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
if (error) {
*error = QStringLiteral("Impossible d'ouvrir %1.").arg(m_filePath);
}
return QString();
}
if (error) error->clear();
// Read the file in chunks to avoid loading a very large journal into memory
// at once; the file grows with session usage.
constexpr int bufferSize = 8192;
QByteArray chunk;
chunk.resize(bufferSize);
QString result;
while (!file.atEnd()) {
const qint64 read = file.read(chunk.data(), bufferSize);
if (read > 0) {
result += QString::fromUtf8(chunk, static_cast<int>(read));
}
}
return result;
}
bool LogManager::hasEntries() const {
return !readFile().isEmpty();
}
void LogManager::installQtMessageHandler() {
// Make sure the singleton is created on the calling (main) thread before any
// worker emits a log message.
instance();
qInstallMessageHandler([](QtMsgType type, const QMessageLogContext& context,
const QString& message) {
// Keep the usual console output too, so a developer still sees the logs
// in a terminal.
const char* category = context.category ? context.category : "default";
std::fprintf(stderr, "[%s] %s\n", category, message.toLocal8Bit().constData());
QString level;
switch (type) {
case QtDebugMsg: level = QStringLiteral("debug"); break;
case QtInfoMsg: level = QStringLiteral("info"); break;
case QtWarningMsg: level = QStringLiteral("avertissement"); break;
case QtCriticalMsg: level = QStringLiteral("critique"); break;
case QtFatalMsg: level = QStringLiteral("fatal"); break;
}
LogManager::instance().logEvent(
QStringLiteral("qt/%1").arg(QString::fromLatin1(category)),
QStringLiteral("%1: %2").arg(level, message));
if (type == QtFatalMsg) std::abort();
});
}
+58 -1
View File
@@ -28,6 +28,7 @@
#include <QVBoxLayout>
#include "app-logging.h"
#include "log-manager.h"
#include "browse-page.h"
#include "cleanup-page.h"
#include "dashboard-page.h"
@@ -660,9 +661,13 @@ void MainWindow::setupMenuBar() {
QMenu* fileMenu = menuBar->addMenu("Fichier");
fileMenu->addAction("Exporter la liste affichée...", this, [this] {
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("export de la liste affichée"));
m_browse->exportCsv();
});
fileMenu->addAction("Exporter l'historique...", this, [this] {
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("export de l'historique"));
m_history->exportCsv();
});
fileMenu->addSeparator();
@@ -770,7 +775,11 @@ void MainWindow::setupShortcuts() {
bind(QKeySequence(QStringLiteral("Ctrl+U")), [this]() {
m_navGroup->button(NavUpdates)->click();
});
bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() { m_browse->exportCsv(); });
bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() {
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("export de la liste affichée"));
m_browse->exportCsv();
});
bind(QKeySequence::Quit, [this]() { close(); });
}
@@ -781,6 +790,23 @@ void MainWindow::setupShortcuts() {
void MainWindow::onNavChanged(int id) {
qCDebug(pacmgrUi) << "navigate to page" << id;
QString pageName;
switch (id) {
case NavDashboard: pageName = QStringLiteral("tableau de bord"); break;
case NavSearch: pageName = QStringLiteral("recherche"); break;
case NavInstalled: pageName = QStringLiteral("installés"); break;
case NavUpdates: pageName = QStringLiteral("mises à jour"); break;
case NavCleanup: pageName = QStringLiteral("nettoyage"); break;
case NavHistory: pageName = QStringLiteral("historique"); break;
case NavLogs: pageName = QStringLiteral("logs"); break;
case NavPlugins: pageName = QStringLiteral("plugins"); break;
default: break;
}
LogManager::instance().logEvent(
QStringLiteral("ui"),
pageName.isEmpty() ? QStringLiteral("navigation → page %1").arg(id)
: QStringLiteral("navigation → %1").arg(pageName));
switch (id) {
case NavDashboard:
m_pages->setCurrentWidget(m_dashboard);
@@ -832,6 +858,9 @@ void MainWindow::onOpenPage(const QString& pageId) {
void MainWindow::onOpenPackage(const QString& name) {
if (name.isEmpty()) return;
LogManager::instance().logEvent(
QStringLiteral("ui"),
QStringLiteral("ouverture des détails de %1").arg(name));
m_browse->selectOnNextLoad(name);
if (QAbstractButton* button = m_navGroup->button(NavInstalled)) button->click();
statusBar()->showMessage(QString("Ouverture des détails de %1...").arg(name));
@@ -846,10 +875,14 @@ void MainWindow::onStartRequested(const AppCore::StartResult& result, const QStr
}
void MainWindow::onRefresh() {
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("clic rafraîchir les sources"));
handleStartResult(m_core->refresh(), "Rafraîchissement des sources");
}
void MainWindow::onUpdateAll() {
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("clic tout mettre à jour"));
handleStartResult(m_core->updateAll(), "Mise à jour globale");
}
@@ -868,6 +901,11 @@ void MainWindow::onTrayActivated(QSystemTrayIcon::ActivationReason reason) {
// ---------------------------------------------------------------------------
void MainWindow::applyCredentialMode(AppCore::CredentialMode mode) {
LogManager::instance().logEvent(
QStringLiteral("ui"),
QStringLiteral("mode d'identifiants → %1")
.arg(mode == AppCore::CredentialMode::AtLaunch ? QStringLiteral("au lancement")
: QStringLiteral("à chaque fois")));
m_core->setCredentialMode(mode);
// Per-session credentials: prompt once now so operations don't re-ask. The
// core reports the mode change in the status bar itself.
@@ -879,21 +917,34 @@ void MainWindow::applyCredentialMode(AppCore::CredentialMode mode) {
bool MainWindow::promptForSudoPassword() {
if (m_core->hasSudoPassword()) return true;
LogManager::instance().logEvent(
QStringLiteral("ui"),
QStringLiteral("demande du mot de passe administrateur"));
bool ok = false;
const QString password = QInputDialog::getText(
this, "Authentification",
"Mot de passe administrateur (sudo) :",
QLineEdit::Password, QString(), &ok);
if (!ok) {
LogManager::instance().logEvent(
QStringLiteral("ui"),
QStringLiteral("mot de passe refusé par l'utilisateur"));
statusBar()->showMessage("Opération annulée : identifiants requis.");
return false;
}
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("mot de passe fourni"));
m_core->setSudoPassword(password);
return true;
}
void MainWindow::showActionError(const QString& title, const QString& error, bool locked) {
LogManager::instance().logEvent(
QStringLiteral("erreur"),
QStringLiteral("%1 : %2").arg(title, error.isEmpty() ? QStringLiteral("sans détail") : error));
// A locked database is the one failure the app can resolve on its own, so it
// gets its own dialog instead of a message the user has to act on by hand.
if (locked) {
@@ -930,6 +981,10 @@ void MainWindow::handleStartResult(const AppCore::StartResult& result,
}
void MainWindow::handleDatabaseLock(const QString& title) {
LogManager::instance().logEvent(
QStringLiteral("verrou"),
QStringLiteral("%1 : %2").arg(title, m_core->databaseLockDescription()));
// The other manager frequently finishes while the failed operation was
// unwinding: retry straight away rather than announcing a lock that is gone.
if (!m_core->databaseLocked()) {
@@ -1095,6 +1150,8 @@ void MainWindow::onCoreHistoryChanged() {
}
void MainWindow::onCheckForUpdates() {
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("clic vérifier les mises à jour"));
m_core->checkForAppUpdate();
}
+17 -1
View File
@@ -1,4 +1,7 @@
#include <QApplication>
#include <QLoggingCategory>
#include "log-manager.h"
#include "main-window.h"
#include "update-manager.h"
@@ -8,11 +11,24 @@ int main(int argc, char* argv[]) {
app.setApplicationVersion(UpdateManager::currentVersion());
app.setOrganizationName("Freebuff");
// Every log category the app uses is enabled (qCDebug included) and funnelled
// into the journal, so the Logs screen shows the same detail as a debug run
// without the user having to set QT_LOGGING_RULES.
QLoggingCategory::setFilterRules(QStringLiteral("pacmgr.*=true"));
LogManager::installQtMessageHandler();
LogManager::instance().logEvent(
QStringLiteral("app"),
QStringLiteral("session démarrée (v%1)").arg(UpdateManager::currentVersion()));
MainWindow window;
window.setWindowTitle("PacManager - Gestionnaire de Paquets");
window.resize(1200, 760);
window.setMinimumSize(960, 600);
window.show();
return app.exec();
const int code = app.exec();
LogManager::instance().logEvent(QStringLiteral("app"),
QStringLiteral("session terminée (code %1)").arg(code));
return code;
}
+1 -1
View File
@@ -1 +1 @@
1.4.1
1.6.0