#include "app-core.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "app-logging.h" #include "log-manager.h" #include "plugin-package.h" #include "provider-trace.h" #include "startup-check.h" #include "workers.h" namespace { // Where pacman keeps its log file. constexpr const char* kPacmanLogPath = "/var/log/pacman.log"; // Closes a popen() stream. A named deleter avoids the GCC warning about the // function-pointer attributes carried by decltype(&pclose) being dropped. struct PipeCloser { void operator()(FILE* file) const { if (file) pclose(file); } }; std::string runCommand(const std::string& command) { std::array buffer{}; std::string output; std::unique_ptr pipe(popen(command.c_str(), "r")); if (!pipe) return output; while (fgets(buffer.data(), buffer.size(), pipe.get())) output += buffer.data(); return output; } // Value of a "Key : value" field in pacman's -Qi/-Si output. std::string infoField(const std::string& output, const std::string& name) { std::istringstream stream(output); std::string line; while (std::getline(stream, line)) { const std::size_t colon = line.find(':'); if (colon == std::string::npos) continue; std::string key = line.substr(0, colon); while (!key.empty() && key.back() == ' ') key.pop_back(); if (key != name) continue; std::string value = line.substr(colon + 1); const std::size_t start = value.find_first_not_of(" \t"); if (start != std::string::npos) value = value.substr(start); while (!value.empty() && (value.back() == '\n' || value.back() == '\r' || value.back() == ' ')) { value.pop_back(); } return value; } return std::string(); } AppCore::StartResult accepted() { AppCore::StartResult result; result.started = true; return result; } 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; result.locked = locked; return result; } // "pacman + flatpak", for the journal header of an operation. QString providerLabel(const std::vector& 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) { // Workers emit std::vector from another thread; without this // registration the queued connection is dropped silently. qRegisterMetaType>("std::vector"); qRegisterMetaType("AppCore::ListMode"); // Provider narration — the exact commands run and the decisions around // them — goes to the journal and nowhere else: it is detail to read after // the fact, not something to flash in the status bar while an operation // runs. Providers reach it through a Qt-free sink so they keep building // into the headless tests. provider_trace::setSink( [](const std::string& source, const std::string& message) { LogManager::instance().logEvent(QString::fromStdString(source), QString::fromStdString(message)); }); // Plugin registry: pacman is compiled in; every other plugin (Flatpak, // AUR, ...) ships as an external shared library loaded at runtime from the // plugins/ directories. m_plugins = new PluginManager(); m_plugins->registerBuiltin( {"pacman", "Pacman", "1.0.0", tr("Gestionnaire de paquets natif d'Arch Linux").toStdString(), "FWS"}, new PacmanManager()); m_plugins->discoverExternal(); // Non-owning handle kept for sudo credentials and the database lock. m_pacman = dynamic_cast(m_plugins->managerFor("pacman")); // Plugin packages: a .fwspacm archive dropped on the window, and the // bookkeeping of what was installed from one. What a package carries lands // in the directory the registry scans, so a successful install only needs // that registry reloaded. m_packages = new PluginPackage(this); connect(m_packages, &PluginPackage::installFinished, this, [this](const QString& id, bool success, const QString& message) { if (success) reloadPlugins(); emit pluginPackageInstalled(id, success, message); }); connect(m_packages, &PluginPackage::removeFinished, this, [this](const QString& id, bool success, const QString& message) { if (success) reloadPlugins(); emit pluginPackageRemoved(id, success, message); }); m_history = new HistoryManager(); m_update = new UpdateManager(this); m_credentialMode = m_settings.value("credentials/mode", "each").toString() == "launch" ? CredentialMode::AtLaunch : CredentialMode::EachTime; connect(m_update, &UpdateManager::checkFinished, this, &AppCore::updateCheckFinished); connect(m_update, &UpdateManager::selfUpdateFinished, this, &AppCore::selfUpdateFinished); qCInfo(pacmgrOp) << "core ready," << static_cast(availableProviders().size()) << tr("provider(s) available"); LogManager::instance().logEvent( QStringLiteral("app"), tr("PacManager %1 démarré — %2 gestionnaire(s) : %3") .arg(version()) .arg(static_cast(availableProviders().size())) .arg(providerLabel(availableProviders()))); } AppCore::~AppCore() { // A listing or an action may still be running: its worker calls into the // providers, so it has to stop before they are destroyed. Waiting here also // means the worker thread is never left running while the process tears // down, which used to end in a jump into freed code. for (QThread* worker : {static_cast(m_list), static_cast(m_search), static_cast(m_action)}) { if (!worker) continue; worker->wait(); delete worker; } m_list = nullptr; m_search = nullptr; m_action = nullptr; delete m_plugins; // owns every provider, built-in and external delete m_history; // m_update is a child QObject, destroyed with the core. } void AppCore::disposeWorker(QThread* worker) { connect(worker, &QThread::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); } // --------------------------------------------------------------------------- // Registry and state // --------------------------------------------------------------------------- std::vector AppCore::availableProviders() const { return m_plugins->availableManagers(); } QStringList AppCore::availableProviderNames() const { QStringList names; for (IPackageManager* pm : availableProviders()) { names << QString::fromStdString(pm->getName()); } return names; } bool AppCore::hasAvailableProvider() const { return !availableProviders().empty(); } IPackageManager* AppCore::providerFor(const QString& providerId) const { if (const auto* entry = m_plugins->findAvailable(providerId.toStdString())) { return entry->manager; } auto providers = availableProviders(); return providers.empty() ? nullptr : providers.front(); } QString AppCore::version() const { return UpdateManager::currentVersion(); } int AppCore::historyCount() const { return static_cast(m_history->getHistory().size()); } int AppCore::installedCount() const { return m_installedPackages.empty() ? -1 : static_cast(m_installedPackages.size()); } int AppCore::updateCount() const { return m_updatePackages.empty() ? -1 : static_cast(m_updatePackages.size()); } void AppCore::setBusy(bool busy) { if (m_busy == busy) return; m_busy = busy; emit busyChanged(busy); } void AppCore::invalidateDetails() { // The installed state changed: the cached pacman details are stale. m_detailsCache.clear(); } void AppCore::refreshProviderCache() { // Provider availability changed (a tool was installed, plugins reloaded). invalidateDetails(); } // --------------------------------------------------------------------------- // Credentials // --------------------------------------------------------------------------- void AppCore::setCredentialMode(CredentialMode mode) { m_credentialMode = mode; m_settings.setValue("credentials/mode", mode == CredentialMode::AtLaunch ? "launch" : "each"); if (mode == CredentialMode::EachTime) { // Each operation must re-authenticate: never keep the password around. clearSudoPassword(); LogManager::instance().logEvent( QStringLiteral("config"), tr("identifiants sudo demandés à chaque opération")); emit statusMessage(tr("Identifiants demandés à chaque opération.")); } else { LogManager::instance().logEvent( QStringLiteral("config"), tr("identifiants sudo demandés une fois par session")); emit statusMessage(tr("Identifiants enregistrés pour la session.")); } } void AppCore::setSudoPassword(const QString& password) { if (m_pacman) m_pacman->setPassword(password.toStdString()); } void AppCore::clearSudoPassword() { if (m_pacman) m_pacman->clearPassword(); } bool AppCore::hasSudoPassword() const { return m_pacman && m_pacman->hasPassword(); } AppCore::StartResult AppCore::credentialGate( const std::vector& providers) const { bool privileged = false; for (IPackageManager* pm : providers) { if (pm && pm->requiresPassword()) { privileged = true; break; } } if (!privileged) return accepted(); if (!m_pacman || !m_pacman->isAvailable()) { return refused(tr("pacman est indisponible sur ce système.")); } if (std::system("which sudo > /dev/null 2>&1") != 0) { return refused(tr("sudo n'est pas installé sur ce système.")); } if (m_pacman->hasPassword()) return accepted(); // The view prompts for the password and calls retryPendingRequest(). return refused(tr("Mot de passe administrateur (sudo) requis."), /*needsPassword=*/true); } // --------------------------------------------------------------------------- // Listings // --------------------------------------------------------------------------- AppCore::StartResult AppCore::loadInstalled() { return startList(ListMode::Installed); } AppCore::StartResult AppCore::loadUpdates() { return startList(ListMode::Updates); } AppCore::StartResult AppCore::loadCleanup() { return startList(ListMode::Cleanup); } AppCore::StartResult AppCore::loadCounts() { // The dashboard shows two figures; the second request queues behind the // first instead of being refused. const StartResult first = startList(ListMode::Installed); if (!first.started) return first; return startList(ListMode::Updates); } AppCore::StartResult AppCore::startList(ListMode mode) { if (!hasAvailableProvider()) { return refused(tr("Aucun gestionnaire de paquets disponible sur ce système.")); } if (m_busy) { return refused(tr("Une opération est en cours, chargement impossible.")); } if (m_list) { m_queuedLists.append(mode); return accepted(); } QString listLabel; switch (mode) { case ListMode::Installed: listLabel = tr("Chargement des paquets installés..."); break; case ListMode::Updates: listLabel = tr("Recherche des mises à jour..."); break; case ListMode::Cleanup: listLabel = tr("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 : mode == ListMode::Updates ? ListWorker::Updates : ListWorker::Cleanup); m_list = worker; connect(worker, &ListWorker::finished, this, [this, mode](std::vector results) { m_list = nullptr; QString done; if (mode == ListMode::Installed) { m_installedPackages = results; done = tr("%1 paquet(s) installé(s)") .arg(results.size()); } else if (mode == ListMode::Updates) { m_updatePackages = results; done = tr("%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; } done = tr("%1 orphelin(s) et %2 paquet(s) legacy " "détecté(s)") .arg(orphans) .arg(static_cast(results.size()) - orphans); } LogManager::instance().logEvent(QStringLiteral("liste"), done); emit statusMessage(done); emit listFinished(mode, results); if (!m_queuedLists.isEmpty()) { const ListMode next = m_queuedLists.takeFirst(); // Deferred so this worker is fully unwound before the next // one starts (and so the view paints the results first). QTimer::singleShot(0, this, [this, next] { startList(next); }); } }); disposeWorker(worker); worker->start(); return accepted(); } // --------------------------------------------------------------------------- // Search // --------------------------------------------------------------------------- AppCore::StartResult AppCore::search(const QString& query) { if (m_busy) { return refused(tr("Une opération est en cours, recherche impossible.")); } if (m_search) return refused(tr("Une recherche est déjà en cours.")); return startSearch(query); } AppCore::StartResult AppCore::startSearch(const QString& query) { if (query.trimmed().isEmpty()) { return refused(tr("Entrez un terme de recherche.")); } auto providers = availableProviders(); if (providers.empty()) { return refused(tr("Aucun gestionnaire de paquets disponible sur ce système.")); } LogManager::instance().logEvent( QStringLiteral("recherche"), tr("\"%1\" via %2").arg(query.trimmed(), providerLabel(providers))); emit statusMessage(tr("Recherche en cours...")); auto* worker = new SearchWorker(providers, query.trimmed().toStdString()); m_search = worker; connect(worker, &SearchWorker::chunk, this, &AppCore::searchChunk); connect(worker, &SearchWorker::finished, this, [this](std::vector results) { m_search = nullptr; const QString done = tr("%1 paquet(s) trouvé(s)") .arg(results.size()); LogManager::instance().logEvent(QStringLiteral("recherche"), done); emit statusMessage(done); emit searchFinished(results); }); disposeWorker(worker); worker->start(); return accepted(); } // --------------------------------------------------------------------------- // Requests (install / remove / update / cleanup / plugin tool / lock) // --------------------------------------------------------------------------- AppCore::StartResult AppCore::install(const PackageInfo& package) { Request request; request.action = QStringLiteral("install"); request.package = package; return startRequest(request); } AppCore::StartResult AppCore::remove(const PackageInfo& package) { Request request; request.action = QStringLiteral("remove"); request.package = package; return startRequest(request); } AppCore::StartResult AppCore::removeInstances(const PackageInfo& package, const std::vector& targets) { if (targets.empty()) return remove(package); if (targets.size() == 1) { // One installation picked: the plain removal of that copy. The label // stays the application name, so the status bar, the journal header and // the history keep naming the application rather than its ref. Request request; request.action = QStringLiteral("remove"); request.package = package; request.target = QString::fromStdString(targets.front()); return startRequest(request); } // Several picked: one operation, one command per installation, the provider // removing each copy in turn. Request request; request.action = QStringLiteral("remove"); request.package = package; request.targets = targets; return startRequest(request); } AppCore::StartResult AppCore::update(const PackageInfo& package) { Request request; request.action = QStringLiteral("update"); request.package = package; return startRequest(request); } AppCore::StartResult AppCore::updateAll() { Request request; request.action = QStringLiteral("update-all"); return startRequest(request); } AppCore::StartResult AppCore::refresh() { Request request; request.action = QStringLiteral("refresh"); return startRequest(request); } AppCore::StartResult AppCore::cleanCaches() { Request request; request.action = QStringLiteral("clean-caches"); return startRequest(request); } AppCore::StartResult AppCore::installFile(const QString& path) { Request request; request.action = QStringLiteral("install-file"); request.path = path.trimmed(); return startRequest(request); } bool AppCore::canInstallFile(const QString& path) const { if (path.trimmed().isEmpty()) return false; for (IPackageManager* pm : availableProviders()) { if (pm->canInstallFile(path.trimmed().toStdString())) return true; } return false; } bool AppCore::isPluginPackage(const QString& path) const { return PluginPackage::isPackagePath(path); } AppCore::StartResult AppCore::removePackages(const std::vector& packages, const QString& description) { Request request; request.action = QStringLiteral("cleanup"); request.packages = packages; request.description = description; return startRequest(request); } AppCore::StartResult AppCore::installPluginTool(const std::string& pluginId) { Request request; request.action = QStringLiteral("install-plugin-tool"); request.pluginId = pluginId; return startRequest(request); } AppCore::StartResult AppCore::releaseDatabaseLock() { if (m_busy) return refused(tr("Une opération est déjà en cours, patientez...")); if (!m_pacman) return refused(tr("pacman est indisponible sur ce système.")); const PacmanManager::LockHolder holder = PacmanManager::detectLockHolder(); const StartResult gate = credentialGate({m_pacman}); if (!gate.started) return gate; setBusy(true); emit statusMessage(tr("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) { if (!message.isEmpty()) LogManager::instance().appendOutput(message); emit statusMessage(message); }); connect(worker, &InstallWorker::finished, this, [this](bool released) { setBusy(false); if (!m_pacman) { LogManager::instance().endCommand(released); return; } if (!released) { emit statusMessage(tr("Base pacman toujours verrouillée")); // The core is only asked to free the lock when it is actually held: // releasing is one, single, resume of the pending request. // 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(tr("Base libérée, reprise de l'opération...")); // Deferred so the status message paints before the replayed action // starts streaming its own progress. QTimer::singleShot(0, this, [this] { retryPendingRequest(); }); }); disposeWorker(worker); worker->start(); return accepted(); } AppCore::StartResult AppCore::startRequest(Request request) { if (m_busy) return refused(tr("Une opération est déjà en cours, patientez...")); const QString action = request.action; std::vector providers; InstallWorker::Op op = InstallWorker::Op::Install; QString label = QString::fromStdString(request.package.name); bool bulk = false; if (action == QLatin1String("install") || action == QLatin1String("remove") || action == QLatin1String("update")) { IPackageManager* provider = providerFor(QString::fromStdString(request.package.provider)); if (!provider) { return refused(tr("Aucun gestionnaire de paquets disponible.")); } if (request.package.name.empty()) { return refused(tr("Nom de paquet manquant.")); } if (action == QLatin1String("install") && !provider->canInstall()) { return refused(tr("%1 ne sait pas installer de paquets.") .arg(QString::fromStdString(provider->getName()))); } if (action == QLatin1String("remove") && !provider->canRemove()) { return refused(tr("%1 ne sait pas supprimer de paquets.") .arg(QString::fromStdString(provider->getName()))); } if (action == QLatin1String("update") && !provider->canUpdate()) { return refused(tr("%1 ne sait pas mettre à jour de paquets.") .arg(QString::fromStdString(provider->getName()))); } providers = {provider}; op = action == QLatin1String("install") ? InstallWorker::Op::Install : action == QLatin1String("remove") ? InstallWorker::Op::Remove : InstallWorker::Op::Update; } else if (action == QLatin1String("update-all")) { for (IPackageManager* pm : availableProviders()) { if (pm->canUpdate()) providers.push_back(pm); } op = InstallWorker::Op::UpdateAll; } else if (action == QLatin1String("refresh")) { providers = availableProviders(); op = InstallWorker::Op::Refresh; } else if (action == QLatin1String("clean-caches")) { for (IPackageManager* pm : availableProviders()) { if (pm->canCleanCache()) providers.push_back(pm); } op = InstallWorker::Op::CleanCache; if (providers.empty()) { return refused(tr("Aucun cache à nettoyer sur ce système.")); } } else if (action == QLatin1String("install-file")) { if (request.path.isEmpty()) { return refused(tr("Aucun fichier à installer.")); } // The provider owns the file formats it knows, so the routing is the // same kind of lookup as providerFor() is for package names. for (IPackageManager* pm : availableProviders()) { if (!pm->canInstallFile(request.path.toStdString())) continue; providers = {pm}; break; } if (providers.empty()) { return refused(tr("Aucun gestionnaire de paquets ne sait installer ce fichier.")); } op = InstallWorker::Op::InstallFile; // The package name is unknown until flatpak resolves the file: the file // name is what the status bar and the history row can honestly show. label = QFileInfo(request.path).completeBaseName(); if (label.isEmpty()) label = request.path; request.package.name = label.toStdString(); } else if (action == QLatin1String("cleanup")) { // One command per provider: each provider groups the packages it owns, // and the groups run one after another (pacman locks its database). m_pendingRemovals.clear(); for (const auto& pkg : request.packages) { IPackageManager* provider = providerFor(QString::fromStdString(pkg.provider)); if (!provider || !provider->canRemove()) continue; auto group = std::find_if( m_pendingRemovals.begin(), m_pendingRemovals.end(), [provider](const auto& entry) { return entry.first == provider; }); if (group == m_pendingRemovals.end()) { m_pendingRemovals.push_back({provider, {pkg.name}}); } else { group->second.push_back(pkg.name); } } if (m_pendingRemovals.empty()) { return refused(tr("Aucun paquet sélectionné n'est supprimable.")); } m_cleanupRemovalDescription = request.description; // The gate has to see who the groups belong to: a bulk removal of pacman // packages is a privileged operation like any other, and without them // here it would run `sudo` with an empty password instead of asking — // which only works by accident, when sudo's timestamp is still valid. for (const auto& group : m_pendingRemovals) providers.push_back(group.first); bulk = true; } else if (action == QLatin1String("install-plugin-tool")) { if (!m_pacman || !m_pacman->isAvailable()) { return refused(tr("pacman est requis pour installer l'outil.")); } std::string hint; for (const auto& entry : m_plugins->plugins()) { if (entry.info.id == request.pluginId) { hint = entry.info.installHint; break; } } if (hint.empty()) { return refused(tr("Aucun paquet système connu pour ce plugin.")); } providers = {m_pacman}; op = InstallWorker::Op::Install; label = QString::fromStdString(hint); } else { return refused(tr("Action inconnue : %1").arg(action)); } if (providers.empty()) { return refused(tr("Aucun gestionnaire de paquets disponible.")); } // Kept before the credential check: a request refused for a missing // password (or a locked database) is exactly the one to replay afterwards. m_pending = request; const StartResult gate = credentialGate(providers); if (!gate.started) return gate; setBusy(true); emit statusMessage(startMessage(action, label)); if (bulk) { m_removalSuccess = true; LogManager::instance().beginCommand( providerLabel(providers), QStringLiteral("cleanup"), request.description); startNextRemovalGroup(); return accepted(); } // Multi-provider ops (update-all, refresh, cache purge) walk every provider // in one worker; single-package ops target one provider. InstallWorker* worker = nullptr; if (action == QLatin1String("update-all") || action == QLatin1String("refresh") || action == QLatin1String("clean-caches")) { worker = new InstallWorker(providers, op); } else if (!request.targets.empty()) { // Several installations of one application were picked in the chooser: // the provider removes one copy per target, and the row they share is // what the journal and the history name. worker = new InstallWorker(providers.front(), InstallWorker::Op::RemovePackages, request.targets); } else if (action == QLatin1String("install-file")) { // A file install needs the path, not the display label the other // single-provider operations pass. worker = new InstallWorker(providers.front(), op, request.path.toStdString()); } else if (!request.target.isEmpty()) { // A single installation was picked: the target names it, the label does // not. worker = new InstallWorker(providers.front(), op, request.target.toStdString()); } else { worker = new InstallWorker(providers.front(), op, label.toStdString()); } return startAction(worker, request, providers); } QString AppCore::startMessage(const QString& action, const QString& label) const { if (action == QLatin1String("install")) { return tr("Installation de %1...").arg(label); } if (action == QLatin1String("remove")) { return tr("Suppression de %1...").arg(label); } if (action == QLatin1String("update")) { return tr("Mise à jour de %1...").arg(label); } if (action == QLatin1String("update-all")) { return tr("Mise à jour de tous les paquets..."); } if (action == QLatin1String("refresh")) { return tr("Rafraîchissement des sources..."); } if (action == QLatin1String("clean-caches")) { return tr("Nettoyage des caches..."); } if (action == QLatin1String("install-file")) { return tr("Installation depuis un fichier : %1...").arg(label); } if (action == QLatin1String("install-plugin-tool")) { return tr("Installation de l'outil %1...").arg(label); } return tr("Opération en cours..."); } AppCore::StartResult AppCore::startAction(InstallWorker* worker, const Request& request, const std::vector& providers) { m_action = worker; qCInfo(pacmgrOp) << request.action << QString::fromStdString(request.package.name); // Journal header: which provider(s) and action, so the raw output that // follows reads like a hand-run session. No synthesized command line here: // `request.action target` is not what actually runs — the provider reports // its real command line right after the header, through the trace sink. LogManager::instance().beginCommand(providerLabel(providers), request.action); connect(worker, &InstallWorker::progress, this, [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, [this, request, providers](bool success) { m_action = nullptr; finishAction(request, providers, success); }); disposeWorker(worker); worker->start(); return accepted(); } QString AppCore::firstError(const std::vector& providers) const { for (IPackageManager* pm : providers) { if (pm && !pm->lastError().empty()) return QString::fromStdString(pm->lastError()); } return QString(); } void AppCore::finishAction(const Request& request, const std::vector& providers, bool success) { setBusy(false); const QString action = request.action; const QString name = QString::fromStdString(request.package.name); QString error = firstError(providers); if (!success && error.isEmpty()) { error = tr("L'opération a échoué."); } const bool locked = !success && ((m_pacman && m_pacman->lastErrorWasLock()) || PacmanManager::dbLocked(error.toStdString())); // A locked database is recoverable: the request stays pending so the view // can free the lock and have it replayed. Anything else is dropped. if (success || !locked) m_pending.reset(); emit statusMessage(success ? successMessage(action, name) : failureMessage(action, name)); // History entries, identical to what the History page and the CSV export // have always shown. if (action == QLatin1String("install") || action == QLatin1String("remove") || action == QLatin1String("update")) { recordHistory(action, name, providers.empty() ? nullptr : providers.front(), success); } else if (action == QLatin1String("install-file")) { // Recorded as an install so the History page's filter picks it up. recordHistory(QStringLiteral("install"), name, providers.empty() ? nullptr : providers.front(), success); } else if (action == QLatin1String("clean-caches")) { for (IPackageManager* pm : providers) { recordHistory(QStringLiteral("cleanup"), QStringLiteral("caches"), pm, success); } } clearCredentialsAfterUse(); if (action == QLatin1String("install") || action == QLatin1String("remove") || action == QLatin1String("update") || action == QLatin1String("install-file")) { invalidateDetails(); } if (action == QLatin1String("install-plugin-tool") && success) { m_plugins->refreshAvailability(); refreshProviderCache(); emit pluginsChanged(); } LogManager::instance().endCommand(success, error); emit actionFinished(action, name, success, error, locked); } QString AppCore::successMessage(const QString& action, const QString& name) const { if (action == QLatin1String("install")) { return tr("%1 installé avec succès").arg(name); } if (action == QLatin1String("remove")) { return tr("%1 supprimé avec succès").arg(name); } if (action == QLatin1String("update")) { return tr("Mise à jour terminée"); } if (action == QLatin1String("update-all")) { return tr("Tous les paquets sont à jour"); } if (action == QLatin1String("refresh")) { return tr("Sources rafraîchies"); } if (action == QLatin1String("clean-caches")) { return tr("Caches nettoyés"); } if (action == QLatin1String("install-file")) { return tr("%1 installé avec succès").arg(name); } if (action == QLatin1String("install-plugin-tool")) { return tr("Outil installé, plugin disponible."); } return tr("Opération terminée"); } QString AppCore::failureMessage(const QString& action, const QString& name) const { if (action == QLatin1String("install")) { return tr("Échec de l'installation de %1").arg(name); } if (action == QLatin1String("remove")) { return tr("Échec de la suppression de %1").arg(name); } if (action == QLatin1String("update")) { return tr("Échec de la mise à jour"); } if (action == QLatin1String("update-all")) { return tr("Erreur lors de la mise à jour globale"); } if (action == QLatin1String("refresh")) { return tr("Erreur lors du rafraîchissement"); } if (action == QLatin1String("clean-caches")) { return tr("Échec du nettoyage des caches"); } if (action == QLatin1String("install-file")) { return tr("Échec de l'installation de %1").arg(name); } if (action == QLatin1String("install-plugin-tool")) { return tr("Échec de l'installation de l'outil."); } return tr("Échec de l'opération"); } void AppCore::recordHistory(const QString& action, const QString& name, IPackageManager* provider, bool success) { m_history->record({"", action.toStdString(), name.toStdString(), provider ? provider->getName() : std::string(), success}); emit historyChanged(); } void AppCore::clearCredentialsAfterUse() { // Per-operation mode: the password is single-use, drop it so the next // privileged action authenticates again. if (m_credentialMode == CredentialMode::EachTime) clearSudoPassword(); } // --------------------------------------------------------------------------- // Bulk removal (cleanup page) // --------------------------------------------------------------------------- void AppCore::startNextRemovalGroup() { if (m_pendingRemovals.empty()) { LogManager::instance().endCommand(m_removalSuccess); m_removalSuccess = true; setBusy(false); clearCredentialsAfterUse(); invalidateDetails(); m_pending.reset(); // The package set changed: reload what the pages display. startList(ListMode::Cleanup); startList(ListMode::Installed); startList(ListMode::Updates); return; } const auto job = m_pendingRemovals.front(); m_pendingRemovals.erase(m_pendingRemovals.begin()); IPackageManager* provider = job.first; const std::vector packages = job.second; const QString groupLabel = tr("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) { 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, [this, provider, packages](bool success) { m_action = nullptr; // One history row per removed package keeps the install/remove // filters of the History page meaningful. for (const auto& name : packages) { recordHistory(QStringLiteral("remove"), QString::fromStdString(name), provider, success); } if (!success) { m_removalSuccess = false; // Keep the failed group queued, then rebuild the pending // request from what is left: a lock recovery replays exactly // the outstanding work. m_pendingRemovals.insert(m_pendingRemovals.begin(), {provider, packages}); Request remaining; remaining.action = QStringLiteral("cleanup"); remaining.description = m_cleanupRemovalDescription; for (const auto& group : m_pendingRemovals) { for (const auto& name : group.second) { PackageInfo pkg; pkg.name = name; pkg.provider = group.first->getName(); remaining.packages.push_back(pkg); } } m_pending = remaining; setBusy(false); clearCredentialsAfterUse(); 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(tr("Échec du nettoyage")); emit actionFinished(QStringLiteral("cleanup"), m_cleanupRemovalDescription, false, error, locked); return; } emit actionProgress(tr("%1 paquet(s) supprimé(s)") .arg(packages.size()), -1); startNextRemovalGroup(); }); disposeWorker(worker); worker->start(); } AppCore::StartResult AppCore::retryPendingRequest() { if (!m_pending) return refused(tr("Aucune opération en attente.")); const Request request = *m_pending; m_pending.reset(); // A bulk removal is replayed with the groups it still has queued. const StartResult result = startRequest(request); if (!result.started && !result.needsPassword && !result.locked) { emit statusMessage(result.error); } return result; } void AppCore::cancelPendingRequest() { m_pending.reset(); m_pendingRemovals.clear(); } // --------------------------------------------------------------------------- // Plugins / history / logs / details // --------------------------------------------------------------------------- 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"), tr("registre rechargé")); m_plugins->reload(); refreshProviderCache(); emit pluginsChanged(); emit statusMessage(tr("Plugins rechargés.")); } void AppCore::installPluginPackage(const QString& path) { LogManager::instance().logEvent( QStringLiteral("plugin"), tr("installation du paquet : %1").arg(QFileInfo(path).fileName())); emit statusMessage( tr("Installation du paquet %1...").arg(QFileInfo(path).fileName())); m_packages->install(path); } void AppCore::removePluginPackage(const QString& id) { LogManager::instance().logEvent( QStringLiteral("plugin"), tr("suppression du paquet : %1").arg(id)); m_packages->remove(id); } void AppCore::clearHistory() { LogManager::instance().logEvent(QStringLiteral("historique"), tr("effacé")); m_history->clear(); emit historyChanged(); emit statusMessage(tr("Historique effacé")); } QString AppCore::readPackageLog(QString* error) const { QFile logFile(QString::fromUtf8(kPacmanLogPath)); if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { if (error) { *error = tr("Impossible d'ouvrir %1.\n" "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(); } if (error) error->clear(); 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(); // Cache per name+provider+version+installed: selecting a row repeatedly (or // arrowing through the list) must not re-spawn pacman every time. const QString key = QStringLiteral("%1|%2|%3|%4") .arg(QString::fromStdString(pkg.name), QString::fromStdString(pkg.provider), QString::fromStdString(pkg.version)) .arg(pkg.installed ? 1 : 0); const auto cached = m_detailsCache.constFind(key); if (cached != m_detailsCache.constEnd()) return cached.value(); LogManager::instance().logEvent( tr("détails"), tr("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 "; std::string installed = runCommand(queryInstalled + pkg.name + " 2>/dev/null"); if (installed.empty() && isPacmanPkg) { installed = runCommand("pacman -Qi " + pkg.name + " 2>/dev/null"); } std::string text; auto addRow = [&text](const QString& label, const std::string& value) { if (value.empty() || value == "None" || value == "--") return; if (!text.empty()) text += "\n"; text += label.toStdString() + " : " + value; }; if (!installed.empty()) { addRow(tr("Taille installée"), infoField(installed, "Installed Size")); addRow(tr("Date d'installation"), infoField(installed, "Install Date")); addRow(tr("Dépend de"), infoField(installed, "Depends On")); addRow(tr("Requis par"), infoField(installed, "Required By")); } else { // Only the sync database is queried when the package is not installed // here, halving the subprocess count on the Installed/Updates pages. const std::string sync = runCommand(querySync + pkg.name + " 2>/dev/null"); if (!sync.empty()) { addRow(tr("Taille du téléchargement"), infoField(sync, "Download Size")); addRow(tr("Taille installée"), infoField(sync, "Installed Size")); addRow(tr("Dépend de"), infoField(sync, "Depends On")); } } // Bound the cache so a long browsing session cannot grow it forever. if (m_detailsCache.size() > 512) m_detailsCache.clear(); const QString details = QString::fromStdString(text); m_detailsCache.insert(key, details); return details; } // --------------------------------------------------------------------------- // Application self-update // --------------------------------------------------------------------------- bool AppCore::shouldCheckForAppUpdate() const { if (!appUpdateCheckRefusal().isEmpty()) return false; return m_update->shouldCheck(); } QString AppCore::appUpdateCheckRefusal() const { AppSettings& preferences = AppSettings::instance(); // The user parked the app's own updates: no automatic check, and the manual // one says why instead of quietly doing nothing. if (preferences.updatesBlocked()) { return AppSettings::blockDescription( preferences.updatesBlockedIndefinitely(), preferences.updateBlockedUntil(), QDateTime::currentDateTime()); } if (!preferences.autoUpdateCheckEnabled()) { return tr("La vérification automatique des mises à jour est désactivée dans " "les paramètres."); } return QString(); } void AppCore::checkForAppUpdate() { const QString refusal = appUpdateCheckRefusal(); if (!refusal.isEmpty()) { LogManager::instance().logEvent(QStringLiteral("maj-app"), refusal); emit statusMessage(refusal); return; } LogManager::instance().logEvent(QStringLiteral("maj-app"), tr("vérification de version")); emit statusMessage(tr("Vérification des mises à jour...")); m_update->checkForUpdates(); } bool AppCore::canSelfUpdate() const { return m_update->canSelfUpdate(); } UpdateManager::UpdateMethod AppCore::updateMethod() const { return m_update->updateMethod(); } QString AppCore::updateMethodDescription() const { return UpdateManager::methodDescription(m_update->updateMethod(), m_update->binDir()); } QString AppCore::releasePageUrl() const { return m_update->releasePageUrl(); } QString AppCore::binDir() const { return m_update->binDir(); } bool AppCore::binDirWritable() const { return QFileInfo(m_update->binDir()).isWritable(); } bool AppCore::applySelfUpdate(const QString& sudoPassword, QString* error) { if (!m_update->canSelfUpdate()) { if (error) { *error = tr("Aucune mise à jour ne peut être appliquée localement."); } return false; } if (error) error->clear(); LogManager::instance().logEvent(QStringLiteral("maj-app"), tr("mise à jour appliquée")); m_update->performSelfUpdate(sudoPassword); return true; } // --------------------------------------------------------------------------- // Startup update check // --------------------------------------------------------------------------- namespace { // Directory the systemd user unit is written under. GenericConfigLocation is // ~/.config, honouring XDG_CONFIG_HOME, which is exactly where systemd looks. QString userConfigDir() { QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation); if (dir.isEmpty()) dir = QDir::homePath() + "/.config"; return dir; } } // namespace bool AppCore::checkUpdatesAtStartup() const { return m_settings.value("updates/checkAtStartup", true).toBool(); } void AppCore::setCheckUpdatesAtStartup(bool enabled) { m_settings.setValue("updates/checkAtStartup", enabled); const QString configDir = userConfigDir(); QString error; if (enabled) { // The unit runs the executable that is doing the installing, so the // check follows an app installed anywhere (~/.local/bin, /usr/bin...). const QString program = UpdateManager::restartProgram(QCoreApplication::applicationDirPath()); if (program.isEmpty() || !StartupCheck::installAutostart(configDir, program, &error)) { LogManager::instance().logEvent( QStringLiteral("config"), QStringLiteral("autostart des mises à jour impossible : %1") .arg(error.isEmpty() ? QStringLiteral("binaire introuvable") : error)); emit statusMessage(tr("Impossible d'installer la vérification au démarrage.")); return; } StartupCheck::reloadUserManager(); LogManager::instance().logEvent( QStringLiteral("config"), QStringLiteral("vérification des mises à jour au démarrage activée")); emit statusMessage(tr( "Vérification des mises à jour au démarrage activée (notification à l'ouverture de session).")); } else { StartupCheck::removeAutostart(configDir, &error); StartupCheck::reloadUserManager(); LogManager::instance().logEvent( QStringLiteral("config"), QStringLiteral("vérification des mises à jour au démarrage désactivée")); emit statusMessage(tr("Vérification des mises à jour au démarrage désactivée.")); } } void AppCore::ensureStartupAutostart() { if (!checkUpdatesAtStartup()) return; const QString program = UpdateManager::restartProgram(QCoreApplication::applicationDirPath()); if (program.isEmpty()) return; const QString configDir = userConfigDir(); const bool wasEnabled = StartupCheck::autostartEnabled(configDir); // Rewriting the unit on every launch keeps the executable path current (the // app may have moved), but only a fresh install needs systemd to be told. QString error; if (!StartupCheck::installAutostart(configDir, program, &error)) { LogManager::instance().logEvent( QStringLiteral("config"), QStringLiteral("autostart des mises à jour non installé : %1").arg(error)); return; } if (!wasEnabled) StartupCheck::reloadUserManager(); } // --------------------------------------------------------------------------- // pacman's database lock // --------------------------------------------------------------------------- bool AppCore::databaseLocked() const { return !PacmanManager::databaseIsFree(); } PacmanManager::LockHolder AppCore::lockHolder() const { return PacmanManager::detectLockHolder(); } QString AppCore::databaseLockDescription() const { return QString::fromStdString(PacmanManager::describeLockHolder(lockHolder())); }