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.

This problem can 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 files. Script files should be plain text files that you can edit in a text or code editor. The name you give is not that important, except for being able to recognize the script. You should give your script file the extension «.scm».

Where you place your scripts is a matter of preference. In GIMP's folder preferences you can see in which folders GIMP looks for scripts. It is also possible to add a new folder there. The folder where GIMP stores its own scripts is usually not the best choice for your scripts, but for the rest feel free to choose what suits you best.

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. Угоди щодо назв

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"                        ;function 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;\
      2009, the GIMP Documentation Team"        ;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" "<Image>/File/Create/Text")
      

If you save these functions in a text file with a .scm suffix in your script directory, then restart GIMP. The new script will appear as FileCreateTextText 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 ( HelpProcedure 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 menu label is the name that will be shown in the menu. To specify the location, see Розділ 3.4.9, «Registering the Menu Location».

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

  • Your name (the author of the script).

  • Відомості щодо авторських прав.

  • 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.

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

Опис

Приклад

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. The Script-Fu parameter API[5]

[Примітка] Примітка

Beside the above parameter types there are more types for the interactive mode, each of them will create a widget in the control dialog. You will find a list of these parameters with descriptions and examples in the test script plug-ins/script-fu/scripts/test-sphere.scm shipped with the GIMP source code.

Param Type

Опис

SF-ADJUSTMENT

Creates an adjustment widget in the dialog.

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

Widget arguments list
ЕлементОпис
"label"Text printed before the widget.
значенняValue print at the start.
lower / upperThe lower / upper values (range of choice).
step_incЗначення кроку збільшення або зменшення.
page_incIncrement/decrement value using page key.
digitsКількість цифр після крапки (дробова частина).
typeOne of: SF-SLIDER or 0, SF-SPINNER or 1

SF-COLOR

Creates a color button in the dialog.

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

або

SF-COLOR "label" "color"

Widget arguments list
ЕлементОпис
"label"Text printed before the widget.
'(red green blue) List of three values for the red, green and blue components.
"color"Назва кольору у позначеннях CSS.

SF-FONT

Creates a font-selection widget in the dialog. It returns a fontname as a string. There are two new gimp-text procedures to ease the use of this return parameter:

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

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

where font is the fontname you get. The size specified in the fontname is silently ignored. It is only used in the font-selector. So you are asked to set it to a useful value (24 pixels is a good choice).

SF-FONT "label" "fontname"

Widget arguments list
ЕлементОпис
"label"Text printed before the widget.
"fontname"Назва типового шрифту.

SF-BRUSH

It will create a widget in the control dialog. The widget consists of a preview area (which when pressed will produce a popup preview ) and a button with the "..." label. The button will popup a dialog where brushes can be selected and each of the characteristics of the brush can be modified.

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

Here the brush dialog will be popped up with a default brush of Circle (03) opacity 100 spacing 44 and paint mode of Normal (value 0).

If this selection was unchanged the value passed to the function as a parameter would be '("Circle (03)" 100 44 0).

SF-PATTERN

It will create a widget in the control dialog. The widget consists of a preview area (which when pressed will produce a popup preview ) and a button with the "..." label. The button will popup a dialog where patterns can be selected.

SF-PATTERN "Pattern" "Maple Leaves"

The value returned when the script is invoked is a string containing the pattern name. If the above selection was not altered the string would contain "Maple Leaves".

SF-GRADIENT

It will create a widget in the control dialog. The widget consists of a button containing a preview of the selected gradient.

If the button is pressed a gradient selection dialog will popup.

SF-GRADIENT "Gradient" "Deep Sea"

The value returned when the script is invoked is a string containing the gradient name. If the above selection was not altered the string would contain "Deep Sea".

SF-PALETTE

It will create a widget in the control dialog. The widget consists of a button containing the name of the selected palette.

If the button is pressed a palette selection dialog will popup.

SF-PALETTE "Palette" "Named Colors"

The value returned when the script is invoked is a string containing the palette name. If the above selection was not altered the string would contain "Named Colors".

SF-FILENAME

It will create a widget in the control dialog. The widget consists of a button containing the name of a file.

If the button is pressed a file selection dialog will popup.

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

The value returned when the script is invoked is a string containing the filename.

SF-DIRNAME

Only useful in interactive mode. Very similar to SF-FILENAME, but the created widget allows to choose a directory instead of a file.

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

The value returned when the script is invoked is a string containing the dirname.

SF-OPTION

It will create a widget in the control dialog. The widget is a combo-box showing the options that are passed as a list.

The first option is the default choice.

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

The value returned when the script is invoked is the number of the chosen option, where the option first is counted as 0.

SF-ENUM

It will create a widget in the control dialog. The widget is a combo-box showing all enum values for the given enum type. This has to be the name of a registered enum, without the "Gimp" prefix. The second parameter specifies the default value, using the enum value's nick.

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

Значення, яке буде повернуто при виклику скрипту, відповідає вибраному номеру у переліку.

3.4.9. Registering the Menu Location

Once we have registered our script, we need to tell GIMP where it should be found in the menu.

The best menu location of your script depends on its function. Most scripts are found in the Filters and Colors menus.

For the current script, which creates a new image, we choose a submenu of FileCreate. This is what the line with the script-fu-menu-register function does. Thus, we registered our Text Box script here: FileCreateTextText Box.

If you notice, the Text submenu in the FileCreate menu wasn't there when we began — GIMP automatically creates any menus not already existing.

Рисунок 13.2. The menu of our script.

The menu of our script.



[5] This section is not part of the original tutorial.