#!/usr/bin/perl -w

use strict;
use warnings;
use Gimp;
use Gimp::Fu;

my %imagetype2layertype = (
   RGB,		RGB_IMAGE,
   GRAY,	GRAY_IMAGE,
   INDEXED,	INDEXED_IMAGE,
);

podregister {
  $drawable->is_layer or die "this plug-in only works for layers";
  $image->undo_group_start;
  # make sure something is selected
  $drawable->mask_bounds or $image->selection_all;
  my ($x1,$y1,$x2,$y2)=($drawable->mask_bounds)[1..4];
  my ($w,$h)=($x2-$x1,$y2-$y1);
  my $sel = $image->selection_save;
  $image->select_rectangle(CHANNEL_OP_REPLACE,$x1,$y1,$w,$h);
  $drawable->edit_copy;
  $image->select_item(CHANNEL_OP_REPLACE, $sel);
  $sel->remove_channel;
  my $copy = new Gimp::Image($w, $h, $image->base_type);
  $copy->undo_disable;
  my $draw = new Gimp::Layer(
    $copy, $w, $h,
    $imagetype2layertype{$image->base_type},
    "temporary layer", 100, NORMAL_MODE
  );
  $copy->insert_layer ($draw, 0, 1);
  $draw->edit_paste(0)->anchor;
  $copy->convert_indexed ($dither_type, MAKE_PALETTE, $colours, 1, 1, "");
  $draw->edit_copy;
  $drawable->edit_paste(1)->anchor;
  $copy->delete;
  $image->undo_group_end;
  ();
};

exit main;
__END__

=head1 NAME

ditherize - Dithers current selection

=head1 SYNOPSIS

<Image>/Filters/Noise/Ditherize...

=head1 DESCRIPTION

This script takes the current selection and dithers it just like convert
to indexed.

=head1 PARAMETERS

 [PF_RADIO, "dither_type", "The dither type (see gimp_image_convert_indexed)", 1,
   [none => 0, fs => 1, "fs/low-bleed" => 2, ordered => 3]],
 [PF_SLIDER, "colours",	"The number of colours to dither to", 10, [0, 256, 1, 1]],

=head1 IMAGE TYPES

RGB*, GRAY*

=head1 RATIONALE

This is quite convoluted, but I found no other way to do this than:

 create a new image & one layer
 copy & paste the layer
 ditherize new image
 copy & paste back

=head1 AUTHOR

Marc Lehmann

=head1 DATE

1.2

=head1 LICENSE

Marc Lehmann

Distributed under the same terms as Gimp-Perl.
