Gimp Python Documentation

Abstract

This document outlines the interfaces to Gimp-Python, which is a set of Python modules that act as a wrapper to libgimp allowing the writing of plug-ins for Gimp. In this way, Gimp-Python is similar to Script-Fu, except that you can use the full set of Python extension modules from the plug-in.


Table of Contents
Introduction
The Structure Of A Plugin
The Procedural Database
Gimp Module Procedures
Gimp Objects
Support Modules
End Note

Introduction


The Structure Of A Plugin

The majority of code in this package resides in gimpmodule.c, but this provides a poor interface for implementing some portions of a plugin. For this reason, there is a python module called plugin.py that sets out a structure for plugins and implements some things that were either too dificult or impossible to do in C.

The main purpose of plugin.py was to implement an object oriented structure for plug-ins. As well as this, it handles tracebacks, which are otherwise ignored by libgimp, and gives a method to call other Gimp-Python plug-ins without going through the procedural database.


An Example Plugin

As in a lot of manuals, the first thing you examine is an example, so here is an example. I have included it before explaining what it does to allow more advanced programmers to see the structure up front. It is a translation of the clothify Script-Fu extension:

Example 1. A sample python plugin

#!/usr/bin/python
import math
from gimpfu import *

have_gimp11 = gimp.major_version > 1 or \
	      gimp.major_version == 1 and gimp.minor_version >= 1

def python_clothify(timg, tdrawable, bx=9, by=9,
		    azimuth=135, elevation=45, depth=3):
	bx = 9 ; by = 9 ; azimuth = 135 ; elevation = 45 ; depth = 3
	width = tdrawable.width
	height = tdrawable.height
	img = gimp.image(width, height, RGB)
	layer_one = gimp.layer(img, "X Dots", width, height, RGB_IMAGE,
			       100, NORMAL_MODE)
	img.disable_undo()
	if have_gimp11:
		pdb.gimp_edit_fill(layer_one)
	else:
		pdb.gimp_edit_fill(img, layer_one)
	img.add_layer(layer_one, 0)
	pdb.plug_in_noisify(img, layer_one, 0, 0.7, 0.7, 0.7, 0.7)
	layer_two = layer_one.copy()
	layer_two.mode = MULTIPLY_MODE
	layer_two.name = "Y Dots"
	img.add_layer(layer_two, 0)
	pdb.plug_in_gauss_rle(img, layer_one, bx, 1, 0)
	pdb.plug_in_gauss_rle(img, layer_two, by, 0, 1)
	img.flatten()
	bump_layer = img.active_layer
	pdb.plug_in_c_astretch(img, bump_layer)
	pdb.plug_in_noisify(img, bump_layer, 0, 0.2, 0.2, 0.2, 0.2)
	pdb.plug_in_bump_map(img, tdrawable, bump_layer, azimuth,
			     elevation, depth, 0, 0, 0, 0, TRUE, FALSE, 0)
	gimp.delete(img)

register(
	"python_fu_clothify",
	"Make the specified layer look like it is printed on cloth",
	"Make the specified layer look like it is printed on cloth",
	"James Henstridge",
	"James Henstridge",
	"1997-1999",
	"<Image>/Python-Fu/Alchemy/Clothify",
	"RGB*, GRAY*",
	[
		(PF_INT, "x_blur", "X Blur", 9),
		(PF_INT, "y_blur", "Y Blur", 9),
		(PF_INT, "azimuth", "Azimuth", 135),
		(PF_INT, "elevation", "elevation", 45),
		(PF_INT, "depth", "Depth", 3)
	],
	[],
	python_clothify)

main()

Plugin Framework

With pygimp-0.4, the gimpfu module was introduced. It simplifies writing plugins a lot. It handles the run mode (interactive, non interactive or run with last values), providing a GUI for interactive mode and saving the last used settings.

Using the gimpfu plugin, all you need to do is write the function that should be run, make a call to register, and finally a call to main to get the plugin started.

If the plugin is to be run on an image, the first parameter to the plugin function should be the image, and the second should be the current drawable (do not worry about the run_mode parameter). Plugins that do not act on an existing image (and hence go in the toolbox's menus) do not need these parameters. Any other parameters are specific to the plugin.

After defining the plugin function, you need to call register to register the plugin with gimp (When the plugin is run to query it, this information is passed to gimp. When it is run interactively, this information is used to construct the GUI). The parameters to register are:

name
blurb
help
author
copyright
date
menupath
imagetypes
params
results
function

Most of these parameters are quite self explanatory. The menupath option should start with <Image%gt;/ for image plugins and <Toolbox>/ for toolbox plugins. The remainder of the menupath is a slash separated path to its menu item.

The params parameter holds a list parameters for the function. It is a list of tuples. Note that you do not have to specify the run_type, image or drawable parameters, as gimpfu will add these automatically for you. The tuple format is (type, name, description, default [, extra]). The allowed type codes are:

PF_INT8
PF_INT16
PF_INT32
PF_INT
PF_FLOAT
PF_STRING
PF_VALUE
PF_INT8ARRAY
PF_INT16ARRAY
PF_INT32ARRAY
PF_INTARRAY
PF_FLOATARRAY
PF_STRINGARRAY
PF_COLOR
PF_COLOUR
PF_REGION
PF_IMAGE
PF_LAYER
PF_CHANNEL
PF_DRAWABLE
PF_TOGGLE
PF_BOOL
PF_SLIDER
PF_SPINNER
PF_ADJUSTMENT
PF_FONT
PF_FILE
PF_BRUSH
PF_PATTERN
PF_GRADIENT

These values map onto the standard PARAM_* constants. The reason to use the extra constants is that they give gimpfu more information, so it can produce a better interface (for instance, the PF_FONT type is equivalent to PARAM_STRING, but in the GUI you get a small button that will bring up a font selection dialog).

The PF_SLIDER, PF_SPINNER and PF_ADJUSTMENT types require the extra parameter. It is of the form (min, max, step), and gives the limits for the spin button or slider.

The results parameter is a list of 3-tuples of the form (type, name, description). It defines the return values for the function. If there is only a single return value, the plugin function should return just that value. If there is more than one, the plugin function should return a tuple of results.

The final parameter to register is the plugin function itself.

After registering one or more plugin functions, you must call the main function. This will cause the plugin to start running. A GUI will be displayed when needed, and your plugin function will be called at the appropriate times.


The Procedural Database

The procedural database is a registry of things gimp and its plugins can do. When you install a procedure for your plugin, you are extending the procedural database.

The procedural database is self documenting, in that when you install a procedure in it, you also add documentation for it, its parameters and return values.


Procedural Database Procedures

Procedures can be accessed as procedures, or by treating pdb as a mapping objest. As an example, the probedure gimp_edit_fill can be accessed as either pdb.gimp_edit_fill or pdb['gimp_edit_fill']. The second form is mainly for procedures whose names are not valid Python names (eg in script-fu-..., the dashes are interpreted as minuses).

These procedure objects have a number of attribute:

A procedure object may also be called. At this point, Gimp-Python doesn't support keyword arguments for PDB procedures. Arguments are passed to the procedure in the normal method. The return depends on the number of return values:


Gimp Module Procedures

The gimp module contains a number of procedures and functions, as well as the definitions of many gimp types such as images, and the procedural database. This section explains the base level procedures.


Constructors and Object Deletion

There are a number of functions in the gimp module that are used to create the objects used to make up an image in Gimp. Here is a set of descriptions of these constructors:

When any of these objects get removed from memory (such as when their name goes out of range), the gimp thing it represents does not get deleted with it (otherwise when your plugin finished running, it would delete all its work). In order to delete the thing the Python object represents, you should use the gimp.delete procedure. It deletes the gimp thing associated with the Python object given as a parameter. If the object is not an image, layer, channel, drawable or display gimp.delete does nothing.


PDB Registration Functions

These functions either install procedures into the PDB or alert gimp to their special use (eg as file handlers).

For simple plugins, you will usually only need to use register from gimpfu.


Other Functions

These are the other functions in the gimp module.

gimp.main(init_func, quit_func, query_func, run_func)

This function is the one that controls the execution of a Gimp-Python plugin. It is better to not use this directly but rather subclass the plugin class, defined in the the Section called The gimpplugin Module.

gimp.pdb

The procedural database object.

gimp.progress_init([label])

(Re)Initialise the progress meter with label (or the plugin name) as a label in the window.

gimp.progress_update(percnt)

Set the progress meter to percnt done.

gimp.query_images()

Returns a list of all the image objects.

gimp.quit()

Stops execution imediately and exits.

gimp.displays_flush()

Update all the display windows.

gimp.tile_width()

The maximum width of a tile.

gimp.tile_height()

The maximum height of a tile.

gimp.tile_cache_size(kb)

Set the size of the tile cache in kilobytes.

gimp.tile_cache_ntiles(n)

Set the size of the tile cache in tiles.

gimp.get_data(key)

Get the information associated with key. The data will be a string. This function should probably be used through the the Section called The gimpshelf Module.

gimp.set_data(key, data)

Set the information in the string data with key. The data will persist for the whole gimp session. Rather than directly accessing this function, it is better to go through the the Section called The gimpshelf Module.

gimp.extension_ack()

Tells gimp that the plugin has finished its work, while keeping the plugin connection open. This is used by an extension plugin to tell gimp it can continue, while leaving the plugin connection open. This is what the script-fu plugin does so that only one scheme interpretter is needed.

gimp.extension_process(timeout)

Makes the plugin check for messages from gimp. generally this is not needed, as messages are checked during most calls in the gimp module.


Gimp Objects

Gimp-Python implements a number of special object types that represent the different types of parameters you can pass to a PDB procedure. Rather than just making these place holders, I have added a number of members and methods to them that allow a lot of configurability without directly calling PDB procedures.

There are also a couple of extra objects that allow low level manipulation of images. These are tile objects (working) and pixel regions (not quite finished).


Image Object

This is the object that represents an open image. In this section, image represents a generic image object.


Image Methods

image.add_channel(channel, position)

Adds channel to image in position position.

image.add_layer(layer, position)

Adds layer to image in position position.

image.add_layer_mask(layer, mask)

Adds the mask mask to layer.

image.clean_all()

Unsets the dirty flag on the image.

image.disable_undo()

Disables undo for image.

image.enable_undo()

Enables undo for image. You might use these commands round a plugin, so that the plugin's actions can be undone in a single step.

image.flatten()

Returns the resulting layer after merging all the visible layers, discarding non visible ones and stripping the alpha channel.

image.get_component_active(component)

Returns true if component (one of the *_CHANNEL constants) is active.

image.get_component_visible(component)

Returns true if component is visible.

image.set_component_active(component, active)

Sets the activeness of component.

image.set_component_visible(component, active)

Sets the visibility of component.

image.lower_channel(channel)

Lowers channel.

image.lower_layer(layer)

Lowers layer.

image.merge_visible_layers(type)

Merges the visible layers of image using the given merge type.

image.pick_correlate_layer(x, y)

Returns the layer that is visible at the point (x,y), or None if no layer matches.

image.raise_channel(channel)

Raises channel.

image.raise_layer(layer)

Raises layer.

image.remove_channel(channel)

Removes channel from image.

image.remove_layer(layer)

Removes layer from image.

image.remove_layer_mask(layer, mode)

Removes the mask from layer, with the given mode (either APPLY or DISCARD).

image.resize(width, height, x, y)

Resizes the image to size (width, height) and places the old contents at position (x,y).


Drawable Objects

Both layers and channels are drawables. Hence there are a number of operations that can be performed on both objects. They also have some common attributes and methods. In the description of these attributes, I will refer to a generic drawable called drawable.


Tile Objects

Tile objects represent the way Gimp stores information. A tile is basically just a 64x64 pixel region of the drawable. The reason Gimp breaks the image into small pieces like this is so that the whole image doesn't have to be loaded into memory in order to alter one part of it. This becomes important with larger images.

In Gimp-Python, you would use Tiles if you wanted to perform some low level operation on the image, instead of using procedures in the PDB. This type of object gives a Gimp-Python plugin the power of a C plugin, rather than just the power of a Script-Fu script. Tile objects are created with either the drawable.get_tile() or drawable.get_tile2() functions. In this section, I will refer to a generic tile object named tile.


Pixel Regions

Pixel region objects give an interface for low level operations to act on large regions of an image, instead of on small 64x64 pixel tiles. In this section I will refer to a generic pixel region called pr. For an example of a pixel region's use, please see the example plugin whirlpinch.py.


Support Modules

This section describes the modules that help make using the gimp module easier. These range from a set of constants to storing persistent data.


The gimpplugin Module

This module provides the framework for writing Gimp plugins in Python. It gives more flexibility for writing plugins than the gimpfu module, but does not offer as many features (such as automatic GUI building).

To use this framework you subclass gimpplugin.plugin like so:

import gimpplugin
class myplugin(gimpplugin.plugin):
	def init(self):
		# initialisation routines
		# called when gimp starts.
	def quit(self):
		# clean up routines
		# called when gimp exits (normally).
	def query(self):
		# called to find what functionality the plugin provides.
		gimp.install_procedure("procname", ...)
	# note that this method name matches the first arg of
	# gimp.install_procedure
	def procname(self, arg1, ...):
		# do what ever this plugin should do

End Note

This package is not yet complete, but it has enough in it to be useful for writing plugins for Gimp. If you write any plugins that might be useful as examples, please mail me at james@daa.com.au.