Mostrando entradas con la etiqueta 07 DEFINIR Y GUARDAR SCRIPT-FU. Mostrar todas las entradas
Mostrando entradas con la etiqueta 07 DEFINIR Y GUARDAR SCRIPT-FU. Mostrar todas las entradas

domingo, 14 de febrero de 2010

7.4. Guardar y ejecutar el script-fu

Hasta ahora, hemos trabajado en la consola de Script-Fu. Ahora, sin embargo, vamos a cambiar para editar códigos de archivos de texto.
Para ejecutar este script,
  1. Hay que pensar que ruta ponemos en el script. A mi me gusta crear una opción de menú nueva donde incluyo todos los script personales. Si en la ruta ponemos, p.e., "/Script-Fu/Mis script/Demo Box...", se creará una opción en el menú principal llamada Script-Fu, con una opción llamda Mis Script, donde se encontrarán todos los script que yo prepare.
  2. Crear un archivo de texto copiando el texto en un archivo con extensión .scm.
  3. Copiar el archivo en la carpeta /home/tu-carpeta-usuario/.gimp-2.6/scripts. Me gusta incluirlos aquí para diferenciarlos de los que incluye Gimp en su instalación.
  4. A continuación, necesitamos que Gimp nos muestre el nuevo Script-fu en su menús, para lo cual es necesario refrescar los script, lo cual se logra al ejecutar la opción del menú Filtros → Scrip-Fu → Refrescar script (Cuando se trabaja con la programación de script esta opción es conveniente asociarla a una combinación de teclas en Gimp, lo que se realiza en la opción del menú : Edición-> Configurar las combinaciones de teclas... Lo que buscamos está en Complementos, en mi versión, casi al final
  5. Finalmente, si abre el examinador de procedimientos Filtros → Script-Fu → Consola → Examinar, notará que nuestro script aparece en la base de datos.

Prueba a grabar los dos ejemplos vistos anteriormente, y ejecútalos desde el menú correspondiente.
  • my-demo-box (copiando en un archivo de texto el código que tienes en el punto 7.3.1)
  • test-sphere (Puedes descargarlo de aquí)

Ahora estamos en disposición de comprender como se escribe un script-fu completo, pero antes vamos a preparar nuestra plantilla, en el punto 8., que nos facilitará la escritura de sucesivos script-fu.

7.3.1. Ejemplos

Ejemplo 1
El siguiente código crea una ventana con algunos de los posibles tipos de datos de entrada:
    (define (my-demo-box value adj1 adj2 image drawable toggle pattern string font color option gradient)
(print "Do nothing"))

(script-fu-register "my-demo-box"
"/Xtns/Script-Fu/My Stuff/Demo Box..."
"Do nothing"
"Joe User"
"Joe User"
"August 2000"
""
SF-ADJUSTMENT "SF-ADJUSTMENT (slider)" '( 30 1 2000 1 10 1 0)
SF-ADJUSTMENT "SF-ADJUSTMENT" '(400 1 2000 1 10 1 1)
SF-COLOR "SF-COLOR" '(255 0 255)
SF-DRAWABLE "SF-DRAWABLE" 0
SF-FONT "SF-FONT" ""
SF-GRADIENT "SF-GRADIENT" "Golden"
SF-IMAGE "SF-IMAGE" 0
SF-OPTION "SF-OPTION" '("Option 1" "Option 2" "Option 3")
SF-PATTERN "SF-PATTERN" "Wood"
SF-STRING "SF-STRING" "Test String"
SF-TOGGLE "SF-TOGGLE" TRUE
SF-VALUE "SF-VALUE" "0"
SF-FILENAME "SF-FILENAME" "/")

El resultado es el siguiente:



Ejemplo 2

El código del archivo test-sphere.scm muestra diversos tipos de parámetros, como vemos en la sentencia script-fu-register y en al imagen
    (script-fu-register "script-fu-test-sphere"
_"_Sphere..."
"Simple script to test and show the usage of the new Script-Fu API extensions."
"Spencer Kimball, Sven Neumann"
"Spencer Kimball"
"1996, 1998"
""
SF-ADJUSTMENT "Radius (in pixels)" '(100 1 5000 1 10 0 0)
SF-ADJUSTMENT "Lighting (degrees)" '(45 0 360 1 10 1 1)
SF-TOGGLE "Shadow" TRUE
SF-COLOR "Background color" "white"
SF-COLOR "Sphere color" "red"
SF-BRUSH "Brush" '("Circle (03)" 1.0 44 0)
SF-STRING "Text" "Tiny-Fu rocks!"
SF-TEXT "Multi-line text" "Hello,\nWorld!"
SF-PATTERN "Pattern" "Maple Leaves"
SF-GRADIENT "Gradient" "Deep Sea"
SF-TOGGLE "Gradient reverse" FALSE
SF-FONT "Font" "Agate"
SF-ADJUSTMENT "Font size (pixels)" '(50 1 1000 1 10 0 1)
SF-PALETTE "Palette" "Default"
SF-FILENAME "Environment map"
(string-append gimp-data-directory
"/scripts/images/beavis.jpg")
SF-OPTION "Orientation" '("Horizontal"
"Vertical")
SF-ENUM "Interpolation" '("InterpolationType" "linear")
SF-DIRNAME "Output directory" "/var/tmp/"
SF-IMAGE "Image" -1
SF-LAYER "Layer" -1
SF-CHANNEL "Channel" -1
SF-DRAWABLE "Drawable" -1
SF-VECTORS "Vectors" -1
)

(script-fu-menu-register "script-fu-test-sphere"
"/Xtns/Languages/Script-Fu/Test")

El código completo del script-fu pude bajarse de aquí

7.3. Tipos de parámetros de entrada

Necesitamos listar los parámetros que corresponden a los valores de entrada que nuestro script necesita. Cuando listamos estos parámetros, les damos indicación de como son. También podemos proporcionar valores predefinidos.
A continuación el listado, ordenado, salvo los dos primeros, por orden alfabético:
Tipo de parámetro
Descripción
SF-IMAGE
Si su script opera en una imagen nueva, esta debería ser el primer parámetro después de los parámetros requeridos. GIMP pasará una referencia a la imagen en este parámetro.
SF-DRAWABLE
Si su script opera sobre una imagen abierta, este sería el segundo parámetro después del parámetro SF-IMAGE. Se refiere a la capa activa. GIMP pasará una referencia a la capa activa en este parámetro
SF-ADJUSTMENT
Is only useful in interactive mode, if you call a script from the console, it acts just like a normal SF-VALUE
In interactive mode it creates an adjustment widget in the dialog.

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

Widget arguments list

Element
Descripción
"label" Text printed before the widget.
value Value print at the start.
lower / upper
The lower / upper values (range of choice).
step_inc Increment/decrement value.
page_inc Increment/decrement value using page key.
digits Digits after the point (decimal part).
type One of: SF-SLIDER or 0, SF-SPINNER or 1

SF-BRUSH
is only useful in interactive mode. 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.

The actual value returned when the script is invoked is a list consisting of Brush name, opacity, spacing and brush mode in the same units as passed in as the default value.

Usage:
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-COLOR
creates a color button in the dialog. It accepts either a list of three values for the red, green and blue components or a color name in CSS notatation

SF-COLOR "label" '(red green blue)
or
SF-COLOR "label" "color"
Widget arguments list

Element Descripción
"label" Text printed before the widget.
'(red green blue) List of three values for the red, green and blue components.
"color" Color name in CSS notatation.
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.

Usage:
SF-DIRNAME "Image Directory" "/var/tmp/images"

The value returned when the script is invoked is a string containing the dirname.
SF-ENUM
Only useful in interactive mode. 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 speficies the default value, using the enum value's nick.

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

The value returned when the script is invoked corresponds to chosen enum value.
SF-FILENAME
Only useful in interactive mode. 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.

Usage:
SF-FILENAME "Environment Map"
(string-append "" gimp-data-directory "/scripts/beavis.jpg")

The value returned when the script is invoked is a string containing the filename.
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) when using SF-FONT.

Usage:
SF-FONT "label" "fontname"

Widget arguments list

Element Descripción
"label" Text printed before the widget.
"fontname" Name of the default font.

SF-GRADIENT
Only useful in interactive mode. 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.

Usage:
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-OPTION
Only useful in interactive mode. 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.

Usage:
SF-OPTION "Orientation" '("Horizontal" "Vertical")

The value returned when the script is invoked is the number of the chosen option, where the option first is counted as 0.
SF-PALETTE
Only useful in interactive mode. It will create a widget in the control dialog. The widget consists of a button containing a preview of the selected palette. If the button is pressed a palette selection dialog will popup.

Usage:
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-PATTERN
Only useful in interactive mode. 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.

Usage:
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-STRING Acepta cadenas “Un texto"
SF-TOGGLE Se muestra una caja, para obtener un valor Booleano. TRUE o FALSE
SF-VALUE
Acepta números y cadenas. Notese que las cuotas deben eludir el texto predefinido, mejor usar SF-STRING.

sábado, 13 de febrero de 2010

7.2. Registro del Script-fu

Ahora, registremos la función con el GIMP. Esto se hace llamando a la función script-fu-register. Cuando el GIMP lee un script, ejecutará esta función, que registrará el script en la base de datos de procedimientos. Puede situar esta llamada a función donde quiera en su script, pero, normalmente, se situa al final, después de las otras lineas de códigos. Cuando empiezo a trabajar con un script nuevo, a mi me gusta más ponerla al principio, ya que veo mejor los parámetros y su tipo.
Aquí está el listado de registro de esta función (explicaré todos estos parámetros en un minuto):
    (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" "/Xtns/Script-Fu/Text")
Para registrar nuestro script en el GIMP, llamamos a la función script-fu-register, rellenamos los siete parámetros requeridos y añadimos los nuestros propios, junto con una descripción y valores predefinidos para cada parámetro.
Los parámetros requeridos:
  1. El nombre de la función que definimos. Esto es la llamada de función cuando nuestro script es invocado (el punto de entrada de nuestro script). Esto es necesario porque podriamos definir funciones adicionales bajo el mismo archivo, y GIMP necesita saber a cuales de estas funciones se llama. En nuestro ejemplo, solo definimos una función, text box, que registramos.
  2. La localización en el menú donde el script será insertado. El lugar exacto de el script está especificado, como una ruta en Unix, con la raiz de la ruta estando entre la caja de herramientas o click derecho.
Puede hacerse de dos formas:
En dos sentencias, script-fu-register y script-fu-menu-register, tal como hemos visto arriba, o todo en la sentencia script-fu-register (no siendo necesaría la segunda sentencia)
La función anterior, con el cambio de ubicación del paht, la función script-fu-register aparecería de la siguiente forma:
    (script-fu-register
"script-fu-text-box" ;func name
"/Script-Fu/Text/_My Text Box" ;menu label
…....................................................
SF-COLOR "Color:" '(0 0 0) ; un color
) ;Ya no sería necesaria la función script-fu-menu-register

Si su script no opera sobre una imagen existente (y crea una imagen nueva, como hará nuestro Text Box), querrá insertarlo en el menú de la caja de herramientas, este es el menu en la ventana principal del GIMP (donde se localizan todas las herramientas: herramientas de selección, lupa, etc.).
Si su script está intentando trabajar sobre una imagen que está siendo editada, querrá insertarla en el menú que aparece cuando pulsa el botón derecho sobre una imagen abierta. El resto de la ruta apunta a la lista de menú, menús y sub-menús. Registramos nuestro script en el menú Text de el menú Script-Fu del menú Exts, en el menú de la caja de herramientas ( Filtros → Script-Fu → Text → Text Box ).
Si se fija, el sub-menú Text, en el menú Script-Fu, no estaba allí cuando empezamos, el GIMP crea, automaticamente, cualquier menú que todavia no exista.
"/Script-Fu/_Zona de ajuste con ufraw": aparecerá en el menú superior, opción Script-Fu.
"/Script-Fu/Text/_Text Box": aparece en menú superior, opcion Script-Fu, en la opción Text (creada si no existe)
  1. Una descripción de su script, para ser mostrada en el Examinador de Procedimientos.
  2. El nombre del autor del código.
  3. Información del copyright.
  4. La fecha en que se hizó el código, o la última revisión del mismo.
  5. El tipo de imágenes con las trabaja el script. Puede ser uno de los siguientes: RGB, RGBA, GRAY, GRAYA, INDEXED, INDEXEDA. O podría no ser ninguno de ellos, en nuestro caso, estamos creando una imagen, y no necesitamos definir el tipo de imagen sobre la que trabajaremos.
  6. A continuación irían todos los parámetros, con su leyenda y tipo.Los parámetros se escriben indicando su tipo, que veremos en el siguiente apartado, la leyenda, entre comillas, que aparecerá en la ventana de entrada y los valores del parámetro, que variarán según el tipo de dato.

7.1. Generalidades

7.1. Generalidades
Cada Script-Fu define al menos una función, la cual es la función principal del script. En esta es donde haces el trabajo principal
Cada script debe, también, registrarse en la base de datos de procedimientos, para poder acceder a el bajo GIMP.
Las convenciones de nombres en Scheme parecen preferir minúsculas con guiones, en el nombre de la función. Suele comenzarse con las palabras script-fu.
Sin embargo, prefiero nombres más descriptivos para mis parámetros y variables, y añado el prefijo "in" a los parámetros, así que, puedo, rapidamente, ver que valores entran en el script, más bien que los que se crean en el.
Un esquema muy simplificado del código de un script-fu sería:
    1  Definimos el Script-fu, sentencia define con su nombre y parámetros:
    (define (my-demo-box  image drawable toggle pattern string font color option gradient)
hemos definido una nueva función llamada script-fu-text-box que toma cuatro parámetros, que, más tarde, corresponderán al texto, una fuente, el tamaño de la fuente y el color del texto.
    2 Cuerpo de las sentencia
    (print "Do nothing"))
La función está vacia y no hace nada.
    3  Sentecia o sentencias de registro:
    (script-fu-register "my-demo-box" ; lo veremos más abajo
…......
)
(script-fu-menu-register "script-fu-text-box" "/Xtns/Script-Fu/Text")