Merge branch 'release-1.6.0' into main

The release moved every source into its own layer (core/, app/, pages/,
providers/, preferences/, logging/, archive/, update/, translations/) and
replaced the plugin shop with .fwspacm packages. main added the headless update
check run at login. Both sides are kept, the feature moved onto the new layout:

- core/startup-check.{h,cpp} and its test, wired into the CMake targets the
  release renamed (core/startup-check.cpp, startup-check-test);
- app/main.cpp carries the --check-updates branch, ahead of the command line so
  the login unit never opens a window;
- the settings menu keeps the "check at startup" toggle, now through tr(), and
  translations/en.json gains the new strings;
- doc/mise-a-jour.md keeps the release's version and gains the startup-check
  section; the documented test count follows the new target.
This commit is contained in:
BlackAngelTV committed 2026-10-09 17:56:53 +02:00
commit bea3d61045
104 files changed
+9222 -2036

No files matched your search

+1372
View File
File diff suppressed because it is too large. Load diff
+314
View File
@@ -0,0 +1,314 @@
#pragma once
#include <QHash>
#include <QList>
#include <QObject>
#include <QString>
#include <QStringList>
#include <optional>
#include <utility>
#include <vector>
#include "app-settings.h"
#include "history-manager.h"
#include "package-manager.h"
#include "pacman-manager.h"
#include "plugin-manager.h"
#include "update-manager.h"
class QThread;
class SearchWorker;
class ListWorker;
class InstallWorker;
class PluginPackage;
// Logic layer: everything the application *does*. It owns the providers
// (pacman, Flatpak, AUR, ...), the plugin registry, the history, the privileged
// commands, pacman's database lock and the self-updater — and knows nothing
// about widgets, dialogs or layouts.
//
// MainWindow is only a view on top of it: it builds widgets, calls these
// methods and renders the signals below. Two rules keep the split honest:
// - every operation that shells out is asynchronous and reports through
// signals; the *StartResult answers only say whether the request was
// accepted;
// - whatever needs a human (the sudo password, freeing pacman's lock) is
// decided by the view: the core says what it lacks and the view calls back
// once the user answered.
// The layer therefore runs without a display — tests/app-core.test.cpp links no
// QtWidgets at all.
class AppCore : public QObject {
Q_OBJECT
public:
// Which listing is being loaded.
enum class ListMode { Installed, Updates, Cleanup };
// When the sudo password is requested: once per session (at launch) or
// before every privileged operation.
enum class CredentialMode { AtLaunch, EachTime };
// Outcome of a request. A refused request carries the reason and flags what
// the view has to do before replaying it: ask for the sudo password, or
// free pacman's database lock.
struct StartResult {
bool started = false;
bool needsPassword = false;
bool locked = false;
QString error;
};
explicit AppCore(QObject* parent = nullptr);
~AppCore() override;
// ---- Backend handles the view renders ----
PluginManager* plugins() const { return m_plugins; }
HistoryManager* history() const { return m_history; }
UpdateManager* updateManager() const { return m_update; }
PluginPackage* packages() const { return m_packages; }
// User preferences (journal, drag & drop, language, update policy). The
// core reads them to decide whether a version check may run; the Settings
// screen writes them. Shared process-wide, hence the accessor rather than
// an owned member.
AppSettings* settings() const { return &AppSettings::instance(); }
std::vector<IPackageManager*> availableProviders() const;
QStringList availableProviderNames() const;
bool hasAvailableProvider() const;
// Provider owning a package id, falling back to the first available one.
IPackageManager* providerFor(const QString& providerId) const;
QString version() const;
int historyCount() const;
bool busy() const { return m_busy; }
// Last completed listings; -1 when a list was never loaded.
const std::vector<PackageInfo>& installedPackages() const { return m_installedPackages; }
const std::vector<PackageInfo>& updatePackages() const { return m_updatePackages; }
const std::vector<PackageInfo>& cleanupCandidates() const { return m_cleanupCandidates; }
int installedCount() const;
int updateCount() const;
// ---- Listings ----
StartResult search(const QString& query);
StartResult loadInstalled();
StartResult loadUpdates();
StartResult loadCleanup();
// Dashboard: loads the installed and update lists back to back, so the
// counts and the badges are fresh without the view doing any chaining.
StartResult loadCounts();
// ---- Actions ----
StartResult install(const PackageInfo& package);
StartResult remove(const PackageInfo& package);
// Removes only the installations the user picked, when the provider can
// have several copies of the same application (flatpak: one in the user
// installation and one system-wide, or two remotes or branches). The targets
// are the ones the provider listed in PackageInfo::instances, so the core
// never builds them; an empty list is the plain remove().
StartResult removeInstances(const PackageInfo& package,
const std::vector<std::string>& targets);
StartResult update(const PackageInfo& package);
StartResult updateAll();
StartResult refresh();
StartResult cleanCaches();
// Installs the package a file describes — a Flatpak .flatpakref, .flatpakrepo
// or .flatpak bundle dropped on the window or opened from the file manager
// ("Ouvrir avec PacManager"). The provider owning the format is picked here,
// so the view never names one.
StartResult installFile(const QString& path);
// Whether any available provider knows that file, so the window only accepts
// drops it can act on.
bool canInstallFile(const QString& path) const;
// Whether a file is a plugin package (.fwspacm). Packages are not installed
// by a provider: they carry a plugin, they are not packages to install, so
// they never take the sudo gate and never enter the file install queue.
bool isPluginPackage(const QString& path) const;
// Bulk removal: one command per provider, run one provider at a time
// (pacman locks its database for the whole operation).
StartResult removePackages(const std::vector<PackageInfo>& packages,
const QString& description);
StartResult installPluginTool(const std::string& pluginId);
StartResult releaseDatabaseLock();
// Replays the request that was waiting for a password or for the database
// lock to be freed, so the view can retry right after the user answered.
StartResult retryPendingRequest();
void cancelPendingRequest();
bool hasPendingRequest() const { return m_pending.has_value(); }
// ---- Credentials (the view prompts, the core holds the state) ----
CredentialMode credentialMode() const { return m_credentialMode; }
void setCredentialMode(CredentialMode mode);
void setSudoPassword(const QString& password);
void clearSudoPassword();
bool hasSudoPassword() const;
// ---- History, logs, package details ----
void clearHistory();
// 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);
// ---- Plugins ----
void setPluginEnabled(const std::string& pluginId, bool enabled);
void reloadPlugins();
// ---- Plugin packages ----
// Installs a .fwspacm package (the archive the packaging script builds) and
// removes one that was installed this way. Installing writes the shared
// library in the per-user plugin directory and reloads the registry, so the
// plugin is usable right away.
void installPluginPackage(const QString& path);
void removePluginPackage(const QString& id);
// ---- Application self-update ----
// Whether a version check may run right now: the daily check is not asked
// for, the automatic check is off, or the user put the app's own updates on
// hold (see AppSettings).
bool shouldCheckForAppUpdate() const;
void checkForAppUpdate();
// Why checkForAppUpdate() would refuse, for the status bar and the Settings
// screen. Empty when a check may run.
QString appUpdateCheckRefusal() const;
bool canSelfUpdate() const;
UpdateManager::UpdateMethod updateMethod() const;
QString updateMethodDescription() const;
QString releasePageUrl() const;
QString binDir() const;
bool binDirWritable() const;
// Starts the background rebuild/install. Returns false with `error` filled
// when the update cannot run (no method available).
bool applySelfUpdate(const QString& sudoPassword, QString* error);
// ---- Startup update check ----
// Whether the app installs its login check: a systemd user unit that runs
// `PacManager --check-updates` and pops a notification when updates are
// pending — no window, no sudo password. On by default, since the point is
// to warn the user without them opening the app.
bool checkUpdatesAtStartup() const;
void setCheckUpdatesAtStartup(bool enabled);
// Refreshes the installed unit when the setting is on, in case the binary
// moved since it was written. Idempotent; called once at window startup so
// an update of the app keeps the login check pointing at the real file.
void ensureStartupAutostart();
// ---- pacman's database lock ----
bool databaseLocked() const;
// What currently holds the lock, so the view can name the process it offers
// to close (or the stale lock file it offers to drop).
PacmanManager::LockHolder lockHolder() const;
QString databaseLockDescription() const;
signals:
// Search results, streamed in batches then once complete.
void searchChunk(std::vector<PackageInfo> results);
void searchFinished(std::vector<PackageInfo> results);
// A listing finished; the view renders it and keeps what it needs.
void listFinished(AppCore::ListMode mode, std::vector<PackageInfo> results);
// Progress of a running action: `message` is a log line, `percent` is -1
// when the tool does not report a real percentage.
void actionProgress(const QString& message, int percent);
void actionFinished(const QString& action, const QString& name, bool success,
const QString& error, bool locked);
void busyChanged(bool busy);
void statusMessage(const QString& message);
void historyChanged();
void pluginsChanged();
// A plugin package was installed or removed (or the attempt was refused).
void pluginPackageInstalled(const QString& id, bool success, const QString& message);
void pluginPackageRemoved(const QString& id, bool success, const QString& message);
void updateCheckFinished(bool hasUpdate, const QString& latestVersion,
const QString& errorMessage);
void selfUpdateFinished(bool success, const QString& message);
private:
// Everything the core knows how to run. The pending request is kept so it
// can be replayed once the password is provided or the lock released.
struct Request {
QString action;
PackageInfo package;
std::vector<PackageInfo> packages;
QString description;
// File a file-based request acts on (see installFile), kept apart from
// `package.name`, which only carries the label for the UI and history.
QString path;
// The exact installation a request acts on, when the provider named one
// (see removeInstances). Like `path`, it is what the provider is given
// instead of the display label, which the UI and the history keep.
QString target;
// Several installations of the same application, acted on in one
// operation (see removeInstances).
std::vector<std::string> targets;
std::string pluginId;
};
// Taken by value: the label and the pending copy are filled in from the
// request's contents once the target action is known.
StartResult startRequest(Request request);
StartResult startList(ListMode mode);
StartResult startSearch(const QString& query);
StartResult startAction(InstallWorker* worker, const Request& request,
const std::vector<IPackageManager*>& providers);
void finishAction(const Request& request,
const std::vector<IPackageManager*>& providers, bool success);
// Deletes a worker once its thread has really stopped. wait() has to run on
// the core's thread (a worker cannot wait on itself), so the cleanup is
// connected with the core as context and therefore queued back here.
void disposeWorker(QThread* worker);
// Chains the provider groups of a bulk removal, one after the other.
void startNextRemovalGroup();
void setBusy(bool busy);
// Everything the status bar and the dialogs get to read: the core decides
// what happened, the view decides how to show it.
QString startMessage(const QString& action, const QString& label) const;
QString successMessage(const QString& action, const QString& name) const;
QString failureMessage(const QString& action, const QString& name) const;
QString firstError(const std::vector<IPackageManager*>& providers) const;
void recordHistory(const QString& action, const QString& name,
IPackageManager* provider, bool success);
void invalidateDetails();
void refreshProviderCache();
// Refusal shared by every privileged request: the view is told which of the
// three doors is closed (busy, password, unavailable provider).
StartResult credentialGate(const std::vector<IPackageManager*>& providers) const;
// Per-operation mode: the password is single-use, drop it after a command.
void clearCredentialsAfterUse();
PluginManager* m_plugins = nullptr;
PluginPackage* m_packages = nullptr;
PacmanManager* m_pacman = nullptr; // non-owning, for sudo credentials and the lock
HistoryManager* m_history = nullptr;
UpdateManager* m_update = nullptr;
QSettings m_settings;
CredentialMode m_credentialMode = CredentialMode::EachTime;
std::vector<PackageInfo> m_installedPackages;
std::vector<PackageInfo> m_updatePackages;
std::vector<PackageInfo> m_cleanupCandidates;
QHash<QString, QString> m_detailsCache;
// One worker of each kind at a time; a second listing request is queued
// rather than refused, since the dashboard loads two in a row.
SearchWorker* m_search = nullptr;
ListWorker* m_list = nullptr;
QList<ListMode> m_queuedLists;
InstallWorker* m_action = nullptr;
std::optional<Request> m_pending;
// Bulk removal state.
std::vector<std::pair<IPackageManager*, std::vector<std::string>>> m_pendingRemovals;
bool m_removalSuccess = true;
QString m_cleanupRemovalDescription;
bool m_busy = false;
};
Q_DECLARE_METATYPE(AppCore::ListMode)
+58
View File
@@ -0,0 +1,58 @@
#include "package-model.h"
PackageModel::PackageModel(QObject* parent) : QAbstractListModel(parent) {}
int PackageModel::rowCount(const QModelIndex& parent) const {
Q_UNUSED(parent);
return static_cast<int>(m_packages.size());
}
QVariant PackageModel::data(const QModelIndex& index, int role) const {
if (!index.isValid() || index.row() >= static_cast<int>(m_packages.size())) {
return QVariant();
}
const PackageInfo& pkg = m_packages[index.row()];
switch (role) {
case NameRole: return QString::fromStdString(pkg.name);
case VersionRole: return QString::fromStdString(pkg.version);
case DescriptionRole: return QString::fromStdString(pkg.description);
case RepositoryRole: return QString::fromStdString(pkg.repository);
case InstalledRole: return pkg.installed;
case SizeRole: return QString::fromStdString(pkg.size);
case UpdateAvailableRole: return pkg.updateAvailable;
default: return QVariant();
}
}
QHash<int, QByteArray> PackageModel::roleNames() const {
return {
{NameRole, "name"},
{VersionRole, "version"},
{DescriptionRole, "description"},
{RepositoryRole, "repository"},
{InstalledRole, "installed"},
{SizeRole, "size"},
{UpdateAvailableRole, "updateAvailable"}
};
}
void PackageModel::setPackages(const std::vector<PackageInfo>& packages) {
beginResetModel();
m_packages = packages;
endResetModel();
}
void PackageModel::clear() {
beginResetModel();
m_packages.clear();
endResetModel();
}
PackageInfo PackageModel::getPackage(int row) const {
if (row >= 0 && row < static_cast<int>(m_packages.size())) {
return m_packages[row];
}
return PackageInfo{};
}
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <QObject>
#include <QAbstractListModel>
#include <QVariant>
#include <vector>
#include "package-manager.h"
class PackageModel : public QAbstractListModel {
Q_OBJECT
public:
enum Roles {
NameRole = Qt::UserRole + 1,
VersionRole,
DescriptionRole,
RepositoryRole,
InstalledRole,
SizeRole,
UpdateAvailableRole
};
explicit PackageModel(QObject* parent = nullptr);
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
QHash<int, QByteArray> roleNames() const override;
void setPackages(const std::vector<PackageInfo>& packages);
void clear();
PackageInfo getPackage(int row) const;
private:
std::vector<PackageInfo> m_packages;
};
+347
View File
@@ -0,0 +1,347 @@
#include "startup-check.h"
#include "log-manager.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <QStandardPaths>
#include <QThread>
#include <QtGlobal>
#include <initializer_list>
namespace {
// Package prefixes that make an update worth interrupting the user for. Kept
// short and documented: widening it is a judgement call, not a bug fix.
bool startsWithAny(const QString& name, std::initializer_list<const char*> prefixes) {
for (const char* prefix : prefixes) {
if (name.startsWith(QLatin1String(prefix))) return true;
}
return false;
}
bool toolExists(const QString& program) {
return !QStandardPaths::findExecutable(program).isEmpty();
}
} // namespace
StartupCheck::StartupCheck(QObject* parent) : QObject(parent) {}
// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------
QStringList StartupCheck::parseUpdates(const QString& output) {
QStringList packages;
const QStringList lines = output.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
for (const QString& line : lines) {
// "linux 6.9.1.arch1-1 -> 6.9.2.arch1-1" (checkupdates) and
// "linux 6.9.2.arch1-1" (pacman -Qu) share the same head: the first
// whitespace-separated token is the package name.
const QStringList tokens = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
if (tokens.isEmpty()) continue;
packages << tokens.first();
}
packages.removeDuplicates();
return packages;
}
bool StartupCheck::isCritical(const QString& package) {
return startsWithAny(package, {
"linux", // the kernel itself, its headers and its firmware
"glibc", // everything links against it
"systemd", // init and its libraries
"mesa", // graphics stack: a broken update loses the session
"nvidia", // out-of-tree driver built against the running kernel
"xorg-server",
"wayland",
"pacman", // a broken pacman leaves no way to repair
"openssl",
});
}
bool StartupCheck::isRebootRequired(const QString& package) {
// Only the kernel (and its firmware, which "linux" also covers) plus the
// out-of-tree graphics driver built against the running kernel leave the
// system on the old code until it restarts.
return startsWithAny(package, {"linux", "nvidia"});
}
QStringList StartupCheck::criticalPackages(const QStringList& packages) {
QStringList critical;
for (const QString& package : packages) {
if (isCritical(package)) critical << package;
}
return critical;
}
QString StartupCheck::notificationTitle(const Result& result) {
if (result.rebootRequired) return QStringLiteral("Mise à jour du noyau disponible");
if (result.anyCritical) return QStringLiteral("Mises à jour importantes disponibles");
return QStringLiteral("Mises à jour disponibles");
}
QString StartupCheck::notificationBody(const Result& result) {
const int count = result.updateCount;
QString body = count == 1 ? QStringLiteral("1 mise à jour disponible.")
: QStringLiteral("%1 mises à jour disponibles.").arg(count);
// Name the critical packages, but keep the bubble readable: a system with a
// pending toolchain refresh can have a dozen of them.
const QStringList critical = criticalPackages(result.packages);
if (!critical.isEmpty()) {
const int shown = qMin(critical.size(), 5);
QStringList listed = critical.mid(0, shown);
if (critical.size() > shown) listed << QStringLiteral("…");
body += QStringLiteral("\nPaquets sensibles : %1.").arg(listed.join(QStringLiteral(", ")));
}
body += result.rebootRequired
? QStringLiteral("\nUn redémarrage sera nécessaire après l'installation.")
: QStringLiteral("\nOuvrez PacManager pour les installer.");
return body;
}
// ---------------------------------------------------------------------------
// Check
// ---------------------------------------------------------------------------
QString StartupCheck::runTool(const QString& program, const QStringList& args,
int timeoutMs, int* exitCode, QString* stderrText) {
if (exitCode) *exitCode = -1;
if (stderrText) stderrText->clear();
QProcess process;
// Separate channels: stdout is the package list, stderr is diagnostics. A
// merged stream would turn "warning: database file..." into a package name.
process.setProcessChannelMode(QProcess::SeparateChannels);
process.start(program, args);
if (!process.waitForStarted(5000)) return {};
const bool finished = process.waitForFinished(timeoutMs);
if (!finished) {
process.kill();
process.waitForFinished(2000);
}
const QString out = QString::fromUtf8(process.readAllStandardOutput());
if (stderrText) *stderrText = QString::fromUtf8(process.readAllStandardError()).trimmed();
if (exitCode) *exitCode = finished ? process.exitCode() : -1;
return out;
}
StartupCheck::Result StartupCheck::check() {
Result result;
QString output;
QString stderrText;
int code = 0;
if (toolExists(QStringLiteral("checkupdates"))) {
// checkupdates refreshes a throwaway copy of the databases, so it needs
// no root and cannot leave the real database half-synced. It exits 0
// with updates, 2 when there is nothing to do, and anything else on a
// real failure (no network, broken database...).
output = runTool(QStringLiteral("checkupdates"), {}, 120000, &code, &stderrText);
if (code != 0 && code != 2) {
result.error = stderrText.isEmpty()
? QStringLiteral("checkupdates a échoué (code %1).").arg(code)
: QStringLiteral("checkupdates a échoué (code %1) : %2")
.arg(code).arg(stderrText);
return result;
}
} else if (toolExists(QStringLiteral("pacman"))) {
// Fallback: read the already-synced database. It needs no root either,
// but it only knows what the last `pacman -Sy` saw, so it can miss
// updates — which `error` records rather than hiding.
output = runTool(QStringLiteral("pacman"), {QStringLiteral("-Qu")}, 30000, &code,
&stderrText);
// pacman -Qu exits 1 when nothing matches (= no update at all).
if (code != 0 && code != 1) {
result.error = stderrText.isEmpty()
? QStringLiteral("pacman -Qu a échoué (code %1).").arg(code)
: QStringLiteral("pacman -Qu a échoué (code %1) : %2").arg(code).arg(stderrText);
return result;
}
result.error = QStringLiteral(
"checkupdates est absent (paquet pacman-contrib) : les mises à jour "
"peuvent être manquées tant que la base n'est pas synchronisée.");
} else {
result.error = QStringLiteral("Ni checkupdates ni pacman n'est disponible.");
return result;
}
result.packages = parseUpdates(output);
result.updateCount = result.packages.size();
for (const QString& package : result.packages) {
result.anyCritical = result.anyCritical || isCritical(package);
result.rebootRequired = result.rebootRequired || isRebootRequired(package);
}
return result;
}
int StartupCheck::run() {
const Result result = check();
if (!result.error.isEmpty()) {
LogManager::instance().logEvent(QStringLiteral("maj-verif"), result.error);
}
LogManager::instance().logEvent(
QStringLiteral("maj-verif"),
result.updateCount == 0
? QStringLiteral("aucune mise à jour en attente")
: QStringLiteral("%1 mise(s) à jour en attente : %2")
.arg(result.updateCount)
.arg(result.packages.join(QStringLiteral(", "))));
if (result.updateCount > 0) {
notify(result);
}
return 0;
}
// ---------------------------------------------------------------------------
// Notification
// ---------------------------------------------------------------------------
bool StartupCheck::sendNotification(const QString& title, const QString& body, bool urgent) {
if (!toolExists(QStringLiteral("notify-send"))) return false;
QStringList args{QStringLiteral("-a"), QStringLiteral("PacManager")};
if (urgent) {
// A critical notification that never times out: the user should not be
// able to miss a pending kernel update.
args << QStringLiteral("-u") << QStringLiteral("critical")
<< QStringLiteral("-t") << QStringLiteral("0");
} else {
args << QStringLiteral("-t") << QStringLiteral("10000");
}
args << title << body;
// A login unit can beat the notification daemon (mako, dunst...) to the
// session bus, in which case the first sends fail. Retry for a few seconds
// instead of dropping the notification silently.
for (int attempt = 0; attempt < 30; ++attempt) {
QProcess process;
process.start(QStringLiteral("notify-send"), args);
if (process.waitForStarted(3000) && process.waitForFinished(5000) &&
process.exitCode() == 0) {
return true;
}
QThread::msleep(1000);
}
return false;
}
bool StartupCheck::notify(const Result& result) {
if (result.updateCount <= 0) return false;
const bool urgent = result.rebootRequired || result.anyCritical;
const bool sent = sendNotification(notificationTitle(result),
notificationBody(result), urgent);
LogManager::instance().logEvent(
QStringLiteral("maj-verif"),
sent ? QStringLiteral("notification envoyée")
: QStringLiteral("notification impossible (aucun démon de notification)"));
return sent;
}
// ---------------------------------------------------------------------------
// Autostart
// ---------------------------------------------------------------------------
QString StartupCheck::autostartUnitPath(const QString& configDir) {
if (configDir.isEmpty()) return {};
return configDir + QStringLiteral("/systemd/user/pacmanager-check-updates.service");
}
QString StartupCheck::autostartWantsPath(const QString& configDir) {
if (configDir.isEmpty()) return {};
return configDir +
QStringLiteral("/systemd/user/default.target.wants/pacmanager-check-updates.service");
}
bool StartupCheck::installAutostart(const QString& configDir, const QString& program,
QString* error) {
if (configDir.isEmpty() || program.isEmpty()) {
if (error) *error = QStringLiteral("répertoire de configuration ou programme manquant.");
return false;
}
const QString unitPath = autostartUnitPath(configDir);
const QString wantsPath = autostartWantsPath(configDir);
if (!QDir().mkpath(QFileInfo(unitPath).absolutePath()) ||
!QDir().mkpath(QFileInfo(wantsPath).absolutePath())) {
if (error) *error = QStringLiteral("impossible de créer %1").arg(configDir);
return false;
}
// Quoted because a path may contain spaces; systemd accepts the quotes.
const QString unit = QStringLiteral(
"[Unit]\n"
"Description=PacManager — mises à jour disponibles au démarrage\n"
"Documentation=man:PacManager(1)\n"
"After=network-online.target\n"
"Wants=network-online.target\n"
"\n"
"[Service]\n"
"Type=oneshot\n"
"ExecStart=\"%1\" --check-updates\n"
"\n"
"[Install]\n"
"WantedBy=default.target\n").arg(program);
QFile file(unitPath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate) ||
file.write(unit.toUtf8()) != unit.toUtf8().size()) {
if (error) *error = QStringLiteral("impossible d'écrire %1").arg(unitPath);
return false;
}
file.close();
// The symlink is what `systemctl --user enable` would create; writing it
// directly keeps the install free of any systemd call.
QFile::remove(wantsPath);
if (!QFile::link(unitPath, wantsPath)) {
if (error) *error = QStringLiteral("impossible de créer le lien %1").arg(wantsPath);
return false;
}
return true;
}
bool StartupCheck::removeAutostart(const QString& configDir, QString* error) {
if (configDir.isEmpty()) {
if (error) *error = QStringLiteral("répertoire de configuration manquant.");
return false;
}
QFile::remove(autostartWantsPath(configDir));
QFile::remove(autostartUnitPath(configDir));
return true;
}
bool StartupCheck::autostartEnabled(const QString& configDir) {
const QString wantsPath = autostartWantsPath(configDir);
if (wantsPath.isEmpty()) return false;
const QFileInfo info(wantsPath);
// A symlink whose target is missing would report exists() == false, so the
// link itself is checked too: a stale link is still an installed setting.
return info.isSymLink() || info.exists();
}
bool StartupCheck::reloadUserManager() {
if (!toolExists(QStringLiteral("systemctl"))) return false;
QProcess process;
process.start(QStringLiteral("systemctl"),
{QStringLiteral("--user"), QStringLiteral("daemon-reload")});
if (!process.waitForStarted(3000)) return false;
return process.waitForFinished(10000) && process.exitCode() == 0;
}
+118
View File
@@ -0,0 +1,118 @@
#pragma once
#include <QObject>
#include <QString>
#include <QStringList>
// The headless pass that answers "does this machine have pending updates?" and,
// when it does, raises a desktop notification.
//
// It exists because the graphical window is not running when the machine
// starts: the app installs a systemd user unit (see the autostart helpers here)
// that runs `PacManager --check-updates` at login, and that call lands here.
//
// Two guarantees drive the implementation:
// - no password: the check goes through `checkupdates` (pacman-contrib), which
// syncs into a throwaway database and therefore needs no root, instead of a
// `pacman -Sy` the login unit could never authenticate;
// - no display: everything here is Qt Core only, so the unit runs with no
// DISPLAY, no Wayland socket and no widget.
//
// The pure parts (parsing, classification, notification text, unit contents)
// are static so they are unit-tested without a package manager, a network or a
// session bus.
class StartupCheck : public QObject {
Q_OBJECT
public:
// Outcome of one check, so the caller (and the tests) can inspect what
// happened without parsing console output.
struct Result {
int updateCount = 0;
bool anyCritical = false; // kernel, glibc, init, graphics stack...
bool rebootRequired = false; // a kernel or its firmware is pending
QStringList packages;
// Non-empty when the check failed, or when it could only run in a
// degraded way (the pacman -Qu fallback, which reads a database only
// root can refresh). Never a reason to skip the notification.
QString error;
};
explicit StartupCheck(QObject* parent = nullptr);
// Runs the whole headless pass (check, then notify when something is
// pending) and returns the exit code for main(). Always 0: a background
// check that fails must not fill the user's journal with failed units.
int run();
// ---- Pure helpers (unit-tested) ----
// Parses the checked tool's output. `checkupdates` prints
// "name oldver -> newver" and `pacman -Qu` prints "name newver"; only the
// package name is needed and it is the first whitespace-separated token of
// every line, so one parser accepts both. Duplicates are dropped.
static QStringList parseUpdates(const QString& output);
// A package whose update deserves an urgent notification rather than the
// ordinary one: the kernel and its firmware, the C library and init, the
// graphics stack, pacman itself — the updates that either need a reboot or
// can break the session when they fall behind. Prefix-based on purpose: a
// package nobody thought about simply gets the normal notification.
static bool isCritical(const QString& package);
// A package whose update only takes effect after a reboot: the kernel and
// the out-of-tree driver built against the running one.
static bool isRebootRequired(const QString& package);
// The critical subset of a list, so the notification can name what matters.
static QStringList criticalPackages(const QStringList& packages);
// Notification title and body for a set of pending updates.
static QString notificationTitle(const Result& result);
static QString notificationBody(const Result& result);
// ---- Check and notify (touch the machine) ----
// Pending updates, using `checkupdates` when available and falling back to
// the already-synced `pacman -Qu` otherwise. Never needs root; the fallback
// reads a database only root can refresh, so it may miss updates — which is
// what `error` records rather than hiding.
static Result check();
// Sends the notification through notify-send, waiting briefly for the
// notification daemon (the login unit can start before mako). Returns false
// when nothing could be sent.
static bool notify(const Result& result);
// ---- Autostart: a systemd user unit the app installs itself ----
// The unit lives under `configDir` (XDG_CONFIG_HOME, i.e. ~/.config) and is
// enabled by a symlink in default.target.wants, which is the per-user
// equivalent of `systemctl --user enable` without shelling out to it.
// Passing the directory lets the unit test drive install/remove inside a
// temporary tree instead of the user's own ~/.config.
static QString autostartUnitPath(const QString& configDir);
static QString autostartWantsPath(const QString& configDir);
// Writes the unit and the enabling symlink. `program` is the binary to run
// with --check-updates (the running executable, so it follows the install
// wherever it is). Filesystem only: no systemd call, so tests stay hermetic.
static bool installAutostart(const QString& configDir, const QString& program,
QString* error = nullptr);
static bool removeAutostart(const QString& configDir, QString* error = nullptr);
static bool autostartEnabled(const QString& configDir);
// Asks the user's systemd manager to re-read its units, so a fresh install
// takes effect without waiting for the next boot. Best effort; a system
// without a running user manager (a test, a container) is not an error.
static bool reloadUserManager();
private:
// Runs a tool to completion, returning its stdout. stderr is kept out of it
// on purpose: a pacman warning is not a package name, so folding the two
// would feed the parser lines it must not see — `stderrText` receives them
// for the error message instead. `exitCode` receives the status, or -1 when
// the process could not be started or timed out.
static QString runTool(const QString& program, const QStringList& args,
int timeoutMs, int* exitCode, QString* stderrText = nullptr);
// Waits (bounded) for the session's notification daemon, then sends through
// notify-send with the given urgency.
static bool sendNotification(const QString& title, const QString& body, bool urgent);
};
+140
View File
@@ -0,0 +1,140 @@
#include "workers.h"
#include <algorithm>
SearchWorker::SearchWorker(const std::vector<IPackageManager*>& providers,
const std::string& query)
: m_providers(providers), m_query(query) {}
void SearchWorker::run() {
std::vector<PackageInfo> 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<PackageInfo> providerResults;
for (auto& pkg : pm->search(m_query)) {
pkg.provider = pm->getName();
providerResults.push_back(pkg);
}
constexpr int kBatchSize = 10;
for (size_t i = 0; i < providerResults.size(); i += kBatchSize) {
std::vector<PackageInfo> 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);
// Group by provider (query order), then sort alphabetically within each.
std::vector<std::string> providerOrder;
for (IPackageManager* pm : m_providers) providerOrder.push_back(pm->getName());
sortByProviderThenName(results, providerOrder);
emit finished(results);
}
ListWorker::ListWorker(const std::vector<IPackageManager*>& providers, Mode mode)
: m_providers(providers), m_mode(mode) {}
void ListWorker::run() {
std::vector<PackageInfo> results;
for (IPackageManager* pm : m_providers) {
if (m_mode == Installed) {
if (!pm->canListInstalled()) continue;
for (auto& pkg : pm->listInstalled()) {
pkg.provider = pm->getName();
results.push_back(pkg);
}
} else if (m_mode == Updates) {
if (!pm->canUpdate()) continue;
for (auto& pkg : pm->listUpdates()) {
pkg.provider = pm->getName();
results.push_back(pkg);
}
} else {
if (!pm->canListCleanup()) continue;
for (auto& pkg : pm->listCleanupCandidates()) {
pkg.provider = pm->getName();
results.push_back(pkg);
}
}
}
// One row per package name, whatever the number of providers offering it.
// Cleanup candidates stay as reported: each row is tied to the provider
// that must remove it, and merging would hide which one reported it.
if (m_mode != Cleanup) mergeProviderDuplicates(results);
emit finished(results);
}
InstallWorker::InstallWorker(IPackageManager* pm, Op op, const std::string& package)
: m_providers{pm}, m_op(op), m_package(package) {}
InstallWorker::InstallWorker(IPackageManager* pm, Op op,
const std::vector<std::string>& packages)
: m_providers{pm}, m_op(op), m_packages(packages) {}
InstallWorker::InstallWorker(const std::vector<IPackageManager*>& providers, Op op)
: m_providers(providers), m_op(op) {}
InstallWorker::InstallWorker(PacmanManager* pacman, const PacmanManager::LockHolder& holder)
: m_op(Op::ReleaseLock), m_pacman(pacman), m_lockHolder(holder) {}
void InstallWorker::run() {
// Lock recovery bypasses the provider loop: it is one pacman-side operation
// whose progress comes back through the same signal as an install.
if (m_op == Op::ReleaseLock) {
auto cb = [this](const std::string& message, int) {
emit progress(QString::fromStdString(message));
};
emit finished(m_pacman && m_pacman->releaseDatabaseLock(m_lockHolder, cb));
return;
}
const int providerCount = static_cast<int>(m_providers.size());
bool success = true;
for (int index = 0; index < providerCount; ++index) {
IPackageManager* pm = m_providers[static_cast<size_t>(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, 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) 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.
switch (m_op) {
case Op::Install: success = pm->install(m_package, cb) && success; break;
case Op::Remove: success = pm->remove(m_package, cb) && success; break;
case Op::Update: success = pm->update(m_package, cb) && success; break;
case Op::UpdateAll: success = pm->update("", cb) && success; break;
case Op::InstallFile: success = pm->installFile(m_package, cb) && success; break;
case Op::Refresh: success = pm->refresh(cb) && success; break;
case Op::RemovePackages:
success = pm->removePackages(m_packages, cb) && success;
break;
case Op::CleanCache: success = pm->cleanCache(cb) && success; break;
case Op::ReleaseLock: break; // handled before the provider loop
}
}
emit finished(success);
}
+89
View File
@@ -0,0 +1,89 @@
#pragma once
#include <QThread>
#include <string>
#include <vector>
#include "package-manager.h"
#include "pacman-manager.h"
// Background workers shared by every front-end (the Qt window and the web UI).
// They own the aggregation rules — each provider queried in turn, every result
// tagged with its provider id — so both interfaces display the same list.
// Runs a package search off the UI thread. Queries every given provider and
// merges the results, tagging each package with its provider id.
class SearchWorker : public QThread {
Q_OBJECT
public:
SearchWorker(const std::vector<IPackageManager*>& providers, const std::string& query);
void run() override;
signals:
void finished(std::vector<PackageInfo> 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<PackageInfo> results);
private:
std::vector<IPackageManager*> m_providers;
std::string m_query;
};
// Loads a package list (installed or outdated) off the UI thread, aggregated
// across every given provider.
class ListWorker : public QThread {
Q_OBJECT
public:
enum Mode { Installed, Updates, Cleanup };
ListWorker(const std::vector<IPackageManager*>& providers, Mode mode);
void run() override;
signals:
void finished(std::vector<PackageInfo> results);
private:
std::vector<IPackageManager*> m_providers;
Mode m_mode;
};
// Runs install/remove/update/refresh actions off the UI thread. Single-package
// operations take one provider; UpdateAll/Refresh take every provider and run
// on each of them in sequence.
class InstallWorker : public QThread {
Q_OBJECT
public:
enum class Op {
Install,
Remove,
Update,
UpdateAll,
Refresh,
// Installs the package a file describes (.flatpakref, .flatpakrepo or
// .flatpak bundle); `m_package` then holds the file path, not a name.
InstallFile,
RemovePackages,
CleanCache,
ReleaseLock,
};
InstallWorker(IPackageManager* pm, Op op, const std::string& package);
// Bulk variant: removes several packages in one provider call (cleanup
// page) instead of one call per package.
InstallWorker(IPackageManager* pm, Op op, const std::vector<std::string>& packages);
InstallWorker(const std::vector<IPackageManager*>& providers, Op op);
// Pacman database-lock recovery: stops whatever holds the lock, or drops a
// stale lock file. Runs off the UI thread because waiting for the other
// manager to exit takes seconds.
InstallWorker(PacmanManager* pacman, const PacmanManager::LockHolder& holder);
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<IPackageManager*> m_providers;
Op m_op;
std::string m_package;
std::vector<std::string> m_packages;
PacmanManager* m_pacman = nullptr; // lock recovery only
PacmanManager::LockHolder m_lockHolder;
};