refactor(tree): give the logic layer and the shell a folder each

src/ and include/ are what is left: the controller the screens delegate
to, its workers and its data model (core/), and the window and entry
point that hold them together (app/). With those moved, src/ and
include/ are empty and go away — a header is now always next to its
source, in a folder named after what it does.
This commit is contained in:
BlackAngelTV committed 2026-09-29 21:26:04 +02:00
1 parent c63b231778
commit 5a6aaae244
10 files changed
+22 -22

No files matched your search

-302
View File
@@ -1,302 +0,0 @@
#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);
// ---- 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)
-245
View File
@@ -1,245 +0,0 @@
#pragma once
#include <QElapsedTimer>
#include <QHash>
#include <QMainWindow>
#include <QPalette>
#include <QString>
#include <QStringList>
#include <QSystemTrayIcon>
#include <vector>
#include "app-core.h"
#include "package-manager.h"
class QAction;
class QButtonGroup;
class QDragEnterEvent;
class QDragMoveEvent;
class QDropEvent;
class QFrame;
class QLabel;
class QMimeData;
class QProgressBar;
class QPushButton;
class QStackedWidget;
class QSystemTrayIcon;
class QWidget;
class BrowsePage;
class CleanupPage;
class DashboardPage;
class HistoryPage;
class LogsPage;
class Page;
class PluginsPage;
class SettingsPage;
// The window is only a frame: it owns the sidebar, the header, the status bar,
// the menu, the tray and every dialog, and it stacks one screen per file from
// pages/ inside it. No package-manager command, no privileged operation and no
// pacman query lives here — see include/app-core.h for the logic and
// pages/page.h for the contract a screen honours.
//
// Adding a screen means writing one Page subclass under pages/, registering it
// in setupUI() and giving it a sidebar entry: nothing else in this file has to
// learn about it.
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
~MainWindow();
// Colours the stylesheet cannot reach, applied in main() before any widget
// exists. See the definition for what leaves a light band around a menu.
static QPalette appPalette();
// Installs the Flatpak files handed over by the desktop: dropped on the
// window, or opened from the file manager ("Ouvrir avec PacManager", which
// passes them on the command line). One install runs at a time; the rest
// wait in line. Paths the core does not recognise are reported and skipped.
void installLocalFiles(const QStringList& paths);
protected:
// Dragging a .flatpakref / .flatpakrepo / .flatpak onto the window is the
// same request as opening it from the file manager.
void dragEnterEvent(QDragEnterEvent* event) override;
void dragMoveEvent(QDragMoveEvent* event) override;
void dropEvent(QDropEvent* event) override;
// Language switch: Qt asks every widget to retranslate itself.
void changeEvent(QEvent* event) override;
private slots:
void onNavChanged(int id);
void onRefresh();
void onUpdateAll();
void onTrayActivated(QSystemTrayIcon::ActivationReason reason);
void onCheckForUpdates();
// Ticks once a second while an operation runs: what it does when the
// provider has printed nothing for a while is described in onActivityTick().
void onActivityTick();
// ---- What a page asks the frame to do ----
// A page hands over a request so the frame can walk the user through what
// the core needs (sudo password, freeing pacman's lock) and replay it.
void onStartRequested(const AppCore::StartResult& result, const QString& title);
void onPageMessage(const QString& text);
void onOpenPage(const QString& pageId);
void onOpenPackage(const QString& name);
// ---- What the core reports back ----
void onCoreListFinished(AppCore::ListMode mode, std::vector<PackageInfo> results);
void onCoreActionProgress(const QString& message, int percent);
void onCoreActionFinished(const QString& action, const QString& name, bool success,
const QString& error, bool locked);
void onCoreBusyChanged(bool busy);
void onCoreStatusMessage(const QString& message);
void onCoreHistoryChanged();
void onCoreUpdateCheckFinished(bool hasUpdate, const QString& latestVersion,
const QString& errorMessage);
void onCoreSelfUpdateFinished(bool success, const QString& message);
private:
// Sidebar entries, in display order. Named so the sidebar, the dashboard
// shortcuts, the menu bar and the keyboard shortcuts cannot drift apart
// when a page is inserted.
enum NavPage {
NavDashboard = 0,
NavSearch,
NavInstalled,
NavUpdates,
NavCleanup,
NavHistory,
NavLogs,
NavPlugins,
NavSettings,
};
void setupUI();
void setupSidebar();
void setupHeader();
void setupPages();
void setupMenuBar();
void setupTray();
void setupShortcuts();
// Wires a screen: the frame answers its requests and shows the page it asks
// for. Called once per screen by setupPages().
void registerPage(const QString& id, int navId, Page* page);
// Shows the settings screen, which has no sidebar entry of its own.
void openSettingsPage();
// Screen currently displayed, and the screens themselves.
Page* currentPage() const;
void updatePageTitle();
void updateStatusBar();
// Mirrors the pending update count on the sidebar entry, so the page that
// needs attention is visible from wherever the user is.
void setUpdatesBadge(int count);
// Last count given to the badge, kept so a language switch can rebuild the
// entry's label without having to re-query the core.
int m_updatesBadgeCount = 0;
void notifyUpdatesAvailable(int count);
// Runs a request and, when the core refused it, walks the user through what
// it needs before replaying it.
void handleStartResult(const AppCore::StartResult& result, const QString& title);
// Asks for the sudo password and hands it to the core. Returns false when
// the user cancelled.
bool promptForSudoPassword();
// Names the process holding pacman's database and offers to close it — or to
// drop a stale lock — so the pending action can resume.
void handleDatabaseLock(const QString& title);
// Lock-aware failure reporting: a locked database opens the recovery
// dialog, anything else is shown as-is.
void showActionError(const QString& title, const QString& error, bool locked);
void applyCredentialMode(AppCore::CredentialMode mode);
// Applies the mode and re-checks the matching menu entry, so the menu bar
// and the Settings screen can never disagree about the current mode.
void onCredentialModeRequested(bool atLaunch);
// Re-applies the language and puts the text back in the widgets, so
// switching language on the Settings screen takes effect at once.
void onLanguageChanged(const QString& code);
// Keeps the window's drop target in step with the preference.
void onDragDropEnabledChanged(bool enabled);
// Puts every string the frame owns back into its widget. Called on the
// LanguageChange event, so it is what makes the language setting visible
// without restarting.
void retranslateUI();
// Records that the running operation just said something: the step is kept
// for the heartbeat and the "nothing printed" clock restarts.
void noteOperationOutput(const QString& step);
// The files a drag carries that the core can install; empty when the drop is
// nothing the app handles (which is also how dragEnterEvent refuses it).
QStringList installableDroppedFiles(const QMimeData* mimeData) const;
// Takes the next queued file and asks the core to install it. A core busy
// with another operation leaves it queued: onCoreActionFinished calls back.
void startNextFileInstall();
// Logic layer: it owns the providers, the workers, the history, the
// credentials and the self-updater. The frame never talks to them directly.
AppCore* m_core = nullptr;
// Sidebar
QFrame* m_sidebar = nullptr;
QButtonGroup* m_navGroup = nullptr;
QPushButton* m_refreshButton = nullptr;
QPushButton* m_navUpdatesButton = nullptr;
QLabel* m_versionLabel = nullptr;
// Header
QWidget* m_headerWidget = nullptr;
QLabel* m_headerTitle = nullptr;
QLabel* m_headerSubtitle = nullptr;
QPushButton* m_headerUpdateAllButton = nullptr;
// Screens, stacked in sidebar order.
QStackedWidget* m_pages = nullptr;
QHash<QString, Page*> m_pageById; // "search" -> screen
QHash<QString, int> m_navIdByPage; // "search" -> NavSearch
DashboardPage* m_dashboard = nullptr;
BrowsePage* m_browse = nullptr;
CleanupPage* m_cleanup = nullptr;
HistoryPage* m_history = nullptr;
LogsPage* m_logs = nullptr;
PluginsPage* m_plugins = nullptr;
SettingsPage* m_settings = nullptr;
// Sidebar entries, by nav id, so the language can be re-applied to them
// (and the updates badge found) without rebuilding the sidebar.
QHash<int, QPushButton*> m_navButtons;
// Progress of the running operation, anchored in the status bar: the bar
// itself (indeterminate until a provider reports a real percentage) and the
// value next to it.
QProgressBar* m_installProgressBar = nullptr;
QLabel* m_progressLabel = nullptr;
// Highest percentage reported by the current operation, and a counter that
// invalidates the "hide the completed bar" timer when a new one starts.
int m_progressValue = 0;
int m_progressGeneration = 0;
// What the window knows about the operation it is waiting on. A download
// that takes minutes can print nothing at all for minutes, and a window
// that only repeats the same sentence looks broken: the timer re-states the
// current step with the elapsed time, and the journal notes the wait.
QTimer* m_activityTimer = nullptr;
QElapsedTimer m_operationClock;
QString m_operationStep;
qint64 m_lastOutputAtMs = 0;
qint64 m_lastWaitNoteMs = 0;
// Files waiting to be installed (dropped or opened), and whether one is
// being installed right now.
QStringList m_pendingFileInstalls;
bool m_fileInstallRunning = false;
// Tray (optional: hidden when the desktop has no system tray)
QSystemTrayIcon* m_tray = nullptr;
// Last update count already announced in a tray notification, so repeated
// dashboard refreshes do not spam the user.
int m_lastNotifiedUpdates = -1;
// Menu
QAction* m_credLaunchAction = nullptr;
QAction* m_credEachTimeAction = nullptr;
};
-34
View File
@@ -1,34 +0,0 @@
#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;
};
-89
View File
@@ -1,89 +0,0 @@
#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;
};