Files
FWS-PacManage/src/main-window.cpp
T
BlackAngelTV ed58e87520 style(ui): match the interface to the FWS website's design system
The window carried a palette of its own, so the desktop app and the site
looked like two different products. The stylesheet now uses the website's
tokens (slate surfaces on a #0f172a page, sky-blue accent, serif headings,
pill-shaped badges); the site's rgba() borders are pre-blended because a Qt
stylesheet only takes solid colours, and plain widgets are left transparent
so the page glow shows through them.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-09-16 22:34:32 +02:00

1177 lines
48 KiB
C++

#include "main-window.h"
#include <QAction>
#include <QActionGroup>
#include <QButtonGroup>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QFrame>
#include <QHBoxLayout>
#include <QIcon>
#include <QInputDialog>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QPixmap>
#include <QProcess>
#include <QProgressBar>
#include <QPushButton>
#include <QShortcut>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QSystemTrayIcon>
#include <QTimer>
#include <QUrl>
#include <QVBoxLayout>
#include "app-logging.h"
#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, sizing it to the requested
// resolution.
static QPixmap iconPixmap(const QString& name, int size) {
return loadIcon(name).pixmap(QSize(size, size));
}
// 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");
}
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");
}
// 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).
//
// The palette and the shapes mirror the FWS website's stylesheets
// (p/assets/styles/var.css, styles.css and paquets.css): slate surfaces on a
// #0f172a page, a sky-blue accent, serif headings, pill-shaped badges and
// 8-16px radii. The site draws its borders and tints with rgba() over the
// surface below; a Qt stylesheet only takes a solid colour, so those values are
// pre-blended here onto the surface they sit on (#232c3f is the site's border
// over the page, #303b4e the same border over a card).
static QString appStyleSheet() {
return QStringLiteral(
// ---- Base ----
// Widgets stay transparent like in CSS: only real surfaces declare a
// background, so the page glow below shows through the layouts. The
// dialogs are listed explicitly because they are windows of their own
// and would otherwise fall back to the light system palette.
"QMainWindow, QDialog { background: #0f172a; }"
"QWidget { color: #e2e8f0; }"
// The site tints its dark page with a soft accent glow from the top
// left; Qt has no radial gradient, so a diagonal one stands in for it.
"QWidget#content {"
" background: qlineargradient(x1:0, y1:0, x2:0.85, y2:1,"
" stop:0 #13243b, stop:0.55 #0f172a, stop:1 #0f172a);"
"}"
// ---- Sidebar ----
// A raised surface, like the site's header and footer.
"QFrame#sidebar { background: #1e293b; border-right: 1px solid #232c3f; }"
"QWidget#logo { padding: 4px 0; }"
"QLabel#logoText { font-family: serif; font-size: 19px; font-weight: 700; color: #e2e8f0; }"
"QLabel#tagline { font-size: 11px; color: #64748b; padding: 0 8px 8px 8px; }"
// Navigation entries use the site's navigation idiom: a rounded shape
// that fills with the accent tint, the label turning accent.
"QPushButton[nav=\"true\"] {"
" text-align: left;"
" background: transparent;"
" border: 1px solid transparent;"
" border-radius: 8px;"
" padding: 9px 12px;"
" font-size: 13px;"
" font-weight: 600;"
" color: #94a3b8;"
"}"
"QPushButton[nav=\"true\"]:hover { background: #21384e; color: #7dd3fc; }"
"QPushButton[nav=\"true\"]:checked { background: #21384e; color: #38bdf8; }"
"QPushButton[nav=\"true\"]:disabled { color: #475569; }"
// ---- Header ----
"QWidget#header { background: #1e293b; border-bottom: 1px solid #232c3f; }"
"QLabel#headerTitle { font-family: serif; font-size: 21px; font-weight: 700; color: #e2e8f0; }"
"QLabel#headerSubtitle { font-size: 12px; color: #94a3b8; }"
// ---- Cards ----
// Cards read as raised surfaces: the site's slightly lighter slate, a
// hair line border and a rounded corner separate them from the page
// without adding shadows Qt cannot render consistently across
// platforms.
"QFrame#card {"
" background: #1e293b;"
" border: 1px solid #232c3f;"
" border-radius: 12px;"
"}"
// Stat cards carry a coloured left edge so the four metrics are told
// apart at a glance. The colours are the site's status and accent ones.
"QFrame#card[accent=\"blue\"] { border-left: 3px solid #38bdf8; }"
"QFrame#card[accent=\"amber\"] { border-left: 3px solid #fbbf24; }"
"QFrame#card[accent=\"cyan\"] { border-left: 3px solid #7dd3fc; }"
"QFrame#card[accent=\"green\"] { border-left: 3px solid #34d399; }"
// Small uppercase labels, as the site's section headings.
"QLabel#cardTitle { font-size: 11px; font-weight: 700; color: #64748b; letter-spacing: 1px; }"
"QLabel#statValue { font-size: 30px; font-weight: 800; color: #e2e8f0; }"
"QLabel#statTitle { font-size: 12px; color: #94a3b8; font-weight: 600; }"
// ---- Sidebar extras ----
"QLabel#sectionTitle {"
" font-size: 10px;"
" font-weight: 800;"
" color: #64748b;"
" letter-spacing: 1.2px;"
" padding: 14px 10px 2px 10px;"
"}"
"QLabel#versionLabel { font-size: 11px; color: #64748b; padding: 8px 10px; }"
"QPushButton[nav=\"true\"][highlighted=\"true\"] { color: #fbbf24; }"
// ---- Buttons ----
// Mirrors the site's .button: rounded, 1px transparent border that
// takes the accent when hovered, and a darker fill on hover.
"QPushButton {"
" background: #273449;"
" color: #94a3b8;"
" border: 1px solid #303b4e;"
" border-radius: 8px;"
" padding: 8px 16px;"
" font-size: 13px;"
" font-weight: 600;"
"}"
"QPushButton:hover { background: #29445e; border-color: #7dd3fc; color: #38bdf8; }"
"QPushButton:pressed { background: #22384d; color: #7dd3fc; }"
"QPushButton:disabled { background: #232c3f; border-color: transparent; color: #64748b; }"
"QPushButton[variant=\"primary\"] { background: #38bdf8; border-color: transparent; color: #0f172a; }"
"QPushButton[variant=\"primary\"]:hover { background: #0ea5e9; color: #0f172a; }"
"QPushButton[variant=\"primary\"]:pressed { background: #0284c7; color: #0f172a; }"
"QPushButton[variant=\"success\"] { background: #34d399; border-color: transparent; color: #0f172a; }"
"QPushButton[variant=\"success\"]:hover { background: #10b981; color: #0f172a; }"
"QPushButton[variant=\"success\"]:pressed { background: #059669; color: #0f172a; }"
"QPushButton[variant=\"danger\"] { background: #f87171; border-color: transparent; color: #0f172a; }"
"QPushButton[variant=\"danger\"]:hover { background: #ef4444; color: #0f172a; }"
"QPushButton[variant=\"danger\"]:pressed { background: #dc2626; color: #0f172a; }"
"QPushButton[variant=\"warning\"] { background: #fbbf24; border-color: transparent; color: #0f172a; }"
"QPushButton[variant=\"warning\"]:hover { background: #f59e0b; color: #0f172a; }"
"QPushButton[variant=\"warning\"]:pressed { background: #d97706; color: #0f172a; }"
"QPushButton[variant=\"info\"] { background: #7dd3fc; border-color: transparent; color: #0f172a; }"
"QPushButton[variant=\"info\"]:hover { background: #38bdf8; color: #0f172a; }"
"QPushButton[variant=\"info\"]:pressed { background: #0ea5e9; color: #0f172a; }"
// A disabled button keeps the muted fill of the site's :disabled rule,
// whatever its variant.
"QPushButton[variant=\"primary\"]:disabled, QPushButton[variant=\"success\"]:disabled,"
"QPushButton[variant=\"danger\"]:disabled, QPushButton[variant=\"warning\"]:disabled,"
"QPushButton[variant=\"info\"]:disabled {"
" background: #232c3f; border-color: transparent; color: #64748b;"
"}"
// ---- Inputs ----
"QLineEdit {"
" background: #1e293b;"
" border: 1px solid #303b4e;"
" border-radius: 8px;"
" padding: 9px 14px;"
" font-size: 13px;"
" color: #e2e8f0;"
" selection-background-color: #38bdf8;"
" selection-color: #0f172a;"
"}"
"QLineEdit:hover { border-color: #475569; }"
"QLineEdit:focus { border: 1px solid #38bdf8; }"
"QLineEdit:disabled { color: #64748b; }"
"QComboBox {"
" background: #1e293b;"
" border: 1px solid #303b4e;"
" border-radius: 8px;"
" padding: 7px 12px;"
" font-size: 13px;"
" color: #e2e8f0;"
"}"
"QComboBox:hover { border-color: #7dd3fc; }"
"QComboBox::drop-down { border: none; width: 26px; }"
"QComboBox QAbstractItemView {"
" background: #273449;"
" border: 1px solid #303b4e;"
" selection-background-color: #21384e;"
" selection-color: #38bdf8;"
" color: #e2e8f0;"
"}"
// ---- Progress bar ----
"QProgressBar { background: #273449; border: none; border-radius: 3px; }"
"QProgressBar::chunk { background: #38bdf8; border-radius: 3px; }"
// ---- Package table ----
// No outer frame: the table blends with the card it sits in, keeping
// only the column header and alternating rows as visual separators.
"QTableWidget {"
" background: transparent;"
" alternate-background-color: #223044;"
" border: none;"
" gridline-color: transparent;"
" outline: 0;"
"}"
"QTableWidget::item { border: none; padding: 4px 8px; }"
"QTableWidget::item:selected { background: #21384e; color: #e2e8f0; }"
// Hover stays below the selection tint, so a hovered row is never
// mistaken for the selected one.
"QTableWidget::item:hover { background: #1b2b40; }"
"QHeaderView { background: transparent; }"
"QHeaderView::section {"
" background: transparent;"
" color: #64748b;"
" border: none;"
" border-bottom: 1px solid #303b4e;"
" padding: 8px;"
" font-size: 11px;"
" font-weight: 700;"
" letter-spacing: 1px;"
"}"
// ---- Recent activity list ----
"QListWidget#recentList { background: transparent; border: none; outline: 0; }"
"QListWidget#recentList::item { border-radius: 8px; margin: 1px 2px; }"
"QListWidget#recentList::item:hover { background: #21384e; }"
// ---- Logs editor ----
// Recessed like the site's inline code: the page colour, not a card.
"QTextEdit {"
" background: #0f172a;"
" color: #e2e8f0;"
" border: 1px solid #303b4e;"
" border-radius: 12px;"
" padding: 10px;"
" font-family: monospace;"
" font-size: 13px;"
"}"
// ---- Menus ----
// The menu strip shares the header's surface, so the two read as the
// site's single top band.
"QMenuBar { background: #1e293b; color: #94a3b8; padding: 2px 4px; }"
"QMenuBar::item { padding: 6px 10px; border-radius: 6px; background: transparent; }"
"QMenuBar::item:selected { background: #21384e; color: #38bdf8; }"
"QMenu {"
" background: #1e293b;"
" color: #e2e8f0;"
" border: 1px solid #303b4e;"
" border-radius: 8px;"
" padding: 6px;"
"}"
"QMenu::item { padding: 7px 24px 7px 14px; border-radius: 6px; }"
"QMenu::item:selected { background: #21384e; color: #38bdf8; }"
"QMenu::item:disabled { color: #64748b; }"
"QMenu::separator { height: 1px; background: #303b4e; margin: 6px 8px; }"
// ---- Scrollbars ----
"QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; }"
"QScrollBar::handle:vertical { background: #273449; border-radius: 5px; min-height: 30px; }"
"QScrollBar::handle:vertical:hover { background: #38bdf8; }"
"QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; }"
"QScrollBar::handle:horizontal { background: #273449; border-radius: 5px; min-width: 30px; }"
"QScrollBar::handle:horizontal:hover { background: #38bdf8; }"
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical,"
"QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { height: 0; width: 0; }"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical,"
"QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { background: transparent; }"
// ---- Status bar ----
"QStatusBar {"
" background: #1e293b;"
" color: #94a3b8;"
" border-top: 1px solid #232c3f;"
" font-size: 12px;"
"}"
// ---- Splitter ----
"QSplitter::handle { background: transparent; }"
// ---- Tooltips ----
"QToolTip {"
" background: #273449;"
" color: #e2e8f0;"
" border: 1px solid #303b4e;"
" border-radius: 8px;"
" 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() {
m_sidebar = new QFrame();
m_sidebar->setObjectName("sidebar");
m_sidebar->setFixedWidth(210);
QVBoxLayout* layout = new QVBoxLayout(m_sidebar);
layout->setContentsMargins(12, 16, 12, 12);
layout->setSpacing(4);
QWidget* logoRow = new QWidget();
logoRow->setObjectName("logo");
QHBoxLayout* logoLayout = new QHBoxLayout(logoRow);
logoLayout->setContentsMargins(8, 2, 8, 2);
logoLayout->setSpacing(8);
QLabel* logoIcon = new QLabel();
logoIcon->setPixmap(iconPixmap("package", 20));
logoLayout->addWidget(logoIcon);
QLabel* appTitle = new QLabel("PacManager");
appTitle->setObjectName("logoText");
logoLayout->addWidget(appTitle);
logoLayout->addStretch();
layout->addWidget(logoRow);
QLabel* appSubtitle = new QLabel("Gestionnaire de paquets Arch Linux");
appSubtitle->setObjectName("tagline");
appSubtitle->setWordWrap(true);
layout->addWidget(appSubtitle);
layout->addSpacing(14);
m_navGroup = new QButtonGroup(this);
m_navGroup->setExclusive(true);
auto addSection = [&](const QString& title) {
QLabel* label = new QLabel(title);
label->setObjectName("sectionTitle");
layout->addWidget(label);
};
auto addNavButton = [&](int id, const QString& iconName,
const QString& text, const QString& tip) {
QPushButton* btn = new QPushButton(text);
btn->setProperty("nav", true);
btn->setCheckable(true);
btn->setToolTip(tip);
btn->setCursor(Qt::PointingHandCursor);
btn->setIcon(loadIcon(iconName));
btn->setIconSize(QSize(17, 17));
m_navGroup->addButton(btn, id);
layout->addWidget(btn);
return btn;
};
addSection("GESTION");
addNavButton(NavDashboard, "home", "Tableau de bord", "Vue d'ensemble du système");
addNavButton(NavSearch, "search", "Recherche", "Rechercher des paquets");
addNavButton(NavInstalled, "package", "Installés", "Voir les paquets installés");
m_navUpdatesButton = addNavButton(NavUpdates, "arrow-up", "Mises à jour",
"Voir les mises à jour disponibles");
addSection("SYSTÈME");
addNavButton(NavCleanup, "broom", "Nettoyage",
"Purger les paquets inutilisés ou legacy et vider les caches");
addNavButton(NavHistory, "history", "Historique", "Historique des actions");
addNavButton(NavLogs, "logs", "Logs", "Logs pacman");
addNavButton(NavPlugins, "plugin", "Plugins", "Gestionnaires de paquets et extensions");
connect(m_navGroup, &QButtonGroup::idClicked, this, &MainWindow::onNavChanged);
m_navGroup->button(NavDashboard)->setChecked(true);
layout->addStretch();
m_refreshButton = new QPushButton("Rafraîchir les sources");
m_refreshButton->setProperty("nav", true);
m_refreshButton->setIcon(loadIcon("refresh"));
m_refreshButton->setIconSize(QSize(17, 17));
m_refreshButton->setToolTip("Rafraîchir les bases de données (pacman -Sy)");
connect(m_refreshButton, &QPushButton::clicked, this, &MainWindow::onRefresh);
layout->addWidget(m_refreshButton);
// The version actually installed, right where the user looks for it.
m_versionLabel = new QLabel(QString("v%1").arg(UpdateManager::currentVersion()));
m_versionLabel->setObjectName("versionLabel");
m_versionLabel->setAlignment(Qt::AlignCenter);
m_versionLabel->setToolTip("Version installée de PacManager");
layout->addWidget(m_versionLabel);
}
void MainWindow::setupHeader() {
m_headerWidget = new QWidget();
m_headerWidget->setObjectName("header");
m_headerWidget->setFixedHeight(74);
QHBoxLayout* layout = new QHBoxLayout(m_headerWidget);
layout->setContentsMargins(24, 0, 24, 0);
layout->setSpacing(6);
QVBoxLayout* textLayout = new QVBoxLayout();
textLayout->setSpacing(2);
m_headerTitle = new QLabel("Tableau de bord");
m_headerTitle->setObjectName("headerTitle");
textLayout->addWidget(m_headerTitle);
m_headerSubtitle = new QLabel("Vue d'ensemble de votre système");
m_headerSubtitle->setObjectName("headerSubtitle");
textLayout->addWidget(m_headerSubtitle);
layout->addLayout(textLayout);
layout->addStretch();
// 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);
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);
}
// One screen per file under pages/: the frame only stacks them and answers
// their requests.
void MainWindow::setupPages() {
m_pages = new QStackedWidget();
m_dashboard = new DashboardPage(m_core);
registerPage("dashboard", NavDashboard, m_dashboard);
connect(m_dashboard, &DashboardPage::openPackage, this, &MainWindow::onOpenPackage);
// 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);
m_cleanup = new CleanupPage(m_core);
registerPage("cleanup", NavCleanup, m_cleanup);
m_history = new HistoryPage(m_core);
registerPage("history", NavHistory, m_history);
m_logs = new LogsPage(m_core);
registerPage("logs", NavLogs, m_logs);
m_plugins = new PluginsPage(m_core);
registerPage("plugins", NavPlugins, m_plugins);
}
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);
}
Page* MainWindow::currentPage() const {
return qobject_cast<Page*>(m_pages->currentWidget());
}
void MainWindow::updatePageTitle() {
Page* page = currentPage();
if (!page) return;
m_headerTitle->setText(page->navTitle());
m_headerSubtitle->setText(page->navSubtitle());
}
void MainWindow::updateStatusBar() {
const int providers = static_cast<int>(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);
}
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::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() {
// The menu bar and its menus are styled by the window stylesheet
// (appStyleSheet), which also covers the tray menu.
QMenuBar* menuBar = this->menuBar();
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, [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, goTo] { goTo(NavDashboard); });
toolsMenu->addAction("Rechercher", this, [this] {
m_navGroup->button(NavSearch)->click();
m_browse->focusSearch();
});
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, [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");
QActionGroup* credGroup = new QActionGroup(this);
credGroup->setExclusive(true);
QAction* credTitle = settingsMenu->addAction("Identifiants sudo");
credTitle->setEnabled(false);
m_credEachTimeAction = settingsMenu->addAction("Demander à chaque fois");
m_credEachTimeAction->setCheckable(true);
m_credEachTimeAction->setToolTip("Demande le mot de passe avant chaque opération");
credGroup->addAction(m_credEachTimeAction);
m_credLaunchAction = settingsMenu->addAction("Demander au lancement");
m_credLaunchAction->setCheckable(true);
m_credLaunchAction->setToolTip("Demande le mot de passe une seule fois, au lancement");
credGroup->addAction(m_credLaunchAction);
const bool atLaunch =
m_core->credentialMode() == AppCore::CredentialMode::AtLaunch;
(atLaunch ? m_credLaunchAction : m_credEachTimeAction)->setChecked(true);
connect(m_credEachTimeAction, &QAction::triggered, this,
[this]() { applyCredentialMode(AppCore::CredentialMode::EachTime); });
connect(m_credLaunchAction, &QAction::triggered, this,
[this]() { applyCredentialMode(AppCore::CredentialMode::AtLaunch); });
QMenu* helpMenu = menuBar->addMenu("Aide");
helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates);
helpMenu->addSeparator();
helpMenu->addAction("À propos", [this]() {
QMessageBox::about(this, "PacManager",
QString("<h2>PacManager v%1</h2>"
"<p>Gestionnaire de paquets pour Arch Linux (pacman).</p>")
.arg(UpdateManager::currentVersion()));
});
}
// 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, [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();
}
// Keyboard shortcuts for the actions used most often.
void MainWindow::setupShortcuts() {
auto bind = [this](const QKeySequence& key, const std::function<void()>& 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;
}
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;
const QString password = QInputDialog::getText(
this, "Authentification",
"Mot de passe administrateur (sudo) :",
QLineEdit::Password, QString(), &ok);
if (!ok) {
statusBar()->showMessage("Opération annulée : identifiants requis.");
return false;
}
m_core->setSudoPassword(password);
return true;
}
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.
if (locked) {
handleDatabaseLock(title);
return;
}
if (!error.isEmpty()) QMessageBox::warning(this, title, error);
}
// 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;
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;
}
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);
box.setIcon(QMessageBox::Warning);
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_core->hasPendingRequest();
const QString resume = canRetry
? QStringLiteral(" PacManager reprendra ensuite l'opération automatiquement.")
: QString();
if (holder.pid > 0) {
box.setText(QString("<b>%1</b> utilise déjà la base pacman.").arg(holderName));
box.setInformativeText(
"Le fermer libère la base ; une transaction en cours sera "
"interrompue." + resume);
} else {
box.setText(QString("La base pacman est verrouillée par %1.").arg(holderName));
box.setInformativeText(
"Aucun gestionnaire ne tourne : le verrou peut être supprimé sans "
"risque." + resume);
}
QPushButton* resolveBtn = box.addButton(
holder.pid > 0 ? (canRetry ? QStringLiteral("Fermer et réessayer")
: QStringLiteral("Fermer le gestionnaire"))
: (canRetry ? QStringLiteral("Supprimer et réessayer")
: QStringLiteral("Supprimer le verrou")),
QMessageBox::AcceptRole);
QPushButton* retryBtn =
box.addButton(QStringLiteral("Réessayer"), QMessageBox::ActionRole);
box.addButton(QStringLiteral("Plus tard"), QMessageBox::RejectRole);
box.exec();
if (box.clickedButton() == retryBtn) {
QTimer::singleShot(0, this, [this, title] {
handleStartResult(m_core->retryPendingRequest(), title);
});
return;
}
if (box.clickedButton() != resolveBtn) {
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 (!promptForSudoPassword()) {
m_core->cancelPendingRequest();
return;
}
// The core replays the pending action itself once the lock is gone.
handleStartResult(m_core->releaseDatabaseLock(), title);
}
// ---------------------------------------------------------------------------
// Results reported by the core
// ---------------------------------------------------------------------------
void MainWindow::onCoreListFinished(AppCore::ListMode mode,
std::vector<PackageInfo> results) {
if (mode != AppCore::ListMode::Updates) return;
const int count = static_cast<int>(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::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::onCoreActionFinished(const QString& action, const QString& name,
bool success, const QString& error, bool locked) {
if (!success) showActionError(actionErrorTitle(action), error, locked);
// 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();
}
Q_UNUSED(name);
}
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::onCoreStatusMessage(const QString& message) {
statusBar()->showMessage(message);
}
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() {
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::onCoreUpdateCheckFinished(bool hasUpdate, const QString& latestVersion,
const QString& errorMessage) {
if (!errorMessage.isEmpty()) {
statusBar()->showMessage(errorMessage);
return;
}
if (!hasUpdate) {
statusBar()->showMessage(
QString("PacManager est à jour (v%1)").arg(UpdateManager::currentVersion()));
return;
}
// Ask the user whether to update now or skip. The update runs in the
// 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_core->updateMethod();
const QString targetDir = m_core->binDir();
QMessageBox box(this);
box.setWindowTitle("Mise à jour disponible");
box.setIcon(QMessageBox::Information);
box.setTextFormat(Qt::RichText);
box.setText(QString("<h3>PacManager v%1 est disponible</h3>"
"<p>Vous utilisez actuellement la version %2.</p>")
.arg(latestVersion, UpdateManager::currentVersion()));
QPushButton* updateBtn = box.addButton("Mettre à jour", QMessageBox::AcceptRole);
box.addButton("Plus tard", QMessageBox::RejectRole);
if (method == UpdateManager::UpdateMethod::None) {
// No local way to update: offer the releases page instead of a button
// that would immediately fail.
updateBtn->setText("Ouvrir la page des releases");
}
box.setInformativeText(UpdateManager::methodDescription(method, targetDir));
box.exec();
if (box.clickedButton() != updateBtn) {
// "Plus tard" (or closing the dialog) simply skips the update.
return;
}
if (method == UpdateManager::UpdateMethod::None) {
QDesktopServices::openUrl(QUrl(m_core->releasePageUrl()));
return;
}
// Prompt for the sudo password only when the update must write into a
// root-owned directory (e.g. /usr/bin). Every method installs into the
// 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 (!m_core->binDirWritable()) {
bool ok = false;
sudoPassword = QInputDialog::getText(
this, "Mise à jour",
QString("Mot de passe sudo pour installer dans %1 :").arg(targetDir),
QLineEdit::Password, QString(), &ok);
if (!ok) {
statusBar()->showMessage("Mise à jour annulée.");
return;
}
}
qCInfo(pacmgrUpdate) << "applying update, method" << static_cast<int>(method)
<< "target" << targetDir;
statusBar()->showMessage("Mise à jour en cours en arrière-plan...");
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::onCoreSelfUpdateFinished(bool success, const QString& message) {
if (!success) {
QMessageBox::warning(this, "Échec de la mise à jour",
QString("<p>La mise à jour a échoué :</p><pre>%1</pre>")
.arg(message.toHtmlEscaped()));
return;
}
// The build log is no longer shown to the user, so keep it in the app log
// for troubleshooting.
qCInfo(pacmgrUpdate) << "self-update output:" << 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_core->binDir());
if (!program.isEmpty()
&& QProcess::startDetached(program, QCoreApplication::arguments().mid(1))) {
qCInfo(pacmgrUpdate) << "update installed, relaunching" << program;
statusBar()->showMessage("Mise à jour terminée, redémarrage de PacManager...");
// Quit on the next event-loop pass so the message paints first. The new
// process is detached and outlives this one.
QTimer::singleShot(0, qApp, &QCoreApplication::quit);
return;
}
qCWarning(pacmgrUpdate) << "could not relaunch" << program;
QMessageBox::information(this, "Mise à jour terminée",
QString("<h3>PacManager a été mis à jour</h3>"
"<p>La nouvelle version sera active au prochain démarrage.</p>"
"<pre>%1</pre>")
.arg(message.toHtmlEscaped()));
}