3.4.  Your First Script-Fu Script

Do you not need to stop and catch your breath? No? Well then, let's proceed with your fourth lesson -- your first Script-Fu Script.

3.4.1.  Creating A Text Box Script

One of the most common operations I perform in GIMP is creating a box with some text in it for a web page, a logo or whatever. However, you never quite know how big to make the initial image when you start out. You don't know how much space the text will fill with the font and font size you want.

The Script-Fu Master (and student) will quickly realize that this problem can easily be solved and automated with Script-Fu.

We will, therefore, create a script, called Text Box, which creates an image correctly sized to fit snugly around a line of text the user inputs. We'll also let the user choose the font, font size and text color.

3.4.2.  Editing And Storing Your Scripts

Up until now, we've been working in the Script-Fu Console. Now, however, we're going to switch to editing script text files.

Where you place your scripts is a matter of preference -- if you have access to GIMP's default script directory, you can place your scripts there. However, I prefer keeping my personal scripts in my own script directory, to keep them separate from the factory-installed scripts.

In the .gimp-2.4 directory that GIMP made off of your home directory, you should find a directory called scripts. GIMP will automatically look in your .gimp-2.4 directory for a scripts directory, and add the scripts in this directory to the Script-Fu database. You should place your personal scripts here.

3.4.3.  The Bare Essentials

Every Script-Fu script defines at least one function, which is the script's main function. This is where you do the work.

Every script must also register with the procedural database, so you can access it within GIMP.

We'll define the main function first:

        (define (script-fu-text-box inText inFont inFontSize inTextColor))
      

Here, we've defined a new function called script-fu-text-box that takes four parameters, which will later correspond to some text, a font, the font size, and the text's color. The function is currently empty and thus does nothing. So far, so good -- nothing new, nothing fancy.

3.4.4.  Naming Conventions

Scheme's naming conventions seem to prefer lowercase letters with hyphens, which I've followed in the naming of the function. However, I've departed from the convention with the parameters. I like more descriptive names for my parameters and variables, and thus add the "in" prefix to the parameters so I can quickly see that they're values passed into the script, rather than created within it. I use the prefix "the" for variables defined within the script.

It's GIMP convention to name your script functions script-fu-abc, because then when they're listed in the procedural database, they'll all show up under script-fu when you're listing the functions. This also helps distinguish them from plug-ins.

3.4.5.  Registering The Function

Now, let's register the function with GIMP. This is done by calling the function script-fu-register. When GIMP reads in a script, it will execute this function, which registers the script with the procedural database. You can place this function call wherever you wish in your script, but I usually place it at the end, after all my other code.

Here's the listing for registering this function (I will explain all its parameters in a minute):

        (script-fu-register
          "script-fu-text-box"                        ;func name
          "Text Box"                                  ;menu label
          "Creates a simple text box, sized to fit\
            around the user's choice of text,\
            font, font size, and color."              ;description
          "Michael Terry"                             ;author
          "copyright 1997, Michael Terry"             ;copyright notice
          "October 27, 1997"                          ;date created
          ""                     ;image type that the script works on
          SF-STRING      "Text:"         "Text Box"   ;a string variable
          SF-FONT        "Font:"         "Charter"    ;a font variable
          SF-ADJUSTMENT  "Font size"     '(50 1 1000 1 10 0 1)
                                                      ;a spin-button
          SF-COLOR       "Color:"        '(0 0 0)     ;color variable
        )
        (script-fu-menu-register "script-fu-text-box" "<Toolbox>/Xtns/Script-Fu/Text")
      

If you save these functions in a text file with a .scm suffix in your script directory, then choose XtnsScript-FuRefresh Scripts, this new script will appear as XtnsScript-FuTextText Box.

If you invoke this new script, it won't do anything, of course, but you can view the prompts you created when registering the script (more information about what we did is covered next).

Finally, if you invoke the Procedure Browser ( XtnsProcedure Browser), you'll notice that our script now appears in the database.

3.4.6.  Steps For Registering The Script

To register our script with GIMP, we call the function script-fu-register, fill in the seven required parameters and add our script's own parameters, along with a description and default value for each parameter.

The Required Parameters

  • The name of the function we defined. This is the function called when our script is invoked (the entry-point into our script). This is necessary because we may define additional functions within the same file, and GIMP needs to know which of these functions to call. In our example, we only defined one function, text-box, which we registered.

  • The location in the menu where the script will be inserted. The exact location of the script is specified like a path in Unix, with the root of the path being either toolbox or right-click.

    If your script does not operate on an existing image (and thus creates a new image, like our Text Box script will), you'll want to insert it in the toolbox menu -- this is the menu in GIMP's main window (where all the tools are located: the selection tools, magnifying glass, etc.).

    If your script is intended to work on an image being edited, you'll want to insert it in the menu that appears when you right-click on an open image. The rest of the path points to the menu lists, menus and sub-menus. Thus, we registered our Text Box script in the Text menu of the Script-Fu menu of the Xtns menu of the toolbox ( XtnsScript-FuTextText Box ).

    If you notice, the Text sub-menu in the Script-Fu menu wasn't there when we began -- GIMP automatically creates any menus not already existing.

  • A description of your script, to be displayed in the Procedure Browser.

  • Your name (the author of the script).

  • Copyright information.

  • The date the script was made, or the last revision of the script.

  • The types of images the script works on. This may be any of the following: RGB, RGBA, GRAY, GRAYA, INDEXED, INDEXEDA. Or it may be none at all -- in our case, we're creating an image, and thus don't need to define the type of image on which we work.

Figure 12.4.  The menu of our script.

The menu of our script.

3.4.7.  Registering The Script's Parameters

Once we have listed the required parameters, we then need to list the parameters that correspond to the parameters our script needs. When we list these params, we give hints as to what their types are. This is for the dialog which pops up when the user selects our script. We also provide a default value.

This section of the registration process has the following format:

Param Type

Description

Example

SF-IMAGE

If your script operates on an open image, this should be the first parameter after the required parameters. GIMP will pass in a reference to the image in this parameter.

3

SF-DRAWABLE

If your script operates on an open image, this should be the second parameter after the SF-IMAGE param. It refers to the active layer. GIMP will pass in a reference to the active layer in this parameter.

17

SF-VALUE

Accepts numbers and strings. Note that quotes must be escaped for default text, so better use SF-STRING.

42

SF-STRING

Accepts strings.

"Some text"

SF-COLOR

Indicates that a color is requested in this parameter.

'(0 102 255)

SF-TOGGLE

A checkbox is displayed, to get a Boolean value.

TRUE or FALSE

3.4.8. Les paramètres de l'API Script-Fu[3]

[Note] Note

En plus des paramètres de types ci-dessus, il en existe d'autres pour le mode interactif, chacun d'eux créant une zone de dialogue dans la fenêtre de dialogue du script-fu. Vous trouverez la description de ces paramètres et des exemples dans le script de test plug-ins/script-fu/scripts/test-sphere.scm fourni avec le code source de GIMP.

Type de paramètre

Description

SF-ADJUSTMENT

En mode interactif il crée une zone de dialogue dans la fenêtre de dialogue du script-fu.

SF-ADJUSTMENT "label" '(value lower upper step_inc page_inc digits type)

Liste d'arguments de boutons
ÉlémentDescription
"label"Texte affiché devant la zone de dialogue.
valeurvalue : Valeur affichée par défaut au départ.
lower / upperValeurs mini / maxi (détermine la plage de choix).
step_incValeur pour incrémenter/décrémenter.
page_incValeur pour incrémenter/décrémenter utilisant les touches Page
chiffresChiffres après le point (partie décimale)
typeUn parmi: SF-SLIDER or 0 (glissière), SF-SPINNER or 1 (bouto àflèche)

SF-COLOR

Crée un bouton de choix de couleur.

SF-COLOR "label" '(red green blue)

ou

SF-COLOR "label" "color"

Liste d'arguments de boutons
ÉlémentDescription
"label"Texte affiché devant la zone de dialogue.
'(red green blue)Liste de trois valeurs pour les composantes rouge, vert et bleu de la couleur par défaut.
"color"Un nom de couleur en notation CSS pour la couleur par défaut.

SF-FONT

Crée une zone de sélection de fonte. Retourne le nom de la fonte sous la forme d'une chaîne de caractères. Il existe deux nouvelles procédures de type gimp-text pour utiliser facilement ce paramètre que retourne la fonction:

(gimp-text-fontname image drawable x-pos y-pos text border antialias size unit font)

(gimp-text-get-extents-fontname text size unit font)

dans lesquelles le paramètre "font" est le nom de la fonte que vous obtenez. La taille spécifiée dans fontname est ignorée. Elle est utilisée seulement dans le sélecteur de fonte. On vous demandera de donner une valeur utilisable (24 pixels est un choix correct).

SF-FONT "label" "fontname"

Liste d'arguments de boutons
ÉlémentDescription
"label"Texte affiché devant la zone de dialogue.
"fontname"Nom de la fonte par défaut.

SF-BRUSH

Crée une zone de choix de brosse : prévisualisation de la brosse et à sa droite, bouton "Parcourir". Cliquer sur ce dernier fait apparaître la boite de dialogue des brosses avec possibilité de choisir une brosse ainsi que son espacement, son opacité et son mode.

SF-BRUSH "Brush" '("Circle (03)" 100 44 0)

Dans ce cas la brosse par défaut sera un Cercle (03) avec une opacité de 100, un espacement de 44 et en mode normal (0).

Si cette sélection reste inchangée la valeur passée à la fonction comme paramètre sera '("Circle (03)" 100 44 0).

SF-PATTERN

Crée une zone de choix de motif : prévisualisation du motif et à sa droite, bouton "Parcourir". Cliquer sur ce dernier fait apparaître la boite de dialogue des motifs.

SF-PATTERN "Pattern" "Maple Leaves"

La valeur retournée quand le script est appelé est une chaîne de caractères contenant le nom du motif. Si la sélection par défaut ci-dessus n'est pas modifiée, la chaîne contiendra "Maple Leaves".

SF-GRADIENT

Crée un bouton contenant une prévisualisation du dégradé.

Si on appuie sur le bouton, une fenêtre de sélection de palette apparaît.

SF-GRADIENT "Gradient" "Deep Sea"

La valeur retournée quand le script est appelé est une chaîne de caractères contenant le nom du dégradé. Si la sélection par défaut ci-dessus n'est pas modifiée, la chaîne contiendra "Deep Sea".

SF-PALETTE

Crée un bouton contenant le nom de la palette sélectionnée.

Si on appuie sur le bouton, une fenêtre de sélection de palette apparaît.

SF-PALETTE "Palette" "Named Colors"

La valeur retournée quand le script est appelé est une chaîne de caractères contenant le nom de la palette. Si la sélection par défaut ci-dessus n'est pas modifiée, la chaîne contiendra "Named Colors".

SF-FILENAME

Crée un bouton contenant le nom d'un fichier.

Cliquer sur celui-ci fait apparaître la boite de dialogue de sélection de fichiers.

SF-FILENAME "label" (string-append "" gimp-data-directory "/scripts/beavis.jpg")

La valeur retournée quand le script est appelé est une chaîne de caractères contenant le nom du fichier.

SF-DIRNAME

Similaire à SF-FILENAME, mais permet de choisir un dossier.

SF-DIRNAME "label" "/var/tmp/images"

La valeur retournée quand le script est appelé est une chaîne de caractères contenant le nom du dossier.

SF-OPTION

Crée une boîte de choix (combo-box) pour des options possibles.

La première option est l'option par défaut.

SF-OPTION "label" '("option1" "option2")

La valeur retournée quand le script est appelé est le numéro de l'option choisie (0 correspondant à la 1ère option...).

SF-ENUM

Crée une boîte de choix (combo-box) montrant toutes les valeurs possibles pour un type donné. Le premier paramètre doit être un nom d'énumération de valeurs de GIMP, sans le préfixe "Gimp". Le second spécifie la valeur par défaut.

SF-ENUM "Interpolation" '("InterpolationType" "linear")

La valeur retournée quand le script est appelé est la valeur choisie de l'énumération.



[3] Cette section ne fait pas partie du didacticiel d'origine.