NAME

Gimp - Write GIMP extensions/plug-ins/load- and save-handlers in Perl

SYNOPSIS

  use Gimp;
  use Gimp::Fu;         # easy scripting environment

  podregister {
    # your code
    my $image = new Gimp::Image (600, 300, RGB);
    my $bg = $image->layer_new(
      600,300,RGB_IMAGE,"Background",100,LAYER_MODE_NORMAL_LEGACY
    );
    $image->insert_layer($bg, 1, 0);
    $image->edit_fill($bg, FILL_FOREGROUND);
    eval { Gimp::Display->new($image); };
    $image;
  };

  exit main;
  __END__
  =head1 NAME

  example_function - Short description of the function

  =head1 SYNOPSIS

  <Image>/File/Create/Patterns/Example...

  =head1 DESCRIPTION

  Longer description of the function...

DESCRIPTION

Gimp-Perl is a module for writing plug-ins, extensions, standalone scripts, and file-handlers for the GNU Image Manipulation Program (GIMP). It can be used to automate repetitive tasks, achieve a precision hard to get through manual use of GIMP, interface to a web server, or other tasks that involve GIMP.

It is developed on Linux, and should work with similar OSes. This is a release of Gimp-Perl for gimp-2.8. It is not compatible with version 2.6 or below of GIMP.

To jump straight into how to write GIMP plugins, see Gimp::Fu: it is recommended for scripts not requiring custom interfaces or specialized execution. If you do need a custom interface, see examples/example-no-fu - although Gimp::Fu does also offer custom widgets, see the same script using Gimp::Fu in examples/fade-alpha. Lots of other examples are in the examples/ directory of your gimp-perl source tree, some of which will be installed in your plug-ins directory if you are running from a package.

Using the Help/Procedure Browser is a good way to learn GIMP's Procedural Database (PDB). For referencing functions you already know of, the included script gimpdoc is useful. Be warned Gimp-Perl does not allow use of deprecated GIMP procedures. You'll thank me in time.

Some highlights:

  • Access to GIMP's Procedural Database (PDB) for manipulation of most objects.

  • Program with either a fully object-oriented syntax, or a (deprecated) plain PDB (scheme-like) interface.

  • Scripts that use Gimp::Fu can be accessed seamlessly either from GIMP's menus, other scripting interfaces like Script-Fu, or from the command line (execute the plugin with the --help flag for more information).

    In the latter case, Gimp::Fu can either connect to a GIMP already running, or start up its own.

  • Access the pixel-data functions using PDL (see Gimp::PixelRgn) giving the same level of control as a C plug-in, with a data language wrapper.

  • Over 50 example scripts to give you a good starting point, or use out of the box.

IMPORT TAGS

Place these in your use Gimp qw(...) command to have added features available to your plug-in.

:consts

All constants found by querying GIMP (BG_IMAGE_FILL, RUN_NONINTERACTIVE, LAYER_MODE_NORMAL_LEGACY, PDB_INT32 etc.).

:param

Import constants for plugin parameter types (PDB_INT32, PDB_STRING etc.) only.

net_init=options

This is how to use Gimp-Perl in "net mode". Previous versions of this package required a call to Gimp::init. This is no longer necessary. The technical reason for this change is that when Gimp.pm loads, it must connect to GIMP to load its constants, like PDB_INT32.

Possible options include spawn/gui or unix/path/to/socket. See "ENVIRONMENT" in Gimp::Net for other possibilities. If this is not specified, Gimp will try various options, falling back to spawn which starts a new GIMP instance.

It is important that Gimp be able to connect to an instance of GIMP one way or another: otherwise, it will not be able to load the various constants on which modules rely. The connection is made when Gimp::import is called, after Gimp has been compiled - so don't put use Gimp ();

spawn_options=options

Set default spawn options to options, see Gimp::Net.

:DEFAULT

The default set: ':consts', 'N_', '__'. ('__' is used for i18n purposes).

''

Over-ride (don't import) the defaults.

:auto (DEPRECATED)

Import constants as above, as well as all libgimp and PDB functions automagically into the caller's namespace. This will overwrite your AUTOLOAD function, if you have one. The AUTOLOAD function that gets installed can only be used with PDB functions whose first argument is a reference (including objects):

 use Gimp qw(:auto);
 Gimp->displays_flush; # fine
 my $name = $layer->get_name; # also fine
 gimp_quit(0); # will lose its parameter, due to Perl's OO implementation!
 Gimp->quit(0); # works correctly
 gimp_image_undo_disable($image); # as does this, by a coincidence

This tag is deprecated, and you will be far better off using Gimp-Perl solely in OO mode.

:pollute (DEPRECATED)

In previous version of gimp-perl, you could refer to GIMP classes as either e.g. Gimp::Image, and as Image. Now in order to not pollute the namespace, the second option will be available only when this option is specified.

ARCHITECTURE

There are two modes of operation: the perl is called by GIMP (as a plugin/filter) ("plugin mode"), or GIMP is called by perl (which uses the Gimp::Net functionality) - either connecting to an existing GIMP process ("net mode"), or starting its own one ("batch mode").

Plugin

There are four "entry points" into GIMP plugins: init, query, run, and quit. Gimp-Perl provides hooks for the last 3; the first is implicitly done as the script executes, then either query or run, then quit on exit.

The perl script is written as a plug-in, probably using Gimp::Fu. GIMP, on start-up, runs all the plug-ins in its plugins directory at startup (including all the perl scripts) in "query" mode.

Any plugin will register itself as a GIMP "procedure" in the PDB, during its run in "query" mode.

When such a procedure is called, either from the menu system or a scripting interface, the plugin will be run in "run" mode, and GIMP will supply it with the appropriate arguments.

From outside GIMP

The script will use Gimp as above, and use GIMP functions as it wishes. If you are using GIMP interactively, you need to run the Perl Server (under "Filters/Perl") to allow your script to connect. Otherwise, the script will start its own GIMP, in "batch mode". Either way, your script, when it uses GIMP procedures (and Gimp-Perl functions), will actually be communicating with the Perl server running under GIMP.

The architecture may be visualised like this:

 perlscript <-> Gimp::Net <-> Perl-Server <-> Gimp::Lib <-> GIMP

This has certain consequences; native GIMP objects like images and layers obviously persist between Perl method calls, but libgimp entities such as GimpDrawable, with the perl interface Gimp::PixelRgn, require special handling. Currently they do not work when used over Gimp::Net.

OUTLINE OF A GIMP PLUG-IN

All plug-ins (running in "plugin mode") must finish with a call to Gimp::main.

The return code should be immediately handed out to exit:

 exit Gimp::main;

It used to be the case that before the call to Gimp::main, no other PDB function could be called. This is no longer the case (see "net_init=options"), but there is no point in doing so outside of a "run" hook (unless you have the privilege and joy of writing test modules for Gimp-Perl!).

In a Gimp::Fu-script, it will actually call Gimp::Fu::main instead of Gimp::main:

 exit main; # Gimp::Fu::main is exported by default when using Gimp::Fu

This is similar to Gtk, Tk or similar modules, where you have to call the main eventloop.

Although you call exit with the result of main, the main function might not actually return. This depends on both the version of GIMP and the version of the Gimp-Perl module that is in use. Do not depend on main to return at all, but still call exit immediately.

CALLBACKS

The Gimp module provides routines to be optionally filled in by a plug-in writer. This does not apply if using Gimp::Fu, as these are done automatically. These are specifically how your program can fit into the model of query, run and quit hooks.

The additional on_proc is how to supply code that will be run every time a GIMP PDB call is made. This is mainly useful for updating the progress bar on a plugin.

Gimp::on_query

Do any activities that must be performed at GIMP startup, when the plugin is queried. Should typically have at least one call to Gimp->install_procedure.

Gimp::on_net

Run when the plugin is executed from the command line, either in "net mode" via the Perl-Server, or "batch mode".

Gimp::on_lib

Run only when called from within GIMP, i.e. in "plugin mode".

Gimp::on_run

Run when anything calls it (network or lib).

Gimp::on_quit

Run when plugin terminates - allows a plugin (or extension, see below) to clean up after itself before it actually exits.

Gimp::on_proc

Run each time a PDB call is made. Currently only operates in "lib mode".

OUTLINE OF A GIMP EXTENSION

A GIMP extension is a special type of plugin. Once started, it stays running all the time. Typically during its run-initialisation (not on query) it will install temporary procedures. A module, Gimp::Extension, has been provided to make it easy to write extensions.

If it has no parameters, then rather than being run when called, either from a menu or a scripting interface, it is run at GIMP startup.

An extension can receive and act on messages from GIMP, unlike a plugin, which can only initiate requests and get responses. This does mean the extension needs to fit in with GIMP's event loop (the Glib event loop in fact - use this by using Gtk2). This is easy. In its run hook, the extension simply needs to run Gimp->extension_ack after it has initialised itself (including installing any temporary procedures). Then, if it wants to just respond to GIMP events:

  # to deal only with GIMP events:
  Gimp->extension_ack;
  Gimp->extension_process(0) while 1;

or also other event sources (including a GUI, or Glib::IO):

  # to deal with other events:
  Gimp::gtk_init;
  Gimp->extension_ack; # GIMP locks until this is done
  Gimp->extension_enable; # adds a Glib handler for GIMP messages
  my $tcp = IO::Socket::INET->new(
    Type => SOCK_STREAM, LocalPort => $port, Listen => 5, ReuseAddr => 1,
    ($host ? (LocalAddr => $host) : ()),
  ) or die __"unable to create listening tcp socket: $!\n";
  Glib::IO->add_watch(fileno($tcp), 'in', sub {
    warn "$$-setup_listen_tcp WATCHER(@_)" if $Gimp::verbose;
    my ($fd, $condition, $fh) = @_;
    my $h = $fh->accept or die __"unable to accept tcp connection: $!\n";
    my ($port,$host) = ($h->peerport, $h->peerhost);
    new_connection($h);
    slog __"accepted tcp connection from $host:$port";
    &Glib::SOURCE_CONTINUE;
  }, $tcp);
  Gtk2->main; # won't return if GIMP quits, but
              # GIMP will call your quit callback

A working, albeit trivial, example is provided in examples/example-extension. A summarised example:

  use Gimp;
  Gimp::register_callback extension_gp_test => sub {
    # do some relevant initialisation here
    Gimp->install_temp_proc(
      "perl_fu_temp_demo", "help", "blurb", "id", "id", "2014-04-11",
      "<Toolbox>/Xtns/Perl/Test/Temp Proc demo", undef,
      &Gimp::TEMPORARY,
      [ [ &Gimp::PDB_INT32, 'run_mode', 'Run-mode', 0 ], ],
      [],
    );
    Gimp->extension_ack;
    Gimp->extension_process(0) while 1;
  };
  Gimp::register_callback perl_fu_temp_demo => sub {
    my ($run_mode) = @_;
    # here could bring up UI if $run_mode == RUN_INTERACTIVE
  };
  Gimp::on_query {
     Gimp->install_procedure(
        "extension_gp_test", "help", "blurb", "id", "id", "2014-04-11",
        undef, undef,
        &Gimp::EXTENSION,
        [], [],
     );
  };
  exit Gimp::main;

A more substantial, working, example can be seen in the Perl Server extension that enables "net mode": examples/Perl-Server.

AVAILABLE GIMP FUNCTIONS

There are two different flavours of GIMP functions: those from the Procedural Database (the PDB), and functions from libgimp (the C-language interface library).

You can get a listing and description of every PDB function by starting GIMP's Help/Procedure Browser extension. Perl requires you to change "-" (dashes) to "_" (underscores).

OBJECT-ORIENTED SYNTAX

Gimp-Perl uses some tricks to map the procedural PDB functions onto full classes, with methods. These effectively implement object-oriented C, not coincidentally in the style of Glib Objects. GIMP plans to move to fully supporting Glib Objects, which may mean some (or no) changes to the Gimp-Perl programming interface. The OO interface may well become stricter than the current quite thin mapping. This is why the :auto method of accessing GIMP functions is deprecated.

Therefore, the guidance is that if you can do it as an object method, do - and use the shortest method name that works; no gimp_, no gimp_layer_, etc. The key indication is whether the first argument is an object of the classes given below, and the GIMP function call: gimp_image_* is always either an image object method, or a class method. If the first two arguments are an image and a drawable, call the method on the drawable, with the exception of gimp_image_insert_layer, which we can tell from the prefix is an image method.

If you can't, use a deeper class than just Gimp: Gimp::Context, etc. Otherwise, you have to use Gimp->, and that's fine.

AVAILABLE CLASSES

Classes for which objects are created:

  Gimp::Base # purely virtual
    +-Gimp::Color
    +-Gimp::Image
    +-Gimp::Selection
    +-Gimp::Display
    +-Gimp::Parasite
    +-Gimp::Item
        +-Gimp::Vectors
        +-Gimp::Drawable
          +-Gimp::Layer
          +-Gimp::Channel

Classes for which non-PDB objects are created (see Gimp::PixelRgn):

  Gimp::GimpDrawable
  Gimp::PixelRgn
  Gimp::Tile

Classes for which objects are not created:

  Gimp
  Gimp::Brush
  Gimp::Brushes
  Gimp::Context
  Gimp::Edit
  Gimp::Gradient
  Gimp::Gradients
  Gimp::Palette
  Gimp::Pattern
  Gimp::Patterns
  Gimp::Plugin
  Gimp::Progress

Gimp::Base

Methods:

$object->become($class)

Allows an object of one class to change its class to another, but with the same ID. If a method call of is_valid returns false, an exception will be thrown. It is intended for use in plugins, e.g. where GIMP passes a Gimp::Drawable, but you need a Gimp::Layer:

  my ($image, $drawable, $color) = @_;
  $drawable->become('Gimp::Layer'); # now can call layer methods on it

Returns $object.

$class->existing($id)

Allows you to instantiate a Gimp-Perl object with the given $class and $id. The same check as above is done, throwing an exception if failed.

$object->id

Returns the underlying GIMP identifier, an integer.

$object->is_valid

Returns true if the object is a valid object of the relevant class. Subclasses use appropriate GIMP functions: e.g. Gimp::Layer uses gimp_item_is_layer.

stringify

It also provides a "stringify" overload method, so debugging output can be more readable.

Gimp::Parasite

Self-explanatory methods:

$parasite = Gimp::Parasite->new($name, $flags, $data)

$name and $data are perl strings, flags is the numerical flag value.

$parasite->name

$parasite->flags

$parasite->data

$parasite->has_flag($flag)

$parasite->is_type($type)

$parasite->is_persistent

$parasite->is_error

$different_parasite = $parasite->copy

$parasite->compare($other_parasite)

SPECIAL METHODS

Some methods behave differently from how you'd expect, or methods uniquely implemented in Perl (that is, not in the PDB). All of these must be invoked using the method syntax (Gimp-> or $object->).

Gimp->install_procedure

Takes as parameters (name, blurb, help, author, copyright, date, menu_path, image_types, type, params[, return_vals]).

Mostly the same as gimp_install_procedure from the C library. The parameters and return values for the functions are each specified as an array ref containing array-refs with three elements, [PARAM_TYPE, "NAME", "DESCRIPTION"], e.g.:

  Gimp::on_query {
     Gimp->install_procedure(
        $Gimp::Net::PERLSERVERPROC, "Gimp-Perl scripts net server",
        "Allow scripting GIMP with Perl providing Gimp::Net server",
        "Marc Lehmann <pcg\@goof.com>", "Marc Lehmann", "1999-12-02",
        N_"<Image>/Filters/Languages/_Perl/_Server", undef,
        $Gimp::Net::PERLSERVERTYPE,
        [
         [&Gimp::PDB_INT32, "run_mode", "Interactive, [non-interactive]"],
         [&Gimp::PDB_INT32, "flags", "internal flags (must be 0)"],
         [&Gimp::PDB_INT32, "extra", "multi-purpose"],
         [&Gimp::PDB_INT32, "verbose", "Gimp verbose var"],
        ],
        [],
     );
  };

This will remove the full menu path (up to the last /) and call gimp_plugin_menu_register with it behind the scenes.

Gimp::Progress->init(message,[display])

Gimp::Progress->update(percentage)

Initializes or updates a progress bar. In networked modules these are a no-op.

Gimp::Image->list

$image->get_layers

$image->get_channels

These functions return what you would expect: an array of images, layers or channels. The reason why this is documented is that the usual way to return PDB_INT32ARRAYs would be to return a reference to an array of integers, rather than blessed objects:

  perl -MGimp -e '@x = Gimp::Image->list; print "@x\n"'
  # returns: Gimp::Image->existing(7) Gimp::Image->existing(6)

$drawable->bounds, $gdrawable->bounds

Returns an array (x,y,w,h) containing the upper left corner and the size of currently selected parts of the drawable, just as needed by Gimp::PixelRgn->new and similar functions. Exist for objects of both Gimp::Drawable and Gimp::GimpDrawable.

NORMAL METHODS

If you call a method, Gimp tries to find a GIMP function by prepending a number of prefixes until it finds a valid function:

 $image = Gimp->image_new(...); # calls gimp_image_new(...)
 $image = Gimp::Image->new(...); # calls gimp_image_new as well
 $image = new Gimp::Image(...); # the same in green
 Gimp::Palette->set_foreground(...); # calls gimp_palette_set_foreground(..)
 $image->histogram(...); # calls gimp_histogram($image,...), since
                         # gimp_image_histogram does not exist

Return values from functions are automatically blessed to their corresponding classes, e.g.:

 $image = new Gimp::Image(...); # $image is now blessed to Gimp::Image
 $image->height;                # calls gimp_image_height($image)
 $image->flatten;               # likewise gimp_flatten($image)

The object argument ($image in the above examples) is prepended to the argument list - this is how Perl does OO.

Another shortcut: many functions want a (redundant) image argument, like

 $image->shear ($layer, ...)

Since all you want is to shear the $layer, not the $image, this is confusing as well. In cases like this, Gimp-Perl allows you to write:

 $layer->shear (...)

And automatically infers the additional IMAGE-type argument.

Because method call lookup also search the plug_in_, perl_fu_ and script_fu_ namespaces, any plugin can automatically become a method for an image or drawable (see below).

As the (currently) last goodie, if the first argument is of type INT32, its name is "run_mode" and there are no other ambiguities, you can omit it, i.e. these five calls are equivalent:

 plug_in_gauss_rle(RUN_NONINTERACTIVE, $image, $layer, 8, 1, 1);
 plug_in_gauss_rle($image, $layer, 8, 1, 1);
 plug_in_gauss_rle($layer, 8, 1, 1);
 $layer->plug_in_gauss_rle(8, 1, 1);
 $layer->gauss_rle(8, 1, 1);

You can call all sorts of sensible and not-so-sensible functions, so this feature can be abused:

 patterns_list Gimp::Image;     # will call gimp_patterns_list
 quit Gimp::Plugin;             # will quit the Gimp, not an Plugin.

there is no image involved here whatsoever...

The 'gimpdoc' script will also return OO variants when functions are described. For example:

  gimpdoc image_new

has a section:

  SOME SYNTAX ALTERNATIVES
       $image = Gimp->image_new (width,height,type)
       $image = new Gimp::Image (width,height,type)
       $image = image_new Gimp::Display (width,height,type)

SPECIAL FUNCTIONS

In this section, you can find descriptions of special functions, functions that have unexpected calling conventions/semantics or are otherwise interesting. All of these functions must either be imported explicitly or called using a namespace override (Gimp::), not as methods (Gimp->).

Gimp::main()

Should be called immediately when perl is initialized. Arguments are not supported. Initializations can later be done in the init function.

Gimp::gtk_init()

Initialize Gtk in a similar way GIMP itself did. This automatically parses GIMP's gtkrc and sets a variety of default settings, including visual, colormap, gamma, and shared memory.

Gimp::set_rgb_db(filespec)

Use the given rgb database instead of the default one. The format is the same as the one used by the X11 Consortiums rgb database (you might have a copy in /usr/lib/X11/rgb.txt). You can view the default database with perldoc -m Gimp::ColorDB, at the end of the file; the default database is similar, but not identical to the X11 default rgb.txt.

Gimp::initialized()

this function returns true whenever it is safe to call GIMP functions. This is usually only the case after gimp_main has been called.

Gimp::register_callback(gimp_function_name, perl_function)

Using this function you can override the standard Gimp-Perl behaviour of calling a perl subroutine of the same name as the GIMP function.

The first argument is the name of a registered gimp function that you want to overwrite ('perl_fu_make_something'), and the second argument can be either a name of the corresponding perl sub ('Elsewhere::make_something') or a code reference (\&my_make).

Gimp::canonicalize_colour

Take in a color specifier in a variety of different formats, and return a valid GIMP color specifier (a GimpRGB), consisting of 3 or 4 numbers in the range between 0 and 1.0. Can also be called as /Gimp::canonicalize_color.

For example:

 $color = canonicalize_colour ("#ff00bb"); # html format
 $color = canonicalize_colour ([255,255,34]); # RGB
 $color = canonicalize_colour ([255,255,34,255]); # RGBA
 $color = canonicalize_colour ([1.0,1.0,0.32]); # actual GimpRGB
 $color = canonicalize_colour ('red'); # uses the color database

Note that bounds checking is somewhat lax; this assumes relatively good input.

gimp_tile_*, gimp_pixel_rgn_*, gimp_drawable_get

With these functions you can access the raw pixel data of drawables. They are documented in Gimp::PixelRgn.

server_eval(string)

This evaluates the given string in array context and returns the results. It's similar to eval, but with two important differences: the evaluating always takes place on the server side/server machine (which might be the same as the local one) and compilation/runtime errors are reported as runtime errors (i.e. throwing an exception).

PROCEDURAL SYNTAX (DEPRECATED)

To call PDB functions or libgimp functions, you can (but shouldn't) treat them like normal procedural perl (this requires the use of the :auto import tag - see ":auto (DEPRECATED)"):

 gimp_item_set_name($layer, 'bob'); # $layer is an object (i.e. ref) - works
 gimp_palette_set_foreground([20,5,7]); # works because of array ref
 gimp_palette_set_background("cornsilk"); # colour turned into array ref!

DEBUGGING AIDS

How to debug your scripts:

$Gimp::verbose

If set to true, will make Gimp-Perl say what it's doing on STDERR. If you want it to be set during loading Gimp.pm, make sure to do so in a prior BEGIN block:

 BEGIN { $Gimp::verbose = 1; }
 use Gimp;

Currently three levels of verbosity are supported:

  0: silence
  1: some info - generally things done only once
  2: all the info
GLib debugging

GIMP makes use of GLib. Environment variables including G_DEBUG, and setting G_SLICE to always-malloc, control some behaviour. See https://developer.gnome.org/glib/unstable/glib-running.html for details. Additionally, the behaviour of malloc can be controlled with other environment variables as shown at http://man7.org/linux/man-pages/man3/mallopt.3.html, especially setting MALLOC_CHECK_ (note trailing underscore) to 3.

SUPPORTED GIMP DATA TYPES

GIMP supports different data types like colors, regions, strings. In C, these are represented as (GIMP_PDB_ omitted for brevity - in Gimp-Perl, they are constants starting PDB_):

INT32, INT16, INT8, FLOAT, STRING

normal Perl scalars. Anything except STRING will be mapped to a Perl-number.

INT32ARRAY, INT16ARRAY, INT8ARRAY, FLOATARRAY, STRINGARRAY, COLORARRAY

array refs containing scalars of the same type, i.e. [1, 2, 3, 4]. Gimp-Perl implicitly swallows or generates a preceeding integer argument because the preceding argument usually (this is a de-facto standard) contains the number of elements.

COLOR

on input, either an array ref with 3 or 4 elements (i.e. [0.1,0.4,0.9] or [233,40,40]), a X11-like string ("#rrggbb") or a colour name ("papayawhip") (see "Gimp::set_rgb_db(filespec)").

DISPLAY, IMAGE, LAYER, CHANNEL, DRAWABLE, SELECTION, VECTORS, ITEM

these will be mapped to corresponding objects (IMAGE => Gimp::Image). In verbose output you will see small integers (the image/layer/etc..-ID)

PARASITE

represented as a Gimp::Parasite object (see above).

STATUS

Not yet supported, except implicitly - this is how exceptions (from "die") get returned in "net mode".

AUTHOR

Marc Lehmann <pcg@goof.com> (pre-2.0)

Seth Burgess <sjburge@gimp.org> (2.0+)

Kevin Cozens (2.2+)

Ed J (with oversight and guidance from Kevin Cozens) (2.3)

Ed J (2.3000_01+)

SEE ALSO

perl(1), gimp(1), Gimp::Fu, Gimp::PixelRgn, Gimp::UI, Gimp::Util, Gimp::Data, Gimp::Net, and Gimp::Lib.