Files
BlackAngelTV 3e85db87b2 refactor(pages): group the screens by what the user is doing
pages/ was a flat row of eight screens, so a change to one meant scanning
the whole folder to see what else was in it. The screens now sit in
packages/ (browse, cleanup), overview/ (dashboard, history), system/
(logs, settings) and extensions/ (plugins), with the scaffolding they
all build on — the Page base and the shared widgets — in base/.
2026-09-29 21:26:51 +02:00

522 lines
20 KiB
C++

#include "settings-page.h"
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QDateTime>
#include <QDesktopServices>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QScrollArea>
#include <QSizePolicy>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QStyle>
#include <QUrl>
#include <QVBoxLayout>
#include "language-manager.h"
#include "log-manager.h"
#include "ui-kit.h"
#include "update-manager.h"
namespace {
// Journal size caps offered by the screen, in bytes; 0 being "no cap".
struct SizeChoice {
qint64 bytes;
const char* label;
};
constexpr SizeChoice kSizeChoices[] = {
{0, QT_TRANSLATE_NOOP("SettingsPage", "Illimité")},
{1LL * 1024 * 1024, QT_TRANSLATE_NOOP("SettingsPage", "1 Mo")},
{5LL * 1024 * 1024, QT_TRANSLATE_NOOP("SettingsPage", "5 Mo")},
{20LL * 1024 * 1024, QT_TRANSLATE_NOOP("SettingsPage", "20 Mo")},
{100LL * 1024 * 1024, QT_TRANSLATE_NOOP("SettingsPage", "100 Mo")},
};
// Plain helpers in an anonymous namespace: they translate through
// QCoreApplication rather than through a QObject.
QString formatSize(qint64 bytes) {
if (bytes <= 0) return QCoreApplication::translate("SettingsPage", "vide");
if (bytes < 1024) {
return QCoreApplication::translate("SettingsPage", "%1 o").arg(bytes);
}
if (bytes < 1024 * 1024) {
return QCoreApplication::translate("SettingsPage", "%1 Ko").arg(bytes / 1024);
}
return QCoreApplication::translate("SettingsPage", "%1 Mo")
.arg(bytes / (1024 * 1024));
}
QString formatDeadline(const QDateTime& until) {
return until.toString(QStringLiteral("dd/MM/yyyy hh:mm"));
}
} // namespace
AppSettings* SettingsPage::preferences() const {
return &AppSettings::instance();
}
SettingsPage::SettingsPage(AppCore* core, QWidget* parent) : Page(core, parent) {
// The screen is taller than the window at its minimum size, so the cards
// live in a scroll area rather than being squeezed or clipped.
QScrollArea* scroll = new QScrollArea();
scroll->setWidgetResizable(true);
scroll->setFrameShape(QFrame::NoFrame);
scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
QWidget* content = new QWidget();
QVBoxLayout* layout = new QVBoxLayout(content);
layout->setContentsMargins(24, 20, 24, 20);
layout->setSpacing(14);
layout->addWidget(buildCredentialsCard());
layout->addWidget(buildLogCard());
layout->addWidget(buildDragDropCard());
layout->addWidget(buildLanguageCard());
layout->addWidget(buildUpdateCard());
layout->addStretch();
scroll->setWidget(content);
QVBoxLayout* outer = new QVBoxLayout(this);
outer->setContentsMargins(0, 0, 0, 0);
outer->addWidget(scroll);
// The model is the single source of truth: anything changing elsewhere
// (the menu bar for the credential mode, a restored settings file) is
// reflected here without the screen keeping a second copy.
connect(preferences(), &AppSettings::logDirectoryChanged, this,
[this] { loadLogCard(); });
connect(preferences(), &AppSettings::logMaxBytesChanged, this,
[this] { loadLogCard(); });
connect(preferences(), &AppSettings::languageChanged, this,
[this] { loadLanguageCard(); });
connect(preferences(), &AppSettings::dragDropEnabledChanged, this, [this] {
m_dragDrop->setChecked(preferences()->dragDropEnabled());
});
connect(preferences(), &AppSettings::autoUpdateCheckEnabledChanged, this,
[this] { loadUpdateCard(); });
connect(preferences(), &AppSettings::updateBlockChanged, this,
[this] { loadUpdateCard(); });
loadLogCard();
loadLanguageCard();
loadUpdateCard();
}
// A titled card, with the title rule and the paddings every section shares.
QFrame* SettingsPage::card(const QString& title, QVBoxLayout** layoutOut) const {
QFrame* frame = ui::card();
frame->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
QVBoxLayout* layout = new QVBoxLayout(frame);
layout->setContentsMargins(18, 16, 18, 18);
layout->setSpacing(10);
QLabel* titleLabel = new QLabel(title);
titleLabel->setObjectName("cardTitle");
layout->addWidget(titleLabel);
if (layoutOut) *layoutOut = layout;
return frame;
}
QString SettingsPage::navTitle() const {
return tr("Paramètres");
}
QString SettingsPage::navSubtitle() const {
return tr("Préférences de PacManager : journal, glisser-déposer, langue et mises à jour");
}
void SettingsPage::refresh() {
loadLogCard();
loadLanguageCard();
loadUpdateCard();
}
// ---------------------------------------------------------------------------
// Credentials
// ---------------------------------------------------------------------------
QFrame* SettingsPage::buildCredentialsCard() {
QVBoxLayout* layout = nullptr;
QFrame* frame = card(tr("MOT DE PASSE ADMINISTRATEUR"), &layout);
QLabel* question = new QLabel(tr("Quand PacManager doit-il demander le mot de passe sudo ?"));
question->setWordWrap(true);
layout->addWidget(question);
m_credentialMode = new QComboBox();
m_credentialMode->addItem(tr("Avant chaque opération"));
m_credentialMode->addItem(tr("Une seule fois, au lancement"));
m_credentialMode->setToolTip(
tr("« Au lancement » garde le mot de passe pour toute la session : moins de "
"questions, mais il reste en mémoire jusqu'à la fermeture."));
m_credentialMode->setCurrentIndex(
core()->credentialMode() == AppCore::CredentialMode::AtLaunch ? 1 : 0);
// The frame owns the sudo dialog, so it is the one that changes the mode:
// the screen asks, the frame prompts when the new mode needs it and keeps
// the menu bar's checkmarks in step.
connect(m_credentialMode, &QComboBox::currentIndexChanged, this,
[this](int index) { emit credentialModeRequested(index == 1); });
QHBoxLayout* row = new QHBoxLayout();
row->addWidget(m_credentialMode);
row->addStretch();
layout->addLayout(row);
m_credentialHint = new QLabel();
m_credentialHint->setObjectName("settingHint");
m_credentialHint->setWordWrap(true);
layout->addWidget(m_credentialHint);
auto updateHint = [this] {
m_credentialHint->setText(
m_credentialMode->currentIndex() == 1
? tr("Le mot de passe est demandé au lancement puis conservé jusqu'à la "
"fermeture de la fenêtre. Les paquets système restent protégés : "
"il n'est stocké nulle part.")
: tr("PacManager vous demandera le mot de passe avant chaque installation, "
"suppression ou mise à jour."));
};
connect(m_credentialMode, &QComboBox::currentIndexChanged, this,
[updateHint](int) { updateHint(); });
updateHint();
return frame;
}
// ---------------------------------------------------------------------------
// Journal
// ---------------------------------------------------------------------------
QFrame* SettingsPage::buildLogCard() {
QVBoxLayout* layout = nullptr;
QFrame* frame = card(tr("JOURNAL"), &layout);
QLabel* question = new QLabel(tr("Où PacManager enregistre-t-il ses logs ?"));
question->setWordWrap(true);
layout->addWidget(question);
m_logDirectory = new QLineEdit();
m_logDirectory->setReadOnly(true);
m_logDirectory->setToolTip(tr("Le journal contient toutes les opérations et la sortie "
"des commandes, comme le ferait un terminal."));
// Drops go to the window, which installs Flatpak files, not to a path field.
m_logDirectory->setAcceptDrops(false);
QPushButton* browseButton = new QPushButton(tr("Changer…"));
browseButton->setToolTip(tr("Choisir le dossier qui recevra operations.log"));
connect(browseButton, &QPushButton::clicked, this,
&SettingsPage::chooseLogDirectory);
QPushButton* openButton = new QPushButton(tr("Ouvrir le dossier"));
openButton->setProperty("variant", "primary");
connect(openButton, &QPushButton::clicked, this, &SettingsPage::openLogDirectory);
m_logResetButton = new QPushButton(tr("Réinitialiser"));
m_logResetButton->setToolTip(tr("Revenir au dossier par défaut de l'utilisateur"));
connect(m_logResetButton, &QPushButton::clicked, this,
&SettingsPage::resetLogDirectory);
QHBoxLayout* row = new QHBoxLayout();
row->setSpacing(8);
row->addWidget(m_logDirectory, 1);
row->addWidget(browseButton);
row->addWidget(openButton);
row->addWidget(m_logResetButton);
layout->addLayout(row);
QHBoxLayout* sizeRow = new QHBoxLayout();
sizeRow->setSpacing(8);
QLabel* sizeLabel = new QLabel(tr("Taille maximale :"));
sizeRow->addWidget(sizeLabel);
m_logMaxSize = new QComboBox();
for (const SizeChoice& choice : kSizeChoices) {
m_logMaxSize->addItem(tr(choice.label), static_cast<qlonglong>(choice.bytes));
}
m_logMaxSize->setToolTip(
tr("Au-delà de cette taille, le journal est enregistré et remplacé par un "
"journal neuf. Le précédent est conservé (operations.log.1)."));
connect(m_logMaxSize, &QComboBox::currentIndexChanged, this, [this](int) {
preferences()->setLogMaxBytes(m_logMaxSize->currentData().toLongLong());
});
sizeRow->addWidget(m_logMaxSize);
m_logSizeLabel = new QLabel();
m_logSizeLabel->setObjectName("settingHint");
sizeRow->addWidget(m_logSizeLabel, 1);
layout->addLayout(sizeRow);
return frame;
}
void SettingsPage::loadLogCard() {
const AppSettings& prefs = *preferences();
m_logDirectory->setText(prefs.logDirectory());
const qint64 current = prefs.logMaxBytes();
int index = m_logMaxSize->findData(static_cast<qlonglong>(current));
// A cap typed by hand (or written by a newer build) is not one of the
// offered steps: show it rather than silently rounding it down.
if (index < 0) {
m_logMaxSize->addItem(tr("Personnalisé (%1)").arg(formatSize(current)),
static_cast<qlonglong>(current));
index = m_logMaxSize->count() - 1;
}
m_logMaxSize->setCurrentIndex(index);
m_logResetButton->setEnabled(prefs.logDirectory() != AppSettings::defaultLogDirectory());
updateLogSizeLabel();
}
void SettingsPage::updateLogSizeLabel() {
m_logSizeLabel->setText(
tr("Journal actuel : %1").arg(formatSize(LogManager::instance().currentSizeBytes())));
}
void SettingsPage::chooseLogDirectory() {
const QString chosen = QFileDialog::getExistingDirectory(
this, tr("Dossier du journal"), m_logDirectory->text());
if (chosen.isEmpty()) return;
preferences()->setLogDirectory(chosen);
emit message(tr("Journal déplacé vers %1").arg(chosen));
}
void SettingsPage::openLogDirectory() {
const QString directory = preferences()->logDirectory();
// Revealed in the file manager when the desktop offers that service, and
// simply reported otherwise: the path stays visible in the field either way.
if (!QDesktopServices::openUrl(QUrl::fromLocalFile(directory))) {
emit message(tr("Dossier du journal : %1").arg(directory));
}
}
void SettingsPage::resetLogDirectory() {
preferences()->setLogDirectory(AppSettings::defaultLogDirectory());
emit message(tr("Journal replacé dans le dossier par défaut"));
}
// ---------------------------------------------------------------------------
// Drag & drop
// ---------------------------------------------------------------------------
QFrame* SettingsPage::buildDragDropCard() {
QVBoxLayout* layout = nullptr;
QFrame* frame = card(tr("GLISSER-DÉPOSER"), &layout);
m_dragDrop = new QCheckBox(tr("Accepter les fichiers Flatpak déposés sur la fenêtre"));
m_dragDrop->setChecked(preferences()->dragDropEnabled());
m_dragDrop->setToolTip(
tr("Installer un .flatpakref, .flatpakrepo ou .flatpak en le glissant sur la "
"fenêtre, au lieu de passer par « Ouvrir avec »."));
connect(m_dragDrop, &QCheckBox::toggled, this, [this](bool on) {
preferences()->setDragDropEnabled(on);
emit message(on ? tr("Glisser-déposer activé")
: tr("Glisser-déposer désactivé"));
});
layout->addWidget(m_dragDrop);
QLabel* hint = new QLabel(
tr("Désactivé, le dépôt est refusé par la fenêtre. « Ouvrir avec PacManager » "
"depuis le gestionnaire de fichiers, lui, continue de fonctionner."));
hint->setObjectName("settingHint");
hint->setWordWrap(true);
layout->addWidget(hint);
return frame;
}
// ---------------------------------------------------------------------------
// Language
// ---------------------------------------------------------------------------
QFrame* SettingsPage::buildLanguageCard() {
QVBoxLayout* layout = nullptr;
QFrame* frame = card(tr("LANGUE"), &layout);
QLabel* question = new QLabel(tr("Langue de l'interface"));
question->setWordWrap(true);
layout->addWidget(question);
m_language = new QComboBox();
// "System" names the language it resolves to: a user who installed FWS in
// German and sees French wants to know which entry would change that.
m_language->addItem(
tr("Langue du système (%1)").arg(
AppSettings::languageName(LanguageManager::resolve(QStringLiteral("system")))),
QStringLiteral("system"));
for (const QString& code : AppSettings::knownLanguages()) {
m_language->addItem(AppSettings::languageName(code), code);
}
connect(m_language, &QComboBox::currentIndexChanged, this, [this](int) {
const QString code = m_language->currentData().toString();
if (code == preferences()->language()) return;
preferences()->setLanguage(code);
// Installed here rather than left to the next launch: the whole point
// of the setting is to see the interface change.
LanguageManager::apply(code);
emit message(tr("Langue de l'interface : %1")
.arg(m_language->currentText()));
});
layout->addWidget(m_language);
m_languageHint = new QLabel();
m_languageHint->setObjectName("settingHint");
m_languageHint->setWordWrap(true);
layout->addWidget(m_languageHint);
return frame;
}
void SettingsPage::loadLanguageCard() {
const QString current = preferences()->language();
int index = m_language->findData(current);
m_language->setCurrentIndex(index >= 0 ? index : 0);
// A language whose catalogue is not installed is listed but not offered:
// choosing it would change nothing, and saying so is better than a setting
// that silently does not apply.
for (int i = 0; i < m_language->count(); ++i) {
const QString code = m_language->itemData(i).toString();
const bool available = code == QLatin1String("system") ||
LanguageManager::isTranslationAvailable(code);
m_language->setItemData(i, available ? QVariant() : tr("traduction non installée"),
Qt::ToolTipRole);
// A disabled entry stays in the list, greyed out, so the user can see
// the language exists and why it cannot be picked.
auto* model = qobject_cast<QStandardItemModel*>(m_language->model());
if (QStandardItem* item = model ? model->item(i) : nullptr) {
item->setEnabled(available);
}
}
const QString path = LanguageManager::searchPathHint();
m_languageHint->setText(
path.isEmpty()
? tr("Aucune traduction installée : l'interface reste dans la langue de "
"PacManager. Les catalogues sont cherchés dans un dossier "
"« translations » à côté de la configuration ou de l'exécutable.")
: tr("Catalogues : %1").arg(path));
}
// ---------------------------------------------------------------------------
// Application updates
// ---------------------------------------------------------------------------
QFrame* SettingsPage::buildUpdateCard() {
QVBoxLayout* layout = nullptr;
QFrame* frame = card(tr("MISES À JOUR DE PACMANAGER"), &layout);
m_autoUpdateCheck = new QCheckBox(tr("Vérifier les nouvelles versions au lancement"));
m_autoUpdateCheck->setChecked(preferences()->autoUpdateCheckEnabled());
m_autoUpdateCheck->setToolTip(
tr("Une vérification par jour maximum, au démarrage. Les paquets du système "
"ne sont pas concernés."));
connect(m_autoUpdateCheck, &QCheckBox::toggled, this, [this](bool on) {
preferences()->setAutoUpdateCheckEnabled(on);
});
layout->addWidget(m_autoUpdateCheck);
QHBoxLayout* blockRow = new QHBoxLayout();
blockRow->setSpacing(8);
QLabel* blockLabel = new QLabel(tr("Bloquer les mises à jour pendant"));
blockRow->addWidget(blockLabel);
m_updateBlockDelay = new QComboBox();
m_updateBlockDelay->addItem(tr("1 heure"), 1);
m_updateBlockDelay->addItem(tr("24 heures"), 24);
m_updateBlockDelay->addItem(tr("7 jours"), 24 * 7);
m_updateBlockDelay->addItem(tr("Jusqu'à annulation"), 0);
m_updateBlockDelay->setToolTip(
tr("Pendant cette durée, aucune vérification de version n'est faite, même "
"depuis le menu Aide."));
blockRow->addWidget(m_updateBlockDelay);
m_updateBlockButton = new QPushButton(tr("Bloquer"));
m_updateBlockButton->setProperty("variant", "warning");
connect(m_updateBlockButton, &QPushButton::clicked, this, [this] {
if (preferences()->updatesBlocked()) {
clearUpdateBlock();
} else {
applyUpdateBlock();
}
});
blockRow->addWidget(m_updateBlockButton);
blockRow->addStretch();
layout->addLayout(blockRow);
m_updateHint = new QLabel();
m_updateHint->setObjectName("settingHint");
m_updateHint->setWordWrap(true);
layout->addWidget(m_updateHint);
return frame;
}
void SettingsPage::loadUpdateCard() {
m_autoUpdateCheck->setChecked(preferences()->autoUpdateCheckEnabled());
// The delay picker only matters while nothing is blocked, so it is disabled
// with the block in force — there is nothing left to choose.
m_updateBlockDelay->setEnabled(!preferences()->updatesBlocked());
m_updateBlockButton->setText(preferences()->updatesBlocked() ? tr("Débloquer")
: tr("Bloquer"));
m_updateBlockButton->setProperty(
"variant", preferences()->updatesBlocked() ? QStringLiteral("success")
: QStringLiteral("warning"));
m_updateBlockButton->style()->unpolish(m_updateBlockButton);
m_updateBlockButton->style()->polish(m_updateBlockButton);
updateUpdateHint();
}
void SettingsPage::applyUpdateBlock() {
const int hours = m_updateBlockDelay->currentData().toInt();
preferences()->blockUpdatesFor(hours);
emit message(hours <= 0
? tr("Mises à jour de PacManager bloquées jusqu'à annulation")
: tr("Mises à jour de PacManager bloquées pendant %1 h")
.arg(hours));
}
void SettingsPage::clearUpdateBlock() {
preferences()->unblockUpdates();
emit message(tr("Vérification des mises à jour réactivée"));
}
void SettingsPage::updateUpdateHint() {
const AppSettings& prefs = *preferences();
QString hint = tr("Version installée : v%1. Ces réglages ne concernent que "
"PacManager : les mises à jour des paquets du système ne sont "
"jamais bloquées.")
.arg(UpdateManager::currentVersion());
if (prefs.updatesBlocked()) {
const QString remaining = AppSettings::blockDescription(
prefs.updatesBlockedIndefinitely(), prefs.updateBlockedUntil(),
QDateTime::currentDateTime());
hint += QLatin1Char(' ') +
(prefs.updatesBlockedIndefinitely()
? remaining
: tr("%1 (jusqu'au %2)")
.arg(remaining, formatDeadline(prefs.updateBlockedUntil())));
}
m_updateHint->setText(hint);
}