#!/usr/bin/env python

gimp_plugin_license ="""
 This plug-in uses ccserv.py, a little python localhost server that
 attaches itself to the creative commons web site and was written
 by Manish Singh.
 
 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
import string
import BaseHTTPServer


from gimpfu import *

response_html = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
  <link rel="icon" href="http://carol.gimp.org/flavicon-gipp.png" TYPE="image/png"></link>
  <link rel="stylesheet" href="http://carol.gimp.org/gipp-success.css" type="text/css" media="screen"></link>
  <style type="text/css">
    body  {background-color:#cccccc;
           color:#000000;}
    p  {width:400px;
        text-align:justify;
        margin:70px auto auto auto;
        padding:30px;}
    table  {margin:10px auto;
            width:500px;}
    img {background-color:#cccccc;
         color:#000000;
         border:thin solid black;}
    a:link {text-decoration:none;}
    a:visited {text-decoration:none;}
    a:active {text-decoration:none;}
    a:hover {text-decoration:none;}
  </style>
  <title>GIPP Success!</title>
</head>

<body>
<table>
  <tr><td>
  </td><td style="width:33%%;">
    <img src="http://carol.gimp.org/logo-gipp.png" alt="logo-gipp"></img>
  </td><td>
  </td></tr>
</table>
<p>
You have successfully selected a Creative Commons license and you are about
to apply this license to your digital image via TheGIMP and TheGIMP&apos;s
Image Publishing Plug-in. You may now close this browser window or use it to
learn more about the <a 
href="http://www.creativecommons.org/">Creative Commons Organization</a>, <a 
href="http://www.gimp.org/">TheGIMP</a> or <a 
href="http://carol.gimp.org/gimp2/print/license/">TheGIMP&apos;s Image Publishing Plug-in</a>.
</p>
<table>
  <tr><td>
    <a href="http://www.gnu.org/">
    <img src="http://carol.gimp.org/baubles/another-gnu.png" alt="another-gnu"></img></a>
  </td><td>
    <a href="http://www.gimp.org">
    <img src="http://carol.gimp.org/baubles/wilma.png" alt="wilma"></img></a>
  </td><td>
    <a href="http://carol.gimp.org/gimp2/resources/python/">
    <img src="http://carol.gimp.org/baubles/python.png" style="padding:0px 20px;" alt="python"></img></a>
  </td></tr>
</table>
</body>

</html>
"""


cc_license_template ="""
This work is licensed under the 
Creative Commons %(license_name)s License. 
To view a copy of this license, visit 
%(license_url)s
"""

gimp_template ="""
gimp_comment = %(gimp_comment)s
gimp_version = %(gimp_version)s
gipp_comment = %(gipp_comment)s
gipp_version = demonstration %(gipp_version)d

"""
image_template ="""
background_color = %(background_color)s
foreground_color = %(foreground_color)s
image_name = %(image_name)s
image_source = %(image_source)s
image_source_width = %(image_source_width)d
image_source_height = %(image_source_height)d
image_source_unit = %(image_source_unit)s

"""
license_template ="""
license_url = %(license_url)s
license_name = %(license_name)s
license_text = 
%(license_text)s

"""

extra_template ="""
license_date = %(license_date)s
name = %(name)s

"""

format_template ="""
image_extension = %(image_extension)s
monitor_related_width = %(monitor_related_width)d
monitor_related_height = %(monitor_related_height)d
monitor_related_unit = %(monitor_related_unit)s
monitor_resolution_x = %(monitor_resolution_x)d
monitor_resolution_y = %(monitor_resolution_y)d
monitor_resolution_unit = %(monitor_resolution_unit)s
colorspace  = %(colorspace)s

"""

exif_template ="""
exif_version = %(exif_version)s
exif_id = %(exif_id)s
exif_name = %(exif_name)s
exif_camera_manufacturer = %(exif_camera_manufacturer)s
exif_camera_model = %(exif_camera_model)s
exif_note_maker = %(exif_note_maker)s
exif_note_user = %(exif_note_user)s
exif_orientation = %(exif_orientation)s
exif_resolution_x = %(exif_resolution_x)s
exif_resolution_y = %(exif_resolution_y)s
exif_resolution_unit = %(exif_resolution_unit)s
exif_related_width = %(exif_related_width)s
exif_related_height = %(exif_related_height)s
exif_exposure_time = %(exif_exposure_time)s
exif_exposure_fnumber = %(exif_exposure_fnumber)s
exif_exposure_iso = %(exif_exposure_iso)s
exif_exposure_mode = %(exif_exposure_mode)s
exif_exposure_white = %(exif_exposure_white)s
exif_time_original = %(exif_time_original)s
exif_time_digital = %(exif_time_digital)s
exif_components = %(exif_components)s
exif_compression = %(exif_compression)s
exif_speed = %(exif_speed)s
exif_aperature = %(exif_aperature)s
exif_aperature_max = %(exif_aperature_max)s
exif_bias = %(exif_bias)s
exif_metering = %(exif_metering)s
exif_flash = %(exif_flash)s
exif_flash_mode = %(exif_flash_mode)s
exif_flashpixversion = %(exif_flashpixversion)s
exif_colorspace = %(exif_colorspace)s
exif_pixel_x = %(exif_pixel_x)s
exif_pixel_y = %(exif_pixel_y)s
exif_focal_length = %(exif_focal_length)s
exif_focal_plane_x = %(exif_focal_plane_x)s
exif_focal_plane_y = %(exif_focal_plane_y)s
exif_focal_plane_unit = %(exif_focal_plane_unit)s
exif_sensing = %(exif_sensing)s
exif_file = %(exif_file)s
exif_render = %(exif_render)s
exif_scene = %(exif_scene)s
exif_interoperability_index = %(exif_interoperability_index)s
exif_interoperability_version = %(exif_interoperability_version)s
exif_thumbnail = %(exif_thumbnail)s
exif_thumbnail_size = %(exif_thumbnail_size)s
"""

def macproof_name(macname):
    rmspace = string.maketrans(" ","_")
    name = string.translate(macname, rmspace,'()#,?!')
    return name

def get_cclicense_http():
    url = 'http://creativecommons.org/license/?partner=GIPP&exit_url=http://localhost:19055/?license_url=[license_url]%26license_name=[license_name]'
    catcher = CCWebCatcher()
    pdb.plug_in_web_browser(url)
    license_info = catcher.run()
    license_info['license_text'] = cc_license_template % license_info
    return license_info

def get_lflicense_file(location):
    license_url = location
    license_file = open(license_url)
    file_name, fileext = os.path.splitext(license_url)
    filedirectory, license_name  = os.path.split(file_name)
    license_text = license_file.read().strip()
    license_file.close()
    license_info = {'license_url':license_url,
                    'license_name':license_name,
                    'license_text':license_text}
    return license_info

def grab_gimp_info():
    gimp_comment = 'Made with TheGIMP'
    gimp_version = pdb.gimp_version()
    gipp_comment = 'Touched by GIPP as well....'
#    gipp_version = str(gipp_major*pow(e, gipp_minor))
    gipp_version = 2.7182
    gimp_info = {'gimp_comment':gimp_comment,
                 'gimp_version':gimp_version,
                 'gipp_comment':gipp_comment,
                 'gipp_version':gipp_version}
    return gimp_info, gipp_version


def grab_image_info(image, image_name, fg_color, bg_color):
    foreground_color = str(fg_color)
    background_color = str(bg_color)
    image_source = pdb.gimp_image_get_filename(image)
    image_source_width = image.width
    image_source_height = image.height
    image_source_unit_id = pdb.gimp_image_get_unit(image)
    image_source_unit = pdb.gimp_unit_get_identifier(image_source_unit_id)
    image_info = {'background_color':background_color,
                  'foreground_color':foreground_color,
                  'image_name':image_name,
                  'image_source':image_source,
                  'image_source_width':image_source_width,
                  'image_source_height':image_source_height,
                  'image_source_unit':image_source_unit}
    return image_info 

def grab_license_info(get_license, file_location):
    creativecommons = 'cc'
    locallicense = 'lf'
    none = 'no'
    if (get_license == creativecommons):
        license_info = get_cclicense_http()
    if (get_license == locallicense):
        license_info = get_lflicense_file(file_location)
    if (get_license == none):
        license_info = {'license_url':'',
                        'license_name':'',
                        'license_text':''}
    return license_info


def grab_parasites(image, preserve):
    num_parasites, parasites = pdb.gimp_image_parasite_list(image)
    for parasite_name in parasites:
        image.parasite_detach(parasite_name)
    if not preserve:
        num_parasites = 0
    return num_parasites, parasites


def grab_extra_info(use_extra, name, date):
    if use_extra:
        license_date = int(date)
        extra_info = {'license_date':license_date,
                      'name':name}
    if not use_extra:
        extra_info = {'license_date':'',
                      'name':''}
    return extra_info


def grab_format_info(image, image_extension):
    colorspace = 'undefined'
    monitor_related_width = image.width
    monitor_related_height = image.height
    related_unit_id = pdb.gimp_image_get_unit(image)
    monitor_related_unit = pdb.gimp_unit_get_identifier(related_unit_id)
    monitor_resolution_x, monitor_resolution_y = pdb.gimp_get_monitor_resolution()
    resolution_unit_id = pdb.gimp_image_get_unit(image)
    monitor_resolution_unit = pdb.gimp_unit_get_identifier(resolution_unit_id)
    format_info = {'image_extension':image_extension,
                   'monitor_related_width':monitor_related_width,
                   'monitor_related_height':monitor_related_height,
                   'monitor_related_unit':monitor_related_unit,
                   'monitor_resolution_x':monitor_resolution_x,
                   'monitor_resolution_y':monitor_resolution_y,
                   'monitor_resolution_unit':monitor_resolution_unit,
                   'colorspace':colorspace}
    return format_info

def add_comment(image, num_parasites, image_comment, preserve):
    parasite = gimp.Parasite('GIPP', PARASITE_PERSISTENT, image_comment)
    num_parasites, parasites = grab_parasites(image, preserve)
    if num_parasites:
        for parasite_name in parasites:
            image.parasite_attach(parasite_name)
    if not image_comment:
        print 'Comment contained no information, no parasite was attached.'



def gipp_save_png(image, imagefile, imagelocation):
    png_save_defaults = (0, 9, 0, 0, 0, 0, 0, 1, 0)
    args = list(png_save_defaults)
    pdb.file_png_save2(image, image.active_layer, imagelocation, imagefile,  *args)

def gipp_save_xcf(gipp_version, image, imagefile, imagelocation):
    version = int(gipp_version*1000)
    pdb.gimp_xcf_save(version, image, image.active_layer, imagelocation, imagefile)    


def write_artwork_gipp(image, drawable, image_name, image_extension, image_location, bg_colour, fg_colour, preserve, use_extra, artist, license_date, get_license, file_location):
# strip name and get the current parasites from the image 
    image_name = macproof_name(image_name)
    num_parasites, parasites = grab_parasites(image, preserve)

# open gipp file and a parasite 
    gippfile = os.path.join(image_location, image_name + '.gipp')
    gipp = open(gippfile, 'w')

# get information about gimp and gipp
    gimp_info, gipp_version  = grab_gimp_info()
    gimp_info_text = gimp_template % gimp_info
    gipp.write(gimp_info_text)

# get the image information, write it to the file and to the parasite
    image_info = grab_image_info(image, image_name, fg_colour, bg_colour)
    image_info_text = image_template % image_info
    gipp.write(image_info_text)

# get the license information 
    license_info = grab_license_info(get_license, file_location)
    license_info_text = license_template % license_info
    gipp.write(license_info_text)

# get extra information
    extra_info = grab_extra_info(use_extra, artist, license_date)
    extra_info_text = extra_template % extra_info
    gipp.write(extra_info_text)

# get image format information
    format_info = grab_format_info(image, image_extension)
    format_info_text = format_template % format_info
    gipp.write(format_info_text)

    gipp.close()

    gippparasite = gimp_info_text + image_info_text + license_info_text + extra_info_text + format_info_text
    add_comment(image, num_parasites, gippparasite, preserve)
    
    imagefile = image_name + '.' + image_extension
    imagelocation = os.path.join(image_location, imagefile)
    xcfformat = 'xcf'
    if (image_extension == xcfformat):
        gipp_save_xcf(gipp_version, image, imagefile, imagelocation)
    pngformat = 'png'
    if (image_extension == pngformat):
        gipp_save_png(image, imagefile, imagelocation)
    jpgformat = 'jpg'
    if (image_extension == jpgformat):
        pdb.file_jpeg_save(image, image.active_layer, imagelocation, imagefile, 0.85, 0.0, 1, 0, gippparasite, 1, 0, 0, 0)

register(
        "python_fu_write_artwork_gipp",
        "Write information about your artwork to a text file.",
        "Write information about your artwork to a text file.",
        "Carol Spears",
        "carol",
        "2005",
        "<Image>/Image/Publish/ArtWork",
        "",
        [
        (PF_STRING, "image_name", "Image name:", "No Coding On ..."),
        (PF_RADIO, "image_extension", "Format of the image: {xcf, jpg, png}", "xcf", (("xcf", "xcf"), ("jpg", "jpg"), ("png", "png"))),
        (PF_FILE,   "image_location", "Save file to this directory:", ""),
	(PF_COLOR, "bg_colour", "Background Color", (255,255,255)),
	(PF_COLOR, "fg_colour", "Foreground Color", (0,0,0)),
        (PF_TOGGLE, "preserve", "Preserve original image parasite(s).", TRUE),
        (PF_TOGGLE, "use_extra", "Use artist name and date", TRUE),
        (PF_STRING, "artist", "Artist Name", "Your Name"),
        (PF_SPINNER, "license_date", "License date", 2005, (2000, 2010, 1)),
        (PF_RADIO,  "get_license", "Add a license to your image", "cc", (("cc", "cc"), ("lf", "lf"), ("no", "no"))),
        (PF_FILE,   "file_location", "Location of your personal license.", "")
        ],
        [],
        write_artwork_gipp)
        


# ongoing contest:  while I have reviewed this method and the code, I am not convinced that it is really
# secure, hence a contest.  if you are able to hack this http server, please write details of the method
# you used and any of the details of what you were able to do once you hacked it to either carol@gimp.org
# or yosh@gimp.org.  i will make a teeshirt and send it to you.

class RequestError(Exception): pass

class CCWebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        license_info = self.send_head()

        if license_info:
            self.wfile.write(response_html)

            self.server.license_info = license_info
            self.server.caught_info = True

    def do_HEAD(self):
        self.send_head()

    def send_head(self):
        try:
            if not self.path.startswith('/?'):
                raise RequestError

            license_info = {}

            results = self.path[2:].split('&')

            for result in results:
                try:
                    key, value = result.split('=')
                except ValueError:
                    raise RequestError

                license_info[key] = value

            if not ('license_url' in license_info and
                    'license_name' in license_info and
                    'license_name' in license_info ):
                raise RequestError
        except RequestError:
            self.send_error(400, 'Bad request')
            return None
   
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header('Content-length', str(len(response_html)))
        self.end_headers()

        return license_info

class CCWebCatcher(BaseHTTPServer.HTTPServer):
    def __init__(self):
        self.caught_info = False

        address = ('localhost', 19055)
        BaseHTTPServer.HTTPServer.__init__(self, address, CCWebRequestHandler)

    def run(self):
        while not self.caught_info:
            self.handle_request()

        return self.license_info



main()
