Outils pour utilisateurs

Outils du site


issue47:command_conquor_pp._5-8

I realize that last month I said I was going to do an article on Zenity within a script. However, I couldn't think of a script that would benefit from Zenity - without getting extremely complicated. Instead, I decided I would go further into Conky, specifically the ability to use lua scripts to draw graphical items to the desktop (in this case, rings, but I'm sure other objects are possible). Before we get started, I'd like to make the disclaimer that I am in no way a lua coder, and there is a good chance that there are easier ways to make the changes I've made, but it's what I came up with. For those of you who aren't sure what I'm talking about, this screenshot on my DeviantArt profile is an example of what is possible with Conky: http://lswest.deviantart.com/#/d3ay5fb

Je me rends compte que le mois dernier j'ai dit que j'allais faire un article sur l'utilisation de Zenity dans un script. Cependant, je n'ai pas trouvé de script qui pourrait bénéficier de Zenity, à moins d'être extrêmement compliqué. Au lieu de cela, j'ai décidé que je voulais aller plus loin dans Conky, notamment sa capacité d'utiliser des scripts LUA pour dessiner des éléments graphiques sur le bureau (j'ai choisi des anneaux, mais je suis sûr que d'autres objets sont possibles). Avant de commencer, je veux vous avertir que je ne suis nullement un programmeur LUA et il y a de bonnes chances qu'il existe des moyens plus faciles de faire les changements que j'ai faits, mais je vous montre ce que j'ai trouvé.

Pour ceux d'entre vous qui ne savent pas de quoi je parle, cette capture d'écran de mon profil DeviantArt est un exemple de ce qu'on peut faire avec Conky : http://lswest.deviantart.com/#/d3ay5fb.

First and foremost, make sure you have installed Conky (1.7.2 is in the repositories as of version 9.10 Karmic Koala). I will assume that everyone is using version 9.10 or higher. If you're using an older version, launchpad will probably have a PPA for you. As for the widgets we'll be creating, I'm going for a simple MPD music widget, and a clock (the same widgets visible in the above screenshot). Also, since I felt no need to re-create the wheel (or, in this case, the ring), I will be using the following script as a basis for what we are doing now: http://londonali1010.deviantart.com/art/quot-Rings-quot-Meters-for-Conky-141961783. For those of you who would like the complete scripts (for reference/correction), see the Scripts section at the end of this article.

Tout d'abord, assurez-vous que vous avez installé Conky (la version 1.7.2 est dans les dépôts depuis la version 9.10 Karmic Koala). Je suppose que tout le monde utilise la version 9.10 ou supérieure. Si vous utilisez une version plus ancienne, Launchpad aura probablement un PPA pour vous.

Concernant les widgets que nous allons créer, je vais faire un widget simple pour le lecteur de musique MPD et une horloge (les mêmes widgets visibles dans la capture d'écran ci-dessus). Aussi, comme je n'éprouvais pas le besoin de recréer la roue (ou dans ce cas l'anneau), je vais utiliser le script suivant comme base de ce que nous allons faire maintenant : http://londonali1010.deviantart.com/art/quot-Rings-quot-Meters-for-Conky-141961783. Pour ceux d'entre vous qui aimeraient les scripts complets (pour la référence/correction), voyez la section Scripts à la fin de cet article.

Pre-coding Before we get started on the actual script, I ask you to decide if you want it in two separate Conky instances (my choice) or within a single instance. The reason why I use two is quite simply because I have two other Conky instances on my desktop, and merging the widgets into one would have resulted in overlaps between Conky instances. If you wish to use only one, you will need to increase the minimum size, and adjust the x and y values for each widget to place them within the Conky window. The x and y relate to the relative position of Conky. For example, if Conky starts at (400,200) ((x,y)) then a widget with placement (100,85) will actually be at (500,285) on your monitor. Keep this in mind.

Pré-codage

Avant de commencer sur le script lui-même, je vous demande de décider si vous le voulez dans deux instances distinctes de Conky (mon choix) ou dans une instance unique. La raison pour laquelle j'en utilise deux est tout simplement parce que j'ai deux autres instances de Conky sur mon bureau et fusionner les widgets en un seul aurait donné lieu à des chevauchements entre les instances Conky. Si vous souhaitez en utiliser une seule, vous devrez augmenter la taille minimale et ajuster les valeurs x et y pour chaque widget afin de les placer dans la fenêtre de Conky. x et y se rapportent à la position relative de Conky. Par exemple, si Conky commence à la position (400, 200) ((x, y)), alors un widget placé en (100, 85) sera effectivement à (500, 285) sur votre moniteur. Gardez cela à l'esprit.

Also, to use the lua scripts, you must add in the following to your .conkyrc: lua_load /home/lswest/conky_testing/rings-v1.2.lua lua_draw_hook_pre ring_stats …where the top line is, of course, the actual absolute path to the lua script, and the name below is the name of your main function (if you write conky_ring_stats, or ring_stats, it will find the function regardless of which variation you use within the actual script).

En outre, pour utiliser les scripts LUA, vous devez ajouter ce qui suit à votre .conkyrc :

lua_load /home/lswest/conky_testing/rings-v1.2.lua
lua_draw_hook_pre ring_stats

… où la première ligne est, bien sûr, le chemin d'accès réel absolu au script lua et le nom en dessous est le nom de votre fonction principale (si vous écrivez conky_ring_stats, ou ring_stats, il trouvera la fonction quelle que soit la variation vous utilisez dans le script réel).

The script has comments to clarify the entries, but I'll quickly explain each as well. The name is actually the name of the Conky variable (i.e. ${time }), the args are the arguments (i.e. ${time %I}), and it is parsed by the script in lines 121-131 (on pastebin), within the local function setup_ring. It basically sends the command (after formatting it into ${name args}) to Conky, gets the result, and parses it. Then it's casted into a number, and the deviations (entered into the max variable) of the ring are calculated (so, if you say 360 divisions, then each division is exactly 1° of the ring, or if you have 12, then it's 2*pi/max (in radians)). It's not important if you don't understand this, just keep in mind that to have 12 hours within the ring, you must make 12 divisions. The 4 following variables are simply background and foreground colors, and their alpha (transparency) levels. The x and y variables make up your position vector, radius is the width of the ring, thickness is the size of the line, start_angle is where the circle starts (0°), and end_angle is where it stops (360°), so that we get a complete circle.

Le script a des commentaires pour clarifier les entrées, mais je vais vous les expliquer rapidement. Le nom est en fait le nom de la variable Conky (par exemple ${time }), args représente les arguments (par exemple $ {time %I}, et il est analysé par le script aux lignes 121 à 131 (sur pastebin), dans la fonction locale setup_ring. Il envoie simplement la commande à Conky (après l'avoir mise sous la forme ${name args}), récupère le résultat et l'analyse. Il est alors transformé en nombre, et les écarts de l'anneau (entrés dans la variable max) sont calculés (ainsi si vous indiquez 360 divisions, chaque division représentera exactement 1° de l'anneau, ou si vous en indiquez 12, alors chacune sera de 2*pi/max (en radians)). Ce n'est pas important si vous ne comprenez pas, il faut garder à l'esprit que pour avoir 12 heures dans l'anneau, vous devez faire 12 divisions. Les 4 variables suivantes sont tout simplement les couleurs de fond et de premier plan et leurs niveaux alpha (transparence). Les variables x et y fabriquent votre vecteur de position, le rayon est la largeur de l'anneau, on a également l'épaisseur de la ligne ainsi que l'angle auquel le cercle commence, ou start_angle (0 °), et l'angle où il se termine, ou end_angle (360 °,) de sorte que nous obtenons un cercle complet.

For those of you who know the formatting for the date command, you'll know that %I is the format for the hours with leading 0s (so 01…12). The format for a 12-hour clock, without leading 0s, is %l, but it doesn't matter for this clock - I also had it working fine with %H (0…23). The next two rings I made smaller and made the seconds ring 2 pixels thinner. In the end, you should have something along the lines (after the hours ring) of the code shown right. As you can see, it's fairly straightforward. If you're fine with the seconds ring counting off the seconds, and without the date in the center, you're finished. If you, like me, want the seconds to fill the innermost circle, then you'll need to add the following line before “cairo_arc(cr, xc, yc, ring_r, t_arc-arc_w, t_arc+arc_w)”: if pt['arg'] == '%S' then cairo_arc(cr, xc, yc, ring_r, angle_0, t_arc+arc_w) end

Pour ceux d'entre vous qui connaissent le format de la commande date, vous savez que %I est le format de l'heure avec des 0 devant (donc 01, …, 12). Le format d'une heure sans les 0 devant est %l, mais cela n'a pas d'importance pour cette horloge. J'ai aussi réussi à le faire fonctionner correctement avec %H (0, …, 23). J'ai rendu les deux anneaux suivants plus petits et celui des secondes est 2 pixels plus mince. En fin de compte, vous devriez avoir quelque chose qui ressemble (après l'anneau des heures) au code affiché à droite.

Comme vous pouvez le voir, c'est assez simple. Si vous réussissez à faire compter les secondes au centre et sans la date au centre, vous avez terminé. Si vous voulez, comme moi, que les secondes soient sur le cercle intérieur, alors vous devrez ajouter la ligne suivante avant « cairo_arc(cr, xc, yc, ring_r, t_arc-arc_w, t_arc+arc_w) » :

if pt['arg'] == '%S' then cairo_arc(cr, xc, yc, ring_r, angle_0, t_arc+arc_w) end

What this does is simply start at the angle_0 (12 o'clock on the ring), and extends the line. My first reaction is to put the original line into an else statement, but, it works without it, and it's a little less typing, so we'll forgo good formatting in this case. If you want to place the date within the center of the ring, it's a bit of guess-work for the positioning, but here is what you need to add to your .conkyrc: ${goto 115}${voffset 150}${time %A} ${goto 115}${time %b %d %Y} The goto line shifts it over to the right (you can also use ${offset <pixels>}), and voffset is the vertical offset (i.e. pixels moved down from the top of the conky window). What I did was display the day on the top line (${time %A}), and the date on the line below it. If you want to change the way it's displayed, checking the manpage of date will give you the formatting options you need.

Nous commençons simplement à l'angle_0 (12 heures sur l'anneau) et prolongeons la ligne. Ma première réaction est de mettre la ligne d'origine dans une déclaration else, mais ça fonctionne sans cela et cela fait moins de choses à saisir, donc nous allons renoncer à un bon formatage dans ce cas. Si vous souhaitez placer la date dans le centre de l'anneau, c'est un travail de conjectures pour le positionnement, mais voici ce que vous devez ajouter à votre .conkyrc :

${goto 115}${voffset 150}${time %A}
${goto 115}${time %b %d %Y}

La ligne goto le déplace vers la droite (vous pouvez aussi utiliser ${offset <pixels>}) et voffset est le décalage vertical (c'est-à-dire le nombre de pixels dont on descend depuis le haut de la fenêtre conky). J'ai affiché le jour sur la ligne supérieure ($time %A}) et la date sur la ligne en dessous. Si vous voulez changer la façon dont ça s'affiche, regardez la page de manuel de la commande date pour trouver les options de formatage dont vous avez besoin.

MPD Widget Now before we start this, the widget I describe here works only for MPD (Music Player Daemon), since Conky lacks variables for other music players. I'm sure you could get it working the same with some tricky coding, but I don't think it's worth it as most other music players have a “now-playing” widget of sorts. The settings_table entry for this one looks like the code shown on the next page, top left. As you can see, we're working with 100 divisions (since it's a percent, it will be a value between 0 and 100). Also, the arg variable is empty, which is important, since leaving it out entirely makes it incompatible with the functions we use later (missing argument). Once you've done this, I also altered the script so that the widget disappears when the music is paused. To do this, you need to make the following changes to the script:

Widget MPD

D'abord, avant de commencer, il faut savoir que le widget que je décris ici ne fonctionne que pour MPD (Music Player Daemon), car Conky manque de variables pour les autres lecteurs de musique. Je suis sûr que vous pourriez le faire fonctionner de la même façon avec des bouts de codes compliqués, mais je ne pense pas que ça vaille le coup car la plupart des autres lecteurs de musique ont un widget du type « lecture en cours ».

L'entrée settings_table pour celui-ci ressemble au code qu'on voit en haut à gauche de la page suivante.

Comme vous pouvez le voir, nous travaillons avec 100 divisions (puisque c'est un pourcentage, ça sera une valeur comprise entre 0 et 100). En outre, la variable arg est vide, ce qui est important car si on la laisse complètement de côté c'est incompatible avec les fonctions que nous utilisons plus tard (argument manquant). Une fois que vous avez fait cela, j'ai aussi modifié le script pour que le widget disparaisse quand la musique est en pause. Pour ce faire, vous devez apporter les modifications suivantes au script :

Add this function to the beginning or end of the file: function conky_my_flag(my_arg) flag = my_arg return “” end

Ajoutez cette fonction au début ou à la fin du fichier :

function conky_my_flag(my_arg)
  flag = my_arg
  return ""
end

Then, place the following text from the original script: local updates=conky_parse('${updates}') update_num=tonumber(updates) if update_num>5 then for i in pairs(settings_table) do setup_rings(cr,settings_table[i]) end end inside of the following if statement: if tonumber(flag) == 1 then <text from above> end cairo_destroy(cr) So that the last 11 or so lines of the file read as shown above right.

Placez ensuite le texte suivant du script original :

local updates=conky_parse('${updates}')
  update_num=tonumber(updates)

if update_num>5 then

      for i in pairs(settings_table) do
          setup_rings(cr,settings_table[i])
      end
  end

dans l'instruction if suivante :

if tonumber(flag) == 1 then
  <texte ci-dessus>
end
cairo_destroy(cr)

de façon à ce que les 11 dernières lignes du fichier ressemblent à ce qui est ci-dessus à droite.

What the above changes do is simply to destroy the widget if MPD isn't running, and otherwise to run as normal. The function we created is so we can assign a value to the global variable flag that we use within the if-statement. Now, before this script works, you'll need to add in ${lua my_flag 0} and ${lua my_flag 1} into your .conkyrc so that the function is called and the flag variable is set to 0 or 1, depending on if MPD is stopped (0), or not (1). The TEXT section of my .conkyrc looks like the code shown above. What this does is set the flag variable to 0 when if_mpd_playing is false. Otherwise it gets set to 1. The rest of the settings display and position the album art, display “Paused” if MPD is paused, or the Artist and Song Title on two lines to the right of the ring if MPD is playing. The ${scroll 38 ${mpd_title}} section causes the title to scroll (so the text moves from right to left) if it's longer than 38 pixels. You can leave this out, but I put it in there to prevent the text from being longer than my Conky is wide. In order to display the image, you'll need to add the following two settings above the TEXT marker somewhere: imlib_cache_size 0

Les changements ci-dessus ne font que détruire le widget si MPD ne fonctionne pas et, sinon, le font fonctionner normalement. La fonction que nous avons créée permet d'assigner une valeur au drapeau global que nous utilisons dans l'instruction if. Maintenant, avant que ce script fonctionne, vous devrez ajouter ${lua my_flag 0} et ${lua my_flag 1} à votre .conkyrc de sorte que la fonction soit appelée et que le drapeau soit mis à 0 ou 1 selon si MPD est arrêté (0) ou pas (1). La section TEXT de mon .conkyrc ressemble au code ci-dessus.

Elle permet de définir le drapeau à 0 lorsque if_mpd_playing est faux. Sinon, il est mis à 1. Le reste des paramètres gère l'affichage et la position de la pochette de l'album, affiche « pause » si MPD est en pause, ou l'artiste et le titre de la chanson sur deux lignes à la droite de l'anneau si MPD fonctionne. La section ${scroll 38 ${mpd_title}} fait que le titre défile (le texte se déplace de droite à gauche) s'il fait plus de 38 pixels. Vous pouvez omettre cela, mais je l'ai mis là pour prévoir le cas où le texte est plus long que la largeur de mon Conky. Pour afficher l'image, vous aurez besoin d'ajouter les deux paramètres suivants au-dessus du marqueur TEXT quelque part :

imlib_cache_size 0

Also, the mpd-cover script is below, in the Scripts section. The mpd-cover script is written for python 2.X, but you can always use the 2to3 program to re-write it for python 3. If you have issues, let me know. Be aware that some symbols can cause problems with the script. I have done very little editing (if any) to it, and it was originally from here: https://bbs.archlinux.org/viewtopic.php?id=112708 Hopefully the majority of you have found this interesting, and, as always, I'm open to requests, suggestions, general feedback, and questions. You can reach me at lswest34@gmail.com, and remember to put C&C or FCM into the subject line, so I don't overlook it. Also, English or German are my preferred languages, because otherwise I will have to rely on Google Translate. If anyone improves the scripts I have listed/used here, feel free to send a copy to me with an explanation of additions/changes, and I will note it at the beginning of the next article for anyone who is interested. Scripts: http://pastebin.com/SpC6bcn7 Lua clock ring http://pastebin.com/iZFdZAeg Conky mpd http://pastebin.com/zkVVHkYk .conkyl_mpd http://pastebin.com/BDa5MHuR conkyrc for clock http://pastebin.com/ZX4pLbta mpd-cover script

De plus, le script mpd-couverture est ci-dessous, dans la section Scripts. Le script mpd-couverture est écrit pour Python 2.X, mais vous pouvez toujours utiliser le programme 2to3 pour le ré-écrire pour Python 3. Si vous avez des problèmes, faites-le moi savoir. Soyez conscient que certains symboles peuvent causer des problèmes avec le script. J'ai fait très peu (voire pas) de changements, et il était à l'origine pris ici : https://bbs.archlinux.org/viewtopic.php?id=112708

J'espère que la majorité d'entre vous ont trouvé cela intéressant, et, comme toujours, je suis ouvert aux demandes, suggestions, commentaires d'ordre général et autres questions. Vous pouvez me joindre à l'adresse lswest34@gmail.com, et n'oubliez pas de mettre C&C ou FCM comme « Objet » pour ne pas que je rate votre message. En outre, l'anglais ou l'allemand sont mes langues préférées, parce que sinon je vais devoir compter sur Google Translate. Si quelqu'un améliore les scripts que j'ai énumérés/utilisés ici, n'hésitez pas à envoyer une copie avec une explication des ajouts/modifications, et je le noterai au début du prochain article pour ceux qui seraient intéressés.

Scripts : http://pastebin.com/SpC6bcn7 horloge en anneau Lua http://pastebin.com/iZFdZAeg Conky mpd http://pastebin.com/zkVVHkYk .conkyl_mpd http://pastebin.com/BDa5MHuR conkyrc pour l'horloge http://pastebin.com/3kD1Mcby script mpd-couverture

issue47/command_conquor_pp._5-8.txt · Dernière modification : 2011/05/09 14:23 de auntiee