From 897c174925d0b9fe90e5c61eeefa44b73d93a10a Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Sun, 13 Sep 2026 11:45:48 +0200 Subject: [PATCH] refactor(arch): split the app into a logic core and per-screen pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All the business logic now lives in AppCore (providers, workers, history, plugins, sudo and pacman-lock handling), freed from any widget so it runs headless and is testable on its own. The Qt window becomes a thin frame around one file per screen under pages/, wired through a common Page contract and a shared ui-kit. CMake gains the app-core-test target, which links Qt Core only to enforce the headless guarantee. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- CMakeLists.txt | 39 +- include/app-core.h | 242 +++ include/main-window.h | 378 +---- include/workers.h | 86 + pages/browse-page.cpp | 508 ++++++ pages/browse-page.h | 85 + pages/cleanup-page.cpp | 234 +++ pages/cleanup-page.h | 52 + pages/dashboard-page.cpp | 205 +++ pages/dashboard-page.h | 36 + pages/history-page.cpp | 150 ++ pages/history-page.h | 30 + pages/logs-page.cpp | 81 + pages/logs-page.h | 32 + pages/page.cpp | 13 + pages/page.h | 54 + pages/plugins-page.cpp | 217 +++ pages/plugins-page.h | 38 + pages/ui-kit.cpp | 163 ++ pages/ui-kit.h | 77 + src/app-core.cpp | 1025 ++++++++++++ src/main-window.cpp | 3293 ++++++-------------------------------- src/workers.cpp | 131 ++ tests/app-core.test.cpp | 209 +++ 24 files changed, 4322 insertions(+), 3056 deletions(-) create mode 100644 include/app-core.h create mode 100644 include/workers.h create mode 100644 pages/browse-page.cpp create mode 100644 pages/browse-page.h create mode 100644 pages/cleanup-page.cpp create mode 100644 pages/cleanup-page.h create mode 100644 pages/dashboard-page.cpp create mode 100644 pages/dashboard-page.h create mode 100644 pages/history-page.cpp create mode 100644 pages/history-page.h create mode 100644 pages/logs-page.cpp create mode 100644 pages/logs-page.h create mode 100644 pages/page.cpp create mode 100644 pages/page.h create mode 100644 pages/plugins-page.cpp create mode 100644 pages/plugins-page.h create mode 100644 pages/ui-kit.cpp create mode 100644 pages/ui-kit.h create mode 100644 src/app-core.cpp create mode 100644 src/workers.cpp create mode 100644 tests/app-core.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6dc88ee..3f8fe2c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,6 +32,18 @@ set(SOURCES src/package-model.cpp src/update-manager.cpp src/app-logging.cpp + # Logic layer: background workers and the controller the screens delegate to. + src/workers.cpp + src/app-core.cpp + # Interface: one file per screen under pages/, on top of the logic layer. + pages/page.cpp + pages/ui-kit.cpp + pages/dashboard-page.cpp + pages/browse-page.cpp + pages/cleanup-page.cpp + pages/history-page.cpp + pages/logs-page.cpp + pages/plugins-page.cpp resources/resources.qrc ) @@ -45,11 +57,21 @@ set(HEADERS include/package-model.h include/update-manager.h include/app-logging.h + include/workers.h + include/app-core.h + pages/page.h + pages/ui-kit.h + pages/dashboard-page.h + pages/browse-page.h + pages/cleanup-page.h + pages/history-page.h + pages/logs-page.h + pages/plugins-page.h ) add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) -target_include_directories(${PROJECT_NAME} PRIVATE include) +target_include_directories(${PROJECT_NAME} PRIVATE include pages) target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Widgets Qt6::Network) target_compile_definitions(${PROJECT_NAME} PRIVATE FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}") @@ -134,6 +156,21 @@ add_test(NAME aur-manager-test COMMAND aur-manager-test) # UpdateManager::isNewerVersion is pure logic, but the file also pulls in Qt # Network, so the test links Core + Network (no display needed). +# The logic layer runs without a display: it is exercised on its own (no +# QtWidgets), which is exactly the guarantee the view/core split is for. +# The Q_OBJECT headers are listed explicitly so AUTOMOC generates their moc +# file for this target (same reason as update-manager-test below). +add_executable(app-core-test tests/app-core.test.cpp + src/app-core.cpp src/workers.cpp src/pacman-manager.cpp + src/plugin-manager.cpp src/history-manager.cpp src/update-manager.cpp + src/app-logging.cpp + include/app-core.h include/workers.h include/update-manager.h) +target_include_directories(app-core-test PRIVATE include) +target_link_libraries(app-core-test PRIVATE Qt6::Core Qt6::Network) +target_compile_definitions(app-core-test PRIVATE + FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}") +add_test(NAME app-core-test COMMAND app-core-test) + add_executable(update-manager-test tests/update-manager.test.cpp src/update-manager.cpp src/app-logging.cpp include/update-manager.h) target_include_directories(update-manager-test PRIVATE include) diff --git a/include/app-core.h b/include/app-core.h new file mode 100644 index 0000000..e45325b --- /dev/null +++ b/include/app-core.h @@ -0,0 +1,242 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +#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; + +// 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; } + std::vector 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& installedPackages() const { return m_installedPackages; } + const std::vector& updatePackages() const { return m_updatePackages; } + const std::vector& 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); + StartResult update(const PackageInfo& package); + StartResult updateAll(); + StartResult refresh(); + StartResult cleanCaches(); + // 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& 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; + // 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(); + + // ---- Application self-update ---- + bool shouldCheckForAppUpdate() const; + void checkForAppUpdate(); + 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 results); + void searchFinished(std::vector results); + // A listing finished; the view renders it and keeps what it needs. + void listFinished(AppCore::ListMode mode, std::vector 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(); + 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 packages; + QString description; + std::string pluginId; + }; + + StartResult startRequest(const Request& request); + StartResult startList(ListMode mode); + StartResult startSearch(const QString& query); + StartResult startAction(InstallWorker* worker, const Request& request, + const std::vector& providers); + void finishAction(const Request& request, + const std::vector& 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& 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& providers) const; + // Per-operation mode: the password is single-use, drop it after a command. + void clearCredentialsAfterUse(); + + PluginManager* m_plugins = 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 m_installedPackages; + std::vector m_updatePackages; + std::vector m_cleanupCandidates; + QHash 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 m_queuedLists; + InstallWorker* m_action = nullptr; + + std::optional m_pending; + + // Bulk removal state. + std::vector>> m_pendingRemovals; + bool m_removalSuccess = true; + QString m_cleanupRemovalDescription; + + bool m_busy = false; +}; + +Q_DECLARE_METATYPE(AppCore::ListMode) diff --git a/include/main-window.h b/include/main-window.h index 0f7e4f7..a33f370 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -1,111 +1,42 @@ #pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include -#include -#include #include +#include "app-core.h" #include "package-manager.h" -#include "pacman-manager.h" -#include "plugin-manager.h" -#include "history-manager.h" -#include "update-manager.h" -class QStackedWidget; -class QTableWidget; -class QTextEdit; -class QListWidget; -class QListWidgetItem; +class QAction; class QButtonGroup; class QFrame; -class QAction; +class QLabel; +class QProgressBar; +class QPushButton; +class QStackedWidget; class QSystemTrayIcon; +class QWidget; -// 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& providers, const std::string& query); - void run() override; -signals: - void finished(std::vector 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 results); -private: - std::vector 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& providers, Mode mode); - void run() override; -signals: - void finished(std::vector results); -private: - std::vector 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, - 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& packages); - InstallWorker(const std::vector& 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 m_providers; - Op m_op; - std::string m_package; - std::vector m_packages; - PacmanManager* m_pacman = nullptr; // lock recovery only - PacmanManager::LockHolder m_lockHolder; -}; +class BrowsePage; +class CleanupPage; +class DashboardPage; +class HistoryPage; +class LogsPage; +class Page; +class PluginsPage; +// 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: @@ -113,46 +44,33 @@ public: ~MainWindow(); private slots: - void onSearch(); - void onInstall(); - void onRemove(); - void onUpdate(); - void onUpdateAll(); - void onRefresh(); - void onSearchFinished(std::vector results); - void onSearchChunk(std::vector results); - void onListFinished(std::vector results); - void onInstallProgress(int percent); - void onPackageSelected(int row); void onNavChanged(int id); - void onClearHistory(); - void onRefreshLogs(); - void onExportHistory(); - void onExportPackageList(); - void onLogsFilterChanged(); - void onPreviewUpdates(); + void onRefresh(); + void onUpdateAll(); void onTrayActivated(QSystemTrayIcon::ActivationReason reason); - void onHistoryFilterChanged(); - void onInstalledFilterChanged(const QString& text); - void onRecentActivityClicked(QListWidgetItem* item); - void onPluginTableSelected(int row); - void onTogglePlugin(); - void onRescanPlugins(); - void onInstallPluginTool(); void onCheckForUpdates(); - void onUpdateCheckFinished(bool hasUpdate, const QString& latestVersion, - const QString& errorMessage); - void onSelfUpdateFinished(bool success, const QString& message); - void onCleanupScan(); - void onCleanupListFinished(std::vector results); - void onCleanupSelectionChanged(int row); - void onRemoveCleanupOrphans(); - void onRemoveCleanupSelection(); - void onCleanCaches(); + + // ---- 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 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: - enum BrowseMode { ModeSearch, ModeInstalled, ModeUpdates }; - // 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. @@ -167,100 +85,41 @@ private: NavPlugins, }; - // Indices in the stacked widget. Search / Installed / Updates share the - // browse page, so these deliberately differ from the nav ids. - enum StackedPage { - PageDashboard = 0, - PageBrowse, - PageHistory, - PageLogs, - PagePlugins, - PageCleanup, - }; - - // When the sudo password is requested: once per session (at launch) or - // before every privileged operation. - enum class CredentialMode { AtLaunch, EachTime }; - - void applyCredentialMode(CredentialMode mode); - bool ensureCredentials(const std::vector& providers); - void clearCredentialsAfterUse(); - - // Manager owning a package, based on its provider tag; falls back to the - // first available provider when the tag is unknown or empty. - IPackageManager* providerFor(const std::string& id) const; - - // Show the provider's last error in a dialog when one is available, so a - // failed operation explains itself instead of failing silently. - // Returns true when the error was a locked pacman DB (caller may offer - // a retry once the lock is gone). - bool showProviderError(const QString& title, IPackageManager* provider); - - // Names the process holding pacman's database and offers to close it — or to - // drop a stale lock — before re-running the pending action. Returns true when - // it handled the failure, so the caller skips its own reporting. - bool handleDatabaseLock(const QString& title); - void startLockRecovery(const PacmanManager::LockHolder& holder); - // Re-runs the action that failed, when it can still run. - void retryPendingAction(); - - // Re-runs the given privileged action. Used by the "Réessayer" button - // on db-lock errors: the lock (other manager / stale db.lck) is often - // gone by the time the user retries. - void retryPrivilegedAction(const QString& action); - - QString m_pendingRetryAction; - void setupUI(); void setupSidebar(); void setupHeader(); - void setupDashboardPage(); - void setupBrowsePage(); - void setupHistoryPage(); - void setupLogsPage(); - void setupPluginsPage(); - void setupCleanupPage(); + 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); + // Screen currently displayed, and the screens themselves. + Page* currentPage() const; void updatePageTitle(); void updateStatusBar(); - void refreshDashboard(); - void refreshRecentActivity(); // 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); - void refreshPluginsTable(); - void updatePackageInfo(const PackageInfo& pkg); - std::string richDetails(const PackageInfo& pkg); - void resetDetailsPanel(); - void setBrowseMode(BrowseMode mode); - void performInstall(const std::string& package); - void performRemove(const std::string& package); - void populatePackageTable(const std::vector& results); - void appendPackageRows(const std::vector& results); - void addPackageRow(int row, const PackageInfo& pkg); - void setBusy(bool busy); - // Single privileged op at a time (pacman DB lock). Returns false + a - // status message when an operation already runs. - bool tryAcquireOp(); - void reloadCurrentView(); - void loadInstalled(); - void loadUpdates(); - void refreshHistoryTable(); - void loadCleanup(); - void populateCleanupTable(const std::vector& candidates); - // Runs a bulk removal of the given candidates, one provider at a time, and - // refreshes the cleanup list when the last group is done. - void removeCleanupPackages(const std::vector& packages, - const QString& description); - void startNextCleanupRemoval(); - void loadLogs(); - void applyLogsFilter(); - void setupTray(); - void setupShortcuts(); void notifyUpdatesAvailable(int count); - QFrame* makeCard(); - QFrame* makeStatCard(const QString& iconName, const QString& title, - const QString& accent, QLabel** valueOut); + // 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); + + // 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; @@ -273,54 +132,22 @@ private: QWidget* m_headerWidget = nullptr; QLabel* m_headerTitle = nullptr; QLabel* m_headerSubtitle = nullptr; + QPushButton* m_headerUpdateAllButton = nullptr; - // Pages + // Screens, stacked in sidebar order. QStackedWidget* m_pages = nullptr; + QHash m_pageById; // "search" -> screen + QHash 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; - // Dashboard - QLabel* m_statInstalled = nullptr; - QLabel* m_statUpdates = nullptr; - QLabel* m_statHistory = nullptr; - QLabel* m_statManager = nullptr; - QListWidget* m_recentList = nullptr; - - // Browse page - QWidget* m_searchRowWidget = nullptr; - QLineEdit* m_searchBar = nullptr; - QPushButton* m_searchButton = nullptr; - QWidget* m_filterRowWidget = nullptr; - QLineEdit* m_filterBar = nullptr; - QLabel* m_resultCount = nullptr; - QPushButton* m_installButton = nullptr; - QPushButton* m_removeButton = nullptr; - QPushButton* m_updateButton = nullptr; - QPushButton* m_updateAllButton = nullptr; - QProgressBar* m_progressBar = nullptr; // Small indeterminate bar anchored in the status bar, shown at the bottom // of the window while any install/search runs. QProgressBar* m_installProgressBar = nullptr; - QTableWidget* m_packageTable = nullptr; - // Listing + empty-state hint, swapped depending on the row count. - QStackedWidget* m_packageTableStack = nullptr; - QLabel* m_packageName = nullptr; - QLabel* m_packageVersion = nullptr; - QLabel* m_packageRepo = nullptr; - QLabel* m_packageSize = nullptr; - QLabel* m_packageProvider = nullptr; - QLabel* m_packageDescription = nullptr; - // Rich pacman details are cached per package so re-selecting a row (or - // arrowing through the list) does not re-spawn pacman queries. - QHash m_detailsCache; - - // History page - QTableWidget* m_historyTable = nullptr; - QComboBox* m_historyFilter = nullptr; - QLabel* m_historyCount = nullptr; - - // Logs page - QTextEdit* m_logsText = nullptr; - QLineEdit* m_logsFilter = nullptr; - QString m_logsRaw; // Tray (optional: hidden when the desktop has no system tray) QSystemTrayIcon* m_tray = nullptr; @@ -328,44 +155,7 @@ private: // dashboard refreshes do not spam the user. int m_lastNotifiedUpdates = -1; - // Cleanup page - QTableWidget* m_cleanupTable = nullptr; - QStackedWidget* m_cleanupTableStack = nullptr; - QLabel* m_cleanupCount = nullptr; - QPushButton* m_cleanupRemoveOrphansButton = nullptr; - QPushButton* m_cleanupRemoveSelectionButton = nullptr; - QPushButton* m_cleanupCacheButton = nullptr; - std::vector m_cleanupCandidates; - // Providers left to process for the bulk removal in progress, with the - // packages each of them owns. They run one after another because pacman - // locks its database. - std::vector>> m_pendingRemovals; - - // Plugins page - QTableWidget* m_pluginTable = nullptr; - QPushButton* m_pluginToggleButton = nullptr; - QPushButton* m_pluginInstallButton = nullptr; - QLabel* m_pluginDescription = nullptr; - std::string m_selectedPluginId; - - // Backend - PacmanManager* m_pacman = nullptr; // non-owning, used for sudo credentials/logs - PluginManager* m_pluginManager = nullptr; // owns every provider - HistoryManager* m_historyManager = nullptr; - UpdateManager* m_updateManager = nullptr; // checks Gitea releases (owned) - BrowseMode m_browseMode = ModeSearch; - // True while a privileged op (or blocking load) runs; guards the pacman - // DB lock against concurrent operations from double-clicks. - bool m_busy = false; - - // Settings - QSettings m_settings; - CredentialMode m_credentialMode = CredentialMode::EachTime; + // Menu QAction* m_credLaunchAction = nullptr; QAction* m_credEachTimeAction = nullptr; - - std::vector m_currentResults; - std::vector m_installedPackages; - PackageInfo m_selectedPackage; - std::string m_pendingSelect; // package to auto-select after the installed list loads }; diff --git a/include/workers.h b/include/workers.h new file mode 100644 index 0000000..a4cf868 --- /dev/null +++ b/include/workers.h @@ -0,0 +1,86 @@ +#pragma once + +#include + +#include +#include + +#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& providers, const std::string& query); + void run() override; +signals: + void finished(std::vector 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 results); +private: + std::vector 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& providers, Mode mode); + void run() override; +signals: + void finished(std::vector results); +private: + std::vector 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, + 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& packages); + InstallWorker(const std::vector& 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 m_providers; + Op m_op; + std::string m_package; + std::vector m_packages; + PacmanManager* m_pacman = nullptr; // lock recovery only + PacmanManager::LockHolder m_lockHolder; +}; diff --git a/pages/browse-page.cpp b/pages/browse-page.cpp new file mode 100644 index 0000000..a190d78 --- /dev/null +++ b/pages/browse-page.cpp @@ -0,0 +1,508 @@ +#include "browse-page.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ui-kit.h" + +BrowsePage::BrowsePage(AppCore* core, QWidget* parent) : Page(core, parent) { + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(24, 20, 24, 20); + layout->setSpacing(12); + + // Search row (search mode only) + m_searchRow = new QWidget(); + QHBoxLayout* searchRow = new QHBoxLayout(m_searchRow); + searchRow->setContentsMargins(0, 0, 0, 0); + searchRow->setSpacing(10); + + m_searchBar = new QLineEdit(); + m_searchBar->setPlaceholderText("Rechercher un paquet (ex : firefox)..."); + m_searchBar->setMinimumHeight(40); + m_searchBar->addAction(ui::icon("search"), QLineEdit::LeadingPosition); + connect(m_searchBar, &QLineEdit::returnPressed, this, &BrowsePage::onSearch); + searchRow->addWidget(m_searchBar, 1); + + m_searchButton = new QPushButton("Rechercher"); + m_searchButton->setProperty("variant", "primary"); + m_searchButton->setMinimumHeight(40); + m_searchButton->setMinimumWidth(130); + connect(m_searchButton, &QPushButton::clicked, this, &BrowsePage::onSearch); + searchRow->addWidget(m_searchButton); + + layout->addWidget(m_searchRow); + + // Filter row (installed mode only) + m_filterRow = new QWidget(); + QHBoxLayout* filterRow = new QHBoxLayout(m_filterRow); + filterRow->setContentsMargins(0, 0, 0, 0); + filterRow->setSpacing(10); + + m_filterBar = new QLineEdit(); + m_filterBar->setPlaceholderText("Filtrer par nom..."); + m_filterBar->setMinimumHeight(36); + m_filterBar->addAction(ui::icon("filter"), QLineEdit::LeadingPosition); + m_filterBar->setClearButtonEnabled(true); + connect(m_filterBar, &QLineEdit::textChanged, this, &BrowsePage::onFilterChanged); + filterRow->addWidget(m_filterBar, 1); + + QLabel* filterHint = new QLabel("Filtre local, instantané"); + filterHint->setStyleSheet("font-size: 12px; color: #7a8299;"); + filterRow->addWidget(filterHint); + + m_filterRow->setVisible(false); + layout->addWidget(m_filterRow); + + // Thin progress bar, shown while the core works on a listing. + m_progressBar = new QProgressBar(); + m_progressBar->setVisible(false); + m_progressBar->setFixedHeight(6); + m_progressBar->setTextVisible(false); + layout->addWidget(m_progressBar); + + // Action toolbar + QHBoxLayout* actionBar = new QHBoxLayout(); + actionBar->setSpacing(8); + + m_installButton = new QPushButton("Installer"); + m_installButton->setProperty("variant", "success"); + m_installButton->setIcon(ui::icon("package")); + m_installButton->setEnabled(false); + connect(m_installButton, &QPushButton::clicked, this, [this, core] { + if (m_selected.name.empty()) return; + m_pendingSelect = QString::fromStdString(m_selected.name); + start(core->install(m_selected), tr("Installation")); + }); + actionBar->addWidget(m_installButton); + + m_removeButton = new QPushButton("Supprimer"); + m_removeButton->setProperty("variant", "danger"); + m_removeButton->setIcon(ui::icon("trash")); + m_removeButton->setEnabled(false); + connect(m_removeButton, &QPushButton::clicked, this, [this, core] { + if (m_selected.name.empty()) return; + m_pendingSelect = QString::fromStdString(m_selected.name); + start(core->remove(m_selected), tr("Suppression")); + }); + actionBar->addWidget(m_removeButton); + + m_updateButton = new QPushButton("Mettre à jour"); + m_updateButton->setProperty("variant", "warning"); + m_updateButton->setIcon(ui::icon("refresh")); + m_updateButton->setEnabled(false); + connect(m_updateButton, &QPushButton::clicked, this, [this, core] { + if (m_selected.name.empty()) return; + m_pendingSelect = QString::fromStdString(m_selected.name); + start(core->update(m_selected), tr("Mise à jour")); + }); + actionBar->addWidget(m_updateButton); + + m_updateAllButton = new QPushButton("Tout mettre à jour"); + m_updateAllButton->setProperty("variant", "info"); + m_updateAllButton->setIcon(ui::icon("arrow-up")); + m_updateAllButton->setEnabled(false); + connect(m_updateAllButton, &QPushButton::clicked, this, [this, core] { + start(core->updateAll(), tr("Mise à jour globale")); + }); + actionBar->addWidget(m_updateAllButton); + + QPushButton* exportButton = new QPushButton("Exporter"); + exportButton->setToolTip("Exporter la liste affichée en CSV"); + connect(exportButton, &QPushButton::clicked, this, &BrowsePage::exportCsv); + actionBar->addWidget(exportButton); + + actionBar->addStretch(); + + m_resultCount = ui::countLabel(); + actionBar->addWidget(m_resultCount); + + layout->addLayout(actionBar); + + // Splitter: package table | details + QSplitter* splitter = new QSplitter(Qt::Horizontal); + splitter->setHandleWidth(10); + + QFrame* listCard = ui::card(); + QVBoxLayout* listLayout = new QVBoxLayout(listCard); + listLayout->setContentsMargins(8, 8, 8, 8); + listLayout->setSpacing(6); + + QLabel* listHeader = new QLabel("PAQUETS"); + listHeader->setObjectName("cardTitle"); + listLayout->addWidget(listHeader); + + m_table = ui::table({"Nom", "Version", "Dépôt", "Fournisseur", "Statut"}); + connect(m_table, &QTableWidget::currentCellChanged, this, + [this](int currentRow, int, int, int) { onPackageSelected(currentRow); }); + + m_tableStack = ui::withEmptyState( + m_table, + "Aucun paquet à afficher.\nLancez une recherche ou ouvrez la liste des " + "paquets installés."); + listLayout->addWidget(m_tableStack); + splitter->addWidget(listCard); + + QFrame* detailsCard = ui::card(); + QVBoxLayout* detailsLayout = new QVBoxLayout(detailsCard); + detailsLayout->setContentsMargins(20, 18, 20, 18); + detailsLayout->setSpacing(10); + + m_pkgName = new QLabel("Sélectionnez un paquet"); + m_pkgName->setWordWrap(true); + m_pkgName->setStyleSheet( + "font-size: 22px; font-weight: 700; color: #e8edf9; background: transparent;"); + detailsLayout->addWidget(m_pkgName); + + m_pkgVersion = new QLabel(""); + m_pkgVersion->setStyleSheet("font-size: 13px; color: #7a8299; background: transparent;"); + detailsLayout->addWidget(m_pkgVersion); + + QHBoxLayout* metaRow = new QHBoxLayout(); + metaRow->setSpacing(8); + + auto makeMetaBadge = [](QLabel** out) { + QLabel* label = new QLabel("—"); + label->setStyleSheet( + "background: #1c2434; color: #7a8299; border-radius: 10px;" + "padding: 3px 12px; font-size: 12px;"); + *out = label; + return label; + }; + metaRow->addWidget(makeMetaBadge(&m_pkgRepo)); + metaRow->addWidget(makeMetaBadge(&m_pkgSize)); + metaRow->addWidget(makeMetaBadge(&m_pkgProvider)); + metaRow->addStretch(); + detailsLayout->addLayout(metaRow); + + QFrame* separator = new QFrame(); + separator->setFrameShape(QFrame::HLine); + separator->setStyleSheet( + "color: #232b3a; background: #232b3a; max-height: 1px; border: none;"); + detailsLayout->addWidget(separator); + + m_pkgDescription = new QLabel(""); + m_pkgDescription->setWordWrap(true); + m_pkgDescription->setAlignment(Qt::AlignTop | Qt::AlignLeft); + m_pkgDescription->setStyleSheet( + "font-size: 14px; color: #c8d3f5; background: transparent;"); + detailsLayout->addWidget(m_pkgDescription, 1); + + detailsLayout->addStretch(); + splitter->addWidget(detailsCard); + + splitter->setSizes({560, 420}); + layout->addWidget(splitter, 1); + + // ---- Core wiring ---- + connect(core, &AppCore::searchChunk, this, + [this](std::vector results) { appendRows(results); }); + connect(core, &AppCore::searchFinished, this, + [this](std::vector results) { populateTable(results); }); + connect(core, &AppCore::listFinished, this, + [this](AppCore::ListMode mode, std::vector results) { + if (mode == AppCore::ListMode::Installed) { + m_installed = results; + if (m_mode == Mode::Installed) onFilterChanged(m_filterBar->text()); + } else if (mode == AppCore::ListMode::Updates) { + if (m_mode == Mode::Updates) populateTable(results); + } + }); + connect(core, &AppCore::busyChanged, this, [this](bool busy) { + m_progressBar->setVisible(busy); + if (!busy) return; + // Start indeterminate; only the status-bar bar turns determinate once + // the tool reports a real percentage. + m_progressBar->setRange(0, 0); + m_progressBar->setValue(0); + }); + connect(core, &AppCore::actionFinished, this, + [this](const QString& action, const QString&, bool success, const QString&, + bool) { + // The installed state changed: show the fresh state of what the + // user is looking at, but only when they are looking at it. + if (!success || !isVisible()) return; + if (action == QLatin1String("install") || action == QLatin1String("remove") + || action == QLatin1String("update") + || action == QLatin1String("update-all") + || action == QLatin1String("refresh")) { + reloadCurrentView(); + } + }); +} + +QString BrowsePage::navTitle() const { + if (m_mode == Mode::Installed) return QStringLiteral("Paquets installés"); + if (m_mode == Mode::Updates) return QStringLiteral("Mises à jour disponibles"); + return QStringLiteral("Recherche"); +} + +QString BrowsePage::navSubtitle() const { + if (m_mode == Mode::Installed) return QStringLiteral("Parcourez les paquets de votre système"); + if (m_mode == Mode::Updates) return QStringLiteral("Maintenez votre système à jour"); + return QStringLiteral("Trouvez et installez des paquets"); +} + +void BrowsePage::refresh() { + reloadCurrentView(); +} + +void BrowsePage::showSearch() { + setMode(Mode::Search); + m_searchBar->setFocus(); +} + +void BrowsePage::focusSearch() { + setMode(Mode::Search); + m_searchBar->setFocus(); + m_searchBar->selectAll(); +} + +void BrowsePage::showInstalled(const QString& select) { + setMode(Mode::Installed); + if (!select.isEmpty()) m_pendingSelect = select; + start(core()->loadInstalled(), tr("Paquets installés")); +} + +void BrowsePage::showUpdates() { + setMode(Mode::Updates); + start(core()->loadUpdates(), tr("Mises à jour")); +} + +void BrowsePage::setMode(Mode mode) { + m_mode = mode; + m_searchRow->setVisible(mode == Mode::Search); + m_filterRow->setVisible(mode == Mode::Installed); + m_installButton->setVisible(mode == Mode::Search); + + // Clear any stale selection and reset the details panel + m_table->clearSelection(); + resetDetails(); +} + +void BrowsePage::reloadCurrentView() { + if (m_mode == Mode::Installed) { + start(core()->loadInstalled(), tr("Paquets installés")); + } else if (m_mode == Mode::Updates) { + start(core()->loadUpdates(), tr("Mises à jour")); + } else if (!m_searchBar->text().trimmed().isEmpty()) { + onSearch(); + } +} + +void BrowsePage::onSearch() { + if (m_searchBar->text().trimmed().isEmpty()) { + // Refocus the field instead of interrupting with a dialog. + m_searchBar->setFocus(); + emit message(tr("Entrez un terme de recherche.")); + return; + } + + m_table->setRowCount(0); + m_results.clear(); + start(core()->search(m_searchBar->text()), tr("Recherche")); +} + +void BrowsePage::onFilterChanged(const QString& text) { + if (m_mode != Mode::Installed) return; + + std::vector filtered; + if (text.isEmpty()) { + filtered = m_installed; + } else { + const QString needle = text.toLower(); + for (const auto& pkg : m_installed) { + if (QString::fromStdString(pkg.name).toLower().contains(needle)) { + filtered.push_back(pkg); + } + } + } + populateTable(filtered); +} + +void BrowsePage::populateTable(const std::vector& packages) { + m_results = packages; + ui::showEmptyState(m_tableStack, packages.empty()); + { + ui::TableFillBatch batch(m_table); + m_table->setRowCount(0); + m_table->setRowCount(static_cast(packages.size())); + for (int i = 0; i < static_cast(packages.size()); ++i) { + addRow(i, packages[i]); + } + } + + m_resultCount->setText(QString("%1 paquet(s)").arg(packages.size())); + + if (packages.empty()) { + resetDetails(); + return; + } + + // If we came here for a specific package (dashboard history, or the one an + // operation just touched), select it. + if (!m_pendingSelect.isEmpty()) { + const QString target = m_pendingSelect; + m_pendingSelect.clear(); + for (int i = 0; i < static_cast(m_results.size()); ++i) { + if (QString::fromStdString(m_results[i].name) == target) { + m_table->selectRow(i); + onPackageSelected(i); // update the details panel immediately + return; + } + } + } + + m_table->selectRow(0); +} + +// Appends an incoming search chunk to the rows already displayed, so the first +// matches appear while the remaining providers are still searching. +void BrowsePage::appendRows(const std::vector& packages) { + const int startRow = static_cast(m_results.size()); + m_results.insert(m_results.end(), packages.begin(), packages.end()); + + ui::TableFillBatch batch(m_table); + m_table->setRowCount(static_cast(m_results.size())); + for (int i = 0; i < static_cast(packages.size()); ++i) { + addRow(startRow + i, packages[i]); + } + ui::showEmptyState(m_tableStack, m_results.empty()); + m_resultCount->setText(QString("%1 paquet(s)").arg(m_results.size())); +} + +void BrowsePage::addRow(int row, const PackageInfo& pkg) { + QFont nameFont; + nameFont.setWeight(QFont::DemiBold); + + QTableWidgetItem* nameItem = new QTableWidgetItem(QString::fromStdString(pkg.name)); + nameItem->setFont(nameFont); + m_table->setItem(row, 0, nameItem); + + m_table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(pkg.version))); + m_table->setItem(row, 2, + new QTableWidgetItem(pkg.repository.empty() + ? QStringLiteral("—") + : QString::fromStdString(pkg.repository))); + + QTableWidgetItem* providerItem = + new QTableWidgetItem(ui::providersLabel(core()->plugins(), pkg)); + providerItem->setForeground(QColor("#7a8299")); + m_table->setItem(row, 3, providerItem); + + QTableWidgetItem* statusItem = new QTableWidgetItem(ui::packageStatusText(pkg)); + if (pkg.installed && pkg.updateAvailable) { + statusItem->setForeground(QColor("#e0af68")); + statusItem->setIcon(ui::icon("arrow-up")); + } else if (pkg.installed) { + statusItem->setForeground(QColor("#3fb950")); + statusItem->setIcon(ui::icon("check")); + } else { + statusItem->setIcon(ui::icon("package")); + } + m_table->setItem(row, 4, statusItem); +} + +void BrowsePage::onPackageSelected(int row) { + if (row < 0 || row >= static_cast(m_results.size())) { + resetDetails(); + return; + } + + m_selected = m_results[row]; + updateDetails(m_selected); + + IPackageManager* provider = + core()->providerFor(QString::fromStdString(m_selected.provider)); + m_installButton->setEnabled(provider && provider->canInstall() + && !m_selected.installed); + m_removeButton->setEnabled(provider && provider->canRemove() && m_selected.installed); + m_updateButton->setEnabled(provider && provider->canUpdate() + && m_selected.updateAvailable); +} + +void BrowsePage::updateDetails(const PackageInfo& pkg) { + m_pkgName->setText(QString::fromStdString(pkg.name)); + + QString versionText = QString("Version : %1").arg(QString::fromStdString(pkg.version)); + if (pkg.updateAvailable) versionText += " (mise à jour disponible)"; + m_pkgVersion->setText(versionText); + + m_pkgRepo->setText(pkg.repository.empty() + ? "Dépôt : —" + : QString("Dépôt : %1").arg(QString::fromStdString(pkg.repository))); + m_pkgSize->setText(pkg.size.empty() + ? "Taille : —" + : QString("Taille : %1").arg(QString::fromStdString(pkg.size))); + m_pkgProvider->setText( + QString("Fournisseur : %1").arg(ui::providersLabel(core()->plugins(), pkg))); + + // Rich details (dependencies, required-by, install date, update size): the + // core queries pacman on demand and caches the answer, so selecting a row + // stays instant even when pacman is slow. + QString details = QString::fromStdString(pkg.description); + const QString rich = core()->packageDetails(pkg); + if (!rich.isEmpty()) { + if (!details.isEmpty()) details += "\n\n"; + details += rich; + } + m_pkgDescription->setText(details); +} + +void BrowsePage::resetDetails() { + m_selected = PackageInfo{}; + m_pkgName->setText("Sélectionnez un paquet"); + m_pkgVersion->setText(""); + m_pkgRepo->setText("—"); + m_pkgSize->setText("—"); + m_pkgProvider->setText("—"); + m_pkgDescription->setText(""); + m_installButton->setEnabled(false); + m_removeButton->setEnabled(false); + m_updateButton->setEnabled(false); +} + +void BrowsePage::exportCsv() { + if (m_results.empty()) { + emit message(tr("Aucune liste à exporter.")); + return; + } + + const QString path = QFileDialog::getSaveFileName( + this, "Exporter la liste des paquets", + QDir::homePath() + "/pacmanager-paquets.csv", "CSV (*.csv)"); + if (path.isEmpty()) return; + + QFile file(path); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { + QMessageBox::warning(this, "Export", + QString("Impossible d'écrire dans %1").arg(path)); + return; + } + QTextStream out(&file); + out << "Nom;Version;Depot;Fournisseur;Statut\n"; + for (const auto& pkg : m_results) { + out << ui::csvField(QString::fromStdString(pkg.name)) << ';' + << ui::csvField(QString::fromStdString(pkg.version)) << ';' + << ui::csvField(QString::fromStdString(pkg.repository)) << ';' + << ui::csvField(ui::providersLabel(core()->plugins(), pkg)) << ';' + << ui::csvField(ui::packageStatusText(pkg)) << '\n'; + } + emit message(QString("%1 paquet(s) exporté(s) vers %2") + .arg(m_results.size()) + .arg(path)); +} diff --git a/pages/browse-page.h b/pages/browse-page.h new file mode 100644 index 0000000..0870aae --- /dev/null +++ b/pages/browse-page.h @@ -0,0 +1,85 @@ +#pragma once + +#include + +#include "page.h" + +class QLabel; +class QLineEdit; +class QProgressBar; +class QPushButton; +class QStackedWidget; +class QTableWidget; + +// The browsing screen. Search, installed and updates share this page because +// they are the same table with a different query behind it; the sidebar exposes +// three entries, all landing here with a different mode. +class BrowsePage : public Page { + Q_OBJECT +public: + enum class Mode { Search, Installed, Updates }; + + explicit BrowsePage(AppCore* core, QWidget* parent = nullptr); + + QString navTitle() const override; + QString navSubtitle() const override; + void refresh() override; + + // Entry points used by the sidebar, the dashboard shortcuts and the menu. + void showSearch(); + void showInstalled(const QString& select = QString()); + void showUpdates(); + // Package to select once the next listing arrives: lets the frame open a + // package from the dashboard without loading the list twice. + void selectOnNextLoad(const QString& name) { m_pendingSelect = name; } + // Puts the caret in the search field (Ctrl+F), selecting the current term. + void focusSearch(); + + int resultCount() const { return static_cast(m_results.size()); } + // Exports the displayed list to a CSV file (the file dialog is the frame's + // business, the content is this page's). + void exportCsv(); + +private: + void setMode(Mode mode); + void reloadCurrentView(); + void onSearch(); + void onPackageSelected(int row); + void onFilterChanged(const QString& text); + void populateTable(const std::vector& packages); + void appendRows(const std::vector& packages); + void addRow(int row, const PackageInfo& pkg); + void updateDetails(const PackageInfo& pkg); + void resetDetails(); + + Mode m_mode = Mode::Search; + + // Everything the current query returned, and the last installed listing + // kept aside for the instant local filter. + std::vector m_results; + std::vector m_installed; + PackageInfo m_selected; + // Package to select once the next listing arrives (after a click on the + // dashboard history, or after an operation). + QString m_pendingSelect; + + QWidget* m_searchRow = nullptr; + QLineEdit* m_searchBar = nullptr; + QPushButton* m_searchButton = nullptr; + QWidget* m_filterRow = nullptr; + QLineEdit* m_filterBar = nullptr; + QLabel* m_resultCount = nullptr; + QPushButton* m_installButton = nullptr; + QPushButton* m_removeButton = nullptr; + QPushButton* m_updateButton = nullptr; + QPushButton* m_updateAllButton = nullptr; + QProgressBar* m_progressBar = nullptr; + QTableWidget* m_table = nullptr; + QStackedWidget* m_tableStack = nullptr; + QLabel* m_pkgName = nullptr; + QLabel* m_pkgVersion = nullptr; + QLabel* m_pkgRepo = nullptr; + QLabel* m_pkgSize = nullptr; + QLabel* m_pkgProvider = nullptr; + QLabel* m_pkgDescription = nullptr; +}; diff --git a/pages/cleanup-page.cpp b/pages/cleanup-page.cpp new file mode 100644 index 0000000..b83f7a2 --- /dev/null +++ b/pages/cleanup-page.cpp @@ -0,0 +1,234 @@ +#include "cleanup-page.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ui-kit.h" + +CleanupPage::CleanupPage(AppCore* core, QWidget* parent) : Page(core, parent) { + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(24, 20, 24, 20); + layout->setSpacing(12); + + QFrame* hintCard = ui::card(); + QVBoxLayout* hintLayout = new QVBoxLayout(hintCard); + hintLayout->setContentsMargins(18, 16, 18, 16); + hintLayout->setSpacing(4); + + QLabel* hintTitle = new QLabel("PAQUETS INUTILISÉS ET LEGACY"); + hintTitle->setObjectName("cardTitle"); + hintLayout->addWidget(hintTitle); + + QLabel* hint = new QLabel( + "Les orphelins ont été installés comme dépendances et ne sont " + "plus requis par aucun paquet : ils peuvent être supprimés sans risque. " + "Les paquets étrangers viennent de l'AUR ou d'une compilation " + "manuelle : vérifiez-les un par un avant de les supprimer."); + hint->setTextFormat(Qt::RichText); + hint->setWordWrap(true); + hint->setStyleSheet("font-size: 12px; color: #7a8299;"); + hintLayout->addWidget(hint); + + layout->addWidget(hintCard); + + m_table = ui::table({"Paquet", "Version", "Type", "Fournisseur"}); + connect(m_table, &QTableWidget::currentCellChanged, this, + [this](int currentRow, int, int, int) { onSelectionChanged(currentRow); }); + m_tableStack = ui::withEmptyState( + m_table, + "Rien à nettoyer pour le moment.\nLancez une analyse pour vérifier."); + layout->addWidget(m_tableStack, 1); + + QHBoxLayout* buttonBar = new QHBoxLayout(); + buttonBar->setSpacing(8); + + QPushButton* scanButton = new QPushButton("Analyser"); + scanButton->setProperty("variant", "primary"); + scanButton->setIcon(ui::icon("search")); + scanButton->setToolTip("Rechercher les paquets inutilisés et legacy"); + connect(scanButton, &QPushButton::clicked, this, &CleanupPage::scan); + buttonBar->addWidget(scanButton); + + m_removeOrphansButton = new QPushButton("Supprimer les orphelins"); + m_removeOrphansButton->setProperty("variant", "danger"); + m_removeOrphansButton->setIcon(ui::icon("trash")); + m_removeOrphansButton->setEnabled(false); + m_removeOrphansButton->setToolTip( + "Supprimer tous les paquets que plus rien ne requiert"); + connect(m_removeOrphansButton, &QPushButton::clicked, this, + &CleanupPage::removeOrphans); + buttonBar->addWidget(m_removeOrphansButton); + + m_removeSelectionButton = new QPushButton("Supprimer la sélection"); + m_removeSelectionButton->setIcon(ui::icon("trash")); + m_removeSelectionButton->setEnabled(false); + connect(m_removeSelectionButton, &QPushButton::clicked, this, + &CleanupPage::removeSelection); + buttonBar->addWidget(m_removeSelectionButton); + + m_cacheButton = new QPushButton("Vider les caches"); + m_cacheButton->setProperty("variant", "warning"); + m_cacheButton->setIcon(ui::icon("broom")); + m_cacheButton->setToolTip( + "Purger le cache de paquets (paccache / pacman -Sc) et les runtimes " + "Flatpak inutilisés"); + connect(m_cacheButton, &QPushButton::clicked, this, &CleanupPage::cleanCaches); + buttonBar->addWidget(m_cacheButton); + + buttonBar->addStretch(); + + m_count = ui::countLabel(); + buttonBar->addWidget(m_count); + + layout->addLayout(buttonBar); + + // The candidate list arrives through listFinished, which every page shares. + connect(core, &AppCore::listFinished, this, + [this](AppCore::ListMode mode, std::vector results) { + if (mode == AppCore::ListMode::Cleanup) populate(results); + }); +} + +void CleanupPage::refresh() { + scan(); +} + +void CleanupPage::scan() { + m_table->setRowCount(0); + m_candidates.clear(); + m_removeOrphansButton->setEnabled(false); + m_removeSelectionButton->setEnabled(false); + + start(core()->loadCleanup(), tr("Nettoyage")); +} + +void CleanupPage::populate(const std::vector& candidates) { + m_candidates = candidates; + ui::showEmptyState(m_tableStack, candidates.empty()); + + QFont nameFont; + nameFont.setWeight(QFont::DemiBold); + + ui::TableFillBatch batch(m_table); + m_table->setRowCount(0); + m_table->setRowCount(static_cast(candidates.size())); + + int orphans = 0; + for (int i = 0; i < static_cast(candidates.size()); ++i) { + const PackageInfo& pkg = candidates[i]; + if (pkg.orphan) ++orphans; + + QTableWidgetItem* nameItem = new QTableWidgetItem(QString::fromStdString(pkg.name)); + nameItem->setFont(nameFont); + m_table->setItem(i, 0, nameItem); + + m_table->setItem(i, 1, new QTableWidgetItem(QString::fromStdString(pkg.version))); + + QTableWidgetItem* typeItem = + new QTableWidgetItem(QString::fromStdString(pkg.cleanupReason)); + typeItem->setForeground(QColor(pkg.orphan ? "#e0af68" : "#7a8299")); + typeItem->setIcon(ui::icon(pkg.orphan ? "alert" : "package")); + m_table->setItem(i, 2, typeItem); + + m_table->setItem(i, 3, new QTableWidgetItem(ui::providersLabel(core()->plugins(), pkg))); + } + batch.release(); + + m_count->setText(QString("%1 orphelin(s) · %2 legacy") + .arg(orphans) + .arg(static_cast(candidates.size()) - orphans)); + m_removeOrphansButton->setEnabled(orphans > 0); + m_removeOrphansButton->setText(orphans > 0 + ? QString("Supprimer les orphelins (%1)").arg(orphans) + : QString("Supprimer les orphelins")); + + if (!candidates.empty()) m_table->selectRow(0); + onSelectionChanged(m_table->currentRow()); +} + +void CleanupPage::onSelectionChanged(int row) { + if (row < 0 || row >= static_cast(m_candidates.size())) { + m_removeSelectionButton->setEnabled(false); + m_removeSelectionButton->setToolTip(QString()); + return; + } + + const PackageInfo& pkg = m_candidates[row]; + const QString name = QString::fromStdString(pkg.name); + m_removeSelectionButton->setEnabled(true); + // A legacy package is only ever removed one by one and with an explicit + // warning: nothing on the system proves it is unused. + m_removeSelectionButton->setToolTip( + pkg.orphan + ? QString("Supprimer « %1 » (orphelin)").arg(name) + : QString("Supprimer « %1 » (%2) — à vérifier : rien ne prouve " + "qu'il est inutilisé") + .arg(name, QString::fromStdString(pkg.cleanupReason))); +} + +void CleanupPage::removeOrphans() { + std::vector orphans; + for (const auto& pkg : m_candidates) { + if (pkg.orphan) orphans.push_back(pkg); + } + if (orphans.empty()) { + emit message(tr("Aucun orphelin à supprimer.")); + return; + } + removePackages(orphans, QString("%1 orphelin(s)").arg(orphans.size())); +} + +void CleanupPage::removeSelection() { + const int row = m_table->currentRow(); + if (row < 0 || row >= static_cast(m_candidates.size())) return; + + // Copied: the candidate list is rebuilt once the removal completes. + const PackageInfo pkg = m_candidates[row]; + removePackages({pkg}, QString("« %1 »").arg(QString::fromStdString(pkg.name))); +} + +void CleanupPage::removePackages(const std::vector& packages, + const QString& description) { + if (packages.empty()) { + emit message(tr("Aucun paquet sélectionné n'est supprimable.")); + return; + } + + if (QMessageBox::question(this, "Nettoyage", + QString("Supprimer %1 ?\n\nCette action est irréversible.").arg(description)) + != QMessageBox::Yes) { + return; + } + + start(core()->removePackages(packages, description), tr("Nettoyage")); +} + +void CleanupPage::cleanCaches() { + // The core owns which providers have a cache; the page only names them in + // the confirmation it shows before the purge. + QStringList names; + for (IPackageManager* pm : core()->availableProviders()) { + if (pm->canCleanCache()) names << QString::fromStdString(pm->getName()); + } + if (names.isEmpty()) { + emit message(tr("Aucun cache à nettoyer sur ce système.")); + return; + } + + if (QMessageBox::question(this, "Nettoyage", + QString("Vider les caches de %1 ?\n\npacman ne conserve que la " + "dernière version de chaque paquet téléchargé et Flatpak " + "supprime les runtimes qu'aucune application n'utilise " + "plus.").arg(names.join(", "))) != QMessageBox::Yes) { + return; + } + + start(core()->cleanCaches(), tr("Nettoyage des caches")); +} diff --git a/pages/cleanup-page.h b/pages/cleanup-page.h new file mode 100644 index 0000000..ee0a65c --- /dev/null +++ b/pages/cleanup-page.h @@ -0,0 +1,52 @@ +#pragma once + +#include + +#include + +#include "page.h" + +class QLabel; +class QPushButton; +class QStackedWidget; +class QTableWidget; + +// Nettoyage: lists what a cleanup can reclaim (orphans and legacy packages +// reported by every provider) and frees the disk space the providers hold in +// their caches. Nothing runs until the user asks for it: the candidate list is +// only built on demand, since both queries cost a pacman call. +class CleanupPage : public Page { + Q_OBJECT +public: + explicit CleanupPage(AppCore* core, QWidget* parent = nullptr); + + QString navTitle() const override { return QStringLiteral("Nettoyage"); } + QString navSubtitle() const override { + return QStringLiteral( + "Purger les paquets inutilisés ou legacy et libérer de l'espace"); + } + + void refresh() override; + +private: + void scan(); + void populate(const std::vector& candidates); + void onSelectionChanged(int row); + void removeOrphans(); + void removeSelection(); + void cleanCaches(); + // Confirms the removal, then hands the selection to the core (grouping the + // packages per provider and running the groups in sequence are core rules). + void removePackages(const std::vector& packages, + const QString& description); + + QTableWidget* m_table = nullptr; + QStackedWidget* m_tableStack = nullptr; + QLabel* m_count = nullptr; + QPushButton* m_removeOrphansButton = nullptr; + QPushButton* m_removeSelectionButton = nullptr; + QPushButton* m_cacheButton = nullptr; + // Last listing shown, kept so a row can be mapped back to its package when + // the user asks to remove it. + std::vector m_candidates; +}; diff --git a/pages/dashboard-page.cpp b/pages/dashboard-page.cpp new file mode 100644 index 0000000..c69b663 --- /dev/null +++ b/pages/dashboard-page.cpp @@ -0,0 +1,205 @@ +#include "dashboard-page.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ui-kit.h" + +DashboardPage::DashboardPage(AppCore* core, QWidget* parent) : Page(core, parent) { + setObjectName("dashboardPage"); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(24, 20, 24, 20); + layout->setSpacing(16); + + // Stat cards + QHBoxLayout* statsRow = new QHBoxLayout(); + statsRow->setSpacing(12); + statsRow->addWidget( + ui::statCard("package", "Paquets installés", "blue", &m_statInstalled)); + statsRow->addWidget( + ui::statCard("arrow-up", "Mises à jour dispo", "amber", &m_statUpdates)); + statsRow->addWidget( + ui::statCard("history", "Actions enregistrées", "cyan", &m_statHistory)); + statsRow->addWidget( + ui::statCard("tools", "Gestionnaire", "green", &m_statManager)); + layout->addLayout(statsRow); + + // Quick actions + QFrame* actionsCard = ui::card(); + QVBoxLayout* actionsLayout = new QVBoxLayout(actionsCard); + actionsLayout->setContentsMargins(18, 16, 18, 16); + actionsLayout->setSpacing(10); + + QLabel* actionsTitle = new QLabel("ACTIONS RAPIDES"); + actionsTitle->setObjectName("cardTitle"); + actionsLayout->addWidget(actionsTitle); + + QHBoxLayout* actionsRow = new QHBoxLayout(); + actionsRow->setSpacing(10); + + QPushButton* btnSearch = new QPushButton("Rechercher un paquet"); + btnSearch->setProperty("variant", "primary"); + btnSearch->setIcon(ui::icon("search")); + connect(btnSearch, &QPushButton::clicked, this, + [this] { emit goToPage("search"); }); + actionsRow->addWidget(btnSearch); + + QPushButton* btnInstalled = new QPushButton("Paquets installés"); + btnInstalled->setIcon(ui::icon("package")); + connect(btnInstalled, &QPushButton::clicked, this, + [this] { emit goToPage("installed"); }); + actionsRow->addWidget(btnInstalled); + + QPushButton* btnUpdateAll = new QPushButton("Tout mettre à jour"); + btnUpdateAll->setProperty("variant", "warning"); + btnUpdateAll->setIcon(ui::icon("arrow-up")); + connect(btnUpdateAll, &QPushButton::clicked, this, + [this, core] { start(core->updateAll(), tr("Mise à jour globale")); }); + actionsRow->addWidget(btnUpdateAll); + + QPushButton* btnCleanup = new QPushButton("Nettoyer le système"); + btnCleanup->setIcon(ui::icon("broom")); + btnCleanup->setToolTip("Purger les paquets inutilisés et vider les caches"); + connect(btnCleanup, &QPushButton::clicked, this, + [this] { emit goToPage("cleanup"); }); + actionsRow->addWidget(btnCleanup); + + QPushButton* btnRefresh = new QPushButton("Rafraîchir les sources"); + btnRefresh->setProperty("variant", "info"); + btnRefresh->setIcon(ui::icon("refresh")); + connect(btnRefresh, &QPushButton::clicked, this, + [this, core] { start(core->refresh(), tr("Rafraîchissement des sources")); }); + actionsRow->addWidget(btnRefresh); + + QPushButton* btnLogs = new QPushButton("Logs pacman"); + btnLogs->setIcon(ui::icon("logs")); + connect(btnLogs, &QPushButton::clicked, this, [this] { emit goToPage("logs"); }); + actionsRow->addWidget(btnLogs); + + actionsRow->addStretch(); + actionsLayout->addLayout(actionsRow); + layout->addWidget(actionsCard); + + // Recent activity + QFrame* recentCard = ui::card(); + QVBoxLayout* recentLayout = new QVBoxLayout(recentCard); + recentLayout->setContentsMargins(18, 16, 18, 12); + recentLayout->setSpacing(8); + + QLabel* recentTitle = new QLabel("ACTIVITÉ RÉCENTE"); + recentTitle->setObjectName("cardTitle"); + recentLayout->addWidget(recentTitle); + + m_recentList = new QListWidget(); + m_recentList->setObjectName("recentList"); + m_recentList->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + m_recentList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_recentList->setFocusPolicy(Qt::NoFocus); + connect(m_recentList, &QListWidget::itemClicked, this, + &DashboardPage::onActivityClicked); + recentLayout->addWidget(m_recentList, 1); + + layout->addWidget(recentCard, 1); + + // The figures and the activity list both come from the core. + connect(core, &AppCore::listFinished, this, + [this](AppCore::ListMode mode, std::vector results) { + if (mode == AppCore::ListMode::Installed) { + m_statInstalled->setText(QString::number(results.size())); + } else if (mode == AppCore::ListMode::Updates) { + m_statUpdates->setText(QString::number(results.size())); + m_statUpdates->setStyleSheet(results.empty() + ? QString() + : QString("color: #e0af68;")); + } + }); + connect(core, &AppCore::historyChanged, this, &DashboardPage::refresh); +} + +void DashboardPage::refresh() { + m_statHistory->setText(QString::number(core()->historyCount())); + m_statManager->setText(core()->hasAvailableProvider() + ? core()->availableProviderNames().join(", ") + : QStringLiteral("indisponible")); + refreshRecentActivity(); + + // The listing itself arrives through listFinished: the search/installed + // pages share it, so nothing is queried twice. + if (core()->hasAvailableProvider()) { + start(core()->loadCounts(), tr("Tableau de bord")); + } +} + +void DashboardPage::refreshRecentActivity() { + m_recentList->clear(); + + const auto& history = core()->history()->getHistory(); + if (history.empty()) { + QListWidgetItem* empty = + new QListWidgetItem("Aucune action enregistrée pour le moment"); + empty->setFlags(Qt::NoItemFlags); + empty->setTextAlignment(Qt::AlignCenter); + m_recentList->addItem(empty); + return; + } + + int start = std::max(0, static_cast(history.size()) - 8); + for (int i = static_cast(history.size()) - 1; i >= start; --i) { + const HistoryEntry& entry = history[i]; + + QListWidgetItem* item = new QListWidgetItem(); + item->setSizeHint(QSize(0, 42)); + // Keep the package name so a click can open its details. + item->setData(Qt::UserRole, QString::fromStdString(entry.package)); + + QWidget* row = new QWidget(); + QHBoxLayout* rowLayout = new QHBoxLayout(row); + rowLayout->setContentsMargins(10, 4, 10, 4); + rowLayout->setSpacing(10); + + QLabel* timestamp = new QLabel(QString::fromStdString(entry.timestamp)); + timestamp->setStyleSheet( + "background: transparent; color: #5f6785;" + "font-family: monospace; font-size: 12px;"); + rowLayout->addWidget(timestamp); + + QString actionText, actionBg, actionFg; + if (entry.action == "install") { + actionText = "Installation"; actionBg = "#12301f"; actionFg = "#3fb950"; + } else if (entry.action == "remove") { + actionText = "Suppression"; actionBg = "#3a1a1a"; actionFg = "#f7768e"; + } else if (entry.action == "cleanup") { + actionText = "Nettoyage"; actionBg = "#12333a"; actionFg = "#56b6c2"; + } else { + actionText = "Mise à jour"; actionBg = "#3d2f0f"; actionFg = "#e0af68"; + } + rowLayout->addWidget(ui::badge(actionText, actionBg, actionFg)); + + QLabel* package = new QLabel(QString::fromStdString(entry.package)); + package->setStyleSheet("background: transparent; font-weight: 600; color: #c8d3f5;"); + rowLayout->addWidget(package); + + rowLayout->addStretch(); + + QLabel* status = new QLabel(); + status->setPixmap(ui::iconPixmap(entry.success ? "check" : "close", 16)); + status->setStyleSheet("background: transparent;"); + rowLayout->addWidget(status); + + m_recentList->addItem(item); + m_recentList->setItemWidget(item, row); + } +} + +void DashboardPage::onActivityClicked(QListWidgetItem* item) { + if (!item) return; + const QString name = item->data(Qt::UserRole).toString(); + if (name.isEmpty()) return; + emit openPackage(name); +} diff --git a/pages/dashboard-page.h b/pages/dashboard-page.h new file mode 100644 index 0000000..38ad0c1 --- /dev/null +++ b/pages/dashboard-page.h @@ -0,0 +1,36 @@ +#pragma once + +#include "page.h" + +class QLabel; +class QListWidget; +class QListWidgetItem; + +// Tableau de bord: the four figures of the system, the shortcuts to the pages +// used most often, and the last recorded actions. +class DashboardPage : public Page { + Q_OBJECT +public: + explicit DashboardPage(AppCore* core, QWidget* parent = nullptr); + + QString navTitle() const override { return QStringLiteral("Tableau de bord"); } + QString navSubtitle() const override { + return QStringLiteral("Vue d'ensemble de votre système"); + } + + void refresh() override; + +signals: + // A click on a recent action opens that package on the Installed screen. + void openPackage(const QString& name); + +private: + void refreshRecentActivity(); + void onActivityClicked(QListWidgetItem* item); + + QLabel* m_statInstalled = nullptr; + QLabel* m_statUpdates = nullptr; + QLabel* m_statHistory = nullptr; + QLabel* m_statManager = nullptr; + QListWidget* m_recentList = nullptr; +}; diff --git a/pages/history-page.cpp b/pages/history-page.cpp new file mode 100644 index 0000000..b2cd028 --- /dev/null +++ b/pages/history-page.cpp @@ -0,0 +1,150 @@ +#include "history-page.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ui-kit.h" + +HistoryPage::HistoryPage(AppCore* core, QWidget* parent) : Page(core, parent) { + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(24, 20, 24, 20); + layout->setSpacing(12); + + QHBoxLayout* filterRow = new QHBoxLayout(); + filterRow->setSpacing(10); + + QLabel* filterLabel = new QLabel("Filtrer :"); + filterLabel->setStyleSheet("font-size: 13px; color: #7a8299;"); + filterRow->addWidget(filterLabel); + + m_filter = new QComboBox(); + m_filter->addItems({"Toutes les actions", "Installations", "Suppressions", + "Mises à jour", "Nettoyages"}); + connect(m_filter, QOverload::of(&QComboBox::currentIndexChanged), this, + [this](int) { refreshTable(); }); + filterRow->addWidget(m_filter); + + filterRow->addStretch(); + + m_count = ui::countLabel(); + filterRow->addWidget(m_count); + + layout->addLayout(filterRow); + + m_table = ui::table({"Date", "Action", "Paquet", "Gestionnaire", "Statut"}, + /*allStretch=*/true); + layout->addWidget(m_table, 1); + + QHBoxLayout* buttonBar = new QHBoxLayout(); + buttonBar->addStretch(); + + QPushButton* exportButton = new QPushButton("Exporter (CSV)"); + exportButton->setToolTip("Enregistrer l'historique affiché dans un fichier CSV"); + connect(exportButton, &QPushButton::clicked, this, &HistoryPage::exportCsv); + buttonBar->addWidget(exportButton); + + QPushButton* clearButton = new QPushButton("Effacer l'historique"); + clearButton->setProperty("variant", "danger"); + clearButton->setIcon(ui::icon("trash")); + connect(clearButton, &QPushButton::clicked, this, [this, core] { + // The core clears the file and announces it; this page follows through + // historyChanged (connected below). + core->clearHistory(); + }); + buttonBar->addWidget(clearButton); + + layout->addLayout(buttonBar); + + connect(core, &AppCore::historyChanged, this, &HistoryPage::refresh); + refreshTable(); +} + +void HistoryPage::refresh() { + refreshTable(); +} + +void HistoryPage::refreshTable() { + const auto& all = core()->history()->getHistory(); + + std::vector entries; + const int filter = m_filter->currentIndex(); + for (const auto& entry : all) { + const bool match = filter == 0 + || (filter == 1 && entry.action == "install") + || (filter == 2 && entry.action == "remove") + || (filter == 3 && entry.action == "update") + || (filter == 4 && entry.action == "cleanup"); + if (match) entries.push_back(entry); + } + + m_count->setText(QString("%1 action(s)").arg(entries.size())); + + ui::TableFillBatch batch(m_table); + m_table->setRowCount(static_cast(entries.size())); + + for (int i = 0; i < static_cast(entries.size()); ++i) { + const auto& entry = entries[i]; + + QString actionText, actionColor; + if (entry.action == "install") { + actionText = "Installation"; actionColor = "#3fb950"; + } else if (entry.action == "remove") { + actionText = "Suppression"; actionColor = "#f7768e"; + } else if (entry.action == "cleanup") { + actionText = "Nettoyage"; actionColor = "#56b6c2"; + } else { + actionText = "Mise à jour"; actionColor = "#e0af68"; + } + + m_table->setItem(i, 0, + new QTableWidgetItem(QString::fromStdString(entry.timestamp))); + m_table->setItem(i, 1, new QTableWidgetItem(actionText)); + m_table->item(i, 1)->setForeground(QColor(actionColor)); + m_table->setItem(i, 2, new QTableWidgetItem(QString::fromStdString(entry.package))); + m_table->setItem(i, 3, new QTableWidgetItem(QString::fromStdString(entry.plugin))); + QTableWidgetItem* statusItem = + new QTableWidgetItem(entry.success ? "Succès" : "Échec"); + statusItem->setIcon(ui::icon(entry.success ? "check" : "close")); + m_table->setItem(i, 4, statusItem); + } +} + +void HistoryPage::exportCsv() { + const auto& history = core()->history()->getHistory(); + if (history.empty()) { + emit message(tr("Historique vide.")); + return; + } + + const QString path = QFileDialog::getSaveFileName( + this, "Exporter l'historique", + QDir::homePath() + "/pacmanager-historique.csv", "CSV (*.csv)"); + if (path.isEmpty()) return; + + QFile file(path); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { + QMessageBox::warning(this, "Export", + QString("Impossible d'écrire dans %1").arg(path)); + return; + } + QTextStream out(&file); + out << "Date;Action;Paquet;Gestionnaire;Statut\n"; + for (const auto& entry : history) { + out << ui::csvField(QString::fromStdString(entry.timestamp)) << ';' + << ui::csvField(QString::fromStdString(entry.action)) << ';' + << ui::csvField(QString::fromStdString(entry.package)) << ';' + << ui::csvField(QString::fromStdString(entry.plugin)) << ';' + << (entry.success ? "Succes" : "Echec") << '\n'; + } + emit message(QString("Historique exporté vers %1").arg(path)); +} diff --git a/pages/history-page.h b/pages/history-page.h new file mode 100644 index 0000000..d2d0247 --- /dev/null +++ b/pages/history-page.h @@ -0,0 +1,30 @@ +#pragma once + +#include "page.h" + +class QComboBox; +class QLabel; +class QTableWidget; + +// Historique: every action the application recorded (installations, removals, +// updates, cleanups), filterable and exportable. +class HistoryPage : public Page { + Q_OBJECT +public: + explicit HistoryPage(AppCore* core, QWidget* parent = nullptr); + + QString navTitle() const override { return QStringLiteral("Historique"); } + QString navSubtitle() const override { + return QStringLiteral("Journal de toutes vos actions"); + } + + void refresh() override; + void exportCsv(); + +private: + void refreshTable(); + + QComboBox* m_filter = nullptr; + QLabel* m_count = nullptr; + QTableWidget* m_table = nullptr; +}; diff --git a/pages/logs-page.cpp b/pages/logs-page.cpp new file mode 100644 index 0000000..e7ce482 --- /dev/null +++ b/pages/logs-page.cpp @@ -0,0 +1,81 @@ +#include "logs-page.h" + +#include +#include +#include +#include +#include +#include + +#include "ui-kit.h" + +LogsPage::LogsPage(AppCore* core, QWidget* parent) : Page(core, parent) { + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(24, 20, 24, 20); + layout->setSpacing(12); + + QHBoxLayout* filterRow = new QHBoxLayout(); + filterRow->setSpacing(10); + + m_filter = new QLineEdit(); + m_filter->setPlaceholderText("Filtrer les logs (paquet, action, date)..."); + m_filter->setMinimumHeight(36); + m_filter->setClearButtonEnabled(true); + m_filter->addAction(ui::icon("filter"), QLineEdit::LeadingPosition); + connect(m_filter, &QLineEdit::textChanged, this, [this](const QString&) { + applyFilter(); + }); + filterRow->addWidget(m_filter, 1); + + layout->addLayout(filterRow); + + m_text = new QTextEdit(); + m_text->setReadOnly(true); + layout->addWidget(m_text, 1); + + QHBoxLayout* buttonBar = new QHBoxLayout(); + buttonBar->addStretch(); + + QPushButton* refreshButton = new QPushButton("Recharger"); + refreshButton->setIcon(ui::icon("refresh")); + connect(refreshButton, &QPushButton::clicked, this, [this] { + load(); + emit message(tr("Logs rechargés")); + }); + buttonBar->addWidget(refreshButton); + + layout->addLayout(buttonBar); +} + +void LogsPage::refresh() { + load(); +} + +void LogsPage::load() { + QString error; + m_raw = core()->readPackageLog(&error); + if (!error.isEmpty()) { + m_text->setPlainText(error); + return; + } + applyFilter(); +} + +// Renders the raw log, keeping only the lines matching the filter box. +void LogsPage::applyFilter() { + const QString needle = m_filter->text().trimmed(); + if (needle.isEmpty()) { + m_text->setPlainText(m_raw); + } else { + QString filtered; + const QStringList lines = m_raw.split(QLatin1Char('\n')); + for (const QString& line : lines) { + if (line.contains(needle, Qt::CaseInsensitive)) { + filtered += line; + filtered += QLatin1Char('\n'); + } + } + m_text->setPlainText(filtered); + } + m_text->moveCursor(QTextCursor::End); +} diff --git a/pages/logs-page.h b/pages/logs-page.h new file mode 100644 index 0000000..1f725bc --- /dev/null +++ b/pages/logs-page.h @@ -0,0 +1,32 @@ +#pragma once + +#include + +#include "page.h" + +class QLineEdit; +class QTextEdit; + +// Logs pacman: the raw /var/log/pacman.log, filtered in memory so typing stays +// instant even with a multi-megabyte file (the core reads it, the page keeps a +// copy). +class LogsPage : public Page { + Q_OBJECT +public: + explicit LogsPage(AppCore* core, QWidget* parent = nullptr); + + QString navTitle() const override { return QStringLiteral("Logs pacman"); } + QString navSubtitle() const override { + return QStringLiteral("Journal brut du gestionnaire de paquets"); + } + + void refresh() override; + +private: + void load(); + void applyFilter(); + + QLineEdit* m_filter = nullptr; + QTextEdit* m_text = nullptr; + QString m_raw; +}; diff --git a/pages/page.cpp b/pages/page.cpp new file mode 100644 index 0000000..d71162f --- /dev/null +++ b/pages/page.cpp @@ -0,0 +1,13 @@ +#include "page.h" + +#include + +Page::Page(AppCore* core, QWidget* parent) : QWidget(parent), m_core(core) {} + +QMainWindow* Page::mainWindow() const { + return qobject_cast(window()); +} + +void Page::start(const AppCore::StartResult& result, const QString& title) { + emit requestStart(result, title); +} diff --git a/pages/page.h b/pages/page.h new file mode 100644 index 0000000..ebb441b --- /dev/null +++ b/pages/page.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include + +#include "app-core.h" + +// One screen of the application. Each screen lives in its own file under +// pages/ and owns nothing but its own widgets: the frame (MainWindow) keeps the +// sidebar, the header, the status bar and every dialog, and the logic stays in +// AppCore. +// +// Adding a screen therefore means writing one Page subclass here and +// registering it in MainWindow::setupUI — no backend code involved. +class QMainWindow; + +class Page : public QWidget { + Q_OBJECT +public: + explicit Page(AppCore* core, QWidget* parent = nullptr); + + // Header text, asked by the frame whenever the screen is shown. A screen + // whose title depends on its state (the browse page shows search, installed + // or updates) just returns the current one. + virtual QString navTitle() const = 0; + virtual QString navSubtitle() const = 0; + + // Called every time the screen becomes visible, so it can reload whatever + // may be stale. Default: nothing to reload. + virtual void refresh() {} + +signals: + // Ask the frame to switch to another screen (dashboard shortcuts) or to run + // a request on the user's behalf. + void goToPage(const QString& pageId); + void requestStart(AppCore::StartResult result, const QString& title); + // Something the user should read in the status bar, with no operation + // behind it ("Aucune liste à exporter.", ...). + void message(const QString& text); + +protected: + AppCore* core() const { return m_core; } + + // Top-level window this screen is stacked in. Needed by the addon hook, + // which attaches a plugin's own UI to the main window. + QMainWindow* mainWindow() const; + + // Hands a request to the frame: it owns the sudo-password and pacman-lock + // dialogs and replays the request once the user answered. + void start(const AppCore::StartResult& result, const QString& title); + +private: + AppCore* m_core = nullptr; // non-owning: the frame owns the core +}; diff --git a/pages/plugins-page.cpp b/pages/plugins-page.cpp new file mode 100644 index 0000000..559bc41 --- /dev/null +++ b/pages/plugins-page.cpp @@ -0,0 +1,217 @@ +#include "plugins-page.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "ui-kit.h" + +PluginsPage::PluginsPage(AppCore* core, QWidget* parent) : Page(core, parent) { + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(24, 20, 24, 20); + layout->setSpacing(12); + + QFrame* hintCard = ui::card(); + QVBoxLayout* hintLayout = new QVBoxLayout(hintCard); + hintLayout->setContentsMargins(18, 16, 18, 16); + hintLayout->setSpacing(4); + + QLabel* hintTitle = new QLabel("AJOUTER UN PLUGIN"); + hintTitle->setObjectName("cardTitle"); + hintLayout->addWidget(hintTitle); + + QLabel* hint = new QLabel( + "Pacman est intégré et le plugin Flatpak est livré par défaut. Si un " + "fournisseur est « Indisponible », sélectionnez-le puis cliquez sur " + "« Installer l'outil » pour l'installer via pacman. Un plugin peut être " + "un gestionnaire de paquets (apt, dnf, ...) ou n'importe quelle extension " + "(addon graphique, helper, ...) tant qu'il est écrit en C++ : compilez une " + "bibliothèque partagée (voir plugins/example-provider et " + "plugins/example-addon) et déposez-la dans " + "~/.local/share/PacManager/plugins/ ou dans le dossier plugins/ à côté de " + "l'exécutable, puis cliquez sur « Recharger »."); + hint->setWordWrap(true); + hint->setStyleSheet("font-size: 12px; color: #7a8299;"); + hintLayout->addWidget(hint); + + layout->addWidget(hintCard); + + m_table = ui::table({"Plugin", "Type", "Version", "Auteur", "Statut"}); + connect(m_table, &QTableWidget::currentCellChanged, this, + [this](int currentRow, int, int, int) { onSelected(currentRow); }); + layout->addWidget(m_table, 1); + + m_description = new QLabel(""); + m_description->setWordWrap(true); + m_description->setStyleSheet( + "font-size: 13px; color: #c8d3f5; background: transparent; padding: 2px 4px;"); + layout->addWidget(m_description); + + QHBoxLayout* buttonBar = new QHBoxLayout(); + buttonBar->addStretch(); + + // Installs the OS package backing a provider whose tool is missing + // (e.g. pacman -S flatpak), then rescans so it becomes available. + m_installButton = new QPushButton("Installer l'outil"); + m_installButton->setProperty("variant", "primary"); + m_installButton->setEnabled(false); + m_installButton->setVisible(false); + connect(m_installButton, &QPushButton::clicked, this, [this, core] { + if (m_selectedId.empty()) return; + start(core->installPluginTool(m_selectedId), tr("Installation de l'outil")); + }); + buttonBar->addWidget(m_installButton); + + m_toggleButton = new QPushButton("Activer"); + m_toggleButton->setEnabled(false); + connect(m_toggleButton, &QPushButton::clicked, this, [this, core] { + if (m_selectedId.empty()) return; + const std::string id = m_selectedId; + const bool enabled = !core->plugins()->isEnabled(id); + core->setPluginEnabled(id, enabled); + + // A freshly enabled addon gets the window so it can attach its UI (it + // may have been disabled when onUiReady ran at launch). The core already + // announced the change, which refreshed this table. + if (enabled) { + for (const auto& entry : core->plugins()->plugins()) { + if (entry.info.id == id && entry.plugin) { + entry.plugin->onUiReady(mainWindow()); + break; + } + } + } + }); + buttonBar->addWidget(m_toggleButton); + + QPushButton* rescanButton = new QPushButton("Recharger"); + rescanButton->setIcon(ui::icon("refresh")); + rescanButton->setToolTip("Rescanner les dossiers de plugins"); + connect(rescanButton, &QPushButton::clicked, this, [this, core] { + core->reloadPlugins(); + for (IPlugin* addon : core->plugins()->availableAddons()) { + addon->onUiReady(mainWindow()); + } + }); + buttonBar->addWidget(rescanButton); + + layout->addLayout(buttonBar); + + connect(core, &AppCore::pluginsChanged, this, &PluginsPage::refresh); + refreshTable(); +} + +void PluginsPage::refresh() { + refreshTable(); +} + +void PluginsPage::refreshTable() { + const auto& plugins = core()->plugins()->plugins(); + + QFont nameFont; + nameFont.setWeight(QFont::DemiBold); + + ui::TableFillBatch batch(m_table); + m_table->setRowCount(0); + m_table->setRowCount(static_cast(plugins.size())); + + for (int i = 0; i < static_cast(plugins.size()); ++i) { + const auto& entry = plugins[i]; + const bool enabled = core()->plugins()->isEnabled(entry.info.id); + + QTableWidgetItem* nameItem = + new QTableWidgetItem(QString::fromStdString(entry.info.name)); + nameItem->setFont(nameFont); + nameItem->setData(Qt::UserRole, QString::fromStdString(entry.info.id)); + m_table->setItem(i, 0, nameItem); + + // Type column distinguishes package-manager providers from generic + // addons; the build origin is appended for external plugins. + const QString kindText = entry.info.kind == PluginKind::Addon ? "Extension" + : "Fournisseur"; + QTableWidgetItem* typeItem = + new QTableWidgetItem(entry.info.builtin ? kindText : kindText + " (externe)"); + typeItem->setForeground(QColor("#7a8299")); + m_table->setItem(i, 1, typeItem); + + m_table->setItem(i, 2, new QTableWidgetItem(QString::fromStdString(entry.info.version))); + m_table->setItem(i, 3, new QTableWidgetItem(QString::fromStdString(entry.info.author))); + + QString statusText; + QColor statusColor; + if (!entry.info.available) { + statusText = "Indisponible"; + statusColor = QColor("#565f73"); + } else if (enabled) { + statusText = "Actif"; + statusColor = QColor("#3fb950"); + } else { + statusText = "Désactivé"; + statusColor = QColor("#e0af68"); + } + + QTableWidgetItem* statusItem = new QTableWidgetItem(statusText); + statusItem->setForeground(statusColor); + statusItem->setIcon(ui::icon(entry.info.available ? (enabled ? "check" : "close") + : "alert")); + m_table->setItem(i, 4, statusItem); + } + batch.release(); + + if (plugins.empty()) { + m_toggleButton->setEnabled(false); + m_installButton->setVisible(false); + m_description->clear(); + return; + } + + // Keep the previously selected plugin selected when possible. + int row = 0; + for (int i = 0; i < static_cast(plugins.size()); ++i) { + if (plugins[i].info.id == m_selectedId) { + row = i; + break; + } + } + m_table->selectRow(row); + onSelected(row); +} + +void PluginsPage::onSelected(int row) { + const auto& plugins = core()->plugins()->plugins(); + if (row < 0 || row >= static_cast(plugins.size())) { + m_toggleButton->setEnabled(false); + m_installButton->setVisible(false); + m_description->clear(); + return; + } + + const auto& entry = plugins[row]; + m_selectedId = entry.info.id; + m_description->setText(QString::fromStdString(entry.info.description)); + + const bool toggleable = entry.info.available; + m_toggleButton->setEnabled(toggleable); + m_toggleButton->setToolTip( + toggleable ? QString() + : QString("Outil « %1 » non détecté sur ce système.") + .arg(QString::fromStdString(entry.info.name))); + m_toggleButton->setText(core()->plugins()->isEnabled(entry.info.id) ? "Désactiver" + : "Activer"); + + // Offer to install the backing tool (e.g. flatpak via pacman) when it is + // missing and we know which OS package provides it. + const bool pacmanAvailable = core()->plugins()->findAvailable("pacman") != nullptr; + const bool installable = !entry.info.available && !entry.info.installHint.empty() + && pacmanAvailable; + m_installButton->setVisible(!entry.info.available); + m_installButton->setEnabled(installable); + m_installButton->setToolTip( + installable + ? QString("sudo pacman -S %1").arg(QString::fromStdString(entry.info.installHint)) + : QString()); +} diff --git a/pages/plugins-page.h b/pages/plugins-page.h new file mode 100644 index 0000000..8eaae2f --- /dev/null +++ b/pages/plugins-page.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +#include + +#include "page.h" + +class QLabel; +class QPushButton; +class QTableWidget; + +// Plugins: the add-on store. Lists every plugin known to the application +// (package-manager providers and generic addons, built-in and external), lets +// the user enable/disable one, install the tool behind an unavailable provider +// and rescan the plugin directories. +class PluginsPage : public Page { + Q_OBJECT +public: + explicit PluginsPage(AppCore* core, QWidget* parent = nullptr); + + QString navTitle() const override { return QStringLiteral("Plugins"); } + QString navSubtitle() const override { + return QStringLiteral("Gestionnaires de paquets et extensions"); + } + + void refresh() override; + +private: + void refreshTable(); + void onSelected(int row); + + QTableWidget* m_table = nullptr; + QLabel* m_description = nullptr; + QPushButton* m_toggleButton = nullptr; + QPushButton* m_installButton = nullptr; + std::string m_selectedId; +}; diff --git a/pages/ui-kit.cpp b/pages/ui-kit.cpp new file mode 100644 index 0000000..6e20129 --- /dev/null +++ b/pages/ui-kit.cpp @@ -0,0 +1,163 @@ +#include "ui-kit.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace ui { + +QIcon icon(const QString& name) { + return QIcon(QString(":/icons/%1.svg").arg(name)); +} + +QPixmap iconPixmap(const QString& name, int size) { + return icon(name).pixmap(QSize(size, size)); +} + +QLabel* badge(const QString& text, const QString& background, const QString& foreground) { + QLabel* label = new QLabel(text); + label->setStyleSheet(QString( + "background: %1; color: %2; border-radius: 9px;" + "padding: 2px 9px; font-size: 11px; font-weight: 600;") + .arg(background, foreground)); + return label; +} + +QFrame* card() { + QFrame* frame = new QFrame(); + frame->setObjectName("card"); + return frame; +} + +QFrame* statCard(const QString& iconName, const QString& title, const QString& accent, + QLabel** valueOut) { + QFrame* frame = card(); + // Read by the stylesheet rule that draws the coloured left edge. + frame->setProperty("accent", accent); + QVBoxLayout* layout = new QVBoxLayout(frame); + layout->setContentsMargins(18, 16, 18, 16); + layout->setSpacing(6); + + QLabel* iconLabel = new QLabel(); + iconLabel->setPixmap(iconPixmap(iconName, 24)); + iconLabel->setStyleSheet("background: transparent;"); + layout->addWidget(iconLabel); + + QLabel* value = new QLabel("…"); + value->setObjectName("statValue"); + layout->addWidget(value); + + QLabel* titleLabel = new QLabel(title); + titleLabel->setObjectName("statTitle"); + layout->addWidget(titleLabel); + + if (valueOut) *valueOut = value; + return frame; +} + +QTableWidget* table(const QStringList& headers, bool allStretch) { + QTableWidget* widget = new QTableWidget(0, headers.size()); + widget->setHorizontalHeaderLabels(headers); + widget->verticalHeader()->setVisible(false); + widget->verticalHeader()->setDefaultSectionSize(36); + widget->setSelectionBehavior(QAbstractItemView::SelectRows); + widget->setSelectionMode(QAbstractItemView::SingleSelection); + widget->setEditTriggers(QAbstractItemView::NoEditTriggers); + widget->setShowGrid(false); + widget->setAlternatingRowColors(true); + widget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + + for (int column = 0; column < headers.size(); ++column) { + widget->horizontalHeader()->setSectionResizeMode( + column, + allStretch ? QHeaderView::Stretch + : (column == 0 ? QHeaderView::Stretch : QHeaderView::ResizeToContents)); + } + return widget; +} + +QStackedWidget* withEmptyState(QTableWidget* widget, const QString& hint) { + QStackedWidget* stack = new QStackedWidget(); + stack->addWidget(widget); + + QWidget* placeholder = new QWidget(); + QVBoxLayout* layout = new QVBoxLayout(placeholder); + layout->addStretch(); + QLabel* label = new QLabel(hint); + label->setAlignment(Qt::AlignCenter); + label->setWordWrap(true); + label->setStyleSheet("background: transparent; color: #565f73; font-size: 13px;"); + layout->addWidget(label); + layout->addStretch(); + stack->addWidget(placeholder); + return stack; +} + +void showEmptyState(QStackedWidget* stack, bool empty) { + if (stack) stack->setCurrentIndex(empty ? 1 : 0); +} + +QLabel* countLabel() { + QLabel* label = new QLabel(); + label->setStyleSheet("font-size: 12px; color: #7a8299; font-weight: 600;"); + return label; +} + +QString providersLabel(const PluginManager* plugins, const PackageInfo& pkg) { + auto labelFor = [plugins](const std::string& id) { + for (const auto& entry : plugins->plugins()) { + if (entry.info.id == id) return QString::fromStdString(entry.info.name); + } + return QString::fromStdString(id); + }; + + QStringList names; + for (const auto& id : pkg.providers) names << labelFor(id); + if (names.isEmpty() && !pkg.provider.empty()) names << labelFor(pkg.provider); + return names.join(", "); +} + +QString packageStatusText(const PackageInfo& pkg) { + if (pkg.installed && pkg.updateAvailable) return QStringLiteral("MAJ dispo"); + if (pkg.installed) return QStringLiteral("Installé"); + if (!pkg.repository.empty()) return QStringLiteral("Disponible"); + return QStringLiteral("—"); +} + +QString csvField(const QString& value) { + if (!value.contains(';') && !value.contains('"') && !value.contains('\n')) { + return value; + } + QString escaped = value; + escaped.replace(QLatin1String("\""), QLatin1String("\"\"")); + return QLatin1Char('"') + escaped + QLatin1Char('"'); +} + +struct TableFillBatch::Impl { + QTableWidget* table = nullptr; + std::unique_ptr blocker; +}; + +TableFillBatch::TableFillBatch(QTableWidget* widget) + : m_impl(std::make_unique()) { + m_impl->table = widget; + if (!widget) return; + widget->setUpdatesEnabled(false); + m_impl->blocker = std::make_unique(widget); +} + +void TableFillBatch::release() { + if (!m_impl->table || !m_impl->blocker) return; + m_impl->blocker.reset(); + m_impl->table->setUpdatesEnabled(true); +} + +TableFillBatch::~TableFillBatch() { + release(); +} + +} // namespace ui diff --git a/pages/ui-kit.h b/pages/ui-kit.h new file mode 100644 index 0000000..48083c6 --- /dev/null +++ b/pages/ui-kit.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#include "package-manager.h" +#include "plugin-manager.h" + +class QStackedWidget; +class QTableWidget; + +// Small widget helpers shared by the screens. They exist so a screen file shows +// its layout and its wording instead of repeating the same table, card and pill +// setup — the look itself is still driven by the application stylesheet (see +// MainWindow::setupUI). +namespace ui { + +// One of the embedded SVG icons (resources/resources.qrc). +QIcon icon(const QString& name); +QPixmap iconPixmap(const QString& name, int size); + +// Rounded status pill (coloured background + foreground). +QLabel* badge(const QString& text, const QString& background, const QString& foreground); + +// Plain raised surface, and the coloured stat card used by the dashboard. +QFrame* card(); +QFrame* statCard(const QString& iconName, const QString& title, const QString& accent, + QLabel** valueOut); + +// Listing used by every screen: no frame, alternating rows, and the name column +// taking the free space (every column when allStretch). +QTableWidget* table(const QStringList& headers, bool allStretch = false); + +// Wraps a listing in a stack that swaps in a centered hint while it is empty, +// so a screen with no result explains itself instead of showing a bare header. +QStackedWidget* withEmptyState(QTableWidget* table, const QString& hint); +void showEmptyState(QStackedWidget* stack, bool empty); + +// Small grey counter ("12 paquet(s)"). +QLabel* countLabel(); + +// Display names of every provider offering a package (the Fournisseur column). +QString providersLabel(const PluginManager* plugins, const PackageInfo& pkg); +// Human-readable status of a package row, shared by the table and the exports. +QString packageStatusText(const PackageInfo& pkg); +// Quotes a CSV field when it contains the separator, a quote or a newline, so +// exported lists stay importable in a spreadsheet. +QString csvField(const QString& value); + +// Fills a table in one repaint batch, with its signals muted: without it every +// setItem() repaints the viewport, and on the browse page each selection change +// fires the pacman queries behind the details panel (a thousand rows meant a +// thousand repaints and a pacman call in the middle of the fill). +class TableFillBatch { +public: + explicit TableFillBatch(QTableWidget* table); + ~TableFillBatch(); + // Called before selecting a row: that selection is what refreshes the + // details panel, so it has to be seen by the table's signals. Idempotent, + // which lets the destructor cover an early return too. + void release(); + + TableFillBatch(const TableFillBatch&) = delete; + TableFillBatch& operator=(const TableFillBatch&) = delete; + +private: + struct Impl; + std::unique_ptr m_impl; +}; + +} // namespace ui diff --git a/src/app-core.cpp b/src/app-core.cpp new file mode 100644 index 0000000..43b3ecb --- /dev/null +++ b/src/app-core.cpp @@ -0,0 +1,1025 @@ +#include "app-core.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "app-logging.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) { + AppCore::StartResult result; + result.error = error; + result.needsPassword = needsPassword; + result.locked = locked; + return result; +} + +} // 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"); + + // 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", + "Gestionnaire de paquets natif d'Arch Linux", "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")); + + 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()) + << "provider(s) available"; +} + +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(); + emit statusMessage(QStringLiteral("Identifiants demandés à chaque opération.")); + } else { + emit statusMessage(QStringLiteral("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(QStringLiteral("pacman est indisponible sur ce système.")); + } + if (std::system("which sudo > /dev/null 2>&1") != 0) { + return refused(QStringLiteral("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(QStringLiteral("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(QStringLiteral("Aucun gestionnaire de paquets disponible sur ce système.")); + } + if (m_busy) { + return refused(QStringLiteral("Une opération est en cours, chargement impossible.")); + } + if (m_list) { + m_queuedLists.append(mode); + return accepted(); + } + + switch (mode) { + case ListMode::Installed: + emit statusMessage(QStringLiteral("Chargement des paquets installés...")); + break; + case ListMode::Updates: + emit statusMessage(QStringLiteral("Recherche des mises à jour...")); + break; + case ListMode::Cleanup: + emit statusMessage(QStringLiteral("Analyse des paquets inutilisés et legacy...")); + break; + } + + 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; + + if (mode == ListMode::Installed) { + m_installedPackages = results; + emit statusMessage(QStringLiteral("%1 paquet(s) installé(s)") + .arg(results.size())); + } else if (mode == ListMode::Updates) { + m_updatePackages = results; + emit statusMessage(QStringLiteral("%1 mise(s) à jour disponible(s)") + .arg(results.size())); + } else { + m_cleanupCandidates = results; + int orphans = 0; + for (const auto& pkg : results) { + if (pkg.orphan) ++orphans; + } + emit statusMessage(QStringLiteral("%1 orphelin(s) et %2 paquet(s) legacy " + "détecté(s)") + .arg(orphans) + .arg(static_cast(results.size()) - orphans)); + } + + 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(QStringLiteral("Une opération est en cours, recherche impossible.")); + } + if (m_search) return refused(QStringLiteral("Une recherche est déjà en cours.")); + return startSearch(query); +} + +AppCore::StartResult AppCore::startSearch(const QString& query) { + if (query.trimmed().isEmpty()) { + return refused(QStringLiteral("Entrez un terme de recherche.")); + } + auto providers = availableProviders(); + if (providers.empty()) { + return refused(QStringLiteral("Aucun gestionnaire de paquets disponible sur ce système.")); + } + + emit statusMessage(QStringLiteral("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; + emit statusMessage(QStringLiteral("%1 paquet(s) trouvé(s)").arg(results.size())); + 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::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::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(QStringLiteral("Une opération est déjà en cours, patientez...")); + if (!m_pacman) return refused(QStringLiteral("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(QStringLiteral("Libération de la base de données pacman...")); + + auto* worker = new InstallWorker(m_pacman, holder); + connect(worker, &InstallWorker::progress, this, + [this](const QString& message) { emit statusMessage(message); }); + connect(worker, &InstallWorker::finished, this, [this](bool released) { + setBusy(false); + if (!m_pacman) return; + if (!released) { + emit statusMessage(QStringLiteral("Base pacman toujours verrouillée")); + // The core is only asked to free the lock when it is actually held: + // 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. + emit actionFinished(QStringLiteral("release-lock"), QString(), + false, QString::fromStdString(m_pacman->lastError()), + /*locked=*/false); + return; + } + emit statusMessage(QStringLiteral("Base libérée, reprise de l'opération...")); + // Deferred so the status message paints before the replayed action + // starts streaming its own progress. + QTimer::singleShot(0, this, [this] { retryPendingRequest(); }); + }); + disposeWorker(worker); + worker->start(); + + return accepted(); +} + +AppCore::StartResult AppCore::startRequest(const Request& request) { + if (m_busy) return refused(QStringLiteral("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(QStringLiteral("Aucun gestionnaire de paquets disponible.")); + } + if (request.package.name.empty()) { + return refused(QStringLiteral("Nom de paquet manquant.")); + } + if (action == QLatin1String("install") && !provider->canInstall()) { + return refused(QStringLiteral("%1 ne sait pas installer de paquets.") + .arg(QString::fromStdString(provider->getName()))); + } + if (action == QLatin1String("remove") && !provider->canRemove()) { + return refused(QStringLiteral("%1 ne sait pas supprimer de paquets.") + .arg(QString::fromStdString(provider->getName()))); + } + if (action == QLatin1String("update") && !provider->canUpdate()) { + return refused(QStringLiteral("%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(QStringLiteral("Aucun cache à nettoyer sur ce système.")); + } + } 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(QStringLiteral("Aucun paquet sélectionné n'est supprimable.")); + } + m_cleanupRemovalDescription = request.description; + bulk = true; + } else if (action == QLatin1String("install-plugin-tool")) { + if (!m_pacman || !m_pacman->isAvailable()) { + return refused(QStringLiteral("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(QStringLiteral("Aucun paquet système connu pour ce plugin.")); + } + providers = {m_pacman}; + op = InstallWorker::Op::Install; + label = QString::fromStdString(hint); + } else { + return refused(QStringLiteral("Action inconnue : %1").arg(action)); + } + + if (providers.empty()) { + return refused(QStringLiteral("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; + 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 { + 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 QStringLiteral("Installation de %1...").arg(label); + } + if (action == QLatin1String("remove")) { + return QStringLiteral("Suppression de %1...").arg(label); + } + if (action == QLatin1String("update")) { + return QStringLiteral("Mise à jour de %1...").arg(label); + } + if (action == QLatin1String("update-all")) { + return QStringLiteral("Mise à jour de tous les paquets..."); + } + if (action == QLatin1String("refresh")) { + return QStringLiteral("Rafraîchissement des sources..."); + } + if (action == QLatin1String("clean-caches")) { + return QStringLiteral("Nettoyage des caches..."); + } + if (action == QLatin1String("install-plugin-tool")) { + return QStringLiteral("Installation de l'outil %1...").arg(label); + } + return QStringLiteral("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); + + connect(worker, &InstallWorker::progress, this, + [this](const QString& 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 = QStringLiteral("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("clean-caches")) { + for (IPackageManager* pm : providers) { + recordHistory(QStringLiteral("cleanup"), QStringLiteral("caches"), pm, success); + } + } + + clearCredentialsAfterUse(); + + if (action == QLatin1String("install") || action == QLatin1String("remove") + || action == QLatin1String("update")) { + invalidateDetails(); + } + if (action == QLatin1String("install-plugin-tool") && success) { + m_plugins->refreshAvailability(); + refreshProviderCache(); + emit pluginsChanged(); + } + + emit actionFinished(action, name, success, error, locked); +} + +QString AppCore::successMessage(const QString& action, const QString& name) const { + if (action == QLatin1String("install")) { + return QStringLiteral("%1 installé avec succès").arg(name); + } + if (action == QLatin1String("remove")) { + return QStringLiteral("%1 supprimé avec succès").arg(name); + } + if (action == QLatin1String("update")) { + return QStringLiteral("Mise à jour terminée"); + } + if (action == QLatin1String("update-all")) { + return QStringLiteral("Tous les paquets sont à jour"); + } + if (action == QLatin1String("refresh")) { + return QStringLiteral("Sources rafraîchies"); + } + if (action == QLatin1String("clean-caches")) { + return QStringLiteral("Caches nettoyés"); + } + if (action == QLatin1String("install-plugin-tool")) { + return QStringLiteral("Outil installé, plugin disponible."); + } + return QStringLiteral("Opération terminée"); +} + +QString AppCore::failureMessage(const QString& action, const QString& name) const { + if (action == QLatin1String("install")) { + return QStringLiteral("Échec de l'installation de %1").arg(name); + } + if (action == QLatin1String("remove")) { + return QStringLiteral("Échec de la suppression de %1").arg(name); + } + if (action == QLatin1String("update")) { + return QStringLiteral("Échec de la mise à jour"); + } + if (action == QLatin1String("update-all")) { + return QStringLiteral("Erreur lors de la mise à jour globale"); + } + if (action == QLatin1String("refresh")) { + return QStringLiteral("Erreur lors du rafraîchissement"); + } + if (action == QLatin1String("clean-caches")) { + return QStringLiteral("Échec du nettoyage des caches"); + } + if (action == QLatin1String("install-plugin-tool")) { + return QStringLiteral("Échec de l'installation de l'outil."); + } + return QStringLiteral("É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()) { + 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; + + emit actionProgress(QStringLiteral("Suppression de %1 paquet(s)...") + .arg(packages.size()), -1); + + auto* worker = new InstallWorker(provider, InstallWorker::Op::RemovePackages, packages); + m_action = worker; + + connect(worker, &InstallWorker::progress, this, + [this](const QString& message) { emit actionProgress(message, -1); }); + 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()); + emit statusMessage(QStringLiteral("Échec du nettoyage")); + emit actionFinished(QStringLiteral("cleanup"), m_cleanupRemovalDescription, + false, error, locked); + return; + } + + emit actionProgress(QStringLiteral("%1 paquet(s) supprimé(s)") + .arg(packages.size()), -1); + startNextRemovalGroup(); + }); + disposeWorker(worker); + worker->start(); +} + +AppCore::StartResult AppCore::retryPendingRequest() { + if (!m_pending) return refused(QStringLiteral("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) { + m_plugins->setEnabled(pluginId, enabled); + refreshProviderCache(); + emit pluginsChanged(); +} + +void AppCore::reloadPlugins() { + m_plugins->reload(); + refreshProviderCache(); + emit pluginsChanged(); + emit statusMessage(QStringLiteral("Plugins rechargés.")); +} + +void AppCore::clearHistory() { + m_history->clear(); + emit historyChanged(); + emit statusMessage(QStringLiteral("Historique effacé")); +} + +QString AppCore::readPackageLog(QString* error) const { + QFile logFile(QString::fromUtf8(kPacmanLogPath)); + if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (error) { + *error = QStringLiteral("Impossible d'ouvrir %1.\n" + "Vérifiez que le fichier existe et que vous avez les " + "droits de lecture.") + .arg(QString::fromUtf8(kPacmanLogPath)); + } + return QString(); + } + if (error) error->clear(); + return QString::fromUtf8(logFile.readAll()); +} + +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(); + + 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 char* label, const std::string& value) { + if (value.empty() || value == "None" || value == "--") return; + if (!text.empty()) text += "\n"; + text += std::string(label) + " : " + value; + }; + if (!installed.empty()) { + addRow("Taille installée", infoField(installed, "Installed Size")); + addRow("Date d'installation", infoField(installed, "Install Date")); + addRow("Dépend de", infoField(installed, "Depends On")); + addRow("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("Taille du téléchargement", infoField(sync, "Download Size")); + addRow("Taille installée", infoField(sync, "Installed Size")); + addRow("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 { + return m_update->shouldCheck(); +} + +void AppCore::checkForAppUpdate() { + emit statusMessage(QStringLiteral("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 = QStringLiteral("Aucune mise à jour ne peut être appliquée localement."); + } + return false; + } + if (error) error->clear(); + m_update->performSelfUpdate(sudoPassword); + return true; +} + +// --------------------------------------------------------------------------- +// 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())); +} diff --git a/src/main-window.cpp b/src/main-window.cpp index 29fd01c..db07656 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -1,428 +1,82 @@ #include "main-window.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include #include "app-logging.h" - -#include -#include -#include - -// Worker threads -SearchWorker::SearchWorker(const std::vector& providers, - const std::string& query) - : m_providers(providers), m_query(query) {} - -void SearchWorker::run() { - std::vector 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 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 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 providerOrder; - for (IPackageManager* pm : m_providers) providerOrder.push_back(pm->getName()); - sortByProviderThenName(results, providerOrder); - - emit finished(results); -} - -ListWorker::ListWorker(const std::vector& providers, Mode mode) - : m_providers(providers), m_mode(mode) {} - -void ListWorker::run() { - std::vector 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& packages) - : m_providers{pm}, m_op(op), m_packages(packages) {} - -InstallWorker::InstallWorker(const std::vector& 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; - } - - bool success = true; - for (IPackageManager* pm : m_providers) { - // 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](const std::string& msg, int percent) { - if (m_providers.size() > 1) { - emit progress(QString("[%1] %2") - .arg(QString::fromStdString(pm->getName()), - QString::fromStdString(msg))); - } else { - emit progress(QString::fromStdString(msg)); - } - if (percent >= 0) emit progressValue(percent); - }; - - // 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::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); -} - -// Small rounded "badge" label used for status pills across the UI. -static QLabel* makeBadge(const QString& text, const QString& bg, const QString& fg) { - QLabel* badge = new QLabel(text); - badge->setStyleSheet(QString( - "background: %1; color: %2; border-radius: 9px;" - "padding: 2px 9px; font-size: 11px; font-weight: 600;") - .arg(bg, fg)); - return badge; -} - -// 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); - } -}; +#include "browse-page.h" +#include "cleanup-page.h" +#include "dashboard-page.h" +#include "history-page.h" +#include "logs-page.h" +#include "page.h" +#include "plugins-page.h" // Load one of the embedded SVG icons (see resources/resources.qrc). static QIcon loadIcon(const QString& name) { return QIcon(QString(":/icons/%1.svg").arg(name)); } -// Render an SVG icon as a pixmap for use in QLabel (e.g. stat card icons or -// inline status indicators), sizing it to the requested resolution. +// Render an SVG icon as a pixmap for use in QLabel, sizing it to the requested +// resolution. static QPixmap iconPixmap(const QString& name, int size) { return loadIcon(name).pixmap(QSize(size, size)); } -// Display name of a provider id (e.g. "pacman" -> "Pacman"), falling back to -// the raw id for providers that are no longer registered. -static QString providerLabel(const PluginManager* pm, const std::string& id) { - for (const auto& entry : pm->plugins()) { - if (entry.info.id == id) return QString::fromStdString(entry.info.name); +// Dialog title of a failed action: naming what failed is the frame's job (the +// core reports which action failed, not how to phrase it). +static QString actionErrorTitle(const QString& action) { + if (action == QLatin1String("install")) return QStringLiteral("Échec de l'installation"); + if (action == QLatin1String("remove")) return QStringLiteral("Échec de la suppression"); + if (action == QLatin1String("update")) return QStringLiteral("Échec de la mise à jour"); + if (action == QLatin1String("update-all")) { + return QStringLiteral("Erreur lors de la mise à jour globale"); } - return QString::fromStdString(id); + if (action == QLatin1String("refresh")) { + return QStringLiteral("Erreur lors du rafraîchissement"); + } + if (action == QLatin1String("clean-caches")) { + return QStringLiteral("Échec du nettoyage des caches"); + } + if (action == QLatin1String("cleanup")) return QStringLiteral("Échec du nettoyage"); + if (action == QLatin1String("install-plugin-tool")) { + return QStringLiteral("Échec de l'installation de l'outil"); + } + if (action == QLatin1String("release-lock")) { + return QStringLiteral("Base de données verrouillée"); + } + return QStringLiteral("Échec de l'opération"); } -// Comma-separated display names of every provider offering a package (used by -// the Fournisseur column and the details badge). -static QString providersLabel(const PluginManager* pm, const PackageInfo& pkg) { - QStringList names; - for (const auto& id : pkg.providers) { - names << providerLabel(pm, id); - } - if (names.isEmpty() && !pkg.provider.empty()) { - names << providerLabel(pm, pkg.provider); - } - return names.join(", "); -} - -// Inserts rows into a table in one repaint batch, with the table's signals -// muted for the duration. Without it every setItem() repaints the viewport, and -// on the browse page each selection change fires the pacman queries behind the -// details panel — a thousand rows meant a thousand repaints and a pacman call -// in the middle of the fill. -class TableFillBatch { -public: - explicit TableFillBatch(QTableWidget* table) : m_table(table) { - if (!m_table) return; - m_table->setUpdatesEnabled(false); - m_blocker = std::make_unique(m_table); - } - - // Called before the caller selects a row: that selection is what refreshes - // the details panel, so it has to be seen by the table's signals. Idempotent, - // which lets the destructor cover an early return too. - void release() { - if (!m_table || !m_blocker) return; - m_blocker.reset(); - m_table->setUpdatesEnabled(true); - } - - ~TableFillBatch() { release(); } - - TableFillBatch(const TableFillBatch&) = delete; - TableFillBatch& operator=(const TableFillBatch&) = delete; - -private: - QTableWidget* m_table = nullptr; - std::unique_ptr m_blocker; -}; - -// Wraps a listing in a stack that swaps in a centered hint while the listing is -// empty, so a page with no result explains itself instead of showing a bare -// table header. -static QStackedWidget* withEmptyState(QTableWidget* table, const QString& hint) { - QStackedWidget* stack = new QStackedWidget(); - stack->addWidget(table); - - QWidget* placeholder = new QWidget(); - QVBoxLayout* layout = new QVBoxLayout(placeholder); - layout->addStretch(); - QLabel* label = new QLabel(hint); - label->setAlignment(Qt::AlignCenter); - label->setWordWrap(true); - label->setStyleSheet( - "background: transparent; color: #565f73; font-size: 13px;"); - layout->addWidget(label); - layout->addStretch(); - stack->addWidget(placeholder); - return stack; -} - -// Swaps between the listing and its empty-state hint. -static void showEmptyState(QStackedWidget* stack, bool empty) { - if (stack) stack->setCurrentIndex(empty ? 1 : 0); -} - -// Quote a CSV field when it contains the separator, a quote or a newline, so -// exported lists stay importable in a spreadsheet. -static QString csvField(const QString& value) { - if (!value.contains(';') && !value.contains('"') && !value.contains('\n')) { - return value; - } - QString escaped = value; - escaped.replace(QLatin1String("\""), QLatin1String("\"\"")); - return QLatin1Char('"') + escaped + QLatin1Char('"'); -} - -// Human-readable status of a package row, shared by the table and the export. -static QString packageStatusText(const PackageInfo& pkg) { - if (pkg.installed && pkg.updateAvailable) return QStringLiteral("MAJ dispo"); - if (pkg.installed) return QStringLiteral("Installé"); - if (!pkg.repository.empty()) return QStringLiteral("Disponible"); - return QStringLiteral("—"); -} - -// MainWindow implementation -MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { - // Workers emit std::vector from another thread (QThread::run); - // without this registration the queued connection is dropped silently. - qRegisterMetaType>("std::vector"); - - // Plugin registry: pacman is compiled in; every other plugin (Flatpak, - // ...) ships as an external shared library loaded at runtime from the - // plugins/ directories (see the Plugins page for details). - m_pluginManager = new PluginManager(); - m_pluginManager->registerBuiltin( - {"pacman", "Pacman", "1.0.0", - "Gestionnaire de paquets natif d'Arch Linux", "FWS"}, - new PacmanManager()); - m_pluginManager->discoverExternal(); - - // Non-owning handle kept for sudo credential handling and pacman logs. - m_pacman = dynamic_cast(m_pluginManager->managerFor("pacman")); - - m_historyManager = new HistoryManager(); - m_updateManager = new UpdateManager(this); - - setupUI(); - setupMenuBar(); - setupTray(); - setupShortcuts(); - - // Addon plugins get the main window so they can attach their own UI - // (status-bar widgets, toolbar buttons, ...). Only enabled+available - // addons receive it. - for (IPlugin* addon : m_pluginManager->availableAddons()) { - addon->onUiReady(this); - } - - if (m_pluginManager->availableManagers().empty()) { - statusBar()->showMessage("Aucun gestionnaire de paquets disponible sur ce système."); - m_searchBar->setEnabled(false); - m_searchButton->setEnabled(false); - m_refreshButton->setEnabled(false); - m_updateAllButton->setEnabled(false); - refreshDashboard(); - return; - } - - // With per-session credentials, ask for the sudo password once, right - // after the window is shown (so the dialog has a visible parent). - if (m_pacman && m_pacman->isAvailable()) { - QTimer::singleShot(0, this, [this]() { - if (m_credentialMode == CredentialMode::AtLaunch) { - ensureCredentials(m_pluginManager->availableManagers()); - } - }); - } - - // "Tout mettre à jour" is only meaningful with a provider that can update; - // without this it stayed greyed out even when pacman was available. - for (IPackageManager* pm : m_pluginManager->availableManagers()) { - if (pm->canUpdate()) { - m_updateAllButton->setEnabled(true); - break; - } - } - - refreshDashboard(); - updateStatusBar(); - - // Check for app updates once per day (or on first launch). The delay lets - // the window appear first so the status bar message is visible. - if (m_updateManager->shouldCheck()) { - QTimer::singleShot(1500, this, &MainWindow::onCheckForUpdates); - } -} - -MainWindow::~MainWindow() { - delete m_pluginManager; // owns every provider, built-in and external - delete m_historyManager; - delete m_updateManager; -} - -void MainWindow::setupUI() { - QWidget* centralWidget = new QWidget(this); - QHBoxLayout* rootLayout = new QHBoxLayout(centralWidget); - rootLayout->setContentsMargins(0, 0, 0, 0); - rootLayout->setSpacing(0); - - setupSidebar(); - rootLayout->addWidget(m_sidebar); - - // Right column: header + stacked pages - QWidget* content = new QWidget(); - content->setObjectName("content"); - QVBoxLayout* contentLayout = new QVBoxLayout(content); - contentLayout->setContentsMargins(0, 0, 0, 0); - contentLayout->setSpacing(0); - - setupHeader(); - contentLayout->addWidget(m_headerWidget); - - m_pages = new QStackedWidget(); - setupDashboardPage(); - setupBrowsePage(); - setupHistoryPage(); - setupLogsPage(); - setupPluginsPage(); - setupCleanupPage(); - contentLayout->addWidget(m_pages, 1); - - rootLayout->addWidget(content, 1); - setCentralWidget(centralWidget); - - statusBar()->showMessage("Prêt"); - - // Tiny indeterminate bar anchored at the bottom of the window: it appears - // while install/update/remove/search operations run, without taking space - // on the content pages. - m_installProgressBar = new QProgressBar(); - m_installProgressBar->setRange(0, 0); - m_installProgressBar->setTextVisible(false); - m_installProgressBar->setFixedHeight(4); - m_installProgressBar->setFixedWidth(120); - m_installProgressBar->setVisible(false); - statusBar()->addPermanentWidget(m_installProgressBar); - - setStyleSheet( +// Everything the screens draw with. The look of the application is a single +// stylesheet applied to the window, so a screen file only describes its layout +// and its wording (see pages/ui-kit.h for the shared widgets). +static QString appStyleSheet() { + return QStringLiteral( // ---- Base ---- "QMainWindow, QWidget { background: #0d1017; color: #dbe2f0; }" // ---- Sidebar ---- @@ -603,8 +257,117 @@ void MainWindow::setupUI() { " border: 1px solid #2a3448;" " border-radius: 6px;" " padding: 4px 8px;" - "}" - ); + "}"); +} + +MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { + m_core = new AppCore(this); + + connect(m_core, &AppCore::listFinished, this, &MainWindow::onCoreListFinished); + connect(m_core, &AppCore::actionProgress, this, &MainWindow::onCoreActionProgress); + connect(m_core, &AppCore::actionFinished, this, &MainWindow::onCoreActionFinished); + connect(m_core, &AppCore::busyChanged, this, &MainWindow::onCoreBusyChanged); + connect(m_core, &AppCore::statusMessage, this, &MainWindow::onCoreStatusMessage); + connect(m_core, &AppCore::historyChanged, this, &MainWindow::onCoreHistoryChanged); + connect(m_core, &AppCore::updateCheckFinished, this, + &MainWindow::onCoreUpdateCheckFinished); + connect(m_core, &AppCore::selfUpdateFinished, this, + &MainWindow::onCoreSelfUpdateFinished); + + setupUI(); + setupMenuBar(); + setupTray(); + setupShortcuts(); + + // Addon plugins get the main window so they can attach their own UI + // (status-bar widgets, toolbar buttons, ...). Only enabled+available + // addons receive it: that part is pure UI, so it stays on this side. + for (IPlugin* addon : m_core->plugins()->availableAddons()) { + addon->onUiReady(this); + } + + if (!m_core->hasAvailableProvider()) { + statusBar()->showMessage("Aucun gestionnaire de paquets disponible sur ce système."); + // Nothing to search, list, install or clean: grey out the screens that + // need a provider rather than letting each of them fail. + for (int navId : {NavSearch, NavInstalled, NavUpdates, NavCleanup}) { + if (QAbstractButton* button = m_navGroup->button(navId)) { + button->setEnabled(false); + } + } + m_refreshButton->setEnabled(false); + m_headerUpdateAllButton->setEnabled(false); + m_dashboard->refresh(); + return; + } + + // "Tout mettre à jour" is only meaningful with a provider that can update; + // without this it stayed greyed out even when pacman was available. + m_headerUpdateAllButton->setEnabled(false); + for (IPackageManager* pm : m_core->availableProviders()) { + if (pm->canUpdate()) { + m_headerUpdateAllButton->setEnabled(true); + break; + } + } + + m_dashboard->refresh(); + updateStatusBar(); + + // With per-session credentials, ask for the sudo password once, right + // after the window is shown (so the dialog has a visible parent). + if (m_core->credentialMode() == AppCore::CredentialMode::AtLaunch) { + QTimer::singleShot(0, this, [this] { promptForSudoPassword(); }); + } + + // Check for app updates once per day (or on first launch). The delay lets + // the window appear first so the status bar message is visible. + if (m_core->shouldCheckForAppUpdate()) { + QTimer::singleShot(1500, this, &MainWindow::onCheckForUpdates); + } +} + +MainWindow::~MainWindow() = default; + +void MainWindow::setupUI() { + QWidget* centralWidget = new QWidget(this); + QHBoxLayout* rootLayout = new QHBoxLayout(centralWidget); + rootLayout->setContentsMargins(0, 0, 0, 0); + rootLayout->setSpacing(0); + + setupSidebar(); + rootLayout->addWidget(m_sidebar); + + // Right column: header + stacked screens + QWidget* content = new QWidget(); + content->setObjectName("content"); + QVBoxLayout* contentLayout = new QVBoxLayout(content); + contentLayout->setContentsMargins(0, 0, 0, 0); + contentLayout->setSpacing(0); + + setupHeader(); + contentLayout->addWidget(m_headerWidget); + + setupPages(); + contentLayout->addWidget(m_pages, 1); + + rootLayout->addWidget(content, 1); + setCentralWidget(centralWidget); + + statusBar()->showMessage("Prêt"); + + // Tiny indeterminate bar anchored at the bottom of the window: it appears + // while install/update/remove/search operations run, without taking space + // on the screens. + m_installProgressBar = new QProgressBar(); + m_installProgressBar->setRange(0, 0); + m_installProgressBar->setTextVisible(false); + m_installProgressBar->setFixedHeight(4); + m_installProgressBar->setFixedWidth(120); + m_installProgressBar->setVisible(false); + statusBar()->addPermanentWidget(m_installProgressBar); + + setStyleSheet(appStyleSheet()); } void MainWindow::setupSidebar() { @@ -720,613 +483,108 @@ void MainWindow::setupHeader() { layout->addLayout(textLayout); layout->addStretch(); - // The two actions used most often stay reachable from every page instead of - // only from the dashboard. + // The two actions used most often stay reachable from every screen instead + // of only from the dashboard. QPushButton* refreshBtn = new QPushButton("Rafraîchir"); refreshBtn->setIcon(loadIcon("refresh")); refreshBtn->setToolTip("Rafraîchir les bases de données (Ctrl+R)"); connect(refreshBtn, &QPushButton::clicked, this, &MainWindow::onRefresh); layout->addWidget(refreshBtn); - QPushButton* updateAllBtn = new QPushButton("Tout mettre à jour"); - updateAllBtn->setProperty("variant", "warning"); - updateAllBtn->setIcon(loadIcon("arrow-up")); - updateAllBtn->setToolTip("Mettre à jour tous les paquets (Ctrl+U affiche la liste)"); - connect(updateAllBtn, &QPushButton::clicked, this, &MainWindow::onUpdateAll); - layout->addWidget(updateAllBtn); + m_headerUpdateAllButton = new QPushButton("Tout mettre à jour"); + m_headerUpdateAllButton->setProperty("variant", "warning"); + m_headerUpdateAllButton->setIcon(loadIcon("arrow-up")); + m_headerUpdateAllButton->setToolTip( + "Mettre à jour tous les paquets (Ctrl+U affiche la liste)"); + connect(m_headerUpdateAllButton, &QPushButton::clicked, this, &MainWindow::onUpdateAll); + layout->addWidget(m_headerUpdateAllButton); } -void MainWindow::setupDashboardPage() { - QWidget* page = new QWidget(); - page->setObjectName("dashboardPage"); - QVBoxLayout* layout = new QVBoxLayout(page); - layout->setContentsMargins(24, 20, 24, 20); - layout->setSpacing(16); +// One screen per file under pages/: the frame only stacks them and answers +// their requests. +void MainWindow::setupPages() { + m_pages = new QStackedWidget(); - // Stat cards - QHBoxLayout* statsRow = new QHBoxLayout(); - statsRow->setSpacing(12); - statsRow->addWidget( - makeStatCard("package", "Paquets installés", "blue", &m_statInstalled)); - statsRow->addWidget( - makeStatCard("arrow-up", "Mises à jour dispo", "amber", &m_statUpdates)); - statsRow->addWidget( - makeStatCard("history", "Actions enregistrées", "cyan", &m_statHistory)); - statsRow->addWidget( - makeStatCard("tools", "Gestionnaire", "green", &m_statManager)); - layout->addLayout(statsRow); + m_dashboard = new DashboardPage(m_core); + registerPage("dashboard", NavDashboard, m_dashboard); + connect(m_dashboard, &DashboardPage::openPackage, this, &MainWindow::onOpenPackage); - // Quick actions - QFrame* actionsCard = makeCard(); - QVBoxLayout* actionsLayout = new QVBoxLayout(actionsCard); - actionsLayout->setContentsMargins(18, 16, 18, 16); - actionsLayout->setSpacing(10); + // Search, installed and updates are three sidebar entries landing on the + // same screen with a different query behind it. + m_browse = new BrowsePage(m_core); + registerPage("search", NavSearch, m_browse); + m_navIdByPage.insert("installed", NavInstalled); + m_navIdByPage.insert("updates", NavUpdates); - QLabel* actionsTitle = new QLabel("ACTIONS RAPIDES"); - actionsTitle->setObjectName("cardTitle"); - actionsLayout->addWidget(actionsTitle); + m_cleanup = new CleanupPage(m_core); + registerPage("cleanup", NavCleanup, m_cleanup); - QHBoxLayout* actionsRow = new QHBoxLayout(); - actionsRow->setSpacing(10); + m_history = new HistoryPage(m_core); + registerPage("history", NavHistory, m_history); - QPushButton* btnSearch = new QPushButton("Rechercher un paquet"); - btnSearch->setProperty("variant", "primary"); - btnSearch->setIcon(loadIcon("search")); - connect(btnSearch, &QPushButton::clicked, this, [this]() { - m_navGroup->button(NavSearch)->click(); - m_searchBar->setFocus(); - }); - actionsRow->addWidget(btnSearch); + m_logs = new LogsPage(m_core); + registerPage("logs", NavLogs, m_logs); - QPushButton* btnInstalled = new QPushButton("Paquets installés"); - btnInstalled->setIcon(loadIcon("package")); - connect(btnInstalled, &QPushButton::clicked, this, [this]() { - m_navGroup->button(NavInstalled)->click(); - }); - actionsRow->addWidget(btnInstalled); - - QPushButton* btnUpdateAll = new QPushButton("Tout mettre à jour"); - btnUpdateAll->setProperty("variant", "warning"); - btnUpdateAll->setIcon(loadIcon("arrow-up")); - connect(btnUpdateAll, &QPushButton::clicked, this, &MainWindow::onUpdateAll); - actionsRow->addWidget(btnUpdateAll); - - QPushButton* btnCleanup = new QPushButton("Nettoyer le système"); - btnCleanup->setIcon(loadIcon("broom")); - btnCleanup->setToolTip("Purger les paquets inutilisés et vider les caches"); - connect(btnCleanup, &QPushButton::clicked, this, [this]() { - m_navGroup->button(NavCleanup)->click(); - }); - actionsRow->addWidget(btnCleanup); - - QPushButton* btnRefresh = new QPushButton("Rafraîchir les sources"); - btnRefresh->setProperty("variant", "info"); - btnRefresh->setIcon(loadIcon("refresh")); - connect(btnRefresh, &QPushButton::clicked, this, &MainWindow::onRefresh); - actionsRow->addWidget(btnRefresh); - - QPushButton* btnLogs = new QPushButton("Logs pacman"); - btnLogs->setIcon(loadIcon("logs")); - connect(btnLogs, &QPushButton::clicked, this, [this]() { - m_navGroup->button(NavLogs)->click(); - }); - actionsRow->addWidget(btnLogs); - - actionsRow->addStretch(); - actionsLayout->addLayout(actionsRow); - layout->addWidget(actionsCard); - - // Recent activity - QFrame* recentCard = makeCard(); - QVBoxLayout* recentLayout = new QVBoxLayout(recentCard); - recentLayout->setContentsMargins(18, 16, 18, 12); - recentLayout->setSpacing(8); - - QLabel* recentTitle = new QLabel("ACTIVITÉ RÉCENTE"); - recentTitle->setObjectName("cardTitle"); - recentLayout->addWidget(recentTitle); - - m_recentList = new QListWidget(); - m_recentList->setObjectName("recentList"); - m_recentList->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - m_recentList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - m_recentList->setFocusPolicy(Qt::NoFocus); - // Clicking an entry opens that package's install/remove/update details from the installed list. - connect(m_recentList, &QListWidget::itemClicked, - this, &MainWindow::onRecentActivityClicked); - recentLayout->addWidget(m_recentList, 1); - - layout->addWidget(recentCard, 1); - - m_pages->addWidget(page); + m_plugins = new PluginsPage(m_core); + registerPage("plugins", NavPlugins, m_plugins); } -void MainWindow::setupBrowsePage() { - QWidget* page = new QWidget(); - QVBoxLayout* layout = new QVBoxLayout(page); - layout->setContentsMargins(24, 20, 24, 20); - layout->setSpacing(12); - - // Search row (visible in search mode only) - m_searchRowWidget = new QWidget(); - QHBoxLayout* searchRow = new QHBoxLayout(m_searchRowWidget); - searchRow->setContentsMargins(0, 0, 0, 0); - searchRow->setSpacing(10); - - m_searchBar = new QLineEdit(); - m_searchBar->setPlaceholderText("Rechercher un paquet (ex : firefox)..."); - m_searchBar->setMinimumHeight(40); - m_searchBar->addAction(loadIcon("search"), QLineEdit::LeadingPosition); - connect(m_searchBar, &QLineEdit::returnPressed, this, &MainWindow::onSearch); - searchRow->addWidget(m_searchBar, 1); - - m_searchButton = new QPushButton("Rechercher"); - m_searchButton->setProperty("variant", "primary"); - m_searchButton->setMinimumHeight(40); - m_searchButton->setMinimumWidth(130); - connect(m_searchButton, &QPushButton::clicked, this, &MainWindow::onSearch); - searchRow->addWidget(m_searchButton); - - layout->addWidget(m_searchRowWidget); - - // Filter row (visible in installed mode only) - m_filterRowWidget = new QWidget(); - QHBoxLayout* filterRow = new QHBoxLayout(m_filterRowWidget); - filterRow->setContentsMargins(0, 0, 0, 0); - filterRow->setSpacing(10); - - m_filterBar = new QLineEdit(); - m_filterBar->setPlaceholderText("Filtrer par nom..."); - m_filterBar->setMinimumHeight(36); - m_filterBar->addAction(loadIcon("filter"), QLineEdit::LeadingPosition); - m_filterBar->setClearButtonEnabled(true); - connect(m_filterBar, &QLineEdit::textChanged, this, &MainWindow::onInstalledFilterChanged); - filterRow->addWidget(m_filterBar, 1); - - QLabel* filterHint = new QLabel("Filtre local, instantané"); - filterHint->setStyleSheet("font-size: 12px; color: #7a8299;"); - filterRow->addWidget(filterHint); - - m_filterRowWidget->setVisible(false); - layout->addWidget(m_filterRowWidget); - - // Thin progress bar - m_progressBar = new QProgressBar(); - m_progressBar->setVisible(false); - m_progressBar->setFixedHeight(6); - m_progressBar->setTextVisible(false); - layout->addWidget(m_progressBar); - - // Action toolbar - QHBoxLayout* actionBar = new QHBoxLayout(); - actionBar->setSpacing(8); - - m_installButton = new QPushButton("Installer"); - m_installButton->setProperty("variant", "success"); - m_installButton->setIcon(loadIcon("package")); - m_installButton->setEnabled(false); - connect(m_installButton, &QPushButton::clicked, this, &MainWindow::onInstall); - actionBar->addWidget(m_installButton); - - m_removeButton = new QPushButton("Supprimer"); - m_removeButton->setProperty("variant", "danger"); - m_removeButton->setIcon(loadIcon("trash")); - m_removeButton->setEnabled(false); - connect(m_removeButton, &QPushButton::clicked, this, &MainWindow::onRemove); - actionBar->addWidget(m_removeButton); - - m_updateButton = new QPushButton("Mettre à jour"); - m_updateButton->setProperty("variant", "warning"); - m_updateButton->setIcon(loadIcon("refresh")); - m_updateButton->setEnabled(false); - connect(m_updateButton, &QPushButton::clicked, this, &MainWindow::onUpdate); - actionBar->addWidget(m_updateButton); - - m_updateAllButton = new QPushButton("Tout mettre à jour"); - m_updateAllButton->setProperty("variant", "info"); - m_updateAllButton->setIcon(loadIcon("arrow-up")); - m_updateAllButton->setEnabled(false); - connect(m_updateAllButton, &QPushButton::clicked, this, &MainWindow::onUpdateAll); - actionBar->addWidget(m_updateAllButton); - - QPushButton* exportBtn = new QPushButton("Exporter"); - exportBtn->setToolTip("Exporter la liste affichée en CSV"); - connect(exportBtn, &QPushButton::clicked, this, &MainWindow::onExportPackageList); - actionBar->addWidget(exportBtn); - - actionBar->addStretch(); - - m_resultCount = new QLabel(""); - m_resultCount->setStyleSheet("font-size: 12px; color: #7a8299; font-weight: 600;"); - actionBar->addWidget(m_resultCount); - - layout->addLayout(actionBar); - - // Splitter: package table | details - QSplitter* splitter = new QSplitter(Qt::Horizontal); - splitter->setHandleWidth(10); - - // Left card: package table - QFrame* listCard = makeCard(); - QVBoxLayout* listLayout = new QVBoxLayout(listCard); - listLayout->setContentsMargins(8, 8, 8, 8); - listLayout->setSpacing(6); - - QLabel* listHeader = new QLabel("PAQUETS"); - listHeader->setObjectName("cardTitle"); - listLayout->addWidget(listHeader); - - m_packageTable = new QTableWidget(0, 5); - m_packageTable->setHorizontalHeaderLabels( - {"Nom", "Version", "Dépôt", "Fournisseur", "Statut"}); - m_packageTable->verticalHeader()->setVisible(false); - m_packageTable->setSelectionBehavior(QAbstractItemView::SelectRows); - m_packageTable->setSelectionMode(QAbstractItemView::SingleSelection); - m_packageTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - m_packageTable->setShowGrid(false); - m_packageTable->setAlternatingRowColors(true); - m_packageTable->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - m_packageTable->verticalHeader()->setDefaultSectionSize(36); - m_packageTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); - m_packageTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - m_packageTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); - m_packageTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); - m_packageTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents); - connect(m_packageTable, &QTableWidget::currentCellChanged, this, - [this](int currentRow, int, int, int) { onPackageSelected(currentRow); }); - - m_packageTableStack = withEmptyState( - m_packageTable, - "Aucun paquet à afficher.\nLancez une recherche ou ouvrez la liste des " - "paquets installés."); - listLayout->addWidget(m_packageTableStack); - splitter->addWidget(listCard); - - // Right card: package details - QFrame* detailsCard = makeCard(); - QVBoxLayout* detailsLayout = new QVBoxLayout(detailsCard); - detailsLayout->setContentsMargins(20, 18, 20, 18); - detailsLayout->setSpacing(10); - - m_packageName = new QLabel("Sélectionnez un paquet"); - m_packageName->setWordWrap(true); - m_packageName->setStyleSheet("font-size: 22px; font-weight: 700; color: #e8edf9; background: transparent;"); - detailsLayout->addWidget(m_packageName); - - m_packageVersion = new QLabel(""); - m_packageVersion->setStyleSheet("font-size: 13px; color: #7a8299; background: transparent;"); - detailsLayout->addWidget(m_packageVersion); - - QHBoxLayout* metaRow = new QHBoxLayout(); - metaRow->setSpacing(8); - - m_packageRepo = new QLabel("—"); - m_packageRepo->setStyleSheet( - "background: #1c2434; color: #7a8299; border-radius: 10px;" - "padding: 3px 12px; font-size: 12px;"); - metaRow->addWidget(m_packageRepo); - - m_packageSize = new QLabel("—"); - m_packageSize->setStyleSheet( - "background: #1c2434; color: #7a8299; border-radius: 10px;" - "padding: 3px 12px; font-size: 12px;"); - metaRow->addWidget(m_packageSize); - - m_packageProvider = new QLabel("—"); - m_packageProvider->setStyleSheet( - "background: #1c2434; color: #7a8299; border-radius: 10px;" - "padding: 3px 12px; font-size: 12px;"); - metaRow->addWidget(m_packageProvider); - - metaRow->addStretch(); - detailsLayout->addLayout(metaRow); - - QFrame* separator = new QFrame(); - separator->setFrameShape(QFrame::HLine); - separator->setStyleSheet("color: #232b3a; background: #232b3a; max-height: 1px; border: none;"); - detailsLayout->addWidget(separator); - - m_packageDescription = new QLabel(""); - m_packageDescription->setWordWrap(true); - m_packageDescription->setAlignment(Qt::AlignTop | Qt::AlignLeft); - m_packageDescription->setStyleSheet( - "font-size: 14px; color: #c8d3f5; background: transparent;"); - detailsLayout->addWidget(m_packageDescription, 1); - - detailsLayout->addStretch(); - splitter->addWidget(detailsCard); - - splitter->setSizes({560, 420}); - layout->addWidget(splitter, 1); - +void MainWindow::registerPage(const QString& id, int navId, Page* page) { + m_pageById.insert(id, page); + m_navIdByPage.insert(id, navId); m_pages->addWidget(page); + + connect(page, &Page::requestStart, this, &MainWindow::onStartRequested); + connect(page, &Page::message, this, &MainWindow::onPageMessage); + connect(page, &Page::goToPage, this, &MainWindow::onOpenPage); } -void MainWindow::setupHistoryPage() { - QWidget* page = new QWidget(); - QVBoxLayout* layout = new QVBoxLayout(page); - layout->setContentsMargins(24, 20, 24, 20); - layout->setSpacing(12); - - QHBoxLayout* filterRow = new QHBoxLayout(); - filterRow->setSpacing(10); - - QLabel* filterLabel = new QLabel("Filtrer :"); - filterLabel->setStyleSheet("font-size: 13px; color: #7a8299;"); - filterRow->addWidget(filterLabel); - - m_historyFilter = new QComboBox(); - m_historyFilter->addItems({"Toutes les actions", "Installations", "Suppressions", - "Mises à jour", "Nettoyages"}); - connect(m_historyFilter, QOverload::of(&QComboBox::currentIndexChanged), - this, &MainWindow::onHistoryFilterChanged); - filterRow->addWidget(m_historyFilter); - - filterRow->addStretch(); - - m_historyCount = new QLabel(""); - m_historyCount->setStyleSheet("font-size: 12px; color: #7a8299; font-weight: 600;"); - filterRow->addWidget(m_historyCount); - - layout->addLayout(filterRow); - - m_historyTable = new QTableWidget(0, 5); - m_historyTable->setHorizontalHeaderLabels( - {"Date", "Action", "Paquet", "Gestionnaire", "Statut"}); - m_historyTable->verticalHeader()->setVisible(false); - m_historyTable->setSelectionBehavior(QAbstractItemView::SelectRows); - m_historyTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - m_historyTable->setShowGrid(false); - m_historyTable->setAlternatingRowColors(true); - m_historyTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); - m_historyTable->verticalHeader()->setDefaultSectionSize(34); - layout->addWidget(m_historyTable, 1); - - QHBoxLayout* buttonBar = new QHBoxLayout(); - buttonBar->addStretch(); - - QPushButton* exportBtn = new QPushButton("Exporter (CSV)"); - exportBtn->setToolTip("Enregistrer l'historique affiché dans un fichier CSV"); - connect(exportBtn, &QPushButton::clicked, this, &MainWindow::onExportHistory); - buttonBar->addWidget(exportBtn); - - QPushButton* clearBtn = new QPushButton("Effacer l'historique"); - clearBtn->setProperty("variant", "danger"); - clearBtn->setIcon(loadIcon("trash")); - connect(clearBtn, &QPushButton::clicked, this, &MainWindow::onClearHistory); - buttonBar->addWidget(clearBtn); - - layout->addLayout(buttonBar); - - m_pages->addWidget(page); +Page* MainWindow::currentPage() const { + return qobject_cast(m_pages->currentWidget()); } -void MainWindow::setupLogsPage() { - QWidget* page = new QWidget(); - QVBoxLayout* layout = new QVBoxLayout(page); - layout->setContentsMargins(24, 20, 24, 20); - layout->setSpacing(12); - - // Filter row: /var/log/pacman.log can be huge, so the content is read once - // into m_logsRaw and filtered in memory (no re-read per keystroke). - QHBoxLayout* filterRow = new QHBoxLayout(); - filterRow->setSpacing(10); - - m_logsFilter = new QLineEdit(); - m_logsFilter->setPlaceholderText("Filtrer les logs (paquet, action, date)..."); - m_logsFilter->setMinimumHeight(36); - m_logsFilter->setClearButtonEnabled(true); - m_logsFilter->addAction(loadIcon("filter"), QLineEdit::LeadingPosition); - connect(m_logsFilter, &QLineEdit::textChanged, - this, &MainWindow::onLogsFilterChanged); - filterRow->addWidget(m_logsFilter, 1); - - layout->addLayout(filterRow); - - m_logsText = new QTextEdit(); - m_logsText->setReadOnly(true); - layout->addWidget(m_logsText, 1); - - QHBoxLayout* buttonBar = new QHBoxLayout(); - buttonBar->addStretch(); - - QPushButton* refreshBtn = new QPushButton("Recharger"); - refreshBtn->setIcon(loadIcon("refresh")); - connect(refreshBtn, &QPushButton::clicked, this, &MainWindow::onRefreshLogs); - buttonBar->addWidget(refreshBtn); - - layout->addLayout(buttonBar); - - m_pages->addWidget(page); +void MainWindow::updatePageTitle() { + Page* page = currentPage(); + if (!page) return; + m_headerTitle->setText(page->navTitle()); + m_headerSubtitle->setText(page->navSubtitle()); } -// The Plugins page acts as the add-on store: it lists every plugin known to -// the application (built-in and external — package-manager providers and -// generic addons), lets the user enable/disable them, and rescans the plugin -// directories for new ones. -void MainWindow::setupPluginsPage() { - QWidget* page = new QWidget(); - QVBoxLayout* layout = new QVBoxLayout(page); - layout->setContentsMargins(24, 20, 24, 20); - layout->setSpacing(12); - - QFrame* hintCard = makeCard(); - QVBoxLayout* hintLayout = new QVBoxLayout(hintCard); - hintLayout->setContentsMargins(18, 16, 18, 16); - hintLayout->setSpacing(4); - - QLabel* hintTitle = new QLabel("AJOUTER UN PLUGIN"); - hintTitle->setObjectName("cardTitle"); - hintLayout->addWidget(hintTitle); - - QLabel* hint = new QLabel( - "Pacman est intégré et le plugin Flatpak est livré par défaut. Si un " - "fournisseur est « Indisponible », sélectionnez-le puis cliquez sur " - "« Installer l'outil » pour l'installer via pacman. Un plugin peut être " - "un gestionnaire de paquets (apt, dnf, ...) ou n'importe quelle extension " - "(addon graphique, helper, ...) tant qu'il est écrit en C++ : compilez une " - "bibliothèque partagée (voir plugins/example-provider et " - "plugins/example-addon) et déposez-la dans " - "~/.local/share/PacManager/plugins/ ou dans le dossier plugins/ à côté de " - "l'exécutable, puis cliquez sur « Recharger »."); - hint->setWordWrap(true); - hint->setStyleSheet("font-size: 12px; color: #7a8299;"); - hintLayout->addWidget(hint); - - layout->addWidget(hintCard); - - m_pluginTable = new QTableWidget(0, 5); - m_pluginTable->setHorizontalHeaderLabels( - {"Plugin", "Type", "Version", "Auteur", "Statut"}); - m_pluginTable->verticalHeader()->setVisible(false); - m_pluginTable->setSelectionBehavior(QAbstractItemView::SelectRows); - m_pluginTable->setSelectionMode(QAbstractItemView::SingleSelection); - m_pluginTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - m_pluginTable->setShowGrid(false); - m_pluginTable->setAlternatingRowColors(true); - m_pluginTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); - m_pluginTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - m_pluginTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); - m_pluginTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); - m_pluginTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents); - m_pluginTable->verticalHeader()->setDefaultSectionSize(36); - connect(m_pluginTable, &QTableWidget::currentCellChanged, this, - [this](int currentRow, int, int, int) { onPluginTableSelected(currentRow); }); - layout->addWidget(m_pluginTable, 1); - - m_pluginDescription = new QLabel(""); - m_pluginDescription->setWordWrap(true); - m_pluginDescription->setStyleSheet( - "font-size: 13px; color: #c8d3f5; background: transparent; padding: 2px 4px;"); - layout->addWidget(m_pluginDescription); - - QHBoxLayout* buttonBar = new QHBoxLayout(); - buttonBar->addStretch(); - - // Installs the OS package backing a provider whose tool is missing - // (e.g. pacman -S flatpak), then rescans so it becomes available. - m_pluginInstallButton = new QPushButton("Installer l'outil"); - m_pluginInstallButton->setProperty("variant", "primary"); - m_pluginInstallButton->setEnabled(false); - m_pluginInstallButton->setVisible(false); - connect(m_pluginInstallButton, &QPushButton::clicked, - this, &MainWindow::onInstallPluginTool); - buttonBar->addWidget(m_pluginInstallButton); - - m_pluginToggleButton = new QPushButton("Activer"); - m_pluginToggleButton->setEnabled(false); - connect(m_pluginToggleButton, &QPushButton::clicked, this, &MainWindow::onTogglePlugin); - buttonBar->addWidget(m_pluginToggleButton); - - QPushButton* rescanButton = new QPushButton("Recharger"); - rescanButton->setIcon(loadIcon("refresh")); - rescanButton->setToolTip("Rescanner les dossiers de plugins"); - connect(rescanButton, &QPushButton::clicked, this, &MainWindow::onRescanPlugins); - buttonBar->addWidget(rescanButton); - - layout->addLayout(buttonBar); - - m_pages->addWidget(page); +void MainWindow::updateStatusBar() { + const int providers = static_cast(m_core->availableProviders().size()); + if (providers == 0) { + statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); + return; + } + QString info = QString( + "%1 gestionnaire(s) actif(s) | Paquets affichés : %2 | Actions enregistrées : %3") + .arg(providers) + .arg(m_browse->resultCount()) + .arg(m_core->historyCount()); + statusBar()->showMessage(info); } -// Maintenance page: lists what a cleanup can reclaim (orphans and legacy -// packages reported by every provider) and frees the disk space the providers -// hold in their caches. Nothing runs until the user asks for it: the candidate -// list is only built on demand, since both queries cost a pacman call. -void MainWindow::setupCleanupPage() { - QWidget* page = new QWidget(); - QVBoxLayout* layout = new QVBoxLayout(page); - layout->setContentsMargins(24, 20, 24, 20); - layout->setSpacing(12); +void MainWindow::setUpdatesBadge(int count) { + if (!m_navUpdatesButton) return; - QFrame* hintCard = makeCard(); - QVBoxLayout* hintLayout = new QVBoxLayout(hintCard); - hintLayout->setContentsMargins(18, 16, 18, 16); - hintLayout->setSpacing(4); + m_navUpdatesButton->setText(count > 0 + ? QString("Mises à jour · %1").arg(count) + : QString("Mises à jour")); - QLabel* hintTitle = new QLabel("PAQUETS INUTILISÉS ET LEGACY"); - hintTitle->setObjectName("cardTitle"); - hintLayout->addWidget(hintTitle); + // A dynamic property only takes effect once the style is re-applied, so it + // is only touched when it actually changes. + const bool highlighted = count > 0; + if (m_navUpdatesButton->property("highlighted").toBool() == highlighted) return; + m_navUpdatesButton->setProperty("highlighted", highlighted); + m_navUpdatesButton->style()->unpolish(m_navUpdatesButton); + m_navUpdatesButton->style()->polish(m_navUpdatesButton); +} - QLabel* hint = new QLabel( - "Les orphelins ont été installés comme dépendances et ne sont " - "plus requis par aucun paquet : ils peuvent être supprimés sans risque. " - "Les paquets étrangers viennent de l'AUR ou d'une compilation " - "manuelle : vérifiez-les un par un avant de les supprimer."); - hint->setTextFormat(Qt::RichText); - hint->setWordWrap(true); - hint->setStyleSheet("font-size: 12px; color: #7a8299;"); - hintLayout->addWidget(hint); - - layout->addWidget(hintCard); - - m_cleanupTable = new QTableWidget(0, 4); - m_cleanupTable->setHorizontalHeaderLabels( - {"Paquet", "Version", "Type", "Fournisseur"}); - m_cleanupTable->verticalHeader()->setVisible(false); - m_cleanupTable->setSelectionBehavior(QAbstractItemView::SelectRows); - m_cleanupTable->setSelectionMode(QAbstractItemView::SingleSelection); - m_cleanupTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - m_cleanupTable->setShowGrid(false); - m_cleanupTable->setAlternatingRowColors(true); - m_cleanupTable->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - m_cleanupTable->verticalHeader()->setDefaultSectionSize(36); - m_cleanupTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); - m_cleanupTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - m_cleanupTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); - m_cleanupTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); - connect(m_cleanupTable, &QTableWidget::currentCellChanged, this, - [this](int currentRow, int, int, int) { onCleanupSelectionChanged(currentRow); }); - m_cleanupTableStack = withEmptyState( - m_cleanupTable, - "Rien à nettoyer pour le moment.\nLancez une analyse pour vérifier."); - layout->addWidget(m_cleanupTableStack, 1); - - QHBoxLayout* buttonBar = new QHBoxLayout(); - buttonBar->setSpacing(8); - - QPushButton* scanButton = new QPushButton("Analyser"); - scanButton->setProperty("variant", "primary"); - scanButton->setIcon(loadIcon("search")); - scanButton->setToolTip("Rechercher les paquets inutilisés et legacy"); - connect(scanButton, &QPushButton::clicked, this, &MainWindow::onCleanupScan); - buttonBar->addWidget(scanButton); - - m_cleanupRemoveOrphansButton = new QPushButton("Supprimer les orphelins"); - m_cleanupRemoveOrphansButton->setProperty("variant", "danger"); - m_cleanupRemoveOrphansButton->setIcon(loadIcon("trash")); - m_cleanupRemoveOrphansButton->setEnabled(false); - m_cleanupRemoveOrphansButton->setToolTip( - "Supprimer tous les paquets que plus rien ne requiert"); - connect(m_cleanupRemoveOrphansButton, &QPushButton::clicked, - this, &MainWindow::onRemoveCleanupOrphans); - buttonBar->addWidget(m_cleanupRemoveOrphansButton); - - m_cleanupRemoveSelectionButton = new QPushButton("Supprimer la sélection"); - m_cleanupRemoveSelectionButton->setIcon(loadIcon("trash")); - m_cleanupRemoveSelectionButton->setEnabled(false); - connect(m_cleanupRemoveSelectionButton, &QPushButton::clicked, - this, &MainWindow::onRemoveCleanupSelection); - buttonBar->addWidget(m_cleanupRemoveSelectionButton); - - m_cleanupCacheButton = new QPushButton("Vider les caches"); - m_cleanupCacheButton->setProperty("variant", "warning"); - m_cleanupCacheButton->setIcon(loadIcon("broom")); - m_cleanupCacheButton->setToolTip( - "Purger le cache de paquets (paccache / pacman -Sc) et les runtimes " - "Flatpak inutilisés"); - connect(m_cleanupCacheButton, &QPushButton::clicked, this, &MainWindow::onCleanCaches); - buttonBar->addWidget(m_cleanupCacheButton); - - buttonBar->addStretch(); - - m_cleanupCount = new QLabel(""); - m_cleanupCount->setStyleSheet("font-size: 12px; color: #7a8299; font-weight: 600;"); - buttonBar->addWidget(m_cleanupCount); - - layout->addLayout(buttonBar); - - m_pages->addWidget(page); +void MainWindow::notifyUpdatesAvailable(int count) { + if (!m_tray || count <= 0) return; + m_tray->showMessage("PacManager", + QString("%1 mise(s) à jour disponible(s)").arg(count), + QSystemTrayIcon::Information, 5000); } void MainWindow::setupMenuBar() { @@ -1347,34 +605,37 @@ void MainWindow::setupMenuBar() { "QMenu::separator { height: 1px; background: #2a3448; margin: 6px 8px; }" ); + auto goTo = [this](int navId) { + if (QAbstractButton* button = m_navGroup->button(navId)) button->click(); + }; + QMenu* fileMenu = menuBar->addMenu("Fichier"); - fileMenu->addAction("Exporter la liste affichée...", this, - &MainWindow::onExportPackageList); - fileMenu->addAction("Exporter l'historique...", this, &MainWindow::onExportHistory); + fileMenu->addAction("Exporter la liste affichée...", this, [this] { + m_browse->exportCsv(); + }); + fileMenu->addAction("Exporter l'historique...", this, [this] { + m_history->exportCsv(); + }); fileMenu->addSeparator(); fileMenu->addAction("Quitter", this, &QWidget::close); QMenu* toolsMenu = menuBar->addMenu("Outils"); - toolsMenu->addAction("Tableau de bord", this, - [this]() { m_navGroup->button(NavDashboard)->click(); }); - toolsMenu->addAction("Rechercher", this, [this]() { + toolsMenu->addAction("Tableau de bord", this, [this, goTo] { goTo(NavDashboard); }); + toolsMenu->addAction("Rechercher", this, [this] { m_navGroup->button(NavSearch)->click(); - m_searchBar->setFocus(); + m_browse->focusSearch(); }); - toolsMenu->addAction("Paquets installés", this, - [this]() { m_navGroup->button(NavInstalled)->click(); }); - toolsMenu->addAction("Mises à jour", this, - [this]() { m_navGroup->button(NavUpdates)->click(); }); - toolsMenu->addAction("Nettoyage", this, - [this]() { m_navGroup->button(NavCleanup)->click(); }); - toolsMenu->addAction("Historique", this, - [this]() { m_navGroup->button(NavHistory)->click(); }); - toolsMenu->addAction("Logs pacman", this, - [this]() { m_navGroup->button(NavLogs)->click(); }); - toolsMenu->addAction("Plugins", this, - [this]() { m_navGroup->button(NavPlugins)->click(); }); + toolsMenu->addAction("Paquets installés", this, [this, goTo] { goTo(NavInstalled); }); + toolsMenu->addAction("Mises à jour", this, [this, goTo] { goTo(NavUpdates); }); + toolsMenu->addAction("Nettoyage", this, [this, goTo] { goTo(NavCleanup); }); + toolsMenu->addAction("Historique", this, [this, goTo] { goTo(NavHistory); }); + toolsMenu->addAction("Logs pacman", this, [this, goTo] { goTo(NavLogs); }); + toolsMenu->addAction("Plugins", this, [this, goTo] { goTo(NavPlugins); }); toolsMenu->addSeparator(); - toolsMenu->addAction("Prévisualiser les mises à jour", this, &MainWindow::onPreviewUpdates); + toolsMenu->addAction("Prévisualiser les mises à jour", this, [this, goTo] { + goTo(NavUpdates); + statusBar()->showMessage("Prévisualisation des mises à jour disponibles"); + }); toolsMenu->addAction("Rafraîchir les sources", this, &MainWindow::onRefresh); QMenu* settingsMenu = menuBar->addMenu("Paramètres"); @@ -1395,16 +656,14 @@ void MainWindow::setupMenuBar() { m_credLaunchAction->setToolTip("Demande le mot de passe une seule fois, au lancement"); credGroup->addAction(m_credLaunchAction); - m_credentialMode = (m_settings.value("credentials/mode", "each").toString() == "launch") - ? CredentialMode::AtLaunch - : CredentialMode::EachTime; - (m_credentialMode == CredentialMode::AtLaunch ? m_credLaunchAction - : m_credEachTimeAction)->setChecked(true); + const bool atLaunch = + m_core->credentialMode() == AppCore::CredentialMode::AtLaunch; + (atLaunch ? m_credLaunchAction : m_credEachTimeAction)->setChecked(true); connect(m_credEachTimeAction, &QAction::triggered, this, - [this]() { applyCredentialMode(CredentialMode::EachTime); }); + [this]() { applyCredentialMode(AppCore::CredentialMode::EachTime); }); connect(m_credLaunchAction, &QAction::triggered, this, - [this]() { applyCredentialMode(CredentialMode::AtLaunch); }); + [this]() { applyCredentialMode(AppCore::CredentialMode::AtLaunch); }); QMenu* helpMenu = menuBar->addMenu("Aide"); helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates); @@ -1417,48 +676,162 @@ void MainWindow::setupMenuBar() { }); } -void MainWindow::applyCredentialMode(CredentialMode mode) { - m_credentialMode = mode; - m_settings.setValue("credentials/mode", - mode == CredentialMode::AtLaunch ? "launch" : "each"); +// System tray: optional, only created when the desktop actually provides one. +// Offers quick access to the pending updates from outside the window. +void MainWindow::setupTray() { + if (!QSystemTrayIcon::isSystemTrayAvailable()) return; - if (mode == CredentialMode::EachTime) { - // Each operation must re-authenticate: never keep the password around. - if (m_pacman) m_pacman->clearPassword(); - statusBar()->showMessage("Identifiants demandés à chaque opération."); - } else { - // Per-session credentials: prompt once now so operations don't re-ask. - ensureCredentials(m_pluginManager->availableManagers()); - statusBar()->showMessage("Identifiants enregistrés pour la session."); - } + m_tray = new QSystemTrayIcon(loadIcon("package"), this); + m_tray->setToolTip("PacManager"); + + QMenu* menu = new QMenu(this); + menu->addAction("Afficher PacManager", this, [this]() { + showNormal(); + raise(); + activateWindow(); + }); + menu->addSeparator(); + menu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates); + menu->addAction("Prévisualiser les mises à jour", this, [this]() { + m_navGroup->button(NavUpdates)->click(); + }); + menu->addAction("Tout mettre à jour", this, &MainWindow::onUpdateAll); + menu->addSeparator(); + menu->addAction("Quitter", this, &QWidget::close); + m_tray->setContextMenu(menu); + + connect(m_tray, &QSystemTrayIcon::activated, this, &MainWindow::onTrayActivated); + m_tray->show(); } -// Makes sure a sudo password is available before a privileged operation, -// prompting the user on the UI thread when needed. Only providers that run -// through sudo (pacman) trigger the prompt. Returns false if the user -// cancelled, in which case the operation must not start. -bool MainWindow::ensureCredentials(const std::vector& providers) { - bool needsPassword = false; - for (IPackageManager* pm : providers) { - if (pm && pm->requiresPassword()) { - needsPassword = true; +// Keyboard shortcuts for the actions used most often. +void MainWindow::setupShortcuts() { + auto bind = [this](const QKeySequence& key, const std::function& action) { + QShortcut* shortcut = new QShortcut(key, this); + shortcut->setContext(Qt::WindowShortcut); + connect(shortcut, &QShortcut::activated, this, action); + }; + + bind(QKeySequence::Find, [this]() { + m_navGroup->button(NavSearch)->click(); + m_browse->focusSearch(); + }); + bind(QKeySequence::Refresh, [this]() { onRefresh(); }); + bind(QKeySequence(Qt::Key_F5), [this]() { onRefresh(); }); + bind(QKeySequence(QStringLiteral("Ctrl+U")), [this]() { + m_navGroup->button(NavUpdates)->click(); + }); + bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() { m_browse->exportCsv(); }); + bind(QKeySequence::Quit, [this]() { close(); }); +} + +// --------------------------------------------------------------------------- +// Navigation and page requests +// --------------------------------------------------------------------------- + +void MainWindow::onNavChanged(int id) { + qCDebug(pacmgrUi) << "navigate to page" << id; + + switch (id) { + case NavDashboard: + m_pages->setCurrentWidget(m_dashboard); + m_dashboard->refresh(); + break; + case NavSearch: + m_pages->setCurrentWidget(m_browse); + m_browse->showSearch(); + break; + case NavInstalled: + m_pages->setCurrentWidget(m_browse); + m_browse->showInstalled(); + break; + case NavUpdates: + m_pages->setCurrentWidget(m_browse); + m_browse->showUpdates(); + break; + case NavCleanup: + m_pages->setCurrentWidget(m_cleanup); + m_cleanup->refresh(); + break; + case NavHistory: + m_pages->setCurrentWidget(m_history); + m_history->refresh(); + break; + case NavLogs: + m_pages->setCurrentWidget(m_logs); + m_logs->refresh(); + break; + case NavPlugins: + m_pages->setCurrentWidget(m_plugins); + m_plugins->refresh(); + break; + default: break; - } - } - if (!needsPassword) return true; - if (!m_pacman || !m_pacman->isAvailable()) return false; - if (system("which sudo > /dev/null 2>&1") != 0) { - statusBar()->showMessage("sudo n'est pas installé sur ce système."); - return false; } - // Per-session mode: reuse the password captured at launch. - if (m_credentialMode == CredentialMode::AtLaunch && m_pacman->hasPassword()) { - return true; + updatePageTitle(); +} + +void MainWindow::onOpenPage(const QString& pageId) { + const int navId = m_navIdByPage.value(pageId, -1); + if (navId < 0) return; + if (QAbstractButton* button = m_navGroup->button(navId)) button->click(); +} + +// Navigates to the Installed screen and opens the package the user clicked in +// the dashboard activity list. +void MainWindow::onOpenPackage(const QString& name) { + if (name.isEmpty()) return; + + m_browse->selectOnNextLoad(name); + if (QAbstractButton* button = m_navGroup->button(NavInstalled)) button->click(); + statusBar()->showMessage(QString("Ouverture des détails de %1...").arg(name)); +} + +void MainWindow::onPageMessage(const QString& text) { + statusBar()->showMessage(text); +} + +void MainWindow::onStartRequested(const AppCore::StartResult& result, const QString& title) { + handleStartResult(result, title); +} + +void MainWindow::onRefresh() { + handleStartResult(m_core->refresh(), "Rafraîchissement des sources"); +} + +void MainWindow::onUpdateAll() { + handleStartResult(m_core->updateAll(), "Mise à jour globale"); +} + +void MainWindow::onTrayActivated(QSystemTrayIcon::ActivationReason reason) { + // A click on the icon brings the window back from the background. + if (reason != QSystemTrayIcon::Trigger && reason != QSystemTrayIcon::DoubleClick) { + return; } + showNormal(); + raise(); + activateWindow(); +} + +// --------------------------------------------------------------------------- +// Credentials, database lock and failure reporting +// --------------------------------------------------------------------------- + +void MainWindow::applyCredentialMode(AppCore::CredentialMode mode) { + m_core->setCredentialMode(mode); + // Per-session credentials: prompt once now so operations don't re-ask. The + // core reports the mode change in the status bar itself. + if (mode == AppCore::CredentialMode::AtLaunch) promptForSudoPassword(); +} + +// The core knows *when* a password is needed (it owns the credential state and +// the sudo pipeline); the frame only owns the dialog. +bool MainWindow::promptForSudoPassword() { + if (m_core->hasSudoPassword()) return true; bool ok = false; - QString password = QInputDialog::getText( + const QString password = QInputDialog::getText( this, "Authentification", "Mot de passe administrateur (sudo) :", QLineEdit::Password, QString(), &ok); @@ -1467,50 +840,59 @@ bool MainWindow::ensureCredentials(const std::vector& provider return false; } - m_pacman->setPassword(password.toStdString()); + m_core->setSudoPassword(password); return true; } -// Manager owning a package: the one tagged in the package, or the first -// available provider when the tag is missing or unknown. -IPackageManager* MainWindow::providerFor(const std::string& id) const { - if (const auto* entry = m_pluginManager->findAvailable(id)) { - return entry->manager; - } - auto available = m_pluginManager->availableManagers(); - return available.empty() ? nullptr : available.front(); -} - -bool MainWindow::showProviderError(const QString& title, IPackageManager* provider) { - if (!provider) return false; - const std::string err = provider->lastError(); - if (err.empty()) return false; - +void MainWindow::showActionError(const QString& title, const QString& error, bool locked) { // A locked database is the one failure the app can resolve on its own, so it // gets its own dialog instead of a message the user has to act on by hand. - const bool lockFailure = - (provider == m_pacman && m_pacman && m_pacman->lastErrorWasLock()) - || PacmanManager::dbLocked(err); - if (lockFailure) return handleDatabaseLock(title); - - QMessageBox::warning(this, title, QString::fromStdString(err)); - return false; + if (locked) { + handleDatabaseLock(title); + return; + } + if (!error.isEmpty()) QMessageBox::warning(this, title, error); } -bool MainWindow::handleDatabaseLock(const QString& title) { - if (!m_pacman) return false; +// A page refused to start: ask for the password, free pacman's lock, or report +// the reason — then replay the request. +void MainWindow::handleStartResult(const AppCore::StartResult& result, + const QString& title) { + if (result.started) return; - // The other manager frequently finishes while the failed operation was - // unwinding: retry straight away rather than announcing a lock that is gone. - if (PacmanManager::databaseIsFree()) { - statusBar()->showMessage("Base pacman libérée, nouvelle tentative..."); - QTimer::singleShot(0, this, [this] { retryPendingAction(); }); - return true; + if (result.needsPassword) { + if (!promptForSudoPassword()) { + statusBar()->showMessage("Opération annulée : identifiants requis."); + m_core->cancelPendingRequest(); + return; + } + // The core kept the request pending: replay it with the password now + // available. A second refusal is reported like the first one. + handleStartResult(m_core->retryPendingRequest(), title); + return; } - const PacmanManager::LockHolder holder = PacmanManager::detectLockHolder(); - const QString holderName = - QString::fromStdString(PacmanManager::describeLockHolder(holder)); + if (result.locked) { + handleDatabaseLock(title); + return; + } + + if (!result.error.isEmpty()) statusBar()->showMessage(result.error); +} + +void MainWindow::handleDatabaseLock(const QString& title) { + // The other manager frequently finishes while the failed operation was + // unwinding: retry straight away rather than announcing a lock that is gone. + if (!m_core->databaseLocked()) { + statusBar()->showMessage("Base pacman libérée, nouvelle tentative..."); + QTimer::singleShot(0, this, [this, title] { + handleStartResult(m_core->retryPendingRequest(), title); + }); + return; + } + + const PacmanManager::LockHolder holder = m_core->lockHolder(); + const QString holderName = m_core->databaseLockDescription(); QMessageBox box(this); box.setWindowTitle(title); @@ -1518,7 +900,7 @@ bool MainWindow::handleDatabaseLock(const QString& title) { box.setTextFormat(Qt::RichText); // The action only promises a resume when there is one to replay: a lock hit // by an operation with no pending retry just needs the database freed. - const bool canRetry = !m_pendingRetryAction.isEmpty(); + const bool canRetry = m_core->hasPendingRequest(); const QString resume = canRetry ? QStringLiteral(" PacManager reprendra ensuite l'opération automatiquement.") : QString(); @@ -1547,1713 +929,102 @@ bool MainWindow::handleDatabaseLock(const QString& title) { box.exec(); if (box.clickedButton() == retryBtn) { - QTimer::singleShot(0, this, [this] { retryPendingAction(); }); - return true; + QTimer::singleShot(0, this, [this, title] { + handleStartResult(m_core->retryPendingRequest(), title); + }); + return; } if (box.clickedButton() != resolveBtn) { - m_pendingRetryAction.clear(); - return true; + m_core->cancelPendingRequest(); + return; } // Stopping another user's manager (or removing a root-owned lock file) needs // the sudo password, which the session may not hold yet. - if (!ensureCredentials({m_pacman})) return true; - - // Deferred so the dialog closes before the worker touches the UI. - QTimer::singleShot(0, this, [this, holder] { startLockRecovery(holder); }); - return true; -} - -void MainWindow::startLockRecovery(const PacmanManager::LockHolder& holder) { - if (!m_pacman) return; - - setBusy(true); - statusBar()->showMessage("Libération de la base de données pacman..."); - - auto* worker = new InstallWorker(m_pacman, holder); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::finished, this, [this](bool released) { - setBusy(false); - if (!released) { - statusBar()->showMessage("Base pacman toujours verrouillée"); - QMessageBox::warning(this, "Base de données verrouillée", - QString::fromStdString(m_pacman ? m_pacman->lastError() : std::string())); - m_pendingRetryAction.clear(); - return; - } - statusBar()->showMessage("Base libérée, reprise de l'opération..."); - retryPendingAction(); - }); - connect(worker, &InstallWorker::finished, this, - [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::retryPendingAction() { - if (m_pendingRetryAction.isEmpty()) return; - const QString action = m_pendingRetryAction; - m_pendingRetryAction.clear(); - retryPrivilegedAction(action); -} - -void MainWindow::retryPrivilegedAction(const QString& action) { - if (action == "install" && !m_selectedPackage.name.empty()) { - m_pendingSelect = m_selectedPackage.name; - performInstall(m_selectedPackage.name); - } else if (action == "remove" && !m_selectedPackage.name.empty()) { - m_pendingSelect = m_selectedPackage.name; - performRemove(m_selectedPackage.name); - } else if (action == "update-all") { - onUpdateAll(); - } else if (action == "refresh") { - onRefresh(); - } else if (action == "update" && !m_selectedPackage.name.empty()) { - onUpdate(); - } else if (action == "cleanup") { - // The groups still queued are replayed; the one that failed on the lock - // is gone, and the recovery already freed the database. - std::vector providers; - for (const auto& entry : m_pendingRemovals) providers.push_back(entry.first); - if (!tryAcquireOp()) return; - if (!ensureCredentials(providers)) { - setBusy(false); - return; - } - startNextCleanupRemoval(); - } else if (action == "clean-caches") { - onCleanCaches(); - } else if (action == "install-plugin-tool") { - onInstallPluginTool(); - } -} - -void MainWindow::clearCredentialsAfterUse() { - // In per-operation mode the password is single-use: drop it once the - // command ran so the next operation prompts again. - if (m_credentialMode == CredentialMode::EachTime && m_pacman) { - m_pacman->clearPassword(); - } -} - -QFrame* MainWindow::makeCard() { - QFrame* card = new QFrame(); - card->setObjectName("card"); - return card; -} - -QFrame* MainWindow::makeStatCard(const QString& iconName, const QString& title, - const QString& accent, QLabel** valueOut) { - QFrame* card = makeCard(); - // Read by the stylesheet rule that draws the coloured left edge. - card->setProperty("accent", accent); - QVBoxLayout* layout = new QVBoxLayout(card); - layout->setContentsMargins(18, 16, 18, 16); - layout->setSpacing(6); - - QLabel* iconLabel = new QLabel(); - iconLabel->setPixmap(iconPixmap(iconName, 24)); - iconLabel->setStyleSheet("background: transparent;"); - layout->addWidget(iconLabel); - - QLabel* value = new QLabel("…"); - value->setObjectName("statValue"); - layout->addWidget(value); - - QLabel* titleLabel = new QLabel(title); - titleLabel->setObjectName("statTitle"); - layout->addWidget(titleLabel); - - *valueOut = value; - return card; -} - -void MainWindow::updatePageTitle() { - switch (m_navGroup->checkedId()) { - case NavDashboard: - m_headerTitle->setText("Tableau de bord"); - m_headerSubtitle->setText("Vue d'ensemble de votre système"); - break; - case NavSearch: - m_headerTitle->setText("Recherche"); - m_headerSubtitle->setText("Trouvez et installez des paquets"); - break; - case NavInstalled: - m_headerTitle->setText("Paquets installés"); - m_headerSubtitle->setText("Parcourez les paquets de votre système"); - break; - case NavUpdates: - m_headerTitle->setText("Mises à jour disponibles"); - m_headerSubtitle->setText("Maintenez votre système à jour"); - break; - case NavCleanup: - m_headerTitle->setText("Nettoyage"); - m_headerSubtitle->setText( - "Purger les paquets inutilisés ou legacy et libérer de l'espace"); - break; - case NavHistory: - m_headerTitle->setText("Historique"); - m_headerSubtitle->setText("Journal de toutes vos actions"); - break; - case NavLogs: - m_headerTitle->setText("Logs pacman"); - m_headerSubtitle->setText("Journal brut du gestionnaire de paquets"); - break; - case NavPlugins: - m_headerTitle->setText("Plugins"); - m_headerSubtitle->setText("Gestionnaires de paquets et extensions"); - break; - default: - break; - } -} - -void MainWindow::onNavChanged(int id) { - qCDebug(pacmgrUi) << "navigate to page" << id; - updatePageTitle(); - - switch (id) { - case NavDashboard: - m_pages->setCurrentIndex(PageDashboard); - refreshDashboard(); - break; - case NavSearch: - setBrowseMode(ModeSearch); - m_searchBar->setFocus(); - break; - case NavInstalled: - setBrowseMode(ModeInstalled); - loadInstalled(); - break; - case NavUpdates: - setBrowseMode(ModeUpdates); - loadUpdates(); - break; - case NavCleanup: - m_pages->setCurrentIndex(PageCleanup); - loadCleanup(); - break; - case NavHistory: - m_pages->setCurrentIndex(PageHistory); - refreshHistoryTable(); - break; - case NavLogs: - m_pages->setCurrentIndex(PageLogs); - loadLogs(); - break; - case NavPlugins: - m_pages->setCurrentIndex(PagePlugins); - refreshPluginsTable(); - break; - default: - break; - } -} - -void MainWindow::setBrowseMode(BrowseMode mode) { - m_browseMode = mode; - m_pages->setCurrentIndex(PageBrowse); - - m_searchRowWidget->setVisible(mode == ModeSearch); - m_filterRowWidget->setVisible(mode == ModeInstalled); - m_installButton->setVisible(mode == ModeSearch); - - // Clear any stale selection and reset the details panel - m_packageTable->clearSelection(); - resetDetailsPanel(); -} - -void MainWindow::resetDetailsPanel() { - m_packageName->setText("Sélectionnez un paquet"); - m_packageVersion->setText(""); - m_packageRepo->setText("—"); - m_packageSize->setText("—"); - m_packageProvider->setText("—"); - m_packageDescription->setText(""); - m_installButton->setEnabled(false); - m_removeButton->setEnabled(false); - m_updateButton->setEnabled(false); -} - -void MainWindow::onSearch() { - std::vector providers = m_pluginManager->availableManagers(); - if (providers.empty()) { - statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); + if (!promptForSudoPassword()) { + m_core->cancelPendingRequest(); return; } - std::string query = m_searchBar->text().toStdString(); - if (query.empty()) { - // Refocus the search field instead of interrupting with a dialog. - m_searchBar->setFocus(); - statusBar()->showMessage("Entrez un terme de recherche."); - return; - } - - setBusy(true); - statusBar()->showMessage("Recherche en cours..."); - m_packageTable->setRowCount(0); - - SearchWorker* worker = new SearchWorker(providers, query); - connect(worker, &SearchWorker::chunk, this, &MainWindow::onSearchChunk); - connect(worker, &SearchWorker::finished, this, &MainWindow::onSearchFinished); - connect(worker, &SearchWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); + // The core replays the pending action itself once the lock is gone. + handleStartResult(m_core->releaseDatabaseLock(), title); } -// Called as results stream in: append the incoming row instead of rebuilding -// the whole table, so the first matches appear while the search continues. -void MainWindow::onSearchChunk(std::vector results) { - appendPackageRows(results); -} +// --------------------------------------------------------------------------- +// Results reported by the core +// --------------------------------------------------------------------------- -void MainWindow::loadInstalled() { - setBusy(true); - statusBar()->showMessage("Chargement des paquets installés..."); - m_packageTable->setRowCount(0); +void MainWindow::onCoreListFinished(AppCore::ListMode mode, + std::vector results) { + if (mode != AppCore::ListMode::Updates) return; - ListWorker* worker = new ListWorker(m_pluginManager->availableManagers(), - ListWorker::Installed); - connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished); - connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::loadUpdates() { - setBusy(true); - statusBar()->showMessage("Recherche des mises à jour..."); - m_packageTable->setRowCount(0); - - ListWorker* worker = new ListWorker(m_pluginManager->availableManagers(), - ListWorker::Updates); - connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished); - connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::onSearchFinished(std::vector results) { - setBusy(false); - // The table is already filled incrementally via onSearchChunk; rebuild it - // once at the end to guarantee a consistent final list. - populatePackageTable(results); - statusBar()->showMessage(QString("%1 paquet(s) trouvé(s)").arg(results.size())); -} - -void MainWindow::onListFinished(std::vector results) { - setBusy(false); - - if (m_browseMode == ModeInstalled) { - m_installedPackages = results; - // Re-apply the current filter text on the freshly loaded list - onInstalledFilterChanged(m_filterBar->text()); - statusBar()->showMessage(QString("%1 paquet(s) installé(s)").arg(results.size())); - } else if (m_browseMode == ModeUpdates) { - populatePackageTable(results); - statusBar()->showMessage( - QString("%1 mise(s) à jour disponible(s)").arg(results.size())); + const int count = static_cast(results.size()); + setUpdatesBadge(count); + // Notify once per distinct count, so the periodic dashboard refresh does not + // re-pop the tray message. + if (count != m_lastNotifiedUpdates) { + m_lastNotifiedUpdates = count; + notifyUpdatesAvailable(count); } } -void MainWindow::onInstalledFilterChanged(const QString& text) { - if (m_browseMode != ModeInstalled) return; - - std::vector filtered; - if (text.isEmpty()) { - filtered = m_installedPackages; - } else { - QString needle = text.toLower(); - for (const auto& pkg : m_installedPackages) { - if (QString::fromStdString(pkg.name).toLower().contains(needle)) { - filtered.push_back(pkg); - } - } - } - populatePackageTable(filtered); -} - -// Navigates to the Installed page and opens the clicked package's details -// (with remove / update actions available) by selecting it in the list. -void MainWindow::onRecentActivityClicked(QListWidgetItem* item) { - if (!item) return; - - QString name = item->data(Qt::UserRole).toString(); - if (name.isEmpty()) return; - - m_pendingSelect = name.toStdString(); - m_navGroup->button(NavInstalled)->click(); // Installed page -> loadInstalled() runs - statusBar()->showMessage( - QString("Ouverture des détails de %1...").arg(name)); -} - -void MainWindow::populatePackageTable(const std::vector& results) { - m_currentResults = results; - showEmptyState(m_packageTableStack, results.empty()); - { - TableFillBatch batch(m_packageTable); - m_packageTable->setRowCount(0); - m_packageTable->setRowCount(static_cast(results.size())); - - for (int i = 0; i < static_cast(results.size()); ++i) { - addPackageRow(i, results[i]); - } - } - - m_resultCount->setText(QString("%1 paquet(s)").arg(results.size())); - - if (results.empty()) { - resetDetailsPanel(); - return; - } - - // If we navigated here from the dashboard for a specific package, select it. - if (!m_pendingSelect.empty()) { - std::string target = m_pendingSelect; - m_pendingSelect.clear(); - for (int i = 0; i < static_cast(m_currentResults.size()); ++i) { - if (m_currentResults[i].name == target) { - m_packageTable->selectRow(i); - onPackageSelected(i); // ensure the detail panel updates immediately - return; - } - } - } - - m_packageTable->selectRow(0); -} - -// Appends an incoming search chunk to the already-displayed rows, updating the -// stored result set so selection and the details panel stay consistent. -void MainWindow::appendPackageRows(const std::vector& results) { - const int startRow = static_cast(m_currentResults.size()); - m_currentResults.insert(m_currentResults.end(), results.begin(), results.end()); - { - TableFillBatch batch(m_packageTable); - m_packageTable->setRowCount(static_cast(m_currentResults.size())); - - for (size_t i = 0; i < results.size(); ++i) { - addPackageRow(startRow + static_cast(i), results[i]); - } - } - m_resultCount->setText(QString("%1 paquet(s)").arg(m_currentResults.size())); -} - -void MainWindow::addPackageRow(int i, const PackageInfo& pkg) { - QFont nameFont; - nameFont.setWeight(QFont::DemiBold); - - QTableWidgetItem* nameItem = new QTableWidgetItem(QString::fromStdString(pkg.name)); - nameItem->setFont(nameFont); - m_packageTable->setItem(i, 0, nameItem); - - m_packageTable->setItem(i, 1, - new QTableWidgetItem(QString::fromStdString(pkg.version))); - - m_packageTable->setItem(i, 2, new QTableWidgetItem( - pkg.repository.empty() ? "—" : QString::fromStdString(pkg.repository))); - - QTableWidgetItem* providerItem = new QTableWidgetItem( - providersLabel(m_pluginManager, pkg)); - providerItem->setForeground(QColor("#98a0b3")); - providerItem->setIcon(loadIcon("package")); - m_packageTable->setItem(i, 3, providerItem); - - QString statusText; - QString statusIcon; - QColor statusColor; - if (pkg.installed && pkg.updateAvailable) { - statusText = "MAJ dispo"; - statusIcon = "arrow-up"; - statusColor = QColor("#e0af68"); - } else if (pkg.installed) { - statusText = "Installé"; - statusIcon = "check"; - statusColor = QColor("#3fb950"); - } else if (!pkg.repository.empty()) { - statusText = "Disponible"; - statusIcon = "package"; - statusColor = QColor("#98a0b3"); - } else { - statusText = "—"; - statusIcon.clear(); - statusColor = QColor("#565f73"); - } - - QTableWidgetItem* statusItem = new QTableWidgetItem(statusText); - statusItem->setForeground(statusColor); - if (!statusIcon.isEmpty()) statusItem->setIcon(loadIcon(statusIcon)); - m_packageTable->setItem(i, 4, statusItem); -} - -void MainWindow::onPackageSelected(int row) { - if (row < 0 || row >= static_cast(m_currentResults.size())) { - resetDetailsPanel(); - return; - } - - m_selectedPackage = m_currentResults[row]; - updatePackageInfo(m_selectedPackage); - - IPackageManager* provider = providerFor(m_selectedPackage.provider); - - m_installButton->setEnabled( - m_browseMode == ModeSearch - && provider && provider->canInstall() - && !m_selectedPackage.installed); - m_removeButton->setEnabled( - provider && provider->canRemove() - && m_selectedPackage.installed); - m_updateButton->setEnabled( - provider && provider->canUpdate() - && m_selectedPackage.updateAvailable); -} - -void MainWindow::updatePackageInfo(const PackageInfo& pkg) { - m_packageName->setText(QString::fromStdString(pkg.name)); - - QString versionText = QString("Version : %1").arg(QString::fromStdString(pkg.version)); - if (pkg.updateAvailable) { - versionText += " (mise à jour disponible)"; - } - m_packageVersion->setText(versionText); - - m_packageRepo->setText(pkg.repository.empty() - ? "Dépôt : —" - : QString("Dépôt : %1").arg(QString::fromStdString(pkg.repository))); - m_packageSize->setText(pkg.size.empty() - ? "Taille : —" - : QString("Taille : %1").arg(QString::fromStdString(pkg.size))); - m_packageProvider->setText( - QString("Fournisseur : %1").arg(providersLabel(m_pluginManager, pkg))); - - // Rich details: dependencies, required-by, install date (pacman), update - // size estimate for pending updates. Loaded on demand so selecting a row - // stays instant even when pacman is slow. - QString details = QString::fromStdString(pkg.description); - const std::string rich = m_pacman ? richDetails(pkg) : std::string(); - if (!rich.empty()) { - if (!details.isEmpty()) details += "\n\n"; - details += QString::fromStdString(rich); - } - m_packageDescription->setText(details); -} - -// Runs the read-only pacman queries backing the details panel. Kept -// synchronous: -Qi/-Si answer in milliseconds and the panel already updated -// the basics above, so no worker thread is worth the complexity. -std::string MainWindow::richDetails(const PackageInfo& pkg) { - if (!m_pacman || !m_pacman->isAvailable()) return {}; - - // Cache per name+provider+version+installed: selecting a row repeatedly (or - // arrowing through the table) 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(); - - auto run = [](const std::string& cmd) { - std::array buf{}; - std::string out; - std::unique_ptr pipe(popen(cmd.c_str(), "r")); - if (!pipe) return out; - while (fgets(buf.data(), buf.size(), pipe.get())) out += buf.data(); - return out; - }; - auto field = [&](const std::string& out, const std::string& name) { - std::istringstream iss(out); - std::string line; - while (std::getline(iss, line)) { - 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 val = line.substr(colon + 1); - size_t start = val.find_first_not_of(" \t"); - if (start != std::string::npos) val = val.substr(start); - while (!val.empty() && (val.back() == '\n' || val.back() == '\r' || val.back() == ' ')) - val.pop_back(); - return val; - } - return std::string(); - }; - - const bool isPacmanPkg = pkg.provider == "pacman" || pkg.provider.empty(); - const std::string q = pkg.provider == "aur" ? "yay -Qi " : "pacman -Qi "; - const std::string s = pkg.provider == "aur" ? "yay -Si " : "pacman -Si "; - std::string installed = run(q + pkg.name + " 2>/dev/null"); - if (installed.empty() && isPacmanPkg) installed = run("pacman -Qi " + pkg.name + " 2>/dev/null"); - - std::string out; - auto addRow = [&](const char* label, const std::string& val) { - if (val.empty() || val == "None" || val == "--") return; - if (!out.empty()) out += "\n"; - out += std::string(label) + " : " + val; - }; - if (!installed.empty()) { - addRow("Taille installée", field(installed, "Installed Size")); - addRow("Date d'installation", field(installed, "Install Date")); - addRow("Dépend de", field(installed, "Depends On")); - addRow("Requis par", field(installed, "Required By")); - } else { - // Only query the sync database when the package is not installed here, - // halving the subprocess count on the Installed/Updates pages. - const std::string sync = run(s + pkg.name + " 2>/dev/null"); - if (!sync.empty()) { - addRow("Taille du téléchargement", field(sync, "Download Size")); - addRow("Taille installée", field(sync, "Installed Size")); - addRow("Dépend de", field(sync, "Depends On")); - } - } - - // Bound the cache so a long browsing session cannot grow it forever. - if (m_detailsCache.size() > 512) m_detailsCache.clear(); - m_detailsCache.insert(key, out); - return out; -} - -void MainWindow::onInstall() { - if (m_selectedPackage.name.empty()) return; - performInstall(m_selectedPackage.name); -} - -void MainWindow::onRemove() { - if (m_selectedPackage.name.empty()) return; - performRemove(m_selectedPackage.name); -} - -void MainWindow::onUpdate() { - if (m_selectedPackage.name.empty()) return; - - IPackageManager* provider = providerFor(m_selectedPackage.provider); - if (!provider || !provider->canUpdate()) return; - if (!tryAcquireOp()) return; - m_pendingRetryAction = "update"; - if (!ensureCredentials({provider})) { - setBusy(false); - m_pendingRetryAction.clear(); - return; - } - - statusBar()->showMessage( - QString("Mise à jour de %1...").arg(QString::fromStdString(m_selectedPackage.name))); - - auto* worker = new InstallWorker(provider, InstallWorker::Op::Update, m_selectedPackage.name); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, [this, provider](bool success) { - setBusy(false); - if (success) { - statusBar()->showMessage("Mise à jour terminée"); - } else { - statusBar()->showMessage("Échec de la mise à jour"); - showProviderError("Échec de la mise à jour", provider); - } - m_historyManager->record({"", "update", m_selectedPackage.name, - provider->getName(), success}); - clearCredentialsAfterUse(); - reloadCurrentView(); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::onUpdateAll() { - std::vector providers = m_pluginManager->availableManagers(); - if (providers.empty()) { - statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); - return; - } - if (!tryAcquireOp()) return; - m_pendingRetryAction = "update-all"; - if (!ensureCredentials(providers)) { - setBusy(false); - m_pendingRetryAction.clear(); - return; - } - - statusBar()->showMessage("Mise à jour de tous les paquets..."); - - auto* worker = new InstallWorker(providers, InstallWorker::Op::UpdateAll); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, [this, providers](bool success) { - setBusy(false); - if (success) { - statusBar()->showMessage("Tous les paquets sont à jour"); - } else { - statusBar()->showMessage("Erreur lors de la mise à jour globale"); - for (IPackageManager* pm : providers) { - if (!pm->lastError().empty()) { - // showProviderError offers a retry for db-lock errors. - showProviderError("Erreur lors de la mise à jour globale", pm); - break; - } - } - } - clearCredentialsAfterUse(); - reloadCurrentView(); - refreshDashboard(); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::onRefresh() { - std::vector providers = m_pluginManager->availableManagers(); - if (providers.empty()) { - statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); - return; - } - if (!tryAcquireOp()) return; - m_pendingRetryAction = "refresh"; - if (!ensureCredentials(providers)) { - setBusy(false); - m_pendingRetryAction.clear(); - return; - } - - statusBar()->showMessage("Rafraîchissement des sources..."); - - auto* worker = new InstallWorker(providers, InstallWorker::Op::Refresh); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, [this, providers](bool success) { - setBusy(false); - if (success) { - statusBar()->showMessage("Sources rafraîchies"); - } else { - statusBar()->showMessage("Erreur lors du rafraîchissement"); - for (IPackageManager* pm : providers) { - if (!pm->lastError().empty()) { - showProviderError("Erreur lors du rafraîchissement", pm); - break; - } - } - } - clearCredentialsAfterUse(); - refreshDashboard(); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::onCleanupScan() { - loadCleanup(); -} - -void MainWindow::loadCleanup() { - std::vector providers = m_pluginManager->availableManagers(); - if (providers.empty()) { - statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); - return; - } - - setBusy(true); - statusBar()->showMessage("Analyse des paquets inutilisés et legacy..."); - m_cleanupTable->setRowCount(0); - m_cleanupCandidates.clear(); - m_cleanupRemoveOrphansButton->setEnabled(false); - m_cleanupRemoveSelectionButton->setEnabled(false); - - auto* worker = new ListWorker(providers, ListWorker::Cleanup); - connect(worker, &ListWorker::finished, this, &MainWindow::onCleanupListFinished); - connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::onCleanupListFinished(std::vector results) { - setBusy(false); - populateCleanupTable(results); - - int orphans = 0; - for (const auto& pkg : results) { - if (pkg.orphan) ++orphans; - } - statusBar()->showMessage( - QString("%1 orphelin(s) et %2 paquet(s) legacy détecté(s)") - .arg(orphans).arg(static_cast(results.size()) - orphans)); -} - -void MainWindow::populateCleanupTable(const std::vector& candidates) { - m_cleanupCandidates = candidates; - showEmptyState(m_cleanupTableStack, candidates.empty()); - - QFont nameFont; - nameFont.setWeight(QFont::DemiBold); - - TableFillBatch batch(m_cleanupTable); - m_cleanupTable->setRowCount(0); - m_cleanupTable->setRowCount(static_cast(candidates.size())); - - int orphans = 0; - for (int i = 0; i < static_cast(candidates.size()); ++i) { - const PackageInfo& pkg = candidates[i]; - if (pkg.orphan) ++orphans; - - QTableWidgetItem* nameItem = new QTableWidgetItem(QString::fromStdString(pkg.name)); - nameItem->setFont(nameFont); - m_cleanupTable->setItem(i, 0, nameItem); - - m_cleanupTable->setItem(i, 1, - new QTableWidgetItem(QString::fromStdString(pkg.version))); - - QTableWidgetItem* typeItem = - new QTableWidgetItem(QString::fromStdString(pkg.cleanupReason)); - typeItem->setForeground(QColor(pkg.orphan ? "#e0af68" : "#7a8299")); - typeItem->setIcon(loadIcon(pkg.orphan ? "alert" : "package")); - m_cleanupTable->setItem(i, 2, typeItem); - - m_cleanupTable->setItem(i, 3, - new QTableWidgetItem(providersLabel(m_pluginManager, pkg))); - } - batch.release(); - - m_cleanupCount->setText(QString("%1 orphelin(s) · %2 legacy") - .arg(orphans).arg(static_cast(candidates.size()) - orphans)); - m_cleanupRemoveOrphansButton->setEnabled(orphans > 0); - m_cleanupRemoveOrphansButton->setText(orphans > 0 - ? QString("Supprimer les orphelins (%1)").arg(orphans) - : QString("Supprimer les orphelins")); - - if (!candidates.empty()) m_cleanupTable->selectRow(0); - onCleanupSelectionChanged(m_cleanupTable->currentRow()); -} - -void MainWindow::onCleanupSelectionChanged(int row) { - if (row < 0 || row >= static_cast(m_cleanupCandidates.size())) { - m_cleanupRemoveSelectionButton->setEnabled(false); - m_cleanupRemoveSelectionButton->setToolTip(QString()); - return; - } - - const PackageInfo& pkg = m_cleanupCandidates[row]; - const QString name = QString::fromStdString(pkg.name); - m_cleanupRemoveSelectionButton->setEnabled(true); - // A legacy package is only ever removed one by one and with an explicit - // warning: nothing on the system proves it is unused. - m_cleanupRemoveSelectionButton->setToolTip( - pkg.orphan - ? QString("Supprimer « %1 » (orphelin)").arg(name) - : QString("Supprimer « %1 » (%2) — à vérifier : rien ne prouve " - "qu'il est inutilisé") - .arg(name, QString::fromStdString(pkg.cleanupReason))); -} - -void MainWindow::onRemoveCleanupOrphans() { - std::vector orphans; - for (const auto& pkg : m_cleanupCandidates) { - if (pkg.orphan) orphans.push_back(pkg); - } - if (orphans.empty()) { - statusBar()->showMessage("Aucun orphelin à supprimer."); - return; - } - removeCleanupPackages(orphans, QString("%1 orphelin(s)").arg(orphans.size())); -} - -void MainWindow::onRemoveCleanupSelection() { - const int row = m_cleanupTable->currentRow(); - if (row < 0 || row >= static_cast(m_cleanupCandidates.size())) return; - - // Copied: the candidate list is rebuilt once the removal completes. - const PackageInfo pkg = m_cleanupCandidates[row]; - removeCleanupPackages({pkg}, - QString("« %1 »").arg(QString::fromStdString(pkg.name))); -} - -// Groups the candidates per provider (each provider then gets a single removal -// command), confirms once, and hands over to the sequential runner below. -void MainWindow::removeCleanupPackages(const std::vector& packages, - const QString& description) { - m_pendingRemovals.clear(); - for (const auto& pkg : packages) { - IPackageManager* provider = providerFor(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()) { - statusBar()->showMessage("Aucun paquet sélectionné n'est supprimable."); - return; - } - - if (QMessageBox::question(this, "Nettoyage", - QString("Supprimer %1 ?\n\nCette action est irréversible.") - .arg(description)) != QMessageBox::Yes) { - m_pendingRemovals.clear(); - return; - } - - std::vector providers; - for (const auto& entry : m_pendingRemovals) providers.push_back(entry.first); - - if (!tryAcquireOp()) { - m_pendingRemovals.clear(); - return; - } - if (!ensureCredentials(providers)) { - setBusy(false); - m_pendingRemovals.clear(); - return; - } - - // Lets a database-lock recovery re-run the removal it interrupted. - m_pendingRetryAction = "cleanup"; - startNextCleanupRemoval(); -} - -// Removes the next provider's group of packages, then chains into the -// following one. Two removals never run at once: pacman locks its database for -// the whole operation. -void MainWindow::startNextCleanupRemoval() { - if (m_pendingRemovals.empty()) { - setBusy(false); - clearCredentialsAfterUse(); - m_detailsCache.clear(); - loadCleanup(); - refreshDashboard(); - return; - } - - const auto job = m_pendingRemovals.front(); - m_pendingRemovals.erase(m_pendingRemovals.begin()); - IPackageManager* provider = job.first; - const std::vector packages = job.second; - - statusBar()->showMessage( - QString("Suppression de %1 paquet(s)...").arg(packages.size())); - - auto* worker = new InstallWorker(provider, InstallWorker::Op::RemovePackages, packages); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, - [this, provider, packages](bool success) { - // One history row per removed package keeps the install/remove filters - // of the History page meaningful. - for (const auto& name : packages) { - m_historyManager->record({"", "remove", name, provider->getName(), success}); - } - - if (!success) { - // Stop the chain and keep the group queued, so the failure handler - // can resume the whole cleanup once the cause is gone (typically a - // locked database, freed through retryPendingAction()). - setBusy(false); - m_pendingRemovals.insert(m_pendingRemovals.begin(), {provider, packages}); - statusBar()->showMessage("Échec du nettoyage"); - showProviderError("Échec du nettoyage", provider); - return; - } - - statusBar()->showMessage( - QString("%1 paquet(s) supprimé(s)").arg(packages.size())); - startNextCleanupRemoval(); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::onCleanCaches() { - std::vector providers; - QStringList names; - for (IPackageManager* pm : m_pluginManager->availableManagers()) { - if (!pm->canCleanCache()) continue; - providers.push_back(pm); - names << QString::fromStdString(pm->getName()); - } - if (providers.empty()) { - statusBar()->showMessage("Aucun cache à nettoyer sur ce système."); - return; - } - - if (QMessageBox::question(this, "Nettoyage", - QString("Vider les caches de %1 ?\n\npacman ne conserve que la " - "dernière version de chaque paquet téléchargé et Flatpak " - "supprime les runtimes qu'aucune application n'utilise " - "plus.").arg(names.join(", "))) != QMessageBox::Yes) { - return; - } - - if (!tryAcquireOp()) return; - if (!ensureCredentials(providers)) { - setBusy(false); - return; - } - - m_pendingRetryAction = "clean-caches"; - statusBar()->showMessage("Nettoyage des caches..."); - - auto* worker = new InstallWorker(providers, InstallWorker::Op::CleanCache); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, [this, providers](bool success) { - setBusy(false); - if (success) { - statusBar()->showMessage("Caches nettoyés"); - } else { - statusBar()->showMessage("Échec du nettoyage des caches"); - for (IPackageManager* pm : providers) { - if (!pm->lastError().empty()) { - showProviderError("Échec du nettoyage des caches", pm); - break; - } - } - } - for (IPackageManager* pm : providers) { - m_historyManager->record({"", "cleanup", "caches", pm->getName(), success}); - } - clearCredentialsAfterUse(); - refreshDashboard(); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::performInstall(const std::string& package) { - IPackageManager* provider = providerFor(m_selectedPackage.provider); - if (!provider || !provider->canInstall()) return; - qCInfo(pacmgrOp) << "install" << QString::fromStdString(package) - << "via" << QString::fromStdString(provider->getName()); - if (!tryAcquireOp()) return; - m_pendingRetryAction = "install"; - if (!ensureCredentials({provider})) { - setBusy(false); - m_pendingRetryAction.clear(); - return; - } - - statusBar()->showMessage( - QString("Installation de %1...").arg(QString::fromStdString(package))); - - auto* worker = new InstallWorker(provider, InstallWorker::Op::Install, package); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, [this, provider](bool success) { - setBusy(false); - if (success) { - statusBar()->showMessage( - QString("%1 installé avec succès").arg( - QString::fromStdString(m_selectedPackage.name))); - } else { - statusBar()->showMessage( - QString("Échec de l'installation de %1").arg( - QString::fromStdString(m_selectedPackage.name))); - showProviderError("Échec de l'installation", provider); - } - m_historyManager->record({"", "install", m_selectedPackage.name, - provider->getName(), success}); - clearCredentialsAfterUse(); - reloadCurrentView(); - refreshDashboard(); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::performRemove(const std::string& package) { - IPackageManager* provider = providerFor(m_selectedPackage.provider); - if (!provider || !provider->canRemove()) return; - qCInfo(pacmgrOp) << "remove" << QString::fromStdString(package) - << "via" << QString::fromStdString(provider->getName()); - if (!tryAcquireOp()) return; - m_pendingRetryAction = "remove"; - if (!ensureCredentials({provider})) { - setBusy(false); - m_pendingRetryAction.clear(); - return; - } - - statusBar()->showMessage( - QString("Suppression de %1...").arg(QString::fromStdString(package))); - - auto* worker = new InstallWorker(provider, InstallWorker::Op::Remove, package); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, [this, provider](bool success) { - setBusy(false); - if (success) { - statusBar()->showMessage( - QString("%1 supprimé avec succès").arg( - QString::fromStdString(m_selectedPackage.name))); - } else { - statusBar()->showMessage( - QString("Échec de la suppression de %1").arg( - QString::fromStdString(m_selectedPackage.name))); - showProviderError("Échec de la suppression", provider); - } - m_historyManager->record({"", "remove", m_selectedPackage.name, - provider->getName(), success}); - clearCredentialsAfterUse(); - reloadCurrentView(); - refreshDashboard(); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::reloadCurrentView() { - // Installed state changed: drop the cached pacman details so the panel - // shows the fresh size/date after an install/remove/update. - m_detailsCache.clear(); - if (m_browseMode == ModeInstalled) { - loadInstalled(); - } else if (m_browseMode == ModeUpdates) { - loadUpdates(); - } else if (!m_searchBar->text().isEmpty()) { - onSearch(); - } -} - -void MainWindow::setBusy(bool busy) { - m_busy = busy; - m_progressBar->setVisible(busy); - m_installProgressBar->setVisible(busy); - if (busy) { - // Start indeterminate; a real percentage (onInstallProgress) switches - // the bottom bar to a determinate fill once the tool reports progress. - m_progressBar->setRange(0, 0); - m_progressBar->setValue(0); - m_installProgressBar->setRange(0, 0); - m_installProgressBar->setValue(0); - } -} - -// Single privileged pacman operation at a time: pacman locks its DB -// (/var/lib/pacman/db.lck), so a second concurrent op would fail with -// "verrouillage de la base de données impossible". -bool MainWindow::tryAcquireOp() { - if (m_busy) { - statusBar()->showMessage("Une opération est déjà en cours, patientez..."); - return false; - } - setBusy(true); - return true; -} - -// A real download percentage reported by the provider fills the bottom bar as -// a determinate progress. -1 (unknown) leaves the bar in its previous state. -void MainWindow::onInstallProgress(int percent) { +void MainWindow::onCoreActionProgress(const QString& message, int percent) { + if (!message.isEmpty()) statusBar()->showMessage(message); if (percent < 0) return; + + // A real download percentage reported by the provider fills the bottom bar + // as a determinate progress. m_installProgressBar->setVisible(true); m_installProgressBar->setRange(0, 100); m_installProgressBar->setValue(percent); } -void MainWindow::refreshHistoryTable() { - const auto& all = m_historyManager->getHistory(); +void MainWindow::onCoreActionFinished(const QString& action, const QString& name, + bool success, const QString& error, bool locked) { + if (!success) showActionError(actionErrorTitle(action), error, locked); - std::vector entries; - int filter = m_historyFilter->currentIndex(); - for (const auto& entry : all) { - bool match = filter == 0 - || (filter == 1 && entry.action == "install") - || (filter == 2 && entry.action == "remove") - || (filter == 3 && entry.action == "update") - || (filter == 4 && entry.action == "cleanup"); - if (match) entries.push_back(entry); + // The screens refresh themselves through the core signals they subscribe to + // (a listing reload for the browse page, and so on); the frame only keeps + // the dashboard figures fresh. + if (action == QLatin1String("install") || action == QLatin1String("remove") + || action == QLatin1String("update") || action == QLatin1String("update-all") + || action == QLatin1String("refresh") || action == QLatin1String("clean-caches") + || action == QLatin1String("install-plugin-tool")) { + m_dashboard->refresh(); } - m_historyCount->setText(QString("%1 action(s)").arg(entries.size())); - TableFillBatch batch(m_historyTable); - m_historyTable->setRowCount(static_cast(entries.size())); - - for (int i = 0; i < static_cast(entries.size()); ++i) { - const auto& entry = entries[i]; - - QString actionText, actionColor; - if (entry.action == "install") { - actionText = "Installation"; - actionColor = "#3fb950"; - } else if (entry.action == "remove") { - actionText = "Suppression"; - actionColor = "#f7768e"; - } else if (entry.action == "cleanup") { - actionText = "Nettoyage"; - actionColor = "#56b6c2"; - } else { - actionText = "Mise à jour"; - actionColor = "#e0af68"; - } - - m_historyTable->setItem(i, 0, - new QTableWidgetItem(QString::fromStdString(entry.timestamp))); - m_historyTable->setItem(i, 1, new QTableWidgetItem(actionText)); - m_historyTable->item(i, 1)->setForeground(QColor(actionColor)); - m_historyTable->setItem(i, 2, - new QTableWidgetItem(QString::fromStdString(entry.package))); - m_historyTable->setItem(i, 3, - new QTableWidgetItem(QString::fromStdString(entry.plugin))); - QTableWidgetItem* statusItem = - new QTableWidgetItem(entry.success ? "Succès" : "Échec"); - statusItem->setIcon(loadIcon(entry.success ? "check" : "close")); - m_historyTable->setItem(i, 4, statusItem); - } + Q_UNUSED(name); } -void MainWindow::onHistoryFilterChanged() { - refreshHistoryTable(); +void MainWindow::onCoreBusyChanged(bool busy) { + m_installProgressBar->setVisible(busy); + if (!busy) return; + + // Start indeterminate; a real percentage (onCoreActionProgress) switches the + // bar to a determinate fill once the tool reports progress. + m_installProgressBar->setRange(0, 0); + m_installProgressBar->setValue(0); } -void MainWindow::onClearHistory() { - m_historyManager->clear(); - refreshHistoryTable(); - refreshDashboard(); - statusBar()->showMessage("Historique effacé"); +void MainWindow::onCoreStatusMessage(const QString& message) { + statusBar()->showMessage(message); } -void MainWindow::loadLogs() { - const QString logPath = "/var/log/pacman.log"; - - QFile logFile(logPath); - if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - m_logsRaw.clear(); - m_logsText->setPlainText( - QString("Impossible d'ouvrir %1.\n" - "Vérifiez que le fichier existe et que vous avez les droits de lecture.") - .arg(logPath)); - return; - } - - m_logsRaw = QString::fromUtf8(logFile.readAll()); - applyLogsFilter(); -} - -void MainWindow::onLogsFilterChanged() { - applyLogsFilter(); -} - -// Renders m_logsRaw, keeping only the lines matching the filter box. Filtering -// in memory keeps typing instant even with a multi-megabyte pacman.log. -void MainWindow::applyLogsFilter() { - if (!m_logsText) return; - const QString needle = m_logsFilter ? m_logsFilter->text().trimmed() : QString(); - if (needle.isEmpty()) { - m_logsText->setPlainText(m_logsRaw); - } else { - QString filtered; - const QStringList lines = m_logsRaw.split(QLatin1Char('\n')); - for (const QString& line : lines) { - if (line.contains(needle, Qt::CaseInsensitive)) { - filtered += line; - filtered += QLatin1Char('\n'); - } - } - m_logsText->setPlainText(filtered); - } - m_logsText->moveCursor(QTextCursor::End); -} - -void MainWindow::onRefreshLogs() { - loadLogs(); - statusBar()->showMessage("Logs rechargés"); -} - -void MainWindow::refreshDashboard() { - std::vector providers = m_pluginManager->availableManagers(); - if (providers.empty()) { - m_statInstalled->setText("—"); - m_statUpdates->setText("—"); - m_statManager->setText("indisponible"); - refreshRecentActivity(); - return; - } - - m_statHistory->setText(QString::number(m_historyManager->getHistory().size())); - - QStringList names; - for (IPackageManager* pm : providers) { - names << QString::fromStdString(pm->getName()); - } - m_statManager->setText(names.join(", ")); - refreshRecentActivity(); - - auto* inst = new ListWorker(providers, ListWorker::Installed); - connect(inst, &ListWorker::finished, this, [this](std::vector r) { - m_statInstalled->setText(QString::number(r.size())); - }); - connect(inst, &ListWorker::finished, this, [inst] { inst->wait(); inst->deleteLater(); }); - inst->start(); - - auto* upd = new ListWorker(providers, ListWorker::Updates); - connect(upd, &ListWorker::finished, this, [this](std::vector r) { - m_statUpdates->setText(QString::number(r.size())); - m_statUpdates->setStyleSheet(r.empty() - ? QString() - : QString("color: #e0af68;")); - // Notify once per distinct count, so the periodic dashboard refresh - // does not re-pop the tray message. - if (static_cast(r.size()) != m_lastNotifiedUpdates) { - m_lastNotifiedUpdates = static_cast(r.size()); - notifyUpdatesAvailable(static_cast(r.size())); - } - setUpdatesBadge(static_cast(r.size())); - }); - connect(upd, &ListWorker::finished, this, [upd] { upd->wait(); upd->deleteLater(); }); - upd->start(); -} - -void MainWindow::setUpdatesBadge(int count) { - if (!m_navUpdatesButton) return; - - m_navUpdatesButton->setText(count > 0 - ? QString("Mises à jour · %1").arg(count) - : QString("Mises à jour")); - - // A dynamic property only takes effect once the style is re-applied, so it - // is only touched when it actually changes. - const bool highlighted = count > 0; - if (m_navUpdatesButton->property("highlighted").toBool() == highlighted) return; - m_navUpdatesButton->setProperty("highlighted", highlighted); - m_navUpdatesButton->style()->unpolish(m_navUpdatesButton); - m_navUpdatesButton->style()->polish(m_navUpdatesButton); -} - -void MainWindow::refreshRecentActivity() { - m_recentList->clear(); - - const auto& history = m_historyManager->getHistory(); - if (history.empty()) { - QListWidgetItem* empty = new QListWidgetItem( - "Aucune action enregistrée pour le moment"); - empty->setFlags(Qt::NoItemFlags); - empty->setTextAlignment(Qt::AlignCenter); - m_recentList->addItem(empty); - return; - } - - int start = std::max(0, static_cast(history.size()) - 8); - for (int i = static_cast(history.size()) - 1; i >= start; --i) { - const HistoryEntry& entry = history[i]; - - QListWidgetItem* item = new QListWidgetItem(); - item->setSizeHint(QSize(0, 42)); - // Keep the package name so a click can navigate to its details. - item->setData(Qt::UserRole, QString::fromStdString(entry.package)); - - QWidget* row = new QWidget(); - QHBoxLayout* rowLayout = new QHBoxLayout(row); - rowLayout->setContentsMargins(10, 4, 10, 4); - rowLayout->setSpacing(10); - - QLabel* ts = new QLabel(QString::fromStdString(entry.timestamp)); - ts->setStyleSheet( - "background: transparent; color: #5f6785;" - "font-family: monospace; font-size: 12px;"); - rowLayout->addWidget(ts); - - QString actionText, actionBg, actionFg; - if (entry.action == "install") { - actionText = "Installation"; actionBg = "#12301f"; actionFg = "#3fb950"; - } else if (entry.action == "remove") { - actionText = "Suppression"; actionBg = "#3a1a1a"; actionFg = "#f7768e"; - } else if (entry.action == "cleanup") { - actionText = "Nettoyage"; actionBg = "#12333a"; actionFg = "#56b6c2"; - } else { - actionText = "Mise à jour"; actionBg = "#3d2f0f"; actionFg = "#e0af68"; - } - rowLayout->addWidget(makeBadge(actionText, actionBg, actionFg)); - - QLabel* pkg = new QLabel(QString::fromStdString(entry.package)); - pkg->setStyleSheet( - "background: transparent; font-weight: 600; color: #c8d3f5;"); - rowLayout->addWidget(pkg); - - rowLayout->addStretch(); - - QLabel* status = new QLabel(); - status->setPixmap(iconPixmap(entry.success ? "check" : "close", 16)); - status->setStyleSheet("background: transparent;"); - rowLayout->addWidget(status); - - m_recentList->addItem(item); - m_recentList->setItemWidget(item, row); - } -} - -void MainWindow::updateStatusBar() { - std::vector providers = m_pluginManager->availableManagers(); - if (providers.empty()) { - statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); - return; - } - QString info = QString("%1 gestionnaire(s) actif(s) | Paquets affichés : %2 | Actions enregistrées : %3") - .arg(providers.size()) - .arg(m_currentResults.size()) - .arg(m_historyManager->getHistory().size()); - statusBar()->showMessage(info); -} - -void MainWindow::onPluginTableSelected(int row) { - if (row < 0 || row >= static_cast(m_pluginManager->plugins().size())) { - m_pluginToggleButton->setEnabled(false); - m_pluginInstallButton->setVisible(false); - m_pluginDescription->clear(); - return; - } - - const auto& entry = m_pluginManager->plugins()[row]; - m_selectedPluginId = entry.info.id; - m_pluginDescription->setText(QString::fromStdString(entry.info.description)); - - bool toggleable = entry.info.available; - m_pluginToggleButton->setEnabled(toggleable); - m_pluginToggleButton->setToolTip( - toggleable ? QString() - : QString("Outil « %1 » non détecté sur ce système.") - .arg(QString::fromStdString(entry.info.name))); - m_pluginToggleButton->setText( - m_pluginManager->isEnabled(entry.info.id) ? "Désactiver" : "Activer"); - - // Offer to install the backing tool (e.g. flatpak via pacman) when it is - // missing and we know which OS package provides it. - bool installable = !entry.info.available && !entry.info.installHint.empty() - && m_pacman && m_pacman->isAvailable(); - m_pluginInstallButton->setVisible(!entry.info.available); - m_pluginInstallButton->setEnabled(installable); - m_pluginInstallButton->setToolTip( - installable - ? QString("sudo pacman -S %1").arg(QString::fromStdString(entry.info.installHint)) - : QString()); -} - -// Installs the OS package backing the selected provider through pacman, then -// re-checks availability so the provider can be used right away. -void MainWindow::onInstallPluginTool() { - if (m_selectedPluginId.empty()) return; - if (!m_pacman || !m_pacman->isAvailable()) { - statusBar()->showMessage("pacman est requis pour installer l'outil."); - return; - } - - const std::string id = m_selectedPluginId; - std::string installHint; - for (const auto& entry : m_pluginManager->plugins()) { - if (entry.info.id == id) { - installHint = entry.info.installHint; - break; - } - } - if (installHint.empty()) return; - if (!ensureCredentials({m_pacman})) return; - - // Lets a database-lock recovery re-run the tool installation. - m_pendingRetryAction = "install-plugin-tool"; - setBusy(true); - statusBar()->showMessage( - QString("Installation de l'outil %1...").arg(QString::fromStdString(installHint))); - - auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Install, installHint); - connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { - statusBar()->showMessage(msg); - }); - connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); - connect(worker, &InstallWorker::finished, this, [this, id](bool success) { - setBusy(false); - clearCredentialsAfterUse(); - if (!success) { - statusBar()->showMessage("Échec de l'installation de l'outil."); - return; - } - - m_pluginManager->refreshAvailability(); - refreshPluginsTable(); - refreshDashboard(); - statusBar()->showMessage("Outil installé, plugin disponible."); - }); - connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); - worker->start(); -} - -void MainWindow::onTogglePlugin() { - if (m_selectedPluginId.empty()) return; - - const std::string id = m_selectedPluginId; - bool enabled = !m_pluginManager->isEnabled(id); - m_pluginManager->setEnabled(id, enabled); - - // A freshly enabled addon gets the main window so it can attach its UI - // (it may have been disabled when onUiReady ran at launch). - if (enabled) { - for (const auto& entry : m_pluginManager->plugins()) { - if (entry.info.id == id && entry.plugin) { - entry.plugin->onUiReady(this); - break; - } - } - } - - refreshPluginsTable(); - refreshDashboard(); - reloadCurrentView(); -} - -void MainWindow::onRescanPlugins() { - m_pluginManager->reload(); - - // Newly discovered addons need the main window to attach their UI. - for (IPlugin* addon : m_pluginManager->availableAddons()) { - addon->onUiReady(this); - } - - refreshPluginsTable(); - refreshDashboard(); - reloadCurrentView(); - statusBar()->showMessage("Plugins rechargés."); -} - -void MainWindow::refreshPluginsTable() { - const auto& plugins = m_pluginManager->plugins(); - - QFont nameFont; - nameFont.setWeight(QFont::DemiBold); - - TableFillBatch batch(m_pluginTable); - m_pluginTable->setRowCount(0); - m_pluginTable->setRowCount(static_cast(plugins.size())); - - for (int i = 0; i < static_cast(plugins.size()); ++i) { - const auto& entry = plugins[i]; - - QTableWidgetItem* nameItem = - new QTableWidgetItem(QString::fromStdString(entry.info.name)); - nameItem->setFont(nameFont); - nameItem->setData(Qt::UserRole, QString::fromStdString(entry.info.id)); - m_pluginTable->setItem(i, 0, nameItem); - - // Type column distinguishes package-manager providers from generic - // addons; the build origin is appended for external plugins. - QString kindText = entry.info.kind == PluginKind::Addon ? "Extension" - : "Fournisseur"; - QString typeText = entry.info.builtin ? kindText : kindText + " (externe)"; - QTableWidgetItem* typeItem = new QTableWidgetItem(typeText); - typeItem->setForeground(QColor("#7a8299")); - m_pluginTable->setItem(i, 1, typeItem); - - m_pluginTable->setItem(i, 2, - new QTableWidgetItem(QString::fromStdString(entry.info.version))); - m_pluginTable->setItem(i, 3, - new QTableWidgetItem(QString::fromStdString(entry.info.author))); - - QString statusText; - QColor statusColor; - if (!entry.info.available) { - statusText = "Indisponible"; - statusColor = QColor("#565f73"); - } else if (m_pluginManager->isEnabled(entry.info.id)) { - statusText = "Actif"; - statusColor = QColor("#3fb950"); - } else { - statusText = "Désactivé"; - statusColor = QColor("#e0af68"); - } - - QTableWidgetItem* statusItem = new QTableWidgetItem(statusText); - statusItem->setForeground(statusColor); - statusItem->setIcon(loadIcon( - entry.info.available ? (m_pluginManager->isEnabled(entry.info.id) ? "check" : "close") - : "alert")); - m_pluginTable->setItem(i, 4, statusItem); - } - batch.release(); - - if (!plugins.empty()) { - // Keep the previously selected plugin selected when possible. - int row = 0; - for (int i = 0; i < static_cast(plugins.size()); ++i) { - if (plugins[i].info.id == m_selectedPluginId) { - row = i; - break; - } - } - m_pluginTable->selectRow(row); - onPluginTableSelected(row); - } else { - m_pluginToggleButton->setEnabled(false); - m_pluginInstallButton->setVisible(false); - m_pluginDescription->clear(); - } -} - -// Starts an update check against the Gitea releases API. Used both at launch -// (once per day) and from the Aide menu. -// --------------------------------------------------------------------------- -// System tray: optional, only created when the desktop actually provides one. -// Offers quick access to the pending updates from outside the window. -// --------------------------------------------------------------------------- -void MainWindow::setupTray() { - if (!QSystemTrayIcon::isSystemTrayAvailable()) return; - - m_tray = new QSystemTrayIcon(loadIcon("package"), this); - m_tray->setToolTip("PacManager"); - - QMenu* menu = new QMenu(this); - menu->addAction("Afficher PacManager", this, [this]() { - showNormal(); - raise(); - activateWindow(); - }); - menu->addSeparator(); - menu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates); - menu->addAction("Prévisualiser les mises à jour", this, &MainWindow::onPreviewUpdates); - menu->addAction("Tout mettre à jour", this, &MainWindow::onUpdateAll); - menu->addSeparator(); - menu->addAction("Quitter", this, &QWidget::close); - m_tray->setContextMenu(menu); - - connect(m_tray, &QSystemTrayIcon::activated, this, &MainWindow::onTrayActivated); - m_tray->show(); -} - -void MainWindow::onTrayActivated(QSystemTrayIcon::ActivationReason reason) { - // A click on the icon brings the window back from the background. - if (reason != QSystemTrayIcon::Trigger && reason != QSystemTrayIcon::DoubleClick) { - return; - } - showNormal(); - raise(); - activateWindow(); -} - -void MainWindow::notifyUpdatesAvailable(int count) { - if (!m_tray || count <= 0) return; - m_tray->showMessage("PacManager", - QString("%1 mise(s) à jour disponible(s)").arg(count), - QSystemTrayIcon::Information, 5000); -} - -// Keyboard shortcuts for the actions used most often. -void MainWindow::setupShortcuts() { - auto bind = [this](const QKeySequence& key, const std::function& action) { - QShortcut* shortcut = new QShortcut(key, this); - shortcut->setContext(Qt::WindowShortcut); - connect(shortcut, &QShortcut::activated, this, action); - }; - - bind(QKeySequence::Find, [this]() { - m_navGroup->button(NavSearch)->click(); - m_searchBar->setFocus(); - m_searchBar->selectAll(); - }); - bind(QKeySequence::Refresh, [this]() { onRefresh(); }); - bind(QKeySequence(Qt::Key_F5), [this]() { onRefresh(); }); - bind(QKeySequence(QStringLiteral("Ctrl+U")), [this]() { - m_navGroup->button(NavUpdates)->click(); - }); - bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() { onExportPackageList(); }); - bind(QKeySequence::Quit, [this]() { close(); }); -} - -// Shows the pending updates without applying anything: jumps to the updates -// page, which lists every outdated package across the active providers. -void MainWindow::onPreviewUpdates() { - m_navGroup->button(NavUpdates)->click(); - statusBar()->showMessage("Prévisualisation des mises à jour disponibles"); -} - -// Exports the currently displayed package list (search / installed / updates) -// to a semicolon-separated CSV usable in a spreadsheet. -void MainWindow::onExportPackageList() { - if (m_currentResults.empty()) { - statusBar()->showMessage("Aucune liste à exporter."); - return; - } - const QString path = QFileDialog::getSaveFileName( - this, "Exporter la liste des paquets", - QDir::homePath() + "/pacmanager-paquets.csv", "CSV (*.csv)"); - if (path.isEmpty()) return; - - QFile file(path); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - QMessageBox::warning(this, "Export", - QString("Impossible d'écrire dans %1").arg(path)); - return; - } - QTextStream out(&file); - out << "Nom;Version;Depot;Fournisseur;Statut\n"; - for (const auto& pkg : m_currentResults) { - out << csvField(QString::fromStdString(pkg.name)) << ';' - << csvField(QString::fromStdString(pkg.version)) << ';' - << csvField(QString::fromStdString(pkg.repository)) << ';' - << csvField(providersLabel(m_pluginManager, pkg)) << ';' - << csvField(packageStatusText(pkg)) << '\n'; - } - statusBar()->showMessage( - QString("%1 paquet(s) exporté(s) vers %2") - .arg(static_cast(m_currentResults.size())).arg(path)); -} - -// Exports the recorded action history to CSV. -void MainWindow::onExportHistory() { - const auto& history = m_historyManager->getHistory(); - if (history.empty()) { - statusBar()->showMessage("Historique vide."); - return; - } - const QString path = QFileDialog::getSaveFileName( - this, "Exporter l'historique", - QDir::homePath() + "/pacmanager-historique.csv", "CSV (*.csv)"); - if (path.isEmpty()) return; - - QFile file(path); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - QMessageBox::warning(this, "Export", - QString("Impossible d'écrire dans %1").arg(path)); - return; - } - QTextStream out(&file); - out << "Date;Action;Paquet;Gestionnaire;Statut\n"; - for (const auto& entry : history) { - out << csvField(QString::fromStdString(entry.timestamp)) << ';' - << csvField(QString::fromStdString(entry.action)) << ';' - << csvField(QString::fromStdString(entry.package)) << ';' - << csvField(QString::fromStdString(entry.plugin)) << ';' - << (entry.success ? "Succes" : "Echec") << '\n'; - } - statusBar()->showMessage( - QString("Historique exporté vers %1").arg(path)); +void MainWindow::onCoreHistoryChanged() { + // The dashboard and history screens refresh themselves through the same + // signal; only the frame's summary line is updated here. + updateStatusBar(); } void MainWindow::onCheckForUpdates() { - statusBar()->showMessage("Vérification des mises à jour..."); - connect(m_updateManager, &UpdateManager::checkFinished, - this, &MainWindow::onUpdateCheckFinished); - m_updateManager->checkForUpdates(); + m_core->checkForAppUpdate(); } // Handles the result of a release check: offers to self-update when a newer // version exists, otherwise a status bar confirmation. Errors are reported // silently in the status bar so a network failure never blocks the app. -void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVersion, - const QString& errorMessage) { - disconnect(m_updateManager, &UpdateManager::checkFinished, - this, &MainWindow::onUpdateCheckFinished); - +void MainWindow::onCoreUpdateCheckFinished(bool hasUpdate, const QString& latestVersion, + const QString& errorMessage) { if (!errorMessage.isEmpty()) { statusBar()->showMessage(errorMessage); return; @@ -3269,8 +1040,8 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers // background (git pull from a checkout, clone + rebuild, prebuilt unpack, // or tarball rebuild); the running binary stays untouched and the app // hands over to the new build once the update succeeds. - const UpdateManager::UpdateMethod method = m_updateManager->updateMethod(); - const QString targetDir = m_updateManager->binDir(); + const UpdateManager::UpdateMethod method = m_core->updateMethod(); + const QString targetDir = m_core->binDir(); QMessageBox box(this); box.setWindowTitle("Mise à jour disponible"); @@ -3296,7 +1067,7 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers } if (method == UpdateManager::UpdateMethod::None) { - QDesktopServices::openUrl(QUrl(m_updateManager->releasePageUrl())); + QDesktopServices::openUrl(QUrl(m_core->releasePageUrl())); return; } @@ -3305,8 +1076,7 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers // running binary's directory, and only that final copy is privileged: // everything else builds in a temp directory owned by the user. QString sudoPassword; - if (!QFileInfo(targetDir).isWritable() - && m_pacman && m_pacman->isAvailable()) { + if (!m_core->binDirWritable()) { bool ok = false; sudoPassword = QInputDialog::getText( this, "Mise à jour", @@ -3321,17 +1091,18 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers qCInfo(pacmgrUpdate) << "applying update, method" << static_cast(method) << "target" << targetDir; statusBar()->showMessage("Mise à jour en cours en arrière-plan..."); - connect(m_updateManager, &UpdateManager::selfUpdateFinished, - this, &MainWindow::onSelfUpdateFinished); - m_updateManager->performSelfUpdate(sudoPassword); + + QString error; + if (!m_core->applySelfUpdate(sudoPassword, &error)) { + QMessageBox::warning(this, "Mise à jour", error); + return; + } + // onCoreSelfUpdateFinished reports the outcome once the build is done. } // Called when the background git pull + build finishes. A success hands over to // the freshly installed binary right away; a failure is reported in a dialog. -void MainWindow::onSelfUpdateFinished(bool success, const QString& message) { - disconnect(m_updateManager, &UpdateManager::selfUpdateFinished, - this, &MainWindow::onSelfUpdateFinished); - +void MainWindow::onCoreSelfUpdateFinished(bool success, const QString& message) { if (!success) { QMessageBox::warning(this, "Échec de la mise à jour", QString("

La mise à jour a échoué :

%1
") @@ -3346,7 +1117,7 @@ void MainWindow::onSelfUpdateFinished(bool success, const QString& message) { // Restarting is the only way to run the new build: this process still maps // the inode that was replaced on disk. Ask for a manual restart only when // no runnable binary is there to hand over to. - const QString program = UpdateManager::restartProgram(m_updateManager->binDir()); + const QString program = UpdateManager::restartProgram(m_core->binDir()); if (!program.isEmpty() && QProcess::startDetached(program, QCoreApplication::arguments().mid(1))) { qCInfo(pacmgrUpdate) << "update installed, relaunching" << program; diff --git a/src/workers.cpp b/src/workers.cpp new file mode 100644 index 0000000..da5f686 --- /dev/null +++ b/src/workers.cpp @@ -0,0 +1,131 @@ +#include "workers.h" + +#include + +SearchWorker::SearchWorker(const std::vector& providers, + const std::string& query) + : m_providers(providers), m_query(query) {} + +void SearchWorker::run() { + std::vector 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 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 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 providerOrder; + for (IPackageManager* pm : m_providers) providerOrder.push_back(pm->getName()); + sortByProviderThenName(results, providerOrder); + + emit finished(results); +} + +ListWorker::ListWorker(const std::vector& providers, Mode mode) + : m_providers(providers), m_mode(mode) {} + +void ListWorker::run() { + std::vector 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& packages) + : m_providers{pm}, m_op(op), m_packages(packages) {} + +InstallWorker::InstallWorker(const std::vector& 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; + } + + bool success = true; + for (IPackageManager* pm : m_providers) { + // 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](const std::string& msg, int percent) { + if (m_providers.size() > 1) { + emit progress(QString("[%1] %2") + .arg(QString::fromStdString(pm->getName()), + QString::fromStdString(msg))); + } else { + emit progress(QString::fromStdString(msg)); + } + if (percent >= 0) emit progressValue(percent); + }; + + // 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::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); +} diff --git a/tests/app-core.test.cpp b/tests/app-core.test.cpp new file mode 100644 index 0000000..d3cb9e6 --- /dev/null +++ b/tests/app-core.test.cpp @@ -0,0 +1,209 @@ +#include "app-core.h" + +#include +#include +#include +#include + +#include +#include + +// The logic layer is exercised here without a display and without QtWidgets — +// which is the point of the view/core split. Only requests that are decided +// before any command runs are asserted: an operation that would actually shell +// out to pacman or flatpak is covered by those providers' own tests. +namespace { + +void testCoreDescribesTheSystem() { + AppCore core; + + assert(!core.version().isEmpty()); + assert(core.historyCount() == 0); + assert(!core.busy()); + assert(!core.hasPendingRequest()); + + // pacman is compiled in, so at least one provider is always known. + const auto providers = core.availableProviders(); + bool pacmanAvailable = false; + for (IPackageManager* pm : providers) { + if (pm->getName() == "pacman") pacmanAvailable = true; + } + assert(pacmanAvailable == core.hasAvailableProvider()); + assert(core.providerFor("pacman") != nullptr); + // An unknown id falls back to the first available provider, which is what + // makes an operation on an untagged package still possible. + assert(core.providerFor("not-a-provider") == core.providerFor("pacman")); + assert(core.availableProviderNames().contains("pacman")); +} + +void testSearchRefusesAnEmptyQuery() { + AppCore core; + const AppCore::StartResult result = core.search(" "); + assert(!result.started); + assert(result.error.contains("terme de recherche")); + // A refused request must not leave anything pending. + assert(!core.hasPendingRequest()); +} + +void testInstallRefusesAMissingPackageName() { + AppCore core; + const AppCore::StartResult result = core.install(PackageInfo{}); + assert(!result.started); + assert(!result.error.isEmpty()); + assert(!core.hasPendingRequest()); +} + +void testBulkRemovalRefusesAnEmptySelection() { + AppCore core; + const AppCore::StartResult result = core.removePackages({}, QStringLiteral("rien")); + assert(!result.started); + assert(result.error.contains("supprimable")); +} + +void testPrivilegedActionAsksForThePasswordFirst() { + AppCore core; + if (!core.hasAvailableProvider()) return; // nothing to update on this box + + // No password captured yet: the request is refused but kept pending, so the + // view can prompt and replay it. + const AppCore::StartResult result = core.updateAll(); + assert(!result.started); + if (result.needsPassword) { + assert(core.hasPendingRequest()); + // The view would now supply the password and replay: simulated here by + // simply dropping the pending request, so no command is ever run. + core.cancelPendingRequest(); + assert(!core.hasPendingRequest()); + } +} + +void testCredentialsStayInTheCore() { + AppCore core; + assert(!core.hasSudoPassword()); + + core.setSudoPassword(QStringLiteral("hunter2")); + assert(core.hasSudoPassword()); + core.clearSudoPassword(); + assert(!core.hasSudoPassword()); +} + +void testCredentialModeIsPersistedAndReported() { + AppCore core; + + int messages = 0; + QObject::connect(&core, &AppCore::statusMessage, &core, + [&messages](const QString&) { ++messages; }); + + core.setCredentialMode(AppCore::CredentialMode::AtLaunch); + assert(core.credentialMode() == AppCore::CredentialMode::AtLaunch); + core.setCredentialMode(AppCore::CredentialMode::EachTime); + assert(core.credentialMode() == AppCore::CredentialMode::EachTime); + assert(messages >= 2); + + // Switching back to per-operation mode must drop any captured password. + core.setSudoPassword(QStringLiteral("hunter2")); + core.setCredentialMode(AppCore::CredentialMode::EachTime); + assert(!core.hasSudoPassword()); +} + +void testRetryWithoutAPendingRequestIsRefused() { + AppCore core; + const AppCore::StartResult result = core.retryPendingRequest(); + assert(!result.started); + assert(result.error.contains("attente")); +} + +void testHistoryIsOwnedByTheCore() { + AppCore core; + + int changes = 0; + QObject::connect(&core, &AppCore::historyChanged, &core, + [&changes] { ++changes; }); + + core.clearHistory(); + assert(core.historyCount() == 0); + assert(changes >= 1); + assert(core.history() != nullptr); +} + +void testPluginToggleAnnouncesTheChange() { + AppCore core; + + int changes = 0; + QObject::connect(&core, &AppCore::pluginsChanged, &core, + [&changes] { ++changes; }); + + const bool initial = core.plugins()->isEnabled("pacman"); + core.setPluginEnabled("pacman", !initial); + assert(core.plugins()->isEnabled("pacman") == !initial); + assert(changes == 1); + + core.setPluginEnabled("pacman", initial); + assert(core.plugins()->isEnabled("pacman") == initial); + assert(changes == 2); +} + +void testLogReadReportsItsFailure() { + AppCore core; + QString error; + const QString text = core.readPackageLog(&error); + // Either the log was read, or the reason is reported — never silence. + assert(!text.isEmpty() || !error.isEmpty()); +} + +void testUpdateStateIsReadableWithoutRunningAnything() { + AppCore core; + + assert(!core.binDir().isEmpty()); + // binDirWritable() and the update method are plain filesystem probes: they + // must answer without launching a build. + core.binDirWritable(); + core.updateMethodDescription(); + core.canSelfUpdate(); +} + +void testDatabaseLockIsQueryable() { + AppCore core; + + const PacmanManager::LockHolder holder = core.lockHolder(); + assert(holder.pid >= 0); + // A description is only produced while a lock is actually held. + if (core.databaseLocked()) { + assert(!core.databaseLockDescription().isEmpty()); + } else { + assert(core.databaseLockDescription().isEmpty()); + } +} + +} // namespace + +int main(int argc, char* argv[]) { + // Keep the test hermetic: QSettings, the history file and the update state + // all live under the user's home, which a test run must not touch. + QTemporaryDir home; + assert(home.isValid()); + qputenv("HOME", home.path().toLocal8Bit()); + qputenv("XDG_CONFIG_HOME", QDir(home.path()).filePath("config").toLocal8Bit()); + qputenv("XDG_DATA_HOME", QDir(home.path()).filePath("data").toLocal8Bit()); + + QCoreApplication app(argc, argv); + app.setApplicationName("PacManagerTest"); + app.setOrganizationName("FWSTest"); + + testCoreDescribesTheSystem(); + testSearchRefusesAnEmptyQuery(); + testInstallRefusesAMissingPackageName(); + testBulkRemovalRefusesAnEmptySelection(); + testPrivilegedActionAsksForThePasswordFirst(); + testCredentialsStayInTheCore(); + testCredentialModeIsPersistedAndReported(); + testRetryWithoutAPendingRequestIsRefused(); + testHistoryIsOwnedByTheCore(); + testPluginToggleAnnouncesTheChange(); + testLogReadReportsItsFailure(); + testUpdateStateIsReadableWithoutRunningAnything(); + testDatabaseLockIsQueryable(); + + std::cout << "app-core: all tests passed" << std::endl; + return 0; +}