Résolu le 5-03-21 [XFCE, Bash, Cron] Script pour changer sa configuration de bureau automatiquement

Vos petites astuces, répertoire des tutoriels et astuces
Répondre
Avatar du membre
david37
modérateur
Messages : 3884
Enregistré le : lun. 22 août 2016 05:06

[XFCE, Bash, Cron] Script pour changer sa configuration de bureau automatiquement

Message par david37 »

Salut à tous,

Juste envie de partager un petit script bash que j'ai écris pour switcher la configuration du bureau (XFCE) à partir d'une certaine heure. L'idée c'était de pouvoir changer automatiquement à partir d'une certaine heure les icones, le style d'affichage, le fond d'écran, la coloration du terminal et le thème des fenêtres en une seule fois sans avoir à cliquer partout dans le menu Apparence et gestion des fenêtres.

Voici le script que j'ai fait, c'est assez rudimentaire mais ça marche:

Code : Tout sélectionner

#!/bin/bash
# Version 1.0
# Date création: 2021/03/04

# For crontab management: 
PID=$(pgrep xfce4-session)
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-)

# For changing theme depending of the hour of the day
current_date=$(date '+%H')                                                              # Find the current hour

ref_date=20                                                                             # Hour used as reference for switching color

# Define the list of workspace to be changed
listWorkSpace=$(xfconf-query -c xfce4-desktop -lv | awk '{print $1; }' | grep HDMI.*last-image)

if ((${current_date#0} < ${ref_date#0})) ; then
    #echo "$current_date < $ref_date ; Using Theme bleu"
    echo "It's $current_date , it's still early, let's set the blue theme"
    xfconf-query -c xfwm4 -p /general/theme -s Futurist-hackerist                       # Change Window theme
    xfconf-query -c xsettings -p /Net/IconThemeName -s Abyss-DEEP-Suru-GLOW             # Change Icon theme
    xfconf-query -c xsettings -p /Net/ThemeName -s Mint-Y-Dark-Teal                     # Change Appearance Style
    cp /data/Linux_Projects/Themes/TERMINAL_CYAN ~/.config/xfce4/terminal/terminalrc    # Changing terminal col

    # Changing backgrounds
    for i in $listWorkSpace; do
    xfconf-query -c xfce4-desktop -p $i -s /data/Linux_Projects/Themes/sele_ring_center.jpg
    done
    exit 0

else
    echo "It's past $ref_date, now it's time for setting the red theme"
    xfconf-query -c xfwm4 -p /general/theme -s Futurist-hackerist_Red                   # Change Window theme
    xfconf-query -c xsettings -p /Net/IconThemeName -s Abyss-BLOOD-Suru-GLOW            # Change Icon Theme
    xfconf-query -c xsettings -p /Net/ThemeName -s Mint-Y-Dark-Red                      # Change Appearance Style
    cp /data/Linux_Projects/Themes/TERMINAL_RED ~/.config/xfce4/terminal/terminalrc     # Changing terminal col

    # Changing backgrounds
    for i in $listWorkSpace; do
    xfconf-query -c xfce4-desktop -p $i -s /data/Linux_Projects/Themes/sele_ring_center_red.jpg
    done
    exit 0

fi


# TO ADD:
# Changer l'icone du menu
et une fois implémenté dans mon crontab:

Code : Tout sélectionner

SHELL=/bin/bash
# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
0 * * * * ./SwitchTheme.sh >> /data/logSh.txt
J'ai avant 20h, ce thème: Image
et après 20h, ce thème: Image

(pour des soucis logistique, j'ai modifié la valeur dans le script et la fréquence d’exécution du script dans cron pour pas à avoir à attendre 20h pour faire le screenshot).

Bon, partager un script sans l’expliquer c'est pas hyper intéressant. Donc voici quelques explications sur le cheminement et les problèmes que j'ai rencontré pour faire ce script. Ça pourra peut être aider d'autres membres ayant envie de se lancer dans la création de script.

1. Rassembler les éléments de chaque configuration.

Pour mon bureau "Bleu" sous XFCE, j'utilise:
- le pack d'icone Abyss-DEEP-Suru-Glow disponible ici: https://www.gnome-look.org/s/Gnome/p/1333376
- le thème de fenêtre Futurist-hackerist, disponible ici: https://www.xfce-look.org/p/1320508/
- le style Mint-Y-Dark-Teal et une coloration du terminal en cyan

Pour la configuration "Rouge", je vais donc colorer tous les éléments cités ci-dessus.
Pour le pack d’icône, c'est facile puisque qu'il existe un pack Abyss-BLOOD-Suru-Glow. Pour le style, j'utiliserai Mint-Y-Dark-Red, là aussi rien de compliquer.

Par contre pour le thème des fenêtres, Futurist-Hackerist n'existe que en bleu cyan, j'ai donc du manuellement recolorer tout le bleu en rouge. Pour ça j'ai fait une copie du thème qui se nomme Futurist-Hackerist_Red et j'ai utilisé Image Magick et la fonction "convert" qui avec les arguments "-fill" et "-opaque" permet d'utiliser une couleur pour en remplacer une autre. Une petite loop pour appliquer les changements à tous les fichiers et voilà:

Code : Tout sélectionner

#!/bin/bash

cd /data/Linux_Projects/Themes/Futurist-hackerist_Red/xfwm4

list_files=$(ls *.xpm)

for i in $list_files;
do
convert $i -fill "#5d000d" -opaque "#007aa6" $i
convert $i -fill "#47000a" -opaque "#003b51" $i
echo $i
done
exit 0
De la même façon pour colorer le fond d'écran (qui s'appelle sele_ring_center.jpg), j'ai utilisé Image Magick comme ceci:

Code : Tout sélectionner

convert sele_ring_center.jpg -fuzz 10% -fill "#5d000d" -opaque "#d2d2d2" sele_ring_center_red.jpg 
Pour obtenir les coloration du terminal, j'ai simplement coloré manuellement (en passant par Terminal > Edit > Préférences ...) et à chaque fois j'ai copié le fichier ~/.config/xfce4/terminal/terminalrc dans un autre dossier en le nommant TERMINAL_CYAN et TERMINAL_RED comme ça je n'ai plus qu'à remplacer terminalrc par la configuration que je souhaite en utilisant:

Code : Tout sélectionner

cp /data/Linux_Projects/Themes/TERMINAL_CYAN ~/.config/xfce4/terminal/terminalrc
Les packs d’icônes DEEP et BLOOD on été placés dans /usr/share/icons
Les thèmes Futurist-hackerist et Futurist-hackerist_Red dans /usr/share/themes

Pour les fichiers terminalrc et les fonds d'écrans, je les ai mis sur ma partition /data/ afin de pouvoir les manipuler plus facilement si besoin.

2. Remplacer les différents élément du bureau: xfconf-query

Cyrille avait fait une présentation de l'utilisation de xfconf-query pour remplacer le fond d'écran dans ce tuto: viewtopic.php?f=12&t=15738
J'ai repris cette commande pour changer les paramètres. Avec "xfconf-query -c xsettings -lv", on peut obtenir les valeurs à modifier pour changer les icônes et le style
Exemple:

Code : Tout sélectionner

xfconf-query -c xsettings -p /Net/IconThemeName -s Abyss-DEEP-Suru-GLOW     
xfconf-query -c xsettings -p /Net/ThemeName -s Mint-Y-Dark-Teal
Pour le thème des fenêtres ça se passe dans xfwm4:

Code : Tout sélectionner

xfconf-query -c xfwm4 -p /general/theme -s Futurist-hackerist
Pour le fond d'écran, c'est un peu plus "tricky" parce qu'il faut remplacer la valeur du fond d'écran de chaque écran (j'en ai deux en HDMI) sur chaque workspace (j'en ai 4). Donc pour obtenir la liste des valeurs à changer, j'ai utiliser cette commande:

Code : Tout sélectionner

$ xfconf-query -c xfce4-desktop -lv | awk '{print $1; }' | grep HDMI.*last-image
/backdrop/screen0/monitorHDMI-A-0/workspace0/last-image
/backdrop/screen0/monitorHDMI-A-0/workspace1/last-image
/backdrop/screen0/monitorHDMI-A-0/workspace2/last-image
/backdrop/screen0/monitorHDMI-A-0/workspace3/last-image
/backdrop/screen0/monitorHDMI-A-1/workspace0/last-image
/backdrop/screen0/monitorHDMI-A-1/workspace1/last-image
/backdrop/screen0/monitorHDMI-A-1/workspace2/last-image
/backdrop/screen0/monitorHDMI-A-1/workspace3/last-image
Sur cette liste, je pourrais donc faire une loop pour remplacer le fond d'écran de chaque moniteur sur chaque workspace:

Code : Tout sélectionner

#!/bin/bash

listWorkSpace=$(xfconf-query -c xfce4-desktop -lv | awk '{print $1; }' | grep HDMI.*last-image)

for i in $listWorkSpace; do
    xfconf-query -c xfce4-desktop -p $i -s /data/Linux_Projects/Themes/sele_ring_center_red.jpg
    done
    exit 0
Donc on a tout, on peut passer à la création du script:

3. Test conditionnel suivant l'heure:

Maintenant, je vais appliquer le thème rouge et bleu selon l'heure:

Code : Tout sélectionner

#!/bin/bash

current_date=$(date '+%H')                      # Find the current hour

ref_date=21                                            # Hour used as reference for switching color

if ((${current_date#0} < ${ref_date#0})) ; then
    echo "It's $current_date , it's still early, let's set the blue theme"

else
    echo "It's past $ref_date, now it's time for setting the red theme"
Faire attention à bien mettre ${current_date#0} pour faire la comparaison afin d'indiquer à bash de comparer des décimaux.
Sinon vous aurez des erreurs pour des heures inférieurs à 10h. Plus de détails ici: https://stackoverflow.com/questions/247 ... oken-is-08

Ensuite, j'ai rendu le script executable:

Code : Tout sélectionner

sudo chmod +x SwitchTheme.sh
4. Utilisation de cron

Pour cron, je me suis ajouté en tant qu'utilisateur dans le fichier /etc/cron.allow
Puis j'ai édité le crontab avec "crontab -e"

Code : Tout sélectionner

SHELL=/bin/bash
# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
0 * * * * ./SwitchTheme.sh >> /data/logSh.txt
Petite précision. Quand j'ai commencé à tester avec le cron, mon script ne marchait pas (seulement le terminal changeait de couleur).
En fait, c'était due à une erreur du display. En gros, de ce que j'ai compris, cron ne s'execute pas dans le même environnement que l'environnement de l'utilisateur, donc pour lui dire où effectuer les opérations, il faut rajouter ces deux lignes dans le script:

Code : Tout sélectionner

PID=$(pgrep xfce4-session)
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-)
On peut aussi vérifier que le script marche bien en faisant:

Code : Tout sélectionner

~$ env -i sh -c ./SwitchTheme.sh
Plus d'info sur ce sujet ici: https://stackoverflow.com/tags/cron/info

Voilà. Je crois que j'ai tout dit. Je pense que j'aurais pu déclarer les variables à modifier au début, où même ajouter un argument au script pour définir l'heure de bascule. c'est perfectible mais pour le moment ça marche. Si vous avez des idées pour améliorer le script, où d'autres astuces à partager, je suis preneur ;)
PC1: Mobo: Gigabyte B550 AORUS Elite 2 / CPU: AMD Ryzen 7 3700X / GPU: MSI Radeon RX 580 Armor / RAM: 32 GB @3600 MHz CL16 / SSD: Samsung 970 EVO 500 GB / LM 20.2 Xfce
PC2: HP Pavilion 15 / AMD Ryzen 5 5500U with Radeon Graphics / 16GB RAM / 500 GB SSD / Debian 11 Xfce
PC3: Dell-Latitude E7240 / 2.1GHz i7-4600U / Intel Haswell-ULT HD 4400 / 8GB RAM / 250 GB Hard Drive / LM 20.2 Xfce

Avatar du membre
arghlub
Administrateur du site
Messages : 10421
Enregistré le : dim. 21 mai 2017 08:19
Localisation : Provence
Contact :

Re: [XFCE, Bash, Cron] Script pour changer sa configuration de bureau automatiquement

Message par arghlub »

Salut David,
david37 a écrit :
ven. 5 mars 2021 11:58
Si vous avez des idées pour améliorer le script, où d'autres astuces à partager, je suis preneur ;)
écrire les commentaires de ton script bash en français (et avec des tabulations bien alignées -je chipote) ? :l :l
perso, le rosbif ne me pose pas de souci mais on est sur un forum "francophone" :l :l :D ;)
Tour1 (custom)CM MSI Z270 M3 | CPU Intel I7-7700K | CG Nvidia GTX 1080 | RAM 16Go | tripleBoot : Debian 11 | MXlinux 21 | LMint 19.3 | XFCE
Tour2 (custom)CM Gigabyte | CPU AMD Athlon 5200+ | CG Nvidia GTX 560 | RAM 6Go | FreeBSD 12.1 XFCE
Portable1 MSI GF75 Thin 9SC | CPU Intel I7-9750H | CG Nvidia GTX 1650 | RAM 32Go | dualBoot : LMint 20.2 | MXlinux 21 | XFCE
Portable2 MacBook Air A1466 (2015) | CPU Intel I5-5250U | CG Intel HD Graphics 6000 | RAM 8Go | dualBoot : macOS Sierra | MXlinux 21 XFCE
─────( pour une informatique libre ! -membre en stand-by de l' April.org────────────────

Avatar du membre
david37
modérateur
Messages : 3884
Enregistré le : lun. 22 août 2016 05:06

Re: [XFCE, Bash, Cron] Script pour changer sa configuration de bureau automatiquement

Message par david37 »

arghlub a écrit :
ven. 5 mars 2021 14:17
écrire les commentaires de ton script bash en français (et avec des tabulations bien alignées -je chipote) ? :l :l
ça l'était au départ mais j'ai fait 2-3 modifs et ça s'est retrouvé décalés ... :(
arghlub a écrit :
ven. 5 mars 2021 14:17
perso, le rosbif ne me pose pas de souci mais on est sur un forum "francophone" :l :l :D ;)
C'est vrai mais mon système est en anglais ... et puis faut bien que les gens se frottent à l'anglais, ils en trouveront partout sur le net.... bon en fait la vraie raison, j'ai la flegme ... :l :lol: c'est sorti en anglais quand j'ai écris le script ... trop la flegme de faire la traduction :lol: :lol:
PC1: Mobo: Gigabyte B550 AORUS Elite 2 / CPU: AMD Ryzen 7 3700X / GPU: MSI Radeon RX 580 Armor / RAM: 32 GB @3600 MHz CL16 / SSD: Samsung 970 EVO 500 GB / LM 20.2 Xfce
PC2: HP Pavilion 15 / AMD Ryzen 5 5500U with Radeon Graphics / 16GB RAM / 500 GB SSD / Debian 11 Xfce
PC3: Dell-Latitude E7240 / 2.1GHz i7-4600U / Intel Haswell-ULT HD 4400 / 8GB RAM / 250 GB Hard Drive / LM 20.2 Xfce

Répondre