feat(settings): add a dedicated screen for every user preference

The preferences used to be spread across a menu entry and hardcoded paths,
so the user could not see them, let alone change them: where the journal
goes, whether a dropped Flatpak file is accepted, and when the app checks
its own version were all decided in code.

They now live in AppSettings, one model the rest of the app already reads,
and the new Settings screen only writes to it. Nothing keeps a second copy
of a value, so a change is visible everywhere at once — switching directory
moves the journal, unchecking drag & drop makes the window refuse the drop,
blocking the update has the manual check say why instead of silently doing
nothing.

The update block is deliberately limited to PacManager itself: blocking a
system package update is a decision the app has no business making.

The language setting installs a Qt catalogue and asks every widget to
retranslate. The interface is still written in French with QStringLiteral,
so no catalogue ships yet; a language with none is shown in the list but
disabled rather than silently doing nothing, and Qt Linguist stays optional
so the build does not depend on it.
This commit is contained in:
BlackAngelTV committed 2026-09-28 20:44:21 +02:00
1 parent ed8185d5fe
commit aff959bc4b
27 files changed
+1906 -27

No files matched your search

+41 -2
View File
@@ -32,6 +32,8 @@ set(SOURCES
src/package-model.cpp
src/update-manager.cpp
src/app-logging.cpp
src/app-settings.cpp
src/language-manager.cpp
# Logic layer: background workers, the plugin shop and the controller the
# screens delegate to.
src/workers.cpp
@@ -47,6 +49,7 @@ set(SOURCES
src/log-manager.cpp
pages/logs-page.cpp
pages/plugins-page.cpp
pages/settings-page.cpp
resources/resources.qrc
)
@@ -60,6 +63,8 @@ set(HEADERS
include/package-model.h
include/update-manager.h
include/app-logging.h
include/app-settings.h
include/language-manager.h
include/workers.h
include/progress-tracker.h
include/plugin-shop.h
@@ -73,6 +78,7 @@ set(HEADERS
pages/history-page.h
pages/logs-page.h
pages/plugins-page.h
pages/settings-page.h
)
add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})
@@ -189,15 +195,48 @@ 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/plugin-shop.cpp
src/app-logging.cpp src/log-manager.cpp
src/app-logging.cpp src/log-manager.cpp src/app-settings.cpp
include/app-core.h include/workers.h include/update-manager.h
include/plugin-shop.h include/log-manager.h)
include/plugin-shop.h include/log-manager.h include/app-settings.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)
# AppSettings: the whole preferences model, exercised against a temporary
# settings file. The static policy (what a block lasts, when it is in force, what
# a cap or a directory is worth) is pure and needs no clock.
add_executable(app-settings-test tests/app-settings.test.cpp
src/app-settings.cpp src/log-manager.cpp include/app-settings.h
include/log-manager.h)
target_include_directories(app-settings-test PRIVATE include)
target_link_libraries(app-settings-test PRIVATE Qt6::Core)
add_test(NAME app-settings-test COMMAND app-settings-test)
# ---- Translations ----
#
# The language setting loads Qt catalogues named pacmanager_<code>.qm, looked up
# at runtime next to the settings or next to the binary (see
# src/language-manager.cpp). Compiling the .ts sources into .qm needs Qt
# Linguist, which is not always installed: when it is missing the app simply
# runs untranslated, so the build must not depend on it.
find_package(Qt6 QUIET COMPONENTS LinguistTools)
if(Qt6LinguistTools_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/translations)
file(GLOB PACMANAGER_TS_FILES ${CMAKE_CURRENT_SOURCE_DIR}/translations/*.ts)
if(PACMANAGER_TS_FILES)
qt_add_translation(PACMANAGER_QM_FILES ${PACMANAGER_TS_FILES})
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
$<TARGET_FILE_DIR:${PROJECT_NAME}>/translations
COMMAND ${CMAKE_COMMAND} -E copy
${PACMANAGER_QM_FILES}
$<TARGET_FILE_DIR:${PROJECT_NAME}>/translations/)
install(FILES ${PACMANAGER_QM_FILES}
DESTINATION bin/translations)
endif()
endif()
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)
+1
View File
@@ -13,6 +13,7 @@ Package manager for **Arch Linux** based on **pacman**, with a Qt6 graphical int
- 🧩 **Plugins**: package managers (pacman built-in, **Flatpak shipped by default**) and **extensions** written in C++ (UI addons, helpers, …)
- 📥 **Flatpak files**: drop a `.flatpakref`, `.flatpakrepo` or `.flatpak` onto the window (or right-click → **Open with PacManager** in your file manager) to install it directly — with the bytes actually downloaded and the elapsed time shown live, since flatpak prints nothing while a runtime comes down
- 🔁 **Several installations**: an application installed per-user *and* system-wide, or from two remotes, stays a **single row**; the details panel lists the copies and **Remove** opens one checkbox per installation so the user picks the ones to get rid of
- ⚙️ **Settings**: when the admin password is asked, **where** the journal is written and how large it may grow, drag & drop of Flatpak files on or off, the interface language, and PacManager's own update policy (automatic check, block for 1 h / 24 h / 7 days / until cancelled)
## Architecture
+1
View File
@@ -13,6 +13,7 @@ Gestionnaire de paquets pour **Arch Linux** basé sur **pacman**, avec interface
- 🧩 **Plugins** : gestionnaires de paquets (pacman intégré, **Flatpak livré par défaut**) et **extensions** écrites en C++ (addons graphiques, helpers, …)
- 📥 **Fichiers Flatpak** : glissez-déposez un `.flatpakref`, `.flatpakrepo` ou `.flatpak` sur la fenêtre (ou clic droit → **Ouvrir avec PacManager** dans le gestionnaire de fichiers) pour l'installer directement — avec les octets réellement téléchargés et le temps écoulé affichés en direct, flatpak n'imprimant rien pendant le téléchargement d'un runtime
- 🔁 **Installations multiples** : une application installée en utilisateur *et* en système, ou depuis deux dépôts, reste **une seule ligne** ; la fiche de détail énumère les copies et **Supprimer** ouvre une case par installation pour choisir celles à retirer
- ⚙️ **Paramètres** : quand demander le mot de passe administrateur, **où** et à quelle taille maximale écrire le journal, activer ou désactiver le glisser-déposer Flatpak, la langue de l'interface, et la politique de mise à jour de PacManager (vérification automatique, blocage 1 h / 24 h / 7 jours / jusqu'à annulation)
## Architecture
+27 -1
View File
@@ -139,7 +139,33 @@ refusée tant que la première tourne. Voir [operations.md](operations.md).
| Une nouvelle opération | Une méthode dans `AppCore` qui construit une `Request` et appelle `startRequest()` ; un `InstallWorker::Op` ; sa ligne dans `startMessage()`, `successMessage()`, `failureMessage()`. |
| Une nouvelle liste | Une valeur dans `AppCore::ListMode`, un mode dans `ListWorker`, un slot dans `listFinished`. |
| Un nouveau provider | Un plugin externe (voir [plugins.md](plugins.md)) — jamais une modification du cœur. |
| Un nouveau réglage | `QSettings` (organisation `Freebuff`, application `PacManager`), comme `credentials/mode` ou `plugins/<id>/enabled`. |
| Un nouveau réglage | Une propriété dans `AppSettings` (`include/app-settings.h`), lue par la couche logique et exposée par l'écran Paramètres. Le mode d'identification reste dans `AppCore` (il fait partie de l'état des opérations privilégiées) ; `credentials/mode` et `plugins/<id>/enabled` sont les autres clés historiques. |
| Une nouvelle langue | Un `.ts` sous `translations/`, plus une entrée dans `AppSettings::knownLanguages()`. |
## Les préférences
`AppSettings` est le modèle des préférences : un singleton (comme `LogManager`),
persistant dans `QSettings` sous le préfixe `settings/`, qui **signale** chaque
changement. Personne ne stocke de copie.
C'est un singleton parce que trois moments sans rapport lisent les mêmes valeurs :
`LogManager` quand il ouvre le journal, `main()` avant qu'une fenêtre existe
(pour installer le traducteur), et l'écran Paramètres. Un objet partagé veut dire
qu'une valeur modifiée à l'écran est immédiatement celle que le reste de
l'application voit.
Deux règles que la suite vérifie :
- **une valeur illisible retombe sur un défaut sûr** — un dossier vide, une
langue inconnue ou une taille de journal aberrante ne peuvent pas casser
l'application (`sanitizeLogDirectory`, `sanitizeLanguage`, `sanitizeLogMaxBytes`) ;
- **un réglage n'émet que s'il change vraiment** — sinon les abonnés
(fenêtre, journal) travailleraient pour rien.
Les décisions de politique (durée d'un blocage, encodage ISO, formatage lisible)
sont des **fonctions statiques pures**, testables sans horloge ni fichier de
configuration : c'est pourquoi `AppSettings::isBlocked()` et
`AppSettings::blockDescription()` prennent le temps qu'elles examinent.
## Pourquoi cette séparation
+26 -1
View File
@@ -4,7 +4,7 @@
| Chemin | Contenu |
| --- | --- |
| `~/.config/Freebuff/PacManager.conf` | Tous les réglages (`QSettings`) : mode d'identification, mise à jour automatique, options de nettoyage, plugins activés, dernier contrôle de version. |
| `~/.config/Freebuff/PacManager.conf` | Tous les réglages (`QSettings`) : section `[settings]` (dossier et taille du journal, glisser-déposer, langue, vérification automatique, blocage des mises à jour), `credentials/mode`, plugins activés, dernier contrôle de version. |
| `~/.local/share/PacManager/plugins/` | Plugins utilisateur, y compris ceux installés par le magasin. |
| `~/.local/share/PacManager/` | Données de l'application (historique, cache de version). |
@@ -12,6 +12,22 @@ Supprimer le `.conf` remet l'application à ses valeurs par défaut sans rien
désinstaller. Pour repartir de zéro côté plugins, supprimer le dossier
`~/.local/share/PacManager/plugins/`.
## Réglages qui reviennent toujours
Deux réglages méritent une précision, parce qu'ils ne se comportent pas comme
les autres :
- le **dossier du journal** n'est pas figé : revenir au défaut *supprime* la
clé au lieu d'y écrire le chemin courant, pour qu'un changement de
`XDG_CONFIG_HOME` soit suivi ;
- le **blocage des mises à jour** garde son échéance. Un blocage de 24 h
expiré ne bloque plus tout seul ; « jusqu'à annulation » est le seul qui ne
finit jamais.
Si un réglage semble ignoré, c'est souvent qu'il n'a pas été écrit : vérifier le
`.conf` et l'onglet **Paramètres** de l'application, qui lit le modèle et non le
fichier.
## Logs
Les messages sont rangés par catégorie : `pacmgr.ui`, `pacmgr.op` (opérations),
@@ -112,6 +128,9 @@ depuis le réseau.
### Glisser un fichier Flatpak ne fait rien
- **Le dépôt est désactivé** : l'écran **Paramètres → Glisser-déposer** refuse
alors toute la fenêtre, curseur « interdit » compris. « Ouvrir avec
PacManager » fonctionne toujours, c'est un autre chemin d'entrée.
- **Ouvrir avec PacManager** n'apparaît pas dans le gestionnaire de fichiers :
l'entrée de bureau installée déclare les types MIME (`MimeType=…flatpak.ref`…) ;
si vous avez créé le `.desktop` à la main avant cette version, reprenez-le du
@@ -138,6 +157,12 @@ mémorisé ; pour forcer un nouveau contrôle, utilisez l'entrée **Vérifier le
mises à jour** du menu ou du menu de la barre d'état, ou supprimez la clé
correspondante dans `~/.config/Freebuff/PacManager.conf`.
Si le contrôle ne part pas du tout, ce n'est pas un oubli : l'écran
**Paramètres → Mises à jour de PacManager** permet de couper la vérification
automatique et de **bloquer** les mises à jour pendant 1 h, 24 h, 7 jours ou
jusqu'à annulation. Tant qu'un blocage court, l'action dit pourquoi dans la
barre de statut au lieu de ne rien faire (voir [interface.md](interface.md)).
### « Multiple installed refs match … » ou « Multiple branches available »
L'application est installée plusieurs fois — en utilisateur **et** en système, ou
+57 -2
View File
@@ -15,6 +15,7 @@ Chaque entrée correspond à un écran de `pages/` (ou à un mode d'un écran).
| 📋 Historique | `history-page` | Toutes les actions, filtrables, export CSV. |
| 📜 Logs | `logs-page` | `/var/log/pacman.log`, avec filtre instantané. |
| 🧩 Plugins | `plugins-page` | Plugins installés (activation, rechargement, installation de l'outil manquant) **et magasin** (voir [magasin-de-plugins.md](magasin-de-plugins.md)). |
| ⚙️ Paramètres | `settings-page` | Toutes les préférences (voir [Les paramètres](#les-paramètres)). |
Trois de ces entrées (Recherche, Installés, Mises à jour) partagent le même
écran : `BrowsePage` change de mode et donc de requête derrière, ce qui évite de
@@ -28,8 +29,8 @@ dupliquer la table et le panneau de détails.
paquets affichés, actions enregistrées) et la barre de progression de
l'opération en cours (voir [operations.md](operations.md)).
- **Menus** : Fichier (exports, quitter), Outils (naviguer, rafraîchir),
Paramètres (mode d'identification sudo), Aide (vérifier les mises à jour,
à propos).
Paramètres (ouverture de l'écran, mode d'identification sudo), Aide
(vérifier les mises à jour, à propos).
- **Tray** : icône de notification quand le bureau en fournit une, avec accès
direct aux mises à jour en attente.
@@ -74,6 +75,55 @@ La cible que le fournisseur a donnée à chaque copie (« user:…/master ») ne
jamais à l'écran : elle est conservée à côté du libellé et rendue telle quelle au
fournisseur, qui est le seul à savoir la lire.
## Les paramètres
L'écran **Paramètres** regroupe tout ce que l'utilisateur peut changer. Chaque
carte écrit dans le modèle que le reste de l'application lit déjà
(`AppSettings`, et le mode d'identification que `AppCore` possède déjà) : il n'y
a pas de copie de la valeur dans l'écran, et un changement s'applique **immédiatement**,
sans redémarrage.
| Carte | Réglage | Effet |
| --- | --- | --- |
| Mot de passe administrateur | À chaque opération / une fois au lancement | Passe par `AppCore::setCredentialMode()`. Demander maintenant, c'est le cadre qui possède la boîte de dialogue : l'écran émet `credentialModeRequested` et le cadre applique le mode (et met la case à cocher du menu en accord). |
| Journal | Dossier, taille maximale | `LogManager` écrit dans le dossier choisi. Changer de dossier **déplace** le journal existant, et la limite fait tourner le fichier (`operations.log.1` conserve la version précédente). Un dossier illisible retombe sur celui par défaut plutôt que de laisser l'application sans log. |
| Glisser-déposer | Accepter / refuser les fichiers Flatpak | Le dépôt est refusé par la fenêtre. « Ouvrir avec PacManager » continue de fonctionner : ce sont deux chemins d'entrée distincts. |
| Langue | Système / Français / English | Voir [La langue](#la-langue). |
| Mises à jour de PacManager | Vérification automatique, blocage | Voir [Bloquer les mises à jour](#bloquer-les-mises-à-jour). |
### La langue
L'application ne contient pas de catalogue : l'interface est écrite en français
avec `QStringLiteral`. Le réglage installe le catalogue Qt correspondant
(`translations/pacmanager_<code>.qm`), cherché dans cet ordre :
1. `<dossier du journal>/translations` — celui que l'utilisateur vient de choisir ;
2. `~/.local/share/PacManager/translations` ;
3. `translations/` à côté de l'exécutable (arbre de compilation).
Le changement est **immédiat** : `LanguageManager::apply()` retire l'ancien
traducteur, installe le nouveau et envoie `QEvent::LanguageChange` à tous les
widgets, ce qui fait que `MainWindow::changeEvent()` rappelle ses propres libellés
et que chaque écran réaffiche ses titres. Une langue sans catalogue est affichée dans
la liste mais **désactivée** (infobulle « traduction non installée ») : choisir
une langue qui ne ferait rien serait pire que de le dire.
CMake compile `translations/*.ts` en `.qm` **seulement si Qt Linguist est
installé** (`Qt6::LinguistTools`) : sans lui, l'application démarre simplement
non traduite. Fournir les catalogues est un travail de traduction à part.
### Bloquer les mises à jour
Deux réglages, tous deux limités à **PacManager lui-même** — les mises à jour des
paquets système ne sont jamais bloquées :
- **vérification automatique** : la recherche de version au lancement, déjà
limitée à une fois par jour ;
- **blocage** : 1 heure, 24 heures, 7 jours, ou jusqu'à annulation. Tant qu'il
est actif, `AppCore::checkForAppUpdate()` refuse et dit pourquoi dans la barre
de statut — y compris quand l'action vient du menu Aide. L'échéance est
conservée : un blocage expiré ne bloque plus.
## Raccourcis clavier
| Raccourci | Effet |
@@ -82,6 +132,7 @@ fournisseur, qui est le seul à savoir la lire.
| `Ctrl+R` / `F5` | Rafraîchir les bases de données (`pacman -Sy`). |
| `Ctrl+U` | Ouvrir la liste des mises à jour. |
| `Ctrl+E` | Exporter la liste affichée en CSV. |
| `Ctrl+,` | Ouvrir les Paramètres. |
| `Ctrl+Q` | Quitter. |
## Le thème
@@ -144,3 +195,7 @@ de style ne fait que fixer la couleur du texte.
| Un badge, une pastille, un compteur | `pages/ui-kit.cpp`. |
| Une couleur de statut dans une table | La page concernée (`QTableWidgetItem::setForeground`). |
| Une icône | `resources/icons/*.svg` (le trait suit la couleur du texte). |
L'écran Paramètres ajoute deux règles (`QScrollArea`, `QLabel#settingHint`,
`QCheckBox`) : elles sont dans `appStyleSheet()` comme le reste, pas dans le
fichier d'écran.
+5
View File
@@ -4,6 +4,11 @@ PacManager se met à jour lui-même : au lancement puis une fois par jour, il
interroge la dernière release du dépôt et propose de l'installer. Toute la
logique est dans `include/update-manager.h` / `src/update-manager.cpp`.
L'utilisateur peut couper ce contrôle, et le suspendre pour un temps, depuis
l'écran **Paramètres → Mises à jour de PacManager** (voir
[interface.md](interface.md)). Ces deux réglages ne concernent que PacManager :
les mises à jour des paquets du système ne sont jamais bloquées.
## La version
Le fichier `version` à la racine du dépôt est la **source unique de vérité** :
+5
View File
@@ -24,6 +24,7 @@ lance qu'une partie (`ctest -R progress`).
| `plugin-shop-test` | Format du catalogue (valide, invalide, entrées incomplètes) et comptabilité d'installation/désinstallation dans un dossier temporaire. | Qt Core + Network, aucun accès réseau. |
| `app-core-test` | La couche logique : portes d'entrée (opération en cours, mot de passe, providers), file d'attente des listes, historique, mode d'identification, refus d'un fichier qu'aucun fournisseur ne sait installer ; **porte du mot de passe** : chaque chemin privilégié (install, suppression, mise à jour, globale, rafraîchissement, caches, nettoyage groupé, suppression d'une ou de plusieurs installations, libération du verrou) s'arrête là, sans lancer de commande, et sa demande reste rejouable. | Qt Core seulement — **pas** QtWidgets. |
| `update-manager-test` | Comparaison de versions, choix de la méthode de mise à jour, et le script d'installation, exécuté pour de vrai contre un binaire en cours d'exécution. | Qt Core + Network. |
| `app-settings-test` | Les préférences : valeurs par défaut, valeurs refusées (dossier vide, langue inconnue, taille de journal aberrante), persistance après relecture, un réglage qui n'émet que s'il change, la politique de blocage des mises à jour (durée, expiration, indefini) et — pour de vrai — le **journal** : il atterrit dans le dossier choisi, accompagne un changement de dossier, tourne au plafond de taille et garde une version précédente. | Qt Core seulement. |
### Pourquoi `app-core-test` ne lie pas QtWidgets
@@ -51,6 +52,10 @@ est donc autant une vérification de comportement qu'un garde-fou d'architecture
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsDir.path());
```
`app-settings-test` va plus loin : il redirige aussi `HOME`, `XDG_CONFIG_HOME`
et `XDG_DATA_HOME`, parce que `LogManager` et le repli du journal les
consultent.
## Ajouter un test
1. Écrire `tests/mon-sujet.test.cpp`.
+12
View File
@@ -10,6 +10,7 @@
#include <utility>
#include <vector>
#include "app-settings.h"
#include "history-manager.h"
#include "package-manager.h"
#include "pacman-manager.h"
@@ -64,6 +65,11 @@ public:
HistoryManager* history() const { return m_history; }
UpdateManager* updateManager() const { return m_update; }
PluginShop* shop() const { return m_shop; }
// User preferences (journal, drag & drop, language, update policy). The
// core reads them to decide whether a version check may run; the Settings
// screen writes them. Shared process-wide, hence the accessor rather than
// an owned member.
AppSettings* settings() const { return &AppSettings::instance(); }
std::vector<IPackageManager*> availableProviders() const;
QStringList availableProviderNames() const;
bool hasAvailableProvider() const;
@@ -156,8 +162,14 @@ public:
void removeShopPlugin(const QString& id);
// ---- Application self-update ----
// Whether a version check may run right now: the daily check is not asked
// for, the automatic check is off, or the user put the app's own updates on
// hold (see AppSettings).
bool shouldCheckForAppUpdate() const;
void checkForAppUpdate();
// Why checkForAppUpdate() would refuse, for the status bar and the Settings
// screen. Empty when a check may run.
QString appUpdateCheckRefusal() const;
bool canSelfUpdate() const;
UpdateManager::UpdateMethod updateMethod() const;
QString updateMethodDescription() const;
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <QDateTime>
#include <QObject>
#include <QString>
#include <QStringList>
// Every preference the Settings screen owns, gathered in one place and kept out
// of the widgets: where the journal is written and how big it may grow, the
// drag & drop switch, the language, and the application-update policy (automatic
// check, and the block the user can put on it).
//
// The credential mode deliberately stays in AppCore: it belongs to the
// privileged-operation state, not to this list.
//
// It is a singleton (like LogManager) because three unrelated moments need to
// read it — LogManager when it opens the journal, main() before any window
// exists (to install the translator), and the Settings screen — and a single
// object means a value changed in the screen is immediately what the rest of the
// app reads, with no second copy to keep in sync.
//
// Values live in QSettings (organisation "Freebuff", application "PacManager"),
// under the "settings/" prefix. Every setter signals, so LogManager, MainWindow
// and LanguageManager react instead of the app having to be restarted.
class AppSettings : public QObject {
Q_OBJECT
public:
// Process-wide settings, created on first use (thread-safe).
static AppSettings& instance();
explicit AppSettings(QObject* parent = nullptr);
// ---- Journal: where and how big ----
// Directory holding operations.log. Never empty: an unusable value falls
// back to defaultLogDirectory() rather than leaving the app without a
// journal.
QString logDirectory() const;
void setLogDirectory(const QString& directory);
// Where the journal lived before any preference was set: the user's own
// config tree, so it survives a sandbox rebuild (and a Flatpak build, where
// it resolves inside the sandbox home).
static QString defaultLogDirectory();
// Expands "~", cleans the path and rejects what is left empty, so a
// half-typed directory never breaks logging.
static QString sanitizeLogDirectory(const QString& directory);
// Size cap of the journal, 0 meaning unlimited. Writing past the cap rotates
// the file (LogManager keeps one previous journal).
qint64 logMaxBytes() const;
void setLogMaxBytes(qint64 bytes);
// A cap that would rotate on every line is a cap nobody wants, so anything
// positive below the floor is raised to it; a negative value means no cap.
static qint64 sanitizeLogMaxBytes(qint64 bytes);
// ---- Drag & drop of Flatpak files ----
bool dragDropEnabled() const;
void setDragDropEnabled(bool enabled);
// ---- Language ----
// "system" to follow the desktop, or one of knownLanguages(). Unknown codes
// fall back to "fr", the language the interface is written in.
QString language() const;
void setLanguage(const QString& code);
static QStringList knownLanguages();
static QString sanitizeLanguage(const QString& code);
// ---- Application updates (PacManager itself, not the system packages) ----
// Whether the version is checked on its own at launch, once a day.
bool autoUpdateCheckEnabled() const;
void setAutoUpdateCheckEnabled(bool enabled);
// Blocks every version check for `hours`; 0 blocks until the user unlocks
// it. Only the app's own update is affected: installing system package
// updates is never blocked.
void blockUpdatesFor(int hours);
void unblockUpdates();
bool updatesBlocked() const {
return isBlocked(QDateTime::currentDateTime(), m_blockIndefinite, m_blockUntil);
}
bool updatesBlockedIndefinitely() const { return m_blockIndefinite; }
// Invalid when the block has no scheduled end (not blocked, or blocked
// indefinitely).
QDateTime updateBlockedUntil() const { return m_blockUntil; }
// The two decisions above, as pure functions so the policy can be tested
// without a clock, a settings file or a running app.
static QDateTime blockTarget(const QDateTime& now, int hours);
static bool isBlocked(const QDateTime& now, bool indefinite, const QDateTime& until);
// What the block currently means, for the screen and the status bar. Empty
// when no block is in force.
static QString blockDescription(bool indefinite, const QDateTime& until,
const QDateTime& now);
signals:
void logDirectoryChanged(const QString& directory);
void logMaxBytesChanged(qint64 bytes);
void dragDropEnabledChanged(bool enabled);
void languageChanged(const QString& code);
void autoUpdateCheckEnabledChanged(bool enabled);
void updateBlockChanged();
private:
// Reads the three block values back in one go, so the in-memory state can
// never disagree with what was persisted.
void loadUpdateBlock();
void saveUpdateBlock();
bool m_blockIndefinite = false;
QDateTime m_blockUntil;
};
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <QString>
#include <QStringList>
class QTranslator;
// Installs the translation matching the language preference, and swaps it when
// the user picks another one on the Settings screen.
//
// The translation files are ordinary Qt .qm catalogues, looked up as
// "translations/pacmanager_<code>.qm" in, in order:
//
// 1. <AppSettings log directory>/translations (user's own, survives an update);
// 2. <AppDataLocation>/translations (next to the config);
// 3. <directory of the executable>/translations (running from a build tree).
//
// A code with no .qm on any of those paths simply stays untranslated: the
// interface is written in French, which is what apply() falls back to. That is
// deliberate — the setting is the plumbing, and shipping catalogues is a
// translation pass of its own.
class LanguageManager {
public:
// Resolves "system" to the desktop's language and falls back to the
// interface's own language when the desktop asks for something no catalogue
// covers.
static QString resolve(const QString& code);
// True when a catalogue is actually installed for `code`, so the Settings
// screen can say so instead of pretending a choice will change something.
static bool isTranslationAvailable(const QString& code);
// Where a catalogue is looked up, for the screen to display.
static QString searchPathHint();
// Installs the catalogue for `code` (see resolve) and asks every widget to
// retranslate itself. Returns true when a catalogue was installed.
static bool apply(const QString& code);
// Catalogue currently installed, empty when the interface is untranslated.
static QString activeCode();
// Directories actually searched, in order, existing ones only.
static QStringList searchPaths();
};
+18 -2
View File
@@ -34,8 +34,11 @@
// across the code base feed it without extra plumbing.
//
// The file lives in the user's own data tree (XDG_CONFIG_HOME / home) so it is
// never lost when a sandbox is rebuilt. All methods are safe to call from any
// thread.
// never lost when a sandbox is rebuilt, and both that directory and a size cap
// are the user's to choose on the Settings screen: changing either takes effect
// immediately, the existing journal being moved along (see AppSettings).
//
// All methods are safe to call from any thread.
class LogManager : public QObject {
Q_OBJECT
public:
@@ -70,6 +73,14 @@ public:
// Path of the journal as written on disk (useful for debugging).
QString filePath() const;
// Size the journal currently takes on disk, 0 when there is none yet. The
// Settings screen shows it next to the cap the user picked.
qint64 currentSizeBytes() const;
// Path of the rotated journal, kept so the user can still read what came
// before the last rotation.
static QString backupFilePath();
// Routes every Qt log message into the journal. Call once, after the
// QApplication exists. Safe to call more than once.
static void installQtMessageHandler();
@@ -83,6 +94,11 @@ private:
// lock; this method takes it.
void write(const QString& text);
// Applies the current AppSettings: moves the journal to the configured
// directory and adopts the size cap. Called once from the constructor and
// again whenever a setting changes.
void applySettings();
QString m_filePath;
FILE* m_file = nullptr;
mutable QMutex m_mutex;
+24
View File
@@ -33,6 +33,7 @@ class HistoryPage;
class LogsPage;
class Page;
class PluginsPage;
class SettingsPage;
// The window is only a frame: it owns the sidebar, the header, the status bar,
// the menu, the tray and every dialog, and it stacks one screen per file from
@@ -61,6 +62,8 @@ protected:
void dragEnterEvent(QDragEnterEvent* event) override;
void dragMoveEvent(QDragMoveEvent* event) override;
void dropEvent(QDropEvent* event) override;
// Language switch: Qt asks every widget to retranslate itself.
void changeEvent(QEvent* event) override;
private slots:
void onNavChanged(int id);
@@ -105,6 +108,7 @@ private:
NavHistory,
NavLogs,
NavPlugins,
NavSettings,
};
void setupUI();
@@ -124,6 +128,9 @@ private:
// Mirrors the pending update count on the sidebar entry, so the page that
// needs attention is visible from wherever the user is.
void setUpdatesBadge(int count);
// Last count given to the badge, kept so a language switch can rebuild the
// entry's label without having to re-query the core.
int m_updatesBadgeCount = 0;
void notifyUpdatesAvailable(int count);
// Runs a request and, when the core refused it, walks the user through what
// it needs before replaying it.
@@ -138,6 +145,18 @@ private:
// dialog, anything else is shown as-is.
void showActionError(const QString& title, const QString& error, bool locked);
void applyCredentialMode(AppCore::CredentialMode mode);
// Applies the mode and re-checks the matching menu entry, so the menu bar
// and the Settings screen can never disagree about the current mode.
void onCredentialModeRequested(bool atLaunch);
// Re-applies the language and puts the text back in the widgets, so
// switching language on the Settings screen takes effect at once.
void onLanguageChanged(const QString& code);
// Keeps the window's drop target in step with the preference.
void onDragDropEnabledChanged(bool enabled);
// Puts every string the frame owns back into its widget. Called on the
// LanguageChange event, so it is what makes the language setting visible
// without restarting.
void retranslateUI();
// Records that the running operation just said something: the step is kept
// for the heartbeat and the "nothing printed" clock restarts.
void noteOperationOutput(const QString& step);
@@ -176,6 +195,11 @@ private:
HistoryPage* m_history = nullptr;
LogsPage* m_logs = nullptr;
PluginsPage* m_plugins = nullptr;
SettingsPage* m_settings = nullptr;
// Sidebar entries, by nav id, so the language can be re-applied to them
// (and the updates badge found) without rebuilding the sidebar.
QHash<int, QPushButton*> m_navButtons;
// Progress of the running operation, anchored in the status bar: the bar
// itself (indeterminate until a provider reports a real percentage) and the
+5
View File
@@ -37,6 +37,11 @@ signals:
// Something the user should read in the status bar, with no operation
// behind it ("Aucune liste à exporter.", ...).
void message(const QString& text);
// The screen picked another sudo credential mode. The frame answers it
// rather than the screen writing the preference itself, because prompting
// for the password is the frame's job and the menu bar's checkmarks have to
// follow along.
void credentialModeRequested(bool atLaunch);
protected:
AppCore* core() const { return m_core; }
+517
View File
@@ -0,0 +1,517 @@
#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();
m_language->addItem(tr("Langue du système"), QStringLiteral("system"));
for (const QString& code : AppSettings::knownLanguages()) {
m_language->addItem(code == QLatin1String("fr") ? tr("Français") : tr("English"),
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 .qm sont cherchés dans un dossier "
"« translations » à côté de la configuration ou de l'exécutable.")
: tr("Catalogues .qm : %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);
}
+91
View File
@@ -0,0 +1,91 @@
#pragma once
#include <QString>
#include "page.h"
class QCheckBox;
class QComboBox;
class QFrame;
class QLabel;
class QLineEdit;
class QPushButton;
class QVBoxLayout;
// The Settings screen: one card per family of preferences, each one writing
// straight to the model the rest of the app reads (AppSettings, and the core's
// credential mode), so nothing here holds a private copy of a value.
//
// Four families are the user's alone — the journal (where it is written, how big
// it may grow), drag & drop of Flatpak files, the language, and the app's own
// update policy. The fifth, the sudo credential mode, is not new: the screen
// drives the same AppCore::setCredentialMode() the Paramètres menu already did,
// and the two stay in step.
class SettingsPage : public Page {
Q_OBJECT
public:
explicit SettingsPage(AppCore* core, QWidget* parent = nullptr);
QString navTitle() const override;
QString navSubtitle() const override;
// Re-reads every control from the model, so a value changed elsewhere (the
// menu bar, a restored settings file) is reflected when the screen opens.
void refresh() override;
private:
// ---- Credentials ----
QFrame* buildCredentialsCard();
// ---- Journal ----
QFrame* buildLogCard();
void loadLogCard();
void chooseLogDirectory();
void openLogDirectory();
void resetLogDirectory();
void updateLogSizeLabel();
// ---- Drag & drop ----
QFrame* buildDragDropCard();
// ---- Language ----
QFrame* buildLanguageCard();
void loadLanguageCard();
// ---- Application updates ----
QFrame* buildUpdateCard();
void loadUpdateCard();
void applyUpdateBlock();
void clearUpdateBlock();
void updateUpdateHint();
// One titled card, the building block every section below is made of. The
// card's own vertical layout is handed back so a section can fill it
// without going through QWidget::layout(), which hides the typed layout.
QFrame* card(const QString& title, QVBoxLayout** layoutOut) const;
AppSettings* preferences() const;
// Credentials
QComboBox* m_credentialMode = nullptr;
QLabel* m_credentialHint = nullptr;
// Journal
QLineEdit* m_logDirectory = nullptr;
QComboBox* m_logMaxSize = nullptr;
QLabel* m_logSizeLabel = nullptr;
QPushButton* m_logResetButton = nullptr;
// Drag & drop
QCheckBox* m_dragDrop = nullptr;
// Language
QComboBox* m_language = nullptr;
QLabel* m_languageHint = nullptr;
// Application updates
QCheckBox* m_autoUpdateCheck = nullptr;
QComboBox* m_updateBlockDelay = nullptr;
QPushButton* m_updateBlockButton = nullptr;
QLabel* m_updateHint = nullptr;
};
+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#0f172a" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round" width="24" height="24">
<polyline points="20 6 9 17 4 12"/>
</svg>

After

Width:  |  Height:  |  Size: 224 B

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#e2e8f0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="24" height="24">
<circle cx="12" cy="12" r="3"/>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9v.09a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
</svg>

After

Width:  |  Height:  |  Size: 849 B

+2
View File
@@ -11,10 +11,12 @@
<file alias="refresh.svg">icons/refresh.svg</file>
<file alias="tools.svg">icons/tools.svg</file>
<file alias="check.svg">icons/check.svg</file>
<file alias="check-dark.svg">icons/check-dark.svg</file>
<file alias="close.svg">icons/close.svg</file>
<file alias="filter.svg">icons/filter.svg</file>
<file alias="alert.svg">icons/alert.svg</file>
<file alias="plugin.svg">icons/plugin.svg</file>
<file alias="broom.svg">icons/broom.svg</file>
<file alias="settings.svg">icons/settings.svg</file>
</qresource>
</RCC>
+27
View File
@@ -1,5 +1,6 @@
#include "app-core.h"
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
#include <QTimer>
@@ -1194,10 +1195,36 @@ QString AppCore::packageDetails(const PackageInfo& pkg) {
// ---------------------------------------------------------------------------
bool AppCore::shouldCheckForAppUpdate() const {
if (!appUpdateCheckRefusal().isEmpty()) return false;
return m_update->shouldCheck();
}
QString AppCore::appUpdateCheckRefusal() const {
AppSettings& preferences = AppSettings::instance();
// The user parked the app's own updates: no automatic check, and the manual
// one says why instead of quietly doing nothing.
if (preferences.updatesBlocked()) {
return AppSettings::blockDescription(
preferences.updatesBlockedIndefinitely(), preferences.updateBlockedUntil(),
QDateTime::currentDateTime());
}
if (!preferences.autoUpdateCheckEnabled()) {
return QStringLiteral(
"La vérification automatique des mises à jour est désactivée dans "
"les paramètres.");
}
return QString();
}
void AppCore::checkForAppUpdate() {
const QString refusal = appUpdateCheckRefusal();
if (!refusal.isEmpty()) {
LogManager::instance().logEvent(QStringLiteral("maj-app"), refusal);
emit statusMessage(refusal);
return;
}
LogManager::instance().logEvent(QStringLiteral("maj-app"),
QStringLiteral("vérification de version"));
emit statusMessage(QStringLiteral("Vérification des mises à jour..."));
+242
View File
@@ -0,0 +1,242 @@
#include "app-settings.h"
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QSettings>
#include <QStandardPaths>
namespace {
// Below this a cap would rotate the journal on practically every line, which
// makes the "previous journal" LogManager keeps useless.
constexpr qint64 kMinLogMaxBytes = 64 * 1024;
QString key(const char* name) {
return QStringLiteral("settings/") + QString::fromLatin1(name);
}
} // namespace
AppSettings& AppSettings::instance() {
// Function-local static: created once, thread-safe since C++11.
static AppSettings settings;
return settings;
}
AppSettings::AppSettings(QObject* parent) : QObject(parent) {
loadUpdateBlock();
}
// ---------------------------------------------------------------------------
// Journal
// ---------------------------------------------------------------------------
QString AppSettings::defaultLogDirectory() {
const QString dir = QStandardPaths::writableLocation(
QStandardPaths::AppConfigLocation);
if (!dir.isEmpty()) {
QDir(dir).mkpath(".");
return dir;
}
return QDir::homePath() + QStringLiteral("/.config/PacManager");
}
QString AppSettings::sanitizeLogDirectory(const QString& directory) {
QString path = directory.trimmed();
if (path.isEmpty()) return defaultLogDirectory();
// The dialog hands back a native path, but a hand-edited setting may still
// start with "~" — which no other API in the app would expand.
if (path == QLatin1String("~")) {
path = QDir::homePath();
} else if (path.startsWith(QLatin1String("~/"))) {
path = QDir::homePath() + path.mid(1);
}
const QString clean = QDir::cleanPath(QFileInfo(path).absoluteFilePath());
return clean.isEmpty() ? defaultLogDirectory() : clean;
}
QString AppSettings::logDirectory() const {
QSettings settings;
return sanitizeLogDirectory(settings.value(key("logDirectory")).toString());
}
void AppSettings::setLogDirectory(const QString& directory) {
const QString wanted = sanitizeLogDirectory(directory);
// Compared with what is in force *before* writing: comparing with the
// stored value afterwards would always match, and every setter would
// announce a change that did not happen.
if (wanted == logDirectory()) return;
QSettings settings;
// Back to the default: remove the key rather than pinning the current
// default path, which would survive a change of XDG_CONFIG_HOME.
if (wanted == defaultLogDirectory()) {
settings.remove(key("logDirectory"));
} else {
settings.setValue(key("logDirectory"), wanted);
}
emit logDirectoryChanged(wanted);
}
qint64 AppSettings::sanitizeLogMaxBytes(qint64 bytes) {
if (bytes <= 0) return 0;
if (bytes < kMinLogMaxBytes) return kMinLogMaxBytes;
return bytes;
}
qint64 AppSettings::logMaxBytes() const {
QSettings settings;
return sanitizeLogMaxBytes(settings.value(key("logMaxBytes"), 0).toLongLong());
}
void AppSettings::setLogMaxBytes(qint64 bytes) {
const qint64 wanted = sanitizeLogMaxBytes(bytes);
if (wanted == logMaxBytes()) return;
QSettings settings;
if (wanted == 0) settings.remove(key("logMaxBytes"));
else settings.setValue(key("logMaxBytes"), wanted);
emit logMaxBytesChanged(wanted);
}
// ---------------------------------------------------------------------------
// Drag & drop
// ---------------------------------------------------------------------------
bool AppSettings::dragDropEnabled() const {
QSettings settings;
// On by default: dropping a .flatpakref on the window is the quickest way
// to install it, so turning it off has to be a deliberate act.
return settings.value(key("dragDrop"), true).toBool();
}
void AppSettings::setDragDropEnabled(bool enabled) {
if (enabled == dragDropEnabled()) return;
QSettings settings;
settings.setValue(key("dragDrop"), enabled);
emit dragDropEnabledChanged(enabled);
}
// ---------------------------------------------------------------------------
// Language
// ---------------------------------------------------------------------------
QStringList AppSettings::knownLanguages() {
return {QStringLiteral("fr"), QStringLiteral("en")};
}
QString AppSettings::sanitizeLanguage(const QString& code) {
const QString wanted = code.trimmed().toLower();
// Nothing stored means "follow the desktop", which is what a fresh install
// gets; an unknown code is not the desktop, it is a mistake.
if (wanted.isEmpty() || wanted == QLatin1String("system")) {
return QStringLiteral("system");
}
return knownLanguages().contains(wanted) ? wanted : QStringLiteral("fr");
}
QString AppSettings::language() const {
QSettings settings;
return sanitizeLanguage(settings.value(key("language")).toString());
}
void AppSettings::setLanguage(const QString& code) {
const QString wanted = sanitizeLanguage(code);
if (wanted == language()) return;
QSettings settings;
settings.setValue(key("language"), wanted);
emit languageChanged(wanted);
}
// ---------------------------------------------------------------------------
// Application updates
// ---------------------------------------------------------------------------
bool AppSettings::autoUpdateCheckEnabled() const {
QSettings settings;
return settings.value(key("autoUpdateCheck"), true).toBool();
}
void AppSettings::setAutoUpdateCheckEnabled(bool enabled) {
if (enabled == autoUpdateCheckEnabled()) return;
QSettings settings;
settings.setValue(key("autoUpdateCheck"), enabled);
emit autoUpdateCheckEnabledChanged(enabled);
}
QDateTime AppSettings::blockTarget(const QDateTime& now, int hours) {
if (hours <= 0) return QDateTime();
// Second precision, which is all a snooze needs and is exactly what
// survives the round trip through the settings file: a deadline rebuilt
// from it therefore compares equal to the one that was written.
const QDateTime end = now.addSecs(static_cast<qint64>(hours) * 3600);
return QDateTime::fromSecsSinceEpoch(end.toSecsSinceEpoch());
}
bool AppSettings::isBlocked(const QDateTime& now, bool indefinite, const QDateTime& until) {
if (indefinite) return true;
return until.isValid() && now < until;
}
void AppSettings::loadUpdateBlock() {
QSettings settings;
m_blockIndefinite = settings.value(key("updateBlockIndefinite"), false).toBool();
m_blockUntil = QDateTime::fromString(
settings.value(key("updateBlockUntil")).toString(), Qt::ISODate);
// A stored date that no longer parses is dropped rather than believed: an
// unreadable "until" must never keep the user from checking again.
if (m_blockUntil.isNull()) m_blockUntil = QDateTime();
}
void AppSettings::saveUpdateBlock() {
QSettings settings;
settings.setValue(key("updateBlockIndefinite"), m_blockIndefinite);
if (m_blockUntil.isValid()) {
settings.setValue(key("updateBlockUntil"), m_blockUntil.toString(Qt::ISODate));
} else {
settings.remove(key("updateBlockUntil"));
}
}
void AppSettings::blockUpdatesFor(int hours) {
m_blockIndefinite = hours <= 0;
m_blockUntil = blockTarget(QDateTime::currentDateTime(), hours);
saveUpdateBlock();
emit updateBlockChanged();
}
void AppSettings::unblockUpdates() {
m_blockIndefinite = false;
m_blockUntil = QDateTime();
saveUpdateBlock();
emit updateBlockChanged();
}
QString AppSettings::blockDescription(bool indefinite, const QDateTime& until,
const QDateTime& now) {
if (indefinite) {
return QCoreApplication::translate(
"AppSettings", "Mises à jour bloquées jusqu'à annulation.");
}
if (!until.isValid() || now >= until) return QString();
const qint64 seconds = until.secsTo(now);
const qint64 hours = seconds / 3600;
if (hours >= 24) {
const qint64 days = hours / 24;
return QCoreApplication::translate("AppSettings", "Mises à jour bloisées encore %1 jour(s).")
.arg(days);
}
if (hours >= 1) {
return QCoreApplication::translate("AppSettings", "Mises à jour bloisées encore %1 heure(s).")
.arg(hours);
}
return QCoreApplication::translate("AppSettings", "Mises à jour bloisées encore %1 minute(s).")
.arg(qMax<qint64>(1, seconds / 60));
}
+111
View File
@@ -0,0 +1,111 @@
#include "language-manager.h"
#include "app-settings.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDir>
#include <QEvent>
#include <QFile>
#include <QLocale>
#include <QStandardPaths>
#include <QTranslator>
#include <QWidget>
namespace {
// Kept alive for the whole process: a QTranslator that is destroyed takes the
// installed translation with it.
QTranslator* g_translator = nullptr;
QString catalogueFileName(const QString& code) {
return QStringLiteral("translations/pacmanager_%1.qm").arg(code);
}
} // namespace
QStringList LanguageManager::searchPaths() {
QStringList paths;
// Next to the settings the user just chose: where a catalogue installed by
// hand (or by a future in-app translation pack) belongs.
paths << AppSettings::instance().logDirectory() + QStringLiteral("/translations");
const QString data = QStandardPaths::writableLocation(
QStandardPaths::AppDataLocation);
if (!data.isEmpty()) paths << data + QStringLiteral("/translations");
// Running from a build tree, the catalogues sit beside the binary.
paths << QCoreApplication::applicationDirPath() + QStringLiteral("/translations");
QStringList existing;
for (const QString& path : paths) {
if (QDir(path).exists()) existing << path;
}
return existing;
}
QString LanguageManager::resolve(const QString& code) {
const QString wanted = AppSettings::sanitizeLanguage(code);
if (wanted != QLatin1String("system")) return wanted;
// "system" follows the desktop, but only into a language the app knows: a
// desktop set to Esperanto should leave the interface in its own language
// rather than install nothing at all.
const QString locale = QLocale::system().name().left(2);
if (AppSettings::knownLanguages().contains(locale)) return locale;
return QStringLiteral("fr");
}
bool LanguageManager::isTranslationAvailable(const QString& code) {
const QString resolved = resolve(code);
const QString fileName = catalogueFileName(resolved);
for (const QString& path : searchPaths()) {
if (QFile::exists(path + QLatin1Char('/') + fileName)) return true;
}
return false;
}
QString LanguageManager::searchPathHint() {
return searchPaths().isEmpty() ? QString() : searchPaths().first();
}
QString LanguageManager::activeCode() {
return g_translator ? g_translator->language() : QString();
}
bool LanguageManager::apply(const QString& code) {
const QString resolved = resolve(code);
const QString fileName = catalogueFileName(resolved);
// The previous catalogue goes first, so a language the user just left does
// not keep translating part of the interface.
if (g_translator) {
QCoreApplication::removeTranslator(g_translator);
delete g_translator;
g_translator = nullptr;
}
bool installed = false;
for (const QString& path : searchPaths()) {
if (!g_translator) g_translator = new QTranslator();
if (g_translator->load(fileName, path)) {
QCoreApplication::installTranslator(g_translator);
installed = true;
break;
}
delete g_translator;
g_translator = nullptr;
}
// No catalogue (the common case today): the widgets still get the event, so
// switching back to an untranslated language restores the original wording
// instead of leaving the previous translation in place.
const QWidgetList widgets = QApplication::allWidgets();
for (QWidget* widget : widgets) {
QEvent event(QEvent::LanguageChange);
QCoreApplication::sendEvent(widget, &event);
}
return installed;
}
+77 -14
View File
@@ -1,8 +1,11 @@
#include "log-manager.h"
#include "app-settings.h"
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QLoggingCategory>
#include <QStandardPaths>
#include <QStringBuilder>
@@ -14,24 +17,24 @@
namespace {
// Where the plain text history of what the app did lives on any desktop
// session, inside the user's own data tree (so a Flatpak-sandboxed build still
// finds it in ~/.local/share).
QString logDirectory() {
const QString dir = QStandardPaths::writableLocation(
QStandardPaths::AppConfigLocation);
if (!dir.isEmpty()) {
QDir(dir).mkpath(".");
return dir;
}
return QDir::homePath() + QStringLiteral("/.config/PacManager");
}
// The journal's file name, and the one its rotated copy gets.
constexpr auto kLogFileName = "operations.log";
constexpr auto kBackupFileName = "operations.log.1";
QString currentTimestamp() {
return QDateTime::currentDateTime().toString(
QStringLiteral("yyyy-MM-dd hh:mm:ss"));
}
// Renames `path` onto `target`, replacing whatever was there. Journal rotation
// and the move to a new directory both want that, and Qt refuses to overwrite
// otherwise.
bool replaceFile(const QString& path, const QString& target) {
if (!QFile::exists(path)) return true;
if (QFile::exists(target) && !QFile::remove(target)) return false;
return QFile::rename(path, target);
}
} // namespace
LogManager& LogManager::instance() {
@@ -41,16 +44,77 @@ LogManager& LogManager::instance() {
}
LogManager::LogManager(QObject* parent) : QObject(parent) {
m_filePath = logDirectory() + QStringLiteral("/") + QStringLiteral("operations.log");
// Subscribing before the first write means the journal is opened where the
// user asked, not where it was asked to open.
AppSettings& settings = AppSettings::instance();
connect(&settings, &AppSettings::logDirectoryChanged, this,
[this](const QString&) { applySettings(); });
applySettings();
}
QString LogManager::filePath() const {
QMutexLocker lock(&m_mutex);
return m_filePath;
}
QString LogManager::backupFilePath() {
return AppSettings::instance().logDirectory() + QLatin1Char('/') +
QLatin1String(kBackupFileName);
}
qint64 LogManager::currentSizeBytes() const {
QMutexLocker lock(&m_mutex);
return QFileInfo(m_filePath).size();
}
// Puts the journal where AppSettings says, carrying the existing file along so
// switching directory does not silently start an empty log.
void LogManager::applySettings() {
const QString directory = AppSettings::instance().logDirectory();
const QString wanted = directory + QLatin1Char('/') + QLatin1String(kLogFileName);
// A directory that cannot be created is reported by the absence of the
// journal on the Settings screen, not by throwing here.
if (!QDir().mkpath(directory)) return;
QString previous;
{
QMutexLocker lock(&m_mutex);
if (wanted == m_filePath) return;
previous = m_filePath;
if (m_file) {
std::fclose(m_file);
m_file = nullptr;
}
m_filePath = wanted;
}
// Carried over only when the target has no journal of its own: a directory
// that already has one is not overwritten. Done without the lock, which
// write() takes for itself.
if (!previous.isEmpty()) {
replaceFile(previous, wanted);
}
write(QStringLiteral("[%1] [config] journal → %2\n")
.arg(currentTimestamp(), wanted));
}
void LogManager::write(const QString& text) {
QMutexLocker lock(&m_mutex);
const QByteArray bytes = text.toUtf8();
// Rotation before the write, so the cap really is a ceiling. One previous
// journal is kept; the one before it is dropped.
const qint64 cap = AppSettings::instance().logMaxBytes();
if (cap > 0 && QFileInfo(m_filePath).size() + bytes.size() > cap) {
if (m_file) {
std::fclose(m_file);
m_file = nullptr;
}
replaceFile(m_filePath, m_filePath + QLatin1String(".1"));
}
// Append mode, opened lazily and kept open: a long session keeps growing and
// the file is never truncated while the app runs.
if (!m_file) {
@@ -58,7 +122,6 @@ void LogManager::write(const QString& text) {
if (!m_file) return;
}
const QByteArray bytes = text.toUtf8();
std::fputs(bytes.constData(), m_file);
// Flushed line by line so the journal survives a crash: the last thing the
// app did is exactly what the user wants to read after one.
+140 -4
View File
@@ -37,9 +37,11 @@
#include "cleanup-page.h"
#include "dashboard-page.h"
#include "history-page.h"
#include "language-manager.h"
#include "logs-page.h"
#include "page.h"
#include "plugins-page.h"
#include "settings-page.h"
// How long a wait reads best in the status bar: "45 s", "2 min 05", "1 h 03".
static QString formatElapsed(qint64 ms) {
@@ -236,6 +238,23 @@ static QString appStyleSheet() {
" color: #e2e8f0;"
"}"
"QComboBox:hover { border-color: #7dd3fc; }"
// ---- Settings screen ----
// The cards scroll as a whole: the area itself must not paint, or the
// page gradient would be cut off at its edges.
"QScrollArea { background: transparent; border: none; }"
"QScrollArea > QWidget > QWidget { background: transparent; }"
// Explanatory text under each control, in the site's secondary colour.
"QLabel#settingHint { font-size: 12px; color: #94a3b8; }"
"QCheckBox { font-size: 13px; color: #e2e8f0; spacing: 8px; }"
"QCheckBox::indicator {"
" width: 18px; height: 18px;"
" border: 1px solid #475569; border-radius: 5px; background: #1e293b;"
"}"
"QCheckBox::indicator:hover { border-color: #7dd3fc; }"
"QCheckBox::indicator:checked {"
" background: #38bdf8; border-color: #38bdf8;"
" image: url(:/icons/check-dark.svg);"
"}"
"QComboBox::drop-down { border: none; width: 26px; }"
"QComboBox QAbstractItemView {"
" background: #273449;"
@@ -353,6 +372,15 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
connect(m_core, &AppCore::selfUpdateFinished, this,
&MainWindow::onCoreSelfUpdateFinished);
// The preferences the window reacts to rather than merely reads: dropping a
// file and switching language are both things the user does on the Settings
// screen and expects to see take effect at once.
AppSettings& preferences = AppSettings::instance();
connect(&preferences, &AppSettings::dragDropEnabledChanged, this,
&MainWindow::onDragDropEnabledChanged);
connect(&preferences, &AppSettings::languageChanged, this,
&MainWindow::onLanguageChanged);
setupUI();
setupMenuBar();
setupTray();
@@ -435,8 +463,9 @@ void MainWindow::setupUI() {
statusBar()->showMessage("Prêt");
// Flatpak files can be dropped anywhere on the window (see dragEnterEvent).
setAcceptDrops(true);
// Flatpak files can be dropped anywhere on the window (see dragEnterEvent),
// unless the user turned that off on the Settings screen.
setAcceptDrops(AppSettings::instance().dragDropEnabled());
// Progress of the running operation, anchored at the bottom of the window
// so it takes no space on the screens. It appears while install/update/
@@ -515,6 +544,7 @@ void MainWindow::setupSidebar() {
btn->setIcon(loadIcon(iconName));
btn->setIconSize(QSize(17, 17));
m_navGroup->addButton(btn, id);
m_navButtons.insert(id, btn);
layout->addWidget(btn);
return btn;
};
@@ -532,6 +562,8 @@ void MainWindow::setupSidebar() {
addNavButton(NavHistory, "history", "Historique", "Historique des actions");
addNavButton(NavLogs, "logs", "Logs", "Logs pacman");
addNavButton(NavPlugins, "plugin", "Plugins", "Gestionnaires de paquets et extensions");
addNavButton(NavSettings, "settings", "Paramètres",
"Journal, glisser-déposer, langue et mises à jour");
connect(m_navGroup, &QButtonGroup::idClicked, this, &MainWindow::onNavChanged);
m_navGroup->button(NavDashboard)->setChecked(true);
@@ -621,6 +653,11 @@ void MainWindow::setupPages() {
m_plugins = new PluginsPage(m_core);
registerPage("plugins", NavPlugins, m_plugins);
m_settings = new SettingsPage(m_core);
registerPage("settings", NavSettings, m_settings);
connect(m_settings, &Page::credentialModeRequested, this,
&MainWindow::onCredentialModeRequested);
}
void MainWindow::registerPage(const QString& id, int navId, Page* page) {
@@ -660,6 +697,7 @@ void MainWindow::updateStatusBar() {
void MainWindow::setUpdatesBadge(int count) {
if (!m_navUpdatesButton) return;
m_updatesBadgeCount = count;
m_navUpdatesButton->setText(count > 0
? QString("Mises à jour · %1").arg(count)
@@ -716,6 +754,7 @@ void MainWindow::setupMenuBar() {
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->addAction("Paramètres", this, [this, goTo] { goTo(NavSettings); });
toolsMenu->addSeparator();
toolsMenu->addAction("Prévisualiser les mises à jour", this, [this, goTo] {
goTo(NavUpdates);
@@ -725,6 +764,12 @@ void MainWindow::setupMenuBar() {
QMenu* settingsMenu = menuBar->addMenu("Paramètres");
// The dedicated screen holds every preference; the two entries below are
// shortcuts to the one that would otherwise be a menu of its own.
settingsMenu->addAction("Ouvrir les paramètres", this,
[this, goTo] { goTo(NavSettings); });
settingsMenu->addSeparator();
QActionGroup* credGroup = new QActionGroup(this);
credGroup->setExclusive(true);
@@ -746,9 +791,9 @@ void MainWindow::setupMenuBar() {
(atLaunch ? m_credLaunchAction : m_credEachTimeAction)->setChecked(true);
connect(m_credEachTimeAction, &QAction::triggered, this,
[this]() { applyCredentialMode(AppCore::CredentialMode::EachTime); });
[this]() { onCredentialModeRequested(false); });
connect(m_credLaunchAction, &QAction::triggered, this,
[this]() { applyCredentialMode(AppCore::CredentialMode::AtLaunch); });
[this]() { onCredentialModeRequested(true); });
QMenu* helpMenu = menuBar->addMenu("Aide");
helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates);
@@ -806,6 +851,10 @@ void MainWindow::setupShortcuts() {
bind(QKeySequence(QStringLiteral("Ctrl+U")), [this]() {
m_navGroup->button(NavUpdates)->click();
});
// The convention every other application uses for its own settings.
bind(QKeySequence(QStringLiteral("Ctrl+,")), [this]() {
m_navGroup->button(NavSettings)->click();
});
bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() {
LogManager::instance().logEvent(QStringLiteral("ui"),
QStringLiteral("export de la liste affichée"));
@@ -831,6 +880,7 @@ void MainWindow::onNavChanged(int id) {
case NavHistory: pageName = QStringLiteral("historique"); break;
case NavLogs: pageName = QStringLiteral("logs"); break;
case NavPlugins: pageName = QStringLiteral("plugins"); break;
case NavSettings: pageName = QStringLiteral("paramètres"); break;
default: break;
}
LogManager::instance().logEvent(
@@ -871,6 +921,10 @@ void MainWindow::onNavChanged(int id) {
m_pages->setCurrentWidget(m_plugins);
m_plugins->refresh();
break;
case NavSettings:
m_pages->setCurrentWidget(m_settings);
m_settings->refresh();
break;
default:
break;
}
@@ -907,6 +961,7 @@ void MainWindow::onPageMessage(const QString& text) {
QStringList MainWindow::installableDroppedFiles(const QMimeData* mimeData) const {
QStringList files;
if (!AppSettings::instance().dragDropEnabled()) return files;
if (!mimeData || !mimeData->hasUrls()) return files;
for (const QUrl& url : mimeData->urls()) {
@@ -1063,6 +1118,87 @@ void MainWindow::applyCredentialMode(AppCore::CredentialMode mode) {
if (mode == AppCore::CredentialMode::AtLaunch) promptForSudoPassword();
}
// One place answers a change of mode, whichever of the two entry points (the
// menu bar, the Settings screen) asked for it, so both end up in step.
void MainWindow::onCredentialModeRequested(bool atLaunch) {
applyCredentialMode(atLaunch ? AppCore::CredentialMode::AtLaunch
: AppCore::CredentialMode::EachTime);
(atLaunch ? m_credLaunchAction : m_credEachTimeAction)->setChecked(true);
}
void MainWindow::onLanguageChanged(const QString& code) {
LogManager::instance().logEvent(QStringLiteral("config"),
QStringLiteral("langue → %1").arg(code));
// Qt asks every widget to retranslate itself through the LanguageChange
// event, which this window answers in changeEvent().
LanguageManager::apply(code);
}
void MainWindow::onDragDropEnabledChanged(bool enabled) {
// The preference governs the window's own drop target only: files handed
// over by the desktop ("Ouvrir avec PacManager") keep working either way.
setAcceptDrops(enabled);
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("glisser-déposer → %1")
.arg(enabled ? QStringLiteral("activé") : QStringLiteral("désactivé")));
}
void MainWindow::retranslateUI() {
// The screens provide their own title, so the header follows them.
updatePageTitle();
if (m_versionLabel) {
m_versionLabel->setText(QStringLiteral("v%1").arg(UpdateManager::currentVersion()));
}
struct NavLabel { int id; const char* text; const char* tip; };
// Kept next to the sidebar: those strings are the frame's, and the screens
// below retranslate themselves.
static const NavLabel kNavLabels[] = {
{NavDashboard, QT_TRANSLATE_NOOP("MainWindow", "Tableau de bord"),
QT_TRANSLATE_NOOP("MainWindow", "Vue d'ensemble du système")},
{NavSearch, QT_TRANSLATE_NOOP("MainWindow", "Recherche"),
QT_TRANSLATE_NOOP("MainWindow", "Rechercher des paquets")},
{NavInstalled, QT_TRANSLATE_NOOP("MainWindow", "Installés"),
QT_TRANSLATE_NOOP("MainWindow", "Voir les paquets installés")},
{NavUpdates, QT_TRANSLATE_NOOP("MainWindow", "Mises à jour"),
QT_TRANSLATE_NOOP("MainWindow", "Voir les mises à jour disponibles")},
{NavCleanup, QT_TRANSLATE_NOOP("MainWindow", "Nettoyage"),
QT_TRANSLATE_NOOP("MainWindow", "Purger les paquets inutilisés ou legacy et vider les caches")},
{NavHistory, QT_TRANSLATE_NOOP("MainWindow", "Historique"),
QT_TRANSLATE_NOOP("MainWindow", "Historique des actions")},
{NavLogs, QT_TRANSLATE_NOOP("MainWindow", "Logs"),
QT_TRANSLATE_NOOP("MainWindow", "Logs pacman")},
{NavPlugins, QT_TRANSLATE_NOOP("MainWindow", "Plugins"),
QT_TRANSLATE_NOOP("MainWindow", "Gestionnaires de paquets et extensions")},
{NavSettings, QT_TRANSLATE_NOOP("MainWindow", "Paramètres"),
QT_TRANSLATE_NOOP("MainWindow", "Journal, glisser-déposer, langue et mises à jour")},
};
for (const NavLabel& label : kNavLabels) {
auto it = m_navButtons.find(label.id);
if (it == m_navButtons.end()) continue;
// The updates entry carries its pending count in its label, which
// setUpdatesBadge() is the one to rebuild.
if (label.id != NavUpdates) it.value()->setText(tr(label.text));
it.value()->setToolTip(tr(label.tip));
}
setUpdatesBadge(m_updatesBadgeCount);
if (m_refreshButton) m_refreshButton->setText(tr("Rafraîchir les sources"));
if (m_headerUpdateAllButton) {
m_headerUpdateAllButton->setText(tr("Tout mettre à jour"));
}
}
void MainWindow::changeEvent(QEvent* event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUI();
}
QMainWindow::changeEvent(event);
}
// 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() {
+8
View File
@@ -3,6 +3,8 @@
#include <QStringList>
#include <QTimer>
#include "app-settings.h"
#include "language-manager.h"
#include "log-manager.h"
#include "main-window.h"
#include "update-manager.h"
@@ -17,11 +19,17 @@ int main(int argc, char* argv[]) {
// into the journal, so the Logs screen shows the same detail as a debug run
// without the user having to set QT_LOGGING_RULES.
QLoggingCategory::setFilterRules(QStringLiteral("pacmgr.*=true"));
// The journal opens where the user asked it to, not where the previous
// release wrote it: AppSettings is read before the first line is written.
LogManager::installQtMessageHandler();
LogManager::instance().logEvent(
QStringLiteral("app"),
QStringLiteral("session démarrée (v%1)").arg(UpdateManager::currentVersion()));
// The chosen catalogue is installed before any widget exists, so the whole
// interface is built in the right language from the start.
LanguageManager::apply(AppSettings::instance().language());
MainWindow window;
window.setWindowTitle("PacManager - Gestionnaire de Paquets");
window.resize(1200, 760);
+305
View File
@@ -0,0 +1,305 @@
#include "app-settings.h"
#include "log-manager.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QObject>
#include <QSettings>
#include <QString>
#include <QTemporaryDir>
#include <cassert>
#include <iostream>
// The preferences model, on its own and without a display: what a preference
// reads back, what it signals, and the two decisions that are pure functions
// (how long a block lasts, when it is in force).
namespace {
// Counts one signal so a test can assert it fired exactly once per real change.
// QSignalSpy would need Qt Test, which this target deliberately does not link.
//
// It is a QObject used as the connection's context: the settings object is a
// singleton that outlives every test, so without that the counter would be
// dangling by the time the *next* test changed a value.
class SignalCounter : public QObject {
public:
explicit SignalCounter(AppSettings* prefs) {
QObject::connect(prefs, &AppSettings::logDirectoryChanged, this,
[this](const QString&) { ++m_count; });
QObject::connect(prefs, &AppSettings::logMaxBytesChanged, this,
[this](qint64) { ++m_count; });
QObject::connect(prefs, &AppSettings::dragDropEnabledChanged, this,
[this](bool) { ++m_count; });
QObject::connect(prefs, &AppSettings::languageChanged, this,
[this](const QString&) { ++m_count; });
QObject::connect(prefs, &AppSettings::autoUpdateCheckEnabledChanged, this,
[this](bool) { ++m_count; });
QObject::connect(prefs, &AppSettings::updateBlockChanged, this,
[this] { ++m_count; });
}
int count() const { return m_count; }
private:
int m_count = 0;
};
// Every test starts from a known settings file: the model is a singleton, so
// what one test writes would otherwise leak into the next.
void resetSettings() {
QSettings().clear();
}
void testLogDirectoryDefaultsAndSanitizes() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// No preference saved: the journal goes to the user's own config tree.
assert(prefs.logDirectory() == AppSettings::defaultLogDirectory());
assert(!prefs.logDirectory().isEmpty());
// A home-relative path is what a user types; nothing else in the app would
// expand it for them.
assert(AppSettings::sanitizeLogDirectory(QStringLiteral("~/journaux")) ==
QDir::homePath() + QStringLiteral("/journaux"));
assert(AppSettings::sanitizeLogDirectory(QStringLiteral("~")) ==
QDir::homePath());
// An empty or blank directory is refused rather than leaving the app with
// nowhere to log.
assert(AppSettings::sanitizeLogDirectory(QString()).isEmpty() == false);
assert(AppSettings::sanitizeLogDirectory(QStringLiteral(" ")) ==
AppSettings::defaultLogDirectory());
SignalCounter counter(&prefs);
const QString wanted = QDir::homePath() + QStringLiteral("/journaux-pacmgr");
prefs.setLogDirectory(wanted);
assert(prefs.logDirectory() == wanted);
assert(counter.count() == 1);
// Setting the same value again says nothing new.
prefs.setLogDirectory(wanted);
assert(counter.count() == 1);
// Back to the default the key is dropped, not pinned: a later change of
// XDG_CONFIG_HOME must follow the user.
prefs.setLogDirectory(AppSettings::defaultLogDirectory());
assert(prefs.logDirectory() == AppSettings::defaultLogDirectory());
assert(!QSettings().contains(QStringLiteral("settings/logDirectory")));
}
void testLogSizeCap() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// No cap until the user picks one.
assert(prefs.logMaxBytes() == 0);
// A cap that would rotate on every line is raised to the floor rather than
// honoured; a negative cap means "no cap".
assert(AppSettings::sanitizeLogMaxBytes(-1) == 0);
assert(AppSettings::sanitizeLogMaxBytes(0) == 0);
assert(AppSettings::sanitizeLogMaxBytes(1024) == 64 * 1024);
assert(AppSettings::sanitizeLogMaxBytes(5LL * 1024 * 1024) == 5LL * 1024 * 1024);
SignalCounter counter(&prefs);
prefs.setLogMaxBytes(5LL * 1024 * 1024);
assert(prefs.logMaxBytes() == 5LL * 1024 * 1024);
assert(counter.count() == 1);
// The value stored is the one that will be read back, not what was asked for.
prefs.setLogMaxBytes(10);
assert(prefs.logMaxBytes() == 64 * 1024);
}
void testDragDropIsOnByDefault() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// Dropping a .flatpakref on the window is the quickest way to install one:
// turning it off has to be a deliberate act.
assert(prefs.dragDropEnabled());
SignalCounter counter(&prefs);
prefs.setDragDropEnabled(false);
assert(!prefs.dragDropEnabled());
assert(counter.count() == 1);
prefs.setDragDropEnabled(false);
assert(counter.count() == 1);
prefs.setDragDropEnabled(true);
assert(prefs.dragDropEnabled());
}
void testLanguage() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// No preference: follow the desktop, which the model records as "system".
assert(prefs.language() == QStringLiteral("system"));
// An unknown code must not be stored: the interface would then be in a
// language nothing can translate. An empty one is not unknown, it is unset.
assert(AppSettings::sanitizeLanguage(QString()).isEmpty() == false);
assert(AppSettings::sanitizeLanguage(QString()) == QStringLiteral("system"));
assert(AppSettings::sanitizeLanguage(QStringLiteral("klingon")) == QStringLiteral("fr"));
assert(AppSettings::sanitizeLanguage(QStringLiteral("EN")) == QStringLiteral("en"));
assert(AppSettings::sanitizeLanguage(QStringLiteral("system")) == QStringLiteral("system"));
SignalCounter counter(&prefs);
prefs.setLanguage(QStringLiteral("en"));
assert(prefs.language() == QStringLiteral("en"));
assert(counter.count() == 1);
prefs.setLanguage(QStringLiteral("en"));
assert(counter.count() == 1);
assert(AppSettings::knownLanguages().contains(QStringLiteral("fr")));
assert(AppSettings::knownLanguages().contains(QStringLiteral("en")));
}
void testUpdateBlockPolicyIsPure() {
const QDateTime now(QDate(2026, 9, 28), QTime(12, 0));
// Hours add up; "until cancelled" has no end and says so with an invalid date.
assert(AppSettings::blockTarget(now, 1) == now.addSecs(3600));
assert(AppSettings::blockTarget(now, 24 * 7) == now.addSecs(7 * 24 * 3600));
assert(!AppSettings::blockTarget(now, 0).isValid());
assert(!AppSettings::blockTarget(now, -5).isValid());
// Not blocked, blocked for a while, blocked for ever.
assert(!AppSettings::isBlocked(now, false, QDateTime()));
assert(AppSettings::isBlocked(now, false, now.addSecs(3600)));
assert(!AppSettings::isBlocked(now, false, now.addSecs(-1)));
assert(AppSettings::isBlocked(now, true, QDateTime()));
// The instant the block ends, it is over: a snooze that outlived itself
// must not keep the user from ever checking again.
assert(!AppSettings::isBlocked(now.addSecs(3600), false, now.addSecs(3600)));
// What it means, for the screen: nothing when no block is in force.
assert(AppSettings::blockDescription(false, QDateTime(), now).isEmpty());
assert(!AppSettings::blockDescription(true, QDateTime(), now).isEmpty());
assert(!AppSettings::blockDescription(false, now.addSecs(3600), now).isEmpty());
assert(!AppSettings::blockDescription(false, now.addSecs(180), now).isEmpty());
assert(AppSettings::blockDescription(false, now.addSecs(-1), now).isEmpty());
}
void testUpdateBlockIsPersistedAndCleared() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
assert(!prefs.autoUpdateCheckEnabled() == false); // checked once a day by default
assert(!prefs.updatesBlocked());
SignalCounter counter(&prefs);
prefs.blockUpdatesFor(1);
assert(prefs.updatesBlocked());
assert(!prefs.updatesBlockedIndefinitely());
assert(prefs.updateBlockedUntil().isValid());
assert(counter.count() == 1);
// The block survives being read back: a new process sees the same block.
AppSettings fresh;
assert(fresh.updatesBlocked());
assert(fresh.updateBlockedUntil() == prefs.updateBlockedUntil());
// "Until cancelled" keeps no deadline and still blocks.
prefs.blockUpdatesFor(0);
assert(prefs.updatesBlocked());
assert(prefs.updatesBlockedIndefinitely());
assert(!prefs.updateBlockedUntil().isValid());
prefs.unblockUpdates();
assert(!prefs.updatesBlocked());
assert(!prefs.updatesBlockedIndefinitely());
assert(!prefs.updateBlockedUntil().isValid());
}
void testAutomaticCheckCanBeTurnedOff() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
SignalCounter counter(&prefs);
prefs.setAutoUpdateCheckEnabled(false);
assert(!prefs.autoUpdateCheckEnabled());
assert(counter.count() == 1);
// Turning it back on is not blocked by a block still in force: the two
// settings are independent.
prefs.setAutoUpdateCheckEnabled(true);
assert(prefs.autoUpdateCheckEnabled());
assert(counter.count() == 2);
}
// The journal is the one thing the preferences change on disk, so it is
// exercised for real: it must land in the chosen directory, carry the previous
// one along, and rotate once the cap is reached.
void testJournalMovesAndRotates() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
LogManager& journal = LogManager::instance();
// Cleared before the directory is chosen: a leftover from a previous run
// would be carried over by the move and read as this run's.
const QString first = QDir::homePath() + QStringLiteral("/journal-a");
QFile::remove(first + QStringLiteral("/operations.log"));
prefs.setLogDirectory(first);
journal.logEvent(QStringLiteral("test"), QStringLiteral("premier"));
assert(QFile::exists(first + QStringLiteral("/operations.log")));
assert(journal.filePath() == first + QStringLiteral("/operations.log"));
// Switching directory carries the journal along: the user did not ask to
// lose the record of what the app did.
const QString second = QDir::homePath() + QStringLiteral("/journal-b");
QFile::remove(second + QStringLiteral("/operations.log"));
prefs.setLogDirectory(second);
assert(QFile::exists(second + QStringLiteral("/operations.log")));
assert(!QFile::exists(first + QStringLiteral("/operations.log")));
assert(journal.readFile().contains(QStringLiteral("premier")));
// The cap is a real ceiling, and the journal that came before is kept.
prefs.setLogMaxBytes(64 * 1024);
for (int i = 0; i < 2000; ++i) {
journal.logEvent(QStringLiteral("test"),
QStringLiteral("ligne de remplissage numéro %1").arg(i));
}
assert(QFile::exists(second + QStringLiteral("/operations.log.1")));
assert(journal.currentSizeBytes() <= 64 * 1024);
// Back to no cap, and the log goes on growing.
prefs.setLogMaxBytes(0);
const qint64 before = journal.currentSizeBytes();
journal.logEvent(QStringLiteral("test"), QStringLiteral("dernière"));
assert(journal.currentSizeBytes() > before);
}
} // namespace
int main(int argc, char* argv[]) {
// The model reads and writes QSettings, so the whole run has to happen
// against a throwaway configuration.
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("PacManagerSettingsTest");
app.setOrganizationName("FWSTest");
// The model is a singleton: one format, one place, decided before the first
// QSettings is built.
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
QDir(home.path()).filePath("settings"));
testLogDirectoryDefaultsAndSanitizes();
testLogSizeCap();
testDragDropIsOnByDefault();
testLanguage();
testUpdateBlockPolicyIsPure();
testUpdateBlockIsPersistedAndCleared();
testAutomaticCheckCanBeTurnedOff();
testJournalMovesAndRotates();
std::cout << "app-settings: all tests passed" << std::endl;
return 0;
}
+1 -1
View File
@@ -1 +1 @@
1.5.5
1.6.0