#!/usr/bin/perl
# thumbnailer.pl
#
# V1.0	12-07-2001   Original Version.
#
# Rewritten for GIMP 1.2 and the Graphics Muse Tools CD
# by Michael J. Hammel (mjhammel@graphics-muse.org
# Jan 26, 2002

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

eval 'exec /usr/app/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use Gimp qw(:auto __ N_);
use Gimp::Fu;
use Gimp::Util;
use File::Basename; #for fileparse()


#Gimp::set_trace(TRACE_ALL);

sub thumbnailer {
   my ($path, $bright, $contrast, $stretchHSV, $sharpen, $rotate, $scalefix, $fixed, $gallerytitle, $prefix, $postfix) = @_;
 
   $oldforeground=gimp_palette_get_foreground();
   $path=$path.'/';
   if ($path eq ""){
        Gimp->message(__"All fields were not completed, sorry.");
	exit main;
   }	
   if ($fixed == 0){
	Gimp->message(__"New Image size must be greater than 0.");
	exit main;	
   }	

   $countTotal=`ls $path*.jpg | wc -l`+`ls $path*.JPG | wc -l`;
   $gallerytitle=~s/ /_/g;	
   opendir(cpath, $path) or die ("Unable to open destination path");
   $sysval=system("mkdir $path$gallerytitle");
   if ($sysval != 0){
    	Gimp->message(__"Could not create the thumbnail directory. Maybe it already exists, or you do not have write acces to the current directory.");
	exit main;
   }
   my $dpath="$path$gallerytitle/";
   my $totalentries=0;

   Gimp->progress_init("Generating Thumbnails...");
   while (defined($cfile=readdir(cpath))) { 	
	   if (( $cfile =~ /.jpg/ ) || ($cfile =~ /.JPG/)) {
		   my $img=gimp_file_load(RUN_INTERACTIVE,"$path$cfile", "$path$cfile");
		   my $clayer=gimp_image_get_active_layer($img);
		   if ($rotate != 0){
			#plug_in_rotate manages both global 90-180-270 - reshape $img
			plug_in_rotate(RUN_NONINTERACTIVE,$img,-1,$rotate,1);
		   }  	

		   my $width=gimp_image_width($img);
		   my $height=gimp_image_height($img);		
		   gimp_brightness_contrast($clayer, $bright, $contrast);
		   if ($sharpen > 0) {
		     plug_in_sharpen(RUN_NONINTERACTIVE,$img,$clayer, $sharpen);
		   }
		   if ($stretchHSV) {
		     plug_in_autostretch_hsv(RUN_NONINTERACTIVE,$img,$clayer);
		   }
		
		   #Processing Thumbnail	
		   my $tbheight=1;
		   my $tbwidth=1; 	
		   if ($scalefix == 1){
				    my $scalefactor=$width/$fixed;
				    $tbheight=$height/$scalefactor;	
				    $tbwidth=$fixed;
			  }else{
				    if ($scalefix == 2) {
					   my $scalefactor=$height/$fixed;
					   my $newwidth=$width/$scalefactor;
					   $tbwidth=$newwidth;
					   $tbheight=$fixed;
				    }else {
					   # scalefix 0 => both scaled by factor (value_factor)
				      my $scalefactorx=$width/$fixed;
				      my $scalefactory=$height/$fixed;
				      if ($scalefactorx > $scalefactory) {
					   $tbwidth=$width/$scalefactorx;		    
					   $tbheight=$height/$scalefactorx;
				      } else{
					   $tbwidth=$width/$scalefactory;		    
					   $tbheight=$height/$scalefactory;
				      }
				    }	
		   }
		   ($tmpbase,$tmppath,$tmptype) = fileparse($cfile,'\..*');
		   my $tbfname="$dpath$prefix$tmpbase$postfix$tmptype";
		   gimp_image_scale($img, $tbwidth, $tbheight);
		   file_jpeg_save(RUN_NONINTERACTIVE,$img, ($img->get_layers)[0],"$tbfname", "$tbfname",0.7,0,1,0,"",0,1,0,0);
		   $totalentries=$totalentries+1;
		   Gimp->progress_update ($totalentries/$countTotal);
		   gimp_image_delete($img);	
	  }	
    }
    Gimp->progress_update(1);	
    Gimp->message(__"$totalentries thumbnails have been generated.");
    gimp_palette_set_foreground($oldforeground);
    return();
};

$help=<<EOF.$help;
This Gimp plug-in will generate thumbnails from a given directory of images (only .jpg images are supported). It can also do some image manipulation on the fly.

Choose the path to your source images.

Chose any image modification options (rotation, brightness, contrast, sharpening).

Choose which scaling method you like to use:
  "X or Y" takes the largest dimension of your image and 
  rescales it to the new size. 

  "X" or "Y" resizes the image to fit the horizontal or 
  vertical dimension respectively to the new value.

Type the name of the sub-directory where your thubnails will be created. If the directory already exists, an error is generated to avoid overwriting any images already present.

If you want, you can add a prefix or a postfix to the image name ("pre_name_post.jpg").
EOF

register("thumbnailer",
         "Generate thumbnails from JPEG image files.", 
         $help,
         "Philippe Piatkiewitz <fiepel\@xs4all.nl>",
         "(c) 2001 Philippe Piatkiewitz",
         "20010712",
         N_"<Toolbox>/Xtns/Render/Thumbnailer",
         "RGB*, GRAY*",
         [
          [PF_FILE,   "path", "Source path .... "],
	  [PF_SLIDER, "brightness", "Brightness correction", 0, [ -127, 127]],
	  [PF_SLIDER, "contrast", "Contrast correction", 0, [-127,127]],
	  [PF_TOGGLE, "stretchhsv", "Autostretch Contrast", 0],
	  [PF_SLIDER, "sharpen", "Sharpen", 0, [0,100]],
	  [PF_RADIO,  "rotate", "Rotation angle", 0, [ None => 0, Rotate90CCW => 3, Rotate90 => 1]],
	  [PF_RADIO,  "scalefix", "Scale fixing for thumbnails", 0 ,[ X_or_Y => 0, X => 1, Y => 2 ]],	
	  [PF_INT32,  "new_size", "New image size (pixels)", 150],
	  [PF_STRING, "subdir", "Subdirectory name", "thumbs" ],	
	  [PF_STRING, "prefix", "Image namne prefix" ],	
	  [PF_STRING, "postfix", "Image name postfix" ]	
         ],
	 \&thumbnailer);
exit main; 

__END__

=head1 NAME

Thumbnailer

=head1 SYNOPSIS

Thumbnailer generates thumbnails from image files in a given directory.

=head1 DESCRIPTION

Thumbnailer is a Gimp plugin. All images in a given source directory are resized and copied to a subdirectory.
This plugin currently only processes JPG pictures.
NOTE: This pluging is based on galery Maker by Fabian Frederick.

=head1 AUTHOR

Written by Philippe Piatkiewitz <fiepel\@xs4all.nl>, (c) 2001
