#!/usr/bin/perl

# <sjburges@gimp.org>
# This is tigert's request.  I suppose it'll be useful to those that do
# this sort of thing.  Personally I'll probably only run it to test and
# put up a demo image.

# Since updated a couple times by others, and intgrated by me:
# 
# Bruce Miller                              (fixed to accomdate 1.1.x changes)
# Brendon and Wendy Humphrey <brendy@swipnet.se> (progress bar, nice comments)
#
# Tuomas Kuosmanen <tigert@gimp.org>
# Fixed some things to make this work with cvs gimp. Fixed calls to
# gimp_get_guide_orientation() (guide types that changed from
# GUIDE_VERTICAL to VERTICAL and horizontal, respectively.  Should
# work now). Also convert to indexed parameters changed, fixed them too.
#
# <sjburges@gimp.org> 
# Added changes to make progess bar work for images with only horizontal
# or vertical guides.  This was fixed at one time, I forget who did that.
# Somehow it got broke again ;(
#
# Added File::Path; for making the directory if it doesn't already exist.
#
# If you have more additions, etc please don't hesitate to send them in!

use File::Path;

use Gimp;
use Gimp::Fu;
use Gimp::Util;

# Uncomment if you want to see everything that's going on.
# Gimp::set_trace(TRACE_ALL);

#
# Generates an ordered list of all existing vertical guides.
#
 
sub get_vguides {  
    my ($img)=@_;
    $i=0;
    my @vguides;
    while ($i=$img->find_next_guide($i)) {
        if ($img->get_guide_orientation($i) == &Gimp::VERTICAL){
            $keyval = sprintf("%4d", $img->get_guide_position($i));
            $vkeys{$keyval} = $i;
            }
        }
    foreach $key(sort (keys %vkeys)) {
        # print "Unshifting ",  $key, "\n";
        push @vguides, $vkeys{$key};
        }
    return @vguides;
    }

#
# Generates an ordered list of all existing horizontal guides.
#

sub get_hguides { 
    my ($img)=@_;
    $i=0;
    my @hguides;
    while ($i=$img->find_next_guide($i)) {
        if ($img->get_guide_orientation($i) == &Gimp::HORIZONTAL){
            $keyval = sprintf("%4d", $img->get_guide_position($i));
            $hkeys{$keyval} = $i;
            }
        }
    # need to sort them in order of their occurance in the image
    foreach $key(sort keys %hkeys) {
        push @hguides, $hkeys{$key};
        }
    return @hguides;
    }

#
# Duplicate, crop and save the image fragment.
#

sub dosel { 
    ($img, $savepath, $imgpath, $imgbasename, $l,$r,$t,$b, $i,$j) = @_;
    $filename =~ m/^(.*)\.[^\.]*$/ ;
    $imgname = "$imgbasename-$i-$j.gif";
    $tmpimg = $img->channel_ops_duplicate;
    # print "Cropping from $l to $r, $t to $b\n";
    $tmpimg->crop($r-$l, $b-$t, $l, $t);
    $tmplay = $tmpimg->active_drawable;
    if (! $tmplay->is_indexed) {
	# do this: fs/low-bleed dither, make palette, 256 colors, 
	# dont dither alpha, do remove unused (is 1 "true" here?),
	# custom palette is ignored (we create our own, thus "duck" works).
        $tmpimg->convert_indexed (2,0,256,0,1,duck) 
	}
    $tmpimg->gimp_file_save(-1,"$savepath$imgpath$imgname","$savepath$imgpath$imgname");
    $tmpimg->delete;
    return "$imgpath$imgname"; # what I want printed in html
    }

#
# HTML Table Generation Functions
#

sub html_table_start {
    ($fn,$cellpadding,$cellspacing,$border,$capatalize) = @_;
    $str = $capatalize ? 
"<TABLE CELLSPACING=$cellspacing CELLPADDING=$cellpadding BORDER=$border>\n" :
"<table cellspacing=$cellspacing cellpadding=$cellpadding border=$border>\n" ;
    print $fn $str;
    }

sub html_table_row_start {
    ($fn, $capatalize) = @_;
    $str = $capatalize ? "\t<TR>\n" : "\t<tr>\n";
    print $fn $str;
    }

sub html_table_entry {
    ($fn, $imgname, $width, $height, $capatalize) = @_;
    $str = $capatalize ? 
"\t\t<TD><IMG ALT=\" \" SRC=\"$imgname\" WIDTH=\"$width\" HEIGHT=\"$height\"></TD>\n" :
"\t\t<td><img alt=\" \" src=\"$imgname\" width=\"$width\" height=\"$height\"></td>\n";
    print $fn $str;
    }

sub html_table_row_end {
    ($fn, $capatalize) = @_;
    $str = $capatalize ? "\t</TR>\n" : "\t</tr>\n";
    print $fn $str;
    }

sub html_table_end {
    ($fn, $capatalize) = @_;
    $str = $capatalize ? "</TABLE>\n":"</table>\n";
    print $fn $str;
    }

# <tigert> Save-path: [_____________________][browse]
# <tigert> html-file name: [_________________]
# <tigert> image-basename [__________________]
# <tigert> [x] use separate dir for images
# <tigert> image directory: [___________________]

# later, decided to have UPPER/lower case HTML toggle
# cellspacing: ___^

register "perlotine",
 "Guilotine implemented ala perl, with html output",
 "Add guides to an image.  Then run this.  It will cut along the guides, and give you the html to reassemble the resulting images.",
 "Seth Burgess",
 "Seth Burgess <sjburges\@gimp.org>",
 "1999-03-19",
 N_"<Image>/Filters/Web/Perl-o-tine...",
 "*",
 [
  [PF_STRING, "save_path", "The path to export the HTML to",$ENV{HOME}],
  [PF_STRING, "html_file_name", "Filename to export","perlotine.html"],
  [PF_STRING, "image_basename", "What to call the images","perlotine"],
  [PF_TOGGLE, "separate_image_dir", "Use a separate directory for images?",0],
  [PF_STRING, "relative_image_path", "The path to export the images to, relative to the Save Path", "images/"],
  [PF_TOGGLE, "capitalize_tags", "Capatalize HTML tags?", 0],
  [PF_SPINNER, "cellspacing", "Add space between the table elements", 0, [0,15,1]],
  ], sub {

    my($img,$layer,$savepath, $htmlname, $imgbasename, $separate, $imgpath, $capatalize, $cellspacing) =@_;

    @vert = get_vguides($img);
    @horz = get_hguides($img);

    if (!(scalar(@vert) || scalar(@horz))) {
        die __"No horizontal or vertical guides found. Aborted.";
        }

   # 
   # Progress Bar
   # 

   Gimp->progress_init("Perl-o-Tine");
   $progress_increment = 1/( (scalar(@horz)+1) * (scalar(@vert)+1) );
   $progress = 0.0;
   
   # (Debugging info for the guide functions)

   # print @vert, " LEN = ", scalar(@vert), "\n";
   # print @horz, " LEN = ", scalar(@horz), "\n";
   # foreach $guide (@vert) {
   #        print $img->get_guide_position($guide), "\n";
   #        }

  #
  # Correctly format paths and filenames
  # 
  if (!($savepath=~ m,/$,)) {  # add a trailing slash if its not on there
      $savepath = $savepath . "/";
   }

   if (!($imgpath=~ m,/$,)) {  # add a trailing slash if its not on there
    $imgpath= $imgpath . "/";
   }
   if (!$separate) { $imgpath = ""; }

    # create paths if they don't already exist
    mkpath($savepath);
    mkpath($savepath . $imgpath);

    # open HTML file for writing 
    open FILE, ">$savepath$htmlname" or die "Couldn't open $savepath$htmlname: $!\n";

    $top=0;
    html_table_start(\*FILE,0,$cellspacing,0,$capatalize);
    for ($i=0; $i<=scalar(@horz); $i++) {
        $bot = ($i>$#horz) ? $img->height : $img->get_guide_position($horz[$i]);
        html_table_row_start(\*FILE, $capatalize);
        $left=0;
        for ($j=0; $j<=scalar(@vert); $j++) {
            $right = ($j>$#vert) ? $img->width : $img->get_guide_position($vert[$j]);
            $imgname = dosel($img, $savepath, $imgpath, $imgbasename, $left, $right, $top, $bot, $i, $j);
            html_table_entry(\*FILE, $imgname, $right-$left, $bot-$top, $capatalize);
            $left = $right + $cellspacing;

            # Increment the progress bar
            $progress += $progress_increment;
            Gimp->progress_update ($progress);
            }
        html_table_row_end(\*FILE, $capatalize);
        $top = $bot + $cellspacing;
        }
    html_table_end(\*FILE, $capatalize);
    return();
};
exit main;
