From aff959bc4b9c459c0d44e3afdeed1dee459d8af3 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Mon, 28 Sep 2026 20:44:21 +0200 Subject: [PATCH] feat(settings): add a dedicated screen for every user preference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The preferences used to be spread across a menu entry and hardcoded paths, so the user could not see them, let alone change them: where the journal goes, whether a dropped Flatpak file is accepted, and when the app checks its own version were all decided in code. They now live in AppSettings, one model the rest of the app already reads, and the new Settings screen only writes to it. Nothing keeps a second copy of a value, so a change is visible everywhere at once — switching directory moves the journal, unchecking drag & drop makes the window refuse the drop, blocking the update has the manual check say why instead of silently doing nothing. The update block is deliberately limited to PacManager itself: blocking a system package update is a decision the app has no business making. The language setting installs a Qt catalogue and asks every widget to retranslate. The interface is still written in French with QStringLiteral, so no catalogue ships yet; a language with none is shown in the list but disabled rather than silently doing nothing, and Qt Linguist stays optional so the build does not depend on it. --- CMakeLists.txt | 43 ++- README.en.md | 1 + README.md | 1 + doc/architecture.md | 28 +- doc/depannage.md | 27 +- doc/interface.md | 59 +++- doc/mise-a-jour.md | 5 + doc/tests.md | 5 + include/app-core.h | 12 + include/app-settings.h | 111 +++++++ include/language-manager.h | 45 +++ include/log-manager.h | 20 +- include/main-window.h | 24 ++ pages/page.h | 5 + pages/settings-page.cpp | 517 +++++++++++++++++++++++++++++++++ pages/settings-page.h | 91 ++++++ resources/icons/check-dark.svg | 3 + resources/icons/settings.svg | 4 + resources/resources.qrc | 2 + src/app-core.cpp | 27 ++ src/app-settings.cpp | 242 +++++++++++++++ src/language-manager.cpp | 111 +++++++ src/log-manager.cpp | 91 +++++- src/main-window.cpp | 144 ++++++++- src/main.cpp | 8 + tests/app-settings.test.cpp | 305 +++++++++++++++++++ version | 2 +- 27 files changed, 1906 insertions(+), 27 deletions(-) create mode 100644 include/app-settings.h create mode 100644 include/language-manager.h create mode 100644 pages/settings-page.cpp create mode 100644 pages/settings-page.h create mode 100644 resources/icons/check-dark.svg create mode 100644 resources/icons/settings.svg create mode 100644 src/app-settings.cpp create mode 100644 src/language-manager.cpp create mode 100644 tests/app-settings.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index a2c7be3..7efcf3c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,6 +32,8 @@ set(SOURCES src/package-model.cpp src/update-manager.cpp src/app-logging.cpp + src/app-settings.cpp + src/language-manager.cpp # Logic layer: background workers, the plugin shop and the controller the # screens delegate to. src/workers.cpp @@ -47,6 +49,7 @@ set(SOURCES src/log-manager.cpp pages/logs-page.cpp pages/plugins-page.cpp + pages/settings-page.cpp resources/resources.qrc ) @@ -60,6 +63,8 @@ set(HEADERS include/package-model.h include/update-manager.h include/app-logging.h + include/app-settings.h + include/language-manager.h include/workers.h include/progress-tracker.h include/plugin-shop.h @@ -73,6 +78,7 @@ set(HEADERS pages/history-page.h pages/logs-page.h pages/plugins-page.h + pages/settings-page.h ) add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) @@ -189,15 +195,48 @@ add_executable(app-core-test tests/app-core.test.cpp src/app-core.cpp src/workers.cpp src/pacman-manager.cpp src/plugin-manager.cpp src/history-manager.cpp src/update-manager.cpp src/plugin-shop.cpp - src/app-logging.cpp src/log-manager.cpp + src/app-logging.cpp src/log-manager.cpp src/app-settings.cpp include/app-core.h include/workers.h include/update-manager.h - include/plugin-shop.h include/log-manager.h) + include/plugin-shop.h include/log-manager.h include/app-settings.h) target_include_directories(app-core-test PRIVATE include) target_link_libraries(app-core-test PRIVATE Qt6::Core Qt6::Network) target_compile_definitions(app-core-test PRIVATE FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}") add_test(NAME app-core-test COMMAND app-core-test) +# AppSettings: the whole preferences model, exercised against a temporary +# settings file. The static policy (what a block lasts, when it is in force, what +# a cap or a directory is worth) is pure and needs no clock. +add_executable(app-settings-test tests/app-settings.test.cpp + src/app-settings.cpp src/log-manager.cpp include/app-settings.h + include/log-manager.h) +target_include_directories(app-settings-test PRIVATE include) +target_link_libraries(app-settings-test PRIVATE Qt6::Core) +add_test(NAME app-settings-test COMMAND app-settings-test) + +# ---- Translations ---- +# +# The language setting loads Qt catalogues named pacmanager_.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 + $/translations + COMMAND ${CMAKE_COMMAND} -E copy + ${PACMANAGER_QM_FILES} + $/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) diff --git a/README.en.md b/README.en.md index d1a75b6..af13472 100644 --- a/README.en.md +++ b/README.en.md @@ -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 diff --git a/README.md b/README.md index 45ffd38..26eeb5a 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/doc/architecture.md b/doc/architecture.md index ce4627e..cd48b2e 100644 --- a/doc/architecture.md +++ b/doc/architecture.md @@ -139,7 +139,33 @@ refusĂ©e tant que la premiĂšre tourne. Voir [operations.md](operations.md). | Une nouvelle opĂ©ration | Une mĂ©thode dans `AppCore` qui construit une `Request` et appelle `startRequest()` ; un `InstallWorker::Op` ; sa ligne dans `startMessage()`, `successMessage()`, `failureMessage()`. | | Une nouvelle liste | Une valeur dans `AppCore::ListMode`, un mode dans `ListWorker`, un slot dans `listFinished`. | | Un nouveau provider | Un plugin externe (voir [plugins.md](plugins.md)) — jamais une modification du cƓur. | -| Un nouveau rĂ©glage | `QSettings` (organisation `Freebuff`, application `PacManager`), comme `credentials/mode` ou `plugins//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//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 diff --git a/doc/depannage.md b/doc/depannage.md index e052d8f..d1cc702 100644 --- a/doc/depannage.md +++ b/doc/depannage.md @@ -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 diff --git a/doc/interface.md b/doc/interface.md index 7167bf9..ad34784 100644 --- a/doc/interface.md +++ b/doc/interface.md @@ -15,6 +15,7 @@ Chaque entrĂ©e correspond Ă  un Ă©cran de `pages/` (ou Ă  un mode d'un Ă©cran). | 📋 Historique | `history-page` | Toutes les actions, filtrables, export CSV. | | 📜 Logs | `logs-page` | `/var/log/pacman.log`, avec filtre instantanĂ©. | | đŸ§© Plugins | `plugins-page` | Plugins installĂ©s (activation, rechargement, installation de l'outil manquant) **et magasin** (voir [magasin-de-plugins.md](magasin-de-plugins.md)). | +| ⚙ ParamĂštres | `settings-page` | Toutes les prĂ©fĂ©rences (voir [Les paramĂštres](#les-paramĂštres)). | Trois de ces entrĂ©es (Recherche, InstallĂ©s, Mises Ă  jour) partagent le mĂȘme Ă©cran : `BrowsePage` change de mode et donc de requĂȘte derriĂšre, ce qui Ă©vite de @@ -28,8 +29,8 @@ dupliquer la table et le panneau de dĂ©tails. paquets affichĂ©s, actions enregistrĂ©es) et la barre de progression de l'opĂ©ration en cours (voir [operations.md](operations.md)). - **Menus** : Fichier (exports, quitter), Outils (naviguer, rafraĂźchir), - ParamĂštres (mode d'identification sudo), Aide (vĂ©rifier les mises Ă  jour, - Ă  propos). + ParamĂštres (ouverture de l'Ă©cran, mode d'identification sudo), Aide + (vĂ©rifier les mises Ă  jour, Ă  propos). - **Tray** : icĂŽne de notification quand le bureau en fournit une, avec accĂšs direct aux mises Ă  jour en attente. @@ -74,6 +75,55 @@ La cible que le fournisseur a donnĂ©e Ă  chaque copie (« user:
/master ») ne jamais Ă  l'Ă©cran : elle est conservĂ©e Ă  cĂŽtĂ© du libellĂ© et rendue telle quelle au fournisseur, qui est le seul Ă  savoir la lire. +## Les paramĂštres + +L'Ă©cran **ParamĂštres** regroupe tout ce que l'utilisateur peut changer. Chaque +carte Ă©crit dans le modĂšle que le reste de l'application lit dĂ©jĂ  +(`AppSettings`, et le mode d'identification que `AppCore` possĂšde dĂ©jĂ ) : il n'y +a pas de copie de la valeur dans l'Ă©cran, et un changement s'applique **immĂ©diatement**, +sans redĂ©marrage. + +| Carte | RĂ©glage | Effet | +| --- | --- | --- | +| Mot de passe administrateur | À chaque opĂ©ration / une fois au lancement | Passe par `AppCore::setCredentialMode()`. Demander maintenant, c'est le cadre qui possĂšde la boĂźte de dialogue : l'Ă©cran Ă©met `credentialModeRequested` et le cadre applique le mode (et met la case Ă  cocher du menu en accord). | +| Journal | Dossier, taille maximale | `LogManager` Ă©crit dans le dossier choisi. Changer de dossier **dĂ©place** le journal existant, et la limite fait tourner le fichier (`operations.log.1` conserve la version prĂ©cĂ©dente). Un dossier illisible retombe sur celui par dĂ©faut plutĂŽt que de laisser l'application sans log. | +| Glisser-dĂ©poser | Accepter / refuser les fichiers Flatpak | Le dĂ©pĂŽt est refusĂ© par la fenĂȘtre. « Ouvrir avec PacManager » continue de fonctionner : ce sont deux chemins d'entrĂ©e distincts. | +| Langue | SystĂšme / Français / English | Voir [La langue](#la-langue). | +| Mises Ă  jour de PacManager | VĂ©rification automatique, blocage | Voir [Bloquer les mises Ă  jour](#bloquer-les-mises-Ă -jour). | + +### La langue + +L'application ne contient pas de catalogue : l'interface est Ă©crite en français +avec `QStringLiteral`. Le rĂ©glage installe le catalogue Qt correspondant +(`translations/pacmanager_.qm`), cherchĂ© dans cet ordre : + +1. `/translations` — celui que l'utilisateur vient de choisir ; +2. `~/.local/share/PacManager/translations` ; +3. `translations/` Ă  cĂŽtĂ© de l'exĂ©cutable (arbre de compilation). + +Le changement est **immĂ©diat** : `LanguageManager::apply()` retire l'ancien +traducteur, installe le nouveau et envoie `QEvent::LanguageChange` Ă  tous les +widgets, ce qui fait que `MainWindow::changeEvent()` rappelle ses propres libellĂ©s +et que chaque Ă©cran rĂ©affiche ses titres. Une langue sans catalogue est affichĂ©e dans +la liste mais **dĂ©sactivĂ©e** (infobulle « traduction non installĂ©e ») : choisir +une langue qui ne ferait rien serait pire que de le dire. + +CMake compile `translations/*.ts` en `.qm` **seulement si Qt Linguist est +installĂ©** (`Qt6::LinguistTools`) : sans lui, l'application dĂ©marre simplement +non traduite. Fournir les catalogues est un travail de traduction Ă  part. + +### Bloquer les mises Ă  jour + +Deux rĂ©glages, tous deux limitĂ©s Ă  **PacManager lui-mĂȘme** — les mises Ă  jour des +paquets systĂšme ne sont jamais bloquĂ©es : + +- **vĂ©rification automatique** : la recherche de version au lancement, dĂ©jĂ  + limitĂ©e Ă  une fois par jour ; +- **blocage** : 1 heure, 24 heures, 7 jours, ou jusqu'Ă  annulation. Tant qu'il + est actif, `AppCore::checkForAppUpdate()` refuse et dit pourquoi dans la barre + de statut — y compris quand l'action vient du menu Aide. L'Ă©chĂ©ance est + conservĂ©e : un blocage expirĂ© ne bloque plus. + ## Raccourcis clavier | Raccourci | Effet | @@ -82,6 +132,7 @@ fournisseur, qui est le seul Ă  savoir la lire. | `Ctrl+R` / `F5` | RafraĂźchir les bases de donnĂ©es (`pacman -Sy`). | | `Ctrl+U` | Ouvrir la liste des mises Ă  jour. | | `Ctrl+E` | Exporter la liste affichĂ©e en CSV. | +| `Ctrl+,` | Ouvrir les ParamĂštres. | | `Ctrl+Q` | Quitter. | ## Le thĂšme @@ -144,3 +195,7 @@ de style ne fait que fixer la couleur du texte. | Un badge, une pastille, un compteur | `pages/ui-kit.cpp`. | | Une couleur de statut dans une table | La page concernĂ©e (`QTableWidgetItem::setForeground`). | | Une icĂŽne | `resources/icons/*.svg` (le trait suit la couleur du texte). | + +L'Ă©cran ParamĂštres ajoute deux rĂšgles (`QScrollArea`, `QLabel#settingHint`, +`QCheckBox`) : elles sont dans `appStyleSheet()` comme le reste, pas dans le +fichier d'Ă©cran. diff --git a/doc/mise-a-jour.md b/doc/mise-a-jour.md index 369621f..84c9a63 100644 --- a/doc/mise-a-jour.md +++ b/doc/mise-a-jour.md @@ -4,6 +4,11 @@ PacManager se met Ă  jour lui-mĂȘme : au lancement puis une fois par jour, il interroge la derniĂšre release du dĂ©pĂŽt et propose de l'installer. Toute la logique est dans `include/update-manager.h` / `src/update-manager.cpp`. +L'utilisateur peut couper ce contrĂŽle, et le suspendre pour un temps, depuis +l'Ă©cran **ParamĂštres → Mises Ă  jour de PacManager** (voir +[interface.md](interface.md)). Ces deux rĂ©glages ne concernent que PacManager : +les mises Ă  jour des paquets du systĂšme ne sont jamais bloquĂ©es. + ## La version Le fichier `version` Ă  la racine du dĂ©pĂŽt est la **source unique de vĂ©ritĂ©** : diff --git a/doc/tests.md b/doc/tests.md index ab5dbe3..25258a4 100644 --- a/doc/tests.md +++ b/doc/tests.md @@ -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`. diff --git a/include/app-core.h b/include/app-core.h index 3c1ed0b..ebf96ad 100644 --- a/include/app-core.h +++ b/include/app-core.h @@ -10,6 +10,7 @@ #include #include +#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 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; diff --git a/include/app-settings.h b/include/app-settings.h new file mode 100644 index 0000000..3a5bb57 --- /dev/null +++ b/include/app-settings.h @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include + +// 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; +}; diff --git a/include/language-manager.h b/include/language-manager.h new file mode 100644 index 0000000..9429a6e --- /dev/null +++ b/include/language-manager.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +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_.qm" in, in order: +// +// 1. /translations (user's own, survives an update); +// 2. /translations (next to the config); +// 3. /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(); +}; diff --git a/include/log-manager.h b/include/log-manager.h index 8978a8b..b352867 100644 --- a/include/log-manager.h +++ b/include/log-manager.h @@ -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; diff --git a/include/main-window.h b/include/main-window.h index a0ee3e2..b766221 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -33,6 +33,7 @@ class HistoryPage; class LogsPage; class Page; class PluginsPage; +class SettingsPage; // The window is only a frame: it owns the sidebar, the header, the status bar, // the menu, the tray and every dialog, and it stacks one screen per file from @@ -61,6 +62,8 @@ protected: void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; void dropEvent(QDropEvent* event) override; + // Language switch: Qt asks every widget to retranslate itself. + void changeEvent(QEvent* event) override; private slots: void onNavChanged(int id); @@ -105,6 +108,7 @@ private: NavHistory, NavLogs, NavPlugins, + NavSettings, }; void setupUI(); @@ -124,6 +128,9 @@ private: // Mirrors the pending update count on the sidebar entry, so the page that // needs attention is visible from wherever the user is. void setUpdatesBadge(int count); + // Last count given to the badge, kept so a language switch can rebuild the + // entry's label without having to re-query the core. + int m_updatesBadgeCount = 0; void notifyUpdatesAvailable(int count); // Runs a request and, when the core refused it, walks the user through what // it needs before replaying it. @@ -138,6 +145,18 @@ private: // dialog, anything else is shown as-is. void showActionError(const QString& title, const QString& error, bool locked); void applyCredentialMode(AppCore::CredentialMode mode); + // Applies the mode and re-checks the matching menu entry, so the menu bar + // and the Settings screen can never disagree about the current mode. + void onCredentialModeRequested(bool atLaunch); + // Re-applies the language and puts the text back in the widgets, so + // switching language on the Settings screen takes effect at once. + void onLanguageChanged(const QString& code); + // Keeps the window's drop target in step with the preference. + void onDragDropEnabledChanged(bool enabled); + // Puts every string the frame owns back into its widget. Called on the + // LanguageChange event, so it is what makes the language setting visible + // without restarting. + void retranslateUI(); // Records that the running operation just said something: the step is kept // for the heartbeat and the "nothing printed" clock restarts. void noteOperationOutput(const QString& step); @@ -176,6 +195,11 @@ private: HistoryPage* m_history = nullptr; LogsPage* m_logs = nullptr; PluginsPage* m_plugins = nullptr; + SettingsPage* m_settings = nullptr; + + // Sidebar entries, by nav id, so the language can be re-applied to them + // (and the updates badge found) without rebuilding the sidebar. + QHash 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 diff --git a/pages/page.h b/pages/page.h index ebb441b..b105c88 100644 --- a/pages/page.h +++ b/pages/page.h @@ -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; } diff --git a/pages/settings-page.cpp b/pages/settings-page.cpp new file mode 100644 index 0000000..f551093 --- /dev/null +++ b/pages/settings-page.cpp @@ -0,0 +1,517 @@ +#include "settings-page.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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(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(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(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(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); +} diff --git a/pages/settings-page.h b/pages/settings-page.h new file mode 100644 index 0000000..5801202 --- /dev/null +++ b/pages/settings-page.h @@ -0,0 +1,91 @@ +#pragma once + +#include + +#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; +}; diff --git a/resources/icons/check-dark.svg b/resources/icons/check-dark.svg new file mode 100644 index 0000000..4d4a119 --- /dev/null +++ b/resources/icons/check-dark.svg @@ -0,0 +1,3 @@ + + + diff --git a/resources/icons/settings.svg b/resources/icons/settings.svg new file mode 100644 index 0000000..bd5f887 --- /dev/null +++ b/resources/icons/settings.svg @@ -0,0 +1,4 @@ + + + + diff --git a/resources/resources.qrc b/resources/resources.qrc index 821fb5a..5cfe10c 100644 --- a/resources/resources.qrc +++ b/resources/resources.qrc @@ -11,10 +11,12 @@ icons/refresh.svg icons/tools.svg icons/check.svg + icons/check-dark.svg icons/close.svg icons/filter.svg icons/alert.svg icons/plugin.svg icons/broom.svg + icons/settings.svg \ No newline at end of file diff --git a/src/app-core.cpp b/src/app-core.cpp index 6a4022e..71417f8 100644 --- a/src/app-core.cpp +++ b/src/app-core.cpp @@ -1,5 +1,6 @@ #include "app-core.h" +#include #include #include #include @@ -1194,10 +1195,36 @@ QString AppCore::packageDetails(const PackageInfo& pkg) { // --------------------------------------------------------------------------- bool AppCore::shouldCheckForAppUpdate() const { + if (!appUpdateCheckRefusal().isEmpty()) return false; return m_update->shouldCheck(); } +QString AppCore::appUpdateCheckRefusal() const { + AppSettings& preferences = AppSettings::instance(); + + // The user parked the app's own updates: no automatic check, and the manual + // one says why instead of quietly doing nothing. + if (preferences.updatesBlocked()) { + return AppSettings::blockDescription( + preferences.updatesBlockedIndefinitely(), preferences.updateBlockedUntil(), + QDateTime::currentDateTime()); + } + if (!preferences.autoUpdateCheckEnabled()) { + return QStringLiteral( + "La vĂ©rification automatique des mises Ă  jour est dĂ©sactivĂ©e dans " + "les paramĂštres."); + } + return QString(); +} + void AppCore::checkForAppUpdate() { + const QString refusal = appUpdateCheckRefusal(); + if (!refusal.isEmpty()) { + LogManager::instance().logEvent(QStringLiteral("maj-app"), refusal); + emit statusMessage(refusal); + return; + } + LogManager::instance().logEvent(QStringLiteral("maj-app"), QStringLiteral("vĂ©rification de version")); emit statusMessage(QStringLiteral("VĂ©rification des mises Ă  jour...")); diff --git a/src/app-settings.cpp b/src/app-settings.cpp new file mode 100644 index 0000000..cb96c74 --- /dev/null +++ b/src/app-settings.cpp @@ -0,0 +1,242 @@ +#include "app-settings.h" + +#include +#include +#include +#include +#include + +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(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(1, seconds / 60)); +} diff --git a/src/language-manager.cpp b/src/language-manager.cpp new file mode 100644 index 0000000..07cef4d --- /dev/null +++ b/src/language-manager.cpp @@ -0,0 +1,111 @@ +#include "language-manager.h" + +#include "app-settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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; +} diff --git a/src/log-manager.cpp b/src/log-manager.cpp index de04557..2ccb61a 100644 --- a/src/log-manager.cpp +++ b/src/log-manager.cpp @@ -1,8 +1,11 @@ #include "log-manager.h" +#include "app-settings.h" + #include #include #include +#include #include #include #include @@ -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. diff --git a/src/main-window.cpp b/src/main-window.cpp index 019e9e9..83b5a7e 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -37,9 +37,11 @@ #include "cleanup-page.h" #include "dashboard-page.h" #include "history-page.h" +#include "language-manager.h" #include "logs-page.h" #include "page.h" #include "plugins-page.h" +#include "settings-page.h" // How long a wait reads best in the status bar: "45 s", "2 min 05", "1 h 03". static QString formatElapsed(qint64 ms) { @@ -236,6 +238,23 @@ static QString appStyleSheet() { " color: #e2e8f0;" "}" "QComboBox:hover { border-color: #7dd3fc; }" + // ---- Settings screen ---- + // The cards scroll as a whole: the area itself must not paint, or the + // page gradient would be cut off at its edges. + "QScrollArea { background: transparent; border: none; }" + "QScrollArea > QWidget > QWidget { background: transparent; }" + // Explanatory text under each control, in the site's secondary colour. + "QLabel#settingHint { font-size: 12px; color: #94a3b8; }" + "QCheckBox { font-size: 13px; color: #e2e8f0; spacing: 8px; }" + "QCheckBox::indicator {" + " width: 18px; height: 18px;" + " border: 1px solid #475569; border-radius: 5px; background: #1e293b;" + "}" + "QCheckBox::indicator:hover { border-color: #7dd3fc; }" + "QCheckBox::indicator:checked {" + " background: #38bdf8; border-color: #38bdf8;" + " image: url(:/icons/check-dark.svg);" + "}" "QComboBox::drop-down { border: none; width: 26px; }" "QComboBox QAbstractItemView {" " background: #273449;" @@ -353,6 +372,15 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { connect(m_core, &AppCore::selfUpdateFinished, this, &MainWindow::onCoreSelfUpdateFinished); + // The preferences the window reacts to rather than merely reads: dropping a + // file and switching language are both things the user does on the Settings + // screen and expects to see take effect at once. + AppSettings& preferences = AppSettings::instance(); + connect(&preferences, &AppSettings::dragDropEnabledChanged, this, + &MainWindow::onDragDropEnabledChanged); + connect(&preferences, &AppSettings::languageChanged, this, + &MainWindow::onLanguageChanged); + setupUI(); setupMenuBar(); setupTray(); @@ -435,8 +463,9 @@ void MainWindow::setupUI() { statusBar()->showMessage("PrĂȘt"); - // Flatpak files can be dropped anywhere on the window (see dragEnterEvent). - setAcceptDrops(true); + // Flatpak files can be dropped anywhere on the window (see dragEnterEvent), + // unless the user turned that off on the Settings screen. + setAcceptDrops(AppSettings::instance().dragDropEnabled()); // Progress of the running operation, anchored at the bottom of the window // so it takes no space on the screens. It appears while install/update/ @@ -515,6 +544,7 @@ void MainWindow::setupSidebar() { btn->setIcon(loadIcon(iconName)); btn->setIconSize(QSize(17, 17)); m_navGroup->addButton(btn, id); + m_navButtons.insert(id, btn); layout->addWidget(btn); return btn; }; @@ -532,6 +562,8 @@ void MainWindow::setupSidebar() { addNavButton(NavHistory, "history", "Historique", "Historique des actions"); addNavButton(NavLogs, "logs", "Logs", "Logs pacman"); addNavButton(NavPlugins, "plugin", "Plugins", "Gestionnaires de paquets et extensions"); + addNavButton(NavSettings, "settings", "ParamĂštres", + "Journal, glisser-dĂ©poser, langue et mises Ă  jour"); connect(m_navGroup, &QButtonGroup::idClicked, this, &MainWindow::onNavChanged); m_navGroup->button(NavDashboard)->setChecked(true); @@ -621,6 +653,11 @@ void MainWindow::setupPages() { m_plugins = new PluginsPage(m_core); registerPage("plugins", NavPlugins, m_plugins); + + m_settings = new SettingsPage(m_core); + registerPage("settings", NavSettings, m_settings); + connect(m_settings, &Page::credentialModeRequested, this, + &MainWindow::onCredentialModeRequested); } void MainWindow::registerPage(const QString& id, int navId, Page* page) { @@ -660,6 +697,7 @@ void MainWindow::updateStatusBar() { void MainWindow::setUpdatesBadge(int count) { if (!m_navUpdatesButton) return; + m_updatesBadgeCount = count; m_navUpdatesButton->setText(count > 0 ? QString("Mises Ă  jour · %1").arg(count) @@ -716,6 +754,7 @@ void MainWindow::setupMenuBar() { toolsMenu->addAction("Historique", this, [this, goTo] { goTo(NavHistory); }); toolsMenu->addAction("Logs pacman", this, [this, goTo] { goTo(NavLogs); }); toolsMenu->addAction("Plugins", this, [this, goTo] { goTo(NavPlugins); }); + toolsMenu->addAction("ParamĂštres", this, [this, goTo] { goTo(NavSettings); }); toolsMenu->addSeparator(); toolsMenu->addAction("PrĂ©visualiser les mises Ă  jour", this, [this, goTo] { goTo(NavUpdates); @@ -725,6 +764,12 @@ void MainWindow::setupMenuBar() { QMenu* settingsMenu = menuBar->addMenu("ParamĂštres"); + // The dedicated screen holds every preference; the two entries below are + // shortcuts to the one that would otherwise be a menu of its own. + settingsMenu->addAction("Ouvrir les paramĂštres", this, + [this, goTo] { goTo(NavSettings); }); + settingsMenu->addSeparator(); + QActionGroup* credGroup = new QActionGroup(this); credGroup->setExclusive(true); @@ -746,9 +791,9 @@ void MainWindow::setupMenuBar() { (atLaunch ? m_credLaunchAction : m_credEachTimeAction)->setChecked(true); connect(m_credEachTimeAction, &QAction::triggered, this, - [this]() { applyCredentialMode(AppCore::CredentialMode::EachTime); }); + [this]() { onCredentialModeRequested(false); }); connect(m_credLaunchAction, &QAction::triggered, this, - [this]() { applyCredentialMode(AppCore::CredentialMode::AtLaunch); }); + [this]() { onCredentialModeRequested(true); }); QMenu* helpMenu = menuBar->addMenu("Aide"); helpMenu->addAction("VĂ©rifier les mises Ă  jour", this, &MainWindow::onCheckForUpdates); @@ -806,6 +851,10 @@ void MainWindow::setupShortcuts() { bind(QKeySequence(QStringLiteral("Ctrl+U")), [this]() { m_navGroup->button(NavUpdates)->click(); }); + // The convention every other application uses for its own settings. + bind(QKeySequence(QStringLiteral("Ctrl+,")), [this]() { + m_navGroup->button(NavSettings)->click(); + }); bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() { LogManager::instance().logEvent(QStringLiteral("ui"), QStringLiteral("export de la liste affichĂ©e")); @@ -831,6 +880,7 @@ void MainWindow::onNavChanged(int id) { case NavHistory: pageName = QStringLiteral("historique"); break; case NavLogs: pageName = QStringLiteral("logs"); break; case NavPlugins: pageName = QStringLiteral("plugins"); break; + case NavSettings: pageName = QStringLiteral("paramĂštres"); break; default: break; } LogManager::instance().logEvent( @@ -871,6 +921,10 @@ void MainWindow::onNavChanged(int id) { m_pages->setCurrentWidget(m_plugins); m_plugins->refresh(); break; + case NavSettings: + m_pages->setCurrentWidget(m_settings); + m_settings->refresh(); + break; default: break; } @@ -907,6 +961,7 @@ void MainWindow::onPageMessage(const QString& text) { QStringList MainWindow::installableDroppedFiles(const QMimeData* mimeData) const { QStringList files; + if (!AppSettings::instance().dragDropEnabled()) return files; if (!mimeData || !mimeData->hasUrls()) return files; for (const QUrl& url : mimeData->urls()) { @@ -1063,6 +1118,87 @@ void MainWindow::applyCredentialMode(AppCore::CredentialMode mode) { if (mode == AppCore::CredentialMode::AtLaunch) promptForSudoPassword(); } +// One place answers a change of mode, whichever of the two entry points (the +// menu bar, the Settings screen) asked for it, so both end up in step. +void MainWindow::onCredentialModeRequested(bool atLaunch) { + applyCredentialMode(atLaunch ? AppCore::CredentialMode::AtLaunch + : AppCore::CredentialMode::EachTime); + (atLaunch ? m_credLaunchAction : m_credEachTimeAction)->setChecked(true); +} + +void MainWindow::onLanguageChanged(const QString& code) { + LogManager::instance().logEvent(QStringLiteral("config"), + QStringLiteral("langue → %1").arg(code)); + // Qt asks every widget to retranslate itself through the LanguageChange + // event, which this window answers in changeEvent(). + LanguageManager::apply(code); +} + +void MainWindow::onDragDropEnabledChanged(bool enabled) { + // The preference governs the window's own drop target only: files handed + // over by the desktop ("Ouvrir avec PacManager") keep working either way. + setAcceptDrops(enabled); + LogManager::instance().logEvent( + QStringLiteral("config"), + QStringLiteral("glisser-dĂ©poser → %1") + .arg(enabled ? QStringLiteral("activĂ©") : QStringLiteral("dĂ©sactivĂ©"))); +} + +void MainWindow::retranslateUI() { + // The screens provide their own title, so the header follows them. + updatePageTitle(); + + if (m_versionLabel) { + m_versionLabel->setText(QStringLiteral("v%1").arg(UpdateManager::currentVersion())); + } + + struct NavLabel { int id; const char* text; const char* tip; }; + // Kept next to the sidebar: those strings are the frame's, and the screens + // below retranslate themselves. + static const NavLabel kNavLabels[] = { + {NavDashboard, QT_TRANSLATE_NOOP("MainWindow", "Tableau de bord"), + QT_TRANSLATE_NOOP("MainWindow", "Vue d'ensemble du systĂšme")}, + {NavSearch, QT_TRANSLATE_NOOP("MainWindow", "Recherche"), + QT_TRANSLATE_NOOP("MainWindow", "Rechercher des paquets")}, + {NavInstalled, QT_TRANSLATE_NOOP("MainWindow", "InstallĂ©s"), + QT_TRANSLATE_NOOP("MainWindow", "Voir les paquets installĂ©s")}, + {NavUpdates, QT_TRANSLATE_NOOP("MainWindow", "Mises Ă  jour"), + QT_TRANSLATE_NOOP("MainWindow", "Voir les mises Ă  jour disponibles")}, + {NavCleanup, QT_TRANSLATE_NOOP("MainWindow", "Nettoyage"), + QT_TRANSLATE_NOOP("MainWindow", "Purger les paquets inutilisĂ©s ou legacy et vider les caches")}, + {NavHistory, QT_TRANSLATE_NOOP("MainWindow", "Historique"), + QT_TRANSLATE_NOOP("MainWindow", "Historique des actions")}, + {NavLogs, QT_TRANSLATE_NOOP("MainWindow", "Logs"), + QT_TRANSLATE_NOOP("MainWindow", "Logs pacman")}, + {NavPlugins, QT_TRANSLATE_NOOP("MainWindow", "Plugins"), + QT_TRANSLATE_NOOP("MainWindow", "Gestionnaires de paquets et extensions")}, + {NavSettings, QT_TRANSLATE_NOOP("MainWindow", "ParamĂštres"), + QT_TRANSLATE_NOOP("MainWindow", "Journal, glisser-dĂ©poser, langue et mises Ă  jour")}, + }; + + for (const NavLabel& label : kNavLabels) { + auto it = m_navButtons.find(label.id); + if (it == m_navButtons.end()) continue; + // The updates entry carries its pending count in its label, which + // setUpdatesBadge() is the one to rebuild. + if (label.id != NavUpdates) it.value()->setText(tr(label.text)); + it.value()->setToolTip(tr(label.tip)); + } + setUpdatesBadge(m_updatesBadgeCount); + + if (m_refreshButton) m_refreshButton->setText(tr("RafraĂźchir les sources")); + if (m_headerUpdateAllButton) { + m_headerUpdateAllButton->setText(tr("Tout mettre Ă  jour")); + } +} + +void MainWindow::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + retranslateUI(); + } + QMainWindow::changeEvent(event); +} + // The core knows *when* a password is needed (it owns the credential state and // the sudo pipeline); the frame only owns the dialog. bool MainWindow::promptForSudoPassword() { diff --git a/src/main.cpp b/src/main.cpp index 978be61..4245697 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,6 +3,8 @@ #include #include +#include "app-settings.h" +#include "language-manager.h" #include "log-manager.h" #include "main-window.h" #include "update-manager.h" @@ -17,11 +19,17 @@ int main(int argc, char* argv[]) { // into the journal, so the Logs screen shows the same detail as a debug run // without the user having to set QT_LOGGING_RULES. QLoggingCategory::setFilterRules(QStringLiteral("pacmgr.*=true")); + // The journal opens where the user asked it to, not where the previous + // release wrote it: AppSettings is read before the first line is written. LogManager::installQtMessageHandler(); LogManager::instance().logEvent( QStringLiteral("app"), QStringLiteral("session dĂ©marrĂ©e (v%1)").arg(UpdateManager::currentVersion())); + // The chosen catalogue is installed before any widget exists, so the whole + // interface is built in the right language from the start. + LanguageManager::apply(AppSettings::instance().language()); + MainWindow window; window.setWindowTitle("PacManager - Gestionnaire de Paquets"); window.resize(1200, 760); diff --git a/tests/app-settings.test.cpp b/tests/app-settings.test.cpp new file mode 100644 index 0000000..249fdbe --- /dev/null +++ b/tests/app-settings.test.cpp @@ -0,0 +1,305 @@ +#include "app-settings.h" +#include "log-manager.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// 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; +} diff --git a/version b/version index 9075be4..dc1e644 100644 --- a/version +++ b/version @@ -1 +1 @@ -1.5.5 +1.6.0