#!/usr/bin/env python

# gallery-simple.py 
#  Copyright (C) 2005 Carol Spears
# based on
# cgo-camera-gallery.py - A Gallery Generator
# Copyright (C) 2003 Manish Singh and Carol Spears
#
# 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 os
from stat import *

from gimpfu import *

gallery_template ="""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
  <title>%(photographer)s %(gallery_name)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;
         }         
   td{
        width:%(thumb_html_width)dpx;
         }         
    p.thumb {
      font-size:80%%;
      }
   ul li  {
     list-style-type:none;
     }
:link{
        text-decoration:none;
         }         
:visited{
        text-decoration:none;
         }         
 :active{
        text-decoration:none;
         }         
 a:hover{
        text-decoration:none;
         }         
  </style>
</head>

<body>
<h1>%(photographer)s</h1>
<h2>%(gallery_name)s</h2>
<table>
%(table_rows)s
</table>
</body>
</html>
"""

gallery_cell = """
      <td>
         <p class="thumb">
         <a href="%(filename)s">%(name)s</a><br></br>
         <a href="%(filename)s">
         <img alt="%(name)s" src="%(name)s-thumb.jpg"></img></a><br></br>
        [<a href="%(name)s-original.jpg">original</a>]</p>
      </td>
"""

image_template = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
  <title>%(gallery_name)s:%(name)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;
         }         
:link{
        text-decoration:none;
         }         
:visited{
        text-decoration:none;
         }         
 :active{
        text-decoration:none;
         }         
 a:hover{
        text-decoration:none;
         }         
  </style>
</head>

<body>
<table>
  <tr><td>
<h1>%(photographer)s</h1>
<h2>%(gallery_name)s</h2>
<h3>%(name)s</h3>
  </td><td>
<a href="%(name)s-original.jpg">
<img alt="%(name)s" src="%(name)s-screen.jpg"></img></a><br></br>
<p>[<a href="%(name)s-original.jpg">original</a>]</p>
  </td></tr>
</table>
<p><a href="%(gallery_name)s.html">back to %(gallery_name)s</a></p>
</body>
</html>
"""

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

    # For apache SSI XBitHack
    os.chmod(filename, 0755)

def save_jpeg(image, name, comment=""):
    jpeg_save_defaults = (0.75, 0.0, 1, 0, "", 1, 0, 0, 0)
    args = list(jpeg_save_defaults)
    args[4] = comment

    pdb.file_jpeg_save(image, image.active_layer, name, name, *args)

def calc_aspect_dim(dim, orig_dim, other_dim):
    return int(float(dim) / orig_dim * other_dim)

def calc_dims(image, image_info, screen_side, thumb_side):
    original_width = image.width
    original_height = image.height

    if original_width > original_height:
        screen_width = screen_side
        screen_height = calc_aspect_dim(screen_width, original_width, original_height)
        thumb_width = thumb_side
        thumb_height = calc_aspect_dim(thumb_width, original_width, original_height)

    else:
        screen_height = screen_side
        screen_width = calc_aspect_dim(screen_height, original_height, original_width)
        thumb_height = thumb_side
        thumb_width = calc_aspect_dim(thumb_height, original_height, original_width)

    vars = locals()

    for base in ('original', 'screen', 'thumb'):
        for suffix in ('width', 'height'):
            name = '%s_%s' % (base, suffix)
            image_info[name] = vars[name]

def fill_dims_from_file(page_location, image_info, screen_side, thumb_side):
    filename = os.path.join(page_location, image_info['original_image'])

    try:
        image = pdb.gimp_file_load(filename, filename)
        calc_dims(image, image_info, screen_side, thumb_side)
        gimp.delete(image)

        return 1

    except RuntimeError:
        return 0

def write_images(gallery_name, page_location, images_location, filenames, 
                 screen_side, thumb_side):
    images = []

    for filename in filenames:
        image_info = {'skip': 0} 

        images.append(image_info)

        imagefile = os.path.join(images_location, filename)
        basename = os.path.splitext(filename)[0]

        image_info['name'] =  basename
        image_info['filename'] = basename + '.html'


        image_info['original_image'] = basename + '-original.jpg'
        image_info['screen_image'] = basename + '-screen.jpg'
        image_info['thumb_image'] = basename + '-thumb.jpg'

        htmlfile = os.path.join(page_location, image_info['filename'])
        originalfile = os.path.join(page_location, image_info['original_image'])
        screenfile = os.path.join(page_location, image_info['screen_image'])
        thumbfile = os.path.join(page_location, image_info['thumb_image'])

        image_mtime = os.stat(imagefile)[ST_MTIME]

        try:
            html_mtime = os.stat(htmlfile)[ST_MTIME] 
        except OSError:
            html_mtime = 0

        if html_mtime > image_mtime:
            if fill_dims_from_file(page_location, image_info,
                                   screen_side, thumb_side):
                image_info['skip'] = 1

                print "Already processed %s..." % imagefile
                continue
        
        print "Processing %s..." % imagefile

        image = pdb.gimp_file_load(imagefile, imagefile)
        image.flatten()

        if image.active_layer.is_indexed:
            pdb.gimp_convert_rgb(image)

        calc_dims(image, image_info, screen_side, thumb_side)
        
        comment_text = 'The image was touched by TheGIMP!'
        comment = "%s\nSource: %s" % (comment_text, filename)
        save_jpeg(image, originalfile, comment)

        pdb.gimp_image_scale(image,
                             image_info['screen_width'],
                             image_info['screen_height'])
        save_jpeg(image, screenfile, comment)

        pdb.gimp_image_scale(image,
                             image_info['thumb_width'],
                             image_info['thumb_height'])
        save_jpeg(image, thumbfile, comment)


        gimp.delete(image)

    return images

def write_pages(page_location, images, html_info):
    
    info = []
    info = html_info
    
    for image in images:
        if not image['skip']:
            info.update(image)

            htmlfile = os.path.join(page_location, image['filename'])
            write_html(htmlfile, image_template, info)

def write_gallery(page_location, images, html_info, per_row):

    table_rows = []

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

        for image in images[i:i+per_row]:
            row.append(gallery_cell % image)

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

    html_info['table_rows'] = '\n'.join(table_rows)

    gallery_page = html_info['gallery_name'] + '.html'
    htmlfile = os.path.join(page_location, gallery_page)
    write_html(htmlfile, gallery_template, html_info)


def write_gallery_simple_html(photographer, gallery_name, 
                              page_location, images_location, 
                              screen_side, thumb_side, per_row):
    old_fg = pdb.gimp_context_get_foreground()
    old_bg = pdb.gimp_context_get_background()
    new_fg = (0,0,0)
    new_bg = (255,255,255)
    pdb.gimp_context_set_foreground(new_fg)    
    pdb.gimp_context_set_background(new_bg)
    
    thumb_html_width = thumb_side + 24
    
    html_info = {'photographer': photographer, 
                 'gallery_name': gallery_name, 
                 'thumb_html_width': thumb_html_width}


    filenames = []
    for filename in os.listdir(images_location):
        if filename.endswith('.xcf'):
            filenames.append(filename)

    filenames.sort()

    images = write_images(gallery_name, page_location, images_location, filenames,
                          screen_side, thumb_side)

    write_pages(page_location, images, html_info)
    write_gallery(page_location, images, html_info, per_row)


    pdb.gimp_context_set_foreground(old_fg)    
    pdb.gimp_context_set_background(old_bg)
 

register(
        "python_fu_gallery_simple_html",
        "Makes a simple thumbnailed xhtml image gallery.",
        "Makes a simple thumbnailed xhtml image gallery.",
        "Carol Spears",
        "Carol Spears",
        "2005",
        "<Toolbox>/Xtns/Python-Fu/SimpleGallery",
        "",
        [
        (PF_STRING, "photographer", "Photographer Name", "YourName"),
        (PF_STRING, "gallery_name", "Gallery Title", "GallerySubject"),
        (PF_FILE, "page_location", "Where the page should land.", ""),
        (PF_FILE, "images_location", "Location of the images", ""),
        (PF_INT, "screen_side", "Maximum width or height (in pixels) for screen sized images", 432),
        (PF_INT, "thumb_side", "Maximum width or height (in pixels) for thumbnails", 100),
        (PF_INT, "per_row", "Images per row", 5)
#        (PF_RADIO, "extension", "The format of the images: {jpg, png}", "jpg", (("jpg", "jpg"), ("png", "png"))),
        ],
        [],
        write_gallery_simple_html)

main()
