#!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#

import string
import os
from gimpfu import *

resource_template_html ="""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
  <title>%(resource_title)s </title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
  <style type="text/css">
    body  {
      background-color:white;
      color:black;
      font-family:sans-serif;
      margin:5%%;
      }
   img {
        border:thin solid black;
	margin:auto;
         }         
    p.thumb {
      font-size:80%%;
      }
:link{
        text-decoration:none;
         }         
:visited{
        text-decoration:none;
         }         
 :active{
        text-decoration:none;
         }         
 a:hover{
        text-decoration:none;
         }         
  </style>
</head>

<body>
<h1>GIMP Resources %(resource_version)s</h1>
<h2>%(resource_title)s</h2>
<table>
%(table_rows)s
</table>
</body>
</html>
"""

table_cell = """
      <td>
         <p class="thumb">%(name)s<br></br>
         <img alt="%(resource_type)s-%(pname)s" src="%(resource_type)s-%(pname)s.png"></img></p>
      </td>
"""

def handle_list(name):
    resource_name = []
    rmspace = string.maketrans(" ","_")
    pname = string.translate(name, rmspace,'()#,?')
    resource_name = [name, pname]
    return pname, resource_name

def set_tools(bg_colour, fg_colour):
    version = pdb.gimp_version()
    old_settings = (gimp.get_foreground(),gimp.get_background(),pdb.gimp_context_get_brush(),
                    pdb.gimp_context_get_font(),pdb.gimp_context_get_gradient(),
                    pdb.gimp_context_get_palette(),pdb.gimp_context_get_pattern())
    
    pdb.gimp_context_set_background(bg_colour)
    pdb.gimp_context_set_foreground(fg_colour)
    return old_settings, version


def reset_tools(old_settings):
    old_fg,old_bg,old_brush,old_font,old_gradient,old_palette,old_pattern = old_settings
    pdb.gimp_context_set_background(old_bg)
    pdb.gimp_context_set_foreground(old_fg)
    pdb.gimp_context_set_brush(old_brush)
    pdb.gimp_context_set_font(old_font)
    pdb.gimp_context_set_gradient(old_gradient)
    pdb.gimp_context_set_palette(old_palette)
    pdb.gimp_context_get_pattern(old_pattern)


def write_html(filename, template, info):
    html = open(filename, 'w')
    html.write(template % info)
    html.close()

def make_image(image_width, image_height, layer_width, layer_height, name):
    image = pdb.gimp_image_new(image_width, image_height, RGB)
    drawable = pdb.gimp_layer_new(image, layer_width, layer_height, RGBA_IMAGE, name, 100, 0)
    image.add_layer(drawable, 0)

    pdb.gimp_edit_fill(drawable, BACKGROUND_FILL)
    return image, drawable

def save_as(image, drawable, resource_type, page_location, pname):
    save = resource_type + '-' + pname + '.png'
    saveable = os.path.join(page_location, save)
    pdb.gimp_file_save(image, drawable, saveable, save)
    pdb.gimp_image_delete(image)



def make_brush_images(brush_list, resource_type, bg_colour, fg_colour, page_location):
    resource_names = []
    for a in brush_list:

        pdb.gimp_context_set_brush(a)
        name = pdb.gimp_context_get_brush()
        pname, resource_name = handle_list(name)
        resource_names.append(resource_name)


# if anyone can figure out why i do this wacky image size stuff, feel free to email me carol@gimp.org
# to let me know.  I came up with this for the original script that ran in gimp-1.2 and left it here
# now because it worked.  thanks.
        brush_width, brush_height, mask_bpp, num_mask_bytes, mask_bytes, color_bpp, num_color_bytes, color_bytes = pdb.gimp_brush_get_pixels(name)
        image_width = brush_width + 31
        image_height = brush_height + 31
        layer_width = brush_width + 30
        layer_height = brush_height + 30
        center = (image_width)/2.0

        image, drawable = make_image(image_width, image_height, layer_width, layer_height, name)
        pdb.gimp_paintbrush_default(drawable, 2, [center, center])

        save_as(image, drawable, resource_type, page_location, pname)

    return resource_names
    

def make_resource_html(resource_names, resource_type, resource_version, resource_title, page_location, per_row):

    resource_info = {}
    resource_info = {'resource_type':resource_type,
                     'resource_version':resource_version,
                     'resource_title':resource_title}
    table_rows = []

    for i in range(0, len(resource_names), per_row):
        row = []

        for resource in resource_names[i:i+per_row]:
            name, pname = resource
            resource_name = {}
            resource_name = {'name':name, 
                             'pname':pname,
                             'resource_type':resource_type}
            row.append(table_cell % resource_name)

        table_rows.append('<tr>%s</tr>' % ''.join(row))

    resource_info['table_rows'] = '\n'.join(table_rows)
    htmlfile = os.path.join(page_location, resource_type + '.html')
    write_html(htmlfile, resource_template_html, resource_info)
           


def write_brushes_report(bg_colour, fg_colour, page_location, per_row):
    
    old_settings, version = set_tools(bg_colour, fg_colour)
    
    num_brushes, brush_list = pdb.gimp_brushes_get_list('')
    resource_names = []
    resource_type = 'brushes'
    resource_names = make_brush_images(brush_list, resource_type, bg_colour, fg_colour, page_location)
    resource_version = str(version)
    resource_title = 'GIMP Brushes'
    make_resource_html(resource_names, resource_type, resource_version, resource_title, page_location, per_row)


    reset_tools(old_settings)



register(
	"python_fu_brushes_xhtml",
	"Writes html and generates the sample brush images",
	"Writes html and generates the sample brush images",
	"Carol Spears",
	"Carol Spears",
	"2005",
	"<Toolbox>/Xtns/Python-Fu/Resources/BrushReport",
	"",
	[
		(PF_COLOR, "bg_colour", "Color of page background:", (255,255,255)),
		(PF_COLOR, "fg_colour", "Color of font (unused so far):", (0,0,0)),
        (PF_FILE, "page_location", "Spew the html into this directory:", ""),
        (PF_SPINNER, "per_row", "The number of brushes per html row:", 5, (1,20,1))
	],
	[],
	write_brushes_report)

# this section draws the small checkers checkerboard to display transparent gradients and patterns.
def make_background(image, drawable, fg_colour, bg_colour):
        check1, check2 = (153,153,153),(102,102,102)
        pdb.gimp_context_set_background(check1)
        pdb.gimp_context_set_foreground(check2)
        pdb.plug_in_checkerboard(image, drawable, 0, 4)
        pdb.gimp_context_set_background(bg_colour)
        pdb.gimp_context_set_foreground(fg_colour)
        return image, drawable


def make_gradient_images(gradient_list, resource_type, bg_colour, fg_colour, page_location):
    image_width = 64
    image_height = 32
    layer_width = 64
    layer_height = 32
    x1, y1, x2, y2 = 0, 16, 64, 16

    resource_names = []
    for a in gradient_list:

        pdb.gimp_context_set_gradient(a)
        name = pdb.gimp_context_get_gradient()
        pname, resource_name = handle_list(name)
        resource_names.append(resource_name)

        image, drawable = make_image(image_width, image_height, layer_width, layer_height, name)
        image, drawable = make_background(image, drawable, fg_colour, bg_colour)

# draw and save the gradient
        pdb.gimp_edit_blend(drawable, CUSTOM_MODE, NORMAL_MODE, GRADIENT_LINEAR, 100, 0, REPEAT_NONE, FALSE, FALSE, 0, 0, TRUE, x1, y1, x2, y2)
        save_as(image, drawable, resource_type, page_location, pname)

    return resource_names

def write_gradients_report(bg_colour, fg_colour, page_location, per_row):
    
    old_settings, version = set_tools(bg_colour, fg_colour)
    
    num_gradients, gradient_list = pdb.gimp_gradients_get_list('')
    resource_names = []
    resource_type = 'gradients'
    resource_names = make_gradient_images(gradient_list, resource_type, bg_colour, fg_colour, page_location)
    resource_version = str(version)
    resource_title = 'GIMP Gradients'
    make_resource_html(resource_names, resource_type, resource_version, resource_title, page_location, per_row)

    reset_tools(old_settings)





register(
	"python_fu_gradients_xhtml",
	"Writes html and generates the sample gradient images",
	"Writes html and generates the sample gradient images",
	"Carol Spears",
	"Carol Spears",
	"2005",
	"<Toolbox>/Xtns/Python-Fu/Resources/GradientReport",
	"",
	[
		(PF_COLOR, "bg_colour", "Color of page background:", (255,255,255)),
		(PF_COLOR, "fg_colour", "Color of font (unused so far):", (0,0,0)),
        (PF_FILE, "page_location", "Spew the html into this directory:", ""),
        (PF_SPINNER, "per_row", "The number of gradients per html row:", 5, (1,20,1))
	],
	[],
	write_gradients_report)



def make_pattern_images(pattern_list, resource_type, bg_colour, fg_colour, page_location):
    new_width = 32
    new_height = 32

    resource_names = []
    for a in pattern_list:
        pdb.gimp_context_set_pattern(a)
        name = pdb.gimp_context_get_pattern()
        width, height, bpp, num_color_bytes, color_bytes = pdb.gimp_pattern_get_pixels(name)
        pname, resource_name = handle_list(name)
        resource_names.append(resource_name)
        if width < height:
            sides = height
        else: 
            sides = width
        image, drawable = make_image(sides, sides, sides, sides, name)
        image, drawable = make_background(image, drawable, fg_colour, bg_colour)

# draw and save the gradient
        pdb.gimp_edit_fill(drawable, PATTERN_FILL)
        save_as(image, drawable, resource_type, page_location, pname)

    return resource_names



def write_patterns_report(bg_colour, fg_colour, page_location, per_row):
    
    old_settings, version  = set_tools(bg_colour, fg_colour)
    
    num_patterns, pattern_list = pdb.gimp_patterns_get_list('')
    resource_names = []
    resource_type = 'patterns'
    resource_names = make_pattern_images(pattern_list, resource_type, bg_colour, fg_colour, page_location)
    resource_version = str(version)
    resource_title = 'GIMP Patterns'
    make_resource_html(resource_names, resource_type, resource_version, resource_title, page_location, per_row)

    reset_tools(old_settings)





register(
	"python_fu_patterns_xhtml",
	"Writes html and generates the sample pattern images",
	"Writes html and generates the sample pattern images",
	"Carol Spears",
	"Carol Spears",
	"2005",
	"<Toolbox>/Xtns/Python-Fu/Resources/PatternReport",
	"",
	[
		(PF_COLOR, "bg_colour", "Color of page background:", (255,255,255)),
		(PF_COLOR, "fg_colour", "Color of font (unused so far):", (0,0,0)),
        (PF_FILE, "page_location", "Spew the html into this directory:", ""),
        (PF_SPINNER, "per_row", "The number of patterns per html row:", 5, (1,20,1))
	],
	[],
	write_patterns_report)





main()
