#!/usr/bin/python
# vim:set ai et sts=2 sw=2:
# vim600: set fdm=marker cms=#%s :
#
# This program creates with the same directories, a html gallery.
#  Thumbmails can be any size, aspect ratio is keep
#  Within each directory, we found several directories
#  one foreach resolution thumbail (800x600, ...)
#  html page is build under this name 
#
#
# Includes modules                                                         {{{
import getopt, os, sys, string, shutil, urllib, re
import Image, ImageFile
from stat import *
from array import array
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
""" Global options """#{{{
global options
options = {}
options['verbose_level'] = 0
options['output_directory'] = './photos'
options['comment_filename'] = '.comments'
options['thumbsize'] = (160,120)
options['sizelist'] = [(0,0) , (1024,768), (800,600), (640,480)]
options['forcecreate_html'] = 0
options['display_columns'] = 3
options['display_lines'] = 5
options['generate_root_index_html'] = 1
options['img_bgcolor'] = "blue"
options['body_bgcolor'] = "#ccccff"
options['exif'] = 1
options['exif_bordercolor'] = "#008000"
options['exif_bgcolor'] = "#f0fff0"
options['exif_fgcolor'] = "black"

photon_version = '0.2.0'

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
#
# Some main functions
#
def main():#{{{
  """ main procedure """
  global options

  short_opts="ho:vEd:Vl:s:t:If"
  long_opts=["help", "version", "output-directory=", "verbose", "no-exif",
             "display-columns=", "display-lines=","sizelist=","thumbsize",
             "no-index" , "body-bgcolor=", "img-bgcolor=", "exif-bordercolor=",
             "exif-bgcolor=", "exif-fgcolor=", "force"
             ]
  try:
    opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts)
  except getopt.GetoptError, msg:
    # print help information and exit:
    if msg:
      print msg
    usage()
    sys.exit(2)
  for o, a in opts:
    if o in ("-h", "--help"):
      usage()
      sys.exit()
    elif o in ("-V", "--version"):
      print "Photon",photon_version
      sys.exit()
    elif o in ("-o", "--output-directory"):
      options['output_directory'] = a
    elif o in ("-v", "--verbose"):
      options['verbose_level'] += 1
    elif o in ("-e", "--no-exif"):
      options['exif'] = 0
    elif o in ("-d", "--display-columns"):
      if a.isdigit():
        options['display_columns'] = a
      else:
        print "Bad argument:",a,"must be a number"
    elif o in ("-l", "--display-lines"):
      if a.isdigit():
        options['display_lines'] = a
      else:
        print "Bad argument:",a,"must be a number"
    elif o in ("-s", "--sizelist"):
      l=[]
      for s in a.split(','):
        if s=='0':
          l.append((0,0))
        else:
          m=re.search("^(\d+)x(\d+)$",s)
          if m:
            l.append((int(m.group(1)),int(m.group(2))))
          else:
            print "Bad size:",s,"must in the form 320x240"
      # End: for s in a.split(','):
      options['sizelist']=l
    elif o in ("-t", "--thumbsize"):
      m=re.search("^(\d+)x(\d+)$",s)
      if m:
        options['thumbsize']=((int(m.group(1)),int(m.group(2))))
      else:
        print "Bad size:",s,"must in the form 320x240"
    elif o in ("-I", "--no-index"):
      options['generate_root_index_html'] = 0
    elif o == "body-bgcolor":
      if match_color_type(a):
        options['body_bgcolor']=a
      else:
        print "Bad color:",a,"must in the form #0055ff or white"
    elif o == "img-bgcolor":
      if match_color_type(a):
        options['img_bgcolor']=a
      else:
        print "Bad color:",a,"must in the form #0055ff or white"
    elif o == "exif-bordercolor":
      if match_color_type(a):
        options['exif_bordercolor']=a
      else:
        print "Bad color:",a,"must in the form #0055ff or white"
    elif o == "exif-bgcolor":
      if match_color_type(a):
        options['exif_bgcolor']=a
      else:
        print "Bad color:",a,"must in the form #0055ff or white"
    elif o == "exif-fgcolor":
      if match_color_type(a):
        options['exif_fgcolor']=a
      else:
        print "Bad color:",a,"must in the form #0055ff or white"
    elif o in ("-f", "--force"):
      options['forcecreate_html']=1


  print_options()

  """ Compute some values before processing directory """
  options['sizelist'].append(options['thumbsize'])
  # Fix a bug when decompressing -> compressing a jpeg file
  ImageFile.MAXBLOCK = 1000000 # default is 64k

  for path in args:
    process_directory(path,"")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
def usage(): # {{{
  """ Print information to use this program """
  print """
  Usage: photon.py [OPTIONS] path...
    where OPTIONS are
    -h   --help                 Print this help
    -V   --version              Print Photon version
    -E   --no-exif              Don't include EXIF information in HTML file
    -d N --display-columns N    Set number of columns in index (default 3)
    -l N --display-lines N      Set number of lines in index (default 5)
    -s S --sizelist S           Image sizes (default 0,1024x768,800x600,640x480)
    -t S --sizelist S           Size of thumbnails (default 160x120).
    -I   --no-index             Do not generate the high level index.html (default no).
    -f   --force                Overwrite image files (default no).
         --body-bgcolor C       Background color (default #ccccff)
         --img-bgcolor C        Background color for image (default 'white')
         --exif-bordercolor C   Border color for the exif window (default #008000)
         --exif-bgcolor C       Background color for the exif window (default #f0fff0)
         --exif-fgcolor C       Text Color for the exif window (default 'black')
""" 
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
def print_options():#{{{
  """ Print Options array that contains all configurable options """
  global options

  if options['verbose_level'] >= 1:
    print "Program options:"
    for key in options.keys():
      print " ",key,options[key]
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
#
# Functions that work on an directory or on a file
#
def process_directory(realpath,relativepath): # {{{
  """ Generate thumbmails, html pages for this directory """
  global options

  directories_list = []
  images_list = []

  destdir = os.path.join(options['output_directory'],relativepath)
  safe_mkdir(destdir)

  sourcedir = os.path.join(realpath,relativepath)

  # For each images build alls sub-image,
  # for each directory, recurse into them
  for entry in os.listdir(sourcedir):
    if entry[0] == '.': # Don't accept directory or file beginning this a dot
      continue
    pathname = os.path.join(sourcedir,entry)
    mode = os.stat(pathname)[ST_MODE]
    if S_ISDIR(mode):
      process_directory(realpath,os.path.join(relativepath,entry))
      directories_list.append(entry)
    elif S_ISREG(mode):
      picinfo = process_file(realpath,relativepath,entry)
      if picinfo:
        images_list.append(picinfo)
    else:
      print 'Skipping %s' % pathname

  # Now, we have the complete list of directory, and files ... sort them
  images_list.sort(lambda x,y: cmp(x['filename'],y['filename']))
  directories_list.sort()
  # ... then generate html pages
  make_directory_html(relativepath,directories_list,images_list)
  if len(images_list)>0:
    make_image_html(relativepath,directories_list,images_list)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
def process_file(sourcedir,relativepath,filename): # {{{
  """ Create for this file all thumbmails and return the size of the image """
  global options

  srcfile = os.path.join(sourcedir,relativepath,filename)

  # Keep only Jpeg file (python cores dump with some PCD (kodak) file
  if ((string.rfind(string.lower(filename),".jpg")==-1) and
     (string.rfind(string.lower(filename),".jpeg")==-1)) :
    return None

  pic = {}
  try:
    im = Image.open(srcfile)
    print 'Processing image',srcfile, im.format, "%dx%d" % im.size, im.mode
  except IOError, err:
    print "cannot create thumbnail for",srcfile,"(",err.strerror,")"
  else:
    # Foreach size of the image, resize them only when it's different from Original
    pic['filename']=filename
    pic['original_size']=im.size
    if options['exif']:
      pic['exif'] = get_exif_information_from_file(srcfile)
    if im.size[1] > im.size[0]: # Keep aspect ration
      pic['ratio']=34
    else:
      pic['ratio']=43
    for (w,h) in options['sizelist']:
      if w == 0 and h == 0: # Special case when it is a original file
        subdir="%dx%d" % im.size
        destdir = os.path.join(options['output_directory'],relativepath,subdir)
        destfile = os.path.join(destdir,filename)
	if not compare_lastmodifiedtime(srcfile,destfile):
          safe_mkdir(destdir)
          shutil.copyfile(srcfile,destfile)
      else:
	if pic['ratio']==34:
          newsize=(h,w)
	else:
          newsize=(w,h)
        subdir='%dx%d' % (w,h)
        destdir = os.path.join(options['output_directory'],relativepath,subdir)
        destfile = os.path.join(destdir,filename)
	if not compare_lastmodifiedtime(srcfile,destfile):
          if w > im.size[0]: # Don't generate thumbmail when original file is smaller
            print "Skipping",srcfile,"for resolution %dx%d" % newsize
            continue
          safe_mkdir(destdir)
	  try:
            im.resize(newsize,Image.BICUBIC).save(destfile,'JPEG',optimize=1,progressive=1)
          except IOError, err:
            print "Error while writting Jpeg Optimize file, try to do without optimization, perhaps who can try to increase ImageFile.MAXBLOCK in the source file"
            try: # Try to save the Jpeg file without progessive option
              im.resize(newsize,Image.BICUBIC).save(destfile,'JPEG')
            except IOError, err:
              print "cannot create ",destfile,"(",err,")"
    return pic
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
def make_directory_html(relativepath, directories_list,images_list): # {{{
  """ Make all html page for index this directory """
  global options

  if relativepath == "" and not options['generate_root_index_html']:
    return

  images_processed=0 # Number of the images currently processed in the list
  page_index=0       # Number of index.html page currently processed
  total_images = len(images_list) + len(directories_list)
  items_per_page = options['display_columns'] * options['display_lines'];
  output_directory = os.path.join(options['output_directory'],relativepath)

  while images_processed < total_images:

    if images_processed == 0:
      index_html_filename = 'index.html'
    else:
      index_html_filename = 'index%d.html' % (images_processed / items_per_page)

    f=open(os.path.join(output_directory,index_html_filename),'w')
    output_index_html_header(f,relativepath)
    if images_processed == 0:
      output_index_html_directories(f,directories_list)
      total_images-=len(directories_list) # Small hack, because i want to do a do {} while(x)
    output_index_html_images(f,images_list[images_processed:images_processed+items_per_page])
    output_index_html_footer(f,page_index,images_processed,total_images)

    f.close()

    images_processed+=items_per_page
    page_index+=1

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def make_image_html(relativepath, directories_list,images_list): # {{{
  """ Make all html page for all images """
  global options

  make_blank_gif(os.path.join(options['output_directory'],relativepath,'blank.gif'))
  if options['exif']:
    make_exif_js(os.path.join(options['output_directory'],relativepath,'exif.js'))

  output_directory = os.path.join(options['output_directory'],relativepath)

  total_images = len(images_list)
  k=0

  while k < total_images:

    image = images_list[k]

    for resolution in options['sizelist']:

      image_html_filename=image_filename_to_image_htmlfilename(image['filename'],resolution)

      # Make the html page for this image and this resolution
      f=open(os.path.join(output_directory,urllib.unquote(image_html_filename)),'w')
      output_image_html_header(f,relativepath,image['filename'])
      output_image_html_body(f,relativepath,images_list,k,resolution)
      if options['exif']:
        output_image_html_exif_window(f,image)
      output_image_html_footer(f)
      f.close()
    # End: for resolution in options['sizelist']:

    k+=1

  # End: for image in images_list

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
#
# Functions that output HTML Code
#
def output_index_html_header(f,relativepath): # - - - - - - - - - - - - - - {{{
  """ Write in the file, header of an index.html page (body included) """
  global options

  if relativepath == "":
    html_title = "Albums";
  else:
    html_title = string.split(relativepath,os.sep)[-1];

  navbar = navbar_for_index_html(relativepath)

  f.write("""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
 <title>Photon: %s</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
</head>
<body bgcolor="%s">
<div align=center>
<table bgcolor="black">
<tr>
 <td>
  <table width="100%%" cellpadding=4>
  <tr bgcolor="%s">
   <td colspan=%s>%s</td>
  </tr>
""" % (html_title,options['body_bgcolor'],options['img_bgcolor'],
      options['display_columns'],navbar)) 
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def output_index_html_directories(f,directories_list): # - - - - - - - - - -{{{
  """ Output a HTML table that contains the directories list """
  global options

  column=0

  f.write('  <tr bgcolor="%s">\n' % options['img_bgcolor'])

  # Create a case for each directory
  for d in directories_list:
    if column >= options['display_columns']:
      f.write("  </tr>\n  <tr bgcolor=\"%s\">\n" % options['img_bgcolor']);
      column=0
    f.write('   <td align=center><a href="' + urllib.quote(d) + '/index.html"><b>' + d +
    '</b></a><br><img width=%d height=1 src="blank.gif" alt=""></td>' % options['thumbsize'][0])
    column+=1
  
  # Fill the empty case ...
  if column>0:
    while column < options['display_columns']:
      f.write('   <td><img width=%d height=1 src="blank.gif" alt=""></td>' % options['thumbsize'][0])
      column+=1
    # Close the row
    f.write('  </tr>\n')
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def output_index_html_images(f,images_list):  # - - - - - - - - - - - - - - {{{
  """ Output a HTML table that contains the images list """
  global options
  
  column=0

  f.write('  <tr bgcolor="%s">\n' % options['img_bgcolor'])

  # Create a case for each image
  for pic in images_list:
    if column >= options['display_columns']:
      f.write("  </tr>\n  <tr bgcolor=\"%s\">\n" % options['img_bgcolor']);
      column=0

    if pic['ratio']==34:
      thumbsize_width  = options['thumbsize'][1]
      thumbsize_height = options['thumbsize'][0]
    else:
      (thumbsize_width,thumbsize_height)=options['thumbsize']
 
    imgurl=urllib.quote(os.path.join("%dx%d" % options['thumbsize'],pic['filename']))
    i = string.find(pic['filename'],".") # Remove the extension for image filename
    imghtmlurl = urllib.quote(pic['filename'][0:i]) + '.html'

    f.write('   <td valign=bottom align=center>'
           + '<table border=0><tr><td bgcolor=black>'
           + '<a href="%s">' % imghtmlurl
           + '<img hspace=3 vspace=3 border=0 src="%s" alt="%s" width=%d height=%d>' 
             % (imgurl,pic['filename'],thumbsize_width,thumbsize_height)
           + '</a>'
           + '</td></tr></table>'
	   + '<br><a href="%s"> %s </a></td>\n' % (imghtmlurl,pic['filename']))
    column+=1

  # Fill the empty case ...
  if column>0:
    while column < options['display_columns']:
      f.write('   <td><img width=%d height=1 src="blank.gif" alt=""></td>' % options['thumbsize'][0])
      column+=1
    # Close the row
    f.write('  </tr>\n')
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def output_index_html_footer(f,page_index,images_processed,total_images): # {{{
  """ Output the footer for a index.html page """
  global options

  items_per_page = options['display_columns'] * options['display_lines'];
  f.write('  <tr bgcolor="%s">\n' % options['img_bgcolor'] +
          '   <td colspan=%s>\n' % options['display_columns'] +
          '    <table border=0 width="100%">\n    <tr>\n     <td>')
  # Output the Start and the Prev link
  if page_index==0:
    f.write('Start | Prev %s | ' % items_per_page)
  elif page_index==1:
    f.write('<a href="index.html">Start</a> | <a href="index.html">Prev %s</a> | ' % items_per_page)
  else:
    f.write('<a href="index.html">Start</a> | <a href="index%d.html">Prev %s</a> | ' % (page_index-1,items_per_page))

  # Output the Next link
  max_pages = total_images / items_per_page
  if (total_images % items_per_page) == 0:
    max_pages-=1
  if page_index<max_pages:
    f.write('<a href="index%d.html">Next %s</a> | ' % (page_index+1,items_per_page))
  else:
    f.write('Next %s | ' % items_per_page)

  # Output the End link
  if page_index<max_pages:
    f.write('<a href="index%d.html">End</a></td>' % max_pages)
  else:
    f.write('End</td>')

  # Output the Number of Images
  if total_images==0:
    f.write('<td align=right>&nbsp;</td>')
  else:
    max_images_displayed = images_processed+items_per_page
    if max_images_displayed > total_images:
      max_images_displayed = total_images
    f.write('<td align=right>Images %d to %d of %d</td>' 
       % (images_processed+1,max_images_displayed,total_images))

  f.write("""</td>
    </tr>
    </table>
   </td>
  </tr>
  </table>
 </td>
</tr>
</table>
<font size=-1>Generated by photon %s</font>
</div>
</body>
</html>
""" % photon_version)
          
   
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}

def output_image_html_header(f,relativepath,imagefilename): # - - - - - - - - {{{
  """ Write in the file, header of an image.html page (body included) """
  global options

  html_title = imagefilename;
  if options['exif']:
    script_exif='<script language="JavaScript1.2" src="exif.js"></script>'
    onload_exif='onload="exif_init()"'
  else:
    script_exif=''
    onload_exif=''

  f.write("""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
 <title>Photon: %s</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
 <style type="text/css">
   #exifwindow {position:absolute; height:1; width:1; top:0; left:0;}
 </style>
 %s
</head>
<body bgcolor="%s" %s>
""" % (html_title,script_exif,onload_exif,options['body_bgcolor']))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def output_image_html_body(f,relativepath,images_list,index,resolution): # - -{{{
  """ Output in the file f, the content of the body for this image """
  global photon_version,options

  imageinfo = images_list[index]
  if index==0:
    previous_image = None
  else:
    previous_image = images_list[index-1]

  if index+1>=len(images_list):
    next_image = None
  else:
    next_image = images_list[index+1]

  resolution_string = "%dx%d" % resolution

  if resolution_string == "0x0":
    resolution_string = "%dx%d" % imageinfo['original_size']
  image_urlname=urllib.quote(os.path.join(resolution_string,imageinfo['filename']));

  body = """<div align=center>
<table bgcolor="black">
<tr>
 <td>
  <table width="100%" cellpadding=4>
  <tr bgcolor="BODY_FGCOLOR">
   <td colspan=DISPLAY_COLUMNS>NAVBAR</td>
  </tr>
  <tr bgcolor="BODY_FGCOLOR">
   <td colspan=DISPLAY_COLUMNS><center><table border=0><tr><td bgcolor=black><img hspace=3 vspace=3 border=0 src="IMGSRC" alt="IMGALT"></td></tr></table></center></td>
  </tr>
  <tr bgcolor="BODY_FGCOLOR">
   <td colspan=DISPLAY_COLUMNS>XXX</td>
  </tr>
  </table>
 </td>
</tr>
</table>
<font size=-1>Generated by Photon PHOTON_VERSION</font>
</div>
"""

  body=body.replace("BODY_FGCOLOR",options['img_bgcolor'])
  body=body.replace("DISPLAY_COLUMNS","%d" % options['display_columns'])
  body=body.replace("IMGSRC",image_urlname)
  body=body.replace("IMGALT",imageinfo['filename'])
  body=body.replace("NAVBAR",navbar_for_image_html(relativepath,images_list,index))
  body=body.replace("PHOTON_VERSION",photon_version)
  body=body.replace("XXX",image_html_body_sub(imageinfo,resolution,previous_image,next_image))

  f.write(body)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def image_html_body_sub(imageinfo,resolution,previous_image,next_image): # -{{{
  """ Return the HTML code to display 2 thumbmails to include in the image page """
  global options

  content ="""
    <table border=0 width="100%">
    <tr>
     <td valign=top>LEFT_IMG</td>
     <td valign=top align=center>SIZE_LIST</td>
     <td valign=top align=right>RIGHT_IMG</td>
    </tr>
    </table>
   """
  if previous_image:
    thumblink = image_filename_to_image_htmlfilename(previous_image['filename'],resolution)
    thumbimg = os.path.join("%dx%d" % options['thumbsize'],urllib.quote(previous_image['filename']))
    left_img="<a href=\"%s\">&lt;-Prev</a><br><table border=0><tr><td bgcolor=black><a href=\"%s\"><img align=middle hspace=2 vspace=2 border=0 src=\"%s\"></a></td></tr></table>" % (thumblink,thumblink,thumbimg)
  else:
    left_img="<img width=%d height=1 src=\"blank.gif\" alt=\"\">" % options['thumbsize'][0]

  if next_image:
    thumblink = image_filename_to_image_htmlfilename(next_image['filename'],resolution)
    thumbimg = os.path.join("%dx%d" % options['thumbsize'],urllib.quote(next_image['filename']))
    right_img="<a href=\"%s\">Next -&gt;</a><br><table border=0><tr><td bgcolor=black><a href=\"%s\"><img align=middle hspace=2 vspace=2 border=0 src=\"%s\"></a></td></tr></table>" % (thumblink,thumblink,thumbimg)
  else:
    right_img="<img width=%d height=1 src=\"blank.gif\" alt=\"\">" % options['thumbsize'][0]

  if options['exif']:
    sizelist="<form><input type=\"button\" onclick=\"exif_hide_show()\" value=\"Image Information\"></form><br>"
  else:
    sizelist=''
  if len(options['sizelist']):
    sizelist+= "Other sizes:<br>"
    for r in options['sizelist']:
      if r != resolution:
        if r[0] > imageinfo['original_size'][0]: # Don't add this resolution when original file is smaller
          continue
        if r == (0,0):
          r_str = "Original"
        else:
          r_str = "%dx%d" % r
        sizelist+="<a href=\"%s\">%s</a><br>" % (image_filename_to_image_htmlfilename(imageinfo['filename'],r), r_str)
      # End: if r != resolution:
    # End: for r in options['sizelist']:
  # End: if len(options['sizelist']):

  content=content.replace("LEFT_IMG",left_img);
  content=content.replace("RIGHT_IMG",right_img);
  content=content.replace("SIZE_LIST",sizelist);

  return content

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def output_image_html_exif_window(f,imageinfo): # {{{
  """ Output the HTML code for the exif window page """
  global options

  exif_info=""

  for prop in imageinfo['exif'].keys():
    if prop in ('EXIF ExifImageLength','EXIF ExifImageWidth','EXIF DateTimeDigitized','EXIF ExposureTime'):
      exif_info+='<b>%s</b>: %s<br>' % (prop,imageinfo['exif'][prop].printable)

  
  f.write("""
<div id="exifwindow" style="visibility:hidden">
  <table width="1%%" height="1%%" bgcolor="%s"><tr><td><table width="300" height="250" bgcolor="%s">
   <tr><td align="left" valign="middle">%s</td></tr>
   <tr><td align="right" valign="bottom"><a href="" onclick="exif_hide(); return false;">Close this box</a></td></tr>
  </table></td></tr></table>
</div>
""" % (options['exif_bordercolor'],options['exif_bgcolor'],exif_info))
    
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def output_image_html_footer(f): # {{{
  """ Output the footer for a image.html page """
  f.write("</body>\n</html>\n")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}


#
# Some useful misc function
#
def safe_mkdir(pathname): # - - - - - - - - - - - - - - - - - - - - - - - - {{{
  """ Create a directory only when it doesn't exist """
  try :
    mode = os.stat(pathname)[ST_MODE]
    if not S_ISDIR(mode):
      os.mkdir(pathname);
  except OSError:
    os.mkdir(pathname);
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def navbar_for_index_html(relativepath): # - - -{{{
  """ Transform the directory location in a navigation bar printable in HTML """

  if relativepath == "":
    return "<b>Home</b>"

  ndirs = 1 + string.count(relativepath,os.sep)
  site_home = "../" * ndirs
  url = '<a href="'+site_home+'index.html">Albums</a>'

  for d in string.split(relativepath,os.sep):
    if d == "":
      continue
    ndirs-=1
    if ndirs:
      url += ' -&gt; <a href="'+ "../" * ndirs +'index.html">'+ d +'</a>'
    else:
      url += ' -&gt; <b>'+ d +'</b>'
  return url
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def navbar_for_image_html(relativepath,images_list,index): # - - -{{{
  """ Print the navigation bar for an image.html
  relativepath: Path where to found the image
  images_list: list of the images for this directory
  index: index to the current image in the images_list
  """
  global options

  ndirs = 1 + string.count(relativepath,os.sep)
  site_home = "../" * ndirs
  url = '<a href="'+site_home+'index.html">Albums</a>'

  for d in string.split(relativepath,os.sep):
    if d == "":
      continue
    ndirs-=1
    if ndirs:
      url += ' -&gt; <a href="'+ "../" * ndirs +'index.html">'+ d +'</a>'
    else:
      # Calculate the page number where this page is located
      items_per_page = options['display_columns'] * options['display_lines'];
      current_page = index / items_per_page
      if current_page:
        url += ' -&gt; <a href="index%d.html">%s</a>' % (current_page,d)
        url += ' -&gt; <b>'+ images_list[index]['filename'] +'</b>'
      else:
        url += ' -&gt; <a href="index.html">'+ d +'</a> -&gt; <b>'+ images_list[index]['filename'] +'</b>'
  return url
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def image_filename_to_image_htmlfilename(imagename,resolution): # - - -{{{
  """ Return the name of the HTML page for an image and a resolution """
  # Strip .jpg from filename
  i = string.find(imagename,".")
  image_filename_without_ext = imagename[0:i]

  # if this image is the original size, do not append the resoltuion to the filename
  resolution_string = "%dx%d" % resolution
  if resolution_string == "0x0":
    image_html_filename="%s.html" % image_filename_without_ext;
  else:
    image_html_filename="%s_%s.html" % (image_filename_without_ext,resolution_string);
  return urllib.quote(image_html_filename)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def compare_lastmodifiedtime(pathname1,pathname2): # {{{
  """ Compare the last modified time from 2 files (or directory) """
  global options
  if options['forcecreate_html']:
    return None
  try :
    mode1 = os.stat(pathname1)[ST_MTIME]
    mode2 = os.stat(pathname2)[ST_MTIME]
    return (mode1 < mode2)
  except OSError:
    return None
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}}}
def make_blank_gif(pathname): # - - - - - - - - - - - - - - - - - - - - - - {{{
  """ Make a small gif 1x1 with a transparent color """
  blank_gif="\107\111\106\070\071\141\001\000\001\000\200\000\000\000\000\000"\
            "\377\377\377\041\371\004\001\000\000\000\000\054\000\000\000\000"\
            "\001\000\001\000\100\002\001\104\000\073"

  try :
    f=open(pathname,'wb')
  except OSError:
    return 0
  else:
    f.write(blank_gif)
    f.close()
    
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}
def make_exif_js(pathname): # - - - - - - - - - - - - - - - - - - - - - - {{{
  """ Make a separate javascript file that contains dynamic html functions """

  try :
    f=open(pathname,'w')
  except OSError:
    return 0
  else:
    f.write("""
var ns=(document.layers);
var ie=(document.all);
var w3=(document.getElementById && !ie);
var exif_layer;
var exif_isshow;

function exif_init()
{
   if(!ns && !ie && !w3) 
     return;
   if (ie)
     exif_layer=eval('document.all.exifwindow.style');
   else if (ns)
     exif_layer=eval('document.layers["exifwindow"]');
   else if (w3)
     exif_layer=eval('document.getElementById("exifwindow").style');
   
   exif_hide();
}

function exif_show()
{
  if (ie)
   {
     documentWidth  =document.body.offsetWidth/2+document.body.scrollLeft-20;
     documentHeight =document.body.offsetHeight/2+document.body.scrollTop-20;
     exif_layer.visibility="visible";
   }    
  else if (ns)
   {
     documentWidth=window.innerWidth/2+window.pageXOffset-20;
     documentHeight=window.innerHeight/2+window.pageYOffset-20;
     exif_layer.visibility ="show";
   }
  else if (w3)
   {
     documentWidth=self.innerWidth/2+window.pageXOffset-20;
     documentHeight=self.innerHeight/2+window.pageYOffset-20;
     exif_layer.visibility="visible";
   }
  exif_layer.left=documentWidth-150;
  exif_layer.top =documentHeight-125;
  exif_isshow=1;
  setTimeout("exif_hide()",10000);
}

function exif_hide()
{
  if (ie||w3)
    exif_layer.visibility="hidden";
  else
    exif_layer.visibility="hide";
  exif_isshow=0;
}

function exif_hide_show()
{
  if (exif_isshow)
    exif_hide()
  else
    exif_show()
}
""")
    f.close()
    
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }}}

def match_color_type(color): # {{{
  """ Return the string when the string match a color in HTML format """
  if color[0] == "#":
    if re.match("^#[0-9a-f]{6}$",color):
      return color
  elif re.match("^[a-z]+$",a):
    return color
  return None
# }}}
#
# Exif Parser
# taken from: http://home.cfl.rr.com/genecash/
# Contains code from "exifdump.py" originally written by Thierry Bousch
# <bousch@topo.math.u-psud.fr> and released into the public domain.
# Updated and turned into general-purpose library by Gene Cash
# <gcash@cfl.rr.com>
# Modified by Luc Saillard to include into Photon
# ChangeLog, Licence {{{
# Library to extract EXIF information in digital camera image files
#
# Contains code from "exifdump.py" originally written by Thierry Bousch
# <bousch@topo.math.u-psud.fr> and released into the public domain.
#
# Updated and turned into general-purpose library by Gene Cash
# <gcash@cfl.rr.com>
#
# This copyright license is intended to be similar to the FreeBSD license. 
#
# Copyright 2002 Gene Cash All rights reserved. 
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#    1. Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the
#       distribution.
#
# THIS SOFTWARE IS PROVIDED BY GENE CASH ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# This means you may do anything you want with this code, except claim you
# wrote it. Also, if it breaks you get to keep both pieces.
#
# 21-AUG-99 TB  Last update by Thierry Bousch to his code.
# 17-JAN-02 CEC Discovered code on web.
#               Commented everything.
#               Made small code improvements.
#               Reformatted for readability.
# 19-JAN-02 CEC Added ability to read TIFFs and JFIF-format JPEGs.
#               Added ability to extract JPEG formatted thumbnail.
#               Added ability to read GPS IFD (not tested).
#               Converted IFD data structure to dictionaries indexed by
#               tag name.
#               Factored into library returning dictionary of IFDs plus
#               thumbnail, if any.
# 20-JAN-02 CEC Added MakerNote processing logic.
#               Added Olympus MakerNote.
#               Converted data structure to single-level dictionary, avoiding
#               tag name collisions by prefixing with IFD name.  This makes
#               it much easier to use.
# 23-JAN-02 CEC Trimmed nulls from end of string values.
# 25-JAN-02 CEC Discovered JPEG thumbnail in Olympus TIFF MakerNote.
# 26-JAN-02 CEC Added ability to extract TIFF thumbnails.
#               Added Nikon, Fujifilm, Casio MakerNotes.
#
# To do:
# * Finish Canon MakerNote format
# * Better printing of ratios
# }}}
# FIELD_TYPES, EXIF_TAGS, CAMERA_TAGS {{{
# field type descriptions as (length, abbreviation, full name) tuples
FIELD_TYPES=(
    (0, 'X',  'Dummy'), # no such type
    (1, 'B',  'Byte'),
    (1, 'A',  'ASCII'),
    (2, 'S',  'Short'),
    (4, 'L',  'Long'),
    (8, 'R',  'Ratio'),
    (1, 'SB', 'Signed Byte'),
    (1, 'U',  'Undefined'),
    (2, 'SS', 'Signed Short'),
    (4, 'SL', 'Signed Long'),
    (8, 'SR', 'Signed Ratio')
    )

# dictionary of main EXIF tag names
# first element of tuple is tag name, optional second element is
# another dictionary giving names to values
EXIF_TAGS={
    0x0100: ('ImageWidth', ),
    0x0101: ('ImageLength', ),
    0x0102: ('BitsPerSample', ),
    0x0103: ('Compression',
             {1: 'Uncompressed TIFF',
              6: 'JPEG Compressed'}),
    0x0106: ('PhotometricInterpretation', ),
    0x010A: ('FillOrder', ),
    0x010D: ('DocumentName', ),
    0x010E: ('ImageDescription', ),
    0x010F: ('Make', ),
    0x0110: ('Model', ),
    0x0111: ('StripOffsets', ),
    0x0112: ('Orientation', ),
    0x0115: ('SamplesPerPixel', ),
    0x0116: ('RowsPerStrip', ),
    0x0117: ('StripByteCounts', ),
    0x011A: ('XResolution', ),
    0x011B: ('YResolution', ),
    0x011C: ('PlanarConfiguration', ),
    0x0128: ('ResolutionUnit',
             {1: 'Not Absolute',
              2: 'Pixels/Inch',
              3: 'Pixels/Centimeter'}),
    0x012D: ('TransferFunction', ),
    0x0131: ('Software', ),
    0x0132: ('DateTime', ),
    0x013B: ('Artist', ),
    0x013E: ('WhitePoint', ),
    0x013F: ('PrimaryChromaticities', ),
    0x0156: ('TransferRange', ),
    0x0200: ('JPEGProc', ),
    0x0201: ('JPEGInterchangeFormat', ),
    0x0202: ('JPEGInterchangeFormatLength', ),
    0x0211: ('YCbCrCoefficients', ),
    0x0212: ('YCbCrSubSampling', ),
    0x0213: ('YCbCrPositioning', ),
    0x0214: ('ReferenceBlackWhite', ),
    0x828D: ('CFARepeatPatternDim', ),
    0x828E: ('CFAPattern', ),
    0x828F: ('BatteryLevel', ),
    0x8298: ('Copyright', ),
    0x829A: ('ExposureTime', ),
    0x829D: ('FNumber', ),
    0x83BB: ('IPTC/NAA', ),
    0x8769: ('ExifOffset', ),
    0x8773: ('InterColorProfile', ),
    0x8822: ('ExposureProgram',
             {0: 'Unidentified',
              1: 'Manual',
              2: 'Program Normal',
              3: 'Aperture Priority',
              4: 'Shutter Priority',
              5: 'Program Creative',
              6: 'Program Action',
              7: 'Portrait Mode',
              8: 'Landscape Mode'}),
    0x8824: ('SpectralSensitivity', ),
    0x8825: ('GPSInfo', ),
    0x8827: ('ISOSpeedRatings', ),
    0x8828: ('OECF', ),
    0x9000: ('ExifVersion', ),
    0x9003: ('DateTimeOriginal', ),
    0x9004: ('DateTimeDigitized', ),
    0x9101: ('ComponentsConfiguration',
             {0: '',
              1: 'Y',
              2: 'Cb',
              3: 'Cr',
              4: 'Red',
              5: 'Green',
              6: 'Blue'}),
    0x9102: ('CompressedBitsPerPixel', ),
    0x9201: ('ShutterSpeedValue', ),
    0x9202: ('ApertureValue', ),
    0x9203: ('BrightnessValue', ),
    0x9204: ('ExposureBiasValue', ),
    0x9205: ('MaxApertureValue', ),
    0x9206: ('SubjectDistance', ),
    0x9207: ('MeteringMode',
             {0: 'Unidentified',
              1: 'Average',
              2: 'CenterWeightedAverage',
              3: 'Spot',
              4: 'MultiSpot'}),
    0x9208: ('LightSource',
             {0:   'Unknown',
              1:   'Daylight',
              2:   'Fluorescent',
              3:   'Tungsten',
              10:  'Flash',
              17:  'Standard Light A',
              18:  'Standard Light B',
              19:  'Standard Light C',
              20:  'D55',
              21:  'D65',
              22:  'D75',
              255: 'Other'}),
    0x9209: ('Flash', {0:  'No',
                       1:  'Fired',
                       5:  'Fired (?)', # no return sensed
                       7:  'Fired (!)', # return sensed
                       9:  'Fill Fired',
                       13: 'Fill Fired (?)',
                       15: 'Fill Fired (!)',
                       16: 'Off',
                       24: 'Auto Off',
                       25: 'Auto Fired',
                       29: 'Auto Fired (?)',
                       31: 'Auto Fired (!)',
                       32: 'Not Available'}),
    0x920A: ('FocalLength', ),
    0x927C: ('MakerNote', ),
    0x9286: ('UserComment', ),
    0x9290: ('SubSecTime', ),
    0x9291: ('SubSecTimeOriginal', ),
    0x9292: ('SubSecTimeDigitized', ),
    0xA000: ('FlashPixVersion', ),
    0xA001: ('ColorSpace', ),
    0xA002: ('ExifImageWidth', ),
    0xA003: ('ExifImageLength', ),
    0xA005: ('InteroperabilityOffset', ),
    0xA20B: ('FlashEnergy', ),               # 0x920B in TIFF/EP
    0xA20C: ('SpatialFrequencyResponse', ),  # 0x920C    -  -
    0xA20E: ('FocalPlaneXResolution', ),     # 0x920E    -  -
    0xA20F: ('FocalPlaneYResolution', ),     # 0x920F    -  -
    0xA210: ('FocalPlaneResolutionUnit', ),  # 0x9210    -  -
    0xA214: ('SubjectLocation', ),           # 0x9214    -  -
    0xA215: ('ExposureIndex', ),             # 0x9215    -  -
    0xA217: ('SensingMethod', ),             # 0x9217    -  -
    0xA300: ('FileSource',
             {3: 'Digital Camera'}),
    0xA301: ('SceneType',
             {1: 'Directly Photographed'}),
    }

# interoperability tags
INTR_TAGS={
    0x0001: ('InteroperabilityIndex', ),
    0x0002: ('InteroperabilityVersion', ),
    0x1000: ('RelatedImageFileFormat', ),
    0x1001: ('RelatedImageWidth', ),
    0x1002: ('RelatedImageLength', ),
    }

# GPS tags (not used yet, haven't seen camera with GPS)
GPS_TAGS={
    0x0000: ('GPSVersionID', ),
    0x0001: ('GPSLatitudeRef', ),
    0x0002: ('GPSLatitude', ),
    0x0003: ('GPSLongitudeRef', ),
    0x0004: ('GPSLongitude', ),
    0x0005: ('GPSAltitudeRef', ),
    0x0006: ('GPSAltitude', ),
    0x0007: ('GPSTimeStamp', ),
    0x0008: ('GPSSatellites', ),
    0x0009: ('GPSStatus', ),
    0x000A: ('GPSMeasureMode', ),
    0x000B: ('GPSDOP', ),
    0x000C: ('GPSSpeedRef', ),
    0x000D: ('GPSSpeed', ),
    0x000E: ('GPSTrackRef', ),
    0x000F: ('GPSTrack', ),
    0x0010: ('GPSImgDirectionRef', ),
    0x0011: ('GPSImgDirection', ),
    0x0012: ('GPSMapDatum', ),
    0x0013: ('GPSDestLatitudeRef', ),
    0x0014: ('GPSDestLatitude', ),
    0x0015: ('GPSDestLongitudeRef', ),
    0x0016: ('GPSDestLongitude', ),
    0x0017: ('GPSDestBearingRef', ),
    0x0018: ('GPSDestBearing', ),
    0x0019: ('GPSDestDistanceRef', ),
    0x001A: ('GPSDestDistance', )
    }

# Nikon E99x MakerNote Tags
# http://members.tripod.com/~tawba/990exif.htm
MAKERNOTE_NIKON_NEWER_TAGS={
    0x0002: ('ISOSetting', ),
    0x0003: ('ColorMode', ),
    0x0004: ('Quality', ),
    0x0005: ('Whitebalance', ),
    0x0006: ('ImageSharpening', ),
    0x0007: ('FocusMode', ),
    0x0008: ('FlashSetting', ),
    0x000F: ('ISOSelection', ),
    0x0080: ('ImageAdjustment', ),
    0x0082: ('AuxiliaryLens', ),
    0x0085: ('ManualFocusDistance', ),
    0x0086: ('DigitalZoomFactor', ),
    0x0088: ('AFFocusPosition',
             {0x0000: 'Center',
              0x0100: 'Top',
              0x0200: 'Bottom',
              0x0300: 'Left',
              0x0400: 'Right'}),
    0x0094: ('Saturation',
             {-3: 'B&W',
              -2: '-2',
              -1: '-1',
              0:  '0',
              1:  '1',
              2:  '2'}),
    0x0095: ('NoiseReduction', ),
    0x0010: ('DataDump', )
    }

MAKERNOTE_NIKON_OLDER_TAGS={
    0x0003: ('Quality',
             {1: 'VGA Basic',
              2: 'VGA Normal',
              3: 'VGA Fine',
              4: 'SXGA Basic',
              5: 'SXGA Normal',
              6: 'SXGA Fine'}),
    0x0004: ('ColorMode',
             {1: 'Color',
              2: 'Monochrome'}),
    0x0005: ('ImageAdjustment',
             {0: 'Normal',
              1: 'Bright+',
              2: 'Bright-',
              3: 'Contrast+',
              4: 'Contrast-'}),
    0x0006: ('CCDSpeed',
             {0: 'ISO 80',
              2: 'ISO 160',
              4: 'ISO 320',
              5: 'ISO 100'}),
    0x0007: ('WhiteBalance',
             {0: 'Auto',
              1: 'Preset',
              2: 'Daylight',
              3: 'Incandescent',
              4: 'Fluorescent',
              5: 'Cloudy',
              6: 'Speed Light'})
    }

# decode Olympus SpecialMode tag in MakerNote
def olympus_special_mode(v):
    a={
        0: 'Normal',
        1: 'Unknown',
        2: 'Fast',
        3: 'Panorama'}
    b={
        0: 'Non-panoramic',
        1: 'Left to right',
        2: 'Right to left',
        3: 'Bottom to top',
        4: 'Top to bottom'}
    return '%s - sequence %d - %s' % (a[v[0]], v[1], b[v[2]])
        
MAKERNOTE_OLYMPUS_TAGS={
    # ah HAH! those sneeeeeaky bastids! this is how they get past the fact
    # that a JPEG thumbnail is not allowed in an uncompressed TIFF file
    0x0100: ('JPEGThumbnail', ),
    0x0200: ('SpecialMode', olympus_special_mode),
    0x0201: ('JPEGQual',
             {1: 'SQ',
              2: 'HQ',
              3: 'SHQ'}),
    0x0202: ('Macro',
             {0: 'Normal',
              1: 'Macro'}),
    0x0204: ('DigitalZoom', ),
    0x0207: ('SoftwareRelease',  ),
    0x0208: ('PictureInfo',  ),
    # print as string
    0x0209: ('CameraID', lambda x: ''.join(map(chr, x))), 
    0x0F00: ('DataDump',  )
    }

MAKERNOTE_CASIO_TAGS={
    0x0001: ('RecordingMode',
             {1: 'Single Shutter',
              2: 'Panorama',
              3: 'Night Scene',
              4: 'Portrait',
              5: 'Landscape'}),
    0x0002: ('Quality',
             {1: 'Economy',
              2: 'Normal',
              3: 'Fine'}),
    0x0003: ('FocusingMode',
             {2: 'Macro',
              3: 'Auto Focus',
              4: 'Manual Focus',
              5: 'Infinity'}),
    0x0004: ('FlashMode',
             {1: 'Auto',
              2: 'On',
              3: 'Off',
              4: 'Red Eye Reduction'}),
    0x0005: ('FlashIntensity',
             {11: 'Weak',
              13: 'Normal',
              15: 'Strong'}),
    0x0006: ('Object Distance', ),
    0x0007: ('WhiteBalance',
             {1:   'Auto',
              2:   'Tungsten',
              3:   'Daylight',
              4:   'Fluorescent',
              5:   'Shade',
              129: 'Manual'}),
    0x000B: ('Sharpness',
             {0: 'Normal',
              1: 'Soft',
              2: 'Hard'}),
    0x000C: ('Contrast',
             {0: 'Normal',
              1: 'Low',
              2: 'High'}),
    0x000D: ('Saturation',
             {0: 'Normal',
              1: 'Low',
              2: 'High'}),
    0x0014: ('CCDSpeed',
             {64:  'Normal',
              80:  'Normal',
              100: 'High',
              125: '+1.0',
              244: '+3.0',
              250: '+2.0',})
    }

MAKERNOTE_FUJIFILM_TAGS={
    0x0000: ('NoteVersion', lambda x: ''.join(map(chr, x))),
    0x1000: ('Quality', ),
    0x1001: ('Sharpness',
             {1: 'Soft',
              2: 'Soft',
              3: 'Normal',
              4: 'Hard',
              5: 'Hard'}),
    0x1002: ('WhiteBalance',
             {0:    'Auto',
              256:  'Daylight',
              512:  'Cloudy',
              768:  'DaylightColor-Fluorescent',
              769:  'DaywhiteColor-Fluorescent',
              770:  'White-Fluorescent',
              1024: 'Incandescent',
              3840: 'Custom'}),
    0x1003: ('Color',
             {0:   'Normal',
              256: 'High',
              512: 'Low'}),
    0x1004: ('Tone',
             {0:   'Normal',
              256: 'High',
              512: 'Low'}),
    0x1010: ('FlashMode',
             {0: 'Auto',
              1: 'On',
              2: 'Off',
              3: 'Red Eye Reduction'}),
    0x1011: ('FlashStrength', ),
    0x1020: ('Macro',
             {0: 'Off',
              1: 'On'}),
    0x1021: ('FocusMode',
             {0: 'Auto',
              1: 'Manual'}),
    0x1030: ('SlowSync',
             {0: 'Off',
              1: 'On'}),
    0x1031: ('PictureMode',
             {0:   'Auto',
              1:   'Portrait',
              2:   'Landscape',
              4:   'Sports',
              5:   'Night',
              6:   'Program AE',
              256: 'Aperture Priority AE',
              512: 'Shutter Priority AE',
              768: 'Manual Exposure'}),
    0x1100: ('MotorOrBracket',
             {0: 'Off',
              1: 'On'}),
    0x1300: ('BlurWarning',
             {0: 'Off',
              1: 'On'}),
    0x1301: ('FocusWarning',
             {0: 'Off',
              1: 'On'}),
    0x1302: ('AEWarning',
             {0: 'Off',
              1: 'On'})
    }

MAKERNOTE_CANON_TAGS={
    0x0006: ('ImageType', ),
    0x0007: ('FirmwareVersion', ),
    0x0008: ('ImageNumber', ),
    0x0009: ('OwnerName', )
    }

# see http://www.burren.cx/david/canon.html by David Burren
# this is in element offset, name, optional value dictionary format
MAKERNOTE_CANON_TAG_0x001={
    1: ('Macromode',
        {1: 'Macro',
         2: 'Normal'}),
    2: ('SelfTimer', ),
    3: ('Quality',
        {2: 'Normal',
         3: 'Fine',
         5: 'Superfine'}),
    4: ('FlashMode',
        {0: 'Flash Not Fired',
         1: 'Auto',
         2: 'On',
         3: 'Red-Eye Reduction',
         4: 'Slow Synchro',
         5: 'Auto + Red-Eye Reduction',
         6: 'On + Red-Eye Reduction',
         16: 'external flash'}),
    5: ('ContinuousDriveMode',
        {0: 'Single Or Timer',
         1: 'Continuous'}),
    7: ('FocusMode',
        {0: 'One-Shot',
         1: 'AI Servo',
         2: 'AI Focus',
         3: 'MF',
         4: 'Single',
         5: 'Continuous',
         6: 'MF'}),
    10: ('ImageSize',
         {0: 'Large',
          1: 'Medium',
          2: 'Small'}),
    11: ('EasyShootingMode',
         {0: 'Full Auto',
          1: 'Manual',
          2: 'Landscape',
          3: 'Fast Shutter',
          4: 'Slow Shutter',
          5: 'Night',
          6: 'B&W',
          7: 'Sepia',
          8: 'Portrait',
          9: 'Sports',
          10: 'Macro/Close-Up',
          11: 'Pan Focus'}),
    12: ('DigitalZoom',
         {0: 'None',
          1: '2x',
          2: '4x'}),
    13: ('Contrast',
         {0xFFFF: 'Low',
          0: 'Normal',
          1: 'High'}),
    14: ('Saturation',
         {0xFFFF: 'Low',
          0: 'Normal',
          1: 'High'}),
    15: ('Sharpness',
         {0xFFFF: 'Low',
          0: 'Normal',
          1: 'High'}),
    16: ('ISO',
         {0: 'See ISOSpeedRatings Tag',
          15: 'Auto',
          16: '50',
          17: '100',
          18: '200',
          19: '400'}),
    17: ('MeteringMode',
         {3: 'Evaluative',
          4: 'Partial',
          5: 'Center-weighted'}),
    18: ('FocusType',
         {0: 'Manual',
          1: 'Auto',
          3: 'Close-Up (Macro)',
          8: 'Locked (Pan Mode)'}),
    19: ('AFPointSelected',
         {0x3000: 'None (MF)',
          0x3001: 'Auto-Selected',
          0x3002: 'Right',
          0x3003: 'Center',
          0x3004: 'Left'}),
    20: ('ExposureMode',
         {0: 'Easy Shooting',
          1: 'Program',
          2: 'Tv-priority',
          3: 'Av-priority',
          4: 'Manual',
          5: 'A-DEP'}),
    23: ('LongFocalLengthOfLensInFocalUnits', ),
    24: ('ShortFocalLengthOfLensInFocalUnits', ),
    25: ('FocalUnitsPerMM', ),
    28: ('FlashActivity',
         {0: 'Did Not Fire',
          1: 'Fired'}),
    29: ('FlashDetails',
         {14: 'External E-TTL',
          13: 'Internal Flash',
          11: 'FP Sync Used',
          7: '2nd("Rear")-Curtain Sync Used',
          4: 'FP Sync Enabled'}),
    32: ('FocusMode',
         {0: 'Single',
          1: 'Continuous'})
    }

MAKERNOTE_CANON_TAG_0x004={
    7: ('WhiteBalance',
        {0: 'Auto',
         1: 'Sunny',
         2: 'Cloudy',
         3: 'Tungsten',
         4: 'Fluorescent',
         5: 'Flash',
         6: 'Custom'}),
    9: ('SequenceNumber', ),
    14: ('AFPointUsed', ),
    15: ('FlashBias',
        {0XFFC0: '-2 EV',
         0XFFCC: '-1.67 EV',
         0XFFD0: '-1.50 EV',
         0XFFD4: '-1.33 EV',
         0XFFE0: '-1 EV',
         0XFFEC: '-0.67 EV',
         0XFFF0: '-0.50 EV',
         0XFFF4: '-0.33 EV',
         0X0000: '0 EV',
         0X000C: '0.33 EV',
         0X0010: '0.50 EV',
         0X0014: '0.67 EV',
         0X0020: '1 EV',
         0X002C: '1.33 EV',
         0X0030: '1.50 EV',
         0X0034: '1.67 EV',
         0X0040: '2 EV'}), 
    19: ('SubjectDistance', )
    }

# }}}
# Read, Write, Convert functions {{{
# extract multibyte integer in Motorola format (little endian)
def s2n_motorola(str):
    x=0
    for c in str:
        x=(x << 8) | ord(c)
    return x

# extract multibyte integer in Intel format (big endian)
def s2n_intel(str):
    x=0
    y=0
    for c in str:
        x=x | (ord(c) << y)
        y=y+8
    return x

# ratio object that eventually will be able to reduce itself to lowest
# common denominator for printing
def gcd(a, b):
   if b == 0:
      return a
   else:
      return gcd(b, a % b)

class Ratio:
    def __init__(self, num, den):
        self.num=num
        self.den=den

    def __repr__(self):
        self.reduce()
        if self.den == 1:
            return str(self.num)
        return '%d/%d' % (self.num, self.den)

    def reduce(self):
        div=gcd(self.num, self.den)
        if div > 1:
            self.num=self.num/div
            self.den=self.den/div
# }}}
# for ease of dealing with tags
class IFD_Tag: # {{{
    def __init__(self, printable, tag, field_type, values, field_offset,
                 field_length):
        self.printable=printable
        self.tag=tag
        self.field_type=field_type
        self.field_offset=field_offset
        self.field_length=field_length
        self.values=values
        
    def __str__(self):
        return self.printable
    
    def __repr__(self):
        return '(0x%04X) %s=%s @ %d' % (self.tag,
                                        FIELD_TYPES[self.field_type][2],
                                        self.printable,
                                        self.field_offset)
# }}}
# class that handles an EXIF header  {{{
class EXIF_header:
    def __init__(self, file, endian, offset, debug=0):
        self.file=file
        self.endian=endian
        self.offset=offset
        self.debug=debug
        self.tags={}
        
    # convert slice to integer, based on sign and endian flags
    def s2n(self, offset, length, signed=0):
        self.file.seek(self.offset+offset)
        slice=self.file.read(length)
        if self.endian == 'I':
            val=s2n_intel(slice)
        else:
            val=s2n_motorola(slice)
        # Sign extension ?
        if signed:
            msb=1 << (8*length-1)
            if val & msb:
                val=val-(msb << 1)
        return val

    # convert offset to string
    def n2s(self, offset, length):
        s=''
        for i in range(length):
            if self.endian == 'I':
                s=s+chr(offset & 0xFF)
            else:
                s=chr(offset & 0xFF)+s
            offset=offset >> 8
        return s
    
    # return first IFD
    def first_IFD(self):
        return self.s2n(4, 4)

    # return pointer to next IFD
    def next_IFD(self, ifd):
        entries=self.s2n(ifd, 2)
        return self.s2n(ifd+2+12*entries, 4)

    # return list of IFDs in header
    def list_IFDs(self):
        i=self.first_IFD()
        a=[]
        while i:
            a.append(i)
            i=self.next_IFD(i)
        return a

    # return list of entries in this IFD
    def dump_IFD(self, ifd, ifd_name, dict=EXIF_TAGS):
        entries=self.s2n(ifd, 2)
        for i in range(entries):
            entry=ifd+2+12*i
            tag=self.s2n(entry, 2)
            field_type=self.s2n(entry+2, 2)
            if not 0 < field_type < len(FIELD_TYPES):
                # unknown field type
                raise ValueError, \
                      'unknown type %d in tag 0x%04X' % (field_type, tag)
            typelen=FIELD_TYPES[field_type][0]
            count=self.s2n(entry+4, 4)
            offset=entry+8
            if count*typelen > 4:
                # not the value, it's a pointer to the value
                offset=self.s2n(offset, 4)
            field_offset=offset
            if field_type == 2:
                # special case: null-terminated ASCII string
                if count != 0:
                    self.file.seek(self.offset+offset)
                    values=self.file.read(count).strip().replace('\x00','')
                else:
                    values=''
            else:
                values=[]
                signed=(field_type in [6, 8, 9, 10])
                for j in range(count):
                    if field_type in (5, 10):
                        # a ratio
                        value_j=Ratio(self.s2n(offset,   4, signed),
                                      self.s2n(offset+4, 4, signed))
                    else:
                        value_j=self.s2n(offset, typelen, signed)
                    values.append(value_j)
                    offset=offset+typelen
            # now "values" is either a string or an array
            if count == 1 and field_type != 2:
                printable=str(values[0])
            else:
                printable=str(values)
            # figure out tag name
            tag_entry=dict.get(tag)
            if tag_entry:
                tag_name=tag_entry[0]
                if len(tag_entry) != 1:
                    # optional 2nd tag element is present
                    if callable(tag_entry[1]):
                        # call mapping function
                        printable=tag_entry[1](values)
                    else:
                        printable=''
                        for i in values:
                            # use LUT for this tag
                            printable+=tag_entry[1].get(i, repr(i))
            else:
                tag_name='Tag 0x%04X' % tag
            self.tags[ifd_name+' '+tag_name]=IFD_Tag(printable, tag,
                                                     field_type,
                                                     values, field_offset,
                                                     count*typelen)
            if self.debug:
                print '    %s: %s' % (tag_name,
                                      repr(self.tags[ifd_name+' '+tag_name]))

    # extract uncompressed TIFF thumbnail (like pulling teeth)
    # we take advantage of the pre-existing layout in the thumbnail IFD as
    # much as possible
    def extract_TIFF_thumbnail(self, thumb_ifd):
        entries=self.s2n(thumb_ifd, 2)
        # this is header plus offset to IFD ...
        if self.endian == 'M':
            tiff='MM\x00*\x00\x00\x00\x08'
        else:
            tiff='II*\x00\x08\x00\x00\x00'
        # ... plus thumbnail IFD data plus a null "next IFD" pointer
        self.file.seek(self.offset+thumb_ifd)
        tiff+=self.file.read(entries*12+2)+'\x00\x00\x00\x00'
        
        # fix up large value offset pointers into data area
        for i in range(entries):
            entry=thumb_ifd+2+12*i
            tag=self.s2n(entry, 2)
            field_type=self.s2n(entry+2, 2)
            typelen=FIELD_TYPES[field_type][0]
            count=self.s2n(entry+4, 4)
            oldoff=self.s2n(entry+8, 4)
            # start of the 4-byte pointer area in entry
            ptr=i*12+18
            # remember strip offsets location
            if tag == 0x0111:
                strip_off=ptr
                strip_len=count*typelen
            # is it in the data area?
            if count*typelen > 4:
                # update offset pointer (nasty "strings are immutable" crap)
                # should be able to say "tiff[ptr:ptr+4]=newoff"
                newoff=len(tiff)
                tiff=tiff[:ptr]+self.n2s(newoff, 4)+tiff[ptr+4:]
                # remember strip offsets location
                if tag == 0x0111:
                    strip_off=newoff
                    strip_len=4
                # get original data and store it
                self.file.seek(self.offset+oldoff)
                tiff+=self.file.read(count*typelen)
                
        # add pixel strips and update strip offset info
        old_offsets=self.tags['Thumbnail StripOffsets'].values
        old_counts=self.tags['Thumbnail StripByteCounts'].values
        for i in range(len(old_offsets)):
            # update offset pointer (more nasty "strings are immutable" crap)
            offset=self.n2s(len(tiff), strip_len)
            tiff=tiff[:strip_off]+offset+tiff[strip_off+strip_len:]
            strip_off+=strip_len
            # add pixel strip to end
            self.file.seek(self.offset+old_offsets[i])
            tiff+=self.file.read(old_counts[i])
            
        self.tags['TIFFThumbnail']=tiff
        
    # decode all the camera-specific MakerNote formats
    def decode_maker_note(self):
        note=self.tags['EXIF MakerNote']
        make=self.tags['Image Make'].printable
        model=self.tags['Image Model'].printable

        # Nikon
        if make == 'NIKON':
            if note.values[0:5] == [78, 105, 107, 111, 110]: # "Nikon"
                # older model
                self.dump_IFD(note.field_offset+8, 'MakerNote',
                              dict=MAKERNOTE_NIKON_OLDER_TAGS)
            else:
                # newer model (E99x or D1)
                self.dump_IFD(note.field_offset, 'MakerNote',
                              dict=MAKERNOTE_NIKON_NEWER_TAGS)
            return

        # Olympus
        if make[:7] == 'OLYMPUS':
            self.dump_IFD(note.field_offset+8, 'MakerNote',
                          dict=MAKERNOTE_OLYMPUS_TAGS)
            return

        # Casio
        if make == 'Casio':
            self.dump_IFD(note.field_offset, 'MakerNote',
                          dict=MAKERNOTE_CASIO_TAGS)
            return
        
        # Fujifilm
        if make == 'FUJIFILM':
            # bug: everything else is "Motorola" endian, but the MakerNote
            # is "Intel" endian 
            endian=self.endian
            self.endian='I'
            # bug: IFD offsets are from beginning of MakerNote, not
            # beginning of file header
            offset=self.offset
            self.offset+=note.field_offset
            # process note with bogus values (note is actually at offset 12)
            self.dump_IFD(12, 'MakerNote', dict=MAKERNOTE_FUJIFILM_TAGS)
            # reset to correct values
            self.endian=endian
            self.offset=offset
            return
        
        # Canon
        if make == 'Canon':
            self.dump_IFD(note.field_offset, 'MakerNote',
                          dict=MAKERNOTE_CANON_TAGS)
            for i in (('MakerNote Tag 0x0001', MAKERNOTE_CANON_TAG_0x001),
                      ('MakerNote Tag 0x0004', MAKERNOTE_CANON_TAG_0x004)):
                self.canon_decode_tag(self.tags[i[0]].values, i[1])
            return

    # decode Canon MakerNote tag based on offset within tag
    # see http://www.burren.cx/david/canon.html by David Burren
    def canon_decode_tag(self, value, dict):
        for i in range(1, len(value)):
            x=dict.get(i, ('Unknown', ))
            name=x[0]
            if len(x) > 1:
                val=x[1].get(value[i], 'Unknown')
            else:
                val=value[i]
            self.tags['MakerNote '+name]=val
# }}}
# process an image file (expects an open file object)
# this is the function that has to deal with all the arbitrary nasty bits
# of the EXIF standard
def get_exif_information_from_file(filename, debug=0): # {{{
    file=open(filename, 'rb')
    # determine whether it's a JPEG or TIFF
    data=file.read(12)
    if data[0:4] in ['II*\x00', 'MM\x00*']:
        # it's a TIFF file
        file.seek(0)
        endian=file.read(1)
        file.read(1)
        offset=0
    elif data[0:2] == '\xFF\xD8':
        # it's a JPEG file
        # skip JFIF style header(s)
        while data[2] == '\xFF' and data[6:10] in ('JFIF', 'JFXX', 'OLYM'):
            length=ord(data[4])*256+ord(data[5])
            file.read(length-8)
            # fake an EXIF beginning of file
            data='\xFF\x00'+file.read(10)
        if data[2] == '\xFF' and data[6:10] == 'Exif':
            # detected EXIF header
            offset=file.tell()
            endian=file.read(1)
        else:
            # no EXIF information
            file.close()
            return {}
    else:
        # file format not recognized
        file.close()
        return {}

    # deal with the EXIF info we found
    if debug:
        print {'I': 'Intel', 'M': 'Motorola'}[endian], 'format'
    hdr=EXIF_header(file, endian, offset, debug)
    ifd_list=hdr.list_IFDs()
    ctr=0
    for i in ifd_list:
        if ctr == 0:
            IFD_name='Image'
        elif ctr == 1:
            IFD_name='Thumbnail'
            thumb_ifd=i
        else:
            IFD_name='IFD %d' % ctr
        if debug:
            print ' IFD %d (%s) at offset %d:' % (ctr, IFD_name, i)
        hdr.dump_IFD(i, IFD_name)
        # EXIF IFD
        exif_off=hdr.tags.get(IFD_name+' ExifOffset')
        if exif_off:
            if debug:
                print ' EXIF SubIFD at offset %d:' % exif_off.values[0]
            hdr.dump_IFD(exif_off.values[0], 'EXIF')
            # Interoperability IFD contained in EXIF IFD
            intr_off=hdr.tags.get('EXIF SubIFD InteroperabilityOffset')
            if intr_off:
                if debug:
                    print ' EXIF Interoperability SubSubIFD at offset %d:' \
                          % intr_off.values[0]
                hdr.dump_IFD(intr_off.values[0], 'EXIF Interoperability',
                             dict=INTR_TAGS)
        # GPS IFD
        gps_off=hdr.tags.get(IFD_name+' GPSInfoOffset')
        if gps_off:
            if debug:
                print ' GPS SubIFD at offset %d:' % gps_off.values[0]
            hdr.dump_IFD(gps_off.values[0], 'GPS', dict=GPS_TAGS)
        ctr+=1

    # extract uncompressed TIFF thumbnail
    thumb=hdr.tags.get('Thumbnail Compression')
    if thumb and thumb.printable == 'Uncompressed TIFF':
        hdr.extract_TIFF_thumbnail(thumb_ifd)
        
    # JPEG thumbnail (thankfully the JPEG data is stored as a unit)
    thumb_off=hdr.tags.get('Thumbnail JPEGInterchangeFormat')
    if thumb_off:
        file.seek(offset+thumb_off.values[0])
        size=hdr.tags['Thumbnail JPEGInterchangeFormatLength'].values[0]
        hdr.tags['JPEGThumbnail']=file.read(size)
        
    # deal with MakerNote contained in EXIF IFD
    if hdr.tags.has_key('EXIF MakerNote'):
        hdr.decode_maker_note()

    # Sometimes in a TIFF file, a JPEG thumbnail is hidden in the MakerNote
    # since it's not allowed in a uncompressed TIFF IFD
    if not hdr.tags.has_key('JPEGThumbnail'):
        thumb_off=hdr.tags.get('MakerNote JPEGThumbnail')
        if thumb_off:
            file.seek(offset+thumb_off.values[0])
            hdr.tags['JPEGThumbnail']=file.read(thumb_off.field_length)
            
    file.close()
    return hdr.tags
# }}}

if __name__ == "__main__":
    main()



