#!/bin/python
"""
$Id: gallery2.py,v 1.58 2005/06/05 20:29:52 pj Exp $

Description: Create a gallery of the pictures in a directory. 
             Both source and destination directory configurable.
             Full recursion in order to process directory hierarchies
             available.

Author:  Per Jensen, Net-Es, with help from kind people. See Changelog for
         details

Contact information: per@net-es.dk, http://www.net-es.dk

License: GNU GPL 2 - see http://www.gnu.org/licenses/gpl.txt for details

Synopsis: gallery.py [--sourcedir|-s dirname] [--destdir|-d dirname] 
                     [--title|-t "title"] [--columns|-c #] [--fullsize|-f]
                     [-r|--recurse]
                     [--from|-F "name <URL>"]
                     [--updateFromXML|-x filename]
                     [--width|-w #] [--thumbwidth|-u #] [--padding|-p #]
                     [--fgColor foregroundColor] [--bgColor backgroundcolor]
                     [--lnColor linkColor] [--lnVisitColor followedLinkColor]
                     [--faster] [--force] [--inputEncoding encoding]
                     [--help|-h] [--version|-v]

Dependencies:
  - Python 2.2
  - Python Imaging Library, 1.1.3, (1.1.4 for EXIF data extraction)
  
Options:
--sourcedir  | -s directory     picture source directory
--destdir    | -d directory     gallery directory location
--title      | -t title         assign title to index page, defaults to
                                dir name.
--recurse    | -r               Recurses through a hierarchy of directories.
                                Copies directory layout, if combined with
                                --destdir 
--columns    | -c # of columns  # of columns in table on index page (default 4)
--fullsize   | -f               include fullsize pictures (default no)
--gui        | -g               start simple GUI
--from       | -F "name <URL>"  add creator's name/link to footer,
                                <URL> may be ommited
                                e.g.: -F "me <mailto:me@somewhere.org>" | -F me
--width      | -w               width of resized pictures (default 640)
--thumbwidth | -u               width of thumbnails (default 160)
--padding    | -p               cellpadding in table (default 5 pixels)
--fgColor                       Set foreground color
--bgColor                       Set background color
--lnColor                       Set link color
--lnVisitColor                  Set link color on already followed links
--hoverColor |                  Set hover and visited:hover color on links
--faster     |                  Use a faster resizing algorithm at the expense
                                of quality
--inputEncoding |		Name of encoding used in directory- and 
				filenames, as well as in textfiles. Defaults
				'mcbs' on Windows and 'utf-8' on Linux
--updateFromXML | -x            update gallery from xml file (gallery.xml).
                                XML file must be in the sourcedir
--force      |                  Force creation of gallery
--help       | -h               display this help page
--version    | -v               display version number
"""

import os, sys, getopt
import string
import gallery.galleries
import codecs

try:
    import gallery.gui
except:
    pass # OK we don't do the GUI
import gallery.functions
import gallery.defaultoptions
import Queue

VERSION=gallery.defaultoptions.version()

def version(versionstring):
    print "gallery2.py version: " + versionstring


def usage(full = 0):
    "Print help from __doc__ string"
    if full:
        print __doc__
    else:
        match = 0
        for l in string.split(__doc__, '\n'):
            if l[:11] == "Synopsis:" or match:
                match = 1
                if not string.strip(l):
                    break
                print l[12:]
    sys.exit()



if __name__ == '__main__':
    try:
        optlist, args = getopt.getopt(sys.argv[1:],'ghfrvxc:p:s:d:t:u:w:s:y:F:', ['help', 'gui', 'fullsize', 'force', 'version', 'dontrename', 'faster', 'recurse', 'updatefromXML',  'columns=', 'padding=', 'sourcedir=', 'destdir=', 'title=', 'fgColor=', 'bgColor=', 'lnColor=', 'lnVisitColor=', 'hoverColor=', 'from=', 'thumbwidth=', 'width=', 'xmlPrint=', 'inputEncoding='])
    except getopt.GetoptError:
        usage(1)
        sys.exit()


    props = gallery.defaultoptions.defaults()

    # get options
    for o, a in optlist:
        if o in("-g", "--gui"):
            props["gui"] = 1
        elif o in ("-s", "--sourcedir"):
            props["sourcedir"] = os.path.abspath(a)
            props["galleryDirectory"]= os.path.abspath(a)   #set dest default to srcdir
        elif o in ("-d", "--destdir"):
            props["galleryDirectory"] = os.path.abspath(a)
            props["baseDestinationDir"] = os.path.abspath(a)
        elif o in ("-t", "--title"):
            props["title"] = a
        elif o in ("-h", "--help"):
            usage(full = 1)
            sys.exit()
        elif o in ("-r", "--recurse"):
            props["recurse"] = 1
        elif o in ("-v", "--version"):
            version(VERSION)
            sys.exit()
        elif o in ("-c", "--columns"):
            props["columns"] = int(a)
        elif o in ("-f", "--fullsize"):
            props["fullsize"]='Yes'
        elif o in ("-dummy", "--force"):
            props["forcecreate"] = 1
        elif o in ("-w", "--width"):
            props["size"] = int(a)
        elif o in ("-u", "--thumbwidth"):
            props["thumbsize"] = int(a)
        elif o in ("-F", "--from"):
            props["creator"] = a
        elif o in ("-p", "--padding"):
            props["padding"] = a
        elif o in ("-x", "--updateFromXML"):
            props["updateFromXML"] = 1
        elif o == "--fgColor":
            props["fgColor"] = a
        elif o == "--bgColor":
            props["bgColor"] = a
        elif o =="--lnColor":
            props["lnColor"] = a
        elif o == "--lnVisitColor":
            props["lnVisitColor"] = a
        elif o == "--hoverColor":
            props["hoverColor"] = a
        elif o == "--faster":
            props["faster"] = 1
        elif o == "--inputEncoding":
            props["inputEncoding"] = a


    gallery.functions.init(props)
    requestqueue = Queue.Queue()
    resultqueue = Queue.Queue()

    sys.stdout = codecs.EncodedFile(sys.stdout, props['inputEncoding'], 'utf-8')
        
        
    if props["gui"]:
        gallery.gui.Gui(requestqueue, resultqueue, props).mainloop()
    else:
        g = gallery.galleries.Galleries(requestqueue, resultqueue, props)
        requestID = g.perform()
        msg = ""
        while 1:
            (requestID, msg, status) = resultqueue.get() # blocks until g put a tuple on the resultqueue
            if status == gallery.functions.status_working:
                print ".",
                sys.stdout.flush()
            elif (status == gallery.functions.status_finished) or (status == gallery.functions.status_finished_ok):
                sys.exit(0)
            else:
                print msg
