Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29ec30e867
|
||
|
|
bbaf39144f
|
||
|
|
aff959bc4b
|
No files matched your search
+42
-16
@@ -31,9 +31,9 @@ set(SOURCES
|
||||
src/history-manager.cpp
|
||||
src/package-model.cpp
|
||||
src/update-manager.cpp
|
||||
# Headless pass run at login by the systemd unit the app installs itself.
|
||||
src/startup-check.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
|
||||
@@ -49,6 +49,7 @@ set(SOURCES
|
||||
src/log-manager.cpp
|
||||
pages/logs-page.cpp
|
||||
pages/plugins-page.cpp
|
||||
pages/settings-page.cpp
|
||||
resources/resources.qrc
|
||||
)
|
||||
|
||||
@@ -61,8 +62,9 @@ set(HEADERS
|
||||
include/history-manager.h
|
||||
include/package-model.h
|
||||
include/update-manager.h
|
||||
include/startup-check.h
|
||||
include/app-logging.h
|
||||
include/app-settings.h
|
||||
include/language-manager.h
|
||||
include/workers.h
|
||||
include/progress-tracker.h
|
||||
include/plugin-shop.h
|
||||
@@ -76,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})
|
||||
@@ -191,16 +194,49 @@ add_test(NAME aur-manager-test COMMAND aur-manager-test)
|
||||
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/startup-check.cpp
|
||||
src/app-logging.cpp src/log-manager.cpp
|
||||
src/plugin-shop.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/startup-check.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)
|
||||
@@ -209,16 +245,6 @@ target_compile_definitions(update-manager-test PRIVATE
|
||||
FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}")
|
||||
add_test(NAME update-manager-test COMMAND update-manager-test)
|
||||
|
||||
# StartupCheck: the pure half (parsing, critical/reboot classification,
|
||||
# notification text) and the autostart files, driven inside a temporary tree so
|
||||
# the user's own ~/.config is never touched.
|
||||
add_executable(startup-check-test tests/startup-check.test.cpp
|
||||
src/startup-check.cpp src/log-manager.cpp src/app-logging.cpp
|
||||
include/startup-check.h include/log-manager.h)
|
||||
target_include_directories(startup-check-test PRIVATE include)
|
||||
target_link_libraries(startup-check-test PRIVATE Qt6::Core)
|
||||
add_test(NAME startup-check-test COMMAND startup-check-test)
|
||||
|
||||
# ---- Plugins ----
|
||||
#
|
||||
# Flatpak ships as an external provider plugin (not compiled into the binary):
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+28
-2
@@ -135,11 +135,37 @@ refusée tant que la première tourne. Voir [operations.md](operations.md).
|
||||
|
||||
| Besoin | Endroit |
|
||||
| --- | --- |
|
||||
| Un nouvel écran | Une classe `Page` dans `pages/`, un fichier `.h/.cpp`, puis `setupPages()` et une entrée de barre latérale dans `main_window`. |
|
||||
| Un nouvel écran | Une classe `Page` dans `pages/`, un fichier `.h/.cpp`, puis `setupPages()` et une entrée de barre latérale dans `main_window`. Un écran qui n'est pas une destination à parcourir (les Paramètres) s'enregistre pareil mais s'atteint par `openSettingsPage()` : sans bouton de navigation, `onNavChanged()` ne l'atteint pas. |
|
||||
| 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
@@ -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
|
||||
|
||||
+73
-2
@@ -20,6 +20,13 @@ 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
|
||||
dupliquer la table et le panneau de détails.
|
||||
|
||||
**Un seul écran n'a pas d'entrée** : les **Paramètres** (`settings-page`). Ce
|
||||
n'est pas une destination où l'on navigue pour parcourir, et il n'encombrerait
|
||||
pas la barre latérale ; on l'atteint par le menu **Paramètres** de la barre de
|
||||
menu, ou par `Ctrl+,`. C'est le seul point d'entrée, et la barre latérale ne
|
||||
laisse alors **aucune entrée sélectionnée** (rien à gauche ne correspond à
|
||||
l'écran affiché).
|
||||
|
||||
### Éléments communs
|
||||
|
||||
- **En-tête** : titre et sous-titre de l'écran courant, plus « Rafraîchir » et
|
||||
@@ -28,8 +35,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 +81,57 @@ 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** (`settings-page`, ouvert par le menu du même nom ou
|
||||
`Ctrl+,` — il n'a pas d'entrée dans la barre latérale) 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 +140,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
|
||||
@@ -91,6 +150,13 @@ L'apparence reprend le **design system du site FWS**
|
||||
est appliquée à la fenêtre (`appStyleSheet()` dans `src/main-window.cpp`) : un
|
||||
fichier d'écran ne décrit que sa mise en page et son texte, jamais ses couleurs.
|
||||
|
||||
Une exception : les menus déroulants. Un `QMenu` est une **fenêtre native
|
||||
séparée**, et la marge que la plateforme dessine autour (l'ombre du popup) n'appartient
|
||||
pas au widget que la feuille de style dessine — elle est remplie depuis la
|
||||
palette de l'application. Sans palette sombre, elle ressort en bande **blanche en
|
||||
haut et en bas** du menu sur un thème clair. D'où `MainWindow::appPalette()`,
|
||||
appliquée dans `main()` avant tout widget.
|
||||
|
||||
### Tokens
|
||||
|
||||
| Rôle | Valeur | Usage |
|
||||
@@ -141,6 +207,11 @@ de style ne fait que fixer la couleur du texte.
|
||||
| Besoin | Endroit |
|
||||
| --- | --- |
|
||||
| Une couleur, une bordure, un rayon | `appStyleSheet()` dans `src/main-window.cpp`. |
|
||||
| Ce que la feuille de style n'atteint pas (marge des menus déroulants, ombres de popup) | `MainWindow::appPalette()`, appliquée dans `main.cpp`. Même tableau de tokens, mais en rôles de palette : Qt 6 n'a pas de rôle `Menu`, c'est `Window` qui remplit la marge du popup. |
|
||||
| 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.
|
||||
+109
-43
@@ -4,58 +4,124 @@ 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`.
|
||||
|
||||
## Vérification des mises à jour au démarrage
|
||||
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.
|
||||
|
||||
L'application peut aussi **vérifier les mises à jour disponibles à chaque
|
||||
ouverture de session**, sans rien demander — et afficher une notification
|
||||
quand certains paquets sont en attente, en particulier le noyau
|
||||
(`linux`, `linux-lts`, …), la glibc ou systemd.
|
||||
## La version
|
||||
|
||||
- L'application installe **soi-même** son service systemd `--user` :
|
||||
`~/.config/systemd/user/pacmanager-check-updates.service`, activé
|
||||
(`default.target.wants`). Il suffit de l'ouvrir une fois pour que le
|
||||
comportement existe, et le menu ci-dessous pour l'activer/désactiver.
|
||||
- Le service s'exécute avec **`checkupdates`** (paquet `pacman-contrib`),
|
||||
qui synchrone une base temporaire : **aucun mot de passe, aucun sudo**,
|
||||
pas de risque de base pacman half-synchro. Si `checkupdates` est absent,
|
||||
le service retombe sur `pacman -Qu` (base déjà synchronisée) et avertit
|
||||
dans le journal que les résultats peuvent être moins précis.
|
||||
- La notification est **urgente** quand un paquet critique est en attente
|
||||
(noyau, firmware, glibc, systemd, pilote `nvidia`…) et indique qu'un
|
||||
redémarrage sera nécessaire. Le démon de notification (mako) doit être
|
||||
lancé, et le service attend son lancement avant d'envoyer.
|
||||
- La couche logique est testable sans écran, sans système, sans système de
|
||||
fichiers utilisateur : elle s'exécute dans un dossier temporaire.
|
||||
Le fichier `version` à la racine du dépôt est la **source unique de vérité** :
|
||||
|
||||
Le code est dans `include/startup-check.h` / `src/startup-check.cpp` et le
|
||||
mode CLI est `PacManager --check-updates` (pas de fenêtre, pas de dépôt).
|
||||
|
||||
## Réglage
|
||||
|
||||
Menu **Paramètres → Vérifier les mises à jour au démarrage**.
|
||||
Cocheé par défaut : l'unité est installée à chaque ouverture.
|
||||
|
||||
| Action | Où |
|
||||
| Où | Comment |
|
||||
| --- | --- |
|
||||
| Activer / désactiver la vérification | Paramètres |
|
||||
| Forcer un contrôle maintenant | Menu **Aide → Vérifier les mises à jour** |
|
||||
| Voir les mises à jour disponibles | Page **Mises à jour** |
|
||||
| Compilée dans le binaire | `version` est lu à la configuration CMake et injecté (`FWSPACMANAGE_VERSION`). |
|
||||
| Posée à côté de l'exécutable | Le fichier est recopié après la compilation, et réécrit par chaque mise à jour. |
|
||||
|
||||
Le service est aussi utilisable manuellement :
|
||||
À l'exécution, la version retenue est **la plus récente des deux**
|
||||
(`newestVersion()`). C'est ce qui évite de proposer pour toujours une version
|
||||
déjà installée quand l'une des deux sources retarde — un binaire recompilé sans
|
||||
reconfiguration, ou une installation plus ancienne que le binaire. Le résultat de
|
||||
`isNewerVersion()` (comparaison de versions pointées) décide s'il y a une mise à
|
||||
jour à proposer.
|
||||
|
||||
```sh
|
||||
# exécuter la vérification maintenant (sans passer par le menu)
|
||||
systemctl --user start pacmanager-check-updates.service
|
||||
systemctl --user status pacmanager-check-updates.service --no-pager
|
||||
```
|
||||
## L'état de contrôle
|
||||
|
||||
`~/.local/share/PacManager/update-state.json` retient :
|
||||
|
||||
| Champ | Rôle |
|
||||
| --- | --- |
|
||||
| `lastCheckDate` | Date du dernier contrôle réussi : un seul appel réseau par jour. |
|
||||
| `latestRemoteVersion` | Dernière version vue sur le serveur, affichable même sans réseau. |
|
||||
|
||||
## Les dépendances de compilation
|
||||
|
||||
Les méthodes *Checkout*, *Clone* et *Tarball* recompilent l'application : elles
|
||||
ont besoin de **base-devel, cmake, gcc, git et qt6-base**. Plutôt que de les
|
||||
exiger à l'avance, la mise à jour les installe elle-même :
|
||||
|
||||
1. Le dialogue de mise à jour demande le mot de passe sudo dès que `pacman -T`
|
||||
signale un paquet manquant (en plus du cas « dossier cible non accessible en
|
||||
écriture ») — l'utilisateur voit **pourquoi** le mot de passe est demandé ;
|
||||
2. Le script de mise à jour commence par `pacman -T` puis
|
||||
`sudo pacman -S --needed --noconfirm` avec les paquets manquants ;
|
||||
3. La recompilation n'est tentée qu'ensuite.
|
||||
|
||||
Sur une machine complète, aucune étape de plus : `pacman -T` ne renvoie rien et
|
||||
le bloc est sauté. `pacman -T` n'est interrogé qu'une fois par lancement
|
||||
(`missingBuildDependencies()`), et le choix de méthode considère alors la
|
||||
machine comme « constructible » même sans cmake ni compilateur installés :
|
||||
``canInstallPackages`` suffit, puisque pacman peut combler le manque.
|
||||
|
||||
## Les quatre méthodes d'installation
|
||||
|
||||
Toutes installent **au même endroit : le dossier de l'exécutable en cours
|
||||
d'exécution** (`binDir()`). L'application ne suppose donc aucun préfixe — elle se
|
||||
met à jour dans `~/.local/bin`, `/usr/bin`, un dossier décompressé ou un
|
||||
arborescence de build de la même façon.
|
||||
|
||||
| Méthode | Quand elle est choisie | Ce qui se passe |
|
||||
| --- | --- | --- |
|
||||
| **Checkout** | Un dépôt source entoure le binaire (cas du développeur) | Installe les déps manquantes, puis `git pull`, recompilation, installation dans le dossier du binaire. |
|
||||
| **Clone** | Application installée sans dépôt, avec `git` (ou pacman pour l'installer) | Installe les déps manquantes, clone (puis `git pull`) dans `~/.local/share/PacManager/src`, compilation, installation en place. |
|
||||
| **Prebuilt** | Pas d'outillage de compilation **et** pacman absent ou inutile, avec une archive précompilée attachée à la release | Téléchargement et décompression de `PacManager-<version>-x86_64.tar.gz`. |
|
||||
| **Tarball** | `git` absent mais un toolchain présent **ou installable via pacman** | Installe les déps manquantes, compilation des sources de la release, puis installation en place. |
|
||||
| *Aucune* | Ni outillage (réel ou installable), ni archive attachée | Le dialogue propose d'**ouvrir la page des releases** au lieu d'un bouton qui échouerait. |
|
||||
|
||||
Le choix est une **fonction pure** (`chooseUpdateMethod()` sur
|
||||
`UpdateCapabilities` : checkout utilisable, `git`, `cmake`, compilateur, archive
|
||||
précompilée, tarball), ce qui permet de le tester sans réseau ni outillage.
|
||||
|
||||
## Le déroulé
|
||||
|
||||
1. Le contrôle de version (API Gitea) renvoie un tag plus récent.
|
||||
2. La fenêtre affiche un dialogue : version disponible, méthode qui sera utilisée
|
||||
et dossier cible (`methodDescription()`).
|
||||
3. `sudo` est demandé quand le dossier cible n'est pas accessible en écriture
|
||||
(`binDirWritable()`), c'est-à-dire typiquement pour `/usr/bin`, **ou quand des
|
||||
dépendances de compilation manquent** — voir la section ci-dessus. Tout le
|
||||
reste se compile dans un dossier temporaire appartenant à l'utilisateur.
|
||||
4. La mise à jour tourne en arrière-plan ; le binaire en cours d'exécution n'est
|
||||
pas touché.
|
||||
5. À la fin, l'application **relance** le binaire fraîchement installé
|
||||
(`restartProgram()`) et se ferme : le processus en cours mappe encore l'inode
|
||||
remplacé, seul un redémarrage fait tourner la nouvelle version. Si aucun
|
||||
binaire exécutable n'est trouvé sur place, un message demande un redémarrage
|
||||
manuel.
|
||||
|
||||
L'installation copie chaque fichier vers un fichier temporaire voisin **puis le
|
||||
renomme** (`stagedInstallScript()`) : c'est ce qui permet d'écraser un binaire
|
||||
(ou un plugin) actuellement utilisé, cas où un `cp` direct échoue avec
|
||||
`ETXTBSY` (« Text file busy »).
|
||||
|
||||
## Ce qui n'est jamais fait automatiquement
|
||||
|
||||
- Le contrôle n'**interrompt** jamais l'ouverture de la fenêtre.
|
||||
- La vérification n'**installe jamais** de paquet : elle fait juste
|
||||
remonter le nombre et le type de mises à jour.
|
||||
- Le service n'**attendre jamais** le démon de notification : s'il n'est
|
||||
pas là, la vérification se termine sans notifier.
|
||||
**Aucune archive précompilée n'est produite par le dépôt** : sans asset attaché à
|
||||
la release, ce sont les méthodes *Clone* ou *Tarball* qui s'appliquent. Grâce à
|
||||
l'installation automatique des dépendances, il suffit d'avoir `pacman` (donc
|
||||
d'être sur Arch) et de fournir le mot de passe sudo — `git`, `cmake`, le
|
||||
compilateur et `qt6-base` sont installés par la mise à jour elle-même. Une
|
||||
installation hors Arch sans outillage ni archive ouvre la page des releases.
|
||||
|
||||
## Vérifier à la main
|
||||
|
||||
| Action | Où |
|
||||
| --- | --- |
|
||||
| Forcer un contrôle | Menu **Aide → Vérifier les mises à jour**, ou le menu du tray. |
|
||||
| Voir la version installée | Bas de la barre latérale. |
|
||||
| Comprendre un échec | Le journal applicatif : `QT_LOGGING_RULES="pacmgr.update.debug=true" PacManager`. |
|
||||
| Repartir de zéro | Supprimer `~/.local/share/PacManager/update-state.json`. |
|
||||
|
||||
## Dépannage
|
||||
|
||||
| Symptôme | Cause probable |
|
||||
| --- | --- |
|
||||
| Le dialogue n'apparaît jamais | Dernier contrôle de moins de 24 h (`lastCheckDate`). |
|
||||
| « Aucune release trouvée sur le serveur » | Le dépôt n'a pas de release publiée. |
|
||||
| La mise à jour annonce échouer alors que le binaire a changé | Écriture impossible sans droits : vérifier les droits du dossier du binaire, ou relancer en acceptant la demande `sudo`. |
|
||||
| L'application redémarre sur l'ancienne version | Le `version` voisin du binaire n'a pas pu être réécrit : sans lui, `newestVersion()` retombe sur la version compilée, souvent plus ancienne. Vérifier les droits du fichier. |
|
||||
| Recompilation interminable | Méthode *Clone*/*Tarball* : c'est le comportement attendu sans archive précompilée attachée à la release. |
|
||||
| « sudo: a password is required » dans le journal | La mise à jour a tourné sans mot de passe et le dossier cible (ou l'installation des déps) le demandait : relancer et saisir le mot de passe dans le dialogue. |
|
||||
|
||||
Voir aussi [installation.md](installation.md) pour les chemins concernés et
|
||||
[operations.md](operations.md) pour le rôle de `sudo` dans le reste de
|
||||
|
||||
@@ -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
-12
@@ -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;
|
||||
@@ -168,18 +180,6 @@ public:
|
||||
// when the update cannot run (no method available).
|
||||
bool applySelfUpdate(const QString& sudoPassword, QString* error);
|
||||
|
||||
// ---- Startup update check ----
|
||||
// Whether the app installs its login check: a systemd user unit that runs
|
||||
// `PacManager --check-updates` and pops a notification when updates are
|
||||
// pending — no window, no sudo password. On by default, since the point is
|
||||
// to warn the user without them opening the app.
|
||||
bool checkUpdatesAtStartup() const;
|
||||
void setCheckUpdatesAtStartup(bool enabled);
|
||||
// Refreshes the installed unit when the setting is on, in case the binary
|
||||
// moved since it was written. Idempotent; called once at window startup so
|
||||
// an update of the app keeps the login check pointing at the real file.
|
||||
void ensureStartupAutostart();
|
||||
|
||||
// ---- pacman's database lock ----
|
||||
bool databaseLocked() const;
|
||||
// What currently holds the lock, so the view can name the process it offers
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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
@@ -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;
|
||||
|
||||
+31
-1
@@ -3,6 +3,7 @@
|
||||
#include <QElapsedTimer>
|
||||
#include <QHash>
|
||||
#include <QMainWindow>
|
||||
#include <QPalette>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QSystemTrayIcon>
|
||||
@@ -33,6 +34,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
|
||||
@@ -49,6 +51,10 @@ public:
|
||||
explicit MainWindow(QWidget* parent = nullptr);
|
||||
~MainWindow();
|
||||
|
||||
// Colours the stylesheet cannot reach, applied in main() before any widget
|
||||
// exists. See the definition for what leaves a light band around a menu.
|
||||
static QPalette appPalette();
|
||||
|
||||
// Installs the Flatpak files handed over by the desktop: dropped on the
|
||||
// window, or opened from the file manager ("Ouvrir avec PacManager", which
|
||||
// passes them on the command line). One install runs at a time; the rest
|
||||
@@ -61,6 +67,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 +113,7 @@ private:
|
||||
NavHistory,
|
||||
NavLogs,
|
||||
NavPlugins,
|
||||
NavSettings,
|
||||
};
|
||||
|
||||
void setupUI();
|
||||
@@ -117,6 +126,8 @@ private:
|
||||
// Wires a screen: the frame answers its requests and shows the page it asks
|
||||
// for. Called once per screen by setupPages().
|
||||
void registerPage(const QString& id, int navId, Page* page);
|
||||
// Shows the settings screen, which has no sidebar entry of its own.
|
||||
void openSettingsPage();
|
||||
// Screen currently displayed, and the screens themselves.
|
||||
Page* currentPage() const;
|
||||
void updatePageTitle();
|
||||
@@ -124,6 +135,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 +152,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 +202,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
|
||||
@@ -211,5 +242,4 @@ private:
|
||||
// Menu
|
||||
QAction* m_credLaunchAction = nullptr;
|
||||
QAction* m_credEachTimeAction = nullptr;
|
||||
QAction* m_startupCheckAction = nullptr;
|
||||
};
|
||||
@@ -1,118 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
// The headless pass that answers "does this machine have pending updates?" and,
|
||||
// when it does, raises a desktop notification.
|
||||
//
|
||||
// It exists because the graphical window is not running when the machine
|
||||
// starts: the app installs a systemd user unit (see the autostart helpers here)
|
||||
// that runs `PacManager --check-updates` at login, and that call lands here.
|
||||
//
|
||||
// Two guarantees drive the implementation:
|
||||
// - no password: the check goes through `checkupdates` (pacman-contrib), which
|
||||
// syncs into a throwaway database and therefore needs no root, instead of a
|
||||
// `pacman -Sy` the login unit could never authenticate;
|
||||
// - no display: everything here is Qt Core only, so the unit runs with no
|
||||
// DISPLAY, no Wayland socket and no widget.
|
||||
//
|
||||
// The pure parts (parsing, classification, notification text, unit contents)
|
||||
// are static so they are unit-tested without a package manager, a network or a
|
||||
// session bus.
|
||||
class StartupCheck : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
// Outcome of one check, so the caller (and the tests) can inspect what
|
||||
// happened without parsing console output.
|
||||
struct Result {
|
||||
int updateCount = 0;
|
||||
bool anyCritical = false; // kernel, glibc, init, graphics stack...
|
||||
bool rebootRequired = false; // a kernel or its firmware is pending
|
||||
QStringList packages;
|
||||
// Non-empty when the check failed, or when it could only run in a
|
||||
// degraded way (the pacman -Qu fallback, which reads a database only
|
||||
// root can refresh). Never a reason to skip the notification.
|
||||
QString error;
|
||||
};
|
||||
|
||||
explicit StartupCheck(QObject* parent = nullptr);
|
||||
|
||||
// Runs the whole headless pass (check, then notify when something is
|
||||
// pending) and returns the exit code for main(). Always 0: a background
|
||||
// check that fails must not fill the user's journal with failed units.
|
||||
int run();
|
||||
|
||||
// ---- Pure helpers (unit-tested) ----
|
||||
// Parses the checked tool's output. `checkupdates` prints
|
||||
// "name oldver -> newver" and `pacman -Qu` prints "name newver"; only the
|
||||
// package name is needed and it is the first whitespace-separated token of
|
||||
// every line, so one parser accepts both. Duplicates are dropped.
|
||||
static QStringList parseUpdates(const QString& output);
|
||||
|
||||
// A package whose update deserves an urgent notification rather than the
|
||||
// ordinary one: the kernel and its firmware, the C library and init, the
|
||||
// graphics stack, pacman itself — the updates that either need a reboot or
|
||||
// can break the session when they fall behind. Prefix-based on purpose: a
|
||||
// package nobody thought about simply gets the normal notification.
|
||||
static bool isCritical(const QString& package);
|
||||
|
||||
// A package whose update only takes effect after a reboot: the kernel and
|
||||
// the out-of-tree driver built against the running one.
|
||||
static bool isRebootRequired(const QString& package);
|
||||
|
||||
// The critical subset of a list, so the notification can name what matters.
|
||||
static QStringList criticalPackages(const QStringList& packages);
|
||||
|
||||
// Notification title and body for a set of pending updates.
|
||||
static QString notificationTitle(const Result& result);
|
||||
static QString notificationBody(const Result& result);
|
||||
|
||||
// ---- Check and notify (touch the machine) ----
|
||||
// Pending updates, using `checkupdates` when available and falling back to
|
||||
// the already-synced `pacman -Qu` otherwise. Never needs root; the fallback
|
||||
// reads a database only root can refresh, so it may miss updates — which is
|
||||
// what `error` records rather than hiding.
|
||||
static Result check();
|
||||
|
||||
// Sends the notification through notify-send, waiting briefly for the
|
||||
// notification daemon (the login unit can start before mako). Returns false
|
||||
// when nothing could be sent.
|
||||
static bool notify(const Result& result);
|
||||
|
||||
// ---- Autostart: a systemd user unit the app installs itself ----
|
||||
// The unit lives under `configDir` (XDG_CONFIG_HOME, i.e. ~/.config) and is
|
||||
// enabled by a symlink in default.target.wants, which is the per-user
|
||||
// equivalent of `systemctl --user enable` without shelling out to it.
|
||||
// Passing the directory lets the unit test drive install/remove inside a
|
||||
// temporary tree instead of the user's own ~/.config.
|
||||
static QString autostartUnitPath(const QString& configDir);
|
||||
static QString autostartWantsPath(const QString& configDir);
|
||||
|
||||
// Writes the unit and the enabling symlink. `program` is the binary to run
|
||||
// with --check-updates (the running executable, so it follows the install
|
||||
// wherever it is). Filesystem only: no systemd call, so tests stay hermetic.
|
||||
static bool installAutostart(const QString& configDir, const QString& program,
|
||||
QString* error = nullptr);
|
||||
static bool removeAutostart(const QString& configDir, QString* error = nullptr);
|
||||
static bool autostartEnabled(const QString& configDir);
|
||||
|
||||
// Asks the user's systemd manager to re-read its units, so a fresh install
|
||||
// takes effect without waiting for the next boot. Best effort; a system
|
||||
// without a running user manager (a test, a container) is not an error.
|
||||
static bool reloadUserManager();
|
||||
|
||||
private:
|
||||
// Runs a tool to completion, returning its stdout. stderr is kept out of it
|
||||
// on purpose: a pacman warning is not a package name, so folding the two
|
||||
// would feed the parser lines it must not see — `stderrText` receives them
|
||||
// for the error message instead. `exitCode` receives the status, or -1 when
|
||||
// the process could not be started or timed out.
|
||||
static QString runTool(const QString& program, const QStringList& args,
|
||||
int timeoutMs, int* exitCode, QString* stderrText = nullptr);
|
||||
|
||||
// Waits (bounded) for the session's notification daemon, then sends through
|
||||
// notify-send with the given urgency.
|
||||
static bool sendNotification(const QString& title, const QString& body, bool urgent);
|
||||
};
|
||||
@@ -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; }
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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 |
@@ -11,6 +11,7 @@
|
||||
<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>
|
||||
|
||||
+27
-82
@@ -1,10 +1,8 @@
|
||||
#include "app-core.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDir>
|
||||
#include <QDateTime>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QStandardPaths>
|
||||
#include <QTimer>
|
||||
|
||||
#include <algorithm>
|
||||
@@ -17,7 +15,6 @@
|
||||
#include "app-logging.h"
|
||||
#include "log-manager.h"
|
||||
#include "plugin-shop.h"
|
||||
#include "startup-check.h"
|
||||
#include "workers.h"
|
||||
|
||||
namespace {
|
||||
@@ -1198,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..."));
|
||||
@@ -1246,84 +1269,6 @@ bool AppCore::applySelfUpdate(const QString& sudoPassword, QString* error) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Startup update check
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
// Directory the systemd user unit is written under. GenericConfigLocation is
|
||||
// ~/.config, honouring XDG_CONFIG_HOME, which is exactly where systemd looks.
|
||||
QString userConfigDir() {
|
||||
QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
|
||||
if (dir.isEmpty()) dir = QDir::homePath() + "/.config";
|
||||
return dir;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool AppCore::checkUpdatesAtStartup() const {
|
||||
return m_settings.value("updates/checkAtStartup", true).toBool();
|
||||
}
|
||||
|
||||
void AppCore::setCheckUpdatesAtStartup(bool enabled) {
|
||||
m_settings.setValue("updates/checkAtStartup", enabled);
|
||||
|
||||
const QString configDir = userConfigDir();
|
||||
QString error;
|
||||
|
||||
if (enabled) {
|
||||
// The unit runs the executable that is doing the installing, so the
|
||||
// check follows an app installed anywhere (~/.local/bin, /usr/bin...).
|
||||
const QString program =
|
||||
UpdateManager::restartProgram(QCoreApplication::applicationDirPath());
|
||||
if (program.isEmpty() ||
|
||||
!StartupCheck::installAutostart(configDir, program, &error)) {
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("config"),
|
||||
QStringLiteral("autostart des mises à jour impossible : %1")
|
||||
.arg(error.isEmpty() ? QStringLiteral("binaire introuvable") : error));
|
||||
emit statusMessage(QStringLiteral("Impossible d'installer la vérification au démarrage."));
|
||||
return;
|
||||
}
|
||||
StartupCheck::reloadUserManager();
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("config"),
|
||||
QStringLiteral("vérification des mises à jour au démarrage activée"));
|
||||
emit statusMessage(QStringLiteral(
|
||||
"Vérification des mises à jour au démarrage activée (notification à l'ouverture de session)."));
|
||||
} else {
|
||||
StartupCheck::removeAutostart(configDir, &error);
|
||||
StartupCheck::reloadUserManager();
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("config"),
|
||||
QStringLiteral("vérification des mises à jour au démarrage désactivée"));
|
||||
emit statusMessage(QStringLiteral("Vérification des mises à jour au démarrage désactivée."));
|
||||
}
|
||||
}
|
||||
|
||||
void AppCore::ensureStartupAutostart() {
|
||||
if (!checkUpdatesAtStartup()) return;
|
||||
|
||||
const QString program =
|
||||
UpdateManager::restartProgram(QCoreApplication::applicationDirPath());
|
||||
if (program.isEmpty()) return;
|
||||
|
||||
const QString configDir = userConfigDir();
|
||||
const bool wasEnabled = StartupCheck::autostartEnabled(configDir);
|
||||
|
||||
// Rewriting the unit on every launch keeps the executable path current (the
|
||||
// app may have moved), but only a fresh install needs systemd to be told.
|
||||
QString error;
|
||||
if (!StartupCheck::installAutostart(configDir, program, &error)) {
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("config"),
|
||||
QStringLiteral("autostart des mises à jour non installé : %1").arg(error));
|
||||
return;
|
||||
}
|
||||
if (!wasEnabled) StartupCheck::reloadUserManager();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// pacman's database lock
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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
@@ -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.
|
||||
|
||||
+200
-22
@@ -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;"
|
||||
@@ -305,6 +324,11 @@ static QString appStyleSheet() {
|
||||
" border-radius: 8px;"
|
||||
" padding: 6px;"
|
||||
"}"
|
||||
// The popup's own margin (the shadow the platform draws around it) is
|
||||
// not part of this widget: it is filled from the application palette,
|
||||
// which is why appPalette() has to carry the same surface colour. Left
|
||||
// alone it is the desktop's default, i.e. a light band above and below
|
||||
// the menu on a light theme.
|
||||
"QMenu::item { padding: 7px 24px 7px 14px; border-radius: 6px; }"
|
||||
"QMenu::item:selected { background: #21384e; color: #38bdf8; }"
|
||||
"QMenu::item:disabled { color: #64748b; }"
|
||||
@@ -339,6 +363,44 @@ static QString appStyleSheet() {
|
||||
"}");
|
||||
}
|
||||
|
||||
// Colours the stylesheet cannot reach.
|
||||
//
|
||||
// A QMenu is a separate native popup: only its inner widget is drawn by the
|
||||
// stylesheet, while the margin the platform leaves around it — the shadow — is
|
||||
// filled from the application palette. On a light desktop theme that margin is
|
||||
// white, which shows up as a light band above and below the menu. Giving the
|
||||
// palette the window's own surface colour makes the whole popup one colour.
|
||||
//
|
||||
// The values repeat appStyleSheet()'s on purpose: a palette is a set of roles,
|
||||
// not CSS, and there is no way to point one at a stylesheet. They must be kept
|
||||
// in step with the token table in doc/interface.md.
|
||||
QPalette MainWindow::appPalette() {
|
||||
const QColor window(0x1e, 0x29, 0x3b); // surface
|
||||
const QColor raised(0x27, 0x34, 0x49); // raised surface
|
||||
const QColor text(0xe2, 0xe8, 0xf0); // text
|
||||
const QColor muted(0x94, 0xa3, 0xb8); // secondary text
|
||||
const QColor accent(0x38, 0xbd, 0xf8); // accent
|
||||
|
||||
// Qt 6 has no separate Menu role, and that is exactly the point: the margin
|
||||
// a QMenu popup is drawn with is filled from Window, so this is the colour
|
||||
// that removes the light band.
|
||||
QPalette palette;
|
||||
palette.setColor(QPalette::Window, window);
|
||||
palette.setColor(QPalette::WindowText, text);
|
||||
palette.setColor(QPalette::Base, raised);
|
||||
palette.setColor(QPalette::AlternateBase, window);
|
||||
palette.setColor(QPalette::Text, text);
|
||||
palette.setColor(QPalette::Button, raised);
|
||||
palette.setColor(QPalette::ButtonText, text);
|
||||
palette.setColor(QPalette::BrightText, Qt::white);
|
||||
palette.setColor(QPalette::ToolTipBase, raised);
|
||||
palette.setColor(QPalette::ToolTipText, text);
|
||||
palette.setColor(QPalette::Highlight, accent);
|
||||
palette.setColor(QPalette::HighlightedText, QColor(0x0f, 0x17, 0x2a));
|
||||
palette.setColor(QPalette::PlaceholderText, muted);
|
||||
return palette;
|
||||
}
|
||||
|
||||
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
|
||||
m_core = new AppCore(this);
|
||||
|
||||
@@ -353,6 +415,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();
|
||||
@@ -404,10 +475,6 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
|
||||
if (m_core->shouldCheckForAppUpdate()) {
|
||||
QTimer::singleShot(1500, this, &MainWindow::onCheckForUpdates);
|
||||
}
|
||||
|
||||
// Keep the login check's unit in sync with where this binary actually lives
|
||||
// (an update may have moved it). Silent and idempotent.
|
||||
m_core->ensureStartupAutostart();
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow() = default;
|
||||
@@ -439,8 +506,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/
|
||||
@@ -519,6 +587,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;
|
||||
};
|
||||
@@ -536,6 +605,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");
|
||||
// No entry for the settings screen: it is not a place to browse from, and
|
||||
// the menu bar is the one way in (see openSettingsPage).
|
||||
|
||||
connect(m_navGroup, &QButtonGroup::idClicked, this, &MainWindow::onNavChanged);
|
||||
m_navGroup->button(NavDashboard)->setChecked(true);
|
||||
@@ -625,6 +696,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) {
|
||||
@@ -664,6 +740,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)
|
||||
@@ -729,6 +806,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,
|
||||
&MainWindow::openSettingsPage);
|
||||
settingsMenu->addSeparator();
|
||||
|
||||
QActionGroup* credGroup = new QActionGroup(this);
|
||||
credGroup->setExclusive(true);
|
||||
|
||||
@@ -750,23 +833,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); });
|
||||
|
||||
// The login check: the core installs (or removes) the systemd user unit that
|
||||
// runs the headless pass, so the setting is what makes the feature exist on
|
||||
// the machine — nothing to configure by hand.
|
||||
settingsMenu->addSeparator();
|
||||
m_startupCheckAction = settingsMenu->addAction("Vérifier les mises à jour au démarrage");
|
||||
m_startupCheckAction->setCheckable(true);
|
||||
m_startupCheckAction->setChecked(m_core->checkUpdatesAtStartup());
|
||||
m_startupCheckAction->setToolTip(
|
||||
"Prévient par une notification à l'ouverture de session quand des mises à jour "
|
||||
"sont disponibles — sans mot de passe. Installe le service utilisateur associé.");
|
||||
connect(m_startupCheckAction, &QAction::toggled, this, [this](bool enabled) {
|
||||
m_core->setCheckUpdatesAtStartup(enabled);
|
||||
});
|
||||
[this]() { onCredentialModeRequested(true); });
|
||||
|
||||
QMenu* helpMenu = menuBar->addMenu("Aide");
|
||||
helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates);
|
||||
@@ -824,6 +893,8 @@ 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]() { openSettingsPage(); });
|
||||
bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() {
|
||||
LogManager::instance().logEvent(QStringLiteral("ui"),
|
||||
QStringLiteral("export de la liste affichée"));
|
||||
@@ -899,9 +970,36 @@ void MainWindow::onNavChanged(int id) {
|
||||
void MainWindow::onOpenPage(const QString& pageId) {
|
||||
const int navId = m_navIdByPage.value(pageId, -1);
|
||||
if (navId < 0) return;
|
||||
// The settings screen has no navigation button to click, so it is opened
|
||||
// directly; every other screen is reached by clicking its own button.
|
||||
if (pageId == QLatin1String("settings")) {
|
||||
openSettingsPage();
|
||||
return;
|
||||
}
|
||||
if (QAbstractButton* button = m_navGroup->button(navId)) button->click();
|
||||
}
|
||||
|
||||
// The settings screen is the one screen without a sidebar entry: it is not a
|
||||
// destination to browse from, so the Paramètres menu and Ctrl+, are the only
|
||||
// ways in. Everything a navigation button does for free — switching the stacked
|
||||
// widget, reloading, retitling, journalling — is done here instead.
|
||||
void MainWindow::openSettingsPage() {
|
||||
LogManager::instance().logEvent(QStringLiteral("ui"),
|
||||
QStringLiteral("navigation → paramètres"));
|
||||
|
||||
// Nothing stays selected in the sidebar: the settings screen is not one of
|
||||
// the places it lists, and leaving the previous entry highlighted would
|
||||
// point at the wrong screen. The group has to stop being exclusive first,
|
||||
// otherwise it puts one of its buttons back as soon as none is checked.
|
||||
m_navGroup->setExclusive(false);
|
||||
for (QAbstractButton* button : m_navGroup->buttons()) button->setChecked(false);
|
||||
m_navGroup->setExclusive(true);
|
||||
|
||||
m_pages->setCurrentWidget(m_settings);
|
||||
m_settings->refresh();
|
||||
updatePageTitle();
|
||||
}
|
||||
|
||||
// Navigates to the Installed screen and opens the package the user clicked in
|
||||
// the dashboard activity list.
|
||||
void MainWindow::onOpenPackage(const QString& name) {
|
||||
@@ -925,6 +1023,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()) {
|
||||
@@ -1081,6 +1180,85 @@ 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")},
|
||||
};
|
||||
|
||||
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() {
|
||||
|
||||
+11
-20
@@ -1,47 +1,38 @@
|
||||
#include <QApplication>
|
||||
#include <QCoreApplication>
|
||||
#include <QLoggingCategory>
|
||||
#include <QStringList>
|
||||
#include <QTimer>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "app-settings.h"
|
||||
#include "language-manager.h"
|
||||
#include "log-manager.h"
|
||||
#include "main-window.h"
|
||||
#include "startup-check.h"
|
||||
#include "update-manager.h"
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
// The login check runs headless, from the systemd user unit the app installs
|
||||
// itself (Paramètres → « Vérifier les mises à jour au démarrage »). It is
|
||||
// detected before any QApplication: that unit has no display, and building a
|
||||
// GUI application there would abort on the platform plugin.
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (std::strcmp(argv[i], "--check-updates") == 0) {
|
||||
QCoreApplication app(argc, argv);
|
||||
app.setApplicationName("PacManager");
|
||||
app.setApplicationVersion(UpdateManager::currentVersion());
|
||||
app.setOrganizationName("Freebuff");
|
||||
QLoggingCategory::setFilterRules(QStringLiteral("pacmgr.*=true"));
|
||||
LogManager::installQtMessageHandler();
|
||||
return StartupCheck().run();
|
||||
}
|
||||
}
|
||||
|
||||
QApplication app(argc, argv);
|
||||
app.setApplicationName("PacManager");
|
||||
app.setApplicationVersion(UpdateManager::currentVersion());
|
||||
app.setOrganizationName("Freebuff");
|
||||
// Before any widget exists: the palette is what the platform draws the
|
||||
// parts the stylesheet cannot reach, such as the margin around a menu.
|
||||
app.setPalette(MainWindow::appPalette());
|
||||
|
||||
// Every log category the app uses is enabled (qCDebug included) and funnelled
|
||||
// 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);
|
||||
|
||||
@@ -1,347 +0,0 @@
|
||||
#include "startup-check.h"
|
||||
#include "log-manager.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QProcess>
|
||||
#include <QStandardPaths>
|
||||
#include <QThread>
|
||||
#include <QtGlobal>
|
||||
|
||||
#include <initializer_list>
|
||||
|
||||
namespace {
|
||||
|
||||
// Package prefixes that make an update worth interrupting the user for. Kept
|
||||
// short and documented: widening it is a judgement call, not a bug fix.
|
||||
bool startsWithAny(const QString& name, std::initializer_list<const char*> prefixes) {
|
||||
for (const char* prefix : prefixes) {
|
||||
if (name.startsWith(QLatin1String(prefix))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool toolExists(const QString& program) {
|
||||
return !QStandardPaths::findExecutable(program).isEmpty();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
StartupCheck::StartupCheck(QObject* parent) : QObject(parent) {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
QStringList StartupCheck::parseUpdates(const QString& output) {
|
||||
QStringList packages;
|
||||
const QStringList lines = output.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
|
||||
|
||||
for (const QString& line : lines) {
|
||||
// "linux 6.9.1.arch1-1 -> 6.9.2.arch1-1" (checkupdates) and
|
||||
// "linux 6.9.2.arch1-1" (pacman -Qu) share the same head: the first
|
||||
// whitespace-separated token is the package name.
|
||||
const QStringList tokens = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
|
||||
if (tokens.isEmpty()) continue;
|
||||
packages << tokens.first();
|
||||
}
|
||||
|
||||
packages.removeDuplicates();
|
||||
return packages;
|
||||
}
|
||||
|
||||
bool StartupCheck::isCritical(const QString& package) {
|
||||
return startsWithAny(package, {
|
||||
"linux", // the kernel itself, its headers and its firmware
|
||||
"glibc", // everything links against it
|
||||
"systemd", // init and its libraries
|
||||
"mesa", // graphics stack: a broken update loses the session
|
||||
"nvidia", // out-of-tree driver built against the running kernel
|
||||
"xorg-server",
|
||||
"wayland",
|
||||
"pacman", // a broken pacman leaves no way to repair
|
||||
"openssl",
|
||||
});
|
||||
}
|
||||
|
||||
bool StartupCheck::isRebootRequired(const QString& package) {
|
||||
// Only the kernel (and its firmware, which "linux" also covers) plus the
|
||||
// out-of-tree graphics driver built against the running kernel leave the
|
||||
// system on the old code until it restarts.
|
||||
return startsWithAny(package, {"linux", "nvidia"});
|
||||
}
|
||||
|
||||
QStringList StartupCheck::criticalPackages(const QStringList& packages) {
|
||||
QStringList critical;
|
||||
for (const QString& package : packages) {
|
||||
if (isCritical(package)) critical << package;
|
||||
}
|
||||
return critical;
|
||||
}
|
||||
|
||||
QString StartupCheck::notificationTitle(const Result& result) {
|
||||
if (result.rebootRequired) return QStringLiteral("Mise à jour du noyau disponible");
|
||||
if (result.anyCritical) return QStringLiteral("Mises à jour importantes disponibles");
|
||||
return QStringLiteral("Mises à jour disponibles");
|
||||
}
|
||||
|
||||
QString StartupCheck::notificationBody(const Result& result) {
|
||||
const int count = result.updateCount;
|
||||
QString body = count == 1 ? QStringLiteral("1 mise à jour disponible.")
|
||||
: QStringLiteral("%1 mises à jour disponibles.").arg(count);
|
||||
|
||||
// Name the critical packages, but keep the bubble readable: a system with a
|
||||
// pending toolchain refresh can have a dozen of them.
|
||||
const QStringList critical = criticalPackages(result.packages);
|
||||
if (!critical.isEmpty()) {
|
||||
const int shown = qMin(critical.size(), 5);
|
||||
QStringList listed = critical.mid(0, shown);
|
||||
if (critical.size() > shown) listed << QStringLiteral("…");
|
||||
body += QStringLiteral("\nPaquets sensibles : %1.").arg(listed.join(QStringLiteral(", ")));
|
||||
}
|
||||
|
||||
body += result.rebootRequired
|
||||
? QStringLiteral("\nUn redémarrage sera nécessaire après l'installation.")
|
||||
: QStringLiteral("\nOuvrez PacManager pour les installer.");
|
||||
return body;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Check
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
QString StartupCheck::runTool(const QString& program, const QStringList& args,
|
||||
int timeoutMs, int* exitCode, QString* stderrText) {
|
||||
if (exitCode) *exitCode = -1;
|
||||
if (stderrText) stderrText->clear();
|
||||
|
||||
QProcess process;
|
||||
// Separate channels: stdout is the package list, stderr is diagnostics. A
|
||||
// merged stream would turn "warning: database file..." into a package name.
|
||||
process.setProcessChannelMode(QProcess::SeparateChannels);
|
||||
process.start(program, args);
|
||||
if (!process.waitForStarted(5000)) return {};
|
||||
|
||||
const bool finished = process.waitForFinished(timeoutMs);
|
||||
if (!finished) {
|
||||
process.kill();
|
||||
process.waitForFinished(2000);
|
||||
}
|
||||
|
||||
const QString out = QString::fromUtf8(process.readAllStandardOutput());
|
||||
if (stderrText) *stderrText = QString::fromUtf8(process.readAllStandardError()).trimmed();
|
||||
if (exitCode) *exitCode = finished ? process.exitCode() : -1;
|
||||
return out;
|
||||
}
|
||||
|
||||
StartupCheck::Result StartupCheck::check() {
|
||||
Result result;
|
||||
|
||||
QString output;
|
||||
QString stderrText;
|
||||
int code = 0;
|
||||
|
||||
if (toolExists(QStringLiteral("checkupdates"))) {
|
||||
// checkupdates refreshes a throwaway copy of the databases, so it needs
|
||||
// no root and cannot leave the real database half-synced. It exits 0
|
||||
// with updates, 2 when there is nothing to do, and anything else on a
|
||||
// real failure (no network, broken database...).
|
||||
output = runTool(QStringLiteral("checkupdates"), {}, 120000, &code, &stderrText);
|
||||
if (code != 0 && code != 2) {
|
||||
result.error = stderrText.isEmpty()
|
||||
? QStringLiteral("checkupdates a échoué (code %1).").arg(code)
|
||||
: QStringLiteral("checkupdates a échoué (code %1) : %2")
|
||||
.arg(code).arg(stderrText);
|
||||
return result;
|
||||
}
|
||||
} else if (toolExists(QStringLiteral("pacman"))) {
|
||||
// Fallback: read the already-synced database. It needs no root either,
|
||||
// but it only knows what the last `pacman -Sy` saw, so it can miss
|
||||
// updates — which `error` records rather than hiding.
|
||||
output = runTool(QStringLiteral("pacman"), {QStringLiteral("-Qu")}, 30000, &code,
|
||||
&stderrText);
|
||||
// pacman -Qu exits 1 when nothing matches (= no update at all).
|
||||
if (code != 0 && code != 1) {
|
||||
result.error = stderrText.isEmpty()
|
||||
? QStringLiteral("pacman -Qu a échoué (code %1).").arg(code)
|
||||
: QStringLiteral("pacman -Qu a échoué (code %1) : %2").arg(code).arg(stderrText);
|
||||
return result;
|
||||
}
|
||||
result.error = QStringLiteral(
|
||||
"checkupdates est absent (paquet pacman-contrib) : les mises à jour "
|
||||
"peuvent être manquées tant que la base n'est pas synchronisée.");
|
||||
} else {
|
||||
result.error = QStringLiteral("Ni checkupdates ni pacman n'est disponible.");
|
||||
return result;
|
||||
}
|
||||
|
||||
result.packages = parseUpdates(output);
|
||||
result.updateCount = result.packages.size();
|
||||
for (const QString& package : result.packages) {
|
||||
result.anyCritical = result.anyCritical || isCritical(package);
|
||||
result.rebootRequired = result.rebootRequired || isRebootRequired(package);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
int StartupCheck::run() {
|
||||
const Result result = check();
|
||||
|
||||
if (!result.error.isEmpty()) {
|
||||
LogManager::instance().logEvent(QStringLiteral("maj-verif"), result.error);
|
||||
}
|
||||
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("maj-verif"),
|
||||
result.updateCount == 0
|
||||
? QStringLiteral("aucune mise à jour en attente")
|
||||
: QStringLiteral("%1 mise(s) à jour en attente : %2")
|
||||
.arg(result.updateCount)
|
||||
.arg(result.packages.join(QStringLiteral(", "))));
|
||||
|
||||
if (result.updateCount > 0) {
|
||||
notify(result);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Notification
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
bool StartupCheck::sendNotification(const QString& title, const QString& body, bool urgent) {
|
||||
if (!toolExists(QStringLiteral("notify-send"))) return false;
|
||||
|
||||
QStringList args{QStringLiteral("-a"), QStringLiteral("PacManager")};
|
||||
if (urgent) {
|
||||
// A critical notification that never times out: the user should not be
|
||||
// able to miss a pending kernel update.
|
||||
args << QStringLiteral("-u") << QStringLiteral("critical")
|
||||
<< QStringLiteral("-t") << QStringLiteral("0");
|
||||
} else {
|
||||
args << QStringLiteral("-t") << QStringLiteral("10000");
|
||||
}
|
||||
args << title << body;
|
||||
|
||||
// A login unit can beat the notification daemon (mako, dunst...) to the
|
||||
// session bus, in which case the first sends fail. Retry for a few seconds
|
||||
// instead of dropping the notification silently.
|
||||
for (int attempt = 0; attempt < 30; ++attempt) {
|
||||
QProcess process;
|
||||
process.start(QStringLiteral("notify-send"), args);
|
||||
if (process.waitForStarted(3000) && process.waitForFinished(5000) &&
|
||||
process.exitCode() == 0) {
|
||||
return true;
|
||||
}
|
||||
QThread::msleep(1000);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool StartupCheck::notify(const Result& result) {
|
||||
if (result.updateCount <= 0) return false;
|
||||
|
||||
const bool urgent = result.rebootRequired || result.anyCritical;
|
||||
const bool sent = sendNotification(notificationTitle(result),
|
||||
notificationBody(result), urgent);
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("maj-verif"),
|
||||
sent ? QStringLiteral("notification envoyée")
|
||||
: QStringLiteral("notification impossible (aucun démon de notification)"));
|
||||
return sent;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Autostart
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
QString StartupCheck::autostartUnitPath(const QString& configDir) {
|
||||
if (configDir.isEmpty()) return {};
|
||||
return configDir + QStringLiteral("/systemd/user/pacmanager-check-updates.service");
|
||||
}
|
||||
|
||||
QString StartupCheck::autostartWantsPath(const QString& configDir) {
|
||||
if (configDir.isEmpty()) return {};
|
||||
return configDir +
|
||||
QStringLiteral("/systemd/user/default.target.wants/pacmanager-check-updates.service");
|
||||
}
|
||||
|
||||
bool StartupCheck::installAutostart(const QString& configDir, const QString& program,
|
||||
QString* error) {
|
||||
if (configDir.isEmpty() || program.isEmpty()) {
|
||||
if (error) *error = QStringLiteral("répertoire de configuration ou programme manquant.");
|
||||
return false;
|
||||
}
|
||||
|
||||
const QString unitPath = autostartUnitPath(configDir);
|
||||
const QString wantsPath = autostartWantsPath(configDir);
|
||||
|
||||
if (!QDir().mkpath(QFileInfo(unitPath).absolutePath()) ||
|
||||
!QDir().mkpath(QFileInfo(wantsPath).absolutePath())) {
|
||||
if (error) *error = QStringLiteral("impossible de créer %1").arg(configDir);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Quoted because a path may contain spaces; systemd accepts the quotes.
|
||||
const QString unit = QStringLiteral(
|
||||
"[Unit]\n"
|
||||
"Description=PacManager — mises à jour disponibles au démarrage\n"
|
||||
"Documentation=man:PacManager(1)\n"
|
||||
"After=network-online.target\n"
|
||||
"Wants=network-online.target\n"
|
||||
"\n"
|
||||
"[Service]\n"
|
||||
"Type=oneshot\n"
|
||||
"ExecStart=\"%1\" --check-updates\n"
|
||||
"\n"
|
||||
"[Install]\n"
|
||||
"WantedBy=default.target\n").arg(program);
|
||||
|
||||
QFile file(unitPath);
|
||||
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate) ||
|
||||
file.write(unit.toUtf8()) != unit.toUtf8().size()) {
|
||||
if (error) *error = QStringLiteral("impossible d'écrire %1").arg(unitPath);
|
||||
return false;
|
||||
}
|
||||
file.close();
|
||||
|
||||
// The symlink is what `systemctl --user enable` would create; writing it
|
||||
// directly keeps the install free of any systemd call.
|
||||
QFile::remove(wantsPath);
|
||||
if (!QFile::link(unitPath, wantsPath)) {
|
||||
if (error) *error = QStringLiteral("impossible de créer le lien %1").arg(wantsPath);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool StartupCheck::removeAutostart(const QString& configDir, QString* error) {
|
||||
if (configDir.isEmpty()) {
|
||||
if (error) *error = QStringLiteral("répertoire de configuration manquant.");
|
||||
return false;
|
||||
}
|
||||
|
||||
QFile::remove(autostartWantsPath(configDir));
|
||||
QFile::remove(autostartUnitPath(configDir));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool StartupCheck::autostartEnabled(const QString& configDir) {
|
||||
const QString wantsPath = autostartWantsPath(configDir);
|
||||
if (wantsPath.isEmpty()) return false;
|
||||
const QFileInfo info(wantsPath);
|
||||
// A symlink whose target is missing would report exists() == false, so the
|
||||
// link itself is checked too: a stale link is still an installed setting.
|
||||
return info.isSymLink() || info.exists();
|
||||
}
|
||||
|
||||
bool StartupCheck::reloadUserManager() {
|
||||
if (!toolExists(QStringLiteral("systemctl"))) return false;
|
||||
|
||||
QProcess process;
|
||||
process.start(QStringLiteral("systemctl"),
|
||||
{QStringLiteral("--user"), QStringLiteral("daemon-reload")});
|
||||
if (!process.waitForStarted(3000)) return false;
|
||||
return process.waitForFinished(10000) && process.exitCode() == 0;
|
||||
}
|
||||
@@ -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,206 +0,0 @@
|
||||
// Unit tests for StartupCheck: parsing of the two update-check formats, the
|
||||
// critical / reboot-required classification, the notification text, and the
|
||||
// autostart unit — the last one written inside a temporary directory, never the
|
||||
// user's own ~/.config.
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QString>
|
||||
#include <QTemporaryDir>
|
||||
|
||||
#include "startup-check.h"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// parseUpdates
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static void testParseUpdates_checkupdatesFormat() {
|
||||
// What `checkupdates` prints: name, current version, "->", new version.
|
||||
const QString output =
|
||||
"linux 6.9.1.arch1-1 -> 6.9.2.arch1-1\n"
|
||||
"firefox 127.0-1 -> 128.0-1\n";
|
||||
const QStringList packages = StartupCheck::parseUpdates(output);
|
||||
assert(packages.size() == 2);
|
||||
assert(packages.at(0) == "linux");
|
||||
assert(packages.at(1) == "firefox");
|
||||
}
|
||||
|
||||
static void testParseUpdates_pacmanFormat() {
|
||||
// What `pacman -Qu` prints: name then the *new* version, no arrow.
|
||||
const QString output = "glibc 2.39-3\nvlc 3.0.21-1\n";
|
||||
const QStringList packages = StartupCheck::parseUpdates(output);
|
||||
assert(packages.size() == 2);
|
||||
assert(packages.at(0) == "glibc");
|
||||
assert(packages.at(1) == "vlc");
|
||||
}
|
||||
|
||||
static void testParseUpdates_ignoresBlanksAndDuplicates() {
|
||||
const QString output = "\n\nlinux 6.9-1\n\nlinux 6.9-1\n";
|
||||
const QStringList packages = StartupCheck::parseUpdates(output);
|
||||
assert(packages.size() == 1);
|
||||
assert(packages.at(0) == "linux");
|
||||
}
|
||||
|
||||
static void testParseUpdates_emptyOutput() {
|
||||
assert(StartupCheck::parseUpdates(QString()).isEmpty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Classification
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static void testIsCritical_kernelAndCorePackages() {
|
||||
assert(StartupCheck::isCritical("linux"));
|
||||
assert(StartupCheck::isCritical("linux-lts"));
|
||||
assert(StartupCheck::isCritical("linux-firmware"));
|
||||
assert(StartupCheck::isCritical("glibc"));
|
||||
assert(StartupCheck::isCritical("systemd"));
|
||||
assert(StartupCheck::isCritical("systemd-libs"));
|
||||
assert(StartupCheck::isCritical("mesa"));
|
||||
assert(StartupCheck::isCritical("nvidia-utils"));
|
||||
assert(StartupCheck::isCritical("pacman"));
|
||||
assert(StartupCheck::isCritical("openssl"));
|
||||
}
|
||||
|
||||
static void testIsCritical_ordinaryPackages() {
|
||||
assert(!StartupCheck::isCritical("firefox"));
|
||||
assert(!StartupCheck::isCritical("vlc"));
|
||||
assert(!StartupCheck::isCritical("gimp"));
|
||||
assert(!StartupCheck::isCritical("git"));
|
||||
assert(!StartupCheck::isCritical("python"));
|
||||
}
|
||||
|
||||
static void testIsRebootRequired_onlyKernelAndDrivers() {
|
||||
assert(StartupCheck::isRebootRequired("linux"));
|
||||
assert(StartupCheck::isRebootRequired("linux-firmware"));
|
||||
assert(StartupCheck::isRebootRequired("nvidia-utils"));
|
||||
// Critical because they can break the session, but they take effect on the
|
||||
// spot: no reboot to ask for.
|
||||
assert(!StartupCheck::isRebootRequired("glibc"));
|
||||
assert(!StartupCheck::isRebootRequired("mesa"));
|
||||
assert(!StartupCheck::isRebootRequired("firefox"));
|
||||
}
|
||||
|
||||
static void testCriticalPackages_returnsOnlyTheMatchingOnes() {
|
||||
const QStringList all{"firefox", "linux", "vlc", "glibc"};
|
||||
const QStringList critical = StartupCheck::criticalPackages(all);
|
||||
assert(critical.size() == 2);
|
||||
assert(critical.at(0) == "linux");
|
||||
assert(critical.at(1) == "glibc");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Notification text
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static void testNotification_kernelUpdateIsUrgent() {
|
||||
StartupCheck::Result result;
|
||||
result.packages = {"linux", "glibc", "firefox"};
|
||||
result.updateCount = 3;
|
||||
result.anyCritical = true;
|
||||
result.rebootRequired = true;
|
||||
|
||||
assert(StartupCheck::notificationTitle(result) == "Mise à jour du noyau disponible");
|
||||
const QString body = StartupCheck::notificationBody(result);
|
||||
assert(body.contains("3 mises à jour"));
|
||||
assert(body.contains("linux, glibc"));
|
||||
assert(body.contains("redémarrage"));
|
||||
}
|
||||
|
||||
static void testNotification_ordinaryUpdate() {
|
||||
StartupCheck::Result result;
|
||||
result.packages = {"firefox"};
|
||||
result.updateCount = 1;
|
||||
|
||||
assert(StartupCheck::notificationTitle(result) == "Mises à jour disponibles");
|
||||
const QString body = StartupCheck::notificationBody(result);
|
||||
assert(body.contains("1 mise à jour disponible"));
|
||||
assert(body.contains("Ouvrez PacManager"));
|
||||
assert(!body.contains("redémarrage"));
|
||||
}
|
||||
|
||||
static void testNotification_capsTheCriticalPackageList() {
|
||||
// Eight critical packages must not turn the bubble into a wall of text.
|
||||
StartupCheck::Result result;
|
||||
result.packages = {"linux", "linux-lts", "linux-zen", "linux-hardened",
|
||||
"linux-firmware", "glibc", "systemd", "mesa"};
|
||||
result.updateCount = 8;
|
||||
result.anyCritical = true;
|
||||
result.rebootRequired = true;
|
||||
|
||||
const QString body = StartupCheck::notificationBody(result);
|
||||
assert(body.contains("…"));
|
||||
assert(!body.contains("mesa"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Autostart files
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static void testAutostart_installEnableAndRemove() {
|
||||
QTemporaryDir dir;
|
||||
assert(dir.isValid());
|
||||
const QString configDir = dir.path();
|
||||
// A space in the path checks the quoting systemd needs.
|
||||
const QString program = "/opt/Pac Manager/PacManager";
|
||||
|
||||
assert(!StartupCheck::autostartEnabled(configDir));
|
||||
|
||||
QString error;
|
||||
assert(StartupCheck::installAutostart(configDir, program, &error));
|
||||
assert(error.isEmpty());
|
||||
assert(StartupCheck::autostartEnabled(configDir));
|
||||
|
||||
QFile unit(StartupCheck::autostartUnitPath(configDir));
|
||||
assert(unit.open(QIODevice::ReadOnly));
|
||||
const QString content = QString::fromUtf8(unit.readAll());
|
||||
unit.close();
|
||||
assert(content.contains("\"/opt/Pac Manager/PacManager\" --check-updates"));
|
||||
assert(content.contains("WantedBy=default.target"));
|
||||
assert(content.contains("Type=oneshot"));
|
||||
|
||||
// The enabling link points back at the unit, which is what makes the login
|
||||
// manager start it.
|
||||
const QFileInfo link(StartupCheck::autostartWantsPath(configDir));
|
||||
assert(link.isSymLink());
|
||||
|
||||
assert(StartupCheck::removeAutostart(configDir, &error));
|
||||
assert(!StartupCheck::autostartEnabled(configDir));
|
||||
assert(!QFile::exists(StartupCheck::autostartUnitPath(configDir)));
|
||||
assert(!QFileInfo::exists(StartupCheck::autostartWantsPath(configDir)));
|
||||
}
|
||||
|
||||
static void testAutostart_refusesEmptyInputs() {
|
||||
assert(StartupCheck::autostartUnitPath(QString()).isEmpty());
|
||||
assert(StartupCheck::autostartWantsPath(QString()).isEmpty());
|
||||
|
||||
QString error;
|
||||
assert(!StartupCheck::installAutostart(QString(), "/usr/bin/PacManager", &error));
|
||||
assert(!error.isEmpty());
|
||||
assert(!StartupCheck::installAutostart("/tmp/does-not-matter", QString(), &error));
|
||||
assert(!StartupCheck::autostartEnabled(QString()));
|
||||
}
|
||||
|
||||
int main() {
|
||||
testParseUpdates_checkupdatesFormat();
|
||||
testParseUpdates_pacmanFormat();
|
||||
testParseUpdates_ignoresBlanksAndDuplicates();
|
||||
testParseUpdates_emptyOutput();
|
||||
|
||||
testIsCritical_kernelAndCorePackages();
|
||||
testIsCritical_ordinaryPackages();
|
||||
testIsRebootRequired_onlyKernelAndDrivers();
|
||||
testCriticalPackages_returnsOnlyTheMatchingOnes();
|
||||
|
||||
testNotification_kernelUpdateIsUrgent();
|
||||
testNotification_ordinaryUpdate();
|
||||
testNotification_capsTheCriticalPackageList();
|
||||
|
||||
testAutostart_installEnableAndRemove();
|
||||
testAutostart_refusesEmptyInputs();
|
||||
|
||||
std::cout << "All startup-check tests passed." << std::endl;
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user